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/structures/BinaryTree.kt
DmitryTsyvtsyn
418,166,620
false
{"Kotlin": 223256}
package structures /** * * data structure: binary tree * * description: consists of nodes, each of which has a maximum of two children, * child nodes satisfy the following requirements: * - the left child is less than the parent; * - right child is larger than parent; * * average search time: log(n) * worst search time: n * because the situation is possible when the elements follow each other 1,2,3,4... and the tree takes the following form: * 1 * \ * 2 * \ * 3 * \ * 4 * the same complexity is true for adding and removing nodes * */ class BinaryTree { /** * binary tree root */ private var root: Node? = null /** * adds a new element [value] to the tree */ fun add(value: Int) { fun addRec(current: Node?, value: Int) : Node { if (current == null) { return Node(value) } if (value < current.value()) { current.changeLeft(addRec(current.leftNode(), value)) } else if (value > current.value()) { current.changeRight(addRec(current.rightNode(), value)) } return current } root = addRec(root, value) } /** * checks the tree for emptiness and returns true if the tree does not contain any nodes */ fun isEmpty() = root == null /** * removes an element [value] from the tree */ fun remove(value: Int) { fun smallestValue(root: Node) : Int { return if (root.leftNode() == null) root.value() else smallestValue(root.leftNode()!!) } fun removeRec(current: Node?, value: Int) : Node? { if (current == null) { return null } if (value == current.value()) { if (current.leftNode() == null && current.rightNode() == null) { return null } if (current.leftNode() == null) { return current.rightNode() } if (current.rightNode() == null) { return current.leftNode() } val smallestValue = smallestValue(current.rightNode()!!) current.changeValue(smallestValue) current.changeRight(removeRec(current.rightNode(), smallestValue)) return current } if (value < current.value()) { current.changeLeft(removeRec(current.leftNode(), value)) } else { current.changeRight(removeRec(current.rightNode(), value)) } return current } root = removeRec(root, value) } /** * checks for the existence of an element [value] in the tree, returns true if the element exists */ fun contains(value: Int) : Boolean { fun containsRec(current: Node?, value: Int) : Boolean { if (current == null) { return false } if (value == current.value()) { return true } return if (value < current.value()) { containsRec(current.leftNode(), value) } else { containsRec(current.rightNode(), value) } } return containsRec(root, value) } /** * traversal of the binary tree in depth * * first the left child, then the parent, then the right child * * @return returns the elements of the tree */ fun traverseInOrder() : List<Int> { fun traverseInOrderRec(node: Node?, nodes: MutableList<Int>) { if (node != null) { traverseInOrderRec(node.leftNode(), nodes) nodes.add(node.value()) traverseInOrderRec(node.rightNode(), nodes) } } return mutableListOf<Int>().apply { traverseInOrderRec(root, this) } } /** * traversal of the binary tree in depth * * parent first, then left and right children * * @return returns the elements of the tree */ fun traversePreOrder() : List<Int> { fun traversePreOrderRec(node: Node?, nodes: MutableList<Int>) { if (node != null) { nodes.add(node.value()) traversePreOrderRec(node.leftNode(), nodes) traversePreOrderRec(node.rightNode(), nodes) } } return mutableListOf<Int>().apply { traversePreOrderRec(root, this) } } /** * traversal of the binary tree in depth * * first the left and right children, then the parent * * @return returns the elements of the tree */ fun traversePostOrder() : List<Int> { fun traversePostOrderRec(node: Node?, nodes: MutableList<Int>) { if (node != null) { traversePostOrderRec(node.leftNode(), nodes) traversePostOrderRec(node.rightNode(), nodes) nodes.add(node.value()) } } return mutableListOf<Int>().apply { traversePostOrderRec(root, this) } } /** * traversal of the binary tree in breadth * * uses an additional data structure - a queue into which new tree * nodes are added until the last node is added * * @return returns the elements of the tree */ fun traverseLevelOrder() : List<Int> { val root = this.root ?: return listOf() val queue = java.util.LinkedList<Node>() queue.add(root) val items = mutableListOf<Int>() while (queue.isNotEmpty()) { val node = queue.remove() items.add(node.value()) node.leftNode()?.let(queue::add) node.rightNode()?.let(queue::add) } return items } } /** * represents a tree node * * @property value - node value * @property left - left child node * @property right - right child node */ class Node( private var value: Int, private var left: Node? = null, private var right: Node? = null ) { /** * returns the value of the node */ fun value() = value /** * changes the value of a node */ fun changeValue(value: Int) { this.value = value } /** * changes the left child node */ fun changeLeft(left: Node?) { this.left = left } /** * changes the right child node */ fun changeRight(right: Node?) { this.right = right } /** * returns the left child node */ fun leftNode() = left /** * returns the right child node */ fun rightNode() = right }
0
Kotlin
135
767
7ec0bf4f7b3767e10b9863499be3b622a8f47a5f
6,792
Kotlin-Algorithms-and-Design-Patterns
MIT License
src/day21/Parser.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day21 import readInput import java.lang.IllegalArgumentException import java.util.regex.Pattern enum class Operation (val symbol: Char, val calc: (Long, Long) -> Long){ PLUS ('+', { a, b -> a + b}), MINUS ('-', { a, b -> a - b}), MULTIPLY ('*', { a, b -> a * b }), DIVIDE ('/', { a, b -> a / b}), EQUALS ('=', { a, b -> if (a == b) 1 else 0 }); fun invoke (left: Long, right: Long) = calc (left, right) companion object { private val map = mutableMapOf<Char, Operation> ().apply { values ().forEach { put (it.symbol, it) } }.toMap () fun decode (c: Char): Operation = map[c] as Operation } } sealed class Expression { data class Symbol (val symbol: String): Expression () { override fun toString () = "$symbol" } data class Number (val value: Long) : Expression () { override fun toString () = "$value" } data class Calculation (val left: Expression, val operation: Operation, val right: Expression) : Expression () { fun invoke (left: Long, right: Long): Long = operation.invoke(left, right) override fun toString () = "($left ${operation.symbol} $right)" } companion object { val REGEX0 = "^([a-z]{4}): (\\d+)$" val pattern0 = Pattern.compile (REGEX0) val REGEX1 = "^([a-z]{4}): ([a-z]{4}) ([-+*/]) ([a-z]{4})$" val pattern1 = Pattern.compile (REGEX1) fun parse (str: String, map: MutableMap<String, Expression>) { pattern0.matcher (str).let { if (it.matches ()) { val symbol = it.group (1) val expr = Number (it.group (2).toLong ()) map.put (symbol, expr) return } } pattern1.matcher (str).let { if (it.matches ()) { val symbol = it.group (1) val expr = Calculation (Symbol (it.group (2)), Operation.decode (it.group (3)[0]), Symbol (it.group (4))) map.put (symbol, expr) return } } throw IllegalArgumentException ("Unrecognized input: '$str'") } } } // EOF
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
2,270
advent_of_code_2022
Apache License 2.0
year2017/src/main/kotlin/net/olegg/aoc/year2017/day10/Day10.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2017.day10 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.parseInts import net.olegg.aoc.year2017.DayOf2017 /** * See [Year 2017, Day 10](https://adventofcode.com/2017/day/10) */ object Day10 : DayOf2017(10) { override fun first(): Any? { return data .parseInts(",") .foldIndexed(List(256) { it } to 0) { index, acc, value -> val prev = acc.first + acc.first val curr = prev.subList(0, acc.second) + prev.subList(acc.second, acc.second + value).reversed() + prev.subList(acc.second + value, prev.size) val next = curr.subList(acc.first.size, acc.first.size + acc.second) + curr.subList(acc.second, acc.first.size) return@foldIndexed next to ((acc.second + value + index) % acc.first.size) } .first .let { it[0] * it[1] } } override fun second(): Any? { return data .map { it.code } .let { it + listOf(17, 31, 73, 47, 23) } .let { list -> (0..<64).fold(emptyList<Int>()) { acc, _ -> acc + list } } .foldIndexed(List(256) { it } to 0) { index, acc, value -> val prev = acc.first + acc.first val curr = prev.subList(0, acc.second) + prev.subList(acc.second, acc.second + value).reversed() + prev.subList(acc.second + value, prev.size) val next = curr.subList(acc.first.size, acc.first.size + acc.second) + curr.subList(acc.second, acc.first.size) return@foldIndexed next to ((acc.second + value + index) % acc.first.size) } .first .chunked(16) { chunk -> chunk.reduce { acc, value -> acc xor value } } .joinToString(separator = "") { "%02x".format(it) } } } fun main() = SomeDay.mainify(Day10)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,772
adventofcode
MIT License
src/day02/Day02.kt
GrzegorzBaczek93
572,128,118
false
{"Kotlin": 44027}
package day02 import readInput import utils.withStopwatch fun main() { val testInput = readInput("input02_test") withStopwatch { println(part1(testInput)) } withStopwatch { println(part2(testInput)) } val input = readInput("input02") withStopwatch { println(part1(input)) } withStopwatch { println(part2(input)) } } private fun part1(input: List<String>) = input.sumOf { game -> val shapeA = game.first().toShape() val shapeB = game.last().toShape() calculateResult(shapeA, shapeB) } private fun part2(input: List<String>) = input.sumOf { game -> val shapeA = game.first().toShape() val shapeB = game.last().toShape(shapeA.winningShape, shapeA.drawingShape, shapeA.losingShape) calculateResult(shapeA, shapeB) } private fun calculateResult(shapeA: Shape, shapeB: Shape): Int = when (shapeB) { shapeA.winningShape -> MatchResult.Lose.points + shapeB.points shapeA.drawingShape -> MatchResult.Draw.points + shapeB.points shapeA.losingShape -> MatchResult.Win.points + shapeB.points else -> throw UnsupportedOperationException() }
0
Kotlin
0
0
543e7cf0a2d706d23c3213d3737756b61ccbf94b
1,122
advent-of-code-kotlin-2022
Apache License 2.0
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day25/Command.kt
jrhenderson1988
289,786,400
false
{"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37}
package com.github.jrhenderson1988.adventofcode2019.day25 sealed class Command(val command: String) { val ascii = (command.trim() + "\n").map { it.toLong() } override fun toString() = command } sealed class Direction(val direction: String) : Command(direction) { abstract fun delta(): Pair<Int, Int> abstract fun opposite(): Direction fun next(current: Pair<Int, Int>) = Pair(current.first + delta().first, current.second + delta().second) companion object { fun parse(input: String) = setOf(North, East, South, West).firstOrNull { it.command == input } ?: error("Invalid direction '$input'") } } object North : Direction("north") { override fun opposite() = South override fun delta() = Pair(0, -1) } object South : Direction("south") { override fun opposite() = North override fun delta() = Pair(0, 1) } object East : Direction("east") { override fun opposite() = West override fun delta() = Pair(1, 0) } object West : Direction("west") { override fun opposite() = East override fun delta() = Pair(-1, 0) } sealed class Action(instruction: String) : Command(instruction) data class Take(val item: String) : Command("take $item") data class Drop(val item: String) : Command("drop $item") object Inventory : Command("inv")
0
Kotlin
0
0
7b56f99deccc3790c6c15a6fe98a57892bff9e51
1,308
advent-of-code
Apache License 2.0
Kotlin for Java Developers. Week 4/Rationals/Task/src/rationals/Rational.kt
obarcelonap
374,972,699
false
null
package rationals import java.math.BigInteger data class Rational(val numerator: BigInteger, val denominator: BigInteger) : Comparable<Rational> { init { require(denominator != 0.toBigInteger()) { "Denominator can't be 0." } } companion object { fun sameDenominator(first: Rational, second: Rational): Pair<Rational, Rational> = Pair(first * second.denominator, second * first.denominator) } fun normalize(): Rational { val normalized = this / numerator.gcd(denominator) if (denominator.isNegative()) { return Rational(-normalized.numerator, -normalized.denominator) } return normalized } operator fun plus(increment: Rational): Rational = if (denominator == increment.denominator) Rational(numerator + increment.numerator, denominator) else { val (first, second) = sameDenominator(this, increment) first + second } operator fun minus(decrement: Rational): Rational = if (denominator == decrement.denominator) Rational(numerator - decrement.numerator, denominator) else { val (first, second) = sameDenominator(this, decrement) first - second } operator fun times(other: Rational): Rational = Rational(numerator * other.numerator, denominator * other.denominator) operator fun times(number: BigInteger): Rational = Rational(numerator * number, denominator * number) operator fun div(other: Rational): Rational = this * Rational(other.denominator, other.numerator) operator fun div(number: BigInteger): Rational = Rational(numerator / number, denominator / number) override fun compareTo(other: Rational): Int { val (first, second) = sameDenominator(this.normalize(), other.normalize()) return first.numerator.compareTo(second.numerator) } operator fun unaryMinus(): Rational = Rational(-numerator, denominator) override fun toString(): String { val (numerator, denominator) = normalize() return if (denominator == 1.toBigInteger()) "$numerator" else "$numerator/$denominator" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Rational val (numerator, denominator) = normalize() val (otherNumerator, otherDenominator) = other.normalize() if (numerator != otherNumerator) return false if (denominator != otherDenominator) return false return true } override fun hashCode(): Int { var result = numerator.hashCode() result = 31 * result + denominator.hashCode() return result } } fun Int.toRational(): Rational = Rational(this.toBigInteger(), 1.toBigInteger()) fun String.toRational(): Rational = if (contains("/")) { val (first, second) = split("/", limit = 2) Rational(first.toBigInteger(), second.toBigInteger()) } else Rational(toBigInteger(), 1.toBigInteger()) infix fun Int.divBy(other: Int) = Rational(toBigInteger(), other.toBigInteger()) infix fun Long.divBy(other: Long) = Rational(toBigInteger(), other.toBigInteger()) infix fun BigInteger.divBy(other: BigInteger) = Rational(this, other) fun BigInteger.isNegative(): Boolean = this < 0.toBigInteger() fun main() { val half = 1 divBy 2 val third = 1 divBy 3 val sum: Rational = half + third println(5 divBy 6 == sum) val difference: Rational = half - third println(1 divBy 6 == difference) val product: Rational = half * third println(1 divBy 6 == product) val quotient: Rational = half / third println(3 divBy 2 == quotient) val negation: Rational = -half println(-1 divBy 2 == negation) println((2 divBy 1).toString() == "2") println((-2 divBy 4).toString() == "-1/2") println("117/1098".toRational().toString() == "13/122") val twoThirds = 2 divBy 3 println(half < twoThirds) println(half in third..twoThirds) println(2000000000L divBy 4000000000L == 1 divBy 2) println( "912016490186296920119201192141970416029".toBigInteger() divBy "1824032980372593840238402384283940832058".toBigInteger() == 1 divBy 2 ) }
0
Kotlin
0
0
d79103eeebcb4f1a7b345d29c0883b1eebe1d241
4,296
coursera-kotlin-for-java-developers
MIT License
2021/src/main/kotlin/day11_fast.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.Solution fun main() { Day11Fast.run() } object Day11All { @JvmStatic fun main(args: Array<String>) { mapOf("func" to Day11Func, "imp" to Day11Imp, "fast" to Day11Fast).forEach { (header, solution) -> solution.run(header = header, skipPart1 = false, skipTest = false, printParseTime = false) } } } object Day11Fast : Solution<IntGrid>() { override val name = "day11" override val parser = IntGrid.singleDigits fun evolve(grid: IntArray): Int { val sz = 10 val flashing = ArrayDeque<Int>() val flashed = BooleanArray(sz * sz) { false } var flashes = 0 fun evolve(index: Int) { if (++grid[index] == 10) { flashes++ flashed[index] = true flashing.add(index) grid[index] = 0 } } fun check(index: Int) { if (index < 0 || index >= 100) return if (flashed[index]) return evolve(index) } for (i in 0 until sz*sz) { evolve(i) } while (flashing.isNotEmpty()) { val i = flashing.removeFirst() val col = i % 10 if (col != 0) { check(i - 1 - sz) // top-left check(i - 1) // left check(i - 1 + sz) // bottom-left } if (col != 9) { check(i + 1 - sz) // top-right check(i + 1) // right check(i + 1 + sz) // bottom-right } check(i - sz) // top check(i + sz) // bottom } return flashes } override fun part1(input: IntGrid): Int { val grid = input.values.toIntArray() var totalFlashes = 0 repeat(100) { totalFlashes += evolve(grid) } return totalFlashes } override fun part2(input: IntGrid): Int { val grid = input.values.toIntArray() for (day in 1 .. Integer.MAX_VALUE) { if (evolve(grid) == 100) { return day } } throw IllegalStateException("Never reached synchronization!") } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,943
aoc_kotlin
MIT License
day22/Kotlin/day22.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* fun print_day_22() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 22" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Reactor Reboot -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_22() Day22().part1() Day22().part2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } fun String.toRange(): IntRange = this.split("..").let { IntRange(it[0].toInt(), it[1].toInt()) } class Day22 { fun String.toRange(): IntRange = this.split("..").let { IntRange(it[0].toInt(), it[1].toInt()) } data class Point3D(val x: Int, val y: Int, val z: Int) data class Cube(val xAxis: IntRange, val yAxis: IntRange, val zAxis: IntRange) { fun cubicVolume() = 1L * this.xAxis.count() * this.yAxis.count() * this.zAxis.count() fun overlaps(that: Cube) = (this.xAxis.first <= that.xAxis.last && this.xAxis.last >= that.xAxis.first) && (this.yAxis.first <= that.yAxis.last && this.yAxis.last >= that.yAxis.first) && (this.zAxis.first <= that.zAxis.last && this.zAxis.last >= that.zAxis.first) fun intersect(that: Cube) = if (!overlaps(that)) null else Cube( maxOf(this.xAxis.first, that.xAxis.first)..minOf( this.xAxis.last, that.xAxis.last ), maxOf(this.yAxis.first, that.yAxis.first)..minOf( this.yAxis.last, that.yAxis.last ), maxOf(this.zAxis.first, that.zAxis.first)..minOf( this.zAxis.last, that.zAxis.last ) ) } data class Cuboid(val cube: Cube, val on: Boolean) { fun intersect(other: Cuboid) = if (this.cube.overlaps(other.cube)) Cuboid(this.cube.intersect(other.cube)!!, !on) else null } private val cubes = File("../Input/day22.txt").readLines().map { val on = it.split(" ").first() == "on" val cube = it.split(" ").last().split(",").let { Cube( it[0].drop(2).toRange(), it[1].drop(2).toRange(), it[2].drop(2).toRange() ) } Cuboid(cube, on) } fun part1() { val region = Cube(-50..50, -50..50, -50..50) val onCubes = mutableSetOf<Point3D>() cubes.forEach { val (cube, on) = it if (cube.overlaps(region)) { cube.xAxis.forEach { x -> cube.yAxis.forEach { y -> cube.zAxis.forEach { z -> if (on) onCubes.add(Point3D(x, y, z)) else onCubes.remove(Point3D(x, y, z)) } } } } } println("Puzzle 1: " + onCubes.size) } fun part2() { fun findIntersections(a: Cube, b: Cube): Cube? = if (a.overlaps(b)) a.intersect(b) else null val volumes = mutableListOf<Cuboid>() cubes.forEach { cube -> volumes.addAll( volumes.mapNotNull { other -> findIntersections(cube.cube, other.cube)?.let { Cuboid(it, !other.on) } } ) if (cube.on) volumes.add(cube) } println("Puzzle 2: " + volumes.sumOf { it.cube.cubicVolume() * (if (it.on) 1 else -1) }) } }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
4,382
AOC2021
Apache License 2.0
app/src/main/kotlin/de/tobiasdoetzer/aoc2021/Day4.kt
dobbsy
433,868,809
false
{"Kotlin": 13636}
package de.tobiasdoetzer.aoc2021 import java.lang.IllegalArgumentException import java.lang.IllegalStateException private fun main() { val input = readInput("day4_input.txt") val drawnNumbers = input[0].split(',').map(String::toInt) val boardsPart1 = mutableListOf<BingoBoard>() val boardsPart2 = mutableListOf<BingoBoard>() for (i in (2..(input.lastIndex - 4)) step 6) { val board = BingoBoard.createBoard(input.subList(i, i+ 5)) boardsPart1 += board boardsPart2 += board.copy() } println("The solution of part 1 is: ${part1(boardsPart1, drawnNumbers)}") println("The solution of part 2 is: ${part2(boardsPart2, drawnNumbers)}") } private fun part1(boards: List<BingoBoard>, drawnNumbers: List<Int>): Int { for (number in drawnNumbers) { boards.forEach { it.markNumber(number) } boards.forEach { if (it.isWinningBoard()) return it.calculateScore() } } throw IllegalArgumentException("There was no winning board") } private fun part2(boards: MutableList<BingoBoard>, drawnNumbers: List<Int>): Int { for (number in drawnNumbers) { boards.forEach { it.markNumber(number) } if (boards.size > 1) boards.removeAll { it.isWinningBoard() } else if (boards[0].isWinningBoard()) return boards[0].calculateScore() } throw IllegalArgumentException() } /** * Instances of this class represent a 5x5 Bingo board * Please note that the constructor is private. To create a new instance of this class, use the [createBoard] function. */ class BingoBoard private constructor(private val rowsAndColumns: Array<MutableSet<Int>>) { private var lastNumber: Int? = null fun markNumber(number: Int) { rowsAndColumns.forEach { it.remove(number) } lastNumber = number } /** * Creates a new instance of BingoBoard with the exact same state as this */ fun copy() = BingoBoard(rowsAndColumns) /** * Returns true iff at least one row or column of this board is completely marked */ fun isWinningBoard() = rowsAndColumns.any { it.isEmpty() } /** * Creates the score of a winning board. * @throws IllegalStateException if the board is not in a winning state when calculateScore is called */ fun calculateScore(): Int { if (!isWinningBoard()) throw IllegalStateException("Cannot calculate score if the board has not won") val remainingNumbers = mutableSetOf<Int>() rowsAndColumns.forEach { remainingNumbers += it } return remainingNumbers.sum() * lastNumber!! } companion object { /** * Creates a board based on a list of Strings * * @param[numberStrings] A list with 5 String items. Each item is a String with five numbers, * separated by whitespace */ fun createBoard(numberStrings: List<String>): BingoBoard { val numbers = numberStrings.map { it.trim().split("\\s+".toRegex()) }.map { list -> list.map(String::toInt) } val rowsAndColumns = Array<MutableSet<Int>>(10) { mutableSetOf() } for (i in 0 until 5) { for (j in 0 until 5) { rowsAndColumns[i] += numbers[i][j] rowsAndColumns[j + 5] += numbers[i][j] } } return BingoBoard(rowsAndColumns) } } }
0
Kotlin
0
0
28f57accccb98d8c2949171cd393669e67789d32
3,416
AdventOfCode2021
Apache License 2.0
shared/src/mobileMain/kotlin/org/jetbrains/kotlinconf/View.kt
JetBrains
108,403,211
false
{"Kotlin": 248479, "Ruby": 1705, "Swift": 783, "Shell": 226, "Procfile": 58}
package org.jetbrains.kotlinconf import io.ktor.util.date.GMTDate import org.jetbrains.kotlinconf.utils.dayAndMonth import org.jetbrains.kotlinconf.utils.time data class Agenda( val days: List<Day> = emptyList() ) data class Speakers( val all: List<Speaker> = emptyList() ) { private val dictById = all.associateBy { it.id } operator fun get(id: String): Speaker? = dictById[id] } data class Day( val day: Int, val title: String, val timeSlots: List<TimeSlot> ) data class TimeSlot( val startsAt: GMTDate, val endsAt: GMTDate, val isLive: Boolean, val isFinished: Boolean, val sessions: List<SessionCardView>, val isBreak: Boolean, val isLunch: Boolean, val isParty: Boolean ) { val title: String = if (isLunch || isBreak) { sessions.firstOrNull()?.title ?: "" } else { "${startsAt.time()}-${endsAt.time()}" } val id: String = "${startsAt.timestamp}-${endsAt.timestamp}-$title" val duration: String = "${(endsAt.timestamp - startsAt.timestamp) / 1000 / 60} MIN" } fun Conference.buildAgenda( favorites: Set<String>, votes: List<VoteInfo>, now: GMTDate ): Agenda { val days = sessions .groupBy { it.startsAt.dayOfMonth } .toList() .map { (day, sessions) -> val title = sessions.first().startsAt.dayAndMonth() Day( day, title, sessions.groupByTime(conference = this, now, favorites, votes) ) } .sortedBy { it.day } return Agenda(days) } fun List<Session>.groupByTime( conference: Conference, now: GMTDate, favorites: Set<String>, votes: List<VoteInfo>, ): List<TimeSlot> { val slots = filterNot { it.isLightning } .map { it.startsAt to it.endsAt } .distinct() .sortedBy { it.first } return slots.map { (start, end) -> val cards: List<SessionCardView> = filter { it.startsAt >= start && it.endsAt <= end } .map { it.asSessionCard(conference, now, favorites, votes) } val isBreak = cards.all { it.isBreak } val isLunch = cards.all { it.isLunch } val isParty = cards.all { it.isParty } val isLive = start <= now && now < end val isFinished = end <= now TimeSlot(start, end, isLive, isFinished, cards, isBreak, isLunch, isParty) } } fun Session.asSessionCard( conference: Conference, now: GMTDate, favorites: Set<String>, votes: List<VoteInfo>, ): SessionCardView { val isFinished = endsAt <= now val vote = votes.find { it.sessionId == id }?.score return SessionCardView( id = id, title = title, speakerLine = speakerLine(conference), locationLine = location, isFavorite = favorites.contains(id), startsAt = startsAt, endsAt = endsAt, speakerIds = speakerIds, isFinished = isFinished, vote = vote, description = description ) } fun Session.speakerLine(conference: Conference): String { val speakers = conference.speakers.filter { it.id in speakerIds } return speakers.joinToString { it.name } }
22
Kotlin
308
2,819
69909438506522b279d0771c8f47bdd69baf6c3c
3,221
kotlinconf-app
Apache License 2.0
src/main/kotlin/y2022/day04/Day04.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2022.day04 fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } fun input(): List<Pair<IntRange, IntRange>> { return AoCGenerics.getInputLines("/y2022/day04/input.txt").map { line -> Pair( IntRange( line.split(",")[0].split("-")[0].toInt(), line.split(",")[0].split("-")[1].toInt() ), IntRange( line.split(",")[1].split("-")[0].toInt(), line.split(",")[1].split("-")[1].toInt() ) ) } } fun part1(): Int { return input().map { elvesRanges -> val firstRange = elvesRanges.first.toSet() val secondRange = elvesRanges.second.toSet() val intersection = firstRange.intersect(secondRange) intersection.size == firstRange.size || intersection.size == secondRange.size }.count { it } } fun part2(): Int { return input().map { elvesRanges -> val firstRange = elvesRanges.first.toSet() val secondRange = elvesRanges.second.toSet() val intersection = firstRange.intersect(secondRange) intersection.isNotEmpty() }.count { it } }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
1,214
AdventOfCode
MIT License
year2020/src/main/kotlin/net/olegg/aoc/year2020/day20/Day20.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2020.day20 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2020.DayOf2020 /** * See [Year 2020, Day 20](https://adventofcode.com/2020/day/20) */ object Day20 : DayOf2020(20) { private val NUMBER = "\\d+".toRegex() private const val SIZE = 12 private val MONSTER = """ | # |# ## ## ### | # # # # # # """.trimMargin().lines().map { it.toList() } override fun first(): Any? { val tiles = data .split("\n\n") .map { it.lines() } .map { (NUMBER.find(it.first())?.value?.toIntOrNull() ?: 0) to it.drop(1).map { l -> l.toList() } } .map { it.first to profiles(it.second) } val profileCounts = tiles .flatMap { it.second } .groupingBy { it } .eachCount() val corners = tiles.filter { it.second.count { prof -> profileCounts[prof] == 1 } == 4 } return corners.map { it.first.toLong() }.reduce(Long::times) } override fun second(): Any? { val tiles = data .split("\n\n") .map { it.lines() } .associate { (NUMBER.find(it.first())?.value?.toIntOrNull() ?: 0) to it.drop(1).map { l -> l.toList() } } val profiles = tiles.mapValues { profiles(it.value) } val profileCounts = profiles .values .flatten() .groupingBy { it } .eachCount() val topLeftTile = profiles.entries.first { tile -> tile.value.count { prof -> profileCounts[prof] == 1 } == 4 }.key val available = tiles .mapValues { orderedProfiles(it.value) } .toMutableMap() val topLeft = available[topLeftTile]!! .first { prof -> prof.take(2).map { profileCounts[it] } == listOf(1, 1) } val grid = List(SIZE) { MutableList(SIZE) { 0 to listOf<Int>() } } grid[0][0] = topLeftTile to topLeft available -= topLeftTile (1..<SIZE).forEach { x -> val left = grid[0][x - 1] val rightCount = available.count { left.second[2] in it.value.flatten() } if (rightCount != 1) { error("Tiles available $rightCount") } val right = available.entries .first { left.second[2] in it.value.map { order -> order[0] } } .toPair() val rightOrder = right.second.first { left.second[2] == it[0] } grid[0][x] = right.first to rightOrder available -= right.first } (1..<SIZE).forEach { y -> val top = grid[y - 1][0] val bottomCount = available.count { top.second[3] in it.value.flatten() } if (bottomCount != 1) { error("Tiles available $bottomCount") } val bottom = available.entries .first { top.second[3] in it.value.map { order -> order[1] } } .toPair() val bottomOrder = bottom.second.first { top.second[3] == it[1] } grid[y][0] = bottom.first to bottomOrder available -= bottom.first } (1..<SIZE).forEach { y -> (1..<SIZE).forEach { x -> val left = grid[y][x - 1] val top = grid[y - 1][x] val edge = listOf(left.second[2], top.second[3]) val nextCount = available.count { edge in it.value.map { order -> order.take(2) } } if (nextCount != 1) { error("Tiles available $nextCount") } val next = available.entries .first { edge in it.value.map { order -> order.take(2) } } .toPair() val nextOrder = next.second.first { edge == it.take(2) } grid[y][x] = next.first to nextOrder available -= next.first } } val targetGrid = grid.flatMap { row -> val cells = row.map { (tileNum, profile) -> matchProfile(tiles.getValue(tileNum), profile) }.map { it.drop(1).dropLast(1).map { line -> line.drop(1).dropLast(1) } } cells[0].indices.map { line -> cells.flatMap { it[line] } } } val matchingGrid = (0..3) .scan(targetGrid) { acc, _ -> acc.rotate() } .flatMap { listOf(it, it.map { row -> row.reversed() }) } .first { currGrid -> currGrid.indices.any { y -> currGrid.indices.any { x -> hasPattern(x, y, currGrid) } } } val finalGrid = matchingGrid.map { it.toMutableList() } finalGrid.indices.forEach { y -> finalGrid.indices.forEach { x -> replacePattern(x, y, finalGrid) } } return finalGrid.sumOf { row -> row.count { it == '#' } } } private fun profile(tile: List<List<Char>>): List<Int> { val top = tile.first() val bottom = tile.last() val left = tile.map { it.first() } val right = tile.map { it.last() } return listOf(left, top, right, bottom) .map { it.joinToString(separator = "").replace('#', '1').replace('.', '0').toInt(2) } } private fun profiles(tile: List<List<Char>>): List<Int> { val top = tile.first() val bottom = tile.last() val left = tile.map { it.first() } val right = tile.map { it.last() } return listOf(left, top, right, bottom) .map { it.joinToString(separator = "").replace('#', '1').replace('.', '0') } .flatMap { listOf(it.toInt(2), it.reversed().toInt(2)) } } private fun orderedProfiles(tile: List<List<Char>>): List<List<Int>> { val top = tile.first() val bottom = tile.last().reversed() val left = tile.map { it.first() }.reversed() val right = tile.map { it.last() } return listOf(listOf(left, top, right, bottom)) .flatMap { order -> (0..<3).scan(order) { acc, _ -> acc.drop(1) + acc.take(1) } } .flatMap { listOf(it, it.reversed().map { order -> order.reversed() }) } .map { listOf(it[0].reversed(), it[1], it[2], it[3].reversed()) } .map { order -> order.map { it.joinToString(separator = "").replace('#', '1').replace('.', '0').toInt(2) } } } private fun matchProfile( tile: List<List<Char>>, profile: List<Int> ): List<List<Char>> { return (0..3) .scan(tile) { acc, _ -> acc.rotate() } .flatMap { listOf(it, it.map { row -> row.reversed() }) } .first { profile(it) == profile } } private fun <T> List<List<T>>.rotate(): List<List<T>> { val size = this.size val target = List(size) { y -> MutableList(size) { x -> this[y][x] } } for (i in 0..<size / 2) { for (j in i..<size - i - 1) { target[i][j] = this[size - 1 - j][i] target[size - 1 - j][i] = this[size - 1 - i][size - 1 - j] target[size - 1 - i][size - 1 - j] = this[j][size - 1 - i] target[j][size - 1 - i] = this[i][j] } } return target } private fun hasPattern( x: Int, y: Int, map: List<List<Char>> ): Boolean { return MONSTER.mapIndexed { my, row -> row.mapIndexed { mx, char -> val tx = x + mx val ty = y + my if (ty !in map.indices || tx !in map[ty].indices) return false char != '#' || map[ty][tx] != '.' }.all { it } }.all { it } } private fun replacePattern( x: Int, y: Int, map: List<MutableList<Char>> ) { if (hasPattern(x, y, map)) { MONSTER.forEachIndexed { my, row -> row.forEachIndexed { mx, char -> val tx = x + mx val ty = y + my if (ty !in map.indices || tx !in map[ty].indices) return if (char == '#') { map[ty][tx] = '*' } } } } } } fun main() = SomeDay.mainify(Day20)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
7,382
adventofcode
MIT License
src/Day01.kt
stephenkao
572,205,897
false
{"Kotlin": 14623}
fun main() { fun part1(input: List<String>): Int { var sum = 0 var max = 0 for (line in input) { if (line == "") { if (max < sum) { max = sum; } sum = 0; } else { sum += line.toInt() } } return max } fun part2(input: List<String>): Int { val sumList = mutableListOf<Int>() var currentSum = 0 for ((index, line) in input.withIndex()) { if (line == "") { sumList.add(currentSum) currentSum = 0 } else { currentSum += line.toInt() } if (index == input.lastIndex) { sumList.add(currentSum) currentSum = 0 } } return sumList.sortedDescending().take(3).sum() } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
7a1156f10c1fef475320ca985badb4167f4116f1
1,151
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day05.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2022 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part5A : PartSolution() { protected lateinit var commands: List<Command> internal lateinit var towers: List<MutableList<Char>> override fun parseInput(text: String) { val parts = text.trimEnd().split("\n\n") parseTowers(parts[0]) commands = getCommands(parts[1]) } private fun parseTowers(input: String) { towers = List(10) { mutableListOf() } for (line in input.split("\n")) { if (line[1] == '1') { continue } var i = 0 while (i * 4 + 1 < line.length) { val crate = line[i * 4 + 1] if (crate != ' ') { towers[i].add(crate) } i += 1 } } } private fun getCommands(input: String): List<Command> { return input.trim().split("\n").map(::Command).toList() } override fun compute(): String { commands.forEach { it.execute(towers) } return getMessage() } internal fun getMessage(): String { val message = towers.filter { it.isNotEmpty() }.map { it[0] }.joinToString("") return message.trim() } override fun getExampleAnswer(): String { return "CMZ" } protected data class Command(val count: Int, val src: Int, val dst: Int) { fun execute(towers: List<MutableList<Char>>, moveMultipleAtOnce: Boolean = false) { for (i in 0..<count) { towers[dst].add(if (moveMultipleAtOnce) i else 0, towers[src].removeFirst()) } } } private fun Command(line: String): Command { val match = Regex("move (\\d+) from (\\d+) to (\\d+)").find(line) ?: throw RuntimeException() val cnt = match.groupValues[1].toInt() val src = match.groupValues[2].toInt() val dst = match.groupValues[3].toInt() return Command(cnt, src - 1, dst - 1) } } class Part5B : Part5A() { override fun compute(): String { commands.forEach { it.execute(towers, true) } return getMessage() } override fun getExampleAnswer(): String { return "MCD" } } fun main() { Day(2022, 5, Part5A(), Part5B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
2,352
advent-of-code-kotlin
MIT License
src/Day01.kt
jimmymorales
572,156,554
false
{"Kotlin": 33914}
fun main() { fun List<String>.windowedSumCalories(): List<Int> = buildList { var sum = 0 for (calories in this@windowedSumCalories) { val cal = calories.toIntOrNull() if (cal != null) { sum += cal } else { add(sum) sum = 0 } } add(sum) }.sortedDescending() fun part1(input: List<String>): Int = input .windowedSumCalories() .first() fun part2(input: List<String>): Int = input .windowedSumCalories() .take(3) .sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) // part 2 check(part2(testInput) == 45000) println(part2(input)) }
0
Kotlin
0
0
fb72806e163055c2a562702d10a19028cab43188
899
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day20_trench_map/TrenchMap.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day20_trench_map import geom2d.Point import geom2d.Rect import geom2d.asLinearOffset import geom2d.bounds /** * Image processing! Just as described. Sharpening, blurring, edge detection, et * all are all based on this sort of algorithm. Take a kernel from the input, do * a thing to create an output pixel, repeat. Images are incredibly data-dense, * so making it work is only the tip of the iceberg. It has to be _fast_ or even * images of middling size will ruin your day. * * Part two illustrates the last. Nothing new, just "is it performant?" */ fun main() { util.solve(4917, ::partOne) // 5392, 4924 are too high; 4491 is too low util.solve(16389, ::partTwo) } private class Grid(input: String) { val width = input.indexOf('\n') val grid = input .filter { it != '\n' } val height = grid.length / width val bounds = Rect(width.toLong(), height.toLong()) fun isLit(p: Point) = if (bounds.contains(p)) grid[p.asLinearOffset(bounds).toInt()] == '#' else false } private fun Point.kernel() = listOf( // @formatter:off copy(x = x - 1, y = y - 1), copy( y = y - 1), copy(x = x + 1, y = y - 1), copy(x = x - 1 ), this, copy(x = x + 1 ), copy(x = x - 1, y = y + 1), copy( y = y + 1), copy(x = x + 1, y = y + 1), // @formatter:on ) fun partOne(input: String) = solve(input, 2) private fun solve(input: String, steps: Int): Int { if (steps % 2 != 0) { throw IllegalArgumentException("odd numbers of steps mean infinite pixels!") } val idx = input.indexOf('\n') val mask = input.substring(0, idx) var curr = Grid(input.substring(idx + 2)) .let { grid -> grid.bounds .allPoints() .filter(grid::isLit) .toSet() } var bounds = curr.bounds repeat(steps / 2) { halfTick -> bounds = bounds.expandedBy(3) repeat(2) { curr = bounds .allPoints() .filter { p -> val maskIdx = p.kernel() .map(curr::contains) .fold(0) { n, b -> (n shl 1) + (if (b) 1 else 0) } mask[maskIdx] == '#' } .toSet() } bounds = bounds.expandedBy(-1) curr = curr .filter(bounds::contains) .toSet() } return curr.size } fun partTwo(input: String) = solve(input, 50)
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
2,658
aoc-2021
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem2187/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2187 /** * LeetCode page: [2187. Minimum Time to Complete Trips](https://leetcode.com/problems/minimum-time-to-complete-trips/); */ class Solution { /* Complexity: * Time O(N * Log(MK)) and Space O(1) where N is the size of time, M is totalTrips, * and K is the minimum value in time. */ fun minimumTime(time: IntArray, totalTrips: Int): Long { var lower = 0L var upper = guessUpperBound(time, totalTrips) while (lower < upper) { val mid = lower + (upper - lower) / 2 val canComplete = canComplete(totalTrips, mid, time) if (canComplete) { upper = mid } else { lower = mid + 1 } } return lower } private fun guessUpperBound(tripTimeEachBus: IntArray, totalTrips: Int): Long { val minTime = tripTimeEachBus.min()!! return totalTrips.toLong() * minTime } private fun canComplete(targetTrips: Int, totalTime: Long, tripTimeEachBus: IntArray): Boolean { var totalTrips = 0L for (tripTime in tripTimeEachBus) { totalTrips += totalTime / tripTime if (totalTrips >= targetTrips) { return true } } return false } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,324
hj-leetcode-kotlin
Apache License 2.0
solutions/src/main/kotlin/fr/triozer/aoc/y2022/Day07.kt
triozer
573,964,813
false
{"Kotlin": 16632, "Shell": 3355, "JavaScript": 1716}
package fr.triozer.aoc.y2022 import fr.triozer.aoc.utils.readInput // #region other-file private class File { val parent: File? val name: String val size: Int val isFolder: Boolean val children: MutableList<File> = mutableListOf() constructor(parent: File?, name: String, size: Int) { this.parent = parent this.name = name this.size = size this.isFolder = false } constructor(parent: File?, name: String) { this.parent = parent this.name = name this.size = 0 this.isFolder = true } fun add(file: File) { children.add(file) } fun cd(path: String): File { if (path == "..") { return parent!! } if (path == "/") { var root = this while (root.parent != null) { root = root.parent!! } return root } return children.find { it.isFolder && it.name == path }!! } fun size(): Int { return if (isFolder) { children.sumOf { it.size() } } else { size } } override fun toString(): String { return if (isFolder) { val sb = StringBuilder("$name (folder, ${size()}, ${children.size} children)\n") children.joinToString("\n") { it.toString() }.lines().forEach { sb.append(" $it\n") } sb.toString().trim() } else { "$name (file, $size)" } } } // #endregion other-file // #region other-parse private fun List<String>.parseTree(root: File): File { var mRoot = root forEach { val args = it.split(" ") if (args[0].startsWith("$")) { when (args[1]) { "cd" -> { mRoot = mRoot.cd(args[2]) } "ls" -> {} else -> { println("Unknown command: ${args[1]}") } } } else { if (args[0] == "dir") { mRoot.add(File(mRoot, args[1])) } else { mRoot.add(File(mRoot, args[1], args[0].toInt())) } } } return root } // #endregion other-parse // #region part1 private fun part1(input: List<String>): Int { val root = input.parseTree(File(null, "/")) var totalSize = 0 fun calculate(file: File) { val size = file.size() if (file.isFolder && size <= 100000) { totalSize += size } file.children.forEach { calculate(it) } } calculate(root) return totalSize } // #endregion part1 // #region part2 private fun part2(input: List<String>): Int { val root = input.parseTree(File(null, "/")) val unusedSpace = 70000000 - root.size() val folders = mutableListOf<Int>() fun calculate(file: File) { val size = file.size() if (file.isFolder && unusedSpace + size > 30000000) { folders.add(size) } file.children.forEach { calculate(it) } } calculate(root) return folders.minByOrNull { it }!! } // #endregion part2 private fun main() { val testInput = readInput(2022, 7, "test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) println("Checks passed ✅") val input = readInput(2022, 7, "input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a9f47fa0f749a40e9667295ea8a4023045793ac1
3,462
advent-of-code
Apache License 2.0
src/main/kotlin/com/nibado/projects/advent/collect/Lists.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.collect fun <T> List<T>.reverse(index: Int, length: Int) : List<T> { val copy = toMutableList() reverseMutable(copy, index, length); return copy } fun <T> List<T>.swap(a: Int, b: Int) : List<T> { val copy = toMutableList() swap(copy, a, b) return copy } fun <T> List<T>.swapByValue(a: T, b: T) = swap(indexOf(a), indexOf(b)) fun <T> List<T>.swap(pair: Pair<Int, Int>) = this.swap(pair.first, pair.second) fun <T> swap(list: MutableList<T>, a: Int, b: Int) { val temp = list[a] list[a] = list[b] list[b] = temp } fun <T> swap(list: MutableList<T>, pair: Pair<Int, Int>) = swap(list, pair.first, pair.second) fun <T> List<T>.move(from: Int, to: Int) : List<T> { val copy = toMutableList() move(copy, from, to) return copy } fun <T> move(list: MutableList<T>, from: Int, to: Int) { val temp = list.removeAt(from) list.add(to, temp) } fun <T> List<T>.rotateLeft(amount: Int): List<T> { val amt = amount % size return subList(amt, size) + subList(0, amt) } fun <T> List<T>.rotateRight(amount: Int): List<T> { val amt = amount % size return subList(size - amt, size) + subList(0, size - amt) } fun <T> reverseMutable(list: MutableList<T>, index: Int, length: Int) { val indices = (index until index + length).map { it % list.size } val subList = list.slice(indices).reversed() indices.forEachIndexed { i, v -> list[v] = subList[i] } } fun <T> List<T>.permutations(): List<List<T>> { val permutations: MutableList<List<T>> = mutableListOf() permutate(this, listOf(), permutations) return permutations } private fun <T> permutate(head: List<T>, tail: List<T>, permutations: MutableList<List<T>>) { if (head.isEmpty()) { permutations += tail return } for (i in 0 until head.size) { val newHead = head.filterIndexed({ index, _ -> index != i }).toList() val newTail = tail + head[i] permutate(newHead, newTail, permutations) } }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
2,029
adventofcode
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem5/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem5 /** * LeetCode page: [5. Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/description/); */ class Solution2 { /* Complexity: * Time O(L^2) and Space O(L^2) where L is the length of s; */ fun longestPalindrome(s: String): String { // dp[start][length] ::= is s.slice(start..<start+length) a palindrome val dp = Array(s.length) { BooleanArray(s.length - it + 1) } // Base Cases for (i in s.indices) { dp[i][0] = true dp[i][1] = true } // Propagate the DP relation while keeping track of the longest palindrome var resultStart = 0 var resultLength = 1 for (length in 2..s.length) { for (start in 0..s.length - length) { dp[start][length] = s[start] == s[start + length - 1] && dp[start + 1][length - 2] if (dp[start][length] && length > resultLength) { resultStart = start resultLength = length } } } return s.slice(resultStart..<resultStart + resultLength) } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,213
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/io/github/raphaeltarita/days/Day14.kt
RaphaelTarita
433,468,222
false
{"Kotlin": 89687}
package io.github.raphaeltarita.days import io.github.raphaeltarita.structure.AoCDay import io.github.raphaeltarita.util.day import io.github.raphaeltarita.util.inputPath import io.github.raphaeltarita.util.splitAt import kotlinx.datetime.LocalDate import kotlin.io.path.readLines object Day14 : AoCDay { override val day: LocalDate = day(14) private fun getAllInput(): Triple<Map<Pair<Char, Char>, Long>, Map<Pair<Char, Char>, Char>, Char> { val (firstLine, other) = inputPath.readLines().splitAt(1) val template = firstLine.single() .zipWithNext() .groupingBy { it } .eachCount() .mapValues { (_, v) -> v.toLong() } val instructions = other.drop(1) .map { it.split(Regex("\\s*->\\s*")) } .associate { (pair, result) -> (pair[0] to pair[1]) to result[0] } val lastChar = firstLine.single().last() return Triple(template, instructions, lastChar) } private fun polymerization( template: Map<Pair<Char, Char>, Long>, instructions: Map<Pair<Char, Char>, Char>, iterations: Int ): Map<Pair<Char, Char>, Long> { var original = template var workingCopy = template.toMutableMap() repeat(iterations) { for ((pair, freq) in original) { val insert = instructions[pair] if (insert != null) { val newCount = (workingCopy[pair] ?: 0L) - freq if (newCount <= 0) { workingCopy.remove(pair) } else { workingCopy[pair] = newCount } val left = pair.first to insert val right = insert to pair.second workingCopy[left] = (workingCopy[left] ?: 0L) + freq workingCopy[right] = (workingCopy[right] ?: 0L) + freq } } original = workingCopy workingCopy = original.toMutableMap() } return original } private fun calculateResult(forIterations: Int): Long { val (template, instructions, lastChar) = getAllInput() val letterCounts = polymerization(template, instructions, forIterations).entries .groupingBy { (k, _) -> k.first } .aggregate { _, sum: Long?, count, _ -> (sum ?: 0L) + count.value } .toMutableMap() letterCounts[lastChar] = (letterCounts[lastChar] ?: 0) + 1 return (letterCounts.values.maxOrNull() ?: 0) - (letterCounts.values.minOrNull() ?: 0) } override fun executePart1(): Long { return calculateResult(10) } override fun executePart2(): Long { return calculateResult(40) } }
0
Kotlin
0
3
94ebe1428d8882d61b0463d1f2690348a047e9a1
2,786
AoC-2021
Apache License 2.0
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12926.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12926 * * 시저 암호 * 문제 설명 * 어떤 문장의 각 알파벳을 일정한 거리만큼 밀어서 다른 알파벳으로 바꾸는 암호화 방식을 시저 암호라고 합니다. * 예를 들어 "AB"는 1만큼 밀면 "BC"가 되고, 3만큼 밀면 "DE"가 됩니다. * "z"는 1만큼 밀면 "a"가 됩니다. * 문자열 s와 거리 n을 입력받아 s를 n만큼 민 암호문을 만드는 함수, solution을 완성해 보세요. * * 제한 조건 * 공백은 아무리 밀어도 공백입니다. * s는 알파벳 소문자, 대문자, 공백으로만 이루어져 있습니다. * s의 길이는 8000이하입니다. * n은 1 이상, 25이하인 자연수입니다. * 입출력 예 * s n result * "AB" 1 "BC" * "z" 1 "a" * "a B z" 4 "e F d" */ fun main() { // println(solution("a b y Z", 2)) solution("a b y Z", 2) } private fun solution(s: String, n: Int): String { var answer = "" // " " = 32 // a = 97, z = 122 // A = 65, Z = 90 for (char in s) { println(" - - - - - start - - - - - ") println("char = $char, ascii = ${char.toInt()}") if (isLowerCase(char.toInt())) { println("isLowerCase") if (isLowerCase(char.toInt() + n)) { answer += (char.toInt() + n).toChar() } else { println("LowerCase err, char.toInt() + n = ${char.toInt() + n}, ${(char.toInt() + n).toChar()} ") println("char.toInt() + n = ${char.toInt() + n}") println("${(96 + (char.toInt() + n).toInt() - 122).toChar()}") answer += (96 + (char.toInt() + n).toInt() - 122).toChar() } } if (isUpperCase(char.toInt())) { println("isUpperCase") if (isUpperCase(char.toInt() + n)) { answer += (char.toInt() + n).toChar() } else { println("UpperCase err, char.toInt() + n = ${char.toInt() + n}, ${(char.toInt() + n).toChar()} ") println("char.toInt() + n = ${char.toInt() + n}") println("${(64 + (char.toInt() + n).toInt() - 90).toChar()}") answer += (64 + (char.toInt() + n).toInt() - 90).toChar() } } if (char.toInt() == 32) { println("is ") answer += " " } println("answer = $answer") } return answer } private fun isLowerCase(ascii: Int): Boolean { return ascii in 97 .. 122 } private fun isUpperCase(ascii: Int): Boolean { return ascii in 65..90 }
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
2,702
HoOne
Apache License 2.0
src/Day01.kt
tigerxy
575,114,927
false
{"Kotlin": 21255}
fun main() { fun part1(input: List<String>): Int { var max = 0 var p = 0 input.forEach { val num = it.toIntOrNull() if (num == null) { if (p > max) { max = p } p = 0 } else { p += num } } return max } fun part2(input: List<String>): Int { val top = sortedSetOf<Int>() var p = 0 input.forEach { val num = it.toIntOrNull() if (num == null) { top.add(p) p = 0 } else { p += num } } return top.toList().takeLast(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
d516a3b8516a37fbb261a551cffe44b939f81146
1,029
aoc-2022-in-kotlin
Apache License 2.0
src/main/java/io/github/lunarwatcher/aoc/day12/Day12.kt
LunarWatcher
160,042,659
false
null
package io.github.lunarwatcher.aoc.day12 import io.github.lunarwatcher.aoc.commons.readFile import io.github.lunarwatcher.aoc.framework.Challenge import java.lang.UnsupportedOperationException data class Day12Data (val initialState: String, val modifiers: Map<String, Boolean>) class Day12 : Challenge<List<String>, Day12Data> { private val data = processData(readFile("day12.txt")) override fun part1(): Any = process(data, 20) override fun part2(): Any{ val initial100 = process(data, 100) val continued200 = process(data, 200) val diff = continued200 - initial100 return initial100 + (50000000000 - 100) / 100L * diff } override fun processPart1(case: Day12Data): Any = process(case, 20) override fun processPart2(case: Day12Data) : Any { throw UnsupportedOperationException("No tests allowed for part 2 of this day.") } override fun processData(raw: List<String>): Day12Data { val initialState = raw[0].split(": ")[1] val modifiers = mutableMapOf<String, Boolean>() for (i in 2 until raw.size) { val item = raw[i].split(" => ") modifiers[item[0]] = item[1].map { it == '#' }.also { if (it.size != 1) throw IllegalArgumentException() }[0] } return Day12Data(initialState, modifiers) } private fun process(data: Day12Data, gens: Long): Long { var currState = ".....${data.initialState}..." var zeroCoord = 5; for (generation in 0 until gens) { val builder = StringBuilder() for (i in 2 until currState.length - 2) { val subset = currState.substring(i - 2, i + 3) if (data.modifiers.keys.contains(subset)) { if (data.modifiers[subset]!!) builder.append("#") else builder.append("."); } else builder.append("."); } val current = builder.toString(); zeroCoord += 3; currState = ".....$current..." // Add more pots to make it possible to deal with big generations } return currState.countPlants(zeroCoord); } } private fun String.countPlants(zeroCoord: Int) = this.mapIndexed{ i, item -> if(item == '#') (i - zeroCoord).toLong() else 0 }.sum()
0
Kotlin
0
1
99f9b05521b270366c2f5ace2e28aa4d263594e4
2,401
AoC-2018
MIT License
src/week1/ContainsDuplicate.kt
anesabml
268,056,512
false
null
package week1 import kotlin.system.measureNanoTime class ContainsDuplicate { /** Brute force Linear search * Time complexity O(n2) * Space complexity O(1) */ fun containsDuplicate(nums: IntArray): Boolean { for (i in nums.indices) { for (j in 0 until i) { if (nums[j] == nums[i]) return true } } return false } /** Using sorting algorithms * Time complexity O(nlog(n)) * Space complexity O(1) * It's a good practise to keep the original input intact and work with a copy */ fun containsDuplicate2(nums: IntArray): Boolean { val sorted = nums.sortedArray() for (i in 0 until sorted.size - 1) { if (sorted[i] == sorted[i + 1]) return true } return false } /** Using dynamic data structure eg: HashSet * Time complexity O(n) * Space complexity O(n) */ fun containsDuplicate3(nums: IntArray): Boolean { val map = hashSetOf<Int>() for (n in nums) { if (map.contains(n)) { return true } map.add(n) } return false } /** Using Set * Time complexity O(n) * Space complexity O(n) */ fun containsDuplicate4(nums: IntArray): Boolean { return nums.toSet().size != nums.size } } fun main() { val input = intArrayOf(1, 1, 1, 3, 3, 4, 3, 2, 4, 2) val containsDuplicate = ContainsDuplicate() val firstSolutionTime = measureNanoTime { println(containsDuplicate.containsDuplicate(input)) } val secondSolutionTime = measureNanoTime { println(containsDuplicate.containsDuplicate2(input)) } val thirdSolutionTime = measureNanoTime { println(containsDuplicate.containsDuplicate3(input)) } val forthSolutionTime = measureNanoTime { println(containsDuplicate.containsDuplicate4(input)) } println("First Solution execution time: $firstSolutionTime") println("Second Solution execution time: $secondSolutionTime") println("Third Solution execution time: $thirdSolutionTime") println("Forth Solution execution time: $forthSolutionTime") }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
2,173
leetCode
Apache License 2.0
src/main/kotlin/wtf/log/xmas2021/day/day09/Day09.kt
damianw
434,043,459
false
{"Kotlin": 62890}
package wtf.log.xmas2021.day.day09 import wtf.log.xmas2021.Day import wtf.log.xmas2021.util.collect.Grid import wtf.log.xmas2021.util.collect.toGrid import java.io.BufferedReader object Day09 : Day<Grid<Int>, Int, Int> { override fun parseInput(reader: BufferedReader): Grid<Int> = reader .lineSequence() .map { line -> line.map { it.digitToInt() } } .toList() .toGrid() override fun part1(input: Grid<Int>): Int = findLowPoints(input).sumOf { it.value + 1 } override fun part2(input: Grid<Int>): Int { val lowPoints = findLowPoints(input) val basins = mutableMapOf<Grid.Entry<Int>, Set<Grid.Entry<Int>>>() val visited = mutableSetOf<Grid.Entry<Int>>() for (lowPoint in lowPoints) { val basin = mutableSetOf<Grid.Entry<Int>>() val deque = ArrayDeque<Grid.Entry<Int>>() deque.addFirst(lowPoint) while (deque.isNotEmpty()) { val point = deque.removeFirst() if (point.value != 9) { basin += point if (point !in visited) { for (adjacent in input.getCardinallyAdjacent(point.coordinate)) { if (adjacent !in lowPoints) { deque.addFirst(adjacent) } } } visited += point } } basins[lowPoint] = basin } return basins.values.map { it.size }.sortedDescending().take(3).fold(1, Int::times) } private fun findLowPoints(input: Grid<Int>): Set<Grid.Entry<Int>> { return input.filterTo(mutableSetOf()) { entry -> input.getCardinallyAdjacent(entry.coordinate) .all { it.value > entry.value } } } }
0
Kotlin
0
0
1c4c12546ea3de0e7298c2771dc93e578f11a9c6
1,892
AdventOfKotlin2021
BSD Source Code Attribution
year2023/day03/part1/src/main/kotlin/com/curtislb/adventofcode/year2023/day03/part1/Year2023Day03Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 3: Gear Ratios --- You and the Elf eventually reach a gondola lift station; he says the gondola lift will take you up to the water source, but this is as far as he can bring you. You go inside. It doesn't take long to find the gondolas, but there seems to be a problem: they're not moving. "Aaah!" You turn around to see a slightly-greasy Elf with a wrench and a look of surprise. "Sorry, I wasn't expecting anyone! The gondola lift isn't working right now; it'll still be a while before I can fix it." You offer to help. The engineer explains that an engine part seems to be missing from the engine, but nobody can figure out which one. If you can add up all the part numbers in the engine schematic, it should be easy to work out which part is missing. The engine schematic (your puzzle input) consists of a visual representation of the engine. There are lots of numbers and symbols you don't really understand, but apparently any number adjacent to a symbol, even diagonally, is a "part number" and should be included in your sum. (Periods (`.`) do not count as a symbol.) Here is an example engine schematic: ``` 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. ``` In this schematic, two numbers are not part numbers because they are not adjacent to a symbol: 114 (top right) and 58 (middle right). Every other number is adjacent to a symbol and so is a part number; their sum is 4361. Of course, the actual engine schematic is much larger. What is the sum of all of the part numbers in the engine schematic? */ package com.curtislb.adventofcode.year2023.day03.part1 import com.curtislb.adventofcode.year2023.day03.engine.EngineSchematic import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2023, day 03, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { val schematic = EngineSchematic.fromFile(inputPath.toFile()) return schematic.sumPartNumbers() } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,136
AdventOfCode
MIT License
src/main/kotlin/de/jball/aoc2022/day16/Day16.kt
fibsifan
573,189,295
false
{"Kotlin": 43681}
package de.jball.aoc2022.day16 import de.jball.aoc2022.Day class Day16(test: Boolean = false): Day<Int>(test, 1651, 1707) { private val valveRegex = "Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? (\\w+(, \\w+)*)".toRegex() private val valves = input .map { line -> parseValve(line) } .associateBy { valve -> valve.name } private val start = valves["AA"]!! private val valvesWithImpact = valves .filter { (_, valve) -> valve.flowRate > 0 } .map { (name, valve) -> Pair(name, valve.flowRate) } .toMap() private val happenedStates = mutableMapOf<Pair<Set<String>, String>, Int>() private val happenedStatesWithElephant = mutableMapOf<Triple<Set<String>, String, String>, Int>() private fun parseValve(line: String): Valve { val groups = valveRegex.find(line)!!.groups return Valve(groups[1]!!.value, groups[2]!!.value.toInt(), groups[3]!!.value.split(", "), false) } override fun part1(): Int { val initialState = SingleState(setOf(), 0, start.name) var lastStates = setOf(initialState) for (i in 1..30) { lastStates = lastStates.map { lastState -> if (currentValveHasImpact(lastState) && currentValveIsNotOpen(lastState)) { move(lastState).union(setOf(openVent(lastState))) } else { move(lastState) } }.flatten().toSet() } return lastStates .maxBy { state -> state.ventedSteam } .ventedSteam } private fun currentValveIsNotOpen(lastState: SingleState) = !lastState.openValves.contains(lastState.myPosition) private fun currentElephantValveIsNotOpen(lastState: StateWithElephant) = !lastState.openValves.contains(lastState.elephantPosition) private fun currentValveHasImpact(lastState: SingleState) = valvesWithImpact.containsKey(lastState.myPosition) private fun currentElephantValveHasImpact(lastState: StateWithElephant) = valvesWithImpact.containsKey(lastState.elephantPosition) private fun openVent(current: SingleState) = SingleState(current.openValves.plus(current.myPosition), current.ventedSteam + current.openValves.sumOf { valvesWithImpact[it]!! }, current.myPosition) private fun openVent(current: StateWithElephant) = StateWithElephant(current.openValves.plus(current.myPosition), current.ventedSteam + current.openValves.sumOf { valvesWithImpact[it]!! }, current.myPosition, current.elephantPosition) private fun openElephantVent(current: StateWithElephant) = StateWithElephant(current.openValves.plus(current.elephantPosition), current.ventedSteam, current.myPosition, current.elephantPosition) private fun move(current: SingleState): Set<SingleState> { val newStates = valves[current.myPosition]!!.neighborRefs .map { neighborRef -> SingleState(current.openValves, current.ventedSteam + current.openValves.sumOf { valve -> valvesWithImpact[valve]!! }, neighborRef) } .filter { state -> didntHappenOrWasWorse(state) }.toSet() newStates.forEach { newState -> happenedStates[Pair(newState.openValves, newState.myPosition)] = newState.ventedSteam } return newStates } private fun move(current: StateWithElephant): Set<StateWithElephant> { val newStates = valves[current.myPosition]!!.neighborRefs .map { neighborRef -> StateWithElephant(current.openValves, current.ventedSteam + current.openValves.sumOf { valve -> valvesWithImpact[valve]!! }, neighborRef, current.elephantPosition) } .filter { state -> didntHappenOrWasWorse(state) }.toSet() newStates.forEach { newState -> happenedStatesWithElephant[Triple(newState.openValves, newState.myPosition, newState.elephantPosition)] = newState.ventedSteam } return newStates } private fun moveElephant(current: StateWithElephant): Set<StateWithElephant> { val newStates = valves[current.elephantPosition]!!.neighborRefs .map { neighborRef -> StateWithElephant(current.openValves, current.ventedSteam, current.myPosition, neighborRef) } .filter { stateWithElephant -> didntHappenOrWasWorse(stateWithElephant) }.toSet() newStates.forEach { newState -> happenedStatesWithElephant[Triple(newState.openValves, newState.myPosition, newState.elephantPosition)] = newState.ventedSteam } return newStates } private fun didntHappenOrWasWorse(state: SingleState) = !happenedStates.containsKey(Pair(state.openValves, state.myPosition)) || happenedStates[Pair(state.openValves, state.myPosition)]!! < state.ventedSteam private fun didntHappenOrWasWorse(state: StateWithElephant) = !happenedStatesWithElephant.containsKey(Triple(state.openValves, state.myPosition, state.elephantPosition)) || happenedStatesWithElephant[Triple(state.openValves, state.myPosition, state.elephantPosition)]!! < state.ventedSteam override fun part2(): Int { val initialState = StateWithElephant(setOf(), 0, start.name, start.name) var lastStates = setOf(initialState) for (i in 1..26) { lastStates = lastStates.map { lastState -> if (currentValveHasImpact(lastState) && currentValveIsNotOpen(lastState)) { move(lastState).union(setOf(openVent(lastState))) } else { move(lastState) } }.flatten().toSet() lastStates = lastStates.map { lastState -> if (currentElephantValveHasImpact(lastState) && currentElephantValveIsNotOpen(lastState)) { moveElephant(lastState).union(setOf(openElephantVent(lastState))) } else { moveElephant(lastState) } }.flatten().toSet() } return lastStates .maxBy { state -> state.ventedSteam } .ventedSteam } } data class Valve(val name: String, val flowRate: Int, val neighborRefs: List<String>, var open: Boolean) open class SingleState(val openValves: Set<String>, val ventedSteam: Int, val myPosition: String) { override fun equals(other: Any?): Boolean { return other is SingleState && openValves == other.openValves && ventedSteam == other.ventedSteam && myPosition == other.myPosition } override fun hashCode(): Int { var result = openValves.hashCode() result = 31 * result + ventedSteam result = 31 * result + myPosition.hashCode() return result } } class StateWithElephant(openValves: Set<String>, ventedSteam: Int, myPosition: String, val elephantPosition: String) : SingleState(openValves, ventedSteam, myPosition) { override fun equals(other: Any?): Boolean { return other is StateWithElephant && super.equals(other) && other.elephantPosition == this.elephantPosition } override fun hashCode(): Int { return 31 * super.hashCode() + elephantPosition.hashCode() } } fun main() { Day16().run() }
0
Kotlin
0
3
a6d01b73aca9b54add4546664831baf889e064fb
7,438
aoc-2022
Apache License 2.0
src/main/kotlin/g2501_2600/s2542_maximum_subsequence_score/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2501_2600.s2542_maximum_subsequence_score // #Medium #Array #Sorting #Greedy #Heap_Priority_Queue // #2023_07_04_Time_780_ms_(81.97%)_Space_56.7_MB_(99.45%) import java.util.Arrays import java.util.PriorityQueue class Solution { private class PairInfo(var val1: Int, var val2: Int) fun maxScore(nums1: IntArray, nums2: IntArray, k: Int): Long { val n = nums1.size val nums = arrayOfNulls<PairInfo>(n) for (i in 0 until n) { nums[i] = PairInfo(nums1[i], nums2[i]) } Arrays.sort( nums ) { a: PairInfo?, b: PairInfo? -> if (a!!.val2 == b!!.val2) { return@sort a.val1 - b.val1 } a.val2 - b.val2 } var sum: Long = 0 var ans: Long = 0 val pq = PriorityQueue<Int>() for (i in n - 1 downTo 0) { val minVal = nums[i]!!.val2 while (pq.size > k - 1) { sum -= pq.poll().toLong() } sum += nums[i]!!.val1.toLong() pq.add(nums[i]!!.val1) if (pq.size == k) { ans = Math.max(ans, sum * minVal) } } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,217
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/adventofcode/Day03.kt
keeferrourke
434,321,094
false
{"Kotlin": 15727, "Shell": 1301}
package com.adventofcode data class Diagnostic(val rowView: List<String>) { private val colView: List<String> by lazy { readColumns(rowView) } private fun readColumns(rows: List<String>): List<String> { val columns = mutableMapOf<Int, String>() for (row in rows) { for (j in row.indices) { columns.merge(j, "${row[j]}") { v, _ -> v + row[j] } } } return columns.entries.map { it.value } } private fun mostCommonBit(bitString: String): Char? { val counts = bitString.groupingBy { it }.eachCount() return when { counts['1']!! > counts['0']!! -> '1' counts['0']!! > counts['1']!! -> '0' else -> null } } private fun negateBit(bit: Char) = when (bit) { '1' -> '0' '0' -> '1' else -> error("Expected bit") } val powerConsumption: Int get() { val (gamma, epsilon) = colView.fold("" to "") { (gamma, epsilon), column -> val most = mostCommonBit(column) ?: '1' (gamma + most) to (epsilon + negateBit(most)) } return gamma.toInt(2) * epsilon.toInt(2) } private fun o2RatingStrategy(bitString: String): Char = mostCommonBit(bitString) ?: '1' private fun co2RatingStrategy(bitString: String): Char = negateBit(o2RatingStrategy(bitString)) private fun getRating(strategy: (String) -> Char): Int { var readings = rowView var step = 0 var columns = readColumns(readings) do { val bit = strategy(columns[step]) readings = readings.filter { it[step] == bit } columns = readColumns(readings) step += 1 } while (readings.size > 1) return readings.first().toInt(2) } val o2Rating: Int get() = getRating(this::o2RatingStrategy) val co2Rating: Int get() = getRating(this::co2RatingStrategy) val lifeSupportRating: Int get() = o2Rating * co2Rating } fun day03(input: String, args: List<String> = listOf("p1")) { when (args.first().lowercase()) { "p1" -> println(Diagnostic(input.lines()).powerConsumption) "p2" -> println(Diagnostic(input.lines()).lifeSupportRating) } }
0
Kotlin
0
0
44677c6ae0ba1a8a8dc80dfa68c17b9c315af8e2
2,079
aoc2021
ISC License
src/Day03.kt
revseev
573,354,544
false
{"Kotlin": 9868}
fun main() { println(day3task1()) println(day3task2()) } fun day3task1(): Int { var sum = 0 readInputAsSequence("Day03") { sum = sumOf { findCommonCharCode(it) } } return sum } fun day3task2(): Int { var sum = 0 readInputAsSequence("Day03") { sum = chunked(3) { findCommonCharCode(it[0], it[1], it[2]) }.sum() } return sum } private val CHAR_FREQUENCY_MAP = IntArray(53) fun findCommonCharCode(a: String, b: String, c: String, frequencyBuffer: IntArray = CHAR_FREQUENCY_MAP): Int { frequencyBuffer.clear() for (i in a) { val code = i.getCharCode() frequencyBuffer[code] = 1 } for (j in b) { val code = j.getCharCode() if (frequencyBuffer[code] > 0) { frequencyBuffer[code] = 2 } } for (k in c) { val code = k.getCharCode() if (frequencyBuffer[code] == 2) { return code } } return 0 } fun findCommonCharCode(string: String, frequencyBuffer: IntArray = CHAR_FREQUENCY_MAP): Int { frequencyBuffer.clear() val length = string.length for (l in 0 until length / 2) { val code = string[l].getCharCode() frequencyBuffer[code] = 1 } for (r in length / 2..length) { val code = string[r].getCharCode() if (frequencyBuffer[code] > 0) { return code } } return 0 } fun Char.getCharCode(): Int = if (isUpperCase()) { (code - 'A'.code + 27) } else { (code - 'a'.code + 1) }
0
Kotlin
0
0
df2e12287a30a3a7bd5a026a963bcac41a730232
1,552
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SpiralMatrix2.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 /** * 59. Spiral Matrix II * @see <a href="https://leetcode.com/problems/spiral-matrix-ii">Source</a> */ fun interface SpiralMatrix2 { fun generateMatrix(n: Int): Array<IntArray> } /** * Approach 1: Traverse Layer by Layer in Spiral Form */ class SpiralMatrix2Traverse : SpiralMatrix2 { override fun generateMatrix(n: Int): Array<IntArray> { val result = Array(n) { IntArray(n) } var cnt = 1 for (layer in 0 until (n + 1) / 2) { // direction 1 - traverse from left to right for (ptr in layer until n - layer) { result[layer][ptr] = cnt++ } // direction 2 - traverse from top to bottom for (ptr in layer + 1 until n - layer) { result[ptr][n - layer - 1] = cnt++ } // direction 3 - traverse from right to left for (ptr in layer + 1 until n - layer) { result[n - layer - 1][n - ptr - 1] = cnt++ } // direction 4 - traverse from bottom to top for (ptr in layer + 1 until n - layer - 1) { result[n - ptr - 1][layer] = cnt++ } } return result } } class SpiralMatrix2Optimized : SpiralMatrix2 { override fun generateMatrix(n: Int): Array<IntArray> { val result = Array(n) { IntArray(n) } var cnt = 1 val dir = arrayOf( intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(-1, 0), ) var d = 0 var row = 0 var col = 0 while (cnt <= n * n) { result[row][col] = cnt++ val r = Math.floorMod(row + dir[d][0], n) val c = Math.floorMod(col + dir[d][1], n) // change direction if next cell is non-zero if (result[r][c] != 0) d = (d + 1) % 4 row += dir[d][0] col += dir[d][1] } return result } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,622
kotlab
Apache License 2.0
src/main/kotlin/days/aoc2015/Day18.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2015 import days.Day class Day18: Day(2015, 18) { override fun partOne(): Any { return performLife(inputList, 100).map { string -> string.count { it == '#' } }.sum() } fun performLife(inputList: List<String>, steps: Int): List<String> { var result = mutableListOf<String>() result.addAll(inputList) for (i in 0 until steps) { result = calculateNextLifeState(result) } return result } private fun calculateNextLifeState(currentState: List<String>): MutableList<String> { val result = mutableListOf<String>() for (y in currentState.indices) { val line = currentState[y] val newLine = StringBuilder() for (x in line.indices) { val neighboringLightsOn = currentState.lifeNeighbors(x, y).count { it == '#' } newLine.append(when(line[x]) { '#' -> { if (neighboringLightsOn == 2 || neighboringLightsOn == 3) { '#' } else { '.' } } '.' -> { if (neighboringLightsOn == 3) { '#' } else { '.' } } else -> error("oops") }) } result.add(newLine.toString()) } return result } override fun partTwo(): Any { var result = mutableListOf<String>() result.addAll(inputList) for (i in 0 until 100) { result[0] = '#' + result[0].substring(1, result[0].lastIndex) + '#' result[result.lastIndex] = '#' + result[result.lastIndex].substring(1, result[result.lastIndex].lastIndex) + '#' result = calculateNextLifeState(result) } result[0] = '#' + result[0].substring(1, result[0].lastIndex) + '#' result[result.lastIndex] = '#' + result[result.lastIndex].substring(1, result[result.lastIndex].lastIndex) + '#' return result.map { it.count { it == '#' } }.sum() } } fun List<String>.lifeNeighbors(charIndex: Int, lineIndex: Int) = sequence<Char> { for (y in (lineIndex - 1)..(lineIndex + 1)) for (x in (charIndex - 1)..(charIndex + 1)) if (!(y == lineIndex && x == charIndex) && y in indices && x in get(y).indices) yield(get(y)[x]) }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
2,573
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/2021/Day4.kt
mstar95
317,305,289
false
null
package `2021` import days.Day class Day4 : Day(4) { override fun partOne(): Any { val numbers: List<Int> = inputList.first().split(",").map { it.toInt() } val boards: List<Board> = createBoards(inputList.drop(2)) val bingo = mutableSetOf<Int>() val (wonBoard, wonNumber) = playBingo(bingo, numbers, boards) return wonBoard.mutableSet.map { it.value }.filter { !bingo.contains(it) }.sum() * wonNumber } override fun partTwo(): Any { val numbers: List<Int> = inputList.first().split(",").map { it.toInt() } val boards: List<Board> = createBoards(inputList.drop(2)) val bingo = mutableSetOf<Int>() val (wonBoard, wonNumber) = playLostBingo(bingo, numbers, boards.toMutableList()) return wonBoard.mutableSet.map { it.value }.filter { !bingo.contains(it) }.sum() * wonNumber } fun playBingo(bingo: MutableSet<Int>, numbers: List<Int>, boards: List<Board>): Pair<Board, Int> { numbers.forEach { number -> bingo.add(number) boards.forEach { board -> if (isBingo(board.rows, bingo) || isBingo(board.columns, bingo)) return board to number } } throw IllegalStateException() } fun playLostBingo(bingo: MutableSet<Int>, numbers: List<Int>, boards: MutableList<Board>): Pair<Board, Int> { numbers.forEach { number -> bingo.add(number) val won = boards.filter { board -> isBingo(board.rows, bingo) || isBingo(board.columns, bingo) } boards.removeAll(won) if (boards.isEmpty()) { assert(won.size == 1) return won.first() to number } } throw IllegalStateException() } fun isBingo(rows: Map<Int, List<Int>>, bingo: MutableSet<Int>): Boolean { return rows.values.any { row -> row.all { bingo.contains(it) } } } fun createBoards(param: List<String>): List<Board> { val boards = mutableListOf<Board>() var x = 0 var y = 0 var board = Board() for (line in param) { if (line.isBlank()) { y = 0 boards.add(board) board = Board() continue } line.split(" ").filter { it.isNotBlank() }.forEach { val p = Point(x, y, it.toInt()) board.add(p) x++ } x = 0 y++ } boards.add(board) return boards.toList() } data class Board(val mutableSet: MutableSet<Point> = mutableSetOf()) { fun add(p: Point) { mutableSet.add(p) } val rows: Map<Int, List<Int>> by lazy { mutableSet.groupBy({ it.x }, { it.value }) } val columns: Map<Int, List<Int>> by lazy { mutableSet.groupBy({ it.y }, { it.value }) } } data class Point(val x: Int, val y: Int, val value: Int) }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
3,086
aoc-2020
Creative Commons Zero v1.0 Universal
src/Day01.kt
icoffiel
572,651,851
false
{"Kotlin": 29350}
fun main() { fun parseToSums(input: String) = input .split("${System.lineSeparator()}${System.lineSeparator()}") .map { elf -> elf .lines() .sumOf { it.toInt() } } .sorted() fun part1(input: String): Int { return parseToSums(input) .takeLast(1) .first() } fun part2(input: String): Int { return parseToSums(input) .takeLast(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInputAsText("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputAsText("Day01") check(part1(input) == 69281) println(part1(input)) check(part2(input) == 201524) println(part2(input)) }
0
Kotlin
0
0
515f5681c385f22efab5c711dc983e24157fc84f
859
advent-of-code-2022
Apache License 2.0
src/main/kotlin/kt/kotlinalgs/app/sorting/crack/StreamRank.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.sorting val streamRank = StreamRank() for (value in intArrayOf(5, 1, 4, 4, 5, 9, 7, 13, 3)) { streamRank.track(value) } /* Tree: 5(5) 1(0) 9(1) 4(2) 7(0) 13(0) 4(1) 5(0) 3(0) */ println(streamRank.numTree.inorderTraversal()) println(streamRank.getRankOfNumber(0)) // 0 println(streamRank.getRankOfNumber(1)) // 0 println(streamRank.getRankOfNumber(3)) // 1 println(streamRank.getRankOfNumber(4)) // 3 println(streamRank.getRankOfNumber(13)) // 8 println(streamRank.getRankOfNumber(5)) // 5 println(streamRank.getRankOfNumber(6)) // 6 println(streamRank.getRankOfNumber(12)) // 8 println(streamRank.getRankOfNumber(14)) // 9 // O(log N) track + getRank if tree would be balanced, else O(N) runtime // O(N) space class StreamRank { val numTree = BinarySearchTree<Int>() fun track(num: Int) { numTree.insert(num) } fun getRankOfNumber(num: Int): Int { return numTree.rank(num) } } data class Node<T : Comparable<T>>( val value: T, var left: Node<T>? = null, var right: Node<T>? = null, var sizeOfSmallerElements: Int = 0 ) class BinarySearchTree<T : Comparable<T>>(var root: Node<T>? = null) { fun rank(value: T): Int { var rank = 0 var curNode = root while (curNode != null) { if (curNode.value == value) { return rank + curNode.sizeOfSmallerElements } else if (curNode.value > value) { // go left, doesn't change rank curNode = curNode.left } else { // go right, increase rank by skipped elements count rank += curNode.sizeOfSmallerElements + 1 // + 1 for root node curNode = curNode.right } } return rank } fun insert(value: T) { val node = Node(value) if (root == null) { root = node return } var cur = root while (cur != null) { if (value <= cur.value) { cur.sizeOfSmallerElements++ if (cur.left == null) { cur.left = node return } else { cur = cur.left } } else { // go right if (cur.right == null) { cur.right = node return } else { cur = cur.right } } } } fun inorderTraversal() { inorderTraversal(root) } private fun inorderTraversal(root: Node<T>?) { if (root == null) return // 1. visit left inorderTraversal(root.left) // 2. visit root println("${root.value}: ${root.sizeOfSmallerElements}") // 3. visit right inorderTraversal(root.right) } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
3,018
KotlinAlgs
MIT License
data_structures/Graphs/graph/Kotlin/DjikstraAlgorithm.kt
ZoranPandovski
93,438,176
false
{"Jupyter Notebook": 21909905, "C++": 1692994, "Python": 1158220, "Java": 806066, "C": 560110, "JavaScript": 305918, "Go": 145277, "C#": 117882, "PHP": 85458, "Kotlin": 72238, "Rust": 53852, "Ruby": 43243, "MATLAB": 34672, "Swift": 31023, "Processing": 22089, "HTML": 18961, "Haskell": 14298, "Dart": 11842, "CSS": 10509, "Scala": 10277, "Haxe": 9750, "PureScript": 9122, "M": 9006, "Perl": 8685, "Prolog": 8165, "Shell": 7901, "Erlang": 7483, "Assembly": 7284, "R": 6832, "Lua": 6392, "LOLCODE": 6379, "VBScript": 6283, "Clojure": 5598, "Elixir": 5495, "OCaml": 3989, "Crystal": 3902, "Common Lisp": 3839, "Julia": 3567, "F#": 3376, "TypeScript": 3268, "Nim": 3201, "Brainfuck": 2466, "Visual Basic .NET": 2033, "ABAP": 1735, "Pascal": 1554, "Groovy": 976, "COBOL": 887, "Mathematica": 799, "Racket": 755, "PowerShell": 708, "Ada": 490, "CMake": 393, "Classic ASP": 339, "QMake": 199, "Makefile": 111}
import java.util.ArrayList import java.util.Collections import java.util.HashMap import java.util.HashSet import java.util.LinkedList import kotlin.test.assertNotNull import kotlin.test.assertTrue class DijkstraAlgorithm(graph: Graph) { private val nodes: List<Vertex> private val edges: List<Edge> private var settledNodes: MutableSet<Vertex>? = null private var unSettledNodes: MutableSet<Vertex>? = null private var predecessors: MutableMap<Vertex, Vertex>? = null private var distance: MutableMap<Vertex, Int>? = null init { // create a copy of the array so that we can operate on this array this.nodes = ArrayList<Vertex>(graph.vertexes) this.edges = ArrayList<Edge>(graph.edges) } fun execute(source: Vertex) { settledNodes = HashSet() unSettledNodes = HashSet() distance = HashMap() predecessors = HashMap() distance!![source] = 0 unSettledNodes!!.add(source) while (unSettledNodes!!.size > 0) { val node = getMinimum(unSettledNodes!!) settledNodes!!.add(node!!) unSettledNodes!!.remove(node) findMinimalDistances(node) } } private fun findMinimalDistances(node: Vertex?) { val adjacentNodes = getNeighbors(node) for (target in adjacentNodes) { if (getShortestDistance(target) > getShortestDistance(node) + getDistance(node, target)) { distance!![target] = getShortestDistance(node) + getDistance(node, target) predecessors!![target] = node!! unSettledNodes!!.add(target) } } } private fun getDistance(node: Vertex?, target: Vertex): Int { for (edge in edges) { if (edge.source == node && edge.destination == target) { return edge.weight } } throw RuntimeException("Should not happen") } private fun getNeighbors(node: Vertex?): List<Vertex> { val neighbors = ArrayList<Vertex>() for (edge in edges) { if (edge.source == node && !isSettled(edge.destination)) { neighbors.add(edge.destination) } } return neighbors } private fun getMinimum(vertexes: Set<Vertex>): Vertex? { var minimum: Vertex? = null for (vertex in vertexes) { if (minimum == null) { minimum = vertex } else { if (getShortestDistance(vertex) < getShortestDistance(minimum)) { minimum = vertex } } } return minimum } private fun isSettled(vertex: Vertex): Boolean { return settledNodes!!.contains(vertex) } private fun getShortestDistance(destination: Vertex?): Int { val d = distance!![destination] return d ?: Integer.MAX_VALUE } /* * This method returns the path from the source to the selected target and * NULL if no path exists */ fun getPath(target: Vertex): LinkedList<Vertex>? { val path = LinkedList<Vertex>() var step = target // check if a path exists if (predecessors!![step] == null) { return null } path.add(step) while (predecessors!![step] != null) { step = predecessors!![step]!! path.add(step) } // Put it into the correct order Collections.reverse(path) return path } } class Edge(val id: String, val source: Vertex, val destination: Vertex, val weight: Int) { override fun toString(): String { return source.toString() + " " + destination.toString() } } class Graph(val vertexes: List<Vertex>, val edges: List<Edge>) class Vertex(val id: String?, val name: String) { override fun hashCode(): Int { val prime = 31 var result = 1 result = prime * result + (id?.hashCode() ?: 0) return result } override fun equals(obj: Any?): Boolean { if (this === obj) return true if (obj == null) return false if (javaClass != obj.javaClass) return false val other = obj as Vertex? if (id == null) { if (other!!.id != null) return false } else if (id != other!!.id) return false return true } override fun toString(): String { return name } } class TestDijkstraAlgorithm { companion object { private lateinit var nodes: MutableList<Vertex> private lateinit var edges: MutableList<Edge> @JvmStatic fun main(args : Array<String>) { nodes = ArrayList() edges = ArrayList() for (i in 0..10) { val location = Vertex("Node_$i", "Node_$i") nodes.add(location) } addLane("Edge_0", 0, 1, 85) addLane("Edge_1", 0, 2, 217) addLane("Edge_2", 0, 4, 173) addLane("Edge_3", 2, 6, 186) addLane("Edge_4", 2, 7, 103) addLane("Edge_5", 3, 7, 183) addLane("Edge_6", 5, 8, 250) addLane("Edge_7", 8, 9, 84) addLane("Edge_8", 7, 9, 167) addLane("Edge_9", 4, 9, 502) addLane("Edge_10", 9, 10, 40) addLane("Edge_11", 1, 10, 600) // Lets check from location Loc_1 to Loc_10 val graph = Graph(nodes, edges) val dijkstra = DijkstraAlgorithm(graph) dijkstra.execute(nodes[0]) val path = dijkstra.getPath(nodes[10]) assertNotNull(path) assertTrue(path!!.size > 0) for (vertex in path) { System.out.println(vertex) } } private fun addLane(laneId: String, sourceLocNo: Int, destLocNo: Int, duration: Int) { val lane = Edge(laneId, nodes[sourceLocNo], nodes[destLocNo], duration) edges.add(lane) } } }
62
Jupyter Notebook
1,994
1,298
62a1a543b8f3e2ca1280bf50fc8a95896ef69d63
6,114
al-go-rithms
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/asher_stern/parser/cyk/CykAlgorithmWithHack.kt
asher-stern
109,838,279
false
null
package com.github.asher_stern.parser.cyk import com.github.asher_stern.parser.grammar.ChomskyNormalFormGrammar import com.github.asher_stern.parser.grammar.SyntacticItem import com.github.asher_stern.parser.tree.TreeNode import com.github.asher_stern.parser.utils.Array1 /** * Created by <NAME> on November-05 2017. */ /** * Extends [CykAlgorithm] to generate parse-trees also for ungrammatical sentence. So the method [parse] always returns a tree. */ class CykAlgorithmWithHack<N, T>(grammar: ChomskyNormalFormGrammar<N, T>, sentence: Array1<T>) : CykAlgorithm<N, T>(grammar, sentence) { override fun hackTree(): TreeNode<N, T> { val tree = generateTreeForRange(1, sentence.size) if (tree.content.symbol == grammar.startSymbol) { return tree } else { val newTree = TreeNode<N, T>(SyntacticItem.createSymbol(grammar.startSymbol)) newTree.addChild(tree) return newTree } } private fun generateTreeForRange(start: Int, end: Int): TreeNode<N, T> { val longest = findLongest(start, end) if (longest == null) { val children = sentence.slice(start, end).map { TreeNode<N, T>(SyntacticItem.createTerminal(it)) } return TreeNode<N, T>(SyntacticItem.createSymbol(grammar.startSymbol), children.toMutableList()) } else { val longestTree = buildTree(longest.start, longest.end, longest.symbol) var ret: TreeNode<N, T> = longestTree if (longest.start > start) { val toLeft = generateTreeForRange(start, longest.start-1) val newRet = TreeNode<N, T>(SyntacticItem.createSymbol(grammar.startSymbol)) newRet.addChild(toLeft) newRet.addChild(ret) ret = newRet } if (longest.end < end) { val toRight = generateTreeForRange(longest.end+1, end) val newRet = TreeNode<N, T>(SyntacticItem.createSymbol(grammar.startSymbol)) newRet.addChild(ret) newRet.addChild(toRight) ret = newRet } return ret } } private fun findLongest(start: Int, end: Int): TableIndex<N>? { val givenRangeLength = end-start+1 for (length in givenRangeLength downTo 1) { for (candidateStart in start..(end-length+1)) { val candidateEnd = candidateStart + length -1 val symbolsMap = table[candidateStart, candidateEnd] if (symbolsMap != null) { val candidate = symbolsMap.entries.filter { it.value != null }.sortedByDescending { it.value!!.logProbability }.firstOrNull() if (candidate != null) { return TableIndex(candidateStart, candidateEnd, candidate.key) } } } } return null } } private data class TableIndex<N>(val start: Int, val end: Int, val symbol: N)
0
Kotlin
0
0
4d54f49eae47260a299ca375fc5442f002032116
3,178
parser
MIT License
src/day01/Day01.kt
RegBl
573,086,350
false
{"Kotlin": 11359}
package day01 import readInput fun main() { fun part1(input: List<Int>): Int { return input.last() } fun part2(input: List<Int>): Int { return input.sum() } fun splitByEmptyLine(input: List<String>): List<List<String>> { return input.fold(mutableListOf(mutableListOf<String>())) { acc, line -> if (line.isEmpty()) { acc.add(mutableListOf<String>()) } else { acc.last().add(line) } acc } } val input = readInput("\\day01\\Day01") // test if implementation meets criteria from the description, like: val elvesWithCalories = splitByEmptyLine(input).map { elf -> elf.sumOf { it.toInt() } }.sorted() val (_, elvesWithCaloriesTopThree) = elvesWithCalories.withIndex() .groupBy { it.index < elvesWithCalories.size - 3 } .map { it.value.map { it.value } } println(part1(elvesWithCalories)) println(part2(elvesWithCaloriesTopThree)) }
0
Kotlin
0
0
bd45eb4378d057267823dcc72ad958492f7056ff
1,009
aoc-2022
Apache License 2.0
src/main/kotlin/org/wow/evaluation/transition/BestTransitionsFinder.kt
WonderBeat
22,673,830
false
null
package org.wow.evaluation.transition import org.wow.logger.GameTurn import org.wow.evaluation.Evaluator public data class PlayerGameTurn(val from: GameTurn, val to: GameTurn, val playerName: String) public class BestTransitionsFinder(val evaluator: Evaluator) { fun findBestTransitions(game: List<GameTurn>): List<PlayerGameTurn> { val players = listPlayersOnMap(game) val best = pairs(game).map { gameTurnPair -> val playersTurns = players.map { player -> PlayerGameTurn(gameTurnPair.first, gameTurnPair.second, player!!) } findBestPlayerTurn(playersTurns) }.filterNotNull() return best } fun findBestPlayerTurn(turns: List<PlayerGameTurn>): PlayerGameTurn? = turns.map { Pair(evaluateTurn(it), it) } .filter { it.first > 0 } .sortBy { it.first } .last?.second fun evaluateTurn(turn: PlayerGameTurn): Double = evaluator.difference(turn.playerName, turn.from, turn.to) fun listPlayersOnMap(game: List<GameTurn>): Set<String?> { return game.first().planets.map { it.getOwner() }.filterNot { it!!.isEmpty() }.distinct() } /** * Creates World pairs * (first, second), (second, third) ... (n-1, n) */ private fun pairs(game: List<GameTurn>): List<Pair<GameTurn, GameTurn>> = game.take(game.size - 1).zip(game.tail) }
0
Kotlin
0
0
92625c1e4031ab4439f8d8a47cfeb107c5bd7e31
1,474
suchmarines
MIT License
src/main/kotlin/Day3_1.kt
vincent-mercier
726,287,758
false
{"Kotlin": 37963}
import java.io.File import java.io.InputStream import kotlin.streams.asSequence fun validInts(rowNb: Int, index: Int, matchResults: List<MatchResult>): List<Pair<Pair<Int, Int>, Int>> = matchResults .asSequence() .filter { it.range.contains(index) || index == it.range.start - 1 || index == it.range.endInclusive + 1 } .map { (rowNb to it.range.start) to it.value.toInt() } .toList() fun main() { val inputStream: InputStream = File("./src/main/resources/day3.txt").inputStream() val intRegex = "(\\d+)".toRegex() val input = inputStream.bufferedReader().lines() .asSequence() .map { c -> val intMatches = intRegex.findAll(c).toList() val symbolIndices = c.asSequence() .mapIndexed { i2, c2 -> i2 to (!c2.isDigit() && c2 != '.') } .filter { it.second } .map { it.first } intMatches to symbolIndices } .toList() println( input.flatMapIndexed { index: Int, pair: Pair<List<MatchResult>, Sequence<Int>> -> when (index) { 0 -> { pair.second.flatMap { validInts(index, it, input[index].first) + validInts(index + 1, it, input[index + 1].first) } } input.size - 1 -> { pair.second.flatMap { validInts(index - 1, it, input[index - 1].first) + validInts(index, it, input[index].first) } } else -> { pair.second.flatMap { validInts(index - 1, it, input[index - 1].first) + validInts(index, it, input[index].first) + validInts(index + 1, it, input[index + 1].first) } } } } .groupBy { it.first } .map { it.value.first().second } .sum() ) }
0
Kotlin
0
0
53b5d0a0bb65a77deb5153c8a912d292c628e048
2,224
advent-of-code-2023
MIT License
src/twentytwentytwo/day10/Day10.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentytwo.day10 import readInput import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { var cycleCount = 1 var x = 1 var total = 0 val specialCycles = mutableSetOf(20, 60, 100, 140, 180, 220) input.forEach { line -> var delta = 0 if (line == "noop") { cycleCount++ } else { delta = line.split(" ")[1].toInt() cycleCount += 2 x += delta } val toRemove = mutableSetOf<Int>() specialCycles.forEach { if (cycleCount - it == 0) { total += x * it toRemove.add(it) } else if (cycleCount - it == 1) { total += (x - delta) * it toRemove.add(it) } } specialCycles.removeAll(toRemove) } return total } fun part2(input: List<String>) { var cycleCount = 1 var x = 1 drawPixel(cycleCount, x) input.forEach { line -> if (line == "noop") { cycleCount++ drawPixel(cycleCount, x) } else { val delta = line.split(" ")[1].toInt() cycleCount += 2 drawPixel(cycleCount - 1, x) x += delta drawPixel(cycleCount, x) } } } val input = readInput("day10", "Day10_input") println(part1(input)) part2(input) } private fun drawPixel(cycleCount: Int, x: Int) { if (cycleCount > 240) return if (abs(x - ((cycleCount % 40) - 1)) <= 1) { print("#") } else { print(".") } if (cycleCount % 40 == 0) println() }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
1,809
advent-of-code
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day12.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2022 import at.mpichler.aoc.lib.* import org.jetbrains.kotlinx.multik.api.mk import org.jetbrains.kotlinx.multik.api.zeros import org.jetbrains.kotlinx.multik.ndarray.data.D2Array import org.jetbrains.kotlinx.multik.ndarray.data.set open class Part12A : PartSolution() { private lateinit var grid: D2Array<Int> internal open val startChar = 'S' private val endChar = 'E' override fun parseInput(text: String) { grid = createGrid(text.trim().split("\n")) } override fun compute(): Int { val starts = mutableListOf<Vector2i>() var end = Vector2i(0, 0) for (p in grid.multiIndices) { val pos = Vector2i(p[1], p[0]) val char = grid[pos] if (char == startChar.code) { starts.add(pos) } else if (char == endChar.code) { end = pos } } val traversal = BreadthFirst(this::nextEdges).startFrom(starts).goTo(end) return traversal.depth - 1 } private fun nextEdges(pos: Vector2i, traversal: BreadthFirst<*>): List<Vector2i> { return grid.neighborPositions(pos).filter { height(grid[it]) <= height(grid[pos]) + 1 }.toList() } private fun height(code: Int): Int { if (code == 'S'.code) { return 'a'.code } else if (code == 'E'.code) { return 'z'.code } return code } override fun getExampleAnswer(): Int { return 31 } private fun createGrid(lines: List<String>): D2Array<Int> { val values = mk.zeros<Int>(lines.size, lines.first().length) for ((y, line) in lines.withIndex()) { for ((x, char) in line.withIndex()) { values[y, x] = char.code } } return values } } class Part12B : Part12A() { override val startChar: Char = 'a' override fun getExampleAnswer(): Int { return 29 } } fun main() { Day(2022, 12, Part12A(), Part12B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
2,045
advent-of-code-kotlin
MIT License
src/Day01.kt
rromanowski-figure
573,003,468
false
{"Kotlin": 35951}
object Day01 : Runner<Int, Int>(1, 24000, 45000) { override fun part1(input: List<String>): Int = toCalorieMap(input).values.maxOf { it.sum() } override fun part2(input: List<String>): Int { val calories = toCalorieMap(input).values.map { it.sum() } .sortedByDescending { it } .take(3) return calories.sum() } private fun toCalorieMap(input: List<String>): Map<Int, List<Int>> { var lastCut = 0 val calorieMap = mutableMapOf<Int, List<Int>>() input.foldIndexed(calorieMap) { index, map, calories -> if (calories.isBlank() || index == input.size - 1) { map[lastCut] = input.subList(lastCut, index + 1).filter { it.isNotBlank() }.map { it.toInt() } lastCut = index + 1 } map } return calorieMap.toMap() } }
0
Kotlin
0
0
6ca5f70872f1185429c04dcb8bc3f3651e3c2a84
879
advent-of-code-2022-kotlin
Apache License 2.0
src/Day05.kt
becsegal
573,649,289
false
{"Kotlin": 9779}
import java.io.File fun main() { var stacks: ArrayList<ArrayList<String?>> = ArrayList() var instructions: ArrayList<List<Int>> = ArrayList() fun initializeStackLine(row: List<String?>) { row.forEachIndexed { index, value -> if (stacks.size <= index) { stacks.add(ArrayList<String?>()) } if (value != null) stacks[index].add(value); } } fun initalizeStacksAndInstructions(filename: String) { stacks = ArrayList() instructions = ArrayList() val elementRegex: Regex = "[A-Z]".toRegex() val movesRegex: Regex = """\d+""".toRegex() File(filename).forEachLine { if (it.contains("[")) { val elements = it.chunked(4).map{ elementRegex.find(it)?.value } initializeStackLine(elements) } else if (it.contains("move")) { instructions.add(movesRegex.findAll(it).map{ it.value.toInt() }.toList()) } } } fun part1(filename: String): String { initalizeStacksAndInstructions(filename) instructions.forEach { val nTimes = it[0] val fromStackNum = it[1] - 1 val toStackNum = it[2] - 1 repeat(nTimes) { val fromStack = stacks[fromStackNum] val moveVal = fromStack.removeAt(0) stacks[toStackNum].add(0, moveVal) } } return stacks.map{ if (it.size > 0) it[0] else "" }.joinToString(separator="") } fun part2(filename: String): String { initalizeStacksAndInstructions(filename) instructions.forEach { val nTimes = it[0] val fromStackNum = it[1] - 1 val toStackNum = it[2] - 1 var removeFrom: Int = nTimes - 1; repeat(nTimes) { val fromStack = stacks[fromStackNum] val moveVal = fromStack.removeAt(removeFrom) stacks[toStackNum].add(0, moveVal) removeFrom -= 1 } } return stacks.map{ if (it.size > 0) it[0] else "" }.joinToString(separator="") } println("part 1: " + part1("input_day05.txt")) println("part 2: " + part2("input_day05.txt")) }
0
Kotlin
0
0
a4b744a3e3c940c382aaa1d5f5c93ae0df124179
2,287
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Algorithm.kt
nkkarpov
605,326,618
false
null
import java.lang.Math.ceil import kotlin.math.floor import kotlin.math.max import kotlin.random.Random fun batchedSAR(env: Environment, m: Int, K: Int, budget: Int): List<Int> { val n = emptyList<Int>().toMutableList() val Q = mutableListOf<Int>() var I = (0 until env.n).toMutableList() val est = DoubleArray(env.n) { 0.0 } val cnt = DoubleArray(env.n) { 0.0 } val delta = DoubleArray(env.n) { 0.0 } fun mean(arm: Int) = est[arm] / cnt[arm] + 1e-9 * arm var t = env.n while (t > 1) { n.add(t) t /= 2 } n.add(0) var time = 0 var cntWords = 0 val T = compute2(n, budget * K) for (r in 0 until T.size) { for (arm in I) { repeat(T[r]) { est[arm] += env.pull(arm) cnt[arm] += 1.0 } } time += ceil(1.0 * I.size * (T[r]) / K).toInt() cntWords += 2 * (K * I.size) I.sortBy { -mean(it) } val m0 = m - Q.size val a = mean(I[m0]) val b = mean(I[m0 + 1]) for (arm in I) delta[arm] = max(a - mean(arm), mean(arm) - b) I.sortBy { delta[it] } Q.addAll(I.drop(n[r + 1]).filter { mean(it) > b }) I = I.take(n[r + 1]).toMutableList() } // println(Q) println("B,$K,$budget,${if (Q.sorted() == (0..m).toList()) 1 else 0},$cntWords") // println("time = $time") // assert(time <= budget) return Q } fun SAR(env: Environment, m: Int, K: Int, budget: Int): List<Int> { val coef = 0.5 + (2..env.n).sumOf { 1.0 / it } val T = (0 until env.n).map { if (it == 0) 0.toInt() else floor(1.0 / coef * (budget * K - env.n) / (env.n + 1 - it)).toInt() } val Q = mutableListOf<Int>() val I = (0 until env.n).toMutableList() val est = DoubleArray(env.n) { 0.0 } val cnt = DoubleArray(env.n) { 0.0 } val delta = DoubleArray(env.n) { 0.0 } fun mean(arm: Int) = est[arm] / cnt[arm] for (r in 1 until env.n) { for (arm in I) { repeat(T[r] - T[r - 1]) { est[arm] += env.pull(arm) cnt[arm] += 1.0 } } I.sortBy { -mean(it) } val m0 = m - Q.size val a = mean(I[m0]) val b = mean(I[m0 + 1]) for (arm in I) delta[arm] = max(a - mean(arm), mean(arm) - b) I.sortBy { delta[it] } if (mean(I.last()) > b) Q.add(I.last()) I.removeLast() } val m0 = m - Q.size Q.addAll(I.take(m0 + 1)) if (K > 1) { println("SK,$K,$budget,${if (Q.sorted() == (0..m).toList()) 1 else 0},0") } else { println("S1,$K,$budget,${if (Q.sorted() == (0..m).toList()) 1 else 0},0") } return Q.sorted() } fun compute1(n: List<Int>, budget : Int): List<Int> { val T = IntArray(n.size - 1) { 0 } var left = 0.toDouble() var right = budget.toDouble() repeat(60) { val ave = (left + right) / 2 for (i in T.indices) { T[i] = (ave / n[i]).toInt() } if (T.indices.sumOf { 2 * T[it] * n[it] } <= budget) { left = ave } else { right = ave } } for (i in T.indices) { T[i] = (left / n[i]).toInt() } return T.toList() } fun compute2(n: List<Int>, budget : Int): List<Int> { val T = IntArray(n.size - 1) { 0 } var left = 0.toDouble() var right = budget.toDouble() repeat(60) { val ave = (left + right) / 2 for (i in T.indices) { T[i] = (ave / n[i]).toInt() } if (T.indices.sumOf { T[it] * n[it] } <= budget) { left = ave } else { right = ave } } for (i in T.indices) { T[i] = (left / n[i]).toInt() } return T.toList() } fun collabTop(env: Environment, m: Int, seed: Int, K: Int, budget: Int): List<Int> { val Q = mutableListOf<Int>() val n = emptyList<Int>().toMutableList() val est = DoubleArray(env.n) { 0.0 } val cnt = DoubleArray(env.n) { 0.0 } val delta = DoubleArray(env.n) { 0.0 } fun mean(arm: Int) = est[arm] / cnt[arm] + 1e-9 * arm var t = env.n while (t > 1) { n.add(t) t /= 2 } n.add(0) val T = compute1(n, budget * K) // println(T) var s = 0 for (r in T.indices) { s += n[r] * (T[r]) } // println("KT = ${budget * K}") // println("s = $s") val rnd = Random(seed) val I = Array(K) { emptyList<Int>().toMutableList() } for (i in 0 until env.n) { I[rnd.nextInt(K)].add(i) } var cntWords = 0 var time = 0 var r = 0 while (n[r + 1] != 2 && m - Q.size >= 0) { cntWords += K val maxSize = I.maxOf { it.size } val minSize = I.minOf { it.size } if (maxSize > 2 * minSize) { break } time += maxSize * (T[r]) for (k in I.indices) { for (arm in I[k]) { repeat(T[r]) { est[arm] += env.pull(arm) cnt[arm] += 1.0 } } } val result0 = order(m - Q.size, I, (0 until env.n).map { -mean(it) }.toDoubleArray(), K) val result1 = order(m + 1 - Q.size, I, (0 until env.n).map { -mean(it) }.toDoubleArray(), K) cntWords += result0.second cntWords += result1.second // println("${result0.first} ${result1.first}") // println("${mean(result0.first)} ${mean(result1.first)}") // if (result0.first == result1.first) { // println((0 until env.n).map { mean(it) }.sorted()) // } // assert(result0.first != result1.first) // assert(mean(result0.first) > mean(result1.first)) // println((0 until env.n).sortedBy { mean(it) }.map { mean(it) }) for (i in 0 until env.n) delta[i] = max(mean(result0.first) - mean(i), mean(i) - mean(result1.first)) val result2 = order(n[r + 1], I, delta, K) cntWords += result2.second // println("result = ${result2.first}") // println("split ${delta[result2.first]}") // println(delta.toList()) for (k in I.indices) { Q.addAll(I[k].filter { cmp(Pair(delta[it], it), Pair(delta[result2.first], result2.first)) >= 0 && cmp( Pair( -mean(it), it ), Pair(-mean(result0.first), result0.first) ) == -1 }) I[k] = I[k].filter { cmp(Pair(delta[it], it), Pair(delta[result2.first], result2.first)) == -1 } .toMutableList() } r++ } var Ig = I.flatMap { it }.toMutableList() cntWords += Q.size + Ig.size while (Ig.size > 0 && m >= Q.size && m + 1 < Ig.size + Q.size) { cntWords += 2 * (Ig.size + K) time += ceil(1.0 * Ig.size * (2 * T[r]) / K).toInt() for (arm in Ig) { repeat(2 * T[r]) { est[arm] += env.pull(arm) cnt[arm] += 1.0 } } Ig.sortBy { -mean(it) } val m0 = m - Q.size val a = mean(Ig[m0]) val b = mean(Ig[m0 + 1]) for (arm in Ig) delta[arm] = max(a - mean(arm), mean(arm) - b) Ig.sortBy { delta[it] } Q.addAll(Ig.drop(n[r + 1]).filter { mean(it) > b }) Ig = Ig.take(n[r + 1]).toMutableList() r++ } if (Q.size < m) Q.addAll(Ig) println("C,$K,$budget,${if (Q.sorted() == (0..m).toList()) 1 else 0},$cntWords") // println("time = $time") assert(time <= budget) return Q.sorted() } fun cmp(a: Pair<Double, Int>, b: Pair<Double, Int>) = when { a.first < b.first -> -1 a.first > b.first -> 1 a.second < b.first -> -1 a.second > b.second -> 1 else -> 0 } private fun order( m0: Int, I: Array<MutableList<Int>>, means: DoubleArray, K: Int ): Pair<Int, Int> { val left = IntArray(K) { 0 } val right = IntArray(K) { I[it].size } var cntWords = 0 var result = -1 var m: Int for (k in I.indices) { I[k].sortBy { means[it] } } while (I.indices.any { right[it] - left[it] > 1 }) { cntWords += K val arr = I.indices.map { i -> I[i][(left[i] + right[i]) / 2] }.map { Pair(means[it], it) }.withIndex() .toMutableList() .sortedWith { a, b -> when { a.value.first < b.value.first -> -1 a.value.first > b.value.first -> 1 a.value.second < b.value.first -> -1 a.value.second > b.value.second -> 1 else -> 0 } } var tmp = 0 m = m0 - left.sum() for (k in arr.indices) { val ss = (left[arr[k].index] + right[arr[k].index]) / 2 val size = ss - left[arr[k].index] if (tmp + size < m) { left[arr[k].index] = ss } else { right[arr[k].index] = ss } tmp += size } } cntWords += K val arr = I.indices.map { i -> I[i][(left[i] + right[i]) / 2] }.map { Pair(means[it], it) }.withIndex().toMutableList() .sortedWith { a, b -> when { a.value.first < b.value.first -> -1 a.value.first > b.value.first -> 1 a.value.second < b.value.first -> -1 a.value.second > b.value.second -> 1 else -> 0 } } var tmp = 0 var cnt = m0 - left.sum() for (k in arr.indices) { val ss = left[arr[k].index] if (cnt == 0) { result = arr[k].value.second break } cnt-- tmp += ss } assert(result != -1) return Pair(result, cntWords) }
0
Kotlin
0
0
f0dd06b07bf9ebc5bc199c5280e63103189f5397
9,819
collab-comm
MIT License
year2022/src/cz/veleto/aoc/year2022/Day18.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay import cz.veleto.aoc.core.Pos3 import cz.veleto.aoc.core.manhattanTo class Day18(config: Config) : AocDay(config) { override fun part1(): String { val cubes = parseCubes() return countExposedSides(cubes).toString() } override fun part2(): String { val cubes = parseCubes() val volume = Volume(cubes) val candidates = findPocketCandidates(volume, cubes) val pockets = demoteCandidatesBySpreadingAir(volume, cubes, candidates) return countExposedSides(cubes + pockets).toString() } private fun parseCubes(): List<Pos3> = input.map { line -> line.split(",") .map { it.toInt() } .let { (x, y, z) -> Pos3(x, y, z) } }.toList() private fun countExposedSides(cubes: List<Pos3>): Int { var exposedSides = 0 for (i in 0..cubes.lastIndex) { exposedSides += 6 for (j in i..cubes.lastIndex) { if (cubes[i].manhattanTo(cubes[j]) == 1) exposedSides -= 2 } } return exposedSides } private fun findPocketCandidates(volume: Volume, cubes: List<Pos3>) = buildList { for (x in volume.xRange) { for (y in volume.yRange) { for (z in volume.zRange) { val pos = Pos3(x, y, z) if (pos in cubes) continue val rays = raysFromPos(pos, volume) val isCandidate = rays.all { ray -> ray.any { it in cubes } } if (isCandidate) this += pos } } } } private fun demoteCandidatesBySpreadingAir(volume: Volume, cubes: List<Pos3>, candidates: List<Pos3>): List<Pos3> { var anyCandidateDemoted = true var keptCandidates = candidates while (anyCandidateDemoted) { anyCandidateDemoted = false for (x in volume.xRange) { for (y in volume.yRange) { for (z in volume.zRange) { val pos = Pos3(x, y, z) if (pos !in keptCandidates) continue val rays = raysFromPos(pos, volume) val candidateDemoted = rays.any { ray -> ray.takeWhile { it !in cubes }.any { it !in keptCandidates } } if (candidateDemoted) { keptCandidates = keptCandidates - pos anyCandidateDemoted = true } } } } } return keptCandidates } private fun raysFromPos(pos: Pos3, volume: Volume): Sequence<Sequence<Pos3>> { val (x, y, z) = pos return sequenceOf( sequence { for (rx in (volume.xRange.first..<x).reversed()) yield(Pos3(rx, y, z)) }, sequence { for (rx in x + 1..volume.xRange.last) yield(Pos3(rx, y, z)) }, sequence { for (ry in (volume.yRange.first..<y).reversed()) yield(Pos3(x, ry, z)) }, sequence { for (ry in y + 1..volume.yRange.last) yield(Pos3(x, ry, z)) }, sequence { for (rz in (volume.zRange.first..<z).reversed()) yield(Pos3(x, y, rz)) }, sequence { for (rz in z + 1..volume.zRange.last) yield(Pos3(x, y, rz)) }, ) } private class Volume(cubes: List<Pos3>) { val xRange = cubes.minOf { it.first }..cubes.maxOf { it.first } val yRange = cubes.minOf { it.second }..cubes.maxOf { it.second } val zRange = cubes.minOf { it.third }..cubes.maxOf { it.third } } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
3,742
advent-of-pavel
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2020/Day13.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.* import java.math.BigInteger /** * --- Day 13: --- * https://adventofcode.com/2020/day/13 */ class Day13 : Solver { override fun solve(lines: List<String>): Result { val earliestTime = lines[0].toLong() val busIds = lines[1].split(',').filter { it != "x" }.map { it.toLong() } return Result("${partA(earliestTime, busIds)}", "${partB(lines[1])}") } } /** Part A, when brute force still worked :-) */ fun partA(earliest: Long, busIds: List<Long>): Long { val times = MutableList(busIds.size) { 0L } var currentWinTime = Long.MAX_VALUE var currentWinBus = 0L while (times.min()!! <= earliest) { for (b in busIds.indices) { times[b] += busIds[b] if (times[b] > earliest) { val diff = times[b] - earliest if (diff < currentWinTime - earliest) { currentWinBus = busIds[b] currentWinTime = times[b] } } } } return currentWinBus * (currentWinTime - earliest) } /** * This is an implementation after I read about the problem and how to solve it * efficiently. * Note: Loosely based on Chinese Remainder Theorem. */ fun partB(data: String): Long { // Parse (offset -> busId/period) val busTimes = data.split(',').withIndex().filter { it.value != "x" }.map { Pair(it.index, it.value.toLong()) } // The current time point we are looking at. var currentTime = 0L // The step size will grow as a multiple of busIds. var stepSize = 1L // Go through all the buses... for ((offset, busId) in busTimes) { // Move forward in time until the current busId schedule lines up and a bus // departs (including offset)., while ((currentTime + offset) % busId != 0L) { currentTime += stepSize } // Now that we found it, we know we can move forward in multiples of this // busId multiplied with all other previously found busses. No need to check // any steps in between since we know they won't work. stepSize *= busId } return currentTime } // For prosperity: // This is the brute force solution I originally came up with. Works on the // demo inputs but it will run forever on the real input. Good to understand // the problem though. fun partB_BruteForce(data: String): BigInteger { val busIds = mutableListOf<BigInteger>() val positions = mutableListOf<BigInteger>() val diffs = mutableListOf<BigInteger>() // First, parse the input. val split = data.split(','); for (b in split.indices) { if (split[b] != "x") { busIds.add(split[b].toBigInteger()) positions.add(BigInteger.valueOf(b.toLong())) diffs.add(BigInteger.valueOf(b.toLong())) } } // We step through the schedule while (true) { // First lets check if all the buses are in the order we want them to be. // If so, we're done. var valid = true for (b in 1 until busIds.size) { if (positions[0].add(diffs[b]).mod(busIds[b]) != BigInteger.ZERO) { valid = false break } } if (valid) return positions[0] // Iterate bus positions. for (b in busIds.indices) { positions[b] = positions[b].add(busIds[b]) } } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
3,178
euler
Apache License 2.0
complex-numbers/src/main/kotlin/ComplexNumbers.kt
3mtee
98,672,009
false
null
import kotlin.math.* data class ComplexNumber(val real: Double = 0.0, val imag: Double = 0.0) { val abs = sqrt(real * real + imag * imag) operator fun plus(other: ComplexNumber): ComplexNumber { return ComplexNumber(this.real + other.real, this.imag + other.imag) } operator fun minus(other: ComplexNumber): ComplexNumber { return ComplexNumber(this.real - other.real, this.imag - other.imag) } operator fun times(other: ComplexNumber): ComplexNumber { val real = this.real * other.real - this.imag * other.imag val imag = this.real * other.imag + this.imag * other.real return ComplexNumber(real, imag) } operator fun div(other: ComplexNumber): ComplexNumber { val real = (this.real * other.real + this.imag * other.imag) / (other.real * other.real + other.imag * other.imag) val imag = (this.imag * other.real - this.real * other.imag) / (other.real * other.real + other.imag * other.imag) return ComplexNumber(real, imag) } fun conjugate(): ComplexNumber = ComplexNumber(this.real, -this.imag) } fun exponential(c: ComplexNumber): ComplexNumber = if (c.real == 0.0) { ComplexNumber(cos(c.imag), sin(c.imag)) } else { ComplexNumber(E.pow(c.real)) * exponential(ComplexNumber(imag = c.imag)) }
0
Kotlin
0
0
6e3eb88cf58d7f01af2236e8d4727f3cd5840065
1,338
exercism-kotlin
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem609/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem609 /** * LeetCode page: [609. Find Duplicate File in System](https://leetcode.com/problems/find-duplicate-file-in-system/); */ class Solution { /* Complexity: * Time O(NM) and Aux_Space O(NM) where N is size of paths and M is the average length of path; */ fun findDuplicate(paths: Array<String>): List<List<String>> { val directoryPerPathIndex = getDirectoryPerPathIndex(paths) val filesByContent = groupFilesByContent(paths, directoryPerPathIndex) return getFilePathsHavingDuplicateContent(filesByContent, directoryPerPathIndex) } private fun getDirectoryPerPathIndex(paths: Array<String>): Map<Int, String> { val group = hashMapOf<Int, String>() for ((index, path) in paths.withIndex()) { val directory = getDirectoryOfPath(path) group[index] = directory } return group } private fun getDirectoryOfPath(path: String): String { val directory = StringBuilder() var index = 0 while (index < path.length) { val char = path[index] if (char == ' ') break directory.append(char) index++ } return directory.toString() } private fun groupFilesByContent( paths: Array<String>, directoryPerPathIndex: Map<Int, String> ): Map<String, List<File>> { val group = hashMapOf<String, MutableList<File>>() for ((index, path) in paths.withIndex()) { val directory = directoryPerPathIndex[index] checkNotNull(directory) addFilesToFilesGroupByContent(path, index, directory.length, group) } return group } private data class File(val name: String, val pathIndex: Int) private fun addFilesToFilesGroupByContent( path: String, pathIndex: Int, directoryLength: Int, container: MutableMap<String, MutableList<File>> ) { var index = directoryLength + 1 val builder = StringBuilder() var fileName = "" while (index < path.length) { when (val char = path[index]) { ' ' -> builder.clear() '(' -> { fileName = builder.toString() builder.clear() } ')' -> { val content = builder.toString() val file = File(fileName, pathIndex) container .getOrPut(content) { mutableListOf() } .add(file) builder.clear() } else -> builder.append(char) } index++ } } private fun getFilePathsHavingDuplicateContent( contentToFiles: Map<String, List<File>>, directoryPerPathIndex: Map<Int, String> ): List<List<String>> { val container = mutableListOf<List<String>>() for ((_, files) in contentToFiles) { val hasDuplicate = files.size > 1 if (hasDuplicate) { val paths = getPathsOfFiles(files, directoryPerPathIndex) container.add(paths) } } return container } private fun getPathsOfFiles( files: List<File>, directoryPerPathIndex: Map<Int, String> ): List<String> { val paths = files.map { file -> val directory = directoryPerPathIndex[file.pathIndex] checkNotNull(directory) getPathOfFile(file, directory) } return paths } private fun getPathOfFile(file: File, directory: String): String { val pathLength = directory.length + 1 + file.name.length val path = StringBuilder(pathLength) .append(directory) .append("/") .append(file.name) return path.toString() } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
3,939
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day21.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.ints import se.saidaspen.aoc.util.words fun main() { Day21.run() } object Day21 : Day(2015, 21) { data class Player(var hp: Int, val dmg : Int, val armor: Int) data class Object(val name: String, val cost: Int, val dmg : Int, val armor: Int) val weapons = parseObjects("""Dagger 8 4 0 Shortsword 10 5 0 Warhammer 25 6 0 Longsword 40 7 0 Greataxe 74 8 0""") val armors = parseObjects("""NoArmor 0 0 0 Leather 13 0 1 Chainmail 31 0 2 Splintmail 53 0 3 Bandedmail 75 0 4 Platemail 102 0 5""") val rings = parseObjects("""NoRing1 0 0 0 NoRing2 0 0 0 Damage+1 25 1 0 Damage+2 50 2 0 Damage+3 100 3 0 Defense+1 20 0 1 Defense+2 40 0 2 Defense+3 80 0 3""") private fun parseObjects(s: String): List<Object> { return s.lines().map { words(it) }.map { Object(it[0], it[1].toInt(), it[2].toInt(), it[3].toInt())}.toList() } override fun part1(): Any { val wins = mutableMapOf<Int, String>() val bossHp = ints(input)[0] val bossDmg = ints(input)[1] val bossArmor = ints(input)[2] for (weapon in weapons) { for (armor in armors) { for (ringL in rings) { for (ringR in rings) { if (ringL == ringR) continue val cost = weapon.cost + armor.cost + ringL.cost + ringR.cost val boss = Player(bossHp, bossDmg, bossArmor) val player = Player( 100, weapon.dmg + armor.dmg + ringL.dmg + ringR.dmg, weapon.armor + armor.armor + ringL.armor + ringR.armor ) if (player == play(player, boss)) { wins[cost] = "$weapon, $armor, $ringL, $ringR" } } } } } return wins.minByOrNull { it.key }!!.key } private fun play(player: Player, boss: Player) : Player { var attacker = player var defender = boss while (true) { defender.hp -= (attacker.dmg - defender.armor).coerceAtLeast(1) if (defender.hp < 1) return attacker else { attacker = defender.also { defender = attacker } } } } override fun part2(): Any { val losses = mutableMapOf<Int, String>() val bossHp = ints(input)[0] val bossDmg = ints(input)[1] val bossArmor = ints(input)[2] for (weapon in weapons) { for (armor in armors) { for (ringL in rings) { for (ringR in rings) { if (ringL == ringR) continue val cost = weapon.cost + armor.cost + ringL.cost + ringR.cost val boss = Player(bossHp, bossDmg, bossArmor) val player = Player( 100, weapon.dmg + armor.dmg + ringL.dmg + ringR.dmg, weapon.armor + armor.armor + ringL.armor + ringR.armor ) if (boss == play(player, boss)) { losses[cost] = "$weapon, $armor, $ringL, $ringR" } } } } } return losses.maxByOrNull { it.key }!!.key } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
3,794
adventofkotlin
MIT License
day02/kotlin/RJPlog/day02_1_2.kt
mr-kaffee
720,687,812
false
{"Rust": 223627, "Kotlin": 46100, "Python": 39390, "Shell": 3369, "Haskell": 3122, "Dockerfile": 2236, "Gnuplot": 1678, "C++": 980, "HTML": 592, "CMake": 314}
import java.io.File fun cube(in1: Int): Int { var result = 0 File("day2302_puzzle_input.txt").forEachLine { var gamePossible = true var maxRed = 0 var maxGreen = 0 var maxBlue = 0 var instruction = it.split(": ") var game = instruction[0].substringAfter("Game ").toInt() var results = instruction[1].split("; ") results.forEach{ var colours = it.split(", ") colours.forEach{ if (it.contains("green")) { if (it.substringBefore(" green").toInt() > 13) { gamePossible = false } maxGreen = maxOf(maxGreen, it.substringBefore(" green").toInt()) } if (it.contains("red")) { if (it.substringBefore(" red").toInt() > 12) { gamePossible = false } maxRed = maxOf(maxRed, it.substringBefore(" red").toInt()) } if (it.contains("blue")) { if (it.substringBefore(" blue").toInt() > 14) { gamePossible = false } maxBlue = maxOf(maxBlue, it.substringBefore(" blue").toInt()) } } } if (in1 == 1) { if (gamePossible) result += game } else { result += maxRed * maxGreen * maxBlue } } return result } fun main() { var t1 = System.currentTimeMillis() var solution1 = cube(1) var solution2 = cube(2) // print solution for part 1 println("*******************************") println("--- Day 2: Cube Conundrum ---") println("*******************************") println("Solution for part1") println(" $solution1 is the sum of the IDs of those games") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 is the sum of the power of these sets") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
0
Rust
2
0
5cbd13d6bdcb2c8439879818a33867a99d58b02f
1,743
aoc-2023
MIT License
Kotlin/src/main/kotlin/StalinSort.kt
MeilCli
199,483,286
false
{"C#": 3661, "Kotlin": 1651, "Crystal": 1306}
fun main(args: Array<String>) { println("Hello Stalin!") writeStalinSort(intArrayOf(4)) writeStalinSort(intArrayOf(6, 2, 5, 7, 3, 8, 8, 4)) writeStalinSort(intArrayOf(5, 3, 7, 8, 9, 5, 3, 5, 7)) /** * Hello Stalin! * Input: 4 * StalinBy: 4 * StalinByDescending: 4 * Input: 6,2,5,7,3,8,8,4 * StalinBy: 6,7,8,8 * StalinByDescending: 6,2 * Input: 5,3,7,8,9,5,3,5,7 * StalinBy: 5,7,8,9 * StalinByDescending: 5,3,3 */ } private fun writeStalinSort(source: IntArray) { println("Input: ${source.joinToString(",")}") println("StalinBy: ${source.asSequence().stalinBy().joinToString(",")}") println("StalinByDescending: ${source.asSequence().stalinByDescending().joinToString(",")}") } fun <T> Sequence<T>.stalinBy(): List<T> where T : Comparable<T> { return stalinSort(this, false) } fun <T> Sequence<T>.stalinByDescending(): List<T> where T : Comparable<T> { return stalinSort(this, true) } private fun <T> stalinSort(source: Sequence<T>, descending: Boolean): List<T> where T : Comparable<T> { val iterator = source.iterator() val result = mutableListOf<T>() if (iterator.hasNext()) { var lastElement = iterator.next() result.add(lastElement) while (iterator.hasNext()) { val element = iterator.next() val compare = when (descending) { true -> element <= lastElement false -> lastElement <= element } if (compare) { result.add(element) lastElement = element } } } return result }
0
C#
0
0
b245390a856850ca79470a6ad1b31c980465a68a
1,651
StalinSort
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/PerfectSquares.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 dev.shtanko.algorithms.extensions.isSquare import dev.shtanko.algorithms.math.sqrt import java.util.LinkedList import java.util.Queue import kotlin.math.min /** * 279. Perfect Squares * @see <a href="https://leetcode.com/problems/perfect-squares/">Source</a> */ fun interface PerfectSquares { operator fun invoke(num: Int): Int } /** * Dynamic Programming */ class PerfectSquaresDP : PerfectSquares { override fun invoke(num: Int): Int { val list: MutableList<Int> = ArrayList() var temp = 1 while (temp * temp <= num) { val square = temp * temp if (num == square) { return 1 } list.add(square) temp += 1 } val dp = IntArray(num + 1) dp[0] = 0 for (i in 1 until dp.size) { dp[i] = Int.MAX_VALUE for (j in 0 until list.size) { if (i - list[j] >= 0 && dp[i - list[j]] != Int.MAX_VALUE && dp[i] > dp[i - list[j]] + 1) { dp[i] = dp[i - list[j]] + 1 } } } return if (dp[num] == Int.MAX_VALUE) -1 else dp[num] } } /** * Static Dynamic Programming */ class PerfectSquaresStaticDP : PerfectSquares { override fun invoke(num: Int): Int { val result: MutableList<Int> = ArrayList() if (result.isEmpty()) { result.add(0) } while (result.size <= num) { val m: Int = result.size var tempMin = Int.MAX_VALUE var j = 1 while (j * j <= m) { tempMin = min(tempMin, result[m - j * j] + 1) j++ } result.add(tempMin) } return result[num] } } /** * Mathematical Solution */ class PerfectSquaresMath : PerfectSquares { override fun invoke(num: Int): Int { var remainingNumber = num if (remainingNumber.isSquare()) return 1 // The result is 4 if and only if n can be written in the // form of 4^k*(8*m + 7). Please refer to // Legendre's three-square theorem. while (remainingNumber and 3 == 0) { remainingNumber = remainingNumber shr 2 } if (remainingNumber and 7 == 7) { return 4 } // Check whether 2 is the result. val sqrtRemainingNumber = sqrt(remainingNumber).toInt() for (i in 1..sqrtRemainingNumber) { if ((remainingNumber - i * i).isSquare()) { return 2 } } return 3 } } /** * Breadth-First Search */ class PerfectSquaresBFS : PerfectSquares { override fun invoke(num: Int): Int { val queue: Queue<Int> = LinkedList() val visited: MutableSet<Int> = HashSet() queue.offer(0) visited.add(0) var depth = 0 while (queue.isNotEmpty()) { depth++ val levelSize = queue.size processLevel(queue, visited, levelSize, num, depth)?.let { return it } } return depth } private fun processLevel(queue: Queue<Int>, visited: MutableSet<Int>, levelSize: Int, num: Int, depth: Int): Int? { repeat(levelSize) { val current = queue.poll() var i = 1 while (i * i <= num) { val next = current + i * i if (next == num) { return depth } if (next > num) { break } if (!visited.contains(next)) { queue.offer(next) visited.add(next) } i++ } } return null } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,389
kotlab
Apache License 2.0
src/main/kotlin/me/circuitrcay/euler/challenges/oneToTwentyFive/Problem11.kt
adamint
134,989,381
false
null
package me.circuitrcay.euler.challenges.oneToTwentyFive import me.circuitrcay.euler.Problem class Problem11 : Problem<String>() { override fun calculate(): Any { val prompt = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48""".replace("\n", " ").split(" ") var max = 0L for (x in 0..(prompt.size - 1)) getValidPossibilities(x, prompt).forEach { if (it > max) max = it } return max } private fun getValidPossibilities(index: Int, prompt: List<String>): List<Long> { val results = mutableListOf<Long>() // diagonal RIGHT if (index % 20 <= 16 && index / 20 >= 3 && index / 20 <= 16) { results.add(prompt[index].toLong() * prompt[index - 19].toLong() * prompt[index - 19 - 19].toLong() * prompt[index - 19 - 19 - 19].toLong()) results.add(prompt[index].toLong() * prompt[index + 21].toLong() * prompt[index + 21 + 21].toLong() * prompt[index + 21 + 21 + 21].toLong()) // diagonal LEFT results.add(prompt[index].toLong() * prompt[index - 21].toLong() * prompt[index - 21 - 21].toLong() * prompt[index - 21 - 21].toLong()) results.add(prompt[index].toLong() * prompt[index + 19].toLong() * prompt[index + 19 + 19].toLong() * prompt[index + 19 + 19 + 19].toLong()) } // horizontal if (index % 20 >= 3) results.add(prompt[index].toLong() * prompt[index - 1].toLong() * prompt[index - 2].toLong() * prompt[index - 3].toLong()) if (index % 20 <= 16) results.add(prompt[index].toLong() * prompt[index + 1].toLong() * prompt[index + 2].toLong() * prompt[index + 3].toLong()) // vertical if (index / 20 >= 3) results.add(prompt[index].toLong() * prompt[index - 20].toLong() * prompt[index - 40].toLong() * prompt[index - 60].toLong()) if (index / 20 <= 16) results.add(prompt[index].toLong() * prompt[index + 20].toLong() * prompt[index + 40].toLong() * prompt[index + 60].toLong()) return results } }
0
Kotlin
0
0
cebe96422207000718dbee46dce92fb332118665
3,366
project-euler-kotlin
Apache License 2.0
src/Day16.kt
dragere
440,914,403
false
{"Kotlin": 62581}
fun main() { class Packet(val s: String) { val version: Int = s.substring(0, 3).toInt(2) val type: Int = s.substring(3, 6).toInt(2) val subPackets: List<Packet> val value: Long val leftOver: String init { if (type != 4) { value = 0 val lengthType = if (s[6] == '0') 22 else 18 var leng = s.substring(7, lengthType).toInt(2) if (lengthType == 22) { leng += lengthType leftOver = s.substring(leng) var subStr = s.substring(lengthType, leng) val tmp = mutableListOf<Packet>() while (subStr.isNotEmpty()) { tmp.add(Packet(subStr)) subStr = tmp.last().leftOver } subPackets = tmp.toList() } else { var subStr = s.substring(lengthType) val tmp = mutableListOf<Packet>() var i = 0 while (i < leng) { tmp.add(Packet(subStr)) subStr = tmp.last().leftOver i++ } leftOver = subStr subPackets = tmp.toList() } } else { subPackets = listOf() var o = "" var i = 6 while (true) { o += s.substring(i + 1, i + 5) i += 5 if (s[i - 5] == '0') break } value = o.toLong(2) // i -= 6 // leftOver = s.substring((if (i % 4 == 0) i else 4 - i % 4 + i)+6) leftOver = s.substring(i) } } fun versionSum(): Int = version + subPackets.sumOf { it.versionSum() } fun calcVal(): Long { return when (type) { 0 -> subPackets.sumOf { it.calcVal() } 1 -> subPackets.map { it.calcVal() }.reduce { acc, i -> acc * i } 2 -> subPackets.minOf { it.calcVal() } 3 -> subPackets.maxOf { it.calcVal() } 4 -> value 5 -> if (subPackets[0].calcVal() > subPackets[1].calcVal()) 1 else 0 6 -> if (subPackets[0].calcVal() < subPackets[1].calcVal()) 1 else 0 7 -> if (subPackets[0].calcVal() == subPackets[1].calcVal()) 1 else 0 else -> 0 } } override fun hashCode(): Int { return s.hashCode() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Packet if (s != other.s) return false return true } override fun toString(): String { return "P<V$version,T$type>(${if (type != 4) subPackets.toString() else value})" } } fun part1(input: Packet): Int { return input.versionSum() } fun part2(input: Packet): Long { // println(tmp.joinToString { it.reversed().toString() + "\n" }) return input.calcVal() } fun preprocessing(input: String): Packet { return Packet(input.map { when (it) { '0' -> "0000" '1' -> "0001" '2' -> "0010" '3' -> "0011" '4' -> "0100" '5' -> "0101" '6' -> "0110" '7' -> "0111" '8' -> "1000" '9' -> "1001" 'A' -> "1010" 'B' -> "1011" 'C' -> "1100" 'D' -> "1101" 'E' -> "1110" 'F' -> "1111" else -> "" } }.joinToString("")) } val realInp = read_testInput("real16") // val testInp = read_testInput("test16") val testInp = "880086C3E88112" // println(preprocessing(testInp)) // println("Test 1: ${part1(preprocessing(testInp))}") // println("Real 1: ${part1(preprocessing(realInp))}") // println("-----------") println("Test 2: ${part2(preprocessing(testInp))}") println("Real 2: ${part2(preprocessing(realInp))}") }
0
Kotlin
0
0
3e33ab078f8f5413fa659ec6c169cd2f99d0b374
4,400
advent_of_code21_kotlin
Apache License 2.0
src/main/kotlin/dev/schlaubi/aoc/days/Day2.kt
DRSchlaubi
573,014,474
false
{"Kotlin": 21541}
package dev.schlaubi.aoc.days import dev.schlaubi.aoc.SeparateDay import kotlin.io.path.readLines object Day2 : SeparateDay() { override val number: Int = 2 override fun task1(): Any { return input.readLines() .map { val (opponent, you) = it.split(" ") GameItem.fromLetter(opponent[0]) to GameItem.fromLetter(you[0]) }.score() } override fun task2(): Any { return input.readLines() .map { val (opponent, winType) = it.split(" ") val opponentItem = GameItem.fromLetter(opponent[0]) val item = when (winType[0]) { 'X' -> GameItem.items.first { item -> opponentItem.beats(item) } 'Y' -> opponentItem 'Z' -> GameItem.items.first { item -> item.beats(opponentItem) } else -> error("Invalid letter: $winType") } opponentItem to item }.score() } private fun List<Pair<GameItem, GameItem>>.score() = sumOf { (opponent, you) -> val winnerScore = when { opponent == you -> 3 you.beats(opponent) -> 6 else -> 0 } winnerScore + you.score } } sealed interface GameItem { val score: Int fun beats(other: GameItem): Boolean object Rock : GameItem { override val score: Int = 1 override fun beats(other: GameItem): Boolean = other == Scissors } object Paper : GameItem { override val score: Int = 2 override fun beats(other: GameItem): Boolean = other == Rock } object Scissors : GameItem { override val score: Int = 3 override fun beats(other: GameItem): Boolean = other == Paper } companion object { val items = listOf(Rock, Paper, Scissors) fun fromLetter(letter: Char) = when (letter) { 'A', 'X' -> Rock 'B', 'Y' -> Paper 'C', 'Z' -> Scissors else -> error("Unknown letter: $letter") } } }
1
Kotlin
0
4
4514e4ac86dd3ed480afa907d907e3ae26457bba
2,153
aoc-2022
MIT License
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day01/Trebuchet.kt
Gentleman1983
737,309,232
false
{"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319}
package de.havox_design.aoc2023.day01 class Trebuchet(private var filename: String) { private val words = listOf( Digit("zero", "0"), Digit("one", "1"), Digit("two", "2"), Digit("three", "3"), Digit("four", "4"), Digit("five", "5"), Digit("six", "6"), Digit("seven", "7"), Digit("eight", "8"), Digit("nine", "9"), Digit("0", "0"), Digit("1", "1"), Digit("2", "2"), Digit("3", "3"), Digit("4", "4"), Digit("5", "5"), Digit("6", "6"), Digit("7", "7"), Digit("8", "8"), Digit("9", "9") ) fun solvePart1(): Long { val payloads = getResourceAsText(filename) var calibrationValue = 0L for(payload:String in payloads) { val numbers = payload .chars() .mapToObj { c -> c.toChar() } .filter(Char::isDigit) .mapToInt { c -> c.digitToInt() } .toArray() .toList() val firstNumber = numbers.first() val lastNumber = numbers.last() val currentCalibrationValue = firstNumber * 10 + lastNumber calibrationValue += currentCalibrationValue } return calibrationValue } fun solvePart2(): Long = getResourceAsText(filename) .sumOf { row -> replaceDigitWordsSmart(row) } private fun replaceDigitWordsSmart(row: String): Long { val firstDigit: String val lastDigit: String val wordPositions = words .flatMap { digit -> getDigitIndices(row, digit) } .filter { pos -> pos.position != -1 } .sortedBy { pos -> pos.position } if (wordPositions.isEmpty()) { return 0 } firstDigit = wordPositions .first() .digit .value lastDigit = wordPositions .last() .digit .value return (firstDigit + lastDigit) .toLong() } private fun getDigitIndices(input: String, digit: Digit): Set<DigitPosition> { val indices = ArrayList<Int>() var index: Int = input .indexOf(digit.word) while (index >= 0) { indices.add(index) index = input .indexOf(digit.word, index + 1) } return indices .map { DigitPosition(digit, it) } .toSet() } private fun getResourceAsText(path: String): List<String> = this .javaClass .classLoader .getResourceAsStream(path)!! .bufferedReader() .readLines() }
4
Kotlin
0
1
35ce3f13415f6bb515bd510a1f540ebd0c3afb04
2,747
advent-of-code
Apache License 2.0
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day16/Day16Puzzle.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day16 import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver abstract class Day16Puzzle : PuzzleSolver { companion object { private val hexToBits = mapOf( '0' to "0000", '1' to "0001", '2' to "0010", '3' to "0011", '4' to "0100", '5' to "0101", '6' to "0110", '7' to "0111", '8' to "1000", '9' to "1001", 'A' to "1010", 'B' to "1011", 'C' to "1100", 'D' to "1101", 'E' to "1110", 'F' to "1111", ).mapValues { it.value.toList() } } final override fun solve(inputLines: Sequence<String>) = solve(parseTransmissionHex(inputLines.first())).toString() abstract fun solve(outerPacket: Packet): Long private fun parseTransmissionHex(transmissionHex: String) = transmissionHex .flatMap { hexToBits[it] ?: emptyList() } .asReversed() .let { ArrayDeque(it) } .let { parsePacket(it) } private fun parsePacket(bits: ArrayDeque<Char>): Packet { val version = bits.nNextBitsToInt(3) val typeId = bits.nNextBitsToInt(3) return if (typeId == Packet.LITERAL_VALUE) { Packet.LiteralValue(version, parseLiteralValue(bits)) } else { parseOperator(version, typeId, bits) } } private fun parseLiteralValue(bits: ArrayDeque<Char>): Long { var value = "" var lastBlock = false; while (!lastBlock) { lastBlock = bits.removeLast() == '0' value += bits.nNextBits(4) } return value.toLong(2) } private fun parseOperator(version: Int, typeId: Int, bits: ArrayDeque<Char>): Packet { val lengthTypeId = bits.removeLast() val subPackets = if (lengthTypeId == '0') { val totalSubPacketLength = bits.nNextBitsToInt(15) val subPacketBits = ArrayDeque<Char>() repeat(totalSubPacketLength) { subPacketBits.addFirst(bits.removeLast()) } val subPackets = mutableListOf<Packet>() while (subPacketBits.isNotEmpty()) { subPackets += parsePacket(subPacketBits) } subPackets } else { val numberOfSubPackets = bits.nNextBitsToInt(11) val subPackets = mutableListOf<Packet>() while (subPackets.size < numberOfSubPackets) { subPackets += parsePacket(bits) } subPackets } return toOperator(version, typeId, subPackets) } private fun toOperator(version: Int, typeId: Int, subPackets: List<Packet>): Packet = when (typeId) { 0 -> Packet.Sum(version, subPackets) 1 -> Packet.Product(version, subPackets) 2 -> Packet.Minimum(version, subPackets) 3 -> Packet.Maximum(version, subPackets) 5 -> Packet.GreaterThan(version, subPackets) 6 -> Packet.LessThan(version, subPackets) 7 -> Packet.EqualTo(version, subPackets) else -> throw IllegalArgumentException("Unknown operator typeId: $typeId") } private fun ArrayDeque<Char>.nNextBitsToInt(n: Int) = nNextBits(n).toInt(2) private fun ArrayDeque<Char>.nNextBits(n: Int) = (0 until n).fold("") { binary, _ -> binary + removeLast() } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
3,426
AdventOfCode2021
Apache License 2.0
kotlin/2022/round-1b/3/src/main/kotlin/Solution.kt
ShreckYe
345,946,821
false
null
import kotlin.experimental.xor import kotlin.system.exitProcess fun main() { val equivalentClasses = findEquivalentClasses() val graph = buildGraph(equivalentClasses, getECIndexArray(equivalentClasses)) println(graph) val bests = computeBests(equivalentClasses, graph) println(bests) /*val t = readLine()!!.toInt() repeat(t, ::testCase)*/ } fun testCase(ti: Int) { repeat(300) { println("01010101") val nn = readLine()!!.toInt() if (nn == 0) return if (nn == -1) exitProcess(0) } } infix fun Byte.isEquivalentTo(that: Byte) = (0 until 8).any { rotateRight(it) == that } fun findEquivalentClasses(): List<List<Byte>> { val equivalentClasses = mutableListOf<MutableList<Byte>>() for (bInt in Byte.MIN_VALUE..Byte.MAX_VALUE) { val b = bInt.toByte() val equivalentClass = equivalentClasses.find { equivalentClass -> equivalentClass.first() isEquivalentTo b } if (equivalentClass !== null) equivalentClass.add(b) else equivalentClasses.add(mutableListOf(b)) } return equivalentClasses } fun getECIndexArray(equivalentClasses: List<List<Byte>>): IntArray { val array = IntArray(256) for ((i, equivalentClass) in equivalentClasses.withIndex()) for (b in equivalentClass) array[b.toUByte().toInt()] = i return array } data class OutXorEdges(/*val xorIndex : Int,*/ val outs: Set<Int>) fun buildGraph(equivalentClasses: List<List<Byte>>, ecIndexArray: IntArray): List<List<OutXorEdges>> = equivalentClasses.map { val v = it.first() equivalentClasses.map { val xorRight = it.first() OutXorEdges((0 until 8).map { val result = (v xor (xorRight.rotateRight(it))) ecIndexArray[result.toUByte().toInt()] }.toSet()) } } data class BestEdgeAndDepth(val xorRightECIndex: Int, val depth: Int) fun computeBests(equivalentClasses: List<List<Byte>>, graph: List<List<OutXorEdges>>): List<BestEdgeAndDepth> { val size = graph.size val cache = MutableList<BestEdgeAndDepth?>(size) { null } val zeroV = equivalentClasses.indexOf(listOf(0)) println("zeroV:" + zeroV) cache[zeroV] = BestEdgeAndDepth(-1, 0) for (v in 0 until size) dfsBest(graph, v, cache) return cache.map { it!! } } fun dfsBest( graph: List<List<OutXorEdges>>, v: Int, cache: MutableList<BestEdgeAndDepth?>, searched: BooleanArray ): BestEdgeAndDepth = run { println(v) if (cache[v] !== null) cache[v]!! else { val bestOut = graph[v].map { it.outs.maxOf { out -> dfsBest(graph, out, cache).depth } }.withIndex().minByOrNull { it.value }!! val best = BestEdgeAndDepth(bestOut.index, bestOut.value) cache[v] = best best } }
0
Kotlin
1
1
743540a46ec157a6f2ddb4de806a69e5126f10ad
2,947
google-code-jam
MIT License
kotlin/structures/HeavyLight.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package structures import java.util.ArrayList // Heavy-light decomposition with path queries. Query complexity is O(log^2(n)). // Based on the code from http://codeforces.com/blog/entry/22072 class HeavyLight(tree: Array<List<Integer>>, valuesOnVertices: Boolean) { var tree: Array<List<Integer>> var valuesOnVertices // true - values on vertices, false - values on edges : Boolean var segmentTree: SegmentTree var parent: IntArray var depth: IntArray var pathRoot: IntArray var `in`: IntArray var time = 0 fun dfs1(u: Int): Int { var size = 1 var maxSubtree = 0 for (i in 0 until tree[u].size()) { val v: Int = tree[u][i] if (v == parent[u]) continue parent[v] = u depth[v] = depth[u] + 1 val subtree = dfs1(v) if (maxSubtree < subtree) { maxSubtree = subtree tree[u].set(i, tree[u].set(0, v)) } size += subtree } return size } fun dfs2(u: Int) { `in`[u] = time++ for (v in tree[u]) { if (v == parent[u]) continue pathRoot[v] = if (v == tree[u][0]) pathRoot[u] else v dfs2(v) } } operator fun get(u: Int, v: Int): SegmentTree.Node { val res: Array<SegmentTree.Node> = arrayOf<SegmentTree.Node>(Node()) processPath( u, v, BiConsumer<Integer, Integer> { a, b -> res[0] = SegmentTree.unite(res[0], segmentTree.get(a, b)) }) return res[0] } fun modify(u: Int, v: Int, delta: Long) { processPath(u, v, BiConsumer<Integer, Integer> { a, b -> segmentTree.modify(a, b, delta) }) } fun processPath(u: Int, v: Int, op: BiConsumer<Integer?, Integer?>) { var u = u var v = v while (pathRoot[u] != pathRoot[v]) { if (depth[pathRoot[u]] > depth[pathRoot[v]]) { val t = u u = v v = t } op.accept(`in`[pathRoot[v]], `in`[v]) v = parent[pathRoot[v]] } if (u != v || valuesOnVertices) op.accept( Math.min(`in`[u], `in`[v]) + if (valuesOnVertices) 0 else 1, Math.max( `in`[u], `in`[v] ) ) } companion object { // Usage example fun main(args: Array<String?>?) { val tree: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(5).toArray { _Dummy_.__Array__() } tree[0].add(1) tree[1].add(0) tree[0].add(2) tree[2].add(0) tree[1].add(3) tree[3].add(1) tree[1].add(4) tree[4].add(1) val hlV = HeavyLight(tree, true) hlV.modify(3, 2, 1) hlV.modify(1, 0, -1) System.out.println(1 == hlV[4, 2].sum) val hlE = HeavyLight(tree, false) hlE.modify(3, 2, 1) hlE.modify(1, 0, -1) System.out.println(1 == hlE[4, 2].sum) } } init { this.tree = tree this.valuesOnVertices = valuesOnVertices val n = tree.size segmentTree = SegmentTree(n) parent = IntArray(n) depth = IntArray(n) pathRoot = IntArray(n) `in` = IntArray(n) parent[0] = -1 dfs1(0) dfs2(0) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
3,434
codelibrary
The Unlicense
src/main/kotlin/Day11.kt
dlew
75,886,947
false
null
import java.util.* class Day11 { enum class Type { GENERATOR, MICROCHIP } enum class Element { HYDROGEN, LITHIUM, STRONTIUM, PLUTONIUM, THULIUM, RUTHENIUM, CURIUM, ELERIUM, DILITHIUM } data class Item(val type: Type, val element: Element) { override fun toString() = "${element.name[0]}${type.name[0]}" } data class State(val floors: List<Set<Item>>, val elevator: Int) { fun withMove(item: Item, from: Int, to: Int): State { val mutableFloors = floors.toMutableList() mutableFloors[from] = mutableFloors[from] - item mutableFloors[to] = mutableFloors[to] + item return State(mutableFloors, elevator) } fun withMoves(items: Collection<Item>, from: Int, to: Int): State { val mutableFloors = floors.toMutableList() mutableFloors[from] = mutableFloors[from] - items mutableFloors[to] = mutableFloors[to] + items return State(mutableFloors, elevator) } fun withElevator(floor: Int) = State(floors, floor) fun isSolved() = floors.take(floors.size - 1).filter { it.isNotEmpty() }.isEmpty() fun validFloor(floor: Int) = validFloor(floors[floor]) private fun validFloor(floor: Set<Item>): Boolean { // No generators == valid floor, guaranteed if (floor.filter { it.type == Type.GENERATOR }.isEmpty()) { return true } // Every item is either a generator OR each microchip has its generator present return floor.fold(true, { valid, item -> valid && (item.type == Type.GENERATOR || floor.contains(Item(Type.GENERATOR, item.element))) }) } override fun toString() = floors .mapIndexed { num, floor -> val sb = StringBuilder("F${num + 1} ") sb.append(if (elevator == num) "E " else " ") floor.forEach { sb.append(it.toString() + " ") } sb.toString() } .reversed() .joinToString("\n") } companion object { fun solve(initialState: State): Int { // Keep track of each state we've visited (so we don't visit a state twice) val visited = HashSet<State>() visited += initialState // Keep track of which states we can reach in X # of steps var statesAtLastStep = listOf(initialState) var step = 1 while (true) { println("${step}: Visited ${visited.size}, expanding ${statesAtLastStep.size}") val start = System.currentTimeMillis() // Generate all possible next steps (that are valid and haven't already been investigated) val possibilities = statesAtLastStep .flatMap { generatePossibilities(it) } .toSet() .filter { !visited.contains(it) } // Check if we found a solution possibilities.filter { it.isSolved() }.firstOrNull()?.let { return step } // Keep track of all the states we've visited already visited.addAll(possibilities) // Update state for next cycle statesAtLastStep = possibilities step++ // Metrics val end = System.currentTimeMillis() println("Time taken: ${end - start}ms") } } private fun generatePossibilities(state: State): List<State> { val elevator = state.elevator val moveOne = state.floors[elevator] val moveTwo = combine2(state.floors[state.elevator]) val possibilities = ArrayList<State>((moveOne.size + moveTwo.size) * 2) // Moving items up if (elevator < state.floors.size - 1) { val newState = state.withElevator(elevator + 1) // Move one up possibilities += moveOne.map { item -> newState.withMove(item, elevator, elevator + 1) } .filter { it.validFloor(elevator) && it.validFloor(elevator + 1) } // Move two up (if there are two) possibilities += moveTwo.map { items -> newState.withMoves(items, elevator, elevator + 1) } .filter { it.validFloor(elevator) && it.validFloor(elevator + 1) } } // Moving items down if (elevator > 0) { val newState = state.withElevator(elevator - 1) // Move one down possibilities += moveOne.map { item -> newState.withMove(item, elevator, elevator - 1) } .filter { it.validFloor(elevator) && it.validFloor(elevator - 1) } // Move two down (if there are two) possibilities += moveTwo.map { items -> newState.withMoves(items, elevator, elevator - 1) } .filter { it.validFloor(elevator) && it.validFloor(elevator - 1) } } return possibilities } // Optimized combination algorithm that finds all 2-combinations of a set fun <T> combine2(items: Set<T>): List<Set<T>> { val size = items.size if (size < 2) { return emptyList() } if (size == 2) { return listOf(items) } val itemsList = items.toList() val combinations = ArrayList<Set<T>>() (0..size - 2).forEach { index -> (index + 1..size - 1).forEach { index2 -> combinations += setOf(itemsList[index], itemsList[index2]) } } return combinations } } }
0
Kotlin
2
12
527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd
5,215
aoc-2016
MIT License
src/main/kotlin/com/rtarita/days/Day2.kt
RaphaelTarita
570,100,357
false
{"Kotlin": 79822}
package com.rtarita.days import com.rtarita.structure.AoCDay import com.rtarita.util.day import kotlinx.datetime.LocalDate object Day2 : AoCDay { private enum class Play(val opponentLetter: Char, val ownLetter: Char, val value: Int) { ROCK('X', 'A', 1), PAPER('Y', 'B', 2), SCISSORS('Z', 'C', 3); // use lazy because values() might not be available yet val losing by lazy { values()[(ordinal + 2) % values().size] } val drawing = this val winning by lazy { values()[(ordinal + 1) % values().size] } companion object { fun fromString(play: String): Play { val playChar = play.first() for (option in values()) { if (option.opponentLetter == playChar || option.ownLetter == playChar) { return option } } error("not a valid play: $play") } } } private enum class Outcome(val letter: Char, val value: Int) { LOSS('X', 0), DRAW('Y', 3), WIN('Z', 6); companion object { fun fromString(str: String): Outcome { val char = str.first() for (option in values()) { if (option.letter == char) { return option } } error("not a valid outcome: $str") } } } override val day: LocalDate = day(2) private fun evaluate(opponentPlay: Play, ownPlay: Play): Outcome { return when (ownPlay) { opponentPlay.losing -> Outcome.LOSS opponentPlay.drawing -> Outcome.DRAW opponentPlay.winning -> Outcome.WIN else -> error("not a valid round") } } private fun getOwnMove(opponentPlay: Play, outcome: Outcome): Play { return when (outcome) { Outcome.LOSS -> opponentPlay.losing Outcome.DRAW -> opponentPlay.drawing Outcome.WIN -> opponentPlay.winning } } private fun getInputSplit(from: String): Sequence<List<String>> { return from.lineSequence() .map { it.split(" ") } } override fun executePart1(input: String): Int { return getInputSplit(input).map { (a, b) -> Play.fromString(a) to Play.fromString(b) } .sumOf { (opponent, you) -> you.value + evaluate(opponent, you).value } } override fun executePart2(input: String): Int { return getInputSplit(input).map { (a, b) -> Play.fromString(a) to Outcome.fromString(b) } .sumOf { (opponent, outcome) -> getOwnMove(opponent, outcome).value + outcome.value } } }
0
Kotlin
0
9
491923041fc7051f289775ac62ceadf50e2f0fbe
2,741
AoC-2022
Apache License 2.0
src/Day15.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
import kotlin.math.absoluteValue import kotlin.math.sign fun Point.manhattanDistance(other: Point) = (x - other.x).absoluteValue + (y - other.y).absoluteValue class Beacon(val location: Point) { val tuningFrequency = 4000000L * location.x + location.y override fun toString() = "Beacon(x=${location.x}, y=${location.y})" } class Sensor(val location: Point, val beacon: Beacon) { val range = location.manhattanDistance(beacon.location) fun intersection(y: Int): IntRange { val distance = (location.y - y).absoluteValue if (distance > range) { return IntRange.EMPTY } val difference = range - distance val min = location.x - difference val max = location.x + difference return min..max } fun withinRange(point: Point) = location.manhattanDistance(point) <= range fun frontier(): List<DiagonalLine> { val frontierPoints = listOf( Point(location.x + range + 1, location.y), Point(location.x, location.y + range + 1), Point(location.x - range - 1, location.y), Point(location.x, location.y - range - 1), Point(location.x + range + 1, location.y), // Duplicating the first point makes next loop easier ) return frontierPoints .windowed(2) .map { (a, b) -> DiagonalLine(a, b) } } override fun toString() = "Sensor($location, $beacon, range=$range)" } class DiagonalLine(val start: Point, val end: Point) { val direction = Point( (end.x - start.x).sign, (end.y - start.y).sign, ) val length = start.manhattanDistance(end) private val parity = (start.x + start.y) % 2 fun parallel(other: DiagonalLine) = direction == other.direction fun antiparallel(other: DiagonalLine) = direction == -other.direction fun intersection(other: DiagonalLine): Point? { if (parity != other.parity) { return null } else if (parallel(other)) { if (start == other.end) { return start } else if (end == other.start) { return end } } else if (antiparallel(other)) { if (start == other.start) { return start } else if (end == other.end) { return end } } val (a, b) = start val (c, d) = other.start val sign = if (direction.x == direction.y) { 1 } else { -1 } val m = ((c - a) + sign * (d - b)) / (direction.x + sign * direction.y) if (m in 0..length) { return start + (direction * m) } return null } } fun unavailablePositions(sensors: List<Sensor>, y: Int): Set<Int> = buildSet { sensors.forEach { addAll(it.intersection(y)) if (it.beacon.location.y == y) { remove(it.beacon.location.x) } } } fun findBeacon(sensors: List<Sensor>, bounds: PointRegion): Beacon? { sensors.forEachIndexed { index, sensorA -> val frontierA: List<DiagonalLine> = sensorA.frontier() sensors.drop(index + 1).forEach { sensorB -> val frontierB: List<DiagonalLine> = sensorB.frontier() val intersectionPoints = buildList { frontierA.forEach { lineA -> frontierB.forEach { lineB -> lineA.intersection(lineB)?.let(::add) } } } intersectionPoints.firstOrNull { point -> point in bounds && sensors.all { !it.withinRange(point) } }?.let { return Beacon(it) } } } return null } fun main() { val sensors = readInput("Day15") .parseAllInts() .map { (x, y, bX, bY) -> Sensor(Point(x, y), Beacon(Point(bX, bY))) } val unavailable = unavailablePositions(sensors, 2000000) println(unavailable.size) val distressBeacon = findBeacon(sensors, PointRegion(4000000, 4000000)) println(distressBeacon?.tuningFrequency) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
4,148
advent-of-code-2022
Apache License 2.0
src/main/kotlin/ca/kiaira/advent2023/day1/Day1.kt
kiairatech
728,913,965
false
{"Kotlin": 78110}
package ca.kiaira.advent2023.day1 import ca.kiaira.advent2023.Puzzle /** * Day1 object represents the puzzle for Advent of Code Day 1. * It extends the Puzzle class with a list of strings as input data. * * @constructor Creates a Day1 object with the puzzle number 1. * * @author <NAME> * @since December 10th, 2023 */ object Day1 : Puzzle<List<String>>(1) { // Mapping of spelled-out digits to their corresponding numerical values private val digitsMap = 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 ) /** * Parses the input data for the Day1 puzzle. * * @param input A sequence of strings representing the puzzle input. * @return A list of strings containing the parsed input data. */ override fun parse(input: Sequence<String>): List<String> = input.toList() /** * Solves Part 1 of the Day1 puzzle. * * @param input The parsed input data as a list of strings. * @return The solution to Part 1 of the puzzle. */ override fun solvePart1(input: List<String>): Any { return input.sumOf { line -> val first = line.first(Char::isDigit) val last = line.last(Char::isDigit) "$first$last".toInt() } } /** * Solves Part 2 of the Day1 puzzle. * * @param input The parsed input data as a list of strings. * @return The solution to Part 2 of the puzzle. */ override fun solvePart2(input: List<String>): Any { return input.sumOf { line -> val digits = mutableListOf<Int>() var temp = line while (temp.isNotEmpty()) { if (temp.first().isDigit()) { digits += temp.first().digitToInt() } else { digitsMap.forEach { (k, v) -> if (temp.startsWith(k)) { digits += v return@forEach } } } temp = temp.drop(1) } digits.first() * 10 + digits.last() } } }
0
Kotlin
0
1
27ec8fe5ddef65934ae5577bbc86353d3a52bf89
1,895
kAdvent-2023
Apache License 2.0
src/main/kotlin/g1201_1300/s1219_path_with_maximum_gold/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1201_1300.s1219_path_with_maximum_gold // #Medium #Array #Matrix #Backtracking #2023_06_09_Time_238_ms_(100.00%)_Space_34.3_MB_(100.00%) class Solution { private var maxGold = 0 fun getMaximumGold(grid: Array<IntArray>): Int { for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] != 0) { val g = grid[i][j] grid[i][j] = 0 gold(grid, i, j, g) grid[i][j] = g } } } return maxGold } private fun gold(grid: Array<IntArray>, row: Int, col: Int, gold: Int) { if (gold > maxGold) { maxGold = gold } if (row > 0 && grid[row - 1][col] != 0) { val currGold = grid[row - 1][col] grid[row - 1][col] = 0 gold(grid, row - 1, col, gold + currGold) grid[row - 1][col] = currGold } if (col > 0 && grid[row][col - 1] != 0) { val currGold = grid[row][col - 1] grid[row][col - 1] = 0 gold(grid, row, col - 1, gold + currGold) grid[row][col - 1] = currGold } if (row < grid.size - 1 && grid[row + 1][col] != 0) { // flag=false; val currGold = grid[row + 1][col] grid[row + 1][col] = 0 gold(grid, row + 1, col, gold + currGold) grid[row + 1][col] = currGold } if (col < grid[0].size - 1 && grid[row][col + 1] != 0) { val currGold = grid[row][col + 1] grid[row][col + 1] = 0 gold(grid, row, col + 1, gold + currGold) grid[row][col + 1] = currGold } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,735
LeetCode-in-Kotlin
MIT License
app/src/main/kotlin/com/resurtm/aoc2023/day15/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day15 fun launchDay15(testCase: String) { val input = readInput(testCase) println("Day 15, part 1: ${input.sumOf { calcHash(it) }}") println("Day 15, part 2: ${calcPart2(input)}") } private fun calcPart2(items: List<String>): Int { val boxes = mutableMapOf<Int, MutableList<Pair<String, Int>>>() items.forEach { item -> if (item.indexOf('=') != -1) { val p = item.split('=') val id = calcHash(p[0]) if (!boxes.containsKey(id)) boxes[id] = mutableListOf() val box = boxes[id] if (box != null) { val pos = box.indexOfFirst { it.first == p[0] } if (pos == -1) box.add(Pair(p[0], p[1].toInt())) else box[pos] = Pair(p[0], p[1].toInt()) } } else if (item.indexOf('-') != -1) { val p = item.split('-') val id = calcHash(p[0]) if (!boxes.containsKey(id)) boxes[id] = mutableListOf() val box = boxes[id] if (box != null) { val pos = box.indexOfFirst { it.first == p[0] } if (pos != -1) boxes[id] = (box.subList(0, pos) + box.subList(pos + 1, box.size)).toMutableList() } } } var result = 0 boxes.forEach { box -> box.value.forEachIndexed { idx, item -> result += (box.key + 1) * (idx + 1) * item.second } } return result } private fun calcHash(str: String): Int { var curr = 0 str.forEach { curr += it.code curr *= 17 curr %= 256 } return curr } private fun readInput(testCase: String): List<String> { val reader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() ?: throw Exception("Invalid state, cannot read the input") val rawLine = (reader.readLine() ?: return emptyList()).trim() return rawLine.split(',') }
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
2,004
advent-of-code-2023
MIT License
src/main/kotlin/days/Day8.kt
mstar95
317,305,289
false
null
package days import arrow.core.Either import arrow.core.flatMap class Day8 : Day(8) { override fun partOne(): Any { // val instructions = inputList.map { it.split(" ") }.map { it[0] to it[1].toInt() } // println(instructions) // return Program(instructions).run() return 0; } override fun partTwo(): Any { val instructions = inputList.map { it.split(" ") }.map { it[0] to it[1].toInt() } return Program8(instructions).run().fold({ 0 }, { it }) } } private data class Program8(val instructions: List<Pair<String, Int>>) { fun run(step: Int = 0, accumulator: Int = 0, performed: Set<Int> = setOf(), modifiedStep: Int? = null): Either<Int?, Int> { if (step == instructions.size) { return Either.right(accumulator) } if (performed.contains(step)) { return Either.left(modifiedStep) } val instruction = instructions[step] val either = when (instruction.first) { "nop" -> nop(step, accumulator, performed, modifiedStep) "acc" -> acc(step, instruction, accumulator, performed, modifiedStep) "jmp" -> jmp(step, instruction, accumulator, performed, modifiedStep) else -> error("Not known instruction $instruction, $step") } if (either.isRight()) { return either } return either.swap().flatMap { if(performed.contains(it)) Either.left(it) else when (instruction.first) { "nop" -> jmp(step, instruction, accumulator, performed, step) "acc" -> Either.left(it) "jmp" -> nop(step, accumulator, performed, step) else -> error("Not known instruction $instruction, $step") } } } private fun jmp(step: Int, instruction: Pair<String, Int>, accumulator: Int, performed: Set<Int>, modifiedStep: Int?): Either<Int?, Int> = run(step + instruction.second, accumulator, performed + step, modifiedStep) private fun acc(step: Int, instruction: Pair<String, Int>, accumulator: Int, performed: Set<Int>, modifiedStep: Int?) = run(step + 1, accumulator + instruction.second, performed + step, modifiedStep) private fun nop(step: Int, accumulator: Int, performed: Set<Int>, modifiedStep: Int?) = run(step + 1, accumulator, performed + step, modifiedStep) }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
2,427
aoc-2020
Creative Commons Zero v1.0 Universal
src/dynamicprogramming/MinimumPathSum.kt
faniabdullah
382,893,751
false
null
package dynamicprogramming class MinimumPathSum { fun minPathSum(grid: Array<IntArray>): Int { val m = grid.size val n = grid[0].size val dp = Array(m) { Array(n) { 0 } } for (i in 0 until m) { for (j in 0 until n) { if (i == 0 && j == 0) { dp[i][j] = grid[i][j] } else if (i == 0) { dp[i][j] = dp[i][j - 1] + grid[i][j] } else if (j == 0) { dp[i][j] = dp[i - 1][j] + grid[i][j] } else { dp[i][j] = minOf(dp[i][j - 1], dp[i - 1][j]) + grid[i][j] } } } return dp[m - 1][n - 1] } } fun main() { // [[1,3,1],[1,5,1],[4,2,1]] println( MinimumPathSum().minPathSum( arrayOf( intArrayOf(1, 3, 1), intArrayOf(1, 5, 1), intArrayOf(4, 2, 1) ) ) ) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
966
dsa-kotlin
MIT License
src/day02/Day02.kt
molundb
573,623,136
false
{"Kotlin": 26868}
package day02 import readInput fun main () { val input = readInput(parent = "src/Day02", name = "Day02_input") println(solvePartOne(input)) println(solvePartTwo(input)) } private fun solvePartOne(input: List<String>): Int { val combinations = mapOf( Pair("A X", 4), Pair("A Y", 8), Pair("A Z", 3), Pair("B X", 1), Pair("B Y", 5), Pair("B Z", 9), Pair("C X", 7), Pair("C Y", 2), Pair("C Z", 6), ) var totalScore = 0 input.forEach { totalScore += combinations[it] ?: 0 } return totalScore } private fun solvePartTwo(input: List<String>): Int { val combinations = mapOf( Pair("A X", 3), Pair("A Y", 4), Pair("A Z", 8), Pair("B X", 1), Pair("B Y", 5), Pair("B Z", 9), Pair("C X", 2), Pair("C Y", 6), Pair("C Z", 7), ) var totalScore = 0 input.forEach { totalScore += combinations[it] ?: 0 } return totalScore }
0
Kotlin
0
0
a4b279bf4190f028fe6bea395caadfbd571288d5
1,033
advent-of-code-2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/medium/UniquePaths.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 62. 不同路径 * * 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。 * * 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。 * 问总共有多少条不同的路径? */ class UniquePaths { companion object { @JvmStatic fun main(args: Array<String>) { println(UniquePaths().uniquePaths(3, 7)) println(UniquePaths().uniquePaths(3, 2)) println(UniquePaths().uniquePaths(7, 3)) println(UniquePaths().uniquePaths(3, 3)) } } // 输入:m = 3, n = 7 // 输出:28 fun uniquePaths(m: Int, n: Int): Int { val path = Array(m) { IntArray(n) } path[0][0] = 1 for (i in 0 until m) { for (j in 0 until n) { if (i == 0 && j == 0) continue if (i == 0 && j > 0) { path[i][j] = path[i][j - 1] } else if (i > 0 && j == 0) { path[i][j] = path[i - 1][j] } else { path[i][j] = path[i - 1][j] + path[i][j - 1] } } } return path[m - 1][n - 1] } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,330
daily_algorithm
Apache License 2.0
03/kotlin.kts
mwangel
439,392,005
false
{"Groovy": 84890, "Kotlin": 4809, "Python": 764}
var map:List<BooleanArray> = mutableListOf() // START: Load the data. java.io.File("data.txt").forEachLine { line:String -> if( line.length > 0 ) { //var row = BooleanArray( line.length ) { i:Int -> (line.getAt(i) == '#' ? 1 : 0) } // TRUE for TREES! val row = line.map { it == '#' } map.add( row ) } } /** Check map[row][column] (column is mod:ed by rowLength). */ fun treeAt( map:List<BooleanArray>, row:Int, column:Int ) : Boolean { val rowLength = map[row].length return map[row][column % rowLength ] } /** Count trees found when stepping through the map this way. */ fun ct( map:List<BooleanArray>, ystep:Int, xstep:Int ) : Long { var column:Int = 0 var trees:Long = 0 for( y in 0..map.length step ystep ) { trees += (treeAt( map, y, column ) ? 1 : 0) column += xstep } return trees } // tests assert( map.length == 323 ) val testmap = mutableListOf( booleanArrayOf(true,false,true) ) //,[false,false,true] assert( treeAt( testmap, 0, 2 ) ) assert( treeAt( testmap, 0, 3 ) ) // 3 should rotate back around to 0 assert( treeAt( testmap, 0, 0 ) ) assert( !treeAt( testmap, 0, 1 ) ) assert( !treeAt( testmap, 1, 0 ) ) assert( !treeAt( testmap, 1, 1 ) ) // start println( "Part 1: ${ct(map,1,3)} trees found." ) println( "Part 2: ${ct(map,1,1) * ct(map,1,3) * ct(map,1,5) * ct(map,1,7) * ct(map,2,1)}" )
0
Groovy
0
0
2ba859eda97bdf8ff16fd20afdc4ec2c253eab04
1,336
advent-of-code-2021
The Unlicense
aoc_2023/src/main/kotlin/problems/day17/CrucibleSearch.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day17 import java.util.* open class CrucibleSearch(val city: CrucibleCity) { fun minimumHeastLoss(): Int { val node1 = CrucibleNode(0, 1, city.grid[0][1], hCost(0, 1), EastCrucibleDir.getInstance(), null) val node2 = CrucibleNode(1, 0, city.grid[1][0], hCost(1, 0), SouthCrucibleDir.getInstance(), null) val openedNodes = PriorityQueue<CrucibleNode> { a, b -> a.fCost - b.fCost } val visitedStates = mutableSetOf<CrucibleNode>() openedNodes.add(node1) openedNodes.add(node2) // var openedNodesCount = 0 while (openedNodes.isNotEmpty()) { // openedNodesCount++ val nextNode = openedNodes.poll() if (isGoal(nextNode)) { // println(openedNodesCount) return nextNode.gCost } if (visitedStates.contains(nextNode)) continue visitedStates.add(nextNode) val successors = getSuccessors(nextNode) openedNodes.addAll(successors) } return -1 } private fun hCost(i: Int, j: Int): Int { return this.city.grid.size - 1 - i + this.city.grid[0].size - 1 - j } private fun getSuccessors(node: CrucibleNode): List<CrucibleNode> { val nextDirs = nextDirs(node) val nextNodes = nextDirs.mapNotNull { dir -> val nextPos = dir.nextPos(node.i, node.j, this.city.grid) if (nextPos != null) { node.generateNextNode( nextPos.first, nextPos.second, this.city.grid[nextPos.first][nextPos.second], hCost(nextPos.first, nextPos.second), dir ) } else { null } } return nextNodes } open fun nextDirs(node: CrucibleNode): List<CrucibleDirection> { val nextDirs = mutableListOf(node.dir.rotateAntiClockwise(), node.dir.rotateClockwise()) if (node.repeatedDirs < 3) { nextDirs.add(node.dir) } return nextDirs } open fun isGoal(node: CrucibleNode): Boolean { return node.i == this.city.grid.size - 1 && node.j == this.city.grid[0].size - 1 } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
2,274
advent-of-code-2023
MIT License
2023/src/main/kotlin/org/suggs/adventofcode/Day07CamelCards.kt
suggitpe
321,028,552
false
{"Kotlin": 156836}
package org.suggs.adventofcode import org.slf4j.LoggerFactory object Day07CamelCards { private val log = LoggerFactory.getLogger(this::class.java) private val typeValues = Type.entries.reversed().mapIndexed { idx, type -> Pair(type, idx) }.toMap() private val cardValues = "AKQJT98765432".reversed().mapIndexed { idx, card -> Pair(card, idx) }.toMap() private val jokerCardValues = "AKQT98765432J".reversed().mapIndexed { idx, card -> Pair(card, idx) }.toMap() fun calculateCamelCardsValueFrom(data: List<String>): Int = data.asSequence().map { it.split(" ") } .map { (cards, bid) -> HandOfCards(cards, bid.toInt()) } .sorted().mapIndexed { idx, elem -> (idx + 1) * elem.bidAmount }.sum() .also { log.debug("Part 1: $it") } fun calculateCamelCardsWithJokersValueFrom(data: List<String>): Int = data.asSequence().map { it.split(" ") } .map { (cards, bid) -> HandOfCards(cards, bid.toInt(), true) } .sorted().mapIndexed { idx, elem -> (idx + 1) * elem.bidAmount }.sum() .also { log.debug("Part 2: $it") } data class HandOfCards(val cards: List<Char>, val bidAmount: Int, val handType: Type, val jokersAllowed: Boolean = false) : Comparable<HandOfCards> { companion object { operator fun invoke(cards: String, bid: Int, jokersAllowed: Boolean = false) = HandOfCards(cards.toCharArray().toList(), bid, figureOutHandTypeFrom(cards, jokersAllowed), jokersAllowed) private fun figureOutHandTypeFrom(cards: String, jokersAllowed: Boolean): Type { val cardCounts = cards.toCharArray().toList().groupingBy { it }.eachCount() return if (jokersAllowed) handTypeWithJokersFor(cardCounts) else handTypeNoJokersFor(cardCounts) } private fun handTypeNoJokersFor(cardCounts: Map<Char, Int>): Type = when { 5 in cardCounts.values && cardCounts.size == 1 -> Type.FIVE 4 in cardCounts.values && cardCounts.size == 2 -> Type.FOUR 3 in cardCounts.values && cardCounts.size == 2 -> Type.FULL 3 in cardCounts.values && cardCounts.size == 3 -> Type.THREE 2 in cardCounts.values && cardCounts.size == 3 -> Type.TWO_PAIR 2 in cardCounts.values && cardCounts.size == 4 -> Type.ONE_PAIR cardCounts.size == 5 -> Type.HIGH_CARD else -> throw IllegalStateException("No idea what this type of card type this is: $cardCounts") } private fun handTypeWithJokersFor(cardCounts: Map<Char, Int>): Type { // manipulate the cards return if (cardCounts.containsKey('J')) { val jokerCount = cardCounts['J']!! if (jokerCount == 5) return Type.FIVE val highestCard = cardCounts.filter { it.key != 'J' }.maxBy { it.value }.key val foo = cardCounts.filter { it.key != 'J' && it.key != highestCard } + mapOf(highestCard to (jokerCount + cardCounts[highestCard]!!)) return handTypeNoJokersFor(foo) } else handTypeNoJokersFor(cardCounts) } } override fun compareTo(other: HandOfCards): Int { val cardValuesToUse = if (jokersAllowed) jokerCardValues else cardValues return when { typeValues[handType]!! > typeValues[other.handType]!! -> 1 typeValues[handType]!! < typeValues[other.handType]!! -> -1 else -> recurseCardValues(other, cardValuesToUse) } } private fun recurseCardValues(other: HandOfCards, values: Map<Char, Int>): Int { fun recurseCardValues(other: HandOfCards, index: Int): Int { if (index == 0) return 0 return when { values[cards[cards.size - index]]!! > values[other.cards.get(cards.size - index)]!! -> 1 values[cards[cards.size - index]]!! < values[other.cards.get(cards.size - index)]!! -> -1 else -> recurseCardValues(other, index - 1) } } return recurseCardValues(other, other.cards.size) } } enum class Type { FIVE, FOUR, FULL, THREE, TWO_PAIR, ONE_PAIR, HIGH_CARD } }
0
Kotlin
0
0
9485010cc0ca6e9dff447006d3414cf1709e279e
4,442
advent-of-code
Apache License 2.0
2022/05/05.kt
LiquidFun
435,683,748
false
{"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191}
fun solve(input: String, moveTogether: Boolean) { val (raw_towers, moves) = input.split("\n\n") val towers = raw_towers.split("\n").dropLast(1).asReversed() val stacks: MutableList<MutableList<Char>> = mutableListOf() for (j in 1 until towers[0].length step 4) { stacks.add(mutableListOf()) for (i in 0 until towers.size) if (towers[i][j] != ' ') stacks.last().add(towers[i][j]) } val nums = moves .split("\n") .map {it.filter {!it.isLetter()}} .map { it.split(" ")} .map { it.map {it.trim().toInt()}} for ((num, from, to) in nums) { if (!moveTogether) for (i in 1..num) stacks[to-1].add(stacks[from-1].removeLast()) else { val tmp: MutableList<Char> = mutableListOf() for (i in 1..num) tmp.add(stacks[from-1].removeLast()) for (i in 1..num) stacks[to-1].add(tmp.removeLast()) } } println(stacks.map { it.last() }.joinToString("")) } fun main() { val input = generateSequence(::readlnOrNull).joinToString("\n") solve(input, false) solve(input, true) }
0
Kotlin
7
43
7cd5a97d142780b8b33b93ef2bc0d9e54536c99f
1,202
adventofcode
Apache License 2.0
src/week1/ProductExceptSelf.kt
anesabml
268,056,512
false
null
package week1 import kotlin.system.measureNanoTime class ProductExceptSelf { /** Brute force * Iterate over the array and calculate the multiply result * Time complexity : O(n2) * Space complexity : O(n) */ fun productExceptSelf(nums: IntArray): IntArray { val output = IntArray(nums.size) { 1 } nums.forEachIndexed { i1, num1 -> nums.forEachIndexed { i2, num2 -> if (i1 != i2) output[i1] *= num2 } } return output } /** Better solution * If we observe the array we see that a multiple of nums = (left side) times (right side). * So we Iterate from start to eng and calculate the result of multiplying the left side of i. * After that we iterate from end to start and calculate the result of multiplying the right side of i. * Time complexity : O(n) * Space complexity : O(n) */ fun productExceptSelf2(nums: IntArray): IntArray { val output = IntArray(nums.size) val left = IntArray(nums.size) { 1 } val right = IntArray(nums.size) { 1 } for (i in 1 until nums.size) { left[i] = left[i - 1] * nums[i - 1] } for (i in nums.size - 2 downTo 0) { right[i] = right[i + 1] * nums[i + 1] } output.forEachIndexed { index, i -> output[index] = left[index] * right[index] } return output } /** Better solution * If we observe the array we see that a multiple of nums = (left side) times (right side). * So we Iterate from start to eng and calculate the result of multiplying the left side of i. * After that we iterate from end to start and calculate the result of multiplying the right side of i. * Time complexity : O(n) * Space complexity : O(n) */ fun productExceptSelf3(nums: IntArray): IntArray { val output = IntArray(nums.size) { 1 } var temp = 1 for (i in nums.indices) { output[i] *= temp temp *= nums[i] } temp = 1 for (i in nums.size - 1 downTo 0) { output[i] *= temp temp *= nums[i] } return output } } fun main() { val input = intArrayOf(2, 7, 11, 15) val productExceptSelf = ProductExceptSelf() val firstSolutionTime = measureNanoTime { println(productExceptSelf.productExceptSelf(input).contentToString()) } val secondSolutionTime = measureNanoTime { println(productExceptSelf.productExceptSelf2(input).contentToString()) } val thirdSolutionTime = measureNanoTime { println(productExceptSelf.productExceptSelf3(input).contentToString()) } println("First Solution execution time: $firstSolutionTime") println("Second Solution execution time: $secondSolutionTime") println("Third Solution execution time: $thirdSolutionTime") }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
2,871
leetCode
Apache License 2.0
src/main/kotlin/aoc2023/Day16.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import Point import readInput import to2dCharArray import java.util.* import kotlin.math.max object Day16 { private enum class Direction { TOP, BOTTOM, LEFT, RIGHT } private data class Movement(val comingFrom: Direction, val position: Point) private class ContraptionGrid(input: List<String>) { private val tiles = input.to2dCharArray() private val maxX = input.first().length - 1 private val maxY = input.size - 1 private val grid = Pair(Point(0, 0), Point(maxX, maxY)) fun getEnergizedTileCount(startDirection: Direction = Direction.LEFT, startPosition: Point = Point(0, 0)): Int { val visitedTiles = mutableSetOf<Movement>() val toVisit: Queue<Movement> = LinkedList() toVisit.add(Movement(startDirection, startPosition)) while (toVisit.isNotEmpty()) { val current = toVisit.poll() if (!visitedTiles.contains(current)) { visitedTiles.add(current) val (direction, position) = current val tile = tiles[position.x][position.y] toVisit.addAll(tile.getNext(direction, position).filter { (_, next) -> next.isWithin(grid) }) } } return visitedTiles.map { it.position }.toSet().size } val maxEnergizedTileCount by lazy { // seems fast enough so that we don't even need any cache var max = 0 for (x in 0..maxX) { max = max(max, getEnergizedTileCount(Direction.BOTTOM, Point(x, maxY))) max = max(max, getEnergizedTileCount(Direction.TOP, Point(x, 0))) } for (y in 0..maxY) { max = max(max, getEnergizedTileCount(Direction.RIGHT, Point(maxX, y))) max = max(max, getEnergizedTileCount(Direction.LEFT, Point(0, y))) } max } } /** * @param comingFrom the direction, from which we enter this tile * @param position the position of this tile * @return a list of adjacent tiles and the direction, in which we enter them */ private fun Char.getNext(comingFrom: Direction, position: Point): List<Movement> { val top = Movement(Direction.BOTTOM, position.move(0, -1)) val bottom = Movement(Direction.TOP, position.move(0, 1)) val left = Movement(Direction.RIGHT, position.move(-1, 0)) val right = Movement(Direction.LEFT, position.move(1, 0)) return when (this) { '.' -> when (comingFrom) { Direction.TOP -> listOf(bottom) Direction.BOTTOM -> listOf(top) Direction.LEFT -> listOf(right) Direction.RIGHT -> listOf(left) } '/' -> when (comingFrom) { Direction.TOP -> listOf(left) Direction.BOTTOM -> listOf(right) Direction.LEFT -> listOf(top) Direction.RIGHT -> listOf(bottom) } '\\' -> when (comingFrom) { Direction.TOP -> listOf(right) Direction.BOTTOM -> listOf(left) Direction.LEFT -> listOf(bottom) Direction.RIGHT -> listOf(top) } '-' -> when (comingFrom) { Direction.TOP, Direction.BOTTOM -> listOf(left, right) Direction.LEFT -> listOf(right) Direction.RIGHT -> listOf(left) } '|' -> when (comingFrom) { Direction.TOP -> listOf(bottom) Direction.BOTTOM -> listOf(top) Direction.LEFT, Direction.RIGHT -> listOf(top, bottom) } else -> throw IllegalArgumentException("Unknown input: $this for tile at $position") } } fun part1(input: List<String>) = ContraptionGrid(input).getEnergizedTileCount() fun part2(input: List<String>) = ContraptionGrid(input).maxEnergizedTileCount } fun main() { val testInput = readInput("Day16_test", 2023) check(Day16.part1(testInput) == 46) check(Day16.part2(testInput) == 51) val input = readInput("Day16", 2023) println(Day16.part1(input)) println(Day16.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
4,283
adventOfCode
Apache License 2.0
kotlin-practice/src/main/kotlin/algorithms/old/WordsCount.kt
nicolegeorgieva
590,020,790
false
{"Kotlin": 120359}
package algorithms.old fun main() { val text = "Hi, I'm Nicole. I've been diving deep into Software Development for about 2 years, particularly into " + "Android Development with Kotlin and Jetpack Compose. I'm proficient in mobile UI/UX and have worked on " + "projects related to productivity, fintech, and health. I'm genuinely passionate about tech and believe " + "that IT has a huge role to play in our future. I’m ready to bring my expertise to exciting new challenges" + " in Android development!" println(text.wordsCount { it !in listOf("a", "to", "the") }) println(text.wordsCountWithDensity()) } // Nice exercise. The exercise is under number 5. Nice. private fun String.wordsCount(additionalWordFilter: ((String) -> Boolean)? = null): Map<String, Int> { val wordsCountMap = mutableMapOf<String, Int>() // Nice, exercise, The, exercise val words = this.filter { it != '.' && it != ',' && it != '!' }.lowercase().split(" ") val latest = if (additionalWordFilter != null) { words.filter { additionalWordFilter(it) } } else { words } for (word in latest) { val wordCount = wordsCountMap[word] ?: 0 wordsCountMap[word] = wordCount + 1 } return wordsCountMap.toList().sortedByDescending { it.second }.toMap() } data class SeoInfo( val wordCount: Int, val densityPercent: Double ) // 10 words, 3 count -> 30% private fun String.wordsCountWithDensity(): Map<String, SeoInfo> { val wordsCountMap = this.wordsCount() val totalWords = wordsCountMap.size val resMap = wordsCountMap.map { Pair( it.key, SeoInfo( wordCount = it.value, densityPercent = (it.value / totalWords.toDouble()) * 100 ) ) }.toMap() return resMap }
0
Kotlin
0
1
c96a0234cc467dfaee258bdea8ddc743627e2e20
1,892
kotlin-practice
MIT License
src/commonMain/kotlin/net/dinkla/raytracer/math/Polynomials.kt
jdinkla
38,753,756
false
{"Kotlin": 467610, "Shell": 457}
package net.dinkla.raytracer.math import kotlin.math.acos import kotlin.math.cos import kotlin.math.pow import kotlin.math.sqrt object Polynomials { private fun cbrt(d: Double) = if (d < 0.0) { -(-d).pow(1.0 / 3.0) } else { d.pow(1.0 / 3.0) } fun solveCubic(c: DoubleArray, s: DoubleArray): Int { if (c.size != 4 || s.size != 3) { throw AssertionError() } val num: Int val A: Double = c[2] / c[3] val B: Double = c[1] / c[3] val C: Double = c[0] / c[3] /* normal form: x^3 + Ax^2 + Bx + C = 0 */ /* substitute x = y - A/3 to eliminate quadric term: x^3 +px + q = 0 */ val sq_A = A * A val p = 1.0 / 3 * (-1.0 / 3 * sq_A + B) val q = 1.0 / 2 * ((2.0 / 27) * A * sq_A - (1.0 / 3) * A * B + C) /* use Cardano's formula */ val cb_p = p * p * p val D = q * q + cb_p if (MathUtils.isZero(D)) { if (MathUtils.isZero(q)) { /* one triple solution */ s[0] = 0.0 num = 1 } else { /* one single and one double solution */ val u = cbrt(-q) s[0] = 2.0 * u s[1] = -u num = 2 } } else if (D < 0) { /* Casus irreducibilis: three real solutions */ val phi = 1.0 / 3.0 * acos(-q / sqrt(-cb_p)) val t = 2 * sqrt(-p) s[0] = t * cos(phi) s[1] = -t * cos(phi + MathUtils.PI / 3.0) s[2] = -t * cos(phi - MathUtils.PI / 3.0) num = 3 } else { /* one real solution */ val sqrt_D = sqrt(D) val u = cbrt(sqrt_D - q) val v = -cbrt(sqrt_D + q) s[0] = u + v num = 1 } /* resubstitute */ val sub = 1.0 / 3 * A var i = 0 while (i < num) { s[i] -= sub ++i } return num } fun solveQuadric(c: DoubleArray, s: DoubleArray): Int { if (c.size != 3 || s.size != 2) { throw AssertionError() } /* normal form: x^2 + px + q = 0 */ val p = c[1] / (2 * c[2]) val q = c[0] / c[2] val D = p * p - q return when { MathUtils.isZero(D) -> { s[0] = -p 1 } D > 0 -> { val sqrtD = sqrt(D) s[0] = sqrtD - p s[1] = -sqrtD - p 2 } else -> { 0 } } } fun solveQuartic(c: DoubleArray, s: DoubleArray): Int { if (c.size != 5 || s.size != 4) { throw AssertionError() } val coeffs4 = DoubleArray(4) val coeffs3 = DoubleArray(3) val A: Double = c[3] / c[4] val B: Double = c[2] / c[4] val C: Double = c[1] / c[4] val D: Double = c[0] / c[4] var num: Int /* normal form: x^4 + Ax^3 + Bx^2 + Cx + D = 0 */ /* substitute x = y - A/4 to eliminate cubic term: x^4 + px^2 + qx + r = 0 */ val sq_A = A * A val p = -3.0 / 8 * sq_A + B val q = (1.0 / 8) * sq_A * A - (1.0 / 2) * A * B + C val r = (-3.0 / 256) * sq_A * sq_A + (1.0 / 16) * sq_A * B - (1.0 / 4) * A * C + D if (MathUtils.isZero(r)) { /* no absolute term: y(y^3 + py + q) = 0 */ coeffs4[0] = q coeffs4[1] = p coeffs4[2] = 0.0 coeffs4[3] = 1.0 val ss = doubleArrayOf(s[0], s[1], s[2]) num = solveCubic(coeffs4, ss) s[0] = ss[0] s[1] = ss[1] s[2] = ss[2] s[num++] = 0.0 } else { /* solve the resolvent cubic ... */ coeffs4[0] = (1.0 / 2) * r * p - (1.0 / 8) * q * q coeffs4[1] = -r coeffs4[2] = -1.0 / 2 * p coeffs4[3] = 1.0 val ss = doubleArrayOf(s[0], s[1], s[2]) solveCubic(coeffs4, ss) s[0] = ss[0] s[1] = ss[1] s[2] = ss[2] /* ... and take the one real solution ... */ val z = s[0] /* ... to build two quadric equations */ var u = z * z - r u = when { MathUtils.isZero(u) -> 0.0 u > 0 -> sqrt(u) else -> 0.0 } var v = 2 * z - p v = when { MathUtils.isZero(v) -> 0.0 v > 0 -> sqrt(v) else -> 0.0 } coeffs3[0] = z - u coeffs3[1] = if (q < 0) -v else v coeffs3[2] = 1.0 val ss2 = doubleArrayOf(s[0], s[1]) num = solveQuadric(coeffs3, ss2) s[0] = ss2[0] s[1] = ss2[1] coeffs3[0] = z + u coeffs3[1] = if (q < 0) v else -v coeffs3[2] = 1.0 val ss3 = doubleArrayOf(s[0 + num], s[1 + num]) num += solveQuadric(coeffs3, ss3) s[0] = ss3[0] s[1] = ss3[1] } /* resubstitute */ val sub = 1.0 / 4 * A var i = 0 while (i < num) { s[i] -= sub ++i } return num } }
0
Kotlin
2
5
72ca9b79eb22d9e4f6b7ccfb896427966c20e934
5,340
from-the-ground-up-ray-tracer
Apache License 2.0
src/main/kotlin/Day07.kt
akowal
434,506,777
false
{"Kotlin": 30540}
import kotlin.math.abs fun main() { println(Day07.solvePart1()) println(Day07.solvePart2()) } object Day07 { private val positions = readInput("day07") .single() .toIntArray() .sorted() fun solvePart1(): Int { val median = positions.run { (get(size / 2) + get(size / 2 + size % 2)) / 2 } return positions.sumOf { abs(it - median) } } fun solvePart2(): Int { fun cost(a: Int, b: Int) = abs(a - b).let { it * (it + 1) / 2 } val mean = positions.average() val min = (mean - 1).toInt() val max = (mean + 1).toInt() return (min..max).minOf { pos -> positions.sumOf { cost(it, pos) } } } }
0
Kotlin
0
0
08d4a07db82d2b6bac90affb52c639d0857dacd7
696
advent-of-kode-2021
Creative Commons Zero v1.0 Universal
2021/src/day23/Day23.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day23 import readInput import java.text.SimpleDateFormat import java.util.* import kotlin.IllegalStateException import kotlin.math.abs fun List<String>.toAmphipods() : List<Amphipod> { val amphipods = mutableListOf<Amphipod>() for (y in this.indices) { for (x in this[y].indices) { if (listOf('A', 'B', 'C', 'D').contains(this[y][x])) { amphipods.add(Amphipod(this[y][x], Point(x, y))) } } } return amphipods } data class Point(val x: Int, val y:Int) data class Amphipod( val name: Char, var pos: Point, var usedEnergy: Int = 0 ) { companion object { const val HALLWAY_Y = 1 val WAIT_POSITIONS = listOf( Point(1, 1), Point(2, 1), Point(4, 1), Point(6, 1), Point(8, 1), Point(10, 1), Point(11, 1), ) } private fun energyForStep() = when (name) { 'A' -> 1 'B' -> 10 'C' -> 100 'D' -> 1000 else -> throw IllegalStateException("Unknown name $name") } private fun getCavePosition(table: List<CharArray>, amph: List<Amphipod>) = when (name) { 'A' -> getCaveforX(table, 3, 'A') 'B' -> getCaveforX(table, 5, 'B') 'C' -> getCaveforX(table, 7, 'C') 'D' -> getCaveforX(table, 9, 'D') else -> throw IllegalStateException("Unknown name $name") }.filter { cavePos -> val targetX = cavePos.x // There is one fish on the way, impossible to move there !amph.any { (it.pos.x < maxOf(targetX, pos.x) && it.pos.x > minOf(targetX, pos.x)) && it.pos.y == HALLWAY_Y } } private fun getCaveforX(table: List<CharArray>, requiredX: Int, requiredLetter: Char): List<Point> { for (depth in table.caveDepth() downTo 2) { if (table[depth][requiredX] != requiredLetter) { return if (table[depth][requiredX] == '.'){ listOf(Point(requiredX, depth)) } else { emptyList() } } } return emptyList() } fun isInPosition(table: List<CharArray>) = when (name) { 'A' -> isWellPlaced(table, 3, 'A') 'B' -> isWellPlaced(table, 5, 'B') 'C' -> isWellPlaced(table, 7, 'C') 'D' -> isWellPlaced(table, 9, 'D') else -> throw IllegalStateException("Unknown name $name") } private fun isWellPlaced(table: List<CharArray>, requiredX: Int, requiredLetter: Char) : Boolean { val isInCave = pos.x == requiredX && pos.y >= 2 val allDownAreGood = (pos.y..table.caveDepth()).all { table[it][pos.x] == requiredLetter } return isInCave && allDownAreGood } fun getPossiblePositions(table: List<CharArray>, amph: List<Amphipod>) : List<Point> { // Already in the end position if (isInPosition(table)) return emptyList() // Blocked by another fish to get out if (pos.y >= 3 && table[pos.y - 1][pos.x] != '.') return emptyList() return if (usedEnergy != 0) { // When we got out of a cave, next step is to get into our cave getCavePosition(table, amph) } else { return getCavePosition(table, amph) + WAIT_POSITIONS.filter { waitPos -> val targetX = waitPos.x // There is one fish on the way, impossible to move there !amph.any { (it.pos.x <= maxOf(targetX, pos.x) && it.pos.x >= minOf(targetX, pos.x)) && it.pos.y == waitPos.y } } } } fun getEnergyToMove(newPos: Point): Int { val energyToGoUp = abs(HALLWAY_Y - pos.y) * energyForStep() val energyX = abs(newPos.x - pos.x) * energyForStep() val energyToGoDown = abs(HALLWAY_Y - newPos.y) * energyForStep() return energyToGoUp + energyX + energyToGoDown } fun moveToPos(newPos: Point) { usedEnergy += getEnergyToMove(newPos) pos = newPos } fun resetToPos(resetPos: Point, resetEnergy: Int) { usedEnergy = resetEnergy pos = resetPos } } fun List<Amphipod>.isDone(table: List<CharArray>) = all { it.isInPosition(table) } fun List<Amphipod>.getEnergySpent() = sumOf { it.usedEnergy } fun List<Amphipod>.print() { getEmptyCave(this.maxOf { it.pos.y } + 1).forEachIndexed { y, s -> for (x in s.indices) { this.firstOrNull { it.pos == Point(x, y) }?.let { print(it.name) } ?: print(s[x]) } println() } } fun List<Amphipod>.getTable(caveDepth: Int): MutableList<CharArray> { return getEmptyCave(caveDepth).mapIndexed { y, s -> s.mapIndexed { x, c -> this.firstOrNull { it.pos == Point(x, y) }?.name ?: c }.toCharArray() }.toMutableList() } fun getEmptyCave(depth: Int) : MutableList<String> { val base = mutableListOf( "#############", "#...........#", "###.#.#.#.###", ) for (i in 1 until depth - base.size) { base.add(" #.#.#.#.# ") } base.add(" ######### ") return base } fun List<CharArray>.caveDepth() = this.size - 2 var minFound: Int = Integer.MAX_VALUE fun energyToSolve(table: MutableList<CharArray>, fishes: List<Amphipod>): Int? { if (fishes.isDone(table)) { minFound = minOf(minFound, fishes.getEnergySpent()) return fishes.getEnergySpent() } val energies = mutableListOf<Int>() // fishes.print() for (amph in fishes) { val possiblePos = amph.getPossiblePositions(table, fishes) for (tentativePos in possiblePos) { val potentialAdd = fishes.getEnergySpent() + amph.getEnergyToMove(tentativePos) if (minFound <= potentialAdd) continue val tmp = amph.copy() table[amph.pos.y][amph.pos.x] = '.' table[tentativePos.y][tentativePos.x] = amph.name amph.moveToPos(tentativePos) energyToSolve(table, fishes)?.let { tenta -> energies.add(tenta) } table[tentativePos.y][tentativePos.x] = '.' table[tmp.pos.y][tmp.pos.x] = amph.name amph.resetToPos(tmp.pos, tmp.usedEnergy) } } return energies.minOrNull() } fun <T>measureTime(block: () -> T): T { val start = System.currentTimeMillis() return block().also { println("Solving took ${SimpleDateFormat("mm:ss:SSS").format(Date(System.currentTimeMillis() - start))}") } } fun resolve(lines: List<String>): Int { val fishes = lines.toAmphipods() val table = fishes.getTable(lines.size) minFound = Integer.MAX_VALUE return measureTime { energyToSolve(table, fishes) ?: -1 } } fun main() { val simple = readInput("day23/test") println("part1(test) => " + resolve(simple)) val input = readInput("day23/input") println("part1(input) => " + resolve(input)) val simpleDeep = readInput("day23/test2") println("part2(simpleDeep) => " + resolve(simpleDeep)) val inputDeep = readInput("day23/input2") println("part2(inputDeep) => " + resolve(inputDeep)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
7,101
advent-of-code
Apache License 2.0
src/Day01.kt
driuft
575,221,823
false
{"Kotlin": 1745}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { val inputList = input.map { it.toIntOrNull() } var currMax = 0 var result = 0 for (calories in inputList) { if (calories == null) { currMax = 0 } else { currMax += calories result = max(currMax, result) } } return result } fun part2(input: List<String>): Int { val inputList = input.map { it.toIntOrNull() } val calorieList = mutableMapOf<Int, Int>() var currGroup = 1 var currMax = 0 for (idx in inputList.indices) { if (inputList[idx] == null) { currGroup += 1 currMax = 0 } else { currMax += inputList[idx]!! calorieList[currGroup] = currMax } } val topThree = calorieList.values.sortedDescending().take(3) return topThree.sum() } val input = readInput("Day01") println(part2(input)) }
0
Kotlin
0
0
29ec6bf674834dbd0e3b80eb7e439e541a274ec6
1,090
2022-advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day03.kt
MichalChomo
572,214,942
false
{"Kotlin": 56758}
package eu.michalchomo.adventofcode.year2022 fun main() { val itemTypeToPriority = CharRange('a', 'z').toList().plus(CharRange('A', 'Z')).zip(IntRange(1, 52).toList()).toMap() fun part1(input: List<String>): Int = input.sumOf { itemTypeToPriority[ it.slice(0 until it.length / 2).toSet() .intersect(it.slice((it.length / 2) until it.length).toSet()) .first() ]!! } fun part2(input: List<String>): Int = input.chunked(3).sumOf { itemTypeToPriority[ it.map { rucksack -> rucksack.toSet() } .reduce { acc, r -> acc.intersect(r) } .first() ]!! } val testInput = readInputLines("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInputLines("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a95d478aee72034321fdf37930722c23b246dd6b
925
advent-of-code
Apache License 2.0
kotlin/2022/day05/Day05.kt
nathanjent
48,783,324
false
{"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966}
class Day05 { interface Rule {} interface Location: Rule { val marker: Char } data class Empty( override val marker: Char = ' ' ): Location data class Crate( override val marker: Char ): Location data class Row( val locations: List<Location> ): Rule data class Move( val count: Int, val from: Int, val to: Int, ): Rule class Unknown(): Rule fun part1(input: Iterable<String>): String { val mover = CrateMover() mover.loadInstructions(input) mover.processMovesWith { move: Move, stacks: MutableMap<Int, ArrayDeque<Location>> -> val fromStack = stacks[move.from] for (i in 1..move.count) { val location = fromStack?.removeFirstOrNull() if (location != null && location is Crate) { stacks[move.to]?.addFirst(location) } } } return mover.stacks.map { it.value.firstOrNull() } .filterNotNull() .map { it.marker } .joinToString("") } fun part2(input: Iterable<String>): String { val mover = CrateMover() mover.loadInstructions(input) mover.processMovesWith { move: Move, stacks: MutableMap<Int, ArrayDeque<Location>> -> val fromStack = stacks[move.from] val craneStack: ArrayDeque<Location> = ArrayDeque(listOf()) for (i in 1..move.count) { val location = fromStack?.removeFirstOrNull() if (location != null && location is Crate) { craneStack.addFirst(location) } } craneStack.forEach { stacks[move.to]?.addFirst(it) } } return mover.stacks.map { it.value.firstOrNull() } .filterNotNull() .map { it.marker } .joinToString("") } class CrateMover { private var moveList: List<Move> = listOf() val stacks = mutableMapOf<Int, ArrayDeque<Location>>() fun loadInstructions(instructions: Iterable<String>) { val rules = instructions.map { rule -> if (rule.isBlank()) return@map Unknown() when (rule[0]) { ' ', '[' -> parseRow(rule) ?: Unknown() 'm' -> parseMove(rule) else -> Unknown() } } .filter { it !is Unknown } .partition { it is Row } generateStacks(rules.first.map { it as Row }) moveList = rules.second.map { it as Move } } private fun generateStacks(rows: Iterable<Row>) { for (row in rows) { row.locations.forEachIndexed { i: Int, location: Location -> val stackIndex = i + 1 // Stacks are 1-indexed val stack = stacks.getOrPut(stackIndex ) { ArrayDeque(mutableListOf<Location>()) } when (location) { is Crate -> stack.addLast(location) is Empty -> {} else -> throw Exception("Unknown location type [ $location ]") } } } } fun processMovesWith(process: (Move, MutableMap<Int, ArrayDeque<Location>>) -> Unit) { for (move in moveList) { process(move, stacks) } } private fun parseRow(row: String): Row? { return Row(row.chunked(4).map { when (it[0]) { '[' -> { when (it[1]) { in 'A'..'Z' -> Crate(it[1]) else -> throw Exception("Unmarked crate error [ $it ]") } } ' ' -> { when (it[1]) { in '1'..'9' -> return null else -> Empty() } } else -> Empty() } }) } private fun parseMove(move: String): Move { val stackMoves = move.split(' ').map { when (it) { in "1".."9" -> it "move", "from", "to" -> null else -> throw Exception("Unhandled move index [ $it ]") } } .filterNotNull() return Move( stackMoves[0].toInt(), stackMoves[1].toInt(), stackMoves[2].toInt(), ) } } }
0
Rust
0
0
7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf
3,947
adventofcode
MIT License
kotlin/src/main/kotlin/adventofcode/day9/Day9_2.kt
thelastnode
160,586,229
false
null
package adventofcode.day8 object Day9_2 { data class Marble(val value: Int, var prev: Marble?, var next: Marble?) { fun insertAfter(n: Int) { if (this.prev == this) { val newMarble = Marble(n, this, this) this.prev = newMarble this.next = newMarble } else { val newMarble = Marble(n, this, this.next) this.next!!.prev = newMarble this.next = newMarble } } fun removeAfter(): Int { val next = this.next!! next.next!!.prev = this this.next = next.next!! next.next = null next.prev = null return next.value } override fun toString(): String = "$value" } fun firstMarble(value: Int): Marble { val marble = Marble(value, null, null) marble.next = marble marble.prev = marble return marble } fun printChain(startingMarble: Marble): String { var currentMarble = startingMarble val results = mutableListOf<Int>() while (currentMarble.value != 0) { currentMarble = currentMarble.next!! } do { results.add(currentMarble.value) currentMarble = currentMarble.next!! } while (currentMarble.value != 0) return results.toString() } fun process(playerCount: Int, marbleCount: Int): Long { var currentMarble = firstMarble(0) val scores = (0 until playerCount).map { 0L }.toMutableList() var currentPlayer = 0 for (nextMarble in 1..marbleCount) { if (nextMarble % 23 == 0) { // go back 8 times (0..7).forEach { currentMarble = currentMarble.prev!! } val removed = currentMarble.removeAfter() scores[currentPlayer] += (nextMarble + removed).toLong() currentMarble = currentMarble.next!! } else { currentMarble = currentMarble.next!! currentMarble.insertAfter(nextMarble) currentMarble = currentMarble.next!! } currentPlayer = (currentPlayer + 1) % playerCount // println("$nextMarble - ${printChain(currentMarble)}") } return scores.max()!! } } fun main(args: Array<String>) { println(Day9_2.process(playerCount = 9, marbleCount = 25)) println(Day9_2.process(playerCount = 10, marbleCount = 1618)) println(Day9_2.process(playerCount = 13, marbleCount = 7999)) println(Day9_2.process(playerCount = 17, marbleCount = 1104)) println(Day9_2.process(playerCount = 21, marbleCount = 6111)) println(Day9_2.process(playerCount = 30, marbleCount = 5807)) println(Day9_2.process(playerCount = 491, marbleCount = 71058)) println(Day9_2.process(playerCount = 491, marbleCount = 71058 * 100)) }
0
Kotlin
0
0
8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa
2,946
adventofcode
MIT License
src/main/kotlin/tree/bintree/MinAwkward.kt
yx-z
106,589,674
false
null
package tree.bintree import util.* // given a binary tree representing company hierarchy, with each edge containing // a number, either positive, 0, or negative, also remembering that // there is an edge between two nodes iff. one is a direct parent of the other // find a subset of exactly k nodes with the smallest sum of awkwardness fun main(args: Array<String>) { val root = BinTreeNode(2 as Int? tu 4 as Int?) val l = BinTreeNode(-1 as Int? tu -2 as Int?) val ll = BinTreeNode(null as Int? tu null as Int?) val lr = BinTreeNode(null as Int? tu null as Int?) val r = BinTreeNode(null as Int? tu 3 as Int?) val rr = BinTreeNode(null as Int? tu null as Int?) root.left = l root.left!!.left = ll root.left!!.right = lr root.right = r root.right!!.right = rr root.prettyPrintTree() println(root.minAwkward(3)) } fun BinTreeNode<Tuple2<Int?, Int?>>.minAwkward(k: Int): Int { // dp[node][k][0] = min awkwardness for a tree rooted @ node // , inviting k people, and NOT including the root // dp[node][k][1] = min awkwardness for a tree rooted @ node // , inviting k people, and including the root val dp = HashMap<BinTreeNode<Tuple2<Int?, Int?>>, OneArray<Array<Int>>>() init(dp, k) minAwkwardRecur(dp, k) // for ((k, v) in dp) { // println("$k: $v") // } return dp[this]!![k].min() ?: 0 } val INF = Int.MAX_VALUE / 100 fun BinTreeNode<Tuple2<Int?, Int?>>.init( dp: HashMap<BinTreeNode<Tuple2<Int?, Int?>>, OneArray<Array<Int>>>, k: Int) { dp[this] = OneArray(k) { Array(2) { INF } } dp[this]!!.getterIndexOutOfBoundsHandler = { Array(2) { 0 } } left?.init(dp, k) right?.init(dp, k) } fun BinTreeNode<Tuple2<Int?, Int?>>.minAwkwardRecur( dp: HashMap<BinTreeNode<Tuple2<Int?, Int?>>, OneArray<Array<Int>>>, k: Int) { if (k <= 1) { dp[this]!![1][1] = 0 return } // k >= 2 left?.minAwkwardRecur(dp, k - 1) right?.minAwkwardRecur(dp, k - 1) minAwkwardRecur(dp, k - 1) when { left == null && right == null -> { dp[this]!![k][0] = INF dp[this]!![k][1] = INF } left != null && right == null -> { dp[this]!![k][0] = min(dp[left!!]!![k][0], dp[left!!]!![k][1]) dp[this]!![k][1] = min(dp[left!!]!![k - 1][0], dp[left!!]!![k - 1][1] + data.first!!) } left == null && right != null -> { dp[this]!![k][0] = min(dp[right!!]!![k][0], dp[right!!]!![k][1]) dp[this]!![k][1] = min(dp[right!!]!![k - 1][0], dp[right!!]!![k - 1][1] + data.second!!) } else -> { // left != null && right != null dp[this]!![k][0] = (0..k).map { j -> min(dp[left!!]!![j][0], dp[left!!]!![j][1]) + min(dp[right!!]!![k - j][0], dp[right!!]!![k - j][1]) }.min() ?: INF dp[this]!![k][1] = (0 until k).map { j -> min(dp[left!!]!![j][0], dp[left!!]!![j][1] + data.first!!) + min(dp[right!!]!![k - 1 - j][0], dp[right!!]!![k - 1 - j][1] + data.second!!) }.min() ?: INF } } }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
2,885
AlgoKt
MIT License
src/test/kotlin/io/noobymatze/aoc/y2022/Day17.kt
noobymatze
572,677,383
false
{"Kotlin": 90710}
package io.noobymatze.aoc.y2022 import io.noobymatze.aoc.Aoc import kotlin.math.abs import kotlin.test.Test class Day17 { data class Pos(val row: Int, val col: Int) { val up get() = Pos(row - 1, col) val down get() = Pos(row + 1, col) // I know, this is a bit dirty operator fun plus(value: Int): Pos = Pos(row, col + value) operator fun minus(value: Int): Pos = Pos(row, col - value) } @Test fun test1() { val example = """ |>>><<><>><<<>><>>><<<>>><<<><<<>><>><<>> """.trimMargin() val moves = Aoc.getInput(17) .asSequence().joinToString("v") + "v" var blocked = (0..6).map { Pos(1, it) }.toSet() var rockCounter = 0L var instr = 0 var rock = rock(rockCounter, 1) while (rockCounter < 2023) { val move = moves[instr++ % moves.length] val newRock = rock.move(move, blocked) rock = if (newRock == null) { //printBoard(rock, blocked) blocked = calcBlocked(blocked + rock) rock(++rockCounter, blocked.minOf { it.row }) } else { newRock } } println(abs(blocked.minOf { it.row }) - 1) } @Test fun test2() { val example = """ |>>><<><>><<<>><>>><<<>>><<<><<<>><>><<>> """.trimMargin() val moves = example // Aoc.getInput(17) .asSequence().joinToString("v") + "v" var blocked = (0..6).map { Pos(1, it) }.toSet() var rockCounter = 0L var instr = 0 var rock = rock(rockCounter, 1) while (rockCounter < 1000000000000) { val move = moves[instr++ % moves.length] val newRock = rock.move(move, blocked) rock = if (newRock == null) { //printBoard(rock, blocked) blocked = calcBlocked(blocked + rock) rock(++rockCounter, blocked.minOf { it.row }) } else { newRock } if (rockCounter % 1000 == 0L) { println("$rockCounter: ${blocked.size}") } } println(abs(blocked.minOf { it.row }) - 1) } private fun calcBlocked(blocked: Set<Pos>): Set<Pos> { val result = mutableSetOf<Pos>() val mins = (0..6).map { col -> blocked.filter { it.col == col }.minOf { it.row } } for (pos in blocked) { val onTop = pos.row > mins[pos.col] val left = pos - 1 in blocked || pos.col - 1 < 0 val right = pos + 1 in blocked || pos.col + 1 > 6 val prune = pos.up in blocked && pos - 1 in blocked && pos + 1 in blocked if (!prune) { result.add(pos) } } return result } private fun printBoard(rock: Set<Pos>, blocked: Set<Pos>) { println("==") val minRow = minOf(blocked.minOf { it.row }, minOf(rock.minOf { it.row })) for (row in (minRow..0)) { println(row.toString().padStart(3, ' ') + (0..6).joinToString("") { when (Pos(row, it)) { in blocked -> "#" in rock -> "@" else -> "." } }) } } fun Set<Pos>.move(value: Char, blocked: Set<Pos>): Set<Pos>? = when (value) { '>' -> { val next = map { it + 1 }.toSet() if ((next intersect blocked).isNotEmpty() || next.any { it.col > 6 } ) this else next } '<' -> { val next = map { it - 1 }.toSet() if ((next intersect blocked).isNotEmpty() || next.any { it.col < 0 }) this else next } 'v' -> { val next = map { it.down }.toSet() if ((next intersect blocked).isNotEmpty()) null else next } else -> throw IllegalArgumentException("Unknown jet push $value") } tailrec fun rock(value: Long, bottomRow: Int): Set<Pos> { val pos = Pos(bottomRow - 4, 2) return when (value) { 0L -> setOf(pos, pos + 1, pos + 2, pos + 3) 1L -> setOf(pos.up, pos + 1, (pos + 1).up, (pos + 2).up, (pos + 1).up.up) 2L -> setOf(pos, pos + 1, pos + 2, (pos + 2).up, (pos + 2).up.up) 3L -> setOf(pos, pos.up, pos.up.up, pos.up.up.up) 4L -> setOf(pos, pos.up, pos + 1, (pos + 1).up) else -> rock(value % 5, bottomRow) } } }
0
Kotlin
0
0
da4b9d894acf04eb653dafb81a5ed3802a305901
4,664
aoc
MIT License
src/aoc22/Day21.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc22.day21 import kotlin.math.sign import lib.Solution import lib.Strings.isLong enum class Operation(val symbol: String, val op: (Long, Long) -> Long) { ADD("+", Long::plus), SUBTRACT("-", Long::minus), MULTIPLY("*", Long::times), DIVIDE("/", Long::div), // Using minus here to measure how far off we are from the equality. EQUALS("=", Long::minus); fun apply(a: Long, b: Long): Long = op(a, b) companion object { fun parse(symbol: String): Operation = values().first { it.symbol == symbol } } } sealed interface Job { data class FixedNumber(val num: Long) : Job data class RunOperation(val op: Operation, val op1: String, val op2: String) : Job companion object { fun parse(jobStr: String): Job = if (jobStr.isLong()) { FixedNumber(jobStr.toLong()) } else { val (op1, op, op2) = jobStr.split(" ") RunOperation(Operation.parse(op), op1, op2) } } } data class Monkey(val name: String, val job: Job) { companion object { fun parse(monkeyStr: String): Monkey { val (name, jobPart) = monkeyStr.split(": ") return Monkey(name, Job.parse(jobPart)) } } } typealias Input = List<Monkey> typealias Output = Long private val solution = object : Solution<Input, Output>(2022, "Day21") { override fun parse(input: String): Input { return input.lines().map { Monkey.parse(it) } } override fun format(output: Output): String { return "$output" } override fun part1(input: Input): Output { val monkeyMap = input.associateBy { it.name } val cachedResults = mutableMapOf<String, Long>() fun calcResult(monkeyName: String): Long { return cachedResults[monkeyName] ?: run { val (name, job) = monkeyMap[monkeyName] ?: error("Unknown monkey: $monkeyName") when (job) { is Job.FixedNumber -> job.num is Job.RunOperation -> { job.op.apply(calcResult(job.op1), calcResult(job.op2)) } }.also { cachedResults[name] = it } } } return calcResult("root") } override fun part2(input: Input): Output { val monkeys = input.toMutableList() // Update root job to be an equals operation. val rootIdx = monkeys.indexOfFirst { it.name == "root" } val root = monkeys[rootIdx] val rootJob = root.job as? Job.RunOperation ?: error("Root job should not be a fixed number.") monkeys[rootIdx] = root.copy(job = rootJob.copy(op = Operation.EQUALS)) // Check the root value with the humn number. If the result is 0, then we have the right number. fun check(humnNum: Long): Long { val humnIdx = monkeys.indexOfFirst { it.name == "humn" } val humn = monkeys[humnIdx] monkeys[humnIdx] = humn.copy(job = Job.FixedNumber(humnNum)) return part1(monkeys) } var queryRange = -1L..1L // Expansion phase. Keep increasing the range until we have different signs for the result. while (check(queryRange.first).sign == check(queryRange.last).sign) { queryRange = queryRange.first * 2..queryRange.last * 2 } // Binary search phase. Keep shrinking the range until we have the right number. while (queryRange.first != queryRange.last) { val lowValue = check(queryRange.first) val highValue = check(queryRange.last) val mid = (queryRange.first + queryRange.last) / 2 val midValue = check(mid) if (midValue == 0L) { return mid } queryRange = if (lowValue.sign != midValue.sign) { queryRange.first..mid } else if (highValue.sign != midValue.sign) { mid..queryRange.last } else { error("Invalid state. The result should have different signs in both ends of the range") } } error("Could not find the solution.") } } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
3,886
aoc-kotlin
Apache License 2.0
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day03/EngineSchematic.kt
Gentleman1983
737,309,232
false
{"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319}
package de.havox_design.aoc2023.day03 import de.havox_design.aoc.utils.kotlin.model.positions.Position2d import java.lang.IllegalArgumentException class EngineSchematic(input: List<String>) { private val schematic = ArrayList<List<Point>>() private val partNumbers = HashSet<PartNumber>() private val gears = HashSet<Pair<Point, Long>>() init { buildSchematics(input) collectPartNumbers() collectGears() } fun sumOfPartNumbers(): Long = partNumbers .sumOf { partNumber -> partNumber.getValue() } fun sumOfGearRatios(): Long = gears .sumOf { gear -> gear.second } private fun buildSchematics(input: List<String>) { for (y: Int in input.indices) { val dataRow = input[y] val row = ArrayList<Point>() for (x: Int in dataRow.indices) { val symbol = dataRow[x] row.add(Point(Position2d(x,y), symbol)) } schematic.add(row) } } private fun collectPartNumbers() { for (y: Int in schematic.indices) { val row = schematic[y] for (x: Int in row.indices) { val currentElement = row[x] if (currentElement.isNumber() && ((isOnGrid(currentElement.getLeftNeighborCoordinate()) && !getPosition(currentElement.getLeftNeighborCoordinate()).isNumber()) || !isOnGrid(currentElement.getLeftNeighborCoordinate())) ) { val potentialPartNumber = detectPartNumber(currentElement) if (potentialPartNumber != null) { partNumbers.add(potentialPartNumber) } } } } } @SuppressWarnings("kotlin:S3776") private fun collectGears() { for (y: Int in schematic.indices) { val row = schematic[y] for (x: Int in row.indices) { val currentElement = row[x] if (currentElement.isGearSymbol()) { val neighboringPartNumbers = currentElement .getNeighboringCoordinates() .filter { coordinate -> isOnGrid(coordinate) } .map { coordinate -> getPosition(coordinate) } .filter { point -> point.isNumber() } .toSet() val parts = HashSet<PartNumber>() for (point: Point in neighboringPartNumbers) { partNumbers .filter { partNumber -> partNumber.containsPoint(point) } .forEach { partNumber -> parts.add(partNumber) } } if (parts.size > 1) { var gearRatio = 1L for (partNumber: PartNumber in parts) { gearRatio *= partNumber.getValue() } gears.add(Pair(currentElement, gearRatio)) } } } } } private fun detectPartNumber(point: Point): PartNumber? { val partNumber = ArrayList<Point>() partNumber.add(point) var currentPoint = point do { if ( isOnGrid(currentPoint.getRightNeighborCoordinate()) && getPosition(currentPoint.getRightNeighborCoordinate()).isNumber() ) { currentPoint = getPosition(currentPoint.getRightNeighborCoordinate()) partNumber.add(currentPoint) } else { break } } while (true) var neighboringSymbol = false for (current: Point in partNumber) { neighboringSymbol = neighboringSymbol || current .getNeighboringCoordinates() .filter { position -> isOnGrid(position) } .map { position -> getPosition(position) } .any { p -> p.isSymbol() } } if (neighboringSymbol) { return PartNumber(partNumber) } return null } private fun isOnGrid(position: Position2d<Int>): Boolean = position.y >= 0 && position.y < schematic.size && position.x >= 0 && position.x < schematic[0].size private fun getPosition(position: Position2d<Int>): Point { if (isOnGrid(position)) { return schematic[position.y][position.x] } throw IllegalArgumentException("Position '$position' not on schematic.") } }
4
Kotlin
0
1
35ce3f13415f6bb515bd510a1f540ebd0c3afb04
4,732
advent-of-code
Apache License 2.0
src/main/kotlin/Problem17.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import kotlin.math.floor /** * Number letter counts * * If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 * letters used in total. * * If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? * * NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one * hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British * usage. * * https://projecteuler.net/problem=17 */ fun main() { println(numberLetterCount(115)) println(numberLetterCount(342)) println(sumNumberLetterCounts(5)) println(sumNumberLetterCounts(1_000)) } private fun sumNumberLetterCounts(max: Int): Int = (1..max).sumOf(::numberLetterCount) private fun numberLetterCount(number: Int): Int { if (number < 100) return below100(number) var res = 0; val h = floor(number / 100f) % 10 val t = floor(number / 1000f).toInt() val s = number % 100 if (number > 999) { res += below100(t) + "thousand".length } if (h != 0f) { res += proper[h.toInt()] + "hundred".length } if (s != 0) { res += "and".length + below100(s) } return res } // Returns the length of the numbers between 0 and 99 private fun below100(n: Int): Int = if (n < 20) proper[n] else tenth[n / 10 - 2] + proper[n % 10] // proper nouns private val proper = arrayOf( 0, "one".length, "two".length, "three".length, "four".length, "five".length, "six".length, "seven".length, "eight".length, "nine".length, "ten".length, "eleven".length, "twelve".length, "thirteen".length, "fourteen".length, "fifteen".length, "sixteen".length, "seventeen".length, "eighteen".length, "nineteen".length, ) // tenth prefixes private val tenth = arrayOf( "twenty".length, "thirty".length, "forty".length, "fifty".length, "sixty".length, "seventy".length, "eighty".length, "ninety".length, )
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
2,159
project-euler
MIT License
src/main/kotlin/day18/CoolPair.kt
cyril265
433,772,262
false
{"Kotlin": 39445, "Java": 4273}
package day18 import kotlin.math.ceil import kotlin.math.floor data class CoolPair(var left: PairComponent, var right: PairComponent) : PairComponent { operator fun plus(other: CoolPair): CoolPair { val newPair = CoolPair(this, other) reduce(newPair) return newPair } fun explode(): Boolean { val digitList = digits() val pairToExplode = digitList .firstOrNull { it.depth >= 4 } ?.parent if (pairToExplode != null) { val leftIndex = digitList.indexOfFirst { it.pair === pairToExplode.left } val leftDigit = digitList.getOrNull(leftIndex - 1)?.pair val rightDigit = digitList.getOrNull(leftIndex + 2)?.pair if (leftDigit != null) { leftDigit.number += (pairToExplode.left as Digit).number } if (rightDigit != null) { rightDigit.number += (pairToExplode.right as Digit).number } val parent = parentOf(this, pairToExplode) if (parent != null) { val zeroDigit = Digit(0) if (parent.left === pairToExplode) parent.left = zeroDigit else if (parent.right == pairToExplode) parent.right = zeroDigit } } return pairToExplode != null } fun split(): Boolean { val digitList = digits().map { it.pair } val digit = digitList.firstOrNull { it.number >= 10 } if (digit != null) { val divisionResult = digit.number / 2.0 val left = floor(divisionResult).toInt() val right = ceil(divisionResult).toInt() val parent = parentOf(this, digit) val newPair = CoolPair(Digit(left), Digit(right)) checkNotNull(parent) { "Parent shall not be null" } if (parent.left === digit) { parent.left = newPair } else if (parent.right === digit) { parent.right = newPair } } return digit != null } override fun toString(): String { return "[$left, $right]" } private fun digits() = digits(this) fun magnitude() = magnitude(this) fun reduce() = reduce(this) } private fun reduce(pair: CoolPair) { while (pair.explode() || pair.split()) { } } private fun digits(el: PairComponent, depth: Int = -1, parent: PairComponent? = null): List<PairDepth> { val result = mutableListOf<PairDepth>() val newDepth = depth + 1 return if (el is CoolPair) { result += digits(el.left, newDepth, el) result += digits(el.right, newDepth, el) result } else { listOf(PairDepth(el as Digit, depth, parent as CoolPair)) } } private fun magnitude(pair: CoolPair): Long { val left = pair.left val right = pair.right val leftResult = if (left is Digit) { left.number * 3L } else { magnitude(left as CoolPair) * 3L } val rightResult = if (right is Digit) { right.number * 2L } else { magnitude(right as CoolPair) * 2L } return leftResult + rightResult } private fun parentOf(current: CoolPair, el: PairComponent): CoolPair? { if (current.left === el || current.right === el) return current if (current.right is CoolPair) { val parent = parentOf(current.right as CoolPair, el) if (parent != null) { return parent } } if (current.left is CoolPair) { val parent = parentOf(current.left as CoolPair, el) if (parent != null) { return parent } } return null } private data class PairDepth(val pair: Digit, val depth: Int, val parent: CoolPair)
0
Kotlin
0
0
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
3,735
aoc2021
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfCommonFactors.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 dev.shtanko.algorithms.math.gcd /** * 2427. Number of Common Factors * @see <a href="https://leetcode.com/problems/number-of-common-factors/">Source</a> */ fun interface NumberOfCommonFactors { fun commonFactors(a: Int, b: Int): Int } class NumberOfCommonFactorsNaive : NumberOfCommonFactors { override fun commonFactors(a: Int, b: Int): Int { val listA = mutableListOf<Int>() val listB = mutableListOf<Int>() val result = mutableListOf<Int>() for (i in 1..a) { if (a % i == 0) { listA.add(i) } } for (i in 1..b) { if (b % i == 0) { listB.add(i) } } if (listA.size > listB.size) { listA.forEach { if (listB.contains(it) && listA.contains(it)) { result.add(it) } } } else { listB.forEach { if (listA.contains(it) && listB.contains(it)) { result.add(it) } } } return result.size } } class NumberOfCommonFactorsBruteForce : NumberOfCommonFactors { override fun commonFactors(a: Int, b: Int): Int { var ans = 1 for (i in 2..(a to b).gcd()) { if (a % i == 0 && b % i == 0) { ans++ } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,065
kotlab
Apache License 2.0
src/main/kotlin/hm/binkley/dice/rolling/KeepCount.kt
binkley
259,950,798
false
{"Kotlin": 89213, "Shell": 15649, "Batchfile": 9453}
package hm.binkley.dice.rolling import java.util.Objects.hash sealed class KeepCount(protected val value: Int) { override fun toString() = "${this::class.simpleName}($value)" override fun equals(other: Any?) = this === other || other is KeepCount && javaClass == other.javaClass && value == other.value override fun hashCode() = hash(javaClass, value) /** Splits sorted list of results into those to keep and those to drop. */ protected abstract fun partition(other: List<Int>): Pair<List<Int>, List<Int>> companion object { fun List<Int>.keep(count: KeepCount) = count.partition(this) } } /** * Keeps the highest dice rolls. */ class KeepHigh(value: Int) : KeepCount(value) { override fun partition(other: List<Int>): Pair<List<Int>, List<Int>> { val (kept, dropped) = other.withIndex().partition { (index, _) -> other.size - value <= index } return kept.withoutIndex() to dropped.withoutIndex() } } /** * Keeps the lower middle dice rolls. * When there are even/odd numbers of dice, and even/odd numbers to keep: * - Even / even -- middle low and high are the same * - Even /odd -- picks up an extra low roll * - Odd / even -- picks up an extra low roll * - Odd / odd -- middle low and high are the same */ class KeepMiddleLow(value: Int) : KeepMiddle(value) { override fun splitKeep(listEven: Boolean, keepEven: Boolean) = if (listEven && keepEven) value / 2 else value / 2 + 1 } /** * Keeps the upper middle dice rolls. * When there are even/odd numbers of dice, and even/odd numbers to keep: * - Even / even -- middle low and high are the same * - Even /odd -- picks up an extra high roll * - Odd / even -- picks up an extra high roll * - Odd / odd -- middle low and high are the same */ class KeepMiddleHigh(value: Int) : KeepMiddle(value) { override fun splitKeep(listEven: Boolean, keepEven: Boolean) = if (!listEven && !keepEven) value / 2 + 1 else value / 2 } abstract class KeepMiddle( value: Int, ) : KeepCount(value) { protected abstract fun splitKeep( listEven: Boolean, keepEven: Boolean, ): Int override fun partition(other: List<Int>): Pair<List<Int>, List<Int>> { if (0 == value || other.isEmpty()) return emptyList<Int>() to other val listEven = 0 == other.size % 2 val keepEven = 0 == value % 2 val lowerSize = if (listEven) other.size / 2 else other.size / 2 + 1 val lowerKeep = splitKeep(listEven, keepEven) val upperKeep = value - lowerKeep val (lower, upper) = other.keep(KeepLow(lowerSize)) val (lowerKept, lowerDropped) = lower.keep(KeepHigh(lowerKeep)) val (upperKept, upperDropped) = upper.keep(KeepLow(upperKeep)) return (lowerKept + upperKept) to (lowerDropped + upperDropped) } } /** * Keeps the lowest dice rolls. */ class KeepLow(value: Int) : KeepCount(value) { override fun partition(other: List<Int>): Pair<List<Int>, List<Int>> { val (kept, dropped) = other.withIndex().partition { (index, _) -> value > index } return kept.withoutIndex() to dropped.withoutIndex() } } private fun <T> List<IndexedValue<T>>.withoutIndex() = map { (_, it) -> it }
12
Kotlin
0
0
072d4cb675862a79616d2dea3149a2b3794d2737
3,352
kotlin-dice
The Unlicense
leetcode/src/offer/middle/Offer12.kt
zhangweizhe
387,808,774
false
null
package offer.middle fun main() { val i:Int i=30 println(i) // 剑指 Offer 12. 矩阵中的路径 // https://leetcode.cn/problems/ju-zhen-zhong-de-lu-jing-lcof/ val ca1 = charArrayOf('A', 'B', 'C', 'E') val ca2 = charArrayOf('S', 'F', 'C', 'S') val ca3 = charArrayOf('A', 'D', 'E', 'E') val board = Array<CharArray>(3) { when(it) { 0 -> ca1 1 -> ca2 2 -> ca3 else -> charArrayOf() } } println(exist(board, "ABCCED")) } fun exist(board: Array<CharArray>, word: String): Boolean { if (board.isEmpty()) { return word.isEmpty() } val rowCount = board.size val columnCount = board[0].size for (i in 0 until rowCount) { for (j in 0 until columnCount) { // 遍历矩阵中的每个元素,对每个元素执行递归,如果其中一个满足条件,就返回 if (help(board, rowCount, columnCount, i, j, word, 0)) { return true } } } return false } private fun help(board: Array<CharArray>, rowCount: Int, columnCount: Int, i: Int, j: Int, word: String, wordIndex: Int): Boolean { if (wordIndex == word.length) { // 找到了满足条件的路径,返回 true return true } if (i < 0 || i >= rowCount) { // 水平方向越界,返回 false return false } if (j < 0 || j >= columnCount) { // 竖直方向越界,返回 false return false } if (word[wordIndex] == board[i][j]) { // 遍历到的元素 == word[wordIndex],递归判断上下左右的四个元素是否 == word[wordIndex + 1] // 先把当前元素置为特殊字符,避免递归过程中往回找 board[i][j] = '0' val b = (help(board, rowCount, columnCount, i, j - 1, word, wordIndex + 1) || help(board, rowCount, columnCount, i - 1, j, word, wordIndex + 1) || help(board, rowCount, columnCount, i, j + 1, word, wordIndex + 1) || help(board, rowCount, columnCount, i + 1, j, word, wordIndex + 1)) // 递归结束,恢复该字符 board[i][j] = word[wordIndex] return b } return false }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
2,257
kotlin-study
MIT License
src/net/sheltem/aoc/y2022/Day15.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2022 import kotlin.math.absoluteValue suspend fun main() { Day15().run() } class Day15 : Day<Long>(0, 24) { override suspend fun part1(input: List<String>): Long = input.map { it.toSensorAndBeacon() }.toCaveMap(2000000).countInRow(2000000).toLong() override suspend fun part2(input: List<String>): Long = input.map { it.toSensorAndBeacon() }.findHole(4000000) //.also { println("Candidate: ${it.first}, ${it.second}") } .toFrequency() } private fun List<Pair<Pair<Int, Int>, Pair<Int, Int>>>.findHole(searchSize: Int) = firstNotNullOf { it.perimeter(0..searchSize).check(this) } private fun Set<Pair<Int, Int>>.check(pairs: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>): Pair<Int, Int>? = firstOrNull { point -> pairs.none { it.canReach(point) } } private fun Pair<Pair<Int, Int>, Pair<Int, Int>>.canReach(point: Pair<Int, Int>): Boolean = first.distance(second) >= first.distance(point) private fun Pair<Pair<Int, Int>, Pair<Int, Int>>.perimeter(searchRange: IntRange): Set<Pair<Int, Int>> { val result = mutableSetOf<Pair<Int, Int>>() val sensor = this.first val distance = sensor.distance(this.second) for (diff in -(distance + 1)..(distance + 1)) { val counterdiff = distance + 1 - diff.absoluteValue val x = sensor.first + diff if (x in searchRange) { if (sensor.second - counterdiff in searchRange) result.add(x to sensor.second - counterdiff) if (sensor.second + counterdiff in searchRange) result.add(x to sensor.second + counterdiff) } } return result } private fun Pair<Int, Int>.toFrequency() = first * 4000000L + second private fun Map<Pair<Int, Int>, Content>.countInRow(row: Int): Int = this.entries.count { it.key.second == row && it.value == Content.NOTHING } private fun String.toSensorAndBeacon(): Pair<Pair<Int, Int>, Pair<Int, Int>> { val sensor = this.substringBefore(":").substringAfter("x=").replace("y=", "").split(",").toDataPair() val beacon = this.substringAfterLast("x=").replace("y=", "").split(",").toDataPair() return sensor to beacon } private fun List<Pair<Pair<Int, Int>, Pair<Int, Int>>>.toCaveMap(interestingRow: Int): Map<Pair<Int, Int>, Content> { val caveMap = mutableMapOf<Pair<Int, Int>, Content>() for (pair in this) { caveMap.computeContent(pair.first, pair.second, interestingRow) } return caveMap } private fun MutableMap<Pair<Int, Int>, Content>.computeContent(sensor: Pair<Int, Int>, beacon: Pair<Int, Int>, interestingRow: Int) { this[sensor] = Content.SENSOR this[beacon] = Content.BEACON val emptyPositions = spanArea(sensor, sensor.distance(beacon), interestingRow) for (position in emptyPositions) { this.putIfAbsent(position, Content.NOTHING) } } private fun spanArea(point: Pair<Int, Int>, range: Int, interestingRow: Int): List<Pair<Int, Int>> = buildList { for (x in (point.first - range)..(point.first + range)) { val target = x to interestingRow if (target.distance(point) <= range) { add(target) } } } private fun Pair<Int, Int>.distance(other: Pair<Int, Int>) = (first - other.first).absoluteValue + (second - other.second).absoluteValue private fun List<String>.toDataPair() = this[0].trim().toInt() to this[1].trim().toInt() private enum class Content { SENSOR, BEACON, NOTHING; }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
3,455
aoc
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2022/Day23.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import ru.timakden.aoc.util.Point import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import ru.timakden.aoc.year2022.Day23.Direction.* import ru.timakden.aoc.year2022.Day23.Elf.Companion.fillProposedPositions import ru.timakden.aoc.year2022.Day23.Elf.Companion.move import ru.timakden.aoc.year2022.Day23.Elf.Companion.toElves /** * [Day 23: Unstable Diffusion](https://adventofcode.com/2022/day/23). */ object Day23 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day23") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Int { val elves = input.toElves() val iterator = directionIterator() repeat(10) { elves.fillProposedPositions(iterator.next()) elves.move() } val height = (elves.minOf { it.position.y }..elves.maxOf { it.position.y }).count() val width = (elves.minOf { it.position.x }..elves.maxOf { it.position.x }).count() return height * width - elves.count() } fun part2(input: List<String>): Int { val elves = input.toElves() var round = 1 val iterator = directionIterator() while (true) { elves.fillProposedPositions(iterator.next()) if (elves.all { it.proposedPositions.isEmpty() || it.proposedPositions.size == 4 }) break elves.move() round++ } return round } private fun directionIterator() = iterator { while (true) { yieldAll( listOf( listOf(NORTH, SOUTH, WEST, EAST), listOf(SOUTH, WEST, EAST, NORTH), listOf(WEST, EAST, NORTH, SOUTH), listOf(EAST, NORTH, SOUTH, WEST) ) ) } } private data class Elf(var position: Point) { var proposedPositions: MutableList<Point> = mutableListOf() fun proposePosition(elves: List<Elf>, direction: Direction) = when (direction) { EAST -> { val adjacentPositions = listOf( Point(position.x + 1, position.y), Point(position.x + 1, position.y - 1), Point(position.x + 1, position.y + 1), ) if (elves.any { it.position in adjacentPositions }) null else Point(position.x + 1, position.y) } NORTH -> { val adjacentPositions = listOf( Point(position.x, position.y - 1), Point(position.x - 1, position.y - 1), Point(position.x + 1, position.y - 1) ) if (elves.any { it.position in adjacentPositions }) null else Point(position.x, position.y - 1) } SOUTH -> { val adjacentPositions = listOf( Point(position.x, position.y + 1), Point(position.x - 1, position.y + 1), Point(position.x + 1, position.y + 1) ) if (elves.any { it.position in adjacentPositions }) null else Point(position.x, position.y + 1) } WEST -> { val adjacentPositions = listOf( Point(position.x - 1, position.y), Point(position.x - 1, position.y - 1), Point(position.x - 1, position.y + 1), ) if (elves.any { it.position in adjacentPositions }) null else Point(position.x - 1, position.y) } } companion object { fun List<String>.toElves(): MutableList<Elf> { val elves = mutableListOf<Elf>() this.forEachIndexed { row, s -> s.forEachIndexed { column, c -> if (c == '#') elves += Elf(Point(column, row)) } } return elves } fun List<Elf>.fillProposedPositions(directions: List<Direction>) { this.forEach { elf -> for (direction in directions) { val proposedPosition = elf.proposePosition(this, direction) if (proposedPosition != null) { elf.proposedPositions += proposedPosition } } } } fun List<Elf>.move() { this.forEach { elf -> if (elf.proposedPositions.size in 1..3) { val proposedPosition = elf.proposedPositions.first() val otherElves = this - elf if (otherElves.none { it.proposedPositions.size in 1..3 && it.proposedPositions.first() == proposedPosition }) elf.position = proposedPosition } } this.forEach { it.proposedPositions = mutableListOf() } } } } private enum class Direction { EAST, NORTH, SOUTH, WEST } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
5,332
advent-of-code
MIT License
kotlin/src/com/daily/algothrim/leetcode/CountNodes.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode import java.util.* /** * 222. 完全二叉树的节点个数 * * 给出一个完全二叉树,求出该树的节点个数。 * * 说明: * 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。 * */ class CountNodes { companion object { @JvmStatic fun main(args: Array<String>) { println(CountNodes().solution(TreeNode(1).apply { left = TreeNode(2).apply { left = TreeNode(4) right = TreeNode(5) } right = TreeNode(3).apply { left = TreeNode(6) } })) println() println(CountNodes().solution2(TreeNode(1).apply { left = TreeNode(2).apply { left = TreeNode(4) right = TreeNode(5) } right = TreeNode(3).apply { left = TreeNode(6) } })) } } fun solution(root: TreeNode?): Int { if (root == null) return 0 val deque = ArrayDeque<TreeNode>() var count = 0 deque.offer(root) while (deque.isNotEmpty()) { count++ val cur = deque.poll() cur.left?.let { deque.offer(it) } cur.right?.let { deque.offer(it) } } return count } fun solution2(root: TreeNode?): Int { if (root == null) return 0 val left = solution2(root.left) val right = solution2(root.right) return left + right + 1 } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,999
daily_algorithm
Apache License 2.0
src/Day17_2.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
import java.io.File import kotlin.math.max fun main() { fun Pair<Long, Long>.x(): Long{ return this.first } fun Pair<Long, Long>.y(): Long{ return this.second } class Shape(var points: MutableList<Pair<Long, Long>>){} fun Shape.rightmost(): Long{ return this.points.map { it.x() }.max() } fun Shape.leftmost(): Long{ return this.points.map { it.x() }.min() } fun Shape.lowest(): Long{ return this.points.map { it.y() }.min() } fun Shape.updateStart(floor: Long): Shape{ val leftref = this.leftmost() val lowref = this.lowest() for ((i, point) in this.points.withIndex()){ this.points[i] = Pair(point.x() -leftref+2, point.y() -lowref+floor) } return this } fun Shape.updateJet(dir: Char, chamber: MutableSet<Pair<Long, Long>>): Shape{ if ((dir == '>')&&(this.rightmost() < 6)) { // println("$dir ${this.points.map { chamber[it.x+1] == it.y }.toList().count{it}} $chamber") if (this.points.map { Pair(it.x()+1, it.y()) in chamber }.toList().count{it} == 0) { for ((i, point) in this.points.withIndex()) { this.points[i] = Pair(point.x() + 1, point.y()) } return this } else return this } else if ((dir == '<')&&(this.leftmost() > 0)){ // println("$dir ${this.points.map { chamber[it.y][it.x - 1] == 0 }.toList().count()} ${this.points.size}") if (this.points.map { Pair(it.x()-1, it.y()) in chamber }.toList().count{it} == 0) { for ((i, point) in this.points.withIndex()) { this.points[i] = Pair(point.x() - 1, point.y()) } return this } else return this } else return this } fun Shape.check(chamber: MutableSet<Pair<Long, Long>>): Boolean{ // println(this.points.map{chamber[it.y-1][it.x] == 1}.toList()) // println(this.points.map{chamber[it.y-1][it.x] == 1}.toList().all{it == false}) // chamber.map { print("chamber $it") } // this.points.map { print("checking... $it")} // println("${this.points.map { Pair(it.x(), it.y()-1) in chamber }.toList()}") return (this.points.map { Pair(it.x(), it.y()-1) in chamber }.toList().count{it} == 0) } fun Shape.updateFall(chamber: MutableSet<Pair<Long, Long>>): Pair<Boolean, Shape> { return if (!this.check(chamber)) Pair(false, this) else{ for ((i, point) in this.points.withIndex()){ this.points[i] = Pair(point.x(), point.y()-1) } Pair(true, this) } } fun MutableSet<Pair<Long, Long>>.update(shape: Shape): MutableSet<Pair<Long, Long>> { // shape.points.map { println("${it.x} ${it.y}") } for (point in shape.points){ this.add(point) } return this } fun part1(input: String){ var defaultShape = Shape(mutableListOf(Pair(2,0), Pair(3, 0), Pair(4,0), Pair(5,0))) var countShapes: Long = 0 var floor: Long = 0 var ystart: Long = 0 var actionCount: Long = 0 var savedAction: Int = 0 var savedShape: Int = 0 var savedState = mutableListOf<Long>() var chamber = mutableSetOf<Pair<Long, Long>>() for (i in 0..6){chamber.add(Pair(i.toLong(), 0.toLong()))} val shapes = mutableMapOf<Int, Shape>() shapes[0] = Shape(mutableListOf(Pair(2,0), Pair(3, 0), Pair(4,0), Pair(5,0))) shapes[1] = Shape(mutableListOf(Pair(2,1), Pair(3, 1), Pair(4,1), Pair(3,0), Pair(3, 2))) shapes[2] = Shape(mutableListOf(Pair(2,0), Pair(3, 0), Pair(4,0), Pair(4,1), Pair(4, 2))) shapes[3] = Shape(mutableListOf(Pair(2,0), Pair(2, 1), Pair(2,2), Pair(2,3))) shapes[4] = Shape(mutableListOf(Pair(2,0), Pair(3, 0), Pair(2,1), Pair(3,1))) stop@while (countShapes < 750000){ // println("number of shapes $countShapes, key of shape: ${countShapes % 5}") var shape = shapes.getOrDefault((countShapes % 5).toInt(), defaultShape) // println("check floor ${IntRange(0, 6).map{j -> chamber.map { it[j] }.toList().indexOfLast { it > 0 }}.toList()}") floor = chamber.map { it.y() }.toList().max() ystart = floor + 4 shape = shape.updateStart(ystart.toLong()) // println("starting shape ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}") var moveFlag = true move@while (moveFlag){ for (action in listOf("jet", "fall")){ when (action) { "jet" -> { // println("${input[actionCount % input.length]}") // println("shape befor action ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}") shape = shape.updateJet(input[(actionCount % input.length).toInt()], chamber) // println("shape after action ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}") moveFlag = shape.check(chamber) // println("move? $moveFlag") actionCount++ if (!moveFlag){ chamber = chamber.update(shape) break@move } if (shape.lowest() < 0) break@stop } "fall" -> { // println(action) // println("shape befor action ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}") var res = shape.updateFall(chamber) moveFlag = res.first shape = res.second // println("shape after action ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}") // println("move? $moveFlag") if (!moveFlag){ chamber = chamber.update(shape) break@move } if (shape.lowest() < 0) break@stop } } } } countShapes++ var maxHeight = IntRange(0,6).map{index ->chamber.filter { it.x().toInt() == index }.map { elem -> elem.y() }.toList().max().toLong()}.toList() if (countShapes.toInt() == 560){ savedAction = ((actionCount - 1) % input.length).toInt() savedShape = ((countShapes - 1) % 5).toInt() savedState = maxHeight.map { it - maxHeight.min() }.toMutableList() println("saved action $savedAction, saved shape $savedShape saved state $savedState") } else if (countShapes > 560.toLong()){ var currentAction = ((actionCount - 1) % input.length).toInt() var currentShape = ((countShapes - 1) % 5).toInt() var currentState = maxHeight.map { it - maxHeight.min() }.toList() // println("$savedShape $currentShape $savedAction $currentAction $savedState $currentState") // if ((currentShape == savedShape)&&(currentAction == savedAction)&&(currentState == savedState)){ // println("found duplicate! $countShapes $maxHeight") // } } // var maxHeight = IntRange(0,6).map{index ->chamber.filter { it.x().toInt() == index }.map { elem -> elem.y() }.toList().max().toLong()}.toList() // if (maxHeight.zipWithNext().map { it.first == it.second }.toList().count { it } == 7) {println("$maxHeight $countShapes")} // поиск ещё одного ровного пола, не нашёл if ((countShapes % 1000.toLong()) == 0.toLong()){ var maxHeight = IntRange(0,6).map{index ->chamber.filter { it.x().toInt() == index }.map { elem -> elem.y() }.toList().max().toLong()}.toList() for (i in 0..6){ chamber = chamber.subtract(chamber.filter { (it.x().toInt() == i)&&(it.y() < maxHeight[i]-1000) }.toMutableSet()) as MutableSet<Pair<Long, Long>> } // for (index in 0..6){ // println("$countShapes ${IntRange(0,6).map{index ->chamber.filter { it.x().toInt() == index }.map { elem -> elem.y() }.toList().max()}.toList()}") } if (countShapes % 1725.toLong() == 0.toLong()){ var maxHeight = IntRange(0,6).map{index ->chamber.filter { it.x().toInt() == index }.map { elem -> elem.y() }.toList().max().toLong()}.toList() println("1725 divider $countShapes, ${maxHeight.max()} ${maxHeight.min()} ${maxHeight.map { it - maxHeight.min() }.toList()}, ${((actionCount - 1) % input.length).toInt()}, ${((countShapes - 1) % 5).toInt()}") } if (countShapes % 1725.toLong() == 1600.toLong()){ var maxHeight = IntRange(0,6).map{index ->chamber.filter { it.x().toInt() == index }.map { elem -> elem.y() }.toList().max().toLong()}.toList() println("1600 divider $countShapes, ${maxHeight.max()} ${maxHeight.min()} ${maxHeight.map { it - maxHeight.min() }.toList()}, ${((actionCount - 1) % input.length).toInt()}, ${((countShapes - 1) % 5).toInt()}") } } println(chamber.map { it.y() }.toList().max()) // println(chamber.filter { it.y > 20 }) } // test if implementation meets criteria from the description, like: val testInput = File("src", "Day17.txt").readText() part1(testInput) // println(testInput.length) // println("${testInput.length * 5}") // part2(testInput) val input = readInput("Day17") // part1(testInput) // part2(input) }
0
Kotlin
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
10,074
aoc22
Apache License 2.0
src/Day08.kt
GarrettShorr
571,769,671
false
{"Kotlin": 82669}
fun main() { fun part1(input: List<String>): Int { val forest = input.map { it.chunked(1).map { it.toInt() } } // val forest2 = input.map { it.map { it.digitToInt() } } println(forest) val visible = mutableSetOf<Pair<Int, Int>>() val width = forest[0].size val height = forest.size //outside edges for(i in forest[0].indices) { visible.add(Pair(0, i)) visible.add(Pair(height-1, i)) } for(i in forest.indices) { visible.add(Pair(i, 0)) visible.add(Pair(i, width - 1)) } // looking left, right, top, bottom for(row in 1 until forest.size) { var tallest = forest[row][0] for(col in 1 until forest[0].size) { if(forest[row][col] > tallest) { visible.add(Pair(row, col)) tallest = forest[row][col] } } } for(row in 1 until forest.size) { var tallest = forest[row][width-1] for(col in forest[0].size-1 downTo 1) { if(forest[row][col] > tallest) { visible.add(Pair(row, col)) tallest = forest[row][col] } } } for(col in 1 until forest[0].size) { var tallest = forest[0][col] for(row in 1 until forest.size) { if(forest[row][col] > tallest) { visible.add(Pair(row, col)) tallest = forest[row][col] } } } for(col in 1 until forest[0].size) { var tallest = forest[height-1][col] for(row in forest.size-1 downTo 1) { if(forest[row][col] > tallest) { visible.add(Pair(row, col)) tallest = forest[row][col] } } } return visible.size } fun part2(input: List<String>): Int { val forest = input.map { it.chunked(1).map { it.toInt() } } val width = forest[0].size val height = forest.size var maxScore = 0 for(row in forest.indices) { for(col in forest.indices) { val treeHeight = forest[row][col] var count = 0 var score = 1 // look up for(r in row-1 downTo 0) { count++ if(forest[r][col] >= treeHeight) { break } } score *= count count = 0 // look down for(r in row+1 until height) { count++ if(forest[r][col] >= treeHeight) { break } } score *= count println("row $row col $col tree: ${forest[row][col]} score: $score count: $count") count = 0 // look left for(c in col-1 downTo 0) { count++ if(forest[row][c] >= treeHeight) { break } } score *= count count = 0 // look right for(c in col+1 until width) { count++ if(forest[row][c] >= treeHeight) { break } } score *= count if(score > maxScore) { maxScore = score } } } return maxScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") println(part1(testInput)) // println(part2(testInput)) val input = readInput("Day08") // output(part1(input)) // output(part2(input)) }
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
3,256
AdventOfCode2022
Apache License 2.0
advent-of-code-2022/src/test/kotlin/Day 11 Monkey in the Middle.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import io.kotest.matchers.collections.shouldStartWith import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test /** 15:15 */ class `Day 11 Monkey in the Middle` { @Test fun parsing() { parse(testInput) shouldStartWith Monkey( items = listOf(79.toLong(), 98.toLong()), operation = Multiply(19.toLong()), testDivisible = 23, pass = 2, fail = 3, ) } @Test fun silverTestOneRound() { generateSequence(parse(testInput)) { round(it) } .onEach { monkeys -> println("--------------") monkeys.forEach { println("Monkey ${it.index}: ${it.items.joinToString()}") } } .drop(1) .take(1) .last() .map { it.items } shouldBe listOf( listOf(20, 23, 27, 26).map { it.toLong() }, listOf(2080, 25, 167, 207, 401, 1046), emptyList(), emptyList(), ) } @Test fun silverTestTwoRounds() { generateSequence(parse(testInput)) { round(it) } .onEach { monkeys -> println("--------------") monkeys.forEach { println("Monkey ${it.index}: ${it.items.joinToString()}") } } .drop(1) .take(2) .last() .map { it.items } shouldBe listOf( listOf(695, 10, 71, 135, 350), listOf(43, 49, 58, 55, 362), emptyList(), emptyList(), ) } @Test fun silverTest() { monkeyBusiness(parse(testInput)) shouldBe 10605 } @Test fun silver() { monkeyBusiness(parse(loadResource("day11"))) shouldBe 120756 } private fun monkeyBusiness(monkeys: List<Monkey>, rounds: Int = 20): Long = generateSequence(monkeys) { round(it) } .drop(1) .take(rounds) .last() .asSequence() .map { it.inspections } .sortedDescending() .take(2) .reduce { acc, inspections -> acc * inspections } private fun round(monkeys: List<Monkey>): List<Monkey> { return monkeys.fold(monkeys) { acc, monkey -> val (mutatedMonkey, passes) = monkeyRound(acc[monkey.index]) acc.map { otherMonkey -> if (otherMonkey.index == mutatedMonkey.index) mutatedMonkey else { val passedToThisMonkey = passes.filter { it.index == otherMonkey.index }.map { it.value } otherMonkey.copy(items = otherMonkey.items + passedToThisMonkey) } } .also { check(acc.sumOf { it.items.size } == monkeys.sumOf { it.items.size }) } } } data class Pass(val index: Int, val value: Long) private fun monkeyRound(monkey: Monkey): Pair<Monkey, List<Pass>> { val passes = monkey.items .map { item -> monkey.operation(item) / 3 } .map { item -> Pass( value = item, index = if (item.rem(monkey.testDivisible) == 0L) monkey.pass else monkey.fail) } check(passes.size == monkey.items.size) check(passes.none { it.index == monkey.index }) return monkey.copy( items = emptyList(), inspections = monkey.inspections + monkey.items.size, ) to passes } private fun parse(testInput: String): List<Monkey> { return testInput.split("\n\n").mapIndexed { index, string -> val lines = string.lines() val starting = lines[1].substringAfter(": ").split(", ").map { it.toLong() } val operation = lines[2].substringAfter("new = old ").let { when { it == "* old" -> Square it.startsWith("*") -> Multiply(it.substringAfter("* ").toLong()) it.startsWith("+") -> Add(it.substringAfter("+ ").toLong()) else -> error("") } } val test = lines[3].substringAfterLast(" ").toInt() val pass = lines[4].substringAfter(" monkey ").toInt() val fail = lines[5].substringAfter(" monkey ").toInt() Monkey(index, starting, operation, test, pass, fail) } } sealed class Operation : (Long) -> Long data class Multiply(val value: Long) : Operation() { override fun invoke(p1: Long): Long = p1 * value } data class Add(val value: Long) : Operation() { override fun invoke(p1: Long): Long = p1 + value } object Square : Operation() { override fun invoke(p1: Long): Long = p1 * p1 } data class Monkey( val index: Int = 0, val items: List<Long>, val operation: Operation, val testDivisible: Int, val pass: Int, val fail: Int, val inspections: Long = 0 ) private val testInput = """ Monkey 0: Starting items: 79, 98 Operation: new = old * 19 Test: divisible by 23 If true: throw to monkey 2 If false: throw to monkey 3 Monkey 1: Starting items: 54, 65, 75, 74 Operation: new = old + 6 Test: divisible by 19 If true: throw to monkey 2 If false: throw to monkey 0 Monkey 2: Starting items: 79, 60, 97 Operation: new = old * old Test: divisible by 13 If true: throw to monkey 1 If false: throw to monkey 3 Monkey 3: Starting items: 74 Operation: new = old + 3 Test: divisible by 17 If true: throw to monkey 0 If false: throw to monkey 1 """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
5,338
advent-of-code
MIT License