path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/me/grison/aoc/y2021/Day04.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2021
import me.grison.aoc.*
class Day04 : Day(4, 2021) {
override fun title() = "Giant Squid"
private val suite = inputList.first().allInts()
private val boards = inputGroups.tail().map { it.lines().map { it.allInts() } }
override fun partOne(): Int {
(1..suite.size).forEach { round ->
suite.first(round).let { numbers ->
boards.firstOrNull { it.wins(numbers) }?.let { board ->
return board.sumOfAllUnmarkedNumbers(numbers) * numbers.last()
}
}
}
return 0
}
override fun partTwo(): Int {
val winners = mutableListOf<Int>()
(1..suite.size).forEach { round ->
suite.first(round).let { numbers ->
boards.withIndex().forEach { (boardIndex, board) ->
if (boardIndex !in winners && board.wins(numbers)) {
winners.add(boardIndex)
if (winners.size == boards.size)
return board.sumOfAllUnmarkedNumbers(numbers) * numbers.last()
}
}
}
}
return 0
}
}
typealias Board = List<List<Int>>
fun Board.wins(numbers: List<Int>): Boolean {
return indices.any { row ->
this[row].all { numbers.contains(it) } || // horizontal
indices.all { numbers.contains(this[it][row]) } // vertical
}
}
fun Board.sumOfAllUnmarkedNumbers(numbers: List<Int>) =
this.sumOf { it.filter { !numbers.contains(it) }.sum() }
| 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 1,583 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/Day21.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | fun main() {
fun getAnsMap(opMap: Map<String, String>, humnUnknow: Boolean = false): Map<String, Long?> {
val ansMap = mutableMapOf<String, Long?>()
fun dfs(key: String): Long? {
if (key in ansMap) return ansMap[key]
val op = opMap[key]!!
val result = if (op[0].isDigit()) {
op.toLong()
} else {
val splits = op.split(" ")
val a = dfs(splits[0])
val b = dfs(splits[2])
if (a == null || b == null) null
else {
when (splits[1]) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
"/" -> a / b
else -> throw java.lang.RuntimeException()
}
}
}
ansMap[key] = result
return result
}
if (humnUnknow) ansMap["humn"] = null
dfs("root")
return ansMap
}
fun part1(input: List<String>): Long {
val opMap = input.associate { it.split(": ")[0] to it.split(": ")[1] }
val ansMap = getAnsMap(opMap)
return ansMap["root"]!!
}
// Find the value of "humn" from top to bottom.
fun part2(input: List<String>): Long {
val opMap = input.associate { it.split(": ")[0] to it.split(": ")[1] }
val ansMap = getAnsMap(opMap, humnUnknow = true)
val ka = opMap["root"]!!.split(" ")[0]
val kb = opMap["root"]!!.split(" ")[2]
val va = ansMap[ka]
val vb = ansMap[kb]
var (key, currentValue) = if (va == null) ka to vb!! else kb to va
while (key != "humn") {
val op = opMap[key]!!
val splits = op.split(" ")
val kx = splits[0]
val ky = splits[2]
val vx = ansMap[kx]
val vy = ansMap[ky]
if (vx == null) {
key = kx
currentValue = when (splits[1]) {
"+" -> currentValue - vy!!
"-" -> currentValue + vy!!
"*" -> currentValue / vy!!
"/" -> currentValue * vy!!
else -> 0
}
} else {
key = ky
currentValue = when (splits[1]) {
"+" -> currentValue - vx
"-" -> vx - currentValue
"*" -> currentValue / vx
"/" -> vx * currentValue
else -> 0
}
}
}
return currentValue
}
println(part1(readInput("data/Day21_test")))
println(part1(readInput("data/Day21")))
println(part2(readInput("data/Day21_test")))
println(part2(readInput("data/Day21")))
} | 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 2,383 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day05.kt | arturkowalczyk300 | 573,084,149 | false | {"Kotlin": 31119} | import java.util.LinkedList
import java.util.Queue
fun main() {
class Move(val howMuch: Int, val from: Int, val to: Int) {
override fun toString(): String {
return "move ${howMuch} crates from ${from} to ${to}"
}
}
fun parseListOfMoves(input: List<String>): List<Move> {
val regexPattern = """move ([\d]+) from ([\d]+) to ([\d]+)"""
val regex = Regex(regexPattern)
val listOfMoves = mutableListOf<Move>()
input.forEach {
val found = regex.find(it)
val matches = found!!.groupValues
val move = Move(matches[1].toInt(), matches[2].toInt(), matches[3].toInt())
listOfMoves.add(move)
}
return listOfMoves
}
fun parseHeapsOfCrates(heap: List<String>, numerationString: String): List<MutableList<Char>> {
//find all numbers in numeration line - then get indices of columns where number are in heap string
var numbers =
numerationString.mapIndexed { index, it -> if (!" []".toCharArray().contains(it)) index else null }
numbers = numbers.filterNotNull()
val heapQueues = mutableListOf<LinkedList<Char>>()
numbers.forEachIndexed { index, column ->
heapQueues.add(LinkedList<Char>())
for (i in heap.size - 1 downTo 0) {
val heapQueue = heapQueues[index]
if (heap[i].length > column && heap[i].get(column) != ' ')
heapQueue.add(heap[i].get(column))
}
}
return heapQueues
}
fun move(heap: List<MutableList<Char>>, targetMove: Move): List<MutableList<Char>> {
for (i in 1..targetMove.howMuch) {
heap[targetMove.to - 1].add(heap[targetMove.from - 1].removeLast())
}
return heap
}
fun moveWithoutReorganisation(heap: List<MutableList<Char>>, targetMove: Move): List<MutableList<Char>> {
val lastIndex = heap[targetMove.from - 1].lastIndex
val elementsToRemove: List<Char> =
heap[targetMove.from - 1].filterIndexed { index, it -> index in lastIndex - (targetMove.howMuch - 1)..lastIndex }
elementsToRemove.forEach {
heap[targetMove.from - 1].removeLast()
}
heap[targetMove.to - 1].addAll(elementsToRemove)
println(heap.toString())
println(targetMove.toString())
return heap
}
fun getSymbolsOfTopCrates(heap: List<List<Char>>): String {
val sb = StringBuilder()
for (i in 0 until heap.size) {
if (heap[i].size > 0)
sb.append(heap[i].last())
}
return sb.toString()
}
fun part1(input: List<String>): String {
var beginningOfMoveListIndex = -1
input.forEachIndexed() { index, it ->
if (it.contains("move") && beginningOfMoveListIndex == -1) //not found yet
beginningOfMoveListIndex = index
}
var heapContent = input.take(beginningOfMoveListIndex).dropLast(1)
var numerationLine = heapContent.takeLast(1)[0]
heapContent = heapContent.dropLast(1)
var listOfMoves = input.drop(beginningOfMoveListIndex)
var heap = parseHeapsOfCrates(heapContent, numerationLine)
val moves = parseListOfMoves(listOfMoves)
moves.forEach { move ->
heap = move(heap, move)
}
return getSymbolsOfTopCrates(heap)
}
fun part2(input: List<String>): String {
var beginningOfMoveListIndex = -1
input.forEachIndexed() { index, it ->
if (it.contains("move") && beginningOfMoveListIndex == -1) //not found yet
beginningOfMoveListIndex = index
}
var heapContent = input.take(beginningOfMoveListIndex).dropLast(1)
var numerationLine = heapContent.takeLast(1)[0]
heapContent = heapContent.dropLast(1)
var listOfMoves = input.drop(beginningOfMoveListIndex)
var heap = parseHeapsOfCrates(heapContent, numerationLine)
val moves = parseListOfMoves(listOfMoves)
moves.forEach { move ->
heap = moveWithoutReorganisation(heap, move)
}
return getSymbolsOfTopCrates(heap)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
val input = readInput("Day05")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 69a51e6f0437f5bc2cdf909919c26276317b396d | 4,515 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day04.kt | remidu | 573,452,090 | false | {"Kotlin": 22113} | fun main() {
fun extend(range: String): List<Int> {
val result = ArrayList<Int>()
val numbers = range.split('-')
for (i in numbers[0].toInt()..numbers[1].toInt()) {
result.add(i)
}
return result
}
fun part1(input: List<String>): Int {
var total = 0
for (line in input) {
val split = line.split(',')
if (extend(split[0]).containsAll(extend(split[1]))
or extend(split[1]).containsAll(extend(split[0])))
total++
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
for (line in input) {
val split = line.split(',')
val range1 = extend(split[0])
val range2 = extend(split[1])
for (number in range1) {
if (range2.contains(number)) {
total++
break
}
}
}
return total
}
// 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 | ecda4e162ab8f1d46be1ce4b1b9a75bb901bc106 | 1,284 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/me/circuitrcay/euler/challenges/fiftyOneToSeventyFive/probUtils/Prob54Utils.kt | adamint | 134,989,381 | false | null | package me.circuitrcay.euler.challenges.fiftyOneToSeventyFive.probUtils
/**
* [value] is 1-10 for numbered cards, 11 for J, 12 for Q, and 13 and 14 for K and A respectively
*/
data class Card(val value: Int, val suit: Suit)
enum class Suit { HEART, SPADE, CLUB, DIAMOND }
class Deck(vararg val cards: Card) {
val royalFlush: Boolean
get() = cards.filter { it.suit == cards[0].suit }
.containsAll(listOf(Card(10, cards[0].suit), Card(11, cards[0].suit),
Card(12, cards[0].suit), Card(13, cards[0].suit), Card(14, cards[0].suit)))
val straightFlush: Boolean
get() {
val sorted = cards.filter { it.suit == cards[0].suit }.sortedBy { it.value }
if (sorted.size != 5) return false
val first = sorted[0].value
return sorted[1].value == first + 1 && sorted[2].value == first + 2 && sorted[3].value == first + 3
&& sorted[4].value == first + 4
}
val fourOfKind: Boolean
get() {
val sorted = sort
return if (sorted.size > 4) sorted[0] == sorted[3] || sorted[1] == sorted[4] else false
}
val fullHouse: Boolean
get() {
val sorted = cards.filter { it.suit == cards[0].suit }.sortedBy { it.value }.toMutableList()
val pair = hasPair(sorted)
return if (pair == null) false else sorted.filter { it.value != pair && it.suit == sorted[0].suit }.count() == 3
}
val flush: Boolean
get() = cards.filter { it.suit == cards[0].suit }.count() == 5
val straight: Boolean
get() {
val sorted = sort
val first = sorted[0].value
return sorted[1].value == first + 1 && sorted[2].value == first + 2 && sorted[3].value == first + 3
&& sorted[4].value == first + 4
}
val threeOfKind: Boolean
get() {
val sorted = sort
for (i in 0..(cards.size - 2)) if (sorted[i] == sorted[2]) return true
return true
}
val twoPairs: Boolean
get() {
val sorted = sort
val first = hasPair(sorted) ?: return false
val second = hasPair(sorted.filter { it.value != first })
return second != null
}
val pair: Boolean
get() = hasPair(sort) != null
fun hasPair(cards: List<Card>): Int? {
return if (cards.size < 2) null else {
(0..(cards.size - 2)).forEach { i -> if (cards[i].value == cards[i + 1].value) return cards[i].value }
return null
}
}
val sort: MutableList<Card>
get() = cards.sortedBy { it.value }.toMutableList()
val value: Int
get() {
return when {
royalFlush -> 1000
straightFlush -> 900
fourOfKind -> 800
fullHouse -> 700
flush -> 600
straight -> 500
threeOfKind -> 400
twoPairs -> 300
pair -> 200
else -> sort.last().value
}
}
fun compare(o: Deck): Boolean {
val firstValue = value
val secondValue = o.value
val firstSorted = sort
val secondSorted = o.sort
when {
firstValue > secondValue -> return true
firstValue < secondValue -> return false
else -> {
if (firstValue <= 400 || firstValue == 800) {
when (firstValue) {
800 -> {
val fMax = if (firstSorted[0].value == firstSorted[3].value) firstSorted[0].value else firstSorted[1].value
val sMax = if (secondSorted[0].value == secondSorted[3].value) secondSorted[0].value else secondSorted[1].value
return when {
fMax > sMax -> true
fMax < sMax -> false
else -> return lastHigher(firstSorted.filter { it.value != fMax }, secondSorted.filter { it.value != sMax })
}
}
100, 200 -> {
val fPair = hasPair(firstSorted)!!
val sPair = hasPair(secondSorted)!!
val fSPair = hasPair(firstSorted.filter { it.value != fPair })
val sSPair = hasPair(secondSorted.filter { it.value != sPair })
if (fPair != sPair) return fPair > sPair
else if (fSPair != null && sSPair != null && fSPair != sSPair) return fSPair > sSPair
else return lastHigher(firstSorted.filter { it.value != fPair && it.value != fSPair },
secondSorted.filter { it.value != sPair && it.value != sSPair })
}
400 -> {
val fTrip = when {
firstSorted[0].value == firstSorted[2].value -> firstSorted[0].value
firstSorted[1].value == firstSorted[3].value -> firstSorted[1].value
else -> firstSorted[2].value
}
val sTrip = when {
secondSorted[0].value == secondSorted[2].value -> secondSorted[0].value
secondSorted[1].value == secondSorted[3].value -> secondSorted[1].value
else -> secondSorted[2].value
}
if (fTrip != sTrip) return fTrip > sTrip
return lastHigher(firstSorted.filter { it.value != fTrip }, secondSorted.filter { it.value != sTrip })
}
else -> {
println("wot")
System.exit(1)
return false
}
}
} else return lastHigher(o)
}
}
}
fun lastHigher(one: List<Card>, two: List<Card>) = Deck(*one.toTypedArray()).compare(Deck(*two.toTypedArray()))
fun lastHigher(o: Deck): Boolean {
val firstSorted = sort
val secondSorted = o.sort
var index = 4
while (index >= 0 && firstSorted[index].value == secondSorted[index].value) index--
return when {
firstSorted[index].value > secondSorted[index].value -> true
else -> false
}
}
} | 0 | Kotlin | 0 | 0 | cebe96422207000718dbee46dce92fb332118665 | 6,665 | project-euler-kotlin | Apache License 2.0 |
src/main/kotlin/com/kishor/kotlin/ds/StringsAndArrays.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.ds
import kotlin.math.min
fun main() {
val list = MutableList(10) { Int.MAX_VALUE }
Math.min(10, 5)
var test: Pair<Int, Int> = Pair(1, 2)
println(isAnagram("restful", "furstel"))
}
class StringsAndArrays {
val nums = IntArray(10) { 1 }
var list = mutableListOf<String>()
fun findMissingRanges(nums: IntArray, lower: Int, upper: Int): List<String> {
val theRange = mutableListOf<String>() // mutableList and MutableList
var prev = lower - 1
for (i in nums.indices) {
val cur = if (i < nums.size) nums[i] else upper + 1
if (prev + 1 <= cur - 1) {
addTheRange(cur - 1, prev + 1, theRange)
}
prev = cur
}
return theRange
}
fun addTheRange(upper: Int, lower: Int, theRange: MutableList<String>) {
if (lower == upper) {
theRange.add("$lower")
} else {
theRange.add("$lower->$upper")
}
}
fun largestRange(array: List<Int>): Pair<Int, Int> {
// Write your code here.
val sortedArray = array.sorted() // O(nlogn)
var maxDiff = Int.MIN_VALUE
var pairOfResult = Pair(-1, -1)
for (i in 0 until sortedArray.size - 1) {
if (sortedArray[i + 1] - sortedArray[i] > 1) {
if (maxDiff <= sortedArray[i + 1] - sortedArray[i]) {
maxDiff = sortedArray[i + 1] - sortedArray[i]
pairOfResult = Pair(sortedArray[i], sortedArray[i + 1])
}
}
}
return pairOfResult
}
fun expressiveWords(S: String, words: Array<String>): Int {
val stringMap = mutableMapOf<Char, Int>()
var result = 0
// form a string map
formAMap(S, stringMap)
// Iterate through array and compare
for (s in words) {
val wordMap = mutableMapOf<Char, Int>()
formAMap(s, wordMap)
// compare the map and increament the count
if (isWordStretchy(wordMap, stringMap)) {
result++
}
}
return result
}
}
fun formAMap(s: String, map: MutableMap<Char, Int>) {
for (c in s.toCharArray()) {
map[c] = map.getOrDefault(c, 0) + 1
}
}
fun isWordStretchy(wordMap: MutableMap<Char, Int>, stringMap: MutableMap<Char, Int>): Boolean {
for (entity in stringMap) {
val key = entity.key
val value = entity.value
if (!wordMap.containsKey(key)) {
return false
}
if (wordMap[key]!! > value) {
return false
} else if (wordMap[key]!! <= value) {
continue
}
}
return true
}
fun isAnagram(str1: String, str2: String): Boolean {
val intArray = IntArray(26) { 0 }
for (i in 0 until str1.length) {
val c = str1[i].toInt() - 96
intArray[c] += 1
}
for (i in 0 until str2.length) {
val c = str2[i].toInt() - 96
intArray[c] -= 1
}
intArray.forEach { it ->
if (it > 0) return false
}
return true
}
| 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 3,141 | DS_Algo_Kotlin | MIT License |
src/main/aoc2019/Day17.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2019
import Direction
import Pos
import AMap
import kotlin.enums.EnumEntries
import kotlin.math.min
class Day17(input: List<String>) {
val parsedInput = input.map { it.toLong() }
private fun countIntersections(map: AMap): Int {
var sum = 0
for (y in 1 until map.yRange().last) {
for (x in 1 until map.xRange().last) {
val current = Pos(x, y)
if (map[current] == '#' &&
Direction.entries.all { dir -> map[dir.from(current)] == '#' }) {
sum += x * y
}
}
}
return sum
}
private fun generateMap(): AMap {
val c = Intcode(parsedInput)
c.run()
var x = 0
var y = 0
val map = AMap()
c.output.forEach {
val current = it.toInt().toChar()
if (current == '\n') {
y++
x = 0
} else {
map[Pos(x++, y)] = current
}
}
return map
}
private fun findPath(map: AMap): List<String> {
var facing = Direction.Up // Robot is facing up at first
var pos = map.toMap().filterValues { it == '^' }.keys.first()
val path = mutableListOf<String>()
while (true) {
val code: String
val toLeft = map.getOrDefault(facing.turnLeft().from(pos), '.')
val toRight = map.getOrDefault(facing.turnRight().from(pos), '.')
if (toLeft == '.' && toRight == '.') {
// Found the end
break
} else if (toLeft == '#') {
facing = facing.turnLeft()
code = "L"
} else {
facing = facing.turnRight()
code = "R"
}
var steps = 0
do {
pos = facing.from(pos)
steps++
} while (map.getOrDefault(facing.from(pos), '.') == '#') // Move until the pipe turns
path.add("$code,$steps")
}
return path
}
private fun List<String>.startsWith(prefix: List<String>): Boolean {
return subList(0, min(size, prefix.size)) == prefix
}
// Drop all occurrences of the given prefixes from the given list.
private fun dropPrefixes(list: List<String>, prefixes: List<List<String>>): List<String> {
var offset = 0
while (offset < list.size) {
val current = list.subList(offset, list.size)
// Find first prefix that the list starts with, if it exist advance offset and continue
// If there is no prefix all prefixes have been dropped, return the remainder
prefixes.firstOrNull { current.startsWith(it) }
.let { prefix ->
if (prefix == null) {
return current
}
offset += prefix.size
}
}
return emptyList()
}
// The path needs to be split up in three functions with maximum 20 characters
// in each function. Find the three functions that can be repeated several times
// to make up the whole path.
private fun findFunctions(path: List<String>): List<Pair<String, List<String>>> {
// Max 20 characters per function means max 5 instructions per function
val maxInstructions = 5
val minInstructions = 1
for (i in minInstructions..maxInstructions) {
// Candidate instructions for the first function
val candidate1 = path.subList(0, i)
val remaining1 = dropPrefixes(path, listOf(candidate1))
for (j in minInstructions..maxInstructions) {
// candidate instructions for the second function
val candidate2 = remaining1.subList(0, j)
val remaining2 = dropPrefixes(remaining1, listOf(candidate2, candidate1))
for (k in minInstructions..maxInstructions) {
// candidate instructions for the third function
val candidate3 = remaining2.subList(0, k)
val remaining3 = dropPrefixes(remaining2, listOf(candidate3, candidate2, candidate1))
if (remaining3.isEmpty()) {
return listOf("A" to candidate1, "B" to candidate2, "C" to candidate3)
} // else: these candidates didn't work, try with the next candidate
}
}
}
return emptyList()
}
private fun makeMainMovementRoutine(patterns: List<Pair<String, List<String>>>, path: List<String>): String {
var ret = path.joinToString(",")
patterns.forEach { (functionName, instructionList) ->
val instructions = instructionList.joinToString(",")
// Replace the identified movement functions in the path with the function names
ret = ret.replace(instructions, functionName)
}
return ret
}
fun solvePart1(): Int {
return countIntersections(generateMap())
}
fun solvePart2(): Long {
val map = generateMap()
val path = findPath(map)
val functions = findFunctions(path)
val mainRoutine = makeMainMovementRoutine(functions, path)
.map { it.code.toLong() }
.toMutableList()
.apply { add('\n'.code.toLong()) }
val movementFunctions = functions
.map { (_, instructions) ->
instructions.joinToString(",")
.map { it.code.toLong() }
.toMutableList()
.apply { add('\n'.code.toLong()) }
}
// Change the value at address 0 to 2 to wake the robot up
val actualProgram = parsedInput.toMutableList().apply { this[0] = 2L }.toList()
Intcode(actualProgram).run {
input.addAll(mainRoutine)
movementFunctions.forEach { input.addAll(it) }
input.add('n'.code.toLong()) // No video feed please
input.add('\n'.code.toLong())
run()
return output.last()
}
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 6,247 | aoc | MIT License |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2017/2017-14.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2017
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.searchGraph
import com.github.ferinagy.adventOfCode.singleStep
fun main() {
println("Part1:")
println(part1(testInput1))
println(part1(input))
println()
println("Part2:")
println(part2(testInput1))
println(part2(input))
}
private fun part1(input: String): Int = parseDisk(input).sumOf { line -> line.count { it == '1' } }
private fun part2(input: String): Int {
val disk = parseDisk(input)
val used = mutableSetOf<Coord2D>()
disk.forEachIndexed { y, row ->
row.forEachIndexed { x, c ->
if (c == '1') used += Coord2D(x, y)
}
}
var regions = 0
while (used.isNotEmpty()) {
val visited = mutableSetOf<Coord2D>()
searchGraph(
start = used.first(),
isDone = {
visited += it
false
},
nextSteps = { (it.adjacent(false).toSet() intersect used).singleStep() }
)
used -= visited
regions++
}
return regions
}
private fun parseDisk(input: String): List<String> {
val strings = (0 until 128).map { n ->
val hasher = KnotHasher()
val hashInput = "$input-$n"
hasher.hash(hashInput)
}
val binary = strings.map { line ->
line.map { "%04d".format(it.digitToInt(16).toString(2).toInt()) }.joinToString(separator = "")
}
return binary
}
private const val testInput1 = """flqrgnkx"""
private const val input = """amgozmfv"""
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,613 | advent-of-code | MIT License |
cz.wrent.advent/Day7.kt | Wrent | 572,992,605 | false | {"Kotlin": 206165} | package cz.wrent.advent
fun main() {
println(partOne(test))
val result = partOne(input)
println("7a: $result")
println(partTwo(test))
val resultTwo = partTwo(input)
println("7b: $resultTwo")
}
private fun partOne(input: String): Long {
val nodes = input.parseTree()
return nodes.values.filterIsInstance<Dir>().filter { it.getSize() <= 100000 }.sumOf { it.getSize() }
}
private fun partTwo(input: String): Long {
val nodes = input.parseTree()
val root = nodes["/"]!!
val freeSpace = 70000000 - root.getSize()
val requiredSpace = 30000000 - freeSpace
return nodes.values.filterIsInstance<Dir>().filter { it.getSize() >= requiredSpace }.minByOrNull { it.getSize() }!!
.getSize()
}
private interface Node {
fun getChildren(): List<Node>
fun getSize(): Long
fun getFullName(): String
fun getParent(): Dir
}
private data class File(
private val parent: Dir,
private val name: String,
private val size: Long,
) : Node {
override fun getChildren(): List<Node> {
return emptyList()
}
override fun getSize(): Long {
return size
}
override fun getFullName(): String {
return this.parent.getFullName() + "/" + this.name
}
override fun getParent(): Dir {
return this.parent
}
}
private data class Dir(
private val parent: Dir?,
private val name: String,
private val children: MutableList<Node>,
) : Node {
override fun getChildren(): List<Node> {
return children
}
override fun getSize(): Long {
return children.sumOf { it.getSize() }
}
override fun getFullName(): String {
return (this.parent?.getFullName() ?: "") + "/" + this.name
}
override fun getParent(): Dir {
return this.parent ?: this
}
fun addChild(node: Node) {
this.children.add(node)
}
}
private fun String.parseTree(): Map<String, Node> {
val split = this.split("$ ").drop(1)
val iterator = split.iterator()
val root = Dir(null, "", mutableListOf())
val nodes = mutableMapOf<String, Node>(root.getFullName() to root)
var current = root
while (iterator.hasNext()) {
val next = iterator.next()
if (next.startsWith("cd")) {
val path = next.split(" ").get(1).trim()
val dir = Dir(current, path, mutableListOf())
if (path == "/") {
current = root
} else if (path == "..") {
current = current.getParent()
} else if (!nodes.containsKey(dir.getFullName())) {
current = dir
nodes[dir.getFullName()] = dir
} else {
current = nodes[dir.getFullName()] as Dir
}
} else if (next.startsWith("ls")) {
val files = next.split("\n").drop(1).filter { it.isNotEmpty() }
files.forEach { fileString ->
val (size, name) = fileString.split(" ")
val node = if (size == "dir") {
Dir(current, name, mutableListOf())
} else {
File(current, name, size.toLong())
}
current.addChild(node)
nodes[node.getFullName()] = node
}
} else {
error("Unknown command $next")
}
}
return nodes
}
private const val test = """${'$'} cd /
${'$'} ls
dir a
14848514 b.txt
8504156 c.dat
dir d
${'$'} cd a
${'$'} ls
dir e
29116 f
2557 g
62596 h.lst
${'$'} cd e
${'$'} ls
584 i
${'$'} cd ..
${'$'} cd ..
${'$'} cd d
${'$'} ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k"""
private const val input = """${'$'} cd /
${'$'} ls
dir bntdgzs
179593 cjw.jgc
110209 grbwdwsm.znn
dir hsswswtq
dir jdfwmhg
dir jlcbpsr
70323 qdtbvqjj
48606 qdtbvqjj.zdg
dir tvcr
dir vhjbjr
dir vvsg
270523 wpsjfqtn.ljt
${'$'} cd bntdgzs
${'$'} ls
297955 gcwcp
${'$'} cd ..
${'$'} cd hsswswtq
${'$'} ls
dir bsjbvff
dir dpgvp
267138 grbwdwsm.znn
dir hldgfpvh
dir jdfwmhg
dir jtgdv
93274 ptsd.nzh
268335 qdtbvqjj.dlh
185530 qdtbvqjj.jrw
dir vcbqdj
dir wtrsg
${'$'} cd bsjbvff
${'$'} ls
dir dmnt
148799 grbwdwsm.znn
324931 hzmqrfc.lsd
211089 qdtbvqjj
${'$'} cd dmnt
${'$'} ls
221038 zht
${'$'} cd ..
${'$'} cd ..
${'$'} cd dpgvp
${'$'} ls
dir fzttpjtd
dir jdrbwrc
dir rwz
dir tssm
${'$'} cd fzttpjtd
${'$'} ls
149872 jdfwmhg
${'$'} cd ..
${'$'} cd jdrbwrc
${'$'} ls
149973 hpgg.srm
dir ptsd
${'$'} cd ptsd
${'$'} ls
2594 twzf.pqq
${'$'} cd ..
${'$'} cd ..
${'$'} cd rwz
${'$'} ls
dir jdfwmhg
302808 zzlh
${'$'} cd jdfwmhg
${'$'} ls
229683 cdcrgcmh
218733 nhzt
${'$'} cd ..
${'$'} cd ..
${'$'} cd tssm
${'$'} ls
dir ptsd
37272 qfnnrqsh.qvg
215066 wnvjc.jqf
${'$'} cd ptsd
${'$'} ls
24102 bwtbht.dwq
224035 qdtbvqjj.dmp
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd hldgfpvh
${'$'} ls
316712 grbwdwsm.znn
328950 tqvgqjrr
${'$'} cd ..
${'$'} cd jdfwmhg
${'$'} ls
130652 gcwcp
dir jdfwmhg
215427 lfw.zml
dir qdtbvqjj
4181 rgsvgssj.qsr
${'$'} cd jdfwmhg
${'$'} ls
dir bvm
dir hsswswtq
122279 qznt.jhl
dir sjw
dir zpfdtl
${'$'} cd bvm
${'$'} ls
22841 fbcgh.mrp
dir hsswswtq
dir hstg
41317 ndrt
dir nvmvghb
239316 ptsd
dir qtwvdtsp
98555 vzh
${'$'} cd hsswswtq
${'$'} ls
dir ddcjvjgf
127104 plwvb.pbj
dir ptsd
dir qhp
dir rjtrhgwh
${'$'} cd ddcjvjgf
${'$'} ls
135870 bwtbht.dwq
81968 gcwcp
182253 mrbh.wmc
275931 nsrqrts
322128 pfpcp
${'$'} cd ..
${'$'} cd ptsd
${'$'} ls
214981 jsrlsc
dir wpbdrcw
${'$'} cd wpbdrcw
${'$'} ls
197849 mljfb.ggb
173586 ptsd
${'$'} cd ..
${'$'} cd ..
${'$'} cd qhp
${'$'} ls
293198 bnrgl
${'$'} cd ..
${'$'} cd rjtrhgwh
${'$'} ls
224393 clrp.nst
${'$'} cd ..
${'$'} cd ..
${'$'} cd hstg
${'$'} ls
51671 gdsfpc
209216 hsswswtq
97203 jlnr
dir thdhg
57399 tssm
${'$'} cd thdhg
${'$'} ls
201896 jjp.wvw
${'$'} cd ..
${'$'} cd ..
${'$'} cd nvmvghb
${'$'} ls
210047 gfcrzgj
dir rqjbplv
dir rvwd
292931 sgwvcqfr.bpq
dir vtjd
${'$'} cd rqjbplv
${'$'} ls
105204 gcwcp
${'$'} cd ..
${'$'} cd rvwd
${'$'} ls
66170 jdfwmhg
${'$'} cd ..
${'$'} cd vtjd
${'$'} ls
dir ptsd
${'$'} cd ptsd
${'$'} ls
300524 bwtbht.dwq
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd qtwvdtsp
${'$'} ls
289574 wctgtq
${'$'} cd ..
${'$'} cd ..
${'$'} cd hsswswtq
${'$'} ls
24935 gcwcp
dir jzpbdcmc
26834 mljfb.ggb
182501 phnmlsjp.pjc
dir pttnl
dir qdtbvqjj
dir vst
${'$'} cd jzpbdcmc
${'$'} ls
297521 grbwdwsm.znn
dir qwc
dir zzswd
${'$'} cd qwc
${'$'} ls
81143 hsswswtq.rjw
54843 mjvvfsz.rgz
273051 pfwgtmtt.ccs
${'$'} cd ..
${'$'} cd zzswd
${'$'} ls
216062 vlbwz.zmh
${'$'} cd ..
${'$'} cd ..
${'$'} cd pttnl
${'$'} ls
257733 mljfb.ggb
250887 pfwgtmtt.ccs
${'$'} cd ..
${'$'} cd qdtbvqjj
${'$'} ls
34667 gcwcp
${'$'} cd ..
${'$'} cd vst
${'$'} ls
70250 pfwgtmtt.ccs
dir zpcqhml
${'$'} cd zpcqhml
${'$'} ls
219936 jdfwmhg.zbm
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd sjw
${'$'} ls
152311 nqjtvzff
157117 pfwgtmtt.ccs
118226 ptsd.vsm
${'$'} cd ..
${'$'} cd zpfdtl
${'$'} ls
189042 gcwcp
${'$'} cd ..
${'$'} cd ..
${'$'} cd qdtbvqjj
${'$'} ls
dir ftz
dir hvlffb
dir lzbb
53335 ptsd
dir qdtbvqjj
${'$'} cd ftz
${'$'} ls
dir fft
256058 gcwcp
497 hsswswtq.vqs
103941 hvtcz.fsg
171587 ljlnz.ffg
115101 mljfb.ggb
dir qdtbvqjj
${'$'} cd fft
${'$'} ls
58845 bwtbht.dwq
136040 gcwcp
256973 mljfb.ggb
${'$'} cd ..
${'$'} cd qdtbvqjj
${'$'} ls
dir fgqhdh
304573 ntm.wmc
${'$'} cd fgqhdh
${'$'} ls
317143 gcwcp
26010 lsfpfdqz
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd hvlffb
${'$'} ls
6682 vjt.mcf
${'$'} cd ..
${'$'} cd lzbb
${'$'} ls
dir bbvml
324162 bwtbht.dwq
dir fjs
dir pffntc
dir pnltt
dir ptsd
${'$'} cd bbvml
${'$'} ls
dir qdtbvqjj
dir qssdcrp
dir tssm
${'$'} cd qdtbvqjj
${'$'} ls
246275 qdtbvqjj.cgn
${'$'} cd ..
${'$'} cd qssdcrp
${'$'} ls
274399 hsswswtq
${'$'} cd ..
${'$'} cd tssm
${'$'} ls
dir ssqc
${'$'} cd ssqc
${'$'} ls
178904 njrssmlm.gcm
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd fjs
${'$'} ls
dir dmvnp
121967 fqlzlvwt
204348 grbwdwsm.znn
102733 jdfwmhg.qsl
240279 ptsd.jwm
228793 ptsd.nsh
dir ssm
${'$'} cd dmvnp
${'$'} ls
dir psj
dir zjw
${'$'} cd psj
${'$'} ls
170665 gcwcp
56058 lsfzc.dcp
40658 tfsllqqw.fgv
${'$'} cd ..
${'$'} cd zjw
${'$'} ls
79989 fggsl.dmz
${'$'} cd ..
${'$'} cd ..
${'$'} cd ssm
${'$'} ls
106263 bwtbht.dwq
106259 jdfwmhg.qtb
6246 rwbnr.tqv
${'$'} cd ..
${'$'} cd ..
${'$'} cd pffntc
${'$'} ls
111475 qbmrdms.ldm
${'$'} cd ..
${'$'} cd pnltt
${'$'} ls
dir nptfhlf
dir zngmf
${'$'} cd nptfhlf
${'$'} ls
223065 qrb.drh
205674 rdgfz
${'$'} cd ..
${'$'} cd zngmf
${'$'} ls
61655 bwtbht.dwq
${'$'} cd ..
${'$'} cd ..
${'$'} cd ptsd
${'$'} ls
dir hrvrt
dir thwtl
${'$'} cd hrvrt
${'$'} ls
152296 pfwgtmtt.ccs
${'$'} cd ..
${'$'} cd thwtl
${'$'} ls
156783 pfwgtmtt.ccs
323304 sltc
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd qdtbvqjj
${'$'} ls
320175 pfwgtmtt.ccs
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd jtgdv
${'$'} ls
81164 ptsd.tpj
${'$'} cd ..
${'$'} cd vcbqdj
${'$'} ls
dir crng
330203 gvlrg
152022 qdtbvqjj.slq
294095 rthwj.zrf
dir vjsbf
${'$'} cd crng
${'$'} ls
dir gznrh
${'$'} cd gznrh
${'$'} ls
259458 ptsd
${'$'} cd ..
${'$'} cd ..
${'$'} cd vjsbf
${'$'} ls
47331 hlld.fzf
147103 jdfwmhg
${'$'} cd ..
${'$'} cd ..
${'$'} cd wtrsg
${'$'} ls
144344 dtcc
${'$'} cd ..
${'$'} cd ..
${'$'} cd jdfwmhg
${'$'} ls
323973 qdtbvqjj
${'$'} cd ..
${'$'} cd jlcbpsr
${'$'} ls
dir htrdwm
dir jdfwmhg
dir pwmvbhsl
dir vwfdfmcp
${'$'} cd htrdwm
${'$'} ls
dir btn
105731 dlncqrbm.dgl
158267 gqqghldt
242513 hsswswtq.drj
dir jdfwmhg
212816 swsgtv.wbb
228996 tgll.rcs
${'$'} cd btn
${'$'} ls
50419 pfwgtmtt.ccs
${'$'} cd ..
${'$'} cd jdfwmhg
${'$'} ls
dir bwc
${'$'} cd bwc
${'$'} ls
184634 cfwg
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd jdfwmhg
${'$'} ls
319749 hsswswtq
dir jdfwmhg
271619 jdfwmhg.znz
dir jhmmt
181217 mljfb.ggb
11297 rcpl.tgf
83423 zwscbcvm.ths
${'$'} cd jdfwmhg
${'$'} ls
267171 cts.hlf
${'$'} cd ..
${'$'} cd jhmmt
${'$'} ls
84473 jdfwmhg
${'$'} cd ..
${'$'} cd ..
${'$'} cd pwmvbhsl
${'$'} ls
dir jsg
171725 mljfb.ggb
152612 qjr
dir vfsqw
${'$'} cd jsg
${'$'} ls
176951 jdfwmhg.fhn
284927 ljvvtw.wcq
153109 vnvtt
${'$'} cd ..
${'$'} cd vfsqw
${'$'} ls
104559 htsrns.gws
${'$'} cd ..
${'$'} cd ..
${'$'} cd vwfdfmcp
${'$'} ls
291404 csmvbjlt.tdf
${'$'} cd ..
${'$'} cd ..
${'$'} cd tvcr
${'$'} ls
dir djtwv
dir hsswswtq
272845 mdds
dir ndshbjzn
65929 scpltww.twm
dir tssm
30516 zdpscm
dir zqdrdzv
${'$'} cd djtwv
${'$'} ls
271696 cwjj.hjp
${'$'} cd ..
${'$'} cd hsswswtq
${'$'} ls
dir djngm
dir hcz
dir ptsd
${'$'} cd djngm
${'$'} ls
317775 ltwjzpjb.rcj
37776 qdtbvqjj.lzf
${'$'} cd ..
${'$'} cd hcz
${'$'} ls
217741 pgdmr
128868 qdtbvqjj
306138 zbmrplsn
${'$'} cd ..
${'$'} cd ptsd
${'$'} ls
304048 ftm
120236 mdcwvvng
${'$'} cd ..
${'$'} cd ..
${'$'} cd ndshbjzn
${'$'} ls
206408 pfwgtmtt.ccs
${'$'} cd ..
${'$'} cd tssm
${'$'} ls
dir mlcnsf
dir nbgjm
204079 pdljvb
185465 rqgdmbjf.rhr
dir sfnlb
${'$'} cd mlcnsf
${'$'} ls
249868 fqrncwd
29146 zdz.jth
${'$'} cd ..
${'$'} cd nbgjm
${'$'} ls
113314 mljfb.ggb
${'$'} cd ..
${'$'} cd sfnlb
${'$'} ls
234917 tjp
${'$'} cd ..
${'$'} cd ..
${'$'} cd zqdrdzv
${'$'} ls
40790 vtdnhzm
${'$'} cd ..
${'$'} cd ..
${'$'} cd vhjbjr
${'$'} ls
dir glv
dir mvns
dir qbrnh
${'$'} cd glv
${'$'} ls
288849 bgvqll.sfj
259105 jdfwmhg
dir qcjlshcv
${'$'} cd qcjlshcv
${'$'} ls
dir nwqqjcmh
${'$'} cd nwqqjcmh
${'$'} ls
137244 grbwdwsm.znn
312904 mzh
dir qdtbvqjj
${'$'} cd qdtbvqjj
${'$'} ls
dir nlqbq
${'$'} cd nlqbq
${'$'} ls
307636 ptsd.vtr
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd mvns
${'$'} ls
dir gzqlmrdh
dir qjhtlh
dir tssm
dir vthg
${'$'} cd gzqlmrdh
${'$'} ls
274950 mlzdqwm
${'$'} cd ..
${'$'} cd qjhtlh
${'$'} ls
157835 ptsd.lqm
300380 wst.trp
${'$'} cd ..
${'$'} cd tssm
${'$'} ls
15772 gcwcp
${'$'} cd ..
${'$'} cd vthg
${'$'} ls
dir gdndtlnc
${'$'} cd gdndtlnc
${'$'} ls
3175 hsswswtq.bds
320462 mljfb.ggb
305508 mzvtzvqc
dir qdtbvqjj
154575 tssm.vgb
${'$'} cd qdtbvqjj
${'$'} ls
236889 drnnvh
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd qbrnh
${'$'} ls
dir hsswswtq
4623 hsswswtq.rnf
266326 jrmq.ztg
295980 tssm.vzb
dir wnbfzd
dir zjzhncs
dir zttlggt
${'$'} cd hsswswtq
${'$'} ls
48277 gsqjdbhv
${'$'} cd ..
${'$'} cd wnbfzd
${'$'} ls
97133 mljfb.ggb
${'$'} cd ..
${'$'} cd zjzhncs
${'$'} ls
298303 gcwcp
dir ggr
113206 grbwdwsm.znn
${'$'} cd ggr
${'$'} ls
244876 ptsd.zvb
${'$'} cd ..
${'$'} cd ..
${'$'} cd zttlggt
${'$'} ls
dir hdbwrcm
dir mbvpd
dir mtd
dir ptsd
dir tcwqp
${'$'} cd hdbwrcm
${'$'} ls
267323 bwtbht.dwq
${'$'} cd ..
${'$'} cd mbvpd
${'$'} ls
84087 frf.smv
${'$'} cd ..
${'$'} cd mtd
${'$'} ls
158543 mljfb.ggb
${'$'} cd ..
${'$'} cd ptsd
${'$'} ls
112797 vtschwnb.fnp
${'$'} cd ..
${'$'} cd tcwqp
${'$'} ls
90637 lbsqcj.sfn
179097 tssm.dbl
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd vvsg
${'$'} ls
168715 bwtbht.dwq
dir bwv
dir hsswswtq
dir lqmnjrlb
dir mmrfrj
175244 vct.tsc
dir zwvlhs
${'$'} cd bwv
${'$'} ls
201509 gcwcp
62815 grbwdwsm.znn
dir gwdh
dir mfdvcn
166355 pfwgtmtt.ccs
dir ptsd
169681 qdtbvqjj.fgh
250573 wvndzgv
${'$'} cd gwdh
${'$'} ls
306377 sphrj.pjh
${'$'} cd ..
${'$'} cd mfdvcn
${'$'} ls
27796 bvclvtrm.jlf
65045 cghr.vzg
dir hsswswtq
197145 jdqztgh.pvd
${'$'} cd hsswswtq
${'$'} ls
298155 bwtbht.dwq
${'$'} cd ..
${'$'} cd ..
${'$'} cd ptsd
${'$'} ls
27501 grbwdwsm.znn
231999 jdnsv
113528 rmfmb.zzw
dir tssm
dir vgjfsh
${'$'} cd tssm
${'$'} ls
dir dndv
226375 grbwdwsm.znn
${'$'} cd dndv
${'$'} ls
152739 sdjrzcv.tvs
${'$'} cd ..
${'$'} cd ..
${'$'} cd vgjfsh
${'$'} ls
211409 swtbttb.vrp
170879 vvfnf.hrp
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd hsswswtq
${'$'} ls
dir qdtbvqjj
dir tssm
86418 vhsgq
${'$'} cd qdtbvqjj
${'$'} ls
118588 bwtbht.dwq
${'$'} cd ..
${'$'} cd tssm
${'$'} ls
113460 gml.wdg
${'$'} cd ..
${'$'} cd ..
${'$'} cd lqmnjrlb
${'$'} ls
dir tssm
${'$'} cd tssm
${'$'} ls
dir jdfwmhg
${'$'} cd jdfwmhg
${'$'} ls
64663 nswd.rwc
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd mmrfrj
${'$'} ls
319070 gltlwnlt.jzw
232039 hspr
104688 hsswswtq.jsr
dir jdfwmhg
88712 jdfwmhg.zcw
dir pfr
dir prnnpwcd
45488 qdtbvqjj
dir tssm
dir wcmwrtjn
${'$'} cd jdfwmhg
${'$'} ls
140910 bjjhtzct.stm
${'$'} cd ..
${'$'} cd pfr
${'$'} ls
289538 qdtbvqjj
217502 vvpwf
${'$'} cd ..
${'$'} cd prnnpwcd
${'$'} ls
dir qdtbvqjj
${'$'} cd qdtbvqjj
${'$'} ls
dir pqg
dir tssm
${'$'} cd pqg
${'$'} ls
222392 ptsd.ggr
${'$'} cd ..
${'$'} cd tssm
${'$'} ls
158252 dcnvjj.zfd
10486 jdfwmhg.qmb
4374 qdtbvqjj.vqm
254229 vgqfw
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd tssm
${'$'} ls
dir ptsd
${'$'} cd ptsd
${'$'} ls
173766 fvlsgqb
35658 wtc.vvd
${'$'} cd ..
${'$'} cd ..
${'$'} cd wcmwrtjn
${'$'} ls
160089 chfhpc
76202 frgpdnd.ngw
138996 jsfsfpqg.nhf
dir mlm
dir nbdbzsn
dir ptsd
278574 vrnb
${'$'} cd mlm
${'$'} ls
dir gqwhhmvd
dir nrzvzgrt
dir nzplht
dir zzp
${'$'} cd gqwhhmvd
${'$'} ls
dir ddmvjpj
dir jdfwmhg
${'$'} cd ddmvjpj
${'$'} ls
273423 jdfwmhg
43605 pfwgtmtt.ccs
${'$'} cd ..
${'$'} cd jdfwmhg
${'$'} ls
239406 qctw.vzb
${'$'} cd ..
${'$'} cd ..
${'$'} cd nrzvzgrt
${'$'} ls
20712 gcwcp
239372 gjgdvbwb.gcz
dir hdzhl
124814 jdfwmhg
dir jfzr
295071 qwjgwqp
221611 shrzpsj.dwh
dir tssm
dir wdlsvzvl
${'$'} cd hdzhl
${'$'} ls
dir gfwbd
184323 hsswswtq.mln
177147 nqgqz.tnf
4680 pfwgtmtt.ccs
${'$'} cd gfwbd
${'$'} ls
254870 cldm.fft
301411 tssm.cvn
${'$'} cd ..
${'$'} cd ..
${'$'} cd jfzr
${'$'} ls
dir dvvflnnw
dir jdfwmhg
216389 lwtwn.ttt
201727 pfwgtmtt.ccs
107829 prphc.ncb
5816 sdvq.jvn
${'$'} cd dvvflnnw
${'$'} ls
24741 brtrbwh.wwd
27700 mljfb.ggb
${'$'} cd ..
${'$'} cd jdfwmhg
${'$'} ls
325218 bwtbht.dwq
63718 mvl.ngz
162645 vtd.vgp
${'$'} cd ..
${'$'} cd ..
${'$'} cd tssm
${'$'} ls
60903 pfwgtmtt.ccs
332768 qdtbvqjj.jwb
${'$'} cd ..
${'$'} cd wdlsvzvl
${'$'} ls
142213 vgvd
${'$'} cd ..
${'$'} cd ..
${'$'} cd nzplht
${'$'} ls
275904 hsswswtq
157369 jdfwmhg
84363 jvcvmbm.fht
dir qbjqgg
${'$'} cd qbjqgg
${'$'} ls
331934 gcwcp
${'$'} cd ..
${'$'} cd ..
${'$'} cd zzp
${'$'} ls
151335 flsd.zmj
dir gwlhqlp
99086 jdfwmhg.hft
${'$'} cd gwlhqlp
${'$'} ls
201894 glcnpqzp.jvc
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd nbdbzsn
${'$'} ls
169929 bwtbht.dwq
${'$'} cd ..
${'$'} cd ptsd
${'$'} ls
128999 bwtbht.dwq
dir jtlrn
dir pszlt
dir ptjnh
dir ptsd
2981 qdtbvqjj.qcn
dir rpb
dir tcjgpqj
dir tmddnh
dir tssm
${'$'} cd jtlrn
${'$'} ls
124888 grbwdwsm.znn
30046 jznz.dwf
${'$'} cd ..
${'$'} cd pszlt
${'$'} ls
154368 dbblsg.mzr
${'$'} cd ..
${'$'} cd ptjnh
${'$'} ls
306974 grbwdwsm.znn
82840 ptsd
${'$'} cd ..
${'$'} cd ptsd
${'$'} ls
dir ftjhsb
dir jdfwmhg
304012 lqgtvmrl.qbj
96971 mljfb.ggb
${'$'} cd ftjhsb
${'$'} ls
56965 dhgds
${'$'} cd ..
${'$'} cd jdfwmhg
${'$'} ls
dir lssbmtms
dir vmwshd
${'$'} cd lssbmtms
${'$'} ls
95453 gcwcp
198402 mljfb.ggb
1507 mzlmp
40526 twlqhml
${'$'} cd ..
${'$'} cd vmwshd
${'$'} ls
267087 pfwgtmtt.ccs
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd rpb
${'$'} ls
dir lqbchlbp
dir ptsd
${'$'} cd lqbchlbp
${'$'} ls
151429 ptsd.tjz
${'$'} cd ..
${'$'} cd ptsd
${'$'} ls
28900 gcwcp
55920 llt
${'$'} cd ..
${'$'} cd ..
${'$'} cd tcjgpqj
${'$'} ls
dir cvdlcvq
329232 hcmj.nvp
232764 nvtmgc.qgs
108056 ptsd.gcn
39056 qdtbvqjj
91792 tssm.wqz
${'$'} cd cvdlcvq
${'$'} ls
46978 grbwdwsm.znn
17760 qrdbsdpj.dhm
${'$'} cd ..
${'$'} cd ..
${'$'} cd tmddnh
${'$'} ls
238434 gggvq.tfc
${'$'} cd ..
${'$'} cd tssm
${'$'} ls
dir tlllv
${'$'} cd tlllv
${'$'} ls
198184 trmf.qqw
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd ..
${'$'} cd zwvlhs
${'$'} ls
19923 gcwcp
129179 grbwdwsm.znn
214660 pghcvh
101270 ptsd.gzl
dir srjlz
${'$'} cd srjlz
${'$'} ls
221301 nrcg.pqw"""
| 0 | Kotlin | 0 | 0 | 8230fce9a907343f11a2c042ebe0bf204775be3f | 17,032 | advent-of-code-2022 | MIT License |
src/main/kotlin/de/tek/adventofcode/y2022/day16/ProboscideaVolcanium.kt | Thumas | 576,671,911 | false | {"Kotlin": 192328} | package de.tek.adventofcode.y2022.day16
import de.tek.adventofcode.y2022.util.algorithms.permutations
import de.tek.adventofcode.y2022.util.algorithms.subsets
import de.tek.adventofcode.y2022.util.math.Edge
import de.tek.adventofcode.y2022.util.math.Graph
import de.tek.adventofcode.y2022.util.readInputLines
class Valve(val name: String, val flowRate: Int) {
private val reachableValves = mutableListOf<Valve>()
fun addReachableValves(valves: List<Valve>) = reachableValves.addAll(valves)
fun getReachableValves() = reachableValves.toList()
override fun toString(): String {
return "Valve(name='$name', flowRate=$flowRate, reachableValves=${reachableValves.map(Valve::name)})"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Valve) return false
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
companion object {
private val valveRegex = Regex("""Valve ([^ ]+) has flow rate=(\d+)""")
fun parseFrom(string: String): Valve {
val valveRegexMatches = valveRegex.matchEntire(string)
if (valveRegexMatches != null) {
val (name, flowRate) = valveRegexMatches.destructured
return Valve(name, flowRate.toInt())
}
throw IllegalArgumentException("Cannot parse valve from $string. Expected format is $valveRegex.")
}
}
}
class Volcano private constructor(valves: Collection<Valve>, private val startValve: Valve) {
private val tunnelGraph: Graph<Valve>
private val valvePathGraph: Graph<Valve>
init {
val tunnels = valves.flatMap { it.getReachableValves().map { other -> it to other } }.toSet()
tunnelGraph = Graph(tunnels)
val workingValves = valves.filter { it.flowRate > 0 }
val pathsBetweenVertices = (workingValves + startValve).flatMap { from ->
workingValves.filter { it != from }
.map { to -> Edge(from, to, tunnelGraph.findShortestPath(from, to).size) }
.filter { it.weight > 0 }
}
valvePathGraph = Graph(pathsBetweenVertices)
}
fun calculateMaximumPressureRelease(): Int {
val valvesWithoutStartValve = valvePathGraph.vertices() - startValve
return allFeasibleValvePaths(valvesWithoutStartValve, 30)
.map { (valvePathWithoutStartValve, _) -> valvePathWithoutStartValve.calculateReleasedPressure(30) }
.max()
}
private fun allFeasibleValvePaths(
valvesWithoutStartValve: Set<Valve>,
timeLimit: Int
): Sequence<Pair<ValvePath, ValveSet>> =
valvesWithoutStartValve.permutations { valves ->
toValvePathEdges(valves).sumOf { edge -> edge.weight + 1 } > timeLimit
}.filter { it.first.isNotEmpty() }
.map { ValvePath(it.first) to ValveSet.from(it.second) }
private inner class ValvePath(private val valves: List<Valve>) {
private val code = valves.joinToString("|") { it.name }
val size = valves.size
fun toValveSet() = ValveSet.from(valves.toSet())
fun calculateReleasedPressure(timeLimit: Int): Int {
var timeLeft = timeLimit
return toValvePathEdges(valves).sumOf { edge ->
timeLeft -= edge.weight + 1
timeLeft * edge.to.flowRate
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ValvePath) return false
if (code != other.code) return false
return true
}
override fun hashCode(): Int {
return code.hashCode()
}
override fun toString() = code
}
class ValveSet private constructor(private val valves: Set<Valve>) {
private val code = encode(valves)
fun subsets() = valves.subsets().map { from(it) }
val size = valves.size
override fun toString() = code
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ValveSet) return false
if (code != other.code) return false
return true
}
override fun hashCode(): Int {
return code.hashCode()
}
companion object {
private val cache = mutableMapOf<String, ValveSet>()
fun from(valves: Set<Valve>): ValveSet {
return cache.getOrPut(encode(valves)) { ValveSet(valves) }
}
private fun encode(valves: Set<Valve>) =
valves.sortedBy { it.name }.joinToString("|") { it.name }
}
}
private fun toValvePathEdges(valves: List<Valve>) = valvePathGraph.toPath(listOf(startValve) + valves)
fun calculateMaximumPressureReleaseWithHelp(): Int {
val valvesWithoutStartValve = valvePathGraph.vertices() - startValve
val allPathsAndTheirComplements = allFeasibleValvePaths(valvesWithoutStartValve, 26).toList()
val pathPressureMap =
allPathsAndTheirComplements
.map { it.first }
.associateWith { path -> path.calculateReleasedPressure(26) }
val numberOfValvesWithoutTheStartValve = valvesWithoutStartValve.size
val valveSubsetToMaximumPressureForAllPathsInComplementMap =
valveSubsetToMaximumPressureForAllPathsInComplementMap(
allPathsAndTheirComplements,
numberOfValvesWithoutTheStartValve,
pathPressureMap
)
val nonFullPathPressures =
pathPressureMap.filter { (path, _) -> path.size <= numberOfValvesWithoutTheStartValve / 2 }.asSequence()
return nonFullPathPressures
.map { (path, pressure) -> path.toValveSet() to pressure }
.map { (valveSet, pressure) ->
val otherPressure = (valveSubsetToMaximumPressureForAllPathsInComplementMap[valveSet]
?: throw IllegalStateException("No maximum pressure for paths in complement calculated for subset $valveSet."))
otherPressure + pressure
}.max()
}
private fun valveSubsetToMaximumPressureForAllPathsInComplementMap(
allPathsAndTheirComplements: List<Pair<ValvePath, ValveSet>>,
numberOfValvesWithoutTheStartValve: Int,
pathPressureMap: Map<ValvePath, Int>
): Map<ValveSet, Int> {
// here we get a map from subsets of valves to all paths that contain ALL remaining valves
// in the next step, for each subset, we have to multiply its paths to all subsets of the subset
val valveSubsetToFullPathsInComplementMap = allPathsAndTheirComplements.groupBy({ it.second }) { it.first }
return allValveSubsetToAllPathsInComplement(
valveSubsetToFullPathsInComplementMap,
numberOfValvesWithoutTheStartValve
).mapValues { (_, encodedPaths) -> maximumPressure(encodedPaths, pathPressureMap) }
}
// we only have to consider paths of at most half the maximum length for the elephant path, since we get
// the other combinations by symmetry
private fun allValveSubsetToAllPathsInComplement(
valveSubsetToFullPathsInComplementMap: Map<ValveSet, List<ValvePath>>,
numberOfValvesWithoutTheStartValve: Int
) = valveSubsetToFullPathsInComplementMap
.flatMap { (valveSet, paths) ->
valveSet
.subsets()
.filter { it.size in 1..numberOfValvesWithoutTheStartValve / 2 }
.map { it to paths }
}.groupBy({ it.first }) { it.second }
.mapValues { it.value.flatten() }
private fun maximumPressure(
encodedPaths: List<ValvePath>,
pathPressureMap: Map<ValvePath, Int>
) = encodedPaths.maxOfOrNull {
pathPressureMap[it] ?: throw IllegalStateException("No pressure for path $it calculated.")
} ?: 0
companion object {
private val valveAndTunnelsRegex = Regex("(.*?); tunnels* leads* to valves* (.*)")
fun parseFrom(input: List<String>, startValveName: String): Volcano {
val valvesToConnectedValveNamesMap =
input.mapNotNull(valveAndTunnelsRegex::matchEntire).associate(::valveToConnectedValveNames)
val valveNameToValveMap = valvesToConnectedValveNamesMap.keys.associateBy { it.name }
makeValveConnections(valvesToConnectedValveNamesMap, valveNameToValveMap)
val startValve = valveNameToValveMap[startValveName]
?: throw NoSuchElementException("There is no start valve $startValveName.")
return Volcano(valvesToConnectedValveNamesMap.keys, startValve)
}
private fun makeValveConnections(
valvesToConnectedValveNamesMap: Map<Valve, List<String>>, valveNameToValveMap: Map<String, Valve>
) {
valvesToConnectedValveNamesMap.mapValues { (_, names) ->
names.map {
valveNameToValveMap[it] ?: throw IllegalArgumentException("Tunnel to unknown valve $it.")
}
}.forEach { (valve, connectedValves) ->
valve.addReachableValves(connectedValves)
}
}
private fun valveToConnectedValveNames(result: MatchResult): Pair<Valve, List<String>> {
val (valveString, tunnelEndpointsString) = result.destructured
val valve = Valve.parseFrom(valveString)
val connectedValveNames = tunnelEndpointsString.split(",").map(String::trim)
return valve to connectedValveNames
}
}
}
fun main() {
val input = readInputLines(Volcano::class)
println("The most pressure you can release alone is ${part1(input)}.")
println("The most pressure you can release with the help of an elephant is ${part2(input)}.")
}
fun part1(input: List<String>): Int {
return Volcano.parseFrom(input, "AA").calculateMaximumPressureRelease()
}
fun part2(input: List<String>): Int {
return Volcano.parseFrom(input, "AA").calculateMaximumPressureReleaseWithHelp()
} | 0 | Kotlin | 0 | 0 | 551069a21a45690c80c8d96bce3bb095b5982bf0 | 10,215 | advent-of-code-2022 | Apache License 2.0 |
Kotlin/src/ThreeSum.kt | TonnyL | 106,459,115 | false | null | /**
* Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
* Find all unique triplets in the array which gives the sum of zero.
*
* Note: The solution set must not contain duplicate triplets.
*
* For example, given array S = [-1, 0, 1, 2, -1, -4],
*
* A solution set is:
* [
* [-1, 0, 1],
* [-1, -1, 2]
* ]
*
* Accepted.
*/
class ThreeSum {
fun threeSum(nums: IntArray): List<List<Int>> {
nums.sort()
val set = mutableSetOf<Triple>()
for (first in 0 until nums.size - 2) {
if (nums[first] > 0) {
break
}
val target = 0 - nums[first]
var second = first + 1
var third = nums.size - 1
while (second < third) {
when {
nums[second] + nums[third] == target -> {
set.add(Triple(nums[first], nums[second], nums[third]))
while (second < third && nums[second] == nums[second + 1]) {
second++
}
while (second < third && nums[third] == nums[third - 1]) {
third--
}
second++
third--
}
nums[second] + nums[third] < target -> second++
else -> third--
}
}
}
return mutableListOf<List<Int>>().apply {
addAll(set.map { arrayListOf(it.a, it.b, it.c) })
}
}
internal data class Triple(
val a: Int,
val b: Int,
val c: Int
)
}
| 1 | Swift | 22 | 189 | 39f85cdedaaf5b85f7ce842ecef975301fc974cf | 1,711 | Windary | MIT License |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day21/Day21.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day21
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.toPair
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 21](https://adventofcode.com/2020/day/21)
*/
object Day21 : DayOf2020(21) {
override fun first(): Any? {
val foods = lines
.map { it.replace("(", "").replace(")", "").replace(",", "") }
.map { it.split("contains").toPair() }
.map { it.first.trim().split(" ").toSet() to it.second.trim().split(" ").toSet() }
val allItems = foods.flatMap { it.first }.toSet()
val possible = foods
.flatMap { (items, allergens) ->
allergens.map { it to items }
}
.groupBy { it.first }
.mapValues {
it.value.map { mapping -> mapping.second }
.fold(allItems) { acc, value -> acc.intersect(value) }
.toMutableSet()
}
.toMutableMap()
val finalAllergens = mutableMapOf<String, String>()
while (possible.isNotEmpty()) {
val toRemove = possible.filterValues { it.size == 1 }.mapValues { it.value.first() }
val removedItems = toRemove.map { it.value }.toSet()
finalAllergens += toRemove
possible -= toRemove.keys
possible.forEach {
it.value -= removedItems
}
}
val badItems = finalAllergens.values.toSet()
val safeItems = allItems - badItems
return foods
.flatMap { it.first }
.count { it in safeItems }
}
override fun second(): Any? {
val foods = lines
.map { it.replace("(", "").replace(")", "").replace(",", "") }
.map { it.split("contains").toPair() }
.map { it.first.trim().split(" ").toSet() to it.second.trim().split(" ").toSet() }
val allItems = foods.flatMap { it.first }.toSet()
val possible = foods
.flatMap { (items, allergens) ->
allergens.map { it to items }
}
.groupBy { it.first }
.mapValues {
it.value.map { mapping -> mapping.second }
.fold(allItems) { acc, value -> acc.intersect(value) }
.toMutableSet()
}
.toMutableMap()
val finalAllergens = mutableMapOf<String, String>()
while (possible.isNotEmpty()) {
val toRemove = possible.filterValues { it.size == 1 }.mapValues { it.value.first() }
val removedItems = toRemove.map { it.value }.toSet()
finalAllergens += toRemove
possible -= toRemove.keys
possible.forEach {
it.value -= removedItems
}
}
return finalAllergens
.toList()
.sortedBy { it.first }
.joinToString(",") { it.second }
}
}
fun main() = SomeDay.mainify(Day21)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,625 | adventofcode | MIT License |
src/main/kotlin/com/jacobhyphenated/advent2023/day11/Day11.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day11
import com.jacobhyphenated.advent2023.Day
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
/**
* Day 11: Cosmic Expansion
*
* The puzzle input is a representation of observed galaxies in space.
* However, all rows with no galaxies and all columns with no galaxies undergo expansion and are larger than they appear
*/
class Day11: Day<List<List<Char>>> {
override fun getInput(): List<List<Char>> {
return readInputFile("11").lines().map { it.toCharArray().toList() }
}
/**
* Part 1: Each fully blank row is actually 2 blank rows. Same with columns.
*
* Given that, what is the total distance between every galaxy?
* Distance is calculated by moving only up/down, left/right (manhattan distance)
*
* Calculate the distance between galaxies in any order, but don't repeat
*/
override fun part1(input: List<List<Char>>): Int {
// first, find the blank rows and columns that will undergo "expansion"
val blankRows = input.indices.filter { row -> input[row].all { it == '.' } }
val blankCols = input[0].indices.filter { col -> input.indices.all { row -> input[row][col] == '.' } }
// build a new "universe" by doubling the blank rows and columns
val expandedUniverse = input.flatMapIndexed { r, row ->
val expanded = row.flatMapIndexed{ c, value -> if (c in blankCols) { listOf(value, '.') } else { listOf(value) } }
if (r in blankRows) {
listOf(expanded, expanded)
} else {
listOf(expanded)
}
}
// now find the location of each galaxy in the expanded universe
val galaxies = expandedUniverse.indices
.flatMap { r -> expandedUniverse[r].indices.map { c ->
if(expandedUniverse[r][c] == '#') {
Pair(r,c)
} else {
null
}
}}.filterNotNull()
var sum = 0
for (i in galaxies.indices) {
for (j in i until galaxies.size) {
sum += calcManhattanDistance(galaxies[i], galaxies[j])
}
}
return sum
}
/**
* Part 2: Rather than doubling the blank rows and columns, each one expands by 1 Million.
*/
override fun part2(input: List<List<Char>>): Long {
// For this, we don't worry about modifying the universe. Keep the original shape
val blankRows = input.indices.filter { row -> input[row].all { it == '.' } }
val blankCols = input[0].indices.filter { col -> input.indices.all { row -> input[row][col] == '.' } }
val galaxies = input.indices
.flatMap { r -> input[r].indices.map { c ->
if(input[r][c] == '#') {
Pair(r,c)
} else {
null
}
}}.filterNotNull()
var sum = 0L
for (i in galaxies.indices) {
for (j in i until galaxies.size) {
sum += calcDistanceAccountingForExpansion(galaxies[i], galaxies[j], blankRows, blankCols, 1_000_000)
}
}
return sum
}
/** for part 2, we modify our manhattan distance algorithm
* if a step crosses an expansion row or column, count that as [expansion] units instead of 1
* where expansion is 1,000,000 for part 2
*/
fun calcDistanceAccountingForExpansion(p1: Pair<Int,Int>,
p2: Pair<Int,Int>,
blankRows: List<Int>,
blankCols: List<Int>,
expansion: Long): Long {
val (r1, c1) = p1
val (r2, c2) = p2
val rowRange = min(r1, r2) .. max(r1, r2)
val colRange = min(c1, c2) .. max(c1, c2)
val expansionOverlap = rowRange.count { it in blankRows } + colRange.count { it in blankCols }
// just don't forget to subtract expansionOverlap to prevent double counting
return calcManhattanDistance(p1, p2).toLong() + expansionOverlap.toLong() * expansion - expansionOverlap
}
override fun warmup(input: List<List<Char>>) {
part2(input)
}
}
private fun calcManhattanDistance(p1: Pair<Int,Int>, p2: Pair<Int,Int>): Int {
val (x1,y1) = p1
val (x2, y2) = p2
return (x1 - x2).absoluteValue + (y1 - y2).absoluteValue
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
Day11().run()
} | 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 4,255 | advent2023 | The Unlicense |
src/day02/Day02.kt | iulianpopescu | 572,832,973 | false | {"Kotlin": 30777} | package day02
import readInput
import kotlin.IllegalArgumentException
import kotlin.IllegalStateException
import kotlin.Int
import kotlin.String
import kotlin.check
import kotlin.to
private const val DAY = "02"
private const val DAY_TEST = "day${DAY}/Day${DAY}_test"
private const val DAY_INPUT = "day${DAY}/Day${DAY}"
fun main() {
fun part1(input: List<String>) = input.map {
val shapes = it.split(' ')
shapes[0].toShape() to shapes[1].toShape()
}.fold(0) { total, (opponent, player) ->
total + opponent.match(player).points + player.points
}
fun part2(input: List<String>) = input.map {
val shapes = it.split(' ')
shapes[0].toShape() to shapes[1].toResult()
}.fold(0) { total, (opponent, desiredResult) ->
val options = listOf(Shape.PAPER, Shape.ROCK, Shape.SCISSORS)
val player = options.find {
opponent.match(it) == desiredResult
} ?: throw IllegalStateException("Can't find match that satisfies the result")
total + desiredResult.points + player.points
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(DAY_TEST)
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput(DAY_INPUT)
println(part1(input))
println(part2(input))
}
private sealed class Shape(val points: Int) {
object ROCK : Shape(1)
object PAPER : Shape(2)
object SCISSORS : Shape(3)
/**
* Compares two shapes with normal rules of the game
*/
private fun compareTo(other: Shape): Result {
return when (this) {
PAPER -> when (other) {
PAPER -> Result.DRAW
ROCK -> Result.WIN
SCISSORS -> Result.LOSE
}
ROCK -> when (other) {
PAPER -> Result.LOSE
ROCK -> Result.DRAW
SCISSORS -> Result.WIN
}
SCISSORS -> when (other) {
PAPER -> Result.WIN
ROCK -> Result.LOSE
SCISSORS -> Result.DRAW
}
}
}
/**
* "Battles" one shape with another one and returns the result of the match
*/
fun match(player: Shape) = player.compareTo(this)
}
private enum class Result(val points: Int) {
WIN(6),
DRAW(3),
LOSE(0)
}
private fun String.toResult() = when (this) {
"X" -> Result.LOSE
"Y" -> Result.DRAW
"Z" -> Result.WIN
else -> throw IllegalArgumentException("Input value not supported")
}
private fun String.toShape() = when (this) {
"A", "X" -> Shape.ROCK
"B", "Y" -> Shape.PAPER
"C", "Z" -> Shape.SCISSORS
else -> throw IllegalArgumentException("Input value not supported")
} | 0 | Kotlin | 0 | 0 | 4ff5afb730d8bc074eb57650521a03961f86bc95 | 2,770 | AOC2022 | Apache License 2.0 |
src/Day14.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | import kotlin.streams.toList
fun main() {
fun part1(input: Pair<String, Map<String, String>>): Int {
val map = input.second
var str = input.first
for (round in 1..10) {
var nextStr = ""
for (i in str.indices) {
nextStr += str[i]
if (i == str.indices.last) {
continue
}
val k = str.slice(i..i + 1)
if (map.containsKey(k)) {
nextStr += map[k]
}
}
str = nextStr
}
val countmap = HashMap<Char, Int>()
str.forEach {
countmap[it] = if (countmap.containsKey(it)) countmap[it]!! + 1 else 1
}
return countmap.maxOf { it.value } - countmap.minOf { it.value }
}
// fun rLsys(str: String, rules: Map<String, String>, remainingIterations: Int): String {
//
// }
fun part2(input: Pair<String, Map<String, String>>): Long {
val map = input.second
val strRules = map.mapValues {
var str = it.key[0] + it.value + it.key[1]
for (round in 1..11) {
var nextStr = ""
for (i in str.indices) {
nextStr += str[i]
if (i == str.indices.last) {
continue
}
val k = str.slice(i..i + 1)
if (map.containsKey(k)) {
nextStr += map[k]
}
}
// println("Round $round")
str = nextStr
}
str
}
val valRules = strRules.mapValues {
val str = it.value
val countmap = HashMap<Char, Long>()
str.removeSuffix(str.last().toString()).forEach { c ->
countmap[c] = if (countmap.containsKey(c)) countmap[c]!! + 1 else 1
}
countmap
}
val rules = strRules.mapValues {
val str = it.value
val totalMap = HashMap<Char, Long>()
for (i in str.indices) {
if (i == str.indices.last) {
continue
}
val k = str.slice(i..i + 1)
valRules[k]!!.forEach { it1 ->
totalMap[it1.key] = totalMap.getOrDefault(it1.key, 0) + it1.value
}
}
totalMap
}
var str = input.first
for (round in 1..16) {
var nextStr = ""
for (i in str.indices) {
nextStr += str[i]
if (i == str.indices.last) {
continue
}
val k = str.slice(i..i + 1)
if (map.containsKey(k)) {
nextStr += map[k]
}
}
// println("Round $round")
str = nextStr
}
val totalMap = HashMap<Char, Long>()
for (i in str.indices) {
if (i == str.indices.last) {
totalMap[str[i]] = totalMap[str[i]]!! + 1
continue
}
val k = str.slice(i..i + 1)
rules[k]!!.forEach {
totalMap[it.key] = totalMap.getOrDefault(it.key, 0) + it.value
}
}
return totalMap.maxOf { it.value } - totalMap.minOf { it.value }
}
fun preprocessing(input: String): Pair<String, Map<String, String>> {
val tmp = input.trim().split("\r\n\r\n")
val t = tmp[0]
val i = tmp[1].split("\r\n").associate {
val i = it.split(" -> ")
Pair(i[0], i[1])
}
return Pair(t, i)
}
val realInp = read_testInput("real14")
val testInp = read_testInput("test14")
// val testInp = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
// println("Test 1: ${part1(preprocessing(testInp))}")
// println("Real 1: ${part1(preprocessing(realInp))}")
// println("-----------")
println("Test 2: ${part2(preprocessing(testInp))}")
println("Want : 2188189693529")
println("Real 2: ${part2(preprocessing(realInp))}")
}
| 0 | Kotlin | 0 | 0 | 3e33ab078f8f5413fa659ec6c169cd2f99d0b374 | 4,238 | advent_of_code21_kotlin | Apache License 2.0 |
src/Day02/Day02.kt | rooksoto | 573,602,435 | false | {"Kotlin": 16098} | package Day02
import profile
import readInputActual
import readInputTest
private const val DAY = "Day02"
fun main() {
fun part1(
input: List<String>
): Int = toCharPairs(input)
.map(RPS::fromPairOfChars)
.sumOf(::evaluateMatchScore)
fun part2(
input: List<String>
): Int = toCharPairs(input)
.map { charPair ->
val opponentMove = RPS.fromChar(charPair.first)
Pair(opponentMove, opponentMove.desiredOutcome(charPair.second))
}.sumOf(::evaluateMatchScore)
val testInput = readInputTest(DAY)
val input = readInputActual(DAY)
check(part1(testInput) == 15)
profile(shouldLog = true) {
println("Part 1: ${part1(input)}")
} // Answer: 14264 @ 25ms
check(part2(testInput) == 12)
profile(shouldLog = true) {
println("Part 2: ${part2(input)}")
} // Answer: 12382 @ 7ms
}
private fun toCharPairs(
input: List<String>
): List<Pair<Char, Char>> = input.map { it.split(" ") }
.map { Pair(it.first().first(), it.last().first()) }
private fun evaluateMatchScore(
rpsPair: Pair<RPS, RPS>
): Int = RPS.evaluateWin(rpsPair) + RPS.evaluateExtraPoints(rpsPair.second)
sealed class RPS {
abstract val value: Int
abstract val beats: RPS
abstract val losesTo: RPS
infix fun beats(
other: RPS
): Boolean = other == beats
infix fun losesTo(
other: RPS
): Boolean = other == losesTo
fun desiredOutcome(
code: Char
): RPS = when (code) {
'X' -> this.beats
'Y' -> this
'Z' -> this.losesTo
else -> throw IllegalArgumentException("Invalid input: $code")
}
companion object {
fun fromChar(
input: Char
): RPS = when (input) {
'A', 'X' -> Rock
'B', 'Y' -> Paper
'C', 'Z' -> Scissors
else -> throw IllegalArgumentException("Invalid input: $input")
}
fun fromPairOfChars(
charPair: Pair<Char, Char>
): Pair<RPS, RPS> = Pair(fromChar(charPair.first), fromChar(charPair.second))
fun evaluateWin(
rpsPair: Pair<RPS, RPS>
) = when {
rpsPair.second beats rpsPair.first -> 6
rpsPair.second losesTo rpsPair.first -> 0
else -> 3
}
fun evaluateExtraPoints(
rps: RPS
) = when (rps) {
is Rock -> 1
is Paper -> 2
is Scissors -> 3
}
}
object Rock : RPS() {
override val value: Int = 1
override val beats: RPS = Scissors
override val losesTo: RPS = Paper
}
object Paper : RPS() {
override val value: Int = 2
override val beats: RPS = Rock
override val losesTo: RPS = Scissors
}
object Scissors : RPS() {
override val value: Int = 3
override val beats: RPS = Paper
override val losesTo: RPS = Rock
}
}
| 0 | Kotlin | 0 | 1 | 52093dbf0dc2f5f62f44a57aa3064d9b0b458583 | 2,980 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/github/walkmansit/aoc2020/Day09.kt | walkmansit | 317,479,715 | false | null | package github.walkmansit.aoc2020
class Day09(val input: List<String>, private val windowSize: Int) : DayAoc<Long, Long> {
private class SlidingWindow(val numbers: LongArray, val size: Int) {
private var window = 0 until size
private val summWeight: MutableMap<Long, Int> = mutableMapOf()
init {
for (i in 0..size - 2)
for (j in i + 1 until size) {
val sum = numbers[i] + numbers[j]
if (summWeight.containsKey(sum)) {
summWeight[sum] = summWeight[sum]!! + 1
} else
summWeight[sum] = 1
}
}
fun findWrongSum(): Long {
for (i in size until numbers.size) {
if (!summWeight.contains(numbers[i]))
return numbers[i]
else
moveWindow()
}
return -1L
}
fun findWeakness(target: Long): Long {
var left = 0
var right = 1
val list = mutableListOf(numbers[left], numbers[right])
var sum = list.sum()
while (sum != target) {
if (sum < target && right < numbers.size) {
sum += numbers[++right]
list.add(numbers[right])
} else if (sum > target && left < right) {
sum -= numbers[left++]
list.removeAt(0)
}
}
return list.max()!! + list.min()!!
}
fun moveWindow() {
val removeCandidate = numbers[window.first]
for (i in window.first + 1..window.last) {
val sum = removeCandidate + numbers[i]
// remove left from summs
if (summWeight.containsKey(sum)) {
val newCount = summWeight[sum]!! - 1
if (newCount == 0)
summWeight.remove(sum)
else
summWeight[sum] == newCount
}
// add right to sums
val newSumm = numbers[i] + numbers[window.last + 1]
if (summWeight.containsKey(newSumm)) {
summWeight[newSumm] = summWeight[newSumm]!! + 1
} else
summWeight[newSumm] = 1
}
window = window.first + 1..window.last + 1
}
}
override fun getResultPartOne(): Long {
return SlidingWindow(input.map { it.toLong() }.toLongArray(), windowSize).findWrongSum()
}
override fun getResultPartTwo(): Long {
val model = SlidingWindow(input.map { it.toLong() }.toLongArray(), windowSize)
val target = model.findWrongSum()
return model.findWeakness(target)
}
}
| 0 | Kotlin | 0 | 0 | 9c005ac4513119ebb6527c01b8f56ec8fd01c9ae | 2,860 | AdventOfCode2020 | MIT License |
src/main/kotlin/day17_trick_shot/TrickShot.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day17_trick_shot
import geom2d.Point
import geom2d.Rect
import util.countForever
import kotlin.math.abs
/**
* More analysis; no code required. The probe has to go up and then come back
* down at the same rate (the `y` velocity changes at a constant rate). Thus,
* the target area's bottom y-coordinate is all you need to know.
*
* Like Seven Segment Search (#8), solving part one the expedient way appears
* valueless for part two. Not true, however. Part one's answer is one of the
* bounds for part two's search space. Finding the x-dimension's bound is
* different (it doesn't have a constant rate), but not _much_ different. An
* exhaustive search of this constrained domain is well within reach, though
* further constraining is possible.
*/
fun main() {
util.solve(11781, ::partOne)
util.solve(4531, ::partTwo)
}
data class Probe(val pos: Point, val vel: Point) {
constructor(dx: Long, dy: Long) : this(Point.ORIGIN, Point(dx, dy))
fun step() =
Probe(
Point(pos.x + vel.x, pos.y + vel.y),
Point(
vel.x.let {
when {
it == 0L -> 0
it < 0 -> it + 1
it > 0 -> it - 1
else -> throw IllegalStateException("Huh? $it is non-zero, non-negative, and non-positive?")
}
},
vel.y - 1
)
)
}
fun partOne(input: String) =
(1 until abs(input.toRect().y1)).sum()
// "target area: x=1..2, y=3..4" => Rect(1, 3, 2, 4)
fun String.toRect() =
split(":")[1]
.split(",")
.map { it.split("=")[1] }
.map { it.split("..").map(String::toLong) }
.let {
Rect(it[0][0], it[1][0], it[0][1], it[1][1])
}
fun partTwo(input: String): Int {
val target = input.toRect()
// this is the smallest possible dx (use for a final plummet)
val minDx = countForever()
.runningFold(Pair(0, 0)) { p, n ->
Pair(n, p.second + n)
}
.dropWhile { it.second < target.x1 }
.first()
.first
// this is the largest possible dy (a final plummet)
val maxDy = abs(target.y1) - 1
// every target area coord can be hit, so those are the other bounds...
return (minDx..target.x2).sumOf { dx ->
(target.y1..maxDy).count { dy ->
var curr = Probe(dx, dy)
while (true) {
curr = curr.step()
if (target.contains(curr.pos)) {
// we hit it!
return@count true
}
if (curr.pos.x > target.x2 || curr.pos.y < target.y1) {
// we're past it
return@count false
}
}
// Kotlin refuses to compile without this unreachable code?!
@Suppress("UNREACHABLE_CODE", "ThrowableNotThrown")
throw IllegalStateException("Never to to/past target area?")
}
}
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 3,041 | aoc-2021 | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day265/day265.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day265
// day265.kt
// By <NAME>, 2019.
import kotlin.math.max
typealias LOC = Int
typealias Bonus = Int
typealias LOCWithBonus = Pair<LOC, Bonus>
/**
* Calculate the bonus based on LOC of your neighbours.
* If you have written more LOC than your neighbours, you should receive the minimal amount more bonus than they do.
* This is a messy functional solution: the solution is much easier allowing for mutability and loops.
*/
fun calculateBonus(locs: List<LOC>): List<Bonus> {
if (locs.isEmpty()) return emptyList()
// Make a left-to-right pass, with the first bonus set to 1, and subsequent bonuses set to prev + 1 if their
// loc is greater. If it is equal, maintain it. If it is less, leave it at 1.
val withBonus: List<LOCWithBonus> = locs.fold(emptyList()){ acc, loc2 ->
if (acc.isEmpty()) listOf(LOCWithBonus(loc2, 1))
else {
val (loc1, bonus) = acc.last()
acc + LOCWithBonus(
loc2, when {
loc2 > loc1 -> bonus + 1
loc2 == loc1 -> bonus
else -> 1
}
)
}
}
// Now make a right-to-left pass, but limit the bonus to the maximum of the current value and the right
// neighbour + 1 so that we don't allow any reductions.
return withBonus.foldRight(emptyList<LOCWithBonus>()){ locWithBonus1, acc ->
if (acc.isEmpty()) listOf(locWithBonus1)
else {
val (loc1, bonus1) = locWithBonus1
val (loc2, bonus2) = acc.first()
listOf(LOCWithBonus(
loc1, when {
loc1 > loc2 -> max(bonus1, bonus2 + 1)
loc2 == loc1 -> bonus1
else -> bonus1
}
)) + acc
}
}.unzip().second
}
fun calculateBonusMutable(locs: List<LOC>): List<Bonus> {
if (locs.isEmpty()) return emptyList()
// Initialize all bonuses to 1.
val bonuses = MutableList(locs.size){1}
// Iterate left-to-right, making sure the bonus of an employee is larger than its neighbour if the employee
// has written more LOC.
for (i in (1 until locs.size)) {
bonuses[i] = when {
locs[i] > locs[i-1] -> bonuses[i-1] + 1
locs[i] == locs[i-1] -> bonuses[i-1]
else -> 1
}
}
// Now iterate from right-to-left, making sure the same condition holds.
// We must take the max with the existing value to not violate what we calculated on the left-to-right pass.
for (i in (locs.size - 2 downTo 0)) {
bonuses[i] = when {
locs[i] > locs[i+1] -> max(bonuses[i], bonuses[i+1] + 1)
locs[i] == locs[i+1] -> bonuses[i]
else -> bonuses[i]
}
}
return bonuses
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 2,819 | daily-coding-problem | MIT License |
src/main/kotlin/dev/kosmx/aoc23/differential/OhMoarMath.kt | KosmX | 726,056,762 | false | {"Kotlin": 32011} | package dev.kosmx.aoc23.differential
import kotlin.math.*
// It's beautiful how mathematical functions can be written down in functional programming :D
fun distance(totalTime: Int, buttonPress: Int): Int = (totalTime - buttonPress) * buttonPress // travel time times speed
// -(buttonPress^2) + totalTime*buttonPress
// dl/dp -- differentiated by buttonPress
fun dDistance(totalTime: Int, buttonPress: Int) = 2*buttonPress - totalTime
// this one is quite useless
// quadratic solution
// val x = buttonPress
// x^2 - totalTime*x + equals
fun zeroOfDistanceMinusTravel(totalTime: Double, equals: Double): Pair<Double, Double> {
val discriminant = sqrt(totalTime * totalTime - 4 * equals) // -4ac => -4*1*-equals
return (totalTime + discriminant)/2 to (totalTime - discriminant)/2
}
fun main() {
// This input is simple, I don't see its necessary to use files
val input = """
Time: 7 15 30
Distance: 9 40 200
""".trimIndent().lines()
val races = run {
val times = input[0].split(" ").asSequence().mapNotNull { it.toLongOrNull() }.toList()
val distances = input[1].split(" ").asSequence().mapNotNull { it.toLongOrNull() }.toList()
times.indices.map { times[it] to distances[it] }
}
races.fold(1L) { acc, (time, distance) ->
val solutions = zeroOfDistanceMinusTravel(time.toDouble(), distance.toDouble())
val margin = (solutions.first.nextDown().toLong() - (solutions.second.toLong()))
println("solutions: $solutions margin: $margin")
acc * margin
}.let {
println("part1: $it")
}
// for part2, just remove spaces
}
| 0 | Kotlin | 0 | 0 | ad01ab8e9b8782d15928a7475bbbc5f69b2416c2 | 1,660 | advent-of-code23 | MIT License |
src/Day12.kt | sabercon | 648,989,596 | false | null | import kotlin.math.absoluteValue
fun main() {
val directions = listOf('E', 'N', 'W', 'S')
data class Position1(val east: Int = 0, val north: Int = 0, val direction: Char = 'E') {
fun move(action: Char, value: Int): Position1 = when (action) {
'E' -> copy(east = east + value)
'N' -> copy(north = north + value)
'W' -> copy(east = east - value)
'S' -> copy(north = north - value)
'L' -> copy(direction = directions[(directions.indexOf(direction) + value / 90).mod(4)])
'R' -> copy(direction = directions[(directions.indexOf(direction) - value / 90).mod(4)])
'F' -> move(direction, value)
else -> throw IllegalArgumentException("Unknown Action: $action")
}
fun distance() = east.absoluteValue + north.absoluteValue
}
data class Position2(val east: Int = 0, val north: Int = 0, val wpEast: Int = 10, val wyNorth: Int = 1) {
fun move(action: Char, value: Int): Position2 = when (action) {
'E' -> copy(wpEast = wpEast + value)
'N' -> copy(wyNorth = wyNorth + value)
'W' -> copy(wpEast = wpEast - value)
'S' -> copy(wyNorth = wyNorth - value)
'L' -> {
if (value == 0) this
else copy(wpEast = -wyNorth, wyNorth = wpEast).move('L', value - 90)
}
'R' -> {
if (value == 0) this
else copy(wpEast = wyNorth, wyNorth = -wpEast).move('R', value - 90)
}
'F' -> copy(east = east + wpEast * value, north = north + wyNorth * value)
else -> throw IllegalArgumentException("Unknown Action: $action")
}
fun distance() = east.absoluteValue + north.absoluteValue
}
val input = readLines("Day12").map { it[0] to it.drop(1).toInt() }
input.fold(Position1()) { position, (action, value) -> position.move(action, value) }.distance().println()
input.fold(Position2()) { position, (action, value) -> position.move(action, value) }.distance().println()
}
| 0 | Kotlin | 0 | 0 | 81b51f3779940dde46f3811b4d8a32a5bb4534c8 | 2,095 | advent-of-code-2020 | MIT License |
src/main/kotlin/Day04.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | fun main() {
fun part1(input: List<String>): Int {
var fullOverlaps = 0
for (pairLine in input) {
val pairs = pairLine.split(',')
val firstElf = pairs[0]
val secondElf = pairs[1]
val firstElfRange = firstElf.split('-')
val firstElfStart = firstElfRange[0].toInt()
val firstElfEnd = firstElfRange[1].toInt()
val secondElfRange = secondElf.split('-')
val secondElfStart = secondElfRange[0].toInt()
val secondElfEnd = secondElfRange[1].toInt()
val firstContainedInSecond = firstElfStart >= secondElfStart && firstElfEnd <= secondElfEnd
val secondContainedInFirst = firstElfStart <= secondElfStart && firstElfEnd >= secondElfEnd
if (firstContainedInSecond || secondContainedInFirst) {
fullOverlaps++
}
}
return fullOverlaps
}
fun part2(input: List<String>): Int {
var overlaps = 0
for (pairLine in input) {
val pairs = pairLine.split(',')
val firstElf = pairs[0]
val secondElf = pairs[1]
val firstElfRange = firstElf.split('-')
val firstElfStart = firstElfRange[0].toInt()
val firstElfEnd = firstElfRange[1].toInt()
val secondElfRange = secondElf.split('-')
val secondElfStart = secondElfRange[0].toInt()
val secondElfEnd = secondElfRange[1].toInt()
val firstStartIsInSecondRange = firstElfStart in secondElfStart..secondElfEnd
val firstEndIsInSecondRange = firstElfEnd in secondElfStart..secondElfEnd
val secondStartIsInSecondRange = secondElfStart in firstElfStart..firstElfEnd
val secondEndIsInSecondRange = secondElfEnd in firstElfStart..firstElfEnd
if (firstStartIsInSecondRange || firstEndIsInSecondRange || secondStartIsInSecondRange || secondEndIsInSecondRange) {
overlaps++
}
}
return overlaps
}
val input = readFileAsList("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 2,160 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day16.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | val pattern16 = Regex("""Valve (.*) has flow rate=(\d+); tunnels? leads? to valves? (.*)""")
data class Node16(val name: String, val flowRate: Int, val edges: List<String>)
data class State16(val location: String, val timeLeft: Int, val open: Set<String>, val pressureReleased: Int)
interface PairGuy {
fun <E> get(pair: Pair<E, E>): E
fun <E> other(pair: Pair<E, E>): E
fun <E> set(pair: Pair<E, E>, value: E): Pair<E, E>
}
object FirstPairGuy: PairGuy {
override fun <E> get(pair: Pair<E, E>): E {
return pair.first
}
override fun <E> other(pair: Pair<E, E>): E {
return pair.second
}
override fun <E> set(pair: Pair<E, E>, value: E): Pair<E, E> {
return value to pair.second
}
}
object SecondPairGuy: PairGuy {
override fun <E> get(pair: Pair<E, E>): E {
return pair.second
}
override fun <E> other(pair: Pair<E, E>): E {
return pair.first
}
override fun <E> set(pair: Pair<E, E>, value: E): Pair<E, E> {
return pair.first to value
}
}
data class PairState16(
val location: Pair<String, String>,
val timeLeft: Pair<Int, Int>,
val open: Set<String>,
val pressureReleased: Int
)
fun main() {
fun parse(input: List<String>): Map<String, Node16> =
input.map { pattern16.matchEntire(it) ?: error("no match for $it") }
.map { it.groupValues }
.map { Node16(it[1], it[2].toInt(), it[3].split(", ")) }
.associateBy { it.name }
fun part1(input: List<String>): Int {
val nodes = parse(input)
val goodNodes = nodes.filter { it.value.flowRate > 0 }.keys
var bestScore = 0
val cache = mutableMapOf<Pair<String, String>, Int>()
val stack = ArrayDeque<State16>()
stack.add(State16("AA", 30, setOf(), 0))
while (stack.isNotEmpty()) {
val nextNode = stack.removeLast()
val from = nextNode.location
for (to in (goodNodes - nextNode.open)) {
val steps = cache[from to to] ?: bfs(
from,
next = { nodes[it]!!.edges.asSequence() },
found = { it == to })!!.steps
cache[from to to] = steps
val newTimeLeft = nextNode.timeLeft - steps
if (newTimeLeft > 0) {
val score = nextNode.pressureReleased + nodes[to]!!.flowRate * (newTimeLeft - 1)
stack.add(
State16(
to, newTimeLeft - 1, nextNode.open + setOf(to),
score
)
)
bestScore = max(score, bestScore)
}
}
}
return bestScore
}
fun part2(input: List<String>): Int {
val nodes = parse(input)
val goodNodes = nodes.filter { it.value.flowRate > 0 }.keys
var bestScore = 0
val cache = mutableMapOf<Pair<String, String>, Int>()
val stack = ArrayDeque<PairState16>()
val seen = mutableMapOf<Set<String>, Int>()
stack.add(PairState16("AA" to "AA", 26 to 26, setOf(), 0))
while (stack.isNotEmpty()) {
val nextNode = stack.removeLast()
if (nextNode.pressureReleased <= (seen[nextNode.open] ?: -1)) {
continue
} else {
seen[nextNode.open] = nextNode.pressureReleased
}
for (pairGuy in listOf(FirstPairGuy, SecondPairGuy)) {
val from = pairGuy.get(nextNode.location)
for (to in (goodNodes - nextNode.open)) {
val steps = cache[from to to] ?: bfs(
from,
next = { nodes[it]!!.edges.asSequence() },
found = { it == to })!!.steps
cache[from to to] = steps
val newTimeLeft = pairGuy.get(nextNode.timeLeft) - steps
if (newTimeLeft > 0) {
val score = nextNode.pressureReleased + nodes[to]!!.flowRate * (newTimeLeft - 1)
stack.add(
PairState16(
pairGuy.set(nextNode.location, to),
pairGuy.set(nextNode.timeLeft, newTimeLeft - 1),
nextNode.open + setOf(to),
score
)
)
bestScore = max(score, bestScore)
}
}
}
}
return bestScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
val input = readInput("Day16")
println(part1(input))
check(part2(testInput) == 1707)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 4,946 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch6/Problem65.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch6
/**
* Problem 65: Convergents Of E
*
* https://projecteuler.net/problem=65
*
* Goal: Find the sum of the digits in the numerator of the Nth convergent of the continued
* fraction of Euler's number, the mathematical constant e.
*
* Constraints: 1 <= N <= 3e4
*
* As seen in Problems 57 and 64, the infinite continued fraction of sqrt(2) can be written as [1;
* (2)], indicating that 2 repeats ad infinitum. The 1st 10 convergents of sqrt(2) are ->
* 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ...
*
* Euler's number, e, however can be written as:
*
* [2;1,2,1,1,4,1,1,6,1,...,1,2n,1,...], with its 1st 10 convergents being ->
*
* 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ...
*
*
* e.g.: N = 10
* 10th convergent of e = 1457/536
* sum = 1 + 4 + 5 + 7 = 17
*/
class ConvergentsOfE {
/**
* Solution based on the pattern observed for the numerator in the continued fraction
* representation:
*
* if n_1_1 = 2, n_1_2 = 3, n_1_3 = 8, with m_1_1 = 1, m_1_2 = 1, m_1_3 = 2, then
*
* 8 = 2 + 2 * 3, which continues for the sequences as ->
*
* n_i_j = n_i_j-2 + m_i_j * n_i_j-1
*/
fun nthConvergentDigitSum(n: Int): Int {
// represents [nI, nIMinus2, nIMinus1]
val numerators = arrayOf(0.toBigInteger(), 2.toBigInteger(), 3.toBigInteger())
for (i in 1 until n / 3 + 1) {
numerators[0] = 2.toBigInteger() * i.toBigInteger() * numerators[2] + numerators[1]
numerators[1] = numerators[0] + numerators[2]
numerators[2] = numerators[0] + numerators[1]
}
return numerators[n % 3].toString().sumOf(Char::digitToInt)
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 1,779 | project-euler-kotlin | MIT License |
src/day08.kt | skuhtic | 572,645,300 | false | {"Kotlin": 36109} | import kotlin.math.max
fun main() {
day08.execute(forceBothParts = true)
}
val day08 = object : Day<Int>(8, 21, 8) {
override val testInput: InputData
get() = """
30373
25512
65332
33549
35390
""".trimIndent().lines()
override fun part1(input: InputData): Int {
val trans = transposedInput(input)
val mapMaxIndex = input.size - 1
val visible = mutableSetOf<Pair<Int, Int>>()
(0..mapMaxIndex).forEach { c ->
visible.addAll(input[c].visibleIndexesFromOutside().map { it to c })
visible.addAll(input[c].reversed().visibleIndexesFromOutside().map { mapMaxIndex - it to c })
visible.addAll(trans[c].visibleIndexesFromOutside().map { c to it })
visible.addAll(trans[c].reversed().visibleIndexesFromOutside().map { c to mapMaxIndex - it })
}
return visible.count()
}
override fun part2(input: InputData): Int {
val trans = transposedInput(input)
val mapMaxIndex = input.size - 1
var maxScore = 0
(0..mapMaxIndex).forEach { x ->
(0..mapMaxIndex).forEach { y ->
val tl = input[y].visibleCountFromTree(x)
val tr = input[y].reversed().visibleCountFromTree(mapMaxIndex - x)
val td = trans[x].visibleCountFromTree(y)
val tu = trans[x].reversed().visibleCountFromTree(mapMaxIndex - y)
(tl * tr * td * tu).let {
maxScore = max(maxScore, it)
}
}
}
return maxScore
}
fun String.visibleCountFromTree(pos: Int): Int = drop(pos).visibleCountFromTree()
fun String.visibleCountFromTree(): Int {
if (length <= 1) return 0
val h = first()
val blocked = asSequence().drop(1).indexOfFirst { c -> c >= h } + 1
return if (blocked != 0) blocked else length - 1
}
fun String.visibleIndexesFromOutside(): Set<Int> {
return asSequence().drop(1)
.scanIndexed(0 to first()) { i, acc, c ->
if (c > acc.second) i + 1 to c else acc
}.map { it.first }.toSet()
}
fun transposedInput(input: InputData): List<String> {
require(input.size == input.first().length) { "Input is not a square" }
return input.map { it.toList() }.transposed().map { it.joinToString("") }
}
} | 0 | Kotlin | 0 | 0 | 8de2933df90259cf53c9cb190624d1fb18566868 | 2,443 | aoc-2022 | Apache License 2.0 |
src/main/year_2017/day11/day11.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package year_2017.day11
import kotlin.math.absoluteValue
import readInput
fun part1(input: List<String>): Int {
val directions = input.first().split(",")
val origin = HexPoint(0, 0, 0)
val endPoint = directions.fold(origin) { point, dir ->
point.step(dir)
}
return origin.distance(endPoint)
}
fun part2(input: List<String>): Int {
val directions = input.first().split(",")
val origin = HexPoint(0, 0, 0)
val steps = mutableListOf(origin)
directions.forEach { dir ->
steps.add(steps.last().step(dir))
}
return steps.maxOf { it.distance(origin) }
}
fun main() {
val input = readInput("main/year_2017/day11/Day11")
println(part1(input))
println(part2(input))
}
data class HexPoint(val x: Int, val y: Int, val z: Int) {
fun step(direction: String): HexPoint =
when (direction) {
"n" -> HexPoint(x, y + 1, z - 1)
"s" -> HexPoint(x, y - 1, z + 1)
"ne" -> HexPoint(x + 1, y, z - 1)
"nw" -> HexPoint(x - 1, y + 1, z)
"se" -> HexPoint(x + 1, y - 1, z)
"sw" -> HexPoint(x - 1, y, z + 1)
else -> error("illegal direction")
}
fun distance(other: HexPoint): Int =
maxOf(
(this.x - other.x).absoluteValue,
(this.y - other.y).absoluteValue,
(this.z - other.z).absoluteValue
)
} | 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 1,407 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc/Day05.kt | fluxxion82 | 573,716,300 | false | {"Kotlin": 39632} | package aoc
import java.io.File
import java.util.Stack
fun main() {
val testInput = File("src/Day05_test.txt").readText()
val input = File("src/Day05.txt").readText()
fun part1(input: String): String {
val splitInput = input.split("\n")
val crates = splitInput
.takeWhile { it.isNotEmpty() }
.dropLast(1)
.map {
it.chunked(4)
}
val stacks = crates
.maxBy { it.size }
.map {
Stack<String>()
}
crates.forEachIndexed { _, createRow ->
createRow.forEachIndexed { stackNumber, id ->
val crate = id.filter(Char::isLetter)
if (crate.isNotEmpty()) {
stacks.getOrNull(stackNumber)?.add(0, crate)
}
}
}
splitInput
.filter { it.startsWith("move") }
.forEach {
val amount = it.substringAfter("move ").substringBefore(" ")
val startStack = it.substringAfter("from ").substringBefore(" ").toInt()
val endStack = it.substringAfter("to ").substringBefore("\n").toInt()
for (i in 0 until amount.toInt()) {
val crate = stacks[startStack - 1].pop()
stacks[endStack - 1].push(crate)
}
}
return stacks.reversed().foldRight("") { stack, initial ->
"$initial${stack.lastElement()}"
}
}
fun part2(input: String): String {
val splitInput = input.split("\n")
val crates = splitInput
.takeWhile { it.isNotEmpty() }
.dropLast(1)
.map {
it.chunked(4)
}
val stacks = crates
.maxBy { it.size }
.map {
Stack<String>()
}
crates.forEachIndexed { _, createRow ->
createRow.forEachIndexed { stackNumber, id ->
val crate = id.filter(Char::isLetter)
if (crate.isNotEmpty()) {
stacks.getOrNull(stackNumber)?.add(0, crate)
}
}
}
splitInput
.filter { it.startsWith("move") }
.forEach {
val amount = it.substringAfter("move ").substringBefore(" ")
val startStack = it.substringAfter("from ").substringBefore(" ").toInt()
val endStack = it.substringAfter("to ").substringBefore("\n").toInt()
val tempCrates = mutableListOf<String>()
for (i in 0 until amount.toInt()) {
val crate = stacks[startStack - 1].pop()
tempCrates.add(crate)
}
tempCrates.reverse()
tempCrates.forEach { crate ->
stacks[endStack - 1].push(crate)
}
}
return stacks.reversed().foldRight("") { stack, initial ->
"$initial${stack.lastElement()}"
}
}
println("part one test: ${part1(testInput)}")
println("part one: ${part1(input)}")
println("part two test: ${part2(testInput)}")
println("part two: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 3920d2c3adfa83c1549a9137ffea477a9734a467 | 3,266 | advent-of-code-kotlin-22 | Apache License 2.0 |
src/day09/Day09.kt | Puju2496 | 576,611,911 | false | {"Kotlin": 46156} | package day09
import readInput
import java.util.*
import kotlin.math.abs
fun main() {
// test if implementation meets criteria from the description, like:
val input = readInput("src/day09", "Day09")
println("Part1")
part1(input)
println("Part2")
part2(input)
}
private fun part1(inputs: List<String>) {
val size = 4000
val visited: MutableList<Position> = mutableListOf()
var head = Position(size/2, size/2)
var tail = Position(size/2, size/2)
visited.add(tail)
inputs.forEach {
val direction = it.split(" ")
for (i in 0 until direction[1].toInt()) {
when(direction[0]) {
"L" -> {
head = head.copy(col = head.col - 1)
}
"R" -> {
head = head.copy(col = head.col + 1)
}
"U" -> {
head = head.copy(row = head.row - 1)
}
"D" -> {
head = head.copy(row = head.row + 1)
}
}
val rowDifference = tail.row - head.row
val colDifference = tail.col - head.col
if (abs(rowDifference) == 2 && abs(colDifference) == 1) {
val row = tail.row + if (rowDifference > 0) - 1 else + 1
tail = tail.copy(row = row, col = head.col)
}
else if (abs(colDifference) == 2 && abs(rowDifference) == 1) {
val col = tail.col + if (colDifference > 0) - 1 else + 1
tail = tail.copy(row = head.row, col = col)
}
else if (head.row == tail.row + 2) {
tail = tail.copy(row = tail.row + 1)
}
else if (head.row == tail.row - 2) {
tail = tail.copy(row = tail.row - 1)
}
else if (head.col == tail.col + 2) {
tail = tail.copy(col = tail.col + 1)
}
else if (head.col == tail.col - 2) {
tail = tail.copy(col = tail.col - 1)
}
if (!visited.contains(tail))
visited.add(tail)
}
}
println("tail - ${visited.size} - ${visited}")
}
private fun part2(inputs: List<String>) {
val size = 4000
val visited: MutableList<Position> = mutableListOf()
var head = Position(size/2, size/2)
val tail: MutableList<Position> = generateSequence { Position(size/2, size/2) }.take(9).toMutableList()
visited.add(tail[8])
inputs.forEach {
val direction = it.split(" ")
for (i in 0 until direction[1].toInt()) {
when (direction[0]) {
"L" -> head = head.copy(col = head.col - 1)
"R" -> head = head.copy(col = head.col + 1)
"U" -> head = head.copy(row = head.row - 1)
"D" -> head = head.copy(row = head.row + 1)
}
for (j in 0 until tail.size) {
val head1 = if (j == 0) head else tail[j-1]
val rowDifference = tail[j].row - head1.row
val colDifference = tail[j].col - head1.col
if (abs(rowDifference) == 2 && abs(colDifference) == 2) {
val row = tail[j].row + if (rowDifference > 0) - 1 else + 1
val col = tail[j].col + if (colDifference > 0) - 1 else + 1
tail[j] = Position(row, col)
} else if (abs(rowDifference) == 2 && abs(colDifference) == 1) {
val row = tail[j].row + if (rowDifference > 0) - 1 else + 1
tail[j] = Position(row, head1.col)
} else if (abs(colDifference) == 2 && abs(rowDifference) == 1) {
val col = tail[j].col + if (colDifference > 0) - 1 else + 1
tail[j] = Position(head1.row, col)
} else if (head1.row == tail[j].row + 2)
tail[j] = tail[j].copy(row = tail[j].row + 1)
else if (head1.row == tail[j].row - 2)
tail[j] = tail[j].copy(row = tail[j].row - 1)
else if (head1.col == tail[j].col + 2)
tail[j] = tail[j].copy(col = tail[j].col + 1)
else if (head1.col == tail[j].col - 2)
tail[j] = tail[j].copy(col = tail[j].col - 1)
}
if (!visited.contains(tail[8]))
visited.add(tail[8])
}
}
println("tail - ${visited.size} - $visited")
}
data class Position(val row: Int, val col: Int) | 0 | Kotlin | 0 | 0 | e04f89c67f6170441651a1fe2bd1f2448a2cf64e | 4,550 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/euclidea/Coincidences.kt | jedwidz | 589,137,278 | false | null | package euclidea
typealias Segment = Two<Point>
data class SegmentWithLine(val segment: Segment, val line: Element.Line?)
sealed class SegmentOrCircle {
data class Segment(val segment: euclidea.Segment) : SegmentOrCircle()
data class Circle(val circle: Element.Circle) : SegmentOrCircle()
}
data class Coincidences(
val distances: List<Pair<Double, List<SegmentOrCircle>>>,
val headings: List<Pair<Double, List<SegmentWithLine>>>,
val triangles: List<Pair<Three<Double>, List<Three<SegmentWithLine>>>>
)
fun EuclideaContext.coincidences(): Coincidences {
return Coincidences(
distances = distanceCoincidences(),
headings = headingCoincidences(),
triangles = triangleCoincidences()
)
}
private fun EuclideaContext.triangleCoincidences(): List<Pair<Three<Double>, List<Three<SegmentWithLine>>>> {
// Algorithm of complexity O(yikes!)
val triangles = points.triples().map { pointsTriple ->
val (a, b, c) = pointsTriple
val angles = threeFrom(listOf(angle(a, b, c), angle(b, a, c), angle(a, c, b)).sorted())
angles to pointsTriple
}
// Exclude degenerate triangles with three collinear points
.filter { !coincidesRough(it.first.third, 180.0) }
val contextLines = elements.filterIsInstance<Element.Line>()
fun contextLineFor(point1: Point, point2: Point): SegmentWithLine {
val contextLine = contextLines.firstOrNull { e ->
val line = Element.Line(point1, point2)
coincides(e, line)
}
return SegmentWithLine(point1 to point2, contextLine)
}
val res = mutableListOf<Pair<Three<Double>, List<Three<SegmentWithLine>>>>()
for ((angle1, triangles2) in coalesceOnCoincide(triangles) { it to it.first.first }) {
for ((angle2, triangles3) in coalesceOnCoincide(triangles2) { it to it.first.second }) {
for ((angle3, triangles4) in coalesceOnCoincide(triangles3) { it to it.first.third }) {
res.add(Triple(angle1, angle2, angle3) to triangles4.map { (_, points) ->
Triple(
contextLineFor(points.first, points.second),
contextLineFor(points.second, points.third),
contextLineFor(points.third, points.first),
)
})
}
}
}
return res
}
private fun EuclideaContext.distanceCoincidences(): List<Pair<Double, List<SegmentOrCircle>>> {
val contextCircles = elements.filterIsInstance<Element.Circle>()
fun matchesContextCircle(segment: Segment): Boolean {
fun matches(pointA: Point, pointB: Point): Boolean {
val circle = EuclideaTools.circleTool(pointA, pointB)
return contextCircles.any { coincides(it, circle) }
}
return matches(segment.first, segment.second) || matches(segment.second, segment.first) || matches(
midpoint(
segment.first,
segment.second
), segment.first
)
}
val segmentToMeasure =
points.pairs().map { pair -> pair to distance(pair.first, pair.second) }
.filter { !matchesContextCircle(it.first) }
val segmentOrCircleToMeasure = (segmentToMeasure.map { SegmentOrCircle.Segment(it.first) to it.second }
+ contextCircles.map { SegmentOrCircle.Circle(it) to it.radius }
+ contextCircles.map { SegmentOrCircle.Circle(it) to it.radius * 2.0 })
return coalesceOnCoincide(segmentOrCircleToMeasure) { it }
}
private fun EuclideaContext.headingCoincidences(): List<Pair<Double, List<SegmentWithLine>>> {
val res = mutableListOf<Pair<Double, List<SegmentWithLine>>>()
for ((heading, segments) in segmentCoincidences { segment -> heading(segment.first, segment.second) }) {
val filteredSegments = mutableListOf<SegmentWithLine>()
var remainingLines = segments.map { lineFor(it) }
while (remainingLines.isNotEmpty()) {
val line = remainingLines.first()
val contextLine = elements.filterIsInstance<Element.Line>().firstOrNull { e -> coincides(e, line) }
remainingLines = remainingLines.filter { !coincides(line, it) }
filteredSegments.add(SegmentWithLine(segmentFor(line), contextLine))
}
if (filteredSegments.size > 1)
res.add(heading to filteredSegments)
}
return res
}
fun lineFor(segment: Segment): Element.Line {
return Element.Line(segment.first, segment.second)
}
fun segmentFor(line: Element.Line): Segment {
return line.point1 to line.point2
}
private fun EuclideaContext.segmentCoincidences(measureFor: (Segment) -> Double): List<Pair<Double, List<Segment>>> {
return coalesceOnCoincide(points.pairs()) { it to measureFor(it) }
}
private fun <T, R> coalesceOnCoincide(
items: List<T>,
resultAndMeasureFor: (T) -> Pair<R, Double>
): List<Pair<Double, List<R>>> {
val itemToMeasure = items.map(resultAndMeasureFor).sortedBy { e -> e.second }
val res = mutableMapOf<Double, List<R>>()
val acc = mutableListOf<Pair<R, Double>>()
fun cut() {
if (acc.isNotEmpty()) {
val size = acc.size
if (size > 1) {
val middleMeasure = acc[size / 2].second
res[middleMeasure] = acc.map { it.first }
}
acc.clear()
}
}
var prevMeasure: Double? = null
for ((item, measure) in itemToMeasure) {
if (prevMeasure?.let { coincidesRough(it, measure) } == true)
acc.add(item to measure)
else cut()
prevMeasure = measure
}
cut()
return res.toList()
}
| 0 | Kotlin | 0 | 1 | 70f7a397bd6abd0dc0d6c295ba9625e6135b2167 | 5,682 | euclidea-solver | MIT License |
src/Day03.kt | rdbatch02 | 575,174,840 | false | {"Kotlin": 18925} | fun main() {
val items = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // I wonder if there's a slick way to do this, will check later
fun pointsOfItem(item: String): Int = items.indexOf(item) + 1
fun part1(input: List<String>): Int {
var totalPriority = 0
input.forEach {
val firstHalf = it.substring(0, it.length/2)
val secondHalf = it.removePrefix(firstHalf)
val dupes = firstHalf.filter { firstHalfItem -> secondHalf.contains(firstHalfItem) }.split("").distinct().joinToString("")
totalPriority += dupes.sumOf { dupe -> pointsOfItem(dupe.toString()) }
}
return totalPriority
}
fun part2(input: List<String>): Int {
val groups: MutableList<MutableList<String>> = mutableListOf(mutableListOf())
input.forEach { // Setup groups of 3
if (groups.last().size < 3) {
groups.last().add(it)
}
else {
groups.add(mutableListOf(it))
}
}
val priorityItem: List<String> = groups.map { group ->
group.first().find { item -> group[1].contains(item) && group[2].contains(item) }.toString()
}
return priorityItem.sumOf { pointsOfItem(it) }
}
val input = readInput("Day03")
println("Part 1 - " + part1(input))
println("Part 2 - " + part2(input))
}
| 0 | Kotlin | 0 | 1 | 330a112806536910bafe6b7083aa5de50165f017 | 1,402 | advent-of-code-kt-22 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day09.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import Point
import readInput
import kotlin.math.sign
fun main() {
/**
* Moves a rope along the given movements
*
* @param input the movement input
* @param knotSize the number of knots in this rope
* @return the unique positions the last knot visited during the rope movement
*/
fun moveRope(input: List<String>, knotSize: Int): Int {
val start = Point(0, 0)
val knots = Array(knotSize) { start }
val visitedPoints = mutableSetOf(start)
input.map { it.split(" ") }.forEach { (direction, distance) ->
repeat(distance.toInt()) {
knots[0] = when (direction) {
"U" -> knots[0].move(0, 1)
"D" -> knots[0].move(0, -1)
"L" -> knots[0].move(-1, 0)
"R" -> knots[0].move(1, 0)
else -> throw IllegalArgumentException("Unknown direction: $direction")
}
for (i in knots.indices.drop(1)) {
val isLastKnot = i == knots.size - 1
val previous = knots[i - 1]
val neighbours = previous.getNeighbours(true)
var knot = knots[i]
while (previous != knot && !neighbours.contains(knot)) {
knot = knot.move((previous.x - knot.x).sign, (previous.y - knot.y).sign)
if (isLastKnot) {
visitedPoints.add(knot)
}
}
knots[i] = knot
}
}
}
return visitedPoints.size
}
fun part1(input: List<String>) = moveRope(input, 2)
fun part2(input: List<String>) = moveRope(input, 10)
val testInput = readInput("Day09_test", 2022)
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent().split("\n")
check(part2(testInput2) == 36)
val input = readInput("Day09", 2022)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 2,192 | adventOfCode | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day19/Day19.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day19
import nl.sanderp.aoc.common.*
import java.util.*
fun main() {
val input = readResource("Day19.txt")
.split("\n\n")
.map { parse(it) }
.mapIndexed { i, b -> Scanner(i, Point3D(0, 0, 0), b) }
val scanners = locateScanners(input)
val beacons = scanners.flatMap { it.beaconsAbsolute }.toSet()
println("Part one: ${beacons.size}")
val distances = scanners.map { it.center }.allPairs().map { (s1, s2) -> s1.manhattanTo(s2) }
println("Part two: ${distances.maxOf { it }}")
}
private val orientations2 = listOf<Point3D.() -> Point3D>(
{ Point3D(+x, +y, +z) },
{ Point3D(+x, +z, -y) },
{ Point3D(+x, -y, -z) },
{ Point3D(+x, -z, +y) },
{ Point3D(+y, +x, -z) },
{ Point3D(+y, +z, +x) },
{ Point3D(+y, -x, +z) },
{ Point3D(+y, -z, -x) },
{ Point3D(+z, +x, +y) },
{ Point3D(+z, +y, -x) },
{ Point3D(+z, -x, -y) },
{ Point3D(+z, -y, +x) },
{ Point3D(-x, +y, -z) },
{ Point3D(-x, +z, +y) },
{ Point3D(-x, -y, +z) },
{ Point3D(-x, -z, -y) },
{ Point3D(-y, +x, +z) },
{ Point3D(-y, +z, -x) },
{ Point3D(-y, -x, -z) },
{ Point3D(-y, -z, +x) },
{ Point3D(-z, +x, -y) },
{ Point3D(-z, +y, +x) },
{ Point3D(-z, -x, +y) },
{ Point3D(-z, -y, -x) },
)
private data class Scanner(val id: Int, val center: Point3D, val beacons: List<Point3D>) {
val beaconsAbsolute = beacons.map { it + center }
val orientations by lazy {
orientations2.map { t -> this.copy(beacons = beacons.map(t)) }
}
}
private fun parse(block: String) = block.lines().drop(1).map { line ->
val (x, y, z) = line.split(',').map { it.toInt() }
Point3D(x, y, z)
}
private fun locateScanners(input: List<Scanner>) = buildList {
val queue = LinkedList<Scanner>()
val pending = input.drop(1).toMutableList()
add(input.first())
queue.push(input.first())
while (queue.isNotEmpty()) {
val located = queue.poll()
val matches = pending.mapNotNull { matchScanners(located, it) }
for (match in matches) {
print("#")
add(match)
queue.push(match)
pending.removeIf { it.id == match.id }
}
}
println()
if (pending.isNotEmpty()) {
throw Exception("Unable to locate scanners: ${pending.joinToString { it.id.toString() }}")
}
}
private fun matchScanners(a: Scanner, b: Scanner): Scanner? {
for (beaconA in a.beaconsAbsolute) {
for (orientationB in b.orientations) {
for (beaconB in orientationB.beaconsAbsolute) {
val translatedB = orientationB.copy(center = beaconA - beaconB)
if (a.beaconsAbsolute.intersect(translatedB.beaconsAbsolute.toSet()).size >= 12) {
return translatedB
}
}
}
}
return null
} | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 2,896 | advent-of-code | MIT License |
src/main/kotlin/day11/Day11.kt | dustinconrad | 572,737,903 | false | {"Kotlin": 100547} | package day11
import byEmptyLines
import readResourceAsBufferedReader
import java.math.BigInteger
import java.util.function.BinaryOperator
import java.util.function.UnaryOperator
fun main() {
println("part 1: ${part1(readResourceAsBufferedReader("11_1.txt").readLines())}")
println("part 2: ${part2(readResourceAsBufferedReader("11_1.txt").readLines())}")
}
fun part1(input: List<String>): Long {
val monkeys = input.byEmptyLines().map { parseMonkey(it) }
val middle = MonkeyInTheMiddle(monkeys)
repeat(20) { middle.round() }
val sorted = middle.monkeys.map { it.inspectCount.toLong() }.sortedDescending()
return sorted[0] * sorted[1]
}
fun part2(input: List<String>): Long {
val monkeys = input.byEmptyLines().map { parseMonkey(it) }
val middle = MonkeyInTheMiddle(monkeys, part2Worry(monkeys))
repeat(10_000) { middle.round() }
val sorted = middle.monkeys.map { it.inspectCount.toLong() }.sortedDescending()
return sorted[0] * sorted[1]
}
fun part2Worry(monkeys: List<Monkey>): UnaryOperator<BigInteger> {
val product = monkeys.map { it.tst }.reduce(BigInteger::times)
return UnaryOperator{ t -> t % product }
}
data class Operation(val l: String, val op: BinaryOperator<BigInteger>, val r: String) {
fun call(worry: BigInteger): BigInteger {
val left = if (l == "old") {
worry
} else {
l.toBigInteger()
}
val right = if (r == "old") {
worry
} else {
r.toBigInteger()
}
return op.apply(left, right)
}
companion object {
fun parse(line: String): Operation {
val parts = line.trim().split(Regex("\\s+"))
val l = parts[3]
val r = parts[5]
val op: (BigInteger, BigInteger) -> BigInteger = when(parts[4]) {
"*" -> { a, b -> a.times(b) }
"+" -> { a, b -> a.plus(b)}
"-" -> { a, b -> a.minus(b) }
else -> throw IllegalArgumentException("Unknown op: ${parts[4]}")
}
return Operation(l, op, r)
}
}
}
fun parseMonkey(monkey: String): Monkey {
val lines = monkey.lines()
val id = lines[0].trim().replace(":","", false).split(Regex("\\s+"))[1].toInt()
val start = lines[1].split(":")[1].split(",").map { it.trim() }.map { it.toBigInteger() }.toMutableList()
val op = Operation.parse(lines[2])
val test = lines[3].trim().split(Regex("\\s+")).last().toBigInteger()
val tr = lines[4].trim().split(Regex("\\s+")).last().toInt()
val fls = lines[5].trim().split(Regex("\\s+")).last().toInt()
return Monkey(id, start, op, test, tr, fls)
}
class Monkey(
val id: Int,
val items: MutableList<BigInteger>,
val op: Operation,
val tst: BigInteger,
val tBranch: Int,
val fBranch: Int,
) {
var inspectCount = 0
fun turn(worryFn: UnaryOperator<BigInteger>): Map<Int, List<BigInteger>> {
inspectCount += items.size
val result = items.map {
var newWorry = op.call(it)
newWorry = worryFn.apply(newWorry)
if (newWorry.mod(tst).compareTo(BigInteger.ZERO) == 0) {
tBranch to newWorry
} else {
fBranch to newWorry
}
}.groupBy({p -> p.first}, { p -> p.second })
items.clear()
return result
}
override fun toString(): String {
return "Monkey{$items}"
}
}
class MonkeyInTheMiddle(
val monkeys: List<Monkey>,
val worryFn: UnaryOperator<BigInteger> = UnaryOperator { t -> t.divide(BigInteger.valueOf(3L)) }
) {
fun state(): List<Int> {
return monkeys.map { it.inspectCount }
}
fun round() {
monkeys.forEach {
val turnResult = it.turn(worryFn)
turnResult.forEach { (m, w) ->
monkeys[m].items.addAll(w)
}
}
}
} | 0 | Kotlin | 0 | 0 | 1dae6d2790d7605ac3643356b207b36a34ad38be | 3,937 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/g1301_1400/s1301_number_of_paths_with_max_score/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1301_1400.s1301_number_of_paths_with_max_score
// #Hard #Array #Dynamic_Programming #Matrix
// #2023_06_05_Time_178_ms_(100.00%)_Space_37.8_MB_(100.00%)
class Solution {
fun pathsWithMaxScore(board: List<String>): IntArray {
val rows = board.size
val columns = board[0].length
val dp = Array(rows) { Array(columns) { IntArray(2) } }
for (r in rows - 1 downTo 0) {
for (c in columns - 1 downTo 0) {
val current = board[r][c]
if (current == 'S') {
dp[r][c][0] = 0
dp[r][c][1] = 1
} else if (current != 'X') {
var maxScore = 0
var paths = 0
val currentScore = if (current == 'E') 0 else current.code - '0'.code
for (dir in DIRECTIONS) {
val nextR = r + dir[0]
val nextC = c + dir[1]
if (nextR < rows && nextC < columns && dp[nextR][nextC][1] > 0) {
if (dp[nextR][nextC][0] + currentScore > maxScore) {
maxScore = dp[nextR][nextC][0] + currentScore
paths = dp[nextR][nextC][1]
} else if (dp[nextR][nextC][0] + currentScore == maxScore) {
paths = (paths + dp[nextR][nextC][1]) % 1000000007
}
}
}
dp[r][c][0] = maxScore
dp[r][c][1] = paths
}
}
}
return intArrayOf(dp[0][0][0], dp[0][0][1])
}
companion object {
private val DIRECTIONS = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(1, 1))
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,824 | LeetCode-in-Kotlin | MIT License |
src/Day05.kt | aaronbush | 571,776,335 | false | {"Kotlin": 34359} | fun main() {
data class MoveInstruction(val howMany: Int, val fromWhere: Int, val toWhere: Int)
fun String.toMoveInstruction(): MoveInstruction {
val (howMany, from, to) = this.split(" ").chunked(2).map { it.last().toInt() }
return MoveInstruction(howMany, from, to)
}
fun parseStacks(input: List<String>): MutableMap<Int, ArrayDeque<String>> {
val result = mutableMapOf<Int, ArrayDeque<String>>()
val stackPattern = "\\[([a-zA-Z])]".toRegex()
val stackLines = input.takeWhile { it.isNotEmpty() && !it.startsWith(" 1") } // up to the stack numbers
val stacks = stackLines.map {
it.chunked(4) // each stack is 4-chars '[A] ' (except for last - chunked still grabs it though as partial window)
}
stacks.map { stack ->
stack.mapIndexed { index, s ->
val currStack = result.getOrPut(index + 1) { ArrayDeque() }
stackPattern.matchEntire(s.trim())?.destructured
?.apply { currStack.addFirst(this.component1()) }
}
}
return result
}
fun ArrayDeque<String>.removeLast(n: Int): List<String> {
val result = mutableListOf<String>()
repeat(n) {
result += this.removeLast()
}
return result
}
fun ArrayDeque<String>.removeLastTogether(n: Int) = removeLast(n).reversed()
fun moveCrates(input: List<String>, f: (dq: ArrayDeque<String>, n: MoveInstruction) -> List<String>): String {
val stacks = parseStacks(input)
val moves = input.takeLastWhile { it.isNotBlank() }.map { it.toMoveInstruction() }
moves.forEach { move ->
val toMoveCrates = stacks[move.fromWhere]!!.let { f(it, move) }
stacks[move.toWhere]!!.addAll(toMoveCrates)
}
return stacks.values.joinToString(separator = "") { it.last() }
}
fun part1(input: List<String>) =
moveCrates(input) { d, m -> d.removeLast(m.howMany) }
fun part2(input: List<String>) =
moveCrates(input) { d, m -> d.removeLastTogether(m.howMany) }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println("p1: ${part1(input)}")
println("p2: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | d76106244dc7894967cb8ded52387bc4fcadbcde | 2,413 | aoc-2022-kotlin | Apache License 2.0 |
src/Day07/Day07.kt | kritanta | 574,453,685 | false | {"Kotlin": 8568} | import java.util.LinkedList
import java.util.zip.DataFormatException
enum class Command {
ls, cd
}
data class FileTree(val parent:FileTree?, val name: String, var size:Int = 0, val children:MutableList<FileTree> = mutableListOf())
fun main() {
fun buildFileTree(input: List<String>): MutableList<FileTree> {
val list : MutableList<FileTree> = mutableListOf()
list.add(FileTree(null, "/"))
var currentDir = list[0];
input.forEach { s ->
if (s[0] == '$') {
val command = Command.valueOf(s.substring(2..3))
when (command) {
Command.ls -> {
}
Command.cd -> {
val dir = s.substring(5)
currentDir = when (dir) {
"/" -> {
list[0];
}
".." -> {
currentDir.parent ?: list[0]
}
else -> {
val newDir = FileTree(currentDir, dir)
currentDir.children.add(newDir)
newDir
}
}
}
}
}
else if (s.substring(0..2) == "dir"){
}
else {
var fileline = s.split(' ')
val size = fileline[0].toInt()
currentDir.children.add(FileTree(currentDir, fileline[1], size))
// calculate parent sizes
var parent: FileTree? = currentDir;
while (parent != null){
parent.size += size;
parent = parent.parent;
}
}
}
return list;
}
fun GetSmallDirectories(files :List<FileTree>): MutableList<FileTree> {
val currentDirectories = mutableListOf<FileTree>();
files.forEach {
if(it.children.isNotEmpty()){
if(it.size <= 100000){
currentDirectories.add(it);
}
currentDirectories.addAll(GetSmallDirectories(it.children))
}
}
return currentDirectories;
}
fun GetBigEnoughDirectories(files :List<FileTree>, size: Int): FileTree {
var smallestDirectoryWithSpace: FileTree = FileTree(null, "blank", Int.MAX_VALUE);
files.forEach {
if(it.children.isNotEmpty()){
println("${it.name}, ${it.size}")
if(it.size >= size && it.size <= smallestDirectoryWithSpace.size){
smallestDirectoryWithSpace = it;
}
val smallestChild = GetBigEnoughDirectories(it.children, size)
if(smallestChild.size <= smallestDirectoryWithSpace.size){
smallestDirectoryWithSpace = smallestChild
}
}
}
return smallestDirectoryWithSpace;
}
fun part1(input: List<String>): Int {
val fileTree = buildFileTree(input)
return GetSmallDirectories(fileTree).sumOf { it.size };
}
fun part2(input: List<String>): String {
val fileTree = buildFileTree(input)
val totalSize = 70000000
val sizeOfUpdate = 30000000
val sizeNeeded = sizeOfUpdate - (totalSize - fileTree[0].size)
val dir = GetBigEnoughDirectories(fileTree, sizeNeeded);
return "${dir.name} - ${dir.size}"
}
fun mapDirs(files :FileTree): List<FileTree> {
return files.children + files.children.flatMap { mapDirs(it) }
}
fun part2_2(input: List<String>): String {
val fileTree = buildFileTree(input)
val totalSize = 70000000
val sizeOfUpdate = 30000000
val sizeNeeded = sizeOfUpdate - (totalSize - fileTree[0].size)
val dir = mapDirs(fileTree[0]).filter { it.children.isNotEmpty() && it.size >= sizeNeeded }.sortedBy { it.size }.first()
return "${dir.name} - ${dir.size}"
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07/Test")
println(part1(testInput))
//println(part2(testInput))
check(part1(testInput) == 95437)
check(part2(testInput) == "d")
val input = readInput("Day07/Main")
println(part1(input))
println(part2(input))
println(part2_2(input))
}
| 0 | Kotlin | 0 | 0 | 834259cf076d0bfaf3d2e06d1bc1d5df13cffd6c | 4,537 | AOC-2022-Kotlin | Apache License 2.0 |
src/Day11.kt | JIghtuse | 572,807,913 | false | {"Kotlin": 46764} | import java.lang.IllegalStateException
typealias WorryLevel = Long
typealias MonkeyIndex = Int
fun reduceOnRelief(level: WorryLevel): WorryLevel = level / 3
fun toOperation(s: String, modulo: Long): (WorryLevel) -> WorryLevel {
val parts = s
.substringAfter(" = ")
.split(" ")
val op = parts[1]
return when (parts[0] to parts[2]) {
"old" to "old" -> when (op) {
"+" -> { x: WorryLevel -> (x % modulo) + (x % modulo) }
"*" -> { x: WorryLevel -> (x % modulo) * (x % modulo) }
else -> throw IllegalStateException("unknown op $op")
}
"old" to parts[2] -> when (op) {
"+" -> { x: WorryLevel -> (x % modulo) + parts[2].toInt() }
"*" -> { x: WorryLevel -> (x % modulo) * parts[2].toInt() }
else -> throw IllegalStateException("unknown op $op")
}
else -> when (op) {
"+" -> { x: WorryLevel -> parts[0].toInt() + (x % modulo) }
"*" -> { x: WorryLevel -> parts[0].toInt() * (x % modulo) }
else -> throw IllegalStateException("unknown op $op")
}
}
}
fun parseLastWordNumber(s: String) = s.split(" ").last().toInt()
fun toTest(monkeyData: List<String>): (WorryLevel) -> MonkeyIndex {
val divisibleBy = parseLastWordNumber(monkeyData[3])
val trueIndex = parseLastWordNumber(monkeyData[4])
val falseIndex = parseLastWordNumber(monkeyData[5])
return { x: WorryLevel -> if (x % divisibleBy == 0L) trueIndex else falseIndex }
}
class Monkey(
var items: MutableList<WorryLevel>,
val operation: (WorryLevel) -> WorryLevel,
val test: (WorryLevel) -> MonkeyIndex,
private val modulo: Long) {
var itemsInspected = 0
fun makeTurnWithOperationPostprocess(
monkeys: List<Monkey>,
postprocess: (WorryLevel) -> WorryLevel) {
items.forEach {
itemsInspected++
val item = postprocess(operation(it))
val throwTo = test(item)
monkeys[throwTo].items.add(item)
}
items.clear()
}
fun makeTurn(monkeys: List<Monkey>) =
makeTurnWithOperationPostprocess(monkeys, ::reduceOnRelief)
fun makeTurnNoRelief(monkeys: List<Monkey>) =
makeTurnWithOperationPostprocess(monkeys) { it % modulo }
}
fun monkeyBusiness(monkeys: List<Monkey>): Long {
return monkeys
.toMutableList()
.sortedBy { it.itemsInspected }
.takeLast(2)
.map { it.itemsInspected.toLong() }
.reduce(Long::times)
}
fun runRounds(
monkeys: List<Monkey>,
roundsCount: Int,
turn: (Monkey, List<Monkey>) -> Unit): Long {
repeat(roundsCount) {
for (monkey in monkeys) {
turn(monkey, monkeys)
}
}
return monkeyBusiness(monkeys)
}
fun listItems(monkeys: List<Monkey>): String {
return monkeys
.flatMap { it.items }
.joinToString()
}
fun listInspections(monkeys: List<Monkey>): String {
return monkeys
.map { it.itemsInspected }
.joinToString()
}
fun parseMonkeys(input: String, modulo: Long): List<Monkey> {
return input
.split("\n\n")
.map { monkeyString ->
val lines = monkeyString.split("\n")
val items = lines[1]
.substringAfter(": ")
.split(", ")
.map { it.toLong() }
Monkey(
items.toMutableList(),
toOperation(lines[2], modulo),
toTest(lines),
modulo)
}
}
fun main() {
fun part1(input: String, modulo: Long): Long {
val monkeys = parseMonkeys(input, modulo)
return runRounds(monkeys, 20, Monkey::makeTurn)
}
fun part2(input: String, modulo: Long): Long {
val monkeys = parseMonkeys(input, modulo)
return runRounds(monkeys, 10_000, Monkey::makeTurnNoRelief)
}
// test if implementation meets criteria from the description, like:
val testInput = readText("Day11_test")
check(part1(testInput, 96577L) == 10605L)
check(part2(testInput, 96577L) == 2713310158)
val input = readText("Day11")
println(part1(input, 9699690L))
println(part2(input, 9699690L))
} | 0 | Kotlin | 0 | 0 | 8f33c74e14f30d476267ab3b046b5788a91c642b | 4,225 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day03/Day03.kt | cmargonis | 573,161,233 | false | {"Kotlin": 15730} | package day03
import readInput
private const val DIRECTORY = "./day03"
fun main() {
fun toCommons(it: String): Set<Char> {
val inter = it.chunked(it.length / 2)
return inter.first().toSet().intersect(inter[1].toSet())
}
fun toPriority(c: Char): Int {
val lowerCaseRange = 'a'..'z'
val upperCaseRange = 'A'..'Z'
return if (c in lowerCaseRange) lowerCaseRange.indexOf(c).plus(1)
else upperCaseRange.indexOf(c).plus(27)
}
fun findCommonsBetweenTwo(acc: String, v: String) = if (acc.isEmpty()) v else acc.filter { v.contains(it) }
fun findBadge(group: List<String>): Char = group
.runningReduce(::findCommonsBetweenTwo)
.last()
.first()
fun part1(input: List<String>): Int = input
.fold(0) { l: Int, r: String -> toCommons(r).sumOf { toPriority(it) } + l }
fun part2(input: List<String>): Int = input
.asSequence()
.chunked(3)
.map { toPriority(findBadge(it)) }
.sum()
val input = readInput("${DIRECTORY}/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd243c61bf8aae81daf9e50b2117450c4f39e18c | 1,120 | kotlin-advent-2022 | Apache License 2.0 |
2015/Day03/src/main/kotlin/Main.kt | mcrispim | 658,165,735 | false | null | import java.io.File
typealias Position = Pair<Int, Int>
fun main() {
fun part1(input: List<String>): Int {
var noelPosition = Position(0, 0)
val houses = mutableSetOf(noelPosition)
for (direction in input[0]) {
when (direction) {
'^' -> noelPosition = Position(noelPosition.first, noelPosition.second + 1)
'v' -> noelPosition = Position(noelPosition.first, noelPosition.second - 1)
'<' -> noelPosition = Position(noelPosition.first - 1, noelPosition.second)
'>' -> noelPosition = Position(noelPosition.first + 1, noelPosition.second)
else -> throw Exception("Unexpected direction: $direction")
}
houses.add(noelPosition)
}
return houses.size
}
fun part2(input: List<String>): Int {
fun changeDriver(driver: String) = if (driver == "noel") "robot" else "noel"
var driver = "noel"
var noelPosition = Position(0, 0)
var robotPosition = Position(0, 0)
val houses = mutableSetOf(noelPosition)
for (direction in input[0]) {
var position = if (driver == "noel") noelPosition else robotPosition
when (direction) {
'^' -> position = Position(position.first, position.second + 1)
'v' -> position = Position(position.first, position.second - 1)
'<' -> position = Position(position.first - 1, position.second)
'>' -> position = Position(position.first + 1, position.second)
else -> throw Exception("Unexpected direction: $direction")
}
houses.add(position)
if (driver == "noel") {
noelPosition = position
} else {
robotPosition = position
}
driver = changeDriver(driver)
}
return houses.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 4)
check(part2(testInput) == 3)
val input = readInput("Day03_data")
println("Part 1 answer: ${part1(input)}")
println("Part 2 answer: ${part2(input)}")
}
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
| 0 | Kotlin | 0 | 0 | 2f4be35e78a8a56fd1e078858f4965886dfcd7fd | 2,379 | AdventOfCode | MIT License |
src/PathUtils.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | import java.util.PriorityQueue
import kotlin.collections.ArrayDeque
fun <T> breadthFirstSearch(start: T, end: T, edges: Map<T, Collection<T>>) = breadthFirstSearch(start, { it == end }, { edges[it] })
fun <T> breadthFirstSearch(start: T, end: (T) -> Boolean, edges: (T) -> Collection<T>?): List<T>? {
val queue = ArrayDeque<T>().apply { this += start }
val seen = hashSetOf<T>().apply { this += start }
val from = hashMapOf<T, T>()
while (queue.isNotEmpty()) {
val current = queue.removeFirst()
if (end(current))
return reconstruct(current, from)
edges(current)?.forEach {
if (seen.add(it)) {
from[it] = current
queue.addLast(it)
}
}
}
return null
}
fun <T> findShortest(
start: T,
end: T,
edges: Map<T, Collection<T>>,
weight: (T, T) -> Int = { _, _ -> 1 },
heuristic: (T, T) -> Int = { _, _ -> 0 }
): List<T>? {
val gScore = hashMapOf<T, Int>().apply { this[start] = 0 }
val fScore = hashMapOf<T, Int>().apply { this[start] = heuristic(start, end) }
val open = PriorityQueue<T>(edges.size, compareBy { fScore.computeIfAbsent(it) { p -> heuristic(p, end) } }).apply { this += start }
val from = hashMapOf<T, T>()
while (open.isNotEmpty()) {
val current = open.poll()
if (current == end)
return reconstruct(current, from)
edges[current]?.forEach {
val tentative = gScore.getOrDefault(current, Int.MAX_VALUE) + weight(current, it)
if (tentative < gScore.getOrDefault(it, Int.MAX_VALUE)) {
from[it] = current
gScore[it] = tentative
fScore[it] = tentative + heuristic(it, end)
if (it !in open)
open += it
}
}
}
return null
}
private fun <T> reconstruct(last: T, from: Map<T, T>): List<T> {
val path = ArrayDeque<T>()
var current: T? = last
while (current != null) {
path.addFirst(current)
current = from[current]
}
return path
}
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 2,109 | advent-of-code-2022 | Apache License 2.0 |
src/Day18.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} | fun main() {
fun parsePoints(input: List<String>): Set<Point3D> {
return input.map {
val parts = it.split(',').map { n -> n.toInt() }
Point3D(parts[0], parts[1], parts[2])
}.toSet()
}
fun draw(points: Set<Point3D>) {
val minX = points.minOf { it.x }
val maxX = points.maxOf { it.x }
val minY = points.minOf { it.y }
val maxY = points.maxOf { it.y }
val minZ = points.minOf { it.z }
val maxZ = points.maxOf { it.z }
println("==============")
for(y in minY .. maxY) {
for(x in minX .. maxX) {
if (points.find { it.x == x && it.y == y } != null) {
print("#")
} else {
print(".")
}
}
println()
}
println("==============")
for(z in minZ .. maxZ) {
for(x in minX .. maxX) {
if (points.find { it.x == x && it.z == z } != null) {
print("#")
} else {
print(".")
}
}
println()
}
println("==============")
for(y in minY .. maxY) {
for(z in minZ .. maxZ) {
if (points.find { it.y == y && it.z == z } != null) {
print("#")
} else {
print(".")
}
}
println()
}
}
fun part1(input: List<String>): Int {
val points = parsePoints(input)
return points.sumOf { 6 - points.intersect(it.getSides()).size }
}
fun part2(input: List<String>): Int {
val points = parsePoints(input).toMutableSet()
//draw(points)
val bubbleCandidates = mutableSetOf<Point3D>()
for((x,y,z) in points) {
val left = Point3D(x+1,y,z)
if (!points.contains(left) && points.find { (x2,y2,z2) -> x2 > left.x && y2 == left.y && z2 == left.z } != null) {
bubbleCandidates.add(left)
}
val right = Point3D(x-1,y,z)
if (!points.contains(right) && points.find { (x2,y2,z2) -> x2 < right.x && y2 == right.y && z2 == right.z } != null) {
bubbleCandidates.add(right)
}
val up = Point3D(x,y+1,z)
if (!points.contains(up) && points.find { (x2,y2,z2) -> x2 == up.x && y2 > up.y && z2 == up.z } != null) {
bubbleCandidates.add(up)
}
val down = Point3D(x,y-1,z)
if (!points.contains(down) && points.find { (x2,y2,z2) -> x2 == down.x && y2 < down.y && z2 == down.z } != null) {
bubbleCandidates.add(down)
}
val front = Point3D(x,y,z+1)
if (!points.contains(front) && points.find { (x2,y2,z2) -> x2 == front.x && y2 == front.y && z2 > front.z } != null) {
bubbleCandidates.add(front)
}
val back = Point3D(x,y,z-1)
if (!points.contains(back) && points.find { (x2,y2,z2) -> x2 == back.x && y2 == back.y && z2 < back.z } != null) {
bubbleCandidates.add(back)
}
}
val minBoundary = Point3D(points.minOf { it.x } - 1, points.minOf { it.y } - 1, points.minOf { it.z } - 1)
val maxBoundary = Point3D(points.maxOf { it.x } + 1, points.maxOf { it.y } + 1, points.maxOf { it.z } + 1)
for(candidate in bubbleCandidates) {
//println("Candidate: $candidate")
if (points.contains(candidate)) {
continue
}
var isBubble = true
val visited = mutableSetOf<Point3D>()
val active = mutableSetOf(candidate)
while(active.isNotEmpty()) {
val current = active.first()
if (current.x <= minBoundary.x || current.y <= minBoundary.y || current.z <= minBoundary.z
|| current.x >= maxBoundary.x || current.y >= maxBoundary.y || current.z >= maxBoundary.z) {
isBubble = false
break
}
active.remove(current)
visited.add(current)
active.addAll(current.getSides().toSet().subtract(points).subtract(visited).subtract(active))
}
if(isBubble) {
println("Found bubble. Size=${visited.size}")
points.addAll(visited)
}
}
return points.sumOf { 6 - points.intersect(it.getSides()).size }
}
val testInput = readInput("Day18_test")
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
data class Point3D(
val x: Int,
val y: Int,
val z: Int
) {
fun getSides(): Set<Point3D> {
return setOf(
Point3D(x+1,y,z),
Point3D(x-1,y,z),
Point3D(x,y+1,z),
Point3D(x,y-1,z),
Point3D(x,y,z+1),
Point3D(x,y,z-1)
)
}
}
| 0 | Kotlin | 0 | 0 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 5,121 | aoc2022 | Apache License 2.0 |
src/Day02.kt | askeron | 572,955,924 | false | {"Kotlin": 24616} | class Day02 : Day<Int>(15, 12, 13565, 12424) {
fun String.singleChar(): Char {
assert(this.length == 1) { "not a single char" }
return toCharArray()[0]
}
override fun part1(input: List<String>): Int {
return input
.asSequence()
.map { it.split(" ").map { Shape.byChar(it.singleChar()) } }
.map { it[0] to it[1] }
.map { it.second.pointsAgainst(it.first) }
.sum()
}
override fun part2(input: List<String>): Int {
return input
.asSequence()
.map { it.split(" ").map { it.singleChar() } }
.map { Shape.byChar(it[0]) to it[1] }
.map { it.first to it.first.shapeForPart2(it.second) }
.map { it.second.pointsAgainst(it.first) }
.sum()
}
}
enum class Shape(val primary: Char, val secondary: Char, private val points: Int, private val winsAgainstSupplier: () -> Shape) {
ROCK('A', 'X', 1, { SCISSORS }),
PAPER('B', 'Y', 2, { ROCK }),
SCISSORS('C', 'Z', 3, { PAPER }),
;
private val winsAgainst by lazy { winsAgainstSupplier.invoke() }
private val drawsAgainst = this
private val losesAgainst by lazy { values().first { it !in listOf(winsAgainst, drawsAgainst) } }
fun pointsAgainst(shape: Shape) = points + when (shape) {
winsAgainst -> 6
drawsAgainst -> 3
else -> 0
}
fun shapeForPart2(c: Char): Shape = when(c) {
'X' -> winsAgainst
'Y' -> drawsAgainst
'Z' -> losesAgainst
else -> error("invalid char")
}
companion object {
fun byChar(c: Char): Shape = values().first { c == it.primary || c == it.secondary }
}
}
| 0 | Kotlin | 0 | 1 | 6c7cf9cf12404b8451745c1e5b2f1827264dc3b8 | 1,717 | advent-of-code-kotlin-2022 | Apache License 2.0 |
2021/src/main/kotlin/de/skyrising/aoc2021/day17/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day17
import de.skyrising.aoc.*
val test = TestInput("target area: x=20..30, y=-10..-5")
@PuzzleName("Trick Shot")
fun PuzzleInput.part1v0(): Any {
val target = parseInput(this)
val x2 = target.first.last
val y1 = target.second.first
var maxY = 0
for (x in 1..x2) {
for (y in 1..-y1) {
val result = ProbeState(0, 0, x, y).simulate(target)
if (result.hit) {
maxY = maxOf(maxY, result.maxY)
//println("$x,$y ${result.maxY}")
}
}
}
return maxY
}
@PuzzleName("Trick Shot")
fun PuzzleInput.part1v1(): Any {
val target = parseInput(this)
val vy = -target.second.first - 1
return vy * (vy + 1) / 2
}
fun PuzzleInput.part2(): Any {
val target = parseInput(this)
val x2 = target.first.last
val y1 = target.second.first
var hits = 0
for (x in 1..x2) {
for (y in y1..-y1) {
val result = ProbeState(0, 0, x, y).simulate(target)
if (result.hit) {
hits++
//println("$x,$y ${result.maxY}")
}
}
}
return hits
}
private fun parseInput(input: PuzzleInput): Pair<IntRange, IntRange> {
val comma = input.chars.indexOf(',')
val (x1, x2) = input.chars.substring(15, comma).split("..").map(String::toInt)
val (y1, y2) = input.chars.substring(comma + 4).trimEnd().split("..").map(String::toInt)
return Pair(x1..x2, y1..y2)
}
data class ProbeState(val x: Int, val y: Int, val vx: Int, val vy: Int) {
fun step(): ProbeState {
val x = this.x + vx
val y = this.y + vy
val vx = if (this.vx > 0) this.vx - 1 else 0
val vy = this.vy - 1
return ProbeState(x, y, vx, vy)
}
fun simulate(target: Pair<IntRange, IntRange>): ProbeResult {
var state = this
var steps = 0
var maxY = state.y
//println(target)
while (true) {
//println(state)
if (state.x in target.first && state.y in target.second) return ProbeResult(true, state.x, state.y, maxY)
if (state.x > target.first.last || state.y < target.second.first) return ProbeResult(false, state.x, state.y, maxY)
state = state.step()
maxY = maxOf(maxY, state.y)
steps++
}
}
}
data class ProbeResult(val hit: Boolean, val x: Int, val y: Int, val maxY: Int) | 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,432 | aoc | MIT License |
src/day11/Day11.kt | felldo | 572,762,654 | false | {"Kotlin": 76496} | class Monkey {
var items = mutableListOf<Long>()
var trueMonkey = 0
var falseMonkey = 0
var isMultiply = false
var opValue = 0L
var opOld = false
var testValue = 0L
var numThrows = 0L
fun operation (item: Long): Long {
val opVal = if (opOld) item else opValue
return if (isMultiply) {
item * opVal
} else {
item + opVal
}
}
fun throwItem (item: Long): Int {
return if (item % testValue == 0L) {
trueMonkey
} else {
falseMonkey
}
}
}
fun main() {
fun parseInput(input: List<List<String>>): List<Monkey> {
val monkeys = mutableListOf<Monkey>()
for (monkey in input) {
val newMonkey = Monkey()
// items
val items = monkey[1].replace(",", "").split(" ")
for (i in 4 until items.size) {
newMonkey.items.add(items[i].toLong())
}
// operation
val ops = monkey[2].split(" ")
if (ops[6] == "*") {
newMonkey.isMultiply = true
}
if (ops[7] == "old") {
newMonkey.opOld = true
} else {
newMonkey.opValue = ops.last().toLong()
}
// test
newMonkey.testValue = monkey[3].split(" ").last().toLong()
// trueMonkey / falseMonkey
newMonkey.trueMonkey = monkey[4].split(" ").last().toInt()
newMonkey.falseMonkey = monkey[5].split(" ").last().toInt()
monkeys.add(newMonkey)
}
return monkeys
}
fun part1(input: List<List<String>>): Long {
val monkeys = parseInput(input)
for (turn in 0 until 20) {
for (monkey in monkeys) {
for (item in monkey.items) {
val worry = monkey.operation(item) / 3L
val whichMonkey = monkey.throwItem(worry)
monkeys[whichMonkey].items.add(worry)
monkey.numThrows++
}
monkey.items.clear()
}
}
val topTwo = monkeys.sortedByDescending { it.numThrows }.take(2)
return topTwo[0].numThrows * topTwo[1].numThrows
}
fun part2(input: List<List<String>>): Long {
val monkeys = parseInput(input)
var maxStress = 1L
monkeys.map { it.testValue }.forEach { maxStress *= it }
for (turn in 0 until 10_000) {
for (monkey in monkeys) {
for (item in monkey.items) {
val worry = monkey.operation(item) % maxStress
val whichMonkey = monkey.throwItem(worry)
monkeys[whichMonkey].items.add(worry)
monkey.numThrows++
}
monkey.items.clear()
}
}
val topTwo = monkeys.sortedByDescending { it.numThrows }.take(2)
return topTwo[0].numThrows * topTwo[1].numThrows
}
val input = readInputSpaceDelimited("Day11")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 3,149 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day10.kt | iartemiev | 573,038,071 | false | {"Kotlin": 21075} | import kotlin.math.floor
enum class Instruction(val cycles: Int) {
noop(1),
addx(2),
}
fun drawCRT(): (cycle: Int, sprite: Int) -> Unit {
val grid = MutableList(6) { MutableList(40) {"."} }
return fun (cycle: Int, sprite: Int) {
val row = (cycle - 1).floorDiv(40)
val pixel = (cycle - 1) % 40
if (pixel in (sprite-1)..(sprite+1)) {
grid[row][pixel] = "#"
}
if (cycle == 240) {
val p = grid.joinToString(separator = "\n" ) { it.joinToString("") }
println(p + "\n")
}
}
}
fun runProgram(instructionList: MutableList<List<String>>, drawOutput: Boolean = false): Int {
var cycle = 1
var registerX = 1
var signalSum = 0
var currentLine = instructionList.removeFirst()
var currentInstruction = Instruction.valueOf(currentLine[0])
var currentCycles = currentInstruction.cycles
val draw = drawCRT()
while(true) {
if (drawOutput) {
draw(cycle, registerX)
}
cycle++
currentCycles--
if (currentCycles == 0) {
if (currentInstruction == Instruction.addx) {
registerX += currentLine[1].toInt()
}
if (instructionList.size == 0) break
currentLine = instructionList.removeFirst()
currentInstruction = Instruction.valueOf(currentLine[0])
currentCycles = currentInstruction.cycles
}
if ((cycle == 20) || ((cycle - 20) % 40 == 0)) {
val signal = cycle * registerX
signalSum += signal
}
}
return signalSum
}
fun main() {
fun part1(input: List<String>): Int {
val instructionList = input.map { it.split(" ") } as MutableList<List<String>>
return runProgram(instructionList)
}
fun part2(input: List<String>): Int {
val instructionList = input.map { it.split(" ") } as MutableList<List<String>>
return runProgram(instructionList, true)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
part2(testInput)
// check(part2(testInput) == 1)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8d2b7a974c2736903a9def65282be91fbb104ffd | 2,117 | advent-of-code | Apache License 2.0 |
src/Day14.kt | frungl | 573,598,286 | false | {"Kotlin": 86423} | import kotlin.math.max
import kotlin.math.sign
typealias Coord = Pair<Int, Int>
private operator fun Coord.plus(other: Coord): Coord {
return first + other.first to second + other.second
}
fun main() {
val tryGo = listOf(0 to 1, -1 to 1, 1 to 1)
fun tryAdd(now: Coord, used: MutableSet<Coord>): Coord {
if (now.second == 1000)
return now
val pos = tryGo.map{ it + now }
if (pos.all { used.contains(it) })
return now
return tryAdd(pos.first { !used.contains(it) }, used)
}
fun MutableSet<Coord>.addLine(from: Coord, to: Coord) {
var last = from
val move = (to.first - last.first).sign to (to.second - last.second).sign
add(last)
while (last != to) {
last += move
add(last)
}
}
fun part1(input: List<String>): Int {
val set = mutableSetOf<Coord>()
input.forEach { line ->
val crd = line.split("->")
.map { it.trim() }
.map {
val (a, b) = it.split(',')
a.toInt() to b.toInt()
}
crd.windowed(2) {
set.addLine(it[0], it[1])
}
}
var cnt = 0
while (true) {
val new = tryAdd(500 to 0, set)
if (new.second == 1000)
break
set.add(new)
cnt++
}
return cnt
}
fun part2(input: List<String>): Int {
val set = mutableSetOf<Coord>()
var mx = 0
input.forEach { line ->
val crd = line.split("->")
.map { it.trim() }
.map {
val (a, b) = it.split(',')
mx = max(mx, b.toInt() + 2)
a.toInt() to b.toInt()
}
crd.windowed(2) {
set.addLine(it[0], it[1])
}
}
set.addLine(-1000 to mx, 1000 to mx)
var cnt = 0
while (!set.contains(500 to 0)) {
val new = tryAdd(500 to 0, set)
set.add(new)
cnt++
}
return cnt
}
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d4cecfd5ee13de95f143407735e00c02baac7d5c | 2,378 | aoc2022 | Apache License 2.0 |
src/Day08.kt | ds411 | 573,543,582 | false | {"Kotlin": 16415} | fun main() {
fun part1(input: List<String>): Int {
val cols = input[0].length
val rows = input.size
val grid = input.map { it.toCharArray().map { it.toInt() } }
val visibleTrees = hashSetOf<Tree>()
var max = -1;
// From top
(0 until cols).forEach { col ->
max = -1
(0 until rows).forEach { row ->
val height = grid[row][col]
if (height > max) {
val tree = Tree(
x = col,
y = row,
height = height
)
visibleTrees += tree
max = height
}
}
}
// From bottom
(0 until cols).forEach { col ->
max = -1
(rows-1 downTo 0).forEach { row ->
val height = grid[row][col]
if (height > max) {
val tree = Tree(
x = col,
y = row,
height = height
)
visibleTrees += tree
max = height
}
}
}
// From left
(0 until rows).forEach { row ->
max = -1
(0 until cols).forEach { col ->
val height = grid[row][col]
if (height > max) {
val tree = Tree(
x = col,
y = row,
height = height
)
visibleTrees += tree
max = height
}
}
}
// From right
(0 until rows).forEach { row ->
max = -1
(cols-1 downTo 0).forEach { col ->
val height = grid[row][col]
if (height > max) {
val tree = Tree(
x = col,
y = row,
height = height
)
visibleTrees += tree
max = height
}
}
}
return visibleTrees.size
}
fun part2(input: List<String>): Int {
val cols = input[0].length
val rows = input.size
val grid = input.map { it.toCharArray().map { it.toInt() } }
var max = -1;
(0 until cols).forEach { col ->
(0 until rows).forEach { row ->
val score = calcScore(grid, col, row)
if (score > max) max = score
}
}
return max
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
println(part2(testInput))
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
private fun calcScore(grid: List<List<Int>>, col: Int, row: Int): Int {
if (row == 0 || col == 0) return 0
val rows = grid.size
val cols = grid[0].size
val height = grid[row][col]
var folding = true
val left = (col-1 downTo 0).fold(0) { acc, col ->
if (folding) {
val height2 = grid[row][col]
if (height2 >= height) folding = false
acc+1
}
else acc
}
folding = true
val right = (col+1 .. cols-1).fold(0) { acc, col ->
if (folding) {
val height2 = grid[row][col]
if (height2 >= height) folding = false
acc+1
}
else acc
}
folding = true
val top = (row-1 downTo 0).fold(0) { acc, row ->
if (folding) {
val height2 = grid[row][col]
if (height2 >= height) folding = false
acc+1
}
else acc
}
folding = true
val bottom = (row+1 .. rows-1).fold(0) { acc, row ->
if (folding) {
val height2 = grid[row][col]
if (height2 >= height) folding = false
acc+1
}
else acc
}
return left * right * top * bottom
}
private data class Tree(
val x: Int,
val y: Int,
val height: Int
)
| 0 | Kotlin | 0 | 0 | 6f60b8e23ee80b46e7e1262723960af14670d482 | 4,280 | advent-of-code-2022 | Apache License 2.0 |
src/day09/Day09Answer1.kt | IThinkIGottaGo | 572,833,474 | false | {"Kotlin": 72162} | package day09
import readInput
import java.lang.Math.abs
/**
* Answers from [Advent of Code 2022 Day 9 | Kotlin](https://youtu.be/ShU9dNUa_3g)
*/
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)),
}
data class Pos(val x: Int, val y: Int) {
override fun toString(): String = "(x:$x, y:$y)"
}
operator fun Pos.plus(move: Move): Pos = copy(x + move.dx, y + move.dy)
operator fun Pos.minus(other: Pos): Move = Move(x - other.x, y - other.y)
// Chebyshev's Chessboard distance
val Move.distance: Int get() = maxOf(abs(dx), abs(dy))
fun tailToHeadAttraction(head: Pos, tail: Pos): Move {
val tailToHead = head - tail
return if (tailToHead.distance > 1) {
Move(tailToHead.dx.coerceIn(-1, 1), tailToHead.dy.coerceIn(-1, 1))
} else {
Move(0, 0)
}
}
fun main() {
val input = readInput("day09").map { line -> line.split(" ").let { (d, n) -> Direction.valueOf(d) to n.toInt() } }
run part1@{
var head = Pos(0, 0)
var tail = head
val tailVisited = mutableSetOf(tail)
for ((d, n) in input) {
repeat(n) {
head += d.move
tail += tailToHeadAttraction(head, tail)
tailVisited += tail
}
}
println(tailVisited.size) // 5981
}
run part2@{
val knotsNumber = 10
val knots = MutableList(knotsNumber) { Pos(0, 0) }
val tailVisited = mutableSetOf(knots.last())
for ((d, n) in input) {
repeat(n) {
knots[0] = knots[0] + d.move
for ((headIndex, tailIndex) in knots.indices.zipWithNext()) {
knots[tailIndex] = knots[tailIndex] + tailToHeadAttraction(knots[headIndex], knots[tailIndex])
}
tailVisited += knots.last()
}
}
println(tailVisited.size) // 2352
}
} | 0 | Kotlin | 0 | 0 | 967812138a7ee110a63e1950cae9a799166a6ba8 | 1,987 | advent-of-code-2022 | Apache License 2.0 |
src/pt/davidafsilva/aoc/d3/ManhattanDistance.kt | davidafsilva | 83,922,983 | false | {"Java": 10029, "Kotlin": 9144} | package pt.davidafsilva.aoc.d3
import pt.davidafsilva.aoc.loadInput
import java.awt.geom.Line2D
import java.io.BufferedReader
import kotlin.LazyThreadSafetyMode.NONE
import kotlin.math.pow
import kotlin.math.sqrt
private object ManhattanDistance {
private data class Point(val x: Int, val y: Int) {
companion object {
val ZERO = Point(0, 0)
}
}
private data class Line(val a: Point, val z: Point, val cost: Int, val totalCost: Int) {
val path: List<Point> by lazy(NONE) {
when (a.x) {
z.x -> {
val yRange = if (a.y > z.y) IntProgression.fromClosedRange(a.y, z.y, -1)
else IntProgression.fromClosedRange(a.y, z.y, 1)
yRange.map { Point(a.x, it) }
}
else -> {
val xRange = if (a.x > z.x) IntProgression.fromClosedRange(a.x, z.x, -1)
else IntProgression.fromClosedRange(a.x, z.x, 1)
xRange.map { Point(it, a.y) }
}
}
}
fun cost(p: Point): Int =
totalCost - cost + sqrt((a.x - p.x).toDouble().pow(2) + (a.y - p.y).toDouble().pow(2)).toInt()
}
fun compute(): Pair<Point, Int>? {
val (wire1Path, wire2Path) = javaClass.loadInput {
it.readCoordinates() to it.readCoordinates()
}
val candidates = mutableListOf<Pair<Point, Int>>()
wire1Path.forEach { w1p ->
wire2Path.forEach { w2p ->
candidates.addAll(interceptionPoints(w1p, w2p))
}
}
return candidates.minBy { it.second }
}
private fun interceptionPoints(l1: Line, l2: Line): Collection<Pair<Point, Int>> = when {
(l1.a == Point.ZERO && l2.a == Point.ZERO) -> emptyList()
!Line2D.linesIntersect(
l1.a.x.toDouble(), l1.a.y.toDouble(), l1.z.x.toDouble(), l1.z.y.toDouble(),
l2.a.x.toDouble(), l2.a.y.toDouble(), l2.z.x.toDouble(), l2.z.y.toDouble()
) -> emptyList()
else -> l1.path.intersect(l2.path).map { ip -> ip to l1.cost(ip) + l2.cost(ip) }
}
private fun BufferedReader.readCoordinates(): List<Line> = readLine()
.splitToSequence(",")
.mapNotNull { coordinate ->
val value = coordinate.substring(1).toInt()
value to when (coordinate[0]) {
'R' -> Point(value, 0)
'L' -> Point(-value, 0)
'U' -> Point(0, value)
'D' -> Point(0, -value)
else -> error("unsupported operation: ${coordinate[0]}")
}
}
.fold(mutableListOf()) { lines, (hop, move) ->
val lastTrail = lines.lastOrNull()
val sourceP = lastTrail?.z ?: Point(0, 0)
val destinationP = Point(sourceP.x + move.x, sourceP.y + move.y)
val cost = (lastTrail?.totalCost ?: 0) + hop
lines.apply { add(Line(sourceP, destinationP, hop, cost)) }
}
}
fun main() {
println(ManhattanDistance.compute())
}
| 0 | Java | 0 | 0 | 336baee33e968917b536e92244b289f8d1580e15 | 3,088 | exercises | MIT License |
2022/src/main/kotlin/day18.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.MutableIntSpace
import utils.Parser
import utils.Solution
import utils.Point3i
import utils.Vec4i
import utils.mapItems
fun main() {
Day18.run()
}
object Day18 : Solution<Set<Vec4i>>() {
override val name = "day18"
override val parser = Parser.lines.mapItems {
val (x, y, z) = it.split(",", limit = 3).map(String::toInt)
Point3i(x + 1, y + 1, z + 1)
}.map(List<Vec4i>::toSet)
private fun makeSpace(input: Set<Vec4i>) = MutableIntSpace(
input.maxOf { it.x } + 2,
input.maxOf { it.y } + 2,
input.maxOf { it.z } + 2) {
if (it in input) 1 else 0 // init known blocks to 1
}
override fun part1(input: Set<Vec4i>): Int {
val space = makeSpace(input)
return input.flatMap { it.adjacent }.sumOf { 1 - space[it] }
}
override fun part2(input: Set<Vec4i>): Int {
val space = makeSpace(input)
// fill outer area with tows using 6-way fill
val queue = ArrayDeque<Vec4i>()
queue.add(Point3i(0, 0, 0))
while (queue.isNotEmpty()) {
val p = queue.removeFirst()
if (space[p] != 0) continue
space[p] = 2
queue.addAll(p.adjacent.filter { it in space })
}
return input.flatMap { it.adjacent }.sumOf { space[it] ushr 1 }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,231 | aoc_kotlin | MIT License |
kotlin/src/com/s13g/aoc/aoc2021/Day21.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import kotlin.math.max
import kotlin.math.min
/**
* --- Day 21: <NAME> ---
* https://adventofcode.com/2021/day/21
*/
class Day21 : Solver {
override fun solve(lines: List<String>): Result {
var stateA = GameState(lines[0].substring(28).toInt(), lines[1].substring(28).toInt(), 0, 0, 0)
val stateB = stateA.copy()
val dieA = DiePartA(100)
while (max(stateA.score1, stateA.score2) < 1000) {
var newPos = stateA.getPos() + dieA.roll() + dieA.roll() + dieA.roll()
while (newPos > 10) newPos -= 10
val newScore = stateA.getScore() + newPos
stateA = newState(newPos, newScore, stateA)
}
val partA = min(stateA.score1, stateA.score2) * dieA.timesRolled
val wins = countWinsForPlayers(stateB)
val partB = max(wins.first, wins.second)
return Result("$partA", "$partB")
}
// DP aka memoization of all the branches of the tree (most are duplicates).
private var cache = mutableMapOf<GameState, Pair<Long, Long>>()
private fun countWinsForPlayers(state: GameState): Pair<Long, Long> {
if (state.score1 >= 21) return Pair(1, 0)
if (state.score2 >= 21) return Pair(0, 1)
if (cache.containsKey(state)) return cache[state]!!
var wins1 = 0L
var wins2 = 0L
for (dice1 in 1..3) {
for (dice2 in 1..3) {
for (dice3 in 1..3) {
var newPos = state.getPos() + dice1 + dice2 + dice3
while (newPos > 10) newPos -= 10
val newScore = state.getScore() + newPos
val newGameState = newState(newPos, newScore, state)
val wins = countWinsForPlayers(newGameState)
wins1 += wins.first
wins2 += wins.second
}
}
}
val result = Pair(wins1, wins2)
cache[state] = result
return result
}
private class DiePartA(val sides: Int) {
var value = 0
var timesRolled = 0
fun roll(): Int {
timesRolled++
return (value++ % sides) + 1
}
}
private data class GameState(val pos1: Int, val pos2: Int, val score1: Int, val score2: Int, val turn: Int) {
fun getPos() = if (turn == 0) pos1 else pos2
fun getScore() = if (turn == 0) score1 else score2
}
private fun newState(pos: Int, score: Int, prev: GameState): GameState {
return if (prev.turn == 0) GameState(pos, prev.pos2, score, prev.score2, 1)
else GameState(prev.pos1, pos, prev.score1, score, 0)
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,466 | euler | Apache License 2.0 |
advent-of-code2015/src/main/kotlin/day20/Advent20.kt | REDNBLACK | 128,669,137 | false | null | package day20
import java.util.stream.IntStream
/**
--- Day 20: Infinite Elves and Infinite Houses ---
To keep the Elves busy, Santa has them deliver some presents by hand, door-to-door. He sends them down a street with infinite houses numbered sequentially: 1, 2, 3, 4, 5, and so on.
Each Elf is assigned a number, too, and delivers presents to houses based on that number:
The first Elf (number 1) delivers presents to every house: 1, 2, 3, 4, 5, ....
The second Elf (number 2) delivers presents to every second house: 2, 4, 6, 8, 10, ....
Elf number 3 delivers presents to every third house: 3, 6, 9, 12, 15, ....
There are infinitely many Elves, numbered starting with 1. Each Elf delivers presents equal to ten times his or her number at each house.
So, the first nine houses on the street end up like this:
House 1 got 10 presents.
House 2 got 30 presents.
House 3 got 40 presents.
House 4 got 70 presents.
House 5 got 60 presents.
House 6 got 120 presents.
House 7 got 80 presents.
House 8 got 150 presents.
House 9 got 130 presents.
The first house gets 10 presents: it is visited only by Elf 1, which delivers 1 * 10 = 10 presents. The fourth house gets 70 presents, because it is visited by Elves 1, 2, and 4, for a total of 10 + 20 + 40 = 70 presents.
What is the lowest house number of the house to get at least as many presents as the number in your puzzle input?
--- Part Two ---
The Elves decide they don't want to visit an infinite number of houses. Instead, each Elf will stop after delivering presents to 50 houses. To make up for it, they decide to deliver presents equal to eleven times their number at each house.
With these changes, what is the new lowest house number of the house to get at least as many presents as the number in your puzzle input?
*/
fun main(args: Array<String>) {
println(findHouseNumber(33100000))
println(findHouseNumberSecondStep(33100000))
}
fun findHouseNumber(presentsCount: Int): Int? = IntStream.rangeClosed(1, presentsCount / 10)
.parallel()
.mapToObj { houseNum ->
houseNum to IntStream.rangeClosed(1, houseNum)
.filter { houseNum % it == 0 }
.map { it * 10 }
.sum()
}
.filter { it.second >= presentsCount }
.findFirst()
.map { it.first }
.orElse(null)
fun findHouseNumberSecondStep(presentsCount: Int): Int {
val visited = Array(presentsCount) { 1 }
(1 until presentsCount)
.forEach { houseNum ->
for ((counter, n) in (houseNum until presentsCount step houseNum).withIndex()) {
visited[n] += houseNum * 11
if (counter + 1 == 50) break
}
}
return visited.indexOfFirst { it >= presentsCount }
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 2,810 | courses | MIT License |
src/main/kotlin/tr/emreone/adventofcode/Extensions.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode
import tr.emreone.kotlin_utils.math.Point2D
import kotlin.math.abs
fun String.readTextGroups(delimitter: String = "\n\n"): List<String> {
return this.split(delimitter)
}
fun Point2D.manhattanDistanceTo(other: Point2D): Long {
return abs(x - other.x) + abs(y - other.y)
}
fun Point2D.move(direction: String, distance: Int): Point2D {
return when (direction.lowercase()) {
in arrayOf("u", "up", "n", "north", "norden") -> Point2D(x, y + distance)
in arrayOf("d", "down", "s", "south", "sueden") -> Point2D(x, y - distance)
in arrayOf("r", "right", "e", "east", "osten") -> Point2D(x + distance, y)
in arrayOf("l", "left", "w", "west", "westen") -> Point2D(x - distance, y)
else -> throw IllegalArgumentException("Unknown direction: $direction")
}
}
operator fun IntRange.contains(other: IntRange): Boolean {
return this.contains(other.first) && this.contains(other.last)
}
infix fun IntRange.overlaps(other: IntRange): Boolean {
return this.first <= other.last && other.first <= this.last
}
fun List<Long>.product(): Long = this.reduce { acc, i -> acc * i }
infix fun Long.isDivisibleBy(divisor: Int): Boolean = this % divisor == 0L
// greatest common divisor
infix fun Long.gcd(other: Long): Long {
var a = this
var b = other
while (b != 0L) {
val temp = b
b = a % b
a = temp
}
return a
}
// least common multiple
infix fun Long.lcm(other: Long): Long = (this * other) / (this gcd other)
fun List<Long>.gcd(): Long = this.reduce(Long::gcd)
fun List<Long>.lcm(): Long = this.reduce(Long::lcm)
| 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 1,690 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day18.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.Logger.logger
import tr.emreone.kotlin_utils.math.Point3D
import java.util.*
import kotlin.math.min
import kotlin.math.max
object Day18 {
data class Cube(val center: Point3D) {
fun possibleDirectNeighbors(): List<Cube> {
return listOf(
Cube(Point3D(center.x - 1, center.y, center.z)),
Cube(Point3D(center.x + 1, center.y, center.z)),
Cube(Point3D(center.x, center.y - 1, center.z)),
Cube(Point3D(center.x, center.y + 1, center.z)),
Cube(Point3D(center.x, center.y, center.z - 1)),
Cube(Point3D(center.x, center.y, center.z + 1))
)
}
}
class Droplet(input: List<String>) {
val cubes = input.map { line ->
val (x, y, z) = line.split(",").map { it.toLong() }
Cube(Point3D(x, y, z))
}
private val outCubes = mutableSetOf<Cube>()
private val inCubes = mutableSetOf<Cube>()
fun calcSurfaceArea(): Int {
return this.cubes.sumOf { cube ->
val neighbors = cube.possibleDirectNeighbors()
6 - neighbors.count { this.cubes.contains(it) }
}
}
fun calcOnlyOutsideSurfaceArea(): Int {
outCubes.clear()
inCubes.clear()
fun reachesOutside(cube: Cube): Boolean {
if (outCubes.contains(cube)) return true
if (inCubes.contains(cube)) return false
val seenCubes = mutableSetOf<Cube>()
val queue = mutableListOf<Cube>(cube)
while(queue.isNotEmpty()) {
val c = queue.removeFirst()
if (this.cubes.contains(c))
continue
if (seenCubes.contains(c))
continue
seenCubes.add(c)
if (seenCubes.size > this.cubes.size) {
seenCubes.forEach { outCubes.add(it) }
return true
}
queue.addAll(c.possibleDirectNeighbors())
}
seenCubes.forEach { inCubes.add(it) }
return false
}
return this.cubes.sumOf { cube ->
val neighbors = cube.possibleDirectNeighbors()
neighbors.count { reachesOutside(it) }
}
}
}
fun part1(input: List<String>): Int {
val droplet = Droplet(input)
return droplet.calcSurfaceArea()
}
fun part2(input: List<String>): Int {
val droplet = Droplet(input)
return droplet.calcOnlyOutsideSurfaceArea()
}
}
| 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 2,784 | advent-of-code-2022 | Apache License 2.0 |
src/questions/FindAllAnagrams.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* Given two strings s and p, return an array of all the start indices of p's anagrams in s.
* You may return the answer in any order.
*
* [Source](https://leetcode.com/problems/find-all-anagrams-in-a-string/)
*/
@UseCommentAsDocumentation
private fun findAnagrams(s: String, p: String): List<Int> {
if (p.length > s.length) {
return emptyList()
}
val result = mutableListOf<Int>()
val charCounts = mutableMapOf<Char, Int>()
for (i in p) {
charCounts[i] = charCounts.getOrDefault(i, 0) + 1
}
// val sortedP = p.toCharArray().sorted()
// findAnagramUsingSortCompare(s, 0, sortedP, result)
findAnagramUsingCharCount(s, 0, p.length, charCounts, result)
return result
}
/**
* Sliding window method with map
* @see questions.isAnagram
*/
private fun findAnagramUsingCharCount(
s: String,
startIndex: Int,
targetSize: Int,
countMap: MutableMap<Char, Int>,
result: MutableList<Int>
) {
if (s.length - startIndex < targetSize) {
return
}
val copy = HashMap(countMap)
val subString = s.substring(startIndex, startIndex + targetSize)
for (i in subString) {
val newVal = copy.getOrDefault(i, 0) - 1
if (newVal == 0) copy.remove(i)
else copy[i] = newVal
}
if (copy.isEmpty()) {
result.add(startIndex)
}
findAnagramUsingCharCount(s, startIndex + 1, targetSize, countMap, result)
}
/**
* Sliding window method with sorted compare
* @see questions.isAnagramII
*/
private fun findAnagramUsingSortCompare(s: String, startIndex: Int, target: List<Char>, result: MutableList<Int>) {
val size = target.size
if (s.length - startIndex < size) {
return
}
val subString = s.substring(startIndex, startIndex + size).toCharArray().sorted()
if (subString == target) { // sorted strings are equal then it is anagram
result.add(startIndex)
}
findAnagramUsingSortCompare(s, startIndex + 1, target, result)
}
fun main() {
// The substring with start index = 0 is "cba", which is an anagram of "abc".
// The substring with start index = 6 is "bac", which is an anagram of "abc".
findAnagrams(s = "cbaebabacd", p = "abc") shouldBe listOf(0, 6)
// The substring with start index = 0 is "ab", which is an anagram of "ab".
// The substring with start index = 1 is "ba", which is an anagram of "ab".
// The substring with start index = 2 is "ab", which is an anagram of "ab".
findAnagrams(s = "abab", p = "ab") shouldBe listOf(0, 1, 2)
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,625 | algorithms | MIT License |
src/day7/Day7.kt | calvin-laurenson | 572,736,307 | false | {"Kotlin": 16407} | package day7
import readInput
import java.lang.Exception
import kotlin.math.absoluteValue
fun getAllFolders(folder: Item.Folder): List<Item.Folder> {
val folders = mutableListOf<Item.Folder>(folder)
for (item in folder.items) {
if (item is Item.Folder) {
val subFolders = getAllFolders(item)
folders.addAll(subFolders)
folders.add(item)
}
}
return folders
}
fun getAllFiles(folder: Item.Folder): List<Item.File> {
val files = mutableListOf<Item.File>()
for (item in folder.items) {
// println(item)
when (item) {
is Item.Folder -> {
val subFolders = getAllFiles(item)
files.addAll(subFolders)
}
is Item.File -> {
files.add(item)
}
}
}
return files
}
sealed class Item {
data class File(val name: String, val size: Int) : Item()
data class Folder(val name: String, val items: MutableList<Item>) : Item() {
fun size(): Int {
return getAllFiles(this).sumOf { it.size }
}
}
companion object {
fun parse(item: String): Item {
val split = item.split(" ")
return when {
split[0] == "dir" -> Folder(split[1], mutableListOf())
split[0].toIntOrNull() != null -> File(split[1], split[0].toInt())
else -> throw Exception("invalid item")
}
}
}
}
sealed class Command {
data class Cd(val directory: String) : Command()
object Ls : Command()
companion object {
fun parse(command: String): Command {
val split = command.split(" ")
return when (split[0]) {
"cd" -> Cd(split[1])
"ls" -> Ls
else -> throw Exception("Invalid command")
}
}
}
}
fun main() {
f@ fun part1(input: List<String>): Int {
val root = Item.Folder("/", mutableListOf())
var pwd = root
var currentCommand: Command? = null
for (line in input) {
if (line.startsWith("$")) {
// Is command
val command = Command.parse(line.drop(2))
// println("root: $root")
// println("pwd: $pwd")
// println("command: $command")
if (command is Command.Cd) {
when (command.directory) {
".." -> {
pwd = getAllFolders(root).find { it.items.contains(pwd) }!!
}
"/" -> pwd = root
else -> {
val newFolder = Item.Folder(command.directory, mutableListOf())
pwd.items.add(newFolder)
pwd = newFolder
}
}
}
currentCommand = command
} else {
// Is output
if (currentCommand is Command.Ls) {
val item = Item.parse(line)
// println("adding: $item to $pwd")
pwd.items.add(item)
}
}
}
return getAllFolders(root).toSet().map { it.size() }.filter { it <= 100_000 }.sum()
}
f@ fun part2(input: List<String>): Int {
val root = Item.Folder("/", mutableListOf())
var pwd = root
var currentCommand: Command? = null
for (line in input) {
if (line.startsWith("$")) {
// Is command
val command = Command.parse(line.drop(2))
// println("root: $root")
// println("pwd: $pwd")
// println("command: $command")
if (command is Command.Cd) {
when (command.directory) {
".." -> {
pwd = getAllFolders(root).find { it.items.contains(pwd) }!!
}
"/" -> pwd = root
else -> {
val newFolder = Item.Folder(command.directory, mutableListOf())
pwd.items.add(newFolder)
pwd = newFolder
}
}
}
currentCommand = command
} else {
// Is output
if (currentCommand is Command.Ls) {
val item = Item.parse(line)
// println("adding: $item to $pwd")
pwd.items.add(item)
}
}
}
val allFolders = getAllFolders(root)
val rootSize = root.size()
val needToFree = (40_000_000 - rootSize).absoluteValue
return allFolders.toSet().map { it.size() }.filter { it > needToFree }.sorted()[0]
}
val testInput = readInput("day7/test")
// println(part1(testInput))
check(part1(testInput) == 95437)
// check(part2(testInput) == 26)
val input = readInput("day7/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 155cfe358908bbe2a554306d44d031707900e15a | 5,195 | aoc2022 | Apache License 2.0 |
Problems/Algorithms/1631. Path with Minimum Effort/PathMinEffort.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun minimumEffortPath(heights: Array<IntArray>): Int {
val n = heights.size
val m = heights[0].size
val deltas = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
val visited = Array(n) { BooleanArray(m) { false } }
val dp = Array(n) { IntArray(m) { Int.MAX_VALUE } }
val heap = PriorityQueue<IntArray>({ a, b -> a[2] - b[2] })
heap.add(intArrayOf(0, 0, 0))
dp[0][0] = 0
while (!heap.isEmpty()) {
val curr = heap.poll()
val row = curr[0]
val col = curr[1]
val effort = curr[2]
if (!visited[row][col]) {
visited[row][col] = true
for (neighbor in deltas) {
val newRow = row + neighbor[0]
val newCol = col + neighbor[1]
if (isValid(n, m, newRow, newCol, visited)) {
val newEffort = maxOf(effort, Math.abs(heights[newRow][newCol]-heights[row][col]))
if (newEffort < dp[newRow][newCol]) {
dp[newRow][newCol] = newEffort
heap.add(intArrayOf(newRow, newCol, newEffort))
}
}
}
}
}
return dp[n-1][m-1]
}
private fun isValid(n: Int, m: Int, i: Int, j: Int, visited: Array<BooleanArray>): Boolean {
return i >= 0 && i < n && j >= 0 && j < m && !visited[i][j]
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,659 | leet-code | MIT License |
src/main/aoc2020/Day19.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2020
class Day19(input: List<String>) {
// options is a list of options available
data class Rule(val options: List<List<String>>)
private val messages: List<String> = input.last().split("\n")
private val rules: Map<String, Rule>
// Example input:
// 0: 4 1 5
// 1: 2 3 | 3 2
// 4: "a"
init {
rules = input.first().split("\n").associate { line ->
val id = line.substringBefore(":")
val options = line.substringAfter(": ")
.split(" | ")
.map { it.replace("\"", "").split(" ") }
id to Rule(options)
}
}
private fun String.isLetter() = this in listOf("a", "b")
/**
* Recursively check if the msg is valid under the given rule number when starting from any
* of the given start indexes. Since a rule can have more than one option there may be more than
* one way to fulfil the rule.
* @return an empty list if the rule is not valid or a list of indexes if it is valid. The indexes
* specify the index of first characters after those that has been consumed by fulfilling the rule.
*/
private fun check(msg: String, startIndexes: List<Int>, ruleNumber: String, rules: Map<String, Rule>): List<Int> {
val ruleToUse = rules[ruleNumber]!!
val ret = mutableListOf<Int>()
// Check the rule for all the given start indexes
for (startIndex in startIndexes) {
when { // cases that ends recursion
startIndex !in msg.indices -> {
// Can't fulfil this rule, we're past the end of msg already
continue
}
ruleToUse.options.first().first().isLetter() -> { // This rule is a leaf node
if (msg[startIndex].toString() == ruleToUse.options.first().first()) {
ret.add(startIndex + 1) // and msg is valid under this rule
}
continue
}
}
// The current rule has one or more options that refers to other rules. All options needs
// to be checked since we don't know which option is right. Both might look good so far
// but they could consume different amounts of the message which becomes important when
// checking other rules later on.
// Example: rule 1: a | aa ==> Should rule 1 consume one or two a:s?
optionCheck@ for (option in ruleToUse.options) {
var indexes = listOf(startIndex)
// For the current option, check if all it's requirements / sub rules are fulfilled
// Example: "option" could be [42, 42, 42], meaning it must be possible to apply rule 42
// three times in a row.
for (i in option.indices) {
val nextRuleNumber = option[i]
// Recursively (depth first) check if the character at the current position is correct.
val indexesThatCouldWork = check(msg, indexes, nextRuleNumber, rules)
if (indexesThatCouldWork.isEmpty()) {
// The current sub rule is not valid at all, no point in checking any further sub rules
// continue with the next option instead.
continue@optionCheck
}
// This option looks promising so far, continue checking for all indexes that are valid
indexes = indexesThatCouldWork
}
// We have successfully checked all sub rules, meaning this option is valid.
ret.addAll(indexes)
}
}
return ret
}
private fun checkAllRules(msg: String, rules: Map<String, Rule>): Boolean {
val result = check(msg, listOf(0), "0", rules)
return result.isNotEmpty() && result.any { it == msg.length }
}
fun solvePart1(): Int {
return messages.count { checkAllRules(it, rules) }
}
private fun changeRules(): Map<String, Rule> {
return rules.toMutableMap().apply {
this["8"] = Rule(listOf(listOf("42"), listOf("42", "8")))
this["11"] = Rule(listOf(listOf("42", "31"), listOf("42", "11", "31")))
}
}
fun solvePart2(): Int {
return messages.count { checkAllRules(it, changeRules()) }
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 4,452 | aoc | MIT License |
src/main/kotlin/ru/timakden/aoc/year2022/Day12.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2022
import ru.timakden.aoc.util.Point
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
import java.util.*
import kotlin.properties.Delegates
/**
* [Day 12: Hill Climbing Algorithm](https://adventofcode.com/2022/day/12).
*/
object Day12 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2022/Day12")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
val nodes = buildNodes(input)
val start = checkNotNull(nodes.find { it.elevation == 'S' })
val finish = checkNotNull(nodes.find { it.elevation == 'E' })
dijkstra(start)
return finish.shortestPath.size
}
fun part2(input: List<String>): Int {
val nodes = buildNodes(input)
fun reset() {
nodes.forEach {
it.distance = Int.MAX_VALUE
it.shortestPath = LinkedList<Node>()
}
}
return nodes.filter { it.elevation == 'a' || it.elevation == 'S' }
.map { it.point }
.map { coordinate ->
reset()
val start = checkNotNull(nodes.find { it.point == coordinate })
val finish = checkNotNull(nodes.find { it.elevation == 'E' })
dijkstra(start)
finish.shortestPath.size
}.filter { it != 0 }.min()
}
private fun buildNodes(input: List<String>) =
input.flatMapIndexed { i, s -> s.mapIndexed { j, c -> Node(Point(i, j), c) } }.also { nodes ->
nodes.forEach { node ->
val x = node.point.x
val y = node.point.y
(listOf(x - 1, x + 1)).forEach { i ->
nodes.find { it.point == Point(i, y) }?.let {
if (canMove(node, it)) node.addDestination(it, 1)
}
}
(listOf(y - 1, y + 1)).forEach { j ->
nodes.find { it.point == Point(x, j) }?.let {
if (canMove(node, it)) node.addDestination(it, 1)
}
}
}
}
private fun canMove(currentNode: Node, adjacentNode: Node): Boolean {
val currentElevation = when (currentNode.elevation) {
'S' -> 'a'
'E' -> 'z'
else -> currentNode.elevation
}
val adjacentElevation = when (adjacentNode.elevation) {
'S' -> 'a'
'E' -> 'z'
else -> adjacentNode.elevation
}
return currentElevation >= adjacentElevation || (adjacentElevation - currentElevation) == 1
}
private fun dijkstra(source: Node) {
val lowestDistanceNode = { unsettledNodes: Set<Node> ->
var lowestDistanceNode: Node by Delegates.notNull()
var lowestDistance = Int.MAX_VALUE
unsettledNodes.forEach { node ->
val nodeDistance = node.distance
if (nodeDistance < lowestDistance) {
lowestDistance = nodeDistance
lowestDistanceNode = node
}
}
lowestDistanceNode
}
val calculateMinimumDistance = { evaluationNode: Node, edgeWeight: Int, sourceNode: Node ->
val sourceDistance = sourceNode.distance
if (sourceDistance + edgeWeight < evaluationNode.distance) {
evaluationNode.distance = sourceDistance + edgeWeight
val shortestPath = LinkedList(sourceNode.shortestPath)
shortestPath.add(sourceNode)
evaluationNode.shortestPath = shortestPath
}
}
source.distance = 0
val settledNodes = mutableSetOf<Node>()
val unsettledNodes = mutableSetOf<Node>()
unsettledNodes.add(source)
while (unsettledNodes.size != 0) {
val currentNode = lowestDistanceNode(unsettledNodes)
unsettledNodes.remove(currentNode)
currentNode.adjacentNodes.forEach { (adjacentNode, edgeWeight) ->
if (adjacentNode !in settledNodes) {
calculateMinimumDistance(adjacentNode, edgeWeight, currentNode)
unsettledNodes.add(adjacentNode)
}
}
settledNodes.add(currentNode)
}
}
private data class Node(val point: Point, val elevation: Char) {
var shortestPath = LinkedList<Node>()
var distance = Int.MAX_VALUE
val adjacentNodes = mutableMapOf<Node, Int>()
fun addDestination(destination: Node, distance: Int) {
adjacentNodes[destination] = distance
}
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 4,821 | advent-of-code | MIT License |
neuro/src/main/java/com/bukalapak/neuro/Nucleus.kt | bukalapak | 167,192,746 | false | null | package com.bukalapak.neuro
import java.util.Locale
sealed class Nucleus(val id: String) : Comparable<Nucleus> {
// pattern to expression, sort descending from the longest pattern
private val schemePatterns: List<Pair<Regex, String>> by lazy {
schemes.map {
val lowerCase = it.toLowerCase(Locale.ROOT) // make it lowercase
lowerCase.toPattern() to lowerCase
}.sortedByDescending { it.first }.map { Regex(it.first) to it.second }
}
// pattern to expression, sort descending from the longest pattern
private val hostPatterns: List<Pair<Regex, String>> by lazy {
hosts.map {
val lowerCase = it.toLowerCase(Locale.ROOT) // make it lowercase
lowerCase.toPattern() to lowerCase
}.sortedByDescending { it.first }.map { Regex(it.first) to it.second }
}
// only return boolen
internal fun isMatch(
scheme: String?,
host: String?,
port: Int
): Boolean {
val hostMatch = hostPatterns.isEmpty() || hostPatterns.any {
it.first.matches(host ?: "")
}
if (!hostMatch) return false
val schemeMatch = schemePatterns.isEmpty() || schemePatterns.any {
it.first.matches(scheme ?: "")
}
if (!schemeMatch) return false
val portMatch = ports.isEmpty() || ports.contains(port)
if (!portMatch) return false
// all passed, means all is match
return true
}
// return matched nucleus
internal fun nominate(
scheme: String?,
host: String?,
port: Int
): Chosen? {
val chosenHost = if (hostPatterns.isEmpty()) null
else hostPatterns.find {
it.first.matches(host ?: "")
}?.second
val chosenScheme = if (schemePatterns.isEmpty()) null
else schemePatterns.find {
it.first.matches(scheme ?: "")
}?.second
val chosenPort = if (ports.isEmpty()) null else port
// all passed, means all is match
return Chosen(this, chosenScheme, chosenHost, chosenPort)
}
internal val memberCount: Int by lazy {
val schemeSize = if (schemes.isEmpty()) 1 else schemes.size
val hostSize = if (hosts.isEmpty()) 1 else hosts.size
val portSize = if (ports.isEmpty()) 1 else ports.size
schemeSize * hostSize * portSize
}
/**
* Priorities:
* #1 lowest priority number
* #2 highest member count
* #3 alphabetically by id
*/
final override fun compareTo(other: Nucleus): Int {
val priority1 = priority
val priority2 = other.priority
return if (priority1 == priority2) {
val memberCount1 = memberCount
val memberCount2 = other.memberCount
if (memberCount1 == memberCount2) {
val id1 = id
val id2 = other.id
id1.compareTo(id2)
} else memberCount2 - memberCount1
} else priority1 - priority2
}
// empty means may be included or not
open val schemes: List<String> = emptyList()
// empty means may be included or not
open val hosts: List<String> = emptyList()
// empty means may be included or not
open val ports: List<Int> = emptyList()
open val priority: Int = DEFAULT_PRIORITY
class Chosen(
val nucleus: Nucleus,
val scheme: String?,
val host: String?,
val port: Int?
)
final override fun toString(): String = id
final override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is Nucleus) return false
return id == other.id
}
final override fun hashCode(): Int = 31 * id.hashCode()
companion object {
const val DEFAULT_PRIORITY = 100
}
}
abstract class Soma(id: String) : Nucleus(id) {
internal val noBranchAction: AxonBranch by lazy {
AxonBranch(EXPRESSION_NO_BRANCH) {
onProcessNoBranch(it)
}
}
internal val noBranchWithSlashAction: AxonBranch by lazy {
AxonBranch(EXPRESSION_NO_BRANCH_WITH_SLASH) {
onProcessNoBranch(it)
}
}
internal val otherBranchAction: AxonBranch by lazy {
AxonBranch(EXPRESSION_OTHER_BRANCH) {
onProcessOtherBranch(it)
}
}
// do return false if you want to forward action to AxonBranch
open fun onSomaProcess(signal: Signal): Boolean = false
// onSomaProcess must return false to be processed here
open fun onProcessNoBranch(signal: Signal) = Unit
// onSomaProcess must return false to be processed here
open fun onProcessOtherBranch(signal: Signal) = Unit
companion object {
const val EXPRESSION_NO_BRANCH = ""
const val EXPRESSION_NO_BRANCH_WITH_SLASH = "/"
const val EXPRESSION_OTHER_BRANCH = "/<path:.+>"
}
}
abstract class SomaOnly(id: String) : Nucleus(id) {
abstract fun onSomaProcess(signal: Signal)
}
abstract class SomaFallback : SomaOnly(ID) {
final override val schemes = super.schemes
final override val hosts = super.hosts
final override val ports = super.ports
final override val priority: Int = Int.MAX_VALUE
companion object {
const val ID = "*"
}
} | 0 | Kotlin | 6 | 24 | b6707ad6f682bbd929febdd39054f10c57b1b12d | 5,323 | neuro | Apache License 2.0 |
src/main/kotlin/d9_SmokeBasin/SmokeBasin.kt | aormsby | 425,644,961 | false | {"Kotlin": 68415} | package d9_SmokeBasin
import util.Coord
import util.Input
import util.Output
val caveTopo = Input.parseLines(filename = "/input/d9_caves_topo_map.txt").map {
Input.parseToListOf<Int>(rawData = it)
}
// topo map bounds and helper
val numCol = caveTopo[0].size
val numRow = caveTopo.size
val adjInd = Pair(-1, 1)
// for part 2
val checkedCoords = mutableListOf<Coord>()
fun main() {
Output.day(9, "Smoke Basin")
val startTime = Output.startTime()
// Part 1
val lowPointsMap = mutableMapOf<Coord, Int>()
caveTopo.forEachIndexed { r, rowList ->
rowList.forEachIndexed { c, colVal ->
val horiz = adjInd.clampToPos(c, numCol)
val vert = adjInd.clampToPos(r, numRow)
if (isLowPoint(r, c, horiz, vert))
lowPointsMap[Coord(x = r, y = c)] = colVal
}
}
Output.part(1, "Sum of Low Point Risk Levels", lowPointsMap.values.sumOf { it + 1 })
// Part 2
val basinMap = lowPointsMap.keys.associateWith { 1 } as MutableMap
// expand outward from all lowest points and count number of non-9 spaces
basinMap.keys.forEach { point ->
checkedCoords.add(point)
basinMap[point] = point.expand()
checkedCoords.clear()
}
Output.part(2, "Sum of Basin Sizes",
basinMap.values.sorted().takeLast(3).reduce { acc, n -> acc * n })
Output.executionTime(startTime)
}
/**
* Checks adjacent coordinates to find out if provided point is the lowest
*/
fun isLowPoint(r: Int, c: Int, h: Pair<Int, Int>, v: Pair<Int, Int>): Boolean {
val heights = mutableListOf(
caveTopo[r][c]
)
if (r + v.first != r)
heights.add(caveTopo[r + v.first][c])
if (r + v.second != r)
heights.add(caveTopo[r + v.second][c])
if (c + h.first != c)
heights.add(caveTopo[r][c + h.first])
if (c + h.second != c)
heights.add(caveTopo[r][c + h.second])
val min = heights.minOrNull()
return heights.count { it == min } == 1 && heights[0] == min
}
/**
* Clamps adjacent coordinates to bounds of 2d list
*/
fun Pair<Int, Int>.clampToPos(i: Int, len: Int): Pair<Int, Int> =
when (i) {
0 -> Pair(0, this.second)
len - 1 -> Pair(this.first, 0)
else -> this
}
/**
* Returns size of expanded basin
*/
fun Coord.expand(): Int {
val v = adjInd.clampToPos(this.x, numRow)
val h = adjInd.clampToPos(this.y, numCol)
val listAdj = mutableListOf<Coord>()
var count = 0
if (this.x + v.first != this.x)
listAdj.add(Coord(x = this.x + v.first, y = this.y))
if (this.x + v.second != this.x)
listAdj.add(Coord(x = this.x + v.second, y = this.y))
if (this.y + h.first != this.y)
listAdj.add(Coord(x = this.x, y = this.y + h.first))
if (this.y + h.second != this.y)
listAdj.add(Coord(x = this.x, y = this.y + h.second))
val next = listAdj.filter { caveTopo[it.x][it.y] != 9 && it !in checkedCoords }
checkedCoords.addAll(next)
next.forEach {
count += it.expand()
}
return count + 1
}
| 0 | Kotlin | 1 | 1 | 193d7b47085c3e84a1f24b11177206e82110bfad | 3,081 | advent-of-code-2021 | MIT License |
src/main/kotlin/com/github/davio/aoc/y2022/Day5.kt | Davio | 317,510,947 | false | {"Kotlin": 405939} | package com.github.davio.aoc.y2022
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.getInputAsSequence
import com.github.davio.aoc.general.split
import kotlin.system.measureTimeMillis
fun main() {
println(Day5.getResultPart1())
measureTimeMillis {
println(Day5.getResultPart2())
}.also { println("Took $it ms") }
}
/**
* See [Advent of Code 2022 Day 5](https://adventofcode.com/2022/day/5#part2])
*/
object Day5 : Day() {
private data class Move(val amount: Int, val from: Int, val to: Int)
private fun parseInput(): Pair<List<MutableList<String>>, List<Move>> {
val parts = getInputAsSequence()
.split(String::isBlank)
.toList()
val stackLines = parts.first()
val noOfColumns = stackLines.last().split(" ").last().toInt()
val stacks = (0 until noOfColumns).map {
mutableListOf<String>()
}.toList()
stackLines.take(stackLines.size - 1).forEach { line ->
repeat(noOfColumns) { columnNo ->
val startIndex = columnNo * 3 + columnNo + 1
if (startIndex > line.lastIndex) {
return@repeat
}
val crate = line.substring(startIndex, startIndex + 1)
if (crate != " ") {
stacks[columnNo].add(crate)
}
}
}
val moveRegex = Regex("""move (\d+) from (\d+) to (\d+)""")
val moves = parts.last().map { line ->
val (amount, from, to) = moveRegex.matchEntire(line)!!.destructured
Move(amount.toInt(), from.toInt(), to.toInt())
}
return stacks to moves
}
fun getResultPart1(): String {
val (stacks, moves) = parseInput()
fun moveCrates(move: Move) {
repeat(move.amount) {
stacks[move.to - 1].add(0, stacks[move.from - 1].removeAt(0))
}
}
moves.forEach { moveCrates(it) }
return stacks.joinToString(separator = "") { it.firstOrNull() ?: "" }
}
fun getResultPart2(): String {
val (stacks, moves) = parseInput()
fun moveCrates(move: Move) {
val fromStack = stacks[move.from - 1]
stacks[move.to - 1].addAll(0, fromStack.take(move.amount))
repeat(move.amount) {
fromStack.removeFirst()
}
}
moves.forEach { moveCrates(it) }
return stacks.joinToString(separator = "") { it.firstOrNull() ?: "" }
}
}
| 1 | Kotlin | 0 | 0 | 4fafd2b0a88f2f54aa478570301ed55f9649d8f3 | 2,555 | advent-of-code | MIT License |
src/main/kotlin/com/github/dangerground/aoc2020/Day5.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
import kotlin.math.pow
class Day5(input: List<String>) {
val seats = input.map { Seat(it) }
fun highestSeadId(): Int {
return seats.maxOf { it.getId() }
}
fun mySeatId(): Int {
val seatIds = seats.map { it.getId() }
val candidates = seatIds.filter { !seatIds.contains(it - 1) }.map { it - 1 }
return seatIds.filter { candidates.contains(it + 1) && !seatIds.contains(it + 1) }
.map { it + 1 }
.first()
}
}
class Seat(input: String) {
val row = getNumber(input, 0, 7, 'B')
val column = getNumber(input, 7, 3, 'R')
private fun getNumber(input: String, lower: Int, length: Int, high: Char): Int {
val upper = lower + length
return input.substring(lower, upper).mapIndexed { index, c ->
if (c == high) {
2.0.pow(length.toDouble() - 1 - index)
} else {
0
}
}.sumOf { it.toInt() }
}
fun getId() = row * 8 + column
override fun toString(): String {
return "Seat(id=${getId()})"
}
}
fun main() {
val input = DayInput.asStringList(5)
val day5 = Day5(input)
// part 1
val part1 = day5.highestSeadId()
println("result part 1: $part1")
// part2
val part2 = day5.mySeatId()
println("result part 2: $part2")
} | 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 1,434 | adventofcode-2020 | MIT License |
src/main/kotlin/_2023/Day05.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2023
import Day
import InputReader
import rangeIntersect
data class RangeToValue(
val range: LongRange,
val value: Long
)
class Day05 : Day(2023, 5) {
override val firstTestAnswer: Long = 35L
override val secondTestAnswer = 46L
override fun first(input: InputReader): Long {
val almanac = input.asGroups().toMutableList()
val seeds = almanac.removeFirst().first()
return numRegex.findAll(seeds).map {
val seedId = it.value.toLong()
almanac.fold(seedId) { result, map ->
val range = map.drop(1).map { str ->
val (value, start, rangeSize) = str.trim().split(" ").map { value -> value.toLong() }
RangeToValue(start until start + rangeSize, value)
}.firstOrNull { range -> range.range.contains(result) } ?: return@fold result
result - range.range.first + range.value
}
}.min()
}
override fun second(input: InputReader): Long {
val almanac = input.asGroups().toMutableList()
val seeds = almanac.removeFirst().first()
val seedsRanges =
seeds.drop(7).split(" ").chunked(2)
.map { it.first().trim().toLong() until it.first().toLong() + it.last().trim().toLong() }
return seedsRanges.map { seedRange ->
almanac.fold(listOf(seedRange)) { result, map ->
var leftovers = result
val ranges = map.drop(1).map { str ->
val (value, start, rangeSize) = str.trim().split(" ").map { value -> value.toLong() }
RangeToValue(start until start + rangeSize, value)
}
val finish = result.flatMap { currentRange ->
ranges.mapNotNullTo(mutableListOf()) { range ->
val intersect = (range.range rangeIntersect currentRange)
?: return@mapNotNullTo null
if (intersect.isEmpty()) {
return@mapNotNullTo null
}
return@mapNotNullTo LongRange(
intersect.first - range.range.first + range.value,
intersect.last() - range.range.first + range.value
).also {
leftovers = leftovers.flatMap { range ->
val rangeIntersect =
(range rangeIntersect intersect)
if (rangeIntersect == null) {
listOf(range)
} else {
val first = LongRange(range.first(), rangeIntersect.first() - 1L)
val second = LongRange(rangeIntersect.last() + 1L, range.last())
listOfNotNull(first, second).filter { !it.isEmpty() }
}
}
}
}
} + leftovers
finish
}.minOf {
it.first
}
}.min()
}
}
fun main() {
Day05().solve(skipTest = true)
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 3,345 | advent-of-code | Apache License 2.0 |
advent-of-code2015/src/main/kotlin/day15/Advent15.kt | REDNBLACK | 128,669,137 | false | null | package day15
import mul
import parseInput
import splitToLines
/**
--- Day 15: Science for Hungry People ---
Today, you set out on the task of perfecting your milk-dunking cookie recipe. All you have to do is find the right balance of ingredients.
Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a list of the remaining ingredients you could use to finish the recipe (your puzzle input) and their properties per teaspoon:
capacity (how well it helps the cookie absorb milk)
durability (how well it keeps the cookie intact when full of milk)
flavor (how tasty it makes the cookie)
texture (how it improves the feel of the cookie)
calories (how many calories it adds to the cookie)
You can only measure ingredients in whole-teaspoon amounts accurately, and you have to be accurate so you can reproduce your results in the future. The total score of a cookie can be found by adding up each of the properties (negative totals become 0) and then multiplying together everything except calories.
For instance, suppose you have these two ingredients:
Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3
Then, choosing to use 44 teaspoons of butterscotch and 56 teaspoons of cinnamon (because the amounts of each ingredient must add up to 100) would result in a cookie with the following properties:
A capacity of 44*-1 + 56*2 = 68
A durability of 44*-2 + 56*3 = 80
A flavor of 44*6 + 56*-2 = 152
A texture of 44*3 + 56*-1 = 76
Multiplying these together (68 * 80 * 152 * 76, ignoring calories for now) results in a total score of 62842880, which happens to be the best score possible given these ingredients. If any properties had produced a negative total, it would have instead become zero, causing the whole score to multiply to zero.
Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make?
--- Part Two ---
Your cookie recipe becomes wildly popular! Someone asks if you can make another recipe that has exactly 500 calories per cookie (so they can use it as a meal replacement). Keep the rest of your award-winning process the same (100 teaspoons, same ingredients, same scoring system).
For example, given the ingredients above, if you had instead selected 40 teaspoons of butterscotch and 60 teaspoons of cinnamon (which still adds to 100), the total calorie count would be 40*8 + 60*3 = 500. The total score would go down, though: only 57600000, the best you can do in such trying circumstances.
Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make with a calorie total of 500?
*/
fun main(args: Array<String>) {
val test = """
|Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
|Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3
""".trimMargin()
val input = parseInput("day15-input.txt")
println(findBestCombination(test) == 62842880)
println(findBestCombination(test, 500) == 57600000)
println(findBestCombination(input))
println(findBestCombination(input, 500))
}
fun findBestCombination(input: String, maxCalories: Int = 0): Int? {
val maxTeaspoons = 100
val ingredients = parseIngredients(input)
fun mixtures(size: Int, max: Int, acc: MutableList<List<Int>> = mutableListOf()): List<List<Int>> {
val start = if (size == 1) max else 0
for (i in start..max) {
val left = max - i
if (size - 1 > 0) {
mixtures(size - 1, left).mapTo(acc) { it + i }
} else {
acc.add(listOf(i))
}
}
return acc
}
fun score(recipe: List<Int>, maxCalories: Int): Int {
val proportions = ingredients.map { it.toList() }
.zip(recipe)
.map { p -> p.first.map { it * p.second } }
val dough = proportions.reduce { a, b -> a.zip(b).map { it.toList().sum() } }
val calories = dough.last()
val result = dough.dropLast(1).map { Math.max(it, 0) }.mul()
return if (maxCalories != 0) (if (calories == maxCalories) result else 0) else result
}
return mixtures(ingredients.size, maxTeaspoons).map { score(it, maxCalories) }.max()
}
data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
) {
fun toList() = listOf(capacity, durability, flavor, texture, calories)
}
private fun parseIngredients(input: String) = input.splitToLines()
.map {
val name = it.split(":", limit = 2).first()
val (capacity, durability, flavor, texture, calories) = Regex("""(-?\d+)""")
.findAll(it)
.map { it.groupValues[1] }
.map(String::toInt)
.toList()
Ingredient(name, capacity, durability, flavor, texture, calories)
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 5,143 | courses | MIT License |
src/main/kotlin/aoc2023/Day17.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2023
import AoCDay
import aoc2023.Day17.Dir.*
import util.Vec2
import util.plus
import java.util.*
// https://adventofcode.com/2023/day/17
object Day17 : AoCDay<Int>(
title = "Clumsy Crucible",
part1ExampleAnswer = 102,
part1Answer = 953,
part2ExampleAnswer = 94,
part2Answer = 1180,
) {
private enum class Dir(val vec: Vec2) {
UP(Vec2(0, -1)),
DOWN(Vec2(0, 1)),
RIGHT(Vec2(1, 0)),
LEFT(Vec2(-1, 0)),
}
private fun leastHeatLoss(input: String, minBeforeTurn: Int, maxConsecutive: Int): Int {
class Path(val heatLoss: Int, val pos: Vec2, val dir: Dir, val consecutive: Int)
fun Path.seenKey() = Triple(pos, dir, consecutive)
val heatLossMap = input.lines().map { line -> line.map { it - '0' } }
val destination = Vec2(x = heatLossMap.first().lastIndex, y = heatLossMap.lastIndex)
val xs = 0..destination.x
val ys = 0..destination.y
val paths = PriorityQueue(compareBy(Path::heatLoss)).apply {
add(Path(heatLoss = heatLossMap[0][1], pos = Vec2(1, 0), dir = RIGHT, consecutive = 1))
add(Path(heatLoss = heatLossMap[1][0], pos = Vec2(0, 1), dir = DOWN, consecutive = 1))
}
val seen = HashSet(paths.map(Path::seenKey))
while (true) {
val path = paths.remove()
if (path.pos == destination && path.consecutive >= minBeforeTurn) return path.heatLoss
fun go(dir: Dir, consecutive: Int) {
val pos = path.pos + dir.vec
if (pos.x in xs && pos.y in ys) {
val p = Path(heatLoss = path.heatLoss + heatLossMap[pos.y][pos.x], pos, dir, consecutive)
if (seen.add(p.seenKey())) paths.add(p)
}
}
if (path.consecutive < maxConsecutive) go(path.dir, consecutive = path.consecutive + 1)
if (path.consecutive >= minBeforeTurn) when (path.dir) {
UP, DOWN -> {
go(LEFT, consecutive = 1)
go(RIGHT, consecutive = 1)
}
RIGHT, LEFT -> {
go(UP, consecutive = 1)
go(DOWN, consecutive = 1)
}
}
}
}
override fun part1(input: String) = leastHeatLoss(input, minBeforeTurn = 0, maxConsecutive = 3)
override fun part2(input: String) = leastHeatLoss(input, minBeforeTurn = 4, maxConsecutive = 10)
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 2,482 | advent-of-code-kotlin | MIT License |
src/main/kotlin/kr/co/programmers/P159993.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
import java.util.*
// https://github.com/antop-dev/algorithm/issues/497
class P159993 {
fun solution(maps: Array<String>): Int {
// 시작 지점, 레버, 출구 위치를 찾는다
val pos = IntArray(6)
for (i in maps.indices) {
for (j in maps[i].indices) {
when (maps[i][j]) {
'S' -> {
pos[0] = i
pos[1] = j
}
'L' -> {
pos[2] = i
pos[3] = j
}
'E' -> {
pos[4] = i
pos[5] = j
}
}
}
}
// 시작지점 -> 레버
val move1 = move(maps, intArrayOf(pos[0], pos[1]), intArrayOf(pos[2], pos[3]))
if (move1 == -1) return -1
// 레버 -> 출구
val move2 = move(maps, intArrayOf(pos[2], pos[3]), intArrayOf(pos[4], pos[5]))
if (move2 == -1) return -1
return move1 + move2
}
private val dy = intArrayOf(-1, 0, 1, 0)
private val dx = intArrayOf(0, 1, 0, -1)
private fun move(maps: Array<String>, start: IntArray, end: IntArray): Int {
println()
val n = maps.size
val m = maps[0].length
val visited = Array(n) { IntArray(m) }
val queue = LinkedList<IntArray>()
queue.add(start)
var move = 0
while (queue.isNotEmpty()) {
// 큐 안에 들어있는 모든 위치를 다 이동해야 한번 움직인 것이다
val size = queue.size
repeat(size) {
val (y, x) = queue.poll()
// 목적지에 도착
if (y == end[0] && x == end[1]) return move
// 4방향으로 이동 예약
dy.zip(dx) { a, b ->
val nextY = y + a
val nextX = x + b
// 북,동,남,서 방향으로 이동할 수 있는지 체크
if (nextY in 0 until n
&& nextX in 0 until m
&& visited[nextY][nextX] == 0
&& maps[nextY][nextX] != 'X'
) { // 이동할 수 있다
// 방문 체크를 미리 한다.
// 이래야 시간초과가 안난다.
visited[nextY][nextX] = 1
queue += intArrayOf(nextY, nextX)
}
}
}
move++
}
return -1
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 2,666 | algorithm | MIT License |
2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day03.kt | codelicia | 627,407,402 | false | {"Kotlin": 49578, "PHP": 554, "Makefile": 293} | package com.codelicia.advent2021
import java.util.SortedMap
class Day03(private val input: List<String>) {
private val bitLength = input.first().length
private fun List<Int>.toInt() =
this.joinToString("").toInt(2)
private fun List<Int>.gamma() = this.toInt()
private fun List<Int>.epsilon() = this.map(::invertBit).toInt()
private fun SortedMap<Int, Int>.bit(): Int =
if (this.getValue(0) > this.getValue(1)) 0 else 1
private fun SortedMap<Int, Int>.invBit(): Int =
if (this.getValue(0) > this.getValue(1)) 1 else 0
private fun Set<String>.countBits(n: Int): List<SortedMap<Int, Int>> =
listOf(
this.map { v -> v[n].digitToInt() }
.groupingBy { it }
.eachCount()
.toSortedMap()
)
private val diagnosticReport = buildList {
repeat(bitLength) { i ->
val mostCommonBit = input
.groupingBy { it[i].digitToInt() }
.eachCount()
.maxBy { it.value }
.key
add(mostCommonBit)
}
}
private fun invertBit(n: Int) = if (n == 1) 0 else 1
private fun calculateRating(
remainingNumbers: Set<String>,
predicate: (String, Int, List<SortedMap<Int, Int>>) -> Boolean,
index: Int = 0,
): Int {
if (remainingNumbers.count() == 1) return remainingNumbers.first().toInt(radix = 2)
val sortedList = remainingNumbers.countBits(index)
val filteredNumbers = remainingNumbers.filterNot { v -> predicate(v, index, sortedList) }.toSet()
return calculateRating(filteredNumbers, predicate, index + 1)
}
fun part1(): Int = diagnosticReport.gamma() * diagnosticReport.epsilon()
fun part2(): Int {
val binaryNumbers = input.toSet()
val co2ScrubberRating = calculateRating(
binaryNumbers,
{ v, n, sl -> v[n].digitToInt() == sl[0].invBit() }
)
val oxygenGeneratorRating = calculateRating(
binaryNumbers,
{ v, n, sl -> v[n].digitToInt() == sl[0].bit() }
)
return oxygenGeneratorRating * co2ScrubberRating
}
} | 2 | Kotlin | 0 | 0 | df0cfd5c559d9726663412c0dec52dbfd5fa54b0 | 2,211 | adventofcode | MIT License |
2022/Day19.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
data class Blueprint(
val id: Int,
val oreRobotCostOre: Int,
val clayRobotCostOre: Int,
val obsidianRobotCost: Pair<Int, Int>,
val geodeRobotCost: Pair<Int, Int>,
)
val blueprints = readInput("Day19").mapIndexed { index, line ->
val parts = line.split("Blueprint ", ": Each ore robot costs ", ". Each clay robot costs ", ". Each obsidian robot costs ", ". Each geode robot costs ").filter { it.isNotEmpty() }
assert(parts.size == 5) { parts }
assert(parts[0].toInt() == index + 1) { parts[0] }
fun parseCost2(s: String) = s.split(" ore and ", " clay", " obsidian.").filter { it.isNotEmpty() }.map { it.toInt() }.let { it[0] to it[1] }
Blueprint(
index+1,
parts[1].removeSuffix(" ore").toInt(),
parts[2].removeSuffix(" ore").toInt(),
parseCost2(parts[3]),
parseCost2(parts[4]),
)
}
fun solve(b: Blueprint, timeLimit: Int): Int {
data class State(
val res: IntArray,
val robots: IntArray
) {
fun pass1min() = State(res1min(), robots)
fun res1min() = intArrayOf(res[0] + robots[0], res[1] + robots[1], res[2] + robots[2], res[3] + robots[3])
fun incRobots(ir: Int) = robots.clone().also { it[ir] ++ }
fun geodesMin(t: Int) = res[3] + t * robots[3]
fun geodesMax(t: Int) = res[3] + t*(robots[3] + robots[3]+t-1)/2
fun buyRobots(): List<State> {
val states = mutableListOf<State>()
if (res[0] >= b.oreRobotCostOre) {
val res1 = res1min()
res1[0] -= b.oreRobotCostOre
states.add(State(res1, incRobots(0)))
}
if (res[0] >= b.clayRobotCostOre) {
val res1 = res1min()
res1[0] -= b.clayRobotCostOre
states.add(State(res1, incRobots(1)))
}
if (res[0] >= b.obsidianRobotCost.first && res[1] >= b.obsidianRobotCost.second) {
val res1 = res1min()
res1[0] -= b.obsidianRobotCost.first
res1[1] -= b.obsidianRobotCost.second
states.add(State(res1, incRobots(2)))
}
if (res[0] >= b.geodeRobotCost.first && res[2] >= b.geodeRobotCost.second) {
val res1 = res1min()
res1[0] -= b.geodeRobotCost.first
res1[2] -= b.geodeRobotCost.second
states.add(State(res1, incRobots(3)))
}
return states
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as State
if (!res.contentEquals(other.res)) return false
if (!robots.contentEquals(other.robots)) return false
return true
}
override fun hashCode(): Int {
var result = res.contentHashCode()
result = 31 * result + robots.contentHashCode()
return result
}
}
val states = HashMap<State, Int>()
val queue = ArrayDeque<State>()
State(intArrayOf(0,0,0,0), intArrayOf(1,0,0,0)).let {
states[it] = 0
queue.add(it)
}
var maxGeodes = 0
var maxTime = 0
while (queue.isNotEmpty()) {
val s0 = queue.removeFirst()
val time = states[s0]!!
maxGeodes = maxOf(maxGeodes, s0.geodesMin(timeLimit - time))
if (time > maxTime) {
maxTime = time
print(".$maxTime")
}
if (time >= timeLimit) continue
if (s0.geodesMax(timeLimit - time) <= maxGeodes) continue
val s1 = s0.pass1min()
if (states.putIfAbsent(s1, time+1) == null) {
queue.add(s1)
}
for (s2 in s0.buyRobots()) {
if (states.putIfAbsent(s2, time+1) == null) {
queue.add(s2)
}
}
}
return maxGeodes
}
val res1 = blueprints.sumOf {
println("Blueprint #${it.id}")
val geodes = solve(it, 24)
println("\ngeodes=${geodes}")
it.id * geodes
}
println("\nPart1:")
println(res1)
val res2 = blueprints.take(3).map {
println("Blueprint #${it.id}")
val geodes = solve(it, 32)
println("\ngeodes=${geodes}")
geodes
}
println("Part2:")
println(res2[0] * res2[1] * res2[2])
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 4,786 | advent-of-code-kotlin | Apache License 2.0 |
src/day05/Day05.kt | iulianpopescu | 572,832,973 | false | {"Kotlin": 30777} | package day05
import readInput
private const val DAY = "05"
private const val DAY_TEST = "day${DAY}/Day${DAY}_test"
private const val DAY_INPUT = "day${DAY}/Day${DAY}"
fun main() {
fun parseInput(input: List<String>): Pair<List<Stack>, List<Move>> {
val numberOfStacks = input.first().length / 4 + 1
val stacks = Array(numberOfStacks) { Stack() }
var lineIndex = 0
// parse initial arrangement
while (!input[lineIndex].startsWith(" 1")) {
for (j in input[lineIndex].indices step 4) {
if (input[lineIndex][j] == ' ') continue
stacks[j / 4].items.add(0, input[lineIndex][j + 1])
}
lineIndex++
}
// skip stack index and empty line
lineIndex += 2
val moves = mutableListOf<Move>()
while (lineIndex <= input.lastIndex) {
val parts = input[lineIndex].split(' ')
moves.add(Move(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1))
lineIndex++
}
return stacks.toList() to moves
}
fun part1(input: List<String>): String {
val (stacks, moves) = parseInput(input)
moves.forEach { move ->
repeat(move.itemCount) {
val item = stacks[move.start].items.removeLastOrNull()
if (item != null)
stacks[move.end].items.add(item)
}
}
return stacks.map { it.items.lastOrNull() ?: " " }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val (stacks, moves) = parseInput(input)
moves.forEach { move ->
val items = mutableListOf<Char>()
repeat(move.itemCount) {
val item = stacks[move.start].items.removeLastOrNull()
if (item != null)
items.add(0, item)
}
stacks[move.end].items.addAll(items)
}
return stacks.map { it.items.lastOrNull() ?: " " }.joinToString(separator = "")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(DAY_TEST)
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput(DAY_INPUT)
println(part1(input))
println(part2(input))
}
data class Stack(val items: MutableList<Char> = mutableListOf())
data class Move(val itemCount: Int, val start: Int, val end: Int) | 0 | Kotlin | 0 | 0 | 4ff5afb730d8bc074eb57650521a03961f86bc95 | 2,465 | AOC2022 | Apache License 2.0 |
src/Day02.kt | acrab | 573,191,416 | false | {"Kotlin": 52968} | import Opponent.Companion.toOpponent
import Player.Companion.toPlayer
import Result.Companion.toResult
import com.google.common.truth.Truth.assertThat
enum class Opponent(val key: String) {
Rock("A"),
Paper("B"),
Scissors("C");
companion object {
fun String.toOpponent() = values().first { it.key == this }
}
}
enum class Player(val key: String, val score: Int) {
Rock("X", 1),
Paper("Y", 2),
Scissors("Z", 3);
companion object {
fun String.toPlayer() = values().first { it.key == this }
}
}
enum class Result(val key: String) {
Lose("X"),
Draw("Y"),
Win("Z");
companion object {
fun String.toResult() = values().first { it.key == this }
}
}
fun main() {
fun win(with: Player) = 6 + with.score
fun draw(with: Player) = 3 + with.score
fun lose(with: Player) = 0 + with.score
fun pointsForRound(them: Opponent, us: Player): Int =
when (us) {
Player.Rock -> when (them) {
Opponent.Rock -> draw(us)
Opponent.Paper -> lose(us)
Opponent.Scissors -> win(us)
}
Player.Paper -> when (them) {
Opponent.Rock -> win(us)
Opponent.Paper -> draw(us)
Opponent.Scissors -> lose(us)
}
Player.Scissors -> when (them) {
Opponent.Rock -> lose(us)
Opponent.Paper -> win(us)
Opponent.Scissors -> draw(us)
}
}
fun symbolForWin(other: Opponent) =
when (other) {
Opponent.Rock -> Player.Paper
Opponent.Paper -> Player.Scissors
Opponent.Scissors -> Player.Rock
}
fun symbolForDraw(other: Opponent) =
when (other) {
Opponent.Rock -> Player.Rock
Opponent.Paper -> Player.Paper
Opponent.Scissors -> Player.Scissors
}
fun symbolForLoss(other: Opponent) =
when (other) {
Opponent.Rock -> Player.Scissors
Opponent.Paper -> Player.Rock
Opponent.Scissors -> Player.Paper
}
fun symbolForResult(other: Opponent, result: Result): Player =
when (result) {
Result.Lose -> symbolForLoss(other)
Result.Draw -> symbolForDraw(other)
Result.Win -> symbolForWin(other)
}
fun part1(input: List<String>): Int {
return input
.asSequence()
.map { it.split(" ") }
.sumOf { pointsForRound(it[0].toOpponent(), it[1].toPlayer()) }
}
fun part2(input: List<String>): Int {
return input.asSequence()
.map { it.split(" ") }
.map { it[0].toOpponent() to it[1].toResult() }
.sumOf { pointsForRound(it.first, symbolForResult(it.first, it.second)) }
}
val testInput = readInput("Day02_test")
assertThat(part1(testInput)).isEqualTo(15)
val input = readInput("Day02")
println(part1(input))
assertThat(part2(testInput)).isEqualTo(12)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0be1409ceea72963f596e702327c5a875aca305c | 3,095 | aoc-2022 | Apache License 2.0 |
src/day13/b/day13b.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day13.b
import readInputLines
import shouldBe
fun main() {
val msg = readInput()
val div0 = Message(listOf(Message(2)))
val div1 = Message(listOf(Message(6)))
msg.add(div0)
msg.add(div1)
msg.sort()
val i0 = msg.indexOfFirst { it === div0 } + 1
val i1 = msg.indexOfFirst { it === div1 } + 1
val answer = i0 * i1
shouldBe(23520, answer)
}
data class Message(
val list : List<*>
) : Comparable<Message> {
constructor(v: Int): this(listOf(v))
override fun toString(): String {
return list.toString()
}
override operator fun compareTo(other: Message): Int {
val it0 = this.list.iterator()
val it1 = other.list.iterator()
while (it0.hasNext() && it1.hasNext()) {
var v0 = it0.next()
var v1 = it1.next()
var d : Int
if (v0 is Int && v1 is Int) {
d = v0 - v1
} else {
if (v0 is Int) v0 = Message(v0)
if (v1 is Int) v1 = Message(v1)
v0 as Message
v1 as Message
d = v0.compareTo(v1)
}
if (d != 0) return d
}
if (it0.hasNext()) return 1
if (it1.hasNext()) return -1
return 0
}
}
fun readInput(): ArrayList<Message> {
val r = ArrayList<Message>()
val lines = readInputLines(13)
val it = lines.iterator()
while(it.hasNext()) {
val s0 = it.next()
if (s0.isBlank()) continue
val m0 = parse(s0, 0)
r.add(m0.second)
}
return r
}
fun parse(s: String, start: Int): Pair<Int, Message> {
val l = ArrayList<Any>()
var i = start+1
while (true) {
when (s[i]) {
'[' -> {
val p = parse(s, i)
i = p.first + 1
l.add(p.second)
}
']' -> return Pair(i, Message(l))
',' -> i++
else -> {
val j = i
while (s[i] in '0'..'9') i++
val v = s.substring(j, i).toInt()
l.add(v)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 2,141 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2023/Day18.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2023
import checkValue
import readInput
import kotlin.math.abs
fun main() {
val (year, day) = "2023" to "Day18"
fun parsePlan(line: String, withHex: Boolean): Pair<Pair<Int, Int>, Long> {
val dir: Int
val distance: Long
if (withHex) {
val (_, _, hexStr) = line.split(" ")
val hex = hexStr.substring(2, hexStr.length - 1)
dir = hex.last().toString().toInt(radix = 16)
distance = hex.substring(0..4).toLong(radix = 16)
} else {
val (dirStr, distanceStr, _) = line.split(" ")
dir = "RDLU".indexOf(dirStr)
distance = distanceStr.toLong()
}
val dx = when (dir) {
0 -> 0 to 1
1 -> 1 to 0
2 -> 0 to -1
else -> -1 to 0
}
return dx to distance
}
fun polygonArea(holes: List<Hole>): Double {
var area = 0.0
var ref = holes.size - 1
for ((index, hole) in holes.withIndex()) {
area += (holes[ref].row + hole.row) * (holes[ref].col - hole.col)
ref = index
}
return abs(area / 2.0)
}
fun interiorPoints(holes: List<Hole>): Long {
val area = polygonArea(holes)
return (area - holes.size / 2.0 + 1).toLong()
}
fun cubicMeters(input: List<String>, withHex: Boolean): Long {
val borderHoles = mutableListOf<Hole>()
var currentHole = Hole(0, 0)
var minRow = Long.MAX_VALUE
var minCol = Long.MAX_VALUE
var maxRow = Long.MIN_VALUE
var maxCol = Long.MIN_VALUE
input.forEach { line ->
val (dx, distance) = parsePlan(line, withHex)
for (i in 1..distance) {
currentHole = currentHole.move(dx.first, dx.second)
borderHoles.add(currentHole)
minRow = minOf(minRow, currentHole.row)
maxRow = maxOf(maxRow, currentHole.row)
minCol = minOf(minCol, currentHole.col)
maxCol = maxOf(maxCol, currentHole.col)
}
}
val interiorPoints = interiorPoints(borderHoles)
return interiorPoints + borderHoles.size
}
fun part1(input: List<String>) = cubicMeters(input, withHex = false)
fun part2(input: List<String>) = cubicMeters(input, withHex = true)
val testInput = readInput(name = "${day}_test", year = year)
val input = readInput(name = day, year = year)
checkValue(part1(testInput), 62)
println(part1(input))
checkValue(part2(testInput), 952408144115)
println(part2(input))
}
data class Hole(val row: Long, val col: Long) {
fun move(dr: Int, dc: Int) = Hole(row + dr, col + dc)
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 2,723 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch7/Problem73.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch7
import dev.bogwalk.util.maths.primeNumbers
/**
* Problem 73: Counting Fractions In A Range
*
* https://projecteuler.net/problem=73
*
* Goal: Count the elements of a sorted set of reduced proper fractions of order D (their
* denominator <= D) that lie between 1/A+1 and 1/A (both exclusive).
*
* Constraints: 1 < D < 2e6, 1 < A <= 100
*
* Reduced Proper Fraction: A fraction n/d, where n & d are positive integers, n < d, and
* gcd(n, d) == 1.
*
* Farey Sequence: A sequence of completely reduced fractions, either between 0 and 1, or which
* when in reduced terms have denominators <= N, arranged in order of increasing size.
*
* e.g. if d <= 8, the Farey sequence would be ->
* 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4,
* 4/5, 5/6, 6/7, 7/8
*
* e.g.: D = 8, A = 2
* count between 1/3 and 1/2 = 3
*/
class CountingFractionsInARange {
/**
* Solution uses recursion to count mediants between neighbours based on:
*
* p/q = (a + n)/(b + d)
*
* This is a recursive implementation of the Stern-Brocot tree binary search algorithm.
*
* There is no need to reference the numerators of these bounding fractions, so each fraction
* is represented as its Integer denominator instead of a Pair as in previous problem sets.
*
* SPEED (WORSE) 96.63ms for D = 12000, A = 2
* SPEED (BETTER) 2.22ms for D = 1e5, A = 100
* Risk of StackOverflow Error for D > 1e5.
*/
fun fareyRangeCountRecursive(d: Int, a: Int): Long = countMediants(d, a + 1, a)
/**
* Recursively counts all mediants between a lower and upper bound until the calculated
* denominator exceeds [d]. Each new mediant will replace both the lower and upper bounds in
* different recursive calls.
*/
private fun countMediants(d: Int, left: Int, right: Int): Long {
val mediantDenom = left + right
return if (mediantDenom > d) {
0L
} else {
1L + countMediants(d, left, mediantDenom) + countMediants(d, mediantDenom, right)
}
}
/**
* This an iterative implementation of the Stern-Brocot tree binary search algorithm above.
*
* SPEED (WORST) 213.63ms for D = 12000, A = 2
* SPEED (WORSE) 16.69ms for D = 1e5, A = 100
* Quadratic complexity O(N^2) makes it difficult to scale for D > 1e5.
*/
fun fareyRangeCountIterative(d: Int, a: Int): Long {
var count = 0L
var left = a + 1
var right = a
val stack = mutableListOf<Int>()
while (true) {
val mediantDenom = left + right
if (mediantDenom > d) {
if (stack.isEmpty()) break
left = right
right = stack.removeLast()
} else {
count++
stack.add(right)
right = mediantDenom
}
}
return count
}
/**
* Solution finds the number of reduced fractions less than the greater fraction 1/[a], then
* subtracts the number of reduced fractions less than 1/([a]+1) from the former. The result is
* further decremented to remove the count for the upper bound fraction itself.
*
* SPEED (BETTER) 8.97ms for D = 12000, A = 2
* SPEED (BETTER) 719.88ms for D = 2e6, A = 2
*/
fun fareyRangeCountSieve(d: Int, a: Int): Long {
return fareySieve(d, a) - fareySieve(d, a + 1) - 1
}
/**
* Finds number of reduced fractions p/q <= 1/[a] with q <= [d].
*/
private fun fareySieve(d: Int, a: Int): Long {
// every denominator q is initialised to floor(1/a * q) == floor(q/a)
val cache = LongArray(d + 1) { q -> 1L * q / a }
for (q in 1..d) {
// subtract each q's rank from all its multiples
for (m in 2 * q..d step q) {
cache[m] -= cache[q]
}
}
return cache.sum()
}
/**
* Solution based on the Inclusion-Exclusion principle.
*
* If F(N) is a Farey sequence and R(N) is a Farey sequence of reduced proper fractions, i.e.
* gcd(n, d) = 1), then the starting identity is:
*
* F(N) = {N}Sigma{m=1}(R(floor(N/m)))
*
* Using the Mobius inversion formula, this becomes:
*
* R(N) = {N}Sigma{m=1}(mobius(m) * F(floor(N/m)))
*
* If all Mobius function values were pre-generated, this would allow a O(N) loop. Instead,
* R(N) is calculated using primes and the inclusion-exclusion principle.
*
* N.B. This solution does not translate well if A != 2.
*
* SPEED (BEST) 5.43ms for D = 12000, A = 2
* SPEED (BEST) 167.49ms for D = 2e6, A = 2
*/
fun fareyRangeCountIE(d: Int, a: Int): Long {
require(a == 2) { "Solution does not work if A != 2" }
val primes = primeNumbers(d)
val numOfPrimes = primes.size
fun inclusionExclusion(limit: Int, index: Int): Long {
var count = numOfFractionsInRange(limit)
var i = index
while (i < numOfPrimes && 5 * primes[i] <= limit) {
val newLimit = limit / primes[i]
count -= inclusionExclusion(newLimit, ++i)
}
return count
}
return inclusionExclusion(d, 0)
}
/**
* Counts the number of fractions between 1/3 and 1/2 based on the formula:
*
* F(N) = {N}Sigma{m=1}(R(floor(N/m)))
*
* This can be rewritten to assist finding R(N) in the calling function:
*
* F(m) = {m}Sigma{n=1}(floor((n-1)/2) - floor(n/3))
*
* F(m) = q(3q - 2 + r) + { if (r == 5) 1 else 0 }
*
* where m = 6q + r and r in [0, 6).
*
* This helper function has not been adapted to allow different values of A. Once the lcm of
* A and A+1 is found, the above F(m) equation needs to be solved for q and r to determine
* the coefficients for the final function. How to do so programmatically for any input A has
* not yet been achieved.
*/
private fun numOfFractionsInRange(limit: Int): Long {
val q = limit / 6
val r = limit % 6
var f = 1L * q * (3 * q - 2 + r)
if (r == 5) f++
return f
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 6,352 | project-euler-kotlin | MIT License |
src/Day07.kt | gojoel | 573,543,233 | false | {"Kotlin": 28426} | import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
fun main() {
val input = readInput("07")
// val input = readInput("07_test")
data class File(val name: String, val size: Int)
fun parseDirFiles(input: List<String>) : HashMap<String, ArrayList<File>> {
val dirStack: Stack<String> = Stack()
val dirMap: HashMap<String, ArrayList<File>> = hashMapOf()
input.forEach { cmd ->
if (cmd.startsWith("$ cd")) {
val dir = cmd.split(" ")[2].trim()
if (dir == "..") {
if (dirStack.size != 1) {
dirStack.pop()
}
} else {
val key = if (dirStack.size <= 1) { dir } else { "${dirStack.peek()}/$dir" }
dirStack.push(key)
}
// println(dirStack)
} else if (!cmd.startsWith("$") && !cmd.startsWith("dir")) {
val fileSplit = cmd.split(" ")
for (dir in dirStack) {
val dirFiles = dirMap.getOrElse(dir) { arrayListOf() }
dirFiles.add(File(fileSplit[1], fileSplit[0].toInt()))
dirMap[dir] = dirFiles
}
}
}
return dirMap
}
fun directorySize(dirMap: HashMap<String, ArrayList<File>>) : HashMap<String, Int> {
val sizeMap: HashMap<String, Int> = hashMapOf()
dirMap.keys.forEach { key ->
dirMap[key]?.let { files ->
val size = files.sumOf { file -> file.size }
sizeMap[key] = size
}
}
return sizeMap
}
fun part1(input: List<String>) : Int {
return directorySize(parseDirFiles(input)).values.filter { size -> size <= 100000 }
.sum()
}
fun part2(input: List<String>): Int {
val usedSpace = directorySize(parseDirFiles(input))
val freeSpace = 70000000 - (usedSpace["/"] ?: 0)
val neededSpace = 30000000 - freeSpace
return usedSpace.filter { entry -> entry.value >= neededSpace }
.values.minOf { it }
}
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0690030de456dad6dcfdcd9d6d2bd9300cc23d4a | 2,236 | aoc-kotlin-22 | Apache License 2.0 |
src/Day01.kt | cisimon7 | 573,872,773 | false | {"Kotlin": 41406} | fun main() {
fun part1(elves: List<List<Int>>): Pair<Int, Long> {
val maxElf = elves.maxBy { it.sum() }
val idx = elves.indexOf(maxElf) + 1
return idx to maxElf.sum().toLong()
}
fun part2(elves: List<List<Int>>): Int {
return elves.map { it.sum() }.sortedDescending().take(3).sum()
}
fun parse(stringList: List<String>): List<List<Int>> {
var input = stringList
return generateSequence {
val items = input.takeWhile { it.isNotBlank() }.map { it.toInt() }
input = input.drop(items.size + 1)
items.ifEmpty { null }
}.toList()
}
val testInput = readInput("Day01_test")
check(part1(parse(testInput)) == (4 to 24_000L))
check(part2(parse(testInput)) == 45_000)
val input = readInput("Day01_input")
println(part1(parse(input)))
println(part2(parse(input)))
}
| 0 | Kotlin | 0 | 0 | 29f9cb46955c0f371908996cc729742dc0387017 | 897 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day08/Day08.kt | dustinconrad | 572,737,903 | false | {"Kotlin": 100547} | package day08
import geometry.Coord
import geometry.down
import geometry.left
import geometry.right
import geometry.up
import readResourceAsBufferedReader
fun main() {
println("part 1: ${part1(readResourceAsBufferedReader("8_1.txt").readLines())}")
println("part 2: ${part2(readResourceAsBufferedReader("8_1.txt").readLines())}")
}
fun part1(input: List<String>): Int {
val grid = parseGrid(input)
return visible(grid).size
}
fun part2(input: List<String>): Int {
val grid = parseGrid(input)
val scores = scenicScore(grid)
return scores.maxOfOrNull { it.max() } ?: throw IllegalStateException()
}
fun parseGrid(input: List<String>): Grid {
return input.map { line -> line.toCharArray().toList().map { it.code - '0'.code } }
}
fun visible(grid: Grid): Set<Coord> {
val answer = mutableSetOf<Pair<Int,Int>>()
for (y in grid.indices) {
// left to right
val row = grid[y]
var tallestSoFar = -1
for (x in row.indices) {
if (row[x] > tallestSoFar) {
answer.add(y to x)
tallestSoFar = row[x]
}
}
// right to left
tallestSoFar = -1
for (x in row.indices.reversed()) {
if (row[x] > tallestSoFar) {
answer.add(y to x)
tallestSoFar = row[x]
}
}
}
for (x in 0 until grid[0].size) {
// top to bottom
var tallestSoFar = -1
for (y in grid.indices) {
if (grid[y][x] > tallestSoFar) {
answer.add(y to x)
tallestSoFar = grid[y][x]
}
}
// bottom to top
tallestSoFar = -1
for (y in grid.indices.reversed()) {
if (grid[y][x] > tallestSoFar) {
answer.add(y to x)
tallestSoFar = grid[y][x]
}
}
}
return answer
}
typealias Grid = List<List<Int>>
fun Grid.at(c: Coord): Int {
return this[c.first][c.second]
}
fun scenicScore(grid: Grid): Array<IntArray> {
fun right(y: Int, x: Int): Int {
val curr = grid[y][x]
val lastTree = (y to x).right().drop(1).first { grid.at(it) >= curr || it.second >= grid[y].size - 1 }
return lastTree.second - x
}
fun left(y: Int, x: Int): Int {
val curr = grid[y][x]
val lastTree = (y to x).left().drop(1).first { grid.at(it) >= curr || it.second <= 0 }
return x - lastTree.second
}
fun down(y: Int, x: Int): Int {
val curr = grid[y][x]
val lastTree = (y to x).down().drop(1).first { grid.at(it) >= curr || it.first >= grid.size - 1 }
return lastTree.first - y
}
fun up(y: Int, x: Int): Int {
val curr = grid[y][x]
val lastTree = (y to x).up().drop(1).first { grid.at(it) >= curr || it.first <= 0 }
return y - lastTree.first
}
val scores = Array(grid.size) { IntArray(grid[0].size) }
for (y in 1 until grid.size - 1) {
val row = grid[y]
for (x in 1 until row.size - 1) {
val up = up(y, x)
val left = left(y, x)
val right = right(y, x)
val down = down(y, x)
scores[y][x] = right * left * down * up
}
}
return scores
} | 0 | Kotlin | 0 | 0 | 1dae6d2790d7605ac3643356b207b36a34ad38be | 3,290 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day05.kt | nmx | 572,850,616 | false | {"Kotlin": 18806} | fun main(args: Array<String>) {
fun parseStacks(input: List<String>): Pair<List<MutableList<Char>>, List<String>> {
val stackLabels = input.find { s -> s.startsWith(" 1") }!!
val numStacks = stackLabels.split(" ").last { s -> !s.isEmpty() }.toInt()
val stacks = mutableListOf<MutableList<Char>>()
for (i in 1..numStacks) {
stacks.add(mutableListOf())
}
var i = 0
while (!input[i].startsWith(" 1")) {
val line = input[i]
var j = 0
while (j < numStacks) {
val c = line[j * 4 + 1]
if (c != ' ') {
stacks[j].add(c)
}
j += 1
}
i++
}
return Pair(stacks, input.subList(i + 2, input.size))
}
fun executeMoves(stacks: List<MutableList<Char>>, moves: List<String>, reverseOrder: Boolean) {
moves.filter{ it.isNotEmpty() }.forEach {
val (num, src, dst) = it.split(" ").mapNotNull { s -> s.toIntOrNull() }
if (reverseOrder) {
for (i in num - 1 downTo 0) {
stacks[dst - 1].add(0, stacks[src - 1].removeAt(i))
}
} else {
for (i in 1..num) {
stacks[dst - 1].add(0, stacks[src - 1].removeAt(0))
}
}
}
}
fun resultString(stacks: List<List<Char>>): String {
return stacks.map { it.first() }.joinToString("")
}
fun part1(input: String) {
val (stacks, moves) = parseStacks(input.split("\n"))
executeMoves(stacks, moves, false)
println(resultString(stacks))
}
fun part2(input: String) {
val (stacks, moves) = parseStacks(input.split("\n"))
executeMoves(stacks, moves, true)
println(resultString(stacks))
}
val input = object {}.javaClass.getResource("Day05.txt").readText()
part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | 33da2136649d08c32728fa7583ecb82cb1a39049 | 1,993 | aoc2022 | MIT License |
src/Day08.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | import kotlin.math.max
fun main() {
// Convert to digits
fun parseInput(input: List<String>): MutableList<MutableList<Int>> {
return input
.map {
it
.map { n -> n.toString().toInt() }
.toMutableList()
}.toMutableList()
}
fun part1(input: List<String>): Int {
var counter = 0
val grid = parseInput(input)
val gridHorizontal = parseInput(input)
for (y in 1..gridHorizontal.size - 2) {
var left = 1
var right = gridHorizontal[y].size - 2
var leftHeight = gridHorizontal[y][0]
var rightHeight = gridHorizontal[y][gridHorizontal[y].size - 1]
for (x in 1..gridHorizontal[y].size - 2) {
if (leftHeight < rightHeight) {
if (leftHeight >= grid[y][left]) {
gridHorizontal[y][left] = Int.MAX_VALUE
}
leftHeight = max(grid[y][left], leftHeight)
left++
} else {
if (rightHeight >= grid[y][right]) {
gridHorizontal[y][right] = Int.MAX_VALUE
}
rightHeight = max(grid[y][right], rightHeight)
right--
}
}
}
val gridVertical = parseInput(input)
for (x in 1..gridVertical[0].size - 2) {
var top = 1
var bottom = gridVertical.size - 2
var topHeight = gridVertical[0][x]
var bottomHeight = gridVertical[gridVertical.size - 1][x]
for (y in 1..gridVertical.size - 2) {
if (topHeight < bottomHeight) {
if (topHeight >= grid[top][x]) {
gridVertical[top][x] = Int.MAX_VALUE
}
topHeight = max(grid[top][x], topHeight)
top++
} else {
if (bottomHeight >= grid[bottom][x]) {
gridVertical[bottom][x] = Int.MAX_VALUE
}
bottomHeight = max(grid[bottom][x], bottomHeight)
bottom--
}
}
}
for (y in grid.indices) {
for (x in grid[y].indices) {
if (grid[y][x] == gridHorizontal[y][x] || grid[y][x] == gridVertical[y][x]) {
counter++
}
}
}
return counter
}
fun part2(input: List<String>): Int {
val grid = parseInput(input)
val output = parseInput(input).map { it.map { 0 }.toMutableList() }.toMutableList()
var viewDistance: Int
val distances = ArrayList<List<Int>>()
for (y in 1..grid.size - 2) {
viewDistance = 0
distances.clear()
grid[y].windowed(2).withIndex().forEach { (x, items) ->
if (x == grid[y].size - 2) {
return@forEach
}
val (prev, current) = items
if (current > prev) {
for (j in distances.size - 1 downTo 0) {
val (stackItem, dist) = distances[j]
if (current > stackItem) {
viewDistance += dist
distances.removeLast()
} else {
break
}
}
viewDistance++
} else {
distances.add(listOf(prev, viewDistance))
viewDistance = 1
}
output[y][x + 1] = viewDistance
}
viewDistance = 0
distances.clear()
grid[y].reversed().windowed(2).withIndex().forEach { (x, items) ->
if (x == grid[y].size - 2) {
return@forEach
}
val (prev, current) = items
if (current > prev) {
for (j in distances.size - 1 downTo 0) {
val (stackItem, dist) = distances[j]
if (current > stackItem) {
viewDistance += dist
distances.removeLast()
} else {
break
}
}
viewDistance++
} else {
distances.add(listOf(prev, viewDistance))
viewDistance = 1
}
output[y][grid[y].size - 2 - x] *= viewDistance
}
}
for (x in 1..grid[0].size - 2) {
viewDistance = 0
distances.clear()
grid.map { it[x] }.windowed(2).withIndex().forEach { (y, items) ->
if (y == grid.size - 2) {
return@forEach
}
val (prev, current) = items
if (current > prev) {
for (j in distances.size - 1 downTo 0) {
val (stackItem, dist) = distances[j]
if (current > stackItem) {
viewDistance += dist
distances.removeLast()
} else {
break
}
}
viewDistance++
} else {
distances.add(listOf(prev, viewDistance))
viewDistance = 1
}
output[y + 1][x] *= viewDistance
}
viewDistance = 0
distances.clear()
grid.reversed().map { it[x] }.windowed(2).withIndex().forEach { (y, items) ->
if (y == grid.size - 2) {
return@forEach
}
val (prev, current) = items
if (current > prev) {
for (j in distances.size - 1 downTo 0) {
val (stackItem, dist) = distances[j]
if (current > stackItem) {
viewDistance += dist
distances.removeLast()
} else {
break
}
}
viewDistance++
} else {
distances.add(listOf(prev, viewDistance))
viewDistance = 1
}
output[grid.size - 2 - y][x] *= viewDistance
}
}
return output.flatten().max()
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 6,960 | aoc-2022 | Apache License 2.0 |
src/day4/Solution.kt | Zlate87 | 572,858,682 | false | {"Kotlin": 12960} | package day4
import readInput
fun main() {
fun String.toSections() = this
.split("-")
.map { it.toInt() }
fun List<Int>.toSectionSet(): Set<Int> {
val set = HashSet<Int>()
for (i in this[0]..this[1]) {
set.add(i)
}
return set
}
fun List<String>.toElvesPairSectionsSets() = this
.map { pairString -> pairString.split(",") }
.map { pairList ->
Pair(
pairList[0].toSections().toSectionSet(),
pairList[1].toSections().toSectionSet()
)
}
fun part1(input: List<String>): Int {
return input.toElvesPairSectionsSets()
.count {
it.first.containsAll(it.second) or it.second.containsAll(it.first)
}
}
fun part2(input: List<String>): Int {
return input.toElvesPairSectionsSets()
.count {
it.first.intersect(it.second).isNotEmpty()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day4/Input_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("day4/Input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 57acf4ede18b72df129ea932258ad2d0e2f1b6c3 | 1,282 | advent-of-code-2022 | Apache License 2.0 |
solutions/aockt/y2015/Y2015D09.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2015
import aockt.util.generatePermutations
import io.github.jadarma.aockt.core.Solution
object Y2015D09 : Solution {
private val inputRegex = Regex("""^(\w+) to (\w+) = (\d+)$""")
/** Parses a single line of input and returns a triple containing two locations and the distance between them. */
private fun parseInput(input: String): Triple<String, String, Int> {
val (from, to, distance) = inputRegex.matchEntire(input)!!.destructured
return Triple(from, to, distance.toInt())
}
/**
* Given a list of distances between all pairs of locations on the map, returns all possible paths that visit all
* of them and their total distance.
*/
private fun bruteForceRoutes(locationData: List<Triple<String, String, Int>>): Sequence<Pair<List<String>, Int>> {
val locations = mutableSetOf<String>()
val distances = mutableMapOf<Pair<String, String>, Int>()
locationData.forEach { (from, to, distance) ->
locations.add(from)
locations.add(to)
distances[from to to] = distance
distances[to to from] = distance
}
return locations
.toList()
.generatePermutations()
.map { route -> route to route.windowed(2).sumOf { distances.getValue(it[0] to it[1]) } }
}
override fun partOne(input: String) =
input
.lines()
.map(this::parseInput)
.let(this::bruteForceRoutes)
.minOf { it.second }
override fun partTwo(input: String) =
input
.lines()
.map(this::parseInput)
.let(this::bruteForceRoutes)
.maxOf { it.second }
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 1,725 | advent-of-code-kotlin-solutions | The Unlicense |
src/day05/Day05.kt | sanyarajan | 572,663,282 | false | {"Kotlin": 24016} | package day05
import readInput
import kotlin.math.ceil
fun main() {
val instructionsRegex = Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)")
fun parseInput(input: List<String>): Pair<List<ArrayDeque<Char>>, List<String>> {
val numStacks = ceil(input[0].length / 4.0).toInt()
// list of length numStacks of stacks of chars
val stacks = List(numStacks) { ArrayDeque<Char>() }
var stackLines = 0
run loop@{
input.forEachIndexed { index, line ->
if (line[1] == '1') {
stackLines = index
return@loop
}
for (i in 1 until numStacks * 4 - 1 step 4) {
if (line[i] != ' ')
stacks[(i - 1) / 4].addFirst(line[i])
}
}
}
val instructions = input.subList(stackLines + 2, input.size)
return Pair(stacks, instructions)
}
fun part1(input: List<String>): String {
var topCrates = ""
val (stacks, instructions) = parseInput(input)
instructions.forEach { instruction ->
val (numCrates, fromStack, toStack) = instructionsRegex.find(instruction)!!.destructured
val numCratesInt = numCrates.toInt()
val fromStackInt = fromStack.toInt()
val toStackInt = toStack.toInt()
//move crates from fromStack to toStack
for (i in 0 until numCratesInt) {
stacks[toStackInt-1].addLast(stacks[fromStackInt-1].removeLast())
}
}
// get the last crate from each stack
stacks.forEach { stack ->
topCrates += stack.last()
}
return topCrates
}
fun part2(input: List<String>): String {
var topCrates = ""
val (stacks, instructions) = parseInput(input)
instructions.forEach { instruction ->
val (numCrates, fromStack, toStack) = instructionsRegex.find(instruction)!!.destructured
val numCratesInt = numCrates.toInt()
val fromStackInt = fromStack.toInt()
val toStackInt = toStack.toInt()
//move crates from fromStack to toStack preserving the order of the crates
val cratesToMove = ArrayDeque<Char>()
for (i in 0 until numCratesInt) {
cratesToMove.addLast(stacks[fromStackInt-1].removeLast())
}
for (i in 0 until numCratesInt) {
stacks[toStackInt-1].addLast(cratesToMove.removeLast())
}
}
// get the last crate from each stack
stacks.forEach { stack ->
topCrates += stack.last()
}
return topCrates
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day05/Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("day05/day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e23413357b13b68ed80f903d659961843f2a1973 | 3,029 | Kotlin-AOC-2022 | Apache License 2.0 |
src/Day13.kt | armandmgt | 573,595,523 | false | {"Kotlin": 47774} | data class PacketList(val items: List<Either<Int, PacketList>>) : Comparable<PacketList> {
override fun toString(): String {
return buildString {
append("[")
append(items.joinToString(", ") {
when (it) {
is Either.Left<Int, PacketList> -> it.left.toString()
is Either.Right<Int, PacketList> -> it.right.toString()
}
})
append("]")
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is PacketList) return false
return compareTo(other) == 0
}
override fun hashCode(): Int {
return items.hashCode()
}
companion object {
fun from(iterator: CharIterator): PacketList {
val items = mutableListOf<Either<Int, PacketList>>()
var intStr = ""
while (iterator.hasNext()) {
val c = iterator.next()
when {
c == '[' -> items.add(Either.Right(from(iterator)))
('0'..'9').contains(c) -> intStr += c
c == ',' || c == ']' -> {
if (intStr.isNotEmpty()) {
items.add(Either.Left(intStr.toInt()))
intStr = ""
}
if (c == ']') {
return PacketList(items)
}
}
}
}
throw IllegalArgumentException("Packet is not terminated correctly. Current items: `$items`")
}
}
override fun compareTo(other: PacketList): Int {
for (itemWithIndex in items.withIndex()) {
val itemLeft = itemWithIndex.value
if (itemWithIndex.index >= other.items.size) return 1
val itemRight = other.items[itemWithIndex.index]
if (itemLeft is Either.Left<Int, PacketList> && itemRight is Either.Left<Int, PacketList>) {
if (itemLeft.left < itemRight.left) return -1
if (itemLeft.left > itemRight.left) return 1
} else if (itemLeft is Either.Right<Int, PacketList> && itemRight is Either.Right<Int, PacketList>) {
if (itemLeft.right < itemRight.right) return -1
if (itemLeft.right > itemRight.right) return 1
} else if (itemLeft is Either.Left<Int, PacketList> && itemRight is Either.Right<Int, PacketList>) {
val newLeft = PacketList(listOf(itemLeft))
if (newLeft < itemRight.right) return -1
if (newLeft > itemRight.right) return 1
} else if (itemRight is Either.Left<Int, PacketList> && itemLeft is Either.Right<Int, PacketList>) {
val newRight = PacketList(listOf(itemRight))
if (itemLeft.right < newRight) return -1
if (itemLeft.right > newRight) return 1
}
}
if (items.size == other.items.size) return 0
return -1
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.chunked(3).mapIndexed { index, (packet1, packet2) ->
if (PacketList.from(packet1.iterator().apply { next() }) <= PacketList.from(
packet2.iterator().apply { next() })
) {
index + 1
} else 0
}.sum()
}
fun part2(input: List<String>): Int {
return (input + listOf("", "[[2]]", "[[6]]")).chunked(3).flatMap { (packet1, packet2) ->
listOf(
PacketList.from(packet1.iterator().apply { next() }),
PacketList.from(packet2.iterator().apply { next() })
)
}.sorted().let { res ->
(res.indexOf(PacketList.from("[[2]]".iterator().apply { next() })) + 1) *
(res.indexOf(PacketList.from("[[6]]".iterator().apply { next() })) + 1)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("resources/Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("resources/Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 0d63a5974dd65a88e99a70e04243512a8f286145 | 4,284 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/com/ikueb/advent18/Day12.kt | h-j-k | 159,901,179 | false | null | package com.ikueb.advent18
object Day12 {
fun getSumOfPlantedPots(input: List<String>) =
process(input, (1..20).asSequence(), 0).toInt()
fun getSumOfPlantedPotsAt(input: List<String>, target: Long) =
process(input = input, target = target)
private fun process(input: List<String>,
sequence: Sequence<Int> = generateSequence(1) { it + 1 },
target: Long): Long {
val state = input[0].replace("initial state: ", "")
.mapIndexed { i, c -> i to (c == '#') }.toMap(mutableMapOf())
val rules = input.drop(2).map { PlantPredicate(it) }
var previous = setOf<Int>()
var last = 0
for (i in sequence) {
val stateCopy = state.toMap()
val start = stateCopy.keys.minBy { it }!! - 3
val end = stateCopy.keys.maxBy { it }!! + 3
val current = (start..end).associateWith { n ->
rules.map { it.isPlantNext(n, stateCopy) }.firstNonNull()
}.mapValues { it.value ?: false }
.apply { state.putAll(this) }
.filterValues { it }.keys
if (current.map { it - 1 }.toSet() == previous) {
last = i
break
}
previous = current
}
return state.filterValues { it }.keys
.map { it + (target - last) }
.reduce(Long::plus)
}
}
data class PlantPredicate(val plants: List<Boolean>, val outcome: Boolean) {
constructor(input: String) :
this(input.substring(0, 5).map { it == '#' }, input.endsWith("#"))
fun isPlantNext(n: Int, stateCopy: Map<Int, Boolean>) =
if ((-2..2).map { n + it }.all {
(stateCopy[it] == true) == plants[it - n + 2]
}) outcome else null
} | 0 | Kotlin | 0 | 0 | f1d5c58777968e37e81e61a8ed972dc24b30ac76 | 1,876 | advent18 | Apache License 2.0 |
src/main/kotlin/de/consuli/aoc/year2022/days/Day07.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2022.days
import de.consuli.aoc.common.Day
class Day07 : Day(7, 2022) {
override fun partOne(testInput: Boolean): Any {
this.init()
parseDirectories(testInput)
return directories.map { it.totalSize }.filter { it <= 100000 }.sum()
}
override fun partTwo(testInput: Boolean): Any {
this.init()
val totalSize = parseDirectories(testInput)
directories.sortBy { it.totalSize }
val sizeToDelete = totalSize - 40000000L
val smallestDirectoryToDelete = directories.find { it.totalSize >= sizeToDelete }
return smallestDirectoryToDelete!!.totalSize
}
private fun parseDirectories(testInput: Boolean): Long {
val rootDirectory = Directory()
var currentDirectory = rootDirectory
getInput(testInput).forEach {
when {
it.startsWith(CHANGE_DIRECTORY_COMMAND) ->
when (val directoryName = it.substringAfter(CHANGE_DIRECTORY_COMMAND)) {
"/" -> currentDirectory = rootDirectory
".." -> currentDirectory = currentDirectory.parentDirectory!!
else -> currentDirectory =
currentDirectory.subDirectories.getOrPut(directoryName) {
Directory(currentDirectory)
}
}
it.startsWith(LIST_DIRECTORY_COMMAND) -> {
// do nothing
}
// line with either
// directory with name in the current directory
// size and filename in current directory
else -> {
val (commandOrFilesize, name) = it.split(" ")
if (commandOrFilesize == "dir") {
currentDirectory.subDirectories.getOrPut(name) { Directory(currentDirectory) }
} else {
currentDirectory.files[name] = commandOrFilesize.toLong()
}
}
}
}
return scanDirectoryAndReturnTotalSize(rootDirectory)
}
private fun scanDirectoryAndReturnTotalSize(directoryToScan: Directory): Long {
var totalSize = 0L
directoryToScan.subDirectories.values.forEach { directory ->
totalSize += scanDirectoryAndReturnTotalSize(directory)
}
totalSize += directoryToScan.directorySize()
if (totalSize <= 100000) {
totalSizeOfDirectoriesWithAtMost100000 += totalSize
}
directoryToScan.totalSize = totalSize
directories += directoryToScan
return totalSize
}
private fun init() {
totalSizeOfDirectoriesWithAtMost100000 = 0L
directories = ArrayList()
}
companion object {
private const val CHANGE_DIRECTORY_COMMAND = "$ cd "
private const val LIST_DIRECTORY_COMMAND = "$ ls"
private var totalSizeOfDirectoriesWithAtMost100000 = 0L
private var directories = ArrayList<Directory>()
}
}
class Directory(val parentDirectory: Directory? = null) {
val subDirectories = HashMap<String, Directory>()
val files = HashMap<String, Long>()
var totalSize = 0L
fun directorySize(): Long {
return files.map { files -> files.value }.sum()
}
}
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 3,389 | advent-of-code | Apache License 2.0 |
src/Day09.kt | gojoel | 573,543,233 | false | {"Kotlin": 28426} | import java.lang.Integer.max
import kotlin.math.abs
import kotlin.math.min
enum class StepDirection { U, D, L, R }
fun main() {
val input = readInput("09")
// val input = readInput("09_test")
data class Move(val direction: StepDirection, val steps: Int)
fun retrieveMoves(input: List<String>): List<Move> {
return input.map {
val split = it.split(" ")
Move(StepDirection.valueOf(split[0]), split[1].toInt())
}
}
fun limit(value: Int) : Int {
return if (value < -1) {
-1
} else if (value > 1) {
1
} else {
value
}
}
fun nextMove(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
var xDiff = head.first - tail.first
var yDiff = head.second - tail.second
return if (abs(xDiff) == 1 && abs(yDiff) == 1) {
Pair(0, 0)
} else if (xDiff == 0 && abs(yDiff) == 1) {
Pair(0, 0)
} else if (yDiff == 0 && abs(xDiff) == 1) {
Pair(0, 0)
} else {
xDiff = limit(xDiff)
yDiff = limit(yDiff)
Pair(xDiff, yDiff)
}
}
fun updatePositions(list: MutableList<Pair<Int, Int>>, direction: StepDirection) {
for (i in 1 until list.size) {
val prev = list[i - 1]
val curr = list[i]
val diff = nextMove(prev, curr)
val pos = when (direction) {
StepDirection.U -> {
Pair(curr.first + diff.first, curr.second + min(diff.second, 1))
}
StepDirection.D -> {
Pair(curr.first + diff.first, curr.second + max(diff.second, -1))
}
StepDirection.L -> {
Pair(curr.first + max(diff.first, -1), curr.second + diff.second)
}
StepDirection.R -> {
Pair(curr.first + min(diff.first, 1), curr.second + diff.second)
}
}
list[i] = pos
}
}
fun moveKnots(input: List<String>, knotCount: Int = 2) : Int {
val moves = retrieveMoves(input)
val tailPositions: HashSet<Pair<Int, Int>> = hashSetOf()
val knotsList = MutableList(knotCount) {
Pair(0, 0)
}
// starting position
tailPositions.add(Pair(0, 0))
moves.forEach { move ->
for (i in 1..move.steps) {
val curr = knotsList[0]
val head = when (move.direction) {
StepDirection.U -> {
Pair(curr.first, curr.second + 1)
}
StepDirection.D -> {
Pair(curr.first, curr.second - 1)
}
StepDirection.L -> {
Pair(curr.first - 1, curr.second)
}
StepDirection.R -> {
Pair(curr.first + 1, curr.second)
}
}
knotsList[0] = head
updatePositions(knotsList, move.direction)
tailPositions.add(knotsList[knotsList.size - 1])
}
}
return tailPositions.size
}
fun part1(input: List<String>): Int {
return moveKnots(input, 2)
}
fun part2(input: List<String>): Int {
return moveKnots(input, 10)
}
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0690030de456dad6dcfdcd9d6d2bd9300cc23d4a | 3,528 | aoc-kotlin-22 | Apache License 2.0 |
src/Day07.kt | marosseleng | 573,498,695 | false | {"Kotlin": 32754} | fun main() {
fun part1(input: List<String>): Long {
return parseCommands(input).values.filter { it <= 100000 }.sum()
}
fun part2(input: List<String>): Long {
val parsedLines = parseCommands(input)
val rootSize = parsedLines["/"] ?: return -1
val availableSpace2 = 70000000 - rootSize
val requiredSpace = 30000000
val spaceToDelete = requiredSpace - availableSpace2
return parsedLines.values.filter { it > spaceToDelete }.min()
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
fun parseCommands(commands: List<String>): Map<String, Long> {
var path: String = ""
val directoriesSizes = mutableMapOf<String, Long>()
fun cd(directory: String) {
path = if (directory == "/" && path.isEmpty()) {
directory
} else if (directory == "..") {
path.dropLastWhile { it != '/' }.dropLast(1)
} else if (path == "/") {
"$path$directory"
} else {
"$path/$directory"
}
}
fun addFileSize(size: Long, targetPath: String = path) {
val currentSize = directoriesSizes[targetPath] ?: 0L
val newSize = currentSize + size
directoriesSizes[targetPath] = newSize
// update upper dirs
if (targetPath != "/") {
var parent = targetPath.dropLastWhile { it != '/' }.dropLast(1)
if (parent.isEmpty()) {
parent = "/"
}
addFileSize(size, parent)
}
}
val cdRegex = """\$ cd (.+)""".toRegex()
val lsRegex = """\$ ls""".toRegex()
val directoryRegex = """dir (.+)""".toRegex()
val fileRegex = """(\d+) .+""".toRegex()
for (line in commands) {
when {
cdRegex.matches(line) -> {
val directoryName = cdRegex.matchEntire(line)?.groupValues?.get(1) ?: continue
cd(directoryName)
}
lsRegex.matches(line) -> { /*nothing*/ }
directoryRegex.matches(line) -> { /* nothing */ }
fileRegex.matches(line) -> {
val fileSize = fileRegex.matchEntire(line)?.groupValues?.get(1)?.toLong() ?: continue
addFileSize(fileSize)
}
}
}
return directoriesSizes
} | 0 | Kotlin | 0 | 0 | f13773d349b65ae2305029017490405ed5111814 | 2,446 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/problems/Day18.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
import kotlin.math.ceil
import kotlin.math.floor
class Day18(override val input: String) : Problem {
override val number: Int = 18
private val numbers = input.lines().map { SnailfishNumber.fromString(it) }
override fun runPartOne(): String {
return numbers
.reduce { acc, snailfishNumber -> (acc + snailfishNumber).reduce() }
.magnitude()
.toString()
}
override fun runPartTwo(): String {
var maxMagnitude = 0L
for (n1 in (numbers.indices)) {
for (n2 in (n1 until numbers.size)) {
maxMagnitude = listOf(
(numbers[n1] + numbers[n2]).reduce().magnitude(),
(numbers[n2] + numbers[n1]).reduce().magnitude(),
maxMagnitude
).maxOf { it }
}
}
return maxMagnitude.toString()
}
data class SnailfishNumber(val left: SnailfishElement, val right: SnailfishElement) {
companion object {
fun fromString(str: String): SnailfishNumber {
val strWithoutBrackets = str.substring((1 until str.length - 1))
var openBrackets = 0
val list = mutableListOf<String>()
strWithoutBrackets
.toCharArray()
.forEachIndexed fei@{ idx, c ->
if (c == ',' && openBrackets == 0) {
list.add(strWithoutBrackets.substring(0 until idx))
list.add(strWithoutBrackets.substring(idx + 1))
return@fei
} else {
when (c) {
'[' -> openBrackets++
']' -> openBrackets--
else -> {}
}
}
}
val (left, right) = list
return SnailfishNumber(SnailfishElement.fromString(left), SnailfishElement.fromString(right))
}
}
override fun toString(): String {
return "[${left},${right}]"
}
fun reduce(): SnailfishNumber {
var previousNumber = SnailfishNumber(SnailfishElement(), SnailfishElement())
var currentNumber = this
while (previousNumber != currentNumber) {
previousNumber = currentNumber
currentNumber = currentNumber.explode()
if (currentNumber != previousNumber) {
continue
}
currentNumber = currentNumber.split()
}
return currentNumber
}
private fun findFirstExplodedPair(): Pair<Int, Int>? {
var level = 0
var start: Int? = null
this.toString().toCharArray().forEachIndexed { idx, char ->
when (char) {
'[' -> level++
']' -> level--
}
if (level == 5 && start == null) {
start = idx
}
if (level == 4 && start != null) {
return Pair(start!!, idx)
}
}
return null
}
fun explode(): SnailfishNumber {
val explodedPairIdxs = findFirstExplodedPair() ?: return this
val (leftIdx, rightIdx) = explodedPairIdxs
val thisStr = this.toString()
val (leftRemainder, rightRemainder) = thisStr.substring(leftIdx + 1, rightIdx).split(",")
.map { it.toLong() }
val leftString = thisStr.substring(0, leftIdx)
val rightString = thisStr.substring(rightIdx + 1)
val digitRegex = """\d+""".toRegex()
var findPairLeft = digitRegex.find(leftString)
val newLeftString = if (findPairLeft != null) {
var value = findPairLeft.value
while (findPairLeft != null) {
value = findPairLeft.value
findPairLeft = findPairLeft.next()
}
val newValue = (value.toLong() + leftRemainder).toString()
leftString.reversed().replaceFirst(value.reversed(), newValue.reversed()).reversed()
} else {
leftString
}
val findPairRight = digitRegex.find(rightString)
val newRightString = if (findPairRight != null) {
val newValue = (findPairRight.value.toLong() + rightRemainder).toString()
rightString.replaceFirst(findPairRight.value, newValue)
} else {
rightString
}
return fromString(newLeftString + "0" + newRightString)
}
fun split(): SnailfishNumber {
val newLeft = left.split()
if (newLeft != left) {
return SnailfishNumber(newLeft, right)
}
return SnailfishNumber(left, right.split())
}
operator fun plus(other: SnailfishNumber): SnailfishNumber {
return SnailfishNumber(SnailfishElement(element = this.copy()), SnailfishElement(element = other.copy()))
}
fun magnitude(): Long {
val leftMagnitude = 3 * (left.value ?: left.element!!.magnitude())
val rightMagnitude = 2 * (right.value ?: right.element!!.magnitude())
return leftMagnitude + rightMagnitude
}
}
data class SnailfishElement(val value: Long? = null, val element: SnailfishNumber? = null) {
companion object {
fun fromString(str: String): SnailfishElement {
return if (str[0].isDigit()) {
SnailfishElement(str.toLong())
} else {
SnailfishElement(element = SnailfishNumber.fromString(str))
}
}
}
fun split(): SnailfishElement {
return if (value != null) {
if (value > 9) {
val halfValue = value.toFloat() / 2
SnailfishElement(
element = SnailfishNumber(
SnailfishElement(floor(halfValue).toLong()),
SnailfishElement(ceil(halfValue).toLong())
)
)
} else {
this
}
} else {
SnailfishElement(element = this.element!!.split())
}
}
override fun toString(): String {
return value?.toString() ?: element.toString()
}
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 6,728 | AdventOfCode2021 | MIT License |
src/Day04.kt | mlidal | 572,869,919 | false | {"Kotlin": 20582} | import java.lang.IllegalArgumentException
fun main() {
fun part1(input: List<String>): Int {
var containsCount = 0
input.forEach {
val parts = it.split(",")
val (start1, end1) = parts[0].split("-").map { it.toInt() }
val (start2, end2) = parts[1].split("-").map { it.toInt() }
if (start1 <= start2 && end1 >= end2 || start2 <= start1 && end2 >= end1) {
containsCount += 1
}
}
return containsCount
}
fun part2(input: List<String>): Int {
var containsCount = 0
input.forEach {
val parts = it.split(",")
val (start1, end1) = parts[0].split("-").map { it.toInt() }
val range1 = start1..end1
val (start2, end2) = parts[1].split("-").map { it.toInt() }
val range2 = start2..end2
if (range1.intersect(range2).isNotEmpty()) containsCount += 1
}
return containsCount
}
// 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 | bea7801ed5398dcf86a82b633a011397a154a53d | 1,268 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/year2022/day17/Problem.kt | Ddxcv98 | 573,823,241 | false | {"Kotlin": 154634} | package year2022.day17
import IProblem
import kotlin.math.max
import kotlin.math.min
class Problem : IProblem {
private val jets = javaClass
.getResource("/2022/17.txt")!!
.readText()
.trim()
.toCharArray()
private fun cycleSize(matrix: Array<BooleanArray>, i: Int, j: Int): Int {
var i = i
var j = j
var n = 0
while (j != matrix.size && matrix[i].contentEquals(matrix[j])) {
i++
j++
n++
}
return n
}
private fun calculateHeight(
pieceHeight: Map<Int, Int>,
stats: Stats,
totalPieces: Long,
pieceNumber: Int,
height: Int,
heightPerCycle: Int
): Long {
val piecesLeft = totalPieces - pieceNumber - 1
val piecesPerCycle = pieceNumber - stats.pieces + 1
val cyclesLeft = piecesLeft / piecesPerCycle
val remainder = piecesLeft % piecesPerCycle
val cyclesHeight = cyclesLeft * heightPerCycle
val remainderPiece = (stats.pieces + remainder - 1).toInt()
val remainderHeight = pieceHeight[remainderPiece]!! - stats.height
return height + cyclesHeight + remainderHeight + 1
}
private fun towerSize(n: Long): Long {
val maxComputedPieces = min(n, 5000).toInt()
val size = PIECES.sumOf { it.height() + 1 } * (maxComputedPieces + 1) / PIECES.size + OFFSET_Y
val matrix = Array(size) { BooleanArray(WIDTH) }
val pieceHeight = mutableMapOf<Int, Int>()
val state = mutableMapOf<Indexes, Stats>()
var height = -1
var jetIndex = 0
for (i in 0 until maxComputedPieces) {
val pieceIndex = (i % PIECES.size)
val piece = PIECES[pieceIndex].copy()
piece.move(OFFSET_X, height + OFFSET_Y + 1)
do {
when (jets[jetIndex]) {
'<' -> piece.shiftLeft(matrix)
else -> piece.shiftRight(matrix)
}
piece.shiftDown(matrix)
jetIndex = (jetIndex + 1) % jets.size
} while (!piece.grounded)
val indexes = Indexes(pieceIndex, jetIndex)
val stats = state[indexes]
piece.rocks.forEach { matrix[size - it.y - 1][it.x] = true }
height = max(piece.height(), height)
pieceHeight[i] = height
state[indexes] = Stats(height, i + 1)
if (stats == null) {
continue
}
val heightPerCycle = cycleSize(matrix, matrix.size - height - 1, matrix.size - stats.height - 1)
if (heightPerCycle == height - stats.height) {
return calculateHeight(pieceHeight, stats, n, i, height, heightPerCycle)
}
}
return height + 1L
}
override fun part1(): Long {
return towerSize(2022)
}
override fun part2(): Long {
return towerSize(1_000_000_000_000)
}
}
| 0 | Kotlin | 0 | 0 | 455bc8a69527c6c2f20362945b73bdee496ace41 | 3,000 | advent-of-code | The Unlicense |
yandex/y2020/qual/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package yandex.y2020.qual
private fun solve(): Boolean {
readLn()
val a = readInts().sorted()
readLn()
val b = readInts().sorted()
if (a.size != b.size) return false
if (a.isEmpty()) return true
val aSame = a.all { it == a[0] }
val bSame = b.all { it == b[0] }
if (aSame && bSame) return true
if (aSame || bSame) return false
return good(a, b) || good(a, b.reversed())
}
private fun good(a: List<Int>, b: List<Int>): Boolean {
return a.indices.all {
(a[it] - a.first()).toLong() * (b.last() - b.first()) ==
(b[it] - b.first()).toLong() * (a.last() - a.first())
}
}
fun main() = repeat(readInt()) { println(if (solve()) "YES" else "NO") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().filter { it.isNotEmpty() }.map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 871 | competitions | The Unlicense |
src/Day25.kt | mjossdev | 574,439,750 | false | {"Kotlin": 81859} | import java.math.BigInteger
fun main() {
fun readSnafuNumber(number: String): BigInteger {
var factor = BigInteger.ONE
var total = BigInteger.ZERO
for (digit in number.reversed()) {
val value = when (digit) {
'=' -> -2
'-' -> -1
'0', '1', '2' -> digit.digitToInt()
else -> error("$digit is not a SNAFU digit")
}.toBigInteger()
total += value * factor
factor *= 5.toBigInteger()
}
return total
}
fun BigInteger.toSnafuNumber(): String {
val digits = ArrayDeque<Char>()
var remaining = this
var power = BigInteger.ONE
while (remaining != BigInteger.ZERO) {
val nextPower = power * 5.toBigInteger()
val current = remaining % nextPower
val base5Digit = (current / power).intValueExact()
if (base5Digit < 3) {
digits.addFirst(base5Digit.digitToChar())
remaining -= current
} else {
remaining += power
when (base5Digit) {
3 -> {
remaining += power
digits.addFirst('=')
}
4 -> digits.addFirst('-')
}
}
power = nextPower
}
val number = digits.joinToString("")
check(readSnafuNumber(number) == this)
return number
}
fun part1(input: List<String>): String = input.sumOf(::readSnafuNumber).toSnafuNumber()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
check(part1(testInput) == "2=-1=0")
val input = readInput("Day25")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | afbcec6a05b8df34ebd8543ac04394baa10216f0 | 1,829 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/Day02.kt | uipko | 572,710,263 | false | {"Kotlin": 25828} |
fun main() {
val score = scores1("Day02.txt").sum()
println("Your total score [1] is $score")
val score2 = scores2("Day02.txt").sum()
println("Your total score [2] is $score2")
}
fun scores1(fileName: String): List<Int> {
val rounds = mutableListOf<Int>()
readInput(fileName).forEach {
val they = it.first().code - offset_A
val you = it.last().code - offset_X
rounds.add(
if ((!(they == 1 && you == 3) && (they < you)) || (they == 3 && you == 1) ) {
you + 6
} else if (they == you) {
you + 3
} else {
you
}
)
}
return rounds
}
fun scores2(fileName: String): List<Int> {
val rounds = mutableListOf<Int>()
readInput(fileName).forEach {
val they = it.first().code - offset_A
val score = when (it.last().code - offset_X) {
1 -> 0 + if (they > 1) they - 1 else 3
2 -> 3 + they
else -> 6 + if (they < 3) they + 1 else 1
}
rounds.add(score)
}
return rounds
}
| 0 | Kotlin | 0 | 0 | b2604043f387914b7f043e43dbcde574b7173462 | 1,105 | aoc2022 | Apache License 2.0 |
src/main/kotlin/endredeak/aoc2022/Day11.kt | edeak | 571,891,076 | false | {"Kotlin": 44975} | package endredeak.aoc2022
fun main() {
solve("Monkey in the Middle") {
data class Monkey(
val items: ArrayDeque<Long>,
val op: (Long) -> Long,
val divider: Long,
val ifTrue: Int,
val ifFalse: Int,
var activity: Long = 0
)
fun input() = text
.split("\n\n")
.associate { monkeyLines ->
monkeyLines.split("\n")
.let { p ->
p[0].substringAfter(" ").replace(":", "").toInt() to
Monkey(
ArrayDeque(p[1].substringAfter(": ").split(", ").map { it.toLong() }),
p[2].substringAfter("new = old ")
.let {
if (it.contains("old")) {
when (it[0]) {
'+' -> { old -> old + old }
'*' -> { old: Long -> old * old }
else -> error("waat")
}
} else {
val c = it.substringAfter(" ").toLong()
when (it[0]) {
'+' -> { old -> old + c }
'*' -> { old: Long -> old * c }
else -> error("waat")
}
}
},
p[3].substringAfter("by ").toLong(),
p[4].substringAfter("monkey ").toInt(),
p[5].substringAfter("monkey ").toInt()
)
}
} to text.split("\n")
.filter { it.contains("divisible by") }
.map { it.substringAfter("by ") }
.map { it.toLong() }
.fold(1L) { f, s -> f * s }
fun run(rounds: Int, calculateWorry: (Long) -> Long) =
input()
.let { (monkeys, d) ->
repeat(rounds) { _ ->
monkeys.forEach { (_, m) ->
while (m.items.isNotEmpty()) {
val n = calculateWorry(m.op(m.items.removeFirst()) % d)
run {
if (n % m.divider == 0L) monkeys[m.ifTrue] else monkeys[m.ifFalse]
}!!.items.add(n)
m.activity++
}
}
}
monkeys
.map { (_, m) -> m.activity }
.sortedDescending()
.take(2)
.let { (f, s) -> f * s }
}
part1(64032) { run(20) { it / 3 } }
part2(12729522272) { run(10000) { it } }
}
} | 0 | Kotlin | 0 | 0 | e0b95e35c98b15d2b479b28f8548d8c8ac457e3a | 3,068 | AdventOfCode2022 | Do What The F*ck You Want To Public License |
src/main/kotlin/g1001_1100/s1091_shortest_path_in_binary_matrix/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1001_1100.s1091_shortest_path_in_binary_matrix
// #Medium #Array #Breadth_First_Search #Matrix
// #Algorithm_II_Day_8_Breadth_First_Search_Depth_First_Search
// #Graph_Theory_I_Day_5_Matrix_Related_Problems
// #2023_06_02_Time_305_ms_(98.28%)_Space_47.6_MB_(93.10%)
import java.util.LinkedList
import java.util.Queue
class Solution {
private val directions = intArrayOf(0, 1, 1, 0, -1, 1, -1, -1, 0)
fun shortestPathBinaryMatrix(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
if (grid[0][0] == 1 || grid[m - 1][n - 1] == 1) {
return -1
}
var minPath = 0
val queue: Queue<IntArray> = LinkedList()
queue.offer(intArrayOf(0, 0))
val visited = Array(m) { BooleanArray(n) }
visited[0][0] = true
while (queue.isNotEmpty()) {
val size = queue.size
for (i in 0 until size) {
val curr = queue.poll()
if (curr[0] == m - 1 && curr[1] == n - 1) {
return minPath + 1
}
for (j in 0 until directions.size - 1) {
val newx = directions[j] + curr[0]
val newy = directions[j + 1] + curr[1]
if (newx in 0 until n && newy >= 0 && newy < n && !visited[newx][newy] && grid[newx][newy] == 0) {
queue.offer(intArrayOf(newx, newy))
visited[newx][newy] = true
}
}
}
minPath++
}
return -1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,595 | LeetCode-in-Kotlin | MIT License |
src/day12/Day12.kt | IThinkIGottaGo | 572,833,474 | false | {"Kotlin": 72162} | package day12
import readInput
fun main() {
fun part1(input: List<String>): Int {
val settled = mutableListOf<Node>()
val unsettled = mutableListOf<Node>()
val grid = parseInput(input)
val startNode = Node(grid.getSpecifyPositionAndReplaceChar('S'), 0) // replace start position 'S' to 'a'
val endPos = grid.getSpecifyPositionAndReplaceChar('E') // replace end position 'E' to 'z'
unsettled += startNode
while (unsettled.isNotEmpty()) {
val node = unsettled.removeShortestNode()
settled += node
val waitSync = grid.nextPossiblePositions(settled, node.position) { it <= 1 }
addOrSyncSteps(unsettled, waitSync, node)
}
return settled.first { it.position == endPos }.steps
}
fun part2(input: List<String>): Int {
val settled = mutableListOf<Node>()
val unsettled = mutableListOf<Node>()
val grid = parseInput(input)
val aPosInGrid = grid.getAPosInGrid()
val startNode = Node(grid.getSpecifyPositionAndReplaceChar('E'), 0)
grid.getSpecifyPositionAndReplaceChar('S')
unsettled += startNode
while (unsettled.isNotEmpty()) {
val node = unsettled.removeShortestNode()
settled += node
val waitSync = grid.nextPossiblePositions(settled, node.position) { it >= -1 }
addOrSyncSteps(unsettled, waitSync, node)
}
return settled.filter { it.position in aPosInGrid }.minBy { it.steps }.steps
}
val testInput = readInput("day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("day12")
println(part1(input)) // 497
println(part2(input)) // 492
}
typealias Grid = List<MutableList<Char>>
data class Position(val i: Int, val j: Int)
data class Node(val position: Position, var steps: Int) {
override fun toString(): String {
return "(${position.i}, ${position.j}, $steps)"
}
}
fun parseInput(input: List<String>): Grid = input.map(String::toMutableList)
fun Grid.getSpecifyPositionAndReplaceChar(c: Char): Position {
for (i in indices) {
for (j in this[0].indices) {
if (this[i][j] == c) {
if (c == 'S') this[i][j] = 'a'
else if (c == 'E') this[i][j] = 'z'
return Position(i, j)
}
}
}
error("can not find $c position.")
}
fun Grid.nextPossiblePositions(
settled: MutableList<Node>,
position: Position,
condition: (Int) -> Boolean
): MutableList<Position> {
val (i, j) = position
val possiblePos = mutableListOf<Position>()
tryMoveUp(settled, i, j, condition)?.also { possiblePos += it }
tryMoveDown(settled, i, j, condition)?.also { possiblePos += it }
tryMoveLeft(settled, i, j, condition)?.also { possiblePos += it }
tryMoveRight(settled, i, j, condition)?.also { possiblePos += it }
return possiblePos
}
fun Grid.tryMoveUp(settled: MutableList<Node>, i: Int, j: Int, elevationCondition: (Int) -> Boolean): Position? {
val p = Position(i - 1, j)
if (i - 1 >= 0 && elevationCondition(this[i - 1][j] - this[i][j]) && p !in settled) {
return p
}
return null
}
fun Grid.tryMoveDown(settled: MutableList<Node>, i: Int, j: Int, elevationCondition: (Int) -> Boolean): Position? {
val p = Position(i + 1, j)
if (i + 1 < this.size && elevationCondition(this[i + 1][j] - this[i][j]) && p !in settled) {
return p
}
return null
}
fun Grid.tryMoveLeft(settled: MutableList<Node>, i: Int, j: Int, elevationCondition: (Int) -> Boolean): Position? {
val p = Position(i, j - 1)
if (j - 1 >= 0 && elevationCondition(this[i][j - 1] - this[i][j]) && p !in settled) {
return p
}
return null
}
fun Grid.tryMoveRight(settled: MutableList<Node>, i: Int, j: Int, elevationCondition: (Int) -> Boolean): Position? {
val p = Position(i, j + 1)
if (j + 1 < this[0].size && elevationCondition(this[i][j + 1] - this[i][j]) && p !in settled) {
return p
}
return null
}
fun MutableList<Node>.removeShortestNode(): Node {
return minBy { it.steps }.also { remove(it) }
}
fun addOrSyncSteps(unsettled: MutableList<Node>, waitSyncQueued: MutableList<Position>, node: Node) {
waitSyncQueued.forEach { pos ->
if (pos !in unsettled) unsettled += Node(pos, node.steps + 1)
else {
val oldNode = unsettled.first { it.position == pos }
if (node.steps + 1 < oldNode.steps) {
oldNode.steps = node.steps + 1
}
}
}
}
fun Grid.getAPosInGrid(): List<Position> {
val list = mutableListOf<Position>()
for (i in indices) {
for (j in this[0].indices) {
if (this[i][j] == 'a') {
list += Position(i, j)
}
}
}
return list
}
operator fun MutableList<Node>.contains(position: Position): Boolean {
return position in this.map { it.position }
} | 0 | Kotlin | 0 | 0 | 967812138a7ee110a63e1950cae9a799166a6ba8 | 5,053 | advent-of-code-2022 | Apache License 2.0 |
src/day10/Day10.kt | zypus | 573,178,215 | false | {"Kotlin": 33417, "Shell": 3190} | package day10
import AoCTask
// https://adventofcode.com/2022/day/10
sealed class Operation(val cycles: Int) {
data class AddX(val amount: Int): Operation(cycles = 2)
object Noop: Operation(cycles = 1)
companion object {
fun fromString(string: String): Operation {
return if (string == "noop") {
Noop
} else {
val (_, amount) = string.split(" ")
AddX(amount.toInt())
}
}
}
}
data class ExecutionResult(val cycle: Int, val registerStartOfCycle: Int, val registerEndOfCycle: Int, val ss: Int)
private fun executeProgram(input: List<String>): List<ExecutionResult> {
val operations = input.map { Operation.fromString(it) }
val expandedOps = operations.flatMap {
when (it) {
is Operation.Noop -> listOf(Operation.Noop)
is Operation.AddX -> listOf(Operation.Noop, it)
}
}
val registerAndScores = expandedOps.scanIndexed(ExecutionResult(0, 1, 1, 0)) { previousCycle, (_, _, register, _), op ->
val cycle = previousCycle + 1
when (op) {
is Operation.Noop -> ExecutionResult(cycle, register, register, cycle * register)
is Operation.AddX -> ExecutionResult(cycle, register, register + op.amount, cycle * register)
}
}
return registerAndScores
}
fun part1(input: List<String>): Int {
val results = executeProgram(input)
val padStartWith19DummyValues = (-19..-1).map { ExecutionResult(it, 0, 0,0) }
val paddedResults = padStartWith19DummyValues + results
val finalSignalStrengthScore = paddedResults
.take(240)
.windowed(40, 40)
.map {
it.last()
}
.sumOf {
it.ss
}
return finalSignalStrengthScore
}
fun part2(input: List<String>): String {
val cycles = executeProgram(input)
val crt = cycles
.drop(1)
.take(240)
.map { cycle ->
val crtCursor = (cycle.cycle - 1) % 40
if (crtCursor in (cycle.registerStartOfCycle - 1)..(cycle.registerStartOfCycle + 1)) {
"#"
} else {
"."
}
}
return crt
.windowed(40, 40)
.joinToString("\n") {
it.joinToString("")
}
}
fun main() = AoCTask("day10").run {
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 13140)
val expectedOutput = """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent()
check(part2(testInput) == expectedOutput)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f37ed8e9ff028e736e4c205aef5ddace4dc73bfc | 2,929 | aoc-2022 | Apache License 2.0 |
src/exercises/Day12.kt | Njko | 572,917,534 | false | {"Kotlin": 53729} | // ktlint-disable filename
package exercises
import readInput
data class Point(val x: Int, val y: Int, var visited: Boolean = false)
fun main() {
fun findPoint(grid: List<String>, point: Char): Point {
grid.forEachIndexed { y, line ->
val x = line.indexOf(point)
if (x != -1) return Point(x, y)
}
return Point(-1, -1)
}
fun getValidNeighbours(grid: List<String>, currentPosition: Point): MutableMap<Point, Char> {
val result = mutableMapOf<Point, Char>()
// make sure our neighbours coordinates are not out of bounds
val left = (currentPosition.x - 1).coerceIn(0 until grid[0].length)
val right = (currentPosition.x + 1).coerceIn(0 until grid[0].length)
val top = (currentPosition.y - 1).coerceIn(grid.indices)
val bottom = (currentPosition.y + 1).coerceIn(grid.indices)
// get all neighbours
result[currentPosition.copy(x = left)] = grid[currentPosition.y].elementAt(left)
result[currentPosition.copy(x = right)] = grid[currentPosition.y].elementAt(right)
result[currentPosition.copy(y = top)] = grid[top].elementAt(currentPosition.x)
result[currentPosition.copy(y = bottom)] = grid[bottom].elementAt(currentPosition.x)
// remove the neighbour that produced the same coordinates as current position
result.remove(currentPosition)
return result
}
fun part1(input: List<String>): Int {
//val grid = mutableListOf<Point>().addAll(input.map { })
val currentPosition = findPoint(input, 'S')
val toVisit = mutableListOf(currentPosition)
var currentValue: Char
val endPosition = findPoint(input, 'E')
var steps = 0
while (toVisit.isNotEmpty()) {
steps++
var nextToVisit = mutableSetOf<Point>()
for (point in toVisit) {
currentValue = input[point.y][point.x]
if (currentValue == 'S') currentValue = 'a'
// find neighbours
val neighbours = getValidNeighbours(input, point)
// find coordinates to go to
nextToVisit =
neighbours
.filterKeys { !it.visited }
.filterValues { it >= currentValue && it - currentValue <= 1 }
.keys as MutableSet<Point>
point.visited = true
}
if(nextToVisit.any { it == endPosition }) {
return steps
} else {
toVisit.clear()
toVisit.addAll(nextToVisit)
}
}
return input.size
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
println("Test results:")
println(part1(testInput))
// check(part1(testInput) == 31)
// println(part2(testInput))
// check(part2(testInput) == 0)
val input = readInput("Day12")
println("Final results:")
println(part1(input))
// check(part1(input) == 0)
// println(part2(input))
// check(part2(input) == 0)
}
| 0 | Kotlin | 0 | 2 | 68d0c8d0bcfb81c183786dfd7e02e6745024e396 | 3,235 | advent-of-code-2022 | Apache License 2.0 |
solutions/aockt/y2023/Y2023D17.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.Graph
import aockt.util.parse
import aockt.util.path
import aockt.util.search
import aockt.util.spacial.Area
import aockt.util.spacial.Direction
import aockt.util.spacial.Direction.*
import aockt.util.spacial.Point
import aockt.util.spacial.move
import aockt.util.spacial.opposite
import io.github.jadarma.aockt.core.Solution
object Y2023D17 : Solution {
/**
* A map of the factory in Gear Island.
* @param initial The points in the map, associated to the amount of lost heat whenever travelling through it.
*/
private class GearIslandMap(initial: Iterable<Pair<Point, Int>>) {
private val grid: Map<Point, Int> = initial.associate { it.first to it.second }
val area: Area = Area(grid.keys)
/** A search state when navigating with a crucible. */
private data class CrucibleSearchState(
val position: Point,
val direction: Direction,
val straightLineStreak: Int,
)
/**
* Get the valid neighbouring nodes of a search state, by making sure to prevent the crucible:
* - from going out of bounds.
* - from going too much in the same direction.
* - from turning 180 degrees.
* - from turning if it is an ultra crucible and hasn't walked enough in a straight line.
*
* @param node The current search state.
* @param ultraCrucible Whether to navigate as an ultra crucible, or a regular one.
*/
private fun neighboursOf(
node: CrucibleSearchState,
ultraCrucible: Boolean,
): List<Pair<CrucibleSearchState, Int>> {
val validDirections = listOf(Up, Down, Left, Right)
.minus(node.direction.opposite)
.run { if (node.straightLineStreak == if (ultraCrucible) 10 else 3) minus(node.direction) else this }
.run { if (ultraCrucible && node.straightLineStreak in 1..<4) listOf(node.direction) else this }
.filter { direction -> node.position.move(direction) in area }
return validDirections.map { direction ->
val nextPosition = node.position.move(direction)
val nextCost = grid.getValue(nextPosition)
val nextState = CrucibleSearchState(
position = nextPosition,
direction = direction,
straightLineStreak = if (node.direction == direction) node.straightLineStreak.inc() else 1,
)
nextState to nextCost
}
}
/** Navigate a crucible from [start] to [end], returning the path taken and the running cost along it. */
fun navigate(start: Point, end: Point, withUltraCrucible: Boolean): List<Pair<Point, Int>> {
val graph = object : Graph<CrucibleSearchState> {
override fun neighboursOf(node: CrucibleSearchState) = neighboursOf(node, withUltraCrucible)
}
val search = graph.search(
start = CrucibleSearchState(start, Right, 0),
goalFunction = { it.position == end && (!withUltraCrucible || it.straightLineStreak >= 4) },
)
return search.path()!!.map { it.position to search.searchTree[it]!!.second }
}
}
/** Parse the [input] and return the [GearIslandMap]. */
private fun parseInput(input: String): GearIslandMap = parse {
input
.lines()
.asReversed()
.flatMapIndexed { y, line -> line.mapIndexed { x, n -> Point(x, y) to n.digitToInt() } }
.let(::GearIslandMap)
}
/** Calculate the cost of travelling with a crucible from the top-left to the bottom-right corners. */
private fun GearIslandMap.solve(withUltraCrucible: Boolean): Int {
val start = Point(area.xRange.first, area.yRange.last)
val end = Point(area.xRange.last, area.yRange.first)
return navigate(start, end, withUltraCrucible).last().second
}
override fun partOne(input: String) = parseInput(input).solve(withUltraCrucible = false)
override fun partTwo(input: String) = parseInput(input).solve(withUltraCrucible = true)
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 4,250 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day14.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | private val LINE_REGEX = "(?<x>\\d+),(?<y>\\d+)(?:\\s+->\\s+)?".toRegex()
private val SAND_START = 500 to 0
data class Line(
val start: Pair<Int, Int>,
val end: Pair<Int, Int>
)
fun Line.isVertical() = start.first == end.first
enum class Item(private val text: String) {
AIR("."), ROCK("#"), SAND("o");
override fun toString(): String {
return text
}
}
fun main() {
fun parseLines(input: List<String>) = input.flatMap { line ->
val matches = LINE_REGEX.findAll(line).toList()
(1 until matches.count()).map {
Line(
matches[it - 1].groups["x"]!!.value.toInt() to matches[it - 1].groups["y"]!!.value.toInt(),
matches[it].groups["x"]!!.value.toInt() to matches[it].groups["y"]!!.value.toInt()
)
}
}
fun sandFallingIntoAbyss(
sandX: Int,
sandY: Int,
minX: Int,
minY: Int,
maxX: Int,
maxY: Int,
partOne: Boolean = true
) = if (partOne) {
sandY - minY < 0 ||
sandY > maxY ||
sandX - minX < 0 ||
sandX > maxX
} else {
sandY - minY < 0 ||
sandY > maxY + 2
}
fun checkIfAirInPosition(x: Int, y: Int, minX: Int, minY: Int, maxX: Int, maxY: Int, minimumX: Int, gridMap: Map<Pair<Int, Int>, Item>, partOne: Boolean): Boolean {
if (sandFallingIntoAbyss(x, y, minX, minY, maxX, maxY, partOne)) {
return true
}
if (!partOne && y == maxY + 2) {
return false
}
return x to y !in gridMap ||
gridMap[x to y] == Item.AIR
}
fun fillGrid(gridMap: MutableMap<Pair<Int, Int>, Item>, lines: List<Line>) {
for (line in lines) {
if (line.isVertical()) {
val range = if (line.start.second < line.end.second) {
(line.start.second until line.end.second + 1)
} else {
(line.start.second downTo line.end.second)
}
for (y in range) {
gridMap[line.start.first to y] = Item.ROCK
}
} else {
val range = if (line.start.first < line.end.first) {
(line.start.first until line.end.first + 1)
} else {
(line.start.first downTo line.end.first)
}
for (x in range) {
gridMap[x to line.end.second] = Item.ROCK
}
}
}
}
fun play(input: List<String>, partOne: Boolean): Int {
val lines = parseLines(input)
val minX = minOf(lines.minOf { minOf(it.start.first, it.end.first) }, SAND_START.first)
val minY = minOf(lines.minOf { minOf(it.start.second, it.end.second) }, SAND_START.second)
val minimumX = minOf(lines.minOf { minOf(it.start.first, it.end.first) }, SAND_START.first)
val maxX = maxOf(lines.maxOf { maxOf(it.start.first, it.end.first) }, SAND_START.first)
val maxY = maxOf(lines.maxOf { maxOf(it.start.second, it.end.second) }, SAND_START.second)
val gridMap = mutableMapOf<Pair<Int, Int>, Item>()
fillGrid(gridMap, lines)
var lastSandX = SAND_START.first
var lastSandY = SAND_START.second
while (!sandFallingIntoAbyss(lastSandX, lastSandY, minX, minY, maxX, maxY, partOne) &&
gridMap[SAND_START.first to SAND_START.second] != Item.SAND) {
var sandX = SAND_START.first
var sandY = SAND_START.second
gridMap[sandX to sandY] = Item.SAND
var blocked = false
while (!blocked && !sandFallingIntoAbyss(sandX, sandY, minX, minY, maxX, maxY, partOne)) {
if (checkIfAirInPosition(sandX, sandY + 1, minX, minY, maxX, maxY, minimumX, gridMap, partOne)) {
gridMap[sandX to sandY] = Item.AIR
sandY += 1
} else if (checkIfAirInPosition(sandX - 1, sandY + 1, minX, minY, maxX, maxY, minimumX, gridMap, partOne)) {
gridMap[sandX to sandY] = Item.AIR
sandY += 1
sandX -= 1
} else if (checkIfAirInPosition(sandX + 1 , sandY + 1, minX, minY, maxX, maxY, minimumX, gridMap, partOne)) {
gridMap[sandX to sandY] = Item.AIR
sandY += 1
sandX += 1
} else {
blocked = true
}
if (!sandFallingIntoAbyss(sandX, sandY, minX, minY, maxX, maxY, partOne)) {
gridMap[sandX to sandY] = Item.SAND
}
lastSandX = sandX
lastSandY = sandY
}
}
return gridMap.count { it.value == Item.SAND }
}
fun part1(input: List<String>) = play(input, true)
fun part2(input: List<String>) = play(input, false)
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input)) // 665
println(part2(input)) // 25434
} | 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 5,164 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.