path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2 classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37 values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day03.kt | vjgarciag96 | 572,719,091 | false | {"Kotlin": 44399} | private val A_TO_Z_UPPERCASE = 65..90
private val A_TO_Z_LOWERCASE = 97..122
private fun calculatePriority(char: Char): Int {
return when (val charCode = char.code) {
in A_TO_Z_LOWERCASE -> charCode % (A_TO_Z_LOWERCASE.first - 1)
in A_TO_Z_UPPERCASE -> A_TO_Z_LOWERCASE.count() + (charCode % (A_TO_Z_UPPERCASE.first - 1))
else -> error("invalid char $char")
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val firstCompartment = rucksack.substring(
startIndex = 0,
endIndex = rucksack.length / 2,
).toHashSet()
val invalidItemType = rucksack.substring(
rucksack.length / 2,
rucksack.length,
).first { itemType -> firstCompartment.contains(itemType) }
calculatePriority(invalidItemType)
}
}
fun part2(input: List<String>): Int {
return input.chunked(size = 3) { (elf1, elf2, elf3) ->
val elf1Types = elf1.toHashSet()
val elf2Types = elf2.toHashSet()
val commonType = elf3.first { itemType ->
itemType in elf1Types && itemType in elf2Types
}
calculatePriority(commonType)
}.sum()
}
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 | ee53877877b21166b8f7dc63c15cc929c8c20430 | 1,510 | advent-of-code-2022 | Apache License 2.0 |
src/Day23.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | fun main() {
fun parseInput(input: List<String>): Set<Pair<Int, Int>> {
return input.mapIndexed { y, line ->
line.withIndex().filter { x -> x.value == '#' }.map { x ->
Pair(y, x.index)
}
}.flatten().toSet()
}
fun neighbors(p: Pair<Int, Int>): List<Pair<Int, Int>> {
val (y, x) = p
return listOf(
Pair(y - 1, x - 1),
Pair(y - 1, x),
Pair(y - 1, x + 1),
Pair(y, x - 1),
Pair(y, x + 1),
Pair(y + 1, x - 1),
Pair(y + 1, x),
Pair(y + 1, x + 1),
)
}
fun addToNewPositions(
p: Pair<Int, Int>,
target: Pair<Int, Int>,
newPositions: MutableMap<Pair<Int, Int>, MutableList<Pair<Int, Int>>>,
) {
if (target !in newPositions) {
newPositions[target] = mutableListOf(p)
return
}
newPositions[target]!!.add(p)
}
fun solution(input: List<String>, cutoff: Int, part2: Boolean): Int {
var elves = parseInput(input)
for (round in 0..cutoff) {
val newPositions: MutableMap<Pair<Int, Int>, MutableList<Pair<Int, Int>>> = mutableMapOf()
elves.forEach { elf ->
val (y, x) = elf
val n = neighbors(elf).filter { it in elves }
if (n.isEmpty()) {
addToNewPositions(elf, elf, newPositions)
return@forEach
}
for (i in 0 until 4) {
when ((i + round) % 4) {
0 -> {
if (listOf(Pair(y - 1, x - 1), Pair(y - 1, x), Pair(y - 1, x + 1)).all { it !in n }) {
addToNewPositions(elf, Pair(y - 1, x), newPositions)
return@forEach
}
}
1 -> {
if (listOf(Pair(y + 1, x - 1), Pair(y + 1, x), Pair(y + 1, x + 1)).all { it !in n }) {
addToNewPositions(elf, Pair(y + 1, x), newPositions)
return@forEach
}
}
2 -> {
if (listOf(Pair(y + 1, x - 1), Pair(y, x - 1), Pair(y - 1, x - 1)).all { it !in n }) {
addToNewPositions(elf, Pair(y, x - 1), newPositions)
return@forEach
}
}
3 -> {
if (listOf(Pair(y + 1, x + 1), Pair(y, x + 1), Pair(y - 1, x + 1)).all { it !in n }) {
addToNewPositions(elf, Pair(y, x + 1), newPositions)
return@forEach
}
}
}
}
addToNewPositions(elf, elf, newPositions)
}
var moved = false
elves = newPositions.flatMap { (target, positions) ->
if (positions.size == 1) {
moved = moved || positions[0] != target
listOf(target)
} else {
positions
}
}.toSet()
if (!moved) {
if (part2) {
return round + 1
}
break
}
}
return (1 + elves.maxBy { it.first }.first - elves.minBy { it.first }.first) * (1 + elves.maxBy { it.second }.second - elves.minBy { it.second }.second) - elves.size
}
fun part1(input: List<String>) = solution(input, 10, false)
fun part2(input: List<String>) = solution(input, Int.MAX_VALUE, true)
val testInput = readInput("Day23_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 4,056 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day11.kt | cbrentharris | 712,962,396 | false | {"Kotlin": 171464} | import kotlin.String
import kotlin.collections.List
object Day11 {
fun part1(input: List<String>): String {
val pairs = generatePairs(input)
val emptyRows = generateEmptyRows(input)
val emptyColumns = generateEmptyColumns(input)
return pairs.sumOf { (a, b) ->
manhattanDistance(a, b) + crossingRows(a, b, emptyRows) + crossingColumns(a, b, emptyColumns)
}.toString()
}
private fun crossingColumns(a: Day10.Coordinate, b: Day10.Coordinate, emptyColumns: Set<Int>): Long {
return emptyColumns.count { a.x < it && b.x > it || a.x > it && b.x < it }.toLong()
}
private fun crossingRows(a: Day10.Coordinate, b: Day10.Coordinate, emptyRows: Set<Int>): Long {
return emptyRows.count { a.y < it && b.y > it || a.y > it && b.y < it }.toLong()
}
private fun manhattanDistance(a: Day10.Coordinate, b: Day10.Coordinate): Long {
return (Math.abs(a.x - b.x) + Math.abs(a.y - b.y)).toLong()
}
fun part2(input: List<String>): String {
val pairs = generatePairs(input)
val emptyRows = generateEmptyRows(input)
val emptyColumns = generateEmptyColumns(input)
return pairs.sumOf { (a, b) ->
manhattanDistance(a, b) + crossingRows(a, b, emptyRows) * 999_999L + crossingColumns(
a,
b,
emptyColumns
) * 999_999L
}.toString()
}
private fun generatePairs(input: List<String>): List<Pair<Day10.Coordinate, Day10.Coordinate>> {
val coordinates = input.mapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == '#') {
Day10.Coordinate(x, y)
} else {
null
}
}
}.flatten()
return coordinates.indices.flatMap { i ->
(i + 1..<coordinates.size).map { j ->
Pair(coordinates[i], coordinates[j])
}
}
}
private fun generateEmptyColumns(input: List<String>): Set<Int> {
return (0..<input[0].length).filter { col ->
input.all { it[col] == '.' }
}.toSet()
}
private fun generateEmptyRows(input: List<String>): Set<Int> {
return input.mapIndexedNotNull { y, line ->
if (line.all { it == '.' }) {
y
} else {
null
}
}.toSet()
}
}
| 0 | Kotlin | 0 | 1 | f689f8bbbf1a63fecf66e5e03b382becac5d0025 | 2,454 | kotlin-kringle | Apache License 2.0 |
2022/src/main/kotlin/com/github/akowal/aoc/Day15.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Day15 {
private val sensor2beacon: Map<Point, Point>
init {
val pattern = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex()
sensor2beacon = inputFile("day15").readLines().associate { line ->
val coord = pattern.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() }
val sensor = Point(coord[0], coord[1])
val beacon = Point(coord[2], coord[3])
sensor to beacon
}
}
fun solvePart1(): Int {
val row = 2_000_000
val coverage = rowCoverage(row)
val beaconsOverlap = sensor2beacon.values.toSet().count { b ->
coverage.any { b.y == row && b.x in it }
}
return coverage.sumOf { it.last - it.first + 1 } - beaconsOverlap
}
private fun rowCoverage(row: Int): Set<IntRange> {
val coverage = mutableSetOf<IntRange>()
for ((sensor, beacon) in sensor2beacon) {
val d1 = sensor.distanceTo(beacon)
val d2 = sensor.distanceTo(sensor.copy(y = row))
if (d2 >= d1) {
continue
}
var x1 = sensor.x - (d1 - d2)
var x2 = sensor.x + (d1 - d2)
val overlapping = coverage.filter { it.overlaps(x1..x2) }.toSet()
if (overlapping.isNotEmpty()) {
coverage -= overlapping
x1 = min(x1, overlapping.minOf { it.first })
x2 = max(x2, overlapping.maxOf { it.last })
}
coverage += x1..x2
}
return coverage
}
fun solvePart2(): Long {
val limit = 4_000_000
for(y in 0..limit) {
val coverage = rowCoverage(y)
for (segment in coverage) {
when {
segment.first > 0 -> return tuningFreq(segment.first - 1, y)
segment.last < limit -> return tuningFreq(segment.last + 1, y)
}
}
}
error("xoxoxo")
}
private fun tuningFreq(x: Int, y: Int) = x * 4_000_000L + y
private fun Point.distanceTo(other: Point) = abs(x - other.x) + abs(y - other.y)
}
fun main() {
val solution = Day15()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 2,394 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/Day13.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | import java.util.Stack
data class Node(val num: Int?, val list: List<Node>?)
fun main() {
fun String.toNode(): Node {
fun getPairMap(): Map<Int, Int> {
val pairMap = mutableMapOf<Int, Int>()
val stack = Stack<Int>()
for (i in indices) {
if (this[i] == '[') {
stack.push(i)
} else if (this[i] == ']') {
val top = stack.pop()
pairMap[top] = i
}
}
return pairMap
}
val pairMap = getPairMap()
fun dfs(l: Int, r: Int): Node {
if (this[l].isDigit()) return Node(substring(l..r).toInt(), null)
val splits = mutableListOf(l, r)
var i = l + 1
while (i < r) {
if (this[i] == '[') i = pairMap[i]!!
if (this[i] == ',') splits += i
i++
}
splits.sort()
val list = mutableListOf<Node>()
for (j in 1 until splits.size) {
val left = splits[j - 1] + 1
val right = splits[j] - 1
if (left <= right) list += dfs(left, right)
}
return Node(null, list)
}
return dfs(0, length - 1)
}
fun compareTo(a: Int, b: Int) = when {
a < b -> -1
a > b -> 1
else -> 0
}
fun compareTo(x: Node, y: Node): Int {
if (x.num != null && y.num != null) return compareTo(x.num, y.num)
if (x.list != null && y.list != null) {
val size = minOf(x.list.size, y.list.size)
for (i in 0 until size) {
val diff = compareTo(x.list[i], y.list[i])
if (diff != 0) return diff
}
return compareTo(x.list.size, y.list.size)
}
val a = if (x.list != null) x else Node(null, listOf(Node(x.num, null)))
val b = if (y.list != null) y else Node(null, listOf(Node(y.num, null)))
return compareTo(a, b)
}
fun compareTo(s: String, t: String) = compareTo(s.toNode(), t.toNode())
fun part1(input: List<String>): Int {
return input.chunked(3).withIndex().sumOf {
val index = it.index
val list = it.value
if (compareTo(list[0], list[1]) == -1) index + 1 else 0
}
}
fun part2(input: List<String>): Int {
val d1 = "[[2]]"
val d2 = "[[6]]"
val result = input.toMutableList().apply {
add(d1)
add(d2)
}.filter { it.isNotEmpty() }
.sortedWith { o1, o2 -> compareTo(o1, o2) }
val i1 = result.indexOf(d1)
val i2 = result.indexOf(d2)
return (i1 + 1) * (i2 + 1)
}
println(part1(readInput("data/Day13_test")))
println(part1(readInput("data/Day13")))
println(part2(readInput("data/Day13_test")))
println(part2(readInput("data/Day13")))
} | 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 2,570 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day15.kt | cagriyildirimR | 572,811,424 | false | {"Kotlin": 34697} | import kotlin.math.abs
fun day15() {
val input = readInput("Day15").map {
it.split("Sensor at x=", ": closest beacon is at x=", ", y=").filter { x -> x != "" }.map { s -> s.toInt() }
}
val Y = 2_000_000
val abc = mutableListOf<List<List<Int>>>()
for (j in 0..4_000_000) {
val l = mutableListOf<Pair<Int, Int>>()
for (i in input) {
val x = i[0]
val y = i[1]
val d = norm1(x, y, i[2], i[3])
val distanceToY = abs(y - j)
val remain = d - distanceToY
l.add(Pair(x - remain, x + remain))
}
abc.add(joinPairs(l))
}
var result = 0
for (i in abc[Y]) {
result = i.last() - i.first()
}
result.print()
for ((y, i) in abc.withIndex()) {
if (i.size > 1) {
val x: Long = i[0][1] + 1L
println("Tuning frequency is: ${x * 4_000_000 + y}")
}
}
}
fun joinPairs(l: List<Pair<Int, Int>>): MutableList<List<Int>> {
val sorted = l.sortedWith(compareBy({ it.first }, { it.second }))
var start = sorted.first().first
var end = sorted.first().second
val result = mutableListOf<List<Int>>()
for (i in 1..sorted.lastIndex) {
if (start < sorted[i].first && sorted[i].second < end) {
} else if (sorted[i].first <= end && sorted[i].second >= end) end = sorted[i].second else {
result.add(listOf(start, end))
start = sorted[i].first
end = sorted[i].second
}
}
result.add(listOf(start, end))
return result
}
fun norm1(x1: Int, y1: Int, x2: Int, y2: Int): Int {
val x = abs(x1 - x2)
val y = abs(y1 - y2)
return x + y
}
| 0 | Kotlin | 0 | 0 | 343efa0fb8ee76b7b2530269bd986e6171d8bb68 | 1,712 | AoC | Apache License 2.0 |
src/Day04.kt | benwicks | 572,726,620 | false | {"Kotlin": 29712} | fun main() {
fun extracted(pair: String): Pair<IntRange, IntRange> {
val split = pair.split(',')
val firstRange = split[0].split('-')
val secondRange = split[1].split('-')
val firstRangeStart = firstRange.first().toInt()
val secondRangeStart = secondRange.first().toInt()
val firstRangeEnd = firstRange.last().toInt()
val secondRangeEnd = secondRange.last().toInt()
return firstRangeStart..firstRangeEnd to secondRangeStart..secondRangeEnd
}
fun doesOneRangeFullyContainTheOther(parsedRangesPair: Pair<IntRange, IntRange>) =
(parsedRangesPair.first.first <= parsedRangesPair.second.first && parsedRangesPair.first.last >= parsedRangesPair.second.last) ||
(parsedRangesPair.first.first >= parsedRangesPair.second.first && parsedRangesPair.first.last <= parsedRangesPair.second.last)
fun part1(input: List<String>): Int {
var sumFullyContainedRangesByPair = 0
for (pair in input) {
val parsedRangesPair = extracted(pair)
// does one fully contain the other?
if (doesOneRangeFullyContainTheOther(parsedRangesPair)) {
sumFullyContainedRangesByPair++
}
}
return sumFullyContainedRangesByPair
}
fun part2(input: List<String>): Int {
var sumOverlappingRangesByPair = 0
for (pair in input) {
val parsedRangesPair = extracted(pair)
// does one fully or partially contain the other?
if (doesOneRangeFullyContainTheOther(parsedRangesPair) ||
parsedRangesPair.first.first in parsedRangesPair.second || parsedRangesPair.first.last in parsedRangesPair.second) {
sumOverlappingRangesByPair++
}
}
return sumOverlappingRangesByPair
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fbec04e056bc0933a906fd1383c191051a17c17b | 2,134 | aoc-2022-kotlin | Apache License 2.0 |
src/Day07.kt | rifkinni | 573,123,064 | false | {"Kotlin": 33155, "Shell": 125} | class Parser(root: Directory) {
private var pwd: Directory = root
fun parse(line: String) {
if (line.startsWith("$ cd ")) {
val name = line.replace("$ cd ", "")
pwd = when(name) {
"/" -> pwd //no-op, already set
".." -> pwd.parent!!
else -> {
val directory = Directory(name, pwd)
pwd.children.add(directory)
directory
}
}
} else if (line.matches(Regex("^[0-9]+ .+"))) {
val size = Integer.parseInt(line.split(" ")[0])
pwd.cumulativeFileSize += size
}
}
}
class Directory(val name: String, val parent: Directory?) {
val children: MutableList<Directory> = ArrayList()
var cumulativeFileSize = 0
fun calculateTotalSize(): Int {
return cumulativeFileSize + children.sumOf { it.calculateTotalSize() }
}
}
class FileSystem(input: List<String>) {
val root = Directory("/", null)
init {
val parser = Parser(root)
input.forEach { parser.parse(it) }
}
fun sumSizes(): Int {
val sizes = recurseDirectorySizes(root.children, ArrayList())
return sizes.filter { it < MAX_SIZE }.sum()
}
fun minMaxSize(): Int {
val delta = SPACE_NEEDED - (SYSTEM_SIZE - root.calculateTotalSize())
val sizes = recurseDirectorySizes(root.children, mutableListOf(root.calculateTotalSize()))
return sizes.filter { it > delta }.min()
}
private fun recurseDirectorySizes(directories: List<Directory>, result: MutableList<Int>): MutableList<Int> {
for (directory in directories) {
result.add(directory.calculateTotalSize())
recurseDirectorySizes(directory.children, result)
}
return result
}
companion object {
const val SYSTEM_SIZE = 70000000
const val SPACE_NEEDED = 30000000
const val MAX_SIZE = 100000
}
}
fun main() {
fun part1(input: List<String>): Int {
val fileSystem = FileSystem(input)
return fileSystem.sumSizes()
}
fun part2(input: List<String>): Int {
val fileSystem = FileSystem(input)
return fileSystem.minMaxSize()
}
// 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 | c2f8ca8447c9663c0ce3efbec8e57070d90a8996 | 2,556 | 2022-advent | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/Day18.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 18: Snailfish
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.readFileAsStringList
import kotlin.math.ceil
fun main() {
println(" ** Day 18: Snailfish ** \n")
val mathsHomework = readFileAsStringList("/Day18SnailfishMathsHomework.txt")
val completedHomeworkNumber = completeSnailfishMathsHomework(mathsHomework)
println("The magnitude of the final sum from the maths homework is ${completedHomeworkNumber.magnitude}")
val largestMagnitude = calculateLargestMagnitudeForSumOfAnyTwoNumbers(mathsHomework)
println("The largest magnitude of the sum of any two snailfish numbers in this list is $largestMagnitude")
}
fun completeSnailfishMathsHomework(mathsHomework: List<String>) =
mathsHomework
.drop(1)
.fold(SnailfishNumber(mathsHomework.first())) { accumulator, number -> accumulator + SnailfishNumber(number) }
fun calculateLargestMagnitudeForSumOfAnyTwoNumbers(mathsHomework: List<String>) =
mathsHomework
.flatMap { number -> mathsHomework.map { Pair(number, it) } }
.distinct()
.map { (left, right) -> SnailfishNumber(left) + SnailfishNumber(right) }
.maxOfOrNull { it.magnitude } ?: 0
class SnailfishNumber(stringEncodedNumber: String) {
private val rootNode = parse(stringEncodedNumber).apply { reduce() }
val magnitude: Int by lazy { rootNode.magnitude }
private fun parse(number: String, nestLevel: Int = 0): SnailfishNode {
val bracketsDropped = number.substring(1, number.length - 1)
val nodes = bracketsDropped.splitAtIndex(findPairSplitPosition(bracketsDropped)).map {
it.toIntOrNull()?.let { SnailfishInteger(it, nestLevel + 1) } ?: parse(it, nestLevel + 1)
}
return SnailfishNode(nodes[0], nodes[1], nestLevel)
}
private fun findPairSplitPosition(number: String): Int {
var bracketCount = 0
for ((index, char) in number.toCharArray().withIndex()) {
if (char == '[') ++bracketCount
else if (char == ']') --bracketCount
else if (char == ',' && bracketCount == 0) return index
}
return -1
}
operator fun plus(number: SnailfishNumber) = SnailfishNumber("[$this,$number]")
override fun toString() = rootNode.toString()
}
private class SnailfishNode(private var left: SnailfishElement, private var right: SnailfishElement, nestLevel: Int) : SnailfishElement(nestLevel) {
override val magnitude by lazy { (3 * left.magnitude) + (2 * right.magnitude) }
override fun explode(): Pair<Int?, Int?>? {
if (left is SnailfishInteger && right is SnailfishInteger && nestLevel >= 4) {
return Pair(left.toIntOrNull(), right.toIntOrNull())
}
left.explode()?.let {
if (allNotNull(it.first, it.second)) left = snailfishZero(nestLevel + 1)
it.second?.let { right.addToLeft(it) }
return Pair(it.first, null)
}
right.explode()?.let {
if (allNotNull(it.first, it.second)) right = snailfishZero(nestLevel + 1)
it.first?.let { left.addToRight(it) }
return Pair(null, it.second)
}
return null
}
override fun split() =
left.split()?.also { if (it.nestLevel == left.nestLevel) left = it }
?: right.split()?.also { if (it.nestLevel == right.nestLevel) right = it }
fun reduce() {
do {
val reducedResult = left.explode()?.also {
it.second?.let { right.addToLeft(it) }
} ?: right.explode()?.also {
it.first?.let { left.addToRight(it) }
} ?: split()
} while (reducedResult != null)
}
override fun addToLeft(regularNumber: Int) = left.addToLeft(regularNumber)
override fun addToRight(regularNumber: Int) = right.addToRight(regularNumber)
override fun toString() = "[$left,$right]"
}
private class SnailfishInteger(private var number: Int, nestLevel: Int) : SnailfishElement(nestLevel) {
override val magnitude
get() = number
fun toInt() = number
override fun split(): SnailfishNode? {
if (number > 9) {
return SnailfishNode(
(number / 2).toSnailfishInteger(nestLevel + 1),
number.divideRoundUp(2).toSnailfishInteger(nestLevel + 1),
nestLevel)
}
return null
}
override fun addToLeft(regularNumber: Int) {
number += regularNumber
}
override fun addToRight(regularNumber: Int) {
number += regularNumber
}
override fun toString() = number.toString()
}
private abstract class SnailfishElement(val nestLevel: Int) {
abstract val magnitude: Int
open fun explode(): Pair<Int?, Int?>? = null
open fun split(): SnailfishNode? = null
abstract fun addToLeft(regularNumber: Int)
abstract fun addToRight(regularNumber: Int)
fun toIntOrNull() = (this as? SnailfishInteger)?.toInt()
}
private fun snailfishZero(nestLevel: Int) = SnailfishInteger(0, nestLevel)
private fun String.splitAtIndex(index: Int) = listOf(this.substring(0, index), this.substring(index + 1))
private fun Int.toSnailfishInteger(nestLevel: Int) = SnailfishInteger(this, nestLevel)
private fun Int.divideRoundUp(divisor: Int) = ceil(this.toDouble() / divisor).toInt()
private fun allNotNull(vararg items: Any?) = items.all { it != null }
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 5,406 | AdventOfCode2021 | MIT License |
src/main/kotlin/aoc2022/Day05.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
object Day05 {
data class Command(val n: Int, val from: Int, val to: Int)
data class Stacks(private val state: List<String>) {
override fun toString(): String {
val seq = sequence<List<String>> {
yield(state.indices.map { " ${it + 1} " })
val maxLength: Int = state.maxOf { it.length }
for (x in 0 until maxLength) {
yield(state.map {
if (x < it.length) "[${it[x]}]" else " "
})
}
}
return seq.map { it.joinToString(" ") }.toList().reversed().joinToString("\n")
}
fun tops() = state.map { it.last() }
fun <T> List<T>.replace(n: Int, new: T) = mapIndexed { i, v -> if (i == n) new else v }
fun moveSingle(from: Int, to: Int): Stacks = moveN(1, from, to)
fun moveN(n: Int, from: Int, to: Int): Stacks {
val c = state[from].takeLast(n)
val newState = state
.replace(from, state[from].dropLast(n))
.replace(to, state[to] + c)
return Stacks(newState)
}
fun applyPart1(c: Command) = applyN(this, c.n) { it.moveSingle(c.from - 1, c.to - 1) }
fun applyPart2(c: Command) = moveN(c.n, c.from - 1, c.to - 1)
}
}
fun parseToStack(s: List<String>): Day05.Stacks {
val r = s.reversed()
val maxIndex = r[0].max().digitToInt()
val tail = r.drop(1)
val stacks = (0 until maxIndex).map { col ->
val index = (col * 4) + 1
tail.takeWhile { index < it.length }
.map { it[index] }
.filter { it in 'A'..'Z' || it in 'a'..'z' }
.joinToString("")
}.toList()
return Day05.Stacks(stacks)
}
fun main() {
val testInput = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2""".split("\n")
fun parse(input: List<String>): Pair<Day05.Stacks, Sequence<Day05.Command>> {
val (rawState, rawCommands) = blocksOfLines(input).toList()
val state = parseToStack(rawState)
val commands = rawCommands.parsedBy("move (\\d+) from (\\d+) to (\\d+)".toRegex()) {
val (count, from, to) = it.destructured
Day05.Command(count.toInt(), from.toInt(), to.toInt())
}
return state to commands
}
fun part1(input: List<String>): String {
val (state, commands) = parse(input)
return commands.fold(state) { s, command -> s.applyPart1(command) }.tops().joinToString("")
}
fun part2(input: List<String>): String {
val (state, commands) = parse(input)
return commands.fold(state) { s, command -> s.applyPart2(command) }.tops().joinToString("")
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == "CMZ")
val puzzleInput = InputUtils.downloadAndGetLines(2022, 5)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 3,156 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch6/Problem69.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch6
import dev.bogwalk.util.maths.primeFactors
import dev.bogwalk.util.maths.primeNumbers
import kotlin.math.pow
/**
* Problem 69: Totient Maximum
*
* https://projecteuler.net/problem=69
*
* Goal: Find the smallest value of n < N for which n / Phi(n) is maximum.
*
* Constraints: 3 <= N <= 1e18
*
* Euler's Totient Function: Phi(n) is used to determine the count of positive integers < n that are
* relatively prime to n. An integer k is relatively prime to n (aka co-prime or its totative) if
* gcd(n, k) = 1, as the only positive integer that is a divisor of both of them is 1.
* n = 2 -> {1} -> Phi(n) = 1; n/Phi(n) = 2
* n = 3 -> {1, 2} -> Phi(n) = 2; n/Phi(n) = 1.5
* n = 4 -> {1, 3} -> Phi(n) = 2; n/Phi(n) = 2
* n = 5 -> {1, 2, 3, 4} -> Phi(n) = 4; n/Phi(n) = 1.25
* n = 6 -> {1, 5} -> Phi(n) = 2; n/Phi(n) = 3
* n = 7 -> {1, 2, 3, 4, 5, 6} -> Phi(n) = 6; n/Phi(n) = 1.1666...
* n = 8 -> {1, 3, 5, 7} -> Phi(n) = 4; n/Phi(n) = 2
* n = 9 -> {1, 2, 4, 5, 7, 8} -> Phi(n) = 6; n/Phi(n) = 1.5
* n = 10 -> {1, 3, 7, 9} -> Phi(n) = 4; n/Phi(n) = 2.5
*
* e.g.: N = 3
* n = 2
* N = 10
* n = 6
*/
class TotientMaximum {
/**
* Solution calculates the totient of each n under [limit] & returns the first n that
* achieves the maximum ratio.
*
* SPEED (WORSE) 10.22s for N = 1e6
*/
fun maxTotientRatio(limit: Long): Long {
var maxValues = 1L to 1.0
for (n in 2..limit) {
val currentTotient = totient(n)
val currentRatio = 1.0 * n / currentTotient
if (currentRatio > maxValues.second) {
maxValues = n to currentRatio
}
}
return maxValues.first
}
/**
* Based on Euler's product formula:
*
* Phi(n) = n * Pi(1 - (1/p)), with p being distinct prime factors of n.
*
* This is equivalent to the formula that doesn't use fractions:
*
* Phi(n) = p_1^(e_1 - 1)(p_1 - 1) * p_2^(e_2 - 1)(p_2 - 1)... p_r(e_r - 1)(p_r - 1)
*
* e.g. Phi(20) = Phi({2^2, 5^1}) = 2^1 * 1 * 5^0 * 4 = 8
*/
private fun totient(n: Long): Long {
val primeFactors = primeFactors(n)
var count = 1L
for ((p, e) in primeFactors.entries) {
count *= (1.0 * p).pow(e - 1).toLong() * (p - 1)
}
return count
}
/**
* Solution optimised by taking Euler's product formula further:
*
* Phi(n) = n * Pi(1 - (1/p)), with p being distinct prime factors of n.
*
* If the ratio n / Phi(n) is the required result, this becomes:
*
* n/Phi(n) = n / (n * Pi(1 - (1/p)))
* n/Phi(n) = Pi(p / (p - 1))
*
* Among all numbers having exactly k-distinct prime factors, the quotient is maximised for
* those numbers divisible by the k-smallest primes. So if n_k is the product of the
* k-smallest primes, n_k/Phi(n_k) is maximised over all n/Phi(n) that occur for n < n_{k+1}.
*
* N.B. Upper constraints 1e18 will be reached by prime number 47.
*
* SPEED (BETTER) 5.0e4ns for N = 1e6
*/
fun maxTotientRatioPrimorial(n: Long): Long {
val primes = primeNumbers(50)
var maxN = 1L
for (p in primes) {
// maxN < 1e18 occurs for prime = 43; if this is multiplied by 47, it will overflow
// Long's 64 bits & not return the correct answer for N = 1e18, so, unlike with Python,
// the loop break has to be determined before the limit is exceeded.
if (maxN >= (n + p - 1) / p) break
maxN *= p
}
return maxN
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,744 | project-euler-kotlin | MIT License |
src/main/kotlin/days/Day9.kt | VictorWinberg | 433,748,855 | false | {"Kotlin": 26228} | package days
class Day9 : Day(9) {
private fun parseInput() = inputList.map { it.toList().map { it.toString().toInt() } }
override fun partOne(): Any {
val input = parseInput()
return locations(input).sumOf { (x, y) -> input[y][x] + 1 }
}
override fun partTwo(): Any {
val input = parseInput()
return locations(input)
.map { (x, y) -> rec(input, x, y, HashMap()) }
.sortedDescending()
.take(3)
.fold(1) { acc, i -> acc * i }
}
private fun rec(input: List<List<Int>>, x: Int, y: Int, visited: HashMap<Pair<Int, Int>, Boolean>): Int {
if (visited.putIfAbsent(Pair(y, x), true) == true) return 0
val basins = listOf(Pair(y - 1, x), Pair(y + 1, x), Pair(y, x + 1), Pair(y, x - 1))
.map { pos -> Pair(pos, input.getOrNull(pos.first)?.getOrNull(pos.second) ?: 9) }
.filter { it.second != 9 }
return 1 + basins.sumOf { rec(input, it.first.second, it.first.first, visited) }
}
private fun locations(input: List<List<Int>>): MutableList<Pair<Int, Int>> {
val locations = mutableListOf<Pair<Int, Int>>()
input.indices.forEach { y ->
input[0].indices.forEach { x ->
val lowestNeighbour = listOf(Pair(y - 1, x), Pair(y + 1, x), Pair(y, x + 1), Pair(y, x - 1))
.map { pos -> input.getOrNull(pos.first)?.getOrNull(pos.second) ?: 9 }
.minOf { it }
if (input[y][x] < lowestNeighbour) {
locations.add(Pair(x, y))
}
}
}
return locations
}
}
| 0 | Kotlin | 0 | 0 | d61c76eb431fa7b7b66be5b8549d4685a8dd86da | 1,660 | advent-of-code-kotlin | Creative Commons Zero v1.0 Universal |
src/main/kotlin/adventofcode2018/Day06ChronalCoordinates.kt | n81ur3 | 484,801,748 | false | {"Kotlin": 476844, "Java": 275} | package adventofcode2018
class Day06ChronalCoordinates
data class Coordinate(val id: Int, val x: Int, val y: Int) {
fun manhattanDistance(fromX: Int, fromY: Int): Int {
val xDist = if (fromX > x) (fromX - x) else (x - fromX)
val yDist = if (fromY > y) (fromY - y) else (y - fromY)
return xDist + yDist
}
companion object {
var counter = 0
fun fromString(input: String): Coordinate {
return Coordinate(counter++, input.substringBefore(",").toInt(), input.substringAfter(", ").toInt())
}
}
}
class CoordinateSystem(input: List<String>) {
val coordinates: List<Coordinate>
val fields = mutableListOf<Coordinate>()
val xMin: Int
val xMax: Int
val yMin: Int
val yMax: Int
init {
coordinates = input.map { Coordinate.fromString(it) }
xMin = coordinates.minOf { it.x }
xMax = coordinates.maxOf { it.x }
yMin = coordinates.minOf { it.y }
yMax = coordinates.maxOf { it.y }
}
fun innerCoordinates(): List<Coordinate> {
return coordinates.filter {
it.x > xMin && it.x < xMax && it.y > yMin && it.y < yMax
}
}
private fun mapFields() {
(0..xMax).forEach { x ->
(0..yMax).forEach { y ->
findClosestInnerCoordinate(x, y)?.run { fields.add(this) }
}
}
}
private fun findClosestInnerCoordinate(x: Int, y: Int): Coordinate? {
val inner = innerCoordinates()
val distances = coordinates.map { it to it.manhattanDistance(x, y) }.sortedBy { it.second }
.filter { x >= xMin && x <= xMax && y >= yMin && y <= yMax }
if (distances.isEmpty()) return Coordinate(-1, x, y)
if (distances[0].second == distances[1].second) return Coordinate(-1, x, y)
if (!(inner.contains(distances[0].first))) return Coordinate(-1, x, y)
return Coordinate(distances[0].first.id, x, y)
}
fun calcLargestInnerFieldSize(): Int {
mapFields()
val innerFields = fields.filterNot { it.id == -1 }
val groupedFields = innerFields.groupBy { it.id }
return groupedFields.filterNot { isInfiniteGroup(it.value) }.maxOf { it.value.size }
}
private fun isInfiniteGroup(group: List<Coordinate>) = group.any { outOfBounds(it) }
private fun outOfBounds(it: Coordinate) = it.x <= xMin || it.x >= xMax || it.y <= yMin || it.y >= yMax
fun printSystem() {
(0..yMax).forEach { y ->
(0..xMax).forEach { x ->
fields.firstOrNull { it.x == x && it.y == y }?.run {
if (id == -1) print('.') else print(id)
} ?: print('.')
}
println()
}
}
fun sizeOfLargestSafeRegion(range: Int): Int {
var counter = 0
(0..yMax).forEach { y ->
(0..xMax).forEach { x ->
if (calcTotalDistance(x, y) < range) counter++
}
}
return counter
}
private fun calcTotalDistance(x: Int, y: Int): Int {
return coordinates.sumOf { it.manhattanDistance(x, y) }
}
} | 0 | Kotlin | 0 | 0 | fdc59410c717ac4876d53d8688d03b9b044c1b7e | 3,145 | kotlin-coding-challenges | MIT License |
src/main/kotlin/com/anahoret/aoc2022/day25/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day25
import java.io.File
import kotlin.math.pow
import kotlin.system.measureTimeMillis
private val snafuCoding = mapOf(
'2' to 2,
'1' to 1,
'0' to 0,
'-' to -1,
'=' to -2
)
private val reverseSnafuCoding = snafuCoding.map { (key, value) -> value to key }.toMap()
fun snafuToDec(snafu: String): Long {
return snafu
.map(snafuCoding::getValue)
.reversed()
.foldIndexed(0L) { pow, acc, c -> acc + (c * 5.pow(pow)) }
}
fun Int.pow(n: Int): Long {
return this.toDouble().pow(n).toLong()
}
data class MulPower(val mul: Int, val power: Int)
fun decToSnafu(dec: Long): String {
fun sumPower5(pow: Int, mul: Int): Long {
return (0..pow).fold(0L) { acc, p -> acc + mul * 5.pow(p) }
}
fun loop(acc: List<MulPower> = mutableListOf()): List<Int> {
val accVal = acc.fold(0L) { accV, (mul, pow) -> accV + mul * 5.pow(pow) }
if (accVal == dec) {
val minPow = acc.minOf(MulPower::power)
val multipliers = acc.map(MulPower::mul)
return if (minPow == 0) multipliers
else multipliers + List(minPow) { 0 }
}
val nextPow = acc.minOfOrNull(MulPower::power)?.dec()
?: (0..Int.MAX_VALUE).first { 2 * 5.pow(it) >= dec }
val nextMul = if (accVal > dec) {
(-2 .. 0).find { accVal + it * 5.pow(nextPow) + sumPower5(nextPow - 1, 2) >= dec } ?: -2
} else {
(2 downTo 0).find { accVal + it * 5.pow(nextPow) + sumPower5(nextPow - 1, -2) <= dec } ?: 2
}
return loop(acc + MulPower(nextMul, nextPow))
}
return loop().joinToString(separator = "") { reverseSnafuCoding.getValue(it).toString() }
}
fun main() {
val input = File("src/main/kotlin/com/anahoret/aoc2022/day25/input.txt")
.readText()
.trim()
part1(input).also { println("P1: ${it}ms") }
}
private fun part1(input: String) = measureTimeMillis {
input.lines()
.fold(0L) { acc, snafu -> acc + snafuToDec(snafu) }
.let(::decToSnafu)
.also(::println)
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 2,098 | advent-of-code-2022 | Apache License 2.0 |
workshops/moscow_prefinals2020/day4/k.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package workshops.moscow_prefinals2020.day4
fun main() {
val (n, m) = readInts()
val g = MutableList(n) { DoubleArray(n) }
repeat(m) {
val (uIn, vIn, resistance) = readInts()
for ((u, v) in listOf(uIn, vIn).map { it - 1 }.withReversed()) {
g[u][v] += 1.0 / resistance
g[u][u] -= 1.0 / resistance
}
}
val potential = List(n) { kirchhoff(g, 0, it) }
val current = List(n) { v -> g.indices.sumByDouble { potential[v][it] * g[0][it] } }
val ans = List(n) { v -> DoubleArray(v) { u ->
if (u == 0) return@DoubleArray 1 / current[v]
fun newPotential(w: Int) = potential[u][w] - potential[v][w] * current[u] / current[v]
val (npu, npv) = listOf(u, v).map(::newPotential)
1 / g.indices.sumByDouble { g[u][it] * (newPotential(it) - npu) / (npv - npu) }
}}
println(List(readInt()) {
val (u, v) = readInts().map { it - 1 }.sorted()
ans[v][u]
}.joinToString("\n"))
}
private fun kirchhoff(g: List<DoubleArray>, @Suppress("SameParameterValue") u: Int, v: Int): DoubleArray {
val gClone = g.map { it.clone() }
listOf(u, v).forEach { gClone[it].fill(0.0); gClone[it][it] = 1.0 }
val h = DoubleArray(gClone.size).also { it[v] = 1.0 }
return gauss(gClone, h)
}
private fun gauss(a: List<DoubleArray>, b: DoubleArray): DoubleArray {
val m = a.size
val n = a[0].size
val pos = IntArray(m)
for (i in 0 until m) {
val ai = a[i]
val s = (0 until n).maxByOrNull { ai[it].abs() }!!
pos[i] = s
for (k in 0 until m) if (k != i) {
val ak = a[k]
val c = -ak[s] / ai[s]
for (j in 0 until n) ak[j] += c * ai[j]
b[k] += c * b[i]
}
}
val ans = DoubleArray(n)
for (i in 0 until m) ans[pos[i]] = b[i] / a[i][pos[i]]
return ans
}
private fun <T> Iterable<T>.withReversed() = listOf(toList(), reversed())
private fun Double.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,972 | competitions | The Unlicense |
src/main/kotlin/aoc2021/Day14.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
/**
* @param input the input polymer string
* @param rules a map of polymer transformation rules. Key=Input elements, Value=Element to be inserted between the input elements
* @return a polymer string constructed by taking the [input] string an applying all the [rules] simultaneously
*/
private fun applyRules(input: String, rules: Map<String, Char>) =
input.windowed(2).map { it[0] + rules.getOrDefault(it, it).toString() + it[1] }
.foldIndexed(StringBuilder()) { index, acc, s ->
if (index == 0) acc.append(s) else acc.append(s.drop(1))
}.toString()
/**
* Parses the input for to a map of polymer transformation rules
*/
private fun parseRules(input: List<String>) =
input.drop(2).map { it.split(" -> ") }.associate { Pair(it[0], it[1].first()) }
/**
* Calculates the result number for aoc2021.part1 & aoc2021.part2 based on the occurrences of each character in the final polymer string
*/
private fun calculateResult(occurrences: Map<Char, Long>) =
occurrences.values.maxOf { it } - occurrences.values.minOf { it }
private fun part1(input: List<String>): Int {
var current = input.first()
val rules = parseRules(input)
repeat(10) { current = applyRules(current, rules) }
val occurrences = current.toCharArray().groupBy { it }.mapValues { it.value.size.toLong() }
return calculateResult(occurrences).toInt()
}
/**
* A polymer factory to generate a polymer string based on an initial polymer and a set of transformation rules.
*
* @param input the initial polymer string
* @property rules the transformation rules. Key=Pair of characters, Value=Character to place in between the Key in a single step
*/
private class PolymerFactory(input: String, private val rules: Map<String, Char>) {
private val lastCharacter = input.last()
private val occurrences: MutableMap<String, Long> = HashMap(26 * 26)
init {
input.windowed(2).forEach { occurrences[it] = (occurrences[it] ?: 0L) + 1 }
}
/**
* Performs one building step, e.g. applies all the rules once
*/
fun performBuildStep() {
val diff: MutableMap<String, Long> = HashMap(rules.size)
for (rule in rules) {
val currentCount = occurrences[rule.key] ?: 0L
if (currentCount > 0L) {
diff[rule.key] = (diff[rule.key] ?: 0L) - currentCount
val newPair1 = String(charArrayOf(rule.key[0], rule.value))
val newPair2 = String(charArrayOf(rule.value, rule.key[1]))
diff[newPair1] = (diff[newPair1] ?: 0L) + currentCount
diff[newPair2] = (diff[newPair2] ?: 0L) + currentCount
}
}
diff.forEach { occurrences[it.key] = (occurrences[it.key] ?: 0L) + it.value }
}
/**
* @return the number of occurrences of each character in the current polymer
*/
fun getOccurrences(): Map<Char, Long> {
val result: MutableMap<Char, Long> = HashMap(26)
occurrences.forEach { result[it.key.first()] = (result[it.key.first()] ?: 0L) + it.value }
result[lastCharacter] = (result[lastCharacter] ?: 0) + 1
return result
}
}
private fun part2(input: List<String>): Long {
val rules = parseRules(input)
val factory = PolymerFactory(input.first(), rules)
repeat(40) {
factory.performBuildStep()
}
return calculateResult(factory.getOccurrences())
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 1588)
check(part2(testInput) == 2188189693529L)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,755 | adventOfCode | Apache License 2.0 |
y2018/src/main/kotlin/adventofcode/y2018/Day25.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2018
import adventofcode.io.AdventSolution
import kotlin.math.abs
fun main() = Day25.solve()
object Day25 : AdventSolution(2018, 25, "Four-Dimensional Adventure") {
override fun solvePartOne(input: String): Int {
val constellations = input.splitToSequence('\n', ',')
.map(String::toInt)
.chunked(4)
.toList()
val mergeFind = DisjointUnionSets(constellations.size)
for (a in constellations.indices)
for (b in 0 until a)
if (distance(constellations[a], constellations[b]) <= 3)
mergeFind.union(a, b)
return mergeFind.countSets()
}
override fun solvePartTwo(input: String) = "Free Star! ^_^"
}
private fun distance(xs: List<Int>, ys: List<Int>) = xs.zip(ys) { x, y -> abs(x - y) }.sum()
private class DisjointUnionSets(n: Int) {
private val rank: IntArray = IntArray(n)
private val parent: IntArray = IntArray(n) { it }
private var numDisjoint = n
fun findRoot(x: Int): Int {
if (parent[x] != x)
parent[x] = findRoot(parent[x])
return parent[x]
}
fun union(x: Int, y: Int) {
val xRoot = findRoot(x)
val yRoot = findRoot(y)
when {
xRoot == yRoot -> return
rank[xRoot] < rank[yRoot] -> parent[xRoot] = yRoot
rank[yRoot] < rank[xRoot] -> parent[yRoot] = xRoot
else -> {
parent[yRoot] = xRoot
rank[xRoot]++
}
}
numDisjoint--
}
fun countSets() = numDisjoint
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,620 | advent-of-code | MIT License |
src/Day07.kt | paul-griffith | 572,667,991 | false | {"Kotlin": 17620} | private sealed interface Node {
val name: String
val size: Int
}
private data class File(
override val name: String,
override val size: Int
) : Node
private data class Directory(
override val name: String,
val children: MutableMap<String, Node> = mutableMapOf()
) : Node, MutableMap<String, Node> by children {
lateinit var parent: Directory
override val size: Int
get() = children.values.sumOf { it.size }
}
private val pattern =
"""(\$ (?<cmd>cd|ls)(?> (?<target>.+))?|dir (?<directory>.+)|(?<filesize>\d+) (?<filename>.+))""".toRegex()
fun main() {
fun parseCommandsToTree(lines: Sequence<String>): Directory {
val root = Directory("/")
var currentDirectory = root
for (line in lines.drop(1)) {
val matchResult = pattern.find(line)!!
val cmd = matchResult.groups["cmd"]?.value
val target = matchResult.groups["target"]?.value
val directory = matchResult.groups["directory"]?.value
val filesize = matchResult.groups["filesize"]?.value
val filename = matchResult.groups["filename"]?.value
if (cmd == "cd") {
currentDirectory = if (target == "..") {
currentDirectory.parent
} else {
val newCurrent = currentDirectory.getOrPut(target!!) { Directory(target) } as Directory
newCurrent.parent = currentDirectory
newCurrent
}
} else if (directory != null) {
currentDirectory[directory] = Directory(directory)
} else if (filename != null) {
currentDirectory[filename] = File(filename, filesize!!.toInt())
}
}
return root
}
fun Directory.depthFirstSearch(): Sequence<Node> {
return sequence {
yield(this@depthFirstSearch)
for (child in children.values) {
when (child) {
is Directory -> yieldAll(child.depthFirstSearch())
is File -> yield(child)
}
}
}
}
fun part1(lines: Sequence<String>): Int {
val root = parseCommandsToTree(lines)
return root.depthFirstSearch().filterIsInstance<Directory>().filter { it.size < 100_000 }.sumOf { it.size }
}
fun part2(lines: Sequence<String>): Int {
val root = parseCommandsToTree(lines)
val currentFreeSpace = 70_000_000 - root.size
val neededFreeSpace = 30_000_000
val missingFreeSpace = neededFreeSpace - currentFreeSpace
return root.depthFirstSearch()
.filterIsInstance<Directory>()
.filter { it.size >= missingFreeSpace }
.minBy { it.size }
.size
}
val sample = sequenceOf(
"\$ cd /",
"\$ ls",
"dir a",
"14848514 b.txt",
"8504156 c.dat",
"dir d",
"\$ cd a",
"\$ ls",
"dir e",
"29116 f",
"2557 g",
"62596 h.lst",
"\$ cd e",
"\$ ls",
"584 i",
"\$ cd ..",
"\$ cd ..",
"\$ cd d",
"\$ ls",
"4060174 j",
"8033020 d.log",
"5626152 d.ext",
"7214296 k",
)
// println(part1(sample))
println(part1(readInput("day07")))
println(part2(readInput("day07")))
}
| 0 | Kotlin | 0 | 0 | 100a50e280e383b784c3edcf65b74935a92fdfa6 | 3,416 | aoc-2022 | Apache License 2.0 |
src/Day16.kt | robinpokorny | 572,434,148 | false | {"Kotlin": 38009} | import kotlin.math.*
private data class Valve(
val name: String,
val flow: Int,
val nearby: List<String>
)
private val lineRe =
Regex("Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? (.*)")
private fun parse(input: List<String>): List<Valve> = input
.map { line ->
val (name, flow, nearby) = lineRe.matchEntire(line)!!.destructured
Valve(name, flow.toInt(), nearby.split(", "))
}
// Distances[i][j] -> from i to j or null
typealias Distances = MutableMap<String, MutableMap<String, Int?>>
// Floyd–Warshall
private fun shortestPaths(distances: Distances) {
for (k in distances.keys) {
for (i in distances.keys) {
for (j in distances.keys) {
distances[i]!![j] = listOfNotNull(
distances[i]!![j],
distances[k]!![j]?.let { distances[i]!![k]?.plus(it) }
).minOrNull()
}
}
}
}
private fun dfs(
paths: Distances,
valves: Map<String, Valve>,
seen: Set<String>,
current: String,
score: Int,
time: Int
): Int = paths[current]!!
.maxOf { (valve, dist) ->
if (!seen.contains(valve) && time + dist!! + 1 < 30) {
val newScore = score + (30 - time - dist - 1) * valves[valve]!!.flow
dfs(
paths,
valves,
seen + valve,
valve,
newScore,
time + dist + 1,
)
}
else
score
}
private fun part1(valves: List<Valve>): Int {
val paths: Distances = valves.associate {
Pair(
it.name,
it.nearby
.associateWith<String, Int?> { 1 }
.plus(it.name to 0)
.toMutableMap()
)
}.toMutableMap()
shortestPaths(paths)
val zeroFlowValveNames = valves.filter { it.flow == 0 }.map { it.name }
zeroFlowValveNames.forEach { name ->
paths.values.forEach { it.remove(name) }
}
return dfs(
paths,
valves.associateBy { it.name }.toMap(),
emptySet(),
"AA",
0,
0
)
}
private fun part2(input: List<String>): Int {
return 0
}
fun main() {
val input = parse(readDayInput(16))
val testInput = parse(rawTestInput)
// PART 1
assertEquals(part1(testInput), 1651)
println("Part1: ${part1(input)}")
// PART 2
// assertEquals(part2(testInput), 0)
// println("Part2: ${part2(input)}")
}
private val rawTestInput = """
Valve AA has flow rate=0; tunnels lead to valves DD, II, BB
Valve BB has flow rate=13; tunnels lead to valves CC, AA
Valve CC has flow rate=2; tunnels lead to valves DD, BB
Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE
Valve EE has flow rate=3; tunnels lead to valves FF, DD
Valve FF has flow rate=0; tunnels lead to valves EE, GG
Valve GG has flow rate=0; tunnels lead to valves FF, HH
Valve HH has flow rate=22; tunnel leads to valve GG
Valve II has flow rate=0; tunnels lead to valves AA, JJ
Valve JJ has flow rate=21; tunnel leads to valve II
""".trimIndent().lines() | 0 | Kotlin | 0 | 2 | 56a108aaf90b98030a7d7165d55d74d2aff22ecc | 3,187 | advent-of-code-2022 | MIT License |
2k23/aoc2k23/src/main/kotlin/17.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d17
import java.util.*
fun main() {
println("Part 1: ${part1(input.read("17.txt"))}")
println("Part 2: ${part2(input.read("17.txt"))}")
}
fun part1(input: List<String>): Int =
FactoryCity(input).minimizeHeatLoss(1, 3)
fun part2(input: List<String>): Int =
FactoryCity(input).minimizeHeatLoss(4, 10)
class FactoryCity(input: List<String>) {
data class Point(val x: Int, val y: Int) {
fun move(delta: Point): Point = Point(x + delta.x, y + delta.y)
}
enum class Direction(val point: Point) {
North(Point(0, -1)),
South(Point(0, 1)),
East(Point(1, 0)),
West(Point(-1, 0));
private fun opposite(): Direction =
when (this) {
North -> South
South -> North
East -> West
West -> East
}
fun directions(): List<Direction> =
entries.filter { it != this.opposite() }
}
data class TravelState(val position: Point, val direction: Direction, val steps: Int)
data class TravelHeatLoss(val state: TravelState, val heatLoss: Int) : Comparable<TravelHeatLoss> {
override fun compareTo(other: TravelHeatLoss): Int {
return heatLoss compareTo other.heatLoss
}
}
private val map = input.map { row -> row.map { it.digitToInt() } }
private val xMax = map.first().lastIndex
private val yMax = map.lastIndex
private val dest = Point(xMax, yMax)
private val orig = Point(0, 0)
private fun visit(point: Point): Int = map[point.y][point.x]
fun minimizeHeatLoss(minSteps: Int, maxSteps: Int): Int {
val heatLosses = mutableMapOf<TravelState, Int>().withDefault { Int.MAX_VALUE }
val toVisit = PriorityQueue<TravelHeatLoss>()
Direction.entries.forEach { dir ->
val state = TravelState(orig, dir, 0)
heatLosses[state] = 0
toVisit.add(TravelHeatLoss(state, 0))
}
while (toVisit.isNotEmpty()) {
val (currentState, heatLoss) = toVisit.poll();
if (currentState.position == dest && currentState.steps >= minSteps) {
return heatLoss
}
neighbors(currentState, minSteps, maxSteps).forEach { newState ->
val newHeatLoss = heatLoss + visit(newState.position)
if (newState !in heatLosses) {
heatLosses[newState] = newHeatLoss
toVisit.add(TravelHeatLoss(newState, newHeatLoss))
}
}
}
return -1
}
private fun neighbors(state: TravelState, minSteps: Int, maxSteps: Int): List<TravelState> {
return state.direction.directions().filter { dir ->
if (state.steps < minSteps) {
dir == state.direction
} else if (state.steps >= maxSteps) {
dir != state.direction
} else {
true
}
}
.map { dir ->
TravelState(
state.position.move(dir.point),
dir,
if (dir == state.direction) state.steps + 1 else 1
)
}
.filter { inBound(it.position) && it.steps <= maxSteps }
}
private fun inBound(point: Point): Boolean = point.x in 0..xMax && point.y in 0..yMax
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 3,395 | aoc | The Unlicense |
src/Day11.kt | lsimeonov | 572,929,910 | false | {"Kotlin": 66434} |
fun main() {
class Monkey(
val id: Int,
val operation: (Long) -> Long,
val test: (Long) -> Int,
var Items: ArrayDeque<Long>,
var div: Long,
var activity: Long
)
fun part1(input: List<String>): Long {
return 0.toLong()
}
fun part2(input: List<String>): Long {
val MonkeyList = mutableListOf<Monkey>()
input.chunked(7).forEach { mi ->
val id = mi[0].filter { it.isDigit() }.toInt()
val items = mi[1].substringAfter(":").split(",").map { it.trim().toLong() }.toCollection(ArrayDeque())
var operationParts = mi[2].substringAfter("= ").split(" ")
val operationFunction = fun(w: Long): Long {
val rightValue = if (operationParts[2] == "old") {
w
} else {
operationParts[2].toLong()
}
return when (operationParts[1]) {
"+" -> w + rightValue
"*" -> w * rightValue
else -> w
}
}
var mod = mi[3].substringAfter(": ").filter { it.isDigit() }.toLong()
var t = mi[4].filter { it.isDigit() }.toInt()
val f = mi[5].filter { it.isDigit() }.toInt()
val testFunction = fun(w: Long): Int {
return if (w % mod == 0.toLong()) {
t
} else {
f
}
}
MonkeyList.add(Monkey(id, operationFunction, testFunction, items, mod, 0.toLong()))
}
val cmod = MonkeyList.fold(1.toLong()) { acc, it -> acc * it.div }
for (i in 1..10000) {
MonkeyList.forEach { monkey ->
for (j in 0 until monkey.Items.size) {
monkey.activity++
val item = monkey.Items.removeFirst()
var newWorryLevel = monkey.operation(item).mod(cmod)
val toMonkey = monkey.test(newWorryLevel)
MonkeyList[toMonkey].Items.add(newWorryLevel)
}
}
}
var sort = MonkeyList.sortedByDescending { it.activity }
return sort[0].activity * sort[1].activity
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
// check(part1(testInput) == (10605).toLong())
check(part2(testInput) == (2713310158).toLong())
val input = readInput("Day11")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9d41342f355b8ed05c56c3d7faf20f54adaa92f1 | 2,599 | advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | chbirmes | 572,675,727 | false | {"Kotlin": 32114} | fun main() {
fun part1(input: List<String>): Int =
input.asSequence()
.filter { it.isNotEmpty() }
.map { PacketElement.ElementList.parse(it) }
.chunked(2)
.map { Pair(it[0], it[1]) }
.mapIndexed { index, pair -> if (pair.first < pair.second) index + 1 else 0 }
.sum()
fun part2(input: List<String>): Int {
val divider1 = PacketElement.ElementList.parse("[[2]]")
val divider2 = PacketElement.ElementList.parse("[[6]]")
val elementLists = input.asSequence()
.filter { it.isNotEmpty() }
.map { PacketElement.ElementList.parse(it) } + divider1 + divider2
return elementLists.sorted()
.let { (it.indexOf(divider1) + 1) * (it.indexOf(divider2) + 1) }
}
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
sealed class PacketElement : Comparable<PacketElement> {
override operator fun compareTo(other: PacketElement): Int {
return when (this) {
is ElementList -> when (other) {
is ElementList -> {
list.asSequence().zip(other.list.asSequence()) { a, b -> a.compareTo(b) }
.firstOrNull { it != 0 }
?: list.size.compareTo(other.list.size)
}
is SingleInt -> compareTo(ElementList(mutableListOf(other)))
}
is SingleInt -> when (other) {
is ElementList -> ElementList(mutableListOf(this)).compareTo(other)
is SingleInt -> i.compareTo(other.i)
}
}
}
data class SingleInt(val i: Int) : PacketElement()
data class ElementList(val list: MutableList<PacketElement> = mutableListOf()) : PacketElement() {
var parent: ElementList? = null
companion object {
fun parse(s: String): ElementList {
val root = ElementList()
parseStep(s.substring(1, s.length - 1), root)
return root
}
private tailrec fun parseStep(s: String, current: ElementList) {
if (s.isNotEmpty()) {
val (rest, newCurrent) = when (s.first()) {
'[' -> {
val newList = ElementList()
newList.parent = current
current.list.add(newList)
Pair(s.drop(1), newList)
}
']' -> Pair(s.drop(1), current.parent!!)
',' -> Pair(s.drop(1), current)
else -> {
val number = s.takeWhile { it.isDigit() }
current.list.add(SingleInt(number.toInt()))
Pair(s.substringAfter(number), current)
}
}
parseStep(rest, newCurrent)
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | db82954ee965238e19c9c917d5c278a274975f26 | 3,165 | aoc-2022 | Apache License 2.0 |
2021/src/day03/Day03.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day03
import readInput
fun part1(lines: List<String>) : Int {
val counts = MutableList(lines[0].length) { 0 }
lines.forEach { line ->
counts.forEachIndexed { idx, _ ->
counts[idx] = if (line[idx] == '1') {
counts[idx] + 1
} else {
counts[idx] - 1
}
}
}
var gamma = 0
var epsilon = 0
counts.map {
val gammaBit = if (it > 0) { 1 } else { 0 }
val epsilonBit = if (it > 0) { 0 } else { 1 }
gamma = gamma.shl(1) or gammaBit
epsilon = epsilon.shl(1) or epsilonBit
}
return gamma * epsilon
}
enum class Type {
OXYGEN_GENERATOR_RATING,
CO2_SCRUBBER_RATING
}
fun find_rating(lines: List<String>, type: Type, pos: Int = 0) : String {
if (lines.size == 1) {
return lines[0]
}
var count = 0
lines.forEach { line -> if (line[pos] == '1') { count++ } else { count-- } }
val keepOnes = if (type == Type.OXYGEN_GENERATOR_RATING) {
count >= 0 // If 0 and 1 are equally common, keep values with a 1 in the position being considered
} else {
count < 0 // If 0 and 1 are equally common, keep values with a 0 in the position being considered.
}
return find_rating(lines.filter {
it[pos] == if (keepOnes) { '1' } else { '0' }
}, type, pos + 1)
}
fun part2(lines: List<String>) : Int {
val ogr = find_rating(lines, Type.OXYGEN_GENERATOR_RATING)
val csr = find_rating(lines, Type.CO2_SCRUBBER_RATING)
return ogr.toInt(2) * csr.toInt(2)
}
fun main() {
val testInput = readInput("day03/test")
println("part1(testInput) => " + part1(testInput))
println("part2(testInput) => " + part2(testInput))
val input = readInput("day03/input")
println("part1(input) => " + part1(input))
println("part1(input) => " + part2(input))
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 1,873 | advent-of-code | Apache License 2.0 |
Advent-of-Code-2023/src/Day19.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day19"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
private data class Rule(val name: Char? = null, val signal: Char? = null, val comparingNum: Int? = null, val destiny: String)
private fun part1(input: List<String>): Int {
val (part1, part2) = input.joinToString("\n").split("\n\n")
val workflows = part1.split("\n").associate { flow ->
val (partName, rulesToParse) = flow.split("{")
val rules = rulesToParse.removeSuffix("}").split(",").map { part ->
val ruleSplit = part.split(":")
val parsedPart = if (ruleSplit.size == 2) {
val comparingNum = ruleSplit[0].substring(1).split("<", ">")[1].toInt()
Rule(ruleSplit[0].first(), ruleSplit[0][1], comparingNum, ruleSplit[1])
} else {
Rule(destiny = ruleSplit[0])
}
parsedPart
}
partName to rules
}
val ratings = part2.split("\n").map { rating ->
val parts = rating.substring(1..<rating.length - 1).split(",").associate {
val (partName, value) = it.split("=")
partName.first() to value.toInt()
}
parts
}
fun isAccepted(workflowName: String, rating: Map<Char, Int>): Boolean {
if (workflowName == "R") return false
if (workflowName == "A") return true
val rules = workflows[workflowName]!!
for (rule in rules) {
if (rule.name == null) return isAccepted(rule.destiny, rating)
val partValue = rating[rule.name]!!
if (rule.signal == '<' && partValue < rule.comparingNum!!) return isAccepted(rule.destiny, rating)
else if (rule.signal == '>' && partValue > rule.comparingNum!!) return isAccepted(rule.destiny, rating)
}
return false
}
return ratings.sumOf { rating ->
val sum = if (isAccepted("in", rating)) {
rating.values.sum()
} else 0
sum
}
}
private fun part2(input: List<String>): Long {
val (part1, _) = input.joinToString("\n").split("\n\n")
val workflows = part1.split("\n").associate { flow ->
val (partName, rulesToParse) = flow.split("{")
val rules = rulesToParse.removeSuffix("}").split(",").map { part ->
val ruleSplit = part.split(":")
val parsedPart = if (ruleSplit.size == 2) {
val comparingNum = ruleSplit[0].substring(1).split("<", ">")[1].toInt()
Rule(ruleSplit[0].first(), ruleSplit[0][1], comparingNum, ruleSplit[1])
} else {
Rule(destiny = ruleSplit[0])
}
parsedPart
}
partName to rules
}
fun countAccepted(workflowName: String, rating: MutableMap<Char, IntRange>): Long {
if (workflowName == "R") return 0
if (workflowName == "A") return rating.values.fold(1L) { acc, range ->
acc * (range.last - range.first + 1)
}
val rules = workflows[workflowName]!!
var total = 0L
for (rule in rules.dropLast(1)) {
val partRange = rating[rule.name]!!
val (trueRange, falseRange) = if (rule.signal == '<') {
Pair(partRange.first..<rule.comparingNum!!, rule.comparingNum..partRange.last)
} else {
Pair(rule.comparingNum!! + 1..partRange.last, partRange.first..rule.comparingNum)
}
if (trueRange.first <= trueRange.last) {
val newRating = rating.toMutableMap()
newRating[rule.name!!] = trueRange
total += countAccepted(rule.destiny, newRating)
}
if (falseRange.first <= falseRange.last) {
rating[rule.name!!] = falseRange
} else {
break
}
}
total += countAccepted(rules.last().destiny, rating)
return total
}
val ratings = mutableMapOf('x' to 1..4000, 'm' to 1..4000, 'a' to 1..4000, 's' to 1..4000)
return countAccepted("in", ratings)
}
fun main() {
createTestFiles(AOC_DAY)
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 19114
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 167409079868000L
println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 377025" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 135506683246673" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 4,731 | Advent-of-Code-2023 | Apache License 2.0 |
src/day8/Day08.kt | MatthewWaanders | 573,356,006 | false | null | package day8
import utils.readInput
typealias Direction = String
const val up: Direction = "UP"
const val down: Direction = "DOWN"
const val left: Direction = "LEFT"
const val right: Direction = "RIGHT"
fun main() {
val testInput = readInput("Day08_test", "day8")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08", "day8")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>) = inputToMatrix(input).let { matrix ->
matrix.mapIndexed { rowIndex, row ->
row.mapIndexed { columnIndex, value ->
val column = selectColumn(matrix, columnIndex)
if (
treeIsVisible(value, matrix[rowIndex].subList(0, columnIndex), emptyList(), left) ||
treeIsVisible(value, matrix[rowIndex].subList(columnIndex + 1, row.size), emptyList(), right) ||
treeIsVisible(value, emptyList(), column.subList(0, rowIndex), up) ||
treeIsVisible(value, emptyList(), column.subList(rowIndex + 1, matrix.size), down)
) 1 else 0
}
}.sumOf { it.sum() }
}
fun part2(input: List<String>) = inputToMatrix(input).let { matrix ->
matrix.mapIndexed { rowIndex, row ->
row.mapIndexed {columnIndex, value ->
countVisibleTrees(value, matrix[rowIndex].subList(0, columnIndex), emptyList(), left) *
countVisibleTrees(value, matrix[rowIndex].subList(columnIndex + 1, row.size), emptyList(), right) *
countVisibleTrees(value, emptyList(), selectColumn(matrix, columnIndex).subList(0, rowIndex), up) *
countVisibleTrees(value, emptyList(), selectColumn(matrix, columnIndex).subList(rowIndex + 1, matrix.size), down)
}
}.maxOf { it.max() }
}
fun inputToMatrix(input: List<String>): List<List<Int>> = input.map { line -> line.toList().map { tree -> tree.digitToInt() } }
fun treeIsVisible(tree: Int, row: List<Int>, column: List<Int>, direction: Direction) = if (direction == up || direction == down) column.none { it >= tree } else row.none { it >= tree }
fun countVisibleTrees(tree: Int, row: List<Int>, column: List<Int>, direction: Direction) = (if (direction == up || direction == down) column else row).let {relevantDimension ->
if (direction == right || direction == down) {
relevantDimension.indexOfFirst { it >= tree }.let { if (it == -1) relevantDimension.size else it + 1 }
} else {
relevantDimension.indexOfLast { it >= tree }.let { if (it == -1) relevantDimension.size else relevantDimension.size - it }
}
}
fun selectColumn(matrix: List<List<Int>>, columnIndex: Int): List<Int> = matrix.map { it[columnIndex] } | 0 | Kotlin | 0 | 0 | f58c9377edbe6fc5d777fba55d07873aa7775f9f | 2,797 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/DirWalk.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | fun main() {
DirWalk.solve()
}
private object DirWalk {
fun solve() {
val tree = buildTree(readInput())
val sizes = getDirSizes(tree)
// for (size in sizes) {
// println("${size.key.name} ${size.value}")
// }
val smallDirsTotal = sizes.filter { it.value <= 100_000 }.values.sum()
println("Small dirs total: $smallDirsTotal")
val totalSpace = 70_000_000
val targetFreeSpace = 30_000_000
val spaceToFree = targetFreeSpace - (totalSpace - sizes.getValue(tree))
println("Space to free: $spaceToFree")
val sortedDirs = sizes.toList().sortedBy { it.second }
val smallestToDelete = sortedDirs.find { it.second >= spaceToFree }
println("Delete dir ${smallestToDelete?.first?.name}, size: ${smallestToDelete?.second}")
}
private fun readInput(): Sequence<Input> {
return generateSequence(::readLine).map(::parseLine)
}
private fun buildTree(input: Sequence<Input>): Dir {
val root = Dir("/", mutableListOf<Node>())
var dir: Dir = root
val stack = mutableListOf<Dir>()
for (item in input) {
when (item) {
is CommandCd -> {
when (item.path) {
"/" -> {
dir = root
stack.clear()
stack.add(dir)
}
".." -> {
stack.removeLast()
dir = stack.last()
}
else -> {
dir = dir.items.find { if (it is Dir) it.name == item.path else false } as Dir
stack.add(dir)
}
}
}
is CommandLs -> {}
is File -> dir.items.add(item)
is Dir -> dir.items.add(item)
}
}
return root
}
private fun parseLine(line: String): Input {
return when {
line == "$ ls" -> CommandLs()
line.startsWith("$ cd") -> CommandCd(line.substringAfter("$ cd "))
line.startsWith("dir") -> Dir(line.substringAfter("dir "))
else -> {
val parts = line.split(" ")
val size = parts[0].toInt(10)
File(parts[1],size)
}
}
}
private fun getDirSizes(root: Dir): Map<Dir, Int> {
val result = mutableMapOf<Dir, Int>()
fun walk(dir: Dir) {
var current = 0
for (item in dir.items) {
current += when (item) {
is File -> item.size
is Dir -> {
walk(item)
result.getValue(item)
}
}
}
result[dir] = current
}
walk(root)
return result
}
sealed interface Input
data class CommandCd(val path: String) : Input
data class CommandLs(val path: String = ""): Input
sealed interface Node
data class File(val name: String, val size: Int): Node, Input
data class Dir(val name: String, val items: MutableList<Node> = mutableListOf()): Node, Input
}
| 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 3,333 | aoc2022 | MIT License |
src/Day03.kt | Loahrs | 574,175,046 | false | {"Kotlin": 7516} | fun main() {
fun part1(input: List<String>): Int {
val letters : List<Char> = listOf('a'..'z','A'..'Z').flatten()
return input.asSequence().map {
val (leftPocket, rightPocket) = it.chunked(it.length / 2)
val leftPocketSet : HashSet<Char> = hashSetOf()
leftPocket.toCharArray().forEach(leftPocketSet::add)
return@map rightPocket
.toCharArray()
.distinct()
.filter { char -> leftPocketSet.contains(char) }
.sumOf { char -> letters.indexOf(char) + 1 }
}.sum()
}
fun part2(input: List<String>): Int {
val letters : List<Char> = listOf('a'..'z','A'..'Z').flatten()
return input.windowed(size = 3, step = 3)
.map {
val (firstList, secondList, thirdList) = it
firstList.find { char -> secondList.contains(char) and thirdList.contains(char) }
}
.sumOf { letters.indexOf(it) + 1 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
fun getCharValue(char : Char) : Int {
return char.digitToInt()
}
| 0 | Kotlin | 0 | 0 | b1ff8a704695fc6ba8c32a227eafbada6ddc0d62 | 1,330 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | sebokopter | 570,715,585 | false | {"Kotlin": 38263} | import Outcome.*
import Shape.*
enum class Shape(val value: Int) {
Rock(1), Paper(2), Scissors(3);
}
enum class Outcome(val score: Int) {
Win(6), Lose(0), Draw(3);
}
val outcomeMap = mapOf(
(Rock to Paper) to Win,
(Paper to Scissors) to Win,
(Scissors to Rock) to Win,
(Paper to Rock) to Lose,
(Scissors to Paper) to Lose,
(Rock to Scissors) to Lose,
(Paper to Paper) to Draw,
(Scissors to Scissors) to Draw,
(Rock to Rock) to Draw,
)
fun main() {
// A|X Rock
// B|Y Paper
// C|Z Scissors
fun charToShape(shape: String) = when (shape) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> error("$shape cannot be mapped to a Shape")
}
// X Lose
// Y Draw
// Z Win
fun charToOutcome(outcome: String) = when (outcome) {
"X" -> Lose
"Y" -> Draw
"Z" -> Win
else -> error("$outcome cannot be mapped to a Outcome")
}
fun calculateScore(opShape: Shape, myShape: Shape) = outcomeMap.getValue(opShape to myShape).score
fun part1(input: List<List<String>>): Int = input.sumOf { line ->
val (opShape, myShape) = line.map(::charToShape)
val score = calculateScore(opShape, myShape)
myShape.value + score
}
fun findOutMyShape(opShape: Shape, outcome: Outcome): Shape {
val possibleGames = outcomeMap.filterValues { it == outcome }
return possibleGames.keys.toMap().getValue(opShape)
}
fun part2(input: List<List<String>>): Int = input.sumOf { (shapeChar, outcomeChar) ->
val (opShape, outcome) = charToShape(shapeChar) to charToOutcome(outcomeChar)
val myShape = findOutMyShape(opShape, outcome)
myShape.value + outcome.score
}
val testInput = readInput("Day02_test").map { it.split(" ") }
println("part1(testInput): " + part1(testInput))
println("part2(testInput): " + part2(testInput))
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02").map { it.split(" ") }
println("part1(input): " + part1(input))
println("part2(input): " + part2(input))
}
| 0 | Kotlin | 0 | 0 | bb2b689f48063d7a1b6892fc1807587f7050b9db | 2,167 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | import kotlin.math.min
fun main() {
class Node(
val id: String,
val parent: Node?,
val children: MutableMap<String, Node>,
val isDir: Boolean,
var size: Int? = null
) {
fun getSize(): Int {
return size ?: fetchSize().also { this.size = it }
}
fun fetchSize(): Int =
if (isDir) children.values.sumOf { it.getSize() }
else size ?: throw RuntimeException("Something is wrong!: $this")
fun makeChild(
id: String,
isDir: Boolean,
size: Int? = null
) = Node(id, this, mutableMapOf(), isDir, size)
.also { this.children[it.id] = it }
fun parseLine(line: String): Node {
val tokens = line.split(' ')
return if (tokens[0].isNumeric()) makeChild(tokens[1], false, tokens[0].toInt())
else if (tokens[0] == "dir") makeChild(tokens[1], true)
else throw RuntimeException("Unknown command: $line")
}
fun calcTotalSize(limit: Int): Int {
return if (!this.isDir) 0
else if (this.getSize() < limit) this.getSize() + children.values.sumOf { it.calcTotalSize(limit) }
else children.values.sumOf { it.calcTotalSize(limit) }
}
fun getMin(least: Int): Int {
return if (!this.isDir) 100_000_000
else if (this.getSize() < least) 100_000_000
else min(getSize(), this.children.values.minOf { it.getMin(least) })
}
val isRoot = isDir && parent == null
}
fun parseTree(input: List<String>): Node {
var current = Node("/", null, mutableMapOf(), true)
input.forEach { line ->
// println("current: [${current.hashCode()}], ${current.id}, parent: [${current.parent.hashCode()}] ${current.parent?.id}, line: $line")
if (line.startsWith("$")) {
if (line != "$ ls") {
if (line.endsWith("..")) current = current.parent
?: throw RuntimeException("This is root: $current")
else current = current.children[line.split(' ').last()]
?: throw RuntimeException("No children in ${current.children}, ${line.split(' ').last()}")
}
} else current.parseLine(line)
}
while (!current.isRoot) current = current.parent ?: throw RuntimeException("Already root")
return current
}
fun part1(input: List<String>): Int {
return parseTree(input.drop(2))
.calcTotalSize(100000)
}
fun part2(input: List<String>): Int {
return parseTree(input.drop(2))
.let { it.getMin(it.getSize() - 40_000_000) }
}
val input = readInput("Day07")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 2,851 | advent-of-code-kotlin | Apache License 2.0 |
src/day02/Day02.kt | Ciel-MC | 572,868,010 | false | {"Kotlin": 55885} | package day02
import day02.Move.*
import day02.Result.*
import readInput
enum class Move(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
fun beats(other: Move): Result {
return when (this to other) {
ROCK to SCISSORS, PAPER to ROCK, SCISSORS to PAPER -> WIN
ROCK to PAPER, PAPER to SCISSORS, SCISSORS to ROCK -> LOSE
else -> DRAW
}
}
companion object {
fun from(s: String): Move {
return when (s) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException("Invalid move: $s")
}
}
}
}
enum class Result(val score: Int) {
WIN(6), LOSE(0), DRAW(3);
companion object {
fun from(s: String): Result {
return when (s) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException("Invalid result: $s")
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.map { it.split(" ") }.map { Move.from(it[0]) to Move.from(it[1]) }.sumOf {
val (opponent, me) = it
me.beats(opponent).score + me.score
}
}
fun part2(input: List<String>): Int {
fun moveToMake(opponent: Move, result: Result): Move {
return when (opponent to result) {
ROCK to WIN, PAPER to DRAW, SCISSORS to LOSE -> PAPER
ROCK to DRAW, PAPER to LOSE, SCISSORS to WIN -> ROCK
ROCK to LOSE, PAPER to WIN, SCISSORS to DRAW -> SCISSORS
else -> throw IllegalArgumentException("Invalid move: $opponent $result")
}
}
return input.map {
it.split(" ").let { (opponent, result) -> Move.from(opponent) to Result.from(result) }
}.sumOf {
val (opponent, result) = it
moveToMake(opponent, result).score + result.score
}
}
val testInput = readInput(2, true)
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput(2)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7eb57c9bced945dcad4750a7cc4835e56d20cbc8 | 2,253 | Advent-Of-Code | Apache License 2.0 |
src/commonMain/kotlin/advent2020/day19/Day19Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day19
val inputRegex by lazy { """(\d+):(( "a")|( "b")|(((\s\d+)+)( \|((\s\d+)+))?))""".toRegex() }
sealed class Rule
//data class CharRule(val c: Char) : Rule()
data class StringRule(val s: String) : Rule()
data class ConcatRawRule(val ids: List<Int>) : Rule()
data class ConcatRule(val rules: List<Rule>) : Rule()
data class AlternativeRule(val rules: List<Rule>) : Rule()
fun part1(input: String): String {
val lines = input.trim().lines()
val rules = parseRules(lines.takeWhile { it.isNotBlank() })
tests = 0L
return validate(lines.dropWhile { it.isNotBlank() }.filter { it.isNotBlank() }, rules).toString()
// .also { println("tests: $tests") }
}
fun part2(input: String): String {
val lines = input.trim().lines()
val rules = parseRules(lines.takeWhile { it.isNotBlank() })
.toMutableMap()
.apply {
parseRule("8: 42 | 42 8").let { (id, r) -> this[id] = r }
parseRule("11: 42 31 | 42 11 31").let { (id, r) -> this[id] = r }
}
.toMap()
tests = 0L
return validate(lines.dropWhile { it.isNotBlank() }.filter { it.isNotBlank() }, rules).toString()
// .also { println("tests: $tests") }
}
fun parseRules(lines: List<String>): Map<Int, Rule> {
val map = lines
.map { line ->
parseRule(line)
}.toMap().toMutableMap()
// optimization
var check = true
while (check) {
check = false
map.keys.toSet().filter { it != 0 }.forEach { id ->
val r = map[id]
if (r is ConcatRawRule) {
val newR = optConcatRaw(r, map)
if (r != newR) map[id] = newR.also { check = true }
}
if (r is ConcatRule) {
val newR = optConcat(r, map)
if (r != newR) map[id] = newR.also { check = true }
}
if (r is AlternativeRule) {
val newR = optAlternative(r, map)
if (r != newR) map[id] = newR.also { check = true }
}
}
}
// map.forEach { (id, rule)-> println("$id: $rule") }
return map.toMap()
}
fun optConcatRaw(r: ConcatRawRule, map: Map<Int, Rule>) = ConcatRule(r.ids.map { map[it]!! })
fun optConcat(r: ConcatRule, map: Map<Int, Rule>): Rule = when {
r.rules.all { it is StringRule } -> {
val newRule = StringRule(r.rules.joinToString("") { (it as StringRule).s })
newRule
}
r.rules.all { it is ConcatRule } -> {
val newRule = ConcatRule(r.rules.fold(emptyList()) { acc, i -> acc + (i as ConcatRule).rules })
newRule
}
else -> ConcatRule(r.rules.map {
when (it) {
is ConcatRawRule -> optConcatRaw(it, map)
is ConcatRule -> optConcat(it, map)
is AlternativeRule -> optAlternative(it, map)
else -> it
}
})
}
fun optAlternative(r: AlternativeRule, map: Map<Int, Rule>): Rule = AlternativeRule(r.rules.map {
when (it) {
is ConcatRawRule -> optConcatRaw(it, map)
is ConcatRule -> optConcat(it, map)
is AlternativeRule -> optAlternative(it, map)
else -> it
}
})
fun parseRule(rules: String): Pair<Int, Rule> {
val match = (inputRegex.matchEntire(rules) ?: error("invalid line `$rules`"))
val (v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) = match.destructured
val list1 = v6.split(" ").filter { it.isNotBlank() }.map { it.toInt() }
val list2 = v9.split(" ").filter { it.isNotBlank() }.map { it.toInt() }
return when {
v3 == " \"a\"" -> v1.toInt() to StringRule("a")
v4 == " \"b\"" -> v1.toInt() to StringRule("b")
v9.isNotBlank() -> v1.toInt() to AlternativeRule(listOf(ConcatRawRule(list1), ConcatRawRule(list2)))
v6.isNotBlank() -> v1.toInt() to ConcatRawRule(list1)
else -> error("what to do with `$rules` -> 1:`$v1`, 2:`$v2`, 3:`$v3`, 4:`$v4`, 5:`$v5`, 6:`$v6`, 7:`$v7`, 8:`$v8`, 9:`$v9` , 10:`$v10` ")
}
}
fun validate(
messages: List<String>,
rules: Map<Int, Rule>
) = messages.count { message ->
check(message.isNotEmpty())
check(message.all { it == 'a' || it == 'b' })
matches(rules[0]!!, rules, message, 0).any { it == message.length }
}
var tests = 0L
fun matches(rule: Rule, rules: Map<Int, Rule>, message: String, start: Int): Sequence<Int> {
tests++
return when (rule) {
is StringRule -> if (message.startsWith(rule.s, start)) sequenceOf(start + rule.s.length) else emptySequence()
is AlternativeRule -> {
rule.rules.asSequence()
.flatMap { matches(it, rules, message, start) }
.filter { it >= 0 }
}
is ConcatRule -> {
// if (rule.rules.any { it is StringRule && !message.substring(start).contains(it.s) }) emptySequence() else
rule.rules.asSequence().drop(1).fold(matches(rule.rules[0], rules, message, start)) { acc, i ->
acc.filter { it < message.length }.flatMap { matches(i, rules, message, it) }
}
}
is ConcatRawRule -> {
rule.ids.asSequence().drop(1).fold(matches(rules[rule.ids[0]]!!, rules, message, start)) { acc, i ->
acc.filter { it < message.length }.flatMap { matches(rules[i]!!, rules, message, it) }
}
}
}
}
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 5,340 | advent-of-code-2020 | MIT License |
src/main/kotlin/aoc2023/Day02.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
class Day02 {
fun part1(input: List<String>, redCap: Int, greenCap: Int, blueCap: Int): Int = input
.map { line -> CubeGame.fromString(line) }
.filter { game -> game.red.all { it <= redCap } && game.green.all { it <= greenCap } && game.blue.all { it <= blueCap } }
.sumOf { game -> game.id }
fun part2(input: List<String>): Int = input
.map { line -> CubeGame.fromString(line) }.sumOf { game -> game.red.max() * game.green.max() * game.blue.max() }
class CubeGame(val id: Int, val red: IntArray, val green: IntArray, val blue: IntArray) {
companion object {
fun fromString(game: String): CubeGame {
val gameRegex = "^Game (\\d+): (.*)$".toRegex()
val redRegex = "(\\d+) red".toRegex()
val greenRegex = "(\\d+) green".toRegex()
val blueRegex = "(\\d+) blue".toRegex()
val (gameId, gameResultString) = gameRegex.find(game)!!.destructured
val gameResults = gameResultString.split(';')
val red = IntArray(gameResults.size)
val green = IntArray(gameResults.size)
val blue = IntArray(gameResults.size)
for ((i, result) in gameResults.withIndex()) {
red[i] = redRegex.find(result)?.groupValues?.get(1)?.toInt() ?: 0
green[i] = greenRegex.find(result)?.groupValues?.get(1)?.toInt() ?: 0
blue[i] = blueRegex.find(result)?.groupValues?.get(1)?.toInt() ?: 0
}
return CubeGame(gameId.toInt(), red = red, green = green, blue = blue)
}
}
}
}
fun main() {
val day02 = Day02()
val input = readInputAsStringList("day02.txt")
println("02, part 1: ${day02.part1(input, redCap = 12, greenCap = 13, blueCap = 14)}")
println("02, part 2: ${day02.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 1,922 | advent-of-code-2023 | MIT License |
src/main/kotlin/ru/timakden/aoc/year2023/Day12.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2023
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 12: Hot Springs](https://adventofcode.com/2023/day/12).
*/
object Day12 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2023/Day12")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>) =
input.map { parseRow(it) }.sumOf { (springs, damagedSprings) ->
countArrangements(springs, damagedSprings)
}
fun part2(input: List<String>) =
input.map { parseRow(it) }.map { unfold(it) }.sumOf { (springs, damagedSprings) ->
countArrangements(springs, damagedSprings)
}
private fun countArrangements(
springs: String,
damagedSprings: List<Int>,
cache: MutableMap<Pair<String, List<Int>>, Long> = mutableMapOf()
): Long {
val key = springs to damagedSprings
cache[key]?.let { return it }
if (springs.isEmpty()) return if (damagedSprings.isEmpty()) 1 else 0
return when (springs.first()) {
'.' -> countArrangements(springs.dropWhile { it == '.' }, damagedSprings, cache)
'?' -> countArrangements(springs.substring(1), damagedSprings, cache) +
countArrangements("#${springs.substring(1)}", damagedSprings, cache)
'#' -> when {
damagedSprings.isEmpty() -> 0
else -> {
val thisDamage = damagedSprings.first()
val remainingDamage = damagedSprings.drop(1)
if (thisDamage <= springs.length && springs.take(thisDamage).none { it == '.' }) {
when {
thisDamage == springs.length -> if (remainingDamage.isEmpty()) 1 else 0
springs[thisDamage] == '#' -> 0
else -> countArrangements(springs.drop(thisDamage + 1), remainingDamage, cache)
}
} else 0
}
}
else -> error("Invalid springs: $springs")
}.apply {
cache[key] = this
}
}
private fun unfold(input: Pair<String, List<Int>>): Pair<String, List<Int>> =
(0..4).joinToString("?") { input.first } to (0..4).flatMap { input.second }
private fun parseRow(input: String): Pair<String, List<Int>> {
val (springs, damagedSprings) = input.split(" ")
return springs to damagedSprings.split(",").map { it.toInt() }
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 2,657 | advent-of-code | MIT License |
src/main/kotlin/aoc2021/Day08.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
private fun part1(input: List<String>) =
input.map { it.split("|").last().trim().split(" ") }.flatten().map { it.length }.filter {
when (it) {
2, 4, 3, 7 -> true
else -> false
}
}.size
private enum class Digit(vararg chars: Char) {
ZERO('a', 'b', 'c', 'e', 'f', 'g'),
ONE('c', 'f'),
TWO('a', 'c', 'd', 'e', 'g'),
THREE('a', 'c', 'd', 'f', 'g'),
FOUR('b', 'c', 'd', 'f'),
FIVE('a', 'b', 'd', 'f', 'g'),
SIX('a', 'b', 'd', 'e', 'f', 'g'),
SEVEN('a', 'c', 'f'),
EIGHT('a', 'b', 'c', 'd', 'e', 'f', 'g'),
NINE('a', 'b', 'c', 'd', 'f', 'g');
private val charArray = chars
override fun toString() = this.ordinal.toString()
/**
* @param input the input signal
* @param mapping a signal mapping
* @return true, if this [Digit] is a valid solution for the given input signal and signal mapping
*/
fun isPossible(input: String, mapping: Map<Char, Char>) =
charArray.size == input.length && input.chars().mapToObj { it.toChar() }.map { mapping[it] }
.allMatch { char -> char == null || charArray.contains(char) }
companion object {
/**
* @param input the input signal
* @param mapping a signal mapping
* @return true, if the input can be mapped to at least one valid [Digit]
*/
fun isValidMapping(input: String, mapping: Map<Char, Char>) = getDigit(input, mapping) != null
/**
* @param input the input signal
* @param mapping a signal mapping
* @return a [Digit] object which can be constructed with the given input. Might be null if the input can not be
* mapped to a valid [Digit] (e.g. the mapping is invalid)
*/
fun getDigit(input: String, mapping: Map<Char, Char>) = values().firstOrNull { it.isPossible(input, mapping) }
}
}
/**
* @param possibleValues all allowed [Char]s which shall be permutated
* @return a sequence of permutations of the given input array
*/
private fun getPermutations(possibleValues: CharArray) = getPermutationsRec(possibleValues.size, possibleValues)
private fun getPermutationsRec(length: Int, possibleValues: CharArray): Sequence<CharArray> {
return sequence {
if (length == 1) {
for (value in possibleValues) {
yield(charArrayOf(value))
}
} else {
for (value in possibleValues) {
getPermutationsRec(length - 1, possibleValues).filter { !it.contains(value) }
.forEach { yield(charArrayOf(value, *it)) }
}
}
}
}
/**
* @param original the original characters
* @param permutation the permutated characters
* @return a mapping of the original characters to their counterpart in the permutation
*/
private fun getMappingFromPermutation(original: CharArray, permutation: CharArray) = original.zip(permutation).toMap()
private fun part2(input: List<String>): Int {
val charArray = ('a'..'g').toList().toCharArray()
val permutations = getPermutations(charArray)
return input.sumOf { line ->
val signals = line.split("|").first().trim().split(" ")
val test = line.split("|").last().trim().split(" ")
permutations.map { getMappingFromPermutation(charArray, it) }.firstOrNull { mapping ->
signals.all { Digit.isValidMapping(it, mapping) } && test.all { Digit.isValidMapping(it, mapping) }
}?.let { mapping -> test.joinToString("") { Digit.getDigit(it, mapping).toString() }.toInt() }
?: throw IllegalArgumentException("No valid signal mapping found")
}
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 26)
check(part2(testInput) == 61229)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,985 | adventOfCode | Apache License 2.0 |
y2018/src/main/kotlin/adventofcode/y2018/Day06.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2018
import adventofcode.io.AdventSolution
import kotlin.math.abs
object Day06 : AdventSolution(2018, 6, "Chronal Coordinates") {
override fun solvePartOne(input: String): Int? {
val points = parse(input)
val counts = mutableMapOf<Point, Int>()
val disqualified = mutableSetOf<Point>()
val width = points.width()
val height = points.height()
width.forEach { x ->
height.forEach { y ->
//add the point to the region whose origin is strictly closest
val closest = findUniqueClosest(points, x, y)
closest?.let {
counts[it] = (counts[it] ?: 0) + 1
//any region that touches an edge stretches out to infinity and is disqualified
if (x == width.first || x == width.last || y == height.first || y == height.last)
disqualified += it
}
}
}
return counts.filterKeys { it !in disqualified }.values.maxOrNull()
}
private fun findUniqueClosest(points: List<Point>, x: Int, y: Int): Point? {
var closestPoint: Point? = null
var dist = Int.MAX_VALUE
for (p in points) {
val d = p.distanceTo(x, y)
if (d == dist) closestPoint = null
if (d < dist) {
closestPoint = p
dist = d
}
}
return closestPoint
}
override fun solvePartTwo(input: String): Int {
val points = parse(input)
val height = points.height()
return points.width().sumOf { x ->
height.asSequence()
.map { y ->
points.sumOf { it.distanceTo(x, y) }
}
.count { it < 10000 }
}
}
private fun parse(input: String) = input.lineSequence()
.map { it.split(", ") }
.map { (x, y) -> Point(x.toInt(), y.toInt()) }
.toList()
private data class Point(val x: Int, val y: Int) {
fun distanceTo(x: Int, y: Int) = abs(this.x - x) + abs(this.y - y)
}
private fun List<Point>.width() = minOf { it.x }..maxOf { it.x }
private fun List<Point>.height() = minOf { it.y }..maxOf { it.y }
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,321 | advent-of-code | MIT License |
day-20/src/main/kotlin/TrenchMap.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | import kotlin.system.measureTimeMillis
fun main() {
val partOneMillis = measureTimeMillis {
println("Part One Solution: ${partOne()}")
}
println("Part One Solved in: $partOneMillis ms")
val partTwoMillis = measureTimeMillis {
println("Part Two Solution: ${partTwo()}")
}
println("Part Two Solved in: $partTwoMillis ms")
}
private fun partOne(): Int {
val lines = readInputLines()
val algorithm = lines[0]
var map = readMap(lines)
for (i in 1..2) {
map = applyAlgorithm(map, algorithm, i)
}
map.forEach { println(it.joinToString("")) }
return map.sumOf { line ->
line.count { it == '#' }
}
}
private fun partTwo(): Int {
val lines = readInputLines()
val algorithm = lines[0]
var map = readMap(lines)
for (i in 1..50) {
map = applyAlgorithm(map, algorithm, i)
}
map.forEach { println(it.joinToString("")) }
return map.sumOf { line ->
line.count { it == '#' }
}
}
/**
* Since our algorithm's 0 index is #, outer layer will change between # and . on every iteration
*/
private fun applyAlgorithm(map: List<List<Char>>, algorithm: String, iteration: Int): List<List<Char>> {
val char = if (algorithm[0] == '.') '.' else if (iteration % 2 == 0) '#' else '.'
val mapCopy = copyWithOuterLayer(map, char)
val result = getNewEmptyMap(mapCopy.size)
val range = mapCopy.indices
for (x in range) {
for (y in range) {
val decimal = getDecimal(mapCopy, x, y, char)
result[x][y] = algorithm[decimal]
}
}
return result
}
private fun getNewEmptyMap(size: Int, init: Char = '.'): List<MutableList<Char>> {
return List(size) { MutableList(size) { init } }
}
private fun readMap(lines: List<String>): List<List<Char>> {
val map = getNewEmptyMap(lines[1].length)
lines.drop(1)
.forEachIndexed { lineIdx, line ->
line.forEachIndexed { charIdx, char ->
if (char == '#') {
map[lineIdx][charIdx] = '#'
}
}
}
return map
}
fun copyWithOuterLayer(map: List<List<Char>>, init: Char): List<MutableList<Char>> {
val empty = getNewEmptyMap(map.size + 2, init)
for (x in map.indices) {
for (y in map.indices) {
empty[x + 1][y + 1] = map[x][y]
}
}
return empty
}
fun getDecimal(map: List<List<Char>>, x: Int, y: Int, nonExistingChar: Char): Int {
var binary = ""
for (xv in -1..1) {
for (yv in -1..1) {
if (x + xv !in map.indices || y + yv !in map.indices) {
binary += if (nonExistingChar == '.') 0 else 1
} else {
binary += if (map[x + xv][y + yv] == '.') 0 else 1
}
}
}
return binary.toInt(2)
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 3,026 | aoc-2021 | MIT License |
09/part_two.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
fun readInput() : HeightMap {
val inputLines = File("input.txt")
.readLines()
.map { line -> line.split("")
.filter { it.isNotEmpty() }
.map{ it.toInt() }}
return HeightMap(inputLines)
}
class HeightMap(inputLines : List<List<Int>>) {
companion object {
const val INVALID_HEIGHT_FOR_BASIN = 9
val NEIGHBORS_DELTA = listOf(Pair(0, 1),
Pair(1, 0),
Pair(0, -1),
Pair(-1, 0))
}
val rows = inputLines.size
val cols = inputLines[0].size
val heights = inputLines
fun getNeighbors(x : Int, y : Int) : List<Pair<Int, Int>> {
val result = mutableListOf<Pair<Int, Int>>()
for (delta in NEIGHBORS_DELTA) {
val neighborX = x + delta.first
val neighborY = y + delta.second
if (isIn(neighborX, neighborY)) {
result.add(Pair(neighborX, neighborY))
}
}
return result.toList()
}
fun isIn(x : Int, y : Int) : Boolean {
return x in 0 until rows && y in 0 until cols
}
fun isLowPoint(x : Int, y : Int) : Boolean {
val height = heights[x][y]
val neighborsHeights = getNeighbors(x, y)
return neighborsHeights.none { heights[it.first][it.second] <= height }
}
fun getBasins() : MutableList<List<Pair<Int, Int>>> {
val result = mutableListOf<List<Pair<Int, Int>>>()
val processed = mutableSetOf<Pair<Int, Int>>()
for (i in 0 until rows) {
for (j in 0 until cols) {
if (isLowPoint(i, j)) {
val basinPoints = mutableListOf<Pair<Int, Int>>()
DFS(i, j, processed, basinPoints)
result.add(basinPoints)
}
}
}
return result
}
fun DFS(x : Int, y : Int, processed : MutableSet<Pair<Int, Int>>, basinPoints : MutableList<Pair<Int, Int>>) {
processed.add(Pair(x, y))
basinPoints.add(Pair(x, y))
val sameBasinNeighbors = getNeighbors(x, y)
.filter { heights[it.first][it.second] != INVALID_HEIGHT_FOR_BASIN }
for (sameBasinNeighbor in sameBasinNeighbors) {
if (sameBasinNeighbor !in processed) {
DFS(sameBasinNeighbor.first, sameBasinNeighbor.second, processed, basinPoints)
}
}
}
}
fun solve(heightMap : HeightMap) : Int {
val basins = heightMap.getBasins()
basins.sortBy { -it.size }
return basins.take(3).map { it.size }.reduce { a, b -> a * b }
}
fun main() {
val heightMap = readInput()
val ans = solve(heightMap)
println(ans)
}
| 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 2,702 | advent-of-code-2021 | MIT License |
src/day15.kts | miedzinski | 434,902,353 | false | {"Kotlin": 22560, "Shell": 113} | import java.util.PriorityQueue
import kotlin.math.max
import kotlin.math.min
data class Point(val x: Int, val y: Int)
fun Point.neighboursIn(cave: List<List<Int>>): Sequence<Point> = sequenceOf(
copy(x - 1, y),
copy(x + 1, y),
copy(x, y - 1),
copy(x, y + 1),
).filter {
with(it) {
y in 0 until cave.size && x in 0 until cave[y].size
}
}
operator fun List<List<Int>>.get(point: Point): Int = this[point.y][point.x]
operator fun List<MutableList<Int>>.set(point: Point, value: Int): Int =
get(point.y).set(point.x, value)
fun List<List<Int>>.lowestTotalRisk(): Int {
val start = Point(0, 0)
val end = size.minus(1).let { Point(it, get(it).size - 1) }
val visited = mutableSetOf<Point>()
val totalCosts = map {
it.asSequence().map { Int.MAX_VALUE }.toMutableList()
}.also { it[start] = 0 }
val queue = PriorityQueue(size, object : Comparator<Point> {
override fun compare(o1: Point, o2: Point): Int =
totalCosts[o1].compareTo(totalCosts[o2])
}).also { it.add(start) }
generateSequence(queue::poll)
.takeWhile { it != end }
.filterNot(visited::contains)
.onEach { point ->
val currentCost = totalCosts[point]
point.neighboursIn(this).onEach {
totalCosts[it] = min(totalCosts[it], currentCost + get(it))
}.toCollection(queue)
}.toCollection(visited)
return totalCosts[end]
}
val cave = generateSequence(::readLine)
.map { it.map(Char::digitToInt) }
.toList()
println("part1: ${cave.lowestTotalRisk()}")
val expansion = 5
val entireCave = List(expansion * cave.size) { y ->
List(expansion * cave[0].size) { x ->
val original = cave[Point(x % cave[0].size, y % cave.size)]
val increase = y / cave.size + x / cave[0].size
generateSequence(original) { max((it + 1) % 10, 1) }
.elementAt(increase)
}
}
println("part2: ${entireCave.lowestTotalRisk()}")
| 0 | Kotlin | 0 | 0 | 6f32adaba058460f1a9bb6a866ff424912aece2e | 1,989 | aoc2021 | The Unlicense |
src/Day03.kt | zoidfirz | 572,839,149 | false | {"Kotlin": 15878} | fun main() {
firstHalfSolution()
secondHalfSolution()
}
private fun secondHalfSolution() {
val data = readInput("main/resources/Day03_Input")
val groupedData = data.chunked(3)
var sum = 0
groupedData.forEach { chunk ->
var badge: Char = ' '
chunk[0].forEach { charChunk ->
if (chunk[1].contains(charChunk)) {
if (chunk[2].contains(charChunk)) {
badge = charChunk
}
}
}
if (badge.isLowerCase()) {
sum += getLowerCasePointValue(badge.toString())
} else {
sum += getUpperCasePointValue(badge.toString())
}
}
println(sum)
}
private fun firstHalfSolution() {
// Parse examples into variable
val data = readInput("main/resources/Day03_Input")
var duplicate: MutableList<Char> = arrayListOf()
data.forEach { it ->
// split string evenly in two parts
val mid = it.length / 2
val a = it.substring(0, mid).toSet()
val b = it.substring(mid, it.length).toSet()
// find duplicates in the arrays and assign them to a new array
a.forEach { obj ->
if (b.contains(obj)) {
duplicate.add(obj)
}
}
}
println(duplicate)
//separate the newly formed duplicate array into lower and upper case letter arrays
var (lowerCaseArr, upperCaseArr) = duplicate.partition { it.isLowerCase() }
var sum = 0
// getPointValue of lower case letters
var lowerCaseArrPoints = lowerCaseArr.map { getLowerCasePointValue(it.toString()) }
// getPointValue of upper case letters
var upperCaseArrPoints = upperCaseArr.map { getUpperCasePointValue(it.toString()) }
//add values of lower case letters and upper case letters
sum = lowerCaseArrPoints.sum() + upperCaseArrPoints.sum()
println(sum)
}
fun getLowerCasePointValue(value: String): Int {
return when (value) {
"a" -> 1
"b" -> 2
"c" -> 3
"d" -> 4
"e" -> 5
"f" -> 6
"g" -> 7
"h" -> 8
"i" -> 9
"j" -> 10
"k" -> 11
"l" -> 12
"m" -> 13
"n" -> 14
"o" -> 15
"p" -> 16
"q" -> 17
"r" -> 18
"s" -> 19
"t" -> 20
"u" -> 21
"v" -> 22
"w" -> 23
"x" -> 24
"y" -> 25
"z" -> 26
else -> 0
}
}
fun getUpperCasePointValue(value: String): Int {
val lower = value.lowercase()
val lowercasePoints = getLowerCasePointValue(lower)
return lowercasePoints + 26
}
| 0 | Kotlin | 0 | 0 | e955c1c08696f15929aaf53731f2ae926c585ff3 | 2,648 | kotlin-advent-2022 | Apache License 2.0 |
src/Day15.kt | jwklomp | 572,195,432 | false | {"Kotlin": 65103} | import kotlin.math.abs
data class Reading(val sensor: Point, val beacon: Point)
fun makeReadings(input: List<String>): List<Reading> {
val pointList = input.map {
it.replace("Sensor at ", "").replace(" closest beacon is at ", "").replace(":", ", ").split(", ")
}
return pointList.map {
Reading(
sensor = Point(it[0].split("=")[1].toInt(), it[1].split("=")[1].toInt()),
beacon = Point(it[2].split("=")[1].toInt(), it[3].split("=")[1].toInt())
)
}
}
fun main() {
fun part1(input: List<String>): Int {
//val targetY = 10
val targetY = 2000000
val readings = makeReadings(input)
println(readings)
// get min and max X and Y
val allX = readings.flatMap { listOf(it.sensor.x, it.beacon.x) }
val minX = allX.min()
val maxX = allX.max()
val allSensorsXOnTargetY = readings.filter { it.sensor.y == targetY }.map { it.sensor.x }
val allBeaconXOnTargetY = readings.filter { it.beacon.y == targetY }.map { it.beacon.x }
val allXOnTargetY = allBeaconXOnTargetY.union(allSensorsXOnTargetY)
println("allXOnTargetY")
println(allXOnTargetY)
// map over calculate the spots taken for y = ...
val ranges = readings.mapNotNull {
val mdBeaconSensor = manhattanDistance(it.sensor, it.beacon)
val distance = abs(targetY - it.sensor.y) - mdBeaconSensor // negative when useful
if (distance <= 0) {
val min = it.sensor.x + distance
val max = it.sensor.x - distance
return@mapNotNull IntRange(min, max)
} else {
return@mapNotNull null
}
}
println("ranges")
println(ranges)
val blockedRange = ranges.fold(emptySet<Int>()){ sum, element -> sum.union(element)}.minus(allXOnTargetY)
val noBeaconRange = IntRange(minX, maxX).intersect(blockedRange)
return noBeaconRange.size
}
val testInput = readInput("Day15_test")
println(part1(testInput))
val input = readInput("Day15")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | 1b1121cfc57bbb73ac84a2f58927ab59bf158888 | 2,158 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day08.kt | sungi55 | 574,867,031 | false | {"Kotlin": 23985} | fun main() {
val day = "Day08"
fun getTreeGrid(input: List<String>): Grid =
Grid().apply {
input.forEachIndexed { rowIndex, row ->
val treesInRow = row.map { it.digitToInt() }
rows[rowIndex] = treesInRow
treesInRow.forEachIndexed { columnIndex, treeHeight ->
val column = columns[columnIndex] ?: mutableListOf()
columns[columnIndex] = column.apply { add(treeHeight) }
}
}
}
fun onEachTree(grid: Grid, action: (TreeView) -> Unit) {
grid.rows.forEach { (rowIndex, row) ->
grid.columns.forEach { (columnIndex, column) ->
action(
TreeView(
currentTree = row[columnIndex],
up = column.take(rowIndex).reversed(),
down = column.takeLast(column.lastIndex - rowIndex),
left = row.take(columnIndex).reversed(),
fight = row.takeLast(row.lastIndex - columnIndex)
)
)
}
}
}
fun part1(lines: List<String>): Int =
getTreeGrid(lines).let { grid ->
mutableListOf<Int>().apply {
onEachTree(grid) { (current, up, down, left, right) ->
if (left.firstOrNull { it >= current } == null
|| right.firstOrNull { it >= current } == null
|| up.firstOrNull { it >= current } == null
|| down.firstOrNull { it >= current } == null) add(1)
}
}.sum()
}
fun List<Int>.takeUntil(predicate: (Int) -> Boolean): List<Int> {
val list = ArrayList<Int>()
for (item in this) {
list.add(item)
if (predicate(item))
break
}
return list
}
fun part2(lines: List<String>): Int = getTreeGrid(lines).let { grid ->
mutableListOf<Int>().apply {
onEachTree(grid) { (current, up, down, left, right) ->
val l = left.takeUntil { it >= current }.count()
val r = right.takeUntil { it >= current }.count()
val u = up.takeUntil { it >= current }.count()
val d = down.takeUntil { it >= current }.count()
add(l * r * u * d)
}
}.max()
}
val testInput = readInput(name = "${day}_test")
val input = readInput(name = day)
check(part1(testInput) == 21)
check(part2(testInput) == 8)
println(part1(input))
println(part2(input))
}
data class Grid(
val rows: HashMap<Int, List<Int>> = hashMapOf(),
val columns: HashMap<Int, MutableList<Int>> = hashMapOf()
)
data class TreeView(
val currentTree: Int,
val up: List<Int>,
val down: List<Int>,
val left: List<Int>,
val fight: List<Int>,
) | 0 | Kotlin | 0 | 0 | 2a9276b52ed42e0c80e85844c75c1e5e70b383ee | 2,945 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | proggler23 | 573,129,757 | false | {"Kotlin": 27990} | import java.util.*
fun main() {
fun part1(input: List<String>): Long {
val dir = input.parse7()
return dir.getAllDirs { it.size < 100000 }.sumOf { it.size }
}
fun part2(input: List<String>): Long {
val dir = input.parse7()
val freeSpace = 70000000L - dir.size
val sizeToFree = 30000000L - freeSpace
return dir.getAllDirs { it.size > sizeToFree }.minOf { it.size }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
fun List<String>.parse7(): Dir {
val dir = Dir("/")
val stack = Stack<String>()
reversed().forEach { stack.push(it) }
dir.parseCommands(stack, dir)
return dir
}
data class Dir(val name: String, val parent: Dir? = null) {
var dirs = mutableMapOf<String, Dir>()
var files = mutableMapOf<String, File>()
val size: Long get() = dirs.values.sumOf { it.size } + files.values.sumOf { it.size }
fun getAllDirs(predicate: (Dir) -> Boolean): List<Dir> {
val subDirs = dirs.values.flatMap { it.getAllDirs(predicate) }
return dirs.values.filter(predicate) + subDirs
}
fun parseCommands(stack: Stack<String>, rootDir: Dir) {
if (stack.isEmpty()) return
val command = stack.pop()
val cd = if (command.startsWith("$ cd ")) {
when (val newDir = command.drop("$ cd ".length)) {
"/" -> rootDir
".." -> parent!!
else -> dirs.computeIfAbsent(newDir) { Dir(newDir, this) }
}
} else if (command.startsWith("$ ls")) {
while (stack.isNotEmpty()) {
val top = stack.pop()
if (top.startsWith("$")) {
stack.push(top)
break
} else if (top.startsWith("dir")) {
val newDir = top.substringAfter(" ")
dirs.putIfAbsent(newDir, Dir(newDir, this))
} else {
val (size, file) = top.split(" ")
files.putIfAbsent(file, File(file, size.toLong()))
}
}
this
} else this
cd.parseCommands(stack, rootDir)
}
}
data class File(val name: String, val size: Long)
| 0 | Kotlin | 0 | 0 | 584fa4d73f8589bc17ef56c8e1864d64a23483c8 | 2,462 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | ostersc | 572,991,552 | false | {"Kotlin": 46059} | const val MAX_SIZE = 70_000_000
const val FREE_SIZE = 30_000_000
data class File(val dir:Dir, val name:String, val size:Int)
class Dir(var name: String, var parent: Dir?) {
//name->size
var files = mutableMapOf<String, File>()
//name->Dir
var dirs = mutableMapOf<String, Dir>()
fun calcTotals(sizePredicate: (Int) -> Boolean, matchingDirs: MutableList<Pair<Int, Dir>>): Int {
var total = files.values.sumOf(File::size)
if (dirs.isEmpty()) {
if (sizePredicate(total)) matchingDirs.add(Pair(total, this))
return total
}
for ((_, d) in dirs) {
total += d.calcTotals(sizePredicate, matchingDirs)
}
if (sizePredicate(total)) {
matchingDirs.add((Pair(total, this)))
}
return total
}
}
fun main() {
fun parseInput(input: List<String>): Dir {
val root = Dir("/", null)
var currDir = root
//read in files
input.forEach { line ->
//$ command run command
val split = line.split(" ")
if (split.first() == "$") {
// we don't care about "ls" and are just assuming if we cant find the dir, then its /
if (split[1] == "cd") {
currDir = if (split.last() == "..") {
currDir.parent!!
} else {
currDir.dirs.getOrDefault(split.last(), root)
}
}
} else if (split.first() == "dir") {
//dir <name> create new dir
currDir.dirs.putIfAbsent(split.last(), Dir(split.last(), currDir))
} else {
//\d <name> create new file of size \d
currDir.files.putIfAbsent(split.last(), File(currDir, split.last(), split.first().toInt()))
}
}
return root
}
fun part1(input: List<String>): Int {
val root = parseInput(input)
val matches = mutableListOf<Pair<Int, Dir>>()
root.calcTotals({ size -> size <= 100000 }, matches)
return matches.sumOf { it.first }
}
fun part2(input: List<String>): Int {
val root = parseInput(input)
val freeSpace = MAX_SIZE - root.calcTotals({ true }, mutableListOf<Pair<Int, Dir>>())
val toDelete=FREE_SIZE-freeSpace
val candidates = mutableListOf<Pair<Int, Dir>>()
root.calcTotals({ size -> size >= toDelete }, candidates)
return candidates.minOf{ it.first }
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
val part1 = part1(input)
println(part1)
check(part1 == 1454188)
val part2 = part2(input)
println(part2)
check(part2==4183246)
} | 0 | Kotlin | 0 | 1 | 3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9 | 2,862 | advent-of-code-2022 | Apache License 2.0 |
src/Day24.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | fun main() {
val day = 24
fun Char.toDirection() = when (this) {
'>' -> 0
'v' -> 1
'<' -> 2
else -> 3
}
data class Position(val x: Int, val y: Int) {
fun move(steps: Int, direction: Int) = when (direction) {
0 -> copy(y = y + steps)
1 -> copy(x = x + steps)
2 -> copy(y = y - steps)
3 -> copy(x = x - steps)
else -> this
}
}
data class WindPiece(val position: Position, val direction: Int) {
fun move(steps: Int) = copy(position = position.move(steps, direction))
fun putInside(n: Int, m: Int) = this.copy(position = Position(position.x.mod(n), position.y.mod(m)))
constructor(x: Int, y: Int, charDirection: Char) : this(Position(x, y), charDirection.toDirection())
}
data class WindGame(val n: Int, val m: Int, val pieces: List<WindPiece>)
fun List<String>.removeWrapper() = this.drop(1).dropLast(1).map { it.drop(1).dropLast(1) }
fun windPiecesFromLines(lines: List<String>) = lines.flatMapIndexed { x, line ->
line.mapIndexed { y, c ->
if (c == '.') null
else WindPiece(x, y, c)
}.filterNotNull()
}
fun List<String>.toWindGame() = removeWrapper().let { lines ->
WindGame(lines.size, lines.first().length, windPiecesFromLines(lines))
}
fun isInside(n: Int, m: Int, position: Position) =
(position.x in 0 until n && position.y in 0 until m)
fun stepsToMove(game: WindGame, startPosition: Position, finishPosition: Position, initialSteps: Int = 0): Int {
var possiblePositions = listOf(startPosition)
var steps = initialSteps
while (finishPosition !in possiblePositions) {
steps++
val possibleMoves =
(-1..3).flatMap { direction ->
possiblePositions.map { it.move(1, direction) }
}.toSet()
val windPositions =
game.pieces.map {
it.move(steps).putInside(game.n, game.m).position
}.toSet()
possiblePositions = possibleMoves.subtract(windPositions)
.filter { isInside(game.n, game.m, it) || it in listOf(startPosition, finishPosition) }
}
return steps
}
fun part1(input: List<String>): Int {
val game = input.toWindGame()
return stepsToMove(game, Position(-1, 0), Position(game.n, game.m - 1))
}
fun part2(input: List<String>): Int {
val game = input.toWindGame()
val startPosition = Position(-1, 0)
val finishPosition = Position(game.n, game.m - 1)
var steps = stepsToMove(game, startPosition, finishPosition)
steps = stepsToMove(game, finishPosition, startPosition, steps)
steps = stepsToMove(game, startPosition, finishPosition, steps)
return steps
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 3,196 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2020/d21/Day21.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2020.d21
import com.groundsfam.advent.DATAPATH
import kotlin.io.path.div
import kotlin.io.path.useLines
data class Ingredients(val ingredients: List<String>, val allergens: List<String>)
fun parseLine(line: String): Ingredients =
line.split(" (contains ").let { (a, b) ->
Ingredients(
a.split(" "),
b.split(" ").map { it.substring(0, it.length - 1) }
)
}
// map from allergen to ingredients possibly containing that allergen
fun findAllergyCandidates(foods: List<Ingredients>): Map<String, Set<String>> {
val maybeHasAllergy = mutableMapOf<String, Set<String>>()
foods.forEach { (ingredients, allergens) ->
val ingrSet = ingredients.toSet()
allergens.forEach { allergen ->
if (allergen !in maybeHasAllergy) {
maybeHasAllergy[allergen] = ingrSet
} else {
maybeHasAllergy[allergen] = maybeHasAllergy[allergen]!! intersect ingrSet
}
}
}
return maybeHasAllergy
}
fun allergenFreeIngredients(foods: List<Ingredients>): Int {
val allergyCandidates = findAllergyCandidates(foods).values.reduce { a, b -> a union b }
return (foods.flatMap { it.ingredients } - allergyCandidates).size
}
fun associateAllergens(foods: List<Ingredients>): Map<String, String> {
val maybeHasAllergy = findAllergyCandidates(foods).mapValues { (_, v) -> v.toMutableSet() }
val ret = mutableMapOf<String, String>().apply {
maybeHasAllergy.entries.forEach { (allergen, possibleIngredients) ->
if (possibleIngredients.size == 1) {
this[allergen] = possibleIngredients.first()
}
}
}
while (ret.size != maybeHasAllergy.size) {
ret.forEach { (allergen, ingredient) ->
maybeHasAllergy.keys.forEach { otherAllergen ->
if (allergen != otherAllergen) {
maybeHasAllergy[otherAllergen]!!.remove(ingredient)
}
}
}
maybeHasAllergy.entries.forEach { (allergen, possibleIngredients) ->
if (allergen !in ret && possibleIngredients.size == 1) {
ret[allergen] = possibleIngredients.first()
}
}
}
return ret
}
fun main() {
val foods = (DATAPATH / "2020/day21.txt").useLines { lines ->
lines.map(::parseLine).toList()
}
allergenFreeIngredients(foods)
.also { println("Part one: $it") }
associateAllergens(foods)
.entries
.sortedBy { (allergen, _) -> allergen }
.joinToString(",") { it.value }
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,673 | advent-of-code | MIT License |
2021/src/main/kotlin/Day04.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | class Day04(private val input: List<String>) {
private fun parseInput(input: List<String>): Set<Grid> =
input.asSequence().drop(1).filter { it.isNotEmpty() }.chunked(5).map { parseSingleBoard(it) }.toSet()
private fun parseSingleBoard(input: List<String>): Grid = input.map { row ->
row.split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
}
private fun Grid.isWinner(draws: Set<Int>) =
this.any { row -> row.all { it in draws } } || (0..4).any { col -> this.all { row -> row[col] in draws } }
private fun Grid.sumUnmarked(draws: Set<Int>): Int = this.sumOf { row ->
row.filterNot { it in draws }.sum()
}
private fun getFirstWinner(draws: List<Int>, boards: Set<Grid>): Int {
val drawn = draws.take(4).toMutableSet()
return draws.drop(4).firstNotNullOf { draw ->
drawn += draw
boards.firstOrNull { it.isWinner(drawn) }?.let { winner ->
draw * winner.sumUnmarked(drawn)
}
}
}
private fun getLastWinner(draws: List<Int>, boards: Set<Grid>): Int {
val all = draws.toMutableSet()
return draws.reversed().firstNotNullOf { draw ->
all -= draw
boards.firstOrNull { !it.isWinner(all) }?.let { winner ->
draw * (winner.sumUnmarked(all) - draw)
}
}
}
fun solve1(): Int {
val draws: List<Int> = input.first().split(",").map { it.toInt() }
val boards: Set<Grid> = parseInput(input)
return getFirstWinner(draws, boards)
}
fun solve2(): Int {
val draws: List<Int> = input.first().split(",").map { it.toInt() }
val boards: Set<Grid> = parseInput(input)
return getLastWinner(draws, boards)
}
}
| 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 1,778 | adventofcode-2021-2025 | MIT License |
src/Day04.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | private fun part1(input: List<String>): Int {
return input.count { line ->
val assignment = line.split(",").map { it.split("-").map { section -> section.toInt() } }
(assignment[0][0] <= assignment[1][0] && assignment[0][1] >= assignment[1][1])
|| (assignment[1][0] <= assignment[0][0] && assignment[1][1] >= assignment[0][1])
}
}
private fun part2(input: List<String>): Int {
return input.count { line ->
val assignment = line.split(",").map { it.split("-").map { section -> section.toInt() } }
(assignment[0][0] <= assignment[1][0] && assignment[1][0] <= assignment[0][1])
|| (assignment[0][0] <= assignment[1][1] && assignment[1][1] <= assignment[0][1])
|| (assignment[1][0] <= assignment[0][0] && assignment[0][0] <= assignment[1][1])
|| (assignment[1][0] <= assignment[0][1] && assignment[0][1] <= assignment[1][1])
}
}
fun main() {
val input = readInput("Day04")
// val input = readInput("Test")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 1,087 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | D000L | 575,350,411 | false | {"Kotlin": 23716} | sealed interface Component
data class File(val size: Long, val name: String) : Component
data class Directory(
val name: String,
val parent: Directory? = null
) : Component {
private val children: MutableList<Component> = mutableListOf()
fun addChild(component: Component) {
children.add(component)
}
fun findDirectory(name: String): Directory? {
return children.filterIsInstance<Directory>().find { it.name == name }
}
fun totalSize(): Long {
return children.sumOf {
when (it) {
is Directory -> it.totalSize()
is File -> it.size
}
}
}
fun sumOfSizeInRange(upper: Long): Long {
val current = if (totalSize() in 0L..upper) totalSize() else 0L
return current + children.filterIsInstance<Directory>().sumOf { it.sumOfSizeInRange(upper) }
}
fun findNearDirectorySize(amount: Long): Long {
return if (totalSize() > amount) {
totalSize().coerceAtMost(children.filterIsInstance<Directory>().minOf { it.findNearDirectorySize(amount) })
} else {
Long.MAX_VALUE
}
}
}
class FileSystem(data: List<String>) {
private val root = Directory("/")
init {
parse(data)
}
private fun parse(data: List<String>) {
var current: Directory? = root
data.forEach {
when {
it == "$ ls" -> return@forEach
it.startsWith("$ cd") -> {
val target = it.removePrefix("$ cd ")
current = when (target) {
".." -> current?.parent ?: current
else -> {
current?.findDirectory(target) ?: current
}
}
}
else -> {
val (component, name) = it.split(" ")
when (component) {
"dir" -> current?.addChild(Directory(name, current))
else -> current?.addChild(File(component.toLong(), name))
}
}
}
}
}
fun sumOfSizeInRange(upper: Long): Long = root.sumOfSizeInRange(upper)
fun optimize(max: Long, need: Long): Long {
return root.findNearDirectorySize(need - (max - root.totalSize()))
}
}
fun main() {
fun part1(input: List<String>): Long {
return FileSystem(input).sumOfSizeInRange(upper = 100000L)
}
fun part2(input: List<String>): Long {
return FileSystem(input).optimize(max = 70000000L, need = 30000000L)
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b733a4f16ebc7b71af5b08b947ae46afb62df05e | 2,742 | adventOfCode | Apache License 2.0 |
Kotlin/src/dev/aspid812/leetcode/problem1854/Solution.kt | Const-Grigoryev | 367,924,342 | false | {"Python": 35682, "Kotlin": 11162, "C++": 2688, "Java": 2168, "C": 1076} | package dev.aspid812.leetcode.problem1854
import java.time.Year
/* 1854. Maximum Population Year
* -----------------------------
*
* You are given a 2D integer array `logs` where each `logs[i] = [birth_i, death_i]` indicates the birth and death
* years of the `i`-th person.
*
* The **population** of some year `x` is the number of people alive during that year. The `i`-th person is counted
* in year `x`'s population if `x` is in the **inclusive** range `[birth_i, death_i - 1]`. Note that the person
* is **not** counted in the year that they die.
*
* Return *the **earliest** year with the **maximum population***.
*
* ### Constraints:
*
* * `1 <= logs.length <= 100`
* * `1950 <= birth_i < death_i <= 2050`
*/
import kotlin.math.min
typealias Lifespan = IntArray
data class PopulationRecord(
public val year: Int,
public val population: Int
)
class Solution {
fun maximumPopulation(logs: Array<Lifespan>): Int {
val birthYears = logs.map { log -> log[0] }.toIntArray()
birthYears.sort()
val deathYears = logs.map { log -> log[1] }.toIntArray()
deathYears.sort()
return sequence {
var population = 0
var (i, j) = Pair(0, 0)
while (i < birthYears.size || j < deathYears.size) {
var year = min(
birthYears.getOrNull(i) ?: 2050,
deathYears.getOrNull(j) ?: 2050
)
while (i < birthYears.size && birthYears[i] == year) {
population += 1
i++
}
while (j < deathYears.size && deathYears[j] == year) {
population -= 1
j++
}
yield(PopulationRecord(year, population))
}
}.maxByOrNull(PopulationRecord::population)?.year ?: 1950
}
}
fun makeLogs(vararg lifespans: IntRange): Array<Lifespan> {
return lifespans.map { range -> intArrayOf(range.start, range.endInclusive + 1) }.toTypedArray()
}
fun main() {
val s = Solution()
// The maximum population is 1, and 1993 is the earliest year with this population.
val logs1 = makeLogs(1993 until 1999, 2000 until 2010)
println("${s.maximumPopulation(logs1)} == 1993")
// The maximum population is 2, and it had happened in years 1960 and 1970.
// The earlier year between them is 1960.
val logs2 = makeLogs(1950 until 1961, 1960 until 1971, 1970 until 1981)
println("${s.maximumPopulation(logs2)} == 1960")
val logs3 = makeLogs(1982 until 1998, 2013 until 2042, 2010 until 2035, 2022 until 2050, 2047 until 2048)
println("${s.maximumPopulation(logs3)} == 2022")
}
| 0 | Python | 0 | 0 | cea8e762ff79878e2d5622c937f34cf20f0b385e | 2,720 | LeetCode | MIT License |
src/main/kotlin/aoc2022/Day13.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import readInput
import separateBy
import java.util.*
private object PacketComparator : Comparator<PacketData> {
override fun compare(left: PacketData, right: PacketData): Int {
//println("compare $left vs $right")
if (left is IntData) {
return if (right is IntData) {
left.value.compareTo(right.value)
} else {
compare(ListData(listOf(left)), right)
}
} else if (right is IntData) {
return compare(left, ListData(listOf(right)))
}
// both are lists
if (left is ListData && right is ListData) {
for (i in left.value.indices) {
val l = left.value[i]
if (right.value.size >= i + 1) {
val r = right.value[i]
val compare = compare(l, r)
if (compare != 0) {
return compare
}
} else {
return 1
}
}
return if (right.value.size > left.value.size) {
-1
} else {
0
}
} else {
throw IllegalArgumentException("Unknown type: $left, $right")
}
}
}
sealed class PacketData
data class IntData(val value: Int) : PacketData() {
override fun toString(): String {
return value.toString()
}
}
data class ListData(val value: List<PacketData>) : PacketData() {
companion object {
fun fromString(input: String): ListData {
val lists = Stack<MutableList<PacketData>>()
var currentInt = ""
input.forEach {
if (it.isDigit()) {
currentInt += it
} else if (currentInt.isNotEmpty()) {
lists.peek().add(IntData(currentInt.toInt()))
currentInt = ""
}
when (it) {
'[' -> lists.add(mutableListOf())
']' -> {
val l = lists.pop()
if (lists.isEmpty()) {
return ListData(l)
} else {
lists.peek().add(ListData(l))
}
}
else -> {} // ignore
}
}
throw IllegalArgumentException("Invalid input: $input")
}
}
override fun toString(): String {
return value.toString()
}
}
private fun part1(input: List<String>): Int {
return input.separateBy { it.isBlank() }.map { packetPair ->
val leftPacket = ListData.fromString(packetPair[0])
val rightPacket = ListData.fromString(packetPair[1])
PacketComparator.compare(leftPacket, rightPacket)
}.withIndex().filter { it.value == -1 }.sumOf { it.index + 1 }
}
private fun part2(input: List<String>): Int {
val list = input.filter { it.isNotBlank() }.map { ListData.fromString(it) }.toMutableList()
val dividerPacket1 = ListData(listOf(IntData(2)))
val dividerPacket2 = ListData(listOf(IntData(6)))
list.add(dividerPacket1)
list.add(dividerPacket2)
val sorted = list.sortedWith(PacketComparator)
return (sorted.indexOf(dividerPacket1) + 1) * (sorted.indexOf(dividerPacket2) + 1)
}
fun main() {
val testInput = readInput("Day13_test", 2022)
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13", 2022)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,619 | adventOfCode | Apache License 2.0 |
2022/Day24.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
val map = readInput("Day24")
val dirx = arrayOf(1, 0, -1, 0)
val diry = arrayOf(0, 1, 0, -1)
data class Wind(
val x: Int,
val y: Int,
val dir: Int
) {
fun next() = Wind(1 + (x - 1 + map[0].length-2 + dirx[dir]) % (map[0].length-2), 1 + (y - 1 + map.size-2 + diry[dir]) % (map.size-2), dir)
}
data class Pos(
val x: Int,
val y: Int
) {
fun nexts() = listOf(Pos(x + 1, y), Pos(x, y+1), Pos(x-1, y), Pos(x, y-1), this)
}
val dirChars = arrayOf('>', 'v', '<', '^')
var winds = HashSet<Wind>()
map.forEachIndexed() { y, s ->
s.forEachIndexed { x, ch ->
val dir = dirChars.indexOf(ch)
if (dir >= 0) winds.add(Wind(x, y, dir))
}
}
fun solve(startPos: Pos, endPos: Pos): Int {
var poss0 = HashSet<Pos>()
poss0.add(startPos)
var res = 0
while (endPos !in poss0) {
winds = winds.mapTo(HashSet()) { it.next() }
val poss1 = HashSet<Pos>()
for (p0 in poss0) {
for (p1 in p0.nexts()) {
if (p1.y < 0 || p1.y >= map.size || map[p1.y][p1.x] == '#') continue
if (dirx.indices.any() { winds.contains(Wind(p1.x,p1.y,it)) }) continue
poss1.add(p1)
}
}
poss0 = poss1
res++
print(".$res")
}
return res
}
val startPos = Pos(map[0].indexOf('.'), 0)
val endPos = Pos(map.last().indexOf('.'), map.lastIndex)
val res1 = solve(startPos, endPos)
println("\n$res1")
val res2 = res1 + solve(endPos, startPos) + solve(startPos, endPos)
println("\n$res2")
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,741 | advent-of-code-kotlin | Apache License 2.0 |
src/Day08.kt | Xacalet | 576,909,107 | false | {"Kotlin": 18486} | /**
* ADVENT OF CODE 2022 (https://adventofcode.com/2022/)
*
* Solution to day 8 (https://adventofcode.com/2022/day/8)
*
*/
import java.lang.Integer.max
fun main() {
fun part1(trees: List<List<Int>>): Int {
fun isVisibleFromTop(i: Int, j: Int): Boolean =
!(i - 1).downTo(0).any { trees[i][j] <= trees[it][j] }
fun isVisibleFromBottom(i: Int, j: Int): Boolean =
!((i + 1)..trees.lastIndex).any { trees[i][j] <= trees[it][j] }
fun isVisibleFromLeft(i: Int, j: Int): Boolean =
!(j - 1).downTo(0).any { trees[i][j] <= trees[i][it] }
fun isVisibleFromRight(i: Int, j: Int): Boolean =
!((j + 1)..trees[0].lastIndex).any { trees[i][j] <= trees[i][it] }
var visibleTrees = 0
trees.forEachIndexed { i, row ->
row.indices.forEach { j ->
if (isVisibleFromTop(i, j) ||
isVisibleFromBottom(i, j) ||
isVisibleFromLeft(i, j) ||
isVisibleFromRight(i, j)) {
visibleTrees++
}
}
}
return visibleTrees
}
fun part2(trees: List<List<Int>>): Int {
fun visibleTreesFromTop(i: Int, j: Int): Int =
(i - 1).downTo(0).countUntil { trees[i][j] <= trees[it][j] }
fun visibleTreesFromBottom(i: Int, j: Int): Int =
((i + 1)..trees.lastIndex).countUntil { trees[i][j] <= trees[it][j] }
fun visibleTreesFromLeft(i: Int, j: Int): Int =
(j - 1).downTo(0).countUntil { trees[i][j] <= trees[i][it] }
fun visibleTreesFromRight(i: Int, j: Int): Int =
((j + 1)..trees[0].lastIndex).countUntil { trees[i][j] <= trees[i][it] }
var widestView = -1
trees.forEachIndexed { i, row ->
row.indices.forEach { j ->
widestView = max(visibleTreesFromTop(i, j) *
visibleTreesFromBottom(i, j) *
visibleTreesFromLeft(i, j) *
visibleTreesFromRight(i, j), widestView)
}
}
return widestView
}
val trees = readInputLines("day08_dataset").map { line -> line.map { it.toString().toInt() } }
part1(trees).println()
part2(trees).println()
}
| 0 | Kotlin | 0 | 0 | 5c9cb4650335e1852402c9cd1bf6f2ba96e197b2 | 2,284 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | hrach | 572,585,537 | false | {"Kotlin": 32838} | fun main() {
fun isAdjacent(hx: Int, hy: Int, tx: Int, ty: Int): Boolean =
tx in (hx - 1..hx + 1) && ty in (hy - 1..hy + 1)
fun newPos(hx: Int, hy: Int, tx: Int, ty: Int): Pair<Int, Int> {
if (isAdjacent(hx, hy, tx, ty)) return tx to ty
val dx = if (hx > tx) 1 else if (hx == tx) 0 else -1
val dy = if (hy > ty) 1 else if (hy == ty) 0 else -1
return tx + dx to ty + dy
}
fun parse(input: List<String>): List<Pair<Char, Int>> =
input.map {
val (c, n) = it.split(" ")
c.first() to n.toInt()
}
fun part1(input: List<String>): Int {
var hx = 0
var hy = 0
var tx = 0
var ty = 0
val map = mutableSetOf<Pair<Int, Int>>()
parse(input).forEach { (c, n) ->
repeat(n) {
when (c) {
'U' -> hy += 1
'D' -> hy -= 1
'R' -> hx += 1
'L' -> hx -= 1
else -> error(c)
}
val new = newPos(hx, hy, tx, ty)
tx = new.first
ty = new.second
map.add(new)
}
}
return map.size
}
fun part2(input: List<String>): Int {
var hx = 0
var hy = 0
val knots = List(9) { Pair(0, 0) }.toMutableList()
val map = mutableSetOf<Pair<Int, Int>>()
parse(input).forEach { (c, n) ->
repeat(n) {
when (c) {
'U' -> hy += 1
'D' -> hy -= 1
'R' -> hx += 1
'L' -> hx -= 1
else -> error(c)
}
var prev = hx to hy
for (index in knots.indices) {
val knot = knots[index]
val new = newPos(prev.first, prev.second, knot.first, knot.second)
knots[index] = new
prev = new
}
map.add(knots.last())
}
}
return map.size
}
val test2 = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent().lines()
val testInput = readInput("Day09_test")
check(part1(testInput), 13)
check(part2(testInput), 1)
check(part2(test2), 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 40b341a527060c23ff44ebfe9a7e5443f76eadf3 | 2,484 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | HylkeB | 573,815,567 | false | {"Kotlin": 83982} |
private class Stack(val index: Int, val items: ArrayDeque<Char>) {
override fun toString() = "$index: ${items.reversed()}"
}
private class MoveInstruction(val amount: Int, val fromIndex: Int, val toIndex: Int) {
override fun toString(): String = "move $amount from $fromIndex to $toIndex"
}
private fun parseData(input: List<String>): Pair<List<Stack>, List<MoveInstruction>> {
val startingStackData = input.subList(0, input.indexOf("") - 1)
val amountOfStacks = input[input.indexOf("") - 1].last().digitToInt()
val stacks = List(amountOfStacks) { index -> Stack(index, ArrayDeque()) }
startingStackData.forEach { stackData ->
stackData.forEachIndexed { index, item ->
if (item in 'A'..'Z') {
// index 1, 5, 9 equal index 0, 1, 2, so divide by 4
val stackIndex = (index / 4)
stacks[stackIndex].items.addLast(item)
}
}
}
val moveInstructionData = input.subList(input.indexOf("") + 1, input.size)
val moveInstructions = moveInstructionData.map { moveData ->
val parts = moveData.split(" ")
// minus 1 is because we work with 0 indexed information
MoveInstruction(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1)
}
return stacks to moveInstructions
}
fun main() {
fun part1(input: List<String>): String {
val (stacks, moveInstructions) = parseData(input)
moveInstructions.forEach { instruction ->
repeat(instruction.amount) {
val itemMoved = stacks[instruction.fromIndex].items.removeFirst()
stacks[instruction.toIndex].items.addFirst(itemMoved)
}
}
return stacks.joinToString(separator = "") { it.items.first().toString() }
}
fun part2(input: List<String>): String {
val (stacks, moveInstructions) = parseData(input)
moveInstructions.forEach { instruction ->
val fromStack = stacks[instruction.fromIndex].items
val toStack = stacks[instruction.toIndex].items
val itemsMoved = (0 until instruction.amount).map { fromStack.removeFirst() }.reversed()
itemsMoved.forEach { itemMoved ->
toStack.addFirst(itemMoved)
}
}
return stacks.joinToString(separator = "") { it.items.first().toString() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8649209f4b1264f51b07212ef08fa8ca5c7d465b | 2,658 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day13.kt | f1qwase | 572,888,869 | false | {"Kotlin": 33268} | import java.lang.Character.isDigit
private sealed interface PacketElement: Comparable<PacketElement> {
data class Dgt(val value: Int) : PacketElement {
override fun compareTo(other: PacketElement): Int = when (other) {
is Dgt -> value.compareTo(other.value)
is Lst -> Lst(listOf(this)).compareTo(other)
}
override fun toString(): String = value.toString()
}
data class Lst(val elements: List<PacketElement>) : PacketElement {
override fun compareTo(other: PacketElement): Int = when (other) {
is Dgt -> - other.compareTo(this)
is Lst -> {
// println("compare: $this $other")
when {
other.elements.isEmpty() || elements.isEmpty() -> {
elements.size.compareTo(other.elements.size)
}
else -> {
val first = elements.first().compareTo(other.elements.first())
if (first != 0) first
else Lst(elements.drop(1)).compareTo(Lst(other.elements.drop(1)))
}
}
}
}
override fun toString(): String = "[${elements.joinToString(",")}]"
}
}
private fun parsePacket(input: String, startFrom: Int = 0, parentList: MutableList<PacketElement>): Int {
var i = startFrom
while (i < input.length) {
val char = input[i]
when {
char == '[' -> {
val sublist = mutableListOf<PacketElement>()
val end = parsePacket(input, i + 1, sublist)
parentList.add(PacketElement.Lst(sublist))
i = end + 1
}
char == ']' -> return i
isDigit(char) -> {
val numberStart = i
while (i < input.length && isDigit(input[i])) {
i++
}
val value = input.substring(numberStart, i).toInt()
parentList.add(PacketElement.Dgt(value))
}
char == ',' -> {
i++
}
else -> {
throw IllegalArgumentException("Unexpected char $char")
}
}
}
return i
}
private fun parseInput(input: List<String>): List<Pair<PacketElement, PacketElement>> =
input.filter { it.isNotEmpty() }.chunked(2) {
val (left, right) = it.take(2).map { line ->
val list = mutableListOf<PacketElement>()
parsePacket(line, 0, list)
list.single()
}
left to right
}
fun main() {
fun part1(input: List<String>): Int {
return parseInput(input)
// .onEachIndexed {i, (left, right) ->
// val result = if (left < right) "right" else "NOT"
// println("${i + 1}: ${result}, $left $right")
// }
.mapIndexed { i, (left, right) -> if (left < right) i + 1 else 0 }
.sum()
}
fun part2(input: List<String>): Int {
val dividers = listOf("[[2]]", "[[6]]")
println(input + dividers)
return parseInput(input + dividers).flatMap { (left, right) ->
listOf(left, right)
}.sorted()
.map { it.toString() }
.withIndex()
.filter { it.value in listOf("[[2]]", "[[6]]")}
.also { check(it.size == 2) }
.map {it.index + 1}
.reduce(Int::times)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
part1(testInput).let { check(it == 13) { it } }
val input = readInput("Day13")
println(part1(input))
part2(testInput).let { check(it == 140) { it } }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3fc7b74df8b6595d7cd48915c717905c4d124729 | 3,879 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/advent/of/code/hjk/Day24.kt | h-j-k | 427,964,167 | false | {"Java": 46088, "Kotlin": 26804} | package com.advent.of.code.hjk
import java.util.ArrayDeque
object Day24 {
private fun parse(input: List<String>): List<List<Position>> = input.indices.map { y ->
input[0].indices.map { x -> Position(x = x, y = y, value = input[y][x].toString()) }
}
private fun Position.from(other: Position, board: List<List<Position>>): Int {
val seen = mutableMapOf(this to 0)
val queue = ArrayDeque<Position>().also { it.add(this) }
while (queue.isNotEmpty()) {
val current = queue.pop()
val distance = seen.getValue(current)
if (current == other) return distance
listOf(
board[current.y][current.x - 1],
board[current.y][current.x + 1],
board[current.y - 1][current.x],
board[current.y + 1][current.x]
).filter { it.isValid && !it.isWall && it !in seen }.let { neighbors ->
seen.putAll(neighbors.map { it to distance + 1 })
queue.addAll(neighbors)
}
}
return 0
}
private fun mapDistances(map: List<List<Position>>): Map<Pair<Int, Int>, Int> {
val targets = map.flatMap { r -> r.mapNotNull { p -> p.n?.let { it to p } } }.toMap()
return targets.flatMap { (target, position) ->
targets.filter { it.key > target }.flatMap { (otherTarget, otherPosition) ->
val distance = position.from(otherPosition, map)
listOf(target to otherTarget, otherTarget to target).map { it to distance }
}
}.toMap()
}
private fun shortestPath(map: List<List<Position>>, isReturning: Boolean): Int {
val (targets, distances) = mapDistances(map).let { it.keys.flatMap { (a, b) -> listOf(a, b) }.toSet() to it }
fun move(leftover: Set<Int>, current: Int, steps: Int): Int =
if (leftover.isEmpty()) steps + (distances.getValue(current to 0).takeIf { isReturning } ?: 0)
else targets.filter { it in leftover }
.minOf { move(leftover - it, it, steps + distances.getValue(current to it)) }
return move(targets - 0, 0, 0)
}
fun part1(input: List<String>): Int = shortestPath(parse(input), false)
fun part2(input: List<String>): Int = shortestPath(parse(input), true)
private data class Position(val x: Int, val y: Int, val value: String) {
val isValid = x >= 0 && y >= 0
val isWall = value == "#"
val n = try {
value.toInt()
} catch (e: NumberFormatException) {
null
}
}
} | 0 | Java | 0 | 0 | 5ffa381e97cbcfe234c49b5a5f8373641166db6c | 2,607 | advent16 | Apache License 2.0 |
src/Day18.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | import java.util.*
class Cube(val x: Int, val y: Int, val z: Int) {
val coordKey: String
get() = "${this.x},${this.y},${this.z}"
fun add(vector: Cube): Cube {
return Cube(this.x + vector.x, this.y + vector.y, this.z + vector.z)
}
}
class Day18 {
fun part1(input: List<String>): Int {
val cubeCoords = mutableSetOf<String>()
val cubes = mutableListOf<Cube>()
var allSides = input.size * 6
for (line in input) {
cubeCoords.add(line)
val (x, y, z) = line.split(',').map { it.toInt() }
cubes.add(Cube(x, y, z))
}
for (c in cubes) {
val neighborCooords = listOf(
Cube(c.x, c.y, c.z + 1),
Cube(c.x, c.y, c.z - 1),
Cube(c.x, c.y + 1, c.z),
Cube(c.x, c.y - 1, c.z),
Cube(c.x + 1, c.y, c.z),
Cube(c.x - 1, c.y, c.z)
)
for (n in neighborCooords) {
if (cubeCoords.contains(n.coordKey)) {
allSides--
}
}
}
return allSides
}
fun part2(input: List<String>): Int {
val WORLD_SIZE = 25
val coords = Array(WORLD_SIZE) { Array(WORLD_SIZE) { IntArray(WORLD_SIZE) { 0 } } }
for (line in input) {
val (x, y, z) = line.split(',').map { it.toInt() }
coords[x + 1][y + 1][z + 1] = 1
}
val foundSides = mutableSetOf<String>()
println(iterativeDFS(coords, Cube(0, 0, 0), mutableSetOf(), foundSides, WORLD_SIZE))
//println(visited.size)
println(foundSides.size)
return foundSides.size
}
}
//fun DFS(graph: Array<Array<IntArray>>, c: Cube, visited: MutableSet<String>, foundSides: MutableSet<String>, WORLD_SIZE: Int) {
// visited.add(c.coordKey)
// val neighbors = listOf(
// Cube(c.x, c.y, c.z + 1),
// Cube(c.x, c.y, c.z - 1),
// Cube(c.x, c.y + 1, c.z),
// Cube(c.x, c.y - 1, c.z),
// Cube(c.x + 1, c.y, c.z),
// Cube(c.x - 1, c.y, c.z)
// ).filter { it.x >= 0 && it.y >= 0 && it.z >= 0 && it.x < WORLD_SIZE && it.y < WORLD_SIZE && it.z < WORLD_SIZE}
//
// val cubeNeighbors = neighbors.filter { graph[it.x][it.y][it.z] == 1 }
// cubeNeighbors.forEach { foundSides.add(it.coordKey + "-" + c.coordKey) }
// val freeNeighbors = neighbors.filter { graph[it.x][it.y][it.z] == 0 }
// for (n in freeNeighbors) {
// if (!visited.contains(n.coordKey)) {
// DFS(graph, n, visited, foundSides, WORLD_SIZE)
// }
// }
//}
fun main() {
val input = readInput("input18_1")
//println(Day18().part1(input))
println(Day18().part2(input))
}
fun iterativeDFS(graph: Array<Array<IntArray>>, c: Cube, visited: MutableSet<String>, foundSides: MutableSet<String>, WORLD_SIZE: Int): MutableSet<String> {
val stack: Stack<Cube> = Stack()
stack.push(c)
while (!stack.empty()) {
// Pop a vertex from the stack
val current = stack.pop()
// if the vertex is already discovered yet, ignore it
if (visited.contains(current.coordKey)) {
continue
}
// we will reach here if the popped vertex `v` is not discovered yet;
// print `v` and process its undiscovered adjacent nodes into the stack
visited.add(current.coordKey)
val neighbors = listOf(
Cube(current.x, current.y, current.z + 1),
Cube(current.x, current.y, current.z - 1),
Cube(current.x, current.y + 1, current.z),
Cube(current.x, current.y - 1, current.z),
Cube(current.x + 1, current.y, current.z),
Cube(current.x - 1, current.y, current.z)
).filter { it.x >= 0 && it.y >= 0 && it.z >= 0 && it.x < WORLD_SIZE && it.y < WORLD_SIZE && it.z < WORLD_SIZE}
val cubeNeighbors = neighbors.filter { graph[it.x][it.y][it.z] == 1 }
cubeNeighbors.forEach { foundSides.add(it.coordKey + "-" + current.coordKey) }
val freeNeighbors = neighbors.filter { graph[it.x][it.y][it.z] == 0 }
for (n in freeNeighbors) {
if (!visited.contains(n.coordKey)) {
stack.push(n)
}
}
}
return foundSides
} | 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 4,298 | advent-of-code | Apache License 2.0 |
src/day5/Day5.kt | pocmo | 433,766,909 | false | {"Kotlin": 134886} | package day5
import java.io.File
data class Line(
val x1: Int,
val y1: Int,
val x2: Int,
val y2: Int
) {
private fun isHorizontal(): Boolean = y1 == y2
private fun isVertical(): Boolean = x1 == x2
private fun isDiagonal(): Boolean = !isHorizontal() && !isVertical()
fun isHorizontalOrVertical(): Boolean = isHorizontal() || isVertical()
fun getPoints(): List<Pair<Int, Int>> {
return if (isHorizontal()) {
val points = mutableListOf<Pair<Int, Int>>()
val startX = x1.coerceAtMost(x2)
val endX = x1.coerceAtLeast(x2)
for (x in startX..endX) {
points.add(Pair(x, y1))
}
points
} else if (isVertical()) {
val points = mutableListOf<Pair<Int, Int>>()
val startY = y1.coerceAtMost(y2)
val endY = y1.coerceAtLeast(y2)
for (y in startY..endY) {
points.add(Pair(x1, y))
}
points
} else if (isDiagonal()) {
getDiagonalPoints(x1, y1, x2, y2)
} else {
throw IllegalStateException("Line is not horizontal, vertical or diagonal")
}
}
}
fun getDiagonalPoints(startX: Int, startY: Int, endX: Int, endY: Int): List<Pair<Int, Int>> {
val points = mutableListOf<Pair<Int, Int>>()
val start = Pair(startX, startY)
val end = Pair(endX, endY)
val xDiff = end.first - start.first
val yDiff = end.second - start.second
val xStep = if (xDiff > 0) 1 else -1
val yStep = if (yDiff > 0) 1 else -1
var x = start.first
var y = start.second
while (x != end.first || y != end.second) {
points.add(Pair(x, y))
x += xStep
y += yStep
}
points.add(Pair(x, y))
return points
}
fun readLines(): List<Line> {
val values = File("day5.txt").readLines()
return values.map { line ->
val (point1, point2) = line.split(" -> ")
val (x1, y1) = point1.split(",")
val (x2, y2) = point2.split(",")
Line(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt())
}
}
fun List<Pair<Int, Int>>.getDuplicates(): Set<Pair<Int, Int>> {
val counts = mutableMapOf<Pair<Int, Int>, Int>()
for (point in this) {
val count = counts.getOrDefault(point, 0)
counts[point] = count + 1
}
return counts.filter { it.value > 1 }.keys
}
fun part1() {
val points = readLines()
.filter { it.isHorizontalOrVertical() }
.map { it.getPoints() }
.flatten()
.getDuplicates()
println(points.size)
}
fun part2() {
val points = readLines()
.map { it.getPoints() }
.flatten()
.getDuplicates()
// Wong: 22982
// Right: 21406
println(points.size)
}
fun main() {
part2()
}
| 0 | Kotlin | 1 | 2 | 73bbb6a41229e5863e52388a19108041339a864e | 2,807 | AdventOfCode2021 | Apache License 2.0 |
src/main/kotlin/dp/DisplayWords.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
import kotlin.math.pow
// given a sequence of n words and their corresponding length stored in l[1..n]
// we want to break it into L lines
// in each line, the first char starts at the left and except the last line,
// the last character ends in the right
// define the slop as the sum over line 1 until L
// each line containing word i to j as (L - j + i - sum(l[i..j]))^3
// find the minimum total slop for n words
fun main(args: Array<String>) {
val len = oneArrayOf(1, 20, 10)
println(len.minTotalSlop(2))
}
fun OneArray<Int>.minTotalSlop(L: Int): Int {
val n = size
val INF = Int.MAX_VALUE / 2
// dp(l, i, j): sum of slop of 1..l where line l contains word i to j
// memoization structure: 3d array dp[1 until L, 1..n, 1..n] : dp[l, i, j] = dp(l, i, j)
val dp = OneArray(L - 1) { OneArray(n) { OneArray(n) { INF } } }
// preprocess in O(n^2) time and space
val sumTable = allPairsSum()
// sumTable.prettyPrintTable()
// base case:
// dp(1, 1, j) = slop(1, 1, j), 1 < j <= n - (L - 1)
// dp(1, i, j) = +inf o/w
for (j in 1..n - L + 1) {
dp[1, 1, j] = slop(L, 1, j, sumTable)
}
// dp.prettyPrintTables()
// we want min{ dp(L - 1, i, j) }
var min = dp[1, 1].min() ?: INF
// recursive case:
// assume min{ } = +inf
// dp(l, i, j) = min{ dp(l - 1, k, i - 1) } + slop(l, i, j)
// k < i - 1 < i < j
for (l in 2 until L) {
for (i in l..n + l - L) {
for (j in i..n + l - L) {
dp[l, i, j] = slop(l, i, j, sumTable) +
((1 until i).map { k -> dp[l - 1, k, i - 1] }.min()
?: INF)
if (l == L - 1) {
min = min(min, dp[l, i, j])
}
}
}
}
// time complexity: O(n^3L)
dp.prettyPrintTables()
return min
}
// return a table dp[1..n, 1..n] : dp[1, j] = sum(l[i..j])
fun OneArray<Int>.allPairsSum(): OneArray<OneArray<Int>> {
val l = this
val n = l.size
val dp = OneArray(n) { OneArray(n) { 0 } }
for (i in 1..n) {
dp[i, i] = l[i]
for (j in i + 1..n) {
dp[i, j] = dp[i, j - 1] + l[j]
}
}
// O(n^2) space and time
return dp
}
// O(1) time
fun OneArray<Int>.slop(L: Int, i: Int, j: Int, sumTable: OneArray<OneArray<Int>>) = ((L - j + i - sumTable[i, j]).toDouble()).pow(3).toInt()
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,198 | AlgoKt | MIT License |
src/Day12.kt | frango9000 | 573,098,370 | false | {"Kotlin": 73317} | fun main() {
val input = readInput("Day12")
printTime { println(Day12.part1(input)) }
printTime { println(Day12.part2(input)) }
}
class Day12 {
companion object {
fun part1(input: List<String>): Int {
val (end, start) = input.toHeightGraph()
return end.getShortestPathBfs { it == start }
}
fun part2(input: List<String>): Int {
val (end) = input.toHeightGraph()
return end.getShortestPathBfs { it.height == 0 }
}
}
}
class Node(val height: Int, val neighbors: MutableList<Node> = mutableListOf()) {
var distance = 0
fun getShortestPathBfs(isDestination: (Node) -> Boolean): Int {
val queue: ArrayDeque<Node> = ArrayDeque()
val visited = mutableSetOf(this)
queue.add(this)
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
if (isDestination(node)) return node.distance
node.neighbors.filter { it.height >= node.height - 1 }.filter { it !in visited }.forEach {
it.distance = node.distance + 1
queue.add(it)
visited.add(it)
}
}
throw IllegalStateException("Could not find a path to the target node")
}
//private fun getShortestPathDfs(from: Node, to: Node, path: List<Node> = listOf()): Long {
// if (from == to) {
// return 0L
// }
// val validPaths = from.neighbors.filter { !path.contains(it) }
// if (validPaths.isNotEmpty()) {
// return validPaths.minOf { 1L + getShortestPathDfs(it, to, listOf(*path.toTypedArray(), from)) }
// }
// return Int.MAX_VALUE.toLong()
//}
}
fun List<String>.toHeightGraph(): List<Node> {
var start = Node(0)
var end = Node(0)
val nodes: List<List<Node>> = this.map {
it.toCharArray().map { height ->
val newNode: Node
when (height) {
'S' -> {
newNode = Node(0)
start = newNode
}
'E' -> {
newNode = Node('z' - 'a')
end = newNode
}
else -> newNode = Node(height - 'a')
}
newNode
}
}
nodes.matrixForEachIndexed { i, j, _ ->
if (i > 0) {
nodes[i][j].neighbors.add(nodes[i - 1][j])
}
if (i < nodes.lastIndex) {
nodes[i][j].neighbors.add(nodes[i + 1][j])
}
if (j > 0) {
nodes[i][j].neighbors.add(nodes[i][j - 1])
}
if (j < nodes[i].lastIndex) {
nodes[i][j].neighbors.add(nodes[i][j + 1])
}
}
return listOf(end, start)
}
| 0 | Kotlin | 0 | 0 | 62e91dd429554853564484d93575b607a2d137a3 | 2,759 | advent-of-code-22 | Apache License 2.0 |
src/year2023/04/Day04.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`04`
import readInput
import utils.printlnDebug
import kotlin.math.pow
import kotlin.math.roundToInt
private const val CURRENT_DAY = "04"
private fun parseLineIntoCardValues(
line: String,
): Set<String> {
val winningNumbers = line.split("|")
.first()
.split(":")[1]
.trim()
.split(" ")
.filter { it.isNotEmpty() }
val myNumbers = line.split("|")[1]
.trim()
.split(" ")
.filter { it.isNotEmpty() }
return winningNumbers.intersect(myNumbers.toSet())
}
private fun Collection<String>.toAnswerValue(): Int {
if (isEmpty()) return 0
return 2.0.pow(this.size - 1).roundToInt()
}
private fun part2Impl(input: List<String>): Int {
val intersectedCountForCard = mutableMapOf<Int, Int>()
input.mapIndexed { index, line ->
val something = parseLineIntoCardValues(line)
intersectedCountForCard[index] = something.count()
}
printlnDebug { intersectedCountForCard }
val mapOfCardsAtAll = intersectedCountForCard.keys.associateWith { 1 }
.toMutableMap()
intersectedCountForCard.keys.sorted()
.forEach { index ->
val listSize = intersectedCountForCard[index]!!
val howMuchCardIHaveRightNow = mapOfCardsAtAll[index]!!
printlnDebug { "howMuchCardIHaveRightNow: index$index amount:$howMuchCardIHaveRightNow" }
repeat(listSize) { wonIndex ->
val realIndex = index + wonIndex + 1
mapOfCardsAtAll.compute(realIndex) { _, currentValue ->
val initialValue = currentValue ?: 0
initialValue + howMuchCardIHaveRightNow
}
}
}
printlnDebug { "mapOfCount: $mapOfCardsAtAll" }
return mapOfCardsAtAll.values.sum()
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
parseLineIntoCardValues(it).toAnswerValue()
}
}
fun part2(input: List<String>): Int {
return part2Impl(input)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput)
val part2Test = part2(testInput)
println(part1Test)
check(part1Test == 13)
println(part2Test)
check(part2Test == 30)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input)
println(part1)
check(part1 == 28750)
// Part 2
val part2 = part2(input)
println(part2)
check(part2 == 10212704)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 2,598 | KotlinAdventOfCode | Apache License 2.0 |
src/year2023/day22/Day22.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2023.day22
import check
import parallelMap
import readInput
fun main() {
val testInput = readInput("2023", "Day22_test")
check(part1(testInput), 5)
check(part2(testInput), 7)
val input = readInput("2023", "Day22")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val bricks = input.parseBricks().settleBricks()
return bricks.parallelMap { (bricks - it).isStable() }.count { it }
}
private fun part2(input: List<String>): Int {
val bricks = input.parseBricks().settleBricks()
return bricks.parallelMap { (bricks - it).countFallingBricks() }.sum()
}
private data class Pos(val x: Int, val y: Int, val z: Int) {
fun down() = Pos(x, y, z - 1)
}
private data class Brick(val volume: Set<Pos>, val id: Int = nextId()) {
fun down() = Brick(volume.mapTo(mutableSetOf()) { it.down() }, id)
companion object {
private var idSeq = 0
private fun nextId() = idSeq++
}
}
private fun List<String>.parseBricks() = map { line ->
val (start, end) = line.split('~', ',').map { it.toInt() }.chunked(3)
val (startX, startY, startZ) = start
val (endX, endY, endZ) = end
val volume = mutableSetOf<Pos>()
for (x in startX..endX) {
for (y in startY..endY) {
for (z in startZ..endZ) {
volume += Pos(x, y, z)
}
}
}
Brick(volume)
}
private fun List<Brick>.settleBricks(): List<Brick> {
var bricksToSettle = ArrayDeque(this)
val occupiedVolume = flatMap { it.volume }.toMutableSet()
do {
var moved = false
val newBricksToSettle = ArrayDeque<Brick>()
while (bricksToSettle.isNotEmpty()) {
val currentBrick = bricksToSettle.removeFirst()
occupiedVolume -= currentBrick.volume
val newBrick = currentBrick.down()
val canGoDown = newBrick.volume.none { it.z == 0 } && newBrick.volume.none { it in occupiedVolume }
val brick = if (canGoDown) newBrick else currentBrick
newBricksToSettle += brick
occupiedVolume += brick.volume
if (canGoDown) moved = true
}
bricksToSettle = newBricksToSettle
} while (moved)
return bricksToSettle
}
private fun List<Brick>.isStable(): Boolean = countFallingBricks() == 0
private fun List<Brick>.countFallingBricks(): Int {
val originalById = associateBy { it.id }
val settled = settleBricks()
return settled.count { originalById.getValue(it.id).volume != it.volume }
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 2,560 | AdventOfCode | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day12.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val input = readInput(2023, 12, false).readLines().map { line ->
val (spread, compact) = line.split(" ")
spread to compact.split(",").map { it.toInt() }
}
part1(input)
part2(input)
}
private fun part1(input: List<Pair<String, List<Int>>>) {
val result = input.sumOf { (spread, compact) -> arrangements(spread, compact) }
println(result)
}
private fun part2(input: List<Pair<String, List<Int>>>) {
val result = input.sumOf { (s, c) ->
val spread = (1..5).joinToString("?") { s }
val compact = (1..5).flatMap { c }
arrangements(spread, compact)
}
println(result)
}
private fun arrangements(spread: String, compact: List<Int>, cache: MutableMap<String, Long> = hashMapOf()): Long {
var count = 0L
for (i in spread.indices) {
if (i > 0 && spread[i - 1] == '#') return count
val char = spread[i]
if (char == '.') continue
if (compact.isEmpty() && char == '#') return 0
if (compact.isEmpty()) continue
val matchSize = compact.first()
if (i + matchSize > spread.length) continue
val spreadEquivalent = spread.substring(i, i + matchSize)
val isMatch = spreadEquivalent.all { it != '.' }
val hasDelimiter = i + matchSize == spread.length || spread[i + matchSize] != '#'
if (isMatch) count += when {
i + matchSize > spread.lastIndex -> arrangements("", compact.drop(1), cache)
hasDelimiter -> {
val next = spread.substring(i + matchSize + 1)
val nextCompact = compact.drop(1)
val key = "$next-${nextCompact.hashCode()}"
cache.getOrPut(key) { arrangements(next, nextCompact, cache) }
}
else -> 0
}
}
return if (compact.isEmpty()) 1 else count
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,948 | adventofcode | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2020/Day16.kt | tginsberg | 315,060,137 | false | null | /*
* Copyright (c) 2020 by <NAME>
*/
/**
* Advent of Code 2020, Day 16 - Ticket Translation
* Problem Description: http://adventofcode.com/2020/day/16
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day16/
*/
package com.ginsberg.advent2020
class Day16(input: List<String>) {
private val ticketRules: Map<String,List<IntRange>> = parseTicketRules(input)
private val allRuleRanges: List<IntRange> = ticketRules.values.flatten()
private val ourTicket: List<Int> = parseOurTicket(input)
private val nearbyTickets: List<List<Int>> = parseNearbyTickets(input)
fun solvePart1(): Int =
nearbyTickets.sumBy { ticket ->
ticket.filter { field ->
allRuleRanges.none { rule -> field in rule }
}.sum()
}
fun solvePart2(): Long {
val validTickets = nearbyTickets.filter { it.isValidTicket() }
val possibleFieldRules: Map<String,MutableSet<Int>> = ticketRules.keys.map { rule ->
rule to ourTicket.indices.filter { column ->
validTickets.columnPassesRule(column, rule)
}.toMutableSet()
}.toMap()
val foundRules = reduceRules(possibleFieldRules)
return foundRules.entries
.filter { it.key.startsWith("departure") }
.map { ourTicket[it.value].toLong() }
.reduce { a, b -> a * b }
}
private fun reduceRules(possibleRules: Map<String,MutableSet<Int>>): Map<String,Int> {
val foundRules = mutableMapOf<String,Int>()
while(foundRules.size < possibleRules.size) {
possibleRules.entries
.filter { (_, possibleValues) -> possibleValues.size == 1 }
.forEach { (rule, possibleValues) ->
val columnNumber = possibleValues.first()
foundRules[rule] = columnNumber
possibleRules.values.forEach { it.remove(columnNumber) }
}
}
return foundRules
}
private fun List<List<Int>>.columnPassesRule(column: Int, fieldName: String): Boolean =
this.all { ticket ->
ticketRules.getValue(fieldName).any { rule -> ticket[column] in rule }
}
private fun List<Int>.isValidTicket(): Boolean =
this.all { field ->
allRuleRanges.any { rule ->
field in rule
}
}
private fun parseTicketRules(input: List<String>): Map<String,List<IntRange>> =
input.takeWhile { it.isNotEmpty() }.map { line ->
val (name, start1, end1, start2, end2) = ticketRuleRegex.matchEntire(line)!!.destructured
name to listOf(
start1.toInt() .. end1.toInt(),
start2.toInt() .. end2.toInt()
)
}.toMap()
private fun parseOurTicket(input: List<String>): List<Int> =
input.dropWhile { it != "your ticket:" }.drop(1).first().split(",").map { it.toInt() }
private fun parseNearbyTickets(input: List<String>): List<List<Int>> =
input.dropWhile { it != "nearby tickets:" }.drop(1).map { row ->
row.split(",").map { it.toInt() }
}
companion object {
private val ticketRuleRegex = """^([a-z ]+): (\d+)-(\d+) or (\d+)-(\d+)$""".toRegex()
}
}
| 0 | Kotlin | 2 | 38 | 75766e961f3c18c5e392b4c32bc9a935c3e6862b | 3,313 | advent-2020-kotlin | Apache License 2.0 |
year2017/src/main/kotlin/net/olegg/aoc/year2017/day7/Day7.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2017.day7
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2017.DayOf2017
/**
* See [Year 2017, Day 7](https://adventofcode.com/2017/day/7)
*/
object Day7 : DayOf2017(7) {
override fun first(): Any? {
return lines
.map { line -> line.split(" ").map { it.replace(",", "") } }
.fold(emptySet<String>() to emptySet<String>()) { acc, list ->
val used = if (list.size > 3) acc.second + list.subList(3, list.size) else acc.second
val free = (acc.first + list[0]) - used
return@fold free to used
}
.first
.first()
}
override fun second(): Any? {
val disks = lines
.map { it.replace("[()\\->,]".toRegex(), "").split("\\s+".toRegex()) }
.associate { it[0] to (it[1].toInt() to it.subList(2, it.size)) }
val head = disks.entries.fold(emptySet<String>() to emptySet<String>()) { acc, disk ->
val used = acc.second + disk.value.second
val free = (acc.first + disk.key) - used
return@fold free to used
}
.first
.first()
val weights = getWeights(disks, head)
var curr = head
var result = 0
do {
val disk = disks.getOrDefault(curr, 0 to emptyList())
val odd = disk.second
.map { it to (weights[it] ?: 0) }
.groupBy { it.second }
.toList()
.sortedBy { it.second.size }
if (odd.size != 1) {
curr = odd.first().second.first().first
result = (disks[curr]?.first ?: 0) + odd.last().first - odd.first().first
}
} while (odd.size != 1)
return result
}
private fun getWeights(
map: Map<String, Pair<Int, List<String>>>,
root: String
): Map<String, Int> {
val curr = map.getOrDefault(root, 0 to emptyList())
val inter = curr.second
.fold(emptyMap<String, Int>()) { acc, value -> acc + getWeights(map, value) }
.let { children ->
children + mapOf(root to curr.first + curr.second.sumOf { children[it] ?: 0 })
}
return inter
}
}
fun main() = SomeDay.mainify(Day7)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,057 | adventofcode | MIT License |
src/Day13.kt | dmstocking | 575,012,721 | false | {"Kotlin": 40350} |
sealed class Item : Comparable<Item> {
override fun compareTo(other: Item): Int {
return this.compare(other)
}
}
data class ItemList(val items: List<Item>): Item()
data class Value(val value: Int): Item()
fun Item.compare(right: Item): Int {
val left = this
return when {
left is ItemList && right is ItemList -> left.compare(right)
left is ItemList && right is Value -> left.compare(ItemList(listOf(right)))
left is Value && right is ItemList -> ItemList(listOf(left)).compare(right)
left is Value && right is Value -> left.value - right.value
else -> throw Exception()
}
}
fun ItemList.compare(right: ItemList): Int {
val left = this
left.items.zip(right.items)
.forEach { (l, r) ->
val compare = l.compare(r)
if (compare != 0) {
return compare
}
}
return left.items.size - right.items.size
}
class StringParser(private val string: String) {
private var i = 0
fun next(): Char = string[i++]
fun peek(): Char = string[i]
}
fun parseItemList(stringParser: StringParser): ItemList {
stringParser.next()
val items = mutableListOf<Item>()
while (true) {
when (stringParser.peek()) {
']' -> {
stringParser.next()
return ItemList(items)
}
else -> {
items.add(parseItem(stringParser))
if (stringParser.peek() == ',') {
stringParser.next()
}
}
}
}
}
fun parseItem(stringParser: StringParser): Item {
return when (stringParser.peek()) {
'[' -> parseItemList(stringParser)
else -> {
generateSequence {
if (stringParser.peek().isDigit()) {
stringParser.next()
} else {
null
}
}
.joinToString(separator = "")
.toInt()
.let { Value(it) }
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return input
.chunked(3)
.mapIndexed { i, lines ->
val (left, right) = lines
.let { (left, right) -> StringParser(left) to StringParser(right) }
.let { (left, right) -> parseItem(left) to parseItem(right) }
if (left.compare(right) < 0) i+1 else 0
}
.sumOf { it }
}
fun part2(input: List<String>): Int {
return input
.plus("")
.plus("[[2]]")
.plus("[[6]]")
.chunked(3)
.flatMap { lines ->
val (left, right) = lines
.let { (left, right) -> StringParser(left) to StringParser(right) }
.let { (left, right) -> parseItem(left) to parseItem(right) }
listOf(left, right)
}
.sortedBy { it }
.let {
val decoderKeys = listOf("[[2]]", "[[6]]").map { parseItem(StringParser(it)) }
it.mapIndexedNotNull { i, item ->
if (item in decoderKeys) {
i + 1
} else {
null
}
}
}
.let { (i, j) -> i * j }
}
// 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))
}
| 0 | Kotlin | 0 | 0 | e49d9247340037e4e70f55b0c201b3a39edd0a0f | 3,685 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/y2023/Day06.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2023
import util.product
import util.readInput
import util.timingStatistics
import kotlin.math.sqrt
object Day06 {
private fun parse(input: List<String>): Pair<List<Int>, List<Int>> {
val time = input[0].split(Regex("\\s+")).drop(1).map { it.toInt() }
val distance = input[1].split(Regex("\\s+")).drop(1).map { it.toInt() }
return Pair(time, distance)
}
fun part1(input: List<String>): Int {
val (times, records) = parse(input)
val allDistances = times.mapIndexed { idx, t ->
distancesPerTime(t).count { d -> d > records[idx] }
}
return allDistances.product()
}
fun distancesPerTime(t: Int): List<Int> {
return List(t + 1) {
(t - it) * it
}
}
fun part2(input: List<String>): Int {
val (time, distance) = parse2(input)
return (0..time + 1).count { t ->
(time - t) * t > distance
}
}
fun part2Optimized(input: List<String>): Long {
val (time, distance) = parse2(input)
val firstWin = (0..time + 1).first { t ->
(time - t) * t > distance
}
val lastWin = (time + 1 downTo 0).first { t ->
(time - t) * t > distance
}
return lastWin - firstWin + 1
}
fun parse2(input: List<String>): Pair<Long, Long> {
val time = input[0].dropWhile { !it.isDigit() }.replace(" ", "").toLong()
val distance = input[1].dropWhile { !it.isDigit() }.replace(" ", "").toLong()
return time to distance
}
// distance: D = (T - t) * t
// -t² + Tt - D = 0
// t = (-T ± sqrt(T² - 4D)) / -2
fun part2Optimized2(input: List<String>): Long {
val (time, distance) = parse2(input)
val root = sqrt(time * time - 4 * distance.toDouble())
val t1 = (-time + root) / -2
val t2 = (-time - root) / -2
return t2.toLong() - t1.toLong()
}
}
fun main() {
val testInput = """
Time: 7 15 30
Distance: 9 40 200
""".trimIndent().split("\n")
println("------Tests------")
println(Day06.part1(testInput))
println(Day06.part2(testInput))
println(Day06.part2Optimized(testInput))
println(Day06.part2Optimized2(testInput))
println("------Real------")
val input = readInput(2023, 6)
println("Part 1 result: ${Day06.part1(input)}")
println("Part 2 result: ${Day06.part2(input)}")
println("Part 2 result: ${Day06.part2Optimized(input)}")
println("Part 2 result: ${Day06.part2Optimized2(input)}")
timingStatistics { Day06.part1(input) }
timingStatistics { Day06.part2(input) }
timingStatistics { Day06.part2Optimized(input) }
timingStatistics { Day06.part2Optimized2(input) }
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 2,766 | advent-of-code | Apache License 2.0 |
src/day6/d6_2.kt | svorcmar | 720,683,913 | false | {"Kotlin": 49110} | fun main() {
val input = ""
val grid = Array(1000) { Array(1000) { 0 } }
val instructions = parseInstructions(input)
instructions.forEach {
for (i in Math.min(it.p0.first, it.p1.first) .. Math.max(it.p0.first, it.p1.first)) {
for (j in Math.min(it.p0.second, it.p1.second) .. Math.max(it.p0.second, it.p1.second)) {
grid[i][j] = when(it.command) {
Command.ON -> grid[i][j] + 1
Command.OFF -> Math.max(grid[i][j] - 1, 0)
Command.TOGGLE -> grid[i][j] + 2
}
}
}
}
println(grid.fold(0) { acc0, it -> acc0 + it.fold(0) { acc, b -> acc + b } })
}
enum class Command { ON, OFF, TOGGLE }
data class Instruction(val p0: Pair<Int, Int>, val p1: Pair<Int, Int>, val command: Command)
fun parseInstructions(input: String): List<Instruction> {
return input.lines().map { line ->
val tokens = line.split(" ")
val command = when(tokens[1]) {
"on" -> Command.ON
"off" -> Command.OFF
else -> Command.TOGGLE
}
val delta = if (command == Command.TOGGLE) -1 else 0
val p0 = parseCoordinate(tokens[2 + delta])
val p1 = parseCoordinate(tokens[4 + delta])
Instruction(p0, p1, command)
}
}
fun parseCoordinate(input: String): Pair<Int, Int> {
return input.split(",").map { it.toInt() }.let { it[0] to it [1] }
}
| 0 | Kotlin | 0 | 0 | cb097b59295b2ec76cc0845ee6674f1683c3c91f | 1,330 | aoc2015 | MIT License |
src/Day05.kt | yalematta | 572,668,122 | false | {"Kotlin": 8442} | fun main() {
fun part1(input: List<String>): String {
val parse = input.map { it.split("\n") }.flatten()
val emptySpaceIndex = parse.indexOfFirst { it.isBlank() }
val padding = parse[emptySpaceIndex - 1].length + 1
val crates = parse.slice(0 until emptySpaceIndex - 1)
val paddedCrates = crates.map { it.padEnd(padding, ' ').chunked(4) }.reversed()
val parsedCrates = parseCrates(paddedCrates)
val moves = parse.slice(emptySpaceIndex + 1 until parse.size)
val initialStack = List(parsedCrates.size) { index -> index + 1 to parsedCrates[index] }.toMap()
moves.map { move ->
val instruction = instructionParser(move)
moveCrate(instruction, initialStack)
}
return initialStack.values.joinToString("") { it.last() }
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
data class Instruction(val move: Int, val from: Int, val to: Int)
fun instructionParser(input: String): Instruction {
val parse = input.split(" ").chunked(2).associate { it.first() to it.last().toInt() }
return Instruction(move = parse["move"]!!, from = parse["from"]!!, to = parse["to"]!!)
}
fun parseCrates(input: List<List<String>>): List<MutableList<String>> {
val crates = List(input[0].size) { mutableListOf<String>() }
for (i in input[0].indices) {
for (value in input) {
if (value[i].isNotBlank()) crates[i].add(value[i].filter { it.isLetter() })
}
}
return crates
}
fun moveCrate(instruction: Instruction, crates: Map<Int, MutableList<String>>) {
repeat(instruction.move) {
val topCrate = crates[instruction.from]?.last()
crates[instruction.from]?.removeLast()
if (topCrate != null) {
crates[instruction.to]?.add(topCrate)
}
}
}
| 0 | Kotlin | 0 | 0 | 2b43681cc2bd02e4838b7ad1ba04ff73c0422a73 | 2,098 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/graph/core/AllPairsShortestPath.kt | yx-z | 106,589,674 | false | null | package graph.core
import util.*
import java.lang.Math.ceil
import kotlin.math.log
// given a weighted graph with either negative, zero, or positive edges G = (V, E)
// report a table dist[u, v]: the shortest distance between u and v in G
// our first solution is just run Bellman-Ford's Algorithm for every vertex
fun <V> WeightedGraph<V, Int>.bellmanFordAll()
: Map<Vertex<V>, Map<Vertex<V>, Int>> {
val ret = HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>()
vertices.forEach { u ->
ret[u] = HashMap()
vertices.forEach { v ->
ret[u, v] = bellmanFord(u, v)
}
}
return ret
}
// time complexity: O(V^2E)
// now consider dist(i, u, v) which is the length of the shortest path from
// u to v with at most i edges
// we have dist(i, u, v) = min{ dist(i / 2, u, w) + dist(i / 2, w, v) : w in V }
// and then we can report any of dist(i, u, v), i >= V - 1
// for simplicity, let us compute dist(2^k, u, v) : 2^k >= V - 1
// so that i / 2 is always a power of 2
fun <V> WeightedGraph<V, Int>.allPairsShortestPathDivideAndConquer()
: Map<Vertex<V>, Map<Vertex<V>, Int>> {
val V = vertices.size
val k = ceil(log(V.toDouble(), 2.0)).toInt()
val dist = Array(k + 1) { HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>() }
dist.forEach { map ->
vertices.forEach { u ->
map[u] = HashMap()
vertices.forEach { v ->
map[u, v] = when {
u === v -> 0
getEdgesOf(u)
.any { (s, e) -> s === v || e === v } -> {
getEdgesOf(u)
.filter { (s, e) -> s === v || e === v }
.map { it.weight!! }
.first()
}
else -> INF
}
}
}
}
for (i in 1..k) {
vertices.forEach { u ->
vertices.forEach { v ->
dist[i][u, v] = vertices.map { w ->
dist[i - 1][u, w]!! + dist[i - 1][w, v]!!
}.min() ?: INF
}
}
}
return dist.last()
}
// time complexity: O(V^3 log V)
// warshall's dp
// given G = (V, E), number all vertices from 1 to |V|
// consider dp[1..V, 1..V, 0 until V] : dp[u, v, r] is the shortest distance from
// u to v with intermediate vertices having index at most r
// for example dp[u, v, 0] is the shortest distance from u to v with NO
// intermediate vertices (since no vertex has an index <= 0)
fun <V> WeightedGraph<V, Int>.warshallDP(): Map<Vertex<V>, Map<Vertex<V>, Int>> {
val vArr = vertices.toOneArray()
val V = vertices.size
val dp = OneArray(V) { OneArray(V) { Array(V) { 0 } } }
// space complexity: O(V^3)
for (u in 1..V) {
for (v in 1..V) {
dp[u, v][0] = if (u == v) {
0
} else {
getEdgesOf(vArr[u])
.firstOrNull { (_, e) -> e === vArr[v] }?.weight ?: INF
}
}
}
for (r in 1 until V) {
for (u in 1..V) {
for (v in 1..V) {
dp[u, v][r] = min(dp[u, v][r - 1], dp[u, r][r - 1] + dp[r, v][r - 1])
}
}
}
val dist = HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>()
for (u in 1..V) {
dist[vArr[u]] = HashMap()
for (v in 1..V) {
dist[vArr[u], vArr[v]] = dp[u, v][V - 1]
}
}
return dist
}
// time complexity: O(V^3)
// but we can do better as we have done from bellmanFordDP to bellmanFord!
// warshall's final algorithm
fun <V> WeightedGraph<V, Int>.warshall(): Map<Vertex<V>, Map<Vertex<V>, Int>> {
val dist = HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>()
vertices.forEach { u ->
dist[u] = HashMap()
vertices.forEach { v ->
dist[u, v] = if (u === v) {
0
} else {
getEdgesOf(u)
.firstOrNull { (_, e) -> e === v }?.weight ?: INF
}
}
}
vertices.forEach { r ->
vertices.forEach { u ->
vertices.forEach { v ->
dist[u, v] = min(dist[u, v]!!, dist[u, r]!! + dist[r, v]!!)
}
}
}
return dist
}
// time complexity: O(V^3)
fun main(args: Array<String>) {
val vertices = (1..5).map { Vertex(it) }
val edges = setOf(
WeightedEdge(vertices[0], vertices[1], true, 1),
WeightedEdge(vertices[0], vertices[3], true, 3),
WeightedEdge(vertices[1], vertices[2], true, 1),
WeightedEdge(vertices[2], vertices[3], true, 2),
WeightedEdge(vertices[2], vertices[4], true, 3),
WeightedEdge(vertices[3], vertices[4], true, 1))
val graph = WeightedGraph(vertices, edges)
println(graph.bellmanFordAll())
println(graph.allPairsShortestPathDivideAndConquer())
println(graph.warshallDP())
println(graph.warshall())
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 4,217 | AlgoKt | MIT License |
src/Day07/day07.kt | NST-d | 573,224,214 | false | null | import utils.*
fun main() {
data class FileTree(val name: String,
var size: Int = 0,
val children: MutableList<FileTree> = emptyList<FileTree>().toMutableList(),
val parent: FileTree? = null,
val directory : Boolean= true){
fun addSize(value: Int){
size += value
parent?.addSize(value)
}
fun addChild(name: String): FileTree {
require(directory)
val child = FileTree(name = name, parent = this)
children.add(child)
return child
}
fun addFile(name: String, size: Int){
val child = FileTree(name = name, size = size, parent = this, directory = false)
addSize(size)
children.add(child)
}
fun getSumOfSmallDirs(): Int{
var sum = 0
if(directory && size <= 100000){
sum = size
}
sum += children.filter { it.directory }.sumOf { it.getSumOfSmallDirs()}
return sum
}
fun findSmallestForDeletion(needed: Int, currentSmallest: Int): Int{
var smallest = currentSmallest
if(size < needed){
return currentSmallest
}else {
return children.filter { it.directory }.minOfOrNull { it.findSmallestForDeletion(needed, size) }?: size
}
}
override fun toString() :String{
return if(directory) {
"$name $size\n" + children.joinToString("\n", "[", "]")
} else{
"File $name $size"
}
}
}
fun parseCommands(input: String): FileTree{
val root = FileTree(name = "/" )
var currentDir = root
val commands = input.split('$').toMutableList()
commands.removeFirst()
for (command in commands){
val lines = command.split("\n")
//println(lines[0])
when{
lines[0] == " cd /" -> currentDir = root
lines[0] == " cd .." -> currentDir = currentDir.parent!!
lines[0].substring(1,3) == "cd" -> {
val dirName = lines[0].substring(4)
currentDir = currentDir.children.find { it.name == dirName } ?: currentDir.addChild(dirName)
}
lines[0] == " ls" -> {
for (i in 1 until lines.size){
if(lines[i].isBlank()){
continue
}
if (lines[i].substring(0,3)=="dir"){
val dirName = lines[i].substring(4)
if(currentDir.children.count { it.name == dirName } == 0) {
currentDir.addChild(dirName)
}
}else{
val split = lines[i].split(" ")
val size = split[0].toInt()
val name = split[1]
if(currentDir.children.count { it.name == name } == 0) {
currentDir.addFile(name, size)
}
}
}
}
}
}
return root
}
fun part1(input: String): Int{
val root = parseCommands(input)
return root.getSumOfSmallDirs()
}
fun part2(input:String) : Int{
val root = parseCommands(input)
val max = 70000000
val needed = 30000000
return root.findSmallestForDeletion(needed - (max - root.size), max )
}
val test = readTestString("Day07").trimIndent()
val input = readInputString("Day07").trimIndent()
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c4913b488b8a42c4d7dad94733d35711a9c98992 | 3,876 | aoc22 | Apache License 2.0 |
2022/main/day_16/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_16_2022
import java.io.File
val parsed = File("2022/inputs/Day_16.txt").readLines().map(Valve::from)
val valves = parsed.associateBy { it.id }
val shortestPaths =
floydWarshall(parsed.associate { it.id to it.neighborIds.associateWith { 1 }.toMutableMap() }.toMutableMap())
var score = 0
var totalTime = 30
fun dfs(currScore: Int, currentValve: String, visited: Set<String>, time: Int, part2: Boolean = false) {
score = maxOf(score, currScore)
for ((valve, dist) in shortestPaths[currentValve]!!) {
if (!visited.contains(valve) && time + dist + 1 < totalTime) {
dfs(
currScore + (totalTime - time - dist - 1) * valves[valve]?.flowRate!!,
valve,
visited.union(listOf(valve)),
time + dist + 1,
part2
)
}
}
if(part2)
dfs(currScore, "AA", visited, 0, false)
}
fun floydWarshall(shortestPaths: MutableMap<String, MutableMap<String, Int>>): MutableMap<String, MutableMap<String, Int>> {
for (k in shortestPaths.keys) {
for (i in shortestPaths.keys) {
for (j in shortestPaths.keys) {
val ik = shortestPaths[i]?.get(k) ?: 9999
val kj = shortestPaths[k]?.get(j) ?: 9999
val ij = shortestPaths[i]?.get(j) ?: 9999
if (ik + kj < ij)
shortestPaths[i]?.set(j, ik + kj)
}
}
}
//remove all paths that lead to a valve with rate 0
shortestPaths.values.forEach {
it.keys.map { key -> if (valves[key]?.flowRate == 0) key else "" }
.forEach { toRemove -> if (toRemove != "") it.remove(toRemove) }
}
return shortestPaths
}
data class Valve(val id: String, val flowRate: Int, val neighborIds: List<String>) {
companion object {
fun from(line: String): Valve {
val (name, rate) = line.split("; ")[0].split(" ").let { it[1] to it[4].split("=")[1].toInt() }
val neighbors = line.split(", ").toMutableList()
neighbors[0] = neighbors[0].takeLast(2)
return Valve(name, rate, neighbors)
}
}
}
fun part1() {
dfs(0, "AA", emptySet(), 0)
print("The pressure that is able to be relieved is $score")
}
fun part2() {
totalTime = 26
score = 0
dfs(0, "AA", emptySet(), 0, true)
print("The pressure that is able to be relieved is $score")
}
fun main(){
val inputFile =
print("\n----- Part 1 -----\n")
part1()
print("\n----- Part 2 -----\n")
part2()
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 2,562 | AdventofCode | MIT License |
src/main/kotlin/be/seppevolkaerts/day11/Day11.kt | Cybermaxke | 727,453,020 | false | {"Kotlin": 35118} | package be.seppevolkaerts.day11
import kotlin.math.max
import kotlin.math.min
enum class Tile {
Galaxy,
Empty,
}
data class Pos(val x: Int, val y: Int)
class Universe(
private val values: List<List<Tile>>,
private val rowScales: List<Long> = List(values.size) { 1 },
private val colScales: List<Long> = List(values.first().size) { 1 },
) {
fun colScale(x: Int) = colScales[x]
fun rowScale(y: Int) = rowScales[y]
operator fun get(x: Int, y: Int) = values[y][x]
val cols: Int
get() = colScales.size
val rows: Int
get() = rowScales.size
fun expand(times: Int): Universe {
val rowScales = rowScales.mapIndexed { y, scale ->
if (values[y].all { tile -> tile == Tile.Empty }) scale * times else scale
}
val colScales = colScales.mapIndexed { x, scale ->
if ((0..<rows).all { y -> get(x, y) == Tile.Empty }) scale * times else scale
}
return Universe(values, rowScales, colScales)
}
}
fun Iterable<String>.parseUniverse(): Universe =
Universe(map { line -> line.map { char -> if (char == '#') Tile.Galaxy else Tile.Empty } })
fun Universe.findGalaxies(): List<Pos> {
val galaxies = mutableListOf<Pos>()
for (y in 0..<rows) {
for (x in 0..<cols) {
if (get(x, y) == Tile.Galaxy) {
galaxies.add(Pos(x, y))
}
}
}
return galaxies
}
fun Universe.sumOfShortestPaths(): Long {
val galaxies = findGalaxies()
return galaxies.flatMapIndexed { index, a -> galaxies.asSequence().drop(index + 1).map { b -> a to b } }
.sumOf { (a, b) ->
val cols = (min(a.x, b.x)..<max(a.x, b.x)).sumOf(::colScale)
val rows = (min(a.y, b.y)..<max(a.y, b.y)).sumOf(::rowScale)
cols + rows
}
}
| 0 | Kotlin | 0 | 1 | 56ed086f8493b9f5ff1b688e2f128c69e3e1962c | 1,698 | advent-2023 | MIT License |
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day12.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2022
import java.util.PriorityQueue
import kotlin.math.abs
data class Point(
val row: Int,
val col: Int,
)
data class Graph(val edges: Map<Point, List<Point>>) {
fun shortestPath(start: Point, destination: Point): Int {
val costSoFar = mutableMapOf(start to 0)
val cameFrom = mutableMapOf<Point, Point>()
val open = PriorityQueue<Pair<Point, Int>> { o1, o2 ->
costSoFar[o1.first]?.compareTo(costSoFar[o2.first] ?: 0) ?: 0
}
.apply { add(start to 0) }
while (open.isNotEmpty()) {
open.remove().let { (current, _) ->
if (current == destination) return costSoFar[current] ?: 0
edges[current]?.forEach { next ->
val newCost = costSoFar[current]!! + 1
if (next !in costSoFar || newCost < costSoFar[next]!!) {
costSoFar[next] = newCost
open.add(next to newCost + heuristic(next, destination))
cameFrom[next] = current
}
}
}
}
return Int.MAX_VALUE
}
private fun heuristic(point: Point, destination: Point): Int =
abs(destination.row - point.row) + abs(destination.col - point.col)
}
fun main() {
fun Char.isNotFurtherThanOneFrom(other: Char) = until(other).count() <= 1
fun Char.canStepTo(other: Char) = when (this) {
'S' -> 'a'.isNotFurtherThanOneFrom(other)
'E' -> true
else -> when (other) {
'S' -> isNotFurtherThanOneFrom('a')
'E' -> isNotFurtherThanOneFrom('z')
else -> isNotFurtherThanOneFrom(other)
}
}
fun List<String>.findNeighbors(row: Int, col: Int): List<Point> = (row - 1..row + 1)
.filter { rowIndex -> rowIndex in (0 until this.size) }
.map { rowIndex ->
(col - 1..col + 1)
.filter { colIndex ->
colIndex in (0 until this.first().length)
&& ((colIndex != col && rowIndex == row) || (colIndex == col && rowIndex != row))
&& this[row][col].canStepTo(this[rowIndex][colIndex])
}
.map { colIndex -> Point(rowIndex, colIndex) }
}
.flatten()
fun List<String>.toGraph() = mapIndexed { rowIndex, cols ->
cols.mapIndexed { colIndex, col -> Point(rowIndex, colIndex) }
}
.flatten()
.fold(mutableMapOf<Point, List<Point>>()) { acc, point ->
acc.apply { putAll(this@toGraph.findNeighbors(point.row, point.col).groupBy { point }) }
}.let { Graph(it) }
fun List<String>.posOfUniqueChar(c: Char) = asSequence()
.indexOfFirst { it.contains(c) }
.let { it to this[it].indexOf(c) }
fun List<String>.startingPoints(): List<Point> = asSequence()
.flatMapIndexed { index, s -> s.indices.filter { s[it] == 'a' }.map { index to it } }
.map { Point(it.first, it.second) }
.toList()
fun List<String>.startingPos(): Pair<Int, Int> = posOfUniqueChar('S')
fun List<String>.destinationPos(): Pair<Int, Int> = posOfUniqueChar('E')
fun List<String>.startingPoint(): Point = startingPos().let { Point(it.first, it.second) }
fun List<String>.destinationPoint(): Point = destinationPos().let { Point(it.first, it.second) }
fun part1(input: List<String>): Int = input.toGraph()
.run {
shortestPath(input.startingPoint(), input.destinationPoint())
}
fun part2(input: List<String>): Int = input.toGraph()
.run {
input.startingPoints().plus(input.startingPoint())
.minOfOrNull { shortestPath(it, input.destinationPoint()) } ?: 0
}
val testInput = readInputLines("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInputLines("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 4,035 | advent-of-code | Apache License 2.0 |
2022/src/main/kotlin/com/github/akowal/aoc/Day13.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
class Day13 {
private val messages = inputFile("day13").readLines()
.filter { it.isNotEmpty() }
.map { decode(it) }
fun solvePart1(): Int {
return messages
.windowed(2, 2)
.map { it[0] to it[1] }
.mapIndexed { i, (left, right) ->
if (compare(left, right) < 0) i + 1 else 0
}
.sum()
}
fun solvePart2(): Int {
val div1 = listOf(listOf(2))
val div2 = listOf(listOf(6))
return messages.toMutableList()
.apply {
add(div1)
add(div2)
}
.sortedWith(::compare)
.let {
it.indexOf(div1).inc() * it.indexOf(div2).inc()
}
}
private fun compare(left: Any?, right: Any?): Int {
return if (left is Int && right is Int) {
left.compareTo(right)
} else {
val ll = if (left is List<*>) left else listOf(left)
val rl = if (right is List<*>) right else listOf(right)
ll.zip(rl) { l, r -> compare(l, r) }.firstOrNull { it != 0 } ?: ll.size.compareTo(rl.size)
}
}
private fun decode(s: String): List<Any> {
var last = emptyList<Any>()
val q = ArrayDeque<MutableList<Any>>()
var i = 0
while (i < s.length) {
when (s[i]) {
'[' -> q.add(mutableListOf())
']' -> last = q.removeLast().also { q.lastOrNull()?.add(it) }
',' -> {}
else -> {
val j = s.indexOfAny("],".toCharArray(), i)
q.last().add(s.substring(i, j).toInt())
i += j - i - 1
}
}
i++
}
return last
}
}
fun main() {
val solution = Day13()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 1,947 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/day09/Day09.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day09
import day09.Direction.Companion.toDirection
import readInput
import kotlin.math.abs
fun main() {
val testInput = readInput("day09/test")
val motions = testInput.mapNotNull {
val direction = it.split(" ")[0].toDirection() ?: return@mapNotNull null
val count = it.split(" ")[1].toInt()
Motion(direction, count)
}
println(solution(motions, 2))
println(solution(motions, 10))
}
private fun solution(motions: List<Motion>, length: Int): Int {
val ropePosition = Array(length) { Position(0, 0) }
val tailPositionSet = mutableSetOf<Position>().also {
it.add(ropePosition.last())
}
motions.forEach { motion ->
var count = 0
while (count < motion.step) {
val headPosition = ropePosition[0]
ropePosition[0] = when (motion.direction) {
Direction.UP -> Position(headPosition.x, headPosition.y + 1)
Direction.DOWN -> Position(headPosition.x, headPosition.y - 1)
Direction.RIGHT -> Position(headPosition.x + 1, headPosition.y)
Direction.LEFT -> Position(headPosition.x - 1, headPosition.y)
}
var index = 1
while (index < length) {
val previousPosition = ropePosition[index - 1]
val currentPosition = ropePosition[index]
val diffX = previousPosition.x - currentPosition.x
val diffY = previousPosition.y - currentPosition.y
if (abs(diffX) + abs(diffY) > 2) {
ropePosition[index] =
Position(
currentPosition.x + if (diffX > 0) 1 else -1,
currentPosition.y + if (diffY > 0) 1 else -1
)
} else {
when {
abs(diffX) == 2 -> {
ropePosition[index] =
Position(currentPosition.x + if (diffX > 0) 1 else -1, currentPosition.y)
}
abs(diffY) == 2 -> {
ropePosition[index] =
Position(currentPosition.x, currentPosition.y + if (diffY > 0) 1 else -1)
}
else -> Unit
}
}
index++
}
tailPositionSet.add(ropePosition.last())
count++
}
}
return tailPositionSet.size
}
private data class Position(val x: Int, val y: Int)
private data class Motion(val direction: Direction, val step: Int)
private enum class Direction {
UP,
DOWN,
LEFT,
RIGHT;
companion object {
fun String.toDirection(): Direction? =
when (this) {
"U" -> UP
"D" -> DOWN
"L" -> LEFT
"R" -> RIGHT
else -> null
}
}
}
| 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 2,994 | advent-of-code-2022 | Apache License 2.0 |
2022/src/day11/day11.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day11
import GREEN
import RESET
import printTimeMillis
import readInput
data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: (Long) -> Boolean,
val trueMonkey: Int,
val falseMonkey: Int,
val divisor: Long,
var inspect: Int = 0
) {
fun add(new: Long) { items.add(new) }
fun inspect() { inspect += 1 }
}
fun parseMonkeys(input: List<String>) = input.windowed(6, 6) {
val startingItems = it[1].split(":")[1].trim().split(", ").map { it.toLong() }.toMutableList()
val operation = it[2].split("=")[1].trim().let {
when {
it == "old * old" -> {
{ o: Long -> o * o }
}
it.startsWith("old *") -> {
{ o: Long -> o * it.split(" ").last().toLong() }
}
it.startsWith("old +") -> {
{ o: Long -> o + it.split(" ").last().toLong() }
}
else -> throw IllegalStateException("Wrong Operation")
}
}
val divisor = it[3].split(" ").last().toLong()
val test = { e: Long -> e.mod(divisor) == 0L }
Monkey(
startingItems,
operation,
test,
trueMonkey = it[4].split(" ").last().toInt(),
falseMonkey = it[5].split(" ").last().toInt(),
divisor = divisor
)
}
fun playRounds(
monkeys: List<Monkey>,
rounds: Int = 1,
divideWorry: Boolean = true
) {
val reduce = monkeys.fold(1L) { acc, v -> acc * v.divisor }
repeat(rounds) {
monkeys.forEach {
while (it.items.isNotEmpty()) {
val item = it.items.removeFirst()
val examine = it.operation(item).let {
if (divideWorry) it / 3L else it
}.let {
// get the modulo of all divisors multiplied with each others
it % reduce
}
it.inspect()
if (it.test(examine)) {
monkeys[it.trueMonkey].add(examine)
} else {
monkeys[it.falseMonkey].add(examine)
}
}
}
}
}
fun part1(input: List<String>): Long {
val monkeys = parseMonkeys(input)
playRounds(monkeys, 20)
return monkeys.map { it.inspect.toLong() }.sortedDescending().let { it[0] * it[1] }
}
fun part2(input: List<String>): Long {
val monkeys = parseMonkeys(input)
playRounds(monkeys, 10000, false)
return monkeys.map { it.inspect.toLong() }.sortedDescending().let { it[0] * it[1] }
}
fun main() {
val testInput = readInput("day11_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day11.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 2,992 | advent-of-code | Apache License 2.0 |
src/day08/Day08.kt | martinhrvn | 724,678,473 | false | {"Kotlin": 27307, "Jupyter Notebook": 1336} | package day08
import AdventDay
import findLCM
import readInput
data class HauntedWasteland(
val path: Map<String, Pair<String, String>>,
val instructions: List<String>
) {
private fun getInstructions() = generateSequence { instructions }.flatten()
fun getPathLength(start: String, endCondition: (str: String) -> Boolean): Int {
return getInstructions()
.scan(start) { acc, instr ->
val (left, right) =
path[acc] ?: throw NoSuchElementException("No path exists for key $acc")
if (instr == "L") {
left
} else {
right
}
}
.takeWhile { endCondition(it) }
.count()
}
fun findGhostPaths(): Long {
val startPaths = path.keys.filter { it.endsWith("A") }
val lengths = startPaths.map { path -> getPathLength(path) { !it.endsWith("Z") }.toLong() }
return lengths.reduce(::findLCM)
}
companion object {
fun parse(input: List<String>): HauntedWasteland {
val instructions = input.first().split("").filter { it.isNotEmpty() }
val path =
input
.drop(2)
.map { line ->
val result =
"([A-Z0-9]{3}) = \\(([A-Z0-9]{3}), ([A-Z0-9]{3})\\)".toRegex().find(line)
val (from, left, right) = result!!.groupValues
from to (left to right)
}
.toMap()
return HauntedWasteland(path, instructions)
}
}
}
class Day08(private val input: List<String>) : AdventDay {
override fun part1(): Long {
return HauntedWasteland.parse(input).getPathLength("AAA") { it != "ZZZ" }.toLong()
}
override fun part2(): Long {
return HauntedWasteland.parse(input).findGhostPaths()
}
}
fun main() {
val day08 = Day08(readInput("day08/Day08"))
println(day08.part1())
println(day08.part2())
}
| 0 | Kotlin | 0 | 0 | 59119fba430700e7e2f8379a7f8ecd3d6a975ab8 | 1,879 | advent-of-code-2023-kotlin | Apache License 2.0 |
src/Day04.kt | alexaldev | 573,318,666 | false | {"Kotlin": 10807} | fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.split(",")
.map { range -> range.split("-") } }
.map { it.hasARangeIncludedInOther() }
.count { it }
}
fun part2(input: List<String>): Int {
return input
.map {
it.split(",")
.map { range -> range.split("-") }
}.count { it.overlaps() }
}
val testInput = readInput("In04.txt")
print(part2(testInput))
}
fun List<List<String>>.hasARangeIncludedInOther(): Boolean {
val thisToInt = this.map { it.map { s -> s.toInt() } }
val firstRange = thisToInt.first().first()..thisToInt.first()[1]
val secondRange = thisToInt[1].first()..thisToInt[1][1]
val firstInSecond = (firstRange.first >= secondRange.first) && (firstRange.last <= secondRange.last)
val secondInFirst = (firstRange.first <= secondRange.first) && (firstRange.last >= secondRange.last)
return firstInSecond || secondInFirst
}
fun List<List<String>>.overlaps(): Boolean {
val thisToInt = this.map { it.map { s -> s.toInt() } }
val firstRange = thisToInt.first().first()..thisToInt.first()[1]
val secondRange = thisToInt[1].first()..thisToInt[1][1]
return firstRange.overlaps(secondRange)
}
fun IntRange.overlaps(other: IntRange): Boolean {
return this.any { it in other }
}
| 0 | Kotlin | 0 | 0 | 5abf10b2947e1c6379d179a48f1bdcc719e7062b | 1,406 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day02.kt | akijowski | 574,262,746 | false | {"Kotlin": 56887, "Shell": 101} | data class Round(val opponent: String, val you: String) {
// A, X => Rock
// B, Y => Paper
// C, Z => Scissors
// value = winner
private val defeats = mapOf(
"A" to "Y",
"B" to "Z",
"C" to "X"
)
private val draws = mapOf(
"A" to "X",
"B" to "Y",
"C" to "Z"
)
private val scores = mapOf(
"X" to 1,
"Y" to 2,
"Z" to 3
)
fun score(): Int {
return when (you) {
//win
defeats[opponent] -> 6 + scores[you]!!
draws[opponent] -> 3 + scores[you]!!
else -> 0 + scores[you]!!
}
}
}
data class RoundTwo(val opponent: String, val outcome: String) {
// A Rock
// B Paper
// C Scissor
private val wins = mapOf(
"A" to "B",
"B" to "C",
"C" to "A"
)
private val loses = mapOf(
"A" to "C",
"B" to "A",
"C" to "B"
)
private val scores = mapOf(
"A" to 1,
"B" to 2,
"C" to 3,
)
fun score(): Int {
return when (outcome) {
// lose
"X" -> 0 + scores[loses[opponent]!!]!!
// draw
"Y" -> 3 + scores[opponent]!!
// win
else -> 6 + scores[wins[opponent]]!!
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.map { it.split(" ") }
.map { Round(it.first(), it.last()) }
.sumOf { it.score() }
}
fun part2(input: List<String>): Int {
return input.map { it.split(" ") }
.map { RoundTwo(it.first(), it.last())}
.sumOf { it.score() }
}
// 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 | 1 | 0 | 84d86a4bbaee40de72243c25b57e8eaf1d88e6d1 | 1,977 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | tigerxy | 575,114,927 | false | {"Kotlin": 21255} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { round ->
val other = round.first().map()
val me = round.last().map()
val result = when {
other == me -> 3
me == Rock && other == Scissors -> 6
me == Scissors && other == Paper -> 6
me == Paper && other == Rock -> 6
else -> 0
}
me + result
}
}
fun part2(input: List<String>): Int {
return input.sumOf { round ->
val other = round.first().map()
val action = round.last().map()
val result = when {
action == DRAW -> other
other == Scissors && action == LOSE -> Paper
other == Paper && action == LOSE -> Rock
other == Rock && action == LOSE -> Scissors
other == Scissors && action == WIN -> Rock
other == Paper && action == WIN -> Scissors
other == Rock && action == WIN -> Paper
else -> 0
}
result + (action - 1) * 3
}
}
val day = "02"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
println("part1_test=${part1(testInput)}")
println("part2_test=${part2(testInput)}")
val input = readInput("Day$day")
println("part1=${part1(input)}")
println("part2=${part2(input)}")
}
private const val Rock = 1
private const val Paper = 2
private const val Scissors = 3
private const val LOSE = 1
private const val DRAW = 2
private const val WIN = 3
private fun Char.map() = when (this) {
'A' -> Rock
'B' -> Paper
'C' -> Scissors
'X' -> Rock
'Y' -> Paper
'Z' -> Scissors
else -> 0
}
| 0 | Kotlin | 0 | 1 | d516a3b8516a37fbb261a551cffe44b939f81146 | 1,848 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day08.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | data class VisibilityStatus(
val visible: Boolean,
val viewingDistance: Int
)
fun main() {
fun calculateVisibilityStatus(treeHeight: Int, rowRange: Iterable<Int>, colRange: Iterable<Int>, grid: List<List<Int>>): VisibilityStatus {
var viewingDistance = 0
for (i in rowRange) {
for (j in colRange) {
viewingDistance += 1
if (grid[i][j] >= treeHeight) {
return VisibilityStatus(false, viewingDistance)
}
}
}
return VisibilityStatus(true, viewingDistance)
}
fun calculateVisibilityStatuses(treeRow: Int, treeCol: Int, grid: List<List<Int>>): List<VisibilityStatus> {
return listOf(calculateVisibilityStatus(grid[treeRow][treeCol], treeRow - 1 downTo 0, (treeCol..treeCol), grid),
calculateVisibilityStatus(grid[treeRow][treeCol], treeRow + 1 until grid.size, (treeCol..treeCol), grid),
calculateVisibilityStatus(grid[treeRow][treeCol], (treeRow..treeRow), treeCol - 1 downTo 0, grid),
calculateVisibilityStatus(grid[treeRow][treeCol], (treeRow..treeRow), treeCol + 1 until grid[treeRow].size, grid))
}
fun isVisible(treeRow: Int, treeCol: Int, grid: List<List<Int>>) =
calculateVisibilityStatuses(treeRow, treeCol, grid).any { it.visible }
fun calculateViewingDistance(treeRow: Int, treeCol: Int, grid: List<List<Int>>) =
calculateVisibilityStatuses(treeRow, treeCol, grid).fold(1) { acc, next -> acc * next.viewingDistance }
fun parseGrid(input: List<String>) = input.map { line -> line.toList().map { it.toString().toInt() } }
fun part1(input: List<String>): Int {
val grid = parseGrid(input)
var countVisible = grid.size * 2 + grid[0].size * 2 - 4
for (i in 1 until grid.size - 1) {
for (j in 1 until grid[i].size - 1) {
if (isVisible(i, j, grid)) {
countVisible += 1
}
}
}
return countVisible
}
fun part2(input: List<String>): Int {
val grid = parseGrid(input)
var maxViewingDistance = 0
for (i in 1 until grid.size - 1) {
for (j in 1 until grid[i].size - 1) {
val viewingDistance = calculateViewingDistance(i, j, grid)
if (viewingDistance > maxViewingDistance) {
maxViewingDistance = viewingDistance
}
}
}
return maxViewingDistance
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input)) // 1854
println(part2(input)) // 527340
}
| 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 2,760 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
src/Day12.kt | fasfsfgs | 573,562,215 | false | {"Kotlin": 52546} | fun main() {
fun part1(input: List<String>): Int {
val heightMap = HeightMap.fromInput(input)
val result = findPath(heightMap) { it == heightMap.start }
return result.getLength()
}
fun part2(input: List<String>): Int {
val heightMap = HeightMap.fromInput(input)
val result = findPath(heightMap) { heightMap.grid[it.first][it.second] == 0 }
return result.getLength()
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
// For this day, I watched AoC Kotlin live to learn any algorithm for searching.
}
fun findPath(heightMap: HeightMap, destinationFn: (Pair<Int, Int>) -> Boolean): Step {
val visitedGridSquares = mutableSetOf<Pair<Int, Int>>()
val queue = ArrayDeque<Step>()
visitedGridSquares.add(heightMap.target)
queue.add(Step(heightMap.target))
while (queue.isNotEmpty()) {
val step = queue.removeFirst()
if (destinationFn(step.coords)) return step
heightMap.getNeighbours(step.coords)
.filter { !visitedGridSquares.contains(it) }
.filter {
val stepHeight = heightMap.grid[step.coords.first][step.coords.second]
val neighboursHeight = heightMap.grid[it.first][it.second]
stepHeight <= neighboursHeight + 1
}
.map { Step(it, step) }
.forEach {
visitedGridSquares.add(it.coords)
queue.add(it)
}
}
error("No paths found.")
}
data class Step(val coords: Pair<Int, Int>, val previousStep: Step? = null) {
fun getLength(): Int {
var pathLength = 0
var runPath = this
while (runPath.previousStep != null) {
pathLength++
runPath = runPath.previousStep!!
}
return pathLength
}
}
data class HeightMap(val grid: List<List<Int>>, val start: Pair<Int, Int>, val target: Pair<Int, Int>) {
companion object {
fun fromInput(input: List<String>): HeightMap {
var start: Pair<Int, Int> = -1 to -1
var target: Pair<Int, Int> = -1 to -1
val grid = input
.mapIndexed { i, s ->
s.mapIndexed { j, c ->
when (c) {
'S' -> {
start = i to j
'a' - 'a'
}
'E' -> {
target = i to j
'z' - 'a'
}
else -> {
c - 'a'
}
}
}
}
return HeightMap(grid, start, target)
}
}
fun getNeighbours(spot: Pair<Int, Int>): List<Pair<Int, Int>> {
val maxI = grid.lastIndex
val maxJ = grid[0].lastIndex
val i = spot.first
val j = spot.second
val neighbours = mutableListOf<Pair<Int, Int>>()
if (i > 0) neighbours.add(i - 1 to j)
if (i < maxI) neighbours.add(i + 1 to j)
if (j > 0) neighbours.add(i to j - 1)
if (j < maxJ) neighbours.add(i to j + 1)
return neighbours.toList()
}
}
| 0 | Kotlin | 0 | 0 | 17cfd7ff4c1c48295021213e5a53cf09607b7144 | 3,455 | advent-of-code-2022 | Apache License 2.0 |
src/day05/Day05.kt | emartynov | 572,129,354 | false | {"Kotlin": 11347} | package day05
import readInput
private class Schema(
numberOfStacks: Int
) {
private val stacks: MutableList<List<Char>> = MutableList(numberOfStacks) { emptyList() }
operator fun get(indexFromOne: Int): List<Char> = stacks[indexFromOne - 1]
fun add(indexFromOne: Int, value: Char): Schema {
val updatedStack = listOf(value) + get(indexFromOne)
return updateStack(indexFromOne, updatedStack)
}
private fun updateStack(indexFromOne: Int, updatedStack: List<Char>): Schema {
stacks.add(indexFromOne - 1, updatedStack)
stacks.removeAt(indexFromOne)
return this
}
fun move(move: Move, transform: (List<Char>) -> List<Char> = { it }): Schema {
val fromStack = get(move.fromIndex)
val toStack = get(move.toIndex)
val elements = fromStack.subList(fromStack.size - move.numberOfCrates, fromStack.size)
return updateStack(
indexFromOne = move.fromIndex,
updatedStack = fromStack.dropLast(move.numberOfCrates)
).updateStack(
indexFromOne = move.toIndex,
updatedStack = toStack + transform.invoke(elements)
)
}
fun allLast(): String = stacks.map { it.lastOrNull()?.toString().orEmpty() }
.joinToString("")
}
private data class Move(
val numberOfCrates: Int,
val fromIndex: Int,
val toIndex: Int
)
fun main() {
fun readStacksAndMoves(input: List<String>): Pair<Schema, List<Move>> {
val schemaEndIndex = input.indexOf("")
val numberOfStacks = input[schemaEndIndex - 1].chunked(4).last().trim().toInt()
var initialSchema = Schema(numberOfStacks)
input.subList(0, schemaEndIndex - 1)
.map {
it.chunked(4)
.forEachIndexed { index, value ->
if (value.startsWith("[")) {
initialSchema = initialSchema.add(index + 1, value[1])
}
}
}
val moves = input.subList(schemaEndIndex + 1, input.size)
.map {
it.split(" ")
}.map { row ->
row.mapNotNull { it.toIntOrNull() }
}.map { numbers ->
Move(
numberOfCrates = numbers[0],
fromIndex = numbers[1],
toIndex = numbers[2]
)
}
return initialSchema to moves
}
fun playMoves(schema: Schema, moves: List<Move>, transform: (List<Char>) -> List<Char> = { it }): Schema =
moves.fold(schema) { accSchema, move -> accSchema.move(move, transform) }
fun part1(input: List<String>): String {
val data = readStacksAndMoves(input)
val updatedSchema = playMoves(data.first, data.second) { it.reversed() }
return updatedSchema.allLast()
}
fun part2(input: List<String>): String {
val data = readStacksAndMoves(input)
val updatedSchema = playMoves(data.first, data.second)
return updatedSchema.allLast()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day05/Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("day05/Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 8f3598cf29948fbf55feda585f613591c1ea4b42 | 3,375 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day07.kt | todynskyi | 573,152,718 | false | {"Kotlin": 47697} | fun main() {
fun cd(root: Folder, current: Folder, name: String): Folder = when (name) {
"/" -> root
".." -> {
if (current.name == "/") {
current
} else {
val parent = requireNotNull(current.parent)
parent.copy(child = parent.child.filter { it.folder && it.name != current.name } + parent.child.filter { !it.folder } + current)
}
}
else -> current.child.first { it.folder && it.name == current.name + name }.copy(parent = current)
}
fun calculate(root: Folder): Map<String, Long> {
val sizes = mutableMapOf<String, Long>()
fun compute(root: Folder): Int {
return if (root.folder) {
root.child.fold(0) { acc, folder ->
val size = compute(folder)
sizes[root.name] = sizes.getOrDefault(root.name, 0) + size
acc + size
}
} else {
root.size ?: 0
}
}
compute(root)
return sizes
}
fun parse(input: List<String>): Folder {
val root = Folder("/", folder = true)
var current = root
input.forEach { line ->
if (line.startsWith("\$ cd ")) {
current = cd(root, current, line.replace("\$ cd ", ""))
} else if (line == "\$ ls") {
//fileSystem.ls()
} else if (line.startsWith("dir ")) {
current = current.copy(
child = current.child + Folder(
name = current.name + line.replace("dir ", ""),
folder = true,
parent = current
)
)
} else {
val parts = line.split(" ")
current = current.copy(
child = current.child + Folder(
name = parts.last(),
folder = false,
size = parts.first().toInt()
)
)
}
}
while (current.name != "/") {
current = cd(root, current, "..")
}
return current
}
fun part1(input: List<String>): Long = calculate(parse(input)).values.filter { it < 100000 }.sum()
fun part2(input: List<String>): Long {
val sizes = calculate(parse(input))
val total = 70000000 - (sizes["/"] ?: 0)
return sizes.values.sorted().first { total + it >= 30000000 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
println(part2(testInput))
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
class FileSystem() {
private var current: Folder = Folder("/", true)
fun ls() {
}
fun cd(command: String) {
current = when (command) {
"/" -> current
".." -> requireNotNull(current.parent)
else -> current.child.first { it.folder && it.name == command }.copy(parent = current.parent)
}
}
fun dir(folderName: String) {
current = current.copy(child = current.child + Folder(folderName, true, parent = current))
}
fun create(fileName: String, size: Int) {
current = current.copy(child = current.child + Folder(fileName, false, size = size))
}
}
data class Folder(
val name: String,
val folder: Boolean,
val size: Int? = null,
val parent: Folder? = null,
val child: List<Folder> = emptyList()
)
| 0 | Kotlin | 0 | 0 | 5f9d9037544e0ac4d5f900f57458cc4155488f2a | 3,669 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/Day13/Day13.kt | AllePilli | 572,859,920 | false | {"Kotlin": 47397} | package Day13
import checkAndPrint
import measureAndPrintTimeMillis
import readInput
fun main() {
val printComparisons = false
val parser = Parser()
fun List<String>.prepareInputPart1() = (this + "").chunked(3)
.map { it.dropLast(1) }
.map { (left, right) -> left to right }
fun compare(left: List<Any>, right: List<Any>, prefix: String = "-"): Tri {
var pref = prefix
pref = " $pref"
for (i in left.indices) {
val leftItem = left[i]
val rightItem = right.getOrNull(i) ?: run {
if (printComparisons) println("$pref Right side ran out of items, so inputs are not in right order")
return Tri.False
}
if (printComparisons) println("$pref Compare $leftItem vs $rightItem")
if (leftItem is Int) {
if (rightItem is Int) {
if (leftItem < rightItem) {
if (printComparisons) println(" $pref Left side is smaller, so inputs are in right order")
return Tri.True
} else if (leftItem > rightItem) {
if (printComparisons) println(" $pref Right side is smaller, so inputs are not in right order")
return Tri.False
}
} else if (rightItem is List<*>) {
val compare = compare(listOf(leftItem), rightItem as List<Any>, " $pref")
if (compare == Tri.True || compare == Tri.False) return compare
}
} else {
if (rightItem is Int) {
val compare = compare(leftItem as List<Any>, listOf(rightItem), " $pref")
if (compare == Tri.True || compare == Tri.False) return compare
} else {
val compare = compare(leftItem as List<Any>, rightItem as List<Any>, " $pref")
if (compare == Tri.True || compare == Tri.False) return compare
}
}
}
return if (left.size == right.size) Tri.Equal else {
if (printComparisons) println("$pref Left side ran out of items, so inputs are in the right order")
Tri.True
}
}
fun compare(pair: Pair<List<Any>, List<Any>>): Boolean {
if (printComparisons) println("- Compare ${pair.first} vs ${pair.second}")
return compare(pair.first, pair.second).also { if (printComparisons) println() } == Tri.True
}
fun part1(input: List<Pair<String, String>>): Int = input
.map { (left, right) -> parser.parse(left) to parser.parse(right) }
.withIndex()
.filter { (_, pair) -> compare(pair) }
.sumOf { (idx, _) -> idx + 1 }
fun part2(input: List<String>): Int {
val dividers = listOf("[[2]]", "[[6]]")
val orderedPackets = input.toMutableList()
.also { it.addAll(dividers) }
.filterNot { it.isBlank() || it.isEmpty() }
.map(parser::parse)
.sortedWith { o1, o2 ->
when (compare(o1!!, o2!!)) {
Tri.True -> 1
Tri.False -> -1
Tri.Equal -> 0
}
}
.reversed()
.map(List<Any>::toString)
return dividers.fold(1) { acc, div -> acc * (orderedPackets.indexOf(div) + 1) }
}
val testInput = readInput("Day13_test")
check(part1(testInput.prepareInputPart1()) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
measureAndPrintTimeMillis {
checkAndPrint(part1(input.prepareInputPart1()), 5843)
}
measureAndPrintTimeMillis {
checkAndPrint(part2(input), 26289)
}
}
private enum class Tri {
True, False, Equal
}
private class Parser {
var idx = 0
var string = ""
val char: Char get() = string[idx]
fun parse(string: String): List<Any> {
idx = 0
this.string = string
return parseList()
}
private fun parseList(): List<Any> = buildList {
idx++
while (char != ']') {
when {
char.isDigit() -> add(parseNumber())
char == '[' -> add(parseList())
else -> idx++
}
}
idx++
}
private fun parseNumber(): Int = buildString {
while (char.isDigit()) {
append(char)
idx++
}
}.toInt()
} | 0 | Kotlin | 0 | 0 | 614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643 | 4,489 | AdventOfCode2022 | Apache License 2.0 |
src/Day13.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | class Signal private constructor(type: String, private val number: Int?, val list: List<Signal>?): Comparable<Signal> {
private val isNumber = type == "NUMBER"
private val isList = type == "LIST"
fun box() = ofList(listOf(this))
override fun toString(): String {
return if (isList) list.toString() else number.toString()
}
override operator fun compareTo(other: Signal): Int {
return when {
isNumber and other.isNumber -> number?.compareTo(other.number ?:0) ?: throw IllegalStateException("Should not reach here")
isNumber and other.isList -> this.box().compareLists(other)
isList and other.isNumber -> compareLists(other.box())
isList and other.isList -> compareLists(other)
else -> 0
}
}
private fun compareLists(sigB: Signal): Int {
(list!! zip sigB.list!!).forEach {
if (it.first < it.second) return -1
if (it.first > it.second) return 1
}
return list.size.compareTo(sigB.list.size)
}
companion object {
fun ofEmptyList() = ofList(listOf())
fun ofNumber(number: Int) = Signal("NUMBER", number, null)
fun ofList(list: List<Signal>) = Signal("LIST", null, list)
}
}
fun main() {
fun parsePureList(line: String, children: MutableList<Signal>): Signal {
return line.split(',')
.map {
if (it == "parsed") children.removeLast()
else Signal.ofNumber(it.toInt())
}
.let { Signal.ofList(it) }
}
fun parseLine(line: String): Signal {
val signals = mutableListOf<Signal>()
var current = line
while (true) {
val start = current.lastIndexOf('[')
if (start == -1 && current != "parsed") return Signal.ofEmptyList()
val end = current.drop(start).indexOf(']') + start
if (start > end) throw IllegalStateException("Should not reach here: $start, $end, $line")
val nextElement = if (start + 1 == end) Signal.ofEmptyList()
else {
val middle = current.substring(start + 1 until end)
parsePureList(middle, signals)
}
signals.add(nextElement)
current = current.take(start) + "parsed" + current.drop(end + 1)
if (current == "parsed") return signals.first()
}
}
fun parseLines(input: List<String>) = input.asSequence()
.filter { it.isNotBlank() }
.map { parseLine(it) }
fun part1(input: List<String>): Int {
return parseLines(input)
.windowed(2, 2)
.map { Pair(it[0], it[1]) }
.mapIndexed { index, pair -> if (pair.first < pair.second) index + 1 else 0 }
.sum()
}
fun part2(input: List<String>): Int {
return parseLines(listOf(input, listOf("[[2]]", "[[6]]")).flatten())
.toList()
.sorted()
.map { it.toString() }
.let { (it.indexOf("[[2]]") + 1) * (it.indexOf("[[6]]") + 1) }
}
val testInput = readInput("Day13_test")
checkEquals(part1(testInput), 13)
checkEquals(part2(testInput), 140)
val input = readInput("Day13")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 3,317 | advent-of-code-kotlin | Apache License 2.0 |
src/Day01.kt | GunnarBernsteinHH | 737,845,880 | false | {"Kotlin": 10952} | /*
* --- Day 1: Trebuchet?! ---
* Source: https://adventofcode.com/2023/day/1
*
*/
fun main() {
// val numbersAsString = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
val numberMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9)
fun part1(input: List<String>): Int {
var sum = 0
input.forEach { line ->
// line.println()
val firstValue: Int = line.first { it.isDigit() }.digitToInt() * 10
val lastValue: Int = line.last { it.isDigit() }.digitToInt()
sum += firstValue + lastValue
}
return sum
}
fun part2(input: List<String>): Int {
// create reversed map for reversed search of number words
val numberMapReversed = mutableMapOf<String, Int>()
numberMap.forEach { (s, i) -> numberMapReversed[s.reversed()] = i }
// create list of map (possible performance gain)
val numbersAsString = numberMap.keys
val numbersAsStringReversed = numberMapReversed.keys
// create new list which can be evaluated by part1 (digit only) function
val reworkedInput = mutableListOf<String>()
input.forEach { line ->
// find first number word
val found = line.findAnyOf(numbersAsString,0,true)
// find last number word
val foundReversed = line.reversed().findAnyOf(numbersAsStringReversed,0,true)
// insert digits in front of word
val lineNew = StringBuilder(line)
foundReversed?.let { lineNew.insert(line.length - foundReversed.first, numberMapReversed[foundReversed.second]) }
found?.let { lineNew.insert(found.first, numberMap[found.second]) }
reworkedInput.add(lineNew.toString())
}
return part1(reworkedInput)
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// check(part1(testInput) == 1)
val input = readInput("input.day01.txt")
println("Results for 2023, day 1:")
println("Result of part 1: " + part1(input))
println("Result of part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | bc66eef73bca2e64dfa5d83670266c8aaeae5b24 | 2,249 | aoc-2023-in-kotlin | MIT License |
src/main/kotlin/days/Day16.kt | MaciejLipinski | 317,582,924 | true | {"Kotlin": 60261} | package days
class Day16 : Day(16) {
override fun partOne(): Any {
val rules = inputString
.split("your ticket:")[0]
.split("\n")
.filter { it.isNotBlank() }
.map { it.split(": ")[1] }
.map { it.split(" or ") }
.flatMap {
it
.map { inner -> inner.split("-") }
.map { inner -> inner.map { num -> num.toInt() } }
.map { inner -> IntRange(inner[0], inner[1]) }
}
val ticketNumbers = inputString
.split("nearby tickets:")[1]
.split("\n")
.filter { it.isNotBlank() }
.map { it.split(",") }
.flatMap {
it.map { inner -> inner.toInt() }
}
return ticketNumbers
.filter { t -> !rules.any { r -> r.contains(t) } }
.sum()
}
override fun partTwo(): Any {
val rules = inputString
.split("your ticket:")[0]
.split("\n")
.filter { it.isNotBlank() }
.map { it.split(": ") }
.map {
it[0] to it[1]
.split(" or ")
.map { inner -> inner.split("-") }
.map { inner -> inner.map { num -> num.toInt() } }
.map { inner -> IntRange(inner[0], inner[1]) }
}
val tickets = inputString
.split("nearby tickets:")[1]
.split("\n")
.filter { it.isNotBlank() }
.map { it.split(",") }
.map { it.map { inner -> inner.toInt() } }
.filter { t -> !t.any { i -> !rules.any { r -> r.second.any { range -> range.contains(i) } } } }
val possibleRuleAssignments = mutableMapOf<Int, MutableList<String>>()
for (i in tickets[0].indices) {
rules
.forEach { rule ->
if (tickets.all { ticket -> rule.second.any { it.contains(ticket[i]) } }) {
if (possibleRuleAssignments[i] == null) {
possibleRuleAssignments[i] = mutableListOf(rule.first)
} else {
possibleRuleAssignments[i]!!.add(rule.first)
}
}
}
}
val sortedRules = possibleRuleAssignments.toList().sortedBy { it.second.size }
sortedRules.subList(0, sortedRules.lastIndex).forEachIndexed { i, possibleRuleNames ->
possibleRuleNames.second.forEach { ruleName ->
sortedRules.subList(i + 1, sortedRules.lastIndex + 1).forEach { otherPossibleRuleNames ->
otherPossibleRuleNames.second.remove(ruleName)
}
}
}
if (sortedRules.any { it.second.size != 1 }) throw RuntimeException()
val assignedRules = sortedRules.map { it.first to it.second.first() }.toMap()
val myTicket =
inputString
.split("your ticket:")[1]
.split("nearby tickets:")[0]
.split("\n")
.filter { it.isNotBlank() }
.reduce { acc, s -> "$acc$s" }
.split(",")
.map { it.toLong() }
return myTicket
.filterIndexed { index, _ -> assignedRules[index]?.startsWith("departure") ?: false }
.reduce { acc, i -> acc * i }
}
} | 0 | Kotlin | 0 | 0 | 1c3881e602e2f8b11999fa12b82204bc5c7c5b51 | 3,754 | aoc-2020 | Creative Commons Zero v1.0 Universal |
src/Day04.kt | iownthegame | 573,926,504 | false | {"Kotlin": 68002} | class Pair(private val line: String) {
private val assignmentOfFirstElf: Assignment
private val assignmentOfSecondElf: Assignment
init {
val parts = line.split(",")
assignmentOfFirstElf = Assignment(parts.first().split("-").map { it.toInt() })
assignmentOfSecondElf = Assignment(parts.last().split("-").map { it.toInt() })
}
fun hasExclusiveAssignment(): Boolean {
return assignmentOfFirstElf.containsAssignment(assignmentOfSecondElf)
|| assignmentOfSecondElf.containsAssignment(assignmentOfFirstElf)
}
fun hasOverlappedAssignment(): Boolean {
return assignmentOfFirstElf.overlapsAssignment(assignmentOfSecondElf)
}
class Assignment(private val array: List<Int>) {
private var min: Int = 0
private var max: Int = 0
init {
min = array.first()
max = array.last()
}
fun containsAssignment(otherAssignment: Assignment): Boolean {
return min <= otherAssignment.min && max >= otherAssignment.max
}
fun overlapsAssignment(otherAssignment: Assignment): Boolean {
return (max >= otherAssignment.min && max <= otherAssignment.max) || (otherAssignment.max in min..max)
}
}
}
fun main() {
fun getPairs(input: List<String>): Array<Pair> {
var pairs = arrayOf<Pair>()
for (line in input) {
pairs += Pair(line)
}
return pairs
}
fun part1(input: List<String>): Int {
val pairs = getPairs(input)
return pairs.count { it.hasExclusiveAssignment() }
}
fun part2(input: List<String>): Int {
val pairs = getPairs(input)
return pairs.count { it.hasOverlappedAssignment() }
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day04_sample")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readTestInput("Day04")
println("part 1 result: ${part1(input)}")
println("part 2 result: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 4e3d0d698669b598c639ca504d43cf8a62e30b5c | 2,090 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | MatthiasDruwe | 571,730,990 | false | {"Kotlin": 47864} | import kotlin.math.floor
fun main() {
fun part1(input: List<String>): Long {
val monkeys = input.splitOnEmptyString().map { Monkey(it.drop(1)) }
repeat(20){
monkeys.forEach { monkey->
repeat(monkey.numbers.size) {
monkey.inspect()
val number = monkey.numbers.removeFirst()
val newNumber = floor(monkey.executeOperation(number).toDouble()/3).toLong()
if(newNumber%monkey.test==0L){
monkeys[monkey.trueMonkey].numbers.add(newNumber)
} else {
monkeys[monkey.falseMonkey].numbers.add(newNumber)
}
}
}
}
val orderMonkeys = monkeys.sortedByDescending { it.inspectCount }
return orderMonkeys[0].inspectCount * orderMonkeys[1].inspectCount
}
fun part2(input: List<String>): Long {
val monkeys = input.splitOnEmptyString().map { Monkey(it.drop(1)) }
var maxTest =1L
monkeys.forEach { maxTest*=it.test }
repeat(10000){
monkeys.forEach { monkey->
repeat(monkey.numbers.size) {
monkey.inspect()
val number = monkey.numbers.removeFirst()
val newNumber = monkey.executeOperation(number) % maxTest
if(newNumber%monkey.test==0L){
monkeys[monkey.trueMonkey].numbers.add(newNumber)
} else {
monkeys[monkey.falseMonkey].numbers.add(newNumber)
}
}
}
}
val orderMonkeys = monkeys.sortedByDescending { it.inspectCount }
return orderMonkeys[0].inspectCount * orderMonkeys[1].inspectCount
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_example")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
class Monkey(input: List<String>){
val numbers: MutableList<Long>
private val operation: List<String>
val test: Int
val trueMonkey: Int
val falseMonkey: Int
var inspectCount =0L
init {
numbers = input[0].trim().removePrefix("Starting items: ").split(", ").map { it.toLong() }.toMutableList()
operation = input[1].trim().removePrefix("Operation: new = ").split(" ")
test = input[2].trim().removePrefix("Test: divisible by ").toInt()
trueMonkey = input[3].trim().removePrefix("If true: throw to monkey ").toInt()
falseMonkey = input[4].trim().removePrefix("If false: throw to monkey ").toInt()
}
fun inspect(){
inspectCount++
}
fun executeOperation(old: Long): Long{
val number1 = if(operation[0]=="old") old else operation[0].toLong()
val number2 = if(operation[2]=="old") old else operation[2].toLong()
return when(operation[1]){
"+" -> number1+ number2
"-" -> number1- number2
"*" -> number1* number2
"/" -> number1/ number2
else -> 0
}
}
}
| 0 | Kotlin | 0 | 0 | f35f01cea5075cfe7b4a1ead9b6480ffa57b4989 | 3,268 | Advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | aneroid | 572,802,061 | false | {"Kotlin": 27313} | enum class RockPaperScissors(val theirLetter: String, val myLetter: String, val choiceScore: Int) {
ROCK("A", "X", 1),
PAPER("B", "Y", 2),
SCISSORS("C", "Z", 3),
;
private fun beats(other: RockPaperScissors) =
when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
} == other
fun scoreVersus(other: RockPaperScissors) =
when {
beats(other) -> Goal.WIN
this == other -> Goal.DRAW
else -> Goal.LOSE
}.moveScore
companion object {
fun fromString(letter: String) =
values().first { it.theirLetter == letter || it.myLetter == letter }
}
}
enum class Goal(val letter: String, val moveScore: Int) {
LOSE("X", 0),
DRAW("Y", 3),
WIN("Z", 6),
;
fun toRPS(theirs: RockPaperScissors) =
RockPaperScissors.values().first { mine -> mine.scoreVersus(theirs) == moveScore }
companion object {
fun fromRPS(rps: RockPaperScissors) = values().first { it.letter == rps.myLetter }
}
}
class Day02(input: List<String>) {
private val data = parseInput(input)
private fun List<Pair<RockPaperScissors, RockPaperScissors>>.calculateScore() =
fold(0) { acc, (theirs, mine) ->
acc + mine.scoreVersus(theirs) + mine.choiceScore
}
fun partOne(): Int =
data.calculateScore()
fun partTwo(): Int =
data.map { (theirs, mine) -> theirs to Goal.fromRPS(mine).toRPS(theirs) }
.calculateScore()
private companion object {
fun parseInput(input: List<String>) =
input.map { line ->
line.split(" ")
.map(RockPaperScissors::fromString)
}.map { it.first() to it.last() }
}
}
fun main() {
val testInput = """
A Y
B X
C Z
""".trimIndent().lines()
check(Day02(testInput).partOne() == 15)
check(Day02(testInput).partTwo() == 12) // uncomment when ready
val input = readInput("Day02")
println("partOne: ${Day02(input).partOne()}\n")
println("partTwo: ${Day02(input).partTwo()}\n")
}
| 0 | Kotlin | 0 | 0 | cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd | 2,196 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day02.kt | ka1eka | 574,248,838 | false | {"Kotlin": 36739} | fun main() {
val rules1 = mapOf(
Pair('A', 'A') to 3,
Pair('A', 'B') to 6,
Pair('A', 'C') to 0,
Pair('B', 'A') to 0,
Pair('B', 'B') to 3,
Pair('B', 'C') to 6,
Pair('C', 'A') to 6,
Pair('C', 'B') to 0,
Pair('C', 'C') to 3,
)
val rules2 = rules1
.entries
.associate {
Pair(it.key.first, it.value) to it.key
}
fun calcChoicePoints(me: Char): Int = me - 'A' + 1
fun calcPart1Score(round: Pair<Char, Char>): Int = rules1[round]!! + calcChoicePoints(round.second)
fun calcPart2Score(round: Pair<Char, Char>): Int = calcPart1Score(
rules2[Pair(
round.first,
when (round.second) {
'Y' -> 3
'Z' -> 6
else -> 0
}
)]!!
)
fun part1(input: List<String>): Int = input
.map {
it.split(' ')
}.map {
Pair(it[0][0], it[1][0] - ('X' - 'A'))
}.sumOf {
calcPart1Score(it)
}
fun part2(input: List<String>): Int = input
.map {
it.split(' ')
}.map {
Pair(it[0][0], it[1][0])
}.sumOf {
calcPart2Score(it)
}
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 | 4f7893448db92a313c48693b64b3b2998c744f3b | 1,471 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | muellerml | 573,601,715 | false | {"Kotlin": 14872} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val splitted = it.split(" ")
calculateResult(OpponentSymbol.valueOf(splitted[0]).translate(), OwnSymbol.valueOf(splitted[1]))
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val splitted = it.split(" ")
calculateSymbolAndResult(OpponentSymbol.valueOf(splitted[0]), OwnSymbol.valueOf(splitted[1]))
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day02_test")
val result = part1(testInput)
check(result == 15)
val result2 = part2(testInput)
check(result2 == 12)
val input = readInput("day02")
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
enum class OpponentSymbol(val typ: String) {
A("stein"),
B("papier"),
C("schere");
fun translate(): OwnSymbol {
return when (this) {
A -> OwnSymbol.X
B -> OwnSymbol.Y
C -> OwnSymbol.Z
}
}
}
enum class OwnSymbol(val typ: String,val value: Int) {
X("stein", 1),
Y("papier", 2),
Z("schere", 3)
}
sealed class Outcome(val value: Int, val expectedOutcome: String) {
object LOSS: Outcome(0, "X")
object DRAW: Outcome(3, "Y")
object WIN: Outcome(6, "Z")
}
fun calculateResult(opponent: OwnSymbol, own: OwnSymbol): Int {
val outcome : Outcome = when (opponent) {
own -> Outcome.DRAW
OwnSymbol.X -> if (own == OwnSymbol.Y) Outcome.WIN else Outcome.LOSS
OwnSymbol.Y -> if (own == OwnSymbol.X) Outcome.LOSS else Outcome.WIN
OwnSymbol.Z -> if (own == OwnSymbol.X) Outcome.WIN else Outcome.LOSS
else -> error("new case detected: $opponent to $own")
}
println("Outcome: $outcome")
println("Symbol: $own")
return outcome.value + own.value
}
fun calculateSymbolAndResult(opponent: OpponentSymbol, own: OwnSymbol): Int {
val outcome = when (own.name) {
Outcome.DRAW.expectedOutcome -> Outcome.DRAW
Outcome.LOSS.expectedOutcome -> Outcome.LOSS
Outcome.WIN.expectedOutcome -> Outcome.WIN
else -> error("unexpected symbol $own")
}
val chosenSymbol = when (outcome) {
Outcome.DRAW -> opponent.translate()
Outcome.WIN -> when (opponent) {
OpponentSymbol.A -> OwnSymbol.Y
OpponentSymbol.B -> OwnSymbol.Z
OpponentSymbol.C -> OwnSymbol.X
}
Outcome.LOSS -> when(opponent) {
OpponentSymbol.A -> OwnSymbol.Z
OpponentSymbol.B -> OwnSymbol.X
OpponentSymbol.C -> OwnSymbol.Y
}
else -> error("Unexpected symbol $opponent")
}
return outcome.value + chosenSymbol.value
}
| 0 | Kotlin | 0 | 0 | 028ae0751d041491009ed361962962a64f18e7ab | 2,810 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2021/day09/day9.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2021.day09
import biz.koziolek.adventofcode.*
fun main() {
val inputFile = findInput(object {})
val lines = inputFile.bufferedReader().readLines()
val smokeMap = parseSmokeMap(lines)
println("Low points risk sum is: ${getLowPointsRiskSum(smokeMap)}")
val basins = findSmokeBasins(smokeMap)
println("Product of sizes of the three largest basins is: ${getLargestBasinsSizeProduct(basins, n = 3)}")
}
fun getLowPointsRiskSum(smokeMap: Map<Coord, Int>): Int =
findSmokeLowPoints(smokeMap).let { lowPoints ->
lowPoints.sumOf { getRiskLevel(it, smokeMap, lowPoints) }
}
fun getLargestBasinsSizeProduct(basins: Collection<Set<Coord>>, n: Int) =
basins.map { it.size }
.sorted()
.reversed()
.take(n)
.ifEmpty { return 0 }
.fold(1) { acc, size -> acc * size }
fun findSmokeBasins(smokeMap: Map<Coord, Int>): Collection<Set<Coord>> {
return findSmokeLowPoints(smokeMap)
.map { lowPoint ->
buildSet {
visitAll(start = lowPoint) { currentCoord ->
val value = smokeMap[currentCoord] ?: 0
if (value != 9) {
add(currentCoord)
smokeMap.getAdjacentCoords(currentCoord, includeDiagonal = false)
} else {
emptySet()
}
}
}
}
.toSet()
}
fun parseSmokeMap(lines: List<String>): Map<Coord, Int> =
lines.parse2DMap { it.digitToInt() }.toMap()
fun findSmokeLowPoints(smokeMap: Map<Coord, Int>): Set<Coord> =
smokeMap.flatMap { (coord, currentHeight) ->
smokeMap.getAdjacentCoords(coord, includeDiagonal = false)
.map { smokeMap[it] ?: 0 }
.all { it > currentHeight }
.let {
when (it) {
true -> setOf(coord)
false -> emptySet()
}
}
}.toSet()
fun getRiskLevel(coord: Coord, smokeMap: Map<Coord, Int>, lowPoints: Set<Coord>) =
when (coord) {
in lowPoints -> (smokeMap[coord] ?: 0) + 1
else -> throw IllegalArgumentException("Unsupported coordinates: $coord")
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 2,469 | advent-of-code | MIT License |
src/Day07.kt | sbaumeister | 572,855,566 | false | {"Kotlin": 38905} | data class Directory(
val name: String,
val parentNode: Directory?,
val files: MutableSet<File>,
val dirs: MutableSet<Directory>,
var size: Int = 0,
) {
override fun toString(): String = "$parentNode -> $name"
override fun hashCode(): Int = parentNode.hashCode() + name.hashCode()
}
data class File(val name: String, val size: Int, val parentNode: Directory)
fun calcDirSize(dir: Directory): Int {
val fileSizeSum = dir.files.sumOf { it.size }
val dirSizeSum = dir.dirs.sumOf { calcDirSize(it) }
return fileSizeSum + dirSizeSum
}
fun findDirsWithMaxSize(dir: Directory, maxSize: Int = 100000): Set<Directory> {
val result = mutableSetOf<Directory>()
dir.size = calcDirSize(dir)
if (dir.size <= maxSize) {
result.add(dir)
}
dir.dirs.forEach {
result.addAll(findDirsWithMaxSize(it, maxSize))
}
return result
}
fun findDirsWithMinSize(dir: Directory, minSize: Int): Set<Directory> {
val result = mutableSetOf<Directory>()
dir.size = calcDirSize(dir)
if (dir.size >= minSize) {
result.add(dir)
}
dir.dirs.forEach {
result.addAll(findDirsWithMinSize(it, minSize))
}
return result
}
fun buildTree(input: List<String>): Directory {
val rootDir = Directory("/", null, mutableSetOf(), mutableSetOf())
var currentDir = rootDir
input.drop(1).forEach { line ->
if (line.startsWith("$ cd")) {
val targetDirName = line.substring(5)
currentDir = when (targetDirName) {
".." -> currentDir.parentNode!!
else -> currentDir.dirs.first { it.name == targetDirName }
}
}
if (line.startsWith("dir")) {
currentDir.dirs.add(Directory(line.substring(4), currentDir, mutableSetOf(), mutableSetOf()))
}
val fileMatch = """(\d+)\s(.+)""".toRegex().find(line)
if (fileMatch != null) {
val (fileSize, fileName) = fileMatch.destructured
currentDir.files.add(File(fileName, fileSize.toInt(), currentDir))
}
}
return rootDir
}
fun main() {
fun part1(input: List<String>): Int {
val rootDir = buildTree(input)
val dirs = findDirsWithMaxSize(rootDir)
return dirs.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val rootDir = buildTree(input)
val rootDirSize = calcDirSize(rootDir)
val unusedSpace = 70000000 - rootDirSize
val dirs = findDirsWithMinSize(rootDir, 30000000 - unusedSpace)
return dirs.minBy { it.size }.size
}
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 | e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84 | 2,804 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | jstapels | 572,982,488 | false | {"Kotlin": 74335} | typealias Dirs = Map<String, Long>
fun main() {
fun dirSizes(path: String, data: Dirs) =
data.filterKeys { it.startsWith(path) }
.values
.sum()
fun dirSizes(data: Dirs) =
data.keys
.associateWith { dirSizes(it, data) }
fun makePath(path: List<String>) = "/" + path.joinToString("/")
fun parseLine(path: List<String>, data: Dirs, input: String) =
when {
input.startsWith("$ cd /") -> emptyList<String>() to data
input.startsWith("$ cd ..") -> path.dropLast(1) to data
input.startsWith("$ cd ") -> (path + input.split(" ")[2]) to data
input.startsWith("$ ls") -> path to data
input.startsWith("dir") -> path to makePath(path).let { data + (it to (data[it] ?: 0)) }
else -> path to makePath(path).let { data + (it to (data[it] ?: 0) + input.split(" ")[0].toInt()) }
}
fun part1(input: List<String>) =
dirSizes(input.fold(emptyList<String>() to emptyMap<String, Long>()) { (path, data), line -> parseLine(path, data, line) }.second)
.values
.filter{ it <= 100000L }
.sum()
fun part2(input: List<String>) =
dirSizes(input.fold(emptyList<String>() to emptyMap<String, Long>()) { (path, data), line -> parseLine(path, data, line) }.second)
.let { sizes ->
val spaceNeeded = 30000000L - (70000000L - sizes["/"]!!)
sizes.filterValues { it >= spaceNeeded }
.values
.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
checkThat(part1(testInput), 95437)
checkThat(part2(testInput), 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0d71521039231c996e2c4e2d410960d34270e876 | 1,872 | aoc22 | Apache License 2.0 |
src/main/kotlin/net/wrony/aoc2023/a12/Riddle.kt | kopernic-pl | 727,133,267 | false | {"Kotlin": 52043} | package net.wrony.aoc2023.a12
import kotlin.io.path.Path
import kotlin.io.path.readLines
fun txtToSprings(s: String): Pair<String, List<Int>> {
return s.split(" ").let { (inp, desc) -> inp to desc.split(",").map { it.toInt() } }
}
fun isPossible(s: Pair<String, List<Int>>): Boolean {
val (inp, desc) = s
val potential = inp.replace("?", ".").split(".").filter { it.isNotEmpty() }.map { it.length }
return inp.count { it == '#' } <= desc.sum() &&
potential.size <= desc.size && potential.zip(desc).all { (pot, desc) -> pot <= desc }
}
fun isValid(s: Pair<String, List<Int>>): Boolean {
val (inp, desc) = s
return !inp.contains('?') && inp.split(".").filter { it.isNotEmpty() }.map { it.length } == desc
}
fun scanput(str: String, counts: List<Int>, n: Int): Int {
// kill branch early if it's NOK
if(!isPossible(str to counts)) return 0
if (n == str.length) return if (isValid(str to counts)) 1 else 0
return if (str[n] == '?') {
scanput(str.replaceRange(n, n + 1, "#"), counts, n + 1) +
scanput(str.replaceRange(n, n + 1, "."), counts, n + 1)
} else {
scanput(str, counts, n + 1)
}
}
fun main() {
Path("src/main/resources/12.txt").readLines().map { txtToSprings(it) }.also {
// it.sumOf { (inp, desc) -> scanput(inp, desc, 0) }.also { println("Part 1: $it") }
}.also {
it.map { (inp, blocks) -> inp.repeat(5) to List(5) { blocks }.flatten() }
.minBy { (inp, blocks) -> inp.length }
.also { println(it) }
.let { (inp, blocks) -> scanput(inp, blocks, 0) }
.also { println(it) }
}
}
| 0 | Kotlin | 0 | 0 | 1719de979ac3e8862264ac105eb038a51aa0ddfb | 1,684 | aoc-2023-kotlin | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day287/day287.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day287
// day287.kt
// By <NAME>, 2020.
import java.util.PriorityQueue
typealias UserId = Int
typealias Watcher<T> = Pair<T, UserId>
typealias WatcherInfoList<T> = List<Pair<T, Set<UserId>>>
typealias Similarity<T> = Pair<T, T>
/**
* The similarity score between two Ts (assumed to be TV shows, but could be anything with observers).
*/
data class SimilarityScore<T>(val score: Double, val show1: T, val show2: T)
/**
* A comparator for SimilarityScore to be used in the priority queue.
*/
class SimilarityScoreComparator<T> : Comparator<SimilarityScore<T>> {
override fun compare(o1: SimilarityScore<T>?, o2: SimilarityScore<T>?): Int {
require(o1 != null)
require(o2 != null)
val diff = o1.score - o2.score
return when {
diff < 0.0 -> -1
diff > 0.0 -> 1
diff == 0.0 -> 0
else -> 0
}
}
}
fun <T> calculateNMostSimilarShows(n: Int, watcherData: Collection<Watcher<T>>): List<Similarity<T>> {
/**
* We will use the Jaccard index to determine the similarity between two programs.
* Convert the programs from pairs (progId, userID) to sets of userID.
* Then for prog A and for prog B, we determine their similarity using the Jaccard
* index:
*
* J(A, B) = |A symm diff B| / |A union B|
*
* We need to avoid division by 0: in that case, just return 0.
*/
fun jaccardIndex(s1: Set<Int>, s2: Set<Int>): Double {
val union = s1.union(s2)
return if (union.isEmpty()) 0.0
else (union - s1.intersect(s2)).size.toDouble() / union.size.toDouble()
}
/**
* Create a priority queue of similarity scores.
* In Java, a priority queue is based on a max heap, so they have the same performance.
*/
fun calculateSimilarPrograms(): PriorityQueue<SimilarityScore<T>> {
// Group together the watcher data into sets.
val watcherInfoList: WatcherInfoList<T> = watcherData.groupBy { it.first }
.mapValues { (_, v) -> v.map { it.second }.toSet() }.toList()
val size = watcherInfoList.size
// The similarity relationship is reflexive.
val pq = PriorityQueue<SimilarityScore<T>>(size * (size - 1), SimilarityScoreComparator())
for (i in 0 until size - 1)
for (j in i + 1 until size)
pq.add(
SimilarityScore(
jaccardIndex(watcherInfoList[i].second, watcherInfoList[j].second),
watcherInfoList[i].first,
watcherInfoList[j].first
)
)
return pq
}
/**
* Then we can take the top k to represent the k most similar programs, dropping score.
*/
return calculateSimilarPrograms().take(n).map { Pair(it.show1, it.show2) }
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 2,872 | daily-coding-problem | MIT License |
src/Day03.kt | dmarmelo | 573,485,455 | false | {"Kotlin": 28178} | fun main() {
fun calculatePriority(char: Char) = when (char.code) {
in ('a'.code..'z'.code) -> char - 'a' + 1
in ('A'.code..'Z'.code) -> char - 'A' + 27
else -> error("Unknown input $char")
}
infix fun String.intersect(other: String): Set<Char> = toSet() intersect other.toSet()
infix fun Iterable<Char>.intersect(other: String) = this intersect other.toSet()
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val firstComp = rucksack.substring(0, rucksack.length / 2)
val secondComp = rucksack.substring(rucksack.length / 2)
(firstComp intersect secondComp)
.sumOf(::calculatePriority)
}
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.sumOf { (rucksack1, rucksack2, rucksack3) ->
(rucksack1 intersect rucksack2 intersect rucksack3)
.sumOf(::calculatePriority)
}
}
fun part2_2(input: List<String>): Int {
return input.chunked(3)
.flatMap { elfGroup ->
elfGroup.map { it.toSet() }
.reduce { acc, rucksack ->
acc intersect rucksack
}
}
.sumOf(::calculatePriority)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
check(part2_2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
println(part2_2(input))
}
| 0 | Kotlin | 0 | 0 | 5d3cbd227f950693b813d2a5dc3220463ea9f0e4 | 1,672 | advent-of-code-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.