kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
lernejo__korekto-toolkit__df998e7/src/main/kotlin/com/github/lernejo/korekto/toolkit/misc/Distances.kt
package com.github.lernejo.korekto.toolkit.misc import java.util.* import java.util.stream.Collectors import java.util.stream.Stream import kotlin.math.min object Distances { private fun minimum(a: Int, b: Int, c: Int): Int { return min(min(a, b), c) } fun levenshteinDistance(lhs: CharSequence?, rhs: CharSequence?): Int { val distance = Array(lhs!!.length + 1) { IntArray( rhs!!.length + 1 ) } for (i in 0..lhs.length) distance[i][0] = i for (j in 1..rhs!!.length) distance[0][j] = j for (i in 1..lhs.length) for (j in 1..rhs.length) distance[i][j] = minimum( distance[i - 1][j] + 1, distance[i][j - 1] + 1, distance[i - 1][j - 1] + if (lhs[i - 1] == rhs[j - 1]) 0 else 1 ) return distance[lhs.length][rhs.length] } fun isWordsIncludedApprox(left: String, right: String, wordLevenshteinDistance: Int): Boolean { val leftWords = words(left).collect(Collectors.toList()) val rightWords = words(right).collect(Collectors.toList()) val shorterList = if (rightWords.size > leftWords.size) leftWords else rightWords val longerList: MutableList<String?> = if (rightWords.size > leftWords.size) rightWords else leftWords for (shortListWord in shorterList) { if (!contains(longerList, shortListWord, wordLevenshteinDistance)) { return false } } return true } private fun contains(words: MutableList<String?>, match: String?, maxLevenshteinDistance: Int): Boolean { var contained = false var matched: String? = null for (word in words) { if (levenshteinDistance(word, match) <= maxLevenshteinDistance) { contained = true matched = word break } } if (contained) { words.remove(matched) } return contained } fun countWords(text: String): Int { return words(text).count().toInt() } private fun words(sentence: String): Stream<String?> { return Arrays.stream(sentence.split("\\s+".toRegex()).toTypedArray()) .filter { s: String? -> s!!.trim { it <= ' ' }.isNotEmpty() } } fun longestCommonSubSequence(a: String, b: String): Int { return lCSubStr(a.toCharArray(), b.toCharArray(), a.length, b.length) } private fun lCSubStr(X: CharArray, Y: CharArray, m: Int, n: Int): Int { // Create a table to store lengths of longest common suffixes of // substrings. Note that LCSuff[i][j] contains length of longest // common suffix of X[0..i-1] and Y[0..j-1]. The first row and // first column entries have no logical meaning, they are used only // for simplicity of program val lCStuff = Array(m + 1) { IntArray(n + 1) } var result = 0 // To store length of the longest common substring // Following steps build LCSuff[m+1][n+1] in bottom up fashion for (i in 0..m) { for (j in 0..n) { if (i == 0 || j == 0) lCStuff[i][j] = 0 else if (X[i - 1] == Y[j - 1]) { lCStuff[i][j] = lCStuff[i - 1][j - 1] + 1 result = Integer.max(result, lCStuff[i][j]) } else lCStuff[i][j] = 0 } } return result } }
[ { "class_path": "lernejo__korekto-toolkit__df998e7/com/github/lernejo/korekto/toolkit/misc/Distances.class", "javap": "Compiled from \"Distances.kt\"\npublic final class com.github.lernejo.korekto.toolkit.misc.Distances {\n public static final com.github.lernejo.korekto.toolkit.misc.Distances INSTANCE;\n\n...
asher-stern__sudoku__73ee63a/src/main/kotlin/com/learn/sudoku/Sudoku.kt
package com.learn.sudoku import java.io.File typealias Board = Array<Array<Int?>> // Row first. For example, b[1][3] means second row forth column. fun main(args: Array<String>) { val board = Sudoku.read(args[0]) println(Sudoku.print(board)) println((1..11).joinToString("") { "=" } ) if(!Sudoku.solve(board)) println("Unsolvable.") } object Sudoku { fun read(filename: String): Board = File(filename).useLines { lines -> lines.take(9).map { line -> line.map { if (it.isDigit()) it.toString().toInt() else null }.toTypedArray() } .toList().toTypedArray() } fun print(board: Board): String = board.withIndex().joinToString("\n") { (i, r) -> val columnString = r.withIndex().joinToString("") { (ci, c) -> (if ((ci>0)&&(0==(ci%3))) "|" else "") + (c?.toString()?:" ") } (if ((i>0)&&(0==(i%3))) (1..11).joinToString("", postfix = "\n") { "-" } else "") + columnString } fun solve(board: Board): Boolean = solve(board, 0, 0) private fun solve(board: Board, row: Int, column: Int): Boolean { if (board[row][column] == null) { for (value in 1..9) { if (!violates(value, row, column, board)) { board[row][column] = value if ( (row == 8) && (column == 8) ) { println(print(board)) return true } else { val (nextRow, nextColumn) = next(row, column) if (solve(board, nextRow, nextColumn)) { return true } } board[row][column] = null } } return false } else { if ( (row == 8) && (column == 8) ) { println(print(board)) return true } else { val (nextRow, nextColumn) = next(row, column) return solve(board, nextRow, nextColumn) } } } private fun next(row: Int, column: Int): Pair<Int, Int> { if (column < 8) return Pair(row, column + 1) else return Pair(row + 1, 0) } private fun violates(value: Int, row: Int, column: Int, board: Board): Boolean { return violatesRow(value, row, column, board) || violatesColumn(value, row, column, board) || violatesSquare(value, row, column, board) } private fun violatesRow(value: Int, row: Int, column: Int, board: Board): Boolean = (0 until 9).any { (it != column) && (board[row][it] == value) } private fun violatesColumn(value: Int, row: Int, column: Int, board: Board): Boolean = (0 until 9).any { (it != row) && (board[it][column] == value) } private fun violatesSquare(value: Int, row: Int, column: Int, board: Board): Boolean { val rowBegin = (row/3)*3 val columnBegin = (column/3)*3 for (r in rowBegin until (rowBegin+3)) { for (c in columnBegin until (columnBegin+3)) { if ( (r != row) && (c != column) ) { if (board[r][c] == value) { return true } } } } return false } }
[ { "class_path": "asher-stern__sudoku__73ee63a/com/learn/sudoku/SudokuKt.class", "javap": "Compiled from \"Sudoku.kt\"\npublic final class com.learn.sudoku.SudokuKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String arg...
GirZ0n__SPBU-Homework-2__05f2bda/src/main/kotlin/homeworks/homework8/task1/model/MinimaxAlgorithm.kt
package homeworks.homework7.task2.model object MinimaxAlgorithm { private const val MAX_VALUE = 1000 private const val MIN_VALUE = -MAX_VALUE private const val BASIC_VALUE = 10 fun getBestMove(board: Array<CharArray>, playerSign: Char, opponentSign: Char, emptySign: Char): Pair<Int, Int> { var bestValue = MIN_VALUE var bestMove = Pair(-1, -1) for (i in 0..2) { for (j in 0..2) { if (board[i][j] == emptySign) { board[i][j] = playerSign val moveValue = minimax(board, false, playerSign, opponentSign, emptySign) val move = Pair(i, j) board[i][j] = emptySign // Undo bestMove = move.takeIf { bestValue < moveValue } ?: bestMove bestValue = moveValue.takeIf { bestValue < it } ?: bestValue } } } return bestMove } private fun minimax( board: Array<CharArray>, isPlayer: Boolean, // !isPlayer = isOpponent playerSign: Char, opponentSign: Char, emptySign: Char ): Int { val score = evaluateCurrentState(board, playerSign, opponentSign) return if (score == BASIC_VALUE) { score } else if (score == -BASIC_VALUE) { score } else if (!isMovesLeft(board, emptySign)) { 0 } else if (isPlayer) { playerHandling(board, isPlayer, playerSign, opponentSign, emptySign) } else { opponentHandling(board, isPlayer, playerSign, opponentSign, emptySign) } } private fun playerHandling( board: Array<CharArray>, isPlayer: Boolean, playerSign: Char, opponentSign: Char, emptySign: Char ): Int { var best = MIN_VALUE for (i in 0..2) { for (j in 0..2) { if (board[i][j] == emptySign) { board[i][j] = playerSign best = best.coerceAtLeast(minimax(board, !isPlayer, playerSign, opponentSign, emptySign)) board[i][j] = emptySign // Undo } } } return best } private fun opponentHandling( board: Array<CharArray>, isPlayer: Boolean, playerSign: Char, opponentSign: Char, emptySign: Char ): Int { var best = MAX_VALUE for (i in 0..2) { for (j in 0..2) { if (board[i][j] == emptySign) { board[i][j] = opponentSign best = best.coerceAtMost(minimax(board, !isPlayer, playerSign, opponentSign, emptySign)) board[i][j] = emptySign // Undo } } } return best } private fun isMovesLeft(board: Array<CharArray>, emptySign: Char): Boolean { for (raw in board) { for (elem in raw) { if (elem == emptySign) { return true } } } return false } private fun evaluateCurrentState(board: Array<CharArray>, playerSign: Char, opponentSign: Char): Int { val results = emptyList<Int>().toMutableList() results.add(checkRowsForWinningCombinations(board, playerSign, opponentSign)) results.add(checkColumnsForWinningCombinations(board, playerSign, opponentSign)) results.add(checkMainDiagonalForWinningCombination(board, playerSign, opponentSign)) results.add(checkAntidiagonalForWinningCombination(board, playerSign, opponentSign)) for (result in results) { if (result == BASIC_VALUE || result == -BASIC_VALUE) { return result } } return 0 } /* The following 4 functions return: BASIC_VALUE - when player wins; -BASIC_VALUE - when opponent wins; 0 - when tie. */ private fun checkRowsForWinningCombinations(board: Array<CharArray>, playerSign: Char, opponentSign: Char): Int { for (row in 0..2) { if (board[row][0] == board[row][1] && board[row][1] == board[row][2]) { return if (board[row][0] == playerSign) { BASIC_VALUE } else if (board[row][0] == opponentSign) { -BASIC_VALUE } else continue } } return 0 } private fun checkColumnsForWinningCombinations(board: Array<CharArray>, playerSign: Char, opponentSign: Char): Int { for (column in 0..2) { if (board[0][column] == board[1][column] && board[1][column] == board[2][column]) { return if (board[0][column] == playerSign) { BASIC_VALUE } else if (board[0][column] == opponentSign) { -BASIC_VALUE } else continue } } return 0 } private fun checkMainDiagonalForWinningCombination( board: Array<CharArray>, playerSign: Char, opponentSign: Char ): Int { if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) { return when (board[1][1]) { playerSign -> BASIC_VALUE opponentSign -> -BASIC_VALUE else -> 0 } } return 0 } private fun checkAntidiagonalForWinningCombination( board: Array<CharArray>, playerSign: Char, opponentSign: Char ): Int { if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) { return when (board[1][1]) { playerSign -> BASIC_VALUE opponentSign -> -BASIC_VALUE else -> 0 } } return 0 } }
[ { "class_path": "GirZ0n__SPBU-Homework-2__05f2bda/homeworks/homework7/task2/model/MinimaxAlgorithm.class", "javap": "Compiled from \"MinimaxAlgorithm.kt\"\npublic final class homeworks.homework7.task2.model.MinimaxAlgorithm {\n public static final homeworks.homework7.task2.model.MinimaxAlgorithm INSTANCE;\...
nschulzke__mancala-puzzle-solver__b130d3b/src/main/kotlin/Main.kt
package com.nschulzke enum class Stars { One, Two, Three; } private val mancalaIndices = setOf(6, 13) data class Puzzle( private val board: List<Int>, private val turns: Int, private val targets: List<Pair<Stars, Int>>, val steps: List<Int> = emptyList(), ) { fun onBottom(pit: Int): Boolean = pit in 0..5 fun onTop(pit: Int): Boolean = pit in 7..12 fun opposite(pit: Int): Int = when (pit) { 0 -> 12 1 -> 11 2 -> 10 3 -> 9 4 -> 8 5 -> 7 7 -> 5 8 -> 4 9 -> 3 10 -> 2 11 -> 1 12 -> 0 else -> throw IllegalArgumentException("Pit $pit has no opposite") } fun move(pit: Int): Puzzle { if (board[pit] == 0) { throw Error("Cannot move empty pit") } if (pit in mancalaIndices) { throw Error("Cannot move mancala") } val mutableBoard = board.toMutableList() val stones = mutableBoard[pit] mutableBoard[pit] = 0 var index = pit for (i in 1..stones) { index = (index + 1) % mutableBoard.size mutableBoard[index]++ } // If the final pit is opposite of another pit that is not empty, capture all pieces if (index !in mancalaIndices) { val oppositeIndex = opposite(index) val mancala = if (onBottom(index)) { 6 } else { 13 } if (mutableBoard[index] == 1 && mutableBoard[oppositeIndex] > 0) { mutableBoard[mancala] += mutableBoard[oppositeIndex] + 1 mutableBoard[index] = 0 mutableBoard[oppositeIndex] = 0 } } return this.copy( board = mutableBoard, turns = if (index !in mancalaIndices) { turns - 1 } else { turns }, steps = steps + pit ) } private fun pitToString(index: Int): String = board[index].toString().padStart(2, ' ') fun score(): Int = board[6] + board[13] fun starRating(): Stars? = targets.lastOrNull { score() >= it.second }?.first fun isComplete(): Boolean = turns <= 0 || starRating() == Stars.Three fun nonEmptyPitIndices(): Iterable<Int> = board.indices.filter { board[it] > 0 && !mancalaIndices.contains(it) } override fun toString(): String { return """ | ${pitToString(12)} ${pitToString(11)} ${pitToString(10)} ${pitToString(9)} ${pitToString(8)} ${pitToString(7)} |${pitToString(13)} ${pitToString(6)} | ${pitToString(0)} ${pitToString(1)} ${pitToString(2)} ${pitToString(3)} ${pitToString(4)} ${pitToString(5)} |${turns} turns left """.trimMargin() } } class Solver { // Use a search tree to find the minimum number of moves to get 3 stars' worth of stones in the mancalas. fun solve(startingPuzzle: Puzzle): Puzzle? { val queue = mutableListOf(startingPuzzle) val visited = mutableSetOf(startingPuzzle) while (queue.isNotEmpty()) { val puzzle = queue.removeAt(0) if (puzzle.isComplete()) { if (puzzle.starRating() == Stars.Three) { return puzzle } } else { for (pit in puzzle.nonEmptyPitIndices()) { val nextGame = puzzle.move(pit) if (nextGame !in visited) { queue.add(nextGame) visited.add(nextGame) } } } } return null } companion object { @JvmStatic fun main(args: Array<String>) { val puzzle = Puzzle( board = mutableListOf( 1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 2, 0, 0, ), turns = 3, targets = listOf( Stars.One to 8, Stars.Two to 9, Stars.Three to 10, ), ) println(puzzle) val solver = Solver() val solution = solver.solve(puzzle) if (solution == null) { println("No solution found.") } else { solution.steps.fold(puzzle) { acc, next -> acc.move(next).also { println("\nAfter moving $next:\n$it") } } } } } }
[ { "class_path": "nschulzke__mancala-puzzle-solver__b130d3b/com/nschulzke/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.nschulzke.MainKt {\n private static final java.util.Set<java.lang.Integer> mancalaIndices;\n\n public static final java.util.Set access$getMancalaIndices$p();...
analogrelay__advent-of-code__006343d/2019/src/main/kotlin/adventofcode/day04/main.kt
package adventofcode.day04 fun main(args: Array<String>) { if (args.size < 2) { System.err.println("Usage: adventofcode day04 <START> <END>") System.exit(1) } val start = args[0].toInt() val end = args[1].toInt() println("Computing passwords in range $start - $end") val part1Passwords = (start..end).filter { isValidPassword(it, true) } println("[Part 1] Number of valid passwords: ${part1Passwords.size}") val part2Passwords = (start..end).filter { isValidPassword(it, false) } // for(invalidPassword in part1Passwords.minus(part2Passwords)) { // println("[Part 2] Invalid: $invalidPassword") // } // for(validPassword in part2Passwords) { // println("[Part 2] Valid: $validPassword") // } println("[Part 2] Number of valid passwords: ${part2Passwords.size}") } fun Int.iterateDigits(): List<Int> { var number = this return generateSequence { if (number == 0) { null } else { val digit = number % 10 number = number / 10 digit } }.toList().reversed() } fun isValidPassword(candidate: Int, allowMoreThanTwoDigitSequence: Boolean): Boolean { var last = -1 var activeSequenceLength = 0 var hasValidSequence = false for (digit in candidate.iterateDigits()) { if (last >= 0) { if (last > digit) { // Digits must be ascending return false; } if (allowMoreThanTwoDigitSequence) { if(last == digit) { hasValidSequence = true } } else if (last != digit) { if (activeSequenceLength == 2) { // Found a sequence of exactly two digits hasValidSequence = true } activeSequenceLength = 0 } } activeSequenceLength += 1 last = digit } return hasValidSequence || activeSequenceLength == 2 }
[ { "class_path": "analogrelay__advent-of-code__006343d/adventofcode/day04/MainKt.class", "javap": "Compiled from \"main.kt\"\npublic final class adventofcode.day04.MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // Stri...
analogrelay__advent-of-code__006343d/2019/src/main/kotlin/adventofcode/day03/main.kt
package adventofcode.day03 import java.io.File data class Point(val x: Int, val y: Int) { public fun moveLeft(distance: Int)= Point(x - distance, y) public fun moveRight(distance: Int)= Point(x + distance, y) public fun moveUp(distance: Int)= Point(x, y + distance) public fun moveDown(distance: Int)= Point(x, y - distance) public fun iterateLeft(distance: Int) = (1..distance).map { Point(x - it, y) } public fun iterateRight(distance: Int) = (1..distance).map { Point(x + it, y) } public fun iterateUp(distance: Int) = (1..distance).map { Point(x, y + it) } public fun iterateDown(distance: Int) = (1..distance).map { Point(x, y - it) } public fun manhattenDistance(p2: Point): Int = Math.abs(x - p2.x) + Math.abs(y - p2.y) } data class Line(val start: Point, val end: Point) { public fun hasPoint(p: Point): Boolean { val minX = Math.min(start.x, end.x) val maxX = Math.max(start.x, end.x) val minY = Math.min(start.y, end.y) val maxY = Math.max(start.y, end.y) return p.x >= minX && p.x <= maxX && p.y >= minY && p.y <= maxY } public fun intersects(other: Line): Point? { // Generate the intersection val intersection = if (end.y == start.y) { Point(other.start.x, start.y) } else { Point(start.x, other.start.y) } // Check if the intersection is on both lines if (other.hasPoint(intersection) && hasPoint(intersection)) { return intersection } else { return null } } } fun main(args: Array<String>) { val inputFile = if (args.size < 1) { System.err.println("Usage: adventofcode day03 <INPUT FILE>") System.exit(1) throw Exception("Whoop") } else { args[0] } val wires = File(inputFile).readLines().map(::parseItem) // println("[Part 1] Wire #1 ${wires[0]}") // println("[Part 1] Wire #2 ${wires[1]}") val intersections = (wires[0] intersect wires[1]).filterNot { it.x == 0 && it.y == 0 } val best = intersections.minBy { println("[Part 1] Intersection at $it") it.manhattenDistance(Point(0, 0)) } if (best == null) { println("[Part 1] No intersection found.") } else { val distance = best.manhattenDistance(Point(0, 0)) println("[Part 1] Closest intersection is $best (distance: $distance)") } // Now compute the best intersection by distance along the line val bestBySteps = intersections.map { // Add two to include the end points Pair(it, wires[0].indexOf(it) + wires[1].indexOf(it) + 2) }.minBy { it.second } if (bestBySteps == null) { println("[Part 2] No intersection found.") } else { println("[Part 2] Closest intersection is ${bestBySteps.first} (distance: ${bestBySteps.second})") } } fun parseItem(line: String): List<Point> { var prev = Point(0, 0) return line.split(",").flatMap { val start = prev val distance = it.substring(1).toInt() when (it[0]) { 'L' -> { prev = start.moveLeft(distance) start.iterateLeft(distance) } 'R' -> { prev = start.moveRight(distance) start.iterateRight(distance) } 'D' -> { prev = start.moveDown(distance) start.iterateDown(distance) } 'U' -> { prev = start.moveUp(distance) start.iterateUp(distance) } else -> throw Exception("Invalid direction: ${it[0]}") } } }
[ { "class_path": "analogrelay__advent-of-code__006343d/adventofcode/day03/MainKt.class", "javap": "Compiled from \"main.kt\"\npublic final class adventofcode.day03.MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // Stri...
dwbullok__kool__5121acb/common/src/main/kotlin/com/codeviking/kxg/math/Partition.kt
package com.codeviking.kxg.math import kotlin.math.* /** * Partitions items with the given comparator. After partitioning, all elements left of k are smaller * than all elements right of k with respect to the given comparator function. * * This method implements the Floyd-Rivest selection algorithm: * https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm */ fun <T> MutableList<T>.partition(k: Int, cmp: (T, T) -> Int) = partition(indices, k, cmp) fun <T> MutableList<T>.partition(rng: IntRange, k: Int, cmp: (T, T) -> Int) { var left = rng.first var right = rng.last while (right > left) { if (right - left > 600) { val n = right - left + 1 val i = k - left + 1 val z = ln(n.toDouble()) val s = 0.5 * exp(2.0 * z / 3.0) val sd = 0.5 * sqrt(z * s * (n - s) / n) * sign(i - n / 2.0) val newLeft = max(left, (k - i * s / n + sd).toInt()) val newRight = min(right, (k + (n - i) * s / n + sd).toInt()) partition(newLeft..newRight, k, cmp) } val t = get(k) var i = left var j = right swap(left, k) if (cmp(get(right), t) > 0) { swap(right, left) } while (i < j) { swap( i, j) i++ j-- while (cmp(get(i), t) < 0) { i++ } while (cmp(get(j), t) > 0) { j-- } } if (cmp(get(left), t) == 0) { swap(left, j) } else { j++ swap(j, right) } if (j <= k) { left = j + 1 } if (k <= j) { right = j - 1 } } } private fun <T> MutableList<T>.swap(a: Int, b: Int) { this[a] = this[b].also { this[b] = this[a] } }
[ { "class_path": "dwbullok__kool__5121acb/com/codeviking/kxg/math/PartitionKt.class", "javap": "Compiled from \"Partition.kt\"\npublic final class com.codeviking.kxg.math.PartitionKt {\n public static final <T> void partition(java.util.List<T>, int, kotlin.jvm.functions.Function2<? super T, ? super T, java....
borisskert__kotlin-katas__0659b33/src/main/kotlin/helpthebookseller/StockList.kt
package solution /** * https://www.codewars.com/kata/54dc6f5a224c26032800005c/train/kotlin */ object StockList { fun stockSummary(lstOfArt: Array<String>, lstOfCat: Array<String>): String { if (lstOfArt.isEmpty()) { return "" } val stock = lstOfArt .map(::readOne) .groupBy { it.category } .map { (key, value) -> StockItem(key, value.sumOf { it.quantity }) } .associateBy { it.category } return lstOfCat .map { stock[it] ?: StockItem(it, 0) } .joinToString(" - ") { "(${it.category} : ${it.quantity})" } } } data class StockItem(val category: String, val quantity: Int) { } val stockItemPattern = """([A-Z][A-Z0-9]+) ([0-9]+)""".toRegex() fun readOne(input: String): StockItem { val match = stockItemPattern.matchEntire(input) val groups = match!!.groups val category = groups[1]!!.value val quantity = groups[2]!!.value return StockItem(category.take(1), quantity.toInt()) }
[ { "class_path": "borisskert__kotlin-katas__0659b33/solution/StockList.class", "javap": "Compiled from \"StockList.kt\"\npublic final class solution.StockList {\n public static final solution.StockList INSTANCE;\n\n private solution.StockList();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day15.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path import java.util.PriorityQueue object Day15 { data class RiskPath(val currentCost: Int, val row: Int, val col: Int) private fun solve(lines: List<String>, shouldExpandGrid: Boolean = false): Int { val rawGrid = parseLines(lines) val grid = if (shouldExpandGrid) expandGrid(rawGrid) else rawGrid val pq = PriorityQueue<RiskPath> { a, b -> a.currentCost.compareTo(b.currentCost) } pq.add(RiskPath(0, 0, 0)) val directions = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) val minCosts = mutableMapOf<Pair<Int, Int>, Int>() minCosts[0 to 0] = 0 while (true) { val top = pq.remove()!! if (top.row == grid.size - 1 && top.col == grid[0].size - 1) { return top.currentCost } directions.forEach { (dx, dy) -> val x = top.row + dx val y = top.col + dy if (x >= 0 && x < grid.size && y >= 0 && y < grid[0].size) { val newCost = top.currentCost + grid[x][y] if (newCost < (minCosts[x to y] ?: Integer.MAX_VALUE)) { pq.add(RiskPath(newCost, x, y)) minCosts[x to y] = newCost } } } } } private fun parseLines(lines: List<String>): List<List<Int>> { return lines.map { line -> line.map(Char::digitToInt) } } private fun expandGrid(grid: List<List<Int>>): List<List<Int>> { val newGrid = Array(grid.size * 5) { Array(grid[0].size * 5) { 0 } } for (i in grid.indices) { for (j in grid[0].indices) { for (k in 0 until 5) { for (x in 0 until 5) { val ni = i + grid.size * k val nj = j + grid[0].size * x newGrid[ni][nj] = grid[i][j] + k + x while (newGrid[ni][nj] > 9) { newGrid[ni][nj] -= 9 } } } } } return newGrid.map(Array<Int>::toList) } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input15.txt"), Charsets.UTF_8) val solution1 = solve(lines, shouldExpandGrid = false) println(solution1) val solution2 = solve(lines, shouldExpandGrid = true) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day15.class", "javap": "Compiled from \"Day15.kt\"\npublic final class org.aoc2021.Day15 {\n public static final org.aoc2021.Day15 INSTANCE;\n\n private org.aoc2021.Day15();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day24.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path private fun <K, V> Map<K, V>.replaceKeyValue(k: K, v: V): Map<K, V> { return this.entries.associate { (thisKey, thisValue) -> if (thisKey == k) (k to v) else (thisKey to thisValue) } } object Day24 { data class Instruction(val operator: String, val a: String, val b: String? = null) private fun solve(lines: List<String>, findMax: Boolean): String { val program = parseProgram(lines) val expressions = generateExpressions(program) expressions.find { (_, variables) -> variables["z"] == LiteralValue(0) }?.let { (conditions, _) -> if (conditions.any { !it.value }) { throw IllegalStateException("unexpected condition: $conditions") } val result = Array(14) { 0 } conditions.forEach { condition -> val compare = if (condition.compare.a is Input) { Compare(Add(condition.compare.a, LiteralValue(0)), condition.compare.b) } else { condition.compare } if (compare.a !is Add || compare.a.a !is Input || compare.a.b !is LiteralValue || compare.b !is Input) { throw IllegalStateException("unexpected compare: $compare") } if (compare.a.b.value < 0) { result[compare.a.a.index] = if (findMax) 9 else (1 - compare.a.b.value) result[compare.b.index] = result[compare.a.a.index] + compare.a.b.value } else { result[compare.b.index] = if (findMax) 9 else (1 + compare.a.b.value) result[compare.a.a.index] = result[compare.b.index] - compare.a.b.value } } return result.map(Int::digitToChar).joinToString(separator = "") } throw IllegalArgumentException("no solution found") } sealed interface Expression { fun simplify(): Expression } data class Input(val index: Int) : Expression { override fun simplify() = this override fun toString() = "input$index" } data class LiteralValue(val value: Int) : Expression { override fun simplify() = this override fun toString() = value.toString() } data class Add(val a: Expression, val b: Expression) : Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { LiteralValue(a.value + b.value) } else if (a == LiteralValue(0)) { b } else if (b == LiteralValue(0)) { a } else if (a is Add && a.b is LiteralValue && b is LiteralValue) { Add(a.a, LiteralValue(a.b.value + b.value)).simplify() } else { this } } override fun toString() = "($a + $b)" } data class Multiply(val a: Expression, val b: Expression) : Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { LiteralValue(a.value * b.value) } else if (a == LiteralValue(0) || b == LiteralValue(0)) { LiteralValue(0) } else if (a == LiteralValue(1)) { b } else if (b == LiteralValue(1)) { a } else if (a is Multiply && a.b is LiteralValue && b is LiteralValue) { Multiply(a.a, LiteralValue(a.b.value * b.value)).simplify() } else { this } } override fun toString() = "($a * $b)" } data class Divide(val a: Expression, val b: Expression) : Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { LiteralValue(a.value / b.value) } else if (a == LiteralValue(0)) { LiteralValue(0) } else if (b == LiteralValue(1)) { a } else if (a is Multiply && a.b is LiteralValue && b is LiteralValue && (a.b.value % b.value == 0)) { Multiply(a.a, LiteralValue(a.b.value / b.value)).simplify() } else if (a is Add && a.a is Input && a.b is LiteralValue && b is LiteralValue && a.b.value < b.value - 9) { LiteralValue(0) } else if (a is Add && a.b is Add && a.b.a is Input && a.b.b is LiteralValue && b is LiteralValue && a.b.b.value >= 0 && a.b.b.value < b.value - 9) { Divide(a.a, b).simplify() } else { this } } override fun toString() = "($a / $b)" } data class Modulo(val a: Expression, val b: Expression): Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { LiteralValue(a.value % b.value) } else if (a == LiteralValue(0)) { LiteralValue(0) } else if (a is Add && b is LiteralValue) { Add(Modulo(a.a, b).simplify(), Modulo(a.b, b).simplify()).simplify() } else if (a is Multiply && a.b is LiteralValue && b is LiteralValue && (a.b.value % b.value == 0)) { LiteralValue(0) } else if (a is Input && b is LiteralValue && b.value > 9) { a } else { this } } override fun toString() = "($a % $b)" } data class Compare(val a: Expression, val b: Expression, val invert: Boolean = false): Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { if (invert) { LiteralValue(if (a.value == b.value) 0 else 1) } else { LiteralValue(if (a.value == b.value) 1 else 0) } } else if (a is Compare && b == LiteralValue(0)) { Compare(a.a, a.b, invert = true).simplify() } else if (isConditionImpossible(a, b)) { LiteralValue(if (invert) 1 else 0) } else { this } } override fun toString() = if (!invert) { "($a == $b ? 1 : 0)" } else { "($a == $b ? 0 : 1)" } } private fun isConditionImpossible(a: Expression, b: Expression): Boolean { if (b !is Input) { return false } if (a is LiteralValue && (a.value < 1 || a.value > 9)) { return true } if (a is Add && a.a is Input && a.b is LiteralValue && a.b.value >= 9) { return true } if (a is Add && a.a is Modulo && a.b is LiteralValue && a.b.value > 9) { return true } return false } data class Condition(val compare: Compare, val value: Boolean) private fun generateExpressions( program: List<Instruction>, initialState: Map<String, Expression> = listOf("w", "x", "y", "z").associateWith { LiteralValue(0) }, i: Int = 0, initialInputIndex: Int = 0, conditions: List<Condition> = listOf(), ): List<Pair<List<Condition>, Map<String, Expression>>> { val variables = initialState.toMutableMap() var inputIndex = initialInputIndex for (j in i until program.size) { val instruction = program[j] when (instruction.operator) { "inp" -> { variables[instruction.a] = Input(inputIndex) inputIndex++ } "add" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) variables[instruction.a] = Add(aValue, bValue).simplify() } "mul" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) variables[instruction.a] = Multiply(aValue, bValue).simplify() } "div" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) variables[instruction.a] = Divide(aValue, bValue).simplify() } "mod" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) variables[instruction.a] = Modulo(aValue, bValue).simplify() } "eql" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) val compare = Compare(aValue, bValue).simplify() if (compare is Compare) { val oneBranch = variables.replaceKeyValue(instruction.a, LiteralValue(1)) val zeroBranch = variables.replaceKeyValue(instruction.a, LiteralValue(0)) return generateExpressions(program, oneBranch.toMap(), j + 1, inputIndex, conditions.plus(Condition(compare, true))) .plus(generateExpressions(program, zeroBranch.toMap(), j + 1, inputIndex, conditions.plus(Condition(compare, false)))) } variables[instruction.a] = compare } } } return listOf(conditions to variables.toMap()) } private fun getExpressionValueOf(value: String, variables: Map<String, Expression>): Expression { return variables[value] ?: LiteralValue(value.toInt()) } private fun parseProgram(lines: List<String>): List<Instruction> { return lines.map { line -> val split = line.split(" ") if (split[0] == "inp") { Instruction(split[0], split[1]) } else { Instruction(split[0], split[1], split[2]) } } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input24.txt"), Charsets.UTF_8) val solution1 = solve(lines, true) println(solution1) val solution2 = solve(lines, false) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day24$Compare.class", "javap": "Compiled from \"Day24.kt\"\npublic final class org.aoc2021.Day24$Compare implements org.aoc2021.Day24$Expression {\n private final org.aoc2021.Day24$Expression a;\n\n private final org.aoc2021.Day24$Expressi...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day23.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path import java.util.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min object Day23 { private const val hallwayLength = 11 private val amphipodChars = setOf('A', 'B', 'C', 'D') private val roomIndices = setOf(2, 4, 6, 8) private val secondRow = listOf(Amphipod.DESERT, Amphipod.COPPER, Amphipod.BRONZE, Amphipod.AMBER) private val thirdRow = listOf(Amphipod.DESERT, Amphipod.BRONZE, Amphipod.AMBER, Amphipod.COPPER) enum class Amphipod(val energyPerStep: Int) { AMBER(1), BRONZE(10), COPPER(100), DESERT(1000), } private val winState = Amphipod.values().toList() sealed interface HallwayPosition data class Space(val occupant: Amphipod?) : HallwayPosition data class Room(val occupants: List<Amphipod?>) : HallwayPosition { fun withNewOccupant(occupant: Amphipod): Room { if (occupants.all { it == null }) { return Room(occupants.drop(1).plus(occupant)) } val firstNullIndex = firstOpenIndex() return Room( occupants.take(firstNullIndex).plus(occupant).plus(occupants.drop(firstNullIndex + 1)) ) } fun withoutTopOccupant(): Room { val firstNonNullIndex = firstOccupiedIndex() return Room( occupants.take(firstNonNullIndex).plus(null).plus(occupants.drop(firstNonNullIndex + 1)) ) } fun firstOpenIndex(): Int { return occupants.indexOfLast { it == null } } fun firstOccupiedIndex(): Int { return occupants.indexOfFirst { it != null } } } data class State(val distance: Int, val hallway: List<HallwayPosition>) private fun solve(lines: List<String>, expandMiddle: Boolean): Int { val hallway = parseInput(lines, expandMiddle) val pq = PriorityQueue<State> { a, b -> a.distance.compareTo(b.distance) } pq.add(State(0, hallway)) val stateToMinDistance = mutableMapOf<List<HallwayPosition>, Int>() while (!pq.isEmpty()) { val state = pq.remove() if (state.distance >= (stateToMinDistance[state.hallway] ?: Integer.MAX_VALUE)) { continue } stateToMinDistance[state.hallway] = state.distance if (isWinningState(state.hallway)) { return state.distance } generatePossibleMoves(state.hallway).forEach { (moveDistance, moveState) -> val newDistance = state.distance + moveDistance if (newDistance < (stateToMinDistance[moveState] ?: Integer.MAX_VALUE)) { pq.add(State(newDistance, moveState)) } } } throw IllegalArgumentException("no winning solution found") } private fun isWinningState(state: List<HallwayPosition>): Boolean { return state.filterIsInstance<Room>().zip(winState).all { (room, targetAmphipod) -> room.occupants.all { it == targetAmphipod } } } private fun generatePossibleMoves(hallway: List<HallwayPosition>): List<Pair<Int, List<HallwayPosition>>> { val moves = mutableListOf<Pair<Int, List<HallwayPosition>>>() hallway.forEachIndexed { i, position -> when (position) { is Space -> moves.addAll(generateSpaceMoves(hallway, i, position)) is Room -> moves.addAll(generateRoomMoves(hallway, i, position)) } } return moves.toList() } private fun generateSpaceMoves( hallway: List<HallwayPosition>, i: Int, space: Space, ): List<Pair<Int, List<HallwayPosition>>> { if (space.occupant == null) { return listOf() } val targetIndex = 2 * winState.indexOf(space.occupant) + 2 val targetRoom = hallway[targetIndex] as Room if (canMoveToRoom(hallway, i, targetIndex)) { val distance = space.occupant.energyPerStep * (abs(i - targetIndex) + 1 + targetRoom.firstOpenIndex()) val newState = hallway.map { position -> if (position === space) { Space(null) } else if (position === targetRoom) { targetRoom.withNewOccupant(space.occupant) } else { position } } return listOf(distance to newState) } return listOf() } private fun generateRoomMoves( hallway: List<HallwayPosition>, i: Int, room: Room, ): List<Pair<Int, List<HallwayPosition>>> { val targetAmphipod = winState[(i - 2) / 2] if (room.occupants.all { it == null || it == targetAmphipod }) { return listOf() } val firstOccupiedIndex = room.firstOccupiedIndex() val first = room.occupants[firstOccupiedIndex]!! if (first != targetAmphipod) { val firstTargetIndex = 2 * winState.indexOf(first) + 2 val firstTargetRoom = hallway[firstTargetIndex] as Room if (canMoveToRoom(hallway, i, firstTargetIndex)) { val steps = abs(i - firstTargetIndex) + 2 + firstOccupiedIndex + firstTargetRoom.firstOpenIndex() val distance = first.energyPerStep * steps val newState = hallway.map { position -> if (position === room) { room.withoutTopOccupant() } else if (position === firstTargetRoom) { firstTargetRoom.withNewOccupant(first) } else { position } } return listOf(distance to newState) } } val moves = mutableListOf<Pair<Int, List<HallwayPosition>>>() for (j in hallway.indices) { val space = hallway[j] if (space !is Space) { continue } if (canMoveToSpace(hallway, i, j)) { val distance = first.energyPerStep * (abs(i - j) + 1 + room.firstOccupiedIndex()) val newState = hallway.map { position -> if (position === room) { room.withoutTopOccupant() } else if (position === space) { Space(first) } else { position } } moves.add(distance to newState) } } return moves.toList() } private fun canMoveToSpace( hallway: List<HallwayPosition>, i: Int, targetIndex: Int, ): Boolean { val space = hallway[targetIndex] as Space if (space.occupant != null) { return false } return canMoveToPosition(hallway, i, targetIndex) } private fun canMoveToRoom( hallway: List<HallwayPosition>, i: Int, targetIndex: Int, ): Boolean { val targetAmphipod = winState[(targetIndex - 2) / 2] val targetRoom = hallway[targetIndex] as Room if (!targetRoom.occupants.all { it == null || it == targetAmphipod }) { return false } return canMoveToPosition(hallway, i, targetIndex) } private fun canMoveToPosition( hallway: List<HallwayPosition>, i: Int, targetIndex: Int, ): Boolean { val start = min(i, targetIndex) val end = max(i, targetIndex) return ((start + 1) until end).all { j -> val position = hallway[j] position !is Space || position.occupant == null } } private fun parseInput(lines: List<String>, expandMiddle: Boolean): List<HallwayPosition> { val frontOccupants = lines[2].filter(amphipodChars::contains).toCharArray() val backOccupants = lines[3].filter(amphipodChars::contains).toCharArray() val roomOccupants = frontOccupants.zip(backOccupants) var occupantsIndex = 0 val result = mutableListOf<HallwayPosition>() for (i in 0 until hallwayLength) { if (roomIndices.contains(i)) { val (frontOccupant, backOccupant) = roomOccupants[occupantsIndex] val room = if (expandMiddle) { Room(listOf( charToAmphipod(frontOccupant), secondRow[(i - 2) / 2], thirdRow[(i - 2) / 2], charToAmphipod(backOccupant), )) } else { Room(listOf(charToAmphipod(frontOccupant), charToAmphipod(backOccupant))) } result.add(room) occupantsIndex++ } else { result.add(Space(occupant = null)) } } return result.toList() } private fun charToAmphipod(c: Char): Amphipod = when (c) { 'A' -> Amphipod.AMBER 'B' -> Amphipod.BRONZE 'C' -> Amphipod.COPPER 'D' -> Amphipod.DESERT else -> throw IllegalArgumentException("$c") } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input23.txt"), Charsets.UTF_8) val solution1 = solve(lines, false) println(solution1) val solution2 = solve(lines, true) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day23$Room.class", "javap": "Compiled from \"Day23.kt\"\npublic final class org.aoc2021.Day23$Room implements org.aoc2021.Day23$HallwayPosition {\n private final java.util.List<org.aoc2021.Day23$Amphipod> occupants;\n\n public org.aoc2021....
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day9.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day9 { data class Point(val x: Int, val y: Int) private fun solvePart1(lines: List<String>): Int { val heights = lines.map { line -> line.map(Char::digitToInt) } val lowPoints = findLowPoints(heights) return lowPoints.sumOf { p -> 1 + heights[p.x][p.y] } } private fun solvePart2(lines: List<String>): Int { val heights = lines.map { line -> line.map(Char::digitToInt) } val lowPoints = findLowPoints(heights) val basinMarkers = findBasins(heights, lowPoints) return basinMarkers.flatten() .filter { it != 0 } .groupBy { it } .map { (_, values) -> values.size } .sortedDescending() .take(3) .reduce { a, b -> a * b } } private fun findLowPoints(heights: List<List<Int>>): List<Point> { val lowPoints = mutableListOf<Point>() for (i in heights.indices) { for (j in heights[0].indices) { if ( (i == 0 || heights[i][j] < heights[i-1][j]) && (i == heights.size - 1 || heights[i][j] < heights[i+1][j]) && (j == 0 || heights[i][j] < heights[i][j-1]) && (j == heights[0].size - 1 || heights[i][j] < heights[i][j+1]) ) { lowPoints.add(Point(i, j)) } } } return lowPoints.toList() } private fun findBasins(heights: List<List<Int>>, lowPoints: List<Point>): Array<Array<Int>> { val basinMarkers = Array(heights.size) { Array(heights[0].size) { 0 } } lowPoints.forEachIndexed { index, p -> val marker = index + 1 fill(p, marker, heights, basinMarkers) } return basinMarkers } private fun fill(p: Point, marker: Int, heights: List<List<Int>>, basinMarkers: Array<Array<Int>>) { val (x, y) = p basinMarkers[x][y] = marker listOf( -1 to 0, 1 to 0, 0 to -1, 0 to 1, ).forEach { (dx, dy) -> val i = x + dx val j = y + dy if ( i >= 0 && i < heights.size && j >= 0 && j < heights[0].size && heights[i][j] != 9 && basinMarkers[i][j] == 0 ) { fill(Point(i, j), marker, heights, basinMarkers) } } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input9.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day9$Point.class", "javap": "Compiled from \"Day9.kt\"\npublic final class org.aoc2021.Day9$Point {\n private final int x;\n\n private final int y;\n\n public org.aoc2021.Day9$Point(int, int);\n Code:\n 0: aload_0\n 1: invo...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day22.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path import kotlin.math.max import kotlin.math.min private fun IntRange.size(): Int { return if (this.last >= this.first) { this.last - this.first + 1 } else { 0 } } object Day22 { data class Cube(val x: IntRange, val y: IntRange, val z: IntRange) { fun volume(): Long { return x.size().toLong() * y.size() * z.size() } fun intersect(other: Cube): Cube { if (x.first > other.x.last || x.last < other.x.first || y.first > other.y.last || y.last < other.y.first || z.first > other.z.last || z.last < other.z.first) { return Cube(IntRange.EMPTY, IntRange.EMPTY, IntRange.EMPTY) } val minX = max(x.first, other.x.first) val maxX = min(x.last, other.x.last) val minY = max(y.first, other.y.first) val maxY = min(y.last, other.y.last) val minZ = max(z.first, other.z.first) val maxZ = min(z.last, other.z.last) return Cube(minX..maxX, minY..maxY, minZ..maxZ) } } data class Step(val on: Boolean, val cube: Cube) private fun solve(lines: List<String>, shouldBound: Boolean): Long { val steps = parseSteps(lines).let { if (shouldBound) boundCubes(it) else it } val cubes = steps.map(Step::cube) var totalVolume = 0L steps.forEachIndexed { i, step -> val flippedVolume = computeFlippedVolume(steps.subList(0, i), step) if (step.on) { totalVolume += flippedVolume totalVolume += computeNonIntersectingVolume(cubes.subList(0, i), step.cube) } else { totalVolume -= flippedVolume } } return totalVolume } private fun parseSteps(lines: List<String>): List<Step> { return lines.map { line -> val (onString, rest) = line.split(" ") val (xRange, yRange, zRange) = rest.split(",").map { rangeString -> rangeString.substring(2).split("..").let { it[0].toInt()..it[1].toInt() } } Step(onString == "on", Cube(xRange, yRange, zRange)) } } private fun boundCubes(steps: List<Step>): List<Step> { return steps.map { step -> val (x, y, z) = step.cube Step(step.on, Cube( max(x.first, -50)..min(x.last, 50), max(y.first, -50)..min(y.last, 50), max(z.first, -50)..min(z.last, 50), )) } } private fun computeFlippedVolume(previousSteps: List<Step>, step: Step): Long { val overlappingSteps = previousSteps.filter { it.cube.intersect(step.cube).volume() > 0 } var totalFlippedVolume = 0L overlappingSteps.indices.filter { j -> overlappingSteps[j].on != step.on }.forEach { j -> val otherStep = overlappingSteps[j] val laterCubes = overlappingSteps.subList(j + 1, overlappingSteps.size).map(Step::cube) val offOnIntersect = step.cube.intersect(otherStep.cube) totalFlippedVolume += computeNonIntersectingVolume(laterCubes, offOnIntersect) } return totalFlippedVolume } private fun computeNonIntersectingVolume(previousCubes: List<Cube>, cube: Cube): Long { val overlappingCubes = previousCubes.filter { it.intersect(cube).volume() > 0 } var newVolume = cube.volume() var sign = -1 for (cubeCount in 1..overlappingCubes.size) { val cubeCombinations = combinations(overlappingCubes, cubeCount) cubeCombinations.forEach { cubeCombination -> newVolume += sign * cubeCombination.fold(cube) { a, b -> a.intersect(b) }.volume() } sign *= -1 } return newVolume } private fun <T> combinations(list: List<T>, count: Int): List<List<T>> { if (count == 1) { return list.map { listOf(it) } } return list.flatMapIndexed { i, elem -> val subCombinations = combinations(list.subList(i + 1, list.size), count - 1) subCombinations.map { listOf(elem).plus(it) } } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input22.txt"), Charsets.UTF_8) val solution1 = solve(lines, true) println(solution1) val solution2 = solve(lines, false) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day22Kt.class", "javap": "Compiled from \"Day22.kt\"\npublic final class org.aoc2021.Day22Kt {\n private static final int size(kotlin.ranges.IntRange);\n Code:\n 0: aload_0\n 1: invokevirtual #12 // Method kot...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day5.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sign object Day5 { data class Vent(val x1: Int, val y1: Int, val x2: Int, val y2: Int) private fun solvePart1(filename: String): Int { val vents = Files.readAllLines(Path.of(filename), Charsets.UTF_8) .map(Day5::parseLine) val counts = emptyCountsGrid(vents) vents.forEach { vent -> if (vent.x1 == vent.x2) { val start = min(vent.y1, vent.y2) val end = max(vent.y1, vent.y2) for (j in start..end) { counts[vent.x1][j]++ } } if (vent.y1 == vent.y2) { val start = min(vent.x1, vent.x2) val end = max(vent.x1, vent.x2) for (i in start..end) { counts[i][vent.y1]++ } } } return counts.sumOf { column -> column.count { it >= 2 } } } private fun solvePart2(filename: String): Int { val vents = Files.readAllLines(Path.of(filename), Charsets.UTF_8) .map(Day5::parseLine) val counts = emptyCountsGrid(vents) vents.forEach { vent -> val dx = (vent.x2 - vent.x1).sign val dy = (vent.y2 - vent.y1).sign val length = max(abs(vent.x2 - vent.x1), abs(vent.y2 - vent.y1)) for (i in 0..length) { counts[vent.x1 + dx * i][vent.y1 + dy * i]++ } } return counts.sumOf { column -> column.count { it >= 2 } } } private fun emptyCountsGrid(vents: List<Vent>): Array<Array<Int>> { val maxX = vents.maxOf { max(it.x1, it.x2) } + 1 val maxY = vents.maxOf { max(it.y1, it.y2) } + 1 return Array(maxX) { Array(maxY) { 0 } } } private fun parseLine(line: String): Vent { val (p1, p2) = line.split(" -> ") val (x1, y1) = p1.split(",").map(String::toInt) val (x2, y2) = p2.split(",").map(String::toInt) return Vent(x1, y1, x2, y2) } @JvmStatic fun main(args: Array<String>) { val filename = "input5.txt" val solution1 = solvePart1(filename) println(solution1) val solution2 = solvePart2(filename) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day5$Vent.class", "javap": "Compiled from \"Day5.kt\"\npublic final class org.aoc2021.Day5$Vent {\n private final int x1;\n\n private final int y1;\n\n private final int x2;\n\n private final int y2;\n\n public org.aoc2021.Day5$Vent(int...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day16.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day16 { interface Packet { val version: Int val typeId: Int fun sumSubPacketVersions(): Int fun evaluate(): Long } data class LiteralValuePacket( override val version: Int, override val typeId: Int, val value: Long, ) : Packet { override fun sumSubPacketVersions() = 0 override fun evaluate() = value } data class OperatorPacket( override val version: Int, override val typeId: Int, val subPackets: List<Packet>, ) : Packet { override fun sumSubPacketVersions() = subPackets.sumOf { p -> p.version + p.sumSubPacketVersions() } override fun evaluate() = when (typeId) { 0 -> subPackets.sumOf(Packet::evaluate) 1 -> subPackets.fold(1L) { p, packet -> p * packet.evaluate() } 2 -> subPackets.minOf(Packet::evaluate) 3 -> subPackets.maxOf(Packet::evaluate) 5 -> if (subPackets[0].evaluate() > subPackets[1].evaluate()) 1L else 0L 6 -> if (subPackets[0].evaluate() < subPackets[1].evaluate()) 1L else 0L 7 -> if (subPackets[0].evaluate() == subPackets[1].evaluate()) 1L else 0L else -> throw IllegalArgumentException("$typeId") } } private fun solvePart1(lines: List<String>): Int { val binary = hexToBinary(lines[0]) val outerPacket = parsePacket(binary).first return outerPacket.version + outerPacket.sumSubPacketVersions() } private fun solvePart2(lines: List<String>): Long { val binary = hexToBinary(lines[0]) val outerPacket = parsePacket(binary).first return outerPacket.evaluate() } private fun hexToBinary(line: String): String { return line.map { c -> val binary = c.toString().toInt(16).toString(2) if (binary.length == 4) { binary } else { "0".repeat(4 - (binary.length % 4)) + binary } }.joinToString(separator = "") } private fun parsePacket(binary: String, i: Int = 0): Pair<Packet, Int> { val version = binary.substring(i..i+2).toInt(2) val typeId = binary.substring(i+3..i+5).toInt(2) if (typeId == 4) { return parseLiteralValuePacket(binary, i, version, typeId) } return parseOperatorPacket(binary, i, version, typeId) } private fun parseLiteralValuePacket(binary: String, i: Int, version: Int, typeId: Int): Pair<LiteralValuePacket, Int> { var currentIndex = i + 6 var currentValue = 0L while (true) { currentValue = 16 * currentValue + binary.substring(currentIndex+1..currentIndex+4).toInt(2) if (binary[currentIndex] == '0') { break } currentIndex += 5 } val packet = LiteralValuePacket(version, typeId, currentValue) return packet to (currentIndex + 5) } private fun parseOperatorPacket(binary: String, i: Int, version: Int, typeId: Int): Pair<OperatorPacket, Int> { if (binary[i + 6] == '0') { val totalSubPacketLength = binary.substring(i+7..i+21).toInt(2) val subPackets = mutableListOf<Packet>() var currentIndex = i + 22 while (currentIndex - (i + 22) != totalSubPacketLength) { val (packet, nextPacketIndex) = parsePacket(binary, currentIndex) subPackets.add(packet) currentIndex = nextPacketIndex } return OperatorPacket(version, typeId, subPackets.toList()) to currentIndex } else { val numSubPackets = binary.substring(i+7..i+17).toInt(2) val subPackets = mutableListOf<Packet>() var currentIndex = i + 18 (1..numSubPackets).forEach { _ -> val (packet, nextPacketIndex) = parsePacket(binary, currentIndex) subPackets.add(packet) currentIndex = nextPacketIndex } return OperatorPacket(version, typeId, subPackets.toList()) to currentIndex } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input16.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day16$Packet.class", "javap": "Compiled from \"Day16.kt\"\npublic interface org.aoc2021.Day16$Packet {\n public abstract int getVersion();\n\n public abstract int getTypeId();\n\n public abstract int sumSubPacketVersions();\n\n public ab...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day3.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day3 { private fun solvePart1(filename: String): Int { val lines = Files.readAllLines(Path.of(filename), Charsets.UTF_8) val numBits = lines[0].length val oneCounts = Array(numBits) { 0 } lines.forEach { line -> line.forEachIndexed { i, bit -> if (bit == '1') { oneCounts[i]++ } } } val majorityLine = if (lines.size % 2 == 0) { lines.size / 2 } else { lines.size / 2 + 1 } val gammaString = oneCounts.map { if (it >= majorityLine) '1' else '0' } .joinToString(separator = "") val epsilonString = gammaString.map { if (it == '1') '0' else '1' } .joinToString(separator = "") return gammaString.toInt(2) * epsilonString.toInt(2) } private fun solvePart2(filename: String): Int { val lines = Files.readAllLines(Path.of(filename), Charsets.UTF_8) val oxygenRating = findRating(lines, false) val co2Rating = findRating(lines, true) return oxygenRating * co2Rating } private tailrec fun findRating(lines: List<String>, invert: Boolean, i: Int = 0): Int { if (lines.size == 1) { return lines[0].toInt(2) } val (leadingOnes, leadingZeroes) = lines.partition { it[i] == '1' } val mostCommonBit = if (leadingOnes.size >= leadingZeroes.size) '1' else '0' val remainingLines = lines.filter { line -> val matches = (line[i] == mostCommonBit) if (invert) !matches else matches } return findRating(remainingLines, invert, i + 1) } @JvmStatic fun main(args: Array<String>) { val filename = "input3.txt" val solution1 = solvePart1(filename) println(solution1) val solution2 = solvePart2(filename) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day3.class", "javap": "Compiled from \"Day3.kt\"\npublic final class org.aoc2021.Day3 {\n public static final org.aoc2021.Day3 INSTANCE;\n\n private org.aoc2021.Day3();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day13.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day13 { data class Point(val x: Int, val y: Int) data class Fold(val direction: String, val coordinate: Int) private fun solvePart1(lines: List<String>): Int { val (points, folds) = parseLines(lines) val (cols, rows) = determineGridSize(folds) val grid = generateGrid(points, rows, cols) val folded = applyFold(grid, folds[0]) return folded.sumOf { column -> column.count { it } } } private fun solvePart2(lines: List<String>) { val (points, folds) = parseLines(lines) val (cols, rows) = determineGridSize(folds) val grid = generateGrid(points, rows, cols) val folded = folds.fold(grid) { newGrid, fold -> applyFold(newGrid, fold) } printGrid(folded) } private fun parseLines(lines: List<String>): Pair<List<Point>, List<Fold>> { val points = mutableListOf<Point>() val folds = mutableListOf<Fold>() lines.filter(String::isNotBlank).forEach { line -> if (line.startsWith("fold along ")) { val (direction, coordinate) = line.substringAfter("fold along ") .split("=") .let { it[0] to it[1].toInt() } folds.add(Fold(direction, coordinate)) } else { val (x, y) = line.split(",").map(String::toInt) points.add(Point(x, y)) } } return points.toList() to folds.toList() } private fun generateGrid(points: List<Point>, rows: Int, cols: Int): Array<Array<Boolean>> { val grid = Array(cols) { Array(rows) { false } } points.forEach { (x, y) -> grid[x][y] = true } return grid } private fun determineGridSize(folds: List<Fold>): Pair<Int, Int> { val firstHorizontalFold = folds.first { it.direction == "x" } val firstVerticalFold = folds.first { it.direction == "y" } return (2 * firstHorizontalFold.coordinate + 1) to (2 * firstVerticalFold.coordinate + 1) } private fun applyFold(grid: Array<Array<Boolean>>, fold: Fold) = when (fold.direction) { "x" -> applyHorizontalFold(grid, fold.coordinate) "y" -> applyVerticalFold(grid, fold.coordinate) else -> throw IllegalArgumentException(fold.direction) } private fun applyHorizontalFold(grid: Array<Array<Boolean>>, x: Int): Array<Array<Boolean>> { if (x != (grid.size - 1) / 2) throw IllegalArgumentException("$x ${grid.size}") val newGrid = Array(x) { Array(grid[0].size) { false } } for (i in 0 until x) { for (j in grid[0].indices) { newGrid[i][j] = grid[i][j] } } for (i in x+1 until grid.size) { for (j in grid[0].indices) { if (grid[i][j]) { newGrid[grid.size - 1 - i][j] = true } } } return newGrid } private fun applyVerticalFold(grid: Array<Array<Boolean>>, y: Int): Array<Array<Boolean>> { if (y != (grid[0].size - 1) / 2) throw IllegalArgumentException("$y ${grid[0].size}") val newGrid = Array(grid.size) { Array(y) { false } } for (i in grid.indices) { for (j in 0 until y) { newGrid[i][j] = grid[i][j] } } for (i in grid.indices) { for (j in y+1 until grid[0].size) { if (grid[i][j]) { newGrid[i][grid[0].size - 1 - j] = true } } } return newGrid } private fun printGrid(grid: Array<Array<Boolean>>) { for (j in grid[0].indices) { for (i in grid.indices) { print(if (grid[i][j]) "#" else " ") } println() } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input13.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) solvePart2(lines) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day13.class", "javap": "Compiled from \"Day13.kt\"\npublic final class org.aoc2021.Day13 {\n public static final org.aoc2021.Day13 INSTANCE;\n\n private org.aoc2021.Day13();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day19.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path import kotlin.math.abs typealias Vector = List<Int> typealias Matrix = List<List<Int>> private fun Vector.vectorAdd(vector: Vector): Vector { return this.mapIndexed { i, value -> value + vector[i] } } private fun Vector.vectorSubtract(vector: Vector): Vector { return this.mapIndexed { i, value -> value - vector[i] } } private fun Vector.matrixMultiply(matrix: Matrix): Vector { return this.indices.map { i -> matrix.indices.sumOf { j -> this[j] * matrix[j][i] } } } private fun Matrix.multiply(matrix: Matrix): Matrix { return this.map { vector -> vector.matrixMultiply(matrix) } } object Day19 { data class ScannerLocation(val coordinates: Vector, val rotation: Matrix) private val identityMatrix = listOf( listOf(1, 0, 0), listOf(0, 1, 0), listOf(0, 0, 1), ) private val xRotationMatrix = listOf( listOf(1, 0, 0), listOf(0, 0, -1), listOf(0, 1, 0), ) private val yRotationMatrix = listOf( listOf(0, 0, -1), listOf(0, 1, 0), listOf(1, 0, 0), ) private val zRotationMatrix = listOf( listOf(0, 1, 0), listOf(-1, 0, 0), listOf(0, 0, 1), ) private val all3DRotationMatrices = generateRotationMatrices() private fun solve(lines: List<String>): Pair<Int, Int> { val scanners = parseLines(lines) val scannerLocations = findScanners(scanners) val solution1 = countBeacons(scanners, scannerLocations) val solution2 = scannerLocations.values.maxOf { a -> scannerLocations.values.filter { it !== a }.maxOf { b -> a.coordinates.vectorSubtract(b.coordinates).map(::abs).sum() } } return solution1 to solution2 } private fun parseLines(lines: List<String>): List<List<Vector>> { if (lines.isEmpty()) { return listOf() } val nextScanner = lines.drop(1) .takeWhile(String::isNotBlank) .map { line -> line.split(",").map(String::toInt) } return listOf(nextScanner).plus(parseLines(lines.dropWhile(String::isNotBlank).drop(1))) } private fun findScanners(scanners: List<List<Vector>>): Map<Int, ScannerLocation> { val scannerLocations = mutableMapOf( 0 to ScannerLocation(listOf(0, 0, 0), identityMatrix), ) // Triple(rotation matrix, base beacon, other beacon distances) val precomputedRotatedDistances = scanners.mapIndexed { i, beaconLocations -> i to beaconLocations.flatMap { beaconLocation -> all3DRotationMatrices.map { rotationMatrix -> val rotatedBeaconLocation = beaconLocation.matrixMultiply(rotationMatrix) val rotatedBeaconDistances = beaconLocations.filter { it !== beaconLocation } .map { it.matrixMultiply(rotationMatrix).vectorSubtract(rotatedBeaconLocation) } Triple(rotationMatrix, rotatedBeaconLocation, rotatedBeaconDistances.toSet()) } } }.toMap() while (scannerLocations.size < scanners.size) { val foundScannerIds = scanners.indices.filter { i -> scannerLocations.containsKey(i) } foundScannerIds.forEach { foundScannerId -> val foundScannerLocation = scannerLocations[foundScannerId]!! val foundBeaconDistances = precomputedRotatedDistances[foundScannerId]!! .filter { (rotationMatrix, _, _) -> rotationMatrix == foundScannerLocation.rotation } val unknownScannerIds = scanners.indices.filter { i -> !scannerLocations.containsKey(i) } unknownScannerIds.forEach { unknownScannerId -> for (t in precomputedRotatedDistances[unknownScannerId]!!) { val (rotationMatrix, rotatedBeaconLocation, rotatedBeaconDistances) = t val matchingFoundDistances = foundBeaconDistances.find { (_, _, foundDistancesSet) -> foundDistancesSet.intersect(rotatedBeaconDistances).size >= 11 } if (matchingFoundDistances != null) { val (_, foundBeaconLocation, _) = matchingFoundDistances val scannerCoordinates = foundScannerLocation.coordinates .vectorAdd(foundBeaconLocation) .vectorSubtract(rotatedBeaconLocation) scannerLocations[unknownScannerId] = ScannerLocation(scannerCoordinates, rotationMatrix) break } } } } } return scannerLocations.toMap() } private fun countBeacons(scanners: List<List<Vector>>, scannerLocations: Map<Int, ScannerLocation>): Int { val allBeaconLocations = mutableSetOf<Vector>() scanners.forEachIndexed { i, beaconLocations -> val scannerLocation = scannerLocations[i]!! allBeaconLocations.addAll(beaconLocations.map { beaconLocation -> beaconLocation.matrixMultiply(scannerLocation.rotation).vectorAdd(scannerLocation.coordinates) }) } return allBeaconLocations.size } private fun generateRotationMatrices(): List<Matrix> { val result = mutableListOf<Matrix>() var currentMatrix = identityMatrix listOf( zRotationMatrix to yRotationMatrix, yRotationMatrix to xRotationMatrix, xRotationMatrix to zRotationMatrix, ).forEach { (axis1Matrix, axis2Matrix) -> currentMatrix = currentMatrix.multiply(axis2Matrix) result.addAll(generateRotationMatricesForAxis(currentMatrix, axis1Matrix)) currentMatrix = currentMatrix.multiply(axis2Matrix).multiply(axis2Matrix) result.addAll(generateRotationMatricesForAxis(currentMatrix, axis1Matrix)) } return result.toList() } private fun generateRotationMatricesForAxis(matrix: Matrix, rotation: Matrix): List<Matrix> { val result = mutableListOf<Matrix>() var current = matrix (1..4).forEach { _ -> result.add(current) current = current.multiply(rotation) } return result.toList() } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input19.txt"), Charsets.UTF_8) val (solution1, solution2) = solve(lines) println(solution1) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day19$ScannerLocation.class", "javap": "Compiled from \"Day19.kt\"\npublic final class org.aoc2021.Day19$ScannerLocation {\n private final java.util.List<java.lang.Integer> coordinates;\n\n private final java.util.List<java.util.List<java....
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day14.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day14 { private const val iterationsPart1 = 10 private const val iterationsPart2 = 40 private fun solve(lines: List<String>, iterations: Int): Long { val start = lines[0] val rules = lines.drop(2).map { it.split(" -> ") }.associate { it[0] to it[1] } val startMap = start.windowed(2).groupBy { it }.mapValues { (_, values) -> values.size.toLong() } val processed = (1..iterations).fold(startMap) { polymer, _ -> doIteration(polymer, rules) } val countsByChar = processed.entries.flatMap { (pair, count) -> listOf( pair[0] to count, pair[1] to count ) } .groupBy(Pair<Char, Long>::first, Pair<Char, Long>::second) .mapValues { (_, counts) -> counts.sum() } .mapValues { (c, count) -> if (c == start.first() || c == start.last()) { if (start.first() == start.last()) { (count + 2) / 2 } else { (count + 1) / 2 } } else { count / 2 } } return countsByChar.values.maxOrNull()!! - countsByChar.values.minOrNull()!! } private fun doIteration(polymer: Map<String, Long>, rules: Map<String, String>): Map<String, Long> { val newMap = mutableMapOf<String, Long>() polymer.forEach { (pair, count) -> val rule = rules[pair] if (rule != null) { newMap.merge(pair[0] + rule, count) { a, b -> a + b } newMap.merge(rule + pair[1], count) { a, b -> a + b } } else { newMap.merge(pair, count) { a, b -> a + b } } } return newMap.toMap() } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input14.txt"), Charsets.UTF_8) val solution1 = solve(lines, iterationsPart1) println(solution1) val solution2 = solve(lines, iterationsPart2) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day14.class", "javap": "Compiled from \"Day14.kt\"\npublic final class org.aoc2021.Day14 {\n public static final org.aoc2021.Day14 INSTANCE;\n\n private static final int iterationsPart1;\n\n private static final int iterationsPart2;\n\n ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day4.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path class Board(boardLines: List<String>) { companion object { const val boardSize = 5 } private val board: List<List<Int>> private val chosenNumbers: Array<Array<Boolean>> = Array(boardSize) { Array(boardSize) { false } } private val numberToPosition: Map<Int, Pair<Int, Int>> init { board = boardLines.drop(1).map { line -> line.split(Regex(" +")).filter(String::isNotBlank).map(String::toInt) } numberToPosition = board.flatMapIndexed { i, row -> row.mapIndexed { j, number -> number to (i to j) } }.toMap() } fun processNumber(number: Int) { numberToPosition[number]?.let { (i, j) -> chosenNumbers[i][j] = true } } private fun checkRows(): Boolean { return chosenNumbers.any { row -> row.all { it } } } private fun checkColumns(): Boolean { return (0 until boardSize).any { j -> (0 until boardSize).all { i -> chosenNumbers[i][j] } } } fun checkWin() = checkRows() || checkColumns() fun sumUnmarkedNumbers(): Int { return board.mapIndexed { i, row -> row.filterIndexed { j, _ -> !chosenNumbers[i][j] }.sum() }.sum() } } object Day4 { private fun solvePart1(filename: String): Int { val lines = Files.readAllLines(Path.of(filename), Charsets.UTF_8) val chosenNumbers = lines[0].split(",").map(String::toInt) val boards = parseBoards(lines) chosenNumbers.forEach { chosenNumber -> boards.forEach { board -> board.processNumber(chosenNumber) if (board.checkWin()) { return chosenNumber * board.sumUnmarkedNumbers() } } } throw IllegalArgumentException("no winning boards found") } private fun solvePart2(filename: String): Int { val lines = Files.readAllLines(Path.of(filename), Charsets.UTF_8) val chosenNumbers = lines[0].split(",").map(String::toInt) val boards = parseBoards(lines) return findSolution(chosenNumbers, boards) } private fun parseBoards(lines: List<String>): List<Board> { return lines.drop(1).chunked(Board.boardSize + 1, ::Board) } private tailrec fun findSolution(chosenNumbers: List<Int>, boards: List<Board>): Int { val chosenNumber = chosenNumbers[0] boards.forEach { board -> board.processNumber(chosenNumber) } if (boards.size == 1 && boards[0].checkWin()) { return chosenNumber * boards[0].sumUnmarkedNumbers() } val remainingBoards = boards.filterNot(Board::checkWin) return findSolution(chosenNumbers.drop(1), remainingBoards) } @JvmStatic fun main(args: Array<String>) { val filename = "input4.txt" val solution1 = solvePart1(filename) println(solution1) val solution2 = solvePart2(filename) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day4.class", "javap": "Compiled from \"Day4.kt\"\npublic final class org.aoc2021.Day4 {\n public static final org.aoc2021.Day4 INSTANCE;\n\n private org.aoc2021.Day4();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day10.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day10 { private val values = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137, ) private fun solvePart1(lines: List<String>): Int { return lines.sumOf { line -> doLine(line) } } private fun solvePart2(lines: List<String>): Long { val scores = lines.filter { doLine(it) == 0 } .map { line -> solveIncompleteLine(line) } .sorted() return scores[scores.size / 2] } private fun doLine(line: String): Int { val chars = mutableListOf<Char>() for (c in line) { if (c in setOf('(', '[', '{', '<')) { chars.add(c) } else if (chars.isEmpty()) { return values[c]!! } else { if ( (c == ')' && chars.last() != '(') || (c == ']' && chars.last() != '[') || (c == '}' && chars.last() != '{') || (c == '>' && chars.last() != '<') ) { return values[c]!! } chars.removeLast() } } return 0 } private fun solveIncompleteLine(line: String): Long { val chars = mutableListOf<Char>() for (c in line) { if (c in setOf('(', '[', '{', '<')) { chars.add(c) } else { chars.removeLast() } } return chars.reversed().fold(0L) { p, c -> 5 * p + when (c) { '(' -> 1 '[' -> 2 '{' -> 3 '<' -> 4 else -> throw IllegalArgumentException("$c") } } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input10.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day10.class", "javap": "Compiled from \"Day10.kt\"\npublic final class org.aoc2021.Day10 {\n public static final org.aoc2021.Day10 INSTANCE;\n\n private static final java.util.Map<java.lang.Character, java.lang.Integer> values;\n\n privat...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day12.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day12 { private fun solvePart1(lines: List<String>): Int { val points = parseLines(lines) return search("start", points) } private fun solvePart2(lines: List<String>): Int { val points = parseLines(lines) return searchPart2("start", points) } private fun parseLines(lines: List<String>): Map<String, List<String>> { return lines.flatMap { line -> val (b, e) = line.split("-") listOf(b to e, e to b) } .groupBy(Pair<String, String>::first, Pair<String, String>::second) } private fun search(p: String, points: Map<String, List<String>>, visitedSmallCaves: Set<String> = setOf()): Int { return points[p]!!.filter { edge -> edge != "start" && !visitedSmallCaves.contains(edge) } .sumOf { edge -> if (edge == "end") { 1 } else { val newVisitedCaves = if (edge.all(Char::isLowerCase)) { visitedSmallCaves.plus(edge) } else { visitedSmallCaves } search(edge, points, newVisitedCaves) } } } private fun searchPart2( p: String, points: Map<String, List<String>>, visitedSmallCaves: Set<String> = setOf(), visitedTwice: Boolean = false, ): Int { return points[p]!!.filter { it != "start" } .sumOf { edge -> if (edge == "end") { 1 } else if (visitedSmallCaves.contains(edge) && visitedTwice) { 0 } else { val newVisitedTwice = if (visitedSmallCaves.contains(edge)) true else visitedTwice val newVisitedCaves = if (edge.all(Char::isLowerCase)) { visitedSmallCaves.plus(edge) } else { visitedSmallCaves } searchPart2(edge, points, newVisitedCaves, newVisitedTwice) } } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input12.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day12.class", "javap": "Compiled from \"Day12.kt\"\npublic final class org.aoc2021.Day12 {\n public static final org.aoc2021.Day12 INSTANCE;\n\n private org.aoc2021.Day12();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day21.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path import kotlin.math.max object Day21 { data class Key(val p1Pos: Int, val p1Score: Int, val p2Pos: Int, val p2Score: Int, val isP1Turn: Boolean) private fun solvePart1(lines: List<String>): Int { var (p1Pos, p2Pos) = parseStartingPositions(lines) var die = 1 var rolls = 0 var p1Score = 0 var p2Score = 0 while (true) { (1..3).forEach { _ -> p1Pos += die die = (die % 100) + 1 rolls++ } p1Pos = ((p1Pos - 1) % 10) + 1 p1Score += p1Pos if (p1Score >= 1000) { return rolls * p2Score } (1..3).forEach { _ -> p2Pos += die die = (die % 100) + 1 rolls++ } p2Pos = ((p2Pos - 1) % 10) + 1 p2Score += p2Pos if (p2Score >= 1000) { return rolls * p1Score } } } private fun solvePart2(lines: List<String>): Long { val (start1, start2) = parseStartingPositions(lines) val (p1Wins, p2Wins) = computeWinningUniverses(Key(start1, 0, start2, 0, true)) return max(p1Wins, p2Wins) } private fun computeWinningUniverses( key: Key, memoizedResults: MutableMap<Key, Pair<Long, Long>> = mutableMapOf(), ): Pair<Long, Long> { memoizedResults[key]?.let { return it } if (key.p1Score >= 21) { return 1L to 0L } if (key.p2Score >= 21) { return 0L to 1L } var p1WinSum = 0L var p2WinSum = 0L for (i in 1..3) { for (j in 1..3) { for (k in 1..3) { val (newP1Pos, newP1Score) = if (key.isP1Turn) { computeNewPosScore(key.p1Pos, key.p1Score, i, j, k) } else { key.p1Pos to key.p1Score } val (newP2Pos, newP2Score) = if (!key.isP1Turn) { computeNewPosScore(key.p2Pos, key.p2Score, i, j, k) } else { key.p2Pos to key.p2Score } val newKey = Key(newP1Pos, newP1Score, newP2Pos, newP2Score, !key.isP1Turn) val (p1Wins, p2Wins) = computeWinningUniverses(newKey, memoizedResults) p1WinSum += p1Wins p2WinSum += p2Wins } } } memoizedResults[key] = p1WinSum to p2WinSum return p1WinSum to p2WinSum } private fun computeNewPosScore(pos: Int, score: Int, i: Int, j: Int, k: Int): Pair<Int, Int> { val newPos = ((pos + i + j + k - 1) % 10) + 1 return newPos to (score + newPos) } private fun parseStartingPositions(lines: List<String>): Pair<Int, Int> { return lines[0].split(" ").last().toInt() to lines[1].split(" ").last().toInt() } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input21.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day21.class", "javap": "Compiled from \"Day21.kt\"\npublic final class org.aoc2021.Day21 {\n public static final org.aoc2021.Day21 INSTANCE;\n\n private org.aoc2021.Day21();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day20.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day20 { private const val iterationsPart1 = 2 private const val iterationsPart2 = 50 data class Image( val lit: Set<Pair<Int, Int>>, val outOfBoundsLit: Boolean, ) private fun solve(lines: List<String>, iterations: Int): Int { val (algorithm, image) = parseInput(lines) val processed = (1..iterations).fold(image) { prevImage, _ -> processImage(algorithm, prevImage) } return processed.lit.size } private fun processImage(algorithm: String, image: Image): Image { val newImage = mutableSetOf<Pair<Int, Int>>() val minX = image.lit.minOf { it.first } val maxX = image.lit.maxOf { it.first } val minY = image.lit.minOf { it.second } val maxY = image.lit.maxOf { it.second } for (i in (minX - 1)..(maxX + 1)) { for (j in (minY - 1)..(maxY + 1)) { val algorithmIndex = computeAlgorithmIndex(image, i, j, minX, maxX, minY, maxY) if (algorithm[algorithmIndex] == '#') { newImage.add(i to j) } } } val newOutOfBoundsLit = if (image.outOfBoundsLit) (algorithm.last() == '#') else (algorithm.first() == '#') return Image(newImage.toSet(), newOutOfBoundsLit) } private fun computeAlgorithmIndex(image: Image, i: Int, j: Int, minX: Int, maxX: Int, minY: Int, maxY: Int): Int { var algorithmIndex = 0 for (dx in -1..1) { for (dy in -1..1) { algorithmIndex *= 2 if (image.lit.contains(i + dx to j + dy)) { algorithmIndex++ } else if (i + dx < minX || i + dx > maxX || j + dy < minY || j + dy > maxY) { if (image.outOfBoundsLit) { algorithmIndex++ } } } } return algorithmIndex } private fun parseInput(lines: List<String>): Pair<String, Image> { val algorithm = lines[0] val litPixels = lines.drop(2).flatMapIndexed { i, line -> line.mapIndexed { j, c -> if (c == '#') (i to j) else null }.filterNotNull() }.toSet() return algorithm to Image(litPixels, false) } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input20.txt"), Charsets.UTF_8) val solution1 = solve(lines, iterationsPart1) println(solution1) val solution2 = solve(lines, iterationsPart2) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day20$Image.class", "javap": "Compiled from \"Day20.kt\"\npublic final class org.aoc2021.Day20$Image {\n private final java.util.Set<kotlin.Pair<java.lang.Integer, java.lang.Integer>> lit;\n\n private final boolean outOfBoundsLit;\n\n pub...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day8.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day8 { private fun solvePart1(lines: List<String>): Int { return lines.sumOf { line -> val outputDigits = line.split(" | ")[1].split(" ") outputDigits.count { setOf(2, 3, 4, 7).contains(it.length) } } } private fun solvePart2(lines: List<String>): Int { return lines.sumOf { line -> val (referenceDigits, outputDigits) = line.split(" | ").let { it[0].split(" ") to it[1].split(" ") } solveLine(referenceDigits, outputDigits) } } private fun solveLine(referenceDigits: List<String>, outputDigits: List<String>): Int { val digitToChars = Array(10) { setOf<Char>() } val referenceSets = referenceDigits.map(String::toSet) digitToChars[1] = referenceSets.single { it.size == 2 } digitToChars[4] = referenceSets.single { it.size == 4 } digitToChars[7] = referenceSets.single { it.size == 3 } digitToChars[8] = referenceSets.single { it.size == 7 } digitToChars[3] = referenceSets.single { referenceSet -> referenceSet.size == 5 && referenceSet.containsAll(digitToChars[1]) } digitToChars[2] = referenceSets.single { referenceSet -> referenceSet.size == 5 && referenceSet.intersect(digitToChars[4]).size == 2 } digitToChars[5] = referenceSets.single { referenceSet -> referenceSet.size == 5 && referenceSet.intersect(digitToChars[4]).size == 3 && referenceSet != digitToChars[3] } digitToChars[6] = referenceSets.single { referenceSet -> referenceSet.size == 6 && referenceSet.intersect(digitToChars[1]).size == 1 } digitToChars[9] = referenceSets.single { referenceSet -> referenceSet.size == 6 && referenceSet.containsAll(digitToChars[4]) } digitToChars[0] = referenceSets.single { referenceSet -> referenceSet.size == 6 && referenceSet != digitToChars[6] && referenceSet != digitToChars[9] } val setToDigit = digitToChars.mapIndexed { index, chars -> chars to index}.toMap() return outputDigits.fold(0) { sum, outputDigit -> 10 * sum + setToDigit[outputDigit.toSet()]!! } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input8.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day8.class", "javap": "Compiled from \"Day8.kt\"\npublic final class org.aoc2021.Day8 {\n public static final org.aoc2021.Day8 INSTANCE;\n\n private org.aoc2021.Day8();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day25.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day25 { private fun solve(lines: List<String>): Int { var grid = parseInput(lines) var turns = 0 while (true) { turns++ val prevGrid = grid grid = simulateTurn(grid) if (prevGrid == grid) { return turns } } } private fun simulateTurn(grid: List<List<Char>>): List<List<Char>> { return moveDown(moveRight(grid)) } private fun moveRight(grid: List<List<Char>>): List<List<Char>> { val newGrid = Array(grid.size) { Array(grid[0].size) { 'X' } } for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == '>') { val nj = (j + 1) % grid[0].size if (grid[i][nj] == '.') { newGrid[i][j] = '.' newGrid[i][nj] = '>' } else if (newGrid[i][j] == 'X') { newGrid[i][j] = '>' } } else if (newGrid[i][j] == 'X') { newGrid[i][j] = grid[i][j] } } } return newGrid.map(Array<Char>::toList) } private fun moveDown(grid: List<List<Char>>): List<List<Char>> { val newGrid = Array(grid.size) { Array(grid[0].size) { 'X' } } for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 'v') { val ni = (i + 1) % grid.size if (grid[ni][j] == '.') { newGrid[i][j] = '.' newGrid[ni][j] = 'v' } else if (newGrid[i][j] == 'X') { newGrid[i][j] = 'v' } } else if (newGrid[i][j] == 'X') { newGrid[i][j] = grid[i][j] } } } return newGrid.map(Array<Char>::toList) } private fun parseInput(lines: List<String>): List<List<Char>> { return lines.map { line -> line.toCharArray().toList() } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input25.txt"), Charsets.UTF_8) val solution = solve(lines) println(solution) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day25.class", "javap": "Compiled from \"Day25.kt\"\npublic final class org.aoc2021.Day25 {\n public static final org.aoc2021.Day25 INSTANCE;\n\n private org.aoc2021.Day25();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
jsgroth__advent-of-code-2021__ba81fad/src/org/aoc2021/Day18.kt
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day18 { data class TreeNode(val left: TreeNode? = null, val right: TreeNode? = null, val value: Int? = null) private fun solvePart1(lines: List<String>): Int { val snailfishNumbers = lines.map(Day18::parseSnailfishNumber) val snailfishSum = snailfishNumbers.reduce(Day18::addSnailfishNumbers) return magnitude(snailfishSum) } private fun solvePart2(lines: List<String>): Int { val snailfishNumbers = lines.map(Day18::parseSnailfishNumber) return snailfishNumbers.maxOf { snailfishNumber -> snailfishNumbers.filter { it !== snailfishNumber }.maxOf { otherNumber -> magnitude(addSnailfishNumbers(snailfishNumber, otherNumber)) } } } private fun parseSnailfishNumber(line: String): TreeNode { return parseNode(line, 0, false).first } private fun parseNode(line: String, i: Int, parsingRight: Boolean): Pair<TreeNode, Int> { return if (line[i] == '[') { val (left, j) = parseNode(line, i + 1, false) val (right, k) = parseNode(line, j + 1, true) TreeNode(left = left, right = right) to k + 1 } else { val endChar = if (parsingRight) ']' else ',' val end = line.indexOf(endChar, startIndex = i) val value = line.substring(i, end).toInt() TreeNode(value = value) to end } } private fun addSnailfishNumbers(first: TreeNode, second: TreeNode): TreeNode { return reduceSnailfishNumber(TreeNode(left = first, right = second)) } private tailrec fun reduceSnailfishNumber(number: TreeNode): TreeNode { findNodeToExplode(number)?.let { nodeToExplode -> return reduceSnailfishNumber(explode(number, nodeToExplode)) } findNodeToSplit(number)?.let { nodeToSplit -> return reduceSnailfishNumber(split(number, nodeToSplit)) } return number } private fun findNodeToExplode(number: TreeNode, depth: Int = 0): TreeNode? { if (depth == 4 && number.left != null && number.right != null) { return number } if (number.left == null || number.right == null) { return null } findNodeToExplode(number.left, depth + 1)?.let { return it } return findNodeToExplode(number.right, depth + 1) } private fun explode(number: TreeNode, nodeToExplode: TreeNode): TreeNode { val allNodes = traverse(number) val nodeToExplodeIndex = allNodes.indexOfFirst { it === nodeToExplode } val lastValueBefore = allNodes.subList(0, nodeToExplodeIndex - 1).findLast { it.value != null } val firstValueAfter = allNodes.subList(nodeToExplodeIndex + 2, allNodes.size).find { it.value != null } return doExplode(number, nodeToExplode, lastValueBefore, firstValueAfter) } private fun traverse(number: TreeNode): List<TreeNode> { return if (number.left == null || number.right == null) { listOf(number) } else { traverse(number.left).plus(number).plus(traverse(number.right)) } } private fun doExplode( number: TreeNode, nodeToExplode: TreeNode, lastValueBefore: TreeNode?, firstValueAfter: TreeNode?, ): TreeNode { if (number === nodeToExplode) { return TreeNode(value = 0) } if (number === lastValueBefore) { return TreeNode(value = number.value!! + nodeToExplode.left!!.value!!) } if (number === firstValueAfter) { return TreeNode(value = number.value!! + nodeToExplode.right!!.value!!) } if (number.left == null || number.right == null) { return number } return TreeNode( left = doExplode(number.left, nodeToExplode, lastValueBefore, firstValueAfter), right = doExplode(number.right, nodeToExplode, lastValueBefore, firstValueAfter), ) } private fun findNodeToSplit(number: TreeNode): TreeNode? { if (number.value != null && number.value >= 10) { return number } if (number.left == null || number.right == null) { return null } findNodeToSplit(number.left)?.let { return it } return findNodeToSplit(number.right) } private fun split(number: TreeNode, nodeToSplit: TreeNode): TreeNode { if (number === nodeToSplit) { return TreeNode( left = TreeNode(value = number.value!! / 2), right = TreeNode(value = number.value / 2 + (number.value % 2)), ) } if (number.left == null || number.right == null) { return number } return TreeNode( left = split(number.left, nodeToSplit), right = split(number.right, nodeToSplit), ) } private fun magnitude(number: TreeNode): Int { if (number.left == null || number.right == null) { return number.value!! } return 3 * magnitude(number.left) + 2 * magnitude(number.right) } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input18.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
[ { "class_path": "jsgroth__advent-of-code-2021__ba81fad/org/aoc2021/Day18.class", "javap": "Compiled from \"Day18.kt\"\npublic final class org.aoc2021.Day18 {\n public static final org.aoc2021.Day18 INSTANCE;\n\n private org.aoc2021.Day18();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
techstay__algorithm-study__1380ce1/kotlin-algorithm-sample/src/main/kotlin/yitian/study/algorithm/problem/ModProblem.kt
package yitian.study.algorithm.problem /** * 一筐鸡蛋: * 1个1个拿,正好拿完。 * 2个2个拿,还剩1个。 * 3个3个拿,正好拿完。 * 4个4个拿,还剩1个。 * 5个5个拿,还差1个。 * 6个6个拿,还剩3个。 * 7个7个拿,正好拿完。 * 8个8个拿,还剩1个。 * 9个9个拿,正好拿完。 * 问:筐里最少有几个鸡蛋? * */ class ModProblem /** * 直接暴力穷举 */ fun answer1() { var n = 0 while (true) { if (n % 2 == 1 && n % 4 == 1 && n % 5 == 4 && n % 6 == 3 && n % 7 == 0 && n % 8 == 1 && n % 9 == 0) { break } n++ } println(n) } /** * 改良版本 */ fun answer2() { var n = 63 var count = 0 while (true) { count++ if (n % 4 == 1 && n % 5 == 4 && n % 6 == 3 && n % 8 == 1) { break } n += 63 * 2 } println("n=$n,count=$count") } /** * 更优化版本 */ fun answer3() { var n = 63 * 3 var count = 0 while (true) { count++ if (n % 8 == 1) { break } n += 630 } println("n=$n,count=$count") } /** * 计算一个可以让所有余数都相等的数 */ fun cal(): Int { //由题意推出来的除数和余数的结果 val numbers = hashMapOf( 2 to 1, 3 to 0, 4 to 1, 5 to 4, 6 to 3, 7 to 0, 8 to 1, 9 to 0) var n = 0 while (true) { n++ for (k in numbers.keys) { val old = numbers[k] numbers[k] = (old!! + 1) % k } val set = numbers.values.toSet() if (set.size == 1) { break } } println("这个数是:$n") return n } /** * greatest common divisor * a和b的最大公约数 */ tailrec fun gcd(a: Int, b: Int): Int { val c = if (a > b) a % b else b % a if (c == 0) return b else return gcd(b, c) } /** * lowest common multiple * a和b的最小公倍数 */ fun lcm(a: Int, b: Int): Int { val c = gcd(a, b) return a * b / c } /** * 最后一种,通过把所有余数凑成相同的 * 然后使用最小公倍数来计算 */ fun answer4() { val n = cal() val lcmOfAll = (2..10).reduce(::lcm) println("结果是${lcmOfAll - n}") } fun main(args: Array<String>) { answer1() answer2() answer3() answer4() }
[ { "class_path": "techstay__algorithm-study__1380ce1/yitian/study/algorithm/problem/ModProblem.class", "javap": "Compiled from \"ModProblem.kt\"\npublic final class yitian.study.algorithm.problem.ModProblem {\n public yitian.study.algorithm.problem.ModProblem();\n Code:\n 0: aload_0\n 1: invo...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/JaroWinkler.kt
package com.aallam.similarity import kotlin.math.max import kotlin.math.min /** * The Jaro–Winkler distance metric is designed and best suited for short strings such as person names, and to detect * typos; it is (roughly) a variation of Damerau-Levenshtein, where the substitution of 2 close characters is considered * less important than the substitution of 2 characters that a far from each other. * * Jaro-Winkler was developed in the area of record linkage (duplicate detection) (Winkler, 1990). * It returns a value in the interval [0.0, 1.0]. * * @param threshold The current value of the threshold used for adding the Winkler bonus. The default value is 0.7. * * [Jaro–Winkler distance](https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance) */ public class JaroWinkler( private val threshold: Double = 0.7 ) { /** * Compute Jaro-Winkler similarity. * * * @param first the first string to compare. * @param second the second string to compare. * @return The Jaro-Winkler similarity in the range [0, 1] */ public fun similarity(first: String, second: String): Double { if (first == second) return 1.0 val (m, t, l, p) = matchStrings(first, second) if (m == 0f) return 0.0 // Jaro similarity = 1/3 * (m/|s1| + m/|s2| + (m-t)/m) val sj = ((m / first.length) + (m / second.length) + ((m - t) / m)) / 3.0 // Winkler similarity = Sj + P * L * (1 – Sj) return if (sj > threshold) sj + p * l * (1 - sj) else sj } /** * Return 1 - similarity. * @param first the first string to compare. * @param second the second string to compare. * @return 1 - similarity. */ public fun distance(first: String, second: String): Double { return 1.0 - similarity(first, second) } /** * Matches two given strings and returns the count of matching characters, transpositions, the length of the * common prefix, and the scaling factor. * * @param first The first string to compare. * @param second The second string to compare. */ private fun matchStrings(first: String, second: String): Match { val min = minOf(first, second) val max = maxOf(first, second) val (matchIndexes, matchFlags, matches) = computeStringMatch(max, min) val ms1 = CharArray(matches).apply { fill(min, matchIndexes) } val ms2 = CharArray(matches).apply { fill(max, matchFlags) } val transpositions = transpositions(ms1, ms2) val prefix = commonPrefix(min, max) val scaling = min(JW_SCALING_FACTOR, 1.0 / max.length) return Match(matches.toFloat(), transpositions, prefix, scaling) } /** * Computes the matching indexes and flags between two strings. * * @param max the longer string * @param min the shorter string */ private fun computeStringMatch(max: String, min: String): StringMatchInfo { val range = max(max.length / 2 - 1, 0) val matchIndexes = IntArray(min.length) { -1 } val matchFlags = BooleanArray(max.length) var matches = 0 for (i in min.indices) { val char = min[i] var xi = max(i - range, 0) val xn = min(i + range + 1, max.length) while (xi < xn) { if (!matchFlags[xi] && char == max[xi]) { matchIndexes[i] = xi matchFlags[xi] = true matches++ break } xi++ } } return StringMatchInfo(matchIndexes, matchFlags, matches) } /** * Fills this character array with the characters from [max] at the positions indicated by the corresponding value * in [flags]. * * @param max the string from which to take the characters. * @param flags the boolean array indicating which characters in the max string should be included. */ private fun CharArray.fill(max: String, flags: BooleanArray) { var si = 0 for (i in max.indices) { if (flags[i]) { this[si] = max[i] si++ } } } /** * Fills the character array with characters from the given string [min], based on the specified match [indexes]. * * @param min the string containing the characters to be copied into the character array. * @param indexes the indexes indicating which characters to copy from `min`. Any index value of -1 will be ignored. */ private fun CharArray.fill(min: String, indexes: IntArray) { var si = 0 for (i in min.indices) { if (indexes[i] != -1) { this[si] = min[i] si++ } } } /** * Calculates the length of the common prefix between two strings. * * @param min the shorter of the two strings being compared * @param max the longer of the two strings being compared */ private fun commonPrefix(min: String, max: String): Int { var prefix = 0 for (mi in min.indices) { if (min[mi] != max[mi]) break prefix++ } return prefix } /** * Calculates the number of transpositions between two matched strings. * * @param ms1 the first matched string. * @param ms2 the second matched string. */ private fun transpositions(ms1: CharArray, ms2: CharArray): Int { var transpositions = 0 for (mi in ms1.indices) { if (ms1[mi] != ms2[mi]) { transpositions++ } } return transpositions / 2 } public companion object { /** The standard value for the scaling factor */ private const val JW_SCALING_FACTOR = 0.1 } } /** * Represents information about the matching indexes and flags between two strings, * along with the total number of matches found. * * @param matchIndexes matching indexes * @param matchFlags matching flags * @param matches total number of matches found */ internal data class StringMatchInfo( val matchIndexes: IntArray, val matchFlags: BooleanArray, val matches: Int ) /** * Represents a set of parameters that describe the similarity between two strings. * * @param matches number of matching characters * @param transpositions number of transpositions * @param prefix length of common prefix * @param scaling scaling factor */ internal data class Match( val matches: Float, val transpositions: Int, val prefix: Int, val scaling: Double, )
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/JaroWinkler$Companion.class", "javap": "Compiled from \"JaroWinkler.kt\"\npublic final class com.aallam.similarity.JaroWinkler$Companion {\n private com.aallam.similarity.JaroWinkler$Companion();\n Code:\n 0: aload_0\...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/OptimalStringAlignment.kt
package com.aallam.similarity import kotlin.math.min /** * Implementation of the Optimal String Alignment (sometimes called the restricted edit distance) variant * of the Damerau-Levenshtein distance. * * The difference between the two algorithms consists in that the Optimal String Alignment algorithm computes the number * of edit operations needed to make the strings equal under the condition that no substring is edited more than once, * whereas Damerau-Levenshtein presents no such restriction. */ public class OptimalStringAlignment { /** * Compute the distance between strings: the minimum number of operations needed to transform one string into the * other (insertion, deletion, substitution of a single character, or a transposition of two adjacent characters) * while no substring is edited more than once. * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: String, second: String): Int { if (first == second) return 0 val n = first.length val m = second.length if (n == 0) return m if (m == 0) return n // create the distance matrix H[0..first.length+1][0..second.length+1] val distanceMatrix = Array(n + 2) { IntArray(m + 2) } // initialize top row and leftmost column for (i in 0..n) distanceMatrix[i][0] = i for (j in 0..m) distanceMatrix[0][j] = j // fill the distance matrix for (i in 1..n) { for (j in 1..m) { val cost = if (first[i - 1] == second[j - 1]) 0 else 1 val substitution = distanceMatrix[i - 1][j - 1] + cost val insertion = distanceMatrix[i][j - 1] + 1 val deletion = distanceMatrix[i - 1][j] + 1 distanceMatrix[i][j] = minOf(substitution, insertion, deletion) // transposition check if (i > 1 && j > 1 && first[i - 1] == second[j - 2] && first[i - 2] == second[j - 1]) { distanceMatrix[i][j] = min(distanceMatrix[i][j], distanceMatrix[i - 2][j - 2] + cost) } } } return distanceMatrix[n][m] } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/OptimalStringAlignment.class", "javap": "Compiled from \"OptimalStringAlignment.kt\"\npublic final class com.aallam.similarity.OptimalStringAlignment {\n public com.aallam.similarity.OptimalStringAlignment();\n Code:\n ...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/SorensenDice.kt
package com.aallam.similarity import com.aallam.similarity.internal.Shingle /** * Sorensen-Dice coefficient, aka Sørensen index, Dice's coefficient or Czekanowski's binary (non-quantitative) index. * * The strings are first converted to boolean sets of k-shingles (sequences of k characters), then the similarity is * computed as 2 * |A inter B| / (|A| + |B|). * * Attention: Sorensen-Dice distance (and similarity) does not satisfy triangle inequality. * * [Sørensen–Dice coefficient](https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient) * * @param k length of k-shingles */ public class SorensenDice(public val k: Int = 3) { /** * Similarity is computed as 2 * |A ∩ B| / (|A| + |B|). * * @param first The first string to compare. * @param second The second string to compare. */ public fun similarity(first: String, second: String): Double { if (first == second) return 1.0 val profile1 = Shingle.profile(first, k) val profile2 = Shingle.profile(second, k) val intersect = profile1.keys.intersect(profile2.keys) return (2.0 * intersect.size) / (profile1.size + profile2.size) } /** * Returns 1 - similarity. * * @param first The first string to compare. * @param second The second string to compare. */ public fun distance(first: String, second: String): Double { return 1.0 - similarity(first, second) } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/SorensenDice.class", "javap": "Compiled from \"SorensenDice.kt\"\npublic final class com.aallam.similarity.SorensenDice {\n private final int k;\n\n public com.aallam.similarity.SorensenDice(int);\n Code:\n 0: aload_...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/LongestCommonSubsequence.kt
package com.aallam.similarity import kotlin.math.max /** * The longest common subsequence (LCS) problem consists in finding the longest subsequence common to two (or more) * sequences. It differs from problems of finding common substrings: unlike substrings, subsequences are not required * to occupy consecutive positions within the original sequences. * * LCS distance is equivalent to Levenshtein distance, when only insertion and deletion is allowed (no substitution), * or when the cost of the substitution is the double of the cost of an insertion or deletion. */ public class LongestCommonSubsequence { /** * Return the LCS distance between strings [first] (length n) and [second] (length m), * computed as `|n| + |m| - 2 * |LCS(first, second)|`, with min = 0 max = n + m * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: String, second: String): Int { if (first == second) return 0 return first.length + second.length - 2 * length(first, second) } /** * Return the length of the longest common subsequence (LCS) between strings [first] * and [second]. * * @param first the first string to compare. * @param second the second string to compare. */ public fun length(first: String, second: String): Int { val n = first.length val m = second.length val x = first.toCharArray() val y = second.toCharArray() val c = Array(n + 1) { IntArray(m + 1) } for (i in 1..n) { for (j in 1..m) { if (x[i - 1] == y[j - 1]) { c[i][j] = c[i - 1][j - 1] + 1 } else { c[i][j] = max(c[i][j - 1], c[i - 1][j]) } } } return c[n][m] } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/LongestCommonSubsequence.class", "javap": "Compiled from \"LongestCommonSubsequence.kt\"\npublic final class com.aallam.similarity.LongestCommonSubsequence {\n public com.aallam.similarity.LongestCommonSubsequence();\n Code...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/NGram.kt
package com.aallam.similarity import kotlin.math.max import kotlin.math.min /** * N-Gram Similarity as defined by Kondrak, "N-Gram Similarity and Distance", String Processing and Information * Retrieval, Lecture Notes in Computer Science Volume 3772, 2005, pp 115-126. * * The algorithm uses affixing with special character '\n' to increase the weight of first characters. * The normalization is achieved by dividing the total similarity score the original length of the longest word. * * [N-Gram Similarity and Distance](http://webdocs.cs.ualberta.ca/~kondrak/papers/spire05.pdf) * * @param n n-gram length. */ public class NGram(private val n: Int = 2) { /** * Compute n-gram distance, in the range `[0, 1]`. * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: String, second: String): Double { if (first == second) return 0.0 val sl = first.length val tl = second.length if (sl == 0 || tl == 0) return 1.0 val special = '\n' var cost = 0 if (sl < n || tl < n) { val ni = min(sl, tl) for (i in 0..ni) { if (first[i] == second[i]) cost++ } return cost.toDouble() / max(sl, tl) } // construct `sa` with prefix val sa = CharArray(sl + n - 1) { i -> if (i < n - 1) special else first[i - n + 1] } var p = DoubleArray(sl + 1) { it.toDouble() } // 'previous' cost array, horizontally var d = DoubleArray(sl + 1) // cost array, horizontally var tj = CharArray(n) // jth n-gram of t for (j in 1..tl) { // construct tj n-gram if (j < n) { for (ti in 0..<n - j) { tj[ti] = special // add prefix } for (ti in n - j..<n) { tj[ti] = second[ti - (n - j)] } } else { tj = second.substring(j - n, j).toCharArray() } d[0] = j.toDouble() for (i in 1..sl) { cost = 0 var tn = n // compare sa to tj for (ni in 0..<n) { if (sa[i - 1 + ni] != tj[ni]) { cost++ } else if (sa[i - 1 + ni] == special) { tn-- // discount matches on prefix } } val ec = cost.toDouble() / tn // minimum of cell to the left+1, to the top+1, // diagonally left and up +cost d[i] = minOf(d[i - 1] + 1, p[i] + 1, p[i - 1] + ec) } // copy current distance counts to 'previous row' distance counts val swap = p p = d d = swap } // our last action in the above loop was to switch d and p, so p now // actually has the most recent cost counts return p[sl] / max(tl, sl) } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/NGram.class", "javap": "Compiled from \"NGram.kt\"\npublic final class com.aallam.similarity.NGram {\n private final int n;\n\n public com.aallam.similarity.NGram(int);\n Code:\n 0: aload_0\n 1: invokespecial #...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/QGram.kt
package com.aallam.similarity import com.aallam.similarity.internal.Profile import com.aallam.similarity.internal.Shingle import kotlin.math.abs /** * Q-gram distance, as defined by Ukkonen in [Approximate string-matching with q-grams and maximal matches](http://www.sciencedirect.com/science/article/pii/0304397592901434). * The distance between two strings is defined as the L1 norm of the difference of their profiles (the number * of occurrences of each n-gram). * * Q-gram distance is a lower bound on Levenshtein distance, but can be computed in O(m+n), where Levenshtein * requires O(m.n). * * @param k length of k-shingles */ public class QGram(private val k: Int = 3) { /** * The distance between two strings is defined as the L1 norm of the * difference of their profiles (the number of occurence of each k-shingle). * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: String, second: String): Int { if (first == second) return 0 val p1 = Shingle.profile(first, k) val p2 = Shingle.profile(second, k) return distance(p1, p2) } /** * Compute QGram distance using precomputed profiles. */ private fun distance(first: Profile, second: Profile): Int { var agg = 0 for (key in (first.keys + second.keys)) { var v1 = 0 var v2 = 0 first[key]?.let { v1 = it } second[key]?.let { v2 = it } agg += abs(v1 - v2) } return agg } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/QGram.class", "javap": "Compiled from \"QGram.kt\"\npublic final class com.aallam.similarity.QGram {\n private final int k;\n\n public com.aallam.similarity.QGram(int);\n Code:\n 0: aload_0\n 1: invokespecial #...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/WeightedLevenshtein.kt
package com.aallam.similarity import kotlin.math.min /** * Implementation of Levenshtein that allows to define different weights for different character substitutions. * * @param weights the strategy to determine character operations weights. */ public class WeightedLevenshtein( private val weights: OperationsWeights ) { public fun distance(first: CharSequence, second: CharSequence, limit: Double = Double.MAX_VALUE): Double { if (first == second) return 0.0 if (first.isEmpty()) return second.length.toDouble() if (second.isEmpty()) return first.length.toDouble() // initial costs is the edit distance from an empty string, which corresponds to the characters to insert. // the array size is : length + 1 (empty string) var cost = DoubleArray(first.length + 1) var newCost = DoubleArray(first.length + 1) first.forEachIndexed { i, char -> cost[i + 1] = cost[i] + weights.insertion(char) } for (i in 1..second.length) { // calculate new costs from the previous row. // the first element of the new row is the edit distance (deletes) to match empty string val secondChar = second[i - 1] val deletionCost = weights.deletion(secondChar) newCost[0] = cost[0] + deletionCost var minCost = newCost[0] // fill in the rest of the row for (j in 1..first.length) { // if it's the same char at the same position, no edit cost. val firstChar = first[j - 1] val edit = if (firstChar == secondChar) 0.0 else weights.substitution(firstChar, secondChar) val replace = cost[j - 1] + edit val insert = cost[j] + weights.insertion(secondChar) val delete = newCost[j - 1] + weights.deletion(firstChar) newCost[j] = minOf(insert, delete, replace) minCost = min(minCost, newCost[j]) } if (minCost >= limit) return limit // flip references of current and previous row val swap = cost cost = newCost newCost = swap } return cost.last() } } /** * Used to indicate the cost of character operations (add, replace, delete). * The cost should always be in the range `[O, 1]`. * * Default implementation of all operations is `1.0`. * * Examples: * - In an OCR application, cost('o', 'a') could be 0.4. * - In a check-spelling application, cost('u', 'i') could be 0.4 because these are next to each other on the keyboard. */ public interface OperationsWeights { /** * Indicate the cost of substitution. * The cost in the range `[0, 1]`. * * @param first first character of the substitution. * @param second second character of the substitution. */ public fun substitution(first: Char, second: Char): Double = 1.0 /** * Get the cost to delete a given character. * The cost in the range `[0, 1]`. * * @param char the character being inserted. */ public fun deletion(char: Char): Double = 1.0 /** * Get the cost to insert a given character. * The cost in the range `[0, 1]`. * * @param char the character being inserted. */ public fun insertion(char: Char): Double = 1.0 }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/WeightedLevenshtein.class", "javap": "Compiled from \"WeightedLevenshtein.kt\"\npublic final class com.aallam.similarity.WeightedLevenshtein {\n private final com.aallam.similarity.OperationsWeights weights;\n\n public com.aa...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/DamerauLevenshtein.kt
package com.aallam.similarity /** * Damerau-Levenshtein distance with transposition (*unrestricted Damerau-Levenshtein* distance). * * The distance is the minimum number of operations needed to transform one string into the other, where an operation * is defined as an insertion, deletion, or substitution of a single character, or a transposition of two adjacent * characters. It does respect triangle inequality, and is thus a metric distance. * * [Damerau–Levenshtein](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Distance_with_adjacent_transpositions) */ public class DamerauLevenshtein { /** * Compute the distance between strings: the minimum number of operations needed to transform one string into the * other (insertion, deletion, substitution of a single character, or a transposition of two adjacent characters). * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: CharSequence, second: CharSequence): Int { // infinite distance is the max possible distance val n = first.length val m = second.length val infinity = n + m // create and initialize the character array indices val charsRowIndex = mutableMapOf<Char, Int>() for (index in first.indices) charsRowIndex[first[index]] = 0 for (char in second) charsRowIndex[char] = 0 // create the distance matrix H[0 .. first.length+1][0 .. second.length+1] val distanceMatrix = Array(n + 2) { IntArray(m + 2) } // initialize the left edge for (i in first.indices) { distanceMatrix[i + 1][0] = infinity distanceMatrix[i + 1][1] = i } // initialize top edge for (j in second.indices) { distanceMatrix[0][j + 1] = infinity distanceMatrix[1][j + 1] = j } // fill in the distance matrix for (i in 1..n) { var lastMatch = 0 for (j in 1..m) { val lastRowIndex = charsRowIndex.getValue(second[j - 1]) val previousMatch = lastMatch val cost: Int if (first[i - 1] == second[j - 1]) { cost = 0 lastMatch = j } else { cost = 1 } val substitution = distanceMatrix[i][j] + cost val insertion = distanceMatrix[i + 1][j] + 1 val deletion = distanceMatrix[i][j + 1] + 1 val transposition = distanceMatrix[lastRowIndex][previousMatch] + (i - lastRowIndex - 1) + 1 + (j - previousMatch - 1) distanceMatrix[i + 1][j + 1] = minOf(substitution, insertion, deletion, transposition) } charsRowIndex[first[i - 1]] = i } return distanceMatrix[n + 1][m + 1] } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/DamerauLevenshtein.class", "javap": "Compiled from \"DamerauLevenshtein.kt\"\npublic final class com.aallam.similarity.DamerauLevenshtein {\n public com.aallam.similarity.DamerauLevenshtein();\n Code:\n 0: aload_0\n ...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/Cosine.kt
package com.aallam.similarity import com.aallam.similarity.internal.Profile import com.aallam.similarity.internal.Shingle import kotlin.math.sqrt /** * Implements Cosine Similarity between strings. * * The strings are first transformed in vectors of occurrences of k-shingles (sequences of [k] characters). * In this n-dimensional space, the similarity between the two strings is the cosine of their respective vectors. * * The cosine distance is computed as `1 - cosine similarity`. * * [Cosine Similarity](https://en.wikipedia.org/wiki/Cosine_similarity) * * @param k length of k-shingles */ public class Cosine(private val k: Int = 3) { /** * Compute the cosine similarity between strings. * * It is computed as `V1.V2/(|V1|*|V2|)` where `V1` and `V2` are vector representation of [first] and [second]. * * @param first first string to compare. * @param second second string to compare. * @return the cosine similarity in the range `[0, 1]`. */ public fun similarity(first: CharSequence, second: CharSequence): Double { if (first == second) return 1.0 if (first.length < k || second.length < k) return 0.0 val p1 = Shingle.profile(first, k) val p2 = Shingle.profile(second, k) return (p1 dot p2) / (norm(p1) * norm(p2)) } /** Dot product */ private infix fun Profile.dot(profile: Profile): Int { val intersection = keys.intersect(profile.keys) return intersection.sumOf { getValue(it) * profile.getValue(it) } } /** Compute the norm L2 : sqrt(sum(v²)). */ private fun norm(profile: Profile): Double { val sum = profile.values.sumOf { it * it }.toDouble() return sqrt(sum) } /** * Compute the cosine distance between two string. * Corresponds to 1.0 - similarity. * * @param first first string to compare. * @param second second string to compare. */ public fun distance(first: CharSequence, second: CharSequence): Double { return 1.0 - similarity(first, second) } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/Cosine.class", "javap": "Compiled from \"Cosine.kt\"\npublic final class com.aallam.similarity.Cosine {\n private final int k;\n\n public com.aallam.similarity.Cosine(int);\n Code:\n 0: aload_0\n 1: invokespeci...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/Levenshtein.kt
package com.aallam.similarity import kotlin.math.min /** * The Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions or * substitutions) required to change one string into the other. * * This implementation uses dynamic programming (Wagner–Fischer algorithm). * * [Levenshtein Distance](https://en.wikipedia.org/wiki/Levenshtein_distance) */ public class Levenshtein { /** * The Levenshtein distance, or edit distance, between two words is the minimum number of single-character edits * (insertions, deletions or substitutions) required to change one word into the other. * * It is always at least the difference of the sizes of the two strings. * It is at most the length of the longer string. * It is `0` if and only if the strings are equal. * * @param first first string to compare. * @param second second string to compare. * @param limit the maximum result to compute before stopping, terminating calculation early. * @return the computed Levenshtein distance. */ public fun distance(first: CharSequence, second: CharSequence, limit: Int = Int.MAX_VALUE): Int { if (first == second) return 0 if (first.isEmpty()) return second.length if (second.isEmpty()) return first.length // initial costs is the edit distance from an empty string, which corresponds to the characters to inserts. // the array size is : length + 1 (empty string) var cost = IntArray(first.length + 1) { it } var newCost = IntArray(first.length + 1) for (i in 1..second.length) { // calculate new costs from the previous row. // the first element of the new row is the edit distance (deletes) to match empty string newCost[0] = i var minCost = i // fill in the rest of the row for (j in 1..first.length) { // if it's the same char at the same position, no edit cost. val edit = if (first[j - 1] == second[i - 1]) 0 else 1 val replace = cost[j - 1] + edit val insert = cost[j] + 1 val delete = newCost[j - 1] + 1 newCost[j] = minOf(insert, delete, replace) minCost = min(minCost, newCost[j]) } if (minCost >= limit) return limit // flip references of current and previous row val swap = cost cost = newCost newCost = swap } return cost.last() } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/Levenshtein.class", "javap": "Compiled from \"Levenshtein.kt\"\npublic final class com.aallam.similarity.Levenshtein {\n public com.aallam.similarity.Levenshtein();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/NormalizedLevenshtein.kt
package com.aallam.similarity import kotlin.math.max /** * This distance is computed as levenshtein distance divided by the length of the longest string. * The resulting value is always in the interval 0 to 1. * * [Levenshtein Distance](https://en.wikipedia.org/wiki/Levenshtein_distance) */ public class NormalizedLevenshtein { /** * Levenshtein distance metric implementation. */ private val levenshtein = Levenshtein() /** * This distance is computed as levenshtein distance divided by the length of the longest string. * The resulting value is always in the interval 0 to 1. * * Compute distance as Levenshtein(s1, s2) / max(|s1|, |s2|). * * @param first left hand side string to compare. * @param second right hand side string to compare. * @return the computed normalized Levenshtein distance. */ public fun distance(first: CharSequence, second: CharSequence): Double { val maxLength = max(first.length, second.length) if (maxLength == 0) return 0.0 return levenshtein.distance(first, second) / maxLength.toDouble() } /** * Compute the similarity between two string. * Corresponds to 1.0 - normalized distance. * * @param lhs left hand side string to compare. * @param rhs right hand side string to compare. * @return the computer similarity */ public fun similarity(lhs: CharSequence, rhs: CharSequence): Double { return 1.0 - distance(lhs, rhs) } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/NormalizedLevenshtein.class", "javap": "Compiled from \"NormalizedLevenshtein.kt\"\npublic final class com.aallam.similarity.NormalizedLevenshtein {\n private final com.aallam.similarity.Levenshtein levenshtein;\n\n public co...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/Jaccard.kt
package com.aallam.similarity import com.aallam.similarity.internal.Shingle /** * Each input string is converted into a set of n-grams, the Jaccard index is then computed as `|A ∩ B| / |A ∪ B|`. * * Like Q-Gram distance, the input strings are first converted into sets of n-grams (sequences of n characters, also * called k-shingles), but this time the cardinality of each n-gram is not taken into account. * * Jaccard index is a metric distance. * * @param k length of k-shingles */ public class Jaccard(private val k: Int = 3) { /** * Compute Jaccard index. `|A ∩ B| / |A ∪ B|`. * @param first the first string to compare. * @param second the second string to compare. */ public fun similarity(first: String, second: String): Double { if (first == second) return 1.0 val p1 = Shingle.profile(first, k) val p2 = Shingle.profile(second, k) val union = p1.keys + p2.keys val inter = p1.keys.size + p2.keys.size - union.size return inter.toDouble() / union.size } /** * Distance is computed as 1 - similarity. * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: String, second: String): Double { return 1.0 - similarity(first, second) } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/Jaccard.class", "javap": "Compiled from \"Jaccard.kt\"\npublic final class com.aallam.similarity.Jaccard {\n private final int k;\n\n public com.aallam.similarity.Jaccard(int);\n Code:\n 0: aload_0\n 1: invokes...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/RatcliffObershelp.kt
package com.aallam.similarity /** * The Ratcliff/Obershelp algorithm computes the similarity of two strings the doubled number of matching characters * divided by the total number of characters in the two strings. Matching characters are those in the longest common * subsequence plus, recursively, matching characters in the unmatched region on either side of the longest common * subsequence. */ public class RatcliffObershelp { /** * Compute the Ratcliff-Obershelp similarity between strings. * * @param first the first string to compare. * @param second the second string to compare. */ public fun similarity(first: String, second: String): Double { if (first == second) return 1.0 val matches = matchList(first, second) val sumOfMatches = matches.sumOf { it.length } return 2.0 * sumOfMatches / (first.length + second.length) } /** * Return 1 - similarity. * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: String, second: String): Double { return 1.0 - similarity(first, second) } /** * Returns a list of matching substrings between the given [first] and [second] strings. * * @param first The first string to compare. * @param second The second string to compare. */ private fun matchList(first: String, second: String): List<String> { val match = frontMaxMatch(first, second) if (match.isEmpty()) return emptyList() val frontQueue = matchList(first.substringBefore(match), second.substringBefore(match)) val endQueue = matchList(first.substringAfter(match), second.substringAfter(match)) return listOf(match) + frontQueue + endQueue } /** * Returns the longest substring that occurs at the beginning of both the [first] and [second] strings. * * @param first the first string to compare. * @param second the second string to compare. */ private fun frontMaxMatch(first: String, second: String): String { var longestSubstring = "" for (i in first.indices) { for (j in i + 1..first.length) { val substring = first.substring(i, j) if (second.contains(substring) && substring.length > longestSubstring.length) { longestSubstring = substring } } } return longestSubstring } }
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/RatcliffObershelp.class", "javap": "Compiled from \"RatcliffObershelp.kt\"\npublic final class com.aallam.similarity.RatcliffObershelp {\n public com.aallam.similarity.RatcliffObershelp();\n Code:\n 0: aload_0\n ...
aallam__string-similarity-kotlin__40cd4eb/string-similarity/src/commonMain/kotlin/com/aallam/similarity/internal/Shingle.kt
package com.aallam.similarity.internal /** * Similarities that rely on set operations (like cosine similarity or jaccard index). */ internal interface Shingle { /** * Compute and return the profile of string as defined by [Ukkonen](https://www.cs.helsinki.fi/u/ukkonen/TCS92.pdf). * * The profile is the number of occurrences of k-shingles, and is used to compute q-gram similarity, Jaccard index, * etc. * * k-shingling is the operation of transforming a string (or text document) into a set of n-grams, which can be used to * measure the similarity between two strings or documents. * * Generally speaking, a k-gram is any sequence of [k] tokens. * Multiple subsequent spaces are replaced by a single space, and a k-gram is a sequence of k characters. * * Default value of [k] is `3`. A good rule of thumb is to imagine that there are only 20 characters and estimate the * number of k-shingles as 20^k. For small documents like e-mails, k = 5 is a recommended value. For large documents, * such as research articles, k = 9 is considered a safe choice. * * The memory requirement of the profile can be up to [k] * [string]`.length`. * * @param string input string * @param k length of k-shingles * @return the profile of the provided string */ fun profile(string: CharSequence, k: Int = 3): Profile { require(k > 0) { "k should be positive" } val filtered = spaces.replace(string, " ") return filtered.windowed(size = k).groupingBy { it }.eachCount() } companion object : Shingle { /** * Regex for subsequent spaces. */ private val spaces = Regex("\\s+") } } /** * The number of occurrences of k-shingles. */ internal typealias Profile = Map<String, Int>
[ { "class_path": "aallam__string-similarity-kotlin__40cd4eb/com/aallam/similarity/internal/Shingle$DefaultImpls.class", "javap": "Compiled from \"Shingle.kt\"\npublic final class com.aallam.similarity.internal.Shingle$DefaultImpls {\n public static java.util.Map<java.lang.String, java.lang.Integer> profile(...
Malo-T__AoC-2022__f4edefa/src/main/kotlin/day07/Day07.kt
package day07 data class File( val name: String, val size: Int, ) data class Directory( val name: String, val directories: MutableList<Directory> = mutableListOf(), val files: MutableList<File> = mutableListOf(), ) { // must not be in the constructor lateinit var parent: Directory fun size(): Int = files.sumOf { it.size } + directories.sumOf { it.size() } fun children(): List<Directory> = directories + directories.flatMap { it.children() } } private fun root() = Directory(name = "/").apply { parent = this } /** Return parent or child directory depending on command */ private fun Directory.cd(cmd: String): Directory = when (val dir = cmd.substring(5)) { ".." -> parent else -> directories.firstOrNull { it.name == dir } ?: Directory(name = dir) .apply { parent = this@cd } .also { directories.add(it) } } /** Create and add file to current directory. Return current directory */ private fun Directory.addFile(path: String): Directory = apply { val (size, name) = path.split(' ') if (files.none { it.name == name }) { files += File( name = name, size = size.toInt() ) } } class Day07 { fun parse1(input: String): Directory = root().apply { input.lines() .drop(1) // first line is "$ cd /" -> root .fold(this) { dir, line -> when { line == "$ ls" -> dir// do nothing line.startsWith("$ cd ") -> dir.cd(line)// move to directory (create it if necessary) line.startsWith("dir ") -> dir // do nothing (directories are created on 'cd') line[0].isDigit() -> dir.addFile(line)// add file to directory else -> throw IllegalStateException("Invalid line: $line") } } } fun part1(root: Directory): Int = root.children() .map { it.size() } .filter { it < 100_000 } .sum() fun part2(root: Directory): Int { TODO() } }
[ { "class_path": "Malo-T__AoC-2022__f4edefa/day07/Day07Kt.class", "javap": "Compiled from \"Day07.kt\"\npublic final class day07.Day07Kt {\n private static final day07.Directory root();\n Code:\n 0: new #8 // class day07/Directory\n 3: dup\n 4: ldc #...
Malo-T__AoC-2022__f4edefa/src/main/kotlin/day04/Day04.kt
package day04 private typealias Assignments = Pair<IntRange, IntRange> private fun String.toIntRange(): IntRange = split("-").map { it.toInt() }.let { it[0]..it[1] } // anonymous function private val hasCompleteOverlap = fun(assignments: Assignments): Boolean { with(assignments) { return first.subtract(second).isEmpty() || second.subtract(first).isEmpty() } } // lambda private val hasOverlap = { assignments: Assignments -> assignments.first.intersect(assignments.second).isNotEmpty() } class Day04 { fun parse(input: String): List<Assignments> = input .lines() .map { line -> line.split(",") } .map { (first, second) -> Assignments( first = first.toIntRange(), second = second.toIntRange() ) } fun part1(parsed: List<Assignments>): Int = parsed.count(hasCompleteOverlap) fun part2(parsed: List<Assignments>): Int = parsed.count(hasOverlap) }
[ { "class_path": "Malo-T__AoC-2022__f4edefa/day04/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class day04.Day04Kt {\n private static final kotlin.jvm.functions.Function1<kotlin.Pair<kotlin.ranges.IntRange, kotlin.ranges.IntRange>, java.lang.Boolean> hasCompleteOverlap;\n\n private st...
Malo-T__AoC-2022__f4edefa/src/main/kotlin/day03/Day03.kt
package day03 private val itemPriorities: Map<Char, Int> = (('a'..'z') + ('A'..'Z')).mapIndexed { i, c -> c to i + 1 }.toMap() private typealias RuckSack = Pair<Set<Char>, Set<Char>> class Day03 { fun parse(input: String): List<RuckSack> = input.lines().map { line -> RuckSack( first = line.substring(0, line.length / 2).toSet(), second = line.substring(line.length / 2).toSet() ) } fun part1(parsed: List<RuckSack>): Int = parsed.map { (first, second) -> first.intersect(second).first() } .sumOf { itemPriorities[it]!! } fun part2(parsed: List<RuckSack>): Int = parsed.map { it.first + it.second } .windowed(size = 3, step = 3) { (first, second, third) -> first.intersect(second).intersect(third).first() } .sumOf { itemPriorities[it]!! } }
[ { "class_path": "Malo-T__AoC-2022__f4edefa/day03/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class day03.Day03Kt {\n private static final java.util.Map<java.lang.Character, java.lang.Integer> itemPriorities;\n\n public static final java.util.Map access$getItemPriorities$p();\n Co...
Malo-T__AoC-2022__f4edefa/src/main/kotlin/day02/Day02.kt
package day02 class Day02 { enum class Play(val points: Int) { ROCK(1) { override fun scoreAgainst(other: Play) = when (other) { ROCK -> Result.DRAW PAPER -> Result.LOSS SCISSORS -> Result.WIN }.points + points }, PAPER(2) { override fun scoreAgainst(other: Play) = when (other) { ROCK -> Result.WIN PAPER -> Result.DRAW SCISSORS -> Result.LOSS }.points + points }, SCISSORS(3) { override fun scoreAgainst(other: Play) = when (other) { ROCK -> Result.LOSS PAPER -> Result.WIN SCISSORS -> Result.DRAW }.points + points }; abstract fun scoreAgainst(other: Play): Int } enum class Result(val points: Int) { LOSS(0), DRAW(3), WIN(6) } enum class OpponentPlay(val play: Play) { A(Play.ROCK), B(Play.PAPER), C(Play.SCISSORS) } enum class ResponsePlay(val play: Play) { X(Play.ROCK), Y(Play.PAPER), Z(Play.SCISSORS) } enum class ExpectedResult(val result: Result) { X(Result.LOSS) { override fun expectedResponse(opponentPlay: Play) = when (opponentPlay) { Play.ROCK -> Play.SCISSORS Play.PAPER -> Play.ROCK Play.SCISSORS -> Play.PAPER } }, Y(Result.DRAW) { override fun expectedResponse(opponentPlay: Play) = opponentPlay }, Z(Result.WIN) { override fun expectedResponse(opponentPlay: Play) = when (opponentPlay) { Play.ROCK -> Play.PAPER Play.PAPER -> Play.SCISSORS Play.SCISSORS -> Play.ROCK } }; abstract fun expectedResponse(opponentPlay: Play): Play } fun parse1(input: String): List<Pair<OpponentPlay, ResponsePlay>> = input.split("\n") .map { it.split(" ") .let { pair -> OpponentPlay.valueOf(pair[0]) to ResponsePlay.valueOf(pair[1]) } } fun part1(parsed: List<Pair<OpponentPlay, ResponsePlay>>): Int = parsed.sumOf { (opponent, response) -> response.play.scoreAgainst(opponent.play) } fun parse2(input: String): List<Pair<OpponentPlay, ExpectedResult>> = input.split("\n") .map { it.split(" ") .let { pair -> OpponentPlay.valueOf(pair[0]) to ExpectedResult.valueOf(pair[1]) } } fun part2(parsed: List<Pair<OpponentPlay, ExpectedResult>>): Int = parsed.sumOf { (opponent, expectedResult) -> expectedResult.expectedResponse(opponent.play).scoreAgainst(opponent.play) } }
[ { "class_path": "Malo-T__AoC-2022__f4edefa/day02/Day02$Play.class", "javap": "Compiled from \"Day02.kt\"\npublic abstract class day02.Day02$Play extends java.lang.Enum<day02.Day02$Play> {\n private final int points;\n\n public static final day02.Day02$Play ROCK;\n\n public static final day02.Day02$Play P...
Malo-T__AoC-2022__f4edefa/src/main/kotlin/day05/Day05.kt
package day05 import day05.Day05.Step private typealias Stack = MutableList<Char> private typealias Storage = MutableList<Stack> private const val EMPTY = ' ' private fun List<String>.indexOfStackNumbers() = indexOfFirst { it.startsWith(" 1") } private val stepRegex = """move (\d+) from (\d+) to (\d+)""".toRegex() private fun String.toStep() = stepRegex.find(this)!!.groupValues.let { (_, amount, from, to) -> Step( amount = amount.toInt(), from = from.toInt(), to = to.toInt() ) } // CrateMover 9000 moves one by one private fun Storage.move(step: Step) { (0 until step.amount).forEach { _ -> this[step.toIndex].add(this[step.fromIndex].last()) this[step.fromIndex].removeLast() } } // CrateMover 9001 moves by batch private fun Storage.moveV2(step: Step) { this[step.toIndex].addAll(this[step.fromIndex].takeLast(step.amount)) this[step.fromIndex] = this[step.fromIndex].dropLast(step.amount).toMutableList() } class Day05 { data class Step( val amount: Int, val from: Int, val to: Int, ) { val fromIndex: Int get() = from - 1 val toIndex: Int get() = to - 1 } fun parse(input: String): Pair<Storage, List<Step>> { val storage: Storage = input .lines() .let { lines -> lines.subList(0, lines.indexOfStackNumbers()) } .map { row -> row.chunked(4).map { it[1] } } // transform rows to columns (stacks) .let { rows -> rows.fold( initial = List(rows.first().size) { mutableListOf<Char>() }, operation = { columns, row -> columns.apply { forEachIndexed { columnIndex, column -> // remove empty values if (row[columnIndex] != EMPTY) { column.add(row[columnIndex]) } } } } ).map { it.reversed().toMutableList() } // bottom to top of the stack }.toMutableList() .onEach { println(it) } val steps = input .lines() .let { lines -> lines.subList(lines.indexOfStackNumbers() + 2, lines.size) } .map { it.toStep() } .onEach { println(it) } return storage to steps } fun part1(parsed: Pair<Storage, List<Step>>): String { val (storage, steps) = parsed steps.forEach { step -> storage.move(step) } return storage.joinToString(separator = "") { stack -> "${stack.last()}" } } fun part2(parsed: Pair<Storage, List<Step>>): String { val (storage, steps) = parsed steps.forEach { step -> storage.moveV2(step) } return storage.joinToString(separator = "") { stack -> "${stack.last()}" } } }
[ { "class_path": "Malo-T__AoC-2022__f4edefa/day05/Day05Kt.class", "javap": "Compiled from \"Day05.kt\"\npublic final class day05.Day05Kt {\n private static final char EMPTY;\n\n private static final kotlin.text.Regex stepRegex;\n\n private static final int indexOfStackNumbers(java.util.List<java.lang.Stri...
mikhalchenko-alexander__advent-of-kotlin-2018-week1__c483ade/src/main/kotlin/com/anahoret/pathfinding/MarkingWayOnMap.kt
package com.anahoret.pathfinding import java.lang.IllegalArgumentException import java.util.* fun addPath(map: String): String = Graph.getMapWithPath(map) object Graph { private const val STRAIGHT_LENGTH = 2 private const val DIAGONAL_LENGTH = 3 fun getMapWithPath(map: String): String { val (nodes, arcs) = readGraph(map) val start = nodes.find { it.isStart } ?: throw IllegalArgumentException("No start point specified") val end = nodes.find { it.isEnd } ?: throw IllegalArgumentException("No end point specified") val paths = calcDistances(start, nodes, arcs) return map.lines() .map(String::toCharArray) .let { charGrid -> charGrid[start.row][start.col] = '*' paths.getValue(end).forEach { charGrid[it.row][it.col] = '*' } charGrid.joinToString(separator = "\n") { row -> row.joinToString(separator = "") } } } private fun calcDistances(start: Node, nodes: Collection<Node>, arcs: Map<Node, List<Arc>>): Map<Node, List<Node>> { val paths = nodes.map { it to emptyList<Node>() }.toMap().toMutableMap() val distances = nodes.map { it to if (it == start) 0 else Int.MAX_VALUE }.toMap().toMutableMap() val visited = mutableSetOf<Node>() val queue = PriorityQueue<Node>(nodes.size) { n1, n2 -> distances.getValue(n1) - distances.getValue(n2) } queue.addAll(nodes) while (queue.isNotEmpty()) { val node = queue.poll() visited.add(node) arcs.getValue(node) .filterNot { visited.contains(it.node) } .forEach { arc -> if (distances.getValue(node) + arc.length < distances.getValue(arc.node)) { distances[arc.node] = distances.getValue(node) + arc.length paths[arc.node] = paths.getValue(node) + arc.node queue.remove(arc.node) queue.add(arc.node) } } } return paths.toMap() } private fun readGraph(map: String): Pair<List<Node>, Map<Node, List<Arc>>> { val nodes = map.lines() .mapIndexed { row, str -> str.mapIndexedNotNull { col, char -> if (char == 'B') null else Node(row, col, char) } } .flatten() val arcs = nodes.map { node -> val row = nodes.filter { it.row == node.row } val topRow = nodes.filter { it.row == node.row - 1 } val bottomRow = nodes.filter { it.row == node.row + 1 } val nodeArcs = listOfNotNull( topRow.find { it.col == node.col }?.let { Arc(it, STRAIGHT_LENGTH) }, topRow.find { it.col == node.col - 1 }?.let { Arc(it, DIAGONAL_LENGTH) }, topRow.find { it.col == node.col + 1 }?.let { Arc(it, DIAGONAL_LENGTH) }, bottomRow.find { it.col == node.col }?.let { Arc(it, STRAIGHT_LENGTH) }, bottomRow.find { it.col == node.col - 1 }?.let { Arc(it, DIAGONAL_LENGTH) }, bottomRow.find { it.col == node.col + 1 }?.let { Arc(it, DIAGONAL_LENGTH) }, row.find { it.col == node.col - 1 }?.let { Arc(it, STRAIGHT_LENGTH) }, row.find { it.col == node.col + 1 }?.let { Arc(it, STRAIGHT_LENGTH) } ) node to nodeArcs }.toMap() return Pair(nodes, arcs) } class Node(val row: Int, val col: Int, char: Char) { val isStart = char == 'S' val isEnd = char == 'X' override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Node) return false if (row != other.row) return false if (col != other.col) return false return true } override fun hashCode(): Int { var result = row result = 31 * result + col return result } } class Arc(val node: Node, val length: Int) }
[ { "class_path": "mikhalchenko-alexander__advent-of-kotlin-2018-week1__c483ade/com/anahoret/pathfinding/MarkingWayOnMapKt.class", "javap": "Compiled from \"MarkingWayOnMap.kt\"\npublic final class com.anahoret.pathfinding.MarkingWayOnMapKt {\n public static final java.lang.String addPath(java.lang.String);\...
ani03sha__RedQuarkTutorials__67b6eba/ConceptOfTheDay/Kotlin/src/main/java/org/redquark/conceptoftheday/AnagramSubstringSearch.kt
package org.redquark.conceptoftheday /** * @author <NAME> * * We are given two strings "text" and "pattern" of size n and m respectively where m < n. * Find all the indices in text where anagrams of pattern are found. */ private fun findIndices(text: String, pattern: String): List<Int> { // Lengths of strings val n = text.length val m = pattern.length // List that will store the indices val indices: MutableList<Int> = ArrayList() // Frequency arrays - assuming we have a set of 256 characters val textCount = IntArray(256) val patternCount = IntArray(256) // Loop until m for (i in 0 until m) { textCount[text[i].toInt()]++ patternCount[pattern[i].toInt()]++ } // At this point, we have traversed m characters in both the arrays. // Now we will loop through the remaining characters for (i in m until n) { // Check if the counts of characters in frequency arrays are equal or not if (isCountEqual(textCount, patternCount)) { indices.add(i - m) } // Discard left most character textCount[text[i - m].toInt()]-- // Include current character textCount[text[i].toInt()]++ } // Check for the last window if (isCountEqual(textCount, patternCount)) { indices.add(n - m) } return indices } private fun isCountEqual(textCount: IntArray, patternCount: IntArray): Boolean { for (i in 0..255) { if (textCount[i] != patternCount[i]) { return false } } return true } fun main() { var text = "BACDGABCDA" var pattern = "ABCD" println("Anagrams are found at: " + findIndices(text, pattern)) text = "XYYZXZYZXXYZ" pattern = "XYZ" println("Anagrams are found at: " + findIndices(text, pattern)) }
[ { "class_path": "ani03sha__RedQuarkTutorials__67b6eba/org/redquark/conceptoftheday/AnagramSubstringSearchKt.class", "javap": "Compiled from \"AnagramSubstringSearch.kt\"\npublic final class org.redquark.conceptoftheday.AnagramSubstringSearchKt {\n private static final java.util.List<java.lang.Integer> find...
ani03sha__RedQuarkTutorials__67b6eba/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/SubstringWithConcatenationOfAllWords.kt
package org.redquark.tutorials.leetcode class SubstringWithConcatenationOfAllWords { fun findSubstring(s: String, words: Array<String>): List<Int> { // Resultant list val indices: MutableList<Int> = ArrayList() // Base conditions if (s.isEmpty() || words.isEmpty()) { return indices } // Store the words and their counts in a hash map val wordCount: MutableMap<String, Int> = HashMap() for (word in words) { wordCount[word] = wordCount.getOrDefault(word, 0) + 1 } // Length of each word in the words array val wordLength = words[0].length // Length of all the words combined in the array val wordArrayLength = wordLength * words.size // Loop for the entire string for (i in 0..s.length - wordArrayLength) { // Get the substring of length equal to wordArrayLength val current = s.substring(i, i + wordArrayLength) // Map to store each word of the substring val wordMap: MutableMap<String, Int> = HashMap() // Index to loop through the words array var index = 0 // Index to get each word in the current var j = 0 // Loop through each word of the words array while (index < words.size) { // Divide the current string into strings of length of // each word in the array val part = current.substring(j, j + wordLength) // Put this string into the wordMap wordMap[part] = wordMap.getOrDefault(part, 0) + 1 // Update j and index j += wordLength index++ } // At this point compare the maps if (wordCount == wordMap) { indices.add(i) } } return indices } } fun main() { val sObject = SubstringWithConcatenationOfAllWords() var s = "barfoothefoobarman" var words = arrayOf("foo", "bar") println(sObject.findSubstring(s, words)) s = "wordgoodgoodgoodbestword" words = arrayOf("word", "good", "best", "word") println(sObject.findSubstring(s, words)) s = "barfoofoobarthefoobarman" words = arrayOf("bar", "foo", "the") println(sObject.findSubstring(s, words)) s = "wordgoodgoodgoodbestword" words = arrayOf("word", "good", "best", "good") println(sObject.findSubstring(s, words)) }
[ { "class_path": "ani03sha__RedQuarkTutorials__67b6eba/org/redquark/tutorials/leetcode/SubstringWithConcatenationOfAllWords.class", "javap": "Compiled from \"SubstringWithConcatenationOfAllWords.kt\"\npublic final class org.redquark.tutorials.leetcode.SubstringWithConcatenationOfAllWords {\n public org.redq...
ani03sha__RedQuarkTutorials__67b6eba/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/LetterCombinationsOfAPhoneNumber.kt
package org.redquark.tutorials.leetcode fun letterCombinations(digits: String): List<String> { // Resultant list val combinations: MutableList<String> = mutableListOf() // Base condition if (digits.isEmpty()) { return combinations } // Mappings of letters and numbers val lettersAndNumbersMappings = arrayOf( "Anirudh", "is awesome", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" ) findCombinations(combinations, digits, StringBuilder(), 0, lettersAndNumbersMappings) return combinations } fun findCombinations(combinations: MutableList<String>, digits: String, previous: StringBuilder, index: Int, lettersAndNumbersMappings: Array<String>) { // Base condition for recursion to stop if (index == digits.length) { combinations.add(previous.toString()) return } // Get the letters corresponding to the current index of digits string val letters = lettersAndNumbersMappings[digits[index] - '0'] // Loop through all the characters in the current combination of letters for (c in letters.toCharArray()) { findCombinations(combinations, digits, previous.append(c), index + 1, lettersAndNumbersMappings) previous.deleteCharAt(previous.length - 1) } } fun main() { println(letterCombinations("23")) println(letterCombinations("")) println(letterCombinations("2")) }
[ { "class_path": "ani03sha__RedQuarkTutorials__67b6eba/org/redquark/tutorials/leetcode/LetterCombinationsOfAPhoneNumberKt.class", "javap": "Compiled from \"LetterCombinationsOfAPhoneNumber.kt\"\npublic final class org.redquark.tutorials.leetcode.LetterCombinationsOfAPhoneNumberKt {\n public static final jav...
ani03sha__RedQuarkTutorials__67b6eba/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/MergeKSortedLists.kt
package org.redquark.tutorials.leetcode class MergeKSortedLists { internal fun mergeKLists(lists: Array<ListNode?>): ListNode? { // Base condition return if (lists.isEmpty()) { null } else mergeKLists(lists, 0, lists.size - 1) } private fun mergeKLists(lists: Array<ListNode?>, start: Int, end: Int): ListNode? { if (start == end) { return lists[start] } // Mid of list of lists val mid = start + (end - start) / 2 // Recursive call for left sublist val left = mergeKLists(lists, start, mid) // Recursive call for right sublist val right = mergeKLists(lists, mid + 1, end) // Merge the left and right sublist return merge(left, right) } private fun merge(left: ListNode?, right: ListNode?): ListNode? { // Create a dummy node var leftNode = left var rightNode = right val head = ListNode(-1) // Temp node var temp: ListNode? = head // Loop until any of the list becomes null while (leftNode != null && rightNode != null) { // Choose the value from the left and right which is smaller if (leftNode.`val` < rightNode.`val`) { temp!!.next = leftNode leftNode = leftNode.next } else { temp!!.next = rightNode rightNode = rightNode.next } temp = temp.next } // Take all nodes from left list if remaining while (leftNode != null) { temp!!.next = leftNode leftNode = leftNode.next temp = temp.next } // Take all nodes from right list if remaining while (rightNode != null) { temp!!.next = rightNode rightNode = rightNode.next temp = temp.next } return head.next } internal class ListNode(val `val`: Int) { var next: ListNode? = null } } fun main() { val m = MergeKSortedLists() val head1 = MergeKSortedLists.ListNode(1) head1.next = MergeKSortedLists.ListNode(4) head1.next!!.next = MergeKSortedLists.ListNode(5) val head2 = MergeKSortedLists.ListNode(1) head2.next = MergeKSortedLists.ListNode(3) head2.next!!.next = MergeKSortedLists.ListNode(4) val head3 = MergeKSortedLists.ListNode(2) head3.next = MergeKSortedLists.ListNode(6) var result = m.mergeKLists(arrayOf(head1, head2, head3)) while (result != null) { print(result.`val`.toString() + " ") result = result.next } }
[ { "class_path": "ani03sha__RedQuarkTutorials__67b6eba/org/redquark/tutorials/leetcode/MergeKSortedLists$ListNode.class", "javap": "Compiled from \"MergeKSortedLists.kt\"\npublic final class org.redquark.tutorials.leetcode.MergeKSortedLists$ListNode {\n private final int val;\n\n private org.redquark.tutor...
ani03sha__RedQuarkTutorials__67b6eba/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/FourSum.kt
package org.redquark.tutorials.leetcode import java.util.* import kotlin.collections.ArrayList fun fourSum(nums: IntArray, target: Int): List<List<Int>> { // Resultant list val quadruplets: MutableList<List<Int>> = ArrayList() // Base condition if (nums.size < 4) { return quadruplets } // Sort the array Arrays.sort(nums) // Length of the array val n = nums.size // Loop for each element in the array for (i in 0 until n - 3) { // Check for skipping duplicates if (i > 0 && nums[i] == nums[i - 1]) { continue } // Reducing problem to 3Sum problem for (j in i + 1 until n - 2) { // Check for skipping duplicates if (j != i + 1 && nums[j] == nums[j - 1]) { continue } // Left and right pointers var k = j + 1 var l = n - 1 // Reducing to two sum problem while (k < l) { val currentSum = nums[i] + nums[j] + nums[k] + nums[l] when { currentSum < target -> { k++ } currentSum > target -> { l-- } else -> { quadruplets.add(listOf(nums[i], nums[j], nums[k], nums[l])) k++ l-- // Check for skipping duplicates while (k < l && nums[k] == nums[k - 1]) { k++ } while (k < l && nums[l] == nums[l + 1]) { l-- } } } } } } return quadruplets } fun main() { println(fourSum(intArrayOf(1, 0, -1, 0, -2, 2), 0)) println(fourSum(intArrayOf(), 0)) println(fourSum(intArrayOf(1, 2, 3, 4), 10)) println(fourSum(intArrayOf(0, 0, 0, 0), 0)) }
[ { "class_path": "ani03sha__RedQuarkTutorials__67b6eba/org/redquark/tutorials/leetcode/FourSumKt.class", "javap": "Compiled from \"FourSum.kt\"\npublic final class org.redquark.tutorials.leetcode.FourSumKt {\n public static final java.util.List<java.util.List<java.lang.Integer>> fourSum(int[], int);\n Co...
ani03sha__RedQuarkTutorials__67b6eba/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/MedianOfTwoSortedArrays.kt
package org.redquark.tutorials.leetcode fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { // Check if num1 is smaller than num2 // If not, then we will swap num1 with num2 if (nums1.size > nums2.size) { return findMedianSortedArrays(nums2, nums1) } // Lengths of two arrays val m = nums1.size val n = nums2.size // Pointers for binary search var start = 0 var end = m // Binary search starts from here while (start <= end) { // Partitions of both the array val partitionNums1 = (start + end) / 2 val partitionNums2 = (m + n + 1) / 2 - partitionNums1 // Edge cases // If there are no elements left on the left side after partition val maxLeftNums1 = if (partitionNums1 == 0) Int.MIN_VALUE else nums1[partitionNums1 - 1] // If there are no elements left on the right side after partition val minRightNums1 = if (partitionNums1 == m) Int.MAX_VALUE else nums1[partitionNums1] // Similarly for nums2 val maxLeftNums2 = if (partitionNums2 == 0) Int.MIN_VALUE else nums2[partitionNums2 - 1] val minRightNums2 = if (partitionNums2 == n) Int.MAX_VALUE else nums2[partitionNums2] // Check if we have found the match if (maxLeftNums1 <= minRightNums2 && maxLeftNums2 <= minRightNums1) { // Check if the combined array is of even/odd length return if ((m + n) % 2 == 0) { (maxLeftNums1.coerceAtLeast(maxLeftNums2) + minRightNums1.coerceAtMost(minRightNums2)) / 2.0 } else { maxLeftNums1.coerceAtLeast(maxLeftNums2).toDouble() } } else if (maxLeftNums1 > minRightNums2) { end = partitionNums1 - 1 } else { start = partitionNums1 + 1 } } throw IllegalArgumentException() } fun main() { var nums1 = intArrayOf(1, 3) var nums2 = intArrayOf(2) println(findMedianSortedArrays(nums1, nums2)) nums1 = intArrayOf(1, 2) nums2 = intArrayOf(3, 4) println(findMedianSortedArrays(nums1, nums2)) nums1 = intArrayOf(0, 0) nums2 = intArrayOf(0, 0) println(findMedianSortedArrays(nums1, nums2)) nums1 = intArrayOf() nums2 = intArrayOf(1) println(findMedianSortedArrays(nums1, nums2)) nums1 = intArrayOf(2) nums2 = intArrayOf() println(findMedianSortedArrays(nums1, nums2)) }
[ { "class_path": "ani03sha__RedQuarkTutorials__67b6eba/org/redquark/tutorials/leetcode/MedianOfTwoSortedArraysKt.class", "javap": "Compiled from \"MedianOfTwoSortedArrays.kt\"\npublic final class org.redquark.tutorials.leetcode.MedianOfTwoSortedArraysKt {\n public static final double findMedianSortedArrays(...
ani03sha__RedQuarkTutorials__67b6eba/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/RegularExpressionMatching.kt
package org.redquark.tutorials.leetcode fun isMatch(s: String, p: String): Boolean { val rows = s.length val columns = p.length /// Base conditions if (rows == 0 && columns == 0) { return true } if (columns == 0) { return false } // DP array val dp = Array(rows + 1) { BooleanArray(columns + 1) } // Empty string and empty pattern are a match dp[0][0] = true // Deals with patterns with * for (i in 2 until columns + 1) { if (p[i - 1] == '*') { dp[0][i] = dp[0][i - 2] } } // For remaining characters for (i in 1 until rows + 1) { for (j in 1 until columns + 1) { if (s[i - 1] == p[j - 1] || p[j - 1] == '.') { dp[i][j] = dp[i - 1][j - 1] } else if (j > 1 && p[j - 1] == '*') { dp[i][j] = dp[i][j - 2] if (p[j - 2] == '.' || p[j - 2] == s[i - 1]) { dp[i][j] = dp[i][j] or dp[i - 1][j] } } } } return dp[rows][columns] } fun main() { println(isMatch("aa", "a")) println(isMatch("aa", "a*")) println(isMatch("ab", ".")) println(isMatch("aab", "c*a*b")) println(isMatch("mississippi", "mis*is*p*.")) println(isMatch("", ".*")) }
[ { "class_path": "ani03sha__RedQuarkTutorials__67b6eba/org/redquark/tutorials/leetcode/RegularExpressionMatchingKt.class", "javap": "Compiled from \"RegularExpressionMatching.kt\"\npublic final class org.redquark.tutorials.leetcode.RegularExpressionMatchingKt {\n public static final boolean isMatch(java.lan...
ani03sha__RedQuarkTutorials__67b6eba/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/LongestPalindromeSubstring.kt
package org.redquark.tutorials.leetcode fun longestPalindrome(s: String): String { // Update the string to put hash "#" at the beginning, end and in between each character val updatedString = getUpdatedString(s) // Length of the array that will store the window of palindromic substring val length = 2 * s.length + 1 // Array to store the length of each palindrome centered at each element val p = IntArray(length) // Current center of the longest palindromic string var c = 0 // Right boundary of the longest palindromic string var r = 0 // Maximum length of the substring var maxLength = 0 // Position index var position = -1 for (i in 0 until length) { // Mirror of the current index val mirror = 2 * c - i // Check if the mirror is outside the left boundary of current longest palindrome if (i < r) { p[i] = (r - i).coerceAtMost(p[mirror]) } // Indices of the characters to be compared var a = i + (1 + p[i]) var b = i - (1 + p[i]) // Expand the window while (a < length && b >= 0 && updatedString[a] == updatedString[b]) { p[i]++ a++ b-- } // If the expanded palindrome is expanding beyond the right boundary of // the current longest palindrome, then update c and r if (i + p[i] > r) { c = i r = i + p[i] } if (maxLength < p[i]) { maxLength = p[i] position = i } } val offset = p[position] val result = StringBuilder() for (i in position - offset + 1 until position + offset) { if (updatedString[i] != '#') { result.append(updatedString[i]) } } return result.toString() } fun getUpdatedString(s: String): String { val sb = StringBuilder() for (element in s) { sb.append("#").append(element) } sb.append("#") return sb.toString() } fun main() { println(longestPalindrome("babad")) println(longestPalindrome("cbbd")) println(longestPalindrome("a")) println(longestPalindrome("ac")) println(longestPalindrome("abb")) }
[ { "class_path": "ani03sha__RedQuarkTutorials__67b6eba/org/redquark/tutorials/leetcode/LongestPalindromeSubstringKt.class", "javap": "Compiled from \"LongestPalindromeSubstring.kt\"\npublic final class org.redquark.tutorials.leetcode.LongestPalindromeSubstringKt {\n public static final java.lang.String long...