path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day03.kt | kent10000 | 573,114,356 | false | {"Kotlin": 11288} | fun main() {
fun getPriority(letter: Char): Int {
var code = letter.code - 96
if (code < 0) code += 58
return code
}
fun part1(input: List<String>): Int {
var sum = 0
for (line in input) {
val parts = line.chunked(line.length/2) //splits into two
val (compartment1, compartment2) = Pair(parts.component1(), parts.component2())
val same = compartment1.toCharArray().intersect(compartment2.asIterable().toSet())
same.forEach {
sum += getPriority(it)
}
}
return sum
}
fun part2(input: List<String>): Int {
val groups = input.chunked(3)
var sum = 0
for (group in groups) {
val (elf1, elf2, elf3) = Triple(group.component1(), group.component2(), group.component3())
//val same = elf1.toCharArray().intersect(elf2.asIterable().toSet()).intersect(elf3.asIterable().toSet())
for (item in elf1) {
if (elf2.contains(item) && (elf3.contains(item))) {
sum += getPriority(item)
break
}
}
}
return sum
}
/* test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
*/
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c128d05ab06ecb2cb56206e22988c7ca688886ad | 1,463 | advent-of-code-2022 | Apache License 2.0 |
src/day11.kts | miedzinski | 434,902,353 | false | {"Kotlin": 22560, "Shell": 113} | val grid = generateSequence(::readLine).flatMap {
it.asSequence().map(Char::digitToInt)
}.toMutableList()
val gridSize = 10
typealias Grid = MutableList<Int>
data class Point(val x: Int, val y: Int)
operator fun Grid.get(point: Point): Int =
get(point.y * gridSize + point.x)
operator fun Grid.set(point: Point, value: Int): Int =
set(point.y * gridSize + point.x, value)
fun Grid.points(): Sequence<Point> =
(0 until gridSize)
.asSequence()
.flatMap { x ->
(0 until gridSize).asSequence().map { y -> Point(x, y) }
}
fun Point.adjacent(): Sequence<Point> = sequenceOf(
copy(x - 1, y),
copy(x - 1, y - 1),
copy(x - 1, y + 1),
copy(x, y - 1),
copy(x, y + 1),
copy(x + 1, y - 1),
copy(x + 1, y),
copy(x + 1, y + 1),
).filter { (x, y) ->
fun check(n: Int): Boolean = n in 0 until gridSize
check(x) && check(y)
}
fun Grid.tick(): Int {
val queue = grid.points().filter { grid[it] == 9 }.toMutableList()
val visited = queue.toMutableSet()
grid.replaceAll { it + 1 }
while (queue.isNotEmpty()) {
with(queue.removeLast()) {
adjacent()
.filterNot(visited::contains)
.onEach { grid[it]++ }
.filter { grid[it] > 9 }
.onEach { visited.add(it) }
.toCollection(queue)
}
}
grid.replaceAll {
when (it) {
in 0..9 -> it
else -> 0
}
}
return visited.size
}
val nSteps = 100
var part1: Int = 0
var part2: Int? = null
(1..Int.MAX_VALUE).asSequence()
.onEach { step ->
val flashed = grid.tick()
if (step in 1..nSteps) {
part1 += flashed
}
if (part2 == null && flashed == grid.size) {
part2 = step
}
}
.takeWhile {
it <= nSteps || part2 == null
}
.last()
println("part1: $part1")
println("part2: $part2")
| 0 | Kotlin | 0 | 0 | 6f32adaba058460f1a9bb6a866ff424912aece2e | 1,961 | aoc2021 | The Unlicense |
src/Day02.kt | paulbonugli | 574,065,510 | false | {"Kotlin": 13681} | enum class GameChoice() {
ROCK(),
PAPER(),
SCISSORS()
}
enum class GameOutcome(val score: Int) {
WIN(6),
DRAW(3),
LOSE(0)
}
fun main() {
fun parseGameChoice(str: String): GameChoice {
return when (str) {
"A", "X" -> GameChoice.ROCK
"B", "Y" -> GameChoice.PAPER
"C", "Z" -> GameChoice.SCISSORS
else -> {
throw IllegalStateException("Unknown game choice $str")
}
}
}
fun scoreForChoice(choice: GameChoice): Int {
return choice.ordinal + 1
}
fun part1(inputLines: List<String>): Int {
val inputs = inputLines.map { parseGameChoice(it[0].toString()) to parseGameChoice(it[2].toString()) }
fun scoreForOutcome(theirChoice: GameChoice, myChoice: GameChoice): Int {
return when (myChoice) {
GameChoice.ROCK -> when (theirChoice) {
GameChoice.ROCK -> GameOutcome.DRAW
GameChoice.PAPER -> GameOutcome.LOSE
GameChoice.SCISSORS -> GameOutcome.WIN
}
GameChoice.PAPER -> when (theirChoice) {
GameChoice.ROCK -> GameOutcome.WIN
GameChoice.PAPER -> GameOutcome.DRAW
GameChoice.SCISSORS -> GameOutcome.LOSE
}
GameChoice.SCISSORS -> when (theirChoice) {
GameChoice.ROCK -> GameOutcome.LOSE
GameChoice.PAPER -> GameOutcome.WIN
GameChoice.SCISSORS -> GameOutcome.DRAW
}
}.score
}
val scores = inputs.map {
scoreForChoice(it.second) + scoreForOutcome(it.first, it.second)
}
return scores.sum()
}
fun part2(inputLines: List<String>): Int {
fun parseOutcome(str: String): GameOutcome {
return when (str) {
"X" -> GameOutcome.LOSE
"Y" -> GameOutcome.DRAW
"Z" -> GameOutcome.WIN
else -> {
throw IllegalStateException("Unknown game outcome $str")
}
}
}
val inputs = inputLines.map { parseGameChoice(it[0].toString()) to parseOutcome(it[2].toString()) }
fun determineChoice(theirChoice: GameChoice, desiredOutcome: GameOutcome): GameChoice {
var idx = theirChoice.ordinal
if (desiredOutcome == GameOutcome.WIN) {
idx += 1
// 3 -> 0
if (idx > 2) {
idx -= 3
}
} else if (desiredOutcome == GameOutcome.LOSE) {
idx -= 1
// -1 -> 2
if (idx < 0) {
idx += 3
}
}
return GameChoice.values()[idx]
}
val scores = inputs.map {
scoreForChoice(determineChoice(it.first, it.second)) + it.second.score
}
return scores.sum()
}
val lines = readInput("Day02")
println("Part 1: " + part1(lines))
println("Part 2: " + part2(lines))
}
| 0 | Kotlin | 0 | 0 | d2d7952c75001632da6fd95b8463a1d8e5c34880 | 3,161 | aoc-2022-kotlin | Apache License 2.0 |
src/Day02.kt | Excape | 572,551,865 | false | {"Kotlin": 36421} | fun main() {
fun part1(input: List<String>): Int {
val mapOfResults = mapOf(
"A X" to 1 + 3,
"A Y" to 2 + 6,
"A Z" to 3 + 0,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 1 + 6,
"C Y" to 2 + 0,
"C Z" to 3 + 3,
)
return input.sumOf { mapOfResults[it]!! }
}
fun part2(input: List<String>): Int {
val mapOfResults = mapOf(
"A X" to 0 + 3,
"A Y" to 3 + 1,
"A Z" to 6 + 2,
"B X" to 0 + 1,
"B Y" to 3 + 2,
"B Z" to 6 + 3,
"C X" to 0 + 2,
"C Y" to 3 + 3,
"C Z" to 6 + 1,
)
return input.sumOf { mapOfResults[it]!! }
}
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)}")
}
| 0 | Kotlin | 0 | 0 | a9d7fa1e463306ad9ea211f9c037c6637c168e2f | 1,037 | advent-of-code-2022 | Apache License 2.0 |
src/day09/Day09.kt | marcBrochu | 573,884,748 | false | {"Kotlin": 12896} | package day09
import readInput
import day09.Direction.*
import kotlin.math.sign
data class Point(var x: Int, var y: Int) {
fun move(direction: Direction, distance: Int = 1) = when (direction) {
EAST -> x += distance
WEST -> x -= distance
NORTH -> y += distance
SOUTH -> y -= distance
}
fun moveOneToPoint(otherPoint: Point) {
this.x += (otherPoint.x - this.x).sign
this.y += (otherPoint.y - this.y).sign
}
fun getAdjacent(): List<Point> = listOf(
Point(x - 1, y - 1), Point(x, y - 1), Point(x + 1, y - 1),
Point(x - 1, y), Point(x + 1, y),
Point(x - 1, y + 1), Point(x, y + 1), Point(x + 1, y + 1)
)
}
enum class Direction {
NORTH, EAST, SOUTH, WEST;
}
fun main() {
fun part1(input: List<String>): Int {
val head = Point(0,0)
val tail = Point(0, 0)
val visited = mutableSetOf(Point(0,0))
for (line in input) {
val direction: Direction = when(line.substringBefore(" ")) {
"U" -> NORTH
"L" -> WEST
"R" -> EAST
"D" -> SOUTH
else -> error("")
}
repeat(line.substringAfter(" ").toInt()) {
head.move(direction)
if (tail !in head.getAdjacent()) {
tail.moveOneToPoint(head)
visited.add(tail.copy())
}
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val knots = MutableList(10) {Point(0,0)}
val visited = mutableSetOf(Point(0,0))
for (line in input) {
val direction: Direction = when(line.substringBefore(" ")) {
"U" -> NORTH
"L" -> WEST
"R" -> EAST
"D" -> SOUTH
else -> error("")
}
repeat(line.substringAfter(" ").toInt()) {
knots[0].move(direction)
knots.drop(1).indices.forEach { index ->
val head = knots[index]
val tail = knots[index + 1]
if (tail !in head.getAdjacent()) {
tail.moveOneToPoint(head)
visited.add(knots.last().copy())
}
}
}
}
return visited.size
}
val input = readInput("day09/Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 8d4796227dace8b012622c071a25385a9c7909d2 | 2,509 | advent-of-code-kotlin | Apache License 2.0 |
src/day05/Day05.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day05
import readInput
import java.util.Stack
private data class Action(val amount: Int, val from: Int, val to: Int) {
companion object {
fun from(input: String): Action? {
val regex = """move (\d*) from (\d*) to (\d*)""".toRegex()
val result = regex.matchEntire(input) ?: return null
return Action(result.groupValues[1].toInt(), result.groupValues[2].toInt(), result.groupValues[3].toInt())
}
}
}
fun main() {
fun part1(testInput: List<String>): String {
val stackSize =
testInput.firstOrNull { it.startsWith(" 1") }?.filter { !it.isWhitespace() }?.length ?: return ""
val stackArray = Array<Stack<Char>>(stackSize) { Stack() }
val conditions = testInput.filter { it.trim().startsWith('[') }
conditions.reversed().forEach { condition ->
(0 until stackSize).forEach { index ->
if (condition.length > index * 4 + 1) {
val char = condition[index * 4 + 1]
if (!char.isWhitespace()) {
stackArray[index].push(char)
}
}
}
}
val actions = testInput.filter { it.startsWith("move") }.mapNotNull { Action.from(it) }
actions.forEach { action ->
var count = 0
while (count < action.amount) {
stackArray[action.to - 1].push(stackArray[action.from - 1].pop())
count++
}
}
return stackArray.map { it.pop() }.joinToString("")
}
fun part2(testInput: List<String>): String {
val stackSize =
testInput.firstOrNull { it.startsWith(" 1") }?.filter { !it.isWhitespace() }?.length ?: return ""
val stackArray = Array<Stack<Char>>(stackSize) { Stack() }
val conditions = testInput.filter { it.trim().startsWith('[') }
conditions.reversed().forEach { condition ->
(0 until stackSize).forEach { index ->
if (condition.length > index * 4 + 1) {
val char = condition[index * 4 + 1]
if (!char.isWhitespace()) {
stackArray[index].push(char)
}
}
}
}
val actions = testInput.filter { it.startsWith("move") }.mapNotNull { Action.from(it) }
actions.forEach { action ->
val holder = mutableListOf<Char>()
var count = 0
while (count < action.amount) {
holder.add(stackArray[action.from - 1].pop())
count++
}
holder.reversed().forEach {
stackArray[action.to - 1].push(it)
}
}
return stackArray.map { it.pop() }.joinToString("")
}
val testInput = readInput("day05/Day05_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 2,938 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2022/Day13.kt | nguyen-anthony | 572,781,123 | false | null | package aoc2022
import utils.readInputAsList
import kotlin.math.min
fun main() {
data class NumberOrList(
var number: Int?,
var list: List<NumberOrList>?,
val isDivider: Boolean
) {
constructor(
value: Int,
isDivider: Boolean = false,
) : this(value, null, isDivider)
constructor(
value: List<NumberOrList>,
isDivider: Boolean = false
) : this(null, value, isDivider)
private fun isNumber() = number != null
fun isLessThan(other: NumberOrList): Int {
if(this.isNumber() && other.isNumber()) {
return if(this.number!! < other.number!!) {
-1
} else if (this.number!! > other.number!!) {
1
} else {
0
}
}
if(!this.isNumber() && !other.isNumber()) {
val size = min(this.list!!.size, other.list!!.size)
return (0 until size).map { this.list!![it].isLessThan(other.list!![it]) }.firstOrNull { it != 0 }
?: if (this.list!!.size < other.list!!.size) {
-1
} else if (this.list!!.size > other.list!!.size) {
1
} else {
0
}
}
if (this.isNumber()) {
return NumberOrList(listOf(this)).isLessThan(other)
}
return this.isLessThan(NumberOrList(listOf(other)))
}
}
fun parseData(input: String, isDivider: Boolean = false) : NumberOrList {
val allParents = ArrayDeque<MutableList<NumberOrList>>()
var currentList: MutableList<NumberOrList>? = null
var i = 0
while(i < input.length) {
when(input[i]) {
in '0'..'0' -> {
var finalIndex = i + 1
while(input[finalIndex] != ',' && input[finalIndex] != ']') {
finalIndex++
}
val values = NumberOrList(input.substring(i, finalIndex).toInt())
currentList?.add(values)
i = finalIndex
}
'[' -> {
currentList?.also { allParents.add(it) }
currentList = mutableListOf()
i++
}
']' -> {
allParents.removeLastOrNull()?.also { parent ->
currentList?.also { parent.add(NumberOrList(it)) }
currentList = parent
}
i++
}
else -> i++
}
}
return NumberOrList(currentList!!, isDivider)
}
fun part1(input: List<String>) : Any {
return input.windowed(2, 3).mapIndexed { index, it ->
val (left, right) = it
val result = parseData(left).isLessThan(parseData(right))
if (result == -1){
index + 1
} else 0
}.sum()
}
fun part2(input: List<String>) : Any {
val parsedInput = input.filter { it.isNotEmpty() }.map { parseData(it) }
val inputDividers = mutableListOf(parseData("[[2]]", isDivider = true), parseData("[[6]]", isDivider = true)).apply { addAll(parsedInput) }
return inputDividers.sortedWith { a: NumberOrList, b: NumberOrList -> a.isLessThan(b) }
.mapIndexed { index, value ->
if (value.isDivider) {
index + 1
} else {
0
}
}
.filter { it != 0}
.reduce(Int::times)
}
val input = readInputAsList("Day13", "2022")
println(part1(input))
println(part2(input))
val testInput = readInputAsList("Day13_test", "2022")
check(part1(testInput) == 0)
check(part2(testInput) == 0)
} | 0 | Kotlin | 0 | 0 | 9336088f904e92d801d95abeb53396a2ff01166f | 4,026 | AOC-2022-Kotlin | Apache License 2.0 |
src/Day04.kt | strindberg | 572,685,170 | false | {"Kotlin": 15804} | data class RangePair(val start1: Int, val end1: Int, val start2: Int, val end2: Int)
fun ranges(line: String): RangePair {
val pair1 = line.split(",")[0].split("-")
val pair2 = line.split(",")[1].split("-")
return RangePair(pair1[0].toInt(), pair1[1].toInt(), pair2[0].toInt(), pair2[1].toInt())
}
fun main() {
fun part1(input: List<String>): Int =
input.fold(0) { count, line ->
val rs = ranges(line)
if ((rs.start1 <= rs.start2 && rs.end1 >= rs.end2) || ((rs.start2 <= rs.start1 && rs.end2 >= rs.end1)))
count + 1
else
count
}
fun part2(input: List<String>): Int =
input.fold(0) { count, line ->
val rs = ranges(line)
if (rs.end1 < rs.start2 || rs.start1 > rs.end2)
count
else
count + 1
}
val input = readInput("Day04")
println(part1(input))
check(part1(input) == 509)
println(part2(input))
check(part2(input) == 870)
}
| 0 | Kotlin | 0 | 0 | c5d26b5bdc320ca2aeb39eba8c776fcfc50ea6c8 | 1,092 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | makohn | 571,699,522 | false | {"Kotlin": 35992} | fun main() {
operator fun IntRange.contains(other: IntRange) = other.first >= this.first && other.last <= this.last
infix fun IntRange.overlapsWith(other: IntRange) = (
(other.first >= this.first && other.last <= this.last) ||
(other.first >= this.first && other.first <= this.last) ||
(other.last >= this.first && other.last <= this.last))
fun part1(input: List<String>): Int {
var count = 0
val pairs = mutableListOf<Pair<IntRange, IntRange>>()
for (l in input) {
val p = l.split(",")
val p1 = p[0].split("-")
val p2 = p[1].split("-")
val s1 = p1[0].toInt()
val e1 = p1[1].toInt()
val s2 = p2[0].toInt()
val e2 = p2[1].toInt()
pairs.add(s1..e1 to s2 .. e2)
}
for (pair in pairs) {
if ((pair.first in pair.second) || (pair.second in pair.first)) {
count ++
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
val pairs = mutableListOf<Pair<IntRange, IntRange>>()
for (l in input) {
val p = l.split(",")
val p1 = p[0].split("-")
val p2 = p[1].split("-")
val s1 = p1[0].toInt()
val e1 = p1[1].toInt()
val s2 = p2[0].toInt()
val e2 = p2[1].toInt()
pairs.add(s1..e1 to s2 .. e2)
}
for (pair in pairs) {
if ((pair.first overlapsWith pair.second) || (pair.second overlapsWith pair.first)) {
count ++
}
}
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2734d9ea429b0099b32c8a4ce3343599b522b321 | 1,955 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | jarmstrong | 572,742,103 | false | {"Kotlin": 5377} | fun main() {
data class SectionIDRange(val startSectionId: Int, val endSectionId: Int)
data class ElfPair(val firstElf: SectionIDRange, val secondElf: SectionIDRange)
fun List<String>.createElfPairs(): List<ElfPair> {
return map {
val linePair = it.split(",").map { rangeString ->
val range = rangeString.split("-")
SectionIDRange(range.first().toInt(), range.last().toInt())
}
ElfPair(linePair.first(), linePair.last())
}
}
fun part1(input: List<String>): Int {
return input
.createElfPairs()
.count {
(it.firstElf.startSectionId >= it.secondElf.startSectionId && it.firstElf.endSectionId <= it.secondElf.endSectionId) ||
(it.secondElf.startSectionId >= it.firstElf.startSectionId && it.secondElf.endSectionId <= it.firstElf.endSectionId)
}
}
fun part2(input: List<String>): Int {
return input
.createElfPairs()
.count {
val firstRange = (it.firstElf.startSectionId..it.firstElf.endSectionId).toSet()
val secondRange = (it.secondElf.startSectionId..it.secondElf.endSectionId).toSet()
firstRange.intersect(secondRange).isNotEmpty()
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bba73a80dcd02fb4a76fe3938733cb4b73c365a6 | 1,499 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | BenHopeITC | 573,352,155 | false | null | private fun String.isFileWithSize() = split(" ").first().toIntOrNull() != null
private fun String.isMoveToChildDirectory() = startsWith("\$ cd") && !endsWith("..")
private fun String.isMoveToParentDirectory() = startsWith("\$ cd") && (endsWith("..") || endsWith("/"))
private fun String.movePathOneBack() = substringBeforeLast("/").ifBlank { "/" }
fun main() {
val day = "Day07"
fun directoryContents(input: List<String>): MutableMap<String, Int> {
val directoryContents = mutableMapOf<String, Int>()
var currentDirectory = "/"
input.forEach {
when {
it.isMoveToParentDirectory() -> currentDirectory = currentDirectory.movePathOneBack()
it.isMoveToChildDirectory() -> currentDirectory =
"$currentDirectory/${it.split(" ").last()}".replace("//", "/")
it.isFileWithSize() -> {
val fileSize = it.split(" ").first().toInt()
var directoryWithPath = currentDirectory
do {
val totalSize = directoryContents.getOrDefault(directoryWithPath, 0) + fileSize
directoryContents[directoryWithPath] = totalSize
if(directoryWithPath.equals("/")) break
directoryWithPath = directoryWithPath.movePathOneBack()
} while (true)
}
}
}
return directoryContents
}
fun part1(input: List<String>): Int {
val directoryContents = directoryContents(input)
return directoryContents.filter { it.value <= 100_000 }.values.sum()
}
fun part2(input: List<String>): Int {
val foo = directoryContents(input)
val totalFree = 70_000_000 - foo["/"]!!
return foo.map { it.value }.sorted().first { totalFree+it > 30_000_000 }
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("${day}_test")
// println(part1(testInput))
// check(part1(testInput) == 95_437)
// test if implementation meets criteria from the description, like:
// val testInput2 = readInput("${day}_test")
// println(part2(testInput2))
// check(part2(testInput2) == 24_933_642)
val input = readInput(day)
println(part1(input))
println(part2(input))
check(part1(input) == 1_792_222)
check(part2(input) == 1_112_963)
}
| 0 | Kotlin | 0 | 0 | 851b9522d3a64840494b21ff31d83bf8470c9a03 | 2,440 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/tonnoz/adventofcode23/day19/Day19.kt | tonnoz | 725,970,505 | false | {"Kotlin": 78395} | package com.tonnoz.adventofcode23.day19
import com.tonnoz.adventofcode23.utils.println
import com.tonnoz.adventofcode23.utils.readInput
import kotlin.system.measureTimeMillis
object Day19 {
data class Workflow(val name: String, val rules: List<Rule>)
data class Rule(val part: Char, val next: String, val condition: ((Char, Int) -> Boolean)? = null) {
fun check(aPart: Char, aRating: Int?) = if(aRating == null) false else condition?.invoke(aPart, aRating) ?: true
}
data class PartsRating(val parts: List<Map<Char, Int>>)
@JvmStatic
fun main(args: Array<String>) {
val input = "input19.txt".readInput()
println("time part1: ${measureTimeMillis { part1(input).println() }}ms")
}
private fun part1(input: List<String>): Long {
val (workflowsS, ratingsS) = input.splitByEmptyLine()
val ratings = parseRatings(ratingsS)
val workflows = parseWorkflows(workflowsS)
return processWorkflows(workflows, ratings)
}
private fun processWorkflows(workflows: List<Workflow>, ratings: PartsRating): Long {
val toProcess = makePartListToWorkflow(ratings, workflows)
val acceptedParts = mutableListOf<Int>()
while (toProcess.isNotEmpty()) {
val (partListIndex, workflow) = toProcess.removeFirst()
val partMap = ratings.parts[partListIndex]
for (rule in workflow.rules) {
when {
rule.next == "R" && rule.part == '*' -> { break }
rule.next == "A" && rule.part == '*' -> { acceptedParts.addAll(partMap.values); break }
rule.part == '*' -> { toProcess.add(Pair(partListIndex, workflows.first { it.name == rule.next })); break }
rule.next == "R" && rule.check(rule.part, partMap[rule.part]) -> { break }
rule.next == "A" && rule.check(rule.part, partMap[rule.part]) -> { acceptedParts.addAll(partMap.values); break }
rule.check(rule.part, partMap[rule.part]) -> { toProcess.add(Pair(partListIndex, workflows.first { it.name == rule.next })); break }
}
}
}
return acceptedParts.sum().toLong()
}
private fun makePartListToWorkflow(ratings: PartsRating, workflows: List<Workflow>): MutableList<Pair<Int, Workflow>> =
ratings.parts.indices.map { i -> Pair(i, workflows.first { it.name == "in" }) }.toMutableList()
private fun List<String>.splitByEmptyLine() =
this.takeWhile { it.isNotEmpty() } to this.dropWhile { it.isNotEmpty() }.drop(1)
private fun parseRatings(ratingsS: List<String>) =
PartsRating(
ratingsS.map {
it.drop(1).dropLast(1).split(",").associate { rating ->
val (key, value) = rating.split("=")
key.first() to value.toInt()
}
}
)
private fun parseWorkflows(workflowsS: List<String>) = workflowsS.map { workflow ->
val (name, rulesS) = workflow.dropLast(1).split("{")
val rulesSplit = rulesS.split(",")
val rules = rulesSplit.dropLast(1).map { rule ->
val (part, operator) = rule.first() to rule[1]
val (value, nextWorkflow) = rule.substring(2).split(":")
when (operator) {
'>' -> Rule(part, nextWorkflow) { aPart, aRating -> part == aPart && aRating > value.toInt() }
'<' -> Rule(part, nextWorkflow) { aPart, aRating -> part == aPart && aRating < value.toInt() }
else -> throw IllegalArgumentException("Unknown operator")
}
}
val fallbackRule = Rule('*', rulesSplit.last())
Workflow(name, rules + fallbackRule)
}
} | 0 | Kotlin | 0 | 0 | d573dfd010e2ffefcdcecc07d94c8225ad3bb38f | 3,474 | adventofcode23 | MIT License |
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day19.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2020
import com.dvdmunckhof.aoc.splitOnce
class Day19(input: String) {
private val inputRules: List<String>
private val inputMessages: List<String>
init {
val (rules, messages) = input.splitOnce("\n\n")
inputRules = rules.split("\n")
inputMessages = messages.split("\n")
}
fun solvePart1(): Int {
val rules = parseRules(inputRules)
return inputMessages.count { matchRule(rules, it, listOf(0)) }
}
fun solvePart2(): Int {
val updatedRules = listOf("8: 42 | 42 8", "11: 42 31 | 42 11 31")
val rules = parseRules(inputRules + updatedRules).toSortedMap()
return inputMessages.count { matchRule(rules, it, listOf(0)) }
}
private fun matchRule(rules: Map<Int, Rule>, message: String, stack: List<Int>): Boolean {
if (stack.isEmpty()) {
return message.isEmpty()
}
return when (val rule = rules.getValue(stack.first())) {
is Rule.Literal -> message.startsWith(rule.value) && matchRule(rules, message.drop(1), stack.drop(1))
is Rule.Reference -> rule.groups.any { group -> matchRule(rules, message, group + stack.drop(1)) }
}
}
private fun parseRules(rules: List<String>): Map<Int, Rule> {
return rules.associate { rule ->
val (key, value) = rule.splitOnce(": ")
key.toInt() to if (value.startsWith('"')) {
Rule.Literal(value.elementAt(1))
} else {
Rule.Reference(value.split(" | ").map { it.split(" ").map(String::toInt) })
}
}
}
sealed class Rule {
class Literal(val value: Char) : Rule()
class Reference(val groups: List<List<Int>>) : Rule()
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,782 | advent-of-code | Apache License 2.0 |
src/main/day14/day14.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day14
import kotlin.math.max
import kotlin.math.min
import readInput
private typealias Cave = MutableSet<Point>
private typealias Rock = Point
private typealias Grain = Point
private data class Point(val x: Int, val y: Int)
private val source = Point(500, 0)
fun main() {
val input = readInput("main/day14/Day14_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val cave = input.parseTosSolidRock()
return cave.pourSand()
}
fun part2(input: List<String>): Int {
val cave = input.parseTosSolidRock()
val maxX = cave.maxOf { it.x } //.also { println("max x: $it") }
val minX = cave.minOf { it.x } //.also { println("min x: $it") }
val floorY = cave.maxOf { it.y } + 2
cave.addRock(Point(minX - 1500, floorY), Point(maxX + 1500, floorY))
return cave.pourSand()
}
private fun Cave.pourSand(): Int {
val startSize = size
do {
val droppedGrain = source.fall(this)
if (droppedGrain != null) add(droppedGrain)
if (size % 1000 == 0) println(size)
} while (droppedGrain != null)
return size - startSize
}
private fun Grain.fall(cave: Cave): Grain? {
if (cave.contains(source))
return null
if (down().y > cave.maxOf { it.y }) return null
if (!cave.contains(down())) return down().fall(cave)
if (!cave.contains(downLeft())) return downLeft().fall(cave)
if (!cave.contains(downRight())) return downRight().fall(cave)
return this
}
private fun Cave.addRock(start: Point, end: Point) {
val startX = min(start.x, end.x)
val startY = min(start.y, end.y)
val endX = max(start.x, end.x)
val endY = max(start.y, end.y)
(startX..endX).forEach { x ->
(startY..endY).forEach { y ->
add(Rock(x, y))
}
}
}
private fun List<String>.parseTosSolidRock(): Cave {
val cave = mutableSetOf<Point>()
map { line ->
line.split(" -> ")
.map { it.split(", ") }
.windowed(2) { (start, end) ->
cave.addRock(
rock(start.first()),
rock(end.first())
)
}
}
return cave
}
private fun rock(point: String): Rock {
return point.split(",").map { it.toInt() }.let { (x, y) ->
Point(x, y)
}
}
private fun Grain.down() = copy(y = y + 1)
private fun Grain.downLeft() = copy(x = x - 1, y = y + 1)
private fun Grain.downRight() = copy(x = x + 1, y = y + 1)
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 2,490 | aoc-2022 | Apache License 2.0 |
src/Day23.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun readElvesArray(input: List<String>): Array<Coords> {
val resultList = mutableListOf<Coords>()
input.forEachIndexed { rowIndex, s ->
s.forEachIndexed { index, c ->
if (c == '#')
resultList.add(Coords(index, rowIndex))
}
}
return resultList.toTypedArray()
}
fun getMoveProposal(coords: Coords, elvesSet: MutableSet<Coords>, direction: Int): Coords {
if (movesToAdjacent.all {
!elvesSet.contains(getNewCoords(coords, it))
})
return coords
for (i in 0..3) {
val currentDirection = (direction + i) % 4
val checkMove = checkMoveArray[currentDirection]
if (checkMove.checks.all {
!elvesSet.contains(getNewCoords(coords, it))
})
return getNewCoords(coords, checkMove.move)
}
return coords
}
fun getNextMove(
elvesArray: Array<Coords>,
elvesSet: MutableSet<Coords>,
direction: Int
): Boolean {
val moveProposals: Array<Coords> = Array(elvesArray.size) {
getMoveProposal(elvesArray[it], elvesSet, direction)
}
val proposalMap: MutableMap<Coords, List<Int>> = mutableMapOf()
moveProposals.forEachIndexed { index, coords ->
if (moveProposals[index] != elvesArray[index])
proposalMap.merge(coords, listOf(index)) { list1, list2 ->
list1.plus(list2)
}
}
proposalMap
.filter { entry -> entry.value.size == 1 }
.forEach { (_, indexList) ->
indexList.forEach {
elvesSet.remove(elvesArray[it])
elvesArray[it] = moveProposals[it]
elvesSet.add(elvesArray[it])
}
}
return proposalMap
.filter { entry -> entry.value.size == 1 }
.isNotEmpty()
}
fun part1(input: List<String>): Int {
val elvesArray: Array<Coords> = readElvesArray(input)
val elvesSet = elvesArray.toMutableSet()
var direction = 0
repeat(10) {
getNextMove(elvesArray, elvesSet, direction)
direction = (direction + 1) % 4
}
var north = Int.MAX_VALUE
var south = Int.MIN_VALUE
var east = Int.MIN_VALUE
var west = Int.MAX_VALUE
elvesArray.forEach {
north = min(north, it.y)
south = max(south, it.y)
east = max(east, it.x)
west = min(west, it.x)
}
return (south - north + 1) * (east - west + 1) - elvesArray.size
}
fun part2(input: List<String>): Int {
val elvesArray: Array<Coords> = readElvesArray(input)
val elvesSet = elvesArray.toMutableSet()
var direction = 0
var iterationCount = 0
do {
iterationCount++
val wasMoved = getNextMove(elvesArray, elvesSet, direction)
direction = (direction + 1) % 4
} while (wasMoved)
return iterationCount
}
val testInput = readInput("Day23_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
private data class DirectionCheckMove(
val checks: List<Move>,
val move: Move
)
private val checkMoveArray = arrayOf(
// north
DirectionCheckMove(
listOf(Move(-1, -1), Move(0, -1), Move(1, -1)),
Move(0, -1)
),
// south
DirectionCheckMove(
listOf(Move(-1, 1), Move(0, 1), Move(1, 1)),
Move(0, 1)
),
// west
DirectionCheckMove(
listOf(Move(-1, -1), Move(-1, 0), Move(-1, 1)),
Move(-1, 0)
),
// east
DirectionCheckMove(
listOf(Move(1, -1), Move(1, 0), Move(1, 1)),
Move(1, 0)
)
)
private val movesToAdjacent = arrayOf(
Move(-1, -1),
Move(-1, 0),
Move(-1, 1),
Move(0, -1),
Move(0, 1),
Move(1, -1),
Move(1, 0),
Move(1, 1)
) | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 4,202 | AdventOfCode2022 | Apache License 2.0 |
src/Day04.kt | oleskrede | 574,122,679 | false | {"Kotlin": 24620} | fun main() {
fun part1(input: List<String>): Int {
return input.map { it.split(",") }
.count { (a, b) ->
val (aStart, aEnd) = a.split("-").map { it.toInt() }
val (bStart, bEnd) = b.split("-").map { it.toInt() }
val aInB = aStart >= bStart && aEnd <= bEnd
val bInA = bStart >= aStart && bEnd <= aEnd
aInB || bInA
}
}
fun part2(input: List<String>): Int {
return input.map { it.split(",") }
.count { (a, b) ->
val (aStart, aEnd) = a.split("-").map { it.toInt() }
val (bStart, bEnd) = b.split("-").map { it.toInt() }
aStart in bStart..bEnd || bStart in aStart..aEnd
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
test(part1(testInput), 2)
test(part2(testInput), 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a3484088e5a4200011335ac10a6c888adc2c1ad6 | 1,044 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/kotlin/codes/jakob/aoc/solution/Day07.kt | loehnertz | 725,944,961 | false | {"Kotlin": 59236} | package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.*
import codes.jakob.aoc.solution.Day07.HandType.*
object Day07 : Solution() {
private val handComparator: Comparator<Hand> = compareBy(
{ it.type },
{ it.cards[0] },
{ it.cards[1] },
{ it.cards[2] },
{ it.cards[3] },
{ it.cards[4] },
)
override fun solvePart1(input: String): Any {
return calculateWinnings(input, jIsJoker = false)
}
override fun solvePart2(input: String): Any {
return calculateWinnings(input, jIsJoker = true)
}
private fun calculateWinnings(input: String, jIsJoker: Boolean): Int {
return parseHands(input, jIsJoker)
.sortedWith(handComparator)
.associateByIndex()
.mapKeys { (index, _) -> index + 1 }
.entries
.fold(0) { winnings, (index, hand) ->
winnings + hand.bid * index
}
}
private fun parseHands(input: String, jIsJoker: Boolean = false): List<Hand> {
return input.splitByLines().map { line ->
val (handString, bidString) = line.split(" ")
Hand(handString.splitByCharacter().map { Card.fromSymbol(it, jIsJoker) }, bidString.toInt())
}
}
private data class Hand(
val cards: List<Card>,
val bid: Int,
) {
init {
require(cards.count() == 5) { "A hand must consist of exactly 5 cards" }
}
val type: HandType = determineType()
private fun determineType(): HandType {
val valueCounts: Map<Int, Int> = cards
.groupBy { it.value }
.mapValues { (_, cards) -> cards.count() }
val bestNaturalType: HandType = when (valueCounts.values.maxOrNull()) {
5 -> FIVE_OF_A_KIND
4 -> FOUR_OF_A_KIND
3 -> if (valueCounts.values.containsTimes(2, 1)) FULL_HOUSE else THREE_OF_A_KIND
2 -> if (valueCounts.values.containsTimes(2, 2)) TWO_PAIRS else ONE_PAIR
1 -> HIGH_CARD
else -> error("A hand must have at least one card")
}
val jokerCount: Int = cards.count { it.isJoker }
return if (jokerCount > 0) {
when (bestNaturalType) {
HIGH_CARD -> {
when (jokerCount) {
1 -> ONE_PAIR
2 -> THREE_OF_A_KIND
3 -> FOUR_OF_A_KIND
else -> FIVE_OF_A_KIND
}
}
// If the pair are jokers, the highest possible hand is a three of a kind
ONE_PAIR -> {
when (jokerCount) {
1 -> THREE_OF_A_KIND
2 -> THREE_OF_A_KIND
else -> FIVE_OF_A_KIND
}
}
TWO_PAIRS -> {
when (jokerCount) {
1 -> FULL_HOUSE
2 -> FOUR_OF_A_KIND
else -> FIVE_OF_A_KIND
}
}
// If the three of a kind are jokers, the highest possible hand is a four of a kind
THREE_OF_A_KIND -> {
when (jokerCount) {
1 -> FOUR_OF_A_KIND
3 -> FOUR_OF_A_KIND
else -> FIVE_OF_A_KIND
}
}
FULL_HOUSE -> {
when (jokerCount) {
1 -> FOUR_OF_A_KIND
else -> FIVE_OF_A_KIND
}
}
FOUR_OF_A_KIND -> FIVE_OF_A_KIND
FIVE_OF_A_KIND -> FIVE_OF_A_KIND
}
} else bestNaturalType
}
override fun toString(): String {
return "Hand(cards=${cards.joinToString("")}, bid=$bid)"
}
}
private data class Card(
val value: Int,
) : Comparable<Card> {
val isJoker: Boolean = value == 1
init {
require(value in VALUE_RANGE || isJoker) { "A card must have a value between 2 and 14 or be a joker" }
}
private fun convertToSymbol(): Char {
return when (value) {
14 -> 'A'
13 -> 'K'
12 -> 'Q'
11 -> 'J'
10 -> 'T'
1 -> 'J'
else -> value.digitToChar()
}
}
override fun compareTo(other: Card): Int = this.value.compareTo(other.value)
override fun toString(): String = convertToSymbol().toString()
companion object {
private val VALUE_RANGE: IntRange = 2..14
fun fromSymbol(symbol: Char, jIsJoker: Boolean = false): Card {
return when (symbol) {
'A' -> Card(14)
'K' -> Card(13)
'Q' -> Card(12)
'J' -> if (!jIsJoker) Card(11) else Card(1)
'T' -> Card(10)
else -> Card(symbol.parseInt())
}
}
}
}
private enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIRS,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND;
}
}
fun main() = Day07.solve()
| 0 | Kotlin | 0 | 0 | 6f2bd7bdfc9719fda6432dd172bc53dce049730a | 5,638 | advent-of-code-2023 | MIT License |
src/main/kotlin/com/groundsfam/advent/y2020/d19/Day19.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2020.d19
import com.groundsfam.advent.DATAPATH
import kotlin.io.path.div
import kotlin.io.path.useLines
class Solver(private val rules: Map<Int, Rule>, private val string: String, private val partTwo: Boolean = false) {
data class Key(val from: Int, val to: Int, val rule: Int)
private val dp = mutableMapOf<Key, Boolean>()
fun matches(): Boolean {
return checkMatches(0, string.length, 0)
}
private fun checkMatches(from: Int, to: Int, rule: Int): Boolean {
val key = Key(from, to, rule)
if (key in dp) return dp[key]!!
if (partTwo) {
if (rule == 8) {
return (from != to && checkMatches8(from, to))
.also { dp[key] = it }
}
if (rule == 11) {
return (from != to && checkMatches11(from, to))
.also { dp[key] = it }
}
}
return when (val r = rules[rule]) {
is LiteralRule ->
string.substring(from, to) == r.literal
is SequenceRule ->
checkMatchesSequence(from, to, r.rules)
is OrRule ->
checkMatchesSequence(from, to, r.leftRules) || checkMatchesSequence(from, to, r.rightRules)
else ->
throw RuntimeException("Rule $rule not found")
}.also {
dp[key] = it
}
}
private fun checkMatchesSequence(from: Int, to: Int, rules: List<Int>): Boolean {
if (rules.isEmpty()) {
// if we've found matches on all the rules, the sequence match was successful
// iff we used the whole string
return from == to
}
return (from+1..to).any { mid ->
checkMatches(from, mid, rules[0]) && checkMatchesSequence(mid, to, rules.subList(1, rules.size))
}
}
// special case: in part two, the rule is
// 8: 42 | 8 42
// which means "any number of 42s"
private fun checkMatches8(from: Int, to: Int): Boolean {
if (from == to) return true
return (from+1..to).any { mid ->
checkMatches(from, mid, 42) && checkMatches8(mid, to)
}
}
// special case: in part two, the rule is
// 11: 42 31 | 42 11 31
// which means any number of 42s, followed by the same number of 31s
private fun checkMatches11(from: Int, to: Int): Boolean {
if (from == to) return true
return (from+1 until to).any { mid1 ->
checkMatches(from, mid1, 42) && (mid1 until to).any { mid2 ->
checkMatches11(mid1, mid2) && checkMatches(mid2, to, 31)
}
}
}
}
fun main() {
val (rules, messages) = (DATAPATH / "2020/day19.txt")
.useLines { it.toList() }
.let { lines ->
(lines
.takeWhile { it.isNotBlank() }
.let { RuleParser(it).parsedRules }
to lines.takeLastWhile { it.isNotBlank() })
}
messages.count {
Solver(rules, it).matches()
}.also { println("Part one: $it") }
messages.count {
Solver(rules, it, partTwo = true).matches()
}.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,218 | advent-of-code | MIT License |
src/Day18.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | import kotlin.math.abs
fun main() {
data class Point(val x: Int, val y: Int, val z: Int) {
fun touches(other: Point): Boolean {
return (x == other.x && y == other.y && abs(z - other.z) == 1) ||
(x == other.x && z == other.z && abs(y - other.y) == 1) ||
(y == other.y && z == other.z && abs(x - other.x) == 1)
}
fun moveX(dx: Int) = Point(x + dx, y, z)
fun moveY(dy: Int) = Point(x, y + dy, z)
fun moveZ(dz: Int) = Point(x, y, z + dz)
}
fun parse(input: List<String>) = input.map { line ->
val (x, y, z) = line.split(",").map { it.toInt() }
Point(x, y, z)
}
fun surfaceArea(points: List<Point>): Int {
var area = points.size * 6
for (i in points.indices) {
for (j in 0 until i) {
if (points[i].touches(points[j])) area -= 2
}
}
return area
}
fun part1(input: List<String>): Int {
val points = parse(input)
return surfaceArea(points)
}
fun part2(input: List<String>): Int {
val points = parse(input)
val maxX = points.maxOf { it.x }
val maxY = points.maxOf { it.y }
val maxZ = points.maxOf { it.z }
fun Point.isOutside() = x !in 0..maxX || y !in 0..maxY || z !in 0..maxZ
val pointsSet = points.toHashSet()
val inside = HashSet<Point>()
val outside = HashSet<Point>()
fun walk(start: Point) {
val q = ArrayDeque<Point>()
q.addLast(start)
val visited = HashSet<Point>()
while (q.isNotEmpty()) {
val cur = q.removeFirst()
visited += cur
for (move in listOf(Point::moveX, Point::moveY, Point::moveZ)) {
for (dir in listOf(-1, 1)) {
val p = move(cur, dir)
if (p !in pointsSet && p !in visited && p !in inside) {
if (p.isOutside() || p in outside) {
outside += visited
return
}
visited += p
q.addLast(p)
}
}
}
}
inside += visited
}
for (i in 0 until maxX) {
for (j in 0 until maxY) {
for (k in 0 until maxZ) {
val p = Point(i, j, k)
if (p !in pointsSet && p !in inside && p !in outside) {
walk(p)
}
}
}
}
return surfaceArea(points) - surfaceArea(inside.toList())
}
val testInput = readInputLines("Day18_test")
check(part1(testInput), 64)
check(part2(testInput), 58)
val input = readInputLines("Day18")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 2,979 | Advent-of-Code-2022 | Apache License 2.0 |
12/part_two.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
fun readInput() : Graph {
val edges = File("input.txt")
.readLines()
.map { it.split("-") }
return Graph(edges)
}
class Graph(edges : List<List<String>>) {
companion object {
const val START = "start"
const val END = "end"
}
private var start = 0
private var end = 0
private var adjList = mutableMapOf<Int, MutableList<Int>>()
private var nodes = 0
private var smallCaves = setOf<Int>()
init {
val nodeMap = mapNodesToInt(edges)
smallCaves = determineSmallCaves(nodeMap)
addEdges(edges, nodeMap)
start = nodeMap[START]!!
end = nodeMap[END]!!
}
fun calculatePaths() : Int {
val timesVisitedSmallCaves = mutableMapOf(start to 2)
return DFS(start, timesVisitedSmallCaves, false)
}
private fun DFS(node : Int, timesVisitedSmallCaves : MutableMap<Int, Int>, smallVisitedTwice : Boolean) : Int {
if (node == end) return 1
var result = 0
for (adjNode in adjList[node]!!) {
if (isSmallCave(adjNode)) {
val timesVisited = timesVisitedSmallCaves.getOrDefault(adjNode, 0)
if (timesVisited == 0 || timesVisited == 1 && !smallVisitedTwice) {
timesVisitedSmallCaves[adjNode] = timesVisited + 1
result += DFS(adjNode, timesVisitedSmallCaves, smallVisitedTwice || timesVisited == 1)
timesVisitedSmallCaves[adjNode] = timesVisited
}
} else if (!isSmallCave(adjNode)) {
result += DFS(adjNode, timesVisitedSmallCaves, smallVisitedTwice)
}
}
return result
}
private fun isSmallCave(cave : Int) : Boolean {
return cave in smallCaves
}
private fun mapNodesToInt(edges : List<List<String>>) : MutableMap<String, Int> {
val result = mutableMapOf<String, Int>()
for ((a, b) in edges) {
if (a !in result) result[a] = nodes++
if (b !in result) result[b] = nodes++
}
return result
}
private fun determineSmallCaves(nodeMap : MutableMap<String, Int>) : Set<Int> {
val result = mutableSetOf<Int>()
for ((key, value) in nodeMap) {
if (isLowerCase(key)) {
result.add(value)
}
}
return result
}
private fun addEdges(edges: List<List<String>>, nodeMap : MutableMap<String, Int>) {
for (edge in edges) {
val a = nodeMap[edge[0]]!!
val b = nodeMap[edge[1]]!!
addEdge(a, b)
}
}
private fun addEdge(a : Int, b : Int) {
val adjA = adjList.getOrDefault(a, mutableListOf())
adjA.add(b)
adjList[a] = adjA
val adjB = adjList.getOrDefault(b, mutableListOf())
adjB.add(a)
adjList[b] = adjB
}
}
fun isLowerCase(str : String) : Boolean {
for (ch in str) {
if (!ch.isLowerCase()) return false
}
return true
}
fun solve(graph : Graph) : Int {
return graph.calculatePaths()
}
fun main() {
val graph = readInput()
val ans = solve(graph)
println(ans)
}
| 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 3,205 | advent-of-code-2021 | MIT License |
src/Day03.kt | szymon-kaczorowski | 572,839,642 | false | {"Kotlin": 45324} | fun Char.charValue(): Int = when {
isUpperCase() -> this - 'A' + 27
isLowerCase() -> this - 'a' + 1
else -> 0
}
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (ransack in input) {
val first = ransack.substring(0, ransack.length / 2)
val second = ransack.substring(ransack.length / 2)
sum += second.toCharArray().toSet().intersect(first.toCharArray().toSet()).sumOf { it.charValue() }
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (index in input.indices step 3) {
val first = input[index]
val second = input[index + 1]
val third = input[index + 2]
sum += second.toSet().intersect(first.toSet()).intersect(third.toSet()).sumOf { it.charValue() }
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1d7ab334f38a9e260c72725d3f583228acb6aa0e | 1,162 | advent-2022 | Apache License 2.0 |
src/Day10.kt | tigerxy | 575,114,927 | false | {"Kotlin": 21255} | import Operation.Add
import Operation.Nop
fun main() {
fun part1(input: List<String>): Int {
val parsedInput = input.parse()
.addHead(Add(1))
.chunked(10)
return (2..22 step 4)
.sumOf {
parsedInput
.take(it)
.flatten()
.sum() * it
} * 10
}
fun part2(input: List<String>): String {
return input.parse()
.fold(State(1, emptyList())) { state, op ->
with(state) {
val pos = crt.size % 40
val x = regX + op.value
val draw = (x - pos) in 0..2
copy(
regX = x,
crt = crt.append(draw)
)
}
}
.crt
.map { if (it) '#' else '.' }
.chunked(40)
.joinToString("\n") {
it.joinToString("")
}
}
val day = "10"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
val testOutput1 = part1(testInput)
println("part1_test=$testOutput1")
assert(testOutput1 == 13140)
val testOutput2 = part2(testInput)
println("part2_test=\n$testOutput2")
val input = readInput("Day$day")
println("part1=${part1(input)}")
println("part2=\n${part2(input)}")
}
private fun List<Operation>.sum(): Int =
sumOf { it.value }
private fun <E> List<E>.addHead(add: E): List<E> =
listOf<List<E>>(listOf<E>(add), this).flatten()
private fun List<String>.parse(): List<Operation> =
flatMap {
if (it == "noop") {
listOf(Nop)
} else {
val value = it.split(" ")[1].toInt()
listOf(Nop, Add(value))
}
}
private sealed class Operation {
open val value = 0
object Nop : Operation()
data class Add(override val value: Int) : Operation()
}
private data class State(val regX: Int, val crt: List<Boolean>) | 0 | Kotlin | 0 | 1 | d516a3b8516a37fbb261a551cffe44b939f81146 | 2,085 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day10Data.kt | yigitozgumus | 572,855,908 | false | {"Kotlin": 26037} | package days
import utils.SolutionData
fun main() = with(Day10Data()) {
println(" --- Part 1 --- ")
solvePart1()
println(" --- Part 2 --- ")
solvePart2()
}
sealed class Command(val name: String, val effect: Int = 0, val cycle: Int) {
class NOOP(): Command("noop", 0, 1)
class ADDX(effect: Int): Command("addx", effect, 2)
}
class Day10Data: SolutionData(inputFile = "inputs/day10.txt") {
val snapshotList = mutableListOf<Pair<Int, Int>>()
val commandList = rawData.map {
if (it.startsWith("no")) Command.NOOP()
else Command.ADDX(it.split(" ").last().toInt())
}
fun isDrawn(reg: Int, cycle: Int) = listOf(reg-1, reg, reg+1).contains(cycle % 40)
}
fun Day10Data.solvePart1() {
var registerX = 1
var totalCycle = 0
val signalStrengthList = listOf(20, 60, 100, 140, 180, 220)
commandList.forEach { command ->
registerX += command.effect
totalCycle += command.cycle
snapshotList.add(totalCycle to registerX)
}
signalStrengthList.sumOf { test ->
(snapshotList.findLast { it.first < test }?.second?.times(test) ?: 0)
}.also { println(it) }
}
fun Day10Data.solvePart2() {
var screen: String = ""
val breakList = listOf(39, 79, 119, 159, 199, 239)
(0 until 240).forEach { cycle ->
val position = snapshotList.findLast { it.first <= cycle }?.second ?: 0
screen += if (isDrawn(position, cycle)) "#" else "."
if (breakList.contains(cycle)) screen += "\n"
}
println(screen)
}
| 0 | Kotlin | 0 | 0 | 9a3654b6d1d455aed49d018d9aa02d37c57c8946 | 1,450 | AdventOfCode2022 | MIT License |
src/test/kotlin/io/noobymatze/aoc/y2023/Day7.kt | noobymatze | 572,677,383 | false | {"Kotlin": 90710} | package io.noobymatze.aoc.y2023
import io.noobymatze.aoc.Aoc
import kotlin.math.exp
import kotlin.test.Test
class Day7 {
fun compareCards(cards: String, a: String, b: String): Int {
var result = 0
for (i in 0..5) {
result = cards.indexOf(a[i]) - cards.indexOf(b[i])
if (result != 0) return result
}
return result
}
@Test
fun test() {
fun strength(hand: String): Int {
val freq = hand.groupingBy { it }.eachCount()
return when {
// Five of a kind
freq.size == 1 -> 7
// Four of a kind
freq.any { it.value == 4 } -> 6
// Full house
freq.any { it.value == 3 } && freq.any { it.value == 2 } -> 5
// Three of a kind
freq.size == 3 && freq.any { it.value == 3 } -> 4
// Two pair
freq.count { it.value == 2 } == 2 -> 3
// One pair
freq.size == 4 && freq.count { it.value == 2 } == 1 -> 2
// High card
else -> 1
}
}
val cards = "23456789TJQKA"
val result = Aoc.getInput(7)
.lines()
.map { it.split(" ") }
.sortedWith(compareBy<List<String>> { (hand, _) -> strength(hand) }
.then { (a, _), (b, _) -> compareCards(cards, a, b) }
)
.mapIndexed { i, (_, bid) -> bid.toInt() * (i + 1) }
.sum()
println(result)
}
@Test
fun test2() {
val cards = "J23456789TQKA"
fun strength(hand: String): Int {
val freq = hand.groupingBy { it }.eachCount()
val jokers = freq['J'] ?: 0
return when {
// Five of a kind
freq.size == 1 || freq.any { it.key != 'J' && it.value + jokers == 5 } -> 7
// Four of a kind
freq.count { it.value == 4 } == 1
|| freq.any { it.key != 'J' && it.value + jokers == 4 } -> 6
// Full house
freq.any { it.value == 3 } && freq.any { it.value == 2 }
|| (jokers == 2 && freq.count { it.key != 'J' } == 2)
|| (jokers == 1 && freq.count { it.key != 'J' } == 2) -> 5
// Three of a kind
freq.count { it.value == 3 } == 1
|| freq.any { it.key != 'J' && it.value + jokers == 3 } -> 4
// Two pair
freq.count { it.value == 2 } == 2 -> 3
// One pair
freq.count { it.value == 2 } == 1
|| (freq.any { it.key != 'J' && it.value + jokers == 2 }) -> 2
// High card
else -> 1
}
}
val result = Aoc.getInput(7)
.lines()
.map { it.split(" ") }
.sortedWith(compareBy<List<String>> { (hand, _) -> strength(hand) }
.then { (a, _), (b, _) -> compareCards(cards, a, b) }
)
.mapIndexed { i, (_, bid) -> bid.toInt() * (i + 1) }
.sum()
println(result)
}
} | 0 | Kotlin | 0 | 0 | da4b9d894acf04eb653dafb81a5ed3802a305901 | 3,214 | aoc | MIT License |
src/year2022/day11/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2022.day11
import io.kotest.matchers.shouldBe
import utils.readInput
fun main() {
val testInput = readInput("11", "test_input")
val realInput = readInput("11", "input")
val testStartMonkeyList = testInput.buildMonkeyList()
val realStartMonkeyList = realInput.buildMonkeyList()
runRounds(20, testStartMonkeyList) { it / 3 }
.sortedByDescending { it.inspectedItems }
.let { (first, second) -> first.inspectedItems * second.inspectedItems }
.also(::println) shouldBe 10605
runRounds(20, realStartMonkeyList) { it / 3 }
.sortedByDescending { it.inspectedItems }
.let { (first, second) -> first.inspectedItems * second.inspectedItems }
.let(::println)
val testWorryAdjustment = testStartMonkeyList.asSequence()
.map { it.testModulo }
.fold(1, Long::times)
runRounds(10000, testStartMonkeyList) { it % testWorryAdjustment }
.sortedByDescending { it.inspectedItems }
.let { (first, second) -> first.inspectedItems * second.inspectedItems }
.also(::println) shouldBe 2713310158L
val realWorryAdjustment = realStartMonkeyList.asSequence()
.map { it.testModulo }
.fold(1, Long::times)
runRounds(10000, realStartMonkeyList) { it % realWorryAdjustment }
.sortedByDescending { it.inspectedItems }
.let { (first, second) -> first.inspectedItems * second.inspectedItems }
.let(::println)
}
private fun List<String>.buildMonkeyList(): List<Monkey> {
return chunked(7).fold(mutableListOf()) { monkeys, data ->
val operationComputation: Long.(Long) -> Long = if (data[2][23] == '+') Long::plus else Long::times
val operationSecondOperand = data[2].takeLastWhile { it != ' ' }.toLongOrNull()
val testModulo = data[3].takeLastWhile { it != ' ' }.toLong()
val testTrue = data[4].takeLastWhile { it != ' ' }.toInt()
val testFalse = data[5].takeLastWhile { it != ' ' }.toInt()
monkeys.apply {
add(
Monkey(
items = data[1].removePrefix(" Starting items: ").split(", ").map(String::toLong),
operation = operationSecondOperand
?.let { secondOperand -> { it.operationComputation(secondOperand) } }
?: { it * it },
ifTrue = testTrue,
ifFalse = testFalse,
testModulo = testModulo,
)
)
}
}
}
private data class Monkey(
val items: List<Long>,
val operation: (Long) -> Long,
val ifTrue: Int,
val ifFalse: Int,
val testModulo: Long,
val inspectedItems: Long = 0,
)
private fun runRounds(
roundCount: Long,
monkeyList: List<Monkey>,
worryAdjustment: (Long) -> Long,
): List<Monkey> {
return (0 until roundCount).fold(monkeyList) { roundState, _ ->
roundState.indices.fold(roundState) { monkeysState, monkeyTurn ->
val subject = monkeysState[monkeyTurn]
val (toTrue, toFalse) = subject.items.asSequence()
.map(subject.operation)
.map(worryAdjustment)
.partition { it % subject.testModulo == 0L }
monkeysState.toMutableList().apply {
this[monkeyTurn] = subject.copy(
items = emptyList(),
inspectedItems = subject.inspectedItems + subject.items.size,
)
this[subject.ifTrue] = this[subject.ifTrue].run {
copy(items = items + toTrue)
}
this[subject.ifFalse] = this[subject.ifFalse].run {
copy(items = items + toFalse)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 3,782 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/aoc2016/day02_bathroom_security/BathroomSecurity.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package aoc2016.day02_bathroom_security
import geom2d.Dir.*
import geom2d.toDir
fun main() {
util.solve("61529", ::partOne)
util.solve("C2C28", ::partTwo)
}
internal fun String.asKeymap(): Array<IntArray> {
val map = mutableMapOf<Int, IntArray>()
var max = -1
val grid = trimIndent().lines().map {
it.map {
when (it) {
' ' -> -1
else -> it.digitToInt(16)
}
}
}
grid.forEachIndexed { row, nums ->
nums.forEachIndexed inner@{ col, n ->
if (n < 0) return@inner
max = max.coerceAtLeast(n)
val arr = intArrayOf(n, n, n, n)
map[n] = arr
// up
if (row > 0) {
val prevRow = grid[row - 1]
if (prevRow.size > col && prevRow[col] >= 0) {
arr[NORTH.ordinal] = prevRow[col]
}
}
// right
val r = nums.subList(col + 1, nums.size).find { it > 0 }
if (r != null) {
arr[EAST.ordinal] = r
}
// down
if (row < grid.size - 1) {
val nextRow = grid[row + 1]
if (nextRow.size > col && nextRow[col] >= 0) {
arr[SOUTH.ordinal] = nextRow[col]
}
}
// left
val l = nums.subList(0, col).asReversed().find { it > 0 }
if (l != null) {
arr[WEST.ordinal] = l
}
}
}
return Array(max + 1) {
map.getOrDefault(it, intArrayOf())
}
}
private fun solve(input: String, keymap: Array<IntArray>) = input
.lines()
.asSequence()
.map { it.map(Char::toDir) }
.runningFold(5) { btn, steps ->
steps.fold(btn) { b, s ->
keymap[b][s.ordinal]
}
}
.drop(1) // don't want the starting five...
.joinToString(separator = "") {
it.toString(16).uppercase()
}
fun partOne(input: String) =
solve(
input, """
1 2 3
4 5 6
7 8 9
""".asKeymap()
)
fun partTwo(input: String) =
solve(
input, """
1
2 3 4
5 6 7 8 9
A B C
D
""".asKeymap()
)
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 2,291 | aoc-2021 | MIT License |
src/Day07.kt | Feketerig | 571,677,145 | false | {"Kotlin": 14818} | fun main(){
fun buildFileSystem(input: List<String>): Dir {
val root = Dir("/", mutableListOf(), null)
var currentDir = root
input.drop(1).forEach {line ->
when(line.substring(0,4)){
"$ ls" -> {
}
"$ cd" -> {
val path = line.removePrefix("$ cd ")
if (path == ".."){
currentDir = currentDir.parent!!
}else{
currentDir = currentDir.files.find { it.name == path } as Dir
}
}
"dir " -> {
val name = line.removePrefix("dir ")
currentDir.files.add(Dir(name, mutableListOf(), currentDir))
}
else -> {
val (size, name) = line.split(" ")
currentDir.files.add(File(name, size.toInt(), currentDir))
}
}
}
return root
}
fun part1(input: List<String>): Int{
val root = buildFileSystem(input)
val folders = root.findFolders(100_000)
return folders.sumOf { it.getSystemSize() }
}
fun part2(input: List<String>): Int{
val root = buildFileSystem(input)
val totalDisk = 70_000_000
val usedSpace = root.getSystemSize()
val freeSpace = totalDisk - usedSpace
val neededSpace = 30_000_000
val freeUpSpace = neededSpace - freeSpace
val folders = root.findFolders(Int.MAX_VALUE)
return folders.filter { it.getSystemSize() > freeUpSpace }.minOf { it.getSystemSize() }
}
val testInput = readInput("Day07_test_input")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07_input")
println(part1(input))
println(part2(input))
}
sealed class SystemPart(val name: String, val parent: Dir?){
abstract fun getSystemSize(): Int
}
open class File(name: String, val size: Int, parent: Dir?): SystemPart(name, parent){
override fun getSystemSize(): Int = size
}
class Dir(name: String, val files: MutableList<SystemPart>, parent: Dir?): SystemPart(name, parent){
override fun getSystemSize():Int {
return files.sumOf { it.getSystemSize() }
}
fun findFolders(maxSize: Int): List<Dir> {
val children = files.filterIsInstance<Dir>().flatMap { it.findFolders(maxSize) }
return if(getSystemSize() <= maxSize) {
children + this
} else {
children
}
}
} | 0 | Kotlin | 0 | 0 | c65e4022120610d930293788d9584d20b81bc4d7 | 2,585 | Advent-of-Code-2022 | Apache License 2.0 |
src/day05/Day05.kt | cmargonis | 573,161,233 | false | {"Kotlin": 15730} | package day05
import readInput
private const val DIRECTORY = "./day05"
fun main() {
fun getStack(input: List<String>): Pair<Int, Map<Int, ArrayDeque<String>>> {
var stackIndex = 0
val stackRows: List<List<String>> = input.takeWhile { it.isNotBlank() }.mapIndexed { runningIndex, row ->
stackIndex = runningIndex
row.windowed(size = 3, step = 4, partialWindows = true)
}
val stack: MutableMap<Int, MutableList<String>> = mutableMapOf<Int, MutableList<String>>()
val stackKeys: List<Int> = stackRows[stackIndex].map { it.trim(' ', '\"').toInt() }
stackRows.dropLast(1).forEach { row: List<String> ->
row.forEachIndexed { index, item ->
val itemsAtStack: MutableList<String> = stack[stackKeys[index]] ?: mutableListOf()
itemsAtStack.add(item)
stack[stackKeys[index]] = itemsAtStack
}
}
stack.forEach { entry -> entry.value.removeIf { it.isBlank() } }
return Pair(stackIndex, stack.toSortedMap(compareByDescending { it }).mapValues { entry ->
val trimmed = entry.value.map { it.trim('[', ']', ' ') }
ArrayDeque(trimmed)
})
}
fun getInstructions(rawInstructions: List<String>): List<Instruction> = rawInstructions.map {
val instruction = it.split(" ")
Instruction(
quantity = instruction[1].toInt(),
origin = instruction[3].toInt(),
destination = instruction[5].toInt()
)
}
fun Map<Int, ArrayDeque<String>>.move(from: Int, to: Int) {
if (isEmpty()) return
val removed = this[from]?.removeFirst()
this[to]?.addFirst(removed!!)
}
fun Map<Int, ArrayDeque<String>>.moveMany(times: Int, from: Int, to: Int) {
if (isEmpty()) return
val tempQueue: ArrayDeque<String> = ArrayDeque(initialCapacity = times)
repeat(times) {
tempQueue.addFirst(this[from]!!.removeFirst())
}
repeat(times) {
this[to]?.addFirst(tempQueue.removeFirst())
}
}
fun Map<Int, ArrayDeque<String>>.topOfTheStack(): String = asIterable()
.runningFold("") { _, entry -> entry.value.first() }
.filterNot { it.isEmpty() }
.joinToString(separator = "")
fun part1(input: List<String>): String {
val (indexOfInstructions, stack) = getStack(input)
val instructions = getInstructions(input.subList(fromIndex = indexOfInstructions + 2, toIndex = input.size))
instructions.forEach { instruction ->
repeat(instruction.quantity) {
stack.move(from = instruction.origin, to = instruction.destination)
}
}
return stack.topOfTheStack().reversed()
}
fun part2(input: List<String>): String {
val (indexOfInstructions, stack) = getStack(input)
val instructions = getInstructions(input.subList(fromIndex = indexOfInstructions + 2, toIndex = input.size))
instructions.forEach { instruction ->
stack.moveMany(times = instruction.quantity, from = instruction.origin, to = instruction.destination)
}
return stack.topOfTheStack().reversed()
}
val input = readInput("${DIRECTORY}/Day05")
println(part1(input))
println(part2(input))
}
data class Instruction(val quantity: Int, val origin: Int, val destination: Int)
| 0 | Kotlin | 0 | 0 | bd243c61bf8aae81daf9e50b2117450c4f39e18c | 3,434 | kotlin-advent-2022 | Apache License 2.0 |
src/Day10.kt | Shykial | 572,927,053 | false | {"Kotlin": 29698} | private val SIGNAL_REGEX = Regex("""(\w+)(?:\s(-?\d+))?""")
fun main() {
fun part1(input: List<String>): Int {
val searchedCycles = (20..220 step 40).toList().run(::ArrayDeque)
return input
.map { SIGNAL_REGEX.find(it)?.groups?.get(2)?.value }
.fold(Triple(1, 1, 0)) { (cycle, xValue, sum), xMatch ->
val (newCycle, newX) = xMatch
?.let { number -> cycle + 2 to xValue + number.toInt() }
?: (cycle + 1 to xValue)
val newSum = if (newCycle > searchedCycles.first()) {
(sum + xValue * searchedCycles.removeFirst()).also { if (searchedCycles.isEmpty()) return it }
} else sum
Triple(newCycle, newX, newSum)
}.third
}
fun part2(input: List<String>): String {
val drawnLines = mutableListOf<String>()
val lineBuilder = StringBuilder()
fun appendCharCheckingOverflow(char: Char, cycle: Int) {
lineBuilder.append(char)
if (cycle % 40 == 0) {
drawnLines += lineBuilder.toString()
lineBuilder.clear()
}
}
input.map { SIGNAL_REGEX.find(it)?.groups?.get(2)?.value }
.fold(1 to 1) { (cycle, spritePosition), xMatch ->
appendCharCheckingOverflow(crtChar(spritePosition, cycle), cycle)
xMatch?.toInt()?.let { xValue ->
appendCharCheckingOverflow(crtChar(spritePosition, cycle + 1), cycle + 1)
cycle + 2 to spritePosition + xValue
} ?: (cycle + 1 to spritePosition)
}
return drawnLines.joinToString("\n")
}
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
private fun crtChar(spritePosition: Int, cycle: Int) =
if ((cycle % 40).let { if (it == 0) 40 else it } in spritePosition..spritePosition + 2) '#' else '.'
| 0 | Kotlin | 0 | 0 | afa053c1753a58e2437f3fb019ad3532cb83b92e | 1,965 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | arhor | 572,349,244 | false | {"Kotlin": 36845} | fun main() {
val input = readInput {}
println(
"Part 1: " + solvePuzzle(
input, resultTable = hashMapOf(
"A X" to Shape.ROCK + Round.DRAW,
"A Y" to Shape.PAPER + Round.WIN,
"A Z" to Shape.SCISSORS + Round.LOOSE,
"B X" to Shape.ROCK + Round.LOOSE,
"B Y" to Shape.PAPER + Round.DRAW,
"B Z" to Shape.SCISSORS + Round.WIN,
"C X" to Shape.ROCK + Round.WIN,
"C Y" to Shape.PAPER + Round.LOOSE,
"C Z" to Shape.SCISSORS + Round.DRAW,
)
)
)
println(
"Part 2: " + solvePuzzle(
input, resultTable = hashMapOf(
"A X" to Round.LOOSE + Shape.SCISSORS,
"A Y" to Round.DRAW + Shape.ROCK,
"A Z" to Round.WIN + Shape.PAPER,
"B X" to Round.LOOSE + Shape.ROCK,
"B Y" to Round.DRAW + Shape.PAPER,
"B Z" to Round.WIN + Shape.SCISSORS,
"C X" to Round.LOOSE + Shape.PAPER,
"C Y" to Round.DRAW + Shape.SCISSORS,
"C Z" to Round.WIN + Shape.ROCK,
)
)
)
}
private fun solvePuzzle(input: List<String>, resultTable: Map<String, Int>): Int {
return input.mapNotNull(resultTable::get).sum()
}
private interface Scored {
val score: Int
operator fun plus(that: Scored) = this.score + that.score
}
private enum class Round(override val score: Int) : Scored { LOOSE(0), DRAW(3), WIN(6) }
private enum class Shape(override val score: Int) : Scored { ROCK(1), PAPER(2), SCISSORS(3) }
| 0 | Kotlin | 0 | 0 | 047d4bdac687fd6719796eb69eab2dd8ebb5ba2f | 1,684 | aoc-2022-in-kotlin | Apache License 2.0 |
algorithms/src/main/kotlin/com/kotlinground/algorithms/searching/trie/searchsuggestions/suggestedProducts.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 483489, "Shell": 7283, "Python": 1725} | package com.kotlinground.algorithms.searching.trie.searchsuggestions
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.abs
import kotlin.math.min
/**
* Since the question asks for the result in a sorted order, let's start with sorting products.
* An advantage that comes with sorting is Binary Search, we can binary search for the prefix. Once we locate the first
* match of prefix, all we need to do is to add the next 3 words into the result (if there are any), since we sorted the
* words beforehand.
* Complexity Analysis
*
* Time complexity: O(nlog(n)) + O(mlog(n)). Where n is the length of products and m is the length of the search word.
* Here we treat string comparison in sorting as O(1). O(nlog(n)) comes from the sorting and O(mlog(n)) comes from
* running binary search on products m times.
*
* In Java there is an additional complexity of O(m^2) due to Strings being immutable, here m is the length of searchWord.
*
* Space complexity : Varies between O(1) and O(n) where n is the length of products, as it depends on the implementation
* used for sorting. We ignore the space required for output as it does not affect the algorithm's space complexity.
*
* Space required for output is O(m) where m is the length of the search word.
*/
fun suggestedProducts(products: Array<String>, searchWord: String): List<List<String>> {
Arrays.sort(products)
val result = arrayListOf<ArrayList<String>>()
var start: Int
var bsStart = 0
val numberOfProducts = products.size
fun lowerBound(items: Array<String>, startIdx: Int, word: String): Int {
var left = startIdx
var right = items.size
while (left < right) {
val mid = (right + left) / 2
if (items[mid] >= word) {
right = mid
} else {
left = mid + 1
}
}
return left
}
var prefix = ""
for (char in searchWord.toCharArray()) {
prefix += char
// Get the starting index of word starting with `prefix`.
start = lowerBound(products, bsStart, prefix)
// Add empty vector to result.
result.add(ArrayList())
// Add the words with the same prefix to the result.
// Loop runs until `i` reaches the end of input or 3 times or till the
// prefix is same for `products[i]` Whichever comes first.
for (i in start until min(start + 3, numberOfProducts)) {
if (products[i].length < prefix.length || products[i].substring(0, prefix.length) != prefix) break
result[result.size - 1].add(products[i])
}
// Reduce the size of elements to binary search on since we know
bsStart = abs(start.toDouble()).toInt()
}
return result
}
| 1 | Kotlin | 1 | 0 | 5e3e45b84176ea2d9eb36f4f625de89d8685e000 | 2,796 | KotlinGround | MIT License |
src/main/kotlin/days/Day07.kt | julia-kim | 569,976,303 | false | null | package days
import readInput
fun main() {
tailrec fun sumFiles(
filesystem: MutableList<Directory>,
children: List<String>,
sum: Long
): Long {
var total = sum
if (children.isEmpty()) return total
val dirs = children.map { child ->
filesystem.first { it.name == child }
}
dirs.forEach { dir ->
total += dir.files.sumOf { it.size }
sumFiles(filesystem, dir.childrenDirectories, total)
}
return total
}
fun part1(input: List<String>): Long {
val filesystem: MutableList<Directory> = mutableListOf()
var currentDirectory = ""
input.forEach {
when {
it.startsWith("$ ls") -> return@forEach
it.startsWith("$ cd") -> {
val dir = it.split(" ").last()
if (dir == "/" && filesystem.firstOrNull() == null) filesystem.add(
Directory(
"/",
parentDirectory = "/",
isHomeDirectory = true
)
)
val i = filesystem.indexOfFirst { it.name == currentDirectory }
currentDirectory = if (dir == "..") filesystem[i].parentDirectory else dir
}
it.startsWith("dir") -> {
val directoryName = it.split(" ").last()
val current = filesystem.first { it.name == currentDirectory }
current.childrenDirectories.add(directoryName)
val i = filesystem.indexOfFirst { it.name == directoryName }
if (i == -1) {
filesystem.add(Directory(directoryName, parentDirectory = currentDirectory))
} else {
filesystem[i]
}
}
else -> {
val i = filesystem.indexOfFirst { it.name == currentDirectory }
val dir = filesystem[i]
val (size, name) = it.split(" ")
dir.files.add(File(name, size.toLong()))
}
}
}
filesystem.forEach { d ->
d.totalSize = sumFiles(
filesystem,
d.childrenDirectories,
d.files.sumOf { it.size })
}
println(filesystem)
return filesystem.filter { it.totalSize <= 100000 }.sumOf { it.totalSize }
}
fun part2(input: List<String>): Int {
return 0
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 0)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
data class File(var name: String? = null, var size: Long = 0)
data class Directory(
var name: String = "",
var files: MutableList<File> = mutableListOf(),
var parentDirectory: String = "",
var childrenDirectories: MutableList<String> = mutableListOf(),
var isHomeDirectory: Boolean = false,
var totalSize: Long = 0L
) | 0 | Kotlin | 0 | 0 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 3,182 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | rbraeunlich | 573,282,138 | false | {"Kotlin": 63724} | import java.util.Collections
fun main() {
fun part1(input: List<String>): Long {
val fileSystem = RootDirectory()
val allDirectories = mutableListOf<FileDirectory>()
var currentDirectory: FileSystemNode = fileSystem
input.forEach { line ->
if (line == "$ cd /" || line == "$ ls") {
// do nothing
} else if (line.startsWith("dir")) {
val directoryName = line.replace("dir ", "")
val fileDirectory = FileDirectory(parent = currentDirectory, name = directoryName)
currentDirectory.contents.add(fileDirectory)
allDirectories.add(fileDirectory)
} else if (line.matches("(\\d+) (.)+".toRegex())) {
val fileSize = line.split(" ")[0].toLong()
val fileName = line.split(" ")[1]
currentDirectory.contents.add(File(size = fileSize, name = fileName, parent = currentDirectory))
} else if (line == "$ cd ..") {
currentDirectory = currentDirectory.parent
} else {
// must be directory change
val newDirectory = line.replace("$ ", "").split(" ")[1]
currentDirectory = currentDirectory.contents.first { it.name == newDirectory }
}
}
return allDirectories
.filter { it.size() < 100000 }
.sumOf { it.size() }
}
fun part2(input: List<String>): Long {
val fileSystem = RootDirectory()
val allDirectories = mutableListOf<FileDirectory>()
var currentDirectory: FileSystemNode = fileSystem
input.forEach { line ->
if (line == "$ cd /" || line == "$ ls") {
// do nothing
} else if (line.startsWith("dir")) {
val directoryName = line.replace("dir ", "")
val fileDirectory = FileDirectory(parent = currentDirectory, name = directoryName)
currentDirectory.contents.add(fileDirectory)
allDirectories.add(fileDirectory)
} else if (line.matches("(\\d+) (.)+".toRegex())) {
val fileSize = line.split(" ")[0].toLong()
val fileName = line.split(" ")[1]
currentDirectory.contents.add(File(size = fileSize, name = fileName, parent = currentDirectory))
} else if (line == "$ cd ..") {
currentDirectory = currentDirectory.parent
} else {
// must be directory change
val newDirectory = line.replace("$ ", "").split(" ")[1]
currentDirectory = currentDirectory.contents.first { it.name == newDirectory }
}
}
val usedSpace = fileSystem.size()
val unusedSpace = 70000000 - usedSpace
val neededSpace = 30000000 - unusedSpace
return allDirectories
.filter { it.size() > neededSpace }
.minOf { it.size() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
sealed interface FileSystemNode {
fun size(): Long
val parent: FileSystemNode
val contents: MutableList<FileSystemNode>
val name: String
}
data class RootDirectory(override val contents: MutableList<FileSystemNode> = mutableListOf()) : FileSystemNode {
override fun size(): Long = contents.sumOf { it.size() }
override val parent: FileSystemNode
get() = this
override val name: String
get() = "/"
}
data class FileDirectory(
override val contents: MutableList<FileSystemNode> = mutableListOf(),
override val parent: FileSystemNode,
override val name: String
) : FileSystemNode {
override fun size(): Long = contents.sumOf { it.size() }
override fun toString(): String {
return "FileDirectory(contents=$contents, parent=${parent.name}, name='$name')"
}
}
data class File(val size: Long, override val name: String, override val parent: FileSystemNode) : FileSystemNode {
override fun size(): Long = size
override val contents: MutableList<FileSystemNode> = Collections.unmodifiableList(mutableListOf())
override fun toString(): String {
return "File(size=$size, name='$name', parent=${parent.name}, contents=$contents)"
}
} | 0 | Kotlin | 0 | 1 | 3c7e46ddfb933281be34e58933b84870c6607acd | 4,493 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode2023/day4/day4.kt | dzkoirn | 725,682,258 | false | {"Kotlin": 133478} | package adventofcode2023.day4
import adventofcode2023.readInput
typealias Card = Pair<List<Int>, List<Int>>
val Card.winning: List<Int>
get() = this.first
val Card.myNumbers: List<Int>
get() = this.second
fun main() {
val input = readInput("day4")
println("Day 4")
println("Puzzle 1: ${puzzle1(input)}")
println("Puzzle 2: ${puzzle2(input)}")
}
fun parseLine(line: String): Card {
fun String.toNumbers(): List<Int> = this.split(' ').filter { it.isNotEmpty() }.map { it.toInt() }
return line.substring(line.indexOf(':') + 1).split('|').let {(left, right) ->
Card(left.trim().toNumbers(), right.trim().toNumbers())
}
}
fun findWinningNumber(card: Card): List<Int> = card.myNumbers.filter { it in card.winning }
fun calculatePoints(list: List<Int>): Int {
if (list.isEmpty()) return 0
var initial = 1
repeat(list.size - 1) {
initial *= 2
}
return initial
}
fun puzzle1(input: List<String>): Int = input.map { l -> parseLine(l) }
.map { findWinningNumber(it) }
.map { calculatePoints(it) }
.sum()
fun puzzle2(input: List<String>): Int {
val amounts = IntArray(input.size) { 1 }
input.map { l -> parseLine(l) }
.map { findWinningNumber(it).size }
.forEachIndexed { index: Int, i: Int ->
val multiplier = amounts[index]
repeat(i) { delta ->
amounts[index + 1 + delta] += multiplier
}
}
return amounts.sum()
} | 0 | Kotlin | 0 | 0 | 8f248fcdcd84176ab0875969822b3f2b02d8dea6 | 1,484 | adventofcode2023 | MIT License |
src/Day14.kt | adrianforsius | 573,044,406 | false | {"Kotlin": 68131} |
import org.assertj.core.api.Assertions.assertThat
import java.lang.Integer.max
import java.lang.Integer.min
fun rangeBetween(a: Int, b: Int) = min(a, b) .. max(a, b)
fun main() {
fun part1(input: List<String>): Int {
val lines = input.map {
it.split(" -> ")
.map {
val (x, y) = it.split(",").map {
it.toInt()
}
Point(y, x)
}
.windowed(2)
.map { it ->
val (first, second) = it
var points = mutableListOf<Point>()
for (y in rangeBetween(first.y, second.y)) {
for (x in rangeBetween(first.x, second.x)) {
points.add(Point(y,x))
}
}
points
}.flatten()
}
val points = lines.flatten().toSet().toList()
val sandStart = Point(0, 500)
val pointsWithSand = points + sandStart
val maxX = pointsWithSand.sortedByDescending { it.x }.take(1).first().x
val maxY = pointsWithSand.sortedByDescending { it.y }.take(1).first().y
val minX = pointsWithSand.sortedBy { it.x }.take(1).first().x
val minY = pointsWithSand.sortedBy { it.y }.take(1).first().y
val grid = MutableList(maxY - minY + 1) { MutableList(maxX - minX + 1) { "." } }
for (row in grid) {
println(row)
}
for (y in (minY.rangeTo(maxY))) {
for (x in (minX.rangeTo(maxX))) {
val p = points.firstOrNull { it.x == x && it.y == y }
if (p != null) {
grid[y - minY][x - minX] = "#"
}
}
}
grid[sandStart.y - minY][sandStart.x - minX] = "+"
var activeSandRel = Point(sandStart.y - minY, sandStart.x - minX)
var activeSand = activeSandRel.copy()
var count = 0
while(true) {
when {
activeSand.y+1 > maxY-minY -> break
activeSand.x-1 < 0 -> break
activeSand.x+1 > maxX-minX -> break
grid[activeSand.y+1][activeSand.x] == "." -> activeSand.y++
// grid[activeSand.y+1][activeSand.x] == "#" -> {}
grid[activeSand.y+1][activeSand.x-1] == "." -> { activeSand.y++ ; activeSand.x-- }
// grid[activeSand.y+1][activeSand.x-1] == "#" -> {}
grid[activeSand.y+1][activeSand.x+1] == "." -> { activeSand.y++ ; activeSand.x++ }
// grid[activeSand.y+1][activeSand.x+1] == "#" -> {
else -> {
grid[activeSand.y][activeSand.x] = "#"
activeSand = activeSandRel.copy()
count++
}
}
// for (row in grid) {
// println(row)
// }
// println("--------------------")
}
return count
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
// Test
// val testInput = readInput("Day14_test")
// val output1 = part1(testInput)
// assertThat(output1).isEqualTo(24)
// Answer
val input = readInput("Day14")
val outputAnswer1 = part1(input)
assertThat(outputAnswer1).isEqualTo(897)
// // Test
// val output2 = part2(testInput)
// assertThat(output2).isEqualTo(45000)
//
// // Answer
// val outputAnswer2 = part2(input)
// assertThat(outputAnswer2).isEqualTo(199357)
}
| 0 | Kotlin | 0 | 0 | f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb | 3,688 | kotlin-2022 | Apache License 2.0 |
src/days/Day05.kt | nicole-terc | 574,130,441 | false | {"Kotlin": 29131} | package days
import readInput
import java.util.*
import kotlin.math.ceil
fun main() {
fun getInitialStacks(input: List<String>): List<Stack<Char>> {
val grid = input.takeWhile { it.contains('[') }
val numberOfStacks = grid.last().count{it == '['}
val stacks = List(numberOfStacks) { Stack<Char>() }
for (i in grid.size.minus(1) downTo 0) {
grid[i].chunked(4).forEachIndexed { index, chunk ->
if (chunk[1] != ' ') {
stacks[index].push(chunk[1])
}
}
}
return stacks
}
fun part1(input: List<String>): String {
val stacks = getInitialStacks(input)
input.filter { it.contains("move") }
.map { move -> move.split(" ") }
.map { Triple(it[1].toInt(), it[3].toInt()-1, it[5].toInt()-1) }
.onEach { moveInfo ->
for (x in 0 until moveInfo.first) {
stacks[moveInfo.third].push(stacks[moveInfo.second].pop())
}
}
var result = ""
stacks.forEach { stack ->
if (stack.isNotEmpty()) {
result += stack.pop()
}
}
return result
}
fun part2(input: List<String>): String {
val stacks = getInitialStacks(input)
input.filter { it.contains("move") }
.map { move -> move.split(" ") }
.map { Triple(it[1].toInt(), it[3].toInt()-1, it[5].toInt()-1) }
.onEach { moveInfo ->
val tempStack = Stack<Char>()
for (x in 0 until moveInfo.first) {
tempStack.add(stacks[moveInfo.second].pop())
}
while (tempStack.isNotEmpty()) {
stacks[moveInfo.third].push(tempStack.pop())
}
}
var result = ""
stacks.forEach { stack ->
if (stack.isNotEmpty()) {
result += stack.pop()
}
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
println("TEST 1: " + part1(testInput))
println("TEST 2: " + part2(testInput))
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println("PART 1: " + part1(input))
println("PART 2: " + part2(input))
}
| 0 | Kotlin | 0 | 2 | 9b0eb9b20e308e5fbfcb2eb7878ba21b45e7e815 | 2,448 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/Day14.kt | akowal | 434,506,777 | false | {"Kotlin": 30540} | fun main() {
println(Day14.solvePart1())
println(Day14.solvePart2())
}
object Day14 {
private val input = readInput("day14")
private val template = input.first()
private val insertions = input.drop(2)
.map { it.split(" -> ") }
.associate { (pair, insert) -> pair to insert.single() }
fun solvePart1() = polymerize(10)
fun solvePart2() = polymerize(40)
private fun polymerize(steps: Int): Long {
val pairs = mutableMapOf<String, Long>()
val freq = mutableMapOf<Char, Long>()
template.windowed(2).forEach { pairs.addCount(it, 1) }
template.forEach { freq.addCount(it, 1) }
repeat(steps) {
val inserted = mutableMapOf<String, Long>()
insertions.forEach { (pair, insert) ->
val count = pairs.remove(pair) ?: return@forEach
inserted.addCount("${pair[0]}$insert", count)
inserted.addCount("$insert${pair[1]}", count)
freq.addCount(insert, count)
}
inserted.forEach { (pair, count) -> pairs.addCount(pair, count) }
}
return freq.maxOf { it.value } - freq.minOf { it.value }
}
private fun <T> MutableMap<T, Long>.addCount(key: T, x: Long) = compute(key) { _, n -> (n ?: 0) + x }
}
| 0 | Kotlin | 0 | 0 | 08d4a07db82d2b6bac90affb52c639d0857dacd7 | 1,302 | advent-of-kode-2021 | Creative Commons Zero v1.0 Universal |
src/Day04.kt | Sghazzawi | 574,678,250 | false | {"Kotlin": 10945} | fun getRange(input: String): IntRange {
val split = input.split("-")
return (split[0].toInt()..split[1].toInt())
}
fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.split(",") }
.map { Pair(getRange(it[0]), getRange(it[1])) }
.fold(0) { acc, current ->
if (current.first.all { current.second.contains(it) } ||
current.second.all { current.first.contains(it) })
acc + 1
else
acc
}
}
fun part2(input: List<String>): Int {
return input
.map { it.split(",") }
.map { Pair(getRange(it[0]), getRange(it[1])) }
.fold(0) { acc, current -> if (current.first.any { current.second.contains(it) }) acc + 1 else acc }
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a26111fa1bcfec28cc43a2f48877455b783acc0d | 940 | advent-of-code-kotlin | Apache License 2.0 |
advent8/src/main/kotlin/Main.kt | thastreet | 574,294,123 | false | {"Kotlin": 29380} | import java.io.File
fun main(args: Array<String>) {
val lines = File("input.txt").readLines()
val trees: Array<Array<Int>> = parseTrees(lines)
val part1Answer = part1(trees)
println("part1Answer: $part1Answer")
val part2Answer = part2(trees)
println("part2Answer: $part2Answer")
}
fun parseTrees(lines: List<String>): Array<Array<Int>> =
Array(lines.size) { lineIndex ->
val line = lines[lineIndex]
Array(line.length) { charIndex ->
line[charIndex].digitToInt()
}
}
fun part1(trees: Array<Array<Int>>): Int {
var count = 2 * trees[0].size + (trees[0].size - 2) * 2
for (j in trees.indices) {
for (i in trees[0].indices) {
val row = trees[j]
val column = Array(trees.size) {
trees[it][i]
}
val tree = trees[j][i]
val visibleFromTop = (0 until j).all { column[it] < tree }
val visibleFromBottom = (column.size - 1 downTo j + 1).all { column[it] < tree }
val visibleFromLeft = (0 until i).all { row[it] < tree }
val visibleFromRight = (row.size - 1 downTo i + 1).all { row[it] < tree }
if (j > 0 && j < trees.size - 1 && i > 0 && i < trees[0].size - 1 && (visibleFromBottom || visibleFromTop || visibleFromRight || visibleFromLeft)) {
++count
}
}
}
return count
}
fun part2(trees: Array<Array<Int>>): Int {
var highest = 0
for (j in trees.indices) {
for (i in trees[0].indices) {
val row = trees[j]
val column = Array(trees.size) {
trees[it][i]
}
val tree = trees[j][i]
var top = 0
var bottom = 0
var left = 0
var right = 0
for (currentJ in j - 1 downTo 0) {
++top
if (column[currentJ] >= tree) break
}
for (currentJ in j + 1 until column.size) {
++bottom
if (column[currentJ] >= tree) break
}
for (currentI in i - 1 downTo 0) {
++left
if (row[currentI] >= tree) break
}
for (currentI in i + 1 until row.size) {
++right
if (row[currentI] >= tree) break
}
val score = top * bottom * left * right
if (score > highest) {
highest = score
}
}
}
return highest
} | 0 | Kotlin | 0 | 0 | e296de7db91dba0b44453601fa2b1696af9dbb15 | 2,545 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc2020/ex19.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | package aoc2020
import readInputFile
fun main() {
val input = readInputFile("aoc2020/input19")
//.replace(Regex("8: 42")) { "8: 42 | 42 8"}
//.replace(Regex("11: 42 31")) { "11: 42 31 | 42 11 31"}
// val input = """
// 0: 4 1 5
// 1: 2 3 | 3 2
// 2: 4 4 | 5 5
// 3: 4 5 | 5 4
// 4: "a"
// 5: "b"
//
// ababbb
// bababa
// abbbab
// aaabbb
// aaaabbb
// """.trimIndent()
val rulesLines = input.split("\n\n")[0].lines().let {
val index = it.indexOfFirst { it.startsWith("11:") }
it.toMutableList().apply {
val reg = (1..100).map {
val list = List(it) { 42 } + List(it) { 31 }
list.joinToString(" ")
}
val line = "11: " + reg.joinToString(" | ")
set(index, line)
}
}
println(rulesLines)
val messageLines = input.split("\n\n")[1].lines()
val rules = rulesLines.map {
val s = it.split(": ")
require(s.size == 2)
val index = s[0].toInt()
parseRule(index, s[1])
}.associateBy { it.index }
println(rules)
val expandedRule = expandRule(0, rules)
println(messageLines.count { expandedRule.matches(it) })
}
fun expandRule(index: RuleIndex, rules: Map<RuleIndex, RawRule>): Regex {
val cache = mutableMapOf<RuleIndex, Regex>()
return expandRuleRecursive(index, rules, cache)
}
fun expandRuleRecursive(
index: RuleIndex,
rules: Map<RuleIndex, RawRule>,
cache: MutableMap<RuleIndex, Regex>
): Regex {
return cache.getOrPut(index) {
if (index == 8) {
return expandRuleRecursive(42, rules, cache).pattern.let {
Regex("($it+)")
}
}
val rule = rules.getValue(index)
when (rule) {
is RawRule.Concat -> rule.concats.map {
expandRuleRecursive(it, rules, cache)
}.map {
it.pattern
}.joinToString("").let { Regex("($it)") }
is RawRule.Or -> {
rule.groups.map { group ->
group.map {
expandRuleRecursive(it, rules, cache)
}.map {
it.pattern
}.joinToString("").let { Regex("($it)") }
}.joinToString("|").let {
Regex("($it)")
}
}
is RawRule.Single -> Regex("(" + rule.string + ")")
}.also {
println("$rule matches $it")
}
}
}
private fun parseRule(index: RuleIndex, string: String): RawRule {
return when {
'"' in string -> {
require(string[2] == '"')
require(string.length == 3)
RawRule.Single(index, string[1])
}
'|' in string -> {
val s = string.split(" | ").filter { it.isNotEmpty() }
RawRule.Or(index, s.map { it.split(" ").map { it.toInt() } })
}
else -> {
val s = string.split(" ").map { it.toInt() }
RawRule.Concat(index, s)
}
}
}
private fun tests() {
// assertEquals(Rule.Single('a').matches("a"), 1)
// assertEquals(Rule.Single('b').matches("a"), -1)
// assertEquals(
// Rule.Single('a').concat(Rule.Single('b')).matches("a"),
// -1
// )
println("all tests passed")
}
private typealias RuleIndex = Int
sealed interface RawRule {
val index: RuleIndex
data class Single(override val index: RuleIndex, val string: Char) : RawRule
data class Concat(
override val index: RuleIndex,
val concats: List<RuleIndex>
) : RawRule {
override fun toString(): String {
return concats.joinToString(" ")
}
}
data class Or(
override val index: RuleIndex,
val groups: List<List<RuleIndex>>
) : RawRule {
override fun toString(): String {
return groups.map { it.joinToString(" ") }.joinToString("|")
}
}
} | 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 4,048 | AOC-2021 | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day23/Day23.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputSplitOnBlank
import java.util.*
import kotlin.math.abs
object Day23 : Day {
private val exits = listOf(2, 4, 6, 8)
override val input = readInputSplitOnBlank(23)
override fun part1() = sort(parseInput(0), 2)
override fun part2() = sort(parseInput(1), 4)
enum class Pod(val cost: Int) {
A(1),
B(10),
C(100),
D(1000)
}
private fun parseInput(problem: Int): List<List<Pod>> {
return input[problem].lines()
.map { l -> l.filter { c -> c in Pod.values().map { it.toString().single() } } }
.filter { it.isNotEmpty() }
.map { s -> s.map { Pod.valueOf(it.toString()) } }
.run { (0 until first().size).map { i -> map { it[i] } } }
.map { it.reversed() }
}
private fun sort(pods: List<List<Pod>>, roomSize: Int): Int {
val queue = PriorityQueue<State>().apply { add(State(0, Setup(pods))) }
val visited = mutableSetOf<Setup>()
while (queue.isNotEmpty()) {
with(queue.poll()) {
if (setup.isSorted(roomSize)) return energy
if (setup in visited) return@with
setup.moveToHallway(roomSize, energy, visited, queue)
setup.moveToRoom(roomSize, energy, visited, queue)
}
}
error("No result")
}
private fun Setup.moveToHallway(roomSize: Int, energy: Int, visited: MutableSet<Setup>, queue: PriorityQueue<State>) {
visited.add(this)
pods.asSequence()
.withIndex()
.filter { (i, v) -> v.isNotEmpty() && !v.sameRoom(i) }
.forEach { (i, v) ->
val pod = v.last()
listOf((exits[i] downTo 0) - exits, (exits[i]..10) - exits)
.forEach { side ->
side.takeWhile { isHallwayFree(it) }
.map { it to Setup(pods.edit(i, v.dropLast(1)), hallway.edit(it, pod.ordinal)) }
.filter { (_, setup) -> setup !in visited }
.map { (pos, setup) -> State(energy + (roomSize - v.size + abs(exits[i] - pos) + 1) * pod.cost, setup) }
.forEach { queue.add(it) }
}
}
}
private fun Setup.moveToRoom(roomSize: Int, energy: Int, visited: Set<Setup>, queue: PriorityQueue<State>) {
hallway.asSequence()
.withIndex()
.filter { (i, pod) -> !roomBlocked(i, pod) }
.map { (i, pod) -> Triple(Setup(pods.edit(pod!!, pods[pod] + Pod.values()[pod]), hallway.edit(i, null)), i, pod) }
.filter { (setup) -> setup !in visited }
.map { (setup, i, pod) -> State(energy + (roomSize - occupants(pod) + abs(exits[pod] - i)) * Pod.values()[pod].cost, setup) }
.toList()
.forEach { queue.add(it) }
}
private fun Setup.roomBlocked(index: Int, pod: Int?): Boolean {
return isHallwayFree(index) ||
index < exits[pod!!] && !isHallwayFree(index + 1 until exits[pod]) ||
index > exits[pod] && !isHallwayFree(exits[pod] + 1 until index) ||
pods[pod].any { it.ordinal != pod }
}
data class State(val energy: Int, val setup: Setup) : Comparable<State> {
override fun compareTo(other: State) = energy.compareTo(other.energy)
}
data class Setup(val pods: List<List<Pod>>, val hallway: List<Int?> = List(11) { null }) {
fun isSorted(size: Int) = hallway.all { it == null } && pods.withIndex().all { (i, v) -> v.size == size && v.sameRoom(i) }
fun isHallwayFree(index: Int) = hallway[index] == null
fun isHallwayFree(range: IntRange) = range.all { hallway[it] == null }
fun occupants(room: Int) = pods[room].size
}
private fun List<Pod>.sameRoom(number: Int) = isNotEmpty() && all { it.ordinal == number }
private fun <T> List<T>.edit(index: Int, value: T) = toMutableList().apply { set(index, value) }
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 4,108 | aoc2021 | MIT License |
src/Day13.kt | 6234456 | 572,616,769 | false | {"Kotlin": 39979} | import java.util.*
fun main() {
val digit = """\d+""".toRegex()
fun parse(s:String):List<Any>{
val stack = Stack<Any>()
var cnt = 0
while(cnt < s.length){
if(s[cnt] == '['){
stack.push('[')
}else if (digit.matchesAt(s, cnt)){
val v = digit.find(s, cnt)!!.value.toInt()
stack.push(v)
if (v > 9) cnt++
}else if (s[cnt] == ']'){
val l = mutableListOf<Any>()
while (stack.peek() != '['){
l.add(stack.pop())
}
stack.pop()
if (stack.isEmpty())
return l.reversed()
stack.push(l.reversed())
}
cnt++
}
return emptyList()
}
fun isRightOrder(l1: List<Any>, l2: List<Any>):Boolean{
val lower = kotlin.math.min(l1.size, l2.size)
(0 until lower).forEach {
if (l1[it] is List<*> && l2[it] is List<*>){
if (!isRightOrder(l1[it] as List<Any>, l2[it] as List<Any>)) return false
}else if (l1[it] is Int && l2[it] is Int){
if (l1[it] as Int > l2[it] as Int) return false
if ((l1[it] as Int) < l2[it] as Int) return true
}else if(l1[it] is Int){
if (!isRightOrder(listOf(l1[it] as Int), l2[it] as List<Any>)) return false
}else{
if (!isRightOrder(l1[it] as List<Any>, listOf(l2[it] as Int))) return false
}
}
return l1.size <= l2.size
}
fun part1(input: List<String>): Int {
return input.chunked(3).mapIndexed { index, strings ->
if (isRightOrder(parse(strings[0].trim()), parse(strings[1].trim()))) index + 1 else 0
}.sum()
}
fun part2(input: List<String>): Int{
return -1
}
var input = readInput("Test13")
println(part1(input))
println(part2(input))
input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b6d683e0900ab2136537089e2392b96905652c4e | 2,073 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | mythicaleinhorn | 572,689,424 | false | {"Kotlin": 11494} | fun IntRange.contains(range: IntRange): Boolean {
return this.first <= range.first && this.last >= range.last
}
fun IntRange.overlaps(range: IntRange): Boolean {
for (i in this) {
if (range.contains(i)) {
return true
}
}
return false
}
fun main() {
fun part1(input: List<String>): Int {
var sames = 0
for (line in input) {
val firstElve = line.substringBefore(',')
val secondElve = line.substringAfter(',')
val firstRange = firstElve.substringBefore("-").toInt()..firstElve.substringAfter("-").toInt()
val secondRange = secondElve.substringBefore("-").toInt()..secondElve.substringAfter("-").toInt()
if (firstRange.contains(secondRange) || secondRange.contains(firstRange)) {
sames++
continue
}
}
return sames
}
fun part2(input: List<String>): Int {
var overlaps = 0
for (line in input) {
val firstElve = line.substringBefore(',')
val secondElve = line.substringAfter(',')
val firstRange = firstElve.substringBefore("-").toInt()..firstElve.substringAfter("-").toInt()
val secondRange = secondElve.substringBefore("-").toInt()..secondElve.substringAfter("-").toInt()
if (firstRange.overlaps(secondRange)) {
overlaps++
}
}
return overlaps
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 959dc9f82c14f59d8e3f182043c59aa35e059381 | 1,737 | advent-of-code-2022 | Apache License 2.0 |
mapigate/src/main/java/com/github/unbearables/mapigate/gps/DijkstraGraph.kt | unbearables | 342,620,219 | false | {"Kotlin": 28908} | package com.github.unbearables.mapigate.gps
import com.github.unbearables.mapigate.map.MapMarker
data class Edge(val from: MapMarker, val to: MapMarker, val value: Double)
data class DijkstraResult(val markers: List<MapMarker>, val distanceStepMap: Map<Any, Double>,
val totalDistance: Double)
/**
* Non-directed Djikstra graph
*/
class DijkstraGraph {
private val edges = mutableSetOf<Edge>()
private val vertices = mutableSetOf<MapMarker>()
fun addLink(pair: Pair<MapMarker, MapMarker>, value: Double) {
val (from, to) = pair
vertices += from
vertices += to
edges.add(Edge(from, to, value))
edges.add(Edge(to, from, value))
}
/**
* Finds shortest path in djikstra graph
*/
fun shortestPath(from: MapMarker, target: MapMarker): DijkstraResult {
val unvisitedSet = vertices.toSet().toMutableSet() // clone set
val dists = vertices.map { it.markerId to Double.POSITIVE_INFINITY }.toMap().toMutableMap()
val paths = mutableMapOf<MapMarker, List<MapMarker>>()
dists[from.markerId] = 0.0 // 0 to itself
var curr = from // start from itself
while (unvisitedSet.isNotEmpty() && unvisitedSet.contains(target)) {
adjacentVertices(curr).forEach {
adj -> calcAdjacent(curr, adj, dists, paths)
}
unvisitedSet.remove(curr)
if (curr.markerId == target.markerId
|| unvisitedSet.all { dists[it.markerId]!!.isInfinite() }) {
break
}
if (unvisitedSet.isNotEmpty()) {
curr = unvisitedSet.minByOrNull { dists[it.markerId]!! }!!
}
}
if (paths.containsKey(target)) {
return dijkstraResult(target, paths[target]!!, dists)
}
return DijkstraResult(emptyList(), emptyMap(), 0.0) // no result
}
private fun calcAdjacent(curr: MapMarker, adj: MapMarker, dists: MutableMap<Any, Double>,
paths: MutableMap<MapMarker, List<MapMarker>>) {
val dist = getDistance(curr, adj)
if (dists[curr.markerId]!! + dist < dists[adj.markerId]!!) {
dists[adj.markerId] = dists[curr.markerId]!! + dist
paths[adj] = paths.getOrDefault(curr, listOf(curr)) + listOf(adj)
}
}
private fun dijkstraResult(target: MapMarker, markers: List<MapMarker>,
dists: MutableMap<Any, Double>): DijkstraResult {
val distStepMap = mutableMapOf<Any, Double>()
var lastDist = 0.0
var prevMarkerId: Any? = null
for ((i, m) in markers.withIndex()) {
if (i != 0) {
val distStep = dists[m.markerId]!!
distStepMap[prevMarkerId!!] = distStep - lastDist
lastDist = distStep
}
prevMarkerId = m.markerId
}
return DijkstraResult(markers, distStepMap, dists[target.markerId]!!)
}
private fun adjacentVertices(marker: MapMarker): Set<MapMarker> {
return edges
.filter { it.from.markerId == marker.markerId }
.map { it.to }
.toSet()
}
private fun getDistance(from: MapMarker, to: MapMarker): Double {
return edges
.filter { it.from.markerId == from.markerId && it.to.markerId == to.markerId }
.map { it.value }
.first()
}
}
| 0 | Kotlin | 0 | 1 | db314e26978d89e450137b24ddf54bb8e1611a19 | 3,567 | mapigate | Apache License 2.0 |
src/Day05.kt | pimtegelaar | 572,939,409 | false | {"Kotlin": 24985} | fun main() {
class Command(
val amount: Int,
val from: Int,
val to: Int
)
class Puzzle(
val commands: List<Command>,
val stacks: Array<ArrayDeque<Char>>
)
fun parseCommands(input: List<String>) = input.map {
val split = it.split(" ")
Command(split[1].toInt(), split[3].toInt(), split[5].toInt())
}
fun parseStacks(input: List<String>, separatorIndex: Int): Array<ArrayDeque<Char>> {
val size = input[separatorIndex - 1].takeLast(3).replace(" ", "").toInt()
val stacks = Array<ArrayDeque<Char>>(size) { ArrayDeque() }
input.take(separatorIndex - 1).forEach {
for (i in 0 until size) {
val crate = it[(i + 1) * 4 - 3]
if (crate.isLetter()) {
stacks[i].add(crate)
}
}
}
return stacks
}
fun parse(input: List<String>): Puzzle {
val separatorIndex = input.indexOfFirst { it.isBlank() }
return Puzzle(parseCommands(input.drop(separatorIndex + 1)), parseStacks(input, separatorIndex))
}
fun part1(input: List<String>): String {
val puzzle = parse(input)
val stacks = puzzle.stacks
puzzle.commands.forEach { command ->
repeat(command.amount) {
val crate = stacks[command.from - 1].removeFirst()
stacks[command.to - 1].addFirst(crate)
}
}
return stacks.map { it.first() }.joinToString("")
}
fun part2(input: List<String>): String {
val puzzle = parse(input)
val stacks = puzzle.stacks
puzzle.commands.forEach { command ->
val from = stacks[command.from - 1]
val toAdd = from.take(command.amount).toMutableList()
repeat(command.amount) {
stacks[command.from - 1].removeFirst()
stacks[command.to - 1].addFirst(toAdd.removeLast())
}
}
return stacks.map { it.first() }.joinToString("")
}
val testInput = readInput("Day05_test")
val input = readInput("Day05")
val part1 = part1(testInput)
check(part1 == "CMZ") { part1 }
println(part1(input))
val part2 = part2(testInput)
check(part2 == "MCD") { part2 }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16ac3580cafa74140530667413900640b80dcf35 | 2,332 | aoc-2022 | Apache License 2.0 |
src/kotlin2022/Day08.kt | egnbjork | 571,981,366 | false | {"Kotlin": 18156} | package kotlin2022
import readInput
import java.util.*
fun main() {
val gameInput = readInput("Day08_test")
val mapOfTrees = parseInput(gameInput)
var score = 0
val scoreSet = TreeSet<Int>()
for ((i, row) in mapOfTrees.withIndex()) {
for ((n, tree) in row.withIndex()) {
if (notABorderTree(i, n, mapOfTrees.size, row.size)) {
score += scoreLeft(tree, i, n, mapOfTrees) *
scoreUp(tree, i, n, mapOfTrees) *
scoreRight(tree, i, n, mapOfTrees, row.size) *
scoreDown(tree, i, n, mapOfTrees)
}
scoreSet.add(score)
score = 0
}
}
println(scoreSet.last())
}
fun scoreUp(tree: Int, i: Int, n: Int, mapOfTrees: List<List<Int>>): Int {
var score = 0
repeat(i) {index ->
if(tree > mapOfTrees[i - index - 1][n]) {
score++
} else return ++score
}
return score
}
fun scoreRight(tree: Int, i: Int, n: Int, mapOfTrees: List<List<Int>>, rowSize: Int): Int {
var score = 0
repeat(rowSize - n - 1) { index ->
if (tree > mapOfTrees[i][index + n + 1]) {
score++
} else return ++score
}
return score
}
fun scoreDown(tree: Int, i: Int, n: Int, mapOfTrees: List<List<Int>>): Int {
var score = 0
repeat(mapOfTrees.size - i - 1) { index ->
if (tree > mapOfTrees[i + index + 1][n]) {
score++
} else return ++score
}
return score
}
fun scoreLeft(tree: Int, i: Int, n: Int, mapOfTrees: List<List<Int>>): Int {
var score = 0
repeat(n) { index ->
if (tree > mapOfTrees[i][n - index - 1]) {
score++
} else return ++score
}
return score
}
fun notABorderTree(i: Int, n: Int, mapSize: Int, rowSize: Int): Boolean {
return i != 0 &&
n != 0 &&
i != mapSize - 1
&& n != rowSize -1}
fun parseInput(gameInput: List<String>): List<List<Int>> {
val arr = mutableListOf<MutableList<Int>>()
for(line in gameInput) {
val row = mutableListOf<Int>()
for(char in line.toCharArray()) {
row.add(char.digitToInt())
}
arr.add(row)
}
return arr
}
//30373
//25512
//65332
//33549
//35390 | 0 | Kotlin | 0 | 0 | 1294afde171a64b1a2dfad2d30ff495d52f227f5 | 2,306 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/solutions/Day16ProboscideaVolcanium.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import utils.Input
import utils.Solution
import kotlin.math.max
// run only this day
fun main() {
Day16ProboscideaVolcanium()
}
class Day16ProboscideaVolcanium : Solution() {
private val thirty = 30
init {
begin("Day 16 - Proboscidea Volcanium")
val input = Input.parseLines(filename = "/d16_valve_map.txt")
.map { line ->
val captureGroups = """Valve (\S{2}).*=(\d+);.*(?:valve|valves) (.+)""".toRegex()
.find(line)!!.groupValues.drop(1)
Valve(
name = captureGroups[0],
flowRate = captureGroups[1].toInt(),
flowTotalAt = IntRange(1, thirty).map { it * captureGroups[1].toInt() }.reversed(),
connections = captureGroups[2].split(", ")
)
}
val fullGraph = input.associateBy { v -> v.name }
generateTravelMaps(fullGraph)
val sol1 = releaseMostPressure(fullGraph)
output("Max Pressure Release", sol1)
val sol2 = releasePressureElephantStyle(fullGraph)
output("Max Elephant-Assisted Pressure Release", sol2)
}
private fun releaseMostPressure(graph: Map<String, Valve>): Int =
findAllPaths(
graph.filter { it.value.flowRate != 0 || it.value.name == "AA" },
start = "AA",
).values.max()
private fun releasePressureElephantStyle(graph: Map<String, Valve>): Int {
val pathMap = findAllPaths(
graph.filter { it.value.flowRate != 0 || it.value.name == "AA" },
start = "AA",
startOffset = 4
).mapKeys { it.key.removePrefix("AA,") }
val paths = with(pathMap.entries.sortedByDescending { it.value }.map { it.key }) {
associateWith { it.split(',').toSet() }
}
var maxAssistedFlow = 0
for (p in paths) {
for (p2 in paths) {
if (p.value.intersect(p2.value).isEmpty()) {
maxAssistedFlow = max(
maxAssistedFlow,
pathMap[p.key]!! + pathMap[p2.key]!!
)
break
}
}
}
return maxAssistedFlow
}
private fun findAllPaths(
graph: Map<String, Valve>,
start: String,
maxFlow: Int = 0,
curPath: MutableList<String> = mutableListOf(),
startOffset: Int = 0
): Map<String, Int> {
// local var init
var mflow = maxFlow
val scoreMap = mutableMapOf<String, Int>()
// add current node to path
curPath.add(start)
// if current steps are over the max time, just break out of this path - else maybe add a max flow
if (overTime(curPath.map { graph[it]!! }, startOffset)) {
return scoreMap
} else scoreMap[curPath.joinToString(",")] = calculateTotalFlow(curPath.map { graph[it]!! }, startOffset)
// TODO: if this works, try with actual valves, not strings, should reduce conversions
val next = graph.map { it.value.name }.filter { it !in curPath }
// when neighbors available
for (n in next) {
val result = findAllPaths(graph, n, mflow, curPath, startOffset)
if (result.isNotEmpty()) {
result.forEach {
mflow = max(mflow, it.value)
scoreMap[it.key] = it.value
}
}
curPath.removeLast()
}
return scoreMap
}
// the additional 'path.size - 1' adds a step for the 'open valve' action
private fun overTime(path: List<Valve>, startOffset: Int = 0): Boolean =
path.mapIndexed { i, v ->
if (i < path.size - 1) {
v.stepsTo[path[i + 1].name]!!
} else 0
}.sum() + (path.size) + startOffset > thirty
// calculates flow of open valves across time
private fun calculateTotalFlow(pathItems: List<Valve>, startOffset: Int = 0): Int {
var minute = 1 + startOffset
var totalFlow = 0
pathItems.windowed(2).forEach { w ->
// +1 for opening valve action
minute += (w.first().stepsTo[w.last().name]!! + 1)
// add to total flow for remaining minutes
totalFlow += w.last().flowTotalAt[minute - 1]
}
return totalFlow
}
private fun generateTravelMaps(vGraph: Map<String, Valve>) {
val valveKeys = vGraph.keys
valveKeys.forEach { k ->
val v = vGraph[k]!!
v.stepsTo[v.name] = 0
val searchFrontier = mutableListOf(k)
val visited = mutableListOf<String>()
val parent = mutableMapOf<String, String>()
// until all step counts found
while (v.stepsTo.size < valveKeys.size) {
val curCon = searchFrontier.removeFirst()
visited.add(curCon)
val newCons = vGraph[curCon]!!.connections.filterNot { it in visited }
searchFrontier.addAll(newCons)
newCons.forEach { n ->
// add connection parent
parent[n] = curCon
// add steps from current valve
var nextParent = n
var steps = 0
while (nextParent != k) {
// use existing data to short-circuit parent search
// (seems like it doesn't have much effect...)
if (v.stepsTo.keys.contains(nextParent)) {
steps += v.stepsTo[nextParent]!!
break
}
nextParent = parent[nextParent]!!
steps++
}
v.stepsTo[n] = steps
}
}
}
}
// tODO: strip unneeded properties
private data class Valve(
val name: String,
val flowRate: Int,
val flowTotalAt: List<Int>,
val connections: List<String>,
var isOpen: Boolean = false,
val stepsTo: MutableMap<String, Int> = mutableMapOf(),
)
}
/**
* optimize notes - maybe no need to do dfs twice
*
* 0 - try using valves instead of string lists to reduce conversions during dfs (may not help)
* 1 - pass 30-minute search into part 2
* 2 - don't to dfs again, but loop over map of valves and check if over time (at the same time as intersecting?)
* x - remove time offset from dfs since it's only needed for p2 calculations
* x - address todos/cleanup, comment nicely
*
* Benchmark
* Part 1 -> Max Pressure Release = 2250
* -- 694 ms
* Part 2 -> Max Elephant-Assisted Pressure Release = 3015
* -- 1767 ms
*/ | 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 6,846 | advent-of-code-2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumFinishTime.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* 2188. Minimum Time to Finish the Race
* @see <a href="https://leetcode.com/problems/minimum-time-to-finish-the-race/">Source</a>
*/
fun interface MinimumFinishTime {
operator fun invoke(tires: Array<IntArray>, changeTime: Int, numLaps: Int): Int
}
class MinimumFinishTimeDP : MinimumFinishTime {
override operator fun invoke(tires: Array<IntArray>, changeTime: Int, numLaps: Int): Int {
val minTime = IntArray(numLaps + 1) { Int.MAX_VALUE }
for (tire in tires) {
checkMinTime(tire, minTime, changeTime, numLaps)
}
for (i in 2..numLaps) {
for (j in 1 until i) {
val remain = i % j
// Greedy, in order to get the minimal runtime, we should repeat the same loop as much as possible.
val currMin: Int = if (remain != 0) {
i / j * (minTime[j] + changeTime) + minTime[remain]
} else {
// The last changeTime is not required if remain is 0
i / j * (minTime[j] + changeTime) - changeTime
}
minTime[i] = min(minTime[i], currMin)
}
}
return minTime[numLaps]
}
private fun checkMinTime(tire: IntArray, minTime: IntArray, changeTime: Int, numLaps: Int) {
val base = tire[0]
var lap = 1
var curr = base
minTime[lap] = min(minTime[lap], curr)
var sum = base
// Greedy, if changeTime + base is smaller, the minimal runtime for the next lap
// will not be better than minTime[lap - 1] + changeTime + minTime[1]
while (curr * tire[1] - base <= changeTime && lap++ < numLaps) {
curr *= tire[1]
sum += curr
minTime[lap] = min(minTime[lap], sum)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,478 | kotlab | Apache License 2.0 |
src/main/kotlin/Day15.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | import java.util.*
import kotlin.math.abs
fun main() {
val input = readFileAsList("Day15")
println(Day15.part1(input, 10))
println(Day15.part2(input, 4000000))
}
object Day15 {
fun part1(input: List<String>, lookupY: Int): Int {
val sensors = parseSensors(input)
val coveredXsAtY = coveredXsAtYBySensors(sensors, lookupY)
return coveredXsAtY.size - 1
}
fun part2(input: List<String>, searchLength: Int): Long {
val sensors = parseSensors(input)
val searchRange = 0..searchLength
for (lookupY in searchRange) {
var lookupX = 0
while (lookupX < searchLength) {
val coveringSensor = sensors.firstOrNull { sensor ->
val vector = Vector2d(lookupX, lookupY)
val distanceToSensor = vector distanceTo sensor.position
distanceToSensor <= sensor.coveredDistance
}
if (coveringSensor == null) {
return return 4_000_000L * lookupX + lookupY
}
val rangeAtY = coveringSensor.coveredDistance - abs(lookupY - coveringSensor.y)
lookupX = coveringSensor.x + rangeAtY + 1
}
println(lookupY)
}
return 0
}
private fun coveredXsAtYBySensors(
sensors: MutableSet<Sensor>,
lookupY: Int
): TreeSet<Int> {
val coveredXsAtY = TreeSet<Int>()
for (sensor in sensors) {
val radiusAtY = sensor.coveredDistance - abs(lookupY - sensor.y)
coveredXsAtY.addAll((sensor.x - radiusAtY)..sensor.x + radiusAtY)
}
return coveredXsAtY
}
private fun parseSensors(input: List<String>): MutableSet<Sensor> {
val sensors = mutableSetOf<Sensor>()
for (inputLine in input) {
val (sensorDesc, beaconDesc) = inputLine.split(": ")
val sensorX = sensorDesc.substringAfter("x=")
.substringBefore(",")
.toInt()
val sensorY = sensorDesc.substringAfter("y=")
.substringBefore(",")
.toInt()
val beaconX = beaconDesc.substringAfter("x=")
.substringBefore(",")
.toInt()
val beaconY = beaconDesc.substringAfter("y=")
.substringBefore(",")
.toInt()
val sensorPosition = Vector2d(sensorX, sensorY)
val beaconPosition = Vector2d(beaconX, beaconY)
val sensor = Sensor(sensorPosition, sensorPosition distanceTo beaconPosition)
sensors.add(sensor)
}
return sensors
}
data class Sensor(val position: Vector2d, val coveredDistance: Int): Position2d by position
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 2,792 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | KliminV | 573,758,839 | false | {"Kotlin": 19586} | fun main() {
fun part1(input: List<String>): Int {
return input.map {
it.chunkAtIndex(it.length / 2)
}
.map { strings ->
val things = strings.get(0).toCharArray().toSet()
val wrongThing = strings.get(1).filter { things.contains(it) }
.first()
wrongThing.getPriority()
}
.sum()
}
fun part2(input: List<String>): Int {
val badge = input.chunked(3).map {
it.get(0)
.toCharArray()
.filter { element -> it.get(1).contains(element) }
.filter { element -> it.get(2).contains(element) }
.first()
}
return badge.map { it.getPriority() }.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
fun Char.getPriority(): Int {
return if (this.isLowerCase()) {
Character.getNumericValue(this).minus(9)
} else {
Character.getNumericValue(this).plus(17)
}
}
| 0 | Kotlin | 0 | 0 | 542991741cf37481515900894480304d52a989ae | 1,250 | AOC-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/anahoret/aoc2022/day09/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day09
import java.io.File
import kotlin.math.*
data class Point(val x: Int, val y: Int) {
operator fun plus(move: Move): Point {
return Point(x + move.dx, y + move.dy)
}
fun follow(target: Point): Point {
val dx = target.x - x
val dy = target.y - y
return if (abs(dx) > 1 && abs(dy) > 0 || abs(dx) > 0 && abs(dy) > 1) this + Move(dx.sign, dy.sign)
else if (abs(dx) > 1) this + Move(dx.sign, 0)
else if (abs(dy) > 1) this + Move(0, dy.sign)
else this
}
}
data class Move(val dx: Int, val dy: Int) {
companion object {
private val moves = mapOf(
"U" to Move(0, -1),
"D" to Move(0, 1),
"L" to Move(-1, 0),
"R" to Move(1, 0)
)
fun parse(str: String): List<Move> {
val (direction, steps) = str.split(" ")
val move = moves.getValue(direction)
return List(steps.toInt()) { move }
}
}
}
fun main() {
val moves = File("src/main/kotlin/com/anahoret/aoc2022/day09/input.txt")
.readText()
.trim()
.split("\n")
.flatMap { Move.parse(it) }
// Part 1
part1(moves)
// Part 2
part2(moves)
}
private fun part1(moves: List<Move>) {
println(trackTail(2, moves))
}
private fun part2(moves: List<Move>) {
println(trackTail(10, moves))
}
private fun trackTail(length: Int, moves: List<Move>): Int {
val rope = Array(length) { Point(0, 0) }
val res = mutableSetOf<Point>()
fun shiftRope(move: Move) {
rope.indices.forEach { idx ->
when (idx) {
0 -> rope[idx] = rope[idx] + move
else -> rope[idx] = rope[idx].follow(rope[idx - 1])
}
}
}
res.add(rope.last())
moves.forEach { move ->
shiftRope(move)
res.add(rope.last())
}
return res.size
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 1,937 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-08.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.IntGrid
import com.github.ferinagy.adventOfCode.get
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import com.github.ferinagy.adventOfCode.toIntGrid
fun main() {
val input = readInputLines(2022, "08-input")
val testInput1 = readInputLines(2022, "08-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val grid = input.map { line -> line.map { it.digitToInt() } }.toIntGrid()
val visible = mutableSetOf<Coord2D>()
fun Coord2D.rotate(times: Int): Coord2D =
if (times == 0) this else Coord2D(y, grid.width - 1 - x).rotate(times - 1)
repeat(4) { dir ->
for (y in 0 until grid.height) {
var max = -1
for (x in 0 until grid.width) {
val coord = Coord2D(x, y).rotate(dir)
if (max < grid[coord]) {
visible += coord
max = grid[coord]
}
}
}
}
return visible.size
}
private fun part2(input: List<String>): Int {
val grid = input.map { line -> line.map { it.digitToInt() } }.toIntGrid()
val scores = IntGrid(grid.width, grid.height) { x, y -> scenicScore(grid, x, y) }
return scores.maxOrNull()!!
}
private fun scenicScore(grid: IntGrid, x: Int, y: Int): Int {
val current = grid[x, y]
val up = visibleTrees(current, isAtEdge = { y - it == 0 }, next = { grid[x, y - it] })
val down = visibleTrees(current, isAtEdge = { y + it == grid.height - 1 }, next = { grid[x, y + it] })
val left = visibleTrees(current, isAtEdge = { x - it == 0 }, next = { grid[x - it, y] })
val right = visibleTrees(current, isAtEdge = { x + it == grid.width - 1 }, next = { grid[x + it, y] })
return up * down * left * right
}
private fun visibleTrees(current: Int, isAtEdge: (Int) -> Boolean, next: (Int) -> Int): Int {
var up = 0
if (!isAtEdge(up)) {
while (true) {
up++
if (isAtEdge(up) || current <= next(up)) break
}
}
return up
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,360 | advent-of-code | MIT License |
src/Day04.kt | bananer | 434,885,332 | false | {"Kotlin": 36979} | fun main() {
class Field(
val number: Int,
var checked: Boolean = false,
) {
override fun toString(): String = (if (checked) "X" else " ") + number
}
val boardSize = 5
class Board(
val fields: Array<Array<Field>>,
var win: Boolean = false,
) {
constructor(lines: List<String>) :
this(lines
.also { assert(it.size == boardSize) }
.map { line ->
line.trim().split(Regex("\\s+"))
.also { assert(it.size == boardSize) }
.map {
Field(Integer.parseInt(it.trim()))
}.toTypedArray()
}.toTypedArray()
)
private fun checkWin() {
for (x in 0 until boardSize) {
if ((0 until boardSize).all { y ->
fields[x][y].checked
}) {
win = true
return
}
}
for (y in 0 until boardSize) {
if ((0 until boardSize).all { x ->
fields[x][y].checked
}) {
win = true
return
}
}
}
fun numberDrawn(number: Int) {
for (fieldRow in fields) {
for (field in fieldRow) {
if (field.number == number) {
field.checked = true
checkWin()
return
}
}
}
}
fun sumOfUnmarked(): Int {
return fields.flatten().filter { !it.checked }.sumOf { it.number }
}
override fun toString(): String {
return fields.map { row ->
row.map { field ->
field.toString()
}.joinToString(" ")
}.joinToString("\n")
}
}
fun parseInput(input: List<String>): Pair<List<Int>, List<Board>> {
val numbers = input[0].split(",").map { Integer.parseInt(it) }
var pos = 1
val boards = mutableListOf<Board>()
while (pos + boardSize < input.size) {
boards.add(Board(input.subList(pos + 1, pos + boardSize + 1)))
pos += boardSize + 1
}
return Pair(numbers, boards)
}
fun part1(input: List<String>): Int {
val (numbers, boards) = parseInput(input)
for (n in numbers) {
for (b in boards) {
b.numberDrawn(n)
if (b.win) {
return b.sumOfUnmarked() * n
}
}
}
throw IllegalStateException("No board won")
}
fun part2(input: List<String>): Int {
val (numbers, boards) = parseInput(input)
val boardsLeft = boards.toMutableList()
for (n in numbers) {
for (b in boardsLeft.toList()) {
b.numberDrawn(n)
if (b.win) {
if (boardsLeft.size == 1) {
return b.sumOfUnmarked() * n
}
boardsLeft.remove(b)
}
}
}
throw IllegalStateException("No board won")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val testOutput1 = part1(testInput)
check(testOutput1 == 4512)
println("test output1: $testOutput1")
val testOutput2 = part2(testInput)
println("test output2: $testOutput2")
check(testOutput2 == 1924)
val input = readInput("Day04")
println("output part1: ${part1(input)}")
println("output part2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 98f7d6b3dd9eefebef5fa3179ca331fef5ed975b | 3,863 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2023/Day17.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2023
import arrow.core.partially1
import arrow.core.partially2
import ru.timakden.aoc.util.Point
import ru.timakden.aoc.util.Point.Companion.DOWN
import ru.timakden.aoc.util.Point.Companion.LEFT
import ru.timakden.aoc.util.Point.Companion.RIGHT
import ru.timakden.aoc.util.Point.Companion.UP
import ru.timakden.aoc.util.dijkstra
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 17: Clumsy Crucible](https://adventofcode.com/2023/day/17).
*/
object Day17 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2023/Day17")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>) = solve(input)
fun part2(input: List<String>) = solve(input, 4, 10)
private data class State(val position: Point, val dir: Point, val sameDirMoves: Int)
private fun neighbors(
grid: List<List<Int>>,
state: State,
minMoves: Int,
maxMoves: Int
): List<State> {
return buildList {
for (dir in listOf(UP, DOWN, LEFT, RIGHT)) {
val newPosition = state.position + dir
val movesSoFar = if (dir == state.dir) state.sameDirMoves + 1 else 1
val (a, b) = newPosition
if (a !in grid.indices || b !in grid[0].indices) continue
if (movesSoFar > maxMoves) continue
if (dir.x * -1 == state.dir.x && dir.y * -1 == state.dir.y) continue
if (dir != state.dir && state.sameDirMoves < minMoves) continue
add(State(newPosition, dir, movesSoFar))
}
}
}
private fun startingPoint(point: Point): State = State(Point(0, 0), point, 0)
private fun solve(s: List<String>, minMoves: Int = 1, maxMoves: Int = 3): UInt {
val grid = s.map { it.map { char -> char.toString().toInt() } }
val startingPoints = listOf(UP, DOWN, LEFT, RIGHT).map { startingPoint(it) }
val neighbors = ::neighbors.partially1(grid).partially2(minMoves).partially2(maxMoves)
val bestDistance = dijkstra(startingPoints, neighbors) { _, nextNode ->
grid[nextNode.position.x][nextNode.position.y].toUInt()
}
val result = bestDistance.filter { (k, _) -> k.position == Point(grid.indices.last, grid[0].indices.last) }
return result.filterKeys { it.sameDirMoves in minMoves..maxMoves }.minOf { (_, value) -> value }
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 2,559 | advent-of-code | MIT License |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-15.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputText
fun main() {
val input = readInputText(2023, "15-input")
val test1 = readInputText(2023, "15-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: String): Int {
val list = input.split(',')
return list.sumOf(::hash)
}
private fun part2(input: String): Int {
val list = input.split(',')
val boxes = Array(256) { mutableListOf<Pair<String, Int>>() }
list.forEach { instruction ->
val label = instruction.takeWhile { it.isLetter() }
val op = instruction.dropWhile { it.isLetter() }
when (op[0]) {
'-' -> {
val hash = hash(label)
boxes[hash].removeAll { it.first == label }
}
'=' -> {
val focal = op.drop(1).toInt()
val hash = hash(label)
val position = boxes[hash].indexOfFirst { it.first == label }
if (position == -1) boxes[hash] += label to focal else boxes[hash][position] = label to focal
}
}
}
return boxes.withIndex().sumOf { (box, lenses) ->
(box + 1) * lenses.withIndex().sumOf { (it.index + 1) * it.value.second }
}
}
private fun hash(input: String) = input.fold(0) { acc, c -> ((acc + c.code) * 17) % 256 }
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,546 | advent-of-code | MIT License |
2022/Day23.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
data class Pos(
val x: Int,
val y: Int
) {
fun nw() = Pos(x-1, y-1)
fun n() = Pos(x, y-1)
fun ne() = Pos(x+1, y-1)
fun e() = Pos(x+1, y)
fun se() = Pos(x+1, y+1)
fun s() = Pos(x, y+1)
fun sw() = Pos(x-1, y+1)
fun w() = Pos(x-1, y)
fun all() = listOf(nw(), n(), ne(), e(), se(), s(), sw(), w())
fun northSide() = listOf(nw(), n(), ne())
fun southSide() = listOf(sw(), s(), se())
fun westSide() = listOf(nw(), w(), sw())
fun eastSide() = listOf(ne(), e(), se())
fun sides() = listOf(northSide(), southSide(), westSide(), eastSide())
}
val map = readInput("Day23")
var elves = HashSet<Pos>()
for (y in map.indices) {
for (x in map[y].indices) {
if (map[y][x] == '#') {
elves.add(Pos(x,y))
}
}
}
fun printMap() {
for (y in elves.minOf { it.y } .. elves.maxOf { it.y }) {
for (x in elves.minOf { it.x } .. elves.maxOf { it.x })
print(if (Pos(x, y) in elves) "#" else ".")
println()
}
println()
}
fun newPos(e: Pos, time: Int): Pos {
if (e.all().all { it !in elves }) return e
for (t in time until time+4) {
val side = e.sides()[t % 4]
if (side.all { it !in elves }) return side[1]
}
return e
}
repeat(10) { time ->
val newSet = elves.groupBy { newPos(it, time) }
elves = elves.map { e ->
newPos(e, time).takeIf { newSet[it]!!.size == 1 } ?: e
}.toHashSet()
//printMap()
}
var res1 = 0
for (x in elves.minOf { it.x } .. elves.maxOf { it.x }) {
for (y in elves.minOf { it.y } .. elves.maxOf { it.y }) {
if (Pos(x,y) !in elves) res1++
}
}
println(res1)
for (time in 10 until 10000) {
val newSet = elves.groupBy { newPos(it, time) }
val elves1 = elves.map { e ->
newPos(e, time).takeIf { newSet[it]!!.size == 1 } ?: e
}.toHashSet()
if (elves == elves1) {
println(time+1)
break
}
elves = elves1
}
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 2,241 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/me/ccampo/librepoker/engine/util/HandEvaluator.kt | ccampo133 | 113,806,624 | false | null | package me.ccampo.librepoker.engine.util
import me.ccampo.librepoker.engine.model.Card
import me.ccampo.librepoker.engine.model.Hand
import me.ccampo.librepoker.engine.model.HandScore
import me.ccampo.librepoker.engine.model.HandType
/**
* @author <NAME>
*/
/**
* First sort the cards in descending order, and then put any pairs/sets/quads
* of cards in front. Example, A K 4 J 4 becomes 4 4 J K A
*
* See: https://stackoverflow.com/questions/42380183/algorithm-to-give-a-value-to-a-5-card-poker-hand
*/
fun evaluate(hand: Hand): HandScore {
val groups = hand.cards
.sortedByDescending { it.face.weight }
.groupBy { it.face }
.toSortedMap(compareByDescending { it.weight })
val type = when (groups.size) {
2 -> if (groups.any { it.value.size == 4 }) HandType.FOUR_OF_A_KIND else HandType.FULL_HOUSE
3 -> if (groups.any { it.value.size == 3 }) HandType.THREE_OF_A_KIND else HandType.TWO_PAIR
4 -> HandType.PAIR
else -> {
val flush = hand.isFlush()
val straight = hand.isStraight()
when {
flush && straight -> if (hand.cards.sumBy { it.face.weight } == 60) HandType.ROYAL_FLUSH else HandType.STRAIGHT_FLUSH
flush -> HandType.FLUSH
straight -> HandType.STRAIGHT
else -> HandType.HIGH_CARD
}
}
}
val score = groups.values
.sortedByDescending { it.size }
.flatten()
.fold(type.rank, { score, card -> (score shl 4) + card.face.weight })
return HandScore(type, score)
}
fun sort(cards: List<Card>): List<Card> {
return cards
.sortedByDescending { it.face.weight }
.groupBy { it.face }
.toSortedMap(compareByDescending { it.weight })
.values
.sortedByDescending { it.size }
.flatten()
}
fun getBestHand(cards: List<Card>): Hand {
return cards.combinations(5).map { Hand(it) }.maxBy { it.score.score }!!
}
private fun <T> List<T>.combinations(n: Int): List<List<T>> {
fun <T> combinations(l: List<T>, n: Int): List<List<T>> {
val result = mutableListOf<List<T>>()
when {
n > l.size -> throw IllegalArgumentException("Value n must be less than or equal to the list size")
n == l.size -> result.add(l)
n == 0 -> result.add(emptyList())
n < l.size -> result.addAll(combinations(l.tail, n) + combinations(l.tail, n - 1).map { it + l.head })
}
return result
}
return combinations(this, n)
}
private val <T> List<T>.tail: List<T> get() = drop(1)
private val <T> List<T>.head: T get() = first()
| 0 | null | 0 | 0 | 77e678d9c0d871569ebcbedb3f0c835722a4f4c3 | 2,486 | librepoker | MIT License |
src/main/kotlin/aoc/year2023/Day03.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2023
import aoc.Puzzle
private typealias Cell = Pair<Int, Int>
/**
* [Day 3 - Advent of Code 2023](https://adventofcode.com/2023/day/3)
*/
object Day03 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int {
val lines = input.lines()
val (symbolCells, digitCells) = lines.getCells { it != '.' }
return digitCells.filter { it.adjacentCells.any(symbolCells::contains) }
.map { it.value.toInt() }
.sum()
}
override fun solvePartTwo(input: String): Int {
val lines = input.lines()
val (gearCells, digitCells) = lines.getCells { it == '*' }
return digitCells.flatMap { it.adjacentCells.filter(gearCells::contains).map { cell -> cell to it.value } }
.groupBy({ it.first }, { it.second })
.values
.filter { it.size == 2 }
.sumOf { it.map(String::toInt).reduce(Int::times) }
}
private fun List<String>.getCells(symbolFilter: (Char) -> Boolean): Pair<Set<Cell>, Map<Cell, String>> {
val symbolCells = hashSetOf<Cell>()
val digitCells = hashMapOf<Cell, String>()
val digits = arrayListOf<Char>()
fun saveDigitCell(x: Int, y: Int) {
if (digits.isNotEmpty()) {
digitCells += (x - digits.size to y) to String(digits.toCharArray())
digits.clear()
}
}
for ((y, line) in withIndex()) {
for ((x, char) in line.withIndex()) {
if (char.isDigit()) {
digits += char
} else {
saveDigitCell(x, y)
if (symbolFilter(char)) {
symbolCells += x to y
}
}
}
// Edge case: end-of-line number
saveDigitCell(line.length, y)
}
return symbolCells to digitCells
}
private val Map.Entry<Cell, String>.adjacentCells: List<Cell>
get() = buildList {
val (x, y) = key
val length = value.length
generateSequence(x - 1) { it + 1 }
.take(length + 2)
.forEach {
add(it to y - 1)
add(it to y + 1)
}
add(x - 1 to y)
add(x + length to y)
}
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 2,374 | advent-of-code | Apache License 2.0 |
src/days/Day01.kt | EnergyFusion | 572,490,067 | false | {"Kotlin": 48323} | fun main() {
fun part1(input: List<String>): Int {
val elfCalorieMap = mutableMapOf<Int, Int>()
var currentElf = 0
for (line in input) {
if (line.isBlank()) {
currentElf++
} else {
val calorie = line.toInt()
val currentVal = elfCalorieMap.getOrDefault(currentElf, 0)
elfCalorieMap[currentElf] = currentVal + calorie
}
}
return elfCalorieMap.values.maxOrNull() ?: 0
}
fun part2(input: List<String>): Int {
var elfCalorieMap = mutableMapOf<Int, Int>()
var currentElf = 0
for (line in input) {
if (line.isBlank()) {
currentElf++
if (elfCalorieMap.size > 3) {
elfCalorieMap = elfCalorieMap.toList().sortedBy { (_, value) -> value }.takeLast(3).toMap().toMutableMap()
}
} else {
val calorie = line.toInt()
val currentVal = elfCalorieMap.getOrDefault(currentElf, 0)
elfCalorieMap[currentElf] = currentVal + calorie
}
}
if (elfCalorieMap.size > 3) {
elfCalorieMap = elfCalorieMap.toList().sortedBy { (_, value) -> value }.takeLast(3).toMap().toMutableMap()
}
return elfCalorieMap.values.sumOf { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("tests/Day01")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("input/Day01")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 06fb8085a8b1838289a4e1599e2135cb5e28c1bf | 1,663 | advent-of-code-kotlin | Apache License 2.0 |
2022/src/main/kotlin/de/skyrising/aoc2022/day11/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2022.day11
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.longs.LongArrayList
import it.unimi.dsi.fastutil.longs.LongList
import java.util.function.LongConsumer
data class Monkey(val items: LongList, val op: (Long) -> Long, val divisor: Int, val trueMonkey: Int, val falseMonkey: Int) {
var inspected = 0L
fun step(monkeys: List<Monkey>, divideByThree: Boolean) {
items.forEach(LongConsumer { item ->
var newLevel = op(item)
if (divideByThree) {
newLevel /= 3
}
newLevel %= 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19
val throwTo = if (newLevel % divisor == 0L) trueMonkey else falseMonkey
monkeys[throwTo].items.add(newLevel)
inspected++
})
items.clear()
}
}
private fun monkeyBusiness(input: PuzzleInput, steps: Int, divideByThree: Boolean): Long {
val monkeys = parseInput(input)
repeat(steps) {
for (monkey in monkeys) {
monkey.step(monkeys, divideByThree)
}
}
val (a, b) = monkeys.sortedByDescending(Monkey::inspected).take(2)
return a.inspected * b.inspected
}
private fun parseInput(input: PuzzleInput): List<Monkey> {
return input.lines.chunked(7) {
val startingItems = it[1].ints()
val opText = it[2].substringAfter("= ")
val split = opText.split(' ')
val op: (Long) -> Long = when {
split[2] == "old" -> { x -> x * x }
split[1] == "*" -> {
val factor = split[2].toInt();
{ x -> x * factor }
}
split[1] == "+" -> {
val addend = split[2].toInt();
{ x -> x + addend }
}
else -> error("Unknown op: $opText")
}
val divisor = it[3].ints().getInt(0)
val trueMonkey = it[4].ints().getInt(0)
val falseMonkey = it[5].ints().getInt(0)
Monkey(startingItems.mapTo(LongArrayList(), Int::toLong), op, divisor, trueMonkey, falseMonkey)
}
}
@PuzzleName("Monkey in the Middle")
fun PuzzleInput.part1() = monkeyBusiness(this, 20, true)
fun PuzzleInput.part2() = monkeyBusiness(this, 10000, false)
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,216 | aoc | MIT License |
src/Day10.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | class CPU {
private val cyclesMap = mutableMapOf<IntRange, Int>()
private var x = 1
private var cycle = 1
private val toCompute = listOf(20, 60, 100, 140, 180, 220)
fun add(v: Int) {
val startCycle = cycle
cycle += 2
cyclesMap[startCycle until cycle] = x
x += v
}
fun noop() {
val startCycle = cycle
cycle += 1
cyclesMap[startCycle until cycle] = x
}
fun signalStrength(): Int {
return cyclesMap.keys.sortedBy { it.first }.sumOf { cycles ->
toCompute.firstOrNull { cycles.contains(it) }?.let { cycle ->
cycle * cyclesMap[cycles]!!
} ?: 0
}
}
fun draw(): String = buildString {
(1 until 241).forEach { cycle ->
val x = cyclesMap[cyclesMap.keys.firstOrNull { it.contains(cycle) }] ?: -1
val toDraw = if (IntRange(x - 1, x + 1).contains((cycle - 1).mod(40))) {
"#"
} else {
"."
}
append(toDraw)
if (cycle.mod(40) == 0) {
append("\n")
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val cpu = CPU()
input.forEach { row ->
val cmd = row.split(" ")
when (cmd[0]) {
"noop" -> cpu.noop()
"addx" -> cpu.add(cmd[1].toInt())
}
}
return cpu.signalStrength()
}
fun part2(input: List<String>): String {
val cpu = CPU()
input.forEach { row ->
val cmd = row.split(" ")
when (cmd[0]) {
"noop" -> cpu.noop()
"addx" -> cpu.add(cmd[1].toInt())
}
}
return cpu.draw()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140) { "part1 check failed" }
val input = readInput("Day10")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 2,064 | aoc2022 | Apache License 2.0 |
src/day13.kts | miedzinski | 434,902,353 | false | {"Kotlin": 22560, "Shell": 113} | data class Point(val x: Int, val y: Int)
enum class Axis { X, Y }
data class Fold(val axis: Axis, val position: Int)
val dots = generateSequence(::readLine)
.takeWhile(String::isNotEmpty)
.map { it.split(',').map(String::toInt).let { Point(it[0], it[1]) } }
.toSet()
val foldRegex = "fold along ([xy])=(\\d+)".toRegex()
val folds = generateSequence(::readLine)
.map { line ->
val (axis, position) = foldRegex.matchEntire(line)!!.destructured
Fold(Axis.valueOf(axis.uppercase()), position.toInt())
}.toList()
fun Point.select(axis: Axis): Int = when (axis) {
Axis.X -> x
Axis.Y -> y
}
fun Point.transform(fold: Fold): Point {
val oldPosition = select(fold.axis)
val newPosition = 2 * fold.position - oldPosition
return when (fold.axis) {
Axis.X -> copy(x = newPosition)
Axis.Y -> copy(y = newPosition)
}
}
fun Set<Point>.apply(fold: Fold): Set<Point> {
val (unchanged, toMirror) = partition {
it.select(fold.axis) < fold.position
}
val mirrored = toMirror.asSequence().map { it.transform(fold) }.toList()
return unchanged union mirrored
}
fun Set<Point>.asGrid(): String {
val maxX = maxOf { it.x }
val maxY = maxOf { it.y }
val builder = StringBuilder()
for (y in 0..maxY) {
for (x in 0..maxX) {
val mark = when (Point(x, y)) {
in this -> '#'
else -> '.'
}
builder.append(mark)
}
builder.append('\n')
}
return builder.toString()
}
val part1 = dots.apply(folds.first()).size
println("part1: $part1")
println("part2:")
folds.fold(dots) { acc, fold ->
acc.apply(fold)
}.asGrid()
| 0 | Kotlin | 0 | 0 | 6f32adaba058460f1a9bb6a866ff424912aece2e | 1,707 | aoc2021 | The Unlicense |
advent-of-code-2021/src/main/kotlin/Day11.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 11: Dumbo Octopus
//https://adventofcode.com/2021/day/11
import java.io.File
import kotlin.math.sqrt
fun main() {
val octopuses = mutableListOf<Octopus>()
File("src/main/resources/Day11.txt").readLines().forEachIndexed { x, line ->
line.toList().forEachIndexed { y, energy ->
octopuses.add(Octopus(x to y, energy.digitToInt()))
}
}
countFlashes(octopuses.map { it.copy() }, 100)
findFlashSync(octopuses.map { it.copy() })
}
fun countFlashes(octopuses: List<Octopus>, steps: Int) {
(1..steps).forEach { step ->
simulateStep(octopuses, step)
}
val flashes = octopuses.sumOf { it.flashes() }
println(flashes)
}
fun simulateStep(octopuses: List<Octopus>, step: Int) {
octopuses.forEach { octopus ->
energizeOctopus(octopuses, octopus, step)
}
}
fun energizeOctopus(octopuses: List<Octopus>, octopus: Octopus, step: Int) {
val edge = sqrt(octopuses.size.toDouble()).toInt()
val energy = octopus.energize(step)
if (energy > 9) {
octopus.flash()
octopus.adjacentIndexes().filter {
it.first in 0 until edge && it.second in 0 until edge
}.forEach { adjacent ->
val adjacentOctopus = octopuses.find { it.index == adjacent.first to adjacent.second }
adjacentOctopus?.let { energizeOctopus(octopuses, adjacentOctopus, step) }
}
}
}
fun findFlashSync(octopuses: List<Octopus>) {
var step = 0
while (octopuses.all { it.isFlashing() }.not()) {
step++
simulateStep(octopuses, step)
}
println(step)
}
data class Octopus(val index: Pair<Int, Int>, val initialEnergy: Int) {
private var flash = 0
private var energy = initialEnergy
private var step = 0
fun flashes() = flash
fun energize(step: Int): Int {
if (energy != 0) energy++
if (energy == 0 && this.step != step) {
energy++
}
this.step = step
return energy
}
fun adjacentIndexes(): List<Pair<Int, Int>> {
val x = index.first
val y = index.second
return listOf(
x - 1 to y + 1,
x to y + 1,
x + 1 to y + 1,
x - 1 to y,
x + 1 to y,
x - 1 to y - 1,
x to y - 1,
x + 1 to y - 1
)
}
fun flash() {
flash++
energy = 0
}
fun isFlashing() = energy == 0
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,449 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day11.kt | corentinnormand | 725,992,109 | false | {"Kotlin": 40576} | import kotlin.math.abs
fun main() {
Day11().main()
}
class Day11 : Aoc("day11.txt") {
val test = """
...#......
.......#..
#.........
..........
......#...
.#........
.........#
..........
.......#..
#...#.....
""".trimIndent()
fun getColumn(matrix: List<String>, col: Int): String = matrix.map { v -> v[col] }.joinToString("")
data class Coords(val x: Int, val y: Int)
fun distance(
from: Coords,
to: Coords,
emptyCols: Set<Int>,
emptyRows: Set<Int>,
expansion: Long = 1L
): Long =
abs(from.x - to.x) + abs(from.y - to.y) +
(emptyCols.filter {
(if (from.x < to.x) from.x..to.x else to.x..from.x).contains(it)
}.size * expansion) +
(emptyRows.filter {
(if (from.y < to.y) from.y..to.y else to.y..from.y).contains(it)
}.size * expansion)
override fun one() {
val input = input().lines()
val emptyRows =
input.mapIndexed { i, k -> Pair(i, k) }.filter { !it.second.contains("#") }.map { it.first }.toSet()
val emptyCols =
input[0].indices.map { (it to getColumn(input, it)) }.filter { !it.second.contains("#") }.map { it.first }
.toSet()
val galaxies =
input.mapIndexed { y, v -> v.mapIndexed { x, c -> (Coords(x, y) to c) } }.flatten()
.filter { it.second == '#' }
val sumOfDistances = galaxies.mapIndexed { i, first ->
galaxies.filterIndexed { j, _ -> j > i }.map { (first.first to it.first) }
}
.flatten()
.sumOf { distance(it.first, it.second, emptyCols, emptyRows) }
println(sumOfDistances)
}
override fun two() {
val input = test.lines()
val emptyRows =
input.mapIndexed { i, k -> Pair(i, k) }.filter { !it.second.contains("#") }.map { it.first }.toSet()
val emptyCols =
input[0].indices.map { (it to getColumn(input, it)) }.filter { !it.second.contains("#") }.map { it.first }
.toSet()
val galaxies =
input.mapIndexed { y, v -> v.mapIndexed { x, c -> (Coords(x, y) to c) } }.flatten()
.filter { it.second == '#' }
val sumOfDistances = galaxies.mapIndexed { i, first ->
galaxies.filterIndexed { j, _ -> j > i }.map { (first.first to it.first) }
}
.flatten()
.sumOf { distance(it.first, it.second, emptyCols, emptyRows, 10) }
println(sumOfDistances)
}
}
| 0 | Kotlin | 0 | 0 | 2b177a98ab112850b0f985c5926d15493a9a1373 | 2,679 | aoc_2023 | Apache License 2.0 |
src/Day09.kt | sebokopter | 570,715,585 | false | {"Kotlin": 38263} | import kotlin.math.abs
data class Move(val dx: Int, val dy: Int)
enum class Direction(val move: Move) {
R(Move(1, 0)),
L(Move(-1, 0)),
U(Move(0, 1)),
D(Move(0, -1));
}
fun main() {
fun lostTouch(head: Point, tail: Point): Boolean =
!(abs(head.x - tail.x) <= 1 && abs(head.y - tail.y) <= 1)
fun pullTail(head: Point, tail: Point): Point {
val dX = (head.x - tail.x).coerceIn(-1, 1)
val dY = (head.y - tail.y).coerceIn(-1, 1)
return tail.copy(tail.x + dX, tail.y + dY)
}
fun List<String>.readDirections(): List<Pair<Direction, Int>> = map { (directionString, stepsString) ->
val direction = Direction.valueOf(directionString)
val steps = stepsString.toInt()
direction to steps
}
fun part1(input: List<String>): Int {
var head = Point(0, 0)
var tail = head
val tailVisited = mutableSetOf(tail)
input.readDirections().forEach { (direction, steps) ->
repeat(steps) {
head = Point(head.x + direction.move.dx, head.y + direction.move.dy)
if (lostTouch(head, tail)) {
tail = pullTail(head, tail)
tailVisited.add(tail)
}
}
}
return tailVisited.size
}
fun part2(input: List<String>): Int {
val knots = MutableList(10) { Point(0, 0) } // head = 0, tail = 9
val tailVisited = mutableSetOf(Point(0, 0))
input.readDirections().forEach { (direction,steps) ->
repeat(steps) {
knots[0] = Point(knots[0].x + direction.move.dx, knots[0].y + direction.move.dy)
for (i in 0..8) {
if (lostTouch(knots[i], knots[i+1])) {
knots[i+1] = pullTail(knots[i], knots[i+1])
if (i+1 == 9) tailVisited.add(knots[9])
}
}
}
}
return tailVisited.size
}
val testInput = readInput("Day09_test")
println("part1(testInput): " + part1(testInput))
println("part2(testInput): " + part2(testInput))
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09_test2")
println("part2(testInput2): " + part2(testInput2))
check(part2(testInput2) == 36)
val input = readInput("Day09")
println("part1(input): " + part1(input))
println("part2(input): " + part2(input))
}
| 0 | Kotlin | 0 | 0 | bb2b689f48063d7a1b6892fc1807587f7050b9db | 2,474 | advent-of-code-2022 | Apache License 2.0 |
src/Day01.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 142
private const val EXPECTED_2 = 281
private class Day01(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
return readAsLines().sumOf { line ->
val first = line.first { it.isDigit() }
val last = line.last { it.isDigit() }
(first - '0') * 10 + (last - '0')
}
}
fun part2(): Any {
val digits = listOf(
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
)
return readAsLines().sumOf { line ->
fun getDigitAt(index: Int): Int? {
return if (line[index].isDigit()) {
line[index] - '0'
} else {
digits.firstNotNullOfOrNull { digit ->
if (line.substring(index).startsWith(digit)) {
1 + digits.indexOf(digit)
} else {
null
}
}
}
}
val first = line.indices.firstNotNullOf(::getDigitAt)
val last = line.indices.reversed().firstNotNullOf(::getDigitAt)
first * 10 + last
}
}
}
fun main() {
val testInstance = Day01(true)
val instance = Day01(false)
// Commented out because testdata changed from part 1 to part 2
// testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
// println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 1,682 | advent-of-code-2022 | Apache License 2.0 |
src/AoC7.kt | Pi143 | 317,631,443 | false | null | import java.io.File
fun main() {
println("Starting Day 7 A Test 1")
calculateDay7PartA("Input/2020_Day7_A_Test1")
println("Starting Day 7 A Real")
calculateDay7PartA("Input/2020_Day7_A")
println("Starting Day 7 B Test 1")
calculateDay7PartB("Input/2020_Day7_A_Test1")
println("Starting Day 7 B Real")
calculateDay7PartB("Input/2020_Day7_A")
}
fun calculateDay7PartA(file: String): Int {
val Day7Data = readDay7Data(file)
var answerCount = 0
for (bag in Day7Data) {
if(checkContains(bag, Bag("shiny gold", null), Day7Data, 20)){
answerCount++
}
}
println(answerCount)
return answerCount
}
fun checkContains(outerBag: MutableMap.MutableEntry<String, List<BagContent>?>, innerBag: Bag, bagDefinitions: MutableMap<String, List<BagContent>?>, depth: Int): Boolean {
//Sets with objects don't exactly work, but do the deed here
val containmentSet: MutableSet<BagContent> = HashSet()
if (outerBag.value == null) {
return false
}
for (bagContent in outerBag.value!!) {
containmentSet.add(bagContent)
}
for (i in 1..depth) {
val tempContainmentSet: MutableSet<BagContent> = HashSet()
tempContainmentSet.addAll(containmentSet)
for (bagContent in containmentSet) {
val bagDef = bagDefinitions[bagContent.name]
if (bagDef?.size!! > 0) {
tempContainmentSet.addAll(bagDef)
}
}
containmentSet.addAll(tempContainmentSet)
}
for (bag in containmentSet) {
if (bag.name == innerBag.name) {
return true
}
}
return false
}
fun calculateDay7PartB(file: String): Int? {
val Day7Data = readDay7Data(file)
val cost = calculateBagCostMap(Day7Data, 10)["shiny gold"]
println("shiny gold costs $cost")
return cost
}
fun calculateBagCostMap(bagDefinitions: MutableMap<String, List<BagContent>?>, depth: Int): MutableMap<String, Int?> {
val contentCostMap: MutableMap<String,Int?> = HashMap()
for(entry in bagDefinitions){
contentCostMap[entry.key] = null
}
for (i in 1..depth) {
for (costDef in contentCostMap) {
val bagDef = bagDefinitions[costDef.key]
// val bagDef = bagDefinitions.find { it.name == costDef.key }
if (bagDef?.size == 0) {
contentCostMap[costDef.key] = 0
} else {
var innerCost = 0
//all bags inside have cost identified
if (bagDef != null) {
for (innerBagDefs in bagDef) {
val currentBagCostData = contentCostMap[innerBagDefs.name]
if (currentBagCostData != null) {
innerCost += innerBagDefs.amount * (currentBagCostData + 1)
}
}
}
// cost added up + number of bags
contentCostMap[costDef.key] = innerCost
}
}
}
return contentCostMap
}
fun readDay7Data(input: String): MutableMap<String, List<BagContent>?> {
val bagMap: MutableMap<String,List<BagContent>?> = HashMap()
File(localdir + input).forEachLine { bagMap[parseBagDefinition(it).name] =parseBagDefinition(it).content }
return bagMap
}
fun parseBagDefinition(line: String): Bag {
val name = line.split(" bags contain ")[0]
val contentDefinition = line.split(" bags contain ")[1]
val contentList: MutableList<BagContent> = ArrayList()
if (contentDefinition == "no other bags.") {
return Bag(name, contentList)
}
val defSplit = contentDefinition.split(" bag(s)?(, |\\.)?".toRegex())
for (def in defSplit) {
if (def.isNotBlank()) {
val nameContentBag = def.split("\\d ".toRegex())[1]
val amount = "\\d".toRegex().find(def)?.value?.toInt()
contentList.add(BagContent(nameContentBag, amount = amount!!))
}
}
return Bag(name, contentList)
}
class Bag(name: String, content: List<BagContent>?) {
val name = name
val content = content
}
class BagContent(name: String, amount: Int) {
val name = name
val amount = amount
}
| 0 | Kotlin | 0 | 1 | fa21b7f0bd284319e60f964a48a60e1611ccd2c3 | 4,261 | AdventOfCode2020 | MIT License |
src/Day08.kt | PauliusRap | 573,434,850 | false | {"Kotlin": 20299} | fun main() {
fun createGrid(input: List<String>): Array<Array<Int>> {
val matrix = Array<Array<Int>>(input.size) { emptyArray() }
input.forEachIndexed { index, line ->
line.forEach {
matrix[index] = matrix[index] + it.digitToInt()
}
}
return matrix
}
fun countVisible(trees: Array<Array<Int>>): Int {
val time = System.currentTimeMillis()
var visible = 0
trees.forEachIndexed { lineIndex, line ->
line.forEachIndexed lineIter@{ rowIndex, tree ->
if (lineIndex == 0 || lineIndex == trees.lastIndex || rowIndex == 0 || rowIndex == line.lastIndex) {
visible++
} else {
(rowIndex - 1 downTo 0).firstOrNull {
trees[lineIndex][it] >= tree
} ?: run {
visible++
return@lineIter
}
(rowIndex + 1..line.lastIndex).firstOrNull {
trees[lineIndex][it] >= tree
} ?: run {
visible++
return@lineIter
}
(lineIndex - 1 downTo 0).firstOrNull {
trees[it][rowIndex] >= tree
} ?: run {
visible++
return@lineIter
}
(lineIndex + 1..trees.lastIndex).firstOrNull {
trees[it][rowIndex] >= tree
} ?: run {
visible++
return@lineIter
}
}
}
}
return visible.also { println("Part 1 time: ${System.currentTimeMillis() - time} ms") }
}
fun countScore(trees: Array<Array<Int>>): Int {
val time = System.currentTimeMillis()
var topScore = 0
trees.forEachIndexed { lineIndex, line ->
line.forEachIndexed { rowIndex, tree ->
if (lineIndex != 0 && lineIndex != trees.lastIndex && rowIndex != 0 && rowIndex != line.lastIndex) {
val left = (rowIndex - 1 downTo 0).takeWhileLastIncluded {
trees[lineIndex][it] < tree
}.size
val right = (rowIndex + 1..line.lastIndex).takeWhileLastIncluded {
trees[lineIndex][it] < tree
}.size
val top = (lineIndex - 1 downTo 0).takeWhileLastIncluded {
trees[it][rowIndex] < tree
}.size
val bottom = (lineIndex + 1..trees.lastIndex).takeWhileLastIncluded {
trees[it][rowIndex] < tree
}.size
val score = left * right * top * bottom
if (topScore < score) topScore = score
}
}
}
return topScore.also { println("Part 2 time: ${System.currentTimeMillis() - time} ms") }
}
fun part1(input: List<String>) = countVisible(createGrid(input))
fun part2(input: List<String>) = countScore(createGrid(input))
// test if implementation meets criteria from the description:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
inline fun <T> Iterable<T>.takeWhileLastIncluded(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
if (!predicate(item)) {
list.add(item)
break
}
list.add(item)
}
return list
}
| 0 | Kotlin | 0 | 0 | df510c3afb104c03add6cf2597c433b34b3f7dc7 | 3,792 | advent-of-coding-2022 | Apache License 2.0 |
src/day21/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day21
import java.io.File
fun Int.mod(m: Int) = ((this - 1) % m) + 1
class Die(val sides: Int) {
var value = 1
var rolled = 0
fun roll() : Int {
return value.also {
value = (value + 1).mod(sides)
rolled++
}
}
}
fun partOne(initialPositions: List<Int>) {
val positions = initialPositions.toTypedArray()
val scores = arrayOf(0, 0)
val die = Die(100)
var player = 0
while (scores.maxOrNull()!! < 1000) {
val score = (0..2).map { die.roll() }.sum()
positions[player] = (positions[player] + score).mod(10)
scores[player] += positions[player]
player = (player + 1) % 2
}
println(scores.minOrNull()!! * die.rolled)
}
data class PlayerState(val number: Int, val position: Int, val score: Int)
fun partTwo(initialPositions: List<Int>) {
val states = mutableMapOf(
listOf(PlayerState(0, initialPositions[0], 0), PlayerState(1, initialPositions[1], 0)) to 1L
)
val wins = arrayOf(0L, 0L)
while (states.isNotEmpty()) {
val iterator = states.iterator()
val (players, count) = iterator.next()
iterator.remove()
// Next player always comes first in list
val (player, position, score) = players[0]
(1..3).map { die1 ->
(1..3).map { die2 ->
(1..3).map { die3 ->
val newPosition = (position + die1 + die2 + die3).mod(10)
val newScore = score + newPosition
if (newScore >= 21) {
wins[player] += count
} else {
val newPlayerState = PlayerState(player, newPosition, newScore)
val newGameState = listOf(players[1], newPlayerState)
states[newGameState] = count + (states[newGameState] ?: 0)
}
}
}
}
}
println(wins.maxOrNull())
}
fun main() {
val initialPositions = File("src/day21/input.txt").readLines().map { it.last().digitToInt() }
partOne(initialPositions)
partTwo(initialPositions)
}
| 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 2,155 | advent-of-code-2021 | MIT License |
src/main/Day07.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day07
import utils.readInput
typealias Path = List<String>
data class File(val name: String, val size: Long)
data class Directory(
val name: String,
private val files: MutableList<File> = mutableListOf(),
private val subdirectories: MutableList<Directory> = mutableListOf(),
) {
fun addDirectory(directory: Directory) {
subdirectories.add(directory)
}
fun addFile(file: File) {
files.add(file)
}
val totalSize: Long
get() = files.sumOf(File::size) + subdirectories.sumOf(Directory::totalSize)
val totalSizes: List<Long>
get() = subdirectories.flatMap(Directory::totalSizes) + totalSize
}
fun part1(filename: String): Long =
readInput(filename).readDirectories().totalSizes.filter { it <= 100000 }.sum()
fun part2(filename: String): Long {
val directories = readInput(filename).readDirectories()
val unused = 70000000 - directories.totalSize
val minimalFreeUp = 30000000 - unused
return directories.totalSizes.filter { it >= minimalFreeUp }.min()
}
private val root = listOf("/")
class DirectoryWalker(
private val directories: MutableMap<Path, Directory> = mutableMapOf(root to Directory("/")),
private var path: Path = emptyList()
) {
fun execute(command: String) =
when {
command == "$ cd .." -> moveOut()
command.startsWith("$ cd ") -> moveIn(command.removePrefix("$ cd "))
command == "$ ls" -> {}
command.startsWith("dir ") -> addDirectory(command.removePrefix("dir "))
else -> {
val (size, name) = command.split(' ')
addFile(name, size.toLong())
}
}
private fun addFile(name: String, size: Long) {
currentDirectory().addFile(File(name, size))
}
private fun addDirectory(name: String) {
val directory = Directory(name)
directories[path + name] = directory
currentDirectory().addDirectory(directory)
}
private fun currentDirectory() = checkNotNull(directories[path]) { "Missing directory ${path}" }
private fun moveIn(subDirectory: String) {
path = path + subDirectory
}
private fun moveOut() {
path = path.subList(0, path.size - 1)
}
fun root(): Directory = checkNotNull(directories[root]) { "No root directory found" }
}
fun List<String>.readDirectories(): Directory =
DirectoryWalker().apply { forEach(::execute) }.root()
const val filename = "Day07"
fun main() {
println(part1(filename))
println(part2(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 2,570 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2015/day06_fire_hazard/FireHazard.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package aoc2015.day06_fire_hazard
import geom2d.Point
import java.util.*
fun main() {
util.solve(543903, ::partOne)
util.solve(14687245, ::partTwo)
}
private fun String.toPoint(): Point {
val dims = split(",")
.map { it.toLong() }
return Point(dims[0], dims[1])
}
private fun gridRanges(a: Point, b: Point): Collection<IntRange> {
return (a.y..b.y).map {
val offset = 1_000 * it
(a.x + offset).toInt()..(b.x + offset).toInt()
}
}
private data class Op(val name: String, val ranges: Collection<IntRange>) {
fun execute(work: (IntRange) -> Unit) {
ranges.forEach(work)
}
}
private fun String.toOp(): Op {
var words = split(" ")
if (words.first() == "turn") {
words = words.subList(1, words.size)
}
val ranges = gridRanges(
words[1].toPoint(),
words[3].toPoint(),
)
return Op(words.first(), ranges)
}
fun partOne(input: String): Int {
val lights = BitSet(1_000_000)
input.lines()
.map { it.toOp() }
.forEach { op ->
op.execute(
when (op.name) {
"on" -> { it -> lights.set(it.first, it.last + 1) }
"off" -> { it -> lights.clear(it.first, it.last + 1) }
"toggle" -> { it -> lights.flip(it.first, it.last + 1) }
else -> throw IllegalArgumentException("unrecognized instruction '$op'")
}
)
}
return lights.cardinality()
}
fun partTwo(input: String): Int {
val lights = ShortArray(1_000_000)
input.lines()
.map { it.toOp() }
.forEach { op ->
op.execute(
when (op.name) {
"on" -> { it ->
it.forEach { l ->
// this is just stupid
lights[l] = (lights[l] + 1).toShort()
}
}
"off" -> { it ->
it.forEach { l ->
if (lights[l] > 0)
lights[l] = (lights[l] - 1).toShort()
}
}
"toggle" -> { it ->
it.forEach { l ->
lights[l] = (lights[l] + 2).toShort()
}
}
else -> throw IllegalArgumentException("unrecognized instruction '$op'")
}
)
}
return lights.sum()
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 2,553 | aoc-2021 | MIT License |
src/Day04.kt | HylkeB | 573,815,567 | false | {"Kotlin": 83982} | fun main() {
fun getElfRangePairs(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map { pair ->
val parts = pair.split(",")
val elf1 = parts[0].split("-")
val elf2 = parts[1].split("-")
val rangeElf1 = elf1[0].toInt() .. elf1[1].toInt()
val rangeElf2 = elf2[0].toInt() .. elf2[1].toInt()
rangeElf1 to rangeElf2
}
}
fun part1(input: List<String>): Int {
return getElfRangePairs(input)
.count { (rangeElf1, rangeElf2) ->
rangeElf1.all { it in rangeElf2 } || rangeElf2.all { it in rangeElf1 }
}
}
fun part2(input: List<String>): Int {
return getElfRangePairs(input)
.count { (rangeElf1, rangeElf2) ->
rangeElf1.any { it in rangeElf2 } || rangeElf2.any { it in rangeElf1 }
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8649209f4b1264f51b07212ef08fa8ca5c7d465b | 1,201 | advent-of-code-2022-kotlin | Apache License 2.0 |
advent-of-code-2022/src/Day23.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | fun main() {
val testInput = readInput("Day23_test")
val input = readInput("Day23")
"Part 1" {
part1(testInput) shouldBe 110
measureAnswer { part1(input) }
}
"Part 2" {
part2(testInput) shouldBe 20
measureAnswer { part2(input) }
}
}
private fun part1(input: List<String>): Int {
val map = GroundMap(input)
repeat(10) { map.tick() }
return map.countEmptyCells()
}
private fun part2(input: List<String>): Int {
val map = GroundMap(input)
var steps = 1
while (map.tick()) steps++
return steps
}
private class GroundMap(input: List<String>) {
val elves = mutableSetOf<Pair<Int, Int>>()
private var firstDirection = 0 // NORTH
private val batch = mutableMapOf<Pair<Int, Int>, List<Pair<Int, Int>>>()
init {
for (r in input.indices) {
for (c in input[0].indices) {
if (input[r][c] == '#') elves.add(r to c)
}
}
}
fun tick(): Boolean {
// 1. Propose directions
for (elf in elves) {
// Skip elves without neighbors
if (neighbors(elf).none { it in elves }) continue
val dest = directions(elf)
.find { cells -> cells.none { it in elves } }
?.first()
if (dest != null) batch[dest] = batch.getOrDefault(dest, emptyList()) + elf
}
// 2. Move
var moved = false
for ((dest, candidates) in batch) {
if (candidates.size == 1) {
elves.remove(candidates.single())
elves.add(dest)
moved = true
}
}
// 3. Change direction, clear batch
firstDirection = (firstDirection + 1) % 4
batch.clear()
return moved
}
private fun neighbors(position: Pair<Int, Int>): Sequence<Pair<Int, Int>> {
val (r, c) = position
return sequenceOf(-1 to 0, -1 to 1, 0 to 1, 1 to 1, 1 to 0, 1 to -1, 0 to -1, -1 to -1)
.map { (dr, dc) -> (r + dr) to (c + dc) }
}
private fun directions(position: Pair<Int, Int>): Sequence<List<Pair<Int, Int>>> {
val directions = listOf(
listOf(-1 to 0, -1 to -1, -1 to +1), // NORTH
listOf(+1 to 0, +1 to -1, +1 to +1), // SOUTH
listOf(0 to -1, -1 to -1, +1 to -1), // WEST
listOf(0 to +1, -1 to +1, +1 to +1), // EAST
)
return sequence {
val (r, c) = position
for (i in 0..3) {
yield(directions[(firstDirection + i) % 4].map { (dr, dc) -> (r + dr) to (c + dc) })
}
}
}
fun countEmptyCells(): Int {
val (minR, maxR, minC, maxC) = getRectangle()
return (maxR - minR + 1) * (maxC - minC + 1) - elves.size
}
private fun debugPrint() {
println("Direction: $firstDirection")
val (minR, maxR, minC, maxC) = getRectangle()
for (r in minR..maxR) {
for (c in minC..maxC) {
print(if (r to c in elves) "# " else ". ")
}
println()
}
}
private fun getRectangle(): List<Int> {
val minR = elves.minOf { it.first }
val maxR = elves.maxOf { it.first }
val minC = elves.minOf { it.second }
val maxC = elves.maxOf { it.second }
return listOf(minR, maxR, minC, maxC)
}
}
private fun readInput(name: String) = readLines(name)
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 3,461 | advent-of-code | Apache License 2.0 |
src/main/kotlin/twentytwentytwo/Day18.kt | JanGroot | 317,476,637 | false | {"Kotlin": 80906} | package twentytwentytwo
import twentytwentytwo.Structures.Point3d
fun main() {
val input = {}.javaClass.getResource("input-18.txt")!!.readText().linesFiltered { it.isNotEmpty() };
val test = {}.javaClass.getResource("input-18-1.txt")!!.readText().linesFiltered { it.isNotEmpty() };
val day = Day18(input)
val testDay = Day18(test)
println(testDay.part1())
println(testDay.part2())
println(day.part1())
println(day.part2())
}
class Day18(private val input: List<String>) {
private val cubes = input.map { it.split(",") }.map { (x, y, z) -> Point3d(x.toInt(), y.toInt(), z.toInt()) }.toSet()
private val lava = Lava(cubes)
fun part1(): Int {
// count which of the six neigbours are not occupied.
return cubes.sumOf { c -> c.neighbors().count { it !in cubes } }
}
fun part2(): Int {
val unexposed = lava.getUnExposed()
// count which of the six neigbours are not occupied and not in unexposed
return cubes.sumOf { c -> c.neighbors().count { neighbour -> neighbour !in cubes && neighbour !in unexposed } }
}
class Lava(private val cubes: Set<Point3d>) {
private val xBound = cubes.minOf { it.x } until cubes.maxOf { it.x }
private val yBound = cubes.minOf { it.y } until cubes.maxOf { it.y }
private val zBound = cubes.minOf { it.z } until cubes.maxOf { it.z }
private val lava = xBound.map { x -> yBound.map { y -> zBound.map { z -> Point3d(x, y, z) } } }.flatten().flatten().toSet()
private val potentialExposed = lava.toMutableSet()
// copied basic idea from the graph class
fun getUnExposed(): MutableSet<Point3d> {
// find all connected to outside and remove.
lava.forEach { node ->
recurseRemoveExposed(node, setOf(node))
}
return potentialExposed
}
private tailrec fun recurseRemoveExposed(node: Point3d, connectedNodes: Set<Point3d>) {
if (node.isExposed()) {
potentialExposed.removeAll(connectedNodes + node)
}
else node.neighbors().filter { !it.isConnected(connectedNodes) && it !in cubes }.forEach { connection ->
return recurseRemoveExposed(connection, connectedNodes + node)
}
}
private fun Point3d.isExposed() = x !in xBound || y !in yBound || z !in zBound
private fun Point3d.isConnected(connectedNodes: Set<Point3d>) = this in connectedNodes
}
}
| 0 | Kotlin | 0 | 0 | 04a9531285e22cc81e6478dc89708bcf6407910b | 2,510 | aoc202xkotlin | The Unlicense |
kotlin/src/katas/kotlin/leetcode/max_points_on_a_line/FindPoints.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.max_points_on_a_line
import datsok.shouldEqual
import org.junit.jupiter.api.Test
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.math.absoluteValue
//
// https://leetcode.com/problems/max-points-on-a-line ❌
//
// Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
//
// Example 1
// Input: [[1,1],[2,2],[3,3]]
// Output: 3
// Explanation:
// ^
// |
// | o
// | o
// | o
// +------------->
// 0 1 2 3 4
//
// Example 2
// Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
// Output: 4
// Explanation:
// ^
// |
// | o
// | o o
// | o
// | o o
// +------------------->
// 0 1 2 3 4 5 6
fun maxPoints(points: Array<IntArray>): Int {
return lineWithMaxPoints(points.map { Point(it[0], it[1]) }).size
}
private fun lineWithMaxPoints(points: List<Point>): List<Point> {
if (points.size <= 2) return points
return sequence {
points.forEachIndexed { i1, point1 ->
points.drop(i1 + 1).forEachIndexed { i2, point2 ->
val line = Line()
line.add(point1)
line.add(point2)
points.drop(i1 + 1 + i2 + 1).forEach { point3 ->
line.add(point3)
}
yield(line)
}
}
}.maxByOrNull { it.size }!!.points
}
data class Point(val x: Int, val y: Int) {
override fun toString() = "[$x,$y]"
}
data class Line(val points: ArrayList<Point> = ArrayList()) {
val uniquePoints: HashSet<Point> = HashSet()
val size: Int get() = points.size
fun add(point: Point) {
if (uniquePoints.size <= 1 || isOnTheLine(point)) {
uniquePoints.add(point)
points.add(point)
}
}
private fun isOnTheLine(p3: Point): Boolean {
val (p1, p2) = uniquePoints.take(2)
if (p1 == p3 || p2 == p3) return true
if (p1.y == p2.y && p2.y == p3.y) return true
if (p1.x == p2.x) return p1.x == p3.x
val a = (p1.y - p2.y).toDouble() / (p1.x - p2.x)
val b = p1.y - a * p1.x
val b3 = p3.y - a * p3.x
return (b - b3).absoluteValue < 0.000_000_001
}
}
val Int.absoluteValue: Int get() = Math.abs(this)
val Double.absoluteValue: Double get() = Math.abs(this)
class Tests {
@Test fun `some examples`() {
lineWithMaxPoints(listOf(Point(1, 1), Point(2, 2), Point(3, 3))) shouldEqual
listOf(Point(1, 1), Point(2, 2), Point(3, 3))
lineWithMaxPoints(listOf(Point(1, 1), Point(3, 2), Point(5, 3), Point(4, 1), Point(2, 3), Point(1, 4))) shouldEqual
listOf(Point(3, 2), Point(4, 1), Point(2, 3), Point(1, 4))
lineWithMaxPoints(listOf(Point(0, 0), Point(1, 1), Point(1, -1))) shouldEqual
listOf(Point(0, 0), Point(1, 1))
lineWithMaxPoints(listOf(Point(1, 1), Point(1, 1), Point(2, 2), Point(2, 2))) shouldEqual
listOf(Point(1, 1), Point(1, 1), Point(2, 2), Point(2, 2))
}
@Test fun `failing example`() {
val points = (0..120).map { Point(-10 + it, 87 - it) }.shuffled()
lineWithMaxPoints(points).size shouldEqual 121
lineWithMaxPoints("""[[40,-23],[9,138],[429,115],[50,-17],[-3,80],[-10,33],[5,-21],[-3,80],[-6,-65],
[-18,26],[-6,-65],[5,72],[0,77],[-9,86],[10,-2],[-8,85],[21,130],[18,-6],[-18,26],[-1,-15],[10,-2],[8,69],
[-4,63],[0,3],[-4,40],[-7,84],[-8,7],[30,154],[16,-5],[6,90],[18,-6],[5,77],[-4,77],[7,-13],[-1,-45],[16,-5],
[-9,86],[-16,11],[-7,84],[1,76],[3,77],[10,67],[1,-37],[-10,-81],[4,-11],[-20,13],[-10,77],[6,-17],[-27,2],[-10,-81],
[10,-1],[-9,1],[-8,43],[2,2],[2,-21],[3,82],[8,-1],[10,-1],[-9,1],[-12,42],[16,-5],[-5,-61],[20,-7],[9,-35],[10,6],
[12,106],[5,-21],[-5,82],[6,71],[-15,34],[-10,87],[-14,-12],[12,106],[-5,82],[-46,-45],[-4,63],[16,-5],[4,1],[-3,-53],
[0,-17],[9,98],[-18,26],[-9,86],[2,77],[-2,-49],[1,76],[-3,-38],[-8,7],[-17,-37],[5,72],[10,-37],[-4,-57],[-3,-53],[3,74],
[-3,-11],[-8,7],[1,88],[-12,42],[1,-37],[2,77],[-6,77],[5,72],[-4,-57],[-18,-33],[-12,42],[-9,86],[2,77],[-8,77],[-3,77],
[9,-42],[16,41],[-29,-37],[0,-41],[-21,18],[-27,-34],[0,77],[3,74],[-7,-69],[-21,18],[27,146],[-20,13],[21,130],[-6,-65],
[14,-4],[0,3],[9,-5],[6,-29],[-2,73],[-1,-15],[1,76],[-4,77],[6,-29]]""".trimIndent().toPoints()).size shouldEqual 25
}
@Test fun `points on a horizontal line`() {
lineWithMaxPoints(listOf(Point(1, 3), Point(2, 3), Point(10, 3))) shouldEqual
listOf(Point(1, 3), Point(2, 3), Point(10, 3))
}
@Test fun `points on a vertical line`() {
lineWithMaxPoints(listOf(Point(3, 1), Point(3, 2), Point(3, 10))) shouldEqual
listOf(Point(3, 1), Point(3, 2), Point(3, 10))
}
@Test fun `points on parallel lines`() {
lineWithMaxPoints(listOf(Point(5, 5), Point(10, 10), Point(6, 4), Point(11, 9))) shouldEqual
listOf(Point(5, 5), Point(10, 10))
}
@Test fun `duplicate points`() {
lineWithMaxPoints(listOf(Point(1, 1), Point(1, 1), Point(2, 3))) shouldEqual
listOf(Point(1, 1), Point(1, 1), Point(2, 3))
}
@Test fun `two almost the same points far from (0,0)`() {
lineWithMaxPoints(listOf(Point(0, 0), Point(94_911_150, 94_911_151), Point(94_911_151, 94_911_152))) shouldEqual
listOf(Point(0, 0), Point(94_911_150, 94_911_151))
}
private fun String.toPoints(): List<Point> {
return replace(Regex("\\s"), "").replace("[[", "").replace("]]", "").split("],[")
.map { it.split(",") }.map { Point(it[0].toInt(), it[1].toInt()) }
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 5,771 | katas | The Unlicense |
src/Day03.kt | marciprete | 574,547,125 | false | {"Kotlin": 13734} | fun main() {
fun priority(char: Char): Int {
return when (char.isUpperCase()) {
true -> char.code - 38
else -> char.code - 96
}
}
fun part1(input: List<String>): Int {
return input.map { it.trim().toCharArray() }
.map {
val pair = Pair(
it.copyOfRange(0, (it.size + 1) / 2).toHashSet(),
it.copyOfRange((it.size + 1) / 2, it.size).toHashSet()
)
pair.first.retainAll(pair.second)
priority(pair.first.first())
}
.sum()
}
fun part2(input: List<String>): Int {
return input.map { it.toCharArray().toHashSet() }
.windowed(3, 3) {
it.get(1).retainAll(it.get(2))
it.get(0).retainAll(it.get(1))
priority(it.get(0).first())
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6345abc8f2c90d9bd1f5f82072af678e3f80e486 | 1,199 | Kotlin-AoC-2022 | Apache License 2.0 |
src/main/kotlin/dev/kosmx/aoc23/springs/Sets.kt | KosmX | 726,056,762 | false | {"Kotlin": 32011} | package dev.kosmx.aoc23.springs
import java.io.File
import java.math.BigInteger
import javax.swing.Spring
fun <T> Collection<T>.subsets(k: Int): Sequence<Collection<T>> = sequence {
if (k > size) throw IllegalArgumentException("k must be smaller than the superset size")
if (k == size) yield(this@subsets)
else if (k > 0) {
subsets(k, this@subsets)
} else {
yield(emptyList()) // if request is 0 size subset(s), there is one and always one
}
}
private suspend fun <T> SequenceScope<Collection<T>>.subsets(k: Int, set: Collection<T>, subset: Collection<T> = emptyList()) {
if (k == 1) {
yieldAll(set.map { subset + it })
} else {
set.forEachIndexed { index, t ->
subsets(k - 1, set.drop(index + 1), subset + t)
}
}
}
// memoized solver
private class Variations(val rules: List<Int>, val springs: String) {
private val memory: MutableMap<Pair<Int, Int>, BigInteger> = mutableMapOf()
val variation: Int = springs.length - rules.sum() - rules.size + 1
val offset = List(rules.size) { index ->
rules.take(index).sum() + index
}.toIntArray()
init {
assert(offset.last() + rules.last() + variation == springs.length) // sanity check
}
// This should be not simply recursive, but as recursive as possible.
// That's how memoization became powerful
fun getVariations(rulePos: Int = 0, startPos: Int = 0): BigInteger {
assert(rulePos < rules.size)
return memory.getOrPut(rulePos to startPos) {
// step1: check if pos 0 is valid
val offs = offset[rulePos]
val zeroValid = (0 ..< rules[rulePos]).all {i ->
springs[offs + startPos + i] != '.'
}
&& (rulePos + 1 == rules.size || springs[offs + startPos + rules[rulePos]] != '#')
&& (rulePos != 0 || springs.substring(0 ..< startPos).all { it != '#' })
val size = if (zeroValid) {
if (rulePos == rules.size - 1) {
val remainingValid = (offs + startPos + rules[rulePos]..< springs.length).all { i ->
springs[i] != '#'
}
if (remainingValid) BigInteger.ONE else BigInteger.ZERO
} else {
getVariations(rulePos + 1, startPos)
}
} else BigInteger.ZERO
size + (if (startPos < variation && springs[offs + startPos] != '#' ) getVariations(rulePos, startPos + 1) else BigInteger.ZERO)
}
}
}
fun main() {
val games = File("springs.txt").readLines().filter { it.isNotBlank() }.map { it }
val p = Regex("#+")
val sums = games.map { game ->
var variations = 0
val (springs, rules) = game.split(" ").let {
it[0].let { s ->
List(5) {s}.joinToString("?")
} to it[1].let { s ->
val tmp = s.split(",").map { i -> i.toInt() }
(0 ..< 5).flatMap { tmp }
}
}
val v = Variations(rules, springs)
val variation = v.getVariations()
/* //
val check = run {
val totalWrong = rules.sum()
val missing = totalWrong - springs.count { it == '#' }
val options = springs.mapIndexedNotNull { index, c -> if (c == '?') index else null }
for (subset in options.subsets(missing)) {
val newSprings = springs.toCharArray()
for (index in subset) {
newSprings[index] = '#'
}
val matches = p.findAll(newSprings.joinToString("")).map { it.value.length }.toList()
if (matches == rules) {
variations++
}
}
variations
}
assert(check.toLong() == variation) // */
variation
}
println("Part1: $sums\nsum is ${sums.sum()}")
}
private fun Collection<BigInteger>.sum(): BigInteger = fold(BigInteger.ZERO) { acc, i -> acc + i}
| 0 | Kotlin | 0 | 0 | ad01ab8e9b8782d15928a7475bbbc5f69b2416c2 | 4,076 | advent-of-code23 | MIT License |
src/Day03.kt | cornz | 572,867,092 | false | {"Kotlin": 35639} | fun main() {
fun charToIntValues(char: Char): Int {
return if (char.isUpperCase()) {
char.code - 64 + 26
} else {
char.code - 96
}
}
fun findCommonItem(line: String): Char? {
val mid = line.length / 2
val parts = arrayOf(line.substring(0, mid), line.substring(mid))
for (c in parts[0].toCharArray()) {
for (c2 in parts[1].toCharArray()) {
if (c == c2) {
return c
}
}
}
return null
}
fun findCommonBadge(input: List<String>): Char? {
for (c in input[0].toCharArray()) {
if (c in input[1] && c in input[2])
return c
}
return null
}
fun part1(input: List<String>): Int {
val priorityList = arrayListOf<Int>()
for (line in input) {
val commonItem = findCommonItem(line)
val commonItemPriority = commonItem?.let { charToIntValues(it) }
priorityList.add(commonItemPriority!!)
}
return priorityList.sum()
}
fun part2(input: List<String>): Int {
val priorityList = arrayListOf<Int>()
for (list in input.chunked(3)) {
val commonItem = findCommonBadge(list)
val commonItemPriority = commonItem?.let { charToIntValues(it) }
priorityList.add(commonItemPriority!!)
}
return priorityList.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("input/Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("input/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2800416ddccabc45ba8940fbff998ec777168551 | 1,769 | aoc2022 | Apache License 2.0 |
2022/src/Day23.kt | Saydemr | 573,086,273 | false | {"Kotlin": 35583, "Python": 3913} | package src
import java.util.function.Predicate
val cardinals = listOf(
Pair(-1,1), // northwest
Pair(0,1), // north
Pair(1,1), // northeast
Pair(1,0), // east
Pair(-1,0), // west
Pair(-1,-1), // southwest
Pair(0,-1), // south
Pair(1,-1) // southeast
)
var moveOrder = mutableListOf(
Predicate<Pair<Int,Int>> { it.second == 1 }, // north
Predicate<Pair<Int,Int>> { it.second == -1 }, // south
Predicate<Pair<Int,Int>> { it.first == -1 }, // west
Predicate<Pair<Int,Int>> { it.first == 1 } // east
)
fun main() {
var elfPositions = readInput("input23")
.mapIndexed { yCoordinate, list ->
list.mapIndexed { xCoordinate, char ->
if (char == '#') Pair(xCoordinate, -yCoordinate) else Pair(100,100) }
}
.flatten()
.filter { it.first != 100 && it.second != 100 }
fun move(xPosition: Int, yPosition: Int) : Pair<Int,Int> {
val positionsToCheck = cardinals.map { Pair(it.first + xPosition, it.second + yPosition) }
if ( !positionsToCheck.any { elfPositions.contains(it) } ) {
return Pair(xPosition, yPosition)
}
else {
for (direction in moveOrder)
{
val oneDirectionCheck = cardinals.filter { direction.test(it) }.map { Pair(it.first + xPosition, it.second + yPosition) }
if ( !oneDirectionCheck.any { elfPositions.contains(it) } )
{
val towards = cardinals.first { direction.test(it) && (it.first == 0 || it.second == 0) }
return Pair(xPosition + towards.first, yPosition + towards.second)
}
}
}
return Pair(xPosition, yPosition)
}
for (round in 1 until 1000)
{
val proposedMoves = elfPositions.associateWith { oldPosition -> move(oldPosition.first, oldPosition.second) }
val bannedMoves = proposedMoves.values.groupingBy { it }.eachCount().filter { it.value > 1 }.toList().toMutableList().map { it.first }
val nextElfPositions = elfPositions.map { position ->
if (!bannedMoves.contains(proposedMoves[position]!!))
proposedMoves[position]!!
else
position
}.toMutableList()
// part 2. could be checked if all proposed moves are banned
if (nextElfPositions == elfPositions) {
println("Elf positions have stabilized after $round rounds")
break
}
else
elfPositions = nextElfPositions
val fp = moveOrder.first()
moveOrder = moveOrder.drop(1).toMutableList()
moveOrder.add(fp)
}
val minX = elfPositions.minBy { it.first }.first
val minY = elfPositions.minBy { it.second }.second
val maxX = elfPositions.maxBy { it.first }.first
val maxY = elfPositions.maxBy { it.second }.second
println(((maxX + 1 - minX ) * (maxY + 1 - minY )) - elfPositions.size)
}
| 0 | Kotlin | 0 | 1 | 25b287d90d70951093391e7dcd148ab5174a6fbc | 2,986 | AoC | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day01/day1.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day01
import biz.koziolek.adventofcode.findInput
fun main() {
val inputFile = findInput(object {})
val lines = inputFile.bufferedReader().readLines()
println("Sum of all calibration values is: ${sumCalibrationValues(parseCalibrationValues(lines))}")
println("Sum of all calibration values including spelled numbers is: ${sumCalibrationValues(parseCalibrationValuesWithLetters(lines))}")
}
fun parseCalibrationValues(lines: Iterable<String>): List<Int> =
lines
.map { line -> line.filter { c -> c.isDigit() }}
.map { it.first().digitToInt() * 10 + it.last().digitToInt() }
fun sumCalibrationValues(values: List<Int>) = values.sum()
private val spelledDigits = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
)
private val stringsToFind = spelledDigits.keys + (1..9).map { it.toString() }
fun parseCalibrationValuesWithLetters(lines: Iterable<String>): List<Int> =
lines
.asSequence()
.map { line -> line.findAnyOf(stringsToFind) to line.findLastAnyOf(stringsToFind) }
.map { toDigit(it.first?.second) to toDigit(it.second?.second) }
.filter { it.first != null && it.second != null }
.map { it.first!! * 10 + it.second!! }
.toList()
private fun toDigit(str: String?): Int? =
spelledDigits[str] ?: str?.toInt()
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 1,463 | advent-of-code | MIT License |
src/main/kotlin/de/pgebert/aoc/days/Day14.kt | pgebert | 724,032,034 | false | {"Kotlin": 65831} | package de.pgebert.aoc.days
import de.pgebert.aoc.Day
class Day14(input: String? = null) : Day(14, "Parabolic Reflector Dish", input) {
data class Point(val x: Int, val y: Int)
private var cubicStones = setOf<Point>()
private var roundStones = setOf<Point>()
init {
parseStones()
}
override fun partOne() = roundStones.shiftNorth().sumOf { stone -> inputList.size - stone.x }
override fun partTwo(): Int {
val iterations = 1000000000
var shifted = roundStones
val history = mutableListOf<Set<Point>>()
for (i in 0..<iterations) {
shifted = shifted.shiftNorth().shiftWest().shiftSouth().shiftEast()
if (shifted in history) {
val first = history.indexOf(shifted)
val cycleLength = i - first
val offset = (iterations - 1 - first) % cycleLength
shifted = history[first + offset]
break
}
history.add(shifted)
}
return shifted.sumOf { stone -> inputList.size - stone.x }
}
private fun Set<Point>.shiftNorth() =
sortedBy { it.x }.fold(setOf<Point>()) { shifted, (x, y) ->
val newX = (listOf(Point(-1, y)) + cubicStones + shifted)
.filter { it.y == y && it.x < x }
.maxOf { it.x + 1 }
shifted + Point(newX, y)
}
private fun Set<Point>.shiftSouth() =
sortedByDescending { it.x }.fold(setOf<Point>()) { shifted, (x, y) ->
val newX = (listOf(Point(inputList.size, y)) + cubicStones + shifted)
.filter { it.y == y && it.x > x }
.minOf { it.x - 1 }
shifted + Point(newX, y)
}
private fun Set<Point>.shiftEast() =
sortedByDescending { it.y }.fold(setOf<Point>()) { shifted, (x, y) ->
val newY = (listOf(Point(x, inputList.first().length)) + cubicStones + shifted)
.filter { it.x == x && it.y > y }
.minOf { it.y - 1 }
shifted + Point(x, newY)
}
private fun Set<Point>.shiftWest() =
sortedBy { it.y }.fold(setOf<Point>()) { shifted, (x, y) ->
val newY = (listOf(Point(x, -1)) + cubicStones + shifted)
.filter { it.x == x && it.y < y }
.maxOf { it.y + 1 }
shifted + Point(x, newY)
}
private fun parseStones() {
val cubic = mutableListOf<Point>()
val round = mutableListOf<Point>()
inputList.forEachIndexed { x, line ->
line.forEachIndexed { y, char ->
if (char == '#') cubic.add(Point(x, y))
else if (char == 'O') round.add(Point(x, y))
}
}
cubicStones = cubic.toSet()
roundStones = round.toSet()
}
}
| 0 | Kotlin | 1 | 0 | a30d3987f1976889b8d143f0843bbf95ff51bad2 | 2,844 | advent-of-code-2023 | MIT License |
kotlin/graphs/shortestpaths/DijkstraSegmentTree.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs.shortestpaths
import java.util.stream.Stream
// https://en.wikipedia.org/wiki/Dijkstra's_algorithm
object DijkstraSegmentTree {
// calculate shortest paths in O(E*log(V)) time and O(V) memory
fun shortestPaths(edges: Array<List<Edge>>, s: Int, prio: LongArray, pred: IntArray) {
Arrays.fill(pred, -1)
Arrays.fill(prio, Long.MAX_VALUE)
prio[s] = 0
val t = LongArray(edges.size * 2)
Arrays.fill(t, Long.MAX_VALUE)
DijkstraSegmentTree[t, s] = 0
while (true) {
val cur = minIndex(t)
if (t[cur + t.size / 2] == Long.MAX_VALUE) break
DijkstraSegmentTree[t, cur] = Long.MAX_VALUE
for (e in edges[cur]) {
val v = e.t
val nprio = prio[cur] + e.cost
if (prio[v] > nprio) {
prio[v] = nprio
pred[v] = cur
DijkstraSegmentTree[t, v] = nprio
}
}
}
}
operator fun set(t: LongArray, i: Int, value: Long) {
var i = i
i += t.size / 2
if (t[i] < value && value != Long.MAX_VALUE) return
t[i] = value
while (i > 1) {
t[i shr 1] = Math.min(t[i], t[i xor 1])
i = i shr 1
}
}
fun minIndex(t: LongArray): Int {
var res = 1
while (res < t.size / 2) res = res * 2 + if (t[res * 2] > t[1]) 1 else 0
return res - t.size / 2
}
// Usage example
fun main(args: Array<String?>?) {
val cost = arrayOf(intArrayOf(0, 3, 2), intArrayOf(0, 0, -2), intArrayOf(0, 0, 0))
val n = cost.size
val edges: Array<List<Edge>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() }
for (i in 0 until n) {
for (j in 0 until n) {
if (cost[i][j] != 0) {
edges[i].add(Edge(j, cost[i][j]))
}
}
}
val dist = LongArray(n)
val pred = IntArray(n)
shortestPaths(edges, 0, dist, pred)
System.out.println(0 == dist[0])
System.out.println(3 == dist[1])
System.out.println(1 == dist[2])
System.out.println(-1 == pred[0])
System.out.println(0 == pred[1])
System.out.println(1 == pred[2])
}
class Edge(var t: Int, var cost: Int)
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,383 | codelibrary | The Unlicense |
src/main/kotlin/days/Day11.kt | julia-kim | 569,976,303 | false | null | package days
import readInput
fun main() {
fun parseMonkeys(input: List<String>) = input.chunked(7) {
val monkey = Monkey()
it.forEach { string ->
val line = string.trim()
when {
line.startsWith("Monkey") -> return@forEach
line.startsWith("Starting items") -> {
val stringList = line.removePrefix("Starting items: ")
monkey.items =
if (line.contains(","))
stringList.split(", ")
.map { it.toLong() }.toMutableList()
else mutableListOf(stringList.toLong())
}
line.startsWith("Operation") -> {
monkey.operation = line.removePrefix("Operation: new = ")
}
line.startsWith("Test") -> {
monkey.testDivisor = line.removePrefix("Test: divisible by ").toLong()
}
line.startsWith("If true") -> {
monkey.trueMonkey = line.removePrefix("If true: throw to monkey ").toInt()
}
line.startsWith("If false") -> {
monkey.falseMonkey = line.removePrefix("If false: throw to monkey ").toInt()
}
line.isBlank() -> return@forEach
}
}
monkey
}
fun part1(input: List<String>): Long {
val monkeys = parseMonkeys(input)
var round = 1
while (round <= 20) {
monkeys.forEach { m ->
val iterator = m.items.iterator()
while (iterator.hasNext()) {
val itemLevel = iterator.next()
val worryLevel = m.performOperation(itemLevel, true)
val throwToMonkey = m.test(worryLevel)
monkeys[throwToMonkey].items.add(worryLevel)
iterator.remove()
m.inspectionCount++
}
}
round++
}
val mostActiveMonkeys = monkeys.sortedByDescending { it.inspectionCount }.map { it.inspectionCount }.take(2)
return mostActiveMonkeys[0] * mostActiveMonkeys[1] //monkey business
}
fun part2(input: List<String>): Long {
return 0
}
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
data class Monkey(
var items: MutableList<Long> = mutableListOf(),
var operation: String = "",
var testDivisor: Long = 1L,
var trueMonkey: Int = 0,
var falseMonkey: Int = 0,
var inspectionCount: Long = 0
) {
fun performOperation(old: Long, decreaseWorryLevel: Boolean): Long {
val (n1, operator, n2) = operation.split(" ")
val value1 = if (n1 == "old") old else n1.toLong()
val value2 = if (n2 == "old") old else n2.toLong()
val worryLevel: Long = when (operator) {
"*" -> value1 * value2
"+" -> value1 + value2
else -> 0L
}
val divideBy3 = (worryLevel / 3L)
return if (decreaseWorryLevel) divideBy3 else worryLevel
}
fun test(wl: Long): Int {
return if (wl % testDivisor == 0L) trueMonkey else falseMonkey
}
} | 0 | Kotlin | 0 | 0 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 3,415 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/com/leetcode/16_3SumClosest.kt | programmerr47 | 248,502,040 | false | null | package com.leetcode
import kotlin.math.abs
private class Solution16 {
fun threeSumClosest(nums: IntArray, target: Int): Int {
val sorted = nums.sorted()
var result = sorted[0] + sorted[1] + sorted[2]
for (i1 in sorted.indices) {
for (i2 in i1 + 1 until sorted.size) {
val remain = target - sorted[i1] - sorted[i2]
val i3 = findClosest(sorted, i2 + 1, sorted.lastIndex, remain)
if (i3 < sorted.size) {
val newResult = sorted[i1] + sorted[i2] + sorted[i3]
if (abs(newResult - target) < abs(result - target)) {
result = newResult
}
}
}
}
return result
}
private fun findClosest(sorted: List<Int>, start: Int, end: Int, value: Int): Int {
var a = start
var b = end
while (a < b) {
val c = (a + b) shr 1
when {
sorted[c] == value -> return c
sorted[c] < value -> a = c + 1
sorted[c] > value -> b = c
}
}
return a
}
//[2, 3, 4], 1
//c = 1 s[c] = 3 > 1 -> b = 0
//c = 0 s[c] = 2 > 1 -> b = -1
//return 0
//[1, 4], 2
//c = 0 s[c] = 1 < 2 -> a = 1
//c = 1 s[c] = 4 > 2 -> b = 0
//return 1
//[1, 4], 10
//c = 0 s[c] = 1 < 10 -> a = 1
//c = 1 s[c] = 4 < 10 -> a = 2
//return 2
//return a - 1
private fun find(sorted: IntArray, value: Int): Int {
var a = 0
var b = sorted.lastIndex
while (a <= b) {
val c = (a + b) shr 1
when {
sorted[c] == value -> return c
sorted[c] < value -> a = c + 1
sorted[c] > value -> b = c - 1
}
}
return a
}
}
fun main() {
println(Solution16().threeSumClosest(intArrayOf(-1, 0, 1, 1, 55), 3))
} | 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 1,966 | problemsolving | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2021/day12/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2021.day12
import com.kingsleyadio.adventofcode.util.readInput
fun part1(graph: Map<String, List<String>>, start: String, end: String): Int {
var count = 0
fun travel(current: String, visited: MutableSet<String>) {
if (current == end) { count++; return }
for (dest in graph.getValue(current)) {
if (dest !in visited) {
if (dest == dest.lowercase()) visited.add(dest)
travel(dest, visited)
visited.remove(dest)
}
}
}
travel(start, hashSetOf(start))
return count
}
fun part2(graph: Map<String, List<String>>, start: String, end: String): Int {
var count = 0
var secondVisit: String? = null
fun travel(current: String, visited: MutableSet<String>) {
if (current == end) { count++; return }
for (dest in graph.getValue(current)) {
if (dest !in visited || secondVisit == null) {
if (dest == dest.lowercase()) {
if (dest == start) continue
else if (dest !in visited) visited.add(dest)
else secondVisit = dest
}
travel(dest, visited)
if (secondVisit == dest) secondVisit = null
else visited.remove(dest)
}
}
}
travel(start, hashSetOf(start))
return count
}
fun main() {
val graph = buildMap<String, MutableList<String>> {
readInput(2021, 12).forEachLine { line ->
val (current, dest) = line.split("-")
getOrPut(current) { arrayListOf() }.add(dest)
getOrPut(dest) { arrayListOf() }.add(current)
}
}
println(part1(graph, "start", "end"))
println(part2(graph, "start", "end"))
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,808 | adventofcode | Apache License 2.0 |
src/main/kotlin/aoc2022/Day05.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import popTo
import readInput
import java.util.Stack
data class Instruction(val count: Int, val from: Int, val to: Int) {
companion object {
fun fromString(str: String): Instruction {
// example: move 1 from 2 to 1
val split = str.split(" ").toList().mapNotNull { it.toIntOrNull() }
return Instruction(split[0], split[1] - 1, split[2] - 1)
}
}
}
fun main() {
fun parseInitialStackConfig(input: List<String>): List<Stack<Char>> {
val stackInfo = input.withIndex().dropWhile { !it.value.startsWith(" 1") }.first()
val stacks = stackInfo.value.split(" ").map { Stack<Char>() }
var currentLine = stackInfo.index - 1
while (currentLine >= 0) {
input[currentLine].withIndex().filter { it.value.isLetter() }.forEach {
stacks[it.index / 4].add(it.value)
}
currentLine--
}
return stacks
}
fun generateOutput(stacks: List<Stack<Char>>) =
stacks.map { it.peek() }.joinToString(separator = "") { it.toString() }
fun parseInstructions(input: List<String>): List<Instruction> =
input.dropWhile { it.isNotBlank() }.filter { it.isNotBlank() }.map { Instruction.fromString(it) }
fun part1(input: List<String>): String {
val stacks = parseInitialStackConfig(input)
val instructions = parseInstructions(input)
instructions.forEach { stacks[it.from].popTo(stacks[it.to], it.count) }
return generateOutput(stacks)
}
fun part2(input: List<String>): String {
val stacks = parseInitialStackConfig(input)
val instructions = parseInstructions(input)
instructions.forEach {
val tmpStack = Stack<Char>()
stacks[it.from].popTo(tmpStack, it.count)
tmpStack.popTo(stacks[it.to], it.count)
}
return generateOutput(stacks)
}
val testInput = readInput("Day05_test", 2022)
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05", 2022)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 2,159 | adventOfCode | Apache License 2.0 |
src/me/bytebeats/algo/kt/design/NumMatrix.kt | bytebeats | 251,234,289 | false | null | package me.bytebeats.algo.kt.design
class NumMatrix(val matrix: Array<IntArray>) {//308
fun update(row: Int, col: Int, `val`: Int) {
matrix[row][col] = `val`
}
fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int {
var sum = 0
for (i in row1..row2) {
for (j in col1..col2) {
sum += matrix[i][j]
}
}
return sum
}
}
class NumMatrix2(val matrix: Array<IntArray>) {//308
private val sumMatrix: Array<IntArray> =
Array(matrix.size + 1) { IntArray(if (matrix.isNotEmpty()) matrix[0].size + 1 else 1) }
init {
for (i in matrix.indices) {
for (j in matrix[0].indices) {
sumMatrix[i + 1][j + 1] = matrix[i][j] + sumMatrix[i + 1][j] + sumMatrix[i][j + 1] - sumMatrix[i][j]
}
}
}
fun update(row: Int, col: Int, `val`: Int) {
val diff = `val` - matrix[row][col]
matrix[row][col] = `val`
for (i in row until matrix.size) {
for (j in col until matrix[0].size) {
sumMatrix[i + 1][j + 1] += diff
}
}
}
fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int {
return sumMatrix[row1][col1] - sumMatrix[row1][col2 + 1] - sumMatrix[row2 + 1][col1] + sumMatrix[row2 + 1][col2 + 1]
}
}
class NumMatrix3(matrix: Array<IntArray>) {//304
private val sumMatrix = Array(matrix.size + 1) { IntArray(if (matrix.isNotEmpty()) matrix[0].size + 1 else 1) }
init {
for (i in matrix.indices) {
for (j in matrix[0].indices) {
sumMatrix[i + 1][j + 1] = sumMatrix[i + 1][j] + sumMatrix[i][j + 1] + matrix[i][j] - sumMatrix[i][j]
}
}
}
fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int {
return sumMatrix[row2 + 1][col2 + 1] - sumMatrix[row1][col2 + 1] - sumMatrix[row2 + 1][col1] + sumMatrix[row1][col1]
}
} | 0 | Kotlin | 0 | 1 | 7cf372d9acb3274003bb782c51d608e5db6fa743 | 1,969 | Algorithms | MIT License |
src/day22/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day22
import java.io.File
import kotlin.math.max
import kotlin.math.min
data class Line(val min: Int, val max: Int) {
fun overlap(other: Line): Line? {
val start = max(min, other.min)
val end = min(max, other.max)
return if (start <= end) Line(start, end) else null
}
}
data class Cuboid(val on: Boolean, val x: Line, val y: Line, val z: Line) {
fun volume() = (if (on) 1L else -1L) * (1 + x.max - x.min) * (1 + y.max - y.min) * (1 + z.max - z.min)
fun intersection(other: Cuboid): Cuboid? {
val overlapX = x.overlap(other.x)
val overlapY = y.overlap(other.y)
val overlapZ = z.overlap(other.z)
if (overlapX != null && overlapY != null && overlapZ != null) {
return Cuboid(!on, overlapX, overlapY, overlapZ)
}
return null
}
}
fun calculate(cuboids: List<Cuboid>) =
cuboids.fold(mutableListOf<Cuboid>()) { acc, c ->
acc.addAll(acc.mapNotNull { existing -> existing.intersection(c) })
if (c.on) {
acc.add(c)
}
acc
}.sumOf { it.volume() }
fun main() {
val cuboids = File("src/day22/input.txt").readLines()
.map {
val (on, minX, maxX, minY, maxY, minZ, maxZ) =
Regex("(on|off) x=(-?[0-9]*)..(-?[0-9]*),y=(-?[0-9]*)..(-?[0-9]*),z=(-?[0-9]*)..(-?[0-9]*)")
.matchEntire(it)!!.destructured
Cuboid(
on == "on",
Line(minX.toInt(), maxX.toInt()),
Line(minY.toInt(), maxY.toInt()),
Line(minZ.toInt(), maxZ.toInt())
)
}
val cuboidsInRegion = cuboids
.filter { c ->
c.x.min >= -50 && c.x.max <= 50
&& c.y.min >= -50 && c.y.max <= 50
&& c.z.min >= -50 && c.z.max <= 50
}
println(calculate(cuboidsInRegion))
println(calculate(cuboids))
} | 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 1,927 | advent-of-code-2021 | MIT License |
src/Day03.kt | psabata | 573,777,105 | false | {"Kotlin": 19953} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val size = rucksack.length
val compartment1 = rucksack.substring(0, size / 2).toSet()
val compartment2 = rucksack.substring(size / 2, size).toSet()
val item = compartment1.intersect(compartment2).first()
item.priority()
}
}
fun part2(input: List<String>): Int {
return input.withIndex().groupBy(
keySelector = { it.index / 3 },
valueTransform = { it.value.toSet() }
).values.sumOf { group ->
val badge = group.fold(group.first()) { acc, bag -> acc.intersect(bag) }.first()
badge.priority()
}
}
val testInput = InputHelper("Day03_test.txt").readLines()
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = InputHelper("Day03.txt").readLines()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun Char.priority(): Int =
if (this.isUpperCase()) {
52 - ('Z'.code - this.code)
} else {
26 - ('z'.code - this.code)
}
| 0 | Kotlin | 0 | 0 | c0d2c21c5feb4ba2aeda4f421cb7b34ba3d97936 | 1,169 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | cerberus97 | 579,910,396 | false | {"Kotlin": 11722} | fun main() {
class Node(val name: String, val parent: Node? = null) {
val children = mutableMapOf<String, Node>()
val files = mutableMapOf<String, Int>()
var size = 0
fun getChild(childName: String): Node {
if (!children.containsKey(childName)) children[childName] = Node(childName, this)
return children[childName]!!
}
}
fun Node.sumAllDirSizes(maxDirSize: Int = Int.MAX_VALUE): Int {
val childAnsSum = children.values.sumOf { it.sumAllDirSizes(maxDirSize) }
size = files.values.sum() + children.values.sumOf { it.size }
return childAnsSum + if (size <= maxDirSize) size else 0
}
fun Node.smallestSizeLargerThan(requiredSize: Int): Int {
return (children.values.map { it.smallestSizeLargerThan(requiredSize) } + (if (size >= requiredSize) size else Int.MAX_VALUE)).min()
}
fun createInputTree(input: List<String>): Node {
val root = Node("/")
var cur = root
input.forEach { row ->
val tokens = row.split(' ')
if (tokens[0] == "$") {
if (tokens[1] == "cd") {
cur = when (tokens[2]) {
"/" -> root
".." -> cur.parent!!
else -> cur.getChild(tokens[2])
}
}
} else if (tokens[0] != "dir") {
cur.files[tokens[1]] = tokens[0].toInt()
}
}
return root
}
fun part1(root: Node): Int {
return root.sumAllDirSizes(100000)
}
fun part2(root: Node): Int {
val requiredSpace = 30000000 - 70000000 + root.size
return root.smallestSizeLargerThan(requiredSpace)
}
val input = readInput("in")
val root = createInputTree(input)
part1(root).println()
part2(root).println()
} | 0 | Kotlin | 0 | 0 | ed7b5bd7ad90bfa85e868fa2a2cdefead087d710 | 1,674 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/day07/Day07.kt | TheJosean | 573,113,380 | false | {"Kotlin": 20611} | package day07
import readInput
fun main() {
data class Directory(val size: Int, val index: Int)
fun parseDirectories(input: List<String>, startingIndex: Int): List<Directory> {
val items = input.subList(startingIndex + 2, input.size).takeWhile { !it.startsWith('$') }
var size = 0; var index = -1
val directories = mutableListOf<Directory>()
items.forEach {
if (it.startsWith("dir")) {
directories += parseDirectories(input, if (index == - 1) items.size + startingIndex + 2 else index)
val lastDirectory = directories.last()
index = lastDirectory.index + 1
size += lastDirectory.size
} else {
size += it.split(" ").first().toInt()
}
}
return directories.plus(Directory(size, if (index == - 1) items.size + startingIndex + 2 else index))
}
fun part1(input: List<String>): Int {
return parseDirectories(input, 0)
.filter { it.size < 100000 }
.sumOf { it.size}
}
fun part2(input: List<String>): Int {
val discSpace = 70000000
val neededSpace = 30000000
val directories = parseDirectories(input, 0)
val totalUsage = directories.last().size
val minUsage = neededSpace - (discSpace - totalUsage)
return directories.map { it.size }.filter { it > minUsage }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day07/Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("/day07/Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 798d5e9b1ce446ba3bac86f70b7888335e1a242b | 1,739 | advent-of-code | Apache License 2.0 |
src/Day11.kt | chbirmes | 572,675,727 | false | {"Kotlin": 32114} | fun main() {
fun part1(input: List<String>): Long {
val monkeys = input.filter { it.isNotEmpty() }
.chunked(6) { Monkey.parse(it) }
repeat(20) { monkeys.playRound(true) }
return monkeys.map { it.inspectionCount }
.sortedDescending()
.let { it[0] * it[1] }
}
fun part2(input: List<String>): Long {
val monkeys = input.filter { it.isNotEmpty() }
.chunked(6) { Monkey.parse(it) }
repeat(10_000) { monkeys.playRound(false) }
return monkeys.map { it.inspectionCount }
.sortedDescending()
.let { it[0] * it[1] }
}
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
private fun List<Monkey>.playRound(withCoolDown: Boolean) {
val modulo = map { it.testDivisor }.reduce(Long::times)
forEach { monkey ->
monkey.items.forEach { item ->
monkey.inspectionCount++
item.worryLevel = monkey.operation.invoke(item.worryLevel)
if (withCoolDown) {
item.coolDown()
}
item.worryLevel %= modulo
if (item.worryLevel % monkey.testDivisor == 0L) {
this[monkey.trueTarget].items.add(item)
} else {
this[monkey.falseTarget].items.add(item)
}
}
monkey.items.clear()
}
}
private data class Item(var worryLevel: Long) {
fun coolDown() {
worryLevel /= 3
}
}
private class Monkey(
val items: MutableList<Item>,
val operation: (Long) -> Long,
val testDivisor: Long,
val trueTarget: Int,
val falseTarget: Int,
var inspectionCount: Long = 0
) {
companion object {
fun parse(lines: List<String>): Monkey {
val startingItems = lines[1]
.substringAfter(": ")
.split(", ")
.map { Item(it.toLong()) }
val operation: (Long) -> Long = lines[2]
.substringAfter("new = old ")
.split(" ")
.let { tokens ->
{ old ->
val operator: (Long, Long) -> Long = if (tokens[0] == "+") Long::plus else Long::times
val operand = if (tokens[1] == "old") old else tokens[1].toLong()
operator.invoke(old, operand)
}
}
val testDivisor = lines[3].substringAfter("by ").toLong()
val trueTarget = lines[4].substringAfter("monkey ").toInt()
val falseTarget = lines[5].substringAfter("monkey ").toInt()
return Monkey(startingItems.toMutableList(), operation, testDivisor, trueTarget, falseTarget)
}
}
}
| 0 | Kotlin | 0 | 0 | db82954ee965238e19c9c917d5c278a274975f26 | 2,885 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | laricchia | 434,141,174 | false | {"Kotlin": 38143} | import org.jetbrains.kotlinx.multik.api.toNDArray
import org.jetbrains.kotlinx.multik.ndarray.operations.toListD2
fun firstPart04(list : List<String>) {
val extractions = list.first().split(",").map { it.toInt() }
val tables = list.subList(1, list.size).map { it.split(" ").filter { it.isNotEmpty() }.map { it.toInt() } }.chunked(5)
val tablesAndTransposed = tables.map {
listOf(it, it.toNDArray().transpose().toListD2())
}.flatten()
val currentExtraction = extractions.subList(0, 5).toMutableList()
var winnerSum = 0
extraction@ for (extractedNumber in extractions.subList(5, extractions.size)) {
currentExtraction.add(extractedNumber)
for (currentTable in tablesAndTransposed) {
val isBingo = checkBingo(currentExtraction, currentTable)
if (isBingo.first) {
winnerSum = isBingo.second
break@extraction
}
}
}
println(winnerSum * currentExtraction.last())
}
fun checkBingo(extractions : List<Int>, table : List<List<Int>>) : Pair<Boolean, Int> {
table.map {
if (extractions.containsAll(it)) {
val sumOfNotExtracted = table.flatten().filter { it !in extractions }.sum()
return true to sumOfNotExtracted
}
}
return false to 0
}
fun secondPart04(list : List<String>) {
val extractions = list.first().split(",").map { it.toInt() }
val tables = list.subList(1, list.size).map { it.split(" ").filter { it.isNotEmpty() }.map { it.toInt() } }.chunked(5)
val tablesAndTransposed = tables.map {
it to it.toNDArray().transpose().toListD2()
}
val currentPossibleTables = tablesAndTransposed.toMutableList()
val currentExtraction = extractions.subList(0, 5).toMutableList()
var winnerSum = 0
var lastWinnerExtractedNumber = 0
for (extractedNumber in extractions.subList(5, extractions.size)) {
currentExtraction.add(extractedNumber)
val toBeRemoved = mutableListOf<Pair<List<List<Int>>, List<List<Int>>>>()
for (currentTable in currentPossibleTables) {
val isBingoFirst = checkBingo(currentExtraction, currentTable.first)
val isBingoSecond = checkBingo(currentExtraction, currentTable.second)
if (isBingoFirst.first) { winnerSum = isBingoFirst.second }
if (isBingoSecond.first) { winnerSum = isBingoSecond.second }
if (isBingoFirst.first || isBingoSecond.first) {
toBeRemoved.add(currentTable)
lastWinnerExtractedNumber = currentExtraction.last()
}
}
currentPossibleTables.removeAll(toBeRemoved)
}
println(winnerSum * lastWinnerExtractedNumber)
}
fun main() {
val input : List<String> = readInput("Day04")
val list = input.filter { it.isNotBlank() }
firstPart04(list)
secondPart04(list)
}
| 0 | Kotlin | 0 | 0 | 7041d15fafa7256628df5c52fea2a137bdc60727 | 2,893 | Advent_of_Code_2021_Kotlin | Apache License 2.0 |
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day13Test.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
private fun solution1(input: String) = parse(input)
.mapIndexed { index, packets -> index to packets }
.filter { (_, packets) -> packets.first < packets.second }
.sumOf { (index, _) -> index + 1 }
private val div1 = parseEntry("[[2]]")
private val div2 = parseEntry("[[6]]")
private fun solution2(input: String) = parse(input).flatMap { it.toList() }
.plus(listOf(div1, div2))
.sorted().let { (it.indexOf(div1) + 1) * (it.indexOf(div2) + 1) }
private fun parse(input: String) = input.split("\n\n")
.map { it.split("\n") }
.map { (l, r) -> parseEntry(l) to parseEntry(r) }
private fun parseEntry(input: String) = "\\[|]|\\d+".toRegex().findAll(input)
.map { match -> match.value }
.let { tokens -> parse(tokens.iterator()) ?: throw IllegalStateException() }
private fun parse(tokens: Iterator<String>): Entry? =
when (val token = tokens.next()) {
"]" -> null
"[" -> ListEntry(generateSequence { parse(tokens) }.toList())
else -> IntEntry(token.toInt())
}
private sealed interface Entry : Comparable<Entry>
private data class ListEntry(val values: List<Entry>) : Entry {
override fun compareTo(other: Entry): Int = when (other) {
is IntEntry -> compareTo(ListEntry(listOf(other)))
is ListEntry -> values.zip(other.values)
.map { (a, b) -> a.compareTo(b) }
.firstOrNull { it != 0 } ?: values.size.compareTo(other.values.size)
}
}
private data class IntEntry(val value: Int) : Entry {
override fun compareTo(other: Entry) = when (other) {
is IntEntry -> value.compareTo(other.value)
is ListEntry -> ListEntry(listOf(this)).compareTo(other)
}
}
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 13
class Day13Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 13 }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 6369 }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 140 }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 25800 }
})
private val exampleInput =
"""
[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
""".trimIndent()
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 2,782 | adventofcode-kotlin | MIT License |
src/day15/Parser.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day15
import readInput
import java.util.regex.Pattern
data class Point (val x: Int, val y: Int) {
fun add (dx: Int, dy: Int) = Point (x + dx, y + dy)
fun min (other: Point): Point = Point (Math.min (x, other.x), Math.min (y, other.y))
fun max (other: Point): Point = Point (Math.max (x, other.x), Math.max (y, other.y))
}
data class Bounds (val min: Point, val max: Point) {
fun join (other: Bounds) = Bounds (min.min (other.min), max.max (other.max))
}
data class Measurement (val sensor: Point, val beacon: Point) {
val bounds: Bounds
get () {
val d = Math.abs (distance)
val (x, y) = sensor
return Bounds (Point (x - d, y - d), Point (x + d, y + d))
}
fun hasRow (y: Int): Boolean {
val (p0, p1) = bounds
return y in p0.y .. p1.y
}
fun forRow (y: Int): Pair<Int, Int>? {
if (! hasRow (y)) {
return null
}
val delta = Math.abs (distance) - Math.abs (y - sensor.y)
return Pair(sensor.x - delta, sensor.x + delta)
}
val dx: Int = beacon.x - sensor.x
val dy: Int = beacon.y - sensor.y
val distance: Int
get () = Math.abs (dx) + Math.abs (dy)
override fun toString(): String {
return ("S:$sensor B:$beacon D:$distance")
}
}
data class Measurements (val data: List<Measurement>) {
val bounds: Bounds
get () {
var bounds = data[0].bounds
data.forEach { el ->
bounds = bounds.join (el.bounds)
}
return bounds
}
fun dump () = println (toString ())
override fun toString (): String {
val buf = StringBuffer ()
data.forEachIndexed { i, m ->
buf.append ("${i}: $m\n")
}
return buf.toString ()
}
companion object {
private val REGEX = "^Sensor at x=([-\\d]+), y=([-\\d]+): closest beacon is at x=([-\\d]+), y=([-\\d]+)$"
private val PATTERN = Pattern.compile (REGEX)
fun parse (input: String): Measurements {
val list = input.trim ().split ("\n").map { str ->
val m = PATTERN.matcher (str)
if (! m.matches()) {
throw IllegalStateException ("Malformed input: $str")
}
var i = 1
val v = { m.group (i ++).toInt () }
Measurement (
Point (v (), v ()),
Point (v (), v ())
)
}
return Measurements (list)
}
}
}
fun loadMeasurements (example: Boolean): Measurements = Measurements.parse (readInput (15, example))
fun main() {
val example = true
val ms = loadMeasurements (example)
ms.data.forEach { el ->
println (el)
println (" bounds=${el.bounds}")
}
println ("BOUNDS=${ms.bounds}")
return
}
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 2,919 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/day08/Day08.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day08
import readInput
import java.util.BitSet
import java.util.PriorityQueue
fun main() {
fun part1(input: List<String>): Int {
val m = input.size
val n = input[0].length
val bitSet = BitSet(m * n)
fun check(startX: Int, startY: Int, deltaX: Int, deltaY: Int) {
var x = startX
var y = startY
var max = -1
while (x in 0 until m && y in 0 until n) {
val treeHeight = input[x][y].digitToInt()
if (treeHeight > max) {
bitSet[x * n + y] = true
}
max = maxOf(max, treeHeight)
x += deltaX
y += deltaY
}
}
for (i in 0 until m) {
check(i, 0, 0, 1)
check(i, n - 1, 0, -1)
}
for (i in 0 until n) {
check(0, i, 1, 0)
check(m - 1, i, -1, 0)
}
println((0 until m).joinToString(separator = "\n") { x ->
(0 until m).joinToString(separator = "") { y -> if (bitSet[x * n + y]) "1" else "0" }
})
return bitSet.cardinality()
}
fun part2(input: List<String>): Int {
val m = input.size
val n = input[0].length
val result = IntArray(m * n) { 1 }
fun check(startX: Int, startY: Int, deltaX: Int, deltaY: Int) {
var x = startX
var y = startY
val q = PriorityQueue<Pair<Int, Int>>(compareBy { it.first })
while (x in 0 until m && y in 0 until n) {
val treeHeight = input[x][y].digitToInt()
var counter = 0
while (q.isNotEmpty() && q.peek().first < treeHeight) {
val (_, count) = q.remove()
counter += count
}
result[x * n + y] *= counter + if (q.isNotEmpty()) 1 else 0
q.add(treeHeight to counter + 1)
x += deltaX
y += deltaY
}
}
for (i in 0 until m) {
check(i, 0, 0, 1)
check(i, n - 1, 0, -1)
}
for (i in 0 until n) {
check(0, i, 1, 0)
check(m - 1, i, -1, 0)
}
println((0 until m).joinToString(separator = "\n") { x ->
(0 until m).joinToString(separator = " ") { y -> result[x * n + y].toString().padStart(2) }
})
return result.max()
}
val testInput = readInput("day08", "test")
val input = readInput("day08", "input")
check(part1(testInput) == 21)
println(part1(input))
check(part2(testInput) == 8)
check(part2(input) == 410400)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 2,708 | aoc2022 | Apache License 2.0 |
src/Day08.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} | fun main() {
fun parseInput(input: List<String>): Map<Coordinates, Tree> {
val rows = input.size
val cols = input[0].length
val grid = mutableMapOf<Coordinates, Tree>()
for(row in 0 until rows) {
for (col in 0 until cols) {
val position = Coordinates(row, col)
val tree = Tree(position, input[row][col].toString().toInt())
grid[position] = tree
}
}
return grid
}
fun part1(input: List<String>): Int {
val grid = parseInput(input)
return grid.count { (_, tree) -> tree.isVisible(grid) }
}
fun part2(input: List<String>): Int {
val grid = parseInput(input)
return grid.map { (_, tree) -> tree.getScenicScore(grid) }.max()
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
data class Tree(
val position: Coordinates,
val height: Int
) {
private var tallestHeightToWest: Int? = null
private var tallestHeightToEast: Int? = null
private var tallestHeightToNorth: Int? = null
private var tallestHeightToSouth: Int? = null
private fun getTallestHeightToWest(grid: Map<Coordinates, Tree>): Int {
if (tallestHeightToWest == null) {
val westPosition = position.copy(col = position.col - 1)
val westNeighbor = grid[westPosition]
tallestHeightToWest = maxOf(westNeighbor?.height ?: -1, westNeighbor?.getTallestHeightToWest(grid) ?: -1)
}
return tallestHeightToWest!!
}
private fun getTallestHeightToEast(grid: Map<Coordinates, Tree>): Int {
if (tallestHeightToEast == null) {
val eastPosition = position.copy(col = position.col + 1)
val eastNeighbor = grid[eastPosition]
tallestHeightToEast = maxOf(eastNeighbor?.height ?: -1, eastNeighbor?.getTallestHeightToEast(grid) ?: -1)
}
return tallestHeightToEast!!
}
private fun getTallestHeightToNorth(grid: Map<Coordinates, Tree>): Int {
if (tallestHeightToNorth == null) {
val northPosition = position.copy(row = position.row - 1)
val northNeighbor = grid[northPosition]
tallestHeightToNorth = maxOf(northNeighbor?.height ?: -1, northNeighbor?.getTallestHeightToNorth(grid) ?: -1)
}
return tallestHeightToNorth!!
}
private fun getTallestHeightToSouth(grid: Map<Coordinates, Tree>): Int {
if (tallestHeightToSouth == null) {
val southPosition = position.copy(row = position.row + 1)
val southNeighbor = grid[southPosition]
tallestHeightToSouth = maxOf(southNeighbor?.height ?: -1, southNeighbor?.getTallestHeightToSouth(grid) ?: -1)
}
return tallestHeightToSouth!!
}
fun isVisible(grid: Map<Coordinates, Tree>): Boolean {
val neighborHeights = listOf(
getTallestHeightToWest(grid),
getTallestHeightToEast(grid),
getTallestHeightToNorth(grid),
getTallestHeightToSouth(grid)
)
return neighborHeights.any { it < height }
}
private fun distanceWestUntil(maxHeight: Int, grid: Map<Coordinates, Tree>): Int {
val westPosition = position.copy(col = position.col - 1)
val westNeighbor = grid[westPosition]
return if (westNeighbor == null) {
0
} else if (westNeighbor.height >= maxHeight) {
1
} else {
1 + westNeighbor.distanceWestUntil(maxHeight, grid)
}
}
private fun distanceEastUntil(maxHeight: Int, grid: Map<Coordinates, Tree>): Int {
val eastPosition = position.copy(col = position.col + 1)
val eastNeighbor = grid[eastPosition]
return if (eastNeighbor == null) {
0
} else if (eastNeighbor.height >= maxHeight) {
1
} else {
1 + eastNeighbor.distanceEastUntil(maxHeight, grid)
}
}
private fun distanceNorthUntil(maxHeight: Int, grid: Map<Coordinates, Tree>): Int {
val northPosition = position.copy(row = position.row - 1)
val northNeighbor = grid[northPosition]
return if (northNeighbor == null) {
0
} else if (northNeighbor.height >= maxHeight) {
1
} else {
1 + northNeighbor.distanceNorthUntil(maxHeight, grid)
}
}
private fun distanceSouthUntil(maxHeight: Int, grid: Map<Coordinates, Tree>): Int {
val southPosition = position.copy(row = position.row + 1)
val southNeighbor = grid[southPosition]
return if (southNeighbor == null) {
0
} else if (southNeighbor.height >= maxHeight) {
1
} else {
1 + southNeighbor.distanceSouthUntil(maxHeight, grid)
}
}
fun getScenicScore(grid: Map<Coordinates, Tree>): Int {
val west = distanceWestUntil(height, grid)
val east = distanceEastUntil(height, grid)
val north = distanceNorthUntil(height, grid)
val south = distanceSouthUntil(height, grid)
return west * east * north * south
}
} | 0 | Kotlin | 0 | 0 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 5,292 | aoc2022 | Apache License 2.0 |
src/Day16.kt | asm0dey | 572,860,747 | false | {"Kotlin": 61384} | import Graph16.*
fun main() {
fun parseInput(input: List<String>): Set<Valve> = input
.asSequence()
.filter(String::isNotBlank)
.map {
it
.replace(Regex("(Valve |has flow rate=|; tunnels? leads? to valves?)"), "")
.split(' ', ',')
.filter(String::isNotEmpty)
}
.map {
val name = it[0]
val flowRate = it[1].toInt()
val leadsTo = it.subList(2, it.size)
Valve(flowRate, leadsTo, name)
}
.toSet()
fun part1(input: List<String>): Int {
val allValves = parseInput(input)
val maxOpenValves = allValves.count { it.flow > 0 }
val start = allValves.find { it.name == "AA" }!!
val startPath = Path1(listOf(start), HashMap())
var allPaths = listOf(startPath)
var bestPath = startPath
for (time in 1..30) {
allPaths = buildList {
for (it in allPaths) {
if (it.open.size == maxOpenValves) listOf<Path1>()
val currentLast = it.last()
val currentValves = it.valves
// open valve
if (currentLast.flow > 0 && !it.open.containsKey(currentLast)) {
val open = it.open.toMutableMap()
open[currentLast] = time
val possibleValves = currentValves + currentLast
this.add(Path1(possibleValves, open))
}
// move to valve
currentLast.leadsTo
.mapTo(this) { lead ->
Path1(currentValves + (allValves.find { it.name == lead }!!), it.open)
}
}
}
.sortedByDescending { it.total() }
.take(10000)
if (allPaths.first().total() > bestPath.total()) bestPath = allPaths.first()
}
return bestPath.total()
}
fun findPossibleValves(
open: Boolean,
currentLast: Valve,
currentValves: List<Valve>,
opened: MutableMap<Valve, Int>,
time: Int,
allValves: Set<Valve>
) = if (open) {
opened[currentLast] = time
listOf(currentValves + currentLast)
} else {
currentLast.leadsTo.map { lead ->
// add possible path and move on
val possibleValve = allValves.find { it.name == lead } ?: error("valve $lead not found")
val possibleValves = currentValves + possibleValve
possibleValves
}
}
fun part2(input: List<String>): Int {
val allValves = parseInput(input)
val maxOpenValves = allValves.count { it.flow > 0 }
val start = allValves.find { it.name == "AA" }!!
val startPath = Path2(valvesMe = listOf(start), valvesElephant = listOf(start), open = HashMap())
var allPaths = listOf(startPath)
var bestPath = startPath
for (time in 1..26) {
val newPaths = buildList {
for (currentPath in allPaths) {
if (currentPath.open.size == maxOpenValves) continue
val currentLastMe = currentPath.lastMe()
val currentLastElephant = currentPath.lastElephant()
val currentValvesMe = currentPath.valvesMe
val currentValvesElephant = currentPath.valvesElephant
val openMe = currentLastMe.flow > 0 && !currentPath.open.containsKey(currentLastMe)
val openElephant =
currentLastElephant.flow > 0 && !currentPath.open.containsKey(currentLastElephant)
// open both, mine or elephant's valve
if (openMe || openElephant) {
val open = currentPath.open.toMutableMap()
val possibleValvesMe: List<List<Valve>> =
findPossibleValves(openMe, currentLastMe, currentValvesMe, open, time, allValves)
val possibleValvesElephants: List<List<Valve>> = findPossibleValves(
openElephant,
currentLastElephant,
currentValvesElephant,
open,
time,
allValves
)
possibleValvesMe
.flatMapTo(this) { a ->
possibleValvesElephants.map { b ->
Path2(a, b, open)
}
}
}
currentLastMe.leadsTo
.flatMap { a -> currentLastElephant.leadsTo.map { b -> a to b } }
.filter { (a, b) -> a != b }
.mapTo(this) { (leadMe, leadElephant) ->
Path2(
currentValvesMe + (allValves.find { it.name == leadMe }!!),
currentValvesElephant + (allValves.find { it.name == leadElephant }!!),
currentPath.open
)
}
}
}
allPaths = newPaths.sortedByDescending { it.total() }.take(100000).toList()
if (allPaths.first().total() > bestPath.total()) bestPath = allPaths.first()
}
return bestPath.total()
}
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
class Graph16 {
data class Valve(val flow: Int, val leadsTo: List<String>, val name: String)
data class Path1(val valves: List<Valve>, val open: Map<Valve, Int>) {
fun last(): Valve = valves.last()
fun total(): Int = open.map { (valve, time) -> (30 - time) * valve.flow }.sum()
}
data class Path2(val valvesMe: List<Valve>, val valvesElephant: List<Valve>, val open: Map<Valve, Int>) {
fun lastMe(): Valve = valvesMe.last()
fun lastElephant(): Valve = valvesElephant.last()
fun total(): Int = open.map { (valve, time) -> (26 - time) * valve.flow }.sum()
}
} | 1 | Kotlin | 0 | 1 | f49aea1755c8b2d479d730d9653603421c355b60 | 6,441 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | Ramo-11 | 573,610,722 | false | {"Kotlin": 21264} | fun main() {
fun part1(input: List<String>): Int {
var pair1 = ""
var pair2 = ""
var total = 0
for (i in input.indices) {
pair1 = input[i].split(",")[0]
pair2 = input[i].split(",")[1]
if ((pair1.split("-")[0].toInt() >= pair2.split("-")[0].toInt() && pair1.split("-")[1].toInt() <= pair2.split("-")[1].toInt()) ||
(pair2.split("-")[0].toInt() >= pair1.split("-")[0].toInt() && pair2.split("-")[1].toInt() <= pair1.split("-")[1].toInt())) {
total++
}
}
return total
}
fun part2(input: List<String>): Int {
var pair1 = ""
var pair2 = ""
var pair1set: Set<Int> = setOf()
var pair2set: Set<Int> = setOf()
var total = 0
for (i in input.indices) {
pair1 = input[i].split(",")[0]
pair2 = input[i].split(",")[1]
pair1set = IntRange(pair1.split("-")[0].toInt(), pair1.split("-")[1].toInt()).toSet()
pair2set = IntRange(pair2.split("-")[0].toInt(), pair2.split("-")[1].toInt()).toSet()
if (pair1set.any(pair2set::contains) || pair2set.any(pair1set::contains)) {
total++
}
}
return total
}
val input = readInput("Day04")
val part1Answer = part1(input)
val part2Answer = part2(input)
println("Answer for part 1: $part1Answer")
println("Answer for part 2: $part2Answer")
}
| 0 | Kotlin | 0 | 0 | a122cca3423c9849ceea5a4b69b4d96fdeeadd01 | 1,485 | advent-of-code-kotlin | Apache License 2.0 |
archive/2022/Day04.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | package aoc2022
private const val EXPECTED_1 = 2
private const val EXPECTED_2 = 4
private class Day04(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
return readAsLines().sumInt {
val parts = it.split(",")
var elf1 = parts[0].split("-").map { it.toInt() }
var elf2 = parts[1].split("-").map { it.toInt() }
if (elf1[0] > elf2[0] || (elf1[0] == elf2[0] && elf1[1] < elf2[1])) {
elf1 = elf2.also { elf2 = elf1 }
}
if (elf2[1] <= elf1[1]) 1 else 0
}
}
fun part2(): Any {
return readAsLines().sumInt {
val parts = it.split(",")
val elf1 = parts[0].split("-").map { it.toInt() }
val elf2 = parts[1].split("-").map { it.toInt() }
val maxBegin = elf1[0].coerceAtLeast(elf2[0])
val minEnd = elf1[1].coerceAtMost(elf2[1])
if (maxBegin <= minEnd) 1 else 0
}
}
}
fun main() {
val testInstance = Day04(true)
val instance = Day04(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println(instance.part1())
testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } }
println(instance.part2())
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 1,293 | advent-of-code-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.