style(kt): reformat the files

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-05-17 18:23:38 +02:00
parent 1eab058c56
commit aaaebf1d52
Signed by: mfocko
GPG key ID: 7C47D46246790496
19 changed files with 211 additions and 140 deletions

View file

@ -9,7 +9,10 @@
* }
*/
class Solution {
fun inorderTraversal(root: TreeNode?, values: MutableList<Int>): List<Int> {
fun inorderTraversal(
root: TreeNode?,
values: MutableList<Int>,
): List<Int> {
if (root == null) {
return values
}
@ -21,6 +24,5 @@ class Solution {
return values
}
fun inorderTraversal(root: TreeNode?): List<Int>
= inorderTraversal(root, mutableListOf<Int>())
fun inorderTraversal(root: TreeNode?): List<Int> = inorderTraversal(root, mutableListOf<Int>())
}

View file

@ -9,7 +9,11 @@
* }
*/
class Solution {
private fun levelOrder(root: TreeNode?, levels: MutableList<MutableList<Int>>, level: Int): MutableList<MutableList<Int>> {
private fun levelOrder(
root: TreeNode?,
levels: MutableList<MutableList<Int>>,
level: Int,
): MutableList<MutableList<Int>> {
if (root == null) {
return levels
}

View file

@ -3,9 +3,7 @@ class Solution {
val n = matrix.size
val required = (1..n).toSet()
fun checkDimension(
dimensions: Iterable<Iterable<Int>>
): Boolean = dimensions.all { it.toSet() == required }
fun checkDimension(dimensions: Iterable<Iterable<Int>>): Boolean = dimensions.all { it.toSet() == required }
return checkDimension(matrix.map(IntArray::toList)) &&
checkDimension((0 until n).map { x -> matrix.map { row -> row[x] } })

View file

@ -18,7 +18,6 @@ class Solution {
val left = "(${tree2str(root.left)})"
val right = "(${tree2str(root.right)})"
if (left == "()" && right == "()") {
return value
} else if (right == "()") {

View file

@ -19,7 +19,10 @@ fun toListNode(vararg xs: Int): ListNode? {
return dummy.next
}
fun linkedListEquals(head: ListNode?, xs: List<Int>): Boolean {
fun linkedListEquals(
head: ListNode?,
xs: List<Int>,
): Boolean {
var node = head
for ((i, x) in xs.withIndex()) {
if (node == null) {

View file

@ -5,7 +5,8 @@ class Solution {
}
}
fun firstUniqChar(s: String): Int = s
fun firstUniqChar(s: String): Int =
s
.foldIndexed(mutableMapOf<Char, Accumulator>()) { i, acc, c ->
acc.getOrPut(c) { Accumulator(i) }.add()
acc

View file

@ -18,8 +18,7 @@ class CombinationIterator(val characters: String, val combinationLength: Int) {
// By default bumping just the last index
private fun nextCombination() = nextCombination(combinationLength - 1)
private fun getCombination(): String =
indices.map { characters[it] }.joinToString(separator="")
private fun getCombination(): String = indices.map { characters[it] }.joinToString(separator = "")
fun next(): String {
// construct the combination
@ -35,7 +34,6 @@ class CombinationIterator(val characters: String, val combinationLength: Int) {
indices.all {
it < characters.length
}
}
/**

View file

@ -1,5 +1,6 @@
class Solution {
fun largestGoodInteger(num: String): String = num
fun largestGoodInteger(num: String): String =
num
.asSequence()
.windowed(3)
.filter { s ->

View file

@ -7,7 +7,11 @@
*/
class Solution {
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
fun lowestCommonAncestor(
root: TreeNode?,
p: TreeNode?,
q: TreeNode?,
): TreeNode? {
var ancestor: TreeNode? = null
var pTrack = root
var qTrack = root

View file

@ -1,6 +1,5 @@
class Solution {
private fun mapSeats(seats: IntArray): MutableList<Int> =
seats.map { if (it == 1) 0 else Int.MAX_VALUE }.toMutableList()
private fun mapSeats(seats: IntArray): MutableList<Int> = seats.map { if (it == 1) 0 else Int.MAX_VALUE }.toMutableList()
fun maxDistToClosest(seats: IntArray): Int {
val left: MutableList<Int> = mapSeats(seats)

View file

@ -1,8 +1,12 @@
class Solution {
data class BoxType(val boxes: Int, val units: Int)
fun toBoxType(x: IntArray): BoxType = BoxType(x[0], x[1])
fun maximumUnits(boxTypes: Array<IntArray>, truckSize: Int): Int =
fun maximumUnits(
boxTypes: Array<IntArray>,
truckSize: Int,
): Int =
boxTypes
.map { toBoxType(it) }
.sortedByDescending(BoxType::units)

View file

@ -1,7 +1,11 @@
import java.util.PriorityQueue
class Solution {
fun minRefuelStops(target: Int, startFuel: Int, stations: Array<IntArray>): Int {
fun minRefuelStops(
target: Int,
startFuel: Int,
stations: Array<IntArray>,
): Int {
var maxReach = startFuel
val availableRefuelling = PriorityQueue<Int>(reverseOrder())
@ -20,7 +24,6 @@ class Solution {
return -1
}
// refuel at least once in order to progress
maxReach += availableRefuelling.poll()!!
refuelled++
@ -36,8 +39,8 @@ fun main() {
check(s.minRefuelStops(100, 1, arrayOf(intArrayOf(10, 100))) == -1)
check(
s.minRefuelStops(
100, 10, arrayOf(intArrayOf(10, 60), intArrayOf(20, 30), intArrayOf(30, 30), intArrayOf(60, 40))
) == 2
100, 10, arrayOf(intArrayOf(10, 60), intArrayOf(20, 30), intArrayOf(30, 30), intArrayOf(60, 40)),
) == 2,
)
check(
s.minRefuelStops(
@ -52,8 +55,8 @@ fun main() {
intArrayOf(608, 190),
intArrayOf(636, 157),
intArrayOf(647, 255),
intArrayOf(841, 123)
)
) == 4
intArrayOf(841, 123),
),
) == 4,
)
}

View file

@ -1,5 +1,8 @@
class Solution {
fun minWindow(s: String, t: String): String {
fun minWindow(
s: String,
t: String,
): String {
val freqs = IntArray(128) { 0 }
t.forEach {
freqs[it.toInt()]++

View file

@ -19,7 +19,10 @@ fun toListNode(vararg xs: Int): ListNode? {
return dummy.next
}
fun linkedListEquals(head: ListNode?, xs: List<Int>): Boolean {
fun linkedListEquals(
head: ListNode?,
xs: List<Int>,
): Boolean {
var node = head
for ((i, x) in xs.withIndex()) {
if (node == null) {

View file

@ -2,8 +2,15 @@ class Solution {
/**
* Holds fixed mapping of roman numerals to their respective numeric value.
*/
private val values = mapOf(
'I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000
private val values =
mapOf(
'I' to 1,
'V' to 5,
'X' to 10,
'L' to 50,
'C' to 100,
'D' to 500,
'M' to 1000,
)
/**
@ -16,7 +23,8 @@ class Solution {
* @param it Current roman numeral digit.
* @return Sign that is to be used when modifying sum of the accumulator.
*/
private fun sign(it: Int): Int = when (next > it) {
private fun sign(it: Int): Int =
when (next > it) {
true -> -1
false -> 1
}
@ -28,7 +36,8 @@ class Solution {
fun update(it: Int): Accumulator = copy(sum = sum + sign(it) * it, next = it)
}
fun romanToInt(s: String): Int = s
fun romanToInt(s: String): Int =
s
.map { values[it]!! }
.foldRight(Accumulator()) { it, acc ->
acc.update(it)
@ -39,7 +48,8 @@ class Solution {
fun main() {
val s = Solution()
val tests = mapOf(
val tests =
mapOf(
"I" to 1,
"II" to 2,
"III" to 3,
@ -51,7 +61,7 @@ fun main() {
"IX" to 9,
"X" to 10,
"LVIII" to 58,
"MCMXCIV" to 1994
"MCMXCIV" to 1994,
)
tests.forEach { (num, i) ->

View file

@ -8,10 +8,16 @@ class Solution {
return table
}
private fun buildTable(s: String, length: Int): Map<String, Int> =
buildTable(s.chunked(length).asSequence())
fun findSubstring(s: String, words: Array<String>): List<Int> {
private fun buildTable(
s: String,
length: Int,
): Map<String, Int> = buildTable(s.chunked(length).asSequence())
fun findSubstring(
s: String,
words: Array<String>,
): List<Int> {
val expectedFrequencies = buildTable(words.asSequence())
val wordLen = words.first().length
val windowSize = wordLen * words.size

View file

@ -1,5 +1,6 @@
class Solution {
val mapping = arrayOf(
val mapping =
arrayOf(
".-",
"-...",
"-.-.",
@ -25,7 +26,7 @@ class Solution {
".--",
"-..-",
"-.--",
"--.."
"--..",
)
private fun charToMorse(c: Char): String = mapping[c - 'a']

View file

@ -10,16 +10,19 @@
*/
class Solution {
private data class SpecialRange(val min: Int? = null, val max: Int? = null) {
fun check(x: Int): Boolean =
(min == null || x > min) && (max == null || x < max)
fun check(x: Int): Boolean = (min == null || x > min) && (max == null || x < max)
}
private fun isValidBST(root: TreeNode?, range: SpecialRange): Boolean =
private fun isValidBST(
root: TreeNode?,
range: SpecialRange,
): Boolean =
when (root) {
null -> true
else -> range.check(root.`val`)
&& isValidBST(root.left, range.copy(max=root.`val`))
&& isValidBST(root.right, range.copy(min=root.`val`))
else ->
range.check(root.`val`) &&
isValidBST(root.left, range.copy(max = root.`val`)) &&
isValidBST(root.right, range.copy(min = root.`val`))
}
fun isValidBST(root: TreeNode?): Boolean = isValidBST(root, SpecialRange())

View file

@ -1,12 +1,18 @@
class Solution {
private fun wordDifference(lhs: String, rhs: String): Int = lhs.zip(rhs).count { (l, r) -> l != r }
private fun wordDifference(
lhs: String,
rhs: String,
): Int = lhs.zip(rhs).count { (l, r) -> l != r }
private enum class VertexState {
Unvisited, Enqueued, Done
Unvisited,
Enqueued,
Done,
}
private data class Vertex<T>(
val label: T, val neighbours: MutableSet<Vertex<T>> = mutableSetOf()
val label: T,
val neighbours: MutableSet<Vertex<T>> = mutableSetOf(),
) {
var distance: Int = Int.MAX_VALUE
val parents: MutableSet<Vertex<T>> = mutableSetOf()
@ -22,7 +28,8 @@ class Solution {
}
fun transition() {
state = when (state) {
state =
when (state) {
VertexState.Unvisited -> VertexState.Enqueued
VertexState.Enqueued -> VertexState.Done
VertexState.Done -> error("Cannot transition further!")
@ -30,7 +37,9 @@ class Solution {
}
override fun hashCode(): Int = label.hashCode()
override fun toString(): String = "$label(${neighbours.map { it.label.toString() }})"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
@ -46,19 +55,28 @@ class Solution {
private class Graph<T> {
private val vertices: MutableMap<T, Vertex<T>> = mutableMapOf()
fun addVertex(src: T, dst: T) {
fun addVertex(
src: T,
dst: T,
) {
val u = vertices.getOrPut(src) { Vertex(src) }
val v = vertices.getOrPut(dst) { Vertex(dst) }
u.add(v)
}
fun addSymmetricVertex(src: T, dst: T) {
fun addSymmetricVertex(
src: T,
dst: T,
) {
addVertex(src, dst)
addVertex(dst, src)
}
private fun processVertex(queue: ArrayDeque<Vertex<T>>, u: Vertex<T>) {
private fun processVertex(
queue: ArrayDeque<Vertex<T>>,
u: Vertex<T>,
) {
u.neighbours.forEach { v ->
if (v.state == VertexState.Unvisited) {
queue.addLast(v)
@ -75,7 +93,10 @@ class Solution {
u.transition()
}
fun bfs(src: T, dst: T) {
fun bfs(
src: T,
dst: T,
) {
if (vertices[src] == null) {
return
}
@ -101,7 +122,10 @@ class Solution {
override fun toString(): String = vertices.toString()
}
private fun constructGraph(src: String, vertices: List<String>): Graph<String> {
private fun constructGraph(
src: String,
vertices: List<String>,
): Graph<String> {
val g = Graph<String>()
vertices
@ -118,7 +142,9 @@ class Solution {
}
private fun constructPath(
graph: Graph<String>, currentPath: MutableList<String>, paths: MutableList<MutableList<String>>
graph: Graph<String>,
currentPath: MutableList<String>,
paths: MutableList<MutableList<String>>,
): MutableList<MutableList<String>> {
if (graph.parents(currentPath.last()).isEmpty()) {
paths.add(currentPath.reversed().toMutableList())
@ -135,7 +161,9 @@ class Solution {
}
fun findLadders(
beginWord: String, endWord: String, wordList: List<String>
beginWord: String,
endWord: String,
wordList: List<String>,
): List<List<String>> {
val graph = constructGraph(beginWord, wordList)
graph.bfs(beginWord, endWord)
@ -147,9 +175,10 @@ fun main() {
val s = Solution()
check(
s.findLadders("hit", "cog", listOf("hot", "dot", "dog", "lot", "log", "cog")) == listOf(
listOf("hit", "hot", "dot", "dog", "cog"), listOf("hit", "hot", "lot", "log", "cog")
)
s.findLadders("hit", "cog", listOf("hot", "dot", "dog", "lot", "log", "cog")) ==
listOf(
listOf("hit", "hot", "dot", "dog", "cog"), listOf("hit", "hot", "lot", "log", "cog"),
),
)
check(s.findLadders("hit", "cog", listOf("hot", "dot", "dog", "lot", "log")) == emptyList<List<String>>())
check(s.findLadders("hot", "dog", listOf("hot", "dog")) == emptyList<List<String>>())