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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gcj/y2020/round2/b.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2020.round2
private fun solve(): String {
val (n, m) = readInts()
val data = (listOf(0) + readInts()).toIntArray()
val edges = List(m) { readInts().map { it - 1 } }
val added = IntArray(n)
data.withIndex().filter { it.value < 0 }.forEach { entry ->
added[(-entry.value until n).first { added[it] == 0 }] = entry.index
}
val byTime = data.indices.minus(added.toSet()).sortedBy { data[it] }.toMutableList()
for (i in 1 until n) if (added[i] == 0) added[i] = byTime.removeAt(0)
var x = 1
while (x < n) {
if (data[added[x]] > 0) { x++; continue }
val y = (x + 1 until n).firstOrNull { data[added[it]] != data[added[x]] } ?: n
for (i in x until y) data[added[i]] = data[added[x - 1]] + 1
x = y
}
return edges.joinToString(" ") { (u, v) -> (data[u] - data[v]).abs().coerceAtLeast(1).toString() }
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun Int.abs() = kotlin.math.abs(this)
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,133 | competitions | The Unlicense |
src/Day13.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | import java.lang.Integer.min
sealed interface PacketData : Comparable<PacketData> {
data class Single(val value: Int) : PacketData {
override fun compareTo(other: PacketData): Int =
when (other) {
is Single -> this.value - other.value
is Multiple -> Multiple(listOf(this)).compareTo(other)
}
}
data class Multiple(val values: List<PacketData>) : PacketData {
override fun compareTo(other: PacketData): Int {
when (other) {
is Multiple -> {
for (i in 0..min(values.lastIndex, other.values.lastIndex)) {
val result = values[i].compareTo(other.values[i])
if (result != 0) return result
}
return values.lastIndex - other.values.lastIndex
}
is Single -> return compareTo(Multiple(listOf(other)))
}
}
}
}
fun main() {
fun String.extract(): List<String> {
val extraction = mutableListOf<String>()
var depth = 0
var currentExtraction = ""
forEach { char ->
when (char) {
'[' -> {
depth++
currentExtraction += char
}
']' -> {
depth--
currentExtraction += char
}
',' -> when (depth) {
0 -> {
extraction += currentExtraction
currentExtraction = ""
}
else -> currentExtraction += char
}
else -> currentExtraction += char
}
}
extraction += currentExtraction
return extraction
}
fun String.parse(): PacketData {
val packet = removeSurrounding("[", "]")
return when {
packet.isEmpty() -> PacketData.Multiple(emptyList())
packet.all { it.isDigit() } -> PacketData.Single(packet.toInt())
else -> PacketData.Multiple(packet.extract().map { it.parse() })
}
}
fun part1(input: List<String>): Int =
input
.filter { it.isNotBlank() }
.chunked(2)
.mapIndexed { index, line ->
val left = line.first().parse()
val right = line.last().parse()
if (left < right) index + 1 else 0
}
.sum()
fun part2(input: List<String>): Int {
val packets = (input + listOf("[[2]]", "[[6]]"))
.filter { it.isNotBlank() }
.map { it.parse() }
.sorted()
val firstDividerPacket = packets.indexOf(PacketData.Multiple(listOf(PacketData.Single(2)))) + 1
val secondDividerPacket = packets.indexOf(PacketData.Multiple(listOf(PacketData.Single(6)))) + 1
return firstDividerPacket * secondDividerPacket
}
check(part1(readInput("Day13_test")) == 13)
check(part2(readInput("Day13_test")) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 3,181 | AdventOfCode2022 | Apache License 2.0 |
advent-of-code-2023/src/Day17.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | import lib.matrix.*
import lib.matrix.Direction.Companion.nextInDirection
import lib.matrix.Direction.DOWN
import lib.matrix.Direction.RIGHT
import kotlin.math.min
private const val DAY = "Day17"
fun main() {
fun testInput(id: Int) = readInput("${DAY}_test$id")
fun input() = readInput(DAY)
"Part 1" {
part1(testInput(1)) shouldBe 102
measureAnswer { part1(input()) }
}
"Part 2" {
part2(testInput(1)) shouldBe 94
part2(testInput(2)) shouldBe 71
measureAnswer { part2(input()) }
}
}
private fun part1(input: Matrix<Int>): Int = solve(input, steps = 1..3)
private fun part2(input: Matrix<Int>): Int = solve(input, steps = 4..10)
private fun solve(map: Matrix<Int>, steps: IntRange): Int {
val states = ArrayDeque<State>()
val bestSeenLoss = mutableMapOf<State.Key, Int>()
fun addState(state: State) {
val key = state.key()
if (key !in bestSeenLoss || bestSeenLoss.getValue(key) > state.loss) {
bestSeenLoss[key] = state.loss
states.addLast(state)
}
}
tailrec fun State.goInDirection(newDirection: Direction = lastDirection, steps: IntRange) {
val newPosition = position.nextInDirection(newDirection)
if (newPosition !in map) return
val newState = copy(
position = newPosition,
loss = loss + map[newPosition],
lastDirection = newDirection,
)
if (steps.first == 1) addState(newState)
val nextSteps = (steps.first - 1).coerceAtLeast(1)..<steps.last
if (!nextSteps.isEmpty()) newState.goInDirection(steps = nextSteps)
}
// Prefill queue with initial moves
val initialState = State(position = map.topLeftPosition, loss = 0, lastDirection = RIGHT)
initialState.goInDirection(RIGHT, steps)
initialState.goInDirection(DOWN, steps)
while (states.isNotEmpty()) {
val state = states.removeFirst()
if (bestSeenLoss.getValue(state.key()) < state.loss) continue
state.goInDirection(state.lastDirection.turn(clockwise = true), steps)
state.goInDirection(state.lastDirection.turn(clockwise = false), steps)
}
fun finalValue(horizontalDirection: Boolean): Int {
val key = State.Key(map.bottomRightPosition, horizontalDirection)
return bestSeenLoss[key] ?: Int.MAX_VALUE
}
return min(finalValue(horizontalDirection = true), finalValue(horizontalDirection = false))
}
private data class State(
val position: Position,
val lastDirection: Direction,
val loss: Int,
) {
fun key() = Key(position, lastDirection.horizontal)
data class Key(val position: Position, val horizontalDirection: Boolean)
}
private fun readInput(name: String) = readMatrix(name) { line -> line.map(Char::digitToInt) }
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 2,818 | advent-of-code | Apache License 2.0 |
src/y2023/d05/Day05.kt | AndreaHu3299 | 725,905,780 | false | {"Kotlin": 31452} | package y2023.d05
import println
import readInput
class Seed(val min: Long, val max: Long)
class Range(
private val fromMin: Long,
private val fromMax: Long,
private val toMin: Long,
private val toMax: Long
) {
constructor(domainMin: Long, codomainMin: Long, length: Long) :
this(domainMin, domainMin + length - 1, codomainMin, codomainMin + length - 1)
override fun toString(): String {
return "[$fromMin, $fromMax] -> [$toMin, $toMax]"
}
fun contains(value: Long): Boolean {
return value in fromMin..fromMax
}
fun map(value: Long): Long {
return if (contains(value)) toMin + (value - fromMin) else value
}
fun map(seed: Seed): List<Pair<Boolean, Seed>> {
if (seed.min == fromMin) {
return if (seed.max <= fromMax) {
listOf(Pair(true, Seed(map(seed.min), map(seed.max))))
} else {
listOf(
Pair(true, Seed(map(seed.min), map(fromMax))),
Pair(false, Seed(map(fromMax + 1), map(seed.max))),
)
}
} else if (seed.min < fromMin) {
if (seed.max in fromMin..fromMax) {
return listOf(
Pair(false, Seed(seed.min, fromMin - 1)),
Pair(true, Seed(map(fromMin), map(seed.max))),
)
}
if (seed.max > fromMax) {
return listOf(
Pair(false, Seed(seed.min, fromMin - 1)),
Pair(true, Seed(map(fromMin), map(fromMax))),
Pair(false, Seed(fromMax + 1, seed.max)),
)
}
return listOf(Pair(false, seed))
} else /*if (seed.min > fromMin)*/ {
if (seed.min > fromMax) {
return listOf(Pair(false, seed))
}
// if(seed.min <= fromMax) {
if (seed.max <= fromMax) {
return listOf(Pair(true, Seed(map(seed.min), map(seed.max))))
}
// if (seed.max > fromMax) {
return listOf(
Pair(true, Seed(map(seed.min), map(fromMax))),
Pair(false, Seed(fromMax + 1, seed.max)),
)
}
}
}
class Mapper(private val ranges: List<Range>) {
fun map1(seeds: List<Long>): List<Long> {
return seeds.map { seed ->
ranges.firstOrNull { it.contains(seed) }?.map(seed) ?: seed
}
}
fun map2(seeds: List<Seed>): List<Seed> {
var result = mutableListOf<Seed>()
seeds.map { seed ->
var domain = mutableListOf(seed)
ranges.forEach { range ->
val newDomain = mutableListOf<Seed>()
domain.forEach { domainSeed ->
range.map(domainSeed).forEach { (isMapped, seed) ->
if (isMapped) {
result.add(seed)
} else {
newDomain.add(seed)
}
}
}
domain = newDomain
}
result = result.plus(domain).toMutableList()
}
return result
}
override fun toString(): String {
return ranges.toString() + "\n"
}
}
fun main() {
val classPath = "y2023/d05"
fun parseMaps(input: List<String>): List<Mapper> {
val mappers = mutableListOf<Mapper>()
var ranges = mutableListOf<Range>()
for (line in input) {
if (line.isEmpty()) {
val mapper = Mapper(ranges)
mappers.add(mapper)
ranges = mutableListOf()
continue
}
if (!line[0].isDigit()) {
continue
}
val (dest, source, range) = line.split(" ").map { it.toLong() }
ranges.add(Range(source, dest, range))
}
mappers.add(Mapper(ranges))
return mappers
}
fun part1(input: List<String>): Long {
val seeds = input[0].split(": ")[1].split(" ").map { it.toLong() }
val maps = parseMaps(input.subList(2, input.size))
return maps.fold(seeds) { it, mapper ->
mapper.map1(it)
}.min()
}
fun part2(input: List<String>): Long {
val seeds = input[0].split(": ")[1]
.split(" ")
.map { it.toLong() }
.chunked(2)
.map { (a, b) -> Seed(a, a + b - 1) }
val maps = parseMaps(input.subList(2, input.size))
return maps.fold(seeds) { it, mapper ->
mapper.map2(it)
}.minOf { it.min }
}
val testInput = readInput("${classPath}/test")
part1(testInput).println()
part2(testInput).println()
val input = readInput("${classPath}/input")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e | 4,909 | aoc | Apache License 2.0 |
app/src/main/kotlin/day02/Day02.kt | KingOfDog | 433,706,881 | false | {"Kotlin": 76907} | package day02
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 2
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay02Part1, ::solveDay02Part2)
}
fun solveDay02Part1(input: List<String>): Int {
return input
.map { Command.fromString(it) }
.map { command ->
when (command.direction) {
"forward" -> Position(x = command.amount)
"down" -> Position(depth = command.amount)
"up" -> Position(depth = -command.amount)
else -> Position()
}
}
.sum()
.product()
}
fun solveDay02Part2(input: List<String>): Int {
var aim = 0
return input
.map { Command.fromString(it) }
.mapNotNull { command ->
when (command.direction) {
"forward" -> Position(x = command.amount, depth = command.amount * aim)
"down" -> null.also { aim += command.amount }
"up" -> null.also { aim -= command.amount }
else -> null
}
}
.sum()
.product()
}
data class Command(val direction: String, val amount: Int) {
companion object {
fun fromString(input: String): Command {
val parts = input.split(" ")
val direction = parts[0]
val amount = parts[1].toInt()
return Command(direction, amount)
}
}
}
data class Position(val x: Int = 0, val depth: Int = 0) {
operator fun plus(pos: Position): Position {
return Position(x + pos.x, depth + pos.depth)
}
fun product(): Int = x * depth
}
private fun List<Position>.sum(): Position = reduce { acc, position -> acc + position }
| 0 | Kotlin | 0 | 0 | 576e5599ada224e5cf21ccf20757673ca6f8310a | 1,820 | advent-of-code-kt | Apache License 2.0 |
aoc2023/day15.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2023
import utils.InputRetrieval
fun main() {
Day15.execute()
}
private object Day15 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<Operation>): Long = input.sumOf { it.holidayASCIIStringHelper.toLong() }
private fun part2(input: List<Operation>): Long {
// Could I have used other data structure and it would be easier? Yes, but then the joke would be lost ;)
val holidayASCIIStringHelperManualArrangementProcedure = HashMap((0..255).associateWith { Box(it) })
input.forEach {
it.execute(holidayASCIIStringHelperManualArrangementProcedure)
}
return holidayASCIIStringHelperManualArrangementProcedure.values.sumOf { it.focalPower() }
}
private fun String.holidayASCIIStringHelper(): Int {
var hash = 0
this.forEach {
hash = ((hash + it.code) * 17) % 256
}
return hash
}
private fun readInput(): List<Operation> = InputRetrieval.getFile(2023, 15).readLines()
.first().split(',')
.map { Operation.parse(it) }
private enum class OperationCode { REMOVE, REPLACE_OR_ADD }
private data class Operation(val label: String, val operationCode: OperationCode, val focalLength: Int?, val holidayASCIIStringHelper: Int) {
fun execute(holidayASCIIStringHelperManualArrangementProcedure: HashMap<Int, Box>) {
val box = holidayASCIIStringHelperManualArrangementProcedure[label.holidayASCIIStringHelper()]!!
when (operationCode) {
OperationCode.REMOVE -> box.lenses.removeAll { it.label == this.label }
OperationCode.REPLACE_OR_ADD -> {
val lens = box.lenses.find { it.label == this.label }
if (lens == null) {
box.lenses.add(Lens(this.label, this.focalLength!!))
} else {
lens.focalLength = this.focalLength!!
}
}
}
}
companion object {
fun parse(input: String): Operation {
val operationCode = when {
input.contains('-') -> OperationCode.REMOVE
else -> OperationCode.REPLACE_OR_ADD
}
val label = input.substringBefore('=').substringBefore('-')
val focalLength = if (operationCode == OperationCode.REPLACE_OR_ADD) {
input.substringAfter('=').toInt()
} else null
return Operation(label, operationCode, focalLength, input.holidayASCIIStringHelper())
}
}
}
private data class Box(val id: Int, val lenses: MutableList<Lens> = mutableListOf()) {
fun focalPower(): Long = lenses.mapIndexed { index, lens -> (this.id + 1L) * (index + 1L) * lens.focalLength }.sum()
}
private data class Lens(val label: String, var focalLength: Int)
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 3,061 | Advent-Of-Code | MIT License |
src/year2023/day11/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2023.day11
import arrow.core.nonEmptyListOf
import io.kotest.matchers.shouldBe
import kotlin.math.max
import kotlin.math.min
import utils.Point
import utils.ProblemPart
import utils.combinations
import utils.manhattanDistanceTo
import utils.permutations
import utils.readInputs
import utils.runAlgorithm
fun main() {
val (realInput, testInputs) = readInputs(2023, 11, transform = ::parse)
computeDistances(testInputs.head, 10) shouldBe 1030
computeDistances(testInputs.head, 100) shouldBe 8410
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(374),
algorithm = ::part1,
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(82000210),
algorithm = ::part2,
),
)
}
private fun parse(input: List<String>): Universe {
val galaxies = input.asSequence()
.flatMapIndexed { y, line -> line.asSequence().mapIndexed { x, char -> char to Point(x, y) } }
.mapNotNull { (char, coordinates) -> if (char == '#') coordinates else null }
.toSet()
return Universe(
galaxies = galaxies,
emptyRows = input.indices.minus(galaxies.mapTo(mutableSetOf()) { it.y }).toSet(),
emptyColumns = input.indices.minus(galaxies.mapTo(mutableSetOf()) { it.x }).toSet(),
)
}
private data class Universe(
val galaxies: Set<Point>,
val emptyRows: Set<Int>,
val emptyColumns: Set<Int>,
)
private fun part1(input: Universe): Long = computeDistances(input, 2)
private fun computeDistances(input: Universe, expansionRatio: Long): Long {
return input.galaxies.combinations(2)
.map { it.iterator() }
.map(getDistanceMappingFunction(input.emptyRows, input.emptyColumns, expansionRatio))
.sum()
}
private fun getDistanceMappingFunction(
emptyRows: Set<Int>,
emptyColumns: Set<Int>,
expansionRatio: Long,
): (Iterator<Point>) -> Long = { iterator ->
val a = iterator.next()
val b = iterator.next()
val xRange = min(a.x, b.x)..max(a.x, b.x)
val yRange = min(a.y, b.y)..max(a.y, b.y)
(a manhattanDistanceTo b) +
(emptyColumns.count { it in xRange } + emptyRows.count { it in yRange }) * (expansionRatio - 1)
}
private fun part2(input: Universe): Long = computeDistances(input, 1_000_000)
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 2,405 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day08.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.Logger.logger
import tr.emreone.kotlin_utils.math.Coords
object Day08 {
private fun generateTreeMap(input: List<String>): Map<Coords, List<List<Int>>> {
val trees = mutableMapOf<Coords, List<List<Int>>>()
input.forEachIndexed { y, line ->
line.forEachIndexed { x, _ ->
if (y > 0 && y < input.lastIndex && x > 0 && x < line.lastIndex) {
val top = IntRange(0, y - 1).map { yy -> input[yy][x].digitToInt() }
val right = IntRange(x + 1, line.lastIndex).map { xx -> input[y][xx].digitToInt() }
val bottom = IntRange(y + 1, input.lastIndex).map { yy -> input[yy][x].digitToInt() }
val left = IntRange(0, x - 1).map { xx -> input[y][xx].digitToInt() }
trees[x to y] = listOf(top.reversed(), right, bottom, left.reversed())
} else {
// ignore trees on the edge
trees[x to y] = emptyList()
}
}
}
return trees
}
private fun isOnTheEdge(input: List<String>, coords: Coords): Boolean {
return coords.first == 0
|| coords.first == input.first().lastIndex
|| coords.second == 0
|| coords.second == input.lastIndex
}
fun part1(input: List<String>): Int {
val trees = generateTreeMap(input)
// trees on the edge
var visibleTrees = trees.count {(key, _) ->
isOnTheEdge(input, key)
}
visibleTrees += trees.filter { !isOnTheEdge(input, it.key) }
.count { (t, u) ->
val current = input[t.second][t.first].digitToInt()
u.count { it.all { n -> n < current } } > 0
}
return visibleTrees
}
fun part2(input: List<String>): Int {
val trees = generateTreeMap(input)
return trees.filter { !isOnTheEdge(input, it.key) }
.maxOf { (t, u) ->
val current = input[t.second][t.first].digitToInt()
var score = 1;
u.forEach {
var localStore = it.indexOfFirst { n -> n >= current }
score *= if (localStore == -1) it.size else localStore + 1
}
score
}
}
}
| 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 2,409 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code-2023/src/Day06.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | private const val DAY = "Day06"
fun main() {
fun testInput() = readInput("${DAY}_test")
fun testInput2() = readInput2("${DAY}_test")
fun input() = readInput(DAY)
fun input2() = readInput2(DAY)
"Part 1" {
part1(testInput()) shouldBe 288
measureAnswer { part1(input()) }
}
"Part 2" {
part2(testInput2()) shouldBe 71503
measureAnswer { part2(input2()) }
}
}
private fun part1(input: Pair<List<Int>, List<Int>>): Int {
val (times, distances) = input
return times.indices
.map { i ->
val time = times[i]
(1 until time).count { timeToCharge ->
timeToCharge * (time - timeToCharge) > distances[i]
}
}
.reduce(Int::times)
}
private fun part2(input: Pair<Long, Long>): Int {
val (time, distance) = input
return (1 until time).count { timeToCharge ->
timeToCharge * (time - timeToCharge) > distance
}
}
private val spacesRegex = Regex("\\s+")
private fun readInput(name: String): Pair<List<Int>, List<Int>> {
val (time, distance) = readLines(name).map { line ->
line.substringAfter(":").trim()
.split(spacesRegex)
.map(String::toInt)
}
return time to distance
}
private fun readInput2(name: String): Pair<Long, Long> {
val (time, distance) = readLines(name).map { line ->
line.substringAfter(":").trim()
.replace(" ", "")
.toLong()
}
return time to distance
}
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 1,516 | advent-of-code | Apache License 2.0 |
src/twentytwo/Day13.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentytwo
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("Day13_test")
val part1 = part1(testInput)
println(part1)
check(part1 == 13)
val part2 = part2(testInput)
println(part2)
check(part2 == 140)
println("---")
val input = readInputLines("Day13_input")
println(part1(input))
println(part2(input))
}
private sealed interface Packet {
data class IntPacket(val int: Int): Packet
data class ListPacket(val list: List<Packet>): Packet, Comparable<Packet> {
override fun compareTo(other: Packet): Int {
return this.comesBefore(other)
}
}
}
private fun Packet.ListPacket.comesBefore(other: Packet): Int {
val otherList = if (other is Packet.ListPacket) other else Packet.ListPacket(listOf(other))
if (this.list.isEmpty() && otherList.list.isEmpty()) return 0
val smallestList = minOf(this.list.lastIndex, otherList.list.lastIndex)
if (smallestList == -1) return this.list.size.compareTo(otherList.list.size)
for (i in 0 .. smallestList) {
val a = this.list[i]
val b = otherList.list[i]
val result = if (a is Packet.ListPacket) {
a.comesBefore(b)
} else if (b is Packet.ListPacket) {
-b.comesBefore(a)
} else {
(a as Packet.IntPacket).int.compareTo((b as Packet.IntPacket).int)
}
if (result != 0) return result
}
return this.list.size.compareTo(otherList.list.size)
}
private fun String.toListPacket(trim: Boolean = true): Packet.ListPacket {
val trimmed = if (trim) this.removeSurrounding("[", "]") else this
if (!trimmed.contains("[")) {
val items = trimmed.split(",").filter { it.isNotBlank() }.map { it.toIntPacket() }
return Packet.ListPacket(items)
}
val before = trimmed.substringBefore("[")
val firstIndex = trimmed.indexOf("[")
var index = firstIndex+1
var nestingCount = 1
while (nestingCount > 0) {
when (trimmed[index]) {
'[' -> nestingCount++
']' -> nestingCount--
}
index++
}
val beforeItems = before.split(",").filter { it.isNotBlank() }.map { it.toIntPacket() }
val list = trimmed.substring(firstIndex, index).toListPacket()
val afterItems = if (index < trimmed.lastIndex) {
trimmed
.substring(index+1)
.removeSurrounding(",")
.toListPacket(false)
.list
} else {
emptyList()
}
val items = mutableListOf<Packet>()
items.addAll(beforeItems)
items.add(list)
items.addAll(afterItems)
return Packet.ListPacket(items)
}
private fun String.toIntPacket(): Packet.IntPacket = Packet.IntPacket(this.toInt())
private fun part1(input: List<String>): Int {
val pairs: List<List<String>> = input.split("")
val packetPairs = pairs.map { (a, b) ->
Pair(a.toListPacket(), b.toListPacket())
}
val correctOrder = packetPairs.map { (a, b) ->
a.compareTo(b)
}
return correctOrder
.mapIndexed { index, i -> if (i == -1) index+1 else 0 }
.sum()
}
private fun part2(input: List<String>): Int {
val specialItem1 = Packet.ListPacket(listOf(Packet.ListPacket(listOf(Packet.IntPacket(2)))))
val specialItem2 = Packet.ListPacket(listOf(Packet.ListPacket(listOf(Packet.IntPacket(6)))))
val packets = input.filter { it != "" }.map { it.toListPacket() }.toMutableList()
packets.add(specialItem1)
packets.add(specialItem2)
packets.sort()
val spot1 = packets.indexOf(specialItem1)+1
val spot2 = packets.indexOf(specialItem2)+1
return spot1 * spot2
}
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 3,717 | advent-of-code-solutions | Apache License 2.0 |
src/Day08.kt | sebokopter | 570,715,585 | false | {"Kotlin": 38263} | fun main() {
fun forest(input: List<String>): List<List<Int>> =
input.map { row -> row.map { tree -> tree.digitToInt() } }
fun isVisible(view: List<Int>): Boolean {
val treeSize = view.last()
return view.dropLast(1).all { it < treeSize }
}
fun countVisible(view: List<Int>, currentTree: Int): Int {
var sum = 0
for (size in view) {
sum++
if (size >= currentTree) return sum
}
return sum
}
fun part1(input: List<String>): Int {
val forest = forest(input)
val visibleTrees = MutableList(forest.size) { MutableList(forest.first().size) { 0 to false } }
val lastRowIndex = forest.lastIndex
val lastColumnIndex = forest.first().lastIndex
for (rowIndex in 0..lastRowIndex) {
for (columnIndex in 0..lastColumnIndex) {
if (rowIndex == 0 || rowIndex == lastRowIndex || columnIndex == 0 || columnIndex == lastColumnIndex) {
visibleTrees[rowIndex][columnIndex] = forest[rowIndex][columnIndex] to true
} else {
if (visibleTrees[rowIndex][columnIndex].second) continue
val viewFromLeft = forest[rowIndex].subList(0, columnIndex + 1)
val viewFromRight = forest[rowIndex].reversed().subList(0, lastColumnIndex - columnIndex + 1)
val viewFromTop = forest.map { it[columnIndex] }.subList(0, rowIndex + 1)
val viewFromBottom =
forest.map { it[columnIndex] }.reversed().subList(0, lastRowIndex - rowIndex + 1)
val visible = isVisible(viewFromLeft) ||
isVisible(viewFromRight) ||
isVisible(viewFromTop) ||
isVisible(viewFromBottom)
if (visible) visibleTrees[rowIndex][columnIndex] = forest[rowIndex][columnIndex] to true
else visibleTrees[rowIndex][columnIndex] = forest[rowIndex][columnIndex] to false
}
}
}
return visibleTrees.sumOf { row -> row.count { it.second } }
}
fun part2(input: List<String>): Int {
val forest = forest(input)
val scenicScores = MutableList(forest.size) { MutableList(forest.first().size) { 0 to 0 } }
val lastRowIndex = forest.lastIndex
val lastColumnIndex = forest.first().lastIndex
for (rowIndex in 0..lastRowIndex) {
for (columnIndex in 0..lastColumnIndex) {
if (rowIndex == 0 || rowIndex == lastRowIndex || columnIndex == 0 || columnIndex == lastColumnIndex) {
scenicScores[rowIndex][columnIndex] = forest[rowIndex][columnIndex] to 0
} else {
val viewToLeft = forest[rowIndex].subList(0, columnIndex + 1).reversed()
val viewToRight = forest[rowIndex].subList(columnIndex, lastColumnIndex + 1)
val viewToTop = forest.map { it[columnIndex] }.subList(0, rowIndex + 1).reversed()
val viewToBottom = forest.map { it[columnIndex] }.subList(rowIndex, lastRowIndex + 1)
val scenicScore = countVisible(viewToLeft.drop(1), forest[rowIndex][columnIndex]) *
countVisible(viewToRight.drop(1), forest[rowIndex][columnIndex]) *
countVisible(viewToTop.drop(1), forest[rowIndex][columnIndex]) *
countVisible(viewToBottom.drop(1), forest[rowIndex][columnIndex])
scenicScores[rowIndex][columnIndex] = forest[rowIndex][columnIndex] to scenicScore
}
}
}
return scenicScores.maxOf { row ->
row.maxOf { it.second }
}
}
val testInput = readInput("Day08_test")
println("part1(testInput): " + part1(testInput))
println("part2(testInput): " + part2(testInput))
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println("part1(input): " + part1(input))
println("part2(input): " + part2(input))
}
| 0 | Kotlin | 0 | 0 | bb2b689f48063d7a1b6892fc1807587f7050b9db | 4,164 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | rifkinni | 573,123,064 | false | {"Kotlin": 33155, "Shell": 125} | abstract class CharacterPriority {
abstract fun intersection(): Char
fun calculate(): Int {
return getItemPriority(intersection())
}
private fun getItemPriority(c: Char): Int {
return priorityString.indexOf(c) + 1
}
companion object {
private const val priorityString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
}
}
class Rucksack(private val input: String): CharacterPriority() {
override fun intersection(): Char {
val split = (input.length / 2)
val first = input.slice(0 until split).asIterable()
val second = input.slice(split until input.length).asIterable()
return first.intersect(second).first()
}
}
class Badge(private val input: List<Set<Char>>): CharacterPriority() {
init {
assert(input.size == 3)
}
override fun intersection(): Char {
return input[0].intersect(input[1]).intersect(input[2]).first()
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { Rucksack(it).calculate() }
}
fun part2(input: List<String>): Int {
var sum = 0
for (i in input.indices step 3) {
val group = input.slice(i..i+2).map { it.toSet() }
sum += Badge(group).calculate()
}
return sum
}
// 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 | c2f8ca8447c9663c0ce3efbec8e57070d90a8996 | 1,602 | 2022-advent | Apache License 2.0 |
src/Day07.kt | RusticFlare | 574,508,778 | false | {"Kotlin": 78496} | import Filesystem.Directory
private sealed interface Filesystem {
val size: Int
data class Directory(
val name: String,
val parent: Directory?,
val files: MutableList<Filesystem> = mutableListOf(),
) : Filesystem {
override val size: Int
get() = files.sumOf { it.size }
}
data class File(
val name: String,
override val size: Int,
) : Filesystem
}
private fun Directory.deepFlatten(): List<Directory> = files
.filterIsInstance<Directory>()
.flatMap { it.deepFlatten() } + this
fun main() {
fun filesystem(input: List<String>): Directory {
val root = Directory(name = "/", parent = null)
var currentDirectory: Directory = root
input.forEach { line ->
if (line.startsWith("$ cd")) {
currentDirectory = when (val target = line.split(" ")[2]) {
".." -> currentDirectory.parent!!
"/" -> root
else -> currentDirectory.files.filterIsInstance<Directory>().singleOrNull { it.name == target }
?: error("$currentDirectory does not contain $target")
}
} else if (!line.startsWith("$ ls")) {
val (x, name) = line.split(" ")
if (x == "dir") {
currentDirectory.files.add(Directory(name, parent = currentDirectory))
} else {
currentDirectory.files.add(Filesystem.File(name, size = x.toInt()))
}
}
}
return root
}
fun part1(input: List<String>): Int {
return filesystem(input).deepFlatten()
.map { it.size }
.filter { it <= 100000 }
.sum()
}
fun part2(input: List<String>): Int {
val totalDiskSpace = 70000000
val requiredUnusedSpace = 30000000
val filesystem = filesystem(input)
val currentUnusedSpace = totalDiskSpace - filesystem.size
return filesystem.deepFlatten().map { it.size }
.filter { currentUnusedSpace + it >= requiredUnusedSpace }
.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readLines("Day07")
check(part1(input) == 1391690)
println(part1(input))
check(part2(input) == 5469168)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 10df3955c4008261737f02a041fdd357756aa37f | 2,524 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day19.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | import java.util.*
import kotlin.math.max
import kotlin.math.min
private data class Blueprint(val totalCosts: List<List<Int>>)
private data class State(val robotBuilt: List<Int>, var resources: List<Int>)
private const val SHIFT_1: Long = 25
private const val SHIFT_2: Long = 340
private const val BASE: Long = SHIFT_1 * SHIFT_1 * SHIFT_1 * SHIFT_1
private fun State.encode(): Long {
return 1L * robotBuilt[0] + robotBuilt[1] * SHIFT_1 + robotBuilt[2] * SHIFT_1 * SHIFT_1 + robotBuilt[3] * SHIFT_1 * SHIFT_1 * SHIFT_1 +
BASE * resources[0] + BASE * SHIFT_2 * resources[1] + BASE * SHIFT_2 * SHIFT_2 * resources[2]
}
fun main() {
fun parseBlueprint(line: String): Blueprint {
val rawValues =
line.split('.').map { it.split(' ').takeLast(5).mapNotNull { it2 -> it2.toIntOrNull() } }.dropLast(1)
return Blueprint(
listOf(
listOf(rawValues[0][0], 0, 0),
listOf(rawValues[1][0], 0, 0),
listOf(rawValues[2][0], rawValues[2][1], 0),
listOf(rawValues[3][0], 0, rawValues[3][1])
)
)
}
fun maximizeGeodes(
blueprint: Blueprint, time: Int
): Int {
val geodeMemory = mutableSetOf<Long>()
val q: Queue<Pair<State, Pair<Int, Int>>> = LinkedList()
q.add(State(listOf(1, 0, 0, 0), listOf(0, 0, 0)) to (0 to time))
var maxAnswer = 0
var state: State
var stepsLeft: Int
var realGeodes: Int
var newState: State
var failedOnce: Boolean
var bestResult = 0
var bestProductionResult = 0
while (q.isNotEmpty()) {
state = q.first().first
stepsLeft = q.first().second.second
realGeodes = q.remove().second.first + state.robotBuilt[3]
bestResult = max(bestResult, realGeodes)
if (realGeodes + min(2, stepsLeft) < bestResult) continue // zero proof
bestProductionResult = max(bestProductionResult, state.robotBuilt[3])
if (stepsLeft == 0) {
maxAnswer = max(realGeodes - state.robotBuilt[3], maxAnswer)
continue
}
failedOnce = false
for (whichBuild in 0..4) {
newState = if (whichBuild == 4) {
if (!failedOnce) continue
State(
state.robotBuilt,
state.resources.withIndex().map { it.value + state.robotBuilt[it.index] }
)
} else {
if (state.resources.withIndex().any { it.value < blueprint.totalCosts[whichBuild][it.index] }) {
failedOnce = true; continue
}
State(
state.robotBuilt.withIndex().map { it.value + if (it.index == whichBuild) 1 else 0 },
state.resources.withIndex()
.map { it.value + state.robotBuilt[it.index] - blueprint.totalCosts[whichBuild][it.index] }
)
}
if (newState.encode() !in geodeMemory) {
geodeMemory.add(newState.encode())
q.add(newState to (realGeodes to stepsLeft - 1))
}
}
}
return maxAnswer
}
fun part1(input: List<String>): Int {
val blueprints = input.map(::parseBlueprint)
return blueprints.withIndex()
.sumOf { (it.index + 1) * maximizeGeodes(it.value, 24)}
}
fun part2(input: List<String>): Int {
val blueprints = input.map(::parseBlueprint)
return blueprints.take(3).fold(1) { acc, value -> acc * maximizeGeodes(value, 32) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
check(part1(testInput) == 33)
check(part2(testInput) == 62 * 56)
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 4,036 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day13.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | import kotlin.math.min
interface PacketEntry : Comparable<PacketEntry> {
companion object
}
fun PacketEntry.Companion.from(content: String): PacketEntry {
return when {
content.isEmpty() -> PacketList(emptyList())
content.startsWith("[") -> PacketList.from(content)
else -> PacketNumber(content.toInt())
}
}
@JvmInline
value class PacketNumber(val value: Int) : PacketEntry {
override fun compareTo(other: PacketEntry): Int {
return this.compare(other)
}
}
@JvmInline
value class PacketList(val value: List<PacketEntry>) : PacketEntry {
override fun compareTo(other: PacketEntry): Int {
return this.compare(other)
}
companion object
}
fun PacketList.Companion.from(content: String): PacketList {
val elements = mutableListOf<PacketEntry>()
val stripped = content.substring(1 until content.length - 1)
var index = 0
val readSubContent = {
var c = ""
var openCount = 0
do {
when (stripped[index]) {
'[' -> openCount++
']' -> openCount--
}
c += stripped[index++]
} while (index < stripped.length && stripped[index] != ',' || openCount > 0)
index++
c
}
while (index < stripped.length) {
elements.add(PacketEntry.from(readSubContent()))
}
return PacketList(elements)
}
fun PacketEntry.compare(other: PacketEntry): Int {
return when {
this is PacketNumber && other is PacketNumber -> {
value.compareTo(other.value)
}
this is PacketList && other is PacketList -> {
(0 until min(value.size, other.value.size)).firstOrNull {
value[it].compare(other.value[it]) != 0
}.let { index ->
when {
index != null -> value[index].compare(other.value[index])
value.size == other.value.size -> 0
else -> value.size.compareTo(other.value.size)
}
}
}
this is PacketNumber && other is PacketList -> {
PacketList(listOf(this)).compare(other)
}
this is PacketList && other is PacketNumber -> {
this.compare(PacketList(listOf(other)))
}
else -> throw RuntimeException()
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.windowed(2, 3, true) {
val p1 = PacketEntry.from(it[0])
val p2 = PacketEntry.from(it[1])
p1.compare(p2) < 0
}.withIndex().sumOf {
if (it.value) it.index + 1 else 0
}
}
fun part2(input: List<String>): Int {
val divider1 = PacketEntry.from("[[2]]")
val divider2 = PacketEntry.from("[[6]]")
val sorted = (input.filter { it.isNotEmpty() }.map { PacketEntry.from(it) } + listOf(divider1, divider2)).sorted()
val first = sorted.indexOfFirst { it == divider1 }
val second = sorted.indexOfFirst { it == divider2 }
return (first + 1) * (second + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13) { "part1 check failed" }
check(part2(testInput) == 140) { "part2 check failed" }
val input = readInput("Day13")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 3,413 | aoc2022 | Apache License 2.0 |
src/Day03.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | import kotlin.math.max
import kotlin.math.min
private const val EXPECTED_1 = 4361
private const val EXPECTED_2 = 467835
private class Day03(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
val field = readAsLines()
var sum = 0
for (y in field.indices) {
var x = 0
while (x < field[y].length) {
if (field[y][x].isDigit()) {
val startX = x
while (x < field[y].length && field[y][x].isDigit()) {
x++
}
var nextToSymbol = false
for (checkx in max(0, startX-1)..min(field[y].length-1,x)) {
if (y < field.size - 2 && !".0123456789".contains(field[y+1][checkx]))
nextToSymbol = true
if (y > 0 && !".0123456789".contains(field[y-1][checkx]))
nextToSymbol = true
}
if (startX > 0 && !".0123456789".contains(field[y][startX-1]))
nextToSymbol = true
if (x < field[y].length - 1 && !".0123456789".contains(field[y][x]))
nextToSymbol = true
if (nextToSymbol) {
sum += field[y].substring(startX, x).toInt()
}
} else {
x++
}
}
}
return sum
}
fun part2(): Any {
val field = readAsLines()
val gears = mutableMapOf<Pair<Int, Int>, MutableList<Int>>()
for (y in field.indices) {
var x = 0
while (x < field[y].length) {
if (field[y][x].isDigit()) {
val startX = x
while (x < field[y].length && field[y][x].isDigit()) {
x++
}
fun addGear(ax: Int, ay: Int) {
val key = Pair(ax, ay)
val gearList = gears[key] ?: mutableListOf<Int>().also { gears[key] = it }
gearList.add(field[y].substring(startX, x).toInt())
}
for (checkx in max(0, startX-1)..min(field[y].length-1,x)) {
if (y < field.size - 2 && field[y+1][checkx] == '*')
addGear(checkx, y+1)
if (y > 0 && '*' == field[y-1][checkx])
addGear(checkx, y-1)
}
if (startX > 0 && '*' == field[y][startX-1])
addGear(startX-1, y)
if (x < field[y].length - 1 && '*' == field[y][x])
addGear(x, y)
} else {
x++
}
}
}
return gears.filter { it.value.size == 2 }.map {it.value[0] * it.value[1] }.sum()
}
}
fun main() {
val testInstance = Day03(true)
val instance = Day03(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 3,364 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | anoniim | 572,264,555 | false | {"Kotlin": 8381} | fun main() {
Day3().run(
157,
70
)
}
private class Day3 : Day(3) {
override fun part1(input: List<String>): Int {
// What is the sum of the priorities of those item types?
val sharedItemTypes = mutableListOf<ItemType>()
input.forEach { rucksack ->
val compartments = getCompartments(rucksack)
sharedItemTypes.addAll(getSharedItemTypes(compartments))
}
return sharedItemTypes.sumOf { getPriority(it) }
}
private fun getPriority(itemType: ItemType): Int {
return if (itemType.isLowerCase()) {
itemType.code - 96
} else {
itemType.code - 38
}
}
private fun getCompartments(rucksack: String): Compartments {
val middleIndex = rucksack.length / 2
val firstCompartment = rucksack.substring(0, middleIndex)
val secondCompartment = rucksack.substring(middleIndex, rucksack.length)
return Compartments(firstCompartment, secondCompartment)
}
private fun getSharedItemTypes(compartments: Compartments): Set<ItemType> {
return compartments.first.toSet() intersect compartments.second.toSet()
}
override fun part2(input: List<String>): Int {
// Find the item type that corresponds to the badges of each three-Elf group.
// What is the sum of the priorities of those item types?
return input.chunked(3) { rucksackGroup -> getCommonItemTypes(rucksackGroup) }
.map { it.first() }
.sumOf { getPriority(it) }
}
private fun getCommonItemTypes(rucksackGroup: List<String>) =
rucksackGroup[0].toSet() intersect rucksackGroup[1].toSet() intersect rucksackGroup[2].toSet()
}
private typealias Compartments = Pair<String, String>
private typealias ItemType = Char
| 0 | Kotlin | 0 | 0 | 15284441cf14948a5ebdf98179481b34b33e5817 | 1,825 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day11.kt | D000L | 575,350,411 | false | {"Kotlin": 23716} | data class Monkey(
val number: Int,
var items: MutableList<Long> = mutableListOf(),
var operation: String = "",
var divisible: Int = 0,
var trueTarget: Int = 0,
var falseTarget: Int = 0
) {
var inspectedCount = 0L
fun getOperatedItems(): List<Long> {
return items.map {
inspectedCount++
val (_, _, _, cmd, num) = operation.split(" ")
val num2 = if (num == "old") it else num.toLong()
when (cmd) {
"+" -> it + num2
"*" -> it * num2
"-" -> it - num2
else -> it
}
}
}
}
class MonkeyTower(input: List<String>) {
private val monkeys = mutableListOf<Monkey>()
init {
var currentMonkey = 0
input.forEach {
val message = it.trim()
when {
message.startsWith("Monkey") -> {
currentMonkey = message.split(" ")[1][0].digitToInt()
monkeys.add(Monkey(0))
}
message.startsWith("Starting items: ") -> {
monkeys[currentMonkey].items =
message.replace("Starting items: ", "").split(", ").map { it.toLong() }.toMutableList()
}
message.startsWith("Operation: ") -> {
monkeys[currentMonkey].operation = message.replace("Operation: ", "")
}
message.startsWith("Test: divisible by ") -> {
monkeys[currentMonkey].divisible = message.replace("Test: divisible by ", "").toInt()
}
message.startsWith("If true: ") -> {
monkeys[currentMonkey].trueTarget = message.replace("If true: throw to monkey ", "").toInt()
}
message.startsWith("If false:") -> {
monkeys[currentMonkey].falseTarget = message.replace("If false: throw to monkey ", "").toInt()
}
}
}
}
fun run(times: Int, levelOptimizer: (Long) -> Long): Long {
val divider = monkeys.map { it.divisible }.fold(1) { acc, n -> acc * n }
repeat(times) {
monkeys.forEach { monkey ->
val items = monkey.getOperatedItems()
monkey.items = mutableListOf()
items.forEach {
val item = levelOptimizer(it) % divider
if (item % monkey.divisible == 0L) monkeys[monkey.trueTarget].items.add(item)
else monkeys[monkey.falseTarget].items.add(item)
}
}
}
return monkeys.map { it.inspectedCount }.sortedDescending().take(2).fold(1L) { acc, n -> acc * n }
}
}
fun main() {
fun part1(input: List<String>): Long {
return MonkeyTower(input).run(20) { it / 3 }
}
fun part2(input: List<String>): Long {
return MonkeyTower(input).run(10000) { it }
}
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b733a4f16ebc7b71af5b08b947ae46afb62df05e | 3,070 | adventOfCode | Apache License 2.0 |
src/main/kotlin/Day6.kt | Ostkontentitan | 434,500,914 | false | {"Kotlin": 73563} | fun puzzleDaySixPartOne() {
val input = readInput(6).first()
val fishes = inputToPopulation(input)
val fishPrediction = predictPopulation(fishes, 80)
println("Fish prediction after 80 days: ${fishPrediction.size}")
}
fun puzzleDaySixPartTwo() {
val input = readInput(6).first()
val model = inputToPopulationModel(input)
val fishPrediction = predictPopulationWithModel(model, 256)
println("Fish prediction after 80 days: ${fishPrediction.values.sum()}")
}
fun inputToPopulation(input: String) = input.split(",").map { Lanternfish(it.toInt()) }
fun predictPopulation(initial: List<Lanternfish>, daysToPass: Int) = (1..daysToPass).fold(initial) { acc, _ ->
acc.flatMap {
if (it.spawnTimer == 0) {
listOf(it.copy(spawnTimer = 6), Lanternfish())
} else {
listOf(it.copy(spawnTimer = it.spawnTimer - 1))
}
}
}
fun predictPopulationWithModel(model: PopulationModel, daysToPass: Int) = (1..daysToPass).fold(model) { acc, _ ->
val spawnCount = acc[0] ?: 0 // add to 6 and 8 later
mapOf(
0 to (acc[1] ?: 0),
1 to (acc[2] ?: 0),
2 to (acc[3] ?: 0),
3 to (acc[4] ?: 0),
4 to (acc[5] ?: 0),
5 to (acc[6] ?: 0),
6 to (acc[7] ?: 0) + spawnCount,
7 to (acc[8] ?: 0),
8 to spawnCount,
)
}
fun inputToPopulationModel(input: String): PopulationModel =
input.split(",").groupingBy { it.toInt() }.eachCount().mapValues { entry -> entry.value.toLong() }
data class Lanternfish(val spawnTimer: Int = 8)
typealias PopulationModel = Map<Int, Long>
| 0 | Kotlin | 0 | 0 | e0e5022238747e4b934cac0f6235b92831ca8ac7 | 1,608 | advent-of-kotlin-2021 | Apache License 2.0 |
src/main/kotlin/day21/Allergens.kt | lukasz-marek | 317,632,409 | false | {"Kotlin": 172913} | package day21
sealed class AbstractAllergen
object NoAllergen : AbstractAllergen()
data class Allergen(val name: String) : AbstractAllergen()
inline class Ingredient(val name: String)
data class Food(val ingredients: Set<Ingredient>, val allergens: Set<AbstractAllergen>)
private val foodPattern = Regex("^(.+) \\(contains (.+)\\)$")
fun parseFood(food: String): Food {
val (ingredientsPart, allergensPart) = foodPattern.matchEntire(food)!!.destructured
val ingredients =
ingredientsPart.split(" ").asSequence().filter { it.isNotEmpty() }.map { it.trim() }.map { Ingredient(it) }
.toSet()
val allergens =
allergensPart.split(",").asSequence().filter { it.isNotEmpty() }.map { it.trim() }.map { Allergen(it) }
.toSet()
return Food(ingredients, allergens)
}
interface Solver {
fun solve(foods: List<Food>): Map<Ingredient, AbstractAllergen>?
}
class SimpleRecursiveSolver : Solver {
override fun solve(foods: List<Food>): Map<Ingredient, AbstractAllergen>? {
val allIngredients = foods.flatMap { it.ingredients }.toSet()
val allAllergens = foods.flatMap { it.allergens }.toSet()
return solve(foods, allIngredients, allAllergens, emptyMap())
}
private fun solve(
foods: List<Food>,
ingredients: Set<Ingredient>,
allergens: Set<AbstractAllergen>,
solution: Map<Ingredient, AbstractAllergen>
): Map<Ingredient, AbstractAllergen>? {
if (ingredients.isEmpty()) {
return solution
}
val ingredient = ingredients.first()
val remainingIngredients = ingredients.drop(1).toSet()
for (allergen in allergens + NoAllergen) {
val currentSolution = solution + (ingredient to allergen)
val noConflicts = foods.all { it.isSatisfiable(currentSolution) }
if (noConflicts) {
val maybeSolution = solve(foods, remainingIngredients, allergens - allergen, currentSolution)
if (maybeSolution != null) {
return maybeSolution
}
}
}
return null
}
private fun Food.isSatisfiable(mapping: Map<Ingredient, AbstractAllergen>): Boolean {
val expectedAllergens = this.allergens
val detectedAllergens = this.ingredients.mapNotNull { mapping[it] }
return detectedAllergens.containsAll(expectedAllergens) || detectedAllergens.size < ingredients.size
}
}
class SmartRecursiveSolver : Solver {
override fun solve(foods: List<Food>): Map<Ingredient, AbstractAllergen>? {
val ingredients = foods.asSequence().flatMap { it.ingredients }.distinct()
.sortedBy { ingredient -> foods.count { it.ingredients.contains(ingredient) } }.toList()
val allergens = foods.flatMap { it.allergens }.toSet()
val foodsByIngredient = ingredients.map { it to foods.filter { food -> food.ingredients.contains(it) } }.toMap()
return solve(foodsByIngredient, ingredients, allergens, mutableMapOf())
}
private fun solve(
foodsByIngredient: Map<Ingredient, List<Food>>,
ingredients: List<Ingredient>,
allergens: Set<AbstractAllergen>,
solution: MutableMap<Ingredient, AbstractAllergen>
): Map<Ingredient, AbstractAllergen>? {
if (ingredients.isEmpty()) {
return solution
}
val ingredient = ingredients.first()
val remainingIngredients = ingredients.drop(1)
val foods = foodsByIngredient[ingredient]!!
for (allergen in allergens + NoAllergen) {
solution[ingredient] = allergen
val hasConflicts = foods.any { it.isConflicting(solution) }
if (!hasConflicts) {
val maybeSolution =
solve(foodsByIngredient, remainingIngredients, allergens - allergen, solution)
if (maybeSolution != null) {
return maybeSolution
}
}
}
return null
}
private fun Food.isConflicting(mapping: Map<Ingredient, AbstractAllergen>): Boolean {
val expectedAllergens = this.allergens
val detectedAllergens = this.ingredients.mapNotNull { mapping[it] }
return expectedAllergens.asSequence()
.filterNot { it in detectedAllergens }.any { it in mapping.values }
}
}
| 0 | Kotlin | 0 | 0 | a16e95841e9b8ff9156b54e74ace9ccf33e6f2a6 | 4,379 | aoc2020 | MIT License |
src/Day07.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | fun main() {
abstract class FileSystemUnit() {
abstract val size: Int
}
class Directory(val parent: Directory? = null) : FileSystemUnit() {
private var realSize: Int? = null
override val size: Int
get() {
if (realSize == null)
realSize = contents.values.sumOf { it.size }
return realSize!!
}
val contents = mutableMapOf<String, FileSystemUnit>()
fun listOfSubdirs(): List<Directory> = contents.filter { it.value is Directory }
.flatMap { (it.value as Directory).listOfSubdirs() } + listOf<Directory>(this)
}
class File(override val size: Int) : FileSystemUnit()
fun calculateDirectoriesSizes(input: List<String>): List<Directory> {
val rootDirectory = Directory()
var currentDirectory = rootDirectory
val inputIterator = input.listIterator()
while (inputIterator.hasNext()) {
val command = inputIterator.next().split(' ').drop(1)
when (command[0]) {
"ls" -> {
while (inputIterator.hasNext() && !input[inputIterator.nextIndex()].startsWith("$ ")) {
val line = inputIterator.next().split(' ')
val fileSystemName = line[1]
currentDirectory.contents.putIfAbsent(
fileSystemName, when (line[0]) {
"dir" -> Directory(currentDirectory)
else -> File(line[0].toInt())
}
)
}
}
"cd" -> {
val path = command[1]
currentDirectory = when (path) {
"/" -> rootDirectory
".." -> currentDirectory.parent ?: rootDirectory
else -> {
currentDirectory.contents.putIfAbsent(path, Directory(currentDirectory))
currentDirectory.contents[path] as Directory
}
}
}
}
}
return rootDirectory.listOfSubdirs()
}
fun part1(input: List<String>) =
calculateDirectoriesSizes(input)
.filter { it.size <= 100_000 }
.sumOf { it.size }
fun part2(input: List<String>) =
calculateDirectoriesSizes(input).let { directories ->
val totalSize = directories.maxOf { it.size }
val neededFreeSpace = 30_000_000 - (70_000_000 - totalSize)
directories.filter { it.size >= neededFreeSpace }.minOf { it.size }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 3,019 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | Sagolbah | 573,032,320 | false | {"Kotlin": 14528} | import kotlin.math.max
import kotlin.math.min
fun main() {
data class Segment(val start: Int, val end: Int)
fun parse(line: String): Pair<Segment, Segment> {
val (fst, snd) = line.split(',')
val (fst1, fst2) = fst.split('-').map { x -> x.toInt() }
val (snd1, snd2) = snd.split('-').map { x -> x.toInt() }
return Pair(Segment(fst1, fst2), Segment(snd1, snd2))
}
fun part1(input: List<String>): Int {
var ans = 0
for (line in input) {
val (fst, snd) = parse(line)
if (fst.start == fst.end ) {
ans += if (fst.start >= snd.start && fst.start <= snd.end) 1 else 0
} else if (snd.start == snd.end) {
ans += if (snd.start >= fst.start && snd.start <= fst.end) 1 else 0
} else {
val intersection = max(min(fst.end, snd.end) - max(fst.start, snd.start), 0)
if (intersection == (fst.end - fst.start) || intersection == (snd.end - snd.start)) {
ans++
}
}
}
return ans
}
fun part2(input: List<String>): Int {
var ans = 0
for (line in input) {
val (fst, snd) = parse(line)
ans += if (fst.start == fst.end) {
if (fst.start >= snd.start && fst.start <= snd.end) 1 else 0
} else if (snd.start == snd.end) {
if (snd.start >= fst.start && snd.start <= fst.end) 1 else 0
} else {
val intersection = max(min(fst.end, snd.end) - max(fst.start, snd.start), 0)
if (intersection > 0 || fst.end == snd.start || snd.end == fst.start) 1 else 0
}
}
return ans
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 893c1797f3995c14e094b3baca66e23014e37d92 | 1,837 | advent-of-code-kt | Apache License 2.0 |
src/main/kotlin/Day7.kt | vw-anton | 574,945,231 | false | {"Kotlin": 33295} | fun main() {
val parsed = readFile("input/7.txt")
.drop(1)
.map { line ->
when {
line == "\$ cd /" -> Directory(name = "/")
line.startsWith("$") -> Command.from(line)
line.first().isDigit() -> File.from(line)
else -> Directory.from(line)
}
}
val root = Directory(name = "/")
var currentDir = root
parsed.forEach { item ->
when (item) {
is File -> currentDir.childs.add(item)
is Directory -> currentDir.childs.add(item)
is Command -> {
when {
item.isMoveUp() -> currentDir = currentDir.parent!!
item.isMoveDown() -> {
currentDir =
currentDir.childs
.filterIsInstance<Directory>()
.first { it.name == item.param }
.also { newDir -> newDir.parent = currentDir }
}
}
}
}
}
println(part1(parsed))
println(part2(root, parsed))
}
private fun part1(parsed: List<Any>): Int {
return parsed
.filterIsInstance<Directory>()
.filter { it.getSize() < 100_000 }
.sumOf { it.getSize() }
}
private fun part2(root: Directory, parsed: List<Any>): Int {
val totalSpace = 70_000_000
val freeSpaceRequired = 30_000_000
val usedSpace = root.getSize()
val freeSpace = totalSpace - usedSpace
val requiredSpace = freeSpaceRequired - freeSpace
return parsed
.filterIsInstance<Directory>()
.filter { it.getSize() >= requiredSpace }
.minOf { it.getSize() }
}
data class Command(val command: String, val param: String) {
fun isMoveUp() = command == "cd" && param == ".."
fun isMoveDown() = command == "cd" && param != ".."
companion object {
fun from(input: String): Command {
val split = input.split(" ")
return Command(command = split[1], param = split.getOrElse(2) { "" })
}
}
}
data class Directory(
val childs: MutableList<Any> = mutableListOf(),
val name: String,
var parent: Directory? = null
) {
fun getSize(): Int {
return childs.sumOf {
when (it) {
is Directory -> it.getSize()
is File -> it.size
else -> 0
}
}
}
override fun toString(): String {
return "Directory(name='$name')"
}
companion object {
fun from(line: String): Directory {
val split = line.split(" ")
return Directory(name = split[1])
}
}
}
data class File(val size: Int, val name: String) {
companion object {
fun from(input: String): File {
val split = input.split(" ")
return File(size = split[0].toInt(), name = split[1])
}
}
} | 0 | Kotlin | 0 | 0 | a823cb9e1677b6285bc47fcf44f523e1483a0143 | 2,986 | aoc2022 | The Unlicense |
src/Day09.kt | buczebar | 572,864,830 | false | {"Kotlin": 39213} | import java.lang.IllegalArgumentException
import kotlin.math.abs
typealias Point = Pair<Int, Int>
private fun Point.isTouching(point: Point) = abs(first - point.first) < 2 && abs(second - point.second) < 2
fun main() {
fun parseInput(name: String) = readInput(name).map { it.splitWords() }
.map { (direction, steps) -> direction to steps.toInt() }
fun getAllKnotsPositions(moves: List<Pair<String, Int>>, numOfKnots: Int): List<List<Point>> {
fun getNextHeadPosition(position: Point, direction: String) = when (direction) {
"L" -> Pair(position.first - 1, position.second)
"R" -> Pair(position.first + 1, position.second)
"U" -> Pair(position.first, position.second + 1)
"D" -> Pair(position.first, position.second - 1)
else -> throw IllegalArgumentException("Wrong direction $direction")
}
fun followingPosition(currentPosition: Point, leaderPosition: Point) = Point(
currentPosition.first + leaderPosition.first.compareTo(currentPosition.first),
currentPosition.second + leaderPosition.second.compareTo(currentPosition.second)
)
val startingPoint = 0 to 0
val knotsPositions = List(numOfKnots) { mutableListOf(startingPoint) }
moves.forEach { (direction, steps) ->
repeat(steps) {
val headPositions = knotsPositions.head()
headPositions.add(getNextHeadPosition(headPositions.last(), direction))
knotsPositions.forEachIndexed { index, currentKnotPositions ->
if (index == 0) return@forEachIndexed
val previousKnotPosition = knotsPositions[index - 1].last()
val currentKnotPosition = currentKnotPositions.last()
if (!previousKnotPosition.isTouching(currentKnotPosition)) {
currentKnotPositions.add(followingPosition(currentKnotPosition, previousKnotPosition))
} else {
currentKnotPositions.add(currentKnotPosition)
}
}
}
}
return knotsPositions
}
fun part1(input: List<Pair<String, Int>>): Int {
return getAllKnotsPositions(input, 2).last().distinct().size
}
fun part2(input: List<Pair<String, Int>>): Int {
return getAllKnotsPositions(input, 10).last().distinct().size
}
val testInput = parseInput("Day09_test")
val testInputPart2 = parseInput("Day09_test2")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
check(part2(testInputPart2) == 36)
val input = parseInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cdb6fe3996ab8216e7a005e766490a2181cd4101 | 2,739 | advent-of-code | Apache License 2.0 |
src/poyea/aoc/mmxxii/day22/Day22.kt | poyea | 572,895,010 | false | {"Kotlin": 68491} | package poyea.aoc.mmxxii.day22
import poyea.aoc.utils.readInput
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}
sealed class Instruction {
object Left : Instruction()
object Right : Instruction()
data class Move(val steps: Int) : Instruction()
}
enum class Dir(val left: () -> Dir, val right: () -> Dir, val offset: Point, val score: Int) {
EAST(left = { NORTH }, right = { SOUTH }, offset = Point(1, 0), score = 0),
SOUTH(left = { EAST }, right = { WEST }, offset = Point(0, 1), score = 1),
WEST(left = { SOUTH }, right = { NORTH }, offset = Point(-1, 0), score = 2),
NORTH(left = { WEST }, right = { EAST }, offset = Point(0, -1), score = 3),
}
fun calculate(y: Int, x: Int, dir: Dir): Int {
return 1000 * (y + 1) + 4 * (x + 1) + dir.score
}
fun part1(input: String): Int {
val lines = input.split("\n")
val grid =
lines
.dropLast(2)
.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c -> if (c == ' ') null else Point(x, y) to c }
}
.associate { it }
val instructions =
"""\d+|[LR]"""
.toRegex()
.findAll(lines.last())
.map {
when (it.value) {
"L" -> Instruction.Left
"R" -> Instruction.Right
else -> Instruction.Move(it.value.toInt())
}
}
.toList()
var position = Point(grid.keys.filter { it.y == 0 }.minOf { it.x }, 0)
var dir = Dir.EAST
instructions.forEach { instruction ->
when (instruction) {
is Instruction.Left -> dir = dir.left()
is Instruction.Right -> dir = dir.right()
is Instruction.Move ->
generateSequence(position to dir) { (p, d) ->
val next = p + d.offset
when {
next in grid && grid[next] == '#' -> p to d
next !in grid -> {
val rotatedDir = dir.right().right()
val (newPos, newDir) =
generateSequence(position) { it + rotatedDir.offset }
.takeWhile { it in grid }
.last() to dir
if (grid[newPos] == '.') newPos to newDir else p to d
}
else -> next to d
}
}
.take(instruction.steps + 1)
.last()
.let { (p, d) ->
position = p
dir = d
}
}
}
return calculate(position.y, position.x, dir)
}
fun part2(input: String): Int {
val lines = input.split("\n")
val grid =
lines
.dropLast(2)
.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c -> if (c == ' ') null else Point(x, y) to c }
}
.associate { it }
val instructions =
"""\d+|[LR]"""
.toRegex()
.findAll(lines.last())
.map {
when (it.value) {
"L" -> Instruction.Left
"R" -> Instruction.Right
else -> Instruction.Move(it.value.toInt())
}
}
.toList()
var position = Point(grid.keys.filter { it.y == 0 }.minOf { it.x }, 0)
var dir = Dir.EAST
instructions.forEach { instruction ->
when (instruction) {
is Instruction.Left -> dir = dir.left()
is Instruction.Right -> dir = dir.right()
is Instruction.Move ->
generateSequence(position to dir) { (p, d) ->
val next = p + d.offset
when {
next in grid && grid[next] == '#' -> p to d
next !in grid -> {
val (newPos, newDir) =
when (Triple(d, p.x / 50, p.y / 50)) {
Triple(Dir.NORTH, 1, 0) ->
Point(0, 100 + p.x) to Dir.EAST
Triple(Dir.WEST, 1, 0) ->
Point(0, 149 - p.y) to Dir.EAST
Triple(Dir.NORTH, 2, 0) ->
Point(p.x - 100, 199) to Dir.NORTH
Triple(Dir.EAST, 2, 0) ->
Point(99, 149 - p.y) to Dir.WEST
Triple(Dir.SOUTH, 2, 0) ->
Point(99, -50 + p.x) to Dir.WEST
Triple(Dir.EAST, 1, 1) ->
Point(50 + p.y, 49) to Dir.NORTH
Triple(Dir.WEST, 1, 1) ->
Point(p.y - 50, 100) to Dir.SOUTH
Triple(Dir.NORTH, 0, 2) ->
Point(50, p.x + 50) to Dir.EAST
Triple(Dir.WEST, 0, 2) ->
Point(50, 149 - p.y) to Dir.EAST
Triple(Dir.EAST, 1, 2) ->
Point(149, 149 - p.y) to Dir.WEST
Triple(Dir.SOUTH, 1, 2) ->
Point(49, 100 + p.x) to Dir.WEST
Triple(Dir.EAST, 0, 3) ->
Point(p.y - 100, 149) to Dir.NORTH
Triple(Dir.SOUTH, 0, 3) ->
Point(p.x + 100, 0) to Dir.SOUTH
Triple(Dir.WEST, 0, 3) ->
Point(p.y - 100, 0) to Dir.SOUTH
else -> Point(-99999, -99999) to Dir.EAST
}
if (grid[newPos] == '.') newPos to newDir else p to d
}
else -> next to d
}
}
.take(instruction.steps + 1)
.last()
.let { (p, d) ->
position = p
dir = d
}
}
}
return calculate(position.y, position.x, dir)
}
fun main() {
println(part1(readInput("Day22")))
println(part2(readInput("Day22")))
}
| 0 | Kotlin | 0 | 1 | fd3c96e99e3e786d358d807368c2a4a6085edb2e | 6,976 | aoc-mmxxii | MIT License |
2022/src/test/kotlin/Day16.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
private data class Valve(val name: String, val flowRate: Int, val leadsTo: List<String>, var open: Boolean = false)
private val re = "rate=(\\d+);".toRegex()
class Day16 : StringSpec({
"puzzle part 01" {
val valves = getValves()
val start = valves.single { it.name == "AA" }
val relevantValves = valves.filterNot { it.flowRate == 0 }.sortedByDescending { it.flowRate }.toSet()
val distances = (relevantValves + start).flatMap { v1 ->
(relevantValves + start).map { v2 -> Pair(v1.name, v2.name) to valves.distance(v1, v2) }
}.toMap()
val time = 30
val maxPressure = relevantValves.allRoutes(start, listOf(), time, distances)
.maxOf { it.pressure(time) }
maxPressure shouldBe 1728
}
"puzzle part 02" {
val valves = getValves()
val start = valves.single { it.name == "AA" }
val relevantValves = valves.filterNot { it.flowRate == 0 }.sortedByDescending { it.flowRate }.toSet()
val distances = (relevantValves + start).flatMap { v1 ->
(relevantValves + start).map { v2 -> Pair(v1.name, v2.name) to valves.distance(v1, v2) }
}.toMap()
val time = 26
val pressureForOne = relevantValves
.allRoutes(start, listOf(), time, distances)
.sortedByDescending { it.pressure(time) }
.take(1000) // Just a gamble but seems to work
val combinedPressure = pressureForOne
.flatMap { elf ->
pressureForOne
.filter { elephant -> elf.none { elephant.any { e -> e.first.name == it.first.name } } }
.map { elephant -> elf to elephant }
}
.maxOf {
it.first.pressure(time) + it.second.pressure(time)
}
combinedPressure shouldBe 2304
}
})
private fun Set<Valve>.distance(start: Valve, end: Valve) = routesWithoutLoops(start, end)
.filter { v -> v.any { it.name == end.name } }
.minOf { v -> v.indexOfFirst { it.name == end.name } }
private fun Set<Valve>.routesWithoutLoops(
current: Valve,
end: Valve,
path: List<Valve> = listOf(),
knownPaths: List<List<Valve>> = listOf()
): List<List<Valve>> {
if (current == end) return listOf(path + current)
val next = current.leadsTo.filterNot { it in path.map { n -> n.name } }
if (next.none()) return listOf(path + current)
return knownPaths + next.flatMap {
routesWithoutLoops(this.single { n -> n.name == it }, end, path + current, knownPaths)
}
}
private fun Set<Valve>.allRoutes(
current: Valve,
path: List<Pair<Valve, Int>>,
max: Int,
distances: Map<Pair<String, String>, Int>,
knownPaths: Set<List<Pair<Valve, Int>>> = setOf()
): Set<List<Pair<Valve, Int>>> {
val next = this
.filterNot { it.name == current.name || it.name in path.map { n -> n.first.name } }
.map {
val distance = if (path.isEmpty())
distances["AA" to it.name]!!
else
path.last().second + distances[path.last().first.name to it.name]!!
it to distance
}
.filter { it.second < max }
if (next.none())
return setOf(path)
return knownPaths + next.flatMap {
allRoutes(
this.single { n -> n.name == it.first.name },
path + (it.first to it.second.inc()),
max,
distances,
knownPaths
)
}
}
private fun List<Pair<Valve, Int>>.pressure(minutes: Int) = this.fold(0L) { acc, it ->
acc + ((minutes - it.second) * it.first.flowRate)
}
private fun getValves() = getPuzzleInput("day16-input.txt")
.map {
val n = it.substring(6..7)
val r = re.find(it)?.groups?.get(1)?.value?.toInt() ?: throw IllegalArgumentException(it)
val l = it.drop(it.indexOf(";") + 24).split(", ").map { s -> s.trim() }
Valve(n, r, l)
}.toSet()
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 4,046 | adventofcode | MIT License |
src/day4/puzzle04.kt | brendencapps | 572,821,792 | false | {"Kotlin": 70597} | package day4
import Puzzle
import PuzzleInput
import java.io.File
fun day4Puzzle() {
val inputDir = "inputs/day4"
Day4Puzzle1Solution().solve(Day4PuzzleInput("$inputDir/example.txt", 2))
Day4Puzzle1Solution().solve(Day4PuzzleInput("$inputDir/input.txt", 305))
Day4Puzzle2Solution().solve(Day4PuzzleInput("$inputDir/example.txt", 4))
Day4Puzzle2Solution().solve(Day4PuzzleInput("$inputDir/input.txt", 811))
}
data class ElfSectionPair(val input: String) {
private val elf1Section: IntRange
private val elf2Section: IntRange
init {
val inputParser = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex()
val (start1, end1, start2, end2) = inputParser.find(input)!!.destructured
elf1Section = start1.toInt() .. end1.toInt()
elf2Section = start2.toInt() .. end2.toInt()
}
fun duplicateWork() : Boolean {
return elf1Section.fullyContains(elf2Section) || elf2Section.fullyContains(elf1Section)
}
fun overlaps() : Boolean {
return elf1Section.overlaps(elf2Section)
}
}
class Day4PuzzleInput(private val input: String, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) {
fun count(op: (ElfSectionPair) -> Boolean): Int {
return File(input).readLines().count { elfPair ->
op(ElfSectionPair(elfPair))
}
}
}
class Day4Puzzle1Solution : Puzzle<Int, Day4PuzzleInput>() {
override fun solution(input: Day4PuzzleInput): Int {
return input.count {elfSelectionPair ->
elfSelectionPair.duplicateWork()
}
}
}
class Day4Puzzle2Solution : Puzzle<Int, Day4PuzzleInput>() {
override fun solution(input: Day4PuzzleInput): Int {
return input.count {elfSelectionPair ->
elfSelectionPair.overlaps()
}
}
}
fun IntRange.fullyContains(other: IntRange): Boolean {
return first >= other.first && last <= other.last
}
fun IntRange.overlaps(other: IntRange): Boolean {
return other.first in this || other.last in this || first in other || last in other
}
| 0 | Kotlin | 0 | 0 | 00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3 | 2,113 | aoc_2022 | Apache License 2.0 |
src/Day02.kt | stevefranchak | 573,628,312 | false | {"Kotlin": 34220} | class StrategyGuideParser(private val scorer: Scorer) {
fun sumScores(input: List<String>) =
input.asSequence().map(::scoreLine).sum()
private fun scoreLine(line: String): Int {
if (line.isBlank()) {
return 0
}
return scorer.score(line.split(" "))
}
}
interface Scorer {
fun score(lineParts: List<String>): Int
}
class Part1Scorer : Scorer {
override fun score(lineParts: List<String>): Int {
val (otherPlayed, selfPlayed) = lineParts.map(Play::fromString)
return selfPlayed.score + RoundOutcome.fromPlays(selfPlayed, otherPlayed).score
}
}
class Part2Scorer : Scorer {
override fun score(lineParts: List<String>): Int {
val otherPlayed = Play.fromString(lineParts[0])
val desiredOutcome = RoundOutcome.fromString(lineParts[1])
return desiredOutcome.toPlayForOutcome(otherPlayed).score + desiredOutcome.score
}
}
enum class Play(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
companion object {
fun fromString(input: String) =
when (input.trim()) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException("Unknown play input provided: $input")
}
}
}
enum class RoundOutcome(val score: Int) {
LOSS(0),
DRAW(3),
WIN(6);
fun toPlayForOutcome(otherPlay: Play) =
when (this) {
LOSS -> when (otherPlay) {
Play.ROCK -> Play.SCISSORS
Play.PAPER -> Play.ROCK
Play.SCISSORS -> Play.PAPER
}
WIN -> when (otherPlay) {
Play.ROCK -> Play.PAPER
Play.PAPER -> Play.SCISSORS
Play.SCISSORS -> Play.ROCK
}
DRAW -> otherPlay
}
companion object {
fun fromPlays(self: Play, other: Play) =
when (self) {
Play.ROCK -> when (other) {
Play.ROCK -> DRAW
Play.PAPER -> LOSS
Play.SCISSORS -> WIN
}
Play.PAPER -> when (other) {
Play.ROCK -> WIN
Play.PAPER -> DRAW
Play.SCISSORS -> LOSS
}
Play.SCISSORS -> when (other) {
Play.ROCK -> LOSS
Play.PAPER -> WIN
Play.SCISSORS -> DRAW
}
}
fun fromString(input: String) =
when (input.trim()) {
"X" -> LOSS
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException("Unknown round outcome input provided: $input")
}
}
}
fun main() {
fun part1(input: List<String>) = StrategyGuideParser(Part1Scorer()).sumScores(input)
fun part2(input: List<String>) = StrategyGuideParser(Part2Scorer()).sumScores(input)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val part1TestOutput = part1(testInput)
val part1ExpectedOutput = 15
check(part1TestOutput == part1ExpectedOutput) { "$part1TestOutput != $part1ExpectedOutput" }
val part2TestOutput = part2(testInput)
val part2ExpectedOutput = 12
check(part2TestOutput == part2ExpectedOutput) { "$part2TestOutput != $part2ExpectedOutput" }
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 22a0b0544773a6c84285d381d6c21b4b1efe6b8d | 3,569 | advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | proggler23 | 573,129,757 | false | {"Kotlin": 27990} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
return input.parse13().withIndex().sumOf {
val (left, right) = it.value
if (left < right) it.index + 1
else 0
}
}
fun part2(input: List<String>): Int {
val dividerPackets = listOf("[[2]]".parse13(), "[[6]]".parse13())
val packets = (input.parse13().flatten() + dividerPackets).sorted()
return dividerPackets.productOf { packets.indexOf(it) + 1 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
data class Packet(val packets: List<Packet> = emptyList(), val value: Int? = null) : Comparable<Packet> {
override fun toString() = value?.toString() ?: packets.joinToString(separator = ",", prefix = "[", postfix = "]")
override operator fun compareTo(other: Packet): Int {
if (value != null && other.value != null) {
return value.compareTo(other.value)
} else if (value == null && other.value == null) {
for (i in 0 until max(packets.size, other.packets.size)) {
val left = packets.getOrNull(i)
val right = other.packets.getOrNull(i)
if (left == null) {
return -1
} else if (right == null) {
return 1
} else {
val comp = left.compareTo(right)
if (comp != 0) return comp
}
}
return 0
} else if (value != null) {
return Packet(listOf(this)).compareTo(other)
} else {
return compareTo(Packet(listOf(other)))
}
}
}
fun List<String>.parse13() = partitionBy("").map { (p1, p2) -> listOf(p1.parse13(), p2.parse13()) }
fun String.parse13(): Packet {
var index = 0
val packets = mutableListOf<Packet>()
while (index < length) {
if (this[index] == '[') {
packets += substring(index + 1).parse13()
index += packets.last().toString().length
} else if (this[index] == ']') {
break
} else if (this[index] == ',') {
index++
} else {
var v = this[index].digitToInt()
while (++index < this.length && this[index].isDigit()) {
v *= 10
v += this[index].digitToInt()
}
packets += Packet(value = v)
}
}
return Packet(packets = packets)
} | 0 | Kotlin | 0 | 0 | 584fa4d73f8589bc17ef56c8e1864d64a23483c8 | 2,701 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | jpereyrol | 573,074,843 | false | {"Kotlin": 9016} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
val firstSplit = input.map { it.split(",") }
val secondSplit = firstSplit.map { it.map { it.split("-") } }.map { it.map { it.map { it.toInt() } } }
val ranges = secondSplit.map { it.map { IntRange(it.first(), it.last()) } }
return ranges.sumOf { it.first().overlapsFully(it.last()).toInt() }
}
fun part2(input: List<String>): Int {
val firstSplit = input.map { it.split(",") }
val secondSplit = firstSplit.map { it.map { it.split("-") } }.map { it.map { it.map { it.toInt() } } }
val ranges = secondSplit.map { it.map { IntRange(it.first(), it.last()) } }
return ranges.sumOf { it.first().overlapsPartially(it.last()).toInt() }
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun Boolean.toInt(): Int {
return if (this) 1 else 0
}
fun IntRange.overlapsFully(other: IntRange): Boolean {
val resultRange = IntRange(max(this.first, other.first), min(this.last, other.last))
return if (resultRange.first <= resultRange.last) {
//overlap
resultRange == this || resultRange == other
} else {
//no overlap
false
}
}
fun IntRange.overlapsPartially(other: IntRange): Boolean {
return (this intersect other).isNotEmpty()
} | 0 | Kotlin | 0 | 0 | e17165afe973392a0cbbac227eb31d215bc8e07c | 1,403 | advent-of-code | Apache License 2.0 |
src/Day13.kt | achugr | 573,234,224 | false | null | import kotlinx.serialization.json.*
val packetDataComparator = PacketDataComparator()
data class Packet(private val rawData: String, private val data: JsonElement) : Comparable<Packet> {
companion object PacketParser {
fun parse(input: String): Packet {
return Packet(input, Json.parseToJsonElement(input))
}
}
override fun compareTo(other: Packet): Int {
return packetDataComparator.compare(this.data, other.data)
}
override fun toString(): String {
return data.toString()
}
fun isDivider(): Boolean {
return "[[2]]" == rawData || "[[6]]" == rawData
}
}
class PacketDataComparator : Comparator<JsonElement> {
override fun compare(o1: JsonElement?, o2: JsonElement?): Int {
return when {
o1 is JsonPrimitive && o2 is JsonPrimitive -> o1.int.compareTo(o2.int)
o1 is JsonPrimitive -> compare(JsonArray(listOf(o1)), o2)
o2 is JsonPrimitive -> compare(o1, JsonArray(listOf(o2)))
o1 is JsonArray && o2 is JsonArray -> {
val firstMismatch = o1.zip(o2).firstOrNull { compare(it.first, it.second) != 0 }
when {
firstMismatch == null && o1.size == o2.size -> 0
firstMismatch == null && o1.size < o2.size -> -1
firstMismatch == null -> 1
else -> compare(firstMismatch.first, firstMismatch.second)
}
}
else -> throw RuntimeException("Unexpected arguments: $o1 and $o2")
}
}
}
fun main() {
fun part1(input: String): Int {
return input.split("\n")
.windowed(2, 3)
.mapIndexedNotNull { idx, window ->
val packet1 = Packet.parse(window[0])
val packet2 = Packet.parse(window[1])
if (packet1 < packet2) {
idx
} else {
null
}
}
.sumOf { it + 1 }
}
fun part2(input: String): Int {
return input.split("\n")
.asSequence()
.filter { it.trim().isNotEmpty() }
.map { Packet.parse(it) }
.sorted()
.mapIndexedNotNull { idx, packet -> if (packet.isDivider()) idx + 1 else null }
.reduce { acc, value -> acc * value }
}
// test if implementation meets criteria from the description, like:
println(part1(readInputText("Day13")))
println(part2(readInputText("Day13")))
}
| 0 | Kotlin | 0 | 0 | d91bda244d7025488bff9fc51ca2653eb6a467ee | 2,541 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day15.kt | ShuffleZZZ | 572,630,279 | false | {"Kotlin": 29686} | import kotlin.math.absoluteValue
private const val TEST_LINE = 10
private const val LINE = 2_000_000
private const val TEST_SIZE = 20
private const val SIZE = 4_000_000
private val template = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex()
private fun getCoordinates(input: List<String>) = input.map { template.matchEntire(it)!!.destructured }
.map { (x, y, bx, by) -> (x.toInt() to y.toInt()) to (bx.toInt() to by.toInt()) }
private fun MutableSet<Pair<Int, Int>>.addRange(other: Pair<Int, Int>) {
for (pair in this) {
if (pair.include(other)) {
if (other.diff() > pair.diff()) {
remove(pair)
addRange(other)
}
return
}
}
for (pair in this) {
if (pair.intersect(other)) {
remove(pair)
addRange(
pair.first.coerceAtMost(other.first)
to pair.second.coerceAtLeast(other.second)
)
return
}
}
add(other)
}
private fun Set<Pair<Int, Int>>.amount() = sumOf { it.diff() + 1 }
private fun fillLine(
coordinates: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>,
line: Int,
leastX: Int = Int.MIN_VALUE,
mostX: Int = Int.MAX_VALUE,
): Set<Pair<Int, Int>> {
val xs = mutableSetOf<Pair<Int, Int>>()
for ((sensor, beacon) in coordinates) {
val beaconDistance = sensor.manhattan(beacon)
val lineDistance = (line - sensor.second).absoluteValue
val rangeWidth = beaconDistance - lineDistance
if (rangeWidth < 0) continue
xs.addRange(
(sensor.first - rangeWidth).coerceAtLeast(leastX)
to (sensor.first + rangeWidth).coerceAtMost(mostX)
)
}
return xs
}
private fun frequency(x: Int, y: Int) = 1L * SIZE * x + y
fun main() {
fun part1(input: List<String>, line: Int) = fillLine(getCoordinates(input), line).amount() - 1
fun part2(input: List<String>, size: Int): Long? {
val coordinates = getCoordinates(input)
for (line in 0..size) {
val xs = fillLine(coordinates, line, 0, size)
if (xs.amount() != size + 1) {
if (xs.size == 2) {
assert(xs.first().second + 1 == xs.last().first - 1)
return frequency(xs.first().second + 1, line)
}
assert(xs.size == 1)
return frequency(if (xs.first().first == 0) size else 0, line)
}
}
return null
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, TEST_LINE) == 26)
check(part2(testInput, TEST_SIZE) == 56_000_011L)
val input = readInput("Day15")
println(part1(input, LINE))
println(part2(input, SIZE))
}
| 0 | Kotlin | 0 | 0 | 5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e | 2,891 | advent-of-code-kotlin | Apache License 2.0 |
src/Day07.kt | bendh | 573,833,833 | false | {"Kotlin": 11618} | fun main() {
data class File(val name: String, val size: Int)
class Directory(val name: String, var parent: Directory? = null) {
val files = mutableListOf<File>()
val childDirectories = mutableListOf<Directory>()
var dirSize = 0
}
fun diskSizeData(input: List<String>): List<Directory> {
val root = Directory("/")
val allDirs = mutableListOf(root)
var pwd = root
input.drop(1).forEach {
command ->
when {
command == "$ cd .." -> pwd = pwd.parent!!
command.startsWith("$ cd") -> {
val substringAfter = command.substringAfter("$ cd ")
pwd = pwd.childDirectories.find { directory -> directory.name == substringAfter }!!
}
command.startsWith("dir") -> {
val dir = Directory(command.substringAfter("dir "), pwd)
pwd.childDirectories.add(dir)
allDirs.add(dir)
}
command[0].isDigit() -> {
val (size, name) = command.split(" ")
pwd.dirSize += size.toInt()
pwd.files.add(File(name, size.toInt()))
var up = pwd.parent
while (up != null) {
up.dirSize += size.toInt()
up = up.parent
}
}
}
}
return allDirs
}
/**
* To begin, find all of the directories with a total size of at most 100000,
* then calculate the sum of their total sizes.
*/
fun part1(input: List<String>): Int {
return diskSizeData(input)
.filter { directory -> directory.dirSize <= 100_000 }
.sumOf { it.dirSize }
}
fun part2(input: List<String>): Int {
val maxDiskSize = 70_000_000
val neededSpace = 30_000_000
val used = diskSizeData(input)[0].dirSize
val available = maxDiskSize - used
val requiredDirToDeleteSize = neededSpace - available
return diskSizeData(input)
.filter { it.dirSize >= requiredDirToDeleteSize }
.sortedBy { it.dirSize }[0].dirSize
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day07_test")
part1(testInput)
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readLines("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e3ef574441b63a99a99a095086a0bf025b8fc475 | 2,596 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/year2022/Day11.kt | Maetthu24 | 572,844,320 | false | {"Kotlin": 41016} | package year2022
fun main() {
data class Monkey(val items: MutableList<Long>, val operation: (Long) -> Long, val divisibleBy: Long, val ifTrue: Int, val ifFalse: Int) {
fun test(nr: Long): Int {
return if(nr % divisibleBy == 0.toLong()) ifTrue else ifFalse
}
}
fun createMonkey(input: List<String>): Monkey {
val items = input[1].drop(18).split(", ").map { it.toLong() }
val opString = input[2].drop(13).split(" ").drop(2)
val divisibleBy = input[3].split(" ").last().toLong()
val ifTrue = input[4].split(" ").last().toInt()
val ifFalse = input[5].split(" ").last().toInt()
return Monkey(items.toMutableList(), { old ->
val first = if (opString[0] == "old") old else opString[0].toLong()
val second = if (opString[2] == "old") old else opString[2].toLong()
when (opString[1]) {
"+" -> first + second
"-" -> first - second
"*" -> first * second
"/" -> first / second
else -> error("Unsupported operator")
}
}, divisibleBy, ifTrue, ifFalse)
}
fun part1(input: String): Int {
val monkeys = input.split("\n\n").map { createMonkey(it.split("\n")) }
val activity: Map<Int, Int> = buildMap {
monkeys.indices.forEach { put(it, 0) }
for (round in 1 .. 20) {
for ((idx, monkey) in monkeys.withIndex()) {
for (item in monkey.items) {
val c: Int = get(idx)!!
put(idx, c + 1)
val new = monkey.operation(item) / 3
val newMonkeyIdx = monkey.test(new)
monkeys[newMonkeyIdx].items.add(new)
}
monkey.items.clear()
}
}
}
return activity.values.sortedDescending()[0] * activity.values.sortedDescending()[1]
}
fun gcd(a: Long, b: Long): Long {
var aa = a
var bb = b
while (bb > 0) {
val temp = bb
bb = aa % bb
aa = temp
}
return aa
}
fun lcm(a: Long, b: Long): Long {
return a * (b / gcd(a, b))
}
fun lcm(input: List<Long>): Long {
var result = input[0]
for (i in 1 until input.size) {
result = lcm(result, input[i])
}
return result
}
fun part2(input: String): Long {
val monkeys = input.split("\n\n").map { createMonkey(it.split("\n")) }
val lcm = lcm(monkeys.map { it.divisibleBy })
val activity: Map<Int, Long> = buildMap {
monkeys.indices.forEach { put(it, 0) }
for (round in 1 .. 10_000) {
for ((idx, monkey) in monkeys.withIndex()) {
for (item in monkey.items) {
val c: Long = get(idx)!!
put(idx, c + 1)
val new = monkey.operation(item) % lcm
val newMonkeyIdx = monkey.test(new)
monkeys[newMonkeyIdx].items.add(new)
}
monkey.items.clear()
}
}
}
return activity.values.sortedDescending()[0] * activity.values.sortedDescending()[1]
}
val day = "11"
// Read inputs
val testInput = readText("Day${day}_test")
val input = readText("Day${day}")
// Test & run part 1
val testResult = part1(testInput)
val testExpected = 10605
check(testResult == testExpected) { "testResult should be $testExpected, but is $testResult" }
println(part1(input))
// Test & run part 2
val testResult2 = part2(testInput)
val testExpected2 = 2713310158
check(testResult2 == testExpected2) { "testResult2 should be $testExpected2, but is $testResult2" }
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 3b3b2984ab718899fbba591c14c991d76c34f28c | 3,963 | adventofcode-kotlin | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day05/Day05.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day05
import nl.sanderp.aoc.common.*
fun main() {
val input = readResource("Day05.txt").lines().map { parse(it) }
val (answer1, duration1) = measureDuration<Int> { countOverlappingPoints(input.filter { it.type != LineType.Diagonal }) }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
val (answer2, duration2) = measureDuration<Int> { countOverlappingPoints(input) }
println("Part two: $answer2 (took ${duration2.prettyPrint()})")
}
enum class LineType { Horizontal, Vertical, Diagonal }
data class LineSegment(val start: Point2D, val end: Point2D) {
val points by lazy {
val xs = if (start.x < end.x) start.x..end.x else start.x downTo end.x
val ys = if (start.y < end.y) start.y..end.y else start.y downTo end.y
when {
start.x == end.x -> ys.map { start.x to it }
start.y == end.y -> xs.map { it to start.y }
else -> xs.zip(ys)
}
}
val type = when {
start.y == end.y -> LineType.Horizontal
start.x == end.x -> LineType.Vertical
else -> LineType.Diagonal
}
}
private fun parse(line: String): LineSegment {
val (a, b) = line.split(" -> ")
.map { p -> p.split(',').map { it.toInt() } }
.map { (p1, p2) -> p1 to p2 }
return LineSegment(a, b)
}
private fun countOverlappingPoints(segments: List<LineSegment>) =
segments.flatMap { it.points }.groupingBy { it }.eachCount().filterValues { it > 1 }.keys.size
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,516 | advent-of-code | MIT License |
src/main/kotlin/be/tabs_spaces/advent2021/days/Day09.kt | janvryck | 433,393,768 | false | {"Kotlin": 58803} | package be.tabs_spaces.advent2021.days
class Day09 : Day(9) {
private val heightMap = HeightMap(inputList)
override fun partOne() = heightMap
.findLowPoints()
.map { heightMap.heightAt(it) }
.sumOf { it.toRiskLevel() }
override fun partTwo() = heightMap.largestThreeBasins().productOf { it.size }
class HeightMap(rawMap: List<String>) {
private val yXZMap = rawMap.mapIndexed { y, xz -> y to xz.mapIndexed { x, z -> x to z.digitToInt() }.toMap() }.toMap()
private val maxY = (yXZMap.size).dec()
private val maxX = (yXZMap[0]?.size ?: -1).dec()
fun findLowPoints(): List<Pair<Int, Int>> {
return yXZMap.entries.flatMap { (y, xz) -> xz.entries.filter { (x, z) -> isLowPoint(x, y, z) }.map { (x, _) -> y to x } }
}
fun heightAt(yX: Pair<Int, Int>) = yXZMap[yX.first]!![yX.second]!!
fun largestThreeBasins() = findLowPoints().map { higherBasinPointsAround(it) }.sortedBy { it.size }.reversed().take(3)
private fun higherBasinPointsAround(point: Pair<Int, Int>): Set<Pair<Int, Int>> {
return setOf(point) + neighbouringPoints(point)
.filter { heightAt(it) in heightAt(point).inc() until 9 }
.flatMap { higherBasinPointsAround(it) }
.toSet()
}
private fun isLowPoint(x: Int, y: Int, z: Int): Boolean {
return z < neighbouringPoints(y to x).minOf { this.heightAt(it) }
}
private fun neighbouringPoints(point: Pair<Int, Int>): List<Pair<Int, Int>> {
val (originalY, originalX) = point
val verticalNeighbours = listOfNotNull(if (originalY == 0) null else originalY - 1, if (originalY < maxY) originalY + 1 else null)
val horizontalNeighbours = listOfNotNull(if (originalX == 0) null else originalX - 1, if (originalX < maxX) originalX + 1 else null)
return verticalNeighbours.map { y -> y to originalX } + horizontalNeighbours.map { x -> originalY to x }
}
}
private fun Int.toRiskLevel() = this.inc()
private fun List<Collection<Any>>.productOf(transform: (Collection<Any>) -> Int) = this.map(transform).reduce { product, size -> product * size }
} | 0 | Kotlin | 0 | 0 | f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9 | 2,242 | advent-2021 | Creative Commons Zero v1.0 Universal |
src/Day01.kt | dyomin-ea | 572,996,238 | false | {"Kotlin": 21309} | fun main() {
fun List<String>.sumsBetweenEmpty(): MutableList<Int> =
fold(mutableListOf(0)) { acc, s ->
acc += if (s.isEmpty()) {
0
} else {
acc.pop() + s.toInt()
}
acc
}
fun part1(input: List<String>): Int =
input.sumsBetweenEmpty()
.max()
fun part2(input: List<String>): Int =
input.sumsBetweenEmpty()
.sortedDescending()
.take(3)
.sum()
fun <T : Comparable<T>> List<T>.getTop(count: Int): List<T> {
tailrec fun <T : Comparable<T>> List<T>.getTopRec(found: List<T>, count: Int, rest: List<T>): List<T> {
val point: T by lazy { random() }
val pair: Pair<List<T>, List<T>> by lazy { partition { it > point } }
val right by lazy { pair.first }
val left by lazy { pair.second }
return when (count) {
0 -> found
1 -> found + max()
right.size -> found + right
else -> {
val receiver: List<T>
val f: List<T>
val c: Int
val r: List<T>
when {
right.size > count -> {
receiver = right
f = found
c = count
r = emptyList()
}
this.size > count -> {
receiver = left
f = found + right
c = count - right.size
r = emptyList()
}
else -> {
receiver = left + rest
f = found + right
c = count - right.size
r = emptyList()
}
}
receiver.getTopRec(f, c, r)
}
}
}
return getTopRec(emptyList(), count, emptyList())
}
fun part1Rec(input: List<String>): Int =
input.sumsBetweenEmpty()
.getTop(1)
.sum()
fun part2Rec(input: List<String>): Int =
input.sumsBetweenEmpty()
.getTop(3)
.sum()
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part1Rec(testInput) == 24000)
check(part2(testInput) == 45000)
check(part2Rec(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part1Rec(input))
println(part2(input))
println(part2Rec(input))
}
| 0 | Kotlin | 0 | 0 | 8aaf3f063ce432207dee5f4ad4e597030cfded6d | 1,998 | advent-of-code-2022 | Apache License 2.0 |
y2015/src/main/kotlin/adventofcode/y2015/Day13.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2015
import adventofcode.io.AdventSolution
import adventofcode.util.collections.permutations
object Day13 : AdventSolution(2015, 13, "Knights of the Dinner Table") {
override fun solvePartOne(input: String) = tryAllRoutes(input).maxOrNull().toString()
override fun solvePartTwo(input: String) = tryAllRoutes2(input).maxOrNull().toString()
private fun tryAllRoutes(input: String): Sequence<Int> {
val distanceMap = parseInput(input)
val locations = distanceMap.keys.flatMap { listOf(it.first, it.second) }.toSet().toList()
val distances = buildDistanceMatrix(locations, distanceMap)
return routes(locations, distances)
}
private fun tryAllRoutes2(input: String): Sequence<Int> {
val distanceMap = parseInput(input)
val locations = distanceMap.keys.flatMap { listOf(it.first, it.second) }.toSet().toList() + "me"
val distances = buildDistanceMatrix(locations, distanceMap)
return routes(locations, distances)
}
private fun buildDistanceMatrix(locations: List<String>, distanceMap: Map<Pair<String, String>, Int>) =
locations.map { start ->
locations.map { end ->
distanceMap[start to end]
?: 0
}
}
private fun routes(locations: List<String>, distanceTable: List<List<Int>>) =
(1 until locations.size).permutations()
.map { listOf(0) + it + 0 }
.map { it.zipWithNext { a, b -> distanceTable[a][b] + distanceTable[b][a] }.sum() }
private fun parseInput(distances: String) = distances.lineSequence()
.mapNotNull { Regex("(\\w+) would (\\w+) (\\d+) happiness units by sitting next to (\\w+).").matchEntire(it) }
.map { it.destructured }
.map { (start, sign, amount, end) ->
val distance = if (sign == "gain") amount.toInt() else -amount.toInt()
start to end to distance
}
.toMap()
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,985 | advent-of-code | MIT License |
src/Day08.kt | freszu | 573,122,040 | false | {"Kotlin": 32507} | enum class Direction { LEFT, TOP, RIGHT, BOTTOM }
fun <T> Sequence<T>.takeWhileInclusive(predicate: (T) -> Boolean): Sequence<T> {
var shouldContinue = true
return takeWhile {
val result = shouldContinue
shouldContinue = predicate(it)
result
}
}
fun <T> Matrix<T>.walkToEdge(fromX: Int, fromY: Int, direction: Direction): Sequence<T> = sequence {
var offset = 1
while (true) {
val inLine = when (direction) {
Direction.LEFT -> this@walkToEdge.getOrNull(fromX - offset, fromY)
Direction.TOP -> this@walkToEdge.getOrNull(fromX, fromY - offset)
Direction.RIGHT -> this@walkToEdge.getOrNull(fromX + offset, fromY)
Direction.BOTTOM -> this@walkToEdge.getOrNull(fromX, fromY + offset)
}
if (inLine == null) break else yield(inLine)
offset++
}
}
fun main() {
fun createHeightMap(input: List<String>) = input.map { line -> line.map(Char::digitToInt) }
fun part1(matrix: Matrix<Int>) = matrix.map2dIndexed { x, y, treeHouseHeight ->
Direction.values()
.map { dir -> matrix.walkToEdge(x, y, dir).all { treeHeight -> treeHeight < treeHouseHeight } }
.any(true::equals)
}
.flatten()
.count(true::equals)
fun part2(matrix: Matrix<Int>) = matrix.map2dIndexed { x, y, treeHouseHeight ->
Direction.values()
.map { dir ->
matrix.walkToEdge(x, y, dir).takeWhileInclusive { treeHeight -> treeHouseHeight > treeHeight }.count()
}
.reduce(Int::times)
}
.flatten()
.max()
val testInput = createHeightMap(readInput("Day08_test"))
val input = createHeightMap(readInput("Day08"))
check(part1(testInput) == 21)
println(part1(input))
check(part2(testInput) == 8)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2f50262ce2dc5024c6da5e470c0214c584992ddb | 1,864 | aoc2022 | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2022/day12/HillClimbingAlgorithm.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day12
import com.barneyb.aoc.util.Slice
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toSlice
import com.barneyb.util.Dir
import com.barneyb.util.HashSet
import com.barneyb.util.Queue
import com.barneyb.util.Vec2
fun main() {
Solver.benchmark(
::parse,
::shortestPath, // 352
::shortestPathFromBestStart, // 345
)
}
private typealias Elevation = Char
private typealias Map = List<Slice>
private val Map.height
get() = this.size
private val Map.width
get() = this[0].length
private fun Map.elevationAt(p: Vec2): Elevation =
if (contains(p))
when (val c = this[p.y][p.x]) {
'S' -> 'a'
'E' -> 'z'
else -> c
}
else
throw IllegalArgumentException("$p isn't a valid position")
private fun Map.contains(p: Vec2) =
p.x in 0 until width && p.y in 0 until height
private fun Map.findMarker(marker: Char): Vec2 {
for ((y, l) in withIndex()) {
val x = l.indexOf(marker)
if (x >= 0) return Vec2(x, y)
}
throw IllegalArgumentException("No position with marker '$marker' found")
}
private fun Map.stepsUntil(
start: Vec2,
testStep: (Elevation, Elevation) -> Boolean,
testGoal: (Vec2) -> Boolean
): Int {
val visited = HashSet<Vec2>()
val queue = Queue<Step>()
queue.enqueue(Step(start, elevationAt(start), 0))
while (queue.isNotEmpty()) {
val (pos, elev, steps) = queue.dequeue()
if (visited.contains(pos)) {
continue
}
if (testGoal(pos)) return steps
visited.add(pos)
for (d in Dir.values()) {
val next = pos.move(d)
if (!contains(next)) continue
val e = elevationAt(next)
if (testStep(elev, e)) {
queue.enqueue(Step(next, e, steps + 1))
}
}
}
throw IllegalArgumentException("No path from $start found?!")
}
private data class Step(val pos: Vec2, val elev: Elevation, val steps: Int)
internal fun parse(input: String) =
input.toSlice().trim().lines()
internal fun shortestPath(map: Map) =
map.findMarker('E').let { goal ->
map.stepsUntil(
map.findMarker('S'),
{ curr, next -> next - curr <= 1 },
goal::equals,
)
}
fun shortestPathFromBestStart(map: Map): Int {
return map.stepsUntil(
map.findMarker('E'),
{ curr, next -> curr - next <= 1 },
{ pos -> map.elevationAt(pos) == 'a' },
)
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 2,549 | aoc-2022 | MIT License |
problems/knights-on-chessboard/knight.kt | mre | 14,571,395 | false | {"Python": 149850, "JavaScript": 52163, "Rust": 22731, "Java": 18047, "Kotlin": 17919, "C++": 16563, "CoffeeScript": 16079, "PHP": 14313, "C#": 14295, "Shell": 11341, "Go": 8067, "Ruby": 5883, "C": 4745, "F#": 4418, "Swift": 1811, "Haskell": 1585, "TypeScript": 1405, "Scala": 1394, "Dart": 1025, "LOLCODE": 647, "Julia": 559, "Makefile": 521} | import java.io.File
import java.util.stream.Collectors
fun main() {
KnightProblem().solve()
}
data class BoardField(val char: Char, val index: Pair<Int, Int>)
internal class KnightProblem {
companion object {
val board = File("problems/knights-on-chessboard/board.txt").readBoard()
}
data class Knight(var currentField: BoardField, var visited: List<BoardField> = mutableListOf()) {
fun clone(): Knight {
return Knight(currentField, visited.stream().collect(Collectors.toList()))
}
fun move(field: BoardField) {
visited += field
currentField = field
}
fun possibleMoves(): List<BoardField> {
return listOf(-1, 1, -1, 1, -2, 2, -2, 2)
.zip(listOf(-2, -2, 2, 2, -1, -1, 1, 1))
.map {
// calculate new pos relative to current pos
it.first + currentField.index.first to it.second + currentField.index.second
}.mapNotNull {
it.asBoardField()
}.filter(this::isValid)
}
fun isValid(field: BoardField): Boolean {
val vowels = "AEIOU"
if(field.char == '_') return false
if(field.index.first < 0 || field.index.second < 0) return false
if(field.index.first > 4 || field.index.second > 4) return false
if(visited.contains(field)) return false
if(vowels.contains(field.char)) {
val vowelCount = visited.count { vowels.contains(it.char) }
if((vowelCount + 1) > 2) return false
}
return true
}
fun Pair<Int, Int>.asBoardField(): BoardField? {
return board.firstOrNull {
it.index.first == first && it.index.second == second
}
}
}
fun solve() {
board.filter { it.char != '_' }.forEach {
calculateNextStep(Knight(it))
}
}
fun calculateNextStep(knight: Knight) {
println(knight.visited.map { it.char })
knight.possibleMoves().forEach {
val cloned = knight.clone()
cloned.move(it)
calculateNextStep(cloned)
}
}
}
fun File.readBoard(): MutableList<BoardField> {
val result = mutableListOf<BoardField>()
this.reader().readLines().forEachIndexed { y, line ->
line.split("|").forEachIndexed { x, char ->
result.add(BoardField(char[0], x to y)) // (x, y)
}
}
return result
}
| 8 | Python | 413 | 1,636 | e879e0949a24da5ebc80e9319683baabf8bb0a37 | 2,565 | the-coding-interview | MIT License |
src/main/kotlin/graph/core/ShortestPathWeighted.kt | yx-z | 106,589,674 | false | null | package graph.core
import util.INF
import util.Tuple2
import util.min
import util.tu
import java.util.*
import kotlin.collections.HashMap
// given a weighted graph, a starting vertex s
// find the shortest path with min weight from s to all other vertices
// assume the weights are all positive ints
fun <V> WeightedGraph<V, Int>.dijkstra(s: Vertex<V>, checkIdentity: Boolean = true)
: Tuple2<Map<Vertex<V>, Int>, Map<Vertex<V>, Vertex<V>?>> {
val dist = HashMap<Vertex<V>, Int>()
val parent = HashMap<Vertex<V>, Vertex<V>?>()
vertices.forEach {
dist[it] = INF
parent[it] = null
}
dist[s] = 0
parent[s] = s
val minHeap = PriorityQueue<Vertex<V>>(Comparator { u, v -> dist[u]!! - dist[v]!! })
minHeap.add(s)
while (minHeap.isNotEmpty()) {
val v = minHeap.remove()
getEdgesOf(v, checkIdentity).forEach { (start, end, isDirected, weight) ->
val u = if (isDirected || start == v) end else start
if (dist[v]!! + weight!! < dist[u]!!) {
dist[u] = dist[v]!! + weight
parent[u] = v
minHeap.add(u)
}
}
}
return dist tu parent
}
// time complexity: O(E log V)
// if we use a queue instead of minHeap in the above classic Dijkstra's Algorithm,
// it will be called Shimbel's or Bellman-Ford's Algorithm
// but we can also do a DP version of Shimbel's i.e. Bellman-Ford's algorithm
fun <V> WeightedGraph<V, Int>.bellmanFordDp(s: Vertex<V>,
t: Vertex<V>,
checkIdentity: Boolean = true): Int {
val V = vertices.size
// dp(i, v): shortest distance from s to v consisting of at most i edges
// memoization structure: array of maps dp[1 until V, vertices ] : dp[i, v] = dp(i, v)
val dp = Array(V) { HashMap<Vertex<V>, Int>() }
// base case:
// dp(0, s) = 0
// dp(0, v) = inf for all v != s
vertices.forEach { vertex ->
dp[0][vertex] = INF
}
dp[0][s] = 0
// space complexity: O(V^2)
// recursive case:
// dp(i, v) = min { dp(i - 1, v), min { dp(i - 1, u) + w(u -> v) : u -> v in E } }
// dependency: dp(i, v) depends on dp(i - 1, u)
// evaluation order: outer loop for i from 1 until V
for (i in 1 until V) {
// inner loop for every vertex v
vertices.forEach { v ->
dp[i][v] = dp[i - 1][v]!!
weightedEdges
.filter { (s, e, isDirected) ->
if (isDirected) {
if (checkIdentity) e === v else e == v
} else {
if (checkIdentity) s === v || e === v else s == v || e == v
}
} // get all edges to v
.forEach { (u, _, _, d) ->
dp[i][v] = min(dp[i][v]!!, dp[i - 1][u]!! + d!!)
}
}
}
// time complexity: O(VE)
// we want dp(V - 1, t)
return dp[V - 1][t]!!
}
// and we can do even better as follows
// (not faster but more succinct)
fun <V> WeightedGraph<V, Int>.bellmanFord(s: Vertex<V>, t: Vertex<V>): Int {
val V = vertices.size
val dist = HashMap<Vertex<V>, Int>()
vertices.forEach { dist[it] = INF }
dist[s] = 0
for (i in 1 until V) {
weightedEdges.forEach { (u, v, isDirected, d) ->
if (dist[v]!! > dist[u]!! + d!!) { // if edge is tense
dist[v] = dist[u]!! + d // relax the edge
}
if (!isDirected) {
// if the graph is undirected
// relax the other edge if necessary
if (dist[u]!! > dist[v]!! + d) {
dist[u] = dist[v]!! + d
}
}
}
}
return dist[t]!!
}
// note that i have also implemented an A* (A Star) algorithm in src/mat/ShortestPath.kt
// it is a generalized dijkstra's algorithm for the single source shortest path
// problem with heuristic functions for better performance
// but it might not ALWAYS find the shortest path depending on the specific
// heuristic function being used
// since by convention, A* is used in a grid/table/bitmap/2d arr, with no explicit
// graph structures (although it can be easily turned into so), i choose not to
// put it under this graph package which mainly uses traditional G = (V, E) graph
// representation/implementation here
fun main(args: Array<String>) {
val vertices = (0..4).map { Vertex('a' + it) }
val edges = setOf(
WeightedEdge(vertices[0], vertices[1], true, 10),
WeightedEdge(vertices[0], vertices[2], true, 2),
WeightedEdge(vertices[0], vertices[4], true, 100),
WeightedEdge(vertices[1], vertices[3], true, 2),
WeightedEdge(vertices[2], vertices[4], true, 10),
WeightedEdge(vertices[3], vertices[4], true, 1))
val graph = WeightedGraph(vertices, edges)
println(graph.dijkstra(vertices[0]).first[vertices[4]])
println(graph.bellmanFordDp(vertices[0], vertices[4]))
println(graph.bellmanFord(vertices[0], vertices[4]))
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 4,566 | AlgoKt | MIT License |
src/main/kotlin/dev/bogwalk/batch9/Problem99.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch9
import kotlin.math.log10
import kotlin.math.pow
/**
* Problem 99: Largest Exponential
*
* https://projecteuler.net/problem=99
*
* Goal: Compare 2 base (B) /exponent (E) pairs whose numbers contain a very large amount of
* digits, then use this comparison to either find the Kth smallest exponential or the greatest
* value exponential from a list of N pairs.
*
* Constraints: 1 <= N <= 1e5, 1 <= K <= N, 1 <= B <= 1e9, 1 <= E <= 1e9
*
* e.g.: N = 3, K = 2, list -> [4 7, 3 7, 2 11]
* sorted -> [2 11, 3 7, 4 7]
* output = 3 7
*/
class LargestExponential {
data class Exponential(
val base: Int, val exponent: Int, val line: Int
) : Comparable<Exponential> {
/**
* Solution avoids using large numbers for comparison by reducing both values using the
* root of the object with the smaller exponent, based on the following:
*
* (a^x)^(1/x) == x_root(a^x) == a
* then the object with the larger exponent becomes:
* (b^y)^(1/x) == b^(y/x)
*
* Based on the large values of the exponents, this provides a more manageable comparison.
*
* N.B. An alternative calculates the gcd of the exponents and depends on the following:
*
* a^(x * y) == (a^x)^y
*
* e.g. 2^350 and 5^150 == (2^7)^50 and (5^3)^50; 2^7 (128) > 5^3 (125), so 2^350 has the
* greater value. This only works if the gcd is assured to be greater than 1.
*/
override operator fun compareTo(other: Exponential): Int {
val smallerExp = minOf(this.exponent, other.exponent)
val reducedExp: Double
val reducedA: Double
val reducedB: Double
if (this.exponent == smallerExp) {
reducedA = this.base.toDouble()
reducedExp = other.exponent / smallerExp.toDouble()
reducedB = other.base.toDouble().pow(reducedExp)
} else {
reducedB = other.base.toDouble()
reducedExp = this.exponent / smallerExp.toDouble()
reducedA = this.base.toDouble().pow(reducedExp)
}
return if (reducedA > reducedB) 1 else -1
}
}
/**
* Project Euler specific implementation that requires the line number of the base/exponent
* pair that has the greatest numerical value, from a 1000-line test file.
*/
fun largestExponential(inputs: List<String>): Triple<Int, Int, Int> {
val largest = inputs.mapIndexed { i, str ->
val nums = str.split(",")
Exponential(nums[0].toInt(), nums[1].toInt(), i + 1)
}.reduce { acc, triple ->
if (acc > triple) acc else triple
}
return Triple(largest.base, largest.exponent, largest.line)
}
/**
* HackerRank specific implementation that requires the [k]th smallest exponential from a
* list of base/exponent pairs.
*
* Data class Exponential's compareTo() is used to sort the input values, then the [k-1]th value
* is accessed.
*
* SPEED (WORSE) 28.13ms for PE test list
*/
fun kSmallestExponential(inputs: List<String>, k: Int): Pair<Int, Int> {
val exponentials = inputs.mapIndexed { i, str ->
val nums = str.split(" ")
Exponential(nums[0].toInt(), nums[1].toInt(), i + 1)
}
val kSmallest = exponentials.sortedBy { it }[k - 1]
return kSmallest.base to kSmallest.exponent
}
/**
* Solution optimised by not relying on data class instances and instead sorting
* base/exponent pairs solely based on their logarithm calculation, based on the following:
*
* a^x > b^y -> log_10(a^x) > log_10(b^y) -> x * log_10(a) > y * log_10(b)
*
* SPEED (BETTER) 12.83ms for PE test list
*/
fun kSmallestExponentialAlt(inputs: List<String>, k: Int): Pair<Int, Int> {
val exponentials = inputs.map { str ->
val (base, exponent) = str.split(" ").map(String::toInt)
Triple(base, exponent, exponent * log10(base.toDouble()))
}
val kSmallest = exponentials.sortedBy { it.third }[k - 1]
return kSmallest.first to kSmallest.second
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 4,326 | project-euler-kotlin | MIT License |
src/main/kotlin/cc/stevenyin/leetcode/_0075_SortColors.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.leetcode
/**
* Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
* We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
* You must solve this problem without using the library's sort function.
*
*
* Example 1:
* Input: nums = [2,0,2,1,1,0]
* Output: [0,0,1,1,2,2]
*
* Example 2:
* Input: nums = [2,0,1]
* Output: [0,1,2]
*
* Constraints:
*
* n == nums.length
* 1 <= n <= 300
* nums[i] is either 0, 1, or 2.
*
*
* Follow up: Could you come up with a one-pass algorithm using only constant extra space?
*/
class _0075_SortColors {
fun sortColors(nums: IntArray): Unit {
var l = -1
var r = nums.size
var idx = 0
while (idx < r) {
when {
nums[idx] == 0 -> swap(nums, idx++, ++l)
nums[idx] == 2 -> swap(nums, idx, --r)
else -> idx ++
}
}
}
private fun swap(nums: IntArray, idx1: Int, idx2: Int) {
val temp = nums[idx1]
nums[idx1] = nums[idx2]
nums[idx2] = temp
}
}
fun main() {
val solution = _0075_SortColors()
val case1 = intArrayOf(1,2,0)
val expectedResult = intArrayOf(0,1,2)
solution.sortColors(case1)
expectedResult.forEachIndexed { index, i ->
assert(case1[index] == i)
}
}
/**
* 为什么要学习O(n^2)的排序算法?
* 1. 基础,易于入门和理解
* 2. 编码简单,易于实现,是一些简单场景的首选
* 3. 在一些特殊的情况下,简单的排序算法更有效
* 4. 简单的排序算法思想衍生出复杂的排序算法
* 5. 有可能可以作为子过程,改进更复杂的排序算法
*/
| 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 1,842 | kotlin-demo-code | MIT License |
src/year2021/04/Day04.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2021.`04`
import readInput
import transpose
private data class Bingos<T>(
val items: List<List<T>>
)
private data class Marked<T>(
val item: T,
var marked: Boolean
)
fun main() {
fun extractListOfNumbers(input: List<String>): List<Int> {
val filteredItems = input.filter { it.isNotBlank() }
val numbers = filteredItems.first()
.split(",")
return numbers.map { it.toInt() }
}
fun extractBingoList(input: List<String>): List<Bingos<Marked<Int>>> {
val filteredItems = input.filter { it.isNotBlank() }
val bingos = filteredItems.drop(1)
.windowed(5, 5)
.map { bingo ->
bingo.map { line ->
line.split(" ")
.filter { it.isNotBlank() }
.map {
Marked(
item = it.toInt(),
marked = false
)
}
}
}
return bingos.map { Bingos(it) }
}
fun Bingos<Marked<Int>>.playRound(number: Int) {
items.forEach { line ->
line.forEach {
if (it.item == number) it.marked = true
}
}
}
fun Bingos<Marked<Int>>.isWinner(): Boolean {
val horizontal = items.any { line -> line.all { it.marked } }
val vertical = transpose(items).any { line -> line.all { it.marked } }
return horizontal || vertical
}
fun Bingos<Marked<Int>>.calculateResult(numberWon: Int): Int {
val sum = this.items.sumOf { line ->
line.sumOf { markedItem ->
markedItem.item.takeIf { !markedItem.marked } ?: 0
}
}
return sum * numberWon
}
fun part1(input: List<String>): Int {
val numbers = extractListOfNumbers(input)
val bingoList = extractBingoList(input)
val iterator = numbers.iterator()
var hasWinner = false
var number = 0
while (!hasWinner) {
number = iterator.next()
bingoList.forEach { it.playRound(number) }
hasWinner = bingoList.any { it.isWinner() }
}
val winner = bingoList.find { it.isWinner() } ?: error("No items found")
return winner.calculateResult(number)
}
fun part2(input: List<String>): Int {
val numbers = extractListOfNumbers(input)
var bingoList = extractBingoList(input)
val iterator = numbers.iterator()
var number = 0
// Run rounds and filter-out winners
while (bingoList.size != 1) {
number = iterator.next()
bingoList.forEach { it.playRound(number) }
val winners = bingoList.filter { it.isWinner() }.toSet()
bingoList = bingoList - winners
}
// Run rounds until last bingo is not won.
val lastBingo = bingoList.first()
while (!lastBingo.isWinner()) {
number = iterator.next()
lastBingo.playRound(number)
}
return lastBingo.calculateResult(number)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val part1Test = part1(testInput)
check(part1Test == 4512)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 3,452 | KotlinAdventOfCode | Apache License 2.0 |
src/Day02.kt | gomercin | 572,911,270 | false | {"Kotlin": 25313} | import java.util.*
/*
* searches I needed to make:
* kotlin enum
* kotlin switch
* kotlin dictionary
* kotlin enum ordinal
* kotlin init array
* kotlin init list
* kotlin permutation
* */
enum class Move {
ROCK, PAPER, SCISSOR
}
enum class Winner {
OPPONENT, DRAW, PLAYER
}
fun main() {
val opponentMoveMap = mapOf("A" to Move.ROCK, "B" to Move.PAPER, "C" to Move.SCISSOR)
// this mapping is a bit tricky to explain; as I assumed they will later ask for a different
// mapping then the one given in part 1, I just mapped the x-y-z to array indices
// and the array will have a permutation of "Move"s
// let's see if "premature optimization is the root of all evil" :)
// Part 2 update: I was wrong indeed :)
val playerMoveMap = mapOf("X" to 0, "Y" to 1, "Z" to 2)
val moveScoreMap = mapOf(Move.ROCK to 1, Move.PAPER to 2, Move.SCISSOR to 3)
val gameScoreMap = mapOf(Winner.OPPONENT to 0, Winner.DRAW to 3, Winner.PLAYER to 6)
fun getResult(opponentMove: Move, playerMove: Move): Winner {
if (opponentMove == playerMove) {
return Winner.DRAW
}
return when(opponentMove) {
Move.ROCK -> if (playerMove == Move.PAPER) Winner.PLAYER else Winner.OPPONENT
Move.PAPER -> if (playerMove == Move.SCISSOR) Winner.PLAYER else Winner.OPPONENT
Move.SCISSOR -> if (playerMove == Move.ROCK) Winner.PLAYER else Winner.OPPONENT
}
}
fun getScore(opponentMove:Move, playerMove:Move): Int {
val result = getResult(opponentMove, playerMove)
return gameScoreMap[result]!! + moveScoreMap[playerMove]!!
}
fun getTotalScore(input: List<String>, playerMoveList: List<Move>): Int {
var totalScore = 0
for (line in input) {
val moves = line.split(" ")
totalScore += getScore(opponentMoveMap[moves[0]]!!, playerMoveList[playerMoveMap[moves[1]]!!])
}
return totalScore
}
fun part1(input: List<String>): Int {
// heh, second part will probably say something like
// your assumption about X,Y,Z was wrong, what is the best combination for highest result
// so let's get ready for that by making it simple to have variations of player move mapping
// later, we can create a list of these lists and loop over them
val playerMoveList = listOf(Move.ROCK, Move.PAPER, Move.SCISSOR)
return getTotalScore(input, playerMoveList)
}
// from https://medium.com/@jcamilorada/recursive-permutations-calculation-algorithm-in-kotlin-86233a0a2ee1
fun permutationsRecursive(input: List<Move>, index: Int, answers: MutableList<List<Move>>) {
// THIS TURNED OUT TO BE A PREMATURE OPTIMIZATION, SEE OTHER COMMENTS :)
if (index == input.lastIndex) answers.add(input.toList())
for (i in index .. input.lastIndex) {
Collections.swap(input, index, i)
permutationsRecursive(input, index + 1, answers)
Collections.swap(input, i, index)
}
}
fun permutations(input: List<Move>): List<List<Move>> {
// THIS TURNED OUT TO BE A PREMATURE OPTIMIZATION, SEE OTHER COMMENTS :)
val solutions = mutableListOf<List<Move>>()
permutationsRecursive(input, 0, solutions)
return solutions
}
fun part2(input: List<String>): Int {
var totalScore = 0
for (line in input) {
val moves = line.split(" ")
val expectedResult = when (moves[1]) {
"X" -> Winner.OPPONENT
"Y" -> Winner.DRAW
"Z" -> Winner.PLAYER
else -> {Winner.DRAW} // shouldn't happen
}
val opponentMove = opponentMoveMap[moves[0]]!!
var playerMove = opponentMove
if (expectedResult != Winner.DRAW) {
playerMove = when(opponentMove) {
Move.ROCK -> if (expectedResult == Winner.PLAYER) Move.PAPER else Move.SCISSOR
Move.PAPER -> if (expectedResult == Winner.PLAYER) Move.SCISSOR else Move.ROCK
Move.SCISSOR -> if (expectedResult == Winner.PLAYER) Move.ROCK else Move.PAPER
}
}
totalScore += getScore(opponentMove, playerMove)
}
return totalScore
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 30f75c4103ab9e971c7c668f03f279f96dbd72ab | 4,430 | adventofcode-2022 | Apache License 2.0 |
src/Day02.kt | hottendo | 572,708,982 | false | {"Kotlin": 41152} |
enum class Score (val score: Int) {
WIN(6),
LOSS(0),
DRAW(3)
}
fun main() {
fun part1(input: List<String>): Int {
val winningMoves = mapOf<String, Int>("C X" to 1, "B Z" to 3, "A Y" to 2)
val loosingMoves = mapOf<String, Int>("B X" to 1, "A Z" to 3, "C Y" to 2)
val drawMoves = mapOf<String, Int>("A X" to 1, "C Z" to 3, "B Y" to 2)
var turn: String
var score = 0
for (item in input) {
turn = item.trim()
// determine outcome and assign score
when(turn) {
in winningMoves -> score += Score.WIN.score + winningMoves.get(turn)!!
in loosingMoves -> score += Score.LOSS.score + loosingMoves.get(turn)!!
in drawMoves -> score += Score.DRAW.score + drawMoves.get(turn)!!
else -> println("ERROR: Score for match $turn could not be determined.")
}
}
return score
}
fun part2(input: List<String>): Int {
fun getExpectedMove(turn: String): String {
/*
takes in an input pair of moves and determines the resulting turn
according to the rules for part2 of this puzzle.
*/
val winningMove = mapOf("C" to "X", "B" to "Z", "A" to "Y")
val loosingMove = mapOf("B" to "X", "A" to "Z", "C" to "Y")
val drawMove = mapOf("C" to "Z", "B" to "Y", "A" to "X")
var newTurn = ""
val elvesMove: String = turn.split(' ').first()
val expectedTurn: String = turn.split(' ').last()
when (expectedTurn) {
"Y" -> newTurn = elvesMove + " " + drawMove[elvesMove]
"X" -> newTurn = elvesMove + " " + loosingMove[elvesMove]
"Z" -> newTurn = elvesMove + " " + winningMove[elvesMove]
}
return newTurn
}
val winningMoves = mapOf<String, Int>("C X" to 1, "B Z" to 3, "A Y" to 2)
val loosingMoves = mapOf<String, Int>("B X" to 1, "A Z" to 3, "C Y" to 2)
val drawMoves = mapOf<String, Int>("A X" to 1, "C Z" to 3, "B Y" to 2)
var turn: String
var score = 0
var newTurn: String
for (item in input) {
turn = item.trim()
// turn the expected move into a proper move
newTurn = getExpectedMove(turn)
// determine outcome and assign score
when (newTurn) {
in winningMoves -> score += Score.WIN.score + winningMoves.get(newTurn)!!
in loosingMoves -> score += Score.LOSS.score + loosingMoves.get(newTurn)!!
in drawMoves -> score += Score.DRAW.score + drawMoves.get(newTurn)!!
else -> println("ERROR: Score for match $newTurn could not be determined.")
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println(part1(testInput))
println(part2(testInput))
// check(part1(testInput) == 1)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a166014be8bf379dcb4012e1904e25610617c550 | 3,170 | advent-of-code-2022 | Apache License 2.0 |
src/day21/Day21.kt | bartoszm | 572,719,007 | false | {"Kotlin": 39186} | package day21
import readInput
import toPair
fun main() {
println(solve1(parse(readInput("day21/test"))))
println(solve1(parse(readInput("day21/input"))))
println(solve2(parse(readInput("day21/test"))))
println(solve2(parse(readInput("day21/input"))))
}
fun String.isIdentifier() = !this[0].isDigit() && this.length > 1
fun convert(exprs: Map<String, List<String>>): Map<String, Operation> {
val operations = hashMapOf<String, Operation>()
fun oper(key: String, tokens : List<String>): Operation {
var o = operations[key]
if(o == null) {
o = if(tokens.size == 1) {
if(tokens[0].isIdentifier()) {
oper(tokens[0], exprs[tokens[0]]!!)
} else {
Const(tokens[0].toLong())
}
}
else {
val(lT, opr, rT) = tokens
val left = oper(lT, exprs[lT]!!)
val right = oper(rT, exprs[rT]!!)
when(opr) {
"+" -> Function(left, right) {a,b -> a + b}
"-" -> Function(left, right) {a,b -> a - b}
"*" -> Function(left, right) {a,b -> a * b}
"/" -> Function(left, right) {a,b -> a / b}
else -> error("Operation $opr is not supported")
}
}
operations[key] = o
}
return o
}
exprs.forEach { (t, u) -> oper(t,u) }
return operations
}
fun solve1(exprs: Map<String, List<String>>): Long {
val operations = convert(exprs)
return operations["root"]?.invoke()!!
}
typealias Expr = Pair<String, List<String>>
fun unresolved(exprs: Map<String, List<String>>) = exprs.values.asSequence()
.flatMap { it.filter { e -> e.isIdentifier() } }
.filter { !exprs.containsKey(it) }
.toSet()
fun transform(from: String, exprs: Map<String, List<String>>) : Map<String, List<String>> {
fun String.isFirst(expr: List<String>) = this == expr[0]
fun map(what: String, expr: Expr): Expr {
val (lhs, old) = expr
require(old.size == 3)
if(lhs == "root") {
return what to listOf(if(what.isFirst(old)) old[2] else old[0])
}
return what to when(old[1]) {
"*" -> if(what.isFirst(old)) listOf(lhs, "/", old[2]) else listOf(lhs, "/", old[0])
"+" -> if(what.isFirst(old)) listOf(lhs, "-", old[2]) else listOf(lhs, "-", old[0])
"/" -> if(what.isFirst(old)) listOf(lhs, "*", old[2]) else listOf(old[0], "/", lhs)
"-" -> if(what.isFirst(old)) listOf(lhs, "+", old[2]) else listOf(old[0], "-", lhs)
else -> error("not supported operator ${old[1]}")
}
}
fun find(name: String) = exprs.asSequence()
.map { it.toPair() }
.first { (_, v) -> v.contains(name) }
fun pathToRoot() : List<Pair<String, Expr>> {
var e = from
return sequence {
while (e != "root") {
val found = find(e)
yield(e to found)
e = found.first
}
}.toList()
}
val trans = hashMapOf<String, List<String>>()
val modified = pathToRoot().map { (what, expr) -> map(what, expr) }
modified.forEach { (k, v) -> trans[k] = v }
var unresolved = unresolved(trans)
while (unresolved.isNotEmpty()) {
unresolved
.map { u -> u to exprs[u]!! }
.forEach { (k,v) -> trans[k] = v }
unresolved = unresolved(trans)
}
return trans
}
fun solve2(exprs: Map<String, List<String>>): Long {
val operations = convert(transform("humn", exprs))
return operations["humn"]?.invoke()!!
}
sealed interface Operation {
operator fun invoke() :Long
}
class Function(val a: Operation, val b: Operation, val f: (Long,Long) -> Long) : Operation {
override fun invoke() = f.invoke(a(), b())
}
class Const(val value: Long) : Operation {
override fun invoke() = value
}
class Subst(val o: Operation) : Operation by o
fun parse(line: String) = line.split(":").map { it.trim() }.toPair()
.let { (k,v) -> k to v.split(" ") }
fun parse(input: List<String>)= input.associate { parse(it) }
| 0 | Kotlin | 0 | 0 | f1ac6838de23beb71a5636976d6c157a5be344ac | 4,247 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day18.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | import kotlin.math.absoluteValue
fun main() {
val input = readFileAsList("Day18")
println(Day18.part1(input))
println(Day18.part2(input))
}
object Day18 {
fun part1(input: List<String>): Long {
val vectors = parseLava(input)
var uncoveredSidesTotal = 0
for ((index, vector) in vectors.withIndex()) {
var uncoveredSides = 6
for (vector2 in vectors.filterIndexed { i, _ -> i != index }) {
val (xDiff, yDiff, zDiff) = vector diffAbs vector2
val isXNeighbor = xDiff == 0 && yDiff == 0 && zDiff.absoluteValue == 1
val isYNeighbor = xDiff == 0 && zDiff == 0 && yDiff.absoluteValue == 1
val isZNeighbor = yDiff == 0 && zDiff == 0 && xDiff.absoluteValue == 1
if (isXNeighbor || isYNeighbor || isZNeighbor) {
uncoveredSides--
}
}
uncoveredSidesTotal += uncoveredSides
}
return uncoveredSidesTotal.toLong()
}
fun part2(input: List<String>): Long {
val vectors = parseLava(input)
val xRange = rangeOf(vectors) { it.x }
val yRange = rangeOf(vectors) { it.y }
val zRange = rangeOf(vectors) { it.z }
val queue = ArrayDeque<Vector3d>().apply {
add(Vector3d(xRange.first, yRange.first, zRange.first))
}
val seen = mutableSetOf<Vector3d>()
var sidesFound = 0
queue.forEach { lookNext ->
if (lookNext !in seen) {
lookNext.neighbours()
.filter { it !in seen && it.x in xRange && it.y in yRange && it.z in zRange }
.forEach { neighbor ->
seen += lookNext
if (neighbor in vectors) sidesFound++
else queue.add(neighbor)
}
}
}
return sidesFound.toLong()
}
private fun rangeOf(lava: Set<Vector3d>, function: (Vector3d) -> Int): IntRange =
lava.minOf(function) - 1..lava.maxOf(function) + 1
private fun parseLava(input: List<String>): Set<Vector3d> {
val vectors = input.map {
val (x, y, z) = it.split(",")
.map { numeric -> numeric.toInt() }
Vector3d(x, y, z)
}
.toSet()
return vectors
}
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 2,375 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day9.kt | vw-anton | 574,945,231 | false | {"Kotlin": 33295} | import kotlin.math.sign
fun main() {
val commands = readFile("input/9.txt")
.map {
MoveCommand(it.first(), it.substringAfter(" ").toInt())
}
val rope1 = Rope(knots = 2)
val rope2 = Rope(knots = 10)
commands.forEach { command ->
rope1.move(command)
rope2.move(command)
}
val result = rope1.tail().log.distinct().count()
rope1.tail().printLog()
println("part 1: $result")
val result2 = rope2.tail().log.distinct().count()
rope2.tail().printLog()
println("part 2: $result2")
}
class Rope(knots: Int) {
private val knots = buildList {
repeat(knots) {
add(Knot())
}
}
fun head() = knots.first()
fun tail() = knots.last()
fun move(command: MoveCommand) {
repeat(command.steps) {
val currentPosition = head().position
val newPosition = when (command.direction) {
'R' -> currentPosition.copy(first = currentPosition.first + 1)
'D' -> currentPosition.copy(second = currentPosition.second - 1)
'L' -> currentPosition.copy(first = currentPosition.first - 1)
'U' -> currentPosition.copy(second = currentPosition.second + 1)
else -> error("")
}
head().moveTo(newPosition)
for (index in 1 until knots.size) {
val knot = knots[index]
val previous = knots[index - 1]
if (!knot.touches(previous.position)) {
val distHorizontal = previous.position.first - knot.position.first
val distVertical = previous.position.second - knot.position.second
val pos = knot.position.apply(Pair(distHorizontal.sign, distVertical.sign))
knot.moveTo(pos)
}
}
}
}
}
fun Pair<Int, Int>.apply(otherPair: Pair<Int, Int>): Pair<Int, Int> {
return copy(first = this.first + otherPair.first, second = this.second + otherPair.second)
}
data class MoveCommand(val direction: Char, val steps: Int)
data class Knot(
var position: Pair<Int, Int> = 0 to 0,
val log: MutableList<Pair<Int, Int>> = mutableListOf(0 to 0)
) {
fun moveTo(newPosition: Pair<Int, Int>) {
log.add(newPosition)
position = newPosition
}
fun touches(newPosition: Pair<Int, Int>): Boolean =
(position.first in newPosition.first - 1..newPosition.first + 1
&& position.second in newPosition.second - 1..newPosition.second + 1)
fun printLog() {
val distinct = log.distinct()
//find bounds
val left = distinct.minBy { it.first }.first
val right = distinct.maxBy { it.first }.first
val top = distinct.maxBy { it.second }.second
val bottom = distinct.minBy { it.second }.second
println("$left $top $right $bottom")
val result = mutableListOf<String>()
for (row in bottom..top) {
val sb = StringBuilder()
for (col in left..right) {
val pair = distinct.find { it.first == col && it.second == row }
if (pair != null) {
if (pair == 0 to 0)
sb.append("s")
else
sb.append("#")
} else sb.append(".")
}
result.add(sb.toString())
}
result.reversed().forEach {
println(it)
}
}
}
| 0 | Kotlin | 0 | 0 | a823cb9e1677b6285bc47fcf44f523e1483a0143 | 3,526 | aoc2022 | The Unlicense |
src/y2021/Day02.kt | Yg0R2 | 433,731,745 | false | null | package y2021
import y2021.Directions.DOWN
import y2021.Directions.FORWARD
import y2021.Directions.UP
fun main() {
fun part1(input: List<String>): Int {
return input.toDirectionAmountPairList()
.fold(Submarine(0, 0, 0)) { acc, (direction, amount) ->
when (direction) {
DOWN -> acc.apply { depth += amount }
FORWARD -> acc.apply { horizontal += amount }
UP -> acc.apply { depth -= amount }
}
}
.let { it.horizontal * it.depth}
}
fun part2(input: List<String>): Int {
return input.toDirectionAmountPairList()
.fold(Submarine(0, 0, 0)) { acc, (direction, amount) ->
when (direction) {
DOWN -> acc.apply { aim += amount }
FORWARD -> acc.apply {
horizontal += amount
depth += aim * amount
}
UP -> acc.apply { aim -= amount }
}
}
.let { it.horizontal * it.depth }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 150)
check(part2(testInput) == 900)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
private data class Submarine(
var aim: Int,
var depth: Int,
var horizontal: Int
)
private fun List<String>.toDirectionAmountPairList(): List<Pair<Directions, Int>> = this
.filter { it.isNotBlank() }
.map { it.split(" ") }
.map { (directionString, amountString) -> Pair(directionString.toDirection(), amountString.toInt()) }
private fun String.toDirection(): Directions = Directions.of(this)
private enum class Directions(val value: String) {
DOWN("down"),
FORWARD("forward"),
UP("up");
companion object {
fun of(value: String): Directions = values()
.find { it.value == value }
?: throw IllegalArgumentException("invalid direction: $value")
}
}
| 0 | Kotlin | 0 | 0 | d88df7529665b65617334d84b87762bd3ead1323 | 2,126 | advent-of-code | Apache License 2.0 |
src/Day19.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day19.run {
solve1(33) // 1199
solve2(3348) // 3510
}
}.let { println("Total: $it ms") }
}
object Day19 : Day.LineInput<List<Day19.Blueprint>, Int>("19") {
class Blueprint(val id: Int, private val costs: Array<IntArray>) {
fun maxGeodes(totalTime: Int): Int {
var res = 0
val resource = intArrayOf(0, 0, 0, 0)
val robot = intArrayOf(1, 0, 0, 0)
val robotMax = IntArray(4) { resId -> costs.maxOf { it[resId] } }.also { it[3] = totalTime }
fun traverse(currTime: Int) {
if (currTime == totalTime) {
res = maxOf(res, resource.last())
return
}
for (robotId in robot.indices.reversed()) {
val canBuildRobot = costs[robotId].withIndex().all { (resId, resNeed) ->
resource[resId] >= resNeed
} && robot[robotId] < robotMax[robotId]
if (canBuildRobot) {
resource.indices.forEach { resource[it] += robot[it] }
resource.indices.forEach { resource[it] -= costs[robotId][it] }
robot[robotId] += 1
traverse(currTime + 1)
robot[robotId] -= 1
resource.indices.forEach { resource[it] += costs[robotId][it] }
resource.indices.forEach { resource[it] -= robot[it] }
if (robotId >= 2) {
return
}
}
}
resource.indices.forEach { resource[it] += robot[it] }
traverse(currTime + 1)
resource.indices.forEach { resource[it] -= robot[it] }
}
traverse(0)
return res
}
}
override fun parse(input: List<String>) = input.map { line ->
Regex("""Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""")
.matchEntire(line)!!.destructured.toList().map(String::toInt).let {
Blueprint(
it[0],
arrayOf(
intArrayOf(it[1], 0, 0, 0),
intArrayOf(it[2], 0, 0, 0),
intArrayOf(it[3], it[4], 0, 0),
intArrayOf(it[5], 0, it[6], 0)
)
)
}
}
override fun part1(data: List<Blueprint>) = data.sumOf { it.maxGeodes(24) * it.id }
override fun part2(data: List<Blueprint>) = data.take(3).fold(1) { acc, it -> acc * it.maxGeodes(32) }
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 2,904 | AdventOfCode2022 | Apache License 2.0 |
src/Day02.kt | anisch | 573,147,806 | false | {"Kotlin": 38951} | enum class Shape(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3)}
enum class OutCome(val result: Int) { LOST(0), DRAW(3), WIN(6)}
fun parseShapes(line: String): Pair<Shape, Shape> {
val s = line
.split(" ")
.map { s -> parseShape(s) }
return Pair(s[0], s[1])
}
fun parseShapeOutCome(line: String): Pair<Shape, OutCome> {
val s = line.split(" ")
return Pair(parseShape(s[0]), parseOutCome(s[1]))
}
fun parseShape(s: String): Shape = when (s) {
"A", "X" -> Shape.ROCK
"B", "Y" -> Shape.PAPER
"C", "Z" -> Shape.SCISSORS
else -> error("wtf???")
}
fun parseOutCome(s: String) = when (s) {
"X" -> OutCome.LOST
"Y" -> OutCome.DRAW
"Z" -> OutCome.WIN
else -> error("wtf???")
}
fun getShapeOutCome(s: Shape, o: OutCome): Shape = when (o) {
OutCome.WIN -> when (s) {
Shape.ROCK -> Shape.PAPER
Shape.PAPER -> Shape.SCISSORS
Shape.SCISSORS -> Shape.ROCK
}
OutCome.LOST -> when (s) {
Shape.ROCK -> Shape.SCISSORS
Shape.PAPER -> Shape.ROCK
Shape.SCISSORS -> Shape.PAPER
}
else -> s
}
fun getResult(m: Pair<Shape, Shape>): Pair<OutCome, OutCome> = when {
m.first == Shape.ROCK && m.second == Shape.SCISSORS -> Pair(OutCome.WIN, OutCome.LOST)
m.first == Shape.ROCK && m.second == Shape.PAPER -> Pair(OutCome.LOST, OutCome.WIN)
m.first == Shape.PAPER && m.second == Shape.ROCK -> Pair(OutCome.WIN, OutCome.LOST)
m.first == Shape.PAPER && m.second == Shape.SCISSORS -> Pair(OutCome.LOST, OutCome.WIN)
m.first == Shape.SCISSORS && m.second == Shape.PAPER -> Pair(OutCome.WIN, OutCome.LOST)
m.first == Shape.SCISSORS && m.second == Shape.ROCK -> Pair(OutCome.LOST, OutCome.WIN)
else -> Pair(OutCome.DRAW, OutCome.DRAW)
}
fun getScore(m: Pair<Shape, Shape>, o: Pair<OutCome, OutCome>): Pair<Int, Int> =
Pair(m.first.score + o.first.result, m.second.score + o.second.result)
fun main() {
fun part1(input: List<String>): Int {
return input
.map { parseShapes(it) }
.map { getScore(it, getResult(it)) }
.reduce { acc, next -> Pair(acc.first + next.first, acc.second + next.second) }
.second
}
fun part2(input: List<String>): Int {
return input
.map { parseShapeOutCome(it) }
.map { Pair(it.first, getShapeOutCome(it.first, it.second)) }
.map { getScore(it, getResult(it)) }
.reduce { acc, next -> Pair(acc.first + next.first, acc.second + next.second) }
.second
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val input = readInput("Day02")
check(part1(testInput) == 15)
println(part1(input))
check(part2(testInput) == 12)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f45d264d578661957800cb01d63b6c7c00f97b1 | 2,919 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day08.kt | timmiller17 | 577,546,596 | false | {"Kotlin": 44667} | fun main() {
fun part1(input: List<String>): Int {
var visibleTreeCount = 0
val rows = input.map { it.chunked(1) }
val outerTreeCount = rows[0].size * 2 + (rows.size - 2) * 2
visibleTreeCount += outerTreeCount
outerLoop@ for (column in 1..rows[0].size - 2) {
for (row in 1..rows.size - 2) {
val treeHeight = rows[row][column].toInt()
val treesToLeft = rows[row].subList(0, column)
if (treeHeight.visibleThrough(treesToLeft.map { it.toInt() })) {
visibleTreeCount++
continue
}
val treesToRight = rows[row].subList(column + 1, rows[row].size)
if (treeHeight.visibleThrough(treesToRight.map { it.toInt() })) {
visibleTreeCount++
continue
}
val treesToTop = mutableListOf<String>()
for (i in 0 until row) {
treesToTop += rows[i][column]
}
if (treeHeight.visibleThrough(treesToTop.map { it.toInt() })) {
visibleTreeCount++
continue
}
val treesToBottom = mutableListOf<String>()
for (i in (row + 1) until rows.size) {
treesToBottom += rows[i][column]
}
if (treeHeight.visibleThrough(treesToBottom.map { it.toInt() })) {
visibleTreeCount++
continue
}
}
}
return visibleTreeCount
}
fun part2(input: List<String>): Int {
var maxScenicScore = 0
val rows = input.map { it.chunked(1) }
for (column in 1..rows[0].size - 2) {
for (row in 1..rows.size - 2) {
val treeHeight = rows[row][column].toInt()
val treesToLeft = rows[row].subList(0, column).reversed().map { it.toInt() }
val treesToRight = rows[row].subList(column + 1, rows[row].size).map { it.toInt() }
val treesToTop = mutableListOf<Int>()
for (i in row - 1 downTo 0) {
treesToTop += rows[i][column].toInt()
}
val treesToBottom = mutableListOf<Int>()
for (i in (row + 1) until rows.size) {
treesToBottom += rows[i][column].toInt()
}
// experimenting with which reads better, I think I like treeHeight.viewingDistanceTo(treesToLeft) better
// val leftViewingDistance = treesToLeft.viewingDistanceFor(treeHeight)
val rightViewingDistance = treesToRight.viewingDistanceFor(treeHeight)
val topViewingDistance = treesToTop.viewingDistanceFor(treeHeight)
val bottomViewingDistance = treesToBottom.viewingDistanceFor(treeHeight)
val leftViewingDistance = treeHeight.viewingDistanceTo(treesToLeft)
val scenicScore = leftViewingDistance * rightViewingDistance * topViewingDistance * bottomViewingDistance
if (scenicScore > maxScenicScore) {
maxScenicScore = scenicScore
}
}
}
return maxScenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
part1(input).println()
part2(input).println()
}
fun Int.visibleThrough(list: List<Int>): Boolean {
return this > list.max()
}
fun List<Int>.viewingDistanceFor(treeHeight: Int): Int {
var viewingDistance = 0
for (tree in this) {
if (tree < treeHeight) {
viewingDistance++
} else {
viewingDistance++
break
}
}
return viewingDistance
}
fun Int.viewingDistanceTo(trees: List<Int>): Int {
var viewingDistance = 0
for (tree in trees) {
if (tree < this) {
viewingDistance++
} else {
viewingDistance++
break
}
}
return viewingDistance
} | 0 | Kotlin | 0 | 0 | b6d6b647c7bb0e6d9e5697c28d20e15bfa14406c | 4,248 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import java.lang.Integer.min
import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Int {
lateinit var start: Node
lateinit var target: Node
val map =
input.mapIndexed { y, line ->
line.toCharArray().mapIndexed { x, height ->
Node(x, y, height.value()).also {
if (height == 'S') start = it
if (height == 'E') target = it
}
}
}
start.distanceFromStart = 0
return dijkstra(start, target, map)
}
fun part2(input: List<String>): Int {
val possibleStarts = mutableListOf<Node>()
lateinit var target: Node
val map =
input.mapIndexed { y, line ->
line.toCharArray().mapIndexed { x, height ->
Node(x, y, height.value()).also {
if (height in listOf('S', 'a')) possibleStarts.add(it)
if (height == 'E') target = it
}
}
}
return possibleStarts.minOf { start ->
val copyOfMap = map.copy()
val startNode = copyOfMap[start.y][start.x].apply { distanceFromStart = 0 }
dijkstra(startNode, copyOfMap[target.y][target.x], copyOfMap)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
assertEquals(31, part1(testInput))
assertEquals(29, part2(testInput))
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
fun List<List<Node>>.copy(): List<List<Node>> {
return this.map { it.map(Node::copy) }
}
fun Char.value() =
when (this) {
'S' -> 'a'.code
'E' -> 'z'.code
else -> this.code
}
fun dijkstra(
startNode: Node,
target: Node,
map: List<List<Node>>,
): Int {
val unvisitedNodes = mutableSetOf<Node>()
var currentNode = startNode
while (true) {
for (node in currentNode.getUnvisitedNeighbors(map)) {
unvisitedNodes.add(node)
val tentativeDistance = currentNode.distanceFromStart + 1
node.distanceFromStart = min(tentativeDistance, node.distanceFromStart)
}
currentNode.isVisited = true
unvisitedNodes.remove(currentNode)
if (currentNode == target) {
break
}
val nodeWithLowestDistance = unvisitedNodes.minOrNull()
if (nodeWithLowestDistance != null) {
currentNode = nodeWithLowestDistance
} else {
break
}
}
return target.distanceFromStart
}
data class Node(
val x: Int,
val y: Int,
val height: Int,
var isVisited: Boolean = false,
var distanceFromStart: Int = Int.MAX_VALUE,
) : Comparable<Node> {
fun getUnvisitedNeighbors(map: List<List<Node>>): List<Node> {
val neighbors = mutableListOf<Node>()
val xMax = map[0].lastIndex
val yMax = map.lastIndex
val maxSlope = 1
if (x > 0) {
val left = map[y][x - 1]
if (left.height - height <= maxSlope) neighbors.add(left)
}
if (x < xMax) {
val right = map[y][x + 1]
if (right.height - height <= maxSlope) neighbors.add(right)
}
if (y < yMax) {
val lower = map[y + 1][x]
if (lower.height - height <= maxSlope) neighbors.add(lower)
}
if (y > 0) {
val upper = map[y - 1][x]
if (upper.height - height <= maxSlope) neighbors.add(upper)
}
return neighbors.filterNot { it.isVisited }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Node
if (x != other.x) return false
if (y != other.y) return false
return true
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
override fun compareTo(other: Node) = distanceFromStart.compareTo(other.distanceFromStart)
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 3,780 | aoc2022 | Apache License 2.0 |
day10/kotlin/corneil/src/main/kotlin/solution.kt | timgrossmann | 224,991,491 | true | {"HTML": 2739009, "Python": 169603, "Java": 157274, "Jupyter Notebook": 116902, "TypeScript": 113866, "Kotlin": 89503, "Groovy": 73664, "Dart": 47763, "C++": 43677, "CSS": 34994, "Ruby": 27091, "Haskell": 26727, "Scala": 11409, "Dockerfile": 10370, "JavaScript": 6496, "PHP": 4152, "Go": 2838, "Shell": 2493, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day10
import java.io.File
import java.math.BigDecimal
import java.math.RoundingMode.HALF_EVEN
import kotlin.math.atan2
import kotlin.math.max
import kotlin.math.sqrt
data class Coord(val x: Int, val y: Int)
data class AsteroidMap(val width: Int, val height: Int, val asteroidLocations: List<Coord>) {
fun contains(point: Coord): Boolean {
return point.x >= 0 && point.x < width && point.y >= 0 && point.y < height
}
}
fun readMap(input: List<String>): AsteroidMap {
var width: Int = 0
val result = mutableListOf<Coord>()
input.forEachIndexed { y, line ->
line.trim().forEachIndexed { x, c ->
width = max(width, x + 1)
if (c == '#') {
result.add(Coord(x, y))
}
}
}
return AsteroidMap(width, input.size, result)
}
// I had to look at other solutions to do the 2nd part. Tx <NAME>
fun direction(start: Coord, end: Coord) = Coord(end.x - start.x, end.y - start.y)
fun distance(pt: Coord): Double = sqrt(Math.pow(pt.x.toDouble(), 2.0) + Math.pow(pt.y.toDouble(), 2.0))
typealias Normalized = Pair<BigDecimal, BigDecimal>
fun normalized(pt: Coord): Normalized {
val dist = distance(pt)
return Pair(
BigDecimal(pt.x.toDouble() / dist).setScale(4, HALF_EVEN),
BigDecimal(pt.y / dist).setScale(4, HALF_EVEN)
)
}
fun prepareOtherAsteroids(map: AsteroidMap, coord: Coord): Map<Normalized, MutableList<Pair<Coord, Double>>> {
val result = mutableMapOf<Normalized, MutableList<Pair<Coord, Double>>>()
map.asteroidLocations.filter { it != coord }.forEach {
val dir = direction(coord, it)
val dist = distance(dir)
val norm = normalized(dir)
val target = Pair(it, dist)
if (result.containsKey(norm)) {
result.get(norm)!!.add(target)
} else {
result.put(norm, mutableListOf(target))
}
}
result.forEach { entry ->
entry.value.sortBy { it.second }
}
return result
}
fun findLineOfSightCount(map: AsteroidMap, coord: Coord): Int {
return prepareOtherAsteroids(map, coord).size
}
fun shootInOrder(map: AsteroidMap, laser: Coord): List<Coord> {
val list = prepareOtherAsteroids(map, laser)
val visiting = list.keys.sortedBy { atan2(it.first.toDouble(), it.second.toDouble()) }.reversed()
val shot = mutableListOf<Coord>()
while (shot.size < map.asteroidLocations.size - 1) {
visiting.forEach { direction ->
val targets = list[direction] ?: mutableListOf()
if (targets.isNotEmpty()) {
shot.add(targets.first().first)
targets.removeAt(0)
}
}
}
return shot
}
fun main(args: Array<String>) {
val fileName = if (args.size > 1) args[0] else "input.txt"
val map = readMap(File(fileName).readLines().map { it.trim() })
val counts = map.asteroidLocations.map { it to findLineOfSightCount(map, it) }
val best = counts.maxBy { it.second }
println("Best = $best")
val shot = shootInOrder(map, best!!.first)
val shot200 = shot[199]
val answer = shot200.x * 100 + shot200.y
println("Answer=$answer")
}
| 0 | HTML | 0 | 1 | bb19fda33ac6e91a27dfaea27f9c77c7f1745b9b | 3,212 | aoc-2019 | MIT License |
src/main/kotlin/tr/emreone/adventofcode/days/Day9.kt | EmRe-One | 434,793,519 | false | {"Kotlin": 44202} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.Logger.logger
object Day9 {
class Navigation(input: List<String>) {
private val cities = mutableSetOf<String>()
private val pattern = """^(\w+) to (\w+) = (\d+)$""".toRegex()
private val distanceMatrix = input.map { line ->
val (from, to, distance) = pattern.matchEntire(line)!!.destructured
cities.add(from)
cities.add(to)
Pair(from, to) to distance.toInt()
}
fun getDistanceBetween(from: String, to: String): Int {
return distanceMatrix.first {
it.first == Pair(from, to) || it.first == Pair(to, from)
}.second
}
fun getShortestDistance(): Pair<Set<String>, Int> {
return cities.map {
shortestDistance(it)
}.minByOrNull { it.second } ?: throw IllegalStateException("No path found")
}
fun getLongestDistance(): Pair<Set<String>, Int> {
return cities.map {
longestDistance(it)
}.maxByOrNull { it.second } ?: throw IllegalStateException("No path found")
}
private fun shortestDistance(current: String, visited: Set<String> = setOf(current)): Pair<Set<String>, Int> {
if (visited.size == cities.size) {
// all cities reached, no more travel possible
return visited to 0
}
var minDistance = Int.MAX_VALUE
var minDistancePath: Set<String> = setOf()
for (next in cities.filter { it != current }) {
if (visited.contains(next)) {
continue
}
val nextDistance = shortestDistance(next, visited + next)
val distance = getDistanceBetween(current, next) + nextDistance.second
if (distance < minDistance) {
minDistance = distance
minDistancePath = nextDistance.first
}
}
return minDistancePath to minDistance
}
private fun longestDistance(current: String, visited: Set<String> = setOf(current)): Pair<Set<String>, Int> {
if (visited.size == cities.size) {
// all cities reached, no more travel possible
return visited to 0
}
var maxDistance = 0
var maxDistancePath: Set<String> = setOf()
for (next in cities.filter { it != current }) {
if (visited.contains(next)) {
continue
}
val nextDistance = longestDistance(next, visited + next)
val distance = getDistanceBetween(current, next) + nextDistance.second
if (distance > maxDistance) {
maxDistance = distance
maxDistancePath = nextDistance.first
}
}
return maxDistancePath to maxDistance
}
}
fun part1(input: List<String>): Int {
val navigation = Navigation(input)
val shortestDistance = navigation.getShortestDistance()
val distanceString = buildString {
shortestDistance.first.windowed(2).forEach { (from, to) ->
append(from)
append(" -(")
append(navigation.getDistanceBetween(from, to))
append(")-> ")
}
append(shortestDistance.first.last())
}
logger.debug { "Shortest distance: ${shortestDistance.second}" }
logger.debug { distanceString }
return shortestDistance.second
}
fun part2(input: List<String>): Int {
val navigation = Navigation(input)
val longestDistance = navigation.getLongestDistance()
val distanceString = buildString {
longestDistance.first.windowed(2).forEach { (from, to) ->
append(from)
append(" -(")
append(navigation.getDistanceBetween(from, to))
append(")-> ")
}
append(longestDistance.first.last())
}
logger.debug { "Longest distance: ${longestDistance.second}" }
logger.debug { distanceString }
return longestDistance.second
}
}
| 0 | Kotlin | 0 | 0 | 57f6dea222f4f3e97b697b3b0c7af58f01fc4f53 | 4,342 | advent-of-code-2015 | Apache License 2.0 |
aoc21/day_18/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
data class Num(var num: Int, var depth: Int)
typealias Snailfish = MutableList<Num>
fun parseNum(str: String): Snailfish {
val result = mutableListOf<Num>()
var i = 0
var depth = 0
while (i < str.length) {
when (str[i]) {
'[' -> depth += 1
']' -> depth -= 1
',' -> {}
else -> {
val len = str.drop(i).indexOfFirst { !it.isDigit() }
result.add(Num(str.substring(i, i + len).toInt(), depth))
i += len - 1
}
}
i += 1
}
return result
}
fun Snailfish.explode(): Boolean {
val i = withIndex().find { (i, n) ->
i < size - 1 && n.depth == this[i + 1].depth && n.depth > 4
}?.index
if (i == null)
return false
if (i > 0)
this[i - 1].num += this[i].num
if (i < size - 2)
this[i + 2].num += this[i + 1].num
removeAt(i)
this[i] = Num(0, this[i].depth - 1)
return true
}
fun Snailfish.split(): Boolean {
val i = withIndex().find { (_, n) -> n.num >= 10 }?.index
if (i == null)
return false
add(i + 1, Num(this[i].num / 2 + this[i].num % 2, this[i].depth + 1))
this[i] = Num(this[i].num / 2, this[i].depth + 1)
return true
}
fun Snailfish.reduce() {
while (explode() || split()) {}
}
fun Snailfish.add(other: Snailfish): Snailfish {
val sum = (this + other).map { Num(it.num, it.depth + 1) }.toMutableList()
sum.reduce()
return sum
}
fun Snailfish.magnitude(): Int {
var muls = mutableListOf<Int>()
var result = 0
for (n in this) {
while (n.depth > muls.size)
muls.add(3)
result += muls.fold(n.num) { prod, m -> prod * m }
while (!muls.isEmpty() && muls.removeLast() == 2) {}
muls.add(2)
}
return result
}
fun main() {
val lines = File("input").readLines()
val nums = lines.map { parseNum(it) }
val first = nums.reduce { sum, num -> sum.add(num) }.magnitude()
println("First: $first")
val second = nums
.flatMap { n1 -> nums.flatMap { n2 -> listOf(n1 to n2, n2 to n1) } }
.map { (n1, n2) -> n1.add(n2).magnitude() }
.maxOrNull()!!
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 2,256 | advent-of-code | MIT License |
src/year2015/day09/Day09.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2015.day09
import check
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2015", "Day09_test")
check(part1(testInput), 605)
check(part2(testInput), 982)
val input = readInput("2015", "Day09")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = distancesByRoute(input).minOf { it.value }
private fun part2(input: List<String>) = distancesByRoute(input).maxOf { it.value }
private fun distancesByRoute(input: List<String>): Map<List<String>, Int> {
val graph = hashMapOf<String, MutableList<Pair<String, Int>>>()
input.forEach { line ->
val (a, _, b, _, distance) = line.split(' ')
graph.getOrPut(a) { mutableListOf() } += b to distance.toInt()
graph.getOrPut(b) { mutableListOf() } += a to distance.toInt()
}
val queue = ArrayDeque<List<String>>()
val possibleRoutes = mutableListOf<List<String>>()
queue += graph.keys.map { listOf(it) }
while (queue.isNotEmpty()) {
val route = queue.removeFirst()
if (route.size == graph.keys.size) {
possibleRoutes += route
continue
}
for (next in graph[route.last()] ?: emptyList()) {
if (next.first !in route) {
queue += route + next.first
}
}
}
return possibleRoutes.associateWith { route ->
route.windowed(2) { (from, to) ->
graph[from]?.find { it.first == to }?.second ?: error("Distance for $from to $to not available")
}.sum()
}
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,627 | AdventOfCode | Apache License 2.0 |
src/Day23.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} | class Day23(input: List<String>) {
private val startingPositions = parseInput(input)
private val nextTurnOffsets: List<List<Point2d>> = createOffsets()
fun solvePart1(): Int {
val locations = (0 until 10).fold(startingPositions) { carry, round -> carry.playRound(round) }
val gridSize =
((locations.maxOf { it.x } - locations.minOf { it.x }) + 1) * ((locations.maxOf { it.y } - locations.minOf { it.y }) + 1)
return gridSize - locations.size
}
fun solvePart2(): Int {
var thisTurn = startingPositions
var roundId = 0
do {
val previousTurn = thisTurn
thisTurn = previousTurn.playRound(roundId++)
} while (previousTurn != thisTurn)
return roundId
}
private fun Set<Point2d>.playRound(roundNumber: Int): Set<Point2d> {
val nextPositions = this.toMutableSet()
val movers: Map<Point2d, Point2d> = this
.filter { elf -> elf.neighbors().any { it in this } }
.mapNotNull { elf ->
nextTurnOffsets.indices.map { direction -> nextTurnOffsets[(roundNumber + direction) % 4] }
.firstNotNullOfOrNull { offsets ->
if (offsets.none { offset -> (elf + offset) in this }) elf to (elf + offsets.first())
else null
}
}.toMap()
val safeDestinations = movers.values.groupingBy { it }.eachCount().filter { it.value == 1 }.keys
movers
.filter { (_, target) -> target in safeDestinations }
.forEach { (source, target) ->
nextPositions.remove(source)
nextPositions.add(target)
}
return nextPositions
}
private fun createOffsets(): List<List<Point2d>> =
listOf(
listOf(Point2d(0, -1), Point2d(-1, -1), Point2d(1, -1)), // N
listOf(Point2d(0, 1), Point2d(-1, 1), Point2d(1, 1)), // S
listOf(Point2d(-1, 0), Point2d(-1, -1), Point2d(-1, 1)), // W
listOf(Point2d(1, 0), Point2d(1, -1), Point2d(1, 1)), // E
)
private fun parseInput(input: List<String>): Set<Point2d> =
input.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
if (char == '#') Point2d(x, y) else null
}
}.toSet()
}
fun main() {
val testInput = readInput("Day23_test")
check(Day23(testInput).solvePart1() == 110)
measureTimeMillisPrint {
val input = readInput("Day23")
val d23 = Day23(input)
println(d23.solvePart1())
println(d23.solvePart2())
}
} | 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 2,657 | aoc-22-kotlin | Apache License 2.0 |
kotlin/src/com/leetcode/47_PermutationsII.kt | programmerr47 | 248,502,040 | false | null | package com.leetcode
import kotlin.math.pow
/**
* This is the enhancement of 47 supporting recurrent numbers
* The approach is similar except the creation of Set in each
* depth level of recursive `permute` call.
*
* We need that Set to check that this number was already used
* in all previous combinations, so we will not repeat ourselfs
*
* Time: O(n^n)
* Space: O(n^2) - since we creating new Set on each level of recursion
* and we have O(n) levels and each Set's size is O(n),
* thus, we will have O(n)*O(n) = O(n^2)
*
* Variation II.
* The other option rather than using new HashSet on each level of
* `permute` method is to sort initial array first (either create
* new one or sort in place) and then just check num[index] ? num[index - 1]
*
* This will make next things:
* Time: O(n^n) + O(n*log(n)) = O(n^n) - the complexity will be the same
* still worth to mention that it
* will be slightly slower :)
*
* Space: O(n) - since we not creating new data structures inside `permute`
* call, we taking back our space complexity!
*/
private class Solution47 {
fun permuteUnique(nums: IntArray): List<List<Int>> {
val result = ArrayList<List<Int>>(nums.size.pow(nums.size))
val bitMask = BooleanArray(nums.size)
val sample = ArrayList<Int>(nums.size)
permute(result, bitMask, nums, sample)
return result
}
private fun permute(permutations: MutableList<List<Int>>, bitMask: BooleanArray, nums: IntArray, sample: MutableList<Int>) {
if (sample.size == nums.size) {
permutations.add(ArrayList(sample))
return
}
val used = HashSet<Int>(nums.size)
nums.forEachIndexed { i, num ->
if (!bitMask[i] && num !in used) {
bitMask[i] = true
sample.add(num)
permute(permutations, bitMask, nums, sample)
sample.removeAt(sample.size - 1)
bitMask[i] = false
used += num
}
}
}
private fun Int.pow(other: Int): Int = this.toDouble().pow(other).toInt()
}
private class Solution47Version2 {
fun permuteUnique(nums: IntArray): List<List<Int>> {
val result = ArrayList<List<Int>>(nums.size.pow(nums.size))
val bitMask = BooleanArray(nums.size)
val sample = ArrayList<Int>(nums.size)
nums.sort()
permute(result, bitMask, nums, sample)
return result
}
private fun permute(permutations: MutableList<List<Int>>, bitMask: BooleanArray, nums: IntArray, sample: MutableList<Int>) {
if (sample.size == nums.size) {
permutations.add(ArrayList(sample))
return
}
nums.forEachIndexed { i, num ->
if (!bitMask[i] && (i <= 0 || nums[i - 1] != num || bitMask[i - 1])) {
bitMask[i] = true
sample.add(num)
permute(permutations, bitMask, nums, sample)
sample.removeAt(sample.size - 1)
bitMask[i] = false
}
}
}
private fun Int.pow(other: Int): Int = this.toDouble().pow(other).toInt()
}
fun main() {
val solution = Solution47Version2()
// println(solution.permuteUnique(intArrayOf(1, 2, 3)))
println(solution.permuteUnique(intArrayOf(1, 2, 1)))
println(solution.permuteUnique(intArrayOf(1, 2, 3, 1)))
// println(solution.permuteUnique(intArrayOf(3, 2, 1)))
// println(solution.permuteUnique(intArrayOf(0, 1)))
// println(solution.permuteUnique(intArrayOf(666)))
// println(solution.permuteUnique(intArrayOf(1, 2, 4, 8)))
// println(solution.permuteUnique(intArrayOf(1, 2, 4, 8, 9)))
} | 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 3,811 | problemsolving | Apache License 2.0 |
app/src/main/kotlin/day03/Day03.kt | W3D3 | 433,748,408 | false | {"Kotlin": 72893} | package day03
import common.InputRepo
import common.readSessionCookie
import common.solve
import kotlin.math.ceil
fun main(args: Array<String>) {
val day = 3
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay03Part1, ::solveDay03Part2)
}
fun solveDay03Part1(input: List<String>): Int {
val total = input.size
val countPerPosition = HashMap<Int, Int>()
for (bitsString in input) {
for ((index, bit) in bitsString.withIndex()) {
if (bit.digitToInt() == 1) {
countPerPosition.computeIfPresent(index) { _, v -> v + 1 }
countPerPosition.putIfAbsent(index, 1)
}
}
}
val gammaBits = countPerPosition
.map { entry -> entry.value > total / 2 }
.map { b -> if (b) 1 else 0 }
.toList()
val epsilonBits = gammaBits
.map { bit -> if (bit == 1) 0 else 1 }
val gammaRate = gammaBits.joinToString("").toInt(2)
val epsilonRate = epsilonBits.joinToString("").toInt(2)
return gammaRate * epsilonRate
}
/**
* Calculates the rating
*
* @param input the list of strings containing the binary numbers of the same length
* @param bitToAppend bit to append if the majority of an index contains ones (true = 1, false = 0)
*/
fun calculateRating(input: List<String>, bitToAppend: Boolean): Int {
var bitStrings = input
var prefix = ""
var index = 0
val bitCharToAppendOnMajority = if (bitToAppend) '1' else '0'
val bitCharToAppendOnMinority = if (bitToAppend) '0' else '1'
while (bitStrings.size > 1) {
val majorityOne = majorityOneOnIndex(bitStrings, index)
prefix += if (majorityOne) bitCharToAppendOnMajority else bitCharToAppendOnMinority
bitStrings = filterForPrefix(bitStrings, prefix)
index++
}
assert(bitStrings.size == 1)
return bitStrings[0].toInt(2)
}
fun majorityOneOnIndex(bitStrings: Collection<String>, index: Int): Boolean {
var cnt = 0
val threshold: Int = ceil(bitStrings.size / 2.0).toInt()
for (bitString in bitStrings) {
if (bitString[index].digitToInt() == 1) {
cnt++
}
if (cnt > threshold) {
return true
}
}
if (cnt == threshold) {
return true
}
return false
}
fun filterForPrefix(bitStrings: Collection<String>, prefix: String): List<String> {
return bitStrings.filter { s -> s.commonPrefixWith(prefix).length == prefix.length }.toList()
}
fun solveDay03Part2(input: List<String>): Int {
val o2Rating = calculateRating(input, true)
val co2Rating = calculateRating(input, false)
return o2Rating * co2Rating
}
| 0 | Kotlin | 0 | 0 | df4f21cd99838150e703bcd0ffa4f8b5532c7b8c | 2,696 | AdventOfCode2021 | Apache License 2.0 |
src/Day11.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | /**
* [Day11](https://adventofcode.com/2022/day/11)
*/
private class Day11 {
class Monkey private constructor(
val id: Int,
items: List<Long>,
val inspect: (Long) -> Long,
val divisible: Int,
private val destTrue: Int,
private val destFalse: Int
) {
val items = ArrayDeque<Long>()
init {
this.items.addAll(items)
}
fun test(n: Long): Int = if (n % divisible == 0L) destTrue else destFalse
companion object {
fun parse(input: List<String>): Monkey {
val numRegex = """(\d+)""".toRegex()
val id = numRegex.find(input[0])!!.groupValues.first().toInt()
val items = input[1].split(":")[1].split(",").map(String::trim).map(String::toLong)
val op = parseOperation(input[2].split("=")[1].trim())
val divisible = numRegex.find(input[3])!!.groupValues.first().toInt()
val destTrue = numRegex.find(input[4])!!.groupValues.first().toInt()
val destFalse = numRegex.find(input[5])!!.groupValues.first().toInt()
return Monkey(id, items, op, divisible, destTrue, destFalse)
}
}
}
companion object {
fun parseOperation(opStr: String): (Long) -> Long {
val (_, operandL, op, operandR) = """([^ ]+) ([+\-*]) ([^ ]+)""".toRegex().find(opStr)!!.groupValues
return { old: Long ->
val l = if (operandL == "old") old else operandL.toLong()
val r = if (operandR == "old") old else operandR.toLong()
when (op) {
"+" -> l + r
"-" -> l - r
"*" -> l * r
else -> throw RuntimeException()
}
}
}
}
}
fun main() {
fun parseMonkey(input: List<String>): List<Day11.Monkey> = buildList {
for (i in input.indices step 7) {
add(Day11.Monkey.parse(input.subList(i, i + 6)))
}
}
fun simulate(monkeyList: List<Day11.Monkey>, repeat: Int, worryHandler: (Long) -> Long): Array<Long> {
val inspectCounts = Array(monkeyList.size) { 0L }
repeat(repeat) {
monkeyList.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
var item = monkey.items.removeFirst()
item = monkey.inspect(item)
inspectCounts[monkey.id]++
item = worryHandler(item)
monkeyList[monkey.test(item)].items.addLast(item)
}
}
}
return inspectCounts
}
fun part1(input: List<String>): Long {
val monkeyList = parseMonkey(input)
val inspectCounts = simulate(monkeyList, 20) { it / 3 }
return inspectCounts.sortedDescending().take(2).reduce { acc, i -> acc * i }
}
fun part2(input: List<String>): Long {
val monkeyList = parseMonkey(input)
val divider = monkeyList.map(Day11.Monkey::divisible).reduce { acc, i -> acc * i }
val inspectCounts = simulate(monkeyList, 10000) { it % divider }
return inspectCounts.sortedDescending().take(2).reduce { acc, i -> acc * i }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 3,596 | aoc-in-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Day13.kt | dliszewski | 573,836,961 | false | {"Kotlin": 57757} | class Day13 {
fun part1(input: String): Int {
return input.split("\n\n").map { it.lines() }
.map { (packet, other) -> packet.mapToPacketData() to other.mapToPacketData() }
.mapIndexed { index, pair -> if (pair.first.compareTo(pair.second) < 1) index + 1 else 0 }
.sum()
}
fun part2(input: String): Int {
val packets = input.split("\n\n").map { it.lines() }
.flatMap { (packet, other) -> listOf(packet.mapToPacketData(), other.mapToPacketData()) }
val dividerPacket2 = "[[6]]".mapToPacketData()
val dividerPacket1 = "[[2]]".mapToPacketData()
val ordered = (packets + dividerPacket1 + dividerPacket2).sorted()
return (ordered.indexOf(dividerPacket1) + 1) * (ordered.indexOf(dividerPacket2) + 1)
}
private fun String.mapToPacketData(): PacketData {
val bracketsAndNumbers = split(Regex("((?<=[\\[\\],])|(?=[\\[\\],]))"))
.filter { it.isNotBlank() }
.filter { it != "," }
.iterator()
return mapIteratorToPacketData(bracketsAndNumbers)
}
private fun mapIteratorToPacketData(input: Iterator<String>): PacketData {
val packets = mutableListOf<PacketData>()
while (input.hasNext()) {
when (val symbol = input.next()) {
"]" -> return ListPacketData(packets)
"[" -> packets.add(mapIteratorToPacketData(input))
else -> packets.add(IntPacketData(symbol.toInt()))
}
}
return ListPacketData(packets)
}
sealed class PacketData : Comparable<PacketData>
data class IntPacketData(val data: Int) : PacketData() {
override fun compareTo(other: PacketData): Int {
return when (other) {
is IntPacketData -> data.compareTo(other.data)
is ListPacketData -> ListPacketData(listOf(this)).compareTo(other)
}
}
}
data class ListPacketData(val data: List<PacketData>) : PacketData() {
override fun compareTo(other: PacketData): Int {
return when (other) {
is IntPacketData -> compareTo(ListPacketData(listOf(other)))
is ListPacketData -> data.zip(other.data)
.map { (packet1, packet2) -> packet1.compareTo(packet2) }
.firstOrNull { it != 0 } ?: data.size.compareTo(other.data.size)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 76d5eea8ff0c96392f49f450660220c07a264671 | 2,469 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code-2022/src/Day09.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
val input = readInput("Day09")
"Part 1" {
val testInput = readInput("Day09_test1")
part1(testInput) shouldBe 13
answer(part1(input))
}
"Part 2" {
val testInput = readInput("Day09_test2")
part2(testInput) shouldBe 36
answer(part2(input))
}
}
private fun part1(input: List<Pair<Command, Int>>): Int = simulateRope(length = 1, input)
private fun part2(input: List<Pair<Command, Int>>): Int = simulateRope(length = 9, input)
// Time - `O(M)`, Space - `O(L + V)`, where
// M - number of total moves (sum of all command arguments)
// L - rope length (including head)
// V - number of points visited by tail
private fun simulateRope(length: Int, commands: List<Pair<Command, Int>>): Int {
// length + head
val positions = Array(length + 1) { 0 to 0 }
// Here we will track coordinates visited by tail
val visited = mutableSetOf(positions.last())
for ((command, times) in commands) {
// I don't know how to simulate all moves once, so let's do it step-by-step
repeat(times) {
// Move head
positions[0] = command.apply(positions[0])
// Simulate tail moves
for (i in 1..positions.lastIndex) {
val (headR, headC) = positions[i - 1]
var (r, c) = positions[i]
val diffR = headR - r
val diffC = headC - c
// If head moved too far, let's move closer to it
// According the rules, we always try to make closer both row and column
if (diffR.absoluteValue > 1 || diffC.absoluteValue > 1) {
r += diffR.sign
c += diffC.sign
}
positions[i] = r to c
}
visited += positions.last()
}
}
return visited.size
}
private fun readInput(name: String) = readLines(name).map {
val (command, number) = it.split(" ")
Command.valueOf(command) to number.toInt()
}
private enum class Command(val dr: Int = 0, val dc: Int = 0) {
R(dc = +1), U(dr = +1), L(dc = -1), D(dr = -1);
/** Returns the next coordinates on this direction. */
fun apply(coordinates: Pair<Int, Int>): Pair<Int, Int> {
val (r, c) = coordinates
return (r + dr) to (c + dc)
}
}
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 2,415 | advent-of-code | Apache License 2.0 |
src/day05/Day05.kt | Mini-Stren | 573,128,699 | false | null | package day05
import readInputLines
import java.util.*
fun main() {
val day = 5
fun part1(input: List<String>): String {
val cratesStacks = input.cratesStacks
val cratesMoves = input.cratesMoves
cratesMoves.forEach { (count, from, to) ->
repeat(count) {
val crate = cratesStacks[from - 1].pop()
cratesStacks[to - 1].push(crate)
}
}
return cratesStacks.topCrates
}
fun part2(input: List<String>): String {
val cratesStacks = input.cratesStacks
val cratesMoves = input.cratesMoves
cratesMoves.forEach { (count, from, to) ->
(0 until count)
.map { cratesStacks[from - 1].pop() }
.reversed()
.forEach { cratesStacks[to - 1].push(it) }
}
return cratesStacks.topCrates
}
val testInput = readInputLines("/day%02d/input_test".format(day))
val input = readInputLines("/day%02d/input".format(day))
check(part1(testInput) == "CMZ")
println("part1 answer is ${part1(input)}")
check(part2(testInput) == "MCD")
println("part2 answer is ${part2(input)}")
}
private val List<String>.cratesStacks: List<Stack<Char>>
get() {
val inputSplitLineIndex = indexOf("")
val cratesStacksCount = get(inputSplitLineIndex - 1).substringAfterLast(' ').toInt()
val cratesLineRegex = "(\\D{1,3})\\s?".toRegex()
val crates = subList(0, inputSplitLineIndex - 1).map { line ->
cratesLineRegex.findAll(line, 0)
.map { it.value.trim() }
.map { it.getOrNull(1) }
.toList()
.let { cratesStack ->
cratesStack.takeIf { it.size == cratesStacksCount }
?: (cratesStack + (cratesStack.size until cratesStacksCount).map { null })
}
}
return (0 until cratesStacksCount).map { stackIndex ->
Stack<Char>().apply {
crates.reversed()
.mapNotNull { it[stackIndex] }
.forEach(::push)
}
}
}
private val List<String>.cratesMoves: List<Triple<Int, Int, Int>>
get() {
val inputSplitLineIndex = indexOf("")
val movesLineRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
return subList(inputSplitLineIndex + 1, size).map { line ->
val movesGroup = movesLineRegex.matchAt(line, 0)
?.groupValues?.drop(1)
?: emptyList()
Triple(movesGroup[0].toInt(), movesGroup[1].toInt(), movesGroup[2].toInt())
}
}
private val List<Stack<Char>>.topCrates: String
get() = map(Stack<Char>::peek).joinToString(separator = "")
| 0 | Kotlin | 0 | 0 | 40cb18c29089783c9b475ba23c0e4861d040e25a | 2,789 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day16.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2022
import com.dvdmunckhof.aoc.common.BitSet
class Day16(private val input: List<String>) {
private val valves = parseInput()
private val possibleValves = valves.filter { it.flowRate != 0 }
private val distances = calculateDistances(valves)
fun solvePart1(): Int {
val states = calculatePressureRelease(30)
return states.maxOf { it.releasedPressure }
}
fun solvePart2(): Int {
val states = calculatePressureRelease(26)
.sortedByDescending { it.releasedPressure }
return states.maxOf { state1 ->
val state2 = states.first { state2 -> (state1.openedValves and state2.openedValves).isEmpty() }
state1.releasedPressure + state2.releasedPressure
}
}
private fun calculatePressureRelease(time: Int): List<State> {
val states = mutableListOf<State>()
/** Depth-first search */
fun walkTunnels(current: Valve, openedValves: BitSet, remainingTime: Int, totalFlow: Int) {
val releasedPressureNew = totalFlow + (remainingTime * current.flowRate)
states += State(openedValves, releasedPressureNew)
for (valve in possibleValves) {
if (valve.index in openedValves) continue
val timeRequired = distances[current.index][valve.index] + 1
if (remainingTime < timeRequired) continue
walkTunnels(valve, openedValves + valve.index, remainingTime - timeRequired, releasedPressureNew)
}
}
val startValve = valves.first { it.name == "AA" }
walkTunnels(startValve, BitSet(), time, 0)
return states
}
private fun parseInput(): List<Valve> {
val lineRegex = Regex("""Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? (.+)""")
return input.mapIndexed { i, line ->
val groups = lineRegex.matchEntire(line)!!.groupValues
Valve(index = i, name = groups[1], flowRate = groups[2].toInt(), tunnels = groups[3].split(", "))
}
}
/** Floyd–Warshall algorithm */
private fun calculateDistances(valves: List<Valve>): List<List<Int>> {
// initialize all distances to 100
val dist = MutableList(valves.size) { MutableList(valves.size) { 100 } }
val mapping = valves.associate { it.name to it.index }
for (valve in valves) {
// paths to itself
dist[valve.index][valve.index] = 0
// all tunnels
for (tunnelName in valve.tunnels) {
val index = mapping.getValue(tunnelName)
dist[valve.index][index] = 1
}
}
for (k in valves.indices) {
for (i in valves.indices) {
for (j in valves.indices) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j]
}
}
}
}
return dist
}
private data class State(
val openedValves: BitSet,
val releasedPressure: Int,
)
private data class Valve(
val index: Int,
val name: String,
val flowRate: Int,
val tunnels: List<String>,
)
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 3,292 | advent-of-code | Apache License 2.0 |
src/y2021/Day04.kt | Yg0R2 | 433,731,745 | false | null | package y2021
import java.util.concurrent.atomic.AtomicBoolean
fun main() {
fun initializeBoards(input: List<String>) = input
.drop(2)
.windowed(5, 6)
.map { BingoBoard(it) }
fun part1(input: List<String>): Int {
val boards: List<BingoBoard> = initializeBoards(input)
var result = 0
input[0].split(",")
.map { it.toInt() }
.any { currentDraw ->
boards.any {
it.drawNumber(currentDraw)
if (it.hasBingo.get()) {
result = it.sumOfNotDrawn() * currentDraw
}
result != 0
}
}
return result
}
fun part2(input: List<String>): Int {
val boards: List<BingoBoard> = initializeBoards(input)
var result = 0
input[0].split(",")
.map { it.toInt() }
.any { currentDraw ->
boards.filter { !it.hasBingo.get() }
.forEach {
it.drawNumber(currentDraw)
if (it.hasBingo.get()) {
result = it.sumOfNotDrawn() * currentDraw
}
}
result != 0 && boards.all { it.hasBingo.get() }
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 4512)
check(part2(testInput) == 1924)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private class BingoBoard(input: List<String>) {
val hasBingo = AtomicBoolean(false)
private val board: Array<Array<BingoBoardNumber>>
private val boardByColumn:Array<Array<BingoBoardNumber>>
init {
board = input
.map { row ->
row.split(" ")
.filter { it.isNotBlank() }
.map { BingoBoardNumber(it.toInt()) }
.toTypedArray()
}
.toTypedArray()
boardByColumn = board.mapIndexed { rowIndex, _ ->
board.map { it[rowIndex] }
.toTypedArray()
}
.toTypedArray()
}
fun drawNumber(drawn: Int) {
board.forEach { row ->
row.filter { it.number == drawn }
.forEach { it.drawn = true }
}
hasBingo.set(isColumnBing() || isRowBing())
}
fun sumOfNotDrawn(): Int = board
.flatten()
.filter { !it.drawn }
.sumOf { it.number }
private fun isColumnBing(): Boolean {
return boardByColumn.any { column -> column.all { it.drawn } }
}
private fun isRowBing(): Boolean {
return board.any { row -> row.all { it.drawn } }
}
}
private data class BingoBoardNumber(
var number: Int,
var drawn: Boolean = false
)
| 0 | Kotlin | 0 | 0 | d88df7529665b65617334d84b87762bd3ead1323 | 2,988 | advent-of-code | Apache License 2.0 |
codeforces/kotlinheroes2/g.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes2
private fun solve() {
val n = readInt()
val flag = readInts()
val want = readInts()
val changed = flag.zip(want) { a, b -> a != b }
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (a, b) = readInts().map { it - 1 }
nei[a].add(b)
nei[b].add(a)
}
val w = changed.indexOfFirst { it }
if (w == -1) return println("Yes\n0")
val p = MutableList(n) { 0 }
val u = dfs(nei, p, changed, w, -1).second
val v = dfs(nei, p, changed, u, -1).second
val path = mutableListOf(v)
while (path.last() != u) path.add(p[path.last()])
println(check(flag, want, path) ?: check(flag, want, path.reversed()) ?: "No")
}
private fun check(flag: List<Int>, want: List<Int>, path: List<Int>): String? {
val f = flag.toMutableList()
val save = f[path.first()]
for ((a, b) in path.zipWithNext()) {
f[a] = f[b]
}
f[path.last()] = save
return "Yes\n${path.size}\n${path.map { it + 1 }.joinToString(" ")}".takeIf { f == want }
}
private fun dfs(nei: List<List<Int>>, p: MutableList<Int>, cool: List<Boolean>, v: Int, parent: Int): Pair<Int, Int> {
var best = if (cool[v]) 0 to v else -nei.size to -1
p[v] = parent
for (u in nei[v].minus(parent)) {
val (dist, vertex) = dfs(nei, p, cool, u, v)
if (dist + 1 > best.first) best = dist + 1 to vertex
}
return best
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,544 | competitions | The Unlicense |
src/Day09.kt | armandmgt | 573,595,523 | false | {"Kotlin": 47774} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
data class State(val headPos: Pair<Int, Int>, val tailNodes: List<Pair<Int, Int>>)
fun follow(head: Int, tail: Int, headOther: Int, tailOther: Int): Pair<Int, Int> {
// If tail is 2 squares away from head, move in direction of head
if (abs(head - tail) >= 2) {
val mainChange = (head - tail).sign
// Move along other axis too if not same position on main axis
val otherChange = if (abs(headOther - tailOther) == 1) {
headOther - tailOther
} else 0
return Pair(mainChange, otherChange)
}
return Pair(0, 0)
}
fun move(state: State, visited: MutableSet<Pair<Int, Int>>, dir: Direction, steps: Int): State {
return (0 until steps).fold(state) { s, _ ->
val newHeadPos = when (dir) {
Direction.NORTH -> Pair(s.headPos.first, s.headPos.second + 1)
Direction.SOUTH -> Pair(s.headPos.first, s.headPos.second - 1)
Direction.WEST -> Pair(s.headPos.first - 1, s.headPos.second)
Direction.EAST -> Pair(s.headPos.first + 1, s.headPos.second)
}
var prevNode = newHeadPos
val newTailNodes = s.tailNodes.map { tailNode ->
var newTailPosX = tailNode.first
var newTailPosY = tailNode.second
follow(prevNode.first, tailNode.first, prevNode.second, tailNode.second).also {
newTailPosX += it.first
newTailPosY += it.second
}
follow(prevNode.second, tailNode.second, prevNode.first, tailNode.first).also {
newTailPosY += it.first
newTailPosX += it.second
}
Pair(newTailPosX, newTailPosY).also { prevNode = it }
}
visited.add(newTailNodes.last())
State(newHeadPos, newTailNodes)
}
}
// fun printState(it: State) {
// for (y in -16 until 5) {
// for (x in -11 until 15) {
// print(
// when {
// it.headPos.first == x && it.headPos.second == y -> 'H'
// it.tailNodes.contains(Pair(x, y)) -> '0' + it.tailNodes.indexOf(Pair(x, y))
// else -> '.'
// }
// )
// }
// print('\n')
// }
// println()
// }
fun parseMotions(input: List<String>, state: State): Int {
val visited = mutableSetOf<Pair<Int, Int>>()
input.fold(state) { s, motion ->
val dir = Direction.from(motion[0])
val steps = motion.substringAfter(" ").toInt()
move(s, visited, dir, steps)
}
return visited.size
}
fun part1(input: List<String>): Int {
val state = State(Pair(0, 0), listOf(Pair(0, 0)))
return parseMotions(input, state)
}
fun part2(input: List<String>): Int {
val state = State(Pair(0, 0), List(9) { Pair(0, 0) })
return parseMotions(input, state)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("resources/Day09_test")
check(part1(testInput) == 13)
val input = readInput("resources/Day09")
println(part1(input))
val testInput2 = readInput("resources/Day09_test2")
check(part2(testInput2) == 36)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 0d63a5974dd65a88e99a70e04243512a8f286145 | 3,527 | advent_of_code_2022 | Apache License 2.0 |
src/Day07.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | import java.util.Stack
import java.util.function.Predicate
fun main() {
val root = Dir("/")
val ditStack = Stack<Dir>().apply { add(root) }
fun part1() {
root.filterSize {
it <= 100000
}.sum().log("part1")
}
fun part2() {
val spaceLeft = 70000000 - root.size
root.filterSize {
it + spaceLeft > 30000000
}.min().log("part2")
}
val input = readInput("Day07", "\n$").drop(1)
input.forEach { cmdAndOutput ->
val split = cmdAndOutput.trim().split("\n")
val cmd = split.first().trim().split(" ")
when (cmd.first()) {
"cd" -> {
if (cmd[1] == "..") ditStack.pop()
else ditStack.push(ditStack.peek().getDir(cmd[1]))
}
"ls" -> ditStack.peek().apply { split.drop(1).forEach { n -> add(n) } }
}
}
part1()
part2()
}
sealed interface Node {
val size: Long
}
data class Dir(val name: String, val nodes: MutableList<Node> = mutableListOf()) : Node {
companion object {
fun from(s: String) = Dir(s.removePrefix("dir "))
}
fun add(node: String) {
if (node.startsWith("dir ")) {
from(node)
} else {
File.from(node)
}.let { nodes.add(it) }
}
fun getDir(name: String) = nodes.filterIsInstance<Dir>().first { n -> n.name == name }
override val size: Long
get() = nodes.sumOf { it.size }
fun filterSize(predicate: Predicate<Long>): List<Long> {
return nodes.filterIsInstance<Dir>()
.map { it.size }
.filter { predicate.test(it) }
.toList() +
nodes.filterIsInstance<Dir>()
.flatMap { it.filterSize(predicate) }
}
}
data class File(val name: String, override val size: Long) : Node {
companion object {
fun from(s: String) = s.split(" ").let { File(it[1], it.first().toLong()) }
}
}
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 1,989 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | import java.util.ArrayDeque
/**
* [Day12](https://adventofcode.com/2022/day/12)
*/
fun main() {
fun toGrid(input: List<String>): Array<Array<Char>> = input.map {
it.toCharArray().toTypedArray()
}.toTypedArray()
fun bfs(
grid: Array<Array<Char>>,
start: Pair<Int, Int>,
costs: Array<Array<Int>>,
comparator: (current: Char, next: Char) -> Boolean
) {
val height = grid.size
val width = grid[0].size
val queue = ArrayDeque(listOf(start))
while (queue.isNotEmpty()) {
val (y, x) = queue.removeFirst()
listOf(
// left
y to x - 1,
// up
y - 1 to x,
// right
y to x + 1,
// down
y + 1 to x,
).filter { (ny, nx) ->
ny in 0 until height && nx in 0 until width
}.forEach { (ny, nx) ->
if (comparator(grid[y][x], grid[ny][nx]) && costs[y][x] + 1 < costs[ny][nx]) {
costs[ny][nx] = costs[y][x] + 1
queue.add(ny to nx)
}
}
}
}
fun calcCostMap(
grid: Array<Array<Char>>,
indexS: Pair<Int, Int>,
indexE: Pair<Int, Int>,
startSelector: (indexS: Pair<Int, Int>, indexE: Pair<Int, Int>) -> Pair<Int, Int>,
comparator: (current: Char, next: Char) -> Boolean,
): Array<Array<Int>> {
val start = startSelector(indexS, indexE)
grid[indexS.first][indexS.second] = 'a'
grid[indexE.first][indexE.second] = 'z'
val costs = Array(grid.size) {
Array(grid[0].size) { 100_000_000 }
}.also {
it[start.first][start.second] = 0
}
bfs(grid, start, costs, comparator)
return costs
}
fun part1(input: List<String>): Int {
val grid = toGrid(input)
val indexS = input.joinToString(separator = "").indexOf('S').let {
it / grid[0].size to it % grid[0].size
}
val indexE = input.joinToString(separator = "").indexOf('E').let {
it / grid[0].size to it % grid[0].size
}
val costs = calcCostMap(
grid, indexS, indexE,
startSelector = { s, _ -> s },
comparator = { current, next -> next - current <= 1 }
)
return costs[indexE.first][indexE.second]
}
fun part2(input: List<String>): Int {
val grid = toGrid(input)
val indexS = input.joinToString(separator = "").indexOf('S').let {
it / grid[0].size to it % grid[0].size
}
val indexE = input.joinToString(separator = "").indexOf('E').let {
it / grid[0].size to it % grid[0].size
}
val costs = calcCostMap(
grid, indexS, indexE,
startSelector = { _, e -> e },
comparator = { current, next -> current - next <= 1 }
)
return grid.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, c ->
if (c == 'a') costs[y][x] else null
}
}.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 3,542 | aoc-in-kotlin-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/year2021/Day03.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2021
private const val ONE = '1'
private const val ZERO = '0'
private fun part1(input: List<String>): Int {
val mostCommonBit = findMostCommonBit(input)
val gammaRate = Integer.valueOf(mostCommonBit, 2)
val leastCommonBit = reverse(mostCommonBit)
val epsilonRate = Integer.valueOf(leastCommonBit, 2)
return gammaRate * epsilonRate
}
private fun findMostCommonBit(input: List<String>): String {
if (input.isEmpty()) {
throw RuntimeException("Input shouldn't be empty")
}
val mostCommonBits = Array(input[0].length) { 0 }
for (number in input) {
number.forEachIndexed { index, bit ->
when (bit) {
ONE -> mostCommonBits[index]++
else -> mostCommonBits[index]--
}
}
}
return mostCommonBits
.map { if (it > 0) ONE else ZERO }
.joinToString(separator = "")
}
private fun reverse(input: String): String {
return input
.toCharArray()
.map { if (it == ONE) ZERO else ONE }
.joinToString(separator = "")
}
private fun part2(input: List<String>): Int {
val oxygenGeneratorRating = oxygenGeneratorRating(input)
val co2ScrubberRating = co2ScrubberRating(input)
return oxygenGeneratorRating * co2ScrubberRating
}
private fun oxygenGeneratorRating(input: List<String>): Int {
return ratingCalculator(input, ::getMostCommonBitForPosition)
}
private fun co2ScrubberRating(input: List<String>): Int {
return ratingCalculator(input, ::getLeastCommonBitForPosition)
}
private fun ratingCalculator(input: List<String>, extractBit: (List<String>, Int) -> Char): Int {
var rating: Int? = null
var position = 0
var data = input.toList()
while (rating == null && position < input.size) {
val bit = extractBit(data, position)
data = extractDataByBitInPosition(data, bit, position)
position++
if (data.size == 1) {
rating = Integer.valueOf(data[0], 2)
}
}
return rating!!
}
private fun getMostCommonBitForPosition(input: List<String>, position: Int): Char {
val counter = input.fold(0) { sum, number ->
if (number[position] == ONE) sum + 1 else sum - 1
}
return if (counter >= 0) ONE else ZERO
}
private fun getLeastCommonBitForPosition(input: List<String>, position: Int): Char {
val mostCommonBit = getMostCommonBitForPosition(input, position)
return if (mostCommonBit == ZERO) ONE else ZERO
}
private fun extractDataByBitInPosition(data: List<String>, mostCommonBit: Char, position: Int): List<String> {
return data.filter { it[position] == mostCommonBit }.toList()
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 198)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 2,927 | advent-of-code | MIT License |
src/Day02.kt | ralstonba | 573,072,217 | false | {"Kotlin": 4128} | fun main() {
val mapping = mapOf(
"A" to RPSMove.ROCK,
"B" to RPSMove.PAPER,
"C" to RPSMove.SCISSORS,
"X" to RPSMove.ROCK,
"Y" to RPSMove.PAPER,
"Z" to RPSMove.SCISSORS
)
val beats = mapOf(
RPSMove.ROCK to RPSMove.SCISSORS,
RPSMove.PAPER to RPSMove.ROCK,
RPSMove.SCISSORS to RPSMove.PAPER
)
fun getMoves(input: String): Pair<RPSMove, RPSMove> {
return input.split(" ")
.map { mapping.getValue(it) }
.zipWithNext()
.single()
}
fun part1(input: List<String>): Int {
return input.asSequence()
.map {
val (theirs, ours) = getMoves(it)
if (ours == theirs) {
3 + ours.score
} else if (beats.getValue(ours) == theirs) {
6 + ours.score
} else {
ours.score
}
}
.sum()
}
fun part2(input: List<String>): Int {
return 0
}
val testInput = readInput("Day02TestInput")
check(part1(testInput) == 15)
// Solve Part 1
val input = readInput("Day02Input")
println("Part 1 solution: ${part1(input)}")
// Test with provided example
// check(part2(testInput, 3) == 45_000)
// Solve Part 2
println("Part 2 solution: ${part2(input)}")
}
enum class RPSMove(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3)
}
| 0 | Kotlin | 0 | 0 | 93a8ba96db519f4f3d42e2b4148614969faa79b1 | 1,489 | aoc-2022 | Apache License 2.0 |
src/Day11.kt | jordan-thirus | 573,476,470 | false | {"Kotlin": 41711} | fun main() {
fun processRound(monkeys: List<Monkey>, reduceWorryLevel: (Long) -> Long) {
for (monkey in monkeys) {
while (monkey.items.any()) {
monkey.throughput += monkey.items.size
for(item in monkey.items) {
val newWorryLevel = reduceWorryLevel(monkey.updateWorryLevel(item))
if (newWorryLevel % monkey.testValue == 0L) {
monkeys[monkey.monkeyIfTrue].items.add(newWorryLevel)
} else {
monkeys[monkey.monkeyIfFalse].items.add(newWorryLevel)
}
}
monkey.items.clear()
}
}
}
fun part1(input: List<String>): Int {
val monkeys = input.chunked(7).map { Monkey.build(it) }
repeat(20) {
processRound(monkeys) { it / 3 }
}
return monkeys
.map { it.throughput }
.sortedDescending()
.let { it[0] * it[1] }
}
fun part2(input: List<String>): Long {
val monkeys = input.chunked(7).map { Monkey.build(it) }
val reduceWorryLevel: Long = monkeys.map { m -> m.testValue.toLong() }.reduce(Long::times)
repeat(10000) {
processRound(monkeys) { item -> item % reduceWorryLevel }
// if (it + 1 in setOf(1, 20, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000)) {
// println("Round ${it + 1}: $monkeys")
// }
}
return monkeys
.map { it.throughput.toLong() }
.sortedDescending()
.let { it[0] * it[1] }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
class Monkey(
val testValue: Int, val monkeyIfTrue: Int, val monkeyIfFalse: Int,
startingItems: List<Long>, operation: List<String>
) {
var throughput: Int = 0
val items: MutableList<Long>
private val modifyOperation: Operation
private val modifyValue: String
init {
items = startingItems.toMutableList()
modifyOperation = Operation.get(operation[0])
modifyValue = operation[1]
}
override fun toString(): String {
return "Throughput $throughput"
}
fun updateWorryLevel(item: Long): Long {
return when (modifyOperation) {
Operation.ADD -> item + modifyValue.toInt()
Operation.MULTIPLY -> when (modifyValue) {
"old" -> item * item
else -> item * modifyValue.toInt()
}
else -> throw UnsupportedOperationException("Invalid operation")
}
}
companion object {
fun build(input: List<String>): Monkey {
val startingItems = input[1].removePrefix(" Starting items: ").split(", ").map { it.toLong() }
val operation = input[2].split(" ").takeLast(2)
val testValue = input[3].split(" ").last().toInt()
val ifTrue = input[4].split(" ").last().toInt()
val ifFalse = input[5].split(" ").last().toInt()
return Monkey(testValue, ifTrue, ifFalse, startingItems, operation)
}
}
}
| 0 | Kotlin | 0 | 0 | 59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e | 3,385 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | eps90 | 574,098,235 | false | {"Kotlin": 9738} | import java.security.InvalidParameterException
enum class FigureType(val score: Int) {
Rock(1),
Paper(2),
Scissors(3),
}
enum class MatchResult(val score: Int) {
Loss(0),
Draw(3),
Win(6);
fun opposite(): MatchResult {
return when (this) {
Loss -> Win
Win -> Loss
else -> Draw
}
}
companion object {
fun of(code: String): MatchResult {
val scoresMapping = mapOf(
"X" to Loss,
"Y" to Draw,
"Z" to Win
)
return scoresMapping[code] ?: throw InvalidParameterException()
}
}
}
typealias ScoreMap = Map<MatchResult, FigureType>
fun ScoreMap.reversed() = entries.associateBy({ it.value }) { it.key }
sealed class Figure(val type: FigureType, val scoreMap: ScoreMap) {
object Rock : Figure(
FigureType.Rock,
mapOf(
MatchResult.Win to FigureType.Scissors,
MatchResult.Loss to FigureType.Paper,
MatchResult.Draw to FigureType.Rock
)
)
object Paper : Figure(
FigureType.Paper, mapOf(
MatchResult.Win to FigureType.Rock,
MatchResult.Loss to FigureType.Scissors,
MatchResult.Draw to FigureType.Paper
)
)
object Scissors : Figure(
FigureType.Scissors, mapOf(
MatchResult.Win to FigureType.Paper,
MatchResult.Loss to FigureType.Rock,
MatchResult.Draw to FigureType.Scissors
)
)
fun matchResultWith(other: Figure): MatchResult {
return scoreMap.reversed()[other.type] ?: throw InvalidParameterException()
}
companion object {
fun of(char: String): Figure {
val figuresMapping = mapOf(
"A" to Rock,
"B" to Paper,
"C" to Scissors,
"X" to Rock,
"Y" to Paper,
"Z" to Scissors
)
return figuresMapping[char] ?: throw InvalidParameterException()
}
}
}
private fun <T> List<T>.destruct() = Pair(first(), last())
fun main() {
fun part1(input: List<String>): Int {
return input.asSequence().map { line ->
val (opponent, santa) = line.split(" ").map { Figure.of(it) }.destruct()
val battleResult = santa.matchResultWith(opponent)
val finalScore = santa.type.score + battleResult.score
finalScore
}.sum()
}
fun part2(input: List<String>): Int {
return input.asSequence().map { line ->
val (opponentCode, matchResultCode) = line.split(" ").destruct()
val opponent = Figure.of(opponentCode)
val matchResult = MatchResult.of(matchResultCode)
val santaFigure = opponent.scoreMap[matchResult.opposite()]
val result = matchResult.score + (santaFigure?.score ?: 0)
result
}.sum()
}
val testInput = readInput("Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
println(part2(testInput))
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bbf58c512fddc0ef1112c3bee5e5c6d43f5aabc0 | 3,242 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | greg-burgoon | 573,074,283 | false | {"Kotlin": 120556} | fun main() {
class Node(elevation: Char) {
val elevation = elevation
var distance = Int.MAX_VALUE
var adjacentNodes = ArrayList<Node>()
fun canTraverseTo(other: Node): Boolean {
var currentElevation = this.elevation
if (this.elevation == 'S') {
currentElevation = 'a'
}
if (this.elevation == 'E') {
currentElevation = 'z'
}
var otherElevation = other.elevation
if (other.elevation == 'S') {
otherElevation = 'a'
}
if (other.elevation == 'E') {
otherElevation = 'z'
}
return otherElevation.code+1 >= currentElevation.code
}
}
fun getDistanceToStartNode(nodeMap: MutableList<MutableList<Node>>): Node {
nodeMap.forEachIndexed { row, nodes ->
nodes.forEachIndexed { column, node ->
var upNode = nodeMap.getOrNull(row - 1)?.get(column)
if (upNode != null && node.canTraverseTo(upNode)) {
node.adjacentNodes.add(upNode)
}
var downNode = nodeMap.getOrNull(row + 1)?.get(column)
if (downNode != null && node.canTraverseTo(downNode)) {
node.adjacentNodes.add(downNode)
}
var leftNode = nodeMap[row].getOrNull(column - 1)
if (leftNode != null && node.canTraverseTo(leftNode)) {
node.adjacentNodes.add(leftNode)
}
var rightNode = nodeMap[row].getOrNull(column + 1)
if (rightNode != null && node.canTraverseTo(rightNode)) {
node.adjacentNodes.add(rightNode)
}
}
}
var allNodes = nodeMap.flatten().toMutableList()
var startNode = allNodes.filter { it.elevation == 'S' }.first()
var endNode = allNodes.filter { it.elevation == 'E' }.first()
endNode.distance = 0
var stack = ArrayDeque<Node>()
stack.add(endNode)
while (stack.isNotEmpty()) {
var currentNode = stack.removeFirst()
currentNode.adjacentNodes.filter { it.distance > currentNode.distance + 1 }.forEach {
it.distance = currentNode.distance + 1
stack.add(it)
}
}
return startNode
}
fun part1(input: String): Int {
var nodeMap = mutableListOf<MutableList<Node>>()
input.split("\n")
.forEachIndexed { row, s ->
nodeMap.add(mutableListOf<Node>())
s.forEachIndexed { column, c ->
nodeMap[row].add(Node(c))
}
}
var startNode = getDistanceToStartNode(nodeMap)
return startNode.distance
}
fun part2(input: String): Int {
var nodeMap = mutableListOf<MutableList<Node>>()
input.split("\n")
.forEachIndexed { row, s ->
nodeMap.add(mutableListOf<Node>())
s.forEachIndexed { column, c ->
nodeMap[row].add(Node(c))
}
}
var startNode = getDistanceToStartNode(nodeMap)
return nodeMap.flatten().filter { it.elevation == 'a' || it.elevation == 'S' }.sortedByDescending { it.distance }.last().distance
}
val testInput = readInput("Day12_test")
val output = part1(testInput)
check(output == 31)
val outputTwo = part2(testInput)
check(outputTwo == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 74f10b93d3bad72fa0fc276b503bfa9f01ac0e35 | 3,671 | aoc-kotlin | Apache License 2.0 |
src/Day19.kt | mikrise2 | 573,939,318 | false | {"Kotlin": 62406} | import java.util.*
import kotlin.math.ceil
data class Robot(
val oreGet: Int,
val clayGet: Int,
val obsidianGet: Int,
val geodeGet: Int,
val ore: Int,
val clay: Int,
val obsidian: Int
)
data class Plan(
val id: Int,
val robots: List<Robot>
)
data class State(
val remaining: Int,
val oreRobots: Int,
val clayRobots: Int,
val obsidianRobots: Int,
val geodeRobots: Int,
val ore: Int,
val clay: Int,
val obsidian: Int,
val geodes: Int
)
fun bestWay(state: State, process: Int, timeBudget: Int): Boolean {
val timeLeft = timeBudget - state.remaining
val potentialProduction = (0 until timeLeft).sumOf { it + state.geodeRobots }
return state.geodes + potentialProduction > process
}
fun state(robot: Robot, state: State): State {
val time = maxOf(
if (robot.ore <= state.ore) 1 else ceil((robot.ore - state.ore) / state.oreRobots.toFloat()).toInt() + 1,
if (robot.clay <= state.clay) 1 else ceil((robot.clay - state.clay) / state.clayRobots.toFloat()).toInt() + 1,
if (robot.obsidian <= state.obsidian) 1 else ceil((robot.obsidian - state.obsidian) / state.obsidianRobots.toFloat()).toInt() + 1
)
return State(
state.remaining + time,
state.oreRobots + robot.oreGet,
state.clayRobots + robot.clayGet,
state.obsidianRobots + robot.obsidianGet,
state.geodeRobots + robot.geodeGet,
state.ore - robot.ore + time * state.oreRobots,
state.clay - robot.clay + time * state.clayRobots,
state.obsidian - robot.obsidian + time * state.obsidianRobots,
state.geodes + time * state.geodeRobots
)
}
fun nextStates(state: State, plan: Plan, remaining: Int): List<State> {
val nextStates = mutableListOf<State>()
if (state.remaining < remaining) {
if (plan.robots.maxOf { it.ore } > state.oreRobots && state.ore > 0) {
nextStates += state(plan.robots[0], state)
}
if (plan.robots.maxOf { it.clay } > state.clayRobots && state.ore > 0) {
nextStates += state(plan.robots[1], state)
}
if (plan.robots.maxOf { it.obsidian } > state.obsidianRobots && state.ore > 0 && state.clay > 0) {
nextStates += state(plan.robots[2], state)
}
if (state.ore > 0 && state.obsidian > 0) {
nextStates += state(plan.robots[3], state)
}
}
return nextStates.filter { it.remaining <= remaining }
}
fun geodes(plan: Plan, time: Int): Int {
var result = 0
val states = LinkedList(listOf(State(1, 1, 0, 0, 0, 1, 0, 0, 0)).sortedBy { it.geodes })
while (states.isNotEmpty()) {
val state = states.poll()
if (bestWay(state, result, time)) {
nextStates(state, plan, time).forEach {
states.add(it)
}
}
result = maxOf(result, state.geodes)
}
return result
}
fun main() {
fun part1(input: List<String>): Int =
input.map {
val split = it.split(" ")
val oreRobot = Robot(1, 0, 0, 0, split[6].toInt(), 0, 0)
val clayRobot = Robot(0, 1, 0, 0, split[12].toInt(), 0, 0)
val obsidianRobot = Robot(0, 0, 1, 0, split[18].toInt(), split[21].toInt(), 0)
val geodeRobot = Robot(0, 0, 0, 1, split[27].toInt(), 0, split[30].toInt())
Plan(
split[1].substring(0, split[1].lastIndex).toInt(),
listOf(oreRobot, clayRobot, obsidianRobot, geodeRobot)
)
}.sumOf { it.id * geodes(it, 24) }
fun part2(input: List<String>): Int {
var result = 1
input.map {
val split = it.split(" ")
val oreRobot = Robot(1, 0, 0, 0, split[6].toInt(), 0, 0)
val clayRobot = Robot(0, 1, 0, 0, split[12].toInt(), 0, 0)
val obsidianRobot = Robot(0, 0, 1, 0, split[18].toInt(), split[21].toInt(), 0)
val geodeRobot = Robot(0, 0, 0, 1, split[27].toInt(), 0, split[30].toInt())
Plan(
split[1].substring(0, split[1].lastIndex).toInt(),
listOf(oreRobot, clayRobot, obsidianRobot, geodeRobot)
)
}.take(3).map { geodes(it, 32) }.forEach { result *= it }
return result
}
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8 | 4,369 | Advent-of-code | Apache License 2.0 |
src/Day01.kt | GreyWolf2020 | 573,580,087 | false | {"Kotlin": 32400} | import java.lang.Integer.max
fun main() {
fun part1(input: List<String>): Int {
val sumIndex = 0
val maxSumIndex = 1
val zeroCalorie = 0
return input.map {
it.toIntOrNull()
}.foldRight(intArrayOf(0, 0)) { calorieOrNull, acc ->
calorieOrNull ?.let { calorie ->
intArrayOf(acc[sumIndex] + calorie, acc[maxSumIndex])
} ?: run {
intArrayOf(zeroCalorie, max(acc[maxSumIndex], acc[sumIndex]))
}
}[maxSumIndex]
}
fun part2(input: List<String>): Int {
val sumIndex = 0
val highSumIndex = 1
val highHighSumIndex = 2
val highHighHighSumIndex = 3
val zeroCalorie = 0
return input.map {
it.toIntOrNull()
}.foldRight(intArrayOf(0, 0, 0, 0)) { calorieOrNull, acc ->
calorieOrNull?.let { calorie ->
intArrayOf(acc[sumIndex] + calorie, acc[highSumIndex], acc[highHighSumIndex], acc[highHighHighSumIndex])
} ?: run {
when {
acc[sumIndex] > acc[highSumIndex] && acc[sumIndex] < acc[highHighSumIndex] -> intArrayOf(zeroCalorie, acc[sumIndex], acc[highHighSumIndex], acc[highHighHighSumIndex])
acc[sumIndex] > acc[highHighSumIndex] && acc[sumIndex] < acc[highHighHighSumIndex] -> intArrayOf(zeroCalorie, acc[highHighSumIndex], acc[sumIndex], acc[highHighHighSumIndex])
acc[sumIndex] > acc[3] -> intArrayOf(zeroCalorie, acc[highHighSumIndex], acc[highHighHighSumIndex], acc[sumIndex])
else -> intArrayOf(zeroCalorie, acc[highSumIndex], acc[highHighSumIndex], acc[highHighHighSumIndex])
}
}
}
.drop(1)
.sum()
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// check(part1(testInput) == 24000)
// check(part2(testInput) == 45000)
//
// val input = readInput("Day01")
// println(part1(input))
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 498da8861d88f588bfef0831c26c458467564c59 | 2,097 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | gsalinaslopez | 572,839,981 | false | {"Kotlin": 21439} | enum class Moves(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3)
}
enum class Results(val points: Int) {
WIN(6),
DRAW(3),
LOSE(0)
}
val modesMap = mapOf(
"A" to Moves.ROCK, "X" to Moves.ROCK,
"B" to Moves.PAPER, "Y" to Moves.PAPER,
"C" to Moves.SCISSORS, "Z" to Moves.SCISSORS,
)
val resultsMap = mapOf(
"X" to Results.LOSE,
"Y" to Results.DRAW,
"Z" to Results.WIN
)
fun main() {
fun part1(input: List<String>): Int = input.sumOf {
val move = it.split(" ")
val opMove = modesMap[move.first()]!!
val myMove = modesMap[move.last()]!!
myMove.points + when (myMove) {
Moves.ROCK -> when (opMove) {
Moves.ROCK -> Results.DRAW.points
Moves.PAPER -> Results.LOSE.points
Moves.SCISSORS -> Results.WIN.points
}
Moves.PAPER -> when (opMove) {
Moves.ROCK -> Results.WIN.points
Moves.PAPER -> Results.DRAW.points
Moves.SCISSORS -> Results.LOSE.points
}
Moves.SCISSORS -> when (opMove) {
Moves.ROCK -> Results.LOSE.points
Moves.PAPER -> Results.WIN.points
Moves.SCISSORS -> Results.DRAW.points
}
}
}
fun part2(input: List<String>): Int = input.sumOf {
val move = it.split(" ")
val opMove = modesMap[move.first()]!!
val result = resultsMap[move.last()]!!
result.points + when (opMove) {
Moves.ROCK -> when (result) {
Results.WIN -> Moves.PAPER.points
Results.DRAW -> Moves.ROCK.points
Results.LOSE -> Moves.SCISSORS.points
}
Moves.PAPER -> when (result) {
Results.WIN -> Moves.SCISSORS.points
Results.DRAW -> Moves.PAPER.points
Results.LOSE -> Moves.ROCK.points
}
Moves.SCISSORS -> when (result) {
Results.WIN -> Moves.ROCK.points
Results.DRAW -> Moves.SCISSORS.points
Results.LOSE -> Moves.PAPER.points
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 041c7c3716bfdfdf4cc89975937fa297ea061830 | 2,457 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/day07/day07.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day07
import readInput
private const val THRESHOLD_PART1 = 100000
private const val TOTAL_DISC_SIZE = 70000000
private const val SIZE_FOR_UPDATE = 30000000
data class Directory(
val name: String,
val files: MutableSet<Int>,
val dirs: MutableMap<String, Directory>,
val parent: Directory? = null
) {
val totalSize: Int
get() = files.sum() + dirs.values.sumOf { it.totalSize }
val allDirectories: List<Directory>
get() = listOf(this) + dirs.values.flatMap { it.allDirectories }
private fun root(): Directory = parent?.root() ?: this
fun changeInto(arg: String): Directory {
return when (arg) {
"/" -> root()
".." -> parent ?: root()
else -> dirs[arg] ?: Directory(arg, mutableSetOf(), mutableMapOf(), this)
}
}
override fun hashCode(): Int = name.hashCode()
override fun equals(other: Any?): Boolean = if (other is Directory) name == other.name else false
}
fun main() {
val input = readInput("main/day07/Day07")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
return input.parseDirectories().allDirectories
.filter { it.totalSize <= THRESHOLD_PART1 }
.sumOf { it.totalSize }
}
fun part2(input: List<String>): Int {
val root = input.parseDirectories()
return root.allDirectories.filter {
it.totalSize >= SIZE_FOR_UPDATE - (TOTAL_DISC_SIZE - root.totalSize)
}.minBy { it.totalSize }.totalSize
}
fun List<String>.parseDirectories(): Directory {
val root = Directory("/", mutableSetOf(), mutableMapOf())
var current = root
forEach { line ->
when {
line.isCd() -> current = current.changeInto(line.lastArg())
line.isDir() -> current.dirs[line.lastArg()] = Directory(line.lastArg(), mutableSetOf(), mutableMapOf(), current)
line.isFile() -> current.files.add(line.firstArg().toInt())
}
}
return root
}
private fun String.lastArg() = split(" ").last()
private fun String.firstArg() = split(" ").first()
fun String.isCd() = startsWith("$ cd")
fun String.isFile() = first().isDigit()
fun String.isDir() = startsWith("dir")
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 2,211 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | Loahrs | 574,175,046 | false | {"Kotlin": 7516} | fun main() {
fun part1(input: List<String>): Int {
return input.asSequence().map {
val (opponentMove, playerMove) = it.split(" ")
val opponentShape = getShape(opponentMove)
val playerShape = getShape(playerMove)
val outcome = calculateOutcome(opponentShape, playerShape)
return@map outcome.points + playerShape.points
}.sum()
}
fun part2(input: List<String>): Int {
return input.asSequence().map {
val (opponentMove, desiredOutcomeHint) = it.split(" ")
val opponentShape = getShape(opponentMove)
val desiredOutcome = desiredOutcome(desiredOutcomeHint)
return@map desiredOutcome.points + requiredShapeForOutcome(opponentShape, desiredOutcome).points
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
fun getShape(input : String) : Shape {
return when(input) {
"A","X" -> Shape.ROCK
"B","Y" -> Shape.PAPER
"C","Z" -> Shape.SCISSORS
else -> throw Exception("Illegal Symbol")
}
}
fun requiredShapeForOutcome(opponentShape: Shape, desiredOutcome: Outcome): Shape {
return when(desiredOutcome) {
Outcome.WIN -> Shape.values().find { it beats opponentShape }!!
Outcome.LOSS -> Shape.values().find { opponentShape beats it }!!
Outcome.DRAW -> opponentShape
}
}
fun desiredOutcome(input : String) : Outcome {
return when(input) {
"X" -> Outcome.LOSS
"Y" -> Outcome.DRAW
"Z" -> Outcome.WIN
else -> throw Exception("Illegal Symbol")
}
}
fun calculateOutcome(opponentShape : Shape, playerShape : Shape) : Outcome {
return when {
playerShape beats opponentShape -> Outcome.WIN
opponentShape beats playerShape -> Outcome.LOSS
else -> Outcome.DRAW
}
}
enum class Outcome(val points: Int) {
WIN(6), DRAW(3), LOSS(0)
}
enum class Shape(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
infix fun beats(otherShape: Shape) : Boolean {
val beatenByThis = when(this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
return beatenByThis == otherShape
}
} | 0 | Kotlin | 0 | 0 | b1ff8a704695fc6ba8c32a227eafbada6ddc0d62 | 2,436 | aoc-2022-in-kotlin | Apache License 2.0 |
src/aoc2022/Day13.kt | Playacem | 573,606,418 | false | {"Kotlin": 44779} | package aoc2022
import utils.readInputText
object Day13 {
fun parseInput(text: String): List<List<String>> = text.split("\n\n").map { it.trim().split("\n") }
sealed class Structure : Comparable<Structure> {
data class AList(val list: List<Structure>) : Structure() {
override fun compareTo(other: Structure): Int {
if (other is I) {
return this.compareTo(other.toList())
} else {
val otherAList = other as AList
var i = 0
while(i < this.list.size && i < otherAList.list.size) {
val cmp = this.list[i].compareTo(otherAList.list[i])
if (cmp != 0) {
return cmp
}
i++
}
return otherAList.list.size - this.list.size
}
}
override fun toString(): String = list.toString()
}
data class I(val value: Int) : Structure() {
fun toList() = AList(list = listOf(this))
override fun compareTo(other: Structure): Int {
return if (other is I) {
other.value - this.value
} else {
this.toList().compareTo(other)
}
}
override fun toString(): String = value.toString()
}
}
fun stringAsStructure(line: String): Structure {
val stack = ArrayDeque<Structure>()
stack.addLast(Structure.AList(listOf()))
var numberString = ""
fun addIntToStack() {
val number = numberString.toIntOrNull()
if (number != null) {
val top = stack.removeLast() as Structure.AList
stack.addLast(Structure.AList(top.list + Structure.I(number)))
}
numberString = ""
}
line.forEach { c ->
when(c) {
'[' -> {
addIntToStack()
stack.addLast(Structure.AList(listOf()))
}
']' -> {
addIntToStack()
val top = stack.removeLast()
val next = stack.removeLast() as Structure.AList
stack.addLast(Structure.AList(list = next.list + top))
}
',' -> {
addIntToStack()
}
else -> {
numberString += c
}
}
}
return stack.removeLast()
}
}
fun main() {
val (year, day) = 2022 to "Day13"
fun part1(input: String): Int {
val parsed = Day13.parseInput(input)
var sum = 0
parsed.forEachIndexed { index, strings ->
val (left, right) = strings.map(Day13::stringAsStructure)
val compResult = left.compareTo(right)
if (compResult > 0) {
sum += (index + 1)
}
}
return sum
}
fun part2(input: String): Int {
val decoderKey1 = Day13.stringAsStructure("[[2]]")
val decoderKey2 = Day13.stringAsStructure("[[6]]")
val parsed = Day13.parseInput(input)
val structures = parsed.flatMap { it.map(Day13::stringAsStructure) } + decoderKey1 + decoderKey2
val sorted = structures.sortedWith { left, right ->
val res = left.compareTo(right)
res * -1
}
val left = sorted.indexOf(decoderKey1) + 1
val right = sorted.indexOf(decoderKey2) + 1
return left * right
}
val testInput = readInputText(year, "${day}_test")
val input = readInputText(year, day)
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 13)
println(part1(input))
check(part2(testInput) == 140)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4ec3831b3d4f576e905076ff80aca035307ed522 | 3,968 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day11/Day11.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package day11
// 36:12
fun solveA(input: List<String>) = parseMonkeys(input).also {
repeat(20) { _ ->
it.forEach { m -> m.takeTurn(it) }
}
}.calcMonkeyBusiness()
//13:32
fun solveB(input: List<String>) = parseMonkeys(input).also {
val superModulo = it.map { monkey -> monkey.test.divisibleBy }.reduce(Long::times)
repeat(10000) { _ ->
it.forEach { m -> m.takeTurn(it, superModulo) }
}
}.calcMonkeyBusiness()
fun parseMonkeys(input: List<String>) = input
.chunked(7)
.mapIndexed { id, strings ->
val startingItems = strings[1].split(" ").drop(4).joinToString("").split(",").map { it.toLong() }
val inspection = Inspection(strings[2].split(" ").drop(6))
val test = Test(listOf(strings[3], strings[4], strings[5]).map { it.split(" ").last() })
Monkey(id, startingItems.toMutableList(), inspection, test)
}
data class Inspection(val operator: String, val operationValue: Long?) {
constructor(input: List<String>) : this(input.first(), input.last().toLongOrNull())
fun run(worryLevel: Long): Long {
val value = operationValue ?: worryLevel
return if (operator == "*") worryLevel * value else worryLevel + value
}
}
data class Test(val divisibleBy: Long, val trueTarget: Int, val falseTarget: Int) {
constructor(input: List<String>) : this(input[0].toLong(), input[1].toInt(), input[2].toInt())
fun run(worryLevel: Long) = if (worryLevel % divisibleBy == 0L) trueTarget else falseTarget
}
data class Monkey(
val id: Int,
var items: MutableList<Long>,
val inspection: Inspection,
val test: Test,
) {
var inspections = 0
fun takeTurn(monkeys: List<Monkey>, superModulo: Long? = null) = items.forEach {
inspections++
val afterInspection = inspection.run(it)
val result = if (superModulo == null) afterInspection.floorDiv(3) else afterInspection % superModulo
val target = test.run(result)
monkeys[target].items.add(result)
}.also { items.clear() }
}
fun List<Monkey>.calcMonkeyBusiness() = this.map { it.inspections.toLong() }.sortedDescending().let { it[0] * it[1] }
//
//
//var superMod = mutableListOf<Int>()
//
//// 36:12
//fun solveA(input: List<String>): Long {
//
// val monkeys = parseMonkeys(input, isPartOne = true)
//
// repeat(20) {
// monkeys.forEach { m -> m.round(monkeys) }
// }
//
// val inspections = monkeys.map { it.inspections.toLong() }.sortedDescending()
// return inspections.first() * inspections[1]
//}
//
//fun parseMonkeys(input: List<String>, isPartOne: Boolean): List<Monkey> {
// val parseMonkeys = input.chunked(7)
//
// return parseMonkeys.mapIndexed { id, strings ->
// val startingItems = strings[1].split(" ").drop(4).joinToString("").split(",").map { it.toLong() }
// val inspectionInput = strings[2].split(" ").drop(6)
// val inspectionFn = parseInspection(inspectionInput.first(), inspectionInput.last())
// val divisibleBy = strings[3].split(" ").last()
// if (!isPartOne) superMod.add(divisibleBy.toInt())
// val trueTarget = strings[4].split(" ").last()
// val falseTarget = strings[5].split(" ").last()
// val testFn = parseTest(divisibleBy, trueTarget, falseTarget)
// Monkey(id, startingItems.toMutableList(), inspectionFn, testFn, isPartOne)
// }
//}
//
//fun parseInspection(operator: String, byString: String): (Long) -> Long {
//
// val isMultiply = operator == "*"
//
// val function: (old: Long) -> Long = {
// val by = byString.toLongOrNull() ?: it
// if (isMultiply) it * by
// else it + by
// }
//
// return function
//}
//
//fun parseTest(divisibleBy: String, trueTarget: String, falseTarget: String): (Long) -> Int {
// val function: (old: Long) -> Int = {
// if (it % divisibleBy.toLong() == 0L) trueTarget.toInt()
// else falseTarget.toInt()
// }
//
// return function
//}
//
//
////13:32
//fun solveB(input: List<String>): Long {
// val monkeys = parseMonkeys(input, isPartOne = false)
//
// repeat(10000) {
// monkeys.forEach { m -> m.round(monkeys) }
// }
//
// val inspections = monkeys.map { it.inspections.toLong() }.sortedDescending()
// return inspections.first() * inspections[1]
//}
//
//data class Monkey(
// val id: Int,
// var items: MutableList<Long>,
// val inspectionFn: (Long) -> Long,
// val testFn: (Long) -> Int,
// val isPartOne: Boolean
//) {
//
// var inspections = 0
// fun round(monkeys: List<Monkey>) {
// items.forEach {
// inspections++
// val afterInspection = inspectionFn(it)
// val result = if (isPartOne) afterInspection.floorDiv(3) else afterInspection % superMod.reduce(Int::times)
// val target = testFn(result)
// monkeys[target].items.add(result)
// }
// items.clear()
// }
//}
| 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 4,933 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | import kotlin.streams.toList
fun main() {
fun flash(field: MutableList<MutableList<Int>>, flashed: Array<Array<Boolean>>, pos: Pair<Int, Int>) {
val i = pos.first
val j = pos.second
if (field[i][j] <= 9 || flashed[i][j]) return
flashed[i][j] = true
for (m in -1..1) {
for (n in -1..1) {
if (m == 0 && n == 0) continue
val ni = i + m
val nj = j + n
if (ni < 0 || ni >= field.size) continue
if (nj < 0 || nj >= field[ni].size) continue
field[ni][nj] += 1
if (field[ni][nj] > 9) flash(field, flashed, Pair(ni, nj))
}
}
}
fun part1(input: List<List<Int>>): Int {
var l = input//.map { it.toMutableList() }.toMutableList()
var out = 0
for (step in 1..100) {
val flashed = Array(10) { Array(10) { false } }
l = l.map { it.map { p -> p + 1 }.toMutableList() }.toMutableList()
for (i in input.indices) {
for (j in input.indices) {
flash(l, flashed, Pair(i, j))
}
}
out += flashed.sumOf { it.count { b -> b } }
l = l.map { it.map { p -> if (p > 9) 0 else p }.toMutableList() }.toMutableList()
// println("Step $step:")
// println(flashed.joinToString { booleans -> booleans.joinToString { b -> if (b) "#" else "." } + "\n" })
}
return out
}
fun part2(input: List<List<Int>>): Int {
var l = input.map { it.toMutableList() }.toMutableList()
for (step in 1..Int.MAX_VALUE) {
val flashed = Array(10) { Array(10) { false } }
l = l.map { it.map { p -> p + 1 }.toMutableList() }.toMutableList()
for (i in input.indices) {
for (j in input.indices) {
flash(l, flashed, Pair(i, j))
}
}
l = l.map { it.map { p -> if (p > 9) 0 else p }.toMutableList() }.toMutableList()
if (flashed.sumOf { it.count { b -> b } } == 100) return step
// println("Step $step:")
// println(flashed.joinToString { booleans -> booleans.joinToString { b -> if (b) "#" else "." } + "\n" })
}
return 0
}
fun preprocessing(input: String): List<List<Int>> {
return input.trim().split("\n").map { it.trim().toCharArray().map { c -> c.digitToInt() } }.toList()
}
val realInp = read_testInput("real11")
val testInp = read_testInput("test11")
// val testInp = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
// println("Test 1: ${part1(preprocessing(testInp))}")
// println("Real 1: ${part1(preprocessing(realInp))}")
println("-----------")
println("Test 2: ${part2(preprocessing(testInp))}")
println("Real 2: ${part2(preprocessing(realInp))}")
}
| 0 | Kotlin | 0 | 0 | 3e33ab078f8f5413fa659ec6c169cd2f99d0b374 | 2,968 | advent_of_code21_kotlin | Apache License 2.0 |
src/main/kotlin/day5/main.kt | janneri | 572,969,955 | false | {"Kotlin": 99028} | package day5
import util.readTestInput
data class Crate(val symbol: Char, val stackNumber: Int)
data class Move(val count: Int, val fromStack: Int, val toStack: Int)
data class GameInput(val moves: List<Move>, val crates: List<Crate>, val stackCount: Int) {
companion object {
/*
Input looks something like this:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
*/
fun parse(inputLines: List<String>): GameInput {
val moves = inputLines.takeLastWhile { it.isNotBlank() }.map { parseMove(it) }
val linesBeforeBlank = inputLines.takeWhile { it.isNotBlank() }
val stackCount = linesBeforeBlank.last().trim().last().digitToInt()
val crates = linesBeforeBlank.dropLast(1).map { parseCrates(it, stackCount) }.flatten()
return GameInput(moves, crates, stackCount)
}
private val moveRegex = Regex("""move (\d+) from (\d+) to (\d+)""")
fun parseMove(line: String): Move =
moveRegex.matchEntire(line)!!
.destructured
.let { (count, fromStack, toStack) ->
Move(count.toInt(), fromStack.toInt(), toStack.toInt())
}
// Parses a line such as "[Z] [M] [P]"
fun parseCrates(line: String, numberOfStacks: Int): List<Crate> {
val crates = mutableListOf<Crate>()
var currentCharIndex = 1 // first letter is at pos 1
for (stackNumber in 1 .. numberOfStacks) {
if (currentCharIndex < line.length && line[currentCharIndex].toString().isNotBlank()) {
crates.add(Crate(line[currentCharIndex], stackNumber))
}
currentCharIndex += 4 // there's a gap of 4 between each letter
}
return crates
}
}
}
fun playMoves(gameInput: GameInput, oneAtATimeMode: Boolean): String {
val stacks = gameInput.crates.groupBy { it.stackNumber }.toMutableMap()
gameInput.moves.forEach {move ->
val cratesToMove = stacks[move.fromStack]!!.take(move.count)
stacks[move.fromStack] = stacks[move.fromStack]!!.drop(move.count)
val cratesToInsert = if (oneAtATimeMode) cratesToMove.reversed() else cratesToMove
stacks[move.toStack] = cratesToInsert + stacks[move.toStack]!!
}
return stacks.keys.sorted().fold("") {
acc, stackNumber -> acc + stacks[stackNumber]?.first()?.symbol.toString()
}
}
fun main() {
// Solution for https://adventofcode.com/2022/day/5
// Downloaded the input from https://adventofcode.com/2022/day/5/input
val gameInput = GameInput.parse(readTestInput("day5"))
println(playMoves(gameInput, true)) // part1
println(playMoves(gameInput, false)) // part2
} | 0 | Kotlin | 0 | 0 | 1de6781b4d48852f4a6c44943cc25f9c864a4906 | 2,881 | advent-of-code-2022 | MIT License |
y2018/src/main/kotlin/adventofcode/y2018/Day22.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2018
import adventofcode.io.AdventSolution
import java.util.*
object Day22 : AdventSolution(2018, 22, "Mode Maze") {
override fun solvePartOne(input: String): Int {
val (depth, tx, ty) = parse(input)
val cave = buildMaze(depth, tx, ty)
cave[ty][tx] = 0
return cave.sumOf(IntArray::sum)
}
override fun solvePartTwo(input: String): Int? {
val (depth, tx, ty) = parse(input)
val cave = buildMaze(depth, tx + 50, ty + 50)
cave[ty][tx] = 0
val start = CavePoint(0, 0, Equipment.Torch)
val goal = CavePoint(tx, ty, Equipment.Torch)
return findPath(start, goal, cave)
}
private fun buildMaze(depth: Int, tx: Int, ty: Int): List<IntArray> {
val m = 20183
val erosionLevel = List(ty + 1) { IntArray(tx + 1) }
for (x in 0..tx) erosionLevel[0][x] = (x * 16807 + depth) % m
for (y in 0..ty) erosionLevel[y][0] = (y * 48271 + depth) % m
for (x in 1..tx) {
for (y in 1..ty) {
erosionLevel[y][x] = (erosionLevel[y - 1][x] * erosionLevel[y][x - 1] + depth) % m
}
}
erosionLevel.forEach { row ->
row.indices.forEach { row[it] %= 3 }
}
return erosionLevel
}
private fun parse(input: String) = input
.filter { it in "0123456789 ," }
.split(' ', ',')
.filterNot(String::isBlank)
.map(String::toInt)
}
private enum class Equipment { Torch, Climbing, Neither }
private data class CavePoint(val x: Int, val y: Int, val equipment: Equipment) {
fun neighbors(cave: List<IntArray>): List<Pair<CavePoint, Int>> {
val list = mutableListOf<Pair<CavePoint, Int>>()
if (x > 0) list.add(CavePoint(x - 1, y, equipment) to 1)
if (y > 0) list.add(CavePoint(x, y - 1, equipment) to 1)
if (x < cave[0].lastIndex) list.add(CavePoint(x + 1, y, equipment) to 1)
if (y < cave.lastIndex) list.add(CavePoint(x, y + 1, equipment) to 1)
if (equipment != Equipment.Torch) list.add(CavePoint(x, y, Equipment.Torch) to 7)
if (equipment != Equipment.Climbing) list.add(CavePoint(x, y, Equipment.Climbing) to 7)
if (equipment != Equipment.Neither) list.add(CavePoint(x, y, Equipment.Neither) to 7)
return list.filter { (s, _) ->
when (cave[s.y][s.x]) {
0 -> s.equipment != Equipment.Neither
1 -> s.equipment != Equipment.Torch
2 -> s.equipment != Equipment.Climbing
else -> false
}
}
}
}
//TODO make this a less botched pathfinding implementation
private fun findPath(start: CavePoint, goal: CavePoint, cave: List<IntArray>): Int? {
val openList = PriorityQueue(compareBy<PathfinderStateW> { it.cost })
openList.add(PathfinderStateW(start, 0))
val distances = mutableMapOf(start to 0)
while (openList.isNotEmpty()) {
val candidate = openList.poll()
if (candidate.st == goal) {
return candidate.cost
} else {
candidate.move(cave).forEach {
val existing = distances[it.st] ?: 10000
if (it.cost < existing) {
distances[it.st] = it.cost
openList.add(PathfinderStateW(it.st, it.cost))
}
}
}
}
return null
}
private data class PathfinderStateW(val st: CavePoint, val cost: Int) {
fun move(cave: List<IntArray>): List<PathfinderStateW> = st.neighbors(cave).map { (s, d) -> PathfinderStateW(s, cost + d) }
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 3,638 | advent-of-code | MIT License |
src/Day03.kt | Reivax47 | 572,984,467 | false | {"Kotlin": 32685} | fun main() {
fun trouvelecommun(gauche: List<Char>, droite: List<Char>): MutableList<Char> {
val reponse = mutableListOf<Char>()
var index_gauche = 0
var index_droite = 0
while (index_gauche < gauche.size && index_droite < droite.size) {
if (gauche[index_gauche] == droite[index_droite]) {
reponse.add(gauche[index_gauche++])
index_droite++
} else {
val inc_droite = if (gauche[index_gauche] > droite[index_droite]) 1 else 0
val inc_gauche = if (gauche[index_gauche] < droite[index_droite]) 1 else 0
index_gauche += inc_gauche
index_droite += inc_droite
}
}
return reponse
}
fun part1(input: List<String>): Int {
var result = 0
input.forEach { line ->
val gauche = line.substring(0, line.length/2 ).toCharArray().distinct().sorted()
val droite = line.substring(line.length /2).toCharArray().distinct().sorted()
val winner = trouvelecommun(gauche, droite)[0]
result += if (winner <='Z') (winner - 38).code else (winner - 96).code
}
return result
}
fun part2(input: List<String>): Int {
var index_input = 0
var result = 0
while (index_input < input.size) {
val premier = input[index_input++].toCharArray().distinct().sorted()
val second = input[index_input++].toCharArray().distinct().sorted()
val troisieme = input[index_input++].toCharArray().distinct().sorted()
val premiers_commun = trouvelecommun(premier, second)
val winner = trouvelecommun(premiers_commun, troisieme)[0]
result += if (winner <='Z') (winner - 38).code else (winner - 96).code
}
return result
}
// 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 | 0affd02997046d72f15d493a148f99f58f3b2fb9 | 2,156 | AD2022-01 | Apache License 2.0 |
src/Day12.kt | Riari | 574,587,661 | false | {"Kotlin": 83546, "Python": 1054} | fun main() {
data class Cell(var value: Char, val edges: MutableList<Int> = mutableListOf())
data class CellToVisit(val index: Int, val distance: Int)
data class Heightmap(var startIndex: Int, var endIndex: Int, val cells: MutableList<Cell> = mutableListOf())
fun buildHeightmap(input: List<String>): Heightmap {
val map = Heightmap(0, 0)
val width = input[0].length
val height = input.size
var i = 0
for (y in input.indices) {
for (x in 0 until width) {
var value = input[y][x]
when (value) {
'S' -> {
map.startIndex = i
value = 'a'
}
'E' -> {
map.endIndex = i
value = 'z'
}
}
val edges = mutableListOf<Int>()
if (x > 0) edges.add(i - 1)
if (x < width - 1) edges.add(i + 1)
if (y > 0) edges.add(i - width)
if (y < height - 1) edges.add(i + width)
map.cells.add(Cell(value, edges))
i++
}
}
return map
}
fun solve(map: Heightmap, startAt: Int): Int {
val visited = BooleanArray(map.cells.size) { false }
val queue: MutableList<CellToVisit> = mutableListOf(CellToVisit(startAt, 0))
while (queue.isNotEmpty()) {
val cell = queue.removeAt(0)
if (cell.index == map.endIndex) return cell.distance
if (visited[cell.index]) continue
map.cells[cell.index].edges.filter { map.cells[it].value <= map.cells[cell.index].value + 1 }.forEach {
queue.add(CellToVisit(it, cell.distance + 1))
}
visited[cell.index] = true
}
return Int.MAX_VALUE
}
fun part1(map: Heightmap): Int {
return solve(map, map.startIndex)
}
fun part2(map: Heightmap): Int {
var fewestSteps = Int.MAX_VALUE
for ((i, cell) in map.cells.withIndex()) {
if (cell.value != 'a') continue
val steps = solve(map, i)
if (steps < fewestSteps) fewestSteps = steps
}
return fewestSteps
}
val testInput = buildHeightmap(readInput("Day12_test"))
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = buildHeightmap(readInput("Day12"))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d | 2,546 | aoc-2022 | Apache License 2.0 |
src/Day11.kt | ZiomaleQ | 573,349,910 | false | {"Kotlin": 49609} | import java.math.BigInteger
fun main() {
fun part1(input: List<String>): Long {
val monkeys = mutableListOf<Monkey>()
val num = magicNumber(input)
for (i in 0..input.size / 7) {
monkeys.add(Monkey.parse(input.subList(i * 7, ((i + 1) * 7) - 1)))
}
repeat(20) {
for (monkey in monkeys) {
val passes = monkey.inspectAll(num)
for (pass in passes) {
monkeys.find { it.id == pass.first }!!.items.add(pass.second)
}
}
}
return monkeys.map { it.inspections }.sorted().reversed().take(2).reduce(Long::times)
}
fun part2(input: List<String>): BigInteger {
val monkeys = mutableListOf<Monkey>()
val num = magicNumber(input)
for (i in 0..input.size / 7) {
monkeys.add(Monkey.parse(input.subList(i * 7, ((i + 1) * 7) - 1), 1))
}
repeat(10000) {
for (monkey in monkeys) {
val passes = monkey.inspectAll(num)
for (pass in passes) {
monkeys.find { it.id == pass.first }!!.items.add(pass.second)
}
}
}
return monkeys.map { BigInteger.valueOf(it.inspections) }.sorted().reversed().take(2).reduce(BigInteger::times)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
part1(testInput).also { println(it); check(it == 10605L) }
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
fun magicNumber(inputs: List<String>): Int {
var magicNumber = 1
for (i in 0..inputs.size / 7) {
val monkeyId = i * 7
magicNumber *= inputs[monkeyId + 3].substringAfter("Test: divisible by ").toInt()
}
return magicNumber
}
data class Monkey(
val id: Int,
val items: MutableList<Long>,
val operation: Pair<Char, Any>,
val divider: Int,
val redirectTo: Pair<Int, Int>,
val boredFactor: Int = 3
) {
var inspections = 0L
fun inspectAll(num: Int): List<Pair<Int, Long>> {
val arr = mutableListOf<Pair<Int, Long>>()
while (items.isNotEmpty()) {
arr.add(inspect(num))
}
return arr
}
//Where, what
private fun inspect(num: Int): Pair<Int, Long> {
inspections++
val item = operate(items.removeFirst()).floorDiv(boredFactor) % num
return if (item % divider == 0L) {
Pair(redirectTo.first, item)
} else {
Pair(redirectTo.second, item)
}
}
private fun operate(num: Long): Long {
return when (operation.first) {
'+' -> num + (if (operation.second is String) num else operation.second as Long)
'*' -> num * (if (operation.second is String) num else operation.second as Long)
else -> throw IllegalArgumentException("unknown operator")
}
}
companion object {
fun parse(input: List<String>, bf: Int = 3): Monkey {
val id = input[0].filter { it.isDigit() }.toInt()
val items =
input[1].substring(" Starting items:".length).split(',').map { it.trim().toLong() }.toMutableList()
val operation =
input[2].substring(" Operation: new = old ".length).split(' ')
.let { Pair(it[0][0], it[1].trim().let { num -> if (num == "old") "OLD" else num.toLong() }) }
val divider =
input[3].substring(" Test: divisible by ".length).trim().toInt()
val redirectToFirst = input[4].substring(" If true: throw to monkey ".length).trim().toInt()
val redirectToSecond = input[5].substring(" If false: throw to monkey ".length).trim().toInt()
return Monkey(id, items, operation, divider, Pair(redirectToFirst, redirectToSecond), bf)
}
}
} | 0 | Kotlin | 0 | 0 | b8811a6a9c03e80224e4655013879ac8a90e69b5 | 3,964 | aoc-2022 | Apache License 2.0 |
src/day9/day9.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day9
import readInput
import kotlin.math.abs
private fun helper(input: List<String>, points: Array<Pair<Int, Int>>): Int {
fun createKey(point: Pair<Int, Int>): String = "${point.first},${point.second}"
val visited: MutableSet<String> = hashSetOf<String>().apply {
add(createKey(points.last()))
}
for (move in input) {
val parts = move.split(" ")
val direction = parts[0]
val steps = parts[1].toInt()
for (step in 0 until steps) {
points[0] = with(points[0]) {
when (direction) {
"R" -> Pair(first, second + 1)
"L" -> Pair(first, second - 1)
"D" -> Pair(first - 1, second)
"U" -> Pair(first + 1, second)
else -> throw NullPointerException()
}
}
for (index in 1 until points.size) {
val tempHeadPoint = points[index - 1]
val tempTailPoint = points[index]
val diffRow = tempHeadPoint.first - tempTailPoint.first
val diffCol = tempHeadPoint.second - tempTailPoint.second
if (abs(diffRow) <= 1 && abs(diffCol) <= 1) {
continue
}
val flowMove = Pair(diffRow.coerceIn(-1, 1), diffCol.coerceIn(-1, 1))
points[index] = Pair(tempTailPoint.first + flowMove.first, tempTailPoint.second + flowMove.second)
}
visited.add(createKey(points.last()))
}
}
return visited.size
}
private fun part1(input: List<String>): Int {
val points: Array<Pair<Int, Int>> = Array(2) { Pair(0, 0) }
return helper(input, points)
}
private fun part2(input: List<String>): Int {
val points: Array<Pair<Int, Int>> = Array(10) { Pair(0, 0) }
return helper(input, points)
}
fun main() {
val input = readInput("day9/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 1,992 | aoc-2022 | Apache License 2.0 |
src/Day09.kt | Redstonecrafter0 | 571,787,306 | false | {"Kotlin": 19087} |
data class Knot(var x: Int = 1000, var y: Int = 1000)
fun main() {
val pullMap = buildList<List<Pair<Int, Int>>> {
this += listOf(1 to 1, 1 to 1, 0 to 1, -1 to 1, -1 to 1)
this += listOf(1 to 1, 0 to 0, 0 to 0, 0 to 0, -1 to 1)
this += listOf(1 to 0, 0 to 0, 0 to 0, 0 to 0, -1 to 0)
this += listOf(1 to -1, 0 to 0, 0 to 0, 0 to 0, -1 to -1)
this += listOf(1 to -1, 1 to -1, 0 to -1, -1 to -1, -1 to -1)
}
fun part1(input: List<String>): Int {
val visited = mutableSetOf<Knot>()
val commands = input.map { it.split(" ") }.map { it[0] to it[1].toInt() }
val head = Knot()
val tail = Knot()
visited += tail.copy()
commands.forEach { (dir, amount) ->
for (i in 1..amount) {
when (dir) {
"U" -> head.y++
"D" -> head.y--
"R" -> head.x++
"L" -> head.x--
}
val offset = pullMap[tail.y - head.y + 2][tail.x - head.x + 2]
tail.x += offset.first
tail.y += offset.second
visited += tail.copy()
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val visited = mutableSetOf<Knot>()
val commands = input.map { it.split(" ") }.map { it[0] to it[1].toInt() }
val rope = buildList {
for (i in 1..10) {
this += Knot()
}
}
visited += rope.last().copy()
commands.forEach { (dir, amount) ->
for (i in 1..amount) {
when (dir) {
"U" -> rope.first().y++
"D" -> rope.first().y--
"R" -> rope.first().x++
"L" -> rope.first().x--
}
rope.windowed(2).forEach { (first, second) ->
val offset = pullMap[second.y - first.y + 2][second.x - first.x + 2]
second.x += offset.first
second.y += offset.second
}
visited += rope.last().copy()
}
}
return visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(readInput("Day09_test2")) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e5dbabe247457aabd6dd0f0eb2eb56f9e4c68858 | 2,512 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day07.kt | xabgesagtx | 572,139,500 | false | {"Kotlin": 23192} | fun main() {
fun readDirectoryContent(input: List<String>): FSDir {
return input.fold(listOf<FSDir>()) { stack, line ->
when {
line.isLeaveCommand -> stack.dropLast(1)
line.isChangeDir -> {
val newDir = line.toDir()
stack.lastOrNull()?.addItem(newDir)
stack + newDir
}
line.isFile -> {
stack.last().addItem(line.toFile())
stack
}
else -> stack
}
}.first()
}
fun part1(input: List<String>): Int {
val mainDir = readDirectoryContent(input)
mainDir.print()
return mainDir.allDirs.map { it.calculatedSize() }.filter { it <= 100_000 }.sum()
}
fun part2(input: List<String>): Int {
val mainDir = readDirectoryContent(input)
val spaceUsed = mainDir.calculatedSize()
val spaceFree = 70_000_000 - spaceUsed
val spaceToBeFreed = 30_000_000 - spaceFree
return mainDir.allDirs.map { it.calculatedSize() }.filter { it >= spaceToBeFreed }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
println(part1(testInput))
check(part1(testInput) == 95_437)
check(part2(testInput) == 24_933_642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private val String.isChangeDir: Boolean
get() = startsWith("$ cd ")
private val String.isFile: Boolean
get() = this[0].isDigit()
private val String.isLeaveCommand: Boolean
get() = this == "$ cd .."
private fun String.toFile(): FSFile {
val (fileSize, name) = split(" ")
return FSFile(fileSize.toInt(), name)
}
private fun String.toDir(): FSDir {
val dirName = this.substringAfter("$ cd ").trim()
return FSDir(dirName)
}
private interface FSItem {
fun calculatedSize(): Int
fun print(indent: Int = 0)
}
private data class FSFile(val size: Int, val name: String) : FSItem {
override fun calculatedSize() = size
override fun print(indent: Int) {
println("${" ".repeat(indent)} file $name $size")
}
}
private data class FSDir(val name: String) : FSItem {
private val items: MutableList<FSItem> = mutableListOf()
override fun calculatedSize(): Int = items.sumOf { it.calculatedSize() }
override fun print(indent: Int) {
println("${" ".repeat(indent)} dir $name")
items.forEach {
it.print(indent + 2)
}
}
fun addItem(item: FSItem) = items.add(item)
val allDirs: List<FSDir>
get() = items.mapNotNull {
it as? FSDir
}.flatMap { listOf(it) + it.allDirs }
}
| 0 | Kotlin | 0 | 0 | 976d56bd723a7fc712074066949e03a770219b10 | 2,783 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day14/Day14.kt | alxgarcia | 435,549,527 | false | {"Kotlin": 91398} | package day14
import java.io.File
fun parseInput(lines: List<String>): Pair<String, Map<String, Char>> {
val initial = lines.first()
val insertions =
lines.drop(2).associate {
val (pattern, addition) = it.split(" -> ")
pattern to addition.first()
}
return initial to insertions
}
private fun combineAllMaps(vararg maps: Map<Char, Long>): Map<Char, Long> =
maps.flatMap { it.toList() }
.groupBy { it.first }
.mapValues { (_, v) -> v.fold(0L) { acc, (_, v) -> acc + v } }
private fun combine2(map1: Map<Char, Long>, map2: Map<Char, Long>): Map<Char, Long> =
combineAllMaps(map1, map2)
val memoizeCountDescendantChars = { insertions: Map<String, Char> ->
// intermediate steps will be stored here
val cache = mutableMapOf<Pair<String, Int>, Map<Char, Long>>()
// Recursively build the count, storing all intermediate steps
// in 'cache' so that they can be reused later on
fun getAdditionCount(pair: String, steps: Int): Map<Char, Long> =
when {
steps == 0 -> emptyMap()
cache.containsKey(pair to steps) -> cache[pair to steps]!!
insertions.containsKey(pair) -> {
val c = insertions[pair]!!
val result = combineAllMaps(
mapOf(c to 1L),
getAdditionCount("${pair[0]}$c", steps - 1),
getAdditionCount("$c${pair[1]}", steps - 1)
)
cache[pair to steps] = result
result
}
else -> emptyMap()
}
::getAdditionCount
}
fun solve(polymer: String, insertions: Map<String, Char>, steps: Int): Long {
val memoizedGetDescendants = memoizeCountDescendantChars(insertions)
val finalCount = sequence {
// Count initial chars
val initialCharCount = polymer
.groupingBy { it }.eachCount()
.mapValues { (_, v) -> v.toLong() }
.toMutableMap()
yield(initialCharCount)
// Count descendant chars generated by each pair or chars ('abc' -> 'ab','bc')
for (i in 0..(polymer.length - 2)) {
val pair = polymer.substring(i, i + 2)
yield(memoizedGetDescendants(pair, steps))
}
}.reduce(::combine2)
val max = finalCount.maxOf { it.value }
val min = finalCount.minOf { it.value }
return max - min
}
fun main() {
File("./input/day14.txt").useLines { lines ->
val (initialPolymer, insertions) = parseInput(lines.toList())
println(solve(initialPolymer, insertions, 10))
println(solve(initialPolymer, insertions, 40))
}
} | 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 2,432 | advent-of-code-2021 | MIT License |
src/main/kotlin/aoc2021/Day04.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
private const val BOARD_SIZE = 5
/**
* A bingo board.
* @see [createBoards]
*/
private class Board private constructor(data: List<String>) {
// speed up bingo checking by keeping the data twice: organized by rows & by columns
private val rows: Array<MutableSet<Int>> = (0 until BOARD_SIZE).map { mutableSetOf<Int>() }.toTypedArray()
private val columns: Array<MutableSet<Int>> = (0 until BOARD_SIZE).map { mutableSetOf<Int>() }.toTypedArray()
companion object {
/**
* Creates some bingo boards
* @param input the input as specified in https://adventofcode.com/2021/day/4
* @return a list of bingo boards corresponding to the input data
*/
fun createBoards(input: List<String>) =
input.drop(1).filter { it.isNotBlank() }.windowed(BOARD_SIZE, BOARD_SIZE).map { Board(it) }
}
init {
data.map { row -> row.split(" ").filter { it.isNotBlank() }.map { it.toInt() } }.forEachIndexed { index, row ->
rows[index] = row.toMutableSet()
for (i in row.withIndex()) {
columns[i.index].add(i.value)
}
}
}
/**
* Marks the given number on the board and checks for a bingo
* @param number the number to mark
* @return the score, if a bingo happened on this board or null otherwise
*/
fun mark(number: Int): Int? {
var matched = false
var bingo = false
rows.forEach {
if (it.remove(number)) {
matched = true
bingo = bingo or it.isEmpty()
}
}
// if a number matched in a row, it must also be present in a column
if (matched) {
columns.forEach {
if (it.remove(number)) {
bingo = bingo or it.isEmpty()
}
}
}
return if (bingo) number * rows.sumOf { it.sum() } else null
}
}
private fun part1(input: List<String>): Int {
val inputNumbers = input.first().split(",").map { it.toInt() }
val boards = Board.createBoards(input)
inputNumbers.forEach { number ->
boards.forEach {
it.mark(number)?.run { return this }
}
}
// no winner
return 0
}
private fun part2(input: List<String>): Int {
val inputNumbers = input.first().split(",").map { it.toInt() }
var boards = Board.createBoards(input)
inputNumbers.forEach { number ->
when {
boards.isEmpty() -> return 0 // no single last winner
boards.size > 1 -> boards = boards.filter { it.mark(number) == null }
else -> boards.first().mark(number)?.run { return this }
}
}
// loser board does never win -> can not calculate score
return 0
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 4512)
check(part2(testInput) == 1924)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,111 | adventOfCode | Apache License 2.0 |
src/main/kotlin/days/y2023/day06/Day06.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2023.day06
import util.InputReader
typealias PuzzleLine = String
typealias PuzzleInput = List<PuzzleLine>
class Day06(val input: PuzzleInput) {
val races = raceDurations(input).zip(raceDistances(input))
val longRace = parseLongRace(input)
fun partOne() = races.map { waysToWin(it.first, it.second) }.product()
fun partTwo() = waysToWin(longRace.first, longRace.second)
}
fun List<Long>.product(): Long {
return this.reduce { acc, i -> acc * i }
}
fun raceDurations(input: PuzzleInput): List<Long> {
return input[0].split(Regex("\\s+")).drop(1).map { it.toLong() }
}
fun raceDistances(input: PuzzleInput): List<Long> {
return input[1].split(Regex("\\s+")).drop(1).map { it.toLong() }
}
fun parseLongRace(input: PuzzleInput): Pair<Long, Long> {
val duration = input[0].split(": ")[1].trim().split(Regex("\\s+")).joinToString("").toLong()
val distance = input[1].split(": ")[1].trim().split(Regex("\\s+")).joinToString("").toLong()
return duration to distance
}
fun waysToWin(duration: Long, distance: Long): Long {
val waysToWin = ( 0..duration).filter { buttonHeldMs ->
val remainingMs = duration - buttonHeldMs
val speed = buttonHeldMs
val travelledDistance = speed * remainingMs
travelledDistance > distance
}
return waysToWin.size.toLong()
}
fun main() {
val year = 2023
val day = 6
val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day)
val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day)
fun partOne(input: PuzzleInput) = Day06(input).partOne()
fun partTwo(input: PuzzleInput) = Day06(input).partTwo()
println("Example 1: ${partOne(exampleInput)}")
println("Puzzle 1: ${partOne(puzzleInput)}")
println("Example 2: ${partTwo(exampleInput)}")
println("Puzzle 2: ${partTwo(puzzleInput)}")
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 1,885 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day11.kt | makohn | 571,699,522 | false | {"Kotlin": 35992} |
fun main() {
val day = "11"
fun toOperation(input: String): (Long) -> Long {
val (x, op, y) = input.split(" ")
return { old ->
val a = if (x == "old") old else x.toLong()
val b = if (y == "old") old else y.toLong()
when (op) {
"+" -> a + b
"*" -> a * b
else -> old
}
}
}
data class Item(var worryLevel: Long) {
fun adaptWorryLevel(operation: (Long) -> Long) {
worryLevel = operation(worryLevel)
}
}
class Monkey(
val id: Int,
private val items: MutableList<Item>,
private val operation: (Long) -> Long,
private val divisor: Int,
private val otherMonkeys: Pair<Int, Int>,
var inspectionCount: Int = 0
) {
lateinit var allOtherMonkeys: List<Monkey>
val commonDivisor: Int
get() = allOtherMonkeys.map { it.divisor }.reduce { a,b -> a*b }
fun inspectItems(decreaseWorry: Boolean) {
items.forEach {
it.adaptWorryLevel(operation)
it.worryLevel %= commonDivisor
if (decreaseWorry) it.worryLevel /= 3
if (it.worryLevel % divisor == 0L)
allOtherMonkeys.first { monkey -> monkey.id == otherMonkeys.first }.add(it)
else
allOtherMonkeys.first { monkey -> monkey.id == otherMonkeys.second }.add(it)
}
inspectionCount += items.size
items.clear()
}
fun add(item: Item) {
items.add(item)
}
}
fun simulateGame(input: List<String>, rounds: Int, decreaseWorry: Boolean): Long {
val monkeys = input
.filter { it.isNotEmpty() }
.chunked(6)
.map { parts ->
val id = parts[0].substringAfter("Monkey ").replace(":", "").toInt()
val items = parts[1].substringAfter("Starting items: ").trim().split(",").map { Item(it.trim().toLong()) }.toMutableList()
val operation = toOperation(parts[2].substringAfter("Operation: new = "))
val divisor = parts[3].substringAfter("divisible by ").toInt()
val monkeyA = parts[4].substringAfter("throw to monkey ").toInt()
val monkeyB = parts[5].substringAfter("throw to monkey ").toInt()
Monkey(id, items, operation, divisor,monkeyA to monkeyB)
}
monkeys.forEach { it.allOtherMonkeys = monkeys }
repeat(rounds) {
monkeys.forEach { it.inspectItems(decreaseWorry) }
}
return monkeys.map { it.inspectionCount }.sortedDescending().take(2).fold(1) { acc, i -> acc * i}
}
fun part1(input: List<String>): Long {
return simulateGame(input, 20, true)
}
fun part2(input: List<String>): Long {
return simulateGame(input, 10_000, false)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2734d9ea429b0099b32c8a4ce3343599b522b321 | 3,264 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/github/brpeterman/advent2022/ForestSurvey.kt | brpeterman | 573,059,778 | false | {"Kotlin": 53108} | package com.github.brpeterman.advent2022
class ForestSurvey(input: String) {
data class Coords(val row: Int, val column: Int)
data class TreeMap(val width: Int, val height: Int, val trees: Map<Coords, Int>)
enum class Offset(val rowOffset: Int, val colOffset: Int) {
NORTH(-1, 0),
SOUTH(1, 0),
WEST(0, -1),
EAST(0, 1)
}
var map: TreeMap
init {
map = parseInput(input)
}
fun countVisible(): Int {
return map.trees.keys
.filter { isVisible(it) }
.count()
}
fun findBestTree(): Int {
return map.trees.keys
.filter { it.row != 0 &&
it.row != map.height-1 &&
it.column != 0 &&
it.column != map.width-1 }
.maxOf { scenicScore(it) }
}
fun isVisible(coords: Coords): Boolean {
val height = map.trees[coords]!!
return ((0..coords.row-1).all { map.trees[Coords(it, coords.column)]!! < height }) ||
(coords.row+1..map.height-1).all { map.trees[Coords(it, coords.column)]!! < height } ||
(0..coords.column-1).all { map.trees[Coords(coords.row, it)]!! < height } ||
(coords.column+1..map.width-1).all { map.trees[Coords(coords.row, it)]!! < height }
}
fun scenicScore(coords: Coords): Int {
val height = map.trees[coords]!!
val score = Offset.values()
.map { offset ->
var current = Coords(coords.row + offset.rowOffset, coords.column + offset.colOffset)
var count = 1
while (map.trees[current] != null && map.trees[current]!! < height) {
current = Coords(current.row + offset.rowOffset, current.column + offset.colOffset)
if (map.trees[current] != null) {
count++
}
}
count
}
.reduce { product, i -> product * i }
return score
}
companion object {
fun parseInput(input: String): TreeMap {
val lines = input.split("\n")
.filter { it.isNotBlank() }
val height = lines.size
val width = lines[0].length
val trees = lines.withIndex()
.fold(mutableMapOf<Coords, Int>()) { map, (lineIndex, line) ->
line.toCharArray()
.withIndex()
.forEach { (charIndex, char) ->
map[Coords(lineIndex, charIndex)] = char.toString().toInt()
}
map
}
return TreeMap(width, height, trees)
}
}
}
| 0 | Kotlin | 0 | 0 | 1407ca85490366645ae3ec86cfeeab25cbb4c585 | 2,747 | advent2022 | MIT License |
src/main/kotlin/Day13.kt | Ostkontentitan | 434,500,914 | false | {"Kotlin": 73563} | fun puzzleDayThirteenPartOne() {
val inputs = readInput(13)
val coordinates = extractCoordinates(inputs)
val instructions = extractInstructions(inputs)
val instruction = instructions.first() as Fold.X
val folded = foldLeft(coordinates, instruction.value)
println("Dots after first fold: ${folded.size}")
}
fun puzzleDayThirteenPartTwo() {
val inputs = readInput(13)
val coordinates = extractCoordinates(inputs)
val instructions = extractInstructions(inputs)
val foldedPaper = foldCompletely(coordinates, instructions)
val printable = visualizePaperDots(foldedPaper)
printable.forEach { println(it) }
}
fun visualizePaperDots(foldedPaper: Set<Point>): List<String> {
val maxY = foldedPaper.maxOf { it.y }
val maxX = foldedPaper.maxOf { it.x }
val canvas = (0..maxY).map { ".".repeat(maxX + 1) }
return foldedPaper.fold(canvas) { canv, point ->
canv.mapIndexed { yIndex, string ->
if (yIndex == point.y) {
string.mapIndexed { yIndex, c -> if (yIndex == point.x) '#' else c }.joinToString("")
} else string
}
}
}
fun foldCompletely(coordinates: Set<Point>, instructions: List<Fold>): Set<Point> =
instructions.fold(coordinates) { paper, instruction ->
return@fold when (instruction) {
is Fold.X -> foldLeft(paper, instruction.value)
is Fold.Y -> foldUp(paper, instruction.value)
}
}
fun extractInstructions(inputs: List<String>): List<Fold> {
val slice = inputs.subList(inputs.indexOfFirst { it.startsWith("fold along ") }, inputs.size)
return slice.map { it.replace("fold along ", "") }.map {
val (xOrY, value) = it.split("=")
when (xOrY) {
"x" -> Fold.X(value.toInt())
"y" -> Fold.Y(value.toInt())
else -> throw IllegalArgumentException("only x or y expected")
}
}
}
sealed class Fold {
abstract val value: Int
data class X(override val value: Int) : Fold()
data class Y(override val value: Int) : Fold()
}
fun extractCoordinates(inputs: List<String>): Set<Point> = inputs.subList(0, inputs.indexOfFirst { it.isEmpty() }).map {
val (x, y) = it.split(",")
Point(x.toInt(), y.toInt())
}.toSet()
fun foldUp(coordinates: Set<Point>, foldY: Int): Set<Point> {
val matchingCoordinates = coordinates.filter { it.y > foldY }
val newCoordinates = matchingCoordinates.mapNotNull {
val newY = foldY - (it.y - foldY)
if (newY >= 0) Point(it.x, newY) else null
}
return (coordinates.filter { it.y < foldY } + newCoordinates).toSet()
}
fun foldLeft(coordinates: Set<Point>, foldX: Int): Set<Point> {
val matchingCoordinates = coordinates.filter { it.x > foldX }
val newCoordinates = matchingCoordinates.mapNotNull {
val newX = foldX - (it.x - foldX)
if (newX >= 0) Point(newX, it.y) else null
}
return (coordinates.filter { it.x < foldX } + newCoordinates).toSet()
}
| 0 | Kotlin | 0 | 0 | e0e5022238747e4b934cac0f6235b92831ca8ac7 | 2,990 | advent-of-kotlin-2021 | Apache License 2.0 |
src/Day02.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | fun main() {
fun part1(input: List<String>): Int {
val shapeScores = mapOf(
'X' to 1,
'Y' to 2,
'Z' to 3,
)
val roundScores = mapOf(
"A X" to 3,
"A Y" to 6,
"A Z" to 0,
"B X" to 0,
"B Y" to 3,
"B Z" to 6,
"C X" to 6,
"C Y" to 0,
"C Z" to 3,
)
return input.sumOf { line ->
shapeScores.getValue(line[2]) + roundScores.getValue(line)
}
}
fun part2(input: List<String>): Int {
val roundScores = mapOf(
'X' to 0,
'Y' to 3,
'Z' to 6,
)
val shapeScores = mapOf(
"A X" to 3, // ls - A C
"A Y" to 1, // dr - A A
"A Z" to 2, // wn - A B
"B X" to 1, // ls - B A
"B Y" to 2, // dr - B B
"B Z" to 3, // wn - B C
"C X" to 2, // ls - C B
"C Y" to 3, // dr - C C
"C Z" to 1, // wn - C A
)
return input.sumOf { line ->
shapeScores.getValue(line) + roundScores.getValue(line[2])
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 1,466 | aoc-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.