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/Day07.kt
|
fasfsfgs
| 573,562,215 | false |
{"Kotlin": 52546}
|
data class AoCFile(val name: String, val size: Long, val dir: String)
fun List<AoCFile>.totalSize() = sumOf { it.size }
fun List<AoCFile>.dirSizes() = asSequence()
.flatMap { it.dir.possibleDirs() }
.distinct()
.map { dir -> this.filter { it.dir == dir || it.dir.startsWith("$dir/") } }
.map { files ->
files.sumOf { it.size }
}
fun List<AoCFile>.totalSizeDirsSmallerThan(limit: Long) = dirSizes()
.filter { it <= limit }
.sum()
fun List<AoCFile>.smallestDirSizeLargerThan(minSize: Long) = dirSizes()
.sorted()
.find { it > minSize } ?: error("Cannot find a single directory that has the minimum required size.")
fun String.possibleDirs() = split('/')
.drop(1)
.fold(listOf("")) { acc, it -> acc.plus(acc.last() + "/$it") }
fun List<String>.toAoCFiles() = run {
var currDir = ""
drop(1) // $ cd /
.mapNotNull { line ->
var file: AoCFile? = null
when {
line == "$ cd .." -> currDir = currDir.substringBeforeLast("/")
line.startsWith("$ cd ") -> currDir = currDir + '/' + line.substring(5)
line.first().isDigit() -> {
val (strFileSize, name) = line.split(" ")
file = AoCFile(name, strFileSize.toLong(), currDir)
}
}
file
}
}
fun main() {
fun part1(input: List<String>) = input.toAoCFiles().totalSizeDirsSmallerThan(100_000)
fun part2(input: List<String>): Long {
val availableSpace = 70_000_000 - 30_000_000
val files = input.toAoCFiles()
val usedSpace = files.totalSize()
val spaceToFreeUp = usedSpace - availableSpace
return files.smallestDirSizeLargerThan(spaceToFreeUp)
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
// For part 2, I began reading threads in Reddit and spotted a bug while reading other people's struggles.
}
| 0 |
Kotlin
| 0 | 0 |
17cfd7ff4c1c48295021213e5a53cf09607b7144
| 2,094 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/aoc2023/Day21.kt
|
Ceridan
| 725,711,266 | false |
{"Kotlin": 110767, "Shell": 1955}
|
package aoc2023
class Day21 {
fun part1(input: String, steps: Int): Int {
val (start, grid) = parseInput(input)
val (reachablePointsCount) = getReachablePoints(grid, start, steps)
return reachablePointsCount
}
fun part2(input: String, steps: Int): Long {
val (start, grid) = parseInput(input)
val gridSize = grid.keys.maxOf { it.y } + 1
val initialSteps = steps % gridSize
// https://en.wikipedia.org/wiki/Vandermonde_matrix
// https://en.wikipedia.org/wiki/Cramer%27s_rule
// Vandermonde matrix:
// [ 1 0 0 ]
// A = [ 1 1 1 ]
// [ 1 2 4 ]
val (b0, b1, b2) = getReachablePoints(
grid,
start,
initialSteps,
initialSteps + gridSize,
initialSteps + 2 * gridSize
)
val detA = 2
val detA0 = 2 * b0
val detA1 = -3 * b0 + 4 * b1 - b2
val detA2 = b0 - 2 * b1 + b2
val x0 = detA0 / detA
val x1 = detA1 / detA
val x2 = detA2 / detA
val n = 1L * steps / gridSize
return x0 + x1 * n + x2 * n * n
}
private fun getReachablePoints(grid: Map<Point, Char>, start: Point, vararg steps: Int): List<Int> {
val gridSize = grid.keys.maxOf { it.y } + 1
var reachablePoints = setOf(start)
val partialResults = mutableListOf<Int>()
val stepSet = steps.toSet()
repeat(steps.last()) { step ->
reachablePoints = reachablePoints.flatMap { point ->
listOf(point + (-1 to 0), point + (0 to -1), point + (1 to 0), point + (0 to 1))
}
.filter { point ->
val gridPoint = point.toGrid(gridSize)
grid[gridPoint] != '#'
}
.toSet()
if ((step + 1) in stepSet) partialResults.add(reachablePoints.size)
}
return partialResults
}
private fun Point.toGrid(gridSize: Int): Point {
val gridY = (y % gridSize + gridSize) % gridSize
val gridX = (x % gridSize + gridSize) % gridSize
return gridY to gridX
}
private fun parseInput(input: String): Pair<Point, Map<Point, Char>> {
val grid = mutableMapOf<Point, Char>()
var start: Point = 0 to 0
val lines = input.split('\n').filter { it.isNotEmpty() }
for (y in lines.indices) {
for (x in lines[y].indices) {
if (lines[y][x] == 'S') {
start = y to x
grid[start] = '.'
} else {
grid[y to x] = lines[y][x]
}
}
}
return start to grid
}
}
fun main() {
val day21 = Day21()
val input = readInputAsString("day21.txt")
println("21, part 1: ${day21.part1(input, 64)}")
println("21, part 2: ${day21.part2(input, 26501365)}")
}
| 0 |
Kotlin
| 0 | 0 |
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
| 2,939 |
advent-of-code-2023
|
MIT License
|
src/main/kotlin/Day5.kt
|
Ostkontentitan
| 434,500,914 | false |
{"Kotlin": 73563}
|
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun puzzleDayFivePartOne() {
val inputs = readInput(5).map { it.trim() }
val lines = parseLines(inputs).filter { it.isVertical() || it.isHorizontal() }
val allPoints = lines.fold(emptyList<Point>()) { acc, line ->
acc + line.points()
}
val distinctPoints = allPoints.groupingBy { it }.eachCount().filter { it.value > 1 }.keys
println("Overlapping point count: ${distinctPoints.size}")
}
fun puzzleDayFivePartTwo() {
val inputs = readInput(5).map { it.trim() }
val lines = parseLines(inputs)
val allPoints = lines.fold(emptyList<Point>()) { acc, line ->
acc + line.points()
}
val distinctPoints = allPoints.groupingBy { it }.eachCount().filter { it.value > 1 }.keys
println("Overlapping point count: ${distinctPoints.size}")
}
fun parseLines(inputs: List<String>): List<Line> = inputs.map {
val points = it.split(" -> ")
val from = points[0].split(",")
val to = points[1].split(",")
Line(Point(from[0].toInt(), from[1].toInt()), Point(to[0].toInt(), to[1].toInt()))
}
fun Line.points(): List<Point> =
if (isHorizontal()) {
val start = min(from.x, to.x)
val end = max(from.x, to.x)
(start..end).map {
Point(it, from.y)
}
} else if (isVertical()) {
val start = min(from.y, to.y)
val end = max(from.y, to.y)
(start..end).map {
Point(from.x, it)
}
} else if (isFortyFiveDegreeDiagonal()) {
val startX = min(from.x, to.x)
if (areXyOnOppositeCourse()) {
val endY = max(from.y, to.y)
val steps = abs(from.x - to.x)
(0..steps).map {
Point(startX + it, endY - it)
}
} else {
val startY = min(from.y, to.y)
val steps = abs(from.x - to.x)
(0..steps).map {
Point(startX + it, startY + it)
}
}
} else {
throw IllegalStateException("Not a linear point. ")
}
fun Line.isHorizontal() = from.y == to.y
fun Line.isVertical() = from.x == to.x
fun Line.isFortyFiveDegreeDiagonal() = abs(from.x - to.x) == abs(from.y - to.y)
fun Line.areXyOnOppositeCourse() = from.x - to.x != from.y - to.y
data class Point(val x: Int, val y: Int)
data class Line(val from: Point, val to: Point)
| 0 |
Kotlin
| 0 | 0 |
e0e5022238747e4b934cac0f6235b92831ca8ac7
| 2,399 |
advent-of-kotlin-2021
|
Apache License 2.0
|
src/aoc2022/Day25.kt
|
NoMoor
| 571,730,615 | false |
{"Kotlin": 101800}
|
package aoc2022
import utils.*
import kotlin.math.max
private class Day25(val lines: List<String>) {
/** Maps from SNAFU character to decimal digit. */
fun map(c: Char) : Int {
return when (c) {
'-' -> -1
'=' -> -2
else -> c.digitToInt()
}
}
/** Maps from decimal digit to SNAFU character. */
fun map(i: Int) : Char {
return when (i) {
-1 -> '-'
-2 -> '='
else -> i.digitToChar()
}
}
fun snafuToDec(value: String): Long {
return value.mapIndexed { index, c ->
val v = map(c)
val exp = value.length - index - 1
(Math.pow(5.0, exp.toDouble()) * v).toLong()
}.sum()
}
fun decToSnafu(value: Long): String {
var s = ""
var modValue = value
while (modValue != 0L) {
var m5 = modValue % 5
if (m5 > 2) {
m5 -= 5
}
s = map(m5.toInt()) + s
modValue -= m5
modValue /= 5
}
return s
}
/** Sums SNAFU numbers digit by digit. */
fun sum(a: String, b: String) : String {
val aa = a.reversed()
val bb = b.reversed()
var result = ""
var cc = 0
for (i in 0 .. max(a.length, b.length)) {
val ac = map(aa.getOrElse(i) { '0' })
val bc = map(bb.getOrElse(i) { '0' })
val abc = ac + bc + cc
var abcMod = abc % 5
if (abcMod > 2) {
abcMod -= 5
} else if (abcMod < -2) {
abcMod += 5
}
result = map(abcMod) + result
cc = (abc - abcMod) / 5
}
return result.trimStart { it == '0' }
}
fun part1DecToSnafuToDec(): String {
val decValue = lines.map {
snafuToDec(it)
}.sum()
return decToSnafu(decValue)
}
fun part1(): String {
return lines.reduce(this::sum)
}
}
fun main() {
val day = "25".toInt()
val todayTest = Day25(readInput(day, 2022, true))
execute(todayTest::part1, "Day[Test] $day: pt 1", "2=-1=0")
val today = Day25(readInput(day, 2022))
execute(today::part1DecToSnafuToDec, "Day $day: pt 1", "2-2=21=0021=-02-1=-0")
execute(today::part1, "Day $day: pt 1", "2-2=21=0021=-02-1=-0")
}
| 0 |
Kotlin
| 1 | 2 |
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
| 2,089 |
aoc2022
|
Apache License 2.0
|
aoc-2023/src/main/kotlin/aoc/aoc12b.kts
|
triathematician
| 576,590,518 | false |
{"Kotlin": 615974}
|
import aoc.AocParser.Companion.parselines
import aoc.*
import aoc.util.getDayInput
val testInput = """
???.### 1,1,3
.??..??...?##. 1,1,3
?#?#?#?#?#?#?#? 1,3,1,6
????.#...#... 4,1,1
????.######..#####. 1,6,5
?###???????? 3,2,1
""".parselines
class Springs(_line: String, val nums: List<Int>) {
val max = nums.maxOrNull()!!
val line = "." + _line
.replace("?" + "#".repeat(max), "." + "#".repeat(max))
.replace("#".repeat(max) + "?", "#".repeat(max) + ".")
.replace("[.]+".toRegex(), ".")
// create five copies of line joined by "?"
fun unfold() = Springs(
"." +
(1..5).joinToString("?") { line.drop(1) },
(1..5).flatMap { nums }
)
fun arrangements() = arrangements(line, nums)
fun arrangements2(print: Boolean): Long {
val res2 = arrangementsCached(line, nums)
if (print) {
println("$line $nums res2 $res2")
// val res = arrangements(line, nums)
// if (res != res2) {
// println("$line $nums res $res != res2 $res2")
// }
}
return res2
}
}
fun arrangements(str: String, nums: List<Int>): Long {
if ('?' !in str) {
val match = str.split("\\.+".toRegex()).map { it.length }.filter { it > 0 } == nums
return if (match) 1 else 0
}
val option1 = str.replaceFirst('?', '#')
val option2 = str.replaceFirst('?', '.')
return arrangements(option1, nums) + arrangements(option2, nums)
}
val cache = mutableMapOf<String, Long>()
fun arrangementsCached(str: String, nums: List<Int>): Long {
if (str.length > 30)
return arrangements3(str, nums)
val case = "$str ${nums.joinToString(",")}"
if (case in cache)
return cache[case]!!
val res = arrangements3(str, nums)
cache[case] = res
return res
}
fun arrangements3(str: String, nums: List<Int>): Long {
if (nums.isEmpty())
return if ('#' in str) 0 else 1
val remainder = nums.sumOf { it + 1 } - 1
if (str.length < remainder)
return 0
// find match in line, where match is sequence of n of ? or #, followed by either ? or . or end of line
val n = nums.first()
val match = "^[.?]*?([#?]{$n}([?.]|$))".toRegex()
val found = match.find(str) ?: return 0
val group1 = found.groups[1]!!
val withThisGroup = arrangements3(str.substring(group1.range.last + 1), nums.drop(1))
val withoutThisGroup = if (group1.value[0] == '#') 0 else
arrangements3(str.substring(group1.range.first + 1), nums)
return withThisGroup + withoutThisGroup
}
fun String.parse() = Springs(chunk(0), chunk(1).split(",").map { it.toInt() })
// part 1
fun List<String>.part1(): Long = sumOf {
print(".")
it.parse().arrangements2(print = false)
}.also { println() }
// part 2
fun List<String>.part2(): Long = withIndex().sumOf {
val mod = (size / 100).coerceAtLeast(1)
if (it.index % mod == 0)
print("x")
else
print(".")
it.value.parse().unfold().arrangements2(print = false)
}.also { println() }
// calculate answers
val day = 12
val input = getDayInput(day, 2023)
val testResult = testInput.part1().also { it.print }
val answer1 = input.part1().also { it.print }
val testResult2 = testInput.part2().also { it.print }
val answer2 = input.part2().also { it.print }
// print results
AocRunner(day,
test = { "$testResult, $testResult2" },
part1 = { answer1 },
part2 = { answer2 }
).run()
| 0 |
Kotlin
| 0 | 0 |
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
| 3,468 |
advent-of-code
|
Apache License 2.0
|
src/main/kotlin/day7.kt
|
Gitvert
| 725,292,325 | false |
{"Kotlin": 97000}
|
fun day7 (lines: List<String>) {
day7part1(lines)
day7part2(lines)
}
fun day7part2(lines: List<String>) {
val cards = parseCamelCards(lines)
cards.forEach { it.handStrength = findHandStrength(replaceJokers(it)) }
cards.forEach {
it.cards = it.cards
.replace("A", "Z")
.replace("K", "Y")
.replace("Q", "X")
.replace("J", "1")
.replace("T", "U")
}
var sum = 0L
cards.sortedWith(compareBy({ it.handStrength }, { it.cards })).forEachIndexed { index, card ->
sum += (index + 1) * card.bid
}
println("Day 7 part 2: $sum")
println()
}
fun day7part1(lines: List<String>) {
val cards = parseCamelCards(lines)
cards.forEach { it.handStrength = findHandStrength(it) }
cards.forEach {
it.cards = it.cards
.replace("A", "Z")
.replace("K", "Y")
.replace("Q", "X")
.replace("J", "V")
.replace("T", "U")
}
var sum = 0L
cards.sortedWith(compareBy({ it.handStrength }, { it.cards })).forEachIndexed { index, card ->
sum += (index + 1) * card.bid
}
println("Day 7 part 1: $sum")
}
fun findHandStrength(hand: CamelCardsHand): Int {
val sortedCardOccurrences = hand.cards.groupingBy { it }.eachCount().entries.map { it.value.toString()[0] }.sortedDescending()
if (sortedCardOccurrences[0] == '5') {
return 7
} else if (sortedCardOccurrences[0] == '4') {
return 6
} else if (sortedCardOccurrences[0] == '3') {
return if (sortedCardOccurrences[1] == '2') {
5
} else {
4
}
} else if (sortedCardOccurrences[0] == '2') {
return if (sortedCardOccurrences[1] == '2') {
3
} else {
2
}
} else {
return 1
}
}
fun replaceJokers(hand: CamelCardsHand): CamelCardsHand {
val sortedCardOccurrences = hand.cards.groupingBy { it }.eachCount().entries.map { it.value.toString() + it.key.toString() }.sortedDescending()
if (hand.cards.contains("J")) {
for (i in sortedCardOccurrences.indices) {
if (!sortedCardOccurrences[i].contains("J")) {
return CamelCardsHand(
hand.cards.replace("J", sortedCardOccurrences[i][1].toString()),
hand.bid,
0
)
}
}
}
return hand
}
fun parseCamelCards(lines: List<String>): List<CamelCardsHand> {
val cards = mutableListOf<CamelCardsHand>()
lines.forEach {
cards.add(CamelCardsHand(it.split(" ")[0], it.split(" ")[1].toLong(), 0))
}
return cards
}
data class CamelCardsHand(var cards: String, val bid: Long, var handStrength: Int)
| 0 |
Kotlin
| 0 | 0 |
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
| 2,817 |
advent_of_code_2023
|
MIT License
|
src/main/kotlin/SevenSegments_8.kt
|
Flame239
| 433,046,232 | false |
{"Kotlin": 64209}
|
val digitLines: List<DigitLine> by lazy {
readFile("SevenSegments").split("\n").map {
val (signal, output) = it.split(" | ")
DigitLine(signal.split(" ").map { it.sortAlphabetically() }, output.split(" ").map { it.sortAlphabetically() })
}
}
val mapCharsToDigit = mapOf(
Pair("abcefg", "0"),
Pair("cf", "1"),
Pair("acdeg", "2"),
Pair("acdfg", "3"),
Pair("bcdf", "4"),
Pair("abdfg", "5"),
Pair("abdefg", "6"),
Pair("acf", "7"),
Pair("abcdefg", "8"),
Pair("abcdfg", "9"),
)
val commonCharsFor5 = listOf('a', 'd', 'g')
val commonCharsFor6 = listOf('a', 'b', 'f', 'g')
val digits1 = listOf('c', 'f')
val digits4 = listOf('b', 'c', 'd', 'f')
val digits7 = listOf('a', 'c', 'f')
fun countUniqueDigits(): Int =
digitLines.sumOf { it.outputDigits.count { d -> d.length == 2 || d.length == 3 || d.length == 4 || d.length == 7 } }
fun findMappingsAndCalculate(): Int {
var total = 0
for (line in digitLines) {
val mapping = mappingsTemplate()
restrictMappingForNonUniqueDigit(line.signalDigits, mapping, 5, commonCharsFor5)
restrictMappingForNonUniqueDigit(line.signalDigits, mapping, 6, commonCharsFor6)
restrictMappingForUniqueDigit(line.signalDigits, mapping, digits1)
restrictMappingForUniqueDigit(line.signalDigits, mapping, digits7)
restrictMappingForUniqueDigit(line.signalDigits, mapping, digits4)
repeat(7) {
mapping.filter { it.value.size == 1 }.forEach {
val decidedChar = it.value.first()
val originalKey = it.key
mapping.forEach { entry -> if (entry.key != originalKey) entry.value.remove(decidedChar) }
}
}
val charMapping = mapping.mapValues { it.value.first() }
val actualDigits = line.outputDigits
.map { it.map { c -> charMapping[c]!! }.sorted().joinToString(separator = "") }
val resultNumber = actualDigits.map { mapCharsToDigit[it]!! }.joinToString(separator = "").toInt()
total += resultNumber
}
return total
}
fun restrictMappingForNonUniqueDigit(
inputDigits: List<String>,
mapping: MutableMap<Char, MutableSet<Char>>,
charsLen: Int,
commonChars: List<Char>
) {
val curCommon = inputDigits
.filter { it.length == charsLen }
.map { it.toSet() }
.reduce { acc, set -> set.intersect(acc) }
curCommon.forEach { mapping[it] = mapping[it]!!.intersect(commonChars) as MutableSet }
}
fun restrictMappingForUniqueDigit(
inputDigits: List<String>,
mapping: MutableMap<Char, MutableSet<Char>>,
digitChars: List<Char>
) {
val curChars = inputDigits
.filter { it.length == digitChars.size }
.map { it.toSet() }
.first()
curChars.forEach { mapping[it] = mapping[it]!!.intersect(digitChars) as MutableSet }
}
fun mappingsTemplate(): MutableMap<Char, MutableSet<Char>> {
val mapping = mutableMapOf<Char, MutableSet<Char>>()
for (i in 0 until 7) {
mapping['a' + i] = mutableSetOf('a', 'b', 'c', 'd', 'e', 'f', 'g')
}
return mapping
}
fun main() {
println(countUniqueDigits())
println(findMappingsAndCalculate())
}
data class DigitLine(val signalDigits: List<String>, val outputDigits: List<String>)
| 0 |
Kotlin
| 0 | 0 |
ef4b05d39d70a204be2433d203e11c7ebed04cec
| 3,302 |
advent-of-code-2021
|
Apache License 2.0
|
src/main/kotlin/Day16.kt
|
Vampire
| 572,990,104 | false |
{"Kotlin": 57326}
|
import kotlin.math.max
fun main() {
data class Valve(
val name: String,
val flowRate: Int,
val reachableValveNames: List<String>
) {
val reachableValves = mutableListOf<Valve>()
}
val inputPattern = """Valve (?<valveName>\w++) has flow rate=(?<flowRate>\d++); (?:tunnels lead to valves|tunnel leads to valve) (?<reachableValves>.*)""".toPattern()
fun parseValveNetwork(input: List<String>) = input
.map {
val matcher = inputPattern.matcher(it)
check(matcher.matches())
Valve(
name = matcher.group("valveName"),
flowRate = matcher.group("flowRate").toInt(),
reachableValveNames = matcher.group("reachableValves").split(", ")
)
}
.also { valves ->
valves.forEach { valve ->
valve
.reachableValveNames
.map { valveName -> valves.find { it.name == valveName }!! }
.forEach(valve.reachableValves::add)
}
}
data class ValveWithPath(val valve: Valve) {
val path = mutableListOf<Valve>()
val distance get() = path.size
}
val shortestPathsCache = mutableMapOf<Valve, Map<Valve, ValveWithPath>>()
fun calculateShortestPaths(valves: List<Valve>, start: Valve): Map<Valve, ValveWithPath> {
var current: ValveWithPath? = null
val visited = mutableSetOf<ValveWithPath>()
val unvisited = valves.map {
ValveWithPath(it).also { result ->
if (it == start) {
current = result
} else {
result.path.addAll(valves)
}
}
}.toMutableSet()
while (unvisited.isNotEmpty()) {
current!!
.valve
.reachableValves
.mapNotNull { valve -> unvisited.find { it.valve.name == valve.name } }
.forEach {
if (current!!.distance + 1 < it.distance) {
it.path.clear()
it.path.addAll(current!!.path)
it.path.add(it.valve)
}
}
visited.add(current!!)
unvisited.remove(current)
current = unvisited.minByOrNull(ValveWithPath::distance)
}
return visited.associateBy { it.valve }
}
fun getMaxSteamRecursive(
valves: List<Valve>,
start: Valve,
closedValves: Set<Valve>,
remainingTime: Int,
releasedSteam: Int,
maxSteam: Array<Int>
): Int {
if ((closedValves.sumOf { remainingTime * it.flowRate } + releasedSteam + (remainingTime * start.flowRate)) <= maxSteam[0]) {
return 0
}
return shortestPathsCache
.computeIfAbsent(start) { key -> calculateShortestPaths(valves, key) }
.values
.asSequence()
.filter { it.valve in closedValves }
.filter { (remainingTime - (it.distance + 1)) > 0 }
.let { possibleNextValves ->
possibleNextValves.maxOfOrNull {
getMaxSteamRecursive(
valves = valves,
start = it.valve,
closedValves = closedValves.filterNot(it.valve::equals).toSet(),
remainingTime = remainingTime - (it.distance + 1),
releasedSteam = releasedSteam + (remainingTime * start.flowRate),
maxSteam = maxSteam
)
} ?: (releasedSteam + (remainingTime * start.flowRate))
}
.also { maxSteam[0] = max(it, maxSteam[0]) }
}
fun getMaxSteamRecursiveWithElephant(
valves: List<Valve>,
currentValve: Valve?,
currentValveElephant: Valve?,
currentTarget: Valve?,
currentTargetElephant: Valve?,
openValves: Set<Valve>,
closedValves: Set<Valve>,
remainingTime: Int,
releasedSteam: Int,
maxSteam: Array<Int>
): Int {
check(remainingTime >= 0) {
"Algorithm error"
}
if ((valves.sumOf { remainingTime * it.flowRate } + releasedSteam) <= maxSteam[0]) {
return 0
}
val newReleasedSteam = releasedSteam + openValves.sumOf { it.flowRate }
val shortestPaths = if (currentValve == null) mapOf() else shortestPathsCache.computeIfAbsent(currentValve) { key ->
calculateShortestPaths(valves, key)
}
val shortestPathsElephant = if (currentValveElephant == null) mapOf() else shortestPathsCache.computeIfAbsent(currentValveElephant) { key ->
calculateShortestPaths(valves, key)
}
return if ((currentTarget != currentValve) && (currentTargetElephant != currentValveElephant)) {
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = shortestPaths[currentTarget]!!.path.first(),
currentValveElephant = shortestPathsElephant[currentTargetElephant]!!.path.first(),
currentTarget = currentTarget,
currentTargetElephant = currentTargetElephant,
openValves = openValves,
closedValves = closedValves,
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
} else if ((currentTarget == currentValve) && (currentTargetElephant != currentValveElephant)) {
if (currentValve in openValves) {
shortestPaths
.values
.asSequence()
.filter { it.valve in closedValves }
.filter { (remainingTime - (it.distance + 1)) > 0 }
.let { possibleNextValves ->
possibleNextValves.maxOfOrNull { nextValve ->
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = nextValve.path.first(),
currentValveElephant = shortestPathsElephant[currentTargetElephant]!!.path.first(),
currentTarget = nextValve.valve,
currentTargetElephant = currentTargetElephant,
openValves = openValves,
closedValves = closedValves.filter { it != nextValve.valve }.toSet(),
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
} ?: getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = null,
currentValveElephant = shortestPathsElephant[currentTargetElephant]!!.path.first(),
currentTarget = null,
currentTargetElephant = currentTargetElephant,
openValves = openValves,
closedValves = closedValves,
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
}
} else {
val newOpenValves = openValves + currentValve
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = currentValve,
currentValveElephant = shortestPathsElephant[currentTargetElephant]!!.path.first(),
currentTarget = currentTarget,
currentTargetElephant = currentTargetElephant,
openValves = newOpenValves.filterNotNull().toSet(),
closedValves = closedValves,
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
}
} else if ((currentTarget != currentValve) && (currentTargetElephant == currentValveElephant)) {
if (currentValveElephant in openValves) {
shortestPathsElephant
.values
.asSequence()
.filter { it.valve in closedValves }
.filter { (remainingTime - (it.distance + 1)) > 0 }
.let { possibleNextValves ->
possibleNextValves.maxOfOrNull { nextValve ->
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = shortestPaths[currentTarget]!!.path.first(),
currentValveElephant = nextValve.path.first(),
currentTarget = currentTarget,
currentTargetElephant = nextValve.valve,
openValves = openValves,
closedValves = closedValves.filter { it != nextValve.valve }.toSet(),
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
} ?: getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = shortestPaths[currentTarget]!!.path.first(),
currentValveElephant = null,
currentTarget = currentTarget,
currentTargetElephant = null,
openValves = openValves,
closedValves = closedValves,
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
}
} else {
val newOpenValves = openValves + currentValveElephant
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = shortestPaths[currentTarget]!!.path.first(),
currentValveElephant = currentValveElephant,
currentTarget = currentTarget,
currentTargetElephant = currentTargetElephant,
openValves = newOpenValves.filterNotNull().toSet(),
closedValves = closedValves,
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
}
} else {
check((currentTarget == currentValve) && (currentTargetElephant == currentValveElephant)) {
"Algorithm error"
}
if ((currentValve == null) && (currentValveElephant == null)) {
return (newReleasedSteam + ((remainingTime - 1) * openValves.sumOf { it.flowRate }))
} else if (currentValve in openValves) {
if (currentValveElephant in openValves) {
shortestPaths
.values
.asSequence()
.filter { it.valve in closedValves }
.filter { (remainingTime - (it.distance + 1)) > 0 }
.let { possibleNextValves ->
possibleNextValves.maxOfOrNull { nextValve ->
shortestPathsElephant
.values
.asSequence()
.filter { (it.valve in closedValves) && (it.valve != nextValve.valve) }
.filter { (remainingTime - (it.distance + 1)) > 0 }
.let { possibleNextValvesElephant ->
possibleNextValvesElephant.maxOfOrNull { nextValveElephant ->
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = nextValve.path.first(),
currentValveElephant = nextValveElephant.path.first(),
currentTarget = nextValve.valve,
currentTargetElephant = nextValveElephant.valve,
openValves = openValves,
closedValves = closedValves.filter { (it != nextValve.valve) && (it != nextValveElephant.valve) }.toSet(),
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
} ?: getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = nextValve.path.first(),
currentValveElephant = null,
currentTarget = nextValve.valve,
currentTargetElephant = null,
openValves = openValves,
closedValves = closedValves.filter { it != nextValve.valve }.toSet(),
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
}
} ?: shortestPathsElephant
.values
.asSequence()
.filter { it.valve in closedValves }
.filter { (remainingTime - (it.distance + 1)) > 0 }
.let { possibleNextValvesElephant ->
possibleNextValvesElephant.maxOfOrNull { nextValveElephant ->
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = null,
currentValveElephant = nextValveElephant.path.first(),
currentTarget = null,
currentTargetElephant = nextValveElephant.valve,
openValves = openValves,
closedValves = closedValves.filter { it != nextValveElephant.valve }.toSet(),
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
} ?: ((remainingTime - 1) * openValves.sumOf { it.flowRate })
}
}
} else {
val newOpenValves = openValves + currentValveElephant
shortestPaths
.values
.asSequence()
.filter { it.valve in closedValves }
.filter { (remainingTime - (it.distance + 1)) > 0 }
.let { possibleNextValves ->
possibleNextValves.maxOfOrNull { nextValve ->
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = nextValve.path.first(),
currentValveElephant = currentValveElephant,
currentTarget = nextValve.valve,
currentTargetElephant = currentTargetElephant,
openValves = newOpenValves.filterNotNull().toSet(),
closedValves = closedValves.filter { it != nextValve.valve }.toSet(),
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
} ?: getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = null,
currentValveElephant = currentValveElephant,
currentTarget = null,
currentTargetElephant = currentTargetElephant,
openValves = newOpenValves.filterNotNull().toSet(),
closedValves = closedValves,
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
}
}
} else {
if (currentValveElephant in openValves) {
val newOpenValves = openValves + currentValve
shortestPathsElephant
.values
.asSequence()
.filter { it.valve in closedValves }
.filter { (remainingTime - (it.distance + 1)) > 0 }
.let { possibleNextValves ->
possibleNextValves.maxOfOrNull { nextValve ->
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = currentValve,
currentValveElephant = nextValve.path.first(),
currentTarget = currentTarget,
currentTargetElephant = nextValve.valve,
openValves = newOpenValves.filterNotNull().toSet(),
closedValves = closedValves.filter { it != nextValve.valve }.toSet(),
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
} ?: getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = currentValve,
currentValveElephant = null,
currentTarget = currentTarget,
currentTargetElephant = null,
openValves = newOpenValves.filterNotNull().toSet(),
closedValves = closedValves,
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
}
} else {
val newOpenValves = openValves + currentValve + currentValveElephant
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = currentValve,
currentValveElephant = currentValveElephant,
currentTarget = currentTarget,
currentTargetElephant = currentTargetElephant,
openValves = newOpenValves.filterNotNull().toSet(),
closedValves = closedValves,
remainingTime = remainingTime - 1,
releasedSteam = newReleasedSteam,
maxSteam = maxSteam
)
}
}
}
.also { maxSteam[0] = max(it, maxSteam[0]) }
}
fun part1(input: List<String>) = parseValveNetwork(input)
.let { valves ->
getMaxSteamRecursive(
valves = valves,
start = valves.find { it.name == "AA" }!!,
closedValves = valves.filter { it.flowRate != 0 }.toSet(),
remainingTime = 30,
releasedSteam = 0,
maxSteam = arrayOf(0)
)
}
fun part2(input: List<String>) = parseValveNetwork(input)
.let { valves ->
val aa = valves.find { it.name == "AA" }!!
check(aa.flowRate == 0) {
"flowRate of AA should be 0 but was ${aa.flowRate}"
}
getMaxSteamRecursiveWithElephant(
valves = valves,
currentValve = aa,
currentValveElephant = aa,
currentTarget = aa,
currentTargetElephant = aa,
openValves = setOf(aa),
closedValves = valves.filter { it.flowRate != 0 }.toSet(),
remainingTime = 26,
releasedSteam = 0,
maxSteam = arrayOf(0)
)
}
val testInput = readStrings("Day16_test")
check(part1(testInput) == 1_651)
val input = readStrings("Day16")
println(part1(input))
check(part2(testInput) == 1_707)
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f
| 22,359 |
aoc-2022
|
Apache License 2.0
|
src/Day16.kt
|
buczebar
| 572,864,830 | false |
{"Kotlin": 39213}
|
fun main() {
lateinit var flowRates: Map<String, Int>
lateinit var connections: Map<String, List<String>>
lateinit var workingValves: List<String>
lateinit var distances: Map<Pair<String, String>, Int>
fun getDistanceToValve(
current: String,
destination: String,
visited: List<String> = emptyList(),
depth: Int = 1
): Int {
val nextValves =
(connections[current]!!).filter { !visited.contains(it) }.takeIf { it.isNotEmpty() }
?: return Int.MAX_VALUE
return if (nextValves.contains(destination)) {
depth
} else {
val newVisited = visited + current
nextValves.minOf { getDistanceToValve(it, destination, newVisited, depth + 1) }
}
}
fun parseInput(fileName: String) {
val valves = mutableMapOf<String, Int>()
val tunnels = mutableMapOf<String, List<String>>()
readInput(fileName)
.map { it.split(";") }
.forEach { (valveRaw, tunnelsRaw) ->
val label = valveRaw.getAllByRegex("[A-Z][A-Z]".toRegex()).single()
val flowRate = valveRaw.getAllInts().single()
val accessibleValves = tunnelsRaw.getAllByRegex("[A-Z][A-Z]".toRegex())
valves[label] = flowRate
tunnels[label] = accessibleValves
}
flowRates = valves
connections = tunnels
workingValves = flowRates.keys.filter { flowRates[it]!! > 0 }
}
fun calculateDistancesBetweenValves(valves: List<String>): Map<Pair<String, String>, Int> {
val resultDistances = mutableMapOf<Pair<String, String>, Int>()
for (start in valves) {
for (end in valves) {
resultDistances[start to end] = getDistanceToValve(start, end)
}
}
return resultDistances
}
fun maxPath(node: String, countDown: Int, opened: Set<String> = emptySet(), pressure: Int = 0): Int {
val nextOpened = opened + node
val openedFlowRate = nextOpened.sumOf { flowRates[it]!! }
return distances
.filter { (path, distance) -> path.first == node && !opened.contains(path.second) && distance <= countDown - 1 }
.map { (path, distance) -> Pair(path.second, distance) }
.map { (nextNode, distance) ->
val nextCountDown = countDown - distance - 1
val nextPressure = pressure + (distance + 1) * openedFlowRate
maxPath(nextNode, nextCountDown, nextOpened, nextPressure)
}.plus(pressure + countDown * openedFlowRate)
.max()
}
fun part1(): Int {
val startingValve = "AA"
distances = calculateDistancesBetweenValves(workingValves + startingValve)
return maxPath(startingValve, 30)
}
parseInput("Day16_test")
check(part1() == 1651)
parseInput("Day16")
println(part1())
}
| 0 |
Kotlin
| 0 | 0 |
cdb6fe3996ab8216e7a005e766490a2181cd4101
| 2,961 |
advent-of-code
|
Apache License 2.0
|
src/year2022/day15/Day15.kt
|
lukaslebo
| 573,423,392 | false |
{"Kotlin": 222221}
|
package year2022.day15
import check
import readInput
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day15_test")
check(part1(testInput, 10), 26)
check(part2(testInput, 20), 56000011)
val input = readInput("2022", "Day15")
println(part1(input, 2000000)) // 4919281
println(part2(input, 4000000)) // 12630143363767
}
private fun part1(input: List<String>, lineY: Int): Int {
val sensorToBeaconPos = parseSensorToBeaconPos(input)
val sensorsToDistance = sensorToBeaconPos.map { Pair(it.first, it.first - it.second) }
val minX = sensorsToDistance.minOf {
val (sensor, distance) = it
sensor.x - distance
}
val maxX = sensorsToDistance.maxOf {
val (sensor, distance) = it
sensor.x + distance
}
val line = Array(maxX - minX + 1) { '.' }
sensorToBeaconPos.forEach { pair ->
val (sensorPos, beaconPos) = pair
if (sensorPos.y == lineY) line[sensorPos.x - minX] = 'S'
if (beaconPos.y == lineY) line[beaconPos.x - minX] = 'B'
val distance = abs(sensorPos.x - beaconPos.x) + abs(sensorPos.y - beaconPos.y)
val deltaY = abs(sensorPos.y - lineY)
val deltaX = distance - deltaY
if (deltaX > 0) {
for (dx in -deltaX..deltaX) {
val x = sensorPos.x - minX + dx
if (x >= 0 && x <= line.lastIndex && line[x] == '.') line[x] = '#'
}
}
}
return line.count { it == '#' }
}
private fun part2(input: List<String>, limit: Int): Long {
val sensorToBeaconPos = parseSensorToBeaconPos(input)
val blockedBySensorOrBeacon = sensorToBeaconPos.flatMapTo(hashSetOf()) { it.toList() }
val sensorsWithDistance = sensorToBeaconPos.map {
val (sensorPos, beaconPos) = it
val distance = sensorPos - beaconPos
Pair(sensorPos, distance)
}
var x = 0
var y = 0
while (y <= limit) {
while (x <= limit) {
val pos = Pos(x, y)
val blockingSensor = sensorsWithDistance.firstOrNull {
it.first - pos <= it.second
}
if (blockingSensor != null) {
val sensorPos = blockingSensor.first
x = sensorPos.x + blockingSensor.second - abs(sensorPos.y - y) + 1
continue
}
if (pos !in blockedBySensorOrBeacon) {
return x.toLong() * 4000000L + y.toLong()
}
x++
}
x = 0
y++
}
error("!")
}
private data class Pos(val x: Int, val y: Int) {
operator fun minus(other: Pos): Int {
return abs(x - other.x) + abs(y - other.y)
}
}
private fun parseSensorToBeaconPos(input: List<String>): List<Pair<Pos, Pos>> {
return input.map { line ->
line.substringAfter("Sensor at ").split(": closest beacon is at ").map { hint ->
val (x, y) = hint.split(", ").map { coord -> coord.substringAfter("=").toInt() }
Pos(x, y)
}
}.map { pair ->
Pair(pair[0], pair[1])
}
}
private fun List<Pair<Pos, Pos>>.minPos(): Pos {
var minX = Int.MAX_VALUE
var minY = Int.MAX_VALUE
forEach {
minX = min(it.first.x, minX)
minX = min(it.second.x, minX)
minY = min(it.first.y, minY)
minY = min(it.second.y, minY)
}
return Pos(minX, minY)
}
private fun List<Pair<Pos, Pos>>.maxPos(): Pos {
var maxX = Int.MIN_VALUE
var maxY = Int.MIN_VALUE
forEach {
maxX = max(it.first.x, maxX)
maxX = max(it.second.x, maxX)
maxY = max(it.first.y, maxY)
maxY = max(it.second.y, maxY)
}
return Pos(maxX, maxY)
}
| 0 |
Kotlin
| 0 | 1 |
f3cc3e935bfb49b6e121713dd558e11824b9465b
| 3,805 |
AdventOfCode
|
Apache License 2.0
|
aoc-2021/src/main/kotlin/nerok/aoc/aoc2021/day04/Day04.kt
|
nerok
| 572,862,875 | false |
{"Kotlin": 113337}
|
package nerok.aoc.aoc2021.day04
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun calculateScore(bingoBoard: List<MutableList<Int>>, drawing: List<Int>): Pair<Int, Int> {
drawing.forEachIndexed { drawNumber, draw ->
bingoBoard.mapIndexed { index, ints ->
if (ints.contains(draw)) {
index to ints.indexOf(draw)
}
else {
null
}
}.filterNotNull().forEach { coordinate ->
bingoBoard[coordinate.first][coordinate.second] = 0
if (bingoBoard[coordinate.first].none { it != 0 }) {
return drawNumber to bingoBoard.sumOf { it.sum() } * drawing[drawNumber]
}
else if (bingoBoard.map { row -> row[coordinate.second] }.none { it != 0 }) {
return drawNumber to bingoBoard.sumOf { it.sum() } * drawing[drawNumber]
}
}
}
return 0 to 0
}
fun part1(input: List<String>): Long {
val drawings = input.first().split(",").map { it.toInt() }
return input.drop(1).asSequence()
.windowed(6, step = 6)
.map { board ->
board.filter { it.isNotEmpty() }
}
.map { board ->
board.map { row ->
row.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.toMutableList()
}
}
.map { board ->
calculateScore(board, drawings)
}
.minBy { it.first }.second.toLong()
}
fun part2(input: List<String>): Long {
val drawings = input.first().split(",").map { it.toInt() }
return input.drop(1).asSequence()
.windowed(6, step = 6)
.map { board ->
board.filter { it.isNotEmpty() }
}
.map { board ->
board.map { row ->
row.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.toMutableList()
}
}
.map { board ->
calculateScore(board, drawings)
}
.maxBy { it.first }.second.toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day04_test")
check(part1(testInput) == 4512L)
check(part2(testInput) == 1924L)
val input = Input.readInput("Day04")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
| 0 |
Kotlin
| 0 | 0 |
7553c28ac9053a70706c6af98b954fbdda6fb5d2
| 2,866 |
AOC
|
Apache License 2.0
|
src/Day23.kt
|
azat-ismagilov
| 573,217,326 | false |
{"Kotlin": 75114}
|
fun main() {
val day = 23
data class Position(val x: Int, val y: Int) {
fun move(direction: Int) = when (direction.mod(4)) {
0 -> copy(x = x - 1)
1 -> copy(x = x + 1)
2 -> copy(y = y - 1)
else -> copy(y = y + 1)
}
fun needToCheck(direction: Int) = when (direction.mod(4)) {
0, 1 -> move(direction).let { listOf(it, it.move(2), it.move(3)) }
else -> move(direction).let { listOf(it, it.move(0), it.move(1)) }
}
fun hasAnyNeighbours(takenPosition: Set<Position>): Boolean {
for (newX in x - 1..x + 1)
for (newY in y - 1..y + 1)
if (copy(x = newX, y = newY).let { it != this && it in takenPosition })
return true
return false
}
fun tryMove(takenPosition: Set<Position>, startDirection: Int): Position {
if (!hasAnyNeighbours(takenPosition))
return this
for (direction in startDirection..startDirection + 3)
if (needToCheck(direction).all { it !in takenPosition })
return move(direction)
return this
}
}
fun prepareInput(input: List<String>): Set<Position> {
val takenPositions = mutableSetOf<Position>()
for (x in input.indices)
for (y in input[x].indices)
if (input[x][y] == '#')
takenPositions.add(Position(x, y))
return takenPositions
}
fun <T> Iterable<T>.distance(cmp: (T) -> Int) = maxOf(cmp) - minOf(cmp) + 1
fun calculateAnswer(takenPositions: Set<Position>) =
takenPositions.distance { it.x } * takenPositions.distance { it.y } - takenPositions.size
fun part1(input: List<String>): Int {
var takenPositions = prepareInput(input)
repeat(10) { startDirection ->
val futurePositions = takenPositions.associateWith { it.tryMove(takenPositions, startDirection) }
val uniquePositions = futurePositions.values.groupBy { it }.filterValues { it.size == 1 }.keys
takenPositions = futurePositions.map { (from, to) -> if (to in uniquePositions) to else from }.toSet()
}
return calculateAnswer(takenPositions)
}
fun part2(input: List<String>): Int {
var takenPositions = prepareInput(input)
var startDirection = 0
while (true) {
val futurePositions = takenPositions.associateWith { it.tryMove(takenPositions, startDirection) }
val uniquePositions = futurePositions.values.groupBy { it }.filterValues { it.size == 1 }.keys
val newTakenPositions =
futurePositions.map { (from, to) -> if (to in uniquePositions) to else from }.toSet()
if (newTakenPositions == takenPositions)
break
takenPositions = newTakenPositions
startDirection++
}
return startDirection + 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
abdd1b8d93b8afb3372cfed23547ec5a8b8298aa
| 3,295 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/main/kotlin/day18/Day18.kt
|
qnox
| 575,581,183 | false |
{"Kotlin": 66677}
|
package day18
import readInput
import java.util.BitSet
fun main() {
data class Cube(val x: Int, val y: Int, val z: Int)
data class Limits(val minX: Int, val maxX: Int, val minY: Int, val maxY: Int, val minZ: Int, val maxZ: Int) {
val numX = maxX - minX + 1
val numY = maxY - minY + 1
val numZ = maxZ - minZ + 1
val size: Int = numX * numY * numZ
fun index(x: Int, y: Int, z: Int): Int = if (isValid(x, y, z)) {
(x - minX) * numY * numZ + (y - minY) * numZ + (z - minZ)
} else {
-1
}
private fun isValid(x: Int, y: Int, z: Int) = x in minX..maxX && y in minY..maxY && z in minZ..maxZ
fun neighbours(cube: Cube): List<Cube> {
val x = cube.x
val y = cube.y
val z = cube.z
val result = listOf<Cube>(
Cube(x + 1, y, z),
Cube(x - 1, y, z),
Cube(x, y + 1, z),
Cube(x, y - 1, z),
Cube(x, y, z + 1),
Cube(x, y, z - 1)
).filter {
isValid(it.x, it.y, it.z)
}
return result
}
fun neighbours(x: Int, y: Int, z: Int): List<Int> {
val result = mutableListOf<Int>()
index(x + 1, y, z).takeIf { it >= 0 }?.let { result.add(it) }
index(x - 1, y, z).takeIf { it >= 0 }?.let { result.add(it) }
index(x, y + 1, z).takeIf { it >= 0 }?.let { result.add(it) }
index(x, y - 1, z).takeIf { it >= 0 }?.let { result.add(it) }
index(x, y, z + 1).takeIf { it >= 0 }?.let { result.add(it) }
index(x, y, z - 1).takeIf { it >= 0 }?.let { result.add(it) }
return result
}
}
fun parseInput(input: List<String>): Pair<List<Cube>, Limits> {
val cubes = input.map { it.split(",").let { (x, y, z) -> Cube(x.toInt(), y.toInt(), z.toInt()) } }
val limits = cubes.fold(
Limits(
Int.MAX_VALUE,
Int.MIN_VALUE,
Int.MAX_VALUE,
Int.MIN_VALUE,
Int.MAX_VALUE,
Int.MIN_VALUE
)
) { limits, cube ->
Limits(
minOf(limits.minX, cube.x - 1),
maxOf(limits.maxX, cube.x + 1),
minOf(limits.minY, cube.y - 1),
maxOf(limits.maxY, cube.y + 1),
minOf(limits.minZ, cube.z - 1),
maxOf(limits.maxZ, cube.z + 1),
)
}
return Pair(cubes, limits)
}
fun part1(input: List<String>): Int {
val (cubes, limits) = parseInput(input)
var result = 0
val space = BitSet(limits.size)
cubes.forEach { cube ->
space[limits.index(cube.x, cube.y, cube.z)] = true
result += 6
val neighbours = limits.neighbours(cube.x, cube.y, cube.z).count { space[it] }
result -= 2 * neighbours
}
return result
}
fun part2(input: List<String>): Int {
val (cubes, limits) = parseInput(input)
val space = BitSet(limits.size)
cubes.forEach { cube ->
space[limits.index(cube.x, cube.y, cube.z)] = true
}
val visited = BitSet(limits.size)
val q = ArrayDeque<Cube>()
val start = Cube(limits.minX, limits.minY, limits.minZ)
q.add(start)
visited[limits.index(start.x, start.y, start.z)] = true
var result = 0
while (q.isNotEmpty()) {
val cube = q.removeFirst()
for (n in limits.neighbours(cube)) {
val index = limits.index(n.x, n.y, n.z)
if (space[index]) {
result += 1
} else if (!visited[index]) {
visited[index] = true
q.addLast(n)
}
}
}
return result
}
val testInput = readInput("day18", "test")
val input = readInput("day18", "input")
val part1 = part1(testInput)
println(part1)
check(part1 == 64)
println(part1(input))
val part2 = part2(testInput)
println(part2)
check(part2 == 58)
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
727ca335d32000c3de2b750d23248a1364ba03e4
| 4,268 |
aoc2022
|
Apache License 2.0
|
src/Day02.kt
|
cisimon7
| 573,872,773 | false |
{"Kotlin": 41406}
|
fun main() {
fun abcMap(a: String) = when (a) {
"A" -> HandShape.Rock
"B" -> HandShape.Paper
"C" -> HandShape.Scissors
else -> throw Error("$a is not applicable")
}
fun xyzMap(a: String) = when (a) {
"X" -> HandShape.Rock to Outcome.Loose
"Y" -> HandShape.Paper to Outcome.Draw
"Z" -> HandShape.Scissors to Outcome.Win
else -> throw Error("$a is not applicable")
}
fun part1(input: List<String>): Int {
return input
.map { line -> line.split(" ") }
.map { Pair(it[0], it[1]) }
.map { (elf, me) -> abcMap(elf) to xyzMap(me).first }
.sumOf { (elf, me) -> me.play(elf) }
}
fun part2(input: List<String>): Int {
return input
.map { line -> line.split(" ") }
.map { Pair(it[0], it[1]) }
.map { (elfa, mea) ->
val elf = abcMap(elfa)
when (xyzMap(mea).second) {
Outcome.Draw -> elf to elf
Outcome.Loose -> elf to elf.negative()
Outcome.Win -> elf to elf.positive()
}
}
.sumOf { (elf, me) -> me.play(elf) }
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02_input")
println(part1(input))
println(part2(input))
}
sealed interface HandShape {
val point: Int
object Rock : HandShape {
override val point = 1
}
object Paper : HandShape {
override val point = 2
}
object Scissors : HandShape {
override val point = 3
}
}
fun HandShape.positive(): HandShape {
return when (this) {
HandShape.Paper -> HandShape.Scissors
HandShape.Rock -> HandShape.Paper
HandShape.Scissors -> HandShape.Rock
}
}
fun HandShape.negative(): HandShape {
return when (this) {
HandShape.Paper -> HandShape.Rock
HandShape.Rock -> HandShape.Scissors
HandShape.Scissors -> HandShape.Paper
}
}
sealed interface Outcome {
object Win : Outcome
object Draw : Outcome
object Loose : Outcome
}
val winMatrix: List<List<Double>> = listOf(
listOf(0.5, 0.0, 1.0),
listOf(1.0, 0.5, 0.0),
listOf(0.0, 1.0, 0.5)
)
fun HandShape.play(other: HandShape): Int {
val (idx1, idx2) = listOf(this, other).map { shape ->
listOf(HandShape.Rock, HandShape.Paper, HandShape.Scissors).indexOf(shape)
}
val win = winMatrix[idx1][idx2] * 6
return if (win == 0.0) this.point else (win + this.point).toInt()
}
| 0 |
Kotlin
| 0 | 0 |
29f9cb46955c0f371908996cc729742dc0387017
| 2,651 |
aoc-2022
|
Apache License 2.0
|
src/Day02.kt
|
MarkRunWu
| 573,656,261 | false |
{"Kotlin": 25971}
|
fun main() {
fun calculateScore(shape: Pair<Int, Int>): Int {
val diff = shape.second - shape.first
return shape.second + (if (diff == 0) {
3
} else if ((diff == -2) or (diff == 1)) { // -2: rock - scissors, 1: paper - rock / scissors - paper
6
} else {
0
})
}
fun part1(input: List<String>): Int {
return input.map { it ->
val p = it.split(" ").map {
if ((it == "X") or (it == "A")) {
1 // rock
} else if ((it == "Y") or (it == "B")) {
2 // paper
} else {
3 // scissors
}
}
Pair(p.first(), p.last())
}.sumOf { calculateScore(it) }
}
fun part2(input: List<String>): Int {
return input.map { it ->
val p = it.split(" ").map {
if ((it == "X") or (it == "A")) {
1 // rock / loss
} else if ((it == "Y") or (it == "B")) {
2 // paper / draw
} else {
3 // scissors / win
}
}
Pair(
p.first(), when (val q = p.last()) {
1 -> (3 + (p.first() - 1) - 1) % 3 + 1;
2 -> p.first();
3 -> ((p.first() - 1) + 1) % 3 + 1;
else -> throw IllegalArgumentException("Invalid value range $q");
}
)
}.sumOf { calculateScore(it) }
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
ced885dcd6b32e8d3c89a646dbdcf50b5665ba65
| 1,674 |
AOC-2022
|
Apache License 2.0
|
src/Day04.kt
|
dyomin-ea
| 572,996,238 | false |
{"Kotlin": 21309}
|
import kotlin.math.max
fun main() {
fun IntRange.length(): Int =
last - first + 1
fun String.asRange(): IntRange =
splitBy("-")
.let { it.first.toInt()..it.second.toInt() }
fun String.intoRangePair(): Pair<IntRange, IntRange> =
splitBy(",")
.let { it.first.asRange() to it.second.asRange() }
fun part1(input: List<String>): Int =
input
.map(String::intoRangePair)
.count { (l, r) ->
(l union r).size == max(l.length(), r.length())
}
fun part2(input: List<String>): Int {
return input
.map(String::intoRangePair)
.count { (l, r) ->
(l intersect r).isNotEmpty()
}
}
infix fun String.gr(other: String): Boolean =
length > other.length || length == other.length && this > other
infix fun String.grOrEq(other: String): Boolean =
gr(other) || equals(other)
infix fun String.ls(other: String): Boolean =
length < other.length || length == other.length && this < other
infix fun String.lsOrEq(other: String): Boolean =
ls(other) || equals(other)
fun fullyIntersects(left: Pair<String, String>, right: Pair<String, String>): Boolean {
fun condition(l: Pair<String, String>, r: Pair<String, String>): Boolean =
l.first grOrEq r.first && l.second lsOrEq r.second
return condition(left, right) || condition(right, left)
}
fun partiallyIntersects(left: Pair<String, String>, right: Pair<String, String>): Boolean {
fun String.within(r: Pair<String, String>): Boolean =
this grOrEq r.first && this lsOrEq r.second
fun condition(l: Pair<String, String>, r: Pair<String, String>): Boolean =
l.first.within(r) || l.second.within(r)
return condition(left, right) || condition(right, left)
}
fun part1NoRanges(input: List<String>): Int =
input
.map { pair ->
pair.splitBy(",")
.let { (l, r) ->
l.splitBy("-") to r.splitBy("-")
}
}
.count { (l, r) ->
fullyIntersects(l, r)
}
fun part2NoRanges(input: List<String>): Int =
input
.map { pair ->
pair.splitBy(",")
.let { (l, r) ->
l.splitBy("-") to r.splitBy("-")
}
}
.count { (l, r) ->
partiallyIntersects(l, r)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
check(part1NoRanges(testInput) == 2)
check(part2NoRanges(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part1NoRanges(input))
println(part2(input))
println(part2NoRanges(input))
}
| 0 |
Kotlin
| 0 | 0 |
8aaf3f063ce432207dee5f4ad4e597030cfded6d
| 2,509 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/year2023/Day07.kt
|
forketyfork
| 572,832,465 | false |
{"Kotlin": 142196}
|
package year2023
import year2023.Day07.CardType1
import kotlin.reflect.KClass
class Day07 {
enum class HandType {
HighCard,
OnePair,
TwoPair,
ThreeOfAKind,
FullHouse,
FourOfAKind,
FiveOfAKind
}
interface CardType<T : CardType<T>> : Comparable<T>
enum class CardType1 : CardType<CardType1> { `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, T, J, Q, K, A }
enum class CardType2 : CardType<CardType2> { J, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, T, Q, K, A }
class Hand<T : CardType<T>>(val string: String, klass: KClass<T>) {
val cards: List<T> = string.map { it ->
val parser = if (klass == CardType1::class) CardType1::valueOf else CardType2::valueOf
parser(it.toString()) as T
}
val type: HandType = let {
val cardCounts = cards.groupBy { it }.mapValues { it.value.size }.let { it ->
if (klass == CardType2::class) {
val map = it as Map<CardType2, Int>
if (map.containsKey(CardType2.J)) {
val jokerCount = map[CardType2.J]!!
if (jokerCount == 5) {
return@let it
}
val maxOccurrenceCard = map.filter { it.key != CardType2.J }
.toSortedMap { a, b -> map[a]!!.compareTo(map[b]!!) }
.lastKey()!!
return@let map.filter { it.key != CardType2.J }.mapValues { (key, value) ->
if (key == maxOccurrenceCard) {
value + jokerCount
} else {
value
}
}
}
}
it
}
when (cardCounts.size) {
1 -> HandType.FiveOfAKind
2 -> if (cardCounts.containsValue(4)) {
HandType.FourOfAKind
} else {
HandType.FullHouse
}
3 -> if (cardCounts.containsValue(3)) {
HandType.ThreeOfAKind
} else {
HandType.TwoPair
}
4 -> HandType.OnePair
else -> HandType.HighCard
}
}
}
fun part1(input: String) = solve(input, CardType1::class)
fun part2(input: String) = solve(input, CardType2::class)
fun <T : CardType<T>> solve(input: String, cardTypeKlass: KClass<T>): Long {
return parseInput(input, cardTypeKlass).sortedWith { hand1, hand2 ->
hand1.first.type.compareTo(hand2.first.type).let { compareResult ->
if (compareResult != 0) {
compareResult
} else {
hand1.first.cards.zip(hand2.first.cards).forEach { cardPair ->
cardPair.first.compareTo(cardPair.second).let { compareResult ->
if (compareResult != 0) {
return@sortedWith compareResult
}
}
}
0
}
}
}.mapIndexed { idx, hand -> hand.second * (idx + 1) }.sum()
}
fun <T : CardType<T>> parseInput(input: String, klass: KClass<T>): List<Pair<Hand<T>, Long>> {
return input.lines()
.map { it.split(' ').let { Pair(Hand(it[0], klass), it[1].toLong()) } }
}
}
| 0 |
Kotlin
| 0 | 0 |
5c5e6304b1758e04a119716b8de50a7525668112
| 3,614 |
aoc-2022
|
Apache License 2.0
|
src/y2022/Day13.kt
|
gaetjen
| 572,857,330 | false |
{"Kotlin": 325874, "Mermaid": 571}
|
package y2022
import util.readInput
import util.split
object Day13 {
private fun parse(input: List<String>): List<List<ListItem>> {
return input.split { it.isEmpty() }
.map {
it.map { ln ->
ListItem.of(ln)
}
}
}
sealed class ListItem {
companion object {
fun of(string: String): ListItem {
if (string.count { it == '[' } != string.count { it == ']' }) {
error("opening and closing brackets don't match")
}
if ('[' !in string) {
if (',' in string) error("unexpected comma!")
return ListNumber(string.toInt())
}
val elements = splitOnTopLevelComma(string.drop(1).dropLast(1))
return SubList(elements.map { of(it) })
}
}
fun compareTo(other: ListItem): Int {
return when {
this is ListNumber && other is ListNumber -> this.number - other.number
this is ListNumber && other is SubList -> SubList(listOf(this)).compareTo(other)
this is SubList && other is ListNumber -> this.compareTo(SubList(listOf(other)))
this is SubList && other is SubList -> {
this.list.zip(other.list).map { (ti, oi) ->
ti.compareTo(oi)
}.firstOrNull { it != 0} ?: (this.list.size - other.list.size)
}
else -> error("exhaustive conditions")
}
}
data class ListNumber(val number: Int) : ListItem()
data class SubList(val list: List<ListItem>) : ListItem()
}
private fun splitOnTopLevelComma(str: String): List<String> {
if (str.isEmpty()) return listOf()
return if (str[0] == '[') {
val idx = getIndexOfMatchingClosing(str)
listOf(str.substring(0..idx)) + splitOnTopLevelComma(str.drop(idx + 2))
} else {
val h = str.takeWhile { it != ',' }
val t = str.dropWhile { it != ',' }.drop(1)
listOf(h) + splitOnTopLevelComma(t)
}
}
private fun getIndexOfMatchingClosing(str: String): Int {
var idx = 0
var stackLevel = 1
while (stackLevel != 0) {
idx++
when (str[idx]) {
'[' -> stackLevel++
']' -> stackLevel--
//else -> just continue iterating
}
}
return idx
}
fun part1(input: List<String>): Long {
val items = parse(input)
return items.mapIndexed { index, listItems ->
if (listItems[0].compareTo(listItems[1]) <= 0) {
index + 1
} else {
-1
}
}.filter { it >= 0 }.sum().toLong()
}
fun part2(input: List<String>): Long {
val cmp = Comparator<ListItem> { o1, o2 ->
if (o1 == null || o2 == null) error("did not expect to compare nulls")
o1.compareTo(o2)
}
val items = parse(input).flatten()
val (div1, div2) = parse(listOf("[[2]]", "[[6]]")).flatten()
val sorted = (items + listOf(div1, div2)).sortedWith(cmp)
return (sorted.indexOf(div1) + 1L) * (sorted.indexOf(div2) + 1)
}
}
fun main() {
val testInput = """
[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
""".trimIndent().split("\n")
println("------Tests------")
println(Day13.part1(testInput))
println(Day13.part2(testInput))
println("------Real------")
val input = readInput("resources/2022/day13")
println(Day13.part1(input))
println(Day13.part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
| 4,012 |
advent-of-code
|
Apache License 2.0
|
src/aoc2021/day04/Code.kt
|
ldickmanns
| 572,675,185 | false |
{"Kotlin": 48227}
|
package aoc2021.day04
import readInput
fun main() {
val input = readInput("aoc2021/day04/input")
println(part1(input))
println(part2(input))
}
typealias NumberBoard = Array<IntArray> // IntArrays are the rows
typealias BingoBoard = Array<BooleanArray> // BooleanArrays are the rows
fun part1(input: List<String>): Int {
val inputNumbers = input.first().split(",").map { it.toInt() }
val (numberBoards, bingoBoards) = getBoards(input)
for (inputNumber in inputNumbers) {
val boardBingoZip = numberBoards zip bingoBoards
boardBingoZip.forEach { (boardArray, bingoArray) ->
val bingo = checkNumber(boardArray, bingoArray, inputNumber)
if (bingo) {
val unmarkedSum = getUnmarkedSum(boardArray, bingoArray)
return unmarkedSum * inputNumber
}
}
}
return -1
}
fun getBoards(input: List<String>): Pair<List<NumberBoard>, List<BingoBoard>> {
val boardStrings = input
.drop(2) // input numbers + blank line
.filter { it.isNotEmpty() } // remove blank lines
val boardChunks = boardStrings.chunked(5)
val numberBoards: List<NumberBoard> = boardChunks.map { board: List<String> ->
val boardArray = Array(5) { IntArray(5) }
board.forEachIndexed { rowIndex: Int, row: String ->
val numbers = row
.split(" ")
.filter { it.isNotEmpty() } // single digit numbers result in empty strings
.map { it.toInt() }
numbers.forEachIndexed { columnIndex, number ->
boardArray[rowIndex][columnIndex] = number
}
}
boardArray
}
val bingoBoards: List<BingoBoard> = List(numberBoards.size) {
Array(5) {
BooleanArray(5) { false }
}
}
return Pair(numberBoards, bingoBoards)
}
fun checkNumber(
boardArray: Array<IntArray>,
bingoArray: Array<BooleanArray>,
inputNumber: Int
): Boolean {
boardArray.forEachIndexed { rowIndex, row ->
row.forEachIndexed { columnIndex, number ->
if (number == inputNumber) {
bingoArray[rowIndex][columnIndex] = true
return checkBingo(bingoArray, rowIndex, columnIndex)
}
}
}
return false
}
fun checkBingo(
bingoArray: Array<BooleanArray>,
rowIndex: Int,
columnIndex: Int,
): Boolean {
val rowBingo = bingoArray[rowIndex].all { it }
val columnBingo = bingoArray.map { it[columnIndex] }.all { it }
return rowBingo or columnBingo
}
fun getUnmarkedSum(
boardArray: Array<IntArray>,
bingoArray: Array<BooleanArray>,
): Int {
var sum = 0
bingoArray.forEachIndexed { rowIndex, row ->
row.forEachIndexed { columnIndex, isMarked ->
if (isMarked.not()) sum += boardArray[rowIndex][columnIndex]
}
}
return sum
}
fun part2(input: List<String>): Int {
val inputNumbers = input.first().split(",").map { it.toInt() }
val (numberBoards, bingoBoards) = getBoards(input)
val boardFinished = BooleanArray(numberBoards.size) { false }
for (inputNumber in inputNumbers) {
val boardBingoZip = numberBoards zip bingoBoards
boardBingoZip.forEachIndexed { index, (boardArray, bingoArray) ->
if (boardFinished[index]) return@forEachIndexed
val bingo = checkNumber(boardArray, bingoArray, inputNumber)
if (bingo) boardFinished[index] = true
if (boardFinished.all { it }) {
val unmarkedSum = getUnmarkedSum(boardArray, bingoArray)
return unmarkedSum * inputNumber
}
}
}
return -1
}
| 0 |
Kotlin
| 0 | 0 |
2654ca36ee6e5442a4235868db8174a2b0ac2523
| 3,705 |
aoc-kotlin-2022
|
Apache License 2.0
|
src/day17/Day17.kt
|
maxmil
| 578,287,889 | false |
{"Kotlin": 32792}
|
package day17
import println
import readInputAsText
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
data class Target(val minX: Int, val maxX: Int, val minY: Int, val maxY: Int)
private fun String.parseTarget() = "target area: x=([-\\d]+)..([-\\d]+), y=([-\\d]+)..([-\\d]+)"
.toRegex().matchEntire(this)!!
.groupValues
.drop(1)
.map { it.toInt() }
.let { Target(it[0], it[1], it[2], it[3]) }
/*
If we look only at the y trajectory then it has to pass through 0 as it comes down
since it is symmetrical. The same increments going up happen in reverse going down.
The downward path is a series of triangular numbers and the problem consists in
maximizing these.
The largest possible jump is from 0 to the min y value in the target.
The upward path is the same series of triangular numbers without this last jump.
*/
private fun Target.maxHeightPossible(): Int {
val initialY = -minY - 1
return initialY * (initialY + 1) / 2
}
/*
minX = n(n-1)/2 where n is the initial X velocity
*/
private fun Target.minXVelocity() = ceil((-1 + sqrt(1.0 + 8 * minX)) / 2).toInt()
private fun Target.trajectoryHits(initialXV: Int, initialYV: Int): Boolean {
var xV = initialXV
var yV = initialYV
var x = xV
var y = yV
while (y > minY && !isHit(x, y)) {
yV--
xV = (xV - 1).coerceAtLeast(0)
x += xV
y += yV
}
return isHit(x, y)
}
private fun Target.isHit(x: Int, y: Int) = x in minX..maxX && y in minY..maxY
private fun Target.maxYVelocity() = floor((-1 + sqrt(1 + 8 * maxHeightPossible().toFloat())) / 2).toInt()
fun part1(input: String): Int {
return input.parseTarget().maxHeightPossible()
}
fun part2(input: String): Int {
val target = input.parseTarget()
return (target.minXVelocity()..target.maxX)
.flatMap { xV -> (target.minY..target.maxYVelocity()).map { yV -> Pair(xV, yV) } }
.count { (xV, yV) -> target.trajectoryHits(xV, yV) }
}
fun main() {
check(part1(readInputAsText("day17/input_test")) == 45)
check(part2(readInputAsText("day17/input_test")) == 112)
val input = readInputAsText("day17/input")
part1(input).println()
part2(input).println()
}
| 0 |
Kotlin
| 0 | 0 |
246353788b1259ba11321d2b8079c044af2e211a
| 2,244 |
advent-of-code-2021
|
Apache License 2.0
|
2022/src/test/kotlin/Day12.kt
|
jp7677
| 318,523,414 | false |
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
|
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import java.util.PriorityQueue
private data class Coord12(val x: Int, val y: Int)
private val directions = listOf(Coord12(1, 0), Coord12(0, 1), Coord12(-1, 0), Coord12(0, -1))
class Day12 : StringSpec({
"puzzle part 01" {
val map = getMap()
val start = map.filterValues { it == S }.keys.single()
val end = map.filterValues { it == E }.keys.single()
val path = map.findShortestPathLength(start, end)
path shouldBe 456
}
"puzzle part 02" {
val map = getMap()
val end = map.filterValues { it == E }.keys.single()
val shortestPath = map.filter { it.value <= 1 }
.mapNotNull { map.findShortestPathLength(it.key, end) }
.min()
shortestPath shouldBe 454
}
})
private fun Map<Coord12, Int>.findShortestPathLength(start: Coord12, end: Coord12): Int? {
val queue = PriorityQueue<Pair<Coord12, Int>>(1, compareBy { (_, distance) -> distance })
.apply { offer(start to 0) }
val totals = mutableMapOf(start to 0)
val visited = mutableSetOf<Coord12>()
while (queue.isNotEmpty()) {
val (current, totalDistance) = queue.poll()
val distance = this[current]!! + 1
directions
.map { direction -> Coord12(current.x + direction.x, current.y + direction.y) }
.filterNot { coord -> visited.contains(coord) }
.mapNotNull { coord -> this[coord]?.let { coord to it } }.toMap()
.filterValues { it <= distance }
.keys.forEach { coord ->
val newTotalDistance = totalDistance + 1
val knownTotalDistance = totals[coord] ?: Int.MAX_VALUE
if (newTotalDistance < knownTotalDistance) {
totals[coord] = newTotalDistance
queue.offer(coord to newTotalDistance)
}
}
if (current == end) break
visited.add(current)
}
return totals.filterKeys { it == end }.toList().firstOrNull()?.second
}
private fun getMap() = getPuzzleInput("day12-input.txt").toList()
.map {
it.map { c ->
when (c) {
'S' -> S
'E' -> E
else -> c.code - 96
}
}
}
.let {
it.first().indices.flatMap { x ->
List(it.size) { y -> Coord12(x, y) to it[y][x] }
}
}.toMap()
private const val S = 0
private const val E = ('z'.code - 96) + 1
| 0 |
Kotlin
| 1 | 2 |
8bc5e92ce961440e011688319e07ca9a4a86d9c9
| 2,543 |
adventofcode
|
MIT License
|
y2023/src/main/kotlin/adventofcode/y2023/Day03.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2023
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec2
fun main() {
Day03.solve()
}
object Day03 : AdventSolution(2023, 3, "Gear Ratios") {
override fun solvePartOne(input: String): Int {
val (numbers, symbols) = parse(input)
return numbers.filterKeys { it.any(symbols::containsKey) }
.values
.sum()
}
override fun solvePartTwo(input: String): Int {
val (numbers, symbols) = parse(input)
val gears = symbols.filterValues { it == "*" }.keys
return gears
.map { position -> numbers.filterKeys { position in it }.values }
.filter { it.size == 2 }
.sumOf { it.reduce(Int::times) }
}
}
private fun neighborhood(root: Vec2, length: Int) =
(root.y - 1..root.y + 1).flatMap { y ->
(root.x - 1..root.x + length).map { x -> Vec2(x, y) }
}.toSet()
private fun parse(input: String): Pair<Map<Set<Vec2>, Int>, Map<Vec2, String>> {
val numbers = "\\d+".toRegex().parse(input)
.mapKeys { neighborhood(it.key, it.value.length) }
.mapValues { it.value.toInt() }
val symbols = "[^\\d.]".toRegex().parse(input)
return Pair(numbers, symbols)
}
private fun Regex.parse(input: String): Map<Vec2, String> = input
.lineSequence()
.flatMapIndexed(this::parseLine)
.toMap()
private fun Regex.parseLine(y: Int, line: String) =
findAll(line).map { match -> Vec2(match.range.first, y) to match.value }
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 1,518 |
advent-of-code
|
MIT License
|
src/Day08.kt
|
dizney
| 572,581,781 | false |
{"Kotlin": 105380}
|
object Day08 {
const val EXPECTED_PART1_CHECK_ANSWER = 21
const val EXPECTED_PART2_CHECK_ANSWER = 8
}
fun main() {
fun List<String>.parseTreeGrid(): List<List<Int>> =
this.map { it.toList() }.map { it.map { chr -> chr.digitToInt() } }
fun List<List<Int>>.isVisible(x: Int, y: Int): Boolean {
if (x == 0 || y == 0 || x == this[0].size - 1 || y == this.size - 1) return true
val heightOfTree = this[y][x]
if (this[y].subList(0, x).all { it < heightOfTree }) return true
if (this[y].subList(x + 1, this[y].size).all { it < heightOfTree }) return true
val treesInSameVerticalRow = this.fold(emptyList<Int>()) { acc, row -> acc + row[x] }
if (treesInSameVerticalRow.subList(0, y).all { it < heightOfTree }) return true
if (treesInSameVerticalRow.subList(y + 1, treesInSameVerticalRow.size).all { it < heightOfTree }) return true
return false
}
fun List<List<Int>>.scenicScore(x: Int, y: Int): Int {
val heightOfTree = this[y][x]
val treesToTheLeft = this[y].subList(0, x)
val leftTreesVisible = treesToTheLeft
.takeLastWhile { it < heightOfTree }.size
.let { if (it == treesToTheLeft.size) it else it + 1 } // accommodate for edges
val treesToTheRight = this[y].subList(x + 1, this[y].size)
val rightTreesVisible = treesToTheRight
.takeWhile { it < heightOfTree }.size
.let { if (it == treesToTheRight.size) it else it + 1 } // accommodate for edges
val treesInSameVerticalRow = this.fold(emptyList<Int>()) { acc, row -> acc + row[x] }
val treesToTheTop = treesInSameVerticalRow.subList(0, y)
val upTreesVisible = treesToTheTop
.takeLastWhile { it < heightOfTree }.size
.let { if (it == treesToTheTop.size) it else it + 1 } // accommodate for edge
val treesToTheBottom = treesInSameVerticalRow.subList(y + 1, treesInSameVerticalRow.size)
val downTreesVisible = treesToTheBottom
.takeWhile { it < heightOfTree }.size
.let { if (it == treesToTheBottom.size) it else it + 1 } // accommodate for edge
return leftTreesVisible * rightTreesVisible * upTreesVisible * downTreesVisible
}
fun part1(input: List<String>): Int {
val treeGrid = input.parseTreeGrid()
var treesVisible = 0
for (xIndex in treeGrid[0].indices) {
for (yIndex in treeGrid.indices) {
if (treeGrid.isVisible(xIndex, yIndex)) {
treesVisible++
}
}
}
return treesVisible
}
fun part2(input: List<String>): Int {
val treeGrid = input.parseTreeGrid()
var highestScenicScore = 0
for (xIndex in treeGrid[0].indices) {
for (yIndex in treeGrid.indices) {
val scenicScore = treeGrid.scenicScore(xIndex, yIndex)
highestScenicScore = maxOf(scenicScore, highestScenicScore)
}
}
return highestScenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == Day08.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day08.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
f684a4e78adf77514717d64b2a0e22e9bea56b98
| 3,458 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/Day08.kt
|
anilkishore
| 573,688,256 | false |
{"Kotlin": 27023}
|
import java.lang.Math.abs
fun main() {
fun part1(trees: List<String>): Int {
val n = trees.size
val mins = Array(n) { CharArray(n) { ':' } }
val scores = Array(n) { IntArray(n) { 1 } }
for (i in 1 until n - 1)
for ((js, jd) in arrayOf(1 to 1, n - 2 to -1)) {
var j = js
var acc = trees[i][js - jd]
var pj = js - jd
while (j > 0 && j + 1 < n) {
mins[i][j] = minOf(mins[i][j], acc)
val s: Int =
if (trees[i][j] >= acc) {
acc = trees[i][j]
pj = j
abs(j - js + 1)
} else {
abs(j - pj)
}
scores[i][j] *= s
if (i == 1 && j == 2) println("$js $jd, s = $s")
j += jd
}
j = js
acc = trees[js - jd][i]
while (j > 0 && j + 1 < n) {
mins[j][i] = minOf(mins[j][i], acc)
acc = maxOf(acc, trees[j][i])
val s = if (trees[j][i] >= acc) {
acc = trees[j][i]
pj = j
abs(j - js + 1)
} else {
abs(j - pj)
}
scores[j][i] *= s
if (i == 2 && j == 1) println("$js $jd, s = $s")
j += jd
}
}
var res = 0
var bestScore = 0
for (i in 1 until n - 1)
for (j in 1 until n - 1) {
res += if (trees[i][j] > mins[i][j]) 1 else 0
bestScore = maxOf(bestScore, scores[i][j])
}
println(bestScore)
return res + 4 * n - 4
}
val input = readInput("Day08_test")
println(part1(input))
}
| 0 |
Kotlin
| 0 | 0 |
f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9
| 1,972 |
AOC-2022
|
Apache License 2.0
|
src/day9/Day9.kt
|
pocmo
| 433,766,909 | false |
{"Kotlin": 134886}
|
package day9
import java.io.File
fun readInput(filename: String = "day9.txt"): List<List<Int>>{
return File(filename)
.readLines()
.map { line -> line.toCharArray().map { character -> character.digitToInt() } }
}
fun List<List<Int>>.neighbours(x: Int, y: Int): List<Int> {
val top = get(x).getOrNull(y - 1)
val bottom = get(x).getOrNull(y + 1)
val left = getOrNull(x - 1)?.get(y)
val right = getOrNull(x + 1)?.get(y)
return listOfNotNull(top, left, right, bottom)
}
fun List<List<Int>>.isValid(x: Int, y: Int): Boolean {
return x in indices && y in get(0).indices
}
fun List<List<Int>>.neighbourPositions(x: Int, y: Int): List<Pair<Int, Int>> {
val top = Pair(x, y - 1)
val bottom = Pair(x, y + 1)
val left = Pair(x - 1, y)
val right = Pair(x + 1, y)
return listOf(top, bottom, left, right).filter { (x, y) -> isValid(x, y) }
}
fun part1() {
val input = readInput()
var riskLevel = 0
for (x in input.indices) {
for (y in input[0].indices) {
val current = input[x][y]
val neighbours = input.neighbours(x, y)
if (neighbours.all { value -> value > current }) {
riskLevel += current + 1
}
}
}
println("Risk level: $riskLevel")
}
fun List<List<Int>>.findLowPoints(): List<Pair<Int, Int>> {
val lowPoints = mutableListOf<Pair<Int, Int>>()
for (x in indices) {
for (y in get(0).indices) {
val current = get(x)[y]
val neighbours = neighbours(x, y)
if (neighbours.all { value -> value > current }) {
lowPoints.add(Pair(x, y))
}
}
}
return lowPoints
}
fun List<List<Int>>.findBasin(x: Int, y: Int): Set<Pair<Int, Int>> {
val visitedPoints = mutableSetOf<Pair<Int, Int>>()
val queue = mutableListOf(Pair(x, y))
while (queue.isNotEmpty()) {
val point = queue.removeFirst()
visitedPoints.add(point)
val neighbours = neighbourPositions(point.first, point.second)
neighbours.forEach { neighbour ->
if (!visitedPoints.contains(neighbour)) {
if (get(neighbour.first)[neighbour.second] != 9) {
queue.add(neighbour)
}
}
}
}
return visitedPoints
}
fun part2() {
val input = readInput("day9.txt")
val lowPoints = input.findLowPoints()
val basins = lowPoints.map { point ->
input.findBasin(point.first, point.second)
}.sortedByDescending { points ->
points.size
}
println("Basins: ${basins.size}")
var result = 1
basins.take(3).forEach { points ->
result *= points.size
}
println("Result: $result")
}
fun main() {
part2()
}
| 0 |
Kotlin
| 1 | 2 |
73bbb6a41229e5863e52388a19108041339a864e
| 2,789 |
AdventOfCode2021
|
Apache License 2.0
|
src/Day05.kt
|
konclave
| 573,548,763 | false |
{"Kotlin": 21601}
|
fun main() {
fun solve1(input: List<String>): String {
val movements = getMovements(input)
val crateStacks = getCrateStacks(input)
return applyMovements9000(movements, crateStacks)
}
fun solve2(input: List<String>): String {
val movements = getMovements(input)
val crateStacks = getCrateStacks(input)
return applyMovements9001(movements, crateStacks)
}
val input = readInput("Day05")
println(solve1(input))
println(solve2(input))
}
fun getCrateStacks(lines: List<String>): List<ArrayDeque<String>> {
val crates = lines
.takeWhile { it.matches(Regex("\\s*\\[.+]\\s*")) }
val cratesNumber = lines[crates.size]
.split(" ")
.last()
.toInt()
val initialStacks = List(cratesNumber) { ArrayDeque<String>() }
return crates
.map { it
.split("")
.filterIndexed { i, _ -> i % 4 != 0 }
.joinToString("")
}
.fold(initialStacks) {
stacks, it ->
it
.chunked(3)
.forEachIndexed { i, crate ->
val clean = crate.replace(Regex("[\\[\\]]"), "")
if (crate.trim() != "") stacks[i].addFirst(clean)}
stacks
}
}
fun getMovements(lines: List<String>): List<Triple<Int, Int, Int>> {
val movementRegex = Regex("move\\s(\\d+)\\sfrom\\s(\\d+)\\sto\\s(\\d+)")
return lines
.dropWhile { !it.matches(movementRegex) }
.map {
val matched = movementRegex.find(it)
if (matched != null) {
val (_, number, from, to) = matched.groupValues
Triple(number.toInt(), from.toInt() - 1, to.toInt() - 1)
} else {
Triple(0, 0, 0)
}
}
}
fun applyMovements9000(movements: List<Triple<Int, Int, Int>>, crates: List<ArrayDeque<String>>): String {
movements.forEach {formula ->
repeat(formula.first) {
crates[formula.third].addLast(crates[formula.second].removeLast())
}
}
return getTopCrates(crates)
}
fun applyMovements9001(movements: List<Triple<Int, Int, Int>>, crates: List<ArrayDeque<String>>): String {
movements.forEach {formula ->
val moving = List(formula.first) { crates[formula.second].removeLast() }
for(i in 0 until formula.first) {
crates[formula.third].addLast(moving[moving.size - i - 1])
}
}
return getTopCrates(crates)
}
fun getTopCrates(crates: List<ArrayDeque<String>>): String {
return crates.fold("") { acc, stack -> acc + stack.last() }
}
| 0 |
Kotlin
| 0 | 0 |
337f8d60ed00007d3ace046eaed407df828dfc22
| 2,644 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day09.kt
|
davidkna
| 572,439,882 | false |
{"Kotlin": 79526}
|
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
fun main() {
fun parseInput(input: List<String>): List<Pair<Int, Int>> {
return input.map { l ->
val (direction, steps) = l.split(" ")
val stepsInt = steps.toInt()
return@map when (direction) {
"R" -> Pair(stepsInt, 0)
"L" -> Pair(-stepsInt, 0)
"U" -> Pair(0, stepsInt)
"D" -> Pair(0, -stepsInt)
else -> throw Exception("Unknown direction")
}
}.toList()
}
fun solution(input: List<String>, len: Int): Int {
val rope = Array(len + 1) { Pair(0, 0) }
val moves = parseInput(input)
val visited = mutableSetOf(Pair(0, 0))
for (move in moves) {
(0 until max(abs(move.first), abs(move.second))).forEach { _ ->
rope[0] = Pair(rope[0].first + move.first.sign, rope[0].second + move.second.sign)
rope.indices.drop(1).forEach { i ->
val head = rope[i - 1]
val tail = rope[i]
if (abs(head.first - tail.first) > 1 || abs(head.second - tail.second) > 1) {
val xStep = (head.first - tail.first).sign
val yStep = (head.second - tail.second).sign
rope[i] = Pair(tail.first + xStep, tail.second + yStep)
}
}
visited.add(rope.last())
}
}
return visited.size
}
val testInputA = readInput("Day09_test_a")
val testInputB = readInput("Day09_test_b")
check(solution(testInputA, 1) == 13)
check(solution(testInputA, 9) == 1)
check(solution(testInputB, 9) == 36)
val input = readInput("Day09")
println(solution(input, 1))
println(solution(input, 9))
}
| 0 |
Kotlin
| 0 | 0 |
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
| 1,883 |
aoc-2022
|
Apache License 2.0
|
src/Day02.kt
|
cjosan
| 573,106,026 | false |
{"Kotlin": 5721}
|
fun main() {
fun part1(input: List<String>): Int {
// A -> Rock; B -> Paper; C -> Scissors
// X -> Rock; Y -> Paper; Z -> Scissors
val shapeScores = mapOf("X" to 1, "Y" to 2, "Z" to 3)
return input
.stream()
.mapToInt { round ->
val shapes = round.split(" ")
val roundResult = shapes[1].single() - shapes[0].single()
var score = shapeScores.getValue(shapes[1])
// 23 -> draw; 21, 24 -> win; 22, 25 -> lose
if (roundResult == 23) {
score += 3
} else if (roundResult == 21 || roundResult == 24) {
score += 6
}
score
}
.sum()
}
fun part2(input: List<String>): Int {
// X -> lose; Y -> draw; Z -> win
val roundResultScore = mapOf('X' to 0, 'Y' to 3, 'Z' to 6)
// A -> Rock; B -> Paper; C -> Scissors
val shapeScores = mapOf('A' to 1, 'B' to 2, 'C' to 3)
return input
.stream()
.mapToInt { round ->
val shapes = round.split(" ").map { it.single() }
var score = roundResultScore.getValue(shapes[1])
when (score) {
3 -> score += shapeScores.getValue(shapes[0])
6 -> score += shapeScores.getOrDefault((shapes[0] + 1), 1)
0 -> score += shapeScores.getOrDefault((shapes[0] - 1), 3)
}
score
}
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
a81f7fb9597361d45ff73ad2a705524cbc64008b
| 1,866 |
advent-of-code2022
|
Apache License 2.0
|
2023/12/solve-1.kts
|
gugod
| 48,180,404 | false |
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
|
import java.io.File
data class SpringProblem (
val observation: String,
val expectation: List<Int>,
)
data class SpringParts (
val c: Char,
val quantity: Int,
)
fun isMatch(problem: SpringProblem, guess: String): Boolean =
problem.expectation == Regex("#+").findAll(guess).map { it.value.length }.toList()
fun isPartialMatch(problem: SpringProblem, guess: String): Boolean {
val current = Regex("#+").findAll(guess).map { it.value.length }.toList()
return if (current.isEmpty()) true else {
current.count() <= problem.expectation.count() &&
current.last() <= problem.expectation[current.lastIndex] &&
(0 .. current.lastIndex - 1).all { i -> current[i] == problem.expectation[i] }
}
}
fun countMatch(problem: SpringProblem, currentGuess: String, offset: Int): Int {
if (offset > problem.observation.lastIndex) {
return if (isMatch(problem, currentGuess)) 1 else 0
}
if (!isPartialMatch(problem, currentGuess)) {
return 0
}
return when (problem.observation[offset]) {
'?' -> {
countMatch(problem, currentGuess + ".", offset + 1) + countMatch(problem, currentGuess + "#", offset + 1)
}
else -> {
countMatch(problem, currentGuess + problem.observation[offset], offset + 1)
}
}
}
fun solveOne(problem: SpringProblem): Int = countMatch(problem, "", 0)
fun solve(problems: List<SpringProblem>) {
problems.map { solveOne(it) }.sum().let { println(it) }
}
fun main(input: String) {
val rows = File(input)
.readLines()
.map { line ->
val cols = line.split(" ")
SpringProblem(
observation = cols[0],
expectation = cols[1].split(",").map { it.toInt() },
)
}
solve(rows)
}
main(args.getOrNull(0) ?: "input")
| 0 |
Raku
| 1 | 5 |
ca0555efc60176938a857990b4d95a298e32f48a
| 1,868 |
advent-of-code
|
Creative Commons Zero v1.0 Universal
|
src/Day12.kt
|
davidkna
| 572,439,882 | false |
{"Kotlin": 79526}
|
import java.util.PriorityQueue
fun main() {
fun height(c: Char): Int {
if (('a'..'z').contains(c)) {
return c.code - 'a'.code
}
return when (c) {
'S' -> 0
'E' -> 25
else -> throw Exception("Unknown char")
}
}
fun neighbors(x: Int, y: Int, input: List<String>): List<Pair<Int, Int>> {
val neighbors = mutableListOf<Pair<Int, Int>>()
if (x > 0) {
neighbors.add(Pair(x - 1, y))
}
if (x < input.size - 1) {
neighbors.add(Pair(x + 1, y))
}
if (y > 0) {
neighbors.add(Pair(x, y - 1))
}
if (y < input[0].length - 1) {
neighbors.add(Pair(x, y + 1))
}
val minHeight = height(input[x][y])
neighbors.removeIf { height(input[it.first][it.second]) + 1 < minHeight }
return neighbors.toList()
}
fun solution(input: List<String>, finalStates: List<Char>): Int {
var start = Pair(0, 0)
val q = PriorityQueue<Pair<Int, Pair<Int, Int>>> { a, b -> a.first - b.first }
val visited = mutableMapOf<Pair<Int, Int>, Int>()
for (y in input.indices) {
for (x in input[y].indices) {
val c = input[y][x]
if (c == 'E') {
start = Pair(y, x)
break
}
}
}
q.add(Pair(0, start))
visited[start] = 0
while (q.isNotEmpty()) {
val current = q.poll()
if (finalStates.contains(input[current.second.first][current.second.second])) {
return current.first
}
for (neighbor in neighbors(current.second.first, current.second.second, input)) {
val newCost = current.first + 1
if (!visited.contains(neighbor) || newCost < visited[neighbor]!!) {
visited[neighbor] = newCost
q.add(Pair(newCost, neighbor))
}
}
}
throw Exception("No solution")
}
val testInput = readInput("Day12_test")
check(solution(testInput, listOf('S')) == 31)
check(solution(testInput, listOf('S', 'a')) == 29)
val input = readInput("Day12")
println(solution(input, listOf('S')))
println(solution(input, listOf('S', 'a')))
}
| 0 |
Kotlin
| 0 | 0 |
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
| 2,383 |
aoc-2022
|
Apache License 2.0
|
src/day02/Day02.kt
|
Harvindsokhal
| 572,911,840 | false |
{"Kotlin": 11823}
|
package day02
import readInput
fun main() {
val data = readInput("day02/day02_data")
/*
* L -> Lose
* T -> Tie
* W -> Win
* */
fun totalScore(list:List<String>): Int {
val myMap: HashMap<String, String> = hashMapOf("X" to "Rock", "Y" to "Paper", "Z" to "Scissors")
val oppMap: HashMap<String, String> = hashMapOf("A" to "Rock", "B" to "Paper", "C" to "Scissors")
val choiceStack = listOf("Paper", "Rock", "Scissors")
val pickPoints = mapOf("X" to 1, "Y" to 2, "Z" to 3)
val results = arrayOf(arrayOf("T", "L", "W"), arrayOf("W", "T", "L"), arrayOf("L", "W", "T"))
var score = 0
list.forEach { pair ->
val myChoice = pair.split(' ')[1]
val oppChoice = pair.split(' ')[0]
score += pickPoints[myChoice]!!
when(results[choiceStack.indexOf(oppMap[oppChoice])][choiceStack.indexOf(myMap[myChoice])]) {
"L" -> score+=0
"T" -> score+=3
"W" -> score+=6
}
}
return score
}
fun totalScoreWithStrat(list:List<String>): Int {
val myMap: HashMap<String, String> = hashMapOf("X" to "L", "Y" to "T", "Z" to "W")
val oppMap: HashMap<String, String> = hashMapOf("A" to "Rock", "B" to "Paper", "C" to "Scissors")
val choiceStack = listOf("Paper", "Rock", "Scissors")
val pickPoints = mapOf("Rock" to 1, "Paper" to 2, "Scissors" to 3)
val results = arrayOf(arrayOf("T", "L", "W"), arrayOf("W", "T", "L"), arrayOf("L", "W", "T"))
var score = 0
list.forEach { pair ->
val myChoice = pair.split(' ')[1]
val oppChoice = pair.split(' ')[0]
score += pickPoints[choiceStack[(results[choiceStack.indexOf(oppMap[oppChoice])].toList().indexOf(myMap[myChoice]))]]!!
when(myMap[myChoice]) {
"L" -> score+=0
"T" -> score+=3
"W" -> score+=6
}
}
return score
}
fun part1(list:List<String>) = totalScore(list)
fun part2(list:List<String>) = totalScoreWithStrat(list)
println(part1(data))
println(part2(data))
}
| 0 |
Kotlin
| 0 | 0 |
7ebaee4887ea41aca4663390d4eadff9dc604f69
| 2,210 |
aoc-2022-kotlin
|
Apache License 2.0
|
src/Day07.kt
|
JanTie
| 573,131,468 | false |
{"Kotlin": 31854}
|
fun main() {
fun buildFileTree(input: List<String>): Map<String, Int> {
var currentDir = ""
val map = mutableMapOf<String, Int>()
input.forEach {
when {
it.startsWith("\$ cd") -> {
val param = it.split(" ")[2]
currentDir = when {
param.startsWith("/") -> param
param.startsWith("..") -> currentDir.substring(0, currentDir.lastIndexOf("/"))
else -> ("$currentDir/$param").replace("//", "/")
}
}
it.startsWith("\$ ls") -> {
if (!map.containsKey(currentDir)) {
map[currentDir] = 0
}
}
it.startsWith("dir") -> Unit // no-op
else -> {
val (size) = it.split(" ")
map[currentDir] = map[currentDir]!! + size.toInt()
}
}
}
return map
}
fun part1(input: List<String>): Int {
val map = buildFileTree(input)
return map.keys.map { key -> map.filter { it.key.startsWith(key) }.values.sum() }
.filter { it < 100000 }
.sum()
}
fun part2(input: List<String>): Int {
val totalSize = 70000000
val updateSize = 30000000
val map = buildFileTree(input)
val sizes = map.keys.associateWith { key -> map.filter { it.key.startsWith(key) }.values.sum() }
val availableSpace = totalSize - sizes["/"]!!
val requiredSpace = updateSize - availableSpace
return sizes.filter { it.value >= requiredSpace }.minOf { it.value }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
val input = readInput("Day07")
check(part1(testInput) == 95437)
println(part1(input))
check(part2(testInput) == 24933642)
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
3452e167f7afe291960d41b6fe86d79fd821a545
| 2,015 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day13.kt
|
tomoki1207
| 572,815,543 | false |
{"Kotlin": 28654}
|
import DatumType.NumDatumType
import DatumType.PacketDatumType
sealed class DatumType {
class NumDatumType(val value: Int) : DatumType() {
override fun toString(): String {
return value.toString()
}
}
class PacketDatumType(val value: Packet) : DatumType() {
override fun toString(): String {
return "[$value]"
}
}
}
data class Packet(val data: List<DatumType>) : Comparable<Packet> {
override fun toString(): String {
return data.joinToString(",")
}
override fun compareTo(other: Packet): Int {
if (this == other) {
return 0
}
this.data.forEachIndexed { i, l ->
val r = other.data.getOrNull(i) ?: return 1
if (l is NumDatumType && r is NumDatumType) {
if (l.value == r.value) {
return@forEachIndexed
}
return l.value - r.value
}
val lP = if (l is PacketDatumType) l.value else Packet(listOf(l as NumDatumType))
val rP = if (r is PacketDatumType) r.value else Packet(listOf(r as NumDatumType))
return lP.compareTo(rP)
}
return -1
}
}
fun main() {
fun parse(packet: String): Packet {
var i = 0
fun innerParse(): Packet {
val packets = mutableListOf<DatumType>()
while (i < packet.length && packet[i] != ']') {
if (packet[i] == '[') {
++i // [
packets.add(PacketDatumType(innerParse()))
++i // ]
} else {
// integer value
val s = i
while (packet[i] in '0'..'9') ++i
val numOrEmpty = packet.substring(s, i)
if (numOrEmpty.isNotEmpty()) {
packets.add(NumDatumType(numOrEmpty.toInt()))
}
}
if (packet.getOrNull(i) == ',') ++i // ,
}
return Packet(packets)
}
return innerParse()
}
fun part1(input: List<String>): Int {
val packets = input.chunked(3) { (left, right) ->
parse(left) to parse(right)
}
return packets.mapIndexed { i, (left, right) ->
if (left <= right) {
i + 1
} else {
null
}
}.filterNotNull().sum()
}
fun part2(input: List<String>): Int {
val packets = input.toMutableList().also { it.addAll(listOf("[[2]]", "[[6]]")) }
.filter { it.isNotEmpty() }
.map { parse(it) }
return packets.asSequence()
.sorted()
.map { it.toString() }
.mapIndexed { i, p ->
if (p == "[[2]]" || p == "[[6]]") i + 1 else null
}
.filterNotNull()
.reduce(Int::times)
}
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 |
2ecd45f48d9d2504874f7ff40d7c21975bc074ec
| 3,163 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/main/kotlin/codes/jakob/aoc/solution/Day12.kt
|
The-Self-Taught-Software-Engineer
| 433,875,929 | false |
{"Kotlin": 56277}
|
package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.UndirectedGraph
import codes.jakob.aoc.shared.UndirectedGraph.Vertex
object Day12 : Solution() {
override fun solvePart1(input: String): Any {
val graph: UndirectedGraph<Cave> = UndirectedGraph(parseInput(input))
val paths: Set<List<Vertex<Cave>>> = findAllPaths(graph) { vertex, visited ->
vertex !in visited || vertex.value.size == Cave.Size.BIG
}
return paths.count()
}
override fun solvePart2(input: String): Any {
val graph: UndirectedGraph<Cave> = UndirectedGraph(parseInput(input))
val paths: Set<List<Vertex<Cave>>> = findAllPaths(graph) { vertex, visited ->
val smallCaveVisitedFrequencies: Map<Vertex<Cave>, Int> =
visited.filter { it.value.size == Cave.Size.SMALL }.countBy { it }
val canVisitSmallCaveAgain: Boolean =
smallCaveVisitedFrequencies.none { it.value > 1 } && (!vertex.value.isStart && !vertex.value.isEnd)
return@findAllPaths vertex !in visited || vertex.value.size == Cave.Size.BIG || canVisitSmallCaveAgain
}
return paths.count()
}
private fun findAllPaths(
graph: UndirectedGraph<Cave>,
canVisit: (Vertex<Cave>, Collection<Vertex<Cave>>) -> Boolean,
): Set<List<Vertex<Cave>>> {
val start: Vertex<Cave> = graph.vertices.first { it.value.isStart }
val end: Vertex<Cave> = graph.vertices.first { it.value.isEnd }
return graph.findAllPaths(start, end, canVisit)
}
private fun parseInput(input: String): List<Pair<Cave, Cave>> {
return input
.splitMultiline()
.map { line: String ->
val (a: String, b: String) = line.split("-")
return@map Cave(a) to Cave(b)
}
}
data class Cave(
val id: String,
val size: Size = if (id.all { it.isUpperCase() }) Size.BIG else Size.SMALL,
val isStart: Boolean = id == "start",
val isEnd: Boolean = id == "end",
) {
enum class Size {
SMALL,
BIG;
}
}
}
fun main() {
Day12.solve()
}
| 0 |
Kotlin
| 0 | 6 |
d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c
| 2,189 |
advent-of-code-2021
|
MIT License
|
src/Day09.kt
|
bigtlb
| 573,081,626 | false |
{"Kotlin": 38940}
|
import kotlin.math.abs
fun main() {
fun distance(head: Pos, tail: Pos): Int = Math.max(abs(head.first - tail.first), abs(head.second - tail.second))
fun follow(head: Pos, tail: Pos): Pos =
tail.copy(tail.first + if (distance(head, tail)>1) head.first.compareTo(tail.first) else 0,
tail.second + if (distance(head,tail) >1) head.second.compareTo(tail.second) else 0)
fun move(head:Pos, direction:Char):Pos = when (direction) {
'R' -> head.copy(first = head.first + 1)
'L' -> head.copy(first = head.first - 1)
'U' -> head.copy(second = head.second + 1)
'D' -> head.copy(second = head.second - 1)
else -> head
}
fun moves(knots:MutableList<Pos>, line:String): Collection<Pos> {
val results = mutableListOf<Pos>()
repeat(line.substring(2).toInt()) {
List(knots.size) { idx ->
when{
(idx==0) -> knots[0] = move(knots[0], line[0])
else -> knots[idx] = follow(knots[idx-1], knots[idx])
}
}
results.add(knots.last())
}
return results
}
fun moves(head: Pos, tail: Pos, line: String): Triple<Pos, Pos, Collection<Pos>> {
var h = head
var t = tail
val results = mutableListOf<Pos>()
repeat(line.substring(2).toInt()) {
h = move(h, line[0])
t = follow(h,t)
results.add(t)
}
return Triple(h, t, results)
}
fun part1(input: List<String>): Int {
var head = Pos(0, 0)
var tail = Pos(0, 0)
return input.fold(listOf(tail)) { acc, line ->
val (h, t, trail) = moves(head, tail, line)
head = h
tail = t
acc + trail
}.toSet().count()
}
fun part2(input: List<String>): Int {
val knots = (0..9).map{Pos(0,0)}.toMutableList()
return input.fold(listOf(knots.last())) { acc, line ->
acc + moves(knots, line)
}.toSet().count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
d8f76d3c75a30ae00c563c997ed2fb54827ea94a
| 2,331 |
aoc-2022-demo
|
Apache License 2.0
|
app/src/main/kotlin/codes/jakob/aoc/solution/Day08.kt
|
loehnertz
| 725,944,961 | false |
{"Kotlin": 59236}
|
package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.cyclicIterator
import codes.jakob.aoc.shared.lowestCommonMultiple
import codes.jakob.aoc.shared.splitByCharacter
object Day08 : Solution() {
private val mapPattern = Regex("([A-Z]{3})\\s=\\s\\(([A-Z]{3}),\\s([A-Z]{3})\\)")
override fun solvePart1(input: String): Any {
val (instructions: List<Direction>, map: Map<Node, Junction>) = parseInput(input)
val startNode = Node("AAA")
val endNode = Node("ZZZ")
val nodeWalker = NodeWalker(map, startNode) { it == endNode }
return nodeWalker.countSteps(instructions)
}
override fun solvePart2(input: String): Any {
val (instructions: List<Direction>, map: Map<Node, Junction>) = parseInput(input)
fun Node.isStart(): Boolean = lastSymbol == 'A'
fun Node.isEnd(): Boolean = lastSymbol == 'Z'
val startNodes: Set<Node> = map.keys.filter { it.isStart() }.toSet()
val requiredStepsByNode: Map<Node, Int> = startNodes.associateWith { node ->
val nodeWalker = NodeWalker(map, node) { it.isEnd() }
nodeWalker.countSteps(instructions)
}
return requiredStepsByNode.values.lowestCommonMultiple()
}
private fun parseInput(input: String): Pair<List<Direction>, Map<Node, Junction>> {
val (instructionString: String, mapString: String) = input.split("\n\n")
val instructions: List<Direction> = instructionString.splitByCharacter().map { Direction.fromSymbol(it) }
val map: Map<Node, Junction> = mapPattern.findAll(mapString).map { matchResult ->
val (source: String, leftTarget: String, rightTarget: String) = matchResult.destructured
Node(source) to Junction(Node(leftTarget), Node(rightTarget))
}.toMap()
return instructions to map
}
private class NodeWalker(
private val map: Map<Node, Junction>,
startNode: Node,
private val isEndNode: (Node) -> Boolean,
) {
private var currentNode: Node = startNode
fun countSteps(instructions: List<Direction>): Int = step(currentNode, instructions.cyclicIterator(), 0)
private tailrec fun step(currentNode: Node, remainingDirections: Iterator<Direction>, steps: Int): Int {
return if (!isEndNode(currentNode)) {
val junction: Junction = map[currentNode] ?: error("The node '$currentNode' is not in the map.")
val nextDirection: Direction = remainingDirections.next()
val nextNode: Node = junction.nextNode(nextDirection)
step(nextNode, remainingDirections, steps + 1)
} else steps
}
}
private enum class Direction {
LEFT,
RIGHT;
companion object {
fun fromSymbol(symbol: Char): Direction = when (symbol) {
'L' -> LEFT
'R' -> RIGHT
else -> error("The symbol '$symbol' is not a valid direction.")
}
}
}
@JvmInline
private value class Node(
val value: String,
) {
init {
require(value.length == 3) { "The value '$value' is not a valid node." }
}
val firstSymbol: Char
get() = value.first()
val lastSymbol: Char
get() = value.last()
}
private data class Junction(
val left: Node,
val right: Node,
) {
fun nextNode(direction: Direction): Node = when (direction) {
Direction.LEFT -> left
Direction.RIGHT -> right
}
}
}
fun main() = Day08.solve()
| 0 |
Kotlin
| 0 | 0 |
6f2bd7bdfc9719fda6432dd172bc53dce049730a
| 3,633 |
advent-of-code-2023
|
MIT License
|
src/Day04.kt
|
lukewalker128
| 573,611,809 | false |
{"Kotlin": 14077}
|
fun main() {
val testInput = readInput("Day04_test")
val testAssignmentPairs = testInput.toAssignmentPairs()
checkEquals(2, part1(testAssignmentPairs))
checkEquals(4, part2(testAssignmentPairs))
val input = readInput("Day04")
val assignmentPairs = input.toAssignmentPairs()
println("Part 1: ${part1(assignmentPairs)}")
println("Part 2: ${part2(assignmentPairs)}")
}
/**
* Counts the number of assignment pairs for which one is contained entirely within the other.
*/
private fun part1(assignmentPairs: List<Pair<IntRange, IntRange>>): Int {
return assignmentPairs.count { (first, second) -> first.within(second) || second.within(first) }
}
private fun List<String>.toAssignmentPairs() = map { line ->
line.split(',').let {
require(it.size == 2)
Pair(it.first().toIntRange(), it.last().toIntRange())
}
}
private fun String.toIntRange() = split('-').let {
require(it.size == 2)
val first = it.first().toInt()
val second = it.last().toInt()
require(first <= second)
IntRange(first, second)
}
private fun IntRange.within(other: IntRange) = first >= other.first && last <= other.last
/**
* Counts the number of assignment pairs that overlap at all.
*/
private fun part2(assignmentPairs: List<Pair<IntRange, IntRange>>): Int {
return assignmentPairs.count { (first, second) -> first.overlaps(second) || second.overlaps(first) }
}
// Checks for overlapping intervals by looking at the start and end points.
private fun IntRange.overlaps(other: IntRange) = first in other || last in other
| 0 |
Kotlin
| 0 | 0 |
c1aa17de335bd5c2f5f555ecbdf39874c1fb2854
| 1,577 |
advent-of-code-2022
|
Apache License 2.0
|
day11/src/main/kotlin/Main.kt
|
joshuabrandes
| 726,066,005 | false |
{"Kotlin": 47373}
|
package org.example
import java.io.File
fun main() {
println("------ Advent of Code 2023 - Day 10 -----")
val puzzleInput = getPuzzleInput()
val starMap = puzzleInput
.map { line ->
line.map { Space.fromChar(it) }
}
val spaceGraph = buildSpaceGraph(starMap)
val shortestPathLength = getShortestPathLength(spaceGraph)
println("Task 1: Shortest path length: $shortestPathLength")
println("----------------------------------------")
}
fun getShortestPathLength(galaxies: List<Space>): Int {
return getPathLength(findShortestPath(galaxies))
}
fun findShortestPath(galaxies: List<Space>): List<Space> {
val visited = mutableSetOf<Space>()
var currentSpace = galaxies.first()
visited.add(currentSpace)
val path = mutableListOf(currentSpace)
while (visited.size < galaxies.size) {
val nextSpace = currentSpace.connections
.filter { it.key !in visited }
.minByOrNull { it.value }
?.key ?: break
visited.add(nextSpace)
path.add(nextSpace)
currentSpace = nextSpace
}
return path
}
fun getPathLength(path: List<Space>): Int {
return path
.zipWithNext()
.sumOf { (current, next) -> current.getDistanceTo(next) }
}
fun buildSpaceGraph(starMap: List<List<Space>>): List<Space> {
val galaxies = starMap.flatten().filter { it.isGalaxy }
val distanceMap = buildMapWithMovement(starMap)
require(starMap.size == distanceMap.size) { "Galaxies and distance map have different sizes" }
for (line in distanceMap.indices) {
require(starMap[line].size == distanceMap[line].size) { "Galaxies and distance map have different sizes" }
}
galaxies
.map { galaxy ->
val (x, y) = getGalaxyCoordinates(starMap, galaxy)
for (otherGalaxy in galaxies) {
if (otherGalaxy == galaxy) {
continue
}
val (otherX, otherY) = getGalaxyCoordinates(starMap, otherGalaxy)
val distance = getDistance(distanceMap, x to y, otherX to otherY)
galaxy.addConnection(otherGalaxy, distance)
}
}
return galaxies
}
fun getGalaxyCoordinates(starMap: List<List<Space>>, galaxy: Space): Pair<Int, Int> {
val galaxyLine = starMap.find { it.contains(galaxy) }!!
val galaxyColumnIndex = galaxyLine.indexOf(galaxy)
val galaxyLineIndex = starMap.indexOf(galaxyLine)
return galaxyLineIndex to galaxyColumnIndex
}
fun getDistance(distanceMap: List<List<Int>>, start: Pair<Int, Int>, target: Pair<Int, Int>): Int {
val (startX, startY) = start
val (targetX, targetY) = target
var distance = 0
var currentX = startX
var currentY = startY
while (currentX != targetX) {
val nextX = if (currentX < targetX) currentX + 1 else currentX - 1
if (currentY in distanceMap.indices && nextX in distanceMap[currentY].indices) {
distance += distanceMap[currentY][nextX]
} else {
error("Indexes out of bounds: $nextX, $currentY")
}
currentX = nextX
}
while (currentY != targetY) {
val nextY = if (currentY < targetY) currentY + 1 else currentY - 1
if (nextY in distanceMap.indices && currentX in distanceMap[nextY].indices) {
distance += distanceMap[nextY][currentX]
} else {
error("Indexes out of bounds: $currentX, $nextY")
}
currentY = nextY
}
return distance
}
/*
corrects distances; lines and columns without Galaxies have double the width/height
*/
fun buildMapWithMovement(starMap: List<List<Space>>): List<List<Int>> {
val mapWithMovement = mutableListOf<List<Int>>()
for (line in starMap) {
if (isEmptyArea(line)) {
mapWithMovement.add(line.map { 2 })
} else {
mapWithMovement.add(line.map { 1 })
}
}
for (column in starMap[0].indices) {
val columnLine = starMap.map { it[column] }
// if column is empty, double the distance
if (isEmptyArea(columnLine)) {
for (line in mapWithMovement.indices) {
val lineList = mapWithMovement[line].toMutableList()
lineList[column] *= 2
mapWithMovement[line] = lineList
}
}
}
return mapWithMovement
}
fun isEmptyArea(line: List<Space>): Boolean {
for (space in line) {
if (space.isGalaxy) {
return false
}
}
return true
}
fun getPuzzleInput(): List<String> {
val fileUrl = ClassLoader.getSystemResource("input.txt")
return File(fileUrl.toURI()).readLines()
}
class Space private constructor(val galaxyId: Int, val isEmpty: Boolean) {
val connections = mutableMapOf<Space, Int>()
val isGalaxy
get() = !isEmpty
fun addConnection(space: Space, distance: Int) {
connections[space] = distance
}
fun getDistanceTo(space: Space): Int {
return connections[space] ?: throw Exception("No connection to space $space")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Space
return galaxyId == other.galaxyId
}
override fun hashCode(): Int {
return galaxyId
}
companion object {
private var nextGalaxyId = 0
fun fromChar(char: Char): Space = when (char) {
'#' -> Space(nextGalaxyId++, false)
'.' -> Space(nextGalaxyId++, true)
else -> error("Unknown space type: $char")
}
}
}
| 0 |
Kotlin
| 0 | 1 |
de51fd9222f5438efe9a2c45e5edcb88fd9f2232
| 5,701 |
aoc-2023-kotlin
|
The Unlicense
|
src/Day11.kt
|
mathijs81
| 572,837,783 | false |
{"Kotlin": 167658, "Python": 725, "Shell": 57}
|
import kotlin.math.max
import kotlin.math.min
private const val EXPECTED_1 = 374L
private const val EXPECTED_2 = 1030L
private class Day11(isTest: Boolean) : Solver(isTest) {
val field = readAsLines().map { it.toCharArray() }
val Y = field.size
val X = field[0].size
var mul = 2L
fun part1(): Any {
val rows = (0..<Y).filter { y -> (0..<X).all { x -> field[y][x] == '.' } }.toSet()
val columns = (0..<X).filter { x -> (0..<Y).all { y -> field[y][x] == '.' } }.toSet()
val galaxies = mutableListOf<Pair<Int, Int>>()
for (y in 0 until Y) {
for (x in 0 until X) {
if (field[y][x] == '#') {
galaxies.add(Pair(y, x))
}
}
}
fun dist(a: Int, b: Int): Long {
val y1 = min(galaxies[a].first, galaxies[b].first)
val y2 = max(galaxies[a].first, galaxies[b].first)
val x1 = min(galaxies[a].second, galaxies[b].second)
val x2 = max(galaxies[a].second, galaxies[b].second)
val add = (x1..x2).intersect(columns).count() + (y1..y2).intersect(rows).count()
return (add * (mul - 1) + y2-y1 + x2-x1)
}
var sum = 0L
for (a in galaxies.indices) {
for (b in a + 1 until galaxies.size) {
sum += dist(a, b)
}
}
return sum
}
fun part2(): Any {
return part1()
}
}
fun main() {
val testInstance = Day11(true)
val instance = Day11(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.mul = 10L
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
instance.mul = 1000000L
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 |
Kotlin
| 0 | 2 |
92f2e803b83c3d9303d853b6c68291ac1568a2ba
| 1,901 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day08.kt
|
wgolyakov
| 572,463,468 | false | null |
fun main() {
fun parse(input: List<String>): List<List<Int>> {
val grid = mutableListOf<List<Int>>()
for (line in input)
grid.add(line.map { it.digitToInt() })
return grid
}
fun part1(input: List<String>): Int {
val grid = parse(input)
val h = grid.size
val w = grid[0].size
val visible = Array(h) { BooleanArray(w) }
var max = -1
fun checkTree(i: Int, j: Int) {
if (grid[i][j] > max) visible[i][j] = true
if (max < grid[i][j]) max = grid[i][j]
}
for (i in 0 until h) {
max = -1
for (j in 0 until w) checkTree(i, j)
max = -1
for (j in w - 1 downTo 0) checkTree(i, j)
}
for (j in 0 until w) {
max = -1
for (i in 0 until h) checkTree(i, j)
max = -1
for (i in h - 1 downTo 0) checkTree(i, j)
}
return visible.sumOf { line -> line.count { it } }
}
fun part2(input: List<String>): Int {
val grid = parse(input)
val h = grid.size
val w = grid[0].size
val score = Array(h) { IntArray(w) { 1 } }
var distance = IntArray(10)
fun checkTree(i: Int, j: Int) {
score[i][j] *= distance[grid[i][j]]
for (k in 0..9)
if (k <= grid[i][j])
distance[k] = 1
else
distance[k]++
}
for (i in 0 until h) {
distance = IntArray(10)
for (j in 0 until w) checkTree(i, j)
distance = IntArray(10)
for (j in w - 1 downTo 0) checkTree(i, j)
}
for (j in 0 until w) {
distance = IntArray(10)
for (i in 0 until h) checkTree(i, j)
distance = IntArray(10)
for (i in h - 1 downTo 0) checkTree(i, j)
}
return score.maxOf { it.max() }
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
789a2a027ea57954301d7267a14e26e39bfbc3c7
| 1,727 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day09.kt
|
pavlo-dh
| 572,882,309 | false |
{"Kotlin": 39999}
|
import kotlin.math.pow
import kotlin.math.sign
import kotlin.math.sqrt
fun main() {
data class Point(val x: Int, val y: Int)
fun parseMovement(inputLine: String): Triple<Int, Int, Int> {
val (direction, steps) = inputLine.split(' ')
val (headXMovement, headYMovement) = when (direction.first()) {
'R' -> 1 to 0
'L' -> -1 to 0
'U' -> 0 to 1
'D' -> 0 to -1
else -> error("Wrong direction!")
}
return Triple(steps.toInt(), headXMovement, headYMovement)
}
fun movementNeeded(previous: Point, current: Point) =
sqrt((current.x - previous.x).toDouble().pow(2) + (current.y - previous.y).toDouble().pow(2)).toInt() > 1
fun move(previous: Point, current: Point, previousXMovement: Int, previousYMovement: Int) = when {
previous.x == current.x -> Point(current.x, current.y + previousYMovement)
previous.y == current.y -> Point(current.x + previousXMovement, current.y)
else -> Point(current.x + (previous.x - current.x).sign, current.y + (previous.y - current.y).sign)
}
fun part1(input: List<String>): Int {
var head = Point(0, 0)
var tail = head
val visited = mutableSetOf(tail)
input.forEach { inputLine ->
val (steps, headXMovement, headYMovement) = parseMovement(inputLine)
repeat(steps) {
head = Point(head.x + headXMovement, head.y + headYMovement)
if (movementNeeded(head, tail)) {
tail = move(head, tail, headXMovement, headYMovement)
visited.add(tail)
}
}
}
return visited.size
}
fun part2(input: List<String>): Int {
var head = Point(0, 0)
var rope = Array(10) { head }
val visited = mutableSetOf(rope.last())
input.forEach { inputLine ->
val (steps, headXMovement, headYMovement) = parseMovement(inputLine)
repeat(steps) {
head = rope.first()
val newHead = Point(head.x + headXMovement, head.y + headYMovement)
val newRope = rope.copyOf()
newRope[0] = newHead
for (i in 1..9) {
val previous = newRope[i - 1]
val previousNotMoved = rope[i - 1]
val previousXMovement = previous.x - previousNotMoved.x
val previousYMovement = previous.y - previousNotMoved.y
val current = newRope[i]
if (movementNeeded(previous, current)) {
newRope[i] = move(previous, current, previousXMovement, previousYMovement)
if (i == 9) {
visited.add(newRope[i])
}
}
}
rope = newRope
}
}
return visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 2 |
c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992
| 3,319 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/day10/Day10.kt
|
banshay
| 572,450,866 | false |
{"Kotlin": 33644}
|
package day10
import readInput
fun main() {
fun part1(input: List<String>): Int {
val program = input.toCycleSignalStrengthMap()
val relevantCycles = 20..220 step 40
return relevantCycles.sumOf {
val x = when (program[it]) {
null -> program[it + 1]!!.during()
else -> program[it]!!.during()
}
it * x
}
}
fun part2(input: List<String>): Int {
val cols = 40
val rows = 6
val program = input.toCycleSignalStrengthMap()
var currentInstruction = program[0]!!
val screen = List(rows) { row ->
List(cols) { col ->
val cycle = row * cols + col + 1
currentInstruction = program[cycle] ?: currentInstruction
val x = program[cycle]?.during() ?: currentInstruction.after()
when (col) {
x - 1 -> "#"
x -> "#"
x + 1 -> "#"
else -> "."
}
}
}
screen.prettyPrint()
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
val input = readInput("Day10")
println("test part1: ${part1(testInput)}")
println("result part1: ${part1(input)}")
println("test part2: ${part2(testInput)}")
println("result part2: ${part2(input)}")
}
fun List<String>.toCycleSignalStrengthMap(): Map<Int, Instruction> =
this.scan(0 to Instruction(1, 0)) { prev, rawInstruction ->
val key = prev.first + when {
rawInstruction.contains("noop") -> 1
else -> 2
}
key to Instruction(
prev.second.after(), when {
rawInstruction.contains("noop") -> 0
else -> {
val match = Regex("""addx (-?\d+)+""").find(rawInstruction)!!
val (number) = match.destructured
number.toInt()
}
}
)
}
.toMap()
fun List<List<String>>.prettyPrint() {
this.forEach {
println(it.joinToString(""))
}
}
data class Instruction(val X: Int, val change: Int) {
fun during() = X
fun after() = X + change
}
| 0 |
Kotlin
| 0 | 0 |
c3de3641c20c8c2598359e7aae3051d6d7582e7e
| 2,316 |
advent-of-code-22
|
Apache License 2.0
|
src/Day05.kt
|
zirman
| 572,627,598 | false |
{"Kotlin": 89030}
|
fun main() {
fun part1(input: List<String>): String {
val (stacksInput, movesInput) = input.joinToString("\n").split("\n\n")
val stacks = stacksInput.split("\n").map { it.map { it } }
val cs = stacks.last().mapIndexedNotNull { i, c -> if (c.isDigit()) i else null }
fun parseStack(c: Int): List<Char> {
fun parseColumn(r: Int): List<Char> {
return if (stacks.indices.contains(r).not() ||
stacks[r].indices.contains(c).not() ||
stacks[r][c].isLetter().not()
) {
emptyList()
} else {
listOf(stacks[r][c]).plus(parseColumn(r - 1))
}
}
return parseColumn(stacks.size - 2)
}
val parsedStacks = cs.map { parseStack(it) }.toTypedArray()
val parsedMoves = movesInput
.split("\n")
.map {
val (countStr, moveStr) = it.substringAfter("move ").split(" from ")
val (fromStr, toStr) = moveStr.split(" to ")
Triple(countStr.toInt(), fromStr.toInt() - 1, toStr.toInt() - 1)
}
parsedMoves.forEach { (count, from, to) ->
parsedStacks[to] = parsedStacks[to].plus(parsedStacks[from].takeLast(count).reversed())
parsedStacks[from] = parsedStacks[from].take(parsedStacks[from].size - count)
}
return parsedStacks.joinToString("") { "${it.last()}" }
}
fun part2(input: List<String>): String {
val (stacksInput, movesInput) = input.joinToString("\n").split("\n\n")
val stacks = stacksInput.split("\n").map { it.map { it } }
val cs = stacks.last().mapIndexedNotNull { i, c -> if (c.isDigit()) i else null }
fun parseStack(c: Int): List<Char> {
fun parseColumn(r: Int): List<Char> {
return if (stacks.indices.contains(r).not() ||
stacks[r].indices.contains(c).not() ||
stacks[r][c].isLetter().not()
) {
emptyList()
} else {
listOf(stacks[r][c]).plus(parseColumn(r - 1))
}
}
return parseColumn(stacks.size - 2)
}
val parsedStacks = cs.map { parseStack(it) }.toTypedArray()
val parsedMoves = movesInput
.split("\n")
.map {
val (countStr, moveStr) = it.substringAfter("move ").split(" from ")
val (fromStr, toStr) = moveStr.split(" to ")
Triple(countStr.toInt(), fromStr.toInt() - 1, toStr.toInt() - 1)
}
parsedMoves.forEach { (count, from, to) ->
parsedStacks[to] = parsedStacks[to].plus(parsedStacks[from].takeLast(count))
parsedStacks[from] = parsedStacks[from].take(parsedStacks[from].size - count)
}
return parsedStacks.joinToString("") { "${it.last()}" }
}
// 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))
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
2ec1c664f6d6c6e3da2641ff5769faa368fafa0f
| 3,284 |
aoc2022
|
Apache License 2.0
|
src/Day17.kt
|
Flame239
| 570,094,570 | false |
{"Kotlin": 60685}
|
import kotlin.math.max
private fun pushes(): List<Int> {
return readInput("Day17")[0].map { if (it == '>') 1 else -1 }
}
private val addHeightByTurn = mutableListOf<Long>()
private fun part1(pushes: List<Int>, rounds: Int): Int {
val game = Array(7) { BooleanArray(100000) }
for (i in 0 until 7) game[i][0] = true
var height = 0
var pushTurn = 0
repeat(rounds) { round ->
var curShape = Shape(round, height + 4)
while (true) {
val xDiff = pushes[pushTurn++ % pushes.size]
val sideShape = curShape.shiftX(xDiff)
if (!sideShape.collide(game)) curShape = sideShape
val downShape = curShape.shiftY(-1)
if (downShape.collide(game)) {
curShape.includeInto(game)
addHeightByTurn.add(max(curShape.top() - height, 0).toLong())
height = max(curShape.top(), height)
break
} else {
curShape = downShape
}
}
}
return height
}
private fun part2(pushes: List<Int>): Long {
addHeightByTurn.clear()
part1(pushes, 20000)
val turns = 1000000000000L
// found manually (V)-_-(V)
val offset = 156 // 15
val cycle = 1725 // 35
val offsetSum = addHeightByTurn.take(offset).sum()
val cycleSum = addHeightByTurn.drop(offset).take(cycle).sum()
val cycleTotal = (turns - offset) / cycle * cycleSum
val cycleRem = (turns - offset) % cycle
val cycleRemTotal = addHeightByTurn.drop(offset).take(cycleRem.toInt()).sum()
return offsetSum + cycleTotal + cycleRemTotal
}
data class Shape(var pts: List<C>) {
constructor(turn: Int, height: Int) : this(createShape(turn, height))
fun shiftX(diff: Int): Shape = Shape(pts.map { it.shiftX(diff) })
fun shiftY(diff: Int) = Shape(pts.map { it.shiftY(diff) })
fun top(): Int = pts.maxOf { it.y }
fun collide(game: Array<BooleanArray>): Boolean {
val collideWithSides = pts.any { it.x < 0 || it.x >= game.size }
return collideWithSides || pts.any { game[it.x][it.y] }
}
fun includeInto(game: Array<BooleanArray>) {
pts.forEach { game[it.x][it.y] = true }
}
}
fun createShape(turn: Int, height: Int): List<C> = shapes[turn % shapes.size].map { it.shiftY(height) }
// already shifted right by 2
private val shapes = listOf(
listOf(C(2, 0), C(3, 0), C(4, 0), C(5, 0)),
listOf(C(2, 1), C(3, 0), C(3, 1), C(3, 2), C(4, 1)),
listOf(C(2, 0), C(3, 0), C(4, 0), C(4, 1), C(4, 2)),
listOf(C(2, 0), C(2, 1), C(2, 2), C(2, 3)),
listOf(C(2, 0), C(2, 1), C(3, 0), C(3, 1))
)
fun main() {
println(part1(pushes(), 2022))
println(part2(pushes()))
}
| 0 |
Kotlin
| 0 | 0 |
27f3133e4cd24b33767e18777187f09e1ed3c214
| 2,709 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day09.kt
|
esp-er
| 573,196,902 | false |
{"Kotlin": 29675}
|
package patriker.day09
import kotlin.math.abs
import patriker.utils.*
data class Pos(val x: Int, val y: Int)
enum class Dir{
RIGHT,LEFT,UP,DOWN;
}
fun main() {
val testInput = readInput("Day09_test")
val test2 = readInput("Day09_test2")
val input = readInput("Day09_input")
// test if implementation meets criteria from the description, like:
//val testInput = readInputText("Day01_test")
println(solvePart1(testInput))
println(solvePart1(input))
println(solvePart2(testInput))
println(solvePart2(test2))
}
fun maxDist(hpos: Pos, tpos: Pos): Int{
val diff = Pos(abs(hpos.x - tpos.x), abs(hpos.y - tpos.y))
return maxOf(diff.x, diff.y)
}
fun moveRope(dir: Dir, HPos: Pos, TPos: Pos, times: Int = 1): List<Pair<Pos,Pos>>{
var tpos = TPos
var hpos = HPos
val hdir = when(dir){
Dir.RIGHT -> 1
Dir.LEFT -> -1
else -> 0
}
val vdir = when(dir){
Dir.UP -> -1
Dir.DOWN -> 1
else -> 0
}
var visitedPos = mutableListOf<Pair<Pos,Pos>>()
repeat(times){
val oldpos = hpos
hpos = Pos(hpos.x + hdir, hpos.y + vdir)
if(maxDist(hpos,tpos) > 1)
tpos = oldpos
visitedPos.add(Pair(hpos,tpos))
}
return visitedPos
}
fun moveRope(dir: Dir, positions: Array<Pos>, times: Int = 1): List<Pair<Pos,Pos>>{
val hdir = when(dir){
Dir.RIGHT -> 1
Dir.LEFT -> -1
else -> 0
}
val vdir = when(dir){
Dir.UP -> -1
Dir.DOWN -> 1
else -> 0
}
var visitedPos = mutableListOf<Pair<Pos,Pos>>()
repeat(times){
var newpos = positions[9]
positions[9] = Pos(positions[9].x + hdir, positions[9].y + vdir)
var oldPos = positions[9]
( 8 downTo 0 ).forEach{i ->
if (maxDist(positions[i], positions[i+1]) > 1) {
if (i == 8) {
oldPos = positions[i]
positions[i] = newpos
}
else {
var tmp = positions[i]
positions[i] = oldPos
oldPos = tmp
}
}
}
visitedPos.add(Pair(positions[1], positions[0]))
}
return visitedPos
}
fun solvePart1(input: List<String>): Int{
val visitedPositions = mutableSetOf<Pos>()
visitedPositions.add(Pos(0,0))
var hpos = Pos(0,0)
var tpos = Pos(0,0)
input.forEach{
val (direction, times) = it.split(" ")
val timesInt = times.toInt()
val visited = when(direction) {
"R" -> moveRope(Dir.RIGHT, hpos, tpos, timesInt)
"L" -> moveRope(Dir.LEFT, hpos, tpos, timesInt)
"U" -> moveRope(Dir.UP, hpos, tpos, timesInt)
"D" -> moveRope(Dir.DOWN, hpos, tpos, timesInt)
else -> error("Erroneous input!")
}
visitedPositions.addAll( visited.map{ it.second } )
hpos = visited.last().first
tpos = visited.last().second
}
return visitedPositions.size
}
fun solvePart2(input: List<String>): Int{
val visitedPositions = mutableSetOf<Pos>()
visitedPositions.add(Pos(0,0))
val arr = Array<Pos>(10){
Pos(0,0)
}
input.forEach{
val (direction, times) = it.split(" ")
val timesInt = times.toInt()
val visited = when(direction) {
"R" -> moveRope(Dir.RIGHT, arr, timesInt)
"L" -> moveRope(Dir.LEFT, arr, timesInt)
"U" -> moveRope(Dir.UP, arr, timesInt)
"D" -> moveRope(Dir.DOWN, arr, timesInt)
else -> error("Erroneous input!")
}
visitedPositions.addAll( visited.map{ it.second } )
}
println(visitedPositions)
return visitedPositions.size
}
| 0 |
Kotlin
| 0 | 0 |
f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362
| 3,859 |
aoc2022
|
Apache License 2.0
|
src/main/kotlin/de/jball/aoc2022/day08/Day08.kt
|
fibsifan
| 573,189,295 | false |
{"Kotlin": 43681}
|
package de.jball.aoc2022.day08
import de.jball.aoc2022.Day
import kotlin.math.max
class Day08(test: Boolean = false) : Day<Int>(test, 21, 8) {
private val grid = input
.mapIndexed { lineNo, line ->
line.chunked(1)
.mapIndexed { colNo, col -> Pair(Pair(lineNo, colNo), col.toInt()) }
}
private val gridMap = grid.flatten().toMap()
private val lines = input.size
private val columns = input[0].length
override fun part1(): Int {
val fromTop = grid.fold(emptyListsOfMaximums()) { listsOfMaximums, nextLine ->
listsOfMaximums.zip(nextLine) { previousMaximumsInDirection, currentValue ->
appendCurrentValueIfLarger(previousMaximumsInDirection, currentValue)
}
}.flatMap { it.first }.toSet()
val fromBottom = grid.reversed().fold(emptyListsOfMaximums()) { listsOfMaximums, nextLine ->
listsOfMaximums.zip(nextLine) { previousMaximumsInDirection, currentValue ->
appendCurrentValueIfLarger(previousMaximumsInDirection, currentValue)
}
}.flatMap { it.first }.toSet()
val fromLeft = grid.map { line ->
line.fold(emptyListOfMaximums()) { previousMaximumsInDirection, currentValue ->
appendCurrentValueIfLarger(previousMaximumsInDirection, currentValue)
}.first
}.flatten().toSet()
val fromRight = grid.map { line ->
line.reversed().fold(emptyListOfMaximums()) { previousMaximumsInDirection, currentValue ->
appendCurrentValueIfLarger(previousMaximumsInDirection, currentValue)
}.first
}.flatten().toSet()
return fromBottom.union(fromTop).union(fromLeft).union(fromRight).count()
}
private fun appendCurrentValueIfLarger(
currentMax: Pair<List<Pair<Int, Int>>, Int>,
currentValue: Pair<Pair<Int, Int>, Int>
) = Pair(
if (currentMax.second < currentValue.second) currentMax.first + listOf(currentValue.first) else currentMax.first,
max(currentMax.second, currentValue.second)
)
private fun emptyListsOfMaximums() = List(lines) {
emptyListOfMaximums()
}
private fun emptyListOfMaximums() = Pair(listOf<Pair<Int, Int>>(), Int.MIN_VALUE)
override fun part2(): Int {
return grid.maxOf { line ->
line.maxOf { (pos, height) ->
val scenicScore = linesOfSight(pos).map { lineOfSight ->
val visibleTrees = lineOfSight.takeWhile { otherTree ->
gridMap[otherTree]!! < height
}
if (visibleTrees.size < lineOfSight.size) visibleTrees.size+1 else visibleTrees.size
}.reduce {a, b -> a*b}
scenicScore
}
}
}
private fun linesOfSight(treePosition: Pair<Int, Int>): List<List<Pair<Int, Int>>> {
val (x, y) = treePosition
return listOf((0 until x).reversed().zip(List(x) { y }),
(x+1 until lines).zip(List(lines-x){ y }),
List(y) { x }.zip((0 until y).reversed()),
List(columns-y) { x }.zip((y+1 until columns)))
}
}
fun main() {
Day08().run()
}
| 0 |
Kotlin
| 0 | 3 |
a6d01b73aca9b54add4546664831baf889e064fb
| 3,237 |
aoc-2022
|
Apache License 2.0
|
src/Day07.kt
|
zhtk
| 579,137,192 | false |
{"Kotlin": 9893}
|
sealed class FileSystem(var size: Int = 0) {
class File(val name: String, size: Int) : FileSystem(size)
data class Directory(
val name: String,
val files: MutableSet<String> = mutableSetOf()
) : FileSystem()
}
fun main() {
val input = readInput("Day07")
val fileSystem = mutableMapOf<String, FileSystem>("/" to FileSystem.Directory("/"))
val currentPath = mutableListOf<String>()
input.forEach {
when {
it == "$ cd /" -> currentPath.clear()
it == "$ cd .." -> currentPath.removeLast()
it == "$ ls" -> Unit
it.startsWith("dir ") || it.startsWith("$ cd ") -> {
val directory = currentPath.joinToString("/", "/")
val name = it.substring((if (it.startsWith("dir ")) "dir " else "$ cd ").length)
val path = (currentPath + name).joinToString("/", "/")
(fileSystem[directory] as FileSystem.Directory).files.add(name)
fileSystem.putIfAbsent(path, FileSystem.Directory(path))
if (it.startsWith("$ cd ")) currentPath.add(name)
}
else -> {
val (size, name) = it.split(' ')
val directory = currentPath.joinToString("/", "/")
val path = (currentPath + name).joinToString("/", "/")
(fileSystem[directory] as FileSystem.Directory).files.add(name)
fileSystem[path] = FileSystem.File(name, size.toInt())
}
}
}
calculateDirectorySize("", fileSystem)
fileSystem.values.sumOf { if (it is FileSystem.Directory && it.size <= 100000) it.size else 0 }.println()
val neededSpace = 30000000 - (70000000 - fileSystem["/"]!!.size)
fileSystem.values.filter { it is FileSystem.Directory }.sortedBy { it.size }.first { it.size >= neededSpace}
.size.println()
}
private fun calculateDirectorySize(path: String, fileSystem: Map<String, FileSystem>): Int {
val file = fileSystem[path.ifEmpty { "/" }]!!
if (file is FileSystem.Directory) {
file.size = file.files.sumOf { calculateDirectorySize("$path/$it", fileSystem) }
}
return file.size
}
| 0 |
Kotlin
| 0 | 0 |
bb498e93f9c1dd2cdd5699faa2736c2b359cc9f1
| 2,184 |
aoc2022
|
Apache License 2.0
|
src/Day07.kt
|
Yasenia
| 575,276,480 | false |
{"Kotlin": 15232}
|
abstract class FileSystemNode(val name: String) {
abstract val parent: Directory?
abstract fun size(): Int
}
class Directory(
name: String,
override val parent: Directory? = null,
private val content: MutableList<FileSystemNode> = mutableListOf()
) : FileSystemNode(name) {
override fun size(): Int = this.content.sumOf { it.size() }
fun addFile(name: String, size: Int) {
if (this.content.none { it.name == name }) this.content.add(File(name, size, this))
}
fun addDirectory(name: String) {
if (this.content.none { it.name == name }) this.content.add(Directory(name, this))
}
fun changeDirectoryTo(relativePath: List<String>): Directory = relativePath.fold(this as Directory?) { directory, path ->
if (path == "..") directory?.parent else directory?.content?.find { it.name == path } as? Directory
} ?: throw NoSuchElementException("No such directory")
fun listAllDirectories(): List<Directory> = this.content.flatMap { if (it is Directory) it.listAllDirectories() else emptyList() } + this
}
class File(name: String, private val size: Int, override val parent: Directory? = null) : FileSystemNode(name) {
override fun size(): Int = this.size
}
fun main() {
fun buildFileSystem(input: List<String>): Directory {
val relativeChangeDirectoryCommand = "^\\$ cd ((\\w+|..)(/(\\w+|..))*)$".toRegex()
val absoluteChangeDirectoryCommand = "^\\$ cd (((/(\\w+|..))+)|/)$".toRegex()
val fileLine = "^(\\d+) ((\\w+)(.\\w+)?)$".toRegex()
val directoryLine = "^dir (\\w+)$".toRegex()
val root = Directory("/")
var currentDirectory = root
for (line in input) {
if (relativeChangeDirectoryCommand.matches(line)) {
val path = relativeChangeDirectoryCommand.find(line)!!.groupValues[1].split("/")
currentDirectory = currentDirectory.changeDirectoryTo(path)
} else if (absoluteChangeDirectoryCommand.matches(line)) {
val path = absoluteChangeDirectoryCommand.find(line)!!.groupValues[1].split("/").filter { it.isNotBlank() }
currentDirectory = root.changeDirectoryTo(path)
} else if (fileLine.matches(line)) {
val matchResult = fileLine.find(line)!!
val size = matchResult.groupValues[1].toInt()
val name = matchResult.groupValues[2]
currentDirectory.addFile(name, size)
} else if (directoryLine.matches(line)) {
val name = directoryLine.find(line)!!.groupValues[1]
currentDirectory.addDirectory(name)
}
}
return root
}
fun part1(input: List<String>): Int = buildFileSystem(input).listAllDirectories().filter { it.size() <= 100000 }.sumOf { it.size() }
fun part2(input: List<String>): Int {
val root = buildFileSystem(input)
val needDeletedSize = root.size() + 30000000 - 70000000
return root.listAllDirectories().filter { it.size() >= needDeletedSize }.minOf { it.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 |
9300236fa8697530a3c234e9cb39acfb81f913ba
| 3,299 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/main/kotlin/g2501_2600/s2572_count_the_number_of_square_free_subsets/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g2501_2600.s2572_count_the_number_of_square_free_subsets
// #Medium #Array #Dynamic_Programming #Math #Bit_Manipulation #Bitmask
// #2023_07_09_Time_218_ms_(100.00%)_Space_37.8_MB_(100.00%)
class Solution {
private val primes = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
private val badNums = (1..30).filter { primes.any { p -> it % (p * p) == 0 } }.toSet()
private val nonPrimes = (2..30).filter { it !in primes }.filter { it !in badNums }.toList()
private fun gcd(a: Int, b: Int): Int {
return if (b == 0) a else gcd(b, a % b)
}
fun squareFreeSubsets(nums: IntArray): Int {
val mod: Long = 1_000_000_007
// Get the frequency map
val freqMap = nums.toTypedArray().groupingBy { it }.eachCount()
var dp = mutableMapOf<Int, Long>()
for (v in nonPrimes) {
if (v !in freqMap) continue
val howmany = freqMap[v]!!
val prev = HashMap(dp)
dp[v] = (dp[v] ?: 0) + howmany
for ((product, quantity) in prev)
if (gcd(product, v) == 1)
dp[product * v] = ((dp[product * v] ?: 0L) + quantity * howmany.toLong()) % mod
}
for (v in primes) {
if (v !in freqMap) continue
val howmany = freqMap[v]!!.toLong()
val prev = dp
dp = mutableMapOf<Int, Long>()
dp[v] = howmany
for ((product, quantity) in prev)
dp[product] = if (product % v != 0) quantity * (1 + howmany) else quantity
}
// Getting all possible subsets without `1`
var res = dp.values.sum() % mod
// Find the permutations of `1`
val possible = (1..(freqMap[1] ?: 0)).fold(1L) { sum, _ -> (sum shl 1) % mod }
res = (res * possible + possible + mod - 1) % mod
return res.toInt()
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 1,868 |
LeetCode-in-Kotlin
|
MIT License
|
src/year2021/Day4.kt
|
drademacher
| 725,945,859 | false |
{"Kotlin": 76037}
|
package year2021
import readFile
fun main() {
val input = parseInput(readFile("2021", "day4"))
val testInput = parseInput(readFile("2021", "day4_test"))
check(part1(testInput) == 4512)
println("Part 1:" + part1(input))
check(part2(testInput) == 1924)
println("Part 2:" + part2(input))
}
private fun parseInput(file: String): NumbersAndBoards {
val rawInput =
file
.split("\n")
.filter { it != "" }
val numbers = rawInput[0].split(",").map { it.toInt() }
val boards =
(1 until rawInput.size step 5)
.map { lineIndex ->
Board(
rawInput
.slice(lineIndex..lineIndex + 4)
.map { line -> line.split(" ").filter { it != "" }.map { it.toInt() } },
)
}
return NumbersAndBoards(numbers, boards)
}
private fun part1(input: NumbersAndBoards): Int {
val (numbers, boards) = input
for (number in numbers) {
boards.forEach { it.mark(number) }
if (boards.any { it.hasBingo() }) {
val board = boards.first { it.hasBingo() }
return board.sumOfUnmarkedNumbers() * number
}
}
return -1
}
private fun part2(input: NumbersAndBoards): Int {
val (numbers, boards) = input
var lastBoard = Board(mutableListOf())
for (number in numbers) {
boards.forEach { it.mark(number) }
if (boards.filter { !it.hasBingo() }.size == 1) {
lastBoard = boards.first { !it.hasBingo() }
break
}
}
// solve the last board
for (number in numbers) {
lastBoard.mark(number)
if (lastBoard.hasBingo()) {
return lastBoard.sumOfUnmarkedNumbers() * number
}
}
return -1
}
data class NumbersAndBoards(val numbers: List<Int>, val boards: List<Board>)
class Board(val numbers: List<List<Int>>) {
var marked: MutableList<MutableList<Boolean>> = mutableListOf()
init {
for (i in numbers.indices) {
marked.add(Array(5) { false }.toMutableList())
}
}
fun mark(number: Int) {
for (i in marked.indices) {
for (j in marked.indices) {
if (numbers[i][j] == number) {
marked[i][j] = true
}
}
}
}
fun hasBingo(): Boolean {
for (i in marked.indices) {
val lineMatch = marked.indices.all { j -> marked[i][j] }
val rowMatch = marked.indices.all { j -> marked[j][i] }
val firstDiagonal = marked.indices.map { marked.size - 1 - it }.all { j -> marked[i][j] }
val secondDiagonal = marked.indices.map { marked.size - 1 - it }.all { j -> marked[j][i] }
if (lineMatch || rowMatch || firstDiagonal || secondDiagonal) {
return true
}
}
return false
}
fun sumOfUnmarkedNumbers(): Int {
var result = 0
for (i in marked.indices) {
for (j in marked.indices) {
if (!marked[i][j]) {
result += numbers[i][j]
}
}
}
return result
}
}
| 0 |
Kotlin
| 0 | 0 |
4c4cbf677d97cfe96264b922af6ae332b9044ba8
| 3,229 |
advent_of_code
|
MIT License
|
src/Day15.kt
|
jinie
| 572,223,871 | false |
{"Kotlin": 76283}
|
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun ints(input: String): List<Int>{
return """-?\d+""".toRegex().findAll(input).map { it.value.toInt()}.toList()
}
fun String.aints() = ints(this)
private class Day15(val lines: List<String>) {
val sensors = lines.map { it.aints() }.map { Point2d(it[0], it[1]) to Point2d(it[2], it[3]) }
val beaconDistance = lines.map { it.aints() }.map { Point2d(it[0], it[1]) to Point2d(it[2], it[3]) }.map {it.first to it.first.manhattanDistance(it.second) }.toList()
fun findOpenSpot(i: Int): Long {
val notHereRanges = mutableSetOf<IntRange>()
for (s in beaconDistance) {
val sensorLocation = s.first
val dSToI = i - sensorLocation.y
val total = s.second
if (abs(dSToI) > total)
continue
val y = dSToI
val dx = total - abs(y)
val notHereRange = -dx + sensorLocation.x..dx + sensorLocation.x
notHereRanges.add(notHereRange)
}
val rangeList = notHereRanges.sortedBy { it.first }.toList()
var bigRange = rangeList[0]
if (bigRange.first > 0) {
return 0
}
for (r in rangeList) {
if (bigRange.contains(r)) {
continue
}
if (bigRange.overlaps(r) || bigRange.last + 1 == r.first) {
bigRange = min(bigRange.first, r.first)..max(bigRange.last, r.last)
} else {
return bigRange.last + 1.toLong()
}
}
return -1
}
fun part1(targetY: Int): Long {
val notHereRange = mutableSetOf<IntRange>()
beaconDistance.forEach { s ->
for (sensor in beaconDistance) {
val sensorLocation = sensor.first
val total = sensor.second
if (abs(targetY - sensorLocation.y) > total) {
continue
}
val dx = total - abs(targetY - sensorLocation.y)
notHereRange.add(-dx + sensorLocation.x..dx + sensorLocation.x)
}
}
val lineII = notHereRange.flatten().distinct()
val beaconsI = sensors.map { it.second }.filter { it.y == targetY }.distinct()
return lineII.size - beaconsI.size.toLong()
}
fun part2(dimension: Int): Long {
for (y in 0..dimension) {
val x = findOpenSpot(y)
if (x != -1L) {
return x * 4_000_000 + y
}
}
return -1
}
}
fun main() {
val todayTest = Day15(readInput("Day15_test"))
check(todayTest.part1(20) == 27L)
measureTimeMillisPrint {
val today = Day15(readInput("Day15"))
println(today.part1(2000000))
println(today.part2(4_000_000))
}
}
| 0 |
Kotlin
| 0 | 0 |
4b994515004705505ac63152835249b4bc7b601a
| 2,837 |
aoc-22-kotlin
|
Apache License 2.0
|
src/Day18.kt
|
andrikeev
| 574,393,673 | false |
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
|
import kotlin.math.abs
fun main() {
data class Cube(val x: Int, val y: Int, val z: Int)
fun List<String>.parse(): List<Cube> {
return map {
val (x, y, z) = it.split(",").map(String::toInt)
Cube(x, y, z)
}
}
fun part1(input: List<String>): Int {
fun Cube.isConnectedTo(cube: Cube): Boolean {
return abs(cube.x - x) == 1 && cube.y == y && cube.z == z ||
abs(cube.y - y) == 1 && cube.x == x && cube.z == z ||
abs(cube.z - z) == 1 && cube.y == y && cube.x == x
}
return with(input.parse().toSet()) {
sumOf { cube -> 6 - count(cube::isConnectedTo) }
}
}
fun part2(input: List<String>): Int {
val rock = input.parse().toSet()
var surfaces = 0
val xx = rock.minOf(Cube::x) - 1..rock.maxOf(Cube::x) + 1
val yy = rock.minOf(Cube::y) - 1..rock.maxOf(Cube::y) + 1
val zz = rock.minOf(Cube::z) - 1..rock.maxOf(Cube::z) + 1
val visited = mutableSetOf<Cube>()
val queue = ArrayDeque<Cube>(1).apply {
add(Cube(xx.first, yy.first, zz.first))
}
fun enqueue(cube: Cube) {
if (cube.x in xx && cube.y in yy && cube.z in zz) {
queue.addLast(cube)
visited.add(cube)
}
}
fun Cube.neighbours(visited: Set<Cube>): Set<Cube> = buildSet {
fun tryAdd(cube: Cube) {
if (cube !in visited) add(cube)
}
tryAdd(copy(x = x - 1))
tryAdd(copy(x = x + 1))
tryAdd(copy(y = y - 1))
tryAdd(copy(y = y + 1))
tryAdd(copy(z = z - 1))
tryAdd(copy(z = z + 1))
}
while (queue.isNotEmpty()) {
queue.removeFirst()
.neighbours(visited)
.forEach { cube ->
if (cube in rock) {
surfaces++
} else {
enqueue(cube)
}
}
}
return surfaces
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
check(part1(testInput).also { println("part1 test: $it") } == 64)
check(part2(testInput).also { println("part2 test: $it") } == 58)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
1aedc6c61407a28e0abcad86e2fdfe0b41add139
| 2,472 |
aoc-2022
|
Apache License 2.0
|
src/main/kotlin/Day03.kt
|
NielsSteensma
| 572,641,496 | false |
{"Kotlin": 11875}
|
val alphabet = ('a'..'z').toMutableList()
fun main() {
val input = readInput("Day03")
println("Day 03 Part 1 ${calculateDay03Part1(input)}")
println("Day 03 Part 2 ${calculateDay03Part2(input)}")
}
fun calculateDay03Part1(input: List<String>): Int {
val priority = input.map(::getCompartments).map(::commonItem).map(::priority)
return priority.sum()
}
fun calculateDay03Part2(input: List<String>): Int {
val priority = input.chunked(3).map(::commonGroupItem).map(::priority)
return priority.sum()
}
private fun getCompartments(itemsInRucksack: String): Pair<String, String> {
val halfIndex = itemsInRucksack.count() / 2
val leftCompartment = itemsInRucksack.substring(0, halfIndex)
val rightCompartment = itemsInRucksack.substring(halfIndex, itemsInRucksack.count())
return Pair(leftCompartment, rightCompartment)
}
private fun commonItem(compartments: Pair<String, String>): Char {
val (leftCompartment, rightCompartment) = compartments
var recurringChar: Char? = null
leftCompartment.forEach {
if (rightCompartment.contains(it)) {
recurringChar = it
}
}
return recurringChar!!
}
private fun commonGroupItem(rucksacks: List<String>): Char {
var recurringGroupItem: Char? = null
rucksacks.first().forEach { groupItem ->
val otherRucksacks = rucksacks.subList(1, rucksacks.size)
var foundGroupItem = true
otherRucksacks.forEach {
foundGroupItem = it.contains(groupItem) && foundGroupItem != false
}
if (foundGroupItem) {
recurringGroupItem = groupItem
}
}
return recurringGroupItem!!
}
private fun priority(char: Char): Int {
var priority = if (char.isUpperCase()) 26 else 0
priority += alphabet.indexOf(char.lowercase()[0]) + 1
return priority
}
| 0 |
Kotlin
| 0 | 0 |
4ef38b03694e4ce68e4bc08c390ce860e4530dbc
| 1,849 |
aoc22-kotlin
|
Apache License 2.0
|
src/Day04.kt
|
MatthiasDruwe
| 571,730,990 | false |
{"Kotlin": 47864}
|
fun main() {
fun part1(input: List<String>): Int {
val output = input.map { it.split(",").map { minmax -> minmax.split("-").map { number-> number.toInt() } } }.map{
(it[0][0]>= it[1][0] && it[0][1]<=it[1][1]) || (it[1][0] >= it[0][0] && it[1][1]<= it[0][1])
}.count { it }
return output
}
fun part2(input: List<String>): Int {
val output = input.map { it.split(",").map { minmax -> minmax.split("-").map { number-> number.toInt() } } }.map {
(it[0][0] >= it[1][0] && it[0][1] <= it[1][0]) || (it[1][0] >= it[0][0] && it[1][0] <= it[0][1]) || (it[0][1] >= it[1][0] && it[0][1] <= it[1][1])
|| (it[1][1]>=it[0][0] && it[1][1]<=it[0][1])
}.count { it }
return output
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_example")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
f35f01cea5075cfe7b4a1ead9b6480ffa57b4989
| 1,059 |
Advent-of-code-2022
|
Apache License 2.0
|
src/twentytwo/Day04.kt
|
mihainov
| 573,105,304 | false |
{"Kotlin": 42574}
|
package twentytwo
import readInputTwentyTwo
data class Section(val start: Int, val end: Int) {
fun getSize(): Int {
return end - start
}
}
data class ElfSections(val firstSection: Section?, val secondSection: Section?)
fun String.toSections(): ElfSections {
val elvesSection = this.split(",")
val firstElfSections = elvesSection.component1().split("-")
val firstSection = Section(firstElfSections.component1().toInt(), firstElfSections.component2()!!.toInt())
val secondElfSections = elvesSection.component2()!!.split("-")
val secondSection = Section(secondElfSections.component1().toInt(), secondElfSections.component2()!!.toInt())
// sort so that the bigger section is always first
val sections = listOf(firstSection, secondSection).sortedBy { it.getSize() }.reversed()
return ElfSections(sections.component1(), sections.component2())
}
fun main() {
fun part1(input: List<String>): Int {
return input.map { it.toSections() }
.stream()
.filter { it.firstSection!!.start <= it.secondSection!!.start && it.firstSection.end >= it.secondSection.end }
.count()
.toInt()
}
fun part2(input: List<String>): Int {
return input.map { it.toSections() }
.stream()
.filter {
it.secondSection!!.start in it.firstSection!!.start..it.firstSection.end
|| it.secondSection.end in it.firstSection.start..it.firstSection.end
}
.count()
.toInt()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputTwentyTwo("Day04_test")
check(part1(testInput).also(::println) == 2)
check(part2(testInput).also(::println) == 4)
val input = readInputTwentyTwo("Day04")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
a9aae753cf97a8909656b6137918ed176a84765e
| 1,887 |
kotlin-aoc-1
|
Apache License 2.0
|
src/Day03.kt
|
strindberg
| 572,685,170 | false |
{"Kotlin": 15804}
|
fun priority(char: Char) =
if (char.isUpperCase()) char - 'A' + 27 else if (char.isLowerCase()) char - 'a' + 1 else throw RuntimeException()
fun String.uniqueChars() = this.toSet().toList()
fun main() {
fun part1(input: List<String>): Int =
input.sumOf { line ->
val first = line.take(line.length / 2).uniqueChars()
val second = line.takeLast(line.length / 2).uniqueChars()
val doubles = (first + second)
.groupBy { it }
.filter { it.value.size > 1 }
.map { it.key }
priority(doubles[0])
}
fun part2(input: List<String>): Int =
input.fold(Pair(0, listOf<String>())) { (sum, list), line ->
if (list.size < 2) {
Pair(sum, list + line)
} else {
val triples = (list[0].uniqueChars() + list[1].uniqueChars() + line.uniqueChars())
.groupBy { it }
.filter { it.value.size == 3 }
.map { it.key }
Pair(sum + priority(triples[0]), listOf())
}
}.first
val input = readInput("Day03")
println(part1(input))
check(part1(input) == 8105)
println(part2(input))
check(part2(input) == 2363)
}
| 0 |
Kotlin
| 0 | 0 |
c5d26b5bdc320ca2aeb39eba8c776fcfc50ea6c8
| 1,392 |
aoc-2022
|
Apache License 2.0
|
src/Day16.kt
|
Riari
| 574,587,661 | false |
{"Kotlin": 83546, "Python": 1054}
|
fun main() {
data class Valve(val id: String, val rate: Int, val edges: List<String>)
data class State(val valves: Map<String, Valve>, val shortestPaths: MutableMap<String, MutableMap<String, Int>>, var score: Int = 0)
fun processInput(input: List<String>): State {
val list = mutableListOf<Valve>()
val regexValves = Regex("[A-Z]{2}")
val regexFlow = Regex("\\d+")
for (line in input) {
val valves = regexValves.findAll(line).map { it.value }.toList()
val flow = regexFlow.find(line)!!.value.toInt()
list.add(Valve(valves[0], flow, valves.subList(1, valves.lastIndex + 1)))
}
// The Floyd-Warshall algorithm seems to be a perfect fit for this day, but it's totally new to me.
// I ended up borrowing the implementation from here: https://github.com/ckainz11/AdventOfCode2022/blob/main/src/main/kotlin/days/day16/Day16.kt
val shortestPaths = list.associate { it.id to it.edges.associateWith { 1 }.toMutableMap() }.toMutableMap()
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)
}
}
}
val map = list.associateBy { it.id }
shortestPaths.values.forEach { it.keys.removeIf { valve -> map[valve]?.rate == 0 } }
return State(map, shortestPaths)
}
// Solve using recursive DFS
fun solve(state: State, timeLimit: Int = 30, withHelp: Boolean = false, opened: Set<String> = setOf(), score: Int = 0, currentValve: String = "AA", timer: Int = 0) {
state.score = maxOf(state.score, score)
for ((valve, distance) in state.shortestPaths[currentValve]!!) {
val ticks = timer + distance + 1
if (opened.contains(valve) || ticks >= timeLimit) continue
solve(
state,
timeLimit,
withHelp,
opened.union(listOf(valve)),
score + (timeLimit - ticks) * state.valves[valve]!!.rate,
valve,
ticks)
}
if (withHelp) solve(state, timeLimit, false, opened, score)
}
fun part1(state: State): Int {
solve(state)
return state.score
}
fun part2(state: State): Int {
state.score = 0
solve(state, 26, true)
return state.score
}
val testInput = processInput(readInput("Day16_test"))
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = processInput(readInput("Day16"))
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
| 2,899 |
aoc-2022
|
Apache License 2.0
|
src/Day03.kt
|
davedupplaw
| 573,042,501 | false |
{"Kotlin": 29190}
|
fun main() {
fun findCommonItem(rucksackContents: String): Char {
val numberOfItems = rucksackContents.length / 2
val firstCompartmentContents = rucksackContents.substring(0, numberOfItems)
val secondCompartmentContents = rucksackContents.substring(numberOfItems)
return firstCompartmentContents.find { item ->
secondCompartmentContents.contains(item)
}!!
}
fun convertToPriorities(commonItem: Char): Int {
val priority = commonItem.code - 96
return if(priority > 0) priority else priority + 58
}
fun part1(input: List<String>): Int {
return input
.map { findCommonItem(it) }
.sumOf { convertToPriorities(it) }
}
fun findCommonItems(rucksack1: Set<Char>, rucksack2: String): Set<Char> {
return rucksack1.mapNotNull { item ->
if (rucksack2.contains(item)) item else null
}.toSet()
}
fun findCommonItemInGroup(group: List<String>): Char {
val firstRucksack = group[0]
var foundItems = firstRucksack.toCharArray().toSet()
for (rucksack in group.drop(1)) {
foundItems = findCommonItems(foundItems, rucksack)
}
return foundItems.toList()[0]
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map { findCommonItemInGroup(it) }
.sumOf { convertToPriorities(it) }
}
val test = readInput("Day03.test")
val part1 = part1(test)
println("part1: $part1")
check(part1 == 157)
val part2 = part2(test)
println("part2: $part2")
check(part2 == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
3b3efb1fb45bd7311565bcb284614e2604b75794
| 1,743 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day24.kt
|
er453r
| 572,440,270 | false |
{"Kotlin": 69456}
|
fun main() {
val directions = mapOf('<' to Vector3d.LEFT, '>' to Vector3d.RIGHT, '^' to Vector3d.UP, 'v' to Vector3d.DOWN)
val neighboursInTime = directions.values.map { it + Vector3d.BACK }.toSet() + Vector3d.BACK
val start = Vector3d(0, -1, 0)
fun isEmpty(positionInTime: Vector3d, width: Int, height: Int, initialState: Map<Vector3d, Vector3d?>, start: Vector3d, end: Vector2d) = when {
(positionInTime.x == start.x && positionInTime.y == start.y) || (positionInTime.x == end.x && positionInTime.y == end.y) -> true // start or end is OK
positionInTime.x !in (0 until width) || positionInTime.y !in (0 until height) -> false
directions.values.map { direction ->
Pair((Vector3d(positionInTime.x, positionInTime.y, 0) - direction * positionInTime.z).apply {
x = (width + (x % width)) % width
y = (height + (y % height)) % height
}, direction)
}.any { (possibleBlizzard, direction) -> possibleBlizzard in initialState && initialState[possibleBlizzard] == direction } -> false
else -> true
}
fun neighbours(node: Vector3d, start: Vector3d, end: Vector2d, width: Int, height: Int, initialState: Map<Vector3d, Vector3d?>): Set<Vector3d> {
return neighboursInTime.map { node + it }.filter { isEmpty(it, width, height, initialState, start, end) }.toSet()
}
fun part1(input: List<String>): Int {
val grid = Grid(input.map { it.toCharArray().toList() })
val width = grid.width - 2
val height = grid.height - 2
val end = Vector2d(width - 1, height)
val initialState = grid.data.flatten().filter { it.value in directions }.associate {
Vector3d(it.position.x, it.position.y, 0) - Vector3d(1, 1, 0) to directions[it.value]
}
val path = aStar(
start = start,
isEndNode = { node -> node.x == end.x && node.y == end.y },
heuristic = { (end - Vector2d(it.x, it.y)).manhattan() },
neighbours = { node ->
neighbours(node, start, end, width, height, initialState)
})
return path.size - 1
}
fun part2(input: List<String>): Int {
val grid = Grid(input.map { it.toCharArray().toList() })
val width = grid.width - 2
val height = grid.height - 2
val end = Vector2d(width - 1, height)
val initialState = grid.data.flatten().filter { it.value in directions }.associate {
Vector3d(it.position.x, it.position.y, 0) - Vector3d(1, 1, 0) to directions[it.value]
}
val path1 = aStar(
start = start,
isEndNode = { node -> node.x == end.x && node.y == end.y },
heuristic = { (end - Vector2d(it.x, it.y)).manhattan() },
neighbours = { node ->
neighbours(node, start, end, width, height, initialState)
})
val path2 = aStar(
start = path1.first(),
isEndNode = { node -> node.x == 0 && node.y == -1 },
heuristic = { (end - Vector2d(it.x, it.y)).manhattan() },
neighbours = { node ->
neighbours(node, start, end, width, height, initialState)
})
val path3 = aStar(
start = path2.first(),
isEndNode = { node -> node.x == end.x && node.y == end.y },
heuristic = { (end - Vector2d(it.x, it.y)).manhattan() },
neighbours = { node ->
neighbours(node, start, end, width, height, initialState)
})
return path1.size + path2.size + path3.size - 3
}
test(
day = 24,
testTarget1 = 18,
testTarget2 = 54,
part1 = ::part1,
part2 = ::part2,
)
}
| 0 |
Kotlin
| 0 | 0 |
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
| 3,773 |
aoc2022
|
Apache License 2.0
|
src/Day07.kt
|
peterfortuin
| 573,120,586 | false |
{"Kotlin": 22151}
|
fun main() {
fun parseToTree(input: List<String>): TreeNode {
val rootNode = TreeNode("root")
var currentNode = rootNode
input.forEach { line ->
when {
!line.contains("$") && line.contains("dir") -> currentNode.add(TreeNode(line.split(" ")[1]))
!line.contains("$") -> currentNode.add(TreeNode(line.split(" ")[1], line.split(" ")[0].toInt()))
line == "$ cd .." -> currentNode = currentNode.parent!!
line.startsWith("\$ cd ") && line != "\$ cd /" -> currentNode =
currentNode.children.first { it.name == line.split(" ")[2] }
}
}
return rootNode
}
fun part1(input: List<String>): Int {
val tree = parseToTree(input)
var totalSize = 0
tree.forEachDepthFirst { node ->
if (node.isDirectory() && node.getSize() < 100000) {
totalSize += node.getSize()
}
}
return totalSize
}
fun part2(input: List<String>): Int {
val tree = parseToTree(input)
val spaceNeeded = 30000000 - (70000000 - tree.getSize())
val dirList = mutableListOf<TreeNode>()
tree.forEachDepthFirst { node ->
if (node.isDirectory()) {
dirList.add(node)
}
}
dirList
.filter { dir -> dir.getSize() > spaceNeeded }
.sortedBy { dir -> dir.getSize() }.first()
.let { dir ->
return dir.getSize()
}
}
// 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("Part 1 = ${part1(input)}")
println("Part 2 = ${part2(input)}")
}
typealias Visitor = (TreeNode) -> Unit
class TreeNode(val name: String, private val size: Int = 0) {
val children: MutableList<TreeNode> = mutableListOf()
var parent: TreeNode? = null
fun add(child: TreeNode): Boolean {
child.parent = this
return children.add(child)
}
fun forEachDepthFirst(visit: Visitor) {
visit(this)
children.forEach {
it.forEachDepthFirst(visit)
}
}
fun getSize(): Int {
return size + children.sumOf { it.getSize() }
}
fun isDirectory(): Boolean {
return children.isNotEmpty()
}
override fun toString(): String {
return toString(0)
}
private fun toString(indentation: Int): String {
return " ".repeat(indentation) + "- $name\n" + children
.joinToString("") { child -> child.toString(indentation + 2) }
}
}
| 0 |
Kotlin
| 0 | 0 |
c92a8260e0b124e4da55ac6622d4fe80138c5e64
| 2,765 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day15.kt
|
Cryosleeper
| 572,977,188 | false |
{"Kotlin": 43613}
|
import kotlin.math.abs
fun main() {
fun part1(input: List<String>, yToUse: Int): Int {
val sensors = input.parseToSensors()
val pointsToIgnore = mutableSetOf<Beacon>()
val minX = sensors.minBy { it.x }.x
val maxX = sensors.maxBy { it.x }.x
val maxDistance = sensors.maxBy { it.distance }.distance
((minX - maxDistance)..(maxX + maxDistance)).forEach { x ->
for (sensor in sensors) {
if (sensor.distanceTo(x, yToUse) <= sensor.distance) {
pointsToIgnore.add(Beacon(x, yToUse))
break
}
}
}
pointsToIgnore.removeAll(sensors.map { it.beacon }.toSet())
println("Points to ignore: $pointsToIgnore")
return pointsToIgnore.size
}
fun part2(input: List<String>, coordinateLimit: Int): Long {
val sensors = input.parseToSensors()
lateinit var result: Beacon
run search@ {
sensors.forEach {
(-it.distance-1..it.distance+1).forEach {dx ->
listOf(it.distance - abs(dx) + 1, it.distance + abs(dx) - 1).forEach {dy ->
val x = it.x + dx
val y = it.y + dy
if (x in 0..coordinateLimit && y in 0..coordinateLimit) {
println("Checking $x, $y")
if (sensors.none { sensorToCheck ->
sensorToCheck.distanceTo(
x,
y
) <= sensorToCheck.distance
}) {
result = Beacon(x, y)
return@search
}
}
}
}
}
}
return result.x * 4000000L + result.y
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
val input = readInput("Day15")
//println(part1(input, 2000000))
println(part2(input, 4000000))
}
private fun List<String>.parseToSensors(): List<Sensor> {
val result = mutableListOf<Sensor>()
this.forEach {line ->
line.split(":").apply {
val (sx, sy) = "-?\\d+".toRegex().findAll(this[0]).toList().subList(0, 2).map { it.value.toInt() }
val (bx, by) = "-?\\d+".toRegex().findAll(this[1]).toList().subList(0, 2).map { it.value.toInt() }
result.add(Sensor(sx, sy, Beacon(bx, by)))
}
}
println("Parsed sensors are $result")
return result
}
private data class Beacon(val x: Int, val y: Int)
private data class Sensor(val x: Int, val y: Int, val beacon: Beacon) {
val distance: Int by lazy { distanceTo(beacon.x, beacon.y) }
fun distanceTo(x: Int, y: Int) = abs(this.x - x) + abs(this.y - y)
}
| 0 |
Kotlin
| 0 | 0 |
a638356cda864b9e1799d72fa07d3482a5f2128e
| 3,059 |
aoc-2022
|
Apache License 2.0
|
cz.wrent.advent/Day18.kt
|
Wrent
| 572,992,605 | false |
{"Kotlin": 206165}
|
package cz.wrent.advent
import java.util.*
fun main() {
println(partOne(test))
val result = partOne(input)
println("18a: $result")
println(partTwo(test))
val resultTwo = partTwo(input)
println("18b: $resultTwo")
}
private fun partOne(input: String): Int {
val cubes = input.split("\n")
.map { it.parseCube() }
.toSet()
return cubes.sumOf { it.getArea(cubes) }
}
private fun partTwo(input: String): Int {
val cubes = input.split("\n")
.map { it.parseCube() }
.toSet()
val maxX = cubes.maxByOrNull { it.x }!!.x
val maxY = cubes.maxByOrNull { it.y }!!.y
val maxZ = cubes.maxByOrNull { it.z }!!.z
val minX = cubes.minByOrNull { it.x }!!.x
val minY = cubes.minByOrNull { it.y }!!.y
val minZ = cubes.minByOrNull { it.z }!!.z
val bigCube = mutableSetOf<Cube>()
for (i in minX - 1 .. maxX + 1) {
for (j in minY - 1 .. maxY + 1) {
for (k in minZ - 1 .. maxZ + 1) {
bigCube.add(Cube(i, j, k))
}
}
}
val visited = blowAir(Cube(minX - 1, minY - 1, minZ - 1), bigCube, cubes)
val inside = bigCube.minus(visited).minus(cubes)
return cubes.sumOf { it.getArea(cubes) } - inside.sumOf { it.getArea(inside) }
}
private fun blowAir(
cube: Cube,
bigCube: Set<Cube>,
cubes: Set<Cube>,
): Set<Cube> {
val deque: Deque<Cube> = LinkedList(listOf(cube))
val visited = mutableSetOf<Cube>()
while (deque.isNotEmpty()) {
val next = deque.pop()
visited.add(next)
next.getNeighbours(bigCube).forEach {
if (!(visited.contains(it) || cubes.contains(it))) {
deque.push(it)
}
}
}
return visited
}
private fun String.parseCube(): Cube {
return this.split(",")
.map { it.toInt() }
.let {
Cube(it.get(0), it.get(1), it.get(2))
}
}
private data class Cube(val x: Int, val y: Int, val z: Int) {
fun getArea(cubes: Set<Cube>): Int {
return 6 - getNeighbours(cubes).size
}
fun getNeighbours(cubes: Set<Cube>): Set<Cube> {
return setOf(
Cube(x + 1, y, z),
Cube(x - 1, y, z),
Cube(x, y + 1, z),
Cube(x, y - 1, z),
Cube(x, y, z + 1),
Cube(x, y, z - 1)
).intersect(cubes)
}
}
private const val test = """2,2,2
1,2,2
3,2,2
2,1,2
2,3,2
2,2,1
2,2,3
2,2,4
2,2,6
1,2,5
3,2,5
2,1,5
2,3,5"""
private const val input = """1,8,8
12,8,3
13,16,7
8,1,11
7,17,7
14,11,16
13,9,17
5,9,3
6,6,4
15,11,5
3,13,9
17,9,15
12,1,8
4,14,5
9,11,17
13,16,11
7,8,16
13,14,14
16,9,4
9,17,12
3,10,5
8,5,15
7,5,15
13,7,2
9,3,12
4,10,4
13,10,15
11,14,3
6,11,2
15,5,14
14,4,12
16,11,6
12,3,10
12,3,5
12,12,15
10,7,2
8,17,6
13,4,14
11,1,8
10,16,13
11,14,16
4,5,4
8,10,17
15,7,10
12,15,16
4,13,13
14,3,12
8,18,12
7,17,8
15,12,15
15,10,3
13,9,14
11,5,5
9,10,18
12,12,1
6,15,9
10,17,10
11,1,9
7,14,3
10,16,5
3,8,5
19,7,9
16,5,9
15,11,3
2,8,13
16,11,9
2,9,11
4,4,13
13,6,16
3,14,8
9,4,9
4,5,12
12,14,15
1,10,11
16,7,6
16,12,10
6,3,11
14,6,4
8,10,18
12,4,16
11,18,8
3,9,12
17,8,12
13,8,17
10,13,2
10,7,1
9,16,4
9,4,4
8,14,15
10,6,17
12,16,14
8,14,16
17,11,6
12,16,10
15,11,12
14,9,5
11,15,15
15,6,9
3,8,13
8,5,16
17,8,9
2,11,9
16,13,6
10,9,2
14,3,6
12,4,14
3,10,12
8,6,16
4,12,6
10,14,13
17,9,6
3,14,10
14,9,3
9,14,17
16,7,10
9,1,8
12,13,17
13,4,9
15,14,13
12,17,11
7,14,6
11,16,12
11,17,13
16,14,13
9,5,3
6,4,14
13,16,6
6,9,2
15,12,14
9,14,5
10,12,3
3,5,11
17,11,12
2,8,12
5,7,3
15,5,6
10,14,16
12,4,4
16,7,14
13,9,3
11,15,3
10,15,15
2,12,13
8,12,17
6,15,14
12,14,5
14,5,14
8,10,1
11,6,4
8,15,5
17,7,10
9,11,0
5,16,8
10,10,18
11,14,15
4,7,6
8,2,9
16,13,7
8,7,2
15,14,4
12,18,9
17,9,13
11,10,17
15,13,11
13,2,8
3,13,8
11,16,5
16,8,5
12,13,16
9,2,12
8,17,9
7,1,10
16,4,7
9,1,10
16,10,14
16,6,10
16,13,11
3,4,11
3,12,6
3,8,3
14,12,14
10,15,2
12,5,3
11,2,10
10,2,14
6,17,11
15,14,9
6,16,7
14,13,13
4,11,5
11,17,7
3,10,7
5,9,5
6,9,1
14,14,4
9,4,17
9,5,15
3,9,5
13,12,17
13,16,12
7,6,16
11,15,5
8,17,7
8,4,15
13,2,12
10,13,17
4,6,14
4,6,13
5,4,9
7,12,17
5,10,14
17,12,9
10,18,9
9,12,14
7,9,1
14,14,8
7,2,12
3,15,9
4,14,7
2,12,11
13,4,12
3,11,12
2,6,11
6,5,3
5,5,5
4,10,13
11,2,8
10,11,17
16,4,10
16,11,11
9,2,10
15,15,11
15,4,9
4,12,14
6,11,16
12,17,6
15,13,15
7,8,3
14,8,14
7,17,10
4,7,8
9,2,8
13,13,18
10,3,5
3,8,10
9,7,17
14,11,3
16,12,6
1,9,7
16,10,6
12,18,10
12,15,13
9,16,6
9,17,14
8,4,4
12,4,3
6,8,17
3,12,10
7,7,3
7,6,3
4,10,15
15,3,7
6,7,4
8,16,12
16,10,4
14,9,4
12,9,17
16,7,7
3,11,7
14,12,5
17,7,7
12,16,11
9,12,5
14,15,7
7,6,15
13,4,6
14,15,8
11,11,16
16,15,9
3,5,7
6,5,6
3,7,13
14,13,15
5,15,6
7,16,5
10,4,7
7,5,4
7,15,4
8,9,2
11,2,6
15,13,13
17,10,6
8,16,4
13,12,12
5,16,12
10,17,12
5,11,15
16,7,5
8,18,10
16,10,11
15,13,9
15,14,14
5,8,3
9,6,3
4,7,15
4,17,9
15,6,4
7,15,5
6,12,15
10,16,6
9,13,17
11,2,9
5,6,14
5,9,17
14,13,14
9,3,13
5,8,16
16,5,13
11,14,14
10,14,17
14,3,7
15,4,7
15,16,9
7,15,14
9,7,4
9,3,15
7,16,6
3,7,11
7,6,2
10,4,4
14,7,16
9,17,11
14,7,3
15,3,10
8,4,2
11,5,3
13,15,8
12,2,10
13,15,14
13,8,1
15,7,5
4,7,14
13,12,4
5,17,10
4,8,16
6,12,2
3,8,11
7,10,17
5,11,17
2,9,12
7,18,7
9,3,11
5,14,6
4,15,12
5,8,7
2,9,4
8,4,10
12,12,2
12,4,6
14,10,15
13,17,7
10,8,1
16,6,12
16,11,14
14,3,8
15,12,13
5,10,3
14,14,12
16,9,14
3,12,5
13,15,6
7,5,3
12,13,3
5,8,15
17,5,8
8,3,6
17,7,8
8,3,13
12,10,4
12,10,17
15,12,6
10,0,8
6,18,10
14,16,10
9,5,4
6,15,15
9,10,16
12,6,16
10,8,17
5,14,9
6,13,16
11,2,7
2,12,7
11,3,4
7,3,14
16,10,15
6,15,13
12,2,12
7,9,16
12,11,17
8,10,2
5,6,3
11,7,16
13,10,17
12,5,17
15,12,4
14,15,14
4,14,9
2,8,11
8,8,17
7,13,16
15,9,14
16,8,15
11,4,16
14,7,15
4,12,15
4,3,11
15,7,11
12,3,13
11,5,16
10,14,15
17,10,5
14,9,15
4,7,5
13,11,1
14,11,14
3,7,7
3,5,13
4,4,10
2,8,9
5,13,3
3,13,10
5,7,15
9,12,1
18,9,13
16,13,10
5,7,4
11,4,5
3,14,13
14,5,15
2,7,10
12,13,4
9,17,7
6,2,11
10,5,3
11,1,11
6,9,3
13,6,14
12,17,13
5,13,16
3,8,4
8,13,2
13,12,1
16,14,12
9,4,6
10,2,6
4,7,4
9,12,2
12,11,1
6,13,15
8,16,14
10,3,6
16,10,8
12,16,9
6,18,9
8,6,4
14,16,12
11,6,16
3,15,7
4,7,7
3,9,11
4,5,7
17,8,5
9,12,18
7,12,3
3,9,14
14,5,7
10,0,11
15,7,3
8,16,13
8,4,5
18,11,11
12,10,3
3,15,13
17,13,7
2,12,8
16,4,11
13,11,17
11,6,3
3,13,4
12,6,4
12,6,5
3,5,6
5,15,13
16,10,5
9,14,16
18,7,8
7,11,3
4,9,14
7,3,5
16,10,9
8,4,16
16,14,9
15,6,15
6,16,6
11,10,1
7,2,13
8,2,14
6,6,15
14,14,15
17,10,12
5,4,15
17,13,5
3,5,10
2,7,7
15,16,8
3,13,12
5,3,11
17,8,11
10,5,2
14,6,15
8,17,13
10,9,18
2,10,9
14,15,5
15,4,8
10,10,16
16,10,13
9,14,3
10,5,4
4,16,10
14,4,5
2,12,10
5,11,5
17,13,11
2,11,13
17,10,7
17,6,10
8,12,18
16,10,7
7,12,16
5,17,11
11,13,3
9,5,16
10,14,5
13,12,16
16,8,8
2,12,9
7,14,14
4,15,6
8,14,3
2,12,12
4,11,16
6,7,16
9,7,16
10,13,4
16,6,8
10,18,5
3,6,8
8,5,3
11,13,2
10,3,15
10,11,1
13,5,5
1,10,9
9,3,8
9,6,16
5,3,6
9,4,14
12,3,14
4,5,6
13,17,12
18,10,7
7,13,15
17,9,14
4,6,3
9,16,9
10,8,18
11,4,4
17,14,11
13,3,13
10,15,5
2,7,8
11,7,2
6,10,17
16,9,8
13,14,13
13,14,4
9,2,13
2,13,9
14,6,5
4,13,6
15,5,12
15,15,6
9,10,2
16,8,11
15,13,4
2,11,11
7,10,2
16,13,8
13,6,4
6,14,15
6,12,4
17,6,8
5,12,16
5,15,11
4,8,4
14,10,16
11,1,12
15,12,5
11,10,3
5,15,12
15,7,7
10,18,13
10,17,14
9,18,7
9,11,2
12,14,16
13,5,3
18,7,11
13,18,9
6,16,12
5,8,13
7,2,11
15,8,15
15,10,7
10,14,3
16,13,15
4,8,14
9,11,16
12,6,3
11,2,5
7,4,15
7,2,8
13,5,15
6,10,3
4,14,6
18,9,11
1,8,9
7,4,8
12,2,6
14,9,7
12,3,9
2,9,13
1,8,10
3,13,5
16,11,4
10,11,2
5,3,8
8,16,7
13,10,3
17,8,6
17,12,5
11,12,2
7,2,10
4,9,15
10,17,13
3,12,15
10,6,3
16,12,8
15,10,15
9,17,13
11,8,3
9,14,2
12,3,12
11,16,7
3,6,12
9,16,8
11,17,11
6,9,18
13,2,7
4,7,11
15,8,10
8,4,12
2,9,6
6,12,16
11,16,14
4,8,7
12,15,5
9,3,6
12,3,8
15,2,10
1,11,12
17,12,11
5,5,15
17,14,10
4,9,5
14,6,8
13,5,14
8,5,17
1,9,11
3,10,14
16,7,11
15,11,2
11,14,17
7,14,16
4,9,16
15,8,3
3,9,4
6,7,3
8,13,15
5,10,15
17,7,6
3,7,6
7,15,15
17,6,7
11,15,2
14,13,4
4,4,12
8,17,8
9,11,1
16,8,4
18,8,9
11,18,10
3,9,15
5,2,11
5,10,4
12,8,18
7,16,13
12,16,12
5,6,7
7,8,17
16,6,11
12,18,11
14,8,5
15,14,7
17,7,12
5,11,11
8,2,5
12,1,12
3,9,6
15,7,6
13,15,3
7,12,14
10,4,2
13,15,5
2,13,13
14,5,5
16,12,7
5,14,12
12,12,3
16,14,11
2,14,10
14,16,5
15,5,9
4,12,5
19,8,8
16,5,10
6,3,7
10,2,12
11,17,9
8,11,15
9,8,17
6,2,9
9,1,7
9,2,16
9,13,15
17,14,13
3,6,6
5,14,7
7,10,3
17,9,12
10,3,13
14,12,12
7,16,14
8,2,11
8,13,17
5,12,15
9,4,13
3,5,8
2,10,5
4,15,11
13,2,9
3,12,14
3,5,9
8,16,6
3,9,7
14,9,16
13,17,8
10,2,8
6,15,10
5,14,5
16,8,10
5,12,4
14,14,5
3,7,12
4,8,12
15,4,14
4,4,8
14,5,12
12,1,10
13,3,6
4,14,14
8,5,4
14,4,6
11,6,2
6,4,4
9,12,17
4,13,12
8,4,6
5,5,16
2,6,7
15,13,12
6,2,8
16,12,15
16,11,13
10,12,16
7,17,5
11,13,4
10,16,16
10,15,7
12,13,2
4,3,8
7,3,7
13,8,3
11,15,17
13,16,10
11,12,4
16,15,11
1,8,7
3,11,4
6,9,16
10,17,11
6,15,7
12,15,4
6,9,17
7,13,1
14,16,8
3,6,9
4,16,12
5,9,2
15,12,3
5,6,5
9,12,4
7,10,1
6,3,12
10,3,8
14,4,15
5,4,6
7,13,3
17,7,13
15,13,6
6,4,9
4,5,13
8,8,2
3,12,11
13,2,10
15,7,15
0,11,7
17,11,13
17,10,8
4,7,3
2,11,7
11,17,8
7,4,10
6,6,14
8,5,14
15,11,4
14,8,15
4,3,9
10,4,12
14,16,11
2,9,7
15,12,9
5,11,3
10,2,13
9,2,14
5,9,4
3,7,5
15,6,14
5,15,8
7,4,7
6,8,16
2,15,12
16,14,8
9,7,13
8,14,17
13,11,2
4,9,13
14,13,12
7,10,16
11,16,13
13,14,5
2,8,6
15,13,10
15,5,5
18,7,10
17,13,9
6,16,9
4,14,13
11,15,4
15,11,15
15,15,9
14,8,4
10,17,6
15,13,7
6,8,2
10,10,17
5,12,2
10,6,18
17,6,5
4,6,12
8,7,18
6,16,11
4,15,10
9,18,10
3,13,11
16,5,8
12,17,8
11,11,17
9,17,6
8,1,13
13,17,6
9,9,17
2,6,9
12,16,7
17,6,12
10,2,7
15,10,4
8,15,15
14,16,7
16,5,7
3,5,14
11,7,5
7,3,4
13,11,3
2,9,5
11,6,18
10,17,8
3,11,10
10,9,1
7,2,7
16,9,13
8,12,16
4,8,6
8,15,4
4,16,11
3,15,10
16,9,11
8,8,16
5,16,9
17,8,8
12,14,4
6,14,6
16,3,9
11,13,17
9,14,14
7,4,13
9,2,15
8,11,18
17,11,7
7,9,2
8,1,9
11,17,10
8,18,8
14,12,16
16,14,5
3,15,12
11,4,6
9,18,9
15,10,16
3,9,10
5,4,14
8,17,11
5,14,11
15,13,5
16,3,10
10,10,2
9,9,2
16,7,12
10,7,17
10,12,18
11,8,17
10,4,16
14,12,6
11,12,3
3,12,9
4,6,8
11,1,10
4,3,12
13,4,13
8,16,8
10,8,2
13,16,13
8,8,18
11,16,15
5,13,15
13,13,6
5,15,5
10,1,10
14,3,10
13,8,14
7,5,12
16,7,9
15,16,10
6,4,5
5,14,14
16,6,6
15,12,12
18,9,8
1,8,12
5,13,14
17,9,7
12,14,2
4,12,3
7,6,13
11,10,18
10,1,12
15,4,13
8,6,1
12,10,16
7,6,4
6,10,16
17,13,10
12,16,6
15,5,13
6,17,13
9,1,12
9,8,16
10,4,13
11,7,3
18,10,8
11,1,6
6,17,8
16,13,5
13,14,15
14,14,14
16,8,9
3,6,11
4,6,5
6,16,10
11,18,9
7,4,11
5,5,12
3,14,6
10,9,3
3,14,9
8,10,16
9,15,6
8,2,13
7,14,4
13,2,11
12,10,2
8,7,3
3,4,10
2,15,8
14,2,8
7,17,11
4,13,11
7,15,9
13,17,9
15,4,11
13,17,13
2,7,11
8,18,7
14,13,5
3,6,5
10,2,11
9,13,16
11,2,12
7,13,4
10,16,15
7,4,14
11,4,15
4,13,7
15,7,13
13,15,12
6,4,12
11,15,11
16,12,5
18,8,8
4,6,7
13,3,5
6,7,17
15,3,6
9,17,5
8,7,17
8,5,2
3,11,15
10,5,17
5,7,16
17,10,14
3,7,8
7,16,7
7,11,2
15,13,8
2,7,13
11,16,4
4,12,4
9,4,15
4,5,15
12,5,4
13,7,3
9,16,10
5,10,5
4,16,8
4,5,10
7,3,13
16,13,12
15,14,6
13,3,9
11,3,14
1,6,10
15,8,17
4,12,13
8,18,6
14,15,9
10,4,3
9,18,8
2,8,5
16,5,12
3,8,12
15,15,7
9,15,8
15,7,4
3,15,11
17,9,5
16,11,12
13,9,16
11,7,17
6,14,3
9,16,16
11,7,1
16,15,8
11,18,7
9,2,7
5,5,3
16,12,12
13,5,4
12,1,9
7,5,16
6,4,15
17,10,11
2,6,8
5,16,11
5,13,4
5,9,15
6,14,13
14,15,13
4,9,12
16,12,9
6,13,3
10,1,8
13,11,18
14,14,16
1,10,7
14,4,9
3,14,11
3,7,10
8,2,8
2,8,7
7,9,17
3,12,12
14,17,10
9,14,4
3,6,10
6,11,14
16,4,8
7,11,17
14,12,13
11,3,10
7,11,15
12,5,14
11,9,17
12,5,5
8,17,12
17,9,9
3,11,5
2,11,6
10,1,7
4,5,14
8,16,5
17,11,14
7,13,17
17,11,11
9,2,9
9,5,2
11,8,2
3,10,4
11,6,15
12,4,11
5,4,10
10,4,15
17,12,7
4,13,10
14,7,4
16,12,11
7,16,8
10,2,10
14,17,13
9,6,5
15,4,5
3,5,12
15,13,14
8,3,9
9,4,3
3,12,7
6,1,12
8,9,16
15,14,11
15,12,8
15,14,15
1,11,11
6,16,8
12,16,5
16,8,13
8,11,1
11,1,7
4,15,8
18,8,13
13,14,3
3,8,7
15,7,14
4,6,6
10,18,10
5,4,4
6,4,13
1,10,8
7,7,17
13,3,8
14,8,17
6,8,3
14,14,6
3,6,14
13,17,10
12,3,6
14,5,16
17,5,9
17,5,10
16,15,10
2,13,7
8,17,5
18,12,11
8,17,10
16,5,5
9,2,11
5,4,13
14,8,3
16,7,13
11,12,17
17,8,10
4,5,5
13,12,15
16,12,13
8,16,11
4,15,7
10,1,11
2,10,10
9,15,5
9,16,14
7,13,2
17,11,8
12,8,16
6,3,6
2,13,8
6,6,13
17,7,11
8,12,15
5,12,3
16,15,7
5,9,13
6,3,8
9,15,2
6,17,12
9,16,7
15,9,12
12,7,15
7,17,14
10,9,17
8,1,8
9,10,1
11,7,18
3,7,15
5,6,16
6,14,4
4,13,5
9,15,12
7,7,4
7,3,8
11,11,1
8,11,17
11,11,18
14,10,3
10,2,9
6,11,3
2,9,9
8,15,2
3,13,13
9,16,13
8,15,14
16,6,4
16,8,14
6,8,15
15,10,14
15,16,14
9,16,5
2,3,8
5,3,9
13,8,4
12,12,17
4,12,12
9,18,11
5,3,12
2,7,9
5,9,16
14,2,13
16,11,8
6,15,5
16,6,13
12,8,2
6,2,7
8,14,4
4,4,11
1,9,8
10,3,14
10,15,12
2,6,12
15,6,8
3,10,6
14,13,16
2,11,14
14,3,11
9,6,2
4,7,12
2,13,11
6,6,16
5,4,5
2,5,10
14,3,14
7,5,13
11,3,13
5,14,8
12,3,7
5,13,12
7,2,9
16,5,11
12,16,13
7,14,7
4,15,9
9,3,7
16,9,6
6,13,4
13,4,3
4,7,16
3,8,8
11,3,6
3,13,6
8,3,12
11,8,4
10,17,9
4,14,8
16,9,5
5,12,14
9,9,1
4,4,9
17,9,8
7,9,3
15,14,12
6,12,3
10,3,7
7,5,2
11,4,8
8,3,10
5,16,6
17,11,9
12,6,14
12,2,11
6,16,13
6,7,18
2,4,10
8,15,3
14,16,9
6,3,14
16,11,5
12,9,2
13,4,4
15,14,8
8,18,9
18,9,9
13,7,16
8,13,13
16,14,7
13,6,15
18,13,8
15,14,10
13,5,9
15,16,12
6,17,10
13,14,6
4,11,15
4,17,11
8,9,1
4,9,3
10,6,15
15,3,11
14,11,15
6,5,15
4,11,14
12,2,7
10,15,14
6,13,13
4,6,4
14,4,8
15,15,15
11,2,11
7,15,8
3,16,9
13,2,13
2,5,9
10,4,10
8,12,2
10,6,2
14,6,14
11,17,14
8,6,3
16,14,10
9,5,7
15,15,12
2,11,8
8,2,15
2,13,10
6,5,7
14,2,10
5,8,2
8,2,10
9,9,18
6,13,2
10,16,4
14,12,4
12,5,15
2,10,6
5,14,3
5,8,4
9,15,15
13,5,16
15,15,10
5,7,8
12,7,2
3,11,6
11,3,12
4,13,14
15,15,5
14,11,2
7,15,11
8,1,7
13,15,4
13,13,2
17,5,12
11,5,17
7,15,7
6,15,12
9,1,11
9,5,1
7,4,9
9,6,17
10,16,8
12,2,9
18,10,6
3,10,9
5,3,10
16,8,12
7,16,9
14,15,12
13,15,7
16,8,7
14,16,6
5,6,11
8,6,2
13,13,17
5,4,7
7,13,18
16,9,12
1,11,7
13,10,16
18,11,9
13,4,15
15,3,8
6,3,5
10,13,16
18,12,8
6,10,2
3,10,16
10,6,16
11,3,5
11,10,2
4,7,13
1,9,10
11,9,18
13,16,5
11,13,5
4,13,16
3,10,13
11,3,15
16,9,7
5,6,4
1,7,8
13,6,2
15,16,11
12,16,4
13,10,2
2,9,14
2,5,7
4,3,10
10,4,5
9,13,3
9,13,2
11,16,3
11,3,9
17,11,10
13,3,10
11,1,14
10,15,6
7,15,16
6,12,17
13,8,2
2,6,13
11,15,12
12,8,1
15,5,10
4,11,4
8,3,8
1,11,10
18,9,7
5,15,9
10,4,17
8,18,11
10,7,3
9,7,18
7,3,6
11,17,5
14,17,14
7,2,6
13,15,15
3,14,14
14,5,6
13,17,11
15,8,5
11,9,3
3,10,15
6,14,5
4,14,4
5,7,5
15,6,13
12,4,5
14,6,12
7,16,4
3,4,8
7,7,2
15,4,6
14,12,15
15,6,16
9,15,4
13,10,1
15,6,6
8,9,17
16,6,5
4,4,5
13,10,18
3,7,14
7,6,17
7,6,6
12,9,1
2,10,8
7,8,1
12,11,16
11,3,16
5,5,9
11,8,16
14,10,17
14,10,14
5,15,7
2,8,10
10,13,3
6,4,11
14,14,10
4,10,16
5,8,5
4,10,14
9,12,16
16,10,12
16,6,7
12,7,18
13,3,7
11,3,11
1,7,9
3,8,6
9,3,16
9,17,8
5,14,4
5,17,9
18,11,8
5,4,11
10,7,16
7,7,15
6,2,10
16,13,13
13,12,2
16,11,15
12,8,17
17,8,7
16,14,6
4,13,15
2,7,5
5,11,4
6,14,7
12,15,6
11,13,15
4,16,6
6,6,3
14,13,3
11,14,4
4,9,6
16,12,4
7,16,12
7,17,12
9,10,17
15,11,7
9,13,4
11,9,2
10,14,4
4,10,5
15,9,15
3,11,3
12,7,17
3,5,5
7,1,12
8,4,14
2,11,10
8,6,17
18,9,12
7,4,5
11,14,2
3,6,13
15,6,3
6,3,13
7,9,15
6,5,4
17,12,12
14,10,13
4,8,15
13,16,14
11,4,11
4,16,7
10,18,7
7,4,4
5,2,5
14,4,14
5,13,9
7,2,15
13,14,8
6,7,5
13,7,17
15,6,11
10,17,7
17,13,12
4,9,4
7,6,1
15,8,8
17,12,4
16,11,7
4,5,9
11,6,17
14,14,9
4,13,9
9,3,14
6,13,12
11,11,2
15,15,8
4,9,10
12,11,4
9,8,3
12,6,17
5,3,13
15,8,11
2,10,7
5,4,8
11,8,18
16,12,14
8,11,2
4,14,15
12,5,13
1,11,9
13,13,15
1,9,9
6,14,17
7,16,10
4,4,14
16,6,9
1,10,10
4,9,11
16,15,12
16,14,14
9,15,14
9,4,5
12,14,3
13,11,6
15,14,5
3,8,16
9,9,16
12,15,14
11,4,3
6,5,14
4,5,11
15,5,8
18,8,10
6,3,9
7,7,16
12,3,15
14,4,13
15,3,13
15,15,13
8,9,18
12,17,7
1,10,12
9,7,2
5,11,9
15,8,12
13,16,4
10,9,16
18,10,11
12,13,14
1,7,12
13,15,13
17,6,9
2,9,10
8,4,13
15,6,5
5,11,16
3,6,7
4,4,7
4,12,7
14,9,14
7,15,13
8,11,3
15,8,7
5,7,14
3,12,13
11,16,9
13,18,10
6,10,15
11,16,11
7,3,15
12,7,3
14,12,8
6,14,9
10,4,14
1,10,6
3,10,8
7,5,7
14,11,4
11,4,14
13,6,3
4,6,11
3,14,4
17,6,11
18,13,10
2,12,5
8,13,16
17,12,8
9,1,9
15,4,12
11,17,6
10,6,5
14,6,16
17,12,10
18,9,10
4,11,3
2,12,6
7,12,15
10,3,9
12,9,3
11,15,9
5,10,17
8,13,1
9,5,13
12,9,16
15,9,16
13,4,7
6,13,17
10,18,6
6,7,14
10,7,4
13,13,5
8,7,16
17,4,9
8,9,4
9,9,19
4,11,13
13,7,4
13,6,5
6,4,6
5,13,5
15,9,3
10,13,1
10,6,4
4,14,12
6,12,6
5,16,7
4,15,13
12,4,12
10,14,6
9,6,1
15,6,10
7,3,10
8,4,3
13,9,1
5,2,12
14,3,5
7,11,18
14,10,2
4,8,5
6,12,18
7,17,6
9,8,18
3,14,7
12,4,13
14,4,11
15,7,16
14,2,9
8,3,15
5,16,14
14,3,9
12,14,17
17,14,6
5,6,13
7,14,15
4,15,14
14,14,13
5,3,7
8,2,7
13,3,15
8,1,10
4,3,6
17,12,6
6,8,1
14,5,4
17,9,11
13,15,9
11,5,13
3,10,11
17,10,10
15,10,11
13,18,12
14,15,15
16,16,9
14,12,3
11,3,7
18,10,9
13,3,14
4,10,6
3,12,8
2,9,8
14,8,13
13,11,16
5,10,16
9,17,9
14,5,9
13,12,3
5,12,8
7,18,12
9,5,14
5,6,15
0,8,10
16,9,10
8,2,12
17,6,6
14,5,13
3,8,9
5,5,13
8,13,4
15,12,7
14,11,5
14,15,6
18,10,10
9,8,1
5,12,6
10,3,4
10,5,16
7,4,6
13,16,9
6,5,5
10,2,15
4,16,9
4,8,13
11,15,13
5,5,14
9,7,3
6,2,12
11,9,1
15,16,13
15,16,7
10,5,5
14,6,11
14,15,10
2,14,9
8,8,15
10,11,18
12,2,13
12,10,18
10,15,17
17,14,9
12,15,7
7,3,12
12,12,16
6,9,4
1,12,10
13,10,4
14,4,7
10,10,4
13,14,12
2,12,14
8,5,5
14,9,17
8,11,4
7,4,3
10,2,5
8,16,10
10,11,16
18,12,9
17,4,11
14,16,13
11,9,4
18,7,12
7,4,12
13,9,2
13,13,16
8,3,5
6,5,16
1,7,11
7,10,19
14,6,13
15,11,14
14,2,11
14,4,10
8,8,3
15,8,4
14,10,5
3,15,6
17,13,8
11,3,3
10,16,7
17,7,9
6,2,6
14,6,6
17,12,13
14,7,5
13,4,5
4,3,7
13,8,16
3,9,9
2,10,12
16,4,9
1,8,11
10,18,12
10,12,1
16,11,10
15,8,6
10,14,2
13,3,12
18,11,10
18,12,10
6,7,15
7,18,9
12,15,9
6,5,13
13,4,8
2,5,8
5,5,6
10,12,17
15,17,8
10,15,16
7,15,3
8,0,11
4,14,11
15,5,7
3,16,10
8,16,15
15,11,16
6,7,2
12,17,12
4,15,5
15,7,12
6,14,14
18,13,7
4,4,6
6,10,4
10,16,11
11,4,13
4,11,12
10,0,7
6,5,12
16,7,8
9,16,11
14,15,11
16,7,4
12,18,12
17,8,13
2,11,12
2,14,13
8,8,4
6,2,13
9,5,17
11,6,1
2,13,6
3,3,8
12,7,16
7,9,18
11,14,5
15,3,12
14,17,11
14,12,2
16,8,6
15,7,9
10,10,15
3,4,9
6,4,8
5,7,2
15,10,6
9,8,2
9,15,3
5,4,12
16,7,15
9,11,18
13,5,13
2,14,11
12,5,16
4,16,5
14,17,8
5,7,10
12,6,15
13,6,6
2,7,15
11,13,18
7,1,7
15,9,5
5,15,14
8,13,3
10,16,14
4,17,13
13,3,11
16,13,9
2,14,8
7,2,5
11,13,16
12,10,1
4,12,10
5,14,10
4,12,8
6,16,15
18,5,11
7,8,2
14,8,16
7,17,13
13,14,7
10,1,9
2,6,10
12,4,7
4,11,2
9,16,15
8,3,11
6,3,10
11,5,4
4,5,8
9,5,11
1,12,9
15,16,6
10,3,12
4,10,17
10,10,1
8,9,3
15,12,16
15,8,16
13,9,4
7,11,16
4,11,7
9,11,3
5,2,10
10,3,16
11,16,6
5,16,10
11,8,1
13,7,18
11,18,13
9,17,10
8,3,7
4,13,3
12,17,9
10,15,3
6,15,6
17,10,9
13,4,11
9,15,16
13,13,14
5,1,7
11,2,14
8,1,12
10,18,11
4,13,8
2,10,4
14,3,13
17,13,6
1,9,13
2,11,5
6,15,4
8,15,6
17,14,7
12,11,18
11,5,2
9,16,3
2,8,8
3,8,15
14,6,3
5,2,9
12,6,18
18,6,8
3,6,4
10,9,0
16,9,3
6,12,14
7,17,9
7,14,13
7,16,15
10,17,5
12,15,3
3,4,7
9,3,5
5,14,16
7,5,6
6,14,16
13,5,2
5,13,8
7,1,9
17,9,10
8,15,16
6,6,10
7,5,14"""
| 0 |
Kotlin
| 0 | 0 |
8230fce9a907343f11a2c042ebe0bf204775be3f
| 18,195 |
advent-of-code-2022
|
MIT License
|
src/Day12.kt
|
askeron
| 572,955,924 | false |
{"Kotlin": 24616}
|
class Day12 : Day<Int>(31, 29, 447, 446) {
private fun partCommon(input: List<String>, lookForBestStartPoint: Boolean): Int {
val inputMap = input.charMatrixToPointMap()
val allPoints = inputMap.keys
val start = inputMap.entries.filter { it.value == 'S' }.singleValue().key
val end = inputMap.entries.filter { it.value == 'E' }.singleValue().key
val charMap = inputMap.toMutableMap().also {
it[start] = 'a'
it[end] = 'z'
}.toMap()
val possibleSteps = allPoints.flatMap { p -> p.neighboursNotDiagonal.filter { it in allPoints }.map { p to it } }
.filter { (a, b) -> charMap[b]!! <= charMap[a]!! + 1 }
.toSet()
val possibleStartPoints = if (lookForBestStartPoint) {
charMap.entries.filter { it.value == 'a' }.map { it.key }
} else {
listOf(start)
}
val shortestPath = possibleStartPoints
.mapNotNull { shortestPathByDijkstra(possibleSteps.map { it toTriple 1 }.toSet(), it, end)?.first }
.minByOrNull { it.size }!!
//println(getPathMapString(allPoints, shortestPath, end))
return shortestPath.size - 1
}
override fun part1(input: List<String>): Int {
return partCommon(input, false)
}
override fun part2(input: List<String>): Int {
return partCommon(input, true)
}
fun getPathMapString(allPoints: Set<Point>, path: List<Point>, end: Point): String {
val directionCharMap = buildMap {
put(Point.UP, '^')
put(Point.DOWN, 'v')
put(Point.LEFT, '<')
put(Point.RIGHT, '>')
}
val pathCharMap = path.windowed(2)
.map { (a, b) -> a to directionCharMap[b-a]!! }
.plus(end to 'E')
.toMap()
return allPoints.matrixString { x, y -> pathCharMap[Point(x,y)] ?: '.' }
}
}
| 0 |
Kotlin
| 0 | 1 |
6c7cf9cf12404b8451745c1e5b2f1827264dc3b8
| 1,923 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/AOC2022/Day07/Day07.kt
|
kfbower
| 573,519,224 | false |
{"Kotlin": 44562}
|
package AOC2022.Day07
import AOC2022.readInput
fun main(){
fun treeBuilder(lines: List<String>): Directory {
val root = Directory("/", parent = null)
var current = root
lines.drop(1).forEach {
if (it.startsWith("$ cd ..")) {
current = current.parent!!
} else if (it.startsWith("$ cd")) {
val path = it.drop(5)
val newDir = Directory(path, parent = current)
current.children.add(newDir)
current = newDir
} else if (it[0].isDigit()) {
val size = it.split(" ")[0].toInt()
current.file += size
}
}
return root
}
fun part1(input: List<String>): Pair<Int, Int> {
val root = treeBuilder(input)
getSizes(root)
val all = flatten(root)
val answer = all.filter { it.size < Params.dirMax }.sumOf { it.size}
val currentUsed = all.sumOf { it.file }
val unused = Params.maxSpace - currentUsed
val toDelete = Params.unusedSpace - unused
val part2 = all.sortedBy { it.size }.first { it.size > toDelete }.size
return answer to part2
}
val input = readInput("Day07")
println(part1(input))
}
fun getSizes(directory: Directory): Int {
//recursive function to pull add the sizes
val sizes = directory.children.sumOf { getSizes(it) }
directory.size = sizes + directory.file
return directory.size
}
fun flatten(directory: Directory): List<Directory> {
//recursive function to get the sizes
val children = directory.children.flatMap { flatten(it) }
return children + directory
}
data class Directory(
val name: String,
val parent: Directory?,
val children: MutableList<Directory> = mutableListOf(),
var file: Int = 0,
var size: Int = 0)
object Params{
val dirMax = 100000
val maxSpace = 70000000
val unusedSpace = 30000000
}
| 0 |
Kotlin
| 0 | 0 |
48a7c563ebee77e44685569d356a05e8695ae36c
| 1,939 |
advent-of-code-2022
|
Apache License 2.0
|
2021/src/day05/Day05.kt
|
Bridouille
| 433,940,923 | false |
{"Kotlin": 171124, "Go": 37047}
|
package day05
import readInput
import kotlin.math.abs
data class Point(val x: Int, val y: Int)
fun part1(lines: List<String>) : Int {
val boardLines = mutableListOf<Point>()
for (line in lines) {
val split = line.filter { !it.isWhitespace() }.split("->")
val fromX = split[0].split(",")[0].toInt()
val fromY = split[0].split(",")[1].toInt()
val toX = split[1].split(",")[0].toInt()
val toY = split[1].split(",")[1].toInt()
if (fromX == toX) { // horizontal line
for (i in minOf(fromY, toY)..maxOf(fromY, toY)) {
boardLines.add(Point(fromX, i))
}
} else if (fromY == toY) { // vertical line
for (i in minOf(fromX, toX)..maxOf(fromX, toX)) {
boardLines.add(Point(i, fromY))
}
}
}
val pointsOccurences = boardLines.groupingBy { it }.eachCount().values
return pointsOccurences.count { it >= 2 }
}
fun part2(lines: List<String>) : Int {
val boardLines = mutableListOf<Point>()
for (line in lines) {
val split = line.filter { !it.isWhitespace() }.split("->")
val fromX = split[0].split(",")[0].toInt()
val fromY = split[0].split(",")[1].toInt()
val toX = split[1].split(",")[0].toInt()
val toY = split[1].split(",")[1].toInt()
if (fromX == toX) { // horizontal line
for (i in minOf(fromY, toY)..maxOf(fromY, toY)) {
boardLines.add(Point(fromX, i))
}
} else if (fromY == toY) { // vertical line
for (i in minOf(fromX, toX)..maxOf(fromX, toX)) {
boardLines.add(Point(i, fromY))
}
} else if (abs(fromX - toX) == abs(fromY - toY)) { // diagonal lines
val dist = abs(fromX - toX) // == fromY - toY
val incrementX = if (toX > fromX) { 1 } else { -1 }
val incrementY = if (toY > fromY) { 1 } else { -1 }
for (i in 0..dist) {
boardLines.add(Point(fromX + (incrementX * i), fromY + (incrementY * i)))
}
}
}
val pointsOccurences = boardLines.groupingBy { it }.eachCount().values
return pointsOccurences.count { it >= 2 }
}
fun main() {
val testInput = readInput("day05/test")
println("part1(testInput) => " + part1(testInput))
println("part2(testInput) => " + part2(testInput))
val input = readInput("day05/input")
println("part1(input) => " + part1(input))
println("part1(input) => " + part2(input))
}
| 0 |
Kotlin
| 0 | 2 |
8ccdcce24cecca6e1d90c500423607d411c9fee2
| 2,538 |
advent-of-code
|
Apache License 2.0
|
src/Day07.kt
|
Jintin
| 573,640,224 | false |
{"Kotlin": 30591}
|
import java.util.*
fun main() {
fun part1(input: List<String>): Int {
val root = buildFileTree(input)
return countSize(root)
}
fun part2(input: List<String>): Int {
val root = buildFileTree(input)
return findMin(root, root.size - 40000000)
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private enum class FileType {
DIR, File
}
private class Tree(val name: String, val type: FileType, val fileSize: Int = 0) {
val child = mutableMapOf<String, Tree>()
val size: Int by lazy {
when (type) {
FileType.File -> fileSize
FileType.DIR -> child.values.sumOf { it.size }
}
}
fun add(tree: Tree) {
child[tree.name] = tree
}
}
private fun buildFileTree(input: List<String>): Tree {
val stack = Stack<Tree>()
input.forEachIndexed { index, s ->
if (s.startsWith("$ ls")) {
var start = index + 1
while (start < input.size && !input[start].startsWith("$")) {
val strings = input[start].split(" ")
if (strings[0].startsWith("dir")) {
stack.peek().add(Tree(strings[1], FileType.DIR))
} else {
stack.peek().add(Tree(strings[1], FileType.File, strings[0].toInt()))
}
start++
}
} else if (s.startsWith("$ cd")) {
when (val target = s.split(" ")[2]) {
"/" -> stack.push(Tree("/", FileType.DIR))
".." -> stack.pop()
else -> stack.push(stack.peek().child[target])
}
}
}
while (stack.size > 1) {
stack.pop()
}
return stack.peek()
}
private fun countSize(current: Tree): Int {
var total = current.child.values.sumOf { countSize(it) }
if (current.type == FileType.DIR && current.size <= 100000) {
total += current.size
}
return total
}
private fun findMin(root: Tree, target: Int): Int {
if (root.type != FileType.DIR) {
return Int.MAX_VALUE
}
val value = root.child.values.minOfOrNull {
findMin(it, target)
} ?: Int.MAX_VALUE
return if (root.size >= target) {
minOf(root.size, value)
} else {
value
}
}
| 0 |
Kotlin
| 0 | 2 |
4aa00f0d258d55600a623f0118979a25d76b3ecb
| 2,321 |
AdventCode2022
|
Apache License 2.0
|
src/Day03.kt
|
ktrom
| 573,216,321 | false |
{"Kotlin": 19490, "Rich Text Format": 2301}
|
fun main() {
fun part1(input: List<String>): Int {
return input.map {
val charsInFirstHalfOfString: Set<Char> = it.substring(0 until it.length / 2).toSet()
val charsInSecondHalfOfString: Set<Char> = it.substring(it.length / 2).toSet()
val charsInBothHalvesOfString: Set<Char> =
charsInFirstHalfOfString intersect charsInSecondHalfOfString
// This function assumes there is exactly one type of char in both halves
check(charsInBothHalvesOfString.size == 1)
getPriority(charsInBothHalvesOfString.first())
}.sum();
}
/**
* 1. takes a list of strings and chunks them by chunkSize.
* 2. each chunk is a List<String>s whose charset's intersection is of size 1.
* 3. for each chunk, finds the common char, and calculuates its priority value using [getPriority]
* 4. sums priority values of common char for all each chunks
*
* @param chunkSize size of chunks with common char
*/
fun part2(input: List<String>, chunkSize: Int): Int {
return input.chunked(chunkSize).map {
var charsInAllStrings: Set<Char> = it.first().toSet()
it.forEach { charsInAllStrings = charsInAllStrings intersect it.toSet() }
charsInAllStrings
}.map {
check(it.size == 1)
getPriority(it.first())
}.sum()
}
// takes an list of strings and assumes chunk size of 3
fun part2(input: List<String>): Int {
return part2(input, 3)
}
// test if implementation meets criteria from the description
val testInput = readInput("Day03_test")
println(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
println(part2(testInput) == 70)
println(part2(input))
}
// returns the priority value of a food type as outlined in spec https://adventofcode.com/2022/day/3
fun getPriority(character: Char): Int {
// lower case ASCII values begin at 97, so to map them to 1 - 26, we subtract 96
if (character.isLowerCase()) {
return character.code - 96
}
// uppercase case ASCII values begin at 65, so to map them to 27 - 52, we subtract 38
return character.code - 38
}
| 0 |
Kotlin
| 0 | 0 |
6940ff5a3a04a29cfa927d0bbc093cd5df15cbcd
| 2,057 |
kotlin-advent-of-code
|
Apache License 2.0
|
src/y2022/Day05.kt
|
a3nv
| 574,208,224 | false |
{"Kotlin": 34115, "Java": 1914}
|
package y2022
import utils.readInput
fun main() {
fun part1(columns: MutableList<MutableList<String>>, operations: List<String>): String {
operations.forEachIndexed() { index, it ->
val task = it.split(",")
val qty = task[0].toInt()
val from = task[1].toInt() - 1
val to = task[2].toInt() - 1
val source = columns[from]
val tail = source.takeLast(qty).reversed()
source.subList(source.size - qty, source.size).clear()
val target = columns[to]
target.addAll(tail)
}
return foldIt(columns)
}
fun part2(columns: MutableList<MutableList<String>>, operations: List<String>): String {
operations.forEachIndexed() { index, it ->
val task = it.split(",")
val qty = task[0].toInt()
val from = task[1].toInt() - 1
val to = task[2].toInt() - 1
val source = columns[from]
val tail = source.takeLast(qty)
source.subList(source.size - qty, source.size).clear()
val target = columns[to]
target.addAll(tail)
}
return foldIt(columns)
}
// test if implementation meets criteria from the description, like:
var input = readInput("y2022", "Day05_test_full")
var pairs = parseInput(input)
var res = part1(pairs.first, pairs.second)
println(res)
check(res == "CMZ")
pairs = parseInput(input)
res = part2(pairs.first, pairs.second)
println(res)
check(res == "MCD")
input = readInput("y2022", "Day05_full")
pairs = parseInput(input)
res = part1(pairs.first, pairs.second)
println(res)
check(res == "QNNTGTPFN")
pairs = parseInput(input)
res = part2(pairs.first, pairs.second)
println(res)
check(res == "GGNPJBTTR")
}
fun foldIt(columns: MutableList<MutableList<String>>): String {
return columns.filter{ it.isNotEmpty() }.fold("") { acc: String, list: List<String> -> acc + list.last() }
}
fun parseInput(input: List<String>): Pair<MutableList<MutableList<String>>, List<String>> {
val header: List<String> = input.takeWhile { it.isNotBlank() }.reversed()
val last = Regex("""\d+""").findAll(header.get(0)).map { it.groupValues[0] }.joinToString().last()
val columns: MutableList<MutableList<String>> = MutableList(last.toInt() - 1) { mutableListOf() }
header.drop(1).forEach { line ->
println(line.replace(" [", ",[").replace("] ", "],").replace(", ", ", ,"))
line.replace(" [", ",[").replace("] ", "],").replace(", ", ", ,") // that will help us to distinguish spaces which separate columns and placeholders for empty places in columns
.split(",")
.forEachIndexed {index, item ->
val column: MutableList<String> = columns.get(index)
val str = item.get(1).toString() // it's either an empty line (3 spaces) " " or "[A]", in second case get(1) will return actual value
if (str.isNotBlank()) {
column.add(str)
}
}
}
val reg = Regex("""\d+""")
val operations = input.drop(header.size + 1).map { reg.findAll(it).map { it.groupValues[0] }.joinToString(separator = ",") }
return Pair(columns, operations)
}
| 0 |
Kotlin
| 0 | 0 |
ab2206ab5030ace967e08c7051becb4ae44aea39
| 3,331 |
advent-of-code-kotlin
|
Apache License 2.0
|
Kotlin101/13-lambda-functions/01_Basics.kt
|
ge47jaz
| 695,323,673 | false |
{"Kotlin": 77958}
|
// val lambdaName: (inputType) -> outputType = { inputVariable: inputType -> body }
// example:
val square: (Int) -> Int = { number: Int -> number * number }
// equivalent to:
fun square2(number: Int): Int {
return number * number
}
// lambda function can be assigned to a variable
val square3 = { number: Int -> number * number }
// can be passed as a parameter to another function - calculate is a higher order function
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}
// can be returned from another function
fun operation(): (Int) -> Int {
return square
}
// common higher order functions
// forEach - applies the lambda function to each element of the collection
fun forEachExample() {
val numbers = arrayListOf(1, 2, 3, 4, 5)
numbers.forEach { number: Int -> println(number) }
// if a lambda has a single parameter, the parameter can be omitted and the keyword it can be
// used instead
// numbers.forEach { println(it) }
}
// map - applies the lambda function to each element of the collection and returns a new collection
fun mapExample() {
val numbers = arrayListOf(1, 2, 3, 4, 5)
val squaredNumbers = numbers.map { number: Int -> number * number }
// using it:
// val squaredNumbers = numbers.map { it * it }
println(squaredNumbers)
}
// filter - applies the lambda function to each element of the collection and returns a new
// collection
fun filterExample() {
val numbers = arrayListOf(1, 2, 3, 4, 5)
numbers.filter { number: Int -> number % 2 == 0 }.forEach { println(it) }
}
// sortedBy - applies the lambda function to each element of the collection and returns a new
// collection
fun sortedByExample() {
val names = arrayListOf("John", "Mary", "Mike", "Anne", "Peter")
val sortedNumbers = names.sortedBy { it.length }
println(sortedNumbers)
}
// maxBy - applies the lambda function to each element of the collection and returns the element
// for which the lambda function returns the largest value
fun maxByExample() {
val names = arrayListOf("John", "Mary", "Mike", "Anne", "Peter")
val longestName = names.maxBy { it.length } // returns the element with the longest name
println(longestName)
}
// minBy - applies the lambda function to each element of the collection and returns the element
// for which the lambda function returns the smallest value
fun minByExample() {
val names = arrayListOf("John", "Mary", "Mike", "Anne", "Peter")
val shortestName = names.minBy { it.length } // returns the element with the shortest name
println(shortestName)
}
/*
cerate a higher ored funciton that takes a mutable collection fo integers and a lambda function.
It then applies the lambda function to every even element of that collection
cerate a labda function that when applied to an integer it returns that integer divided by 10
all the HOF using the lambda and display the results
*/
fun update(collection: ArrayList<Int>, lambda: (Int) -> Int): ArrayList<Int> {
for (i in 0 until collection.size - 1) {
if (collection[i] % 2 == 0) {
collection[i] = lambda(collection[i])
}
}
return collection
}
// create a higher order function that takes a collection of strings and a lambda function.
fun getMessages(clients: Collection<String>, getMessage: (String) -> String): ArrayList<String> {
val messages = ArrayList<String>()
for (client in clients) {
messages.add(getMessage(client))
}
return messages
}
// given a set of random integers, print out a subset that consists of only double digit numbers
fun doubleDigit(numbers: Set<Int>): Set<Int> {
return numbers.filter { it in 10..99 }.toSet()
}
// given a list of Strings, sort by the last char
fun sortLast(strings: List<String>): List<String> {
return strings.sortedBy { it[it.length - 1] } // -1 because the index starts at 0
}
// given a list of 3-digit integers, print ouf the ones that have the biggest middle digit
fun biggestMiddle(numbers: List<Int>): Int {
return numbers.filter { it in 100..999 }.maxBy { (it / 10) % 10 }
// /10%10 gives us the middle integer of each number
}
/*
* perform map and filter operations on the following collections of numbers
*
* if a number is odd, double it
* if a number is even, half it
*
* @param numbers: a collection of integers
* @return a subset of the collection that has numbers greater than 25
*/
fun mapFilter(numbers: Set<Int>): Set<Int> {
return numbers.map { if (it % 2 == 0) it / 2 else it * 2 }.filter { it > 25 }.toSet()
}
fun main() {
// val numbers: ArrayList<Int> = arrayListOf(1, 2, 33, 4, 54, 66, 37, 48, 9)
// println(numbers)
// val updatedNumbers = update(numbers) { number: Int -> number / 10 }
// println(updatedNumbers)
// val clients = arrayListOf("John", "Mary", "Mike", "Anne", "Peter")
// val messages =
// getMessages(clients) { client: String ->
// "Hello $client" // lambda function body
// }
// println(clients)
// println(messages)
// for (i in 0 until clients.size) {
// println("${clients[i]}: ${messages[i]}")
// }
// forEachExample()
// mapExample()
// filterExample()
// val numbers2 = setOf(3, 456, 67, 4, 567, 34, 6789)
// println(doubleDigit(numbers2))
// val strings = listOf("John", "Mary", "Mike", "Anne", "Peter")
// println(sortLast(strings))
// val ints = listOf(345, 654, 234, 868, 546, 987)
// println(biggestMiddle(ints))
// val numbers3 = setOf(34, 76, 234, 435, 675, 12, 54, 87, 98, 65)
// println(mapFilter(numbers3))
println(calculateCircleArea(30))
}
| 0 |
Kotlin
| 0 | 0 |
87dba8f8137c32d0ef6912efd5999675a2620ab4
| 5,711 |
kotlin-progress
|
MIT License
|
src/Day07.kt
|
lassebe
| 573,423,378 | false |
{"Kotlin": 33148}
|
fun main() {
fun sizeOf(
dirName: String,
fileStructure: Map<String, List<String>>,
dirSize: Map<String, Long>,
): Long {
val subDirs = fileStructure.getOrDefault(dirName, emptyList())
return dirSize.getOrDefault(dirName, 0) + subDirs.sumOf {
sizeOf(
it,
fileStructure,
dirSize,
)
}
}
fun buildFileStructure(input: List<String>): Pair<Map<String, List<String>>, Map<String, Long>> {
val fileStructure = mutableMapOf<String, List<String>>()
val dirSize = mutableMapOf<String, Long>()
var currentDir = "/"
for (i in input.indices) {
val line = input[i]
if (line.startsWith("\$ cd")) {
val nextDir = line.split(" cd ").last()
currentDir = when (nextDir) {
"" -> "/"
"/" -> "/"
".." -> {
if (currentDir == "/")
"/"
else
currentDir.substring(0, currentDir.lastIndexOf("/"))
}
else -> if (currentDir.length > 1) "$currentDir/$nextDir" else "/$nextDir"
}
}
if (line.startsWith("\$ ls")) {
var j = i + 1
var size = 0L
fileStructure[currentDir] = fileStructure.getOrDefault(currentDir, emptyList())
while (j < input.size && !input[j].startsWith("\$")) {
val subLine = input[j]
val fileInfo = subLine.split(" ")
if (fileInfo.first() != "dir") {
size += fileInfo.first().toLong()
} else {
val subDirName = fileInfo.last()
fileStructure[currentDir] =
fileStructure[currentDir]!! + if (currentDir.length > 1) "$currentDir/$subDirName" else "/$subDirName"
}
j++
}
dirSize[currentDir] = size
}
}
return Pair(fileStructure, dirSize)
}
fun part1(input: List<String>): Long {
val (fileStructure, dirSize) = buildFileStructure(input)
return fileStructure.keys.map { dirName ->
Pair(dirName, sizeOf(dirName, fileStructure, dirSize))
}.filter { it.second < 100000 }.sumOf { it.second }
}
fun part2(input: List<String>): Long {
val totalSize = 70000000
val (fileStructure, dirSize) = buildFileStructure(input)
val sizes = fileStructure.keys.map { dirName ->
Pair(dirName, sizeOf(dirName, fileStructure, dirSize))
}
val rootSize = sizes.find { it.first == "/" }!!.second
val remainingSize = totalSize - rootSize
return sizes.filter {
it.first != "/" && remainingSize + it.second >= 30000000
}.minOf { it.second }
}
val testInput = readInput("Day07_test")
expect(part1(testInput), 95437)
val input = readInput("Day07")
expect(part1(input), 1307902)
println(part1(input))
expect(part2(testInput), 24933642)
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
c3157c2d66a098598a6b19fd3a2b18a6bae95f0c
| 3,299 |
advent_of_code_2022
|
Apache License 2.0
|
src/Day03.kt
|
frungl
| 573,598,286 | false |
{"Kotlin": 86423}
|
fun main() {
fun cost(ch: Char): Int {
return when(ch) {
in 'a'..'z' -> ch - 'a' + 1
else -> ch - 'A' + 27
}
}
fun part1(input: List<String>): Int {
return input.sumOf { str ->
val (l, r) = str.chunked(str.length / 2)
l.toCharArray().distinct().sumOf { ch ->
when (r.contains(ch)) {
true -> cost(ch)
else -> 0
}
}
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { bp ->
bp[0].toCharArray().distinct().sumOf { ch ->
when (bp[1].contains(ch) && bp[2].contains(ch)) {
true -> cost(ch)
else -> 0
}
}
}
}
fun part1Beauty(input: List<String>): Int {
return input.map { str ->
val (l, r) = str.chunked(str.length / 2).map { it.toSet() }
(l intersect r).single()
}.sumOf { cost(it) }
}
fun part2Beauty(input: List<String>): Int {
return input.chunked(3) { ch ->
val (a, b, c) = ch.map { it.toSet() }
(a intersect b intersect c).single()
}.sumOf { cost(it) }
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
println(part1Beauty(input))
println(part2Beauty(input))
}
| 0 |
Kotlin
| 0 | 0 |
d4cecfd5ee13de95f143407735e00c02baac7d5c
| 1,544 |
aoc2022
|
Apache License 2.0
|
kotlin-practice/src/main/kotlin/exercise/collection/CollectionOperators.kt
|
nicolegeorgieva
| 590,020,790 | false |
{"Kotlin": 120359}
|
package exercise.collection
fun main() {
val students = listOf<Student>(
Student("John", 20, 3.5),
Student("Jane", 21, 3.8),
Student("Jack", 22, 3.2),
Student("J", 20, 6.0),
Student("JC", 20, 4.5)
)
println(studentsInfo(students))
}
data class Student(
val name: String,
val age: Int,
val grade: Double
)
fun sortStudentsByName(students: List<Student>): List<Student> {
return students.sortedBy { it.name }
}
fun sortStudentsByGradeDescending(students: List<Student>): List<Student> {
return students.sortedByDescending { it.grade }
}
fun filterStudentsByAgeRange(students: List<Student>, minAge: Int, maxAge: Int): List<Student> {
return students.filter { it.age in minAge..maxAge }
}
fun findTopStudents(students: List<Student>, topN: Int): List<Student> {
return students.sortedByDescending { it.grade }.take(topN)
}
fun groupByGradeRange(students: List<Student>): Map<GradeLetter, List<Student>> {
return students.groupBy { gradeDoubleToLetter(it.grade) }
}
enum class GradeLetter {
A,
B,
C,
D,
F
}
fun gradeDoubleToLetter(grade: Double): GradeLetter {
return when (grade) {
in 2.0..2.49 -> GradeLetter.F
in 2.5..3.49 -> GradeLetter.D
in 3.5..4.49 -> GradeLetter.C
in 4.5..5.49 -> GradeLetter.B
else -> {
GradeLetter.A
}
}
}
fun calculateAverageGrade(students: List<Student>): Double {
return students.map { it.grade }.average()
}
// students with grade >= 2.5 , sortedBy grade, uppercase name
fun passedStudents(students: List<Student>): List<Student> {
return students.filter { it.grade >= 2.5 }.map { it ->
Student(it.name.uppercase(), it.age, it.grade)
}
}
/*
new data class StudentInfo (1 student, belowAvg: Boolean (true if grade < avg), gradeLetter: Char)
fun studentsInfo(students: List<Student>) : List<StudentInfo>
Use fun calculateAverageGrade
Use fun gradeDoubleToLetter
*/
data class StudentInfo(
val student: Student,
val belowAverage: Boolean,
val gradeLetter: GradeLetter
)
fun studentsInfo(students: List<Student>): List<StudentInfo> {
val averageGrade = calculateAverageGrade(students)
return students.map { student ->
StudentInfo(
student = student,
belowAverage = student.grade < averageGrade,
gradeLetter = gradeDoubleToLetter(student.grade)
)
}
}
| 0 |
Kotlin
| 0 | 1 |
c96a0234cc467dfaee258bdea8ddc743627e2e20
| 2,462 |
kotlin-practice
|
MIT License
|
src/Day08.kt
|
jwklomp
| 572,195,432 | false |
{"Kotlin": 65103}
|
fun main() {
fun isVisible(grid: Grid2D<Int>, cell: Cell<Int>): Boolean {
val row = grid.getRow(cell.y) // y fixed, x variable
val isLeftVisible = row.filter { it.x < cell.x }.all { it.value < cell.value }
val isRightVisible = row.filter { it.x > cell.x }.all { it.value < cell.value }
val col = grid.getCol(cell.x) // x fixed, y variable
val isUpVisible = col.filter { it.y < cell.y }.all { it.value < cell.value }
val isDownVisible = col.filter { it.y > cell.y }.all { it.value < cell.value }
return isLeftVisible || isRightVisible || isUpVisible || isDownVisible
}
fun getScenicScore(grid: Grid2D<Int>, cell: Cell<Int>): Int {
val row = grid.getRow(cell.y) // y fixed, x variable
val leftVisible =
row.filter { it.x < cell.x }.sortedByDescending { it.x }.takeWhileInclusive { it.value < cell.value }
val rightVisible = row.filter { it.x > cell.x }.takeWhileInclusive { it.value < cell.value }
val col = grid.getCol(cell.x) // x fixed, y variable
val upVisible =
col.filter { it.y < cell.y }.sortedByDescending { it.y }.takeWhileInclusive { it.value < cell.value }
val downVisible = col.filter { it.y > cell.y }.takeWhileInclusive { it.value < cell.value }
return leftVisible.size * rightVisible.size * upVisible.size * downVisible.size
}
fun makeGrid(input: List<String>): Grid2D<Int> =
input.map { it.chunked(1).map { c -> c.toInt() } }.run { Grid2D(this) }
fun part1(input: List<String>): Int {
val grid: Grid2D<Int> = makeGrid(input)
val nonEdges = grid.getNonEdges()
val visible = nonEdges.filter { isVisible(grid, it) }
return (grid.getAllCells().size - nonEdges.size) + visible.size
}
fun part2(input: List<String>): Int? =
makeGrid(input).run { this.getNonEdges().maxOf { getScenicScore(this, it) } }
val testInput = readInput("Day08_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
1b1121cfc57bbb73ac84a2f58927ab59bf158888
| 2,127 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/Day07.kt
|
erikthered
| 572,804,470 | false |
{"Kotlin": 36722}
|
fun main() {
data class File(val name: String, val path: List<String>, val size: Int)
data class Folder(val name: String, val path: List<String>, val files: List<File>)
fun computeFolderSizes(input: List<String>): List<Pair<String, Int>> {
val location = mutableListOf<String>()
val folders = mutableListOf<Folder>()
val files = mutableListOf<File>()
folders.add(Folder("[root]", emptyList(), emptyList()))
for (line in input) {
// Command
if (line.startsWith("$")) {
val segments = line.split(" ")
when (segments[1]) {
"ls" -> {
}
"cd" -> {
when (segments[2]) {
"/" -> {
location.clear()
}
".." -> {
location.removeLast()
}
else -> {
location.add(segments[2])
}
}
}
}
} else { // Output
val (first, name) = line.split(" ")
when (first) {
"dir" -> {
folders.add(Folder(name, location.toList(), emptyList()))
}
else -> {
val size = first.toInt()
files.add(File(name, location.toList(), size))
}
}
}
}
return folders.map { folder ->
val fullPath = if (folder.name == "[root]") {
folder.path
} else {
folder.path + folder.name
}
"/" + fullPath.joinToString("/") to files.filter { file ->
file.path.size >= fullPath.size && file.path.subList(0, fullPath.lastIndex + 1) == fullPath
}.sumOf { it.size }
}
}
fun part1(input: List<String>): Int {
val sizeLimit = 100000
val folderSizes = computeFolderSizes(input)
return folderSizes
.filter { (_, size) -> size <= sizeLimit }
.sumOf { it.second }
}
fun part2(input: List<String>): Int {
val totalDiskSpace = 70000000
val spaceNeeded = 30000000
val folderSizes = computeFolderSizes(input)
val toFree = spaceNeeded - (totalDiskSpace - folderSizes.first().second)
return folderSizes.sortedBy { it.second }.first { it.second > toFree }.second
}
// 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 |
3946827754a449cbe2a9e3e249a0db06fdc3995d
| 2,967 |
aoc-2022-kotlin
|
Apache License 2.0
|
src/Day07.kt
|
chasebleyl
| 573,058,526 | false |
{"Kotlin": 15274}
|
data class Directory(
val name: String,
val parent: Directory? = null,
val subDirectories: MutableList<Directory> = mutableListOf<Directory>(),
val files: MutableList<File> = mutableListOf<File>(),
) {
fun allSubDirectories(): List<Directory> = subDirectories + subDirectories.flatMap { it.allSubDirectories() }
fun size(): Int = files.sumOf { it.size } + subDirectories.sumOf { it.size() }
}
data class File(
val size: Int,
val name: String,
)
fun main() {
fun buildRootDirectory(input: List<String>): Directory {
val root = Directory("/")
var currentDirectory = root
input.drop(1).forEach { command ->
when {
command.startsWith("$ cd ..") -> currentDirectory = currentDirectory.parent!!
command.startsWith("$ cd ") -> currentDirectory = currentDirectory.subDirectories.first { it.name == command.split(" ")[2] }
command.startsWith("dir ") -> currentDirectory.subDirectories.add(Directory(name = command.split(" ")[1], parent = currentDirectory))
!command.startsWith("$") -> currentDirectory.files.add(File(size = command.split(" ")[0].toInt(), name = command.split(" ")[1]))
}
}
return root
}
fun part1(input: List<String>): Int {
val root = buildRootDirectory(input)
return root.allSubDirectories().map { it.size() }.filter { it < 100000 }.sum()
}
fun part2(input: List<String>): Int {
val root = buildRootDirectory(input)
val remainingRequiredSpace = 30000000 - (70000000 - root.size())
return root.allSubDirectories().map { it.size() }.filter { it > remainingRequiredSpace }.sorted().first()
}
val input = readInput("Day07")
val testInput = readInput("Day07_test")
// PART 1
check(part1(testInput) == 95437)
println(part1(input))
// PART 2
check(part2(testInput) == 24933642)
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
f2f5cb5fd50fb3e7fb9deeab2ae637d2e3605ea3
| 1,966 |
aoc-2022
|
Apache License 2.0
|
src/Day11.kt
|
maewCP
| 579,203,172 | false |
{"Kotlin": 59412}
|
import java.math.BigInteger
fun main() {
fun readMonkeys(strs: List<String>): MutableList<Day11Monkey> {
val monkeys = mutableListOf<Day11Monkey>()
val regex = "Monkey (\\d+):\\n.*Starting items: (.*)\\n.*Operation: new = old (.*)\\n.*Test: divisible by (\\d+)\\n.*If true: throw to monkey (\\d+)\\n.*If false: throw to monkey (\\d+)".toRegex()
strs.forEach { str ->
val groups = regex.find(str)!!.destructured.toList()
val (operation, value) = groups[2].split(" ")
monkeys.add(
Day11Monkey(
no = groups[0].toInt(),
items = groups[1].split(", ").map { Day11Item(it.toBigInteger(), it.toBigInteger()) }.toMutableList(),
operation = operation,
value = if (value == "old") -1 else value.toInt(),
divisibleBy = groups[3].toInt(),
whenTrue = groups[4].toInt(),
whenFalse = groups[5].toInt()
)
)
}
return monkeys
}
fun _process(input: List<String>, divideWorry: Boolean, noOfRound: Int): List<Day11Monkey> {
val allInput = input.joinToString(separator = "\n")
var monkeys = readMonkeys(allInput.split("\n\n"))
var superDiv = 1
monkeys.forEach { monkey ->
superDiv *= monkey.divisibleBy
}
(0 until noOfRound).forEach { round ->
monkeys.forEach { m ->
(0 until m.items.size).forEach { i ->
val item = m.items[0]
m.items = m.items.drop(1).toMutableList()
when (m.operation) {
"+" -> {
// item.realValue = item.realValue + if (m.value == -1) item.realValue else m.value.toBigInteger()
item.modded = item.modded + if (m.value == -1) item.modded else m.value.toBigInteger()
}
"*" -> {
// item.realValue = item.realValue * (if (m.value == -1) item.realValue else m.value.toBigInteger())
item.modded = item.modded * (if (m.value == -1) item.modded else m.value.toBigInteger())
}
}
if (divideWorry) item.modded /= 3.toBigInteger()
item.modulo(superDiv)
if (item.divisibleBy(m.divisibleBy)) {
monkeys[m.whenTrue].items.add(item)
} else {
monkeys[m.whenFalse].items.add(item)
}
m.counting++
}
}
// monkeys.forEach { monkey ->
// println(monkey)
// }
}
monkeys = monkeys.sortedByDescending { it.counting }.toMutableList()
return monkeys
}
fun part1(input: List<String>): Long {
val monkeys = _process(input, true, 20)
return monkeys[0].counting * monkeys[1].counting
}
fun part2(input: List<String>): Long {
val monkeys = _process(input, false, 10000)
return monkeys[0].counting * monkeys[1].counting
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
part1(input).println()
part2(input).println()
}
data class Day11Monkey(
val no: Int,
var items: MutableList<Day11Item>,
val operation: String,
val value: Int,
val divisibleBy: Int,
val whenTrue: Int,
val whenFalse: Int,
var counting: Long = 0
)
data class Day11Item(var modded: BigInteger, var realValue: BigInteger) {
fun modulo(superDiv: Int) {
modded = modded.mod(superDiv.toBigInteger())
}
fun divisibleBy(value: Int): Boolean {
return modded.mod(value.toBigInteger()).equals(BigInteger.ZERO)
}
}
| 0 |
Kotlin
| 0 | 0 |
8924a6d913e2c15876c52acd2e1dc986cd162693
| 4,049 |
advent-of-code-2022-kotlin
|
Apache License 2.0
|
src/Day07.kt
|
gsalinaslopez
| 572,839,981 | false |
{"Kotlin": 21439}
|
const val TOTAL_DISK_SPACE = 70000000
const val UPDATE_SIZE = 30000000
enum class FileType { FILE, DIR }
data class FileSystemEntry(val size: Long, val name: String, val fileType: FileType)
fun main() {
fun buildFileSystemTree(input: List<String>): Map<FileSystemEntry, List<FileSystemEntry>> {
val dirNavigationStack = ArrayDeque<String>()
val fileSystemTree = mutableMapOf<FileSystemEntry, MutableList<FileSystemEntry>>()
var i = 0
while (i < input.size) {
val instructionLine = input[i]
when {
instructionLine.contains("$ cd") -> {
with(instructionLine.split(" ")[2]) {
when {
equals("..") -> dirNavigationStack.removeLast()
equals("/") -> dirNavigationStack.clear()
.also { dirNavigationStack.add(this) }
else -> dirNavigationStack.add(this)
}
}
}
instructionLine.contains("$ ls") -> {
val currentPath = "/" + dirNavigationStack.subList(1, dirNavigationStack.size)
.joinToString(separator = "/")
val currentDir = FileSystemEntry(-1, currentPath, FileType.DIR)
fileSystemTree[currentDir] = mutableListOf()
input.subList(i + 1, input.size).takeWhile { !it.contains("$") }.forEach {
val entry = it.split(" ")
val filePath = if (currentPath.length == 1) {
"/${entry[1]}"
} else {
"$currentPath/${entry[1]}"
}
val fileSystemEntry = if (entry[0].contains("dir")) {
FileSystemEntry(-1, filePath, FileType.DIR)
} else {
FileSystemEntry(entry[0].toLong(), filePath, FileType.FILE)
}
fileSystemTree[currentDir]?.add(fileSystemEntry)
i++
}
}
}
i++
}
return fileSystemTree
}
fun buildDirList(
fileSystemTree: Map<FileSystemEntry, List<FileSystemEntry>>
): List<FileSystemEntry> {
val dirs = mutableListOf<FileSystemEntry>()
fun rec(fileSystemEntry: FileSystemEntry): Long {
val totalSum = fileSystemTree[fileSystemEntry]?.sumOf {
when (it.fileType) {
FileType.FILE -> it.size
FileType.DIR -> rec(it)
}
} ?: 0
dirs.add(FileSystemEntry(totalSum, fileSystemEntry.name, FileType.DIR))
return totalSum
}
rec(fileSystemEntry = FileSystemEntry(-1, "/", FileType.DIR))
return dirs
}
fun part1(input: List<String>): Long {
val fileSystemTree = buildFileSystemTree(input)
val dirs = buildDirList(fileSystemTree)
return dirs.filter { it.size <= 100000L }.sumOf { it.size }
}
fun part2(input: List<String>): Long {
val fileSystemTree = buildFileSystemTree(input)
val dirs = buildDirList(fileSystemTree)
val remainingSize = TOTAL_DISK_SPACE - dirs.first { it.name == "/" }.size
val minSpaceToFree = UPDATE_SIZE - remainingSize
return dirs.sortedBy { it.size }.first { it.size >= minSpaceToFree }.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))
}
| 0 |
Kotlin
| 0 | 0 |
041c7c3716bfdfdf4cc89975937fa297ea061830
| 3,871 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
AdventOfCodeDay19/src/nativeMain/kotlin/Day19.kt
|
bdlepla
| 451,510,571 | false |
{"Kotlin": 165771}
|
class Day19(lines:List<String>) {
private val scanners: List<Set<Point3d>> = parseInput(lines.joinToString("\n"))
private fun parseInput(input: String): List<Set<Point3d>> =
input.split("\n\n").map { singleScanner ->
singleScanner
.lines()
.drop(1)
.map { Point3d.of(it) }
.toSet()
}
fun solvePart1() = solve().beacons.size
fun solvePart2() = solve().scanners.pairs().maxOf { it.first distanceTo it.second }
private fun solve(): Solution {
val baseSector = scanners.first().toMutableSet()
val foundScanners = mutableSetOf(Point3d(0,0,0))
val unmappedSectors = ArrayDeque<Set<Point3d>>().apply { addAll(scanners.drop(1)) }
while(unmappedSectors.isNotEmpty()) {
val thisSector = unmappedSectors.removeFirst()
when (val transform = findTransformIfIntersects(baseSector, thisSector)) {
null -> unmappedSectors.add(thisSector)
else -> {
baseSector.addAll(transform.beacons)
foundScanners.add(transform.scanner)
}
}
}
return Solution(foundScanners, baseSector)
}
private fun findTransformIfIntersects(left: Set<Point3d>, right: Set<Point3d>): Transform? =
(0 until 6).firstNotNullOfOrNull { face ->
(0 until 4).firstNotNullOfOrNull { rotation ->
val rightReoriented = right.map { it.face(face).rotate(rotation) }.toSet()
left.firstNotNullOfOrNull { s1 ->
rightReoriented.firstNotNullOfOrNull { s2 ->
val difference = s1 - s2
val moved = rightReoriented.map { it + difference }.toSet()
if (moved.intersect(left).size >= 12) {
Transform(difference, moved)
} else null
}
}
}
}
}
private class Transform(val scanner: Point3d, val beacons: Set<Point3d>)
private class Solution(val scanners: Set<Point3d>, val beacons: Set<Point3d>)
| 0 |
Kotlin
| 0 | 0 |
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
| 2,173 |
AdventOfCode2021
|
The Unlicense
|
jvm/src/main/kotlin/io/prfxn/aoc2021/day08.kt
|
prfxn
| 435,386,161 | false |
{"Kotlin": 72820, "Python": 362}
|
// Seven Segment Search (https://adventofcode.com/2021/day/8)
package io.prfxn.aoc2021
fun main() {
val lines =
requireNotNull(object {}.javaClass.classLoader.getResourceAsStream("input/08.txt"))
.reader()
.useLines { lineSeq ->
lineSeq
.map { line ->
val (patterns, output) =
line.split(" | ").map { it.split(" ").map { p -> p.toSet() } }
object {
val patterns = patterns
val output = output
}
}
.toList()
}
fun part1() =
lines
.flatMap { line ->
line.output.filter { it.size in setOf(2, 4, 3, 7) }
}
.count()
fun part2(): Int {
fun <T> isValid235(digitToPattern: Map<Int, Set<T>>, p2: Set<T>, p3: Set<T>, p5: Set<T>): Boolean =
p2 union p5 == digitToPattern[8] &&
p2 union digitToPattern[4]!! == digitToPattern[8]
fun <T> isValid069(digitToPattern: Map<Int, Set<T>>, p0: Set<T>, p6: Set<T>, p9: Set<T>): Boolean =
p6 union digitToPattern[1]!! == digitToPattern[8] &&
p9 union digitToPattern[4]!! == p9
return lines
.sumOf { line ->
val patternsBySize = line.patterns.groupBy { it.size }
val patternToDigit =
patternsBySize
.map { (patternSize, patterns) ->
when (patternSize) {
2 -> {
require(patterns.size == 1)
patterns.first() to 1
}
3 -> {
require(patterns.size == 1)
patterns.first() to 7
}
4 -> {
require(patterns.size == 1)
patterns.first() to 4
}
7 -> {
require(patterns.size == 1)
patterns.first() to 8
}
else -> null
}
}
.filterNotNull()
.toMap()
.toMutableMap()
val digitToPattern = patternToDigit.map { (k, v) -> v to k }.toMap()
patternsBySize
.flatMap { (patternSize, patterns) ->
when (patternSize) {
5 -> {
val (p2, p3, p5) = requireNotNull(
patterns
.permutations()
.find { (p2, p3, p5) -> isValid235(digitToPattern, p2, p3, p5) }
)
listOf(p2 to 2, p3 to 3, p5 to 5)
}
6 -> {
val (p0, p6, p9) = requireNotNull(
patterns
.permutations()
.find { (p0, p6, p9) -> isValid069(digitToPattern, p0, p6, p9) }
)
listOf(p0 to 0, p6 to 6, p9 to 9)
}
else -> listOf()
}
}
.toMap(patternToDigit)
line.output
.map(patternToDigit::get)
.joinToString("")
.toInt()
}
}
sequenceOf(part1(), part2()).forEach(::println)
}
/** output
* 349
* 1070957
*/
| 0 |
Kotlin
| 0 | 0 |
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
| 4,121 |
aoc2021
|
MIT License
|
kotlin/src/Day04.kt
|
ekureina
| 433,709,362 | false |
{"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386}
|
import java.lang.Long.parseLong
data class BingoSquare(val number: Long, val isPicked:Boolean = false)
data class BingoBoard(val numbers: List<List<BingoSquare>>) {
fun markNumber(number:Long): BingoBoard {
return BingoBoard(numbers.map { row ->
row.map { square ->
if (square.number == number) {
BingoSquare(square.number, true)
} else {
BingoSquare(square.number, square.isPicked)
}
}
})
}
fun score(finalPick: Long): Long {
return numbers
.flatten()
.filterNot(BingoSquare::isPicked)
.map(BingoSquare::number)
.sum() * finalPick
}
}
data class BingoGame(val numberPicks: List<Long>, var boards: List<BingoBoard>)
fun parseBingo(input: List<String>): BingoGame {
val picks = input.first()
val numberPicks = picks.split(",").map(::parseLong)
val boards = input.drop(2).chunked(6).map(::parseBingoBoard)
return BingoGame(numberPicks, boards)
}
fun parseBingoBoard(input: List<String>): BingoBoard {
return BingoBoard(input.filter { it != "" }.map { bingoLine ->
bingoLine.split(" ").filter { it != "" }.map(::parseLong).map(::BingoSquare)
})
}
fun winningBingo(board: BingoBoard): Boolean {
val rowWin = board.numbers.any { row ->
row.all(BingoSquare::isPicked)
}
if (rowWin) {
return true
}
return board.numbers.indices.asSequence().map { index ->
val column = board.numbers.map { row ->
row[index]
}
column.all(BingoSquare::isPicked)
}.any { it }
}
fun main() {
fun part1(input: List<String>): Long {
val game = parseBingo(input)
game.numberPicks.forEach { pick ->
game.boards = game.boards.map { board ->
board.markNumber(pick)
}
val score = game.boards.firstOrNull(::winningBingo)?.score(pick)
if (score != null ) {
return score
}
}
return -1
}
fun part2(input: List<String>): Long {
val game = parseBingo(input)
game.numberPicks.forEach { pick ->
val boards = game.boards.map { board ->
board.markNumber(pick)
}
if (boards.filterNot(::winningBingo).isEmpty()) {
return boards.firstOrNull(::winningBingo)!!.score(pick)
} else {
game.boards = boards.filterNot(::winningBingo)
}
}
return -1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 4512L)
val output = part2(testInput)
check(output == 1924L) { "$output" }
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
391d0017ba9c2494092d27d22d5fd9f73d0c8ded
| 2,913 |
aoc-2021
|
MIT License
|
src/Day09.kt
|
mkfsn
| 573,042,358 | false |
{"Kotlin": 29625}
|
import kotlin.math.sign
fun main() {
data class Action(val direction: Char, val steps: Int)
data class Point(val x: Int, val y: Int)
class Solution(input: List<String>, size: Int) {
val actions: List<Action>
val rope = MutableList(size) { Point(1, 1) }
init {
this.actions = input.map { it.split(" ").run { Action(this[0][0], this[1].toInt()) } }
}
fun result() =
actions.fold(mutableListOf<Point>()) { tailHistory, action ->
(1..action.steps).forEach { _ ->
rope.forEachIndexed { i, cur ->
rope[i] = if (i == 0) moveHead(action.direction, cur) else moveKnot(rope[i - 1], cur)
}
tailHistory.add(rope.last().copy())
}
tailHistory
}.distinct().count()
private fun moveHead(direction: Char, cur: Point): Point = when (direction) {
'U' -> Point(cur.x, cur.y + 1)
'D' -> Point(cur.x, cur.y - 1)
'R' -> Point(cur.x + 1, cur.y)
'L' -> Point(cur.x - 1, cur.y)
else -> cur
}
private fun moveKnot(pre: Point, cur: Point): Point = run {
val (dx, dy) = listOf(pre.x - cur.x, pre.y - cur.y)
if (dx in -1..1 && dy in -1..1) cur else Point(cur.x + dx.sign, cur.y + dy.sign)
}
}
fun part1(input: List<String>) = Solution(input, 2).result()
fun part2(input: List<String>) = Solution(input, 10).result()
// test if implementation meets criteria from the description, like:
val testInput1 = readInput("Day09_test1")
check(part1(testInput1) == 13)
check(part2(testInput1) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
8c7bdd66f8550a82030127aa36c2a6a4262592cd
| 1,903 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
gcj/y2020/round2/a.kt
|
mikhail-dvorkin
| 93,438,157 | false |
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
|
package gcj.y2020.round2
import kotlin.math.pow
fun solvePancakes(aIn: Long, bIn: Long): String {
var a = aIn; var b = bIn
var i = 1L
val maxN = (a.toDouble() + b + 100).pow(0.5).toLong() * 2
fun step(): String? {
if (maxOf(a, b) < i) return "${i - 1} $a $b"
if (a >= b) a -= i else b -= i
i++
return null
}
fun take(amount: Long) = (i - 1..maxN).binarySearch { j -> sum(i, j) >= amount } - 1
val takeA = take(a - b)
a -= sum(i, takeA)
i = takeA + 1
step()?.also { return it }
val takeB = take(b - a)
b -= sum(i, takeB)
i = takeB + 1
if (b > a) { step()?.also { return it } }
val takeAB = (take(a + b) - i) / 2
a -= (i + takeAB - 1) * takeAB
b -= (i + takeAB) * takeAB
i += 2 * takeAB
while (true) { step()?.also { return it } }
}
private fun solve(): String {
val (a, b) = readLongs()
return solvePancakes(a, b)
}
private fun sum(start: Long, end: Long) = (start + end) * (end + 1 - start) / 2
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun LongRange.binarySearch(predicate: (Long) -> Boolean): Long {
var (low, high) = this.first to this.last // must be false .. must be true
while (low + 1 < high) (low + (high - low) / 2).also { if (predicate(it)) high = it else low = it }
return high // first true
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readLongs() = readStrings().map { it.toLong() }
| 0 |
Java
| 1 | 9 |
30953122834fcaee817fe21fb108a374946f8c7c
| 1,477 |
competitions
|
The Unlicense
|
advent-of-code-2021/src/main/kotlin/Day8.kt
|
jomartigcal
| 433,713,130 | false |
{"Kotlin": 72459}
|
//Day 8: Seven Segment Search
//https://adventofcode.com/2021/day/8
import java.io.File
fun main() {
val lines = File("src/main/resources/Day8.txt").readLines()
count1478FromOutput(lines.map { it.substringAfter(" | ").split(" ") })
countAll(lines)
}
fun count1478FromOutput(outputs: List<List<String>>) {
val count = outputs.sumOf { output ->
output.count { it.length in listOf(2, 3, 4, 7) }
}
println(count)
}
fun countAll(lines: List<String>) {
val sum = lines.sumOf { line ->
decode(
line.substringBefore(" | ").split(" "),
line.substringAfter(" | ").split(" ")
)
}
println(sum)
}
fun decode(input: List<String>, output: List<String>): Int {
val cf = input.find { it.length == 2 }!!
val acf = input.find { it.length == 3 }!!
val bcdf = input.find { it.length == 4 }!!
val abcdefg = input.find { it.length == 7 }!!
val abcdfg = input.find { it.length == 6 && (it.toSet() intersect bcdf.toSet()).size == 4 }!!
val abdefg = input.find { it.length == 6 && (it.toSet() intersect acf.toSet()).size == 2 }!!
val abcefg = input.find { it.length == 6 && it != abcdfg && it != abdefg }!!
val acdfg = input.find { it.length == 5 && (it.toSet() intersect acf.toSet()).size == 3 }!!
val acdeg = input.find { it.length == 5 && (it.toSet() intersect bcdf.toSet()).size == 2 }!!
val abdfg = input.find { it.length == 5 && it != acdfg && it != acdeg }!!
val map = mapOf(
abcefg to 0, cf to 1, acdeg to 2, acdfg to 3, bcdf to 4, abdfg to 5,
abdefg to 6, acf to 7, abcdefg to 8, abcdfg to 9,
).mapKeys { it.key.toSet().sorted().joinToString("") }
val sum = output.map {
map[it.toSet().sorted().joinToString("")]!!
}.joinToString("")
return sum.toInt()
}
| 0 |
Kotlin
| 0 | 0 |
6b0c4e61dc9df388383a894f5942c0b1fe41813f
| 1,814 |
advent-of-code
|
Apache License 2.0
|
src/main/kotlin/Day17.kt
|
clechasseur
| 267,632,210 | false | null |
import org.clechasseur.adventofcode2016.Direction
import org.clechasseur.adventofcode2016.Pt
import org.clechasseur.adventofcode2016.md5
object Day17 {
private const val input = "awrkjxxr"
fun part1(): String = shortestPath(State(Pt.ZERO, emptyList()))
fun part2(): Int = longestPath(State(Pt.ZERO, emptyList())).length
private fun shortestPath(initialState: State): String = generateSequence(listOf(initialState)) { ls ->
ls.flatMap { it.possibilities() }.apply {
require(isNotEmpty()) { "No path found" }
}
}.dropWhile { ls ->
ls.none { it.inVault }
}.first().first { it.inVault }.path.toPathString()
private fun longestPath(initialState: State): String {
var states = listOf(initialState)
var longestState: State? = null
while (states.isNotEmpty()) {
states = states.flatMap { it.possibilities() }
states.firstOrNull { it.inVault }?.apply { longestState = this }
states = states.filterNot { it.inVault }
}
return longestState?.path?.toPathString() ?: error("No path found")
}
private data class State(val pos: Pt, val path: List<Direction>) {
val inVault: Boolean
get() = pos == Pt(3, 3)
fun possibilities(): List<State> = Direction.values().filter { d ->
val next = pos + d.displacement
next.x in 0..3 && next.y in 0..3
}.filter { d ->
val hash = md5("$input${path.toPathString()}")
hash[d.hashIndex].open
}.map {
State(pos + it.displacement, path + it)
}
}
private fun List<Direction>.toPathString(): String = joinToString("") { it.c.toString() }
private val Direction.hashIndex: Int
get() = when (this) {
Direction.UP -> 0
Direction.DOWN -> 1
Direction.LEFT -> 2
Direction.RIGHT -> 3
}
private val Char.open: Boolean
get() = this in 'b'..'f'
}
| 0 |
Kotlin
| 0 | 0 |
120795d90c47e80bfa2346bd6ab19ab6b7054167
| 2,008 |
adventofcode2016
|
MIT License
|
src/Day02.kt
|
l8nite
| 573,298,097 | false |
{"Kotlin": 105683}
|
fun main() {
val points = mapOf("Rock" to 1, "Paper" to 2, "Scissors" to 3)
val beats = mapOf("Rock" to "Paper", "Paper" to "Scissors", "Scissors" to "Rock")
val beatenBy = beats.entries.associateBy({ it.value }){ it.key }
fun parseGuide(input: List<String>, strategy: Map<String, String>): List<Pair<String, String>> {
val opponent = mapOf("A" to "Rock", "B" to "Paper", "C" to "Scissors")
return input.map { line ->
line.split(" ").let {
Pair(opponent[it[0]]!!, strategy[it[1]]!!)
}
}
}
fun score(theirs: String, ours: String): Int {
var score = if (theirs == ours) { 3 } else if ( beats[theirs] == ours ) { 6 } else { 0 }
score += points[ours]!!
return score
}
fun part1(input: List<String>): Int {
val guide = parseGuide(input, mapOf("X" to "Rock", "Y" to "Paper", "Z" to "Scissors"))
var score = 0
guide.forEach {
score += score(it.first, it.second)
}
return score
}
fun part2(input: List<String>): Int {
val guide = parseGuide(input, mapOf("X" to "Lose", "Y" to "Draw", "Z" to "Win"))
var score = 0
guide.forEach {
val (theirs, strategy) = it
val ours = when (strategy) {
"Lose" -> beatenBy[theirs]
"Win" -> beats[theirs]
"Draw" -> theirs
else -> null
}
score += score(theirs, ours!!)
}
return 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
| 0 | 0 |
f74331778fdd5a563ee43cf7fff042e69de72272
| 1,828 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day08.kt
|
iartemiev
| 573,038,071 | false |
{"Kotlin": 21075}
|
fun generateTreePairSet(matrix: List<List<Int>>): Set<Pair<Int, Int>> {
val minLeft = 1
val minTop = 1
val minRight = matrix[0].size - 2
val minBottom = matrix.size - 2
val treePairSet = mutableSetOf<Pair<Int, Int>>()
// top left -> bottom right
val minTopY = matrix[0].toCollection(mutableListOf())
for (i in minTop..minBottom) {
var minX = matrix[i][0]
for (j in minLeft..minRight) {
val treeHeight = matrix[i][j]
if (minX < treeHeight) {
treePairSet.add(Pair(i, j))
minX = treeHeight
}
if (minTopY[j] < treeHeight) {
treePairSet.add(Pair(i, j))
minTopY[j] = treeHeight
}
}
}
// bottom right -> top left
val minBottomY = matrix[matrix.size - 1].toCollection(mutableListOf())
for (i in minBottom downTo minTop) {
var minX = matrix[i][matrix[0].size - 1]
for (j in minRight downTo minLeft) {
val treeHeight = matrix[i][j]
if (minX < treeHeight) {
treePairSet.add(Pair(i, j))
minX = treeHeight
}
if (minBottomY[j] < treeHeight) {
treePairSet.add(Pair(i, j))
minBottomY[j] = treeHeight
}
}
}
return treePairSet
}
fun scenicScoreForTree(matrix: List<List<Int>>, treeCoords: Pair<Int, Int>): Int {
val (y, x) = treeCoords
val treeHeight = matrix[y][x]
var topDownTotal = 0
for(i in y+1 until matrix.size) {
topDownTotal++
if (matrix[i][x] >= treeHeight) {
break
}
}
var leftRightTotal = 0
for(i in x+1 until matrix.size) {
leftRightTotal++
if (matrix[y][i] >= treeHeight) {
break
}
}
var bottomUpTotal = 0
for(i in y-1 downTo 0) {
bottomUpTotal++
if (matrix[i][x] >= treeHeight) {
break
}
}
var rightLeftTotal = 0
for(i in x-1 downTo 0) {
rightLeftTotal++
if (matrix[y][i] >= treeHeight) {
break
}
}
return topDownTotal * leftRightTotal * bottomUpTotal * rightLeftTotal
}
fun main() {
fun part1(input: List<String>): Int {
val matrix: List<List<Int>> = input.map { it.map { inner -> inner.toString().toInt() } }
val perimeterLength = 2 * (matrix.size - 1 + matrix[0].size - 1)
val treePairSet = generateTreePairSet(matrix)
return perimeterLength + treePairSet.size
}
fun part2(input: List<String>): Int {
val matrix: List<List<Int>> = input.map { it.map { inner -> inner.toString().toInt() } }
val treePairSet = generateTreePairSet(matrix)
return treePairSet.maxOfOrNull { scenicScoreForTree(matrix, it) } ?: 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
8d2b7a974c2736903a9def65282be91fbb104ffd
| 2,812 |
advent-of-code
|
Apache License 2.0
|
src/Day09.kt
|
jorgecastrejon
| 573,097,701 | false |
{"Kotlin": 33669}
|
import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val moves = input.map { move -> move.split(" ").let { it.first() to it.last().toInt() } }
return moves.resolve(chainLength = 2).size
}
fun part2(input: List<String>): Int {
val moves = input.map { move -> move.split(" ").let { it.first() to it.last().toInt() } }
return moves.resolve(chainLength = 10).size
}
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
fun List<Pair<String, Int>>.resolve(chainLength: Int): Set<PointXY> =
fold(Array(chainLength) { PointXY() } to mutableSetOf(PointXY())) { (chain, visitedPosition), (dir, amount) ->
repeat(amount) { chain.move(dir).also { visitedPosition.add(it.last()) } }
chain to visitedPosition
}.second
private fun Array<PointXY>.move(dir: String): Array<PointXY> {
val diff = when (dir) {
"R" -> 1 to 0
"L" -> -1 to 0
"U" -> 0 to -1
else -> 0 to 1
}
this[0] = get(0).plus(x = diff.first, y = diff.second)
for (i in 1 until this.size) {
this[i] = get(i) follows this[i - 1]
}
return this
}
private infix fun PointXY.follows(head: PointXY): PointXY {
val dx = head.x - this.x
val dy = head.y - this.y
return if (abs(dx) <= 1 && abs(dy) <= 1) {
this
} else {
plus(x = if (abs(dx) > 1) dx / 2 else dx, y = if (abs(dy) > 1) dy / 2 else dy)
}
}
| 0 |
Kotlin
| 0 | 0 |
d83b6cea997bd18956141fa10e9188a82c138035
| 1,487 |
aoc-2022
|
Apache License 2.0
|
src/main/kotlin/day15/Day15.kt
|
joostbaas
| 573,096,671 | false |
{"Kotlin": 45397}
|
package day15
import kotlin.math.abs
fun String.parse(): SensorReading {
val regex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)"""
val (x1, y1, x2, y2) = regex.toRegex().matchEntire(this)!!.destructured
return SensorReading(Point(x1.toInt(), y1.toInt()), Point(x2.toInt(), y2.toInt()))
}
data class Point(
val x: Int,
val y: Int,
) {
fun distanceTo(other: Point) = abs(x - other.x) + abs(y - other.y)
}
data class SensorReading(val sensor: Point, val beacon: Point) {
val distanceToBeacon = sensor.distanceTo(beacon)
fun rulesOutPossibilityOfHereBeingABeacon(point: Point): Boolean {
return sensor.distanceTo(point) <= distanceToBeacon
}
}
fun day15Part1(input: List<String>, y: Int): Int =
input.map {
it.parse()
}.let { sensorReadings ->
val allPoints = sensorReadings.flatMap { listOf(it.sensor, it.beacon) }
val minY = allPoints.minOf { it.y }
val minX = allPoints.minOf { it.x }
val maxY = allPoints.maxOf { it.y }
val maxX = allPoints.maxOf { it.x }
// this could be simpler/more efficient: just take the max distance between a sensor and it's beacon for instance.
val maximumDistanceToLookFurther = Point(minX, minY).distanceTo(Point(maxX, maxY))
val start = minX - maximumDistanceToLookFurther
val end = maxX + maximumDistanceToLookFurther
val whichPointCannotContainABeacon = (start..end).map { Point(it, y) }
.count { point ->
sensorReadings.any { reading -> reading.rulesOutPossibilityOfHereBeingABeacon(point) }
}
val beaconsOnThatLine = sensorReadings.map { it.beacon }.toSet().count { it.y == y }
whichPointCannotContainABeacon - beaconsOnThatLine
}
fun day15Part2(input: List<String>, end: Int): Long = input.map {
it.parse()
}.let { sensorReadings ->
val allSensorsAndBeacons = sensorReadings.flatMap { listOf(it.sensor, it.beacon) }
// check all the points distance+1 from a sensor, it must be there somewhere
val locationsWhereThereCouldBeABeacon = (0..end).flatMap { y ->
val relevantSensors = sensorReadings.filter {
val distanceToThisLine = abs(y - it.sensor.y)
distanceToThisLine < it.distanceToBeacon
}
relevantSensors.flatMap { sensorReading ->
val distanceToThisLine = abs(y - sensorReading.sensor.y)
val leftX = sensorReading.sensor.x - (sensorReading.distanceToBeacon - distanceToThisLine) - 1
val rightX = sensorReading.sensor.x + (sensorReading.distanceToBeacon - distanceToThisLine) + 1
listOf(Point(leftX, y), Point(rightX, y))
.filter { candidate -> candidate.x in (0..end) && candidate.y in (0..end) }
.filter { candidate -> candidate !in allSensorsAndBeacons }
.filter { candidate ->
sensorReadings.none { reading -> reading.rulesOutPossibilityOfHereBeingABeacon(candidate) }
}
}
}
return locationsWhereThereCouldBeABeacon[0].let { it.x.toLong() * 4_000_000L + it.y }
}
| 0 |
Kotlin
| 0 | 0 |
8d4e3c87f6f2e34002b6dbc89c377f5a0860f571
| 3,160 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day02.kt
|
WhatDo
| 572,393,865 | false |
{"Kotlin": 24776}
|
fun main() {
val input = readInput("Day02")
val rounds = input.map(::mapRound)
val scores = rounds.map(::roundScore)
println("Total score for following guide is ${scores.sum()}")
val outcomeRound = input.map(::mapOutcomeRound)
val outcomeScores = outcomeRound.map(::outcomeRoundScore)
println("Total score for following outcomes is ${outcomeScores.sum()}")
}
fun outcomeRoundScore(round: OutcomeRound): Int {
return (round.outcome.score + handFromOutcome(round.opponent, round.outcome).also {
println("$round gives outcome $it")
}.score).also {
println("$round gives score $it")
}
}
fun handFromOutcome(opponent: Hand, outcome: Outcome): Hand {
return when (outcome) {
Outcome.Win -> opponent.losesTo()
Outcome.Draw -> opponent
Outcome.Loss -> opponent.winsAgainst()
}
}
fun roundScore(round: Round): Int {
return round.you.score + handOutcome(round.you, round.opponent).also {
// println("Round $round gives outcome $it")
}.score
}
fun handOutcome(you: Hand, opponent: Hand): Outcome {
if (you == opponent) return Outcome.Draw
val isWin = when (you) {
Hand.Rock -> opponent == Hand.Scissor
Hand.Paper -> opponent == Hand.Rock
Hand.Scissor -> opponent == Hand.Paper
}
return if (isWin) {
Outcome.Win
} else {
Outcome.Loss
}
}
data class OutcomeRound(
val opponent: Hand,
val outcome: Outcome
)
data class Round(
val opponent: Hand,
val you: Hand
)
enum class Hand(val score: Int) {
Rock(1), Paper(2), Scissor(3);
fun losesTo() = when (this) {
Rock -> Paper
Paper -> Scissor
Scissor -> Rock
}
fun winsAgainst() = when (this) {
Rock -> Scissor
Paper -> Rock
Scissor -> Paper
}
}
enum class Outcome(val score: Int) {
Win(6), Draw(3), Loss(0)
}
fun mapOutcomeRound(round: String): OutcomeRound {
val (p1, outcome) = round.split(" ")
return OutcomeRound(mapHand(p1), mapOutcome(outcome))
}
fun mapRound(round: String): Round {
val (p1, p2) = round.split(" ")
return Round(mapHand(p1), mapHand(p2))
}
fun mapOutcome(hand: String) = when (hand) {
"X" -> Outcome.Loss
"Y" -> Outcome.Draw
"Z" -> Outcome.Win
else -> TODO()
}
fun mapHand(hand: String): Hand {
return when (hand) {
"A", "X" -> Hand.Rock
"B", "Y" -> Hand.Paper
"C", "Z" -> Hand.Scissor
else -> throw IllegalArgumentException("$hand is not a legal input")
}
}
| 0 |
Kotlin
| 0 | 0 |
94abea885a59d0aa3873645d4c5cefc2d36d27cf
| 2,562 |
aoc-kotlin-2022
|
Apache License 2.0
|
src/Day11.kt
|
kpilyugin
| 572,573,503 | false |
{"Kotlin": 60569}
|
fun main() {
class Monkey(
val operation: (Long) -> Long,
val divisibleBy: Int,
val test: (Long) -> Int) {
val items = mutableListOf<Long>()
var inspected = 0L
fun inspect(monkeys: List<Monkey>, manage: (Long) -> Long = { it / 3 }) {
for (item in items) {
inspected++
var cur = operation(item)
cur = manage(cur)
monkeys[test(cur)].items += cur
}
items.clear()
}
}
fun String.parseMonkey(): Monkey {
val (starting, operation, test, testTrue, testFalse) = split("\n").drop(1)
val ops = operation.substringAfter("= ").split(" ")
val opFunction = { old: Long ->
val r = if (ops[2] == "old") old else ops[2].toLong()
if (ops[1] == "*") old * r else old + r
}
val divisibleBy = test.substringAfter("by ").toInt()
val ifTrue = testTrue.substringAfter("monkey ").toInt()
val ifFalse = testFalse.substringAfter("monkey ").toInt()
val testFunction = { value: Long ->
if (value % divisibleBy == 0L) ifTrue else ifFalse
}
return Monkey(opFunction, divisibleBy, testFunction).apply {
starting.substringAfter(": ").split(", ").forEach {
items += it.toLong()
}
}
}
fun List<Monkey>.top2(): Long {
val top = map { it.inspected }.sortedDescending()
return top[0] * top[1]
}
fun part1(input: String): Long {
val monkeys = input.split("\n\n").map { it.parseMonkey() }
repeat(20) {
for (monkey in monkeys) {
monkey.inspect(monkeys)
}
}
return monkeys.top2()
}
fun part2(input: String): Long {
val monkeys = input.split("\n\n").map { it.parseMonkey() }
val product = monkeys.map { it.divisibleBy }.reduce { d1, d2 -> d1 * d2 }
repeat(10000) {
for (monkey in monkeys) {
monkey.inspect(monkeys) { value -> value % product }
}
}
return monkeys.top2()
}
val testInput = readInput("Day11_test")
check(part1(testInput), 10605L)
check(part2(testInput), 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
7f0cfc410c76b834a15275a7f6a164d887b2c316
| 2,376 |
Advent-of-Code-2022
|
Apache License 2.0
|
src/year2021/day15/Day15.kt
|
fadi426
| 433,496,346 | false |
{"Kotlin": 44622}
|
package year2021.day15
import util.read2021DayInput
fun main() {
fun task1(input: List<String>): Int {
val board = MutableList(input.size) { input[it].map { "$it".toInt() }.toMutableList() }
return findShortestDistance(board)
}
fun task2(input: List<String>, expansionNumber: Int): Int {
val board = MutableList(input.size) { input[it].map { "$it".toInt() }.toMutableList() }
return findShortestDistance(expandBoard(board, expansionNumber))
}
val input = read2021DayInput("Day15")
// assertTrue(task1(input) == 609)
// println(task1(input))
println(task2(input, 5))
}
fun findShortestDistance(board: MutableList<MutableList<Int>>): Int {
val distanceFromStartBoard = board.map { it.map { Int.MAX_VALUE }.toMutableList() }.toMutableList()
distanceFromStartBoard[0][0] = board[0][0]
for (y in board.indices) {
for (x in board.indices) {
board.getOrNull(y)?.getOrNull(x + 1)?.let {
val xValue = distanceFromStartBoard[y][x] + board[y][x + 1]
if (xValue < distanceFromStartBoard[y][x + 1]) distanceFromStartBoard[y][x + 1] = xValue
}
board.getOrNull(y)?.getOrNull(x - 1)?.let {
val xValue = distanceFromStartBoard[y][x] + board[y][x - 1]
if (xValue < distanceFromStartBoard[y][x - 1]) distanceFromStartBoard[y][x - 1] = xValue
}
board.getOrNull(y + 1)?.getOrNull(x)?.let {
val yValue = distanceFromStartBoard[y][x] + board[y + 1][x]
if (yValue < distanceFromStartBoard[y + 1][x]) distanceFromStartBoard[y + 1][x] = yValue
}
board.getOrNull(y - 1)?.getOrNull(x)?.let {
val yValue = distanceFromStartBoard[y][x] + board[y - 1][x]
if (yValue < distanceFromStartBoard[y - 1][x]) distanceFromStartBoard[y - 1][x] = yValue
}
}
}
distanceFromStartBoard.forEach { println(it) }
return distanceFromStartBoard.last().last() - distanceFromStartBoard[0][0]
}
fun expandBoard(board: MutableList<MutableList<Int>>, times: Int): MutableList<MutableList<Int>> {
val fullBoard = MutableList(board.size * (times)) { mutableListOf<Int>() }
for (i in 0 until times) {
for (y in board.indices) {
fullBoard[y].addAll(board[y].map { if (it + i > 9) it + i - 9 else it + i })
}
}
for (i in 1 until times) {
for (y in board.indices) {
fullBoard[y + board.size * i].addAll(fullBoard[y].map { if (it + i > 9) it + i - 9 else it + i })
}
}
return fullBoard
}
| 0 |
Kotlin
| 0 | 0 |
acf8b6db03edd5ff72ee8cbde0372113824833b6
| 2,640 |
advent-of-code-kotlin-template
|
Apache License 2.0
|
src/day9/Day09.kt
|
MatthewWaanders
| 573,356,006 | false | null |
package day9
import utils.readInput
typealias PositionState = Pair<Int, Int>
typealias Dimension = String
typealias Direction = Int
const val row: Dimension = "ROW"
const val column: Dimension = "COLUMN"
const val reverse: Direction = -1
const val normal: Direction = 1
fun main() {
val testInput = readInput("Day09_test", "day9")
check(part1(testInput) == 13)
val testInputPart2 = readInput("Day09_test_2", "day9")
check(part2(testInputPart2) == 36)
val input = readInput("Day09", "day9")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>) = solution(input, List(2) { PositionState(0,0) })
fun part2(input: List<String>) = solution(input, List(10) { PositionState(0,0) })
fun solution(input: List<String>, knots: List<PositionState>) = knots.run {
var workingList = this
input
.map { line -> line.split(" ").let { splitInputLine -> Pair(splitInputLine[0], splitInputLine[1].toInt()) } }
.fold(emptyList<PositionState>()) { acc, move ->
val head = workingList[0]
val tails = workingList.subList(1, workingList.size)
val (newlyVisited, headUpdated, tailsUpdated) = when (move.first) {
"R" -> processSteps(column, normal, head, tails, move.second)
"L" -> processSteps(column, reverse, head, tails, move.second)
"U" -> processSteps(row, normal, head, tails, move.second)
"D" -> processSteps(row, reverse, head, tails, move.second)
else -> Triple(emptyList(), head, tails)
}
workingList = listOf(headUpdated, *(tailsUpdated.toTypedArray()))
acc + newlyVisited
}.toSet().size
}
fun processSteps(dimension: Dimension, direction: Direction, head: PositionState, tails: List<PositionState>, steps: Int): Triple<List<PositionState>, PositionState, List<PositionState>> {
var headAdjustable = head
val tailsAdjustable = tails.toMutableList()
val visitedByLastTail = (0 until steps).fold(listOf(tails.last())) { acc, it ->
headAdjustable = if (dimension == column && direction == normal) {
PositionState(headAdjustable.first + 1, headAdjustable.second)
} else if (dimension == column && direction == reverse) {
PositionState(headAdjustable.first - 1, headAdjustable.second)
} else if (dimension == row && direction == normal) {
PositionState(headAdjustable.first, headAdjustable.second + 1)
} else {
PositionState(headAdjustable.first, headAdjustable.second - 1)
}
tailsAdjustable[0] = processTailStep(headAdjustable, tailsAdjustable[0])
if (tailsAdjustable.size == 1) {
acc + tailsAdjustable[0]
} else {
for (j in 1 until tailsAdjustable.size) {
tailsAdjustable[j] = processTailStep(tailsAdjustable[j-1], tailsAdjustable[j])
}
acc + tailsAdjustable.last()
}
}
return Triple(visitedByLastTail, headAdjustable, tailsAdjustable)
}
fun processTailStep(newHeadPosition: PositionState, tailPosition: PositionState): PositionState {
var xPos = tailPosition.first
var yPos = tailPosition.second
if (areTouching(newHeadPosition, tailPosition)) {
return tailPosition
}
if (newHeadPosition.first != tailPosition.first) {
if (newHeadPosition.first > tailPosition.first) xPos++ else xPos--
}
if (newHeadPosition.second != tailPosition.second) {
if (newHeadPosition.second > tailPosition.second) yPos++ else yPos--
}
return PositionState(xPos, yPos)
}
fun areTouching(head: PositionState, tail: PositionState): Boolean {
return (head.first == tail.first && head.second == tail.second) || // overlapping
(head.first == tail.first && (head.second - tail.second) in -1..1) || // same column, different row
((head.first - tail.first in -1..1) && head.second == tail.second) || // same row, different column
((head.first - tail.first in -1..1) && (head.second - tail.second in -1..1)) // diagonally touching
}
| 0 |
Kotlin
| 0 | 0 |
f58c9377edbe6fc5d777fba55d07873aa7775f9f
| 4,201 |
aoc-2022
|
Apache License 2.0
|
src/Day02.kt
|
davedupplaw
| 573,042,501 | false |
{"Kotlin": 29190}
|
fun main() {
val yourShapeMap = mapOf(
"X" to "A",
"Y" to "B",
"Z" to "C"
)
val shapeScores = mapOf(
"A" to 1,
"B" to 2,
"C" to 3
)
val beats = mapOf(
"C" to "B",
"B" to "A",
"A" to "C"
)
val winOrLose = { yours: String, theirs: String ->
if (yours == theirs) 3
else if (beats[yours] == theirs) 6
else 0
}
val forceOutcome = mapOf(
"X" to { t: String -> beats[t] },
"Y" to { t: String -> t },
"Z" to { t: String -> beats.entries.find { it.value == t }!!.key },
)
fun part1(input: List<String>): Int {
return input.asSequence()
.map { it.split(" ") }
.sumOf { winOrLose(yourShapeMap[it[1]]!!, it[0]) + shapeScores[yourShapeMap[it[1]]!!]!! }
}
fun part2(input: List<String>): Int {
return input.asSequence()
.map { it.split(" ") }
.map { listOf(it[0], forceOutcome[it[1]]!!(it[0])) }
.sumOf { winOrLose(it[1]!!, it[0]!!) + shapeScores[it[1]]!! }
}
val test = readInput("Day02.test")
check(part1(test) == 15)
check(part2(test) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
3b3efb1fb45bd7311565bcb284614e2604b75794
| 1,358 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/aoc/year2023/Day11.kt
|
SackCastellon
| 573,157,155 | false |
{"Kotlin": 62581}
|
package aoc.year2023
import aoc.Puzzle
import kotlin.math.abs
/**
* [Day 11 - Advent of Code 2023](https://adventofcode.com/2023/day/11)
*/
object Day11 : Puzzle<Long, Long> {
override fun solvePartOne(input: String): Long = input.solve(expansionRate = 2)
override fun solvePartTwo(input: String): Long = input.solve(expansionRate = 1000000)
private fun String.solve(expansionRate: Int) = lines()
.map { it.toList() }
.galaxyPositions()
.expandRows(expansionRate)
.expandColumns(expansionRate)
.cartesianProduct()
.sumOf(::distanceBetweenPoints)
private fun List<List<Char>>.galaxyPositions(): List<Pair<Long, Long>> =
flatMapIndexed { y, line -> line.mapIndexedNotNull { x, cell -> if (cell == '#') x.toLong() to y.toLong() else null } }
private fun List<Pair<Long, Long>>.expandRows(expansionRate: Int): List<Pair<Long, Long>> {
var emptyRows = 0
val sortedBy = sortedBy { it.second }
val (min, max) = sortedBy.let { it.first().second to it.last().second }
val galaxiesByRow = sortedBy.groupBy { it.second }
val result = arrayListOf<Pair<Long, Long>>()
for (row in min..max) {
galaxiesByRow[row]?.mapTo(result) { (x, y) -> x to y - emptyRows + emptyRows * expansionRate }
?: emptyRows++
}
return result
}
private fun List<Pair<Long, Long>>.expandColumns(expansionRate: Int): List<Pair<Long, Long>> {
var emptyColumns = 0
val sortedBy = sortedBy { it.first }
val (min, max) = sortedBy.let { it.first().first to it.last().first }
val galaxiesByColumn = sortedBy.groupBy { it.first }
val result = arrayListOf<Pair<Long, Long>>()
for (col in min..max) {
galaxiesByColumn[col]?.mapTo(result) { (x, y) -> x - emptyColumns + emptyColumns * expansionRate to y }
?: emptyColumns++
}
return result
}
private fun <T> List<T>.cartesianProduct(): List<Pair<T, T>> =
flatMapIndexed { i, p1 -> drop(i + 1).map { p2 -> p1 to p2 } }
private fun distanceBetweenPoints(pair: Pair<Pair<Long, Long>, Pair<Long, Long>>): Long {
val (x1, y1) = pair.first
val (x2, y2) = pair.second
return abs(x1 - x2) + abs(y1 - y2)
}
}
| 0 |
Kotlin
| 0 | 0 |
75b0430f14d62bb99c7251a642db61f3c6874a9e
| 2,334 |
advent-of-code
|
Apache License 2.0
|
src/Day13.kt
|
dizney
| 572,581,781 | false |
{"Kotlin": 105380}
|
object Day13 {
const val EXPECTED_PART1_CHECK_ANSWER = 13
const val EXPECTED_PART2_CHECK_ANSWER = 140
const val PACKET_COMBOS_NR_OF_LINES = 3
val NONE_NUMBER_CHARS = listOf('[', ']', ',')
const val DIVIDER_PACKET_ONE = 2
const val DIVIDER_PACKET_TWO = 6
val DIVIDER_PACKETS: List<List<Any>> = listOf(
listOf(listOf(DIVIDER_PACKET_ONE)),
listOf(listOf(DIVIDER_PACKET_TWO))
)
}
fun main() {
fun String.parse(): List<Any> {
val stack = ArrayDeque<MutableList<Any>>()
var idx = 0
do {
when (this[idx]) {
'[' -> {
stack.addFirst(mutableListOf())
idx++
}
']' -> {
if (stack.size > 1) {
val innerList = stack.removeFirst()
stack.first().add(innerList)
}
idx++
}
in '0'..'9' -> {
var nrStr: String = this[idx].toString()
while (this[++idx] !in Day13.NONE_NUMBER_CHARS) {
nrStr += this[idx]
}
stack.first().add(nrStr.toInt())
}
else -> idx++
}
} while (idx < this.length)
check(stack.size == 1) { "Stack should only have root left" }
return stack.first()
}
operator fun List<Any>.compareTo(other: List<Any>): Int {
for (leftIdx in this.indices) {
val firstValue = this[leftIdx]
if (leftIdx < other.size) {
val secondValue = other[leftIdx]
when {
firstValue is Int && secondValue is Int -> {
if (firstValue != secondValue) return firstValue.compareTo(secondValue)
}
else -> {
val firstValueList = if (firstValue is Int) listOf(firstValue) else firstValue as List<Any>
val secondValueList = if (secondValue is Int) listOf(secondValue) else secondValue as List<Any>
if (firstValueList != secondValueList) {
return firstValueList.compareTo(secondValueList)
}
}
}
} else {
return 1
}
}
return -1
}
fun part1(input: List<String>): Int {
val pairs = input.chunked(Day13.PACKET_COMBOS_NR_OF_LINES).map { it[0].parse() to it[1].parse() }
val compareResults = pairs.map { it.first.compareTo(it.second) }
return compareResults.foldIndexed(0) { index, acc, compareResult ->
if (compareResult < 0) acc + index + 1 else acc
}
}
fun part2(input: List<String>): Int {
val pairs = input.filter { it.isNotBlank() }.map { it.parse() } + Day13.DIVIDER_PACKETS
val sorted = pairs.sortedWith { o1, o2 -> o1!!.compareTo(o2!!) }
val result = Day13.DIVIDER_PACKETS.map {
sorted.indexOf(it) + 1
}.reduce(Int::times)
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == Day13.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day13.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
f684a4e78adf77514717d64b2a0e22e9bea56b98
| 3,563 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/Day02.kt
|
icoffiel
| 572,651,851 | false |
{"Kotlin": 29350}
|
fun main() {
fun winLoseOrDraw(playerOne: ITEM, playerTwo: ITEM) = when (playerOne) {
playerTwo -> OUTCOME.DRAW
playerTwo.beats() -> OUTCOME.WIN
else -> OUTCOME.LOSE
}
fun shouldPlay(playerOne: ITEM, expectedOutcome: OUTCOME): ITEM = when(expectedOutcome) {
OUTCOME.LOSE -> playerOne.beats()
OUTCOME.DRAW -> playerOne
OUTCOME.WIN -> playerOne.beatenBy()
}
fun part1(input: List<String>): Int {
val items = input
.map {
it.split(" ")
.map { letter -> ITEM.fromLetter(letter) }
}
val basePoints = items.sumOf { it[1].score }
val winPoints = items.sumOf { winLoseOrDraw(it[0], it[1]).score }
return basePoints + winPoints
}
fun part2(input: List<String>): Int {
val itemToOutcomes = input
.map {
val strings = it.split(" ")
ITEM.fromLetter(strings[0]) to OUTCOME.fromLetter(strings[1])
}
val winPoints = itemToOutcomes.sumOf { it.second.score }
val basePoints = itemToOutcomes.sumOf { shouldPlay(it.first, it.second).score }
return winPoints + basePoints
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
check(part1(input) == 11150)
println(part2(input))
check(part2(input) == 8295)
}
enum class ITEM(val letters: String, val score: Int) {
ROCK("AX", 1),
PAPER("BY", 2),
SCISSORS("CZ", 3);
companion object {
fun fromLetter(letter: String): ITEM = ITEM.values().first { letter in it.letters }
}
}
fun ITEM.beats(): ITEM = when(this) {
ITEM.ROCK -> ITEM.SCISSORS
ITEM.PAPER -> ITEM.ROCK
ITEM.SCISSORS -> ITEM.PAPER
}
fun ITEM.beatenBy(): ITEM = when(this) {
ITEM.ROCK -> ITEM.PAPER
ITEM.PAPER -> ITEM.SCISSORS
ITEM.SCISSORS -> ITEM.ROCK
}
enum class OUTCOME(val letters: String, val score: Int) {
LOSE("X", 0),
DRAW("Y", 3),
WIN("Z", 6);
companion object {
fun fromLetter(letter: String): OUTCOME = OUTCOME.values().first { letter in it.letters }
}
}
| 0 |
Kotlin
| 0 | 0 |
515f5681c385f22efab5c711dc983e24157fc84f
| 2,242 |
advent-of-code-2022
|
Apache License 2.0
|
src/y2015/Day14.kt
|
gaetjen
| 572,857,330 | false |
{"Kotlin": 325874, "Mermaid": 571}
|
package y2015
import util.readInput
import kotlin.math.min
data class Reindeer(
val speed: Int,
val endurance: Int,
val rest: Int
) {
fun distance(testTime: Int): Int {
val cycleLength = endurance + rest
val distancePerCycle = endurance * speed
val numCycles = testTime / cycleLength
val remaining = min(testTime % cycleLength, endurance)
return numCycles * distancePerCycle + remaining * speed
}
}
object Day14 {
private fun parse(input: List<String>): List<Reindeer> {
return input.map {
val words = it.split(' ')
Reindeer(
words[3].toInt(),
words[6].toInt(),
words[words.size - 2].toInt()
)
}
}
fun part1(input: List<String>, testTime: Int): Int {
val parsed = parse(input)
return parsed.maxOf {
it.distance(testTime)
}
}
fun part2(input: List<String>, realTime: Int): Int {
val parsed = parse(input)
val allDistances = (1..realTime).map { t ->
parsed.map { it.distance(t) }
}
val points = allDistances.fold(List(parsed.size) {0}) { acc, distances ->
val leadDistance = distances.max()
val points = distances.map { if (it == leadDistance) 1 else 0 }
acc.zip(points).map { it.first + it.second }
}
return points.max()
}
}
fun main() {
val testInput = """
Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.
Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds.
""".trimIndent().split("\n")
val testTime = 1000
println("------Tests------")
println(Day14.part1(testInput, testTime))
println(Day14.part2(testInput, testTime))
println("------Real------")
val input = readInput("resources/2015/day14")
val realTime = 2503
println(Day14.part1(input, realTime))
println(Day14.part2(input, realTime))
}
| 0 |
Kotlin
| 0 | 0 |
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
| 2,023 |
advent-of-code
|
Apache License 2.0
|
src/main/kotlin/g0801_0900/s0891_sum_of_subsequence_widths/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g0801_0900.s0891_sum_of_subsequence_widths
// #Hard #Array #Math #Sorting #2023_04_10_Time_481_ms_(100.00%)_Space_48.5_MB_(100.00%)
class Solution {
// 1-6 (number of elements in between 1 and 6) = (6-1-1) = 4
// length of sub seq 2 -> 4C0 3 -> 4C1 ; 4 -> 4c2 ; 5 -> 4C3 6 -> 4C4 4c0 + 4c1 + 4c2 + 4c3 +
// 4c4 1+4+6+4+1=16
// 1-5 3c0 + 3c1 + 3c2 + 3c3 = 8
// 1-4 2c0 + 2c1 2c2 = 4
// 1-3 1c0 + 1c1 = 2
// 1-2 1c0 = 1
/*
16+8+4+2+1(for 1 as min) 8+4+2+1(for 2 as min) 4+2+1(for 3 as min) 2+1(for 4 as min) 1(for 5 as min)
-1*nums[0]*31 + nums[1]*1 + nums[2]*2 + nums[3]*4 + nums[4]*8 + nums[5]*16
-1*nums[1]*15 + nums[2]*1 +nums[3]*2 + nums[4]*4 + nums[5]*8
-1*nums[2]*7 + nums[3]*1 + nums[4]*2 + nums[5]*4
-1*nums[3]*3 + nums[4]*1 + nums[5]*2
-1*nums[4]*1 + nums[5]*1
-nums[0]*31 + -nums[1]*15 - nums[2]*7 - nums[3]*3 - nums[4]*1
nums[1]*1 + nums[2]*3 + nums[3]*7 + nums[4]*15 + nums[5]*31
(-1)*nums[0]*(pow[6-1-0]-1) + (-1)*nums[1]*(pow[6-1-1]-1) + (-1)*nums[2]*(pow[6-1-2]-1)
... (-1)* nums[5]*(pow[6-1-5]-1)
+ nums[1]*(pow[1]-1) + nums[2]*(pow[2]-1) + .... + nums[5]*(pow[5]-1)
(-1)*A[i]*(pow[l-1-i]-1) + A[i]*(pow[i]-1)
*/
fun sumSubseqWidths(nums: IntArray): Int {
val mod = 1000000007
nums.sort()
val l = nums.size
val pow = LongArray(l)
pow[0] = 1
for (i in 1 until l) {
pow[i] = pow[i - 1] * 2 % mod
}
var res: Long = 0
for (i in 0 until l) {
res = (res + -1 * nums[i] * (pow[l - 1 - i] - 1) + nums[i] * (pow[i] - 1)) % mod
}
return res.toInt()
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 1,754 |
LeetCode-in-Kotlin
|
MIT License
|
src/main/kotlin/aoc2021/Day04.kt
|
davidsheldon
| 565,946,579 | false |
{"Kotlin": 161960}
|
package aoc2021
import aoc2022.blocksOfLines
import utils.InputUtils
class Day04(val calls: List<Int>, private val boards: List<Board>) {
fun makeCalls(): Sequence<Pair<Int, Board>> = calls.asSequence().flatMap { n ->
boards.filter { !it.isWinner() }.filter {
it.callNumber(n)
it.isWinner()
}.map { n to it }
}
fun callNumber(n: Int) {
boards.filter { !it.isWinner() }.forEach { it.callNumber(n) }
}
fun winningBoard() : Board? = boards.find { it.isWinner() }
class Board(private val cells: IntArray) {
private val marked = BooleanArray(5*5)
override fun toString(): String {
return cells.asSequence()
.chunked(5)
.map { it.joinToString(" ") { it.toString().padStart(2) }}
.joinToString("\n")
}
fun callNumber(n: Int) {
val index = cells.indexOf(n)
if (index >= 0) marked[index] = true
}
fun isWinner(): Boolean {
return markedRows().any { row -> row.all { it } } ||
markedCols().any {col -> col.all { it } }
}
fun sumOfUnmarkedCells(): Int = cells.filterIndexed { index, _ -> !marked[index] }.sum()
private fun markedRows() = marked.asSequence().chunked(5)
private fun markedCols() = marked.indices
.groupBy({it % 5}, {marked[it]}).values.toList()
}
}
fun main() {
val testInput = """7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
22 13 17 11 0
8 2 23 4 24
21 9 14 16 7
6 10 3 18 5
1 12 20 15 19
3 15 0 2 22
9 18 13 17 5
19 8 7 25 23
20 11 10 24 4
14 21 16 12 6
14 21 17 24 4
10 16 15 9 19
18 8 23 26 20
22 11 13 6 5
2 0 12 3 7""".split("\n")
fun parseBoard(input: List<String>): Day04.Board {
val board = input
.flatMap {
it.trim().split("\\s+".toRegex()).map(String::toInt)
}
.toIntArray()
return Day04.Board(board)
}
fun parse(input: List<String>): Day04 {
val calls = input[0].split(",").map { it.toInt() }
val boards = blocksOfLines(input.drop(2))
.map(::parseBoard).toList()
return Day04(calls, boards)
}
fun part1(input: List<String>): Int {
val state = parse(input)
val (call, board) = state.makeCalls().first()
return call * board.sumOfUnmarkedCells()
}
fun part2(input: List<String>): Int {
val state = parse(input)
val (call, board) = state.makeCalls().last()
return call * board.sumOfUnmarkedCells()
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 4512)
val puzzleInput = InputUtils.downloadAndGetLines(2021, 4)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
5abc9e479bed21ae58c093c8efbe4d343eee7714
| 2,986 |
aoc-2022-kotlin
|
Apache License 2.0
|
2k23/aoc2k23/src/main/kotlin/21.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 d21
import input.read
import java.math.BigInteger
fun main() {
println("Part 1: ${part1(read("21.txt"))}")
println("Part 2: ${part2(read("21.txt"))}")
}
fun part1(input: List<String>): Int = Maze(input).discover()
fun part2(input: List<String>): BigInteger {
val goal = 26501365
val maze = Maze(input)
val distToEdge = maze.size / 2
val n = ((goal - distToEdge) / maze.size).toBigInteger()
val results = mutableListOf<BigInteger>()
var visited = mutableSetOf(maze.start)
var count = 1
while (true) {
val nextVisited = mutableSetOf<Maze.Point>()
visited.forEach { point ->
nextVisited.addAll(point.neighbours().filter { neighbour ->
val target = Maze.Point(modulo(neighbour.x, maze.size), modulo(neighbour.y, maze.size))
maze.get(target) == Maze.Tile.Garden
})
}
visited = nextVisited
if (count == distToEdge + maze.size * results.size) {
results.add(visited.size.toBigInteger())
if (results.size == 3) {
// Lagrange's interpolation shit
val a = (results[2] - (BigInteger("2") * results[1]) + results[0]) / BigInteger("2")
val b = results[1] - results[0] - a
val c = results[0]
return (a * (n.pow(2))) + (b * n) + c
}
}
count++
}
}
fun modulo(dividend: Int, divisor: Int): Int = ((dividend % divisor) + divisor) % divisor
class Maze(input: List<String>) {
enum class Tile {
Garden,
Rock;
}
data class Point(val x: Int, val y: Int) {
fun neighbours(): List<Point> = listOf(
Point(x - 1, y),
Point(x + 1, y),
Point(x, y - 1),
Point(x, y + 1)
)
}
val map =
input.map { line ->
line.map { ch ->
when (ch) {
'#' -> Tile.Rock
'.' -> Tile.Garden
'S' -> Tile.Garden
else -> throw Exception("Unknown char $ch")
}
}
}
val start = Point(input.first().length / 2, input.size / 2)
val size = map.size
fun get(point: Point): Tile = map[point.y][point.x]
private fun inBound(point: Point): Boolean =
point.x >= 0 && point.y >= 0 && point.y < map.size && point.x < map[point.y].size
fun discover(): Int =
(1..64).fold(mutableSetOf(start)) { acc, _ ->
acc.fold(mutableSetOf()) { next, point ->
next.addAll(point.neighbours()
.filter { inBound(it) }
.filter { get(it) == Tile.Garden })
next
}
}.size
}
| 0 |
Rust
| 0 | 3 |
cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5
| 2,776 |
aoc
|
The Unlicense
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.