path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day03.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | private fun rucksacks(): List<Pair<String, String>> {
return readInput("Day03").map { Pair(it.substring(0, it.length / 2), it.substring(it.length / 2)) }
}
private fun rucksackGroups(): List<List<String>> {
return readInput("Day03").chunked(3)
}
private fun part1(rucksacks: List<Pair<String, String>>): Int {
return rucksacks.sumOf {
val common = it.first.find { c -> it.second.contains(c) }!!
score(common)
}
}
private fun part2(rucksacks: List<List<String>>): Int {
return rucksacks.sumOf {
val common = it[0].find { c -> it[1].contains(c) && it[2].contains(c) }!!
score(common)
}
}
private fun score(c: Char): Int = if (Character.isUpperCase(c)) (c - 'A' + 27) else (c - 'a' + 1)
fun main() {
println(part1(rucksacks()))
println(part2(rucksackGroups()))
}
| 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 829 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | MarkRunWu | 573,656,261 | false | {"Kotlin": 25971} | import java.lang.Math.abs
import java.util.Stack
fun main() {
fun parseStacks(input: List<String>): List<Stack<String>> {
val stackStrings = input.joinToString("\n") { it }.split(
"\n\n"
)[0].split("\n")
val labelLine = stackStrings.last().split(" ")
val stacks = labelLine.map {
Stack<String>()
}
val stackSize = stacks.size
val stackValues = stackStrings.subList(0, stackStrings.size - 1).reversed()
.map {
val items = arrayListOf<String>()
for (i in 0 until stackSize) {
if (i * 4 + 3 <= it.length) {
items.add(it.slice(i * 4 until i * 4 + 3).trim())
} else {
items.add("")
}
}
items
}
for (values in stackValues) {
for (i in 0 until stackSize) {
if (values[i].isEmpty()) {
continue
}
stacks[i].push(values[i])
}
}
return stacks
}
data class Movement(val steps: Int, val fromIndex: Int, val toIndex: Int)
fun parseMovementList(commands: List<String>): List<Movement> {
val pattern = Regex("^move (\\d+) from (\\d+) to (\\d+)")
return commands.map {
pattern.findAll(it)
}.map {
Movement(
it.first().groups[1]!!.value.toInt(),
it.first().groups[2]!!.value.toInt() - 1,
it.first().groups[3]!!.value.toInt() - 1
)
}
}
fun part1(input: List<String>): String {
val stacks = parseStacks(input)
val movementList = parseMovementList(input.joinToString("\n") { it }.split("\n\n").last().split("\n"))
movementList.forEach {
for (i in 0 until it.steps) {
stacks[it.toIndex].push(stacks[it.fromIndex].pop())
}
}
return stacks.map {
it.last()
}.joinToString("") { it }.replace("[", "").replace("]", "")
}
fun part2(input: List<String>): String {
val stacks = parseStacks(input)
val movementList = parseMovementList(input.joinToString("\n") { it }.split("\n\n").last().split("\n"))
val tmpStack = Stack<String>()
movementList.forEach {
tmpStack.clear()
for (i in 0 until it.steps) {
tmpStack.push(stacks[it.fromIndex].pop())
}
for (i in 0 until it.steps) {
stacks[it.toIndex].push(tmpStack.pop())
}
}
return stacks.map {
it.last()
}.joinToString("") { it }.replace("[", "").replace("]", "")
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ced885dcd6b32e8d3c89a646dbdcf50b5665ba65 | 2,883 | AOC-2022 | Apache License 2.0 |
src/Day04.kt | pejema | 576,456,995 | false | {"Kotlin": 7994} | import kotlin.streams.toList
fun main() {
// Example of full range inside other: 1-5,2-4
fun getRanges(rangesPair: List<String>) : Int {
val elf1 = rangesPair[0].substringBefore("-").toInt() .. rangesPair[0].substringAfter("-").toInt()
val elf2 = rangesPair[1].substringBefore("-").toInt() .. rangesPair[1].substringAfter("-").toInt()
return if (elf1.intersect(elf2).size == elf1.toList().size || elf2.intersect(elf1).size == elf2.toList().size)
1 else 0
}
// Example of overlapped ranges: 2-6,4-8
fun getOverlappedRanges(rangesPair: List<String>) : Int {
val elf1 = rangesPair[0].substringBefore("-").toInt() .. rangesPair[0].substringAfter("-").toInt()
val elf2 = rangesPair[1].substringBefore("-").toInt() .. rangesPair[1].substringAfter("-").toInt()
return if (elf1.intersect(elf2).isEmpty()) 0 else 1
}
fun part1(input: List<String>): Int {
return input.stream()
.map { line -> getRanges(line.split(",")) }
.toList().sum()
}
fun part2(input: List<String>): Int {
return input.stream()
.map { line -> getOverlappedRanges(line.split(",")) }
.toList().sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | b2a06318f0fcf5c6067058755a44e5567e345e0c | 1,523 | advent-of-code | Apache License 2.0 |
src/day12/Day12.kt | ivanovmeya | 573,150,306 | false | {"Kotlin": 43768} | package day12
import readInput
fun main() {
data class Point(val x: Int, val y: Int, var steps: Int = 0) {
override fun toString(): String {
return "[$x][$y]"
}
}
val directions = listOf(
Pair(0, 1), // right
Pair(1, 0), // down
Pair(0, -1), // left
Pair(-1, 0) // up
)
fun List<String>.toMatrix(): Array<CharArray> {
return Array(this.size) { row ->
this[row].toCharArray()
}
}
fun Array<CharArray>.findStartAndDestination(): Pair<Point, Point> {
var start = Point(-1, -1)
var destination = Point(-1, -1)
this.forEachIndexed { row, chars ->
val startColumn = chars.indexOf('S')
if (startColumn != -1) {
start = Point(row, startColumn)
}
val destColumn = chars.indexOf('E')
if (destColumn != -1) {
destination = Point(row, destColumn)
}
}
return start to destination
}
fun Array<CharArray>.findAllA(): List<Point> {
val res = mutableListOf<Point>()
this.forEachIndexed { row, chars ->
val startColumn = chars.indexOf('S')
val aColumn = chars.indexOf('a')
if (startColumn != -1) {
res.add(Point(row, startColumn))
}
if (aColumn != -1) {
res.add(Point(row, aColumn))
}
}
return res
}
fun Array<CharArray>.isValid(from: Point, to: Point): Boolean {
//destination could be at most one higher
//Start S has level 'a'
//End E has level 'z'
val fromChar = this[from.x][from.y]
val toChar = this[to.x][to.y]
return when {
fromChar == 'S' -> true
toChar == 'E' -> fromChar >= 'z' - 1
else -> fromChar >= toChar - 1
}
}
fun shortestPath(matrix: Array<CharArray>, start: Point, dest: Point): Int {
//Using BFS to calc all path costs
var shortestPath = -1
val isVisited = Array(matrix.size) {
BooleanArray(matrix[0].size) { false }
}
val queue = ArrayDeque<Point>().apply {
add(start)
}
while (queue.isNotEmpty()) {
val currentPoint = queue.removeFirst()
if (isVisited[currentPoint.x][currentPoint.y]) continue
isVisited[currentPoint.x][currentPoint.y] = true
if (currentPoint.x == dest.x && currentPoint.y == dest.y) {
if (shortestPath == -1 || currentPoint.steps < shortestPath) {
shortestPath = currentPoint.steps
}
continue
}
for (direction in directions) {
val x = currentPoint.x + direction.first
val y = currentPoint.y + direction.second
if (x >= 0 && y >= 0 && x < matrix.size && y < matrix[0].size) {
if (!isVisited[x][y] && matrix.isValid(currentPoint, Point(x, y))) {
queue.addLast(Point(x, y, currentPoint.steps + 1))
}
}
}
}
return shortestPath
}
fun Array<CharArray>.printGrid() {
this.forEach {
println(it.joinToString(""))
}
}
fun part1(input: List<String>): Int {
val matrix = input.toMatrix()
val (start, dest) = matrix.findStartAndDestination()
return shortestPath(matrix, start, dest)
}
fun part2(input: List<String>): Int {
val matrix = input.toMatrix()
val (_, dest) = matrix.findStartAndDestination()
val allAStarts = matrix.findAllA()
return allAStarts.minOf {
shortestPath(matrix, it, dest)
}
}
val testInput = readInput("day12/input_test")
val test1Result = part1(testInput)
val test2Result = part2(testInput)
println(test1Result)
println(test2Result)
check(test1Result == 31) { "Part ONE failed" }
check(test2Result == 29) { "Part TWO failed" }
val input = readInput("day12/input")
val part1 = part1(input)
val part2 = part2(input)
check(part1 == 472)
check(part2 == 465)
println(part1)
println(part2)
} | 0 | Kotlin | 0 | 0 | 7530367fb453f012249f1dc37869f950bda018e0 | 4,328 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | JIghtuse | 572,807,913 | false | {"Kotlin": 46764} | fun main() {
fun isVisibleTree(grid: Array<IntArray>, row: Int, col: Int): Boolean {
val treeHeight = grid[row][col]
return (0 until row).all { grid[it][col] < treeHeight }
|| (row + 1..grid.lastIndex).all { grid[it][col] < treeHeight }
|| (0 until col).all { grid[row][it] < treeHeight }
|| (col + 1..grid.first().lastIndex).all { grid[row][it] < treeHeight }
}
fun countInteriorVisibleTrees(grid: Array<IntArray>): Int {
val rows = 1 until grid.lastIndex
val cols = 1 until grid.first().lastIndex
var visibleTrees = 0
for (row in rows) {
for (col in cols) {
if (isVisibleTree(grid, row, col)) {
visibleTrees += 1
}
}
}
return visibleTrees
}
fun countVisibleTrees(grid: Array<IntArray>): Int {
val edge = 2 * (grid.size + grid.first().size - 2)
return edge + countInteriorVisibleTrees(grid)
}
fun part1(grid: Array<IntArray>): Int {
return countVisibleTrees(grid)
}
fun scenicScore(grid: Array<IntArray>, row: Int, col: Int): Int {
val treeHeight = grid[row][col]
fun colMax(range: IntProgression): Int {
val totalLength = range.asIterable().count { true }
val scenePartCount = range.takeWhile {
grid[it][col] < treeHeight
}.count()
return scenePartCount + if (scenePartCount == totalLength) {
0
} else {
1
}
}
fun rowMax(range: IntProgression): Int {
val totalLength = range.asIterable().count { true }
val scenePartCount = range.takeWhile {
grid[row][it] < treeHeight
}.count()
return scenePartCount + if (scenePartCount == totalLength) {
0
} else {
1
}
}
val up = colMax((0 until row).reversed())
val down = colMax(row + 1..grid.lastIndex)
val left = rowMax((0 until col).reversed())
val right = rowMax(col + 1..grid.first().lastIndex)
return left * right * up * down
}
fun highestScenicScore(grid: Array<IntArray>): Int {
var maxScore = scenicScore(grid, 1, 1)
for (row in 1 until grid.lastIndex) {
for (col in 1 until grid.first().lastIndex) {
val score = scenicScore(grid, row, col)
maxScore = maxOf(maxScore, score)
}
}
return maxScore
}
fun part2(grid: Array<IntArray>): Int {
return highestScenicScore(grid)
}
// test if implementation meets criteria from the description, like:
val testInput = read2dArray("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = read2dArray("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 8f33c74e14f30d476267ab3b046b5788a91c642b | 2,977 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2021/Day21.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import modulo
import readInput
import withEachOf
import kotlin.math.max
private data class Player(var position: Int, var score: Int = 0) {
/**
* Moves the player on the game board
*
* @param distance the distance by which to advance the player
* @return the player itself to chain commands
*/
fun move(distance: Int): Player {
position = (position + distance.modulo(10)).modulo(10)
score += position
return this
}
}
private data class DeterministicDice(private var rollCount: Int = 0) {
private var diceValue = 0
val rolls: Int
get() = rollCount
private fun throwDice(): Int {
rollCount++
diceValue = (diceValue + 1).modulo(100)
return diceValue
}
fun throwDice(times: Int): Int {
var sum = 0
repeat(times) {
sum += throwDice()
}
return sum
}
}
private fun part1(input: List<String>): Int {
val dice = DeterministicDice()
val player1 = Player(input[0].substring("aoc2021.Player 1 starting position: ".length).toInt())
val player2 = Player(input[1].substring("aoc2021.Player 2 starting position: ".length).toInt())
while (true) {
var diceSum = dice.throwDice(3)
player1.move(diceSum)
if (player1.score >= 1000)
return dice.rolls * player2.score
diceSum = dice.throwDice(3)
player2.move(diceSum)
if (player2.score >= 1000)
return dice.rolls * player1.score
}
}
private class DiracGame {
var player1WinCount = 0L
private set
var player2WinCount = 0L
private set
/**
* A map of possible results and their frequency when throwing a 3-sided dirac dice 3 times
*/
private val diracDiceThrows = sequenceOf(1, 2, 3).withEachOf(sequenceOf(1, 2, 3)).withEachOf(sequenceOf(1, 2, 3))
.map { it.first.first + it.first.second + it.second }.groupBy { it }.mapValues { it.value.size }
fun play(player1: Player, player2: Player, multiplier: Long = 1L) {
diracDiceThrows.forEach { (distance, frequency) ->
val p1 = player1.copy().move(distance)
if (p1.score >= 21) {
player1WinCount += (multiplier * frequency)
} else {
diracDiceThrows.forEach { (distance2, frequency2) ->
val p2 = player2.copy().move(distance2)
if (p2.score >= 21) {
player2WinCount += (multiplier * frequency2)
} else {
play(p1, p2, multiplier * frequency * frequency2)
}
}
}
}
}
}
private fun part2(input: List<String>): Long {
val player1 = Player(input[0].substring("aoc2021.Player 1 starting position: ".length).toInt())
val player2 = Player(input[1].substring("aoc2021.Player 2 starting position: ".length).toInt())
val game = DiracGame()
game.play(player1, player2)
return max(game.player1WinCount, game.player2WinCount)
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day21_test")
check(part1(testInput) == 739785)
check(part2(testInput) == 444356092776315L)
val input = readInput("Day21")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,389 | adventOfCode | Apache License 2.0 |
src/Day08.kt | arnoutvw | 572,860,930 | false | {"Kotlin": 33036} |
fun main() {
fun isGreaterThanAlPrevious(tree: Char, index: Int, line: String): Boolean {
return line.subSequence(0, index).all { it.code < tree.code }
}
fun checkLine(line: String, checked: Array<Array<Boolean>>, lineIndex: Int, columnMode: Boolean, reversed : Boolean) {
for ((index, tree) in line.subSequence(1, line.length - 1).withIndex()) {
if (isGreaterThanAlPrevious(tree, index + 1, line)) {
if (columnMode) {
if(reversed) {
checked[checked.size - 1 - index][lineIndex] = true
} else {
checked[index][lineIndex] = true
}
} else {
if(reversed) {
checked[lineIndex][checked[lineIndex].size - 1 - index] = true
} else {
checked[lineIndex][index] = true
}
}
}
}
}
fun part1(input: List<String>): Int {
val checked = Array(input.get(0).length - 2) {Array(input.size - 2) { false } }
var visible = 0
visible += input.size * 2
visible += (input.get(0).length * 2) - 4
for((index, line) in input.subList(1, input.size - 1).withIndex()) {
checkLine(line, checked, index, false, false)
checkLine(line.reversed(), checked, index, false, true)
}
val rotated = Array(input.get(0).length) {Array(input.size) { Char(0) } }
for((lineIndex, line) in input.withIndex()) {
for ((index, tree) in line.withIndex()) {
rotated[index][lineIndex] = tree
}
}
for((index, column) in rotated.sliceArray(1 until rotated.size - 1).withIndex()) {
val line = column.joinToString("")
checkLine(line, checked, index, true, false)
checkLine(line.reversed(), checked, index, true, true)
}
return visible + checked.sumOf { it -> it.count { it } }
}
fun part2(input: List<String>): Int {
var senic = 0;
for((index, line) in input.withIndex()) {
for((i2, tree) in line.withIndex()) {
var countTop = 0
for(j in (0 until index).reversed() ) {
countTop++
if(input[j][i2].code >= tree.code) {
break
}
}
var countLeft = 0
for(j in (0 until i2).reversed() ) {
countLeft++
if(line[j].code >= tree.code) {
break
}
}
var countRight = 0
for(j in i2 + 1 until line.length) {
countRight++
if(line[j].code >= tree.code) {
break
}
}
var countBottom = 0
for(j in index + 1 until input.size) {
countBottom++
if (input[j][i2].code >= tree.code){
break
}
}
val multi = countTop * countLeft * countBottom * countRight
if(multi > senic) {
senic = multi
}
}
}
return senic
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
println("Test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 21)
check(part2(testInput) == 8)
println("Waarde")
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4 | 3,805 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day05.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | private fun input(): Stacks {
val lines = readInput("Day05")
val stacksInput = lines.takeWhile { it.isNotEmpty() }
val stacksCount = (stacksInput.last().length + 2) / 4
val stacks = List(stacksCount) { ArrayDeque<Char>() }
stacksInput.forEach {
for (i in 0 until stacksCount) {
val charInd = 4 * i + 2
if (charInd >= it.length) continue
val curChar = it[4 * i + 1]
if (curChar.isUpperCase()) {
stacks[i].addFirst(curChar)
}
}
}
val ops = lines.subList(stacksInput.size + 1, lines.size).map {
val split = it.split(" ")
OP(split[1].toInt(), split[3].toInt() - 1, split[5].toInt() - 1)
}
return Stacks(stacks, ops)
}
private fun part1(input: Stacks): String {
val stacks = input.stacks
input.ops.forEach { op ->
repeat(op.count) {
stacks[op.to].add(stacks[op.from].removeLast())
}
}
return stacks.map { it.last() }.joinToString(separator = "")
}
private fun part2(input: Stacks): String {
val stacks = input.stacks
input.ops.forEach { op ->
val tmp = mutableListOf<Char>()
repeat(op.count) {
tmp.add(stacks[op.from].removeLast())
}
tmp.reversed().forEach { stacks[op.to].add(it) }
}
return stacks.map { it.last() }.joinToString(separator = "")
}
fun main() {
println(part1(input()))
println(part2(input()))
}
data class Stacks(val stacks: List<ArrayDeque<Char>>, val ops: List<OP>)
data class OP(val count: Int, val from: Int, val to: Int)
| 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 1,598 | advent-of-code-2022 | Apache License 2.0 |
src/day11/day11.kt | bienenjakob | 573,125,960 | false | {"Kotlin": 53763} | package day11
import inputTextOfDay
import testTextOfDay
import kotlin.math.floor
fun part1(input: String): Long {
return monkeyBusiness(input, 20, ::reduceWorryLevels)
}
fun part2(input: String): Long {
return monkeyBusiness(input, 10000, ::manageWorryLevels)
}
fun monkeyBusiness(input: String, rounds: Int, managedWorries: (Long, Long) -> Long): Long {
val monkeys = parseMonkeys(input)
val monkeyItems = monkeys.map { monkey -> monkey.first().split(", ").map { it.toLong() }.toMutableList() }
val monkeyInspections = MutableList(8) { 0L }
val monkeyDivisor = monkeys.map{ monkey -> monkey[2].toLong() }.reduce { a, b -> a * b }
repeat(rounds) {
for (monkey in monkeys.indices) {
monkeyItems[monkey].forEach { worryLevel ->
monkeyInspections[monkey] = monkeyInspections[monkey] + 1L
val (_, operation, tests, testTrue, testFalse) = monkeys[monkey]
val (operator, operand) = operation.split(" ")
val worryLevelDuringInspection = when (operator) {
"*" -> worryLevel * when (operand) {
"old" -> worryLevel
else -> operand.toLong()
}
else -> worryLevel + when (operand) {
"old" -> worryLevel
else -> operand.toLong()
}
}
val worryLevelAfterInspection = managedWorries(worryLevelDuringInspection, monkeyDivisor)
when (worryLevelAfterInspection % tests.toInt() == 0L) {
true -> {
monkeyItems[testTrue.toInt()].add(worryLevelAfterInspection)
}
false -> {
monkeyItems[testFalse.toInt()].add(worryLevelAfterInspection)
}
}
}
monkeyItems[monkey].clear()
}
}
return monkeyInspections.sortedDescending().take(2).let { (a,b) -> a * b }
}
private fun reduceWorryLevels(worryLevel: Long, monkeyDivisor: Long) =
floor(worryLevel.toDouble() / 3.0).toLong()
private fun manageWorryLevels(worryLevel: Long, monkeyDivisor: Long) =
worryLevel % monkeyDivisor
private fun parseMonkeys(input: String) = input.lines().chunked(7) { monkey ->
monkey.drop(1).mapNotNull {
when {
it.startsWith(" Starting items: ") -> it.substringAfter(" Starting items: ")
it.startsWith(" Operation: new = old ") -> it.substringAfter(" Operation: new = old ")
it.startsWith(" Test: divisible by ") -> it.substringAfter(" Test: divisible by ")
it.startsWith(" If true: throw to monkey ") -> it.substringAfter(" If true: throw to monkey ")
it.startsWith(" If false: throw to monkey ") -> it.substringAfter(" If false: throw to monkey ")
else -> null
}
}
}
fun main() {
val day = 11
val test = testTextOfDay(day)
val input = inputTextOfDay(day)
println(part1(test))
println(part1(input))
check(part1(test) == 10605L)
check(part1(input) == 57838L)
println(part2(test))
println(part2(input))
check(part2(test) == 2713310158L)
check(part2(input) == 15050382231L)
}
| 0 | Kotlin | 0 | 0 | 6ff34edab6f7b4b0630fb2760120725bed725daa | 3,323 | aoc-2022-in-kotlin | Apache License 2.0 |
gcj/y2020/round1b/b.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2020.round1b
import kotlin.math.abs
private const val SIZE = 1_000_000_000
private fun solve() {
val grid = listOf(-SIZE / 3, SIZE / 3).cartesianSquare()
val (xInit, yInit) = grid.first { (x, y) -> hit(x, y) }
val (xLeft, _) = furthestInside(xInit, yInit, -1, 0)
val (xRight, _) = furthestInside(xInit, yInit, 1, 0)
val xCenter = (xLeft + xRight) / 2
val (_, yUp) = furthestInside(xCenter, yInit, 0, 1)
val (_, yDown) = furthestInside(xCenter, yInit, 0, -1)
hit(xCenter, (yUp + yDown) / 2)
}
private fun furthestInside(x: Int, y: Int, dx: Int, dy: Int): Pair<Int, Int> {
val r = (0..2 * SIZE + 1).binarySearch { !hit(x + dx * it, y + dy * it) } - 1
return x + dx * r to y + dy * r
}
private fun hit(x: Int, y: Int): Boolean {
if (maxOf(abs(x), abs(y)) > SIZE) return false
println("$x $y")
return "HIT" == readLn().also { if (it == "CENTER") throw Found() }
}
private class Found : Exception()
fun main() = repeat(readLn().split(" ")[0].toInt()) { try { solve() } catch (_: Found) {} }
private fun IntRange.binarySearch(predicate: (Int) -> Boolean): Int {
var (low, high) = this.first to this.last
while (low + 1 < high) (low + (high - low) / 2).also { if (predicate(it)) high = it else low = it }
return high
}
private fun readLn() = readLine()!!
private fun <T> Iterable<T>.cartesianSquare() = flatMap { x -> map { y -> x to y } }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,371 | competitions | The Unlicense |
src/main/kotlin/year_2022/Day03.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package year_2022
import utils.readInput
fun main() {
fun proccessInput(input : String) : Pair<String, String>{
val middle = input.length / 2
val first = input.substring(0, middle)
val second = input.substring(middle, input.length)
return (first to second)
}
fun part1(input: List<String>): Int {
return input.sumOf {entry ->
val (firstHalf, secondHalf) = proccessInput(entry)
var repeatedPosition = -1
for(letterIndex in firstHalf.indices){
val letter = firstHalf[letterIndex]
for(letterIndexSecond in secondHalf.indices){
val letterSecond = secondHalf[letterIndexSecond]
if(letter == letterSecond && repeatedPosition == -1){
repeatedPosition = letterIndex
}
}
}
var letterValue = entry[repeatedPosition] - 'a' + 1
if(letterValue < 0) letterValue += 'A'.code - 7
letterValue
}
}
fun calculateGroupLetter(group: List<String>): Int {
var repeatedPosition = -1
if(group.isEmpty()) return 0
for(letterIndex in group[0].indices){
val letter = group[0][letterIndex]
for(letterIndexSecond in group[1].indices){
val letterSecond = group[1][letterIndexSecond]
for(letterIndexThird in group[2].indices) {
val letterThird = group[2][letterIndexThird]
if(letter == letterSecond && letter == letterThird){
repeatedPosition = letterIndex
var letterValue = group[0][repeatedPosition] - 'a' + 1
if(letterValue < 0) letterValue += 'A'.code - 7
return letterValue
}
}
}
}
return 0
}
fun part2(input: List<String>): Int {
var sum = 0
val group = arrayListOf<String>()
input.forEachIndexed{ _, element ->
group.add(element)
if(group.size == 3) {
sum += calculateGroupLetter(group)
group.clear()
}
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 2,566 | advent-of-code | Apache License 2.0 |
y2023/src/main/kotlin/adventofcode/y2023/Day22.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec2
import adventofcode.util.vector.Vec3
fun main() {
Day22.solve()
}
object Day22 : AdventSolution(2023, 22, "Sand Slabs") {
override fun solvePartOne(input: String): Any {
val slabsInAir = parse(input)
val columns: Map<Vec2, List<Int>> = buildColumns(slabsInAir)
val nextAbove = nextSlabsInDirection(slabsInAir, columns, 1)
val nextBelow = nextSlabsInDirection(slabsInAir, columns, -1)
val slabs = turnOnGravity(slabsInAir, nextBelow)
val touchingBelow = nextBelow.mapIndexed { iHigh, lower ->
lower.filter { iLow -> slabs[iHigh].lowest() - 1 == slabs[iLow].highest() }
}
val touchingAbove = nextAbove.mapIndexed { iLow, higher ->
higher.filter { iHigh -> slabs[iHigh].lowest() - 1 == slabs[iLow].highest() }
}
return slabs.indices.count { removedIndex ->
touchingAbove[removedIndex].all { touchingBelow[it].size > 1 }
}
}
override fun solvePartTwo(input: String): Any {
val slabsInAir = parse(input)
val columns: Map<Vec2, List<Int>> = buildColumns(slabsInAir)
val nextAbove = nextSlabsInDirection(slabsInAir, columns, 1)
val nextBelow = nextSlabsInDirection(slabsInAir, columns, -1)
val slabs = turnOnGravity(slabsInAir, nextBelow)
val touchingBelow = nextBelow.mapIndexed { iHigh, lower ->
lower.filter { iLow -> slabs[iHigh].lowest() - 1 == slabs[iLow].highest() }
}
val touchingAbove = nextAbove.mapIndexed { iLow, higher ->
higher.filter { iHigh -> slabs[iHigh].lowest() - 1 == slabs[iLow].highest() }
}
fun disintegrate(index: Int): Int {
val removed = mutableSetOf(index)
val incomplete = mutableListOf(index)
while (incomplete.isNotEmpty()) {
val iRemoved = incomplete.removeLast()
val falling = touchingAbove[iRemoved]
.filter { it !in removed }
.filter { touchingBelow[it].all { sup-> sup in removed } }
incomplete += falling
removed += falling
}
return removed.size - 1
}
return slabs.indices.sumOf { disintegrate(it) }
}
private fun turnOnGravity(slabsInAir: List<Slab>, nextBelow: List<Set<Int>>): List<Slab> {
val slabs = slabsInAir.toMutableList()
val unmoved = slabs.indices.toMutableSet()
while (unmoved.isNotEmpty()) {
val canFall = unmoved.filter { nextBelow[it].none { it in unmoved } }
unmoved -= canFall
for (falling in canFall) {
val heightOfSlabsBelow = nextBelow[falling].maxOfOrNull { slabs[it].highest() } ?: 0
val currentHeight = slabs[falling].lowest()
val delta = Vec3(0, 0, currentHeight - heightOfSlabsBelow - 1)
slabs[falling] = slabs[falling].let { Slab(it.start - delta, it.end - delta) }
}
}
return slabs
}
private fun nextSlabsInDirection(slabs: List<Slab>, columns: Map<Vec2, List<Int>>, direction: Int) =
slabs.mapIndexed { index, slab ->
slab.cubes.map { c -> Vec2(c.x, c.y) }
.mapNotNull {
val stack = columns.getValue(it)
val above = stack.indexOf(index) + direction
stack.getOrNull(above)
}.toSet()
}
private fun buildColumns(slabsInAir: List<Slab>): Map<Vec2, List<Int>> = slabsInAir
.flatMapIndexed { i, s -> s.cubes.map { c -> Vec2(c.x, c.y) to i } }
.groupBy({ it.first }, { it.second })
.mapValues { (_, v) -> v.distinct().sortedBy { slabsInAir[it].lowest() } }
}
private fun parse(input: String) = input.lines()
.map {
it.split("~", ",")
.map { it.toInt() }.chunked(3) { (x, y, z) -> Vec3(x, y, z) }
}
.map { Slab(it[0], it[1]) }
private data class Slab(val start: Vec3, val end: Vec3) {
val cubes =
(end - start).sign.let { step -> generateSequence(start, step::plus).takeWhile { it != end } + end }.toSet()
fun lowest() = minOf(start.z, end.z)
fun highest() = maxOf(start.z, end.z)
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 4,369 | advent-of-code | MIT License |
year2023/src/cz/veleto/aoc/year2023/Day05.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2023
import cz.veleto.aoc.core.AocDay
import cz.veleto.aoc.core.fullyIn
import cz.veleto.aoc.core.intersect
import cz.veleto.aoc.core.shift
class Day05(config: Config) : AocDay(config) {
data class Problem(
val rawSeeds: List<Long>, // for part 1
val seedRanges: List<LongRange>, // for part 2
val maps: List<Map>,
) {
data class Map(
val name: String,
val ranges: List<Range>,
)
data class Range(
val source: LongRange,
val destination: LongRange,
) {
companion object {
val StartBound = Range(
source = Long.MIN_VALUE..Long.MIN_VALUE,
destination = LongRange.EMPTY,
)
val EndBound = Range(
source = Long.MAX_VALUE..Long.MAX_VALUE,
destination = LongRange.EMPTY,
)
}
}
}
override fun part1(): String {
val problem = input.parse()
val locations = problem.mapSeedsToLocations()
return locations.min().toString()
}
override fun part2(): String {
val problem = input.parse()
if (config.log) {
println("Init seeds")
problem.seedRanges.onEach { println("\t$it") }
}
val locationRanges = problem.mapSeedRangesToLocations()
return locationRanges.minOf { it.first }.toString()
}
private fun Sequence<String>.parse(): Problem {
val iterator = iterator()
val rawSeeds = iterator.next().drop(7).split(' ').map { it.toLong() }
val seedRanges = rawSeeds.chunked(2) { (start, length) -> start..<start + length }.sortedBy { it.first }
iterator.next()
val maps = buildList {
while (iterator.hasNext()) {
this += iterator.parseMap()
}
}
return Problem(
rawSeeds = rawSeeds,
seedRanges = seedRanges,
maps = maps,
)
}
private fun Iterator<String>.parseMap(): Problem.Map = Problem.Map(
name = next().split(' ').first(),
ranges = asSequence()
.takeWhile { it.isNotBlank() }
.map { line ->
val (destinationStart, sourceStart, length) = line.split(' ').map { it.toLong() }
Problem.Range(
source = sourceStart..<sourceStart + length,
destination = destinationStart..<destinationStart + length,
)
}
.toList()
.sortedBy { range -> range.source.first },
)
private fun Problem.mapSeedsToLocations(): List<Long> = maps.fold(rawSeeds) { seeds, map ->
seeds.map { seed ->
map.ranges
.firstOrNull { seed in it.source }
?.map(seed)
?: seed
}
}
private fun Problem.Range.map(seed: Long): Long =
destination.first + seed - source.first
private fun Problem.Range.map(seedRange: LongRange): LongRange {
if (seedRange.isEmpty()) return seedRange
require(seedRange.fullyIn(source))
val shift = destination.first - source.first
return seedRange.shift(shift)
}
private fun Problem.mapSeedRangesToLocations(): List<LongRange> = maps
.fold(seedRanges) { seedRanges, map ->
if (config.log) println("Map ${map.name}")
seedRanges
.also { if (config.log) println("\tMapped to (debug)") }
.flatMap { seedRange ->
val mapRanges = buildList {
add(Problem.Range.StartBound)
addAll(map.ranges)
add(Problem.Range.EndBound)
}
mapRanges
.windowed(2) { (mapRange, nextMapRange) ->
listOf(
mapRange.map(seedRange.intersect(mapRange.source)),
seedRange.intersect(mapRange.source.last + 1..<nextMapRange.source.first),
).also { if (config.log) println("\t\tSeeds $seedRange, map $mapRange, new seeds $it") }
}
.flatten()
}
.filterNot(LongRange::isEmpty)
.also { if (config.log) println("\tMapped to (simplified)") }
.onEach { if (config.log) println("\t\t$it") }
}
.toList()
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 4,581 | advent-of-pavel | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-19.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import kotlin.math.max
fun main() {
val input = readInputLines(2022, "19-input")
val testInput1 = readInputLines(2022, "19-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
return NotEnoughMinerals(input).solve()
}
private fun part2(input: List<String>): Int {
return NotEnoughMinerals(input).solve2()
}
private class NotEnoughMinerals(input: List<String>) {
private val regex = """Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""".toRegex()
private val blueprints = input.map {
val match = regex.matchEntire(it)!!
Blueprint(
match.groupValues[1].toInt(),
match.groupValues[2].toInt(),
match.groupValues[3].toInt(),
match.groupValues[4].toInt(),
match.groupValues[5].toInt(),
match.groupValues[6].toInt(),
match.groupValues[7].toInt(),
)
}
private data class Blueprint(
val id: Int,
val oreRobotOre: Int,
val clayRobotOre: Int,
val obsidianRobotOre: Int,
val obsidianRobotClay: Int,
val geodeRobotOre: Int,
val geodeRobotObsidian: Int
)
private data class State(
val time: Int,
val ore: Int = 0,
val clay: Int = 0,
val obsidian: Int = 0,
val geode: Int = 0,
val oreRobot: Int = 1,
val clayRobot: Int = 0,
val obsidianRobot: Int = 0,
val geodeRobot: Int = 0,
)
fun solve(): Int {
val geodes = blueprints.map {
val dfs = Dfs(24, it)
val quality = dfs.solve(State(24))
quality * it.id
}
return geodes.sum()
}
fun solve2(): Int {
val geodes = blueprints.take(3).map {
val dfs = Dfs(32, it)
val quality = dfs.solve(State(32))
quality
}
return geodes.reduce { acc, i -> acc * i }
}
private class Dfs(private val time: Int, private val blueprint: Blueprint) {
private val cache = mutableMapOf<State, Int>()
private var bestSoFar = 0
private val seq = (1..32).scan(0) { a, b -> a + b }
fun solve(state: State = State(time)): Int {
if (state in cache) {
return cache[state]!!
}
if (state.time == 0) {
cache[state] = state.geode
bestSoFar = bestSoFar.coerceAtLeast(state.geode)
return state.geode
}
var best = state.geodeRobot * state.time + state.geode
val potential = state.geode + seq[state.time] + state.time * state.geodeRobot
if (potential < bestSoFar) {
cache[state] = 0
return 0
}
best = buildGeodeRobot(state).coerceAtLeast(best)
best = buildObsidianRobot(state).coerceAtLeast(best)
best = buildClayRobot(state).coerceAtLeast(best)
best = buildOreRobot(state).coerceAtLeast(best)
cache[state] = best
return best
}
private fun buildGeodeRobot(state: State): Int {
if (state.oreRobot != 0 && state.obsidianRobot != 0) {
val t = geodeRobotTime(state)
if (t < state.time) {
return solve(
state = state.copy(
time = state.time - t,
ore = state.ore + state.oreRobot * t - blueprint.geodeRobotOre,
clay = state.clay + state.clayRobot * t,
obsidian = state.obsidian + state.obsidianRobot * t - blueprint.geodeRobotObsidian,
geode = state.geode + state.geodeRobot * t,
geodeRobot = state.geodeRobot + 1
)
)
}
}
return 0
}
private fun buildObsidianRobot(state: State): Int {
if (state.oreRobot != 0 && state.clayRobot != 0) {
val maxObsidianNeeded = blueprint.geodeRobotObsidian * state.time
val t = obsidianRobotTime(state)
if (t < state.time && state.obsidianRobot * state.time + state.obsidian < maxObsidianNeeded) {
return solve(
state = state.copy(
time = state.time - t,
ore = state.ore + state.oreRobot * t - blueprint.obsidianRobotOre,
clay = state.clay + state.clayRobot * t - blueprint.obsidianRobotClay,
obsidian = state.obsidian + state.obsidianRobot * t,
geode = state.geode + state.geodeRobot * t,
obsidianRobot = state.obsidianRobot + 1
)
)
}
}
return 0
}
private fun buildClayRobot(state: State): Int {
if (state.oreRobot != 0) {
val maxClayNeeded = blueprint.obsidianRobotClay * state.time
val t = if (blueprint.clayRobotOre > state.ore) {
((blueprint.clayRobotOre - state.ore - 1) / state.oreRobot) + 1
} else 0
if (t < state.time && state.clayRobot * state.time + state.clay < maxClayNeeded) {
return solve(
state = state.copy(
time = state.time - t - 1,
ore = state.ore + state.oreRobot * (t + 1) - blueprint.clayRobotOre,
clay = state.clay + state.clayRobot * (t + 1),
obsidian = state.obsidian + state.obsidianRobot * (t + 1),
geode = state.geode + state.geodeRobot * (t + 1),
clayRobot = state.clayRobot + 1
)
)
}
}
return 0
}
private fun buildOreRobot(state: State): Int {
if (state.oreRobot != 0) {
val maxOreNeeded = maxOf(
blueprint.oreRobotOre,
blueprint.clayRobotOre,
blueprint.obsidianRobotOre,
blueprint.geodeRobotOre
) * state.time
val t = if (blueprint.oreRobotOre > state.ore) {
((blueprint.oreRobotOre - state.ore - 1) / state.oreRobot) + 1
} else 0
if (t < state.time && state.oreRobot * state.time + state.ore < maxOreNeeded) {
return solve(
state = state.copy(
time = state.time - t - 1,
ore = state.ore + state.oreRobot * (t + 1) - blueprint.oreRobotOre,
clay = state.clay + state.clayRobot * (t + 1),
obsidian = state.obsidian + state.obsidianRobot * (t + 1),
geode = state.geode + state.geodeRobot * (t + 1),
oreRobot = state.oreRobot + 1
)
)
}
}
return 0
}
private fun geodeRobotTime(state: State): Int {
val timeToGetOre = if (blueprint.geodeRobotOre > state.ore) {
((blueprint.geodeRobotOre - state.ore - 1) / state.oreRobot) + 1
} else 0
val timeToGetObsidian = if (blueprint.geodeRobotObsidian > state.obsidian) {
((blueprint.geodeRobotObsidian - state.obsidian - 1) / state.obsidianRobot) + 1
} else 0
return max(timeToGetOre, timeToGetObsidian) + 1
}
private fun obsidianRobotTime(state: State): Int {
val timeToGetOre = if (blueprint.obsidianRobotOre > state.ore) {
((blueprint.obsidianRobotOre - state.ore - 1) / state.oreRobot) + 1
} else 0
val timeToGetClay = if (blueprint.obsidianRobotClay > state.clay) {
((blueprint.obsidianRobotClay - state.clay - 1) / state.clayRobot) + 1
} else {
0
}
return max(timeToGetOre, timeToGetClay) + 1
}
}
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 8,797 | advent-of-code | MIT License |
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day09/Day09.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2021.day09
import eu.janvdb.aocutil.kotlin.point2d.Point2D
import eu.janvdb.aocutil.kotlin.readNonSeparatedDigits
import java.util.*
private const val FILENAME = "input09.txt"
fun main() {
val cave = Cave.read()
val riskLevel = cave.lowPoints()
.map { cave.heightAt(it) + 1 }
.sum()
println(riskLevel)
val score2 = cave.bassins()
.map { it.size }
.sortedDescending()
.take(3)
.fold(1) { acc, it -> acc * it }
println(score2)
}
private const val MAX_HEIGHT = 9
data class Cave(val heights: List<List<Int>>) {
val width = heights[0].size
val height = heights.size
fun bassins(): Set<Set<Point2D>> {
fun expandToBassin(origin: Point2D): Set<Point2D> {
val bassin = mutableSetOf<Point2D>()
val toDo = LinkedList<Point2D>()
toDo.addFirst(origin)
while (!toDo.isEmpty()) {
val point = toDo.removeAt(0)
if (heightAt(point) != MAX_HEIGHT && !bassin.contains(point)) {
bassin.add(point)
toDo.addLast(point.left())
toDo.addLast(point.right())
toDo.addLast(point.up())
toDo.addLast(point.down())
}
}
return bassin
}
return lowPoints().map(::expandToBassin).toSet()
}
fun lowPoints() = points().filter(this::isLowPoint)
private fun points(): Sequence<Point2D> {
return (0..height).asSequence()
.flatMap { y -> (0..width).asSequence().map { x -> Point2D(x, y) } }
}
private fun isLowPoint(point: Point2D): Boolean {
val height = heightAt(point)
return height < heightAt(point.left()) && height < heightAt(point.right())
&& height < heightAt(point.up()) && height < heightAt(point.down())
}
fun heightAt(point: Point2D): Int {
if (point.x < 0 || point.x >= width || point.y < 0 || point.y >= height) return MAX_HEIGHT
return heights[point.y][point.x]
}
companion object {
fun read(): Cave {
val heights = readNonSeparatedDigits(2021, FILENAME)
return Cave(heights)
}
}
}
| 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 1,912 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/briarshore/aoc2022/day02/Puzzle.kt | steveswing | 579,243,154 | false | {"Kotlin": 47151} | package com.briarshore.aoc2022.day02
import println
import readInput
enum class Hand(val points: Int) {
Rock(1), Paper(2), Scissors(3)
}
enum class Outcome(val points: Int) {
Win(6), Draw(3), Lose(0)
}
interface IPoints {
fun points(): Int
}
data class Score(val hand: Hand, val outcome: Outcome) : IPoints {
override fun points(): Int = hand.points + outcome.points
}
data class Round(val moveScore: Score, val counterMoveScore: Score)
fun main() {
val moves: Map<String, Hand> = mapOf(Pair("A", Hand.Rock), Pair("B", Hand.Paper), Pair("C", Hand.Scissors))
val outcomes: Map<String, Outcome> = mapOf(Pair("X", Outcome.Lose), Pair("Y", Outcome.Draw), Pair("Z", Outcome.Win))
val testStrategy: List<Pair<Hand, Outcome>> = listOf(Pair("A", "Y"), Pair("B", "X"), Pair("C", "Z"))
.map { Pair(moves.getValue(it.first), outcomes.getValue(it.second)) }
check(part1(testStrategy) == 12)
val realInput = readInput("d2p1-input")
val realStrategy: List<Pair<Hand, Outcome>> = realInput.map { it.split(" ") }.map { Pair(moves.getValue(it.first()), outcomes.getValue(it.last())) }
val part1 = part1(realStrategy)
"part1 $part1".println()
}
fun part1(strategy: List<Pair<Hand, Outcome>>): Int {
return strategy.map { playRound(it.first, it.second) }.sumOf { it.second.points() }
}
fun playRound(move: Hand, riggedOutcome: Outcome): Pair<Score, Score> {
val round = rigOutcome(move, riggedOutcome)
return Pair(round.moveScore, round.counterMoveScore)
}
fun determineOutcome(move: Hand, counterMove: Hand): Round {
if (move == counterMove) {
return Round(Score(move, Outcome.Draw), Score(counterMove, Outcome.Draw))
} else if (move == Hand.Rock && counterMove == Hand.Scissors) {
return Round(Score(move, Outcome.Win), Score(counterMove, Outcome.Lose))
} else if (move == Hand.Paper && counterMove == Hand.Rock) {
return Round(Score(move, Outcome.Win), Score(counterMove, Outcome.Lose))
} else if (move == Hand.Scissors && counterMove == Hand.Paper) {
return Round(Score(move, Outcome.Win), Score(counterMove, Outcome.Lose))
} else if (move == Hand.Rock && counterMove == Hand.Paper) {
return Round(Score(move, Outcome.Lose), Score(counterMove, Outcome.Win))
} else if (move == Hand.Paper && counterMove == Hand.Scissors) {
return Round(Score(move, Outcome.Lose), Score(counterMove, Outcome.Win))
} else if (move == Hand.Scissors && counterMove == Hand.Rock) {
return Round(Score(move, Outcome.Lose), Score(counterMove, Outcome.Win))
}
throw Exception("Unreachable")
}
fun rigOutcome(move: Hand, riggedOutcome: Outcome): Round {
return when (riggedOutcome) {
Outcome.Draw -> Round(Score(move, riggedOutcome), Score(move, riggedOutcome))
Outcome.Lose -> Round(Score(move, Outcome.Win), Score(counter(move, riggedOutcome), riggedOutcome))
Outcome.Win -> Round(Score(move, Outcome.Lose), Score(counter(move, riggedOutcome), riggedOutcome))
}
}
fun counter(move: Hand, riggedOutcome: Outcome): Hand {
return when(riggedOutcome) {
Outcome.Draw -> move
Outcome.Lose ->
when(move) {
Hand.Paper -> Hand.Rock
Hand.Scissors -> Hand.Paper
Hand.Rock -> Hand.Scissors
}
Outcome.Win ->
when(move) {
Hand.Paper -> Hand.Scissors
Hand.Scissors -> Hand.Rock
Hand.Rock -> Hand.Paper
}
}
}
| 0 | Kotlin | 0 | 0 | a0d19d38dae3e0a24bb163f5f98a6a31caae6c05 | 3,536 | 2022-AoC-Kotlin | Apache License 2.0 |
src/Day07.kt | mzlnk | 573,124,510 | false | {"Kotlin": 14876} | fun main() {
fun evaluate(input: List<String>): Directory {
val root = Directory(name = "/")
var current: Directory = root
var lineIdx = 0
while (lineIdx < input.size) {
val line = input[lineIdx++]
val pattern = Regex("\\$ (cd|ls) ?(.+)?")
val (command, option) = pattern.find(line)!!.destructured
when (command) {
"cd" -> {
current = when (option) {
".." -> current.switchToParent()
"/" -> current.switchToRoot()
else -> current.switchToChild(option)
}
}
"ls" -> {
while (lineIdx < input.size && !input[lineIdx].startsWith("$")) {
val lsData = input[lineIdx].split(" ")
when (lsData[0]) {
"dir" -> current.directories[lsData[1]] =
Directory(root = root, parent = current, name = lsData[1])
else -> current.files.add(File(lsData[1], lsData[0].toInt()))
}
lineIdx++
}
}
}
}
return root
}
fun part1(input: List<String>): Int {
val root = evaluate(input)
return root.listDirectoriesWithSize()
.filter { it.second <= 100000 }
.sumOf { it.second }
}
fun part2(input: List<String>): Int {
val root = evaluate(input)
val totalSize = 70000000
val toRemove = 30000000 - (totalSize - root.size())
return root.listDirectoriesWithSize()
.map { it.second }
.filter { it >= toRemove }
.minOf { it }
}
// 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))
}
data class File(val name: String, val size: Int)
data class Directory(
val root: Directory? = null,
var parent: Directory? = null,
val name: String,
var files: MutableList<File> = mutableListOf(),
var directories: MutableMap<String, Directory> = mutableMapOf()
) {
private var size: Int? = null
fun switchToRoot(): Directory {
return root ?: this
}
fun switchToParent(): Directory {
return parent ?: this
}
fun switchToChild(name: String): Directory {
return directories[name]!!
}
fun listDirectoriesWithSize(): List<Pair<String, Int>> {
val children = directories.values.flatMap { it.listDirectoriesWithSize() }
val self = Pair(name, size())
return children + self
}
fun size(): Int {
this.size = this.size ?: calculateSize()
return this.size!!
}
private fun calculateSize(): Int {
val filesSize = files.sumOf { it.size }
val directoriesSize = directories.values.sumOf { it.size() }
return filesSize + directoriesSize
}
override fun toString(): String {
return "Directory(root=${root?.name}, parent=${parent?.name}, name=$name)"
}
}
| 0 | Kotlin | 0 | 0 | 3a8ec82e9a8b4640e33fdd801b1ef87a06fa5cd5 | 3,347 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/day11.kt | josergdev | 573,178,933 | false | {"Kotlin": 20792} | package days
import java.io.File
fun String.parseMonkeys() = this
.split("\n\n")
.map { it.split("\n").map { l -> l.trim() } }
.map {
Pair(
it[0].replace("Monkey ", "").replace(":", "").toLong(),
Triple(
it[1].replace("Starting items: ", "").split(",").map { item -> item.trim().toLong() },
it[2].replace("Operation: new = ", "").parseOp(),
Triple(
it[3].replace("Test: divisible by ", "").toLong(),
it[4].replace("If true: throw to monkey ", "").toLong(),
it[5].replace("If false: throw to monkey ", "").toLong())))
}
.map { (monkey, monkeyData) -> (monkey to (monkeyData.first to 0L)) to (monkey to (monkeyData.second to monkeyData.third)) }
.let { it.associate { p -> p.first } to it.associate { p -> p.second } }
fun String.parseOp() = when {
this == "old * old" -> { old: Long -> old * old }
this.contains("old +") -> this.replace("old + ", "").toLong().let { { old: Long -> old + it } }
else -> this.replace("old * ", "").toLong().let { { old: Long -> old * it } }
}
fun executeRound(
monkeyItems: Map<Long, Pair<List<Long>, Long>>,
monkeyBehaviour: Map<Long, Pair<(Long) -> Long, Triple<Long, Long, Long>>>,
worryReduction: (Long) -> Long
) =
monkeyItems.keys.fold(monkeyItems) { map, monkey -> monkeyInspect(map, monkeyBehaviour, worryReduction, monkey) }
fun monkeyInspect(
monkeyItems: Map<Long, Pair<List<Long>, Long>>,
monkeyBehaviour: Map<Long, Pair<(Long) -> Long, Triple<Long, Long, Long>>>,
worryReduction: (Long) -> Long,
monkey: Long
) =
monkeyItems[monkey]!!.first.fold(monkeyItems) { map , item -> inspectItem(map, monkeyBehaviour, worryReduction, monkey, item) }
fun inspectItem(
monkeyItems: Map<Long, Pair<List<Long>, Long>>,
monkeyBehaviour: Map<Long, Pair<(Long) -> Long, Triple<Long, Long, Long>>>,
worryReduction: (Long) -> Long,
monkey: Long,
item: Long
) =
monkeyItems.toMutableMap().let {
it[monkey] = it[monkey]!!.first.drop(1) to it[monkey]!!.second + 1
val newItem = monkeyBehaviour[monkey]!!.first(item)
val newItemReduced = worryReduction(newItem)
val newMonkey =
if ((newItemReduced % monkeyBehaviour[monkey]!!.second.first) == 0L)
monkeyBehaviour[monkey]!!.second.second
else
monkeyBehaviour[monkey]!!.second.third
it[newMonkey] = it[newMonkey]!!.first.plus(newItemReduced) to it[newMonkey]!!.second
it.toMap()
}
fun monkeyBusiness(monkeyItems: Map<Long, Pair<List<Long>, Long>>) = monkeyItems
.entries.map { it.value.second }
.sortedDescending()
.take(2)
.reduce { acc, act -> acc * act }
fun day11part1() = File("input/11.txt").readText()
.parseMonkeys()
.let { (monkeyItems, monkeyBehaviour) ->
(1 .. 20).fold(monkeyItems) { map, _ ->
executeRound(map, monkeyBehaviour) { level -> level.div(3)}
}
}
.let { monkeyBusiness(it) }
fun day11part2() = File("input/11.txt").readText()
.parseMonkeys()
.let { (monkeyItems, monkeyBehaviour) ->
(1 .. 10000).fold(monkeyItems) { map, _ ->
executeRound(map, monkeyBehaviour,
monkeyBehaviour.values.map { mbv -> mbv.second.first }.reduce(Long::times).let {
{ level: Long -> level.mod(it) }
}
)
}
}
.let { monkeyBusiness(it) } | 0 | Kotlin | 0 | 0 | ea17b3f2a308618883caa7406295d80be2406260 | 3,534 | aoc-2022 | MIT License |
src/Day02.kt | AlexeyVD | 575,495,640 | false | {"Kotlin": 11056} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { apply(it, RPS::fight) }
}
fun part2(input: List<String>): Int {
return input.sumOf { apply(it, RPS::getByResult) }
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class RPS(
val title: String,
private val points: Int,
private val other: String,
private val wins: String
) {
X("Rock", 1, "A", "C"),
Y("Paper", 2, "B", "A"),
Z("Scissors", 3, "C", "B");
companion object {
fun fight(other: String, value: String): Int {
val rps = RPS.valueOf(value)
val result = when {
rps.wins == other -> Result.WIN
rps.other == other -> Result.DRAW
else -> Result.LOSS
}
return result.points + rps.points
}
fun getByResult(otherRps: String, resultString: String): Int {
val rps = RPS.getByOther(otherRps)
val result = Result.getByOther(resultString)
val value = when (result) {
Result.DRAW -> rps
Result.WIN -> values().first { it.wins == rps.other }
else -> values().first { it.other == rps.wins }
}
return value.points + result.points
}
private fun getByOther(other: String): RPS {
return values().first { it.other == other }
}
}
}
enum class Result(val points: Int, private val other: String) {
WIN(6, "Z"),
DRAW(3, "Y"),
LOSS(0, "X");
companion object {
fun getByOther(value: String): Result {
return values().first { it.other == value }
}
}
}
fun apply(input: String, transform: (first: String, second: String) -> Int): Int {
val (first, second) = input.split(" ")
return transform.invoke(first, second)
} | 0 | Kotlin | 0 | 0 | ec217d9771baaef76fa75c4ce7cbb67c728014c0 | 2,024 | advent-kotlin | Apache License 2.0 |
src/Day09.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} | import kotlin.math.max
import kotlin.math.abs
data class Position(val x: Int, val y: Int)
fun main() {
fun sign(a : Int) : Int =
if (a > 0) {
1
} else if (a < 0) {
-1
} else {
0
}
fun snake(commands: List<Pair<Int, Position>>, size : Int): Int {
val ropes = Array(size) { _ -> Position(0, 0) }
val positions = mutableSetOf<Position>()
for (command in commands) {
val (steps: Int, delta: Position) = command
for (step in 1..steps) {
val next = Position(ropes[0].x + delta.x, ropes[0].y + delta.y)
ropes[0] = next
for(i in 1 until ropes.size) {
val delta = Position(ropes[i - 1].x - ropes[i].x, ropes[i - 1].y - ropes[i].y)
if (max(abs(delta.x), abs(delta.y)) > 1) {
val corrected = Position(sign(delta.x), sign(delta.y))
ropes[i] = Position(ropes[i].x + corrected.x, ropes[i].y + corrected.y)
}
}
positions += ropes.last()
}
}
return positions.size
}
fun getCommands(input: List<String>) = input.map {
val (command, steps) = it.split(" ")
val n = steps.toInt()
when (command) {
"U" -> Pair(n, Position(0, 1))
"D" -> Pair(n, Position(0, -1))
"L" -> Pair(n, Position(-1, 0))
"R" -> Pair(n, Position(1, 0))
else -> throw IllegalStateException()
}
}
fun part1(input: List<String>): Int {
val commands = getCommands(input)
return snake(commands, 2)
}
fun part2(input: List<String>): Int {
val commands = getCommands(input)
return snake(commands, 10)
}
// test if implementation meets criteria from the description, like:
val testInputExample = readInput("Day09_example")
check(part1(testInputExample) == 13)
check(part2(testInputExample) == 1)
val testLargerInputExample = readInput("Day09_example_larger")
check(part2(testLargerInputExample) == 36)
val testInput = readInput("Day09_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 2,287 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day14/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day14
import println
import readInput
fun main() {
val ROLLING_ROCK = 'O'
val SQAURE_ROCK = '#'
val EMPTY = '.'
fun cacheKey(map: Array<Array<Char>>): String {
return map.joinToString(separator = "") { it.joinToString(separator = "") }
}
fun tiltNorth(map: Array<Array<Char>>): Array<Array<Char>> {
val height = map.size
val width = map[0].size
var emptyPositionInColumn = List(width) {height}.toMutableList()
for (rowIndex in (0 ..<height)) {
for (columnIndex in (0 ..<width)) {
if (map[rowIndex][columnIndex] == EMPTY && rowIndex < emptyPositionInColumn[columnIndex]) {
emptyPositionInColumn[columnIndex] = rowIndex
continue
}
if (map[rowIndex][columnIndex] == SQAURE_ROCK) {
emptyPositionInColumn[columnIndex] = height
continue
}
if (map[rowIndex][columnIndex] == ROLLING_ROCK) {
if (emptyPositionInColumn[columnIndex] < rowIndex) {
map[rowIndex][columnIndex] = EMPTY
map[emptyPositionInColumn[columnIndex]][columnIndex] = ROLLING_ROCK
emptyPositionInColumn[columnIndex]++
}
}
}
}
return map
}
fun rotateClockwise(map: Array<Array<Char>>): Array<Array<Char>> {
val oldHeight = map.size
val oldWidth = map[0].size
return Array(oldWidth) { newRowIndex -> Array(oldHeight) {newColumnIndex -> map[oldHeight - newColumnIndex - 1][newRowIndex]} }
}
fun print(map: Array<Array<Char>>) {
map.forEach {it ->
String(it.toCharArray()).println()
}
}
fun calculateWeight(map: Array<Array<Char>>): Long {
return map.mapIndexed { rowIndex, row ->
row.sumOf {
if (it == ROLLING_ROCK) (map.size - rowIndex).toLong() else 0L
}
}.sum()
}
fun tiltAndCalculateWeight(input: List<String>): Long {
val platform = tiltNorth(input.map { it.toCharArray().toTypedArray() }.toTypedArray())
var result = calculateWeight(platform)
result.println()
return result
}
fun spinAndCalculateWeight(input: List<String>): Long {
var map = input.map { it.toCharArray().toTypedArray() }.toTypedArray()
var previousPermutations = mutableListOf<Pair<String, Long>>()
val iterations = 1_000_000_000
var result = 0L
for (i in 1..iterations) {
val cacheKey = cacheKey(map)
if (previousPermutations.any{ it.first == cacheKey}) {
"Loop detected".println()
var loopSize = previousPermutations.size - previousPermutations.indexOfFirst{ it.first == cacheKey}
var loopStartPosition = previousPermutations.size - loopSize
"Loop size: ${loopSize}; loop start: $loopStartPosition ".println()
var resultIndex = (iterations - loopStartPosition) % loopSize + loopStartPosition
"resultIndex: $resultIndex".println()
result = previousPermutations[resultIndex].second
break
}
previousPermutations += Pair(cacheKey, calculateWeight(map))
map = tiltNorth(map)
map = rotateClockwise(map)
map = tiltNorth(map)
map = rotateClockwise(map)
map = tiltNorth(map)
map = rotateClockwise(map)
map = tiltNorth(map)
map = rotateClockwise(map)
"$i -> ${calculateWeight(map)}".println()
}
return result
}
check(tiltAndCalculateWeight(readInput("day14/test1")) == 136L)
"Part 1:".println()
tiltAndCalculateWeight(readInput("day14/input")).println()
check(spinAndCalculateWeight(readInput("day14/test1")) == 64L)
"Part 2:".println()
spinAndCalculateWeight(readInput("day14/input")).println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 4,083 | advent-of-code-2023 | Apache License 2.0 |
src/Day05.kt | jbotuck | 573,028,687 | false | {"Kotlin": 42401} | fun main() {
val lines = readInput("Day05")
val indexOfStackKeyLine = lines.indexOfFirst { it.trim().first() == '1' }
val part1 = part1(lines, indexOfStackKeyLine)
val part2 = part2(lines, indexOfStackKeyLine)
println("part 1 $part1")
println("part 2 $part2")
}
private fun part1(lines: List<String>, indexOfStackKeyLine: Int): String {
return solve(lines, indexOfStackKeyLine, 1)
}
private fun part2(lines: List<String>, indexOfStackKeyLine: Int): String {
return solve(lines, indexOfStackKeyLine, 2)
}
private fun solve(lines: List<String>, indexOfStackKeyLine: Int, part: Int): String {
val stacks = parseStacks(lines.subList(0, indexOfStackKeyLine).asReversed(), lines[indexOfStackKeyLine])
for (line in lines.subList(indexOfStackKeyLine + 2, lines.size)) {
stacks.parseInstruction(line).execute(part)
}
return topOfEach(stacks)
}
fun parseStacks(lines: List<String>, key: String) = mutableMapOf<Char, ArrayDeque<Char>>()
.apply {
key.forEachIndexed { index, c ->
if (c.isDigit()) {
val stack = ArrayDeque<Char>()
for (line in lines) {
line.getOrNull(index)?.takeIf { it.isUpperCase() }?.let { stack.addLast(it) } ?: break
}
this[c] = stack
}
}
}.toMap()
private fun Map<Char, ArrayDeque<Char>>.parseInstruction(line: String): Instruction {
val split = line.split(" ")
return Instruction(
count = split[1].toInt(),
from = get(split[3].first())!!,
to = get(split[5].first())!!
)
}
private fun topOfEach(stacks: Map<Char, ArrayDeque<Char>>) = stacks.keys.sorted()
.map { stacks[it]!!.last() }
.joinToString("")
data class Instruction(val count: Int, val from: ArrayDeque<Char>, val to: ArrayDeque<Char>) {
private fun execute1() {
repeat(count) {
to.addLast(from.removeLast())
}
}
private fun execute2() {
to.addAll(from.takeLast(count))
from.subList(from.size - count, from.size).clear()
}
fun execute(part: Int) {
if (part == 1) execute1() else execute2()
}
} | 0 | Kotlin | 0 | 0 | d5adefbcc04f37950143f384ff0efcd0bbb0d051 | 2,180 | aoc2022 | Apache License 2.0 |
src/Day24.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | fun main() {
val d = Day24(readInput("inputs/Day24"))
println(d.part1())
println(d.part2())
}
class Day24(input: List<String>) {
private val initialMapState: MapState = MapState.of(input)
private val start: Point = Point(input.first().indexOfFirst { it == '.' }, 0)
private val goal: Point = Point(input.last().indexOfFirst { it == '.' }, input.lastIndex)
fun part1(): Int =
solve().first
fun part2(): Int {
val toGoal = solve()
val backToStart = solve(goal, start, toGoal.second, toGoal.first)
val backToGoal = solve(start, goal, backToStart.second, backToStart.first)
return backToGoal.first
}
private fun solve(
startPlace: Point = start,
stopPlace: Point = goal,
startState: MapState = initialMapState,
stepsSoFar: Int = 0
): Pair<Int, MapState> {
val mapStates = mutableMapOf(stepsSoFar to startState)
val queue = mutableListOf(PathAttempt(stepsSoFar, startPlace))
val seen = mutableSetOf<PathAttempt>()
while (queue.isNotEmpty()) {
val thisAttempt = queue.removeFirst()
if (thisAttempt !in seen) {
seen += thisAttempt
val nextMapState = mapStates.computeIfAbsent(thisAttempt.steps + 1) { key ->
mapStates.getValue(key - 1).nextState()
}
if (nextMapState.isOpen(thisAttempt.location)) queue.add(thisAttempt.next())
val neighbors = thisAttempt.location.adjacents()
if (stopPlace in neighbors) return Pair(thisAttempt.steps + 1, nextMapState)
neighbors
.filter { it == start || (nextMapState.inBounds(it) && nextMapState.isOpen(it)) }
.forEach { neighbor ->
queue.add(thisAttempt.next(neighbor))
}
}
}
throw IllegalStateException("No paths found")
}
private data class PathAttempt(val steps: Int, val location: Point) {
fun next(place: Point = location): PathAttempt =
PathAttempt(steps + 1, place)
}
private data class MapState(val boundary: Point, val blizzards: Set<Blizzard>) {
private val unsafeSpots = blizzards.map { it.location }.toSet()
fun isOpen(place: Point): Boolean =
place !in unsafeSpots
fun inBounds(place: Point): Boolean =
place.x > 0 && place.y > 0 && place.x <= boundary.x && place.y <= boundary.y
fun nextState(): MapState =
copy(blizzards = blizzards.map { it.next(boundary) }.toSet())
companion object {
fun of(input: List<String>): MapState =
MapState(
Point(input.first().lastIndex - 1, input.lastIndex - 1),
input.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
when (char) {
'>' -> Blizzard(Point(x, y), Point(1, 0))
'<' -> Blizzard(Point(x, y), Point(-1, 0))
'v' -> Blizzard(Point(x, y), Point(0, 1))
'^' -> Blizzard(Point(x, y), Point(0, -1))
else -> null
}
}
}.toSet()
)
}
}
private data class Blizzard(val location: Point, val offset: Point) {
fun next(boundary: Point): Blizzard {
var nextLocation = location + offset
when {
nextLocation.x == 0 -> nextLocation = Point(boundary.x, location.y)
nextLocation.x > boundary.x -> nextLocation = Point(1, location.y)
nextLocation.y == 0 -> nextLocation = Point(location.x, boundary.y)
nextLocation.y > boundary.y -> nextLocation = Point(location.x, 1)
}
return copy(location = nextLocation)
}
}
}
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 4,050 | aoc-2022 | Apache License 2.0 |
src/day25/day25.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day25
import readInput
import kotlin.math.pow
fun main() {
fun fromSnafu(line: String) = line.mapIndexed { index, digit ->
5.0.pow(line.lastIndex - index) * when (digit) {
'2' -> 2
'1' -> 1
'0' -> 0
'-' -> -1
'=' -> -2
else -> error("wrong input")
}
}.sum().toLong()
fun parse(input: List<String>): Long {
return input.sumOf { line ->
fromSnafu(line)
}
}
fun part1(input: List<String>): String {
val sum = parse(input)
println("sum: $sum")
println("snafu:${fromSnafu(sum.toSnafu())}")
return sum.toSnafu()
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day25/Day25_test")
val input = readInput("day25/Day25")
check((part1(testInput)).also { println(it) } == "2=-1=0")
println(part1(input))
check(part2(testInput).also { println(it) } == 1)
println(part2(input))
}
private fun Long.toSnafu(): String {
if (this == 0L) return ""
return when (this.mod(5)) {
0 -> (this / 5).toSnafu() + "0"
1 -> (this / 5).toSnafu() + "1"
2 -> (this / 5).toSnafu() + "2"
3 -> (this / 5 + 1).toSnafu() + "="
4 -> (this / 5 + 1).toSnafu() + "-"
else -> error("wrong number")
}
}
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 1,459 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day02.kt | sbaumeister | 572,855,566 | false | {"Kotlin": 38905} | enum class Symbol { ROCK, PAPER, SCISSOR }
fun playRockPaperScissorRound(opponent: Symbol, me: Symbol): Int {
// Opponent wins
if ((opponent == Symbol.ROCK && me == Symbol.SCISSOR)
|| (opponent == Symbol.PAPER && me == Symbol.ROCK)
|| (opponent == Symbol.SCISSOR && me == Symbol.PAPER)
) {
return me.ordinal + 1
}
// Me wins
if ((me == Symbol.ROCK && opponent == Symbol.SCISSOR)
|| (me == Symbol.PAPER && opponent == Symbol.ROCK)
|| (me == Symbol.SCISSOR && opponent == Symbol.PAPER)
) {
return 6 + me.ordinal + 1
}
// Draw
return 3 + me.ordinal + 1
}
fun mapCharToSymbol(ch: Char): Symbol = when (ch) {
'A', 'X' -> Symbol.ROCK
'B', 'Y' -> Symbol.PAPER
'C', 'Z' -> Symbol.SCISSOR
else -> throw IllegalStateException()
}
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEach {
val (opponentChar, meChar) = it.split(" ", limit = 2).map { str -> str.toCharArray().first() }
sum += playRockPaperScissorRound(mapCharToSymbol(opponentChar), mapCharToSymbol(meChar))
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.forEach {
val (opponentChar, meChar) = it.split(" ", limit = 2).map { str -> str.toCharArray().first() }
val opponentSymbol = mapCharToSymbol(opponentChar)
val meSymbol = when (meChar) {
// Loose
'X' -> {
when (opponentSymbol) {
Symbol.ROCK -> Symbol.SCISSOR
Symbol.PAPER -> Symbol.ROCK
Symbol.SCISSOR -> Symbol.PAPER
}
}
// Draw
'Y' -> opponentSymbol
// Win
'Z' -> {
when (opponentSymbol) {
Symbol.ROCK -> Symbol.PAPER
Symbol.PAPER -> Symbol.SCISSOR
Symbol.SCISSOR -> Symbol.ROCK
}
}
else -> throw IllegalStateException()
}
sum += playRockPaperScissorRound(opponentSymbol, meSymbol)
}
return sum
}
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 | e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84 | 2,497 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/nosswald/aoc/days/Day04.kt | 7rebux | 722,943,964 | false | {"Kotlin": 34890} | package de.nosswald.aoc.days
import de.nosswald.aoc.Day
import kotlin.math.pow
// https://adventofcode.com/2023/day/4
object Day04 : Day<Int>(4, "Scratchcards") {
private data class Card(val id: Int, val winning: List<Int>, val actual: List<Int>)
private fun parseInput(input: List<String>): List<Card> {
return input.mapIndexed { index, line ->
val (winning, actual) = line
.substringAfter(':')
.split("|")
.map { numbers ->
numbers
.split(" ")
.filter(String::isNotBlank)
.map(String::toInt)
}
return@mapIndexed Card(index + 1, winning, actual)
}
}
override fun partOne(input: List<String>): Int {
return parseInput(input).sumOf { card ->
// 2 to the power of -1 is 0.5, so after converting it to an integer its 0
2.toDouble().pow(card.actual.count(card.winning::contains) - 1).toInt()
}
}
override fun partTwo(input: List<String>): Int {
val cards = parseInput(input)
val copies = cards
.associate { it.id to 1 }
.toMutableMap()
cards.forEach { card ->
val matching = card.actual.count(card.winning::contains)
val cardsToCopy = (card.id + 1)..(card.id + matching)
cardsToCopy.forEach { id ->
copies[id] = copies[id]!! + copies[card.id]!!
}
}
return copies.values.sum()
}
override val partOneTestExamples: Map<List<String>, Int> = mapOf(
listOf(
"Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53",
"Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19",
"Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1",
"Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83",
"Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36",
"Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11",
) to 13
)
override val partTwoTestExamples: Map<List<String>, Int> = mapOf(
listOf(
"Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53",
"Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19",
"Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1",
"Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83",
"Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36",
"Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11",
) to 30
)
}
| 0 | Kotlin | 0 | 1 | 398fb9873cceecb2496c79c7adf792bb41ea85d7 | 2,563 | advent-of-code-2023 | MIT License |
kotlin/src/main/kotlin/year2023/Day08.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
fun main() {
val input = readInput("Day08")
Day08.part1(input).println()
Day08.part2(input).println()
}
object Day08 {
fun part1(input: List<String>): Int {
val instructions = input[0].map { if (it == 'L') 0 else 1 }
val map = input
.drop(2).map {
val (key, rest) = it.split(" = (")
val value = Pair(rest.substring(0, 3), rest.substring(5, 8))
key to value
}.toMap()
var iterator = 0
var key = "AAA"
while (key != "ZZZ") {
val leftOrRight = instructions[iterator % instructions.size]
key = if (leftOrRight == 0) {
map[key]?.first ?: key
} else {
map[key]?.second ?: key
}
iterator++
}
return iterator
}
fun part2(input: List<String>): Long {
val instructions = input[0].map { if (it == 'L') 0 else 1 }
val map = input
.drop(2).map {
val (key, rest) = it.split(" = (")
val value = Pair(rest.substring(0, 3), rest.substring(5, 8))
key to value
}.toMap()
var startingGhosts = map.keys.filter { it.endsWith("A") }
return startingGhosts
.map {
var iterator = 0L
var key = it
while (!key.endsWith("Z")) {
val leftOrRight = instructions[(iterator % instructions.size).toInt()]
key = if (leftOrRight == 0) {
map[key]?.first ?: key
} else {
map[key]?.second ?: key
}
iterator++
}
iterator
}.lcm()
}
private fun List<Long>.lcm(): Long {
if (this.isEmpty()) {
return 0
}
if (this.size == 1) {
return this[0]
}
var result = this[0]
for (i in 1 until this.size) {
result = lcm(result, this[i])
}
return result
}
private fun lcm(a: Long, b: Long): Long {
val larger = if (a > b) a else b
val maxLcm = a * b
var lcm = larger
while (lcm <= maxLcm) {
if (lcm % a == 0L && lcm % b == 0L) {
return lcm
}
lcm += larger
}
return maxLcm
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 2,472 | advent-of-code | MIT License |
src/Day12.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | data class Node(val row: Int, val col: Int, var char: Char = '?', var distance: Int = -1, var visited: Boolean = false) {
val height get(): Int = when {
char.isLowerCase() -> char.code - 'a'.code // 0 - 25
char == 'E' -> 26 // end point is 1 higher than 'z'
else -> Int.MAX_VALUE // everything else is out of reach
}
}
class Grid(val nodes: Array<Array<Node>>, val start: Node, val end: Node )
fun main() {
fun log(message: Any?) {
println(message)
}
fun bfs(
nodes: Array<Array<Node>>, start: Node,
isCandidate: (from: Node, to: Node) -> Boolean,
isTarget: (Node) -> Boolean
): Int {
// Create a queue and add start to represent the index of the first node
start.distance = 0 // make sure we start at 0, not sure if I need the default of -1 yet
val queue: MutableList<Node> = mutableListOf(start)
while (queue.isNotEmpty()) {
// Dequeue a node from queue
val node = queue.removeAt(0)
// Add all the node's unvisited neighbors to the queue
if (!node.visited) {
val candidates = listOfNotNull(
nodes[node.row].getOrNull(node.col - 1), // left
nodes[node.row].getOrNull(node.col + 1), // right
nodes.getOrNull(node.row - 1)?.getOrNull(node.col), // up
nodes.getOrNull(node.row + 1)?.getOrNull(node.col), // down
).filter { isCandidate(node, it) } // fn param checks the height diffs
candidates.forEach { candidate -> candidate.distance = node.distance + 1 }
candidates.singleOrNull() { candidate -> isTarget(candidate) }
?.let { endNode -> return endNode.distance } // we found the target! return the result
queue.addAll(candidates)
node.visited = true
}
}
return -1
}
fun parse(input: List<String>): Grid {
val nodes = Array<Array<Node>>(input.size) { row: Int ->
Array<Node>(input[0].length) { col ->
Node(row, col)
}
}
var start: Node? = null
var end: Node? = null
input.forEachIndexed { row, s ->
s.forEachIndexed { col, c ->
nodes[row][col].char = c
if (c == 'S') { start = nodes[row][col] }
if (c == 'E') { end = nodes[row][col] }
}
}
return Grid(nodes, start!!, end!!)
}
fun findStart(nodes: Array<Array<Node>>, char: Char): Node? {
// hm should do this on init too, but the parse return type gets ugly
nodes.forEachIndexed { row, s ->
s.forEachIndexed { col, c ->
if (c.char == char) return nodes[row][col]
}
}
return null
}
fun part1(input: List<String>): Int {
val grid = parse(input)
return bfs(grid.nodes, start = grid.start,
isCandidate = { from, to -> to.height - from.height <= 1 }, // cannot be more than + 1 height from->to
isTarget = { node -> node.char == 'E' } // stop at the end
)
}
fun part2(input: List<String>): Int {
val grid = parse(input)
return bfs(grid.nodes, start = grid.end,
isCandidate = { from, to -> from.height - to.height <= 1 }, // cannot be more than + 1 height to->from
isTarget = { node -> node.char == 'a' } // stop at any 'a' height
)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test.txt")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12.txt")
println(part1(input))
check(part1(input) == 423)
println(part2(input))
check(part2(input) == 416)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 3,889 | aoc2022 | Apache License 2.0 |
src/day18/Day18.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day18
import readInput
fun main() {
val testInput = readInput("day18/test")
val cubes = testInput.map { it.split(',') }.map { Point3D(it[0].toInt(), it[1].toInt(), it[2].toInt()) }
println(part1(cubes))
println(part2(cubes))
}
private fun part1(cubes: List<Point3D>): Int =
cubes.sumOf { cube ->
cube.neighbors.count { it !in cubes }
}
private fun part2(cubes: List<Point3D>): Int {
val xRange = cubes.minOf { it.x } - 1..cubes.maxOf { it.x } + 1
val yRange = cubes.minOf { it.y } - 1..cubes.maxOf { it.y } + 1
val zRange = cubes.minOf { it.z } - 1..cubes.maxOf { it.z } + 1
val checkedPoints = mutableSetOf<Point3D>()
var count = 0
val queue = mutableListOf<Point3D>()
queue.add(Point3D(xRange.first, yRange.first, zRange.first))
while (queue.isNotEmpty()) {
val point = queue.removeFirst()
if (point in checkedPoints) continue
checkedPoints.add(point)
point.neighbors
.filter { it.x in xRange && it.y in yRange && it.z in zRange }
.forEach {
if (it in cubes) {
count++
} else {
queue.add(it)
}
}
}
return count
}
private data class Point3D(val x: Int, val y: Int, val z: Int) {
val neighbors: Set<Point3D>
get() = setOf(
Point3D(x - 1, y, z),
Point3D(x + 1, y, z),
Point3D(x, y - 1, z),
Point3D(x, y + 1, z),
Point3D(x, y, z - 1),
Point3D(x, y, z + 1)
)
} | 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 1,592 | advent-of-code-2022 | Apache License 2.0 |
src/Day23.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | fun main() {
val d = Day23(readInput("inputs/Day23"))
println(d.part1())
println(d.part2())
}
class Day23(input: List<String>) {
private val startingPositions = parseInput(input)
private val nextTurnOffsets: List<List<Point>> = createOffsets()
fun part1(): Int {
val locations = (0 until 10).fold(startingPositions) { carry, round -> carry.playRound(round) }
val gridSize = ((locations.maxOf { it.x } - locations.minOf { it.x }) + 1) * ((locations.maxOf { it.y } - locations.minOf { it.y }) + 1)
return gridSize - locations.size
}
fun part2(): Int {
var thisTurn = startingPositions
var roundId = 0
do {
val previousTurn = thisTurn
thisTurn = previousTurn.playRound(roundId++)
} while (previousTurn != thisTurn)
return roundId
}
fun Point.neighbors(): Set<Point> =
setOf(
Point(x - 1, y - 1),
Point(x, y - 1),
Point(x + 1, y - 1),
Point(x - 1, y),
Point(x + 1, y),
Point(x - 1, y + 1),
Point(x, y + 1),
Point(x + 1, y + 1)
)
private fun Set<Point>.playRound(roundNumber: Int): Set<Point> {
val nextPositions = this.toMutableSet()
val movers: Map<Point, Point> = this
.filter { elf -> elf.neighbors().any { it in this } }
.mapNotNull { elf ->
nextTurnOffsets.indices.map { direction -> nextTurnOffsets[(roundNumber + direction) % 4] }
.firstNotNullOfOrNull { offsets ->
if (offsets.none { offset -> (elf + offset) in this }) elf to (elf + offsets.first())
else null
}
}.toMap()
val safeDestinations = movers.values.groupingBy { it }.eachCount().filter { it.value == 1 }.keys
movers
.filter { (_, target) -> target in safeDestinations }
.forEach { (source, target) ->
nextPositions.remove(source)
nextPositions.add(target)
}
return nextPositions
}
private fun createOffsets(): List<List<Point>> =
listOf(
listOf(Point(0, -1), Point(-1, -1), Point(1, -1)), // N
listOf(Point(0, 1), Point(-1, 1), Point(1, 1)), // S
listOf(Point(-1, 0), Point(-1, -1), Point(-1, 1)), // W
listOf(Point(1, 0), Point(1, -1), Point(1, 1)), // E
)
private fun parseInput(input: List<String>): Set<Point> =
input.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
if (char == '#') Point(x, y) else null
}
}.toSet()
} | 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 2,734 | aoc-2022 | Apache License 2.0 |
facebook/y2020/round1/a1.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package facebook.y2020.round1
private fun solve(M: Int = 1_000_000_007): Int {
val (n, k, w) = readInts()
val (L, h) = List(2) { readInts().toMutableList().also { list ->
val (a, b, c, d) = readInts()
for (i in k until n) {
list.add(((a.toLong() * list[i - 2] + b.toLong() * list[i - 1] + c) % d + 1).toInt())
}
}}
var ans = 1
var perimeter = 0L
val height = mutableMapOf<Int, Int>()
fun perimeter(xMax: Int): Long {
var res = 0L
for (x in xMax - w - 1 .. xMax) {
val y = height.getOrDefault(x, 0)
val yLeft = height.getOrDefault(x - 1, 0)
if (y > 0) res += 2
res += (y - yLeft).abs()
}
return res
}
for (i in h.indices) {
val xMax = L[i] + w
perimeter -= perimeter(xMax)
for (x in L[i] until xMax) {
height[x] = maxOf(height.getOrDefault(x, 0), h[i])
}
perimeter += perimeter(xMax)
ans = ((ans.toLong() * (perimeter % M)) % M).toInt()
}
return ans
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun Int.abs() = kotlin.math.abs(this)
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,212 | competitions | The Unlicense |
src/DayEight.kt | P-ter | 572,781,029 | false | {"Kotlin": 18422} | import java.util.*
fun main() {
fun buildTheMap(input: List<String>): Pair<List<List<Int>>, List<List<Int>>> {
val row = mutableListOf<MutableList<Int>>()
val column = mutableListOf<MutableList<Int>>()
input.forEach { line ->
val rowLine = mutableListOf<Int>()
line.forEachIndexed {index, tree ->
if(column.size <= index) {
column.add(mutableListOf(tree.digitToInt()))
} else {
column[index].add(tree.digitToInt())
}
rowLine.add(tree.digitToInt())
}
row.add(rowLine)
}
return Pair(row, column)
}
fun partOne(input: List<String>): Int {
var total = 0
val (row, column) = buildTheMap(input)
row.forEachIndexed { rowIndex, treeY ->
column.forEachIndexed { columnIndex, treeX ->
if(rowIndex == 0 || rowIndex == row.size-1 || columnIndex == 0 || columnIndex == column.size -1) {
total++
} else {
val fromTop = column[columnIndex].subList(0, rowIndex)
val fromBottom = column[columnIndex].subList(rowIndex + 1, column[columnIndex].size)
val fromLeft = row[rowIndex].subList(0, columnIndex)
val fromRight = row[rowIndex].subList(columnIndex + 1, row[rowIndex].size)
val tree = treeX[rowIndex]
if (fromTop.max() < tree && fromTop.count { it == tree } == 0) {
total++
} else if (fromBottom.max() < tree && fromBottom.count { it == tree } == 0) {
total++
} else if (fromLeft.max() < tree && fromLeft.count { it == tree } == 0) {
total++
} else if (fromRight.max() < tree && fromRight.count { it == tree } == 0) {
total++
}
}
}
}
return total
}
fun partTwo(input: List<String>): Int {
var total = 0
val (row, column) = buildTheMap(input)
row.forEachIndexed { rowIndex, treeY ->
column.forEachIndexed { columnIndex, treeX ->
if(rowIndex == 0 || rowIndex == row.size-1 || columnIndex == 0 || columnIndex == column.size -1) {
} else {
val tree = treeX[rowIndex]
val fromTop = column[columnIndex].subList(0, rowIndex).reversed()
val fromBottom = column[columnIndex].subList(rowIndex + 1, column[columnIndex].size)
val fromLeft = row[rowIndex].subList(0, columnIndex).reversed()
val fromRight = row[rowIndex].subList(columnIndex + 1, row[rowIndex].size)
val topScore = fromTop.indexOfFirst { it >= tree }.let { if(it == -1) fromTop.size else it + 1 }
val bottomScore = fromBottom.indexOfFirst { it >= tree }.let { if(it == -1) fromBottom.size else it + 1 }
val leftScore = fromLeft.indexOfFirst { it >= tree }.let { if(it == -1) fromLeft.size else it + 1 }
val rightScore = fromRight.indexOfFirst { it >= tree }.let { if(it == -1) fromRight.size else it + 1 }
if(topScore * bottomScore * leftScore * rightScore > total) {
total = topScore * bottomScore * leftScore * rightScore
}
}
}
}
return total
}
val input = readInput("dayeight")
// val input = readInput("dayeightex")
println(partOne(input))
println(partTwo(input))
}
| 0 | Kotlin | 0 | 1 | e28851ee38d6de5600b54fb884ad7199b44e8373 | 3,734 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/com/ncorti/aoc2023/Day17.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
import com.ncorti.aoc2023.Direction.*
import java.util.*
fun main() {
fun parseInput() = getInputAsText("17") {
split("\n").filter(String::isNotBlank).map {
it.toCharArray().map { it.digitToInt() }.toIntArray()
}
}.toTypedArray()
data class Item(
val x: Int, val y: Int, val score: Int, val disallowedDirection: Direction
)
val directions = listOf(Triple(1, 0, DOWN), Triple(0, 1, RIGHT), Triple(-1, 0, UP), Triple(0, -1, LEFT))
fun part(min: Int, max: Int): Int {
val input = parseInput()
val distances = Array(input.size) {
IntArray(input[0].size) { Int.MAX_VALUE }
}
val seen = mutableSetOf<Triple<Int, Int, Direction>>()
distances[0][0] = 0
val queue = PriorityQueue<Item> { o1, o2 ->
o1.score - o2.score
}
queue.add(Item(0, 0, 0, UP))
while (queue.isNotEmpty()) {
val (x, y, currentScore, disallowedDirection) = queue.remove()
val seenEntry = Triple(x, y, disallowedDirection)
if (seenEntry in seen) {
continue
}
seen.add(seenEntry)
directions.forEach { (dx, dy, direction) ->
var (nx, ny) = x to y
var updatedScore = currentScore
if (x == 0 && y == 0 || direction != disallowedDirection && direction != disallowedDirection.opposite()) {
for (i in 1..max) {
nx += dx
ny += dy
if (nx >= 0 && ny >= 0 && nx < input.size && ny < input[0].size) {
updatedScore += input[nx][ny]
if (i !in min..max) {
continue
}
if (updatedScore <= distances[nx][ny]) {
distances[nx][ny] = updatedScore
}
queue.add(Item(nx, ny, updatedScore, direction))
}
}
}
}
}
return distances[input.size - 1][input[0].size - 1]
}
println(part(min = 1, max = 3))
println(part(min = 4, max = 10))
}
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 2,317 | adventofcode-2023 | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day220/day220.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day220
// day220.kt
// By <NAME>, 2019.
import kotlin.math.max
import kotlin.math.min
// Two solutions: backtracking and dynamic programming.
// Backtracking: O(2^N)
fun coin_backtrack(coins: List<Int>): Int {
if (coins.isEmpty()) return 0
fun aux(curr_coins: List<Int>, value: Int): Int {
if (curr_coins.size == 1)
return curr_coins[0] + value
else if (curr_coins.size == 2)
return max(curr_coins[0], curr_coins[1]) + value
else {
val m1 = curr_coins[0] + min(aux(curr_coins.drop(2), value), aux(curr_coins.drop(1).dropLast(1), value))
val m2 = curr_coins.last() + min(aux(curr_coins.dropLast(2), value), aux(curr_coins.drop(1).dropLast(1), value))
return value + max(m1, m2)
}
}
return aux(coins, 0)
}
// Dynamic programming approach. Upper triangular, where coins[i]..coins[j] represents the highest possible
// value for coins v_i through v_j.
fun coin_dynamic(coins: List<Int>): Int {
if (coins.isEmpty()) return 0
val n = coins.size
val value = MutableList(n) {MutableList(n) {0} }
// Strategy to fill:
// 1. If there is just one coin, then that is the highest value.
(0 until n).forEach { value[it][it] = coins[it] }
// 2. The maximum value of two coins (stored in value[i][i]) is the maximum of the two choices.
(0 until n-1).forEach { value[it][it+1] = max(value[it][it], value[it+1][it+1]) }
// 3. Now we consider longer rows of coins.
// We choose a coin that maximizes our value and the minimal value of the opponent.
(2 until n)
.forEach{ gap -> (0 until (n-gap))
.forEach {
val j = it + gap
val left = value[it][j - 2]
val diagonal = value[it + 1][j - 1]
val bottom = value[it + 2][j]
value[it][it + gap] = max(
coins[it] + min(diagonal, bottom),
coins[j] + min(left, diagonal)
)}
}
return value[0][n-1]
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 2,070 | daily-coding-problem | MIT License |
src/main/kotlin/aoc/year2023/Day15.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2023
import aoc.Puzzle
/**
* [Day 15 - Advent of Code 2023](https://adventofcode.com/2023/day/15)
*/
object Day15 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int = input.split(',')
.sumOf { it.map(Char::code).fold(0) { hash, ascii -> ((hash + ascii) * 17).rem(256) }.toInt() }
override fun solvePartTwo(input: String): Int {
val hashMap = hashMapOf<Int, MutableList<Lens>>()
input.split(',').map { it.toStep() }.forEach { step ->
val box = hashMap.getOrPut(step.hash, ::arrayListOf)
when (step) {
is Step.Remove -> box.removeAll { it.label == step.label }
is Step.Add -> {
val index = box.indexOfFirst { it.label == step.label }
val lens = Lens(step.label, step.focalLength)
if (index == -1) box.add(lens) else box[index] = lens
}
}
}
return hashMap.map { (box, lenses) ->
lenses.mapIndexed { slot, lens ->
(box + 1) * (slot + 1) * lens.focalLength
}.sum()
}.sum()
}
private fun String.toStep(): Step = if (endsWith('-')) Step.Remove(this) else Step.Add(this)
private sealed class Step(string: String) {
val label: String = string.takeWhile { it.isLetter() }
val hash: Int = label.map(Char::code).fold(0) { hash, ascii -> ((hash + ascii) * 17).rem(256) }
class Add(string: String) : Step(string) {
val focalLength: Int = string.dropWhile { !it.isDigit() }.toInt()
}
class Remove(string: String) : Step(string)
}
private data class Lens(val label: String, val focalLength: Int)
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 1,738 | advent-of-code | Apache License 2.0 |
src/Day07.kt | cypressious | 572,916,585 | false | {"Kotlin": 40281} | import kotlin.math.abs
fun main() {
fun parsePositions(input: List<String>): Map<Int, Int> {
val positions = input[0].split(",").map(String::toInt)
return positions.groupingBy { it }.eachCount()
}
fun part1(input: List<String>): Int {
val countsByPosition = parsePositions(input)
var cheapest = Int.MAX_VALUE
for (target in countsByPosition.keys.min()..countsByPosition.keys.max()) {
cheapest = minOf(
countsByPosition.entries.sumOf { (pos, count) -> abs(target - pos) * count },
cheapest
)
}
return cheapest
}
fun sumBetweenOneAnd(n: Int) = (n * (n + 1)) / 2
fun part2(input: List<String>): Int {
val countsByPosition = parsePositions(input)
var cheapest = Int.MAX_VALUE
for (target in countsByPosition.keys.min()..countsByPosition.keys.max()) {
cheapest = minOf(
countsByPosition.entries.sumOf { (pos, count) -> sumBetweenOneAnd(abs(target - pos)) * count },
cheapest
)
}
return cheapest
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 37)
check(part2(testInput) == 168)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 169fb9307a34b56c39578e3ee2cca038802bc046 | 1,416 | AdventOfCode2021 | Apache License 2.0 |
src/day03/Day03.kt | Dr4kn | 575,092,295 | false | {"Kotlin": 12652} | package day03
import readInput
import java.lang.Exception
fun main() {
fun getDuplicateItem(backpack: String): Char {
val firstCompartment = backpack
.toCharArray(0, backpack.length / 2)
.distinct()
val secondCompartment = backpack
.toCharArray(backpack.length / 2, backpack.length)
.distinct()
for (first in firstCompartment) {
for (second in secondCompartment) {
if (first == second) return first
}
}
throw Exception("No match found")
}
fun getItemPriority(priority: Char): Int {
return if (priority.isLowerCase()) {
priority.minus('`')
} else {
priority.minus('@') + 26
}
}
fun part1(input: List<String>): Int {
var sum = 0
input.forEach {
val duplicate = getDuplicateItem(it)
sum += getItemPriority(duplicate)
}
return sum
}
fun findBadge(backpacks: Array<List<Char>>): Char {
for (badge1 in backpacks[0]) {
for (badge2 in backpacks[1]) {
if (badge1 != badge2) continue
for (badge3 in backpacks[2]) {
if (badge1 == badge3) {
return badge1
}
}
}
}
throw Exception("There is no common badge")
}
fun part2(input: List<String>): Int {
val group = arrayOf(listOf(' '), listOf(' '), listOf(' '))
var sum = 0
input.forEachIndexed { index, backpack ->
val distinctBackpack: List<Char> = backpack.toCharArray().distinct()
group[index % 3] = distinctBackpack
if (index % 3 == 2) {
sum += getItemPriority(findBadge(group))
}
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6de396cb4eeb27ff0dd9a98b56e68a13c2c90cd5 | 2,174 | advent-of-code-2022 | Apache License 2.0 |
src/year2021/day03/Day03.kt | fadi426 | 433,496,346 | false | {"Kotlin": 44622} | package year2021.day01.day03
import util.assertTrue
import util.read2021DayInput
fun main() {
fun task01(positions: List<String>): Int {
var gamma = ""
var epsilon = ""
positions[0].forEachIndexed { row, _ ->
gamma = gamma.plus(findMostOccurringBitInRow(positions, row))
epsilon = epsilon.plus(findLeastOccurringBitInRow(positions, row))
}
return Integer.parseInt(gamma, 2) * Integer.parseInt(epsilon, 2)
}
fun task02(positions: List<String>): Int {
var oxGenRating = positions
var co2ScrubRating = positions
positions[0].forEachIndexed { row, _ ->
oxGenRating = oxGenRating.filter { it[row] == findMostOccurringBitInRow(oxGenRating, row) }
co2ScrubRating = co2ScrubRating.filter { it[row] == findLeastOccurringBitInRow(co2ScrubRating, row) }
}
return Integer.parseInt(oxGenRating.first(), 2) * Integer.parseInt(co2ScrubRating.first(), 2)
}
val input = read2021DayInput("Day03")
assertTrue(task01(input) == 1458194)
assertTrue(task02(input) == 2829354)
}
fun findMostOccurringBitInRow(bits: List<String>, row: Int): Char {
val frequencyOneBit = bits.map { it[row] }.count { it == '1' }
return if (frequencyOneBit >= bits.size.toDouble() / 2 && frequencyOneBit != 0) '1' else '0'
}
fun findLeastOccurringBitInRow(bits: List<String>, row: Int): Char {
val frequencyZeroBit = bits.map { it[row] }.count { it == '0' }
return if (bits.map { it[row] }.size == 1) bits[0][row] else if (frequencyZeroBit <= bits.size.toDouble() / 2 && frequencyZeroBit != 0) '0' else '1'
}
| 0 | Kotlin | 0 | 0 | acf8b6db03edd5ff72ee8cbde0372113824833b6 | 1,644 | advent-of-code-kotlin-template | Apache License 2.0 |
src/main/kotlin/io/github/kmakma/adventofcode/y2020/Y2020Day19.kt | kmakma | 225,714,388 | false | null | package io.github.kmakma.adventofcode.y2020
import io.github.kmakma.adventofcode.utils.Day
fun main() {
Y2020Day19().solveAndPrint()
}
class Y2020Day19 : Day(2020, 19, "Monster Messages") {
private lateinit var ruleList: List<String>
private lateinit var messages: List<String>
private lateinit var inputLines: List<String>
override fun initializeDay() {
inputLines = inputInStringLines()
val input = inputLines
.filterNot { it.isBlank() }
.partition { line -> (line.startsWith("a") || line.startsWith("b")) }
messages = input.first
ruleList = input.second
}
override suspend fun solveTask1(): Any? {
return countMatches(false)
}
override suspend fun solveTask2(): Any? {
return countMatches(true)
}
private fun countMatches(specialRules: Boolean): Int {
val rules = ruleList.map { line ->
val (no, rule) = line.split(": ")
no.toInt() to rule.split(" ").toMutableList()
}.toMap().toMutableMap()
reduceRule(rules, 11, specialRules)
for (rule in rules.keys.filter { it != 0 }) {
reduceRule(rules, rule, specialRules)
}
val regex = (rules[0] ?: error("missing rule no 0"))
.fold(StringBuilder()) { sb, s -> sb.append(s) }
.toString()
.toRegex()
var matches = 0
for (message in messages) {
if (message.matches(regex)) matches++
}
return matches
}
private val tokenRegex = Regex(""""[ab]"""")
private fun reduceRule(rules: MutableMap<Int, MutableList<String>>, ruleNo: Int, specialRules: Boolean) {
val rule: MutableList<String> = if (ruleNo == 11 && specialRules) {
// assumption: longest message has 88 chars
// rule 11 consists of at least 4 chars (11: 42 31 with 42 and 31 at least 2)
// worst case for 11: 42 11 31 -> 22x42 and 22x31
rules.remove(ruleNo)
val tempRule = mutableListOf<String>("(")
for (i in 1..22) {
tempRule.addAll(listOf("(", "(", "42", ")", "{$i}", "(", "31", ")", "{$i}", ")", "|"))
}
tempRule.removeLast()
tempRule.add(")")
tempRule
} else {
rules.remove(ruleNo).apply {
when {
isNullOrEmpty() -> return
first().matches(tokenRegex) -> replaceAll { it.substring(1, it.lastIndex) }
size > 1 -> apply { add(0, "("); add(")") }
}
}!!
}
if (ruleNo == 8 && specialRules) {
rule.add("+")
}
for ((_, oldRule) in rules) {
var index = oldRule.indexOf(ruleNo.toString())
while (index > -1) {
oldRule.removeAt(index)
oldRule.addAll(index, rule)
index = oldRule.indexOf(ruleNo.toString())
}
}
}
}
| 0 | Kotlin | 0 | 0 | 7e6241173959b9d838fa00f81fdeb39fdb3ef6fe | 3,017 | adventofcode-kotlin | MIT License |
src/Day02.kt | befrvnk | 574,229,637 | false | {"Kotlin": 15788} | enum class Hand(val points: Int) {
Rock(1), Paper(2), Scissor(3)
}
fun handFromValue(value: String): Hand {
return when (value) {
"A", "X" -> Hand.Rock
"B", "Y" -> Hand.Paper
"C", "Z" -> Hand.Scissor
else -> throw Exception("Unsupported value $value")
}
}
fun resultFromValue(value: String): Result {
return when (value) {
"X" -> Result.LOSS
"Y" -> Result.DRAW
"Z" -> Result.WIN
else -> throw Exception("Unsupported value $value")
}
}
fun Hand.forResult(result: Result): Hand {
return when (result) {
Result.DRAW -> this
Result.LOSS -> when (this) {
Hand.Rock -> Hand.Scissor
Hand.Paper -> Hand.Rock
Hand.Scissor -> Hand.Paper
}
Result.WIN -> when (this) {
Hand.Rock -> Hand.Paper
Hand.Paper -> Hand.Scissor
Hand.Scissor -> Hand.Rock
}
}
}
data class Round(
val opponent: Hand,
val own: Hand,
) {
private fun result(): Result {
return when {
opponent == Hand.Rock && own == Hand.Scissor -> Result.LOSS
opponent == Hand.Paper && own == Hand.Rock -> Result.LOSS
opponent == Hand.Scissor && own == Hand.Paper -> Result.LOSS
opponent == own -> Result.DRAW
else -> Result.WIN
}
}
fun points(): Int {
return own.points + result().points
}
}
enum class Result(val points: Int) {
LOSS(0), DRAW(3), WIN(6)
}
fun main() {
fun part1(input: List<String>): Int {
return input.map { line ->
Round(
opponent = handFromValue(line[0].toString()),
own = handFromValue(line[2].toString()),
)
}.sumOf { it.points() }
}
fun part2(input: List<String>): Int {
return input.map { line ->
val opponentHand = handFromValue(line[0].toString())
val result = resultFromValue(line[2].toString())
val ownHand = opponentHand.forResult(result)
Round(
opponent = opponentHand,
own = ownHand,
)
}.sumOf { it.points() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 68e5dd5656c052d8c8a2ea9e03c62f4cd2438dd7 | 2,480 | aoc-2022-kotlin | Apache License 2.0 |
src/Day03.kt | devheitt | 573,207,407 | false | {"Kotlin": 11944} | fun main() {
fun getPriority(repeated: Char): Int {
//Priorities
// a to z = 1 to 26
// A to Z = 27 to 52
val priority = if(repeated.code >= 97) {
repeated.code - 96
} else {
repeated.code - 64 + 26
}
return priority
}
fun part1(input: List<String>): Int {
var sum = 0
for(rucksack in input) {
val firstCompartment = rucksack.substring(0, rucksack.length / 2)
val secondCompartment = rucksack.substring( rucksack.length / 2)
firstCompartment
.filter { c -> secondCompartment.contains(c) }
.toSet()
.map { repeated -> sum += getPriority(repeated) }
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
var index = 0
while( index < input.size) {
val first = input[index++]
val second = input[index++]
val third = input[index++]
first
.filter { second.contains(it) && third.contains(it)}
.toSet()
.map { sum += getPriority(it) }
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
// check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
//println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a9026a0253716d36294709a547eaddffc6387261 | 1,502 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2020/ex10.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | import java.util.*
fun main() {
val input = readInputFile("aoc2020/input10")
val data = input.lines().map { it.toInt() }
val sorted = data.sorted()
val withActual = listOf(0) + sorted + (sorted.last() + 3)
require(withActual.size == withActual.toSet().size) { "size: $withActual set:${withActual.toSet()}" }
println(withActual)
val diffs = withActual.zipWithNext { a, b -> b - a }
val sortedDiffs = diffs.sorted()
require(sortedDiffs.first() >= 1)
require(sortedDiffs.last() <= 3)
println(sortedDiffs)
val ones = diffs.count { it == 1 }
val threes = diffs.count { it == 3 }
println("$ones, $threes")
println(ones * threes)
print(findOptions(withActual.first(), withActual.drop(1), withActual.last()))
}
val cache: MutableMap<Pair<Int, List<Int>>, Long> = mutableMapOf()
fun findOptions(start: Int, adapters: List<Int>, end: Int): Long {
println("start: $start, options: $adapters")
require(adapters.sorted() == adapters)
require(adapters.isEmpty() || adapters.first() != 0)
// require(adapters.last() == adapters[adapters.lastIndex - 1] + 3)
if (cache.contains(start to adapters)) {
println("from cache ${cache.getValue(start to adapters)}")
return cache.getValue(start to adapters)
}
if (adapters.isEmpty()&&end==start) return 1L.also{
println("calculated: start:$start, options: $adapters ans: 1")
}
if (adapters.isEmpty()||adapters.first() - start > 3) return 0L.also{
println("calculated: start:$start, options: $adapters ans: 0")
}
val ans = findOptions(start, adapters.drop(1), end) + findOptions(adapters.first(), adapters.drop(1), end)
cache[start to adapters] = ans
return ans.also {
println("calculated: start:$start, options: $adapters ans: $ans")
}
}
fun findOptions2(adapters: List<Int>): Int {
require(adapters.sorted() == adapters)
require(adapters.first() == 0)
require(adapters.last() == adapters[adapters.lastIndex - 1] + 3)
val used = Stack<Pair<Int, Int>>()
used.push(adapters.first() to 0)
val indexedAdapters = adapters.mapIndexed { index, i -> i to index }
val remainingOptions = indexedAdapters.toMutableList().apply { removeAt(0) }
var count = 0
fun backtrack() {
used.pop()
val last = used.pop()
remainingOptions.addAll(indexedAdapters.subList(last.second+1, indexedAdapters.size))
}
var iter = 0
while (true && iter < 1000000) {
iter++
//println("stack $used")
//println("remaining $remainingOptions")
//println("count $count")
if (remainingOptions.isEmpty()) {
println("found combination ${used.map { it.first }}")
count++
backtrack()
continue
}
if(used.isEmpty()) return count
val lastAdapter = used.peek()
if (remainingOptions.first().first - lastAdapter.first <= 3) {
used.push(remainingOptions.first())
remainingOptions.apply { removeAt(0) }
} else {
used.push(remainingOptions.first())
remainingOptions.apply { clear() }
backtrack()
}
}
return count
}
/***
* push
* if not valid pop2
* if is empty. validate, increment
* pop2 restore remaining from last pop from original array. if stack is empty, return
* remove first option
*
* 12345
* []
*
* 2345 - push
* 1
*
* 345
* 12
*
* 45
* 123
*
* 5
* 1234 -push
*
* []
* 12345 - is empty. validate, increment/or not
*
* 45
* 123 - pop2 restore remaining from last pop from original array
*
* 5
* 123 - remove first option
*
* 1235
*
* XXX
* 35
* 12
*
* 345
* 12
*
* 45
* 12
*
* 5
* 124
*
* 1245
*
* 45
* 12
*
* 5
* 12
*
* 125
*
* 2345
* 1
*
* 345
* 1
*
* 45
* 13
*
* 5
* 134
*
* 1345
*
* 45
* 13
*
* 5
* 13
*
* 135
*
* 345
* 1
*
* 45
* 1
*
* 5
* 14
*
* 145
*
* 45
* 1
*
* 5
* 1
*
* 15 - X . is empty validate, dont incement
*
* 12345 . pop 2 as usual. if stack is empty, return
* 0
*
* 2345
* 0
*
*/ | 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 4,128 | AOC-2021 | MIT License |
src/Day05.kt | RusticFlare | 574,508,778 | false | {"Kotlin": 78496} | fun main() {
fun part1(input: String): String {
val (initialState, steps) = input.split("\n\n")
val totalStacks = initialState.lines().last().split(" ").mapNotNull { it.toIntOrNull() }.last()
val stacks = (1..totalStacks).associateWith { mutableListOf<Char>() }
initialState.lines().forEach { line ->
stacks.forEach { (index, stack) ->
line.getOrNull((index * 4) - 3)?.takeIf { it.isLetter() }
?.let { stack.add(it) }
}
}
steps.lines().forEach { step ->
val (move, from, to) = step.split(" ").mapNotNull { it.toIntOrNull() }
repeat(times = move) {
stacks.getValue(to).add(index = 0, stacks.getValue(from).removeFirst())
}
}
return stacks.values.joinToString(separator = "") { it.first().toString() }
}
fun part2(input: String): String {
val (initialState, steps) = input.split("\n\n")
val totalStacks = initialState.lines().last().split(" ").mapNotNull { it.toIntOrNull() }.last()
val stacks = (1..totalStacks)
.associateWith { mutableListOf<Char>() }
initialState.lines().forEach { line ->
stacks.forEach { (index, stack) ->
line.getOrNull((index * 4) - 3)?.takeIf { it.isLetter() }
?.let { stack.add(it) }
}
}
steps.lines().forEach { step ->
val (move, from, to) = step.split(" ").mapNotNull { it.toIntOrNull() }
stacks.getValue(to).addAll(index = 0, stacks.getValue(from).take(move))
repeat(times = move) { stacks.getValue(from).removeFirst() }
}
return stacks.values.joinToString(separator = "") { it.first().toString() }
}
// test if implementation meets criteria from the description, like:
val testInput = readText("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readText("Day05")
check(part1(input) == "GFTNRBZPF")
println(part1(input))
check(part2(input) == "VRQWPDSGP")
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 10df3955c4008261737f02a041fdd357756aa37f | 2,151 | advent-of-code-kotlin-2022 | Apache License 2.0 |
23.kts | pin2t | 725,922,444 | false | {"Kotlin": 48856, "Go": 48364, "Shell": 54} | import kotlin.math.max
class Day23 {
val up = Pair(0, -1); val right = Pair(1, 0); val down = Pair(0, 1); val left = Pair(-1, 0)
val grid = ArrayList<String>()
var width = 0
var processed: BooleanArray = BooleanArray(0)
inline fun move(pos: Pair<Int, Int>, dir: Pair<Int, Int>): Pair<Int, Int> = Pair(pos.first + dir.first, pos.second + dir.second)
fun longest(from: Pair<Int, Int>, to: Pair<Int, Int>, steps: Int): Int {
if (from == to) return steps
processed[from.second * width + from.first] = true
var l = 0
fun tryMove(dir: Pair<Int, Int>) {
val next = move(from, dir);
if (next.first >= 0 && next.second >= 0 &&
next.first < grid[0].length && next.second < grid.size &&
grid[next.second][next.first] != '#' &&
!processed[next.second * width + next.first]) {
l = max(l, longest(next, to, steps + 1))
}
}
when (grid[from.second][from.first]) {
'>' -> tryMove(right); 'v' -> tryMove(down); '<' -> tryMove(left); '^' -> tryMove(up,)
'.' -> { tryMove(right); tryMove(down); tryMove(left); tryMove(up); }
else -> throw IllegalStateException()
}
processed[from.second * width + from.first] = false
return l
}
var result2 = 0
inline fun tryMove2(from: Pair<Int, Int>, dir: Pair<Int, Int>, to: Pair<Int, Int>, steps: Int) {
val next = move(from, dir);
if (grid[next.second][next.first] != '#' && !processed[next.second * width + next.first]) {
longest2(next, to, steps + 1)
}
}
fun longest2(from: Pair<Int, Int>, to: Pair<Int, Int>, steps: Int) {
if (from == to) {
result2 = max(result2, steps)
return
}
processed[from.second * width + from.first] = true
tryMove2(from, right, to, steps);
tryMove2(from, down, to, steps);
tryMove2(from, left, to, steps);
tryMove2(from, up, to, steps)
processed[from.second * width + from.first] = false
}
fun run() {
while (true) {
val line = readlnOrNull() ?: break
grid.add(line)
}
width = grid[0].length
processed = BooleanArray(grid.size * width) { false }
val start = Pair(1, 0); val end = Pair(grid[0].length - 2, grid.size - 1)
val result1 = longest(start, end, 0);
processed = BooleanArray(grid.size * width) { false }
processed[start.second * width + start.first] = true
longest2(Pair(1, 1), end, 1)
println(listOf(result1, result2))
}
}
Day23().run()
| 0 | Kotlin | 1 | 0 | 7575ab03cdadcd581acabd0b603a6f999119bbb6 | 2,692 | aoc2023 | MIT License |
src/Day02.kt | mpylypovych | 572,998,434 | false | {"Kotlin": 6455} | fun main() {
fun isDraw(a: Char, b: Char) = a - 'A' == b -'X'
fun isWin(a: Char, b: Char) : Boolean {
val opponent = a - 'A'
val my = b - 'X'
return (my - opponent == 1) || (my == 0 && opponent == 2)
}
fun score(a: Char) = a.minus('X') + 1
fun part1(input: List<String>) = input
.sumOf {
when {
isDraw(it.first(), it.last()) -> 3 + score(it.last())
isWin(it.first(), it.last()) -> 6 + score(it.last())
else -> score(it.last())
}
}
fun solve(input: String) = when (input.last()) {
'X' -> (input.first() - 'A' + 2) % 3 + 1
'Y' -> input.first() - 'A' + 1
else -> (input.first() -'A' + 1) % 3 + 1
}
fun part2(input: List<String>) = input.sumOf { solve(it) + it.last().minus('X') * 3 }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 733b35c3f4eea777a5f666c804f3c92d0cc9854b | 1,124 | aoc-2022-in-kotlin | Apache License 2.0 |
src/chapter5/section1/ex12_Alphabet_MSD.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter5.section1
import chapter2.swap
import kotlin.math.min
/**
* 基于字母表的高位优先字符串排序算法
*/
fun alphabetMSDSort(array: Array<String>, alphabet: Alphabet) {
val aux = Array(array.size) { "" }
alphabetMSDSort(array, alphabet, aux, 0, array.size - 1, 0)
}
private const val M = 10
private fun alphabetMSDSort(array: Array<String>, alphabet: Alphabet, aux: Array<String>, low: Int, high: Int, d: Int) {
if (high - low < M) {
msdInsertionSort(array, alphabet, low, high, d)
return
}
val count = IntArray(alphabet.R() + 2)
for (i in low..high) {
count[msdCharAt(array[i], alphabet, d) + 2]++
}
for (i in 1 until count.size) {
count[i] += count[i - 1]
}
for (i in low..high) {
val index = msdCharAt(array[i], alphabet, d) + 1
aux[count[index] + low] = array[i]
count[index]++
}
for (i in low..high) {
array[i] = aux[i]
}
for (i in 0 until alphabet.R()) {
alphabetMSDSort(array, alphabet, aux, low + count[i], low + count[i + 1] - 1, d + 1)
}
}
private fun msdCharAt(string: String, alphabet: Alphabet, d: Int): Int {
return if (d < string.length) alphabet.toIndex(string[d]) else -1
}
private fun msdInsertionSort(array: Array<String>, alphabet: Alphabet, low: Int, high: Int, d: Int) {
val msdComparator = MSDComparator(alphabet)
for (i in low + 1..high) {
for (j in i downTo low + 1) {
if (msdLess(array, msdComparator, j, j - 1, d)) {
array.swap(j, j - 1)
} else break
}
}
}
private fun msdLess(array: Array<String>, msdComparator: MSDComparator, i: Int, j: Int, d: Int): Boolean {
if (i == j) return false
val first = array[i]
val second = array[j]
return msdComparator.compare(first.substring(d, first.length), second.substring(d, second.length)) < 0
}
private class MSDComparator(private val alphabet: Alphabet) : Comparator<String> {
override fun compare(o1: String, o2: String): Int {
for (i in 0 until min(o1.length, o2.length)) {
val result = msdCharAt(o1, alphabet, i).compareTo(msdCharAt(o2, alphabet, i))
if (result != 0) return result
}
return o1.length - o2.length
}
}
fun main() {
val array = getMSDData()
alphabetMSDSort(array, Alphabet.EXTENDED_ASCII)
println(array.joinToString(separator = "\n"))
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 2,450 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/main/kotlin/day23/Day23.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day23
import execute
import readAllText
fun part1(input: String) = parse(input)
.let { elves -> (1..10).fold(elves, ::round) }
.let { elves ->
val rs = elves.minOf { it.first }..elves.maxOf { it.first }
val cs = elves.minOf { it.second }..elves.maxOf { it.second }
rs.sumOf { r -> cs.count { c -> (r to c) !in elves } }
}
fun part2(input: String) = parse(input)
.let { initial ->
var round = 1
var prev = initial
while (true) {
val next = round(prev, round)
if (next == prev) break
prev = next
round++
}
round
}
private fun parse(input: String) = input.lineSequence()
.flatMapIndexed { r, l -> l.flatMapIndexed { c, char -> if (char == '#') listOf(r to c) else emptyList() } }
.toSet()
fun Pos.adj() = sequence {
(first - 1..first + 1).forEach { r ->
(second - 1..second + 1).forEach { c ->
if (r != first || c != second) yield(r to c)
}
}
}
typealias Pos = Pair<Int, Int>
operator fun Pos.plus(o: Pos) = first + o.first to second + o.second
operator fun Pos.plus(o: Dir2) = this + o.v
enum class Dir2(val v: Pos) {
NW(-1 to -1), N(-1 to 0), NE(-1 to 1), W(0 to -1),
E(0 to 1), SW(1 to -1), S(1 to 0), SE(1 to 1)
}
enum class Dir(val look: List<Dir2>, val move: Dir2) {
N(listOf(Dir2.NW, Dir2.N, Dir2.NE), Dir2.N),
S(listOf(Dir2.SW, Dir2.S, Dir2.SE), Dir2.S),
W(listOf(Dir2.NW, Dir2.W, Dir2.SW), Dir2.W),
E(listOf(Dir2.NE, Dir2.E, Dir2.SE), Dir2.E),
}
fun round(elves: Set<Pos>, round: Int): Set<Pos> {
// println("== End of Round $round ==")
// println("starting: $elves")
val proposed = elves.associateWith { pos ->
if (pos.adj().none { it in elves }) pos
else (1..4).asSequence().map { Dir.values()[(it + round - 2) % 4] }.firstOrNull { dir ->
dir.look.none { (pos + it) in elves }
}?.let { dir -> pos + dir.move.v } ?: pos
}
// println("proposed: $proposed")
val conflicts = proposed.toList().groupBy { it.second }
// println("conflicts: $conflicts")
val resolved = conflicts.flatMap { (proposed, wanting) ->
if (wanting.size == 1) listOf(proposed)
else wanting.map { it.first }
}
// println("resolved: $resolved")
val result = resolved.toSet()
// println("result: $result")
// (-2..9).forEach { r->
// (-3..10).forEach { c->
// print(if (r to c in result) "#" else ".")
// }
// println()
// }
//
// println()
check(result.size == elves.size)
return result
}
fun main() {
val input = readAllText("local/day23_input.txt")
val test = """
....#..
..###.#
#...#.#
.#...##
#.###..
##.#.##
.#..#..
""".trimIndent()
execute(::part1, test, 110)
execute(::part1, input)
execute(::part2, test)
execute(::part2, input)
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 2,963 | advent-of-code-2022 | MIT License |
src/Day03.kt | MwBoesgaard | 572,857,083 | false | {"Kotlin": 40623} | fun main() {
fun part1(input: List<String>): Int {
val pointsByCharacter = generatePointsByCharacterMap()
return input.sumOf {
val firstCompartment = it.substring(0, it.length / 2).toSet()
val secondCompartment = it.substring(it.length / 2, it.length).toSet()
val misplacedItem = firstCompartment.intersect(secondCompartment).first()
pointsByCharacter[misplacedItem]!!
}
}
fun part2(input: List<String>): Int {
val pointsByCharacter = generatePointsByCharacterMap()
return input
.chunked(3)
.map {
it.map { elf -> elf.toSet() }
.reduce { combinedSets, elfSet -> combinedSets.intersect(elfSet) }
.first()
}
.sumOf { pointsByCharacter[it]!! }
}
printSolutionFromInputLines("Day03", ::part1)
printSolutionFromInputLines("Day03", ::part2)
}
fun generatePointsByCharacterMap(): Map<Char, Int> {
val alphabet = ('a'..'z').toList() + ('A'..'Z').toList()
val numbers = (1..alphabet.size + 1).toList()
return alphabet.zip(numbers).associate { it }
}
| 0 | Kotlin | 0 | 0 | 3bfa51af6e5e2095600bdea74b4b7eba68dc5f83 | 1,178 | advent_of_code_2022 | Apache License 2.0 |
src/Day7/Day7.kt | tomashavlicek | 571,148,715 | false | {"Kotlin": 23780} | package Day7
import readInput
class File(val name: String, val size: Int)
class Folder(val name: String, val subfolders: MutableList<Folder>, val files: MutableList<File>, val parent: Folder?) {
fun folderSize(): Int {
var size = files.sumOf { it.size }
return size + subfolders.sumOf { it.folderSize() }
}
fun findSubfolders(size: Int): List<Folder> {
val sizedFolders = subfolders.flatMap { it.findSubfolders(size) }
return if (folderSize() <= size) {
sizedFolders + this
} else {
sizedFolders
}
}
}
fun main() {
fun parseInput(input: List<String>): Folder? {
var current: Folder? = null
for (line in input) {
if (line == "\$ cd /") {
val root = Folder(name = "/", subfolders = mutableListOf(), files = mutableListOf(), parent = null)
current = root
} else if (line.startsWith("\$ cd ")) {
val where = line.substringAfter("\$ cd ")
if (where == "..") {
current = current?.parent
} else {
current = current?.subfolders?.first { it.name == where }
}
} else if (line == "\$ ls") {
// do nothing
} else {
val (first, second) = line.split(' ')
if (first == "dir") {
current?.subfolders?.add(Folder(name = second, mutableListOf(), mutableListOf(), parent = current))
} else {
current?.files?.add(File(name = second, size = first.toInt()))
}
}
}
while (current?.parent != null) {
current = current.parent
}
return current
}
fun part1(input: List<String>): Int {
val rootFolder = parseInput(input)
return rootFolder?.findSubfolders(100000)?.sumBy { it.folderSize() } ?: 0
}
fun part2(input: List<String>): Int {
val rootFolder = parseInput(input)
val diskSpace = 70000000
val updateSpace = 30000000
val freeSpace = diskSpace - rootFolder!!.folderSize()
val requiredSpace = updateSpace - freeSpace
return rootFolder.findSubfolders(Int.MAX_VALUE).filter { it.folderSize() >= requiredSpace }.minOf { it.folderSize() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day7/Day7_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day7/Day7")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 899d30e241070903fe6ef8c4bf03dbe678310267 | 2,669 | aoc-2022-in-kotlin | Apache License 2.0 |
solutions/src/main/kotlin/fr/triozer/aoc/y2022/Day08.kt | triozer | 573,964,813 | false | {"Kotlin": 16632, "Shell": 3355, "JavaScript": 1716} | package fr.triozer.aoc.y2022
import fr.triozer.aoc.utils.readInput
// #region part1
private fun part1(input: List<String>) = input.indices.sumOf { i ->
input[0].indices.count { j ->
val left = (j - 1 downTo 0).map { i to it }
val right = (j + 1 until input[0].length).map { i to it }
val up = (i - 1 downTo 0).map { it to j }
val down = (i + 1 until input.size).map { it to j }
listOf(left, right, up, down).any { trees ->
trees.all { (x, y) -> input[x][y] < input[i][j] }
}
}
}
// #endregion part1
// #region part2
private fun part2(input: List<String>) = input.indices.maxOf { i ->
input[0].indices.maxOf { j ->
val left = (j - 1 downTo 0).map { i to it }
val right = (j + 1 until input[0].length).map { i to it }
val up = (i - 1 downTo 0).map { it to j }
val down = (i + 1 until input.size).map { it to j }
listOf(left, right, up, down).map { trees ->
minOf(trees.takeWhile { (x, y) -> input[x][y] < input[i][j] }.size + 1, trees.size)
}.reduce(Int::times)
}
}
// #endregion part2
private fun main() {
val testInput = readInput(2022, 8, "test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
println("Checks passed ✅")
val input = readInput(2022, 8, "input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | a9f47fa0f749a40e9667295ea8a4023045793ac1 | 1,394 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/adventofcode/Day02.kt | keeferrourke | 434,321,094 | false | {"Kotlin": 15727, "Shell": 1301} | package com.adventofcode
/**
* [https://adventofcode.com/2021/day/2]
*/
enum class Command {
FORWARD, DOWN, UP;
companion object {
fun of(string: String) = when (string) {
"forward" -> FORWARD
"down" -> DOWN
"up" -> UP
else -> error("Unknown command")
}
}
}
private data class Position(val x: Int, val y: Int, val aim: Int)
fun commands(input: String): List<Pair<Command, Int>> = input.trim().lines()
.map {
val (first, second) = it.trim().split(" ", "\t")
Command.of(first) to second.toInt()
}
private fun diveBadly(pos: Position, command: Command, magnitude: Int): Position {
return when (command) {
Command.FORWARD -> pos.copy(x = pos.x + magnitude)
Command.UP -> pos.copy(y = pos.y - magnitude)
Command.DOWN -> pos.copy(y = pos.y + magnitude)
}
}
private fun diveCorrectly(pos: Position, command: Command, magnitude: Int): Position {
return when (command) {
Command.FORWARD -> pos.copy(x = pos.x + magnitude, y = pos.y + magnitude * pos.aim)
Command.UP -> pos.copy(aim = pos.aim - magnitude)
Command.DOWN -> pos.copy(aim = pos.aim + magnitude)
}
}
fun dive(commands: List<Pair<Command, Int>>, strategy: Strategy): Int = commands
.fold(Position(0, 0, 0)) { pos, (command, magnitude) ->
when (strategy) {
Strategy.BADLY -> diveBadly(pos, command, magnitude)
Strategy.CORRECTLY -> diveCorrectly(pos, command, magnitude)
}
}
.run { x * y }
enum class Strategy { BADLY, CORRECTLY }
fun day02(input: String, args: List<String> = listOf("p1")) {
when (args.first().lowercase()) {
"p1" -> println(dive(commands(input), Strategy.BADLY))
"p2" -> println(dive(commands(input), Strategy.CORRECTLY))
}
}
| 0 | Kotlin | 0 | 0 | 44677c6ae0ba1a8a8dc80dfa68c17b9c315af8e2 | 1,726 | aoc2021 | ISC License |
src/Day05.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | const val Empty = " "
data class Instruction(val count: Int, val from: Int, val to: Int)
typealias BucketsMap = MutableMap<Int, MutableList<Char>>
fun main() {
fun parseBuckets(input: List<String>): BucketsMap {
val stacks: BucketsMap = mutableMapOf()
outer@for (line in input) {
for ((i, chunk) in line.chunked(4).withIndex()) {
if (chunk == Empty) {
continue
}
val (_, s, _, _) = chunk.toCharArray()
if (s.isDigit()) {
break@outer
}
if (!stacks.containsKey(i+1)) {
stacks[i+1] = mutableListOf()
}
stacks[i+1]!!.add(s)
}
}
for ((_, v) in stacks) {
v.reverse()
}
return stacks
}
fun parseInstructions(input: List<String>): List<Instruction> {
val instructions = mutableListOf<Instruction>()
input.forEach {
if (it.startsWith("move")) {
val components = it.split(' ')
val instr = Instruction(
count = components[1].toInt(),
from = components[3].toInt(),
to = components[5].toInt(),
)
instructions.add(instr)
}
}
return instructions
}
fun getTopItems(buckets: BucketsMap): String {
return buckets.keys
.sorted()
.map{buckets[it]!!.last()}
.joinToString("")
}
fun part1(input: List<String>): String {
val buckets = parseBuckets(input)
val instructions = parseInstructions(input)
instructions.forEach {
(0 until it.count).forEach {
_ -> buckets[it.to]!!.add(buckets[it.from]!!.removeLast())
}
}
return getTopItems(buckets)
}
fun part2(input: List<String>): String {
val buckets = parseBuckets(input)
val instructions = parseInstructions(input)
instructions.forEach {
val lastN = buckets[it.from]!!.takeLast(it.count)
buckets[it.from] = buckets[it.from]!!.dropLast(it.count).toMutableList()
buckets[it.to]!! += lastN
}
return getTopItems(buckets)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 2,646 | aoc2022 | Apache License 2.0 |
src/Day04.kt | maciekbartczak | 573,160,363 | false | {"Kotlin": 41932} | fun main() {
fun part1(input: List<String>): Int {
return input
.map {
parsePair(it)
}
.sumOf {
checkFullOverlap(it)
}
}
fun part2(input: List<String>): Int {
return input
.map {
parsePair(it)
}.sumOf {
checkPartialOverlap(it)
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun parsePair(line: String): Pair<String, String> {
val pair = line.split(",")
return pair[0] to pair[1]
}
private fun checkFullOverlap(pair: Pair<String, String>): Int {
val firstRange = pair.first.toRange()
val secondRange = pair.second.toRange()
if (firstRange.overlaps(secondRange) || secondRange.overlaps(firstRange)) {
return 1
}
return 0
}
private fun checkPartialOverlap(pair: Pair<String, String>): Int {
val firstRange = pair.first.toRange()
val secondRange = pair.second.toRange()
if ((firstRange intersect secondRange).isNotEmpty()) {
return 1
}
return 0
}
private fun String.toRange(): IntRange {
val range = this.split("-")
.map { it.toInt() }
return IntRange(range[0], range[1])
}
private fun IntRange.overlaps(other: IntRange): Boolean {
return this.first >= other.first && this.last <= other.last
} | 0 | Kotlin | 0 | 0 | 53c83d9eb49d126e91f3768140476a52ba4cd4f8 | 1,527 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day11SeatingSystem.kt | Scavi | 68,294,098 | false | {"Java": 1449516, "Kotlin": 59149} | package com.scavi.brainsqueeze.adventofcode
import java.util.*
import kotlin.math.max
import kotlin.math.min
enum class Strategy { Plan, Reality }
class Day11SeatingSystem(val strategy: Strategy) {
private val empty = 'L'
private val occupied = '#'
private val floor = '.'
private val directions = listOf(Pair(+1, +1), Pair(+1, 0), Pair(-1, -1), Pair(0, +1),
Pair(-1, +1), Pair(0, -1), Pair(-1, 0), Pair(+1, -1))
fun solve(input: List<CharArray>): Int {
var areMoving = true
while (areMoving) {
val movement = LinkedList<Action>()
for (y in input.indices) {
for (x in input[0].indices) {
val lookup = lookAround(input, x, y)
when (input[y][x]) {
empty -> if (!lookup.containsKey(occupied)) {
movement.add(Action(occupied, x, y))
}
occupied -> if (occupied in lookup &&
(lookup[occupied]!! >= if (strategy == Strategy.Plan) 4 else 5)) {
movement.add(Action(empty, x, y))
}
}
}
}
for (move in movement) {
input[move.y][move.x] = move.change
}
areMoving = movement.size > 0
}
return input.map { it.count { item -> item == occupied } }.sum()
}
private fun lookAround(input: List<CharArray>, row: Int, col: Int): Map<Char, Int> {
val cache = mutableMapOf<Char, Int>()
if (strategy == Strategy.Plan) {
for (y in max(col - 1, 0)..min(col + 1, input.size - 1)) {
for (x in max(row - 1, 0)..min(row + 1, input[0].size - 1)) {
if (y != col || x != row) {
if (input[y][x] in cache) {
cache[input[y][x]] = cache[input[y][x]]!!.plus(1)
} else {
cache[input[y][x]] = 1
}
}
}
}
} else {
for (direction in directions) {
var x = row + direction.first
var y = col + direction.second
while (x >= 0 && x < input[0].size && y >= 0 && y < input.size) {
if (input[y][x] in cache) {
cache[input[y][x]] = cache[input[y][x]]!!.plus(1)
} else {
cache[input[y][x]] = 1
}
if (input[y][x] != floor) {
break
}
x += direction.first
y += direction.second
}
}
}
return cache
}
private data class Action(val change: Char, val x: Int, val y: Int)
}
| 0 | Java | 0 | 1 | 79550cb8ce504295f762e9439e806b1acfa057c9 | 2,927 | BrainSqueeze | Apache License 2.0 |
src/day02/Day02.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day02
import readInput
fun main() {
fun calculatePart1Score(input: List<String>): Int {
return input.toPart1Moves().sumOf { it.points }
}
fun calculatePart2Score(input: List<String>): Int {
val toPart2Moves = input.toPart2Moves()
return toPart2Moves.sumOf { it.points }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day02/Day02_test")
val part1TestPoints = calculatePart1Score(testInput)
val part2TestPoints = calculatePart2Score(testInput)
println("Part1 test points: $part1TestPoints")
println("Part2 test points: $part2TestPoints")
check(part1TestPoints == 15)
check(part2TestPoints == 12)
val input = readInput("/day02/Day02")
val part1Points = calculatePart1Score(input)
val part2Points = calculatePart2Score(input)
println("Part1 points: $part1Points")
println("Part2 points: $part2Points")
}
fun List<String>.toPart1Moves(): List<MovePart1> = map { it.toPart1Move() }
fun String.toPart1Move(): MovePart1 = split(" ").let { MovePart1(it[0].toHand(), it[1].toHand()) }
fun List<String>.toPart2Moves(): List<MovePart2> = map { it.toPart2Move() }
fun String.toPart2Move(): MovePart2 = split(" ").let { MovePart2(it[0].toHand(), it[1].toOutcome()) }
data class MovePart1(private val opponent: Hand, override val yourHand: Hand) : GameMove {
private val win: Boolean
get() = when {
opponent == Hand.Rock && yourHand == Hand.Paper ||
opponent == Hand.Paper && yourHand == Hand.Scissors ||
opponent == Hand.Scissors && yourHand == Hand.Rock -> true
else -> false
}
private val draw: Boolean
get() = opponent == yourHand
override val outcome: Outcome
get() = when {
win -> Outcome.Win
draw -> Outcome.Draw
else -> Outcome.Loss
}
}
data class MovePart2(private val opponent: Hand, override val outcome: Outcome) : GameMove {
override val yourHand: Hand
get() = when (outcome) {
Outcome.Win -> when (opponent) {
Hand.Rock -> Hand.Paper
Hand.Paper -> Hand.Scissors
Hand.Scissors -> Hand.Rock
}
Outcome.Draw -> when (opponent) {
Hand.Rock -> Hand.Rock
Hand.Paper -> Hand.Paper
Hand.Scissors -> Hand.Scissors
}
Outcome.Loss -> when (opponent) {
Hand.Rock -> Hand.Scissors
Hand.Paper -> Hand.Rock
Hand.Scissors -> Hand.Paper
}
}
}
interface GameMove {
val outcome: Outcome
val yourHand: Hand
val points: Int
get() = outcome.score + yourHand.score
}
enum class Hand(val score: Int) {
Rock(1), Paper(2), Scissors(3);
}
enum class Outcome(val score: Int) {
Win(6), Draw(3), Loss(0)
}
fun String.toHand(): Hand = when (this) {
"A", "X" -> Hand.Rock
"B", "Y" -> Hand.Paper
"C", "Z" -> Hand.Scissors
else -> error("don't know hand $this")
}
fun String.toOutcome(): Outcome = when (this) {
"X" -> Outcome.Loss
"Y" -> Outcome.Draw
"Z" -> Outcome.Win
else -> error("don't know outcome $this")
} | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 3,306 | advent-of-code-22-kotlin | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day8/Day8.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day8
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputLines
object Day8 : Day {
override val input = readInputLines(8).map { Line(it) }
override fun part1() = input.sumOf { it.countDirectSolution() }
override fun part2() = input.sumOf { it.sum() }
class Line(raw: String) {
private val patterns: List<String>
private val output: List<String>
init {
with(raw.split("|").map { it.trim() }.map { it.split(" ") }) {
patterns = first()
output = last()
}
}
fun countDirectSolution() = output.count { it.length in listOf(2, 3, 4, 7) }
fun sum() = patternMap().run { output.map { forDigit(it) }.joinToString("").toInt() }
private fun patternMap() = buildMap<Int, String>(10) {
patterns.groupBy { it.length }.let {
this[1] = it[2]!!.single()
this[7] = it[3]!!.single()
this[4] = it[4]!!.single()
this[8] = it[7]!!.single()
it[6]!!.forEach { pattern ->
when {
!pattern.containsAll(this[1]!!) -> this[6] = pattern
pattern.containsAll(this[4]!!) -> this[9] = pattern
else -> this[0] = pattern
}
}
it[5]!!.forEach { pattern ->
when {
pattern.containsAll(this[1]!!) -> this[3] = pattern
this[9]!!.containsAll(pattern) -> this[5] = pattern
else -> this[2] = pattern
}
}
}
}
}
private fun String.containsAll(other: String) = toList().containsAll(other.toList())
private fun String.isSame(str: String) = length == str.length && containsAll(str)
private fun Map<Int, String>.forDigit(digit: String) = entries.single { it.value.isSame(digit) }.key
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 2,059 | aoc2021 | MIT License |
src/Day14.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | import kotlin.math.max
fun main() {
fun solve(input: List<String>, withFloor: Boolean): Int {
val d = Array(200) { CharArray(1000) { '.' } }
var maxY = 0
input.forEach { line ->
line.split(" -> ")
.map {
val (x, y) = it.split(",").map(String::toInt)
x to y
}
.zipWithNext()
.forEach {
val (p0, p1) = it
for (x in rangeBetween(p0.first, p1.first)) {
for (y in rangeBetween(p0.second, p1.second)) {
d[y][x] = '#'
maxY = max(maxY, y)
}
}
}
}
if (withFloor) {
for (x in 0 until 1000) {
d[maxY + 2][x] = '#'
}
}
fun drop(x: Int, y: Int): Boolean {
return when {
y > 190 -> false
d[y + 1][x] == '.' -> drop(x, y + 1)
d[y + 1][x - 1] == '.' -> drop(x - 1, y + 1)
d[y + 1][x + 1] == '.' -> drop(x + 1, y + 1)
else -> {
d[y][x] = '+'
true
}
}
}
var count = 0
while (d[0][500] != '+' && drop(500, 0)) {
count++
}
return count
}
fun part1(input: List<String>) = solve(input, false)
fun part2(input: List<String>): Int = solve(input, true)
val testInput = readInputLines("Day14_test")
check(part1(testInput), 24)
check(part2(testInput), 93)
val input = readInputLines("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 1,762 | Advent-of-Code-2022 | Apache License 2.0 |
src/day02/Day02.kt | easchner | 572,762,654 | false | {"Kotlin": 104604} | package day02
import readInputString
fun main() {
fun part1(input: List<String>): Long {
var totalScore = 0L
// A(ZXY) B(XYZ) C(YZX)
// 036 036 036
val ptMap = mapOf(
"A" to mapOf("Z" to 0L, "X" to 3L, "Y" to 6L),
"B" to mapOf("X" to 0L, "Y" to 3L, "Z" to 6L),
"C" to mapOf("Y" to 0L, "Z" to 3L, "X" to 6L)
)
for (line in input) {
val hands = line.split(" ")
totalScore += when (hands[1]) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
totalScore += ptMap.getOrDefault(hands[0], mapOf())
.getOrDefault(hands[1], 0L)
}
return totalScore
}
fun part2(input: List<String>): Long {
var totalScore = 0L
// A(YZX) B(XYZ) C(ZXY)
// 123 123 123
val ptMap = mapOf(
"A" to mapOf("Y" to 1L, "Z" to 2L, "X" to 3L),
"B" to mapOf("X" to 1L, "Y" to 2L, "Z" to 3L),
"C" to mapOf("Z" to 1L, "X" to 2L, "Y" to 3L)
)
for (line in input) {
val hands = line.split(" ")
totalScore += when (hands[1]) {
"Y" -> 3
"Z" -> 6
else -> 0
}
totalScore += ptMap.getOrDefault(hands[0], mapOf())
.getOrDefault(hands[1], 0L)
}
return totalScore
}
val testInput = readInputString("day02/test")
val input = readInputString("day02/input")
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 15L)
println(part1(input))
check(part2(testInput) == 12L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 1,787 | Advent-Of-Code-2022 | Apache License 2.0 |
src/day2/Day02.kt | jorgensta | 573,824,365 | false | {"Kotlin": 31676} | package day2
import readInput
fun main() {
val rockPoints = 1
val paperPoints = 2
val scissorsPoints = 3
val rules = mapOf(
"B" to "A",
"C" to "B",
"A" to "C"
)
val mapshit = mapOf(
"X" to "A",
"Y" to "B",
"Z" to "C"
)
val points = mapOf(
"A" to rockPoints,
"B" to paperPoints,
"C" to scissorsPoints,
"X" to rockPoints,
"Y" to paperPoints,
"Z" to scissorsPoints
)
fun part1(input: List<String>): Int {
return input.map { it.split(" ") }.map {
var winDrawLose = 0
val opponent = it.first()
val me = mapshit[it.last()]
winDrawLose += points[me]!!
if (me == opponent) {
winDrawLose += 3
}
if (rules[opponent] == me) {
winDrawLose += 6
}
return@map winDrawLose
}.sum()
}
fun part2(input: List<String>): Int {
return input.map { it.split(" ") }.map {
var winDrawLose = 0
// if Rock (A) -> Draw, score = 4
// if Paper (B) -> Lose, score = 1
// if Scissor (C) -> WIN, score = 7
val me = mapshit[it.last()]
val action = it.last()
val opponent = it.first()
if (action == "Y") {
// make it a draw
winDrawLose += points[opponent]!! // i.e. if opponent choose Rock (A), give me the same points.
winDrawLose += 3
return@map winDrawLose// i.e. draw gets me 3 points
}
if (action == "Z") {
// make it a win
// it.key is the winning move, so we find it.value, and then take the key
val myMove = rules.filter { it.value == opponent }.firstNotNullOf { it.key }
winDrawLose += points[myMove]!!
winDrawLose += 6
return@map winDrawLose
}
if (action == "X") {
// Lose
// it.value is the losing move, so we find, get the key to lose.
val myMove = rules.filter { it.key == opponent }.firstNotNullOf { it.value }
winDrawLose += points[myMove]!!
return@map winDrawLose
}
return@map winDrawLose
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day2/Day02_test")
val partTwoTest = part2(testInput)
check(partTwoTest == 12)
val input = readInput("/day2/Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7243e32351a926c3a269f1e37c1689dfaf9484de | 2,712 | AoC2022 | Apache License 2.0 |
src/day20/Day20.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day20
import readInput
fun main() {
fun parse(input: List<String>): List<Number> {
return input.mapIndexed { i, line -> Number(line.toInt(), i) }
}
fun arrangeNumbers(numbers: List<Number>): MutableList<Number> {
val order = numbers.toMutableList()
numbers.forEach {currentNumber ->
val currentPos = order.indexOf(currentNumber)
order.removeAt(currentPos)
order.add((currentPos + currentNumber.value).mod(order.size), currentNumber)
}
return order
}
fun arrangeNumbers(numbers: List<BigNumber>, times: Int): MutableList<BigNumber> {
val order = numbers.toMutableList()
repeat(times) {
numbers.forEach {currentNumber ->
val currentPos = order.indexOf(currentNumber)
order.removeAt(currentPos)
order.add((currentPos + currentNumber.value).mod(order.size), currentNumber)
}
}
return order
}
fun part1(input: List<String>): Int {
val numbers = parse(input)
val rearrangedNumbers = arrangeNumbers(numbers)
val zeroIndex = rearrangedNumbers.indexOfFirst { it.value == 0 }
return rearrangedNumbers[(zeroIndex + 1000) % rearrangedNumbers.size].value +
rearrangedNumbers[(zeroIndex + 2000) % rearrangedNumbers.size].value +
rearrangedNumbers[(zeroIndex + 3000) % rearrangedNumbers.size].value
}
fun part2(input: List<String>): Long {
val numbers = parse(input).map { BigNumber(it.value * 811589153L, it.idx) }
val rearrangedNumbers = arrangeNumbers(numbers, 10)
val zeroIndex = rearrangedNumbers.indexOfFirst { it.value == 0L }
return rearrangedNumbers[(zeroIndex + 1000) % rearrangedNumbers.size].value +
rearrangedNumbers[(zeroIndex + 2000) % rearrangedNumbers.size].value +
rearrangedNumbers[(zeroIndex + 3000) % rearrangedNumbers.size].value
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day20/Day20_test")
val input = readInput("day20/Day20")
check((part1(testInput)).also { println(it) } == 3)
println(part1(input))
check(part2(testInput).also { println(it) } == 1623178306L)
println(part2(input))
}
data class Number(
val value: Int,
val idx: Int
)
data class BigNumber(
val value: Long,
val idx: Int
)
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 2,451 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day11.kt | AndreiShilov | 572,661,317 | false | {"Kotlin": 25181} | fun main() {
fun part1(input: List<String>): Long {
val monkeys = input.chunked(7).map { it.toMonkey() }.toList()
val lcm = monkeys.map { it.divider() }.reduce { acc, value ->
acc * value
}
println(lcm)
repeat(10000) {
monkeys.forEach {
it.round(monkeys, lcm)
}
}
monkeys.forEachIndexed { i, value ->
println("Monkey # $i have times ${value.timesInspected}")
}
val take = monkeys.map { it.timesInspected }.sortedDescending().take(2)
return take[0] * take[1]
}
fun part2(input: List<String>) {
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
println(part1(testInput))
// check(part1(testInput) == 10605L)
check(part1(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
// part2(input)
}
private fun List<String>.toMonkey(): Monkey {
val monkeyIndex = this[0].filter { it.isDigit() }[0].digitToInt().toLong() // probably we do not need it
val initialInspectionList =
this[1]
.split("Starting items: ")[1].split(",")
.map { it.trim() }
.map { it.toLong() }
.toMutableList()
val (sign, value) = this[2].replace(" Operation: new = old ", "").split(" ")
val divider = this[3].replace(" Test: divisible by ", "").toInt()
val tI = this[4].replace(" If true: throw to monkey ", "").toInt()
val fI = this[5].replace(" If false: throw to monkey ", "").toInt()
return Monkey(
inspectionQueue = initialInspectionList,
operation = getOperationFunc(sign, value),
decider = getDeciderFun(tI, fI),
divider
)
}
private fun getDeciderFun(trueIndex: Int, falseIndex: Int): (Boolean) -> Int {
return fun(result: Boolean): Int {
if (result) return trueIndex
return falseIndex
}
}
private fun getOperationFunc(sign: String, value: String): (Long) -> Long {
when (sign) {
"+" -> return fun(old: Long): Long {
if (value == "old") return old + old
return old + value.toInt()
}
"*" -> return fun(old: Long): Long {
if (value == "old") return old * old
return old * value.toInt()
}
}
throw NotImplementedError("Boom")
}
class Monkey(
private var inspectionQueue: MutableList<Long> = mutableListOf(),
private val operation: (Long) -> Long,
private val decider: (Boolean) -> Int,
private val divider: Int,
) {
var timesInspected = 0L
fun round(monkeys: List<Monkey>, lcm: Int = 3) {
timesInspected += inspectionQueue.size
inspectionQueue.forEach {
val newWorryLvl = operation(it) % lcm
// println(newWorryLvl)
monkeys[decider(newWorryLvl % divider == 0L)].addItem(newWorryLvl)
}
inspectionQueue = mutableListOf()
}
fun timesInspected() = timesInspected
fun divider() = divider
fun addItem(item: Long) {
inspectionQueue.add(item)
}
}
| 0 | Kotlin | 0 | 0 | 852b38ab236ddf0b40a531f7e0cdb402450ffb9a | 3,174 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day22/Day22.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day22
import groupByBlanks
import runDay
import stackOf
import toPair
import utils.Point
import utils.Ring
import java.util.function.Predicate
fun main() {
fun part1(input: List<String>) =
input.parse()
.let { (grid, instructions) ->
val initialX = grid[0].indexOf(MapTile.OPEN)
val startPosition = Position(Point(initialX, 0), Direction.RIGHT)
instructions.fold(startPosition) { position, instruction ->
when (instruction) {
is TurnLeft -> position.turnLeft()
is TurnRight -> position.turnRight()
is Move -> position.move(instruction.spaces, grid)
}
}
}.toScore()
fun part2(input: List<String>) =
input.parse().let { (grid, instructions) ->
val cube = grid.toCube()
val startPosition = Position(Point(0, 0), Direction.RIGHT)
instructions.fold(startPosition) { position, instruction ->
when (instruction) {
is TurnLeft -> position.turnLeft()
is TurnRight -> position.turnRight()
is Move -> position.move(instruction.spaces, cube)
}
}.let(cube::absoluteLocation)
}.toScore()
(object {}).runDay(
part1 = ::part1,
part1Check = 6032,
part2 = ::part2,
part2Check = 5031,
)
}
fun List<String>.parse() = groupByBlanks().toPair().let { (mapLines, instructionLines) ->
mapLines.toMap() to instructionLines.toInstructions()
}
fun Grid.toCube() = this.getSideLength().let { sideLength ->
val faces = this.findFaces(sideLength)
val box = BoxTemplate.from(faces)
Cube(
sideLength,
faces,
List(faces.size) { index -> box.getEdges(index) }
)
}
fun Grid.getSideLength(): Int {
val tileCheck = if (this[0][0] == MapTile.VOID) {
Predicate<MapTile> { it == MapTile.VOID }
} else {
Predicate<MapTile> { it != MapTile.VOID }
}
return kotlin.math.min(
this.takeWhile { tileCheck.test(it[0]) }.count(),
this[0].takeWhile { tileCheck.test(it) }.count(),
)
}
fun Grid.findFaces(sideLength: Int): List<Face> {
val faces = mutableListOf<Pair<Point, Face>>()
val start = Point(0, 0)
(indices step sideLength).forEach { yOffset ->
(this[yOffset].indices step sideLength).forEach { xOffset ->
val sideStart = start + Point(xOffset, yOffset)
if (sideStart in this && this[sideStart] != MapTile.VOID) {
val offset = Point(xOffset / sideLength, yOffset / sideLength)
faces.add(
sideStart to Face(
getFace(sideStart, sideLength),
offset,
)
)
}
}
}
return faces
.sortedWith(
compareBy<Pair<Point, Face>> { (point) -> point.y }
.thenBy { (point) -> point.x }
).map { it.second }
}
fun Grid.getFace(start: Point, sideLength: Int) =
subList(start.y, start.y + sideLength).map {
it.subList(start.x, start.x + sideLength)
}
class Cube(
private val sideLength: Int,
private val faces: List<Face>,
private val allEdges: List<Map<Direction, FaceSide>>
) {
private var currentSide = 0
private var currentFace = faces[currentSide]
private val end = sideLength - 1
fun tryMove(position: Position): Position? {
val next = position.next()
val nextPoint = next.point
return when {
(nextPoint !in currentFace) -> wrapAround(position)
currentFace[nextPoint] == MapTile.WALL -> null
currentFace[nextPoint] == MapTile.OPEN -> next
else -> wrapAround(position)
}
}
private fun wrapAround(position: Position): Position? {
val edges = allEdges[currentSide]
val nextSide = edges[position.direction]!!
val sideChange = position.direction to nextSide.edge
val nextPoint = translate(position.point, sideChange)
val nextFace = faces[nextSide.region]
return if (nextFace[nextPoint] != MapTile.WALL) {
val newDirection = when (sideChange.second) {
Direction.UP -> Direction.DOWN
Direction.DOWN -> Direction.UP
Direction.LEFT -> Direction.RIGHT
Direction.RIGHT -> Direction.LEFT
}
currentFace = nextFace
currentSide = nextSide.region
Position(nextPoint, newDirection)
} else {
null
}
}
private fun translate(point: Point, sideChange: Pair<Direction, Direction>) = with(point) {
when (sideChange) {
(Direction.UP to Direction.UP) -> {
Point(end - x, 0)
}
(Direction.DOWN to Direction.UP) -> {
Point(x, 0)
}
(Direction.LEFT to Direction.UP) -> {
Point(y, 0)
}
(Direction.RIGHT to Direction.UP) -> {
Point(end - y, 0)
}
(Direction.UP to Direction.DOWN) -> {
Point(x, end)
}
(Direction.DOWN to Direction.DOWN) -> {
Point(end - x, end)
}
(Direction.LEFT to Direction.DOWN) -> {
Point(end - y, end)
}
(Direction.RIGHT to Direction.DOWN) -> {
Point(y, end)
}
(Direction.UP to Direction.LEFT) -> {
Point(0, x)
}
(Direction.DOWN to Direction.LEFT) -> {
Point(0, end - x)
}
(Direction.LEFT to Direction.LEFT) -> {
Point(0, end - y)
}
(Direction.RIGHT to Direction.LEFT) -> {
Point(0, y)
}
(Direction.UP to Direction.RIGHT) -> {
Point(end, end - x)
}
(Direction.DOWN to Direction.RIGHT) -> {
Point(end, x)
}
(Direction.LEFT to Direction.RIGHT) -> {
Point(end, y)
}
(Direction.RIGHT to Direction.RIGHT) -> {
Point(end, end - y)
}
else -> throw IllegalArgumentException("Invalid side combination")
}
}
fun absoluteLocation(position: Position) = (faces[currentSide].offset * sideLength)
.let { offset ->
position.copy(
point = position.point + offset
)
}
}
operator fun Point.times(value: Int) = Point(
x = x * value,
y = y * value,
)
open class Face(
private val tiles: Grid,
val offset: Point,
) {
operator fun contains(point: Point) = point in tiles
operator fun get(point: Point) = tiles[point]
}
data class FaceSide(val region: Int, val edge: Direction)
val sides = Ring(Direction.UP, Direction.RIGHT, Direction.DOWN, Direction.LEFT)
class BoxTemplate {
enum class Side {
A, B, C, D, E, F;
}
private val Side.edges
get() = when (this) {
Side.A -> Ring(Edge.AD, Edge.AF, Edge.AB, Edge.AE)
Side.B -> Ring(Edge.AB, Edge.BF, Edge.BC, Edge.BE)
Side.C -> Ring(Edge.BC, Edge.CF, Edge.CD, Edge.CE)
Side.D -> Ring(Edge.CD, Edge.DF, Edge.AD, Edge.DE)
Side.E -> Ring(Edge.AE, Edge.BE, Edge.CE, Edge.DE)
Side.F -> Ring(Edge.AF, Edge.DF, Edge.CF, Edge.BF)
}
fun getEdgeDirections(side: Side) =
side.edges.iterator().asSequence().associateBy { edge -> edgeDirections[side to edge]!! }
enum class Edge(vararg sides: Side) {
AB(Side.A, Side.B), AD(Side.A, Side.D), AE(Side.A, Side.E), AF(Side.A, Side.F),
BC(Side.B, Side.C), BE(Side.B, Side.E), BF(Side.B, Side.F),
CD(Side.C, Side.D), CE(Side.C, Side.E), CF(Side.C, Side.F),
DE(Side.D, Side.E), DF(Side.D, Side.F);
private val sides: List<Side> = sides.toList()
fun otherSide(side: Side) = sides.find { it != side }!!
}
private val sidesToRegions = mutableMapOf<Side, Int>()
private val regionsToSides = mutableMapOf<Int, Side>()
private val edgesToFaceSides = mutableMapOf<Edge, Pair<FaceSide, FaceSide?>>()
private val edgeDirections = mutableMapOf<Pair<Side, Edge>, Direction>()
fun addFaceToSide(mapping: FaceMapping) {
val (edge, side, faceSide) = mapping
sidesToRegions[side] = faceSide.region
regionsToSides[faceSide.region] = side
val firstEdge = sides.find(faceSide.edge)
(1..4).fold(side.edges.find(edge) to firstEdge) { (boxEdge, faceEdge), _ ->
val newFaceSide = faceSide.copy(edge = faceEdge.value)
edgeDirections[side to boxEdge.value] = newFaceSide.edge
edgesToFaceSides[boxEdge.value] =
edgesToFaceSides[boxEdge.value]?.copy(second = newFaceSide) ?: (newFaceSide to null)
boxEdge.next to faceEdge.next
}
}
fun getEdges(region: Int) = regionsToSides[region]!!.let { side ->
side.edges.iterator().asSequence().associate {
val faceSides = edgesToFaceSides[it]!!
if (faceSides.first.region == region) {
faceSides.first.edge to faceSides.second!!
} else {
faceSides.second!!.edge to faceSides.first
}
}
}
data class FaceMapping(
val edge: Edge,
val side: Side,
val faceSide: FaceSide,
)
companion object {
fun from(faces: List<Face>): BoxTemplate {
val template = BoxTemplate()
val seen = mutableSetOf(0)
val queue = stackOf(FaceMapping(Edge.AD, Side.A, FaceSide(0, Direction.UP)))
while (queue.size > 0) {
val mapping = queue.removeFirst()
template.addFaceToSide(mapping)
seen.add(mapping.faceSide.region)
val edgeDirections = template.getEdgeDirections(mapping.side)
val face = faces[mapping.faceSide.region]
val potentialNeighbors = face.offset.neighbors
val neighbors = faces.mapIndexed { region, neighbor ->
region to neighbor
}.filter { (region, neighbor) ->
region !in seen && neighbor.offset in potentialNeighbors
}.map { (region, neighbor) ->
val edgeDirection = when (neighbor.offset) {
face.offset.copy(x = face.offset.x + 1) -> Direction.RIGHT
face.offset.copy(x = face.offset.x - 1) -> Direction.LEFT
face.offset.copy(y = face.offset.y + 1) -> Direction.DOWN
face.offset.copy(y = face.offset.y - 1) -> Direction.UP
else -> throw IllegalArgumentException()
}
val edge = edgeDirections[edgeDirection]!!
val otherSide = edge.otherSide(mapping.side)
FaceMapping(edge, otherSide, FaceSide(region, edgeDirection.opposite()))
}
queue.addAll(neighbors)
}
return template
}
}
}
val Point.neighbors
get() = setOf(
Point(x + 1, y),
Point(x - 1, y),
Point(x, y + 1),
Point(x, y - 1)
)
fun List<String>.toMap(): Grid = map { row ->
row.map {
when (it) {
' ' -> MapTile.VOID
'.' -> MapTile.OPEN
'#' -> MapTile.WALL
else -> throw IllegalArgumentException("Invalid Map Tile: $it")
}
}
}
fun List<String>.toInstructions() = flatMap { line ->
line.fold(mutableListOf<String>()) { chars, next ->
val last = chars.lastOrNull()
if (next.isDigit() && last?.lastOrNull()?.isDigit() == true) {
chars[chars.size - 1] = last + next
} else {
chars.add("$next")
}
chars
}
}.map {
it.toInstruction()
}
fun String.toInstruction() = when (this) {
"R" -> TurnRight
"L" -> TurnLeft
else -> Move(this.toInt())
}
enum class MapTile {
OPEN,
WALL,
VOID
}
typealias Grid = List<List<MapTile>>
sealed interface Instruction
object TurnLeft : Instruction
object TurnRight : Instruction
data class Move(val spaces: Int) : Instruction
enum class Direction(val unitOfMovement: Point, val value: Int) {
RIGHT(Point(1, 0), 0),
DOWN(Point(0, 1), 1),
LEFT(Point(-1, 0), 2),
UP(Point(0, -1), 3);
fun turnRight() = when (this) {
RIGHT -> DOWN
DOWN -> LEFT
LEFT -> UP
UP -> RIGHT
}
fun turnLeft() = when (this) {
RIGHT -> UP
UP -> LEFT
LEFT -> DOWN
DOWN -> RIGHT
}
fun opposite() = turnRight().turnRight()
}
data class Position(val point: Point, val direction: Direction) {
fun turnRight() = copy(direction = direction.turnRight())
fun turnLeft() = copy(direction = direction.turnLeft())
fun move(spaces: Int, grid: Grid): Position {
var lastValid = this
for (i in (1..spaces)) {
lastValid = grid.tryMove(lastValid) ?: break
}
return lastValid
}
fun move(spaces: Int, cube: Cube): Position {
var lastValid = this
for (i in (1..spaces)) {
lastValid = cube.tryMove(lastValid) ?: break
}
return lastValid
}
fun next() = copy(
point = point + direction.unitOfMovement
)
fun opposite() = copy(
direction = direction.opposite()
)
fun toScore() = this.point.let { (x, y) ->
1000L * (y + 1) + 4 * (x + 1) + this.direction.value
}
}
operator fun Grid.get(point: Point) = this[point.y][point.x]
operator fun Grid.contains(point: Point) =
point.y in this.indices && point.x in this[point.y].indices
fun Grid.tryMove(position: Position): Position? {
val next = position.next()
val nextPoint = next.point
return when {
(nextPoint !in this) -> wrapAround(position)
this[nextPoint] == MapTile.WALL -> null
this[nextPoint] == MapTile.OPEN -> next
else -> wrapAround(position)
}
}
fun Grid.wrapAround(position: Position): Position? {
var nextOpposite = position.opposite()
while (nextOpposite.point in this && this[nextOpposite.point] != MapTile.VOID) {
nextOpposite = nextOpposite.next()
}
return nextOpposite.opposite().next().let {
when (this[it.point]) {
MapTile.WALL -> null
else -> it
}
}
} | 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 14,813 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} |
fun main() {
val loss = 0
val draw = 3
val win = 6
val rock = 1
val paper = 2
val scissors = 3
// A for Rock, B for Paper, and C for Scissors
// X for Rock, Y for Paper, and Z for Scissors
fun part1(input: List<String>): Int {
val score = input
.map { line ->
val split = line.split(' ')
Pair(split[0][0], split[1][0])
}
.sumOf { pair ->
val result = when (pair) {
Pair('A', 'X') -> Pair(draw, rock)
Pair('B', 'Y') -> Pair(draw, paper)
Pair('C', 'Z') -> Pair(draw, scissors)
Pair('C', 'X') -> Pair(win, rock)
Pair('A', 'Y') -> Pair(win, paper)
Pair('B', 'Z') -> Pair(win, scissors)
Pair('B', 'X') -> Pair(loss, rock)
Pair('C', 'Y') -> Pair(loss, paper)
Pair('A', 'Z') -> Pair(loss, scissors)
else -> Pair(0, 0)
}
result.first + result.second
}
return score
}
// A for Rock, B for Paper, and C for Scissors
// X for loose, Y for draw, and Z for win
fun part2(input: List<String>): Int {
val score = input
.map { line ->
val split = line.split(' ')
Pair(split[0][0], split[1][0])
}
.sumOf { pair ->
val result = when (pair) {
Pair('A', 'X') -> Pair(loss, scissors)
Pair('A', 'Y') -> Pair(draw, rock)
Pair('A', 'Z') -> Pair(win, paper)
Pair('B', 'X') -> Pair(loss, rock)
Pair('B', 'Y') -> Pair(draw, paper)
Pair('B', 'Z') -> Pair(win, scissors)
Pair('C', 'X') -> Pair(loss, paper)
Pair('C', 'Y') -> Pair(draw, scissors)
Pair('C', 'Z') -> Pair(win, rock)
else -> Pair(0, 0)
}
result.first + result.second
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 12156)
check(part2(testInput) == 10835)
}
| 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 2,363 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/days/y2023/day08/Day08.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2023.day08
import java.math.BigInteger
import util.InputReader
typealias PuzzleLine = String
typealias PuzzleInput = List<PuzzleLine>
class Day08(val input: PuzzleInput) {
val nodes = input.drop(2).toNodes()
fun partOne(): Int {
val lr = input.first().toLR()
var currNode = nodes["AAA"]!!
var steps = 0
while (currNode.key != "ZZZ") {
steps += 1
val next = lr.next()
val nextNode = when (next) {
Direction.LEFT -> nodes[currNode.left]!!
Direction.RIGHT -> nodes[currNode.right]!!
}
currNode = nextNode
}
return steps
}
fun pathLength(start: Node): Int {
var length = 0
var currNode = start
val lr = input.first().toLR()
while (!currNode.key.endsWith("Z")) {
length += 1
val direction = lr.next()
currNode = when (direction) {
Direction.LEFT -> nodes[currNode.left]!!
Direction.RIGHT -> nodes[currNode.right]!!
}
}
return length
}
fun partTwo(): BigInteger {
val nodes = nodes.filter { it.key.endsWith("A") }.values.toList()
val periodLengths = nodes.map { pathLength(it) }.map { it.toBigInteger() }
println(periodLengths)
return periodLengths.leastCommonMultiple()
}
}
private fun List<BigInteger>.leastCommonMultiple(): BigInteger {
var lcm = this[0]
for (i in 1 until this.size) {
lcm = lcm.multiply(this[i]).divide(lcm.gcd(this[i]))
}
return lcm
}
enum class Direction {
LEFT, RIGHT
}
class NextLeftRight(
private val directions: List<Direction>,
) {
var i = -1
private var realI = 0L
fun next(): Direction {
i = (i + 1) % directions.size
realI += 1L
if (realI % 100000000L == 0L) {
println("We have taken $realI turns")
}
return directions[i]
}
}
fun String.toLR(): NextLeftRight {
val split = this.split("")
return NextLeftRight(split.filter { it.isNotBlank() }.map {
when (it) {
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> error("Unknown direction $it")
}
})
}
data class Node(
val key: String,
val left: String,
val right: String
)
fun List<String>.toNodes(): Map<String, Node> {
val nodes = mutableMapOf<String, Node>()
this.forEach { line ->
val split = line.split(" = ")
val name = split[0]
val (left, right) = split[1].removeSurrounding("(", ")").split(", ")
nodes[name] = Node(name, left, right)
}
return nodes
}
fun main() {
val year = 2023
val day = 8
val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day)
val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day)
val exampleInput2: PuzzleInput = InputReader.getExampleLines(year, day, "example2")
fun partOne(input: PuzzleInput) = Day08(input).partOne()
fun partTwo(input: PuzzleInput) = Day08(input).partTwo()
println("Example 1: ${partOne(exampleInput)}")
println("Part 1: ${partOne(puzzleInput)}")
println("Example 2: ${partTwo(exampleInput2)}")
println("Part 2: ${partTwo(puzzleInput)}")
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 3,332 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day08.kt | thomasreader | 573,047,664 | false | {"Kotlin": 59975} | import java.util.function.Predicate
fun main() {
val testInput = """
30373
25512
65332
33549
35390
""".trimIndent()
.split("\n")
val testResult = inputToMatrix(testInput)
check(partOne(testResult) == 21)
val input = inputToMatrix(readInput("Day08.txt"))
println(partOne(input))
check(partTwo(testResult) == 8)
println(partTwo(input))
}
fun partOne(intMatrix: IntMatrix): Int {
val edgeTrees = intMatrix.rows * 2 + intMatrix.columns * 2 - 4
var interiorTrees = 0
for (r in 1..intMatrix.rows - 2) {
for (c in 1..intMatrix.columns - 2) {
val row = intMatrix.getRow(r).toList()
val column = intMatrix.getColumn(c).toList()
val thisHeight = intMatrix[r, c]
val leftMax = row.subList(0, c).max()
val rightMax = row.subList(c+1, intMatrix.columns).max()
val topMax = column.subList(0, r).max()
val bottomMax = column.subList(r+1, intMatrix.rows).max()
if (thisHeight > leftMax || thisHeight > rightMax || thisHeight > topMax || thisHeight > bottomMax) {
interiorTrees++
}
}
}
return edgeTrees + interiorTrees
}
fun partTwo(intMatrix: IntMatrix): Int {
var highestScore = 0
for (r in 0 until intMatrix.rows) {
for (c in 0 until intMatrix.columns) {
val row = intMatrix.getRow(r).toList()
val column = intMatrix.getColumn(c).toList()
val thisHeight = intMatrix[r, c]
val left = row.subList(0, c)
val right = row.subList(c+1, intMatrix.columns)
val top = column.subList(0, r)
val bottom = column.subList(r+1, intMatrix.rows)
val predicate: (Int) -> Boolean = { it >= thisHeight }
val leftTreesVisible = (left.indexOfLast(predicate)).let {
if (it == -1) c else c - it
}
val rightTreesVisible = (right.indexOfFirst(predicate)).let {
if (it == -1) intMatrix.columns - c - 1 else it + 1
}
val topTreesVisible = (top.indexOfLast(predicate)).let {
if (it == -1) r else r - it
}
val bottomTreesVisible = (bottom.indexOfFirst(predicate)).let {
if (it == -1) intMatrix.rows - r - 1 else it + 1
}
val scenicScore = leftTreesVisible * rightTreesVisible * topTreesVisible * bottomTreesVisible
if (scenicScore > highestScore) {
highestScore = scenicScore
}
}
}
return highestScore
}
class IntMatrix(
private val internalMatrix: Array<IntArray>
) {
private val columnMatrix = internalMatrix.getColumns()
val rows: Int get() = internalMatrix.size
val columns: Int get() = internalMatrix[0].size
operator fun set(row: Int, column: Int, value: Int) {
internalMatrix[row][column] = value
}
operator fun get(row: Int, column: Int): Int {
return internalMatrix[row][column]
}
fun getRow(row: Int) = internalMatrix[row]
fun getColumn(column: Int) = columnMatrix[column]
private fun Array<IntArray>.getColumns(): Array<IntArray> {
val numCols = this[0].size
val numRows = this.size
return Array(numCols) { col ->
IntArray(numRows) { row ->
this[row][col]
}
}
}
override fun toString(): String {
return buildString(internalMatrix.size * (internalMatrix[0].size - 1) * 3 + 3) {
internalMatrix.forEachIndexed { index, row ->
append(row.contentToString())
if (index - 1 < internalMatrix.size) {
append("\n")
}
}
}
}
}
//private fun inputToList(src: List<String>): List<List<Int>> = src.map { s ->
// s.toCharArray().map { c -> c.digitToInt() }
//}
private fun inputToMatrix(src: List<String>): IntMatrix {
return Array<IntArray>(src.size) { row ->
val chars = src[row].toCharArray()
IntArray(chars.size) { cols ->
chars[cols].digitToInt()
}
}.let { IntMatrix(it) }
} | 0 | Kotlin | 0 | 0 | eff121af4aa65f33e05eb5e65c97d2ee464d18a6 | 4,226 | advent-of-code-2022-kotlin | Apache License 2.0 |
2022/src/main/kotlin/Day24.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day24 {
fun part1(input: String): Int {
val board = parseInput(input)
return 1 + shortestPath(board, Point(0, -1), Point(board.width - 1, board.height - 1), 0)
}
fun part2(input: String): Int {
val board = parseInput(input)
val start1 = Point(0, -1)
val end1 = Point(board.width - 1, board.height - 1)
val start2 = Point(board.width - 1, board.height)
val end2 = Point(0, 0)
val there = 1 + shortestPath(board, start1, end1, 0)
val back = 1 + shortestPath(board, start2, end2, there)
return 1 + shortestPath(board, start1, end1, back)
}
private fun shortestPath(board: Board, start: Point, end: Point, startMinute: Int): Int {
val (_, width, height) = board
val configurations = getAllConfigurations(board)
val cycleSize = configurations.size
val initialState = State(startMinute, start)
val queue = mutableListOf(initialState)
val explored = mutableSetOf(initialState.toExploredState(cycleSize))
while (queue.isNotEmpty()) {
val (minute, position) = queue.removeFirst()
// We reached the end!
if (position == end) {
return minute
}
val nextConfig = configurations[(minute + 1) % cycleSize]
val nextStates = listOf(
position.copy(x = position.x + 1),
position.copy(y = position.y + 1),
position.copy(x = position.x - 1),
position.copy(y = position.y - 1),
position
).filter {
(it.x in 0 until width
&& it.y in 0 until height
&& it !in nextConfig)
|| it == start
}
.map { State(minute + 1, it) }
.filter { it.toExploredState(cycleSize) !in explored }
explored.addAll(nextStates.map { it.toExploredState(cycleSize) })
queue.addAll(nextStates)
}
throw IllegalStateException("Could not find path")
}
private fun getAllConfigurations(board: Board): List<Set<Point>> {
var curr = board
val boards = mutableListOf(blizzardPoints(curr))
while(true) {
curr = cycleBlizzard(curr)
val currPoints = blizzardPoints(curr)
if (currPoints !in boards) {
boards.add(currPoints)
}
else {
return boards
}
}
}
private fun blizzardPoints(board: Board) = board.blizzards.map { it.point }.toSet()
private fun cycleBlizzard(board: Board): Board {
return board.copy(
blizzards = board.blizzards.map {
it.copy(
point = when (it.direction) {
Direction.NORTH -> it.point.copy(y = (it.point.y - 1 + board.height) % board.height)
Direction.EAST -> it.point.copy(x = (it.point.x + 1) % board.width)
Direction.SOUTH -> it.point.copy(y = (it.point.y + 1) % board.height)
Direction.WEST -> it.point.copy(x = (it.point.x - 1 + board.width) % board.width)
}
)
}.toSet()
)
}
private fun parseInput(input: String): Board {
val blizzards = mutableSetOf<Blizzard>()
val lines = input.splitNewlines()
lines
.drop(1)
.dropLast(1)
.forEachIndexed { y: Int, line: String ->
line.drop(1).dropLast(1)
.mapIndexed { x, c ->
val direction = when (c) {
'^' -> Direction.NORTH
'>' -> Direction.EAST
'v' -> Direction.SOUTH
'<' -> Direction.WEST
else -> null
}
if (direction != null) {
blizzards.add(Blizzard(Point(x, y), direction))
}
}
}
return Board(
blizzards = blizzards,
width = lines[0].length - 2,
height = lines.size - 2
)
}
private enum class Direction { NORTH, EAST, SOUTH, WEST }
private data class Board(val blizzards: Set<Blizzard>, val width: Int, val height: Int)
private data class Blizzard(val point: Point, val direction: Direction)
private data class State(val minute: Int, val position: Point) {
fun toExploredState(cycleSize: Int) = ExploredState(minute % cycleSize, position)
}
// Same as State, only module the cycle size so you can tell when you've repeated yourself
private data class ExploredState(val cycle: Int, val position: Point)
private data class Point(val x: Int, val y: Int)
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 4,274 | advent-of-code | MIT License |
src/Day13.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | sealed interface Data : Comparable<Data>
class IntData(val value: Int) : Data {
override fun compareTo(other: Data): Int {
return if (other is IntData) {
value.compareTo(other.value)
} else {
-other.compareTo(this)
}
}
override fun toString() = value.toString()
}
class ListData(val values: List<Data>) : Data {
override fun compareTo(other: Data): Int {
val otherValues = if (other is ListData) other.values else listOf(other)
for (i in values.indices) {
if (i >= otherValues.size) {
return 1
}
val compareItems = values[i].compareTo(otherValues[i])
if (compareItems != 0) {
return compareItems
}
}
return values.size.compareTo(otherValues.size)
}
override fun toString() = values.joinToString(prefix="[", postfix = "]")
}
fun main() {
fun parse(line: String): Data {
var position = 0
fun parseChunk(): Data {
if (line[position] == '[') {
val values = mutableListOf<Data>()
while (true) {
position++ // [ or ,
if (line[position] != ']') {
values += parseChunk()
}
if (line[position] == ']') {
position++
return ListData(values)
}
}
} else {
val start = position
while (line[position].isDigit()) position++
return IntData(line.substring(start, position).toInt())
}
}
return parseChunk()
}
fun part1(input: String): Int {
return input.split("\n\n")
.map { group ->
val (left, right) = group.split("\n").map { parse(it) }
left <= right
}
.asSequence()
.withIndex()
.filter { it.value }
.sumOf { it.index + 1 }
}
fun part2(input: String): Int {
val divider1 = parse("[[2]]")
val divider2 = parse("[[6]]")
val all = input.lines()
.filter { it.isNotEmpty() }
.map { parse(it) }
.toMutableList()
.apply {
add(divider1)
add(divider2)
sort()
}
return (all.indexOf(divider1) + 1) * (all.indexOf(divider2) + 1)
}
val testInput = readInput("Day13_test")
check(part1(testInput), 13)
check(part2(testInput), 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 2,722 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day05.kt | leeturner | 572,659,397 | false | {"Kotlin": 13839} | typealias Stack = ArrayDeque<Char>
val numbersInInstructionRegex = """\d+""".toRegex()
data class Instruction(val num: Int, val from: Int, val to: Int)
fun List<String>.parseStacks(): MutableList<Stack> {
val numberOfStacks =
this.takeWhile { it.trim().isNotEmpty() }.last().last { it.isDigit() }.digitToInt()
val stacks = MutableList(numberOfStacks) { Stack() }
this.filter { it.contains('[') }
.reversed()
.map { it.chunked(4).map { item -> item[1] } }
.forEach {
it.forEachIndexed { index, item ->
if (!item.isWhitespace()) {
stacks[index].add(item)
}
}
}
return stacks
}
fun List<String>.parseInstructions(): List<Instruction> =
this.dropWhile { it.isNotEmpty() }
.drop(1)
.map {
val (num, from, to) =
numbersInInstructionRegex
.findAll(it)
.map { instruction -> instruction.value.toInt() }
.toList()
Instruction(num, from - 1, to - 1)
}
fun MutableList<Stack>.peekTopItems(): String {
return map { stack -> stack.last() }.joinToString(separator = "")
}
object Crane {
fun moveCrateMover9000(stacks: MutableList<Stack>, instruction: Instruction) {
repeat(instruction.num) { stacks[instruction.to].add(stacks[instruction.from].removeLast()) }
}
fun moveCrateMover9001(stacks: MutableList<Stack>, instruction: Instruction) {
val temp: MutableList<Char> = mutableListOf()
repeat(instruction.num) { temp.add(stacks[instruction.from].removeLast()) }
temp.reversed().forEach { stacks[instruction.to].add(it) }
}
}
fun main() {
fun part1(input: List<String>): String {
val stacks = input.parseStacks()
input.parseInstructions().forEach { Crane.moveCrateMover9000(stacks, it) }
return stacks.peekTopItems()
}
fun part2(input: List<String>): String {
val stacks = input.parseStacks()
input.parseInstructions().forEach { Crane.moveCrateMover9001(stacks, it) }
return stacks.peekTopItems()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8da94b6a0de98c984b2302b2565e696257fbb464 | 2,323 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2023/Day12.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 12 -Hot Springs
* Problem Description: http://adventofcode.com/2023/day/12
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day12/
*/
package com.ginsberg.advent2023
class Day12(private val input: List<String>) {
fun solvePart1(): Long =
input
.map { parseRow(it) }
.sumOf { (springs, damage) -> countArrangements(springs, damage) }
fun solvePart2(): Long =
input
.map { parseRow(it) }
.map { unfold(it) }
.sumOf { (springs, damage) -> countArrangements(springs, damage) }
private fun countArrangements(
springs: String,
damage: List<Int>,
cache: MutableMap<Pair<String, List<Int>>, Long> = HashMap()
): Long {
val key = springs to damage
cache[key]?.let {
return it
}
if (springs.isEmpty()) return if (damage.isEmpty()) 1 else 0
return when (springs.first()) {
'.' -> countArrangements(springs.dropWhile { it == '.' }, damage, cache)
'?' -> countArrangements(springs.substring(1), damage, cache) +
countArrangements("#${springs.substring(1)}", damage, cache)
'#' -> when {
damage.isEmpty() -> 0
else -> {
val thisDamage = damage.first()
val remainingDamage = damage.drop(1)
if (thisDamage <= springs.length && springs.take(thisDamage).none { it == '.' }) {
when {
thisDamage == springs.length -> if (remainingDamage.isEmpty()) 1 else 0
springs[thisDamage] == '#' -> 0
else -> countArrangements(springs.drop(thisDamage + 1), remainingDamage, cache)
}
} else 0
}
}
else -> throw IllegalStateException("Invalid springs: $springs")
}.apply {
cache[key] = this
}
}
private fun unfold(input: Pair<String, List<Int>>): Pair<String, List<Int>> =
(0..4).joinToString("?") { input.first } to (0..4).flatMap { input.second }
private fun parseRow(input: String): Pair<String, List<Int>> =
input.split(" ").run {
first() to last().split(",").map { it.toInt() }
}
}
| 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 2,455 | advent-2023-kotlin | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2020/d01/Day01.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2020.d01
import com.groundsfam.advent.DATAPATH
import kotlin.io.path.div
import kotlin.io.path.useLines
fun findTwoSum(nums: List<Int>, target: Int): Pair<Int, Int>? {
nums
.groupBy { it }
.mapValues { (_, v) -> v.size }
.let { countsMap ->
countsMap.forEach { (num, count) ->
when {
num * 2 == target && count > 1 -> return num to num
target - num in countsMap -> return num to target - num
}
}
}
return null
}
fun findSumSlow(nums: List<Int>, target: Int, n: Int): List<Int>? {
val list = MutableList(n) { 0 }
fun helper(from: Int, subTarget: Int, subN: Int): Boolean {
if (subN == 0) return subTarget == 0
if (from >= nums.size) return false
(from until nums.size).forEach { i ->
if (helper(from = i + 1, subTarget = subTarget - nums[i], subN = subN - 1)) {
list[n - subN] = nums[i]
return true
}
}
return false
}
if (helper(0, target, n)) return list
return null
}
fun main() {
val input = (DATAPATH / "2020/day01.txt").useLines { lines ->
lines.map { it.toInt() }.toList()
}
findTwoSum(input, 2020)
?.let { (n1, n2) ->
println("first part: ${n1 * n2}")
} ?: println("first part: not found :(")
findSumSlow(input, 2020, 3)
?.fold(1) { x, y -> x*y }
?. also { println("second part: $it") }
?: println("second part: not found :(")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 1,604 | advent-of-code | MIT License |
src/Day03.kt | erikthered | 572,804,470 | false | {"Kotlin": 36722} | fun main() {
fun part1(input: List<String>): Int {
val pointMap = pointValues()
var points = 0
for(line in input) {
val h1 = line.substring(0..line.lastIndex/2)
val h2 = line.substring(line.lastIndex/2 + 1)
val overlap = h1.toCharArray().intersect(h2.toCharArray().asIterable().toSet())
points += overlap.sumOf { pointMap[it]!! }
}
return points
}
fun part2(input: List<String>): Int {
val pointMap = pointValues()
var points = 0
input.windowed(3, 3).forEach { group ->
val badge = group[0].toCharArray().intersect(group[1].toSet()intersect(group[2].toSet())).single()
points += pointMap[badge]!!
}
return points
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun pointValues(): Map<Char, Int> {
var points = 1
return ('a'.rangeTo('z') + 'A'.rangeTo('Z')).associate {
val pair = it to points
points += 1
pair
}
}
| 0 | Kotlin | 0 | 0 | 3946827754a449cbe2a9e3e249a0db06fdc3995d | 1,261 | aoc-2022-kotlin | Apache License 2.0 |
src/Day07.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | fun main() {
fun log(message: Any?) {
println(message)
}
class Dir(val name: String, val parent: Dir? = null) {
val childDirs: MutableList<Dir> = mutableListOf()
var fileSize: Int = 0
val fileSizeRecursive: Int get() = fileSize + childDirs.sumOf { it.fileSizeRecursive }
override fun toString(): String =
"Dir(\"$name\", ${parent?.name}, $fileSize, $fileSizeRecursive, [${childDirs.joinToString { it.name }}])"
}
fun parts(input: List<String>, part: Int = 1): Int {
val rootDir = Dir("/")
var cwd: Dir = rootDir
val dirs: MutableList<Dir> = mutableListOf()
dirs.add(rootDir)
input.forEach { cmd ->
// log("INS $cmd")
when {
// 123 filename
cmd[0].isDigit() -> {
val fileSize: Int = cmd.substringBefore(" ").toInt()
cwd.fileSize += fileSize
}
// dir dirName, don't care (we'll handle them on cd only)
cmd.startsWith("dir ") -> {}
// $ ls, don't care, we'll pick up the file sizes anyway
cmd.startsWith("$ ls") -> {}
// cd [/|..|dirname]
cmd.startsWith("$ cd ") -> {
val dirName = cmd.substringAfter("$ cd ")
cwd = when (dirName) {
"/" -> rootDir
".." -> (if (cwd.parent != null) cwd.parent else cwd)!!
else -> Dir(dirName, cwd).apply {
cwd.childDirs.add(this)
dirs.add(this)
}
}
}
// wtf
else -> error("CMD $cmd")
}
}
// log("DIRS $dirs")
val smallerDirs = dirs.filter { it.fileSizeRecursive <= 100000 }.map { it.name }
// log("SMALL ${smallerDirs.joinToString()}")
return when (part) {
1 -> dirs.filter { it.fileSizeRecursive <= 100000 }.sumOf { it.fileSizeRecursive }
2 -> {
val diskMax = 70000000
val need = 30000000
val unused = diskMax - rootDir.fileSizeRecursive
val missingSpace = need - unused
// log("BIG ENUF ${dirs.filter { it.fileSizeRecursive > missingSpace }}")
val delDir = dirs.filter { it.fileSizeRecursive > missingSpace }.map { it.fileSizeRecursive }.min()
// log("DEL DIR size $delDir")
delDir
}
else -> error("PART WUT? $part")
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test.txt")
check(parts(testInput) == 95437)
check(parts(testInput, 2) == 24933642)
val input = readInput("Day07.txt")
println(parts(input))
check(parts(input) == 1444896)
println(parts(input, 2))
check(parts(input, 2) == 404395)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 3,044 | aoc2022 | Apache License 2.0 |
src/day08/Day08.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day08
import readInput
import kotlin.math.min
fun main() {
fun part1(grid: List<List<Int>>): Int {
val rowSize = grid.size
val columnSize = grid[0].size
val rowRange = (0 until rowSize)
val columnRange = (0 until columnSize)
val visibleMap = Array(rowSize) { BooleanArray(columnSize) { false } }
columnRange.forEach { column ->
visibleMap[0][column] = true
visibleMap[visibleMap.lastIndex][column] = true
}
rowRange.forEach { row ->
visibleMap[row][0] = true
visibleMap[row][visibleMap[0].lastIndex] = true
}
rowRange.drop(1).dropLast(1).forEach { row ->
// From left
var maxLeftHeight = grid[row][0]
columnRange.drop(1).dropLast(1).forEach { column ->
if (grid[row][column] > maxLeftHeight) {
visibleMap[row][column] = true
maxLeftHeight = grid[row][column]
}
}
// From right
var maxRightHeight = grid[row][columnSize - 1]
columnRange.drop(1).dropLast(1).reversed().forEach { column ->
if (grid[row][column] > maxRightHeight) {
visibleMap[row][column] = true
maxRightHeight = grid[row][column]
}
}
}
columnRange.drop(1).dropLast(1).forEach { column ->
// From top
var maxTopHeight = grid[0][column]
rowRange.drop(1).dropLast(1).forEach { row ->
if (grid[row][column] > maxTopHeight) {
visibleMap[row][column] = true
maxTopHeight = grid[row][column]
}
}
// From bottom
var maxBottomHeight = grid[rowSize - 1][column]
rowRange.drop(1).dropLast(1).reversed().forEach { row ->
if (grid[row][column] > maxBottomHeight) {
visibleMap[row][column] = true
maxBottomHeight = grid[row][column]
}
}
}
return visibleMap.sumOf { it.count { it } }
}
fun countVisibleTrees(height: Int, trees: List<Int>): Int {
var treeIndex = 0
while (treeIndex <= trees.lastIndex && height > trees[treeIndex]) {
treeIndex++
}
return min(treeIndex, trees.lastIndex) + 1
}
fun part2(grid: List<List<Int>>): Int {
var maxScenicScore = 0
val rowSize = grid.size
val columnSize = grid[0].size
val rowRange = (0 until rowSize)
val columnRange = (0 until columnSize)
rowRange.drop(1).dropLast(1).forEach { row ->
columnRange.drop(1).dropLast(1).forEach { column ->
val columns = grid.map { it[column] }
val leftTrees = grid[row].slice(0 until column)
val rightTrees = grid[row].slice(column + 1 until columnSize)
val topTrees = columns.slice(0 until row)
val bottomTrees = columns.slice(row + 1 until rowSize)
val leftScore = countVisibleTrees(grid[row][column], leftTrees.reversed())
val rightScore = countVisibleTrees(grid[row][column], rightTrees)
val topScore = countVisibleTrees(grid[row][column], topTrees.reversed())
val bottomScore = countVisibleTrees(grid[row][column], bottomTrees)
val scenicScore = leftScore * rightScore * topScore * bottomScore
if (maxScenicScore < scenicScore) {
maxScenicScore = scenicScore
}
}
}
return maxScenicScore
}
val testInput = readInput("day08/Day08_test")
val grid = testInput.map { it.map { it.code - '0'.code } }
println(part1(grid))
println(part2(grid))
}
| 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 3,915 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | import kotlin.math.abs
import kotlin.math.max
class Sensor(
val location: Pair<Int, Int>,
val beacon: Pair<Int, Int>
) {
val dist = location between beacon
override fun toString(): String {
return "location=$location, beacon=$beacon, dist=$dist"
}
}
fun main() {
fun parseLine(line: String): Sensor {
val sensor = line.split(':')[0].let {
val x = it.dropWhile { it != '=' }
.dropLastWhile { it != ',' }
.drop(1)
.dropLast(1)
.toInt()
val y = it.takeLastWhile { it != '=' }
.toInt()
Pair(x, y)
}
val beacon = line.split(':')[1].let {
val x = it.dropWhile { it != '=' }
.dropLastWhile { it != ',' }
.drop(1)
.dropLast(1)
.toInt()
val y = it.takeLastWhile { it != '=' }
.toInt()
Pair(x, y)
}
return Sensor(sensor, beacon)
}
fun part1(input: List<String>, y: Int): Int {
val positions = mutableSetOf<Int>()
val sensors = input.map { parseLine(it) }
sensors.map { getXRange(it, y) }
.forEach { it.forEach { x -> positions.add(x) } }
sensors.flatMap { listOf(it.location, it.beacon) }
.filter { it.second == y }
.toSet()
.map { it.first }
.forEach { positions.remove(it) }
return positions.size
}
fun findPosition(sensors: List<Sensor>, edge: Int): Pair<Int, Int> {
var x = 0
var y = 0
do {
if (y > edge) throw IllegalStateException("Should not reach here")
var step: Int? = null
sensors.forEach { sensor ->
if (Pair(x, y) between sensor.location <= sensor.dist) {
step = max(step ?: -1, getXRange(sensor, y).last + 1)
}
}
if (step == null) {
return Pair(x, y)
}
x = step!!
if (x > edge) {
y += 1
x = 0
}
} while (true)
}
fun part2(input: List<String>, edge: Int): Long {
val sensors = input.map { parseLine(it) }
val searched: Pair<Int, Int> = findPosition(sensors, edge)
.also { println("Searched: $it") }
return searched.frequency
}
val day = 15
val dayString = String.format("%02d", day)
//
// -----------------------------
//
val testInput = readInput("Day${dayString}_test")
checkEquals(part1(testInput, 10), 26)
checkEquals(part2(testInput, 20), 56000011L)
val input = readInput("Day$dayString")
part1(input, 2_000_000).println()
part2(input, 4_000_000).println()
}
infix fun Pair<Int, Int>.between(to: Pair<Int, Int>) = abs(first - to.first) + abs(second - to.second)
fun getXRange(sensor: Sensor, y: Int): IntRange {
val x = sensor.location.first
val xDist = sensor.dist - (sensor.location between Pair(x, y))
return (x - xDist)..(x + xDist)
}
val Pair<Int, Int>.frequency: Long
get() = this.first * 4_000_000L + this.second | 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 3,212 | advent-of-code-kotlin | Apache License 2.0 |
src/y2015/Day17.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2015
import util.readInput
import kotlin.math.pow
object Day17 {
private fun parse(input: List<String>): List<Int> {
return input.map { it.toInt() }
}
fun part1(input: List<String>, total: Int): Int {
val parsed = parse(input)
val variations = 2.0.pow(parsed.size.toDouble()).toInt()
return (0 until variations).count { bitMask ->
val bits = Integer.toBinaryString(bitMask).padStart(parsed.size, '0')
parsed.zip(bits.toList()).filter { it.second == '1' }.sumOf { it.first } == total
}
}
fun part2(input: List<String>, total: Int): Int {
val parsed = parse(input)
val variations = 2.0.pow(parsed.size.toDouble()).toInt()
val containers = (0 until variations).mapNotNull { bitMask ->
val bits = Integer.toBinaryString(bitMask).padStart(parsed.size, '0')
if (parsed.zip(bits.toList()).filter { it.second == '1' }.sumOf { it.first } == total) {
bits.count { it == '1' }
} else {
null
}
}
val min = containers.min()
return containers.count { it == min }
}
}
fun main() {
val testInput = """
20
15
10
5
5
""".trimIndent().split("\n")
println("------Tests------")
println(Day17.part1(testInput, 25))
println(Day17.part2(testInput, 25))
println("------Real------")
val input = readInput("resources/2015/day17")
println(Day17.part1(input, 150))
println(Day17.part2(input, 150))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,579 | advent-of-code | Apache License 2.0 |
src/Day09.kt | tbilou | 572,829,933 | false | {"Kotlin": 40925} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
val day = "Day09"
fun getNextHead(direction: String, head: Coord): Coord {
return when (direction) {
"U" -> Coord(head.x, head.y + 1)
"D" -> Coord(head.x, head.y - 1)
"L" -> Coord(head.x - 1, head.y)
"R" -> Coord(head.x + 1, head.y)
else -> error("check your input!")
}
}
fun part1(input: List<String>): Int {
var head = Coord(0, 0)
var tailPosition = Coord(0, 0)
var lastHead = Coord(0, 0)
var visited = mutableSetOf<Coord>()
input.forEach { instruction ->
var (direction, times) = instruction.split(" ")
repeat(times.toInt()) {
lastHead = head
head = getNextHead(direction, head)
val dist = distance(head, tailPosition)
if (dist.x > 1 || dist.y > 1) {
visited.add(tailPosition)
tailPosition = lastHead
}
}
}
visited.add(tailPosition)
return visited.size
}
fun part2(input: List<String>): Int {
var visited = mutableSetOf<Coord>()
var knots = List(9) { Coord(0, 0) }
var head = Coord(0, 0)
input.forEach { instruction ->
var (direction, times) = instruction.split(" ")
repeat(times.toInt()) {
var nextHead = getNextHead(direction, head)
head = nextHead
knots = knots.map { knot ->
val updated = knot.update(nextHead)
nextHead = updated
updated
}
visited.add(knots.last())
}
}
return visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
val testInput2 = readInput("${day}_test2")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
check(part2(testInput2) == 36)
val input = readInput("$day")
println(part1(input))
println(part2(input))
}
private fun distance(a: Coord, b: Coord): Coord {
return Coord(abs(a.x - b.x), abs(a.y - b.y))
}
private data class Coord(var x: Int, var y: Int) {
override fun toString(): String {
return "($x,$y)"
}
fun update(knot: Coord): Coord {
var magnitude = distance(knot, this)
if (magnitude.x > 1 || magnitude.y > 1) {
var signx = if (this.x > knot.x) -1 else 1
var signy = if (this.y > knot.y) -1 else 1
// we have the magnitude but we need direction
val vector = Coord(magnitude.x * signx, magnitude.y * signy)
// vector of magnitude 1
val normalizedVector = Coord(1 * vector.x.sign, 1 * vector.y.sign)
return Coord(x + normalizedVector.x, y + normalizedVector.y)
}
return this
}
} | 0 | Kotlin | 0 | 0 | de480bb94785492a27f020a9e56f9ccf89f648b7 | 2,994 | advent-of-code-2022 | Apache License 2.0 |
src/Day09/Day09.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day09
import kotlin.math.*
import readInput
class RopeMover(val ropeSize: Int) {
var rope = MutableList(ropeSize) { _ -> Pair(0, 0) }
var visitedLocations = hashSetOf(Pair(0, 0))
fun processInput(input: List<String>) {
for (row in input) {
processRow(row)
}
}
private fun processRow(row: String) {
val rowElements = row.split(" ")
val countToMove = rowElements[1].toInt()
val movement = when(rowElements[0]) {
"R" -> Pair(1, 0)
"L" -> Pair(-1, 0)
"U" -> Pair(0, 1)
"D" -> Pair(0, -1)
else -> Pair(0, 0)
}
for (i in 0 until countToMove) {
moveHead(movement)
moveRestOfRope()
}
}
private fun moveHead(movement: Pair<Int, Int>) {
rope[0] += movement
}
private fun moveRestOfRope() {
for (index in 1 until rope.size) {
moveTailPartAt(index)
}
}
private fun moveTailPartAt(index: Int) {
val difference = rope[index - 1] - rope[index]
var xMovement = when (difference.first) {
in -Int.MAX_VALUE..-2 -> -1
in 2..Int.MAX_VALUE -> 1
else -> 0
}
var yMovement = when (difference.second) {
in -Int.MAX_VALUE..-2 -> -1
in 2..Int.MAX_VALUE -> 1
else -> 0
}
if (xMovement != 0 && difference.second != 0) {
yMovement = max(-1, min(difference.second, 1))
} else if (yMovement != 0 && difference.first != 0) {
xMovement = max(-1, min(difference.first, 1))
}
rope[index] += Pair(xMovement, yMovement)
if (index == rope.size - 1) {
visitedLocations.add(rope[index])
}
}
}
operator fun Pair<Int, Int>.plus(pair: Pair<Int, Int>): Pair<Int, Int> {
return Pair(first + pair.first, second + pair.second)
}
operator fun Pair<Int, Int>.minus(pair: Pair<Int, Int>): Pair<Int, Int> {
return Pair(first - pair.first, second - pair.second)
}
fun main() {
fun part1(input: List<String>): Int {
val ropeMover = RopeMover(2)
ropeMover.processInput(input)
return ropeMover.visitedLocations.count()
}
fun part2(input: List<String>): Int {
val ropeMover = RopeMover(10)
ropeMover.processInput(input)
return ropeMover.visitedLocations.count()
}
val testInput = readInput("Day09","Day09_test")
// println(part1(testInput))
// check(part1(testInput) == 13)
println(part2(testInput))
check(part2(testInput) == 36)
val input = readInput("Day09","Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 2,729 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day3/Shematic.kt | remhiit | 727,182,240 | false | {"Kotlin": 12212} | package day3
import java.awt.Point
import kotlin.math.sqrt
class Shematic(input: List<String>) {
val mapSize: Point
val numbers: List<Num>
val symbols: List<Symbol>
init {
mapSize = Point(input[0].length, input.size)
numbers = input.withIndex().map { findNumbersInRow(it.value, it.index) }.flatten()
symbols = input.withIndex().map { findSymbolsInRow(it.value, it.index) }.flatten()
}
private fun findNumbersInRow(row: String, yAxis: Int): List<Num> {
return Regex("(\\d+)").findAll(row)
.map { it.range to it.value }
.map { Num(it.second.toInt(), Point(it.first.first, yAxis), Point(it.first.last, yAxis)) }
.toList()
}
private fun findSymbolsInRow(row: String, yAxis: Int): List<Symbol> {
return Regex("[^a-zA-Z0-9.\\n\\r]").findAll(row)
.map { it.range to it.value }
.map { Symbol(it.second, Point(it.first.first, yAxis)) }
.toList()
}
fun getPartNumbers(): List<Num> {
return numbers.filter { symbols.firstOrNull { s -> isAdjacent(it, s) } != null }
}
private fun isAdjacent(n: Num, s: Symbol): Boolean {
return getDistOk(n.coordDebut, s.coord) || getDistOk(n.coordFin, s.coord)
}
private fun getDistOk(p1: Point, p2: Point): Boolean {
val px: Double = p1.getX() - p2.getX()
val py: Double = p1.getY() - p2.getY()
val x = sqrt(px * px).toInt()
val y = sqrt(py * py).toInt()
return x <= 1 && y <= 1
}
fun getGears(): List<Gear> {
return symbols.filter { it.id.equals("*") }
.map { s -> numbers.filter { isAdjacent(it, s) } }
.filter { it.size == 2 }
.map { Gear(it[0].id * it[1].id) }
}
}
data class Gear(val value: Int)
data class Num(val id: Int, val coordDebut: Point, val coordFin: Point)
data class Symbol(val id: String, val coord: Point)
| 0 | Kotlin | 0 | 0 | 122ee235df1af8e3d0ea193b9a37162271bad7cb | 1,939 | aoc2023 | Creative Commons Zero v1.0 Universal |
src/Day16.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | import kotlin.math.max
private const val TIME_LIMIT_1 = 30
private const val TIME_LIMIT_2 = 26
fun main() {
val testInput = readInput("Day16_test")
val testData: ValvesData = createData(testInput)
val testValvesSolution = ValvesSolution(testData)
check(testValvesSolution.getMaxPressure() == 1651)
check(testValvesSolution.getMaxPressure2() == 1707)
val input = readInput("Day16")
val data = createData(input)
val valvesSolution = ValvesSolution(data)
println(valvesSolution.getMaxPressure())
println(valvesSolution.getMaxPressure2())
}
private val REGEX =
Regex("""Valve (?<ID>[A-Z]{2}) has flow rate=(?<flowRate>\d+); (tunnels lead to valves|tunnel leads to valve)\s(?<tunnelList>.*)""")
private fun createData(testInput: List<String>): ValvesData {
val valveNameMap = mutableMapOf<String, Int>()
val flowRateArray: Array<Int> = Array(testInput.size) { 0 }
val movesArrayString: Array<List<String>> = Array(testInput.size) { listOf() }
testInput.forEachIndexed { idx, s ->
val matchResult = REGEX.matchEntire(s) ?: return@forEachIndexed
val valve: String = matchResult.groups["ID"]!!.value
flowRateArray[idx] = matchResult.groups["flowRate"]!!.value.toInt()
movesArrayString[idx] = matchResult.groups["tunnelList"]!!.value.split(", ")
valveNameMap[valve] = idx
}
val movesArray: Array<List<Int>> = Array(movesArrayString.size) {
movesArrayString[it].map { valve -> valveNameMap[valve]!! }
}
return ValvesData(flowRateArray, movesArray, valveNameMap.get("AA")!!)
}
private data class ValvesData(
val flowRate: Array<Int>,
val moves: Array<List<Int>>,
val start: Int
)
private data class ValvesState(
val current: Int,
val opened: Long
)
private class ValvesSolution(val valvesData: ValvesData) {
private val timeMap = mutableMapOf<ValvesState, Int>()
private var result = 0
private val maxOpened: Long = valvesData.flowRate.foldIndexed(0) {
idx, acc, v -> if (v > 0) acc or (1L shl idx) else acc
}
private val pressureForMinuteMap = mutableMapOf<Long, Int>()
private val pressureForPart2Map = mutableMapOf<Long, Int>()
private fun getPressureForState(opened: Long): Int {
return pressureForMinuteMap.computeIfAbsent(opened) { key ->
valvesData.flowRate
.filterIndexed { idx, _ -> key and (1L shl idx) > 0 }
.sum()
}
}
fun getMaxPressure(): Int {
val startState = ValvesState(valvesData.start, 0)
calculatePressure(startState, 0, 1)
return result
}
fun getMaxPressure2(): Int {
val list: List<Pair<Long, Int>> = pressureForPart2Map
.map { entry -> Pair(entry.key, entry.value) }
var result = 0
list.forEachIndexed { index, pair1 ->
for(i in index + 1 .. list.lastIndex) {
if (pair1.first and list[i].first == 0L ) {
val sum = pair1.second + list[i].second
if (sum > result)
result = sum
}
}
}
return result
}
private fun calculatePressure(
state: ValvesState,
pressure: Int,
time: Int
) {
val pressureForMinute = getPressureForState(state.opened)
val newPressure = pressure + pressureForMinute
if (time == TIME_LIMIT_1) {
if (newPressure > result)
result = newPressure
return
}
if (time <= TIME_LIMIT_2) {
val expectedPressure = newPressure + (TIME_LIMIT_2 - time) * pressureForMinute
pressureForPart2Map.merge(state.opened, expectedPressure) {
old, new -> max(old, new)
}
}
if (maxOpened == state.opened) {
val expectedPressure = newPressure + (TIME_LIMIT_1 - time) * pressureForMinute
if (expectedPressure > result)
result = expectedPressure
return
}
if (timeMap.getOrDefault(state, TIME_LIMIT_1 + 1) < time)
return
timeMap[state] = time
for (doMove in 0..1) { // 1 - move, 0 - open
if (doMove == 1) {
valvesData.moves[state.current].forEach {
calculatePressure(
ValvesState(it, state.opened),
newPressure,
time + 1
)
}
} else if ((state.opened and (1L shl state.current) == 0L)
&& valvesData.flowRate[state.current] > 0
)
calculatePressure(
ValvesState(state.current, state.opened or (1L shl state.current)),
newPressure,
time + 1
)
}
}
} | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 4,895 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/days/Day8.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
class Day8 : Day(8) {
private val dirs = sequenceOf(0 to 1, 1 to 0, 0 to -1, -1 to 0)
override fun partOne(): Any {
val trees = inputList.map { it.map { it.code - '0'.code } }
val size = trees.size
val visible = Array(size) { Array(size) { false } }
for (row in 0 until size) {
for (col in 0 until size) {
visible[row][col] = dirs.any { (dr, dc) ->
var k = 1
while (!away(row + k * dr, col + k * dc, size)
&& trees[row][col] > trees[row + k * dr][col + k * dc]
) k++
away(row + k * dr, col + k * dc, size)
}
}
}
return visible.sumOf { it.count { it } }
}
override fun partTwo(): Any {
val trees = inputList.map { it.map { it.code - '0'.code } }
val size = trees.size
val view = Array(size) { Array(size) { 0 } }
for (row in 0 until size) {
for (col in 0 until size) {
view[row][col] =
dirs.map { (dr, dc) ->
var k = 1
while (!away(row + k * dr, col + k * dc, size)
&& trees[row][col] > trees[row + k * dr][col + k * dc]
) k++
if (!away(row + k * dr, col + k * dc, size)) k else k - 1
}.reduce { acc, next -> acc * next }
}
}
return view.maxOf { it.maxOf { it } }
}
private fun away(row: Int, col: Int, size: Int) =
row < 0 || row >= size || col < 0 || col >= size
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 1,679 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/Day10.kt | jorgecastrejon | 573,097,701 | false | {"Kotlin": 33669} | fun main() {
fun part1(input: List<String>): Int =
getInstructions(input).foldIndexed(1 to mutableListOf<Int>()) { index, (x, strengths), (instruction, value) ->
if (((index + 1) - 20) % 40 == 0) strengths.add(x * (index + 1))
val x1 = if (instruction == "addx" && value != null) x + value else x
x1 to strengths
}.second.sum()
fun part2(input: List<String>): Int {
getInstructions(input).foldIndexed(1 to mutableListOf<String>()) { index, (x, pixels), (instruction, value) ->
pixels.add(if (((index + 1) % 40) in (x until x + 3)) "#" else ".")
val x1 = if (instruction == "addx" && value != null) x + value else x
x1 to pixels
}.second.chunked(40).forEach { line -> println(line.joinToString("")) }
return 0
}
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
private fun getInstructions(input: List<String>): List<Pair<String, Int?>> =
input.map { line ->
line.split(" ").let {
if (it.first() == "addx") {
listOf(it.first() to null, it.first() to it.last().toIntOrNull())
} else {
listOf(it.first() to null)
}
}
}.flatten()
| 0 | Kotlin | 0 | 0 | d83b6cea997bd18956141fa10e9188a82c138035 | 1,288 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day05/day5.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day05
import biz.koziolek.adventofcode.findInput
fun main() {
val inputFile = findInput(object {})
val almanac = parseAlmanacV1(inputFile.bufferedReader().readLines())
println("Lowest location is: ${almanac.mapAll(from = "seed", to = "location", items = almanac.seeds).min()}")
}
fun parseAlmanacV1(lines: Iterable<String>): Almanac =
parseAlmanac(lines, ::parseSeedsV1)
fun parseAlmanacV2(lines: Iterable<String>): Almanac =
parseAlmanac(lines, ::parseSeedsV2)
private fun parseAlmanac(lines: Iterable<String>, seedParser: (String) -> Sequence<Long>): Almanac {
var seeds: Sequence<Long> = emptySequence()
val maps: MutableList<AlmanacMap> = mutableListOf()
val iterator = lines.iterator()
while (iterator.hasNext()) {
val line = iterator.next()
if (line.startsWith("seeds:")) {
seeds = seedParser(line)
} else if (line.contains("map:")) {
val (from, _, to, _) = line.split("-", " ")
val map = buildList {
while (iterator.hasNext()) {
val mappingLine = iterator.next()
if (mappingLine.isBlank()) {
break
}
val mapping = mappingLine
.split(" ")
.map { it.trim().toLong() }
.let { (destination, source, length) ->
AlmanacMapping(
destination = destination,
source = source,
length = length,
)
}
add(mapping)
}
}
maps.add(AlmanacMap(from, to, map))
}
}
return Almanac(seeds, maps)
}
private fun parseSeedsV1(line: String) =
line
.replace("seeds:", "")
.trim()
.split(" ")
.map { it.trim().toLong() }
.asSequence()
private fun parseSeedsV2(line: String) =
line
.replace("seeds:", "")
.trim()
.split(" ")
.map { it.trim().toLong() }
.chunked(2)
.asSequence()
.flatMap { (start, length) ->
start until start + length
}
data class Almanac(val seeds: Sequence<Long>, val maps: List<AlmanacMap>) {
fun findMap(from: String, to: String? = null): AlmanacMap? =
maps.singleOrNull { it.sourceCategory == from
&& (to == null || it.destinationCategory == to) }
fun mapAll(from: String, to: String, items: Sequence<Long>): Sequence<Long> {
val mapsToUse = buildList {
var next: String? = from
while (next != null) {
val map = findMap(next) ?: throw IllegalArgumentException("Cannot map $from to $to - no map for $next")
add(map)
next = if (map.destinationCategory == to) {
null
} else {
map.destinationCategory
}
}
}
return items.map { item ->
mapsToUse.fold(item) { acc, map -> map.map(acc) }
}
}
}
data class AlmanacMap(
val sourceCategory: String,
val destinationCategory: String,
val mapping: List<AlmanacMapping>
) {
fun map(from: Long): Long =
mapping
.singleOrNull { it.covers(from) }
?.map(from)
?: from
}
data class AlmanacMapping(val destination: Long, val source: Long, val length: Long) {
val sourceRange = source until source + length
val destinationRange = destination until destination + length
fun map(from: Long): Long =
when {
covers(from) -> destination + (from - source)
else -> from
}
fun covers(from: Long) = from in sourceRange
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 3,919 | advent-of-code | MIT License |
src/day05/day05.kt | taer | 573,051,280 | false | {"Kotlin": 26121} | package day05
import readInput
import split
fun main() {
fun parseStacks(stacks: List<String>): List<MutableList<String>> {
val simpler = stacks.dropLast(1).map {
it.drop(1).mapIndexedNotNull { index, c ->
if (index % 4 == 0)
c.toString()
else
null
}
}
val indexes = simpler.last()
val realStacks = List(indexes.size) {
mutableListOf<String>()
}
simpler.reversed().forEach {
it.forEachIndexed { index, s ->
if (s.isNotBlank()) {
realStacks[index].add(s)
}
}
}
return realStacks
}
data class Move(val count: Int, val from: Int, val to: Int)
fun computerMoves(
toList: List<List<String>>,
moves: List<String>
): List<Move> {
val regex = """move (\d+) from (\d+) to (\d+)""".toRegex()
return moves.map {
val matchEntire = regex.matchEntire(it)
requireNotNull(matchEntire)
val (amount, from, to) = matchEntire.destructured
Move(amount.toInt(), from.toInt(), to.toInt())
}
}
fun dataParse(input: List<String>): Pair<List<MutableList<String>>, List<Move>> {
val toList = input.asSequence().split { it == "" }.toList()
val sta = parseStacks(toList[0])
val moves = computerMoves(toList, toList[1])
return Pair(sta, moves)
}
fun part1(input: List<String>): String {
val (sta, moves) = dataParse(input)
fun stackForMove(location: Int) = sta[location-1]
moves.forEach {move ->
repeat(move.count){
val item = stackForMove(move.from).removeLast()
stackForMove(move.to).add(item)
}
}
return sta.joinToString("") { it.last() }
}
fun part2(input: List<String>): String {
val (sta, moves) = dataParse(input)
fun stackForMove(location: Int) = sta[location-1]
moves.forEach {move ->
val sourceStack = stackForMove(move.from)
val item = sourceStack.takeLast(move.count)
repeat(move.count){
sourceStack.removeLast()
}
stackForMove(move.to).addAll(item)
move.to
}
return sta.joinToString("") { it.last() } }
val testInput = readInput("day05", true)
val input = readInput("day05")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
check(part1(input) == "GRTSWNJHH")
check(part2(input) == "QLFQDBBHM")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1bd19df8949d4a56b881af28af21a2b35d800b22 | 2,727 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-09.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2021
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.filterIn
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2021, "09-input")
val test1 = readInputLines(2021, "09-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
var result = 0
input.forEachIndexed { row, line ->
line.forEachIndexed { col, c ->
val neighbors = input.getNeighboringValues(row, col)
if (neighbors.all { c < it }) result += c.digitToInt() + 1
}
}
return result
}
private fun part2(input: List<String>): Int {
val visited = mutableSetOf<Coord2D>()
val height = input.size
val width = input.first().length
input.forEachIndexed { row, line ->
line.forEachIndexed { col, c ->
if (c == '9') visited += Coord2D(col, row)
}
}
val basins = mutableListOf<Int>()
while (visited.size != width * height) {
for (row in input.indices) {
for (col in input[row].indices) {
val coord = Coord2D(col, row)
if (coord !in visited) {
basins += input.findBasin(coord, visited)
}
}
}
}
return basins.sortedDescending().take(3).fold(1) { acc, item -> acc * item }
}
private fun List<String>.findBasin(coord: Coord2D, visited: MutableSet<Coord2D>): Int {
if (coord in visited) return 0
visited += coord
return getNeighborCoords(coord).map { findBasin(it, visited) }.sum() + 1
}
private fun List<String>.getNeighboringValues(row: Int, col: Int): List<Char> {
return getNeighborCoords(Coord2D(col, row)).map { this[it.y][it.x] }
}
private fun List<String>.getNeighborCoords(coord2D: Coord2D): List<Coord2D> {
return coord2D.adjacent(false)
.filterIn(first().indices, indices)
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,146 | advent-of-code | MIT License |
lib/src/main/kotlin/aoc/day14/Day14.kt | Denaun | 636,769,784 | false | null | package aoc.day14
import kotlin.math.max
import kotlin.math.min
fun part1(input: String): Int = simulateCave(parse(input), ::simulateFloorless)
fun part2(input: String): Int = simulateCave(parse(input), ::simulateFloorful)
fun simulateCave(
paths: List<Path>,
simulateUnit: (originalMaxY: Int, occupiedPoints: Set<Point>) -> Point?,
): Int {
val occupiedPoints = paths.flatten().toMutableSet()
val emptySize = occupiedPoints.size
val originalMaxY = occupiedPoints.maxOf { it.y }
occupiedPoints.addAll(generateSequence { simulateUnit(originalMaxY, occupiedPoints) })
return occupiedPoints.size - emptySize
}
fun simulateFloorless(originalMaxY: Int, occupiedPoints: Set<Point>): Point? {
val start = Point(500, 0)
require(!occupiedPoints.contains(start))
val end = start.fall(occupiedPoints).takeWhile { it.y <= originalMaxY }.last()
return if (end.y < originalMaxY) {
end
} else {
null
}
}
fun simulateFloorful(originalMaxY: Int, occupiedPoints: Set<Point>): Point? {
val start = Point(500, 0)
if (occupiedPoints.contains(start)) {
return null
}
val floor = 2 + originalMaxY
return start.fall(occupiedPoints).takeWhile { it.y < floor }.last()
}
data class Point(val x: Int, val y: Int) {
fun fall(occupiedPoints: Set<Point>): Sequence<Point> =
generateSequence(this) { it.neighbors().find { next -> !occupiedPoints.contains(next) } }
private fun neighbors(): List<Point> = listOf(
Point(x, y + 1),
Point(x - 1, y + 1),
Point(x + 1, y + 1),
)
}
data class Path(val points: List<Point>) : Iterable<Point> {
override fun iterator(): Iterator<Point> =
points.zipWithNext().asSequence().flatMap { (start, end) ->
if (start.x == end.x) {
(min(start.y, end.y)..max(start.y, end.y)).map { Point(start.x, it) }
} else {
require(start.y == end.y)
(min(start.x, end.x)..max(start.x, end.x)).map { Point(it, start.y) }
}
}.iterator()
} | 0 | Kotlin | 0 | 0 | 560f6e33f8ca46e631879297fadc0bc884ac5620 | 2,075 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2016/Day11.kt | colinodell | 495,627,767 | false | {"Kotlin": 80872} | package com.colinodell.advent2016
class Day11(private val input: List<String>) {
fun solve(): Int {
// Parse the input
val rgx = Regex("(\\w+(?: generator|-compatible microchip))")
val floors = input.map { rgx.findAll(it).map { it.groupValues[1] }.toList() }
val start = State(0, floors.mapIndexed { i, f -> i to f.toSet() }.toMap())
val end = State(
3,
mapOf(
0 to setOf(),
1 to setOf(),
2 to setOf(),
3 to floors.flatten().toSet(),
)
)
val generator = fun(state: State) = state.generateNextStates()
val h = fun(state: State) = (state.items[2]!!.size * 4) + (state.items[1]!!.size * 6) + (state.items[0]!!.size * 8)
return AStar(start, end, generator, h).distance
}
private data class State(val currentFloor: Int, val items: Map<Int, Set<String>>) {
fun generateNextStates() = generateAllPossibleNextStates()
private fun generateAllPossibleNextStates() = sequence {
val itemsExistOnLowerFloors = items.filterKeys { it < currentFloor }.values.any { it.isNotEmpty() }
val nextPossibleFloors = (0..3).filter { it == currentFloor + 1 || (it == currentFloor - 1 && itemsExistOnLowerFloors) }
for (nextFloor in nextPossibleFloors) {
// Optimization: If we're going up, bring two items if we can, instead of one
if (nextFloor > currentFloor) {
val twoItemMoves = generateTwoItemMoves(nextFloor)
if (twoItemMoves.isNotEmpty()) {
yieldAll(twoItemMoves)
} else {
yieldAll(generateSingleItemMoves(nextFloor))
}
}
// Optimization: If we're going down, bring one item if we can, instead of two
else {
val singleItemMoves = generateSingleItemMoves(nextFloor)
if (singleItemMoves.isNotEmpty()) {
yieldAll(singleItemMoves)
} else {
yieldAll(generateTwoItemMoves(nextFloor))
}
}
}
}
private fun generateSingleItemMoves(nextFloor: Int): Collection<State> =
items[currentFloor]!!.toList().map { item ->
val newItems = items.toMutableMap().mapValues { it.value.toMutableSet() }
newItems[currentFloor]!!.remove(item)
newItems[nextFloor]!!.add(item)
State(nextFloor, newItems)
}.filter { it.isValid() }
private fun generateTwoItemMoves(nextFloor: Int): Collection<State> = items[currentFloor]!!.permutationPairs().map { pair ->
val newItems = items.toMutableMap().mapValues { it.value.toMutableSet() }
newItems[currentFloor]!!.remove(pair.first)
newItems[currentFloor]!!.remove(pair.second)
newItems[nextFloor]!!.add(pair.first)
newItems[nextFloor]!!.add(pair.second)
State(nextFloor, newItems)
}.filter { it.isValid() }.toList()
fun isValid(): Boolean {
for (itemsOnFloor in items.values) {
val generators = itemsOnFloor.filter { it.endsWith("generator") }.map { it.replace(" generator", "") }
val microchips = itemsOnFloor.filter { it.endsWith("microchip") }.map { it.replace("-compatible microchip", "") }
// Floors may contain only generators, only microchips, or be empty
if (generators.isEmpty() || microchips.isEmpty()) {
continue
}
// If a chip exists on the same floor as another RTG, and it's not connected to its own RTG, the state is invalid
if (!generators.containsAll(microchips)) {
return false
}
}
return true
}
val hashString: String by lazy {
var hash = currentFloor.toString()
for ((floor, items) in items) {
// Find pairs of generators and compatible microchips
val generators = items.filter { it.endsWith("generator") }.map { it.replace(" generator", "") }.toSet()
val microchips = items.filter { it.endsWith("microchip") }.map { it.replace("-compatible microchip", "") }.toSet()
val pairs = generators.intersect(microchips)
val remainingItems = items.toSortedSet()
// Remove any items that start with any pair prefix
for (prefix in pairs) {
remainingItems.removeIf { it.startsWith(prefix) }
}
// Add the remaining items to the hash
hash += "|floor-$floor-pairs-${pairs.size}-${remainingItems.joinToString(",")}"
}
hash
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as State
if (currentFloor != other.currentFloor) return false
return hashString == other.hashString
}
override fun hashCode(): Int {
return hashString.hashCode()
}
}
}
| 0 | Kotlin | 0 | 0 | 8a387ddc60025a74ace8d4bc874310f4fbee1b65 | 5,410 | advent-2016 | Apache License 2.0 |
src/Day11.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | fun main() {
fun solution(input: List<String>, roundCount: Int, worthLevelUpdate: (Long) -> Long): Long {
val monkeyList: List<Monkey> = readMonkeyList(input)
val inspectionList = Array(monkeyList.size) { 0 }
val divider = monkeyList
.map { m -> m.divisionCheckNum }
.fold(1L) { a, b -> a * b }
repeat(roundCount) {
monkeyList.forEachIndexed { index, monkey ->
monkey.itemList.forEach {
inspectionList[index]++
val newWorthLevel = worthLevelUpdate.invoke(monkey.getWorthLevel(it) % divider )
val newMonkeyIdx = monkey.getNewMonkeyIdx(newWorthLevel)
monkeyList[newMonkeyIdx].itemList.add(newWorthLevel)
}
monkey.itemList.clear()
}
}
val maxTwo = inspectionList.sortedArrayDescending().take(2)
return maxTwo[0].toLong() * maxTwo[1]
}
val testInput = readInput("Day11_test")
check(solution(testInput, 20) { a -> a / 3 } == 10605L)
check(solution(testInput, 10000) { a -> a } == 2713310158)
val input = readInput("Day11")
println(solution(input, 20) { a -> a / 3 } )
println(solution(input, 10000) { a -> a })
}
private class Monkey(
val itemList: MutableList<Long>,
val operation: Operation,
val divisionCheckNum: Int,
val monkeyTrueIdx: Int,
val monkeyFalseIdx: Int
) {
fun getWorthLevel(level: Long): Long {
return operation.calculate(level)
}
fun getNewMonkeyIdx(newWorthLevel: Long): Int {
return if (newWorthLevel % divisionCheckNum == 0L) monkeyTrueIdx else monkeyFalseIdx
}
}
private enum class OperationType { ADD, MULTIPLE }
private class Operand(string: String) {
val isWorthLevel: Boolean = string == "old"
val value: Long? = string.toLongOrNull()
}
private data class Operation(
val operand1: Operand,
val operand2: Operand,
val operationType: OperationType
) {
fun calculate(worthLevel: Long): Long {
return when (operationType) {
OperationType.ADD -> {
operand1.getOperandValue(worthLevel) + operand2.getOperandValue(worthLevel)
}
OperationType.MULTIPLE -> {
operand1.getOperandValue(worthLevel) * operand2.getOperandValue(worthLevel)
}
}
}
}
private fun Operand.getOperandValue(worthLevel: Long): Long {
return if (isWorthLevel) worthLevel else value!!
}
private fun readMonkeyList(input: List<String>): List<Monkey> {
val result = mutableListOf<Monkey>()
var items: MutableList<Long>? = null
var operation: Operation? = null
var divisionCheckNum = 1
var trueIdx = -1
var falseIdx = -1
input.forEach { string ->
when {
string.startsWith(" Starting items") -> {
items = string.substringAfterLast(": ")
.split(", ")
.map { it.toLong() }
.toMutableList()
}
string.startsWith(" Operation") -> {
val expression = string.substringAfterLast("new = ")
val operationType = if (expression.contains("+"))
OperationType.ADD
else
OperationType.MULTIPLE
operation = Operation(
Operand(expression.substringBefore(" ")),
Operand(expression.substringAfterLast(" ")),
operationType
)
}
string.contains("Test") -> {
divisionCheckNum = string.substringAfterLast(" ").toInt()
}
string.contains("If true") -> {
trueIdx = string.substringAfterLast(" ").toInt()
}
string.contains("If false") -> {
falseIdx = string.substringAfterLast(" ").toInt()
}
string.isBlank() -> {
result.add(Monkey(
items!!,
operation!!,
divisionCheckNum,
trueIdx,
falseIdx
))
}
}
}
result.add(Monkey(
items!!,
operation!!,
divisionCheckNum,
trueIdx,
falseIdx
))
return result
}
| 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 4,386 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/io/steinh/aoc/day03/GearRatios.kt | daincredibleholg | 726,426,347 | false | {"Kotlin": 25396} | package io.steinh.aoc.day03
class GearRatios {
fun addUpPartNumbers(lines: List<String>): Int {
var result = 0
for (lineIndex in lines.indices) {
val line = lines[lineIndex]
val numberMatches = "(\\d+)".toRegex().findAll(line)
for (numberMatch in numberMatches) {
var startPos = numberMatch.groups[0]!!.range.first()
if (startPos > 0) {
startPos -= 1
}
val endPos = numberMatch.groups[0]!!.range.last() + 1
val startLineId = if (lineIndex > 0) lineIndex - 1 else 0
val endLineId = if (lineIndex < lines.lastIndex) lineIndex + 1 else lineIndex
if (hasAdjacentSymbol(lines, startLineId, endLineId, startPos, endPos)) {
result += numberMatch.groups[0]!!.value.toInt()
}
}
}
return result
}
fun calculateGearRatioSum(lines: List<String>): Int {
var result = 0
for (lineIndex in lines.indices) {
val line = lines[lineIndex]
val asteriskMatches = "([*])".toRegex().findAll(line)
for (match in asteriskMatches) {
result += searchAndCalculate(lines, lineIndex, match.groups[0]!!.range)
}
}
return result
}
private fun searchAndCalculate(lines: List<String>, lineIndex: Int, range: IntRange): Int {
val minLineId = if (lineIndex > 0) lineIndex - 1 else 0
val maxLineId = if (lineIndex < lines.lastIndex) lineIndex + 1 else lineIndex
val foundNumbers = mutableListOf<Int>()
for (i in minLineId..maxLineId) {
val line = lines[i]
val numberMatches = "(\\d+)".toRegex().findAll(line)
for (match in numberMatches) {
val matchRange = match.groups[0]!!.range
val startAt = if (matchRange.first() > 0) matchRange.first() - 1 else 0
val endAt = matchRange.last() + 1
if ((startAt..endAt).contains(range.first())) {
foundNumbers.add(match.groups[0]!!.value.toInt())
}
}
}
if (foundNumbers.size == 2) {
return foundNumbers.first() * foundNumbers.last()
}
return 0
}
private fun hasAdjacentSymbol(
lines: List<String>,
startLineId: Int,
endLineId: Int,
startPos: Int,
endPos: Int
): Boolean {
var result = false
for (i in startLineId..endLineId) {
val max = if (endPos >= lines[i].length) lines[i].length - 1 else endPos
val subString = lines[i].substring(startPos..max)
result = result || subString.any { it != '.' && !it.isDigit() }
}
return result
}
}
fun main() {
val gearRatios = GearRatios()
val lines = {}.javaClass.classLoader?.getResource("day03/input.txt")?.readText()?.lines()!!
val resultPart1 = gearRatios.addUpPartNumbers(lines)
val resultPart2 = gearRatios.calculateGearRatioSum(lines)
print ("Result Day 3, Part I: $resultPart1\n")
print ("Result Day 3, Part II: $resultPart2\n")
}
| 0 | Kotlin | 0 | 0 | 4aa7c684d0e337c257ae55a95b80f1cf388972a9 | 3,242 | AdventOfCode2023 | MIT License |
2023/src/day15/day15.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day15
import GREEN
import RESET
import printTimeMillis
import readInput
private fun hash(str: String): Int {
var s = 0
for (c in str) {
s = ((s + c.code) * 17) % 256
}
return s
}
fun part1(input: List<String>): Int {
return input.first().split(",")
.map { hash(it) }
.sum()
}
data class Lense(val label: String, val number: Int)
fun part2(input: List<String>): Int {
val boxes = mutableMapOf<Int, MutableList<Lense>>()
input.first().split(",")
.forEach {
val isAdding = it.contains("=")
val (label, number) = if (isAdding) {
it.split("=")
} else {
it.split("-")
}
if (isAdding) {
val boxNb = hash(label)
if (!boxes.containsKey(boxNb)) {
boxes[boxNb] = mutableListOf()
}
val currentLenseIdx = boxes[boxNb]!!.indexOfFirst { it.label == label }
if (currentLenseIdx != -1) {
boxes[boxNb]!![currentLenseIdx] = Lense(label, number.toInt())
} else {
boxes[boxNb]!!.add(Lense(label, number.toInt()))
}
} else {
for (k in boxes.keys) {
val toRemoveIdx = boxes[k]!!.indexOfFirst { it.label == label }
if (toRemoveIdx != -1) {
boxes[k]!!.removeAt(toRemoveIdx)
}
}
}
}
return boxes.keys.map { boxNb ->
boxes[boxNb]!!.mapIndexed { index, lense -> (boxNb + 1) * (index + 1) * lense.number }.sum()
}.sum()
}
fun main() {
val testInput = readInput("day15_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day15.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 2,125 | advent-of-code | Apache License 2.0 |
src/Day03.kt | ka1eka | 574,248,838 | false | {"Kotlin": 36739} | fun main() {
fun part1(input: List<String>): Int = input
.asSequence()
.map {
it.toList()
}.map {
it.chunked(it.size / 2)
}.map {
it[0] intersect it[1].toSet()
}.onEach {
check(it.size == 1)
}.map {
it.first()
}.sumOf {
when (it) {
in 'a'..'z' -> (it - 'a' + 1)
in 'A'..'Z' -> (it - 'A' + 27)
else -> 0
}
}
fun part2(input: List<String>): Int = input
.asSequence()
.map {
it.toList()
}.chunked(3)
.map {
it[0] intersect it[1].toSet() intersect it[2].toSet()
}.onEach {
check(it.size == 1)
}.map {
it.first()
}.sumOf {
when (it) {
in 'a'..'z' -> (it - 'a' + 1)
in 'A'..'Z' -> (it - 'A' + 27)
else -> 0
}
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f7893448db92a313c48693b64b3b2998c744f3b | 1,198 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | michaelYuenAE | 573,094,416 | false | {"Kotlin": 74685} | class Day11(input: String) {
private val monkeys = input.split("\n\n").map { Monkey.from(it.lines()) }
fun solvePart1() = keepAway(rounds = 20, manageWorryLevel = { level, _ -> level / 3 })
fun solvePart2() = keepAway(rounds = 10_000, manageWorryLevel = { level, modulus -> level % modulus })
private fun keepAway(rounds: Int, manageWorryLevel: (Long, Int) -> Long): Long {
val modulus = monkeys.map { it.divisor }.reduce(Int::times)
repeat(rounds) {
monkeys.forEach { monkey ->
monkey.items.forEach { item ->
monkey.inspected++
val new = manageWorryLevel(monkey.operation(item), modulus)
monkeys[if (new % monkey.divisor == 0L) monkey.trueMonkey else monkey.falseMonkey].items.add(new)
}
monkey.items.clear()
}
}
return monkeys.map { it.inspected.toLong() }.sortedDescending().take(2).reduce(Long::times)
}
private data class Monkey(
var inspected: Int = 0,
val items: MutableList<Long>,
val operation: (Long) -> Long,
val divisor: Int,
val trueMonkey: Int,
val falseMonkey: Int
) {
companion object {
fun from(definition: List<String>): Monkey {
val operation = { previous: Long ->
val argument = definition[2].substringAfterLast(" ")
.let { if (it == "old") previous else it.toLong() }
when (definition[2].substringAfter("old ").first()) {
'+' -> previous + argument
'*' -> previous * argument
else -> previous
}
}
return Monkey(
items = definition[1].substringAfter("items: ").split(", ").map { it.toLong() }.toMutableList(),
operation = operation,
divisor = definition[3].substringAfter("by ").toInt(),
trueMonkey = definition[4].substringAfter("monkey ").toInt(),
falseMonkey = definition[5].substringAfter("monkey ").toInt()
)
}
}
}
}
fun main() {
val todayTest = Day11(readText("day11_input"))
println(todayTest.solvePart1())
} | 0 | Kotlin | 0 | 0 | ee521263dee60dd3462bea9302476c456bfebdf8 | 2,357 | advent22 | Apache License 2.0 |
2022/src/main/kotlin/com/github/akowal/aoc/Day02.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
import com.github.akowal.aoc.Day02.Shape.*
class Day02 {
private val pairs = inputScanner("day02").let { input ->
val result = mutableListOf<Pair<Char, Char>>()
while (input.hasNextLine()) {
val line = input.nextLine()
result += line[0] to line[2]
}
result
}
fun solvePart1(): Int {
val shapes = mapOf(
'A' to ROCK,
'X' to ROCK,
'B' to PAPER,
'Y' to PAPER,
'C' to SCISSORS,
'Z' to SCISSORS,
)
return pairs.sumOf {
val other = shapes.getValue(it.first)
val your = shapes.getValue(it.second)
score(other, your)
}
}
fun solvePart2(): Int {
val shapes = mapOf(
'A' to ROCK,
'B' to PAPER,
'C' to SCISSORS,
)
val winners = mapOf(
ROCK to PAPER,
PAPER to SCISSORS,
SCISSORS to ROCK,
)
val losers = mapOf(
ROCK to SCISSORS,
PAPER to ROCK,
SCISSORS to PAPER,
)
return pairs.sumOf {
val other = shapes.getValue(it.first)
val your = when(it.second) {
'X' -> losers.getValue(other)
'Z' -> winners.getValue(other)
else -> other
}
score(other, your)
}
}
enum class Shape {
ROCK {
override fun beats(other: Shape) = other == SCISSORS
},
PAPER {
override fun beats(other: Shape) = other == ROCK
},
SCISSORS {
override fun beats(other: Shape) = other == PAPER
};
abstract infix fun beats(other: Shape): Boolean
}
private fun score(other: Shape, yours: Shape): Int {
var score = when (yours) {
ROCK -> 1
PAPER -> 2
SCISSORS -> 3
}
score += when {
other == yours -> 3
yours beats other -> 6
else -> 0
}
return score
}
}
fun main() {
val solution = Day02()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 2,261 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day18/Day18SettlersOfTheNorthPole.kt | Zordid | 160,908,640 | false | null | package day18
import shared.Coordinate
import shared.measureRuntime
import shared.readPuzzle
import shared.toArea
class LumberArea(puzzle: List<String>) {
private val initialMap = puzzle.map { it.toList() }
private val area = initialMap.toArea()
fun solve(minutes: Int, debug: Boolean = false): Int {
val future = future(minutes, debug)
val trees = future.count('|')
val lumberyards = future.count('#')
if (debug) {
println("Trees: $trees")
println("Lumberyards: $lumberyards")
}
return trees * lumberyards
}
private fun future(minutes: Int, debug: Boolean = false): List<List<Char>> {
var map = initialMap
val seenBefore = mutableMapOf<List<List<Char>>, Int>()
var minutesLeft = minutes
if (debug) println("Initial state:\n${map.neat()}")
while (!seenBefore.contains(map) && minutesLeft > 0) {
seenBefore[map] = minutesLeft
map = map.nextGeneration()
minutesLeft--
if (debug) println("After ${minutes - minutesLeft} minutes:\n${map.neat()}")
}
if (minutesLeft == 0)
return map
if (debug)
println("Loop detected after ${minutes - minutesLeft} minutes with $minutesLeft minutes to go!")
val before = seenBefore[map]!!
val loopSize = before - minutesLeft
minutesLeft %= loopSize
if (debug)
println("Loop length is $loopSize, fast forward to only $minutesLeft minutes left to go!")
repeat(minutesLeft) { map = map.nextGeneration() }
return map
}
private fun List<List<Char>>.nextGeneration() =
mapIndexed { y, chars ->
chars.mapIndexed { x, c ->
nextState(c, Coordinate(x, y).let { coordinate ->
coordinate.allNeighbors.mapNotNull { of(it) }
})
}
}
private fun nextState(current: Char, neighbors: List<Char>) =
arrayOf('|', '#').map { c -> neighbors.count { it == c } }.let { (trees, lumberyards) ->
when (current) {
'.' -> if (trees >= 3) '|' else '.'
'|' -> if (lumberyards >= 3) '#' else '|'
'#' -> if ((lumberyards >= 1) && (trees >= 1)) '#' else '.'
else -> throw IllegalStateException(current.toString())
}
}
private fun List<List<Char>>.of(c: Coordinate) =
if (area contains c) this[c.y][c.x] else null
private fun List<List<Char>>.neat() =
joinToString("") { it.joinToString("", postfix = "\n") }
private fun List<List<Char>>.count(searchFor: Char) = sumOf { it.count { c -> c == searchFor } }
}
fun part1(puzzle: List<String>, debug: Boolean = false) = LumberArea(puzzle).solve(10, debug)
fun part2(puzzle: List<String>, debug: Boolean = false) = LumberArea(puzzle).solve(1000000000, debug)
fun main() {
val puzzle = readPuzzle(18)
measureRuntime {
println(part1(puzzle))
println(part2(puzzle))
}
} | 0 | Kotlin | 0 | 0 | f246234df868eabecb25387d75e9df7040fab4f7 | 3,074 | adventofcode-kotlin-2018 | Apache License 2.0 |
src/day03/Day03.kt | pnavais | 574,712,395 | false | {"Kotlin": 54079} | package day03
import readInput
fun computePriority(item: Char): Short {
var itemId = item.code.toShort()
itemId = if (itemId >= 'a'.code.toShort() && itemId <= 'z'.code.toShort()) {
itemId.minus('a'.code.toShort() - 1).toShort()
} else if (itemId >= 'A'.code.toShort() && itemId <= 'Z'.code.toShort()) {
itemId.minus('A'.code.toShort() - 27).toShort()
} else {
0
}
return itemId
}
fun part1(input: List<String>): Long {
var totalPriorities = 0L
for (ruckSackSpec in input) {
val firstRuckSack = ruckSackSpec.substring(0, ruckSackSpec.length / 2)
val secondRuckSack = ruckSackSpec.substring(ruckSackSpec.length / 2)
var commonItem = Character.MIN_VALUE
for (item in secondRuckSack.toCharArray()) {
if (firstRuckSack.indexOf(item) != -1) {
commonItem = item
break
}
}
totalPriorities += computePriority(commonItem)
}
return totalPriorities
}
fun part2(input: List<String>): Long {
var totalPriorities = 0L
for (i in input.indices step 3) {
var commonItem = Character.MIN_VALUE
val firstRuckSack = input[i]
val secondRuckSack = input[i + 1]
val thirdRuckSack = input[i + 2]
for (item in firstRuckSack.toCharArray()) {
if ((secondRuckSack.indexOf(item) != -1) && (thirdRuckSack.indexOf(item) != -1)) {
commonItem = item
break
}
}
totalPriorities += computePriority(commonItem)
}
return totalPriorities
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("day03/Day03_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | ed5f521ef2124f84327d3f6c64fdfa0d35872095 | 1,804 | advent-of-code-2k2 | Apache License 2.0 |
y2023/src/main/kotlin/adventofcode/y2023/Day02.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
fun main() {
Day02.solve()
}
object Day02 : AdventSolution(2023, 2, "Cube Conundrum") {
override fun solvePartOne(input: String) = parse(input)
.filter { it.draws.all { (r, g, b) -> r <= 12 && g <= 13 && b <= 14 } }
.sumOf { it.id }
override fun solvePartTwo(input: String) = parse(input)
.map { it.draws.reduce(::maxOf) }
.sumOf { it.red * it.green * it.blue }
}
private fun parse(input: String): Sequence<Game> {
return input.lineSequence().map { line ->
val (idStr, drawsStr) = line.split(": ")
val id = idStr.substringAfter("Game ").toInt()
val draws = drawsStr.split("; ")
.map { draw ->
draw.split(", ")
.associate { singleDraw ->
singleDraw
.split(" ")
.let { (n, c) -> c to n.toInt() }
}
}
.map(::Draw)
Game(id, draws)
}
}
private data class Game(
val id: Int,
val draws: List<Draw>
)
private data class Draw(
val red: Int,
val green: Int,
val blue: Int
) {
constructor(map: Map<String, Int>) : this(
red = map["red"] ?: 0,
green = map["green"] ?: 0,
blue = map["blue"] ?: 0
)
}
private fun maxOf(a: Draw, b: Draw) = Draw(
red = maxOf(a.red, b.red),
green = maxOf(a.green, b.green),
blue = maxOf(a.blue, b.blue)
) | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,519 | advent-of-code | MIT License |
src/Day07.kt | BrianEstrada | 572,700,177 | false | {"Kotlin": 22757} | fun main() {
// Test Case
val testInput = readInput("Day07_test")
val part1TestResult = Day07.part1(testInput)
println(part1TestResult)
check(part1TestResult == 95437)
val part2TestResult = Day07.part2(testInput)
println(part2TestResult)
check(part2TestResult.second == 24933642)
// Actual Case
val input = readInput("Day07")
println("Part 1: " + Day07.part1(input))
println("Part 2: " + Day07.part2(input))
}
private object Day07 {
fun part1(lines: List<String>): Int {
return buildDirectories(lines).getDirectoriesBySize { fileSize -> fileSize < 100_000 }.sumOf { it.second }
}
fun part2(lines: List<String>): Pair<String, Int> {
val maxSpace = 70_000_000
val requiredSpace = 30_000_000
val rootDirectory = buildDirectories(lines)
val directories = rootDirectory.getDirectoriesBySize { fileSize ->
fileSize >= rootDirectory.fileSize() - (maxSpace - requiredSpace)
}
return directories.minBy { it.second }
}
private fun buildDirectories(lines: List<String>): Directory {
val rootDirectory = Directory("/")
var currentDirectory: Directory? = null
var lastCommand: Command.Type? = null
for (line in lines) {
val command = Command(line.split(" "))
if (command.isCommand) {
lastCommand = command.getType()
if (lastCommand != Command.Type.ChangeDirectory) continue
currentDirectory = when (command.thirdValue) {
"/" -> rootDirectory
".." -> currentDirectory?.parentDirectory
else -> currentDirectory?.directories?.first { directory ->
directory.name == command.thirdValue
}
}
} else {
if (lastCommand == Command.Type.List) {
if (command.firstValue == "dir") {
currentDirectory?.directories?.add(
Directory(command.secondValue).apply {
parentDirectory = currentDirectory
}
)
} else {
currentDirectory?.files?.set(
command.secondValue,
command.firstValue.toInt()
)
}
}
}
}
return rootDirectory
}
data class Command(
val firstValue: String,
val secondValue: String,
val thirdValue: String?,
) {
constructor(values: List<String>) : this(
firstValue = values[0],
secondValue = values[1],
thirdValue = values.getOrNull(2)
)
val isCommand: Boolean = (firstValue == "$")
fun getType(): Type {
return Type.parse(secondValue)
}
enum class Type(val value: String) {
ChangeDirectory("cd"),
List("ls");
companion object {
fun parse(value: String): Type {
return values().first { it.value == value }
}
}
}
}
data class Directory(
val name: String,
val files: MutableMap<String, Int> = mutableMapOf(),
val directories: MutableSet<Directory> = mutableSetOf(),
) {
var parentDirectory: Directory? = null
fun getDirectoriesBySize(op: (fileSize: Int) -> Boolean): List<Pair<String, Int>> {
return buildList {
val fileSize = fileSize()
if (op(fileSize)) {
add(name to fileSize)
}
addAll(
directories.map { it.getDirectoriesBySize(op) }.flatten()
)
}
}
fun fileSize(): Int {
return files.map { it.value }.sum() + directories.sumOf { it.fileSize() }
}
}
} | 1 | Kotlin | 0 | 1 | 032a4693aff514c9b30e979e63560dc48917411d | 4,062 | aoc-kotlin-2022 | Apache License 2.0 |
src/year2022/day24/Day24.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day24
import check
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day24_test")
check(part1(testInput), 18)
check(part2(testInput), 54)
val input = readInput("2022", "Day24")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val (walls, blizzards) = parseWallsAndBlizzards(input)
val (start, target) = getStartAndTarget(input)
return getStepsThroughBlizzardValley(start, target, walls, blizzards)
}
private fun part2(input: List<String>): Int {
val (walls, blizzards) = parseWallsAndBlizzards(input)
val (start, target) = getStartAndTarget(input)
val p1 = getStepsThroughBlizzardValley(start, target, walls, blizzards)
val p2 = getStepsThroughBlizzardValley(target, start, walls, blizzards)
val p3 = getStepsThroughBlizzardValley(start, target, walls, blizzards)
return p1 + p2 + p3
}
private fun parseWallsAndBlizzards(input: List<String>): Pair<Set<Pos>, List<Blizzard>> {
val walls = mutableSetOf<Pos>()
val blizzards = mutableListOf<Blizzard>()
input.forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
if (c == '#') walls += Pos(x, y)
if (c != '#' && c != '.') {
val pos = Pos(x, y)
val dir = c.toDir()
blizzards += Blizzard(pos, dir)
}
}
}
return walls to blizzards
}
private fun getStartAndTarget(input: List<String>): Pair<Pos, Pos> {
val start = input.first().indexOfFirst { it == '.' }.let { Pos(it, 0) }
val target = input.last().indexOfFirst { it == '.' }.let { Pos(it, input.lastIndex) }
return start to target
}
private data class Pos(val x: Int, val y: Int) {
val possibleMoves
get() = listOf(
this, // wait
Pos(x, y + 1), // N
Pos(x + 1, y), // E
Pos(x, y - 1), // S
Pos(x - 1, y), // W
)
}
private enum class Direction {
N, E, S, W
}
private fun Char.toDir() = when (this) {
'^' -> Direction.N
'>' -> Direction.E
'v' -> Direction.S
'<' -> Direction.W
else -> error("$this cannot be mapped to a direction")
}
private class Blizzard(var pos: Pos, val dir: Direction) {
fun move(maxX: Int, maxY: Int) {
pos = nextBlizzardPosition(pos, dir, maxX, maxY)
}
}
private fun nextBlizzardPosition(current: Pos, dir: Direction, maxX: Int, maxY: Int): Pos {
val next = when (dir) {
Direction.N -> Pos(current.x, current.y - 1)
Direction.E -> Pos(current.x + 1, current.y)
Direction.S -> Pos(current.x, current.y + 1)
Direction.W -> Pos(current.x - 1, current.y)
}
return when {
next.x < 1 -> Pos(maxX, next.y)
next.x > maxX -> Pos(1, next.y)
next.y < 1 -> Pos(next.x, maxY)
next.y > maxY -> Pos(next.x, 1)
else -> next
}
}
private fun getStepsThroughBlizzardValley(
start: Pos,
target: Pos,
walls: Set<Pos>,
blizzards: List<Blizzard>,
): Int {
val maxX = walls.maxOf { it.x } - 1
val maxY = walls.maxOf { it.y } - 1
blizzards.forEach { it.move(maxX, maxY) }
val yRange = 0..maxY + 1
var positions = setOf(start)
var steps = 0
while (true) {
val blockedByBlizzard = blizzards.mapTo(hashSetOf()) { it.pos }
positions = positions.flatMapTo(hashSetOf()) { it.possibleMoves }.filterTo(hashSetOf()) {
it !in blockedByBlizzard && it !in walls && it.y in yRange
}
steps++
if (target in positions) break
blizzards.forEach { it.move(maxX, maxY) }
}
return steps
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 3,740 | AdventOfCode | Apache License 2.0 |
src/Day09.kt | iartemiev | 573,038,071 | false | {"Kotlin": 21075} | import kotlin.math.abs
data class Point(val x: Int, val y: Int) {
operator fun minus(point2: Point): Point {
return Point(abs(x - point2.x), abs(y - point2.y))
}
}
class Bridge(private val tailLength: Int = 1) {
private val knotPositions: MutableList<Point> = MutableList(tailLength + 1) { Point(0, 0) }
private val tailPointsVisited = mutableSetOf(Point(0, 0))
fun move(direction: Char, steps: Int) {
for (i in 1..steps) {
moveHead(direction)
for (j in 1.. tailLength) {
moveTail(j)
}
}
}
fun visitedSize(): Int {
return tailPointsVisited.size
}
private fun moveHead(direction: Char) {
val headPos = knotPositions[0]
knotPositions[0] = when (direction) {
'U' -> Point(headPos.x, headPos.y + 1)
'D' -> Point(headPos.x, headPos.y - 1)
'L' -> Point(headPos.x - 1, headPos.y)
'R' -> Point(headPos.x + 1, headPos.y)
else -> throw IllegalArgumentException("Invalid direction $direction")
}
}
private fun moveTail(pos: Int) {
val currentKnot = knotPositions[pos]
val prevKnot = knotPositions[pos - 1]
val (diffX, diffY) = prevKnot - currentKnot
if (diffX < 2 && diffY < 2) return
// stole the compareTo use from Cathrin
knotPositions[pos] = Point(
currentKnot.x + prevKnot.x.compareTo(currentKnot.x),
currentKnot.y + prevKnot.y.compareTo(currentKnot.y)
)
if (pos == tailLength) {
tailPointsVisited.add(knotPositions[pos])
}
}
}
fun ropeBridge(bridge: Bridge, input: List<String>) {
for (line in input) {
val (direction, steps) = line.split(" ").map { if (it.matches("\\d+".toRegex())) it.toInt() else it.single() }
bridge.move(direction as Char, steps as Int)
}
}
fun main() {
fun part1(input: List<String>): Int {
val bridge = Bridge()
ropeBridge(bridge, input)
return bridge.visitedSize()
}
fun part2(input: List<String>): Int {
val bridge = Bridge(9)
ropeBridge(bridge, input)
return bridge.visitedSize()
}
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 | 0 | 8d2b7a974c2736903a9def65282be91fbb104ffd | 2,305 | advent-of-code | Apache License 2.0 |
src/Day01.kt | peterfortuin | 573,120,586 | false | {"Kotlin": 22151} | fun main() {
fun part1(input: List<String>): Int {
val elfs = input.asElfs()
val caloriesPerElf = elfs.map { elfCaloriesList ->
elfCaloriesList.map { calories ->
calories.toInt()
}.toIntArray().sum()
}
val highestCaloryElf = caloriesPerElf.foldIndexed(Pair<Int, Int>(0, 0)) { index, acc, elfCalories ->
if (elfCalories > acc.second) {
Pair(index, elfCalories)
} else {
acc
}
}
return highestCaloryElf.second
}
fun part2(input: List<String>): Int {
val elfs = input.asElfs()
val caloriesPerElf = elfs.map { elfCaloriesList ->
elfCaloriesList.map { calories ->
calories.toInt()
}.toIntArray().sum()
}
val top3Elfs = caloriesPerElf.sortedDescending().subList(0, 3)
val totalOfTop3 = top3Elfs.sum()
return totalOfTop3
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println("Part 1 = ${part1(input)}")
println("Part 2 = ${part2(input)}")
}
fun List<String>.asElfs(): List<List<String>> {
val elfList = mutableListOf<MutableList<String>>()
elfList.add(mutableListOf())
return this.fold(elfList) { acc, line ->
if (line.isBlank()) {
elfList.add(mutableListOf())
} else {
elfList.last().add(line)
}
acc
}
}
| 0 | Kotlin | 0 | 0 | c92a8260e0b124e4da55ac6622d4fe80138c5e64 | 1,629 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode/year2020/Day16TicketTranslation.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2020
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.common.product
class Day16TicketTranslation(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val ticketRules by lazy {
input
.split("\n\n")
.first()
.lines()
.map { it.split(": ") }
.map { TicketRule(it.first(), it.last().split(" or ").map { it.split("-").first().toInt()..it.split("-").last().toInt() }) }
}
private val yourTicket by lazy { input.split("\n\n")[1].lines().last().split(",").map(String::toInt) }
private val nearbyTickets by lazy {
input
.split("\n\n")
.last()
.lines()
.drop(1)
.map { it.split(",").map(String::toInt) }
}
override fun partOne() = nearbyTickets
.flatMap { ticket -> ticket.filter { ticketRules.flatMap(TicketRule::ranges).none { rule -> rule.contains(it) } } }
.sum()
override fun partTwo(): Long {
val validNearbyTickets = nearbyTickets
.filter { ticket -> ticket.all { ticketRules.flatMap(TicketRule::ranges).any { rule -> rule.contains(it) } } }
val rulesWithIndex = ticketRules
.map { rule ->
val possibleIndices = (yourTicket.indices)
.filter { index -> validNearbyTickets.map { it[index] }.all { rule.ranges.any { range -> range.contains(it) } } }
rule to possibleIndices.toMutableList()
}
repeat((ticketRules.indices).count()) {
val unique = rulesWithIndex.map { it.second }.filter { it.size == 1 }.flatten()
rulesWithIndex.filter { it.second.size > 1 }.map { Pair(it.first, it.second.removeAll(unique)) }
}
return rulesWithIndex
.map { Pair(it.first, it.second.first()) }
.filter { it.first.name.startsWith("departure") }
.map { yourTicket[it.second].toLong() }
.product()
}
companion object {
private data class TicketRule(
val name: String,
val ranges: List<IntRange>
)
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 2,186 | AdventOfCode | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.