path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/dev/shtanko/algorithms/leetcode/RemoveBoxes.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 546. Remove Boxes * @see <a href="https://leetcode.com/problems/remove-boxes/">Source</a> */ fun interface RemoveBoxes { operator fun invoke(boxes: IntArray): Int } class RemoveBoxesTopDown : RemoveBoxes { override operator fun invoke(boxes: IntArray): Int { val n: Int = boxes.size val dp = Array(n) { Array(n) { IntArray(n) } } return removeBoxesSub(boxes, 0, n - 1, 0, dp) } private fun removeBoxesSub(boxes: IntArray, i: Int, j: Int, k: Int, dp: Array<Array<IntArray>>): Int { var i0 = i var k0 = k if (i0 > j) return 0 if (dp[i0][j][k0] > 0) return dp[i0][j][k0] while (i0 + 1 <= j && boxes[i0 + 1] == boxes[i0]) { // optimization: all boxes of the same color counted continuously from the first box should be // grouped together i0++ k0++ } var res = (k0 + 1) * (k0 + 1) + removeBoxesSub(boxes, i0 + 1, j, 0, dp) for (m in i0 + 1..j) { if (boxes[i0] == boxes[m]) { res = max( res, removeBoxesSub(boxes, i0 + 1, m - 1, 0, dp).plus( removeBoxesSub(boxes, m, j, k0 + 1, dp), ), ) } } dp[i][j][k] = res // When updating the dp matrix, we should use the initial values of i, j and k return res } } class RemoveBoxesBottomUp : RemoveBoxes { override operator fun invoke(boxes: IntArray): Int { val n: Int = boxes.size val dp = Array(n) { Array(n) { IntArray(n) } } for (j in 0 until n) { for (k in 0..j) { dp[j][j][k] = (k + 1) * (k + 1) } } for (l in 1 until n) { for (j in l until n) { val i = j - l for (k in 0..i) { var res = (k + 1) * (k + 1) + dp[i + 1][j][0] for (m in i + 1..j) { if (boxes[m] == boxes[i]) { res = max(res, dp[i + 1][m - 1][0] + dp[m][j][k + 1]) } } dp[i][j][k] = res } } } return if (n == 0) 0 else dp[0][n - 1][0] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,017
kotlab
Apache License 2.0
src/main/java/com/ncorti/aoc2021/Exercise03.kt
cortinico
433,486,684
false
{"Kotlin": 36975}
package com.ncorti.aoc2021 object Exercise03 { fun part1(): Int { val input = getInputAsTest("03") { split("\n") }.map { it.toCharArray().map { digit -> digit.digitToInt() } } return input .reduce { l, r -> l.mapIndexed { index, item -> item + r[index] } } .fold("" to "") { (gamma, epsilon), count -> if (count > input.size / 2) "${gamma}0" to "${epsilon}1" else "${gamma}1" to "${epsilon}0" } .let { (first, second) -> first.toInt(2) * second.toInt(2) } } fun part2(): Int { val input = getInputAsTest("03") { split("\n") } return IntArray(input[0].length) .foldIndexed(input to input) { index, (oxygen, co2), _ -> val mostCommonInOxygen = if ((oxygen.count { it[index] == '1' }) >= oxygen.size / 2.0) '1' else '0' val mostCommonInCo2 = if ((co2.count { it[index] == '1' }) >= co2.size / 2.0) '1' else '0' val newOxygen = if (oxygen.size == 1) { oxygen } else { oxygen.filter { it[index] == mostCommonInOxygen } } val newCo2 = if (co2.size == 1) { co2 } else { co2.filter { it[index] != mostCommonInCo2 } } newOxygen to newCo2 } .let { (first, second) -> first[0].toInt(2) * second[0].toInt(2) } } } fun main() { println(Exercise03.part1()) println(Exercise03.part2()) }
0
Kotlin
0
4
af3df72d31b74857201c85f923a96f563c450996
1,727
adventofcode-2021
MIT License
src/main/kotlin/Day07.kt
dliszewski
573,836,961
false
{"Kotlin": 57757}
class Day07 { fun part1(input: List<String>): Long { val hashMapOf = directoriesMap(input) return hashMapOf.values.filter { it <= 100_000 }.sum() } private fun directoriesMap(input: List<String>): MutableMap<String, Long> { val hashMapOf = mutableMapOf<String, Long>() var path = "" for (line in input) { when (line.getTyp()) { CommandType.COMMAND_CD_ROOT -> path = "" CommandType.COMMAND_CD_UP -> { path = path.substringBeforeLast("/") } CommandType.COMMAND_CD -> { val tempPath = line.substringAfter("$ cd ") path = "$path/$tempPath" } CommandType.COMMAND_DIR -> "" CommandType.DIR -> "" CommandType.SIZE -> { val tempSize = line.substringBefore(" ").toInt() var tempDir = path while (true) { val previous = hashMapOf.getOrDefault(tempDir, 0) hashMapOf[tempDir] = previous + tempSize if (tempDir.isEmpty()) break tempDir = tempDir.substringBeforeLast("/", "") } } } } return hashMapOf } private enum class CommandType { COMMAND_CD_ROOT, COMMAND_CD, COMMAND_CD_UP, COMMAND_DIR, DIR, SIZE } private fun String.getTyp(): CommandType { return when { this.startsWith("$ cd /") -> CommandType.COMMAND_CD_ROOT this.startsWith("$ cd ..") -> CommandType.COMMAND_CD_UP this.startsWith("$ cd ") -> CommandType.COMMAND_CD this.startsWith("$ ls") -> CommandType.COMMAND_DIR this.startsWith("dir ") -> CommandType.DIR else -> CommandType.SIZE } } fun part2(input: List<String>): Long { val total = 70_000_000 val required = 30_000_000 val directoriesMap = directoriesMap(input) val used = directoriesMap.getOrDefault("", 0) val unusedSpace = total - used val deficit = required - unusedSpace return directoriesMap.values.filter { it >= deficit }.min() } }
0
Kotlin
0
0
76d5eea8ff0c96392f49f450660220c07a264671
2,295
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/dikodam/Utils.kt
dikodam
573,126,346
false
{"Kotlin": 26584}
package de.dikodam data class Coordinates2D(val x: Int, val y: Int) { operator fun plus(other: Coordinates2D) = Coordinates2D(x + other.x, y + other.y) fun all4Neighbors(): List<Coordinates2D> { return Cardinal4Direction.values().map { dir -> this + dir.toCoords2D() } } fun all8neighbors(): List<Coordinates2D> { return Cardinal8Direction.values().map { dir -> this + dir.toCoords2D() } } } enum class Cardinal4Direction { N, S, W, E; fun toCoords2D(): Coordinates2D = when (this) { N -> Coordinates2D(0, -1) S -> Coordinates2D(0, 1) W -> Coordinates2D(-1, 0) E -> Coordinates2D(1, 0) } } enum class Cardinal8Direction { N, S, W, E, NW, NE, SW, SE; fun toCoords2D(): Coordinates2D = when (this) { N -> Coordinates2D(0, -1) S -> Coordinates2D(0, 1) W -> Coordinates2D(-1, 0) E -> Coordinates2D(1, 0) NW -> N.toCoords2D() + W.toCoords2D() NE -> N.toCoords2D() + E.toCoords2D() SW -> S.toCoords2D() + W.toCoords2D() SE -> S.toCoords2D() + E.toCoords2D() } } data class Coordinates3D(val x: Int, val y: Int, val z: Int) fun <T : Comparable<T>> min(pair: Pair<T, T>): T { val (a, b) = pair return if (a <= b) a else b } fun <T : Comparable<T>> max(pair: Pair<T, T>): T { val (a, b) = pair return if (a >= b) a else b } fun pointsBetween(low: Coordinates3D, high: Coordinates3D): Set<Coordinates3D> { return (low.x..high.x).flatMap { x -> (low.y..high.y).flatMap { y -> (low.z..high.z).map { z -> Coordinates3D(x, y, z) } } }.toSet() } fun String.hexToBinString(): String = this.map { char -> char.digitToInt(16) }.map { Integer.toBinaryString(it) }.map { it.padStart(4, '0') } .joinToString("") fun String.splitAfter(count: Int): Pair<String, String> = take(count) to drop(count) fun <T> Iterable<T>.splitAfter(count: Int): Pair<List<T>, List<T>> = take(count) to drop(count) fun <T> List<T>.divideAt(splitter: T): List<List<T>> { var remaining = this var accumulator: MutableList<List<T>> = mutableListOf() while (remaining.isNotEmpty()) { val list = remaining.takeWhile { it != splitter } accumulator += list remaining = remaining.drop(list.size + 1) } return accumulator } fun IntRange.containsRange(other: IntRange): Boolean = this.first <= other.first && this.last >= other.last fun Collection<Coordinates2D>.minMaxBox() = MinMaxBox(minX = minOf { it.x }, maxX = maxOf { it.x }, minY = minOf { it.y }, maxY = maxOf { it.y }) data class MinMaxBox(val minX: Int, val maxX: Int, val minY: Int, val maxY: Int)
0
Kotlin
0
1
3eb9fc6f1b125565d6d999ebd0e0b1043539d192
2,695
aoc2022
MIT License
src/day_13/kotlin/Day13.kt
Nxllpointer
573,051,992
false
{"Kotlin": 41751}
import kotlin.math.max // AOC Day 13 fun Pair<List<*>, List<*>>.isInRightOrder(): Boolean? { val left = first val right = second for (listIndex in 0..max(left.lastIndex, right.lastIndex)) { if (listIndex > left.lastIndex) return true if (listIndex > right.lastIndex) return false val itemLeft = left[listIndex] val itemRight = right[listIndex] if (itemLeft is Int && itemRight is Int) { if (itemLeft < itemRight) return true if (itemLeft > itemRight) return false } if (itemLeft is List<*> && itemRight is List<*>) (itemLeft to itemRight).isInRightOrder().also { if (it != null) return it } if (itemLeft is Int && itemRight is List<*>) { val order = (listOf(itemLeft) to itemRight).isInRightOrder() if (order != null) return order } if (itemLeft is List<*> && itemRight is Int) { val order = (itemLeft to listOf(itemRight)).isInRightOrder() if (order != null) return order } } return null } fun compareLists(first: MutableList<*>, other: MutableList<*>) = when ((first to other).isInRightOrder()) { false -> 1 true -> -1 null -> throw IllegalArgumentException("Order was not able to be determined") } fun part1(lists: MutableList<MutableList<Any>>) { val pairs = lists .chunked(2) .map { it.first() to it.last() } val correctlyOrderedIndicesSum = pairs .filter { it.isInRightOrder()!! } .sumOf { pairs.indexOf(it) + 1 } println("Part 1: The sum of indices of correctly ordered pairs is $correctlyOrderedIndicesSum") } fun part2(lists: MutableList<MutableList<Any>>) { val dividers = arrayOf( mutableListOf(mutableListOf(2)), mutableListOf(mutableListOf(6)) ) val decoderKey = lists .plus(dividers) .sortedWith(::compareLists) .let { sortedLists -> sortedLists .filter { it in dividers } .map { sortedLists.indexOf(it) + 1 } .product() } println("Part 2: The decoder key is $decoderKey") } fun main() { val lists = getAOCInput { rawInput -> val lists = mutableListOf<MutableList<Any>>() var currentCharIndex = 0 var currentChar = rawInput[currentCharIndex] var nextChar = rawInput[currentCharIndex + 1] fun next() { currentCharIndex++ currentChar = rawInput[currentCharIndex] nextChar = rawInput.getOrElse(currentCharIndex + 1) { '?' } } fun readInt(): Int { var intString = currentChar.toString() while (nextChar.isDigit()) { next() intString += currentChar } return intString.toInt() } fun readList(): MutableList<Any> { val list = mutableListOf<Any>() while (nextChar != ']') { next() if (currentChar.isDigit()) list.add(readInt()) else if (currentChar == '[') list.add(readList()) } next() return list } while (nextChar != '?') { if (currentChar == '[') readList().also { lists += it } next() } lists } part1(lists) part2(lists) }
0
Kotlin
0
0
b6d7ef06de41ad01a8d64ef19ca7ca2610754151
3,450
AdventOfCode2022
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-07.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2015, "07-input") val test1 = readInputLines(2015, "07-test1") println("Part1:") part1(test1, "g").println() part1(input, "a").println() println() println("Part2:") part2(input).println() } private fun part1(input: List<String>, wire: String): UShort { val map = parse(input) val gates = LogicGates(map) return gates.solveWire(wire) } private fun part2(input: List<String>): UShort { val map = parse(input) map["b"] = "16076" val gates = LogicGates(map) return gates.solveWire("a") } private class LogicGates(private val map: Map<String, String>) { private val solved = mutableMapOf<String, UShort>() fun solveWire(wire: String): UShort { val const = """\d+""".toRegex() if (const.matches(wire)) return wire.toUShort() if (wire in solved) return solved[wire]!! val gate = map[wire]!! val pipe = """\w+""".toRegex() val not = """NOT ([a-z]+)""".toRegex() val andGate = """(\w+) AND (\w+)""".toRegex() val orGate = """([a-z]+) OR ([a-z]+)""".toRegex() val rshift = """([a-z]+) RSHIFT (\d+)""".toRegex() val lshift = """([a-z]+) LSHIFT (\d+)""".toRegex() val result: UShort = when { pipe.matches(gate) -> { solveWire(gate) } not.matches(gate) -> { val g = not.matchEntire(gate)!!.groupValues[1] solveWire(g).inv() } andGate.matches(gate) -> { val (g1, g2) = andGate.matchEntire(gate)!!.destructured solveWire(g1) and solveWire(g2) } orGate.matches(gate) -> { val (g1, g2) = orGate.matchEntire(gate)!!.destructured solveWire(g1) or solveWire(g2) } lshift.matches(gate) -> { val (g1, g2) = lshift.matchEntire(gate)!!.destructured (solveWire(g1).toInt() shl g2.toInt()).toUShort() } rshift.matches(gate) -> { val (g1, g2) = rshift.matchEntire(gate)!!.destructured (solveWire(g1).toInt() shr g2.toInt()).toUShort() } else -> error("Should not happen") } return result.also { solved[wire] = it } } } private fun parse(input: List<String>): MutableMap<String, String> { val map = mutableMapOf<String, String>() input.forEach { val (src, dst) = it.split(" -> ") map[dst] = src } return map }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,705
advent-of-code
MIT License
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day10/Day10.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2020.day10 import eu.janvdb.aocutil.kotlin.readLines fun main() { val numbers = readLines(2020, "input10.txt").map(String::toInt) val numbersIncludingStartAndEndValue = listOf(listOf(0, numbers.maxOrNull()!! + 3), numbers).flatten().sorted() part1(numbersIncludingStartAndEndValue) part2(numbersIncludingStartAndEndValue) } private fun part1(numbers: List<Int>) { val differences = numbers.asSequence() .zipWithNext() .map { Math.abs(it.first - it.second) } .groupBy({ it }) val difference1 = differences[1]?.size ?: 0 val difference3 = differences[3]?.size ?: 0 assert(difference1 + difference3 == numbers.size - 1) println(difference1 * difference3) } fun part2(numbers: List<Int>) { val numberOfPathsByStartValue = mutableMapOf(Pair(numbers[numbers.size - 1], 1L)) fun getNumberOfPaths(index: Int): Long { return numberOfPathsByStartValue[index] ?: 0L } for (i in numbers.size - 2 downTo 0) { val value = numbers[i] val numberOfPaths = getNumberOfPaths(value + 1) + getNumberOfPaths(value + 2) + getNumberOfPaths(value + 3) numberOfPathsByStartValue[value] = numberOfPaths } println(getNumberOfPaths(0)) }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,168
advent-of-code
Apache License 2.0
src/day04/Day04.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day04 import readInput private const val DAY_ID = "04" fun main() { fun parseInput(input: List<String>): List<Pair<IntRange, IntRange>> = input.map { line -> val (first, second) = line.split(",").map { range -> val (start, end) = range.split("-").map { it.toInt() } start..end } first to second } fun part1(input: List<String>): Int { fun IntRange.fullyContains(b: IntRange): Boolean = b.first >= this.first && b.last <= this.last val data = parseInput(input) return data.count { (first, second) -> first.fullyContains(second) || second.fullyContains(first) } } fun part2(input: List<String>): Int { fun overlap(a: IntRange, b: IntRange): Boolean = b.last >= a.first && b.first <= a.last val data = parseInput(input) return data.count { (first, second) -> overlap(first, second) } } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("day${DAY_ID}/Day$DAY_ID") println(part1(input)) // answer = 588 println(part2(input)) // answer = 911 }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
1,342
aoc-2022-in-kotlin
Apache License 2.0
src/Day15.kt
ostersc
572,991,552
false
{"Kotlin": 46059}
import kotlin.math.absoluteValue fun log(s: String) { //println(s) } sealed class LocationContent class Beacon : LocationContent() class Sensor(var distanceFromBeacon: Int) : LocationContent() data class Location(var x: Int, var y: Int) { fun distanceFrom(l: Location): Int { return (x - l.x).absoluteValue + (y - l.y).absoluteValue } } class BeaconGrid(var contents: MutableMap<Location, LocationContent>) { companion object { fun of(input: List<String>): BeaconGrid { val g = BeaconGrid(contents = mutableMapOf<Location, LocationContent>()) for (line in input) { val (a, b, c, d) = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex() .find(line)!!.destructured.toList().map { it.toInt() } val sensor = Location(a, b) val beacon = Location(c, d) g.contents[beacon] = Beacon() g.contents[sensor] = Sensor(sensor.distanceFrom(beacon)) } return g } } } fun main() { fun part1(input: List<String>, row: Int): Int { var count = 0 val grid = BeaconGrid.of(input) val minX = grid.contents.minOf { if (it.value is Sensor) it.key.x - (it.value as Sensor).distanceFromBeacon else 0 } val maxX = grid.contents.maxOf { if (it.value is Sensor) it.key.x + (it.value as Sensor).distanceFromBeacon else 0 } for (i in minX..maxX) { val l = Location(i, row) log("At location $l") if (grid.contents[l] is Sensor) { /** if the location is a Sensor, it can't contain a Beacon, so include **/ count++ log("\t its a sensor, so upped count to $count") continue } else if (grid.contents[l] is Beacon) { /** if the location is a Beacon, it can't not contain a Beacon, so exclude **/ log("\t its a beacon") continue } else if (grid.contents.count { it.value is Sensor && l.distanceFrom(it.key) <= (it.value as Sensor).distanceFromBeacon } > 0) { /** there's at least 1 sensor that this location is closer to than that sensor's nearest beacon, so include it **/ count++ log("\t there's a nearby sensor, so upped count to $count") } } return count } fun part2(input: List<String>, max:Long): Long { val grid = BeaconGrid.of(input) // generate a list of locations that are on the edge of each sensors vision val locations = mutableListOf<Location>() for ((l, s) in grid.contents.filter { it.value is Sensor }) { val dist = (s as Sensor).distanceFromBeacon for (i in l.x - dist - 1..l.x + dist + 1) { var h:Int if(i<=l.x){ h = (l.x-dist-i-1).absoluteValue }else{ h = (l.x-dist+i+1).absoluteValue } //up val up = Location(i, l.y + h) if (up.x > 0 && up.y >= 0 && up.x <= max && up.y <= max) { locations.add(up) } //down val down = Location(i, l.y - h) if (down.x > 0 && down.y >= 0 && down.x <= max && down.y <= max) { locations.add(down) } } } //find the location that is beyond all sensors vision var beacon = Location(0, 0) for (l in locations) { if (grid.contents[l] is Sensor) { continue } else if (grid.contents[l] is Beacon) { continue } else if (grid.contents.count { it.value is Sensor && l.distanceFrom(it.key) > (it.value as Sensor).distanceFromBeacon } == input.size) { beacon = l } } return beacon.x * 4_000_000L + beacon.y } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") val part1 = part1(input, 2000000) println(part1) check(part1 == 5112034) val part2 = part2(input, 4_000_000L) println(part2) check(part2==13172087230812L) }
0
Kotlin
0
1
3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9
4,436
advent-of-code-2022
Apache License 2.0
src/main/kotlin/year2022/day-08.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2022 import lib.aoc.Day import lib.aoc.Part import lib.math.Vector import lib.math.plus import lib.math.plusAssign import lib.math.product fun main() { Day(8, 2022, PartA8(), PartB8()).run() } open class PartA8 : Part() { lateinit var trees: List<List<Int>> lateinit var limits: Iterable<Int> operator fun List<List<Int>>.get(pos: Vector) = this[pos.y][pos.x] override fun parse(text: String) { trees = text .split("\n") .map { it.toList().map(Char::digitToInt) } limits = trees.indices } override fun compute(): String { val visible = mutableSetOf<Vector>() limits.forEach { visible.addAll(walkLine(Vector.at(0, it), Vector.at(1, 0))) visible.addAll(walkLine(Vector.at(trees.size - 1, it), Vector.at(-1, 0))) visible.addAll(walkLine(Vector.at(it, 0), Vector.at(0, 1))) visible.addAll(walkLine(Vector.at(it, trees.size - 1), Vector.at(0, -1))) } return visible.size.toString() } private fun walkLine(startPos: Vector, direction: Vector): MutableSet<Vector> { val currentPos = startPos.toMutableVector() var currentHeight = -1 val visible = mutableSetOf<Vector>() while (currentPos within limits) { if (trees[currentPos] > currentHeight) { visible.add(currentPos.toVector()) currentHeight = trees[currentPos] } currentPos += direction } return visible } override val exampleAnswer: String get() = "21" } class PartB8 : PartA8() { override fun compute(): String { return (1 until trees.size).product(1 until trees.size) .maxOf(::calculateScenicScore) .toString() } private fun calculateScenicScore(value: Pair<Int, Int>): Int { val position = Vector.at(value.first, value.second) val directions = listOf(Vector.at(-1, 0), Vector.at(1, 0), Vector.at(0, -1), Vector.at(0, 1)) return directions.map { calculateScoreOfLine(position, it) }.reduce(Int::times) } private fun calculateScoreOfLine(position: Vector, direction: Vector): Int { val currentPos = (position + direction).toMutableVector() var score = 0 while (currentPos within limits) { score += 1 if (trees[currentPos] >= trees[position]) { break } currentPos += direction } return score } override val exampleAnswer: String get() = "8" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
2,685
Advent-Of-Code-Kotlin
MIT License
src/main/kotlin/days/aoc2023/Day12.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2023 import days.Day class Day12 : Day(2023, 12) { override fun partOne(): Any { return calculatePartOne(inputList) } override fun partTwo(): Any { return calculatePartTwo(inputList) } fun calculatePartOne(input: List<String>): Int { // brute force it return input.sumOf { line -> val (record, contiguousSpringsList) = line.split(" ").let { it.first() to it.last().split(",").map { it.toInt() } } constructSpringPermutations(record).count { isValidCondition( it, contiguousSpringsList ) } } } private fun constructSpringPermutations(record: String): List<String> { val permutations = mutableListOf<String>() val deque = ArrayDeque<String>() deque.add(record) while (deque.isNotEmpty()) { val current = deque.removeFirst() if (current.indexOfFirst { it == '?' } >= 0) { deque.add(current.replaceFirst('?','.')) deque.add(current.replaceFirst('?','#')) } else { permutations.add(current) } } return permutations } fun isValidCondition(springConditions: String, contiguousSprings: List<Int>): Boolean { val pattern = "\\.*" + contiguousSprings.joinToString("\\.+") { springCount -> "#".repeat( springCount ) } + "\\.*" return Regex(pattern).matches(springConditions) } fun calculatePartTwo(input: List<String>): Long { val result = input.sumOf { line -> val (record, contiguousSpringsList) = line.split(" ").let { it.first().plus("?").repeat(5).dropLast(1) to it.last().plus(",").repeat(5).dropLast(1).split(",").map { it.toInt() } } // can't brute force this :| val count = countValidRemaining(record, contiguousSpringsList) //println("Found $count valid configs for $record") count } println("Cache contains ${memoize.size} entries and was hit $hitCount times") return result } private val memoize = mutableMapOf<Pair<String, List<Int>>, Long>() private var hitCount = 0L private fun countValidRemaining(record: String, contiguousSprings: List<Int>): Long { if (contiguousSprings.isEmpty()) { // if there are any other broken springs in the (optional) remainder of the record // it's not a valid record return if (record.contains('#')) 0 else 1 } else if (record.isEmpty()) { // empty record but non-empty springs list... we're missing springs return 0 } var count = 0L // stats! val pair = Pair(record, contiguousSprings) if (memoize.contains(pair)) { hitCount++ } return memoize.getOrPut(pair) { if (record.first() == '#' || record.first() == '?') { val contiguousLength = contiguousSprings.first() // count as though the ? is actually a #... we've (potentially) found a group of // contiguous broken springs. Verify this group is possible and count the // remaining groups. Possible groups mean that: // // * the remaining record can even hold the group of springs // * the current record doesn't have any working springs in the contiguous length // * it's the end of the record or there's either a working spring after it if (record.length >= contiguousLength && !record.take(contiguousLength).contains(".") && (record.drop(contiguousLength).isEmpty() || record.drop(contiguousLength) .first() in "?.") ) { // this contiguous group is okay... count the remainder after dropping the contiguous group // PLUS the following one since we have to assume it's a '.' for this config to work count += countValidRemaining( record.drop(contiguousLength + 1), contiguousSprings.drop(1) ) } } if (record.first() == '.' || record.first() == '?') { // count as though the ? is actually a . count += countValidRemaining(record.drop(1), contiguousSprings) } count } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
4,669
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/Day03.kt
aneroid
572,802,061
false
{"Kotlin": 27313}
class Day03(private val input: List<String>) { private val data get() = parseInput(input) private val priorities = (('a'..'z') + ('A'..'Z')).zip(1..52).toMap() fun partOne(): Int = data .asSequence() .map { it.first.toSet().intersect(it.second.toSet()).first() } .sumOf { priorities.getValue(it) } fun partTwo(): Int = input.chunked(3) .map { chunks -> chunks.map(String::toSet) .reduce { acc, set -> acc.intersect(set) } .first() }.sumOf { priorities.getValue(it) } private companion object { fun parseInput(input: List<String>) = input.map { it.length.let { len -> it.substring(0, len / 2) to it.substring(len / 2) } } } } fun main() { val testInput = readInput("Day03_test") check(Day03(testInput).partOne() == 157) check(Day03(testInput).partTwo() == 70) // uncomment when ready val input = readInput("Day03") println("partOne: ${Day03(input).partOne()}\n") println("partTwo: ${Day03(input).partTwo()}\n") }
0
Kotlin
0
0
cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd
1,211
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/dp/LIBAFS.kt
yx-z
106,589,674
false
null
package dp // given an array of (int, boolean) pair, find the length of longest increasing // back-and-forth subsequence which is defined as // the subsequence is increasing // when boolean == true, find the next element to the right // o/w, find the next element to the left fun main(args: Array<String>) { // ex. length of LIBAFS should be nine in that it is (val @ idx): // 0 @ 20, 1 @ 1, 2 @ 16, 3 @ 17, 4 @ 9, 6 @ 8, 7 @ 13, 8 @ 11, 9 @ 12 val arr = arrayOf( 1 to true, 1 to false, 0 to true, 2 to false, 5 to false, 9 to true, 6 to false, 6 to true, 4 to false, 5 to true, 8 to true, 9 to false, 7 to false, 7 to true, 3 to true, 2 to true, 3 to false, 8 to false, 4 to true, 0 to false) println(arr.libafs()) } fun Array<Pair<Int, Boolean>>.libafs(): Int { // get the original index in the sorted array val idx = IntArray(size) { it } val sortedIdx = idx.sortedByDescending { this[it].first } // dp[i] = length of libafs that starts @ this[i] // dp[i] = 1 + max(dp[k] : this[k] > this[i], k in i + 1 until size), if this[i].second // = 1 + max(dp[k] : this[k] > this[i], k in 0 until i), o/w val dp = IntArray(size) sortedIdx.forEach { i -> dp[i] = 1 + if (this[i].second) { dp.filterIndexed { k, _ -> k in i + 1 until size && this[k].first > this[i].first }.max() ?: 0 } else { dp.filterIndexed { k, _ -> k in 0 until i && this[k].first > this[i].first }.max() ?: 0 } } return dp.max() ?: 0 }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,512
AlgoKt
MIT License
src/main/kotlin/binary/NumberOfOccurrences.kt
Pawlllosss
526,668,214
false
{"Kotlin": 61939}
package binary import sorting.QuickSort fun main() { val list = listOf(6, 2, 8, 1, 4, 1, 7, 5, 1, 8, 4, 1, 6, 1) // 5 ones val sortedList = QuickSort().sort(list) val leftBoundary = boundaryBinarySearch(sortedList, 1, true) val rightBoundary = boundaryBinarySearch(sortedList, 1, false) print(rightBoundary - leftBoundary) } fun boundaryBinarySearch(input: List<Int>, targetValue: Int, lookToLeft: Boolean): Int { return boundaryBinarySearch(input, targetValue, 0, input.size - 1, lookToLeft) } private fun boundaryBinarySearch(input: List<Int>, targetValue: Int, low: Int, high: Int, lookToLeft: Boolean): Int { if (low > high) { return low } val middle = low + (high - low) / 2 val compareFunction: (Int, Int) -> Boolean = if (lookToLeft) { a, b -> a > b } else { a, b -> a < b } return if (compareFunction(targetValue, input[middle])) { if (lookToLeft) { boundaryBinarySearch(input, targetValue, middle + 1, high, lookToLeft) } else { boundaryBinarySearch(input, targetValue, low, middle - 1, lookToLeft) } } else { if (lookToLeft) { boundaryBinarySearch(input, targetValue, low, middle - 1, lookToLeft) } else { boundaryBinarySearch(input, targetValue, middle + 1, high, lookToLeft) } } }
0
Kotlin
0
0
94ad00ca3e3e8ab7a2cb46f8846196ae7c55c8b4
1,358
Kotlin-algorithms
MIT License
src/aoc2017/kot/Day15.kt
Tandrial
47,354,790
false
null
package aoc2017.kot import getWords import java.io.File object Day15 { fun partOne(seedA: Long, seedB: Long): Int { val genA = gen(seedA, 16807) val genB = gen(seedB, 48271) return getCount(genA, genB, 40_000_000) } fun partTwo(seedA: Long, seedB: Long): Int { val genA = gen(seedA, 16807, 4) val genB = gen(seedB, 48271, 8) return getCount(genA, genB, 5_000_000) } private fun gen(seed: Long, mult: Int, filter: Long = 1): Sequence<Long> = generateSequence(seed) { var next = it do { // after = (after * mult) % Int.MAX_VALUE // Int.MAX_VALUE is a Mersenne prime 2^s - 1, so we can calculate the mod with: //https://ariya.io/2007/02/modulus-with-mersenne-prime // int i = (k & p) + (k >> s); // return (i >= p) ? i - p : i; next *= mult next = (next and 0x7fffffff) + (next shr 31) next = if (next shr 31 != 0L) next - 0x7fffffff else next } while (next and (filter - 1) != 0L) next } private fun getCount(seqA: Sequence<Long>, seqB: Sequence<Long>, length: Int): Int { val values = seqA.zip(seqB).take(length) return values.count { (a, b) -> a and 0xFFFF == b and 0xFFFF } } } fun main(args: Array<String>) { val input = File("./input/2017/Day15_input.txt").readLines() val seeds = input.map { it.getWords()[4].toLong() } println("Part One = ${Day15.partOne(seeds[0], seeds[1])}") println("Part Two = ${Day15.partTwo(seeds[0], seeds[1])}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,472
Advent_of_Code
MIT License
src/main/kotlin/days/y23/Day02.kt
kezz
572,635,766
false
{"Kotlin": 20772}
package days.y23 import util.Day public fun main() { Day02().run() } public class Day02 : Day(23, 2) { private val limits = mapOf( "red" to 12, "green" to 13, "blue" to 14, ) private fun parseInput(input: List<String>) = input .map { string -> string.split(": ") } .map { (gamePart, pulls) -> Pair(gamePart.split(' ')[1].toInt(), pulls.split("; ")) } .map { (gameIndex, pulls) -> gameIndex to pulls.foldIndexed(mutableMapOf<String, Int>()) { _, acc, string -> string .split(", ") .map { pull -> pull.split(' ') } .map { (number, colour) -> Pair(number.toInt(), colour) } .forEach { (number, colour) -> acc.compute(colour) { _, existing -> when { existing == null -> number existing > number -> existing else -> number } } } acc } } override fun part1(input: List<String>): Any? = input .let(::parseInput) .filter { (_, maxSeen) -> maxSeen.all { (colour, number) -> number <= limits.getOrDefault(colour, 0) } } .sumOf(Pair<Int, MutableMap<String, Int>>::first) override fun part2(input: List<String>): Any? = input .let(::parseInput) .map(Pair<Int, MutableMap<String, Int>>::second) .map(MutableMap<String, Int>::values) .sumOf { maxes -> maxes.reduce(Int::times) } }
0
Kotlin
0
0
1cef7fe0f72f77a3a409915baac3c674cc058228
1,686
aoc
Apache License 2.0
src/Day09.kt
MwBoesgaard
572,857,083
false
{"Kotlin": 40623}
import kotlin.math.max import kotlin.math.abs fun main() { class Knot(var posX: Int, var posY: Int, var attachedTo: Knot?) { val setOfPlacesVisited = mutableSetOf(Pair(0, 0)) fun moveInDirection(direction: String) { when (direction) { "U" -> posY += 1 "R" -> posX += 1 "D" -> posY -= 1 "L" -> posX -= 1 } } fun distanceFromOtherKnot(other: Knot): Int { // Chebyshev (or chess) distance return max(abs(other.posX - this.posX), abs(other.posY - this.posY)) } fun moveTowardsOtherKnot(other: Knot) { if (other.posY - this.posY > 0) moveInDirection("U") if (other.posY - this.posY < 0) moveInDirection("D") if (other.posX - this.posX > 0) moveInDirection("R") if (other.posX - this.posX < 0) moveInDirection("L") this.setOfPlacesVisited.add(Pair(posX, posY)) } } class Rope(size: Int) { val knots = MutableList(size) { Knot(0, 0, null) } var head: Knot var tail: Knot init { knots.forEachIndexed { i, knot -> if (i != 0) knot.attachedTo = knots[i - 1] } head = knots.first() tail = knots.last() } } fun part1(input: List<String>): Int { val rope = Rope(2) for (move in input) { val (direction, distance) = move.split(" ") for (step in 1..distance.toInt()) { rope.head.moveInDirection(direction) if (rope.tail.distanceFromOtherKnot(rope.tail.attachedTo!!) > 1) { rope.tail.moveTowardsOtherKnot(rope.tail.attachedTo!!) } } } return rope.tail.setOfPlacesVisited.size } fun part2(input: List<String>): Int { val rope = Rope(10) for (move in input) { val (direction, distance) = move.split(" ") for (step in 1..distance.toInt()) { rope.head.moveInDirection(direction) for (knot in rope.knots.drop(1)) { if (knot.distanceFromOtherKnot(knot.attachedTo!!) > 1) { knot.moveTowardsOtherKnot(knot.attachedTo!!) } } } } return rope.tail.setOfPlacesVisited.size } printSolutionFromInputLines("Day09", ::part1) printSolutionFromInputLines("Day09", ::part2) }
0
Kotlin
0
0
3bfa51af6e5e2095600bdea74b4b7eba68dc5f83
2,516
advent_of_code_2022
Apache License 2.0
src/test/kotlin/Day19.kt
christof-vollrath
317,635,262
false
null
import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import java.lang.IllegalArgumentException /* --- Day 19: Monster Messages --- See https://adventofcode.com/2020/day/19 */ fun List<String>.filterMatchingRule(rules: Map<Int, MessageRule>): List<String> { val allValidMessages = generateValidMessages(0, rules) return filter { it in allValidMessages } } fun parseRulesAndMessages(input: String): Pair<Map<Int, MessageRule>, List<String>> { val parts = input.split("\n\n") if (parts.size != 2) throw IllegalArgumentException("Input should have parts rules and messages") val rules = parseMessageRules(parts[0]) val messages = parts[1].split("\n").map { it.trim() } return rules to messages } fun generateValidMessages(ruleId: Int, rules: Map<Int, MessageRule>): Set<String> { return when (val rule = rules[ruleId]) { is MessageCharRule -> setOf(rule.c.toString()) is MessageAlternativesRule -> { val alternatives = rule.alternatives alternatives.flatMap { parts -> val partAlternatives = parts.map { alternativeRuleId -> generateValidMessages(alternativeRuleId, rules) } combine(partAlternatives).map { it.joinToString("") } }.toSet() } else -> throw IllegalArgumentException("Unexpected rule $rule") } } fun parseMessageRules(rulesString: String): Map<Int, MessageRule> = rulesString.split("\n") .map { val rule = parseMessageRule(it) rule.id to rule }.toMap() fun parseMessageRule(ruleString: String): MessageRule { val idAndRule = ruleString.split(":").map{ it.trim() } val id = idAndRule[0].toInt() return if (idAndRule[1].startsWith('"')) MessageCharRule(id, idAndRule[1][1]) else { val ruleParts = idAndRule[1].split("|").map{ it.trim() } val alternatives = ruleParts.map { rulePart -> rulePart.split("""\s+""".toRegex()).map { it.toInt() } } MessageAlternativesRule(id, alternatives) } } sealed class MessageRule { abstract val id: Int } data class MessageAlternativesRule(override val id: Int, val alternatives: List<List<Int>>) : MessageRule() data class MessageCharRule(override val id: Int, val c: Char) : MessageRule() fun List<String>.filterStringsCustomRules(rules: Map<Int, MessageRule>): List<String> { val generated42 = generateValidMessages(42, rules) val generated31 = generateValidMessages(31, rules) val generatedLength = generated42.first().length generated42.forEach { if (it.length != generatedLength) throw IllegalArgumentException("Assuming that all string generated by rule 42 have the same size") } generated31.forEach { if (it.length != generatedLength) throw IllegalArgumentException("Assuming that all string generated by rule 31 have the same size as rule 42") } return filter { str -> checkCustomRule(str, generated42, generated31) } } fun checkCustomRule(str: String, generated42: Set<String>, generated31: Set<String>): Boolean { val generatedLength = generated42.first().length val chunkedString = str.chunked(generatedLength) // Using the fact that all elements in generated42, generated31 have the same size // remove matching rule 31 from back val without31fromLast = chunkedString.dropLastWhile { it in generated31 } val matching31Count = chunkedString.size - without31fromLast.size if (matching31Count == 0) return false // because of rule 31 at least one chunk must match 31 if (! without31fromLast.all { it in generated42}) return false // because of modified rules 8, 11 the start must contain string fulfilling rule 42 if (without31fromLast.size <= matching31Count) return false // because of modified rule 8 there must be more rule-42-strings than rule 31-strings in the back return true } class Day19_Part1 : FunSpec({ context("parse message rules") { context("simple rule") { val ruleString = "10: 4 1 5" val rule = parseMessageRule(ruleString) test("should have parsed rule") { rule shouldBe MessageAlternativesRule(10, listOf(listOf(4, 1, 5))) } } context("rule with alternatives") { val ruleString = "1: 2 3 | 3 2" val rule = parseMessageRule(ruleString) test("should have parsed rule") { rule shouldBe MessageAlternativesRule(1, listOf(listOf(2, 3), listOf(3, 2))) } } context("rule with single char") { val ruleString = """4: "a"""" val rule = parseMessageRule(ruleString) test("should have parsed rule") { rule shouldBe MessageCharRule(4, 'a') } } context("rules") { val rulesString = """ 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" """.trimIndent() val rules = parseMessageRules(rulesString) test("should have parsed all rules") { rules.size shouldBe 6 rules[1] shouldBe MessageAlternativesRule(1, listOf(listOf(2, 3), listOf(3, 2))) rules[5] shouldBe MessageCharRule(5, 'b') } } } context("combine lists") { combine(listOf(listOf(1, 2), listOf(3, 4))) shouldBe listOf(listOf(1, 3), listOf(1, 4), listOf(2, 3),listOf(2, 4)) } context("generate all valid messages") { val rules = parseMessageRules(""" 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" """.trimIndent()) val validMessages = generateValidMessages(0, rules) test("all valid messages should be generated") { validMessages shouldBe setOf("aaaabb", "aaabab", "abbabb", "abbbab", "aabaab", "aabbbb", "abaaab", "ababbb") } } context("parse rules and messages") { val input = """ 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" ababbb bababa abbbab aaabbb aaaabbb """.trimIndent() val (rules, messages) = parseRulesAndMessages(input) test("should have parsed rules and messages") { rules.size shouldBe 6 rules[4] shouldBe MessageCharRule(4, 'a') messages.size shouldBe 5 messages[3] shouldBe "aaabbb" } context("filter messages") { val matchingMessages = messages.filterMatchingRule(rules) test("only the two messages ababbb and abbbab should match") { matchingMessages.toSet() shouldBe setOf("ababbb", "abbbab") } } } }) class Day19_Part1_Exercise: FunSpec({ val input = readResource("day19Input.txt")!! val (rules, messages) = parseRulesAndMessages(input) val matchingMessages = messages.filterMatchingRule(rules) val solution = matchingMessages.size test("should have found solution") { solution shouldBe 233 } }) class Day19_Part2 : FunSpec({ val input = """ 42: 9 14 | 10 1 9: 14 27 | 1 26 10: 23 14 | 28 1 1: "a" 11: 42 31 5: 1 14 | 15 1 19: 14 1 | 14 14 12: 24 14 | 19 1 16: 15 1 | 14 14 31: 14 17 | 1 13 6: 14 14 | 1 14 2: 1 24 | 14 4 0: 8 11 13: 14 3 | 1 12 15: 1 | 14 17: 14 2 | 1 7 23: 25 1 | 22 14 28: 16 1 4: 1 1 20: 14 14 | 1 15 3: 5 14 | 16 1 27: 1 6 | 14 18 14: "b" 21: 14 1 | 1 14 25: 1 1 | 1 14 22: 14 14 8: 42 26: 14 22 | 1 20 18: 15 15 7: 14 5 | 1 21 24: 14 1 abbbbbabbbaaaababbaabbbbabababbbabbbbbbabaaaa bbabbbbaabaabba babbbbaabbbbbabbbbbbaabaaabaaa aaabbbbbbaaaabaababaabababbabaaabbababababaaa bbbbbbbaaaabbbbaaabbabaaa bbbababbbbaaaaaaaabbababaaababaabab ababaaaaaabaaab ababaaaaabbbaba baabbaaaabbaaaababbaababb abbbbabbbbaaaababbbbbbaaaababb aaaaabbaabaaaaababaa aaaabbaaaabbaaa aaaabbaabbaaaaaaabbbabbbaaabbaabaaa babaaabbbaaabaababbaabababaaab aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba """.trimIndent() val (rules, messages) = parseRulesAndMessages(input) context("make sure that unmodified rules act like described") { val matchingMessages = messages.filterMatchingRule(rules) test("only the three messages should match") { matchingMessages.toSet() shouldBe setOf("bbabbbbaabaabba", "ababaaaaaabaaab", "ababaaaaabbbaba") } } context("what is rule 42 producing") { val generated42 = generateValidMessages(42, rules) println(generated42.sorted()) generated42.size shouldBe 16 } context("what is rule 31 producing") { val generated31 = generateValidMessages(31, rules) println(generated31.sorted()) generated31.size shouldBe 16 } context("split string in chunks") { "bbabbbbaabaabb".chunked(2) shouldBe listOf( "bb", "ab", "bb", "ba", "ab", "aa", "bb" ) } context("a valid message should pass the modified rules") { val validMessages = listOf("aaabbbbbbaaaabaababaabababbabaaabbababababaaa") val matchingMessages = validMessages.filterStringsCustomRules(rules) test("this message should match") { matchingMessages.toSet() shouldBe setOf( "aaabbbbbbaaaabaababaabababbabaaabbababababaaa", ) } } context("use a custom filter for part 2") { val matchingMessages = messages.filterStringsCustomRules(rules) test("only some messages should match") { matchingMessages.toSet() shouldBe setOf( "bbabbbbaabaabba", "babbbbaabbbbbabbbbbbaabaaabaaa", "aaabbbbbbaaaabaababaabababbabaaabbababababaaa", "bbbbbbbaaaabbbbaaabbabaaa", "bbbababbbbaaaaaaaabbababaaababaabab", "ababaaaaaabaaab", "ababaaaaabbbaba", "baabbaaaabbaaaababbaababb", "abbbbabbbbaaaababbbbbbaaaababb", "aaaaabbaabaaaaababaa", "aaaabbaabbaaaaaaabbbabbbaaabbaabaaa", "aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba", ) } } }) class Day19_Part2_Exercise: FunSpec({ val input = readResource("day19Input.txt")!! val (rules, messages) = parseRulesAndMessages(input) val matchingMessages = messages.filterStringsCustomRules(rules) val solution = matchingMessages.size test("should have found solution") { solution shouldBe 396 } })
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
11,063
advent_of_code_2020
Apache License 2.0
2022/src/main/kotlin/Day07.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
object Day07 { fun part1(input: String): Int { val root = parseCommandHistory(input) val sizes = getDirectorySizes(root) return sizes.values.filter { it <= 1e5 }.sum() } fun part2(input: String): Int { val root = parseCommandHistory(input) val sizes = getDirectorySizes(root) val neededSpace = sizes[root]!! - 4e7 return sizes .values .sorted() .first { it >= neededSpace } } private fun getDirectorySizes(dir: Entry.Directory): Map<Entry.Directory, Int> { val sizes = mutableMapOf<Entry.Directory, Int>() var currSize = 0 dir.entries.forEach { entry -> when (entry) { is Entry.File -> currSize += entry.size is Entry.Directory -> { sizes.putAll(getDirectorySizes(entry)) currSize += sizes[entry]!! } } } sizes[dir] = currSize return sizes } private fun parseCommandHistory(history: String): Entry.Directory { val root = Entry.Directory("/", null) var curr = root history .splitNewlines() .forEach { cmd -> when { cmd == "$ cd /" -> curr = root cmd == "$ cd .." -> curr = curr.parent!! cmd.startsWith("$ cd") -> curr = curr.entries .filterIsInstance<Entry.Directory>() .find { it.name == cmd.drop(5) }!! cmd == "$ ls" -> {} cmd.startsWith("dir") -> curr.entries.add(Entry.Directory(cmd.drop(4), parent = curr)) else -> curr.entries.add(Entry.File(cmd.splitWhitespace()[0].toInt())) } } return root } sealed class Entry { data class File(val size: Int) : Entry() data class Directory(val name: String, val parent: Directory?) : Entry() { val entries: MutableList<Entry> = mutableListOf() } } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
1,804
advent-of-code
MIT License
src/day8/result.kt
davidcurrie
437,645,413
false
{"Kotlin": 37294}
package day8 import java.io.File data class Line(val input:Set<Set<Char>>, val output: List<Set<Char>>) { private val from: Map<Set<Char>, Int> init { val to = mutableMapOf( 1 to input.find { it.size == 2 }!!, 4 to input.find { it.size == 4 }!!, 7 to input.find { it.size == 3 }!!, 8 to input.find { it.size == 7 }!! ) to[6] = (input - to.values).find { it.size == 6 && (it - to[1]!!).size == 5 }!! to[3] = (input - to.values).find { it.size == 5 && (to[8]!! - it - to[1]!!).size == 2}!! to[5] = (input - to.values).find { it.size == 5 && (it - to[4]!!).size == 2}!! to[9] = (input - to.values).find { (it - to[4]!!).size == 2 }!! to[2] = (input - to.values).find { it.size == 5 }!! to[0] = (input - to.values).single() from = to.entries.associate { (k, v) -> v to k } } fun partOne() = output.map { segments -> if (setOf(1, 4, 7, 8).contains(from[segments])) 1 else 0 }.sum() fun partTwo() = output.fold(0) { acc, segments -> acc * 10 + from[segments]!! } } fun String.toSegments() = split(" ").map { it.toCharArray().toSet() } fun main() { val lines = File("src/day8/input.txt").readLines() .map { it.split(" | ") } .map { line -> Line(line[0].toSegments().toSet(), line[1].toSegments())} println(lines.sumOf { it.partOne() }) println(lines.sumOf { it.partTwo() }) }
0
Kotlin
0
0
dd37372420dc4b80066efd7250dd3711bc677f4c
1,442
advent-of-code-2021
MIT License
src/aoc2023/Day03.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import readInput import checkValue fun main() { val (year, day) = "2023" to "Day03" val directions = listOf(-1, 0, 1) fun resized(board: List<String>): List<String> { val boardLength = board.first().length + 1 val emptyLine = CharArray(boardLength) { '.' }.joinToString("") return buildList { add(emptyLine) addAll(board.map { "$it." }) add(emptyLine) } } fun checkAdjacents(board: List<String>, column: Int, row: Int, filter: (Char, Int, Int) -> Unit) { val length = board.first().length for (dx in directions) { for (dy in directions) { if (dx == 0 && dy == 0) { continue } val x = dx + row val y = dy + column if (y in 0 until length) { filter(board[x][y], x, y) } } } } fun part1(input: List<String>): Long { val board = resized(board = input) return board.mapIndexed { row, line -> var lineSum = 0L var currentNumber = "" var hasSymbolNear = false line.forEachIndexed { column, cell -> if (cell.isDigit()) { currentNumber += cell checkAdjacents(board, column, row) { adj, _, _ -> if (!adj.isDigit() && adj != '.') { hasSymbolNear = true } } } else if (currentNumber.isNotEmpty()) { if (hasSymbolNear) { lineSum += currentNumber.toLong() } currentNumber = "" hasSymbolNear = false } } lineSum }.sum() } fun part2(input: List<String>): Long { val board = resized(board = input) val partsByGear = mutableMapOf<Pair<Int, Int>, MutableList<Long>>() board.forEachIndexed { row, line -> var currentNumber = "" val parts = mutableSetOf<Pair<Int, Int>>() line.forEachIndexed { column, cell -> if (cell.isDigit()) { currentNumber += cell checkAdjacents(board, column, row) { adj, x, y -> if (adj == '*') { parts.add(x to y) } } } else if (currentNumber.isNotEmpty()) { if (parts.isNotEmpty()) { val partNumber = currentNumber.toLong() parts.forEach { pos -> partsByGear.getOrPut(pos) { mutableListOf() }.add(partNumber) } } currentNumber = "" parts.clear() } } } return partsByGear.values.filter { it.size == 2 }.sumOf { it.reduce { acc, l -> acc * l } } } val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput), 4361) println(part1(input)) checkValue(part2(testInput), 467835) println(part2(input)) }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
3,390
aoc-kotlin
Apache License 2.0
year2018/src/main/kotlin/net/olegg/aoc/year2018/day22/Day22.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day22 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.Companion.NEXT_4 import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.parseInts import net.olegg.aoc.year2018.DayOf2018 import java.util.PriorityQueue /** * See [Year 2018, Day 22](https://adventofcode.com/2018/day/22) */ object Day22 : DayOf2018(22) { override fun first(): Any? { val (depthLine, targetLine) = lines.map { it.substringAfter(": ") } val depth = depthLine.toInt() val (tx, ty) = targetLine.parseInts(",") val t = Vector2D(tx, ty) val erosion = ErosionCache(depth.toLong(), t) return (0..tx).sumOf { x -> (0..ty).sumOf { y -> erosion[Vector2D(x, y)].toInt() % 3 } } } override fun second(): Any? { val (depthLine, targetLine) = lines.map { it.substringAfter(": ") } val depth = depthLine.toInt() val (tx, ty) = targetLine.parseInts(",") val t = Vector2D(tx, ty) val target = Config(t, Tool.Torch) val erosions = ErosionCache(depth.toLong(), t) val queue = PriorityQueue<Pair<Config, Int>>( compareBy({ it.second }, { it.first.pos.x }, { it.first.pos.y }, { it.first.tool }), ) val start = Config(Vector2D(), Tool.Torch) val visited = mutableSetOf<Config>() queue.add(start to 0) while (queue.isNotEmpty()) { val (curr, time) = queue.poll() val (pos, tool) = curr if (curr == target) { return time } if (curr in visited) continue visited += curr val surface = erosions[pos] % 3 if (surface !in tool.surfaces) continue queue += Tool.values() .filter { it != tool } .filter { surface in it.surfaces } .map { curr.copy(tool = it) to time + 7 } queue += NEXT_4 .map { curr.copy(pos = curr.pos + it.step) } .filter { it.pos.x >= 0 && it.pos.y >= 0 } .filter { erosions[it.pos] % 3 in it.tool.surfaces } .map { it to time + 1 } } return 0 } private class ErosionCache(val depth: Long, val t: Vector2D) { private val cache = mutableMapOf<Vector2D, Long>() operator fun get(pos: Vector2D): Long { return cache.getOrPut(pos) { when { pos.x == 0 && pos.y == 0 -> 0L pos == t -> 0L pos.y == 0 -> pos.x * 16807L pos.x == 0 -> pos.y * 48271L else -> get(pos.copy(x = pos.x - 1)) * get(pos.copy(y = pos.y - 1)) }.let { (it + depth) % 20183L } } } } private enum class Tool(val surfaces: Set<Long>) { Torch(setOf(0, 2)), Climb(setOf(0, 1)), Neither(setOf(1, 2)) } private data class Config( val pos: Vector2D, val tool: Tool ) } fun main() = SomeDay.mainify(Day22)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,780
adventofcode
MIT License
src/main/kotlin/aoc23/Day11.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc23 import aoc23.Day11Domain.Observatory import aoc23.Day11Parser.toObservatory import com.github.shiguruikai.combinatoricskt.combinations import common.Space2D import common.Space2D.Parser.toPointToChars import common.Year23 object Day11 : Year23 { fun List<String>.part1(): Long = toObservatory(emptySpaceMultiplier = 2) .sumOfShortestPaths() fun List<String>.part2(emptySpaceMultiplier: Int): Long = toObservatory(emptySpaceMultiplier = emptySpaceMultiplier) .sumOfShortestPaths() } object Day11Domain { data class Observatory( private val galaxyMap: Map<Space2D.Point, Char>, private val emptySpaceMultiplier: Int ) { fun sumOfShortestPaths(): Long = expandGalaxies() .toShortestPaths() .sum() private fun expandGalaxies(): Set<Space2D.Point> = galaxyMap .toGalaxies() .expandGalaxies( expandUpFromY = galaxyMap.emptyAlong { it.y }, expandRightFromX = galaxyMap.emptyAlong { it.x }, emptySpaceMultiplier = emptySpaceMultiplier, ) } private fun Map<Space2D.Point, Char>.emptyAlong(function: (Space2D.Point) -> Int): Set<Int> = keys .groupBy(function) .filterValues { points -> points.all { this[it] == '.' } } .keys private fun Map<Space2D.Point, Char>.toGalaxies(): Set<Space2D.Point> = this .filterValues { it != '.' } .keys private fun Set<Space2D.Point>.expandGalaxies( expandUpFromY: Set<Int>, expandRightFromX: Set<Int>, emptySpaceMultiplier: Int ): Set<Space2D.Point> = this.map { point -> point .move( direction = Space2D.Direction.North, by = (expandUpFromY.count { it < point.y } * (emptySpaceMultiplier - 1)) ) .move( direction = Space2D.Direction.East, by = (expandRightFromX.count { it < point.x } * (emptySpaceMultiplier - 1)) ) }.toSet() private fun Set<Space2D.Point>.toShortestPaths(): List<Long> = this.combinations(2) .map { it.first().distanceTo(it.last()).toLong() } .toList() } object Day11Parser { fun List<String>.toObservatory(emptySpaceMultiplier: Int): Observatory = Observatory( galaxyMap = toPointToChars().toMap(), emptySpaceMultiplier = emptySpaceMultiplier ) }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
2,641
aoc
Apache License 2.0
src/main/kotlin/adventofcode2023/day9/day9.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day9 import adventofcode2023.readInput import kotlin.time.measureTime fun main() { println("Day 9") val input = readInput("day9") val puzzle1Time = measureTime { println("Puzzle 1 ${puzzle1(input)}") } println("Puzzle 1 took $puzzle1Time") val puzzle2Time = measureTime { println("Puzzle 2 ${puzzle2(input)}") } println("Puzzle 2 took $puzzle2Time") } fun parseInput(input: List<String>): List<List<Int>> { return input.map { line -> line.split(' ') .filter { it.isNotEmpty() } .map { it.toInt() } } } fun predictNext(input: List<Int>): Int { val difference = input.windowed(size = 2).map { (f,s) -> s - f } // println("difference = $difference") return if (difference.all { it == 0 }) { input.last } else { val predicted = predictNext(difference) input.last() + predicted } } fun puzzle1(input: List<String>): Int = parseInput(input).sumOf { predictNext(it) } fun predictPrevious(input: List<Int>): Int { // println("input = $input") val difference = input.windowed(size = 2).map { (f,s) -> s - f } // println("difference = $difference") return if (difference.all { it == 0 }) { input.first } else { val predicted = predictPrevious(difference) input.first - predicted } } fun puzzle2(input: List<String>): Int = parseInput(input).sumOf { predictPrevious(it) }
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
1,462
adventofcode2023
MIT License
src/Day03/Day03.kt
JamesKing95
574,470,043
false
{"Kotlin": 7225}
package Day03 import readInput private val ALPHABET_INDEX = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun main() { val testInput = readInput("Day03/Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03/Day03") println("Part 1: ".plus(part1(input))) println("Part 2: ".plus(part2(input))) } fun part1(input: List<String>): Int { var total = 0 input.forEach{ // Split the line in half val halfWayPoint = it.length / 2 val firstHalf = it.take(halfWayPoint) val secondHalf = it.takeLast(halfWayPoint).split("").drop(1).dropLast(1) // Compare two halves and find common value val matchingCharacter = firstHalf.findAnyOf(secondHalf, 0, false)!!.second // Compare common value to priority table. val priority = ALPHABET_INDEX.indexOf(matchingCharacter) + 1 // Add up all priority values. total += priority } return total } fun part2(input: List<String>): Int { //Find groups of 3 lines val currentGroup = mutableListOf<String>() var total = 0 input.forEach{ currentGroup.add(it) if(currentGroup.size == 3) { val firstElf = currentGroup[0] val secondElf = currentGroup[1].split("").drop(1).dropLast(1).toMutableList() // Find all common items between Elf one and two val elfOneAndTwoCommonItems = mutableListOf<String>() var currentMatchingItem = firstElf.findAnyOf(secondElf, 0, false)?.second while(!currentMatchingItem.isNullOrBlank()) { elfOneAndTwoCommonItems.add(currentMatchingItem) while(secondElf.contains(currentMatchingItem)) { // Remove any duplicate matching items from secondElf to not match them again. secondElf.remove(currentMatchingItem) } currentMatchingItem = firstElf.findAnyOf(secondElf, 0, false)?.second } // Find the one matching item between elf three and array of all matches between one and two. val idCardValue = currentGroup[2].findAnyOf(elfOneAndTwoCommonItems, 0, false)!!.second // Calculate priority value from index val priority = ALPHABET_INDEX.indexOf(idCardValue) + 1 // Add to total total += priority // Clear current working group so can focus on the next three elves. currentGroup.clear() } } return total }
0
Kotlin
0
0
cf7b6bd5ae6e13b83d871dfd6f0a75b6ae8f04cf
2,553
aoc-2022-in-kotlin
Apache License 2.0
day25/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
import java.io.File fun main() { val points = parseInput(readInputFile()) println("The solution is ${solveProblem(points)}.") } fun readInputFile(): List<String> { return File(ClassLoader.getSystemResource("input.txt").file).readLines() } fun parseInput(input: List<String>): List<Coordinate4d> { val fixedPointRegex = "(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+)".toRegex() return input .map { instruction -> val ints = fixedPointRegex.matchEntire(instruction)!!.destructured.toList().map(String::toInt) Coordinate4d.fromInput(ints) } } fun solveProblem(points: List<Coordinate4d>): Int { val constellations = mutableListOf<MutableList<Coordinate4d>>() points.forEach { point -> val newConstellation = mutableListOf<Coordinate4d>() newConstellation.add(point) val iterator = constellations.listIterator() while (iterator.hasNext()) { val constellation = iterator.next() var i = 0 var keepGoing = true while (keepGoing) { val constellationPoint = constellation[i] when { point.taxicabDistanceTo(constellationPoint) <= 3 -> { newConstellation.addAll(constellation) iterator.remove() keepGoing = false } i == constellation.size - 1 -> keepGoing = false else -> i++ } } } iterator.add(newConstellation) } return constellations.size } data class Coordinate4d(var x: Int, var y: Int, var z: Int, var t: Int) { companion object { fun fromInput(ints: List<Int>): Coordinate4d { return Coordinate4d(ints[0], ints[1], ints[2], ints[3]) } } fun taxicabDistanceTo(other: Coordinate4d): Int { return Math.abs(other.x - this.x) + Math.abs(other.y - this.y) + Math.abs(other.z - this.z) + Math.abs(other.t - this.t) } }
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
2,067
AdventOfCode2018
MIT License
src/main/kotlin/days/Day16.kt
hughjdavey
317,575,435
false
null
package days import splitOnBlank class Day16 : Day(16) { private val ticketFields: List<TicketField> private val yourTicket: List<Int> private val nearbyTickets: List<List<Int>> init { val (fields, your, nearby) = if (customInput != null) customInput!!.splitOnBlank() else inputList.splitOnBlank() ticketFields = fields .map { Regex("(\\w+ ?\\w+?): (\\d+-\\d+) or (\\d+-\\d+)").matchEntire(it)!!.groupValues } .map { (_, name, range1, range2) -> TicketField(name, dashRangeToList(range1).plus(dashRangeToList(range2))) } yourTicket = your.last().split(",").map { it.toInt() } nearbyTickets = nearby.drop(1).map { it.split(",").map { it.toInt() } } } private fun dashRangeToList(dashRange: String): List<Int> { val (lo, hi) = dashRange.split("-").map { it.toInt() } return (lo..hi).toList() } // 23925 override fun partOne(): Any { return nearbyTickets .map { ticket -> ticket.map { it to ticketFields.notValidForAny(it) } } .flatten().filter { it.second } .sumBy { it.first } } // 964373157673 override fun partTwo(): Any { return getSolvedTicket() .filter { it.first.startsWith("departure") } .fold(1L) { acc, elem -> acc * elem.second } } // todo make more functional! fun getSolvedTicket(): List<Pair<String, Int>> { val nearbyTickets = nearbyTickets.filterNot { ticket -> ticket.any { ticketFields.notValidForAny(it) } } val allRows = (0..nearbyTickets.first().lastIndex).map { idx -> nearbyTickets.map { it[idx] } } val potentialFields = allRows.map { r -> ticketFields.filter { it.valid.containsAll(r) }.map { it.name }.toMutableList() }.toMutableList() val realFields = Array(ticketFields.size) { "" } while (realFields.any { it == "" }) { potentialFields.forEachIndexed { index, potentials -> when { potentials.isEmpty() -> return@forEachIndexed potentials.size == 1 -> realFields[index] = potentials.removeAt(0) else -> potentials.removeIf { realFields.contains(it) } } } } return realFields.zip(yourTicket) } data class TicketField(val name: String, val valid: List<Int>, var value: Int = -1) private fun List<TicketField>.notValidForAny(value: Int): Boolean { return this.none { it.valid.contains(value) } } companion object { // hack for testing var customInput: List<String>? = null } }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
2,642
aoc-2020
Creative Commons Zero v1.0 Universal
lib/src/main/kotlin/com/bloidonia/advent/day19/Day19.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day19 import java.lang.StrictMath.pow import kotlin.math.sqrt data class Vector(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Vector) = Vector(x + other.x, y + other.y, z + other.z) operator fun times(other: Vector) = Vector(x * other.x, y * other.y, z * other.y) fun distance(other: Vector) = sqrt( pow(other.x - x.toDouble(), 2.0) + pow(other.y - y.toDouble(), 2.0) + pow(other.z - z.toDouble(), 2.0) ) } fun <T, S> Collection<T>.cartesianProduct(other: Iterable<S>): List<Pair<T, S>> { return cartesianProduct(other) { first, second -> first to second } } fun <T, S, V> Collection<T>.cartesianProduct(other: Iterable<S>, transformer: (first: T, second: S) -> V): List<V> { return this.flatMap { first -> other.map { second -> transformer.invoke(first, second) } } } class Scanner(val readings: List<Vector>) { fun distance(index: Int) = readings.map { readings[index].distance(it) } } fun String.toScanners() = this.split("\n\n").map { Scanner(readings = it.split("\n") .drop(1) .map { line -> line.split(",").let { (x, y, z) -> Vector(x.toInt(), y.toInt(), z.toInt()) } } ) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
1,252
advent-of-kotlin-2021
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/BurstBalloons.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.max /** * 312. Burst Balloons * @see <a href="https://leetcode.com/problems/burst-balloons/">Source</a> */ fun interface BurstBalloons { fun maxCoins(nums: IntArray): Int } class BurstBalloonsMemoization : BurstBalloons { override fun maxCoins(nums: IntArray): Int { val n: Int = nums.size val arr = IntArray(n + 2) arr[0] = 1.also { arr[n + 1] = it } for (i in 1..n) { arr[i] = nums[i - 1] } val memo = Array(n + 2) { IntArray(n + 2) } return burst(memo, arr, 0, n + 1) } fun burst(memo: Array<IntArray>, nums: IntArray, left: Int, right: Int): Int { if (left + 1 == right) return 0 if (memo[left][right] > 0) return memo[left][right] var ans = 0 for (i in left + 1 until right) { ans = max( ans, nums[left] * nums[i] * nums[right] + burst(memo, nums, left, i) + burst(memo, nums, i, right), ) } memo[left][right] = ans return ans } } class BurstBalloonsDP : BurstBalloons { override fun maxCoins(nums: IntArray): Int { val n: Int = nums.size val arr = IntArray(n + 2) arr[0] = 1.also { arr[n + 1] = it } // Giving padding of 1 to the corner elements for (i in 1..n) { arr[i] = nums[i - 1] // final padded array } val dp = Array(n + 2) { IntArray(n + 2) } for (window in 1..n) { // window size for (left in 1..n - window + 1) { // left pointer val right = left + window - 1 // right pointer for (i in left..right) { dp[left][right] = max( dp[left][right], arr[left - 1] * arr[i] * arr[right + 1] + dp[left][i - 1] + dp[i + 1][right], ) } } } return dp[1][n] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,587
kotlab
Apache License 2.0
src/main/kotlin/days/Day7.kt
mstar95
317,305,289
false
null
package days class Day7 : Day(7) { override fun partOne(): Any { val bags: Map<String, List<String>> = parse(inputList) .map { it.key to it.value.map { p -> p.first } } .toMap() val bag = bags.keys.map { findBag(bags, it, "shiny gold bag") } return bag.filter { it }.size } override fun partTwo(): Any { val bags = parse(inputList) println(bags) val count = countBadges(bags, "shiny gold bag") - 1 return count } } private fun parse(inputList: List<String>): Map<String, List<Pair<String, Int>>> { return inputList.map { parse(it) }.toMap() } fun parse(inputList: String): Pair<String, List<Pair<String, Int>>> { val spliced = inputList.split(" contain ") require(spliced.size == 2) { "Splited should have size of 2" } val key = bagsToBag(spliced[0]) val rest = spliced[1].split(", ") val bags = parseBags(rest) return key to bags } private fun parseBags(bags: List<String>): List<Pair<String, Int>> { if (bags.size == 1) { if (bags[0] == "no other bags.") { return emptyList() } } return bags.map { deleteDot(it) }.map { bagsToBag(it) } .map { deleteNumbers(it) to it[0].toString().toInt() } } private fun deleteNumbers(it: String) = it.drop(2) private fun deleteDot(it: String) = if (it.contains('.')) it.dropLast(1) else it private fun bagsToBag(s: String) = s.replace("bags", "bag") val memo: MutableMap<Pair<String,String>, Boolean> = mutableMapOf() fun findBag(map: Map<String, List<String>>, actual: String, bag: String): Boolean { val memoized = memo[actual to bag] if(memoized != null) { return memoized } val bags = map[actual] ?: error("No key $actual") val result = if (bags.contains(bag)) true else bags.asSequence() .map { findBag(map, it, bag) } .any { it } memo[actual to bag] = result return result } val memo2: MutableMap<String, Int> = mutableMapOf() fun countBadges(map: Map<String, List<Pair<String, Int>>>, actual: String): Int { val memoized = memo2[actual] if(memoized != null) { return memoized } val bags = map[actual] ?: error("No key $actual") if (bags.isEmpty()) { return 1 } val sum = bags.map { it.second * countBadges(map, it.first) }.sum() + 1 memo2[actual] = sum return sum }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
2,424
aoc-2020
Creative Commons Zero v1.0 Universal
aoc-2021/src/main/kotlin/nerok/aoc/aoc2021/day05/Day05.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2021.day05 import nerok.aoc.utils.Input import kotlin.math.abs import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: List<String>): Long { val coordinates = mutableListOf<List<Pair<Int, Int>>>() var size = 0 input.forEach { fileLine -> fileLine .split("->") .map { coordinates -> coordinates .split(",") .map { coordinate -> Integer.parseInt(coordinate.filter { !it.isWhitespace() }).also { if (it > size) { size = it } } }.let { it.first() to it.last() } }.let { coordinatePair -> if (coordinatePair.first().first == coordinatePair.last().first) { val lowerEnd = minOf(coordinatePair.first().second, coordinatePair.last().second) val higherEnd = maxOf(coordinatePair.first().second, coordinatePair.last().second) return@let IntRange(lowerEnd, higherEnd).map { coordinatePair.first().first to it } } else if (coordinatePair.first().second == coordinatePair.last().second) { val lowerEnd = minOf(coordinatePair.first().first, coordinatePair.last().first) val higherEnd = maxOf(coordinatePair.first().first, coordinatePair.last().first) return@let IntRange(lowerEnd, higherEnd).map { it to coordinatePair.first().second } } else { return@let emptyList() } }.let { coordinates.add(it) } } val area = Array(size+1) { IntArray(size+1) { 0 } } coordinates.flatten().forEach { area[it.second][it.first] = area[it.second][it.first] + 1 } val hotpoints = area.map { it.filter { it > 1 } }.flatten().count() return hotpoints.toLong() } fun part2(input: List<String>): Long { val coordinates = mutableListOf<List<Pair<Int, Int>>>() var size = 0 input.forEach { fileLine -> fileLine .split("->") .map { coordinates -> coordinates .split(",") .map { coordinate -> Integer.parseInt(coordinate.filter { !it.isWhitespace() }).also { if (it > size) { size = it } } }.let { it.first() to it.last() } }.let { coordinatePair -> if (coordinatePair.first().first == coordinatePair.last().first) { val lowerEnd = minOf(coordinatePair.first().second, coordinatePair.last().second) val higherEnd = maxOf(coordinatePair.first().second, coordinatePair.last().second) return@let IntRange(lowerEnd, higherEnd).map { coordinatePair.first().first to it } } else if (coordinatePair.first().second == coordinatePair.last().second) { val lowerEnd = minOf(coordinatePair.first().first, coordinatePair.last().first) val higherEnd = maxOf(coordinatePair.first().first, coordinatePair.last().first) return@let IntRange(lowerEnd, higherEnd).map { it to coordinatePair.first().second } } else { val firstDistance = abs(coordinatePair.first().first - coordinatePair.last().first) val secondDistance = abs(coordinatePair.first().second - coordinatePair.last().second) if (firstDistance == secondDistance) { val lowerFirst = minOf(coordinatePair.first().first, coordinatePair.last().first) val higherFirst = maxOf(coordinatePair.first().first, coordinatePair.last().first) val firstRange = IntRange(lowerFirst, higherFirst).toList() val lowerSecond = minOf(coordinatePair.first().second, coordinatePair.last().second) val higherSecond = maxOf(coordinatePair.first().second, coordinatePair.last().second) val secondRange = IntRange(lowerSecond, higherSecond).toList() val reverseFirst = coordinatePair.first().first != firstRange.first() val reverseSecond = coordinatePair.first().second != secondRange.first() return@let firstRange.mapIndexed { index, i -> if (reverseFirst xor reverseSecond) { i to secondRange[secondDistance - index] } else { i to secondRange[index] } } } else { return@let emptyList() } } }.let { coordinates.add(it) } } val area = Array(size+1) { IntArray(size+1) { 0 } } coordinates.flatten().forEach { area[it.second][it.first] = area[it.second][it.first] + 1 } val hotpoints = area.map { it.filter { it > 1 } }.flatten().count() return hotpoints.toLong() } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day05_test") check(part1(testInput) == 5L) check(part2(testInput) == 12L) val input = Input.readInput("Day05") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
6,272
AOC
Apache License 2.0
src/Day17.kt
ked4ma
573,017,240
false
{"Kotlin": 51348}
import kotlin.math.max /** * [Day17](https://adventofcode.com/2022/day/17) */ private class Day17 { data class Rock(val array: List<List<Char>>) { val height = array.size val width = array[0].size } companion object { val ROCKS = listOf( Rock(listOf("####".toList())), Rock(".#.|###|.#.".split("|").map(String::toList)), Rock("..#|..#|###".split("|").map(String::toList)), Rock("#|#|#|#".split("|").map(String::toList)), Rock("##|##".split("|").map(String::toList)) ) } } fun main() { fun fallHist(winds: String, num: Int): List<Int> { var topHist = mutableListOf(0) val chamber = mutableListOf(Array(7) { '-' }) var top = 0 var windIndex = 0 fun fall(rock: Day17.Rock) { repeat((top + rock.height + 3) - chamber.lastIndex) { chamber.add(".......".toCharArray().toTypedArray()) } var rockHeight = top + rock.height + 3 var rockLeft = 2 fun isCross(height: Int, left: Int): Boolean { rock.array.forEachIndexed { h, row -> row.forEachIndexed { w, v -> if (v == '.') return@forEachIndexed if (chamber[height - h][left + w] != '.') return true } } return false } do { val rockMove = if (winds[windIndex % winds.length] == '>') 1 else -1 windIndex++ var moves = 0 rockLeft = when { rockLeft + rockMove !in 0..7 - rock.width -> rockLeft isCross(rockHeight, rockLeft + rockMove) -> rockLeft else -> { rockLeft + rockMove } } if (!isCross(rockHeight - 1, rockLeft)) { rockHeight-- moves++ } } while (moves > 0) rock.array.forEachIndexed { h, row -> row.forEachIndexed { w, v -> if (v == '#') { chamber[rockHeight - h][rockLeft + w] = v } } } top = max(top, rockHeight) } repeat(num) { fall(Day17.ROCKS[it % Day17.ROCKS.size]) topHist.add(top) } return topHist } fun part1(input: String): Int { return fallHist(input, 2022).last() } fun part2(input: String): Long { val topHist = fallHist(input, 5000) val diff = (1..topHist.lastIndex).map { topHist[it] - topHist[it - 1] } fun findRepeat(start: Int): Pair<Int, Int>? { var len = 10 // want to exclude little value like 1, 2, ... while (start + 2 * len < diff.lastIndex) { if (diff.subList(start, start + len) == diff.subList(start + len, start + 2 * len)) { return start to len } len++ } return null } var i = 0 val start: Int val len: Int while (true) { val d = findRepeat(i) if (d == null) { i++ continue } start = d.first len = d.second break } val loops = (1_000_000_000_000 - start) / len val rem = (1_000_000_000_000 - start) % len return diff.subList(0, start).sum().toLong() + loops * diff.subList(start, start + len).sum().toLong() + diff.subList(start, start + rem.toInt()).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day17_test") check(part1(testInput[0]) == 3068) check(part2(testInput[0]) == 1_514_285_714_288L) val input = readInput("Day17") println(part1(input[0])) println(part2(input[0])) }
1
Kotlin
0
0
6d4794d75b33c4ca7e83e45a85823e828c833c62
4,074
aoc-in-kotlin-2022
Apache License 2.0
src/Day02.kt
dustinlewis
572,792,391
false
{"Kotlin": 29162}
fun main() { fun part1(input: List<String>): Int { return input.fold(0) { acc, el -> val (opponentLetter, myLetter) = el.split(" ") acc + calculateMatchScore(opponentLetter, myLetter) } } fun part2(input: List<String>): Int { return input.fold(0) { acc, el -> val (opponentLetter, myLetter) = el.split(" ") acc + calculateMatchScoreForDesiredOutcome(opponentLetter, myLetter) } } val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun calculateMatchScore(opponentLetter: String, myLetter: String): Int { val outcome = getOutcomeForLetterCodes(opponentLetter, myLetter) val myChoice = getChoiceFromLetterCode(myLetter) return outcome.pointValue + myChoice.pointValue } fun calculateMatchScoreForDesiredOutcome(opponentLetter: String, myLetter: String): Int { val desiredOutcome = getDesiredOutcomeFromLetterCode(myLetter) val choice = getChoiceForOutcome(opponentLetter, desiredOutcome) return desiredOutcome.pointValue + choice.pointValue } enum class Choice(val pointValue: Int) { ROCK(1), PAPER(2), SCISSORS(3); fun defeats(): Choice = when(this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } fun losesTo(): Choice = when(this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } } enum class MatchOutcome(val pointValue: Int) { LOSE(0), DRAW(3), WIN(6), } fun getChoiceFromLetterCode(letterCode: String): Choice = when(letterCode) { "A", "X" -> Choice.ROCK "B", "Y" -> Choice.PAPER "C", "Z" -> Choice.SCISSORS else -> { throw Throwable("Unknown letter code") } } fun getDesiredOutcomeFromLetterCode(letterCode: String): MatchOutcome = when(letterCode) { "X" -> MatchOutcome.LOSE "Y" -> MatchOutcome.DRAW "Z" -> MatchOutcome.WIN else -> { throw Throwable("Unknown letter code") } } fun getChoiceForOutcome(opponentLetter: String, desiredOutcome: MatchOutcome): Choice { val opponentChoice = getChoiceFromLetterCode(opponentLetter) return when(desiredOutcome) { MatchOutcome.DRAW -> opponentChoice MatchOutcome.WIN -> opponentChoice.losesTo() MatchOutcome.LOSE -> opponentChoice.defeats() } } fun getOutcomeForLetterCodes(opponentLetter: String, myLetter: String) : MatchOutcome { val opponentChoice = getChoiceFromLetterCode(opponentLetter) val myChoice = getChoiceFromLetterCode(myLetter) return when (myChoice) { opponentChoice -> MatchOutcome.DRAW opponentChoice.losesTo() -> MatchOutcome.WIN else -> MatchOutcome.LOSE } }
0
Kotlin
0
0
c8d1c9f374c2013c49b449f41c7ee60c64ef6cff
2,837
aoc-2022-in-kotlin
Apache License 2.0
src/test/kotlin/aoc2016/day7/IPAddresses.kt
arnab
75,525,311
false
null
package aoc2016.day7 data class IpAddress(val address: String) { fun supportsSsl(): Boolean { println("Testing: $address") val (supernets, hypernets) = partitionSequences(address) println("Supernet sequences: $supernets") println("Hypernet sequences: $hypernets") val abaPatterns = findAbaMatches(supernets) val babPatterns = abaPatterns.map { (a, b) -> Pair(b, a) } println("Checking if any of the BAB patterns ($babPatterns) are in the hypernets.") val babInHypernets = babPatterns.any { patternFoundIn(it, hypernets) } println("Verifying that none of the ABA patterns ($abaPatterns) are in the hypernets.") val abaNotInHypernets = abaPatterns.none { patternFoundIn(it, hypernets) } return babInHypernets // && abaNotInHypernets } private val supernetMatcher = Regex("(\\w+)(?![^\\[]*\\])") private val hypernetMatcher = Regex("""\[(\w+)\]""") private fun partitionSequences(address: String): Pair<List<String>, List<String>> { val hypernets: List<String> = findAllNthMatchedGroups(hypernetMatcher, address, 1) val supernets: List<String> = findAllNthMatchedGroups(supernetMatcher, address, 1) return Pair(supernets, hypernets) } private fun findAllNthMatchedGroups(regex: Regex, s: String, matchGroup: Int): List<String> = regex.findAll(s) .toList() .map { it.groups[matchGroup]?.value!! } private val abaMatcher = Regex("""([a-z])([a-z])\1""") private fun findAbaMatches(strings: List<String>): List<Pair<Char, Char>> { val abaMatches = strings.map { s -> var matches: MutableList<MatchResult> = mutableListOf() for (i in 0 until s.count()) { val subStr = s.subSequence(i, s.count()) matches.addAll(abaMatcher.findAll(subStr).toList()) } matches.map { m -> val (_, a, b) = m.groupValues if (a != b) { Pair(a.toCharArray()[0], b.toCharArray()[0]) } else null } } val uniqueAbaMatches = abaMatches.flatten().filter { it != null }.map { it!! }.distinct() println("Found ABA patterns: $uniqueAbaMatches") return uniqueAbaMatches } private fun patternFoundIn(chars: Pair<Char, Char>, strings: List<String>): Boolean { val (a, b) = chars val pattern = Regex("$a$b$a") val stringsMatchingPattern = strings.filter { pattern.containsMatchIn(it) } if (stringsMatchingPattern.any()) println("Following strings contain $pattern: $stringsMatchingPattern") return stringsMatchingPattern.any() } } object IPAddresses { fun supportsSsl(data: String): List<IpAddress> { val (accepted, rejected) = data.lines() .map(String::trim) .filter(String::isNotBlank) .map { IpAddress(it) } .partition(IpAddress::supportsSsl) println("Following ${accepted.count()} IP Addresses support SLL:") accepted.forEach { println("\t ✔ $it") } println("Following ${rejected.count()} IP Addresses DO NOT support SLL:") rejected.forEach { println("\t ✘ $it") } return accepted } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
3,327
adventofcode
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day13.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.P import se.saidaspen.aoc.util.permutations fun main() = Day13.run() object Day13 : Day(2015, 13) { private val inpMap = input.lines().associate { val split = it.split(" ") val points = if (split[2] == "gain") split[3].toInt() else -split[3].toInt() val to = split[10].replace(".", "") P(split[0] + "-" + to, points) } override fun part1(): Any { val participants = inpMap.flatMap { it.key.split("-").toList() }.distinct().toList() return participants.permutations().map { toHappiness(it) }.maxOrNull()!! } override fun part2(): Any { val participants = inpMap.flatMap { it.key.split("-").toList() }.distinct().toMutableList() participants.add("self") return participants.permutations().map { toHappiness(it) }.maxOrNull()!! } private fun toHappiness(conf: List<String>) : Int { var sum = 0 for (i in conf.indices){ val left = conf[i] + "-" + conf[(i - 1).mod(conf.size)] val right = conf[i] + "-" + conf[(i + 1).mod(conf.size)] sum += if(left.contains("self")) 0 else inpMap[left]!! sum += if(right.contains("self")) 0 else inpMap[right]!! } return sum } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,348
adventofkotlin
MIT License
src/main/kotlin/days/Day21.kt
andilau
399,220,768
false
{"Kotlin": 85768}
package days @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2020/day/21", date = Date(day = 21, year = 2020) ) class Day21(lines: List<String>) : Puzzle { private val food = readFood(lines) private val allergens = food.values.flatten().toSet() override fun partOne(): Int { val goodIngredients: Set<String> = goodIngredients() return food.keys .sumOf { ingredients -> ingredients.count { it in goodIngredients } } } override fun partTwo(): String { val allergenPossibleIngredients: MutableMap<String, Set<String>> = allergenPossibleIngredients() val allergenExactIngredient = mutableListOf<Pair<String, String>>() while (allergenPossibleIngredients.isNotEmpty()) { val (a, i) = allergenPossibleIngredients.entries.first { it.value.size == 1 } allergenPossibleIngredients.remove(a) allergenPossibleIngredients.replaceAll { _, recipe -> recipe - i } allergenExactIngredient.add(a to i.first()) } return allergenExactIngredient.sortedBy { it.first }.joinToString(",") { it.second } } private fun allergenPossibleIngredients(): MutableMap<String, Set<String>> { val good: Set<String> = goodIngredients() return allergens.associateWith { allergen -> food.entries .filter { allergen in it.value } .map { it.key - good } .reduce { a, b -> a intersect b } }.toMutableMap() } private fun goodIngredients(): Set<String> { val allIngredients = food.keys.flatten().toSet() val badIngredients = allergens.associateWith { allergen -> food .filter { allergen in it.value } .map { it.key } .reduce { acc, i -> i intersect acc } }.values.flatten().toSet() return allIngredients - badIngredients } private fun readFood(lines: List<String>): Map<Set<String>, Set<String>> = lines.associate { line -> val foods = line.substringBefore(" (contains ") .split(" ").toSet() val allergens = line.substringAfter(" (contains ").substringBefore(")") .split(", ").toSet() foods to allergens } }
7
Kotlin
0
0
2809e686cac895482c03e9bbce8aa25821eab100
2,339
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/day2/Solution.kt
chipnesh
572,700,723
false
{"Kotlin": 48016}
package day2 import day2.Result.DRAW import day2.Result.LOOSE import day2.Result.WIN import readInput fun main() { fun part1(input: List<String>): Int { return input.sumOf { round -> val (f, s) = round.split(" ") Figure.of(s).fightClassic(Figure.of(f)).score } } fun part2(input: List<String>): Int { return input.sumOf { round -> val (f, s) = round.split(" ") Figure.of(s).fightElfStrategy(Figure.of(f)).score } } //val input = readInput("test") val input = readInput("prod") println(part1(input)) println(part2(input)) } sealed class Result(val score: Int) { class WIN(score: Int) : Result(score + 6) class DRAW(score: Int) : Result(score + 3) class LOOSE(score: Int) : Result(score) } enum class Figure(private val score: Int) { ROCK(1) { override val beats by lazy { SCISSOR } override val beatenBy by lazy { PAPER } }, PAPER(2) { override val beats by lazy { ROCK } override val beatenBy by lazy { SCISSOR } }, SCISSOR(3) { override val beats by lazy { PAPER } override val beatenBy by lazy { ROCK } }; abstract val beats: Figure abstract val beatenBy: Figure fun fightClassic(other: Figure): Result { return when (this) { other.beatenBy -> WIN(score) other.beats -> LOOSE(score) else -> DRAW(score) } } fun fightElfStrategy(other: Figure): Result { return when (this) { ROCK -> LOOSE(other.beats.score) PAPER -> DRAW(other.score) SCISSOR -> WIN(other.beatenBy.score) } } companion object { fun of(s: String): Figure { return when (s) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSOR else -> error("oops") } } } }
0
Kotlin
0
1
2d0482102ccc3f0d8ec8e191adffcfe7475874f5
1,973
AoC-2022
Apache License 2.0
src/main/kotlin/day07/day07.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package main.day07 import main.utils.Stack import utils.readFile import utils.separator fun main() { val test = readFile("day07_test") val input = readFile("day07") data class FileInfo(val name: String, val size: Int) class Directory(val name: String) { private val files = mutableMapOf<String, FileInfo>() private val directories = mutableMapOf<String, Directory>() fun listDirectories() = directories.values.toList() fun hasDir(dirname: String): Boolean = directories.containsKey(dirname) fun getDir(dirname: String) = directories[dirname] fun addDir(dirname: String): Directory = directories.getOrPut(dirname) { Directory(dirname) } fun addFile(name: String, size: Int): FileInfo { val file = FileInfo(name, size) files[name] = file return file } fun listFiles(): List<FileInfo> = files.values.toList() fun fileSizes(): Int = files.values.sumOf { it.size } fun totalSize(): Int = fileSizes() + directories.values.sumOf { it.totalSize() } override fun toString(): String { return "Directory(name='$name',directories=${ directories.values.map { it.name }.toList() },files=${files.values.map { "${it.name}:${it.size}" }})" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Directory if (name != other.name) return false return true } override fun hashCode(): Int { return name.hashCode() } private fun printTree(dir: Directory, depth: Int) { println("- ${dir.name} (dir)") val prefix = 0 until depth dir.listDirectories().forEach { prefix.forEach { _ -> print(' ') } printTree(it, depth + 2) } dir.listFiles().forEach { prefix.forEach { _ -> print(' ') } println("- ${it.name} (file, size = ${it.size})") } } fun printTree() = printTree(this, 0) } fun listAllDirectories(directories: Directory): List<Directory> { val result = mutableListOf<Directory>() directories.listDirectories().forEach { result.add(it) result.addAll(listAllDirectories(it)) } return result } fun parseCommandsAndOutput(lines: List<String>): Directory { val root = Directory("/") val dirs = Stack<Directory>() dirs.push(root) var current = root for(line in lines) { val data = line.split(" ") when { data[0] == "$" && data[1] == "cd" && data[2] == "/" -> { dirs.clear(); dirs.push(root); current = dirs.peek() } data[0] == "$" && data[1] == "cd" && data[2] == ".." -> { dirs.pop(); current = dirs.peek()} data[0] == "$" && data[1] == "cd" -> { dirs.push(current.addDir(data[2])); current = dirs.peek() } data[0] == "$" && data[1] == "ls" -> println("listing ${dirs.items().joinToString("/") { it.name }}") data[0] == "dir" -> current.addDir(data[1]) else -> { val file = current.addFile(data[1], data[0].toInt()) println("file=dir:${current.name} + ${file.name}:${file.size}") } } } return root } fun calcDirectoriesBelow(input: List<String>, maxValue: Int): Int { val root = parseCommandsAndOutput(input) separator() root.printTree() separator() val directories = listAllDirectories(root) return directories.map { it.totalSize() }.filter { it <= maxValue }.sum() } fun calcDirectoriesToFree(input: List<String>, diskSize: Int, freeSpace: Int): Int { val root = parseCommandsAndOutput(input) val directories = listAllDirectories(root) val unused = diskSize - root.totalSize() val requiredDelete = freeSpace - unused return directories.map { it.totalSize() }.filter { it > requiredDelete }.min() } fun part1() { val testResult = calcDirectoriesBelow(test, 100000) println("Part 1 Answer = $testResult") check(testResult == 95437) separator() val result = calcDirectoriesBelow(input, 100000) check(result == 1792222) println("Part 1 Answer = $result") separator() } fun part2() { val testResult = calcDirectoriesToFree(test, 70000000, 30000000) println("Part 2 Answer = $testResult") check(testResult == 24933642) separator() val result = calcDirectoriesToFree(input, 70000000, 30000000) println("Part 2 Answer = $result") check(result == 1112963) separator() } println("Day - 07") part1() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
4,493
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindLongestChain.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 /** * 646. Maximum Length of Pair Chain * @see <a href="https://leetcode.com/problems/maximum-length-of-pair-chain">Source</a> */ fun interface FindLongestChain { operator fun invoke(pairs: Array<IntArray>): Int } /** * Approach 1: Recursive Dynamic Programming */ class FindLongestChainRecursive : FindLongestChain { override operator fun invoke(pairs: Array<IntArray>): Int { val n = pairs.size pairs.sortWith(compareBy { it[0] }) val memo = IntArray(n) var ans = 0 for (i in 0 until n) { ans = ans.coerceAtLeast(longestPairChain(i, pairs, n, memo)) } return ans } private fun longestPairChain(i: Int, pairs: Array<IntArray>, n: Int, memo: IntArray): Int { if (memo[i] != 0) { return memo[i] } memo[i] = 1 for (j in i + 1 until n) { if (pairs[i][1] < pairs[j][0]) { memo[i] = memo[i].coerceAtLeast(1 + longestPairChain(j, pairs, n, memo)) } } return memo[i] } } class FindLongestChainIterative : FindLongestChain { override operator fun invoke(pairs: Array<IntArray>): Int { val n = pairs.size pairs.sortWith(compareBy { it[0] }) val dp = IntArray(n) { 1 } var ans = 1 for (i in n - 1 downTo 0) { for (j in i + 1 until n) { if (pairs[i][1] < pairs[j][0]) { dp[i] = maxOf(dp[i], 1 + dp[j]) } } ans = maxOf(ans, dp[i]) } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,228
kotlab
Apache License 2.0
src/aoc2023/Day1.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2023 import utils.alsoPrintln import utils.checkEquals import utils.checkNotEquals import utils.readInput fun main(): Unit = with(Day1) { part1(testInput.take(4)) .checkEquals(142) part1(input) .alsoPrintln() // .sendAnswer(part = 1, day = "1", year = 2023) part2(testInput.drop(4)).checkEquals(281) part2(input) .checkNotEquals(55624) .checkNotEquals(55929) .checkEquals(55902) .alsoPrintln() // .sendAnswer(part = 2, day = "1", year = 2023) } object Day1 { fun part1(input: List<String>): Int = input.sumOf { line -> (line.first { it.isDigit() } + "" + line.last { it.isDigit() }).toInt() } fun part2(input: List<String>): Int { val spelledNumbersMap = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9, ) val regexToCaptureFirstN = spelledNumbersMap.map { it.key }.joinToString(prefix = "\\d|", separator = "|").toRegex() val regexToCaptureLastNReversed = spelledNumbersMap.map { it.key.reversed() }.joinToString(prefix = "\\d|", separator = "|").toRegex() return input.sumOf { line -> val firstN = regexToCaptureFirstN.find(line)!!.value.let { digitOrSpelledN -> digitOrSpelledN.toIntOrNull() ?: spelledNumbersMap.getValue(digitOrSpelledN) } val lastN = regexToCaptureLastNReversed.find(line.reversed())!!.value .let { digitOrReversedSpelledN -> digitOrReversedSpelledN.toIntOrNull() ?: spelledNumbersMap.getValue(digitOrReversedSpelledN.reversed()) } firstN * 10 + lastN } } val input get() = readInput("Day1", "aoc2023") val testInput get() = readInput("Day1_test", "aoc2023") }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
2,033
Kotlin-AOC-2023
Apache License 2.0
src/day25/day.kt
LostMekka
574,697,945
false
{"Kotlin": 92218}
package day25 import util.readInput import util.shouldBe fun main() { val testInput = readInput(Input::class, testInput = true).parseInput() testInput.part1() shouldBe "2=-1=0" testInput.part2() shouldBe Unit val input = readInput(Input::class).parseInput() println("output for part1: ${input.part1()}") println("output for part2: ${input.part2()}") } private class Input( val snafuNumbers: List<String>, ) private fun List<String>.parseInput(): Input { return Input(this) } private fun Char.snafuDigitToInt() = when (this) { '2' -> 2 '1' -> 1 '0' -> 0 '-' -> -1 '=' -> -2 else -> error("unknown digit: $this") } private fun Int.digitToSnafu() = when (this) { 2 -> '2' 1 -> '1' 0 -> '0' -1 -> '-' -2 -> '=' else -> error("int $this is not a valid snafu digit") } private fun List<String>.sumSnafu(): String { var i = 1 var carry = 0 var result = "" do { val relevantDigits = mapNotNull { it.getOrNull(it.length - i)?.snafuDigitToInt() } var currDigit = carry + relevantDigits.sum() carry = 0 while (currDigit > 2) { currDigit -= 5 carry++ } while (currDigit < -2) { currDigit += 5 carry-- } result += currDigit.digitToSnafu() i++ } while (carry != 0 || relevantDigits.isNotEmpty()) return result.reversed().trimStart('0') } private fun Input.part1(): String { return snafuNumbers.sumSnafu() } private fun Input.part2(): Unit { return Unit // sorry :D }
0
Kotlin
0
0
58d92387825cf6b3d6b7567a9e6578684963b578
1,600
advent-of-code-2022
Apache License 2.0
src/Day11.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
import java.lang.IllegalArgumentException data class Monkey( val id: Int, val startItems: List<Long>, val operation: (Long) -> Long, val divisor: Int, val trueTo: Int, val falseTo: Int ) { val items = startItems.toMutableList() var inspected = 0 fun throwItems(monkeys: Map<Int, Monkey>, modulus: Int) { items.forEach { val worry = operation(it) % modulus if (worry % divisor == 0L) monkeys[trueTo]!!.items.add(worry) else monkeys[falseTo]!!.items.add(worry) } inspected += items.size items.clear() } } fun main() { fun makeList(s: String) = s.replace(" Starting items: ", "") .split(", ") .map { it.toLong() } val opRegex = """ Operation: new = (old|\d+) (\+|\*) (old|\d+)""".toRegex() fun makeOp(s: String, worryLevel: Int = 3): (Long) -> Long { val match = opRegex.matchEntire(s) ?: throw IllegalArgumentException() val (in1, op, in2) = match.destructured return { old -> val l = if (in1 == "old") old else in1.toLong() val r = if (in2 == "old") old else in2.toLong() val out = if (op == "+") l + r else l * r (out / worryLevel) } } fun divisor(s: String) = s.replace(" Test: divisible by ", "") .toInt() fun trueMonkey(s: String) = s.replace(" If true: throw to monkey ", "") .toInt() fun falseMonkey(s: String) = s.replace(" If false: throw to monkey ", "") .toInt() fun parseInput(input: List<String>, worryLevel: Int = 3) = input.chunked(7) .mapIndexed { i, it -> val items = makeList(it[1]) val op = makeOp(it[2], worryLevel) val div = divisor(it[3]) val tm = trueMonkey(it[4]) val fm = falseMonkey(it[5]) Monkey(i, items, op, div, tm, fm) } fun doRound(monkeys: Map<Int, Monkey>, modulus: Int) { monkeys.keys .sorted() .forEach { monkeys[it]!!.throwItems(monkeys, modulus) } } fun dumpMonkeys(monkeys: Map<Int, Monkey>) { monkeys.keys .sorted() .map { monkeys[it]!! } .forEach { println("Monkey ${it.id}: inspected items ${it.inspected} | ${it.items}") } } fun doIt(monkeys: Map<Int, Monkey>, rounds: Int): Long { val modulus = monkeys.values .map { it.divisor } .fold(1) { m, v -> m * v } repeat(rounds) { doRound(monkeys, modulus) } return monkeys.values .map { it.inspected } .sortedDescending() .take(2) .let { it[0].toLong() * it[1].toLong() } } fun part1(input: List<String>): Long { val monkeys = parseInput(input) .associateBy { it.id } return doIt(monkeys, 20) } fun part2(input: List<String>): Long { val monkeys = parseInput(input, 1) .associateBy { it.id } return doIt(monkeys, 10000) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") checkThat(part1(testInput), 10605) checkThat(part2(testInput), 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
3,462
aoc22
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SearchSuggestionsSystem.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.ALPHABET_LETTERS_COUNT import kotlin.math.abs import kotlin.math.min /** * Search Suggestions System */ fun interface SearchSuggestionsSystem { operator fun invoke(products: Array<String>, searchWord: String): List<List<String>> } /** * Approach 1: Binary Search * Time complexity : O(n log(n))+O(m log(n)). * Space complexity : Varies between O(1) */ class SSSBinarySearch : SearchSuggestionsSystem { override operator fun invoke(products: Array<String>, searchWord: String): List<List<String>> { products.sort() val result: MutableList<MutableList<String>> = ArrayList() var start: Int var bsStart = 0 val n: Int = products.size var prefix = String() for (c in searchWord.toCharArray()) { prefix += c // Get the starting index of word starting with `prefix`. start = lowerBound(products, bsStart, prefix) // Add empty vector to result. result.add(ArrayList()) // Add the words with the same prefix to the result. // Loop runs until `i` reaches the end of input or 3 times or till the // prefix is same for `products[i]` Whichever comes first. for (i in start until min(start + 3, n)) { if (products[i].length < prefix.length || products[i].substring(0, prefix.length) != prefix) break result[result.size - 1].add(products[i]) } // Reduce the size of elements to binary search on since we know bsStart = abs(start) } return result } private fun lowerBound(products: Array<String>, start: Int, word: String?): Int { var i = start var j = products.size var mid: Int while (i < j) { mid = (i + j) / 2 if (products[mid] >= word!!) j = mid else i = mid + 1 } return i } } /** * Approach 2: Trie + DFS * Time complexity : O(M). * Space complexity : O(26n)=O(n). */ class SSSTrie : SearchSuggestionsSystem { override operator fun invoke(products: Array<String>, searchWord: String): List<List<String>> { val result: MutableList<List<String>> = ArrayList() val roots: MutableList<TrieNode> = ArrayList() // Time O(m * l): where m == products array length and l == max length of products // Space O(m * l) var root: TrieNode? = buildTrie(products) // O(L): where L == searchWord length // Space O(L) for (element in searchWord) { root = root?.next?.get(element - 'a') if (root == null) break roots.add(root) } // O(L * m * l): where L == searchWord length // : m == products array length // : l == max length of products // Space O(m * l) for (child in roots) { val subList: MutableList<String> = ArrayList() search(child, subList) result.add(subList) } // O(L): where L == searchWord length while (result.size < searchWord.length) result.add(ArrayList()) return result } private fun search(root: TrieNode, res: MutableList<String>) { root.word?.let { res.add(it) } if (res.size >= 3) return for (child in root.next) { if (child != null) { search(child, res) if (res.size >= 3) return } } } private fun buildTrie(words: Array<String>): TrieNode { val root = TrieNode() for (word in words) { var p: TrieNode? = root for (ch in word.toCharArray()) { val index = ch - 'a' p?.let { if (it.next[index] == null) it.next[index] = TrieNode() } p = p?.next?.get(index) } p?.word = word } return root } class TrieNode { var word: String? = null var next = arrayOfNulls<TrieNode>(ALPHABET_LETTERS_COUNT) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,786
kotlab
Apache License 2.0
src/main/java/challenges/coderbyte/Palindrome.kt
ShabanKamell
342,007,920
false
null
package challenges.coderbyte /** * Have the function PalindromeCreator(str) take the str parameter being passed and * determine if it is possible to create a palindromic string of minimum length 3 * characters by removing 1 or 2 characters. For example: if str is "abjchba" * then you can remove the characters jc to produce "abhba" which is a palindrome. * For this example your program should return the two characters that were removed * with no delimiter and in the order they appear in the string, so jc. * If 1 or 2 characters cannot be removed to produce a palindrome, * then return the string not possible. If the input string is already a palindrome, * your program should return the string palindrome. * * * The input will only contain lowercase alphabetic characters. * Your program should always attempt to create the longest palindromic substring * by removing 1 or 2 characters (see second sample test case as an example). * The 2 characters you remove do not have to be adjacent in the string. * Examples * Input: "mmop" * Output: not possible * Input: "kjjjhjjj" * Output: k */ object Palindrome { private val notPossible = Result.NOT_POSSIBLE.value private enum class Result(val value: String) { PALINDROME("palindrome"), NOT_POSSIBLE("not possible") } private fun palindromeCreator(str: String): String { //If the input string is already a palindrome if (isPalindrome(str)) return Result.PALINDROME.value val fromFirst = createPalindrome(str, false) val fromLast = createPalindrome(str, true) if (fromFirst != notPossible && fromLast != notPossible) { if (fromFirst.length > 2 || fromLast.length > 2) return notPossible return if (fromFirst.length > fromLast.length) fromLast else fromFirst } if (fromFirst != fromLast && fromFirst == notPossible) { return if (fromLast.length > 2) notPossible else fromLast } return if (fromLast != fromFirst && fromLast == notPossible) { if (fromFirst.length > 2) notPossible else fromFirst } else notPossible } private fun isPalindrome(string: String): Boolean { return string == reverseString(string) } private fun reverseString(string: String): String { return StringBuilder(string).reverse().toString() } private fun createPalindrome(_str: String, reverseOrder: Boolean): String { var str = _str if (reverseOrder) str = reverseString(str) val result = StringBuilder() val temp = StringBuilder(str) for (i in str.indices) { if (str[i] != str[str.length - 1 - i]) { if (removeCharAndCheck(result, temp)) return result.toString() } } return Result.NOT_POSSIBLE.value } private fun removeCharAndCheck(result: StringBuilder, temp: StringBuilder): Boolean { result.append(temp[0]) temp.deleteCharAt(0) return isPalindrome(temp.toString()) && temp.length > 2 } @JvmStatic fun main(args: Array<String>) { println(palindromeCreator("mnop")) println(palindromeCreator("kjjjhjjj")) println(palindromeCreator("kkkkkjjjhjjj")) } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,275
CodingChallenges
Apache License 2.0
src/main/kotlin/days/Day10.kt
hughjdavey
225,440,374
false
null
package days import kotlin.math.abs import kotlin.math.atan2 class Day10 : Day(10) { private val grid = AsteroidGrid(inputList) override fun partOne(): Any { val bestLocation = grid.bestLocationForMonitoring() val numberDetectable = grid.numberCanDetect(bestLocation.first, bestLocation.second) return "Best is $bestLocation with $numberDetectable other asteroids detected" } override fun partTwo(): Any { val vaporized200th = grid.vaporizedNth(200) return (vaporized200th.first * 100) + vaporized200th.second } class AsteroidGrid(private val rows: List<String>) { fun get(x: Int, y: Int): Char { return rows[y][x] } fun numberCanDetect(x: Int, y: Int): Int { val angles = allAsteroids().filter { it != x to y }.map { asteroid -> val deltaX = asteroid.first.toDouble() - x.toDouble() val deltaY = asteroid.second.toDouble() - y.toDouble() atan2(deltaY, deltaX) * 180 / Math.PI } return angles.toSet().size } fun allAsteroids(): List<Pair<Int, Int>> { return (0..rows.lastIndex).flatMap { y -> (0..rows[0].lastIndex).map { x -> if (isAsteroid(x, y)) x to y else null } }.filterNotNull() } fun bestLocationForMonitoring(): Pair<Int, Int> { return allAsteroids().maxBy { numberCanDetect(it.first, it.second) } ?: 0 to 0 } fun vaporizedNth(n: Int): Pair<Int, Int> { val location = bestLocationForMonitoring() val asteroidsToAngles = allAsteroids().filter { it != location }.map { asteroid -> val deltaX = asteroid.first.toDouble() - location.first.toDouble() val deltaY = asteroid.second.toDouble() - location.second.toDouble() val angle = ( atan2(deltaY, deltaX) * 180 / Math.PI ) + 90 asteroid to if (angle < 0) angle + 360 else angle }.sortedByDescending { it.second }.reversed() // todo clean up var aa = asteroidsToAngles val destroyed = mutableListOf<Pair<Int, Int>>() while (destroyed.size < n) { val (remaining, gone) = doRotation(aa, location) destroyed.addAll(gone.map { it.first }) aa = remaining } return destroyed[n - 1] } // todo clean up private fun doRotation(asteroidsToAngles: List<Pair<Pair<Int, Int>, Double>>, location: Pair<Int, Int>): Pair< List<Pair<Pair<Int, Int>, Double>>, List<Pair<Pair<Int, Int>, Double>> > { val pass = asteroidsToAngles.filter { a2a -> val allWithSameAngle = asteroidsToAngles.filter { it.second == a2a.second } if (allWithSameAngle.size == 1) { true } else { val distance = distance(location, a2a.first) distance == allWithSameAngle.map { distance(location, it.first) }.min() ?: 0 } } return asteroidsToAngles.filter { a2a -> pass.find { it.first == a2a.first } == null } to asteroidsToAngles.filter { a2a -> pass.find { it.first == a2a.first } != null } } private fun isAsteroid(x: Int, y: Int): Boolean = get(x, y) == '#' companion object { fun distance(a1: Pair<Int, Int>, a2: Pair<Int, Int>): Int { return abs(a2.second - a1.second) + abs(a2.first - a1.first) } } } }
0
Kotlin
0
1
84db818b023668c2bf701cebe7c07f30bc08def0
3,623
aoc-2019
Creative Commons Zero v1.0 Universal
p12/src/main/kotlin/SubterraneanSustainability.kt
jcavanagh
159,918,838
false
null
package p12 import common.file.readLines object Transitions { data class Transition(val match: String, val survives: Boolean) val transitions = loadTransitions() val byStrMatch = transitions.groupBy { it.match }.mapValues { it.value.first() } private fun loadTransitions(): List<Transition> { return readLines("input.txt").map { val spl = it.split(" => ") Transition(spl[0], spl[1] == "#") } } fun match(candidate: List<Char>): Transition? { return byStrMatch[candidate.joinToString("")] } } fun sumOfGenerations(plants: String, generations: Long): Long { fun sumOf(data: CharArray, buffer: Int): Long { return data.foldIndexed(0L) { idx, acc, p -> when (p) { '#' -> acc + (idx - buffer) else -> acc } } } //Create some buffer for the edges and just kind of hope it works out val buffer = 4000 val addendum = "".padStart(buffer, '.') var lastGen = (addendum + plants + addendum).toCharArray() var lastDelta = 0L var sameDeltaCount = 0 val equilibriumThreshold = 5 for(genIdx in 1..generations) { val currentGenList = lastGen.copyOf() val startIdx = lastGen.indexOf('#') - 4 val endIdx = lastGen.lastIndexOf('#') + 4 for(i in startIdx..endIdx) { val candidate = lastGen.slice(i..(i + 4)) val survives = Transitions.match(candidate)?.survives when(survives) { true -> currentGenList[i + 2] = '#' false -> currentGenList[i + 2] = '.' null -> currentGenList[i + 2] = '.' } } val currSum = sumOf(currentGenList, buffer) val lastSum = sumOf(lastGen, buffer) val delta = currSum - lastSum //Check for equilibrium if(delta == lastDelta) { if(sameDeltaCount >= equilibriumThreshold) { return currSum + (generations - genIdx) * delta } sameDeltaCount++ } else { lastDelta = delta sameDeltaCount = 0 } println( currentGenList.slice(startIdx..endIdx).joinToString("") + "(s:$startIdx, e:$endIdx, c:$currSum, l:$lastSum, d:$delta)" ) lastGen = currentGenList } return sumOf(lastGen, buffer) } fun main(args: Array<String>) { val plants = ".#####.##.#.##...#.#.###..#.#..#..#.....#..####.#.##.#######..#...##.#..#.#######...#.#.#..##..#.#.#" val generations = 100L val sum = sumOfGenerations(plants, generations) print("Sum of plant indices at gen 20: $sum") val generations50B = 50000000000 val sum50B = sumOfGenerations(plants, generations50B) print("Sum of plant indices at gen 50,000,000,000: $sum50B") }
0
Kotlin
0
0
289511d067492de1ad0ceb7aa91d0ef7b07163c0
2,585
advent2018
MIT License
src/CommonFun.kt
syncd010
324,790,559
false
null
import java.math.BigInteger import kotlin.math.abs import kotlin.math.pow import kotlin.math.sign /** * Position class with helper functions */ data class Position(var x: Int, var y: Int = 0, var z: Int = 0) { operator fun plus(other: Position): Position = Position(x + other.x, y + other.y, z + other.z) operator fun minus(other: Position): Position = Position(x - other.x, y - other.y, z - other.z) operator fun unaryMinus(): Position = Position(-x, -y, -z) fun sign() : Position = Position(x.sign, y.sign, z.sign) } fun manhattanDist(pos1: Position, pos2: Position): Int = abs(pos1.x - pos2.x) + abs(pos1.y - pos2.y) + abs(pos1.z - pos2.z) typealias Velocity = Position /** * Integer power */ infix fun Int.pow(exponent: Int): Int = toDouble().pow(exponent).toInt() fun ceil(a: Int, b: Int): Int = (a / b) + (if (a % b > 0) 1 else 0) fun ceil(a: Long, b: Long): Long = (a / b) + (if (a % b > 0) 1 else 0) infix fun Long.pow(exponent: Long): Long = toDouble().pow(exponent.toDouble()).toLong() /** * Returns the Greatest Common Divisor of [a] and [b], using Euclid's division algorithm * https://en.wikipedia.org/wiki/Euclidean_algorithm */ tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) tailrec fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) fun lcm(a: Int, b: Int): Int = a / gcd(a, b) * b fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b /** * Returns the digits of this int as a [MutableList] */ fun Long.toDigits(): MutableList<Int> { val res = mutableListOf<Int>() var aux = this while (aux > 0) { res.add((aux % 10).toInt()) aux /= 10 } return res.asReversed() } fun Int.toDigits(): MutableList<Int> { return this.toLong().toDigits() } /** * Returns the number obtained by concatenating [digits] */ fun digitsToNum(digits: List<Int>): Int = digits.reversed().mapIndexed { index, i -> i * 10.pow(index) }.sum() fun <T: Comparable<T>> List<T>.isSorted() : Boolean = this.zipWithNext { a: T, b: T -> a <= b }.all{ it } /** * Returns all permutations of elements from list. These are different ways to arrange elements from this list. */ fun <T> List<T>.permutations(): Set<List<T>> = when { isEmpty() -> setOf() size == 1 -> setOf(listOf(get(0))) else -> { val element = get(0) drop(1).permutations<T>() .flatMap { sublist -> (0..sublist.size).map { i -> sublist.plusAt(i, element) } } .toSet() } } private fun <T> List<T>.plusAt(index: Int, element: T): List<T> = when (index) { !in 0..size -> throw Error("Cannot put at index $index because size is $size") 0 -> listOf(element) + this size -> this + element else -> dropLast(size - index) + element + drop(index) } /** * Returns all combinations of elements in set */ fun <T> Set<T>.combinations(combinationSize: Int): Set<Set<T>> = when { combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize") combinationSize == 0 -> setOf(setOf()) combinationSize >= size -> setOf(toSet()) else -> powerset() .filter { it.size == combinationSize } .toSet() } fun <T> Collection<T>.powerset(): Set<Set<T>> = powerset(this, setOf(setOf())) private tailrec fun <T> powerset(left: Collection<T>, acc: Set<Set<T>>): Set<Set<T>> = when { left.isEmpty() -> acc else ->powerset(left.drop(1), acc + acc.map { it + left.first() }) }
0
Kotlin
0
0
11c7c7d6ccd2488186dfc7841078d9db66beb01a
3,676
AoC2019
Apache License 2.0
src/Day03.kt
benwicks
572,726,620
false
{"Kotlin": 29712}
fun main() { fun Char.toPriority(): Int { return if (code > 90) { code - 96 } else { code - 38 } } fun part1(input: List<String>): Int { var repeatedCharSum = 0 for (line in input) { val numChars = line.length val halfwayPoint = numChars / 2 val firstHalf = line.subSequence(0, halfwayPoint).toSet() val secondHalf = line.subSequence(halfwayPoint, numChars).toSet() repeatedCharSum += firstHalf.first { it in secondHalf }.toPriority() } return repeatedCharSum } fun part2(input: List<String>): Int { var groupBadgeSum = 0 input.chunked(3).forEach { group -> val elf1 = group.first().toSet() val elf2 = group[1].toSet() val elf3 = group.last().toSet() groupBadgeSum += elf1.first { it in elf2 && it in elf3 }.toPriority() } return groupBadgeSum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
fbec04e056bc0933a906fd1383c191051a17c17b
1,269
aoc-2022-kotlin
Apache License 2.0
src/Day05.kt
drothmaler
572,899,837
false
{"Kotlin": 15196}
import Crate.Companion.chars import Crate.Companion.print import kotlin.time.measureTime var debug = false @JvmInline value class Crate(val char:Char) { override fun toString() = if (char == ' ') " " else "[$char]" companion object { val empty = Crate(' ') val List<Crate>.chars get() = String(this.map { it.char }.toCharArray()) fun List<Crate>.print() = println(this.joinToString(" ") ) } } data class Movement(val count:Int, val from:Int, val to:Int) { override fun toString(): String { return "move $count from $from to $to" } companion object { private val pattern = Regex("move (?<count>\\d+) from (?<from>\\d+) to (?<to>\\d+)") private fun MatchResult.value(name: String) = groups[name]!!.value.toInt() fun parse(description: String): Movement { val movement = pattern.matchEntire(description)!! return Movement(movement.value("count"), movement.value("from"), movement.value("to")) } } } class SupplyStacks(private val stacks: Array<ArrayDeque<Crate>>) { fun moveCrates(iter: Iterator<String>) { iter.forEachRemaining { val m = Movement.parse(it) for (i in 0..<m.count) { stacks[m.to-1].addLast(stacks[m.from-1].removeLast()) } } } fun moveCrates2(iter: Iterator<String>) { val craneStack = ArrayDeque<Crate>(50) iter.forEachRemaining { val m = Movement.parse(it) for (i in 0..<m.count) { craneStack.addLast(stacks[m.from-1].removeLast()) } for (i in 0..<m.count) { stacks[m.to-1].addLast(craneStack.removeLast()) } } } private fun printStack() { val maxHeight = stacks.maxOf { it.size } for (i in (maxHeight - 1).downTo(0)) { stacks.map { if (i < it.size) it[i] else Crate.empty }.print() } println() } val size get() = stacks.sumOf { it.size } val topItems get() = stacks.map { it.lastOrNull() ?: Crate.empty } companion object { fun parse(iterator: Iterator<String>): SupplyStacks { val stacks = mutableListOf<MutableList<Crate>>() while (iterator.hasNext()) { val current = iterator.next() val line = current.chunked(4) { it[1] } if (line.any { it.isDigit() }) continue if (line.isEmpty()) break while (stacks.size < line.size) stacks.add(ArrayDeque()) line.mapIndexed { index, c -> if (c.isLetter()) stacks[index].add(Crate(c)) } } val size = stacks.sumOf { it.size } return SupplyStacks( stacks.map { val stack = ArrayDeque<Crate>(size) stack.addAll(it.asReversed()) stack }.toTypedArray() ) } } } fun main() { fun part1(input: Sequence<String>): String { val iter = input.iterator() val ss = SupplyStacks.parse(iter) ss.moveCrates(iter) return ss.topItems.chars } fun part2(input: Sequence<String>): String { val iter = input.iterator() val ss = SupplyStacks.parse(iter) ss.moveCrates2(iter) return ss.topItems.chars } // test if implementation meets criteria from the description, like: println("took " + measureTime { val testOutput = useSanitizedInput("Day05_test", ::part1) println(testOutput) check(testOutput == "CMZ") }) println("took " + measureTime { val testOutput = useSanitizedInput("Day05_test", ::part2) println(testOutput) check(testOutput == "MCD") }) println("took " + measureTime { val largeOutput = useSanitizedInput("aoc_2022_day05_large_input", ::part1) println(largeOutput) }) // readln() //debug = true println("took " + measureTime { val output = useSanitizedInput("Day05", ::part1) println(output) }) println("took " + measureTime { val output = useSanitizedInput("Day05", ::part2) println(output) }) }
0
Kotlin
0
0
1fa39ebe3e4a43e87f415acaf20a991c930eae1c
4,301
aoc-2022-in-kotlin
Apache License 2.0
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day09/Day09.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * 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 com.pietromaggi.aoc2021.day09 import com.pietromaggi.aoc2021.readInput fun part1(input: List<String>): Int { val numbersMap = mutableMapOf<Pair<Int, Int>, Int>() val sizeX = input[0].length - 1 val sizeY = input.size - 1 input.forEachIndexed { y, line -> line.forEachIndexed { x, char -> numbersMap[Pair(x, y)] = char.digitToInt() } } var result = 0 checkMap@ for ((key, value) in numbersMap) { val (x,y) = key if (x > 0) if (value >= numbersMap[Pair(x - 1, y)] as Int) continue@checkMap if (x < sizeX) if (value >= numbersMap[Pair(x + 1, y)] as Int) continue@checkMap if (y > 0) if (value >= numbersMap[Pair(x, y - 1)] as Int) continue@checkMap if (y < sizeY) if (value >= numbersMap[Pair(x, y + 1)] as Int) continue@checkMap result += value + 1 } return result } fun part2(input: List<String>): Int { data class Cell(val value: Int, val counted: Boolean) val numbersMap = mutableMapOf<Pair<Int, Int>, Cell>() val sizeX = input[0].length - 1 val sizeY = input.size - 1 input.forEachIndexed { y, line -> line.forEachIndexed { x, char -> numbersMap[Pair(x, y)] = Cell(char.digitToInt(), false) } } val result = mutableListOf<Int>() fun countIt(x: Int, y: Int, cell: Cell): Int { if ((cell.value == 9) or (cell.counted)) return 0 var partialCount = 1 numbersMap[Pair(x, y)] = Cell(cell.value, true) if (x > 0) partialCount += countIt(x - 1, y, numbersMap[Pair(x - 1, y)]!!) if (x < sizeX) partialCount += countIt(x + 1, y, numbersMap[Pair(x + 1, y)]!!) if (y > 0) partialCount += countIt(x, y - 1, numbersMap[Pair(x, y - 1)]!!) if (y < sizeY) partialCount += countIt(x, y + 1, numbersMap[Pair(x, y + 1)]!!) return partialCount } checkMap@ for ((key, cell) in numbersMap) { if ((cell.value == 9) or (cell.counted)) continue@checkMap val (x, y) = key result.add(countIt(x, y, cell)) } result.sortDescending() return result.take(3).fold(1) { sum, element -> sum * element } } fun main() { val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
2,879
AdventOfCode
Apache License 2.0
src/test/kotlin/de/tek/adventofcode/y2022/util/math/GraphTest.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.util.math import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe class GraphTest : StringSpec({ "Given linear graph and its ends as start and end, the shortest path is the whole line." { val graph = Graph(setOf(1 to 2, 2 to 3, 3 to 4, 4 to 5)) graph.findShortestPath(1, 5).visitedVertices() shouldBe listOf(1, 2, 3, 4, 5) } "Given a bi-directional cycle and some start and end, the shortest path is the edge." { val graph = Graph(setOf(1 to 2, 2 to 3, 3 to 4, 4 to 5, 5 to 1, 5 to 4, 4 to 3, 3 to 2, 2 to 1, 1 to 5)) graph.findShortestPath(1, 5).visitedVertices() shouldBe listOf(1, 5) } "Given a line from start to end and a shortcut, the shortest path is the shortcut." { val graph = Graph(setOf(1 to 2, 2 to 3, 3 to 4, 4 to 5, 1 to 5)) graph.findShortestPath(1, 5).visitedVertices() shouldBe listOf(1, 5) } "Given a line from start to end and a shortcut with an intermediate stop, the shortest path is the shortcut." { val graph = Graph(setOf(1 to 2, 2 to 3, 3 to 4, 4 to 5, 1 to 3, 3 to 5)) graph.findShortestPath(1, 5).visitedVertices() shouldBe listOf(1, 3, 5) } /* (1)-1->(2) | | 3 1 | | v v (3)-1->(4) */ "Given two paths from start to end with different weights, the path with the smaller edge-weight sum is returned." { val edges = listOf(Edge(1, 2, 1), Edge(2, 4, 1), Edge(1, 3, 3), Edge(3, 4, 1)) val graph = Graph(edges) graph.findShortestPath(1, 4) shouldBe listOf(edges[0], edges[1]) } "Given a linear graph and some consecutive vertices, toPath returns the edges between them." { val edges = listOf(1 to 2, 2 to 3, 3 to 4, 4 to 5).map { (from,to) -> Edge(from,to, from)} val graph = Graph(edges) graph.toPath(listOf(2,3,4)) shouldBe listOf(edges[1], edges[2]) } "Given a tree and some consecutive vertices, toPath returns the edges between them." { val edges = listOf(1 to 2, 2 to 3, 3 to 4, 4 to 5, 3 to 6, 6 to 7).map { (from,to) -> Edge(from,to, from)} val graph = Graph(edges) graph.toPath(listOf(2,3,6,7)) shouldBe listOf(edges[1], edges[4], edges[5]) } }) private fun <T> Iterable<Edge<T>>.visitedVertices(): List<T> { val vertices = mutableListOf<T>() val iterator = this.iterator() if (iterator.hasNext()) { val firstEdge = iterator.next() vertices.add(firstEdge.from) vertices.add(firstEdge.to) } while (iterator.hasNext()) { val edge = iterator.next() if (vertices.last() != edge.from) { throw IllegalStateException("Edges are not consecutive. Last end vertex was ${vertices.last()}, next start vertex was ${edge.from}.") } vertices.add(edge.to) } return vertices }
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
2,931
advent-of-code-2022
Apache License 2.0
10/part_two.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File fun readInput() : List<String> { return File("input.txt") .readLines() } class SyntaxChecker { companion object { val OPEN_CHARS = listOf('(', '[', '{', '<') val MATCH = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') val SCORE_TABLE = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4) } fun calcScore(line : String) : Long { val stack = mutableListOf<Char>() if (isIncomplete(line, stack)) { return completionScore(stack.toList()) } else { return 0 } } private fun isIncomplete(line : String, stack : MutableList<Char>) : Boolean { for (ch in line) { if (ch in OPEN_CHARS) { stack.add(ch) } else { if (stack.isNotEmpty() && MATCH[stack.last()] == ch) { stack.removeLast() } else { return false } } } return true } private fun completionScore(unmatched : List<Char>) : Long { var result = 0L for (ch in unmatched.reversed()) { result *= 5 result += SCORE_TABLE[MATCH[ch]!!]!! } return result } } fun solve(lines : List<String>) : Long { val completionScores = mutableListOf<Long>() val syntaxChecker = SyntaxChecker() for (line in lines) { completionScores.add(syntaxChecker.calcScore(line)) } val sortedScores = completionScores.filter { it > 0 }.sortedBy { it } return sortedScores[sortedScores.size / 2] } fun main() { val lines = readInput() val ans = solve(lines) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
1,778
advent-of-code-2021
MIT License
src/main/kotlin/com/groundsfam/advent/y2015/d13/Day13.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2015.d13 import com.groundsfam.advent.DATAPATH import kotlin.io.path.div import kotlin.io.path.useLines fun maxHappiness(opinions: Array<IntArray>): Int { // happiness - total happiness from seatings so far // prevPerson - most recent seated person // needToSeat - set of people still needing to be seated // the first and last person (circular table) is always 0 by convention fun helper(happiness: Int, prevPerson: Int, needToSeat: Set<Int>): Int { if (needToSeat.isEmpty()) { return happiness + opinions[0][prevPerson] + opinions[prevPerson][0] } return needToSeat.maxOf { person -> helper(happiness + opinions[prevPerson][person] + opinions[person][prevPerson], person, needToSeat - person) } } return helper(0, 0, (1 until opinions.size).toSet()) } fun main() { val opinions = Array(8) { IntArray(8) } (DATAPATH / "2015/day13.txt").useLines { lines -> val names = mutableListOf<String>() lines.forEach { line -> val parts = line.split(" ") val person = parts[0] val neighbor = parts[10].let { it.substring(0, it.length-1) } // remove trailing period val happiness = parts[3].let { if (parts[2] == "lose") -it.toInt() else it.toInt() } if (person !in names) names.add(person) if (neighbor !in names) names.add(neighbor) opinions[names.indexOf(person)][names.indexOf(neighbor)] = happiness } } println("Part one: ${maxHappiness(opinions)}") val opinions2 = Array(9) { IntArray(9) } opinions.forEachIndexed { i, row -> row.forEachIndexed { j, happiness -> opinions2[i][j] = happiness } } println("Part two: ${maxHappiness(opinions2)}") }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,874
advent-of-code
MIT License
src/Year2022Day04.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
fun main() { operator fun IntRange.contains(other: IntRange): Boolean = first <= other.first && other.last <= last fun IntRange.overlap(other: IntRange): Boolean = !(other.last < first || last < other.first) fun part1(input: List<String>): Int { return input.map { val (l1, r1, l2, r2) = it.split(",", "-").map(String::toInt) Pair(l1..r1, l2..r2) }.count { (a, b) -> a in b || b in a } } fun part2(input: List<String>): Int { return input.map { val (l1, r1, l2, r2) = it.split(",", "-").map(String::toInt) Pair(l1..r1, l2..r2) }.count { (a, b) -> a.overlap(b)} } val testLines = readLines(true) check(part1(testLines) == 2) check(part2(testLines) == 4) val lines = readLines() println(part1(lines)) println(part2(lines)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
872
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/net/voldrich/aoc2021/Day5.kt
MavoCz
434,703,997
false
{"Kotlin": 119158}
package net.voldrich.aoc2021 import net.voldrich.BaseDay import kotlin.math.abs import kotlin.math.max import kotlin.math.min // https://adventofcode.com/2021/day/5 // result 5632 // result 22213 fun main() { Day5().run() } private class Day5 : BaseDay() { override fun task1() : Int { return calculateDangerPoints { ventLine -> ventLine is HorizontalLine || ventLine is VerticalLine } } override fun task2() : Int { return calculateDangerPoints { true } // calculate all lines } fun calculateDangerPoints(lineFilter: (VentLine) -> Boolean): Int { val lines = input.lines().mapNotNull(this::parseLine).filter(lineFilter).toList() val maxx = lines.maxOf { max(it.start.x, it.end.x) } val maxy = lines.maxOf { max(it.start.y, it.end.y) } val grid = Array(maxy + 1) { IntArray(maxx + 1) } lines.forEach { it.render(grid) } return grid.flatMap { row -> row.filter { it > 1 } }.size } val lineRegex = Regex("([0-9]+),([0-9]+) -> ([0-9]+),([0-9]+)") fun parseLine(line: String): VentLine? { val matches = lineRegex.find(line) ?: throw Exception("Failed to parse vent line $line") fun getIntResult(mr: MatchGroup?) = mr?.value?.toInt() ?: throw Exception("Failed to parse vent line $line") val start = Point(getIntResult(matches.groups[1]), getIntResult(matches.groups[2])) val end = Point(getIntResult(matches.groups[3]), getIntResult(matches.groups[4])) if (start.x == end.x) { return VerticalLine(start, end) } else if (start.y == end.y) { return HorizontalLine(start, end) } else if (abs(start.x - end.x) == abs(start.y - end.y)) { return DiagonalLine(start, end) } return null } data class Point(val x: Int, val y: Int) abstract class VentLine(val start: Point, val end: Point) { abstract fun render(grid: Array<IntArray>) } class HorizontalLine(start: Point, end: Point) : VentLine(start, end) { override fun render(grid: Array<IntArray>) { for (x in min(start.x, end.x) .. max(start.x, end.x)) { grid[start.y][x] += 1 } } } class VerticalLine(start: Point, end: Point) : VentLine(start, end) { override fun render(grid: Array<IntArray>) { for (y in min(start.y, end.y) .. max(start.y, end.y)) { grid[y][start.x] += 1 } } } class DiagonalLine(start: Point, end: Point) : VentLine(start, end) { override fun render(grid: Array<IntArray>) { val dimensionsX = abs(start.x - end.x) var y = start.y val yIncrement = if (start.y < end.y) 1 else -1 var x = start.x val xIncrement = if (start.x < end.x) 1 else -1 grid[y][x] += 1 for (i in 0 until dimensionsX) { y += yIncrement x += xIncrement grid[y][x] += 1 } } } }
0
Kotlin
0
0
0cedad1d393d9040c4cc9b50b120647884ea99d9
3,081
advent-of-code
Apache License 2.0
src/Day07.kt
rosyish
573,297,490
false
{"Kotlin": 51693}
class Node(val name: String, val parent: Node?, val isDir: Boolean = false, var size: Int = 0, val children: HashMap<String, Node> = hashMapOf()) val part1MaxVal = 100000 var part1answer = 0 var minDirSize = Int.MAX_VALUE fun fillSizes(current: Node) { if (!current.isDir) return; if (current.children.isEmpty()) return; for (c in current.children.values) { fillSizes(c); current.size += c.size } if (current.size <= part1MaxVal) part1answer += current.size } fun findSmallerDirWithRequiredSpace(current: Node, spaceToFreeUp: Int) { if (!current.isDir) return if (current.size in spaceToFreeUp until minDirSize) { if (current.size < minDirSize) { minDirSize = current.size } } for (c in current.children.values) { findSmallerDirWithRequiredSpace(c, spaceToFreeUp) } } fun main() { val root = Node("/", null,true) var pwd = root readInput("Day07_input").drop(1).forEach { when { it == "$ cd .." -> pwd = pwd.parent ?: pwd it == "$ ls" -> return@forEach it.startsWith("$ cd") -> pwd = pwd.children[it.split(" ")[2]]!! it.startsWith("dir") -> { val dirname = it.split(" ")[1] pwd.children.putIfAbsent(dirname, Node(dirname, pwd, isDir = true)) } else -> { val (fileSize, fileName) = it.split(" ").let { Pair(it[0].toInt(), it[1]) } pwd.children.putIfAbsent(fileName, Node(fileName, pwd, isDir = false, size = fileSize)) } } } fillSizes(root) println(part1answer) val totalDiskSpace = 70000000; val minUnusedSpace = 30000000; val unusedSpace = totalDiskSpace - root.size; val spaceToFreeUp = minUnusedSpace - unusedSpace; findSmallerDirWithRequiredSpace(root, spaceToFreeUp) println(minDirSize) }
0
Kotlin
0
2
43560f3e6a814bfd52ebadb939594290cd43549f
1,919
aoc-2022
Apache License 2.0
src/main/kotlin/dp/MaxPlusMult.kt
yx-z
106,589,674
false
null
package dp import util.get import util.max import util.min import util.set // similar to MaxPlusMinus // but this time, the input array contains only numbers, +, and * // find the maximum value of expression by adding parenthesis // also with different constraints as the following // 1. all numbers are positive fun CharArray.maxPlusMult1(): Int { // I can prove that we should always do multiplication later // given A + B * C, (A + B) * C = AC + BC > A + BC // similarly, A * B + C, A * (B + C) = AB + AC > AB + C if (size == 0) { return 1 } for (i in 0 until size) { if (this[i] == '*') { return this[0 until i].maxPlusMult1() * this[i + 1 until size].maxPlusMult1() } } // no '*' any more -> sum them up return filter { it.isDigit() }.sumBy { it.toDigit() } // space complexity: O(1) // time complexity: O(n) } // 2. all numbers are nonnegative fun CharArray.maxPlusMult2(): Int { val E = this // E for Expression val n = size // should always be an odd number val h = (n - 1) / 2 // h for Half-size // E[2i] is a number, 0 <= i <= h // E[2j - 1] is an operator, 1 <= j <= h // dp(s, e): max output for E[2s..2e], s, e in 0..h // memoization structure: 2d array dp[0..h, 0..h] : dp[s, e] = dp(s, e) val dp = Array(h + 1) { Array(h + 1) { 0 } } // space complexity: O(n^2) // base case: // dp(s, e) = 0 if s, e !in 0..h or s > e // = E[2s] (as an int) if s = e for (s in 0..h) { dp[s, s] = E[2 * s].toDigit() } // recursive case: // dp(s, e) = max_k{ if E[2k - 1] = '+': // dp(s, k - 1) + dp(k, e) // else // dp(s, k - 1) * dp(k, e) // } for all s < k <= e // dependency: dp(s, e) depends on dp(s, k), and dp(k + 1, e), s < k < e // that is entries below and to the left // evaluation order: outer loop for s from h down to 0 (bottom up) for (s in h downTo 0) { // inner loop for e from s + 1 to h (left to right) for (e in s + 1..h) { dp[s, e] = (s + 1..e).map { k -> if (E[2 * k - 1] == '+') { dp[s, k - 1] + dp[k, e] } else { dp[s, k - 1] * dp[k, e] } }.max() ?: 0 } } // for (s in 0..h) { // println(Arrays.toString(dp[s])) // } // we want dp(0, h) return dp[0, h] } fun CharArray.maxPlusMultRedo(): Int { val E = this val n = size / 2 val dp = Array(n + 1) { Array(n + 1) { 0 } } for (i in 0..n) { dp[i, i] = E[2 * i].toDigit() } for (i in n - 1 downTo 0) { for (j in i + 1..n) { dp[i, j] = (2 * i + 1 until 2 * j step 2).map { if (E[it] == '+') { dp[i, (it - 1) / 2] + dp[(it + 1) / 2, j] } else { // E[it] == '*' dp[i, (it - 1) / 2] * dp[(it + 1) / 2, j] } }.max() ?: 0 } } return dp[0, n] } fun Array<Any>.maxPlusMultNegativeIncluded(): Int { val E = this val n = size / 2 val dpMax = Array(n + 1) { Array(n + 1) { 0 } } val dpMin = Array(n + 1) { Array(n + 1) { 0 } } for (i in 0..n) { dpMax[i, i] = E[2 * i] as Int dpMin[i, i] = E[2 * i] as Int } for (i in n - 1 downTo 0) { for (j in i + 1..n) { dpMax[i, j] = (2 * i + 1 until 2 * j step 2).map { val pre = (it - 1) / 2 val nex = (it + 1) / 2 if (E[it] == '+') { dpMax[i, pre] + dpMax[nex, j] } else { // E[it] == '*' max(dpMax[i, pre] * dpMax[nex, j], dpMin[i, pre] * dpMin[nex, j]) } }.max()!! dpMin[i, j] = (2 * i + 1 until 2 * j step 2).map { val pre = (it - 1) / 2 val nex = (it + 1) / 2 if (E[it] == '+') { dpMin[i, pre] + dpMin[nex, j] } else { // E[it] == '*' min( dpMax[i, pre] * dpMin[nex, j], dpMax[i, pre] * dpMax[nex, j], dpMin[i, pre] * dpMin[nex, j], dpMin[i, pre] * dpMax[nex, j]) } }.min()!! } } return dpMax[0, n] } fun main(args: Array<String>) { val test1 = "1+3*2+1*6+7".toCharArray() // println(test1.maxPlusMult1()) val test2 = "1+3*2*0+1*6+7".toCharArray() // println(test2.maxPlusMult2()) // println(test2.maxPlusMultRedo()) val test3 = arrayOf(1, '+', -3, '*', 5, '*', -1, '+', 4) println(test3.maxPlusMultNegativeIncluded()) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
4,089
AlgoKt
MIT License
2022/src/main/kotlin/de/skyrising/aoc2022/day15/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2022.day15 import de.skyrising.aoc.* import kotlin.math.abs private fun parseInput(input: PuzzleInput) = input.lines.map { val (a, b, c, d) = it.ints() Vec2i(a, b) to Vec2i(c, d) } private fun rangesForRow(pairs: List<Pair<Vec2i, Vec2i>>, row: Int) = joinRanges(pairs.mapNotNull { (s, b) -> val dist = s.manhattanDistance(b) val yDiff = abs(s.y - row) val width = dist - yDiff if (width < 0) null else s.x - width..s.x + width }) private fun findGap(ranges: Set<IntRange>, min: Int, max: Int) = when (ranges.size) { 1 -> { val range = ranges.single() when { min !in range -> min max !in range -> max else -> null } } 2 -> ranges.minBy(IntRange::first).last + 1 else -> null } val test = TestInput(""" Sensor at x=2, y=18: closest beacon is at x=-2, y=15 Sensor at x=9, y=16: closest beacon is at x=10, y=16 Sensor at x=13, y=2: closest beacon is at x=15, y=3 Sensor at x=12, y=14: closest beacon is at x=10, y=16 Sensor at x=10, y=20: closest beacon is at x=10, y=16 Sensor at x=14, y=17: closest beacon is at x=10, y=16 Sensor at x=8, y=7: closest beacon is at x=2, y=10 Sensor at x=2, y=0: closest beacon is at x=2, y=10 Sensor at x=0, y=11: closest beacon is at x=2, y=10 Sensor at x=20, y=14: closest beacon is at x=25, y=17 Sensor at x=17, y=20: closest beacon is at x=21, y=22 Sensor at x=16, y=7: closest beacon is at x=15, y=3 Sensor at x=14, y=3: closest beacon is at x=15, y=3 Sensor at x=20, y=1: closest beacon is at x=15, y=3 """) @PuzzleName("Beacon Exclusion Zone") fun PuzzleInput.part1(): Any { val pairs = parseInput(this) val row = 2000000 val joined = rangesForRow(pairs, row) val beaconsThisRow = pairs.map { it.second }.filterTo(mutableSetOf()) { it.y == row } return joined.sumOf { range -> range.last - range.first + 1 - beaconsThisRow.count { it.x in range } } } fun PuzzleInput.part2(): Any? { val pairs = parseInput(this) val bound = 4000000 for (y in 0..bound) { val ranges = rangesForRow(pairs, y) val gap = findGap(ranges, 0, bound) ?: continue val pos = Vec2i(gap, y) return pos.x * 4000000L + y } return null }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
2,315
aoc
MIT License
app/src/main/kotlin/kotlinadventofcode/util/Relations.kt
pragmaticpandy
356,481,847
false
{"Kotlin": 1003522, "Shell": 219}
package kotlinadventofcode.util import kotlin.math.pow fun isQuadratic(x: List<Int>, y: List<Int>): Boolean { if (!x.map { it.toDouble() }.isLinear()) error("x values must be linear") if (x.size != y.size) error("x and y must be the same size") if (x.size < 4) error("x and y must have at least 4 values") return y.map { it.toDouble() }.finiteDifferences().isLinear() } fun List<Pair<Int, Int>>.isQuadratic(): Boolean { return isQuadratic(map { it.first }, map { it.second }) } fun List<Double>.finiteDifferences(): List<Double> { return (0 until indices.last).map { this[it + 1] - this[it] } } fun List<Double>.isLinear(): Boolean { return finiteDifferences().distinct().size == 1 } val List<Pair<Int, Int>>.quadratic: (Int) -> Double get() { if (!isQuadratic()) error("Series is not quadratic") val (x1, y1) = this[0] val (x2, y2) = this[1] val (x3, y3) = this[2] val denominator = (x1 - x2) * (x1 - x3) * (x2 - x3) val a = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denominator.toDouble() val b = (x3 * x3 * (y1 - y2) + x2 * x2 * (y3 - y1) + x1 * x1 * (y2 - y3)) / denominator.toDouble() val c = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * (x1 - x2) * y3) / denominator.toDouble() return { x -> a * x.toDouble().pow(2) + b * x + c } }
0
Kotlin
0
3
26ef6b194f3e22783cbbaf1489fc125d9aff9566
1,383
kotlinadventofcode
MIT License
src/y2016/Day11.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2016 import util.readInput object Day11 { fun part1(input: List<String>): Int { val itemsPerFloor = input.map { it.split(" a ").size - 1 } val cumulative = itemsPerFloor.scan(0) { acc, i -> acc + i }.drop(1).dropLast(1) /** * bringing n items up one floor taken 2*n - 3 steps (one up, one down each, minus the last down, and on the last up you can take * 2 items) * * In general we can always move the generators first, we never need to move items back down, except to make sure the elevator * operates */ return cumulative.sumOf { it * 2 - 3 } } fun part2(input: List<String>): Int { val itemsPerFloor = input.map { it.split(" a ").size - 1 } val cumulative = itemsPerFloor.scan(4) { acc, i -> acc + i }.drop(1).dropLast(1) return cumulative.sumOf { it * 2 - 3 } } } fun main() { val testInput = """ The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip. The second floor contains a hydrogen generator. The third floor contains a lithium generator. The fourth floor contains nothing relevant. """.trimIndent().split("\n") println("------Tests------") println(Day11.part1(testInput)) println(Day11.part2(testInput)) println("------Real------") val input = readInput("resources/2016/day11") println(Day11.part1(input)) println(Day11.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,495
advent-of-code
Apache License 2.0
src/main/kotlin/adventofcode/year2022/Day08TreetopTreeHouse.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2022 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.product import adventofcode.year2022.Day08TreetopTreeHouse.Companion.Direction.DOWN import adventofcode.year2022.Day08TreetopTreeHouse.Companion.Direction.LEFT import adventofcode.year2022.Day08TreetopTreeHouse.Companion.Direction.RIGHT import adventofcode.year2022.Day08TreetopTreeHouse.Companion.Direction.UP class Day08TreetopTreeHouse(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val treeMap by lazy { input.lines().map { line -> line.map(Char::digitToInt) } } override fun partOne() = treeMap .flatMapIndexed { y, row -> row.mapIndexed { x, tree -> Direction .entries .map { direction -> treeMap.neighbors(x, y, direction).filter { neighbor -> neighbor >= tree } } .any(List<Int>::isEmpty) } } .count { tree -> tree } override fun partTwo() = treeMap .flatMapIndexed { y, row -> row.mapIndexed { x, tree -> Direction .entries .map { direction -> val neighbors = treeMap.neighbors(x, y, direction) when (val tallestNeighbor = neighbors.indexOfFirst { neighbor -> neighbor >= tree }) { -1 -> neighbors.size else -> tallestNeighbor + 1 } } } } .maxOf(List<Int>::product) companion object { private enum class Direction { DOWN, LEFT, RIGHT, UP } private fun List<List<Int>>.neighbors(x: Int, y: Int, direction: Direction) = when (direction) { DOWN -> map { row -> row[x] }.drop(y + 1) LEFT -> this[y].take(x).reversed() RIGHT -> this[y].drop(x + 1) UP -> map { row -> row[x] }.take(y).reversed() } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,015
AdventOfCode
MIT License
src/main/kotlin/g0501_0600/s0587_erect_the_fence/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0587_erect_the_fence // #Hard #Array #Math #Geometry #2023_01_30_Time_470_ms_(100.00%)_Space_54.7_MB_(100.00%) import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.pow import kotlin.math.sqrt class Solution { private fun dist(p1: Pair<Int, Int>, p2: Pair<Int, Int>): Double { return sqrt((p2.second - p1.second).toDouble().pow(2.0) + Math.pow((p2.first - p1.first).toDouble(), 2.0)) } private fun angle(p1: Pair<Int, Int>, p2: Pair<Int, Int>): Double { return atan2((p2.second - p1.second).toDouble(), (p2.first - p1.first).toDouble()).let { if (it < 0) return (2.0 * Math.PI + it) else it } } fun outerTrees(trees: Array<IntArray>): Array<IntArray> { if (trees.size < 3) { return trees } val left = trees.asSequence().map { it[0] to it[1] }.toMutableList() left.sortWith(compareBy<Pair<Int, Int>> { it.second }.thenBy { it.first }) val firstPoint = left[0] var nowPoint = firstPoint val pointList = mutableListOf(nowPoint) var prevAngle = 0.0 while (true) { val nowList = mutableListOf<Pair<Pair<Int, Int>, Double>>() var nowMinAngleDiff = 7.0 var nowMinAngle = 7.0 left.forEach { if (it != nowPoint) { val angle = angle(nowPoint, it) if (abs(angle - nowMinAngle) < 0.0000001) { nowList.add(it to dist(it, nowPoint)) } else { val diff = if (angle >= prevAngle) (angle - prevAngle) else 2.0 * Math.PI - (angle - prevAngle) if ((diff) < nowMinAngleDiff) { nowMinAngle = angle nowMinAngleDiff = (diff) nowList.clear() nowList.add(it to dist(it, nowPoint)) } } } } prevAngle = nowMinAngle nowList.sortBy { it.second } val nowListOnlyPoints = nowList.map { it.first }.toMutableList() if (nowListOnlyPoints.last() == firstPoint) { nowListOnlyPoints.removeAt(nowListOnlyPoints.size - 1) left.removeAll(nowListOnlyPoints) pointList.addAll(nowListOnlyPoints) break } else { nowPoint = nowListOnlyPoints.last() left.removeAll(nowListOnlyPoints) pointList.addAll(nowListOnlyPoints) } } return pointList.asSequence().map { intArrayOf(it.first, it.second) }.toList().toTypedArray() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,737
LeetCode-in-Kotlin
MIT License
src/main/kotlin/be/swsb/aoc2021/day6/Day6.kt
Sch3lp
433,542,959
false
{"Kotlin": 90751}
package be.swsb.aoc2021.day6 object Day6 { fun solve1(input: List<Int>, days: Int): Int { return dayCycle(input, days).size } fun solve2(input: List<Int>, days: Int): Long { return dayCyclePart2(input, days) } } fun dayCycle(school: List<Int>, days: Int): List<Int> { return (1..days).fold(school) { acc, _ -> acc.dayPasses() } } fun List<Int>.dayPasses(): List<Int> { val amountOfNewSpawns = count { it == 0 } val newSpawns: Sequence<Int> = generateSequence { 8 }.take(amountOfNewSpawns) return map { if (it == 0) 6 else it - 1 } + newSpawns.toList() } fun dayCyclePart2(initialSchool: List<Int>, days: Int): Long { val fishGroupedByGestationTime: Map<GestationTime, Long> = (0..8).associateWith { gestationTime -> initialSchool.count { it == gestationTime }.toLong() } return (1..days).fold(fishGroupedByGestationTime) { acc, _ -> acc.dayPasses() }.values.sum() } fun Map<GestationTime, Long>.dayPasses(): Map<GestationTime, Long> { return map { (k, _) -> when (k) { 6 -> k to (this[k+1]!! + this[0]!!) 8 -> k to this[0]!! else -> k to this[k+1]!! } }.toMap() } typealias GestationTime = Int
0
Kotlin
0
0
7662b3861ca53214e3e3a77c1af7b7c049f81f44
1,229
Advent-of-Code-2021
MIT License
src/Day16.kt
janbina
112,736,606
false
null
package day16 import getInput import java.util.* import kotlin.test.assertEquals fun main(args: Array<String>) { val input = getInput(16).readLines().first().split(',').map { Instruction.fromString(it) } val programs = CharArray(16) { (it + 'a'.toInt()).toChar() } assertEquals("ociedpjbmfnkhlga", part1(programs, input)) assertEquals("gnflbkojhicpmead", part2(programs, input)) } sealed class Instruction { companion object { fun fromString(input: String): Instruction { val first = input[0] val rest = input.substring(1).split('/') return when (first) { 's' -> Spin(rest[0].toInt()) 'x' -> Exchange(rest[0].toInt(), rest[1].toInt()) 'p' -> Partner(rest[0][0], rest[1][0]) else -> throw IllegalArgumentException(input) } } } abstract fun apply(input: CharArray): CharArray data class Spin(private val x: Int) : Instruction() { override fun apply(input: CharArray): CharArray { if (input.size < x) throw IllegalArgumentException() val p1 = input.copyOfRange(input.size - x, input.size) val p2 = input.copyOfRange(0, input.size - x) return p1 + p2 } } data class Exchange(private val x: Int, private val y: Int) : Instruction() { override fun apply(input: CharArray): CharArray { if (x !in input.indices || y !in input.indices) throw IllegalArgumentException() val copy = input.copyOf() copy[x].let { copy[x] = copy[y] copy[y] = it } return copy } } data class Partner(private val x: Char, private val y: Char) : Instruction() { override fun apply(input: CharArray):CharArray { val i = input.indexOf(x) val j = input.indexOf(y) if (i !in input.indices || j !in input.indices) throw IllegalArgumentException() val copy = input.copyOf() copy[i].let { copy[i] = copy[j] copy[j] = it } return copy } } } fun part1(programs: CharArray, instructions: List<Instruction>): String { val transformed = instructions.fold(programs, {acc, inst -> inst.apply(acc)}) return transformed.joinToString(separator = "") } fun part2(programs: CharArray, instructions: List<Instruction>): String { var transformed = programs.copyOf() val transformations = mutableListOf<String>() (1..Int.MAX_VALUE).forEach { transformed = instructions.fold(transformed, {acc, inst -> inst.apply(acc)}) if (Arrays.equals(transformed, programs)) { return transformations[1_000_000_000 % it - 1] } transformations.add(transformed.joinToString(separator = "")) } return "" }
0
Kotlin
0
0
71b34484825e1ec3f1b3174325c16fee33a13a65
2,904
advent-of-code-2017
MIT License
src/Day21.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
import kotlin.math.sign const val MY_MONKEY_NAME = "humn" const val ROOT = "root" enum class Operation(val perform: (Double, Double) -> Double) { DIV(Double::div), MUL(Double::times), MINUS(Double::minus), PLUS(Double::plus); override fun toString(): String { return when (this) { DIV -> " / " MUL -> " * " MINUS -> " - " PLUS -> " + " } } companion object { fun getByString(op: String): Operation { return when (op) { "/" -> DIV "*" -> MUL "-" -> MINUS else -> PLUS } } } } abstract class Monkey { abstract fun get(): Double? } class OpMonkey(val left: String, val right: String, val op: Operation): Monkey() { var result: Double? = null var formula: ((Double) -> Double)? = null override fun get(): Double? { return result } } class NumMonkey(val number: Double, val isMe: Boolean = false): Monkey() { override fun get(): Double? { if (isMe) return null return number } override fun toString(): String { if (isMe) return "X" return number.toString() } } fun main() { fun parseInput(input: List<String>, countMyself: Boolean = false): HashMap<String, Monkey> { val monkeys = HashMap<String, Monkey>() input.map { val words = it.replace(":", "").split(" ") val from = words[0] if (words.size == 4) monkeys[from] = OpMonkey(words[1], words[3], if (!countMyself || words[0] != ROOT) Operation.getByString(words[2]) else Operation.MINUS) else monkeys[from] = NumMonkey(words[1].toDouble(), countMyself && words[0] == MY_MONKEY_NAME) } return monkeys } fun countValue(current: Monkey, monkeys: HashMap<String, Monkey>) { if (current is NumMonkey || (current as OpMonkey).result != null) return val left = monkeys[current.left]!! countValue(left, monkeys) val right = monkeys[current.right]!! countValue(right, monkeys) if (left.get() == null && right.get() == null) { println("Logic failed...") return } if (left.get() == null) { if (left is NumMonkey) current.formula = { number -> current.op.perform(number, right.get()!!) } else current.formula = { number -> current.op.perform((left as OpMonkey).formula!!(number), right.get()!!) } } else if (right.get() == null) { if (right is NumMonkey) current.formula = { number -> current.op.perform(left.get()!!, number) } else current.formula = { number -> current.op.perform(left.get()!!, (right as OpMonkey).formula!!(number)) } } else { current.result = current.op.perform(left.get()!!, right.get()!!) } } fun part1(input: List<String>): Long { val monkeys = parseInput(input) val root = monkeys["root"]!! if (root is NumMonkey) return root.number.toLong() countValue(root, monkeys) return (root as OpMonkey).result?.toLong() ?: 0L } fun findResult(root: OpMonkey): Long { fun apply(n: Long): Double = root.formula!!(n.toDouble()) var left = 0L var right = 14564962656856 val multiple = -apply(left).sign while (left < right - 1L) { val mid = (left + right) / 2L val midValue = apply(mid) if (midValue == 0.0) return mid else if (midValue * multiple < 0L) left = mid else right = mid } return left } fun part2(input: List<String>): Long { val monkeys = parseInput(input, true) val root = monkeys["root"]!! if (root is NumMonkey) return root.number.toLong() countValue(root, monkeys) return findResult(root as OpMonkey) } val testInput = readInputLines("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInputLines(21) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
3,756
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
src/main/kotlin/d20_TrenchMap/TrenchMap.kt
aormsby
425,644,961
false
{"Kotlin": 68415}
package d20_TrenchMap import util.Coord import util.Input import util.Output fun main() { Output.day(20, "Trench Map") val startTime = Output.startTime() val input = Input.parseLines(filename = "/input/d20_trench_map_input.txt") val algorithm = input[0].map { if (it == '#') '1' else '0' }.joinToString("") var image = input.drop(2).map { s -> s.map { c -> if (c == '#') '1' else '0' }.joinToString("") } val flipVoid = algorithm[0] == '1' var voidDefault = '0' for (step in 1..2) { if (flipVoid) voidDefault = if (step % 2 == 0) '1' else '0' image = image.enhance(algorithm, voidDefault) } val twoStepLit = image.fold(0) { sum, line -> sum + line.fold(0) { acc, cur -> acc + if (cur == '1') 1 else 0 } } for (step in 3..50) { if (flipVoid) voidDefault = if (step % 2 == 0) '1' else '0' image = image.enhance(algorithm, voidDefault) } val fiftyStepLit = image.fold(0) { sum, line -> sum + line.fold(0) { acc, cur -> acc + if (cur == '1') 1 else 0 } } Output.part(1, "Number Lit, 2 Steps", twoStepLit) Output.part(2, "Number Lit, 50 Steps", fiftyStepLit) Output.executionTime(startTime) } val neighbors = Coord(0, 0).allNeighborsWithSelf() .sortedWith(compareBy<Coord> { it.x }.thenBy { it.y }) fun List<String>.getEnhancementIndex(x: Int, y: Int, voidDefault: Char): Int { var binaryString = "" val squareSize = this.size neighbors.forEach { n -> val c = Coord(x, y) + n binaryString += if (c.x < 0 || c.y < 0 || c.x + 1 > squareSize || c.y + 1 > squareSize) voidDefault else this[c.x][c.y] } return binaryString.toInt(2) } fun List<String>.enhance(algo: String, voidDefault: Char): List<String> { val newImage = mutableListOf<String>() for (x in -1..size) { var s = "" for (y in -1..first().length) { s += algo[this.getEnhancementIndex(x, y, voidDefault)] } newImage.add(s) } return newImage }
0
Kotlin
1
1
193d7b47085c3e84a1f24b11177206e82110bfad
2,091
advent-of-code-2021
MIT License
src/Day09.kt
dyomin-ea
572,996,238
false
{"Kotlin": 21309}
import kotlin.math.abs import kotlin.math.sign import kotlin.math.truncate typealias Dot = Pair<Int, Int> fun main() { fun way(input: String): List<Direction> = buildList { val pair = input.splitBy(" ") repeat(pair.second.toInt()) { add(Direction(pair.first)) } } fun Dot.move(direction: Direction) = when (direction) { Direction.U -> copy(first = first + 1) Direction.D -> copy(first = first - 1) Direction.L -> copy(second = second - 1) Direction.R -> copy(second = second + 1) } infix fun Dot.cl(right: Dot): Boolean = abs(first - right.first) <= 1 && abs(second - right.second) <= 1 fun tailMovement(lastTail: Dot, lastHead: Dot, head: Dot): Dot = TODO() fun List<Dot>.getTailPath(): List<Dot> = windowed(2) .scan(0 to 0) { t, (h1, h2) -> if (t cl h2) t else t + tailMovement(t, h1, h2) } fun readHeadPath(input: List<String>): List<Dot> = input.flatMap(::way) .scan(0 to 0) { h, d -> h.move(d) } fun part1(input: List<String>): Int = readHeadPath(input) .getTailPath() .toSet() .size fun part2(input: List<String>): Int { tailrec fun getDeepPath( input: List<Dot>, accumulator: MutableSet<Any> = HashSet(), depth: Int = 9, ): Set<Any> = if (depth == 0) accumulator else { val headPath = input.getTailPath() accumulator.addAll(headPath) getDeepPath( headPath, accumulator, depth = depth - 1 ) } return getDeepPath(readHeadPath(input)).size } val testInput = readInput("Day09_test") check(part1(testInput) == 13) { part1(testInput) } check(part2(testInput) == 9) val input = readInput("Day09") println(part1(input)) println(part2(input)) } enum class Direction { U, D, L, R; companion object { operator fun invoke(input: String): Direction = when (input) { "U" -> U "D" -> D "L" -> L "R" -> R else -> error("unknown") } } operator fun plus(other: Direction): Direction? = if (this to other == this to this) this else null } val line: MutableList<String> get() = (0..5).map { "." } .toMutableList() fun debug(t: Dot, h1: Dot, h2: Dot) { val field = (0..4).map { line } field[t.first][t.second] = "T" field[h1.first][h1.second] = "1" field[h2.first][h2.second] = "2" println( field.reversed() .joinToString(separator = "\n") { it.joinToString(separator = "") } ) println() } fun vec(start: Dot, end: Dot): Dot = end.first - start.first to end.second - start.second operator fun Dot.plus(other: Dot): Dot = first + other.first to second + other.second operator fun Dot.div(d: Int): Dot = truncate(first.toDouble() / d).toInt() to truncate(second.toDouble() / d).toInt() val Dot.direction get() = first.sign to second.sign
0
Kotlin
0
0
8aaf3f063ce432207dee5f4ad4e597030cfded6d
3,375
advent-of-code-2022
Apache License 2.0
src/day06/Day06.kt
spyroid
433,555,350
false
null
package day06 import readInput fun main() { fun liveOneDay(map: Map<Int, Long>): Map<Int, Long> { return map .mapKeys { it.key - 1 } .toMutableMap() .also { val m1 = it.getOrDefault(-1, 0) it.merge(6, m1) { a, b -> a + b } it.merge(8, m1) { a, b -> a + b } it.remove(-1) } } fun part1(seq: Map<Int, Long>, days: Int): Long { var mm = seq return repeat(days) { mm = liveOneDay(mm) }.let { mm.values.sum() } } fun inputToMap(str: String): Map<Int, Long> { return str.split(",") .map { it.toInt() } .groupingBy { it } .eachCount() .mapValues { (_, v) -> v.toLong() } } val testSeq = readInput("day06/test").map { inputToMap(it) }.first() val inputSeq = readInput("day06/input").map { inputToMap(it) }.first() val res1 = part1(testSeq, 80) check(res1 == 5934L) { "Expected 5934 but got $res1" } println("Part1: ${part1(inputSeq, 80)}") println("Part2: ${part1(inputSeq, 256)}") }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
1,163
Advent-of-Code-2021
Apache License 2.0
yandex/y2023/qual/d_wrong.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package yandex.y2023.qual private fun solve() { val (n, m) = readInts() val nei = List(2) { List(n + 1) { mutableListOf<Pair<Int, Int>>() } } repeat(m) { val tokens = readStrings() val a = tokens[0].toInt() - 1 val b = tokens[1].toInt() val greater = (tokens[2][0] == '>').toInt() val value = tokens[3].toInt() nei[greater][b].add(a to value) } val news = MutableList(2) { IntArray(0) } for (c in 1..n) { for (greater in 0..1) { val neutral = if (greater == 1) Int.MIN_VALUE else Int.MAX_VALUE val op: Function2<Int, Int, Int> = if (greater == 1) ::maxOf else ::minOf val new = IntArray(n) { neutral } news[greater] = new for ((b, value) in nei[greater][c]) { new[b] = op(new[b], value) for ((a, value2) in nei[greater][b]) { new[a] = op(new[a], new[b] + value2) } } nei[greater][c].clear() for (b in 0 until c) if (new[b] != neutral) nei[greater][c].add(b to new[b]) } for (b in 0 until c) if (news[0][b] < news[1][b]) { return println("NO") } } println("YES") } private fun readStrings() = readln().split(" ") private fun readInts() = readStrings().map { it.toInt() } private fun Boolean.toInt() = if (this) 1 else 0 fun main() = repeat(1) { solve() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,229
competitions
The Unlicense
src/Day01.kt
buongarzoni
572,991,996
false
{"Kotlin": 26251}
fun solveDay01() { val testInput = readInput("Day01_test") val carriedCaloriesPerElve: List<List<String>> = testInput.toCarriedCaloriesPerElve() val caloriesIntakePerElve = carriedCaloriesPerElve.toCaloriesIntakePerElve() val maxCalorieIntake = caloriesIntakePerElve.max() println("Max calorie intake of an Elve: $maxCalorieIntake") val top3Sum = caloriesIntakePerElve.sortedDescending().take(3).sum() println("Sum of top 3 total calories : $top3Sum") } private fun List<String>.toCarriedCaloriesPerElve(): List<List<String>> = fold(emptyList()) { acc, s -> if(acc.isEmpty()) { listOf(listOf(s)) }else if(s.isBlank()) { acc + listOf(listOf()) } else { acc.take(acc.size - 1) + listOf(acc.last() + s) } } private fun List<List<String>>.toCaloriesIntakePerElve() = map { calories -> calories.fold(0) { acc, s -> s.toInt() + acc } }
0
Kotlin
0
0
96aadef37d79bcd9880dbc540e36984fb0f83ce0
917
AoC-2022
Apache License 2.0
aoc-2023/src/main/kotlin/nerok/aoc/aoc2023/day03/Day03.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2023.day03 import nerok.aoc.utils.Input import nerok.aoc.utils.Point import nerok.aoc.utils.append import nerok.aoc.utils.createCharGrid import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: List<String>): Long { val engineSchematic = createCharGrid(input) val validPartNumbers = emptyList<Long>().toMutableList() var currentPartNumber = "" var currentPartNumberValid = false engineSchematic.rows.forEach { row -> row.forEach { point -> if (point.content.isDigit()) { currentPartNumber = "$currentPartNumber${point.content}" engineSchematic.neighbours(point).forEach { neighbour -> if ((!neighbour.content.isDigit()) and (neighbour.content != '.')) { currentPartNumberValid = true } } } else { if (currentPartNumberValid) { validPartNumbers.append(currentPartNumber.toLong()) } currentPartNumber = "" currentPartNumberValid = false } } } return validPartNumbers.sum() } fun part2(input: List<String>): Long { val engineSchematic = createCharGrid(input) val validPartNumbers = emptyList<Pair<Point<Char>,Long>>().toMutableList() var currentPartNumber = "" var currentPartNumberSymbol: Point<Char>? = null engineSchematic.rows.forEachIndexed { rowIndex, row -> row.forEachIndexed { columnIndex, point -> if (point.content.isDigit()) { currentPartNumber = "$currentPartNumber${point.content}" engineSchematic.neighbours(point).forEach { neighbour -> if ((!neighbour.content.isDigit()) and (neighbour.content != '.')) { currentPartNumberSymbol = neighbour } } } else { if (currentPartNumberSymbol != null) { validPartNumbers.append(currentPartNumberSymbol!! to currentPartNumber.toLong()) } currentPartNumber = "" currentPartNumberSymbol = null } } } return validPartNumbers .groupBy { it.first } .filterKeys { it.content == '*' } .filterValues { it.size > 1 } .map { it.key to it.value.map { it.second }.reduce { acc, l -> acc * l } } .sumOf { it.second } } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day03_test") check(part1(testInput) == 4361L) check(part2(testInput) == 467835L) val input = Input.readInput("Day03") println("Part1:") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println("Part2:") println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
3,216
AOC
Apache License 2.0
src/Day21.kt
rod41732
572,917,438
false
{"Kotlin": 85344}
fun main() { fun part1(input: List<String>): Long { val ctx = ExpressionContext() input.forEach { val parts = it.split(" ") val name = parts[0].substring(0, 4) val cur = ctx.get(name) when (parts.size) { 2 -> cur.num = parts[1].toLong() 4 -> { val (l, m, r) = parts.subList(1, 4) cur.left = ctx.get(l) cur.right = ctx.get(r) cur.op = m } } } return ctx.get("root").calculatedValue } fun part2(input: List<String>): Long { val ctx = ExpressionContext() input.forEach { val parts = it.split(" ") val name = parts[0].substring(0, 4) val cur = ctx.get(name) if (name == "humn") { cur.isUnknown = true return@forEach } when (parts.size) { 2 -> cur.num = parts[1].toLong() 4 -> { val (l, m, r) = parts.subList(1, 4) cur.left = ctx.get(l) cur.right = ctx.get(r) cur.op = m } } } val root = ctx.get("root") var (human, monkey) = ctx.get("root").children().map { it.value } // while (human != ctx.get("humn")) { while( human != ctx.get("humn")) { solve(human, monkey).let { (x, y) -> human = x monkey = y } } // } return monkey.calculatedValue } val testInput = readInput("Day21_test") println(part1(testInput)) check(part1(testInput) == 152L) println(part2(testInput)) check(part2(testInput) == 301L) val input = readInput("Day21") println("Part1") println(part1(input)) // 51928383302238 println("Part2") println(part2(input)) // 3305669217840 } fun solve(withUnknown: Expression2, constant: Expression2): Pair<Expression2, Expression2> { val (unknown, known) = withUnknown.children() return when (withUnknown.op!!) { "+" -> unknown.value to Expression2(left = constant, op = "-", right = known.value) "-" -> unknown.value to Expression2(left = known.value, op = if (known.index == 0) "-" else "+", right = constant) "*" -> unknown.value to Expression2(left = constant, op = "/", right = known.value) "/" -> unknown.value to Expression2(left = known.value, op = if (known.index == 0) "/" else "*", right = constant) else -> throw Error("XD") } } data class Expression2( var num: Long? = null, var left: Expression2? = null, var op: String? = null, var right: Expression2? = null, var isUnknown: Boolean = false, ) { val calculatedValue: Long by lazy { if (num != null) num!! else { val l = left!! val r = right!! when (op!!) { "+" -> l.calculatedValue + r.calculatedValue "-" -> l.calculatedValue - r.calculatedValue "*" -> l.calculatedValue * r.calculatedValue "/" -> l.calculatedValue / r.calculatedValue else -> throw Error("XD") } } } val containsUnknown: Boolean by lazy { when { isUnknown -> true num != null -> false else -> left!!.containsUnknown || right!!.containsUnknown } } /** return 2 tuple of indexedvalue, first element's value always contains unknown, seconds doesn't, * the index allow determining if it's left or right child */ fun children(): List<IndexedValue<Expression2>> { return listOf(left!!, right!!).withIndex().sortedBy { if (it.value.containsUnknown) 0 else 1 } } override fun toString(): String { if (num != null) return num!!.toString() else if (isUnknown) return "X" return "($left $op $right)" } } data class ExpressionContext(private val x: MutableMap<String, Expression2> = mutableMapOf()) { fun get(name: String): Expression2 = x.getOrPut(name) { Expression2() } }
0
Kotlin
0
0
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
4,213
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/cbrew/chart/Chart.kt
cbrew
248,690,438
false
{"Kotlin": 147469, "ANTLR": 8870, "Vue": 8502, "HTML": 303, "Dockerfile": 123}
package com.cbrew.chart import com.cbrew.unify.FeatureMap import com.cbrew.unify.FeatureStructure import com.cbrew.unify.subst import com.cbrew.unify.unify import java.util.* import kotlin.Comparator import kotlin.collections.set /** * A chart is a container for edges. It contains two arrays: one for complete edges, with * edges being stored in a bucket at their start point, and one for partial * edges, with edges being stored at their end point. It also contains a mutable map * that is used to record which partial edges, if any, gave rise to each edge that * is created. Some edges will have been created from the lexicon, so will have no predecessors. */ class Chart(val completes: Array<MutableSet<Complete>>, val partials: Array<MutableSet<Partial>>, val predecessors: MutableMap<Edge, MutableSet<Pair<Partial, Complete>>>, val spans: MutableList<Span>, val sentence: Array<String>) { private val agenda: PriorityQueue<Edge> = PriorityQueue(edgeComparator) constructor(sentence: Array<String>) : this( completes = Array(sentence.size + 1, { _ -> mutableSetOf<Complete>() }), partials = Array(sentence.size + 1, { _ -> mutableSetOf<Partial>() }), predecessors = mutableMapOf(), spans = mutableListOf<Span>(), sentence = sentence) fun stats(doCount: Boolean = true) = mapOf( Pair("sentence", "" + "\"${sentence.joinToString(" ")}\""), Pair("length", sentence.size), Pair("numSolutions", solutions().size), Pair("numCompletes", completes.sumOf { it.size }), Pair("numPartials", partials.sumOf { it.size }), Pair("numTrees", if (doCount) countTrees() else "\"not counted\"")) fun add(e: Edge): Boolean = when (e) { is Complete -> completes[e.start].add(e) is Partial -> partials[e.end].add(e) } fun pairwithpartials(c: Complete): List<Edge> = partials[c.start].mapNotNull { p -> fundamental(p, c)?.let { e -> recordPredecessors(p, c, e); e } } fun pairwithcompletes(p: Partial): List<Edge> = completes[p.end].mapNotNull { c -> fundamental(p, c)?.let { e -> recordPredecessors(p, c, e); e } } // record a predecessor relationship. private fun recordPredecessors(p: Partial, c: Complete, created: Edge) { val pair = Pair(p, c) if (created in predecessors) predecessors[created]?.add(pair) else predecessors[created] = mutableSetOf(pair) } // count the number of distinct trees under an edge fun countTrees(e: Edge): Int = if (e in predecessors) predecessors[e]!!.sumOf { (p, c) -> countTrees(p) * countTrees(c) } else 1 fun countTrees(): Int = solutions().sumOf { countTrees(it) } fun getTrees(e: Edge): Sequence<Tree> = predecessors[e]?.asSequence()?.flatMap { (p, c) -> getTrees(p, c) } ?: /** * if there were no predecessors, we will have gotten null * above, and we have the base case */ sequenceOf(if (e.start == e.end) empty(e) else leaf(e)) fun getTrees(p: Partial, c: Complete): Sequence<Tree> = getTrees(p).flatMap { t1 -> getTrees(c).map { t2 -> val node = t1 as Node Node(node.category, node.children + listOf(t2)) } } fun empty(e: Edge): Node = Node(e.category as FeatureMap, emptyList<Tree>()) // leaf() creates // EITHER a lexical edge with a label and words. // OR an empty edge with a label but no words. // The code is the same either way. fun leaf(e: Edge) = Leaf(e.category as FeatureMap, sentence.sliceArray(IntRange(e.start, e.end - 1))) fun solutions(): List<Complete> { return completes[0].filter { c -> c.end == completes.size - 1 } } fun solutions(target: FeatureStructure): List<Complete> = completes[0].filter { c -> c.end == completes.size - 1 && (unify(c.category, target) != null) } object edgeComparator : Comparator<Edge> { override fun compare(o1: Edge?, o2: Edge?): Int = if (o1!!.start != o2!!.start) o1.start - o2.start else if (o1.end != o2.end) o1.end - o2.end else if (o1.category != o2.category) o1.category.toString().compareTo(o2.category.toString()) else o1.needed.toString().compareTo(o2.needed.toString()) } // comparator that puts complete edges first class CompleteComparator(val predecessors: MutableMap<Edge, MutableSet<Pair<Partial, Complete>>>): Comparator<Complete> { fun creates(e1: Complete, e2: Complete): Boolean { // read as e1 creates e2 val pairs = predecessors[e2] for ((_, c) in pairs ?: listOf()) { if (c == e1) { return true } } return false } override fun compare(o1: Complete?, o2: Complete?): Int { val l1 = o1!!.end - o1.start val l2 = o2!!.end - o2.start if (l1 != l2) return l2 - l1 else if (creates(o1, o2)) return 1 else if (creates(o2, o1)) return -1 else return edgeComparator.compare(o1, o2) } } fun sortedEdges() = completes.flatMap {it}.sortedWith(CompleteComparator(predecessors)) fun wordSpans(): List<Span> = spans /** * bottom-up left-to-right chart parser. */ fun parse(grammar: ChartGrammar) { start(grammar) while (!done()){ oneStep(grammar) } } fun oneStep(grammar: ChartGrammar) : Edge? { val edge = agenda.remove() if (add(edge)) { when (edge) { is Complete -> { agenda.addAll(grammar.spawn(edge)) agenda.addAll(pairwithpartials(edge)) } is Partial -> { agenda.addAll(pairwithcompletes(edge)) } } return edge } else { return null } } fun done() = agenda.size == 0 fun start(grammar:ChartGrammar) { for (j in 0 until sentence.size) { // 1. Single word lexical entries val cats = grammar.lookup(sentence.get(j), j) if(cats.size > 0) { spans.add(Span(label=sentence.get(j),start=j,end=j+1)) agenda.addAll(cats) } // 2. Multiple word lexical entries ending here for (i in 0 until j) { val prefix: List<String> = sentence.sliceArray(IntRange(i, j)).toList() val cats = grammar.lookup(prefix, i, j + 1) if(cats.size > 0) { spans.add(Span(label = prefix.joinToString(" "), start = i, end = j + 1)) agenda.addAll(cats) } } } } fun debug(grammar: ChartGrammar) { start(grammar) while (!done()){ val edge = oneStep(grammar) if(edge != null){ println(edge) } } } /** * fundamental rule of chart parsing. * Returns new edge if possible. * Returns null if partial and complete are incompatible. */ fun fundamental(partial: Partial, complete: Complete): Edge? = unify(partial.needed.first(), complete.category) ?.let { (_, bindings) -> makeEdge(bindings.subst(partial.category), partial.start, complete.end, bindings.subst(partial.needed.subList(1, partial.needed.size))) } fun nonterminals(): List<Span> { return sortedEdges().filter {predecessors.containsKey(it)}.map {Span((it.category as FeatureMap)["cat"].toString(),it.start,it.end)} } fun preterminals(): List<Span> { return sortedEdges().filter {! predecessors.containsKey(it)}.map {Span((it.category as FeatureMap)["cat"].toString(),it.start,it.end)} } fun fullSemantics(): Map<Int, String> { return mapOf() } fun simpleSemantics(): Map<Int, Predicate> { return mapOf() } fun fullSyntax(): Map<Int, String> { return mapOf() } }
1
Kotlin
0
0
16c4e42911782595e419f38c23796ce34b65f384
8,892
quadruplet
Apache License 2.0
src/Day03.kt
diesieben07
572,879,498
false
{"Kotlin": 44432}
private val file = "Day03" private data class RucksackContents(val contents: String) { val firstCompartment: String get() = contents.substring(0, contents.length / 2) val secondCompartment: String get() = contents.substring(contents.length / 2) fun getCommonItemType(): Char { return firstCompartment.toSet().intersect(secondCompartment.toSet()).single() } } private fun Char.getPriority(): Int { return if (this in 'a'..'z') { this - 'a' + 1 } else { this - 'A' + 27 } } private fun Sequence<String>.parseInput(): Sequence<RucksackContents> { return map { RucksackContents(it) } } private fun part1() { streamInput(file) { input -> println(input.parseInput().map { it.getCommonItemType() }.map { it.getPriority() }.sum()) } } private fun part2() { streamInput(file) { input -> val result = input.parseInput().chunked(3).map { group -> val set = group[0].contents.toHashSet() set.retainAll(group[1].contents.toHashSet()) set.retainAll(group[2].contents.toHashSet()) set.single() }.map { it.getPriority() }.sum() println(result) } } fun main() { part1() part2() }
0
Kotlin
0
0
0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6
1,232
aoc-2022
Apache License 2.0
src/Day03.kt
chbirmes
572,675,727
false
{"Kotlin": 32114}
fun main() { fun part1(input: List<String>): Int = input.map { it.charInBothHalves() } .sumOf { it.priority() } fun part2(input: List<String>): Int = input.chunked(3) .map { it.charInEach() } .sumOf { it.priority() } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } private fun List<String>.charInEach() = drop(1) .fold(first().toSet()) {intersection, string -> intersection.intersect(string.toSet())} .first() private fun Char.priority() = if (isLowerCase()) 1 + code - 'a'.code else 27 + code - 'A'.code private fun String.charInBothHalves() = take(length / 2) .toSet() .intersect(takeLast(length / 2).toSet()) .first()
0
Kotlin
0
0
db82954ee965238e19c9c917d5c278a274975f26
915
aoc-2022
Apache License 2.0
solutions/aockt/y2021/Y2021D11.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2021 import io.github.jadarma.aockt.core.Solution object Y2021D11 : Solution { /** Represents a 10x10 2D map of octopus energy levels, as scanned by the submarine. */ private class OctopusMap(initial: List<Int>) { /** Represents a discrete point in 2D space. */ private data class Point(val x: Int, val y: Int) /** The state of an octopus, keeps track of location, energy level, and whether it flashed this turn. */ private data class Octopus(val coordinates: Point, var energy: Int = 0, var flashed: Boolean = false) { /** Energize this octopus and return whether it flashed as a result of gaining new energy. */ fun energize(): Boolean { if (flashed) return false energy = if (energy < 9) energy + 1 else 0 flashed = energy == 0 return flashed } } private val data: Array<Octopus> init { require(initial.size == 100) { "Not enough data points." } data = Array(100) { Octopus(coordinates = Point(it / 10, it % 10), energy = initial[it]) } } /** Returns all the [Point]s that are orthogonally or diagonally adjacent to this one. */ private fun Point.adjacent(): Set<Point> = buildSet { for (i in (x - 1)..(x + 1)) { if (i !in 0..9) continue for (j in (y - 1)..(y + 1)) { if (j !in 0..9) continue add(Point(i, j)) } } remove(this@adjacent) } /** Simulate the next step of the energy cycle and return all points at which an octopus flashed. */ fun simulateStep(): Set<Point> = buildSet { data.forEach { it.flashed = false it.energize() if (it.flashed) add(it.coordinates) } val flashQueue = ArrayDeque(this) while (flashQueue.isNotEmpty()) { flashQueue.removeFirst().adjacent().forEach { point -> data[point.x * 10 + point.y].takeIf { it.energize() }?.coordinates?.let { add(it) flashQueue.addLast(it) } } } } } /** Parse the [input] and return the [OctopusMap] as scanned by the submarine. */ private fun parseInput(input: String): OctopusMap = input .lines().joinToString("") .map { it.digitToInt() } .let(::OctopusMap) override fun partOne(input: String) = parseInput(input).run { (1..100).fold(0) { acc, _ -> acc + simulateStep().size } } override fun partTwo(input: String) = parseInput(input).run { var step = 1 while (simulateStep().size != 100) step++ step } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
2,935
advent-of-code-kotlin-solutions
The Unlicense
src/y2022/day02.kt
sapuglha
573,238,440
false
{"Kotlin": 33695}
package y2022 import readFileAsLines import java.lang.IllegalArgumentException fun main() { fun part1(input: List<String>): Int = input.sumOf { line -> val round = line.split(" ") val theirMove = round.first().toHand() val myMove = round.last().toHand() when (theirMove) { Hand.ROCK -> when (myMove) { Hand.ROCK -> Outcome.DRAW.score + myMove.score Hand.PAPER -> Outcome.WIN.score + myMove.score Hand.SCISSOR -> Outcome.LOSE.score + myMove.score } Hand.PAPER -> when (myMove) { Hand.ROCK -> Outcome.LOSE.score + myMove.score Hand.PAPER -> Outcome.DRAW.score + myMove.score Hand.SCISSOR -> Outcome.WIN.score + myMove.score } Hand.SCISSOR -> when (myMove) { Hand.ROCK -> Outcome.WIN.score + myMove.score Hand.PAPER -> Outcome.LOSE.score + myMove.score Hand.SCISSOR -> Outcome.DRAW.score + myMove.score } } } fun part2(input: List<String>): Int = input.sumOf { line -> val round = line.split(" ") val theirMove = round.first().toHand() val desiredOutcome = round.last().toOutcome() when (theirMove) { Hand.ROCK -> when (desiredOutcome) { Outcome.WIN -> desiredOutcome.score + Hand.PAPER.score Outcome.DRAW -> desiredOutcome.score + Hand.ROCK.score Outcome.LOSE -> desiredOutcome.score + Hand.SCISSOR.score } Hand.PAPER -> when (desiredOutcome) { Outcome.WIN -> desiredOutcome.score + Hand.SCISSOR.score Outcome.DRAW -> desiredOutcome.score + Hand.PAPER.score Outcome.LOSE -> desiredOutcome.score + Hand.ROCK.score } Hand.SCISSOR -> when (desiredOutcome) { Outcome.WIN -> desiredOutcome.score + Hand.ROCK.score Outcome.DRAW -> desiredOutcome.score + Hand.SCISSOR.score Outcome.LOSE -> desiredOutcome.score + Hand.PAPER.score } } } "y2022/data/day02".readFileAsLines().let { input -> println("part1: ${part1(input)}") println("part2: ${part2(input)}") } } enum class Hand(val score: Int) { ROCK(1), PAPER(2), SCISSOR(3), } enum class Outcome(val score: Int) { WIN(6), DRAW(3), LOSE(0), } fun String.toHand(): Hand = when (this) { "A", "X" -> Hand.ROCK "B", "Y" -> Hand.PAPER "C", "Z" -> Hand.SCISSOR else -> throw IllegalArgumentException() } fun String.toOutcome(): Outcome = when (this) { "X" -> Outcome.LOSE "Y" -> Outcome.DRAW "Z" -> Outcome.WIN else -> throw IllegalArgumentException() }
0
Kotlin
0
0
82a96ccc8dcf38ae4974e6726e27ddcc164e4b54
2,810
adventOfCode2022
Apache License 2.0
src/y2015/Day19.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2015 import util.readInput import util.split import y2015.Day19.analysis import kotlin.math.max typealias Replacements = Map<String, List<String>> typealias Molecule = List<String> object Day19 { private fun parse(input: List<String>): Pair<Replacements, String> { val replacements = input.dropLast(2).map { val (original, replace) = it.split(" => ") original to replace }.groupBy { it.first }.mapValues { (_, v) -> v.map { it.second } } return replacements to input.last() } fun part1(input: List<String>): Int { val (replacements, start) = parse(input) val elements = moleculeToElements(start) println(elements) val results = oneStepReplacements(elements, replacements) return results.size } private fun moleculeToElements(start: String) = start.toList().split(matchInPost = true) { it.isUpperCase() }.drop(1).map { it.joinToString(separator = "") } private fun oneStepReplacements( elements: List<String>, replacements: Replacements ) = elements.flatMapIndexed { idx, element -> val tmp = elements.toMutableList() (replacements[element] ?: listOf()).map { tmp[idx] = it tmp.joinToString(separator = "") } }.toSet() private fun oneStepP2( startMolecule: Molecule, replacements: Map<String, List<Molecule>> ): List<Molecule> { return startMolecule.flatMapIndexed { idx, element -> (replacements[element] ?: listOf()).map { startMolecule.safeTake(idx - 1) + it + startMolecule.drop(idx + 1) } } } private fun Molecule.safeTake(idx: Int) = this.take(max(0, idx)) private fun parse2(input: List<String>): Pair<Map<String, String>, String> { val replacements = input.dropLast(5).associate { val (original, replace) = it.split(" => ") replace to original } return replacements to input.last() } fun part2(input: List<String>): Int { val (replacementsStr, targetStr) = parse(input) val target = moleculeToElements(targetStr) val replacements = replacementsStr.mapValues { (_, results) -> results.map { moleculeToElements(it) } } var steps = 1 var stepMolecules = setOf(listOf("H", "F"), listOf("N", "Al"), listOf("O", "Mg")) val alreadyExplored = mutableSetOf<Molecule>() alreadyExplored.addAll(stepMolecules) while (target !in stepMolecules) { println("step: $steps") println("molecules: ${stepMolecules.size}") println("explored: ${alreadyExplored.size}") println("longest: ${alreadyExplored.maxBy { it.size }}") stepMolecules = stepMolecules.flatMap { oneStepP2(it, replacements) }.toSet() val intersect = stepMolecules.intersect(alreadyExplored) println("duplicates: ${intersect.size}") stepMolecules = stepMolecules - intersect val new = stepMolecules.size println("new molecules: $new") alreadyExplored.addAll(stepMolecules) stepMolecules = stepMolecules.filter { reachable(it, targetStr) }.toSet() println("dead ends: ${new - stepMolecules.size}") steps++ } return steps } private val finals = setOf("C", "Rn", "Ar", "Y") private fun reachable(molecule: List<String>, targetStr: String): Boolean { val re = molecule.joinToString(separator = "", prefix = "^", postfix = "$") { if (it in finals) it else "@" }.replace(Regex("@+"), ".+") return Regex(re).matchEntire(targetStr) != null } fun analysis(input: List<String>) { val (replacements, target) = parse(input) val validKeys = mutableSetOf("e") var newKeys = setOf("e") repeat(3) { newKeys = newKeys.flatMap { key -> (replacements[key] ?: listOf()).flatMap { moleculeToElements(it) } }.toSet() validKeys.addAll(newKeys) println("new: $newKeys") println(validKeys) } println("actual keys: ${validKeys.intersect(replacements.keys)}") println("dead ends: ${validKeys - replacements.keys}") val (inverse, _) = parse2(input) println("original keys: ${inverse.keys.size}") val unreachable = inverse.filterKeys { it.contains(Regex("Rn|Ar|Y|C[^a]]")) } println("contains dead end: ${unreachable.size}") println(unreachable) /*replacements.forEach { (key, values) -> //println("reachable from $key") moleculeToElements(values.joinToString("")).toSet().forEach { println(" $key --> $it") } }*/ val foo = replacements.values.flatten().map { mol -> val els = moleculeToElements(mol) els to finals.any { it in els } } val (dead, notDead) = foo.partition { it.second } println("partition first:") dead.forEach { val fResults = it.first.filter { it in finals} println("${it.first.size} $fResults, ${fResults.size}") } println("partition second:") notDead.forEach { println(it.first.size) } val targetElements = moleculeToElements(target) println("target length: ${targetElements.size}") println("target dead ends: ${targetElements.filter { it in finals }.size}") println("target only dead ends: ${targetElements.filter { it in finals }}") } } fun main() { val testInput = """ H => HO H => OH O => HH e => H e => O e => X HOHOHO """.trimIndent().split("\n") println("------Tests------") println(Day19.part1(testInput)) //println(Day19.part2(testInput)) println("------Real------") val input = readInput("resources/2015/day19") println(Day19.part1(input)) analysis(input) //println(Day19.part2(input)) } /** * total length: 274 * Only dead ends: [C, Rn, Rn, Rn, Ar, Ar, Rn, Ar, Rn, Ar, Rn, Ar, Rn, Rn, Ar, Ar, Rn, Rn, Ar, Y, Rn, Y, Ar, Ar, Rn, Ar, Rn, Y, Rn, Ar, Ar, Rn, Rn, Ar, Y, Ar, Rn, Ar, Rn, Y, Ar, Rn, Ar, Rn, Y, Ar, Rn, Ar, Rn, Ar, Rn, Ar, Rn, Rn, Y, Ar, Ar, Ar, Rn, Rn, Ar, Ar, Rn, Ar, Rn, Ar, Rn, Y, Ar, Rn, Ar] * Rn / Ar: 31 * Y: 8 * C: 1 * * 31 replacements had at least +3 * of those, at least an additional 6 had an additional +2 for Y * * option 1: * C was added without Y → two additional +2 for .Rn.Y.Ar * option 2: * C was added with one Y → one additional +2 for CRN.Y.AR, one +2 for .Rn.Y.Ar * option 3 * C was added with two Ys → one additional +4 for CRnFYFYFAr * C is already accounted for in all cases as it is included in the +3 for .Rn.Ar * C always gets added together with Rn/Ar, so it does not add a replacement. * The 2 additional Ys always add +4 to the length. * * 31 .Rn.Ar replacements add length 31 * 3 = 93 * with 8 Ys (+16): 109 * 274 - 109 + 31 = 165 + 31 = 196 * subtract one, because at step zero we have length 1 → 195 */
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
7,339
advent-of-code
Apache License 2.0
Kotlin/problems/0008_array_nesting.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
// Proble Statement // // A zero-indexed array A of length N contains all integers from 0 to N-1. // Find and return the longest length of set S, // where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. // // Suppose the first element in S starts with the selection of element A[i] // of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… // By that analogy, we stop adding right before a duplicate element occurs in S. // // Example: // Input: A = [5,4,0,3,1,6,2] // Output: 4 // Explanation: // A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. // // One of the longest S[K]: // S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} class Solution { fun arrayNesting(nums: IntArray): Int { var visited:HashSet<Int> = HashSet<Int>(); var result:Int = 0; for(index in nums.indices){ if(!visited.contains(index)){ var dfs:ArrayList<Int> = ArrayList<Int>(); var actual_counter:Int = 0; dfs.add(index); while(!dfs.isEmpty()){ var last:Int = dfs.last(); dfs.removeAt(dfs.size-1); if(!visited.contains(last)){ visited.add(last); dfs.add(nums[last]); actual_counter++; } } result = maxOf(result,actual_counter); } } return result; } } fun main(args:Array<String>){ var sol: Solution = Solution(); var vec: IntArray = intArrayOf(5,4,0,3,1,6,2); println(sol.arrayNesting(vec)); }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
1,664
algorithms
MIT License
src/main/kotlin/Day04.kt
robert-iits
573,124,643
false
{"Kotlin": 21047}
class Day04 { fun part1(input: List<String>): Int { return input.sumOf { sectionPair -> stringToRanges(sectionPair.split(',')) .let { ranges -> countFullOverlap(ranges.first(), ranges.last()) } } } private fun stringToRanges(listOfStrings: List<String>): List<IntRange> { return listOfStrings.map { IntRange(it.split('-').first().toInt(), it.split('-').last().toInt()) } } fun countFullOverlap(range1: IntRange, range2: IntRange): Int { return if ((range1.minus(range2).isEmpty() || range2.minus(range1).isEmpty())) 1 else 0 } fun countOverlap(range1: IntRange, range2: IntRange): Int { return if (range1.count() + range2.count() > range1.plus(range2).toSet().size) 1 else 0 } fun part2(input: List<String>): Int { return input.sumOf { sectionPair -> stringToRanges(sectionPair.split(',')) .let { ranges -> countOverlap(ranges.first(), ranges.last()) } } } } fun main() { println("part 1:") println(Day04().part1(readInput("Day04"))) println("part 2:") println(Day04().part2(readInput("Day04"))) }
0
Kotlin
0
0
223017895e483a762d8aa2cdde6d597ab9256b2d
1,173
aoc2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinDays.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 1553. Minimum Number of Days to Eat N Oranges * @see <a href="https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/">Source</a> */ sealed interface MinDays { operator fun invoke(n: Int): Int } class MinDaysSimple : MinDays { private var dp: MutableMap<Int, Int> = HashMap() override operator fun invoke(n: Int): Int { if (n <= 1) { return n } if (!dp.containsKey(n)) { dp[n] = 1 + min(n % 2 + invoke(n / 2), n % 3 + invoke(n / 3)) } return dp.getOrDefault(n, n) } } class MinDaysDP : MinDays { private var dp = mutableMapOf(0 to 0, 1 to 1, 2 to 2) override operator fun invoke(n: Int): Int { return solve(n) } private fun solve(n: Int): Int { if (dp.containsKey(n)) { return dp.getOrDefault(n, -1) } var ans = Int.MAX_VALUE when { n % 2 == 0 && n % 3 == 0 -> { ans = min(ans, 1 + min(solve(n / 2), solve(n / 3))) } n % 3 == 0 -> { ans = min(ans, 1 + min(solve(n - 1), solve(n / 3))) } n % 2 == 0 -> { ans = if ((n - 1) % 3 == 0) { min(ans, 1 + min(solve(n / 2), solve(n - 1))) } else { min(ans, min(1 + solve(n / 2), 2 + solve(n - 2))) } } else -> { ans = min(ans, 1 + solve(n - 1)) if ((n - 2) % 3 == 0) { ans = min(ans, 2 + solve(n - 2)) } } } dp[n] = ans return dp.getOrDefault(n, n) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,351
kotlab
Apache License 2.0
src/day8/Day08.kt
jorgensta
573,824,365
false
{"Kotlin": 31676}
fun asGrid(input: List<String>) = input.map { it .split("") .mapNotNull { s -> s.toIntOrNull() } } fun countPerimeter(grid: List<List<Int>>): Int { val height = grid.size val width = grid.first().size return (height + width) * 2 - 4 // counts the corners four times ;) } fun visibleFromRight(row: Int, column: Int, grid: List<List<Int>>): Boolean { val width = grid.first().size val toCheck = grid[row].subList(column + 1, width) return toCheck.all { grid[row][column] > it } } fun visibleFromLeft(row: Int, column: Int, grid: List<List<Int>>): Boolean { val toCheck = grid[row].subList(0, column).reversed() val value = grid[row][column] return toCheck.all { value > it } } fun gridToFixedColumn(column: Int, grid: List<List<Int>>): List<Int> { return grid.map { it[column] } } fun visibleFromBottom(row: Int, column: Int, grid: List<List<Int>>): Boolean { val toCheck = gridToFixedColumn(column, grid).subList(row + 1, grid.first().size) return toCheck.all { grid[row][column] > it } } fun visibleFromTop(row: Int, column: Int, grid: List<List<Int>>): Boolean { val toCheck = gridToFixedColumn(column, grid).subList(0, row) return toCheck.all { grid[row][column] > it } } fun visible(row: Int, column: Int, grid: List<List<Int>>): Boolean = visibleFromLeft(row, column, grid) || visibleFromBottom(row, column, grid) || visibleFromTop(row, column, grid) || visibleFromRight(row, column, grid) fun visibleFromOutside(grid: List<List<Int>>): Int { var count = 0 for (row in 1 until grid.size - 1) { // Shrink grid on both top and bottom for (column in 1 until grid[row].size - 1) { if (visible(row, column, grid)) count++ } } return count } fun gotBlocked(height: Int, otherHeight: Int) = otherHeight >= height fun calculate(height: Int, treesInOneDirection: List<Int>): Int { var count = 0 for (otherHeight in treesInOneDirection) { if (gotBlocked(height, otherHeight)) { count ++ break } if (height > otherHeight) count++ } return count } fun calculateScenicScore(row: Int, col: Int, grid: List<List<Int>>): Int { val top = gridToFixedColumn(col, grid).subList(0, row).reversed() var right = grid[row].subList(col + 1, grid.first().size) if (col == grid.first().size) right = emptyList() var bottom = gridToFixedColumn(col, grid).subList(row + 1, grid.first().size) if (row == grid.size) bottom = emptyList() val left = grid[row].subList(0, col).reversed() val tree = grid[row][col] return calculate(tree, top) * calculate(tree, right) * calculate(tree, bottom) * calculate(tree, left) } fun bestScenicScore(grid: List<List<Int>>): Int { val scenicScores = mutableListOf<Int>() for (row in 0..grid.size - 1) { for (col in 0..grid.first().size - 1) { scenicScores.add(calculateScenicScore(row, col, grid)) } } return scenicScores.max() } fun part1(input: List<String>): Int { val grid = asGrid(input) return countPerimeter(grid) + visibleFromOutside(grid) } fun part2(input: List<String>): Int { return bestScenicScore(asGrid(input)) } fun main() { val day = "day8" val filename = "Day08" // test if implementation meets criteria from the description, like: val testInput = readInput("/$day/${filename}_test") val input = readInput("/$day/$filename") val partOneTest = part1(testInput) check(partOneTest == 21) println("Part one: ${part1(input)}") val partTwoTest = part2(testInput) check(partTwoTest == 8) println("Part two: ${part2(input)}") }
0
Kotlin
0
0
7243e32351a926c3a269f1e37c1689dfaf9484de
3,708
AoC2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem983/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem983 /** * LeetCode page: [983. Minimum Cost For Tickets](https://leetcode.com/problems/minimum-cost-for-tickets/); */ class Solution2 { /* Complexity: * Time O(N) and Space O(N) where N is the size of days; */ fun mincostTickets(days: IntArray, costs: IntArray): Int { // suffixMinCost[i] ::= the min cost of the suffix array of days start from index i val suffixMinCost = IntArray(days.size + 1) // The last index of days that the pass is still valid var weekPassExpiryDayIndex = days.lastIndex var monthPassExpiryDayIndex = days.lastIndex for (i in days.indices.reversed()) { // Case 1: We buy a day pass on day[i] val firstDay = days[i] val dayPassFirstInvalidIndex = i + 1 val dayPassMinCost = costs[0] + suffixMinCost[dayPassFirstInvalidIndex] // Case 2: We buy a week pass on day[i] val weekPassExpiryDay = firstDay + 6 weekPassExpiryDayIndex = days.lastIndex(upperIndex = weekPassExpiryDayIndex) { day -> day <= weekPassExpiryDay } val weekPassFirstInvalidIndex = weekPassExpiryDayIndex + 1 val weekPassMinCost = costs[1] + suffixMinCost[weekPassFirstInvalidIndex] // Case 3: We buy a month pass on day[i] val monthPassExpiryDay = firstDay + 29 monthPassExpiryDayIndex = days.lastIndex(upperIndex = monthPassExpiryDayIndex) { day -> day <= monthPassExpiryDay } val monthPassFirstInvalidIndex = monthPassExpiryDayIndex + 1 val monthPassMinCost = costs[2] + suffixMinCost[monthPassFirstInvalidIndex] // The min cost is the min among possible cases suffixMinCost[i] = minOf(dayPassMinCost, weekPassMinCost, monthPassMinCost) } return suffixMinCost[0] } private fun IntArray.lastIndex( upperIndex: Int = lastIndex, fallBackValue: Int = -1, predicate: (element: Int) -> Boolean = { true } ): Int { var index = upperIndex while (index >= 0) { val element = this[index] val isMatched = predicate(element) if (isMatched) return index index-- } return fallBackValue } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,361
hj-leetcode-kotlin
Apache License 2.0
src/Day01.kt
sbaumeister
572,855,566
false
{"Kotlin": 38905}
fun main() { fun part1(input: List<String>): Int { var maxSumCalories = 0 var sumCalories = 0 input.forEach { if (it == "") { sumCalories = 0 } else { sumCalories += it.toInt() if (sumCalories > maxSumCalories) { maxSumCalories = sumCalories } } } return maxSumCalories } fun part2(input: List<String>): Int { val calorieSums = arrayListOf<Int>() var sumCalories = 0 input.forEachIndexed { i, line -> if (line == "") { calorieSums.add(sumCalories) sumCalories = 0 } else { sumCalories += line.toInt() // add last sum if (i == input.size - 1) { calorieSums.add(sumCalories) } } } return calorieSums.sortedDescending().take(3).sum() } 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
e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84
1,211
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/paulshields/aoc/Day21.kt
Pkshields
433,609,825
false
{"Kotlin": 133840}
/** * Day 21: Dirac Dice */ package dev.paulshields.aoc import dev.paulshields.aoc.common.readFileAsStringList fun main() { println(" ** Day 21: Dirac Dice ** \n") val diracDiceStaringPositionsText = readFileAsStringList("/Day21StartingPositions.txt") val playerOnePosition = diracDiceStaringPositionsText[0].split(" ").last().toInt() val playerTwoPosition = diracDiceStaringPositionsText[1].split(" ").last().toInt() val gameResults = playDiracDiceWithDeterminateDie(playerOnePosition, playerTwoPosition) val finalCalculation = when (gameResults.winner) { Player.PLAYER_ONE -> gameResults.playerTwoScore * gameResults.numberOfDieRolls else -> gameResults.playerOneScore * gameResults.numberOfDieRolls } println("The final result after playing the game with a deterministic die is $finalCalculation") val resultsFromAllRealities = playDiracDiceWithQuantumDie(playerOnePosition, playerTwoPosition) val result = resultsFromAllRealities.map { it.value }.maxOf { it } println("When playing with the quantum die, the player who wins the most wins in $result universes.") } fun playDiracDiceWithDeterminateDie(playerOneStartingPosition: Int, playerTwoStartingPosition: Int): DiracDiceResults { var playerOnePosition = playerOneStartingPosition - 1 var playerTwoPosition = playerTwoStartingPosition - 1 var playerOneScore = 0 var playerTwoScore = 0 val die = DeterministicDie() var playerTurn = Player.PLAYER_ONE while (playerOneScore < 1000 && playerTwoScore < 1000) { val steps = die.rollDie() + die.rollDie() + die.rollDie() if (playerTurn == Player.PLAYER_ONE) { playerOnePosition = (playerOnePosition + steps) % 10 playerOneScore += playerOnePosition + 1 playerTurn = Player.PLAYER_TWO } else { playerTwoPosition = (playerTwoPosition + steps) % 10 playerTwoScore += playerTwoPosition + 1 playerTurn = Player.PLAYER_ONE } } return DiracDiceResults(playerOneScore, playerTwoScore, die.numberOfRolls) } data class DiracDiceResults(val playerOneScore: Int, val playerTwoScore: Int, val numberOfDieRolls: Int) { val winner = if (playerOneScore >= 1000) Player.PLAYER_ONE else Player.PLAYER_TWO } class DeterministicDie { var numberOfRolls = 0 private set private var lastRole = -1 fun rollDie(): Int { ++numberOfRolls lastRole = (lastRole + 1) % 100 return lastRole + 1 } } fun playDiracDiceWithQuantumDie(playerOneStartingPosition: Int, playerTwoStartingPosition: Int): Map<Player, Long> { val initialGameData = DiracDiceGameData( 0, playerOneStartingPosition - 1, 0, playerTwoStartingPosition - 1, Player.PLAYER_ONE) val memoizeData = mutableMapOf<Pair<DiracDiceGameData, Int>, Map<Player, Long>>() val resultsFromAllUniverses = allPossibleQuantumDieRolls().map { playDiracDiceWithQuantumDie(initialGameData, it, memoizeData) } return sumNumericMaps(resultsFromAllUniverses) } private fun playDiracDiceWithQuantumDie( gameData: DiracDiceGameData, nextRole: Int, memoizeData: MutableMap<Pair<DiracDiceGameData, Int>, Map<Player, Long>>): Map<Player, Long> { memoizeData[gameData to nextRole]?.let { return it } val gameDataAfterMove = gameData.moveNextPlayerBy(nextRole) if (gameDataAfterMove.playerOneScore >= 21) { return mapOf(Player.PLAYER_ONE to 1, Player.PLAYER_TWO to 0) } else if (gameDataAfterMove.playerTwoScore >= 21) { return mapOf(Player.PLAYER_ONE to 0, Player.PLAYER_TWO to 1) } val resultsFromAllUniverses = allPossibleQuantumDieRolls() .map { playDiracDiceWithQuantumDie(gameDataAfterMove, it, memoizeData) } return sumNumericMaps(resultsFromAllUniverses) .also { memoizeData[gameData to nextRole] = it } } private fun allPossibleQuantumDieRolls() = (1..3).flatMap { one -> (1..3).flatMap { two -> (1..3).map { one + two + it } } } private fun sumNumericMaps(maps: List<Map<Player, Long>>) = maps.first() .keys .associateWith { player -> maps.mapNotNull { it[player] }.sumOf { it } } data class DiracDiceGameData( val playerOneScore: Int, val playerOnePosition: Int, val playerTwoScore: Int, val playerTwoPosition: Int, val nextPlayerToMove: Player) { fun moveNextPlayerBy(steps: Int) = if (nextPlayerToMove == Player.PLAYER_ONE) { val playerPosition = (playerOnePosition + steps) % 10 val playerScore = playerOneScore + playerPosition + 1 DiracDiceGameData(playerScore, playerPosition, playerTwoScore, playerTwoPosition, Player.PLAYER_TWO) } else { val playerPosition = (playerTwoPosition + steps) % 10 val playerScore = playerTwoScore + playerPosition + 1 DiracDiceGameData(playerOneScore, playerOnePosition, playerScore, playerPosition, Player.PLAYER_ONE) } } enum class Player { PLAYER_ONE, PLAYER_TWO }
0
Kotlin
0
0
e3533f62e164ad72ec18248487fe9e44ab3cbfc2
5,128
AdventOfCode2021
MIT License
src/main/kotlin/dec18/Main.kt
dladukedev
318,188,745
false
null
package dec18 fun <T> List<T>.tail(): List<T> = this.drop(1) const val NESTED_PARENTHESIS_REGEX = "\\(([^()]*|\\([^()]*\\))*\\)" fun solveParenthesis(input: String, sum: (String) -> String): String { val parensRegex = Regex(NESTED_PARENTHESIS_REGEX) val paren = parensRegex.find(input) ?: return sum(input) val inParens = paren.value.substring(1, paren.value.length -1) val updatedInput = parensRegex.replaceFirst(input, solveParenthesis(inParens, sum)) return solveParenthesis(updatedInput, sum) } fun newMath(input: String): String { val parts = input.split(" ") if(parts.count() == 1) { return input } val firstInput = parts.first().toLong() val chunks = parts.tail().chunked(2) return chunks.fold(firstInput) { accum, (operation, value) -> when(operation) { "*" -> accum * value.toLong() "+" -> accum + value.toLong() else -> throw Exception("Unknown Operation") } }.toString() } fun newAdvancedMath(input: String): String { if (input.toIntOrNull() != null) { return input } val parts = input.split(" * ") return parts.map { it.split(" + ") .map { num -> num.toLong() } .sum() }.reduce { acc, num -> acc * num } .toString() } fun solveEquation(input: String): Long { val flattenedInput = solveParenthesis(input) { newMath(it) } return newMath(flattenedInput).toLong() } fun solveAdvancedEquation(input: String): Long { val flattenedInput = solveParenthesis(input) { newAdvancedMath(it) } return newAdvancedMath(flattenedInput).toLong() } fun main() { val x = input .lines() .map { solveEquation(it) } .sum() println(x) val y = input .lines() .map { solveAdvancedEquation(it) } .sum() println(y) }
0
Kotlin
0
0
d4591312ddd1586dec6acecd285ac311db176f45
1,902
advent-of-code-2020
MIT License
src/Day01.kt
tbilou
572,829,933
false
{"Kotlin": 40925}
fun List<String>.split(): List<List<Int>> { val listOfLists = arrayListOf<List<Int>>() var tmp = arrayListOf<Int>() this.forEach { // if we find an empty line, store the current list and create a new one if (it.isBlank()) { listOfLists.add(tmp) tmp = arrayListOf() } else { tmp.add(it.toInt()) } } listOfLists.add(tmp) return listOfLists } fun main() { // [1,2,3, ,4,4, ,1,4,5] -> [[1,2,3],[4,4],[1,4,5]] // [[1,2,3],[4,4],[1,4,5]] -> [6,8,10] // [6,8,10] -> 10 fun part1(input: List<String>): Int { return input.split() .map { it -> it.fold(0) { total, i -> total + i } } .max() } fun part2(input: List<String>): Int { return input.split() .map { it -> it.fold(0) { total, i -> total + i } } .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) // test if implementation meets criteria from the description, like: val testInput2 = readInput("Day01_test") check(part2(testInput2) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) } // Initial implementation //fun part1(input: List<String>): Int { // // var caloriesPerElf = mutableListOf<Int>() // caloriesPerElf.add(0, 0) // var elf = 0; // for (i in 0..input.size - 1) { // if (input.get(i).isNotEmpty()){ // caloriesPerElf[elf]=caloriesPerElf.get(elf)+input.get(i).toInt() //// caloriesPerElf[elf] = (caloriesPerElf.get(elf)+input.get(i).toInt()) // } // else // { // elf++ // caloriesPerElf.add(elf, 0) // } // } // return caloriesPerElf.max() // return caloriesPerElf[0]+caloriesPerElf[1]+caloriesPerElf[2]
0
Kotlin
0
0
de480bb94785492a27f020a9e56f9ccf89f648b7
2,045
advent-of-code-2022
Apache License 2.0
src/Day03.kt
Akhunzaada
573,119,655
false
{"Kotlin": 23755}
fun main() { fun Char.getPriority() = code - if (isLowerCase()) 96 else 38 fun part1(input: List<String>): Int { var sum = 0 input.forEach skip@ { val firstCompartment = it.subSequence(0, it.length / 2).toSet() for (i in it.length / 2 until it.length) { if (firstCompartment.contains(it[i])) { sum += it[i].getPriority() return@skip } } } return sum } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { val commonItems = HashSet(it.first().toSet()) for (i in 1 until it.size) { commonItems.retainAll(it[i].toSet()) } commonItems.first().getPriority() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b2754454080989d9579ab39782fd1d18552394f0
1,093
advent-of-code-2022
Apache License 2.0
src/Day03.kt
MarkRunWu
573,656,261
false
{"Kotlin": 25971}
import java.lang.Math.abs fun main() { fun getPriority(char: Char): Int { return if (char.code >= 'a'.code) { char.code - 'a'.code } else { char.code - 'A'.code + 26 } + 1 } fun part1(input: List<String>): Int { return input.map { it -> val a = it.substring(0 until it.length / 2) val b = it.substring(it.length / 2 until it.length) a.find { b.contains(it) } }.sumOf { getPriority(it!!) } } fun part2(input: List<String>): Int { return input.mapIndexed { index, s -> Pair(index, s) }.groupBy { it.first / 3 } .map { it.value[0].second.find { c -> it.value[1].second.contains(c) and it.value[2].second.contains(c) } }.sumOf { getPriority(it!!) } } val input = readInput("Day03") input.forEach { check(it.count() % 2 == 0) } check(input.count() % 3 == 0) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ced885dcd6b32e8d3c89a646dbdcf50b5665ba65
1,127
AOC-2022
Apache License 2.0
src/Day07.kt
kedvinas
572,850,757
false
{"Kotlin": 15366}
fun main() { fun part1(input: List<String>): Int { val files = mutableListOf<File>() var workingDirectory = "" for (i in input) { val split = i.split(" ") if (split[0] == "$") { if (split[1] == "cd") { if (split[2] == "/") { workingDirectory = "/" } else if (split[2] == "..") { workingDirectory = workingDirectory.dropLast(1).replaceAfterLast("/", "") } else { workingDirectory += "${split[2]}/" } } } else { if (split[0] != "dir") { files.add(File(name = "$workingDirectory${split[1]}", size = split[0].toInt())) } } } val directorySizes = mutableMapOf<String, Int>() for (f in files) { var name = f.name.replaceAfterLast("/", "") while (name.isNotEmpty()) { var size = directorySizes.getOrDefault(name, 0) directorySizes[name] = size + f.size name = name.dropLast(1).replaceAfterLast("/", "") } } var sum = 0 for (d in directorySizes) { if(d.value <= 100000) { sum += d.value } } return sum } fun part2(input: List<String>): Int { val files = mutableListOf<File>() var workingDirectory = "" for (i in input) { val split = i.split(" ") if (split[0] == "$") { if (split[1] == "cd") { if (split[2] == "/") { workingDirectory = "/" } else if (split[2] == "..") { workingDirectory = workingDirectory.dropLast(1).replaceAfterLast("/", "") } else { workingDirectory += "${split[2]}/" } } } else { if (split[0] != "dir") { files.add(File(name = "$workingDirectory${split[1]}", size = split[0].toInt())) } } } val directorySizes = mutableMapOf<String, Int>() for (f in files) { var name = f.name.replaceAfterLast("/", "") while (name.isNotEmpty()) { var size = directorySizes.getOrDefault(name, 0) directorySizes[name] = size + f.size name = name.dropLast(1).replaceAfterLast("/", "") } } val requiredSpace = 30000000 - (70000000 - directorySizes["/"]!!) return directorySizes.map { it.value }.sorted().takeLastWhile { it > requiredSpace }.first() } val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) } class File( val name: String, val size: Int )
0
Kotlin
0
0
04437e66eef8cf9388fd1aaea3c442dcb02ddb9e
3,085
adventofcode2022
Apache License 2.0
src/main/kotlin/com/nibado/projects/advent/y2020/Day11.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2020 import com.nibado.projects.advent.* import com.nibado.projects.advent.collect.CharMap object Day11 : Day { private val map = resourceString(2020, 11) override fun part1(): Int = solve({ map, p -> map.count(p) == 0 }, { map, p -> map.count(p) >= 4 }) override fun part2(): Int = solve({ map, p -> map.countRays(p) == 0 }, { map, p -> map.countRays(p) >= 5 }) private fun solve(occRule: (CharMap, Point) -> Boolean, emptyRule: (CharMap, Point) -> Boolean): Int { var map = CharMap.from(map) var count: Int do { count = map.count('#') map = round(map, occRule, emptyRule) } while(count != map.count('#')) return count } private fun round(map: CharMap, occRule: (CharMap, Point) -> Boolean, emptyRule: (CharMap, Point) -> Boolean): CharMap { val newMap = CharMap(map.width, map.height, fill = '.') map.points { it != '.' }.forEach { newMap[it] = map[it] if (map[it] == 'L' && occRule(map, it)) { newMap[it] = '#' } if (map[it] == '#' && emptyRule(map, it)) { newMap[it] = 'L' } } return newMap } private fun CharMap.count(p: Point): Int = p.neighbors().filter { this.inBounds(it) }.count { this[it] == '#' } private fun CharMap.countRays(p: Point): Int = Point.NEIGHBORS .mapNotNull { n -> Point.ray(n) .map { it + p } .takeWhile { this.inBounds(it) } .firstOrNull { this[it] != '.' } } .count { this[it] == '#' } }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,777
adventofcode
MIT License
src/twentytwentytwo/day7/Day07.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentytwo.day7 import readInput class TreeNode(var value: Int, private var name: String) { var parent: TreeNode? = null var children: MutableMap<String, TreeNode> = mutableMapOf() fun addChild(node: TreeNode): TreeNode? { if (!children.containsKey(node.name)) { children[node.name] = node node.parent = this return null } return node } fun totalValue(): Int { return children.values.sumOf { it.totalValue() } + this.value } override fun toString(): String { var s = "$value" if (children.isNotEmpty()) { s += " {" + children.map { it.toString() } + " }" } return s } } fun main() { fun part1(input: List<String>): Int { val root = TreeNode(0, "/") var currNode = root for (i in input.indices) { val line = input[i] val parts = line.split(" ") if (parts[0] == "$") { if (parts[1] == "cd") { currNode = when (parts[2]) { ".." -> currNode.parent!! "/" -> root else -> if (currNode.children.containsKey(parts[2])) { currNode.children[parts[2]]!! } else { currNode.addChild(TreeNode(0, parts[2]))!! } } } } else { if (parts[0] == "dir") { currNode.addChild(TreeNode(0, parts[1])) } else { val size = parts[0].toInt() val fileName = parts[1] currNode.addChild(TreeNode(size, fileName)) } } } var sum = 0 val stack = ArrayDeque<TreeNode>() stack.addFirst(root) while (!stack.isEmpty()) { val curr = stack.removeFirst() curr.value = curr.totalValue() curr.children.values.forEach { stack.addFirst(it) } if (curr.value <= 100000 && curr.children.isNotEmpty()) { sum += curr.value } } return sum } fun part2(input: List<String>): Int { val root = TreeNode(0, "/") var currNode = root for (i in input.indices) { val line = input[i] val parts = line.split(" ") if (parts[0] == "$") { if (parts[1] == "cd") { currNode = when (parts[2]) { ".." -> currNode.parent!! "/" -> root else -> if (currNode.children.containsKey(parts[2])) { currNode.children[parts[2]]!! } else { currNode.addChild(TreeNode(0, parts[2]))!! } } } } else { if (parts[0] == "dir") { currNode.addChild(TreeNode(0, parts[1])) } else { val size = parts[0].toInt() val fileName = parts[1] currNode.addChild(TreeNode(size, fileName)) } } } val sizeNeeded = 30000000 - (70000000 - root.totalValue()) var min = Int.MAX_VALUE val stack = ArrayDeque<TreeNode>() stack.addFirst(root) while (!stack.isEmpty()) { val curr = stack.removeFirst() curr.value = curr.totalValue() curr.children.values.forEach { stack.addFirst(it) } if (curr.value in (sizeNeeded + 1)..min && curr.children.isNotEmpty()) { min = curr.value } } return min } val input = readInput("day7", "Day07_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
4,025
advent-of-code
Apache License 2.0
src/DayFive.kt
P-ter
572,781,029
false
{"Kotlin": 18422}
import java.util.* fun main() { fun partOne(input: List<String>): Int { var total = 0 val stacks = (0 .. 9).map { Stack<String>() } input.take(8).forEach { line -> line.windowed(3, 4).forEachIndexed { index, crate -> if(crate.isNotBlank()) { stacks[index].push(crate) } } } stacks.forEach { it.reverse() } val instructions = input.subList(10, input.size).forEach {line -> val (numberOfBlock, fromIndex, toIndex) = line.split(" ").filter { it.isNotBlank() && it.toIntOrNull() != null }.map { it.toInt() } for(i in 1 .. numberOfBlock) { stacks[toIndex-1].push(stacks[fromIndex-1].pop()) } } stacks.forEach { if(it.isNotEmpty()) { println(it.peek()) } } return total } fun partTwo(input: List<String>): Int { var total = 0 val stacks = (0 .. 9).map { mutableListOf<String>() }.toMutableList() input.take(8).forEach { line -> line.windowed(3, 4).forEachIndexed { index, crate -> if(crate.isNotBlank()) { stacks[index].add(crate) } } } stacks.forEach { it.reverse() } val instructions = input.subList(10, input.size).forEach {line -> val (numberOfBlock, fromIndex, toIndex) = line.split(" ").filter { it.isNotBlank() && it.toIntOrNull() != null }.map { it.toInt() } stacks[toIndex-1].addAll(stacks[fromIndex-1].takeLast(numberOfBlock)) stacks[fromIndex-1] = stacks[fromIndex-1].dropLast(numberOfBlock).toMutableList() } stacks.forEach { println(it.lastOrNull()) } return total } val input = readInput("dayfive") println(partOne(input)) println(partTwo(input)) }
0
Kotlin
0
1
e28851ee38d6de5600b54fb884ad7199b44e8373
1,945
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/ca/kiaira/advent2023/day3/Day3.kt
kiairatech
728,913,965
false
{"Kotlin": 78110}
package ca.kiaira.advent2023.day3 import ca.kiaira.advent2023.Puzzle /** * Day3 is an implementation of the Puzzle class for Advent of Code 2023, Day 3. * It solves two parts of the puzzle: * - Part 1: Calculate the sum of all part numbers adjacent to certain symbols in an engine schematic. * - Part 2: Calculate the sum of gear ratios, where a gear is represented by a '*' symbol adjacent to two part numbers. * * @constructor Initializes the Day3 puzzle with the corresponding day number. * * @author <NAME> <<EMAIL>> * @since December 8th, 2023 */ object Day3 : Puzzle<List<String>>(3) { /** * Parses the input data into a list of strings. * * @param input Input data as a sequence of strings. * @return A list of strings representing the engine schematic. */ override fun parse(input: Sequence<String>): List<String> { return input.toList() } /** * Calculates the sum of part numbers adjacent to certain symbols in the engine schematic. * * @param input The engine schematic represented as a list of strings. * @return The sum of part numbers. */ override fun solvePart1(input: List<String>): Long { // Implementation of part 1 logic val numbers = input.flatMapIndexed { i, s -> Regex("\\d+").findAll(s).map { i to it.range } } return numbers.sumOf { (i, range) -> if (getAdjacentSymbol(input, i, range) != null) input[i].substring(range).toLong() else 0 } } /** * Calculates the sum of gear ratios in the engine schematic. * * @param input The engine schematic represented as a list of strings. * @return The sum of gear ratios. */ override fun solvePart2(input: List<String>): Long { // Implementation of part 2 logic val numbers = input.flatMapIndexed { i, s -> Regex("\\d+").findAll(s).map { i to it.range } } var sum = 0L for ((i, r1) in numbers) { for ((j, r2) in numbers) { val (x1, y1) = getAdjacentSymbol(input, i, r1) ?: continue val (x2, y2) = getAdjacentSymbol(input, j, r2) ?: continue if ((i != j || r1 != r2) && x1 == x2 && y1 == y2 && input[x1][y1] == '*') sum += input[i].substring(r1).toLong() * input[j].substring(r2).toLong() } } return sum / 2 } /** * Helper function to find an adjacent symbol in the engine schematic. * * @param input The engine schematic represented as a list of strings. * @param i The current row index. * @param range The range of characters to search for adjacent symbols. * @return The coordinates (row, column) of the adjacent symbol, or null if not found. */ private fun getAdjacentSymbol(input: List<String>, i: Int, range: IntRange): Pair<Int, Int>? { listOf(i - 1, i + 1).forEach { r -> for (j in maxOf(range.first - 1, 0)..minOf(range.last + 1, input[i].lastIndex)) if (r in input.indices && input[r][j] in "@#$%&*/=+-") return r to j } listOf(range.first - 1, range.last + 1).forEach { c -> if (c in input[i].indices && input[i][c] in "@#$%&*/=+-") return i to c } return null } }
0
Kotlin
0
1
27ec8fe5ddef65934ae5577bbc86353d3a52bf89
3,009
kAdvent-2023
Apache License 2.0
src/main/kotlin/day05.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
class Day05 : Solvable("05") { override fun solveA(input: List<String>): String { val lineCount = HashMap<Pair<Int, Int>, Int>() getLines(input).forEach { it.getVertHorPoints().forEach { lineCount[it] = 1 + (lineCount[it] ?: 0) } } return lineCount.filterValues { it >= 2 }.size.toString() } override fun solveB(input: List<String>): String { val lineCount = HashMap<Pair<Int, Int>, Int>() getLines(input).forEach { it.getAllPoints().forEach { lineCount[it] = (lineCount[it] ?: 0) + 1 } } return lineCount.filterValues { it >= 2 }.size.toString() } private fun getLines(input: List<String>): List<Line> { return input.map { Line(it.split(" -> ")) } } } class Line { val x1: Int val x2: Int val y1: Int val y2: Int constructor(input: List<String>) { val (x1, x2) = input.first().split(",").map(String::toInt) val (y1, y2) = input.last().split(",").map(String::toInt) this.x1 = x1 this.x2 = x2 this.y1 = y1 this.y2 = y2 } fun getVerticalPoints(): List<Pair<Int, Int>> { if (x1 == y1) { return (if (y2 > x2) (x2..y2) else (y2..x2)).map { Pair(x1, it) } } return listOf() } fun getHorizontalPoints(): List<Pair<Int, Int>> { if (x2 == y2) { return (if (y1 > x1) (x1..y1) else (y1..x1)).map { Pair(it, x2) } } return listOf() } fun getDiagonalPoints(): List<Pair<Int, Int>> { if ((x1 != y1) and (x2 != y2)) { val xrange = if (y1 > x1) x1..y1 else x1 downTo y1 val yrange = if (y2 > x2) x2..y2 else x2 downTo y2 return xrange.zip(yrange) } return listOf() } fun getVertHorPoints(): List<Pair<Int, Int>> { return getVerticalPoints() + getHorizontalPoints() } fun getAllPoints(): List<Pair<Int, Int>> { return getVerticalPoints() + getHorizontalPoints() + getDiagonalPoints() } }
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
2,065
AdventOfCode
Creative Commons Zero v1.0 Universal
src/leetcodeProblem/leetcode/editor/en/LargestDivisibleSubset.kt
faniabdullah
382,893,751
false
null
//Given a set of distinct positive integers nums, return the largest subset //answer such that every pair (answer[i], answer[j]) of elements in this subset //satisfies: // // // answer[i] % answer[j] == 0, or // answer[j] % answer[i] == 0 // // // If there are multiple solutions, return any of them. // // // Example 1: // // //Input: nums = [1,2,3] //Output: [1,2] //Explanation: [1,3] is also accepted. // // // Example 2: // // //Input: nums = [1,2,4,8] //Output: [1,2,4,8] // // // // Constraints: // // // 1 <= nums.length <= 1000 // 1 <= nums[i] <= 2 * 10⁹ // All the integers in nums are unique. // // Related Topics Array Math Dynamic Programming Sorting 👍 2270 👎 105 package leetcodeProblem.leetcode.editor.en import java.util.* class LargestDivisibleSubset { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun largestDivisibleSubset(nums: IntArray): List<Int> { val n = nums.size val count = IntArray(n) val pre = IntArray(n) Arrays.sort(nums) var max = 0 var index = -1 for (i in 0 until n) { count[i] = 1 pre[i] = -1 for (j in i - 1 downTo 0) { if (nums[i] % nums[j] == 0) { if (1 + count[j] > count[i]) { count[i] = count[j] + 1 pre[i] = j } } } if (count[i] > max) { max = count[i] index = i } } val res: MutableList<Int> = ArrayList() while (index != -1) { res.add(nums[index]) index = pre[index] } return res } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { println( LargestDivisibleSubset.Solution().largestDivisibleSubset(intArrayOf(4, 8, 10, 240)) ) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,194
dsa-kotlin
MIT License
codeforces/round621/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round621 fun main() { val (n, m, _) = readInts() val special = readInts().map { it - 1 } val nei = List(n) { mutableListOf<Int>() } repeat(m) { val (u, v) = readInts().map { it - 1 } nei[u].add(v); nei[v].add(u) } val (s, t) = listOf(0, n - 1).map { bfs(nei, it) } val best = special.sortedBy { s[it] - t[it] }.fold(0 to -n) { (ans, maxPrev), i -> maxOf(ans, maxPrev + t[i]) to maxOf(maxPrev, s[i]) }.first println(minOf(t[0], best + 1)) } private fun bfs(nei: List<MutableList<Int>>, s: Int): List<Int> { val n = nei.size val queue = mutableListOf(s) val dist = MutableList(nei.size) { n }; dist[s] = 0 var low = 0 while (low < queue.size) { val v = queue[low++] for (u in nei[v]) { if (dist[u] == n) { dist[u] = dist[v] + 1 queue.add(u) } } } return dist } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
965
competitions
The Unlicense
src/Day02/Day02.kt
thmsbdr
574,632,643
false
{"Kotlin": 6603}
package Day02 import readInput fun main() { fun part1(input: List<String>): Int { var total = 0 val valueOfMove = mapOf('X' to 1, 'Y' to 2, 'Z' to 3) val whoDoIBeat = mapOf('X' to 'C', 'Y' to 'A', 'Z' to 'B') input.forEach { if (it[0] == it[2] -23) { total += 3 } else if (whoDoIBeat.getValue(it[2]) == it[0]) { total += 6 } total += valueOfMove.getValue(it[2]) } return total } fun part2(input: List<String>): Int { var total = 0 val valueOfMove = mapOf('A' to 1, 'B' to 2, 'C' to 3) val whoDoIBeat = mapOf('A' to 'C', 'B' to 'A', 'C' to 'B') input.forEach { s -> if (s[2] == 'X') { total += valueOfMove.getValue(whoDoIBeat.getValue(s[0])) } else if (s[2] == 'Y') { total += valueOfMove.getValue(s[0]) total += 3 } else { whoDoIBeat.keys.forEach { if (whoDoIBeat.getValue(it) == s[0]) total += valueOfMove.getValue(it) } total += 6 } } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b9ac3ed8b52a95dcc542f4de79fb24163f3929a4
1,528
AoC-2022
Apache License 2.0
src/day07/Day07.kt
ivanovmeya
573,150,306
false
{"Kotlin": 43768}
package day07 import readInput fun main() { data class File(val name: String, val ext: String?, val size: Long) data class Dir( val name: String, val files: MutableList<File>, val dirs: MutableList<Dir>, val parentDir: Dir?, var calculatedSize: Long = -1 ) fun String.toDir(parent: Dir?) = Dir( name = this.split(' ').last(), files = mutableListOf(), dirs = mutableListOf(), parentDir = parent ) fun String.toFile(): File { val (size, fileName) = this.split(' ') val (name, ext) = if (fileName.contains('.')) { val splits = fileName.split('.') splits.first() to splits.last() } else { fileName to null } return File( name = name, ext = ext, size = size.toLong() ) } fun parseDirectories(input: List<String>): Dir { val root = Dir( name = "/", files = mutableListOf(), dirs = mutableListOf(), parentDir = null ) var currentDir = root input.drop(1).forEach { line -> if (line.startsWith('$')) { //parse commands when { line.contains("cd") -> { currentDir = when { line.contains("..") -> { currentDir.parentDir ?: throw IllegalArgumentException("You are in the root dir = ${currentDir.name}, can't go up ") } else -> { val dirName = line.split(' ').last() currentDir.dirs.first { it.name == dirName } } } } line.contains("ls") -> { /*just skip*/ } } } else { //parse directory content when { line.startsWith("dir") -> { val dir = line.toDir(currentDir) currentDir.dirs.add(dir) } else -> { currentDir.files.add(line.toFile()) } } } } return root } fun spacePrefixByLevel(level: Int): String { val spaceBuilder = StringBuilder() repeat((level * 1.5).toInt()) { spaceBuilder.append(' ') } return spaceBuilder.toString() } fun printDir(dir: Dir, level: Int) { println("${spacePrefixByLevel(level)}- ${dir.name} (dir), calcSize = ${dir.calculatedSize}") dir.files.forEach { file -> println("${spacePrefixByLevel(level)} - ${file.name}${file.ext?.let { ".$it" } ?: ""} (file, size = ${file.size})") } dir.dirs.forEach { printDir(it, level + 1) } } fun calcDirSizes(dir: Dir, candidatesToDeletion: MutableList<Dir>, predicate: (Dir) -> Boolean = { false }): Long { val filesSize = dir.files.sumOf { it.size } dir.calculatedSize = if (dir.dirs.isEmpty()) { filesSize } else { filesSize + dir.dirs.sumOf { calcDirSizes(it, candidatesToDeletion, predicate) } } if (predicate(dir)) { candidatesToDeletion.add(dir) } return dir.calculatedSize } fun part1(input: List<String>): Long { val root = parseDirectories(input) val candidatesToDeletion = mutableListOf<Dir>() val totalSize = calcDirSizes(root, candidatesToDeletion) { it.calculatedSize <= 100000L } println("Total dir size = $totalSize") return candidatesToDeletion.sumOf { it.calculatedSize } } fun findCandidatesToDeletion(spaceToDelete: Long, root: Dir, candidatesToDeletion: MutableList<Long>) { if (root.calculatedSize >= spaceToDelete) { candidatesToDeletion.add(root.calculatedSize) } root.dirs.forEach { findCandidatesToDeletion(spaceToDelete, it, candidatesToDeletion) } } fun part2(input: List<String>): Long { val totalDiskSpace = 70000000L val spaceRequiredByUpdate = 30000000L val root = parseDirectories(input) val totalSize = calcDirSizes(root, mutableListOf()) val unusedSpace = totalDiskSpace - totalSize val spaceToDelete = spaceRequiredByUpdate - unusedSpace val candidatesSizesToDelete = mutableListOf<Long>() findCandidatesToDeletion(spaceToDelete, root, candidatesSizesToDelete) return candidatesSizesToDelete.minOf { it } } val testInput = readInput("day07/input_test") val test1Result = part1(testInput) val test2Result = part2(testInput) println(test1Result) println(test2Result) check(test1Result == 95437L) check(test2Result == 24933642L) val input = readInput("day07/input") val part1 = part1(input) val part2 = part2(input) check(part1 == 1886043L) println(part1) println(part2) }
0
Kotlin
0
0
7530367fb453f012249f1dc37869f950bda018e0
5,257
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfCombinations.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD import java.util.PriorityQueue /** * 1977. Number of Ways to Separate Numbers * @see <a href="https://leetcode.com/problems/number-of-ways-to-separate-numbers/">Source</a> */ fun interface NumberOfCombinations { operator fun invoke(num: String): Int } class NumberOfCombinationsBottomUp : NumberOfCombinations { override operator fun invoke(num: String): Int { val cs = num.toCharArray() val n = cs.size val rank = Array(n) { IntArray(n + 1) } val pq: PriorityQueue<IntArray> = PriorityQueue<IntArray>(1) { a, b -> a[1] - b[1] } for (i in 1..n) { var c = 0 var prev = 0 var j = 0 while (j + i <= n) { pq.add(intArrayOf(j, rank[j][i - 1] * 10 + cs[i + j - 1].code - '0'.code)) ++j } while (pq.isNotEmpty()) { val cur: IntArray = pq.poll() if (cur[1] != prev) c++ rank[cur[0]][i] = c prev = cur[1] } } val dp = Array(n) { IntArray(n + 1) } var j = n - 1 while (0 <= j) { if ('0' == cs[j]) { --j continue } val len = n - j dp[j][len] = 1 var i = len - 1 while (1 <= i) { // dp[j][i] means the valid number that can start from j and the length of the first number // is at least i thus here I aggregate dp[j][i + 1] into dp[j][i] dp[j][i] = dp[j][i + 1] val next = i + j if (next >= n || next + i > n) { --i continue } // if the rank of the next part is greater than the current one if (rank[j][i] <= rank[next][i]) { dp[j][i] = (dp[j][i] + dp[next][i]) % MOD } else if (next + i < n) { dp[j][i] = (dp[j][i] + dp[next][i + 1]) % MOD } --i } dp[j][0] = dp[j][1] --j } return dp[0][0] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,840
kotlab
Apache License 2.0