path
string
owner
string
repo_id
int64
is_fork
bool
languages_distribution
string
content
string
issues
float64
main_language
string
forks
int64
stars
int64
commit_sha
string
size
int64
name
string
license
string
src/main/kotlin/me/grison/aoc/y2020/Day19.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2020 import me.grison.aoc.* class Day19 : Day(19, 2020) { override fun title() = "Monster Messages" private val solutionKey = "0" override fun partOne() = findSolutions(loadRules()).let { solutions -> loadMessages().count { solutions[solutionKey]!!.regex().matches(it) } } override fun partTwo(): Any { val rules = loadRules() val resolved = findSolutions(rules) // replacement rules as per part 2 spec rules["8"] = "42 | 42 8" rules["11"] = "42 31 | 42 11 31" val solutionsSoFar: MutableSet<String> = mutableSetOf() // iterate until we cannot find a new solution (infinite loop) while (true) { var foundSolution = false iterateRules(rules, resolved) loadMessages().forEach { message -> if (message !in solutionsSoFar && resolved[solutionKey]!!.regex().matches(message)) { solutionsSoFar.add(message) foundSolution = true } } if (!foundSolution) return solutionsSoFar.size } } private fun loadRules(): MutableMap<String, String> = mutableMapOf<String, String>().let { rules -> rules().forEach { line -> rules[line.before(":")] = line.after(": ") } rules } // iterate on rules until the rule "0" can be fully resolved private fun findSolutions(rules: Map<String, String>) = mutableMapOf<String, String>().let { solutions -> while (solutionKey !in solutions.keys) { iterateRules(rules, solutions) } solutions } // build a map of regular expressions to match messages with later on private fun iterateRules(rules: Map<String, String>, solutions: MutableMap<String, String>) { rules.forEach { (number, rule) -> when { // this is an initial rule '"' in rule -> solutions[number] = rule.except('"') else -> { val ruleParts = rule.normalSplit(" ") val solved = ruleParts.except("|").all { it in solutions.keys } if (solved) { solutions[number] = "(" + ruleParts.map { it.or("|", solutions[it]) }.join() + ")" } } } } } private fun rules() = inputGroups[0].lines() private fun loadMessages() = inputGroups[1].lines() }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
2,516
advent-of-code
Creative Commons Zero v1.0 Universal
src/main/kotlin/year2021/day-13.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2021 import lib.Position import lib.aoc.Day import lib.aoc.Part fun main() { Day(13, 2021, PartA13(), PartB13()).run() } open class PartA13 : Part() { data class Paper(var points: List<Position>) { var width = points.maxOf { it[0] } + 1 var height = points.maxOf { it[1] } + 1 } sealed class Command { abstract fun fold(paper: Paper) } class FoldHorizontal(val y: Int) : Command() { override fun fold(paper: Paper) { paper.points = paper.points.map { if (it[1] > y) { val newY = y - (it[1] - y) Position.at(it[0], newY) } else { it } }.distinct() paper.height = y } } class FoldVertical(val x: Int) : Command() { override fun fold(paper: Paper) { paper.points = paper.points.map { if (it[0] > x) { val newX = x - (it[0] - x) Position.at(newX, it[1]) } else { it } }.distinct() paper.width = x } } private fun Command(line: String): Command { val regex = """.*([yx])=(\d+)""".toRegex() val matches = regex.find(line)!! return when (matches.groupValues[1]) { "x" -> FoldVertical(matches.groupValues[2].toInt()) "y" -> FoldHorizontal(matches.groupValues[2].toInt()) else -> throw IllegalArgumentException("unknown fold ${matches.groupValues[1]}") } } private lateinit var commands: List<Command> protected lateinit var paper: Paper override fun parse(text: String) { val (pointsText, commandsText) = text.split("\n\n") commands = commandsText.split("\n").map(::Command) val points = pointsText.split("\n").map { it.split(",") }.map { Position.at(it[0].toInt(), it[1].toInt()) } paper = Paper(points) } override fun compute(): String { commands = commands.take(1) doFolds() return paper.points.size.toString() } protected fun doFolds() { commands.forEach { it.fold(paper) } } override val exampleAnswer: String get() = "17" override val customExampleData: String? get() = """ 6,10 0,14 9,10 0,3 10,4 4,11 6,0 6,12 4,1 0,13 10,12 3,4 3,0 8,4 1,10 2,14 8,10 9,0 fold along y=7 fold along x=5 """.trimIndent() } class PartB13 : PartA13() { override fun compute(): String { doFolds() println() for (y in 0..<paper.height) { for (x in 0..<paper.width) { print(if (Position.at(x, y) !in paper.points) " " else "#") } println() } return "" } override val exampleAnswer: String get() = "" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
3,270
Advent-Of-Code-Kotlin
MIT License
src/day_7.kt
gardnerdickson
152,621,962
false
null
import java.io.File import java.util.regex.Matcher fun main(args: Array<String>) { val filename = "res/day_7_input.txt" val answer1 = Day7.part1(File(filename)) println("Part 1: $answer1") val answer2 = Day7.part2(File(filename), answer1) println("Part 2: $answer2") } object Day7 { fun part1(file: File): Int { val wires = mutableMapOf<String, Gate>() file.useLines { lines -> lines.map { Gate.parse(it) }.forEach { wires[it.target] = it } } return wires["a"]!!.evaluate(wires) } fun part2(file: File, a: Int): Int { val wires = mutableMapOf<String, Gate>() file.useLines { lines -> lines.map { Gate.parse(it) }.forEach { wires[it.target] = it } } wires["b"]!!.wireValue = a return wires["a"]!!.evaluate(wires) } } sealed class Gate(val target: String) { companion object { private val andRegex = Regex("(?<left>[\\w\\d]+) AND (?<right>[\\w\\d]+) -> (?<target>\\w+)").toPattern() private val orRegex = Regex("(?<left>[\\w\\d]+) OR (?<right>[\\w\\d]+) -> (?<target>\\w+)").toPattern() private val lshiftRegex = Regex("(?<left>[\\w\\d]+) LSHIFT (?<right>[\\d]+) -> (?<target>\\w+)").toPattern() private val rshiftRegex = Regex("(?<left>[\\w\\d]+) RSHIFT (?<right>[\\d]+) -> (?<target>\\w+)").toPattern() private val notRegex = Regex("NOT (?<source>[\\w]+) -> (?<target>\\w+)").toPattern() private val signalRegex = Regex("(?<source>[\\w\\d]+) -> (?<target>\\w+)").toPattern() operator fun Matcher.get(name: String): String { return this.group(name) } fun parse(instruction: String): Gate { var matcher = andRegex.matcher(instruction) if (matcher.matches()) { return AndGate(matcher["left"], matcher["right"], matcher["target"]) } matcher = orRegex.matcher(instruction) if (matcher.matches()) { return OrGate(matcher["left"], matcher["right"], matcher["target"]) } matcher = lshiftRegex.matcher(instruction) if (matcher.matches()) { return LshiftGate(matcher["left"], matcher["right"].toInt(), matcher["target"]) } matcher = rshiftRegex.matcher(instruction) if (matcher.matches()) { return RshiftGate(matcher["left"], matcher["right"].toInt(), matcher["target"]) } matcher = notRegex.matcher(instruction) if (matcher.matches()) { return NotGate(matcher["source"], matcher["target"]) } matcher = signalRegex.matcher(instruction) if (matcher.matches()) { return SignalGate(matcher["source"], matcher["target"]) } throw IllegalArgumentException("Instruction '$instruction' could not be parsed") } } var wireValue: Int? = null abstract fun evaluate(wires: Map<String, Gate>): Int } class AndGate(private val left: String, private val right: String, target: String) : Gate(target) { override fun evaluate(wires: Map<String, Gate>): Int { if (wireValue == null) { wireValue = (left.toIntOrNull() ?: wires[left]!!.evaluate(wires)) and (right.toIntOrNull() ?: wires[right]!!.evaluate(wires)) } return wireValue!!.toInt() } } class OrGate(private val left: String, private val right: String, target: String) : Gate(target) { override fun evaluate(wires: Map<String, Gate>): Int { if (wireValue == null) { wireValue = (left.toIntOrNull() ?: wires[left]!!.evaluate(wires)) or (right.toIntOrNull() ?: wires[right]!!.evaluate(wires)) } return wireValue!!.toInt() } } class LshiftGate(private val left: String, private val right: Int, target: String) : Gate(target) { override fun evaluate(wires: Map<String, Gate>): Int { if (wireValue == null) { wireValue = (left.toIntOrNull() ?: wires[left]!!.evaluate(wires)) shl right } return wireValue!!.toInt() } } class RshiftGate(private val left: String, private val right: Int, target: String) : Gate(target) { override fun evaluate(wires: Map<String, Gate>): Int { if (wireValue == null) { wireValue = (left.toIntOrNull() ?: wires[left]!!.evaluate(wires)) shr right } return wireValue!!.toInt(); } } class NotGate(private val source: String, target: String) : Gate(target) { override fun evaluate(wires: Map<String, Gate>): Int { if (wireValue == null) { wireValue = (source.toIntOrNull() ?: wires[source]!!.evaluate(wires)).inv() } return wireValue!!.toInt() } } class SignalGate(private val source: String, target: String) : Gate(target) { override fun evaluate(wires: Map<String, Gate>): Int { if (wireValue == null) { wireValue = source.toIntOrNull() ?: wires[source]!!.evaluate(wires) } return wireValue!!.toInt() } }
0
Kotlin
0
0
4a23ab367a87cae5771c3c8d841303b984474547
5,103
advent-of-code-2015
MIT License
day22/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
fun main() { val inputDepth = 5616 val inputTarget = GridPoint2d(x = 10, y = 785) val cave = Cave(inputDepth, inputTarget) println("Part I: the solution is ${cave.risk()}") println("Part II: the solution is ${cave.rescueTime()}") } class Cave(private val scanDepth: Int, private val scanTarget: GridPoint2d) { private val regionMap = mutableMapOf<GridPoint2d, RegionType>() private val erosionMap = mutableMapOf<GridPoint2d, Int>() private val geologicIndexMap = mutableMapOf<GridPoint2d, Int>() fun risk(): Int { var result = 0 for (y in 0..scanTarget.y) { for (x in 0..scanTarget.x) { result += regionAt(GridPoint2d(x, y)).ordinal } } return result } fun regionAt(point: GridPoint2d): RegionType { check(point.x >= 0 && point.y >= 0) { "Solid rock; cannot compute region type." } return regionMap[point] ?: RegionType.values()[(erosionAt(point) % 3)] .also { regionMap += point to it } } private fun erosionAt(point: GridPoint2d): Int { check(point.x >= 0 && point.y >= 0) { "Solid rock; cannot compute erosion." } return erosionMap[point] ?: ((geologicIndexAt(point) + scanDepth) % 20183) .also { erosionMap += point to it } } private fun geologicIndexAt(point: GridPoint2d): Int { check(point.x >= 0 && point.y >= 0) { "Solid rock; cannot compute geologic index." } return geologicIndexMap[point] ?: when { point.x == 0 && point.y == 0 -> 0 point == scanTarget -> 0 point.x == 0 -> (point.y * 48271) point.y == 0 -> (point.x * 16807) else -> erosionAt(point.shiftBy(dx = -1)) * erosionAt(point.shiftBy(dy = -1)) }.also { geologicIndexMap += point to it } } fun rescueTime(): Int { val firstNode = Node(point = GridPoint2d.origin, tool = Tool.TORCH) val targetNode = Node(point = scanTarget, tool = Tool.TORCH) val nodesToEvaluate = mutableSetOf<Node>().apply { this += firstNode } val evaluatedNodes = mutableSetOf<Node>() val gScores = mutableMapOf(firstNode to 0) fun heuristic(current: Node): Int { return current.point.l1DistanceTo(targetNode.point) } val fScores = mutableMapOf(firstNode to heuristic(firstNode)) while (nodesToEvaluate.isNotEmpty()) { val currentNode = nodesToEvaluate.minBy { fScores[it]!! }!! if (currentNode == targetNode) return fScores[currentNode]!! nodesToEvaluate.remove(currentNode) evaluatedNodes.add(currentNode) for ((node, distance) in currentNode.validNeighborCosts(this)) { if (node in evaluatedNodes) continue val tentativeGScore = gScores[currentNode]!! + distance if (node !in nodesToEvaluate) { nodesToEvaluate += node } else if (tentativeGScore >= gScores[node]!!) { continue } gScores[node] = tentativeGScore fScores[node] = gScores[node]!! + heuristic(node) } } throw IllegalStateException("Algorithm should terminate in while loop") } } data class Node(val point: GridPoint2d, val tool: Tool) { fun validNeighborCosts(cave: Cave): Map<Node, Int> { return validNeighborCosts { point -> cave.regionAt(point).allowedTools } } private fun validNeighborCosts(allowedTools: (GridPoint2d) -> Collection<Tool>): Map<Node, Int> { val newPointNeighbors = point .adjacentPoints() .filter { point -> point.x >= 0 } .filter { point -> point.y >= 0 } .map { point -> Node(point, tool) } .filter { (point, tool) -> tool in allowedTools(point) } val newToolNeighbors = allowedTools(point) .minus(tool) .map { newTool -> Node(point, newTool) } return mutableMapOf<Node, Int>().apply { putAll(newPointNeighbors.map { it to 1 }) putAll(newToolNeighbors.map { it to 7 }) } } }
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
4,377
AdventOfCode2018
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LatestDayToCross.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue /** * 1970. Last Day Where You Can Still Cross * @see <a href="https://leetcode.com/problems/last-day-where-you-can-still-cross/">Source</a> */ fun interface LatestDayToCross { operator fun invoke(row: Int, col: Int, cells: Array<IntArray>): Int } class DSU(n: Int) { var root: IntArray var size: IntArray init { root = IntArray(n) for (i in 0 until n) { root[i] = i } size = IntArray(n) { 1 } } fun find(x: Int): Int { if (root[x] != x) { root[x] = find(root[x]) } return root[x] } fun union(x: Int, y: Int) { var rootX = find(x) var rootY = find(y) if (rootX == rootY) { return } if (size[rootX] > size[rootY]) { val tmp = rootX rootX = rootY rootY = tmp } root[rootX] = rootY size[rootY] += size[rootX] } } /** * Approach 1: Binary Search + Breadth-First Search */ class LatestDayToCrossBSBFS : LatestDayToCross { private val directions = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) override operator fun invoke(row: Int, col: Int, cells: Array<IntArray>): Int { var left = 1 var right = row * col while (left < right) { val mid = right - (right - left) / 2 if (canCross(row, col, cells, mid)) { left = mid } else { right = mid - 1 } } return left } private fun canCross(row: Int, col: Int, cells: Array<IntArray>, day: Int): Boolean { val grid = Array(row) { IntArray(col) } val queue: Queue<IntArray> = LinkedList() for (i in 0 until day) { grid[cells[i][0] - 1][cells[i][1] - 1] = 1 } for (i in 0 until col) { if (grid[0][i] == 0) { queue.offer(intArrayOf(0, i)) grid[0][i] = -1 } } while (queue.isNotEmpty()) { val cur: IntArray = queue.poll() val r = cur[0] val c = cur[1] if (r == row - 1) { return true } for (dir in directions) { val newRow = r + dir[0] val newCol = c + dir[1] if (newRow in 0 until row && newCol >= 0 && newCol < col && grid[newRow][newCol] == 0) { grid[newRow][newCol] = -1 queue.offer(intArrayOf(newRow, newCol)) } } } return false } } /** * Approach 2: Binary Search + Depth-First Search */ class LatestDayToCrossBSDFS : LatestDayToCross { private val directions = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) override operator fun invoke(row: Int, col: Int, cells: Array<IntArray>): Int { var left = 1 var right = row * col while (left < right) { val mid = right - (right - left) / 2 if (canCross(row, col, cells, mid)) { left = mid } else { right = mid - 1 } } return left } private fun canCross(row: Int, col: Int, cells: Array<IntArray>, day: Int): Boolean { val grid = Array(row) { IntArray(col) } for (i in 0 until day) { val r = cells[i][0] - 1 val c = cells[i][1] - 1 grid[r][c] = 1 } for (i in 0 until day) { grid[cells[i][0] - 1][cells[i][1] - 1] = 1 } for (i in 0 until col) { if (grid[0][i] == 0 && dfs(grid, 0, i, row, col)) { return true } } return false } private fun dfs(grid: Array<IntArray>, r: Int, c: Int, row: Int, col: Int): Boolean { if (r < 0 || r >= row || c < 0 || c >= col || grid[r][c] != 0) { return false } if (r == row - 1) { return true } grid[r][c] = -1 for (dir in directions) { val newR = r + dir[0] val newC = c + dir[1] if (dfs(grid, newR, newC, row, col)) { return true } } return false } } /** * Approach 3: Disjoint Set Union (on land cells) */ class LatestDayToCrossDisjoint : LatestDayToCross { override operator fun invoke(row: Int, col: Int, cells: Array<IntArray>): Int { return performCross( row, col, cells, arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)), ) } } /** * Approach 4: Disjoint Set Union (on water cells) */ class LatestDayToCrossUnion : LatestDayToCross { override operator fun invoke(row: Int, col: Int, cells: Array<IntArray>): Int { val dsu = DSU(row * col + 2) val grid = Array(row) { IntArray(col) } val directions = arrayOf( intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(1, 1), intArrayOf(1, -1), intArrayOf(-1, 1), intArrayOf(-1, -1), ) for (i in 0 until row * col) { val r = cells[i][0] - 1 val c = cells[i][1] - 1 grid[r][c] = 1 val index1 = r * col + c + 1 directions.forEach { d -> val newR = r + d[0] val newC = c + d[1] val index2 = newR * col + newC + 1 if (newR in 0 until row && newC >= 0 && newC < col && grid[newR][newC] == 1) { dsu.union(index1, index2) } } if (c == 0) { dsu.union(0, index1) } if (c == col - 1) { dsu.union(row * col + 1, index1) } if (dsu.find(0) == dsu.find(row * col + 1)) { return i } } return -1 } } private fun performCross( row: Int, col: Int, cells: Array<IntArray>, directions: Array<IntArray>, ): Int { val dsu = DSU(row * col + 2) val grid = Array(row) { IntArray(col) } cells.indices.reversed().forEach { i -> val r = cells[i][0] - 1 val c = cells[i][1] - 1 grid[r][c] = 1 val index1 = r * col + c + 1 for (d in directions) { val newR = r + d[0] val newC = c + d[1] val index2 = newR * col + newC + 1 if (newR in 0 until row && newC >= 0 && newC < col && grid[newR][newC] == 1) { dsu.union(index1, index2) } } if (r == 0) { dsu.union(0, index1) } if (r == row - 1) { dsu.union(row * col + 1, index1) } if (dsu.find(0) == dsu.find(row * col + 1)) { return i } } return -1 }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
7,717
kotlab
Apache License 2.0
src/main/kotlin/at/doml/anc/lab2/MultiSearchers.kt
domagojlatecki
124,923,523
false
null
package at.doml.anc.lab2 import java.lang.Math.sqrt object MultiSearchers { private operator fun DoubleArray.minus(other: DoubleArray): DoubleArray { val new = DoubleArray(this.size) { i -> this[i] } for (i in this.indices) { new[i] -= other[i] } return new } private fun DoubleArray.norm(): Double = Math.sqrt(this.map { it * it }.sum()) private fun DoubleArray.add(other: DoubleArray): DoubleArray { val new = DoubleArray(this.size) { i -> this[i] } for (i in this.indices) { new[i] += other[i] } return new } private fun DoubleArray.add(value: Double): DoubleArray { val new = DoubleArray(this.size) { i -> this[i] } for (i in this.indices) { new[i] += value } return new } private operator fun Double.times(array: DoubleArray): DoubleArray { val new = DoubleArray(array.size) { i -> array[i] } for (i in array.indices) { new[i] *= this } return new } fun coordinateSearch(initialPoint: DoubleArray, fn: CountableFunction<DoubleArray>, precision: Double, h: Double, epsilon: DoubleArray, verbose: Boolean): DoubleArray { var x = initialPoint.copyOf() var xs = x while ((x - xs).norm() <= precision) { xs = x.copyOf() for (i in initialPoint.indices) { val prevCounts = fn.count val aFn: CountableFunction<Double> = CountableFunction { a -> fn(x.add(a * epsilon)) } val (start, end) = Algorithms.unimodalInterval(h, 0.0, aFn, verbose) val alphaMin = Algorithms.goldenSectionSearch(start, end, aFn, precision, verbose) x = x.add(alphaMin * epsilon[i]) fn.count = aFn.count + prevCounts } } return x } private fun calculateSimplexPoints(initialPoint: DoubleArray, simplexOffset: Double): Array<DoubleArray> { val points = Array(initialPoint.size) { initialPoint.copyOf() } for (i in points.indices) { points[i][i] += simplexOffset } return points + initialPoint.copyOf() } private fun List<Double>.argMax(): Int { var max = this[0] var arg = 0 for (i in this.indices) { if (this[i] >= max) { max = this[i] arg = i } } return arg } private fun List<Double>.argMin(): Int { var min = this[0] var arg = 0 for (i in this.indices) { if (this[i] <= min) { min = this[i] arg = i } } return arg } private fun Array<DoubleArray>.centroid(h: Int): DoubleArray { val k = this.size - 1 val sums = this.filterIndexed { index, _ -> index != h }.reduce { f, s -> f.add(s) } return sums.map { it / k }.toDoubleArray() } private fun List<Double>.greaterThanAllExcept(index: Int, value: Double): Boolean { return this.filterIndexed { i, _ -> i != index }.all { it < value } } private fun sumOfSquareDifferences(list: List<Double>, value: Double): Double { return list.map { (it - value) * (it - value) }.sum() } private fun Array<DoubleArray>.moveAllTowards(index: Int) { val value = this[index] for (i in this.indices) { if (i != index) { this[i] = 0.5 * (this[i] - value) } } } private fun DoubleArray.prettyString(): String { return this.joinToString( prefix = "{", separator = ", ", postfix = "}" ) } private fun printCentroid(xc: DoubleArray, fn: CountableFunction<DoubleArray>) { println("┌") println("│ xₒ = ${xc.prettyString()}") println("│ f(xₒ) = ${fn.invokeWithoutCount(xc)}") println("└") } fun nelderMeadSimplexSearch(initialPoint: DoubleArray, alpha: Double, beta: Double, gamma: Double, sigma: Double, precision: Double, fn: CountableFunction<DoubleArray>, verbose: Boolean): DoubleArray { val x = calculateSimplexPoints(initialPoint, sigma) var xc: DoubleArray var fnX = x.map { fn(it) } var fXc: Double do { val h = fnX.argMax() val l = fnX.argMin() xc = x.centroid(h) if (verbose) { printCentroid(xc, fn) } val xr = (1.0 + alpha) * xc - alpha * x[h] val fXr = fn(xr) if (fXr < fnX[l]) { val xe = ((1.0 - gamma) * xc).add(gamma * xr) if (fn(xe) < fnX[l]) { x[h] = xe } else { x[h] = xr } } else if (fnX.greaterThanAllExcept(h, fXr)) { if (fXr < fnX[h]) { x[h] = xr val xk = ((1.0 - beta) * xc).add(beta * x[h]) if (fn(xk) < fnX[h]) { x[h] = xk } else { x.moveAllTowards(l) } } } else { x[h] = xr } fnX = x.map { fn(it) } fXc = fn(xc) } while (sqrt(sumOfSquareDifferences(fnX, fXc) / x.size) < precision) return xc } private fun search(xp: DoubleArray, dx: DoubleArray, fn: CountableFunction<DoubleArray>): DoubleArray { val x = xp.copyOf() for (i in x.indices) { val p = fn(x) x[i] += dx[i] var n = fn(x) if (n > p) { x[i] -= 2 * dx[i] n = fn(x) if (n > p) { x[i] = x[i] + dx[i] } } } return x } private fun printPoints(xp: DoubleArray, xb: DoubleArray, xn: DoubleArray, fn: CountableFunction<DoubleArray>) { println("┌") println("│ xₚ = ${xp.prettyString()}, xₛ = ${xb.prettyString()}, xₙ = ${xn.prettyString()}") println("│ f(xₚ) = ${fn.invokeWithoutCount(xp)}, " + "f(xₛ) = ${fn.invokeWithoutCount(xb)}, " + "f(xₙ) = ${fn.invokeWithoutCount(xn)}") println("└") } fun hookeJeevesSearch(initialPoint: DoubleArray, dx: DoubleArray, precision: Double, fn: CountableFunction<DoubleArray>, verbose: Boolean): DoubleArray { var dx2 = dx var xp = initialPoint.copyOf() var xb = initialPoint.copyOf() do { val xn = search(xp, dx2, fn) if (verbose) { printPoints(xp, xb, xn, fn) } if (fn(xn) < fn(xb)) { xp = 2.0 * xn - xb xb = xn } else { dx2 = 0.5 * dx2 xp = xb } } while (dx2.norm() > precision) return xb } }
0
Kotlin
0
0
b483dda88bd9f2a6dc9f4928c7aa4e9a217eac8f
7,209
anc-lab
MIT License
src/main/kotlin/no/uib/inf273/operators/MinimizeWaitTime.kt
elgbar
237,403,030
false
{"Kotlin": 141160}
package no.uib.inf273.operators import no.uib.inf273.extra.randomizeExchange import no.uib.inf273.processor.Solution /** * Minimize the cargo that is waiting the longest globally. * This operators find the cargo which is currently waiting for port opening the longest and to and change the vessel cargo * order in such a way the the maximum wait time is lower. * * This operator helps with intensification as it optimizes a vessels cargo route. * * @author Elg */ object MinimizeWaitTime : Operator() { override fun operate(sol: Solution) { val subs = sol.splitToSubArray(true) //find the vessel with the greatest waiting time // note that we do not select the vessel with the greatest average waiting time just the global max waiting time val vesselMeta = findVessels(sol, subs).map() { (index, sub) -> // generate all info we know about this vessel (objval, port tardiness, etc) sol.generateVesselRouteMetadata(index, sub) }.maxBy { it.portTardiness.max() ?: -1 } if (vesselMeta == null) { //Nothing to do, vessel is either the dummy vessel or has zero or one cargo log.debug { "Failed to find a vessel to change" } return } val maxTardiness = vesselMeta.portTardiness.max() ?: error("Failed to find a cargo in vessel $vesselMeta") val vIndex = vesselMeta.vesselIndex //find what cargo is waiting the longest val sub = subs[vIndex] val maxTries = 20 var tryNr = 0 val solCopy = sol.copy() //then try and minimize the waiting time do { if (operateVesselTilFeasible(solCopy, vIndex, sub, maxCargoesToBruteForce = 2) { it.randomizeExchange() }) { val newMeta = solCopy.generateVesselRouteMetadata(vIndex, sub) val newMaxTardiness = newMeta.portTardiness.max() ?: error("Failed to calculate max new tardiness for ${newMeta.portTardiness}") if (newMaxTardiness < maxTardiness) { log.debug { "New smaller maximum tardiness found! new = $newMaxTardiness, old = $maxTardiness" } break } } } while (tryNr++ < maxTries) } }
0
Kotlin
0
3
1f76550a631527713b1eba22817e6c1215f5d84e
2,310
INF273
The Unlicense
src/main/kotlin/_2022/Day3.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2022 import REGEX_LINE_SEPARATOR import aoc const val LOWER_CODE_OFFSET = 'a'.code - 1 const val UPPER_CODE_OFFSET = 'A'.code - 27 fun main() { aoc(2022, 3) { aocRun { input -> input.split(REGEX_LINE_SEPARATOR).sumOf { contents -> findCommonItemsInRucksack(contents).sumOf { itemPriority(it) } } } aocRun { input -> input.split(REGEX_LINE_SEPARATOR).chunked(3).sumOf { group -> itemPriority(findCommonItemInGroup(group)) } } } } private fun findCommonItemsInRucksack(contents: String): Set<Char> { val indexMid = contents.length / 2 val first = contents.substring(0, indexMid).toSet() val second = contents.substring(indexMid).toSet() return first.intersect(second) } private fun findCommonItemInGroup(group: List<String>): Char { var commonItems = group[0].toSet() group.subList(1, group.size).forEach { commonItems = commonItems.intersect(it.toSet()) } return commonItems.single() } private fun itemPriority(item: Char): Int = if (item in ('a'..'z')) item.code - LOWER_CODE_OFFSET else item.code - UPPER_CODE_OFFSET
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
1,074
AdventOfCode
Creative Commons Zero v1.0 Universal
p08/src/main/kotlin/MemoryManeuver.kt
jcavanagh
159,918,838
false
null
package p08 import common.file.readLines import java.util.* class Node( val metadata: MutableList<Int> = mutableListOf(), val children: MutableList<Node> = mutableListOf() ) { fun sum(): Int { return children.fold(metadata.sum()) { all, node -> all + node.sum() } } fun value(): Int { if(children.isEmpty()) { return metadata.sum() } else { return metadata.fold(0) { all, meta -> //Find the node at the meta index, and value it val node = children.getOrNull(meta - 1) all + (node?.value() ?: 0) } } } } fun parseLicense(items: List<Int>) : Node { data class ParseItem(val node: Node, var numChildren: Int, var numMeta: Int) val head = ParseItem(Node(), items[0], items[1]) val stack = LinkedList<ParseItem>() stack.add(head) var pointer = 2 while(pointer < items.size) { val current = stack.pop() if (current.node.children.size < current.numChildren) { val parseItem = ParseItem(Node(), items[pointer], items[pointer + 1]) current.node.children.add(parseItem.node) stack.push(current) stack.push(parseItem) pointer += 2 } else if(current.node.metadata.isEmpty()) { current.node.metadata.addAll(items.subList(pointer, pointer + current.numMeta)) pointer += current.numMeta } } return head?.node!! } fun main() { val licenseTree = parseLicense(readLines("input.txt")[0].split(" ").map { it.toInt() }) println("Sum of meta: ${licenseTree.sum()}") println("Root value: ${licenseTree.value()}") }
0
Kotlin
0
0
289511d067492de1ad0ceb7aa91d0ef7b07163c0
1,562
advent2018
MIT License
src/day05/a/day05a.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day05.a import readInputLines import shouldBe fun main() { val lines = readInputLines(5) val i = lines.indexOfFirst { it.isBlank() } val stacks = readInitialStacks(lines.subList(0, i)) val instr = lines.subList(i+1, lines.size) for (j in instr) apply(decodeInstruction(j), stacks) val top = stacks.map { it.last() }.joinToString("") shouldBe("VJSFHWGFT", top) } private fun apply(job: IntArray, stacks: Array<ArrayList<Char>>) { val n = job[0] val from = stacks[job[1]-1] val to = stacks[job[2]-1] for (i in 0 until n) to.add(from.removeLast()) } fun decodeInstruction(str: String): IntArray { return str.split(" ").filterIndexed { i, _ -> i % 2 == 1 }.map(String::toInt).toIntArray() } fun readInitialStacks(line: List<String>): Array<ArrayList<Char>> { // ignore last line with indices val idxBottom = line.size - 2 val nStacks = (line[idxBottom].length + 1) / 4 val stack = Array<ArrayList<Char>>(nStacks) { ArrayList() } for (j in idxBottom downTo 0) { val l = line[j] for (i in 0 until nStacks) { val c = l[4*i+1] if (c != ' ') stack[i].add(c) } } return stack }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
1,213
advent-of-code-2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/MaxTurbulenceSize.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 978. 最长湍流子数组 * 当 A 的子数组 A[i], A[i+1], ..., A[j] 满足下列条件时,我们称其为湍流子数组: * * 若 i <= k < j,当 k 为奇数时, A[k] > A[k+1],且当 k 为偶数时,A[k] < A[k+1]; * 或 若 i <= k < j,当 k 为偶数时,A[k] > A[k+1] ,且当 k 为奇数时, A[k] < A[k+1]。 * 也就是说,如果比较符号在子数组中的每个相邻元素对之间翻转,则该子数组是湍流子数组。 * 返回 A 的最大湍流子数组的长度。 */ class MaxTurbulenceSize { companion object { @JvmStatic fun main(args: Array<String>) { println(MaxTurbulenceSize().solution(intArrayOf(9, 4, 2, 10, 7, 8, 8, 1, 9))) println(MaxTurbulenceSize().solution(intArrayOf(4, 8, 12, 16))) println(MaxTurbulenceSize().solution(intArrayOf(100))) println(MaxTurbulenceSize().solution(intArrayOf(9, 9))) } } // 输入:[9,4,2,10,7,8,8,1,9] // 输出:5 // 解释:(A[1] > A[2] < A[3] > A[4] < A[5]) fun solution(arr: IntArray): Int { val size = arr.size if (size == 1) return 1 var max = 0 var temp = 1 var i = 0 var flag = false while (i < size - 1) { val sub = arr[i] - arr[i + 1] if (sub > 0 && !flag) { temp++ } else if (sub < 0 && flag) { temp++ } else { max = Math.max(max, temp) temp = if (sub != 0) 2 else 1 } flag = sub > 0 i++ } max = Math.max(max, temp) return max } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,726
daily_algorithm
Apache License 2.0
src/main/kotlin/com/staricka/adventofcode2023/days/Day13.kt
mathstar
719,656,133
false
{"Kotlin": 107115}
package com.staricka.adventofcode2023.days import com.staricka.adventofcode2023.framework.Day import com.staricka.adventofcode2023.util.* enum class ReflectionDirection { COLUMN, ROW } data class ReflectionPoint(val num: Int, val direction: ReflectionDirection) fun <T: GridCell> StandardGrid<T>.findReflection(): ReflectionPoint { for (reflection in minX until maxX) { for (i in 0..maxX) { val top = reflection - i val bottom = reflection + 1 + i if (top < 0 || bottom > maxX) return ReflectionPoint(reflection, ReflectionDirection.ROW) if (row(top).map { (_,_,v) -> v } != row(bottom).map { (_,_,v) -> v }) break } } for (reflection in minY until maxY) { for (i in 0..maxY) { val left = reflection - i val right = reflection + 1 + i if (left < 0 || right > maxY) return ReflectionPoint(reflection, ReflectionDirection.COLUMN) if (col(left).map { (_,_,v) -> v } != col(right).map { (_,_,v) -> v }) break } } throw Exception() } fun <T: GridCell> StandardGrid<T>.findSmudgeReflection(original: ReflectionPoint): ReflectionPoint { for (reflection in minX until maxX) { var smudgeIdentified = false reflectionInner@for (i in 0..maxX) { val top = reflection - i val bottom = reflection + 1 + i if (top < 0 || bottom > maxX) { val reflectionPoint = ReflectionPoint(reflection, ReflectionDirection.ROW) if (reflectionPoint != original) return reflectionPoint break@reflectionInner } val topRow = row(top) val bottomRow = row(bottom) for (j in 0..maxY) { if (topRow[j].third != bottomRow[j].third) { if (!smudgeIdentified) { smudgeIdentified = true } else { break@reflectionInner } } } } } for (reflection in minY until maxY) { var smudgeIdentified = false reflectionInner@for (i in 0..maxY) { val left = reflection - i val right = reflection + 1 + i if (left < 0 || right > maxY) { val reflectionPoint = ReflectionPoint(reflection, ReflectionDirection.COLUMN) if (reflectionPoint != original) return reflectionPoint break@reflectionInner } val leftCol = col(left) val rightCol = col(right) for (j in 0..maxX) { if (leftCol[j].third != rightCol[j].third) { if (!smudgeIdentified) { smudgeIdentified = true } else { break@reflectionInner } } } } } throw Exception() } class Day13: Day { override fun part1(input: String): Int { return input.splitByBlankLines().map { StandardGrid.build(it, ::BasicCell) } .map { it.findReflection() } .sumOf { if(it.direction == ReflectionDirection.COLUMN) it.num + 1 else 100 * (it.num + 1) } } override fun part2(input: String): Int { return input.splitByBlankLines().map { StandardGrid.build(it, ::BasicCell) } .map { Pair(it, it.findReflection()) } .map { (grid, reflection) -> grid.findSmudgeReflection(reflection) } .sumOf { if(it.direction == ReflectionDirection.COLUMN) it.num + 1 else 100 * (it.num + 1) } } }
0
Kotlin
0
0
8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa
3,639
adventOfCode2023
MIT License
src/main/kotlin/se/brainleech/adventofcode/aoc2020/Aoc2020Day01.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2020 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readIntegers import se.brainleech.adventofcode.verify class Aoc2020Day01 { fun part1(entries: List<Int>): Int { return entries .filter { entries.contains(2020 - it) } .take(1) .sumOf { it.times(2020 - it) } } fun part2(entries: List<Int>): Int { for (first in entries) { for (second in entries.filter { it != first }) { val third = entries .filter { third -> third != first && third != second } .firstOrNull { third -> first.plus(second).plus(third) == 2020 } if (third != null) { return first.times(second).times(third) } } } return -1 } } fun main() { val solver = Aoc2020Day01() val prefix = "aoc2020/aoc2020day01" val testData = readIntegers("$prefix.test.txt") val realData = readIntegers("$prefix.real.txt") verify(514_579, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(241_861_950, solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
1,287
adventofcode
MIT License
src/Day01.kt
lonskiTomasz
573,032,074
false
{"Kotlin": 22055}
fun main() { fun maxCalories(input: List<String>): Int { var maximum = 0 var current = 0 input.forEach { line -> if (line.isBlank()) { maximum = maxOf(maximum, current) current = 0 } else { current += line.toInt() } } return maximum } fun totalCaloriesOfTopThreeElves(input: List<String>): Int { val topThree = mutableListOf(0, 0, 0) var current = 0 input.forEach { line -> if (line.isBlank()) { when { current > topThree[0] -> { topThree[2] = topThree[1] topThree[1] = topThree[0] topThree[0] = current } current > topThree[1] -> { topThree[2] = topThree[1] topThree[1] = current } current > topThree[2] -> { topThree[2] = current } } current = 0 } else { current += line.toInt() } } return topThree.sum() } val inputTest = readInput("day01/input_test") val input = readInput("day01/input") println(maxCalories(inputTest)) println(maxCalories(input)) println(totalCaloriesOfTopThreeElves(inputTest)) println(totalCaloriesOfTopThreeElves(input)) } /** * 24000 * 68467 * 45000 * 203420 */
0
Kotlin
0
0
9e758788759515049df48fb4b0bced424fb87a30
1,570
advent-of-code-kotlin-2022
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day12/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day12 fun launchDay12(testCase: String) { println("Day 12, part 1: ${calculate(testCase)}") println("Day 12, part 2: ${calculate(testCase, 5)}") } private fun calculate(testCase: String, repCount: Int = 1): Long { val reader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() ?: throw Exception("Invalid state, cannot read the input") var result = 0L while (true) { val rawLine = reader.readLine() ?: break val p = parseLine(rawLine, repCount) val cache = mutableMapOf<Pair<String, List<Int>>, Long>() val item = comb(p.first, p.second, cache) result += item } return result } private fun parseLine(rawLine: String, repCount: Int = 1): Pair<String, List<Int>> { val parts = rawLine.split(' ') val rawMask = parts[0] val rawBlocks = parts[1].split(',').map { it.trim() }.filter { it.isNotEmpty() }.map { it.toInt() } var mask = "" val blocks = mutableListOf<Int>() repeat(repCount) { mask += rawMask if (it != repCount - 1) mask += "?" blocks += rawBlocks } return Pair(mask, blocks) } private fun comb( mask: String, blocks: List<Int>, ca: MutableMap<Pair<String, List<Int>>, Long> ): Long { val existing = ca[Pair(mask, blocks)] if (existing != null) return existing if (mask.isEmpty()) { return if (blocks.isEmpty()) 1 else 0 } return when (mask.first()) { '?' -> { comb(mask.replaceFirst('?', '#'), blocks, ca) + comb(mask.replaceFirst('?', '.'), blocks, ca) } '.' -> { val res = comb(mask.trimStart('.'), blocks, ca) ca[Pair(mask, blocks)] = res res } '#' -> { if (blocks.isEmpty() || mask.length < blocks.first() || mask.substring(0, blocks.first()) .indexOf('.') != -1 ) { ca[Pair(mask, blocks)] = 0 0 } else if (blocks.size > 1) { if (mask.length < blocks.first() + 1 || mask[blocks.first()] == '#') { ca[Pair(mask, blocks)] = 0 0 } else { val res = comb(mask.substring(blocks.first() + 1, mask.length), blocks.subList(1, blocks.size), ca) ca[Pair(mask, blocks)] = res res } } else { val res = comb(mask.substring(blocks.first(), mask.length), blocks.subList(1, 1), ca) ca[Pair(mask, blocks)] = res res } } else -> 0 } }
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
2,706
advent-of-code-2023
MIT License
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec15.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2021 import org.elwaxoro.advent.Node import org.elwaxoro.advent.PuzzleDayTester import org.elwaxoro.advent.cost import org.elwaxoro.advent.neighborCoords import org.elwaxoro.advent.splitToInt /** * Chiton (oh look its Dijkstra) */ class Dec15 : PuzzleDayTester(15, 2021) { override fun part1(): Any = parse().cornerToCornerCost() // victim of incomplete refactors to optimize and clean up code, now goes OOM but it's a year later so :shrug: override fun part2(): Any = "OOM"//parse(reps = 5).cornerToCornerCost() private fun List<List<Node>>.cornerToCornerCost(): Int { this[0][0].dijkstra() // because I'm dumb and insisted on reusing existing code that wasn't a perfect fit, // the shortest path (and cost) includes the start node but not the end // it works, so I'm just leaving it - but the true cost must be recalculated: val end = this[size - 1][size - 1] return (end.shortestPath + end).cost() } fun parse(reps: Int = 1): List<List<Node>> = load().map { it.splitToInt() }.getSwole(reps).let { grid -> val refGraph = mutableMapOf<String, Node>() grid.mapIndexed { rowIdx, row -> row.mapIndexed { colIdx, i -> // LOTS of debugging here, so went with a key that could be parsed back out in various ways val nodeKey = "$colIdx,$rowIdx:$i" val node = refGraph.getOrDefault(nodeKey, Node(nodeKey)) refGraph[node.name] = node grid.neighborCoords(rowIdx, colIdx).forEach { (coord, cost) -> val neighborKey = "${<KEY>${coord.y}:$cost" val neighbor = refGraph.getOrDefault(neighborKey, Node(neighborKey)) refGraph[neighbor.name] = neighbor node.addEdge(neighbor, cost) neighbor.addEdge(node, i) } node } } } /** * Never skip leg day */ private fun List<List<Int>>.getSwole(reps: Int): List<List<Int>> = (0 until size * reps).map { y -> (0 until size * reps).map { x -> // All truly great code is completely unreadable ((this[y % size][x % size] + x / size + y / size - 1) % 9) + 1 } } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
2,352
advent-of-code
MIT License
src/Day02.kt
ArtManyak
572,905,558
false
{"Kotlin": 2152}
fun main() { fun part1(lines: List<String>): Int { var score = 0 for (round in lines.map { Pair(it[0] - 'A', it[2] - 'X') }) { score += round.second + 1 if (round.first == round.second) score += 3 if ((round.first + 1) % 3 == round.second) score += 6 } return score } fun part2(lines: List<String>): Int { var score = 0 for (round in lines.map { Pair(it[0] - 'A', it[2] - 'X') }) { score += when (round.second) { 1 -> 3 + round.first + 1 2 -> 6 + (round.first + 1) % 3 + 1 else -> (round.first + 2) % 3 + 1 } } return score } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8450515b1773f4fd2103a5c8594d43c476603348
806
AoC2022
Apache License 2.0
src/Day08.kt
hrach
572,585,537
false
{"Kotlin": 32838}
@file:Suppress("NAME_SHADOWING") fun main() { fun getSeq(input: List<List<Int>>, y: Int, x: Int, dy: Int, dx: Int): Sequence<Int> = sequence { var x = x var y = y do { y += dy x += dx val t = input.getOrNull(y)?.getOrNull(x) if (t != null) yield(t) } while (t != null) } fun Sequence<Int>.customAny(t: Int): Boolean { if (this.firstOrNull() == null) return true return find { it >= t } == null } fun part1(input: List<String>): Int { val input = input.map { it.toCharArray().map { it.toString().toInt() } } var counter = 0 val map = mutableMapOf<Int, MutableMap<Int, Int>>() input.forEachIndexed { y, row -> row.forEachIndexed { x, t -> val up = getSeq(input, y, x, -1, 0).customAny(t) val left = getSeq(input, y, x, 0, -1).customAny(t) val right = getSeq(input, y, x, 0, +1).customAny(t) val bottom = getSeq(input, y, x, +1, 0).customAny(t) val isVisible = up || left || right || bottom if (isVisible) { counter += 1 } map.getOrPut(y) { mutableMapOf<Int, Int>() } map[y]!![x] = if (isVisible) 1 else 0 } } return counter } fun Sequence<Int>.score(t: Int): Int { if (firstOrNull() == null) return 0 val taken = takeWhile { it < t } return if (taken.count() == count()) taken.count() else taken.count() + 1 } fun part2(input: List<String>): Int { val input = input.map { it.toCharArray().map { it.toString().toInt() } } val map = mutableMapOf<Int, MutableMap<Int, Int>>() input.forEachIndexed { y, row -> row.forEachIndexed { x, t -> val up = getSeq(input, y, x, -1, 0).score(t) val left = getSeq(input, y, x, 0, -1).score(t) val right = getSeq(input, y, x, 0, +1).score(t) val bottom = getSeq(input, y, x, +1, 0).score(t) val score = up * left * right * bottom map.getOrPut(y) { mutableMapOf<Int, Int>() } map[y]!![x] = score } } return map.values.flatMap { it.values }.max() } val testInput = readInput("Day08_test") check(part1(testInput), 21) check(part2(testInput), 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
40b341a527060c23ff44ebfe9a7e5443f76eadf3
2,562
aoc-2022
Apache License 2.0
src/test/kotlin/com/igorwojda/string/maxchar/solution.kt
handiism
455,862,994
true
{"Kotlin": 218721}
package com.igorwojda.string.maxchar // Kotlin idiomatic solution private object Solution1 { private fun maxOccurrentChar(str: String): Char? { return str.toCharArray() .groupBy { it } .maxBy { it.value.size } ?.key } } // Kotlin idiomatic solution private object Solution2 { private fun maxOccurrentChar(str: String): Char? { return str.toList() .groupingBy { it } .eachCount() .maxBy { it.value } ?.key } } private object Solution3 { private fun maxOccurrentChar(str: String): Char? { val map = mutableMapOf<Char, Int>() str.forEach { map[it] = (map[it] ?: 0) + 1 } return map.maxBy { it.value }?.key } } // Recursive optimal approach: // Time complexity: O(n) private object Solution4 { private fun recurringChar(str: String): Char? { val set = mutableSetOf<Char>() str.forEach { char -> if (set.any { it == char }) { return char } set.add(char) } return null } } // Recursive naive approach // Time complexity: O(n^2) private object Solution5 { private fun recurringChar(str: String): Char? { str.forEachIndexed { index, c -> str.substring(index + 1).forEach { if (c == it) { return it } } } return null } }
1
Kotlin
2
1
413316e0e9de2f237d9768cfa68db3893e72b48c
1,491
kotlin-coding-challenges
MIT License
src/main/kotlin/net/mguenther/adventofcode/day12/Day12.kt
mguenther
115,937,032
false
null
package net.mguenther.adventofcode.day12 import net.mguenther.adventofcode.array2dOfBoolean /** * @author <NAME> (<EMAIL>) */ data class Node(val id: String, val successors: Map<Int, List<Int>>) fun programsInRootComponent(nodes: Map<Int, List<Int>>): Int { val adjacencyMatrix = computeAdjacencyMatrix(nodes) var transitiveClosure = adjacencyMatrix.clone() for (k in 0 until adjacencyMatrix.size) { val nextTransitiveClosure = array2dOfBoolean(nodes.size, nodes.size) for (i in 0 until adjacencyMatrix.size) { for (j in 0 until adjacencyMatrix.size) { nextTransitiveClosure[i][j] = transitiveClosure[i][j] || transitiveClosure[i][k] && transitiveClosure[k][j] } } transitiveClosure = nextTransitiveClosure } return transitiveClosure[0] .asList() .map { connected -> if (connected) 1 else 0 } .sum() } private fun computeAdjacencyMatrix(nodes: Map<Int, List<Int>>): Array<BooleanArray> { val adjacencyMatrix = array2dOfBoolean(nodes.size, nodes.size) for (from in nodes.keys) { for (to in nodes.get(from)!!) { adjacencyMatrix[from][to] = true adjacencyMatrix[to][from] = true } } return adjacencyMatrix }
0
Kotlin
0
0
c2f80c7edc81a4927b0537ca6b6a156cabb905ba
1,326
advent-of-code-2017
MIT License
kotlin/src/main/kotlin/year2023/Day20.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 import year2023.Day20.Pulse.HIGH import year2023.Day20.Pulse.LOW fun main() { val input = readInput("Day20") Day20.part1(input).println() Day20.part2(input).println() } //832957356 //240162699605221 object Day20 { fun part1(input: List<String>): Int { val dataStructures = initDataStructures(input) val startButton = Button() startButton.receivers.forEach { dataStructures.usageCount[it] = (dataStructures.usageCount[it] ?: 0) + 1 } return (1..1000) .map { round -> startButton.press(round, dataStructures) } .fold(0 to 0) { (sumHigh, sumLow), (high, low) -> sumHigh + high to sumLow + low } .let { (high, low) -> high * low } } fun part2(input: List<String>): Long { val (dictionary, _, _) = initDataStructures(input) val flipFlops = dictionary.values.filterIsInstance<FlipFlop>().map { it.name }.distinct() val binaryCounterResults = dictionary["broadcaster"] ?.receivers ?.map { name -> val start = dictionary[name] val conjunction = start?.receivers?.first { dictionary[it] is Conjunction } generateSequence(start) { module -> dictionary[module.receivers.firstOrNull { it in flipFlops }] } .map { if (conjunction in it.receivers) 1 else 0 } .foldIndexed(0L) { index, acc, i -> acc + (i shl index) } } return binaryCounterResults?.lcm() ?: 0L } private data class DataStructureWrapper( val dictionary: Map<String, Module>, val queue: ArrayDeque<Signal>, val usageCount: MutableMap<String, Int> ) private fun initDataStructures(input: List<String>): DataStructureWrapper { val dictionary = input .map { Pair(it.split(" -> ")[0], it.split(" -> ")[1].split(", ")) } .map { val name = it.first.drop(1) val downstream = it.second when (it.first[0]) { '%' -> FlipFlop(name, downstream) '&' -> Conjunction(name, downstream) else -> BroadCaster(downstream) } } .associateBy { it.name } val usageCount = mutableMapOf<String, Int>() dictionary.values.forEach { module -> module.receivers.forEach { usageCount[it] = (usageCount[it] ?: 0) + 1 } } return DataStructureWrapper( dictionary = dictionary, queue = ArrayDeque(), usageCount = usageCount ) } private enum class Pulse { HIGH, LOW } private data class Signal( val sender: String, val receivers: List<String>, val pulse: Pulse, val dataStructures: DataStructureWrapper ) { fun send(round: Int) { receivers.forEach { name -> dataStructures.dictionary[name]?.processSignal(this, round) } } } private interface Module { val name: String val receivers: List<String> fun processSignal(signal: Signal, round: Int) } private data class Button( override val name: String = "button", override val receivers: List<String> = listOf("broadcaster") ) : Module { override fun processSignal(signal: Signal, round: Int) { val out = Signal(name, receivers, LOW, signal.dataStructures) signal.dataStructures.queue.add(out) } fun press( round: Int, dataStructures: DataStructureWrapper ): Pair<Int, Int> { val firstSignal = Signal(name, receivers, LOW, dataStructures) processSignal(firstSignal, 0) return generateSequence { dataStructures.queue.removeFirstOrNull() } .fold(0 to 0) { (high, low), signal -> signal.send(round) if (signal.pulse == HIGH) { high + signal.receivers.size to low } else { high to low + signal.receivers.size } } } } private data class BroadCaster( override val receivers: List<String> ) : Module { override val name = "broadcaster" override fun processSignal(signal: Signal, round: Int) { val out = Signal(name, receivers, signal.pulse, signal.dataStructures) signal.dataStructures.queue.add(out) } } private data class FlipFlop( override val name: String, override val receivers: List<String>, private var on: Boolean = false ) : Module { override fun processSignal(signal: Signal, round: Int) { if (signal.pulse == LOW) { on = !on val pulse = if (on) HIGH else LOW val out = Signal(name, receivers, pulse, signal.dataStructures) signal.dataStructures.queue.add(out) } } } private data class Conjunction( override val name: String, override val receivers: List<String> ) : Module { private val previousPulses = mutableMapOf<String, Pulse>() override fun processSignal(signal: Signal, round: Int) { val countModulesCallingMe = signal.dataStructures.usageCount[name] previousPulses[signal.sender] = signal.pulse val isLOW = previousPulses.values.all { it == HIGH } && countModulesCallingMe == previousPulses.size val pulse = if (isLOW) LOW else HIGH val out = Signal(name, receivers, pulse, signal.dataStructures) signal.dataStructures.queue.add(out) } } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
5,873
advent-of-code
MIT License
src/main/kotlin/com/chriswk/aoc/advent2021/Day21.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report class Day21: AdventDay(2021, 21) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day21() report { day.part1() } report { day.part2() } } } fun parseInput(input: List<String>): Game { val players = input.map { Player(it) } return Game(players[0], players[1], 0) } fun playTurn(game: Game): Sequence<Game> { return generateSequence(game) { g -> val move = listOf(g.rolls + 1, g.rolls + 2, g.rolls + 3) if (g.player1) { val d = (g.p1.position + move.sum()) % 10 if (d == 0) { val newPlayer = g.p1.copy(position = 10, score = g.p1.score + 10) g.copy(rolls = g.rolls + 3, p1 = newPlayer, player1 = false) } else { val newPlayer = g.p1.copy(position = d, score = g.p1.score + d) g.copy(rolls = g.rolls + 3, p1 = newPlayer, player1 = false) } } else { val d = (g.p2.position + move.sum()) % 10 if (d == 0) { val newPlayer = g.p2.copy(position = 10, score = g.p2.score + 10) g.copy(rolls = g.rolls + 3, p2 = newPlayer, player1 = true) } else { val newPlayer = g.p2.copy(position = d, score = g.p2.score + d) g.copy(rolls = g.rolls + 3, p2 = newPlayer, player1 = true) } } } } fun Int.gauss(): Long { return (this * this + 1) / 2L } data class Player(val startingPosition: Int, val position: Int = startingPosition, val score: Int = 0) { constructor(s: String): this(startingPosition = s.split(":")[1].trim().toInt()) } data class Game(val p1: Player, val p2: Player, val rolls: Int, val player1: Boolean = true) fun part1(): Long { val game = parseInput(inputAsLines) val g = playTurn(game).first { it.p1.score >= 1000 || it.p2.score >= 1000 } return if (g.p1.score >= 1000) { g.p2.score * g.rolls.toLong() } else { g.p1.score * g.rolls.toLong() } } fun part2(): Long { val players = inputAsLines.map { Player(it) } return Score(players[0].startingPosition, players[1].startingPosition, 0, 0).let { p -> maxOf(p.first, p.second) } } data class LongPair(val first: Long, val second: Long) { override fun toString(): String = "($first, $second)" } infix fun Long.to(other: Long): LongPair = LongPair(this, other) private object Score { private val dice = sequence { for (i in 1..3) for (j in 1..3) for (k in 1..3) yield(i + j + k) }.groupingBy { it }.eachCount() private val x = LongArray(44100) private val y = LongArray(44100) operator fun invoke(player1: Int, player2: Int, score1: Int, score2: Int): LongPair { val i = player1 + 10 * player2 + 100 * score1 + 2100 * score2 - 11 if (x[i] == 0L && y[i] == 0L) { var x1 = 0L var y1 = 0L for ((d, n) in dice) { val play = (player1 + d - 1) % 10 + 1 if (score1 + play < 21) { val (x2, y2) = this(player2, play, score2, score1 + play) x1 += n * y2 y1 += n * x2 } else { x1 += n } } x[i] = x1 y[i] = y1 } return LongPair(x[i], y[i]) } } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
3,869
adventofcode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/BeautifulArrangement.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <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.swap /** * https://leetcode.com/problems/beautiful-arrangement/ * 526. Beautiful Arrangement */ fun interface BeautifulArrangement { fun countArrangement(n: Int): Int } /** * Approach #2 Better Brute Force */ class BABruteForce : BeautifulArrangement { private var count = 0 override fun countArrangement(n: Int): Int { val nums = IntArray(n) for (i in 1..n) nums[i - 1] = i return permute(nums, 0) } fun permute(nums: IntArray, l: Int): Int { if (l == nums.size) { count++ } for (i in l until nums.size) { nums.swap(i, l) if (nums[l] % (l + 1) == 0 || (l + 1) % nums[l] == 0) { permute(nums, l + 1) } nums.swap(i, l) } return count } } /** * Approach #3 Backtracking */ class BABacktracking : BeautifulArrangement { private var count = 0 override fun countArrangement(n: Int): Int { val visited = BooleanArray(n + 1) calculate(n, 1, visited) return count } fun calculate(n: Int, pos: Int, visited: BooleanArray) { if (pos > n) count++ for (i in 1..n) { if (!visited[i] && (pos % i == 0 || i % pos == 0)) { visited[i] = true calculate(n, pos + 1, visited) visited[i] = false } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,084
kotlab
Apache License 2.0
src/day18.kt
miiila
725,271,087
false
{"Kotlin": 77215}
import java.io.File import java.util.Collections.max import java.util.Collections.min import kotlin.math.abs import kotlin.system.exitProcess private const val DAY = 18 fun main() { if (!File("./day${DAY}_input").exists()) { downloadInput(DAY) println("Input downloaded") exitProcess(0) } val transformer = { x: String -> val x = x.replace("(", "").replace(")", "").split(" ") Triple(x[0][0], x[1].toInt(), x[2]) } val input = loadInput(DAY, false, transformer) // println(input) println(solvePart1(input)) println(solvePart2(input)) } // Part 1 private fun solvePart1(input: List<Triple<Char, Int, String>>): Int { val res = getEdges(input) // printRes(res) val rmin = min(res.map { it.first }) val rmax = max(res.map { it.first }) val cmin = min(res.map { it.second }) val cmax = max(res.map { it.second }) val q = mutableListOf<Pair<Int, Int>>() // Find first inside cell for (r in (rmin..rmax)) { var found = false for (c in (cmin..cmax)) { if (Pair(r, c) in res && Pair(r, c + 1) in res) { break } if (Pair(r, c) in res) { found = true q.add(Pair(r, c + 1)) break } } if (found) break } // Fill everything val filled = res.toMutableSet() while (q.isNotEmpty()) { val i = q.removeFirst() for (n in getNeighbours(i)) { if (n !in filled) { filled.add(n) q.add(n) } } } // printRes(filled.toList()) return filled.count() } // Part 2 private fun solvePart2(input: List<Triple<Char, Int, String>>): Long { val inputHexa = input.map { parseHexa(it.third) } val vertices = getVertices(inputHexa).map { Pair(it.first.toLong(), it.second.toLong()) } return getPolygonArea(vertices) } fun parseHexa(hexa: String): Triple<Char, Int, String> { val dir = when (hexa[6]) { '0' -> 'R' '1' -> 'D' '2' -> 'L' '3' -> 'U' else -> error("BOOM") } return Triple(dir, hexa.slice(1..5).toInt(16), "") } fun getVertices(input: List<Triple<Char, Int, String>>): List<Pair<Int, Int>> { val res = mutableListOf<Pair<Int, Int>>() var cur = Pair(0, 1) for ((i, inp) in input.withIndex()) { if (i == input.count() - 1) { break } val (store, next) = getNextDig(cur, inp.first, inp.second, input[i + 1].first) res.add(store) cur = next } res.add(Pair(0, 0)) return res } fun getEdges(input: List<Triple<Char, Int, String>>): List<Pair<Int, Int>> { val res = mutableListOf<Pair<Int, Int>>() var cur = Pair(0, 0) for (inp in input) { for (i in (0..<inp.second)) { cur = getNextDig(cur, inp.first, 1) res.add(cur) } } return res } fun getNeighbours(pos: Pair<Int, Int>): List<Pair<Int, Int>> { val res = mutableListOf<Pair<Int, Int>>() for (i in listOf(-1, 1)) { res.add(Pair(pos.first + i, pos.second)) res.add(Pair(pos.first, pos.second + i)) } return res } fun getPolygonArea(vertices: List<Pair<Long, Long>>): Long { val pairs = vertices.windowed(2).toMutableList() val r = 0.5 * abs(pairs.sumOf { (v1, v2) -> v1.first * v2.second - v2.first * v1.second }) return r.toLong() } fun getNextDig(pos: Pair<Int, Int>, dir: Char, l: Int, nextDir: Char): Pair<Pair<Int, Int>, Pair<Int, Int>> { var storePos = when (dir) { 'U' -> Pair(pos.first - l, pos.second) 'D' -> Pair(pos.first + l, pos.second) 'R' -> Pair(pos.first, pos.second + l) 'L' -> Pair(pos.first, pos.second - l) else -> error("BOOOM") } val nextPos: Pair<Int, Int> if (isRightTurn(dir, nextDir)) { nextPos = when (dir) { 'R' -> Pair(storePos.first + 1, storePos.second) 'D' -> Pair(storePos.first, storePos.second - 1) 'L' -> Pair(storePos.first - 1, storePos.second) 'U' -> Pair(storePos.first, storePos.second + 1) else -> error("BOOOM") } } else { nextPos = when (dir) { 'R' -> Pair(storePos.first, storePos.second - 1) 'D' -> Pair(storePos.first - 1, storePos.second) 'L' -> Pair(storePos.first, storePos.second + 1) 'U' -> Pair(storePos.first + 1, storePos.second) else -> error("BOOOM") } storePos = nextPos } return Pair(storePos, nextPos) } fun getNextDig(pos: Pair<Int, Int>, dir: Char, l: Int): Pair<Int, Int> { return when (dir) { 'U' -> Pair(pos.first - l, pos.second) 'D' -> Pair(pos.first + l, pos.second) 'R' -> Pair(pos.first, pos.second + l) 'L' -> Pair(pos.first, pos.second - l) else -> error("BOOOM") } } fun isRightTurn(prevDir: Char, nextDir: Char): Boolean { return when (prevDir) { 'R' -> nextDir == 'D' 'D' -> nextDir == 'L' 'L' -> nextDir == 'U' 'U' -> nextDir == 'R' else -> error("BOOM") } } fun printRes(res: List<Pair<Int, Int>>) { val rmin = min(res.map { it.first }) val rmax = max(res.map { it.first }) val cmin = min(res.map { it.second }) val cmax = max(res.map { it.second }) for (r in (rmin..rmax)) { for (c in (cmin..cmax)) { if (Pair(r, c) in res) { print('#') } else { print('.') } } println("") } }
0
Kotlin
0
1
1cd45c2ce0822e60982c2c71cb4d8c75e37364a1
5,635
aoc2023
MIT License
src/main/kotlin/com/pandarin/aoc2022/Day4.kt
PandarinDev
578,619,167
false
{"Kotlin": 6586}
package com.pandarin.aoc2022 class Range(val from: Int, val until: Int) typealias RangePair = Pair<Range, Range> fun RangePair.fullyOverlaps(): Boolean { return (first.from >= second.from && first.until <= second.until) || (second.from >= first.from && second.until <= first.until) } fun RangePair.hasOverlap(): Boolean { return (first.from >= second.from && first.from <= second.until) || (second.from >= first.from && second.from <= first.until) } fun parseRangePair(entry: String): RangePair { val (first, second) = entry.split(",") val (firstFrom, firstUntil) = first.split("-") val (secondFrom, secondUntil) = second.split("-") return RangePair( first = Range(firstFrom.toInt(), firstUntil.toInt()), second = Range(secondFrom.toInt(), secondUntil.toInt())) } fun main() { val inputLines = Common.readInput("/day4.txt").split("\n").filter { it.isNotEmpty() } val rangePairs = inputLines.stream().map { parseRangePair(it) }.toList() val numberOfFullyOverlappingRanges = rangePairs.count(RangePair::fullyOverlaps) println("Part1: $numberOfFullyOverlappingRanges") val numberOfPartiallyOverlappingRanges = rangePairs.count(RangePair::hasOverlap) println("Part2: $numberOfPartiallyOverlappingRanges") }
0
Kotlin
0
0
42c35d23129cc9f827db5b29dd10342939da7c99
1,296
aoc2022
MIT License
src/main/kotlin2023/Day005.kt
teodor-vasile
573,434,400
false
{"Kotlin": 41204}
package main.kotlin2023 class Day005 { fun part1(lines: String): Long { val parsedInput = parseInput(lines) val seeds = parsedInput.get(0).get(0) val seedMaps = parsedInput.drop(1) val locationValues = mutableSetOf<Long>() for (seed in seeds) { val foundCorrespondent = findCorrespondent(seed, seedMaps[0]) val foundCorrespondent2 = findCorrespondent(foundCorrespondent, seedMaps[1]) val foundCorrespondent3 = findCorrespondent(foundCorrespondent2, seedMaps[2]) val foundCorrespondent4 = findCorrespondent(foundCorrespondent3, seedMaps[3]) val foundCorrespondent5 = findCorrespondent(foundCorrespondent4, seedMaps[4]) val foundCorrespondent6 = findCorrespondent(foundCorrespondent5, seedMaps[5]) val foundCorrespondentFinal = findCorrespondent(foundCorrespondent6, seedMaps[6]) locationValues.add(foundCorrespondentFinal) } return locationValues.min() } fun part2(lines: String): Long { val parsedInput = parseInput(lines) val seedsRaw = parsedInput.get(0).get(0) // val seeds = mutableSetOf<Long>() // for (i in 0..seedsRaw.size - 2 step 2) { // seeds.addAll(seedsRaw[i]..seedsRaw[i] + seedsRaw[i + 1]) // } val seeds = sequence { for (i in 0..seedsRaw.size-2 step 2) { yieldAll(seedsRaw[i] .. seedsRaw[i]+seedsRaw[i+1]) } } val seedMaps = parsedInput.drop(1) val locationValues = mutableSetOf<Long>() for (seed in seeds) { val foundCorrespondent = findCorrespondent(seed, seedMaps[0]) val foundCorrespondent2 = findCorrespondent(foundCorrespondent, seedMaps[1]) val foundCorrespondent3 = findCorrespondent(foundCorrespondent2, seedMaps[2]) val foundCorrespondent4 = findCorrespondent(foundCorrespondent3, seedMaps[3]) val foundCorrespondent5 = findCorrespondent(foundCorrespondent4, seedMaps[4]) val foundCorrespondent6 = findCorrespondent(foundCorrespondent5, seedMaps[5]) val foundCorrespondentFinal = findCorrespondent(foundCorrespondent6, seedMaps[6]) locationValues.add(foundCorrespondentFinal) } return locationValues.min() } private fun findCorrespondent(source: Long, targets: List<List<Long>>): Long { for (target in targets) { if (source >= target[1] && source <= target[1] + target[2]) { return target[0] + source - target[1] } } return source } private fun parseInput(input: String) = input.split("\n\n") .map { eachLine -> eachLine.split("\n") .map { it.dropWhile { !it.isDigit() } } .map { it.split(' ') .filter { it.isNotEmpty() && it.all(Character::isDigit) } .map(String::toLong) } .filter { it.isNotEmpty() } } }
0
Kotlin
0
0
2fcfe95a05de1d67eca62f34a1b456d88e8eb172
3,081
aoc-2022-kotlin
Apache License 2.0
src/Day11.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
fun main() { class MultiModuloNumber private constructor(private val valueByModulus: Map<Int, Int>) { constructor(value: Int, moduluses: Iterable<Int>) : this(moduluses.associateWith { value % it }) operator fun plus(x: Int) = MultiModuloNumber(valueByModulus.mapValues { (modulus, value) -> (value + x) % modulus }) operator fun plus(x: MultiModuloNumber): MultiModuloNumber { check(valueByModulus.keys == x.valueByModulus.keys) return MultiModuloNumber(valueByModulus.mapValues { (modulus, value) -> (value + x.valueByModulus.getValue(modulus)) % modulus }) } operator fun times(x: Int) = MultiModuloNumber(valueByModulus.mapValues { (modulus, value) -> (value * x) % modulus }) operator fun times(x: MultiModuloNumber): MultiModuloNumber { check(valueByModulus.keys == x.valueByModulus.keys) return MultiModuloNumber(valueByModulus.mapValues { (modulus, value) -> (value * x.valueByModulus.getValue(modulus)) % modulus }) } operator fun div(x: Int) = MultiModuloNumber(valueByModulus.mapValues { (modulus, value) -> (value / x) % modulus}) operator fun rem(x: Int): Int = valueByModulus.getValue(x) fun withValue(x: Int) = MultiModuloNumber(valueByModulus.mapValues { (modulus) -> x % modulus }) override fun toString(): String = valueByModulus.toString() } data class Throw(val monkeyIndex: Int, val itemWorryLevel: MultiModuloNumber) data class RawMonkey(val worryLevels: List<Int>, val inspectOperation: (MultiModuloNumber) -> MultiModuloNumber, val modulus: Int, val trueMonkey: Int, val falseMonkey: Int) class Monkey( initialWorryLevels: List<MultiModuloNumber>, private val inspectOperation: (MultiModuloNumber) -> MultiModuloNumber, private val modulus: Int, private val trueMonkey: Int, private val falseMonkey: Int ) { private val worryLevels = initialWorryLevels.toMutableList() var inspectedItems = 0L private set fun takeTurn(worryReducer: (MultiModuloNumber) -> MultiModuloNumber): List<Throw> { val result = worryLevels.map { val newLevel = worryReducer(inspectOperation(it)) Throw(if (newLevel % modulus == 0) trueMonkey else falseMonkey, newLevel) } inspectedItems += worryLevels.size worryLevels.clear() return result } fun addItem(worryLevel: MultiModuloNumber) { worryLevels.add(worryLevel) } } class MonkeyGroup(monkeys: Iterable<RawMonkey>) { private val monkeys = monkeys.let { val moduluses = monkeys.map { it.modulus } monkeys.map { (levels, inspectOperation, modulus, trueMonkey, falseMonkey) -> val worryLevels = levels.map { MultiModuloNumber(it, moduluses) } Monkey(worryLevels, inspectOperation, modulus, trueMonkey, falseMonkey) } } val monkeyBusiness get() = monkeys.sortedByDescending { it.inspectedItems } .let { (fst, snd) -> fst.inspectedItems * snd.inspectedItems } fun runRound(worryReducer: (MultiModuloNumber) -> MultiModuloNumber) { for (monkey in monkeys) { val throws = monkey.takeTurn(worryReducer) throws.forEach { (index, worryLevel) -> monkeys[index].addItem(worryLevel) } } } } fun readOperation(operation: String): (MultiModuloNumber) -> MultiModuloNumber { val (operand1, operator, operand2) = operation.split(' ') val func: (MultiModuloNumber, MultiModuloNumber) -> MultiModuloNumber = when (operator) { "+" -> MultiModuloNumber::plus "*" -> MultiModuloNumber::times else -> error("$operator is no operator") } return { func( if (operand1 == "old") it else it.withValue(operand1.toInt()), if (operand2 == "old") it else it.withValue(operand2.toInt()) ) } } fun readMonkeys(input: List<String>): MonkeyGroup = input.chunked(7) { lines -> val startingItems = lines[1].split(": ").last().split(", ").map { it.toInt() } val operation = readOperation(lines[2].split(" = ").last()) val modulus = lines[3].split(' ').last().toInt() val trueMonkey = lines[4].split(' ').last().toInt() val falseMonkey = lines[5].split(' ').last().toInt() RawMonkey(startingItems, operation, modulus, trueMonkey, falseMonkey) }.let { MonkeyGroup(it) } fun calculateMonkeyBusiness( monkeyGroup: MonkeyGroup, rounds: Int, worryReducer: (MultiModuloNumber) -> MultiModuloNumber = { it } ): Long { repeat(rounds) { monkeyGroup.runRound(worryReducer) } return monkeyGroup.monkeyBusiness } fun part1(input: List<String>): Long = calculateMonkeyBusiness(readMonkeys(input), 20) { it / 3} fun part2(input: List<String>): Long = calculateMonkeyBusiness(readMonkeys(input), 10000) // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
afbcec6a05b8df34ebd8543ac04394baa10216f0
5,449
advent-of-code-22
Apache License 2.0
src/aoc2022/Day04.kt
nguyen-anthony
572,781,123
false
null
package aoc2022 import utils.readInputAsList fun main() { fun part1(input: List<String>) : Int { var fullContains = 0 for(assignment in input) { val (elf1, elf2) = assignment.split(",") val (min1, max1) = elf1.split("-").map(String::toInt) val (min2, max2) = elf2.split("-").map(String::toInt) if( min1 <= min2 && max1 >= max2 || min2 <= min1 && max2 >= max1 ) fullContains++ } return fullContains } fun part2(input : List<String>) : Int { var allContains = 0 for(assignment in input) { val (elf1, elf2) = assignment.split(",") val (min1, max1) = elf1.split("-").map(String::toInt) val (min2, max2) = elf2.split("-").map(String::toInt) val pair1 = min1..max1 val pair2 = min2..max2 if( pair1.first in pair2 || pair1.last in pair2 || pair2.first in pair1 || pair2.last in pair1 ) allContains++ } return allContains } val input = readInputAsList("Day04", "2022") println(part1(input)) println(part2(input)) // test if implementation meets criteria from the description, like: val testInput = readInputAsList("Day04_test", "2022") check(part1(testInput) == 2) check(part2(testInput) == 4) }
0
Kotlin
0
0
9336088f904e92d801d95abeb53396a2ff01166f
1,387
AOC-2022-Kotlin
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/EqualSubstring.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode import kotlin.math.abs import kotlin.math.max /** * 1208. 尽可能使字符串相等 * 给你两个长度相同的字符串,s 和 t。 * * 将 s 中的第 i 个字符变到 t 中的第 i 个字符需要 |s[i] - t[i]| 的开销(开销可能为 0),也就是两个字符的 ASCII 码值的差的绝对值。 * * 用于变更字符串的最大预算是 maxCost。在转化字符串时,总开销应当小于等于该预算,这也意味着字符串的转化可能是不完全的。 * * 如果你可以将 s 的子字符串转化为它在 t 中对应的子字符串,则返回可以转化的最大长度。 * * 如果 s 中没有子字符串可以转化成 t 中对应的子字符串,则返回 0。 */ class EqualSubstring { companion object { @JvmStatic fun main(args: Array<String>) { println(EqualSubstring().solution("abcd", "bcdf", 3)) println(EqualSubstring().solution("abcd", "cdef", 3)) println(EqualSubstring().solution("abcd", "acde", 0)) } } // 输入:s = "abcd", t = "bcdf", cost = 3 // 输出:3 // 解释:s 中的 "abc" 可以变为 "bcd"。开销为 3,所以最大长度为 3。 // 双指针,滑动窗口 fun solution(s: String, t: String, maxCost: Int): Int { var max = 0 var i = 0 var j = 0 val length = s.length var currentCost = 0 while (i < length) { val sub = abs(s[i] - t[i]) when { currentCost + sub <= maxCost -> { currentCost += sub i++ } i != j -> { currentCost -= abs(s[j] - t[j]) max = max(max, i - j) j++ } else -> { i++ j++ } } } max = max(max, i - j) return max } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,014
daily_algorithm
Apache License 2.0
src/main/kotlin/g0801_0900/s0886_possible_bipartition/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0886_possible_bipartition // #Medium #Depth_First_Search #Breadth_First_Search #Graph #Union_Find // #Graph_Theory_I_Day_14_Graph_Theory #2023_04_08_Time_397_ms_(100.00%)_Space_51.3_MB_(100.00%) class Solution { fun possibleBipartition(n: Int, dislikes: Array<IntArray>): Boolean { // build graph val g = Graph(n) for (dislike in dislikes) { g.addEdge(dislike[0] - 1, dislike[1] - 1) } val marked = BooleanArray(n) val colors = BooleanArray(n) for (v in 0 until n) { if (!marked[v] && !checkBipartiteDFS(g, marked, colors, v)) { // No need to run on other connected components if one component has failed. return false } } return true } private fun checkBipartiteDFS(g: Graph, marked: BooleanArray, colors: BooleanArray, v: Int): Boolean { marked[v] = true for (w in g.adj(v)) { if (!marked[w]) { colors[w] = !colors[v] if (!checkBipartiteDFS(g, marked, colors, w)) { // this is to break for other neighbours return false } } else if (colors[v] == colors[w]) { return false } } return true } private class Graph(v: Int) { private val adj: Array<ArrayList<Int>?> init { adj = arrayOfNulls(v) for (i in 0 until v) { adj[i] = ArrayList<Int>() } } fun addEdge(v: Int, w: Int) { adj[v]!!.add(w) adj[w]!!.add(v) } fun adj(v: Int): List<Int> { return adj[v]!! } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,766
LeetCode-in-Kotlin
MIT License
src/Day01.kt
EemeliHeinonen
574,062,219
false
{"Kotlin": 6073}
fun sumByElf(input: List<String>): List<Int> = input.fold(mutableListOf(0)) { sums, currentString -> if (currentString == "") { sums.add(0) } else { sums[sums.lastIndex] = sums.last().plus(currentString.toInt()) } sums } fun main() { fun part1(input: List<String>): Int { return sumByElf(input).max() } fun part2(input: List<String>): Int { return sumByElf(input) .sorted() .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
0
33775d9e6e848ab0efae0e3f00f43368c036799d
784
aoc-22-kotlin
Apache License 2.0
src/Day07.kt
sushovan86
573,586,806
false
{"Kotlin": 47064}
import java.util.* sealed class Node( val name: String, val parent: Directory? = null, protected var size: Int = 0 ) { fun getNodeSize() = size override fun equals(other: Any?): Boolean { return Objects.equals(this, other) } override fun hashCode(): Int { return Objects.hash(name) } } class Directory( name: String, parent: Directory? = null ) : Node(name, parent) { private val children: MutableSet<Node> = mutableSetOf() fun addDirectory(name: String) { val newDirectory = Directory(name = name, parent = this) this.children += newDirectory } fun addFile(name: String, fileSize: Int) { val file = File(name = name, parent = this, size = fileSize) val isAdded = this.children.add(file) if (!isAdded) { return } // Adjust size of parent directories this.size += fileSize var parentDirectory = this.parent while (parentDirectory != null) { parentDirectory.size += fileSize parentDirectory = parentDirectory.parent } } fun goToDirectory(name: String): Directory = children.firstOrNull { it.name == name } as? Directory ?: error("Directory $name doesn't exist under ${this.name}") fun getAllSubDirectoriesUnderSize(maxSize: Int): List<Directory> { val directoryList = children.filterIsInstance<Directory>() .flatMap { it.getAllSubDirectoriesUnderSize(maxSize) } return if (size <= maxSize) { directoryList + this } else { directoryList } } } class File( name: String, parent: Directory, size: Int ) : Node(name, parent, size) fun main() { fun Directory.getSumOfDirectoriesUnder(maxSize: Int) = getAllSubDirectoriesUnderSize(maxSize) .sumOf(Directory::getNodeSize) fun Directory.getDirectoryToDeleteToFreeUp(freeUpSpace: Int) = getAllSubDirectoriesUnderSize(Int.MAX_VALUE) .filter { it.getNodeSize() > freeUpSpace } .minOf(Directory::getNodeSize) fun calculateSpaceToFreeUp(rootTest: Directory): Int { val totalSpace = 70_000_000 val totalUsedSpace = rootTest.getNodeSize() val availableFreeSpace = totalSpace - totalUsedSpace val spaceNeeded = 30_000_000 return spaceNeeded - availableFreeSpace } fun parseDirectoryListing(line: String, directory: Directory) = when { line.startsWith("dir") -> directory .addDirectory( line .removePrefix("dir ") .trim() ) line.first().isDigit() -> { val (size, name) = line.split(" ") directory.addFile(name, size.toInt()) } else -> error("Invalid Input $line") } fun parseDay07Input(input: String): Directory { val inputLines = input.split("$") .drop(2) .map(String::trim) // println(inputLines) val root = Directory("/") var current: Directory = root for (command in inputLines) { when (command.substring(0, 2)) { "cd" -> { val commandParam = command.removePrefix("cd").trim() current = when (commandParam) { ".." -> current.parent ?: error("No Parent Directory to ${current.name}") else -> current.goToDirectory(commandParam) } } "ls" -> command.lines() .drop(1) .forEach { parseDirectoryListing(it, current) } else -> error("Invalid command $command") } } return root } val testInput = readInputAsText("Day07_test") val rootTest = parseDay07Input(testInput) check(rootTest.getSumOfDirectoriesUnder(100_000) == 95437) check(rootTest.getDirectoryToDeleteToFreeUp(calculateSpaceToFreeUp(rootTest)) == 24_933_642) val input = readInputAsText("Day07") val root = parseDay07Input(input) println(root.getSumOfDirectoriesUnder(100_000)) println(root.getDirectoryToDeleteToFreeUp(calculateSpaceToFreeUp(root))) }
0
Kotlin
0
0
d5f85b6a48e3505d06b4ae1027e734e66b324964
4,325
aoc-2022
Apache License 2.0
src/main/kotlin/Day07.kt
brigham
573,127,412
false
{"Kotlin": 59675}
private val ElfDirectory.dirs: Sequence<ElfDirectory> get() = entries.asSequence().mapNotNull { it.asDirectory } fun ElfDirectory.getDirectory(name: String): ElfDirectory = dirs.first { it.name == name } interface ElfEntry { val name: String val size: Int val entries: List<ElfEntry> val asFile: ElfFile? val asDirectory: ElfDirectory? } data class ElfFile(override val name: String, override val size: Int, override val entries: List<ElfEntry> = listOf()) : ElfEntry { override val asFile: ElfFile = this override val asDirectory: ElfDirectory? = null } class ElfDirectory( override val name: String, val parent: ElfDirectory?, override val entries: MutableList<ElfEntry> = mutableListOf(), ) : ElfEntry { private var sizeCache: Int? = null private fun hasEntry(name: String): Boolean = entries.any { it.name == name } fun addDirectory(name: String) { check(!hasEntry(name)) entries.add(ElfDirectory(name, this)) } fun addFile(name: String, size: Int) { check(!hasEntry(name)) entries.add(ElfFile(name, size)) } fun walk(consumer: (dir: ElfDirectory) -> Unit) { val q = ArrayDeque<ElfDirectory>() q.add(this) while (q.isNotEmpty()) { val dir = q.removeFirst() consumer(dir) for (other in dir.dirs) { q.add(other) } } } override val size: Int get() { val curSizeCache = sizeCache return if (curSizeCache != null) curSizeCache else { val toCache = entries.sumOf { it.size } sizeCache = toCache return toCache } } override val asFile: ElfFile? = null override val asDirectory: ElfDirectory = this } class ElfFilesystem(var root: ElfDirectory = ElfDirectory("", null), var curdir: ElfDirectory? = null) { fun descend(name: String) { val newdir = curdir!!.getDirectory(name) curdir = newdir } fun ascend() { val newdir = curdir!!.parent curdir = newdir } fun gotoRoot() { curdir = root } } private const val TOTAL_SIZE = 70000000 private const val DESIRED_FREE_SPACE = 30000000 private const val PART1_MAX_SIZE = 100000 fun main() { fun parse(input: List<String>): ElfFilesystem { val iter = input.iterator() val fs = ElfFilesystem() var lsMode = false while (iter.hasNext()) { val line = iter.next().split(' ') when { line[0] == "$" -> { lsMode = false when (line[1]) { "cd" -> when (line[2]) { ".." -> fs.ascend() "/" -> fs.gotoRoot() else -> fs.descend(line[2]) } "ls" -> lsMode = true } } lsMode -> { when (line[0]) { "dir" -> fs.curdir!!.addDirectory(line[1]) else -> fs.curdir!!.addFile(line[1], line[0].toInt()) } } else -> { error("Unexpected $line") } } } return fs } fun part1(input: List<String>): Int { val fs = parse(input) var result = 0 fs.root.walk { val size = it.size if (size <= PART1_MAX_SIZE) { result += size } } return result } fun part2(input: List<String>): Int { val fs = parse(input) val rootSize = fs.root.size val freespace = TOTAL_SIZE - rootSize var result = rootSize fs.root.walk { val size = it.size if (size < result && size + freespace >= DESIRED_FREE_SPACE) { result = size } } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b87ffc772e5bd9fd721d552913cf79c575062f19
4,348
advent-of-code-2022
Apache License 2.0
src/Day10.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
fun main() { fun toValues(input: List<String>): List<Int> { val current = mutableListOf(1) input.forEach { current.add(current.last()) if (it.startsWith("addx")) { current.add(current.last() + it.split(" ")[1].toInt()) } } return current } fun part1(input: List<String>): Int { return toValues(input).withIndex().filter { (it.index + 1) % 40 == 20 && it.index <= 220 } .sumOf { (it.index + 1) * it.value } } fun whatToPrint(cycleNum: Int, current: Int): Char { return if ((cycleNum - 1) % 40 in current - 1..current + 1) { '#' } else { '.' } } fun part2(input: List<String>): String { return toValues(input).dropLast(1).asSequence().withIndex().map { whatToPrint(it.index + 1, it.value) }.chunked(40).map { it.joinToString("") }.joinToString("\n") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check( part2(testInput) == """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######.....""".trimIndent() ) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
1,719
advent-of-kotlin-2022
Apache License 2.0
year2018/src/main/kotlin/net/olegg/aoc/year2018/day23/Day23.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day23 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Vector3D import net.olegg.aoc.year2018.DayOf2018 import java.util.PriorityQueue /** * See [Year 2018, Day 23](https://adventofcode.com/2018/day/23) */ object Day23 : DayOf2018(23) { private val PATTERN = "pos=<(-?\\d+),(-?\\d+),(-?\\d+)>, r=(-?\\d+)".toRegex() override fun first(): Any? { val bots = lines .mapNotNull { line -> PATTERN.matchEntire(line)?.let { match -> val (x, y, z, r) = match.groupValues.drop(1).map { it.toInt() } return@mapNotNull Bot(Vector3D(x, y, z), r) } } val strong = bots.maxBy { it.r } return bots.count { strong.distance(it) <= strong.r } } override fun second(): Any? { val bots = lines .mapNotNull { line -> PATTERN.matchEntire(line)?.let { match -> val (x, y, z, r) = match.groupValues.drop(1).map { it.toInt() } return@mapNotNull Bot(Vector3D(x, y, z), r) } } var best = bots.count { it.pos.manhattan() <= it.r } to 0 val minX = bots.minOf { it.pos.x } val maxX = bots.maxOf { it.pos.x } val minY = bots.minOf { it.pos.y } val maxY = bots.maxOf { it.pos.y } val minZ = bots.minOf { it.pos.z } val maxZ = bots.maxOf { it.pos.z } val queue = PriorityQueue<Pair<Box, Int>>(compareBy({ -it.second }, { it.first.size })) queue.add(Box(Vector3D(minX, minY, minZ), Vector3D(maxX, maxY, maxZ)) to bots.count()) while (queue.isNotEmpty()) { val (box, botsIn) = queue.poll() if (botsIn < best.first) continue val selected = bots.filter { it.distance(box) <= it.r } if (box.size <= 32) { box.points().forEach { point -> val distance = point.manhattan() val botsCount = selected.count { it.distance(point) <= it.r } if (botsCount > best.first || (botsCount == best.first && distance < best.second)) { best = botsCount to distance queue.removeIf { it.second < botsCount } } } continue } val splits = box.split() .map { newBox -> newBox to selected.count { it.distance(newBox) <= it.r } } .filter { it.second >= best.first } queue.addAll(splits) } return best } data class Bot( val pos: Vector3D, val r: Int, ) { fun distance(other: Bot): Int { return (pos - other.pos).manhattan() } fun distance(other: Vector3D): Int { return (pos - other).manhattan() } fun distance( otherX: Int, otherY: Int, otherZ: Int ): Int { return (pos - Vector3D(otherX, otherY, otherZ)).manhattan() } fun distance(box: Box): Int { return distance( pos.x.coerceIn(box.min.x, box.max.x), pos.y.coerceIn(box.min.y, box.max.y), pos.z.coerceIn(box.min.z, box.max.z), ) } } data class Box( val min: Vector3D, val max: Vector3D, ) { fun split(): List<Box> { val midX = (min.x + max.x) / 2 val midY = (min.y + max.y) / 2 val midZ = (min.z + max.z) / 2 return listOf( Box(Vector3D(min.x, min.y, min.z), Vector3D(midX, midY, midZ)), Box(Vector3D(midX + 1, min.y, min.z), Vector3D(max.x, midY, midZ)), Box(Vector3D(min.x, midY + 1, min.z), Vector3D(midX, max.y, midZ)), Box(Vector3D(midX + 1, midY + 1, min.z), Vector3D(max.x, max.y, midZ)), Box(Vector3D(min.x, min.y, midZ + 1), Vector3D(midX, midY, max.z)), Box(Vector3D(midX + 1, min.y, midZ + 1), Vector3D(max.x, midY, max.z)), Box(Vector3D(min.x, midY + 1, midZ + 1), Vector3D(midX, max.y, max.z)), Box(Vector3D(midX + 1, midY + 1, midZ + 1), Vector3D(max.x, max.y, max.z)), ) } val size = maxOf(max.x - min.x, max.y - min.y, max.z - min.z) fun points(): Sequence<Vector3D> { return (min.x..max.x).asSequence().flatMap { x -> (min.y..max.y).asSequence().flatMap { y -> (min.z..max.z).asSequence().map { z -> Vector3D(x, y, z) } } } } } } fun main() = SomeDay.mainify(Day23)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
4,165
adventofcode
MIT License
06/src/commonMain/kotlin/Main.kt
daphil19
725,415,769
false
{"Kotlin": 131380}
expect fun getLines(): List<String> fun main() { var lines = getLines() // lines = """Time: 7 15 30 //Distance: 9 40 200""".lines() part1(lines) part2(lines) } fun part1(lines: List<String>) = printDuration { val times = lines[0].removePrefix("Time: ").trim().split(" ").filter { it.isNotBlank() }.map { it.toLong() } val distances = lines[1].removePrefix("Distance: ").trim().split(" ").filter { it.isNotBlank() }.map { it.toLong() } val res = times.zip(distances).map { (time, bestDist) -> // please don't int overflow... (0..time).count { speed -> val remaining = time - speed val dist = speed * remaining dist > bestDist }.toLong() }.reduce { acc, i -> acc * i } print("part 1: $res ") } fun part2(lines: List<String>) = printDuration { val time = lines[0].replace("\\D".toRegex(), "").toLong() val bestDist = lines[1].replace("\\D".toRegex(), "").toLong() // replace count with filter/fold in the event that we overflow val res = (0..time).filter { speed -> val remaining = time - speed val dist = speed * remaining dist > bestDist }.fold(0L) { acc, _ -> acc + 1} print("part 2: $res ") }
0
Kotlin
0
0
70646b330cc1cea4828a10a6bb825212e2f0fb18
1,256
advent-of-code-2023
Apache License 2.0
src/Day01.kt
ty-garside
573,030,387
false
{"Kotlin": 75779}
// Day 1: Calorie Counting // https://adventofcode.com/2022/day/1 fun main() { // NOTE: assumes always at least one elf and ignores possible // parsing errors and extra blank lines fun List<String>.sumOfCaloriesForEachElf() = fold(mutableListOf(0 /* first elf */)) { elves, calories -> elves.apply { if (calories.isBlank()) { // new elf, add a new zero element this += 0 } else { // add to current elf this[lastIndex] += calories.toInt() } } } fun part1(input: List<String>): Int { return input .sumOfCaloriesForEachElf() .max() } fun part2(input: List<String>): Int { return input .sumOfCaloriesForEachElf() .sortedDescending() .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)) println(part2(input)) } /* --- Day 1: Calorie Counting --- Santa's reindeer typically eat regular reindeer food, but they need a lot of magical energy to deliver presents on Christmas. For that, their favorite snack is a special type of star fruit that only grows deep in the jungle. The Elves have brought you on their annual expedition to the grove where the fruit grows. To supply enough magical energy, the expedition needs to retrieve a minimum of fifty stars by December 25th. Although the Elves assure you that the grove has plenty of fruit, you decide to grab any fruit you see along the way, just in case. Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input). The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's inventory (if any) by a blank line. For example, suppose the Elves finish writing their items' Calories and end up with the following list: 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 This list represents the Calories of the food carried by five Elves: The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories. The second Elf is carrying one food item with 4000 Calories. The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories. The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories. The fifth Elf is carrying one food item with 10000 Calories. In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf). Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? Your puzzle answer was 65912. --- Part Two --- By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most Calories of food might eventually run out of snacks. To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups. In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves is 45000. Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? Your puzzle answer was 195625. Both parts of this puzzle are complete! They provide two gold stars: ** */
0
Kotlin
0
0
49ea6e3ad385b592867676766dafc48625568867
4,481
aoc-2022-in-kotlin
Apache License 2.0
lib/src/main/kotlin/com/bloidonia/advent/day14/Day14.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day14 import com.bloidonia.advent.readText class Template( private val initialChar: Char, private val polymer: Map<String, Long>, private val insertions: Map<String, List<String>> ) { fun step(): Template { val next = mutableMapOf<String, Long>() polymer.forEach { entry -> val inserts = insertions[entry.key] if (inserts != null) { inserts.forEach { next[it] = (next[it] ?: 0L) + entry.value } } else { next[entry.key] = entry.value } } return Template(initialChar, next, insertions) } // Count is the initial char, plus the number of last chars in all the pairs fun count() = buildMap<Char, Long> { put(initialChar, 1L) polymer.forEach { entry -> put(entry.key.last(), getOrDefault(entry.key.last(), 0L) + entry.value) } }.let { map -> map.maxOf { it.value } - map.minOf { it.value } } } fun String.parsePolymers() = this.split("\n\n".toPattern(), limit = 2).let { (template, insertions) -> Template( this.first(), template.windowed(2).groupingBy { it }.eachCount().map { it.key to it.value.toLong() }.toMap(), insertions.split("\n").associate { tr -> tr.split(" -> ".toPattern(), limit = 2).let { (src, ins) -> src to listOf(src.first() + ins, ins + src.last()) } } ) } fun main() { println(generateSequence(readText("/day14input.txt").parsePolymers()) { it.step() }.drop(10).first().count()) println(generateSequence(readText("/day14input.txt").parsePolymers()) { it.step() }.drop(40).first().count()) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
1,757
advent-of-kotlin-2021
MIT License
kotlin/src/com/daily/algothrim/leetcode/medium/Exist.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 79. 单词搜索 * * 给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。 * 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。 */ class Exist { companion object { @JvmStatic fun main(args: Array<String>) { println(Exist().exist(arrayOf( charArrayOf('A', 'B', 'C', 'E'), charArrayOf('S', 'F', 'C', 'S'), charArrayOf('A', 'D', 'E', 'E') ), "ABCCED")) println(Exist().exist(arrayOf( charArrayOf('A', 'B', 'C', 'E'), charArrayOf('S', 'F', 'C', 'S'), charArrayOf('A', 'D', 'E', 'E') ), "SEE")) println(Exist().exist(arrayOf( charArrayOf('A', 'B', 'C', 'E'), charArrayOf('S', 'F', 'C', 'S'), charArrayOf('A', 'D', 'E', 'E') ), "ABCB")) println(Exist().exist(arrayOf( charArrayOf('a') ), "a")) } } // 输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" // 输出:true fun exist(board: Array<CharArray>, word: String): Boolean { board.forEachIndexed { i, chars -> chars.forEachIndexed { j, c -> if (board[i][j] == word[0]) { val result = backtracking(board, word, Array(board.size) { BooleanArray(board[0].size) }, i, j, 0) if (result) return true } } } return false } private fun backtracking(board: Array<CharArray>, word: String, visited: Array<BooleanArray>, i: Int, j: Int, index: Int): Boolean { if (!visited[i][j] && board[i][j] == word[index]) { if (index == word.length - 1) return true visited[i][j] = true var left = false var up = false var right = false var bottom = false if (i > 0) { left = backtracking(board, word, visited, i - 1, j, index + 1) } if (j > 0 && !left) { up = backtracking(board, word, visited, i, j - 1, index + 1) } if (i < board.size - 1 && !left && !up) { right = backtracking(board, word, visited, i + 1, j, index + 1) } if (j < board[0].size - 1 && !left && !up && !right) { bottom = backtracking(board, word, visited, i, j + 1, index + 1) } visited[i][j] = false return left || up || right || bottom } return false } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,969
daily_algorithm
Apache License 2.0
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day04/Day04.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day04 import eu.janvdb.aocutil.kotlin.readLines const val FILENAME = "input04.txt" const val CARD_SIZE = 5 fun main() { val lines = readLines(2021, FILENAME).map { it.trim() }.filter { it.isNotBlank() } val numbers = lines[0].split(",").map { it.toInt() } val cards = lines.asSequence() .drop(1) .map { line -> line.split(Regex(" +")).map { it.toInt() } } .chunked(CARD_SIZE) .map { it.flatten() } .map { BingoCard(it) } .toList() val wins = cards.map { it.calculateWin(numbers) } val win = wins.minByOrNull { it.numberOfTurns } println(win) val lose = wins.maxByOrNull { it.numberOfTurns } println(lose) } data class BingoCard(val values: List<Int>) { fun calculateWin(numbers: List<Int>): Win { for (index in 1..numbers.size) { val subList = numbers.subList(0, index).toSet() if (hasWin(subList)) { val numbersRemaining = values.minus(subList) return Win(index, numbersRemaining.sum() * numbers[index - 1]) } } return Win(Int.MAX_VALUE, 0) } private fun hasWin(subList: Set<Int>): Boolean { val foundNumbers = values.map { subList.contains(it) } for (x in 0 until CARD_SIZE) { var won1 = true var won2 = true for (y in 0 until CARD_SIZE) { if (!foundNumbers[x * 5 + y]) won1 = false if (!foundNumbers[y * 5 + x]) won2 = false } if (won1 || won2) { return true } } return false } } data class Win(val numberOfTurns: Int, val score: Int)
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,462
advent-of-code
Apache License 2.0
2022/09/09.kt
LiquidFun
435,683,748
false
{"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191}
operator fun Pair<Int, Int>.plus(o: Pair<Int, Int>) = Pair(this.first + o.first, this.second + o.second) fun main() { val input = generateSequence(::readlnOrNull).toList().map { it.split(" ") } val visited2: MutableSet<Pair<Int, Int>> = mutableSetOf() val visited10: MutableSet<Pair<Int, Int>> = mutableSetOf() val lookup = mapOf("D" to Pair(0, 1), "U" to Pair(0, -1), "L" to Pair(-1, 0), "R" to Pair(1, 0)) val rope = MutableList(10) { Pair(0, 0) } for ((dir, steps) in input) { for (j in 1..steps.toInt()) { rope[0] = rope[0] + lookup[dir]!! for (i in 0..rope.size-2) { val dx = rope[i].first - rope[i+1].first val dy = rope[i].second - rope[i+1].second if (Math.abs(dx) >= 2 || Math.abs(dy) >= 2) rope[i+1] = rope[i+1] + Pair(dx.coerceIn(-1..1), dy.coerceIn(-1..1)) } visited2.add(rope[1]) visited10.add(rope.last()) } } println(visited2.size) println(visited10.size) }
0
Kotlin
7
43
7cd5a97d142780b8b33b93ef2bc0d9e54536c99f
1,054
adventofcode
Apache License 2.0
src/main/kotlin/day09/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day09 import java.io.File private const val MAX_HEIGHT = 9 fun main() { val lines = File("src/main/kotlin/day09/input.txt").readLines() val mapSize = lines.size val heightMap: Array<IntArray> = Array(mapSize) { i -> lines[i].map { it.digitToInt() }.toIntArray() } var riskLevel = 0 val basins = mutableListOf<Set<Point>>() for (row in heightMap.indices) { for (col in heightMap[row].indices) { val currHeight = heightMap[row][col] val isLowPoint = ( (row == 0 || heightMap[row - 1][col] > currHeight) && (row == mapSize - 1 || row < mapSize - 1 && heightMap[row + 1][col] > currHeight) && (col == 0 || heightMap[row][col - 1] > currHeight) && (col == mapSize - 1 || col < mapSize - 1 && heightMap[row][col + 1] > currHeight) ) if (isLowPoint) { riskLevel += currHeight + 1 val lowPoint = Point(row, col) basins += scanBasinAroundPoint(lowPoint, heightMap, mutableSetOf()) } } } println(riskLevel) println(basins.map { it.size }.sortedDescending().take(3).reduce(Int::times)) } fun scanBasinAroundPoint(point: Point, heightMap: Array<IntArray>, basinPoints: MutableSet<Point>): Set<Point> { val heightMapSize = heightMap.size if ( point.row < 0 || point.row >= heightMapSize || point.col < 0 || point.col >= heightMapSize || heightMap[point.row][point.col] == MAX_HEIGHT || point in basinPoints ) return emptySet() basinPoints.add(point) scanBasinAroundPoint(Point(point.row - 1, point.col), heightMap, basinPoints) scanBasinAroundPoint(Point(point.row + 1, point.col), heightMap, basinPoints) scanBasinAroundPoint(Point(point.row, point.col - 1), heightMap, basinPoints) scanBasinAroundPoint(Point(point.row, point.col + 1), heightMap, basinPoints) return basinPoints } data class Point(val row: Int, val col: Int)
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
2,067
aoc-2021
MIT License
dsalgo/src/commonMain/kotlin/com/nalin/datastructurealgorithm/problems/DataStructure.kt
nalinchhajer1
534,780,196
false
{"Kotlin": 86359, "Ruby": 1605}
package com.nalin.datastructurealgorithm.problems fun findFibonacciSeries(n: Int): MutableList<Int> { val result = mutableListOf<Int>() var a = 0; result.add(a) if (n == 0) { return result } var b = 1; result.add(b) if (n == 1) { return result } var sum = 0; for (i in 2 until n) { sum = a + b a = b b = sum result.add(sum) } return result } fun primeNumbers(n: Int): List<Int> { val array = Array(n + 1) { true } array[0] = false array[1] = false var i = 2; while (i <= n) { if (array[i]) { var j = i + i while (j <= n) { array[j] = false j += i } } i++ } return array.mapIndexed() { index, b -> if (b) index else 0 }.filter { it > 0 } } fun gcd(a: Int, b: Int): Int { return if (b == 0) a else gcd(b, a % b) } fun lcm(a: Int, b: Int): Int { return (a * b) / gcd(a, b) } fun binarySearch(array: List<Int>, target: Int): Boolean { // Write your code here. fun search(range: IntRange): Boolean { val mid = range.start + ((range.endInclusive - range.start) shr 1) if (range.start > mid || range.start > range.endInclusive) return false; if (array[mid] == target) { return true; } if (array[mid] > target) { return search(range.start..mid - 1) } return search(mid + 1..range.endInclusive) } return search(0 until array.size) }
0
Kotlin
0
0
eca60301dab981d0139788f61149d091c2c557fd
1,555
kotlin-ds-algo
MIT License
src/main/kotlin/co/csadev/advent2021/Day03.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2021 by <NAME> * Advent of Code 2021, Day 3 * Problem Description: http://adventofcode.com/2021/day/3 */ package co.csadev.advent2021 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsList import co.csadev.adventOfCode.longest import co.csadev.adventOfCode.shortest class Day03(override val input: List<String> = resourceAsList("21day03.txt")) : BaseDay<List<String>, Int, Int> { override fun solvePart1(): Int { val gamma = (0 until (input.first().length)) .map { index -> input.sortedBy { it[index] }[input.size / 2][index] } .joinToString(separator = "") .toIntOrNull(2) ?: 0 val epsilon = gamma.inv() and (0xFFFF shr (16 - input.first().length)) return gamma * epsilon } override fun solvePart2(): Int = input.bitwiseFilter(true).toInt(2) * input.bitwiseFilter(false).toInt(2) private fun List<String>.bitwiseFilter(keepMostCommon: Boolean): String = first().indices.fold(this) { inputs, column -> if (inputs.size == 1) { inputs } else { val split = inputs.partition { it[column] == '1' } if (keepMostCommon) split.longest() else split.shortest() } }.first() fun originalPart2(): Int { val inputSize = input.first().length val gammaList = input.toMutableList() val epsilonList = input.toMutableList() (0 until inputSize).forEach { index -> val gammaLength = gammaList.size val gammaCount = gammaList.count { it[index] == '1' } val gammaCount0 = epsilonList.count { it[index] == '1' } if (gammaCount < gammaLength && gammaCount0 < gammaLength) { gammaList.removeIf { it[index] != if (gammaCount * 2 >= gammaLength) '1' else '0' } } val epsilonLength = epsilonList.size val epsilonCount = epsilonList.count { it[index] == '1' } val epsilonCount0 = epsilonList.count { it[index] == '0' } if (epsilonCount < epsilonLength && epsilonCount0 < epsilonLength) { epsilonList.removeIf { it[index] == if (epsilonCount * 2 >= epsilonLength) '1' else '0' } } } val gamma = gammaList.firstOrNull()?.toIntOrNull(2) ?: 0 val epsilon = epsilonList.firstOrNull()?.toIntOrNull(2) ?: 0 return gamma * epsilon } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,476
advent-of-kotlin
Apache License 2.0
src/main/kotlin/Day1.kt
noamfreeman
572,834,940
false
{"Kotlin": 30332}
private val part1ExampleInput = """ 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 """.trimIndent() private fun main() { println("day1") println() println("part1") assertEquals(part1(part1ExampleInput), 24_000) println(part1(readInputFile("day1_input.txt"))) println() println("part2") assertEquals(part2(part1ExampleInput), 45_000) println(part2(readInputFile("day1_input.txt"))) } private fun part1(input: String): Int { val calories: List<List<Int>> = parseInput(input) return calories.maxOf { it.sum() } } private fun part2(input: String): Int { val calories: List<List<Int>> = parseInput(input) return calories .map { it.sum() } .sorted() .takeLast(3) .sum() } private fun parseInput(input: String): List<List<Int>> { return input .splitByEmptyLines() .map { elf -> elf.lines().map { it.toInt() } } }
0
Kotlin
0
0
1751869e237afa3b8466b213dd095f051ac49bef
985
advent_of_code_2022
MIT License
leetcode/src/daily/mid/Q904.kt
zhangweizhe
387,808,774
false
null
package daily.mid fun main() { // 904. 水果成篮 // https://leetcode.cn/problems/fruit-into-baskets/ println(totalFruit(intArrayOf(1,2,3,2,2))) } fun totalFruit(fruits: IntArray): Int { // 其实就是找一个只包含两个元素的最长子序列 // 用一个 hashMap 存储出现的元素,以及这个元素出现的次数 // 且要保证 hashMap 中只能有2个键值对 // 用双指针 left、right 执行第一个元素,用 right 遍历数组,把遍历到的元素,加入到 hashMap 中, // 如果加入 hashMap 之后,键值对数量大于 2,要把 left 指针右移,并把 left 指针指向的元素的出现次数-1,如果次数减少到0,要把这个元素从 map 中移除 var left = 0 var right = 0 val map = HashMap<Int, Int>() var maxRange = 0 while (right < fruits.size) { map[fruits[right]] = map.getOrDefault(fruits[right], 0) + 1 while (map.size > 2) { // 键值对数量超过2,left 指针右移 map[fruits[left]] = map.getOrDefault(fruits[left], 0) - 1 if (map[fruits[left]]!! <= 0) { map.remove(fruits[left]) } left++ } val tmpRange = right - left + 1 if (tmpRange > maxRange) { maxRange = tmpRange } right++ } return maxRange }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,417
kotlin-study
MIT License
src/day2.kts
AfzalivE
317,962,201
false
null
println("Start") // val input = listOf( // "1-3 a: abcde", // "1-3 b: cdefg", // "2-9 c: ccccccccc" // ) val input = readInput("day2.txt").readLines() val validPasswords = findValid(input) println("${validPasswords.size} valid passwords") // println(validPasswords) fun findValid(input: List<String>): List<Pair<Policy, String>> { return input.map { val (policyStr, password) = it.split(":") Pair(Policy.fromString(policyStr), password.trim()) }.filter { it.first.matchesPart2(it.second) } } data class Policy( val min: Int, val max: Int, val letter: Char ) { fun matchesPart1(password: String): Boolean { val count = password.count { it == letter } return count in min..max } fun matchesPart2(password: String): Boolean { val minMatch = password[min - 1] == letter val maxMatch = password[max - 1] == letter return minMatch xor maxMatch // return (minMatch || maxMatch) && minMatch != maxMatch } companion object { fun fromString(string: String): Policy { val (range, letter) = string.split(" ") val (min, max) = range.split("-") return Policy(min.toInt(), max.toInt(), letter.single()) } } }
0
Kotlin
0
0
cc5998bfcaadc99e933fb80961be9a20541e105d
1,303
AdventOfCode2020
Apache License 2.0
src/day4/Day04.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day4 import readInput private fun part1(input: List<String>): Int { var result = 0 for(line in input) { val items = line.split(',') val first = items[0].split("-") val second = items[1].split("-") if((first[0].toInt() >= second[0].toInt() && first[1].toInt() <= second[1].toInt()) || (second[0].toInt() >= first[0].toInt() && second[1].toInt() <= first[1].toInt())) { result++ } } return result } private fun part2(input: List<String>): Int { var result = 0 for(line in input) { val items = line.split(',') val first = items[0].split("-") val second = items[1].split("-") if( first[0].toInt() > second[1].toInt() || first[1].toInt() < second[0].toInt() || second[1].toInt() < first[0].toInt() || second[0].toInt() > first[1].toInt() ) { result++ } } return input.size - result } fun main() { val input = readInput("day4/input") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
1,135
aoc-2022
Apache License 2.0
src/day04/Day04.kt
taer
573,051,280
false
{"Kotlin": 26121}
package day04 import readInput fun main() { fun oneContainsOther(first: IntRange, second: IntRange) = first.first <= second.first && first.last >= second.last fun parseInput(input: List<String>) = input.map { it.split(",") }.map { val first = it[0].split("-") val second = it[1].split("-") val firstRange = first[0].toInt()..first[1].toInt() val secondRange = second[0].toInt()..second[1].toInt() firstRange to secondRange } fun part1(input: List<String>): Int { return parseInput(input).count { (first, second) -> oneContainsOther(first, second) || oneContainsOther(second, first) } } fun part2(input: List<String>): Int { return parseInput(input) .count { (first, second) -> first.intersect(second).isNotEmpty() } } val testInput = readInput("day04", true) val input = readInput("day04") check(part1(testInput) == 2) println(part1(input)) check(part2(testInput) == 4) println(part2(input)) }
0
Kotlin
0
0
1bd19df8949d4a56b881af28af21a2b35d800b22
1,092
aoc2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day15.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day fun main() = Day15.run() object Day15 : Day(2015, 15) { data class Ingredient(val name: String, val cap: Int, val dur: Int, val fla: Int, val tex: Int, val cal: Int) private val inp = input.lines().map { val (ing, cap, dur, fla, tex, cal) = """(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""".toRegex().find(it)!!.destructured Ingredient(ing, cap.toInt(), dur.toInt(), fla.toInt(), tex.toInt(), cal.toInt()) }.toList() private fun score(a: Int, b: Int, c: Int, d: Int): Int { var score = 1 score *= 0.coerceAtLeast(inp[0].cap * a + inp[1].cap * b + inp[2].cap * c + inp[3].cap * d) score *= 0.coerceAtLeast(inp[0].dur * a + inp[1].dur * b + inp[2].dur * c + inp[3].dur * d) score *= 0.coerceAtLeast(inp[0].fla * a + inp[1].fla * b + inp[2].fla * c + inp[3].fla * d) score *= 0.coerceAtLeast(inp[0].tex * a + inp[1].tex * b + inp[2].tex * c + inp[3].tex * d) return score } override fun part1(): Any { var score = 0 for (a in 0..100) { for (b in 0..100 - a) { for (c in 0..100 - a - b) { val d = 100 - a - b - c score = score.coerceAtLeast(score(a, b, c, d)) } } } return score } private fun calOf(a: Int, b: Int, c: Int, d: Int) = inp[0].cal * a + inp[1].cal * b + inp[2].cal * c + inp[3].cal * d override fun part2(): Any { var score = 0 for (a in 0..100) { for (b in 0..100 - a) { for (c in 0..100 - a - b) { val d = 100 - a - b - c val localScore = score(a, b, c, d) if (localScore > score && calOf(a, b, c, d) == 500) { score = localScore } } } } return score } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,018
adventofkotlin
MIT License
AoC2022/src/main/kotlin/xyz/danielstefani/Day8.kt
OpenSrcerer
572,873,135
false
{"Kotlin": 14185}
package xyz.danielstefani import java.util.function.Function lateinit var trees: List<List<Int>> const val GRID_SIZE = 4 fun main() { trees = object {}.javaClass .classLoader .getResource("Day8Input.in")!! .readText() .split("\n") .map { it.map { it.digitToInt() }.toList() } // Part 1 var visible = 0 for (row in trees.indices) { for (column in trees.indices) { val top = isVisible(trees[row][column], row - 1, column, rowFunction = { r -> r - 1 }) val bottom = isVisible(trees[row][column], row + 1, column, rowFunction = { r -> r + 1 }) val left = isVisible(trees[row][column], row, column - 1, columnFunction = { c -> c - 1 }) val right = isVisible(trees[row][column], row, column + 1, columnFunction = { c -> c + 1 }) if (top || bottom || left || right) visible++ } } println(visible) // Part 2 var maxScenicScore = 0 for (row in trees.indices) { for (column in trees.indices) { val top = getScenicScore(row - 1, column, rowFunction = { r -> r - 1 }) val bottom = getScenicScore(row + 1, column, rowFunction = { r -> r + 1 }) val left = getScenicScore(row, column - 1, columnFunction = { c -> c - 1 }) val right = getScenicScore(row, column + 1, columnFunction = { c -> c + 1 }) val score = top * bottom * left * right if (score > maxScenicScore) maxScenicScore = score } } println(maxScenicScore) } fun isVisible(treeHeight: Int, row: Int, column: Int, rowFunction: Function<Int, Int> = Function { r -> r }, columnFunction: Function<Int, Int> = Function { c -> c } ): Boolean { if (column < 0 || column > GRID_SIZE || row < 0 || row > GRID_SIZE) return true if (treeHeight <= trees[row][column]) return false if (column == 0 || column == GRID_SIZE || row == 0 || row == GRID_SIZE) return true return isVisible(treeHeight, rowFunction.apply(row), columnFunction.apply(column), rowFunction, columnFunction) } fun getScenicScore(row: Int, column: Int, rowFunction: Function<Int, Int> = Function { r -> r }, columnFunction: Function<Int, Int> = Function { c -> c } ): Int { if (column <= 0 || column >= GRID_SIZE || row <= 0 || row >= GRID_SIZE) return 0 return 1 + getScenicScore(rowFunction.apply(row), columnFunction.apply(column), rowFunction, columnFunction) }
0
Kotlin
0
3
84b9b62e15c70a4a17f8b2379dc29f9daa9f4be3
2,503
aoc-2022
The Unlicense
src/main/java/io/deeplay/qlab/algorithm/placer/PlacerHelper.kt
oQaris
475,961,305
false
{"Jupyter Notebook": 766904, "Java": 47993, "Kotlin": 23299}
package io.deeplay.qlab.algorithm.placer import com.github.shiguruikai.combinatoricskt.combinations import com.github.shiguruikai.combinatoricskt.permutations import com.github.shiguruikai.combinatoricskt.powerset import io.deeplay.qlab.algorithm.eval.IEvaluator import io.deeplay.qlab.parser.models.Unit import io.deeplay.qlab.parser.models.input.EnemyLocation import io.deeplay.qlab.parser.models.output.UnitWithLocation fun findBestArrangement( units: Set<Unit>, locations: Set<EnemyLocation>, strategy: IEvaluator ): Set<UnitWithLocation> { if (locations.isEmpty() || units.isEmpty()) return emptySet() return locations.flatMap { arrangeUnitsOnLocation(units, it) }.maxByOrNull { strategy.evaluateGoldProfit(it.toSet()) }!!.toSet() } private fun arrangeUnitsOnLocation( units: Set<Unit>, location: EnemyLocation ): Sequence<List<UnitWithLocation>> { val enemyPos = location.opponentUnits .map { it.locatePosition }.toSet() return units.powerset() .filter { it.size <= location.maxPositionsQuantity - enemyPos.size } .flatMap { unitSet -> val places = (0 until location.maxPositionsQuantity) .minus(enemyPos) .take(unitSet.size) // Убрать, если не нужна "стекоподобность" размещения generateUnitPositionPairs(unitSet, places).map { unitsWithPos -> unitsWithPos.map { it.first.toUnitWithLocation( location, it.second ) } } } } private fun generateUnitPositionPairs( units: Collection<Unit>, places: Collection<Int> ): Sequence<List<Pair<Unit, Int>>> { require(places.size >= units.size) return places.combinations(units.size) .flatMap { it.permutations() } // Убрать, если позиции не влияют на юнитов (т.е. 123 = 312) .map { units.zip(it) } } private fun Unit.toUnitWithLocation(location: EnemyLocation, position: Int) = UnitWithLocation(name, sourceGoldCount, position, location)
0
Jupyter Notebook
0
0
5dd497b74a767c740386dc67e6841673b17b96fb
2,173
QLab
MIT License
src/Day03.kt
AleksanderBrzozowski
574,061,559
false
null
import java.lang.IllegalArgumentException fun main() { fun Char.priority(): Int = if (this.isUpperCase()) this.code - 38 else this.code - 96 fun String.splitIntoCompartments(): Pair<String, String> = take(length / 2) to substring(length / 2) fun Pair<String, String>.itemInBothCompartments(): Char { val (first, second) = this return first.find { second.contains(it) } ?: throw IllegalArgumentException("No item found that is present in both compartments") } fun List<String>.commonItem(): Char { val first = first() val rest = drop(1) return first.find { item -> rest.all { items -> items.contains(item) } } ?: throw IllegalArgumentException("No item found that is present in all compartments") } val testResult = readInput("Day03").sumOf { it.splitIntoCompartments() .itemInBothCompartments() .priority() } println(testResult) val result = readInput("Day03") .foldIndexed(emptyList<List<String>>()) { index, rucksacks, input -> if (index % 3 == 0) rucksacks + listOf(listOf(input)) else rucksacks.replaceLast { it + input } } .sumOf { it.commonItem().priority() } println(result) }
0
Kotlin
0
0
161c36e3bccdcbee6291c8d8bacf860cd9a96bee
1,302
kotlin-advent-of-code-2022
Apache License 2.0
src/days/Day12.kt
EnergyFusion
572,490,067
false
{"Kotlin": 48323}
import java.io.BufferedReader fun main() { val day = 12 fun getHeight(char: Char):Int { return if (char.isUpperCase()) { if (char == 'S') { 0 } else { 27 } } else { char.code - 96 } } fun setupMapAndStepNodes(stepNodes: MutableList<StepNode>, inputReader: BufferedReader): Array<Array<StepNode>> { lateinit var map: Array<Array<StepNode>> var i = 0 var width: Int inputReader.forEachLine { line -> val row = line.toCharArray() if (i == 0) { width = row.size map = Array(width) { r -> Array(width, init = { c -> StepNode(coords = Pair(r,c)) }) } } row.forEachIndexed{ j, char -> // print("%02d ".format(getHeight(char))) val node = StepNode(height = getHeight(char), coords = Pair(i,j)) stepNodes.add(node) map[i][j] = node } // println() i++ } return map } fun checkNeighbors(map: Array<Array<StepNode>>, i: Int, j: Int): List<StepNode> { val neighbours = mutableListOf<StepNode>() val currH = map[i][j].height //Check left if (j > 0 && map[i][j-1].height <= currH+1) { neighbours.add(map[i][j-1]) } //Check up if (i > 0 && map[i-1][j].height <= currH+1) { neighbours.add(map[i-1][j]) } //Check right if (j < map[i].size-1 && map[i][j+1].height <= currH+1) { neighbours.add(map[i][j+1]) } //Check down if (i < map.size-1 && map[i+1][j].height <= currH+1) { neighbours.add(map[i+1][j]) } return neighbours } fun updateNeighbors(map: Array<Array<StepNode>>): Pair<Pair<Int, Int>, Pair<Int, Int>> { var heighestPoint = Pair(0, 0) var startPoint = Pair(0, 0) var i = 0 while (i < map.size) { var j = 0 while (j < map[i].size) { map[i][j].neighbours.addAll(checkNeighbors(map, i, j)) if (map[i][j].height == 27) { heighestPoint = Pair(i, j) } if (map[i][j].height == 0) { startPoint = Pair(i, j) } j++ } i++ } return Pair(startPoint, heighestPoint) } fun bfs(map: Array<Array<StepNode>>, queue: MutableList<Pair<Int, Int>>, target: Pair<Int, Int>): Int { val dist = queue.associateWith { 0 }.toMutableMap() val dirs = listOf(-1 to 0, 1 to 0, 0 to 1, 0 to -1) while (queue.isNotEmpty()) { val (y, x) = queue.removeFirst() dirs .map { (ya, xa) -> Pair(y+ya, x+xa) } .filter { (ya, xa) -> ya in map.indices && xa in map[0].indices } .filter { !dist.contains(it) } .filter { (ya, xa) -> map[ya][xa].height <= map[y][x].height + 1 } .forEach { dist[it] = dist[Pair(y, x)]!! + 1 queue.add(it) } } return dist[target]!! } fun part1(inputReader: BufferedReader): Int { val stepNodes = mutableListOf<StepNode>() val map = setupMapAndStepNodes(stepNodes, inputReader) val (startPoint, heighestPoint) = updateNeighbors(map) val steps = bfs(map, mutableListOf(startPoint), heighestPoint) val result = steps //path.size-1 println(result) println() return result } fun updateNeighbors2(map: Array<Array<StepNode>>): Pair<MutableList<Pair<Int, Int>>, Pair<Int, Int>> { var heighestPoint = Pair(0, 0) var startPoints = mutableListOf<Pair<Int, Int>>() var i = 0 while (i < map.size) { var j = 0 while (j < map[i].size) { map[i][j].neighbours.addAll(checkNeighbors(map, i, j)) if (map[i][j].height == 27) { heighestPoint = Pair(i, j) } if (map[i][j].height == 0 || map[i][j].height == 1) { startPoints.add(Pair(i, j)) } j++ } i++ } return Pair(startPoints, heighestPoint) } fun part2(inputReader: BufferedReader): Int { val stepNodes = mutableListOf<StepNode>() val map = setupMapAndStepNodes(stepNodes, inputReader) val (startPoints, heighestPoint) = updateNeighbors2(map) val steps = bfs(map, startPoints, heighestPoint) val result = steps //path.size-1 println(result) println() return result } val testInputReader = readBufferedInput("tests/Day%02d".format(day)) // check(part1(testInputReader) == 31) check(part2(testInputReader) == 29) val input = readBufferedInput("input/Day%02d".format(day)) // println(part1(input)) println(part2(input)) } data class StepNode(val neighbours:MutableList<StepNode> = mutableListOf(), var height: Int = -99, var coords: Pair<Int, Int>, var visited: Boolean = false) { override fun toString(): String { return "%02d - (%d,%d)".format(height, coords.first, coords.second) } override fun hashCode(): Int { return coords.first*999 + coords.second } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as StepNode // if (neighbours != other.neighbours) return false if (height != other.height) return false if (coords != other.coords) return false if (visited != other.visited) return false return true } }
0
Kotlin
0
0
06fb8085a8b1838289a4e1599e2135cb5e28c1bf
5,965
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2020/Day20.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2020 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.Point2D import com.chriswk.aoc.util.report import kotlin.math.sqrt class Day20 : AdventDay(2020, 20) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day20() report { day.part1() } report { day.part2() } } } fun part1(): Long { val tiles = parseInput(inputAsString) val image = createImage(tiles) return image.first().first().id * image.first().last().id * image.last().first().id * image.last().last().id } fun part2(): Int { val seaMonsterOffsets = listOf( Point2D(0, 18), Point2D(1, 0), Point2D(1, 5), Point2D(1, 6), Point2D(1, 11), Point2D(1, 12), Point2D(1, 17), Point2D(1, 18), Point2D(1, 19), Point2D(2, 1), Point2D(2, 4), Point2D(2, 7), Point2D(2, 10), Point2D(2, 13), Point2D(2, 16) ) val tiles = parseInput(inputAsString) val image = createImage(tiles) return imageToSingleTile(tiles, image) .orientations() .first { it.maskIfFound(seaMonsterOffsets) } .body .sumOf { row -> row.count { char -> char == '#' } } } private fun imageToSingleTile(tiles: List<Tile>, image: List<List<Tile>>): Tile { val rowsPerTile = tiles.first().body.size val body = image.flatMap { row -> (1 until rowsPerTile - 1).map { y -> row.joinToString("") { it.insetRow(y) }.toCharArray() } }.toTypedArray() return Tile(0, body) } fun cornerProduct(image: List<List<Tile>>): Long { return image.first().first().id * image.first().last().id * image.last().first().id * image.last().last().id } fun createImage(tiles: List<Tile>): List<List<Tile>> { val width = sqrt(tiles.count().toFloat()).toInt() var mostRecentTile: Tile = findTopCorner(tiles) var mostRecentRowHeader: Tile = mostRecentTile return (0 until width).map { row -> (0 until width).map { col -> when { row == 0 && col == 0 -> mostRecentTile col == 0 -> { mostRecentRowHeader = mostRecentRowHeader.findAndOrientNeighbor(Orientation.South, Orientation.North, tiles) mostRecentTile = mostRecentRowHeader mostRecentRowHeader } else -> { mostRecentTile = mostRecentTile.findAndOrientNeighbor(Orientation.East, Orientation.West, tiles) mostRecentTile } } } } } fun findTopCorner(tiles: List<Tile>): Tile = tiles .first { tile -> tile.sharedSideCount(tiles) == 2 } .orientations() .first { it.isSideShared(Orientation.South, tiles) && it.isSideShared(Orientation.East, tiles) } enum class Orientation { North, East, South, West } class Tile(val id: Long, var body: Array<CharArray>) { private val sides: Set<String> = Orientation.values().map { sideFacing(it) }.toSet() private val sidesReversed = sides.map { it.reversed() }.toSet() fun sharedSideCount(tiles: List<Tile>): Int = sides.sumOf { side -> tiles .filterNot { it.id == id } .count { tile -> tile.hasSide(side) } } fun isSideShared(dir: Orientation, tiles: List<Tile>): Boolean = tiles .filterNot { it.id == id } .any { tile -> tile.hasSide(sideFacing(dir)) } fun findAndOrientNeighbor(mySide: Orientation, theirSide: Orientation, tiles: List<Tile>): Tile { val mySideValue = sideFacing(mySide) return tiles .filterNot { it.id == id } .first { it.hasSide(mySideValue) } .also { it.orientToSide(mySideValue, theirSide) } } fun insetRow(row: Int): String = body[row].drop(1).dropLast(1).joinToString("") fun maskIfFound(mask: List<Point2D>): Boolean { var found = false val maxWidth = mask.maxByOrNull { it.y }!!.y val maxHeight = mask.maxByOrNull { it.x }!!.x (0..(body.size - maxHeight)).forEach { x -> (0..(body.size - maxWidth)).forEach { y -> val lookingAt = Point2D(x, y) val actualSpots = mask.map { it + lookingAt } if (actualSpots.all { body[it.x][it.y] == '#' }) { found = true actualSpots.forEach { body[it.x][it.y] = '0' } } } } return found } fun orientations(): Sequence<Tile> = sequence { repeat(2) { repeat(4) { yield(this@Tile.rotateClockwise()) } this@Tile.flip() } } fun hasSide(side: String): Boolean = side in sides || side in sidesReversed private fun flip(): Tile { body = body.map { it.reversed().toCharArray() }.toTypedArray() return this } private fun rotateClockwise(): Tile { body = body.mapIndexed { x, row -> row.mapIndexed { y, _ -> body[y][x] }.reversed().toCharArray() }.toTypedArray() return this } fun sideFacing(dir: Orientation): String = when (dir) { Orientation.North -> body.first().joinToString("") Orientation.South -> body.last().joinToString("") Orientation.West -> body.map { row -> row.first() }.joinToString("") Orientation.East -> body.map { row -> row.last() }.joinToString("") } private fun orientToSide(side: String, direction: Orientation) = orientations().first { it.sideFacing(direction) == side } } fun parseInput(input: String): List<Tile> = input.split("\n\n").map { it.lines() }.map { tileText -> val id = tileText.first().substringAfter(" ").substringBefore(":").toLong() val body = tileText.drop(1).map { it.toCharArray() }.toTypedArray() Tile(id, body) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
6,748
adventofcode
MIT License
src/main/kotlin/Day4.kt
ivan-gusiev
726,608,707
false
{"Kotlin": 34715, "Python": 2022, "Makefile": 50}
import util.AocDay import util.AocInput typealias Day4InputType = List<Day4.ScratchCard>; class Day4 : Runner { val TEST_INPUT: String = """ Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11 """.trimIndent() override fun run() { val day = AocDay("2023".toInt(), "4".toInt()) val lines = AocInput.lines(day) //val lines = TEST_INPUT.split("\n") val cards = lines.map(ScratchCard::parse) part1(cards) part2(cards) } private fun part1(input: Day4InputType) { val scores = input.map(ScratchCard::part1Score) println(scores.sum()) } private fun part2(input: Day4InputType) { val calculator = ScoreCalculator(input) val totalScore = input .map { x -> calculator.scoreByIndex(x.id) } .reduce(CardDistribution::plus) .ids .reduce(Int::plus) println(totalScore) } class ScoreCalculator(private val cards: List<ScratchCard>) { private val distributionByIndexCache = mutableMapOf<Int, CardDistribution>() private fun getByIndex(i: Int): ScratchCard { return cards[i - 1] } private fun calculateDistribution(i: Int): CardDistribution { val nums = IntArray(cards.size) val card = getByIndex(i) val winnerIds = card.winnerIds() nums[i - 1] = 1 var distro = CardDistribution(nums) winnerIds.forEach { distro += scoreByIndex(it) } return distro } fun scoreByIndex(i: Int): CardDistribution { return distributionByIndexCache.getOrPut(i) { calculateDistribution(i) } } } data class CardDistribution(val ids: IntArray) { operator fun plus(other: CardDistribution): CardDistribution { return CardDistribution(ids.zip(other.ids) { a, b -> a + b }.toIntArray()) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as CardDistribution return ids.contentEquals(other.ids) } override fun hashCode(): Int { return ids.contentHashCode() } override fun toString(): String { return ids.joinToString(",") } } data class ScratchCard(val id: Int, val winningNumbers: List<Int>, val scratchNumbers: List<Int>) { companion object { // parses text like a line of from TEST_INPUT and returns a ScratchCard fun parse(input: String): ScratchCard { val parts = input.replace("Card ", "").split(":") val id = parts[0].trim().toInt() val numbers = parts[1].split("|").map { it.trim() } val winningNumbers = numbers[0].split(Regex("\\s+")).map(String::toInt) val scratchNumbers = numbers[1].split(Regex("\\s+")).map(String::toInt) return ScratchCard(id, winningNumbers, scratchNumbers) } } private fun winningCount(): Int { return scratchNumbers.count { it in winningNumbers } } // return 0 if winningCount() == 0, and 2^i, where i is the number of winning numbers fun part1Score(): Int { val count = winningCount() if (count == 0) return 0 return 1 shl (count - 1) } fun winnerIds(): List<Int> { return (id + 1..id + winningCount()).toList() } // returns the representation of ScratchCard as a String, like TEST_INPUT override fun toString(): String { return "Card $id: ${winningNumbers.joinToString(" ")} | ${scratchNumbers.joinToString(" ")}" } } }
0
Kotlin
0
0
5585816b435b42b4e7c77ce9c8cabc544b2ada18
4,137
advent-of-code-2023
MIT License
src/Day14.kt
6234456
572,616,769
false
{"Kotlin": 39979}
import kotlin.math.min fun main() { fun part1(input: List<String>): Int { var minX = Int.MAX_VALUE var maxX = Int.MIN_VALUE var maxY = Int.MIN_VALUE input.forEach { it.split(" -> ").forEach { val tmp = it.split(",").map { it.toInt() } minX = kotlin.math.min(minX, tmp.first()) maxX = kotlin.math.max(maxX, tmp.first()) maxY = kotlin.math.max(maxY, tmp.last()) } } val stage = Array<BooleanArray>(maxX - minX + 1){ BooleanArray(maxY + 1){false} } input.forEach { val t = it.split(" -> ").map { val tmp = it.split(",").map { it.toInt() } tmp.first() to tmp.last() } (1 until t.size).forEach { val current = t[it] val last = t[it - 1] if (current.first == last.first){ val min = kotlin.math.min(current.second, last.second) val max = kotlin.math.max(current.second, last.second) (min .. max).forEach { stage[current.first - minX][it] = true } }else{ val min = kotlin.math.min(current.first, last.first) val max = kotlin.math.max(current.first, last.first) (min .. max).forEach { stage[it - minX][current.second] = true } } } } fun drop(x0:Int = 500, y0:Int = 0):Boolean{ var x = x0 - minX var y = y0 while(x < stage.size && x >= 0 && y <= maxY && y >= 0){ if (stage[x][y]) return false if(y+1 <= maxY && stage[x][y+1]){ if (x >= 1 && stage[x-1][y+1]){ if (x + 1 < stage.size && stage[x+1][y+1]){ stage[x][y] = true return true } else{ x++ y++ } }else{ x-- y++ } }else{ y++ } } return false } var ans = 0 while (true){ ans++ if(!drop()){ return ans - 1 } } } fun part2(input: List<String>): Int{ var minX = Int.MAX_VALUE var maxX = Int.MIN_VALUE var maxY = Int.MIN_VALUE input.forEach { it.split(" -> ").forEach { val tmp = it.split(",").map { it.toInt() } minX = kotlin.math.min(minX, tmp.first()) maxX = kotlin.math.max(maxX, tmp.first()) maxY = kotlin.math.max(maxY, tmp.last()) } } maxY += 2 minX = -2000 maxX = 2000 val stage = Array<BooleanArray>(maxX - minX + 1){ BooleanArray(maxY + 1){false} } input.forEach { val t = it.split(" -> ").map { val tmp = it.split(",").map { it.toInt() } tmp.first() to tmp.last() } (1 until t.size).forEach { val current = t[it] val last = t[it - 1] if (current.first == last.first){ val min = kotlin.math.min(current.second, last.second) val max = kotlin.math.max(current.second, last.second) (min .. max).forEach { stage[current.first - minX][it] = true } }else{ val min = kotlin.math.min(current.first, last.first) val max = kotlin.math.max(current.first, last.first) (min .. max).forEach { stage[it - minX][current.second] = true } } } } (0 until stage.size).forEach { stage[it][maxY] = true } fun drop(x0:Int = 500, y0:Int = 0):Boolean{ var x = x0 - minX var y = y0 while(x < stage.size && x >= 0 && y <= maxY && y >= 0){ if (stage[x][y]) return false if(y+1 <= maxY && stage[x][y+1]){ if (x >= 1 && stage[x-1][y+1]){ if (x + 1 < stage.size && stage[x+1][y+1]){ stage[x][y] = true return true } else{ x++ y++ } }else{ x-- y++ } }else{ y++ } } return false } var ans = 0 while (true){ ans++ if(!drop()){ return ans - 1 } } } var input = readInput("Test14") println(part1(input)) println(part2(input)) input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b6d683e0900ab2136537089e2392b96905652c4e
5,426
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinOperationsToMakeArrayContinuous.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 2009. Minimum Number of Operations to Make Array Continuous * @see <a href="https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous">Source</a> */ fun interface MinOperationsToMakeArrayContinuous { operator fun invoke(nums: IntArray): Int } /** * Approach 1: Binary Search */ class MinOperationsToMakeArrayContinuousBS : MinOperationsToMakeArrayContinuous { override fun invoke(nums: IntArray): Int { val n: Int = nums.size var ans = n val newNums = nums.newUniqueArray() for (i in newNums.indices) { val left = newNums[i] val right = left + n - 1 val j = binarySearch(newNums, right) val count = j - i ans = min(ans.toDouble(), (n - count).toDouble()).toInt() } return ans } private fun binarySearch(newNums: IntArray, target: Int): Int { var left = 0 var right = newNums.size while (left < right) { val mid = (left + right) / 2 if (target < newNums[mid]) { right = mid } else { left = mid + 1 } } return left } } /** * Approach 2: Sliding Window */ class MinOperationsToMakeArrayContinuousSW : MinOperationsToMakeArrayContinuous { override fun invoke(nums: IntArray): Int { val n: Int = nums.size var ans = n val newNums = nums.newUniqueArray() var j = 0 for (i in newNums.indices) { while (j < newNums.size && newNums[j] < newNums[i] + n) { j++ } val count = j - i ans = min(ans.toDouble(), (n - count).toDouble()).toInt() } return ans } } private fun IntArray.newUniqueArray(): IntArray { val unique = HashSet<Int>() for (num in this) { unique.add(num) } val newNums = IntArray(unique.size) var index = 0 for (num in unique) { newNums[index++] = num } newNums.sort() return newNums }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,734
kotlab
Apache License 2.0
src/main/kotlin/days/Day3.kt
hughjdavey
725,972,063
false
{"Kotlin": 76988}
package days import xyz.hughjd.aocutils.Coords.Coord class Day3 : Day(3) { val bounds = Coord(inputList[0].length, inputList.size) private val numbers = schematicMatches(Regex("\\d+")) private val partNumbers = numbers.filter { number -> number.getValidAdjacents(bounds).any { !Character.isDigit(inputList[it.y][it.x]) && inputList[it.y][it.x] != '.' } } override fun partOne(): Any { return partNumbers.sumOf { it.value.toInt() } } override fun partTwo(): Any { return schematicMatches(Regex("\\*")) .filter { star -> star.getAdjacentSlices(bounds, partNumbers).size == 2 } .map { gear -> gear.getAdjacentSlices(bounds, partNumbers) } .sumOf { it[0].toInt() * it[1].toInt() } } fun schematicMatches(regex: Regex): List<SchematicMatch> { return inputList.flatMapIndexed { y, line -> val matches = regex.findAll(line).toList() matches.map { SchematicMatch(it.value, it.range.map { x -> Coord(x, y) }) } } } data class SchematicMatch(val value: String, val coords: List<Coord>) { fun getValidAdjacents(bounds: Coord): List<Coord> { return coords.flatMap { it.getAdjacent(true) } .filter { it.x >= 0 && it.y >= 0 && it.x < bounds.x && it.y < bounds.y } .filterNot { coords.contains(it) } .distinct() } fun getAdjacentSlices(bounds: Coord, slices: List<SchematicMatch>): List<String> { return getValidAdjacents(bounds) .flatMap { a -> slices.filter { it.coords.contains(a) }.map { it.value } } .distinct() } } }
0
Kotlin
0
0
330f13d57ef8108f5c605f54b23d04621ed2b3de
1,703
aoc-2023
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/staricka/adventofcode2023/days/Day17.kt
mathstar
719,656,133
false
{"Kotlin": 107115}
package com.staricka.adventofcode2023.days import com.staricka.adventofcode2023.days.CrucibleQueueKey.Companion.toQueueKey import com.staricka.adventofcode2023.framework.Day import com.staricka.adventofcode2023.util.Direction import com.staricka.adventofcode2023.util.Grid import com.staricka.adventofcode2023.util.GridCell import com.staricka.adventofcode2023.util.StandardGrid import kotlin.math.min data class CrucibleState(val heatLoss: Int, val direction: Direction, val directionStep: Int, val x: Int, val y: Int) class CrucibleGridCell(val heatLoss: Int): GridCell { override val symbol = heatLoss.toString()[0] private val visited = HashMap<CrucibleQueueKey, Int>() private var minHeat: Int? = null fun visit(crucibleState: CrucibleState, minSteps: Int): Boolean { val crucibleHeatLoss = crucibleState.heatLoss val lowestHeatExisting = visited[crucibleState.toQueueKey()] if (lowestHeatExisting != null && lowestHeatExisting <= crucibleHeatLoss) { return false } visited[crucibleState.toQueueKey()] = crucibleHeatLoss if (minSteps <= crucibleState.directionStep) { minHeat = min(minHeat ?: Int.MAX_VALUE, crucibleHeatLoss) } return true } fun minVisitedHeat() = minHeat } fun CrucibleState.nextSteps(grid: Grid<CrucibleGridCell>, minSteps: Int = 0, maxSteps: Int = 3): List<CrucibleState> { if (x == grid.maxX && y == grid.maxY) { return emptyList() } val minEndHeat = grid[grid.maxX, grid.maxY]!!.minVisitedHeat() if (minEndHeat != null && minEndHeat <= heatLoss) { return emptyList() } return when (direction) { Direction.LEFT -> listOf(Pair(grid.left(x, y), Direction.LEFT), Pair(grid.up(x, y), Direction.UP), Pair(grid.down(x, y), Direction.DOWN)) Direction.UP -> listOf(Pair(grid.up(x, y), Direction.UP), Pair(grid.left(x, y), Direction.LEFT), Pair(grid.right(x, y), Direction.RIGHT)) Direction.RIGHT -> listOf(Pair(grid.right(x, y), Direction.RIGHT), Pair(grid.up(x, y), Direction.UP), Pair(grid.down(x, y), Direction.DOWN)) Direction.DOWN -> listOf(Pair(grid.down(x, y), Direction.DOWN), Pair(grid.left(x, y), Direction.LEFT), Pair(grid.right(x, y), Direction.RIGHT)) }.asSequence().filter { (dest, _) -> dest.third != null }.filter { (_, newDirection) -> directionStep >= minSteps || newDirection == direction }.map { (dest, newDirection) -> CrucibleState(heatLoss + grid[dest.first,dest.second]!!.heatLoss, newDirection, if (newDirection == direction) directionStep + 1 else 1, dest.first, dest.second) }.filter { it.directionStep <= maxSteps }.filter { grid[it.x, it.y]!!.visit(it, minSteps) }.toList() } data class CrucibleQueueKey(val direction: Direction, val directionStep: Int, val x: Int, val y: Int) { companion object { fun CrucibleState.toQueueKey() = CrucibleQueueKey(direction, directionStep, x, y) } } class CrucibleQueue { private val delegate = LinkedHashMap<CrucibleQueueKey, CrucibleState>() fun add(crucibleState: CrucibleState) { val key = crucibleState.toQueueKey() if(delegate.contains(key) && delegate[key]!!.heatLoss <= crucibleState.heatLoss) { return } delegate[key] = crucibleState } fun pop(): CrucibleState { val next = delegate.entries.first() delegate.remove(next.key) return next.value } fun isNotEmpty() = delegate.isNotEmpty() } fun Grid<CrucibleGridCell>.walk(minSteps: Int = 0, maxSteps: Int = 3): Int { val queue = CrucibleQueue() queue.add(CrucibleState(0, Direction.DOWN, 0, 0, 0)) queue.add(CrucibleState(0, Direction.RIGHT, 0, 0, 0)) while (queue.isNotEmpty()) { queue.pop().nextSteps(this, minSteps, maxSteps).forEach { queue.add(it) } } return this[maxX, maxY]!!.minVisitedHeat()!! } class Day17: Day { override fun part1(input: String): Int { return StandardGrid.build(input){CrucibleGridCell(it - '0')}.walk() } override fun part2(input: String): Int { return StandardGrid.build(input){CrucibleGridCell(it - '0')}.walk(minSteps = 4, maxSteps = 10) } }
0
Kotlin
0
0
8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa
4,253
adventOfCode2023
MIT License
advent-of-code-2018/src/test/java/aoc/Advent23.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.Assertions.assertThat import org.junit.Test import kotlin.math.absoluteValue class Advent23 { data class Point(val x: Int, val y: Int, val z: Int) { operator fun minus(other: Point): Point { return copy(x = x - other.x, y = y - other.y, z = z - other.z) } val distanceToNull = x.absoluteValue + y.absoluteValue + z.absoluteValue fun distanceTo(other: Point) = (x - other.x).absoluteValue + (y - other.y).absoluteValue + (z - other.z).absoluteValue } data class NanoBot(val point: Point, val range: Int) private fun parseBots(input: String): List<NanoBot> { return input.lines() .map { it.split('<', ',', '>', '=') } .map { line -> NanoBot(Point(line[2].toInt(), line[3].toInt(), line[4].toInt()), line[7].toInt()) } } @Test fun `Point#distanceTo measures a Manhattan distance to the given point`() { assertThat(Point(10, 10, 10).distanceTo(Point(10, 10, 10))).isEqualTo(0) assertThat(Point(10, 10, 10).distanceTo(Point(10, -10, 10))).isEqualTo(20) assertThat(Point(-10, -10, -10).distanceTo(Point(-11, -11, -9))).isEqualTo(3) } @Test fun `Star 1 test input result is 7`() { val result = countBotsInRangeOfTheStrongestBot(testInput) assertThat(result).isEqualTo(7) } @Test fun `Star 1 result is 609`() { val result = countBotsInRangeOfTheStrongestBot(input) assertThat(result).isEqualTo(609) } /** * For Star 1 */ private fun countBotsInRangeOfTheStrongestBot(input: String): Int { val bots = parseBots(input) val strongest: NanoBot = bots.maxBy { it.range }!! val normalized = bots.map { bot -> bot.copy(point = bot.point - strongest.point) } return normalized .filter { bot -> bot.point.distanceToNull <= strongest.range } .count() } private fun Point.botsInRange(bots: List<NanoBot>): Int { return bots .count { bot -> val distanceTo = bot.point.distanceTo(this) distanceTo <= bot.range } } @Test fun `Star 2 test`() { val bots = parseBots(testInput2) val inRange = Point(12, 12, 12).botsInRange(bots) assertThat(inRange).isEqualTo(5) } /** * 26 neighborrs and the point itself. Seems to be more efficient than [neighbors2] */ fun Point.neighbors(distance: Int): List<Point> { val xs = listOf(x - distance, x, x + distance) val ys = listOf(y - distance, y, y + distance) val zs = listOf(z - distance, z, z + distance) return xs.flatMap { x -> ys.flatMap { y -> zs.map { z -> Point(x, y, z) } } } } /** * Works just as well, but sims a bit slower than [neighbors] */ fun Point.neighbors2(distance: Int): List<Point> { return listOf( Point(x + distance, y, z), Point(x - distance, y, z), Point(x, y + distance, z), Point(x, y - distance, z), Point(x, y, z + distance), Point(x, y, z - distance), this ) } data class Search(val position: Point, val rad: Int) @Test fun `Star 2`() { val bots = parseBots(input) fun Point.botsInRange(): Int { return this.botsInRange(bots) } val comparator = compareBy<Point> { it.botsInRange() }.thenBy { -it.distanceToNull } //val seed = Search(Point(0, 0, 0), 1000000) // we will be near some bot, let't just take the most connected one // x=33486149, y=47665314, z=49219071 val seed = Search(bots.maxBy { it.point.botsInRange(bots) }!!.point, 1000000) // lol, this also is a correct result, but it finds less bots :D // x=35986124, y=49565313, z=44819097 // val seed = Search(bots.maxBy { it.point.botsInRange(bots) }!!.point, 100000) val sequence = generateSequence(seed) { prevSearch -> val nextPosition: Point = prevSearch.position .neighbors(prevSearch.rad) .maxWith(comparator)!! when { // we are stuck, reduce the gradient distance and try again nextPosition.botsInRange() == prevSearch.position.botsInRange() && nextPosition.distanceToNull == prevSearch.position.distanceToNull -> { prevSearch.copy(rad = Math.max(prevSearch.rad / 2, 1)) } // we can go in this direction else -> prevSearch.copy(position = nextPosition) } } val result = sequence .onEach { println("$it: in range: ${it.position.botsInRange()}, distanceToNull: ${it.position.distanceToNull}") } .windowed(2) .takeWhile { (prev, next) -> prev != next } .map { it.last() } .last() .position .distanceToNull assertThat(result).isEqualTo(130370534) } val testInput = """ pos=<0,0,0>, r=4 pos=<1,0,0>, r=1 pos=<4,0,0>, r=3 pos=<0,2,0>, r=1 pos=<0,5,0>, r=3 pos=<0,0,3>, r=1 pos=<1,1,1>, r=1 pos=<1,1,2>, r=1 pos=<1,3,1>, r=1 """.trimIndent() val testInput2 = """ pos=<10,12,12>, r=2 pos=<12,14,12>, r=2 pos=<16,12,12>, r=4 pos=<14,14,14>, r=6 pos=<50,50,50>, r=200 pos=<10,10,10>, r=5 """.trimIndent() val input = """ pos=<76659180,55463797,20890147>, r=80344142 pos=<-2084092,73605216,31684616>, r=79399057 pos=<86586460,61479794,43016484>, r=74160571 pos=<68206254,70100628,34130819>, r=73287183 pos=<53122274,61050769,46492042>, r=90033180 pos=<36297356,85099054,37937271>, r=52570139 pos=<30238533,70777092,46130193>, r=56599095 pos=<3738834,63492215,61035427>, r=56701969 pos=<135550995,127900747,8337871>, r=52178968 pos=<53251499,72992675,14261101>, r=81094095 pos=<210356533,50342748,27786515>, r=74614378 pos=<110857676,49213932,43292716>, r=85889782 pos=<40090364,79904452,-1333054>, r=90438706 pos=<20176869,107772682,61669836>, r=85178747 pos=<12059060,52583513,40527255>, r=65372520 pos=<90583154,54962940,36882927>, r=77774300 pos=<38333281,58595422,51498027>, r=53544840 pos=<103305407,59583377,35902187>, r=96097397 pos=<36444415,77276541,16484109>, r=66347729 pos=<-3456416,68556221,11850897>, r=95555945 pos=<76884405,34324596,28816657>, r=77830387 pos=<65834232,74004529,33464146>, r=75485531 pos=<43752787,27986936,24674664>, r=55178417 pos=<62605893,146012567,145236167>, r=77460342 pos=<21494248,67621934,15535478>, r=65987002 pos=<101153301,55519625,65991520>, r=92293934 pos=<75318782,19163896,34903483>, r=85338666 pos=<112298191,40603076,60572624>, r=96873690 pos=<42268644,69366303,20763136>, r=59982761 pos=<37478347,77703998,15924828>, r=68368432 pos=<91328501,45489542,46789701>, r=63136485 pos=<66143086,81452047,27163357>, r=89542572 pos=<81086096,53848006,52701441>, r=57265021 pos=<45305011,70681429,691853>, r=84405447 pos=<47986375,15102493,7569609>, r=89401993 pos=<57329109,57158032,81668>, r=83516267 pos=<35530582,84367399,26424603>, r=62584532 pos=<40286243,53965408,44918978>, r=84917892 pos=<37005879,81753266,29320912>, r=58549047 pos=<39164327,71276768,9671320>, r=69880567 pos=<42409287,-11006689,54194358>, r=72216293 pos=<67832422,43503537,76095484>, r=65030681 pos=<11717835,76314668,55554926>, r=56064615 pos=<30686684,52212644,31080894>, r=84446115 pos=<44748158,48847300,-20712253>, r=83418503 pos=<110131671,49006028,46035045>, r=82213600 pos=<108275167,50563715,50899328>, r=79367684 pos=<55946744,45855334,7686899>, r=66491733 pos=<45042576,95852506,40932043>, r=69073863 pos=<59562368,76687589,57830382>, r=63710107 pos=<65328112,-4861132,41449401>, r=92827070 pos=<88193694,55373976,31175320>, r=81503168 pos=<92861325,49230857,42905831>, r=68297206 pos=<89447620,29689135,58957740>, r=83322249 pos=<21287675,82220328,32334716>, r=63992131 pos=<44145097,10063968,55064543>, r=53751754 pos=<-4563347,62012257,44985316>, r=56984410 pos=<56075723,200075610,24249521>, r=53265918 pos=<-21544945,56993350,21591433>, r=92340962 pos=<76305419,68607543,38401326>, r=75622435 pos=<48252631,29269301,31805625>, r=51264967 pos=<35288999,98593772,18860975>, r=84132644 pos=<43550324,-9071309,40823592>, r=75885267 pos=<11371772,76604458,45880141>, r=54746741 pos=<53876992,-1016478,28949713>, r=90030989 pos=<54714775,63554150,4832292>, r=82547423 pos=<61983986,32753848,38813255>, r=54504154 pos=<61450298,-3998856,56943164>, r=86998260 pos=<58406387,54200948,29534904>, r=52183261 pos=<86174086,26986952,36518029>, r=86756327 pos=<72559523,4183979,39723752>, r=92739264 pos=<42745443,66627472,57245586>, r=86618509 pos=<69075699,57260270,38894547>, r=56552211 pos=<97656047,36332283,38910992>, r=86500318 pos=<91215543,49146195,51325532>, r=61316887 pos=<80461398,72634354,31610763>, r=90595955 pos=<-32390642,96794130,-39631847>, r=79593175 pos=<42203790,87365383,68964475>, r=68163356 pos=<54309677,11731249,45792599>, r=60873100 pos=<21006256,56363651,34607886>, r=59319884 pos=<57872394,85531510,32289775>, r=80224918 pos=<56388066,22238956,22593591>, r=75642741 pos=<47159655,57889571,80825196>, r=55504282 pos=<70725623,81924310,29749968>, r=92010785 pos=<92007362,50306666,53271552>, r=65215150 pos=<74365563,57070949,40561166>, r=59986439 pos=<70479442,90047251,54628805>, r=84785207 pos=<39368703,80065068,28539252>, r=60005311 pos=<54605193,68098228,63165269>, r=55498157 pos=<49837569,45682523,48225062>, r=80662355 pos=<62353878,102376252,34937955>, r=98903051 pos=<34939780,52273032,4533139>, r=51790770 pos=<49525621,48690478,40381323>, r=53728728 pos=<17180587,108415084,66907340>, r=94055086 pos=<65233666,73313269,55543441>, r=63719842 pos=<-9319682,60918409,8390492>, r=97241735 pos=<29034582,44269925,58803241>, r=71847572 pos=<42119653,53982007,14781451>, r=50431401 pos=<57391543,113340563,46630758>, r=93212155 pos=<78465090,50957877,48458029>, r=50075769 pos=<106343982,52497130,36127072>, r=91824902 pos=<-21893189,53993780,27351145>, r=83929972 pos=<-25256701,29978172,32954873>, r=92694191 pos=<42683498,45865070,38352794>, r=53722737 pos=<70355503,68160123,47153238>, r=60473271 pos=<38037286,96820157,35410051>, r=68558193 pos=<53930010,52562466,-3155730>, r=78759027 pos=<65022031,74607755,36270577>, r=72469999 pos=<36450514,107507996,47860772>, r=65208526 pos=<98546682,60935498,31129676>, r=97463453 pos=<47541049,54622434,5111213>, r=66163408 pos=<-25732052,52049004,44600875>, r=68574362 pos=<15583127,64809694,9026522>, r=75594163 pos=<41483217,84651570,65201571>, r=60965904 pos=<69481518,14485972,40232238>, r=78850832 pos=<53793823,48738479,8251383>, r=63391714 pos=<107871820,57716350,44655684>, r=90043314 pos=<91042436,26928769,48567033>, r=79633856 pos=<53114223,-5031000,56785689>, r=79536947 pos=<103133613,59068345,45533790>, r=85779040 pos=<50484484,95145664,58108065>, r=73367717 pos=<67997212,29782707,39986266>, r=62315549 pos=<29778057,97197763,34270313>, r=68543675 pos=<55802307,80246082,19694962>, r=85464223 pos=<-28959529,19759588,47511619>, r=92059242 pos=<95901167,50601143,27599541>, r=88013573 pos=<80196571,44014061,12152119>, r=88117696 pos=<17231284,52489764,15709961>, r=54942714 pos=<41102807,17534811,27558190>, r=60097279 pos=<38425473,86861768,31868202>, r=62529904 pos=<-17352085,53021603,46728727>, r=59039129 pos=<-16435681,49258322,44951372>, r=56136802 pos=<58950831,77549288,6549218>, r=99061695 pos=<27581261,5951296,59129678>, r=56486338 pos=<-28182808,42924260,25066507>, r=90562625 pos=<94328742,40706754,42186217>, r=75523178 pos=<80023516,49324632,38218874>, r=60240075 pos=<45483388,66030793,-7897910>, r=88523119 pos=<44271186,78999072,22009840>, r=70371232 pos=<56538092,73729666,65233442>, r=65130735 pos=<61639360,10231006,48150755>, r=67344906 pos=<2406381,34127548,42346458>, r=51490414 pos=<75703852,66787671,78278920>, r=90399984 pos=<79120937,49140871,42790454>, r=54582306 pos=<59386588,72962568,42336085>, r=59123893 pos=<50190186,60968066,89454620>, r=70242488 pos=<71604908,52090304,77660092>, r=70984810 pos=<49875189,43754367,33719900>, r=70265861 pos=<55806852,-11990623,37284560>, r=94600469 pos=<10852335,61768556,35658394>, r=50651934 pos=<80306522,50156753,8803425>, r=90770836 pos=<76963944,63908876,39133554>, r=70850352 pos=<-840550,53893467,32543768>, r=57584570 pos=<102879763,57821020,47722524>, r=82089091 pos=<79089640,9557112,38309036>, r=95310790 pos=<58601182,60317348,5062710>, r=82966612 pos=<57005137,20288683,26775080>, r=74028599 pos=<88712863,61688954,68211219>, r=88242563 pos=<75882815,53891459,40491427>, r=58393734 pos=<42169838,111234430,47761436>, r=74753666 pos=<-23900902,81225283,48668344>, r=91851951 pos=<-11105994,61252732,33638587>, r=74114244 pos=<64532110,15887417,41634392>, r=71097604 pos=<52563007,56016263,19250893>, r=58439186 pos=<35702464,29307962,2941299>, r=67540557 pos=<60455706,14623586,60287090>, r=70725187 pos=<86265290,63843879,47027150>, r=72192900 pos=<78188012,77585432,26580140>, r=98304104 pos=<-36248137,49846808,44429502>, r=77059955 pos=<17742932,52636106,-7328678>, r=77616067 pos=<45061872,32219640,46302896>, r=60150781 pos=<73446136,85823692,37301412>, r=91079311 pos=<20268956,81523255,31784877>, r=64863653 pos=<66711671,62792084,54474803>, r=53608038 pos=<86657405,31359557,48547829>, r=70837382 pos=<53280114,78083598,59808651>, r=60801838 pos=<2516582,80427339,36281478>, r=77023469 pos=<15867066,74387470,12838152>, r=81076362 pos=<-37313442,40984797,48477879>, r=78221593 pos=<63539840,57428706,39390353>, r=50689092 pos=<14151000,34912706,45102673>, r=68064235 pos=<87917918,52941141,71829653>, r=82318235 pos=<-358005,60325724,7026657>, r=89051283 pos=<75259606,84306490,31692122>, r=96984788 pos=<16549611,83055817,3677615>, r=98222716 pos=<44435811,61045062,13377629>, r=61214074 pos=<41095198,81271916,21704423>, r=69773783 pos=<68444732,65302452,28068734>, r=74789530 pos=<36354710,13865021,2335418>, r=84241549 pos=<-35901175,63454538,42250504>, r=92499309 pos=<60068522,67463418,38857721>, r=57785052 pos=<74261549,44020994,100274633>, r=95121101 pos=<104247861,41596638,47919773>, r=78818694 pos=<59161488,35371150,15618648>, r=72259499 pos=<-13158547,35912926,8469349>, r=99146807 pos=<90606141,49395606,41803473>, r=67309156 pos=<46142629,65454316,-8533674>, r=89241545 pos=<37860095,21511518,25555326>, r=54880592 pos=<-49318515,55595164,48057487>, r=92250516 pos=<51295463,9236771,31923882>, r=74222202 pos=<42595196,99612152,57716969>, r=69553839 pos=<62839591,58078750,39836273>, r=50192859 pos=<220507970,62351975,37279625>, r=72254465 pos=<127387178,50071692,47310147>, r=99259528 pos=<20974704,78630024,28337624>, r=64712190 pos=<77681440,61625216,30212214>, r=78205350 pos=<54220387,70659882,90173328>, r=84683092 pos=<78798214,72372906,46766363>, r=73515545 pos=<91937978,37361296,18802303>, r=99861641 pos=<44781717,123812829,40098187>, r=97607151 pos=<88324046,67484716,52063035>, r=77501381 pos=<3726592,50553833,9342099>, r=72879371 pos=<65522002,37607400,82789990>, r=75310544 pos=<101104743,50473546,21621743>, r=99067686 pos=<37484712,-5017340,11583634>, r=95005754 pos=<85292432,69111648,46319339>, r=77195554 pos=<-15271154,57758716,41698714>, r=66725267 pos=<89234907,53229585,55452000>, r=67546017 pos=<41480431,62682284,-12279881>, r=85553394 pos=<48555925,53984136,14102000>, r=57549121 pos=<92777521,46161302,22971296>, r=87732254 pos=<115176759,42939170,48371943>, r=87952958 pos=<113372946,53719697,40991426>, r=95212110 pos=<41175792,82287802,2450299>, r=90124095 pos=<68257345,59154237,15931050>, r=80591349 pos=<-2032896,59611675,57229730>, r=54787685 pos=<75951059,64500119,36444595>, r=73117398 pos=<38607651,68775576,52746819>, r=81618202 pos=<93282068,-55706088,-8590487>, r=84873166 pos=<97992081,64200751,38274819>, r=93028801 pos=<79113048,32893240,46415888>, r=63891242 pos=<55239978,54206918,-8169081>, r=86726861 pos=<55127465,43958070,12924702>, r=62331941 pos=<74478048,58269807,17592364>, r=84266522 pos=<94453994,50383070,38642174>, r=75306399 pos=<31843203,68102261,81070363>, r=53242260 pos=<59403856,52869083,47915558>, r=99141300 pos=<72624460,50383834,7253145>, r=84866047 pos=<54858280,77577157,87358582>, r=89423531 pos=<198312304,78158173,41935481>, r=65596769 pos=<-8786568,62281351,29570779>, r=76891502 pos=<86771451,71958945,48479295>, r=79361925 pos=<17038574,67761670,-7685784>, r=93802988 pos=<67703324,73146181,34406211>, r=75554089 pos=<85462952,56883449,30513180>, r=80944012 pos=<38465522,36680043,34190722>, r=53668420 pos=<-1799891,76576778,76766337>, r=91055804 pos=<112091932,59458344,43823125>, r=96838242 pos=<8112922,48553836,42157995>, r=67460860 pos=<-8589491,68562498,65665934>, r=78730702 pos=<90163111,63518864,41703341>, r=81089758 pos=<143569659,101340093,-10678689>, r=76082500 pos=<40476822,49946893,6516942>, r=53017561 pos=<49312378,82528124,31810136>, r=69141181 pos=<229689668,51577859,35278007>, r=94146993 pos=<39109417,105948166,47163094>, r=67005278 pos=<5299688,96833540,57776031>, r=85222661 pos=<24067043,4410539,29819392>, r=72073572 pos=<100252222,61181655,36162978>, r=94381702 pos=<38637924,26976137,21318588>, r=54430467 pos=<53927809,52376849,-539094>, r=75955016 pos=<35337142,101756510,40084695>, r=66119752 pos=<79341881,53060148,15900714>, r=85612113 pos=<49702374,92179436,39164132>, r=71828577 pos=<74147450,60511153,13587580>, r=90181848 pos=<-45289459,105422502,-29571485>, r=62363878 pos=<50557969,66314956,30027138>, r=55956719 pos=<40017347,64420890,44650395>, r=56015218 pos=<16230354,56296817,-2509080>, r=77969905 pos=<68921722,59891827,45201971>, r=52722428 pos=<88888545,65106964,74948176>, r=98573422 pos=<-25005775,55668875,45878692>, r=70190245 pos=<22611490,87662815,94644712>, r=95609070 pos=<-37558160,33056940,47625853>, r=87246043 pos=<58208666,74808284,57631390>, r=60277947 pos=<63593929,87359539,41831905>, r=78232374 pos=<68803559,43693715,13982675>, r=75214987 pos=<71546788,51621065,29566078>, r=62712604 pos=<79945579,52356227,45842615>, r=55570085 pos=<63880826,62436724,38828886>, r=56599511 pos=<85396946,32027351,52495056>, r=70470574 pos=<-2763677,74122674,26524636>, r=85755817 pos=<80617738,39315003,39574385>, r=65815706 pos=<-10631064,78745716,39875535>, r=84895670 pos=<73723253,73415828,37580477>, r=78669426 pos=<71998185,55606411,33061534>, r=63653877 pos=<35907891,85075433,18355252>, r=71738866 pos=<66978166,8651365,36562853>, r=85851531 pos=<39661241,109656978,19007874>, r=99421385 pos=<21553682,33954622,11139225>, r=63723057 pos=<37758163,96075519,22092273>, r=80852258 pos=<24660950,84924512,-85533>, r=95743321 pos=<91228110,59847340,46080802>, r=74105535 pos=<180230940,87030129,63114795>, r=86087663 pos=<-17019974,32901625,52039725>, r=67047440 pos=<1906387,24702148,37604530>, r=66157678 pos=<114507170,52201178,48696560>, r=87122578 pos=<51713545,60401091,75730269>, r=57474378 pos=<99768190,60182616,35630988>, r=93430642 pos=<71374218,17729425,59933745>, r=78184446 pos=<59512019,35202459,35847105>, r=52549758 pos=<21345195,65729975,-9233105>, r=89012561 pos=<-19870430,54053685,21189348>, r=88129150 pos=<48685066,104219966,58487100>, r=81021614 pos=<16893124,96666803,36277934>, r=78889948 pos=<93502466,56464006,47248901>, r=71828502 pos=<44514629,63826054,7879606>, r=69571887 pos=<78334534,36206546,28112634>, r=78102651 pos=<-59403511,51729870,48459331>, r=98068341 pos=<-6461241,49413970,27210638>, r=64058793 pos=<85332906,52148849,43785015>, r=62807671 pos=<81611124,8742785,45777908>, r=91177689 pos=<-1597896,76465459,13983215>, r=99474290 pos=<44367985,77763206,36203895>, r=55038090 pos=<42552879,73973932,4182586>, r=81455049 pos=<60993485,-116341471,40308009>, r=76771665 pos=<63464107,55361286,10866417>, r=77069765 pos=<69092435,67938253,45902844>, r=60238632 pos=<60677488,51101129,44960310>, r=80549886 pos=<61875098,59573547,35853663>, r=54705973 pos=<54842949,14823950,66291346>, r=70916348 pos=<36308878,100890766,58861678>, r=65691295 pos=<65064783,75103712,24965010>, r=84314312 pos=<47383095,96293222,42280840>, r=70506316 pos=<-8542167,55999237,27698161>, r=72237345 pos=<-34322347,49470287,51965562>, r=71671418 pos=<2930589,80100436,31937937>, r=80626066 pos=<173993689,75998196,6864438>, r=82454107 pos=<69290076,71890283,48153688>, r=62137461 pos=<-17575677,45070608,5076397>, r=97799270 pos=<41121980,50394324,29993159>, r=76826483 pos=<93086669,78887377,46407878>, r=94677082 pos=<66005637,53950699,60521196>, r=50107115 pos=<-17232743,36646730,20219089>, r=90737967 pos=<85855173,50693669,47685703>, r=57973927 pos=<91003203,52382453,42510681>, r=69985990 pos=<-27954369,56942324,48390805>, r=71900089 pos=<84953332,33560052,61900030>, r=77899330 pos=<75949144,81119145,37460772>, r=88718344 pos=<48166834,49306459,42121703>, r=99746556 pos=<62091916,66523556,13005160>, r=84721215 pos=<77793245,63433316,48236786>, r=62100838 pos=<95872085,56536821,36165298>, r=85354420 pos=<105088018,66369241,46378100>, r=94190085 pos=<103208232,55142513,53335176>, r=81315478 pos=<-16776243,48960934,44296549>, r=56834778 pos=<71716189,70167256,56737120>, r=68250530 pos=<83683800,46330317,92170494>, r=94130311 pos=<52989610,76840394,19471613>, r=79469189 pos=<63489595,62395357,30839612>, r=64156397 pos=<106399436,125822410,-17915007>, r=93317974 pos=<60423341,53632285,31731891>, r=51434566 pos=<128728275,44969975,48504967>, r=99340820 pos=<62578734,49353854,25663764>, r=55379907 pos=<67397212,52915517,31022715>, r=58400906 pos=<80618520,93271743,45061828>, r=97939266 pos=<35077892,20557407,19731482>, r=58877009 pos=<62244987,73728715,29336733>, r=75747838 pos=<51079490,53105364,-11719103>, r=85014755 pos=<102120814,48673090,44043658>, r=75861060 pos=<66660325,70087329,39416962>, r=66441597 pos=<81699381,55780275,29836221>, r=76754227 pos=<39877590,110314783,34078578>, r=85224978 pos=<84746696,76841724,52272014>, r=83490074 pos=<42142115,50289677,46231646>, r=73017479 pos=<45728418,39911946,57918522>, r=75465930 pos=<72670856,75593984,51552390>, r=69446718 pos=<58747154,46182255,-14543892>, r=91196015 pos=<65287501,42033513,-595368>, r=87936583 pos=<84428109,62386266,46703048>, r=69222262 pos=<56007472,75302113,54299946>, r=55239190 pos=<114696217,48743876,39499862>, r=93051019 pos=<99803812,50824126,32821803>, r=86917071 pos=<35400901,63657664,5154275>, r=63015080 pos=<44218706,74898438,12999492>, r=75228602 pos=<51671680,65419139,32104452>, r=54097167 pos=<69169526,56379065,79498748>, r=74677008 pos=<68373552,76515148,35548245>, r=78451266 pos=<49369845,23797117,38612255>, r=51047760 pos=<90926116,57704687,40544102>, r=77197610 pos=<67665367,71275918,58245484>, r=66816246 pos=<71528754,51792035,74031636>, r=66981896 pos=<28396405,58679660,-29643390>, r=95321060 pos=<17846043,80009009,-857531>, r=98414624 pos=<50734000,79988655,29510632>, r=70322916 pos=<49015604,38738111,10283811>, r=64080958 pos=<74874840,80160850,46751414>, r=77395357 pos=<61521470,108069692,57064442>, r=96285248 pos=<95218339,60085071,55415826>, r=80348843 pos=<11450387,68837519,23994626>, r=68786634 pos=<-23328305,41302614,20176923>, r=92219392 pos=<96773303,51561548,65624968>, r=83589732 pos=<27783858,76489323,31706114>, r=52393955 pos=<19191737,53643299,-20324466>, r=90170214 pos=<27918451,107207454,22986493>, r=91696626 pos=<46881434,52536341,61462104>, r=59395078 pos=<-491528,64238329,22861609>, r=77262908 pos=<93982476,25646684,54650529>, r=87592423 pos=<-32153270,49188578,47707226>, r=69028739 pos=<107659617,51584122,36488663>, r=91866095 pos=<-2944730,90882708,35525286>, r=93696509 pos=<90808568,51695467,84952939>, r=97086527 pos=<58074726,76909968,72496053>, r=77110265 pos=<48405477,107043320,62504220>, r=87582561 pos=<-28432326,49086163,48417825>, r=64495168 pos=<-32451432,51910254,42322434>, r=77433371 pos=<89669160,74795341,63514281>, r=97608276 pos=<171688348,71550560,-11128933>, r=76227310 pos=<43405551,110214855,34319595>, r=88411660 pos=<94196088,66079660,40641579>, r=88745060 pos=<-18753033,81873266,45327180>, r=90693440 pos=<78570650,52614973,41510635>, r=58785872 pos=<105204003,51948531,42649607>, r=83613883 pos=<76089719,61347449,52324071>, r=59390974 pos=<104035173,52763075,46369775>, r=79539301 pos=<46550627,60798352,20516230>, r=55943615 pos=<72606292,50940222,10392092>, r=82265285 pos=<38151769,51422523,-9387006>, r=68072652 pos=<46379127,31788228,24879832>, r=53798296 pos=<64957097,98238992,41536141>, r=90771081 pos=<98523502,48666403,46647267>, r=69653543 pos=<85995970,52103934,18702943>, r=88507852 pos=<-18575859,46375073,83018123>, r=86108186 pos=<80917162,60895648,46182966>, r=64740914 pos=<75587883,36412623,55558210>, r=59339398 pos=<-13707419,73717866,70657967>, r=93996405 pos=<72249849,59728029,37329932>, r=63758769 pos=<76820995,51645106,24052895>, r=73524205 pos=<43531625,50554789,65716756>, r=62571441 pos=<84110818,52825617,32319238>, r=73728099 pos=<80905548,27296288,38325478>, r=79371047 pos=<10496288,83414957,23159422>, r=85153411 pos=<55854029,24316303,42582360>, r=53042588 pos=<65301911,107391508,43249682>, r=98554685 pos=<47569841,102727692,28182793>, r=91225604 pos=<91656397,55649155,23556411>, r=92859932 pos=<56995415,74402430,47674732>, r=52833902 pos=<111059255,53764186,40383273>, r=93551118 pos=<95130400,51077926,46176759>, r=69142381 pos=<76662171,71627412,26786574>, r=90613969 pos=<81874816,59969108,70680398>, r=82153992 pos=<34338576,97267474,3193790>, r=97523230 pos=<42675242,33209321,414195>, r=73139050 pos=<51357265,24592339,21049552>, r=69803204 pos=<43599330,90336796,45266020>, r=57780895 pos=<34694099,10579738,73160222>, r=61880729 pos=<90845833,44092111,47594036>, r=63246951 pos=<-6914407,60670006,46273609>, r=56704908 pos=<77316498,54051155,47341678>, r=53136775 pos=<71300994,52682013,63999999>, r=57613003 pos=<20005637,104876294,30146076>, r=90118691 pos=<46669446,61440152,24669433>, r=52551219 pos=<64537918,87112026,32331439>, r=88429623 pos=<81435191,50473738,42715928>, r=58303795 pos=<36722723,80070991,24955465>, r=60949086 pos=<57176592,12395849,77489543>, r=86876223 pos=<-36401058,58939813,43409921>, r=87325069 pos=<86613286,52798269,36947241>, r=71575105 pos=<35708954,62121677,1647094>, r=65294328 pos=<88856357,75808923,38915079>, r=94861125 pos=<55031620,43858978,3599714>, r=71660177 pos=<96616266,26598094,51769024>, r=86393096 pos=<-10969831,37647303,41878117>, r=61815059 pos=<-31382932,58504054,45017912>, r=80263189 pos=<88254026,71973102,31818919>, r=97519015 pos=<64323715,3865379,26482002>, r=98063558 pos=<48971656,79335831,41788252>, r=55630053 pos=<39589746,5851420,12597623>, r=85227965 pos=<76023652,51853656,19845362>, r=77142743 pos=<101899138,50875631,34371916>, r=87514121 pos=<63963198,73502499,39538373>, r=67038133 pos=<56466428,61408152,22850501>, r=64134964 pos=<87854988,73463238,34403364>, r=96026450 pos=<47439733,17589380,13764512>, r=80173187 pos=<61239939,54645049,47585951>, r=57674867 pos=<70544966,24953391,44278480>, r=65400553 pos=<40273570,55565872,10705787>, r=54244443 pos=<90777370,63037420,56834627>, r=80279655 pos=<83497062,73144860,42190316>, r=83562395 pos=<83066711,53098573,68811619>, r=74606383 pos=<45534560,52772164,12491269>, r=54926345 pos=<96496310,73839220,44404746>, r=95041588 pos=<114782347,49587511,38775710>, r=94705062 pos=<35360710,74686797,26221360>, r=52936938 pos=<15946293,63316595,82713596>, r=65996777 pos=<10199584,58817028,70538580>, r=55068986 pos=<55686420,66677772,29967805>, r=61507195 pos=<38736573,88223717,38914123>, r=57157126 pos=<70147452,57937940,61002103>, r=58716976 pos=<38147591,96391897,78639854>, r=82809443 pos=<66806178,58496832,32177199>, r=62236599 pos=<42453600,122185967,41022831>, r=92727530 pos=<96693760,26959884,40271061>, r=93550156 pos=<82644916,50249029,46247633>, r=55757373 pos=<55823840,49391686,43787004>, r=61690759 pos=<64298453,77335057,22736041>, r=88008271 pos=<-12423191,53641298,12833525>, r=88625358 pos=<76569743,62456531,69186290>, r=77842033 pos=<51075924,9741190,10665657>, r=94756320 pos=<84100679,31782749,35140643>, r=81264546 pos=<102589001,48523211,47692498>, r=72530528 pos=<55773965,90595566,17086355>, r=98394093 pos=<41305633,31771238,8954903>, r=64666717 pos=<90599185,31820276,55895426>, r=79280874 pos=<70511088,67187959,43163563>, r=63646311 pos=<77433096,27947900,32217619>, r=81354803 pos=<45905011,71515695,24015996>, r=62515572 pos=<49283081,95183034,33784699>, r=79792871 pos=<59552628,54184041,29864476>, r=52983102 pos=<96472302,60709656,35813223>, r=90479668 pos=<114967424,52679084,47023260>, r=89734207 pos=<40413063,54568293,65958359>, r=97318819 pos=<104757736,43951477,64140128>, r=89552305 pos=<73661041,55317550,65758004>, r=64366080 pos=<75129560,90569902,35866478>, r=98943779 pos=<22742647,-19121910,42051717>, r=84698215 pos=<56213410,56163217,91318319>, r=73324447 pos=<-32417471,69412850,58964203>, r=96707304 pos=<44467710,-16399828,44445595>, r=80509359 pos=<79608203,63374753,45887964>, r=66205782 pos=<59366904,55195343,22173824>, r=61499243 pos=<46298561,-24449036,39692746>, r=95142226 pos=<59370922,48696612,3341053>, r=73837309 pos=<14836800,79123661,27793187>, r=71887779 pos=<-18885560,48698521,40948350>, r=62029920 pos=<105527030,49026208,45535873>, r=78128153 pos=<58185441,53279033,13275472>, r=67300170 pos=<79181291,18799025,63589377>, r=88577604 pos=<117933167,56662359,44231296>, r=99475530 pos=<52061014,104464373,67921289>, r=94076176 pos=<23650061,94872565,15035233>, r=91581399 pos=<63894482,50405536,10773593>, r=72637224 pos=<115362925,50197781,45854567>, r=88817280 pos=<59020866,51381584,51844169>, r=86178082 pos=<72552729,43323467,42843755>, r=50472860 pos=<82741354,55268414,64120719>, r=71759997 pos=<101636449,59682283,37567609>, r=92861920 pos=<44350711,64047646,17758831>, r=59750595 pos=<85402584,49335061,54971587>, r=59338747 pos=<81094723,41107826,27037037>, r=77037110 pos=<530589,10539975,24293299>, r=95006689 pos=<60168297,55970332,48443529>, r=91976758 pos=<84363867,67732398,66902909>, r=88628723 pos=<94964932,28779960,38495672>, r=91776526 pos=<70402991,25011361,34056500>, r=75422571 pos=<-15651786,54327089,58107010>, r=63998747 pos=<972284,8403229,39541172>, r=81453856 pos=<48927115,58953585,114942478>, r=92452797 pos=<41895996,53542469,-24157895>, r=88707210 pos=<232141916,49769257,51216213>, r=90681159 pos=<-26379000,49278783,37589257>, r=73462632 pos=<35884097,34550203,-18713294>, r=84134415 pos=<67980893,37658444,103989409>, r=98918097 pos=<35263215,81493771,5148491>, r=80719417 pos=<56735096,60950160,22725269>, r=64070790 pos=<-22566916,48814154,44059110>, r=62716060 pos=<79399434,24076902,34150259>, r=85259512 pos=<78782699,52857749,86472534>, r=87742772 pos=<18779679,64586850,46970913>, r=85277299 pos=<59226349,50851363,48004216>, r=57047039 pos=<-46057742,49845552,48687916>, r=82609498 pos=<73368103,50019025,23659311>, r=68838980 pos=<64353753,56602973,64858546>, r=55444833 pos=<57749044,69318201,55364950>, r=52061744 pos=<56007227,53159091,51447626>, r=68281776 pos=<58081859,29382622,67123442>, r=60429153 pos=<43985585,41874136,40666251>, r=84388380 pos=<56659116,85031290,13895345>, r=96905964 pos=<6319713,77985793,35645488>, r=71414987 pos=<105369132,48767350,74369291>, r=98135241 pos=<34725414,5815811,34613215>, r=58383854 pos=<105426090,53725451,56457072>, r=85238159 pos=<191800777,84088203,28351140>, r=88172658 pos=<76580582,55382301,38591370>, r=62482302 pos=<66669567,54458832,32433837>, r=57805578 pos=<72877740,57356481,35684959>, r=63660082 pos=<61525028,56135135,105345225>, r=92635263 pos=<37395600,39235306,-6731371>, r=68978951 pos=<100697653,99550410,-54486204>, r=71017066 pos=<69307881,-6588952,44654193>, r=95330110 pos=<105161350,49875092,65308222>, r=89974480 pos=<117918381,50900536,45178228>, r=92751664 pos=<-25758688,48899624,30319308>, r=79733337 pos=<78334081,58992446,36681631>, r=69755893 pos=<88796110,54494426,47073495>, r=65327849 pos=<62282097,80778366,23125530>, r=89045736 pos=<86714180,48891975,42205244>, r=62511826 pos=<89907271,58648404,42024193>, r=75642297 pos=<34689118,54468794,-14509073>, r=72777773 pos=<85016349,52847761,42126137>, r=64848804 pos=<77633854,86983264,40794552>, r=92933558 pos=<111526968,58697998,48173990>, r=91161768 pos=<71478111,57387023,31236284>, r=66739641 pos=<76238151,68716916,22592941>, r=91472938 pos=<68781627,51930941,18443854>, r=71379536 pos=<63203847,66879505,22008915>, r=77185252 pos=<61351779,86300698,34248336>, r=82515032 pos=<52324441,62747783,-4054635>, r=88237840 pos=<36984366,96965082,37200045>, r=65860526 pos=<94511034,51819758,38470308>, r=76971475 pos=<-3801508,35243206,28268008>, r=70660833 pos=<86601865,40311181,46172487>, r=64205738 pos=<67475128,41689345,28630289>, r=61242721 pos=<95070234,62224881,47409982>, r=78995931 pos=<52246652,-9240409,-81204088>, r=50966298 pos=<62030792,61044182,-1661881>, r=93847845 pos=<67622042,37792149,35631189>, r=58285938 pos=<99383401,146030304,88409823>, r=73873960 pos=<39557888,73961085,16684926>, r=65944936 pos=<45141391,-12526410,-81240507>, r=81990979 pos=<67579019,64887679,50774960>, r=52871125 pos=<73528665,70544074,80472965>, r=94175170 pos=<100020121,69687463,47019387>, r=91798991 pos=<98015596,51164966,25235359>, r=93056028 pos=<114587170,53355539,41555572>, r=95498187 pos=<53860621,51181758,21436698>, r=52716485 pos=<40622440,81247129,32306990>, r=58673385 pos=<-36990096,57754802,44569062>, r=85569940 pos=<-43301170,56695868,38330578>, r=97060783 pos=<-52041809,53895648,42081584>, r=99249974 pos=<558534,79502902,47576323>, r=66762152 pos=<16114068,58914371,19333985>, r=58860511 pos=<43656929,48779145,52492261>, r=51463905 pos=<94930996,61953950,32639935>, r=93355831 pos=<72966489,50544031,14025631>, r=78596274 pos=<6707523,21862937,51740684>, r=54059461 pos=<43571790,91865716,36172313>, r=68376207 pos=<46781802,25076733,27181566>, r=58610928 pos=<52870590,103048555,44778903>, r=80251482 pos=<35799108,25564399,12519796>, r=61802147 pos=<52330447,64691062,16523430>, r=69608869 pos=<82889576,8166139,44948755>, r=93861958 pos=<66470292,69361492,27877579>, r=77064993 pos=<78241886,51581260,54211288>, r=53663900 pos=<13320511,30706430,16635680>, r=69707994 pos=<88519466,21751510,47310643>, r=83544560 pos=<19365883,79177311,27553530>, r=67652323 pos=<40455189,99954808,38385185>, r=71135655 pos=<53652283,84746053,45419816>, r=62089312 pos=<84634478,54146076,56804686>, r=65215062 pos=<65979195,79534020,41925058>, r=72699220 pos=<14037692,81474172,47358722>, r=55471939 pos=<79633064,72690114,56237262>, r=78189921 pos=<-16785227,54920470,46556280>, r=60543936 pos=<58379260,48996589,6377380>, r=70109398 pos=<98357431,43142986,57654168>, r=77474640 pos=<29596394,104332431,27969603>, r=82160616 pos=<61409331,79714890,26780766>, r=83454268 pos=<67381162,63602529,53676496>, r=54289709 pos=<-32403037,50268331,48168384>, r=69897117 pos=<99373981,57518238,38683281>, r=87319726 pos=<83999221,59762435,19196827>, r=93675960 pos=<36188347,36633439,47585343>, r=86384709 pos=<76652667,40519841,32710042>, r=67510033 pos=<78421532,49736882,58115117>, r=55903001 pos=<83972862,62629211,26247163>, r=89465783 pos=<-21474938,64152829,77683520>, r=99224110 pos=<52708721,56975527,-5466240>, r=84261287 pos=<75090917,49735378,36848605>, r=57088501 pos=<73370042,98731290,41735666>, r=99476522 pos=<53255289,80223909,3803309>, r=98786750 pos=<45762162,33385217,-16400707>, r=92864887 pos=<91415571,54629910,31246724>, r=83909545 pos=<35246135,49379351,-29679665>, r=83415987 pos=<17701348,56066313,38381875>, r=63176443 pos=<93148387,68663168,43453934>, r=87468425 pos=<78715156,67610106,31467972>, r=83968091 pos=<66562978,19702813,86916253>, r=98382352 pos=<63525646,49333998,-15019410>, r=96990502 pos=<-36233907,51458803,47300636>, r=75786361 pos=<48951406,82796575,54664210>, r=56041883 pos=<36493537,53131650,28991435>, r=98486889 pos=<46178608,74831307,18821582>, r=71299122 pos=<47849427,87189824,85086303>, r=89755120 pos=<50355784,80272369,46532113>, r=53207203 pos=<70619701,55612787,39262854>, r=56080627 pos=<83925516,75610188,51150280>, r=80316093 pos=<38677060,71126960,41777781>, r=50073693 pos=<96576758,50755607,39301821>, r=77141339 pos=<-17331405,53921754,23927286>, r=82720268 pos=<43332395,52458915,3866564>, r=61035550 pos=<76122990,28318999,58119928>, r=70530164 pos=<47500964,49641475,98571177>, r=65343091 pos=<22923179,68555521,30750427>, r=50276217 pos=<23091196,-663438,24702281>, r=83240510 pos=<44176702,-2088753,51077057>, r=61948446 pos=<25748443,63443705,84635437>, r=58243573 pos=<13259869,76647362,45407184>, r=53374425 pos=<-12708932,54641046,12827704>, r=89916460 pos=<11597565,56512747,45732470>, r=56082372 pos=<83863787,48938436,26605415>, r=75307637 pos=<111720503,63295571,53641335>, r=98286931 pos=<90255010,65464935,41721677>, r=83109101 pos=<62511344,40688910,9977153>, r=75933031 pos=<46512894,57154577,-14411715>, r=87189979 pos=<44991986,77274865,5422426>, r=85955379 pos=<68581967,87679430,32313488>, r=93059010 pos=<-9895799,37956619,45991926>, r=56318065 pos=<30594150,67561380,-13550826>, r=85912161 pos=<3292439,36387663,28836072>, r=61854374 pos=<34715043,60276526,42449>, r=64059915 pos=<74799549,79960424,58309856>, r=82699463 pos=<62188994,65467044,25298517>, r=71468348 pos=<111302007,50463293,47336720>, r=83539448 pos=<17303774,99506938,66856869>, r=84973019 pos=<43463935,52565826,47471688>, r=73753770 pos=<-15427149,49454018,47723632>, r=52551669 pos=<78854566,50061729,39587252>, r=58440013 pos=<100981781,29749470,53015999>, r=88854639 pos=<31567763,27992097,45961837>, r=99359367 pos=<85059131,31223257,41401432>, r=76521952 pos=<104863345,43834669,35854760>, r=89261139 pos=<67365288,60969099,54499431>, r=52463517 pos=<44325731,86559120,43682084>, r=56313912 pos=<60787433,120857878,-53218737>, r=51539653 pos=<-40542186,53042528,37514324>, r=91464543 pos=<-53238721,56004530,47401774>, r=97236009 pos=<84581463,31878157,51770627>, r=69079848 pos=<58210328,59995535,2943278>, r=84373566 pos=<83159811,71151609,25803605>, r=97618603 pos=<38562186,70339653,1975116>, r=76037511 pos=<79723396,42912077,68559190>, r=69976530 pos=<27698445,114640930,27819911>, r=94516954 pos=<59683812,54444932,73026567>, r=56784785 pos=<76423841,58163371,39853977>, r=63844151 pos=<59940113,97989764,45297181>, r=81743681 pos=<49851262,99298228,34298246>, r=83962133 pos=<97647278,52542749,61788575>, r=81608130 pos=<80381103,49920431,4843763>, r=94569289 pos=<67208666,64912712,40211479>, r=61020771 pos=<5876800,31371392,6242288>, r=86880120 pos=<40514291,56031808,-3094702>, r=68751641 pos=<46051512,75671023,26787648>, r=64045757 pos=<57886730,71741545,2953300>, r=95785867 pos=<58239203,49515152,5177028>, r=71688119 pos=<9231832,73555934,94311276>, r=94548351 pos=<71185870,51521759,5821785>, r=85996810 pos=<71740751,69907357,45736268>, r=65023123 pos=<74373508,53585604,45108363>, r=51961543 pos=<39384745,63423764,11808214>, r=60111677 pos=<53897865,40488967,26955101>, r=50541686 pos=<1968151,67648920,1324951>, r=99749981 pos=<-6333108,53401995,41500387>, r=53628817 pos=<93995657,64045955,48179912>, r=78972768 pos=<75630102,33122351,12331280>, r=94263775 pos=<111950993,58111756,44479139>, r=94694513 pos=<104393444,55359869,36104516>, r=92759681 pos=<36139191,58890754,51953379>, r=80709461 pos=<91085904,27925266,46727551>, r=80520331 pos=<101028871,48547805,60995137>, r=80201347 pos=<75933689,54860932,47736252>, r=52169362 pos=<102245190,44587653,41255787>, r=80489018 pos=<75182160,75977082,46662873>, r=73607276 pos=<72101713,49093329,15791800>, r=74514055 pos=<110525391,61843353,51420127>, r=93418745 pos=<-3621330,70853323,41554771>, r=68314015 pos=<109703044,96876496,-27071358>, r=95644195 pos=<49165976,80200821,39104163>, r=59373488 pos=<40090315,49865951,-8297231>, r=67364352 pos=<85720191,52646559,48539250>, r=58938472 pos=<50274283,21618061,6831837>, r=85911627 pos=<55069440,64226849,-10266833>, r=98673920 pos=<159630263,64353283,-13718722>, r=75930614 pos=<26868851,48923381,66408638>, r=66058620 pos=<98311741,52889957,24557608>, r=95754967 pos=<78084883,66770544,31453330>, r=82512915 pos=<46594488,46295551,53593396>, r=92772706 pos=<37630649,79322970,65415047>, r=51998550 pos=<3832250,30190558,10794020>, r=85553706 pos=<68526113,84813691,46857962>, r=75592691 pos=<112439911,49017555,45181953>, r=85386301 pos=<39722262,84270763,24460504>, r=68643641 pos=<216644213,19856107,38332409>, r=67921068 pos=<118234806,48630898,42562996>, r=93413497 pos=<68087077,-4550885,61759748>, r=99003722 pos=<36413663,106275103,33453722>, r=78345896 pos=<69922715,52551006,64668903>, r=56772230 pos=<54565095,64403657,24258140>, r=63821908 pos=<53813289,51477776,-2489697>, r=76891633 pos=<41504944,58671613,44506054>, r=83135575 pos=<64788649,56304225,32894768>, r=57308914 pos=<45342419,77998725,27467433>, r=64984727 pos=<79536903,53915876,31075747>, r=71488148 pos=<61070564,55472196,34310941>, r=51342649 pos=<-11926056,41087860,23401613>, r=77807128 pos=<60544660,91578834,30947013>, r=90287631 pos=<107741019,52595667,43248213>, r=86199358 pos=<31797178,37465472,10322781>, r=50785118 pos=<29615930,59135087,12904337>, r=52009012 pos=<53865045,82674943,15268406>, r=90382768 pos=<47281082,45839255,4256856>, r=61272615 pos=<-30021964,60631832,30990714>, r=95057193 pos=<66683927,55882542,60726208>, r=52922155 pos=<14368668,66090973,76833826>, r=64468944 pos=<24582267,66116128,-2205526>, r=79133591 pos=<34963578,96689674,18721815>, r=82042660 pos=<31315310,60444280,41691633>, r=70003165 pos=<42633271,76711564,85479284>, r=74453600 pos=<99172457,56481958,45683876>, r=79081356 pos=<96067013,53357174,29466165>, r=89069311 pos=<46608092,82673079,46162026>, r=52230014 pos=<70165673,48533951,27467077>, r=60343473 pos=<38035984,106964660,46978585>, r=67132972 pos=<88262984,61298966,47013636>, r=71659212 pos=<79456089,35340950,38654710>, r=69547699 pos=<12702563,110272257,41302497>, r=91661307 pos=<62382150,59570813,39119020>, r=51944761 pos=<90974634,52432262,58487027>, r=71523426 pos=<105829710,25923254,48058781>, r=95934917 pos=<98255307,53994911,25442461>, r=95918560 pos=<54420761,51363140,42491748>, r=63248704 pos=<57535629,72600642,72219014>, r=71984768 pos=<55253458,63464715,89286920>, r=77634684 pos=<45264921,48526083,8023545>, r=54878520 pos=<53717805,-9387807,46218820>, r=80974106 pos=<87604280,71314279,45386687>, r=82642773 pos=<19406778,53516813,39069920>, r=93360868 pos=<-38802406,54553326,55406028>, r=84674544 pos=<87370529,48649193,37536912>, r=67593653 pos=<22831538,48591138,53050872>, r=64822654 pos=<108568731,49007857,47602183>, r=79085411 pos=<47895193,34973905,-21364631>, r=98373143 pos=<92659768,50191526,46223386>, r=65738909 pos=<53623181,79134818,5208699>, r=96660093 pos=<66629663,31264801,47859140>, r=51593024 pos=<114439370,49216948,54811820>, r=88097625 pos=<31822540,38862429,42669471>, r=84074254 pos=<39816171,92161313,39797637>, r=61290652 pos=<67830923,68202327,24840831>, r=80303350 pos=<52440598,59747047,109877627>, r=91694813 pos=<-3528699,35702096,35292963>, r=62904454 pos=<66070748,58317730,42894355>, r=50604966 pos=<-22389131,64814077,45968147>, r=76629163 pos=<18331832,91968078,31030428>, r=77999921 pos=<51876412,97739735,75486370>, r=94732101 pos=<73955606,38849779,46685992>, r=52507064 pos=<37013163,54223174,-13894282>, r=74241493 pos=<64287972,46181567,1844376>, r=80349300 pos=<-17791401,61940529,54279116>, r=69923872 pos=<80083579,38207328,33469101>, r=72494430 pos=<28468785,59327672,-22848495>, r=89101556 pos=<48778093,74415362,33650665>, r=58653789 pos=<1309589,55413121,103015515>, r=93031911 pos=<79767556,52102896,42121727>, r=58859572 pos=<116443353,45556613,43635792>, r=91338171 pos=<42435508,49610797,47649500>, r=83603615 pos=<110915024,56228953,41636148>, r=94618677 pos=<34455788,128665491,36571022>, r=95661195 pos=<55369364,57918203,32029389>, r=50369206 pos=<3535116,50852510,16448567>, r=66263142 pos=<53473421,74071528,9397278>, r=87258622 pos=<7608689,63344445,30059859>, r=61070737 pos=<76819859,77847867,29335302>, r=94443357 pos=<29107674,85549285,6279163>, r=85556611 pos=<44066583,52827895,-3384355>, r=69389638 pos=<8424586,66330736,41918657>, r=51381742 pos=<70122470,53995764,23278485>, r=69950993 pos=<28895023,61793192,36212615>, r=77248369 pos=<78163511,57807201,30174976>, r=74906524 pos=<60360726,63482254,66839283>, r=60311751 pos=<57157611,33621366,28887709>, r=58735800 pos=<62094936,95751537,42533853>, r=84423425 pos=<92870498,61866625,55058451>, r=79425316 pos=<67493191,60633226,43255690>, r=53981917 pos=<74520394,54451860,46194573>, r=51888489 pos=<34987682,59630453,48534416>, r=68745339 pos=<108182239,53061912,41637190>, r=88717758 pos=<22071485,100381324,22951133>, r=90752937 pos=<61476541,4442213,39200534>, r=81921026 pos=<97466468,54771648,53077797>, r=74945561 pos=<92224642,49093198,40667295>, r=69761785 pos=<37336193,67183494,-2266108>, r=75896593 pos=<69249728,73068853,12943453>, r=98485926 pos=<114969350,49559522,43172333>, r=90467399 pos=<86081297,48756364,18530405>, r=85418045 pos=<26316601,99912906,17036675>, r=91953743 pos=<36218371,59377387,14275042>, r=50431835 pos=<107304671,59234940,44197427>, r=91452994 pos=<35805794,97559504,7072346>, r=95403780 pos=<-14800571,60339069,24352342>, r=86181490 pos=<41087088,80963485,19486854>, r=71674721 pos=<15311833,18533918,46535147>, r=49989815 pos=<238700985,51350135,44639309>, r=95314466 pos=<60911140,79558607,70008496>, r=80107911 pos=<50373656,61506173,29722597>, r=51268174 pos=<70784771,61792291,58891161>, r=61097817 pos=<87745488,49397456,48409204>, r=57844605 pos=<100278508,42242232,47251793>, r=74871990 pos=<58574854,17919615,45175977>, r=59566503 pos=<38245994,57149063,-31232941>, r=95738887 pos=<-35089760,51492405,43584688>, r=78391583 pos=<40202324,64679674,21845792>, r=52147034 pos=<-19241225,36598464,23102492>, r=89910841 pos=<87093236,86795846,44701335>, r=98298593 pos=<112565070,34599389,45797465>, r=96256116 pos=<73985567,58061688,47533395>, r=53624998 pos=<95906658,48935965,40929646>, r=73023769 pos=<44027337,91125409,10276196>, r=93987340 pos=<77866021,71870919,24885899>, r=93962060 pos=<35562102,76720509,94945268>, r=76857434 pos=<68790412,84597174,74984103>, r=98001193 pos=<86018683,48772033,33521207>, r=70380414 pos=<77078839,53741526,42480625>, r=57450596 pos=<111126741,52522762,47121971>, r=85638486 pos=<23446490,77963127,12232878>, r=77677871 pos=<120316030,48650403,51021087>, r=89617001 pos=<68371476,48512552,35613191>, r=50382016 pos=<40519652,54849290,-21094011>, r=85573791 pos=<82453383,75574204,40612745>, r=86525640 pos=<40935104,102797991,48165712>, r=64678403 pos=<101425657,64131415,45727471>, r=88940417 pos=<-899224,50429103,2066375>, r=84656232 pos=<94661889,50308113,52884497>, r=67483976 pos=<227033046,49429705,35092569>, r=85997165 pos=<41150717,67835583,87324367>, r=65940163 pos=<58536267,114290965,43180927>, r=98757319 pos=<87517293,53148741,29481377>, r=80295652 pos=<51354776,80233324,38988033>, r=61711054 pos=<101129486,50012572,48220768>, r=72032093 pos=<40224556,55061577,30931039>, r=89248748 pos=<77338284,49470612,34128628>, r=61791245 pos=<103972356,55564222,51107694>, r=80273739 pos=<83121037,58994889,56662967>, r=68408428 pos=<42144050,66110508,78022092>, r=55906188 pos=<94495043,44411640,45093006>, r=69077727 pos=<37249337,54286999,-4285002>, r=64932151 pos=<75965619,65819019,16495440>, r=94400023 pos=<67645189,61937193,46053833>, r=52639535 pos=<83322481,62070104,43780163>, r=70723405 pos=<83793770,52857802,46996858>, r=58766064 pos=<112381911,35850675,51406825>, r=92543968 pos=<-31483204,48808902,43187178>, r=72499048 pos=<101146501,56468410,30153742>, r=96571958 pos=<-6763738,95285008,52993149>, r=90954699 pos=<72599880,65344890,13649064>, r=93406710 pos=<13152903,46003033,47430234>, r=91168190 pos=<37541439,29222953,118820059>, r=91744507 pos=<75271943,84522151,45843375>, r=83061725 pos=<57555552,66987400,31583493>, r=62070331 pos=<63081707,79346820,41545279>, r=69994077 pos=<98790204,53448424,30915927>, r=90433763 pos=<39919429,59776484,46240724>, r=86303372 pos=<44919356,63670437,12611009>, r=65089633 pos=<73584306,62813189,21811725>, r=83696587 pos=<46065027,32283297,72366360>, r=50754038 pos=<1076768,21695357,45614653>, r=61984114 pos=<13783404,50061764,47363496>, r=54153576 pos=<108302715,45732820,50825885>, r=78001694 pos=<71443601,-7171046,48132357>, r=94569540 pos=<200070638,16020550,59141214>, r=50437420 pos=<43080920,62187036,24347464>, r=50031365 pos=<87341044,62371105,42806251>, r=76016814 pos=<44833180,65233281,11571820>, r=67605441 pos=<98539946,29789687,47336000>, r=85501514 pos=<42374674,54616138,100430047>, r=67050325 pos=<59384316,66808209,4540047>, r=90763274 pos=<73559697,98081771,42718532>, r=98033919 pos=<76993631,91408186,60627908>, r=98659442 pos=<39314325,102067296,41758854>, r=68733651 pos=<7591631,73477845,43212357>, r=58068102 pos=<61719239,94075619,40881186>, r=84024625 pos=<40252559,71986557,-8060814>, r=89410736 pos=<57297698,48606729,-11513823>, r=86529103 pos=<83962752,66010678,42699058>, r=76385205 pos=<98112834,34521608,38912955>, r=88765613 pos=<47600507,84446487,47324998>, r=53832785 pos=<34354794,51301295,-35770137>, r=90537035 pos=<57977931,79862226,24623196>, r=82327776 pos=<26240575,94255214,19137323>, r=84271555 pos=<60806453,21789784,22326856>, r=80777046 pos=<93130641,61821510,72682852>, r=97264643 pos=<-27521714,60892883,31462424>, r=92347130 pos=<31477636,131890053,-78006680>, r=96992044 pos=<28940630,56019849,45100137>, r=90359950 pos=<47417633,37128899,11883223>, r=62493032 pos=<-26218044,52241408,35291041>, r=78562616 pos=<101232133,65882845,53256407>, r=90000852 pos=<65296926,53654841,68470095>, r=57051421 pos=<41573901,85775638,23686239>, r=72774114 pos=<124193979,106570642,102045214>, r=83182121 pos=<47107110,61519378,-20321721>, r=98059183 pos=<79154936,53445314,58513895>, r=60743634 pos=<-170534126,62752335,47882666>, r=65812186 pos=<69403224,66655649,44922882>, r=60247147 pos=<105723136,49324883,24436946>, r=99721904 pos=<89828941,63653354,23274080>, r=99319043 pos=<43687606,54055361,-24610179>, r=91464037 pos=<54199873,76787202,41695823>, r=58402126 pos=<56383506,111064054,45077539>, r=91480821 pos=<82469710,61477616,34973096>, r=78085059 pos=<83812917,56729712,38984151>, r=70669588 pos=<1976805,61597193,43068070>, r=51946504 pos=<61202791,44650297,22015885>, r=58623857 pos=<37711648,60370417,5268745>, r=61924112 pos=<45065221,70394266,13567651>, r=71002888 pos=<56280651,74168523,32890412>, r=66669643 pos=<96938374,71616156,46810695>, r=90854904 pos=<75852652,99239435,48569246>, r=95633674 pos=<59455996,87291938,31799838>, r=84059083 pos=<90116841,44986070,37361608>, r=71856468 """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
50,776
advent-of-code
MIT License
src/day02/Day02.kt
tschens95
573,743,557
false
{"Kotlin": 32775}
fun main() { val valueMap = mapOf("A" to 1, "B" to 2, "C" to 3, "X" to 1, "Y" to 2, "Z" to 3) fun part1(input: List<String>): Int { var totalSum = 0 for (r in input) { val s = r.split(" ") val myShapeValue = valueMap[s[1]] val enemyShapeValue = valueMap[s[0]] if (myShapeValue != null && enemyShapeValue != null) { when (s[1]) { "X" -> when (s[0]) { "A" -> totalSum += myShapeValue + 3 "B" -> totalSum += myShapeValue "C" -> totalSum += myShapeValue + 6 } "Y" -> when (s[0]) { "A" -> totalSum += myShapeValue + 6 "B" -> totalSum += myShapeValue + 3 "C" -> totalSum += myShapeValue } "Z" -> when (s[0]) { "A" -> totalSum += myShapeValue "B" -> totalSum += myShapeValue + 6 "C" -> totalSum += myShapeValue + 3 } } } } return totalSum } fun part2(input: List<String>): Int { var totalSum2 = 0 for (r in input) { val s = r.split(" ") val enemyShapeValue = valueMap[s[0]] if (enemyShapeValue != null) { when (s[1]) { "X" -> when (s[0]) { "A" -> totalSum2 += 3 "B" -> totalSum2 += 1 "C" -> totalSum2 += 2 } "Y" -> when (s[0]) { "A" -> totalSum2 += 4 "B" -> totalSum2 += 5 "C" -> totalSum2 += 6 } "Z" -> when (s[0]) { "A" -> totalSum2 += 8 "B" -> totalSum2 += 9 "C" -> totalSum2 += 7 } } } } return totalSum2 } val input = readInput("02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
9d78a9bcd69abc9f025a6a0bde923f53c2d8b301
2,229
AdventOfCode2022
Apache License 2.0
21-MonkeyMath/MonkeyMath.kt
SwampThingTom
573,012,389
false
null
// Monkey Math // https://adventofcode.com/2022/day/21 import java.io.File import java.util.ArrayDeque typealias MonkeyMap = Map<String, List<String>> typealias MutableValuesMap = MutableMap<String, Long> fun debugPrint(msg: String, show: Boolean = false) = if (show) { println(msg) } else {} fun readInput(): List<String> = File("input.txt").useLines { it.toList() } fun parseMonkey(line: String): Pair<String, List<String>> { val components = line.split(": ") val value = components[1].split(" ") return components[0] to value } fun solvePart1(monkeys: MonkeyMap): Long { val values: MutableValuesMap = mutableMapOf() return solveFor("root", monkeys, values) } fun solvePart2(monkeys: MonkeyMap): Long { val values: MutableValuesMap = mutableMapOf() val rootExpr = monkeys["root"]!! val (humnMonkey, otherMonkey) = whichMonkeyLeadsToHumn(rootExpr[0], rootExpr[2], monkeys) val expectedValue = solveFor(otherMonkey, monkeys, values) return solveForHumn(humnMonkey, expectedValue, monkeys, values) } fun whichMonkeyLeadsToHumn(lhs: String, rhs: String, monkeys: MonkeyMap): Pair<String, String> = if (leadsToHumn(lhs, monkeys)) Pair(lhs, rhs) else Pair(rhs, lhs) fun leadsToHumn(monkey: String, monkeys: MonkeyMap): Boolean { if (monkey == "humn") return true val expr = monkeys[monkey]!! if (expr.size == 1) return false return leadsToHumn(expr[0], monkeys) || leadsToHumn(expr[2], monkeys) } fun solveForHumn(monkey: String, expectedValue: Long, monkeys: MonkeyMap, values: MutableValuesMap): Long { if (monkey == "humn") { return expectedValue } val expr = monkeys[monkey]!! assert(expr.size == 3) val (humnMonkey, otherMonkey) = whichMonkeyLeadsToHumn(expr[0], expr[2], monkeys) val knownValue = solveFor(otherMonkey, monkeys, values) val newExpectedValue = evaluateInverse(expr[1], expectedValue, knownValue, humnMonkey == expr[0]) return solveForHumn(humnMonkey, newExpectedValue, monkeys, values) } fun solveFor(monkey: String, monkeys: MonkeyMap, values: MutableValuesMap): Long { val value = values[monkey] if (value is Long) { return value } val expr = monkeys[monkey]!! if (expr.size == 1) { values[monkey] = expr[0].toLong() return values[monkey]!! } assert(expr.size == 3) val lhs = values[expr[0]] ?: solveFor(expr[0], monkeys, values) val rhs = values[expr[2]] ?: solveFor(expr[2], monkeys, values) values[monkey] = evaluate(expr[1], lhs, rhs) return values[monkey]!! } fun evaluate(op: String, lhs: Long, rhs: Long): Long { return when (op) { "+" -> lhs + rhs "-" -> lhs - rhs "*" -> lhs * rhs "/" -> lhs / rhs else -> throw IllegalArgumentException("Unexpected operator.") } } fun evaluateInverse(op: String, lhs: Long, rhs: Long, lhsIsHumn: Boolean): Long { return when (op) { "+" -> lhs - rhs "-" -> if (lhsIsHumn) lhs + rhs else rhs - lhs "*" -> lhs / rhs "/" -> lhs * rhs else -> throw IllegalArgumentException("Unexpected operator.") } } fun main() { val input = readInput() val monkeys: MonkeyMap = input.map { parseMonkey(it) }.toMap() val part1 = solvePart1(monkeys) println("Part 1: $part1") val part2 = solvePart2(monkeys) println("Part 2: $part2") }
0
Makefile
1
14
a7825f70aee93980a959a63fb2d429ac587b0c86
3,406
AoC2022
MIT License
src/main/kotlin/dp/maxProfit/SolutionKt3.kt
eleven-max
441,597,605
false
{"Java": 104251, "Kotlin": 41506}
package dp.maxProfit import com.evan.dynamicprogramming.Common.CommonUtil //https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ class SolutionKt3 { fun maxProfit(prices: IntArray): Int { val dp = Array(3) { IntArray(prices.size) { 0 } } //0, 持有股票 //1,处于冷冻期 //2,不吃持有股票,也非冷冻期 dp[0][0] = -prices[0] dp[1][0] = 0 dp[2][0] = 0 for (i in 1 until prices.size){ //持有股票的最大收益 dp[0][i] = Math.max(dp[0][i-1], dp[2][i-1] - prices[i]) //处于冷冻期,今天卖出股票 dp[1][i] = dp[0][i-1] + prices[i] //不处于冷冻期,也不持有股票 dp[2][i] = Math.max(dp[2][i-1], dp[1][i-1]) } val end = prices.size -1 // CommonUtil.printMatrix(dp) return Math.max(dp[0][end], Math.max(dp[1][end], dp[2][end])) } } fun main() { val solutionKt3 = SolutionKt3() val r = solutionKt3.maxProfit(intArrayOf(1,2,3,0,2)) println(r) }
0
Java
0
0
2e9b234b052896c6b8be07044d2b0c6812133e66
1,092
Learn_Algorithm
Apache License 2.0
src/Day10.kt
JIghtuse
572,807,913
false
{"Kotlin": 46764}
import java.io.File sealed class Instruction { object Noop: Instruction() data class Addx(val value: Int): Instruction() } fun parseInstruction(line: String) = when (line) { "noop" -> Instruction.Noop else -> Instruction.Addx(line.substringAfter(" ").toInt()) } fun parseInstructions(name: String) = File("src", "$name.txt") .readLines() .map(::parseInstruction) fun execute(instructions: List<Instruction>) { val lastValue = instructions.fold(1) { x, instruction -> when (instruction) { is Instruction.Noop -> x is Instruction.Addx -> x + instruction.value } } println("last value is $lastValue") } fun sumSignalStrengthValues( instructions: List<Instruction>, interestingCycles: List<Int>): Int { var x = 1 var interestingSignalValue = 0 fun updateOnInterestingCycle(c: Int) { if (c in interestingCycles) { interestingSignalValue += c * x } } var cycle = 0 instructions.forEach { cycle += 1 when (it) { is Instruction.Noop -> { updateOnInterestingCycle(cycle) } is Instruction.Addx -> { updateOnInterestingCycle(cycle) cycle += 1 updateOnInterestingCycle(cycle) x += it.value } } } return interestingSignalValue } data class Sprite(val start: Int, val end: Int) fun isCurrentlyDrawn(sprite: Sprite, cycle: Int) = cycle >= sprite.start && cycle <= sprite.end fun toSprite(xRegister: Int) = Sprite(xRegister - 1, xRegister + 1) fun render(instructions: List<Instruction>) { var x = 1 var cycle = 0 fun drawPixel() { print(if (isCurrentlyDrawn(toSprite(x), cycle % 40)) "#" else ".") } instructions.forEach { if (cycle % 40 == 0) println() drawPixel() cycle += 1 when (it) { is Instruction.Noop -> {} is Instruction.Addx -> { if (cycle % 40 == 0) println() drawPixel() cycle += 1 x += it.value } } } println() } fun main() { fun part1(input: List<Instruction>): Int { return sumSignalStrengthValues( input, listOf(20, 60, 100, 140, 180, 220) ) } // test if implementation meets criteria from the description, like: val testInput = parseInstructions("Day10_test") check(part1(testInput) == 13140) render(testInput) val input = parseInstructions("Day10") println(part1(input)) render(input) }
0
Kotlin
0
0
8f33c74e14f30d476267ab3b046b5788a91c642b
2,692
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/pl/klemba/aoc/day1/Main.kt
aklemba
726,935,468
false
{"Kotlin": 16373}
package pl.klemba.aoc.day1 import java.io.File fun main2() { // ----- PART 1 ----- File(inputPath) .readLines() .map { extractCalibrationValue(it) } .reduce { accumulator, calibrationValue -> accumulator + calibrationValue } .let { println(it) } // ----- PART 2 ----- File(inputPath) .readLines() .map { rawLine -> formatToDigits(rawLine) } .map { extractCalibrationValue(it) } .reduce { accumulator, calibrationValue -> accumulator + calibrationValue } .let { println(it) } } fun formatToDigits(rawLine: String): String { var calibrationValue = "" var rawLineLeftToCheck = rawLine while (rawLineLeftToCheck.isNotEmpty()) { rawLineLeftToCheck.getDigitAtStart()?.let { calibrationValue += it } rawLineLeftToCheck = rawLineLeftToCheck.substring(1) } return calibrationValue } private fun String.getDigitAtStart(): Int? { println("length: " + this.length) if (first().isDigit()) return first().digitToInt() digitNames .forEach { mapEntry -> if (startsWith(mapEntry.key)) return mapEntry.value } return null } fun extractCalibrationValue(line: String): Int { val firstDigit = line.first { it.isDigit() } val lastDigit = line.last { it.isDigit() } return "$firstDigit$lastDigit".toInt() } fun transformDigitNames(line: String) = digitNames.keys .fold(line) { accumulator, digitName -> accumulator.transformDigitName(digitName) } private fun String.transformDigitName(digitName: String): String = this.replace(digitName, digitNames[digitName].toString()) private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day1/input.txt" private val digitNames: Map<String, Int> = listOf( "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" ).mapIndexed { index, digitName -> digitName to index + 1 } .toMap()
0
Kotlin
0
1
2432d300d2203ff91c41ffffe266e19a50cca944
1,901
adventOfCode2023
Apache License 2.0
src/main/kotlin/_2020/Day4.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2020 import aocRun private val keyValueRegex = Regex("(\\w+):([\\w#]+)") fun main() { aocRun(puzzleInput) { input -> return@aocRun process(input) { passport -> val size = passport.size return@process size == 8 || (size == 7 && !passport.any { it.first == PassportField.COUNTRY_ID }) } } aocRun(puzzleInput) { input -> return@aocRun process(input) { passport -> val size = passport.size return@process (size == 8 || (size == 7 && !passport.any { it.first == PassportField.COUNTRY_ID })) && passport.all { it.first.validate(it.second) } } } } private fun process(input: String, validator: (List<Pair<PassportField, String>>) -> Boolean): Int = input.split("\n\n") .map { passport -> val fields = keyValueRegex.findAll(passport) .map { PassportField.getByCode(it.groupValues[1])!! to it.groupValues[2] } .toList() if (validator(fields)) 1 else 0 } .sum() private enum class PassportField(val code: String) { BIRTH_YEAR("byr") { override fun validate(value: String): Boolean = validateYear(value, 1920..2002) }, ISSUE_YEAR("iyr") { override fun validate(value: String): Boolean = validateYear(value, 2010..2020) }, EXPIRATION_YEAR("eyr") { override fun validate(value: String): Boolean = validateYear(value, 2020..2030) }, HEIGHT("hgt") { override fun validate(value: String): Boolean = heightRegex.matchEntire(value)?.let { val num = it.groupValues[1].toInt() when (it.groupValues[2]) { "cm" -> num in 150..193 "in" -> num in 59..76 else -> false } } ?: false }, HAIR_COLOUR("hcl") { override fun validate(value: String): Boolean = colourRegex.matches(value) }, EYE_COLOUR("ecl") { override fun validate(value: String): Boolean = EyeColour.getByCode(value) != null }, PASSPORT_ID("pid") { override fun validate(value: String): Boolean = value.length == 9 && value.toIntOrNull() != null }, COUNTRY_ID("cid") { override fun validate(value: String): Boolean = true }; companion object { private val heightRegex = Regex("(\\d+)(cm|in)") private val colourRegex = Regex("#[0-9a-f]{6}") fun getByCode(code: String): PassportField? = values().find { it.code == code } } abstract fun validate(value: String): Boolean protected fun validateYear(value: String, range: IntRange): Boolean = value.length == 4 && value.toIntOrNull()?.let { it in range } ?: false } private enum class EyeColour { AMB, BLU, BRN, GRY, GRN, HZL, OTH; companion object { fun getByCode(code: String): EyeColour? = values().find { it.name.equals(code, true) } } } private val puzzleInput = """ byr:1985 eyr:2021 iyr:2011 hgt:175cm pid:163069444 hcl:#18171d eyr:2023 hcl:#cfa07d ecl:blu hgt:169cm pid:494407412 byr:1936 ecl:zzz eyr:2036 hgt:109 hcl:#623a2f iyr:1997 byr:2029 cid:169 pid:170290956 hcl:#18171d ecl:oth pid:266824158 hgt:168cm byr:1992 eyr:2021 byr:1932 ecl:hzl pid:284313291 iyr:2017 hcl:#efcc98 eyr:2024 hgt:184cm iyr:2017 pid:359621042 cid:239 eyr:2025 ecl:blu byr:1986 hgt:188cm eyr:2027 hgt:185cm hcl:#373b34 pid:807766874 iyr:2015 byr:1955 ecl:hzl iyr:2017 hcl:#7d3b0c hgt:174cm byr:1942 eyr:2025 ecl:blu pid:424955675 eyr:2026 byr:1950 hcl:#ceb3a1 hgt:182cm iyr:2016 pid:440353084 ecl:amb hcl:a4c546 iyr:1932 pid:156cm eyr:2034 hgt:193 ecl:zzz byr:2025 hcl:#ceb3a1 eyr:2020 pid:348696077 hgt:163cm ecl:hzl byr:1921 iyr:2016 ecl:gmt eyr:2031 iyr:2018 byr:1971 hgt:152in pid:454492414 hcl:z hcl:#341e13 byr:1921 iyr:2020 pid:072379782 eyr:2022 hgt:166cm cid:253 ecl:brn ecl:blu hgt:75in byr:1954 eyr:2026 iyr:2012 hcl:#623a2f pid:328598886 byr:2004 eyr:2035 hcl:#7d3b0c pid:359128744 iyr:2020 hgt:65cm ecl:#70f23f eyr:1988 pid:171cm byr:2003 iyr:1984 cid:50 hcl:z hgt:66cm ecl:#7a4c6e pid:9632440323 eyr:1964 hgt:63cm ecl:#fab0c5 hcl:z iyr:1945 byr:1986 pid:936403762 ecl:#337357 byr:1997 cid:196 iyr:2020 eyr:2030 hgt:165cm hcl:#7d3b0c byr:1931 pid:488791624 hgt:169cm ecl:blu eyr:2029 hcl:#fffffd iyr:2013 hcl:#733820 hgt:76in pid:517689823 eyr:2028 byr:1988 ecl:brn iyr:2016 eyr:2023 hcl:#fffffd hgt:190cm iyr:2015 ecl:brn pid:739536900 byr:1951 ecl:brn byr:1986 cid:262 hcl:#efcc98 pid:880203213 hgt:185cm iyr:2018 eyr:2029 pid:181cm hgt:113 hcl:z ecl:#2c2d2c iyr:1961 byr:2021 eyr:2031 hcl:#ceb3a1 iyr:2020 byr:1977 hgt:192cm pid:338237458 eyr:2030 ecl:amb iyr:1953 byr:2025 hgt:66cm eyr:1932 pid:181cm ecl:#6f0b15 hcl:f79cb7 cid:109 hcl:#6b5442 pid:164cm ecl:blu hgt:176cm byr:2015 iyr:2010 eyr:2029 eyr:2035 pid:085002665 ecl:#f88074 iyr:2018 hcl:#602927 hgt:169cm byr:1958 hcl:z pid:0468194841 iyr:2016 eyr:2007 hgt:152cm ecl:#1c7a89 cid:124 hcl:z pid:233430735 byr:2021 eyr:2026 iyr:1953 ecl:#64769d hgt:184 hgt:70cm pid:156397147 iyr:2014 ecl:#d6ada0 byr:2030 hcl:#cfa07d ecl:amb byr:1990 iyr:2017 hgt:164cm hcl:10f33a cid:293 eyr:2020 pid:332276985 pid:163252726 eyr:2026 hgt:163cm iyr:2011 hcl:#efcc98 ecl:hzl byr:1936 hgt:157cm iyr:2019 pid:078770050 hcl:#efcc98 byr:1967 eyr:2030 ecl:gry cid:190 hgt:184cm ecl:amb pid:851379559 hcl:#ceb3a1 byr:1946 eyr:2022 iyr:2017 cid:280 hgt:171cm byr:1942 pid:830156471 hcl:#cfa07d ecl:gry eyr:2032 iyr:2022 byr:2013 ecl:#67cbe8 eyr:2024 pid:242908367 hgt:76cm iyr:2025 hcl:796bda ecl:amb iyr:2019 byr:1945 eyr:2021 hcl:#602927 pid:550065206 hgt:72in ecl:brn byr:1956 pid:253685193 iyr:2017 eyr:2023 hcl:#6b5442 eyr:2032 iyr:2019 hgt:176cm ecl:oth pid:800237895 hcl:#888785 byr:1979 eyr:2026 iyr:2020 cid:226 pid:882830512 hcl:#866857 byr:1929 ecl:amb hgt:60in hcl:#cfa07d ecl:oth iyr:2015 pid:807837948 byr:1966 eyr:2030 hgt:191in byr:1969 iyr:2012 eyr:2024 cid:244 ecl:hzl hcl:#18171d pid:344160556 eyr:2020 pid:718422803 hcl:#18171d hgt:181cm byr:1925 ecl:amb iyr:2019 byr:1943 pid:740807220 hgt:72in ecl:amb iyr:2013 eyr:2022 hcl:#cfa07d hcl:#733820 byr:1986 iyr:2016 hgt:184cm cid:333 pid:768188726 ecl:oth eyr:2030 eyr:2022 byr:1996 hcl:#341e13 ecl:hzl iyr:2015 hgt:160cm pid:516401532 hgt:182cm ecl:grn pid:336742028 iyr:2014 hcl:#34f021 byr:1967 eyr:2029 byr:2030 hgt:142 iyr:2029 eyr:2040 hcl:426fc5 cid:312 pid:169cm ecl:#069ff7 hgt:169cm ecl:gry hcl:#6b5442 iyr:2012 byr:1949 pid:131835020 eyr:2022 hgt:70cm iyr:2012 eyr:2037 hcl:64fd76 cid:175 pid:4880649770 ecl:grn byr:2029 iyr:2013 hcl:#7d3b0c eyr:2024 hgt:190cm pid:659772377 cid:226 ecl:oth byr:1958 ecl:lzr hgt:163cm pid:013605217 byr:2000 eyr:2020 hcl:z iyr:2024 cid:131 pid:896076106 hcl:#c0946f byr:1930 hgt:162cm eyr:2023 ecl:oth iyr:2017 byr:1935 iyr:2012 pid:942509879 ecl:amb hgt:185cm cid:152 eyr:2024 hcl:#866857 ecl:#e490a3 hcl:4813a2 hgt:176cm pid:778369210 iyr:2020 eyr:2035 byr:2020 byr:2006 ecl:amb pid:148409219 hgt:189cm eyr:2021 hcl:z iyr:2028 hgt:188in hcl:#9ed525 iyr:2018 ecl:grn eyr:2021 pid:065515632 byr:2012 cid:109 hgt:167cm pid:545112664 ecl:grn hcl:#a62fea eyr:2026 iyr:2012 byr:1921 pid:174997024 iyr:2012 eyr:2030 ecl:grn hgt:150cm byr:1997 hcl:#866857 pid:451921339 hgt:181cm hcl:#888785 iyr:2017 eyr:2026 byr:1936 ecl:hzl hgt:187in hcl:#866857 ecl:grn pid:623919686 eyr:2028 iyr:2011 byr:2016 byr:2001 ecl:gry eyr:2023 pid:324948416 hcl:ef16f8 cid:139 hgt:184in iyr:2026 byr:1954 hcl:#341e13 eyr:2023 pid:129321944 iyr:2012 hgt:183cm ecl:amb hgt:164cm pid:596870080 ecl:hzl eyr:2021 iyr:2017 hcl:#a97842 byr:1951 iyr:2013 byr:1944 hcl:#cfa07d hgt:168cm cid:72 pid:160531632 ecl:grn iyr:2012 pid:900043442 hcl:#ceb3a1 cid:124 byr:1941 ecl:blu hgt:156cm eyr:2025 eyr:2021 hgt:61in iyr:2020 ecl:grn byr:1933 byr:1971 cid:175 eyr:2028 hcl:#efcc98 iyr:2013 hgt:170cm pid:225213589 pid:147112660 hcl:#ceb3a1 eyr:2029 hgt:159cm ecl:grn iyr:2014 byr:1967 iyr:2015 pid:502975636 hgt:71in byr:1994 hcl:#18171d ecl:amb eyr:2029 byr:1948 hcl:#b6652a hgt:171in pid:181cm iyr:2019 ecl:grt cid:87 pid:859849571 ecl:amb hcl:#6b5442 hgt:193cm byr:1980 iyr:2017 eyr:2020 cid:125 pid:508147848 hcl:06ea75 iyr:1997 byr:2010 ecl:#c707f7 eyr:1970 hgt:161 eyr:2020 cid:326 byr:1989 ecl:gry hgt:160cm hcl:#cc080c pid:319135853 iyr:2010 ecl:utc pid:531595917 hgt:180cm byr:1987 eyr:2024 hcl:#cfa07d iyr:2025 ecl:gry byr:2007 eyr:2028 iyr:2025 pid:6072964414 hgt:59cm hcl:#888785 pid:791025828 ecl:hzl hgt:178cm iyr:2017 hcl:#733820 byr:1960 eyr:2021 cid:66 byr:1991 iyr:1934 cid:304 hgt:183cm ecl:grn pid:408294229 eyr:2027 hcl:#623a2f ecl:blu hgt:181cm eyr:2024 iyr:2010 pid:633234602 hcl:#2ce009 byr:1985 hcl:#c0946f hgt:192cm iyr:2012 pid:120684397 ecl:grn eyr:2027 byr:1974 eyr:2026 pid:068304960 hgt:190cm byr:1925 iyr:2020 ecl:oth hcl:#733820 hgt:168cm cid:307 iyr:2014 byr:1981 ecl:hzl pid:898831724 eyr:2026 hgt:73cm eyr:2038 byr:1980 ecl:gry iyr:2027 pid:678846912 hcl:z hgt:150cm cid:261 eyr:2021 hcl:z pid:159cm iyr:2014 ecl:hzl byr:1955 pid:#172650 ecl:gry eyr:2040 hcl:z iyr:2013 hgt:169cm byr:2008 cid:290 iyr:2017 byr:1998 hcl:#ceb3a1 pid:274178898 eyr:2027 ecl:brn hgt:183cm eyr:2024 cid:183 ecl:grn byr:1946 hgt:63in hcl:#6b5442 iyr:2017 hgt:97 byr:1990 iyr:2019 ecl:grn pid:587580330 hcl:#341e13 eyr:2022 ecl:oth pid:441517075 hcl:#c0946f iyr:2015 hgt:188cm eyr:2024 byr:1920 hgt:191in pid:185cm iyr:1993 hcl:93033d eyr:2034 ecl:dne pid:591478424 ecl:grn hcl:#888785 byr:1929 eyr:2023 hgt:173cm iyr:2017 iyr:1954 hgt:63cm hcl:bdf2e0 ecl:amb pid:#912f46 byr:1956 iyr:2012 hgt:73in pid:986643426 ecl:blu cid:235 eyr:2025 hcl:#cfa07d cid:320 byr:1930 hgt:172cm ecl:oth eyr:2024 iyr:2019 byr:1935 hgt:182cm pid:22794407 hcl:1b96fb eyr:1961 iyr:1941 ecl:#5e80cd cid:70 iyr:2020 eyr:2021 ecl:amb hgt:59in pid:594829025 hcl:#93092e byr:1976 hcl:#a97842 eyr:2030 byr:1937 iyr:2018 cid:295 ecl:oth hgt:166cm pid:282634012 hgt:171cm hcl:#623a2f byr:1956 pid:068178613 cid:214 iyr:2012 eyr:2026 ecl:brn byr:1921 hgt:161cm hcl:#888785 ecl:brn pid:010348794 eyr:2023 iyr:2011 hcl:#a97842 iyr:2010 byr:1955 eyr:2024 pid:473791166 ecl:brn hgt:175cm eyr:2028 ecl:grn pid:186196675 byr:1945 hgt:155cm cid:349 iyr:2011 hcl:#6b5442 hgt:161cm eyr:2030 cid:221 pid:994494879 hcl:#733820 iyr:2012 ecl:blu byr:1957 eyr:1993 iyr:2022 hcl:z byr:2020 pid:013428192 hgt:62cm ecl:dne hgt:178cm eyr:2029 hcl:#733820 byr:1962 iyr:2017 ecl:blu pid:567713232 hcl:#fffffd byr:1928 pid:390162554 eyr:2030 cid:79 hgt:150cm ecl:amb iyr:2019 eyr:2030 cid:320 hgt:171cm hcl:#888785 pid:540720799 ecl:amb iyr:2012 byr:1979 byr:1921 ecl:oth pid:204986110 eyr:2023 hgt:154cm iyr:2017 hcl:#341e13 cid:126 eyr:2020 cid:175 ecl:dne byr:1983 iyr:2016 hcl:#c0946f hgt:65cm hgt:191cm iyr:2010 cid:295 byr:1984 eyr:2025 hcl:#cfa07d pid:799775698 ecl:amb iyr:2020 cid:278 hcl:#c0946f byr:1970 pid:773144393 eyr:2024 hgt:180cm hgt:176cm byr:1963 pid:252396293 iyr:2012 ecl:brn hcl:#ceb3a1 eyr:2030 pid:545130492 byr:2030 iyr:2020 hgt:190cm eyr:2034 ecl:blu hcl:#fffffd hcl:#a97842 pid:032201787 hgt:190cm ecl:gry eyr:2028 iyr:2012 byr:1994 hcl:#a97842 pid:064591809 ecl:hzl byr:1927 hgt:165cm iyr:2011 eyr:2028 cid:77 byr:2005 hgt:125 iyr:1923 ecl:#605d73 eyr:2022 pid:90184674 hcl:z cid:301 pid:106820988 iyr:2018 hcl:#cfa07d eyr:2029 byr:1993 hgt:193cm ecl:grn hcl:#623a2f cid:118 ecl:oth pid:75827285 hgt:189cm iyr:2010 eyr:2030 byr:1976 ecl:blu iyr:2023 eyr:1996 hgt:66cm cid:251 byr:1972 hcl:z pid:557774244 byr:2002 hgt:169cm pid:629420566 eyr:2026 ecl:grn hcl:#341e13 cid:166 iyr:2019 iyr:2026 hcl:9b83a1 eyr:1979 ecl:dne hgt:111 pid:176cm pid:#89718c byr:2026 hcl:2ca5c7 hgt:142 eyr:2040 ecl:lzr iyr:2029 ecl:grn byr:2022 eyr:2020 pid:7024869 hgt:123 iyr:2019 hcl:z hcl:#733820 hgt:155cm ecl:grn iyr:2020 byr:1955 eyr:2028 pid:217362007 hcl:#18171d ecl:gry byr:1971 hgt:193cm eyr:2020 pid:352009857 iyr:2013 byr:2018 hgt:175in ecl:xry iyr:2015 eyr:2036 cid:171 pid:6132398 hcl:#efcc98 pid:839955293 byr:1928 hcl:#fffffd ecl:hzl iyr:2011 hgt:162cm eyr:2023 hgt:175cm pid:482827478 eyr:2028 hcl:#6b5442 ecl:blu byr:1932 iyr:2010 iyr:2020 hcl:#866857 ecl:brn byr:1933 cid:269 pid:003931873 hgt:188cm eyr:2022 byr:1981 hcl:#fffffd hgt:160cm cid:311 ecl:brn eyr:2025 pid:930857758 iyr:2014 hcl:#cfa07d hgt:73in ecl:gry pid:383281251 iyr:2013 byr:1934 eyr:2026 byr:1988 eyr:2026 pid:458002476 iyr:2017 hgt:175cm ecl:amb eyr:1987 byr:2020 pid:299341304 hcl:#341e13 iyr:1935 cid:125 hgt:168cm ecl:gry iyr:2014 hcl:#b6652a pid:445799347 hgt:188cm byr:1960 eyr:2030 cid:290 ecl:amb eyr:2023 hgt:75cm hcl:#733820 cid:195 byr:1933 ecl:amb pid:062770586 iyr:2019 hgt:168cm eyr:2021 pid:725299968 ecl:grn byr:1932 iyr:2016 hcl:#888785 hgt:161cm hcl:#ceb3a1 byr:1962 eyr:2026 iyr:2013 ecl:amb pid:695426469 cid:227 ecl:dne hcl:#ceb3a1 iyr:2013 eyr:2022 pid:434786988 byr:1956 hgt:183cm pid:697500517 byr:1968 hgt:169cm hcl:#fffffd ecl:grn cid:143 iyr:2010 eyr:2027 byr:2029 ecl:amb hgt:175in iyr:2015 hcl:#ceb3a1 pid:39839448 eyr:2021 cid:105 pid:0985607981 ecl:hzl iyr:2012 eyr:2021 byr:2024 hcl:5cad22 hgt:190cm hcl:#b6652a hgt:178cm cid:222 byr:1992 ecl:grn iyr:2011 pid:419544742 iyr:2019 byr:1960 ecl:hzl eyr:2021 hgt:184cm cid:66 hcl:#866857 pid:412920622 eyr:2025 hcl:#888785 iyr:2018 byr:1956 pid:698098389 ecl:grn hgt:173cm ecl:blu byr:1935 pid:354892542 hgt:161cm iyr:2018 eyr:2021 hcl:#b6652a ecl:oth cid:287 iyr:2028 byr:1953 eyr:2027 hcl:#7d3b0c hgt:151cm pid:211411839 iyr:2018 byr:1934 hcl:#a97842 pid:859748861 ecl:oth hgt:175cm eyr:2025 byr:1930 iyr:2018 eyr:2022 hgt:175cm hcl:#292092 ecl:brn pid:987163365 hgt:167in hcl:#888785 eyr:2040 pid:4646402867 byr:2013 iyr:1941 ecl:#389aec ecl:hzl hcl:#602927 hgt:168cm eyr:2026 cid:235 iyr:2016 byr:1942 iyr:1975 pid:11337832 ecl:#a25273 hgt:151 byr:2017 eyr:1979 hgt:71cm byr:2003 hcl:7e7da7 pid:151cm ecl:#a8afb3 iyr:1937 eyr:2021 hgt:74in hcl:#cfa07d iyr:2014 byr:1932 pid:641867677 ecl:grn ecl:gry hgt:185cm pid:556229206 iyr:2013 byr:1984 hcl:#fffffd eyr:2028 eyr:2020 byr:1989 ecl:grn pid:618876158 hcl:z hgt:176cm iyr:2025 eyr:2025 byr:2001 hcl:#cdb7f9 pid:377402126 ecl:hzl hgt:184cm iyr:2019 byr:1939 hgt:180cm eyr:2029 ecl:oth hcl:#733820 iyr:2016 pid:733456875 pid:883743276 hcl:#7d3b0c eyr:2022 ecl:blu byr:1928 hgt:150cm cid:150 iyr:2013 hgt:60cm ecl:#43f03d eyr:1994 byr:1975 iyr:1980 pid:169cm hgt:104 byr:2029 eyr:2040 hcl:64a9b2 pid:83898860 iyr:1990 ecl:#938bbe pid:284399238 ecl:gry hcl:#888785 iyr:2019 hgt:168cm byr:1944 eyr:2022 hcl:#733820 pid:486515752 ecl:grn hgt:188in byr:1941 iyr:2017 eyr:2005 iyr:2010 byr:1978 hgt:160cm eyr:2003 ecl:oth hcl:#efcc98 pid:584668011 byr:1944 ecl:gry pid:962700562 iyr:2011 hcl:#866857 eyr:2022 hgt:191cm hcl:z pid:758583213 iyr:1941 ecl:gry eyr:2007 hgt:67 byr:2022 cid:215 byr:1988 ecl:#ae2a9b hcl:#fe9d14 iyr:2012 pid:411550516 hgt:169cm eyr:2038 pid:400034647 byr:1927 hgt:165cm iyr:2017 ecl:brn eyr:2024 cid:144 hcl:#341e13 hcl:#733820 hgt:153cm eyr:2027 byr:1935 pid:217121064 cid:120 iyr:2012 ecl:grn hgt:168cm hcl:#866857 iyr:2012 pid:1527348755 byr:1946 eyr:2028 cid:184 ecl:amb hcl:#a97842 byr:1967 hgt:152cm eyr:2030 ecl:blu pid:929661915 iyr:2018 pid:671485026 hgt:188cm byr:1974 iyr:2015 ecl:grn cid:268 eyr:2021 hcl:#c0946f pid:789877199 iyr:2011 cid:219 eyr:2029 ecl:oth byr:1991 hcl:#866857 hgt:154cm cid:137 pid:059579902 eyr:2020 byr:1952 hcl:#18171d iyr:2020 hgt:172cm ecl:oth pid:182cm iyr:1997 byr:2012 eyr:2034 hgt:161in ecl:#528abf hcl:b7d2fe hgt:192cm ecl:oth iyr:2017 pid:264538307 byr:1994 cid:285 hcl:#18171d eyr:2030 hcl:#efcc98 pid:38036608 eyr:2010 iyr:2026 byr:2027 cid:239 ecl:zzz hgt:74 iyr:2012 eyr:2022 hgt:178cm hcl:#888785 ecl:hzl byr:1998 pid:000080585 pid:719620152 hcl:#b6652a cid:133 ecl:hzl byr:1983 iyr:2012 hgt:175cm eyr:2024 cid:155 eyr:1977 iyr:2019 ecl:#28de8b byr:1941 hcl:#602927 hgt:173cm pid:493773064 iyr:2010 pid:842124616 ecl:hzl eyr:2025 cid:146 hcl:#733820 hgt:166cm byr:1987 hcl:fd4dcf byr:2006 iyr:2011 pid:820797708 eyr:2020 hgt:189cm ecl:gry iyr:1971 pid:22107293 hcl:#5b3f01 cid:257 ecl:hzl hgt:60cm eyr:2000 byr:1965 byr:1932 eyr:2028 hcl:#6b5442 ecl:amb pid:947149686 iyr:2015 hgt:187cm hcl:#a97842 cid:260 hgt:167cm eyr:2027 byr:1973 ecl:oth pid:741678753 iyr:2016 pid:334234443 ecl:gry hcl:#18171d eyr:2020 iyr:2016 hgt:159cm byr:1926 hgt:118 eyr:1929 iyr:2013 pid:987139064 cid:196 hcl:#cfa07d ecl:#f72601 byr:1929 byr:1924 pid:623185744 iyr:2012 cid:341 hcl:#602927 hgt:192cm eyr:2022 iyr:2012 byr:1971 hgt:168cm cid:146 pid:673038025 hcl:#866857 eyr:2020 ecl:hzl eyr:2023 iyr:2017 pid:205596613 cid:298 hcl:#341e13 hgt:169cm ecl:oth byr:1996 ecl:blu pid:775831730 eyr:2029 iyr:1924 hgt:168cm hcl:z byr:2023 hgt:181cm pid:4365105095 iyr:2021 ecl:lzr eyr:2024 hcl:z hgt:184cm byr:1987 pid:175cm ecl:#83a5fa eyr:2023 eyr:2021 pid:422371422 ecl:oth iyr:2015 hcl:#866857 byr:1963 hgt:174cm pid:006970943 hcl:#2f22ef iyr:2020 ecl:gry byr:1922 eyr:2024 hgt:163cm cid:160 byr:2015 eyr:2038 hcl:z ecl:grt hgt:166 iyr:2026 pid:#14978f hgt:178cm eyr:2021 iyr:2016 pid:471529794 hcl:#b6652a cid:192 ecl:grn byr:1970 iyr:2015 ecl:brn hcl:#602927 hgt:187cm pid:729284172 eyr:2024 byr:1932 cid:153 ecl:dne eyr:2005 pid:178cm iyr:2028 byr:2029 hgt:160in hcl:482a92 byr:1995 iyr:2012 hcl:#866857 hgt:159cm eyr:1950 ecl:gry pid:183cm pid:875885919 hgt:159cm iyr:2011 ecl:gry byr:1988 hcl:#341e13 eyr:2028 pid:2390267705 hcl:#7d3b0c byr:2009 eyr:2017 ecl:grn hgt:183cm iyr:2015 ecl:brn eyr:2029 hcl:#866857 iyr:2020 hgt:180cm byr:2001 pid:668021168 hcl:#c0946f eyr:2024 ecl:amb pid:013487714 byr:1965 hgt:172cm cid:320 iyr:2020 eyr:2025 pid:115479767 hcl:#866857 ecl:oth hgt:163cm iyr:2010 byr:1999 byr:1967 iyr:2011 cid:112 hcl:#733820 eyr:2040 ecl:grt hgt:66 pid:804536366 hgt:163 pid:1764836278 eyr:2035 iyr:2021 hcl:z ecl:#f1bb27 hcl:#efcc98 hgt:176cm byr:1994 pid:590539278 ecl:grn iyr:2011 eyr:2021 iyr:2017 eyr:2024 hgt:167cm hcl:#b62e29 pid:495674801 byr:1970 ecl:brn hgt:168cm pid:993244641 byr:1968 eyr:1926 hcl:#b6652a ecl:brn iyr:2023 hgt:63in hcl:z pid:594070517 eyr:2021 ecl:oth iyr:2017 byr:2000 eyr:2030 pid:272955042 cid:319 iyr:2011 ecl:amb byr:1999 hcl:#888785 hgt:158cm eyr:2025 pid:814305816 byr:1945 ecl:brn hgt:162cm iyr:2018 hcl:#a97842 cid:229 byr:1996 eyr:2026 pid:582584802 hcl:#c0946f iyr:2020 ecl:grn hgt:162cm eyr:2027 hgt:155cm byr:1925 hcl:#888785 cid:182 iyr:2014 ecl:brn pid:250884352 hgt:173cm cid:135 iyr:2017 pid:661330507 byr:1950 eyr:2020 ecl:gry hcl:#18171d pid:208932950 eyr:2030 hgt:179cm iyr:2013 ecl:oth byr:1981 cid:58 hcl:#6b5442 hcl:#f183e7 iyr:2014 hgt:159cm pid:614579850 ecl:gry eyr:2029 cid:186 byr:1962 eyr:2027 hcl:#db3405 byr:1938 pid:194516631 cid:167 hgt:177cm ecl:oth hgt:68in hcl:#733820 pid:228644594 eyr:2030 ecl:gry iyr:2010 cid:334 byr:1951 iyr:2017 hcl:#341e13 pid:#6a28c9 hgt:154cm ecl:gry byr:1966 eyr:2023 pid:250155574 cid:84 hgt:157cm ecl:grn byr:1937 iyr:2017 eyr:2024 hcl:#b6652a pid:831823039 eyr:2028 iyr:2015 ecl:gry hgt:192cm cid:137 byr:1922 hcl:#6b5442 hgt:193cm byr:1941 eyr:2024 cid:56 hcl:#623a2f ecl:amb pid:351293754 iyr:2016 byr:1947 iyr:2012 ecl:hzl hcl:#602927 eyr:2028 pid:252010138 hgt:152cm hcl:#a97842 pid:801192586 ecl:hzl iyr:2018 hgt:193cm byr:1928 cid:323 eyr:2028 hgt:151cm pid:756347561 ecl:hzl eyr:2024 cid:161 iyr:2016 hcl:#623a2f byr:2002 pid:648012871 iyr:2015 ecl:blu eyr:2025 hcl:#623a2f byr:1973 hgt:177cm byr:1999 hcl:#ceb3a1 cid:345 eyr:2025 ecl:#b29a96 pid:093304949 iyr:2017 hgt:93 hcl:#b6652a iyr:2018 ecl:grn byr:1951 pid:077278028 eyr:2024 hgt:62in hgt:164cm pid:410770618 byr:1958 iyr:2019 eyr:2030 ecl:gry hcl:#fffffd cid:293 ecl:grt eyr:2039 hcl:z pid:188cm byr:2022 iyr:2027 hgt:76cm ecl:grn iyr:2012 hgt:150cm eyr:2024 byr:1926 pid:954310029 cid:64 hcl:#fffffd ecl:oth eyr:2027 pid:091152959 hgt:180cm hcl:#ceb3a1 iyr:2015 cid:350 byr:1924 iyr:2017 hcl:#49a793 eyr:2021 cid:144 byr:1966 pid:717543257 hgt:161cm ecl:hzl eyr:2025 ecl:brn hgt:60in pid:391973520 byr:1928 cid:77 iyr:2012 hcl:#602927 iyr:2013 hgt:161cm pid:784483994 byr:1991 hcl:#cfa07d eyr:2024 ecl:grn ecl:hzl iyr:1967 byr:2009 cid:265 hgt:180in pid:168cm eyr:1966 eyr:2024 iyr:2019 pid:534453983 byr:2028 ecl:oth hcl:#341e13 hgt:193cm eyr:2029 iyr:2010 hcl:#623a2f ecl:gry hgt:152cm pid:572128647 byr:1996 iyr:2014 byr:1981 cid:176 ecl:grn hgt:183cm pid:974469723 eyr:2027 eyr:2029 pid:233353682 byr:1968 ecl:gry hgt:181cm iyr:2011 hcl:#efcc98 hgt:61 iyr:2005 cid:203 ecl:gmt pid:157cm hcl:z byr:2013 iyr:2020 byr:1923 ecl:blu eyr:2026 pid:069770502 hgt:69cm hcl:z byr:1997 hgt:160cm hcl:z iyr:2021 eyr:1920 pid:9374226872 ecl:hzl eyr:2024 pid:537492791 hgt:186cm byr:1952 hcl:#cfa07d iyr:2020 hgt:73cm byr:1974 ecl:xry iyr:2016 cid:133 hcl:e741f5 pid:186cm pid:161cm byr:1950 eyr:2028 ecl:hzl hcl:#7d3b0c iyr:2014 hgt:158cm ecl:#2c491e hcl:f8fe13 byr:2022 hgt:137 iyr:1948 eyr:2040 pid:#959a0f byr:1923 hgt:70in pid:904825661 hcl:#b6652a iyr:2010 eyr:2020 ecl:oth iyr:2013 ecl:blu pid:858020233 byr:1950 hgt:61in hcl:#18171d iyr:2016 ecl:amb pid:613754206 byr:1975 hgt:164cm eyr:2025 byr:1938 iyr:2017 hcl:#623a2f cid:191 eyr:2027 hgt:174cm pid:287108745 ecl:amb iyr:2025 hcl:#623a2f byr:2019 hgt:170cm cid:233 pid:55323151 ecl:amb eyr:2037 ecl:amb hgt:177cm hcl:#b6a3ce eyr:2025 byr:1967 pid:506927066 iyr:2018 cid:93 byr:1964 hgt:173cm eyr:2030 cid:106 pid:587635596 iyr:2012 hcl:#fb5993 ecl:hzl ecl:lzr pid:190cm hcl:44746d eyr:1955 hgt:66cm iyr:1990 byr:2003 ecl:brn byr:1968 cid:216 hgt:181in hcl:#b6652a iyr:2016 eyr:2020 pid:0208311541 ecl:hzl hgt:181cm eyr:1977 byr:2018 pid:527754216 hcl:#c0946f ecl:grn hcl:#efcc98 byr:1935 eyr:2025 iyr:2018 hgt:65in pid:396444938 cid:293 hgt:64in ecl:oth hcl:#18171d pid:105602506 byr:1973 eyr:2022 iyr:2014 eyr:2039 hgt:64 ecl:#ab45a8 byr:2009 iyr:2025 pid:182cm hcl:d1614a cid:103 """.trimIndent()
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
21,560
AdventOfCode
Creative Commons Zero v1.0 Universal
src/Day14.kt
arksap2002
576,679,233
false
{"Kotlin": 31030}
import kotlin.math.max import kotlin.math.min fun main() { val board = mutableListOf<MutableList<Char>>() val n = 700 fun put(x: Int, y: Int): Boolean { if (x == board.size - 1) return false if (board[x + 1][y] == '.') return put(x + 1, y) if (board[x + 1][y - 1] == '.') return put(x + 1, y - 1) if (board[x + 1][y + 1] == '.') return put(x + 1, y + 1) board[x][y] = 'o' return true } fun part1(input: List<String>): Int { for (i in 0..n) { val line = mutableListOf<Char>() for (j in 0..n) { line.add('.') } board.add(line) } for (line in input) { val points = line.split(" -> ") for (i in points.indices) { if (i == points.size - 1) break val x1 = points[i].split(",")[0].toInt() val y1 = points[i].split(",")[1].toInt() val x2 = points[i + 1].split(",")[0].toInt() val y2 = points[i + 1].split(",")[1].toInt() if (x1 == x2) { for (k in min(y1, y2)..max(y1, y2)) { board[k][x1] = '#' } } if (y1 == y2) { for (k in min(x1, x2)..max(x1, x2)) { board[y1][k] = '#' } } } } var result = 0 while (put(1, 500)) { result++ } return result } fun part2(input: List<String>): Int { for (i in 0..n) { val line = mutableListOf<Char>() for (j in 0..n) { line.add('.') } board.add(line) } var depth = 0 for (line in input) { val points = line.split(" -> ") for (i in points.indices) { if (i == points.size - 1) break val x1 = points[i].split(",")[0].toInt() val y1 = points[i].split(",")[1].toInt() val x2 = points[i + 1].split(",")[0].toInt() val y2 = points[i + 1].split(",")[1].toInt() depth = max(depth, max(y1, y2)) if (x1 == x2) { for (k in min(y1, y2)..max(y1, y2)) { board[k][x1] = '#' } } if (y1 == y2) { for (k in min(x1, x2)..max(x1, x2)) { board[y1][k] = '#' } } } } depth += 2 for (i in 0..n) { board[depth][i] = '#' } var result = 0 while (put(0, 500)) { result++ if (board[0][500] == 'o') break } return result } val input = readInput("Day14") part1(input).println() board.clear() part2(input).println() }
0
Kotlin
0
0
a24a20be5bda37003ef52c84deb8246cdcdb3d07
2,977
advent-of-code-kotlin
Apache License 2.0
src/test/kotlin/be/brammeerten/y2022/Day8Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2022 import be.brammeerten.readFile import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class Day8Test { @Test fun `part 1`() { val forest = toMap(readFile("2022/day8/exampleInput.txt")) Assertions.assertEquals(21, forest.getVisibleTrees().size) } @Test fun `part 2`() { val forest = toMap(readFile("2022/day8/exampleInput.txt")) Assertions.assertEquals(4, forest.getScenicScore(2, 1)) Assertions.assertEquals(8, forest.getScenicScore(2, 3)) Assertions.assertEquals(8, forest.getBestScenicScore()) } fun toMap(lines: List<String>) = ForestMap(lines.map { it.toCharArray().map { tree -> tree.digitToInt() } }) class ForestMap(val trees: List<List<Int>>) { val width = trees[0].size val height = trees.size fun getVisibleTrees(): Set<Tree> { val visible = HashSet<Tree>() for (row in 0 until height) { var heighest = Int.MIN_VALUE for (col in 0 until width) { if (trees[row][col] > heighest) { visible.add(Tree(col, row, trees[row][col])) heighest = trees[row][col] } } } for (row in 0 until height) { var heighest = Int.MIN_VALUE for (col in width-1 downTo 0) { if (trees[row][col] > heighest) { visible.add(Tree(col, row, trees[row][col])) heighest = trees[row][col] } } } for (col in 0 until width) { var heighest = Int.MIN_VALUE for (row in 0 until height) { if (trees[row][col] > heighest) { visible.add(Tree(col, row, trees[row][col])) heighest = trees[row][col] } } } for (col in 0 until width) { var heighest = Int.MIN_VALUE for (row in height-1 downTo 0) { if (trees[row][col] > heighest) { visible.add(Tree(col, row, trees[row][col])) heighest = trees[row][col] } } } return visible } fun getBestScenicScore(): Int { var max = -1 for (row in trees.indices) { for (col in trees[0].indices) { max = Math.max(max, getScenicScore(col, row)) } } return max } fun getScenicScore(x: Int, y: Int): Int { var score = 1 // To right var count = 0 for (col in x+1 until width) { count++ if (trees[y][col] >= trees[y][x]) break } score *= count // To left count = 0 for (col in x-1 downTo 0) { count++ if (trees[y][col] >= trees[y][x]) break } score *= count // Down count = 0 for (row in y+1 until height) { count++ if (trees[row][x] >= trees[y][x]) break } score *= count // Up count = 0 for (row in y-1 downTo 0) { count++ if (trees[row][x] >= trees[y][x]) break } return score * count } } data class Tree(val x: Int, val y: Int, val height: Int) }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
3,795
Advent-of-Code
MIT License
src/main/kotlin/aoc2019/MonitoringStation.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2019 import komu.adventofcode.utils.Point import komu.adventofcode.utils.nonEmptyLines import kotlin.math.atan2 private typealias Angle = Double fun monitoringStation1(input: String): Int = parseAsteroidMap(input).buildAngleMap().values.map { it.size }.maxOrNull()!! fun monitoringStation2(input: String): Int { val asteroids = parseAsteroidMap(input) val (station, slopes) = parseAsteroidMap(input).buildAngleMap().entries.maxByOrNull { it.value.size }!! var count = 0 val otherAsteroids = (asteroids - station) for (angle in slopes) { val vaporized = otherAsteroids.filter { angleBetween(station, it) == angle } .minByOrNull { station.manhattanDistance(it) } if (vaporized != null) { count++ if (count == 200) return vaporized.x * 100 + vaporized.y } } error("no result") } private fun Set<Point>.buildAngleMap(): Map<Point, Set<Angle>> = associateWith { start -> (this - start).map { angleBetween(start, it) }.toSortedSet() } private fun parseAsteroidMap(input: String): Set<Point> { val asteroids = mutableSetOf<Point>() for ((y, line) in input.nonEmptyLines().withIndex()) for ((x, c) in line.withIndex()) if (c == '#') asteroids += Point(x, y) return asteroids } private fun angleBetween(from: Point, to: Point): Angle { val dx = from.x - to.x val dy = from.y - to.y val radians = atan2(dx.toDouble(), dy.toDouble()) return if (radians <= 0) -radians else Math.PI * 2 - radians }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,602
advent-of-code
MIT License
archive/k/kotlin/Rot13.kt
TheRenegadeCoder
125,427,624
false
{"BASIC": 97136, "Rust": 61107, "PHP": 58368, "Beef": 51651, "Mathematica": 43477, "C++": 37590, "Java": 33084, "Python": 30222, "JavaScript": 29447, "C": 29061, "Go": 22022, "C#": 18001, "Objective-C": 16797, "Haskell": 16781, "Kotlin": 13185, "Brainfuck": 12179, "Perl": 11260, "TypeScript": 10875, "MATLAB": 9411, "Makefile": 8577, "Assembly": 8277, "Fortran": 7187, "Scala": 7134, "Lua": 7054, "Dart": 6882, "Pascal": 6597, "Swift": 6304, "Elixir": 6151, "Shell": 6026, "Erlang": 5920, "Common Lisp": 5499, "Julia": 4624, "COBOL": 4343, "Groovy": 3998, "Ruby": 3725, "R": 3369, "Visual Basic .NET": 2790, "Clojure": 2313, "PowerShell": 2135, "CoffeeScript": 1071, "D": 1012, "Pyret": 988, "Racket": 967, "Nim": 901, "REXX": 735, "LOLCODE": 710, "Dockerfile": 705, "Ada": 632, "TeX": 607, "Boo": 576, "Vim Script": 545, "Berry": 544, "Prolog": 478, "F#": 427, "Crystal": 390, "Witcher Script": 390, "Agda": 343, "Scheme": 293, "Solidity": 191, "Zig": 145, "ColdFusion": 144, "PureScript": 140, "Eiffel": 135, "Modula-2": 130, "PicoLisp": 111, "Opa": 102, "Verilog": 102, "Ballerina": 95, "Haxe": 95, "Odin": 86, "Raku": 85, "Lex": 84, "F*": 76, "Golo": 74, "Frege": 73, "Pony": 72, "Hack": 69, "Idris": 58, "Red": 57, "V": 55, "Smalltalk": 34, "Csound": 33, "OCaml": 33, "Factor": 31, "Scilab": 31, "Wren": 30, "Batchfile": 29, "LiveScript": 28, "Shen": 27, "Chapel": 26, "Forth": 25, "Fennel": 24, "Io": 24, "Janet": 24, "GLSL": 23, "MoonScript": 22, "Nit": 22, "Elvish": 21, "Tcl": 21, "Ring": 20}
data class EncodingBounds(val lowerBound: Int, val upperBound: Int) fun encodingBoundsForCharValue(c: Char): EncodingBounds? { val lowerCaseBounds = EncodingBounds('a'.toInt(), 'z'.toInt()) val upperCaseBounds = EncodingBounds('A'.toInt(), 'Z'.toInt()) return when (c) { in 'a'..'z' -> lowerCaseBounds in 'A'..'Z' -> upperCaseBounds else -> null } } fun calculateRotatedChar(char: Char, rotation: Int, bounds: EncodingBounds): Char { val rotatedCharVal = char.toInt() + rotation val remainder = rotatedCharVal - (bounds.upperBound + 1) return (if (rotatedCharVal > bounds.upperBound) bounds.lowerBound + remainder else rotatedCharVal).toChar() } fun parseInput(args: Array<String>): String? { if (args.isEmpty()) { return null } val text = args[0] if (text.isEmpty()) { return null } return text } fun rot13Encode(text: String): String { val rotation = 13 return text.map { c -> val bounds = encodingBoundsForCharValue(c) if (bounds == null) { c.toString() } else { calculateRotatedChar(c, rotation, bounds).toString() } }.reduce { encodedText, encodedChar -> encodedText + encodedChar } } fun main(args: Array<String>) { val strToEncode = parseInput(args) if (strToEncode == null) { println("Usage: please provide a string to encrypt") } else { println(rot13Encode(strToEncode)) } }
83
BASIC
540
527
bd5f385f6b3f7881c496a4c2884d1a63b8bb5448
1,495
sample-programs
MIT License
ceria/04/src/main/kotlin/Solution.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File; lateinit var drawList: List<Int> var boards = mutableListOf<List<MutableList<Int>>>() fun main(args : Array<String>) { arrangeInput(File(args.first()).readLines()) println("Solution 1: ${solution1()}") println("Solution 2: ${solution2()}") } private fun solution1() :Int { for (x in drawList.indices) { markBoards(drawList.get(x)) // at least 5 numbers (indexes 0 - 4) have been drawn, check for bingo var bingoBoardIndex = -1 if (x > 3) { bingoBoardIndex = checkForBingo() } // if bingoBoardIndex is not -1, we have a winning board if (bingoBoardIndex != -1) { var winningBoard = boards.get(bingoBoardIndex) var sum = 0 winningBoard.map{ sum += it.filter{ it > 0 }.sum() } return sum * drawList.get(x) } } return 0 } private fun solution2() :Int { // doesn't matter what we set this to - this is just to initialize it. var lastWinningBoard = boards.get(0) var lastWinningDraw = drawList.get(0) for (x in drawList.indices) { markBoards(drawList.get(x)) // at least 5 numbers (indexes 0 - 4) have been drawn, check for bingo if (x > 3) { var bingoBoardIndex = -2 while (bingoBoardIndex != -1) { bingoBoardIndex = checkForBingo() if (bingoBoardIndex != -1) { lastWinningBoard = boards.get(bingoBoardIndex) boards.removeAt(bingoBoardIndex) lastWinningDraw = drawList.get(x) } } } } var sum = 0 lastWinningBoard.map{ sum += it.filter{ it > 0 }.sum() } return sum * lastWinningDraw } private fun arrangeInput(input: List<String>) { drawList = input.get(0).split(",").map{ it.toInt() } for (x in 2..input.size step 6) { boards.add(listOf<MutableList<Int>>( input.get(x).trim().split("\\s+".toRegex()).map{ it.toInt() }.toMutableList(), input.get(x+1).trim().split("\\s+".toRegex()).map{ it.toInt() }.toMutableList(), input.get(x+2).trim().split("\\s+".toRegex()).map{ it.toInt() }.toMutableList(), input.get(x+3).trim().split("\\s+".toRegex()).map{ it.toInt() }.toMutableList(), input.get(x+4).trim().split("\\s+".toRegex()).map{ it.toInt() }.toMutableList() )) } } private fun markBoards(num: Int) { for (board in boards) { for (row in board) { if (row.contains(num)) { // find all occurrances of the number in the row (incase it's more than once) // and mark it by replacing it with -1 for (x in row.indices) { if (row.get(x) == num) { row.set(x, -1) } } } } } } private fun checkForBingo() :Int { for (boardIdx in boards.indices) { val board = boards.get(boardIdx) // horizontal check for (row in board) { if (row.all{ it < 0 }) { return boardIdx } } // vertical check for ( x in 0..board.get(0).size - 1) { var allNegative = true for (row in board) { if (row.get(x) > 0 ){ allNegative = false break } } if (allNegative) { return boardIdx } } } return -1 }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
3,604
advent-of-code-2021
MIT License
advent-of-code-2022/src/test/kotlin/Day 8 Treetop Tree House.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test class `Day 8 Treetop Tree House` { @Test fun silverTest() { countTreesVisibleFromOutside(forest(testInput)) shouldBe 21 } @Test fun silver() { countTreesVisibleFromOutside(forest(loadResource("day8"))) shouldBe 1684 } private fun forest(testInput: String): Map<Point, Int> { return parseMap(testInput).mapValues { (k, char) -> "$char".toInt() } } /** Count trees which are higher than previous highest tree */ fun visibleFromDistance(forest: Map<Point, Int>, points: List<Point>): Set<Point> { var maxHeight = Int.MIN_VALUE val visible = mutableSetOf<Point>() for (point in points) { val height = forest.getValue(point) if (height > maxHeight) { visible.add(point) maxHeight = height } } return visible } private fun countTreesVisibleFromOutside(forest: Map<Point, Int>): Int { val max = forest.keys.last() val scans = (0..max.y).map { y -> (Point(0, y)..Point(max.x, y)) } + (0..max.y).map { y -> (Point(0, y)..Point(max.x, y)).reversed() } + (0..max.x).map { x -> (Point(x, 0)..Point(x, max.y)) } + (0..max.x).map { x -> (Point(x, 0)..Point(x, max.y)).reversed() } val visible = scans.flatMap { scan -> visibleFromDistance(forest, scan) }.toSet() return visible.size } @Test fun goldTest() { val forest = forest(testInput) forest.keys.maxOf { point -> scenicScore(forest, point) } shouldBe 8 } @Test fun gold() { val forest = forest(loadResource("day8")) forest.keys.maxOf { point -> scenicScore(forest, point) } shouldBe 486540 } @Test fun goldSmallTest() { scenicScore(forest(testInput), Point(2, 1)) shouldBe 4 scenicScore(forest(testInput), Point(2, 3)) shouldBe 8 scenicScore(forest(testInput), Point(3, 2)) shouldBe 2 } fun visibleFromTreeHouse( forest: Map<Point, Int>, points: List<Point>, treeHouseHeight: Int ): Int { var seen = 0 for (point in points) { seen++ if (forest.getValue(point) >= treeHouseHeight) { break } } return seen } fun scenicScore(forest: Map<Point, Int>, point: Point, debug: Boolean = false): Int { val max = forest.keys.last() if (point.x == 0 || point.x == max.x || point.y == 0 || point.y == max.y) return 0 val height = forest.getValue(point) val scans = listOf( (point.copy(x = 0)..point).reversed().minus(point), (point..point.copy(x = max.x)).minus(point), (point.copy(y = 0)..point).reversed().minus(point), (point..point.copy(y = max.y)).minus(point), ) if (debug) { println("----") printMap(scans.flatten().plus(point).associateWith { forest.getValue(it) }) } return scans .map { scan -> visibleFromTreeHouse(forest, scan, height) } .reduce { acc, next -> acc * next } .also { if (debug) println("res: $it") } } private val testInput = """ 30373 25512 65332 33549 35390 """.trimIndent() fun printMap(tiles: Map<Point, Int>) { printMap(tiles) { when (it) { null -> " " else -> it.toString() } } } }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
3,308
advent-of-code
MIT License
gcj/y2023/farewell_d/b_small_to_upsolve.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2023.farewell_d private fun solve(): String { val (a, b, qIn) = readLn().split(" ") val leftMost = HashMap<Long, Int>(a.length * a.length) for (i in a.indices) { var h = 0L for (j in i until a.length) { h = mix(h + a[j].code) leftMost.putIfAbsent(h, j + 1) } } val ans = List(qIn.toInt()) { val (aLen, bLen) = readInts() val bStart = b.length - bLen var h = 0L for (j in bStart until b.length) { h = mix(h + b[j].code) val pos = leftMost.get(h) ?: (a.length + 1) if (pos > aLen) { return@List j - bStart } } bLen } return ans.joinToString(" ") } fun mix(x: Long): Long { var y = x y = y xor (y ushr 33) y *= -0xae502812aa7333L // y = y xor (y ushr 33) // y *= -0x3b314601e57a13adL // y = y xor (y ushr 33) return y } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,042
competitions
The Unlicense
src/2022/Day09.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import java.io.File import java.util.* fun main() { Day09().solve() } class Day09 { val input1 = """ R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2 """.trimIndent() val input2 = """ R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20 """.trimIndent() data class Step(val direction: Char, val size: Int) data class Point(val x: Long, val y: Long) fun Point.step(direction: Char): Point { return when (direction) { 'L' -> Point(x-1, y) 'R' -> Point(x+1, y) 'U' -> Point(x, y-1) 'D' -> Point(x, y+1) else -> throw RuntimeException() } } fun Point.stepTo(p: Point): Point { val x1 = if (x > p.x) {x-1} else if (x < p.x) {x+1} else {x} val y1 = if (y > p.y) {y-1} else if (y < p.y) {y+1} else {y} if (Point(x1, y1) == p) { return this } return Point(x1, y1) } fun hash(p: Point, maxDimension: Long): Long { return p.x + maxDimension + p.y * maxDimension * 2 } fun solve() { val f = File("src/2022/inputs/day09.in") val s = Scanner(f) // val s = Scanner(input2) val steps = mutableListOf<Step>() while (s.hasNextLine()) { val line = s.nextLine().trim() val words = line.split(" ") if (!words.isEmpty()) { steps.add(Step(words[0][0], words[1].toInt())) } } val maxDimension = steps.size.toLong() + 1 val l = 10 val rope = MutableList(l){ Point(0, 0) } val visited = mutableSetOf(hash(rope.last(), maxDimension)) steps.forEach{ for (i in 0 until it.size) { rope[0] = rope[0].step(it.direction) for (i in 1 until l) { rope[i] = rope[i].stepTo(rope[i-1]) } visited.add(hash(rope.last(), maxDimension)) }} println("${visited.size}") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
2,001
advent-of-code
Apache License 2.0
src/main/java/com/booknara/problem/dp/LongestPalindromicSubsequenceKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.dp /** * 516. Longest Palindromic Subsequence (Medium) * https://leetcode.com/problems/longest-palindromic-subsequence/ */ class LongestPalindromicSubsequenceKt { // T:O(n^2), S:O(n^2) fun longestPalindromeSubseq(s: String): Int { // input check s.length >= 1 val n = s.length val dp = Array(n) {IntArray(n) { 0 } } for (i in dp.size - 1 downTo 0) { val arr = dp[i] for (j in i until arr.size) { if (i == j) { dp[i][j] = 1 continue } if (s[i] == s[j]) { dp[i][j] = dp[i + 1][j - 1] + 2 } else { dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]) } } //println(arr.joinToString()) } return dp[0][n - 1] } } /** 0 b b b a b b 0 1 2 3 3 4 b 0 1 2 2 3 b 0 1 1 3 a 0 1 1 b 0 1 */
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
863
playground
MIT License
src/day02/Day02.kt
pnavais
574,712,395
false
{"Kotlin": 54079}
package day02 import readInput fun part1(input: List<String>): Long { var totalSum = 0L for (moveDesc in input) { val points = when (moveDesc) { "A X" -> 3 + 1 // Rock vs Rock, Draw, 1 point for Rock "A Y" -> 6 + 2 // Rock vs Paper, Win, 2 point for Paper "A Z" -> 0 + 3 // Rock vs Scissors , Loss, 3 points for Scissors "B X" -> 0 + 1 // Paper vs Rock, Loss, 1 point for Rock "B Y" -> 3 + 2 // Paper vs Paper, Draw, 2 points for Paper "B Z" -> 6 + 3 // Paper vs Scissors, Win, 3 points for Scissors "C X" -> 6 + 1 // Scissors vs Rock, Win, 1 point for Rock "C Y" -> 0 + 2 // Scissors vs Paper, Loss, 2 points for Paper "C Z" -> 3 + 3 // Scissors vs Scissors, Draw, 3 points for Scissors else -> 0 } totalSum += points } return totalSum } fun part2(input: List<String>): Long { var totalSum = 0L for (moveDesc in input) { val points = when (moveDesc) { "A X" -> 0 + 3 // Rock vs Scissors, Loss, 3 points for Scissors "A Y" -> 3 + 1 // Rock vs Rock, Draw, 1 point for Rock "A Z" -> 6 + 2 // Rock vs Paper, Win, 2 points for Paper "B X" -> 0 + 1 // Paper vs Rock, Loss, 1 point for Rock "B Y" -> 3 + 2 // Paper vs Paper, Draw, 2 points for Paper "B Z" -> 6 + 3 // Paper vs Scissors, Win, 3 points for Scissors "C X" -> 0 + 2 // Scissors vs Paper, Loss, 2 points for Paper "C Y" -> 3 + 3 // Scissors vs Scissors, Draw, 3 points for Scissors "C Z" -> 6 + 1 // Scissors vs Rock, Win, 1 point for Rock else -> 0 } totalSum += points } return totalSum } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day02/Day02_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
ed5f521ef2124f84327d3f6c64fdfa0d35872095
2,025
advent-of-code-2k2
Apache License 2.0
yandex/y2021/qual/e.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package yandex.y2021.qual fun main() { val (hei, wid) = readInts() val f = List(hei) { readLn().map { it - '0' } } val countZero = f.sumOf { row -> row.count { it == 0 } } val inf = hei * wid * 3 val a = List(wid + 1) { List(hei + 1) { IntArray(wid * hei + 1) { inf } } } for (y in 0..hei) a[0][y][0] = 0 for (x in 0 until wid) { val ones = IntArray(hei + 1) for (y in 0 until hei) { ones[y + 1] = ones[y] + f[y][x] } val prev = a[x] val next = a[x + 1] for (y in 0..hei) { val prevY = prev[y] val nextY = next[y] val onesY = ones[y] for (z in x * y..wid * hei - y) { nextY[z + y] = minOf(nextY[z + y], prevY[z] + onesY) } } for (y in hei - 1 downTo 0) { val nextY = next[y] val nextY1 = next[y + 1] for (z in 0..wid * hei) { nextY[z] = minOf(nextY[z], nextY1[z]) } } } println(a[wid][0][countZero]) } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,011
competitions
The Unlicense
src/main/kotlin/g1401_1500/s1419_minimum_number_of_frogs_croaking/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1419_minimum_number_of_frogs_croaking // #Medium #String #Counting #2023_06_07_Time_210_ms_(90.91%)_Space_37.5_MB_(90.91%) class Solution { fun minNumberOfFrogs(s: String): Int { var ans = 0 val f = IntArray(26) for (i in 0 until s.length) { f[s[i].code - 'a'.code]++ if (s[i] == 'k' && checkEnough(f)) { reduce(f) } if (!isValid(f)) { return -1 } ans = Math.max(ans, getMax(f)) } return if (isEmpty(f)) ans else -1 } private fun checkEnough(f: IntArray): Boolean { return f['c'.code - 'a'.code] > 0 && f['r'.code - 'a'.code] > 0 && f['o'.code - 'a'.code] > 0 && f[0] > 0 && f['k'.code - 'a'.code] > 0 } fun reduce(f: IntArray) { f['c'.code - 'a'.code]-- f['r'.code - 'a'.code]-- f['o'.code - 'a'.code]-- f[0]-- f['k'.code - 'a'.code]-- } private fun getMax(f: IntArray): Int { var max = 0 for (v in f) { max = Math.max(max, v) } return max } private fun isEmpty(f: IntArray): Boolean { for (v in f) { if (v > 0) { return false } } return true } private fun isValid(f: IntArray): Boolean { if (f['r'.code - 'a'.code] > f['c'.code - 'a'.code]) { return false } if (f['o'.code - 'a'.code] > f['r'.code - 'a'.code]) { return false } return if (f[0] > f['o'.code - 'a'.code]) { false } else f['k'.code - 'a'.code] <= f[0] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,693
LeetCode-in-Kotlin
MIT License
src/Day03.kt
llama-0
574,081,845
false
{"Kotlin": 6422}
fun main() { fun fillCase(start: Int, end: Int, char: Char): Map<Char, Int> { val case = mutableMapOf<Char, Int>() for (i in start..end) { case[char + i - start] = i } return case } val lowercase = fillCase(1, 26, 'a') val uppercase = fillCase(27, 52, 'A') val case = lowercase + uppercase fun part1(input: List<String>): Int { var res = 0 for (i in input) { val middle = i.length / 2 val first = i.slice(0 until middle).toList() val second = i.slice(middle until i.length).toSet() val elem = first.intersect(second).single() res += case[elem] ?: 0 } return res } fun part2(input: List<String>): Int { var res = 0 var i = 0 while (i < input.size - 2) { // todo: check for end index if needed val first = input[i].toList() val second = input[i + 1].toSet() val third = input[i + 2].toSet() val elemsFirstSecond = first.intersect(second) val elemsSecondThird = second.intersect(third) val elem = elemsFirstSecond.intersect(elemsSecondThird).single() res += case[elem] ?: 0 i += 3 } return res } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day03_test") // println(testInput) // check(part1(testInput) == 157) // check(part2(testInput) == 70) val input = readInput("Day03") // val input = readInput("Day03_test") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a3a9a07be54a764a707ab25332a9f324cb84ac2a
1,669
AoC-2022
Apache License 2.0
src/Day01.kt
JonasDBB
573,382,821
false
{"Kotlin": 17550}
private fun splitListOnEmpty(lst: List<Int?>): List<List<Int>> { val ret: MutableList<List<Int>> = mutableListOf() val sublist: MutableList<Int> = mutableListOf() for (i in lst.indices) { if (lst[i] == null) { if (sublist.isNotEmpty()) ret.add(sublist.toList()) sublist.clear() continue } sublist.add(lst[i]!!) } if (sublist.isNotEmpty()) ret.add(sublist.toList()) return ret } private fun part1(nrs: List<List<Int>>) { println(nrs.maxOfOrNull { it.sum() } ?: 0) } private fun part2(nrs: List<List<Int>>) { val mutNrs: MutableList<Int> = nrs.map { it.sum() }.toMutableList() mutNrs.sort() println(mutNrs.takeLast(3).sum()) } fun main() { val listOfIntLists = splitListOnEmpty(readInput("01").map { it.toIntOrNull() }) println("part 1") part1(listOfIntLists) println("part 2") part2(listOfIntLists) }
0
Kotlin
0
0
199303ae86f294bdcb2f50b73e0f33dca3a3ac0a
923
AoC2022
Apache License 2.0
Kotlin/7 kyu Complementary DNA.kt
MechaArms
508,384,440
false
{"Kotlin": 22917, "Python": 18312}
/* Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms. If you want to know more: http://en.wikipedia.org/wiki/DNA In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". Your function receives one side of the DNA (string, except for Haskell); you need to return the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell). More similar exercise are found here: http://rosalind.info/problems/list-view/ (source) Example: (input --> output) "ATTGC" --> "TAACG" "GTAT" --> "CATA" */ //My Solution //=========== package dna fun makeComplement(dna : String) : String { val arr = dna.split("") var comp: String = "" for (i in arr){ when (i) { "A" -> comp = comp + "T" "C" -> comp = comp + "G" "T" -> comp = comp + "A" "G" -> comp = comp + "C" } } return comp } //Best Solution //============= package dna fun makeComplement(dna: String) = dna.map { when(it) { 'A' -> 'T' 'T' -> 'A' 'C' -> 'G' 'G' -> 'C' else -> it } }.joinToString("")
0
Kotlin
0
1
b23611677c5e2fe0f7e813ad2cfa21026b8ac6d3
1,231
My-CodeWars-Solutions
MIT License
src/main/kotlin/year2022/Day07.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2022 class Day07 { class Directory(val parent: Directory?) { var totalSize: Int = 0 val childDirs: MutableMap<String, Directory> = mutableMapOf() fun find(predicate: (Directory) -> Boolean): List<Directory> = buildList { if (predicate(this@Directory)) { add(this@Directory) } addAll(childDirs.values.flatMap { dir -> dir.find(predicate) }) } fun updateTotalSizes(): Int { totalSize += childDirs.values.sumOf { it.updateTotalSizes() } return totalSize } } private fun buildGraph(input: String) = Directory(null).apply { var current: Directory = this input.lines().forEach { line -> current = when { line == "$ cd /" -> this line == "$ ls" -> current line == "$ cd .." -> current.parent!! line.startsWith("$ cd ") -> current.childDirs[line.substringAfter("$ cd ")]!! line.startsWith("dir ") -> current.apply { childDirs[line.substringAfter("dir ")] = Directory(current) } line[0].isDigit() -> current.apply { totalSize += line.split(" ")[0].toInt() } else -> throw RuntimeException("Can't parse: $line") } } updateTotalSizes() } fun part1(input: String): Int = buildGraph(input) .find { it.totalSize <= 100000 } .sumOf { it.totalSize } fun part2(input: String): Int { val root = buildGraph(input) val excess = 30000000 - (70000000 - root.totalSize) return root.find { it.totalSize >= excess }.minOf { it.totalSize } } }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
1,734
aoc-2022
Apache License 2.0
src/main/kotlin/g1801_1900/s1870_minimum_speed_to_arrive_on_time/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1870_minimum_speed_to_arrive_on_time // #Medium #Array #Binary_Search #Binary_Search_II_Day_6 // #2023_06_22_Time_628_ms_(50.00%)_Space_51.5_MB_(100.00%) class Solution { fun minSpeedOnTime(dist: IntArray, hour: Double): Int { val n = dist.size return fmin(dist, n, hour) } private fun check(dist: IntArray, n: Int, h: Double, spe: Int): Boolean { var cost = 0.0 for (i in 0 until n - 1) { // same as ceil(doubleTime/doubleSpeed) cost += ((dist[i] - 1) / spe + 1).toDouble() } cost += dist[n - 1].toDouble() / spe.toDouble() return cost <= h } private fun fmin(dist: IntArray, n: Int, h: Double): Int { if (h + 1 <= n) { return -1 } val max = fmax(dist) * 100 var lo = 1 var hi = max while (lo < hi) { val mid = (lo + hi) / 2 // speed of mid is possible, move to left side if (check(dist, n, h, mid)) { hi = mid } else { // need higher speed, move to right side lo = mid + 1 } } return lo } private fun fmax(arr: IntArray): Int { var res = arr[0] for (num in arr) { res = Math.max(res, num) } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,373
LeetCode-in-Kotlin
MIT License
src/main/java/challenges/leetcode/LongestCommonPrefix.kt
ShabanKamell
342,007,920
false
null
package challenges.leetcode import java.util.* /** Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Example 2: Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lower-case English letters. */ object LongestCommonPrefix { private fun longestCommonPrefix(strs: Array<String>): String { val size = strs.size var result = "" for ((i, str) in strs.withIndex()) { val prefix = StringBuilder() val current = str.toCharArray() if (i + 1 >= size) break val next = strs[i + 1].toCharArray() if (current.first() != next.first()) continue for (j in current.indices) { if (j >= next.size) break if (current[j] != next[j]) continue prefix.append(current[j]) } if (result.isEmpty()) { result = prefix.toString() continue } if (prefix.isNotEmpty() && prefix.length < result.length) { result = prefix.toString() } } return result } private fun longestCommonPrefix2(strs: Array<String>): String { if (strs.isEmpty()) return "" var prefix = strs[0] for (i in 1 until strs.size) { while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length - 1) if (prefix.isEmpty()) return "" } } return prefix } @JvmStatic fun main(args: Array<String>) { var strs = arrayOf("flower", "flow", "flight") println("${strs.joinToString { it }}: ${longestCommonPrefix(strs)}") println("${strs.joinToString { it }}: ${longestCommonPrefix2(strs)}") strs = arrayOf("dog", "racecar", "car") println("${strs.joinToString { it }}: ${longestCommonPrefix(strs)}") println("${strs.joinToString { it }}: ${longestCommonPrefix2(strs)}") } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,282
CodingChallenges
Apache License 2.0
2019/kotlin/day3/day3.kt
Deph0
225,142,801
false
null
package aoc.day.three import java.io.File import kotlin.random.Random import java.awt.* import java.awt.geom.* import javax.swing.* data class WirePosition( var x: Int = 0, var y: Int = 0, var walked: Int = 0 ) data class WireData( val direction: String, val steps: Int ) data class Wire( var actions: List<WireData>, var path: List<WirePosition> = listOf(), var position: WirePosition = WirePosition() ) fun manhattan(ax: Int, ay: Int, bx: Int, by: Int): Int { return Math.abs(ax - bx) + Math.abs(ay - by) } fun WireIntersects(a: Wire, b: Wire): List<WirePosition> { // Get intersection of wires and calculate Manhattan distance of each and get the minimum distance from origin val apath = a.path.map { WirePosition(it.x, it.y) } // Remove Walked property, val bpath = b.path.map { WirePosition(it.x, it.y) } // In order to be able to use intersect return apath.intersect(bpath).toList() } fun WireSteps(a: Wire, b: Wire): Int? { var totSteps = listOf<Int>() var intersects = WireIntersects(a, b) for (cross in intersects) { var w1steps = 0 var w2steps = 0 for (pos in a.path) { if (pos.x == cross.x && pos.y==cross.y) { w1steps = pos.walked } } for (pos in b.path) { if (pos.x == cross.x && pos.y==cross.y) { w2steps = pos.walked } } totSteps += ( w1steps + w2steps ) } // println("totSteps: ${totSteps.min()}") return totSteps.min() } fun WireDistance(a: Wire, b: Wire): Int? { var intersects = WireIntersects(a, b) println("${intersects.size} intersection found!") val dist = intersects.map { println("intersection: (${it.x}, ${it.y})") manhattan(0, 0, it.x, it.y) } return dist.min() } fun WalkWire(w: Wire): Wire { val wire = w.copy() wire.actions.forEach { action -> (0..action.steps-1).forEach { when (action.direction) { "R" -> wire.position.x += 1 "L" -> wire.position.x -= 1 "U" -> wire.position.y -= 1 "D" -> wire.position.y += 1 } wire.position.walked += 1 wire.path += wire.position.copy() } } return wire } fun main(args: Array<String>) { val lineList = File("./input_2019-3.txt").readLines().map { it.split(",") } var wire1 = lineList.get(0) // distance: 273 var wire2 = lineList.get(1) // steps: 15622 // val wire1 = listOf("R8","U5","L5","D3") // val wire2 = listOf("U7","R6","D4","L4") // distance: 6, steps: 30 // val wire1 = listOf("R75","D30","R83","U83","L12","D49","R71","U7","L72") // val wire2 = listOf("U62","R66","U55","R34","D71","R55","D58","R83") // distance: 159, steps: 610 // val wire1 = listOf("R98","U47","R26","D63","R33","U87","L62","D20","R33","U53","R51") // val wire2 = listOf("U98","R91","D20","R16","D67","R40","U7","R15","U6","R7") // distance: 135, steps: 410 // Parse raw data into a data structure var wires = listOf(wire1, wire2) .map { wire -> Wire( wire.map { action -> WireData( action.take(1) , action.drop(1).toInt() ) }) } // Run val walkedwires = wires.map { WalkWire(it) } println("Wire Distance:" + WireDistance(walkedwires[0],walkedwires[1])) println("Wire Steos:" + WireSteps(walkedwires[0], walkedwires[1])) // Open gui window for drawing // EventQueue.invokeLater( { // val frame = Window("Advent Of Code 2019 - Day 3") // frame.setWires( walkedwires.toMutableList() ) // frame.isVisible = true // }) } // Create a window for the Canvas class Window(title: String) : JFrame() { var wires: ArrayList<Wire> var canvas: MyCanvas init { wires = arrayListOf<Wire>() setTitle(title) defaultCloseOperation = JFrame.EXIT_ON_CLOSE // setSize(800, 800) setSize(400, 400) setLocationRelativeTo(null) canvas = MyCanvas() add(canvas) } fun setWires(wireList: MutableList<Wire>) { wires.clear() wires.addAll(wireList) canvas.wires = wires } } class MyCanvas(): Canvas() { var wires: ArrayList<Wire> = arrayListOf<Wire>() fun paintWires(gfx: Graphics) { wires.forEach { wire -> gfx.color = Color(Random.nextFloat(), Random.nextFloat(), Random.nextFloat()) wire.path.forEach { p -> gfx.drawLine(p.x, p.y, p.x, p.y) // gfx.drawString("${p.x.toInt()},${p.y.toInt()}", p.x, p.y) } } } fun painIntersections(gfx: Graphics) { var s = 1f gfx.color = Color.WHITE gfx.drawString("0, 0", (0/s).toInt(), (0/s).toInt()) // Draw Origin Position WireIntersects(wires[0], wires[1]).forEach { p -> gfx.color = Color(Random.nextFloat(), Random.nextFloat(), Random.nextFloat()) gfx.drawString("${p.x.toInt()},${p.y.toInt()}", (p.x/s).toInt(), (p.y/s).toInt()) } } override fun paint(gfx: Graphics) { gfx.color = Color.BLACK gfx.fillRect(0,0,400,400) gfx.translate(100,270) paintWires(gfx) painIntersections(gfx) } }
0
Kotlin
0
0
42a4fce4526182737d9661fae66c011f0948e481
5,342
adventofcode
MIT License
archive/2022/Day16_dijkstra.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import java.util.* import kotlin.time.ExperimentalTime import kotlin.time.measureTime private const val EXPECTED_1 = 1651 private const val EXPECTED_2 = 1707 /** * Reworked solution: use Dijkstra's to find the highest value path through the state space * for part1. * * Actually a bit slower than the dp solution. */ private class Day16(isTest: Boolean) : Solver(isTest) { private val edges = mutableMapOf<String, List<String>>() private val num = mutableMapOf<String, Int>() private val flowList = mutableListOf<Int>() init { readAsLines().withIndex().forEach { (index, line) -> val parts = line.split(" ") val key = parts[1] flowList.add(parts[4].removeSurrounding("rate=", ";").toInt()) val parts2 = line.split(", ") edges[key] = parts2.map { it.substringAfterLast(' ', it) } num[key] = index } } data class State(val open: Long, val loc: String, val timeLeft: Int) // Return the best score from start, and the map of end states fun dijkstra(start: State): Pair<Int, Map<State, Int>> { val best = mutableMapOf<State, Int>() val queue = TreeSet(compareBy<State>({ best[it] }, { it.timeLeft }, { it.loc }, { it.open }).reversed()) var result = 0 best[start] = 0 queue.add(start) while (!queue.isEmpty()) { val state = queue.pollFirst()!! val score = best[state]!! result = maxOf(result, score) if (state.timeLeft == 0) { // Special case: store the best score at any location in state 'any' so we // can look it up fast after partitioning best.compute(state.copy(loc = "any")) { key, prev -> maxOf(score, prev ?: 0) } continue } val locNum = num[state.loc]!! if (flowList[locNum] > 0 && (state.open and (1L shl locNum)) == 0L) { val newScore = score + (state.timeLeft - 1) * flowList[locNum]; val newState = state.copy(open = state.open or (1L shl locNum), timeLeft = state.timeLeft - 1) if (newScore > (best[newState] ?: -1)) { queue.remove(newState) best[newState] = newScore queue.add(newState) } } for (dest in edges[state.loc]!!) { val newState = state.copy(loc = dest, timeLeft = state.timeLeft - 1) if (score > (best[newState] ?: -1)) { queue.remove(newState) best[newState] = score queue.add(newState) } } } return result to best } fun part1() = dijkstra(State(0, "AA", 30)).first fun partition(startIndex: Int, assignment1: Long, assignment2: Long, best: Map<State, Int>): Int { var index = startIndex while (index < flowList.size && flowList[index] == 0) index++ return if (index < flowList.size) { // This valve gets opened either by user1, by user2 or by neither maxOf( partition(index + 1, assignment1 or (1L shl index), assignment2, best), partition(index + 1, assignment1, assignment2 or (1L shl index), best), partition(index + 1, assignment1, assignment2, best) ) } else { // Evaluate: just look up what score we can get by opening the valves as assigned (best[State(assignment1, "any", 0)] ?: 0) + (best[State(assignment2, "any", 0)] ?: 0) } } fun part2(): Any { val bestMap = dijkstra(State(0, "AA", 26)).second return partition(0, 0L, 0L, bestMap) } } fun main() { val testInstance = Day16(true) val instance = Day16(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
4,221
advent-of-code-2022
Apache License 2.0
src/Day16.kt
greg-burgoon
573,074,283
false
{"Kotlin": 120556}
fun main() { class Node(name: String, flowRate: Int, adjacentValves: MutableList<Node> = mutableListOf<Node>()) { val name = name val flowRate = flowRate var adjacentValves = adjacentValves } data class State(val currentNode: String, val openValves: List<String>, var accumulatedPressure: Long, val timeRemaining: Long, val previousState: State?) { } data class ElephantState(val elephantNode: String, val myState: State) { } fun initMap(input: String): MutableMap<String, Node> { val valveDescriptions = input.split("\n") var nodeMap = mutableMapOf<String, Node>() val valveRegex = "Valve [A-Z][A-Z]".toRegex() val flowRateRegex = "[0-9]+".toRegex() valveDescriptions.forEach { val valveName = valveRegex.find(it)?.value?.takeLast(2)!! val flowRate = flowRateRegex.find(it)?.value!! nodeMap.put(valveName, Node(valveName, flowRate.toInt())) } valveDescriptions.forEach { val valveName = valveRegex.find(it)?.value?.takeLast(2)!! val adjacentValves = it.split(",").map { token -> nodeMap.get(token.takeLast(2))!! } nodeMap.get(valveName)?.adjacentValves?.addAll(adjacentValves)!! } return nodeMap } fun findEndStatesForSinglePerson(nodeMap: MutableMap<String, Node>, time: Long): MutableList<State> { val startState = State("AA", mutableListOf<String>(), 0L, time, null) var stack = ArrayDeque<State>() stack.add(startState) var maxMap = mutableMapOf<String, Long>() var endStates = mutableListOf<State>() while (stack.isNotEmpty()) { var currentState = stack.removeFirst() if (currentState.timeRemaining <= 0L) { endStates.add(currentState) continue } var additionalPressure = currentState.openValves.sumOf { nodeMap?.get(it)?.flowRate!! } var potentialMax = currentState.accumulatedPressure + additionalPressure if (potentialMax >= maxMap?.getOrDefault(currentState.currentNode, 0L)!!) { maxMap.put(currentState.currentNode, potentialMax) if (nodeMap.get(currentState.currentNode)?.flowRate!! > 0 && !currentState.openValves.contains( currentState.currentNode ) ) { var openValves = currentState.openValves.toMutableList() openValves.add(currentState.currentNode) var newState = State( currentState.currentNode, openValves, potentialMax, (currentState.timeRemaining - 1), currentState ) stack.add(newState) } nodeMap?.get(currentState.currentNode)?.adjacentValves?.forEach { var openValves = currentState.openValves.toMutableList() var newState = State( it.name, openValves, potentialMax, (currentState.timeRemaining - 1), currentState ) stack.add(newState) } } } return endStates } fun part1(input: String): Long { var nodeMap = initMap(input) return findEndStatesForSinglePerson(nodeMap, 30L).maxOf { it.accumulatedPressure } } fun part2(input: String): Long { var nodeMap = initMap(input) var endStatesSingle = findEndStatesForSinglePerson(nodeMap, 26L) var successPaths = mutableListOf<ArrayDeque<State>>() for(state in endStatesSingle) { var successPath = ArrayDeque<State>() var currentState = state successPath.add(currentState) while (currentState.previousState != null) { currentState = currentState?.previousState!! successPath.addFirst(currentState) } successPaths.add(successPath) } var maxMap = mutableMapOf<String, Long>() var endStates = mutableListOf<ElephantState>() for (path in successPaths) { var stack = ArrayDeque<ElephantState>() var startState = path?.removeFirst()!! var startElephantState = ElephantState(startState.currentNode, startState) stack.add(startElephantState) var nextState = path?.removeFirst()!! while (stack.isNotEmpty()) { var currentState = stack.removeFirst() if (currentState.myState.timeRemaining <= 0L) { endStates.add(currentState) continue } if (currentState.myState.timeRemaining == nextState.timeRemaining) { nextState = path?.removeFirst()!! } var additionalPressure = currentState.myState.openValves.sumOf { nodeMap?.get(it)?.flowRate!! } var potentialMax = currentState.myState.accumulatedPressure + additionalPressure if (potentialMax >= maxMap?.getOrDefault(currentState.elephantNode, 0L)!!) { maxMap.put(currentState.elephantNode, potentialMax) if (nodeMap.get(currentState.elephantNode)?.flowRate!! > 0 && !currentState.myState.openValves.contains( currentState.elephantNode ) && currentState.elephantNode != currentState.myState.currentNode ) { var openValves = nextState.openValves.toMutableList() openValves.add(currentState.elephantNode) nextState.accumulatedPressure = potentialMax var newState = ElephantState( currentState.elephantNode, nextState ) stack.add(newState) } nodeMap?.get(currentState.elephantNode)?.adjacentValves?.forEach { nextState.accumulatedPressure = potentialMax var newState = ElephantState( it.name, nextState ) stack.add(newState) } } } } return 0 // // var bestStates = endStates // return bestStates.maxOf { it.accumulatedPressure } //dopart 2 // var nodeMap = initMap(input) // // val startState = ElephantState("AA", "AA", mutableListOf<String>(), 0L, 26L) // // var stack = ArrayDeque<ElephantState>() // stack.add(startState) // // var maxMap = mutableMapOf<String, Long>() // // var endStates = mutableListOf<ElephantState>() // while (stack.isNotEmpty()) { // var currentState = stack.removeFirst() // if (currentState.timeRemaining <= 0L) { // endStates.add(currentState) // continue // } // var additionalPressure = currentState.openValves.sumOf { nodeMap?.get(it)?.flowRate!! } // var potentialMax = currentState.accumulatedPressure + additionalPressure // if (potentialMax >= maxMap?.getOrDefault(currentState.currentNode, 0L)!!) { // maxMap.put(currentState.currentNode, potentialMax) // //we both open a valve // if (nodeMap.get(currentState.currentNode)?.flowRate!! > 0 && // !currentState.openValves.contains(currentState.currentNode) // && nodeMap.get(currentState.elephantNode)?.flowRate!! > 0 && // !currentState.openValves.contains(currentState.elephantNode) // && !currentState.currentNode.equals(currentState.elephantNode)) { // var openValves = currentState.openValves.toMutableList() // openValves.add(currentState.currentNode) // openValves.add(currentState.elephantNode) // var newState = ElephantState(currentState.currentNode, currentState.elephantNode, openValves, potentialMax, (currentState.timeRemaining-1)) // stack.add(newState) // } // // //Only I open valve // if (nodeMap.get(currentState.currentNode)?.flowRate!! > 0 && // !currentState.openValves.contains(currentState.currentNode)) { // var openValves = currentState.openValves.toMutableList() // openValves.add(currentState.currentNode) // // nodeMap?.get(currentState.elephantNode)?.adjacentValves?.forEach { // var newState = ElephantState( // currentState.currentNode, // it.name, // openValves, // potentialMax, // (currentState.timeRemaining - 1) // ) // stack.add(newState) // } // } // // // // //elephant opens valve // if (nodeMap.get(currentState.elephantNode)?.flowRate!! > 0 && // !currentState.openValves.contains(currentState.elephantNode)) { // var openValves = currentState.openValves.toMutableList() // openValves.add(currentState.elephantNode) // // nodeMap?.get(currentState.currentNode)?.adjacentValves?.forEach { // var newState = ElephantState( // it.name, // currentState.elephantNode, // openValves, // potentialMax, // (currentState.timeRemaining - 1) // ) // stack.add(newState) // } // } // // //we both move // nodeMap?.get(currentState.currentNode)?.adjacentValves?.forEach { adjacentNode -> // var openValves = currentState.openValves.toMutableList() // nodeMap?.get(currentState.elephantNode)?.adjacentValves?.forEach { elephantAdjacentNode -> // var newState = ElephantState( // adjacentNode.name, // elephantAdjacentNode.name, // openValves, // potentialMax, // (currentState.timeRemaining - 1) // ) // stack.add(newState) // } // } // } // } // return endStates.maxOf { it.accumulatedPressure } } val testInput = readInput("Day16_test") val output = part1(testInput) check(output == 1651L) val outputTwo = part2(testInput) check(outputTwo == 1707L) val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
11,422
aoc-kotlin
Apache License 2.0
src/day04/Day04.kt
EdwinChang24
572,839,052
false
{"Kotlin": 20838}
package day04 import readInput fun main() { part1() part2() } fun part1() { val input = readInput(4) var total = 0 for (line in input) { val ranges = line.split(',') val r1 = ranges[0].split('-')[0].toInt() to ranges[0].split('-')[1].toInt() val r2 = ranges[1].split('-')[0].toInt() to ranges[1].split('-')[1].toInt() if ((r1.first >= r2.first && r1.second <= r2.second) || (r2.first >= r1.first && r2.second <= r1.second)) { total++ } } println(total) } fun part2() { val input = readInput(4) var total = 0 for (line in input) { val ranges = line.split(',') val r1 = ranges[0].split('-')[0].toInt() to ranges[0].split('-')[1].toInt() val r2 = ranges[1].split('-')[0].toInt() to ranges[1].split('-')[1].toInt() if (r1.first in r2.first..r2.second || r1.second in r2.first..r2.second || r2.first in r1.first..r1.second || r2.second in r1.first..r1.second ) { total++ } } println(total) }
0
Kotlin
0
0
e9e187dff7f5aa342eb207dc2473610dd001add3
1,087
advent-of-code-2022
Apache License 2.0
src/main/Kotlin/fca/Concept.kt
Jianwei-Wu-1
467,248,073
false
{"Kotlin": 133590, "Java": 595}
package edu.udel.fca data class Concept<O, A>( val objects: Set<O>, val attributes: Set<A>, private val context: Context<O, A> ) : Comparable<Concept<O, A>> { val successors: Set<Concept<O, A>> by lazy { context.successors(this).toSet() } val predecessors: Set<Concept<O, A>> by lazy { context.predecessors(this).toSet() } val sparseObjects: Set<O> by lazy { objects - successors.flatMap { it.objects } } val sparseAttributes: Set<A> by lazy { attributes - predecessors.flatMap { it.attributes } } val uniqueAttributes: Set<A> by lazy { sparseAttributes.takeIf { it.isNotEmpty() } ?: successors.flatMap { it.uniqueAttributes }.toSet() //here predecessors -> successors } //Compare and compute val support: Double by lazy { objects.size.toDouble() / context.objects.size } override fun compareTo(other: Concept<O, A>): Int { return when { other.objects.containsAll(objects) -> -1 objects.containsAll(other.objects) -> 1 else -> 0 } } override fun toString(): String = "Concept(objects=$objects, attributes=$attributes)" companion object { fun weightedSimilarity( weight: Double, similarity: (Set<*>, Set<*>) -> Double ): (Concept<*, *>, Concept<*, *>) -> Double = fun(c1: Concept<*, *>, c2: Concept<*, *>): Double { return weight * similarity(c1.objects, c2.objects) + (1 - weight) * similarity(c1.attributes, c2.attributes) } } }
0
Kotlin
0
0
fc9d1658fcbd03f33a66ee279efe2f057c69b6dc
1,598
NameGenerationPlugin
The Unlicense
src/main/kotlin/g1301_1400/s1312_minimum_insertion_steps_to_make_a_string_palindrome/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1312_minimum_insertion_steps_to_make_a_string_palindrome // #Hard #String #Dynamic_Programming #2023_06_05_Time_186_ms_(67.70%)_Space_37.6_MB_(26.09%) class Solution { private fun longestPalindrome(a: String, b: String, n: Int): Int { val dp = Array(n + 1) { IntArray(n + 1) } for (i in 0 until n + 1) { for (j in 0 until n + 1) { if (i == 0 || j == 0) { dp[i][j] = 0 } else if (a[i - 1] == b[j - 1]) { dp[i][j] = 1 + dp[i - 1][j - 1] } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) } } } return dp[n][n] } fun minInsertions(s: String): Int { val n = s.length if (n < 2) { return 0 } val rs = StringBuilder(s).reverse().toString() val l = longestPalindrome(s, rs, n) return n - l } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
972
LeetCode-in-Kotlin
MIT License
jvm/src/main/kotlin/io/prfxn/aoc2021/day24.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Arithmetic Logic Unit (https://adventofcode.com/2021/day/24) package io.prfxn.aoc2021 import kotlin.math.absoluteValue import kotlin.math.log fun main() { fun parseInstruction(str: String) = str.split(" ").let { if (it.size == 3) Triple(it[0], it[1], it[2]) else Triple(it[0], it[1], "") } fun processInstruction(state: Map<String, Int>, instruction: Triple<String, String, String>, read: () -> Int): Map<String, Int> = instruction.let { (cmd, dest, op2) -> val a = state[dest] ?: 0 val b = op2.toIntOrNull() ?: state[op2] ?: 0 state + ( dest to when (cmd) { "inp" -> read() "add" -> a + b "mul" -> a * b "div" -> a / b "mod" -> a % b "eql" -> if (a == b) 1 else 0 else -> fail() } ) } fun processInstructions(state: Map<String, Int>, instructions: List<Triple<String, String, String>>, read: () -> Int): Map<String, Int> = instructions.fold(state) { s, i -> processInstruction(s, i, read) } fun numBase26Digits(decimal: Int) = decimal.absoluteValue.takeIf { it != 0 }?.let { log(it.toFloat(), 26F).toCeilInt() } ?: 0 // see explanation below fun nextValidStateOrNull(state: Map<String, Int>, chunk: List<Triple<String, String, String>>, input: Int): Map<String, Int>? = processInstructions(state, chunk) { input }.takeIf { newState -> numBase26Digits(newState["z"]!!) - numBase26Digits(state["z"]!!) == if (chunk[4].third == "1") 1 else -1 } fun findModelNumber(instructions: List<Triple<String, String, String>>, findMax: Boolean = true): String = instructions.chunked(instructions.size / 14).let { chunks -> var last: Int? = -1 val stack = mutableListOf<Pair<Int, Map<String, Int>>>() var state = mapOf("z" to 0) while (stack.size < 14) { last = if (last == null && stack.isNotEmpty()) { stack.removeLast().let { (last, lastState) -> val chunk = chunks[stack.size] (if (findMax) (last - 1 downTo 1) else (last + 1 .. 9)) .find { i -> nextValidStateOrNull(lastState, chunk, i)?.also { newState -> stack.add(i to lastState) state = newState } != null } } } else { val chunk = chunks[stack.size] (if (findMax) (9 downTo 1) else (1 .. 9)) .find { i -> nextValidStateOrNull(state, chunk, i)?.also { newState -> stack.add(i to state.toMap()) state = newState } != null } } } return stack.map { it.first }.joinToString("") } val instructions = textResourceReader("input/24.txt").useLines { it.map(::parseInstruction).toList() } .apply { dump(this); println() } // answer 1 println(findModelNumber(instructions)) // answer 2 println(findModelNumber(instructions, findMax = false)) } /** output 1: inp w 2: mul x 0 3: add x z 4: mod x 26 5: div z 1, 1, 1, 26, 1, 26, 1, 1, 1, 26, 26, 26, 26, 26 6: add x 13, 11, 15, -11, 14, 0, 12, 12, 14, -6, -10, -12, -3, -5 7: eql x w 8: eql x 0 9: mul y 0 10: add y 25 11: mul y x 12: add y 1 13: mul z y 14: mul y 0 15: add y w 16: add y 13, 10, 5, 14, 5, 15, 4, 11, 1, 15, 12, 8, 14, 9 17: mul y x 18: add z y 12934998949199 11711691612189 */ fun dump(instructions: List<Triple<String, String, String>>) { val chunkSize = instructions.size / 14 instructions .mapIndexed { i, ins -> i % chunkSize to ins } .groupBy({ (pos, _) -> pos }) { (_, ins) -> ins } .forEach { (i, posList) -> val (a, b) = posList.first() val c = posList.map { it.third }.let { val s = it.toSet() when { s.isEmpty() -> "" s.size == 1 -> " ${it.first()}" else -> it.map { n -> "%3s".format(n) }.joinToString(", ") } } println("%2d: $a $b $c".format(i + 1)) } } /* - The instructions can be split into 14 similar chunks, each made up of 18 instructions - Most instructions are identical across each chunk, except instructions in positions 5, 6 and 16, where the values of the second operand differ across chunks. Let's call these parameters a, b and c respectively - Upon studying the instructions and working out the state of vars as below, 1. x, y & w reset for every new chunk processing. x & y are set to 0 while w holds the input for the current chunk. The value of z from one chunk's processing feeds into the processing for the next 2. Every chunk processing results in a new value of z, related to the previous one as - new_z = (z % 26 + b == w) ? z/a : (26 * z/a + w + c) - The condition (z % 26 + b == w) cannot be satisfied when a = 1, as the corresponding values of b are all above 9 (the max possible value of w). For chunks where a = 26, it's possible to statisfy this condition though, by choosing the right inputs leading upto such chunks. When the condition is satisfied, z gets divided by 26, but when it's not, z gets multiplied by 26 and a value less than 26 (based on values in input and c) is added to it. This is equivalent to shifting base26 digits of z left or right respectively - There's an even split of 1s and 26s for "a" across the chunks. If we ensure shifting z right for all chunks with a = 26 we'd have shifted it left and right an equal number of times bringing it back to 0, if it started with 0 1: inp w 2: mul x 0 3: add x z x = z 4: mod x 26 x = z % 26 5: div z 1, 1, 1, 26, 1, 26, 1, 1, 1, 26, 26, 26, 26, 26 z = z/a 6: add x 13, 11, 15, -11, 14, 0, 12, 12, 14, -6, -10, -12, -3, -5 x = z % 26 + b 7: eql x w 8: eql x 0 x = (z % 26 + b == w) ? 0 : 1 9: mul y 0 10: add y 25 y = 25 11: mul y x 12: add y 1 y = (z % 26 + b == w) ? 1 : 26 13: mul z y z = (z % 26 + b == w) ? z/a : 26 * z/a 14: mul y 0 15: add y w 16: add y 13, 10, 5, 14, 5, 15, 4, 11, 1, 15, 12, 8, 14, 9 y = w + c 17: mul y x y = (z % 26 + b == w) ? 0 : w + c 18: add z y z = ((z % 26 + b == w) ? z/a : 26 * z/a) + ((z % 26 + b == w) ? 0 : (w + c)) z = (z % 26 + b == w) ? z/a : (26 * z/a + w + c) */
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
7,251
aoc2021
MIT License
src/day5/Day05.kt
armanaaquib
572,849,507
false
{"Kotlin": 34114}
package day5 import readInput fun main() { fun parseInput(input: List<String>) = input.map { val line = it.split(" ") listOf( line[1].toInt(), line[3].toInt(), line[5].toInt() ) } val testStacks = listOf( mutableListOf(), mutableListOf('Z', 'N'), mutableListOf('M', 'C', 'D'), mutableListOf('P') ) val stacks = listOf( mutableListOf(), mutableListOf('S', 'T', 'H', 'F', 'W', 'R'), mutableListOf('S', 'G', 'D', 'Q', 'W'), mutableListOf('B', 'T', 'W'), mutableListOf('D', 'R', 'W', 'T', 'N', 'Q', 'Z', 'J'), mutableListOf('F', 'B', 'H', 'G', 'L', 'V', 'T', 'Z'), mutableListOf('L', 'P', 'T', 'C', 'V', 'B', 'S', 'G'), mutableListOf('Z', 'B', 'R', 'T', 'W', 'G', 'P'), mutableListOf('N', 'G', 'M', 'T', 'C', 'J', 'R'), mutableListOf('L', 'G', 'B', 'W'), ) fun createMessage(stacks: List<List<Char>>): String { val message = mutableListOf<Char>() for(i in 1 until stacks.size) { message.add(stacks[i].last()) } return message.joinToString("") } fun part1(input: List<String>, stacks: List<MutableList<Char>>): String { val data = parseInput(input) for (move in data) { val noOfCrates = move[0] val from = move[1] val to = move[2] for (i in 1..noOfCrates) { stacks[to].add(stacks[from].removeLast()) } } return createMessage(stacks) } fun part2(input: List<String>, stacks: List<MutableList<Char>>): String { val data = parseInput(input) for (move in data) { val noOfCrates = move[0] val from = move[1] val to = move[2] val crates = MutableList(noOfCrates) { 'x' } for (i in 0 until noOfCrates) { crates[crates.lastIndex - i] = stacks[from].removeLast() } stacks[to].addAll(crates) } return createMessage(stacks) } // test if implementation meets criteria from the description, like: // check(part1(readInput("Day05_test"), testStacks) == "CMZ") // println(part1(readInput("Day05"), stacks)) check(part2(readInput("Day05_test"), testStacks) == "MCD") println(part2(readInput("Day05"), stacks)) }
0
Kotlin
0
0
47c41ceddacb17e28bdbb9449bfde5881fa851b7
2,468
aoc-2022
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day02.kt
EmRe-One
726,902,443
false
{"Kotlin": 95869, "Python": 18319}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.automation.Day class Day02 : Day(2, 2023, "Cube Conundrum") { class Bag( val red: Int = 0, val green: Int = 0, val blue: Int = 0 ) { val MAX_RED = 13 val MAX_GREEN = 14 val MAX_BLUE = 15 fun possible(): Boolean { return this.red <= MAX_RED && this.green <= MAX_GREEN && this.blue <= MAX_BLUE; } } private val GAME_PATTERN = "Game (?<id>\\d+)".toRegex() private val BAG_PATTERN = "(?<number>\\d+) (?<color>red|green|blue)".toRegex() private fun getBags(input: List<String>): Map<Int, List<Bag>> { return input.associate { line -> val (first, second) = line.split(":") val id = GAME_PATTERN.matchEntire(first)!!.groups["id"]!!.value.toInt() val bags = second.split(";").map { bag -> val groups = BAG_PATTERN.findAll(bag) .associate { it.groups["color"]!!.value to it.groups["number"]!!.value.toInt() } Bag( groups["red"] ?: 0, groups["green"] ?: 0, groups["blue"] ?: 0 ) } id to bags } } override fun part1(): Int { return getBags(inputAsList) .filterValues { it.all { b -> b.possible() } } .keys .sum() } override fun part2(): Int { return getBags(inputAsList) .map { (_, bags) -> val minRed = bags.maxOf { it.red } val minGreen = bags.maxOf { it.green } val minBlue = bags.maxOf { it.blue } minRed * minGreen * minBlue } .sum() } }
0
Kotlin
0
0
c75d17635baffea50b6401dc653cc24f5c594a2b
1,901
advent-of-code-2023
Apache License 2.0
src/Day04.kt
AxelUser
572,845,434
false
{"Kotlin": 29744}
fun main() { fun List<String>.parse(): Sequence<Pair<IntRange, IntRange>> { val regex = Regex("\\d+") return sequence { for (s in this@parse) { yield(regex.findAll(s).map { it.value.toInt() }.toList().let { (it[0]..it[1]) to (it[2]..it[3]) }) } } } fun part1(input: Sequence<Pair<IntRange, IntRange>>): Int { return input.count { (first, second) -> (first.first >= second.first && first.last <= second.last) || (second.first >= first.first && second.last <= first.last) } } fun part2(input: Sequence<Pair<IntRange, IntRange>>): Int { return input.count { (first, second) -> second.contains(first.last) || first.contains(second.last) } } check(part1(readInput("Day04_test").parse()) == 2) check(part2(readInput("Day04_test").parse()) == 4) println(part1(readInput("Day04").parse())) println(part2(readInput("Day04").parse())) }
0
Kotlin
0
1
042e559f80b33694afba08b8de320a7072e18c4e
972
aoc-2022
Apache License 2.0
2023/src/main/kotlin/de/skyrising/aoc2023/day8/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2023.day8 import de.skyrising.aoc.* import it.unimi.dsi.fastutil.ints.Int2LongMap import it.unimi.dsi.fastutil.ints.Int2LongOpenHashMap private inline fun steps(start: Int, lr: BooleanArray, map: Int2LongMap, end: (Int)->Boolean) = start.stepsUntil(end) { PackedIntPair(map[this])[lr[it % lr.size]] } private const val AAA = 13330 private const val ZZZ = 46655 private const val Z = 35 val test = TestInput(""" RL AAA = (BBB, CCC) BBB = (DDD, EEE) CCC = (ZZZ, GGG) DDD = (DDD, DDD) EEE = (EEE, EEE) GGG = (GGG, GGG) ZZZ = (ZZZ, ZZZ) """) val test2 = TestInput(""" LR 11A = (11B, XXX) 11B = (XXX, 11Z) 11Z = (11B, XXX) 22A = (22B, XXX) 22B = (22C, 22C) 22C = (22Z, 22Z) 22Z = (22B, 22B) XXX = (XXX, XXX) """) fun parse(input: PuzzleInput) = Pair( input.lines[0].map { it == 'L' }.toBooleanArray(), input.lines.asSequence().drop(2).associateTo(Int2LongOpenHashMap(input.lines.size - 2)) { val (k, v) = it.split(" = ") val (l, r) = v.substring(1, v.length - 1).split(", ") k.toInt(36) to PackedIntPair(l.toInt(36), r.toInt(36)).longValue }) @PuzzleName("") fun PuzzleInput.part1(): Any { val (lr, map) = parse(this) return steps(AAA, lr, map) { it == ZZZ } } fun PuzzleInput.part2(): Any { val (lr, map) = parse(this) var result = 1L val iter = map.keys.intIterator() while (iter.hasNext()) { val k = iter.nextInt() if (k % 36 != 0xA) continue result = result lcm steps(k, lr, map) { it % 36 == Z }.toLong() } return result }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
1,621
aoc
MIT License
src/day07/Day07.kt
hamerlinski
572,951,914
false
{"Kotlin": 25910}
package day07 import readInput import java.math.BigDecimal fun main() { fun part1and2() { val input = readInput("Day07", "day07") val maxSize = BigDecimal(70000000) val updateSizeRequirement = BigDecimal(30000000) val fileSystem = FileSystem(input) fileSystem.load() fileSystem.tree() val used = fileSystem.totalSize() println("fileSystem.sumOfSmallSizeDirs() " + fileSystem.sumOfSmallSizeDirs()) println("fileSystem.totalSize() $used") val requiredSpaceToFree = updateSizeRequirement.minus(maxSize.minus(used)) println("requiredSpaceToFree $requiredSpaceToFree") val dirToDelete = fileSystem.suggestedDeletion(requiredSpaceToFree) if (dirToDelete != null) { println("dirToDelete: " + dirToDelete.name() + " " + dirToDelete.totalSize()) } } part1and2() } class File(input: String) { private val fileInfo = input.split(" ") fun size(): BigDecimal { return BigDecimal(fileInfo[0]) } fun name(): String { return fileInfo[1] } } class Directory( private val dirName: String, private val files: MutableList<File> = mutableListOf(), private val dirs: MutableList<Directory> = mutableListOf() ) { private fun filesSize(): BigDecimal { var fileSize = BigDecimal(0) files.listIterator().forEach { fileSize = fileSize.plus(it.size()) } return fileSize } private fun dirsSizes(): BigDecimal { var dirSize = BigDecimal(0) dirs.listIterator().forEach { dirSize = dirSize.plus(it.totalSize()) } return dirSize } fun totalSize(): BigDecimal { return filesSize().plus(dirsSizes()) } fun name(): String { return dirName } fun addFile(file: File) { files.add(file) } fun printFiles() { files.listIterator().forEach { println(" └── ${it.name()}") } } fun addDir(dir: Directory) { dirs.add(dir) } } class FileSystem(private val input: List<String>) { private var root = Directory("/") private var dirMap: MutableMap<String, Directory> = mutableMapOf(root.name() to root) fun load() { val workingDirectories: MutableList<Directory> = mutableListOf(root) var currentDir = root val iterator = input.listIterator() while (iterator.hasNext()) { val it = iterator.next() if (it == "$ ls" || it == "$ cd /") continue if (it[0] == '$') { if (it == "$ cd ..") { workingDirectories.removeAt(workingDirectories.lastIndex) currentDir = workingDirectories[workingDirectories.lastIndex] continue } if (it.startsWith("$ cd ")) { val dirName = it.split(" ")[2] + "/" val currentDirPath = workingDir(workingDirectories) + dirName workingDirectories.add(dirMap[currentDirPath]!!) currentDir = dirMap[currentDirPath]!! continue } } else { if (it.startsWith("dir ")) { val dirName = it.split(" ")[1] + "/" val newDir = Directory(dirName) val currentDirPath = workingDir(workingDirectories) + dirName dirMap[currentDirPath] = newDir dirMap[currentDirPath]?.let { dir -> currentDir.addDir(dir) } continue } else { val file = File(it) currentDir.addFile(file) continue } } } } private fun workingDir(list: MutableList<Directory>): String { var pwd = "" list.listIterator().forEach { pwd = pwd.plus(it.name()) } return pwd } fun tree() { val dirSortedMap = dirMap.toSortedMap() dirSortedMap.iterator().forEach { println(it.key) it.value.printFiles() } } fun totalSize(): BigDecimal { return dirMap["/"]?.totalSize() ?: BigDecimal(0) } fun sumOfSmallSizeDirs(): BigDecimal { var sum = BigDecimal(0) dirMap.iterator().forEach { val totalSize = it.value.totalSize() if (totalSize <= BigDecimal(100000)) { sum = sum.plus(totalSize) } } return sum } fun suggestedDeletion(requiredSpace: BigDecimal): Directory? { val iterator = dirMap.iterator() var dirToDelete: Directory? = iterator.next().value while (iterator.hasNext()) { val it = iterator.next() if (dirToDelete != null && dirToDelete.totalSize() > it.value.totalSize() && it.value.totalSize() >= requiredSpace) { dirToDelete = it.value continue } } return dirToDelete } }
0
Kotlin
0
0
bbe47c5ae0577f72f8c220b49d4958ae625241b0
5,094
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/TwoEditWords.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT /** * 2452. Words Within Two Edits of Dictionary * @see <a href="https://leetcode.com/problems/words-within-two-edits-of-dictionary/">Source</a> */ fun interface TwoEditWords { operator fun invoke(queries: Array<String>, dictionary: Array<String>): List<String> } class TwoEditWordsBF : TwoEditWords { override operator fun invoke(queries: Array<String>, dictionary: Array<String>): List<String> { val ans: MutableList<String> = ArrayList() for (query in queries) { for (word in dictionary) { val diff = diff(query, word) if (diff <= 2) { ans.add(query) break } } } return ans.toList() } private fun diff(a: String, b: String): Int { val n = a.length var same = 0 for (i in 0 until n) { if (a[i] == b[i]) { same++ } } return n - same } } class TwoEditWordsTrie : TwoEditWords { override operator fun invoke(queries: Array<String>, dictionary: Array<String>): List<String> { val ans: MutableList<String> = ArrayList() for (word in dictionary) { insertWord(word) } for (query in queries) { val curr: TNode = root if (searchWord(curr, query, 0, 0)) { ans.add(query) } } return ans } private fun insertWord(word: String) { var curr: TNode = root for (i in word.indices) { val childIdx = word[i].code - 'a'.code if (curr.children[childIdx] == null) { curr.children[childIdx] = TNode(data = word[i]) } curr = curr.children[childIdx]!! } curr.isEnd = true } private fun searchWord(root: TNode, word: String, count: Int, index: Int): Boolean { if (index == word.length) { return count <= 2 } var ans = false for (i in 0 until root.children.size) { if (root.children[i] != null) { ans = ans or searchWord( root.children[i]!!, word, count + if (word[index].code - 'a'.code == i) 0 else 1, index + 1, ) } } return ans } private data class TNode(private var data: Char, var isEnd: Boolean = false) { val children: Array<TNode?> = arrayOfNulls(ALPHABET_LETTERS_COUNT) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TNode return children.contentEquals(other.children) } override fun hashCode(): Int { return children.contentHashCode() } } private val root = TNode('/') }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,636
kotlab
Apache License 2.0
src/main/kotlin/solutions/Day12HillClimbingAlgorithm.kt
aormsby
571,002,889
false
{"Kotlin": 80084}
package solutions import models.Coord2d import utils.Input import utils.Solution // run only this day fun main() { Day12HillClimbingAlgorithm() } class Day12HillClimbingAlgorithm : Solution() { init { begin("Day 12 - Hill Climbing Algorithm") var start = Coord2d(0, 0) var end = Coord2d(0, 0) val input = Input.parseLines(filename = "/d12_heightmap.txt") .mapIndexed { i, s -> s.mapIndexed char@{ j, c -> when (c) { 'S' -> { start = Coord2d(i, j) return@char 'a' } 'E' -> { end = Coord2d(i, j) return@char 'z' } } return@char c } } val sol1 = findPath(input, start, end) output("Shortest Path", sol1.size - 1) val sol2 = findHikingPath(input, end) output("Shortest Hiking Path", sol2.size - 1) } // breadth first search, then retrace steps from end to start private fun findPath(graph: List<List<Char>>, start: Coord2d, end: Coord2d): List<Coord2d> { val frontier = mutableListOf(start) val parentOf = mutableMapOf(start to start) val xLimit = graph.size - 1 val yLimit = graph.first().size - 1 while (frontier.isNotEmpty()) { val current = frontier.removeFirst() if (current == end) break current.adjacentNeighbors(xLimit, yLimit) .filter { graph[it.x][it.y] <= (graph[current.x][current.y] + 1) && it !in parentOf.keys } .forEach { frontier.add(it) parentOf[it] = current } } val path = mutableListOf(end) while (path.first() != start) { val cur = path.first() path.add(0, parentOf[cur]!!) } return path } // backwards breadth first search from end to first 'a', then retrace steps from 'a' to end private fun findHikingPath(graph: List<List<Char>>, end: Coord2d): List<Coord2d> { val frontier = mutableListOf(end) val childOf = mutableMapOf(end to end) val xLimit = graph.size - 1 val yLimit = graph.first().size - 1 val path = mutableListOf<Coord2d>() while (frontier.isNotEmpty()) { val current = frontier.removeFirst() if (graph[current.x][current.y] == 'a') { path.add(current) break } current.adjacentNeighbors(xLimit, yLimit) .filter { graph[it.x][it.y] >= (graph[current.x][current.y] - 1) && it !in childOf.keys } .forEach { frontier.add(it) childOf[it] = current } } while (path.last() != end) { val cur = path.last() path.add(childOf[cur]!!) } return path } }
0
Kotlin
0
0
1bef4812a65396c5768f12c442d73160c9cfa189
3,117
advent-of-code-2022
MIT License
src/Day08.kt
vlsolodilov
573,277,339
false
{"Kotlin": 19518}
fun main() { fun fillMatrix(input: List<String>): List<List<Int>> = input.map { line -> line.map { it.digitToInt() } } fun checkLeft(y: Int, x: Int, matrix: List<List<Int>>): Boolean { val currentTree = matrix[y][x] matrix[y].forEachIndexed { index, tree -> if ((index < x) && ( tree - currentTree >= 0 )) return false } return true } fun checkRight(y: Int, x: Int, matrix: List<List<Int>>): Boolean { val currentTree = matrix[y][x] matrix[y].forEachIndexed { index, tree -> if ((index > x) && ( tree - currentTree >= 0 )) return false } return true } fun checkTop(y: Int, x: Int, matrix: List<List<Int>>): Boolean { val currentTree = matrix[y][x] for (i in 0 until y) { if (matrix[i][x] - currentTree >= 0) return false } return true } fun checkBottom(y: Int, x: Int, matrix: List<List<Int>>): Boolean { val currentTree = matrix[y][x] for (i in y+1 until matrix.size) { if (matrix[i][x] - currentTree >= 0) return false } return true } fun part1(input: List<String>): Int { var count = 0 val matrix = fillMatrix(input) for (i in 1..matrix.size-2) { for (j in 1..matrix[0].size-2) { if (checkLeft(i,j,matrix) || checkRight(i,j,matrix) || checkTop(i,j,matrix) || checkBottom(i,j,matrix)) { count ++ } } } return count + (matrix.size + matrix[0].size - 2) * 2 } fun sumLeft(y: Int, x: Int, matrix: List<List<Int>>): Int { val currentTree = matrix[y][x] var count = 0 for (i in x - 1 downTo 0) { if (matrix[y][i] < currentTree) { count++ } else if (matrix[y][i] >= currentTree){ count++ break } else { break } } return count } fun sumRight(y: Int, x: Int, matrix: List<List<Int>>): Int { val currentTree = matrix[y][x] var count = 0 for (i in x + 1 until matrix[y].size) { if (matrix[y][i] < currentTree) { count++ } else if (matrix[y][i] >= currentTree){ count++ break } else { break } } return count } fun sumTop(y: Int, x: Int, matrix: List<List<Int>>): Int { val currentTree = matrix[y][x] var count = 0 for (i in y - 1 downTo 0) { if (matrix[i][x] < currentTree) { count++ } else if (matrix[i][x] >= currentTree){ count++ break } else { break } } return count } fun sumBottom(y: Int, x: Int, matrix: List<List<Int>>): Int { val currentTree = matrix[y][x] var count = 0 for (i in y + 1 until matrix.size) { if (matrix[i][x] < currentTree) { count++ } else if (matrix[i][x] >= currentTree){ count++ break } else { break } } return count } fun part2(input: List<String>): Int { var score = 0 val matrix = fillMatrix(input) for (i in 1..matrix.size-2) { for (j in 1..matrix[0].size-2) { val currentScore = sumLeft(i,j,matrix) * sumRight(i,j,matrix) * sumTop(i,j,matrix) * sumBottom(i,j,matrix) if (currentScore > score) score = currentScore } } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b75427b90b64b21fcb72c16452c3683486b48d76
4,111
aoc22
Apache License 2.0