path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/dev/claudio/adventofcode2021/Day9Part2.kt
ClaudioConsolmagno
434,559,159
false
{"Kotlin": 78336}
package dev.claudio.adventofcode2021 fun main() { Day9Part2().main() } private class Day9Part2 { fun main() { val input: List<String> = Support.readFileAsListString("day9-input.txt") val xSize = input[0].length val input2: MutableList<String> = mutableListOf() input2.add("9".repeat(xSize)) input2.addAll(input) input2.add("9".repeat(xSize)) val map: List<List<Int>> = input2 .map { "9" + it + "9" } .map { it.toCharArray().map { it2 -> it2.titlecase().toInt() } } val basins: MutableList<Pair<Int, Int>> = mutableListOf() (1 until map.size-1).forEach { x -> (1 until map[x].size-1).forEach { y -> val candidate = map[x][y] val neighbours = listOf(map[x-1][y-1],map[x-1][y-0],map[x-1][y+1], map[x-0][y-1],map[x-0][y+1], map[x+1][y-1],map[x+1][y-0],map[x+1][y+1],) if (neighbours.all { candidate < it }) { basins.add(Pair(x, y)) } } } println(basins) basins.map{ pair -> var basinSize = 1 var excluded: MutableSet<Pair<Int, Int>> = basins.toMutableSet() var neighbours: MutableSet<Pair<Int, Int>> = getNon9Neighbours(map, pair, excluded) while(neighbours.isNotEmpty()) { basinSize += neighbours.size excluded.addAll(neighbours) neighbours = neighbours.flatMap { getNon9Neighbours(map, it, excluded) }.toMutableSet() } basinSize }.sortedDescending().take(3).reduce(Int::times).let { println(it) } } private fun getNon9Neighbours( map: List<List<Int>>, pair: Pair<Int, Int>, excluded: MutableSet<Pair<Int, Int>>, ): MutableSet<Pair<Int, Int>> { val neighbours: MutableSet<Pair<Int, Int>> = mutableSetOf() (-1 .. 1).forEach { x -> (-1 .. 1).forEach { y -> if (x != y && x == 0 || y == 0) { val candidate = map[pair.first + x][pair.second +y] val candidatePair = Pair(pair.first + x, pair.second +y) if (candidate < 9 && candidatePair !in excluded) { neighbours.add(candidatePair) } } } } return neighbours } }
0
Kotlin
0
0
5f1aff1887ad0a7e5a3af9aca7793f1c719e7f1c
2,444
adventofcode-2021
Apache License 2.0
Day22/src/Shuffle.kt
gautemo
225,219,298
false
null
import java.io.File import java.math.BigInteger import kotlin.math.absoluteValue fun main(){ val commands = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText().trim() val deck = Deck(10007) deck.shuffle(commands) println(deck.cards.indexOf(2019)) solvePart2(commands) } class Deck(size: Int){ val cards = (0 until size).toMutableList() fun shuffle(commands: String) { for(c in commands.lines()){ when{ c == "deal into new stack" -> dealIntoNewStack() c.contains("cut") -> cut(c.split(' ')[1].toInt()) c.contains("increment") -> dealWithIncrement(c.split(' ').last().toInt()) } } } private fun dealIntoNewStack(){ cards.reverse() } private fun cut(n: Int){ if(n < 0){ val move = cards.takeLast(n.absoluteValue) cards.removeAll(move) cards.addAll(0, move) }else { val move = cards.take(n) cards.removeAll(move) cards.addAll(move) } } private fun dealWithIncrement(n: Int){ val copy = cards.toList() copy.forEachIndexed { index, card -> val placeAt = (index * n) % cards.size cards[placeAt] = card } } } fun solvePart2(commands: String){ val size = 119315717514047.toBigInteger() val iterations = 101741582076661.toBigInteger() val checkPos = 2020 var increment = 1.toBigInteger() var offsetDifference = 0.toBigInteger() for(c in commands.lines()){ val pair = p2(increment, offsetDifference, size, c) increment = pair.first offsetDifference = pair.second } val pair = getSeq(iterations, increment, offsetDifference, size) increment = pair.first offsetDifference = pair.second val card = getCard(increment, offsetDifference, checkPos, size) println(card) } fun getCard(increment: BigInteger, offsetDifference: BigInteger, checkPos: Int, size: BigInteger) = (offsetDifference + checkPos.toBigInteger() * increment) % size fun p2(increment: BigInteger, offsetDifference: BigInteger, size: BigInteger, c: String): Pair<BigInteger, BigInteger> { var offset = offsetDifference var inc = increment when{ c == "deal into new stack" -> { inc *= (-1).toBigInteger(); offset += inc } c.contains("cut") -> offset += c.split(' ')[1].toBigInteger() * increment c.contains("increment") -> inc *= c.split(' ').last().toBigInteger().modInverse(size) } return Pair(inc % size, offset % size) } fun getSeq(iterations: BigInteger, increment: BigInteger, offsetDifference: BigInteger, size: BigInteger): Pair<BigInteger, BigInteger>{ val inc = increment.modPow(iterations, size) var offset = offsetDifference * ( 1.toBigInteger() - inc) * ((1.toBigInteger() - increment) % size).modInverse(size) offset %= size return Pair(inc, offset) }
0
Kotlin
0
0
f8ac96e7b8af13202f9233bb5a736d72261c3a3b
3,001
AdventOfCode2019
MIT License
src/day02/Day02.kt
Sardorbekcyber
573,890,266
false
{"Kotlin": 6613}
package day02 import java.io.File fun main() { fun part1(input: String) : Long { val lostSet = setOf("A Z", "B X", "C Y") val winSet = setOf("A Y", "B Z", "C X") val drawSet = setOf("A X", "B Y", "C Z") val scoreMap = mapOf('X' to 1, 'Y' to 2, 'Z' to 3) val data = input.split("\n").sumOf { val gameScore = when(it){ in lostSet -> 0L in drawSet -> 3L in winSet -> 6L else -> throw IllegalArgumentException() } gameScore + scoreMap.getOrDefault(it.last(), 0) } return data } fun part2(input: String) : Long { val winSet = setOf("A B", "B C", "C A") val lostSet = setOf("A C", "B A", "C B") val drawSet = setOf("A A", "B B", "C C") val scoreMap = mapOf('A' to 1, 'B' to 2, 'C' to 3) val data = input.split("\n").sumOf { game -> val (gameScore, myScore) = when(game.last()){ 'X' -> 0L to scoreMap.getOrDefault(lostSet.first { it.first() == game.first() }.last(), 0) 'Y' -> 3L to scoreMap.getOrDefault(drawSet.first { it.first() == game.first() }.last(), 0) 'Z' -> 6L to scoreMap.getOrDefault(winSet.first { it.first() == game.first() }.last(), 0) else -> throw IllegalArgumentException() } gameScore + myScore } return data } val testInput = File("src/day02/Day02_test.txt").readText() println(part2(testInput)) check(part2(testInput) == 12L) val input = File("src/day02/Day02.txt").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
56f29c8322663720bc83e7b1c6b0a362de292b12
1,699
aoc-2022-in-kotlin
Apache License 2.0
y2017/src/main/kotlin/adventofcode/y2017/Day11.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution import kotlin.math.abs object Day11 : AdventSolution(2017, 11, "Hex Ed") { override fun solvePartOne(input: String) = input.split(",") .mapNotNull { coordinatesForDirection[it] } .reduce { a, b -> a + b } .distance .toString() override fun solvePartTwo(input: String) = input.split(",") .mapNotNull { coordinatesForDirection[it] } .scan(HexCoordinates(0, 0, 0)) { a, b -> a + b } .map { it.distance } .maxOrNull() .toString() } //Cubic coordinates for hex grid. See https://www.redblobgames.com/grids/hexagons/ private data class HexCoordinates(private val x: Int, private val y: Int, private val z: Int) { infix operator fun plus(o: HexCoordinates) = HexCoordinates(x + o.x, y + o.y, z + o.z) val distance get() = listOf(x, y, z).maxOf(::abs) } private val coordinatesForDirection = mapOf( "n" to HexCoordinates(0, 1, -1), "s" to HexCoordinates(0, -1, 1), "ne" to HexCoordinates(1, 0, -1), "sw" to HexCoordinates(-1, 0, 1), "se" to HexCoordinates(1, -1, 0), "nw" to HexCoordinates(-1, 1, 0) ) //Analogous to the Rx scan operator. A fold that returns each intermediate value. private fun <T, R> Iterable<T>.scan(initial: R, operation: (R, T) -> R): List<R> { var result: R = initial return this.map { result = operation(result, it) result } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,420
advent-of-code
MIT License
src/Day04.kt
yalematta
572,668,122
false
{"Kotlin": 8442}
fun main() { fun parseInput(input: List<String>): List<List<Set<Int>>> { return input.map { line -> line.split(",") .map { section -> section.split("-") .map { it.toInt() }.let { (a, b) -> (a..b).toSet() } } } } fun part1(input: List<String>): Int { return parseInput(input).count { (a, b) -> a.containsAll(b) || b.containsAll(a) } } fun part2(input: List<String>): Int { return parseInput(input).count { (a, b) -> a.intersect(b).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2b43681cc2bd02e4838b7ad1ba04ff73c0422a73
1,009
advent-of-code-2022
Apache License 2.0
year2021/day10/part2/src/main/kotlin/com/curtislb/adventofcode/year2021/day10/part2/Year2021Day10Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- Now, discard the corrupted lines. The remaining lines are incomplete. Incomplete lines don't have any incorrect characters - instead, they're missing some closing characters at the end of the line. To repair the navigation subsystem, you just need to figure out the sequence of closing characters that complete all open chunks in the line. You can only use closing characters (`)`, `]`, `}`, or `>`), and you must add them in the correct order so that only legal pairs are formed and all chunks end up closed. In the example above, there are five incomplete lines: ``` [({(<(())[]>[[{[]{<()<>> - Complete by adding }}]])})]. [(()[<>])]({[<{<<[]>>( - Complete by adding )}>]}). (((({<>}<{<{<>}{[]{[]{} - Complete by adding }}>}>)))). {<[[]]>}<{[{[{[]{()[[[] - Complete by adding ]]}}]}]}>. <{([{{}}[<[[[<>{}]]]>[]] - Complete by adding ])}>. ``` Did you know that autocomplete tools also have contests? It's true! The score is determined by considering the completion string character-by-character. Start with a total score of 0. Then, for each character, multiply the total score by 5 and then increase the total score by the point value given for the character in the following table: - `)`: 1 point. - `]`: 2 points. - `}`: 3 points. - `>`: 4 points. So, the last completion string above - ])}> - would be scored as follows: - Start with a total score of 0. - Multiply the total score by 5 to get 0, then add the value of `]` (2) to get a new total score of 2. - Multiply the total score by 5 to get 10, then add the value of `)` (1) to get a new total score of 11. - Multiply the total score by 5 to get 55, then add the value of `}` (3) to get a new total score of 58. - Multiply the total score by 5 to get 290, then add the value of `>` (4) to get a new total score of 294. The five lines' completion strings have total scores as follows: ``` }}]])})] - 288957 total points. )}>]}) - 5566 total points. }}>}>)))) - 1480781 total points. ]]}}]}]}> - 995444 total points. ])}> - 294 total points. ``` Autocomplete tools are an odd bunch: the winner is found by sorting all of the scores and then taking the middle score. (There will always be an odd number of scores to consider.) In this example, the middle score is 288957 because there are the same number of scores smaller and larger than it. Find the completion string for each incomplete line, score the completion strings, and sort the scores. What is the middle score? */ package com.curtislb.adventofcode.year2021.day10.part2 import com.curtislb.adventofcode.common.number.medianOrNull import com.curtislb.adventofcode.year2021.day10.syntax.SyntaxScorer import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2021, day 10, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long? { val scorer = SyntaxScorer(inputPath.toFile().readLines()) return scorer.completionScores.values.toList().medianOrNull() } fun main() = when (val solution = solve()) { null -> println("No solution found.") else -> println(solution) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
3,179
AdventOfCode
MIT License
2023/src/main/kotlin/day21.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Grid import utils.MutableGrid import utils.Parser import utils.Solution import utils.Vec2i import utils.toMutable fun main() { Day21.run(skipTest = true) } object Day21 : Solution<Grid<Char>>() { override val name = "day21" override val parser = Parser.charGrid override fun part1() = solve(64) override fun part2() = solve(26501365) enum class TileKind(val start: Vec2i) { // init square INIT(Vec2i(65, 65)), // cardinal directions UP(Vec2i(65, 130)), RIGHT(Vec2i(0, 65)), DOWN(Vec2i(65, 0)), LEFT(Vec2i(130, 65)), // diagonal directions LU(Vec2i(130, 130)), RU(Vec2i(0, 130)), LD(Vec2i(130, 0)), RD(Vec2i(0, 0)); } data class TileInfo( val initialCounts: List<Int>, val repeats: List<Int>, ) /** * Simulate one step of cellular automata based on [prev], output is fed into [g] * * @return the number of "on" states in output */ private fun simulate(g: MutableGrid<Char>, prev: Grid<Char>): Int { var count = 0 g.coords.forEach { p -> if (g[p] != '#') { if (p.adjacent.any { it in prev && prev[it] == 'O' }) { g[p] = 'O' count++ } else { g[p] = '.' } } } return count } /** * Evolve a tile init condition as indicated by [kind] into * a repeating steady state. */ private fun evolve(kind: TileKind): TileInfo { val out = mutableListOf<Int>() val start = input.coords.first { input[it] == 'S' } var a = input.toMutable() var b = input.toMutable() b[start] = '.' b[kind.start] = 'O' var c2 = Integer.MIN_VALUE var c1 = Integer.MIN_VALUE while (true) { val count = simulate(a, b) a = b.also { b = a } if (count == c2) { break } c2 = c1 c1 = count out.add(count) } return TileInfo(out, listOf(c2, c1)) } private fun getCount(info: TileInfo, step: Long): Int { if (step == 0L) { return 1 } if (step - 1 < info.initialCounts.size) { return info.initialCounts[(step - 1).toInt()] } else { val off = step - 1 - info.initialCounts.size return info.repeats[(off % 2).toInt()] } } fun solve(steps: Long): Long { val tiles = mutableListOf( Triple(TileKind.INIT, 0L, 1) ) // spawn cardinals val cardinals = listOf(TileKind.UP, TileKind.LEFT, TileKind.DOWN, TileKind.RIGHT) for (i in 66 .. steps step 131) { cardinals.forEach { tiles.add(Triple(it, i, 1)) } } val oldgens = (steps / 131) - 2 var evenolds = 0L var oddolds = 0L val corners = listOf(TileKind.RU, TileKind.RD, TileKind.LD, TileKind.LU) var gen = 1 for (i in 132 .. steps step 131) { if (gen <= oldgens) { if ((gen + 1) % 2L == 0L) { evenolds += gen } else { oddolds += gen } } else { // add gen manually corners.forEach { kind -> tiles.add(Triple(kind, i, gen)) } } gen++ } val tileInfos = TileKind.entries.associateWith { evolve(it) } val oldCount = corners.sumOf { val tileInfo = tileInfos[it]!! evenolds * getCount(tileInfo, 401) + oddolds * getCount(tileInfo, 400) } val cardinalCellCount = tiles.sumOf { (kind, birth, amount) -> getCount(tileInfos[kind]!!, steps - birth).toLong() * amount } return cardinalCellCount + oldCount } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
3,482
aoc_kotlin
MIT License
src/Day03_part1.kt
yashpalrawat
573,264,560
false
{"Kotlin": 12474}
fun main() { val input = readInput("Day03") // split string into two halves // add all elements of first string to a map // iterate through second string and see if record existing in first map // if exists then add that character to result list ( or just get the priority ) val priorities = getPriorities() val totalPriority = input.sumOf { val (str1, str2) = splitString(it) val chars = findCommanCharacters(str1, str2) val characterPriority = chars.sumOf { priorities[it] ?: 0 } println("comman chars: $chars, characterPriority: $characterPriority") characterPriority } println(totalPriority) } fun getPriorities(): Map<Char, Int> { return ('a'..'z').associateWith { it.code - 'a'.code + 1 }.plus( ('A'..'Z').associateWith { it.code - 'A'.code + 27 } ) } fun findCommanCharacters(firstString: String, secondString: String): Set<Char> { val mapOfCharsInFirstString = firstString.associateWith { it to 1 } return secondString.toCharArray().filter { mapOfCharsInFirstString.containsKey(it) }.toSet() } fun splitString(inputString: String): List<String> { return listOf( inputString.substring(0, inputString.length / 2), inputString.substring(inputString.length / 2) ) }
0
Kotlin
0
0
78a3a817709da6689b810a244b128a46a539511a
1,305
code-advent-2022
Apache License 2.0
src/Day20.kt
inssein
573,116,957
false
{"Kotlin": 47333}
fun main() { fun List<String>.parse(decryptionKey: Long = 1L) = map { it.toLong() * decryptionKey } fun List<Long>.mix(times: Int = 1): List<Long> { // using `IndexedValue<T>` to keep track of the original index (because the data can contain duplicates) val data = this.withIndex().toMutableList() repeat(times) { data.indices.forEach { originalIndex -> val i = data.indexOfFirst { (index) -> index == originalIndex } // first we remove item val item = data.removeAt(i) // re-add the item back at the new index data.add((i + item.value).mod(data.size), item) } } // strip out temporary data structure return data.map { it.value } } fun List<Long>.grooveCoordinates() = indexOf(0).let { zero -> listOf(1000, 2000, 3000).map { this[(zero + it) % size] } } fun part1(input: List<String>): Long { val parsed = input.parse() val mixed = parsed.mix() return mixed.grooveCoordinates().sum() } fun part2(input: List<String>): Long { val parsed = input.parse(811589153) val mixed = parsed.mix(10) return mixed.grooveCoordinates().sum() } val testInput = readInput("Day20_test") println(part1(testInput)) // 3 println(part2(testInput)) // 1623178306 val input = readInput("Day20") println(part1(input)) // 9866 println(part2(input)) // 12374299815791 }
0
Kotlin
0
0
095d8f8e06230ab713d9ffba4cd13b87469f5cd5
1,523
advent-of-code-2022
Apache License 2.0
src/Day08.kt
chrisjwirth
573,098,264
false
{"Kotlin": 28380}
import kotlin.math.max fun main() { class VisibleTreeCounter(input: List<String>) { val rowLength = input.size val colLength = input[0].length val lastRow = rowLength - 1 val lastCol = colLength - 1 val grid = List(rowLength) { List(colLength) { Tree() } } inner class Tree( var row: Int = 0, var col: Int = 0, var height: Int = 0, var isOnBorder: Boolean = false, var maxTreeAbove: Int = 0, var maxTreeRight: Int = 0, var maxTreeBelow: Int = 0, var maxTreeLeft: Int = 0, var isVisible: Boolean = false ) private fun determineIfTreeIsOnBorder(tree: Tree) { if (tree.row == 0 || tree.row == lastRow) tree.isOnBorder = true if (tree.col == 0 || tree.col == lastCol) tree.isOnBorder = true if (tree.isOnBorder) tree.isVisible = true } init { for (row in 0..lastRow) { for (col in 0..lastCol) { val tree = grid[row][col] tree.row = row tree.col = col tree.height = input[tree.row][tree.col].digitToInt() determineIfTreeIsOnBorder(tree) } } } private fun calculateMaxTreeAbove(tree: Tree) { if (tree.row > 0) { val treeAbove = grid[tree.row - 1][tree.col] tree.maxTreeAbove = max(treeAbove.height, treeAbove.maxTreeAbove) } if (tree.height > tree.maxTreeAbove) tree.isVisible = true } private fun calculateMaxTreeRight(tree: Tree) { if (tree.col < lastCol) { val treeRight = grid[tree.row][tree.col + 1] tree.maxTreeRight = max(treeRight.height, treeRight.maxTreeRight) } if (tree.height > tree.maxTreeRight) tree.isVisible = true } private fun calculateMaxTreeBelow(tree: Tree) { if (tree.row < lastRow) { val treeBelow = grid[tree.row + 1][tree.col] tree.maxTreeBelow = max(treeBelow.height, treeBelow.maxTreeBelow) } if (tree.height > tree.maxTreeBelow) tree.isVisible = true } private fun calculateMaxTreeLeft(tree: Tree) { if (tree.col > 0) { val treeLeft = grid[tree.row][tree.col - 1] tree.maxTreeLeft = max(treeLeft.height, treeLeft.maxTreeLeft) } if (tree.height > tree.maxTreeLeft) tree.isVisible = true } private fun scenicScoreUp(tree: Tree): Int { var visibleTrees = 0 for (row in (tree.row - 1)downTo 0) { visibleTrees++ val comparisonTree = grid[row][tree.col] if (tree.height <= comparisonTree.height) break } return visibleTrees } private fun scenicScoreRight(tree: Tree): Int { var visibleTrees = 0 for (col in (tree.col + 1) .. lastCol) { visibleTrees++ val comparisonTree = grid[tree.row][col] if (tree.height <= comparisonTree.height) break } return visibleTrees } private fun scenicScoreDown(tree: Tree): Int { var visibleTrees = 0 for (row in (tree.row + 1) .. lastRow) { visibleTrees++ val comparisonTree = grid[row][tree.col] if (tree.height <= comparisonTree.height) break } return visibleTrees } private fun scenicScoreLeft(tree: Tree): Int { var visibleTrees = 0 for (col in (tree.col - 1) downTo 0) { visibleTrees++ val comparisonTree = grid[tree.row][col] if (tree.height <= comparisonTree.height) break } return visibleTrees } private fun calculateScenicScore(tree: Tree): Int { return if (tree.isOnBorder) { 0 } else { scenicScoreUp(tree) * scenicScoreRight(tree) * scenicScoreDown(tree) * scenicScoreLeft(tree) } } fun numberVisibleTrees(): Int { var numberVisibleTrees = 0 // First pass - upper left to bottom right for (row in 0..lastRow) { for (col in 0..lastCol) { val tree = grid[row][col] calculateMaxTreeAbove(tree) calculateMaxTreeLeft(tree) } } // Second pass - bottom right to upper left for (row in lastRow downTo 0) { for (col in lastCol downTo 0) { val tree = grid[row][col] calculateMaxTreeBelow(tree) calculateMaxTreeRight(tree) if (tree.isVisible) numberVisibleTrees++ } } return numberVisibleTrees } fun maxScenicScore(): Int { var maxScenicScore = 0 for (row in 0..lastRow) { for (col in 0..lastCol) { val tree = grid[row][col] val treeScenicScore = calculateScenicScore(tree) maxScenicScore = max(maxScenicScore, treeScenicScore) } } return maxScenicScore } } fun part1(input: List<String>): Int { val visibleTreeCounter = VisibleTreeCounter(input) return visibleTreeCounter.numberVisibleTrees() } fun part2(input: List<String>): Int { val visibleTreeCounter = VisibleTreeCounter(input) return visibleTreeCounter.maxScenicScore() } // Test val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) // Final val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8b1f2a0d0f579dd23fa1dc1f7b156f728152c2d
6,123
AdventOfCode2022
Apache License 2.0
6_six/MovieFan.kt
thalees
250,902,664
false
null
import java.util.* fun main() { repeat(readLine()!!.toInt()) { // readLine() // skip empty line solveCase() } } private data class Mv(val i: Int, val a: Int, val b: Int, var t: Int = 0) : Comparable<Mv> { override fun compareTo(other: Mv): Int = if (b != other.b) b.compareTo(other.b) else i.compareTo(other.i) } private fun solveCase() { val (n, m) = readLine()!!.split(" ").map { it.toInt() } val d = Array(n) { i -> readLine()!!.split(" ").map { it.toInt() }.let { (a, b) -> Mv(i, a, b) } } d.sortBy { it.a } var t = 0 val w = TreeSet<Mv>() fun advance(to: Int) { while (t < to && !w.isEmpty()) { repeat(minOf(w.size, m)) { val v = w.first() v.t = t w -= v } t++ } t = to } for (v in d) { advance(v.a) w += v } advance(Int.MAX_VALUE) d.sortBy { it.i } println(maxOf(0, d.map { it.t - it.b }.max()!!)) println(d.joinToString(" ") { it.t.toString() }) }
0
Kotlin
0
0
3b499d207d366450c7b2facbd99a345c86b6eff8
1,073
kotlin-code-challenges
MIT License
src/main/kotlin/analysis/SatelliteCalculator.kt
TheKoren
708,303,908
false
{"Kotlin": 22459}
package analysis import analysis.data.ConstellationInfo import analysis.data.SatelliteInfo import model.SatelliteData import java.time.LocalDate import kotlin.math.PI import kotlin.math.cbrt import kotlin.math.pow /** * A utility object for calculating and analyzing satellite-related information. */ object SatelliteCalculator { /** * Calculate the altitude of a satellite based on its mean motion. * * @param meanMotion The mean motion of the satellite in orbits per day. * @see <a href="https://www.spaceacademy.net.au/watch/track/leopars.htm">SpaceAcademy</a> * @return The altitude of the satellite in kilometers. */ fun calculateAltitude(meanMotion: Double): Double { val period = Constants.DAY_IN_SECONDS / meanMotion return cbrt((period.pow(2) * Constants.GRAVITY_CONSTANT) / (2 * PI).pow(2)) - Constants.EARTH_RADIUS_KM } /** * Count the number of LEO (Low Earth Orbit) and GEO (Geostationary Earth Orbit) and MEO (Medium Earth Orbit) satellites in a list. * * @param satelliteDataList A list of SatelliteData objects. * @return A triple of counts, where the first element is the count of LEO satellites, and the second is the count of GEO satellites and the third is MEO satellites. */ fun countLEOandGEOandMEO(satelliteDataList: List<SatelliteData>): Triple<Int, Int, Int> { return satelliteDataList .map { satelliteData -> val meanMotion = satelliteData.MEAN_MOTION val altitude = calculateAltitude(meanMotion) when { altitude < Constants.LEO_ALTITUDE_THRESHOLD -> Triple(1, 0, 0) altitude > Constants.GEO_ALTITUDE_THRESHOLD -> Triple(0, 1, 0) else -> Triple(0, 0, 1) } } .reduce { acc, triple -> Triple( acc.first + triple.first, acc.second + triple.second, acc.third + triple.third ) } } /** * Get a list of NORAD Catalog Numbers from a list of SatelliteData objects. * * @param satelliteDataList A list of SatelliteData objects. * @return A list of NORAD Catalog Numbers. */ fun getNoradCatalogNumber(satelliteDataList: List<SatelliteData>): List<Int> { return satelliteDataList.map { it.NORAD_CAT_ID } } /** * Get a list of SatelliteData objects sorted by mean motion in descending order. * * @param satelliteDataList A list of SatelliteData objects. * @return A sorted list of SatelliteData objects. */ fun getTopSatellitesByMeanMotion(satelliteDataList: List<SatelliteData>): List<SatelliteData> { return satelliteDataList.sortedByDescending { it.MEAN_MOTION } } /** * Analyze constellations and calculate satellite counts for each constellation. * * @param satelliteDataList A list of SatelliteData objects. * @return A map where keys are constellation names and values are ConstellationInfo objects. */ fun analyzeConstellations(satelliteDataList: List<SatelliteData>): Map<String, ConstellationInfo> { return satelliteDataList.groupBy { it.OBJECT_NAME.getFirstPart() } .mapValues { ConstellationInfo().apply { it.value.forEach { addSatellite(calculateAltitude(it.MEAN_MOTION)) } } } } /** * Find and list the longest-running satellites based on their launch year. * * @param satelliteDataList A list of SatelliteData objects. * @return A list of SatelliteInfo objects representing long-running satellites. */ fun findLongestRunningSatellites(satelliteDataList: List<SatelliteData>): List<SatelliteInfo> { val currentDate = LocalDate.now() return satelliteDataList.filter { val launchDate = it.OBJECT_ID.getFirstPart().toInt() currentDate.year - launchDate >= Constants.OLD_AGE_THRESHOLD }.map { SatelliteInfo(it.NORAD_CAT_ID, currentDate.year - it.OBJECT_ID.getFirstPart().toInt()) } .also { if (it.isEmpty()) println("No old satellites found for this dataset.") } } /** * Analyze launch years and count the number of satellites launched in each year. * * @param satelliteDataList A list of SatelliteData objects. * @return A map where keys are launch years and values are the counts of satellites launched in each year. */ fun analyzeLaunchYears(satelliteDataList: List<SatelliteData>): Map<Int, Int> { return satelliteDataList.groupingBy { it.OBJECT_ID.getFirstPart().toInt() } .eachCount() } /** * Analyze apogee and perigee altitudes of satellites * * @param satelliteDataList A list of SatelliteData objects. * @return A map where keys are norad catalog numbers and values are the apogee and perigee altitudes. */ fun analyzeOrbit(satelliteDataList: List<SatelliteData>): Map<Int, Pair<Double, Double>> { return satelliteDataList.associate { data -> data.NORAD_CAT_ID to Pair(data.calculateApogeeAltitude(), data.calculatePerigeeAltitude()) } } }
0
Kotlin
0
0
98570983ed3354b5e3c1e99fecf37d2f168bb510
5,218
satellite-data-analysis
MIT License
advent-of-code2016/src/main/kotlin/day03/Advent3.kt
REDNBLACK
128,669,137
false
null
package day03 import parseInput import splitToLines /** --- Day 3: Squares With Three Sides --- Now that you can think clearly, you move deeper into the labyrinth of hallways and office furniture that makes up this part of Easter Bunny HQ. This must be a graphic design department; the walls are covered in specifications for triangles. Or are they? The design document gives the side lengths of each triangle it describes, but... 5 10 25? Some of these aren't triangles. You can't help but mark the impossible ones. In a valid triangle, the sum of any two sides must be larger than the remaining side. For example, the "triangle" given above is impossible, because 5 + 10 is not larger than 25. In your puzzle input, how many of the listed triangles are possible? */ fun main(args: Array<String>) { val test = "5 10 25" val input = parseInput("day3-input.txt") println(findPossible(test).isEmpty()) println(findPossible(input).size) } data class Triangle(val x: Int, val y: Int, val z: Int) { fun isPossible() = x + y > z && x + z > y && y + z > x } fun findPossible(input: String) = parseTriangles(input).filter { it.isPossible() } private fun parseTriangles(input: String) = input.splitToLines() .map { val (x, y, z) = it.splitToLines(" ").map(String::toInt) Triangle(x, y, z) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
1,357
courses
MIT License
aoc-2016/src/main/kotlin/nl/jstege/adventofcode/aoc2016/days/Day20.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2016.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.sumBy /** * * @author <NAME> */ class Day20 : Day(title = "Firewall Rules") { private companion object Configuration { private const val MAX_ADDRESS = (1L shl Integer.SIZE) - 1 } override fun first(input: Sequence<String>): Any = input .map(Day20::IpRange).optimize().first .first().end + 1 override fun second(input: Sequence<String>): Any = input .map(Day20::IpRange).optimize().second .sumBy { it.end + 1 - it.start } private fun Sequence<IpRange>.optimize(): Pair<List<IpRange>, List<IpRange>> { val blockedRanges = mutableListOf<IpRange>() val allowedRanges = mutableListOf<IpRange>() val trackedHigh = this .sortedBy { it.start } .fold(Pair(0L, 0L)) { (trackedHigh, trackedLow), (start, end) -> if (start > trackedHigh + 1) { blockedRanges += IpRange(trackedLow, trackedHigh) allowedRanges += IpRange(trackedHigh + 1, start - 1) Pair(end, start) } else { Pair(Math.max(trackedHigh, end), trackedLow) } }.first if (trackedHigh < MAX_ADDRESS) { allowedRanges += IpRange(trackedHigh + 1, MAX_ADDRESS) } return Pair(blockedRanges, allowedRanges) } private data class IpRange(val start: Long, val end: Long) { constructor(i: List<Long>) : this(i[0], i[1]) constructor(s: String) : this(s.split('-').map(String::toLong).sorted()) } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
1,710
AdventOfCode
MIT License
leetcode-75-kotlin/src/main/kotlin/MaxConsecutiveOnesIII.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * Given a binary array nums and an integer k, * return the maximum number of consecutive 1's in the array if you can flip at most k 0's. * * * * Example 1: * * Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 * Output: 6 * Explanation: [1,1,1,0,0,1,1,1,1,1,1] * Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. * Example 2: * * Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3 * Output: 10 * Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] * Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. * * * Constraints: * * 1 <= nums.length <= 10^5 * nums[i] is either 0 or 1. * 0 <= k <= nums.length * @see <a href="https://leetcode.com/problems/max-consecutive-ones-iii/">LeetCode</a> */ fun longestOnes(nums: IntArray, k: Int): Int { var startIndex = 0 var numberOfZeros = 0 var maxConsecutiveOnes = 0 for ((endIndex, endDigit) in nums.withIndex()) { if (endDigit == 0) { numberOfZeros++ } while (numberOfZeros > k) { if (nums[startIndex] == 0) { numberOfZeros-- } startIndex++ } maxConsecutiveOnes = maxOf(maxConsecutiveOnes, endIndex - startIndex + 1) } return maxConsecutiveOnes }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,304
leetcode-75
Apache License 2.0
src/main/kotlin/tools/graph/ShortPath.kt
wrabot
739,807,905
false
{"Kotlin": 19706}
package tools.graph fun <Node : Any> shortPath( start: Node, end: Node, cost: (origin: Node, destination: Node) -> Double = { _, _ -> 1.0 }, estimatedEndCost: (Node) -> Double = { 0.0 }, // A* neighbors: (Node) -> List<Node> ) = shortPath(start, isEnd = { this == end }, cost, estimatedEndCost, neighbors) fun <Node : Any> shortPath( start: Node, isEnd: Node.() -> Boolean, cost: (origin: Node, destination: Node) -> Double = { _, _ -> 1.0 }, toEndMinimalCost: (Node) -> Double = { 0.0 }, // A* neighbors: Node.() -> List<Node> ): List<Node> { val spStart = ShortPathNode(start, 0.0, toEndMinimalCost(start), true) val spNodes = mutableMapOf(start to spStart) val todo = mutableListOf(spStart) while (true) { val currentSPNode = todo.removeFirstOrNull() ?: return emptyList() currentSPNode.todo = false if (currentSPNode.node.isEnd()) return generateSequence(currentSPNode) { it.predecessor }.map { it.node }.toList().reversed() neighbors(currentSPNode.node).forEach { nextNode -> val newFromStartCost = currentSPNode.fromStartCost + cost(currentSPNode.node, nextNode) val nextSPNode = spNodes[nextNode] when { nextSPNode == null -> { val spNode = ShortPathNode( nextNode, newFromStartCost, newFromStartCost + toEndMinimalCost(nextNode), true ) spNode.predecessor = currentSPNode spNodes[nextNode] = spNode todo.add(-todo.binarySearch(spNode) - 1, spNode) } newFromStartCost < nextSPNode.fromStartCost -> { var toIndex = todo.size if (nextSPNode.todo) { toIndex = todo.binarySearch(nextSPNode) todo.removeAt(toIndex) } nextSPNode.predecessor = currentSPNode nextSPNode.minimalCost -= nextSPNode.fromStartCost - newFromStartCost nextSPNode.fromStartCost = newFromStartCost nextSPNode.todo = true todo.add(-todo.binarySearch(nextSPNode, toIndex = toIndex) - 1, nextSPNode) } } } } } private data class ShortPathNode<Node : Any>( val node: Node, var fromStartCost: Double, var minimalCost: Double, var todo: Boolean ) : Comparable<ShortPathNode<Node>> { var predecessor: ShortPathNode<Node>? = null override fun compareTo(other: ShortPathNode<Node>): Int { val compare = minimalCost.compareTo(other.minimalCost) return if (compare != 0) compare else id.compareTo(other.id) } private val id = nextId++ companion object { private var nextId = Int.MIN_VALUE } }
0
Kotlin
0
0
fd2da26c0259349fbc9719e694d58549e7f040a0
2,955
competitive-tools
Apache License 2.0
src/main/kotlin/ca/kiaira/advent2023/day9/Day9.kt
kiairatech
728,913,965
false
{"Kotlin": 78110}
package ca.kiaira.advent2023.day9 import ca.kiaira.advent2023.Puzzle import ca.kiaira.advent2023.day9.Day9.number /** * Object representing the solution for Day 9 of the Advent of Code. * * This class extends the Puzzle class and provides specific implementations for parsing and solving * the puzzle for Day 9, which involves extrapolating values from historical data based on a series * of integers. * * @property number The day number of the puzzle, which is 9. * * @author <NAME> <<EMAIL>> * @since December 9th, 2023 */ object Day9 : Puzzle<List<List<Int>>>(9) { /** * Parses the input data from a sequence of strings into a list of lists of integers. * Each line of the input is split into a list of integers. * * @param input The input data as a sequence of strings. * @return The parsed input data as a list of lists of integers. */ override fun parse(input: Sequence<String>): List<List<Int>> { return input.map { line -> line.split(" ").map { it.toInt() } }.toList() } /** * Solves Part 1 of the Day 9 puzzle. * This involves summing the next extrapolated value for each series in the input. * * @param input The parsed input data, a list of lists of integers. * @return The solution to Part 1 of the puzzle as an integer. */ override fun solvePart1(input: List<List<Int>>): Int { return input.sumOf { calculateValue(it, true) } } /** * Solves Part 2 of the Day 9 puzzle. * This involves summing the previous extrapolated value for each series in the input. * * @param input The parsed input data, a list of lists of integers. * @return The solution to Part 2 of the puzzle as an integer. */ override fun solvePart2(input: List<List<Int>>): Int { return input.sumOf { calculateValue(it, false) } } /** * Calculates the next or previous value in a series based on the difference method. * * This function uses a tail-recursive helper function to generate sequences of differences * until all differences are zero, then either extrapolates the next or previous value * based on the 'calculateNext' flag. * * @param history A list of integers representing the historical series. * @param calculateNext A boolean flag indicating the direction of extrapolation. * If true, calculates the next value, else calculates the previous value. * @return The extrapolated value as an integer. */ private fun calculateValue(history: List<Int>, calculateNext: Boolean): Int { return calculate(history, mutableListOf(history.toMutableList()), calculateNext) } /** * Tail-recursive helper function for calculating the next or previous value in a series. * * This function iteratively generates sequences of differences and uses them to extrapolate * the next or previous value. The recursion terminates when all differences are zero. * * @param history The original series of historical values. * @param sequences A mutable list of mutable lists, each containing a sequence of differences. * @param calculateNext A boolean flag to determine the direction of extrapolation. * @return The extrapolated value as an integer. */ private tailrec fun calculate( history: List<Int>, sequences: MutableList<MutableList<Int>>, calculateNext: Boolean ): Int { if (sequences.last().all { it == 0 }) { for (i in sequences.size - 2 downTo 0) { val nextValue = if (calculateNext) { sequences[i].last() + sequences[i + 1].last() } else { sequences[i].first() - sequences[i + 1].first() } if (calculateNext) sequences[i].add(nextValue) else sequences[i].add(0, nextValue) } return if (calculateNext) sequences[0].last() else sequences[0].first() } else { val newSequence = (0 until sequences.last().size - 1).map { i -> sequences.last()[i + 1] - sequences.last()[i] }.toMutableList() sequences.add(newSequence) return calculate(history, sequences, calculateNext) } } }
0
Kotlin
0
1
27ec8fe5ddef65934ae5577bbc86353d3a52bf89
3,974
kAdvent-2023
Apache License 2.0
src/org/aoc2021/Day8.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
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) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
2,643
advent-of-code-2021
The Unlicense
src/AoC11.kt
Pi143
317,631,443
false
null
import java.io.File val floor = 0 val emptySeat = 1 val occupiedSeat = 2 fun main() { println("Starting Day 11 A Test 1") calculateDay11PartA("Input/2020_Day11_A_Test1") println("Starting Day 11 A Real") calculateDay11PartA("Input/2020_Day11_A") println("Starting Day 11 B Test 1") calculateDay11PartB("Input/2020_Day11_A_Test1") println("Starting Day 11 B Real") calculateDay11PartB("Input/2020_Day11_A") } fun calculateDay11PartA(file: String): Int { val Day11Data = readDay11Data(file) var oldSeatConfig = Day11Data.map { it.clone() }.toTypedArray() var newSeatConfig = sitPeopleA(Day11Data) while (!(oldSeatConfig contentDeepEquals newSeatConfig)) { oldSeatConfig = newSeatConfig.map { it.clone() }.toTypedArray() newSeatConfig = sitPeopleA(oldSeatConfig) } val occupiedSeats = newSeatConfig.sumBy { row -> row.count { it == occupiedSeat } } println("$occupiedSeats seats are occupied") return occupiedSeats } fun sitPeopleA(seatConfig: Array<IntArray>): Array<IntArray> { val nextSeatConfig = seatConfig.map { it.clone() }.toTypedArray() val rows = seatConfig.size val columns = seatConfig[0].size for (line in 0 until rows) { for (seat in 0 until columns) { nextSeatConfig[line][seat] = determineNextSittingA(line, seat, seatConfig) } } return nextSeatConfig } fun determineNextSittingA(row: Int, seat: Int, seatConfig: Array<IntArray>): Int { return when (seatConfig[row][seat]) { emptySeat -> { if (countOccupiedDirectNeighbors(row, seat, seatConfig) == 0) { occupiedSeat } else { seatConfig[row][seat] } } occupiedSeat -> { if (countOccupiedDirectNeighbors(row, seat, seatConfig) >= 4) { emptySeat } else { seatConfig[row][seat] } } else -> seatConfig[row][seat] } } fun countOccupiedDirectNeighbors(row: Int, seat: Int, seatConfig: Array<IntArray>): Int { var occupiedNeighbors = 0 val rows = seatConfig.size val columns = seatConfig[0].size if (row > 0) { if (seat > 0) { if (seatConfig[row - 1][seat - 1] == occupiedSeat) { occupiedNeighbors++ } } if (seatConfig[row - 1][seat] == occupiedSeat) { occupiedNeighbors++ } if (seat < columns - 1) { if (seatConfig[row - 1][seat + 1] == occupiedSeat) { occupiedNeighbors++ } } } if (seat > 0) { if (seatConfig[row][seat - 1] == occupiedSeat) { occupiedNeighbors++ } } if (seat < columns - 1) { if (seatConfig[row][seat + 1] == occupiedSeat) { occupiedNeighbors++ } } if (row < rows - 1) { if (seat > 0) { if (seatConfig[row + 1][seat - 1] == occupiedSeat) { occupiedNeighbors++ } } if (seatConfig[row + 1][seat] == occupiedSeat) { occupiedNeighbors++ } if (seat < columns - 1) { if (seatConfig[row + 1][seat + 1] == occupiedSeat) { occupiedNeighbors++ } } } return occupiedNeighbors } fun calculateDay11PartB(file: String): Int { val Day11Data = readDay11Data(file) var oldSeatConfig = Day11Data.map { it.clone() }.toTypedArray() var newSeatConfig = sitPeopleA(Day11Data) while (!(oldSeatConfig contentDeepEquals newSeatConfig)) { oldSeatConfig = newSeatConfig.map { it.clone() }.toTypedArray() newSeatConfig = sitPeopleB(oldSeatConfig) } val occupiedSeats = newSeatConfig.sumBy { row -> row.count { it == occupiedSeat } } println("$occupiedSeats seats are occupied") return occupiedSeats } fun sitPeopleB(seatConfig: Array<IntArray>): Array<IntArray> { val nextSeatConfig = seatConfig.map { it.clone() }.toTypedArray() val rows = seatConfig.size val columns = seatConfig[0].size for (line in 0 until rows) { for (seat in 0 until columns) { nextSeatConfig[line][seat] = determineNextSittingB(line, seat, seatConfig) } } return nextSeatConfig } fun determineNextSittingB(row: Int, seat: Int, seatConfig: Array<IntArray>): Int { return when (seatConfig[row][seat]) { emptySeat -> { if (countOccupiedDistantNeighbors(row, seat, seatConfig) == 0) { occupiedSeat } else { seatConfig[row][seat] } } occupiedSeat -> { if (countOccupiedDistantNeighbors(row, seat, seatConfig) >= 5) { emptySeat } else { seatConfig[row][seat] } } else -> seatConfig[row][seat] } } fun countOccupiedDistantNeighbors(row: Int, seat: Int, seatConfig: Array<IntArray>): Int { var occupiedNeighbors = 0 occupiedNeighbors += isNextVisbleSeatInDirectionOccupied(row, seat, -1, -1, seatConfig) occupiedNeighbors += isNextVisbleSeatInDirectionOccupied(row, seat, -1, 0, seatConfig) occupiedNeighbors += isNextVisbleSeatInDirectionOccupied(row, seat, -1, 1, seatConfig) occupiedNeighbors += isNextVisbleSeatInDirectionOccupied(row, seat, 0, -1, seatConfig) occupiedNeighbors += isNextVisbleSeatInDirectionOccupied(row, seat, 0, 1, seatConfig) occupiedNeighbors += isNextVisbleSeatInDirectionOccupied(row, seat, 1, -1, seatConfig) occupiedNeighbors += isNextVisbleSeatInDirectionOccupied(row, seat, 1, 0, seatConfig) occupiedNeighbors += isNextVisbleSeatInDirectionOccupied(row, seat, 1, 1, seatConfig) return occupiedNeighbors } fun isNextVisbleSeatInDirectionOccupied(row: Int, col: Int, rowDir: Int, colDir: Int, seatConfig: Array<IntArray>): Int { var currentConsideredRow = row + rowDir var currentConsideredColumn = col + colDir while (seatConfig.getOrNull(currentConsideredRow)?.getOrNull(currentConsideredColumn) != null){ when(seatConfig.getOrNull(currentConsideredRow)?.getOrNull(currentConsideredColumn)){ floor -> { currentConsideredRow += rowDir currentConsideredColumn += colDir} occupiedSeat -> return 1 emptySeat -> return 0 } } return 0 } fun readDay11Data(input: String): Array<IntArray> { val lines = File(localdir + input).readLines() val rows = lines.size val columns = lines[0].length val seatConfig: Array<IntArray> = Array(rows) { IntArray(columns) } for (line in 0 until rows) { for (seat in 0 until columns) { when (lines[line][seat]) { '.' -> seatConfig[line][seat] = floor 'L' -> seatConfig[line][seat] = emptySeat '#' -> seatConfig[line][seat] = occupiedSeat } } } return seatConfig }
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
7,012
AdventOfCode2020
MIT License
src/main/kotlin/advent2019/day3/day3.kt
davidpricedev
225,621,794
false
null
package advent2019.day3 import java.lang.Exception import java.util.* import kotlin.math.absoluteValue fun main() { calculateClosestIntersection(InputData().input1, InputData().input2) calculateShortestWire(InputData().input1, InputData().input2) } fun calculateShortestWire(inputWire1: List<String>, inputWire2: List<String>): Int { val wirePoints1 = inputWireToPointSetWithLength(inputWire1) val wirePoints2 = inputWireToPointSetWithLength(inputWire2) val wirePointsNoLength1 = wirePoints1.map { Point(it.x, it.y) } val wirePointsNoLength2 = wirePoints2.map { Point(it.x, it.y) } val intersections = wirePointsNoLength1.intersect(wirePointsNoLength2) val combinedResults = mutableListOf<Point>() for (intersection in intersections) { val intersection1 = getShortestPathPoint(wirePoints1, intersection) val intersection2 = getShortestPathPoint(wirePoints2, intersection) combinedResults.add(intersection.copy(wireLength = intersection1.wireLength + intersection2.wireLength)) } println(combinedResults) val result = combinedResults.sortedBy { it.wireLength }.first() println("Result: ${result.wireLength} at ${result}") return result.wireLength } fun getShortestPathPoint(wirePoints: Set<Point>, pointToFind: Point): Point = wirePoints.filter { it.x == pointToFind.x && it.y == pointToFind.y }.sortedBy { it.wireLength }.first() fun calculateClosestIntersection(inputLine1: List<String>, inputLine2: List<String>): Int { val linePoints1 = inputLineToPointSet(inputLine1) val linePoints2 = inputLineToPointSet(inputLine2) val intersections = linePoints1.intersect(linePoints2) val result = intersections.sortedBy { it.distance() }.first() println("Result: ${result.distance()} at ${result}") return result.distance() } fun inputWireToPointSetWithLength(inputWire: List<String>): Set<Point> { val vectors = inputWire.map { translateInputToVector(it) } val wirePoints: MutableSet<Point> = mutableSetOf() var currentPos = Point(0, 0) for (vector in vectors) { println("change point: ${currentPos}") val nextPoints = getPathPointsWithLength(currentPos, vector).toMutableList() // 1st element might be the starting point (aka core) and should already be included otherwise nextPoints.removeAt(0) wirePoints.addAll(nextPoints) currentPos = nextPoints.last() } println("change point: ${currentPos}") return Collections.unmodifiableSet(wirePoints) } fun inputLineToPointSet(inputLine: List<String>): Set<Point> { val vectors = inputLine.map { translateInputToVector(it) } val linePoints: MutableSet<Point> = mutableSetOf() var currentPos = Point(0, 0) for (vector in vectors) { println("change point: ${currentPos}") val nextPoints = getPathPoints(currentPos, vector).toMutableList() // 1st element might be the starting point (aka core) and should already be included otherwise nextPoints.removeAt(0) linePoints.addAll(nextPoints) currentPos = nextPoints.last() } println("change point: ${currentPos}") return Collections.unmodifiableSet(linePoints) } data class Point( val x: Int, val y: Int, val wireLength: Int = 0 ) { /** * Manhattan/Taxi distance */ fun distance() = x.absoluteValue + y.absoluteValue } fun getPathPointsWithLength(start: Point, vector: Point) = if (vector.x != 0) { val range = buildRange(start.x, start.x + vector.x) range.map { Point(it, start.y, start.wireLength + (it - start.x).absoluteValue) } } else { val range = buildRange(start.y, start.y + vector.y) range.map { Point(start.x, it, start.wireLength + (it - start.y).absoluteValue) } } fun getPathPoints(start: Point, vector: Point) = if (vector.x != 0) { val range = buildRange(start.x, start.x + vector.x) range.map { Point(it, start.y) } } else { val range = buildRange(start.y, start.y + vector.y) range.map { Point(start.x, it) } } /** * kotlin has nice ranges for 0..8, but doesn't support 8..0 * While we are at it, we need to skip the first 0,0 point and we can do that by skipping the first element here */ fun buildRange(start: Int, end: Int) = if (start < end) { (start..end).map { it } } else { val forwardList = (end..start).map { it } forwardList.reversed() } fun translateInputToVector(input: String): Point { val direction = input.substring(0, 1) val magnitude = input.substring(1).toInt() return when (direction) { "U" -> Point(0, magnitude) "L" -> Point(-magnitude, 0) "D" -> Point(0, -magnitude) "R" -> Point(magnitude, 0) else -> throw Exception("(╯°□°)╯︵ ┻━┻") } } data class InputData( val input1: List<String> = "R998,U547,L703,D251,L776,U837,R100,U240,R197,D216,L220,U606,L437,U56,R940,U800,L968,D464,L870,D797,L545,D824,R790,U5,R347,D794,R204,U538,L247,U385,L103,D260,L590,U813,L549,U309,L550,U321,R862,D686,R368,D991,R451,D836,R264,D138,L292,D319,L784,D369,R849,U865,R776,D726,R223,D118,L790,D208,L836,D592,R310,D36,R991,U674,L205,U407,R422,U350,L126,D320,L239,U353,L509,U48,R521,D544,L157,D551,R614,D493,R407,D965,R498,U248,R826,U573,L782,D589,R616,D992,L806,D745,R28,U142,L333,D849,L858,D617,R167,U341,R46,U940,L615,D997,L447,D604,R148,U561,R925,D673,R441,U200,R458,U193,L805,D723,L208,U600,L926,U614,R660,D183,L408,D834,R248,U354,L110,U391,L37,U599,L287,U28,R859,D936,L404,D952,R11,U20,R708,U218,L800,U750,R936,D213,R6,D844,R728,D391,R114,U406,R390,U791,L199,D397,R476,D583,R99,U419,R575,D836,L896,U780,L77,U964,R441,U723,R248,D170,R527,D94,L39,U645,L338,D728,R503,U641,L358,D287,R171,U368,R176,D986,R821,U912,L231,D206,L451,U900,L35,D490,R190,D180,L937,D500,R157,U989,L336,U202,R178,U52,R931,U306,L85,D866,R756,U715,L521,D977,R936,U4,R207,D384,L785,U138,L682,U488,L537,U250,L877,D446,R849,U35,R258,U784,R263,D494,L324,U601,R302,U473,L737,D143,R184,D967,R95,U51,L713,U733,R297,U740,R677,D715,R750,U143,L980,U260,R915,D535,R202,U460,R365,U956,L73,U441,R182,D982,L869,D755,L837,D933,L856,D341,R189,D519,L387,D144,R575,U682,R317,U838,R154,D201,R237,D410,L43,U853,L495,U983,L953,U220,R697,D592,R355,U377,R792,U824,L441,U783,R258,D955,R451,D178,L151,D435,L232,U923,L663,U283,L92,D229,R514".split( "," ), val input2: List<String> = "L995,U122,R472,U470,R725,U906,L83,U672,R448,U781,L997,U107,R66,D966,L780,D181,L662,U158,R804,D837,L237,U164,L98,U582,R925,D806,L153,D843,R601,U941,L968,D528,R482,D586,R15,U370,L592,U836,R828,U676,R606,D20,R841,U117,L262,U377,R375,U503,R166,D398,R161,D9,R140,D188,R895,D226,R77,U28,L727,D72,L51,U425,R370,D377,L801,D525,R102,D568,L416,D300,R415,U199,R941,U211,R285,U719,L259,U872,L959,U350,L196,D830,R515,U899,R298,U875,R946,U797,R108,U461,R999,D49,L369,D472,R83,D265,L825,D163,R162,U906,L816,D241,L587,D801,R601,D630,R937,U954,L379,D347,R831,D337,L192,D649,L853,U270,R162,D892,L26,D663,L276,U891,R843,U67,R225,D88,R686,U662,R794,D814,L200,D887,R567,U363,L863,U16,R975,D470,R714,U771,L267,D402,R75,U98,L686,U565,R584,D402,L824,D927,R71,U39,L174,D494,L358,D626,R616,D369,R471,U881,L428,U53,R862,U749,L847,D944,L887,D695,R442,U870,L993,U315,L878,U100,L480,D354,L12,D533,L236,D364,R450,U679,L926,D391,R313,D953,L560,D740,L974,D119,L370,U404,R339,U233,R901,U514,R584,D495,R308,U170,R759,U592,R388,U396,R477,U670,R906,D687,L874,U352,R124,U700,R289,D524,L93,D817,R408,D776,L235,D928,L534,D296,R116,U995,L63,D903,R758,U881,L530,U498,R573,D626,L26,U269,R237,U287,L840,D603,R948,D567,R89,U552,L299,D774,R863,D182,R773,D108,L137,U88,L731,U793,L267,U902,L41,U258,L156,U361,R389,D839,L976,U960,L342,D489,R816,U391,L393,U601,R255,D629,R832,U877,L34,D373,L809,D679,L104,U901,R157,U468,R143,U896,L637,D577,L545,D486,L970,D130,L305,D909,R984,D500,L935,U949,R525,D547,L786,U106,L269,D511,L919".split( "," ) )
0
Kotlin
0
0
2283647e5b4ed15ced27dcf2a5cf552c7bd49ae9
7,991
adventOfCode2019
Apache License 2.0
src/main/kotlin/com/anahoret/aoc2022/day23/main.kt
mikhalchenko-alexander
584,735,440
false
null
package com.anahoret.aoc2022.day23 import java.io.File import kotlin.system.measureTimeMillis data class Elf(var row: Int, var col: Int) { operator fun plus(point: Point): Point { return Point(row + point.row, col + point.col) } } data class Point(val row: Int, val col: Int) fun parseElves(input: String): List<Elf> { return input.split("\n").flatMapIndexed { rowIdx, row -> row.mapIndexedNotNull { colIdx, col -> if (col == '#') Elf(rowIdx, colIdx) else null } } } fun main() { val input = File("src/main/kotlin/com/anahoret/aoc2022/day23/input.txt") .readText() .trim() // Part 1 part1(input).also { println("P1: ${it}ms") } // Part 2 part2(input).also { println("P2: ${it}ms") } } fun Map<Int, Map<Int, Elf>>.anyAt(row: Int, col: Int): Boolean { return get(row)?.get(col) != null } private val checkOrder = listOf( listOf(Point(-1, -1), Point(-1, 0), Point(-1, 1)), listOf(Point(1, -1), Point(1, 0), Point(1, 1)), listOf(Point(-1, -1), Point(0, -1), Point(1, -1)), listOf(Point(-1, 1), Point(0, 1), Point(1, 1)), ) private fun part1(input: String) = measureTimeMillis { val elves = parseElves(input) val proposes = mutableMapOf<Point, MutableList<Elf>>() var checkStart = 0 repeat(10) { tick(elves, proposes, checkStart) proposes.filter { it.value.size == 1 } .forEach { (propose, elves) -> elves.forEach { it.row = propose.row; it.col = propose.col } } checkStart++ if (checkStart == checkOrder.size) checkStart = 0 } val minRow = elves.minOf { it.row } val maxRow = elves.maxOf { it.row } val minCol = elves.minOf { it.col } val maxCol = elves.maxOf { it.col } val area = (maxRow - minRow + 1) * (maxCol - minCol + 1) val emptyGround = area - elves.size println(emptyGround) } private fun part2(input: String) = measureTimeMillis { val elves = parseElves(input) val proposes = mutableMapOf<Point, MutableList<Elf>>() var checkStart = 0 var round = 1 while(true) { tick(elves, proposes, checkStart) var noElfMoved = true proposes.forEach { (propose, elves) -> if (elves.size == 1) { noElfMoved = false elves.forEach { it.row = propose.row; it.col = propose.col } } } if (noElfMoved) break checkStart++ if (checkStart == checkOrder.size) checkStart = 0 round++ } println(round) } private fun tick(elves: List<Elf>, proposes: MutableMap<Point, MutableList<Elf>>, checkStart: Int) { val elvesMap = elves .groupBy(Elf::row) .mapValues { (_, value) -> value.associateBy(Elf::col) } proposes.forEach { it.value.clear() } elves.forEach { elf -> var matches = 0 var firstMatch: Point? = null for (check in checkOrder.indices) { val checkSideIdx = (checkStart + check) % checkOrder.size val checkSide = checkOrder[checkSideIdx] if (checkSide.none { shift -> elvesMap.anyAt(elf.row + shift.row, elf.col + shift.col) }) { matches++ if (firstMatch == null) firstMatch = elf + checkSide[1] } } if (matches < 4 && firstMatch != null) { proposes.getOrPut(firstMatch) { mutableListOf() } .add(elf) } } }
0
Kotlin
0
0
b8f30b055f8ca9360faf0baf854e4a3f31615081
3,482
advent-of-code-2022
Apache License 2.0
kotlin/app/src/main/kotlin/coverick/aoc/day1/calorieCounting.kt
RyTheTurtle
574,328,652
false
{"Kotlin": 82616}
package coverick.aoc.day1; import readResourceFile private val INPUT_FILE = "calorieCounting-input.txt" /* The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input). The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's inventory (if any) by a blank line. For example, suppose the Elves finish writing their items' Calories and end up with the following list: 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 This list represents the Calories of the food carried by five Elves: The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories. The second Elf is carrying one food item with 4000 Calories. The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories. The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories. The fifth Elf is carrying one food item with 10000 Calories. In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf). Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? --- Part Two --- By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most Calories of food might eventually run out of snacks. To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups. In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves is 45000. Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? */ private fun getElfCalorieCounts(elfInput:List<String>): List<Int> { val elves = ArrayList<Int>() var currentElfCalorieCount = 0 elfInput.forEach({ if(it.isNullOrBlank()){ elves.add(currentElfCalorieCount) currentElfCalorieCount = 0 } else { currentElfCalorieCount += Integer.valueOf(it) } }) return elves } fun calorieCountingSolutionPart1() : Int{ val fileLines = readResourceFile(INPUT_FILE) val elfCalorieCounts = getElfCalorieCounts(fileLines) return elfCalorieCounts.maxOrNull()?:0 } fun calorieCountingSolutionPart2(): Int{ val fileLines = readResourceFile(INPUT_FILE) val elfCalorieCounts = getElfCalorieCounts(fileLines).sortedDescending() var calorieSum = 0 for(i in 0..2){ if(i < elfCalorieCounts.size){ calorieSum += elfCalorieCounts[i] } } return calorieSum } fun solution(){ println("Calorie Counting Part 1 Solution: ${calorieCountingSolutionPart1()}") println("Calorie Counting Part 2 Solution: ${calorieCountingSolutionPart2()}") }
0
Kotlin
0
0
35a8021fdfb700ce926fcf7958bea45ee530e359
3,586
adventofcode2022
Apache License 2.0
src/main/kotlin/year2022/day13/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2022.day13 import IProblem class Problem : IProblem { private val lines = javaClass .getResource("/2022/13.txt")!! .readText() .lines() .filter(String::isNotEmpty) .map { parseList(it.toCharArray()) } private fun getClosingBracket(chars: CharArray, i: Int): Int { var brackets = 1 var j = i + 1 while (brackets != 0) { if (chars[j] == '[') { brackets++ } else if (chars[j] == ']') { brackets-- } j++ } return j } private fun parseList(chars: CharArray): List<Any> { if (chars.size == 2) { return emptyList() } val list = mutableListOf<Any>() var n = 0 var i = 1 while (i < chars.size) { when (val c = chars[i]) { '[' -> { val j = getClosingBracket(chars, i) list.add(parseList(chars.sliceArray(i until j))) i = j } ',', ']' -> { list.add(n) n = 0 } else -> { n = n * 10 + c.digitToInt() } } i++ } return list } private fun compare(a: Any, b: Any): Int { if (a is Int && b is Int) { return a.compareTo(b) } val l1 = if (a is List<*>) a else listOf(a) val l2 = if (b is List<*>) b else listOf(b) var i = 0 var j = 0 while (i < l1.size && j < l2.size) { val diff = compare(l1[i]!!, l2[j]!!) if (diff != 0) return diff i++ j++ } return l1.size.compareTo(l2.size) } override fun part1(): Int { return lines .chunked(2) .mapIndexed { i, (a, b) -> if (compare(a, b) < 0) i + 1 else 0 } .sum() } override fun part2(): Int { val list = lines.toMutableList() val key1 = listOf(listOf(2)) val key2 = listOf(listOf(6)) list.add(key1) list.add(key2) list.sortWith { a, b -> compare(a, b) } return list.indexOf(key1).plus(1) * list.indexOf(key2).plus(1) } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
2,339
advent-of-code
The Unlicense
src/Day20.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
import kotlin.math.abs fun main() { fun printList(startingNode: EncryptionNode) { print(" ${startingNode.number}") var current = startingNode.next while(current != startingNode) { print(", ${current!!.number}") current = current.next } println() } fun parse(input: List<String>, multiplier: Long): List<EncryptionNode> { val nodes = input.map { EncryptionNode(it.toLong() * multiplier) } for(i in 1 until nodes.size-1) { nodes[i-1].next = nodes[i] nodes[i].previous = nodes[i-1] nodes[i+1].previous = nodes[i] nodes[i].next = nodes[i+1] } nodes[0].previous = nodes[nodes.size-1] nodes[nodes.size-1].next = nodes[0] return nodes } fun mix(nodes: List<EncryptionNode>) { for(node in nodes) { //println("Moving ${node.number}") val move = node.number.let { val adjusted = it % (nodes.size-1) // Avoid multiple wraparounds //println(" Wraparound move adjusted to $adjusted") adjusted }.let { // Check if moving the opposite direction is shorter val directionAdjust = if (it < 0) { val oppositeMove = (nodes.size-1) + it if (oppositeMove < abs(it)) { oppositeMove } else { it } } else if (it > 0) { val oppositeMove = it - (nodes.size-1) if (abs(oppositeMove) < it) { //println("$oppositeMove is faster than $it") oppositeMove } else { it } } else { 0 } //println(" Direction move adjusted to $directionAdjust") directionAdjust } if (move != 0L) { // Cut the node out for the move node.previous!!.next = node.next node.next!!.previous = node.previous var current = node if (move < 0) { // Go through 'previous' links for (i in 0 until abs(move)) { current = current.previous!! } } else { // Go through 'next'' links for (i in 0 until move) { current = current.next!! } current = current.next!! // One more to adjust for general linkage } // Insert the node node.next = current node.previous = current.previous current.previous!!.next = node current.previous = node } //printList(nodes.first()) } } fun sumAnswerNodes(nodes: List<EncryptionNode>): Long { var sum = 0L val zeroNode = nodes.find { it.number == 0L }!! var current = zeroNode repeat(3) { repeat(1000) { current = current.next!! } //println(current.number) sum += current.number } return sum } fun part1(input: List<String>): Long { val nodes = parse(input, 1L) //printList(nodes.first()) mix(nodes) return sumAnswerNodes(nodes) } fun part2(input: List<String>): Long { val nodes = parse(input, 811589153L) //printList(nodes.first()) repeat(10) { mix(nodes) } return sumAnswerNodes(nodes) } val testInput = readInput("Day20_test") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) } data class EncryptionNode( val number: Long ) { var previous: EncryptionNode? = null var next: EncryptionNode? = null }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
4,153
aoc2022
Apache License 2.0
src/Day04.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
fun main() { fun part1(input: List<String>): Int { var count = 0 for (line in input) { val (range1, range2) = line.split(",") val (start1, end1) = range1.split("-").map { it.toInt() } val (start2, end2) = range2.split("-").map { it.toInt() } if ((start1 <= start2 && end1 >= end2) || (start2 <= start1 && end2 >= end1)) count++ } return count } fun part2(input: List<String>): Int { var count = 0 for (line in input) { val (range1, range2) = line.split(",") val (start1, end1) = range1.split("-").map { it.toInt() } val (start2, end2) = range2.split("-").map { it.toInt() } if (end1 < start2 || end2 < start1) continue count++ } return count } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
923
Advent-Of-Code-2022
Apache License 2.0
2022/src/day05/day05.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day05 import GREEN import RESET import printTimeMillis import readInput const val letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" fun buildStacks(input: List<String>): MutableList<MutableList<Char>> { val stacks = mutableListOf<MutableList<Char>>() input.forEach { s -> for (i in 1..s.lastIndex step 4) { if (letters.contains(s[i])) { val stackNb = i / 4 if (stacks.size <= stackNb) { stacks.add(stackNb, mutableListOf()) } stacks[stackNb].add(s[i]) } } } return stacks } fun executeInstructions( instructions: List<String>, stacks: MutableList<MutableList<Char>>, keepInPlace: Boolean = false ) { for (inst in instructions) { val (nb, from, to) = inst.split(" ").let { listOf(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1) } if (!keepInPlace) { for (i in 0 until nb) { stacks[to].add(stacks[from].removeLast()) } } else { val toTransfer = stacks[from].takeLast(nb) stacks[to].addAll(toTransfer) stacks[from] = stacks[from].take(stacks[from].size - toTransfer.size).toMutableList() } } } fun part1(input: List<String>): String { val delimiter = input.indexOfFirst { it.isEmpty() } val stacks = buildStacks(input.subList(0, delimiter - 1).reversed()) executeInstructions(input.subList(delimiter + 1, input.size), stacks) return stacks.map { it.last() }.joinToString("") } fun part2(input: List<String>): String { val delimiter = input.indexOfFirst { it.isEmpty() } val stacks = buildStacks(input.subList(0, delimiter - 1).reversed()) executeInstructions(input.subList(delimiter + 1, input.size), stacks, true) return stacks.map { it.last() }.joinToString("") } fun main() { val testInput = readInput("day05_example.txt", false) printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day05.txt", false) printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,331
advent-of-code
Apache License 2.0
src/main/kotlin/day19/part2/Part2.kt
bagguley
329,976,670
false
null
package day19.part2 import java.util.* val ruleMap: MutableMap<Int, Rule> = mutableMapOf() fun main() { val rules = parseRules(data2[0].split("\n")) val input = parseInput(data2[1].split("\n")) for (rule in rules) { ruleMap[rule.index] = rule } val valid = ruleMap[0]!!.validStrings(ruleMap) println("Valid size " + valid.size) val mInput = input.toMutableList() println("input size " + input.size) mInput.removeAll(valid) println("minput size " + mInput.size) val x42 = ruleMap[42]!!.validStrings(ruleMap) val regStr42 = StringJoiner("|", "^(", ")+") for (a in x42) { regStr42.add(a) } val reg8 = regStr42.toString() val x31 = ruleMap[31]!!.validStrings(ruleMap) for (i in 1..120) { val regstr42 = StringJoiner("|", "(", "){$i}+") for (a in x42) { regstr42.add(a) } val regstr31 = StringJoiner("|", "(", "){$i}+") for (a in x31) { regstr31.add(a) } val s = "^$reg8$regstr42$regstr31$" val r4231 = Regex(s) mInput.removeIf { it.matches(r4231) } } println("minput size " + mInput.size) println(input.size - mInput.size) } fun parseInput(input: List<String>): List<String> { return input.filter { it.isNotEmpty() } } fun parseRules(input: List<String>): List<Rule> { return input.filter { it.isNotEmpty() }.map{parseRule(it)}.sortedBy { it.index } } fun parseRule(input: String): Rule { val split = input.split(": ") val index = split[0].toInt() val rule = split[1] return parseRuleString(index, rule) } fun parseRuleString(index: Int, rule: String): Rule { return if (rule.contains("\"")) { StringRule(index, rule.substring(1, rule.length-1)) } else { if (rule.contains("|")) { val leftRule = rule.split(" | ")[0] val rightRule = rule.split(" | ")[1] OrRule(index, leftRule, rightRule) } else { PairRule(index, rule) } } } //Valid size 2097152 //input size 475 //minput size 234 //minput size 228
0
Kotlin
0
0
6afa1b890924e9459f37c604b4b67a8f2e95c6f2
2,125
adventofcode2020
MIT License
src/day02/day02.kt
tmikulsk1
573,165,106
false
{"Kotlin": 25281}
package day02 import day02.Constants.CommandSymbols import day02.Constants.DEFAULT_VALUE import day02.Constants.DRAW_EARNING_POINT import day02.Constants.InterpretedSymbols import day02.Constants.PAPER_POINT_VALUE import day02.Constants.PAPER_SYMBOL import day02.Constants.ROCK_POINT_VALUE import day02.Constants.ROCK_SYMBOL import day02.Constants.SCISSOR_POINT_VALUE import day02.Constants.SCISSOR_SYMBOL import day02.Constants.WIN_EARNING_POINT import readInput /** * Advent of Code 2022 - Day 2 * @author tmikulsk1 */ fun main() { val inputGame = readInput("day02/input.txt").readLines() getPuzzle1TotalScore(inputGame) getPuzzle2TotalScore(inputGame) } /** * Puzzle1: get total score and print */ fun getPuzzle1TotalScore(inputGameChart: List<String>) { val matches = getIncompleteConvertedGameChart(inputGameChart) val totalScore = sumTotalScore(matches) println(totalScore) } /** * Puzzle2: get total score and print */ fun getPuzzle2TotalScore(inputGameChart: List<String>) { val matches = getFullConvertedGameChart(inputGameChart) val totalScore = sumTotalScore(matches) println(totalScore) } /** * Paper, Rock & Scissor game logic sum total score * from ultra top secret strategy guide */ fun sumTotalScore(matches: List<HashMap<Int, Int>>): Int { var score = 0 matches.forEachIndexed { index, match -> val opponentValue = match.keys.first() val ownValue = match.values.first() val earningPoint = getEarningPoint(opponentValue, ownValue) score += earningPoint + ownValue } return score } /** * When next (from opponent) in circular list from Paper, Rock & Scissor logic is * equals with my own value, opponent wins * * When both values are equal, is a draw * * When next (from opponent) in circular list from Paper, Rock & Scissor logic is * difference with my own value, I win */ fun getEarningPoint(opponentValue: Int, ownValue: Int): Int { val next = getNextValueInCircularCycle(opponentValue) return if (opponentValue == ownValue) { // WE DRAW DRAW_EARNING_POINT } else if (next == ownValue) { // I WON WIN_EARNING_POINT } else { // I LOST DEFAULT_VALUE } } /** * Return the value from the circular list in Paper, Rock & Scissor sequence */ fun getNextValueInCircularCycle(opponentValue: Int): Int { val cycle = listOf(ROCK_POINT_VALUE, PAPER_POINT_VALUE, SCISSOR_POINT_VALUE) val index = cycle.indexOf(opponentValue) return if (cycle.size - 1 == index) { cycle[0] } else { cycle[index + 1] } } /** * Puzzle 1: without knowing the meaning of the second element from match */ fun getIncompleteConvertedGameChart(inputGameChart: List<String>): List<HashMap<Int, Int>> { return inputGameChart.splitGameChart().map { value -> val opponentValue = value[0].convertSymbolToPointValue() val ownValue = value[1].convertInterpretedSymbolToPointValue() hashMapOf(opponentValue to ownValue) } } /** * Puzzle 2: with all instructions for the match */ fun getFullConvertedGameChart(inputGameChart: List<String>): List<HashMap<Int, Int>> { return inputGameChart.splitGameChart().map { value -> val opponentValue = value[0].convertSymbolToPointValue() val ownValue = value[1].convertCommandSymbolToPointValue(opponentValue) hashMapOf(opponentValue to ownValue) } } fun List<String>.splitGameChart(): List<List<String>> = map { line -> line.split(" ") } fun String.convertSymbolToPointValue(): Int { return when { compareString(ROCK_SYMBOL) -> ROCK_POINT_VALUE compareString(PAPER_SYMBOL) -> PAPER_POINT_VALUE compareString(SCISSOR_SYMBOL) -> SCISSOR_POINT_VALUE else -> DEFAULT_VALUE } } fun String.convertInterpretedSymbolToPointValue(): Int { return when { compareString(InterpretedSymbols.ROCK_SYMBOL) -> ROCK_POINT_VALUE compareString(InterpretedSymbols.PAPER_SYMBOL) -> PAPER_POINT_VALUE compareString(InterpretedSymbols.SCISSOR_SYMBOL) -> SCISSOR_POINT_VALUE else -> DEFAULT_VALUE } } fun String.convertCommandSymbolToPointValue(opponentValue: Int): Int { return when { compareString(CommandSymbols.DRAW_SYMBOL) -> opponentValue compareString(CommandSymbols.LOSE_SYMBOL) -> { return when (opponentValue) { ROCK_POINT_VALUE -> SCISSOR_POINT_VALUE PAPER_POINT_VALUE -> ROCK_POINT_VALUE SCISSOR_POINT_VALUE -> PAPER_POINT_VALUE else -> DEFAULT_VALUE } } compareString(CommandSymbols.WIN_SYMBOL) -> { return when (opponentValue) { ROCK_POINT_VALUE -> PAPER_POINT_VALUE PAPER_POINT_VALUE -> SCISSOR_POINT_VALUE SCISSOR_POINT_VALUE -> ROCK_POINT_VALUE else -> DEFAULT_VALUE } } else -> DEFAULT_VALUE } } fun String.compareString(value: String) = equals(value, ignoreCase = true) object Constants { const val ROCK_POINT_VALUE = 1 const val PAPER_POINT_VALUE = 2 const val SCISSOR_POINT_VALUE = 3 const val DEFAULT_VALUE = 0 const val ROCK_SYMBOL = "A" const val PAPER_SYMBOL = "B" const val SCISSOR_SYMBOL = "C" const val WIN_EARNING_POINT = 6 const val DRAW_EARNING_POINT = 3 /** * Puzzle 1: interpreted strategy guide */ object InterpretedSymbols { const val ROCK_SYMBOL = "X" const val PAPER_SYMBOL = "Y" const val SCISSOR_SYMBOL = "Z" } /** * Puzzle 2: presented full strategy guide */ object CommandSymbols { const val LOSE_SYMBOL = "X" const val DRAW_SYMBOL = "Y" const val WIN_SYMBOL = "Z" } }
0
Kotlin
0
1
f5ad4e601776de24f9a118a0549ac38c63876dbe
5,846
AoC-22
Apache License 2.0
src/Day14.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
open class Point(val x: Int, val y: Int): Comparable<Point> { open val char = '~' override fun toString(): String { return "($x, $y)" } override fun compareTo(other: Point): Int { return if (x < other.x || x == other.x && y < other.y) { -1 } else if (x == other.x && y == other.y) { 0 } else { 1 } } } class Wall(x: Int, y: Int): Point(x, y) { override val char = '#' constructor(s: String): this(s.split(",")[0].toInt(), s.split(",")[1].toInt()) fun pointsBetween(other: Point): List<Point> { return if (x == other.x) { IntRange(minOf(y, other.y), maxOf(y, other.y)).map { Wall(x, it) } } else { IntRange(minOf(x, other.x), maxOf(x, other.x)).map { Wall(it, y) } } } } class Sand(x: Int, y: Int): Point(x, y) { override val char = 'o' } object Origin: Point(500, 0) { override val char = '+' } fun main() { fun print(obstacles: MutableSet<Point>) { for (x in obstacles.minOf { it.x }..obstacles.maxOf { it.x }) { print((x / 100) % 10) } println() for (x in obstacles.minOf { it.x }..obstacles.maxOf { it.x }) { print((x / 10) % 10) } println() for (x in obstacles.minOf { it.x }..obstacles.maxOf { it.x }) { print(x % 10) } println() for (y in obstacles.minOf { it.y }..obstacles.maxOf { it.y }) { for (x in obstacles.minOf { it.x }..obstacles.maxOf { it.x }) { val char = obstacles.find { it.x == x && it.y == y}?.char ?: '.' print(char) } println(y) } } fun drop(curPos: Point, obstacles: MutableSet<Point>, trace: Boolean): Boolean { if (curPos.y > obstacles.filterIsInstance<Wall>().maxOf { it.y }) { return false } val below = Point(curPos.x, curPos.y + 1) if (below !in obstacles) { if (trace) obstacles.add(below) return drop(below, obstacles, trace) } val belowLeft = Point(curPos.x - 1, curPos.y + 1) if (belowLeft !in obstacles) { if (trace) obstacles.add(belowLeft) return drop(belowLeft, obstacles, trace) } val belowRight = Point(curPos.x + 1, curPos.y + 1) if (belowRight !in obstacles) { if (trace) obstacles.add(belowRight) return drop(belowRight, obstacles, trace) } obstacles.add(Sand(curPos.x, curPos.y)) return true } fun genWalls(input: List<String>): MutableSet<Point> { val walls = sortedSetOf<Point>() input.forEach { line -> val stops = line.split(" -> ") var curPoint = Wall(stops[0]) walls.add(curPoint) line.split(" -> ").forEach { val nextPoint = Wall(it) walls.addAll(curPoint.pointsBetween(nextPoint)) curPoint = nextPoint } } println(walls.joinToString(", ", "[", "]")) println("Min : (${walls.minOf { it.x }}, ${walls.minOf { it.y }})") println("Max : (${walls.maxOf { it.x }}, ${walls.maxOf { it.y }})") return walls } fun showNthSand(walls: MutableSet<Point>, n: Int) { repeat(n) { drop(Origin, walls, false) } drop(Origin, walls, true) print(walls) } fun part1(input: List<String>): Int { val walls = genWalls(input) var i = 0 while (drop(Origin, walls, false)) { ++i } return i } fun part2(input: List<String>): Int { val walls = genWalls(input) walls.addAll(Wall(300, 163).pointsBetween(Wall(700, 163))) var i = 0 while (Sand(500, 0) !in walls) { if (i > 0 && i % 1000 == 0) { print("...") println(i) } drop(Origin, walls, false) ++i } return i } val input = readInput("Day14") showNthSand(genWalls(input), 874) println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
4,216
aoc2022-kotlin
Apache License 2.0
src/shmulik/klein/day04/Day04.kt
shmulik-klein
573,426,488
false
{"Kotlin": 9136}
package shmulik.klein.day04 import readInput fun main() { val input = readInput("shmulik/klein/day04/Day04_test") val result1 = part1(input) println(result1) val result2 = part2(input) println(result2) } fun part2(input: List<String>): Int { var count = 0 for (line in input) { val ranges = line.split(",", "-") if ((ranges[0].toInt() >= ranges[2].toInt()) && (ranges[0].toInt() <= ranges[3].toInt()) || ((ranges[1].toInt() >= ranges[2].toInt()) && (ranges[1].toInt() <= ranges[3].toInt()) || (ranges[0].toInt() <= ranges[2].toInt() && ranges[1].toInt() >= ranges[3].toInt())) ) { count++ println("${ranges[0]}, ${ranges[1]}, ${ranges[2]}, ${ranges[3]}") } } return count } fun part1(input: List<String>): Int { var count = 0 for (line in input) { val ranges = line.split(",", "-") if ((ranges[2].toInt() <= ranges[0].toInt() && (ranges[1].toInt() <= ranges[3].toInt())) || (ranges[0].toInt() <= ranges[2].toInt() && ranges[1].toInt() >= ranges[3].toInt())) { count++ // println("${ranges[0]}, ${ranges[1]}, ${ranges[2]}, ${ranges[3]}") } } return count }
0
Kotlin
0
0
4d7b945e966dad8514ec784a4837b63a942882e9
1,228
advent-of-code-2022
Apache License 2.0
advent-of-code-2023/src/main/kotlin/Day12.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
// Day 12: Hot Springs // https://adventofcode.com/2023/day/12 import java.io.File private const val WORKING = "." private const val BROKEN = "#" private const val UNKNOWN = "?" fun main() { val rows = File("src/main/resources/Day12.txt").readLines() val sumOfPossileArrangements = rows.sumOf { row -> val (records, arrangement) = row.split(" ") getPossibleArrangemnts(records, arrangement.split(",").map { it.toInt() }) } println(sumOfPossileArrangements) } private fun getPossibleArrangemnts(records: String, arrangement: List<Int>): Int { var count = 0 val index = records.indexOf(UNKNOWN) count += count(records.replaceRange(index..index, WORKING), arrangement) count += count(records.replaceRange(index..index, BROKEN), arrangement) return count } private fun count(records: String, arrangement: List<Int>): Int { var count = 0 if (records.contains(UNKNOWN).not() && arrangement == records.split(WORKING) .filter { record -> record.contains(BROKEN) } .map { record -> record.count { it == BROKEN.first() } } ) { count++ } if (records.contains(UNKNOWN)) { val index = records.indexOf(UNKNOWN) count += count(records.replaceRange(index..index, WORKING), arrangement) count += count(records.replaceRange(index..index, BROKEN), arrangement) } return count }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
1,414
advent-of-code
Apache License 2.0
kotlin/src/2022/Day20_2022.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
fun main() { val input = readInput(20).trim().lines() .map {it.toInt()} val N = input.size val idxes = listOf(1000, 2000, 3000) fun solve(x: MutableList<Pair<Long, Int>>, rep: Int = 1): Long { repeat(rep) { for (i in 0 until N) { // find where's the item originally at index `i` var j = 0 while (x[j].second != i) j++ // N-1 rotations don't do anything in either direction val rot = x[j].first % (N - 1) var nj = j + rot // if rotation happens at the end, jumping one more pos (as in the examples) ... if (nj < 0 || (nj == 0L && j != 0)) nj -= 1 else if (nj >= N) nj += 1 val jj = ((nj + N) % N).toInt() val curr = x[j] if (jj > j) { for (k in j until jj) x[k] = x[k+1] } else { for (k in j downTo jj + 1) x[k] = x[k-1] } x[jj] = curr } } val zero = x.indexOfFirst {it.first == 0L} return idxes.sumOf { x[(zero + it) % N].first } } // part1 val x1 = input.withIndex().map {it.value.toLong() to it.index}.toMutableList() println(solve(x1)) // part2 val x2 = input.withIndex().map {it.value.toLong() * 811589153 to it.index}.toMutableList() println(solve(x2, 10)) }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
1,455
adventofcode
Apache License 2.0
src/Day01.kt
othimar
573,607,284
false
{"Kotlin": 14557}
fun main() { fun part1(input: List<String>): Int { val data: ArrayList<ArrayList<Int>> = ArrayList() data.add(ArrayList()) for (str in input) { if (str.isBlank()) { data.add(ArrayList()) } else { data.last().add(str.toInt()) } } return data.map { it.sum() }.max() } fun part2(input: List<String>): Int { val data: ArrayList<ArrayList<Int>> = ArrayList() data.add(ArrayList()) for (str in input) { if (str.isBlank()) { data.add(ArrayList()) } else { data.last().add(str.toInt()) } } val dataSum = data.map { it.sum() } return with(dataSum.sorted()) { val first = this.last() val second = this[dataSum.size - 2] val third = this[dataSum.size - 3] first + second + third } } check(part1(readInput("Day01_test")) == 24000) check(part2(readInput("Day01_test")) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ff62a00123fe817773ff6248d34f606947ffad6d
1,166
advent-of-code-2022
Apache License 2.0
src/day22/Day22.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day22 import readInput typealias InputType = Triple<Map<Pair<Int, Int>, Node>, List<Instruction>, Pair<Int, Int>> enum class Direction(val score: Int) { N(3), S(1), W(2), E(0); fun rotate(direction: RotationDirection): Direction = when (direction) { RotationDirection.R -> rotateRight() RotationDirection.L -> rotateLeft() } private fun rotateLeft(): Direction = when (this) { S -> E W -> S N -> W E -> N } private fun rotateRight(): Direction = when (this) { N -> E E -> S S -> W W -> N } } abstract class Instruction data class Rotate(val direction: RotationDirection) : Instruction() data class Move(val steps: Int) : Instruction() enum class RotationDirection { R, L } data class Actor( val graph: Map<Pair<Int, Int>, Node>, var pos: Pair<Int, Int>, var facingDirection: Direction = Direction.E ) { fun move(steps: Int) { repeat(steps) { val (pos, facingDirection) = graph[pos]!!.move(facingDirection) this.pos = pos this.facingDirection = facingDirection } } fun rotate(direction: RotationDirection) { facingDirection = facingDirection.rotate(direction) } fun getScore(): Int = 1000 * (pos.first + 1) + 4 * (pos.second + 1) + facingDirection.score } data class Node(val neighbors: Map<Direction, Pair<Pair<Int, Int>, Direction>>, val pos: Pair<Int, Int>) { fun move(direction: Direction): Pair<Pair<Int, Int>, Direction> = neighbors.getOrDefault(direction, pos to direction) } fun main() { fun solve(input: InputType): Int { val (graph, instructions, start) = input val actor = Actor(graph, start) instructions.forEach { when (it) { is Rotate -> actor.rotate(it.direction) is Move -> actor.move(it.steps) } } return actor.getScore() } fun wrapPart1(pos: Pair<Int, Int>, direction: Direction): Pair<Pair<Int, Int>, Direction> { val (y, x) = pos return when (direction) { Direction.N -> if (x in 0 until 50 && y == 100) (199 to x) to direction else if (x in 50 until 100 && y == 0) (149 to x) to direction else if (x in 100 until 150 && y == 0) (49 to x) to direction else (y - 1 to x) to direction Direction.S -> if (x in 0 until 50 && y == 199) (100 to x) to direction else if (x in 50 until 100 && y == 149) (0 to x) to direction else if (x in 100 until 150 && y == 49) (0 to x) to direction else (y + 1 to x) to direction Direction.W -> if (y in 0 until 50 && x == 50) (y to 149) to direction else if (y in 50 until 100 && x == 50) (y to 99) to direction else if (y in 100 until 150 && x == 0) (y to 99) to direction else if (y in 150 until 200 && x == 0) (y to 49) to direction else (y to x - 1) to direction Direction.E -> if (y in 0 until 50 && x == 149) (y to 50) to direction else if (y in 50 until 100 && x == 99) (y to 50) to direction else if (y in 100 until 150 && x == 99) (y to 0) to direction else if (y in 150 until 200 && x == 49) (y to 0) to direction else (y to x + 1) to direction } } fun wrapPart2(pos: Pair<Int, Int>, direction: Direction): Pair<Pair<Int, Int>, Direction> { val (y, x) = pos return when (direction) { Direction.N -> if (x in 0 until 50 && y == 100) (50 + x to 50) to Direction.E else if (x in 50 until 100 && y == 0) (150 + (x - 50) to 0) to Direction.E else if (x in 100 until 150 && y == 0) (199 to x - 100) to Direction.N else (y - 1 to x) to direction Direction.S -> if (x in 0 until 50 && y == 199) (0 to x + 100) to Direction.S else if (x in 50 until 100 && y == 149) (150 + x - 50 to 49) to Direction.W else if (x in 100 until 150 && y == 49) (50 + x - 100 to 99) to Direction.W else (y + 1 to x) to direction Direction.W -> if (y in 0 until 50 && x == 50) (149 - y to 0) to Direction.E else if (y in 50 until 100 && x == 50) (100 to y - 50) to Direction.S else if (y in 100 until 150 && x == 0) (49 - (y - 100) to 50) to Direction.E else if (y in 150 until 200 && x == 0) (0 to 50 + (y - 150)) to Direction.S else (y to x - 1) to direction Direction.E -> if (y in 0 until 50 && x == 149) (149 - y to 99) to Direction.W else if (y in 50 until 100 && x == 99) (49 to 100 + (y - 50)) to Direction.N else if (y in 100 until 150 && x == 99) (49 - (y - 100) to 149) to Direction.W else if (y in 150 until 200 && x == 49) (149 to 50 + (y - 150)) to Direction.N else (y to x + 1) to direction } } fun preprocess( input: List<String>, wrapper: (Pair<Int, Int>, Direction) -> Pair<Pair<Int, Int>, Direction> ): InputType { val instructions = input.last().replace("R", ",R,").replace("L", ",L,").split(",").map { if (it == "L" || it == "R") { Rotate(RotationDirection.valueOf(it)) } else { Move(it.toInt()) } } val map = mutableMapOf<Pair<Int, Int>, Node>() val maxRow = input.slice(0 until input.size - 2).maxOf { it.length } val mapRaw = input.slice(0 until input.size - 2).map { it.padEnd(maxRow) } for (x in mapRaw.indices) { for (y in mapRaw[x].indices) { if (mapRaw[x][y] == '.') { val pos = x to y val neighbors = Direction.values().associateWith { wrapper(pos, it) } .filterValues { mapRaw[it.first.first][it.first.second] == '.' } map[pos] = Node(neighbors, pos) } } } return Triple(map, instructions, Pair(0, input[0].indexOf('.'))) } // test if implementation meets criteria from the description, like: val input = readInput(22) println(solve(preprocess(input) { pos, direction -> wrapPart1(pos, direction) })) println(solve(preprocess(input) { pos, direction -> wrapPart2(pos, direction) })) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
6,675
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/colinodell/advent2022/Day07.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 class Day07(input: List<String>) { private val root = Directory() init { var currentDir = root // Assume the first line is the root, so skip it for (line in input.drop(1)) { val parts = line.split(" ") when (true) { (line == "$ cd ..") -> currentDir = currentDir.parent!! (parts[1] == "cd") -> currentDir = currentDir.children[parts[2]]!! (parts[1] == "ls") -> null // no-op (parts[0] == "dir") -> currentDir.addChild(parts[1]) (parts.size == 2) -> currentDir.fileSize += parts[0].toInt() else -> throw IllegalArgumentException("Unknown operation: $line") } } } fun solvePart1() = iterateDirectories(root) .filter { it.totalSize() <= 100000 } .sumOf { it.totalSize() } fun solvePart2(): Int { val freeSpace = 70000000 - root.totalSize() val neededSpace = 30000000 return iterateDirectories(root) .filter { freeSpace + it.totalSize() >= neededSpace } .sortedBy { it.totalSize() } .first() .totalSize() } class Directory(val parent: Directory? = null) { val children = mutableMapOf<String, Directory>() var fileSize: Int = 0 fun addChild(name: String) { children[name] = Directory(this) } fun totalSize(): Int = fileSize + children.values.sumOf { it.totalSize() } } private fun iterateDirectories(root: Directory): Sequence<Directory> { return sequence { yield(root) for (child in root.children.values) { yieldAll(iterateDirectories(child)) } } } }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
1,802
advent-2022
MIT License
src/Day03.kt
novotnyradekcz
579,767,169
false
{"Kotlin": 11517}
fun main() { fun part1(input: List<String>): Int { var total = 0 val lower = "abcdefghijklmnopqrstuvwxyz" val upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for (line in input) { var temp = ' ' for (i in 0 until line.length / 2) { for (j in line.length / 2 until line.length) { if (line[i] == line[j] && line[i] != temp) { if (line[i] in lower) total += lower.indexOf(line[i]) + 1 if (line[i] in upper) total += upper.indexOf(line[i]) + 27 temp = line[i] } } } } return total } fun part2(input: List<String>): Int { var total = 0 var i = 0 val lower = "abcdefghijklmnopqrstuvwxyz" val upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" while (i < input.size - 2) { var temp = ' ' for (j in lower) { if (j in input[i] && j in input[i + 1] && j in input[i + 2] && j != temp) { total += lower.indexOf(j) + 1 temp = j } } for (j in upper) { if (j in input[i] && j in input[i + 1] && j in input[i + 2] && j != temp) { total += upper.indexOf(j) + 27 temp = j } } i += 3 } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") part1(input).println() part2(input).println() }
0
Kotlin
0
0
2f1907dc63344cf536f5031bc7e1c61db03fc570
1,753
advent-of-code-kotlin-2022
Apache License 2.0
src/Day03.kt
LauwiMeara
572,498,129
false
{"Kotlin": 109923}
const val START_ASCII_UPPERCASE = 'A'.code const val START_ASCII_LOWERCASE = 'a'.code const val START_ITEM_UPPERCASE = 27 const val START_ITEM_LOWERCASE = 1 const val GROUP_SIZE = 3 fun main() { fun calculatePriority(item: Char) : Int{ return if (item.isUpperCase()) { item.code - START_ASCII_UPPERCASE + START_ITEM_UPPERCASE } else { item.code - START_ASCII_LOWERCASE + START_ITEM_LOWERCASE } } fun calculateSum(groups: List<List<String>>): Int { var sum = 0 for (group in groups) { for (item in group.first()) { if (group.all{it.contains(item)}) { sum += calculatePriority(item) break } } } return sum } fun part1(input: List<String>): Int { val rucksacks = input.map{it.chunked(it.length / 2)} return calculateSum(rucksacks) } fun part2(input: List<String>): Int { val elfGroups = input.windowed(GROUP_SIZE,GROUP_SIZE) return calculateSum(elfGroups) } val input = readInputAsStrings("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
34b4d4fa7e562551cb892c272fe7ad406a28fb69
1,199
AoC2022
Apache License 2.0
src/Day16b2.kt
jrmacgill
573,065,109
false
{"Kotlin": 76362}
import java.lang.Integer.max import java.lang.Integer.min class Day16b2 { val inputLineRegex = """Valve ([A-Z]*) has flow rate=(\d+); tunnel[s]? lead[s]? to valve[s]? (.*)""".toRegex() val data = mutableMapOf<String, Room>() val compactData = mutableMapOf<String, CompactRoom>() val maxTicks = 26 var best = 0 var options = mutableSetOf<List<Pair<String,Int>>>() class Room(val id : String, val flow : Int, val links : List<String>) { } class CompactRoom(val id : String, val flow : Int, val links : List<Pair<String,Int>>) { } fun step(room : CompactRoom , tick : Int, open : List<String>, history:List<Pair<String, Int>>, score:Int) { var nextOpen = open.toMutableList() var nextHistory = history.toMutableList() var cost = 0 var bonus = 0 if (tick >= maxTicks) { println("Done with: " + score) options.add(history) if (score > best) { best = score } return } if (!open.contains(room.id)) { nextOpen.add(room.id) cost+=1 bonus = room.flow*(maxTicks-(tick+1)) if (bonus > 0) { nextHistory.add(Pair(room.id, bonus)) } //step(room, tick+1,next, score + (room.flow*(maxTicks-(tick+1)))) } if (nextOpen.size == compactData.size) { println("All open with " + (score+bonus)) if (score+bonus > best) { best = score+bonus } options.add(history) return } room.links.forEach{ if (!open.contains(it.first)) { step(compactData[it.first.trim()]!!, tick + it.second+cost, nextOpen, nextHistory,score+bonus) } } } fun cost(room : String, target : String, visited : List<String>, cost: Int) : Int { if (room.trim() == target.trim()) return cost; var best = Int.MAX_VALUE data[room.trim()]!!.links.filter { r -> !visited.contains(r) }.forEach{ var c = cost(it, target, visited+room, cost+1) best = min(c, best) } return best } fun compact(room: Room) : CompactRoom{ //var visited = listOf<String>() var costLinks = mutableListOf<Pair<String, Int>>() data.forEach{ if (it.key != room.id) { if (data[it.key]!!.flow > 0) { var cost = cost(room.id, it.key, listOf(), 0) costLinks.add(Pair(it.key, cost)) } } } return CompactRoom(room.id, room.flow, costLinks) } fun parse(line : String) { val match = inputLineRegex .find(line)!! println(match) val (code, flow, links) = match.destructured data[code] = Room(code, flow.toInt(), links.split(",")) } fun go() { var lines =readInput("day16") lines.forEach(::parse) println("compacting") compactData["AA"] = compact(data["AA"]!!) data.forEach { if(it.value.flow > 0) { println("compact " + it.key) compactData[it.key] = compact(it.value) } } println("find:") step(compactData["AA"]!!, 0, listOf("AA"), listOf<Pair<String, Int>>(), 0) println(best) println(options.size) options.forEach(::println) var bestComboScore = 0 var bestCombo = mapOf<String, Int>() options.forEach{a-> options.forEach { b -> var combo = a.associateBy ( {it.first}, {it.second} ).toMutableMap() b.forEach{ if (it.second > combo[it.first]?:0) { combo[it.first] = it.second } } var score = combo.values.sum() if (score > bestComboScore) { bestComboScore = score bestCombo = combo println(bestCombo) } bestComboScore = max(combo.values.sum(), bestComboScore) //println(combo) } } println(bestComboScore) println(bestCombo) } } fun main() { Day16b2().go() }
0
Kotlin
0
1
3dcd590f971b6e9c064b444139d6442df034355b
4,359
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/days/Day4.kt
andilau
544,512,578
false
{"Kotlin": 29165}
package days import java.lang.IllegalArgumentException @AdventOfCodePuzzle( name = "Security Through Obscurity", url = "https://adventofcode.com/2016/day/4", date = Date(day = 4, year = 2016) ) class Day4(private val input: List<String>) : Puzzle { override fun partOne(): Int = input.map { Room.of(it) } .filter { it.isReal() } .sumOf { it.sectorId } override fun partTwo(): Int = input.map { Room.of(it) } .filter { it.isReal() } .firstOrNull { it.decrypt() == "northpole object storage" }?.sectorId ?: throw IllegalArgumentException() data class Room(val nameEncrypted: List<String>, val sectorId: Int, val checksum: String) { fun decrypt(): String { return nameEncrypted.joinToString("-") .let { ShiftCipher(sectorId).encode(it) } } fun isReal(): Boolean { return checksum() == checksum } private fun checksum(): String { val letterByCount: Map<Char, Int> = nameEncrypted.flatMap { it.asIterable() }.groupingBy { it }.eachCount() val letterCountSorted: List<Pair<Char, Int>> = letterByCount.toList() .sortedWith(Comparator.comparing<Pair<Char, Int>?, Int?> { it.second }.reversed().thenComparing(Comparator.comparing { it.first })) return letterCountSorted.map { it.first }.take(5).joinToString("") } companion object { fun of(line: String): Room { val nameAndId = line.substringBefore('[').split('-') val checksum = line.substringAfter('[').substringBefore(']') return Room(nameAndId.dropLast(1), nameAndId.last().toInt(), checksum) } } } class ShiftCipher(private val base: Int = 1) { fun encode(text: String): String = text.map { when (it) { in 'a'..'z' -> 'a' + (it - 'a' + base) % 26 '-' -> ' ' else -> it } }.joinToString("") } }
3
Kotlin
0
0
b2a836bd3f1c5eaec32b89a6ab5fcccc91b665dc
2,147
advent-of-code-2016
Creative Commons Zero v1.0 Universal
kotlin-java/src/main/kotlin/func/prog/java/recursion/ListExtn.kt
kogupta
150,227,783
false
{"Java": 533747, "Scala": 120497, "Kotlin": 23555}
package func.prog.java.recursion fun main(args: Array<String>) { println("abc".toList().head()) println(List(1) { 'a' }.mkString()) println(('a'..'z').asSequence().toList().mkString()) println("-- fold left --") println("Sum of [1..10] : " + sum2((1..10).toList())) println(List(1) { 'a' }.mkString2()) println(('a'..'z').asSequence().toList().mkString2()) println("-- that's all folds! --") } fun <T> List<T>.head(): T { require(isNotEmpty()) { "`head` of an empty list" } return first() } fun <T> List<T>.tail(): List<T> { require(isNotEmpty()) { "`tail` of an empty list" } return drop(1) } fun sum(xs: List<Int>): Int = if (xs.isEmpty()) 0 else xs.head() + sum(xs.tail()) fun sum2(xs: List<Int>): Int = xs.foldLeft(0) { a, b -> a + b } fun sumCoRec(xs: List<Int>): Int { tailrec fun helper(ns: List<Int>, acc: Int): Int = if (ns.isEmpty()) acc else helper(ns.tail(), ns.head() + acc) return helper(xs, 0) } fun <T> List<T>.mkString( prefix: String = "[", delim: String = ",", suffix: String = "]"): String { tailrec fun helper(xs: List<T>, acc: String): String = when { xs.isEmpty() -> acc xs.tail().isEmpty() -> acc + xs.head() else -> helper(xs.tail(), acc + xs.head() + delim) } return prefix + helper(this, "") + suffix } fun <T> List<T>.mkString2( prefix: String = "[", delim: String = ",", suffix: String = "]"): String { val s = foldLeft("") { acc, elem -> if (acc.isEmpty()) elem.toString() else acc + delim + elem.toString() } return prefix + s + suffix } /** * z -> zero value aka seed */ fun <T, U> List<T>.foldLeft(z: U, f: (U, T) -> U): U { tailrec fun helper(xs: List<T>, acc: U): U = when { xs.isEmpty() -> acc else -> helper(xs.tail(), f(acc, xs.head())) } return helper(this, z) } fun <T, U> List<T>.foldRight(z: U, f: (T, U) -> U): U = reversed().foldLeft(z) { u, t -> f(t, u) }
16
Java
0
0
aabace38199e695027969143e5955f8399d20dbf
2,108
misc-projects
The Unlicense
src/commonMain/kotlin/sequences/Last.kt
tomuvak
511,086,330
false
{"Kotlin": 92304, "Shell": 619}
package com.tomuvak.util.sequences /** * Returns a sequence containing all elements of the receiver sequence [this] except for the last [n] (which is not * allowed to be negative) ones (resulting in an empty sequence in case there are only [n] elements or less to begin * with). * * The resulting sequence has the same elements as the result of calling the standard library's * `.toList().dropLast(`[n]`)`, but is a sequence rather than a list, and it consumes the original sequence lazily * (though note it will always have consumed the [n] elements following any element it yields. In particular, when the * result is enumerated completely, the entire original sequence will have been enumerated as well, including the * dropped elements). * * For a given [n], any sequence is the concatenation of its [dropLast]`(n)` and its [takeLast]`(n)`. * * This operation is _intermediate_ and _stateful_. */ fun <T> Sequence<T>.dropLast(n: Int): Sequence<T> { require(n >= 0) { "Can't drop a negative number of elements ($n)" } return if (n == 0) this else Sequence { DropLastIterator(iterator(), n) } } private class DropLastIterator<T>(private val sourceIterator: Iterator<T>, private val n: Int): Iterator<T> { private var index: Int = -1 private var buffer: Array<Any?>? = null private fun ensureInitialized() { if (index == -1) { index = 0 val firstElements = arrayOfNulls<Any?>(n) buffer = firstElements for (i in 0 until n) if (sourceIterator.hasNext()) firstElements[i] = sourceIterator.next() else { buffer = null break } } } override fun hasNext(): Boolean { ensureInitialized() if (buffer == null) return false if (sourceIterator.hasNext()) return true buffer = null return false } override fun next(): T { ensureInitialized() if (buffer == null) throw NoSuchElementException() val nextSourceElement = try { sourceIterator.next() } catch (e: Throwable) { buffer = null throw e } val buffer = buffer!! @Suppress("UNCHECKED_CAST") return buffer[index].also { buffer[index++] = nextSourceElement index %= buffer.size } as T } } /** * Returns a sequence containing all elements of the receiver sequence [this] except for the longest suffix all of whose * elements satisfy the given [predicate] (in the extreme cases this can result in the whole original sequence in case * the last element does not satisfy the predicate, or in an empty sequence in case all elements satisfy it). * * The resulting sequence has the same elements as the result of calling the standard library's * `.toList().dropLastWhile(`[predicate]`)`, but is a sequence rather than a list, and it consumes the original sequence * lazily (though note that when it yields an element which satisfies the predicate, it will always have consumed the * elements immediately following it up to and including the first one which doesn't, and when the result is enumerated * completely, the entire original sequence will have been enumerated as well, including any dropped elements). Whether * that's preferable to calling `.toList().dropLastWhile(predicate)` for a particular use case or not depends on several * factors; this function enumerates the original sequence lazily, and does not hold more elements in memory at any * given time than it has to, but it computes the given [predicate] for each and every element, in iteration order, * whereas the version for lists computes the predicate for elements going from the end backwards, and stops at the * first (= last) element which does not satisfy it. * * For a given [predicate], any sequence is the concatenation of its [dropLastWhile]`(predicate)` and its * [takeLastWhile]`(predicate)`. * * This operation is _intermediate_ and _stateful_. */ fun <T> Sequence<T>.dropLastWhile(predicate: (T) -> Boolean): Sequence<T> = Sequence { DropLastWhileIterator(iterator(), predicate) } private class DropLastWhileIterator<T>( private val sourceIterator: Iterator<T>, private val predicate: (T) -> Boolean ) : Iterator<T> { private var buffer: ArrayDeque<T>? = ArrayDeque() private fun checkNext() { val buffer = buffer if (buffer == null || buffer.isNotEmpty()) return while (sourceIterator.hasNext()) { val next = sourceIterator.next().also(buffer::addLast) if (!predicate(next)) return } this.buffer = null } override fun hasNext(): Boolean { checkNext() return buffer != null } override fun next(): T { checkNext() val buffer = buffer return if (buffer == null) throw NoSuchElementException() else buffer.removeFirst() } } /** * Returns a list of the last [n] (which is not allowed to be negative) elements of the receiver sequence [this] * (resulting in a list of all elements in case there are only [n] elements or less to begin with). * * The result is the same as that of calling the standard library's `.toList().takeLast(`[n]`)`, but the computation is * less wasteful, as it never holds more than [n] elements in memory at any one time. * * For a given [n], any sequence is the concatenation of its [dropLast]`(n)` and its [takeLast]`(n)`. * * This operation is _terminal_ (as for a general sequence this cannot be computed without iterating over all of the * elements. For this reason it also returns the result as a list rather than as a sequence). */ fun <T> Sequence<T>.takeLast(n: Int): List<T> { require(n >= 0) { "Can't take a negative number of elements ($n)" } if (n == 0) return emptyList() val iterator = iterator() val buffer = ArrayList<T>(n) repeat(n) { if (!iterator.hasNext()) return@takeLast buffer buffer.add(iterator.next()) } var index = 0 while (iterator.hasNext()) { buffer[index++] = iterator.next() index %= n } return if (index == 0) buffer else buffer.subList(index, n) + buffer.subList(0, index) } /** * Returns the longest suffix of the receiver sequence [this] all of whose elements satisfy the given [predicate] (in * the extreme cases this can be empty if the last element does not satisfy the predicate, or the whole original * sequence in case all elements satisfy it), as a list. * * The result is the same as that of calling the standard library's `.toList().takeLastWhile(`[predicate]`)`. Which * option is preferable for a particular use case depends on several factors: this function does not hold more elements * in memory at any given time than it has to, but it computes the given [predicate] for each and every element, in * iteration order, whereas the version for lists computes the predicate for elements going from the end backwards, and * stops at the first (= last) element which does not satisfy it. * * For a given [predicate], any sequence is the concatenation of its [dropLastWhile]`(predicate)` and its * [takeLastWhile]`(predicate)`. * * This operation is _terminal_ (as for a general sequence this cannot be computed without iterating over all of the * elements. For this reason it also returns the result as a list rather than as a sequence). */ fun <T> Sequence<T>.takeLastWhile(predicate: (T) -> Boolean): List<T> { val buffer = mutableListOf<T>() for (element in this) if (predicate(element)) buffer.add(element) else buffer.clear() return buffer } /** * Returns the longest suffix of the receiver sequence [this] all of whose elements are of type [T]. * * This operation is _terminal_ (as for a general sequence this cannot be computed without iterating over all of the * elements. For this reason it also returns the result as a list rather than as a sequence). */ @Suppress("UNCHECKED_CAST") inline fun <reified T> Sequence<Any?>.takeLastWhileIsInstance(): List<T> = takeLastWhile { it is T } as List<T>
0
Kotlin
0
0
e20cfae9535fd9968542b901c698fdae1a24abc1
8,133
util
MIT License
src/Day11.kt
hoppjan
433,705,171
false
{"Kotlin": 29015, "Shell": 338}
typealias Octopuses = MutableMap<Point, Int> fun main() { fun part1(input: Octopuses) = input.flashingSequence() .take(100) .sum() fun part2(input: Octopuses) = input.flashingSequence() .takeWhile { it < input.size } .count() .plus(1) val day = "11" val testInput = OctopusesInputReader.read("Day${day}_test") val input = OctopusesInputReader.read("Day$day") // part 1 val testSolution1 = 1656 val testOutput1 = part1(testInput) printTestResult(1, testOutput1, testSolution1) check(testOutput1 == testSolution1) printResult(1, part1(input).also { check(it == 1723) }) // part 2 val testSolution2 = 195 val testOutput2 = part2(testInput) printTestResult(2, testOutput2, testSolution2) check(testOutput2 == testSolution2) printResult(2, part2(input).also { check(it == 327) }) } // COROUTINES! // Thanks to <NAME> for the blog article. I hope this is not too much of a copy :) private fun Octopuses.flashingSequence(): Sequence<Int> = sequence { val octopuses = toMutableMap() while (true) { octopuses.forEach { (point, energy) -> octopuses[point] = energy + 1 } val flashed = mutableSetOf<Point>() do { val currentFlashed = octopuses .filter { (it.value > 9) && (it.key !in flashed) } .keys .also { currentFlashed -> flashed.addAll(currentFlashed) currentFlashed .flatMap { it.neighbors() } .filter { (it in octopuses) && (it !in flashed) } .forEach { octopuses[it] = octopuses.getValue(it) + 1 } } } while (currentFlashed.isNotEmpty()) flashed.forEach { octopuses[it] = 0 } yield(flashed.size) } } private fun Point.neighbors(): List<Point> = listOf( Point(x, y + 1), Point(x, y - 1), Point(x + 1, y), Point(x - 1, y), Point(x - 1, y - 1), Point(x - 1, y + 1), Point(x + 1, y - 1), Point(x + 1, y + 1) )
0
Kotlin
0
0
04f10e8add373884083af2a6de91e9776f9f17b8
2,260
advent-of-code-2021
Apache License 2.0
year2022/src/cz/veleto/aoc/year2022/Day12.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay import cz.veleto.aoc.core.Pos class Day12(config: Config) : AocDay(config) { override fun part1(): String { val (nodes, start, end) = parseNodes() start.currentShortestPath = 0 val nodesToHandle = mutableListOf(start) while (nodesToHandle.isNotEmpty()) { val node = nodesToHandle.removeFirst() if (node == end) break val neighbors = findNeighbors(nodes, node) .filter { it.height - node.height <= 1 } explore(node, neighbors, nodesToHandle) } return end.currentShortestPath!!.toString() } override fun part2(): String { val (nodes, _, end) = parseNodes() end.currentShortestPath = 0 val nodesToHandle = mutableListOf(end) while (nodesToHandle.isNotEmpty()) { val node = nodesToHandle.removeFirst() if (node.height == 'a') return node.currentShortestPath!!.toString() val neighbors = findNeighbors(nodes, node) .filter { node.height - it.height <= 1 } explore(node, neighbors, nodesToHandle) } error("no 'a' found") } private fun parseNodes(): Triple<List<List<Node>>, Node, Node> { var start: Node? = null var end: Node? = null val nodes = input .mapIndexed { x, s -> s.mapIndexed { y, c -> when (c) { 'S' -> Node( pos = x to y, height = 'a', ).also { start = it } 'E' -> Node( pos = x to y, height = 'z', ).also { end = it } else -> Node( pos = x to y, height = c, ) } } } .toList() return Triple(nodes, start!!, end!!) } private fun findNeighbors(nodes: List<List<Node>>, current: Node): Sequence<Node> { val (x, y) = current.pos return sequenceOf( x - 1 to y, x to y - 1, x + 1 to y, x to y + 1, ).filter { (x, y) -> x in 0..nodes.lastIndex && y in 0..nodes[0].lastIndex } .map { (x, y) -> nodes[x][y] } } private fun explore(current: Node, neighbors: Sequence<Node>, nodesToHandle: MutableList<Node>) { val nextPathLength = current.currentShortestPath!! + 1 neighbors .filter { it.currentShortestPath?.let { pathLength -> pathLength > nextPathLength } ?: true } .forEach { nodesToHandle.remove(it) it.currentShortestPath = nextPathLength it.previousInPath = current nodesToHandle.add(it) } } private data class Node( val pos: Pos, val height: Char, var currentShortestPath: Int? = null, var previousInPath: Node? = null, ) }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
3,157
advent-of-pavel
Apache License 2.0
src/main/kotlin/Excercise09.kt
underwindfall
433,989,850
false
{"Kotlin": 55774}
private fun part1() { var ans = 0 val input = getInputAsTest("09") { split("\n") } val n = input.size val m = input[0].length for (i in 0 until n) { for (j in 0 until m) { val b = listOfNotNull( input[i].getOrNull(j + 1), input[i].getOrNull(j - 1), input.getOrNull(i - 1)?.get(j), input.getOrNull(i + 1)?.get(j) ) if (input[i][j] < b.minOrNull()!!) { ans += 1 + (input[i][j] - '0') } } } println("Part 1 $ans") } private fun part2() { val ans = mutableListOf<Int>() val input = getInputAsTest("09") { split("\n") } val n = input.size val m = input[0].length val u = Array(n) { BooleanArray(m) } fun dfs(i: Int, j: Int): Int { if (i < 0 || i >= n || j < 0 || j >= m || u[i][j] || input[i][j] == '9') return 0 u[i][j] = true return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i, j + 1) } for (i in 0 until n) { for (j in 0 until m) { if (!u[i][j] && input[i][j] != '9') { ans += dfs(i, j) } } } ans.sortDescending() println("Part 2 ${ans[0] * ans[1] * ans[2]}") } fun main() { part1() part2() }
0
Kotlin
0
0
4fbee48352577f3356e9b9b57d215298cdfca1ed
1,178
advent-of-code-2021
MIT License
day10/src/main/kotlin/com/lillicoder/adventofcode2023/day10/Day10.kt
lillicoder
731,776,788
false
{"Kotlin": 98872}
package com.lillicoder.adventofcode2023.day10 import com.lillicoder.adventofcode2023.grids.Direction import com.lillicoder.adventofcode2023.grids.Grid import com.lillicoder.adventofcode2023.grids.GridParser import com.lillicoder.adventofcode2023.grids.Node import kotlin.math.abs fun main() { val day10 = Day10() val maze = PipeMaze(GridParser().parseFile("input.txt").first()) println("The max distance for the loop in the pipe maze is ${day10.part1(maze)}.") println("The area of enclosures spaces is ${day10.part2(maze)}.") } class Day10 { fun part1(maze: PipeMaze) = Pathfinder().findLoopMaxDistance(maze) fun part2(maze: PipeMaze) = Pathfinder().findEnclosureArea(maze) } /** * Represents an arbitrary grid of pipes. It's not really a maze but whatever. */ data class PipeMaze(private val grid: Grid<String>) { private val validTops = mapOf( "|" to listOf("|", "7", "F", "S"), "-" to listOf(""), "L" to listOf("|", "7", "F", "S"), "J" to listOf("|", "7", "F", "S"), "7" to listOf(""), "F" to listOf(""), "S" to listOf("|", "7", "F", "S"), ) private val validBottoms = mapOf( "|" to listOf("|", "L", "J", "S"), "-" to listOf(""), "L" to listOf(""), "J" to listOf(""), "7" to listOf("|", "L", "J", "S"), "F" to listOf("|", "L", "J", "S"), "S" to listOf("|", "L", "J", "S"), ) private val validLefts = mapOf( "|" to listOf(""), "-" to listOf("-", "F", "L", "S"), "L" to listOf(""), "J" to listOf("-", "F", "L", "S"), "7" to listOf("-", "F", "L", "S"), "F" to listOf(""), "S" to listOf("-", "F", "L", "S"), ) private val validRights = mapOf( "|" to listOf(""), "-" to listOf("-", "7", "J", "S"), "L" to listOf("-", "7", "J", "S"), "J" to listOf(""), "7" to listOf(""), "F" to listOf("-", "7", "J", "S"), "S" to listOf("-", "7", "J", "S"), ) /** * Gets all valid adjacent [Node] for the given node. * @param node Node. * @return Valid adjacent nodes. */ fun adjacent(node: Node<String>) = // Only some kinds of values are legitimate adjacent nodes for the purposes of finding // distances, paths, enclosures, so filter the output from the underlying grid grid.adjacent(node) { adjacent, direction -> val validSymbols = when (direction) { Direction.LEFT -> validLefts Direction.UP -> validTops Direction.DOWN -> validBottoms Direction.RIGHT -> validRights else -> null } validSymbols?.get(node.value)?.contains(adjacent.value) ?: false } /** * Finds the first [Node] that satisfies the given predicate. * @param predicate Predicate to check. * @return Found node or null if no node satisfied the predicate. */ fun find(predicate: (String) -> Boolean): Node<String>? = grid.find(predicate) } class Pathfinder { /** * Gets the area of all enclosed spaces in the given [PipeMaze]. * @param maze Maze to search. * @return Sum of enclosed areas. */ fun findEnclosureArea(maze: PipeMaze): Double { val loop = findLoop(maze) val vertices = loop.filter { when (it.value) { "F", "7", "L", "J", "S" -> true else -> false } } // Shoelace formula // area = 1/2 * sum of all cross products of vertex pairs (including first and last as they form an edge) var shoelace = 0.0 vertices.windowed(2, 1).forEach { pair -> shoelace += cross(pair[0].x, pair[0].y, pair[1].x, pair[1].y) } shoelace += cross(vertices.last().x, vertices.last().y, vertices.first().x, vertices.first().y) shoelace = abs(shoelace) / 2L // Pick's theorem // interior area = area - (loopSize / 2) + 1 return shoelace - (loop.size / 2) + 1 } /** * Finds the maximum distance away from the starting node in * the pipe loop for the given [PipeMaze]. * @param maze Maze to search. * @return Max distance. */ fun findLoopMaxDistance(maze: PipeMaze): Long { val start = maze.find { it == "S" }!! // Using BFS, each iteration of a queue pop will be the next tier of distance val queue = ArrayDeque<Node<String>>() val distance = mutableMapOf<Node<String>, Long>().withDefault { 0 } queue.add(start) while (queue.isNotEmpty()) { val next = queue.removeFirst() maze.adjacent(next).forEach { adjacent -> if (!distance.contains(adjacent)) { distance[adjacent] = distance.getValue(next) + 1 queue.add(adjacent) } } } return distance.values.max() } /** * Gets the cross product of the given points. * @param x1 First X-coordinate. * @param y1 First y-coordinate. * @param x2 Second x-coordinate. * @param y2 Second y-coordinate. * @return Cross product. */ private fun cross( x1: Long, y1: Long, x2: Long, y2: Long, ) = (x1 * y2) - (x2 * y1) /** * Find the list of [Node] that comprise the pipe loop in the given [PipeMaze]. * @param maze Maze to find the loop in. * @return Pipe loop nodes starting with S and ending with a node adjacent to S. */ private fun findLoop(maze: PipeMaze): List<Node<String>> { val loop = mutableListOf<Node<String>>() val start = maze.find { it == "S" }!! var node = start do { val adjacent = maze.adjacent(node).toMutableList() if (loop.isNotEmpty()) { adjacent.remove(loop.last()) // Force forward movement } loop.add(node) node = adjacent.first() } while (node != start) return loop } }
0
Kotlin
0
0
390f804a3da7e9d2e5747ef29299a6ad42c8d877
6,348
advent-of-code-2023
Apache License 2.0
leetcode2/src/leetcode/first-unique-character-in-a-string.kt
hewking
68,515,222
false
null
package leetcode /** * 387. 字符串中的第一个唯一字符 * https://leetcode-cn.com/problems/first-unique-character-in-a-string/ * 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.   注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object FirstUniqueCharInAString { class Solution { /** * 思路: * 1. 遍历字符串找到每个char * 2. 运用位运算 : 任何数与1异或两次返回 等于原数 */ fun firstUniqChar(s: String): Int { if (s.length == 1) { return 0 } var unselected = BooleanArray(s.length) for (i in 0 until s.length) { if (unselected[i]) { continue } for (j in i + 1 until s.length) { if (s[i] == s[j]) { unselected[j] = true unselected[i] = true } } if (unselected[i]){ continue } return i } return unselected.indexOfFirst { !it } } } } fun main() { print(FirstUniqueCharInAString.Solution().firstUniqChar("cc")) }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,668
leetcode
MIT License
src/main/kotlin/algorithms/MedianString.kt
jimandreas
377,843,697
false
null
@file:Suppress("LiftReturnOrAssignment", "GrazieInspection") package algorithms import java.lang.Integer.min /** 2.4 From Motif Finding to Finding a Median String 8 out of 11 steps passed 0 out of 5 points received Code Challenge: Implement MedianString. Input: An integer k, followed by a collection of strings Dna. Output: A k-mer Pattern that minimizes d(Pattern, Dna) among all possible choices of k-mers. (If there are multiple such strings Pattern, then you may return any one.) * See also: * stepik: @link: https://stepik.org/lesson/240240/step/9?unit=212586 * rosalind: @link: http://rosalind.info/problems/ba2b/ */ /** * The first potential issue with implementing MedianString is writing a * function to compute d(Pattern, Dna) = ∑ti=1 d(Pattern, Dnai), * the sum of distances between Pattern and each string in Dna = {Dna1, ..., Dnat}. */ fun distanceBetweenPatternAndStrings(pattern: String, dnaList: List<String>): Int { var distance = 0 for (g in dnaList) { var minHammingDistance = Integer.MAX_VALUE for (i in 0..g.length - pattern.length) { val kmer = g.substring(i, i + pattern.length) val dist = hammingDistance(pattern, kmer) minHammingDistance = min(minHammingDistance, dist) } distance += minHammingDistance } return distance } /** * return all possible {ACGT} strings of length [kmer] * Use a basic iterative approach rather than recursion for speed */ fun allStrings(kmer: Int): List<String> { if (kmer <= 0) { println("ERROR kmer must be > 0") return listOf("") } val allStringsList: MutableList<String> = mutableListOf() var fourToTheKmer = 4 for (i in 1 until kmer) { fourToTheKmer *= 4 // 4 to the power of kmer } for (i in 0 until fourToTheKmer) { var k = "" var temp = i for (j in 0 until kmer) { k = k.plus( "ACGT"[temp%4]) temp /= 4 } allStringsList.add(k) } return allStringsList } /** * medianString * To solve the Median String Problem, we need to iterate through * all possible 4k k-mers Pattern before computing d(Pattern, Dna). * We can use a subroutine called AllStrings(k) that returns an array * containing all strings of length k. * * return the string of length [kmer] that represents * the candidate with the minimum hamming distance to all * strings in the [dnaList] */ fun medianString(dnaList: List<String>, kmer: Int): String { var minHammingDistance = Integer.MAX_VALUE var retKmer = "" val allPossibleKmers = allStrings(kmer) for (g in allPossibleKmers) { val hammingDistance = distanceBetweenPatternAndStrings(g, dnaList) if (minHammingDistance > hammingDistance) { minHammingDistance = hammingDistance retKmer = g } } return retKmer }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
2,907
stepikBioinformaticsCourse
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/RestoreArrayFromAdjacentPairs.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1743. Restore the Array From Adjacent Pairs * @see <a href="https://leetcode.com/problems/restore-the-array-from-adjacent-pairs">Source</a> */ fun interface RestoreArrayFromAdjacentPairs { operator fun invoke(adjacentPairs: Array<IntArray>): IntArray } sealed interface RestoreArrayFromAdjacentPairsStrategy { data object DFS : RestoreArrayFromAdjacentPairs, RestoreArrayFromAdjacentPairsStrategy { override fun invoke(adjacentPairs: Array<IntArray>): IntArray { val graph = mutableMapOf<Int, MutableList<Int>>() for (pair in adjacentPairs) { val x = pair[0] val y = pair[1] graph.computeIfAbsent(x) { mutableListOf() }.add(y) graph.computeIfAbsent(y) { mutableListOf() }.add(x) } var root: Int? = null for (num in graph.keys) { if (graph[num]?.size == 1) { root = num break } } val ans = mutableListOf<Int>() root?.let { helper(root, null, ans, graph) } return ans.toIntArray() } private fun helper(node: Int, prev: Int?, ans: MutableList<Int>, graph: Map<Int, List<Int>>) { ans.add(node) graph[node]?.let { for (neighbor in it) { if (neighbor != prev) { helper(neighbor, node, ans, graph) } } } } } data object Iterative : RestoreArrayFromAdjacentPairs, RestoreArrayFromAdjacentPairsStrategy { override fun invoke(adjacentPairs: Array<IntArray>) = IntArray(adjacentPairs.size + 1).apply { val map = HashMap<Int, Pair<Int, Int?>>() adjacentPairs.forEach { (a, b) -> map[a] = map[a]?.run { b to first } ?: (b to null) map[b] = map[b]?.run { a to first } ?: (a to null) } foldIndexed(map.asIterable().find { it.value.second == null }!!.key) { i, curr, _ -> this[i] = curr val (first, second) = map.remove(curr)!! if (second != null && first !in map) second else first } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,946
kotlab
Apache License 2.0
leetcode2/src/leetcode/validate-binary-search-tree.kt
hewking
68,515,222
false
null
package leetcode import leetcode.structure.TreeNode /** * 98. 验证二叉搜索树 * https://leetcode-cn.com/problems/validate-binary-search-tree/ * Created by test * Date 2019/10/5 23:30 * Description * 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 示例 1: 输入: 2 / \ 1 3 输出: true 示例 2: 输入: 5 / \ 1 4   / \   3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。   根节点的值为 5 ,但是其右子节点值为 4 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/validate-binary-search-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object ValidateBinarySearchTree { class Solution { /** * 思路: * 1. 本题一看挺简单,通过递归可以实现。其实还有跟问题,就是 * 所有右子树值都要比左子树及父节点都要大。 * 2. 这里就需要个上下界限了,用于判断左右子树的上下界 */ fun isValidBST(root: TreeNode?): Boolean { return helper(root, null, null) } fun helper(root: TreeNode?, lower: Int?, upper: Int?): Boolean { root ?: return true val value = root.`val` val leftValid = if (lower != null) { value > lower } else true val rightValid = if (upper != null) { value < upper } else true return leftValid && rightValid && helper(root.right, value, upper) && helper(root.left, lower, value) } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,885
leetcode
MIT License
y2019/src/main/kotlin/adventofcode/y2019/Day06.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution fun main() = Day06.solve() object Day06 : AdventSolution(2019, 6, "Universal Orbit Map") { override fun solvePartOne(input: String): Int { val satellites: Map<String, List<String>> = input .lineSequence() .map { it.split(')') } .groupBy({ it[0] }, { it[1] }) fun check(obj: String, depth: Int): Int = depth + satellites[obj].orEmpty().sumOf { check(it, depth + 1) } return check("COM", 0) } override fun solvePartTwo(input: String): Int { val parents: Map<String, String> = input .lineSequence() .map { it.split(')') } .associate { it[1] to it[0] } val y = generateSequence("YOU", parents::get).toList().asReversed() val s = generateSequence("SAN", parents::get).toList().asReversed() val same = y.zip(s).count { (a, b) -> a == b } return y.size + s.size - 2 * same - 2 } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,040
advent-of-code
MIT License
src/main/kotlin/fr/chezbazar/aoc23/day5/AlmanacMapper.kt
chezbazar
728,404,822
false
{"Kotlin": 54427}
package fr.chezbazar.aoc23.day5 class AlmanacMapper(private val instructions: List<Instruction>) { fun map(input: Long): Long { instructions.forEach { (range, diff) -> if (range.contains(input)) { return input + diff } } return input } fun minDestination(interval: LongRange) = instructions.minOf { instruction -> val intersection = instruction.sourceRange.intersect(interval) if (!intersection.isEmpty()) { map(intersection.first) } else { Long.MAX_VALUE } } fun fullInstructions(): List<Instruction> { val currentInstructions = instructions.toMutableList() if (instructions.minOf { it.sourceRange.first } != 0L) { currentInstructions.add(Instruction(0L ..< instructions.minOf { it.sourceRange.first }, 0)) } if (instructions.maxOf { it.sourceRange.last } != Long.MAX_VALUE) { currentInstructions.add(Instruction(instructions.maxOf { it.sourceRange.last } + 1 .. Long.MAX_VALUE, 0)) } currentInstructions.sortBy { it.sourceRange.first } val instructionsToAdd = mutableListOf<Instruction>() for (i in 1..currentInstructions.lastIndex) { if (currentInstructions[i].sourceRange.first > currentInstructions[i-1].sourceRange.last + 1) { instructionsToAdd.add(Instruction( currentInstructions[i-1].sourceRange.last + 1 ..< currentInstructions[i].sourceRange.first, 0)) } } currentInstructions.addAll(instructionsToAdd) return currentInstructions.sortedBy { it.sourceRange.first } } fun mergeWith(successor: AlmanacMapper): AlmanacMapper { val currentInstructions = fullInstructions() val successorInstructions = successor.fullInstructions() val instructions = mutableListOf<Instruction>() currentInstructions.forEach { instruction -> val destinationRange = instruction.getDestinationRange() successorInstructions.forEach { successorInstruction -> val intersection = destinationRange.intersect(successorInstruction.sourceRange) if (!intersection.isEmpty()) { instructions.add( Instruction( intersection.first - instruction.offset .. intersection.last - instruction.offset, instruction.offset + successorInstruction.offset) ) } } } return AlmanacMapper(instructions.sortedBy { it.sourceRange.first }) } private fun LongRange.intersect(other: LongRange) = maxOf(this.first, other.first) .. minOf(this.last, other.last) }
0
Kotlin
0
0
223f19d3345ed7283f4e2671bda8ac094341061a
2,790
adventofcode
MIT License
src/Day03.kt
robinpokorny
572,434,148
false
{"Kotlin": 38009}
typealias Rucksack = List<Char> private fun parse(input: List<String>): List<Rucksack> = input .map { it.toCharArray().toList() } private fun itemToPriority(char: Char): Int = if (char in 'a'..'z') char - 'a' + 1 else char - 'A' + 27 private fun findDuplicate(rucksack: Rucksack): Char = rucksack .chunked(rucksack.size / 2) .map { it.toSet() } .reduce(Set<Char>::intersect) .single() private fun sumPrioOfDuplicates(rucksacks: List<Rucksack>) = rucksacks .map(::findDuplicate) .sumOf(::itemToPriority) private fun sumPrioForGroupBadges(input: List<Rucksack>): Int = input .map { it.toSet() } .chunked(3) .map { it.reduce(Set<Char>::intersect).single() } .sumOf(::itemToPriority) fun main() { val input = parse(readDayInput(3)) val testInput = parse(rawTestInput) // PART 1 assertEquals(sumPrioOfDuplicates(testInput), 157) println("Part1: ${sumPrioOfDuplicates(input)}") // PART 2 assertEquals(sumPrioForGroupBadges(testInput), 70) println("Part2: ${sumPrioForGroupBadges(input)}") } private val rawTestInput = """ vJrwpWtwJgWr<KEY> <KEY> """.trimIndent().lines()
0
Kotlin
0
2
56a108aaf90b98030a7d7165d55d74d2aff22ecc
1,299
advent-of-code-2022
MIT License
src/main/kotlin/io/dmitrijs/aoc2022/Day18.kt
lakiboy
578,268,213
false
{"Kotlin": 76651}
package io.dmitrijs.aoc2022 class Day18(input: List<String>) { private val points = input.map { line -> val (x, y, z) = line.split(",").map(String::toInt) Point(x, y, z) }.toSet() fun puzzle1() = points.surfaceSize fun puzzle2() = points.surfaceSize - points.gaps().surfaceSize private val Set<Point>.surfaceSize get() = sumOf { point -> CUBE_SIDES - point.neighbours().count { it in this } } private val Point.lava get() = this in points private fun Set<Point>.rangeOf(transform: (Point) -> Int) = minOf(transform) - 1 until maxOf(transform) private fun Set<Point>.gaps(): Set<Point> { val xRange = rangeOf { it.x } val yRange = rangeOf { it.y } val zRange = rangeOf { it.z } fun Point.edge() = x !in xRange || y !in yRange || z !in zRange fun Point.blocked(): Boolean { val queue = ArrayDeque<Point>() val visited = hashSetOf<Point>() queue.add(this) visited.add(this) while (queue.isNotEmpty()) { val node = queue.removeFirst() if (node.edge()) { return false } node.neighbours().filterNot { it.lava || it in visited }.forEach { queue.add(it) visited.add(it) } } return true } return xRange.flatMap { x -> yRange.flatMap { y -> zRange.map { z -> Point(x, y, z) } }.filterNot { it.lava }.filter { it.blocked() } }.toSet() } private fun Point.neighbours() = setOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1), copy(z = z - 1), copy(z = z + 1), ) private data class Point(val x: Int, val y: Int, val z: Int) companion object { private const val CUBE_SIDES = 6 } }
0
Kotlin
0
1
bfce0f4cb924834d44b3aae14686d1c834621456
1,993
advent-of-code-2022-kotlin
Apache License 2.0
src/main/java/challenges/cracking_coding_interview/trees_graphs/build_order/dfs/Question.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.trees_graphs.build_order.dfs import java.util.* /** * You are given a list of projects and a list of dependencies (which is a list of pairs of projects, * where the second project is dependent on the first project). * All of a project's dependencies must be built before the project is. * Find a build order that will allow the projects to be built. * If there is no valid build order, return an error. * EXAMPLE * Input: * Projects: a, b, c, d, e, f * Dependencies: (a, d), (f, b), (b, d), (f, a), (d, c) Output: f, e, a, b, d, c */ object Question { private fun buildOrderWrapper( projects: Array<String>, dependencies: Array<Array<String>> ): Array<String>? { val buildOrder = findBuildOrder(projects, dependencies) ?: return null return convertToStringList(buildOrder) } private fun convertToStringList(projects: Stack<Project>): Array<String> { val buildOrder = Array(projects.size) { projects.pop().name } return buildOrder } private fun findBuildOrder(projects: Array<String>, dependencies: Array<Array<String>>): Stack<Project>? { val graph = buildGraph(projects, dependencies) return orderProjects(graph.nodes) } /* Build the graph, adding the edge (a, b) if b is dependent on a. * Assumes a pair is listed in “build order” (which is the reverse * of dependency order). The pair (a, b) in dependencies indicates * that b depends on a and a must be built before a. * */ private fun buildGraph(projects: Array<String>?, dependencies: Array<Array<String>>): Graph { val graph = Graph() for (dependency in dependencies) { val first = dependency[0] val second = dependency[1] graph.addEdge(first, second) } return graph } private fun orderProjects(projects: List<Project>): Stack<Project>? { val stack: Stack<Project> = Stack() for (project in projects) { when (project.state) { Project.State.BLANK -> { if (!doDFS(project, stack)) return null } Project.State.PARTIAL, Project.State.COMPLETE -> continue } } return stack } private fun doDFS(project: Project, stack: Stack<Project>): Boolean { when (project.state) { Project.State.PARTIAL -> return false Project.State.BLANK -> { project.state = Project.State.PARTIAL val children = project.children for (child in children) { if (!doDFS(child, stack)) return false } project.state = Project.State.COMPLETE stack.push(project) } Project.State.COMPLETE -> { // Nothing } } return true } @JvmStatic fun main(args: Array<String>) { val projects = arrayOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") val dependencies = arrayOf( arrayOf("a", "b"), arrayOf("b", "c"), arrayOf("a", "c"), arrayOf("d", "e"), arrayOf("b", "d"), arrayOf("e", "f"), arrayOf("a", "f"), arrayOf("h", "i"), arrayOf("h", "j"), arrayOf("i", "j"), arrayOf("g", "j") ) val buildOrder = buildOrderWrapper(projects, dependencies) if (buildOrder == null) { println("Circular Dependency.") } else { for (s in buildOrder) { println(s) } } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,765
CodingChallenges
Apache License 2.0
Meeting Scheduler for Two/Main.kt
JChoPop
429,859,326
false
{"Kotlin": 20296}
// By HJC 2021-11-18 // Meeting Scheduler for two calendars // // example input: val calOne = listOf(Pair("9:00", "10:30"), Pair("12:00", "13:00"), Pair("16:00", "18:00")) val bounds1 = Pair("9:00", "20:00") val calTwo = listOf(Pair("10:00", "11:30"), Pair("12:30", "14:30"), Pair("14:30", "15:00"), Pair("16:00", "17:00")) val bounds2 = Pair("10:00", "18:30") const val duration = 30 // // output should be [["11:30", "12:00"], ["15:00", "16:00"], ["18:00", "18:30"]] // fun main() { println("Person 1: bounds $bounds1\n + meetings $calOne") println("Person 2: bounds $bounds2\n + meetings $calTwo") val combinedCal = listOf( listOf(Pair("0:00", min0Max1(1, bounds1.first, bounds2.first))), (calOne + calTwo).sortedBy { it.first.split(':').first().toInt() * 60 + it.first.split(':').last().toInt() }, listOf(Pair(min0Max1(0, bounds1.second, bounds2.second), "24:00")) ).flatten() // println("combinedCal:\n$combinedCal\n") val avails = simplify(combinedCal) println("\nAvailable blocks of time for a $duration-minute meeting:\n $avails") } // fun min0Max1(option: Int, here: String, there: String): String{ val times = mutableListOf<Int>() listOf(here, there).forEach { times.add(it.split(':').first().toInt() * 60 + it.split(':').last().toInt()) } return if (times[option] == times.minOrNull()) here else there } // fun simplify(combinedCal: List<Pair<String, String>>): List<Pair<String, String>> { var tempEnd = combinedCal.first().second val avBlocks = mutableListOf<Pair<String, String>>() for (comp in 1..combinedCal.lastIndex) { val nextStart = combinedCal[comp] // still in string if (canMeet(tempEnd, nextStart.first)) avBlocks.add(Pair(tempEnd, nextStart.first)) // println("tempEnd: $tempEnd, comp: $comp, combinedCal[comp]: ${combinedCal[comp]}, abBlocks: $avBlocks") tempEnd = min0Max1(1, tempEnd, nextStart.second) } return avBlocks.toList() } // fun canMeet(end: String, start: String): Boolean { return (((start.split(':').first().toInt() * 60 + start.split(':').last().toInt()) - (end.split(':').first().toInt() * 60 + end.split(':').last().toInt())) >= duration) } // // ////[ [a,b], [c,d], ...] // c - b >= duration -> add [b, c] to avBlocks; // replace [a,b], [c,d] with [a,d] -> replace [a,b] with [a,maxOf(b,d)], then delete [c,d] // b > d -> replace [a,b], [c,d] with [a,b] -> replace [a,b] with [a,maxOf(b,d)], then delete [c,d] // else b in (c-duration+1)..d -> replace [a,b], [c,d] with [a,d] -> replace [a,b] with [a,maxOf(b,d)], then delete [c,d] // // // //
0
Kotlin
0
0
3fb587f2af747acc29886cdc2a02653196326dbf
2,664
kotlin_projects
MIT License
src/main/kotlin/com/ginsberg/advent2022/Day07.kt
tginsberg
568,158,721
false
{"Kotlin": 113322}
/* * Copyright (c) 2022 by <NAME> */ /** * Advent of Code 2022, Day 7 - No Space Left On Device * Problem Description: http://adventofcode.com/2022/day/7 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day7/ */ package com.ginsberg.advent2022 class Day07(input: List<String>) { private val rootDirectory: Directory = parseInput(input) fun solvePart1(): Int = rootDirectory.find { it.size <= 100_000 }.sumOf { it.size } fun solvePart2(): Int { val unusedSpace = 70_000_000 - rootDirectory.size val deficit = 30_000_000 - unusedSpace return rootDirectory.find { it.size >= deficit }.minBy { it.size }.size } private fun parseInput(input: List<String>): Directory { val callStack = ArrayDeque<Directory>().apply { add(Directory("/")) } input.forEach { item -> when { item == "$ ls" -> {}// Noop item.startsWith("dir") -> {} // Noop item == "$ cd /" -> callStack.removeIf { it.name != "/" } item == "$ cd .." -> callStack.removeFirst() item.startsWith("$ cd") -> { val name = item.substringAfterLast(" ") callStack.addFirst(callStack.first().traverse(name)) } else -> { val size = item.substringBefore(" ").toInt() callStack.first().addFile(size) } } } return callStack.last() } class Directory(val name: String) { private val subDirs: MutableMap<String, Directory> = mutableMapOf() private var sizeOfFiles: Int = 0 val size: Int get() = sizeOfFiles + subDirs.values.sumOf { it.size } fun addFile(size: Int) { sizeOfFiles += size } fun traverse(dir: String): Directory = subDirs.getOrPut(dir) { Directory(dir) } fun find(predicate: (Directory) -> Boolean): List<Directory> = subDirs.values.filter(predicate) + subDirs.values.flatMap { it.find(predicate) } } }
0
Kotlin
2
26
2cd87bdb95b431e2c358ffaac65b472ab756515e
2,155
advent-2022-kotlin
Apache License 2.0
src/main/kotlin/io/github/ajoz/puzzles/Day04.kt
ajoz
574,043,593
false
{"Kotlin": 21275}
package io.github.ajoz.puzzles import io.github.ajoz.utils.containsAll import io.github.ajoz.utils.containsAny import io.github.ajoz.utils.readInput /** * --- Day 4: Camp Cleanup --- * * Space needs to be cleared before the last supplies can be unloaded from the ships, and so several Elves have been * assigned the job of cleaning up sections of the camp. Every section has a unique ID number, and each Elf is assigned * a range of section IDs. * * However, as some of the Elves compare their section assignments with each other, they've noticed that many of the * assignments overlap. To try to quickly find overlaps and reduce duplicated effort, the Elves pair up and make a big * list of the section assignments for each pair (your puzzle input). * * For example, consider the following list of section assignment pairs: * * 2-4,6-8 * 2-3,4-5 * 5-7,7-9 * 2-8,3-7 * 6-6,4-6 * 2-6,4-8 * * For the first few pairs, this list means: * * Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4), while the second Elf * was assigned sections 6-8 (sections 6, 7, 8). * The Elves in the second pair were each assigned two sections. * The Elves in the third pair were each assigned three sections: one got sections 5, 6, and 7, while the other also * got 7, plus 8 and 9. * * Some of the pairs have noticed that one of their assignments fully contains the other. For example, 2-8 fully * contains 3-7, and 6-6 is fully contained by 4-6. In pairs where one assignment fully contains the other, one Elf in * the pair would be exclusively cleaning sections their partner will already be cleaning, so these seem like the most * in need of reconsideration. In this example, there are 2 such pairs. */ fun main() { val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) check(part2(testInput) == 4) println(part2(input)) } /** * --- Part One --- * * In how many assignment pairs does one range fully contain the other? */ private fun part1(input: List<String>): Int { return input.fold(0) { totalPairsContainingTheOther, inputLine -> val (firstSections, secondSections) = inputLine.parseAsIntRanges() if (firstSections.containsAll(secondSections) || secondSections.containsAll(firstSections)) { totalPairsContainingTheOther + 1 } else { totalPairsContainingTheOther } } } /** * --- Part Two --- * * It seems like there is still quite a bit of duplicate work planned. Instead, the Elves would like to know the number * of pairs that overlap at all. * * In the above example, the first two pairs (2-4,6-8 and 2-3,4-5) don't overlap, while the remaining four pairs * (5-7,7-9, 2-8,3-7, 6-6,4-6, and 2-6,4-8) do overlap: * * 5-7,7-9 overlaps in a single section, 7. * 2-8,3-7 overlaps all of the sections 3 through 7. * 6-6,4-6 overlaps in a single section, 6. * 2-6,4-8 overlaps in sections 4, 5, and 6. * * So, in this example, the number of overlapping assignment pairs is 4. */ private fun part2(input: List<String>): Int { return input.fold(0) { totalPairsContainingTheOther, inputLine -> val (firstSections, secondSections) = inputLine.parseAsIntRanges() if (firstSections.containsAny(secondSections) || secondSections.containsAny(firstSections)) { totalPairsContainingTheOther + 1 } else { totalPairsContainingTheOther } } } /** * Parses Strings in the form num-num,num-num. */ private fun String.parseAsIntRanges(): List<IntRange> = this .split(",") .map { pairString -> val (startSection, endSection) = pairString.split("-").map { it.toInt() } IntRange( start = startSection, endInclusive = endSection, ) }
0
Kotlin
0
0
6ccc37a4078325edbc4ac1faed81fab4427845b8
3,929
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/Day09.kt
brigham
573,127,412
false
{"Kotlin": 59675}
import kotlin.math.abs import kotlin.math.sign data class Movement(val dir: Char, val count: Int) data class Position(val x: Int, val y: Int) fun main() { fun parse(input: List<String>): List<Movement> { return input.map { it.split(' ') } .map { it[0] to it[1].toInt() } .map { Movement(it.first[0], it.second) } } fun expand(m: List<Movement>): List<Char> { return m.flatMap { m1 -> List(m1.count) { m1.dir } } } fun part1(input: List<String>): Int { val parsed = parse(input) val moves = expand(parsed) var head = Position(0, 0) var tail = Position(0, 0) val seen = mutableSetOf<Position>() for (move in moves) { head = when (move) { 'U' -> head.copy(y = head.y - 1) 'D' -> head.copy(y = head.y + 1) 'L' -> head.copy(x = head.x - 1) 'R' -> head.copy(x = head.x + 1) else -> error("unknown dir") } if (abs(head.x - tail.x) > 1 || abs(head.y - tail.y) > 1) { if (head.x - tail.x >= 2) { tail = tail.copy(x = tail.x + 1, y = (if (head.y == tail.y) tail.y else (head.y - tail.y).sign + tail.y)) } else if (head.x - tail.x <= -2) { tail = tail.copy(x = tail.x - 1, y = (if (head.y == tail.y) tail.y else (head.y - tail.y).sign + tail.y)) } if (head.y - tail.y >= 2) { tail = tail.copy(y = tail.y + 1, x = (if (head.x == tail.x) tail.x else (head.x - tail.x).sign + tail.x)) } else if (head.y - tail.y <= -2) { tail = tail.copy(y = tail.y - 1, x = (if (head.x == tail.x) tail.x else (head.x - tail.x).sign + tail.x)) } } seen.add(tail) } return seen.size } fun part2(input: List<String>): Int { val parsed = parse(input) val moves = expand(parsed) val rope = MutableList(10) { Position(0, 0) } val seen = mutableSetOf<Position>() for (move in moves) { for (headIndex in rope.indices.drop(0).dropLast(1)) { val tailIndex = headIndex + 1 var head = rope[headIndex] var tail = rope[tailIndex] if (headIndex == 0) { head = when (move) { 'U' -> head.copy(y = head.y - 1) 'D' -> head.copy(y = head.y + 1) 'L' -> head.copy(x = head.x - 1) 'R' -> head.copy(x = head.x + 1) else -> error("unknown dir") } } if (abs(head.x - tail.x) > 1 || abs(head.y - tail.y) > 1) { if (head.x - tail.x >= 2) { tail = tail.copy( x = tail.x + 1, y = (if (head.y == tail.y) tail.y else (head.y - tail.y).sign + tail.y) ) } else if (head.x - tail.x <= -2) { tail = tail.copy( x = tail.x - 1, y = (if (head.y == tail.y) tail.y else (head.y - tail.y).sign + tail.y) ) } if (head.y - tail.y >= 2) { tail = tail.copy( y = tail.y + 1, x = (if (head.x == tail.x) tail.x else (head.x - tail.x).sign + tail.x) ) } else if (head.y - tail.y <= -2) { tail = tail.copy( y = tail.y - 1, x = (if (head.x == tail.x) tail.x else (head.x - tail.x).sign + tail.x) ) } } rope[headIndex] = head rope[tailIndex] = tail } seen.add(rope.last()) } return seen.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val testInput2 = readInput("Day09_test2") check(part1(testInput) == 13) check(part2(testInput) == 1) check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b87ffc772e5bd9fd721d552913cf79c575062f19
4,457
advent-of-code-2022
Apache License 2.0
src/Day12.kt
treegem
572,875,670
false
{"Kotlin": 38876}
import common.Position import common.readInput import kotlin.math.min // i am sorry for the mess, but i fell behind in schedule and will not refactor or optimize this code // still hoping to catch up fun main() { fun part1(input: List<String>): Long { val charCodeArray = input.to2dArray() val startingPosition = charCodeArray.startingPosition val targetPosition = charCodeArray.targetPosition val allNodes = createNodes(charCodeArray) val startingNode = allNodes.getByPosition(startingPosition) return calculateDistanceToTargetPosition(startingNode, targetPosition, allNodes) } fun part2(input: List<String>): Long { val charCodeArray = input.to2dArray() val targetPosition = charCodeArray.targetPosition val allNodes = createNodes(charCodeArray) return allNodes .filter { it.height == 'a'.code } .minOfOrNull { calculateDistanceToTargetPosition(it, targetPosition, allNodes) .also { reset(allNodes) } }!! } val day = "12" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 31L) { part1(testInput) } check(part2(testInput) == 29L) { part2(testInput) } val input = readInput("Day${day}") println(part1(input)) println(part2(input)) } private fun reset(nodes: List<Node>) { nodes.forEach { it.apply { hasBeenVisited = false } } } private fun calculateDistanceToTargetPosition( startingNode: Node, targetPosition: Position, allNodes: List<Node>, ): Long { println("-------------") println("startingNode: ${startingNode.position}") println("-------------") val unvisitedNodes = allNodes.toMutableList() var currentNode = startingNode.apply { distanceToStart = 0 } while (!targetHasBeenReached(allNodes, targetPosition) && existsReachableUnvisitedNode(allNodes)) { unvisitedNodes.remove(currentNode) currentNode.apply { hasBeenVisited = true } val relevantNeighbors = unvisitedNodes .filter { it.isDirectNeighborOf(currentNode) } .filter { it.isClimbableFrom(currentNode) } relevantNeighbors.forEach { it.apply { distanceToStart = min(distanceToStart, currentNode.distanceToStart + 1) } } currentNode = unvisitedNodes.minByOrNull { it.distanceToStart } ?: break } return allNodes .getByPosition(targetPosition) .distanceToStart } private fun createNodes(charCodeArray: Array<IntArray>): List<Node> { val heights = charCodeArray.convertToHeights() return (charCodeArray.indices).flatMap { row -> charCodeArray[0].indices.map { column -> Node( position = Position(x = column, y = row), height = heights[row][column] ) } } } private fun targetHasBeenReached(allNodes: List<Node>, targetPosition: Position) = allNodes.getByPosition(targetPosition).hasBeenVisited private fun existsReachableUnvisitedNode(allNodes: List<Node>) = allNodes .filterNot { it.hasBeenVisited } .minOf { it.distanceToStart } < Long.MAX_VALUE private fun List<Node>.getByPosition(position: Position) = this.single { it.position == position } private fun List<String>.to2dArray(): Array<IntArray> = this.map { it.toCharArray().toTypedArray() } .map { charArray -> charArray.map { it.code }.toIntArray() } .toTypedArray() private fun Array<IntArray>.getPositionOf(target: Int) = this.mapIndexedNotNull() { index, row -> if (row.contains(target)) { Position(y = index, x = row.indexOf(target)) } else null }.single() private val Array<IntArray>.startingPosition: Position get() = this.getPositionOf('S'.code) private val Array<IntArray>.targetPosition: Position get() = this.getPositionOf('E'.code) private fun Array<IntArray>.convertToHeights() = this.apply { this[this.startingPosition.y][this.startingPosition.x] = 'a'.code this[this.targetPosition.y][this.targetPosition.x] = 'z'.code } private data class Node( val position: Position, val height: Int, ) { var hasBeenVisited: Boolean = false var distanceToStart: Long = Long.MAX_VALUE fun isDirectNeighborOf(other: Node) = (this.position.x == other.position.x && this.position.y in listOf( other.position.y - 1, other.position.y + 1 ) || this.position.y == other.position.y && this.position.x in listOf( other.position.x - 1, other.position.x + 1 )) fun isClimbableFrom(other: Node) = this.height <= other.height + 1 }
0
Kotlin
0
0
97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8
4,787
advent_of_code_2022
Apache License 2.0
src/algorithmdesignmanualbook/sorting/KSortedListMerge.kt
realpacific
234,499,820
false
null
package algorithmdesignmanualbook.sorting import algorithmdesignmanualbook.print import utils.assertArraysSame /** * Give an O(n log k)-time algorithm that merges k sorted lists with a total of n * elements into one sorted list. (Hint: use a heap to speed up the elementary O(kn)-time algorithm). */ private fun kSortedListMerge(arrays: Array<Array<Int>>, n: Int): Array<Int?> { val indices = Array(arrays.size) { 0 } // total size is the size of the result val result = Array<Int?>(n) { null } // What if i load the [arrays] in a heap? // Comparison between smallest elements of heap will still take O(k) for (i in 0 until n) { // O(n) val currentValues = arrays.mapIndexed { index, array -> // O(k) // can run out of items Pair(array.getOrNull(indices.getOrNull(index) ?: -1), index) } // take the min value val minValue = currentValues.filter { it.first != null }.minByOrNull { it.first!! }!! result[i] = minValue.first // increase the index indices[minValue.second] += 1 } return result } fun main() { val input1 = arrayOf(1, 2, 6, 8, 10, 11) val input2 = arrayOf(1, 2, 7, 9, 12) val input3 = arrayOf(-1, 0, 3, 5) val input4 = arrayOf(-2, -1, 12, 22) val input = arrayOf(input1, input2, input3, input4) assertArraysSame( expected = kSortedListMerge(input, n = input.map { it.size }.sum()).print(), actual = arrayOf(-2, -1, -1, 0, 1, 1, 2, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 12, 22) ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,550
algorithms
MIT License
src/main/kotlin/Day03.kt
attilaTorok
573,174,988
false
{"Kotlin": 26454}
fun main() { fun getItemValue(item: Char) = if (item.isUpperCase()) { item.code - 38 } else { item.code - 96 } fun sumOfThePriorities(fileName: String): Int { var result = 0 readInputWithStream(fileName).useLines { val iterator = it.iterator() while (iterator.hasNext()) { val line = iterator.next() val compartmentA = line.substring(0, line.length / 2) val compartmentB = line.substring(line.length / 2) var sum = 0 val checkedItems = mutableSetOf<Char>() for (item in compartmentA) { if (compartmentB.contains(item, ignoreCase = false) && !checkedItems.contains(item)) { sum += getItemValue(item) checkedItems.add(item) } } result += sum } } return result } fun isRucksackContainsItem(items: String, item: Char) = items.contains(item, ignoreCase = false) fun getGroupPriority(groupRucksack: MutableList<String>): Int { var result = 0 groupRucksack.sort() groupRucksack[0].filter { item -> isRucksackContainsItem(groupRucksack[1], item) }.filter { item -> isRucksackContainsItem(groupRucksack[2], item) }.toSet() .forEach { item -> result += getItemValue(item) } return result } fun sumOfThePrioritiesInGroups(fileName: String): Int { var result = 0 readInputWithStream(fileName).useLines { val iterator = it.iterator() var groupRucksack = mutableListOf<String>() var numberOfIteration = 0 while (iterator.hasNext()) { groupRucksack.add(iterator.next()) if (++numberOfIteration % 3 == 0) { result += getGroupPriority(groupRucksack) groupRucksack = mutableListOf() } } } return result } println("Test") println("Sum of the priorities should be 157! My answer: ${sumOfThePriorities("Day03_test")}") println("Sum of the priorities in three groups should be 70! My answer: ${sumOfThePrioritiesInGroups("Day03_test")}") println() println("Exercise") println("Sum of the priorities should be 7785! My answer: ${sumOfThePriorities("Day03")}") println("Sum of the priorities in three groups should be 2633! My answer: ${sumOfThePrioritiesInGroups("Day03")}") }
0
Kotlin
0
0
1799cf8c470d7f47f2fdd4b61a874adcc0de1e73
2,636
AOC2022
Apache License 2.0
src/main/kotlin/g1801_1900/s1851_minimum_interval_to_include_each_query/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1851_minimum_interval_to_include_each_query // #Hard #Array #Sorting #Binary_Search #Heap_Priority_Queue #Line_Sweep // #2023_06_22_Time_1612_ms_(87.50%)_Space_129.5_MB_(75.00%) import java.util.Arrays import java.util.PriorityQueue class Solution { fun minInterval(intervals: Array<IntArray>, queries: IntArray): IntArray { val numQuery = queries.size val queriesWithIndex = Array(numQuery) { IntArray(2) } for (i in 0 until numQuery) { queriesWithIndex[i] = intArrayOf(queries[i], i) } Arrays.sort(intervals, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) Arrays.sort(queriesWithIndex, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) val minHeap = PriorityQueue({ a: IntArray, b: IntArray -> (a[1] - a[0]).compareTo(b[1] - b[0]) }) val result = IntArray(numQuery) var j = 0 for (i in queries.indices) { val queryVal = queriesWithIndex[i][0] val queryIndex = queriesWithIndex[i][1] while (j < intervals.size && intervals[j][0] <= queryVal) { minHeap.add(intervals[j]) j++ } while (minHeap.isNotEmpty() && minHeap.peek()[1] < queryVal) { minHeap.remove() } result[queryIndex] = if (minHeap.isEmpty()) -1 else minHeap.peek()[1] - minHeap.peek()[0] + 1 } return result } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,455
LeetCode-in-Kotlin
MIT License
src/jvmMain/kotlin/day14/initial/Day14.kt
liusbl
726,218,737
false
{"Kotlin": 109684}
package day14.initial import day11.initial.Grid import day11.initial.Location import day11.initial.rotate import day11.initial.toPrintableString import java.io.File fun main() { solvePart1() // Solution: 112046, Time: 2023-12-15 23:41 } fun solvePart1() { // val input = File("src/jvmMain/kotlin/day14/input/input_part1_test.txt") val input = File("src/jvmMain/kotlin/day14/input/input.txt") val grid = Grid(input.readLines()) println("Input:") println(grid.toPrintableString(includeLocation = false)) println() val tiltedGrid = grid.columnList.map { row -> row.joinToString("") { it.toPrintableString() } .split("#") .joinToString("#") { section -> val (rocks, space) = section.partition { it == 'O' } rocks + space } }.let(::Grid).rotate() println("Tilted grid:") println(tiltedGrid.toPrintableString(includeLocation = false)) println() val columnSize = tiltedGrid.columnList[0].size val result = tiltedGrid.rowList.mapIndexed { rowIndex, row -> row.sumOf { location -> when(location.value) { Image.Rock -> columnSize - rowIndex Image.Space -> 0 Image.StableRock -> 0 } } }.sum() println("Result: $result") } sealed class Image { abstract val char: Char object Rock : Image() { override val char = 'O' } object StableRock : Image() { override val char = '#' } object Space : Image() { override val char = '.' } override fun toString(): String = char.toString() } fun Grid(lines: List<String>): Grid<Image> { val list = lines.flatMapIndexed { row, line -> line.mapIndexed { column, char -> Location(value = Image(char), row = row, column = column) } } return Grid(list) } fun Image(char: Char): Image = when (char) { 'O' -> Image.Rock '#' -> Image.StableRock '.' -> Image.Space else -> error("Invalid image char: $char") }
0
Kotlin
0
0
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
2,102
advent-of-code
MIT License
src/DaySeven.kt
jrmacgill
573,065,109
false
{"Kotlin": 76362}
data class Folder(val name: String, val parent: String, var size : Int, var children: MutableList<String>) data class File(val name: String, val size: Int, val dir: String) fun main() { DaySeven().run() } class DaySeven( val dirMap: HashMap<String, Folder> = HashMap<String, Folder>()) { var current: Folder? = Folder("/", "/", 0, mutableListOf()) fun up() { println("Up Directory") current = dirMap[current!!.parent] ?: error("unknown parent " + current) } fun down(child: String) { println("Down Directory to " + child) if (dirMap.contains(child)) error("duplicate!") val mkdir = Folder(current!!.name+":"+child, current!!.name, 0, mutableListOf()) current!!.children.add(mkdir.name) current = mkdir dirMap[mkdir.name] = mkdir } fun root() { println("To Root") current = dirMap["/"] } fun dir() { println("dir exists") } fun ls() { println("start listing") current!!.size = 0 } fun record(it: String) { println("make a note of " + it) val file = File(it.split(" ")[1], it.split(" ")[0].toInt(), current!!.name) current!!.size += file.size } fun totalSize(name : String) : Int { val f = dirMap[name] ?: return 0 return f.size + f.children.sumOf { totalSize(it) } } fun run() { val file = "daySeven" dirMap["/"] = current!! val maxSize = 70000000 val spaceNeeded = 30000000 val input = readInput(file) input.forEach() { when { it.startsWith("$ cd ..") -> up() it.startsWith("$ cd /") -> root() it.startsWith("$ cd ") -> down(it.split(" ").last()) it.startsWith("$ dir") -> dir() it.startsWith("$ ls") -> ls() it.startsWith("dir") -> {} else -> record(it) } } val sizes = dirMap.mapValues { f -> totalSize(f.value.name) } val totalUsed = maxSize - totalSize("/") println(sizes.filter { n -> n.value < 100000 }.values.sum()) println(totalUsed) val minToFree = spaceNeeded - totalUsed println(" min to free " + minToFree) val candidates = sizes.filter{ n -> n.value > minToFree}.values.sortedDescending() println(candidates) } }
0
Kotlin
0
1
3dcd590f971b6e9c064b444139d6442df034355b
2,428
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/io/github/trustedshops_public/spring_boot_starter_keycloak_path_based_resolver/configuration/holder.kt
trustedshops-public
524,078,409
false
{"Kotlin": 22803}
package io.github.trustedshops_public.spring_boot_starter_keycloak_path_based_resolver.configuration import org.keycloak.adapters.KeycloakDeployment import java.lang.IllegalArgumentException class MatcherConfiguration( private val parent: KeycloakPathContextConfigurationHolder, private val antPatterns: Array<out String> ) { /** * Configure keycloak deployment for the given antPatterns * * @see org.keycloak.adapters.KeycloakDeployment */ fun useKeycloakDeployment(keycloakDeployment: KeycloakDeployment): KeycloakPathContextConfigurationHolder { antPatterns .associateWith { keycloakDeployment } .forEach { (pattern, deployment) -> if (parent.mapping.containsKey(pattern)) { throw IllegalArgumentException("pattern '${pattern}' can not be assigned twice") } parent.mapping[pattern] = deployment } parent.mapping.putAll(antPatterns.associateWith { keycloakDeployment }) return parent } } /** * Configuration allowing to map given ant patterns to keycloak deployments */ class KeycloakPathContextConfigurationHolder { /** * Mapping, sorted by the longest string being the first in the map, so iteration always uses the most specific * matcher first */ internal val mapping = sortedMapOf<String, KeycloakDeployment>(compareBy<String> { -it.length }.thenBy { it }) /** * Configure context for given ant path matcher * * For more information check AntPathMatcher * @see org.springframework.util.AntPathMatcher */ fun antMatchers(vararg antPatterns: String): MatcherConfiguration = MatcherConfiguration(this, antPatterns) }
2
Kotlin
0
0
451885d836f596ae1423b78d9a7a873552b42e18
1,752
spring-boot-starter-keycloak-path-based-resolver
MIT License
kotlin/graphs/flows/MinCostFlowBF.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package graphs.flows import java.util.stream.Stream // https://en.wikipedia.org/wiki/Minimum-cost_flow_problem in O(E * V * FLOW) // negative-cost edges are allowed // negative-cost cycles are not allowed class MinCostFlowBF(nodes: Int) { var graph: Array<List<Edge>> inner class Edge(var to: Int, var rev: Int, var cap: Int, var cost: Int) { var f = 0 } fun addEdge(s: Int, t: Int, cap: Int, cost: Int) { graph[s].add(Edge(t, graph[t].size(), cap, cost)) graph[t].add(Edge(s, graph[s].size() - 1, 0, -cost)) } fun bellmanFord(s: Int, dist: IntArray, prevnode: IntArray, prevedge: IntArray, curflow: IntArray) { val n = graph.size Arrays.fill(dist, 0, n, Integer.MAX_VALUE) dist[s] = 0 curflow[s] = Integer.MAX_VALUE val inqueue = BooleanArray(n) val q = IntArray(n) var qt = 0 q[qt++] = s for (qh in 0 until qt) { val u = q[qh % n] inqueue[u] = false for (i in 0 until graph[u].size()) { val e = graph[u][i] if (e.f >= e.cap) continue val v = e.to val ndist = dist[u] + e.cost if (dist[v] > ndist) { dist[v] = ndist prevnode[v] = u prevedge[v] = i curflow[v] = Math.min(curflow[u], e.cap - e.f) if (!inqueue[v]) { inqueue[v] = true q[qt++ % n] = v } } } } } fun minCostFlow(s: Int, t: Int, maxf: Int): IntArray { val n = graph.size val dist = IntArray(n) val curflow = IntArray(n) val prevedge = IntArray(n) val prevnode = IntArray(n) var flow = 0 var flowCost = 0 while (flow < maxf) { bellmanFord(s, dist, prevnode, prevedge, curflow) if (dist[t] == Integer.MAX_VALUE) break val df: Int = Math.min(curflow[t], maxf - flow) flow += df var v = t while (v != s) { val e = graph[prevnode[v]][prevedge[v]] e.f += df graph[v][e.rev].f -= df flowCost += df * e.cost v = prevnode[v] } } return intArrayOf(flow, flowCost) } companion object { // Usage example fun main(args: Array<String?>?) { val mcf = MinCostFlowBF(3) mcf.addEdge(0, 1, 3, 1) mcf.addEdge(0, 2, 2, 1) mcf.addEdge(1, 2, 2, 1) val res = mcf.minCostFlow(0, 2, Integer.MAX_VALUE) val flow = res[0] val flowCost = res[1] System.out.println(4 == flow) System.out.println(6 == flowCost) } } init { graph = Stream.generate { ArrayList() }.limit(nodes).toArray { _Dummy_.__Array__() } } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
3,002
codelibrary
The Unlicense
kotlin/src/katas/kotlin/leetcode/subarray_sum_equals_k/Tests.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.subarray_sum_equals_k import java.util.* // // https://leetcode.com/problems/subarray-sum-equals-k // // Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. // Constraints: // - The length of the array is in range [1, 20000]. // - The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. // // Example 1: // Input:nums = [1,1,1], k = 2 // Output: 2 // // 5 2 3 -4 -1 1 // 5 7 10 6 5 6 <- prefix sum // f t fun subarraySum(ints: IntArray, targetSum: Int): Int { return subArrays(ints, targetSum).count() } private fun subArrays(ints: IntArray, targetSum: Int): Sequence<Pair<Int, Int>> = sequence { (0..ints.lastIndex).forEach { from -> var sum = 0 (from..ints.lastIndex).forEach { to -> sum += ints[to] if (sum == targetSum) yield(Pair(from, to)) } } } fun subarraySum_cleverHashMap(nums: IntArray, targetSum: Int): Int { var count = 0 val countBySum = HashMap<Int, Int>() countBySum[0] = 1 var sum = 0 nums.forEach { sum += it count += countBySum.getOrDefault(sum - targetSum, defaultValue = 0) countBySum[sum] = countBySum.getOrDefault(sum, defaultValue = 0) + 1 } return count }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,365
katas
The Unlicense
src/Day02.kt
RogozhinRoman
572,915,906
false
{"Kotlin": 28985}
fun main() { fun part1(input: List<String>): Int { var result = 0 for (pair in input.map { it.split(' ') }) { when (pair.first()) { "A" -> when (pair.last()) { "X" -> result += 1 + 3 "Y" -> result += 2 + 6 "Z" -> result += 3 + 0 } "B" -> when (pair.last()) { "X" -> result += 1 + 0 "Y" -> result += 2 + 3 "Z" -> result += 3 + 6 } "C" -> when (pair.last()) { "X" -> result += 1 + 6 "Y" -> result += 2 + 0 "Z" -> result += 3 + 3 } } } return result } fun part2(input: List<String>): Int { var result = 0 for (pair in input.map { it.split(' ') }) { when (pair.first()) { "A" -> when (pair.last()) { "X" -> result += 0 + 3 "Y" -> result += 3 + 1 "Z" -> result += 6 + 2 } "B" -> when (pair.last()) { "X" -> result += 0 + 1 "Y" -> result += 3 + 2 "Z" -> result += 6 + 3 } "C" -> when (pair.last()) { "X" -> result += 0 + 2 "Y" -> result += 3 + 3 "Z" -> result += 6 + 1 } } } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val testInput1 = readInput("Day02_test") check(part2(testInput1) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) // println(part2(input)) } // A -- rock 1 // B -- paper 2 // C -- scissors 3 // X -- rock 1 // Y -- paper 2 // Z -- scissors 3 // 0 -- lost // 3 -- draw // 6 -- won // X -- lose 0 // Y -- draw 3 // Z -- win 6
0
Kotlin
0
1
6375cf6275f6d78661e9d4baed84d1db8c1025de
2,109
AoC2022
Apache License 2.0
src/year2022/day14/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day14 import io.kotest.matchers.shouldBe import utils.Point import utils.not import utils.readInput import utils.sequenceTo fun main() { val testInput = readInput("14", "test_input") val realInput = readInput("14", "input") val testWalls = parseRockWalls(testInput) val testInitialState = testWalls.initialState() val isInTestAbyss = testWalls.getIsInAbyssPredicate sandFallingSequence( testInitialState, isFinal = { isFallingInAbyss(isInTestAbyss) }, isValid = !isInTestAbyss, ) .count() .minus(1) .also(::println) shouldBe 24 val realWalls = parseRockWalls(realInput) val initialState = realWalls.initialState() val isInAbyss = realWalls.getIsInAbyssPredicate sandFallingSequence( initialState, isFinal = { isFallingInAbyss(isInAbyss) }, isValid = !isInAbyss, ) .count() .minus(1) .let(::println) sandFallingSequence( testInitialState, isFinal = { lastFallenGrain == Point(500, 0) }, isValid = testWalls.getIsAboveFloorPredicate, ) .count() .also(::println) shouldBe 93 sandFallingSequence( initialState, isFinal = { lastFallenGrain == Point(500, 0) }, isValid = realWalls.getIsAboveFloorPredicate, ) .count() .let(::println) } private fun parseRockWalls(input: List<String>): Set<Point> { return input.asSequence() .map(pointRegex::findAll) .flatMapTo(mutableSetOf()) { pointStops -> pointStops.map { Point(it.groupValues[1].toInt(), it.groupValues[2].toInt()) } .windowed(2) { (start, end) -> start sequenceTo end } .flatten() } } private val pointRegex = "(\\d+),(\\d+)".toRegex() private data class State( val walls: Set<Point>, val sand: Set<Point>, val lastGrainPath: List<Point>, ) { val lastFallenGrain get() = lastGrainPath.last() } private fun Set<Point>.initialState(): State { return filter { it.x == 500 } .minBy { it.y } .let { Point(500, 0) sequenceTo it } .toList() .dropLast(1) .let { State( walls = this, sand = setOf(it.last()), lastGrainPath = it, ) } } private val Set<Point>.getIsInAbyssPredicate: Point.() -> Boolean get() { val xRange = minOf { it.x }..maxOf { it.x } val maxY = maxOf { it.y } return { x !in xRange || y >= maxY } } private fun sandFallingSequence( initialState: State, isFinal: State.() -> Boolean, isValid: Point.() -> Boolean, ) = generateSequence(initialState) { lastState -> if (lastState.isFinal()) null else { val projectedGrain = lastState.lastGrainPath[lastState.lastGrainPath.lastIndex - 1] val nextGrainPath = lastState.lastGrainPath .dropLast(1) .plus( generateSequence(projectedGrain){ previousGrain -> previousGrain.fallPrioritySequence.firstOrNull { it !in lastState.walls && it !in lastState.sand && it.isValid() } } .drop(1) .takeWhile(isValid) ) State( walls = lastState.walls, sand = lastState.sand + nextGrainPath.last(), lastGrainPath = nextGrainPath, ) } } private val Point.fallPrioritySequence get() = sequenceOf( Point(x, y + 1), Point(x - 1, y + 1), Point(x + 1, y + 1), ) private val Set<Point>.getIsAboveFloorPredicate: Point.() -> Boolean get() { val floorY = maxOf { it.y } + 2 return { y < floorY } } private fun State.isFallingInAbyss(isInAbyss: Point.() -> Boolean): Boolean { return lastFallenGrain.fallPrioritySequence .firstOrNull { it !in walls && it !in sand } ?.isInAbyss() == true }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
4,116
Advent-of-Code
Apache License 2.0
src/Day22.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
fun main() { fun parseInstructions(input: List<String>): List<String> { val rawInstructions = input[input.size - 1] val distances = rawInstructions.split('L', 'R').filter { it.isNotEmpty() } val turns = rawInstructions.split('0', '1', '2', '3', '4', '5', '6', '7', '8', '9').filter { it.isNotEmpty() } return distances.zip(turns) { a, b -> listOf(a, b) }.flatten() + distances.last() } fun parseGrid(input: List<String>): Map<Coordinates, Char> { val grid = mutableMapOf<Coordinates, Char>() for (row in 0 until input.size - 2) { for (col in 0 until input[row].length) { if (input[row][col] != ' ') { grid[Coordinates(row + 1, col + 1)] = input[row][col] } } } return grid } // Helpers fun getMinCol(row: Int, grid: Map<Coordinates, Char>) = grid.filterKeys { it.row == row }.minOf { (k, _) -> k.col } fun getMaxCol(row: Int, grid: Map<Coordinates, Char>) = grid.filterKeys { it.row == row }.maxOf { (k, _) -> k.col } fun getMinRow(col: Int, grid: Map<Coordinates, Char>) = grid.filterKeys { it.col == col }.minOf { (k, _) -> k.row } fun getMaxRow(col: Int, grid: Map<Coordinates, Char>) = grid.filterKeys { it.col == col }.maxOf { (k, _) -> k.row } fun part1(input: List<String>): Int { val instructions = parseInstructions(input) val grid = parseGrid(input) // Setup initial position and orientation var position = Coordinates(1, getMinCol(1, grid)) val vectors = listOf( Coordinates(0, 1), // Right Coordinates(1, 0), // Down Coordinates(0, -1), // Left Coordinates(-1, 0) // Up ) var orientation = 0 // Right for (instruction in instructions) { //println("Instruction: $instruction") //println(" -Current position $position, orientation $orientation") if (instruction == "L") { orientation-- if (orientation < 0) { orientation = 3 } //println(" Turn left to: $orientation") } else if (instruction == "R") { orientation++ if (orientation >= 4) { orientation = 0 } //println(" Turn right to: $orientation") } else { // Walk val distance = instruction.toInt() //println(" Walk: $distance") for (d in 1..distance) { //println(" Step $d") var nextPosition = position.add(vectors[orientation]) var nextGridSpot = grid[nextPosition] //println(" Next position: $nextPosition") if (nextGridSpot == null) { // Wrap around nextPosition = when (orientation) { 0 -> Coordinates(nextPosition.row, getMinCol(nextPosition.row, grid)) 1 -> Coordinates(getMinRow(nextPosition.col, grid), nextPosition.col) 2 -> Coordinates(nextPosition.row, getMaxCol(nextPosition.row, grid)) 3 -> Coordinates(getMaxRow(nextPosition.col, grid), nextPosition.col) else -> throw IllegalStateException("Bad orientation '$orientation'") } //println(" Calculating wraparound to $nextPosition") nextGridSpot = grid[nextPosition] if (nextGridSpot == null) { throw IllegalStateException("After calculating wraparound of $position to $nextPosition, found no valid spot on grid") } } if (nextGridSpot == '#') { // Wall, have to stop //println(" Wall, have to stop") break } else { // Walk //println(" Walk") position = nextPosition } } } } // grid[position] = 'O' // val maxRow = grid.maxOf { (k,_) -> k.row} // val maxCol = grid.maxOf { (k,_) -> k.col} // for(row in 1 .. maxRow) { // for(col in 1 .. maxCol) { // val tile = grid[Coordinates(row,col)] // if (tile == null) { // print(' ') // } else { // print(tile) // } // } // println() // } //println(position) return (position.row * 1000) + (position.col * 4) + orientation } fun transition(position: Coordinates, orientation: Int): Pair<Coordinates, Int> { if (orientation == 3) { // Up if (position.row == 1) { if (position.col in 51..100) { // Face 1->6 return Pair(Coordinates(position.col+100, 1), 0) } else if (position.col in 101..150) { // Face 2->6 return Pair(Coordinates(200, position.col-100), 3) } } else if (position.row == 101 && position.col in 1..50) { // Face 5->3 return Pair(Coordinates(position.col+50, 51), 0) } } else if (orientation == 2) { // Left if (position.col == 51) { if (position.row in 1 .. 50) { // Face 1->5 return Pair(Coordinates(151-position.row, 1), 0) } else if (position.row in 51 .. 100) { // Face 3->5 return Pair(Coordinates(101, position.row-50), 1) } } else if (position.col == 1) { if (position.row in 101 .. 150) { // Face 5->1 return Pair(Coordinates(151-position.row, 51), 0) } else if (position.row in 151 .. 200) { // Face 6->1 return Pair(Coordinates(1, position.row-100), 1) } } } else if (orientation == 1) { // Down if (position.row == 50 && position.col in 101 .. 150) { // Face 2->3 return Pair(Coordinates(position.col-50,100), 2) } else if (position.row == 150 && position.col in 51 .. 100) { // Face 4->6 return Pair(Coordinates(position.col+100,50), 2) } else if (position.row == 200 && position.col in 1 .. 50) { // Face 6->2 return Pair(Coordinates(1,position.col+100), 1) } //return Pair(Coordinates(), 0) } else if (orientation == 0) { // Right if (position.col == 150 && position.row in 1 .. 50) { // Face 2->4 return Pair(Coordinates(151-position.row,100), 2) } else if (position.col == 100) { if (position.row in 51 .. 100) { // Face 3->2 return Pair(Coordinates(50,position.row+50), 3) } else if (position.row in 101 .. 150) { // Face 4->2 return Pair(Coordinates(151-position.row,150), 2) } } else if (position.col == 50 && position.row in 151 .. 200) { // Face 6->4 return Pair(Coordinates(150,position.row-100), 3) } } throw IllegalArgumentException("Unknown transition for $position with orientation $orientation") } // Only works for how my specific input map is folded. Does not work for sample. fun part2(input: List<String>): Int { val instructions = parseInstructions(input) val grid = parseGrid(input) // Setup initial position and orientation var position = Coordinates(1, getMinCol(1, grid)) val vectors = listOf( Coordinates( 0, 1), // Right Coordinates( 1, 0), // Down Coordinates( 0, -1), // Left Coordinates(-1, 0) // Up ) var orientation = 0 // Right for(instruction in instructions) { //println("Instruction: $instruction") //println(" -Current position $position, orientation $orientation") if (instruction == "L") { orientation-- if (orientation < 0) { orientation = 3 } //println(" Turn left to: $orientation") } else if (instruction == "R") { orientation++ if (orientation >= 4) { orientation = 0 } //println(" Turn right to: $orientation") } else { // Walk val distance = instruction.toInt() //println(" Walk: $distance") for(d in 1 .. distance) { //println(" Step $d") var nextOrientation = orientation var nextPosition = position.add(vectors[orientation]) var nextGridSpot = grid[nextPosition] //println(" Next position: $nextPosition") if (nextGridSpot == null) { // Wrap around val (translatedPosition, translatedOrientation) = transition(position, orientation) nextPosition = translatedPosition nextOrientation = translatedOrientation //println(" Calculating wraparound to $nextPosition") nextGridSpot = grid[nextPosition] if (nextGridSpot == null) { throw IllegalStateException("After calculating wraparound of $position to $nextPosition, found no valid spot on grid") } } if (nextGridSpot == '#') { // Wall, have to stop //println(" Wall, have to stop") break } else { // Walk //println(" Walk") position = nextPosition orientation = nextOrientation } } } } // grid[position] = 'O' // val maxRow = grid.maxOf { (k,_) -> k.row} // val maxCol = grid.maxOf { (k,_) -> k.col} // for(row in 1 .. maxRow) { // for(col in 1 .. maxCol) { // val tile = grid[Coordinates(row,col)] // if (tile == null) { // print(' ') // } else { // print(tile) // } // } // println() // } //println(position) return (position.row*1000) + (position.col*4) + orientation } val testInput = readInput("Day22_test") check(part1(testInput) == 6032) val input = readInput("Day22") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
11,441
aoc2022
Apache License 2.0
src/Day04.kt
eo
574,058,285
false
{"Kotlin": 45178}
// https://adventofcode.com/2022/day/4 fun main() { infix fun IntRange.isEitherFullyContainedInTheOther(other: IntRange): Boolean = (first in other && last in other) || (other.first in this && other.last in this) infix fun IntRange.overlaps(other: IntRange): Boolean = !(first > other.last || last < other.first) fun sectionAssignmentPairs(input: List<String>): List<Pair<IntRange, IntRange>> { return input.map { line -> val (firstSection, secondSection) = line.split(",").map { section -> val (sectionStart, sectionEnd) = section.split("-").map(String::toInt) sectionStart..sectionEnd } firstSection to secondSection } } fun part1(input: List<String>): Int { return sectionAssignmentPairs(input) .count { (first, second) -> first isEitherFullyContainedInTheOther second } } fun part2(input: List<String>): Int { return sectionAssignmentPairs(input) .count { (first, second) -> first overlaps second } } val input = readLines("Input04") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
8661e4c380b45c19e6ecd590d657c9c396f72a05
1,199
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/aoc2020/ex5.kt
noamfree
433,962,392
false
{"Kotlin": 93533}
fun main() { val input = readInputFile("aoc2020/input5") val rowsAndColums = input.lines().map { row(it.take(7)) to column(it.takeLast(3)) }.sortedBy { (a, b) -> seatId(a, b) } val firstRow = rowsAndColums.first().first val lastRow = rowsAndColums.last().first var index = 0 print(rowsAndColums) for (i in firstRow..lastRow) { for (j in 0 ..7) { if (rowsAndColums[index] == i to j) { println("$i, $j, exists") index++ } else println("$i, $j, not exists") //index++ } } } fun row(string: String): Int { require(string.length == 7) return parseBinary(string, zero = 'F', one = 'B') } fun column(string: String): Int { require(string.length == 3) return parseBinary(string, zero = 'L', one = 'R') } fun parseBinary(string: String, zero: Char, one: Char): Int { val binaryString = string.map { char -> when (char) { zero -> '0' one -> '1' else -> error("cant") } }.joinToString("") return Integer.parseInt(binaryString, 2) } fun getSeatId(string: String): Int { val row = row(string.take(7)) val column = column(string.takeLast(3)) return seatId(row = row, column = column) } fun seatId(row: Int, column: Int) = row * 8 + column // 100 //1000100 -> bfffbffrll
0
Kotlin
0
0
566cbb2ef2caaf77c349822f42153badc36565b7
1,396
AOC-2021
MIT License
src/leetcode_study_badge/dynamic_programming/Day3.kt
faniabdullah
382,893,751
false
null
package leetcode_study_badge.dynamic_programming class Day3 { // https://leetcode.com/problems/house-robber/ fun rob(nums: IntArray): Int { val dp = nums.clone() for (i in nums.indices) { for (j in i + 2 until nums.size) { dp[j] = maxOf(dp[j], nums[j] + dp[i]) } } var maxI = 0 dp.forEach { maxI = maxOf(it, maxI) } return maxI } // optimizing fun houseRob(nums: IntArray): Int { if (nums.isEmpty()) { return 0 } if (nums.size == 1) return nums[0] if (nums.size == 2) return maxOf(nums[0], nums[1]) val dp = IntArray(nums.size) dp[0] = nums[0] dp[1] = maxOf(nums[0], nums[1]) for (i in 2 until dp.size) { dp[i] = maxOf(nums[i] + dp[i - 2], dp[i - 1]) } return dp[nums.size - 1] } fun houseRob2NotStabil(nums: IntArray): Int { if (nums.isEmpty()) { return 0 } if (nums.size == 1) return nums[0] if (nums.size == 2) return maxOf(nums[0], nums[1]) if (nums.size == 2) return maxOf(nums[0], nums[1], nums[3]) val dp = IntArray(nums.size) dp[1] = nums[1] dp[2] = maxOf(nums[1], nums[2]) for (i in 3 until nums.size) { dp[i] = maxOf(nums[i] + dp[i - 2], dp[i - 1]) } val maxOne = dp.maxOrNull() ?: 0 dp[nums.size - 1] = 0 dp[0] = nums[0] dp[1] = nums[1] for (i in 2 until nums.size - 1) { dp[i] = maxOf(nums[i] + dp[i - 2], dp[i - 1]) } val maxTwo = dp.maxOrNull() ?: 0 return maxOf(maxOne, maxTwo) } fun houseRob2Stabil(nums: IntArray): Int { var dp = nums.clone() for (i in 0..nums.size - 2) { for (j in i + 2..nums.size - 2) { dp[j] = maxOf(dp[j], nums[j] + dp[i]) } } var maxI = 0 dp.forEach { maxI = maxOf(it, maxI) } println(dp.contentToString()) dp = nums.clone() for (i in 1 until nums.size) { for (j in i + 2 until nums.size) { dp[j] = maxOf(dp[j], nums[j] + dp[i]) } } maxI = maxOf(dp.maxOrNull() as Int, maxI) return maxI } fun deleteAndEarn(nums: IntArray): Int { val hashMap = HashMap<Int, Int>() nums.forEach { hashMap[it] = hashMap.getOrDefault(it, 0) + 1 } val dp = IntArray(nums.size) { -1 } repeat(nums.count()) { val map = hashMap.clone() dp[it] = earn(map as HashMap<Int, Int>, nums[it]) } println(dp.contentToString()) return dp.maxOrNull() ?: 0 } private fun earn(hashMap: HashMap<Int, Int>, value: Int): Int { hashMap.remove(value - 1) hashMap.remove(value + 1) hashMap[value] = hashMap.getOrDefault(value, 1) - 1 if (hashMap[value] == 0) hashMap.remove(value) if (hashMap.isEmpty()) { return value } else { val firstKey = hashMap.keys.toList()[0] return value + earn(hashMap, firstKey) } } fun deleteAndEarnDP(nums: IntArray): Int { val count = IntArray(10001) for (x in nums) count[x]++ var avoid = 0 var using = 0 var prev = -1 for (k in 0..10000) if (count[k] > 0) { val m = Math.max(avoid, using) if (k - 1 != prev) { using = k * count[k] + m avoid = m } else { using = k * count[k] + avoid avoid = m } prev = k } return maxOf(avoid, using) } } fun main() { println(Day3().deleteAndEarnDP(intArrayOf(3, 4, 2))) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
3,881
dsa-kotlin
MIT License
src/main/kotlin/ru/timakden/aoc/year2015/Day21.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2015 import ru.timakden.aoc.util.PowerSet import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import ru.timakden.aoc.year2015.Day21.Item.* /** * [Day 21: RPG Simulator 20XX](https://adventofcode.com/2015/day/21). */ object Day21 { @JvmStatic fun main(args: Array<String>) { measure { val (hitPoints, damage, armor) = readInput("year2015/Day21") .map { it.substringAfter(": ") } .map { it.toInt() } val character = Character(hitPoints, damage, armor) val items = setOf( // Weapons Weapon(cost = 8, damage = 4), Weapon(cost = 10, damage = 5), Weapon(cost = 25, damage = 6), Weapon(cost = 40, damage = 7), Weapon(cost = 74, damage = 8), // Armor Armor(cost = 13, armor = 1), Armor(cost = 31, armor = 2), Armor(cost = 53, armor = 3), Armor(cost = 75, armor = 4), Armor(cost = 102, armor = 5), // Rings Ring(cost = 25, damage = 1), Ring(cost = 50, damage = 2), Ring(cost = 100, damage = 3), Ring(cost = 20, armor = 1), Ring(cost = 40, armor = 2), Ring(cost = 80, armor = 3) ) val validItems = PowerSet(items).filter(::isValid).toMutableList() println("Part One: ${part1(validItems, character)}") println("Part Two: ${part2(validItems, character)}") } } fun part1(itemSets: MutableList<Set<Item>>, input: Character): Int { itemSets.sortBy { it.sumOf(Item::cost) } var bossDefeated = false itemSets.forEach { items -> val boss = input.copy() val player = Character(100, items.sumOf(Item::damage), items.sumOf(Item::armor)) var currentMove = 1 while (true) { if (currentMove % 2 == 0) { boss.attack(player) if (player.hitpoints <= 0) break } else { player.attack(boss) if (boss.hitpoints <= 0) { bossDefeated = true break } } currentMove++ } if (bossDefeated) return items.sumOf(Item::cost) } return 0 } fun part2(itemSets: MutableList<Set<Item>>, input: Character): Int { itemSets.sortByDescending { it.sumOf(Item::cost) } var playerDefeated = false itemSets.forEach { items -> val boss = input.copy() val player = Character(100, items.sumOf(Item::damage), items.sumOf(Item::armor)) var currentMove = 1 while (true) { if (currentMove % 2 == 0) { boss.attack(player) if (player.hitpoints <= 0) { playerDefeated = true break } } else { player.attack(boss) if (boss.hitpoints <= 0) break } currentMove++ } if (playerDefeated) return items.sumOf(Item::cost) } return 0 } private fun isValid(items: Set<Item>) = !(items.isEmpty() || items.size > 4 || items.count { it.type == ItemType.WEAPON } != 1 || items.count { it.type == ItemType.ARMOR } > 1 || items.count { it.type == ItemType.RING } > 2) sealed class Item(val type: ItemType) { abstract val cost: Int abstract val damage: Int abstract val armor: Int class Weapon( override val cost: Int, override val damage: Int = 0, override val armor: Int = 0 ) : Item(ItemType.WEAPON) class Armor( override val cost: Int, override val damage: Int = 0, override val armor: Int = 0 ) : Item(ItemType.ARMOR) class Ring( override val cost: Int, override val damage: Int = 0, override val armor: Int = 0 ) : Item(ItemType.RING) } data class Character(var hitpoints: Int = 0, var damage: Int = 0, var armor: Int = 0) { fun attack(other: Character) { other.hitpoints -= if (damage - other.armor < 1) 1 else damage - other.armor } } enum class ItemType { WEAPON, ARMOR, RING } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
4,669
advent-of-code
MIT License
src/main/kotlin/Day11.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.time.LocalDateTime import java.time.ZoneOffset import kotlin.math.abs fun main() { fun calculateDistances(input: List<String>, driftAdder: Long): Long { var emptyLines = 0L val galaxies = input.mapIndexedNotNull { lineNumber, s -> val galaxyCoordinates = s.mapIndexedNotNull { index, c -> if (c == '#') lineNumber + emptyLines to index else null } if (galaxyCoordinates.isEmpty()) { emptyLines += driftAdder null } else { galaxyCoordinates } }.flatten() val columnsWithGalaxies = galaxies.map { it.second } val lastColumnWithGalaxy = columnsWithGalaxies.max() val columnsWithoutGalaxies = (0..lastColumnWithGalaxy).filterNot { it in columnsWithGalaxies } return galaxies.mapIndexed { index, a -> galaxies.subList(index, galaxies.size).sumOf { b -> if (a == b) { 0 } else { val correctedPositionForA = columnsWithoutGalaxies.count { it < a.second } * driftAdder + a.second val correctedPositionForB = columnsWithoutGalaxies.count { it < b.second } * driftAdder + b.second abs(a.first - b.first) + abs(correctedPositionForA - correctedPositionForB) } } }.sum() } fun part1(input: List<String>): Long { return calculateDistances(input, 1L) } fun part2(input: List<String>): Long { return calculateDistances(input, 1_000_000L - 1) } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val input = readLines("day11-input.txt") val result1 = part1(input) "Result1: $result1".println() val result2 = part2(input) "Result2: $result2".println() println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms") }
0
Kotlin
0
0
41f376bd71a8449e05bbd5b9dd03b3019bde040b
1,979
aoc-2023-in-kotlin
Apache License 2.0
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day04.kt
MichalChomo
572,214,942
false
{"Kotlin": 56758}
package eu.michalchomo.adventofcode.year2023 import eu.michalchomo.adventofcode.Day import eu.michalchomo.adventofcode.main import java.math.BigInteger typealias CountMatchingToOccurrences = Pair<Int, Int> object Day04 : Day { override val number: Int = 4 override fun part1(input: List<String>): String = input.map { line -> BigInteger.ONE.shl(line.getMatchingNumbers().size - 1) }.reduce(BigInteger::plus).toString() override fun part2(input: List<String>): String = input.foldIndexed(mutableMapOf<Int, CountMatchingToOccurrences>()) { i, acc, line -> val currentCardIndex = i + 1 val matchingNumbers = line.getMatchingNumbers() val currentCardCopies = acc[currentCardIndex]?.second?.plus(1) ?: 1 acc[currentCardIndex] = matchingNumbers.size to currentCardCopies matchingNumbers.indices.forEach { j -> val otherCardIndex = currentCardIndex + j + 1 acc.merge(otherCardIndex, 0 to currentCardCopies) { (a, b), _ -> a to b + currentCardCopies } } acc }.values.sumOf { it.second }.toString() private fun String.getMatchingNumbers(): Set<Int> = this.split(':', '|') .drop(1) .map { it.trim().split(' ') .filter { numberString -> numberString.isNotEmpty() } .map { numberString -> numberString.trim().toInt() } } .let { it[0].toSet().intersect(it[1].toSet()) } } fun main() { main(Day04) }
0
Kotlin
0
0
a95d478aee72034321fdf37930722c23b246dd6b
1,572
advent-of-code
Apache License 2.0
src/me/bytebeats/algo/kt/Solution2.kt
bytebeats
251,234,289
false
null
package me.bytebeats.algo.kt import me.bytebeats.algs.ds.ListNode import me.bytebeats.algs.ds.TreeNode class Solution2 { fun removeDuplicates(s: String, k: Int): String { if (k < 2 || s.isEmpty() || s.length < k) { return s } var start = -1 var str = s start = startOfKDuplicates(str, k) while (start > -1) { str = str.substring(0, start) + str.substring(start + k) start = startOfKDuplicates(str, k) } return str } private fun startOfKDuplicates(s: String, k: Int): Int { var start = -1 var has = true for (i in 0..s.length - k) { has = true for (j in i + 1 until i + k) { if (s[j] != s[i]) { has = false break } } if (has) { start = i return start } } return start } fun verifyPreorder(preorder: IntArray): Boolean { if (preorder.isEmpty() || preorder.size == 1) { return true } return verifyPreorder(preorder, 0, preorder.lastIndex) } fun verifyPreorder(preorder: IntArray, s: Int, e: Int): Boolean { if (s >= e) { return true } val rootVal = preorder[s] var rightIndex = -1 for (i in s + 1..e) { if (rootVal < preorder[i]) { rightIndex = i break } } if (rightIndex == -1) { return verifyPreorder(preorder, s + 1, e) } else { for (i in rightIndex + 1..e) { if (rootVal > preorder[i]) { return false } } return verifyPreorder(preorder, s + 1, rightIndex - 1) && verifyPreorder(preorder, rightIndex, e) } } fun sortedArrayToBST(nums: IntArray): TreeNode? {//108 return createBST(nums, 0, nums.lastIndex) } fun createBST(nums: IntArray, s: Int, e: Int): TreeNode? { if (s > e) { return null } val mid = s + (e - s) / 2 val root = TreeNode(nums[mid]) root.left = createBST(nums, s, mid - 1) root.right = createBST(nums, mid + 1, e) return root } fun isRectangleOverlap(rec1: IntArray, rec2: IntArray): Boolean {//矩形是否重叠 return !(rec1[3] <= rec2[1] || rec1[1] >= rec2[3] || rec1[0] >= rec2[2] || rec1[2] <= rec2[0]) } fun computeArea(A: Int, B: Int, C: Int, D: Int, E: Int, F: Int, G: Int, H: Int): Int { val s1 = (C - A) * (D - B) val s2 = (G - E) * (H - F) if (A >= G || C <= E || B >= H || D <= F) { return s1 + s2 } else { val sX = Math.max(A, E) val sY = Math.max(B, F) val eX = Math.min(C, G) val eY = Math.min(D, H) return s1 - (eX - sX) * (eY - sY) + s2 } } fun minMoves2(nums: IntArray): Int { if (nums.size < 2) { return 0 } nums.sort() val mid = nums.size / 2 if (nums.size and 1 == 0) { val sum2 = nums.map { if (nums[mid - 1] > it) nums[mid - 1] - it else it - nums[mid - 1] }.sum() if (nums[mid] == nums[mid - 1]) { return sum2 } val sum1 = nums.map { if (nums[mid] > it) nums[mid] - it else it - nums[mid] }.sum() return if (sum1 > sum2) sum2 else sum1 } else { return nums.map { if (nums[mid] > it) nums[mid] - it else it - nums[mid] }.sum() } } fun minMoves(nums: IntArray): Int { var count = 0 val minVal = nums.minOfOrNull { it } ?: 0 nums.forEach { count += it - minVal } return count } fun confusingNumber(N: Int): Boolean { var num = N var newNum = 0 var rem = 0 while (num != 0) { rem = num % 10 if (isValidDigit(rem)) { newNum *= 10 if (isDifferentAfterRotated(rem)) { newNum += getRotatedDigit(rem) } else { newNum += rem } } else { return false } num /= 10 } return newNum != N } private fun isValidDigit(i: Int): Boolean = i == 1 || i == 0 || i == 8 || i == 6 || i == 9 private fun isDifferentAfterRotated(i: Int): Boolean = i == 6 || i == 9 fun getRotatedDigit(d: Int): Int = if (d == 9) 6 else 9 fun insertBits(N: Int, M: Int, i: Int, j: Int): Int { var sbN = N.toString(2).reversed() println(sbN) val sbM = M.toString(2) println(sbM) while (sbN.length < j + 1) { sbN = "${sbN}0" } println(sbM) val ans = StringBuilder() for (k in sbN.indices) { if (k < i) { ans.append(sbN[k]) } else if (k > i + sbM.length - 1) { ans.append(sbN[k]) } else { ans.append(sbM[k - i]) } println(ans.toString()) } return ans.reverse().toString().toInt(2) } fun insertBits2(N: Int, M: Int, i: Int, j: Int): Int { var n = N for (k in i..j) { n = n and (1.inv() shl i) } return n or (M shl i) } fun longestPalindrome(s: String): Int { val map = HashMap<Char, Int>() s.forEach { map.compute(it) { k, v -> if (v == null) 1 else v + 1 } } var count = 0 var oddCount = 0 count += map.values.map { if (it % 2 == 0) { it } else { oddCount++ it - 1 } }.sum() if (oddCount > 0) { count += 1 } return count } fun shiftingLetters(S: String, shifts: IntArray): String { val ans = StringBuilder(S) for (i in shifts.indices) { for (j in 0..i) { ans[j] = shift(ans[j], shifts[i]) } } return ans.toString() } private fun shift(ch: Char, shift: Int): Char { val mod = shift % 26 val d = ch - 'a' if (mod + d <= 26) { return ch + mod } else { return 'a' + (d + mod) % 26 - 1 } } fun reverseWords(s: String): String {//557 val ans = StringBuilder() s.trim().forEach { if (it == ' ') { if (ans.last() != ' ') { ans.append(it) } } else { ans.append(it) } } var i = 0 for (k in ans.indices) { if (k == ans.lastIndex) { reverse(ans, i, k) } else if (ans[k] == ' ') { reverse(ans, i, k - 1) i = k + 1 } } return ans.toString() } fun reverse(sb: StringBuilder, s: Int, e: Int) { if (s >= e || e >= sb.length || s >= sb.length) { return } val m = s + (e - s) / 2 var tmp = ' ' for (i in s..m) { tmp = sb[i] sb[i] = sb[e - i + s] sb[e - i + s] = tmp } } fun reverseWords(s: CharArray): Unit { var i = 0 var j = 0 for (k in s.indices) { if (k == s.lastIndex) { reverse(s, i, k) } else if (s[k] == ' ') { reverse(s, i, k - 1) i = k + 1 } } reverse(s, 0, s.lastIndex) } fun reverse(sb: CharArray, s: Int, e: Int) { if (s >= e || e >= sb.size || s >= sb.size) { return } val m = s + (e - s) / 2 var tmp = ' ' for (i in s..m) { tmp = sb[i] sb[i] = sb[e - i + s] sb[e - i + s] = tmp } } fun medianSlidingWindow(nums: IntArray, k: Int): DoubleArray { val ans = DoubleArray(k - nums.size + 1) return ans } fun canMeasureWater(x: Int, y: Int, z: Int): Boolean { if (x + y < z) { return false } else if (x == 0 || y == 0) { return z == 0 || x + y == z } else { return z % gcd(x, y) == 0 } } private fun gcd(m: Int, n: Int): Int { if (n == 0) { return m } else { return gcd(m, n % m) } } fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {//105, 面试题07 if (preorder == null || inorder == null || preorder.size != inorder.size) { return null } return buildTree(preorder, 0, preorder.lastIndex, inorder, 0, inorder.lastIndex) } private fun buildTree(preorder: IntArray, preS: Int, preE: Int, inorder: IntArray, inS: Int, inE: Int): TreeNode? { if (preS < 0 || inS < 0 || preS > preE || inS > inE || preE > preorder.lastIndex || inE > inorder.lastIndex) { return null } val root = TreeNode(preorder[preS]) var inSplit = -1 for (i in inS..inE) { if (inorder[i] == preorder[preS]) { inSplit = i break } } if (inSplit != -1) { val leftSize = inSplit - inS val rightSize = inE - inSplit if (leftSize > 0) { root.left = buildTree(preorder, preS + 1, preS + leftSize, inorder, inSplit - leftSize, inSplit - 1) } if (rightSize > 0) { root.right = buildTree(preorder, preS + leftSize + 1, preE, inorder, inSplit + 1, inE) } } return root } fun buildTree2(inorder: IntArray, postorder: IntArray): TreeNode? {//106 if (inorder == null || postorder == null || inorder.size != postorder.size) { return null } return buildTree2(inorder, 0, inorder.lastIndex, postorder, 0, postorder.lastIndex) } fun buildTree2(inorder: IntArray, inS: Int, inE: Int, postorder: IntArray, postS: Int, postE: Int): TreeNode? { if (inS > inE || postS > postE) { return null } val root = TreeNode(postorder[postE]) var inSplit = -1 for (i in inS..inE) { if (inorder[i] == postorder[postE]) { inSplit = i break } } if (inSplit != -1) { val leftSize = inSplit - inS val rightSize = inE - inSplit if (leftSize > 0) { root.left = buildTree2(inorder, inS, inSplit - 1, postorder, postS, postS + leftSize - 1) } if (rightSize > 0) { root.right = buildTree2(inorder, inSplit + 1, inE, postorder, postE - rightSize, postE - 1) } } return root } fun constructFromPrePost(pre: IntArray, post: IntArray): TreeNode? {//从先序和后序遍历生成二叉树 if (pre == null || post == null || pre.size != post.size) { return null } return construct(pre, 0, pre.lastIndex, post, 0, post.lastIndex) } private fun construct(pre: IntArray, preS: Int, preE: Int, post: IntArray, postS: Int, postE: Int): TreeNode? { if (preS > preE || postS > postE || pre[preS] != post[postE]) { return null } val root = TreeNode(pre[preS]) if (preS < preE) { var nextHeadIndex = -1 for (i in postS..postE) { if (post[i] == pre[preS + 1]) { nextHeadIndex = i break } } if (nextHeadIndex != -1) { val leftSize = nextHeadIndex - postS + 1 val rightSize = postE - nextHeadIndex - 1 if (leftSize > 0) { root.left = construct(pre, preS + 1, preS + leftSize, post, postS, postS + leftSize - 1) } if (rightSize > 0) { root.right = construct(pre, preE - rightSize + 1, preE, post, nextHeadIndex + 1, postE - 1) } } } return root } fun verifyPostorder(postorder: IntArray): Boolean { return verifyPostorder(postorder, 0, postorder.lastIndex) } fun verifyPostorder(postorder: IntArray, s: Int, e: Int): Boolean { if (s >= e) { return true } var l = s while (postorder[l] < postorder[e]) { l++ } val m = l while (postorder[l] > postorder[e]) { l++ } return l == e && verifyPostorder(postorder, s, m - 1) && verifyPostorder(postorder, m, e - 1) } fun findTheDistanceValue(arr1: IntArray, arr2: IntArray, d: Int): Int {//1385 var count = 0 var flag = false for (i in arr1.indices) { flag = false for (j in arr2.indices) { if (Math.abs(arr1[i] - arr2[j]) <= d) { flag = true } } if (!flag) { count++ } } return count } fun getKth(lo: Int, hi: Int, k: Int): Int { val weights = HashMap<Int, Int>(hi - lo + 1) for (i in lo..hi) { weights.put(i, getWeight(i)) } weights.entries.sortedBy { it.key }.sortedBy { it.value }.forEach { println("${it.key}, ${it.value}") } return weights.entries.sortedBy { it.key }.sortedBy { it.value }.map { it.key }.take(k).last() } private fun getWeight(N: Int): Int { var weight = 0 var n = N while (n != 1) { if (n and 1 == 0) { n /= 2 } else { n = n * 3 + 1 } weight++ } return weight } fun maxNumberOfFamilies(n: Int, reservedSeats: Array<IntArray>): Int { val matrix = Array(reservedSeats.size) { IntArray(10) { 0 } } var x = 0 var y = 0 for (i in reservedSeats.indices) { x = reservedSeats[i][0] - 1 y = reservedSeats[i][1] - 1 matrix[x][y] = -1 } var count = 0 var a = true var b = true var c = true var d = true for (i in matrix.indices) { a = true b = true c = true d = true for (j in 0..9) { if (matrix[i][j] == -1) { if (j in 1..2) { a = false } else if (j in 3..4) { b = false } else if (j in 5..6) { c = false } else if (j in 7..8) { d = false } } } println("$a, $b, $c, $d") if (a && b && c && d) { count += 2 continue } else if (a && b && c) { count++ continue } else if (b && c && d) { count++ continue } else if (a && b) { continue count++ } else if (b && c) { continue count++ } else if (c && d) { continue count++ } } return count } fun createTargetArray(nums: IntArray, index: IntArray): IntArray {//1389 val ans = ArrayList<Int>() for (i in nums.indices) { ans.add(index[i], nums[i]) } return ans.toIntArray() } fun sumFourDivisors(nums: IntArray): Int { var sum = 0 for (i in nums.indices) { if (divisors(nums[i]).size == 4) { sum += divisors(nums[i]).sum() } } return sum } private fun divisors(num: Int): Set<Int> { val set = HashSet<Int>() for (i in 1..Math.sqrt(num.toDouble()).toInt()) { if (num % i == 0) { set.add(i) set.add(num / i) } } return set } fun hasValidPath(grid: Array<IntArray>): Boolean { val m = grid.size val n = grid[0].size var x = 0 var y = 0 while (x > -1 && y > -1 && x < m && y < n) { if (grid[x][y] == 1) { if (y < m - 1) { if (grid[x][y + 1] == 3 || grid[x][y + 1] == 4 || grid[x][y] == 6) { y++ } else if (grid[x][y + 1] == 5) { y-- } else { break } } else { break } } else if (grid[x][y] == 2 || grid[x][y] == 3) { if (x < m - 1) { if (grid[x + 1][y] == 5) { x++ } else if (grid[x + 1][y] == 6) { x++ } else { break } } else { break } } else if (grid[x][y] == 5) { if (x > 1) { if (grid[x - 1][y] in 2..4) { x-- } else { break } } else { break } } else { break } } return x == m - 1 && y == n - 1 } fun longestPrefix(s: String): String { val prefixs = ArrayList<String>() var size = 1 var prefix = "" while (size++ < s.length) { prefix = s.substring(0, size) if (prefix == s.substring(s.length - size)) { prefixs.add(prefix) } } prefixs.forEach { print(", $it") } if (prefixs.isEmpty()) { return "" } else { prefixs.sortBy { it.length } return prefixs.last() } } fun longestPrefix2(s: String): String { val next = IntArray(s.length) var max = 0 var j = 0 for (i in 1..s.lastIndex) { while (j > 0 && s[i] != s[j]) { j = next[j - 1] } if (s[i] == s[j]) { j++ } next[i] = j } next.forEach { print(", $it") } return s.substring(0, next.last()) } fun removeElements(head: ListNode?, `val`: Int): ListNode? {//203 val dummy = ListNode(-1) dummy.next = head var p = dummy while (p?.next != null) { if (p.next.`val` == `val`) { p.next = p.next.next } else { p = p.next } } return dummy.next } fun middleNode(head: ListNode?): ListNode? { if (head == null) { return null } var size = 0 var p = head while (p != null) { p = p.next size++ } var half = size / 2 p = head while (half-- > 0) { p = p?.next } return p } fun oddEvenList(head: ListNode?): ListNode? {//328, 奇数索引节点在前, 偶数索引节点在后 if (head == null) return null var odd: ListNode = head var even = head.next val evenHead = even while (even?.next != null) { odd.next = even.next odd = odd.next even.next = odd.next even = even.next } odd.next = evenHead return head } fun splitListToParts(root: ListNode?, k: Int): Array<ListNode?> { var count = 0 var p = root while (p != null) { p = p.next count++ } val ans = Array<ListNode?>(k) { null } return ans } fun partition(head: ListNode?, x: Int): ListNode? { val preXDummy = ListNode(-1) val postXDummy = ListNode(-1) var p = preXDummy var q = postXDummy var k = head while (k != null) { // if (k.`val` < x) } preXDummy.next return preXDummy.next } fun arrayPairSum(nums: IntArray): Int {//561 nums.sort() return nums.filterIndexed { index, _ -> index and 1 == 0 }.sum() } fun thirdMax(nums: IntArray): Int { val map = HashMap<Int, Int>() nums.forEach { map.compute(it) { k, v -> 0 } } val ans = map.keys.sortedBy { it } ans.forEach { print(", ${it}") } if (ans.size >= 3) { return ans.drop(map.size - 3).first() } else { return ans.last() } } fun triangleNumber(nums: IntArray): Int { var count = 0 for (i in 0..nums.size - 3) { for (j in i + 1..nums.size - 2) { for (k in j + 1..nums.size - 1) { if (isTriangleValid(nums[i], nums[j], nums[k])) { count++ } } } } return count } private fun isTriangleValid(a: Int, b: Int, c: Int): Boolean { return a * b * c != 0 && Math.abs(a + b) > c && Math.abs(b + c) > a && Math.abs(a + c) > b } fun shortestToChar(S: String, C: Char): IntArray { val ans = IntArray(S.length) val set = HashSet<Int>() S.forEachIndexed { index, ch -> if (ch == C) { set.add(index) } } val min = set.minOfOrNull { it } ?: 0 val max = set.maxOfOrNull { it } ?: 0 S.forEachIndexed { index, c -> if (set.contains(index)) { ans[index] = 0 } else { if (index < min) { ans[index] = min - index } else if (index > max) { ans[index] = index - max } else { var minDiff = Int.MAX_VALUE set.forEach { if (Math.abs(it - index) < minDiff) { minDiff = Math.abs((it - index)) } } ans[index] = minDiff } } } return ans } fun toGoatLatin(S: String): String {//824 val ans = StringBuilder() val words = S.split(" ") words.forEachIndexed { index, s -> ans.append(" ") ans.append(toGoatLatin(s, index)) } return ans.substring(1) } private fun toGoatLatin(s: String, index: Int): String { val ans = StringBuilder() if (startWithVowel(s)) { ans.append(s) } else { ans.append(s.substring(1)) ans.append(s.first()) } ans.append("ma") for (i in 0..index) { ans.append('a') } return ans.toString() } private fun startWithVowel(s: String): Boolean { val ch = s.first() return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' } fun largeGroupPositions(S: String): List<List<Int>> { val ans = ArrayList<List<Int>>() var i = 0 var ch = ' ' var j = 0 while (i < S.length) { ch = S[i] j = i + 1 while (j < S.length && S[j] == ch) { j++ } if (j - i >= 3) { val element = ArrayList<Int>(2) element.add(i) element.add(j - 1) ans.add(element) } i = j } return ans } fun removeElement(nums: IntArray, `val`: Int): Int { var ans = nums.size if (nums.isNotEmpty()) { var i = -1 for (j in nums.indices) { if (nums[j] == `val`) { if (i < 0) { i = j } ans-- } else { if (i > -1) { nums[i++] = nums[j] } } } } return ans } fun minSubArrayLen(s: Int, nums: IntArray): Int { var sum = 0 for (i in 1..nums.size) { sum = 0 for (j in 0 until i - 1) { sum += nums[j] } for (k in i until nums.size) { sum += nums[k] if (sum >= s) { return i } sum -= nums[k - i + 1] } } return 0 } fun moveZeroes(nums: IntArray): Unit { var i = 0 var j = nums.lastIndex while (i < j) { if (nums[i] != 0) { i++ } else { for (k in i + 1..j) { nums[k - 1] = nums[k] } nums[j] = 0 j-- } } } fun findDiagonalOrder(matrix: Array<IntArray>): IntArray { val m = matrix.size val n = matrix[0].size val ans = IntArray(m * n) var k = 0 val min = if (m > n) n else m var up = true for (i in 0 until min) { for (j in 0..i) { if (up) { ans[k++] = matrix[i - j][j] } else { ans[k++] = matrix[j][i - j] } } up = !up } if (m != n) { if (m > n) { for (i in 0 until m - n) { for (j in 0 until n) { if (up) { ans[k++] = matrix[n + i - j][j] } else { ans[k++] = matrix[n + j][n - j] } } up = !up } } else { for (i in 0 until n - m) { for (j in 0 until m) { if (up) { ans[k++] = matrix[m + i - j][j] } else { ans[k++] = matrix[m + j][m - j] } } up = !up } } } for (i in 0 until min - 1) { for (j in min - 2 - i..0) { if (up) { ans[k++] = matrix[m - 1][j + 1] } else { ans[k++] = matrix[m - i + j - 1][min - j] } } up = !up } return ans } fun reverseOnlyLetters(S: String): String { val ans = StringBuilder(S) var i = 0 var j = ans.lastIndex var tmp = ' ' while (i < j) { if (ans[i].isLetter() && ans[j].isLetter()) { tmp = ans[i] ans[i] = ans[j] ans[j] = tmp i++ j++ } else if (!ans[i].isLetter() && !ans[j].isLetter()) { i++ j-- } else if (ans[i].isLetter()) { j-- } else { i++ } } return ans.toString() } fun CheckPermutation(s1: String, s2: String): Boolean { if (s1 == s2) { return true } if (s1.length != s2.length) { return false } val map1 = HashMap<Char, Int>() s1.forEach { map1.compute(it) { k, v -> if (v == null) 1 else v + 1 } } val map2 = HashMap<Char, Int>() s2.forEach { map2.compute(it) { k, v -> if (v == null) 1 else v + 1 } } if (map1.size != map2.size) { return false } var res = true map1.forEach { t, u -> if (!map2.containsKey(t) || map2[t] != u) { res = false return@forEach } } return res } fun replaceSpaces(S: String, length: Int): String { val ans = S.toCharArray() var i = length - 1 var j = ans.lastIndex while (i > 0) { if (ans[i] != ' ') { ans[j--] = ans[i--] } else { i-- ans[j--] = '0' ans[j--] = '2' ans[j--] = '%' } } return String(ans) } fun hasGroupsSizeX(deck: IntArray): Boolean { val map = HashMap<Int, Int>() deck.forEach { map.compute(it) { _, v -> if (v == null) 1 else v + 1 } } map.forEach { t, u -> println("$t = $u") } val min = map.values.minOfOrNull { it } ?: 0 val max = map.values.maxOfOrNull { it } ?: 0 val d = gcd(min, max) if (d < 2) { return false } var ans = true map.values.forEach { if (it % d != 0) { ans = false return@forEach } } return ans } fun lastRemaining(n: Int, m: Int): Int { var ans = 0 var i = 2 while (i != n + 1) { ans = (m + ans) % i i++ } return ans } fun gameOfLife(board: Array<IntArray>): Unit { val ans = Array(board.size) { IntArray(board[0].size) } for (i in board.indices) { for (j in board[i].indices) { ans[i][j] = compute(board, i, j) } } for (i in ans.indices) { for (j in ans[i].indices) { board[i][j] = ans[i][j] } } } private fun compute(board: Array<IntArray>, x: Int, y: Int): Int { var count = 0 val src = board[x][y] var preX = x - 1 var preY = y - 1 var nextX = x + 1 var nextY = y + 1 if (preX > -1) { if (preY > -1 && board[preX][preY] == 1) { count++ } if (board[preX][y] == 1) { count++ } if (nextY < board[0].size && board[preX][nextY] == 1) { count++ } } if (nextX < board.size) { if (preY > -1 && board[nextX][preY] == 1) { count++ } if (board[nextX][y] == 1) { count++ } if (nextY < board[0].size && board[nextX][nextY] == 1) { count++ } } if (preY > -1 && board[x][preY] == 1) { count++ } if (nextY < board[0].size && board[x][nextY] == 1) { count++ } return if (src == 1) { if (count < 2) 0 else if (count in 2..3) 1 else if (count > 3) 0 else 0 } else { if (count == 3) 1 else 0 } } fun titleToNumber(s: String): Int { var ans = 0 s.forEach { ans *= 26 ans += it - 'A' + 1 } return ans } fun myAtoi(str: String): Int { var ans = 0 var s = str.trim() var negative = false if (s.isNotEmpty()) { var firstDigitIndex = 0 for (i in s.indices) { if (s[i].isDigit()) { firstDigitIndex = i break } } if (firstDigitIndex > 1) { return 0 } val firstChar = s.first() if (firstChar == '-') { negative = true s = s.substring(1) } else if (firstChar == '+') { negative = false s = s.substring(1) } else { negative = false } for (i in s.indices) { if (s[i].isDigit()) { if (ans > Int.MAX_VALUE / 10 || ans == Int.MAX_VALUE / 10 && s[i] - '0' > 7) { if (negative) { return Int.MIN_VALUE } else { return Int.MAX_VALUE } } else { ans *= 10 ans += s[i] - '0' } } else if (s[i] == '+' || s[i] == '-') { break } else { break } } } return if (negative) -ans else ans } //dp[i] = max(dp[i - 1], nums[i] + dp[i - 2]) fun rob(nums: IntArray): Int {//loop var tmp = 0 var dp1 = 0 var dp2 = 0 for (i in 0..nums.lastIndex) { if (i == 0) { dp1 = nums[0] } else if (i == 1) { dp2 = Math.max(dp1, nums[1]) } else { tmp = Math.max(dp2, nums[i] + dp1) dp1 = dp2 dp2 = tmp } } return Math.max(dp1, dp2) // return rob(nums, nums.lastIndex) } // private fun rob(nums: IntArray, i: Int): Int{//recursive // if(i == 0){ // return nums[0] // } else if(i == 1){ // return Math.max(nums[0], nums[1]) // } else { // return Math.max(rob(nums, i - 1), rob(nums, i - 2) + nums[i]) // } // } fun rob2(nums: IntArray): Int { if (nums.isEmpty()) { return 0 } if (nums.size == 1) { return nums[0] } if (nums.size == 2) { return Math.max(nums[0], nums[1]) } var tmp = 0 var dp1 = 0 var dp2 = 0 for (i in 0..nums.lastIndex - 1) { if (i == 0) { dp1 = nums[0] } else if (i == 1) { dp2 = Math.max(dp1, nums[1]) } else { tmp = Math.max(dp2, nums[i] + dp1) dp1 = dp2 dp2 = tmp } } val p1 = Math.max(dp1, dp2) tmp = 0 dp1 = 0 dp2 = 0 for (i in 1..nums.lastIndex) { if (i == 0) { dp1 = nums[0] } else if (i == 1) { dp2 = Math.max(dp1, nums[1]) } else { tmp = Math.max(dp2, nums[i] + dp1) dp1 = dp2 dp2 = tmp } } val p2 = Math.max(dp1, dp2) return Math.max(p1, p2) } fun rob(root: TreeNode?): Int { if (root == null) { return 0 } var ans = root.`val` if (root.left != null) { ans += rob(root.left.left) + rob(root.left.right) } if (root.right != null) { ans += rob(root.right.left) + rob(root.right.right) } return Math.max(ans, rob(root.left) + rob(root.right)) } // fun rob(root: TreeNode?): Int { // if (root == null) { // return 0 // } else { // if (root.left == null && root.right == null) { // return root.`val` // } else if (root.left != null && root.right != null) { // return Math.max( // root.`val` + rob(root.left.left) + rob(root.left.right) + rob(root.right.left) + rob(root.right.right), // rob(root.left) + rob(root.right) // ) // } else if (root.left != null) { // return Math.max(root.`val` + rob(root.left.left) + rob(root.left.right), rob(root.left)) // } else { // return Math.max(root.`val` + rob(root.right.left) + rob(root.right.right), rob(root.right)) // } // } // } fun maxDepthAfterSplit(seq: String): IntArray { return IntArray(0) } fun nthUglyNumber(n: Int): Int { val uglies = IntArray(1690) uglies[0] = 1 var ugly = 0 var i2 = 0 var i3 = 0 var i5 = 0 for (i in 1 until 1690) { ugly = Math.min(Math.min(uglies[i2] * 2, uglies[i3] * 3), uglies[i5] * 5) uglies[i] = ugly if (ugly == uglies[i2] * 2) i2++ if (ugly == uglies[i3] * 3) i3++ if (ugly == uglies[i5] * 5) i5++ } return uglies[n - 1] } fun rotate(matrix: Array<IntArray>): Unit {//顺时针旋转90 度 val n = matrix.size var tmp = 0 for (i in 0 until n / 2) {//y for (j in i until n - 1 - i) {//x tmp = matrix[j][i] matrix[j][i] = matrix[n - i - 1][j] matrix[n - i - 1][j] = matrix[n - j - 1][n - i - 1] matrix[n - j - 1][n - i - 1] = matrix[i][n - j - 1] matrix[i][n - j - 1] = tmp } } } fun findMissingRanges(nums: IntArray, lower: Int, upper: Int): List<String> { val ans = mutableListOf<String>() if (nums.isNotEmpty()) { if (lower < nums.first()) { if (nums.first() - lower.toLong() > 1L) {//in case result of minus greater than Int.MAX_VALUE ans.add("$lower->${nums.first() - 1}") } else { ans.add("$lower") } } for (i in 1..nums.lastIndex) { if (nums[i].toLong() - nums[i - 1] > 1) { if (nums[i].toLong() - nums[i - 1] > 2) {//in case result of minus greater than Int.MAX_VALUE ans.add("${nums[i - 1] + 1}->${nums[i] - 1}") } else { ans.add("${nums[i] - 1}") } } else { continue } } if (upper > nums.last()) { if (upper.toLong() - nums.last() > 1) {//in case result of minus greater than Int.MAX_VALUE ans.add("${nums.last() + 1}->$upper") } else { ans.add("$upper") } } } else { if (upper.toLong() - lower > 0) {//in case result of minus greater than Int.MAX_VALUE ans.add("$lower->$upper") } else { ans.add("$lower") } } return ans } //lowest common ancestor of a binary search tree fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? { if (root == null || p == null || q == null) { return null } var t = root while (t != null && t != p && t != q) { if (t?.`val` < p?.`val` && t?.`val` < q?.`val`) { t = t.right } else if (t?.`val` > p?.`val` && t?.`val` > q?.`val`) { t = t.left } else { break } } return t } fun countElements(arr: IntArray): Int { var count = 0 if (arr.size > 1) { val set = mutableSetOf<Int>() arr.forEach { if (!set.contains(it)) { set.add(it) } } for (i in arr.indices) { if (set.contains(arr[i] + 1)) { count++ } } } return count } fun movingCount(m: Int, n: Int, k: Int): Int { if (k == 0) { return 1 } var ans = 0 val matrix = Array(m) { IntArray(n) { 0 } } for (i in 0 until m) { for (j in 0 until n) { if (i == 0 && j == 0) { matrix[i][j] = 1 ans = 1 } else if (sum(i) + sum(j) > k) { continue } else { if (i > 0) { matrix[i][j] = matrix[i][j] or matrix[i - 1][j] } if (j > 0) { matrix[i][j] = matrix[i][j] or matrix[i][j - 1] } ans += matrix[i][j] } } } return ans } private fun sum(num: Int): Int { var ans = 0 var n = num while (n != 0) { ans += n % 10 n /= 10 } return ans } fun reversePrint(head: ListNode?): IntArray { var p = head var count = 0 while (p != null) { p = p.next count++ } val ans = IntArray(count) p = head count = 0 while (p != null) { ans[count++] = p.`val` p = p.next } ans.reverse() return ans } fun middleNode2(head: ListNode?): ListNode? { var p = head var q = head while (q != null && q.next != null) { p = p?.next q = q.next.next } if (q != null && q.next != null) { p = p?.next } return p } fun generateParenthesis(n: Int): List<String> {//22 val ans = mutableListOf<String>() backtrack(ans, StringBuilder(), 0, 0, n) return ans } private fun backtrack(ans: MutableList<String>, sb: StringBuilder, open: Int, close: Int, max: Int) { if (sb.length == max * 2) { ans.add(sb.toString()) return } if (open < max) { sb.append('(') backtrack(ans, sb, open + 1, close, max) sb.deleteCharAt(sb.lastIndex) } if (close < open) { sb.append(')') backtrack(ans, sb, open, close + 1, max) sb.deleteCharAt(sb.lastIndex) } } fun isStrobogrammatic(num: String): Boolean {//246 for (i in 0 until (num.length + 1) / 2) { if (isRotatable(num[i]) && isRotatable(num[num.length - 1 - i]) && isSameAfterRotated(num[num.length - 1 - i], num[i]) ) { continue } else { return false } } return true } private fun isSameAfterRotated(ch1: Char, ch2: Char): Boolean { return ch1 == ch2 && ch2 == '1' || ch1 == ch2 && ch2 == '0' || ch1 == ch2 && ch2 == '8' || ch1 == '9' && ch2 == '6' || ch1 == '6' && ch2 == '9' } private fun isRotatable(ch: Char): Boolean = ch == '0' || ch == '1' || ch == '6' || ch == '8' || ch == '9' val map1 = mapOf('0' to '0') val map2 = mapOf('1' to '1', '8' to '8') val map3 = mapOf('6' to '9', '9' to '6') fun findStrobogrammatic(n: Int): List<String> {//247 val ans = mutableListOf<String>() findStrobogrammatic(n, "", "", ans, n) ans.sort() return ans } private fun findStrobogrammatic(n: Int, left: String, right: String, ans: MutableList<String>, max: Int) { if (n < 0) { //nothing } else if (n == 0) { ans.add("$left$right") } else if (n == 1) { map1.keys.forEach { ans.add("$left$it$right") } map2.keys.forEach { ans.add("$left$it$right") } } else { if (n != 2 && n != 3) {// in case of "01..." & "...10" map1.keys.forEach { findStrobogrammatic(n - 2, "$it$left", "$right$it", ans, max) } } map2.keys.forEach { findStrobogrammatic(n - 2, "$it$left", "$right$it", ans, max) } map3.keys.forEach { findStrobogrammatic(n - 2, "$it$left", "$right${map3[it]}", ans, max) } } } fun backspaceCompare(S: String, T: String): Boolean {//844 return get(S) == get(T) } private fun get(s: String): String { val ans = StringBuilder() s.forEach { if (it == '#') { if (ans.isNotEmpty()) { ans.deleteCharAt(ans.lastIndex) } } else { ans.append(it) } } return ans.toString() } fun addDigits(num: Int): Int {//258 var n = num var tmp = 0 while (n > 9) { tmp = 0 while (n > 0) { tmp += n % 10 n /= 10 } n = tmp } return n } fun intersection(nums1: IntArray, nums2: IntArray): IntArray {//349 return nums1.distinct().intersect(nums2.distinct()).toIntArray() } fun intersect(nums1: IntArray, nums2: IntArray): IntArray {//350 nums1.sort() nums2.sort() val ans = mutableListOf<Int>() var i = 0 var j = 0 while (i < nums1.size && j < nums2.size) { if (nums1[i] > nums2[j]) { j++ } else if (nums1[i] < nums2[j]) { i++ } else { ans.add(nums1[i]) i++ j++ } } return ans.toIntArray() } fun arraysIntersection(arr1: IntArray, arr2: IntArray, arr3: IntArray): List<Int> {//1213 val ans = mutableListOf<Int>() val intersetList = mutableListOf<Int>() var i = 0 var j = 0 while (i < arr1.size && j < arr2.size) { if (arr1[i] > arr2[j]) { j++ } else if (arr1[i] < arr2[j]) { i++ } else { intersetList.add(arr1[i]) i++ j++ } } if (intersetList.isNotEmpty()) { i = 0 j = 0 while (i < intersetList.size && j < arr3.size) { if (intersetList[i] > arr3[j]) { j++ } else if (intersetList[i] < arr3[j]) { i++ } else { ans.add(intersetList[i]) i++ j++ } } } return ans } fun commonChars(A: Array<String>): List<String> {//1002 val chCounts = Array(A.size) { IntArray(26) } val ans = mutableListOf<String>() A.forEachIndexed { index, s -> count(chCounts[index], s) } for (i in 0..25) { var min = Int.MAX_VALUE for (j in A.indices) { if (chCounts[j][i] == 0) { min = 0 break } else { if (min > chCounts[j][i]) { min = chCounts[j][i] } } } while (min-- > 0) { ans.add(('a' + i).toString()) } } return ans } private fun count(array: IntArray, s: String) { s.forEach { array[it - 'a']++ } } fun numberOfSubstrings(s: String): Int {//1358 var ans = 0 val counts = IntArray(3) { 0 } val size = s.length var r = -1 var i = 0 while (i < size) { while (r < size && !(counts[0] >= 1 && counts[1] >= 1 && counts[2] >= 1)) { if (++r == size) { break } counts[s[r] - 'a']++ } ans += size - r counts[s[i++] - 'a']-- } return ans } fun compareVersion(version1: String, version2: String): Int {//165 if (version1 == version2) { return 0 } val dotCount1 = version1.count { it == '.' } val dotCount2 = version2.count { it == '.' } val s = (if (dotCount1 > dotCount2) dotCount1 else dotCount2) + 1 val vNum1 = IntArray(s) { 0 } version1.split(".").forEachIndexed { index, s -> vNum1[index] = s.toInt() } val vNum2 = IntArray(s) { 0 } version2.split(".").forEachIndexed { index, s -> vNum2[index] = s.toInt() } for (i in 0 until s) { if (vNum1[i] > vNum2[i]) { return 1 } else if (vNum1[i] < vNum2[i]) { return -1 } } return 0 } }
0
Kotlin
0
1
7cf372d9acb3274003bb782c51d608e5db6fa743
48,765
Algorithms
MIT License
src/main/kotlin/days/Day5.kt
butnotstupid
571,247,661
false
{"Kotlin": 90768}
package days class Day5 : Day(5) { override fun partOne(): Any { val mapState = parseMap().map { it.toMutableList() } parseCommands().forEach { (number, from, to) -> repeat(number) { mapState[to - 1].add(0, mapState[from - 1].first()) mapState[from - 1].removeFirst() } } return mapState.map { it.first() }.joinToString("") } override fun partTwo(): Any { val mapState = parseMap().map { it.toMutableList() } parseCommands().forEach { (number, from, to) -> mapState[to - 1].addAll(0, mapState[from - 1].subList(0, number)) repeat(number) { mapState[from - 1].removeFirst() } } return mapState.map { it.first() }.joinToString("") } private fun parseMap(): List<List<Char>> = inputList .takeWhile { !it.startsWith(" 1") } .map { row -> row.chunked(4) .map { it[1] } .withIndex() .filter { it.value != ' ' } .map { it.value to it.index } } .flatten() .groupBy { it.second } .mapValues { (_, value) -> value.map { it.first } } .toSortedMap().values .toList() private fun parseCommands(): List<Command> = inputList .dropWhile { !it.startsWith("move") } .map { commandRaw -> inputRegex .matchEntire(commandRaw)!!.groupValues.drop(1) .map { it.toInt() } } .map { (number, from, to) -> Command(number, from, to) } data class Command(val number: Int, val from: Int, val to: Int) private companion object { private val inputRegex = "move (\\d*) from (\\d*) to (\\d*)".toRegex() } }
0
Kotlin
0
0
4760289e11d322b341141c1cde34cfbc7d0ed59b
1,788
aoc-2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/leetcode/P1314.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://github.com/antop-dev/algorithm/issues/277 class P1314 { fun matrixBlockSum(mat: Array<IntArray>, k: Int): Array<IntArray> { val dp = Array(mat.size) { i -> IntArray(mat[i].size) }.apply { this[0][0] = mat[0][0] for (i in 1 until mat.size) this[i][0] = this[i - 1][0] + mat[i][0] for (i in 1 until mat[0].size) this[0][i] = this[0][i - 1] + mat[0][i] for (i in 1 until mat.size) { for (j in 1 until mat[i].size) { this[i][j] = this[i - 1][j] + this[i][j - 1] + mat[i][j] - this[i - 1][j - 1] } } } return Array(mat.size) { i -> IntArray(mat[i].size) }.apply { for (i in mat.indices) { for (j in mat[i].indices) { val y = minOf(i + k, dp.lastIndex) val x = minOf(j + k, dp[i].lastIndex) this[i][j] = dp[y][x] val r = i - k - 1 val c = j - k - 1 if (r >= 0) this[i][j] -= dp[r][x] if (c >= 0) this[i][j] -= dp[y][c] if (r >= 0 && c >= 0) this[i][j] += dp[r][c] } } } } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,271
algorithm
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[16]最接近的三数之和.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import kotlin.math.abs //给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和 //。假定每组输入只存在唯一答案。 // // // // 示例: // // 输入:nums = [-1,2,1,-4], target = 1 //输出:2 //解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。 // // // // // 提示: // // // 3 <= nums.length <= 10^3 // -10^3 <= nums[i] <= 10^3 // -10^4 <= target <= 10^4 // // Related Topics 数组 双指针 // 👍 784 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun threeSumClosest(nums: IntArray, target: Int): Int { //双指针 遍历 Arrays.sort(nums) //先随意计算一个结果值 var res = nums[0]+nums[1]+nums[2] for (i in 0 until nums.size){ var left = i+1 var right = nums.size -1 while (left < right){ //获取当前遍历的和 var currSum = nums[i] + nums[left] + nums[right] if (Math.abs(target - currSum) < Math.abs(target - res)){ //更接近 res = currSum } when{ currSum > target ->{ right -- } currSum < target ->{ left++ } else -> { //sum = target return target } } } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,760
MyLeetCode
Apache License 2.0
src/year2022/day10/Day10.kt
kingdongus
573,014,376
false
{"Kotlin": 100767}
package year2022.day10 import readInputFileByYearAndDay import readTestFileByYearAndDay fun main() { fun calculateXOverTime(input: List<String>): Array<Int> { val history = Array(input.size * 3) { 1 } var cycle = 1 var x = 1 input .map { if (it == "noop") "noop 0" else it } // append the 0 for easier parsing later .map { it.split(" ") } .map { it.first() to it.last().toInt() } .forEach { when (it.first) { "noop" -> history[cycle++] = x "addx" -> { history[cycle++] = x x += it.second history[cycle++] = x } else -> println("oh no") } } return history } fun part1(input: List<String>): Int { val history = calculateXOverTime(input) return listOf(20, 60, 100, 140, 180, 220).sumOf { it * history[it - 1] } } fun part2(input: List<String>): String { val spritePositions = calculateXOverTime(input) return listOf(0, 40, 80, 120, 160, 200) .map { it..it + 39 } .joinToString("\n") { row -> row.joinToString(separator = "") { val spriteRange = spritePositions[it] - 1..spritePositions[it] + 1 if (spriteRange.contains(it % 40)) "#" else "." } } } val testInput = readTestFileByYearAndDay(2022, 10) check(part1(testInput) == 13140) check( part2(testInput) == "##..##..##..##..##..##..##..##..##..##..\n" + "###...###...###...###...###...###...###.\n" + "####....####....####....####....####....\n" + "#####.....#####.....#####.....#####.....\n" + "######......######......######......####\n" + "#######.......#######.......#######....." ) val input = readInputFileByYearAndDay(2022, 10) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
aa8da2591310beb4a0d2eef81ad2417ff0341384
2,103
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/KWeakestRows.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue /** * 1337. The K Weakest Rows in a Matrix * @see <a href="https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix">Source</a> */ fun interface KWeakestRows { operator fun invoke(mat: Array<IntArray>, k: Int): IntArray } class KWeakestRowsPQ : KWeakestRows { override fun invoke(mat: Array<IntArray>, k: Int): IntArray { fun numOnes(row: IntArray): Int { var lo = 0 var hi = row.size while (lo < hi) { val mid = lo + (hi - lo) / 2 if (row[mid] == 1) lo = mid + 1 else hi = mid } return lo } val pq: PriorityQueue<IntArray> = PriorityQueue { a, b -> if (a[0] != b[0]) b[0] - a[0] else b[1] - a[1] } var k0 = k val ans = IntArray(k0) for (i in mat.indices) { pq.offer(intArrayOf(numOnes(mat[i]), i)) if (pq.size > k0) pq.poll() } while (k0 > 0) { ans[--k0] = pq.poll()[1] } return ans } } class KWeakestRowsBF : KWeakestRows { override fun invoke(mat: Array<IntArray>, k: Int) = Pair(mat, k).kWeakestRows() private fun Pair<Array<IntArray>, Int>.kWeakestRows(): IntArray { val matrix = first val rows = matrix.size val cols = matrix.first().size val score = IntArray(rows) var j: Int for (i in 0 until rows) { j = 0 while (j < cols) { if (matrix[i][j] == 0) { break } j++ } score[i] = j * rows + i } score.sort() for (i in score.indices) { score[i] = score[i] % rows } return score.copyOfRange(0, second) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,464
kotlab
Apache License 2.0
src/main/java/com/ncorti/aoc2021/Exercise13.kt
cortinico
433,486,684
false
{"Kotlin": 36975}
package com.ncorti.aoc2021 object Exercise13 { private fun getInput(): Pair<List<String>, Array<IntArray>> { val input = getInputAsTest("13") { split("\n") } val size = input.filter { "," in it }.flatMap { it.trim().split(",") }.maxOf(String::toInt) + 1 val world = Array(size) { i -> IntArray(size) { j -> if ("$j,$i" in input) 1 else 0 } } return input to world } private fun Array<IntArray>.runFolding(folds: List<List<String>>) = folds.forEach { (axes, number) -> if (axes == "y") { val row = number.toInt() for (i in 1 until this.size - row) { for (j in this.indices) { if (row - i >= 0) { this[row - i][j] += this[row + i][j] this[row + i][j] = 0 } } } } else { val col = number.toInt() for (i in 1 until this.size - col) { for (j in this.indices) { if (col - i >= 0) { this[j][col - i] += this[j][col + i] this[j][col + i] = 0 } } } } } fun part1() = getInput().let { (input, world) -> world.runFolding(listOf(input.first { "fold" in it }.split(" ").last().split("="))) return@let world.sumOf { it.count { cell -> cell != 0 } } } fun part2() = getInput().let { (input, world) -> world.runFolding(input.filter { "fold" in it }.map { it.split(" ").last().split("=") }) val lastX = input.last { "x" in it }.split("=").last().toInt() val lastY = input.last { "y" in it }.split("=").last().toInt() for (i in 0..lastY) { for (j in 0..lastX) { print(if (world[i][j] == 0) "." else "#") print("\t") } println("") } // Answer is on the stdout and here for your convenience ¯\_(ツ)_/¯ return@let "CJCKBAPB" } } fun main() { println(Exercise13.part1()) println(Exercise13.part2()) }
0
Kotlin
0
4
af3df72d31b74857201c85f923a96f563c450996
2,325
adventofcode-2021
MIT License
src/main/kotlin/days/Day07.kt
TheMrMilchmann
725,205,189
false
{"Kotlin": 61669}
/* * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package days import utils.* fun main() { data class Hand(val type: HandType, val cards: String) { override fun toString(): String = cards } fun String.toHandType(): HandType { val groups = groupBy { it } return when { groups.size == 1 -> HandType.FIVE groups.any { (_, values) -> values.size == 4 } -> HandType.FOUR groups.any { (_, values) -> values.size == 3 } -> when { groups.any { (_, values) -> values.size == 2 } -> HandType.FULL_HOUSE else -> HandType.THREE } groups.count { (_, values) -> values.size == 2 } == 2 -> HandType.TWO_PAIR groups.any { (_, values) -> values.size == 2 } -> HandType.ONE_PAIR else -> HandType.HIGH_CARD } } fun solve(symbols: String, replaceJokers: Boolean = false): Long = readInput().asSequence() .map { it.split(' ') } .map { (cards, bid) -> val hand = Hand( type = if (replaceJokers) { cards.replace('J', cards.filter { it != 'J' }.groupingBy { it }.eachCount().maxByOrNull(Map.Entry<Char, Int>::value)?.key ?: 'A') } else { cards }.toHandType(), cards = cards ) hand to bid.toLong() } .sortedWith { (a, _), (b, _) -> var res = a.type.compareTo(b.type) if (res != 0) return@sortedWith res for (i in 0..<5) { res = compareValuesBy(a, b) { it: Hand -> symbols.indexOf(it.cards[i]) } if (res != 0) return@sortedWith res } error("Should never be reached") } .mapIndexed { index, (_, bid) -> (index + 1) * bid } .sum() println("Part 1: ${solve("23456789TJQKA")}") println("Part 2: ${solve("J23456789TQKA", replaceJokers = true)}") } private enum class HandType { HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE, FULL_HOUSE, FOUR, FIVE }
0
Kotlin
0
1
f94ff8a4c9fefb71e3ea183dbc3a1d41e6503152
3,277
AdventOfCode2023
MIT License
src/y2022/Day19.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.readInput import util.transpose import kotlin.math.ceil object Day19 { class Resources( ore: Int = 0, clay: Int = 0, obsidian: Int = 0, geode: Int = 0, ) { constructor(list: List<Int>) : this(list[0], list[1], list[2], list[3]) val amounts = listOf(ore, clay, obsidian, geode) val geode: Int get() = amounts[3] operator fun plus(other: Resources): Resources { return Resources(amounts.zip(other.amounts).map { (t, o) -> t + o }) } operator fun minus(other: Resources): Resources { return Resources(amounts.zip(other.amounts).map { (t, o) -> t - o }) } operator fun div(other: Resources): Resources { return Resources(amounts.zip(other.amounts).map { (t, o) -> if (o == 0) 0 else t / o + 1 }) } operator fun times(factor: Int): Resources { return Resources(amounts.map { it * factor }) } override fun toString(): String { return amounts.toString() } } data class Blueprint( val id: Int, val oreRobotCost: Resources, val clayRobotCost: Resources, val obsidianRobotCost: Resources, val geodeRobotCost: Resources, ) { fun costList() = listOf(oreRobotCost, clayRobotCost, obsidianRobotCost, geodeRobotCost) operator fun get(idx: Int): Resources { return costList()[idx] } } val singleRobots = listOf( Resources(1), Resources(clay = 1), Resources(obsidian = 1), Resources(geode = 1) ) data class FactoryState( val blueprint: Blueprint, val remainingMinutes: Int = 24, val collected: Resources = Resources(), val robotNumbers: Resources = Resources(1), ) { companion object { val calculatedStates: MutableMap<List<Int>, Int> = mutableMapOf() var cacheLookups = 0 } fun key(): List<Int> { return collected.amounts + robotNumbers.amounts + listOf(remainingMinutes) } val maxBots = blueprint.costList().map { it.amounts }.transpose().map { it.max() } fun maxGeodes(): Int { if (remainingMinutes == 0) { return collected.geode } if (remainingMinutes == 1) { return collected.geode + robotNumbers.geode } if (key() in calculatedStates) { cacheLookups++ return calculatedStates[key()] ?: error("checked null first") } val minutes = minutesToMake() val skipState = this.copy( remainingMinutes = 0, collected = collected + robotNumbers * remainingMinutes ) val newStates = minutes.mapIndexed { idx, min -> if (min == null) { null } else if (min >= remainingMinutes || (idx < 3 && maxBots[idx] < robotNumbers.amounts[idx])) { skipState } else { this.copy( remainingMinutes = remainingMinutes - min, collected = collected + robotNumbers * min - blueprint[idx], robotNumbers = robotNumbers + singleRobots[idx] ) } } val res = if (minutes.last() == 1) { newStates.last()?.maxGeodes() ?: skipState.maxGeodes() } else newStates.filterNotNull().distinct().maxOf { it.maxGeodes() } calculatedStates[key()] = res return res } fun minutesToMake(): List<Int?> { return blueprint.costList().map { minutesToMake(it) } } private fun minutesToMake(cost: Resources): Int? { val remainingCost = cost - collected if (cost.amounts.zip(robotNumbers.amounts).any { (c, r) -> c > 0 && r == 0 }) { return null } return remainingCost.amounts.zip(robotNumbers.amounts).maxOfOrNull { (c, r) -> minutesToGetResources(c, r) } } private fun minutesToGetResources(c: Int, r: Int): Int { return if (c <= 0) { 1 } else { ceil(c.toDouble() / r).toInt() + 1 } } } private fun parse(input: List<String>): List<Blueprint> { return input.mapIndexed { idx, line -> val costs = line.split("robot costs ").drop(1) val orePerOre = costs[0].takeWhile { it != ' ' }.toInt() val orePerClay = costs[1].takeWhile { it != ' ' }.toInt() val orePerObs = costs[2].takeWhile { it != ' ' }.toInt() val orePerGeode = costs[3].takeWhile { it != ' ' }.toInt() val clayPerObs = costs[2].split("and ")[1].takeWhile { it != ' ' }.toInt() val obsPerGeode = costs[3].split("and ")[1].takeWhile { it != ' ' }.toInt() Blueprint( idx + 1, Resources(orePerOre), Resources(orePerClay), Resources(orePerObs, clayPerObs), Resources(orePerGeode, obsidian = obsPerGeode) ) } } fun part1(input: List<String>, remainingMinutes: Int = 24): Int { val blueprints = parse(input) println(blueprints) val factories = blueprints.map { FactoryState(it, remainingMinutes = remainingMinutes) } return factories.asSequence().map { val res = it.maxGeodes() println("did cache lookups: " + FactoryState.cacheLookups) println("number states: " + FactoryState.calculatedStates.size) FactoryState.calculatedStates.clear() res }.mapIndexed { index, geodes -> println("${index + 1}: $geodes") (index + 1) * geodes }.sum() } fun part2(input: List<String>): Long { val blueprints = parse(input).take(3) val factories = blueprints.map { FactoryState(it, remainingMinutes = 32) } val geodes = factories.asSequence().map { val res = it.maxGeodes() println("did cache lookups: " + FactoryState.cacheLookups) println("number states: " + FactoryState.calculatedStates.size) FactoryState.calculatedStates.clear() res }.mapIndexed { index, geodes -> println("${index + 1}: $geodes") geodes } return geodes.reduce { acc, i -> acc * i }.toLong() } } fun main() { val testInput1 = """ Blueprint 1: Each ore robot costs 100 ore. Each clay robot costs 100 ore. Each obsidian robot costs 100 ore and 100 clay. Each geode robot costs 100 ore and 100 obsidian. """.trimIndent().split("\n") println(Day19.part1(testInput1, 30)) val testInput = """ Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian. Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian. """.trimIndent().split("\n") println("------Tests------") println("part 1: " + Day19.part1(testInput)) //println("part 2: " + Day19.part2(testInput)) println("------Real------") val input = readInput("resources/2022/day19") println("part 1: " + Day19.part1(input)) // bp 1: 10, bp 3: 37 println("part 2: " + Day19.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
7,732
advent-of-code
Apache License 2.0
src/Day02.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
fun getPointsForWin(enemyMove: String, yourMove: String) = when (enemyMove) { "A" -> { when (yourMove) { "X" -> 3 "Z" -> 0 else -> 6 } } "B" -> { when (yourMove) { "Y" -> 3 "X" -> 0 else -> 6 } } else -> { when (yourMove) { "Z" -> 3 "Y" -> 0 else -> 6 } } } fun getPointsForItem(item: String) = when (item) { "X" -> 1 "Y" -> 2 else -> 3 } fun getPointsFromGuessedItem(enemyMove: String, yourState: String) = when (enemyMove) { "A" -> when (yourState) { "X" -> 3 "Y" -> 1 else -> 2 } "B" -> when (yourState) { "X" -> 1 "Y" -> 2 else -> 3 } else -> when (yourState) { "X" -> 2 "Y" -> 3 else -> 1 } } fun getPointsForWin(item: String) = when (item) { "X" -> 0 "Y" -> 3 else -> 6 } fun main() { fun part1(input: List<String>): Int { return input.sumOf { val moves = it.split(" ") getPointsForWin(moves[0], moves[1]) + getPointsForItem(moves[1]) } } fun part2(input: List<String>): Int { return input.sumOf { val moves = it.split(" ") getPointsFromGuessedItem(moves[0], moves[1]) + getPointsForWin(moves[1]) } } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
1,502
Advent-of-code
Apache License 2.0
src/Day10.kt
jwklomp
572,195,432
false
{"Kotlin": 65103}
import kotlin.math.abs data class SignalAcc(var registerX: Long, var sumSignal: Long) data class PixelAcc(var registerX: Long, var pixels: MutableList<String>) fun main() { fun toCycles(input: List<String>) = input.map { it.split(" ") } .flatMap { if (it.first() == "addx") listOf(0, it.last().toInt()) else listOf(0) } fun part1(input: List<String>): Long { val signalAcc = toCycles(input).foldIndexed(SignalAcc(1, 0)) { idx, signalAcc, cycleValue -> val cycle = idx + 1 if (listOf(20, 60, 100, 140, 180, 220).contains(idx + 1)) signalAcc.sumSignal += signalAcc.registerX * cycle signalAcc.registerX += cycleValue return@foldIndexed signalAcc } return signalAcc.sumSignal } fun part2(input: List<String>): List<List<String>> { val initialPixels = ".".repeat(40 * 6).chunked(1) as MutableList<String> val pixelAcc = toCycles(input).foldIndexed(PixelAcc(1, initialPixels)) { idx, pixelAcc, cycleValue -> if (abs(pixelAcc.registerX - (idx % 40)) <= 1) pixelAcc.pixels[idx] = "#" pixelAcc.registerX += cycleValue return@foldIndexed pixelAcc } return pixelAcc.pixels.chunked(40) } val testInput = readInput("Day10_test") println(part1(testInput)) part2(testInput).forEach { println(it.joinToString("")) } val input = readInput("Day10") println(part1(input)) part2(input).forEach { println(it.joinToString("")) } }
0
Kotlin
0
0
1b1121cfc57bbb73ac84a2f58927ab59bf158888
1,508
aoc-2022-in-kotlin
Apache License 2.0
src/Day03.kt
arnoutvw
572,860,930
false
{"Kotlin": 33036}
fun main() { val charslist = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun part1(input: List<String>): Int { return input.sumOf { val middle = it.length / 2 val first = it.substring(0 until middle) val second = it.substring(middle) val intersect = first.toCharArray().intersect(second.toSet()) charslist.indexOf(intersect.first()) + 1 } } fun part2(input: List<String>): Int { var sum = 0; for (i in input.indices step 3) { val intersect = input[i].toCharArray().intersect(input[i+1].toSet()).intersect(input[i+2].toSet()) sum += charslist.indexOf(intersect.first()) + 1 } return sum; } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") println("Test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 157) check(part2(testInput) == 70) println("Waarde") val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4
1,132
aoc-2022-in-kotlin
Apache License 2.0
src/Day07_part2.kt
lowielow
578,058,273
false
{"Kotlin": 29322}
// calculate total size of outermost directory fun calcOuterDir(list: MutableList<MutableList<String>>): Int { var outerTotal = 0 for (i in list.indices) { for (j in list[i].indices) { if (list[i][j].toIntOrNull() != null) { outerTotal += list[i][j].toInt() } } } return outerTotal } // calculate minimum size needed to be deleted fun calcMinDelSize(list: MutableList<MutableList<String>>): Int { return calcOuterDir(list) - 40_000_000 } // calculate number of directory needed to be handled / converted to file size fun calcDirCount(list: MutableList<MutableList<String>>): Int { var count = 0 for (i in list.indices) { for (j in list[i].indices) { if (list[i][j] == "dir") { count++ } } } return count } // restate the values in the list from "dir" to actual size values of the dir fun handleDirConversion(dir: MutableList<String>, list: MutableList<MutableList<String>>) { var count = calcDirCount(list) while (true) { for (i in list.size - 1 downTo 0) { for (j in list[i].indices step 2) { if (list[i][j] == "dir") { var newValue = 0 var k = 0 for (x in list.indices) { if (x > i && list[i][j + 1] == dir[x]) { k = x break } } for (l in list[k].indices step 2) { if (list[k][l].toIntOrNull() != null) { newValue += list[k][l].toInt() } } list[i][j] = newValue.toString() count-- } } } if (count == 0) { break } } } // calculate the least minimum total size needed to be deleted fun calcTotalDelSize(input: List<String>, dir: MutableList<String>, list: MutableList<MutableList<String>>): Int { val minDelSize = handleDirAndList(input, dir, list) var totalSum = 70_000_000 for (i in list.indices) { var currSum = 0 for (j in list[i].indices step 2) { currSum += list[i][j].toInt() } if (currSum in minDelSize until totalSum) { totalSum = currSum } } return totalSum } fun handleDirAndList(input: List<String>, dir: MutableList<String>, list: MutableList<MutableList<String>>): Int { var rawList = mutableListOf<String>() val dirRegex = Regex("\\$ cd ([a-z]+|/)") val listRegex = Regex("^([a-z]*\\d*) ([a-z][.a-z]*)$") for (str in input) { if (dirRegex.matches(str)) { if (rawList.isNotEmpty()) { list.add(rawList) rawList = mutableListOf() } val dirMatch = dirRegex.find(str)!! dir.add(dirMatch.groupValues[1]) } else if (listRegex.matches(str)) { val listMatch = listRegex.find(str)!! rawList.add(listMatch.groupValues[1]) rawList.add(listMatch.groupValues[2]) } } list.add(rawList) val minDelSize = calcMinDelSize(list) handleDirConversion(dir, list) return minDelSize } fun main() { val input = readInput("Day07") val dir = mutableListOf<String>() val list = mutableListOf<MutableList<String>>() calcTotalDelSize(input, dir, list).println() }
0
Kotlin
0
0
acc270cd70a8b7f55dba07bf83d3a7e72256a63f
3,533
aoc2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch3/Problem31.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch3 import java.math.BigInteger /** * Problem 31: Coin Sums * * https://projecteuler.net/problem=31 * * Goal: Count the number of ways (mod 1e9 + 7) that N pence can be made using any combination of * English coins. * * Constraints: 1 <= N <= 1e5 * * English currency: There are 8 types of coins in circulation -> * {1p, 2p, 5p, 10p, 20p, 50p, 1 pound (= 100p), 2 pound (= 200p)}. * * e.g.: N = 5 (i.e. goal is 5 pence in coins) * combos = [{5p}, {2p, 2p, 1p}, {2p, 1p, 1p, 1p}, {1p, 1p, 1p, 1p, 1p}] * count = 4 */ class CoinSums { private val modulus = BigInteger.valueOf(1_000_000_007) private val coins = listOf(1, 2, 5, 10, 20, 50, 100, 200) private val recursiveMemo = Array(100_001) { Array<BigInteger>(8) { BigInteger.ZERO } } /** * Recursive solution uses helper function to allow memoization using top-down, thereby * optimising this top-down approach. * * SPEED (WORSE) 20.34s for N = 1e5 * * @param [n] total amount that needs to be achieved by all combinations. * @param [coin] index of coin value from class [coins]. Default is the largest coin * available (2 pounds). This parameter allows flexibility in the method purpose. e.g. Count * combos for making 10p using 2p (& lower coins) = 6, instead of making 10p using all * possible coins = 11 combos. */ fun countCoinCombosRecursive(n: Int, coin: Int = 7): Int { return recursiveCombos(n, coin).mod(modulus).intValueExact() } /** * Repeatedly subtract each coin value from the target value & sum combos previously * calculated for smaller targets. */ private fun recursiveCombos(n: Int, coin: Int): BigInteger { if (coin < 1) return BigInteger.ONE if (recursiveMemo[n][coin] > BigInteger.ZERO) return recursiveMemo[n][coin] var target = n var combos = BigInteger.ZERO while (target >= 0) { combos += recursiveCombos(target, coin - 1) target -= coins[coin] } recursiveMemo[n][coin] = combos return combos } /** * Solution uses bottom-up approach that determines a target's combo based on: * * - The previous combo calculated for the coin with a smaller target, & * * - The previous combo calculated for a coin of lesser value. * * SPEED (BETTER) 23.55ms for N = 1e5 * Better performance due less expensive loops (vs more expensive recursive function calls) & * use of less memory with better cache-access. */ fun countCoinCombos(n: Int): Int { val longMod = modulus.longValueExact() // index 0 exists for when 0p is needed val combosByCoin = LongArray(n + 1) { 0L }.apply { this[0] = 1L } for (coin in coins) { for (i in coin..n) { combosByCoin[i] += combosByCoin[i - coin] combosByCoin[i] %= longMod } } return combosByCoin[n].toInt() } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,044
project-euler-kotlin
MIT License
src/2022/Day10.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun part1(input: List<String>): Int { var cycle = 0 var x = 1 val interestingCycles = setOf(20, 60, 100, 140, 180, 220) return input.sumOf { var result = 0 val commands = it.split(" ") when(commands[0]) { "noop" -> { cycle++ if (cycle in interestingCycles) result = cycle * x } else -> { repeat(2) { cycle++ if (cycle in interestingCycles) result = cycle * x } x += commands[1].toInt() } } result } } fun part2(input: List<String>) { var cycle = 0 var x = 1 fun getSpritePixel(x: Int, cycle: Int): String { return if ((cycle % 40 - x) in -1..1) "#" else "." } input.flatMap { val pixels = mutableListOf<String>() val commands = it.split(" ") when(commands[0]) { "noop" -> { pixels.add(getSpritePixel(x, cycle)) cycle++ } else -> { repeat(2) { pixels.add(getSpritePixel(x, cycle)) cycle++ } x += commands[1].toInt() } } pixels }.chunked(40).forEach{ println(it.joinToString(separator = "")) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
1,882
aoc-2022-in-kotlin
Apache License 2.0
src/chapter5/section2/ex23_DuplicatesRevisitedAgain.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section2 import chapter3.section5.LinearProbingHashSET import chapter5.section1.Alphabet import extensions.formatInt import extensions.random import extensions.spendTimeMillis /** * 重复元素(再续) * 使用StringSET(请见练习5.2.6)代替HashSET重新完成练习3.5.30,比较两种方法的运行时间。 * 然后使用dedup为N=10⁷、10⁸和10⁹运行实验,用随机long型字符串重复实验并讨论结果。 * * 解:随机的long型字符串会导致极少的重复字符串,这里使用Int型字符串 */ fun ex23_DuplicatesRevisitedAgain(M: Int, N: Int, T: Int, create: (Int) -> String): Int { var count = 0 repeat(T) { // 基于小字符集的TrieST实现会比HashSET更快 val set = TrieStringSET(Alphabet.DECIMAL) // 基于三向单词查找树TST的实现会比HashSET略慢 // val set = ThreeWayStringSET() repeat(N) { set.add(create(M)) } count += set.size() } return count / T } /** * 将练习3.5.30的答案复制过来,并修改使其可以支持字符串 */ fun <E : Any> duplicatesRevisitedHashSET(M: Int, N: Int, T: Int, create: (Int) -> E): Int { var count = 0 repeat(T) { val set = LinearProbingHashSET<E>() repeat(N) { set.add(create(M)) } count += set.size() } return count / T } fun main() { val T = 10 val N = 100_0000 var M = N / 2 repeat(3) { var count1 = 0 var count2 = 0 val time1 = spendTimeMillis { count1 = duplicatesRevisitedHashSET(M, N, T) { random(it).toString() } } val time2 = spendTimeMillis { count2 = ex23_DuplicatesRevisitedAgain(M, N, T) { random(it).toString() } } println("N:${formatInt(N, 7)} M:${formatInt(M, 7)}") println("count1=$count1 time1=$time1 ms") println("count2=$count2 time2=$time2 ms") println() M *= 2 } }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,061
Algorithms-4th-Edition-in-Kotlin
MIT License
2019/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2019/day03/day03.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.aoc2019.day03 import nl.sanderp.aoc.aoc2019.IO import kotlin.math.abs enum class Direction { Up, Down, Left, Right } data class Instruction(val direction: Direction, val steps: Int) fun parse(instruction: String): Instruction { val direction = when (instruction.first()) { 'U' -> Direction.Up 'D' -> Direction.Down 'L' -> Direction.Left 'R' -> Direction.Right else -> throw IllegalArgumentException() } return Instruction(direction, instruction.drop(1).toInt()) } typealias Coordinate = Pair<Int, Int> typealias Movement = (Coordinate) -> Coordinate fun expand(instruction: Instruction): Iterable<Movement> = List(instruction.steps) { { (x, y) -> when (instruction.direction) { Direction.Up -> Pair(x, y + 1) Direction.Right -> Pair(x + 1, y) Direction.Down -> Pair(x, y - 1) Direction.Left -> Pair(x - 1, y) } } } fun generatePath(directions: Iterable<Instruction>, start: Coordinate = Coordinate(0, 0)) = directions .flatMap { expand(it) } .runningFold(start) { position, movement -> movement(position) } fun main() { val (pathA, pathB) = IO.readLines("day03.txt") { line -> line.split(',').map { parse(it) } }.map { generatePath(it) } val intersections = pathA.intersect(pathB).drop(1) // Drop (0, 0) println("Part one: ${intersections.map { abs(it.first) + abs(it.second) }.minOrNull()}") println("Part two: ${intersections.map { pathA.indexOf(it) + pathB.indexOf(it) }.minOrNull()}") }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
1,582
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinDifficulty.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Deque import java.util.LinkedList import kotlin.math.max import kotlin.math.min /** * 1335. Minimum Difficulty of a Job Schedule * @see <a href="https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule">Source</a> */ fun interface MinDifficulty { operator fun invoke(jobDifficulty: IntArray, days: Int): Int } class MinDifficultyTopDown : MinDifficulty { override fun invoke(jobDifficulty: IntArray, days: Int): Int { val numJobs: Int = jobDifficulty.size if (numJobs < days) return -1 val memo = Array(numJobs) { IntArray(days + 1) { -1 } } return dfs(days, 0, jobDifficulty, memo) } private fun dfs(remainingDays: Int, currentJobIndex: Int, jobDifficulty: IntArray, memo: Array<IntArray>): Int { val numJobs = jobDifficulty.size if (remainingDays == 0 && currentJobIndex == numJobs) return 0 if (remainingDays == 0 || currentJobIndex == numJobs) return Int.MAX_VALUE if (memo[currentJobIndex][remainingDays] != -1) return memo[currentJobIndex][remainingDays] var currentMaxDifficulty = jobDifficulty[currentJobIndex] var minDifficulty = Int.MAX_VALUE for (scheduledJob in currentJobIndex until numJobs) { currentMaxDifficulty = max(currentMaxDifficulty.toDouble(), jobDifficulty[scheduledJob].toDouble()).toInt() val temp = dfs(remainingDays - 1, scheduledJob + 1, jobDifficulty, memo) if (temp != Int.MAX_VALUE) { minDifficulty = min(minDifficulty.toDouble(), (temp + currentMaxDifficulty).toDouble()).toInt() } } return minDifficulty.also { memo[currentJobIndex][remainingDays] = it } } } class MinDifficultyBottomUp : MinDifficulty { override fun invoke(jobDifficulty: IntArray, days: Int): Int { if (jobDifficulty.isEmpty()) return 0 val numJobs: Int = jobDifficulty.size if (numJobs < days) return -1 val dp = Array(days) { IntArray(numJobs) } dp[0][0] = jobDifficulty[0] for (jobIndex in 1 until numJobs) { dp[0][jobIndex] = max(jobDifficulty[jobIndex], dp[0][jobIndex - 1]) } for (currentDay in 1 until days) { for (jobIndex in currentDay until numJobs) { var localMax = jobDifficulty[jobIndex] dp[currentDay][jobIndex] = Int.MAX_VALUE for (scheduledJob in jobIndex downTo currentDay) { localMax = max(localMax, jobDifficulty[scheduledJob]) dp[currentDay][jobIndex] = min( dp[currentDay][jobIndex].toDouble(), (dp[currentDay - 1][scheduledJob - 1] + localMax).toDouble(), ).toInt() } } } return dp[days - 1][numJobs - 1] } } class MinDifficultyBottomUp1D : MinDifficulty { override fun invoke(jobDifficulty: IntArray, days: Int): Int { val numJobs: Int = jobDifficulty.size var maxDifficulty: Int if (numJobs < days) return -1 val dp = IntArray(numJobs + 1) for (jobIndex in numJobs - 1 downTo 0) { dp[jobIndex] = maxOf(dp[jobIndex + 1], jobDifficulty[jobIndex]) } for (currentDay in 2..days) { for (jobIndex in 0..numJobs - currentDay) { maxDifficulty = 0 dp[jobIndex] = Int.MAX_VALUE for (scheduledJob in jobIndex..numJobs - currentDay) { maxDifficulty = maxOf(maxDifficulty, jobDifficulty[scheduledJob]) dp[jobIndex] = minOf(dp[jobIndex], maxDifficulty + dp[scheduledJob + 1]) } } } return dp[0] } } class MinDifficultyStack : MinDifficulty { companion object { private const val INITIAL_DP_VALUE = 1000 } override fun invoke(jobDifficulty: IntArray, days: Int): Int { if (jobDifficulty.isEmpty()) return 0 val numJobs = jobDifficulty.size if (numJobs < days) return -1 var dp = IntArray(numJobs) { INITIAL_DP_VALUE } val dp2 = IntArray(numJobs) val stack: Deque<Int> = LinkedList() repeat(days) { stack.clear() updateDPValues(jobDifficulty, dp, dp2, stack, it, numJobs) dp = dp2.copyOf() // Swap arrays by copying elements } return dp[numJobs - 1] } private fun updateDPValues( jobDifficulty: IntArray, dp: IntArray, dp2: IntArray, stack: Deque<Int>, startDay: Int, numJobs: Int, ) { for (i in startDay until numJobs) { dp2[i] = if (i > 0) dp[i - 1] + jobDifficulty[i] else jobDifficulty[i] while (stack.isNotEmpty() && jobDifficulty[stack.peek()] <= jobDifficulty[i]) { val j = stack.pop() dp2[i] = minOf(dp2[i], dp2[j] - jobDifficulty[j] + jobDifficulty[i]) } if (stack.isNotEmpty()) { dp2[i] = minOf(dp2[i], dp2[stack.peek()]) } stack.push(i) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,833
kotlab
Apache License 2.0
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day01.kt
JamJaws
725,792,497
false
{"Kotlin": 30656}
package com.jamjaws.adventofcode.xxiii.day import com.jamjaws.adventofcode.xxiii.readInput class Day01 { private val spelledDigits = mapOf( "one" to '1', "two" to '2', "three" to '3', "four" to '4', "five" to '5', "six" to '6', "seven" to '7', "eight" to '8', "nine" to '9', ) fun part1(text: List<String>): Int = text.map { line -> line.filter(Char::isDigit) } .map { digits -> "${digits.first()}${digits.last()}" } .map(String::toInt) .sum() fun part2(text: List<String>): Int = text.map(::replaceSpelledDigits).let(::part1) private fun replaceSpelledDigits(text: String): String = text.indices.map(text::substring) .map { value -> spelledDigits.entries.find { (spelledDigit, _) -> value.startsWith(spelledDigit) } ?.value ?: value.first() }.joinToString("") } fun main() { val answer1 = Day01().part1(readInput("Day01")) println(answer1) val answer2 = Day01().part2(readInput("Day01")) println(answer2) }
0
Kotlin
0
0
e2683305d762e3d96500d7268e617891fa397e9b
1,164
advent-of-code-2023
MIT License
src/Day11.kt
vjgarciag96
572,719,091
false
{"Kotlin": 44399}
private val INT_NUMBER = Regex("[0-9]+") private val OPERATION = Regex("[*+] ([0-9]+|old)") private sealed interface Operation { data class Add(val arg1: Arg) : Operation data class Multiply(val arg1: Arg) : Operation sealed class Arg { object Input : Arg() data class Other(val value: Int) : Arg() } } private fun Operation.execute(input: Int): Int { return when (this) { is Operation.Add -> input + arg1.toInt(input) is Operation.Multiply -> input * arg1.toInt(input) } } private fun Operation.Arg.toInt(input: Int): Int { return when (this) { Operation.Arg.Input -> input is Operation.Arg.Other -> value } } private fun parseArgument(rawArgument: String): Operation.Arg { return when (rawArgument) { "old" -> Operation.Arg.Input else -> Operation.Arg.Other(rawArgument.toInt()) } } private data class Test( val divisibleBy: Int, val ifTrueThrowTo: Int, val ifFalseThrowTo: Int, ) private data class Monkey<T>( val items: ArrayList<T>, val operation: Operation, val test: Test, ) fun main() { fun part1(input: List<String>): Int { val monkeys = input.chunked(size = 7) { monkeyDescription -> val startingItems = INT_NUMBER.findAll(monkeyDescription[1]).map { it.value.toInt() } val (operator, arg) = OPERATION.findAll(monkeyDescription[2]).map { it.value }.single().split(" ") val operation = when (operator) { "*" -> Operation.Multiply(parseArgument(arg)) "+" -> Operation.Add(parseArgument(arg)) else -> error("invalid operator $operator") } val divisibleBy = INT_NUMBER.findAll(monkeyDescription[3]).map { it.value }.single().toInt() val ifTrueThrowTo = INT_NUMBER.findAll(monkeyDescription[4]).map { it.value }.single().toInt() val ifFalseThrowTo = INT_NUMBER.findAll(monkeyDescription[5]).map { it.value }.single().toInt() Monkey( items = startingItems.toCollection(ArrayList()), operation = operation, test = Test( divisibleBy = divisibleBy, ifTrueThrowTo = ifTrueThrowTo, ifFalseThrowTo = ifFalseThrowTo, ) ) } val monkeyInspectionCount = Array(monkeys.size) { 0 } repeat(20) { monkeys.forEachIndexed { index, monkey -> monkey.items.forEach { item -> val worryLevel = monkey.operation.execute(input = item) val reducedWorryLevel = worryLevel / 3 val divisibleBy = reducedWorryLevel % monkey.test.divisibleBy == 0 if (divisibleBy) { monkeys[monkey.test.ifTrueThrowTo].items.add(reducedWorryLevel) } else { monkeys[monkey.test.ifFalseThrowTo].items.add(reducedWorryLevel) } monkeyInspectionCount[index]++ } monkey.items.clear() } } val (monkey1, monkey2) = monkeyInspectionCount.sortedDescending().take(2) return monkey1 * monkey2 } fun part2(input: List<String>): Long { val monkeys = input.chunked(size = 7) { monkeyDescription -> val startingItems = INT_NUMBER.findAll(monkeyDescription[1]).map { it.value.toInt() } val (operator, arg) = OPERATION.findAll(monkeyDescription[2]).map { it.value }.single().split(" ") val operation = when (operator) { "*" -> Operation.Multiply(parseArgument(arg)) "+" -> Operation.Add(parseArgument(arg)) else -> error("invalid operator $operator") } val divisibleBy = INT_NUMBER.findAll(monkeyDescription[3]).map { it.value }.single().toInt() val ifTrueThrowTo = INT_NUMBER.findAll(monkeyDescription[4]).map { it.value }.single().toInt() val ifFalseThrowTo = INT_NUMBER.findAll(monkeyDescription[5]).map { it.value }.single().toInt() Monkey( items = startingItems.map { element -> arrayListOf(element) }.toCollection(ArrayList()), operation = operation, test = Test( divisibleBy = divisibleBy, ifTrueThrowTo = ifTrueThrowTo, ifFalseThrowTo = ifFalseThrowTo, ) ) } val allDivisors = monkeys.map { it.test.divisibleBy } monkeys.forEach { monkey -> monkey.items.forEachIndexed { index, item -> val itemValue = item.single() val dividedByValues = allDivisors.map { divisor -> itemValue % divisor } monkey.items[index] = ArrayList(dividedByValues) } } val monkeyInspectionCount = Array(monkeys.size) { 0 } repeat(10_000) { monkeys.forEachIndexed { index, monkey -> monkey.items.forEach { item -> item.forEachIndexed { index, itemValue -> item[index] = monkey.operation.execute(input = itemValue) % allDivisors[index] } val worryLevelToTest = item[allDivisors.indexOf(monkey.test.divisibleBy)] val divisibleBy = worryLevelToTest % monkey.test.divisibleBy == 0 if (divisibleBy) { monkeys[monkey.test.ifTrueThrowTo].items.add(item) } else { monkeys[monkey.test.ifFalseThrowTo].items.add(item) } monkeyInspectionCount[index]++ } monkey.items.clear() } println("$it ${monkeyInspectionCount.joinToString(",")}") } val (monkey1, monkey2) = monkeyInspectionCount.sortedDescending().take(2) return monkey1.toLong() * monkey2 } val testInput = readInput("Day11_test") check(part1(testInput) == 10605) check(part2(testInput) == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ee53877877b21166b8f7dc63c15cc929c8c20430
6,277
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestCommonSubPath.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 1923. Longest Common Subpath * @see <a href="https://leetcode.com/problems/longest-common-subpath">Source</a> */ fun interface LongestCommonSubPath { operator fun invoke(n: Int, paths: Array<IntArray>): Int } class RollingHash : LongestCommonSubPath { override operator fun invoke(n: Int, paths: Array<IntArray>): Int { var s = 0 var length = paths[0].size for (i in paths.indices) { s += paths[i].size length = min(length, paths[i].size) } val merged = IntArray(s) // all path merged into one to calculate a polynomial hash val sep = IntArray(paths.size) // positions of path's ends in the "merged" array var t = 0 for (i in paths.indices) { sep[i] = t + paths[i].size System.arraycopy(paths[i], 0, merged, t, paths[i].size) t += paths[i].size } val hashes = PolyHash(merged) // basic binary search on l var begin = 0 var end = length + 1 while (begin + 1 < end) { val mid = (end + begin) / 2 val c = check(mid, merged, sep, hashes) if (c) begin = mid else end = mid } return begin } private class PolyHash(x: IntArray) { // This class stores polynomial hashes for a given array private var b: Long = BASE private var q: Long = MODULE private var n: Int private var pow: LongArray // pow[i] = (b^i) % q private var cumulativeHash: LongArray init { n = x.size pow = LongArray(x.size) pow[0] = 1 for (i in 1 until x.size) pow[i] = pow[i - 1] * b % q cumulativeHash = LongArray(x.size) cumulativeHash[0] = x[0] * pow[0] % q for (i in 1 until x.size) cumulativeHash[i] = (cumulativeHash[i - 1] + x[i] * pow[i]) % q } operator fun get(start: Int, end: Int): Long { // returns hash of subarray 'moved' to the end in O(1) var v: Long = if (start > 0) { Math.floorMod(cumulativeHash[end - 1] - cumulativeHash[start - 1], q) } else { Math.floorMod(cumulativeHash[end - 1], q) } // Yes, this may overflow but this is fine v = v * pow[n - end] % q return v } } private class MySubArray( private val array: IntArray, private val polyHash: PolyHash, private val begin: Int, private val end: Int, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val o = other as MySubArray if (end - begin != o.end - o.begin) return false for (i in 0 until end - begin) { if (array[i + begin] != o.array[i + o.begin]) return false if (i > 10) return true // This is a horrible optimization. // It means there is ~1/(n^10 * (collision chance)) probability to make a wrong answer // But in return the equals() works in O(1) } return true } override fun hashCode(): Int { return polyHash[begin, end].toInt() } } private class MySubArrayFactory( // This makes check() more readable... in theory private val l: IntArray, private val polyHash: PolyHash, ) { operator fun get(begin: Int, end: Int): MySubArray { return MySubArray(l, polyHash, begin, end) } } private fun check(l: Int, merged: IntArray, sep: IntArray, hashes: PolyHash): Boolean { // Checks if there is a common subpath of a length "l" if (l == 0) return true val path = MySubArrayFactory(merged, hashes) // <-- generates hashable subpaths var found: MutableSet<MySubArray?> = HashSet() // add all subpaths of the 1st friend of length "l" in "found" for (j in 0..sep[0] - l) { found.add(path[j, j + l]) } for (i in 0 until sep.size - 1) { // remove subpaths from "found" that are not subpaths of the ith friend val res: MutableSet<MySubArray?> = HashSet() for (j in sep[i]..sep[i + 1] - l) { if (found.contains(path[j, j + l])) res.add(path[j, j + l]) } found = res } // if there is a subpath that we didn't remove => then this path is present in all the paths return found.isNotEmpty() } companion object { private const val BASE = 100001L private const val MODULE = 1000000019L } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,428
kotlab
Apache License 2.0
src/day06/Solution.kt
abhabongse
576,594,038
false
{"Kotlin": 63915}
/* Solution to Day 6: Tuning Trouble * https://adventofcode.com/2022/day/6 */ package day06 import java.io.File fun main() { val fileName = // "day06_sample_a.txt" // "day06_sample_b.txt" // "day06_sample_c.txt" // "day06_sample_d.txt" // "day06_sample_e.txt" "day06_input.txt" val datastream = readInput(fileName) // Part 1: find the location of the first marker of length 4 val p1FirstMarker = findFirstMarker(datastream, markerLength = 4) println("Part 1: $p1FirstMarker") // Part 2: find the location of the first marker of length 14 val p2FirstMarker = findFirstMarker(datastream, markerLength = 14) println("Part 2: $p2FirstMarker") } /** * Reads and parses input data according to the problem statement. */ fun readInput(fileName: String): String { return File("inputs", fileName).readText().trim() } /** * Find the location of the first marker, specifically the index to the last character * of the first appearance substring containing unique characters. */ fun findFirstMarker(datastream: String, markerLength: Int): Int? { val counter = object { val frequencies: HashMap<Char, Int> = HashMap() var uniqueCount = 0 private set fun modify(char: Char, diff: Int) { val oldFreq = this.frequencies.getOrDefault(char, 0) val newFreq = oldFreq + diff if (newFreq < 0) { throw IllegalArgumentException("new frequency for $char would decrease from $oldFreq to $newFreq") } this.frequencies[char] = newFreq if (oldFreq == 0 && newFreq > 0) { this.uniqueCount++ } if (oldFreq > 0 && newFreq == 0) { this.uniqueCount-- } } } for ((index, char) in datastream.withIndex()) { counter.modify(char, +1) if (index >= markerLength) { counter.modify(datastream[index - markerLength], -1) } if (counter.uniqueCount == markerLength) { return index + 1 } } return null }
0
Kotlin
0
0
8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb
2,137
aoc2022-kotlin
Apache License 2.0
src/Day18.kt
p357k4
573,068,508
false
{"Kotlin": 59696}
fun main() { data class Cube(val x: Int, val y: Int, val z: Int) fun part1(input: List<String>): Int { val cubes = input.map { val split = it.split(',').map { it.toInt() } Cube(split[0], split[1], split[2]) } var walls = 0 for (cube in cubes) { walls += 6 for (other in cubes) { if (cube == other) { continue } if (cube.copy(x = cube.x + 1) == other) { walls -= 1 continue } if (cube.copy(x = cube.x - 1) == other) { walls -= 1 continue } if (cube.copy(y = cube.y + 1) == other) { walls -= 1 continue } if (cube.copy(y = cube.y - 1) == other) { walls -= 1 continue } if (cube.copy(z = cube.z + 1) == other) { walls -= 1 continue } if (cube.copy(z = cube.z - 1) == other) { walls -= 1 continue } } } return walls } fun part2(input: List<String>): Int { val magma = input.map { line -> val split = line.split(',').map(String::toInt) Cube(split[0], split[1], split[2]) } val minX = magma.minOf { it.x } - 1 val maxX = magma.maxOf { it.x } + 1 val minY = magma.minOf { it.y } - 1 val maxY = magma.maxOf { it.y } + 1 val minZ = magma.minOf { it.z } - 1 val maxZ = magma.maxOf { it.z } + 1 val water = mutableListOf<Cube>() fun flood(drop: Cube): Int { if (drop.x !in minX..maxX || drop.y !in minY..maxY || drop.z !in minZ..maxZ) { return 0 } if (drop in water) { return 0 } if (drop in magma) { return 1 } water.add(drop) return flood(drop.copy(x = drop.x + 1)) + flood(drop.copy(x = drop.x - 1)) + flood(drop.copy(y = drop.y + 1)) + flood(drop.copy(y = drop.y - 1)) + flood(drop.copy(z = drop.z + 1)) + flood(drop.copy(z = drop.z - 1)) } val result = flood(Cube(maxX, maxY, maxZ)) return result } // test if implementation meets criteria from the description, like: val testInputExample = readInput("Day18_example") check(part1(testInputExample) == 64) check(part2(testInputExample) == 58) val testInput = readInput("Day18_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
b9047b77d37de53be4243478749e9ee3af5b0fac
2,912
aoc-2022-in-kotlin
Apache License 2.0
src/Day09.kt
allwise
574,465,192
false
null
import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { val rope = Rope(input) return rope.process() } fun part2(input: List<String>): Int { val rope = Rope(input) return rope.process2() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") println( "part1 " +part1(testInput)) println("part2 " + part2(testInput)) check(part1(testInput) == 88) check(part2(testInput) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) } class Rope(val input:List<String>){ fun process(): Int { var head = mutableListOf<Int>(0, 0) return handleChain(mutableListOf(head,head.copyTwo())) } fun process2():Int{ var head = mutableListOf<Int>(0, 0) var chain = mutableListOf<MutableList<Int>>() repeat(10){chain.add(head.copyTwo())} //println(chain) return handleChain(chain) } fun handleChain( chain:MutableList<MutableList<Int>>):Int { var visitedPosistion = mutableListOf(chain.last().copyTwo()) input.forEach { movement -> // println(movement) val (move: String, count: String) = movement.split(" ") repeat(count.toInt()) { chain.forEachIndexed { idx, knot -> if (idx == 0) { move(move, knot) } else { var head = chain[idx-1] //println(movement) //println("(${head[0]},${head[1]}) (${chain[idx + 1][0]},${chain[idx + 1][1]}) $move") chain[idx] = follow(head, knot) } } // visualize(chain) visitedPosistion.add(chain.last().copyTwo()) } // println(visitedPosistion.size) // println(visitedPosistion.toSet().size) // println(visitedPosistion) } return visitedPosistion.toSet().size } fun MutableList<Int>.copyTwo():MutableList<Int>{ return mutableListOf(this[0], this[1]) } fun move(move:String, head:MutableList<Int>) { when(move) { "R" -> head[0]++ "L" -> head[0]-- "U" -> head[1]++ "D" -> head[1]-- } } fun visualize( chain:MutableList<MutableList<Int>>){ //var plane = mutableListOf(MutableList<String>) for( i in 6 downTo 0) { for (j in 0 until 6) { var char="#" if(chain.contains(mutableListOf(j,i))) { val idx=chain.indexOf(mutableListOf(j, i)) if(idx==0) { char = "H" }else { char="$idx" } } print(char) } println() } println() } fun follow(head:MutableList<Int>, tail:MutableList<Int>, ): MutableList<Int> { val diffX = head[0]-tail[0] val diffY = head[1]-tail[1] if(diffY==0 && abs(diffX)==2) tail[0]+=diffX/2 else if(diffX==0 && abs(diffY)==2) tail[1]+=diffY/2 else if(abs(diffX)+abs(diffY)>2){ if(head[0]>tail[0]){ tail[0]++ }else{ tail[0]-- } if(head[1]>tail[1]){ tail[1]++ }else{ tail[1]-- } } return tail } }
0
Kotlin
0
0
400fe1b693bc186d6f510236f121167f7cc1ab76
3,627
advent-of-code-2022
Apache License 2.0