path
stringlengths 5
169
| owner
stringlengths 2
34
| repo_id
int64 1.49M
755M
| is_fork
bool 2
classes | languages_distribution
stringlengths 16
1.68k
⌀ | content
stringlengths 446
72k
| issues
float64 0
1.84k
| main_language
stringclasses 37
values | forks
int64 0
5.77k
| stars
int64 0
46.8k
| commit_sha
stringlengths 40
40
| size
int64 446
72.6k
| name
stringlengths 2
64
| license
stringclasses 15
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/day8.kt
|
gautemo
| 572,204,209 | false |
{"Kotlin": 78294}
|
import shared.getText
import shared.takeWhileInclusive
fun main(){
val input = getText("day8.txt")
println(day8A(input))
println(day8B(input))
}
fun day8A(input: String): Int {
val trees = toTrees(input)
var count = 0
for(y in trees.indices) {
for((x, tree) in trees[y].withIndex()) {
val visibleTreesLeft = treesLeft(tree, x, y, trees)
val visibleTreesRight = treesRight(tree, x, y, trees)
val visibleTreesUp = treesUp(tree, x, y, trees)
val visibleTreesDown = treesDown(tree, x, y, trees)
val isVisibleLeft = visibleTreesLeft.isEmpty() || visibleTreesLeft.all { it < tree }
val isVisibleRight = visibleTreesRight.isEmpty() || visibleTreesRight.all { it < tree }
val isVisibleUp = visibleTreesUp.isEmpty() || visibleTreesUp.all { it < tree }
val isVisibleDown = visibleTreesDown.isEmpty() || visibleTreesDown.all { it < tree }
if(isVisibleLeft || isVisibleRight || isVisibleUp || isVisibleDown) {
count++
}
}
}
return count
}
fun day8B(input: String): Int {
val trees = toTrees(input)
var best = 0
for(y in trees.indices) {
for((x, tree) in trees[y].withIndex()) {
val visibleTreesLeft = treesLeft(tree, x, y, trees)
val visibleTreesRight = treesRight(tree, x, y, trees)
val visibleTreesUp = treesUp(tree, x, y, trees)
val visibleTreesDown = treesDown(tree, x, y, trees)
best = maxOf(best, visibleTreesLeft.size * visibleTreesRight.size * visibleTreesUp.size * visibleTreesDown.size)
}
}
return best
}
private fun toTrees(input: String): List<List<Int>> {
return input.lines().map { line -> line.map { it.digitToInt() } }
}
private fun treesLeft(height: Int, xPos: Int, yPos: Int, trees: List<List<Int>>): List<Int> {
return trees[yPos].filterIndexed{ x, _ -> x < xPos }.reversed().takeWhileInclusive { it < height }
}
private fun treesRight(height: Int, xPos: Int, yPos: Int, trees: List<List<Int>>): List<Int> {
return trees[yPos].filterIndexed{ x, _ -> x > xPos }.takeWhileInclusive { it < height }
}
private fun treesUp(height: Int, xPos: Int, yPos: Int, trees: List<List<Int>>): List<Int> {
return trees.filterIndexed { y, _ -> y < yPos }.map { it[xPos] }.reversed().takeWhileInclusive { it < height }
}
private fun treesDown(height: Int, xPos: Int, yPos: Int, trees: List<List<Int>>): List<Int> {
return trees.filterIndexed { y, _ -> y > yPos }.map { it[xPos] }.takeWhileInclusive { it < height }
}
| 0 |
Kotlin
| 0 | 0 |
bce9feec3923a1bac1843a6e34598c7b81679726
| 2,613 |
AdventOfCode2022
|
MIT License
|
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-13.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.readInputText
fun main() {
val input = readInputText(2022, "13-input")
val testInput1 = readInputText(2022, "13-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput1).println()
part2(input).println()
}
private fun part1(input: String): Int {
val pairs = input.split("\n\n")
.map { pair -> pair.lines().map { parse(it).first } }
.map { (a, b) -> a to b }
return pairs.map { compare(it.first, it.second) }
.mapIndexed { index, comp -> if (0 < comp) index + 1 else 0 }
.sum()
}
private fun part2(input: String): Int {
val decoders = listOf("[[2]]", "[[6]]").map { parse(it).first }
val packets = input.lines().filter { it.isNotBlank() }.map { parse(it).first } + decoders
val sorted = packets.sortedWith(::compare).reversed()
val i1 = sorted.indexOf(decoders[0]) + 1
val i2 = sorted.indexOf(decoders[1]) + 1
return i1 * i2
}
private sealed class Value {
data class List(val values: kotlin.collections.List<Value>): Value() {
override fun toString(): String {
return values.toString()
}
}
data class Number(val value: Int): Value() {
override fun toString(): String {
return value.toString()
}
}
}
private fun compare(left: Value, right: Value): Int {
when {
left is Value.Number && right is Value.Number -> return right.value - left.value
left is Value.List && right is Value.List -> {
var index = 0
while (index < left.values.size && index < right.values.size) {
val next = compare(left.values[index], right.values[index])
if (next != 0) return next
index++
}
return right.values.size - left.values.size
}
left is Value.Number && right is Value.List -> return compare(Value.List(listOf(left)), right)
left is Value.List && right is Value.Number -> return compare(left, Value.List(listOf(right)))
else -> error("impossibiru")
}
}
private fun parse(text: String, position: Int = 0): Pair<Value, Int> {
return if (text[position] == '[') {
val list = mutableListOf<Value>()
var nextPos = position + 1
while (text[nextPos] != ']') {
val next = parse(text, nextPos)
list += next.first
nextPos = next.second
if (text[nextPos] == ',') nextPos++
}
Value.List(list) to nextPos + 1
} else {
var nextPos = position + 1
while (text[nextPos].isDigit()) nextPos++
Value.Number(text.substring(position, nextPos).toInt()) to nextPos
}
}
| 0 |
Kotlin
| 0 | 1 |
f4890c25841c78784b308db0c814d88cf2de384b
| 2,888 |
advent-of-code
|
MIT License
|
src/Day02.kt
|
PascalHonegger
| 573,052,507 | false |
{"Kotlin": 66208}
|
private enum class Hand(val score: Int) {
Rock(score = 1),
Paper(score = 2),
Scissor(score = 3),
}
private enum class RoundResult(val score: Int) {
Win(score = 6),
Draw(score = 3),
Lose(score = 0),
}
fun main() {
fun String.toHand() = when(this) {
"A" -> Hand.Rock
"B"-> Hand.Paper
"C" -> Hand.Scissor
"X" -> Hand.Rock
"Y"-> Hand.Paper
"Z" -> Hand.Scissor
else -> error("Failed to parse '$this'")
}
fun String.toRoundResult() = when(this) {
"X" -> RoundResult.Lose
"Y"-> RoundResult.Draw
"Z" -> RoundResult.Win
else -> error("Failed to parse '$this'")
}
infix fun Hand.beats(other: Hand) =
this == Hand.Scissor && other == Hand.Paper ||
this == Hand.Rock && other == Hand.Scissor ||
this == Hand.Paper && other == Hand.Rock
fun part1(input: List<String>): Int {
return input.sumOf { round ->
val (opponent, recommendation) = round.split(' ').map { it.toHand() }
val result = when {
recommendation == opponent -> RoundResult.Draw
recommendation beats opponent -> RoundResult.Win
else -> RoundResult.Lose
}
result.score + recommendation.score
}
}
fun part2(input: List<String>): Int {
return input.sumOf { round ->
val (hint1, hint2) = round.split(' ')
val opponent = hint1.toHand()
val result = hint2.toRoundResult()
val recommendation = when(result) {
RoundResult.Draw -> opponent
RoundResult.Win -> Hand.values().first { it beats opponent }
RoundResult.Lose -> Hand.values().first { opponent beats it }
}
result.score + recommendation.score
}
}
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 |
2215ea22a87912012cf2b3e2da600a65b2ad55fc
| 2,097 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day14.kt
|
Excape
| 572,551,865 | false |
{"Kotlin": 36421}
|
fun main() {
val sandDirections = listOf(Pair(0, 1), Pair(-1, 1), Pair(1, 1))
fun createWall(points: List<Point>) = points.windowed(2)
.flatMap { (first, second) ->
(if (first.x > second.x) first.x downTo second.x else first.x..second.x).flatMap { x ->
(if (first.y > second.y) first.y downTo second.y else first.y..second.y).map { y ->
Point(x, y)
}
}
}.toSet()
fun prettyPrint(grid: Map<Point, Char>) {
val points = grid.keys
(points.minOf { it.y }..points.maxOf { it.y }).forEach { y ->
(points.minOf { it.x }..points.maxOf { it.x }).forEach { x ->
print(grid[Point(x, y)] ?: ".")
}
print('\n')
}
}
fun simulateSandUnit(
filled: Map<Point, Char>,
lowestWall: Int,
path: ArrayDeque<Point>
): Point {
val sandPath = generateSequence(path.last()) { current ->
sandDirections.map { (dx, dy) -> Point(current.x + dx, current.y + dy) }
.firstOrNull { !filled.contains(it) && it.y < lowestWall + 2 }
}.toList()
sandPath.dropLast(1).forEach { path.addLast(it) }
return sandPath.last()
}
fun simulateSand(grid: Map<Point, Char>, part1: Boolean = false): Map<Point, Char> {
val filled = grid.toMutableMap()
val path = ArrayDeque(listOf(Point(500, 0)))
val lowestWall = grid.keys.maxOf { it.y }
while (path.isNotEmpty()) {
val nextSand = simulateSandUnit(filled, lowestWall, path)
if (part1 && nextSand.y > lowestWall) {
return filled
}
filled[nextSand] = 'o'
path.removeLast()
}
return filled
}
fun parseWalls(input: List<String>) = input.map { line ->
line.split(" -> ")
.map { coords -> coords.split(",") }
.map { Point(it[0].toInt(), it[1].toInt()) }
}.flatMap { createWall(it) }.associateWith { '#' }
fun execute(input: List<String>, part1: Boolean): Int {
val grid = parseWalls(input)
val filledGrid = simulateSand(grid, part1)
prettyPrint(filledGrid)
return filledGrid.values.count {it == 'o'}
}
fun part1(input: List<String>) = execute(input, true)
fun part2(input: List<String>) = execute(input, false)
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
val part1Answer = part1(input)
val part2Answer = part2(input)
println("part 1: $part1Answer")
println("part 2: $part2Answer")
}
| 0 |
Kotlin
| 0 | 0 |
a9d7fa1e463306ad9ea211f9c037c6637c168e2f
| 2,681 |
advent-of-code-2022
|
Apache License 2.0
|
src/year2023/day03/Day.kt
|
tiagoabrito
| 573,609,974 | false |
{"Kotlin": 73752}
|
package year2023.day03
import year2023.solveIt
fun main() {
val day = "03"
val expectedTest1 = 4361L
val expectedTest2 = 467835L
data class Piece(val l:Int, val c:Int, val len:Int, val id:Int)
fun getParts(input: List<String>) = input.flatMapIndexed { lNumber, line ->
line.mapIndexedNotNull { index, c ->
if (c.isDigit() && (index == 0 || !line[index - 1].isDigit())) {
val number = line.substring(index).takeWhile { it.isDigit() }
Piece(lNumber, index, number.length, number.toInt())
} else
null
}
}
fun part1(input: List<String>): Long {
val parts = getParts(input)
val mapIndexed = parts.filter { partNumber ->
input.subList(maxOf(0, partNumber.l - 1), minOf(input.size, partNumber.l + 2)).flatMap { l ->
l.substring(
maxOf(0, partNumber.c - 1), minOf(l.length, partNumber.c + partNumber.len + 1)
).toList()
}.any { c -> !c.isDigit() && c != '.' }
}.map { it.id }
return mapIndexed.sum().toLong()
}
fun part2(input: List<String>): Long {
val parts = getParts(input)
val asterisks = input.flatMapIndexed { l, line ->
line.mapIndexedNotNull { c, v ->
when (v == '*') {
true -> l to c
false -> null
}
}.toList()
}
return asterisks.map { a ->
parts.filter { it.l in (a.first - 1)..(a.first + 1) }.filter { it.c in (a.second - it.len)..(a.second + 1) }
}.filter { it.size == 2 }.sumOf { it[0].id * it[1].id }.toLong()
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2)
}
| 0 |
Kotlin
| 0 | 0 |
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
| 1,800 |
adventOfCode
|
Apache License 2.0
|
src/year2023/day15/Day.kt
|
tiagoabrito
| 573,609,974 | false |
{"Kotlin": 73752}
|
package year2023.day15
import year2023.solveIt
fun main() {
val day = "15"
val expectedTest1 = 1320L
val expectedTest2 = 145L
fun hash(s: String): Int {
return s.asSequence().fold(0) { acc, c ->
((acc + c.code) * 17) % 256
}
}
fun part1(input: List<String>): Long {
return input.flatMap { it.split(",") }.sumOf { hash(it) }.toLong()
}
fun combine(key: String, value: String, first: Boolean, accumulator: List<Pair<String, Int>>?): List<Pair<String, Int>> {
if (first) {
return listOf(key to value.toInt())
}
val kIndex = accumulator!!.indexOfFirst { it.first == key }
return if (kIndex == -1) {
accumulator + (key to value.toInt())
} else {
accumulator.subList(0, kIndex) + (key to value.toInt()) + accumulator.subList(kIndex+1, accumulator.size)
}
}
fun part2(input: List<String>): Long {
val boxes = List(256) { listOf<Pair<String, Int>>() }
val groupBy = input.flatMap { it.split(",") }.groupingBy { hash(it.split('-', '=')[0]) }
.aggregate { _, accumulator: List<Pair<String, Int>>?, element, first ->
val (k, value) = element.split('-', '=')
if (element.endsWith("-")) {
(accumulator ?: listOf()).filter { it.first != k }
} else {
combine(k, value, first, accumulator)
}
}
val flatten = groupBy.map { entry -> entry.value.mapIndexed { index, pair -> (entry.key+1) * (index + 1) * pair.second } }.flatten()
return flatten.sum().toLong()
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test")
}
| 0 |
Kotlin
| 0 | 0 |
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
| 1,758 |
adventOfCode
|
Apache License 2.0
|
src/Day08.kt
|
Excape
| 572,551,865 | false |
{"Kotlin": 36421}
|
data class Coords(val y: Int, val x: Int)
fun main() {
val directions = listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1))
fun isInBounds(grid: List<List<Int>>, coords: Coords) =
coords.x >= 0 && coords.y >= 0 && coords.y < grid.size && coords.x < grid[coords.y].size
fun applyDirection(coords: Coords, direction: Pair<Int, Int>) =
Coords(coords.y + direction.first, coords.x + direction.second)
fun isVisibleInDirection(coords: Coords, grid: List<List<Int>>, direction: Pair<Int, Int>): Boolean {
val height = grid[coords.y][coords.x]
var current = applyDirection(coords, direction)
while (isInBounds(grid, current)) {
if (grid[current.y][current.x] >= height)
return false
current = applyDirection(current, direction)
}
return true
}
fun isVisible(coords: Coords, grid: List<List<Int>>): Boolean {
return directions.any { dir -> isVisibleInDirection(coords, grid, dir) }
}
fun mapInputToGrid(input: List<String>) = input.map { it.map { it.digitToInt() } }
fun part1(input: List<String>): Int {
val grid = mapInputToGrid(input)
val boundX = grid[0].size - 1
val boundY = grid.size - 1
val treesOnBorder = boundX * 2 + boundY * 2
val visibleTrees = (1 until boundY).flatMap { y ->
(1 until boundX).map { x ->
isVisible(Coords(y, x), grid)
}
}.count { it }
return treesOnBorder + visibleTrees
}
fun getViewingDistance(coords: Coords, grid: List<List<Int>>, direction: Pair<Int, Int>): Int {
val height = grid[coords.y][coords.x]
var current = applyDirection(coords, direction)
var viewingDistance = 0
while (isInBounds(grid, current)) {
if (grid[current.y][current.x] >= height)
return viewingDistance + 1
viewingDistance++
current = applyDirection(current, direction)
}
return viewingDistance
}
fun getScenicScore(coords: Coords, grid: List<List<Int>>): Int {
return directions.map { dir -> getViewingDistance(coords, grid, dir) }.reduce { acc, n -> acc * n }
}
fun part2(input: List<String>): Int {
val grid = mapInputToGrid(input)
val boundX = grid[0].size - 1
val boundY = grid.size - 1
return (1 until boundY).flatMap { y ->
(1 until boundX).map { x ->
getScenicScore(Coords(y, x), grid)
}
}.max()
}
val testInput = readInput("Day08_test")
println(part1(testInput))
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
val part1Answer = part1(input)
val part2Answer = part2(input)
println("part 1: $part1Answer")
println("part 2: $part2Answer")
}
| 0 |
Kotlin
| 0 | 0 |
a9d7fa1e463306ad9ea211f9c037c6637c168e2f
| 2,899 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/Day02.kt
|
michaeljwood
| 572,560,528 | false |
{"Kotlin": 5391}
|
fun main() {
fun part1(input: List<String>) = input.filter { it.isNotBlank() }
.map { it.split(" ") }
.map { Pair(RockPaperScissors.fromString(it.first()), RockPaperScissors.fromString(it[1])) }
.sumOf { it.first.score(it.second) }
fun part2(input: List<String>) = input.filter { it.isNotBlank() }
.map { it.split(" ") }
.map { Pair(RockPaperScissors.fromString(it.first()), it[1]) }
.sumOf { it.first.score(it.second) }
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("day2/test")
check(part1(testInput) == 15)
val input = readInputLines("day2/input")
println(part1(input))
println(part2(input))
}
private enum class RockPaperScissors(private val codes: List<String>, private val value: Int) {
rock(listOf("A", "X"), 1),
paper(listOf("B", "Y"), 2),
scissors(listOf("C", "Z"), 3);
fun score(mine: RockPaperScissors) = when {
this == mine -> 3 + mine.value
this == rock && mine == paper ||
this == paper && mine == scissors ||
this == scissors && mine == rock -> 6 + mine.value
else -> 0 + mine.value
}
fun score(mine: String) = when {
mine == "Y" -> 3 + this.value
mine == "Z" -> 6 + this.pickWinner().value
else -> this.pickLoser().value
}
fun pickLoser() = when {
this == rock -> scissors
this == paper -> rock
else -> paper
}
fun pickWinner() = when {
this == rock -> paper
this == paper -> scissors
else -> rock
}
companion object {
fun fromString(value: String) = RockPaperScissors.values().first { value in it.codes }
}
}
| 0 |
Kotlin
| 0 | 0 |
8df2121f12a5a967b25ce34bce6678ab9afe4aa7
| 1,758 |
advent-of-code-2022
|
Apache License 2.0
|
src/day07/Code.kt
|
ldickmanns
| 572,675,185 | false |
{"Kotlin": 48227}
|
package day07
import readInput
fun main() {
val input = readInput("day07/input")
// val input = readInput("day07/input_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val fileTree = parseToTree(input)
return sumSizes(fileTree, 0)
}
sealed interface Node {
val name: String
val size: Int
val parent: Directory?
}
data class Directory(
override val name: String,
override val parent: Directory?,
val children: MutableList<Node> = mutableListOf(),
) : Node {
override val size: Int
get() = children.sumOf { it.size }
}
data class File(
override val name: String,
override val size: Int,
override val parent: Directory?,
) : Node
private fun parseToTree(input: List<String>): Node {
val rootNode = Directory("/", null)
var currentDirectory = rootNode
input.forEach { line ->
when {
line.startsWith("$ cd ") -> {
val destination = line.substringAfter("$ cd ")
currentDirectory = when (destination) {
"/" -> rootNode
".." -> currentDirectory.parent ?: rootNode
else -> currentDirectory.children.find { it.name == destination } as Directory
}
}
line.startsWith("$ ls") -> {}
line.startsWith("dir ") -> {
val name = line.substringAfter("dir ")
currentDirectory.children.add(Directory(name, currentDirectory))
}
else -> {
val parts = line.split(" ")
val size = parts.first().toInt()
val name = parts.last()
currentDirectory.children.add(File(name, size, currentDirectory))
}
}
}
return rootNode
}
fun sumSizes(node: Node, sizeSum: Int): Int = when (node) {
is File -> 0
is Directory -> {
var newSizeSum = if (node.size <= 100_000) sizeSum + node.size else sizeSum
node.children.forEach {
newSizeSum += sumSizes(it, 0)
}
newSizeSum
}
}
fun part2(input: List<String>): Int {
val fileTree = parseToTree(input)
val totalSize = 70_000_000
val requiredForUpdate = 30_000_000
val totalOccupied = fileTree.size
val free = totalSize - totalOccupied
val atLeastDelete = requiredForUpdate - free
return findCandidate(
node = fileTree,
currentCandidate = totalOccupied,
atLeastDelete = atLeastDelete,
)
}
fun findCandidate(
node: Node,
currentCandidate: Int,
atLeastDelete: Int,
): Int {
when (node) {
is File -> return 0
is Directory -> {
val nodeSize = node.size
if (nodeSize < atLeastDelete) return currentCandidate
var newCandidate = currentCandidate
if (nodeSize in atLeastDelete until currentCandidate) newCandidate = nodeSize
node.children.forEach {
val childSize = findCandidate(it, newCandidate, atLeastDelete)
if (childSize in atLeastDelete until newCandidate) newCandidate = childSize
}
return newCandidate
}
}
}
| 0 |
Kotlin
| 0 | 0 |
2654ca36ee6e5442a4235868db8174a2b0ac2523
| 3,234 |
aoc-kotlin-2022
|
Apache License 2.0
|
src/DaySix.kt
|
P-ter
| 573,301,805 | false |
{"Kotlin": 9464}
|
fun main() {
val map = buildMap<Int, MutableList<Boolean>> {
(0 .. 999).forEach {row ->
this[row] = (0 .. 999).map { false }.toMutableList()
}
}
fun part1(input: List<String>): Int {
var total = 0
val firstMap = map.toMap().toMutableMap()
input.forEach { line ->
val word = line.split(" ")
val (from, to) = word.filter { it.contains(",") }
val (fromX, fromY) = from.split(",").map { it.toInt() }
val (toX, toY) = to.split(",").map { it.toInt() }
for(i in fromX .. toX) {
for(y in fromY .. toY) {
if(line.contains("toggle")) {
firstMap[i]?.set(y, !firstMap[i]?.get(y)!!)
} else if (line.contains("turn off")) {
firstMap[i]?.set(y, false)
} else if (line.contains("turn on")){
firstMap[i]?.set(y, true)
}
}
}
}
total = firstMap.values.fold(0) { count, row ->
count + row.count { it == true }
}
return total
}
fun part2(input: List<String>): Int {
val secondMap = buildMap<Int, MutableList<Int>> {
(0 .. 999).forEach {row ->
this[row] = (0 .. 999).map { 0 }.toMutableList()
}
}
var total = 0
input.forEach { line ->
val word = line.split(" ")
val (from, to) = word.filter { it.contains(",") }
val (fromX, fromY) = from.split(",").map { it.toInt() }
val (toX, toY) = to.split(",").map { it.toInt() }
for(i in fromX .. toX) {
for(y in fromY .. toY) {
if(line.contains("toggle")) {
secondMap[i]?.set(y, secondMap[i]?.get(y)!! + 2)
} else if (line.contains("turn off")) {
secondMap[i]?.set(y, (secondMap[i]?.get(y)!! - 1).takeIf { it >= 0 } ?: 0)
} else if (line.contains("turn on")){
secondMap[i]?.set(y, secondMap[i]?.get(y)!! + 1)
}
}
}
}
total = secondMap.values.fold(0) { count, row ->
count + row.reduce { acc, i -> acc + i }
}
return total
}
val input = readInput("daysix")
// val input = listOf("toggle 0,0 through 999,0")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
fc46b19451145e0c41b1a50f62c77693865f9894
| 2,538 |
aoc-2015
|
Apache License 2.0
|
src/day14/Day14.kt
|
Volifter
| 572,720,551 | false |
{"Kotlin": 65483}
|
package day14
import utils.*
val SAND_SOURCE_COORDS = Coords(500, 0)
data class Coords(var x: Int, var y: Int) {
fun coerceIn(range: IntRange): Coords =
Coords(x.coerceIn(range), y.coerceIn(range))
operator fun plus(other: Coords): Coords = Coords(x + other.x, y + other.y)
operator fun minus(other: Coords): Coords = Coords(x - other.x, y - other.y)
operator fun contains(other: Coords): Boolean =
other.x in 0 until x
&& other.y in 0 until y
override operator fun equals(other: Any?): Boolean =
other is Coords
&& other.x == x
&& other.y == y
override fun hashCode(): Int = x * 31 + y
}
fun parseRockLines(input: List<String>): List<List<Coords>> =
input.map { line ->
line.split(" -> ").map { coords ->
val (x, y) = coords.split(",").map(String::toInt)
Coords(x, y)
}
}
fun getMapFromRockLines(rockLines: List<List<Coords>>): Set<Coords> {
val map = mutableSetOf<Coords>()
rockLines.forEach { rockLine ->
rockLine.windowed(2).forEach { (from, to) ->
val dir = (to - from).coerceIn(-1..1)
map.addAll(
generateSequence(from) { it + dir }.takeWhile { it != to + dir }
)
}
}
return map
}
fun dropSand(map: Set<Coords>, height: Int): Coords =
generateSequence (SAND_SOURCE_COORDS) { coords ->
listOf(
coords + Coords(0, 1),
coords + Coords(-1, 1),
coords + Coords(1, 1)
).find { it !in map }
}
.takeWhile { it.y <= height }
.last()
fun part1(input: List<String>): Int {
val map = getMapFromRockLines(parseRockLines(input)).toMutableSet()
val height = map.maxOf { it.y }
return generateSequence { dropSand(map, height).also { map.add(it) } }
.takeWhile { it.y < height }
.count()
}
fun part2(input: List<String>): Int {
val map = getMapFromRockLines(parseRockLines(input)).toMutableSet()
val height = map.maxOf { it.y } + 1
return generateSequence { dropSand(map, height).also { map.add(it) } }
.takeWhile { SAND_SOURCE_COORDS !in map }
.count() + 1
}
fun main() {
val testInput = readInput("Day14_test")
expect(part1(testInput), 24)
expect(part2(testInput), 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
c2c386844c09087c3eac4b66ee675d0a95bc8ccc
| 2,430 |
AOC-2022-Kotlin
|
Apache License 2.0
|
2022/Day15/problems.kt
|
moozzyk
| 317,429,068 | false |
{"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794}
|
import java.io.File
import kotlin.math.*
data class Position(val x: Int, val y: Int) {}
fun main(args: Array<String>) {
val lines = File(args[0]).readLines()
val regex = """x=(-?\d+).*y=(-?\d+).*x=(-?\d+).*y=(-?\d+)""".toRegex()
val input =
lines.map {
regex.find(it)!!.destructured.let {
(sensorX: String, sensorY: String, beaconX: String, beaconY: String) ->
Pair(
Position(sensorX.toInt(), sensorY.toInt()),
Position(beaconX.toInt(), beaconY.toInt())
)
}
}
println(problem1(input))
println(problem2(input))
}
fun problem1(input: List<Pair<Position, Position>>): Int {
return findIntervals(input, 2000000).map { (from: Int, to: Int) -> to - from }.sum()
}
fun problem2(input: List<Pair<Position, Position>>): Long {
for (row in 0..4000000) {
val intervals = findIntervals(input, row)
if (intervals.size > 1) {
return (intervals.first().second + 1).toLong() * 4000000L + row.toLong()
}
}
throw Exception("Logic error")
}
fun findIntervals(input: List<Pair<Position, Position>>, targetRow: Int): List<Pair<Int, Int>> {
val intervals =
input
.map { (sensor: Position, beacon: Position) ->
val dist = abs(sensor.x - beacon.x) + abs(sensor.y - beacon.y)
val spanY = Pair(sensor.y - dist, sensor.y + dist)
if (targetRow < spanY.first || targetRow > spanY.second) null
else {
val half = dist - abs(targetRow - sensor.y)
Pair<Int, Int>(sensor.x - half, sensor.x + half)
}
}
.filter { it != null }
.map { it!! }
.sortedBy { it.first }
var mergedIntervals = mutableListOf(intervals.first())
intervals.forEach { (from: Int, to: Int) ->
val (lastFrom, lastTo) = mergedIntervals.last()
if (from > lastTo + 1) {
mergedIntervals.add(Pair<Int, Int>(from, to))
} else {
mergedIntervals.removeAt(mergedIntervals.size - 1)
mergedIntervals.add(Pair<Int, Int>(lastFrom, max(lastTo, to)))
}
}
return mergedIntervals
}
| 0 |
Rust
| 0 | 0 |
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
| 2,429 |
AdventOfCode
|
MIT License
|
src/Day07.kt
|
chbirmes
| 572,675,727 | false |
{"Kotlin": 32114}
|
fun main() {
fun part1(input: List<String>): Int {
val state = DeviceState().also { it.processInput(input) }
return state.root.recursiveDirectories()
.map { it.size() }
.filter { it <= 100_000 }
.sum()
}
fun part2(input: List<String>): Int {
val state = DeviceState().also { it.processInput(input) }
val minSizeToDelete = 30_000_000 - (70_000_000 - state.root.size())
return state.root.recursiveDirectories()
.map { it.size() }
.filter { it >= minSizeToDelete }
.min()
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private class DeviceState() {
val root = Directory("/", null)
var currentDirectory = root
class Directory(val name: String, var parent: Directory?) {
val files = mutableListOf<Int>()
val subdirectories = mutableListOf<Directory>()
fun size(): Int = files.sum() + subdirectories.sumOf { it.size() }
fun recursiveDirectories(): Sequence<Directory> =
sequenceOf(this) + subdirectories.asSequence().flatMap { it.recursiveDirectories() }
}
fun processInput(input:List<String>) {
input.forEach { line ->
if (line.startsWith("$")) {
line.drop(2).split(" ").let { command ->
if (command[0] == "cd") {
changeDirectory(command[1])
}
}
} else {
processLsLine(line)
}
}
}
fun changeDirectory(directory: String) {
currentDirectory = when (directory) {
"/" -> root
".." -> currentDirectory.parent
else -> currentDirectory.subdirectories.find { it.name == directory }
} ?: currentDirectory
}
fun processLsLine(line: String) {
line.split(" ", limit = 2)
.let {
it[0].toIntOrNull()?.let { size -> currentDirectory.files.add(size) }
?: currentDirectory.subdirectories.add(
Directory(it[1], currentDirectory)
)
}
}
}
| 0 |
Kotlin
| 0 | 0 |
db82954ee965238e19c9c917d5c278a274975f26
| 2,332 |
aoc-2022
|
Apache License 2.0
|
src/Day07.kt
|
dmarcato
| 576,511,169 | false |
{"Kotlin": 36664}
|
import kotlin.math.min
sealed interface Node
data class Dir(
val name: String,
val parent: Dir? = null,
var children: MutableList<Node> = mutableListOf()
) : Node
data class File(
val name: String,
val size: Int
) : Node
fun Node.totalSize(): Int = when (this) {
is File -> size
is Dir -> children.sumOf { it.totalSize() }
}
@Suppress("unused")
fun Node.print(prefix: String = ""): String {
return when (this) {
is Dir -> {
"$prefix- $name (dir)" + children.joinToString(separator = "\n", prefix = "\n") { it.print("$prefix ") }
}
is File -> {
"$prefix- $name (file, size=$size)"
}
}
}
fun Node.sumIfAtMost(atMost: Int): Int {
return when (this) {
is Dir -> {
val totalSize = totalSize()
if (totalSize <= atMost) {
totalSize
} else {
0
} + children.sumOf { it.sumIfAtMost(atMost) }
}
else -> 0
}
}
fun Dir.findSmallest(minSize: Int): Int {
val totalSize = totalSize()
val subDirs = children.filterIsInstance<Dir>()
return if (subDirs.isEmpty()) {
totalSize
} else {
val childrenMin = subDirs.minOf { node ->
val size = node.findSmallest(minSize)
if (size >= minSize) size else Integer.MAX_VALUE
}
if (totalSize >= minSize) min(totalSize, childrenMin) else childrenMin
}
}
fun main() {
fun createFS(input: List<String>): Dir {
val root = Dir("/")
var pointer = root
input.forEach { row ->
when {
row.startsWith("$") -> {
val pieces = row.trim('$', ' ').split(" ")
when (pieces[0]) {
"cd" -> {
when (val arg = pieces[1]) {
"/" -> pointer = root
".." -> pointer.parent?.let { pointer = it }
else -> pointer = pointer.children.first { (it as? Dir)?.name == arg } as Dir
}
}
}
}
else -> {
val (typeOrSize, name) = row.split(" ")
when (typeOrSize) {
"dir" -> pointer.children.add(Dir(name, pointer))
else -> pointer.children.add(File(name, typeOrSize.toInt()))
}
}
}
}
return root
}
fun part1(input: List<String>): Int {
val root = createFS(input)
return root.sumIfAtMost(100000)
}
fun part2(input: List<String>): Int {
val root = createFS(input)
val freeSpace = 70000000 - root.totalSize()
val minDelete = 30000000 - freeSpace
return root.findSmallest(minDelete)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437) { "part1 check failed" }
check(part2(testInput) == 24933642) { "part2 check failed" }
val input = readInput("Day07")
part1(input).println()
part2(input).println()
}
| 0 |
Kotlin
| 0 | 0 |
6abd8ca89a1acce49ecc0ca8a51acd3969979464
| 3,257 |
aoc2022
|
Apache License 2.0
|
src/main/kotlin/endredeak/aoc2023/Day07.kt
|
edeak
| 725,919,562 | false |
{"Kotlin": 26575}
|
package endredeak.aoc2023
val cardList = "AKQJT98765432".map { it.toString() }.reversed()
val jokerCardList = "AKQT98765432J".map { it.toString() }.reversed()
fun Char.r(jokers: Boolean = false) = (if (jokers) jokerCardList else cardList).indexOf(toString())
fun String.withJokers() =
when {
this.all { it == 'J' } -> "AAAAA"
!this.contains("J") -> this
else -> {
this.replace("J",
this.replace("J", "")
.groupBy { it }
.map { it.key to it.value.size }
.sortedWith(compareBy<Pair<Char, Int>> { it.second }.thenBy { it.first.r(true) }.reversed())
.first()
.first
.toString()
)
}
}
fun main() {
data class Hand(val cards: String, val bid: Long, val jokers: Boolean = false) : Comparable<Hand> {
val type = (if (jokers) cards.withJokers() else cards).let { toUse ->
listOf(
toUse.toCharArray().distinct().size == 1, // 5
toUse.any { c -> toUse.count { c == it } == 4 }, // 4
toUse.groupBy { it }.let { g -> g.size == 2 && g.entries.any { it.value.size == 2 } }, // 3 2
toUse.groupBy { it }.let { g -> g.size == 3 && g.entries.count { it.value.size == 3 } == 1 }, // 3
toUse.groupBy { it }.let { g -> g.size == 3 && g.entries.count { it.value.size == 2 } == 2 }, // 2 2
toUse.groupBy { it }.let { g -> g.size == 4 && g.count { it.value.size == 2 } == 1 }, // 2
toUse.toCharArray().distinct().size == toUse.length, // 1
)
.reversed()
.indexOfFirst { it }
}
override fun compareTo(other: Hand): Int =
if (type == other.type) {
// first index where chars are not equal
cards.indices.first { cards[it] != other.cards[it] }.let {
this.cards[it].r(jokers).compareTo(other.cards[it].r(jokers))
}
} else {
type.compareTo(other.type)
}
}
solve("Camel Cards") {
val input = lines.map { it.split(" ") }
fun calculate(jokers: Boolean = false) =
input
.map { Hand(it.first(), it.last().toLong(), jokers) }
.sortedWith(Hand::compareTo)
.mapIndexed { i, h -> (i + 1) * h.bid }
.sum()
part1(253638586) { calculate() }
part2(253253225) { calculate(true) }
}
}
| 0 |
Kotlin
| 0 | 0 |
92c684c42c8934e83ded7881da340222ff11e338
| 2,582 |
AdventOfCode2023
|
Do What The F*ck You Want To Public License
|
src/Day08.kt
|
bjornchaudron
| 574,072,387 | false |
{"Kotlin": 18699}
|
fun main() {
fun part1(input: List<String>): Int {
val treeGrid = toGrid(input)
return countVisibleTrees(treeGrid)
}
fun part2(input: List<String>): Int {
val treeGrid = toGrid(input)
return findBestScenicScore(treeGrid)
}
// test if implementation meets criteria from the description, like:
val day = "08"
val testInput = readLines("Day${day}_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readLines("Day$day")
println(part1(input))
println(part2(input))
}
fun toGrid(lines: List<String>): Array<Array<Int>> {
var treeGrid = arrayOf<Array<Int>>()
for (line in lines) {
val gridRow = line.toCharArray().map { it.digitToInt() }.toTypedArray()
treeGrid += gridRow
}
return treeGrid
}
fun countVisibleTrees(treeGrid: Array<Array<Int>>): Int {
var visibleTrees = 0
for (y in treeGrid.indices) {
for (x in treeGrid[y].indices) {
val point = Point(x, y)
if (isAtEdge(treeGrid, point) ||
isVisibleFromNorth(treeGrid, point) ||
isVisibleFromEast(treeGrid, point) ||
isVisibleFromSouth(treeGrid, point) ||
isVisibleFromWest(treeGrid, point)
) {
visibleTrees++
}
}
}
return visibleTrees
}
fun isAtEdge(treeGrid: Array<Array<Int>>, point: Point) =
point.x == 0 || point.x == treeGrid.first().lastIndex || point.y == 0 || point.y == treeGrid.lastIndex
fun isVisibleFromNorth(treeGrid: Array<Array<Int>>, point: Point) =
getNorthTrees(treeGrid, point).all { it < treeGrid[point.y][point.x] }
fun getNorthTrees(treeGrid: Array<Array<Int>>, point: Point) =
treeGrid.map { row -> row[point.x] }.filterIndexed { idx, _ -> idx < point.y }.reversed()
fun isVisibleFromEast(treeGrid: Array<Array<Int>>, point: Point) =
getEastTrees(treeGrid, point).all { it < treeGrid[point.y][point.x] }
fun getEastTrees(treeGrid: Array<Array<Int>>, point: Point) =
treeGrid[point.y].filterIndexed { idx, _ -> idx > point.x }
fun isVisibleFromSouth(treeGrid: Array<Array<Int>>, point: Point) =
getSouthTrees(treeGrid, point).all { it < treeGrid[point.y][point.x] }
fun getSouthTrees(treeGrid: Array<Array<Int>>, point: Point) =
treeGrid.map { row -> row[point.x] }.filterIndexed { idx, _ -> idx > point.y }
fun isVisibleFromWest(treeGrid: Array<Array<Int>>, point: Point) =
getWestTrees(treeGrid, point).all { it < treeGrid[point.y][point.x] }
fun getWestTrees(treeGrid: Array<Array<Int>>, point: Point) =
treeGrid[point.y].filterIndexed { idx, _ -> idx < point.x }.reversed()
fun findBestScenicScore(treeGrid: Array<Array<Int>>): Int {
var maxScenicScore = 0
for (y in treeGrid.indices) {
for (x in treeGrid[y].indices) {
val point = Point(x, y)
if (isAtEdge(treeGrid, point)) continue
val score = calcScenicScore(treeGrid, point)
if (score > maxScenicScore) maxScenicScore = score
}
}
return maxScenicScore
}
fun calcScenicScore(treeGrid: Array<Array<Int>>, point: Point): Int {
val height = treeGrid[point.y][point.x]
return listOf(
getNorthTrees(treeGrid, point),
getEastTrees(treeGrid, point),
getSouthTrees(treeGrid, point),
getWestTrees(treeGrid, point),
).map { calcScenicScoreForDirection(height, it) }.reduce { acc, i -> acc * i }
}
fun calcScenicScoreForDirection(height: Int, trees: List<Int>) =
if (trees.all { height > it }) trees.size else trees.takeWhile { height > it }.size + 1
| 0 |
Kotlin
| 0 | 0 |
f714364698966450eff7983fb3fda3a300cfdef8
| 3,648 |
advent-of-code-2022
|
Apache License 2.0
|
y2018/src/main/kotlin/adventofcode/y2018/Day17.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2018
import adventofcode.io.AdventSolution
object Day17 : AdventSolution(2018, 17, "Reservoir Research") {
override fun solvePartOne(input: String) = Reservoirs(input)
.apply { flow(Point(500, 0)) }
.count { it in "|~" }
override fun solvePartTwo(input: String) = Reservoirs(input)
.apply { flow(Point(500, 0)) }
.count { it == '~' }
private class Reservoirs(input: String) {
val xRange: IntRange
val yRange: IntRange
val map: List<CharArray>
init {
val clay = input.let(::parseToClayCoordinates)
xRange = clay.minOf { it.x }..clay.maxOf { it.x }
yRange = clay.minOf { it.y }..clay.maxOf { it.y }
map = coordinatesToMap(clay)
}
fun flow(source: Point) {
map[source.y][source.x] = '|'
val down = Point(source.x, source.y + 1)
if (down.y > map.lastIndex) return
if (map[down] == '.') flow(down)
val left = Point(source.x - 1, source.y)
if (map[left] == '.' && map[down] in "#~") flow(left)
val right = Point(source.x + 1, source.y)
if (map[right] == '.' && map[down] in "#~") flow(right)
fillRow(source)
}
private operator fun List<CharArray>.get(p: Point) = this[p.y][p.x]
//only fills when we've reached the rightmost point of the row
private fun fillRow(source: Point) {
val row = map[source.y]
if (row[source.x + 1] != '#') return
val leftEnd = (source.x downTo 0).find { x -> row[x] != '|' || map[source.y + 1][x] !in "#~" } ?: return
if (row[leftEnd] != '#') return
(leftEnd + 1..source.x).forEach { x -> row[x] = '~' }
}
private fun coordinatesToMap(clay: Iterable<Point>): List<CharArray> {
val map = List(yRange.last + 1) {
CharArray(xRange.last + 1) { '.' }
}
clay.forEach { (x, y) -> map[y][x] = '#' }
map[0][500] = '+'
return map
}
fun count(predicate: (Char) -> Boolean) = map.slice(yRange).sumOf { it.count(predicate) }
}
}
private fun parseToClayCoordinates(input: String): List<Point> {
val regex = """([xy])=(\d+), [xy]=(\d+)..(\d+)""".toRegex()
return input.lineSequence()
.map { regex.matchEntire(it)!!.destructured }
.map { (orientation, a, bStart, bEnd) ->
(bStart.toInt()..bEnd.toInt()).map {
if (orientation == "x")
Point(a.toInt(), it)
else
Point(it, a.toInt())
}
}
.flatten()
.toList()
}
private data class Point(val x: Int, val y: Int)
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 2,858 |
advent-of-code
|
MIT License
|
src/main/kotlin/Day05.kt
|
akowal
| 434,506,777 | false |
{"Kotlin": 30540}
|
import Day05.Orientation.*
fun main() {
println(Day05.solvePart1())
println(Day05.solvePart2())
}
object Day05 {
private val allLines = readInput("day05")
.asSequence()
.map { it.replace(" -> ", ",") }
.map { it.toIntArray() }
.map { (x1, y1, x2, y2) -> Line(x1, y1, x2, y2) }
fun solvePart1() = countIntersections(allLines.filter { it.orientation != DIAGONAL })
fun solvePart2() = countIntersections(allLines)
private fun countIntersections(lines: Sequence<Line>): Int {
val map = mutableMapOf<Point, Int>()
lines.flatMap { it.calculatePoints() }
.forEach {
map.compute(it) { _, hits -> hits?.inc() ?: 1 }
}
return map.values.count { it > 1 }
}
private fun Line.calculatePoints() = when (orientation) {
VERTICAL -> range(y1, y2).map { Point(x1, it) }
HORIZONTAL -> range(x1, x2).map { Point(it, y1) }
DIAGONAL -> range(x1, x2).zip(range(y1, y2)).map { (x, y) -> Point(x, y) }
}
private fun range(a: Int, b: Int) = if (a < b) {
a..b
} else {
a downTo b
}.asSequence()
private enum class Orientation { VERTICAL, HORIZONTAL, DIAGONAL }
private data class Line(
val x1: Int,
val y1: Int,
val x2: Int,
val y2: Int,
val orientation: Orientation = when {
x1 == x2 -> VERTICAL
y1 == y2 -> HORIZONTAL
else -> DIAGONAL
}
)
}
| 0 |
Kotlin
| 0 | 0 |
08d4a07db82d2b6bac90affb52c639d0857dacd7
| 1,505 |
advent-of-kode-2021
|
Creative Commons Zero v1.0 Universal
|
kotlin/src/Day08.kt
|
ekureina
| 433,709,362 | false |
{"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386}
|
import java.lang.IllegalStateException
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
line.split("|").last().trim().split(" ").count { output ->
val segments = output.length
output.length == 2 || output.length == 3 || output.length == 4 || output.length == 7
}
}
}
fun part2(label: String, input: List<String>): Int {
return input.sumOf { line ->
val (signals, entries) = line.split("|")
val options = signals.trim().split(" ").map { sequence ->
when (sequence.length) {
2 -> {
setOf(1) to sequence.toSortedSet()
}
3 -> {
setOf(7) to sequence.toSortedSet()
}
4 -> {
setOf(4) to sequence.toSortedSet()
}
5 -> {
setOf(2, 3, 5) to sequence.toSortedSet()
}
6 -> {
setOf(0, 6, 9) to sequence.toSortedSet()
}
7 -> {
setOf(8) to sequence.toSortedSet()
}
else -> throw IllegalStateException("Bad State! $sequence; ${sequence.length}")
}
}
val onOnes = options.first { it.first == setOf(1) }
val onSevens = options.first { it.first == setOf(7) }
val onFours = options.first { it.first == setOf(4) }
val onEights = options.first { it.first == setOf(8) }
val onNines = options.filter { it.first == setOf(0, 6, 9) }.first {
it.second.count { on ->
onFours.second.contains(on)
} == 4
}
val onZeros = options
.filter { it.first == setOf(0, 6, 9) && it.second != onNines.second }
.first { it.second.count { on ->
onOnes.second.contains(on)
} == 2 }
val onSixes = options.first { it.first == setOf(0, 6, 9) && it.second != onZeros.second && it.second != onNines.second }
val onThrees = options
.filter { it.first == setOf(2, 3, 5) }
.first { it.second.count { on ->
onOnes.second.contains(on)
} == 2 }
val onFives = options
.filter { it.first == setOf(2, 3, 5) && it.second != onThrees.second }
.first { it.second.count { on ->
onFours.second.contains(on)
} == 3 }
val onTwos = options
.first { it.first == setOf(2, 3, 5) && it.second != onThrees.second && it.second != onFives.second }
val mapping = mapOf(
onZeros.second to 0,
onOnes.second to 1,
onTwos.second to 2,
onThrees.second to 3,
onFours.second to 4,
onFives.second to 5,
onSixes.second to 6,
onSevens.second to 7,
onEights.second to 8,
onNines.second to 9
)
entries.trim().split(" ").map { entry ->
mapping[entry.toSortedSet()]!!
}.fold(0) { current, digit ->
current * 10 + digit
}.toInt()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 26) { "${part1(testInput)}" }
val miniFail = "miniFail"
check(part2("micro", listOf("acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf")) == 5353)
check(part2("mini", testInput) == 61229 ) { "${part2(miniFail, testInput)}" }
val input = readInput("Day08")
println(part1(input))
println(part2("mega", input))
}
| 0 |
Kotlin
| 0 | 1 |
391d0017ba9c2494092d27d22d5fd9f73d0c8ded
| 4,033 |
aoc-2021
|
MIT License
|
src/Day08.kt
|
mvanderblom
| 573,009,984 | false |
{"Kotlin": 25405}
|
fun List<Int>.takeUntilIncluding(predicate: (Int) -> Boolean): List<Int> {
val toIndex = this.indexOfFirst(predicate)
return when {
toIndex == -1 || (toIndex == 0 && this.size == 1) -> this
toIndex == 0 -> emptyList()
else -> this.subList(0, toIndex+1)
}
}
class Forest(val input: List<String>) {
private val rows = input.size
private val cols= input[0].length
private val grid = Array(rows) { Array(cols) { 0 } }
init {
input.forEachIndexed { rowNum, row ->
row.forEachIndexed { colNum, cell ->
this.grid[rowNum][colNum] = cell.digitToInt()
}
}
}
fun countVisisbleNodes(): Int = grid.mapIndexed { y: Int, row: Array<Int> ->
row.mapIndexed { x: Int, cell: Int ->
if (isEdge(x, y) || isOnlySurroundedByLowerTrees(x, y)) {
true
} else
null
}
}.flatten().filterNotNull().count()
private fun isEdge(x: Int, y: Int): Boolean = x == 0 || y == 0 || x == cols-1 || y == rows-1
private fun isOnlySurroundedByLowerTrees(x: Int, y: Int): Boolean = isVisibleIn(y, column(x)) || isVisibleIn(x, row(y))
private fun isVisibleIn(index: Int, list: List<Int>): Boolean {
val valueAtIndex = list[index]
val before = list.subList(0, index)
val after = list.subList(index+1, rows)
return before.count { it >= valueAtIndex } == 0 || after.count { it >= valueAtIndex } == 0
}
fun getHighestScenicScore(): Int = (0 until rows).map { y ->
val scores = (0 until cols).map { x ->
val scenicScore = calculateScenicScore(x, y)
scenicScore
}
scores
}.flatten().max()
private fun calculateScenicScore(x: Int, y: Int): Int = calculateScenicScore(y, column(x)) * calculateScenicScore(x, row(y))
private fun calculateScenicScore(index: Int, list: List<Int>): Int {
val valueAtIndex = list[index]
val before = list.subList(0, index)
val after = list.subList(index+1, rows)
return before.reversed().takeUntilIncluding { it >= valueAtIndex }.count() * after.takeUntilIncluding { it >= valueAtIndex }.count()
}
private fun row(y: Int) = grid[y].toList()
private fun column(x: Int): List<Int> = grid.map { it[x] }
}
fun main() {
val dayName = 8.toDayName()
fun part1(input: List<String>): Int = Forest(input).countVisisbleNodes()
fun part2(input: List<String>): Int = Forest(input).getHighestScenicScore()
val testInput = readInput("${dayName}_test")
val input = readInput(dayName)
// Part 1
val testOutputPart1 = part1(testInput)
testOutputPart1 isEqualTo 21
val outputPart1 = part1(input)
outputPart1 isEqualTo 1736
// Part 2
val testOutputPart2 = part2(testInput)
testOutputPart2 isEqualTo 8
val outputPart2 = part2(input)
outputPart2 isEqualTo 268800
}
| 0 |
Kotlin
| 0 | 0 |
ba36f31112ba3b49a45e080dfd6d1d0a2e2cd690
| 2,952 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/main/day12/Part1.kt
|
ollehagner
| 572,141,655 | false |
{"Kotlin": 80353}
|
package day12
import common.Direction.*
import common.Grid
import common.Point
import dequeOf
import readInput
import java.util.*
typealias Path = Deque<Point>
fun main() {
val (start, goal, grid) = parseInput(readInput("day12/input.txt"))
val shortestPath = shortestPath(start, goal, grid)
println("Day 12 part 1. Fewest steps to goal: $shortestPath")
}
fun shortestPath(start: Point, goal: Point, grid: Grid<Int>): Int {
val paths: Deque<Path> = dequeOf()
paths.add(dequeOf(start))
val pathCosts: MutableMap<Point, Int> = mutableMapOf()
while(paths.isNotEmpty()) {
val path = paths.pop()
if(path.last != goal) {
validMoves(path.last, grid)
.map { nextPosition -> path.copyAndAdd(nextPosition) }
.forEach { pathToExplore ->
if (pathToExplore.size < pathCosts.getOrDefault(pathToExplore.last(), Int.MAX_VALUE)) {
pathCosts[pathToExplore.last()] = pathToExplore.size
paths.add(pathToExplore)
}
}
}
}
return pathCosts.getOrDefault(goal, Int.MAX_VALUE) - 1
}
fun validMoves(currentPosition: Point, grid: Grid<Int>): List<Point> {
return listOf(UP, DOWN, RIGHT, LEFT)
.map { direction -> currentPosition.move(direction) }
.filter { point -> grid.hasValue(point) && grid.valueOf(point) <= grid.valueOf(currentPosition) + 1}
}
fun Path.copyAndAdd(value: Point): Path {
val copy = dequeOf<Point>()
copy.addAll(this)
copy.addLast(value)
return copy
}
private const val START_CHAR = 'S'
private const val START_HEIGHT = 'a'.code
private const val GOAL_CHAR = 'E'
private const val GOAL_HEIGHT = 'z'.code
fun parseInput(input: List<String>): Triple<Point, Point, Grid<Int>> {
var start = Point(0,0)
var goal = Point(0,0)
val grid = Grid<Int>()
input.forEachIndexed { y, row ->
row.forEachIndexed { x, heightChar ->
val point = Point(x, y)
if(heightChar == START_CHAR) {
start = point
grid.set(point, START_HEIGHT)
} else if(heightChar == GOAL_CHAR) {
goal = point
grid.set(point, GOAL_HEIGHT)
} else {
grid.set(point, heightChar.code)
}
}
}
return Triple(start, goal, grid)
}
| 0 |
Kotlin
| 0 | 0 |
6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1
| 2,403 |
aoc2022
|
Apache License 2.0
|
src/Day07.kt
|
MatthiasDruwe
| 571,730,990 | false |
{"Kotlin": 47864}
|
import java.lang.Error
fun main() {
fun createStructure(input: List<String>): Directory {
val structure = Directory("root")
var currentItem: Directory? = null
val parents = mutableMapOf<String, Directory>()
input.forEach { line ->
val items = line.split(" ")
if (items[0] == "$") {
if (items[1] == "cd") {
if (items[2] == "/") {
currentItem = structure
} else if (items[2] == "..") {
currentItem = parents[currentItem?.name]
} else {
currentItem = currentItem?.directories?.find { it.name == currentItem?.name + "/" + items[2] }
}
}
} else {
if (items[0] == "dir") {
val directory = Directory(currentItem?.name + "/" + items[1])
currentItem?.directories?.add(directory)
currentItem?.also { parents[directory.name] = it }
} else {
currentItem?.files?.add(File(items[1], items[0].toLong()))
}
}
}
return structure
}
fun part1(input: List<String>): Long {
val structure = createStructure(input)
val x = structure.getDirectoriesWithSizeBelow(100000)
return x.sumOf { it.getSize() }
}
fun part2(input: List<String>): Long {
val structure = createStructure(input)
val totalSize = 30000000 - 70000000 + structure.getSize()
val items = structure.getDirectoriesWithSizeAbove(totalSize).minBy { it.getSize() }
return items.getSize()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_example")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
data class Directory(val name: String, val directories: MutableList<Directory> = mutableListOf<Directory>(), val files: MutableList<File> = mutableListOf<File>() ){
fun getDirectoriesWithSizeBelow(number: Long): List<Directory>{
return directories.filter { it.getSize() <= number } + directories.map { it.getDirectoriesWithSizeBelow(number) }.flatten()
}
fun getDirectoriesWithSizeAbove(number: Long): List<Directory>{
return directories.filter { it.getSize() >= number } + directories.map { it.getDirectoriesWithSizeAbove(number) }.flatten()
}
fun getSize(): Long{
return directories.sumOf { it.getSize() } + files.sumOf { it.size }
}
}
data class File(val name: String, val size: Long)
| 0 |
Kotlin
| 0 | 0 |
f35f01cea5075cfe7b4a1ead9b6480ffa57b4989
| 2,753 |
Advent-of-code-2022
|
Apache License 2.0
|
kotlin-practice/src/main/kotlin/algorithms/new/CubeConundrum.kt
|
nicolegeorgieva
| 590,020,790 | false |
{"Kotlin": 120359}
|
package algorithms.new
import java.io.File
fun main() {
val input = File("cubes.txt").readText()
val sets =
parseSets("Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green")
println(sumOfGamePowers(input))
}
val bag = Set(
redCubesCount = 12,
greenCubesCount = 13,
blueCubesCount = 14
)
data class Game(
val id: Int,
val sets: List<Set>
)
data class Set(
val redCubesCount: Int,
val greenCubesCount: Int,
val blueCubesCount: Int
)
private fun validGamesSum(input: String): Int {
return input.lines()
.map(::parseAsGame)
.filter(::validateGame)
.sumOf { it.id }
}
private fun sumOfGamePowers(input: String): Int {
val gamesList = input.lines()
.map(::parseAsGame)
var sum = 0
for (game in gamesList) {
val set = getFewestValidGameCubes(game.sets)
sum += powerOfFewestValidGameCubes(set)
}
return sum
}
private fun powerOfFewestValidGameCubes(set: Set): Int {
return set.redCubesCount * set.blueCubesCount * set.greenCubesCount
}
// Set(blue=2, red=3, red=1), Set(green=2, blue=3; green=4)
private fun getFewestValidGameCubes(gameSets: List<Set>): Set {
val redCount = gameSets.maxOf { it.redCubesCount }
val blueCount = gameSets.maxOf { it.blueCubesCount }
val greenCount = gameSets.maxOf { it.greenCubesCount }
return Set(redCubesCount = redCount, greenCubesCount = greenCount, blueCubesCount = blueCount)
}
// "Game 1: 4 blue, 16 green, 2 red; 5 red, 11 blue, 16 green; 9 green, 11 blue; 10 blue, 6 green, 4 red"
private fun parseAsGame(line: String): Game {
val gameId = parseGameId(line)
val gameSets = parseSets(line)
return Game(id = gameId, sets = gameSets)
}
// Game 15
private fun parseGameId(line: String): Int {
val gameTitleList = line
.split(":")
.first()
.split(" ")
return gameTitleList[1].toInt()
}
// "Game 1: 4 blue, 16 green, 2 red; 5 red, 11 blue, 16 green; 9 green, 11 blue; 10 blue, 6 green, 4 red"
private fun parseSets(line: String): List<Set> {
val lineWithoutTitle = line.split(":").last()
val sets = lineWithoutTitle.split(";")
return sets.map {
parseStringToSet(it)
}
}
// 4 blue, 16 green, 2 red
private fun parseStringToSet(input: String): Set {
var red = 0
var green = 0
var blue = 0
val inputList = input.split(",")
// 4 blue
for (i in inputList.indices) {
val current = inputList[i].filter {
it != ','
}.trim().split(" ")
when (current[1]) {
"red" -> red += current[0].toInt()
"green" -> green += current[0].toInt()
"blue" -> blue += current[0].toInt()
}
}
return Set(
redCubesCount = red,
greenCubesCount = green,
blueCubesCount = blue
)
}
private fun validateGame(game: Game): Boolean {
return game.sets.all {
validateSet(it)
}
}
// Set(redCubesCount=2, greenCubesCount=16, blueCubesCount=4)
private fun validateSet(set: Set): Boolean {
return set.redCubesCount <= bag.redCubesCount &&
set.greenCubesCount <= bag.greenCubesCount &&
set.blueCubesCount <= bag.blueCubesCount
}
| 0 |
Kotlin
| 0 | 1 |
c96a0234cc467dfaee258bdea8ddc743627e2e20
| 3,232 |
kotlin-practice
|
MIT License
|
src/Day09.kt
|
asm0dey
| 572,860,747 | false |
{"Kotlin": 61384}
|
import kotlin.math.abs
import kotlin.math.sign
data class Point09(val x: Int, val y: Int) {
infix fun notTouches(other: Point09): Boolean = !(abs(this.x - other.x) <= 1 && abs(this.y - other.y) <= 1)
operator fun plus(other: Point09): Point09 = copy(x = x + other.x, y = y + other.y)
}
fun main() {
infix fun Point09.moveCloserTo(other: Point09) =
if (this notTouches other)
copy(x = x + (other.x - x).sign, y = y + (other.y - y).sign)
else this
fun Char.asMovementVector() = when (this) {
'R' -> Point09(1, 0)
'L' -> Point09(-1, 0)
'U' -> Point09(0, 1)
'D' -> Point09(0, -1)
else -> throw UnsupportedOperationException(toString())
}
fun part1(input: List<String>): Int {
var head = Point09(0, 0)
var tail = Point09(0, 0)
return input
.map { it.split(' ') }
.filter { it.size == 2 }
.map { it[0][0] to it[1].toInt() }
.flatMap { (direction, amount) ->
(0 until amount).map {
head += direction.asMovementVector()
tail = tail moveCloserTo head
tail
}
}
.distinct()
.size
}
fun part2(input: List<String>, size: Int): Int {
val knots = Array(size) { Point09(0, 0) }
return input
.map { it.split(' ') }
.filter { it.size == 2 }
.map { it[0][0] to it[1].toInt() }
.flatMap { (direction, amount) ->
(0 until amount).map {
knots[0] += direction.asMovementVector()
for (i in knots.indices.drop(1)) {
knots[i] = knots[i] moveCloserTo knots[i - 1]
}
knots.last()
}
}
.distinct()
.size
}
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
val input = readInput("Day09")
println(part1(input))
println(part2(input, 10))
check(part1(input) == part2(input, 2))
}
| 1 |
Kotlin
| 0 | 1 |
f49aea1755c8b2d479d730d9653603421c355b60
| 2,138 |
aoc-2022
|
Apache License 2.0
|
src/Day02.kt
|
lukewalker128
| 573,611,809 | false |
{"Kotlin": 14077}
|
fun main() {
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
/**
* Determines the score that the second player would achieve following the given strategy guide.
*/
private fun part1(input: List<String>): Int {
return input.map { GameResult(it) }
.sumOf { it.player2Score() }
}
private fun part2(input: List<String>): Int {
return input.map { GameResult2(it) }
.sumOf { it.player2Score() }
}
/**
* For part 1.
*/
private class GameResult(input: String) {
enum class Shape(val identifiers: List<String>, val score: Int) {
ROCK(listOf("A", "X"), 1),
PAPER(listOf("B", "Y"), 2),
SCISSORS(listOf("C", "Z"), 3)
}
enum class Outcome(val score: Int) {
LOSS(0),
DRAW(3),
WIN(6)
}
val player1Shape: Shape
val player2Shape: Shape
init {
val parsedInput = input.split(" ")
player1Shape = parsedInput.first().toShape()
player2Shape = parsedInput.last().toShape()
}
fun String.toShape() = Shape.values().first { shape -> this in shape.identifiers }
fun player2Score(): Int {
return player2Shape.score + getOutcome(player2Shape, player1Shape).score
}
/**
* Determines the outcome of the game from the perspective of the first player.
*/
fun getOutcome(firstPlayer: Shape, secondPlayer: Shape): Outcome {
return when {
firstPlayer == secondPlayer -> Outcome.DRAW
secondPlayer == BEATS[firstPlayer] -> Outcome.WIN
else -> Outcome.LOSS
}
}
companion object {
val BEATS = mapOf(
Shape.ROCK to Shape.SCISSORS,
Shape.PAPER to Shape.ROCK,
Shape.SCISSORS to Shape.PAPER
)
}
}
/**
* For part 2.
*/
private class GameResult2(input: String) {
enum class Shape(val identifier: String, val score: Int) {
ROCK("A", 1),
PAPER("B", 2),
SCISSORS("C", 3)
}
enum class Outcome(val identifier: String, val score: Int) {
LOSS("X", 0),
DRAW("Y", 3),
WIN("Z", 6)
}
val requiredOutcome: Outcome
val player2Shape: Shape
init {
val parsedInput = input.split(" ")
val player1Shape = parsedInput.first().toShape()
requiredOutcome = parsedInput.last().toOutcome()
player2Shape = when (requiredOutcome) {
Outcome.LOSS -> BEATS[player1Shape]!!
Outcome.DRAW -> player1Shape
Outcome.WIN -> BEATS.entries.first { (_, losingShape) -> player1Shape == losingShape }.key
}
}
fun String.toShape() = Shape.values().first { shape -> this == shape.identifier }
fun String.toOutcome() = Outcome.values().first { outcome -> this == outcome.identifier }
fun player2Score(): Int {
return player2Shape.score + requiredOutcome.score
}
companion object {
val BEATS = mapOf(
Shape.ROCK to Shape.SCISSORS,
Shape.PAPER to Shape.ROCK,
Shape.SCISSORS to Shape.PAPER
)
}
}
| 0 |
Kotlin
| 0 | 0 |
c1aa17de335bd5c2f5f555ecbdf39874c1fb2854
| 3,230 |
advent-of-code-2022
|
Apache License 2.0
|
src/y2022/Day20.kt
|
gaetjen
| 572,857,330 | false |
{"Kotlin": 325874, "Mermaid": 571}
|
package y2022
import util.readInput
object Day20 {
class Node(
val value: Long,
var prev: Node?,
var next: Node?,
) {
fun move(mod: Int? = null) {
prev?.next = next
next?.prev = prev
var remainingDist = value
if (mod != null) remainingDist %= (mod - 1) //Math.floorMod(remainingDist, mod.toLong())
var insertionNode = this.prev
if (remainingDist > 0) {
while (remainingDist != 0L) {
insertionNode = insertionNode?.next!!
remainingDist--
}
} else {
while (remainingDist != 0L) {
insertionNode = insertionNode?.prev!!
remainingDist++
}
}
this.next = insertionNode?.next
this.prev = insertionNode
insertionNode?.next?.prev = this
insertionNode?.next = this
}
fun toList(): List<Long> {
val start = this
var it = this.next
val res = mutableListOf(start.value)
while (it != start) {
res.add(it?.value!!)
it = it.next
}
return res
}
}
private fun parse(input: List<String>, key: Long = 1L): List<Node> {
val nodes = input.map { Node(it.toLong() * key, null, null) }
nodes.windowed(3).forEach {
it[1].prev = it[0]
it[1].next = it[2]
}
nodes.first().prev = nodes.last()
nodes.first().next = nodes[1]
nodes.last().next = nodes.first()
nodes.last().prev = nodes[nodes.size - 2]
return nodes
}
fun part1(input: List<String>): Long {
val file = parse(input)
if (file.size != file.distinct().size) {
println("total: " + file.size)
println("unique: " + file.distinct().size)
}
println(file.first().toList())
file.forEach {
it.move()
//println(it.toList())
}
val list = file.first().toList()
val zeroIdx = list.indexOf(0)
return (1..3).sumOf { list[(zeroIdx + 1000 * it) % list.size] }
}
fun part2(input: List<String>): Long {
val file = parse(input, key = 811589153)
val ln = file.size
repeat(10) {
file.forEach {
it.move(ln)
}
}
val list = file.first().toList()
val zeroIdx = list.indexOf(0)
return (1..3).sumOf { list[(zeroIdx + 1000 * it) % list.size] }
}
}
fun main() {
val testInput = """
1
2
-3
3
-2
0
4
""".trimIndent().split("\n")
println("------Tests------")
println(Day20.part1(testInput))
println(Day20.part2(testInput))
println("------Real------")
val input = readInput("resources/2022/day20")
println(Day20.part1(input))
println(Day20.part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
| 3,038 |
advent-of-code
|
Apache License 2.0
|
2023/src/main/kotlin/Day22.kt
|
dlew
| 498,498,097 | false |
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
|
object Day22 {
fun part1(input: String): Int {
val bricks = parse(input).sortedBy { it.zRange.first }
val (settled) = dropBricks(bricks)
return settled.count { brick ->
val bricksWithDisintegration = settled.filter { it != brick }
val (_, numBricksFallen) = dropBricks(bricksWithDisintegration)
return@count numBricksFallen == 0
}
}
fun part2(input: String): Int {
val bricks = parse(input).sortedBy { it.zRange.first }
val (settled) = dropBricks(bricks)
return settled.sumOf { brick ->
val bricksWithDisintegration = settled.filter { it != brick }
val (_, numBricksFallen) = dropBricks(bricksWithDisintegration)
return@sumOf numBricksFallen
}
}
private fun dropBricks(bricks: List<Brick>): DropResult {
val settled = mutableListOf<Brick>()
var numBricksFallen = 0
bricks.forEach { brick ->
var fallingBrick = brick
var fell = false
while (true) {
// Resting on the ground
if (fallingBrick.zRange.first == 1) {
settled.add(fallingBrick)
break
}
// Resting on another brick
if (settled.any { it.supports(fallingBrick) }) {
settled.add(fallingBrick)
break
}
fallingBrick = fallingBrick.fall()
fell = true
}
if (fell) {
numBricksFallen++
}
}
return DropResult(settled, numBricksFallen)
}
private data class DropResult(val bricks: List<Brick>, val numBricksFallen: Int)
private data class Pos(val x: Int, val y: Int, val z: Int)
private data class Brick(val start: Pos, val end: Pos) {
val xRange = if (start.x < end.x) start.x..end.x else end.x..start.x
val yRange = if (start.y < end.y) start.y..end.y else end.y..start.y
val zRange = if (start.z < end.z) start.z..end.z else end.z..start.z
fun fall() = copy(
start = start.copy(z = start.z - 1),
end = end.copy(z = end.z - 1)
)
fun supports(other: Brick): Boolean {
return zRange.last == other.zRange.first - 1
&& xRange.last >= other.xRange.first
&& xRange.first <= other.xRange.last
&& yRange.last >= other.yRange.first
&& yRange.first <= other.yRange.last
}
}
private fun parse(input: String): List<Brick> {
val regex = Regex("(\\d+),(\\d+),(\\d+)~(\\d+),(\\d+),(\\d+)")
return input.splitNewlines().map {
val match = regex.matchEntire(it)!!
return@map Brick(
start = Pos(match.groupValues[1].toInt(), match.groupValues[2].toInt(), match.groupValues[3].toInt()),
end = Pos(match.groupValues[4].toInt(), match.groupValues[5].toInt(), match.groupValues[6].toInt()),
)
}
}
}
| 0 |
Kotlin
| 0 | 0 |
6972f6e3addae03ec1090b64fa1dcecac3bc275c
| 2,728 |
advent-of-code
|
MIT License
|
src/main/kotlin/ru/timakden/aoc/year2015/Day13.kt
|
timakden
| 76,895,831 | false |
{"Kotlin": 321649}
|
package ru.timakden.aoc.year2015
import ru.timakden.aoc.util.Permutations
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 13: Knights of the Dinner Table](https://adventofcode.com/2015/day/13).
*/
object Day13 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2015/Day13")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
val happiness = mutableMapOf<String, Int>()
var optimalHappinessChange = Int.MIN_VALUE
val names = sortedSetOf<String>()
input.forEach {
val split = it.split(' ')
val name1 = split[0]
val name2 = split[10].substring(0, split[10].lastIndex)
var happinessUnits = split[3].toInt()
if (split[2] == "lose") happinessUnits = -happinessUnits
names += name1
names += name2
happiness[name1 + name2] = happinessUnits
}
val seatingArrangements = Permutations.of(names.toList())
seatingArrangements.forEach {
val list = it.toList()
var happinessChange = list.indices
.filter { i -> i != list.lastIndex }
.sumOf { i -> (happiness[list[i] + list[i + 1]] ?: 0) + (happiness[list[i + 1] + list[i]] ?: 0) }
happinessChange += (happiness[list[0] + list[list.lastIndex]] ?: 0) +
(happiness[list[list.lastIndex] + list[0]] ?: 0)
if (happinessChange > optimalHappinessChange) optimalHappinessChange = happinessChange
}
return optimalHappinessChange
}
fun part2(input: List<String>): Int {
val happiness = mutableMapOf<String, Int>()
var optimalHappinessChange = Int.MIN_VALUE
val names = sortedSetOf<String>().apply { add("me") }
input.forEach {
val split = it.split(' ')
val name1 = split[0]
val name2 = split[10].substring(0, split[10].lastIndex)
var happinessUnits = split[3].toInt()
if (split[2] == "lose") happinessUnits = -happinessUnits
names += name1
names += name2
happiness[name1 + name2] = happinessUnits
happiness["${name1}me"] = 0
happiness["me$name1"] = 0
}
val seatingArrangements = Permutations.of(names.toList())
seatingArrangements.forEach {
val list = it.toList()
var happinessChange = list.indices
.filter { i -> i != list.lastIndex }
.sumOf { i -> (happiness[list[i] + list[i + 1]] ?: 0) + (happiness[list[i + 1] + list[i]] ?: 0) }
happinessChange += (happiness[list[0] + list[list.lastIndex]] ?: 0) +
(happiness[list[list.lastIndex] + list[0]] ?: 0)
if (happinessChange > optimalHappinessChange) optimalHappinessChange = happinessChange
}
return optimalHappinessChange
}
}
| 0 |
Kotlin
| 0 | 3 |
acc4dceb69350c04f6ae42fc50315745f728cce1
| 3,098 |
advent-of-code
|
MIT License
|
src/Day03.kt
|
stcastle
| 573,145,217 | false |
{"Kotlin": 24899}
|
/** Finds the common character in the two strings. */
fun findCommon(a: String, b: String): Char {
a.forEach { if (b.contains(it)) return it }
throw Exception("No common character found between the two strings.\n\tFirst: $a\n\tSecond: $b")
}
/** Finds the common character among all the strings. */
fun findCommon(s: List<IndexedValue<String>>): Char {
val strings = s.map { it.value }
val firstString = strings.first()
firstString.forEach { char -> if (strings.drop(1).all { it.contains(char) }) return char }
throw Exception("No common char found in the list of strings: $strings")
}
fun Char.priority(): Int {
if (this in 'a'..'z') {
return this.code - 'a'.code + 1
}
if (this in 'A'..'Z') {
return this.code - 'A'.code + 27
}
throw Exception("Unexpected char: $this")
}
fun main() {
fun part1(input: List<String>): Int {
val commonItems: List<Char> =
input.map {
val numItems = it.length
val half: Int = numItems / 2
val first = it.substring(0, half)
val second = it.substring(half)
findCommon(first, second)
}
return commonItems.fold(0) { acc: Int, item: Char -> acc + item.priority() }
}
fun part2(input: List<String>): Int {
// Makes a map where values are the groups of 3.
val groupsOfThree = input.withIndex().groupBy { it.index / 3 }
val badges: List<Char> = groupsOfThree.map { entry -> findCommon(entry.value) }
return badges.fold(0) { acc: Int, item: Char -> acc + item.priority() }
}
val day = "03"
val testInput = readInput("Day${day}_test")
println("Part 1 test = ${part1(testInput)}")
val input = readInput("Day${day}")
println("part1 = ${part1(input)}")
println("Part 2 test = ${part2(testInput)}")
println("part2 = ${part2(input)}")
}
| 0 |
Kotlin
| 0 | 0 |
746809a72ea9262c6347f7bc8942924f179438d5
| 1,804 |
aoc2022
|
Apache License 2.0
|
2015/src/main/kotlin/day6_func.kt
|
madisp
| 434,510,913 | false |
{"Kotlin": 388138}
|
import utils.IntGrid
import utils.Parser
import utils.Solution
import utils.Vec2i
import utils.cut
import utils.map
import utils.mapItems
fun main() {
Day6Func.run()
}
object Day6Func : Solution<List<Day6Func.Opcode>>() {
override val name = "day6"
override val parser = Parser.lines.mapItems(Opcode::parse)
enum class Insn(val desc: String, val applyBool: (Int) -> Int, val applyNumeric: (Int) -> Int) {
on("turn on", { 1 }, { it + 1 }),
off("turn off", { 0 }, { maxOf(it - 1, 0) }),
toggle("toggle", { it xor 0b1 }, { it + 2 });
companion object {
fun parse(input: String): Pair<Insn, String> {
val insn = Insn.values().first { input.startsWith(it.desc) }
return insn to input.substring(insn.desc.length + 1)
}
}
}
data class Opcode(val insn: Insn, val p1: Vec2i, val p2: Vec2i) {
fun apply(grid: IntGrid, part2: Boolean): IntGrid {
val xr = minOf(p1.x, p2.x) .. maxOf(p1.x, p2.x)
val yr = minOf(p1.y, p2.y) .. maxOf(p1.y, p2.y)
return grid.map { (x, y), v ->
if (x in xr && y in yr) {
if (part2) insn.applyNumeric(v) else insn.applyBool(v)
} else v
}
}
companion object {
fun parse(line: String): Opcode {
val (insn, reminder) = Insn.parse(line)
val (p1, p2) = reminder.cut(" through ")
val (p1x, p1y) = p1.cut(",").map { it.toInt() }
val (p2x, p2y) = p2.cut(",").map { it.toInt() }
return Opcode(insn, Vec2i(p1x, p1y), Vec2i(p2x, p2y))
}
}
}
override fun part1(): Int {
val grid = IntGrid(1000, 1000) { 0 }
return input.fold(grid) { it, op -> op.apply(it, false) }
.cells
.count { (_, v) -> v == 1 }
}
override fun part2(): Int {
val grid = IntGrid(1000, 1000) { 0 }
return input.fold(grid) { it, op -> op.apply(it, true) }
.cells
.sumOf { (_, v) -> v }
}
}
| 0 |
Kotlin
| 0 | 1 |
3f106415eeded3abd0fb60bed64fb77b4ab87d76
| 1,898 |
aoc_kotlin
|
MIT License
|
src/Day12.kt
|
kpilyugin
| 572,573,503 | false |
{"Kotlin": 60569}
|
import java.util.PriorityQueue
fun main() {
fun findAndReplace(table: List<CharArray>, ch: Char, replacement: Char) = buildList {
for (i in table.indices) {
for (j in table[0].indices) {
if (table[i][j] == ch) {
table[i][j] = replacement
add(i to j)
}
}
}
}
data class State(val x: Int, val y: Int, val dist: Int)
fun bfs(table: List<CharArray>, start: List<Pair<Int, Int>>, target: Pair<Int, Int>): Int {
val q = PriorityQueue<State>(compareBy { it.dist })
val used = Array(table.size) { BooleanArray(table[0].size) }
for ((sx, sy) in start) {
q.add(State(sx, sy, 0))
used[sx][sy] = true
}
while (q.isNotEmpty()) {
val cur = q.poll()
for ((dx, dy) in listOf(-1 to 0, 1 to 0, 0 to 1, 0 to -1)) {
val nx = cur.x + dx
val ny = cur.y + dy
if (nx in table.indices &&
ny in table[0].indices &&
!used[nx][ny] &&
table[nx][ny] <= table[cur.x][cur.y] + 1
) {
if (nx == target.first && ny == target.second) {
return cur.dist + 1
}
q.add(State(nx, ny, cur.dist + 1))
used[nx][ny] = true
}
}
}
return -1
}
fun part1(input: List<String>): Int {
val table = input.map { it.toCharArray() }
val start = findAndReplace(table, 'S', 'a')
val target = findAndReplace(table, 'E', 'z')[0]
return bfs(table, start, target)
}
fun part2(input: List<String>): Int {
val table = input.map { it.toCharArray() }
val start = findAndReplace(table, 'a', 'a') + findAndReplace(table, 'S', 'a')
val target = findAndReplace(table, 'E', 'z')[0]
return bfs(table, start, target)
}
val testInput = readInputLines("Day12_test")
check(part1(testInput), 31)
check(part2(testInput), 29)
val input = readInputLines("Day12")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
7f0cfc410c76b834a15275a7f6a164d887b2c316
| 2,232 |
Advent-of-Code-2022
|
Apache License 2.0
|
src/Day15.kt
|
zfz7
| 573,100,794 | false |
{"Kotlin": 53499}
|
fun main() {
println(day15A(readFile("Day15")))
println(day15B(readFile("Day15")))
}
fun parseInput(input: String): List<Pair<Pair<Int, Int>, Pair<Int, Int>>> {
val sensorBeaconPair = input.trim().split("\n").map { line ->
val ints = line.split("Sensor at x=", ", y=", ": closest beacon is at x=", ", y=")
val sensor: Pair<Int, Int> = Pair(ints[1].toInt(), ints[2].toInt())
val beacon: Pair<Int, Int> = Pair(ints[3].toInt(), ints[4].toInt())
Pair(sensor, beacon)
}
return sensorBeaconPair
}
fun generateSensorGrid(sensorBeaconPair: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>): MutableList<MutableList<Char>> {
val ret = Array(100000) { CharArray(100000) { '.' }.toMutableList() }.toMutableList()
sensorBeaconPair.forEach {
ret[it.first.first][it.first.second] = 'S'
ret[it.second.first][it.second.second] = 'B'
}
return ret
}
fun day15B(input: String): Long {
val sensorBeaconPair = parseInput(input)
// println(sensorBeaconPair)
val things = sensorBeaconPair.flatMap { listOf(it.first, it.second) }.toSet()
val points = sensorBeaconPair.flatMap { pair ->
val dist = dist(pair) +1
val points = mutableListOf<Pair<Int,Int>>()
for(i in -dist..+dist){
points.add(Pair(pair.first.first + i, pair.first.second + (dist - i)))
}
points
}.toSet()
points.forEach{ pos ->
if (pos.first in 0..4000000 &&
pos.second in 0..4000000 &&
!things.contains(pos) &&
sensorBeaconPair.all { pair -> dist(pair.first, pos) > dist(pair)
}) {
println(pos)
return pos.first * 4000000L + pos.second
}
}
return -1
}
fun day15A(input: String): Int {
val sensorBeaconPair = parseInput(input)
println(sensorBeaconPair)
val things = sensorBeaconPair.flatMap { listOf(it.first, it.second) }.toSet()
var count = 0
for (x in -50_000_000..50_000_000) {
if (x % 10000000 == 0)
println(x)
if (!things.contains(Pair(x, 2000000)) &&
sensorBeaconPair.any { pair -> dist(pair.first, Pair(x, 2000000)) <= dist(pair) }
)
count++
}
return count
}
fun dist(a: Pair<Int, Int>, b: Pair<Int, Int>) =
Math.abs(a.first - b.first) + Math.abs(a.second - b.second)
fun dist(pair: Pair<Pair<Int, Int>, Pair<Int, Int>>) = dist(pair.first, pair.second)
fun printGrid(grid: MutableList<MutableList<Char>>) {
for (i in 0 until grid[0].size) {
for (j in 0 until grid.size) {
print(grid[j][i])
}
print("|${grid[0].size - i}|$i")
print("\n")
}
}
| 0 |
Kotlin
| 0 | 0 |
c50a12b52127eba3f5706de775a350b1568127ae
| 2,687 |
AdventOfCode22
|
Apache License 2.0
|
src/Day12.kt
|
simonbirt
| 574,137,905 | false |
{"Kotlin": 45762}
|
fun main() {
Day12.printSolutionIfTest(31, 29)
}
object Day12 : Day<Int, Int>(12) {
override fun part1(lines: List<String>): Int {
val map = Map2(lines)
val start = map.select { it.label == 'S' }.first()
val end = map.select { it.label == 'E' }
return map.explore(start, end) { current, next -> next.height - current.height <= 1 }
}
override fun part2(lines: List<String>): Int {
val map = Map2(lines)
val start = map.select { it.label == 'E' }.first()
val end = map.select { it.height == 'a'.code }
return map.explore(start, end) { current, next -> current.height - next.height <= 1 }
}
class Map2(val lines: List<String>) {
private val rows = lines.size
private val cols = lines[0].length
private val cells: List<Cell> = lines.flatMap { it.asIterable() }.mapIndexed { index, value ->
when (value) {
'S' -> Cell(value, index, 'a'.code)
'E' -> Cell(value, index, 'z'.code)
else -> Cell(value, index, value.code)
}
}
private fun chooseNext(path: List<Cell>, test: (Cell, Cell) -> Boolean): Sequence<Cell> {
val index = path.last().index
return sequenceOf(::up, ::down, ::left, ::right).mapNotNull { it(index) }
.filter { newIndex -> newIndex !in path.asReversed().map { it.index } }.map { cells[it] }
.filter { test(path.last(), it) }
}
private fun up(index: Int): Int? = (index - cols).takeIf { it >= 0 }
private fun down(index: Int): Int? = (index + cols).takeIf { it < rows * cols }
private fun left(index: Int): Int? = (index - 1).takeIf { it >= 0 && index % cols > 0 }
private fun right(index: Int): Int? = (index + 1).takeIf { it < rows * cols && index % cols < cols }
fun select(test: (Cell) -> Boolean): List<Cell> {
return cells.filter(test)
}
fun explore(start: Cell, end: List<Cell>, test: (Cell, Cell) -> Boolean): Int {
end.forEach { explore(mutableListOf(start), it, test) }
println("")
return end.minOf { it.minPath }
}
private fun explore(path: MutableList<Cell>, end: Cell, test: (Cell, Cell) -> Boolean) {
if (path.size == 0) {
return
}
for (cell in chooseNext(path, test)) {
if (path.size < cell.minPath) {
cell.minPath = path.size
if (cell.index == end.index) {
break
}
else {
path.add(cell)
explore(path, end, test)
}
}
}
path.removeLast()
return
}
}
}
data class Cell(val label: Char, val index: Int, val height: Int, var minPath: Int = Int.MAX_VALUE)
| 0 |
Kotlin
| 0 | 0 |
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
| 2,972 |
advent-of-code-2022
|
Apache License 2.0
|
day-06-kotlin/src/Main.kt
|
jakoberzar
| 159,959,049 | false |
{"JavaScript": 23733, "TypeScript": 11163, "Scala": 8193, "Rust": 7557, "Kotlin": 4451, "C#": 4250, "HTML": 2059}
|
import java.io.File
typealias Coordinates = List<Pair<Int, Int>>;
fun main() {
val input = getInput()
val coords = parseInput(input)
star1(coords)
star2(coords)
}
fun star1(coords: Coordinates) {
val (xBound, yBound) = getSmallestArea(coords)
val amounts = getAmountClosestInArea(coords, (2..xBound), (2..yBound))
val infiniteAreas = findInfinite(coords, xBound, yBound)
val max = amounts
.withIndex()
.filterNot { infiniteAreas.contains(it.index) }
.maxBy { it.value }
println("Size of largest area, ${max?.index} is ${max?.value}")
}
fun star2(coords: Coordinates) {
val (xBound, yBound) = getSmallestArea(coords)
val count = twoD(0..xBound, 0..yBound).count { loc ->
coords.sumBy { coord ->
Math.abs(coord.first - loc.first) + Math.abs(coord.second - loc.second)
} < 10000
}
println("Size of the region with distance < 10000 is $count")
}
fun getInput(): List<String> {
return File("input.txt").readLines()
}
fun parseInput(input: List<String>): Coordinates {
return input.map {
val split = it.split(", ")
Pair(split[0].toInt(), split[1].toInt())
}
}
fun getSmallestArea(coords: Coordinates): Pair<Int, Int> {
return coords
.unzip()
.toList()
.map { it.max() }
.mapNotNull { it }
.zipWithNext()
.first()
}
fun getAmountClosestInArea(coords: Coordinates, rangeX: Iterable<Int>, rangeY: Iterable<Int>): IntArray {
val amount = IntArray(coords.size)
twoD(rangeX, rangeY)
.map { getClosest(coords, it.first, it.second) }
.filter { it > -1 }
.forEach { amount[it]++ }
return amount
}
fun getClosest(coords: Coordinates, x: Int, y: Int): Int {
return coords
.map { Math.abs(it.first - x) + Math.abs(it.second - y) }
.foldIndexed(Pair(-1, Int.MAX_VALUE)) { idx, acc, d ->
when {
d < acc.second -> Pair(idx, d)
d == acc.second -> Pair(-1, d)
else -> acc
}
}.first
}
fun findInfinite(coords: Coordinates, xBound: Int, yBound: Int): List<Int> {
val amountInner = getAmountClosestInArea(coords, 1..xBound + 1, listOf(1, yBound + 1)) // vertical
.zip(getAmountClosestInArea(coords, listOf(1, xBound + 1), 2..yBound), Int::plus) // horizontal
val amountOuter = getAmountClosestInArea(coords, 0..xBound + 2, listOf(0, yBound + 2)) // vertical
.zip(getAmountClosestInArea(coords, listOf(0, xBound + 2), 1..yBound + 1), Int::plus) // horizontal
return coords.indices.filter {
amountOuter[it] > amountInner[it] || amountOuter[it] == amountInner[it] && amountInner[it] != 0
}
}
fun twoD(rangeX: Iterable<Int>, rangeY: Iterable<Int>): Iterable<Pair<Int, Int>> {
return rangeX.flatMap { x -> rangeY.map { y -> Pair(x, y) } }
}
| 0 |
JavaScript
| 0 | 1 |
8779f71cebff6711e8b6613705bcba9714b4e33f
| 2,981 |
advent-of-code-2018
|
MIT License
|
src/Day02.kt
|
ttypic
| 572,859,357 | false |
{"Kotlin": 94821}
|
fun main() {
fun part1(input: List<String>): Int {
return input.mapIndexed { index, game ->
val reveals = game.split(";").map {
val reds = "(\\d+) red".toRegex().find(it)?.groupValues?.get(1)?.toInt() ?: 0
val greens = "(\\d+) green".toRegex().find(it)?.groupValues?.get(1)?.toInt() ?: 0
val blues = "(\\d+) blue".toRegex().find(it)?.groupValues?.get(1)?.toInt() ?: 0
Reveal(reds, greens, blues)
}
val reds = reveals.maxOf { it.red }
val greens = reveals.maxOf { it.green }
val blues = reveals.maxOf { it.blue }
if (reds <= 12 && greens <= 13 && blues <= 14) index + 1 else 0
}.sum()
}
fun part2(input: List<String>): Int {
return input.mapIndexed { index, game ->
val reveals = game.split(";").map {
val reds = "(\\d+) red".toRegex().find(it)?.groupValues?.get(1)?.toInt() ?: 0
val greens = "(\\d+) green".toRegex().find(it)?.groupValues?.get(1)?.toInt() ?: 0
val blues = "(\\d+) blue".toRegex().find(it)?.groupValues?.get(1)?.toInt() ?: 0
Reveal(reds, greens, blues)
}
val reds = reveals.maxOf { it.red }
val greens = reveals.maxOf { it.green }
val blues = reveals.maxOf { it.blue }
reds * greens * blues
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 8)
check(part2(testInput) == 2286)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
data class Reveal(val red: Int, val green: Int, val blue: Int)
| 0 |
Kotlin
| 0 | 0 |
b3e718d122e04a7322ed160b4c02029c33fbad78
| 1,840 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/Day02.kt
|
SeanDijk
| 575,314,390 | false |
{"Kotlin": 29164}
|
enum class Tool(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3)
}
enum class MatchResult(val score: Int) {
WIN(6), DRAW(3), LOSS(0)
}
data class Line(val abc: Char, val xyz: Char)
val WIN_TABLE = mapOf(
// x wins against y
Tool.ROCK to Tool.SCISSORS,
Tool.PAPER to Tool.ROCK,
Tool.SCISSORS to Tool.PAPER
)
val LOSE_TABLE = WIN_TABLE.asSequence().map { Pair(it.value, it.key) }.toMap()
fun main() {
fun transformLines(input: List<String>) = input.asSequence().map { Line(it.first(), it.last()) }
fun toTool(char: Char) = when (char) {
'A', 'X' -> Tool.ROCK
'B', 'Y' -> Tool.PAPER
'C', 'Z' -> Tool.SCISSORS
else -> throw IllegalStateException()
}
fun part1(input: List<String>): Int {
fun runMatch(elfTool: Tool, myTool: Tool): MatchResult {
return when (elfTool) {
myTool -> MatchResult.DRAW
WIN_TABLE[myTool] -> MatchResult.WIN
else -> MatchResult.LOSS
}
}
return transformLines(input)
.map {
val elfTool = toTool(it.abc)
val myTool = toTool(it.xyz)
runMatch(elfTool, myTool).score + myTool.score
}
.sum()
}
fun part2(input: List<String>): Int {
fun toolToLoseAgainst(tool: Tool) = WIN_TABLE[tool]!!
fun toolToWinAgainst(tool: Tool) = LOSE_TABLE[tool]!!
return transformLines(input)
.map {
val elfTool = toTool(it.abc)
when (it.xyz) {
'X' -> toolToLoseAgainst(elfTool).score + MatchResult.LOSS.score
'Y' -> elfTool.score + MatchResult.DRAW.score
'Z' -> toolToWinAgainst(elfTool).score + MatchResult.WIN.score
else -> throw IllegalStateException()
}
}
.sum()
}
val test = """
A Y
B X
C Z
""".trimIndent().lines()
println(part1(test))
println(part1(readInput("Day02")))
println(part2(test))
println(part2(readInput("Day02")))
}
| 0 |
Kotlin
| 0 | 0 |
363747c25efb002fe118e362fb0c7fecb02e3708
| 2,125 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day15.kt
|
p357k4
| 573,068,508 | false |
{"Kotlin": 59696}
|
import kotlin.math.abs
fun main() {
data class Point(val x: Int, val y: Int)
fun distance(sx: Int, sy: Int, bx: Int, by: Int): Int = abs(sx - bx) + abs(sy - by)
fun pairs(input: List<String>) = input.map { line ->
val sx = line
.substringBefore(":")
.substringAfter("x=")
.substringBefore(", ")
.toInt()
val sy = line
.substringBefore(":")
.substringAfter(", y=")
.toInt()
val bx = line
.substringAfter("closest beacon is at x=")
.substringBefore(", ")
.toInt()
val by = line
.substringAfter("closest beacon is at x=")
.substringAfter(", y=")
.toInt()
Pair(Point(sx, sy), Point(bx, by))
}
fun part1(input: List<String>, y: Int): Int {
val data = pairs(input)
val minimum = data.associate { p -> p.first to distance(p.first.x, p.first.y, p.second.x, p.second.y) }
val minX = data.minOf { p -> p.first.x - minimum.getValue(p.first) }
val maxX = data.maxOf { p -> p.first.x + minimum.getValue(p.first) }
val result = (minX..maxX).count { x ->
data.any { p ->
val actual = distance(p.first.x, p.first.y, x, y)
actual <= minimum.getValue(p.first) && !(x == p.second.x && y == p.second.y)
}
}
return result
}
fun part2(input: List<String>, maxX: Int, maxY: Int): Long {
val data = pairs(input)
val minimum = data.associate { p -> p.first to distance(p.first.x, p.first.y, p.second.x, p.second.y) }
fun covered(x: Int, y: Int): Boolean {
return x !in 0..maxX || y !in 0..maxY || data.any { p ->
val actual = distance(p.first.x, p.first.y, x, y)
actual <= minimum.getValue(p.first)
}
}
for (sb in data) {
val r = minimum.getValue(sb.first)
for (r0 in 0..r + 1) {
val x0 = sb.first.x + r0
val x1 = sb.first.x - r0
val y0 = sb.first.y + (r + 1 - r0)
val y1 = sb.first.y - (r + 1 - r0)
if (!covered(x0, y0)) {
return x0 * 4_000_000L + y0
}
if (!covered(x0, y1)) {
return x0 * 4_000_000L + y1
}
if (!covered(x1, y0)) {
return x1 * 4_000_000L + y0
}
if (!covered(x1, y1)) {
return x1 * 4_000_000L + y1
}
}
}
throw IllegalStateException("distress beacon not found")
}
// test if implementation meets criteria from the description, like:
val testInputExample = readInput("Day15_example")
check(part1(testInputExample, 10) == 26)
check(part2(testInputExample, 20, 20) == 56000011L)
val testInput = readInput("Day15_test")
println(part1(testInput, 2_000_000))
println(part2(testInput, 4_000_000, 4_000_000))
}
| 0 |
Kotlin
| 0 | 0 |
b9047b77d37de53be4243478749e9ee3af5b0fac
| 3,099 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/year2023/Day8.kt
|
drademacher
| 725,945,859 | false |
{"Kotlin": 76037}
|
package year2023
import readLines
fun main() {
val input = parseInput(readLines("2023", "day8"))
val testInputPart1 = parseInput(readLines("2023", "day8_test1"))
val testInputPart2 = parseInput(readLines("2023", "day8_test2"))
check(part1(testInputPart1) == 2)
println("Part 1:" + part1(input))
check(part2(testInputPart2) == 6L)
println("Part 2:" + part2(input))
}
private fun parseInput(lines: List<String>): WalkingInstructionsInput {
val cleanedMainLines = lines.drop(2).map { line -> line.filter { it.isLetterOrDigit() || it == ',' || it == '=' } }
val map = mutableMapOf<String, Pair<String, String>>()
for (line in cleanedMainLines) {
val splittedLine = line.split(Regex("[=,]"), 0)
check(splittedLine.size == 3)
map[splittedLine[0]] = Pair(splittedLine[1], splittedLine[2])
}
return WalkingInstructionsInput(
lines[0],
map,
)
}
private fun part1(input: WalkingInstructionsInput): Int {
return input.findExit("AAA", { it == "ZZZ" })
}
private fun part2(input: WalkingInstructionsInput): Long {
val startingNodes = input.simpleGraph.keys.filter { it.endsWith("A") }
// inputs seems to be tailored to have constant loops
val loopDurationDivisors =
startingNodes
.asSequence()
.map { startingNode -> input.findExit(startingNode, { it.endsWith("Z") }) }
.map { loopLength -> getAllDivisors(loopLength) }
// does fail on corner cases
val commonMergedDivisors =
loopDurationDivisors
.flatten()
.toSet()
return commonMergedDivisors.map { it.toLong() }.reduce { acc, current -> acc * current }
}
private fun getAllDivisors(int: Int): MutableList<Int> {
val result = mutableListOf<Int>()
var remaining = int
for (divisor in (2..remaining)) {
while (remaining % divisor == 0) {
result.add(divisor)
remaining /= divisor
}
}
return result
}
private data class WalkingInstructionsInput(val instructions: String, val simpleGraph: Map<String, Pair<String, String>>) {
fun findExit(
start: String,
isGoalReached: (String) -> Boolean,
): Int {
var current = start
var steps = 0
do {
val instruction = instructions[steps % instructions.length]
val node = simpleGraph[current]!!
current = if (instruction == 'R') node.second else node.first
steps += 1
} while (!isGoalReached(current))
return steps
}
}
| 0 |
Kotlin
| 0 | 0 |
4c4cbf677d97cfe96264b922af6ae332b9044ba8
| 2,581 |
advent_of_code
|
MIT License
|
src/Day05.kt
|
semanticer
| 577,822,514 | false |
{"Kotlin": 9812}
|
fun main() {
fun part1(input: List<String>): String {
val crateMover9000: CrateMover = { move ->
val from: ArrayDeque<Char> = this[move.from - 1]
val to = this[move.to - 1]
repeat(move.quantity) {
val movingPiece = from.last()
from.removeLast()
to.addLast(movingPiece)
}
}
return processWith(input, crateMover9000)
}
fun part2(input: List<String>): String {
val crateMover9001: CrateMover = { move ->
val from: ArrayDeque<Char> = this[move.from - 1]
val to = this[move.to - 1]
val movingPieces = from.takeLast(move.quantity)
to.addAll(movingPieces)
repeat(move.quantity) {
from.removeLast()
}
}
return processWith(input, crateMover9001)
}
// 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")
part1(input).println()
part2(input).println()
}
private fun processWith(input: List<String>, crateMover: CrateMover): String {
val stacks: List<ArrayDeque<Char>> = parseStacks(input)
val moveProcedure: List<Move> = parseMoves(input)
moveProcedure.forEach { move -> stacks.crateMover(move) }
return stacks.map { it.last() }.joinToString("")
}
fun parseStacks(input: List<String>): List<ArrayDeque<Char>> {
val numberOfStacks = input.find { it.startsWith(" 1") }!!.trim().last().toString().toInt()
val stacks = List(numberOfStacks) { ArrayDeque<Char>() }
input.filter { it.contains("[") }
.map {
it.windowed(size = 3, step = 4)
.forEachIndexed { index, item ->
if (item.isNotBlank()) {
stacks[index].addFirst(item[1])
}
}
}
return stacks
}
fun parseMoves(input: List<String>): List<Move> {
return input.map { it.split(" ") }
.filter { it[0] == "move" }
.map { Move(it[1].toInt(), it[3].toInt(), it[5].toInt()) }
}
data class Move(val quantity: Int, val from: Int, val to: Int)
typealias CrateMover = List<ArrayDeque<Char>>.(move: Move) -> Unit
| 0 |
Kotlin
| 0 | 0 |
9013cb13f0489a5c77d4392f284191cceed75b92
| 2,350 |
Kotlin-Advent-of-Code-2022
|
Apache License 2.0
|
src/day14/Day14.kt
|
davidcurrie
| 579,636,994 | false |
{"Kotlin": 52697}
|
package day14
import java.io.File
import kotlin.math.max
import kotlin.math.min
fun main() {
val rocks = File("src/day14/input.txt").readLines().map { line ->
Rock(line.split(" -> ").map { coord -> coord.split(",").let { Pair(it[0].toInt(), it[1].toInt()) } })
}
println(solve(rocks, false))
println(solve(rocks, true))
}
fun solve(rocks: List<Rock>, floor: Boolean): Int {
val rocksBoundary = rocks.map { it.boundary }.reduce(Box::merge)
val settledSand = mutableSetOf<Pair<Int, Int>>()
val start = Pair(500, 0)
outer@ while (true) {
var sand = start
while (true) {
sand = listOf(Pair(0, 1), Pair(-1, 1), Pair(1, 1)).map { delta -> sand + delta }
.firstOrNull { option ->
option !in settledSand
&& (!rocksBoundary.contains(option) || rocks.none { rock -> rock.hit(option) })
&& (!floor || option.second != rocksBoundary.bottom + 2)
} ?: break
if (!floor && sand.second > rocksBoundary.bottom) break@outer
}
settledSand.add(sand)
if (sand == start) break
}
return settledSand.size
}
operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> {
return Pair(first + other.first, second + other.second)
}
data class Box(val a: Pair<Int, Int>, val b: Pair<Int, Int>) {
private val topLeft = Pair(min(a.first, b.first), min(a.second, b.second))
private val bottomRight = Pair(max(a.first, b.first), max(a.second, b.second))
val bottom = bottomRight.second
fun contains(coord: Pair<Int, Int>): Boolean =
coord.first >= topLeft.first && coord.first <= bottomRight.first &&
coord.second >= topLeft.second && coord.second <= bottomRight.second
fun merge(other: Box): Box =
Box(
Pair(min(topLeft.first, other.topLeft.first), min(topLeft.second, other.topLeft.second)),
Pair(max(bottomRight.first, other.bottomRight.first), max(bottomRight.second, other.bottomRight.second))
)
}
data class Rock(val coords: List<Pair<Int, Int>>) {
private val boxes = coords.zipWithNext().map { pair -> Box(pair.first, pair.second) }
val boundary = boxes.reduce(Box::merge)
fun hit(coord: Pair<Int, Int>): Boolean {
return boundary.contains(coord) && boxes.any { it.contains(coord) }
}
}
| 0 |
Kotlin
| 0 | 0 |
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
| 2,416 |
advent-of-code-2022
|
MIT License
|
src/Day02.kt
|
jdappel
| 575,879,747 | false |
{"Kotlin": 10062}
|
enum class Values(val pts: Int) {
ROCK(1), PAPER(2), SCISSORS(3)
}
val resultMap: Map<String, Map<String, Int>> = mapOf(
"A" to mapOf("X" to 3, "Y" to 6, "Z" to 0),
"B" to mapOf("X" to 0, "Y" to 3, "Z" to 6),
"C" to mapOf("X" to 6, "Y" to 0, "Z" to 3)
)
val reverseMap = mapOf("X" to Values.ROCK, "Y" to Values.PAPER, "Z" to Values.SCISSORS)
val part2ScoreMap = mapOf("X" to 0, "Y" to 3, "Z" to 6)
val part2PlayMap: Map<String, Map<Int, String>> = mapOf(
"A" to mapOf(3 to "X", 6 to "Y", 0 to "Z"),
"B" to mapOf(0 to "X", 3 to "Y", 6 to "Z"),
"C" to mapOf(6 to "X", 0 to "Y", 3 to "Z")
)
fun score(elf: String, me: String): Int {
val score = resultMap[elf]?.get(me) ?: 0
return score + (reverseMap[me]?.pts ?: 0)
}
fun score2(elf: String, me: String): Int {
val score = part2ScoreMap[me] ?: 0
return score + (reverseMap[part2PlayMap[elf]?.get(score)]?.pts ?: 0)
}
fun main() {
fun logic(input: List<String>): Int {
return input.fold(0) { acc, line ->
val (elf, me) = line.split(" ")
acc + score2(elf, me)
}
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("Day02_test")
println(logic(input))
}
| 0 |
Kotlin
| 0 | 0 |
ddcf4f0be47ccbe4409605b37f43534125ee859d
| 1,329 |
AdventOfCodeKotlin
|
Apache License 2.0
|
src/Day16.kt
|
ked4ma
| 573,017,240 | false |
{"Kotlin": 51348}
|
import kotlin.math.ceil
/**
* [Day16](https://adventofcode.com/2022/day/16)
*/
private class Day16 {
data class Node(val key: String, val rate: Int) {
val valves = mutableListOf<String>()
}
data class Snapshot(val keys: List<String>, val estimate: Int, val opened: Set<String>, val time: Int)
}
fun main() {
fun parse(input: List<String>): Map<String, Day16.Node> {
val pattern = """Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? (.+)""".toRegex()
return buildMap {
input.forEach { line ->
pattern.find(line)!!.groupValues.let { (_, key, rate, valves) ->
val valveKeys = valves.split(", ")
put(key,
Day16.Node(key, rate.toInt()).apply {
this.valves.addAll(valveKeys)
}
)
}
}
}
}
fun estimate(maps: Map<String, Day16.Node>, playerNum: Int = 1, round: Int = 30): Map<List<String>, Int> {
val start = (1..playerNum).map { "AA" }
val estimates = mutableMapOf(start to 0)
val queue = ArrayDeque(listOf(Day16.Snapshot(start, 0, emptySet(), round * playerNum)))
val bucket = mutableSetOf<Day16.Snapshot>()
fun addToBucket(snap: Day16.Snapshot) {
if (snap.keys !in estimates || snap.keys.filter { it !in snap.opened }.distinct().sumOf {
maps.getValue(it).rate
}.let { it * (snap.time - 1) } + snap.estimate >= estimates.getValue(snap.keys)
) {
bucket.add(snap)
}
}
while (queue.isNotEmpty() || bucket.isNotEmpty()) {
if (queue.isEmpty()) {
queue.addAll(bucket)
bucket.clear()
}
val (current, est, opened, rem) = queue.removeFirst()
val index = rem % playerNum
val nodes = current.map(maps::getValue)
val time = ceil(rem.toFloat() / playerNum).toInt()
when {
rem <= 0 -> continue // finish
// no value to open
nodes[index].rate == 0 -> Unit
// already opened
current[index] in opened -> Unit
est + nodes[index].rate * (time - 1) > estimates.getOrDefault(current, 0) -> {
val v = est + nodes[index].rate * (time - 1)
estimates[current] = v
addToBucket(Day16.Snapshot(current, v, opened + current[index], rem - 1))
}
else -> Unit
}
nodes[index].valves.forEach {
val next = current.toMutableList().apply {
this[index] = it
}
addToBucket(Day16.Snapshot(next, est, opened, rem - 1))
}
}
return estimates
}
fun part1(input: List<String>): Int {
val maps = parse(input)
val estimates = estimate(maps)
return estimates.values.max()
}
fun part2(input: List<String>): Int {
val maps = parse(input)
val estimates = estimate(maps, 2, 26)
return estimates.values.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 1 |
Kotlin
| 0 | 0 |
6d4794d75b33c4ca7e83e45a85823e828c833c62
| 3,536 |
aoc-in-kotlin-2022
|
Apache License 2.0
|
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-17.kt
|
ferinagy
| 432,170,488 | false |
{"Kotlin": 787586}
|
package com.github.ferinagy.adventOfCode.aoc2015
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2015, "17-input")
val test1 = readInputLines(2015, "17-test1")
println("Part1:")
part1(test1, 25).println()
part1(input, 150).println()
println()
println("Part2:")
part2(test1, 25).println()
part2(input, 150).println()
}
private fun part1(input: List<String>, total: Int): Int {
val list = input.map { it.toInt() }
val combinations = combinations(Combo(list, emptyList(), 0))
return combinations.filter { it.sum == total }.size
}
private fun part2(input: List<String>, total: Int): Int {
val list = input.map { it.toInt() }
val combinations = combinations(Combo(list, emptyList(), 0)).filter { it.sum == total }
val min = combinations.minOf { it.usedContainers.size }
return combinations.filter { it.usedContainers.size == min }.size
}
private fun combinations(partial: Combo): List<Combo> {
if (partial.availableContainers.isEmpty()) {
return listOf(partial)
}
val tail = partial.availableContainers.drop(1)
val sub = combinations(Combo(tail, emptyList(), 0))
val current = partial.availableContainers.first()
return sub + sub.map { it.copy(usedContainers = it.usedContainers + current, sum = it.sum + current) }
}
private data class Combo(val availableContainers: List<Int>, val usedContainers: List<Int>, val sum: Int)
| 0 |
Kotlin
| 0 | 1 |
f4890c25841c78784b308db0c814d88cf2de384b
| 1,523 |
advent-of-code
|
MIT License
|
src/Day04.kt
|
makobernal
| 573,037,099 | false |
{"Kotlin": 16467}
|
fun main() {
fun parseToRange(z:String) : IntRange = z.substringBefore("-").toInt()..z.substringAfter("-").toInt()
fun isEitherRangeContainingTheOther(ranges: Pair<IntRange, IntRange>): Boolean =
ranges.first.toList().containsAll(ranges.second.toList()) ||
ranges.second.toList().containsAll(ranges.first.toList())
fun toRangePairs(input: List<String>) = input
.map { it.split(",") }
.map { Pair(parseToRange(it[0]), parseToRange(it[1])) }
fun part1(input: List<String>): Int {
val fullyContainedRanges = toRangePairs(input)
.filter { isEitherRangeContainingTheOther(it) }
return fullyContainedRanges.size
}
fun isThereAnyOverlap(pair: Pair<IntRange, IntRange>) : Boolean {
val totalSize = pair.first.count() + pair.second.count()
val mergedSize = (pair.first.toList() + pair.second.toList()).toSet().size
return totalSize != mergedSize
}
fun part2(input: List<String>): Int {
val pairsOverlapping = toRangePairs(input)
.filter { isThereAnyOverlap(it) }
return pairsOverlapping.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val testResult = part1(testInput)
val testResult2 = part2(testInput)
check(testResult == 2) { "wrong input $testResult is not 2" }
check(testResult2 == 4) { "wrong input $testResult is not 4" }
val input = readInput("Day04")
val result1 = part1(input)
val result2 = part2(input)
println("solution for your input, part 1 = $result1")
println("solution for your input, part 2 = $result2")
}
| 0 |
Kotlin
| 0 | 0 |
63841809f7932901e97465b2dcceb7cec10773b9
| 1,695 |
kotlin-advent-of-code-2022
|
Apache License 2.0
|
src/Day04.kt
|
martintomac
| 726,272,603 | false |
{"Kotlin": 19489}
|
import kotlin.math.pow
data class Scratchcard(
val id: Int,
val winningNumbers: Set<Int>,
val myNumbers: Set<Int>,
)
val Scratchcard.winCount: Int get() = myNumbers.count { it in winningNumbers }
fun main() {
fun parseScratchcard(line: String): Scratchcard {
val (_, cardNumber, winningNumsPart, myNumsPart) =
"Card +(\\d+): +(.+) +\\| +(.+)".toRegex().matchEntire(line)!!.groupValues
val winningNumbers = winningNumsPart.trim().split(" +".toRegex()).map { it.toInt() }.toSet()
val myNumbers = myNumsPart.trim().split(" +".toRegex()).map { it.toInt() }.toSet()
return Scratchcard(cardNumber.toInt(), winningNumbers, myNumbers)
}
fun sumNumberOfScoredPoints(lines: List<String>): Int {
return lines.map { parseScratchcard(it) }
.sumOf { scratchcard ->
when {
scratchcard.winCount == 0 -> 0
else -> 2.0.pow(scratchcard.winCount - 1).toInt()
}
}
}
fun getNumOfTotalScratchcards(lines: List<String>): Int {
val scratchcards = lines.map { parseScratchcard(it) }
val idToNumOfScratchcards = scratchcards.associate { it.id to 1 }.toMutableMap()
scratchcards.forEach { scratchcard ->
val increment = idToNumOfScratchcards[scratchcard.id]!!
for (i in 1..scratchcard.winCount) {
val scratchcardNum = scratchcard.id + i
if (scratchcardNum > scratchcards.count()) break
idToNumOfScratchcards[scratchcardNum] =
idToNumOfScratchcards[scratchcardNum]!! + increment
}
}
return idToNumOfScratchcards.values.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
sumNumberOfScoredPoints(testInput).println()
getNumOfTotalScratchcards(testInput).println()
val input = readInput("Day04")
sumNumberOfScoredPoints(input).println()
getNumOfTotalScratchcards(input).println()
}
| 0 |
Kotlin
| 0 | 0 |
dc97b23f8461ceb9eb5a53d33986fb1e26469964
| 2,086 |
advent-of-code-2023
|
Apache License 2.0
|
src/Day05.kt
|
epishkin
| 572,788,077 | false |
{"Kotlin": 6572}
|
fun main() {
fun parseInput(input: List<String>): Pair<MutableList<MutableList<Char>>, List<CraneCommand>> {
val (first, last) = input.partition { !it.startsWith("move") }
val stackCount = first
.first { it.isNotEmpty() && !it.contains("[") }
.split(" ")
.filter { it.isNotEmpty() }
.maxOf { it.toInt() }
val stacks = mutableListOf<MutableList<Char>>()
repeat(stackCount) {
stacks.add(mutableListOf<Char>())
}
first
.filter { it.isNotEmpty() }
.forEach {
it.forEachIndexed { idx, cell ->
if (cell.isLetter()) {
val col = idx / 4
stacks[col].add(cell)
}
}
}
val commandRegex = """move (\d+) from (\d+) to (\d+)""".toRegex()
val commands = last.map { line ->
val (_, count, from, to) = commandRegex.find(line)!!.groupValues
CraneCommand(count.toInt(), from.toInt(), to.toInt())
}
return Pair(stacks, commands)
}
fun part1(input: List<String>): String {
val (stacks, commands) = parseInput(input)
commands.forEach { cmd ->
repeat(cmd.count) {
val crate = stacks[cmd.from - 1].removeFirst()
stacks[cmd.to - 1].add(0, crate)
}
}
return stacks
.map { it.first() }
.joinToString("")
}
fun part2(input: List<String>): String {
val (stacks, commands) = parseInput(input)
commands.forEach { cmd ->
repeat(cmd.count) {
val crate = stacks[cmd.from - 1].removeFirst()
stacks[cmd.to - 1].add(it, crate)
}
}
return stacks
.map { it.first() }
.joinToString("")
}
// 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))
}
private data class CraneCommand(val count: Int, val from: Int, val to: Int)
| 0 |
Kotlin
| 0 | 0 |
e5e5755c2d77f75750bde01ec5aad70652ef4dbf
| 2,281 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day18.kt
|
astrofyz
| 572,802,282 | false |
{"Kotlin": 124466}
|
fun main(){
fun List<Int>.isAdjacent(other: List<Int>):Boolean{
val diff = this.mapIndexed { index, i -> kotlin.math.abs(this[index] - other[index]) }.toList()
return (diff.count{it==0} == 2)&&(diff.count{it==1} == 1)
}
fun part1(input: List<String>){
val cubes = input.map { it.split(',').map { elem -> elem.toInt() } }
val result = mutableListOf<Boolean>()
for (i in 0 until cubes.size){
for (j in i until cubes.size){
result.add(cubes[i].isAdjacent(cubes[j]))
}
}
println("part1 : ${input.size * 6 - 2*result.count { it }}")
}
fun part2(input: List<String>) {
val cubes = input.map { it.split(',').map { elem -> elem.toInt() } }
var allNeighbours = mutableSetOf<List<Int>>()
for (cube in cubes){
for (dir in listOf<Int>(-1, 1)){
allNeighbours.add(listOf(cube[0]+dir, cube[1], cube[2]))
allNeighbours.add(listOf(cube[0], cube[1]+dir, cube[2]))
allNeighbours.add(listOf(cube[0], cube[1], cube[2]+dir))
}
}
allNeighbours = allNeighbours.subtract(cubes) as MutableSet<List<Int>>
val minList = IntRange(0, 2).map { k -> cubes.map { it[k] }.toList().min()}.toList()
val maxList = IntRange(0, 2).map { k -> cubes.map { it[k] }.toList().max()}.toList()
fun List<Int>.ifInside(): Boolean{
val inside = mutableListOf<Int>()
inside.add(cubes.map { (it[0] in (this[0] .. maxList[0]+3))&&(it[1] == this[1])&&(it[2] == this[2]) }.count { it })
inside.add(cubes.map { (it[0] in (minList[0]-3 .. this[0]))&&(it[1] == this[1])&&(it[2] == this[2]) }.count { it })
inside.add(cubes.map { (it[1] in (this[1] .. maxList[1]+3))&&(it[0] == this[0])&&(it[2] == this[2]) }.count { it })
inside.add(cubes.map { (it[1] in (minList[1]-3 .. this[1]))&&(it[0] == this[0])&&(it[2] == this[2]) }.count { it })
inside.add(cubes.map { (it[2] in (this[2] .. maxList[2]+3))&&(it[1] == this[1])&&(it[0] == this[0]) }.count { it })
inside.add(cubes.map { (it[2] in (minList[2]-3 .. this[2]))&&(it[1] == this[1])&&(it[0] == this[0]) }.count { it })
return inside.all { it > 0 }
}
val cubesInside = allNeighbours.filter { !it.ifInside() }
var adjSides = 0
for (cubeAir in cubesInside){
adjSides += cubes.map { it.isAdjacent(cubeAir) }.toList().count { it == true }
}
println("part2 (wrong) $adjSides")
}
fun part2BFS(input: List<String>){
val cubes = input.map { it.split(',').map { elem -> elem.toInt() } }
val minList = IntRange(0, 2).map { k -> cubes.map { it[k] }.toList().min()}.toList()
val maxList = IntRange(0, 2).map { k -> cubes.map { it[k] }.toList().max()}.toList()
fun List<Int>.neighbours(): List<List<Int>> {
return listOf(
listOf(this[0]-1, this[1], this[2]),
listOf(this[0]+1, this[1], this[2]),
listOf(this[0], this[1]+1, this[2]),
listOf(this[0], this[1]-1, this[2]),
listOf(this[0], this[1], this[2]+1),
listOf(this[0], this[1], this[2]-1)
)
}
val queue = ArrayDeque(listOf(listOf(minList[0]-1, minList[1]-1, minList[2]-1)))
val outside = mutableSetOf<List<Int>>()
while (queue.isNotEmpty()){
for (air in queue.removeFirst().neighbours().filter{(it !in cubes)}){
if ((air[0] in minList[0]-1 .. maxList[0]+1) &&
(air[1] in minList[1]-1 .. maxList[1]+1) &&
(air[2] in minList[2]-1 .. maxList[2]+1) &&
(air !in outside)){
queue.add(air)
outside.add(air)
}
}
}
var adjSides = 0
for (cubeAir in outside){
adjSides += cubes.map { it.isAdjacent(cubeAir) }.toList().count { it == true }
}
println("part2: $adjSides")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18")
part1(testInput)
part2(testInput)
part2BFS(testInput)
}
| 0 |
Kotlin
| 0 | 0 |
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
| 4,307 |
aoc22
|
Apache License 2.0
|
src/main/kotlin/aoc2023/Day06.kt
|
j4velin
| 572,870,735 | false |
{"Kotlin": 285016, "Python": 1446}
|
package aoc2023
import multiplyOf
import readInput
private data class Race(val time: Long, val recordDistance: Long) {
companion object {
fun fromStrings(input: List<String>): List<Race> {
val times =
input.first().replace("Time: ", "").split("\\s+".toRegex()).filter { it.isNotEmpty() }
.map { it.toLong() }
val distances =
input.drop(1).first().replace("Distance: ", "").split("\\s+".toRegex()).filter { it.isNotEmpty() }
.map { it.toLong() }
return times.withIndex().map { (index, time) -> Race(time, distances[index]) }
}
}
val possiblePresstimesToBeatTheRecord = sequence {
for (time in 0..time) {
if (getAchievableDistance(time) > recordDistance) {
yield(time)
}
}
}
private fun getAchievableDistance(pressedTime: Long) = (time - pressedTime) * pressedTime
}
object Day06 {
fun part1(input: List<String>): Int {
val races = Race.fromStrings(input)
return races.map { it.possiblePresstimesToBeatTheRecord.count() }.multiplyOf { it }
}
fun part2(input: List<String>): Int {
val time = input.first().replace("Time: ", "").replace(" ", "").toLong()
val distance = input.drop(1).first().replace("Distance: ", "").replace(" ", "").toLong()
val race = Race(time, distance)
return race.possiblePresstimesToBeatTheRecord.count()
}
}
fun main() {
val testInput = readInput("Day06_test", 2023)
check(Day06.part1(testInput) == 288)
check(Day06.part2(testInput) == 71503)
val input = readInput("Day06", 2023)
println(Day06.part1(input))
println(Day06.part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
f67b4d11ef6a02cba5b206aba340df1e9631b42b
| 1,757 |
adventOfCode
|
Apache License 2.0
|
src/Day09.kt
|
chbirmes
| 572,675,727 | false |
{"Kotlin": 32114}
|
import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
fun solveForTailLength(tailLength: Int, input: List<String>): Int {
val tail = List(tailLength) { origin }
return input.asSequence()
.flatMap { it.toMoves() }
.fold(KnotState(origin, tail)) { state, move -> state.process(move) }
.visitedByLastTailKnot
.size
}
fun part1(input: List<String>): Int = solveForTailLength(1, input)
fun part2(input: List<String>): Int = solveForTailLength(9, input)
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
private fun String.toMoves() = List(drop(2).toInt()) { first() }
private data class Position(val x: Int, val y: Int) {
fun move(move: Char): Position =
when (move) {
'R' -> Position(x + 1, y)
'L' -> Position(x - 1, y)
'U' -> Position(x, y + 1)
'D' -> Position(x, y - 1)
else -> throw IllegalArgumentException()
}
fun follow(other: Position): Position {
val relativeOther = Position(other.x - x, other.y - y)
return if (relativeOther.x.absoluteValue < 2 && relativeOther.y.absoluteValue < 2) {
this
} else {
Position(x + relativeOther.x.sign, y + relativeOther.y.sign)
}
}
}
private val origin = Position(0, 0)
private data class KnotState(val head: Position, val tail: List<Position>, val visitedByLastTailKnot: Set<Position> = setOf(tail.last())) {
fun process(move: Char): KnotState {
val newHead = head.move(move)
val newTail = tail.fold(listOf(newHead)) { newList, knot ->
newList + knot.follow(newList.last())
}
.drop(1)
return KnotState(newHead, newTail, visitedByLastTailKnot + newTail.last())
}
}
| 0 |
Kotlin
| 0 | 0 |
db82954ee965238e19c9c917d5c278a274975f26
| 2,017 |
aoc-2022
|
Apache License 2.0
|
src/main/Day12.kt
|
ssiegler
| 572,678,606 | false |
{"Kotlin": 76434}
|
package day12
import geometry.Direction
import geometry.Position
import geometry.move
import utils.characterPositions
import utils.readInput
import java.util.*
typealias Height = UByte
data class HeightMap(
private val heights: Map<Position, Height>,
private val start: Position,
private val target: Position,
) {
private fun Position.neighbors(): List<Position> =
Direction.values()
.map(::move)
.filter { heights[it] != null }
.filter { heights[it]!! + 1u >= heights[this]!! }
fun shortestPathLength(): Int =
calculateDistances(target)[start] ?: error("No path to target found")
fun shortestPathLengthFromAnywhere(): Int =
calculateDistances(target)
.filter { (position, _) -> heights[position]!! == 0.toUByte() }
.minBy { (_, distance) -> distance }
.value
private fun calculateDistances(position: Position): Map<Position, Int> {
val distances = mutableMapOf(position to 0)
val boundary =
PriorityQueue<Position>(Comparator.comparing { distances[it] ?: Int.MAX_VALUE })
boundary.add(position)
while (boundary.isNotEmpty()) {
val next = boundary.remove()
val distance = distances[next]!! + 1
for (neighbor in next.neighbors().filter { distances[it] == null }) {
distances[neighbor] = distance
boundary.add(neighbor)
}
}
return distances
}
}
fun Char.toHeight(): Height =
when (this) {
in 'a'..'z' -> minus('a').toUByte()
'S' -> 0u
'E' -> 25u
else -> error("Unknown height for marker '$this'")
}
fun List<String>.readHeightMap(): HeightMap {
val characterPositions = characterPositions
return HeightMap(
characterPositions.mapValues { (_, value) -> value.toHeight() },
characterPositions.entries.find { it.value == 'S' }?.key ?: error("start point not found"),
characterPositions.entries.find { it.value == 'E' }?.key ?: error("end point not found"),
)
}
fun part1(filename: String): Int = readInput(filename).readHeightMap().shortestPathLength()
fun part2(filename: String): Int =
readInput(filename).readHeightMap().shortestPathLengthFromAnywhere()
private const val filename = "Day12"
fun main() {
println(part1(filename))
println(part2(filename))
}
| 0 |
Kotlin
| 0 | 0 |
9133485ca742ec16ee4c7f7f2a78410e66f51d80
| 2,422 |
aoc-2022
|
Apache License 2.0
|
y2022/src/main/kotlin/adventofcode/y2022/Day19.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2022
import adventofcode.io.AdventSolution
import kotlin.math.ceil
object Day19 : AdventSolution(2022, 19, "Not Enough Minerals") {
override fun solvePartOne(input: String) = parse(input)
.map { bp -> solveWithBlueprint(bp, 24) }
.sumOf { (i, v) -> i * v }
override fun solvePartTwo(input: String) = parse(input)
.take(3)
.map { bp -> solveWithBlueprint(bp, 32) }
.map { it.second }
.reduce(Int::times)
private fun solveWithBlueprint(bp: Blueprint, time: Int): Pair<Int, Int> {
val states = List(time + 1) { mutableSetOf<State>() }
states[0] += State(
materials = Mats(0, 0, 0, 0),
delta = Mats(1, 0, 0, 0), 0
)
for (i in 0 until time) {
prune(states[i], time)
states[i].flatMap { it.next(bp, time) }.groupBy { it.time }.forEach { (index, new) ->
if (index in states.indices)
states[index] += new
}
states[i].clear()
}
return bp.index to states.last().maxOf { it.materials.geode }
}
private fun parse(input: String): Sequence<Blueprint> {
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()
return input.lineSequence()
.map { regex.matchEntire(it)!!.groupValues.drop(1).map { it.toInt() } }
.map {
Blueprint(
index = it[0],
ore = Mats(it[1], 0, 0, 0),
clay = Mats(it[2], 0, 0, 0),
obsidian = Mats(it[3], it[4], 0, 0),
geode = Mats(it[5], 0, it[6], 0)
)
}
}
private data class Blueprint(val index: Int, val ore: Mats, val clay: Mats, val obsidian: Mats, val geode: Mats) {
val maxima = listOf(ore, clay, obsidian, geode).reduce(Mats::max)
}
private fun prune(states: MutableSet<State>, finishTime: Int) {
if (states.isEmpty()) return
val stepsRemaining = finishTime - states.first().time
val minimalBestScore = states.maxOf { it.materials.geode + it.delta.geode * stepsRemaining }
states.retainAll { candidate ->
val minimalScore = candidate.materials.geode + candidate.delta.geode * stepsRemaining
val bestDelta = (stepsRemaining * stepsRemaining + 1) / 2
minimalScore + bestDelta > minimalBestScore
}
}
private data class State(val materials: Mats, val delta: Mats, val time: Int) {
private fun buildOre(blueprint: Blueprint) =
State(materials - blueprint.ore, delta.copy(ore = delta.ore + 1), time)
private fun buildClay(blueprint: Blueprint) =
State(materials - blueprint.clay, delta.copy(clay = delta.clay + 1), time)
private fun buildObsidian(blueprint: Blueprint) =
State(materials - blueprint.obsidian, delta.copy(obsidian = delta.obsidian + 1), time)
private fun buildGeode(blueprint: Blueprint) =
State(materials - blueprint.geode, delta.copy(geode = delta.geode + 1), time)
fun next(blueprint: Blueprint, end: Int): List<State> {
val candidates = buildList {
if (delta.obsidian > 0) add(buildGeode(blueprint))
if (delta.clay > 0 && delta.obsidian < blueprint.maxima.obsidian) add(buildObsidian(blueprint))
if (delta.clay < blueprint.maxima.clay) add(buildClay(blueprint))
if (delta.ore < blueprint.maxima.ore) add(buildOre(blueprint))
}
val resume = candidates.map {
val fOre = if (it.materials.ore >= 0) 0.0f else -it.materials.ore.toFloat() / this.delta.ore
val fClay = if (it.materials.clay >= 0) 0.0f else -it.materials.clay.toFloat() / this.delta.clay
val fObsidian =
if (it.materials.obsidian >= 0) 0.0f else -it.materials.obsidian.toFloat() / this.delta.obsidian
val steps = ceil(maxOf(fClay, fOre, fObsidian)).toInt() + 1
it.copy(materials = it.materials + this.delta * steps, time = time + steps)
}
val takeNothingAndWait = copy(materials = materials + this.delta * (end - time), time = end)
return resume + takeNothingAndWait
}
}
private data class Mats(val ore: Int, val clay: Int, val obsidian: Int, val geode: Int) {
operator fun plus(other: Mats) = Mats(
ore + other.ore,
clay + other.clay,
obsidian + other.obsidian,
geode + other.geode
)
operator fun times(s: Int) = Mats(
ore * s,
clay * s,
obsidian * s,
geode * s
)
operator fun minus(other: Mats) = Mats(
ore - other.ore,
clay - other.clay,
obsidian - other.obsidian,
geode - other.geode
)
fun max(other: Mats) = Mats(
maxOf(ore, other.ore),
maxOf(clay, other.clay),
maxOf(obsidian, other.obsidian),
maxOf(geode, other.geode)
)
}
}
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 5,350 |
advent-of-code
|
MIT License
|
src/Day05.kt
|
rod41732
| 572,917,438 | false |
{"Kotlin": 85344}
|
typealias Stack = MutableList<Char>
fun main() {
val lines = readInput("Day05")
fun part1(lines: List<String>): String {
val (stacks, operations) = parseInput(lines)
operations.forEach { (num, src, dst) ->
repeat(num) { stacks[dst].add(stacks[src].removeLast()) }
}
return stacks.map { it.last() }.joinToString("")
}
fun part2(lines: List<String>): String {
val (stacks, operations) = parseInput(lines)
operations.forEach { (num, src, dst) ->
val lastN = List(num) { stacks[src].removeLast() }.reversed()
stacks[dst].addAll(lastN)
}
return stacks.map { it.last() }.joinToString("")
}
val testLines = readInput("Day05_test")
check(part1(testLines) == "CMZ")
check(part2(testLines) == "MCD")
println("Part 1")
println(part1(lines))
println("Part 2")
println(part2(lines))
}
private fun parseInput(lines: List<String>): Pair<List<Stack>, List<Operation>> {
val (stackInput, operationInput) = splitInput(lines)
return parseStacks(stackInput) to operationInput.map(::parseOperation)
}
private fun splitInput(lines: List<String>): Pair<List<String>, List<String>> {
val sep = lines.indexOfFirst { it.isBlank() }
val stacksInput = lines.slice(0..sep - 1)
val operations = lines.subList(sep + 1, lines.size)
return stacksInput to operations
}
private fun parseStacks(stackInput: List<String>): List<MutableList<Char>> {
val count = stackInput.last().count { it != ' ' }
val stacks = List(count) { mutableListOf<Char>() }
stackInput.dropLast(1).reversed().forEach { line ->
// NOTE: this won't work if number of stacks >= 10
line.slice(1..line.length step 4).forEachIndexed { i, char ->
if (char != ' ') stacks[i].add(char)
}
}
return stacks
}
private data class Operation(val count: Int, val srcIndex: Int, val dstIndex: Int)
private fun parseOperation(line: String): Operation {
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
return regex.find(line)!!.groupValues.drop(1).map { it.toInt() }
.let { (num, src, dst) -> Operation(num, src - 1, dst - 1) }
}
| 0 |
Kotlin
| 0 | 0 |
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
| 2,212 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/Day16.kt
|
akijowski
| 574,262,746 | false |
{"Kotlin": 56887, "Shell": 101}
|
data class Valve(val flow: Int, val next: List<String>)
data class Path(val valves: List<Valve>, val opened: Map<Valve, Int>) {
fun total(): Int = opened.map { (v, t) -> (30 - t) * v.flow }.sum()
}
fun main() {
val fre = """^Valve (\w+) has flow rate=(\d+)$""".toRegex()
val lre = """^[a-z\s]+([A-Z,\s]+)$""".toRegex()
// DFS and find the "best" each time. Ew.
fun part1(input: List<String>): Int {
val adjList = buildMap {
input.map {
val s1 = it.substringBefore(";")
val s2 = it.substringAfter(";")
val (r, f) = fre.matchEntire(s1)?.destructured ?: throw IllegalArgumentException("invalid: $it")
val next = lre.matchEntire(s2)?.groups?.last()?.value ?: throw IllegalArgumentException("invalid: $it")
put(r, Valve(f.trim().toInt(), next.split(",").map { s -> s.trim() }))
}
}
val maxOpened = adjList.values.count {it.flow > 0}
val start = adjList["AA"]!!
val startPath = Path(listOf(start), HashMap())
var allPaths = listOf(startPath)
var bestPath = startPath
var time = 1
while (time < 30) {
val newPaths = mutableListOf<Path>()
for (curr in allPaths) {
// no more work to do
if (curr.opened.size == maxOpened) {
continue
}
val currentLast = curr.valves.last()
val currentValves = curr.valves
// open valve option
if (currentLast.flow > 0 && !curr.opened.containsKey(currentLast)) {
val opened = curr.opened.toMutableMap()
opened[currentLast] = time
val possibleValves = currentValves + currentLast
val possibleOpenedPath = Path(possibleValves, opened)
newPaths.add(possibleOpenedPath)
}
// move to valve option
val possiblePaths = currentLast.next.map { next ->
val possibleValve = adjList[next] ?: error("could not find valve $next")
val possibleValves = currentValves + possibleValve
val possiblePath = Path(possibleValves, curr.opened)
possiblePath
}
newPaths.addAll(possiblePaths)
}
// arbitrary truncation
allPaths = newPaths.sortedByDescending { it.total() }.take(10_000)
if (allPaths.first().total() > bestPath.total()) {
bestPath = allPaths.first()
}
time++
}
return bestPath.total()
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 1 | 0 |
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
| 3,049 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/io/github/aarjavp/aoc/day05/Day05.kt
|
AarjavP
| 433,672,017 | false |
{"Kotlin": 73104}
|
package io.github.aarjavp.aoc.day05
import io.github.aarjavp.aoc.readFromClasspath
infix fun Int.towards(end: Int): IntProgression {
val step = if (this > end) -1 else 1
return IntProgression.fromClosedRange(this, end, step)
}
class Day05 {
data class Point(val x: Int, val y: Int)
data class Line(val start: Point, val end: Point) {
val isHorizontal
get() = start.y == end.y
val isVertical
get() = start.x == end.x
val isDiagonal //45 deg assumed
get() = start.x != end.x && start.y != end.x
fun getPoints(): Sequence<Point> {
return when {
isVertical -> {
(start.y towards end.y).asSequence().map { Point(x = start.x, y = it) }
}
isHorizontal -> {
(start.x towards end.x).asSequence().map { Point(x = it, y = start.y) }
}
//assume 45 deg diagonal
else -> {
val xRange = (start.x towards end.x).asSequence()
val yRange = (start.y towards end.y).asSequence()
return xRange.zip(yRange).map { (x, y) -> Point(x, y) }
}
}
}
}
class SparseIntPlane {
val coveredPoints = mutableMapOf<Point, Int>()
fun add(line: Line) {
val points = line.getPoints()
for (point in points) {
coveredPoints.compute(point) { _, prev -> if (prev == null) 1 else { prev + 1 } }
}
}
}
fun parseLines(input: Sequence<String>): Sequence<Line> {
fun parsePoint(raw: String): Point {
val (x, y) = raw.split(',').map { it.toInt() }
return Point(x, y)
}
return input.map { line ->
val (start, end) = line.split(" -> ").map { parsePoint(it) }
Line(start, end)
}
}
fun part1(input: Sequence<String>): Int {
val plane = SparseIntPlane()
for (line in parseLines(input).filter { it.isVertical || it.isHorizontal }) {
plane.add(line)
}
return plane.coveredPoints.count { it.value > 1 }
}
fun part2(input: Sequence<String>): Int {
val plane = SparseIntPlane()
for (line in parseLines(input)) {
plane.add(line)
}
return plane.coveredPoints.count { it.value > 1 }
}
}
fun main() {
val solution = Day05()
readFromClasspath("Day05.txt").useLines { lines ->
val points = solution.part1(lines)
println(points)
}
readFromClasspath("Day05.txt").useLines { lines ->
val points = solution.part2(lines)
println(points)
}
}
| 0 |
Kotlin
| 0 | 0 |
3f5908fa4991f9b21bb7e3428a359b218fad2a35
| 2,740 |
advent-of-code-2021
|
MIT License
|
src/Day09.kt
|
cagriyildirimR
| 572,811,424 | false |
{"Kotlin": 34697}
|
import kotlin.math.abs
fun day09Part1() {
val input = readInput("Day09")
var Head = Pair(0, 0)
var Tail = Pair(0, 0)
val visited = mutableSetOf<Pair<Int, Int>>()
for (i in input) {
val m = i.split(" ")
var c = m.last().toInt()
val dir = m.first()
while (c > 0) {
Head = headMove(Head, dir)
c--
Tail = tailMove(Head, Tail)
visited.add(Tail)
}
}
println(visited.size)
}
fun headMove(h: Pair<Int, Int>, dir: String): Pair<Int, Int> {
return when (dir) {
"R" -> Pair(h.first + 1, h.second)
"L" -> Pair(h.first - 1, h.second)
"U" -> Pair(h.first, h.second + 1)
else -> Pair(h.first, h.second - 1)
}
}
fun tailMove(h: Pair<Int, Int>, t: Pair<Int, Int>): Pair<Int, Int> {
return when {
(h.first - t.first) > 1 -> if (h.second == t.second) Pair(t.first + 1, t.second) else if (h.second > t.second) Pair(t.first + 1, t.second + 1) else Pair(t.first + 1, t.second - 1) // H(2,1) T(0,0) -> T(1,1)
(h.first - t.first) < -1 -> if (h.second == t.second) Pair(t.first - 1, t.second) else if (h.second > t.second) Pair(t.first - 1, t.second + 1) else Pair(t.first - 1, t.second - 1)
(h.second - t.second) > 1 -> if (h.first == t.first) Pair(t.first, t.second+1) else if (h.first > t.first) Pair(t.first + 1, t.second + 1) else Pair(t.first - 1, t.second + 1)
(h.second - t.second) < -1 -> if (h.first == t.first) Pair(t.first, t.second-1) else if (h.first > t.first) Pair(t.first + 1, t.second - 1) else Pair(t.first - 1, t.second - 1)
else -> t
}
}
fun day09Part2() {
val input = readInput("Day09")
val l = Array<Pair<Int, Int>>(10) { Pair(0,0) }
val visited = mutableSetOf<Pair<Int, Int>>()
for (i in input) {
val m = i.split(" ")
var c = m.last().toInt()
val dir = m.first()
while (c > 0) {
l[0] = headMove(l[0], dir)
c--
for (j in 1..9) {
l[j] = tailMove(l[j-1], l[j])
}
visited.add(l[9])
}
}
println(visited.size)
}
| 0 |
Kotlin
| 0 | 0 |
343efa0fb8ee76b7b2530269bd986e6171d8bb68
| 2,187 |
AoC
|
Apache License 2.0
|
src/aoc2022/Day08.kt
|
NoMoor
| 571,730,615 | false |
{"Kotlin": 101800}
|
package aoc2022
import utils.*
internal class Day08(lines: List<String>) {
private val grid: List<List<Int>>
init {
lines.forEach { println(it) }
grid = lines.map { it.map { it.digitToInt() } }
}
fun part1(): Any {
return grid.indices.sumOf { r ->
grid[r].indices.count { c ->
isVisible(r, c)
}
}
}
private fun isVisible(r: Int, c: Int): Boolean {
val height = grid[r][c]
val row = grid[r]
if (r == 0 || r == row.size -1 || c == 0 || c == grid.size -1) {
return true
}
val left = row.subList(0, c).max()
val right = row.subList(c + 1, grid.size).max()
val up = grid.map { it[c] }.subList(0, r).max()
val down = grid.map { it[c] }.subList(r + 1, grid.size).max()
return height > left || height > right || height > up || height > down
}
private fun treeScore(r: Int, c: Int): Int {
val height = grid[r][c]
val row = grid[r]
if (r == 0 || r == row.size -1 || c == 0 || c == grid.size -1) {
return 0
}
fun getScore(treeLine: List<Int>) : Int {
var count = 0
for (t in treeLine) {
count++
if (t >= height) {
break
}
}
return count
}
val left = getScore(row.subList(0, c).reversed())
val right = getScore(row.subList(c + 1, grid.size))
val up = getScore(grid.map { it[c] }.subList(0, r).reversed())
val down = getScore(grid.map { it[c] }.subList(r + 1, grid.size))
return left * right * up * down
}
fun part2(): Any {
return grid.indices.maxOf { r ->
grid[r].indices.maxOf { c ->
treeScore(r, c)
}
}
}
companion object {
fun doDay() {
val day = "08".toInt()
val todayTest = Day08(readInput(day, 2022, true))
execute(todayTest::part1, "Day[Test] $day: pt 1", 21)
val today = Day08(readInput(day, 2022))
execute(today::part1, "Day $day: pt 1", 1798)
execute(todayTest::part2, "Day[Test] $day: pt 2", 8)
execute(today::part2, "Day $day: pt 2", 259308)
}
}
}
fun main() {
Day08.doDay()
}
| 0 |
Kotlin
| 1 | 2 |
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
| 2,088 |
aoc2022
|
Apache License 2.0
|
src/main/kotlin/Day14.kt
|
todynskyi
| 573,152,718 | false |
{"Kotlin": 47697}
|
import kotlin.math.abs
import kotlin.math.sign
fun main() {
fun part1(input: Set<Point>): Int {
val units = mutableSetOf<Point>()
val start = Point(500, 0)
val last = input.maxOf { it.y }
var current = start
while (current.y != last) {
current = current.move(input, units) ?: start.also { units.add(current) }
}
return units.size
}
fun part2(input: Set<Point>): Int {
val units = mutableSetOf<Point>()
val floor = input.maxOf { it.y } + 2
val start = Point(500, 0)
var current = start
while (start !in units) {
val next = current.move(input, units)
current = when (next == null || next.y == floor) {
true -> start.also { units.add(current) }
else -> next
}
}
return units.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test").toRocks()
check(part1(testInput) == 24)
println(part2(testInput))
val input = readInput("Day14").toRocks()
println(part1(input))
println(part2(input))
}
fun List<String>.toRocks(): Set<Point> = this.flatMap { line ->
line.split(" -> ")
.map { it.split(",") }
.map { (x, y) -> Point(x.toInt(), y.toInt()) }
.zipWithNext()
.flatMap { (first, second) -> first.to(second) }
}.toSet()
private fun Point.move(rocks: Set<Point>, exclusion: Set<Point>) = listOf(
Point(x, y + 1),
Point(x - 1, y + 1),
Point(x + 1, y + 1)
).firstOrNull { it !in rocks && it !in exclusion }
private fun Point.to(other: Point): List<Point> {
val dx = (other.x - x).sign
val dy = (other.y - y).sign
val steps = maxOf(abs(x - other.x), abs(y - other.y))
return (1..steps).scan(this) { last, _ -> Point(last.x + dx, last.y + dy) }
}
| 0 |
Kotlin
| 0 | 0 |
5f9d9037544e0ac4d5f900f57458cc4155488f2a
| 1,904 |
KotlinAdventOfCode2022
|
Apache License 2.0
|
src/year2022/day02/Day02.kt
|
lukaslebo
| 573,423,392 | false |
{"Kotlin": 222221}
|
package year2022.day02
import check
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day02_test")
check(part1(testInput), 15)
check(part2(testInput), 12)
val input = readInput("2022", "Day02")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int = input.sumOf { it.score1 }
private fun part2(input: List<String>): Int = input.sumOf { it.score2 }
private val String.score1: Int
get() = when (this) {
"A X" -> 3 + 1
"B X" -> 0 + 1
"C X" -> 6 + 1
"A Y" -> 6 + 2
"B Y" -> 3 + 2
"C Y" -> 0 + 2
"A Z" -> 0 + 3
"B Z" -> 6 + 3
"C Z" -> 3 + 3
else -> error("$this could not be mapped to a score")
}
private val String.score2: Int
get() = when (this) {
"A X" -> 0 + 3
"B X" -> 0 + 1
"C X" -> 0 + 2
"A Y" -> 3 + 1
"B Y" -> 3 + 2
"C Y" -> 3 + 3
"A Z" -> 6 + 2
"B Z" -> 6 + 3
"C Z" -> 6 + 1
else -> error("$this could not be mapped to a score")
}
/** Alternative Solution:
private fun part1(input: List<String>): Int = input.sumOf {
val (opponent, me) = it.split(' ').map(String::toShape)
me.fight(opponent)
}
private fun part2(input: List<String>): Int = input.sumOf {
val (opponentString, outcomeString) = it.split(' ')
val opponent = opponentString.toShape()
val outcome = outcomeString.toOutcome()
val play = getPlayForOutcome(opponent, outcome)
outcome.score + play.value
}
private fun getPlayForOutcome(opponent: Shape, outcome: Outcome): Shape = when (outcome) {
Outcome.Draw -> opponent
Outcome.Win -> when (opponent) {
Shape.Rock -> Shape.Paper
Shape.Paper -> Shape.Scissors
Shape.Scissors -> Shape.Rock
}
Outcome.Lose -> when (opponent) {
Shape.Rock -> Shape.Scissors
Shape.Paper -> Shape.Rock
Shape.Scissors -> Shape.Paper
}
}
private enum class Shape(
val value: Int,
) : Comparable<Shape> {
Rock(1),
Paper(2),
Scissors(3);
fun fight(opponent: Shape): Int = when {
this == opponent -> Outcome.Draw
(this == Rock && opponent == Scissors) || (this == Paper && opponent == Rock) || (this == Scissors && opponent == Paper) -> Outcome.Win
else -> Outcome.Lose
}.score + value
}
private enum class Outcome(val score: Int) {
Win(6),
Draw(3),
Lose(0),
}
private fun String.toShape() = when (this) {
"A", "X" -> Shape.Rock
"B", "Y" -> Shape.Paper
"C", "Z" -> Shape.Scissors
else -> error("$this can not be mapped into a shape")
}
private fun String.toOutcome() = when (this) {
"X" -> Outcome.Lose
"Y" -> Outcome.Draw
"Z" -> Outcome.Win
else -> error("$this can not be mapped into a outcome")
}
**/
| 0 |
Kotlin
| 0 | 1 |
f3cc3e935bfb49b6e121713dd558e11824b9465b
| 2,919 |
AdventOfCode
|
Apache License 2.0
|
tree_data_structure/WordLadder/kotlin/Solution.kt
|
YaroslavHavrylovych
| 78,222,218 | false |
{"Java": 284373, "Kotlin": 35978, "Shell": 2994}
|
import java.util.LinkedList
/**
* 127. Word Ladder.
* <br/>
* Given two words (beginWord and endWord), and a dictionary's word list,
* find the length of shortest transformation sequence
* from beginWord to endWord, such that:
* Only one letter can be changed at a time.
* Each transformed word must exist in the word list.
* Note:
* Return 0 if there is no such transformation sequence.
* All words have the same length.
* All words contain only lowercase alphabetic characters.
* You may assume no duplicates in the word list.
* You may assume beginWord and endWord
* are non-empty and are not the same.
*
* <br>
* https://leetcode.com/problems/word-ladder/
*/
class Solution {
fun ladderLength(beginWord: String, endWord: String, wordList: List<String>): Int {
//init map for nodes
val graph = HashMap<String, Node>()
graph[beginWord] = Node(beginWord)
wordList.forEach { graph[it] = Node(it) }
val e = graph[endWord] ?: return 0
//create graph
wordList.forEachIndexed { i, w -> addToGraph(graph, wordList, i + 1, w) }
val s = addToGraph(graph, wordList, 0, beginWord)
//search for the shorted (dijkstra)
val stack = LinkedList<Node>()
stack.add(s)
s.w = 1
while (stack.isNotEmpty()) {
val q = stack.removeFirst()
val w = q.w + 1
for (n in q.cons.values) {
if (n == e) return w
if (w < n.w) {
n.w = w
stack.add(n)
}
}
}
return 0
}
private fun addToGraph(graph: HashMap<String, Node> = HashMap(), wordList: List<String>, from: Int, word: String): Node {
val head: Node = graph[word]!!
for (i in from..wordList.indices.last) {
val nextWord = graph[wordList[i]]!!
if (!neighbors(word, wordList[i])) continue
head.cons.put(wordList[i], nextWord)
nextWord.cons.put(word, head)
}
return head
}
private fun neighbors(w1: String, w2: String): Boolean {
var d = false
for (i in w1.indices) {
if (w1[i] != w2[i]) {
if (d) return false
d = true
}
}
return d
}
class Node(val word: String, val cons: HashMap<String, Node> = HashMap(), var w: Int = Int.MAX_VALUE)
}
fun main() {
print("Word Ladder: ")
val sl = Solution()
var a = sl.ladderLength("hit", "cog",
listOf("hot","dot","dog","lot","log","cog")) == 5
a = a && sl.ladderLength("hit", "cog",
listOf("hot","dot","dog","lot","log")) == 0
println(if(a) "SUCCESS" else "FAIL")
}
| 0 |
Java
| 0 | 2 |
cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd
| 2,858 |
codility
|
MIT License
|
src/Day12.kt
|
WilsonSunBritten
| 572,338,927 | false |
{"Kotlin": 40606}
|
fun Position2.neighbors(maxRow: Int, maxColumn: Int, elevationMap: List<List<Int>>): Set<Position2> {
return setOf(
// up a position
Position2((this.row - 1).coerceAtLeast(0), this.column),
// down a position
Position2((this.row + 1).coerceAtMost(maxRow), this.column),
// left
Position2(this.row, (this.column - 1).coerceAtLeast(0)),
// right
Position2(this.row, (this.column + 1).coerceAtMost(maxColumn))
).filter {
elevationMap[it.row][it.column] <= elevationMap[this.row][this.column] + 1
}.toSet()
}
data class Position2(val row: Int, val column: Int)
fun main() {
fun part1(input: List<String>): Int {
// bfs solution... just need a proper navigation scheme...
val elevationMap = input.map { line ->
line.map { character ->
when(character) {
'S' -> 0
'E' -> 25
else -> character.minus('a')
}
}
}
val maxColumn = input.first().length - 1
val maxRow = input.size - 1
val startingPosition = input.indexOfFirst { it.contains('S') }.let { it to input[it].indexOfFirst { it == 'S' }}.let { Position2(it.first, it.second)}
val endingPosition = input.indexOfFirst { it.contains('E') }.let { it to input[it].indexOfFirst { it == 'E' }}.let { Position2(it.first, it.second)}
// map of positions to length to get there
val visited = mutableSetOf(startingPosition)
// to visit also includes distance
val toVisit = startingPosition.neighbors(maxRow, maxColumn, elevationMap).toMutableList().map { it to 1 }.toMutableList()
while(toVisit.isNotEmpty()) {
val (current, distance) = toVisit.removeFirst()
if (current == endingPosition) {
return distance
}
val previouslyVisited = visited.contains(current)
if (previouslyVisited) {
continue
} else {
visited.add(current)
toVisit.addAll(current.neighbors(maxRow, maxColumn, elevationMap).map { it to distance + 1 })
}
}
return -1
}
fun part2(input: List<String>): Int {
// bfs solution... just need a proper navigation scheme...
val elevationMap = input.map { line ->
line.map { character ->
when(character) {
'S' -> 0
'E' -> 25
else -> character.minus('a')
}
}
}
val startingPositions = elevationMap.flatMapIndexed { rowIndex, row ->
row.mapIndexed { index, value -> index to value }.filter { it.second == 0 }.map { rowIndex to it.first }
}.map { Position2(it.first, it.second)}
val endingPosition = input.indexOfFirst { it.contains('E') }.let { it to input[it].indexOfFirst { it == 'E' }}.let { Position2(it.first, it.second)}
return startingPositions.asSequence().minOf {
distanceToEnd(elevationMap, it, endingPosition = endingPosition)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
val input = readInput("Day12")
val p1TestResult = part1(testInput)
println(p1TestResult)
check(p1TestResult == 31)
println(part1(input))
println("Part 2")
val p2TestResult = part2(testInput)
println(p2TestResult)
check(p2TestResult == 29)
println(part2(input))
}
fun distanceToEnd(elevationMap: List<List<Int>>, startingPosition: Position2, endingPosition: Position2): Int {
val maxColumn = elevationMap.first().size - 1
val maxRow = elevationMap.size - 1
// map of positions to length to get there
val visited = mutableSetOf(startingPosition)
// to visit also includes distance
val toVisit = startingPosition.neighbors(maxRow, maxColumn, elevationMap).toMutableList().map { it to 1 }.toMutableList()
while(toVisit.isNotEmpty()) {
val (current, distance) = toVisit.removeFirst()
if (current == endingPosition) {
return distance
}
val previouslyVisited = visited.contains(current)
if (previouslyVisited) {
continue
} else {
visited.add(current)
toVisit.addAll(current.neighbors(maxRow, maxColumn, elevationMap).map { it to distance + 1 })
}
}
return 999999
}
| 0 |
Kotlin
| 0 | 0 |
363252ffd64c6dbdbef7fd847518b642ec47afb8
| 4,530 |
advent-of-code-2022-kotlin
|
Apache License 2.0
|
src/main/kotlin/aoc2023/Day05.kt
|
lukellmann
| 574,273,843 | false |
{"Kotlin": 175166}
|
package aoc2023
import AoCDay
import kotlin.math.max
import kotlin.math.min
// https://adventofcode.com/2023/day/5
object Day05 : AoCDay<Long>(
title = "If You Give A Seed A Fertilizer",
part1ExampleAnswer = 35,
part1Answer = 218513636,
part2ExampleAnswer = 46,
part2Answer = 81956384,
) {
private class Mapping(val source: LongRange, val destinationShift: Long)
private data class Almanac(val seeds: List<Long>, val maps: List<List<Mapping>>)
private fun parseAlmanac(input: String): Almanac {
val sections = input.split("\n\n")
val seeds = sections.first().substringAfter("seeds: ").split(' ').map(String::toLong)
val maps = sections.drop(1).map { map ->
map.lines().drop(1).map { mapping ->
val (destStart, srcStart, length) = mapping.split(' ', limit = 3).map(String::toLong)
Mapping(source = srcStart..<(srcStart + length), destinationShift = destStart - srcStart)
}.sortedBy { it.source.first } // applyMap expects maps to be sorted by their source range start
}
return Almanac(seeds, maps)
}
private infix fun LongRange.intersect(other: LongRange) = max(this.first, other.first)..min(this.last, other.last)
private fun LongRange.shift(amount: Long) = (first + amount)..(last + amount)
private fun LongRange.splitAround(other: LongRange) = Pair(this.first..<other.first, (other.last + 1)..this.last)
private operator fun List<LongRange>.plus(element: LongRange) = plusElement(element)
private fun List<LongRange>.normalize() = filterNot(LongRange::isEmpty)
.sortedBy(LongRange::first)
.fold(initial = emptyList<LongRange>()) { acc, cur ->
val prev = acc.lastOrNull()
when {
prev == null -> listOf(cur)
prev.last >= cur.first - 1 -> acc.dropLast(1) + (prev.first..max(prev.last, cur.last))
else -> acc + cur
}
}
private fun List<LongRange>.applyMap(map: List<Mapping>) = flatMap { range ->
val (acc, pending) = map.fold(
initial = Pair(emptyList<LongRange>(), range)
) { (acc, pending), mapping -> // mappings have to be sorted by their source range start
val mappedNumbers = pending intersect mapping.source
if (mappedNumbers.isEmpty()) Pair(acc, pending) else {
val (smaller, bigger) = pending.splitAround(mappedNumbers)
Pair(acc + smaller + mappedNumbers.shift(mapping.destinationShift), bigger)
}
}
acc + pending
}.normalize()
private fun findLowestLocationNumber(seedRanges: List<LongRange>, maps: List<List<Mapping>>) =
maps.fold(initial = seedRanges.normalize()) { acc, map -> acc.applyMap(map) }.first().first
override fun part1(input: String): Long {
val (seeds, maps) = parseAlmanac(input)
val seedRanges = seeds.map { it..it } // just part2 with singleton ranges
return findLowestLocationNumber(seedRanges, maps)
}
override fun part2(input: String): Long {
val (seeds, maps) = parseAlmanac(input)
val seedRanges = seeds.chunked(2).map { (start, length) -> start..<(start + length) }
return findLowestLocationNumber(seedRanges, maps)
}
}
| 0 |
Kotlin
| 0 | 1 |
344c3d97896575393022c17e216afe86685a9344
| 3,318 |
advent-of-code-kotlin
|
MIT License
|
src/day10/Day10.kt
|
maxmil
| 578,287,889 | false |
{"Kotlin": 32792}
|
package day10
import println
import readInput
val brackets = mapOf(Pair('(', ')'), Pair('[', ']'), Pair('{', '}'), Pair('<', '>'))
val scores: Map<Char, Int> = mapOf(Pair(')', 3), Pair(']', 57), Pair('}', 1197), Pair('>', 25137))
val autoCompleteScore: Map<Char, Int> = scores.mapValues { scores.keys.indexOf(it.key) + 1 }
fun part1(input: List<String>) = input.sumOf { line ->
val stack = ArrayDeque<Char>(listOf())
for (c in line) {
if (stack.isNotEmpty() && brackets[stack.last()] == c) stack.removeLast()
else if (brackets.values.contains(c)) return@sumOf scores[c]!!
else stack.add(c)
}
0
}
fun part2(input: List<String>) = input.map<String, Long> { line ->
val stack = ArrayDeque<Char>(listOf())
for (c in line) {
if (stack.isNotEmpty() && brackets[stack.last()] == c) stack.removeLast()
else if (brackets.values.contains(c)) return@map 0L
else stack.add(c)
}
stack.foldRight(0) { c, acc -> (acc * 5L) + autoCompleteScore[brackets[c]]!! }
}.filter { it != 0L }.sorted().let { it[(it.size - 1) / 2] }
fun main() {
val testInput = readInput("day10/input_test")
check(part1(testInput) == 26397)
check(part2(testInput) == 288957L)
val input = readInput("day10/input")
part1(input).println()
part2(input).println()
}
| 0 |
Kotlin
| 0 | 0 |
246353788b1259ba11321d2b8079c044af2e211a
| 1,331 |
advent-of-code-2021
|
Apache License 2.0
|
src/Day13.kt
|
Kvest
| 573,621,595 | false |
{"Kotlin": 87988}
|
fun main() {
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
return input.windowed(size = 2, step = 3)
.map { list -> list.map { it.parseList() } }
.mapIndexed { index, (first, second) ->
if (checkOrder(first.values, second.values) == Order.RIGHT) index + 1 else 0
}
.sum()
}
private fun part2(input: List<String>): Int {
val dividerPackets = listOf(
"[[2]]".parseList(),
"[[6]]".parseList(),
)
val originalPackets = input
.filter { it.isNotEmpty() }
.map(String::parseList)
return (originalPackets + dividerPackets)
.sortedWith(ListValueComparator)
.mapIndexed { index, listValue ->
if (listValue in dividerPackets) index + 1 else 1
}
.reduce { acc, value -> acc * value }
}
private object ListValueComparator : Comparator<ListValue> {
override fun compare(left: ListValue, right: ListValue): Int =
checkOrder(left.values, right.values).value
}
private fun String.parseList(
fromIndex: Int = 0,
finishedIndex: IntArray = intArrayOf(fromIndex)
): ListValue {
check(this[fromIndex] == '[') { "This is not start of the list" }
var current = fromIndex + 1
val result = mutableListOf<Value>()
while (current <= this.lastIndex) {
when (this[current]) {
',' -> ++current
']' -> break
'[' -> {
val nested = this.parseList(current, finishedIndex)
result.add(nested)
current = finishedIndex[0] + 1
}
else -> {
val to = this.indexOfAny(chars = charArrayOf(',', ']'), startIndex = current)
val intValue = this.substring(current, to).toInt()
result.add(IntValue(intValue))
current = if (this[to] == ',') {
to + 1
} else {
to
}
}
}
}
finishedIndex[0] = current
return ListValue(result)
}
private fun checkOrder(left: List<Value>, right: List<Value>): Order {
for (i in left.indices) {
if (i > right.lastIndex) {
return Order.WRONG
}
val leftItem = left[i]
val rightItem = right[i]
if (leftItem is IntValue && rightItem is IntValue) {
if (leftItem.value < rightItem.value) return Order.RIGHT
if (leftItem.value > rightItem.value) return Order.WRONG
} else {
val result = checkOrder(
left = if (leftItem is ListValue) leftItem.values else listOf(leftItem),
right = if (rightItem is ListValue) rightItem.values else listOf(rightItem)
)
if (result != Order.UNKNOWN) return result
}
}
return if (left.size < right.size) Order.RIGHT else Order.UNKNOWN
}
private sealed interface Value
private class IntValue(val value: Int) : Value
private class ListValue(val values: List<Value>) : Value
private enum class Order(val value: Int) {
UNKNOWN(0), RIGHT(-1), WRONG(1)
}
| 0 |
Kotlin
| 0 | 0 |
6409e65c452edd9dd20145766d1e0ea6f07b569a
| 3,299 |
AOC2022
|
Apache License 2.0
|
y2021/src/main/kotlin/adventofcode/y2021/Day14.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2021
import adventofcode.io.AdventSolution
object Day14 : AdventSolution(2021, 14, "Extended Polymerization") {
override fun solvePartOne(input: String): Int {
val (initial, rules) = parse(input)
fun step(str: String) = str.windowed(2).joinToString("") { s -> s[0] + rules[s].orEmpty() } + str.last()
val freq = generateSequence(initial, ::step).elementAt(10).groupingBy { it }.eachCount()
return freq.maxOf { it.value } - freq.minOf { it.value }
}
override fun solvePartTwo(input: String): Long {
val (a, rules) = parse(input)
val initial = a.windowed(2).groupingBy { it }.eachCount().mapValues { it.value.toLong() }
fun next(current: Map<String, Long>) =
current.flatMap { (p, c) ->
(rules[p])?.let { listOf((p[0] + it) to c, (it + p[1]) to c) } ?: listOf(p to c)
}
.groupingBy { it.first }
.fold(0L) { a, v -> a + v.second }
val resultPairs = generateSequence(initial, ::next).elementAt(40)
val freq = resultPairs.asSequence()
.groupingBy { it.key[0] }
.fold(0L) { s, v -> s + v.value }
.toMutableMap()
freq[a.last()] = freq.getValue(a.last()) + 1
return freq.maxOf { it.value } - freq.minOf { it.value }
}
private fun parse(input: String): Pair<String, Map<String, String>> {
val (a, b) = input.split("\n\n")
val rules = b.lineSequence().map { it.split(" -> ") }
.associate { it[0] to it[1] }
return a to rules
}
}
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 1,610 |
advent-of-code
|
MIT License
|
src/Day08.kt
|
Fedannie
| 572,872,414 | false |
{"Kotlin": 64631}
|
fun main() {
fun parseInput(input: List<String>): List<List<Int>> = input.map { it.toCharArray().toList().map { it.toString().toInt() } }
fun List<List<Int>>.up(i: Int, j: Int) = map { it[j] }.subList(0, i)
fun List<List<Int>>.down(i: Int, j: Int) = map { it[j] }.subList(i + 1, size)
fun List<List<Int>>.left(i: Int, j: Int) = this[i].subList(0, j)
fun List<List<Int>>.right(i: Int, j: Int) = this[i].subList(j + 1, this[i].size)
fun countNumber(i: Int, j: Int, field: List<List<Int>>): Int {
fun criterion(value: Int): Boolean = value >= field[i][j]
val left = j - 0.coerceAtLeast(field.left(i, j).indexOfLast(::criterion))
var right = field.right(i, j).indexOfFirst(::criterion) + 1
if (right == 0) right = field[i].size - j - 1
val up = i - 0.coerceAtLeast(field.up(i, j).indexOfLast(::criterion))
var down = field.down(i, j).indexOfFirst(::criterion) + 1
if (down == 0) down = field.size - i - 1
return left * right * up * down
}
fun isVisible(i: Int, j: Int, field: List<List<Int>>): Boolean {
fun criterion(value: Int): Boolean = value < field[i][j]
return field.up(i, j).all(::criterion) || field.down(i, j).all(::criterion) ||
field.left(i, j).all(::criterion) || field.right(i, j).all(::criterion)
}
fun part1(input: List<String>): Int {
val field = parseInput(input)
return field.mapIndexed { i, row -> row.filterIndexed { j, _ -> isVisible(i, j, field) }.count() }.sum()
}
fun part2(input: List<String>): Int {
val field = parseInput(input)
return field.mapIndexed { i, row -> List(row.size) { j -> countNumber(i, j, field) } }.maxOf { it.max() }
}
val testInput = readInputLines("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInputLines(8)
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
| 1,853 |
Advent-of-Code-2022-in-Kotlin
|
Apache License 2.0
|
src/Day14.kt
|
RusticFlare
| 575,453,997 | false |
{"Kotlin": 4655}
|
fun main() {
fun part1(input: List<String>): Long {
return input.size.toLong()
}
fun part2(input: String): Long {
val (initial, transforms) = input.split("\n\n")
val mappings = transforms.lines().associate { (it[0] to it[1]) to ((it[0] to it[6]) to (it[6] to it[1])) }
fun Map<Pair<Char, Char>, Long>.nextState(): Map<Pair<Char, Char>, Long> {
val result = mutableMapOf<Pair<Char, Char>, Long>()
forEach { (key, count) ->
val (a, b) = mappings.getValue(key)
result.compute(a) { _, oldCount -> oldCount?.plus(count) ?: count }
result.compute(b) { _, oldCount -> oldCount?.plus(count) ?: count }
}
return result
}
var state = initial.zipWithNext().groupingBy { it }.eachCount().mapValues { (_, count) -> count.toLong() }
repeat(40) { state = state.nextState() }
val counts = state.asSequence()
.groupingBy { (key) -> key.second }
.aggregate { _, oldCount: Long?, (_, count), _ -> oldCount?.plus(count) ?: count }
.toMutableMap()
.apply { compute(initial.first()) { _, oldCount -> oldCount?.plus(1) ?: 1 } }
.values
return counts.max() - counts.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readText("Day14_test")
// check(part1(testInput) == 1)
check(part2(testInput) == 2188189693529)
val input = readText("Day14")
// println(part1(input))
check(part2(input) == 2875665202438)
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
6ad85c80f771be683517fab804e9a933a90d5b41
| 1,629 |
advent-of-code-kotlin-2021
|
Apache License 2.0
|
y2015/src/main/kotlin/adventofcode/y2015/Day21.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2015
import adventofcode.io.AdventSolution
object Day21 : AdventSolution(2015, 21, "RPG Simulator 20XX") {
override fun solvePartOne(input: String): Int {
val bossMonster = parseInput(input)
return itemSets()
.first { equipment -> defeats(Character(100, equipment.damage, equipment.armor), bossMonster) }
.cost
}
override fun solvePartTwo(input: String): Int {
val bossMonster = parseInput(input)
return itemSets()
.last { equipment -> !defeats(Character(100, equipment.damage, equipment.armor), bossMonster) }
.cost
}
private fun parseInput(input: String) = input.lines()
.map { it.substringAfter(": ").toInt() }
.let { (hp, dmg, ar) -> Character(hp, dmg, ar) }
}
private data class Character(val hp: Int, val dmg: Int, val ar: Int)
private fun defeats(player: Character, monster: Character): Boolean {
val playerDamage = (player.dmg - monster.ar).coerceAtLeast(1)
val turnsToWin = (monster.hp + playerDamage - 1) / playerDamage
val monsterDamage = (monster.dmg - player.ar).coerceAtLeast(1)
val turnsToLose = (player.hp + monsterDamage - 1) / monsterDamage
return turnsToWin <= turnsToLose
}
private fun itemSets(): List<Item> = Item.rings
.flatMapIndexed { index: Int, item: Item ->
Item.rings.drop(index).map { item.combine(it) }
}
.flatMap { set -> Item.weapons.map(set::combine) }
.flatMap { set -> Item.armor.map(set::combine) }
.sortedBy(Item::cost)
//required
private data class Item(val cost: Int, val damage: Int, val armor: Int) {
fun combine(o: Item) = Item(cost + o.cost, damage + o.damage, armor + o.armor)
companion object {
val empty = Item(0, 0, 0)
val weapons = listOf(
Item(8, 4, 0),
Item(10, 5, 0),
Item(25, 6, 0),
Item(40, 7, 0),
Item(74, 8, 0)
)
val armor = listOf(
empty,
Item(13, 0, 1),
Item(31, 0, 2),
Item(53, 0, 3),
Item(75, 0, 4),
Item(102, 0, 5)
)
val rings = listOf(
empty,
empty,
Item(25, 1, 0),
Item(50, 2, 0),
Item(100, 3, 0),
Item(20, 0, 1),
Item(40, 0, 2),
Item(80, 0, 3)
)
}
}
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 2,416 |
advent-of-code
|
MIT License
|
src/Day04.kt
|
dustinlewis
| 572,792,391 | false |
{"Kotlin": 29162}
|
fun main() {
fun part1_original(input: List<String>): Int {
val assignments = input.map { assignmentString ->
val (firstStart, firstEnd, secondStart, secondEnd) =
assignmentString.split(*"-,".toCharArray()).map { it.toInt() }
listOf(
Pair(firstStart, firstEnd),
Pair(secondStart, secondEnd),
)
}
return assignments.fold(0) {
acc, (a1, a2) ->
acc + if((a1.first <= a2.first && a1.second >= a2.second) ||
(a2.first <= a1.first && a2.second >= a1.second)) 1 else 0
}
}
fun part1(input: List<String>): Int {
return input
.map { assignments -> assignments.split('-', ',').map { it.toInt() } }
.fold(0) { acc, (a1Start, a1End, a2Start, a2End) ->
acc + if(doPairsFullyOverlap(Pair(a1Start, a1End), Pair(a2Start, a2End))) 1 else 0
}
}
fun part2(input: List<String>): Int {
return input
.map { assignments -> assignments.split('-', ',').map { it.toInt() } }
.fold(0) { acc, (a1Start, a1End, a2Start, a2End) ->
acc + if(doPairsOverlap(Pair(a1Start, a1End), Pair(a2Start, a2End))) 1 else 0
}
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun doPairsFullyOverlap(p1: Pair<Int, Int>, p2: Pair<Int, Int>): Boolean =
(p1.first <= p2.first && p1.second >= p2.second) || (p2.first <= p1.first && p2.second >= p1.second)
fun doPairsOverlap(p1: Pair<Int, Int>, p2: Pair<Int, Int>): Boolean =
(p1.second >= p2.first && p1.second <= p2.second) || (p2.second >= p1.first && p2.second <= p1.second)
| 0 |
Kotlin
| 0 | 0 |
c8d1c9f374c2013c49b449f41c7ee60c64ef6cff
| 1,733 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/year2023/day19/Day.kt
|
tiagoabrito
| 573,609,974 | false |
{"Kotlin": 73752}
|
package year2023.day19
import java.util.LinkedList
import java.util.Queue
import year2023.solveIt
fun main() {
val day = "19"
val expectedTest1 = 19114L
val expectedTest2 = 167409079868000L
fun toRuleFunction(line: String): Pair<String, List<(Map<Char, Long>) -> String?>> {
val (name, rules) = line.split("{", "}")
val lineRules: List<(Map<Char, Long>) -> String?> = rules.split(",").map { rule ->
if (rule.contains(":")) {
val (condition, destination) = rule.split(":")
val (prop, value) = condition.split(">", "<")
if (condition.contains(">")) {
{ l -> if (l[prop[0]]!! > value.toLong()) destination else null }
} else {
{ l -> if (l[prop[0]]!! < value.toLong()) destination else null }
}
} else { _ -> rule }
}
return name to lineRules
}
fun part1(input: List<String>): Long {
val (rules, parts) = input.joinToString("\n").split("\n\n").map { it.split("\n") }
val rulesMap = rules.associate { toRuleFunction(it) }
val partsMap = parts.map {
it.removeSurrounding("{", "}").split(",").map { c ->
val (letter, value) = c.split("=")
letter[0] to value.toLong()
}.toMap()
}
return partsMap.filter { part ->
var curr = "in"
while (curr != "A" && curr != "R") {
val firstNotNullOf = rulesMap[curr]!!.firstNotNullOf { it.invoke(part) }
curr = firstNotNullOf
}
curr == "A"
}.sumOf { it['x']!! + it['m']!! + it['a']!! + it['s']!! }
}
fun getSet(): Set<Int> = (1..4000).iterator().asSequence().toSet()
fun toRuleFunction2(line: String): Pair<String, List<Pair<Pair<Char, IntRange>, String>>> {
val (name, rules) = line.split("{", "}")
val lineRules = rules.split(",").map { rule ->
if (rule.contains(":")) {
val (condition, destination) = rule.split(":")
val (prop, value) = condition.split(">", "<")
if (condition.contains(">")) {
prop[0] to (value.toInt() + 1..4000) to destination
} else {
prop[0] to (1 until value.toInt()) to destination
}
} else {
'1' to (1..4000) to rule
}
}
return name to lineRules
}
fun part2(input: List<String>): Long {
val (rules, _) = input.joinToString("\n").split("\n\n").map { it.split("\n") }
val rulesMap = rules.associate { toRuleFunction2(it) }
val queue: Queue<Pair<String, Map<Char, Set<Int>>>> = LinkedList()
queue.add("in" to mapOf('a' to getSet(), 'x' to getSet(), 'm' to getSet(), 's' to getSet()))
var valid = 0L
while (queue.isNotEmpty()) {
val (s, map) = queue.remove()
when (s) {
"A" -> valid += map.values.map { it.size }.fold(1L) { acc, i -> acc * i }
"S" -> continue
else -> {
var current = map
rulesMap[s]?.forEach { rule ->
val r = rule.first.first
if (r == '1') {
queue.add(rule.second to current)
} else {
val groupBy = current[r]!!.partition { rule.first.second.contains(it) }
queue.add(rule.second to current + (r to groupBy.first.toSet()))
current = current + (r to groupBy.second.toSet())
}
}
}
}
}
return valid
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test")
}
| 0 |
Kotlin
| 0 | 0 |
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
| 3,939 |
adventOfCode
|
Apache License 2.0
|
src/Day15.kt
|
mjossdev
| 574,439,750 | false |
{"Kotlin": 81859}
|
import kotlin.math.abs
fun main() {
data class Coordinate(val x: Int, val y: Int)
fun Coordinate.distanceTo(other: Coordinate): Int = abs(x - other.x) + abs(y - other.y)
data class Reading(val sensorPosition: Coordinate, val beaconPosition: Coordinate) {
val distance = sensorPosition.distanceTo(beaconPosition)
}
val readingPattern = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""")
fun readPositions(input: List<String>): List<Reading> = input.map { line ->
val (sensorX, sensorY, beaconX, beaconY) = readingPattern.matchEntire(line)!!
.groupValues
.drop(1)
.map { it.toInt() }
Reading(Coordinate(sensorX, sensorY), Coordinate(beaconX, beaconY))
}
fun part1(input: List<String>, targetY: Int): Int {
val readings = readPositions(input)
val beaconsInTargetRow = readings.asSequence()
.map { it.beaconPosition }
.filter { it.y == targetY }
.map { it.x }
.toSet()
return readings
.flatMap { (beacon, sensor) ->
val distance = beacon.distanceTo(sensor)
val yDistanceToTarget = abs(beacon.y - targetY)
val possibleXDistance = distance - yDistanceToTarget
beacon.x - possibleXDistance..beacon.x + possibleXDistance
}
.subtract(beaconsInTargetRow)
.size
}
fun part2(input: List<String>, maxCoordinate: Int): Long {
val readings = readPositions(input).sortedByDescending { it.distance }
for (x in 0..maxCoordinate) {
var y = 0
while (y <= maxCoordinate) {
val c = Coordinate(x, y)
val reading = readings.firstOrNull { c.distanceTo(it.sensorPosition) <= it.distance }
if (reading == null) {
return x.toLong() * 4_000_000 + y
}
val maxYDistance = reading.distance - abs(c.x - reading.sensorPosition.x)
y = reading.sensorPosition.y + maxYDistance + 1
}
}
error("not found")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
val input = readInput("Day15")
println(part1(input, 2_000_000))
println(part2(input, 4_000_000))
}
| 0 |
Kotlin
| 0 | 0 |
afbcec6a05b8df34ebd8543ac04394baa10216f0
| 2,497 |
advent-of-code-22
|
Apache License 2.0
|
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day11.kt
|
MichalChomo
| 572,214,942 | false |
{"Kotlin": 56758}
|
package eu.michalchomo.adventofcode.year2022
data class Monkey(
private val items: MutableList<Long>,
private val operation: (Long) -> Long,
private val modulus: Long,
private val monkeyIfTrue: Int,
private val monkeyIfFalse: Int
) {
var itemsInspected: Long = 0
fun turn(monkeys: List<Monkey>, secondOperation: (Long) -> Long) {
items.map(operation)
.map(secondOperation)
.forEach { worryLevel ->
itemsInspected++
monkeys[test(worryLevel)].items.add(worryLevel)
}
items.clear()
}
private fun test(worryLevel: Long): Int = if (worryLevel % modulus == 0L) monkeyIfTrue else monkeyIfFalse
}
fun main() {
fun List<String>.toLongFunction(): (Long, Long) -> Long =
if (this[1] == "*") { a, b -> a.times(b) }
else { a, b -> a.plus(b) }
fun List<String>.toOperation(): (Long) -> Long =
{ a ->
toLongFunction()(
a,
if (this[2] != "old") this[2].toLong() else a
)
}
fun String.lowestCommonMultipleOfModulo(): Long = split("\n")
.asSequence()
.filter { it.contains("divisible by") }
.map { it.split(" ").last().toLong() }
.reduce(Long::times)
fun String.toMonkeys(): List<Monkey> = split("\n\n").map {
it.split("\n")
.filter { it.isNotEmpty() }
.let { monkeyString ->
Monkey(
monkeyString[1].substringAfter(":").split(",").map { it.trim().toLong() }.toMutableList(),
monkeyString[2].substringAfter("=").trim().split(" ").let { it.toOperation() },
monkeyString[3].substringAfterLast(" ").toLong(),
monkeyString[4].substringAfterLast(" ").toInt(),
monkeyString[5].substringAfterLast(" ").toInt()
)
}
}
fun List<Monkey>.round(secondOperation: (Long) -> Long): List<Monkey> =
apply { forEach { it.turn(this, secondOperation) } }
fun List<Monkey>.monkeyBusiness(): Long = map { it.itemsInspected }
.sortedDescending()
.take(2)
.reduce(Long::times)
fun part1(input: String): Long = input.toMonkeys()
.apply { repeat(20) { round { it / 3 } } }
.monkeyBusiness()
fun part2(input: String): Long = input.toMonkeys()
.apply {
input.lowestCommonMultipleOfModulo().let { lcm ->
repeat(10000) {
round { it.mod(lcm) }
}
}
}
.monkeyBusiness()
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
a95d478aee72034321fdf37930722c23b246dd6b
| 2,847 |
advent-of-code
|
Apache License 2.0
|
src/Day02.kt
|
cypressious
| 572,898,685 | false |
{"Kotlin": 77610}
|
enum class Rps(val score: Int) {
Rock(1), Paper(2), Scissors(3)
}
fun main() {
val theirRps = mapOf("A" to Rps.Rock, "B" to Rps.Paper, "C" to Rps.Scissors)
val mineRps = mapOf("X" to Rps.Rock, "Y" to Rps.Paper, "Z" to Rps.Scissors)
val dominators =
mapOf(Rps.Rock to Rps.Scissors, Rps.Paper to Rps.Rock, Rps.Scissors to Rps.Paper)
fun calculateScore(their: Rps, mine: Rps): Int {
val score = when (their) {
mine -> 3
dominators[mine] -> 6
else -> 0
}
return score + mine.score
}
fun part1(input: List<String>): Int {
return input.sumOf {
val parts = it.split(' ')
val their = theirRps[parts[0]]!!
val mine = mineRps[parts[1]]!!
calculateScore(their, mine)
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val parts = it.split(' ')
val their = theirRps[parts[0]]!!
val outcome = parts[1]
val mine = when (outcome) {
"X" -> dominators[their]!!
"Y" -> their
else -> dominators.entries.first { it.value == their }.key
}
calculateScore(their, mine)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
| 1,554 |
AdventOfCode2022
|
Apache License 2.0
|
src/Day11.kt
|
floblaf
| 572,892,347 | false |
{"Kotlin": 28107}
|
fun main() {
data class Test(val division: Long, val targetSuccess: Int, val targetFail: Int) {
fun run(x: Long): Int {
return if (x % division == 0L) targetSuccess else targetFail
}
}
data class Monkey(
val items: MutableList<Long> = mutableListOf(),
val operation: (old: Long) -> Long,
val test: Test,
var inspections: Long = 0L
)
fun playRounds(monkeys: List<Monkey>, round: Int, worryReduce: (Long) -> Long): Long {
repeat(round) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val itemValue = monkey.items.removeFirst()
val newItemValue = worryReduce(monkey.operation(itemValue))
monkeys[monkey.test.run(newItemValue)].items.add(newItemValue)
monkey.inspections++
}
}
}
return monkeys.map { it.inspections }.sortedDescending().let { (first, second) -> first * second }
}
fun part1(monkeys: List<Monkey>): Long {
return playRounds(monkeys, 20) { it / 3 }
}
fun part2(monkeys: List<Monkey>): Long {
val div = monkeys.map { it.test.division }.reduce(Long::times)
return playRounds(monkeys, 10_000) { it % div }
}
fun parseMonkeys(input: List<String>): List<Monkey> {
return input
.filter { it.isNotBlank() }
.windowed(size = 6, step = 6)
.map { lines ->
Monkey(
items = lines[1].substringAfter(": ").split(", ").map { it.toLong() }.toMutableList(),
{ x ->
lines[2].substringAfter("= old ").split(" ").let { (operator, v) ->
val right = if (v == "old") x else v.toLong()
when (operator) {
"*" -> x * right
"+" -> x + right
else -> throw IllegalStateException()
}
}
},
Test(
division = lines[3].split(" ").last().toLong(),
targetSuccess = lines[4].split(" ").last().toInt(),
targetFail = lines[5].split(" ").last().toInt(),
)
)
}
}
val input = readInput("Day11")
println(part1(parseMonkeys(input)))
println(part2(parseMonkeys(input)))
}
| 0 |
Kotlin
| 0 | 0 |
a541b14e8cb401390ebdf575a057e19c6caa7c2a
| 2,558 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/day13/Day13.kt
|
qnox
| 575,581,183 | false |
{"Kotlin": 66677}
|
package day13
import readInput
fun main() {
fun parseList(str: String, p: Int): Pair<List<Any>, Int> {
val result = mutableListOf<Any>()
var cur = p
check(str[cur] == '[')
cur += 1
while (str[cur] != ']') {
if (str[cur] == ',') {
cur += 1
}
if (str[cur] == '[') {
val (list, ret) = parseList(str, cur)
cur = ret
result.add(list)
} else {
val from = cur
while (str[cur].isDigit()) {
cur += 1
}
result.add(str.substring(from, cur).toInt())
}
}
cur += 1
return result to cur
}
fun parseList(str: String): List<Any> {
return parseList(str, 0).first
}
fun inorder(v1: Any, v2: Any): Int {
if (v1 is Int && v2 is Int) {
print("($v1 $v2)")
return v1 - v2
} else {
val l1 = if (v1 is List<*>) v1 else listOf(v1)
val l2 = if (v2 is List<*>) v2 else listOf(v2)
for (i in 0 until minOf(l1.size, l2.size)) {
val r = inorder(l1[i]!!, l2[i]!!)
if (r != 0) {
return r
}
}
return l1.size - l2.size
}
}
fun inorder(str1: String, str2: String): Boolean {
val v1 = parseList(str1)
val v2 = parseList(str2)
return inorder(v1, v2) < 1
}
fun part1(input: List<String>): Int {
return input.chunked(3)
.mapIndexed { i, (v1, v2, _) ->
i + 1 to inorder(v1, v2)
}
.filter { it.second }
.sumOf { it.first }
}
fun part2(input: List<String>): Int {
val sorted = (input.filter { it.isNotEmpty() } + listOf("[[2]]", "[[6]]"))
.sortedWith { str1, str2 ->
val v1 = parseList(str1)
val v2 = parseList(str2)
inorder(v1, v2)
}
val i1 = sorted.indexOf("[[2]]")
val i2 = sorted.indexOf("[[6]]")
return (i1 + 1) * (i2 + 1)
}
val testInput = readInput("day13", "test")
val input = readInput("day13", "input")
check(part1(testInput) == 13)
println(part1(input))
check(part2(testInput) == 140)
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
727ca335d32000c3de2b750d23248a1364ba03e4
| 2,414 |
aoc2022
|
Apache License 2.0
|
src/Day11.kt
|
Fedannie
| 572,872,414 | false |
{"Kotlin": 64631}
|
fun main() {
class Algorithm(val divisibleBy: Int, val ifTrue: Int, val ifFalse: Int) {
fun next(x: Long): Int = if (x % divisibleBy == 0L) ifTrue else ifFalse
}
class Monkey(items: Collection<Long>, val operation: (Long) -> Long, val algorithm: Algorithm) {
val items = MutableList(0) { 0L }
var inspected = 0L
private set
var postprocess: (Long) -> Long = { x -> x }
init {
this.items.addAll(items)
}
fun processItems(monkeys: List<Monkey>) {
for (item in items) {
val current = postprocess(operation(item))
monkeys[algorithm.next(current)].items.add(current)
inspected++
}
items.clear()
}
}
fun parseOperation(operationStr: String): (Long) -> Long {
if (operationStr == "old * old") return { x -> x * x }
if (operationStr == "old + old") return { x -> 2 * x }
val words = operationStr.split(' ')
val right = words[2].toLong()
when (words[1]) {
"*" -> return { x -> x * right }
else -> return { x -> x + right }
}
}
fun parseInput(input: String): List<Monkey> {
return input.split("\n\n").map {
it.split("\n").subList(1, 6)
}.map {
val items = it[0].substring(" Starting items: ".length).split(", ").map { it.toLong() }
val operation = parseOperation(it[1].substring(" Operation: new = ".length))
val algorithm = Algorithm(it[2].lastWord().toInt(), it[3].lastWord().toInt(), it[4].lastWord().toInt())
Monkey(items, operation, algorithm)
}
}
fun monkeyBusiness(monkeys: List<Monkey>): Long =
monkeys.map { it.inspected }.sortedDescending().subList(0, 2).reduceRight { a, b -> a * b }
fun part1(input: String): Long {
val monkeys = parseInput(input)
monkeys.forEach { it.postprocess = { x -> x / 3 } }
repeat (20) {
for (monkey in monkeys) {
monkey.processItems(monkeys)
}
}
return monkeyBusiness(monkeys)
}
fun part2(input: String): Long {
val monkeys = parseInput(input)
val bigNumber = monkeys.fold(1) { current, monkey -> current * monkey.algorithm.divisibleBy }
monkeys.forEach { it.postprocess = { x -> x % bigNumber } }
repeat (10000) {
for (monkey in monkeys) {
monkey.processItems(monkeys)
}
}
return monkeyBusiness(monkeys)
}
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInput(11)
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
| 2,521 |
Advent-of-Code-2022-in-Kotlin
|
Apache License 2.0
|
src/day23/Day23.kt
|
davidcurrie
| 579,636,994 | false |
{"Kotlin": 52697}
|
package day23
import java.io.File
import java.util.*
import kotlin.math.max
import kotlin.math.min
fun main() {
var elves = File("src/day23/input.txt").readLines().mapIndexed { row, line ->
line.toList().mapIndexed { column, char ->
if (char == '#') Pair(column, row) else null
}.filterNotNull()
}.flatten()
val directions = listOf(
listOf(Pair(0, -1), Pair(-1, -1), Pair(1, -1)),
listOf(Pair(0, 1), Pair(-1, 1), Pair(1, 1)),
listOf(Pair(-1, 0), Pair(-1, -1), Pair(-1, 1)),
listOf(Pair(1, 0), Pair(1, -1), Pair(1, 1))
)
val deltas = directions.flatten().toSet()
var round = 1
while(true) {
val proposedMoves = elves.map { elf ->
val neighbouringElves = deltas.map { delta -> elf + delta }.filter { location -> location in elves }
if (neighbouringElves.isEmpty()) {
elf
} else {
val direction = directions.indices.map { i -> directions[(i + round - 1).mod(directions.size)] }
.firstOrNull { direction -> direction.none { d -> (elf + d) in neighbouringElves } }
elf + (direction?.first() ?: Pair(0, 0))
}
}
val frequencies = proposedMoves.groupingBy { it }.eachCount()
val newElves = elves.indices.map { i -> if (frequencies[proposedMoves[i]] == 1) proposedMoves[i] else elves[i] }
if (elves == newElves) {
println(round)
break
}
elves = newElves
if (round == 10) {
val (topLeft, bottomRight) = rectangle(elves)
val area = (1 + bottomRight.first - topLeft.first) * (1 + bottomRight.second - topLeft.second)
val empty = area - elves.size
println(empty)
}
round++
}
}
fun printElves(elves: List<Pair<Int, Int>>) {
val (topLeft, bottomRight) = rectangle(elves)
for (row in topLeft.second .. bottomRight.second) {
for (column in topLeft.first .. bottomRight.first) {
print(if (Pair(column, row) in elves) '#' else '.')
}
println()
}
println()
}
private fun rectangle(elves: List<Pair<Int, Int>>): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val topLeft = elves.reduce { a, b -> Pair(min(a.first, b.first), min(a.second, b.second)) }
val bottomRight = elves.reduce { a, b -> Pair(max(a.first, b.first), max(a.second, b.second)) }
return Pair(topLeft, bottomRight)
}
operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> {
return Pair(first + other.first, second + other.second)
}
| 0 |
Kotlin
| 0 | 0 |
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
| 2,623 |
advent-of-code-2022
|
MIT License
|
src/Day13.kt
|
jbotuck
| 573,028,687 | false |
{"Kotlin": 42401}
|
fun main() {
val lines = readInput("Day13")
//part 1
lines.asSequence()
.chunked(3)
.map { it.take(2) }
.withIndex().map { it.copy(index = it.index.inc()) }
.filter { isValid(it.value) }
.sumOf { it.index }
.let { println(it) }
//part 2
val dividers = listOf(
"[[2]]",
"[[6]]"
)
val sorted = lines
.filter { it.isNotBlank() }
.plus(dividers)
.sortedWith { a, b -> ParserPacketList(a).compareTo(ParserPacketList(b)) }
println(sorted.indexOf(dividers.first()).inc() * sorted.indexOf(dividers.last()).inc())
}
private fun isValid(pair: List<String>): Boolean {
val (left, right) = pair.map { ParserPacketList(it) }
return isValid(left, right)
}
private fun isValid(left: PacketList, right: PacketList): Boolean {
return left < right
}
private class Parser(private val packet: String) {
var currentIndex = 1
private fun currentValue() = packet.getOrNull(currentIndex)
fun nextValue(): PacketValue? {
when (currentValue()) {
null -> return null
'[' -> {
currentIndex++
return ParserPacketList(this)
}
']' -> {
currentIndex++
if (currentValue() == ',') currentIndex++
return null
}
else -> {
return sequence {
while (currentValue() !in setOf(',', ']', null)) {
yield(currentValue()!!)
currentIndex++
}
if (currentValue() == ',') currentIndex++
}.joinToString("").toInt().let { PacketInt(it) }
}
}
}
}
private sealed interface PacketValue : Comparable<PacketValue>
private data class PacketInt(val value: Int) : PacketValue {
override fun compareTo(other: PacketValue): Int {
if (other is PacketInt) return value.compareTo(other.value)
return IntPacketList(value).compareTo(other)
}
}
private interface PacketList : PacketValue {
fun nextValue(): PacketValue?
override fun compareTo(other: PacketValue): Int {
when (other) {
is PacketInt -> return compareTo(IntPacketList(other.value))
is PacketList -> {
var left: PacketValue?
while (nextValue().also { left = it } != null) {
val right = other.nextValue() ?: return 1
left!!.compareTo(right).takeIf { it != 0 }?.let { return it }
}
return if (other.nextValue() != null) -1 else 0
}
}
}
}
private class ParserPacketList(private val parser: Parser) : PacketList {
constructor(packet: String) : this(Parser(packet))
override fun nextValue() = parser.nextValue()
}
private class IntPacketList(private val value: Int) : PacketList {
var hasNext = true
override fun nextValue() = if (hasNext) PacketInt(value).also { hasNext = false } else null
}
| 0 |
Kotlin
| 0 | 0 |
d5adefbcc04f37950143f384ff0efcd0bbb0d051
| 3,072 |
aoc2022
|
Apache License 2.0
|
dcp_kotlin/src/main/kotlin/dcp/day313/day313.kt
|
sraaphorst
| 182,330,159 | false |
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
|
package dcp.day313
import java.util.LinkedList
import java.util.Queue
import kotlin.math.max
/**
* We formulate the problem as a shortest path over a simple graph.
* For every one of the 1000 permissible states, we have a vertex, with edges between vertices if they differ by
* 1 in one place, e.g. 123 is adjacent to 122, 124, 113, 133, 023, and 223.
*
* We can then use BFS to find the shortest path between the single source 000 and the desired state.
*/
/**
* A graph is just a node of adjacencies we can go to.
* The node labeled x is simply the list at x returned from createGraph.
*/
private typealias Node = List<Int>
/**
* Find the adjacencies of a given number.
* This is kind of horrible, but I'm not immediately sure of a better way.
* We make sure i is a three digit number (by prepending 0s if required) and then rotate each digit both
* positively and negatively to get the six adjacencies.
*/
private fun calculateAdjacencies(i: Int): List<Int> {
fun rotateDigitClockwise(str: String, i: Int): String {
return str.take(max(0,i)) + when (str[i]) {
'9' -> '0'
else -> str[i] + 1
} + str.drop(i+1)
}
fun rotateDigitCounterclockwise(str: String, i: Int): String = str.take(max(0,i)) + when (str[i]) {
'0' -> '9'
else -> str[i] - 1
} + str.drop(i+1)
val str = i.toString()
val digits = (if (str.length < 3) "0".repeat(3 - str.length) else "") + str
return (0 until 3).flatMap {
idx -> listOf(rotateDigitClockwise(digits, idx), rotateDigitCounterclockwise(digits, idx))
}.map { it.toInt() }
}
/**
* Create an adjacency list graph and return the array of 1000 nodes.
* Forbidden nodes simply have no edges.
* An array allows us constant lookup, which is why we use it instead of a list.
*/
private fun createGraph(forbidden: Collection<Int>): Array<Node> =
Array(1000) { i -> calculateAdjacencies(i).filter { i !in forbidden } }
/**
* Find the minimum number of moves to unlock the lock, if it is possible at all.
*/
fun unlock(goal: Int, forbidden: Collection<Int>): Int? {
// Conditions:
// 1. 000 cannot be forbidden.
// 2. All minimum forbidden elements must be in range [0,1000).
// 3. The goal is in range.
// 4. The goal is not forbidden.
require(0 !in forbidden)
require((forbidden.min() ?: 0) >= 0)
require((forbidden.max() ?: 0) <= 999)
require(goal in 0..999)
require(goal !in forbidden)
if (goal == 0)
return 0
val graph = createGraph(forbidden)
// We will perform a BFS, using a queue and a list mapping the distance from 000.
// We need mutable data structures to do this.
val distances = MutableList(1000){-1}
distances[0] = 0
// Queue to for BFS to keep track of nodes to visit.
val queue: Queue<Int> = LinkedList<Int>()
queue.add(0)
while (queue.isNotEmpty()) {
val nodeIdx = queue.poll()
if (nodeIdx == goal)
return distances[goal]
// Add all the unvisited nodes to the priority queue.
graph[nodeIdx].filter { distances[it] == -1 }.forEach {
distances[it] = distances[nodeIdx] + 1
queue.add(it)
}
}
// If we reach this point, we never found distances.
require(distances[goal] == -1)
return null
}
| 0 |
C++
| 1 | 0 |
5981e97106376186241f0fad81ee0e3a9b0270b5
| 3,339 |
daily-coding-problem
|
MIT License
|
src/Day12.kt
|
eo
| 574,058,285 | false |
{"Kotlin": 45178}
|
// https://adventofcode.com/2022/day/12
fun main() {
fun shortestPathLength(
grid: ElevationGrid,
sourceCell: Cell,
isDestination: (Cell) -> Boolean,
canReachToCell: (Cell, Cell) -> Boolean
): Int {
val queue = ArrayDeque<Cell>()
val visited = HashSet<Cell>()
queue += sourceCell
visited += sourceCell
var steps = 0
while (queue.isNotEmpty()) {
repeat(queue.size) {
val cell = queue.removeFirst()
if (isDestination(cell)) return steps
cell.adjacentCells.forEach { adjacent ->
if(
adjacent in grid &&
adjacent !in visited &&
canReachToCell(cell, adjacent)
) {
queue += adjacent
visited += adjacent
}
}
}
steps++
}
return -1
}
fun part1(input: String): Int {
val grid = ElevationGrid.fromString(input)
val sourceCell = grid.findOrNull('S') ?: error("S is not in grid!")
val destinationCell = grid.findOrNull('E') ?: error("E is not in grid!")
return shortestPathLength(
grid,
sourceCell,
{ it == destinationCell },
{ fromCell, toCell -> grid.elevationAt(toCell) <= grid.elevationAt(fromCell) + 1 }
)
}
fun part2(input: String): Int {
val grid = ElevationGrid.fromString(input)
val sourceCell = grid.findOrNull('E') ?: error("E is not in grid!")
return shortestPathLength(
grid,
sourceCell,
{ grid.elevationAt(it) == 'a' },
{ fromCell, toCell -> grid.elevationAt(fromCell) <= grid.elevationAt(toCell) + 1 }
)
}
val input = readText("Input12")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
private class ElevationGrid(private val chars: List<List<Char>>) {
val rowCount get() = chars.size
val colCount get() = chars[0].size
operator fun contains(cell: Cell): Boolean =
cell.row in 0 until rowCount && cell.col in 0 until colCount
fun elevationAt(cell: Cell): Char =
when (val ch = chars[cell.row][cell.col]) {
'S' -> 'a'
'E' -> 'z'
else -> ch
}
fun findOrNull(charToFind: Char): Cell? {
chars.forEachIndexed { row, rowChars ->
rowChars.forEachIndexed { col, ch ->
if (ch == charToFind) return Cell(row, col)
}
}
return null
}
companion object {
fun fromString(input: String) = ElevationGrid(
input.lines().map(String::toList)
)
}
}
private data class Cell(val row: Int, val col: Int) {
val adjacentCells: List<Cell>
get() = listOf(
copy(col = col - 1),
copy(row = row - 1),
copy(col = col + 1),
copy(row = row + 1)
)
}
| 0 |
Kotlin
| 0 | 0 |
8661e4c380b45c19e6ecd590d657c9c396f72a05
| 3,091 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/main/kotlin/day8.kt
|
Arch-vile
| 572,557,390 | false |
{"Kotlin": 132454}
|
package day8
import aoc.utils.*
fun part1(): Int {
val input = readInput("day8-input.txt")
.map { it.toList().map { it.toInt() } }
val matrix = Matrix(input)
return matrix.allInColumnOrder()
.filter {
val lineUp = matrix.trace(it.cursor) { p -> Cursor(p.x, p.y - 1) }
val lineDown = matrix.trace(it.cursor) { p -> Cursor(p.x, p.y + 1) }
val lineLeft = matrix.trace(it.cursor) { p -> Cursor(p.x - 1, p.y) }
val lineRight = matrix.trace(it.cursor) { p -> Cursor(p.x + 1, p.y) }
allShorter(it.value, lineUp) ||
allShorter(it.value, lineDown) ||
allShorter(it.value, lineLeft) ||
allShorter(it.value, lineRight)
}
.count()
}
fun part2(): Int {
val input = readInput("day8-input.txt")
.map { it.toList().map { it.toInt() } }
val matrix = Matrix(input)
return matrix.allInColumnOrder()
.map {
val lineUp = matrix.trace(it.cursor) { p -> Cursor(p.x, p.y - 1) }
val lineDown = matrix.trace(it.cursor) { p -> Cursor(p.x, p.y + 1) }
val lineLeft = matrix.trace(it.cursor) { p -> Cursor(p.x - 1, p.y) }
val lineRight = matrix.trace(it.cursor) { p -> Cursor(p.x + 1, p.y) }
product(
listOf(
viewingDistance(it.value, lineUp),
viewingDistance(it.value, lineDown),
viewingDistance(it.value, lineLeft),
viewingDistance(it.value, lineRight)
)
)
}
.maxOf{ it}
}
fun viewingDistance(height: Int, line: List<Entry<Int>>): Int {
if(line.isEmpty())
return 1
return line
.map { it.value }
.breakAfter { it >= height }[0]
.size
}
fun allShorter(height: Int, line: List<Entry<Int>>): Boolean {
return line.filter { it.value >= height }.isEmpty()
}
fun product(it: List<Int>): Int {
return it.reduce { acc, i -> i * acc }
}
| 0 |
Kotlin
| 0 | 0 |
e737bf3112e97b2221403fef6f77e994f331b7e9
| 2,054 |
adventOfCode2022
|
Apache License 2.0
|
workshops/moscow_prefinals2020/day3/l.kt
|
mikhail-dvorkin
| 93,438,157 | false |
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
|
package workshops.moscow_prefinals2020.day3
private fun solve() {
val a = mutableMapOf<Int, MutableMap<Int, Int>>()
var ans = 0
repeat(readInt()) {
val (s, vIn) = readStrings()
val v = vIn.toInt()
if (v <= 0) return@repeat
val hashing = Hashing(s)
var maxSeen = 0
for (len in a.keys) if (len < s.length) {
val map = a[len]!!
for (i in 0..s.length - len) {
val hash = hashing.hash(i, i + len)
val score = map[hash] ?: continue
maxSeen = maxOf(maxSeen, score)
}
}
val map = a.computeIfAbsent(s.length) { mutableMapOf() }
val hash = hashing.hash(0, s.length)
val score = map.compute(hash) { _, oldValue -> v + maxOf(maxSeen, oldValue ?: 0) }!!
ans = maxOf(ans, score)
}
println(ans)
}
private const val M = 1_000_000_007
private class Hashing(s: String, x: Int = 566239) {
val h = IntArray(s.length + 1)
val t = IntArray(s.length + 1)
fun hash(from: Int, to: Int): Int {
var res = ((h[to] - h[from] * t[to - from].toLong()) % M).toInt()
if (res < 0) res += M
return res
}
init {
t[0] = 1
for (i in s.indices) {
t[i + 1] = (t[i] * x.toLong() % M).toInt()
h[i + 1] = ((h[i] * x.toLong() + s[i].toLong()) % M).toInt()
}
}
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
| 0 |
Java
| 1 | 9 |
30953122834fcaee817fe21fb108a374946f8c7c
| 1,365 |
competitions
|
The Unlicense
|
src/day4/Day04.kt
|
blundell
| 572,916,256 | false |
{"Kotlin": 38491}
|
package day4
import readInput
fun main() {
fun IntRange.contains(other: IntRange): Boolean {
return this.first >= other.first && this.last <= other.last
}
fun IntRange.overlaps(other: IntRange): Boolean {
return this.first >= other.first && this.first <= other.last
|| this.last <= other.last && this.last >= other.first
}
fun getElfTasks(input: List<String>) = input
.map {
val elf1 = it.take(it.indexOf(","))
val elf2 = it.substring(it.indexOf(",") + 1)
elf1 to elf2
}.map {
val elf1Low = it.first.take(it.first.indexOf("-")).toInt()
val elf1High = it.first.substring(it.first.indexOf("-") + 1).toInt()
val elf1Range = elf1Low..elf1High
val elf2Low = it.second.take(it.second.indexOf("-")).toInt()
val elf2High = it.second.substring(it.second.indexOf("-") + 1).toInt()
val elf2Range = elf2Low..elf2High
elf1Range to elf2Range
}
fun part1(input: List<String>): Int {
return getElfTasks(input).map { it: Pair<IntRange, IntRange> ->
val elf1Range: IntRange = it.first
val elf2Range: IntRange = it.second
if (elf1Range.contains(elf2Range)) {
return@map 1
}
if (elf2Range.contains(elf1Range)) {
return@map 1
}
0
}.sum()
}
fun part2(input: List<String>): Int {
return getElfTasks(input).map { it: Pair<IntRange, IntRange> ->
val elf1Range: IntRange = it.first
val elf2Range: IntRange = it.second
if (elf1Range.overlaps(elf2Range)) {
return@map 1
}
if (elf2Range.overlaps(elf1Range)) {
return@map 1
}
0
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day4/Day04_test")
check(part1(testInput) == 1)
val input = readInput("day4/Day04")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
f41982912e3eb10b270061db1f7fe3dcc1931902
| 2,143 |
kotlin-advent-of-code-2022
|
Apache License 2.0
|
src/Day15.kt
|
MisterTeatime
| 560,956,854 | false |
{"Kotlin": 37980}
|
import java.math.BigInteger
fun main() {
fun part1(input: List<String>, y: Int): Int {
val beacons = mutableListOf<Point2D>()
val sensors = getSensors(input, beacons)
var covered = 0
// Die Grenzen der Ausdehnung bestimmen.
// Es kann kein Punkt jenseits der niedrigsten X-Koordinate minus Beacon-Abstand existieren.
// Gleiches gilt für Punkte jenseits der höchsten X-Koordinate plus Abstand.
val boundaries = sensors
.map { listOf(it.key.x - it.value, it.key.x + it.value) }
.reduce { best, next -> listOf(minOf(best[0], next[0]), maxOf(best[1], next[1])) }
for (x in boundaries[0]..boundaries[1]) {
val point = Point2D(x, y)
if (beacons.contains(point)) continue
if (sensors.keys.contains(point)) continue
if (sensors.any { sensor -> sensor.key.distanceTo(point) <= sensor.value})
covered += 1
}
return covered
}
fun part2(input: List<String>, to: Int, from: Int = 0): BigInteger {
val beacons = mutableListOf<Point2D>()
val sensors = getSensors(input, beacons)
val aCoefficients = mutableSetOf<Int>()
val bCoefficients = mutableSetOf<Int>()
aCoefficients.addAll(sensors.map { (p, r) -> p.y - p.x + r + 1 })
aCoefficients.addAll(sensors.map { (p, r) -> p.y - p.x - r - 1 })
bCoefficients.addAll(sensors.map { (p, r) -> p.x + p.y + r + 1 })
bCoefficients.addAll(sensors.map { (p, r) -> p.x + p.y - r - 1 })
val intersections = aCoefficients
.flatMap { a ->
bCoefficients.map { b ->
((b - a) / 2) to ((a + b) / 2)
}
}
.map { Point2D(it.first, it.second) }
.filter { it.x in 0 .. to && it.y in 0..to }
return intersections.filter { p -> sensors.all { sensor -> p.distanceTo(sensor.key) > sensor.value } }.map { (x,y) -> x.toBigInteger() * 4_000_000.toBigInteger() + y.toBigInteger() }.first()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56_000_011.toBigInteger())
val input = readInput("Day15")
println(part1(input, 2_000_000))
println(part2(input, 4_000_000))
}
fun getSensors(input: List<String>, beacons: MutableList<Point2D>): MutableMap<Point2D, Int> {
val sensors = mutableMapOf<Point2D, Int>()
val regex = """x=(-?\d+), y=(-?\d+).*x=(-?\d+), y=(-?\d+)""".toRegex()
input.forEach {
val (sensorX, sensorY, beaconX, beaconY) = regex.find(it)!!.destructured
val sensor = Point2D(sensorX.toInt(), sensorY.toInt())
val beacon = Point2D(beaconX.toInt(), beaconY.toInt())
sensors[sensor] = sensor.distanceTo(beacon)
beacons.add(beacon)
}
return sensors
}
| 0 |
Kotlin
| 0 | 0 |
8ba0c36992921e1623d9b2ed3585c8eb8d88718e
| 2,962 |
AoC2022
|
Apache License 2.0
|
src/year2022/18/Day18.kt
|
Vladuken
| 573,128,337 | false |
{"Kotlin": 327524, "Python": 16475}
|
package year2022.`18`
import java.util.LinkedList
import readInput
/**
* Data Class Representing Cube of 1x1x1 in 3D Grid
*/
data class Cube(
val x: Int,
val y: Int,
val z: Int
) {
fun inRange(range: IntRange): Boolean {
return x in range && y in range && z in range
}
}
/**
* Parse input to list of cubes
*/
fun parseInput(input: List<String>): List<Cube> {
return input.map { line ->
line.split(",").mapNotNull { it.toIntOrNull() }
}
.map {
Cube(it[0], it[1], it[2])
}
}
/**
* Get Neighbours of this cube
*/
fun Cube.neighbours(): List<Cube> {
return listOf(
copy(x = x + 1),
copy(x = x - 1),
copy(y = y + 1),
copy(y = y - 1),
copy(z = z + 1),
copy(z = z - 1),
)
}
fun iterateOverAllEmptyCubes(
initialCubes: List<Cube>,
startingCube: Cube,
range: IntRange
): Int {
val visited = mutableSetOf<Cube>()
val queue = LinkedList<Cube>().also { it.add(startingCube) }
var count = 0
while (queue.isNotEmpty()) {
val currentCube = queue.remove()
if (currentCube in visited) continue
visited.add(currentCube)
currentCube.neighbours()
.forEach {
if (it in initialCubes) {
count++
} else if (it.inRange(range)) {
queue.add(it)
}
}
}
return count
}
fun main() {
fun part1(input: List<String>): Int {
val cubes = parseInput(input)
val allCubeSides = 6
return cubes.sumOf { cube ->
val neighbours = cube.neighbours()
val filledCubeSides = cubes.count { it in neighbours }
allCubeSides - filledCubeSides
}
}
fun part2(input: List<String>): Int {
val cubes = parseInput(input)
val max = listOf(
cubes.maxOf { it.x },
cubes.maxOf { it.y },
cubes.maxOf { it.z },
).max()
return iterateOverAllEmptyCubes(
initialCubes = cubes,
startingCube = Cube(max, max, max),
range = -1..max + 1
)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
val part1Test = part1(testInput)
val part2Test = part2(testInput)
check(part1Test == 64)
check(part2Test == 58)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 5 |
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
| 2,524 |
KotlinAdventOfCode
|
Apache License 2.0
|
2022/src/main/kotlin/com/github/akowal/aoc/Day16.kt
|
akowal
| 573,170,341 | false |
{"Kotlin": 36572}
|
package com.github.akowal.aoc
import kotlin.time.ExperimentalTime
import kotlin.time.measureTimedValue
class Day16 {
private val pattern = """Valve (\S+) has flow rate=(\d+); tunnels? leads? to valves? (.+)""".toRegex()
private val flows = mutableMapOf<String, Int>()
private val dists: Map<String, Map<String, Int>>
private val valves = mutableMapOf<String, List<String>>()
init {
inputFile("day16").readLines().map { line ->
val parts = pattern.matchEntire(line)!!.groupValues.drop(1)
val valve = parts[0]
flows[valve] = parts[1].toInt()
valves[valve] = parts[2].split(", ")
}
dists = calcDistancesBetweenWorkingValves()
}
fun solvePart1(): Int {
return findMaxPressureRelease("AA", 30, emptySet(), 0)
}
@OptIn(ExperimentalTime::class)
fun solvePart2(): Int {
return measureTimedValue { findMaxPressureReleaseWithElephant("AA", 26, emptySet(), 0, true) }.also { println(it.duration) }.value
}
private fun findMaxPressureRelease(valve: String, t: Int, open: Set<String>, score: Int): Int {
return dists[valve]!!.maxOf { (v, dist) ->
val tleft = t - dist - 1
if (v in open || tleft < 1) {
score
} else {
findMaxPressureRelease(v, tleft, open + v, score + flows[v]!! * tleft)
}
}
}
private fun findMaxPressureReleaseWithElephant(valve: String, t: Int, open: Set<String>, score: Int, first: Boolean = false): Int {
// brute force =(
val scores = dists[valve]!!.map { (v, dist) ->
val tleft = t - dist - 1
if (v in open || tleft < 1) {
score
} else {
findMaxPressureReleaseWithElephant(v, tleft, open + v, score + flows[v]!! * tleft, first)
}
} + if (first) findMaxPressureReleaseWithElephant("AA", 26, open, score) else 0
return scores.max()
}
private fun calcDistancesBetweenWorkingValves(): Map<String, Map<String, Int>> {
val dists = mutableMapOf<Pair<String, String>, Int>()
valves.forEach { (v, connected) ->
connected.forEach { c ->
dists[v to c] = 1
}
}
for (k in valves.keys) {
for (i in valves.keys) {
val ik = dists[i to k] ?: 2022
for (j in valves.keys) {
val ij = dists[i to j] ?: 2022
val kj = dists[k to j] ?: 2022
if (ij > ik + kj) {
dists[i to j] = ik + kj
}
}
}
}
dists.entries.removeIf { (tunnel, _) -> flows[tunnel.second] == 0 }
return dists.entries.groupBy { it.key.first }.mapValues { it.value.associate { e -> e.key.second to e.value } }
}
}
fun main() {
val solution = Day16()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 |
Kotlin
| 0 | 0 |
02e52625c1c8bd00f8251eb9427828fb5c439fb5
| 3,022 |
advent-of-kode
|
Creative Commons Zero v1.0 Universal
|
src/Day19.kt
|
AlaricLightin
| 572,897,551 | false |
{"Kotlin": 87366}
|
fun main() {
fun part1(blueprints: List<RobotBlueprint>): Int {
return blueprints.sumOf {
it.id * getMaxGeodes(it, 24)
}
}
fun part2(blueprints: List<RobotBlueprint>): Int {
return blueprints.fold(1) { acc, robotBlueprint ->
acc * getMaxGeodes(robotBlueprint, 32)
}
}
val testBlueprints = readBlueprints("Day19_test")
check(part1(testBlueprints) == 33)
check(getMaxGeodes(testBlueprints[0], 32) == 56)
check(getMaxGeodes(testBlueprints[1], 32) == 62)
val blueprints = readBlueprints("Day19")
println(part1(blueprints))
println(part2(blueprints.take(3)))
}
private fun readBlueprints(inputFilename: String): List<RobotBlueprint> {
return readInput(inputFilename).map { string ->
val substrings = string.split(':')
val id = substrings[0].substringAfter(" ").toInt()
val costs = substrings[1]
.split(".")
.filter { it.isNotBlank() }
.map {
val costsString = it.substringAfter("costs ")
.split(" and ")
val result = Array(3) { 0 }
costsString.forEach { s ->
val substrings1 = s.split(" ")
val value = substrings1[0].toInt()
when(substrings1[1]) {
"ore" -> result[0] = value
"clay" -> result[1] = value
"obsidian" -> result[2] = value
}
}
result
}.toTypedArray()
RobotBlueprint(id, costs)
}
}
private data class RobotBlueprint(
val id: Int,
val robotCosts: Array<Array<Int>>
)
private enum class Actions { WAIT, ORE, CLAY, OBSIDIAN, GEODE }
private fun getMaxGeodes(blueprint: RobotBlueprint, timeLimit: Int): Int {
var result = 0
val maxCosts: Array<Int> = Array(3) { index ->
blueprint.robotCosts.maxOf { it[index] }
}
fun canBuildRobot(costs: Array<Int>, resources: Array<Int>): Boolean {
costs.forEachIndexed { index, i ->
if (i > resources[index])
return false
}
return true
}
fun canBuildAnotherGeodeRobot(time: Int,
obsidianResources: Int,
obsidianRobotCount: Int): Boolean {
if (time + blueprint.robotCosts[3][2] < timeLimit)
return true
val timeToEnd = timeLimit - time - 1
return obsidianResources +
(obsidianRobotCount + obsidianRobotCount + timeToEnd - 1) * timeToEnd / 2 >=
blueprint.robotCosts[3][2]
}
fun nextStep(resources: Array<Int>, robots: Array<Int>, time: Int, geodesCount: Int) {
if (time == timeLimit || !canBuildAnotherGeodeRobot(time, resources[2], robots[2])) {
if (result < geodesCount)
result = geodesCount
return
}
enumValues<Actions>().forEach {
when (it) {
Actions.WAIT -> {
if (blueprint.robotCosts.any { costArray ->
var needToWaitResource = false
costArray.forEachIndexed { index, i ->
if (i != 0) {
if (robots[index] == 0)
return@any false
if (resources[index] < i)
needToWaitResource = true
}
}
needToWaitResource
}) {
nextStep(
arrayOf(
resources[0] + robots[0],
resources[1] + robots[1],
resources[2] + robots[2]
),
robots,
time + 1,
geodesCount
)
}
}
Actions.ORE, Actions.CLAY, Actions.OBSIDIAN -> {
if (robots[it.ordinal - 1] >= maxCosts[it.ordinal - 1])
return@forEach
if (resources[it.ordinal - 1] + robots[it.ordinal - 1] * (timeLimit - time) >
maxCosts[it.ordinal - 1] * (timeLimit - time))
return@forEach
if (it == Actions.ORE && (2..3).any {
canBuildRobot(blueprint.robotCosts[it], resources)
})
return@forEach
if (canBuildRobot(blueprint.robotCosts[it.ordinal - 1], resources)) {
nextStep(
arrayOf(
resources[0] + robots[0] - blueprint.robotCosts[it.ordinal - 1][0],
resources[1] + robots[1] - blueprint.robotCosts[it.ordinal - 1][1],
resources[2] + robots[2] - blueprint.robotCosts[it.ordinal - 1][2],
),
arrayOf(
robots[0] + if (it == Actions.ORE) 1 else 0,
robots[1] + if (it == Actions.CLAY) 1 else 0,
robots[2] + if (it == Actions.OBSIDIAN) 1 else 0,
),
time + 1,
geodesCount
)
}
}
Actions.GEODE -> {
if (canBuildRobot(blueprint.robotCosts[3], resources)) {
nextStep(
arrayOf(
resources[0] + robots[0] - blueprint.robotCosts[3][0],
resources[1] + robots[1] - blueprint.robotCosts[3][1],
resources[2] + robots[2] - blueprint.robotCosts[3][2],
),
robots,
time + 1,
geodesCount + timeLimit - time
)
}
}
}
}
}
nextStep(arrayOf(1, 0, 0), arrayOf(1, 0, 0), 2, 0)
println("id = ${blueprint.id} result = $result")
return result
}
| 0 |
Kotlin
| 0 | 0 |
ee991f6932b038ce5e96739855df7807c6e06258
| 6,533 |
AdventOfCode2022
|
Apache License 2.0
|
src/Day07.kt
|
p357k4
| 573,068,508 | false |
{"Kotlin": 59696}
|
import java.util.ArrayList
sealed interface Node {}
data class Directory(val name: String, val nodes: MutableList<Node>, val parent: Directory?, var size : Int) : Node
data class File(val name: String, val size: Int) : Node
fun main() {
fun calculate(directory: Directory): Int {
var size = 0
for (node in directory.nodes) {
size += when (node) {
is File -> node.size
is Directory -> calculate(node)
}
}
directory.size = size
return size
}
fun totalSizeOfSmallDirectories(directory: Directory): Int {
var size = if (directory.size > 100_000) 0 else directory.size
for (node in directory.nodes) {
size += when (node) {
is Directory -> totalSizeOfSmallDirectories(node)
else -> 0
}
}
return size
}
fun directories(root: Directory): List<Directory> {
return root
.nodes
.filterIsInstance<Directory>()
.flatMap(::directories) + root
}
fun smallest(root: Directory, size : Int): Directory {
val result = directories(root)
.minBy {
val distance = it.size - size
if (distance < 0) Int.MAX_VALUE else distance
}
return result;
}
fun build(input: List<String>): Directory {
val root = Directory("", ArrayList<Node>(), null, 0)
var current: Directory? = root
for (line in input) {
val split = line.split(' ')
if (split[0] == "$" && split[1] == "cd" && split[2] == "/") {
current = root;
} else if (split[0] == "$" && split[1] == "cd" && split[2] == "..") {
current = current?.parent
} else if (split[0] == "$" && split[1] == "cd") {
val child = Directory(split[2], ArrayList<Node>(), current, 0)
current?.nodes?.add(child)
current = child
} else if (split[0] == "$" && split[1] == "ls") {
// ls
} else if (split[0] == "dir") {
// dir
} else {
// file
current?.nodes?.add(File(split[1], split[0].toInt()))
}
}
calculate(root)
return root
}
fun part1(input: List<String>): Int {
val root = build(input)
return totalSizeOfSmallDirectories(root)
}
fun part2(input: List<String>): Int {
val root = build(input)
val size = 30_000_000 - (70_000_000 - root.size)
return smallest(root, size).size
}
// test if implementation meets criteria from the description, like:
val testInputExample = readInput("Day07_example")
check(part1(testInputExample) == 95437)
check(part2(testInputExample) == 24933642)
val testInput = readInput("Day07_test")
check(part1(testInput) == 1077191)
check(part2(testInput) == 5649896)
}
| 0 |
Kotlin
| 0 | 0 |
b9047b77d37de53be4243478749e9ee3af5b0fac
| 3,013 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/main/kotlin/day13/Day13.kt
|
cyril265
| 433,772,262 | false |
{"Kotlin": 39445, "Java": 4273}
|
package day13
import readToList
private val input = readToList("day13.txt")
fun main() {
println(part1())
println(part2())
}
private fun part1(): Int {
val (foldInstructions, dots) = mapInput()
val foldInstruction = foldInstructions.first()
dots.forEach { dot ->
dot.fold(foldInstruction)
}
return dots.toSet().size
}
private fun part2(): String {
val (foldInstructions, dots) = mapInput()
foldInstructions.forEach { foldInstruction ->
dots.forEach { dot ->
dot.fold(foldInstruction)
}
}
val yMax = dots.maxOf { it.y }
val xMax = dots.maxOf { it.x }
val resultMatrix = Array(yMax + 1) { Array(xMax + 1) { "." } }
resultMatrix.forEachIndexed { rowIndex, row ->
row.forEachIndexed { columnIndex, _ ->
if (dots.any { it.x == columnIndex && it.y == rowIndex }) resultMatrix[rowIndex][columnIndex] = "#"
}
}
return resultMatrix.joinToString(separator = "\n") { it.contentToString() }
}
private fun mapInput(): Pair<List<FoldInstruction>, List<Dot>> {
val foldIndex = input.indexOfFirst { it.startsWith("fold") }
val dotsPlain = input.subList(0, foldIndex - 1)
val foldInstructionsPlain = input.subList(foldIndex, input.size)
val foldInstructions = foldInstructionsPlain.map {
val (coordinate, value) = it.substringAfter("fold along ").split("=")
val coordinateType = if (coordinate == "x") CoordinateType.X else CoordinateType.Y
FoldInstruction(value.toInt(), coordinateType)
}
val dots = dotsPlain.map {
val (x, y) = it.split(",")
Dot(x.toInt(), y.toInt())
}
return Pair(foldInstructions, dots)
}
private data class Dot(var x: Int, var y: Int) {
fun fold(foldInstruction: FoldInstruction) {
if (foldInstruction.type == CoordinateType.Y) {
if (y > foldInstruction.coordinate) {
y = foldInstruction.coordinate - (y - foldInstruction.coordinate)
}
} else {
if (x > foldInstruction.coordinate) {
x = foldInstruction.coordinate - (x - foldInstruction.coordinate)
}
}
}
}
private data class FoldInstruction(val coordinate: Int, val type: CoordinateType)
enum class CoordinateType {
X, Y
}
| 0 |
Kotlin
| 0 | 0 |
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
| 2,310 |
aoc2021
|
Apache License 2.0
|
src/Day15.kt
|
flex3r
| 572,653,526 | false |
{"Kotlin": 63192}
|
import kotlin.math.abs
fun main() {
val testInput = readInput("Day15_test")
check(part1(testInput, rowToCheck = 10) == 26)
check(part2(testInput, maxY = 20) == 56000011L)
val input = readInput("Day15")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>, rowToCheck: Int = 2000000): Int = buildSet {
parseSensors(input).forEach { (sensor, beacon) ->
val distance = sensor.manhatten(beacon)
val distanceToRow = abs(sensor.y - rowToCheck)
val width = distance - distanceToRow
(sensor.x - width..sensor.x + width).forEach { x ->
val pos = Pos(x, rowToCheck)
if (pos != beacon) {
add(x)
}
}
}
}.size
private fun part2(input: List<String>, maxY: Int = 4000000): Long {
val sensors = parseSensors(input)
(0..maxY)
.asSequence()
.map { y ->
sensors.mapNotNull { (sensor, beacon) ->
val distance = sensor.manhatten(beacon)
val distanceToY = abs(sensor.y - y)
(distance - distanceToY)
.takeIf { it > 0 }
?.let { sensor.x - it..sensor.x + it }
}.sortedBy { it.first }
}
.forEachIndexed { y, ranges ->
var maxRangeEnd = ranges.first().last
ranges.forEach { otherRange ->
when {
otherRange.first > maxRangeEnd -> return (maxRangeEnd + 1) * 4_000_000L + y
otherRange.last > maxRangeEnd -> maxRangeEnd = otherRange.last
}
}
}
return -1
}
private fun parseSensors(input: List<String>): List<Pair<Pos, Pos>> {
return input.map { line ->
val (sensorPart, beaconPart) = line.split(":")
parsePos(sensorPart) to parsePos(beaconPart)
}
}
private fun parsePos(part: String): Pos {
val (xPart, yPart) = part.split(",")
val x = xPart.substringAfter("x=").toInt()
val y = yPart.substringAfter("y=").toInt()
return Pos(x, y)
}
private data class Pos(val x: Int, val y: Int)
private fun Pos.manhatten(other: Pos) = abs(x - other.x) + abs(y - other.y)
| 0 |
Kotlin
| 0 | 0 |
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
| 2,200 |
aoc-22
|
Apache License 2.0
|
src/Day15.kt
|
mcrispim
| 573,449,109 | false |
{"Kotlin": 46488}
|
import kotlin.math.abs
data class PositionDay15(val x: Int, val y: Int)
class CaveDay15(input: List<String>) {
val area = mutableMapOf<PositionDay15, Char>()
val covertAreas = mutableMapOf<PositionDay15, Int>()
init {
input.forEach {
// Format = "Sensor at x=2, y=18: closest beacon is at x=-2, y=15"
val (sensorPartStr, beaconPartStr) = it.split(": ")
val (sensorXStr, sensorYStr) = sensorPartStr.split(", ")
val sensorX = sensorXStr.substringAfter("x=").toInt()
val sensorY = sensorYStr.substringAfter("y=").toInt()
val (beaconXStr, beaconYStr) = beaconPartStr.split(", ")
val beaconX = beaconXStr.substringAfter("x=").toInt()
val beaconY = beaconYStr.substringAfter("y=").toInt()
val sensor = PositionDay15(sensorX, sensorY)
val beacon = PositionDay15(beaconX, beaconY)
area[sensor] = 'S'
area[beacon] = 'B'
// println(" Sensor: $sensorX, $sensorY ==> Beacon: $beaconX, $beaconY")
val distance = abs(sensor.x - beacon.x) + abs(sensor.y - beacon.y)
covertAreas[sensor] = distance
}
}
}
fun main() {
fun itemsInLine(cave: CaveDay15, line: Int): Set<Int> {
val mainAreas = cave.covertAreas
.filter { (pos, dist) -> line in (pos.y - dist)..(pos.y + dist) }
.map { (pos, dist) ->
val d = dist - abs(pos.y - line)
pos.x - d..pos.x + d
}
var lineSet = setOf<Int>()
mainAreas.forEach { lineSet = lineSet.union(it) }
return lineSet
}
fun part1(input: List<String>, line: Int): Int {
val cave = CaveDay15(input)
var lineSet = itemsInLine(cave, line)
val empties = lineSet.size
val sensorsAndBeacons = cave.area.filter { (pos, _) -> pos.y == line }.count()
return empties - sensorsAndBeacons
}
fun part2(input: List<String>, maxXY: Int): Int {
val cave = CaveDay15(input)
for (y in 0..maxXY) {
println(" line: $y")
val lineStr = CharArray(21) { '.' }
val items = itemsInLine(cave, y)
val nonItems = (0..maxXY).toSet() - items
/*items.forEach { if (it in 0..20) lineStr[it] = '#' }
var str = ""
for (c in lineStr) str += c
print(str)
if (nonItems.size != 0)
println(" ${nonItems} - $y")
else
println()*/
if (nonItems.size != 0)
return nonItems.first() * 4_000_000 + y
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011)
val input = readInput("Day15")
println(part1(input, 2_000_000))
println(part2(input, 4_000_000))
}
| 0 |
Kotlin
| 0 | 0 |
5fcacc6316e1576a172a46ba5fc9f70bcb41f532
| 2,980 |
AoC2022
|
Apache License 2.0
|
src/Day07.kt
|
sabercon
| 648,989,596 | false | null |
fun main() {
fun parse(line: String): Pair<String, List<Pair<Int, String>>> {
val (outer, inner) = """([a-z ]+) bags contain ([0-9a-z, ]+)\.""".toRegex().destructureGroups(line)
val inners = inner.split(", ").mapNotNull {
if (it == "no other bags") return@mapNotNull null
val (count, color) = """(\d+) ([a-z ]+) bags?""".toRegex().destructureGroups(it)
count.toInt() to color
}
return outer to inners
}
fun countOuters(rules: Map<String, List<Pair<Int, String>>>, color: String): Int {
val map = rules.flatMap { (outer, inners) -> inners.map { (_, inner) -> inner to outer } }
.groupBy({ it.first }, { it.second })
fun outers(color: String): Set<String> {
if (color !in map) return emptySet()
return map[color]!!.fold(emptySet()) { acc, c -> acc + c + outers(c) }
}
return outers(color).size
}
fun countInners(rules: Map<String, List<Pair<Int, String>>>, color: String): Int {
if (color !in rules) return 0
return rules[color]!!.sumOf { (count, color) -> count * (1 + countInners(rules, color)) }
}
val input = readLines("Day07").associate { parse(it) }
countOuters(input, "shiny gold").println()
countInners(input, "shiny gold").println()
}
| 0 |
Kotlin
| 0 | 0 |
81b51f3779940dde46f3811b4d8a32a5bb4534c8
| 1,339 |
advent-of-code-2020
|
MIT License
|
src/Day05.kt
|
Xacalet
| 576,909,107 | false |
{"Kotlin": 18486}
|
/**
* ADVENT OF CODE 2022 (https://adventofcode.com/2022/)
*
* Solution to day 5 (https://adventofcode.com/2022/day/5)
*
*/
fun main() {
data class StackRearrangement(
val count: Int,
val fromIndex: Int,
val toIndex: Int,
)
fun part1(stacks: List<MutableList<String>>, rearrangements: List<StackRearrangement>): String {
rearrangements.forEach { arrangement ->
(1..arrangement.count).forEach {
val movingCrate = stacks[arrangement.fromIndex - 1].last()
stacks[arrangement.toIndex - 1].add(movingCrate)
stacks[arrangement.fromIndex - 1].removeLast()
}
}
return stacks.joinToString("") { it.lastOrNull() ?: " " }
}
fun part2(stacks: List<MutableList<String>>, rearrangements: List<StackRearrangement>): String {
rearrangements.forEach { arrangement ->
val movingCranes = (1..arrangement.count).map {
stacks[arrangement.fromIndex - 1].removeLast()
}
stacks[arrangement.toIndex - 1].addAll(movingCranes.reversed())
}
return stacks.joinToString("") { it.lastOrNull() ?: " " }
}
fun parseStackInput(input: List<String>): List<MutableList<String>> {
return input.reversed().drop(1).map { it.drop(1).windowed(1,4) }.let { slots ->
slots.flatten().withIndex().groupBy { it.index % slots.first().count() }.map { it.value.map { it.value }.filter { it.isNotBlank() }.toMutableList() }
}
}
fun parseRearrangementsInput(input: List<String>): List<StackRearrangement> {
return input.map {
"""move (\d+) from (\d+) to (\d+)""".toRegex().find(it)!!.destructured.let { (count, origin, destination) ->
StackRearrangement(count.toInt(), origin.toInt(), destination.toInt())
}
}
}
val (stackInput, rearrangementsInput) = readInput("day05_dataset").split("\n\n").map { it.split("\n") }
val stacks = parseStackInput(stackInput)
val rearrangements = parseRearrangementsInput(rearrangementsInput)
val (stacks1, stacks2) = (0..1).map { stacks.map { it.toMutableList() }.toList() }
part1(stacks1, rearrangements).println()
part2(stacks2, rearrangements).println()
}
| 0 |
Kotlin
| 0 | 0 |
5c9cb4650335e1852402c9cd1bf6f2ba96e197b2
| 2,299 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day15.kt
|
fasfsfgs
| 573,562,215 | false |
{"Kotlin": 52546}
|
import kotlin.math.abs
fun main() {
fun part1(input: List<String>, desiredY: Int): Int {
val report = input.toReport()
val scannedXAtY = report
.map { it.sensor }
.flatMap { it.xScannedAtY(desiredY) }
.distinct()
val xWithBeaconAtY = report
.filter { it.beacon.y == desiredY }
.map { it.beacon.x }
return scannedXAtY.count { it !in xWithBeaconAtY }
}
fun part2(input: List<String>, maxRange: Int): Long {
val validRange = 0..maxRange
val sensors = input.toReport().map { it.sensor }
val result = sensors
.asSequence()
.flatMap { it.outerCircle() }
.distinct()
.filter { it.x in validRange && it.y in validRange }
.find { position -> sensors.none { it.isInRange(position) } } ?: error("Couldn't find the beacon")
return (result.x.toLong() * 4_000_000L) + result.y.toLong()
}
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56_000_011L)
val input = readInput("Day15")
println(part1(input, 2_000_000))
println(part2(input, 4_000_000))
// For part 2, I searched for help in Slack and took a possible solution reading other people's comments.
// I had something similar in mind, but it wouldn't get me the answer.
}
data class Position(val x: Int, val y: Int)
data class Sensor(val x: Int, val y: Int, val radius: Int) {
companion object {
fun withBeacon(x: Int, y: Int, nearestBeacon: Beacon): Sensor {
val (beaconX, beaconY) = nearestBeacon
val deltaX = abs(x - beaconX)
val deltaY = abs(y - beaconY)
return Sensor(x, y, deltaX + deltaY)
}
}
fun xScannedAtY(desiredY: Int): Sequence<Int> {
if (desiredY !in y - radius..y + radius) return sequenceOf()
val usedRadiusToGetToDesiredY = abs(y - desiredY)
val radiusLeft = radius - usedRadiusToGetToDesiredY
return (x - radiusLeft..x + radiusLeft).asSequence()
}
fun outerCircle(): Sequence<Position> {
val outerCircleRadius = radius + 1
return (x - outerCircleRadius..x + outerCircleRadius)
.asSequence()
.flatMap { outerCircleX ->
val usedRadiusToGetToOuterCircleX = abs(x - outerCircleX)
val radiusLeft = outerCircleRadius - usedRadiusToGetToOuterCircleX
val outerCircleY1 = y - radiusLeft
val outerCircleY2 = y + radiusLeft
setOf(Position(outerCircleX, outerCircleY1), Position(outerCircleX, outerCircleY2))
}
}
fun isInRange(position: Position) = abs(x - position.x) + abs(y - position.y) <= radius
}
data class Beacon(val x: Int, val y: Int)
data class Report(val sensor: Sensor, val beacon: Beacon)
fun List<String>.toReport(): List<Report> = map {
val (strSensor, strBeacon) = it.split(":")
val sensorX = strSensor.substringAfter("=").substringBefore(",").toInt()
val sensorY = strSensor.substringAfterLast("=").toInt()
val beaconX = strBeacon.substringAfter("=").substringBefore(",").toInt()
val beaconY = strBeacon.substringAfterLast("=").toInt()
val beacon = Beacon(beaconX, beaconY)
val sensor = Sensor.withBeacon(sensorX, sensorY, beacon)
Report(sensor, beacon)
}
| 0 |
Kotlin
| 0 | 0 |
17cfd7ff4c1c48295021213e5a53cf09607b7144
| 3,420 |
advent-of-code-2022
|
Apache License 2.0
|
src/year2023/day13/Day.kt
|
tiagoabrito
| 573,609,974 | false |
{"Kotlin": 73752}
|
package year2023.day13
import year2023.solveIt
fun main() {
val day = "13"
val expectedTest1 = 709L
val expectedTest2 = 1400L
fun getReflections(lines: List<String>): List<Int> {
val repeated = lines.zipWithNext().mapIndexedNotNull { index, pair -> if (pair.first == pair.second) index else null }
val map = repeated.map { r -> r to ((0 until r).map { it to r + (r - it) + 1 }.filter { it.second < lines.size }) }
return map.filter { possible -> possible.second.all { lines[it.first] == lines[it.second] } }.map { it.first }
}
fun getColumnReflection(map: List<String>, original: Int = -1): Int? {
if(map == listOf(
"#..####.##.##",
".##.##.####.#",
"#######.##.##",
"####.........",
"#..##..####..",
"....##.#..#.#",
".##..#.####.#",
"....#.#....#.",
".....##....##",
".##.##.#..#.#",
"#..##..#..#..",
"####.######.#",
".....#.####.#",
".##.##......#",
"#..##........"
)){
println()
}
val transpose = map[0].indices.map { idx -> map.map { l -> l[idx] }.joinToString("") }
val filter = getReflections(transpose)
return filter.map { it.inc() }.firstOrNull { it != original }
}
fun getRowReflection(lines: List<String>, original: Int = -1): Int? {
val filter = getReflections(lines)
return filter.map { it.inc() }.firstOrNull { it != original }
}
fun part1(input: List<String>): Long {
val items = input.joinToString("\n").split("\n\n").map { it.split("\n") }
val map = items.map { (getColumnReflection(it) ?: (getRowReflection(it)?.let { r -> r * 100 } ?: 0)).toLong() }
return map.sum()
}
fun possibleSmugs(it: List<String>): Sequence<List<String>> = sequence {
for (i in it.indices) {
for (j in it[i].indices) {
val changedChar = when (it[i][j]) {
'#' -> '.'
else -> '#'
}
val changedLine = it[i].substring(0, j) + changedChar + it[i].substring(j + 1, it[i].length)
val value = it.subList(0, i) + changedLine + it.subList(i + 1, it.size)
yield(value)
}
}
}
fun part2(input: List<String>): Long {
val items = input.joinToString("\n").split("\n\n").map { it.split("\n") }
return items.mapNotNull { l ->
l.forEach { println(it) }
val original = getColumnReflection(l) ?: getRowReflection(l)?.let { r -> r * 100 } ?: -1
val firstOrNull = possibleSmugs(l)
.mapNotNull { s -> getColumnReflection(s, original) ?: getRowReflection(s, original / 100)?.let { r -> r * 100 } }
.filter { it != original }
.firstOrNull()
println(firstOrNull)
println()
firstOrNull
}.sum().toLong()
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test")
//>26148
}
| 0 |
Kotlin
| 0 | 0 |
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
| 3,093 |
adventOfCode
|
Apache License 2.0
|
src/main/kotlin/net/navatwo/adventofcode2023/day2/Day2Solution.kt
|
Nava2
| 726,034,626 | false |
{"Kotlin": 100705, "Python": 2640, "Shell": 28}
|
package net.navatwo.adventofcode2023.day2
import net.navatwo.adventofcode2023.framework.ComputedResult
import net.navatwo.adventofcode2023.framework.Solution
sealed class Day2Solution : Solution<List<Day2Solution.Game>> {
data object Part1 : Day2Solution() {
override fun solve(input: List<Game>): ComputedResult {
// which games are possible with 12 red cubes, 13 green cubes, and 14 blue cubes
val validGames = input.asSequence()
.filter { game ->
game.pulls.all { pull ->
pull.pulls.all { (colour, count) ->
when (colour) {
Game.Colour.Red -> count <= 12
Game.Colour.Green -> count <= 13
Game.Colour.Blue -> count <= 14
}
}
}
}
return ComputedResult.Simple(validGames.sumOf { it.id })
}
}
data object Part2 : Day2Solution() {
override fun solve(input: List<Game>): ComputedResult {
// what is the fewest number of cubes required for the game to be playable
// this is the maximum number of cubes of each colour in any pull
val cubesPerGame = input.asSequence()
.map { game ->
val maxValues = mutableMapOf<Game.Colour, Int>()
for ((colour, count) in game.pulls.asSequence()
.flatMap { it.pulls.asSequence() }) {
maxValues.compute(colour) { _, current ->
current?.coerceAtLeast(count) ?: count
}
}
maxValues.values
}
val gamePowers = cubesPerGame.map { cubes -> cubes.fold(1, Int::times) }
return ComputedResult.Simple(gamePowers.sum())
}
}
override fun parse(lines: Sequence<String>): List<Game> {
return lines
.map { line ->
val (gamePreamble, pullValues) = line.split(':', limit = 2)
val gameId = gamePreamble.slice("Game ".length..<gamePreamble.length).toInt()
val pulls = pullValues.splitToSequence(';')
.map(Game.Pull::parse)
.toList()
Game(gameId, pulls)
}
.toList()
}
data class Game(
val id: Int,
val pulls: List<Pull>,
) {
@JvmInline
value class Pull(
val pulls: Map<Colour, Int>,
) {
companion object {
fun parse(input: String): Pull {
val pullMap = input.splitToSequence(',')
.map { it.trim() }
.filter { it.isNotEmpty() }
.map { hand ->
val (count, colour) = hand.split(' ', limit = 2)
Colour.valueOfLowered(colour) to count.toInt()
}
.toMap()
return Pull(pullMap)
}
}
}
enum class Colour {
Red,
Green,
Blue,
;
val lowered: String = name.lowercase()
companion object {
private val loweredValues = entries.associateBy { it.lowered }
fun valueOfLowered(name: String): Colour {
return loweredValues.getValue(name)
}
}
}
}
}
| 0 |
Kotlin
| 0 | 0 |
4b45e663120ad7beabdd1a0f304023cc0b236255
| 2,999 |
advent-of-code-2023
|
MIT License
|
src/Day02.kt
|
F-bh
| 579,719,291 | false |
{"Kotlin": 5785}
|
enum class Result (val points: Int) {
Win(6),
Draw(3),
Lose(0);
companion object {
fun parse(input: Char): Result {
return mapOf(
'X' to Lose,
'Y' to Draw,
'Z' to Win
)[input]!!
}
}
}
enum class Choice(val points: Int) {
Rock(1),
Paper(2),
Scissor(3);
operator fun plus(enemyChoice: Choice): Int {
return lookupTwoChoice[Pair(this, enemyChoice)]!!.points + this.points
}
companion object {
fun parse(input: Char): Choice? {
return mapOf(
'A' to Rock,
'B' to Paper,
'C' to Scissor,
)[input]
}
private val lookupTwoChoice = mapOf(
Pair(Rock, Scissor) to Result.Win,
Pair(Rock, Rock) to Result.Draw,
Pair(Rock, Paper) to Result.Lose,
Pair(Paper, Rock) to Result.Win,
Pair(Paper, Paper) to Result.Draw,
Pair(Paper, Scissor) to Result.Lose,
Pair(Scissor, Paper) to Result.Win,
Pair(Scissor, Scissor) to Result.Draw,
Pair(Scissor, Rock) to Result.Lose,
)
val lookupChoiceAndRes = lookupTwoChoice.entries.associate { (k, v) ->
Pair(k.second, v) to k.first
}
}
}
fun main() {
val input = readDayInput(2)
.map { line -> line.split(" ") }
.map {strings -> Pair(strings[0].toCharArray()[0], strings[1].toCharArray()[0])}
//part 1
println(p1(input))
//part 2
println(p2(input))
}
fun p1(input: List<Pair<Char, Char>>): Int {
fun parse(input: Char): Choice {
return Choice.parse(input) ?:
mapOf(
'X' to Choice.Rock,
'Y' to Choice.Paper,
'Z' to Choice.Scissor,
)[input]!!
}
return input.sumOf { pair -> parse(pair.second) + parse(pair.first) }
}
fun p2(input: List<Pair<Char, Char>>): Int {
return input
.map { pair ->
Pair(Choice.parse(pair.first), Result.parse(pair.second))
}
.sumOf { duel -> duel.second.points + Choice.lookupChoiceAndRes[duel]!!.points }
}
| 0 |
Kotlin
| 0 | 0 |
19fa2db8842f166daf3aaffd201544658f41d9e0
| 2,195 |
Christmas2022
|
Apache License 2.0
|
y2015/src/main/kotlin/adventofcode/y2015/Day14.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2015
import adventofcode.io.AdventSolution
object Day14 : AdventSolution(2015, 14, "Reindeer Olympics") {
override fun solvePartOne(input: String) = parseInput(input)
.maxOfOrNull { it.raceFor(2503) }
override fun solvePartTwo(input: String) = parseInput(input).let { r ->
(1..2503).flatMap { s -> leadsAt(r, s) }
.groupingBy { it }
.eachCount()
.values
.maxOrNull()
}
}
private fun parseInput(distances: String) = distances.lines()
.mapNotNull {
Regex("(\\w+) can fly (\\d+) km/s for (\\d+) seconds, but then must rest for (\\d+) seconds.").matchEntire(
it
)
}
.map { it.destructured }
.map { (name, speed, stamina, rest) ->
RaceReindeer(name, speed.toInt(), stamina.toInt(), rest.toInt())
}
data class RaceReindeer(
private val name: String,
private val speed: Int,
private val stamina: Int,
private val rest: Int
) {
fun raceFor(seconds: Int): Int {
val fullCycles = seconds / (stamina + rest)
val remainingTime = seconds % (stamina + rest)
val racingSeconds = fullCycles * stamina + remainingTime.coerceAtMost(stamina)
return racingSeconds * speed
}
fun speedAt(second: Int) = if (second % (stamina + rest) < stamina) speed else 0
}
private fun leadsAt(reindeer: List<RaceReindeer>, seconds: Int): List<RaceReindeer> {
val race = reindeer.groupBy { it.raceFor(seconds) }.toSortedMap()
return race.getValue(race.lastKey())
}
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 1,561 |
advent-of-code
|
MIT License
|
src/Day08.kt
|
chbirmes
| 572,675,727 | false |
{"Kotlin": 32114}
|
fun main() {
fun part1(input: List<String>): Int {
val grid = parseGrid(input)
val rowScanResult = grid.indices
.fold(emptySet<Pair<Int, Int>>()) { acc, i -> acc + grid.scanRow(i) }
val columnScanResult = grid.first().indices
.fold(emptySet<Pair<Int, Int>>()) { acc, i -> acc + grid.scanColumn(i) }
return (rowScanResult + columnScanResult).size
}
fun part2(input: List<String>): Int {
val grid = parseGrid(input)
return input.indices.flatMap { y ->
input.first().indices.map { x ->
grid.viewNorth(x, y) * grid.viewSouth(x, y) * grid.viewEast(x, y) * grid.viewWest(x, y)
}
}
.max()
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
private fun parseGrid(input: List<String>) =
input.map { line -> line.map { it.digitToInt() } }
private fun List<List<Int>>.column(x: Int): List<Int> =
buildList { [email protected] { line -> add(line[x]) } }
private fun List<Int>.maxIncreasingIndices(): Set<Int> {
val leftScanResult = foldIndexed(Pair(-1, emptySet<Int>())) { index, acc, current ->
if (current > acc.first)
Pair(current, acc.second + index)
else
acc
}
.second
val rightScanResult = foldRightIndexed(Pair(-1, emptySet<Int>())) { index, current, acc ->
if (current > acc.first)
Pair(current, acc.second + index)
else
acc
}
.second
return leftScanResult + rightScanResult
}
private fun List<List<Int>>.scanRow(y: Int) =
this[y].maxIncreasingIndices()
.map { Pair(it, y) }
.toSet()
private fun List<List<Int>>.scanColumn(x: Int) =
column(x).maxIncreasingIndices()
.map { Pair(x, it) }
.toSet()
private fun List<List<Int>>.viewWest(x: Int, y: Int): Int {
val tree = this[y][x]
return this[y].asSequence()
.drop(x + 1)
.countVisibleFrom(tree)
}
private fun List<List<Int>>.viewEast(x: Int, y: Int): Int {
val row = this[y]
val tree = row[x]
return row.asReversed()
.asSequence()
.drop(row.size - x)
.countVisibleFrom(tree)
}
private fun List<List<Int>>.viewSouth(x: Int, y: Int): Int {
val column = column(x)
val tree = column[y]
return column.asSequence()
.drop(y + 1)
.countVisibleFrom(tree)
}
private fun List<List<Int>>.viewNorth(x: Int, y: Int): Int {
val column = column(x)
val tree = column[y]
return column.asReversed()
.asSequence()
.drop(column.size - y)
.countVisibleFrom(tree)
}
private fun Sequence<Int>.countVisibleFrom(fromHeight: Int) =
indexOfFirst { it >= fromHeight }
.let { if (it == -1) count() else it + 1 }
| 0 |
Kotlin
| 0 | 0 |
db82954ee965238e19c9c917d5c278a274975f26
| 2,947 |
aoc-2022
|
Apache License 2.0
|
src/Day05.kt
|
cypressious
| 572,916,585 | false |
{"Kotlin": 40281}
|
fun main() {
class Coordinate(val x: Int, val y: Int)
fun List<Coordinate>.isHorizontal() = this[0].y == this[1].y
fun List<Coordinate>.isVertical() = this[0].x == this[1].x
fun sign(n: Int) = if (n > 0) 1 else -1
fun handle(input: List<String>, countDiagonal: Boolean): Int {
val lines = input
.map { it.split(" -> ") }
.map { line ->
line.map {
val parts = it.split(',')
Coordinate(parts[0].toInt(), parts[1].toInt())
}
}
var maxX = 0
var maxY = 0
for (line in lines) {
for (coordinate in line) {
maxX = maxOf(maxX, coordinate.x)
maxY = maxOf(maxY, coordinate.y)
}
}
val map = Array(maxX + 1) { IntArray(maxY + 1) }
for (line in lines) {
val first = line.first()
val second = line.last()
if (line.isHorizontal()) {
for (x in minOf(first.x, second.x)..maxOf(first.x, second.x)) {
map[x][first.y]++
}
} else if (line.isVertical()) {
for (y in minOf(first.y, second.y)..maxOf(first.y, second.y)) {
map[first.x][y]++
}
} else if (countDiagonal) {
val xStep = sign(second.x - first.x)
val yStep = sign(second.y - first.y)
var x = first.x
var y = first.y
while (x in minOf(first.x, second.x)..maxOf(first.x, second.x)) {
map[x][y]++
x += xStep
y += yStep
}
}
}
return map.sumOf { line -> line.count { it >= 2 } }
}
fun part1(input: List<String>): Int {
return handle(input, false)
}
fun part2(input: List<String>): Int {
return handle(input, true)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == 5)
check(part2(testInput) == 12)
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
169fb9307a34b56c39578e3ee2cca038802bc046
| 2,259 |
AdventOfCode2021
|
Apache License 2.0
|
src/main/kotlin/day13.kt
|
Arch-vile
| 572,557,390 | false |
{"Kotlin": 132454}
|
package day13
import aoc.utils.*
fun part2() {
val result = readInput("day13-input.txt")
.plus("[[2]]")
.plus("[[6]]")
.filter { it != "" }
.map { readList(it) }
.sortedWith { a, b -> compareList(a, b) }
.reversed()
.mapIndexed { index, listing ->
index + 1 to listing
}
.filter {
isNestedListWithOneNumber(it.second, 2) ||
isNestedListWithOneNumber(it.second, 6)
}
.map { it.first }
.reduce { acc, pair -> acc * pair }
println(result)
}
fun isNestedListWithOneNumber(list: Listing, number: Int): Boolean {
return list.children?.size == 1 &&
list.children!![0].children?.size == 1 &&
list.children!![0].children!![0].value == number
}
fun part1() {
val result = readInput("day13-input.txt")
.windowed(2, 3)
.mapIndexed { index, strings ->
val result = compareList(readList(strings[0]), readList(strings[1]))
index + 1 to result
}
.filter { it.second == 1 }
.map { it.first }
.sum()
println(result)
}
data class Listing(val children: List<Listing>?, val value: Int?)
fun compareList(left: Listing, right: Listing): Int {
// Both are numbers
if (left.value != null && right.value != null) {
if (left.value < right.value)
return 1
if (left.value > right.value)
return -1
return 0
}
// Both are lists
if (left.children != null && right.children != null) {
left.children.indices.forEach() { index ->
// Right run out of elements
if (index >= right.children.size)
return -1
val compare = compareList(left.children[index], right.children[index])
if (compare != 0)
return compare
// Left out of items
if (index == left.children.size - 1 && right.children.size >= index + 1) {
return 1
}
}
if (left.children.isEmpty() && !right.children.isEmpty())
return 1
return 0
}
// And lastly if one is number other list
if (left.value != null) {
return compareList(Listing(listOf(Listing(null, left.value)), null), right)
}
if (right.value != null) {
return compareList(left, Listing(listOf(Listing(null, right.value)), null))
}
throw Error("should not end here")
}
fun readList(from: String): Listing {
val trimmed = from.replace("""\s+""".toRegex(), "")
// Empty list
if (trimmed == "[]") {
return Listing(listOf(), null)
}
// Simple list remains, this is either [1] or [1,2,...]
if ("""\[[^\]]*\]""".toRegex().matches(trimmed)) {
val numbers = trimmed.substring(1, trimmed.length - 1).split(",").map { it.toInt() }
val simpleListings = numbers.map { Listing(null, it) }
return Listing(simpleListings, null)
}
// List that must have at least one internal list in it
// [1,[....],...] or [[]]
val parts = mutableListOf<Listing>()
var remains = trimmed.substring(1, trimmed.length - 1)
while (remains != "") {
// Next up a number
if ("""\d+.*""".toRegex().matches(remains)) {
val number = remains.findFirstInt().toString()
remains = remains.removePrefix("$number")
parts.add(Listing(null, number.toInt()))
}
// Next up a list
if (remains.startsWith('[')) {
// TODO: Could write a helper for this thing
val listContent = remains.takeUntilMatch {
val countOpening = it.toList().indexesOf { it == "[" }.size
val countClosing = it.toList().indexesOf { it == "]" }.size
countOpening != 0 && countOpening == countClosing
}
remains = listContent.second
parts.add(readList(listContent.first))
}
// Just skip the commas
if (remains.startsWith(',')) {
remains = remains.drop(1)
}
}
return Listing(parts, null)
}
| 0 |
Kotlin
| 0 | 0 |
e737bf3112e97b2221403fef6f77e994f331b7e9
| 4,171 |
adventOfCode2022
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.