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/Day02.kt | bananer | 434,885,332 | false | {"Kotlin": 36979} | fun main() {
fun part1(input: List<String>): Int {
val result: Pair<Int, Int> = input
.fold(Pair(0, 0)) { (position, depth), step ->
val (direction, countStr) = step.split(" ")
val count = Integer.parseInt(countStr)
val pair = Pair(
when (direction) {
"forward" -> position + count
else -> position
},
when (direction) {
"up" -> depth - count
"down" -> depth + count
else -> depth
}
)
pair
}
return result.first * result.second
}
fun part2(input: List<String>): Int {
val result: Triple<Int, Int, Int> = input
.fold(Triple(0, 0, 0)) { (position, depth, aim), step ->
val (direction, countStr) = step.split(" ")
val count = Integer.parseInt(countStr)
Triple(
when (direction) {
"forward" -> position + count
else -> position
},
when (direction) {
"forward" -> depth + aim * count
else -> depth
},
when(direction) {
"down" -> aim + count
"up" -> aim - count
else -> aim
}
)
}
return result.first * result.second
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val testOutput1 = part1(testInput)
println("test output 1: $testOutput1")
check(testOutput1 == 150)
val testOutput2 = part2(testInput)
println("test output: $testOutput2")
check(testOutput2 == 900)
val input = readInput("Day02")
println("output part1: ${part1(input)}")
println("output part2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 98f7d6b3dd9eefebef5fa3179ca331fef5ed975b | 2,109 | advent-of-code-2021 | Apache License 2.0 |
kotlin/src/com/leetcode/23_MergeKSortedLists.kt | programmerr47 | 248,502,040 | false | null | package com.leetcode
import com.leetcode.data.ListNode
import com.leetcode.data.listNodesOf
import kotlin.collections.ArrayList
/**
* Time: O(n^2 * k) - k - max size of lists. We have N lists with size at max K.
* We create a new list of sorted heads:
* To create we go through N heads of original lists +
* put them in respective positions of the result list.
* We have binary search inside which is good optimization, but
* still adding element by index is O(n).
* Thus, creating new sorted heads = O(n) * (O(log(n)) * O(n)) = O(n^2)
*
* Next we go throught the sorted heads until its empty and on each step
* we remove head from sorted list and add it's next pointer to the list back
* Which means `while sortedNew.isNotEmpty` will be false when we will go
* through all elements of all lists. Thus, the cycle itself is O(n*k)
*
* Next in each part of the cycle we:
* 1. Remove item from the sorted head list. Thus, O(n)
* 2. Add next pointer to that list. Thus, O(log(n)) + O(n) = O(n)
*
* Thus, the total cycle is O(n*k) * O(n) = O(n^2 * k)
*
* Thus, overall O(n^2) + O(n^2 * k) = O(n^2 * k)
*/
private class Solution23 {
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
val sortedNew = ArrayList<ListNode>(lists.size)
lists.forEach { head ->
head?.let {
put(sortedNew, it)
}
}
var result: ListNode? = null
var current: ListNode? = null
while (sortedNew.isNotEmpty()) {
val next = sortedNew.removeAt(0)
current?.let {
it.next = next
} ?: run {
result = next
current = next
}
current = next
next.next?.let {
put(sortedNew, it)
}
}
return result
}
private fun put(sorted: MutableList<ListNode>, node: ListNode) {
if (sorted.isEmpty()) {
sorted.add(node)
return
}
sorted.add(findIndex(sorted, node), node)
}
private fun findIndex(sorted: MutableList<ListNode>, node: ListNode): Int {
var head = 0
var tail = sorted.lastIndex
while (head <= tail) {
val mid = (head + tail).ushr(1) // safe from overflows
val midVal = sorted[mid]
val cmp = midVal.`val` - node.`val`
if (cmp < 0)
head = mid + 1
else if (cmp > 0)
tail = mid - 1
else
return mid // key found
}
return head
}
}
fun main() {
val solution = Solution23()
println(solution.mergeKLists(arrayOf(
listNodesOf(3, 5, 10, 20),
listNodesOf(1, 8, 10, 20),
listNodesOf(15, 19, 20, 20),
listNodesOf(25, 26, 30, 100),
))?.joinToString())
} | 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 3,140 | problemsolving | Apache License 2.0 |
src/day12/a/day12a.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day12.a
import readInputLines
import shouldBe
import util.IntGrid
import util.IntVector
import vec2
fun main() {
val map = readInput()
val dist = IntGrid(map.width, map.height)
dist.compute { Integer.MAX_VALUE }
val (start, end) = findStartAndEnd(map)
val modified = HashSet<IntVector>()
// dist will contain the shortest route to each location
// it will be iteratively updated from the previous updated
// coordinates, until no further improvements can be made
dist[start] = 0
modified.add(start)
while(modified.isNotEmpty()) {
val l = ArrayList(modified)
modified.clear()
for (p1 in l) {
var d = vec2(1, 0)
val d1 = dist[p1]
val h1 = map[p1]
for (i in 1..4) {
val p2 = p1 + d
if (map.contains(p2)) {
val h2 = map[p2]
val d2 = dist[p2]
if (h2 <= h1+1 && d2-1 > d1) {
dist[p2] = d1+1
modified.add(p2)
}
}
d = d.rotate(0, 1)
}
}
}
val least = dist[end]
shouldBe(490, least)
}
fun findStartAndEnd(map: IntGrid): Pair<IntVector, IntVector> {
var start : IntVector? = null
var end : IntVector? = null
map.forEachIndexed { p, v ->
if (v == -14) {
map[p] = 0
start = p
} else if (v == -28) {
map[p] = 25
end = p
}
}
return Pair(start!!, end!!)
}
fun readInput(): IntGrid {
val r = ArrayList<IntArray>()
val lines = readInputLines(12)
for (l in lines) {
if (l.isBlank()) continue
r.add(l.chars().map { c -> c - 'a'.code}.toArray())
}
return IntGrid(r)
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 1,832 | advent-of-code-2022 | Apache License 2.0 |
src/day01/Day01Answer.kt | IThinkIGottaGo | 572,833,474 | false | {"Kotlin": 72162} | package day01
import readString
import java.util.*
/**
* Answer basically from [Advent of Code 2022 Day 1 | Kotlin](https://youtu.be/ntbsbqLCKDs)
*/
fun main() {
fun part1(input: String): Int {
val data = parseInput(input)
return data.topNElvesLogN(1)
}
fun part2(input: String): Int {
val data = parseInput(input)
return data.topNElvesLogN(3)
}
val testInput = readString("day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readString("day01")
println(part1(input)) // 72718
println(part2(input)) // 213089
}
fun parseInput(input: String) =
input.split("\n\n")
.map { elf ->
elf.lines()
.map(String::toInt)
.sum()
}
/**
* normal method, O(NlogN) time complexity
*/
fun List<Int>.topNElves(n: Int): Int =
sortedDescending().take(n).sum()
/**
* O(size * log size) -> O(size * log n)
*/
fun List<Int>.topNElvesNLogN(n: Int): Int {
val best = PriorityQueue<Int>() // TreeSet can't accept same value and will lose it, use PriorityQueue here
forEach { calories ->
best.add(calories)
if (best.size > n) {
best.poll()
}
}
return best.sum()
}
/**
* O(size * log n) -> O(log n)
*/
fun List<Int>.topNElvesLogN(n: Int): Int {
fun findTopN(n: Int, element: List<Int>): List<Int> {
if (this.size == n) return element
val x = element.random()
val small = element.filter { it < x }
val equal = element.filter { it == x }
val big = element.filter { it > x }
if (big.size >= n) return findTopN(n, element)
if (equal.size + big.size >= n) return (equal + big).takeLast(n)
return findTopN(n - equal.size - big.size, small) + equal + big
}
return findTopN(n, this).sum()
} | 0 | Kotlin | 0 | 0 | 967812138a7ee110a63e1950cae9a799166a6ba8 | 1,885 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day07/part2/day07_2.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2023.day07.part2
import eu.janvdb.aoc2023.day07.TypeOfHand
import eu.janvdb.aocutil.kotlin.readLines
//const val FILENAME = "input07-test.txt"
const val FILENAME = "input07.txt"
fun main() {
val pairs = readLines(2023, FILENAME).map { CardBidPair.parse(it) }
val score = pairs
.sortedBy { it.hand }
.asSequence()
.mapIndexed { index, it -> (index + 1L) * it.bid }
.sum()
println(score)
}
data class CardBidPair(val hand: Hand, val bid: Int) {
companion object {
fun parse(input: String): CardBidPair {
val split = input.trim().split(" ")
return CardBidPair(Hand.parse(split[0]), split[1].toInt())
}
}
}
enum class Card(val symbol: Char) {
JOKER('J'),
TWO('2'),
THREE('3'),
FOUR('4'),
FIVE('5'),
SIX('6'),
SEVEN('7'),
EIGHT('8'),
NINE('9'),
TEN('T'),
QUEEN('Q'),
KING('K'),
ACE('A');
companion object {
fun findBySymbol(symbol: Char) =
entries.find { it.symbol == symbol } ?: throw IllegalArgumentException("Unknown symbol: $symbol")
}
}
data class Hand(val cards: List<Card>) : Comparable<Hand> {
val numberOfJokers = cards.count() { it == Card.JOKER }
val occurrences =
cards.filter { it != Card.JOKER }.groupingBy { it }.eachCount().map { it.value }.sortedDescending()
val type = calculateType()
private fun calculateType(): TypeOfHand {
if (occurrences.isEmpty()) return TypeOfHand.FIVE_OF_A_KIND // Five jokers
if (occurrences[0] + numberOfJokers == 5) return TypeOfHand.FIVE_OF_A_KIND
if (occurrences[0] + numberOfJokers == 4) return TypeOfHand.FOUR_OF_A_KIND
if (occurrences[0] + numberOfJokers == 3 && occurrences[1] == 2) return TypeOfHand.FULL_HOUSE
if (occurrences[0] + numberOfJokers == 3) return TypeOfHand.THREE_OF_A_KIND
if (occurrences[0] + numberOfJokers == 2 && occurrences[1] == 2) return TypeOfHand.TWO_PAIRS
if (occurrences[0] + numberOfJokers == 2) return TypeOfHand.ONE_PAIR
return TypeOfHand.HIGH_CARD
}
override fun compareTo(other: Hand): Int {
if (type != other.type) return type.compareTo(other.type)
for (i in cards.indices) {
val thisCard = cards[i]
val otherCard = other.cards[i]
if (thisCard != otherCard) return thisCard.compareTo(otherCard)
}
return 0
}
override fun toString(): String {
return "Hand(cards=$cards, numberOfJokers=$numberOfJokers, occurrences=$occurrences, type=$type)"
}
companion object {
fun parse(input: String): Hand {
val cards = input.toCharArray().map { Card.findBySymbol(it) }
return Hand(cards)
}
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,497 | advent-of-code | Apache License 2.0 |
src/main/kotlin/wtf/log/xmas2021/day/day15/Day15.kt | damianw | 434,043,459 | false | {"Kotlin": 62890} | package wtf.log.xmas2021.day.day15
import wtf.log.xmas2021.Day
import wtf.log.xmas2021.util.collect.Grid
import wtf.log.xmas2021.util.collect.Grid.Coordinate
import wtf.log.xmas2021.util.collect.Grid.Entry
import wtf.log.xmas2021.util.collect.toGrid
import java.io.BufferedReader
import java.util.*
object Day15 : Day<Grid<Int>, Int, Int> {
override fun parseInput(reader: BufferedReader): Grid<Int> = reader
.lineSequence()
.map { line ->
line.map { it.digitToInt() }
}
.toList()
.toGrid()
override fun part1(input: Grid<Int>): Int {
val path = input.findShortestPath(
from = Coordinate(0, 0),
to = Coordinate(input.height - 1, input.width - 1),
)
return path.drop(1).sumOf { it.value }
}
override fun part2(input: Grid<Int>): Int {
val tiled = input.tile(5) { i, value ->
val incremented = value + i
(incremented % 10) + (incremented / 10)
}
val path = tiled.findShortestPath(
from = Coordinate(0, 0),
to = Coordinate(tiled.height - 1, tiled.width - 1),
)
return path.drop(1).sumOf { it.value }
}
/**
* https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode
*/
private fun Grid<Int>.findShortestPath(from: Coordinate, to: Coordinate): List<Entry<Int>> {
val fromEntry = Entry(from, get(from))
val toEntry = Entry(to, get(to))
val queue = PriorityQueue<Distance>().apply {
add(Distance(fromEntry, 0))
}
val dist = mutableMapOf(fromEntry to 0)
val prev = mutableMapOf<Entry<Int>, Entry<Int>>()
var current = fromEntry
while (current != toEntry && queue.isNotEmpty()) {
current = queue.remove().to
for (neighbor in getCardinallyAdjacent(current.coordinate)) {
val alt = dist[current]?.let { it + neighbor.value } ?: Int.MAX_VALUE
if (alt < (dist[neighbor] ?: Int.MAX_VALUE)) {
dist[neighbor] = alt
prev[neighbor] = current
queue.add(Distance(neighbor, alt))
}
}
}
return generateSequence(current, prev::get).toList().asReversed()
}
private fun <T> Grid<T>.tile(times: Int, transform: (Int, T) -> T): Grid<T> {
val horizontal = rows.map { row ->
(0 until times).flatMap { i ->
row.map { transform(i, it) }
}
}
return (0 until times)
.flatMap { i ->
horizontal.map { row ->
row.map { transform(i, it) }
}
}
.toGrid()
}
private data class Distance(
val to: Entry<Int>,
val length: Int,
) : Comparable<Distance> {
override fun compareTo(other: Distance): Int = this.length.compareTo(other.length)
}
}
| 0 | Kotlin | 0 | 0 | 1c4c12546ea3de0e7298c2771dc93e578f11a9c6 | 2,979 | AdventOfKotlin2021 | BSD Source Code Attribution |
src/Day11.kt | sushovan86 | 573,586,806 | false | {"Kotlin": 47064} | typealias WorryLevelOperation = (Long) -> Long
class MonkeyProblem {
private data class Monkey(
val monkeyIndex: Int,
val items: List<Long>,
val operation: String,
val rightOperand: String,
val divisorPredicateOperand: Int,
val trueTargetMonkey: Int,
val falseTargetMoney: Int
) {
var inspections: Long = 0
val worryItems = ArrayDeque<Long>()
fun initialize() {
inspections = 0
worryItems.clear()
worryItems += items
}
fun applyMonkeyOperation(oldValue: Long): Long = when (operation) {
"*" -> oldValue * (rightOperand.toLongOrNull() ?: oldValue)
"+" -> oldValue + (rightOperand.toLongOrNull() ?: oldValue)
else -> error("Invalid Operation $operation for Monkey $monkeyIndex")
}
}
private val monkeyList: MutableList<Monkey> = mutableListOf()
private val commonDivisor: Long by lazy {
monkeyList.map { it.divisorPredicateOperand.toLong() }.reduce(Long::times)
}
val worryLevelDivisor: WorryLevelOperation = { worryLevel -> worryLevel / 3 }
val worryLevelModulus: WorryLevelOperation = { worryLevel -> worryLevel % commonDivisor }
fun calculateMonkeyBusiness(rounds: Int, worryLevelOperation: WorryLevelOperation): Long {
monkeyList.forEach(Monkey::initialize)
repeat(rounds) {
for (monkey in monkeyList) {
while (monkey.worryItems.isNotEmpty()) {
val item = monkey.worryItems.removeFirst()
monkey.inspections++
val worryLevel = worryLevelOperation(monkey.applyMonkeyOperation(item))
if (worryLevel % monkey.divisorPredicateOperand == 0L) {
monkeyList[monkey.trueTargetMonkey].worryItems += worryLevel
} else {
monkeyList[monkey.falseTargetMoney].worryItems += worryLevel
}
}
}
}
return monkeyList
.map { it.inspections }
.sortedDescending()
.take(2)
.reduce(Long::times)
}
companion object {
private val MONKEY_INPUT_SEPARATOR: String = System.lineSeparator() + System.lineSeparator()
private fun String.toMonkey(monkeyIndex: Int): Monkey {
val (startingItemsLine,
operationLine,
testPredicateLine,
trueTargetLine,
falseTargetLine) = lines().drop(1)
val items = startingItemsLine.substringAfter(":")
.split(",").map { it.trim().toLong() }
val parsedOperation = operationLine.substringAfter("=").trim()
.substringAfter("old ").trim()
val (operation, rightOperand) = parsedOperation.split(" ")
val testOperand = testPredicateLine.substringAfter("by ").trim().toInt()
val trueTargetMonkey = trueTargetLine.substringAfterLast(" ").trim().toInt()
val falseTargetMonkey = falseTargetLine.substringAfterLast(" ").trim().toInt()
return Monkey(
monkeyIndex,
items,
operation,
rightOperand,
testOperand,
trueTargetMonkey,
falseTargetMonkey
)
}
fun load(input: String): MonkeyProblem {
val monkeyProblem = MonkeyProblem()
for ((index, monkeyGroupInput) in input.split(MONKEY_INPUT_SEPARATOR).withIndex()) {
monkeyProblem.monkeyList += monkeyGroupInput.toMonkey(index)
}
return monkeyProblem
}
}
}
fun main() {
val testInputString = readInputAsText("Day11_test")
val testMonkeyProblem = MonkeyProblem.load(testInputString)
check(testMonkeyProblem.calculateMonkeyBusiness(20, testMonkeyProblem.worryLevelDivisor) == 10605L)
check(testMonkeyProblem.calculateMonkeyBusiness(10_000, testMonkeyProblem.worryLevelModulus) == 2713310158L)
val actualInputString = readInputAsText("Day11")
val actualMonkeyProblem = MonkeyProblem.load(actualInputString)
println(actualMonkeyProblem.calculateMonkeyBusiness(20, actualMonkeyProblem.worryLevelDivisor))
println(actualMonkeyProblem.calculateMonkeyBusiness(10_000, actualMonkeyProblem.worryLevelModulus))
} | 0 | Kotlin | 0 | 0 | d5f85b6a48e3505d06b4ae1027e734e66b324964 | 4,443 | aoc-2022 | Apache License 2.0 |
src/year2023/day06/Day06.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2023.day06
import check
import readInput
fun main() {
val testInput1 = readInput("2023", "Day06_test")
check(part1(testInput1), 288)
check(part2(testInput1), 71503)
val input = readInput("2023", "Day06")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val times = input.first().toNumbers()
val distances = input.last().toNumbers()
return times.zip(distances)
.map { (time, distance) -> countWaysToWinRace(time, distance) }
.reduce { acc, i -> acc * i }
}
private fun part2(input: List<String>): Int {
val time = input.first().toNumber()
val recordDistance = input.last().toNumber()
return countWaysToWinRace(time, recordDistance)
}
private fun countWaysToWinRace(time: Long, recordDistance: Long): Int {
fun winsRace(holdTime: Long) = holdTime * (time - holdTime) > recordDistance
val holdTimes = 0..time
return holdTimes.count { winsRace(it) }
}
private fun String.toNumbers(): List<Long> = split(" ").mapNotNull { it.trim().toLongOrNull() }
private fun String.toNumber(): Long = filter { it.isDigit() }.toLong()
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,153 | AdventOfCode | Apache License 2.0 |
src/Day02.kt | ekgame | 573,100,811 | false | {"Kotlin": 20661} |
fun main() {
class GestureDefinition(
val winAgainst: Char,
val loseAgainst: Char,
val drawAgainst: Char,
val useScore: Int,
) {
fun isWin(against: Char) = winAgainst == against
fun isLoss(against: Char) = loseAgainst == against
fun isDraw(against: Char) = drawAgainst == against
}
val ROCK = GestureDefinition('C', 'B', 'A', 1)
val PAPER = GestureDefinition('A', 'C', 'B', 2)
val SCISSORS = GestureDefinition('B', 'A', 'C', 3)
val ALL = listOf(ROCK, PAPER, SCISSORS)
fun getWinning(against: Char) = ALL.first { it.isWin(against) }
fun getLosing(against: Char) = ALL.first { it.isLoss(against) }
fun getDrawing(against: Char) = ALL.first { it.isDraw(against) }
fun Pair<Char, GestureDefinition>.getScore(): Int {
var result = this.second.useScore
if (this.second.isWin(this.first)) result += 6
else if (this.second.isDraw(this.first)) result += 3
return result
}
fun part1(input: List<String>): Int = input
.map {
it[0] to when (it[2]) {
'X' -> ROCK
'Y' -> PAPER
'Z' -> SCISSORS
else -> error("Should never happen.")
}
}
.sumOf { it.getScore() }
fun part2(input: List<String>): Int = input
.map {
it[0] to when (it[2]) {
'X' -> getLosing(it[0])
'Y' -> getDrawing(it[0])
'Z' -> getWinning(it[0])
else -> error("Should never happen.")
}
}
.sumOf { it.getScore() }
val testInput = readInput("02.test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 0c2a68cedfa5a0579292248aba8c73ad779430cd | 1,839 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/nl/meine/aoc/_2023/Day4.kt | mtoonen | 158,697,380 | false | {"Kotlin": 201978, "Java": 138385} | package nl.meine.aoc._2023
import java.util.concurrent.ConcurrentHashMap
import kotlin.math.pow
class Day4 {
fun one(input: String): Int {
val lines = input.split("\n")
.map { it.substringAfter(": ") }
.map {
val lists = it.split(" | ")
Pair(createList(lists[0]), createList(lists[1]))
}
.map { numbers -> numbers.first.filter { numbers.second.contains(it) } }
.map { it.size }
.filter { it > 0 }.sumOf { 2.0.pow((it - 1).toDouble()).toInt() }
return lines
}
fun createList(input: String): List<Int> {
return input.split(" ")
.filter { it.isNotBlank() }
.map { it.toInt() }
}
fun two(input: String): Int {
val winningsMap: MutableMap<Int, Int> = mutableMapOf()
val lines = input.split("\n")
.mapIndexed { index, card -> card.substringAfter(": ") }
.mapIndexed { index, card ->
val lists = card.split(" | ")
Pair(createList(lists[0]), createList(lists[1]))
}
.mapIndexed { index, numbers -> numbers.first.filter { numbers.second.contains(it) } }
.mapIndexed { index, winnings -> winnings.size }
.mapIndexed { index, winnings -> winningsMap.put(index + 1, winnings) }
// huidige map expanden in een map van id-aantal
// voor elke entry in map
// kijk of er winst is
// zo ja, hoog de opeenvolgende entries op
// tell alle values op
var cards: MutableMap<Int,Int> = winningsMap
.filter { it.value>0 }
.mapValues { entry -> 1 }
.toMutableMap()
var losingCards: Int = winningsMap
.filter { it.value==0 }
.count()
var concurrentMap : ConcurrentHashMap<Int,Int> = ConcurrentHashMap(cards)
for(card in concurrentMap){
for(copy in 1..card.value) {
if (winningsMap.contains(card.key)) {
val numberOfWinnings = winningsMap[card.key] ?: 1
for (id in (card.key + 1)..(numberOfWinnings + card.key)) {
concurrentMap.merge(id, 1, Int::plus)
}
}
}
}
return concurrentMap.values.sum()+losingCards
}
fun computeCards(winningCards: MutableMap<Int,Int>, cards: MutableMap<Int,Int> ):Int{
return 1
}
}
fun main() {
val inputReal =
"""Card 1: 34 50 18 44 19 35 47 62 65 26 | 63 6 27 15 60 9 98 3 61 89 31 43 80 37 54 49 92 55 8 7 10 16 52 33 45
Card 2: 90 12 98 56 22 99 73 46 1 28 | 52 77 32 8 81 41 53 22 28 46 48 27 98 1 94 12 99 72 84 90 92 73 24 63 56
Card 3: 48 10 39 87 23 78 49 40 55 8 | 48 80 78 87 39 24 27 19 41 73 30 52 10 2 67 40 88 53 59 84 55 49 5 33 82
Card 4: 21 45 91 26 64 51 42 84 11 94 | 55 56 36 65 84 2 68 44 52 58 86 6 33 7 97 40 30 14 39 80 82 57 79 1 10
Card 5: 33 6 67 89 64 31 85 11 2 15 | 6 70 29 89 12 11 64 80 7 82 46 16 33 68 48 72 31 2 99 15 67 57 4 49 85
Card 6: 51 20 11 66 38 39 69 48 25 74 | 39 74 3 86 19 25 21 55 2 38 46 60 66 82 51 11 98 88 8 48 49 94 20 69 72
Card 7: 4 50 82 51 52 77 12 11 57 42 | 56 11 73 69 42 82 32 77 52 98 12 51 36 94 46 4 50 39 85 90 93 70 18 71 57
Card 8: 96 31 27 93 7 8 6 23 15 72 | 55 79 86 4 6 35 12 27 95 29 73 81 87 43 7 13 62 15 72 71 58 48 63 94 89
Card 9: 16 90 79 29 93 31 40 24 82 88 | 86 16 73 20 22 93 83 39 36 90 79 72 40 29 35 97 88 12 8 24 31 82 21 59 95
Card 10: 17 36 50 39 96 43 41 38 55 8 | 39 93 38 96 56 27 4 72 17 87 99 78 75 11 55 41 43 68 64 28 50 40 8 36 97
Card 11: 76 96 78 64 80 28 11 24 93 97 | 66 34 64 35 97 47 54 13 79 11 67 24 36 28 17 30 82 93 21 49 4 86 76 12 8
Card 12: 16 73 39 24 54 90 89 55 11 25 | 17 92 1 61 86 2 25 7 50 55 88 74 64 83 24 48 39 84 54 32 58 34 89 28 99
Card 13: 66 99 94 51 17 67 73 32 76 86 | 97 61 50 64 57 41 39 89 60 13 43 72 44 83 84 18 87 20 92 48 75 8 82 36 53
Card 14: 3 56 26 47 68 66 22 20 27 77 | 75 22 63 26 55 66 3 73 47 90 44 64 76 4 92 19 91 62 51 77 58 17 2 40 52
Card 15: 91 1 44 6 51 43 61 5 12 31 | 49 97 10 78 87 95 36 56 96 46 4 14 43 54 94 81 41 67 91 11 83 38 93 22 86
Card 16: 61 46 35 13 79 38 80 3 95 87 | 80 98 46 74 28 26 84 73 75 57 52 91 40 44 2 51 95 77 3 96 35 67 41 55 79
Card 17: 50 89 17 18 60 81 37 29 3 52 | 13 19 83 98 77 25 97 52 10 35 94 99 50 6 27 84 41 11 33 34 20 4 54 89 56
Card 18: 57 1 68 3 86 40 15 2 38 41 | 88 96 18 25 16 15 12 47 37 27 39 48 32 43 33 82 60 13 57 53 40 61 26 99 5
Card 19: 30 48 3 82 23 91 41 63 99 16 | 78 6 46 54 22 85 7 49 59 53 68 12 70 97 77 92 56 41 83 5 75 37 58 61 28
Card 20: 28 5 15 55 66 24 25 93 6 22 | 94 68 4 2 98 37 76 71 78 21 47 67 97 51 99 3 57 89 95 30 26 60 12 9 11
Card 21: 90 98 42 76 23 83 8 29 5 50 | 93 13 90 19 25 61 97 39 99 73 40 38 6 72 65 43 91 20 33 86 55 62 47 1 84
Card 22: 14 49 50 4 1 13 65 30 10 51 | 26 40 32 73 16 93 94 22 59 76 89 27 33 44 87 42 74 3 71 47 67 6 12 43 57
Card 23: 29 57 10 79 78 30 86 69 32 72 | 26 8 96 78 51 90 86 19 3 10 57 29 22 72 35 28 97 34 69 38 79 33 93 32 30
Card 24: 99 66 67 60 23 90 73 1 29 77 | 79 80 74 63 27 68 12 81 19 91 28 56 71 38 24 35 18 4 87 13 62 3 34 44 14
Card 25: 87 8 39 28 6 89 34 17 51 25 | 50 37 16 36 90 60 28 17 84 70 32 22 64 61 6 34 24 56 99 89 40 77 47 68 87
Card 26: 42 82 14 23 59 8 62 53 37 2 | 62 8 14 85 76 53 21 60 79 1 90 19 78 82 42 17 11 49 87 13 59 37 81 2 23
Card 27: 75 95 56 30 17 58 61 11 39 93 | 68 73 94 9 11 86 80 22 61 50 75 62 36 98 17 39 89 93 34 56 30 78 95 58 96
Card 28: 10 54 26 76 5 35 81 67 34 28 | 28 88 89 93 76 35 81 94 26 98 10 84 67 5 65 50 57 34 54 82 4 45 62 24 53
Card 29: 6 40 97 56 4 43 98 55 79 72 | 79 15 43 54 97 4 95 42 40 57 82 91 87 86 68 63 19 1 22 72 7 67 10 84 55
Card 30: 22 85 5 42 74 28 1 63 29 53 | 63 86 80 48 13 2 74 85 25 97 5 43 21 53 88 7 38 29 82 3 30 77 51 11 44
Card 31: 11 69 64 47 44 13 50 33 83 53 | 59 9 57 81 98 69 32 40 11 33 53 20 52 12 37 93 79 64 74 80 71 35 44 7 13
Card 32: 94 44 62 75 35 86 34 20 1 74 | 17 29 50 65 60 57 33 59 31 92 70 11 54 85 99 22 46 53 98 93 97 51 67 64 12
Card 33: 90 55 21 9 10 41 24 51 88 70 | 30 77 78 20 32 1 57 92 15 75 21 37 31 43 60 39 72 54 46 99 53 61 50 33 94
Card 34: 8 77 92 34 84 28 90 40 97 75 | 61 40 99 77 17 28 80 50 37 47 22 70 81 79 97 85 93 15 49 48 69 14 2 12 94
Card 35: 44 61 20 43 35 24 45 53 52 47 | 46 54 93 78 87 31 30 80 23 51 13 99 60 57 38 9 1 19 90 71 70 26 40 97 62
Card 36: 64 40 1 89 19 70 16 71 31 94 | 10 89 43 1 63 77 3 74 62 17 38 54 72 41 50 14 35 59 99 34 52 55 22 44 96
Card 37: 74 56 86 52 37 58 30 55 79 9 | 49 28 37 12 97 61 19 36 90 45 48 21 86 58 96 82 9 87 66 44 35 77 81 70 22
Card 38: 34 46 73 59 45 65 85 27 16 42 | 17 93 58 98 88 64 26 35 2 84 86 80 89 4 48 83 28 50 32 21 74 69 95 40 57
Card 39: 51 82 59 67 24 8 32 23 96 40 | 76 40 59 83 65 24 4 29 88 21 82 68 95 64 10 1 62 37 81 32 74 47 56 63 48
Card 40: 80 57 26 4 27 39 34 24 49 78 | 65 64 86 59 25 16 92 66 13 54 46 91 29 47 32 21 81 14 30 7 62 37 55 41 36
Card 41: 12 70 15 72 82 43 53 21 58 51 | 7 56 3 30 36 45 28 94 67 89 39 2 48 47 24 29 16 20 22 18 41 37 49 93 77
Card 42: 60 85 83 5 82 63 48 36 4 40 | 89 43 57 86 31 45 88 37 90 3 46 94 29 12 25 40 38 50 72 5 9 15 49 16 87
Card 43: 33 94 66 90 14 72 73 59 55 15 | 87 34 37 35 4 77 25 80 54 10 86 6 12 48 60 61 36 55 43 64 97 30 41 5 95
Card 44: 31 17 65 48 36 63 33 46 25 87 | 9 70 4 42 53 97 57 32 80 14 95 23 3 12 15 52 6 34 71 74 39 27 66 22 20
Card 45: 88 52 86 36 5 15 65 61 18 17 | 36 96 32 56 1 80 48 89 95 97 60 91 85 21 82 10 3 75 66 93 51 37 28 23 83
Card 46: 23 86 32 98 41 65 17 89 69 39 | 69 4 80 41 89 43 86 44 16 40 99 8 77 32 39 51 19 36 73 56 90 83 5 17 76
Card 47: 80 15 87 14 9 27 40 44 60 8 | 33 27 15 67 34 8 14 58 37 80 40 73 38 87 84 55 94 60 9 35 42 46 4 79 44
Card 48: 94 32 34 99 60 33 11 3 30 96 | 72 27 32 33 56 11 97 61 94 96 26 93 30 41 83 17 3 60 34 2 47 99 40 24 90
Card 49: 53 60 74 44 36 88 64 45 8 34 | 89 84 68 79 30 67 75 76 21 53 26 72 51 85 18 44 7 25 60 74 64 17 37 88 86
Card 50: 90 69 91 1 43 26 77 19 61 65 | 65 34 92 13 48 46 69 19 44 77 99 11 63 91 76 61 73 53 1 81 23 12 40 26 43
Card 51: 22 94 42 24 28 37 61 88 86 12 | 5 31 3 34 56 82 70 68 39 91 53 22 16 81 71 54 99 41 44 90 24 37 12 27 61
Card 52: 93 57 50 9 14 42 66 23 21 1 | 21 33 48 18 71 1 27 54 11 77 74 22 92 41 34 14 98 36 61 70 89 80 82 10 55
Card 53: 21 12 1 93 98 69 91 8 4 89 | 80 7 1 68 92 32 83 21 76 20 63 33 28 73 43 12 56 5 15 40 89 52 16 22 9
Card 54: 22 52 94 9 63 10 16 1 82 4 | 43 47 48 81 24 35 9 16 94 44 85 18 13 64 49 82 52 77 10 21 41 12 74 79 39
Card 55: 71 92 42 84 19 43 13 54 1 88 | 73 23 32 18 52 38 35 81 45 96 92 15 57 19 55 43 51 12 7 88 62 69 71 5 53
Card 56: 13 52 23 69 26 92 37 47 99 54 | 38 64 66 22 26 99 93 23 86 9 29 98 57 48 51 79 50 42 90 60 87 13 25 5 4
Card 57: 62 8 38 58 6 99 10 14 72 94 | 29 56 27 53 61 77 95 39 24 46 19 40 30 31 9 93 78 91 79 25 20 4 12 67 87
Card 58: 34 57 49 6 78 13 53 81 75 98 | 41 58 21 56 64 7 97 11 80 4 83 12 44 51 62 26 5 22 46 45 27 95 10 16 43
Card 59: 86 27 78 51 67 90 10 44 85 87 | 13 66 32 54 65 92 91 55 53 47 5 11 64 49 18 10 8 16 23 9 12 29 50 70 61
Card 60: 26 62 95 72 31 98 50 9 25 44 | 56 94 2 53 11 51 22 66 12 45 36 17 37 14 78 48 4 29 64 76 39 65 1 15 24
Card 61: 47 54 93 76 68 98 64 15 53 22 | 70 19 86 7 44 45 5 39 30 38 6 83 33 15 3 51 49 29 98 37 56 21 78 60 90
Card 62: 46 53 15 99 29 7 10 34 79 12 | 46 56 94 40 66 26 33 99 39 28 12 67 53 74 11 22 92 34 29 79 7 32 98 15 10
Card 63: 44 3 92 7 24 33 23 31 10 12 | 23 1 96 92 72 33 86 4 80 68 25 12 40 45 17 29 94 36 81 44 61 83 10 24 19
Card 64: 21 95 89 20 7 16 23 73 58 86 | 84 47 11 18 96 90 73 2 38 51 29 30 58 99 76 86 21 1 37 68 16 32 39 22 35
Card 65: 15 42 28 50 91 52 73 79 70 45 | 98 70 45 19 4 46 86 11 68 96 41 58 39 7 64 15 50 89 28 72 47 17 40 27 79
Card 66: 91 48 16 1 24 3 75 60 41 86 | 98 52 55 23 66 14 92 50 74 75 3 1 58 91 13 97 90 73 78 62 48 79 65 77 87
Card 67: 74 29 43 82 93 73 58 98 3 8 | 32 63 13 60 49 73 18 74 65 78 97 92 29 23 43 5 72 35 48 99 3 15 93 52 64
Card 68: 35 33 72 82 59 8 27 67 19 31 | 35 36 80 7 63 62 33 44 55 31 8 75 1 64 95 27 47 79 40 14 72 19 42 69 91
Card 69: 96 20 45 65 51 91 49 30 79 78 | 58 73 89 36 32 69 81 37 20 60 42 76 29 25 75 65 30 86 19 26 66 34 31 99 8
Card 70: 13 59 90 5 63 29 14 32 77 53 | 56 66 32 77 16 85 47 73 55 86 1 90 69 97 4 78 76 59 49 8 48 37 63 50 72
Card 71: 9 31 29 5 50 37 71 94 78 53 | 28 80 53 55 39 58 42 86 57 81 83 64 95 43 69 51 65 20 75 13 30 70 50 63 5
Card 72: 86 87 49 67 68 46 45 60 23 12 | 35 93 94 6 55 49 40 28 38 62 63 32 52 36 69 17 81 73 16 7 56 89 21 20 86
Card 73: 80 81 75 68 33 79 94 53 8 25 | 9 47 95 99 85 48 62 17 44 77 31 12 1 70 86 34 75 83 68 87 88 96 78 4 18
Card 74: 62 64 51 12 54 2 85 81 22 28 | 98 14 10 71 2 61 29 82 39 55 17 76 31 18 86 97 60 87 93 26 69 33 21 13 6
Card 75: 96 50 88 5 16 85 7 27 51 58 | 94 80 41 53 93 20 83 45 61 40 72 95 97 39 26 32 91 70 99 3 48 62 64 79 86
Card 76: 1 73 41 87 54 57 20 7 98 85 | 21 16 15 66 23 75 86 46 11 90 36 96 34 78 58 33 88 56 93 74 8 64 30 28 5
Card 77: 91 50 88 4 58 31 20 6 24 44 | 10 61 50 55 62 47 75 78 80 88 93 4 41 59 95 91 58 31 24 70 22 20 6 12 44
Card 78: 22 28 36 88 75 82 4 99 90 55 | 14 33 24 75 43 4 41 88 16 15 77 36 99 22 52 82 61 55 28 27 89 97 51 32 90
Card 79: 96 3 13 91 24 65 77 1 44 43 | 13 43 24 56 6 3 77 65 61 5 41 73 44 60 21 96 74 72 19 16 1 52 37 91 46
Card 80: 71 29 61 75 72 55 16 26 6 62 | 15 65 38 71 16 10 75 50 6 92 4 26 79 29 94 46 62 63 45 61 51 86 74 55 72
Card 81: 34 57 14 90 99 97 44 31 73 64 | 38 47 54 86 50 4 46 48 14 43 16 15 82 27 51 8 33 59 17 55 84 57 44 19 12
Card 82: 77 46 25 67 61 5 37 49 50 24 | 77 89 5 4 61 43 50 76 55 78 46 6 42 66 25 52 49 7 85 95 37 24 48 23 67
Card 83: 66 30 35 68 10 67 18 14 52 59 | 6 37 16 61 95 66 91 54 79 50 97 21 2 33 74 29 80 77 1 59 41 31 10 13 9
Card 84: 29 39 48 7 2 90 47 93 88 46 | 57 90 50 84 74 52 7 27 93 96 54 78 48 39 29 46 40 88 47 13 2 89 70 25 86
Card 85: 91 93 84 76 7 1 96 60 98 67 | 98 88 10 21 91 27 93 44 1 67 79 7 58 87 47 30 76 96 20 60 2 84 41 73 54
Card 86: 73 1 14 37 79 63 97 75 2 60 | 80 3 56 45 43 23 1 95 72 13 49 27 9 78 55 15 74 40 75 94 86 63 76 32 52
Card 87: 76 35 41 4 25 97 62 99 77 98 | 93 35 81 77 37 76 88 98 53 38 4 48 25 23 84 97 2 49 46 99 42 1 41 95 62
Card 88: 3 15 12 58 57 4 43 44 10 55 | 78 55 51 54 4 44 42 35 69 3 79 25 57 10 77 34 30 38 12 58 43 93 14 86 15
Card 89: 4 99 45 58 49 30 59 21 25 13 | 73 43 99 85 74 13 30 58 45 31 21 52 25 49 29 4 6 62 19 92 39 16 18 89 59
Card 90: 81 84 6 57 1 69 3 68 13 49 | 20 25 40 92 84 38 83 53 94 66 49 52 17 72 56 8 33 43 22 81 64 47 28 36 5
Card 91: 68 97 58 96 34 66 61 81 56 90 | 25 28 51 34 59 40 64 96 97 48 30 90 63 37 89 74 16 87 81 5 1 54 66 57 62
Card 92: 10 53 16 70 72 21 34 4 65 54 | 98 21 63 53 55 75 72 93 7 24 15 25 92 61 67 86 70 10 12 34 65 54 3 5 36
Card 93: 77 45 87 88 72 16 51 26 99 23 | 42 36 65 78 52 92 2 44 9 83 58 37 20 99 57 94 3 66 22 93 86 43 1 17 75
Card 94: 86 29 2 71 17 60 43 8 11 81 | 92 35 45 12 38 47 22 9 13 11 48 58 63 68 20 96 46 94 85 42 66 25 83 26 57
Card 95: 41 71 40 45 4 50 15 94 69 75 | 99 37 47 74 95 19 5 54 20 36 63 23 4 38 28 44 3 83 80 67 93 49 84 6 40
Card 96: 16 14 18 42 90 63 96 37 41 76 | 52 22 37 10 25 99 76 73 93 89 1 79 23 85 6 64 16 97 39 55 96 18 77 69 92
Card 97: 32 69 95 78 91 75 76 45 43 79 | 8 89 34 49 55 71 3 23 83 2 61 68 31 35 46 87 42 13 45 18 25 47 28 39 86
Card 98: 24 37 74 59 60 94 39 40 63 45 | 23 52 8 85 53 70 18 11 46 30 6 83 90 26 24 34 55 71 82 97 37 31 38 68 5
Card 99: 98 5 72 42 44 82 65 57 81 54 | 61 95 32 6 37 43 33 35 49 85 10 17 52 71 68 20 83 58 77 36 69 50 96 38 23
Card 100: 27 84 51 44 31 19 34 98 77 18 | 44 43 39 5 30 48 74 88 23 22 6 35 59 2 20 92 79 89 72 58 80 11 52 10 57
Card 101: 82 38 31 7 27 6 19 20 3 94 | 75 77 95 65 69 15 52 16 34 32 66 9 28 12 22 73 44 61 70 30 88 72 71 45 18
Card 102: 16 59 11 8 88 9 48 1 68 90 | 44 12 18 99 73 27 91 82 29 20 63 1 84 57 87 86 3 54 42 85 78 98 51 60 36
Card 103: 84 77 29 61 67 60 23 89 19 87 | 48 1 84 7 87 15 32 81 25 67 38 29 23 45 9 89 61 88 55 19 50 58 3 56 64
Card 104: 51 4 13 59 15 92 17 65 26 84 | 3 29 85 4 58 66 51 31 2 55 65 54 13 16 24 92 38 26 59 90 67 99 71 33 70
Card 105: 55 58 37 46 12 74 62 16 47 26 | 16 64 46 68 47 56 72 73 4 66 80 58 35 12 55 37 74 62 26 60 69 75 13 63 33
Card 106: 39 80 37 10 26 47 66 79 12 64 | 34 82 72 10 12 20 40 7 39 25 89 9 26 93 5 1 47 64 79 96 66 18 80 37 13
Card 107: 95 28 45 60 91 73 11 23 26 94 | 16 26 8 58 83 90 31 44 80 50 30 11 97 70 89 37 60 38 41 69 55 99 28 65 45
Card 108: 39 54 74 12 56 63 13 34 32 40 | 88 70 89 74 87 96 44 58 2 79 34 37 63 16 30 61 41 23 54 95 33 72 73 40 82
Card 109: 98 96 81 13 69 5 73 50 76 47 | 20 49 30 80 76 50 31 81 66 74 3 86 12 73 5 64 47 34 15 9 25 13 24 96 79
Card 110: 47 43 1 83 76 38 30 45 50 12 | 56 99 38 43 74 68 27 83 55 49 48 78 91 41 51 72 33 76 15 12 22 50 53 26 13
Card 111: 51 68 7 71 30 79 14 26 59 66 | 11 16 79 30 26 7 27 18 53 45 68 76 15 87 77 92 57 62 71 14 10 59 66 78 91
Card 112: 84 37 54 21 19 30 38 20 94 88 | 40 19 38 21 68 62 48 26 44 12 91 74 20 30 42 89 98 51 7 54 37 58 1 88 64
Card 113: 91 41 56 30 18 47 74 45 17 9 | 87 77 68 93 88 56 2 1 69 41 36 9 47 33 13 44 18 25 70 86 45 8 32 91 46
Card 114: 83 62 7 35 48 11 37 69 93 84 | 90 24 81 74 17 54 49 65 67 19 55 47 43 14 64 99 33 28 29 98 36 63 57 52 58
Card 115: 44 84 39 20 33 59 31 34 8 95 | 31 81 39 7 16 92 35 53 11 97 59 78 10 80 91 62 54 29 65 3 75 47 26 24 63
Card 116: 65 74 70 33 44 56 13 10 85 63 | 11 20 54 17 73 41 24 79 18 92 43 76 88 39 95 80 7 75 36 52 94 35 78 31 4
Card 117: 34 82 96 60 48 66 6 37 14 98 | 89 64 6 95 11 54 66 17 45 10 83 98 63 15 1 55 52 68 60 94 79 22 85 57 39
Card 118: 20 80 46 41 97 57 99 56 64 91 | 48 61 98 11 95 50 62 81 10 79 22 32 37 71 43 19 36 58 29 9 16 64 65 17 96
Card 119: 96 42 71 23 45 73 84 94 51 77 | 68 35 22 56 81 54 47 3 77 50 73 51 90 29 82 4 52 8 66 76 15 92 65 24 14
Card 120: 56 34 70 85 68 77 79 94 84 73 | 1 82 60 23 78 10 58 29 26 70 93 2 88 87 4 33 44 69 47 12 48 6 54 41 96
Card 121: 60 85 78 83 68 26 62 65 91 69 | 97 63 12 4 9 46 5 10 52 99 24 74 40 95 35 79 23 39 45 17 38 85 59 69 89
Card 122: 48 51 12 57 61 41 98 22 11 37 | 27 24 95 81 20 73 92 31 32 68 6 63 38 40 83 56 96 62 99 7 30 11 85 75 46
Card 123: 47 62 78 39 69 77 2 43 83 36 | 28 89 49 13 40 70 22 16 23 19 57 61 14 51 44 53 91 50 64 66 33 18 8 15 79
Card 124: 22 28 12 21 40 57 84 5 87 46 | 67 46 31 64 58 22 76 75 37 82 70 21 87 69 13 3 12 5 84 28 14 57 95 61 40
Card 125: 54 74 63 95 39 93 11 81 24 69 | 39 67 71 19 81 84 53 66 51 74 40 63 17 49 95 3 44 11 9 72 91 24 54 56 86
Card 126: 49 98 17 94 19 37 69 1 40 20 | 19 90 77 21 94 96 98 34 49 15 28 76 71 22 83 37 1 69 53 12 31 40 17 42 20
Card 127: 97 45 16 74 87 96 76 60 29 3 | 87 2 45 66 29 17 72 22 15 74 54 38 3 37 60 76 97 62 49 96 61 51 5 16 25
Card 128: 19 79 62 95 67 59 77 5 70 98 | 56 70 21 85 18 68 88 98 79 95 5 83 16 77 91 63 90 19 84 76 37 59 62 67 44
Card 129: 94 73 69 51 30 98 1 65 11 45 | 71 5 44 7 52 79 61 99 11 25 10 8 78 33 57 51 75 20 77 9 6 91 4 46 12
Card 130: 26 98 8 44 84 7 29 47 70 24 | 13 54 48 6 45 78 83 28 10 2 29 71 16 44 62 89 24 53 46 67 20 43 84 91 88
Card 131: 41 27 22 4 39 82 84 68 29 85 | 22 85 16 24 44 25 41 46 23 39 88 9 82 51 90 64 13 80 74 15 4 78 91 94 93
Card 132: 32 46 49 99 77 63 37 18 54 80 | 59 65 42 55 47 18 6 32 9 37 85 52 30 94 72 13 77 97 22 46 26 99 90 92 17
Card 133: 70 72 53 32 24 71 17 27 39 67 | 9 87 57 49 90 81 40 28 37 8 67 51 18 65 99 16 3 31 73 12 91 44 55 70 60
Card 134: 10 65 66 5 88 67 83 75 52 33 | 90 37 65 2 52 69 34 4 45 72 15 1 44 96 94 36 35 76 5 56 63 79 20 12 75
Card 135: 71 54 43 41 34 29 16 88 77 44 | 9 33 48 82 52 74 28 10 22 42 15 47 27 5 7 23 56 55 94 49 63 72 61 78 46
Card 136: 10 97 3 82 73 87 95 80 35 63 | 20 63 50 79 52 77 2 38 84 83 59 74 51 26 5 46 9 49 19 8 13 36 15 7 23
Card 137: 97 53 91 22 90 12 93 23 3 86 | 96 82 24 21 30 51 65 44 50 31 71 34 54 38 36 88 94 48 32 83 99 84 74 27 33
Card 138: 8 97 59 46 75 32 65 82 40 44 | 5 81 19 36 54 2 14 39 20 76 3 68 46 50 47 15 96 89 95 41 37 22 99 40 58
Card 139: 66 97 45 10 72 63 29 43 84 9 | 61 3 74 56 58 4 15 6 68 55 20 23 80 47 83 44 91 19 31 50 54 73 93 45 53
Card 140: 1 9 81 51 8 90 35 61 82 27 | 55 49 88 60 7 93 46 96 70 75 18 37 41 52 36 78 77 80 5 31 76 79 65 99 20
Card 141: 93 8 76 47 31 92 18 23 29 34 | 95 67 73 27 9 98 85 70 96 36 87 89 52 63 65 78 37 24 3 90 2 97 19 93 51
Card 142: 34 71 94 2 79 18 69 89 44 19 | 3 10 9 62 71 44 37 32 97 85 2 89 48 6 14 95 17 91 5 99 11 33 41 39 22
Card 143: 1 91 47 65 14 42 96 12 52 6 | 70 47 45 3 2 54 52 42 65 25 16 38 91 57 72 96 90 36 34 14 79 78 1 39 76
Card 144: 32 9 19 63 16 5 81 1 2 49 | 90 19 52 28 23 75 34 57 70 81 1 36 26 2 32 27 63 43 16 4 49 99 9 21 5
Card 145: 11 45 95 1 92 20 34 49 70 28 | 66 27 57 51 23 24 81 69 56 80 55 89 1 47 95 32 7 5 14 92 99 73 20 84 65
Card 146: 29 84 70 31 61 77 47 89 96 63 | 32 96 52 23 73 79 47 66 67 46 31 26 8 82 15 29 89 84 77 72 11 1 63 97 27
Card 147: 90 51 66 50 32 47 39 20 24 46 | 82 49 76 79 57 9 94 84 80 97 51 4 35 83 63 50 69 72 20 58 31 93 7 24 62
Card 148: 50 53 44 71 81 41 31 57 88 2 | 41 2 68 51 53 37 25 65 34 24 50 98 95 76 88 69 82 42 81 58 31 11 77 33 21
Card 149: 54 32 10 37 35 3 64 4 34 14 | 77 80 53 7 4 29 12 33 69 35 40 32 11 44 83 15 34 2 54 48 30 46 84 14 81
Card 150: 68 41 72 13 84 60 20 54 6 90 | 56 54 65 25 5 32 39 34 26 63 16 86 75 92 95 28 78 62 24 8 48 98 83 69 57
Card 151: 61 48 8 19 95 28 56 34 68 72 | 96 73 69 11 10 29 91 44 28 39 49 34 17 35 19 90 82 61 40 86 95 31 33 81 46
Card 152: 24 65 90 26 97 95 55 68 54 96 | 30 43 70 47 92 96 68 74 26 73 77 97 8 90 86 54 69 17 79 55 16 78 7 38 6
Card 153: 8 61 75 62 12 30 66 64 97 6 | 63 70 81 41 47 85 76 11 90 58 45 39 95 97 22 34 78 82 86 7 99 18 35 31 29
Card 154: 42 2 81 53 80 36 62 64 89 49 | 99 80 49 84 24 91 93 70 88 30 19 47 79 32 33 18 62 25 8 60 28 92 14 89 42
Card 155: 30 76 60 19 12 49 63 33 77 90 | 91 22 96 4 76 47 8 64 58 40 27 49 52 19 63 15 43 73 97 83 61 80 65 34 9
Card 156: 75 23 40 88 39 96 9 36 21 51 | 39 70 67 1 92 62 57 5 27 87 78 81 51 28 63 23 56 2 93 84 75 21 29 97 20
Card 157: 95 86 3 18 98 85 31 22 71 79 | 6 8 89 88 7 38 39 18 15 40 22 96 87 55 90 80 36 9 20 83 1 34 49 73 98
Card 158: 31 36 87 28 57 21 64 35 55 5 | 96 2 78 38 62 32 40 75 14 43 65 71 70 74 61 87 86 1 80 47 23 27 45 67 42
Card 159: 52 31 14 72 16 90 94 45 88 29 | 64 87 46 77 51 74 40 5 16 92 95 82 12 6 38 35 72 98 89 11 84 97 99 57 93
Card 160: 69 51 53 88 58 54 27 48 78 4 | 70 87 72 32 33 23 94 83 10 73 76 19 91 68 80 89 34 64 58 13 98 5 78 75 52
Card 161: 68 34 80 98 81 36 19 61 79 40 | 50 74 25 29 57 12 73 42 83 8 86 30 66 55 20 17 49 84 82 41 46 97 71 23 44
Card 162: 94 12 32 66 57 67 97 39 65 7 | 71 23 76 47 49 9 86 58 50 78 88 15 90 43 54 27 37 81 75 13 34 64 87 2 40
Card 163: 57 72 66 78 45 23 76 2 24 81 | 58 17 19 44 5 3 2 57 39 82 88 24 47 8 90 31 66 92 68 45 72 78 81 76 23
Card 164: 22 57 61 52 83 80 99 37 39 36 | 80 23 67 54 43 99 83 28 37 13 3 55 91 52 51 98 82 27 21 61 22 36 85 57 39
Card 165: 62 81 8 72 15 53 36 98 51 22 | 76 6 26 73 65 98 36 72 33 97 5 81 53 69 22 15 14 44 11 8 51 62 13 45 20
Card 166: 28 33 40 30 17 74 81 2 88 62 | 4 79 81 96 93 48 62 39 40 78 33 75 26 29 37 30 2 17 31 28 15 88 97 72 74
Card 167: 16 1 46 98 76 85 35 91 21 18 | 21 82 94 95 87 66 89 30 64 10 33 93 23 29 34 47 96 20 77 83 81 75 88 46 49
Card 168: 50 86 74 64 85 75 80 21 5 46 | 85 74 50 64 96 51 49 55 48 72 5 14 3 39 92 54 46 38 21 86 33 97 61 75 15
Card 169: 51 49 66 48 30 10 32 67 60 69 | 42 32 67 43 62 66 10 38 37 60 51 48 9 29 16 49 74 25 36 91 24 69 81 17 30
Card 170: 17 24 18 73 64 60 56 38 80 8 | 94 45 30 39 71 12 88 89 61 2 23 40 9 48 42 52 28 96 59 95 19 72 36 81 25
Card 171: 38 32 75 85 98 11 17 57 89 56 | 52 57 75 85 32 61 38 98 3 16 60 50 56 34 26 89 77 11 17 49 81 9 20 8 1
Card 172: 1 30 98 25 63 39 29 17 58 40 | 98 6 30 85 27 25 69 17 93 47 29 31 63 5 23 56 87 7 91 39 35 58 59 22 38
Card 173: 88 59 3 87 21 91 24 4 82 48 | 97 53 67 73 28 66 45 27 36 88 64 99 92 24 26 87 72 96 84 59 85 68 82 49 10
Card 174: 56 79 60 1 77 37 83 9 30 92 | 2 15 71 79 60 31 32 58 34 74 42 1 18 5 38 83 97 12 92 86 56 95 19 85 98
Card 175: 2 50 25 89 41 75 94 78 95 17 | 72 81 28 48 55 17 69 66 40 91 78 32 27 2 95 13 50 80 15 3 49 94 90 85 25
Card 176: 51 22 14 16 1 62 64 84 12 25 | 22 34 91 76 62 38 88 78 35 95 51 45 12 92 61 28 81 16 36 14 8 66 9 10 56
Card 177: 83 47 79 45 75 15 44 52 11 88 | 26 5 59 93 83 88 79 44 4 28 32 86 52 89 56 47 97 48 80 15 3 40 98 18 33
Card 178: 87 42 52 70 32 7 39 6 9 17 | 17 9 5 45 52 4 70 72 27 3 78 24 50 39 94 87 47 14 42 6 44 95 85 88 7
Card 179: 79 87 75 44 93 9 71 16 11 5 | 44 37 11 92 59 50 13 91 36 45 87 77 99 31 68 94 9 62 71 38 8 16 42 55 5
Card 180: 18 98 61 58 87 41 51 37 28 79 | 65 32 36 92 49 45 10 93 40 4 67 76 55 42 88 30 75 44 23 71 98 51 14 78 24
Card 181: 7 17 80 68 38 36 86 59 75 96 | 68 64 54 8 12 6 88 45 80 98 51 60 53 22 75 50 34 77 29 38 24 9 48 70 36
Card 182: 9 57 37 30 78 31 18 40 49 32 | 11 57 40 50 68 22 18 36 74 91 29 52 70 81 75 69 38 7 26 24 33 55 5 34 95
Card 183: 36 15 99 95 83 87 22 80 59 31 | 61 99 31 20 55 57 89 34 26 72 39 67 4 22 2 91 24 83 56 44 14 81 49 10 12
Card 184: 70 55 77 4 95 51 10 13 75 27 | 70 38 97 88 85 24 48 67 69 89 13 49 28 60 71 10 93 72 84 15 57 98 33 16 20
Card 185: 32 53 24 75 26 20 94 4 73 57 | 80 22 1 10 4 71 16 44 87 35 19 72 47 40 59 36 58 2 8 43 23 46 37 34 12
Card 186: 93 84 73 24 6 37 72 41 55 75 | 36 71 80 32 2 68 58 47 33 6 70 10 78 19 44 82 39 90 54 91 88 20 28 64 87
Card 187: 62 23 40 15 57 69 94 64 60 85 | 63 26 36 8 90 42 58 73 30 28 32 18 50 48 54 88 72 86 13 37 22 5 87 79 77
Card 188: 84 42 64 5 88 96 45 91 66 25 | 91 32 93 75 25 2 73 85 88 33 66 58 45 53 28 42 57 40 39 24 5 84 96 78 67
Card 189: 59 99 36 6 34 46 98 29 69 53 | 52 17 67 11 98 25 41 34 59 69 46 99 72 92 80 14 26 1 51 76 33 95 36 6 29
Card 190: 75 5 85 72 81 96 7 74 21 39 | 32 44 7 87 42 72 86 4 71 81 95 84 85 33 75 78 74 76 96 21 37 58 10 64 73
Card 191: 28 83 55 46 56 85 78 21 47 37 | 46 47 82 21 57 29 54 59 78 39 30 33 89 48 83 55 28 85 94 24 72 96 37 56 9
Card 192: 72 91 29 35 2 42 71 24 82 55 | 49 29 84 40 69 85 24 48 3 42 61 9 63 37 41 79 11 20 72 14 80 71 16 38 82
Card 193: 61 88 76 45 71 29 84 78 81 83 | 85 63 56 2 49 92 47 30 71 43 38 76 60 88 81 84 98 94 8 6 51 58 42 70 61
Card 194: 28 18 61 86 27 79 32 48 58 96 | 13 20 95 38 63 46 51 78 90 3 80 15 72 76 88 77 69 24 6 35 28 62 5 36 65
Card 195: 96 89 40 50 26 36 86 75 62 10 | 6 5 69 72 82 45 3 33 86 71 97 34 36 91 42 20 80 93 40 35 96 89 17 31 50
Card 196: 45 11 82 74 51 55 19 43 24 94 | 63 14 22 75 94 29 19 39 13 8 82 32 76 41 53 43 54 91 11 17 62 21 71 42 86
Card 197: 20 64 71 4 50 90 49 17 8 6 | 65 92 6 60 94 54 56 33 80 75 69 15 49 71 26 81 67 37 74 11 20 25 43 85 19
Card 198: 28 11 15 25 97 2 22 31 29 73 | 14 35 15 87 81 54 49 2 20 79 44 96 38 94 55 97 17 86 65 46 32 21 67 58 27
Card 199: 50 83 4 30 82 92 76 11 55 19 | 47 50 57 53 5 14 28 85 46 88 94 51 13 38 3 89 66 45 87 24 31 96 69 73 44
Card 200: 55 23 78 25 87 33 36 80 79 38 | 99 30 52 4 85 95 66 26 28 91 20 45 72 68 8 35 92 86 93 43 65 97 14 50 44
Card 201: 33 75 55 46 25 63 76 37 1 73 | 68 64 22 99 12 56 43 28 44 80 91 65 78 27 71 32 95 29 59 36 45 60 77 62 82
Card 202: 66 29 75 28 68 42 98 21 82 99 | 23 92 38 44 45 12 6 4 17 64 67 60 36 79 46 58 14 73 71 72 81 49 13 2 30"""
val ins = Day4();
println(ins.two(inputReal))
}
| 0 | Kotlin | 0 | 0 | a36addef07f61072cbf4c7c71adf2236a53959a5 | 26,242 | advent-code | MIT License |
AOC-2023/src/main/kotlin/Day04.kt | sagar-viradiya | 117,343,471 | false | {"Kotlin": 72737} | import utils.*
import kotlin.math.pow
object Day04 {
fun part01(input: String): Long {
return input
.splitAtNewLines()
.map { card ->
val numbers = card.splitAtColon()[1].trim().split("|")
val winningNumbers = numbers[0].trim().splitAtWhiteSpace().toIntList()
val cardNumbers = numbers[1].trim().splitAtWhiteSpace().toIntList()
Pair(winningNumbers, cardNumbers)
}.map { pair ->
Pair<Map<Int, Int>, Map<Int, Int>>(
pair.first.groupingBy { it }.eachCount(),
pair.second.groupingBy { it }.eachCount()
)
}.sumOf { pair ->
val numberOfMatches = pair.second.entries.sumOf { numberEntry ->
if (pair.first.contains(numberEntry.key)) {
numberEntry.value
} else 0
}
if (numberOfMatches > 0) {
2.0.pow((numberOfMatches - 1).toDouble()).toLong()
} else {
0L
}
}
}
fun part02(input: String): Int {
val cardWon = mutableMapOf<Int, Int>()
input
.splitAtNewLines()
.map { card ->
val numbers = card.splitAtColon()[1].trim().split("|")
val winningNumbers = numbers[0].trim().splitAtWhiteSpace().toIntList()
val cardNumbers = numbers[1].trim().splitAtWhiteSpace().toIntList()
Pair(winningNumbers, cardNumbers)
}.map { pair ->
Pair<Map<Int, Int>, Map<Int, Int>>(
pair.first.groupingBy { it }.eachCount(),
pair.second.groupingBy { it }.eachCount()
)
}.forEachIndexed { index, pair ->
val currentCards = cardWon.getOrPut(index + 1) {
1
}
val numberOfMatches = pair.second.entries.sumOf { numberEntry ->
if (pair.first.contains(numberEntry.key)) {
numberEntry.value
} else 0
}
repeat(numberOfMatches) { count ->
cardWon[index + 2 + count] = cardWon.getOrPut(index + 2 + count) { 1 } + currentCards
}
}
return cardWon.entries.sumOf { it.value }
}
} | 0 | Kotlin | 0 | 0 | 7f88418f4eb5bb59a69333595dffa19bee270064 | 2,455 | advent-of-code | MIT License |
src/main/kotlin/com/hopkins/aoc/day4/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day4
import java.io.File
const val debug = true
const val part = 2
val scores = buildScores(20)
/** Advent of Code 2023: Day 4 */
fun main() {
if (debug) {
println("Scores: $scores")
}
val inputFile = File("input/input4.txt")
val lines: List<String> = inputFile.readLines()
// Sum the points from each card to get the total
val totalPoints = lines.sumOf { line ->
val cardInfo = extractCardInfo(line)
val points = cardInfo.getPoints()
if (debug) {
println("Card {$cardInfo} points=$points matches=${cardInfo.getMatches()}")
}
points
}
if (part == 1) {
println("Total Points: $totalPoints") // 23941
return
}
val cardMap: Map<Int, CardInfo> =
lines.map { line -> extractCardInfo(line) }.associateBy { it.id }
var numCards = 0
var cards = cardMap.values
var round = 1
while (cards.isNotEmpty()) {
if (debug) {
println("Round: $round Cards: ${cards.map { it.id }}")
}
numCards += cards.size
round++
val wonCards = cards.flatMap { card ->
val numMatches = card.getMatches().size
IntRange(card.id + 1, card.id + numMatches)
}.mapNotNull { cardMap[it] }
cards = wonCards
}
println("Num Cards: $numCards")
}
fun extractCardInfo(line: String): CardInfo {
// Split into sections around ":" and "|"
// Example: Card 1: 12 13 | 14 15 4
val (card, winning, ours) = line.split(":", "|")
// Extract the card number
val id: Int = card.substring(5).trim().toInt()
// Extract winning and our numbers
return CardInfo(id, extractNumbers(winning).toSet(), extractNumbers(ours).toList())
}
class CardInfo(val id: Int, private val winners: Set<Int>, private val ours: List<Int>) {
fun getPoints(): Int =
scores[getMatches().size]
fun getMatches(): Collection<Int> =
ours.intersect(winners)
override fun toString(): String = "id=$id, winners=$winners, ours=$ours"
}
fun buildScores(count: Int) : List<Int> =
buildList {
add(0)
for (i in 0 until count) {
add(Math.pow(2.0, i.toDouble()).toInt())
}
}
fun extractNumbers(numbers: String): Sequence<Int> {
return numbers.split(" ")
.asSequence()
.map { it.trim() }
.filter { it.isNotEmpty() }
.map { it.toInt() }
} | 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 2,456 | aoc2023 | MIT License |
src/Day22.kt | astrofyz | 572,802,282 | false | {"Kotlin": 124466} | import java.io.File
fun main() {
fun parseMap(input: List<String>): Pair<MutableSet<Pair<Int, Int>>, MutableSet<Pair<Int, Int>>> {
var groveMap = mutableSetOf<Pair<Int, Int>>()
var blockedTiles = mutableSetOf<Pair<Int, Int>>()
for ((row, line) in input.withIndex()){
for ((col, elem) in line.withIndex()){
when (elem){
'.' -> groveMap.add(Pair(row, col))
'#' -> {blockedTiles.add(Pair(row, col)); groveMap.add(Pair(row, col))}
else -> continue
}
}
}
return Pair(groveMap, blockedTiles)
}
fun part1(input: String){
val (groveMap, blockedTiles) = parseMap(input.split("\n\n")[0].split("\n"))
var regex = "\\d+|\\D+".toRegex()
val path = regex.findAll(input.split("\n\n")[1]).map { it.value }.toList()
var colMin = groveMap.filter { it.first == 0 }.map { it.second }.toList().min()
var Pos = groveMap.filter { (it.first == 0)&&(it.second == colMin) }.take(1)[0]
var facing = ">"
var facingMapR = mapOf(">" to "v", "v" to "<", "<" to "^", "^" to ">")
var facingMapL = mapOf(">" to "^", "^" to "<", "<" to "v", "v" to ">")
var facingDir = mapOf(">" to Pair(0, 1), "v" to Pair(1, 0), "<" to Pair(0, -1), "^" to Pair(-1, 0))
fun Pair<Int, Int>.move(step: String, facing: String): Pair<Pair<Int, Int>, String> {
// println("move here $step $facing")
var startPos = Pair(this.first, this.second)
var nextPos = Pair(0, 0)
repeat(step.toInt()) {
nextPos = Pair(
startPos.first + (facingDir[facing]?.first ?: 0),
startPos.second + (facingDir[facing]?.second ?: 0))
if ((nextPos !in blockedTiles)&&(nextPos !in groveMap)){
when (facing){
">" -> nextPos = Pair(this.first,
groveMap.filter { (it.first == this.first) }.map { it.second }.toList().min())
"<" -> nextPos = Pair(this.first,
groveMap.filter { (it.first == this.first) }.map { it.second }.toList().max())
"^" -> nextPos = Pair(groveMap.filter { (it.second == this.second) }.map { it.first }.toList().max(),
this.second)
"v" -> nextPos = Pair(groveMap.filter { (it.second == this.second) }.map { it.first }.toList().min(),
this.second).also { println("mia") }
}
println("next pos outside of field $nextPos")
}
if (nextPos in blockedTiles) return Pair(startPos, facing)
else startPos = Pair(nextPos.first, nextPos.second)
}
return Pair(startPos, facing)
}
fun Pair<Int, Int>.update(step: String, facing: String): Pair<Pair<Int, Int>, String> {
// println("update here $step, $facing")
when (step){
"R" -> return Pair(this, facingMapR[facing]?: ">") //.also { println("${facingMapR[facing]}") }
"L" -> return Pair(this, facingMapL[facing]?: "<") //.also { println("${facingMapL[facing]}") }
else -> return this.move(step, facing)
}
}
for (step in path){
println("$step, $facing")
var curPair = Pos.update(step, facing)
Pos = curPair.first
facing = curPair.second
println("$Pos, $facing")
}
}
fun part2(input: String){
var size = 50
val (groveMap, blockedTiles) = parseMap(input.split("\n\n")[0].split("\n"))
var regex = "\\d+|\\D+".toRegex()
val path = regex.findAll(input.split("\n\n")[1]).map { it.value }.toList()
var colMin = groveMap.filter { it.first == 0 }.map { it.second }.toList().min()
var Pos = groveMap.filter { (it.first == 0)&&(it.second == colMin) }.take(1)[0]
var facing = ">"
var facingMapR = mapOf(">" to "v", "v" to "<", "<" to "^", "^" to ">")
var facingMapL = mapOf(">" to "^", "^" to "<", "<" to "v", "v" to ">")
var facingDir = mapOf(">" to Pair(0, 1), "v" to Pair(1, 0), "<" to Pair(0, -1), "^" to Pair(-1, 0))
fun Pair<Int, Int>.move(step: String, facing: String): Pair<Pair<Int, Int>, String> {
var startPos = Pair(this.first, this.second)
var nextPos = Pair(0, 0)
var newFacing = facing
repeat(step.toInt()) {
nextPos = Pair(
startPos.first + (facingDir[facing]?.first ?: 0),
startPos.second + (facingDir[facing]?.second ?: 0))
if ((nextPos !in blockedTiles)&&(nextPos !in groveMap)){
// println("original nextPos: $nextPos $facing")
when (facing){
">" -> {
if (startPos.first in 0 .. (size-1) && startPos.second == (size*3-1)) { // 6 -> 3
newFacing = "<"
nextPos = Pair((size*3-1) - startPos.first, (size*2-1))
}
if (startPos.first in size .. (size*2-1) && startPos.second == (size*2-1)) { // 4 -> 6
newFacing = "^"
nextPos = Pair((size*1-1), startPos.first + size)
}
if (startPos.first in (size*2-1) .. (size*3-1) && startPos.second == (size*2-1)) { // 3 -> 6
newFacing = "<"
nextPos = Pair((size*3-1) - startPos.first, (size*3-1))
}
if (startPos.first in (size*3)..(size*4-1) && startPos.second == (size*1-1)) { // 1 -> 3
newFacing = "^"
nextPos = Pair((size*3-1), startPos.first - (size*2))
}
}
"<" -> {
if (startPos.first in 0 .. (size*1-1) && startPos.second == size) { // 5 -> 2
newFacing = ">"
nextPos = Pair((size*3-1) - startPos.first, 0)
}
if (startPos.first in size .. (size*2-1) && startPos.second == size) { // 4 -> 2
newFacing = "v"
nextPos = Pair((size*3), startPos.first - size)
}
if (startPos.first in size*2 .. (size*3-1) && startPos.second == 0) { // 2 -> 5
newFacing = ">"
nextPos = Pair((size*3-1) - startPos.first, size)
}
if (startPos.first in size*3..(size*4-1) && startPos.second == 0) { // 1 -> 5
newFacing = "v"
nextPos = Pair(0, startPos.first - size*2)
}
}
"^" -> {
if (startPos.first == 0 && startPos.second in size .. (size*2-1)) { // 5 -> 1
newFacing = ">"
nextPos = Pair(startPos.second + size*2, 0)
}
if (startPos.first == 0 && startPos.second in (size*2) .. (size*3-1)) { // 6 -> 1
newFacing = "^"
nextPos = Pair((size*4-1), startPos.second - size*2)
}
if (startPos.first == size*2 && startPos.second in 0 .. size-1) { // 2 -> 4
newFacing = ">"
nextPos = Pair(startPos.second + size, size)
}
}
"v" -> {
if (startPos.first == size-1 && startPos.second in (size*2) .. (size*3-1)) { // 6 -> 4
newFacing = "<"
nextPos = Pair(startPos.second - size, (size*2-1))
}
if (startPos.first == (size*3-1) && startPos.second in size .. (size*2-1)) { // 3 -> 1
newFacing = "<"
nextPos = Pair(startPos.second + size*2, size-1)
}
if (startPos.first == (size*4-1) && startPos.second in 0 .. size-1) { // 1 -> 6
newFacing = "v"
nextPos = Pair(0, size*2 + startPos.second)
}
}
}
// println("recomputed nextPos: $nextPos $newFacing")
// println("next pos outside of field $nextPos")
}
if (nextPos in blockedTiles) return Pair(startPos, newFacing)
else startPos = Pair(nextPos.first, nextPos.second)
}
return Pair(startPos, newFacing)
}
fun Pair<Int, Int>.update(step: String, facing: String): Pair<Pair<Int, Int>, String> {
// println("update here $step, $facing")
when (step){
"R" -> return Pair(this, facingMapR[facing]?: ">") //.also { println("${facingMapR[facing]}") }
"L" -> return Pair(this, facingMapL[facing]?: "<") //.also { println("${facingMapL[facing]}") }
else -> return this.move(step, facing)
}
}
for (step in path){
// println("step $step, $facing")
var curPair = Pos.update(step, facing)
Pos = curPair.first
facing = curPair.second
// println("updated Pos $Pos, $facing")
}
println((Pos.first+1)*1000 + (Pos.second+1)*4)
}
val testInput = File("src","Day22.txt").readText()
// part1(testInput)
part2(testInput)
// for (line in testInput){
// println(line)
} | 0 | Kotlin | 0 | 0 | a0bc190b391585ce3bb6fe2ba092fa1f437491a6 | 10,356 | aoc22 | Apache License 2.0 |
src/array/LeetCode215.kt | Alex-Linrk | 180,918,573 | false | null | package array
/**
* 数组中的第K个最大元素
* 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
*
*示例 1:
*
*输入: [3,2,1,5,6,4] 和 k = 2
*输出: 5
*示例 2:
*
*输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
*输出: 4
*说明:
*
*你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
*
*来源:力扣(LeetCode)
*链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array
*著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class LeetCode215 {
fun findKthLargest(nums: IntArray, k: Int): Int {
var item = k
var x = nums.lastIndex
while (item > 0) {
var swip = false
for (y in 0 until x) {
if (nums[y] > nums[y + 1]) {
swip(nums, y, y + 1)
swip = true
}
}
if (swip.not()) {
break
}
item--
x--
}
println(nums.toList())
return nums[nums.size - k]
}
fun findKthLargestByHeap(nums: IntArray, k: Int): Int {
val begin = nums.lastIndex.shr(1)
for (start in begin downTo 0)
maxHeapify(nums, start, nums.lastIndex)
var index = 0
println(nums.toList())
while (index < k) {
swip(nums, 0, nums.lastIndex - index)
index++
maxHeapify(nums, 0, nums.lastIndex - index)
}
println(nums.toList())
return nums[nums.size - k]
}
fun maxHeapify(nums: IntArray, index: Int, len: Int) {
val left = index.shl(1) + 1
val right = left + 1
var max = left
if (left > len) return
if (right <= len && nums[right] > nums[left])
max = right
if (nums[max] > nums[index]) {
swip(nums, max, index)
maxHeapify(nums, max, len)
}
}
fun swip(nums: IntArray, x: Int, y: Int) {
val temp = nums[x]
nums[x] = nums[y]
nums[y] = temp
}
}
fun main() {
println(
LeetCode215().findKthLargestByHeap(
intArrayOf(3, 2, 1, 5, 6, 4),
2
)
)
println(
LeetCode215().findKthLargestByHeap(
intArrayOf(3, 2, 3, 1, 2, 4, 5, 5, 6),
4
)
)
} | 0 | Kotlin | 0 | 0 | 59f4ab02819b7782a6af19bc73307b93fdc5bf37 | 2,496 | LeetCode | Apache License 2.0 |
src/Day09.kt | MatthiasDruwe | 571,730,990 | false | {"Kotlin": 47864} | import java.lang.Error
import javax.swing.text.Position
import kotlin.math.abs
fun main() {
fun calcPositionT(positionH: Pair<Int,Int>, positionT: Pair<Int, Int>): Pair<Int,Int>{
if(abs(positionH.first - positionT.first) <= 1 && abs(positionT.second - positionH.second) <= 1){
return positionT
}
if(positionH.first-positionT.first == 0){
return Pair(positionT.first , positionT.second + (positionH.second-positionT.second)/abs(positionH.second-positionT.second))
} else if (positionH.second-positionT.second == 0){
return Pair(positionT.first + (positionH.first-positionT.first)/abs(positionH.first-positionT.first), positionT.second)
}
return Pair(positionT.first + (positionH.first-positionT.first)/abs(positionH.first-positionT.first), positionT.second + (positionH.second-positionT.second)/abs(positionH.second-positionT.second))
}
fun part1(input: List<String>): Int {
val output = input.map {
val split = it.split(" ")
Pair(split[0], split[1].toInt())
}
val positions = mutableSetOf<Pair<Int, Int>>()
var positionH = Pair(0,0)
var positionT = Pair(0,0)
positions.add(positionT)
output.forEach {(action, value)->
repeat(value){
positionH = when(action){
"R"-> Pair(positionH.first+1, positionH.second)
"L"-> Pair(positionH.first-1, positionH.second)
"U"-> Pair(positionH.first, positionH.second-1)
"D"-> Pair(positionH.first, positionH.second+1)
else -> positionH
}
positionT = calcPositionT(positionH, positionT)
positions.add(positionT)
}
}
return positions.size
}
fun part2(input: List<String>): Int {
val output = input.map {
val split = it.split(" ")
Pair(split[0], split[1].toInt())
}
val positions = mutableSetOf<Pair<Int, Int>>()
var positionH = Pair(0,0)
var positionT = Array(9){ Pair(0,0)}
positions.add(positionT.last())
output.forEach {(action, value)->
repeat(value){
positionH = when(action){
"R"-> Pair(positionH.first+1, positionH.second)
"L"-> Pair(positionH.first-1, positionH.second)
"U"-> Pair(positionH.first, positionH.second-1)
"D"-> Pair(positionH.first, positionH.second+1)
else -> positionH
}
repeat(positionT.size){
if(it==0){
positionT[it]=calcPositionT(positionH, positionT[it])
} else{
positionT[it]=calcPositionT(positionT[it-1], positionT[it])
}
}
positions.add(positionT.last())
}
}
return positions.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_example")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f35f01cea5075cfe7b4a1ead9b6480ffa57b4989 | 3,345 | Advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day-03.kt | warriorzz | 434,708,459 | true | {"Kotlin": 3651} | package com.github.warriorzz.aoc
import java.io.File
private fun main() {
println("Day 03:")
val lines = File("./input/day-03.txt").readLines()
val map = mutableMapOf<Int, Int>()
lines.map { it ->
it.toCharArray().map { it.digitToInt() }
}.forEach { ints ->
ints.forEachIndexed { index, i ->
map[index] = map[index]?.plus(i) ?: i
}
}
val gamma = map.map { if (it.value.div(1000.0) >= 0.5) "1" else "0" }.reduce { acc, s -> acc + s }.toInt(2)
val epsilon = map.map { if (it.value.div(1000.0) <= 0.5) "1" else "0" }.reduce { acc, s -> acc + s }.toInt(2)
println("Solution part 1: " + (gamma * epsilon))
val oxygen = lines.toMutableList().filterFromCommons()
val co2 = lines.toMutableList().filterFromCommons(least = true)
println("Solution part 2: " + oxygen.toInt(2) * co2.toInt(2))
}
fun MutableList<String>.filterFromCommons(index: Int = 0, least: Boolean = false) : String {
val map = mutableMapOf<Int, Int>()
map { it ->
it.toCharArray().map { it.digitToInt() }
}.forEach { ints ->
ints.forEachIndexed { index, i ->
map[index] = map[index]?.plus(i) ?: i
}
}
val commons = map.map { if (it.value / this@filterFromCommons.size.toDouble() >= 0.5) "1" else "0" }.reduce { acc, s -> acc + s }
val list = filter { if (!least) it[index] == commons[index] else it[index] != commons[index] }
return if (list.size == 1) list.first() else list.toMutableList().filterFromCommons(index + 1, least)
}
fun day03() = main()
| 0 | Kotlin | 1 | 0 | 3014509c222f5c8b41e6dcaea95f796bdfe82d61 | 1,607 | aoc-21 | MIT License |
src/twentythree/Day07.kt | mihainov | 573,105,304 | false | {"Kotlin": 42574} | package twentythree
import readInputTwentyThree
enum class Combination {
FIVE_OF_A_KIND,
FOUR_OF_A_KIND,
FULL_HOUSE,
THREE_OF_A_KIND,
TWO_PAIR,
PAIR,
HIGH;
}
// functionality is changed to solve p2
enum class PlayingCard(val code: String) {
ACE("A"),
KING("K"),
QUEEN("Q"),
TEN("T"),
NINE("9"),
EIGHT("8"),
SEVEN("7"),
SIX("6"),
FIVE("5"),
FOUR("4"),
THREE("3"),
TWO("2"),
JACK("J");
}
fun String.getCardByCode(): PlayingCard {
return PlayingCard.values().find { it.code == this }!!
}
data class Hand(val cards: List<PlayingCard>, val bet: Int) : Comparable<Hand> {
fun getStrength(): Combination {
val occurrences = PlayingCard.values().associateWith { 0 }.toMutableMap()
this.cards.forEach { occurrences[it] = occurrences[it]!!.inc() }
val jacks = occurrences[PlayingCard.JACK]
if (jacks == 5) {
return Combination.FIVE_OF_A_KIND
}
occurrences[PlayingCard.JACK] = 0
val sorted = occurrences.values.sortedDescending()
return when (sorted.first()) {
5 -> Combination.FIVE_OF_A_KIND
4 -> return if (jacks == 1) {
Combination.FIVE_OF_A_KIND
} else {
Combination.FOUR_OF_A_KIND
}
3 -> {
when (jacks) {
0 -> if (sorted[1] == 2) {
Combination.FULL_HOUSE
} else {
Combination.THREE_OF_A_KIND
}
1 -> Combination.FOUR_OF_A_KIND
2 -> Combination.FIVE_OF_A_KIND
else -> error("3 same cards and more than 2 jacks")
}
}
2 -> {
when (jacks) {
3 -> return Combination.FIVE_OF_A_KIND
2 -> return Combination.FOUR_OF_A_KIND
1 -> return if (sorted[1] == 2) {
Combination.FULL_HOUSE
} else {
Combination.THREE_OF_A_KIND
}
0 -> return if (sorted[1] == 2) {
Combination.TWO_PAIR
} else {
Combination.PAIR
}
else -> error("2 same cards and more than 3 jacks")
}
}
1 -> {
when (jacks) {
4 -> return Combination.FIVE_OF_A_KIND
3 -> return Combination.FOUR_OF_A_KIND
2 -> return Combination.THREE_OF_A_KIND
1 -> return Combination.PAIR
0 -> return Combination.HIGH
else -> error("no duplicates and more than 4 jacks")
}
}
else -> error("No occurrences")
}
}
override fun compareTo(other: Hand): Int {
this.getStrength().compareTo(other.getStrength()).let {
if (it != 0) {
return it
}
}
this.cards.indices.forEach { idx ->
this.cards[idx].compareTo(other.cards[idx]).let {
if (it != 0) {
return it
}
}
}
println(0)
return 0
}
}
fun String.parseHand(): Hand {
val cards = mutableListOf<PlayingCard>()
for (i in 0..4) {
cards.add(this[i].toString().getCardByCode())
}
val bet = this.substringAfter(' ').toInt()
return Hand(cards, bet)
}
fun main() {
fun part1(input: List<String>): Int {
val hands = input.map { it.parseHand().also { println("Parsed hand $it with strength ${it.getStrength()}") } }
.sortedDescending()
return hands.mapIndexed { index, hand ->
((index + 1) * hand.bet).also { println("${index + 1} $hand ${hand.getStrength()} has a total value of $it") }
}.sum()
}
fun part2(input: List<String>): Int {
val hands = input.map { it.parseHand().also { println("Parsed hand $it with strength ${it.getStrength()}") } }
.sortedDescending()
return hands.mapIndexed { index, hand ->
((index + 1) * hand.bet).also { println("${index + 1} $hand ${hand.getStrength()} has a total value of $it") }
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputTwentyThree("Day07_test")
// using test input of
//2345A 1
//Q2KJJ 13
//Q2Q2Q 19
//T3T3J 17
//T3Q33 11
//2345J 3
//J345A 2
//32T3K 5
//T55J5 29
//KK677 7
//KTJJT 34
//QQQJA 31
//JJJJJ 37
//JAAAA 43
//AAAAJ 59
//AAAAA 61
//2AAAA 23
//2JJJJ 53
//JJJJ2 41
// check(part1(testInput).also(::println) == 6592)
check(part2(testInput).also(::println) == 6839)
val input = readInputTwentyThree("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a9aae753cf97a8909656b6137918ed176a84765e | 5,059 | kotlin-aoc-1 | Apache License 2.0 |
src/main/Day02.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day02
import utils.readInput
enum class Shape(val score: Int) {
Rock(1),
Paper(2),
Scissors(3);
val defeats: Shape
get() =
when (this) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
val defeated: Shape
get() =
when (this) {
Rock -> Paper
Paper -> Scissors
Scissors -> Rock
}
fun defeats(other: Shape) = other == defeats
}
enum class Outcome(val score: Int) {
Lost(0),
Draw(3),
Won(6)
}
data class Round(val opponent: Shape, val selected: Shape) {
private val outcome =
when {
selected == opponent -> Outcome.Draw
selected.defeats(opponent) -> Outcome.Won
else -> Outcome.Lost
}
val score = selected.score + outcome.score
}
fun Char.decodeOpponent(): Shape =
when (this) {
'A' -> Shape.Rock
'B' -> Shape.Paper
'C' -> Shape.Scissors
else -> error("Cannot decode opponent move: $this")
}
fun Char.decodeSuggestedMove(): Shape =
when (this) {
'X' -> Shape.Rock
'Y' -> Shape.Paper
'Z' -> Shape.Scissors
else -> error("Cannot decode suggested move: $this")
}
fun Char.decodeSuggestedOutcome(): Outcome =
when (this) {
'X' -> Outcome.Lost
'Y' -> Outcome.Draw
'Z' -> Outcome.Won
else -> error("Cannot decode suggested outcome: $this")
}
fun findShapeForOutcome(opponent: Shape, outcome: Outcome): Shape =
when (outcome) {
Outcome.Lost -> opponent.defeats
Outcome.Draw -> opponent
Outcome.Won -> opponent.defeated
}
fun part1(filename: String): Int =
readInput(filename)
.map { Round(it.first().decodeOpponent(), it.last().decodeSuggestedMove()) }
.sumOf(Round::score)
fun part2(filename: String) =
readInput(filename)
.map { it.first().decodeOpponent() to it.last().decodeSuggestedOutcome() }
.map { (opponent, outcome) -> Round(opponent, findShapeForOutcome(opponent, outcome)) }
.sumOf(Round::score)
fun main() {
val filename = "Day02"
println(part1(filename))
println(part2(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 2,279 | aoc-2022 | Apache License 2.0 |
src/Day11.kt | eo | 574,058,285 | false | {"Kotlin": 45178} | // https://adventofcode.com/2022/day/11
fun main() {
fun parseInput(input: String): List<Monkey> =
input
.split("\n\n")
.map(Monkey::fromString)
fun solve(monkeys: List<Monkey>, rounds: Int, reliefFunction: (Long) -> Long): Long {
val monkeysMap = monkeys.associateBy(Monkey::id)
repeat(rounds) {
monkeys.forEach { monkey ->
monkey.inspect(reliefFunction) { item, monkeyId ->
monkeysMap[monkeyId]?.addItem(item)
}
}
}
return monkeys
.map(Monkey::totalInspections)
.sorted()
.takeLast(2)
.reduce { acc, value -> acc * value }
}
fun part1(input: String): Long {
val monkeys = parseInput(input)
return solve(monkeys, 20) { it / 3 }
}
fun part2(input: String): Long {
val monkeys = parseInput(input)
val reliefFactor = monkeys.map { it.test.value }.reduce { acc, value -> acc * value }
return solve(monkeys, 10000) { it % reliefFactor }
}
val input = readText("Input11")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
private class Monkey(val id: Int, items: List<Long>, val operation: Operation, val test: Test) {
private val items = items.toMutableList()
var totalInspections = 0L
private set
fun addItem(item: Long) = items.add(item)
fun inspect(reliefFunction: (Long) -> Long, transferAction: (Long, Int) -> Unit) {
totalInspections += items.size
items.forEach { item ->
val newItem = reliefFunction(operation.perform(item))
transferAction(newItem, test.monkeyIdToThrow(newItem))
}
items.clear()
}
sealed class Operation {
abstract fun perform(oldValue: Long): Long
}
object SquareOperation : Operation() {
override fun perform(oldValue: Long) = oldValue * oldValue
}
class AdditionOperation(val addition: Long): Operation() {
override fun perform(oldValue: Long) = oldValue + addition
}
class MultiplicationOperation(val times: Long): Operation() {
override fun perform(oldValue: Long) = oldValue * times
}
class Test(
val value: Long,
val monkeyIdToThrowIfTrue: Int,
val monkeyIdToThrowIfFalse: Int
) {
fun monkeyIdToThrow(number: Long) = if (number % value == 0L) {
monkeyIdToThrowIfTrue
} else {
monkeyIdToThrowIfFalse
}
}
companion object {
fun fromString(str: String): Monkey {
val lines = str.lines()
return Monkey(
parseMonkeyId(lines[0]),
parseStartingItems(lines[1]),
parseOperation(lines[2]),
parseTest(lines[3], lines[4], lines[5])
)
}
private fun parseMonkeyId(monkeyIdLine: String): Int =
monkeyIdLine.substringAfter("Monkey ").trimEnd(':').toInt()
private fun parseStartingItems(startingItemsLine: String): List<Long> =
startingItemsLine.substringAfter("Starting items: ").split(", ").map(String::toLong)
private fun parseOperation(operationLine: String): Operation {
val restOfOperation = operationLine.substringAfter("Operation: new = old ")
val (symbol, value) = restOfOperation.split(" ")
return when (symbol) {
"*" -> if (value == "old") SquareOperation else MultiplicationOperation(value.toLong())
"+" -> AdditionOperation(value.toLong())
else -> error("Invalid operation! $symbol")
}
}
private fun parseTest(
testLine: String,
trueActionLine: String,
falseActionLine: String
) = Test(
testLine.substringAfter("Test: divisible by ").toLong(),
trueActionLine.substringAfter("If true: throw to monkey ").toInt(),
falseActionLine.substringAfter("If false: throw to monkey ").toInt()
)
}
} | 0 | Kotlin | 0 | 0 | 8661e4c380b45c19e6ecd590d657c9c396f72a05 | 4,124 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day11.kt | thiyagu06 | 572,818,472 | false | {"Kotlin": 17748} | import aoc22.printIt
import java.io.File
fun main() {
fun parseInput() = File("input/day11.txt").readLines()
val input = parseInput().chunkedBy { it.isBlank() }.map { from(it) }
fun star1(): Long {
val monkeys = input.map { it.copy() }
return calculateMonkeyBusiness(monkeys, rounds = 20) { it / 3 }
}
fun star2(): Long {
val monkeys = input.map { it.copy() }
val mod = monkeys.map { it.divisibleBy }.reduce { a, b -> a * b }
return calculateMonkeyBusiness(monkeys, rounds = 10000) { it % mod }
}
// test if implementation meets criteria from the description, like:
check(star1().printIt() == 120756L)
check(star2().printIt() == 39109444654L)
}
data class Monkey(
private val startingItems: List<Long>,
private val operation: (old: Long) -> Long,
val divisibleBy: Long,
private val ifTrueMonkey: Int,
private val ifFalseMonkey: Int
) {
var itemInspectionCount = 0L
private val items = ArrayDeque(startingItems)
private fun receiveItem(value: Long) {
items.add(value)
}
fun inspectItems(monkeys: List<Monkey>, calmDown: (Long) -> Long) {
while (items.isNotEmpty()) {
val inspect = items.removeFirst()
itemInspectionCount++
val afterInspection = operation(inspect)
val afterCalmDown = calmDown(afterInspection)
val giveToMonkey =
if (afterCalmDown % divisibleBy == 0L) ifTrueMonkey
else ifFalseMonkey
monkeys[giveToMonkey].receiveItem(afterCalmDown)
}
}
}
private fun calculateMonkeyBusiness(monkeys: List<Monkey>, rounds: Int, calmDown: (Long) -> Long): Long {
repeat(rounds) {
monkeys.forEach { it.inspectItems(monkeys, calmDown) }
}
return monkeys
.map { it.itemInspectionCount }
.sortedDescending()
.take(2)
.fold(1) { acc, i -> acc * i }
}
fun from(lines: List<String>): Monkey {
val startingItems = lines[1]
.removePrefix(" Starting items: ")
.split(", ")
.map { it.toLong() }
val operation = lines[2]
.removePrefix(" Operation: new = old ")
.split(' ')
.let { (operator, n) ->
when (operator) {
"+" -> { old: Long -> old + n.toLong() }
"*" -> {
if (n == "old") { old: Long -> old * old }
else { old: Long -> old * n.toLong() }
}
else -> error("Unknown operator $operator")
}
}
val divisibleBy = lines[3].substringAfterLast(' ').toLong()
val ifTrue = lines[4].substringAfterLast(' ').toInt()
val ifFalse = lines[5].substringAfterLast(' ').toInt()
return Monkey(startingItems, operation, divisibleBy, ifTrue, ifFalse)
}
fun <T> List<T>.chunkedBy(selector: (T) -> Boolean): List<List<T>> =
fold(mutableListOf(mutableListOf<T>())) { acc, item ->
if (selector(item)) acc.add(mutableListOf())
else acc.last().add(item)
acc
} | 0 | Kotlin | 0 | 0 | 55a7acdd25f1a101be5547e15e6c1512481c4e21 | 3,082 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | askeron | 572,955,924 | false | {"Kotlin": 24616} | class Day07 : Day<Long>(95437L, 24933642L, 1543140L, 1117448L) {
data class File(val dirPath: String, val filename: String, val size: Long) {
val path = "$dirPath$filename"
}
private fun parseInput(input: List<String>): List<File> {
val files = mutableListOf<File>()
var currentPath = "/"
input.forEach { line ->
if (line == "$ cd /") {
currentPath = "/"
} else if (line == "$ cd ..") {
currentPath = getParentDirPath(currentPath)
} else if (line.startsWith("$ cd ")) {
currentPath += "${line.removePrefix("$ cd ")}/"
} else if (line.first().isDigit()) {
files += line.split(" ").toPair().let { File(currentPath, it.second, it.first.toLong()) }
}
}
return files.distinctBy { it.path }
}
override fun part1(input: List<String>): Long {
val files = parseInput(input)
return files.getDirectorySizes()
.filter { it <= 100_000 }
.sumOf { it }
}
override fun part2(input: List<String>): Long {
val files = parseInput(input)
val totalSpace = 70_000_000
val freeSpaceNeeded = 30_000_000
val spaceToFreeUp = freeSpaceNeeded - (totalSpace - files.sumOf { it.size })
return files.getDirectorySizes()
.sorted()
.first { it >= spaceToFreeUp }
}
private fun List<File>.getDirectorySizes() = map { it.dirPath }
.distinct()
.flatMap { getDirPathIncludingAllParentPaths(it) }
.distinct()
.map { dirPath -> this.filter { it.dirPath.startsWith(dirPath) }.sumOf { it.size } }
private fun getParentDirPath(dirPath: String) = dirPath.removeSuffix("/").replaceAfterLast('/',"")
private fun getDirPathIncludingAllParentPaths(dirPath: String): List<String> {
val result = mutableListOf(dirPath)
var path = dirPath
repeat(dirPath.count { it == '/' } - 1) {
path = getParentDirPath(path)
result += path
}
return result.toList()
}
}
| 0 | Kotlin | 0 | 1 | 6c7cf9cf12404b8451745c1e5b2f1827264dc3b8 | 2,132 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day07.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Long {
val commands = parseCommands(input.drop(1))
val root = Directory("/")
Terminal(root).execute(commands)
return root.getAllDirectories().filter { it.size() < 100_000 }.sumOf { it.size() }
}
fun part2(input: List<String>): Long {
val totalAvailableDiskSpace = 70_000_000
val totalRequiredForUpdate = 30_000_000
val commands = parseCommands(input.drop(1))
val root = Directory("/")
Terminal(root).execute(commands)
val usedSpace = root.size()
val availableForUpdate = totalAvailableDiskSpace - usedSpace
val requiredForUpdate = totalRequiredForUpdate - availableForUpdate
val eligibleDirectorySizes =
root.getAllDirectories().map { it.size() }.filter { it >= requiredForUpdate }
return eligibleDirectorySizes.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
assertEquals(95437, part1(testInput))
assertEquals(24933642, part2(testInput))
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private fun parseCommands(input: List<String>): List<Command> {
val commands = mutableListOf<Command>()
var i = 0
while (i < input.size) {
val currentLine = input[i]
val words = currentLine.split(" ")
val command: Command =
when (words[1]) {
"ls" -> {
val files = mutableListOf<AbstractFile>()
while ((i + 1) < input.size && !input[i + 1].startsWith("$")) {
i++
val (size, filename) = input[i].split(" ")
files.add(if (size == "dir") Directory(filename) else File(filename, size.toLong()))
}
LsCommand(files)
}
"cd" -> CdCommand(words[2])
else -> error("unknown command, should not happen")
}
commands.add(command)
i++
}
return commands
}
private class Terminal(var pwd: Directory) {
fun execute(command: Command) {
when (command) {
is CdCommand -> pwd = pwd.get(command.targetPath)
is LsCommand -> pwd.create(command.output)
}
}
fun execute(commands: List<Command>) {
commands.forEach { execute(it) }
}
}
private sealed interface Command
private class CdCommand(val targetPath: String) : Command
private class LsCommand(val output: List<AbstractFile>) : Command
private sealed interface AbstractFile {
val name: String
fun size(): Long
}
private class Directory(
override val name: String,
var childs: MutableList<AbstractFile> = mutableListOf(),
var parent: Directory? = null
) : AbstractFile {
override fun size(): Long = childs.sumOf { it.size() }
fun get(filepath: String): Directory {
return if (filepath == "..") {
parent!!
} else {
childs.first { it.name == filepath } as Directory
}
}
fun getAllDirectories(): List<Directory> {
val directories = childs.filterIsInstance<Directory>()
return directories + directories.flatMap { it.getAllDirectories() }
}
fun create(files: List<AbstractFile>) {
for (file in files) {
if (!childs.map { it.name }.contains(file.name)) {
if (file is Directory) {
file.parent = this
}
childs.add(file)
}
}
}
}
private class File(override val name: String, val size: Long) : AbstractFile {
override fun size(): Long = size
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 3,454 | aoc2022 | Apache License 2.0 |
src/Day04.kt | TheGreatJakester | 573,222,328 | false | {"Kotlin": 47612} | import utils.readInputAsLines
fun main() {
fun part1(input: List<String>): Int {
return input.map {
it.split(",")
}.filter { (elf1, elf2) ->
val (a, b) = elf1.split("-")
val (c, d) = elf2.split("-")
if (a.toInt() <= c.toInt() && b.toInt() >= d.toInt()) {
return@filter true
}
if (c.toInt() <= a.toInt() && d.toInt() >= b.toInt()) {
return@filter true
}
false
}.count()
}
fun part2(input: List<String>): Int {
return input.map {
it.split(",")
}.filter { (elf1, elf2) ->
val (elf1min, elf1max) = elf1.split("-").map { it.toInt() }
val (elf2min, elf2max) = elf2.split("-").map { it.toInt() }
val elf1Range = elf1min..elf1max
val elf2Range = elf2min..elf2max
return@filter elf1min in elf2Range ||
elf1max in elf2Range ||
elf2min in elf1Range ||
elf2max in elf1Range
}.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsLines("Day04_test")
check(part1(testInput) == 2)
val pt2 = part2(testInput)
println(pt2)
check(pt2 == 4)
val input = readInputAsLines("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c76c213006eb8dfb44b26822a44324b66600f933 | 1,431 | 2022-AOC-Kotlin | Apache License 2.0 |
app/src/main/kotlin/codes/jakob/aoc/solution/Day01.kt | loehnertz | 725,944,961 | false | {"Kotlin": 59236} | package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.splitByCharacter
import codes.jakob.aoc.shared.splitByLines
object Day01 : Solution() {
private val digitsPattern = Regex("(?=(zero|one|two|three|four|five|six|seven|eight|nine|\\d))")
override fun solvePart1(input: String): Any {
return input
// Split the input into a list of lines
.splitByLines()
.asSequence()
// Split each line into a list of words
.map { line -> line.splitByCharacter() }
// Filter out all words that do not contain a digit
.map { chars -> chars.first { it.isDigit() } to chars.last { it.isDigit() } }
// Join the first and last digit of each line to a string
.map { (first, last) -> "$first$last" }
// Convert the string to an integer
.map { it.toInt() }
// Sum up all integers
.sum()
}
override fun solvePart2(input: String): Any {
return input
// Split the input into a list of lines
.splitByLines()
.asSequence()
// Detect the digits in each line
.map { line -> detectDigitsFromSentence(line) }
// Join the first and last digit of each line to a string
.map { digits -> digits.first() to digits.last() }
// Join the first and last digit of each line to a string
.map { (first, last) -> "$first$last" }
// Convert the string to an integer
.map { it.toInt() }
// Sum up all integers
.sum()
}
private fun detectDigitsFromSentence(sentence: String): List<Char> {
return digitsPattern
.findAll(sentence)
.mapNotNull { it.groups[1]?.value }
.map { detectDigitFromWord(it) }
.toList()
}
private fun detectDigitFromWord(word: String): Char {
if (word.length == 1 && word.first().isDigit()) return word.first()
return when (word) {
"zero" -> '0'
"one" -> '1'
"two" -> '2'
"three" -> '3'
"four" -> '4'
"five" -> '5'
"six" -> '6'
"seven" -> '7'
"eight" -> '8'
"nine" -> '9'
else -> throw IllegalArgumentException("The given word does not represent a digit")
}
}
}
fun main() {
Day01.solve()
}
| 0 | Kotlin | 0 | 0 | 6f2bd7bdfc9719fda6432dd172bc53dce049730a | 2,459 | advent-of-code-2023 | MIT License |
kotlin/src/2023/Day02_2023.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} | import kotlin.math.max
private fun parseItem(s: String): Pair<String, Int> {
val (cnt, typ) = s.trim().split(" ")
return typ to cnt.toInt()
}
private fun parseGame(s: String): List<Map<String, Int>> {
return s.split(";")
.map {
its -> its.split(",")
.associate {parseItem(it)}
}
}
fun main() {
val input = readInput(2, 2023)
val game_pat = Regex("Game ([0-9]+): (.*)")
val games = input.trim().split("\n")
.map {game_pat.matchEntire(it)!!.groups.toList()}
.map {it[1]!!.value.toInt() to parseGame(it[2]!!.value)}
val items_have = mapOf(
"red" to 12,
"green" to 13,
"blue" to 14,
)
games
.filter {
game -> game.second.all {
it.entries.all {(k, v) -> v <= items_have[k]!!}
}
}
.sumOf {it.first }
.also {println("Part 1: $it")}
fun updateBagReq(d: Map<String, Int>, hand: Map<String, Int>): Map<String, Int> {
val newd = d.toMutableMap()
for ((k, v) in hand.entries) newd[k] = max(newd.getOrDefault(k, 0), v)
return newd
}
games.map { (idx, bags) ->
bags.fold(mapOf(), ::updateBagReq)
}
.map {
it.values.reduce {x, y -> x * y}
}
.sum()
.also {println("Part 2: $it")}
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 1,352 | adventofcode | Apache License 2.0 |
src/main/kotlin/year2022/Day16.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2022
import utils.powerSetSequence
class Day16(input: String) {
data class ValveNode(val name: String) {
var flowRate = 0
var neighbors = mutableListOf<ValveNode>()
val distanceMap: MutableMap<ValveNode, Int> = mutableMapOf()
}
private val regex = """Valve (..) has flow rate=(\d*); tunnels? leads? to valves? (.*)""".toRegex()
private val nodes = buildMap<String, ValveNode> {
regex.findAll(input).toList().forEach { match ->
val valveId = match.groupValues[1]
getOrPut(valveId) { ValveNode(valveId) }.apply {
this.flowRate = match.groupValues[2].toInt()
match.groupValues[3].split(", ").forEach { neighborId ->
this.neighbors.add(getOrPut(neighborId) { ValveNode(neighborId) })
}
}
}
}.values
private val valves = nodes.filter { it.flowRate > 0 }.toSet()
init {
// calculating distances between non-zero flow valves
valves.forEach { root ->
root.distanceMap[root] = 0
with(ArrayDeque<ValveNode>()) {
add(root)
val visited = mutableSetOf<ValveNode>()
while (isNotEmpty()) {
val current = removeFirst()
val distance = current.distanceMap[root]!!
visited.add(current)
current.neighbors.filter { it !in visited }.forEach { neighbor ->
neighbor.distanceMap[root] = distance + 1
addLast(neighbor)
}
}
}
root.distanceMap.remove(root)
}
}
private val startNode = nodes.find { it.name == "AA" }!!
private fun maxPath(opened: Set<ValveNode>, node: ValveNode, steps: Int, sum: Int, open: Int): Int {
val nextOpened = opened.plus(node)
return node.distanceMap.filter { (key, distance) -> !opened.contains(key) && distance <= steps - 1 }
.map { (nextNode, distance) ->
maxPath(
nextOpened,
nextNode,
steps - (distance + 1),
sum + (distance + 1) * open,
open + nextNode.flowRate
)
}.plus(sum + steps * open)
.max()
}
fun part1() = maxPath(emptySet(), startNode, 30, 0, 0)
fun part2() = valves.powerSetSequence()
.maxOf { me ->
val elephant = valves.subtract(me)
maxPath(elephant, startNode, 26, 0, 0) + maxPath(me, startNode, 26, 0, 0)
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 2,656 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | PauliusRap | 573,434,850 | false | {"Kotlin": 20299} | private const val FIRST_CHAR_INDEX = 0
private const val SECOND_CHAR_INDEX = 2
private const val ERROR_MESSAGE = "Unknown character!"
fun main() {
fun getPoints(input: String): Int {
val opponentsSign = input.toCharArray()[FIRST_CHAR_INDEX].getSign()
val yourSign = input.toCharArray()[SECOND_CHAR_INDEX].getSign()
return when (yourSign) {
Sign.Rock -> 1
Sign.Paper -> 2
Sign.Scissors -> 3
} + when {
yourSign == Sign.Rock && opponentsSign == Sign.Scissors ||
yourSign == Sign.Scissors && opponentsSign == Sign.Paper ||
yourSign == Sign.Paper && opponentsSign == Sign.Rock -> 6
yourSign == opponentsSign -> 3
else -> 0
}
}
fun transformToCorrectFormat(input: List<String>): List<String> {
return input.map {
val opponentsSign = it.toCharArray()[FIRST_CHAR_INDEX].getSign()
val outcome = it.toCharArray()[SECOND_CHAR_INDEX]
val char = when (outcome) {
'X' -> when (opponentsSign) {
Sign.Rock -> 'C'
Sign.Paper -> 'A'
Sign.Scissors -> 'B'
}
'Y' -> when (opponentsSign) {
Sign.Rock -> 'A'
Sign.Paper -> 'B'
Sign.Scissors -> 'C'
}
'Z' -> when (opponentsSign) {
Sign.Rock -> 'B'
Sign.Paper -> 'C'
Sign.Scissors -> 'A'
}
else -> throw IllegalArgumentException(ERROR_MESSAGE)
}
it.replace(outcome, char)
}
}
fun part1(input: List<String>) = input.sumOf { getPoints(it) }
fun part2(input: List<String>) = transformToCorrectFormat(input).sumOf { getPoints(it) }
// test if implementation meets criteria from the description:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class Sign {
Rock, Paper, Scissors;
}
fun Char.getSign() =
when (this) {
'X', 'A' -> Sign.Rock
'Y', 'B' -> Sign.Paper
'Z', 'C' -> Sign.Scissors
else -> throw IllegalArgumentException(ERROR_MESSAGE)
}
| 0 | Kotlin | 0 | 0 | df510c3afb104c03add6cf2597c433b34b3f7dc7 | 2,425 | advent-of-coding-2022 | Apache License 2.0 |
src/Day15.kt | pavlo-dh | 572,882,309 | false | {"Kotlin": 39999} | import kotlin.math.abs
fun main() {
data class Point(val x: Int, val y: Int) {
fun manhattanDistance(other: Point) = abs(x - other.x) + abs(y - other.y)
}
fun parsePoint(s: String): Point {
val x = s.substring(s.indexOf('=') + 1, s.indexOf(',')).toInt()
val y = s.substring(s.lastIndexOf('=') + 1).toInt()
return Point(x, y)
}
fun parseInput(input: List<String>) = input.map { line ->
val (sensor, beacon) = line.split(": ").map(::parsePoint)
sensor to beacon
}
fun part1(input: List<String>, y: Int): Int {
val sensors = mutableSetOf<Point>()
val beacons = mutableSetOf<Point>()
val reachedPositions = mutableSetOf<Point>()
parseInput(input).forEach { (sensor, beacon) ->
sensors.add(sensor)
beacons.add(beacon)
val distance = sensor.manhattanDistance(beacon)
val minY = sensor.y - distance
val maxY = sensor.y + distance
if (y in minY..maxY) {
for (x in sensor.x - distance..sensor.x + distance) {
val position = Point(x, y)
if (sensor.manhattanDistance(position) <= distance) {
reachedPositions.add(position)
}
}
}
}
reachedPositions.removeAll(sensors + beacons)
return reachedPositions.size
}
fun part2(input: List<String>, maxCoordinate: Int): Long {
val sensorDistancePairs = parseInput(input).map { (sensor, beacon) ->
val distance = sensor.manhattanDistance(beacon)
sensor to distance
}
fun findDistressBeacon(sensor: Point, distance: Int): Point? {
val increasedDistance = distance + 1
val startX = sensor.x
val startY = sensor.y + increasedDistance
var x = startX
var y = startY
var xIncrement = 1
var yIncrement = -1
do {
if (x in 0..maxCoordinate && y in 0..maxCoordinate) {
val position = Point(x, y)
var otherSensorReaches = false
for ((otherSensor, otherDistance) in sensorDistancePairs) {
if (otherSensor.manhattanDistance(position) <= otherDistance) {
otherSensorReaches = true
break
}
}
if (!otherSensorReaches) {
return position
}
}
x += xIncrement
y += yIncrement
if (abs(x - sensor.x) == increasedDistance) {
xIncrement *= -1
}
if (abs(y - sensor.y) == increasedDistance) {
yIncrement *= -1
}
} while (x != startX && y != startY)
return null
}
for ((sensor, distance) in sensorDistancePairs) {
findDistressBeacon(sensor, distance)?.let { distressBeacon ->
return distressBeacon.x * 4000000L + distressBeacon.y
}
}
error("Distress beacon not found!")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 4000000))
}
| 0 | Kotlin | 0 | 2 | c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992 | 3,589 | aoc-2022-in-kotlin | Apache License 2.0 |
src/heap/LeetCode239.kt | Alex-Linrk | 180,918,573 | false | null | package heap
/**
* 滑动窗口最大值
* 给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口 k 内的数字。滑动窗口每次只向右移动一位。
*
*返回滑动窗口最大值。
*
*示例:
*
*输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
*输出: [3,3,5,5,6,7]
*解释:
*
*滑动窗口的位置 最大值
*--------------- -----
*[1 3 -1] -3 5 3 6 7 3
*1 [3 -1 -3] 5 3 6 7 3
*1 3 [-1 -3 5] 3 6 7 5
*1 3 -1 [-3 5 3] 6 7 5
*1 3 -1 -3 [5 3 6] 7 6
*1 3 -1 -3 5 [3 6 7] 7
*注意:
*
*你可以假设 k 总是有效的,1 ≤ k ≤ 输入数组的大小,且输入数组不为空。
*
*进阶:
*
*你能在线性时间复杂度内解决此题吗?
*
*来源:力扣(LeetCode)
*链接:https://leetcode-cn.com/problems/sliding-window-maximum
*著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class LeetCode239 {
fun maxSlidingWindow(nums: IntArray, k: Int): IntArray {
if (nums.isEmpty()) return intArrayOf()
var left: Int
val result = mutableListOf<Int>()
left = getMaxIndex(nums, 0, k)
result.add(nums[left])
for (i in k until nums.size) {
if (nums[i] >= nums[left]) {
left = i
} else if (left + k - 1 < i) {
left = getMaxIndex(nums, left+1, k)
}
result.add(nums[left])
}
return result.toIntArray()
}
private fun getMaxIndex(nums: IntArray, left: Int, k: Int): Int {
var position = left
var max = nums[position]
var right = if(left+k>nums.size) nums.size else left+k
for (x in left until right) {
if (nums[x] >= max) {
position = x
max = nums[position]
}
}
return position
}
}
/**
* [9,10,9,-7,-4,-8,2,-6]
* 5
*/
fun main() {
println(
LeetCode239().maxSlidingWindow(
intArrayOf(9,10,9,-7,-4,-8,2,-6), 5
).toList()
)
println(
LeetCode239().maxSlidingWindow(
intArrayOf(1,2,3,4,5,6,7,8), 3
).toList()
)
}
| 0 | Kotlin | 0 | 0 | 59f4ab02819b7782a6af19bc73307b93fdc5bf37 | 2,346 | LeetCode | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch9/Problem95.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch9
import dev.bogwalk.util.maths.sumProperDivisors
/**
* Problem 95: Amicable Chains
*
* https://projecteuler.net/problem=95
*
* Goal: Find the smallest member of the longest amicable chain possible without any member
* exceeding N.
*
* Constraints: 6 <= N <= 1e6
*
* Perfect Number: A chain of only 1 member denotes a perfect number; i.e. the sum of this
* number's proper divisors is the number itself. e.g. [6], [28], [496].
* Amicable Pair: A chain of only 2 members. e.g. [220, 284], [1184, 1210], [2620, 2924].
* Amicable Chain: A chain of numbers generated by calculating the sum of each number's proper
* divisors. e.g. 12496 → 14288 → 15472 → 14536 → 14264 (→ 12496 → ...).
*
* e.g.: N = 10
* 6 -> {1, 2, 3} = [6]
* output = 6
*/
class AmicableChains {
/**
* Solution optimised by storing the results of previous chain members in a cache to avoid
* redundant invocation of the helper function.
*
* Potential chains are also terminated early if any member is smaller than the starter
* number (as the former would have already been assessed and deemed valid, invalid, or a
* prime). This is supported by the observation that the few chains (with >2 members) follow a
* normal distribution curve, with the smallest element being the first starter.
*
* Iteration through starters is also reduced by only considering even numbers, based on the
* observation that amicable chains only consist of even numbers.
*/
fun longestAmicableChain(limit: Int): List<Int> {
// null signifies that the starter has yet to be assessed
// emptyList() means no valid chain from starter at that index (most likely ends in a prime)
// list() means a valid chain was found by a smaller starter
val cache = MutableList(limit + 1) {
if (it == 6) listOf(6)
else if (it < 10) emptyList()
else null
}
var longest = listOf(6)
for (n in 10..limit step 2) {
if (cache[n] == null) {
val chain = mutableListOf(n)
var prev = n
while (true) {
prev = sumProperDivisors(prev)
// either a perfect number or a closed chain
if (prev == n) {
for (num in chain) {
cache[num] = chain
}
if (chain.size > longest.size) longest = chain
break
}
// either determined invalid by a smaller starter, is amicable pair/perfect,
// or is already part of an amicable chain
// e.g. 25 -> {1, 5} -> [6]
// e.g. 1692 leads to pair [2924, 2620] that first appears in 1188 chain
if (prev !in (n + 1)..limit || cache[prev] != null) {
for (num in chain) {
cache[num] = emptyList()
}
break
}
// found smaller sub-chain (could be longer than a pair)
if (prev in chain) {
val index = chain.indexOf(prev)
val subChain = chain.slice(index..chain.lastIndex)
if (subChain.size > longest.size) longest = subChain
for ((i, num) in chain.withIndex()) {
cache[num] = if (i < index) emptyList() else subChain
}
break
}
chain.add(prev)
}
}
}
return longest
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,802 | project-euler-kotlin | MIT License |
src/main/kotlin/aoc/Day09.kt | fluxxion82 | 573,716,300 | false | {"Kotlin": 39632} | package aoc
import aoc.model.Coordinate
import aoc.model.moveDown
import aoc.model.moveLeft
import aoc.model.moveRight
import aoc.model.moveUp
import aoc.utils.readInput
fun getDirectionFromValue(directionValue: String): Direction? {
return when (directionValue) {
"R" -> Direction.RIGHT
"L" -> Direction.LEFT
"U" -> Direction.UP
"D" -> Direction.DOWN
else -> null
}
}
fun main() {
val testInput = readInput("Day09_test.txt")
val testTwoInput = readInput("Day09_test_two.txt")
val input = readInput("Day09.txt")
fun part1(input: List<String>): Int {
val directions = input.map {
it.split(" ")
}
var head = Coordinate(0, 0)
var tail = Coordinate(0, 0)
val visited = mutableListOf(tail)
directions.forEach { instruction ->
val (direct, steps) = instruction
for (step in 1 .. steps.toInt()) {
head = when (getDirectionFromValue(direct)) {
Direction.UP -> head.moveUp()
Direction.RIGHT -> head.moveRight()
Direction.LEFT -> head.moveLeft()
Direction.DOWN -> head.moveDown()
null -> head
}
if (!head.isAdjacent(tail)) {
val foo = Coordinate(head.xCoord - tail.xCoord, head.yCoord - tail.yCoord)
tail += Coordinate(foo.xCoord.coerceIn(-1, 1), foo.yCoord.coerceIn(-1, 1))
}
visited.add(tail)
}
}
return visited.toSet().size
}
fun part2(input: List<String>): Int {
val directions = input.map {
it.split(" ")
}
var tail = Coordinate(0, 0)
val visited = mutableListOf(tail)
val rope = (1..10).map { Coordinate(0, 0) }.toTypedArray()
directions.forEach { instruction ->
val (direct, steps) = instruction
for (step in 1 .. steps.toInt()) {
rope[0] = when (getDirectionFromValue(direct)) {
Direction.UP -> rope[0].moveUp()
Direction.RIGHT -> rope[0].moveRight()
Direction.LEFT -> rope[0].moveLeft()
Direction.DOWN -> rope[0].moveDown()
null -> rope[0]
}
for (knot in 1 until 10) {
val head = rope[knot - 1]
tail = rope[knot]
if (!head.isAdjacent(tail)) {
val foo = Coordinate(head.xCoord - tail.xCoord, head.yCoord - tail.yCoord)
rope[knot] += Coordinate(foo.xCoord.coerceIn(-1, 1), foo.yCoord.coerceIn(-1, 1))
}
}
visited.add(rope.last())
}
}
return visited.toSet().size
}
println("part one test: ${part1(testInput)}") // 13
println("part one: ${part1(input)}") // 6175
println("part two test: ${part2(testInput)}") // 1
println("part two test: ${part2(testTwoInput)}") // 36
println("part two: ${part2(input)}") // 2578
}
| 0 | Kotlin | 0 | 0 | 3920d2c3adfa83c1549a9137ffea477a9734a467 | 3,177 | advent-of-code-kotlin-22 | Apache License 2.0 |
src/main/kotlin/day05/Day05.kt | vitalir2 | 572,865,549 | false | {"Kotlin": 89962} | package day05
import Challenge
import java.util.*
import map
object Day05 : Challenge(5) {
override fun part1(input: List<String>): String {
return solveStacksProblem(parse(input)) { command, fromStack, toStack ->
repeat(command.times) {
val item = fromStack.pop()
toStack.push(item)
}
}
}
override fun part2(input: List<String>): String {
return solveStacksProblem(parse(input)) { command, fromStack, toStack ->
val taken = mutableListOf<Char>()
repeat(command.times) {
taken.add(fromStack.pop())
}
for (item in taken.reversed()) {
toStack.push(item)
}
}
}
private fun solveStacksProblem(
parsingResult: ParsingResult,
movementAlgorithm: (MovementCommand, from: Stack<Char>, to: Stack<Char>) -> Unit,
): String {
val (stacks, commands) = parsingResult
for (command in commands) {
val fromStack = stacks[command.fromStack]
val toStack = stacks[command.toStack]
movementAlgorithm(command, fromStack, toStack)
}
return stacks.map(Stack<Char>::peek).joinToString("")
}
private fun parse(input: List<String>): ParsingResult {
val stacksAndCommandSeparatorIndex = input.indexOfFirst { it.isEmpty() }
val initStackInput = input.subList(0, stacksAndCommandSeparatorIndex - 1)
val commandInput = input.subList(stacksAndCommandSeparatorIndex + 1, input.size)
val stacks: MutableList<Stack<Char>> = mutableListOf()
val lastStackNumber = input[stacksAndCommandSeparatorIndex - 1].trimEnd().last().digitToInt()
repeat(lastStackNumber) {
stacks.add(Stack())
}
initStacksValues(initStackInput, stacks)
val commands = parseCommands(commandInput)
return ParsingResult(stacks, commands)
}
private fun initStacksValues(input: List<String>, stacks: List<Stack<Char>>) {
input
.reversed() // start pushing from bottom
.map { line ->
line
.chunked(4) // '[A] ', '[D] ', ' ', ..
.withIndex() // ('[A] ', 0), ('[D] ', 1), (' ', 2), ..
.map { rawPossibleItemWithIndex -> // ('A', 0), ('D', 1), (null, 2), ..
rawPossibleItemWithIndex.map { value -> value.trim().getOrNull(1) }
}
.filter { it.value != null } // ('A', 0), ('D', 1), ..
}
.forEach { itemsOfStack -> itemsOfStack.forEach { (index, item) -> stacks[index].push(item) } }
}
private fun parseCommands(input: List<String>): List<MovementCommand> {
return buildList {
for (line in input) {
val (times, from, to) = line
.split(" ")
.filter { it.first().isDigit() }
.map { it.toInt() }
val command = MovementCommand(
times = times,
fromStack = from - 1,
toStack = to - 1
)
add(command)
}
}
}
private data class ParsingResult(
val stacks: List<Stack<Char>>,
val commands: List<MovementCommand>,
)
private data class MovementCommand(
val times: Int,
val fromStack: Int,
val toStack: Int,
)
}
| 0 | Kotlin | 0 | 0 | ceffb6d4488d3a0e82a45cab3cbc559a2060d8e6 | 3,522 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day16.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2020
import com.dvdmunckhof.aoc.splitOnce
import com.dvdmunckhof.aoc.toRange
class Day16(input: String) {
private val rules: Map<String, List<IntRange>>
private val ticket: List<Int>
private val nearbyTickets: List<List<Int>>
init {
val sections = input.split("\n\n")
rules = sections[0].split('\n').associate { line ->
val (key, value) = line.splitOnce(": ")
key to value.split(" or ").map(String::toRange)
}
ticket = sections[1].substringAfter('\n').split(',').map(String::toInt)
nearbyTickets = sections[2].split('\n').drop(1).map { line -> line.split(',').map(String::toInt) }
}
fun solvePart1(): Int {
val ranges = rules.values.flatten()
return nearbyTickets.flatten().filterNot { value -> ranges.contains(value) }.sum()
}
fun solvePart2(): Long {
val flatRanges = rules.values.flatten()
val validTickets = nearbyTickets.filter { values ->
values.all { value -> flatRanges.contains(value) }
}
val columnMapping = MutableList(ticket.size) { rules.keys.toMutableSet() }
for (ticket in validTickets) {
for ((index, value) in ticket.withIndex()) {
columnMapping[index].removeIf { fieldName -> !rules.getValue(fieldName).contains(value) }
}
}
val columns = columnMapping.sortedBy { it.size }
for (i in columns.indices) {
val fieldName = columns[i].first()
for (nextColumn in columns.listIterator(i + 1)) {
nextColumn.remove(fieldName)
}
}
return columnMapping.map { it.first() }.mapIndexed { index, field -> field to ticket[index] }
.filter { (fieldName, _) -> fieldName.startsWith("departure") }
.fold(1L) { acc, field -> acc * field.second.toLong() }
}
private fun List<IntRange>.contains(value: Int): Boolean {
return this.any { range -> range.contains(value) }
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 2,054 | advent-of-code | Apache License 2.0 |
src/Day04.kt | greeshmaramya | 514,310,903 | false | {"Kotlin": 8307} | fun main() {
fun List<String>.modifyInput(): MutableList<String> {
val passports: MutableList<String> = mutableListOf()
var s = ""
forEach {
if (it.isBlank()) {
passports.add(s)
s = ""
} else {
s += " "
s += it
}
}
passports.add(s)
return passports
}
fun String.valid1(): Boolean {
return contains("byr")
&& contains("iyr")
&& contains("eyr")
&& contains("hgt")
&& contains("hcl")
&& contains("ecl")
&& contains("pid")
}
fun Pair<String, String>.valid2(): Boolean {
return when (first) {
"byr" -> second.toInt() in 1920..2002
"iyr" -> second.toInt() in 2010..2020
"eyr" -> second.toInt() in 2020..2030
"hgt" -> {
val height = second.filter { it.isDigit() }.toInt()
return if (second.contains("cm")) {
height in 150..193
} else {
height in 59..76
}
}
"hcl" -> { val p = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$".toRegex()
p.matches(second)
}
"ecl" -> {
second == "amb" || second == "blu" || second == "brn" ||
second == "gry" || second == "grn" || second == "hzl" || second == "oth"
}
"pid" -> second.length == 9 && second.matches(Regex("[0-9]+"))
else -> true
}
}
fun part1(input: List<String>): Int = input.modifyInput().count { it.valid1() }
fun part2(input: List<String>) {
var count = 0
var valid2 = true
val p = input.modifyInput()
val s = input.modifyInput().map { it.trim() }.map { it.split(" ") }
.map { it1 -> it1.map { Pair(it.split(':').first(), it.split(':').last()) } }
s.forEachIndexed { index, it ->
for (i in it.indices) {
if (!it[i].valid2()) valid2 = false
}
if (p[index].valid1() && valid2) count++
valid2 = true
}
println(count)
}
val testInput = readInput("Day04Test")
val input = readInput("Day04")
println(part1(input))
part2(testInput)
part2(input)
}
| 0 | Kotlin | 0 | 0 | 9e1128ee084145f5a70fe3ad4e71b05944260d6e | 2,422 | aoc2020 | Apache License 2.0 |
src/Day11.kt | DiamondMiner88 | 573,073,199 | false | {"Kotlin": 26457, "Rust": 4093, "Shell": 188} | import java.math.BigInteger
fun main() {
d11part1()
// d11part2()
}
val regex =
"Monkey (\\d):\\n Starting items: (.+?)\\n Operation: new = old (.+?)\\n Test: divisible by (\\d{1,2})\\n If true: throw to monkey (\\d)\\n If false: throw to monkey (\\d)".toRegex()
data class Monkey(
var items: MutableList<BigInteger?>,
var operation: String,
var divisibleBy: BigInteger,
var targetMonkeyTrue: Int,
var targetMonkeyFalse: Int,
var totalInspections: Long = 0,
)
fun d11part1() {
val input = readInput("input/day11.txt")
val monkeys: MutableList<Monkey?> = MutableList(10) { null }
for (match in regex.findAll(input)) {
val (_, monkeyId, items, operation, divisibleBy, targetMonkeyTrue, targetMonkeyFalse) = match.groupValues
monkeys[monkeyId.toInt()] = Monkey(
items = items.split(",").map { it.trim().toBigInteger() }.toMutableList(),
operation = operation,
divisibleBy = divisibleBy.toBigInteger(),
targetMonkeyTrue = targetMonkeyTrue.toInt(),
targetMonkeyFalse = targetMonkeyFalse.toInt(),
)
}
for (round in 1..20) {
for (monkey in monkeys.filterNotNull()) {
val opParts = monkey.operation.split(" ")
val opNum = opParts[1].toBigIntegerOrNull() ?: BigInteger.valueOf(-1L)
monkey.items.forEach {
var newLevel = it ?: return@forEach
val num = if (opNum == BigInteger.valueOf(-1L)) newLevel else opNum
when (opParts[0]) {
"*" -> newLevel *= num
"+" -> newLevel += num
}
newLevel /= BigInteger.valueOf(3)
if (newLevel % monkey.divisibleBy == BigInteger.ONE) {
monkeys[monkey.targetMonkeyTrue]!!.items += newLevel
} else {
monkeys[monkey.targetMonkeyFalse]!!.items += newLevel
}
monkey.totalInspections++
}
monkey.items.clear()
}
}
println(
monkeys.sortedBy { it?.totalInspections }
.takeLast(2)
.let { it[0]!!.totalInspections * it[1]!!.totalInspections }
)
}
private operator fun <E> List<E>.component7(): E {
return this[6]
}
private operator fun <E> List<E>.component6(): E {
return this[5]
}
fun d11part2() {
val input = readInput("input/day11.txt")
val monkeys: MutableList<Monkey?> = MutableList(8) { null }
for (match in regex.findAll(input)) {
val (_, monkeyId, items, operation, divisibleBy, targetMonkeyTrue, targetMonkeyFalse) = match.groupValues
val parsedItems = items.split(",").map { it.trim().toBigInteger() }
monkeys[monkeyId.toInt()] = Monkey(
items = parsedItems.toMutableList(),
operation = operation,
divisibleBy = divisibleBy.toBigInteger(),
targetMonkeyTrue = targetMonkeyTrue.toInt(),
targetMonkeyFalse = targetMonkeyFalse.toInt(),
)
}
val totalItems = monkeys.sumOf { it?.items?.size ?: 0 }
for (monkey in monkeys) {
monkey?.items = MutableList(totalItems) { monkey?.items?.getOrNull(it) }
}
val monkeyOpParts = monkeys.map {
it ?: return@map null
val parts = it.operation.split(" ")
parts[0] to (parts[1].toBigIntegerOrNull() ?: BigInteger.valueOf(-1L))
}
val bigIntNegativeOne = BigInteger.valueOf(-1L)
for (round in 1..10000) {
println("round $round")
for (monkeyId in monkeys.indices) {
val monkey = monkeys[monkeyId] ?: continue
val (op, opNum) = monkeyOpParts[monkeyId] ?: continue
monkey.items.forEach {
var newLevel = it ?: return@forEach
val num = if (opNum == bigIntNegativeOne) newLevel else opNum
when (op) {
"*" -> newLevel *= num
"+" -> newLevel += num
}
num.abs()
if (newLevel % monkey.divisibleBy == BigInteger.ONE) {
val ind = monkeys[monkey.targetMonkeyTrue]!!.items.indexOf(null)
monkeys[monkey.targetMonkeyTrue]!!.items[ind] = newLevel
} else {
val ind = monkeys[monkey.targetMonkeyFalse]!!.items.indexOf(null)
monkeys[monkey.targetMonkeyFalse]!!.items[ind] = newLevel
}
monkey.totalInspections++
}
monkey.items.replaceAll { null }
}
}
println(monkeys)
println(
monkeys.sortedBy { it?.totalInspections }
.takeLast(2)
.let { it[0]!!.totalInspections * it[1]!!.totalInspections }
)
}
| 0 | Kotlin | 0 | 0 | 55bb96af323cab3860ab6988f7d57d04f034c12c | 4,815 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/kotlin/day03/Day03.kt | KingOfDog | 433,706,881 | false | {"Kotlin": 76907} | package day03
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 3
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay03Part1, ::solveDay03Part2)
}
fun solveDay03Part1(input: List<String>): Int {
val transposed = input.map { it.toCharArray() }.transpose()
val gamma = transposed.map { it.mostCommonBit() }.toBinaryInt()
val epsilon = transposed.map { it.leastCommonBit() }.toBinaryInt()
return gamma * epsilon
}
fun solveDay03Part2(input: List<String>): Int {
val oxygen = execute(input) { it.mostCommonBit() }
val co2 = execute(input) { it.leastCommonBit() }
return oxygen * co2
}
private fun execute(input: List<String>, targetFunction: (Array<Char>) -> Char): Int {
var chars = input.map { it.toCharArray() }
var index = 0
while (chars.size > 1) {
val targetBit = targetFunction(chars.transpose()[index])
chars = chars.filter { it[index] == targetBit }
index++
}
return String(chars[0]).toInt(2)
}
fun List<CharArray>.transpose(): Array<Array<Char>> {
val output = Array(this[0].size) { Array<Char>(size) { '0' } }
forEachIndexed { index, chars ->
chars.forEachIndexed { index2, c ->
output[index2][index] = c
}
}
return output
}
fun Array<Char>.mostCommonBit(): Char {
val count = countBits()
return if (count[0] > count[1]) '0' else '1'
}
fun Array<Char>.leastCommonBit(): Char {
val count = countBits()
return if (count[0] <= count[1]) '0' else '1'
}
fun Array<Char>.countBits(): Array<Int> {
val count = arrayOf(0, 0)
this.forEach { if (it == '0') count[0]++ else count[1]++ }
return count
}
fun List<Char>.toBinaryInt(): Int {
return String(this.toCharArray()).toInt(2)
}
| 0 | Kotlin | 0 | 0 | 576e5599ada224e5cf21ccf20757673ca6f8310a | 1,862 | advent-of-code-kt | Apache License 2.0 |
src/Day10.kt | rafael-ribeiro1 | 572,657,838 | false | {"Kotlin": 15675} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
return input.toCycles()
.filter { it.cycle in 20..220 && it.cycle % 40 == 20 }
.sumOf { it.cycle * it.x }
}
fun part2(input: List<String>): String {
var crtPos = 0
var prevPos = 1
return input.toCycles().joinToString("") {
val rowEnd = crtPos == 39
val pixel = (if (isLitPixel(prevPos, crtPos)) "#" else ".") + (if (rowEnd) "\n" else "")
crtPos = if (rowEnd) 0 else crtPos + 1
prevPos = it.x
pixel
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
println(part2(testInput))
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
fun List<String>.toCycles(): List<Cycle> {
val cycles = mutableListOf<Cycle>()
var cycle = 1
var x = 1
this.forEach { input ->
val split = input.split(" ")
if (split.size == 1) {
cycles.add(Cycle(++cycle, x))
} else {
cycles.add(Cycle(++cycle, x))
val value = split[1].toInt()
x += value
cycles.add(Cycle(++cycle, x))
}
}
return cycles
}
fun isLitPixel(spritePos: Int, crtPos: Int): Boolean = abs(spritePos - crtPos) <= 1
data class Cycle(val cycle: Int, val x: Int)
| 0 | Kotlin | 0 | 0 | 5cae94a637567e8a1e911316e2adcc1b2a1ee4af | 1,479 | aoc-kotlin-2022 | Apache License 2.0 |
src/Day09.kt | jamOne- | 573,851,509 | false | {"Kotlin": 20355} | import kotlin.math.abs
import kotlin.math.max
fun main() {
fun move(position: Pair<Int, Int>, direction: Direction): Pair<Int, Int> {
val (x, y) = position
return when (direction) {
Direction.UP -> Pair(x, y - 1)
Direction.DOWN -> Pair(x, y + 1)
Direction.LEFT -> Pair(x - 1, y)
Direction.RIGHT -> Pair(x + 1, y)
}
}
fun charToDirection(char: Char): Direction {
return when (char) {
'U' -> Direction.UP
'D' -> Direction.DOWN
'R' -> Direction.RIGHT
'L' -> Direction.LEFT
else -> throw IllegalArgumentException()
}
}
fun distance(pos1: Pair<Int, Int>, pos2: Pair<Int, Int>): Int {
return max(abs(pos1.first - pos2.first), abs(pos1.second - pos2.second))
}
fun sign(x: Int): Int {
return if (x > 0) 1
else if (x < 0) -1
else 0
}
fun updateTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
if (distance(head, tail) < 2) {
return tail
}
return Pair(tail.first + 1 * sign(head.first - tail.first), tail.second + 1 * sign(head.second - tail.second))
}
fun part1(input: List<String>): Int {
var head = Pair(0, 0)
var tail = Pair(0, 0)
var tailPositions = mutableSetOf(tail)
for (row in input) {
var (char, steps) = row.split(" ")
for (i in 0 until steps.toInt()) {
head = move(head, charToDirection(char[0]))
tail = updateTail(head, tail)
tailPositions.add(tail)
}
}
return tailPositions.size
}
fun part2(input: List<String>): Int {
var rope = Array(10) { Pair(0, 0) }
var tailPositions = mutableSetOf(rope[9])
for (row in input) {
var (char, steps) = row.split(" ")
for (i in 0 until steps.toInt()) {
rope[0] = move(rope[0], charToDirection(char[0]))
for (knot in 1 until 10) {
rope[knot] = updateTail(rope[knot - 1], rope[knot])
}
tailPositions.add(rope[9])
}
}
return tailPositions.size
}
val testInput = readInput("Day09_test")
println(part1(testInput))
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 77795045bc8e800190f00cd2051fe93eebad2aec | 2,520 | adventofcode2022 | Apache License 2.0 |
src/Day03.kt | melo0187 | 576,962,981 | false | {"Kotlin": 15984} | fun main() {
val priorityByItemType = (('a'..'z') + ('A'..'Z'))
.mapIndexed { index, itemType ->
val priority = index + 1
itemType to priority
}
.toMap()
fun part1(input: List<String>): Int = input
.map { rucksack ->
val (compartment1, compartment2) = rucksack.chunked(rucksack.length / 2)
compartment1.toCharArray() to compartment2.toCharArray()
}
.map { (compartment1, compartment2) ->
(compartment1 intersect compartment2.toSet()).single()
}
.sumOf { commonItemType ->
priorityByItemType.getValue(commonItemType)
}
fun part2(input: List<String>): Int = input
.map(String::toCharArray)
.chunked(3) { (rucksack1, rucksack2, rucksack3) ->
(rucksack1 intersect rucksack2.toSet() intersect rucksack3.toSet()).single()
}
.sumOf { itemTypeCorrespondingToGroupBadge ->
priorityByItemType.getValue(itemTypeCorrespondingToGroupBadge)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 97d47b84e5a2f97304a078c3ab76bea6672691c5 | 1,330 | kotlin-aoc-2022 | Apache License 2.0 |
src/Day09.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | import kotlin.math.abs
import kotlin.math.sign
private enum class Direction {
UP, DOWN, LEFT, RIGHT
}
fun main() {
data class Move(val direction: Direction, val steps: Int)
data class SnakeCell(private var row: Int, private var column: Int) {
fun move(direction: Direction) {
when (direction) {
Direction.UP -> row--
Direction.DOWN -> row++
Direction.LEFT -> column--
Direction.RIGHT -> column++
}
}
fun moveTo(other: SnakeCell) {
if (abs(row - other.row) <= 1 && abs(column - other.column) <= 1) return
row += (other.row - row).sign
column += (other.column - column).sign
}
}
class SnakeGame(cells: Int) {
private val snake = List(cells) { SnakeCell(0, 0) }
private val tailPath = mutableSetOf<SnakeCell>()
fun move(direction: Direction) {
snake.first().move(direction)
for ((curr, next) in snake.zipWithNext()) {
next.moveTo(curr)
}
tailPath.add(snake.last().copy())
}
val visitedCells: Int
get() = tailPath.size
}
fun parseMove(move: String): Move {
val (directionStr, stepsStr) = move.split(" ", limit = 2)
val direction = when (directionStr) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> error("Unexpected direction '$directionStr'")
}
return Move(direction, stepsStr.toInt())
}
fun countTailLength(snakeLength: Int, moves: List<Move>): Int {
val snakeGame = SnakeGame(cells = snakeLength)
for (move in moves) {
repeat(move.steps) {
snakeGame.move(move.direction)
}
}
return snakeGame.visitedCells
}
fun part1(input: List<String>): Int {
val moves = input.map { parseMove(it) }
return countTailLength(2, moves)
}
fun part2(input: List<String>): Int {
val moves = input.map { parseMove(it) }
return countTailLength(10, moves)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 88)
check(part2(testInput) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 2,502 | aoc2022 | Apache License 2.0 |
day-16/src/main/kotlin/PacketDecoder.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | import kotlin.system.measureTimeMillis
fun main() {
val partOneMillis = measureTimeMillis {
println("Part One Solution: ${partOne()}")
}
println("Part One Solved in: $partOneMillis ms")
val partTwoMillis = measureTimeMillis {
println("Part Two Solution: ${partTwo()}")
}
println("Part Two Solved in: $partTwoMillis ms")
}
val hexaToBinaryMapping = mapOf(
'0' to "0000",
'1' to "0001",
'2' to "0010",
'3' to "0011",
'4' to "0100",
'5' to "0101",
'6' to "0110",
'7' to "0111",
'8' to "1000",
'9' to "1001",
'A' to "1010",
'B' to "1011",
'C' to "1100",
'D' to "1101",
'E' to "1110",
'F' to "1111",
)
private fun partOne(): Int {
val input = decode(readInputLines()[0])
val (packet, _) = readPacket(input)!!
return sumPacketVersion(packet)
}
fun sumPacketVersion(packet: Packet): Int {
return packet.version + packet.subPackets.sumOf { sumPacketVersion(it) }
}
private fun partTwo(): Long {
val input = decode(readInputLines()[0])
val (packet, _) = readPacket(input)!!
return computePacketValue(packet)
}
/**
* ID 0 are sum packets - their value is the sum of the values of their sub-packets. If they only have a single sub-packet, their value is the value of the sub-packet.
* ID 1 are product packets - their value is the result of multiplying together the values of their sub-packets. If they only have a single sub-packet, their value is the value of the sub-packet.
* ID 2 are minimum packets - their value is the minimum of the values of their sub-packets.
* ID 3 are maximum packets - their value is the maximum of the values of their sub-packets.
* ID 5 are greater than packets - their value is 1 if the value of the first sub-packet is greater than the value of the second sub-packet; otherwise, their value is 0. These packets always have exactly two sub-packets.
* ID 6 are less than packets - their value is 1 if the value of the first sub-packet is less than the value of the second sub-packet; otherwise, their value is 0. These packets always have exactly two sub-packets.
* ID 7 are equal to packets - their value is 1 if the value of the first sub-packet is equal to the value of the second sub-packet; otherwise, their value is 0. These packets always have exactly two sub-packets.
*/
fun computePacketValue(packet: Packet): Long = when (packet.typeId) {
0 -> packet.subPackets.sumOf { computePacketValue(it) }
1 -> packet.subPackets.map { computePacketValue(it) }.reduce(Long::times)
2 -> packet.subPackets.map { computePacketValue(it) }.minOf { it }
3 -> packet.subPackets.map { computePacketValue(it) }.maxOf { it }
4 -> packet.value!!
5 -> {
val (first, second) = packet.subPackets.map { computePacketValue(it) }
if (first > second) 1 else 0
}
6 -> {
val (first, second) = packet.subPackets.map { computePacketValue(it) }
if (first < second) 1 else 0
}
7 -> {
val (first, second) = packet.subPackets.map { computePacketValue(it) }
if (first == second) 1 else 0
}
else -> throw RuntimeException("Impossible state")
}
val regex = Regex("([0-1]{3})([0-1]{3})([0-1]*)")
fun readPacket(input: String): Pair<Packet, String>? {
if (!regex.matches(input)) {
return null
}
val groups = regex.matchEntire(input)!!.groups
val version = groups[1]!!.value.toInt(2)
val typeId = groups[2]!!.value.toInt(2)
val body = groups[3]!!.value
return if (typeId == 4) {
readLiteral(body, version, typeId)
} else {
readOperation(body, version, typeId)
}
}
private fun readOperation(body: String, version: Int, typeId: Int): Pair<Packet, String> {
var updatedBody = body
val lengthTypeId = updatedBody.take(1)
updatedBody = updatedBody.substring(1)
return when (lengthTypeId) {
"0" -> {
readZeroLengthType(updatedBody, version, typeId)
}
"1" -> {
readOneLengthType(updatedBody, version, typeId)
}
else -> {
throw RuntimeException("Impossible State")
}
}
}
private fun readOneLengthType(body: String, version: Int, typeId: Int): Pair<Packet, String> {
var updatedBody = body
val numberOfSubPackets = updatedBody.take(11).toInt(2)
updatedBody = updatedBody.substring(11)
val subs = mutableListOf<Packet>()
for (i in 1..numberOfSubPackets) {
readPacket(updatedBody)?.let {
subs.add(it.first)
updatedBody = it.second
}
}
val packet = Packet(version = version, typeId = typeId, subPackets = subs)
return Pair(packet, updatedBody)
}
private fun readZeroLengthType(body: String, version: Int, typeId: Int): Pair<Packet, String> {
var updatedBody = body
val length = updatedBody.take(15).toInt(2)
updatedBody = updatedBody.substring(15)
var subpackets = updatedBody.take(length)
updatedBody = updatedBody.substring(length)
val packet = Packet(version = version, typeId = typeId)
val subs = mutableListOf<Packet>()
while (true) {
val result = readPacket(subpackets)
if (result == null) {
break
} else {
subpackets = result.second
subs.add(result.first)
}
}
packet.subPackets.addAll(subs)
return Pair(packet, updatedBody)
}
private fun readLiteral(body: String, version: Int, typeId: Int): Pair<Packet, String> {
var updatedBody = body
var literal = ""
while (true) {
val number = updatedBody.take(5)
updatedBody = updatedBody.substring(5)
if (number[0] == '1') {
literal += number.substring(1)
} else {
literal += number.substring(1)
break
}
}
return Pair(Packet(version = version, typeId = typeId, value = literal.toLong(2)), updatedBody)
}
data class Packet(
val version: Int,
val typeId: Int,
val value: Long? = null,
val subPackets: MutableList<Packet> = mutableListOf(),
)
fun decode(s: String): String {
return s.map {
hexaToBinaryMapping[it]
}.joinToString("")
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 6,383 | aoc-2021 | MIT License |
src/main/kotlin/days/Day15.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
import kotlin.math.abs
class Day15 : Day(15) {
override fun partOne(): Any {
val targetRow = 2000000
val input = parseInput()
val sensors = input.mapValues { (s, b) -> manDistance(s, b) }
val beacons = input.values.distinct()
val events = intervalEvents(sensors, targetRow)
var nonBeacon = 0
var curStart: Int? = null
var layers = 0
events.forEach { event ->
when (event.type) {
EventType.START -> {
if (layers == 0) curStart = event.at
layers++
}
EventType.END -> {
layers--
if (layers == 0) nonBeacon += event.at - curStart!! + 1
}
}
}
val minusBeacons = beacons.count { it.row == targetRow }
val minusSensors = sensors.keys.count { it.row == targetRow }
return nonBeacon - minusBeacons - minusSensors
}
override fun partTwo(): Any {
val maxBound = 4000000
val input = parseInput()
val sensors = input.mapValues { (s, b) -> manDistance(s, b) }
for (y in 0..maxBound) {
val events = intervalEvents(sensors, y)
var lastEnd: Int? = null
var curStart: Int
var layers = 0
events.forEach { event ->
when (event.type) {
EventType.START -> {
if (layers == 0) {
curStart = event.at
if (lastEnd != null && curStart - lastEnd!! == 2) {
return tuningFrequency(Point(y, curStart - 1))
}
}
layers++
}
EventType.END -> {
layers--
if (layers == 0) lastEnd = event.at
}
}
}
}
throw IllegalStateException("Couldn't find the signal location")
}
private fun intervalEvents(sensors: Map<Point, Int>, targetRow: Int): List<Event> {
val intervals = sensors
.filter { (sensor, rad) -> abs(sensor.row - targetRow) <= rad }
.map { (sensor, rad) ->
val l = sensor.col - (rad - abs(sensor.row - targetRow))
val r = sensor.col + (rad - abs(sensor.row - targetRow))
l..r
}
return intervals
.flatMap { listOf(Event(it.first, EventType.START), Event(it.last, EventType.END)) }
.sortedBy { it.at }
}
private fun parseInput(): Map<Point, Point> {
return inputList.associate { line ->
val (Scol, Srow, Bcol, Brow) = "Sensor at x=(-?\\d*), y=(-?\\d*): closest beacon is at x=(-?\\d*), y=(-?\\d*)".toRegex()
.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() }
Point(Srow, Scol) to Point(Brow, Bcol)
}
}
private fun manDistance(from: Point, to: Point): Int {
return abs(from.row - to.row) + abs(from.col - to.col)
}
private fun tuningFrequency(point: Point): Long {
return point.col * 4000000L + point.row
}
data class Point(val row: Int, val col: Int)
data class Event(val at: Int, val type: EventType)
enum class EventType { START, END }
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 3,438 | aoc-2022 | Creative Commons Zero v1.0 Universal |
advent-of-code-2023/src/main/kotlin/Day15.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | // Day 15: Lens Library
// https://adventofcode.com/2023/day/15
import java.io.File
private const val DASH = "-"
private const val EQUALS = "="
fun main() {
val input = File("src/main/resources/Day15.txt").readText()
val initializationSequence = input.split(",")
val initializationSequenceSum = initializationSequence.sumOf { step ->
hashString(step.toList())
}
println(initializationSequenceSum)
val sumOfFocusPower = findSumOfFocusPowers(initializationSequence)
println(sumOfFocusPower)
}
private fun hashString(string: List<Char>): Int {
var currentValue = 0
for (character in string) {
currentValue += character.code
currentValue *= 17
currentValue %= 256
}
return currentValue
}
fun findSumOfFocusPowers(initializationSequence: List<String>): Int {
val boxToLensMap = mutableMapOf<Int, List<Pair<String, Int>>>()
initializationSequence.forEach { step ->
val label = step.substringBefore(
if (step.contains(EQUALS)) EQUALS else DASH
)
val stepBox = hashString(label.toList())
val boxWithExistingLens = boxToLensMap.filterValues { lens ->
lens.count { it.first == label } > 0
}.keys
if (step.contains(EQUALS)) {
val focalLength = step.substringAfter(EQUALS).toInt()
if (boxWithExistingLens.isNotEmpty()) {
val lens = boxToLensMap.getOrDefault(stepBox, emptyList()).toMutableList()
val indexToReplace = lens.indexOfFirst { it.first == label }
lens[indexToReplace] = label to focalLength
boxToLensMap[stepBox] = lens
} else {
boxToLensMap[stepBox] = boxToLensMap.getOrDefault(stepBox, emptyList())
.plus(label to focalLength)
}
} else if (step.contains(DASH)) {
if (boxWithExistingLens.isNotEmpty()) {
val lens = boxToLensMap.getOrDefault(stepBox, emptyList()).toMutableList()
lens.removeAt(lens.indexOfFirst { it.first == label })
boxToLensMap[stepBox] = lens
}
}
}
var sum = 0
for (box in boxToLensMap.keys) {
boxToLensMap[box]?.forEachIndexed { i, lens ->
sum += (box + 1) * (i + 1) * lens.second
}
}
return sum
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,371 | advent-of-code | Apache License 2.0 |
src/main/kotlin/g2201_2300/s2203_minimum_weighted_subgraph_with_the_required_paths/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2201_2300.s2203_minimum_weighted_subgraph_with_the_required_paths
// #Hard #Graph #Shortest_Path #2023_06_27_Time_1126_ms_(100.00%)_Space_127.2_MB_(100.00%)
import java.util.PriorityQueue
import java.util.Queue
class Solution {
fun minimumWeight(n: Int, edges: Array<IntArray>, src1: Int, src2: Int, dest: Int): Long {
val graph: Array<MutableList<IntArray>?> = arrayOfNulls(n)
val weight = Array(3) { LongArray(n) }
for (i in 0 until n) {
for (j in 0..2) {
weight[j][i] = Long.MAX_VALUE
}
graph[i] = ArrayList()
}
for (e in edges) {
graph[e[0]]?.add(intArrayOf(e[1], e[2]))
}
val queue: Queue<Node> = PriorityQueue({ node1: Node, node2: Node -> node1.weight.compareTo(node2.weight) })
queue.offer(Node(0, src1, 0))
weight[0][src1] = 0
queue.offer(Node(1, src2, 0))
weight[1][src2] = 0
while (queue.isNotEmpty()) {
val curr = queue.poll()
if (curr.vertex == dest && curr.index == 2) {
return curr.weight
}
for (next in graph[curr.vertex]!!) {
if (curr.index == 2 && weight[curr.index][next[0]] > curr.weight + next[1]) {
weight[curr.index][next[0]] = curr.weight + next[1]
queue.offer(Node(curr.index, next[0], weight[curr.index][next[0]]))
} else if (weight[curr.index][next[0]] > curr.weight + next[1]) {
weight[curr.index][next[0]] = curr.weight + next[1]
queue.offer(Node(curr.index, next[0], weight[curr.index][next[0]]))
if (weight[curr.index xor 1][next[0]] != Long.MAX_VALUE &&
weight[curr.index][next[0]] + weight[curr.index xor 1][next[0]]
< weight[2][next[0]]
) {
weight[2][next[0]] = weight[curr.index][next[0]] + weight[curr.index xor 1][next[0]]
queue.offer(Node(2, next[0], weight[2][next[0]]))
}
}
}
}
return -1
}
private class Node(var index: Int, var vertex: Int, var weight: Long)
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,263 | LeetCode-in-Kotlin | MIT License |
src/Day02.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | import Sign.*
import java.lang.RuntimeException
enum class Sign { ROCK, PAPER, SCISSORS }
data class Round(val opponent: Sign, val mine: Sign) {
private fun signPoints() =
when (mine) {
ROCK -> 1
PAPER -> 2
SCISSORS -> 3
}
private fun matchPoints() =
when (mine) {
ROCK -> when (opponent) {
ROCK -> 3
PAPER -> 0
SCISSORS -> 6
}
PAPER -> when (opponent) {
ROCK -> 6
PAPER -> 3
SCISSORS -> 0
}
SCISSORS -> when (opponent) {
ROCK -> 0
PAPER -> 6
SCISSORS -> 3
}
}
fun totalPoints() = signPoints() + matchPoints()
}
fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.split(" ") }
.map {
it.map { sign ->
when (sign) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw RuntimeException()
}
}
}
.map { (opponent, mine) -> Round(opponent, mine) }
.sumOf { it.totalPoints() }
}
fun part2(input: List<String>): Int {
val signs = listOf(ROCK, SCISSORS, PAPER)
return input
.map { it.split(" ") }
.map { (opponentSign, mySign) ->
val opponent = when (opponentSign) {
"A" -> ROCK
"B" -> PAPER
"C" -> SCISSORS
else -> throw RuntimeException()
}
val mine = when (mySign) {
"X" -> signs[(signs.indexOf(opponent) + 1) % signs.size]
"Y" -> opponent
"Z" -> signs[(signs.indexOf(opponent) + 2) % signs.size]
else -> throw RuntimeException()
}
Round(opponent, mine)
}
.sumOf { it.totalPoints() }
}
val input = readInput("inputs/Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 2,281 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | Flexicon | 576,933,699 | false | {"Kotlin": 5474} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
(line[2] - Char(87)) + when (line) {
"A X", "B Y", "C Z" -> 3
"A Y", "B Z", "C X" -> 6
else -> 0
}
}
}
fun part2(input: List<String>): Int {
fun Int.inBounds() = when {
this <= 0 -> 3
this > 3 -> 1
else -> this
}
return input.sumOf { line ->
val opponent = line[0] - Char(64)
when (line[2]) {
'X' -> 0 + (opponent - 1).inBounds()
'Y' -> 3 + opponent
else -> 6 + (opponent + 1).inBounds()
}
}
}
val testInput = readInput("Day02_test")
val part1Result = part1(testInput)
val expected1 = 15
check(part1Result == expected1) { "Part 1: Expected $expected1, actual $part1Result" }
val part2Result = part2(testInput)
val expected2 = 12
check(part2Result == expected2) { "Part 2: Expected $expected2, actual $part2Result" }
val input = readInput("Day02")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 7109cf333c31999296e1990ce297aa2db3a622f2 | 1,178 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2021/day3/Day3.kt | arnab | 75,525,311 | false | null | package aoc2021.day3
object Day3 {
fun parse(data: String) = data.split("\n")
.map { readings -> readings.split("").filterNot { it.isBlank() } }
fun calculatePowerConsumption(readings: List<List<String>>): Int =
calculateGamma(readings) * calculateEpsilon(readings)
private fun calculateGamma(readings: List<List<String>>): Int {
val bits = readings.first().mapIndexed { i, _ ->
readings.map { it[i] }.groupingBy { it }.eachCount().maxBy { it.value }!!.key
}.joinToString("")
return Integer.parseInt(bits, 2)
}
private fun calculateEpsilon(readings: List<List<String>>): Int {
val bits = readings.first().mapIndexed { i, _ ->
readings.map { it[i] }.groupingBy { it }.eachCount().minBy { it.value }!!.key
}.joinToString("")
return Integer.parseInt(bits, 2)
}
fun calculateLifeSupport(readings: List<List<String>>) =
calculateO2Rating(readings, index = 0) * calculateCO2Rating(readings, index = 0)
private fun calculateO2Rating(readings: List<List<String>>, index: Int): Int {
if (readings.size == 1) {
return Integer.parseInt(readings.first().joinToString(""), 2)
}
val bitCounts = readings.map { it[index] }.groupingBy { it }.eachCount()
val filterBit = if (bitCounts["0"] == bitCounts["1"]) "1" else bitCounts.maxBy { it.value }!!.key
val remainingReadings = readings.filter { it[index] == filterBit }
return calculateO2Rating(remainingReadings, index + 1)
}
private fun calculateCO2Rating(readings: List<List<String>>, index: Int): Int {
if (readings.size == 1) {
return Integer.parseInt(readings.first().joinToString(""), 2)
}
val bitCounts = readings.map { it[index] }.groupingBy { it }.eachCount()
val filterBit = if (bitCounts["0"] == bitCounts["1"]) "0" else bitCounts.minBy { it.value }!!.key
val remainingReadings = readings.filter { it[index] == filterBit }
return calculateCO2Rating(remainingReadings, index + 1)
}
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 2,101 | adventofcode | MIT License |
src/main/kotlin/io/steinh/aoc/day06/BoatRace.kt | daincredibleholg | 726,426,347 | false | {"Kotlin": 25396} | package io.steinh.aoc.day06
class BoatRace(private val input: BoatRaceStats) {
fun calculateWaysToBeatTheRecord(): Int {
val possibleWins = buildList {
input.timeToDistance.forEach { (time, distance) ->
add(
buildList {
for (i in 1..time) {
if (((time - i).times(i)) > distance) {
add(i)
}
}
}
)
}
}
return possibleWins.map { it.size }.reduce { acc, next -> acc * next }
}
fun calculateForOneLargeRace(): Int {
val longTime = input.timeToDistance.keys.map { it.toString() }.reduce { acc, next -> "$acc$next" }.toLong()
val longDistance =
input.timeToDistance.values.map { it.toString() }.reduce { acc, next -> "$acc$next" }.toLong()
var count = 0
for (i in 1..longTime) {
if ((longTime - i).times(i) > longDistance) {
count++
}
}
return count
}
}
data class BoatRaceStats(
val timeToDistance: Map<Int, Int>
)
fun interpretStats(input: String): BoatRaceStats {
val inputLines = input.split("\n")
val times = "(\\d+)".toRegex().findAll(inputLines[0])
.map {
it.groupValues[0].toInt()
}
.toList()
val distances = "(\\d+)".toRegex().findAll(inputLines[1])
.map {
it.groupValues[0].toInt()
}
.toList()
return BoatRaceStats(
timeToDistance = times.zip(distances) { t, d -> t to d }.toMap()
)
}
fun main() {
val input = {}.javaClass.classLoader?.getResource("day06/input.txt")?.readText()!!
val boatRace = BoatRace(interpretStats(input))
val partOneResult = boatRace.calculateWaysToBeatTheRecord()
println("Result for day 06, part I: $partOneResult")
val partTwoResult = boatRace.calculateForOneLargeRace()
println("Result for day 06, part II: $partTwoResult")
}
| 0 | Kotlin | 0 | 0 | 4aa7c684d0e337c257ae55a95b80f1cf388972a9 | 2,073 | AdventOfCode2023 | MIT License |
src/Day13/Day13.kt | martin3398 | 436,014,815 | false | {"Kotlin": 63436, "Python": 5921} | import kotlin.math.max
fun main() {
fun Array<Array<Boolean>>.print() {
for (row in this) {
for (e in row) {
print("${if (e) "X" else "."} ")
}
println()
}
}
fun preprocess(input: List<String>): Pair<Array<Array<Boolean>>, List<Pair<String, Int>>> {
var i = 0
val points = mutableListOf<Pair<Int, Int>>()
while (input[i] != "") {
val split = input[i].split(",")
points.add(Pair(split[0].toInt(), split[1].toInt()))
i++
}
i++
val folds = mutableListOf<Pair<String, Int>>()
while (i < input.size) {
val split = input[i].split(" ").last().split("=")
folds.add(Pair(split[0], split[1].toInt()))
i++
}
val maxX = points.maxOf { it.first }
val maxY = points.maxOf { it.second }
val grid = Array(maxY + 1) { Array(maxX + 1) { false } }
for (e in points) {
grid[e.second][e.first] = true
}
return Pair(grid, folds)
}
fun foldY(input: Array<Array<Boolean>>, direction: Int): Array<Array<Boolean>> {
var lower = input.slice(0 until direction).toTypedArray()
var upper = input.slice(direction + 1 until input.size).reversed().toTypedArray()
if (lower.size > upper.size) {
lower = upper.also { upper = lower }
}
val res = Array(max(lower.size, upper.size)) { Array(input[0].size) { false } }
for ((i, e) in upper.withIndex()) {
res[i] = e
}
val offset = res.size - lower.size
for ((i, e) in lower.withIndex()) {
res[offset + i] = res[offset + i].mapIndexed { index, b -> b || e[index] }.toTypedArray()
}
return res
}
fun foldX(input: Array<Array<Boolean>>, direction: Int): Array<Array<Boolean>> {
var left = input.map { it.slice(0 until direction).toTypedArray() }.toTypedArray()
var right = input.map { it.slice(direction + 1 until it.size).reversed().toTypedArray() }.toTypedArray()
if (left[0].size > right[0].size) {
right = left.also { left = right }
}
val res = Array(input.size) { Array(max(left[0].size, right[0].size)) { false } }
for ((i, e) in right.withIndex()) {
res[i] = e
}
val offset = res[0].size - left[0].size
for ((i, e) in left.withIndex()) {
res[i] =
res[i].mapIndexed { index, b -> b || if (index >= offset) e[index - offset] else false }.toTypedArray()
}
return res
}
fun part1(input: Pair<Array<Array<Boolean>>, List<Pair<String, Int>>>): Int {
return if (input.second[0].first == "x") {
foldX(input.first, input.second[0].second)
} else {
foldY(input.first, input.second[0].second)
}.sumOf { it.count { x -> x } }
}
fun part2(input: Pair<Array<Array<Boolean>>, List<Pair<String, Int>>>): Int {
var inputWc = input.first
for (e in input.second) {
inputWc = if (e.first == "x") {
foldX(inputWc, e.second)
} else {
foldY(inputWc, e.second)
}
}
inputWc.print()
return 0
}
val testInput = preprocess(readInput(13, true))
val input = preprocess(readInput(13))
check(part1(testInput) == 17)
println(part1(input))
check(part2(testInput) == 0)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 085b1f2995e13233ade9cbde9cd506cafe64e1b5 | 3,540 | advent-of-code-2021 | Apache License 2.0 |
src/Day04.kt | haitekki | 572,959,197 | false | {"Kotlin": 24688} | fun main() {
fun part1(input: String): Int {
return input.lines().map {
Pair(it.substringBefore(',').trim(), it.substringAfter(',').trim()).let { pair ->
val fSet = (pair.first.substringBefore("-").toInt() .. pair.first.substringAfter("-").toInt()).toSet()
val sSet = (pair.second.substringBefore("-").toInt() .. pair.second.substringAfter("-").toInt()).toSet()
if (fSet.containsAll(sSet) || sSet.containsAll(fSet)) 1 else 0
}
}.sum()
}
fun part2(input: String): Int {
return input.lines().map {
Pair(it.substringBefore(',').trim(), it.substringAfter(',').trim()).let { pair ->
val fSet = (pair.first.substringBefore("-").toInt() .. pair.first.substringAfter("-").toInt()).toSet()
val sSet = (pair.second.substringBefore("-").toInt() .. pair.second.substringAfter("-").toInt()).toSet()
if (fSet.any { v -> sSet.contains(v) }|| sSet.any{ v -> fSet.contains(v) }) 1 else 0
}
}.sum()
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b7262133f9115f6456aa77d9c0a1e9d6c891ea0f | 1,166 | aoc2022 | Apache License 2.0 |
src/Day08.kt | MarkRunWu | 573,656,261 | false | {"Kotlin": 25971} | import java.lang.Integer.max
enum class Direction(val raw: Int) {
Left(0),
Top(1),
Right(2),
Bottom(3)
}
fun main() {
fun dumpMaxTreeMap(maxTreeMap: Array<Array<Array<Int>>>, direction: Direction) {
for (i in maxTreeMap.indices) {
for (j in maxTreeMap[i].indices) {
print("[${maxTreeMap[i][j][direction.raw]}]")
}
println()
}
println()
}
fun part1(input: List<String>): Int {
val maxTreeMap = Array(input.size) {
Array(input.first().length) {
Array(4) { 0 }
}
}
for (i in input.indices) {
for (j in input[i].indices) {
val value = input[i][j].digitToInt()
if (i == 0 || j == 0 || i == input.lastIndex || j == input[i].lastIndex) {
maxTreeMap[i][j][Direction.Left.raw] = value
maxTreeMap[i][j][Direction.Top.raw] = value
continue
}
maxTreeMap[i][j][Direction.Left.raw] =
max(maxTreeMap[i][j - 1][Direction.Left.raw], value)
maxTreeMap[i][j][Direction.Top.raw] =
max(maxTreeMap[i - 1][j][Direction.Top.raw], value)
}
}
for (i in input.indices.reversed()) {
for (j in input[i].indices.reversed()) {
val value = input[i][j].digitToInt()
if (i == 0 || j == 0 || i == input.lastIndex || j == input[i].lastIndex) {
maxTreeMap[i][j][Direction.Right.raw] = value
maxTreeMap[i][j][Direction.Bottom.raw] = value
continue
}
maxTreeMap[i][j][Direction.Right.raw] =
max(maxTreeMap[i][j + 1][Direction.Right.raw], value)
maxTreeMap[i][j][Direction.Bottom.raw] =
max(maxTreeMap[i + 1][j][Direction.Bottom.raw], value)
}
}
var count = 0
for (i in input.indices) {
for (j in input[i].indices) {
if (i == 0 || j == 0 || i == input.lastIndex || j == input[i].lastIndex) {
count++
} else {
val value = input[i][j].digitToInt()
if ((value == maxTreeMap[i][j][Direction.Left.raw] &&
value > maxTreeMap[i][j - 1][Direction.Left.raw]) ||
(value == maxTreeMap[i][j][Direction.Top.raw] &&
value > maxTreeMap[i - 1][j][Direction.Top.raw]) ||
(value == maxTreeMap[i][j][Direction.Right.raw] &&
value > maxTreeMap[i][j + 1][Direction.Right.raw]) ||
(value == maxTreeMap[i][j][Direction.Bottom.raw]
&& value > maxTreeMap[i + 1][j][Direction.Bottom.raw])
) {
count++
}
}
}
}
return count
}
fun part2(input: List<String>): Int {
val visibleTreesMap = Array(input.size) {
Array(input.first().length) {
Array(4) { 0 }
}
}
val digitsInput = input.map { it ->
it.map {
it.digitToInt()
}
}
for (i in digitsInput.indices) {
for (j in digitsInput[i].indices) {
var maxTreeHeight = -1
for (k in i + 1 until digitsInput.size) {
if (digitsInput[k][j] > maxTreeHeight) {
maxTreeHeight = digitsInput[k][j]
visibleTreesMap[k][j][Direction.Top.raw]++
}
}
}
}
for (i in digitsInput.indices) {
for (j in digitsInput[i].indices) {
var maxTreeHeight = -1
for (k in j + 1 until digitsInput[i].size) {
if (digitsInput[i][k] > maxTreeHeight) {
maxTreeHeight = digitsInput[i][k]
visibleTreesMap[i][k][Direction.Left.raw]++
}
}
}
}
for (i in digitsInput.indices.reversed()) {
for (j in digitsInput[i].indices.reversed()) {
var maxTreeHeight = -1
for (k in i - 1 downTo 0) {
if (digitsInput[k][j] > maxTreeHeight) {
maxTreeHeight = digitsInput[k][j]
visibleTreesMap[k][j][Direction.Bottom.raw]++
}
}
}
}
for (i in digitsInput.indices.reversed()) {
for (j in digitsInput[i].indices.reversed()) {
var maxTreeHeight = -1
for (k in j - 1 downTo 0) {
if (digitsInput[i][k] > maxTreeHeight) {
maxTreeHeight = digitsInput[i][k]
visibleTreesMap[i][k][Direction.Right.raw]++
}
}
}
}
return visibleTreesMap.maxOf { it ->
it.maxOf {
it[Direction.Top.raw] *
it[Direction.Left.raw] *
it[Direction.Right.raw] *
it[Direction.Bottom.raw]
}
}
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ced885dcd6b32e8d3c89a646dbdcf50b5665ba65 | 5,556 | AOC-2022 | Apache License 2.0 |
src/Day17/Day17.kt | martin3398 | 436,014,815 | false | {"Kotlin": 63436, "Python": 5921} | fun main() {
fun preprocess(input: List<String>): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val split = input[0].split(" ")
val x = split[2].split("=")[1].split(",")[0].split("..")
val y = split[3].split("=")[1].split("..")
return Pair(Pair(x[0].toInt(), x[1].toInt()), Pair(y[0].toInt(), y[1].toInt()))
}
fun calc(input: Pair<Pair<Int, Int>, Pair<Int, Int>>): Pair<Int, Int> {
val xRange = input.first.first..input.first.second
val yRange = input.second.first..input.second.second
var count = 0
var bestY = 0
// range -500..500 should be sufficient
for (vxSearch in -500..500) {
for (vySearch in -500..500) {
var x = 0
var y = 0
var vx = vxSearch
var vy = vySearch
var maxY = 0
while (y >= input.second.first) {
x += vx
y += vy
if (vx != 0) {
vx += if (vx > 0) -1 else 1
}
if (y > maxY) {
maxY = y
}
vy--
if (x in xRange && y in yRange) {
count++
if (maxY > bestY) {
bestY = maxY
}
break
}
}
}
}
return Pair(bestY, count)
}
fun part1(input: Pair<Pair<Int, Int>, Pair<Int, Int>>): Int {
return calc(input).first
}
fun part2(input: Pair<Pair<Int, Int>, Pair<Int, Int>>): Int {
return calc(input).second
}
val testInput = preprocess(readInput(17, true))
val input = preprocess(readInput(17))
check(part1(testInput) == 45)
println(part1(input))
check(part2(testInput) == 112)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 085b1f2995e13233ade9cbde9cd506cafe64e1b5 | 1,957 | advent-of-code-2021 | Apache License 2.0 |
src/Day14.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | private fun parsePath(input: String): List<Coord2D> {
return input.split(" -> ").map {
it.split(",").map { it.toInt() }.let { (x, y) -> Coord2D(x, y) }
}
}
private infix fun Int.smartRange(o: Int) = if (this < o) this .. o else o .. this
private fun Coord2D.lineTo(other: Coord2D): Sequence<Coord2D> {
return when {
x == other.x -> (y smartRange other.y).asSequence().map { Coord2D(x, it) }
y == other.y -> (x smartRange other.x).asSequence().map { Coord2D(it, y) }
else -> throw IllegalArgumentException("the other point must have same x or same y")
}
}
private fun drawOnMap(m: MutableSet<Coord2D>, path: List<Coord2D>) {
path.zipWithNext().forEach { (x, y) -> m.addAll(x.lineTo(y)) }
}
/** Mutable Coord 2D */
data class Sand(var x: Int, var y: Int) {
fun toCoord(dx: Int = 0, dy: Int = 0) = Coord2D(x + dx, y + dy)
fun move(dx: Int = 0, dy: Int = 0) {
x += dx
y += dy
}
/** simulate fall, stops when y == maxY */
fun simulateFall(map: Set<Coord2D>, maxY: Int) {
if (y >= maxY) return
if (toCoord(dy = 1) !in map) {
move(dy = 1)
simulateFall(map, maxY = maxY)
} else if (toCoord(dy = 1, dx = -1) !in map) {
move(dy = 1, dx = -1)
simulateFall(map, maxY = maxY)
} else if (toCoord(dy = 1, dx = 1) !in map) {
move(dy = 1, dx = 1)
simulateFall(map, maxY = maxY)
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val paths = input.map(::parsePath)
val map = mutableSetOf<Coord2D>()
paths.forEach { drawOnMap(map, it) }
var cnt = 0
val lowestY = paths.maxOf { points -> points.maxOf { point -> point.y } }
while (true) {
val sand = Sand(500, 0).also { it.simulateFall(map, lowestY) }
if (sand.y == lowestY) {
break
}
map.add(sand.toCoord())
cnt++
}
return cnt
}
fun part2(input: List<String>): Int {
val paths = input.map(::parsePath)
val map = mutableSetOf<Coord2D>()
paths.forEach { drawOnMap(map, it) }
var cnt = 0
val lowestY = paths.maxOf { points -> points.maxOf { point -> point.y } } + 1
while (true) {
val sand = Sand(500, 0).also { it.simulateFall(map, lowestY) }
map.add(sand.toCoord())
cnt++
if (sand.toCoord() == Coord2D(500, 0)) break
}
return cnt
}
val testInput = readInput("Day14_test")
println(part1(testInput))
check(part1(testInput) == 24)
println(part2(testInput))
check(part2(testInput) == 93)
val input = readInput("Day14")
println("Part 1")
println(part1(input))
println("Part 2")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 2,860 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day08.kt | allisonjoycarter | 574,207,005 | false | {"Kotlin": 22303} | import java.io.InputStream
import java.util.*
import kotlin.collections.ArrayList
enum class Direction(val horizontal: Int = 0, val vertical: Int = 0) {
Up(vertical = -1),
Down(vertical = 1),
Left(horizontal = -1),
Right(horizontal = 1)
}
fun main() {
fun traverseDirectionAndCheckVisible(input: List<String>, direction: Direction, x: Int, y: Int, value: Int): Boolean {
if (x <= 0 || y <= 0 || y >= input.size - 1 || x >= input[y].length - 1) { // check if we are on the edges
return input[y][x].digitToInt() < value
}
return input[y][x].digitToInt() < value && // is this a short tree? otherwise keep moving
traverseDirectionAndCheckVisible(input, direction, x + direction.horizontal, y + direction.vertical, value)
}
fun traverseDirectionAndCheckScenery(input: List<String>, direction: Direction, x: Int, y: Int, value: Int, score: Int = 0, blocked: Boolean = false): Int {
if (blocked || x < 0 || y < 0 || y > input.size - 1 || x > input[y].length - 1) { // check if we are on the edges
return score
}
return traverseDirectionAndCheckScenery(input, direction,
x + direction.horizontal, y + direction.vertical, value, score + 1, input[y][x].digitToInt() >= value)
}
fun part1(input: List<String>): Int {
var visible = input.first().count() + input.last().count()
input.forEachIndexed { lineNumber, line ->
if (lineNumber != 0 && lineNumber < input.size - 1) {
line.forEachIndexed { index, height ->
if (index == 0 || index == line.length - 1) {
visible++
} else {
val isVisible = traverseDirectionAndCheckVisible(input, Direction.Down, index, lineNumber + 1, input[lineNumber][index].digitToInt())
|| traverseDirectionAndCheckVisible(input, Direction.Up, index, lineNumber - 1, input[lineNumber][index].digitToInt())
|| traverseDirectionAndCheckVisible(input, Direction.Left, index - 1, lineNumber, input[lineNumber][index].digitToInt())
|| traverseDirectionAndCheckVisible(input, Direction.Right, index + 1, lineNumber, input[lineNumber][index].digitToInt())
if (isVisible) {
visible++
}
}
}
}
}
println("found $visible visible trees")
return visible
}
fun part2(input: List<String>): Int {
var score = 0
input.forEachIndexed { lineNumber, line ->
line.forEachIndexed { index, height ->
val downScore = traverseDirectionAndCheckScenery(input, Direction.Down, index, lineNumber + 1, height.digitToInt())
val upScore = traverseDirectionAndCheckScenery(input, Direction.Up, index, lineNumber - 1, height.digitToInt())
val leftScore = traverseDirectionAndCheckScenery(input, Direction.Left, index - 1, lineNumber, height.digitToInt())
val rightScore = traverseDirectionAndCheckScenery(input, Direction.Right, index + 1, lineNumber, height.digitToInt())
val currentScore = downScore * upScore * leftScore * rightScore
if (currentScore > 0) {
println("checking $height @ ($index, $lineNumber), score = (up = $upScore, down = $downScore, left = $leftScore, right = $rightScore), total = $currentScore")
}
if (currentScore > score) {
score = currentScore
}
}
}
println("max score = $score")
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
// println("Part 1:")
// println(part1(input))
println("Part 2:")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 86306ee6f4e90c1cab7c2743eb437fa86d4238e5 | 4,119 | adventofcode2022 | Apache License 2.0 |
src/Day05.kt | greg-burgoon | 573,074,283 | false | {"Kotlin": 120556} | fun main() {
fun parseStacks(input: String, numberOfStacks: Int): List<ArrayDeque<Char>> {
var stacks = ArrayList<ArrayDeque<Char>>()
repeat(numberOfStacks) {
stacks.add(ArrayDeque<Char>())
}
input
.split("\n")
.map {
it.toList()
.windowed(3, 4)
.forEachIndexed { index, chars ->
val letter = chars.get(1)
if (letter != ' ' && letter.isLetter()) {
stacks.get(index).add(letter)
}
}
}
return stacks.map {
it.reverse()
it
}
}
fun parseInstructions(input: String): List<List<Int>> {
return input
.split("\n")
.map {
it.split("\\D+".toRegex())
.filter { it.isNotBlank() }
.map {
it.toInt()
}
}
}
fun part1(input: String, numberOfStacks: Int): String {
val inputs = input.split("\n\n")
val stacks = parseStacks(inputs[0], numberOfStacks)
val instructions = parseInstructions(inputs[1])
instructions.forEach {(amount, fromIndex, toIndex) ->
val fromStack = stacks[fromIndex-1]
val toStack = stacks[toIndex-1]
for (i in 1..amount) {
toStack.add(fromStack.removeLast())
}
}
return stacks.map {
it.last()
}.joinToString("")
}
fun part2(input: String, numberOfStacks: Int): String {
val inputs = input.split("\n\n")
val stacks = parseStacks(inputs[0], numberOfStacks)
val instructions = parseInstructions(inputs[1])
instructions.forEach {(amount, fromIndex, toIndex) ->
val fromStack = stacks[fromIndex-1]
val toStack = stacks[toIndex-1]
val tempStack = ArrayDeque<Char>()
for (index in fromStack.count()-1 downTo fromStack.count()-amount) {
tempStack.add(fromStack.removeAt(index))
}
toStack.addAll(tempStack.reversed())
}
return stacks.map {
it.last()
}.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
val output = part1(testInput, 3)
check(output == "CMZ")
val outputTwo = part2(testInput, 3)
check(outputTwo == "MCD")
val input = readInput("Day05")
println(part1(input, 9))
println(part2(input, 9))
}
| 0 | Kotlin | 0 | 1 | 74f10b93d3bad72fa0fc276b503bfa9f01ac0e35 | 2,703 | aoc-kotlin | Apache License 2.0 |
src/year2023/day01/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2023.day01
import arrow.core.nonEmptyListOf
import utils.ProblemPart
import utils.readInputs
import utils.runAlgorithm
fun main() {
val (realInput, testInputs) = readInputs(2023, 1, "test_input_part2")
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(142, 209),
algorithm = ::solutionPart1,
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(142, 281),
algorithm = ::solutionPart2,
),
)
}
private fun solutionPart1(input: List<String>): Long {
return input.asSequence()
.map(numberRegex::findAll)
.map { matches -> matches.map { it.value.toInt() }.toList() }
.filter { it.isNotEmpty() }
.map { "${it.first()}${it.last()}".toLong() }
.sum()
}
private val numberRegex = "\\d".toRegex()
private fun solutionPart2(input: List<String>) = input.sumOf {
val first = firstNumberDigitOrLetterRegex.find(it)?.groupValues?.get(1) ?: return@sumOf 0
val last = lastNumberDigitOrLetterRegex.find(it)?.groupValues?.get(1) ?: return@sumOf 0
"${first.toNumber()}${last.toNumber()}".toLong()
}
private val firstNumberDigitOrLetterRegex = ".*?(\\d|one|two|three|four|five|six|seven|eight|nine).*".toRegex()
private val lastNumberDigitOrLetterRegex = ".*(\\d|one|two|three|four|five|six|seven|eight|nine).*".toRegex()
private fun String.toNumber() = toIntOrNull() ?: when (this) {
"one" -> 1
"two" -> 2
"three" -> 3
"four" -> 4
"five" -> 5
"six" -> 6
"seven" -> 7
"eight" -> 8
else -> 9
}
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 1,678 | Advent-of-Code | Apache License 2.0 |
src/Day04.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} | fun main() {
fun part1(input: List<String>): Int {
var numberFullyContained = 0
input.forEach {
val strCleaning1 = it.split(",")[0]
val strCleaning2 = it.split(",")[1]
var clean1 = strCleaning1.split("-").map { it.toInt() }
var clean2 = strCleaning2.split("-").map { it.toInt() }
// swap so that clean 1 always starts with lower or equal number
if (clean2[0] < clean1[0]) {
val temp = clean1
clean1 = clean2
clean2 = temp
}
assert(clean1[0] < clean1[1])
assert(clean2[0] < clean2[1])
assert(clean1[0] <= clean2[0])
if (clean2[1] <= clean1[1]) {
numberFullyContained++
} else if (clean1[0] == clean2[0]){
numberFullyContained++
}
}
return numberFullyContained
}
fun part2(input: List<String>): Int {
var overlapping = 0
input.forEach {
val strCleaning1 = it.split(",")[0]
val strCleaning2 = it.split(",")[1]
val clean1 = strCleaning1.split("-").map { it.toInt() }
val clean2 = strCleaning2.split("-").map { it.toInt() }
val sections = mutableSetOf<Int>()
for (i in clean1[0]..clean1[1]) {
sections.add((i))
}
for (i in clean2[0]..clean2[1]) {
sections.add(i)
}
if (clean1[1] - clean1[0] + 1 + clean2[1] - clean2[0] + 1 > sections.size) {
overlapping++
}
}
println(overlapping)
return overlapping
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04-TestInput")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04-Input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 1,991 | AoC-2022-12-01 | Apache License 2.0 |
src/y2022/Day07.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2022
import util.readInput
object Day07 {
data class File(
val size: Long?,
val parent: File? = null,
val children: MutableList<File> = mutableListOf(),
val name: String
) {
fun totalSize(): Long {
if (children.size == 0) {
return size ?: 0
}
return children.sumOf { it.totalSize() }
}
}
fun part1(input: List<String>): Long {
val allDirs = dirsFromInput(input)
println("directory sizes: " + allDirs.map { it.totalSize() })
println("all directories have zero size: " + allDirs.all { it.size == null })
println("number directories: " + allDirs.size)
println("number lines starting with \"dir\": " + input.filter { it.startsWith("dir ") }.size)
return allDirs.map { it.totalSize() }.filter { it <= 100000 }.sum()
}
private fun dirsFromInput(input: List<String>): MutableList<File> {
val root = File(null, name = "")
var currentDir = root
val allDirs = mutableListOf(root)
var idx = 0
while (idx < input.size) {
when (input[idx]) {
"$ cd .." -> {
currentDir = currentDir.parent!!
idx++
}
"$ ls" -> idx = processLs(input, idx, allDirs, currentDir)
else -> { // $ cd <dir>
currentDir = currentDir.children.first { it.name == input[idx].split(" ").last() }
idx++
}
}
}
return allDirs
}
private fun processLs(input: List<String>, idx: Int, allDirs: MutableList<File>, thisDir: File): Int {
var rtnIdx = idx + 1
while (rtnIdx < input.size && input[rtnIdx][0] != '$') {
val (p1, p2) = input[rtnIdx].split(" ")
when (p1) {
"dir" -> {
val newDir = File(null, thisDir, name = p2)
allDirs.add(newDir)
thisDir.children.add(newDir)
}
else -> {
val newFile = File(p1.toLong(), name = p2)
thisDir.children.add(newFile)
}
}
rtnIdx++
}
return rtnIdx
}
fun part2(input: List<String>): Long {
val allDirs = dirsFromInput(input)
val totalMem = allDirs[0].totalSize()
val freeSpace = 70000000 - totalMem
println("free: $freeSpace")
val toFree = 30000000 - freeSpace
println("need to free $toFree")
return allDirs
.filter { it.totalSize() >= toFree }
.minBy { it.totalSize() }
.totalSize()
}
}
val testInput = """
${'$'} 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
""".trimIndent()
fun main() {
println(Day07.part1(testInput.split("\n").drop(1)))
// wrong: 1081027
val input = readInput("resources/2022/day07")
println(Day07.part1(input.drop(1)))
println(Day07.part2(input.drop(1)))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 3,350 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2023/Day16.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day16(input: List<String>) {
private val grid = input.toGrid()
private val region = grid.region()
private data class Beam(val pos: Vector2, val direction: Direction) {
private fun forward() = Beam(pos + direction.vector(), direction)
private fun left() = Beam(pos + direction.turnLeft().vector(), direction.turnLeft())
private fun right() = Beam(pos + direction.turnRight().vector(), direction.turnRight())
fun nextBeams(tile: Char?): List<Beam> = when (tile) {
'/' -> when (direction) {
Direction.NORTH, Direction.SOUTH -> listOf(right())
Direction.WEST, Direction.EAST -> listOf(left())
}
'\\' -> when (direction) {
Direction.NORTH, Direction.SOUTH -> listOf(left())
Direction.WEST, Direction.EAST -> listOf(right())
}
'|' -> when (direction) {
Direction.NORTH, Direction.SOUTH -> listOf(forward())
Direction.WEST, Direction.EAST -> listOf(left(), right())
}
'-' -> when (direction) {
Direction.NORTH, Direction.SOUTH -> listOf(left(), right())
Direction.WEST, Direction.EAST -> listOf(forward())
}
else -> listOf(forward())
}
}
private fun solve(startingBeam: Beam): Int {
var beams = setOf(startingBeam)
val energized = mutableSetOf<Beam>()
while (beams.isNotEmpty()) {
energized.addAll(beams)
beams = beams
.flatMap { beam -> beam.nextBeams(grid[beam.pos]) }
.filter { beam -> beam.pos in region && beam !in energized }
.toSet()
}
return energized.distinctBy { it.pos }.size
}
fun solvePart1() = solve(Beam(Vector2(0, 0), Direction.EAST))
fun solvePart2() = listOf(
(0 until grid.width()).map { x -> Beam(Vector2(x, 0), Direction.SOUTH) },
(0 until grid.width()).map { x -> Beam(Vector2(x, grid.height() - 1), Direction.NORTH) },
(0 until grid.height()).map { y -> Beam(Vector2(0, y), Direction.EAST) },
(0 until grid.height()).map { y -> Beam(Vector2(grid.width() - 1, y), Direction.WEST) },
)
.flatten()
.maxOf { solve(it) }
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 2,359 | advent-2023 | MIT License |
src/day25/Day25.kt | EndzeitBegins | 573,569,126 | false | {"Kotlin": 111428} | package day25
import readInput
import readTestInput
import kotlin.math.pow
private val snafuPlaceValues = mutableListOf<Long>()
private fun snafuToDecimal(snafu: String): Long {
var value = 0L
for (exponent in snafu.indices) {
val index = snafu.lastIndex - exponent
val digitValue = when(snafu[index]) {
'0' -> 0
'1' -> 1
'2' -> 2
'-' -> -1
'=' -> -2
else -> error("Unsupported digit '${snafu[index]}' for snafu format!")
}
if (snafuPlaceValues.lastIndex < exponent) {
snafuPlaceValues.add(5.0.pow(exponent).toLong())
}
value += digitValue * snafuPlaceValues[exponent]
}
return value
}
private fun decimalToSnafu(decimal: Long): String {
val quinary = decimal.toString(radix = 5)
val snafu = buildString {
var remainder: Int? = null
for (index in quinary.indices.reversed()) {
val placeValue = quinary[index].digitToInt() + (remainder ?: 0)
val digit = placeValue % 5
remainder = placeValue / 5
val snafuRepresentation = when(digit) {
0 -> "0"
1 -> "1"
2 -> "2"
3 -> "1="
4 -> "1-"
else -> error("Cannot represent $digit as snafu digit!")
}
append(snafuRepresentation.last())
if (snafuRepresentation.length > 1) {
remainder = snafuToDecimal(snafuRepresentation.dropLast(1)).toInt()
}
}
}.reversed()
return snafu
}
private fun part1(input: List<String>): String {
val fuelAmount = input
.sumOf { snafuNumber -> snafuToDecimal(snafuNumber) }
return decimalToSnafu(fuelAmount)
}
private fun part2(input: List<String>): Int {
return input.size
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day25")
check(part1(testInput) == "2=-1=0")
// check(part2(testInput) == 1)
val input = readInput("Day25")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebebdf13cfe58ae3e01c52686f2a715ace069dab | 2,187 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | brunojensen | 572,665,994 | false | {"Kotlin": 13161} | private operator fun String.component1() = this.substring(0, this.length / 2)
private operator fun String.component2() = this.substring(this.length / 2)
private fun Char.priority(): Int = when (this) {
in 'a'..'z' -> (this - 'a') + 1
in 'A'..'Z' -> (this - 'A') + 27
else -> error("out of the range: $this")
}
private fun Pair<String, String>.findDuplicatedChar(): Char {
return (this.first.toSet() intersect this.second.toSet()).first()
}
private fun Triple<String, String, String>.findDuplicatedChar(): Char {
return ((this.first.toSet() intersect this.second.toSet())
intersect (this.third.toSet())).first()
}
fun main() {
fun part1(input: List<String>): Int {
return input
.map {
val (first, second) = it
Pair(first, second).findDuplicatedChar()
}.sumOf {
it.priority()
}
}
fun part2(input: List<String>): Int {
return input
.chunked(3) {
val (first, second, third) = it
Triple(first, second, third).findDuplicatedChar()
}.sumOf {
it.priority()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03.test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2707e76f5abd96c9d59c782e7122427fc6fdaad1 | 1,335 | advent-of-code-kotlin-1 | Apache License 2.0 |
src/day05/Day05.kt | TimberBro | 567,240,136 | false | {"Kotlin": 11186} | package day05
import utils.readInput
fun main() {
val rowsMaxValue = 127
val columnMaxValue = 7
val splitRegex = "((?=([RL]){3}))"
fun binarySearchByPattern(minValue: Int = 0, maxValue: Int, patternChar: Char): Pair<Int, Int> {
var tempMax = maxValue
var tempMin = minValue
val midValue = (maxValue + minValue) / 2
when (patternChar) {
'F' -> tempMax = midValue
'L' -> tempMax = midValue
'B' -> tempMin = midValue + 1
'R' -> tempMin = midValue + 1
}
return tempMin to tempMax
}
fun countSeatID(pattern: String): Int {
val strings = pattern.split(splitRegex.toRegex())
val rowsPattern = strings[0]
val columnsPatter = strings[1]
var initColumnPair = 0 to columnMaxValue
var initRowsPair = 0 to rowsMaxValue
for (char in rowsPattern.toCharArray()) {
initRowsPair = binarySearchByPattern(initRowsPair.first, initRowsPair.second, char)
}
for (char in columnsPatter.toCharArray()) {
initColumnPair =
binarySearchByPattern(initColumnPair.first, initColumnPair.second, char)
}
return (initRowsPair.first * 8) + initColumnPair.first
}
fun part1(input: List<String>): Int {
return input.stream().map { countSeatID(it) }.toList().max()
}
fun part2(input: List<String>): Int {
val sortedSeatIDs = input.stream().map { countSeatID(it) }.sorted().toList()
val max = sortedSeatIDs[sortedSeatIDs.size - 1]
val min = sortedSeatIDs[0]
var expectedSum = 0
for (i in min..max) {
expectedSum += i
}
return expectedSum - input.stream().map { countSeatID(it) }.toList().sum()
}
val testInput = readInput("day05/day05_test")
check(part1(testInput) == 820)
val input = readInput("day05/day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1959383d2f422cc565560eefb1ed4f05bb87a386 | 1,984 | aoc2020 | Apache License 2.0 |
2021/src/main/kotlin/com/trikzon/aoc2021/Day15.kt | Trikzon | 317,622,840 | false | {"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397} | package com.trikzon.aoc2021
// Solved using Dijkstra's Shortest Path Algorithm https://www.youtube.com/watch?v=pVfj6mxhdMw
fun main() {
val input = getInputStringFromFile("/day15.txt")
benchmark(Part.One, ::day15Part1, input, 398, 5)
benchmark(Part.Two, ::day15Part2, input, 2817, 1)
}
fun day15Part1(input: String): Int {
val xLen = input.lines()[0].length
val yLen = input.lines().size
val grid = Array(xLen) { Array(yLen) { 0 } }
for (x in 0 until xLen) {
for (y in 0 until yLen) {
grid[x][y] = input.lines()[y][x].digitToInt()
}
}
val visited = Array(xLen) { Array(yLen) { false } }
val distancesFromStart = Array(xLen) { Array(yLen) { Int.MAX_VALUE} }
val prevVertex = Array(xLen) { Array<Pair<Int, Int>?>(yLen) { null } }
distancesFromStart[0][0] = 0
var vertex = Pair(0, 0)
// While a vertex hasn't been visited:
while (visited.map { v -> v.count { r -> !r } }.count { i -> i > 0 } > 0) {
for (neighbor in getNeighbors(vertex.first, vertex.second, xLen, yLen)) {
if (visited[neighbor.first][neighbor.second]) continue
val newDistance = distancesFromStart[vertex.first][vertex.second] + grid[neighbor.first][neighbor.second]
if (distancesFromStart[neighbor.first][neighbor.second] > newDistance) {
prevVertex[neighbor.first][neighbor.second] = vertex
distancesFromStart[neighbor.first][neighbor.second] = newDistance
}
}
visited[vertex.first][vertex.second] = true
var newVertex = Pair(0, 0)
var newVertexDistance = Int.MAX_VALUE
for (x in 0 until xLen) {
for (y in 0 until yLen) {
if (!visited[x][y]) {
val distanceFromStart = distancesFromStart[x][y]
if (distanceFromStart < newVertexDistance) {
newVertex = Pair(x, y)
newVertexDistance = distanceFromStart
}
}
}
}
vertex = newVertex
}
return distancesFromStart[xLen - 1][yLen - 1]
}
fun getNeighbors(x: Int, y: Int, xLen: Int, yLen: Int): List<Pair<Int, Int>> {
val list = ArrayList<Pair<Int, Int>>()
if (x > 0) list.add(Pair(x - 1, y))
if (y > 0) list.add(Pair(x, y - 1))
if (x < xLen - 1) list.add(Pair(x + 1, y))
if (y < yLen - 1) list.add(Pair(x, y + 1))
return list
}
fun day15Part2(input: String): Int {
var xLen = input.lines()[0].length
var yLen = input.lines().size
val smallGrid = Array(xLen) { Array(yLen) { 0 } }
for (x in 0 until xLen) {
for (y in 0 until yLen) {
smallGrid[x][y] = input.lines()[y][x].digitToInt()
}
}
val grid = Array(xLen * 5) { Array(yLen * 5) { 0 } }
for (chunkX in 0 until 5) {
for (chunkY in 0 until 5) {
for (x in 0 until xLen) {
for (y in 0 until yLen) {
var newRisk = smallGrid[x][y] + (chunkX + chunkY)
if (newRisk > 9) newRisk -= 9
grid[x + (xLen * chunkX)][y + (yLen * chunkY)] = newRisk
}
}
}
}
xLen *= 5
yLen *= 5
val visited = Array(xLen) { Array(yLen) { false } }
val distancesFromStart = Array(xLen) { Array(yLen) { Int.MAX_VALUE} }
val prevVertex = Array(xLen) { Array<Pair<Int, Int>?>(yLen) { null } }
distancesFromStart[0][0] = 0
var vertex = Pair(0, 0)
// While a vertex hasn't been visited:
while (visited.map { v -> v.count { r -> !r } }.count { i -> i > 0 } > 0) {
for (neighbor in getNeighbors(vertex.first, vertex.second, xLen, yLen)) {
if (visited[neighbor.first][neighbor.second]) continue
val newDistance = distancesFromStart[vertex.first][vertex.second] + grid[neighbor.first][neighbor.second]
if (distancesFromStart[neighbor.first][neighbor.second] > newDistance) {
prevVertex[neighbor.first][neighbor.second] = vertex
distancesFromStart[neighbor.first][neighbor.second] = newDistance
}
}
visited[vertex.first][vertex.second] = true
// TODO: Look into using a priority queue instead of this...
var newVertex = Pair(0, 0)
var newVertexDistance = Int.MAX_VALUE
for (x in 0 until xLen) {
for (y in 0 until yLen) {
if (!visited[x][y]) {
val distanceFromStart = distancesFromStart[x][y]
if (distanceFromStart < newVertexDistance) {
newVertex = Pair(x, y)
newVertexDistance = distanceFromStart
}
}
}
}
vertex = newVertex
}
return distancesFromStart[xLen - 1][yLen - 1]
}
| 0 | Kotlin | 1 | 0 | d4dea9f0c1b56dc698b716bb03fc2ad62619ca08 | 4,885 | advent-of-code | MIT License |
src/main/kotlin/day3.kt | nerok | 436,232,451 | false | {"Kotlin": 32118} | import java.io.File
fun main(args: Array<String>) {
day3part2()
}
fun day3part1() {
val countArray = IntArray(12) { 0 }
val input = File("day3input.txt").bufferedReader().readLines()
input.map { it.mapIndexed { index, value ->
if (value == '1') {
countArray[index] = (countArray[index] + 1)
}
else {
countArray[index] = (countArray[index] - 1)
}
}
}
countArray.forEach { print(if (it > 0) "1" else "0") }
}
fun day3part2() {
val input = File("day3input.txt")
.bufferedReader()
.readLines()
.map { line ->
line.split("")
.filter {
it.isNotEmpty()
}
.map { it.toInt() }
}
val majority = getMajority(input, 0)
val highset = input.filter { it[0] == majority }
val lowset = input.filter { it[0] != majority }
val oxygenRating = higherReduction(highset)
val CO2Rating = smallerReduction(lowset)
val oxygenRatingDecimal = Integer.parseInt(oxygenRating.joinToString(separator = "") { it.toString() }, 2)
val CO2RatingDecimal = Integer.parseInt(CO2Rating.joinToString(separator = "") { it.toString() }, 2)
println(oxygenRatingDecimal)
println(CO2RatingDecimal)
println("${oxygenRatingDecimal*CO2RatingDecimal}")
}
private fun getMajority(input: List<List<Int>>, index: Int): Int {
return input.map { it[index] }.let {
if (it.sum()*2 == it.size) {
1
}
else if (it.sum() == 2 && it.size == 3) {
1
}
else if (it.sum() > it.size / 2) 1 else 0
}
}
fun higherReduction(set: List<List<Int>>): List<Int> {
var reductionSet = set
var index = 1
while (reductionSet.size > 1) {
val majority = getMajority(reductionSet, index)
reductionSet = reductionSet.filter { it[index] == majority }
index += 1
}
return reductionSet.first()
}
fun smallerReduction(set: List<List<Int>>): List<Int> {
var reductionSet = set
var index = 1
while (reductionSet.size > 1) {
val majority = getMajority(reductionSet, index)
reductionSet = reductionSet.filter { it[index] != majority }
index += 1
}
return reductionSet.first()
}
| 0 | Kotlin | 0 | 0 | 4dee925c0f003fdeca6c6f17c9875dbc42106e1b | 2,297 | Advent-of-code-2021 | MIT License |
src/Day02.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} | fun scoreDraw(a: String): Int = when (a) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
fun scoreWin(a: String, b: String): Int {
return when {
a == "A" && b == "X" -> 3
a == "A" && b == "Y" -> 6
a == "A" && b == "Z" -> 0
a == "B" && b == "X" -> 0
a == "B" && b == "Y" -> 3
a == "B" && b == "Z" -> 6
a == "C" && b == "X" -> 6
a == "C" && b == "Y" -> 0
a == "C" && b == "Z" -> 3
else -> -100
}
}
fun main() {
fun part1(input: List<String>): Int {
var score = 0
input.forEach {
val arr = it.split(" ")
if (arr.size > 1) {
score += scoreDraw(arr[1]) + scoreWin(arr[0], arr[1])
}
}
return score
}
fun derivedOwnScore(a: String, result: String): Int {
// depending on other player and result, we calculate own score for hand
return when {
a == "A" && result == "X" -> 3 // has rock, I lose, I have scissors, I get 3
a == "B" && result == "X" -> 1 // has paper, I lose, I have rock, I get 1
a == "C" && result == "X" -> 2 // has scissors, I lose, I have paper, I get 2
a == "A" && result == "Y" -> 1 // has rock, draw, I have rock, I get 1
a == "B" && result == "Y" -> 2 // has paper, draw, I have paper, I get 2
a == "C" && result == "Y" -> 3 // has scissors, draw, I have scissory, I get 3
a == "A" && result == "Z" -> 2 // has rock, I win, I have paper, I get 2
a == "B" && result == "Z" -> 3 // has paper, I win, I have scissors, I get 3
a == "C" && result == "Z" -> 1 // has scissors, I win, I have rock, I get 1
else -> -100
}
}
fun winningScore(a: String) = when (a) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> -100
}
fun part2(input: List<String>): Int {
var score = 0
input.forEach {
val arr = it.split(" ")
if (arr.size > 1) {
score += derivedOwnScore(arr[0], arr[1]) + winningScore(arr[1])
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02-TestInput")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02-Input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 2,474 | AoC-2022-12-01 | Apache License 2.0 |
src/Day14.kt | fouksf | 572,530,146 | false | {"Kotlin": 43124} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun parseTuple(tuple: List<List<Int>>, result: HashMap<Pair<Int, Int>, String>) {
val x1 = tuple[0][0]
val x2 = tuple[1][0]
val y1 = tuple[0][1]
val y2 = tuple[1][1]
for (i in min(x1, x2)..max(x1, x2)) {
for (j in min(y1, y2)..max(y1, y2)) {
result[Pair(i, j)] = "#"
}
}
}
fun parseLine(line: String, result: HashMap<Pair<Int, Int>, String>) {
line.split(" -> ").windowed(2, 1).toList()
.forEach { parseTuple(it.map { it.split(",").map { it.toInt() } }, result) }
}
fun parseInput(input: List<String>): HashMap<Pair<Int, Int>, String> {
val result = HashMap<Pair<Int, Int>, String>()
input.forEach { parseLine(it, result) }
return result
}
fun releaseSand(map: HashMap<Pair<Int, Int>, String>): Pair<Int, Int>? {
var sand = Pair(500, 0)
val lowestPoint = map.keys.map { it.second }.max()
while (lowestPoint >= sand.second) {
val bellowSand = Pair(sand.first, sand.second + 1)
if (map.contains(bellowSand)) {
val diagonallyLeftBellowSand = Pair(sand.first - 1, sand.second + 1)
if (map.contains(diagonallyLeftBellowSand)) {
val diagonallyRightBellowSand = Pair(sand.first + 1, sand.second + 1)
if (map.contains(diagonallyRightBellowSand)) {
map[sand] = "o"
return sand
} else {
sand = diagonallyRightBellowSand
}
} else {
sand = diagonallyLeftBellowSand
}
} else {
sand = bellowSand
}
}
return null
}
fun releaseSandWithFloor(map: HashMap<Pair<Int, Int>, String>, floor: Int): Pair<Int, Int> {
var sand = Pair(500, 0)
while (floor > sand.second + 1) {
val bellowSand = Pair(sand.first, sand.second + 1)
if (map.contains(bellowSand)) {
val diagonallyLeftBellowSand = Pair(sand.first - 1, sand.second + 1)
if (map.contains(diagonallyLeftBellowSand)) {
val diagonallyRightBellowSand = Pair(sand.first + 1, sand.second + 1)
if (map.contains(diagonallyRightBellowSand)) {
map[sand] = "o"
return sand
} else {
sand = diagonallyRightBellowSand
}
} else {
sand = diagonallyLeftBellowSand
}
} else {
sand = bellowSand
}
}
map[sand] = "o"
return sand
}
fun printMap(map: HashMap<Pair<Int, Int>, String>) {
val minx = map.keys.map { it.first }.min()
val maxx = map.keys.map { it.first }.max()
val miny = map.keys.map { it.second }.min()
val maxy = map.keys.map { it.second }.max()
println("$minx - $maxx; $miny - $maxy")
for (i in minx..maxx) {
print(if (i == 500) "+" else ".")
}
println()
for (j in miny..maxy) {
print(j)
for (i in minx..maxx) {
print(map.getOrDefault(Pair(i, j), "."))
}
println()
}
}
fun part1(map: HashMap<Pair<Int, Int>, String>): Int {
var counter = 0
while (releaseSand(map) != null) {
counter++
}
return counter
}
fun part2(map: HashMap<Pair<Int, Int>, String>): Int {
val floor = map.keys.map { it.second }.max() + 2
var counter = 0
while (releaseSandWithFloor(map, floor) != Pair(500, 0)) {
counter++
}
return counter
}
// test if implementation meets criteria from the description, like:
val testInput = parseInput(readInput("Day14_test"))
// printMap(testInput)
// println(part1(testInput))
println(part2(testInput))
val input = parseInput(readInput("Day14"))
// printMap(input)
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 701bae4d350353e2c49845adcd5087f8f5409307 | 4,271 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2021/day17/day17.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2021.day17
import biz.koziolek.adventofcode.*
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
val inputFile = findInput(object {})
val line = inputFile.bufferedReader().readLine()
val targetArea = parseTargetArea(line)
val (bestVelocity, maxHeight) = findVelocityWithMostStyle(targetArea)
println("Best velocity is: $bestVelocity that gives max height: $maxHeight")
val allVelocitiesThatHitTarget = findAllVelocitiesThatHitTarget(targetArea)
println("There is ${allVelocitiesThatHitTarget.size} velocities that hit target")
}
fun parseTargetArea(line: String): Pair<Coord, Coord> =
Regex("target area: x=(-?[0-9]+)\\.\\.(-?[0-9]+), y=(-?[0-9]+)\\.\\.(-?[0-9]+)")
.find(line)
?.let {
val x1 = it.groupValues[1].toInt()
val x2 = it.groupValues[2].toInt()
val y1 = it.groupValues[3].toInt()
val y2 = it.groupValues[4].toInt()
Coord(min(x1, x2), max(y1, y2)) to Coord(max(x1, x2), min(y1, y2))
}
?: throw IllegalArgumentException("Could not parse target area: $line")
fun findVelocityWithMostStyle(targetArea: Pair<Coord, Coord>): Pair<Coord, Int> =
generateVelocities(0, targetArea.second.x, 0, abs(targetArea.second.y))
.map { velocity -> velocity to calculateTrajectory(velocity, targetArea) }
.filter { (_, trajectory) -> trajectory.last() in targetArea }
.map { (velocity, trajectory) -> velocity to trajectory.maxOf { it.y } }
.sortedByDescending { (_, maxHeight) -> maxHeight }
.first()
fun findAllVelocitiesThatHitTarget(targetArea: Pair<Coord, Coord>): Set<Coord> =
generateVelocities(0, targetArea.second.x, targetArea.second.y, abs(targetArea.second.y))
.map { velocity -> velocity to calculateTrajectory(velocity, targetArea) }
.filter { (_, trajectory) -> trajectory.last() in targetArea }
.map { (velocity, _) -> velocity }
.toSet()
private fun generateVelocities(minX: Int, maxX: Int, minY: Int, maxY: Int): Sequence<Coord> =
sequence {
for (x in minX..maxX) {
for (y in minY..maxY) {
yield(Coord(x, y))
}
}
}
fun calculateTrajectory(velocity: Coord, targetArea: Pair<Coord, Coord>, limit: Int = 1_000_000): List<Coord> =
generateSequence(Triple(Coord(0, 0), velocity, 0)) { (coord, velocity, iteration) ->
if (iteration > limit) {
throw IllegalStateException("Trajectory calculation interrupted by limit")
} else if (coord in targetArea) {
null
} else {
val newCoord = coord + velocity
val newVelocity = Coord(
x = when {
velocity.x > 0 -> velocity.x - 1
velocity.x < 0 -> velocity.x + 1
else -> velocity.x
},
y = velocity.y - 1
)
if (velocity.y < 0 && newCoord.y < targetArea.second.y
|| velocity.x > 0 && newCoord.x > targetArea.second.x) {
null
} else {
Triple(newCoord, newVelocity, iteration + 1)
}
}
}
.map { it.first }
.toList()
fun visualizeTrajectory(trajectory: List<Coord>, targetArea: Pair<Coord, Coord>): String =
buildString {
val allX = trajectory.map { it.x }.plus(targetArea.first.x).plus(targetArea.second.x)
val allY = trajectory.map { it.y }.plus(targetArea.first.y).plus(targetArea.second.y)
val minX = allX.minOrNull() ?: 0
val maxX = allX.maxOrNull() ?: 0
val minY = allY.minOrNull() ?: 0
val maxY = allY.maxOrNull() ?: 0
for (y in maxY downTo minY) {
for (x in minX..maxX) {
val coord = Coord(x, y)
val trajectoryIndex = trajectory.indexOf(coord)
if (trajectoryIndex == 0) {
append('S')
} else if (trajectoryIndex > 0) {
append('#')
} else if (coord in targetArea) {
append('T')
} else {
append('.')
}
}
if (y != minY) {
append('\n')
}
}
}
private operator fun Pair<Coord, Coord>.contains(coord: Coord): Boolean {
val minX = min(first.x, second.x)
val maxX = max(first.x, second.x)
val minY = min(first.y, second.y)
val maxY = max(first.y, second.y)
return coord.x in minX..maxX && coord.y in minY..maxY
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 4,679 | advent-of-code | MIT License |
src/Day05.kt | binaryannie | 573,120,071 | false | {"Kotlin": 10437} | private const val DAY = "05"
private const val PART_1_CHECK = "CMZ"
private const val PART_2_CHECK = "MCD"
fun inputToColumns(input: List<String>): MutableList<MutableList<String>> {
val separatorIndex = input.indexOf("")
val numberOfColumns = input[separatorIndex - 1].chunked(4).size
val boat = input
.slice(0 until separatorIndex - 1)
.map { it.chunked(4).map { box -> box.replace("\\W".toRegex(), "") } }
val flipped = Array(numberOfColumns) { Array<String>(boat.size) { "" } }
boat.reversed().forEachIndexed { row, strings -> strings.forEachIndexed { column, s -> flipped[column][row] = s } }
return flipped.map { row -> row.map { t -> t }.filterNot { it.isBlank() }.toMutableList() }.toMutableList()
}
fun inputToMoves(input: List<String>):
List<List<Int>> {
val separatorIndex = input.indexOf("")
return input
.slice(separatorIndex + 1 until input.size)
.map {
val matches = Regex("move (\\d+) from (\\d+) to (\\d+)").find(it)!!
val (i, amount, from, to) = matches.groupValues
listOf(amount.toInt(), from.toInt() - 1, to.toInt() - 1)
}
}
fun main() {
fun part1(input: List<String>): String {
val columns = inputToColumns(input)
val moves = inputToMoves(input)
moves.forEach { move ->
for (i in 1..move[0]) {
val block = columns[move[1]].removeLast()
columns[move[2]].add(block)
}
}
return columns.joinToString("") { it.last() }
}
fun part2(input: List<String>): String {
val columns = inputToColumns(input)
val moves = inputToMoves(input)
moves.forEach { move ->
val stack = columns[move[1]].takeLast(move[0])
repeat(move[0]){columns[move[1]].removeLastOrNull()}
columns[move[2]].addAll(stack)
}
return columns.joinToString("") { it.last() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${DAY}_test")
check(part1(testInput).also { println("Part 1 check: $it") } == PART_1_CHECK)
check(part2(testInput).also { println("Part 2 check: $it") } == PART_2_CHECK)
val input = readInput("Day${DAY}")
println("Part 1 solution: ${part1(input)}")
println("Part 2 solution: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | 511fc33f9dded71937b6bfb55a675beace84ca22 | 2,390 | advent-of-code-2022 | Apache License 2.0 |
src/day03/Day03.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day03
import java.io.File
fun main() {
val data = parse("src/day03/Day03.txt")
println("🎄 Day 03 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data)}")
println()
println("[Part 2]")
println("Answer: ${part2(data)}")
}
private data class Part(
val rx: IntRange,
val ry: IntRange,
val value: Int,
)
private data class Symbol(
val x: Int,
val y: Int,
val value: Char,
)
private data class Schematic(
val parts: List<Part>,
val symbols: List<Symbol>,
)
private val PATTERN = """(\d+)|[^.]""".toRegex()
private fun parse(path: String): Schematic {
val parts = mutableListOf<Part>()
val symbols = mutableListOf<Symbol>()
val data = File(path).readLines()
for ((y, line) in data.withIndex()) {
val (matchedParts, matchedSymbols) = PATTERN.findAll(line)
.partition { it.value[0].isDigit() }
parts.addAll(matchedParts.map {
val a = it.range.first
val b = it.range.last
val rx = (a - 1)..(b + 1)
val ry = (y - 1)..(y + 1)
Part(rx, ry, it.value.toInt())
})
symbols.addAll(matchedSymbols.map {
Symbol(x = it.range.first, y, it.value[0])
})
}
return Schematic(parts, symbols)
}
private fun part1(data: Schematic): Int {
val (parts, symbols) = data
return parts.sumOf { (rx, ry, value) ->
if (symbols.any { (sx, sy) -> (sx in rx) && (sy in ry) }) {
value
} else {
0
}
}
}
private fun part2(data: Schematic): Int {
val (parts, symbols) = data
val gears = symbols.filter { it.value == '*' }
return gears.sumOf { (sx, sy) ->
val adjacentNumbers = parts.mapNotNull { (rx, ry, value) ->
if ((sx in rx) && (sy in ry)) value else null
}
if (adjacentNumbers.count() == 2) {
adjacentNumbers.reduce(Int::times)
} else {
0
}
}
}
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 2,108 | advent-of-code-2023 | MIT License |
src/main/kotlin/aoc2022/Day02.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
enum class Action(val score : Int) { ROCK(1), PAPER(2), SCISSORS(3) }
private val parseLine = "(\\w) (\\w)".toRegex()
typealias Play = Pair<Action, Action>
fun main() {
val testInput = """A Y
B X
C Z""".split("\n")
fun Char.toAction() = when (this) {
'A','X' -> Action.ROCK
'B','Y' -> Action.PAPER
'C','Z' -> Action.SCISSORS
else -> throw IllegalArgumentException("Unexpected char $this")
}
fun Action.beats(): Action =
when (this) {
Action.ROCK -> Action.SCISSORS
Action.PAPER -> Action.ROCK
Action.SCISSORS -> Action.PAPER
}
fun Action.beatenBy(): Action =
when (this) {
Action.ROCK -> Action.PAPER
Action.PAPER -> Action.SCISSORS
Action.SCISSORS -> Action.ROCK
}
fun Action.beats(other: Action): Boolean = beats() == other
fun scoreFight(opp: Action, my: Action): Int {
if (opp == my) return 3
if (my.beats(opp)) return 6
return 0
}
fun scorePlay(their: Action, my: Action) = scoreFight(their, my) + my.score
fun <T> List<T>.toPair() = Pair(this[0], this[1])
fun Play.score() = scorePlay(first, second)
fun parseLines(input: List<String>) = input.parsedBy(parseLine).map { match -> match.destructured.toList().map { it[0]}.toPair() }
fun part1(input: List<String>): Int {
return parseLines(input).map {
Play(it.first.toAction(), it.second.toAction())
}.map(Play::score).sum()
}
fun part2(input: List<String>): Int {
return parseLines(input).map { line ->
val theirAction = line.first.toAction()
val myAction = when (line.second) {
'X' -> theirAction.beats()
'Y' -> theirAction
else -> theirAction.beatenBy()
}
Play(theirAction, myAction)
}.map(Play::score).sum()
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 15)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 2)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 2,308 | aoc-2022-kotlin | Apache License 2.0 |
src/Day08.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 2
private const val EXPECTED_2 = 6L
private class Day08(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
val lines = readAsLines()
val instructions = lines[0].trim()
val edges = mutableMapOf<String, MutableList<String>>()
for (edge in lines.drop(2)) {
val parts = edge.replace("(", "").replace(")", "").split("=").flatMap { it.trim().split(",")}.map { it.trim() }
check(parts.size == 3) { "Invalid edge: $edge, $parts" }
edges.put(parts[0], mutableListOf(parts[1], parts[2]))
}
var step = 0
var pos = "AAA"
while (pos != "ZZZ") {
println(pos)
val next = instructions[step % instructions.length]
if (next == 'L') {
pos = edges[pos]!![0]
} else {
pos = edges[pos]!![1]
}
step++
}
return step
}
fun part2(): Any {
val lines = readAsLines()
val instructions = lines[0].trim()
val edges = mutableMapOf<String, MutableList<String>>()
for (edge in lines.drop(2)) {
val parts = edge.replace("(", "").replace(")", "").split("=").flatMap { it.trim().split(",")}.map { it.trim() }
check(parts.size == 3) { "Invalid edge: $edge, $parts" }
edges.put(parts[0], mutableListOf(parts[1], parts[2]))
}
var result = 1L
for (p in edges.keys.filter { it.endsWith("A") } ) {
var pos = p
var step = 0
var instructIndex = 0
val seen = mutableMapOf<Pair<String, Int>, Int>()
var cycle = 0 to 0
do {
seen[pos to instructIndex] = step
val next = instructions[instructIndex]
pos = if (next == 'L') {
edges[pos]!![0]
} else {
edges[pos]!![1]
}
step++
instructIndex = step % instructions.length
if (pos.endsWith("Z") && seen.containsKey(pos to instructIndex)) {
val firstStep = seen[pos to instructIndex]!!
cycle = firstStep to (step - firstStep)
break
}
} while (step < 5000000)
println("$p $cycle $step")
val mul = cycle.first
result = result * mul / gcd(result, (mul).toLong())
}
return result
}
}
fun main() {
val testInstance = Day08(true)
val instance = Day08(false)
// testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
// println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 2,904 | advent-of-code-2022 | Apache License 2.0 |
2021/src/main/kotlin/day14_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.mapItems
import utils.withLCounts
fun main() {
Day14Imp.run()
}
object Day14Imp : Solution<Pair<Day14Imp.Polymer, List<Pair<String, String>>>>() {
override val name = "day14"
override val parser = Parser { input ->
val (polymer, ruleLines) = input.split("\n\n")
return@Parser Polymer(polymer) to Parser.lines.mapItems {
val (from, replacement) = it.split(" -> ")
from to replacement
}(ruleLines)
}
data class Polymer(val pairs: Map<String, Long>, val chars: Map<String, Long>) {
constructor(input: String) : this(
input.windowed(2).withLCounts(),
input.windowed(1).withLCounts()
)
}
private fun solve(steps: Int, input: Pair<Polymer, List<Pair<String, String>>>): Long {
val pairs = input.first.pairs.toMutableMap().withDefault { 0L }
val chars = input.first.chars.toMutableMap().withDefault { 0L }
repeat(times = steps) {
val pairDeltas = mutableMapOf<String, Long>().withDefault { 0L }
val charDeltas = mutableMapOf<String, Long>().withDefault { 0L }
for ((pair, char) in input.second) {
val count = pairs.getValue(pair)
if (count == 0L) continue
pairDeltas[pair] = pairDeltas.getValue(pair) - count
pairDeltas[pair.first() + char] = pairDeltas.getValue(pair.first() + char) + count
pairDeltas[char + pair.last()] = pairDeltas.getValue(char + pair.last()) + count
charDeltas[char] = charDeltas.getValue(char) + count
}
pairDeltas.forEach { (k, v) -> pairs[k] = pairs.getValue(k) + v }
charDeltas.forEach { (k, v) -> chars[k] = chars.getValue(k) + v }
}
return chars.values.maxOrNull()!! - chars.values.minOrNull()!!
}
override fun part1(input: Pair<Polymer, List<Pair<String, String>>>): Long {
return solve(10, input)
}
override fun part2(input: Pair<Polymer, List<Pair<String, String>>>): Long {
return solve(40, input)
}
} | 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,972 | aoc_kotlin | MIT License |
calendar/day02/Day2.kt | polarene | 572,886,399 | false | {"Kotlin": 17947} | package day02
import Day
import Lines
class Day2 : Day() {
override fun part1(input: Lines): Any {
return Game().run {
input.forEach { play(it.toHandRound()) }
total()
}
}
override fun part2(input: Lines): Any {
return Game().run {
input.forEach { play(it.toStrategyRound()) }
total()
}
}
}
class Game() {
private val points = mutableListOf<Int>()
fun play(round: Round) {
points += round.points()
}
fun total(): Int {
println(points)
return points.sum()
}
}
interface Round {
fun points(): Int
}
const val LOST = 0
const val DRAW = 3
const val WON = 6
/*
rock A X
paper B Y
scissors C Z
*/
// Rock (A) defeats Scissors (Z), Scissors (C) defeats Paper (Y), and Paper (B) defeats Rock (X)
val defeats = mapOf(
// opponent vs me
'A' to 'Z',
'C' to 'Y',
'B' to 'X',
)
const val ROCK = 1
const val PAPER = 2
const val SCISSORS = 3
val handPoints = mapOf(
'X' to ROCK,
'Y' to PAPER,
'Z' to SCISSORS,
)
class HandRound(val opponent: Char, val me: Char) : Round {
override fun points(): Int = (opponent against me) + handPoints[me]!!
private infix fun Char.against(me: Char) = when {
me == this.plus(23) -> DRAW
me != defeats[this] -> WON
else -> LOST
}
}
fun String.toHandRound() =
split(' ').let { HandRound(opponent = it[0][0], me = it[1][0]) }
// ------------------------part 2---------------------------------------
// Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock
const val DEFEATS_RULE = "ACB"
const val DEFEATED_RULE = "CAB"
val handPoints2 = mapOf(
'A' to ROCK,
'B' to PAPER,
'C' to SCISSORS,
)
val strategyPoints = mapOf(
'X' to LOST,
'Y' to DRAW,
'Z' to WON,
)
class StrategyRound(val opponent: Char, val strategy: Char) : Round {
override fun points(): Int = handPoints2[strategy selectMove opponent]!! + strategyPoints[strategy]!!
private infix fun Char.selectMove(opponent: Char) = when (this) {
'X' -> DEFEATS_RULE[(DEFEATS_RULE.indexOf(opponent) + 1) % 3]
'Z' -> DEFEATED_RULE[(DEFEATED_RULE.indexOf(opponent) + 1) % 3]
else -> opponent
}
}
fun String.toStrategyRound() =
split(' ').let { StrategyRound(opponent = it[0][0], strategy = it[1][0]) }
| 0 | Kotlin | 0 | 0 | 0b2c769174601b185227efbd5c0d47f3f78e95e7 | 2,385 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2023/Day22.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day22(input: List<String>) {
private val bricks = input
.flatMap { it.split("~") }
.map { it.split(",").map { it.toInt() } }
.map { Vector3(it[0], it[1], it[2]) }
.chunked(2)
.map { (start, end) -> Cuboid(start, end) }
.let { makeThemFall(it).first }
private fun isSupporting(bottom: Cuboid, top: Cuboid) = bottom.end.z + 1 == top.start.z && bottom.shift(z = 1).intersects(top)
private fun supportsOtherBricks(brick: Cuboid) = bricks
.filter { isSupporting(brick, it) }
.any { supported -> bricks.count { isSupporting(it, supported) } == 1 }
private fun makeThemFall(bricks: List<Cuboid>): Pair<List<Cuboid>, Int> {
val next = mutableListOf<Cuboid>()
val settled = mutableMapOf<Int, MutableSet<Cuboid>>()
var moved = 0
fun hasSettled(brick: Cuboid) = brick.start.z == 1 || settled[brick.start.z - 1]?.any { other -> isSupporting(other, brick) } ?: false
for (brick in bricks.sortedBy { it.start.z }) {
var b = brick
while (!hasSettled(b)) {
b = b.shift(z = -1)
}
next.add(b)
settled[b.end.z]?.add(b) ?: settled.put(b.end.z, mutableSetOf(b))
if (b != brick) moved++
}
return Pair(next, moved)
}
fun solvePart1() = bricks.count { !supportsOtherBricks(it) }
fun solvePart2() = bricks.filter { supportsOtherBricks(it) }.sumOf { supportingBrick ->
makeThemFall(bricks.filter { it != supportingBrick }).second
}
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 1,605 | advent-2023 | MIT License |
src/Day14.kt | rbraeunlich | 573,282,138 | false | {"Kotlin": 63724} | fun main() {
fun parseLine(line: String): RockLines {
val map = line.split(" -> ")
.map { pair ->
val split = pair.split(",")
split[0].toInt() to split[1].toInt()
}
return RockLines(map)
}
fun part1(input: List<String>): Int {
val allRockLines = input.map { line ->
parseLine(line)
}
val minX = allRockLines.minOf { line -> line.fromTo.minOf { it.first } }
val minY = allRockLines.minOf { line -> line.fromTo.minOf { it.second } }
val maxX = allRockLines.maxOf { line -> line.fromTo.maxOf { it.first } }
val maxY = allRockLines.maxOf { line -> line.fromTo.maxOf { it.second } }
val cave = Cave(minX, minY, maxX, maxY)
allRockLines.forEach { cave.applyRockLine(it) }
var sandFellOff = false
while (!sandFellOff) {
sandFellOff = cave.applySand()
}
return cave.sandCounter
}
fun part2(input: List<String>): Int {
val allRockLines = input.map { line ->
parseLine(line)
}
val minX = allRockLines.minOf { line -> line.fromTo.minOf { it.first } }
val minY = allRockLines.minOf { line -> line.fromTo.minOf { it.second } }
val maxX = allRockLines.maxOf { line -> line.fromTo.maxOf { it.first } } + 300
val maxY = allRockLines.maxOf { line -> line.fromTo.maxOf { it.second } } + 2
val cave = Cave(minX, minY, maxX, maxY)
allRockLines.forEach { cave.applyRockLine(it) }
cave.applyRockLine(RockLines(listOf(0 to maxY, maxX to maxY)))
var topReached = false
while (!topReached) {
topReached = cave.applySandUntilTopReached()
}
return cave.sandCounter +1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
// check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
data class RockLines(val fromTo: List<Pair<Int, Int>>)
data class Cave(
val minX: Int,
val minY: Int,
val maxX: Int,
val maxY: Int,
val caveContent: MutableList<MutableList<String>> = MutableList(maxY + 1) {
MutableList(maxX + 1) { _ -> "." }
},
var sandCounter: Int = 0
) {
fun applyRockLine(rockLines: RockLines) {
var startingPoint = rockLines.fromTo.first()
for (point in rockLines.fromTo.drop(1)) {
if (startingPoint.first == point.first) {
addVerticalRock(startingPoint, point)
} else {
addHorizontalRock(startingPoint, point)
}
startingPoint = point
}
}
private fun addVerticalRock(from: Pair<Int, Int>, to: Pair<Int, Int>) {
val start = minOf(from.second, to.second)
val end = maxOf(from.second, to.second)
(start..end).forEach { y ->
caveContent[y][from.first] = "#"
}
}
private fun addHorizontalRock(from: Pair<Int, Int>, to: Pair<Int, Int>) {
val start = minOf(from.first, to.first)
val end = maxOf(from.first, to.first)
(start..end).forEach { x ->
caveContent[from.second][x] = "#"
}
}
private fun canSandMoveDown(currentSandPosition: Pair<Int, Int>): Boolean {
val newPosition = currentSandPosition.first to currentSandPosition.second + 1
val positionContent = caveContent.getOrNull(newPosition.second)?.getOrNull(newPosition.first)
return positionContent?.let { it == "." } ?: true
}
private fun canSandMoveDownAndLeft(currentSandPosition: Pair<Int, Int>): Boolean {
val newPosition = currentSandPosition.first - 1 to currentSandPosition.second + 1
val positionContent = caveContent.getOrNull(newPosition.second)?.getOrNull(newPosition.first)
return positionContent?.let { it == "." } ?: true
}
private fun canSandMoveDownAndRight(currentSandPosition: Pair<Int, Int>): Boolean {
val newPosition = currentSandPosition.first + 1 to currentSandPosition.second + 1
val positionContent = caveContent.getOrNull(newPosition.second)?.getOrNull(newPosition.first)
return positionContent?.let { it == "." } ?: true
}
private fun isSandOffBounds(currentSandPosition: Pair<Int, Int>): Boolean {
return currentSandPosition.first > maxX || currentSandPosition.second > maxY
}
fun applySand(): Boolean {
// The sand is pouring into the cave from point 500,0.
var currentSandPosition = 500 to 0
while (true) {
if(isSandOffBounds(currentSandPosition)) {
return true
}
else if (canSandMoveDown(currentSandPosition)) {
currentSandPosition = currentSandPosition.first to currentSandPosition.second + 1
} else if (canSandMoveDownAndLeft(currentSandPosition)) {
currentSandPosition = currentSandPosition.first - 1 to currentSandPosition.second + 1
} else if (canSandMoveDownAndRight(currentSandPosition)) {
currentSandPosition = currentSandPosition.first + 1 to currentSandPosition.second + 1
} else {
// sand comes to rest
caveContent[currentSandPosition.second][currentSandPosition.first] = "o"
sandCounter++
return false
}
}
}
fun applySandUntilTopReached(): Boolean {
var iteration = 0
// The sand is pouring into the cave from point 500,0.
var currentSandPosition = 500 to 0
while (true) {
iteration++
if(iteration % 50 == 0) {
printContents()
}
if (canSandMoveDown(currentSandPosition)) {
currentSandPosition = currentSandPosition.first to currentSandPosition.second + 1
} else if (canSandMoveDownAndLeft(currentSandPosition)) {
currentSandPosition = currentSandPosition.first - 1 to currentSandPosition.second + 1
} else if (canSandMoveDownAndRight(currentSandPosition)) {
currentSandPosition = currentSandPosition.first + 1 to currentSandPosition.second + 1
} else if(currentSandPosition == 500 to 0) {
return true
}
else {
// sand comes to rest
caveContent[currentSandPosition.second][currentSandPosition.first] = "o"
sandCounter++
return false
}
}
}
fun printContents() {
caveContent.forEach { row ->
println(row)
}
}
}
| 0 | Kotlin | 0 | 1 | 3c7e46ddfb933281be34e58933b84870c6607acd | 6,767 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | k3vonk | 573,555,443 | false | {"Kotlin": 17347} | import kotlin.math.floor
import kotlin.math.pow
import kotlin.math.sqrt
data class Point(var x: Double, var y: Double) {
operator fun plus(other: Point) {
this.x += other.x
this.y += other.y
}
}
val directions = mapOf(
"R" to Point(1.0, 0.0),
"L" to Point(-1.0, 0.0),
"U" to Point(0.0, 1.0),
"D" to Point(0.0, -1.0)
)
fun main() {
fun isTwoGridApart(head: Point, tail: Point): Boolean {
val distance = sqrt((tail.x - head.x).pow(2) + (tail.y - head.y).pow(2))
return floor(distance) == 2.0
}
fun moveTailBasedOnDirection(head: Point, tail: Point) {
val dx = head.x - tail.x
val dy = head.y - tail.y
if (dx > 0) {
tail.plus(directions["R"]!!)
} else if (dx < 0) {
tail.plus(directions["L"]!!)
}
if (dy > 0) {
tail.plus(directions["U"]!!)
} else if (dy < 0) {
tail.plus(directions["D"]!!)
}
}
fun part1(input: List<String>): Int {
val head = Point(0.0, 0.0)
val tail = Point(0.0, 0.0)
val visited = mutableListOf(Point(0.0, 0.0))
for (i in input) {
val (direction, count) = i.split(" ")
for (walk in 0 until count.toInt()) {
val directionalPoint = directions[direction]!!
head.plus(directionalPoint)
if (isTwoGridApart(head, tail)) {
if (head.x == tail.x || head.y == tail.y) {
tail.plus(directionalPoint)
} else {
moveTailBasedOnDirection(head, tail)
}
if(!visited.contains(Point(tail.x, tail.y))) {
visited.add(Point(tail.x, tail.y))
}
}
// println("head: $head, tail: $tail")
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val ropeknots = MutableList(10) { Point(0.0, 0.0) }
val visited = mutableListOf(Point(0.0, 0.0))
for (i in input) {
val (direction, count) = i.split(" ")
for (walk in 0 until count.toInt()) {
val directionalPoint = directions[direction]!!
ropeknots.forEachIndexed { index, currPoint ->
if(index == 0) {
currPoint.plus(directionalPoint)
} else {
val prevKnot = ropeknots[index - 1]
if (isTwoGridApart(prevKnot, currPoint)) {
if (prevKnot.x == currPoint.x || prevKnot.y == currPoint.y) {
val newDirection = Point((prevKnot.x - currPoint.x)/2, (prevKnot.y - currPoint.y)/2)
currPoint.plus(newDirection)
} else {
moveTailBasedOnDirection(prevKnot, currPoint)
}
if(!visited.contains(Point(currPoint.x, currPoint.y)) && index == 9) {
visited.add(Point(currPoint.x, currPoint.y))
}
}
}
}
}
}
return visited.size
}
val inputs = readInput("Day09_test")
println(part1(inputs))
println(part2(inputs))
} | 0 | Kotlin | 0 | 1 | 68a42c5b8d67442524b40c0ce2e132898683da61 | 3,452 | AOC-2022-in-Kotlin | Apache License 2.0 |
src/main/kotlin/days/Day23.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
class Day23 : Day(23) {
override fun partOne(): Any {
return elvesRounds()
.take(10).last()
.let(::countEmptyGround)
}
override fun partTwo(): Any {
return elvesRounds()
.zipWithNext()
.takeWhile { (prev, cur) -> prev != cur }
.count() + 1
}
private fun elvesRounds(): Sequence<Set<Elf>> {
val elvesStart = inputList.flatMapIndexed { row, str ->
str.mapIndexedNotNull { col, charAt ->
if (charAt == '#') Elf(Point(row, col)) else null
}
}.toSet()
return generateSequence(elvesStart to INIT_DIRECTIONS) { (elves, dir) ->
val proposed = elves.associateWith { it.propose(elves, dir.toNewIterator()) }
val propGroup = proposed.values.groupBy { it.position }
dir.next()
proposed.map { (from, to) ->
if (propGroup.getValue(to.position).size == 1) to else from
}.toSet() to dir.toNewIterator()
}.map { it.first }
}
private fun countEmptyGround(elves: Set<Elf>): Int {
val rows = elves.minOf { it.position.row } .. elves.maxOf { it.position.row }
val cols = elves.minOf { it.position.col } .. elves.maxOf { it.position.col }
val positions = elves.map { it.position }.toSet()
return rows.sumOf { row ->
cols.count { col -> Point(row, col) !in positions }
}
}
data class Elf(val position: Point) {
private val adjPoints = listOf(
Point(-1, -1), Point(-1, 0), Point(-1, 1),
Point(0, -1), Point(0, 1),
Point(1, -1), Point(1, 0), Point(1, 1),
)
fun propose(otherElves: Set<Elf>, dir: Iterator<Direction>): Elf {
val otherPositions = otherElves.map { it.position }.toSet()
if (adjPoints.all { (this.position + it) !in otherPositions }) return this
return (1..4).firstNotNullOfOrNull {
val direction = dir.next()
if (direction.toCheck.all { (this.position + it) !in otherPositions }) Elf(this.position + direction.next)
else null
} ?: this
}
}
data class Point(val row: Int, val col: Int) {
operator fun plus(other: Point) = Point(this.row + other.row, this.col + other.col)
}
enum class Direction(val next: Point, val toCheck: List<Point>) {
NORTH(Point(-1, 0), listOf(Point(-1, -1), Point(-1, 0), Point(-1, 1))),
SOUTH(Point(1, 0), listOf(Point(1, -1), Point(1, 0), Point(1, 1))),
WEST(Point(0, -1), listOf(Point(-1, -1), Point(0, -1), Point(1, -1))),
EAST(Point(0, 1), listOf(Point(-1, 1), Point(0, 1), Point(1, 1))),
}
private val INIT_DIRECTIONS = sequence {
while (true) { yieldAll(Direction.values().toList()) }
}.iterator()
private fun Iterator<Direction>.toNewIterator(): Iterator<Direction> = sequence {
while (true) {
yieldAll(listOf(this@toNewIterator.next(), this@toNewIterator.next(), this@toNewIterator.next(), this@toNewIterator.next()))
}
}.iterator()
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 3,169 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dev/tasso/adventofcode/_2015/day02/Day02.kt | AndrewTasso | 433,656,563 | false | {"Kotlin": 75030} | package dev.tasso.adventofcode._2015.day02
import dev.tasso.adventofcode.Solution
class Day02 : Solution<Int> {
override fun part1(input: List<String>): Int {
val dimensions = input.map { dimension -> dimension.split("x").map { it.toInt() } }
return dimensions.sumOf { dimension ->
getSurfaceArea(dimension[0], dimension[1], dimension[2]) + getSlack(dimension[0], dimension[1], dimension[2])
}
}
override fun part2(input: List<String>): Int {
val dimensions = input.map { dimension -> dimension.split("x").map { it.toInt() } }
return dimensions.sumOf{ dimension ->
getWrapLength(dimension[0], dimension[1], dimension[2]) + getVolume(dimension[0], dimension[1], dimension[2])
}
}
}
fun getSurfaceArea(length : Int, width : Int, height : Int) =
2 * length * width + 2 * width * height + 2 * height * length
fun getSlack(length : Int, width : Int, height : Int) =
listOf(length * width, width * height, height * length).minOrNull()!!
fun getWrapLength(length : Int, width : Int, height : Int) =
listOf(length, width, height).sorted().take(2).sumOf { shortSide -> shortSide * 2 }
fun getVolume(length : Int, width : Int, height : Int) = length * width * height
| 0 | Kotlin | 0 | 0 | daee918ba3df94dc2a3d6dd55a69366363b4d46c | 1,274 | advent-of-code | MIT License |
src/Day15.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 1320
private const val EXPECTED_2 = 145
private class Day15(isTest: Boolean) : Solver(isTest) {
fun String.hash(): Int {
var v = 0
for (ch in this) {
v += ch.code
v = (v * 17) % 256
}
return v
}
fun part1(): Any {
return readAsString().split(",").sumOf { it.hash() }
}
fun part2(): Any {
val boxes = mutableMapOf<Int, MutableList<Pair<String, Int>>>()
readAsString().split(",").forEach { cmd ->
if (cmd.endsWith("-")) {
val lensName = cmd.removeSuffix("-")
boxes[lensName.hash()]?.removeIf { it.first == lensName }
} else {
val lens = cmd.split("=").let { it[0] to it[1].toInt() }
val list = boxes.getOrPut(lens.first.hash()) { mutableListOf() }
val index = list.indexOfFirst { it.first == lens.first }
if (index == -1) {
list.add(lens)
} else {
list[index] = lens
}
}
}
var result = 0
for ((index, list) in boxes.entries) {
for ((lIndex, lens) in list.withIndex()) {
result += (1 + index) * (1 + lIndex) * lens.second
}
}
return result
}
}
fun main() {
val testInstance = Day15(true)
val instance = Day15(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 1,741 | advent-of-code-2022 | Apache License 2.0 |
src/day13/Code.kt | fcolasuonno | 572,734,674 | false | {"Kotlin": 63451, "Dockerfile": 1340} | package day13
import day06.main
import readInput
fun main() {
abstract class Packet : Comparable<Packet>
data class ListPacket(val contents: List<Packet>) : Packet() {
override fun compareTo(other: Packet): Int =
if (other is ListPacket) contents
.zip(other.contents, Packet::compareTo)
.firstOrNull { it != 0 }
?: (contents.size - other.contents.size)
else compareTo(ListPacket(listOf(other)))
}
data class IntPacket(val value: Int) : Packet() {
override fun compareTo(other: Packet) =
if (other is IntPacket) value - other.value
else ListPacket(listOf(this)).compareTo(other)
}
fun <E> MutableCollection<E>.removeWhile(predicate: (E) -> Boolean) = iterator().apply {
while (hasNext() && predicate(next())) {
remove()
}
}
fun List<Char>.toInt() = fold(0) { acc, c -> acc * 10 + (c - '0') }
fun parseInt(chars: MutableList<Char>) = chars.takeWhile(Char::isDigit).toInt().also {
chars.removeWhile(Char::isDigit)
}
fun parseList(chars: MutableList<Char>): ListPacket = ListPacket(buildList {
chars.removeFirst()
while (chars.first() != ']') {
when (chars.first()) {
'[' -> add(parseList(chars))
in '0'..'9' -> add(IntPacket(parseInt(chars)))
',' -> chars.removeFirst()
}
}
chars.removeFirst()
})
fun parse(input: List<String>) =
input.mapNotNull { it.takeIf(String::isNotEmpty)?.let { chars -> parseList(chars.toMutableList()) } }
fun part1(input: List<ListPacket>) = input.chunked(2)
.map { (left, right) -> left < right }
.foldIndexed(0) { index, acc, inOrder ->
if (inOrder) acc + index + 1 else acc
}
fun part2(input: List<ListPacket>) = setOf(
parseList("[[2]]".toMutableList()),
parseList("[[6]]".toMutableList())
).let { dividers ->
input.plus(dividers).sortedWith(Packet::compareTo)
.map { it in dividers }
.foldIndexed(1) { index, acc, isDivider ->
if (isDivider) acc * (index + 1) else acc
}
}
val input = parse(readInput(::main.javaClass.packageName))
println("Part1=\n" + part1(input))
println("Part2=\n" + part2(input))
}
| 0 | Kotlin | 0 | 0 | 9cb653bd6a5abb214a9310f7cac3d0a5a478a71a | 2,396 | AOC2022 | Apache License 2.0 |
AdventOfCodeDay22/src/nativeMain/kotlin/Day22.kt | bdlepla | 451,510,571 | false | {"Kotlin": 165771} | class Day22(input: List<String>) {
private val cubes: List<Cuboid> = input.map { Cuboid.of(it) }
private val part1Cube = Cuboid(true, -50..50, -50..50, -50..50)
fun solvePart1(): Long =
solve(cubes.filter { it.intersects(part1Cube) })
fun solvePart2(): Long =
solve()
private fun solve(cubesToUse: List<Cuboid> = cubes): Long {
val volumes = mutableListOf<Cuboid>()
cubesToUse.forEach { cube ->
volumes.addAll(volumes.mapNotNull { it.intersect(cube) })
if (cube.on) volumes.add(cube)
}
return volumes.sumOf { it.volume() }
}
private class Cuboid(val on: Boolean, val x: IntRange, val y: IntRange, val z: IntRange) {
fun intersects(other: Cuboid): Boolean =
x.intersects(other.x) && y.intersects(other.y) && z.intersects(other.z)
fun intersect(other: Cuboid): Cuboid? =
if (!intersects(other)) null
else Cuboid(!on, x intersect other.x, y intersect other.y, z intersect other.z)
fun volume(): Long =
(x.size().toLong() * y.size().toLong() * z.size().toLong()) * if (on) 1 else -1
companion object {
private val pattern =
"""^(on|off) x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)$""".toRegex()
fun of(input: String): Cuboid {
val (s, x1, x2, y1, y2, z1, z2) = pattern.matchEntire(input)?.destructured
?: error("Cannot parse input: $input")
return Cuboid(
s == "on",
x1.toInt()..x2.toInt(),
y1.toInt()..y2.toInt(),
z1.toInt()..z2.toInt(),
)
}
}
}
}
infix fun IntRange.intersects(other: IntRange): Boolean =
first <= other.last && last >= other.first
infix fun IntRange.intersect(other: IntRange): IntRange =
maxOf(first, other.first)..minOf(last, other.last)
fun IntRange.size(): Int =
last - first + 1 | 0 | Kotlin | 0 | 0 | 1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871 | 2,037 | AdventOfCode2021 | The Unlicense |
src/Day15.kt | realpacific | 573,561,400 | false | {"Kotlin": 59236} | import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.abs
private fun solveForX(coordinate1: Coordinate, coordinate2: Coordinate): (Int) -> Int {
return { y: Int ->
val slope = (coordinate2.second - coordinate1.second) / (coordinate2.first - coordinate1.first)
// y - y1 = m(x - x1)
(y - coordinate1.second) / slope + coordinate1.first
}
}
data class SensorBeacon(val sensor: Coordinate, val beacon: Coordinate) {
val distance: Int = abs(sensor.first - beacon.first) + abs(sensor.second - beacon.second)
// the Manhattan Geometry forms a square
val leftCorner: Coordinate = sensor.first - distance to sensor.second
val rightCorner: Coordinate = sensor.first + distance to sensor.second
val topCorner: Coordinate = sensor.first to sensor.second + distance
val bottomCorner: Coordinate = sensor.first to sensor.second - distance
fun findBottomHalfIntersection(y: Int): IntRange {
return solveForX(leftCorner, bottomCorner)(y)..solveForX(rightCorner, bottomCorner)(y)
}
fun findTopHalfIntersection(y: Int): IntRange {
return solveForX(leftCorner, topCorner)(y)..solveForX(rightCorner, topCorner)(y)
}
fun isHorizontalLinePassesThroughSquare(y: Int): Boolean = y in topCorner.second downTo bottomCorner.second
fun isHorizontalLineCutsAtTopHalf(y: Int): Boolean = y in topCorner.second downTo leftCorner.second
fun isHorizontalLineCutsAtBottomHalf(y: Int): Boolean = y in leftCorner.second downTo bottomCorner.second
}
private fun IntRange.keepRangeInBetween(lowValue: Int, atMostValue: Int): IntRange {
val start: Int = if (first < lowValue) lowValue else first
val end: Int = if (last < atMostValue) last else atMostValue - 1
return start..end
}
private fun List<IntRange>.merge(): List<IntRange> {
val result = mutableListOf<IntRange>()
val sorted = this.sortedBy { it.first }
sorted.forEach { current ->
if (result.isEmpty()) {
result.add(current)
return@forEach
} else {
val prev = result.last()
if (current.first in prev && current.last in prev) {
return@forEach
}
if (current.last !in prev) {
result.removeLast()
result.add(prev.first..current.last)
}
}
}
return result
}
fun main() {
fun extractCoordinates(input: List<String>): List<SensorBeacon> {
val regex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex()
return input.map {
val (sensorX, sensorY, beaconX, beaconY) = regex.matchEntire(it)!!.groupValues
.slice(1..4)
.map(String::toInt)
// the question uses opposite index (y-coordinate increases as you go down the y-axis)
SensorBeacon(Coordinate(sensorX, -sensorY), Coordinate(beaconX, -beaconY))
}
}
fun part1(input: List<String>, yCoordinate: Int): Int {
// the question uses opposite index (y-coordinate increases as you go down the y-axis)
val y = -yCoordinate
val squares = extractCoordinates(input)
val xCoordinateOfBeaconAtY = squares.map { it.beacon }.filter { it.second == y }.map { it.first }
val results = mutableListOf<IntRange>()
squares.forEach { square ->
if (square.isHorizontalLineCutsAtBottomHalf(y)) {
val range = square.findBottomHalfIntersection(y)
results.add(range)
} else if (square.isHorizontalLineCutsAtTopHalf(y)) {
val range = square.findTopHalfIntersection(y)
results.add(range)
}
}
val seen = mutableSetOf<Int>()
for (range in results) {
for (xCoordinate in range) {
if (xCoordinate !in xCoordinateOfBeaconAtY)
seen.add(xCoordinate)
}
}
return seen.size
}
fun part2(input: List<String>, atMostValue: Int): Int {
val squares = extractCoordinates(input)
val foundAnswer = AtomicInteger()
val executor = Executors.newFixedThreadPool(10)
for (i in 0 until atMostValue) {
executor.submit {
println("Executing $i")
val y = -i
var results = mutableListOf<IntRange>()
squares.forEach { square ->
if (square.isHorizontalLineCutsAtBottomHalf(y)) {
val range = square.findBottomHalfIntersection(y)
results.add(range)
} else if (square.isHorizontalLineCutsAtTopHalf(y)) {
val range = square.findTopHalfIntersection(y)
results.add(range)
}
}
results = results.map { it.keepRangeInBetween(0, atMostValue) }.merge().toMutableList()
if (results.size == 1 && results.first().first == 0 && results.first().last == atMostValue - 1) {
return@submit
}
val missingSignalCoordinate = (results.first().first - 1) * 4000000 + -1 * results.first().last
foundAnswer.set(missingSignalCoordinate)
println()
}
}
executor.awaitTermination(100, TimeUnit.MINUTES)
return foundAnswer.get()
}
// run {
// val input = readInput("Day15_test")
// println(part1(input, 10))
// println(part2(input, 20))
// }
run {
val input = readInput("Day15")
// println(part1(input, 2000000))
println(part2(input, 4_000_000))
}
}
| 0 | Kotlin | 0 | 0 | f365d78d381ac3d864cc402c6eb9c0017ce76b8d | 5,810 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | chasebleyl | 573,058,526 | false | {"Kotlin": 15274} |
enum class RPS {
ROCK, PAPER, SCISSORS, UNKNOWN
}
fun RPS.scoreValue(): Int = when (this) {
RPS.ROCK -> 1
RPS.PAPER -> 2
RPS.SCISSORS -> 3
RPS.UNKNOWN -> 0
}
fun String.toRPS(): RPS = when (this) {
"A", "X" -> RPS.ROCK
"B", "Y" -> RPS.PAPER
"C", "Z" -> RPS.SCISSORS
else -> RPS.UNKNOWN
}
enum class Outcome {
WIN, LOSE, DRAW
}
fun Outcome.scoreValue(): Int = when (this) {
Outcome.WIN -> 6
Outcome.LOSE -> 0
Outcome.DRAW -> 3
}
fun String.toOutcome(): Outcome = when (this) {
"X" -> Outcome.LOSE
"Y" -> Outcome.DRAW
else -> Outcome.WIN
}
fun rpsOutcome(opponent: RPS, self: RPS): Outcome = when {
opponent == RPS.ROCK && self == RPS.SCISSORS
|| opponent == RPS.PAPER && self == RPS.ROCK
|| opponent == RPS.SCISSORS && self == RPS.PAPER -> Outcome.LOSE
opponent == self -> Outcome.DRAW
else -> Outcome.WIN
}
fun calculateSelfShape(opponent: RPS, outcome: Outcome): RPS = when {
outcome == Outcome.WIN -> when (opponent) {
RPS.ROCK -> RPS.PAPER
RPS.PAPER -> RPS.SCISSORS
RPS.SCISSORS -> RPS.ROCK
RPS.UNKNOWN -> RPS.UNKNOWN
}
outcome == Outcome.LOSE -> when (opponent) {
RPS.ROCK -> RPS.SCISSORS
RPS.PAPER -> RPS.ROCK
RPS.SCISSORS -> RPS.PAPER
RPS.UNKNOWN -> RPS.UNKNOWN
}
else -> opponent
}
fun main() {
fun part1(input: List<String>): Int {
var runningScore = 0
input.forEach { game ->
val throws = game.split(" ")
runningScore +=
throws[1].toRPS().scoreValue() + rpsOutcome(throws[0].toRPS(), throws[1].toRPS()).scoreValue()
}
return runningScore
}
fun part2(input: List<String>): Int {
var runningScore = 0
input.forEach { game ->
val throws = game.split(" ")
val self = calculateSelfShape(throws[0].toRPS(), throws[1].toOutcome())
runningScore +=
self.scoreValue() + rpsOutcome(throws[0].toRPS(), self).scoreValue()
}
return runningScore
}
val input = readInput("Day02")
val testInput = readInput("Day02_test")
// PART 1
check(part1(testInput) == 15)
println(part1(input))
// PART 2
check(part2(testInput) == 12)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | f2f5cb5fd50fb3e7fb9deeab2ae637d2e3605ea3 | 2,316 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | KarinaCher | 572,657,240 | false | {"Kotlin": 21749} | fun main() {
fun parseData(input: List<String>): Pair<Map<Int, MutableList<Char>>, MutableList<Move>> {
var stacks: Map<Int, MutableList<Char>> = mutableMapOf()
var moves = mutableListOf<Move>()
var boxes = mutableListOf<String>()
var moveRegex = Regex("move (\\d{1,2}) from (\\d) to (\\d)")
for (line in input) {
if (line.contains("[")) {
boxes.add(line)
} else if (line.trim().startsWith("1")) {
stacks = line.trim().split(" ")
.associate { it.toInt() to mutableListOf() }
} else if (line.matches(moveRegex)) {
val matcher = moveRegex.find(line)!!.groupValues
moves.add(Move(matcher.get(1).toInt(), matcher.get(2).toInt(), matcher.get(3).toInt()))
}
}
for (line in boxes) {
val chunked = line.chunked(4)
var i = 1
for (chunk in chunked) {
if (chunk.isNotBlank()) {
stacks.get(i)!!.add(0, chunk.get(1))
}
i++
}
}
return stacks to moves
}
fun part1(input: List<String>): String {
val parseData = parseData(input)
var stacks: Map<Int, MutableList<Char>> = parseData.first
var moves = parseData.second
moves.forEach {
val from = stacks.get(it.from)!!
var start = from.size.minus(it.crateCount)
val end = from.size
for (index in end.minus(1) downTo start) {
val item = from.removeAt(index)
stacks.get(it.to)?.add(item)
}
}
return stacks.map {
if (it.value.isEmpty()) " " else it.value.last().toString()
}.joinToString("")
}
fun part2(input: List<String>): String {
val parseData = parseData(input)
var stacks: Map<Int, MutableList<Char>> = parseData.first
var moves = parseData.second
moves.forEach { move ->
val from = stacks.get(move.from)!!
var start = from.size.minus(move.crateCount)
val end = from.size
val subList = from.subList(start, end).chunked(3)
subList.forEach {
stacks.get(move.to)?.addAll(it)
}
for (index in end.minus(1) downTo start) {
from.removeAt(index)
}
}
return stacks.map {
if (it.value.isEmpty()) " " else it.value.last().toString()
}.joinToString("")
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
data class Move(val crateCount: Int, val from: Int, val to: Int)
| 0 | Kotlin | 0 | 0 | 17d5fc87e1bcb2a65764067610778141110284b6 | 2,873 | KotlinAdvent | Apache License 2.0 |
src/main/day19/day19.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day19
import day19.Resource.CLAY
import day19.Resource.GEODE
import day19.Resource.NONE
import day19.Resource.OBSIDIAN
import day19.Resource.ORE
import kotlin.math.max
import readInput
val regex = """.+ (\d+).+ (\d+) .+ (\d+) .+ (\d+) .+ (\d+) .+ (\d+).+ (\d+) .*""".toRegex()
fun main() {
val input = readInput("main/day19/Day19_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val bluePrints = input.toBlueprints()
return bluePrints.sumOf { it.id * it.maxGeodes(0) }
}
fun part2(input: List<String>): Long {
return -1
}
enum class Resource {
NONE, ORE, CLAY, OBSIDIAN, GEODE
}
fun List<String>.toBlueprints() = map { line ->
regex.matchEntire(line)?.destructured?.let { (id, oreRobotOre, clayRoboTOre, obsidianRobotOre, obsidianRobotClay, geodeRobotOre, geodeRobotObsidian) ->
BluePrint(
id = id.toInt(),
oreRobotTemplate = OreRobot(cost = listOf(Cost(ORE, oreRobotOre.toInt()))),
clayRobotTemplate = ClayRobot(cost = listOf(Cost(ORE, clayRoboTOre.toInt()))),
obsidianRobotTemplate = ObsidianRobot(cost = listOf(Cost(ORE, obsidianRobotOre.toInt()), Cost(CLAY, obsidianRobotClay.toInt()))),
geodeRobotTemplate = GeodeRobot(cost = listOf(Cost(ORE, geodeRobotOre.toInt()), Cost(OBSIDIAN, geodeRobotObsidian.toInt()))),
)
} ?: error("PARSER ERROR")
}
data class Cost(val resource: Resource, val amount: Int)
data class BluePrint(
val id: Int,
val oreRobotTemplate: OreRobot,
val clayRobotTemplate: ClayRobot,
val obsidianRobotTemplate: ObsidianRobot,
val geodeRobotTemplate: GeodeRobot
) {
private val allTemplates = listOf(oreRobotTemplate, clayRobotTemplate, obsidianRobotTemplate, geodeRobotTemplate).reversed()
fun maxGeodes(
maxSoFar: Int,
robots: List<Robot> = listOf(oreRobotTemplate.instance()),
resources: MutableList<Resource> = mutableListOf(),
timeLeft: Int = 24
): Int {
if (timeLeft > 0) {
val buildableRobots = buildableRobots(resources)
buildableRobots.forEach { newRobot ->
newRobot.cost.forEach { repeat(it.amount) { _ -> resources.remove(it.resource) } }
return maxGeodes(
max(maxSoFar, resources.count { it == GEODE }),
robots + newRobot,
resources.filter { it != NONE }.toMutableList(),
timeLeft - 1
)
}
robots.forEach { resources.add(it.resource) }
return maxGeodes(max(maxSoFar, resources.count { it == GEODE }), robots, resources, timeLeft - 1)
} else return maxSoFar
}
private fun buildableRobots(resources: List<Resource>): MutableList<Robot> {
return allTemplates.filter {
it.canBeBuiltFrom(resources)
}.map {
it.instance()
}.toMutableList()
}
}
sealed interface Robot {
val resource: Resource
val cost: List<Cost>
fun canBeBuiltFrom(resources: List<Resource>): Boolean
fun instance(): Robot
}
data class OreRobot(override val resource: Resource = ORE, override val cost: List<Cost>) : Robot {
override fun canBeBuiltFrom(resources: List<Resource>): Boolean {
return cost.all { cost ->
resources.count {
it == cost.resource
} >= cost.amount
}
}
override fun instance(): Robot {
return copy()
}
}
data class ClayRobot(override val resource: Resource = CLAY, override val cost: List<Cost>) : Robot {
override fun canBeBuiltFrom(resources: List<Resource>): Boolean {
return cost.all { cost ->
resources.count {
it == cost.resource
} >= cost.amount
}
}
override fun instance(): Robot {
return copy()
}
}
data class ObsidianRobot(override val resource: Resource = OBSIDIAN, override val cost: List<Cost>) : Robot {
override fun canBeBuiltFrom(resources: List<Resource>): Boolean {
return cost.all { cost ->
resources.count {
it == cost.resource
} >= cost.amount
}
}
override fun instance(): Robot {
return copy()
}
}
data class GeodeRobot(override val resource: Resource = GEODE, override val cost: List<Cost>) : Robot {
override fun canBeBuiltFrom(resources: List<Resource>): Boolean {
return cost.all { cost ->
resources.count {
it == cost.resource
} >= cost.amount
}
}
override fun instance(): Robot {
return copy()
}
}
//object NoOp : Robot {
// override val resource: Resource
// get() = NONE
// override val cost: List<Cost>
// get() = emptyList()
//
// override fun canBeBuiltFrom(resources: List<Resource>): Boolean = true
//
// override fun instance(): Robot {
// return this
// }
//}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 4,996 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2016/TwoStepsForward.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2016
import komu.adventofcode.utils.Direction
import komu.adventofcode.utils.hexEncodedMd5Hash
import utils.shortestPath
fun twoStepsForward1(passcode: String): String =
shortestPath(State.initial, State::isGoal) { it.transitions(passcode) }!!.last().path
fun twoStepsForward2(passcode: String): Int {
fun recurse(state: State): Int =
if (state.isGoal)
state.path.length
else
state.transitions(passcode).maxOfOrNull { recurse(it) } ?: -1
return recurse(State.initial)
}
private class Room private constructor(val x: Int, val y: Int) {
val transitions by lazy {
val transitions = mutableListOf<Pair<Direction, Room>>()
if (this != goal) {
for (d in Direction.values()) {
val xx = x + d.dx
val yy = y + d.dy
if (xx in 0..3 && yy in 0..3)
transitions.add(d to Room[xx, yy])
}
}
transitions
}
companion object {
private val allRooms = (0..3).map { x -> (0..3).map { y -> Room(x, y) } }
operator fun get(x: Int, y: Int) = allRooms[x][y]
val start = this[0, 0]
val goal = this[3, 3]
}
}
private data class State(val room: Room, val path: String) {
val isGoal: Boolean
get() = room == Room.goal
fun transitions(passcode: String): List<State> = buildList {
val openDoors = OpenDoors.forPath(passcode, path)
for ((direction, targetRoom) in room.transitions)
if (openDoors.isOpen(direction))
add(State(targetRoom, path + direction.pathCode))
}
companion object {
val initial = State(Room.start, "")
}
}
private val Direction.pathCode: Char
get() = when (this) {
Direction.UP -> 'U'
Direction.DOWN -> 'D'
Direction.LEFT -> 'L'
Direction.RIGHT -> 'R'
}
private data class OpenDoors(val up: Boolean, val down: Boolean, val left: Boolean, val right: Boolean) {
fun isOpen(d: Direction) = when (d) {
Direction.UP -> up
Direction.DOWN -> down
Direction.LEFT -> left
Direction.RIGHT -> right
}
companion object {
fun forPath(passcode: String, path: String): OpenDoors {
val (up, down, left, right) = hexEncodedMd5Hash(passcode + path).toList()
return OpenDoors(
up = up.isOpen(),
down = down.isOpen(),
left = left.isOpen(),
right = right.isOpen(),
)
}
private fun Char.isOpen() = this in "bcdef"
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 2,649 | advent-of-code | MIT License |
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/TopKElements.kt | betulnecanli | 568,477,911 | false | {"Kotlin": 167849} | /*
The "Top 'K' Elements" coding pattern is often used to efficiently find the K smallest or largest elements in a collection.
*/
//1. ‘K’ Closest Points to the Origin
import java.util.PriorityQueue
data class Point(val x: Int, val y: Int)
fun kClosest(points: Array<Point>, k: Int): Array<Point> {
val result = mutableListOf<Point>()
// Use a max heap to keep track of the 'K' closest points
val maxHeap = PriorityQueue<Point>(compareByDescending { it.x * it.x + it.y * it.y })
for (point in points) {
maxHeap.offer(point)
if (maxHeap.size > k) {
maxHeap.poll()
}
}
// Convert the max heap to an array
while (maxHeap.isNotEmpty()) {
result.add(maxHeap.poll())
}
return result.toTypedArray()
}
fun main() {
val points = arrayOf(Point(1, 3), Point(3, 4), Point(2, -1), Point(4, 6))
val k = 2
val result = kClosest(points, k)
println("K Closest Points to the Origin:")
result.forEach { println("(${it.x}, ${it.y})") }
}
//2. Maximum Distinct Elements
import java.util.PriorityQueue
import java.util.HashMap
fun findMaximumDistinctElements(nums: IntArray, k: Int): Int {
val frequencyMap = HashMap<Int, Int>()
// Count the frequency of each number
for (num in nums) {
frequencyMap[num] = frequencyMap.getOrDefault(num, 0) + 1
}
// Use a min heap to keep track of the least frequent numbers
val minHeap = PriorityQueue<Int>(compareBy { frequencyMap[it] })
// Add numbers to the min heap
for ((num, frequency) in frequencyMap) {
if (frequency == 1) {
// If a number has a frequency of 1, it's already a distinct element
minHeap.offer(num)
} else {
// If a number has a frequency greater than 1, add it to the min heap
// based on its frequency
minHeap.offer(num)
frequencyMap[num] = frequency - 1
}
// Remove the least frequent number if the heap size exceeds 'k'
if (minHeap.size > k) {
frequencyMap[minHeap.poll()] = 0
}
}
// The size of the min heap represents the maximum distinct elements
return minHeap.size
}
fun main() {
val nums = intArrayOf(4, 3, 1, 1, 3, 3, 2, 4, 4)
val k = 3
val result = findMaximumDistinctElements(nums, k)
println("Maximum Distinct Elements: $result")
}
/*
K’ Closest Points to the Origin:
The kClosest function finds the K closest points to the origin using a max heap.
The max heap is used to efficiently keep track of the K closest points,
and it prioritizes points based on their distance from the origin.
Maximum Distinct Elements:
The findMaximumDistinctElements function finds the maximum number of distinct elements in an array
after removing at most 'k' elements. It uses a min heap to efficiently keep track of the least frequent numbers.
*/
| 2 | Kotlin | 2 | 40 | 70a4a311f0c57928a32d7b4d795f98db3bdbeb02 | 2,907 | Kotlin-Data-Structures-Algorithms | Apache License 2.0 |
Day20/src/Pluto.kt | gautemo | 225,219,298 | false | null | import java.io.File
import java.lang.Exception
import kotlin.math.abs
import kotlin.math.hypot
fun main(){
val input = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText()
val result = shortest(input)
println(result)
val resultWithDigging = shortest(input, true)
println(resultWithDigging)
}
fun shortest(map: String, dig: Boolean = false): Int {
val nodes = nodes(map)
val start = nodes.first { it.port == "AA" }
val beenTo = mutableListOf<Pair<Point, Int>>()
val canGo = mutableListOf(Step(start, 0, 0))
while (true){
val go = canGo.minBy { it.point.distToPort + it.step + it.level}!!
if(go.point.port == "ZZ" && go.level == 0){
return go.step
}
beenTo.add(Pair(go.point, go.level))
canGo.remove(go)
for(next in go.point.next){
val blockedIfDigged = go.level != 0 && (next.port == "AA" || next.port == "ZZ")
val blockedIfNotDigged = (dig && go.level == 0 && next.port.isNotEmpty() && isOuterPoint(go.point, map)) && !(next.port == "AA" || next.port == "ZZ")
val toLevel = if(dig) getLevel(go, next, map) else go.level
println(toLevel)
if(!beenTo.contains(Pair(next, toLevel)) && !blockedIfDigged && !blockedIfNotDigged) {
canGo.add(Step(next, go.step + 1, toLevel))
}
}
}
}
fun getLevel(on: Step, next: Point, map: String): Int{
return if(next.port.isNotEmpty() && !pointsAreNeighbour(on.point, next)){
if(isOuterPoint(on.point, map)) {
println("Goes out")
on.level - 1
}else{
println("Goes in")
on.level + 1
}
}else{
on.level
}
}
fun isOuterPoint(p: Point, map: String) = p.x == 2 || p.x == map.lines().first().length - 3 || p.y == 2 || p.y == map.length / map.lines().first().length - 3
fun distToPort(node: Point, nodes: List<Point>) = nodes.filter { it.port.isNotEmpty() }.map { hypot(abs(node.x - it.x).toDouble(), abs(node.y - it.y).toDouble()) }.min()
fun nodes(map: String): List<Point>{
val nodes = mutableListOf<Point>()
for(y in map.lines().indices){
for(x in map.lines()[y].indices){
if(map.lines()[y][x] == '.'){
val point = Point(x,y, hasPort(x,y,map))
val neighbors = nodes.filter { pointsAreNeighbour(it, point) }
for (n in neighbors){
point.next.add(n)
n.next.add(point)
}
val portTo = nodes.firstOrNull { it.port.isNotEmpty() && it.port == point.port }
if(portTo != null){
portTo.next.add(point)
point.next.add(portTo)
}
nodes.add(point)
}
}
}
for(n in nodes){
n.distToPort = distToPort(n, nodes)!!
}
return nodes
}
fun hasPort(x: Int, y: Int, map: String): String{
//To Left
try {
val first = map.lines()[y][x-2]
val second = map.lines()[y][x-1]
if(first.isUpperCase() && second.isUpperCase()){
return first.toString() + second.toString()
}
}catch (e: Exception){}
//To right
try {
val first = map.lines()[y][x+1]
val second = map.lines()[y][x+2]
if(first.isUpperCase() && second.isUpperCase()){
return first.toString() + second.toString()
}
}catch (e: Exception){}
//Up
try {
val first = map.lines()[y-2][x]
val second = map.lines()[y-1][x]
if(first.isUpperCase() && second.isUpperCase()){
return first.toString() + second.toString()
}
}catch (e: Exception){}
//Down
try {
val first = map.lines()[y+1][x]
val second = map.lines()[y+2][x]
if(first.isUpperCase() && second.isUpperCase()){
return first.toString() + second.toString()
}
}catch (e: Exception){}
return ""
}
class Point(val x: Int, val y: Int, val port: String){
val next = mutableListOf<Point>()
var distToPort: Double = Double.MAX_VALUE
}
class Step(val point: Point, val step: Int, val level: Int)
fun pointsAreNeighbour(p1: Point, p2: Point): Boolean{
if(p1.y == p2.y){
return p1.x - 1 == p2.x || p1.x + 1 == p2.x
}
if(p1.x == p2.x){
return p1.y - 1 == p2.y || p1.y + 1 == p2.y
}
return false
} | 0 | Kotlin | 0 | 0 | f8ac96e7b8af13202f9233bb5a736d72261c3a3b | 4,478 | AdventOfCode2019 | MIT License |
src/Day08.kt | floblaf | 572,892,347 | false | {"Kotlin": 28107} | import kotlin.math.max
fun main() {
data class Tree(
val height: Int,
val left: List<Int>,
val right: List<Int>,
val top: List<Int>,
val bottom: List<Int>
)
fun Tree.findDistance(list: List<Int>): Int {
return list.indexOfFirst { it >= this.height }
.let {
if (it == -1) {
list.size
} else {
it + 1
}
}
}
fun part1(grid: List<Tree>): Int {
return grid.count { tree ->
tree.left.all { it < tree.height } ||
tree.right.all { it < tree.height } ||
tree.top.all { it < tree.height } ||
tree.bottom.all { it < tree.height }
}
}
fun part2(grid: List<Tree>): Int {
return grid.maxOfOrNull {
it.findDistance(it.left) * it.findDistance(it.right) *
it.findDistance(it.top) * it.findDistance(it.bottom)
} ?: 0
}
val input = readInput("Day08")
val grid = buildList {
input.forEach { row ->
add(buildList {
row.forEach { add(it.digitToInt()) }
})
}
}
val flattenGrid = buildList {
for (i in grid.indices) {
for (j in grid[i].indices) {
add(
Tree(
height = grid[i][j],
left = grid[i].take(j).reversed(),
right = grid[i].drop(j + 1),
top = grid.map { it[j] }.take(i).reversed(),
bottom = grid.map { it[j] }.drop(i + 1)
)
)
}
}
}
println(part1(flattenGrid))
println(part2(flattenGrid))
} | 0 | Kotlin | 0 | 0 | a541b14e8cb401390ebdf575a057e19c6caa7c2a | 1,823 | advent-of-code-2022 | Apache License 2.0 |
src/day12/day.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day12
import util.Grid
import util.PathFindingMove
import util.PathFindingState
import util.Point
import util.findPath
import util.readInput
import util.shouldBe
import util.toGrid
fun main() {
val testInput = readInput(Input::class, testInput = true).parseInput()
testInput.part1() shouldBe 31
testInput.part2() shouldBe 29
val input = readInput(Input::class).parseInput()
println("output for part1: ${input.part1()}")
println("output for part2: ${input.part2()}")
}
private class Input(
val grid: Grid<Int>,
val start: Point,
val end: Point,
)
private fun List<String>.parseInput(): Input {
var start: Point? = null
var end: Point? = null
val grid = toGrid { x, y, char ->
when (char) {
'S' -> {
start = Point(x, y)
'a'.code
}
'E' -> {
end = Point(x, y)
'z'.code
}
else -> char.code
}
}
return Input(
grid = grid,
start = start ?: error("no start point found"),
end = end ?: error("no end point found"),
)
}
class StateForPart1(
val grid: Grid<Int>,
val currPos: Point,
val end: Point,
) : PathFindingState<StateForPart1> {
override fun nextMoves(): Sequence<PathFindingMove<StateForPart1>> =
currPos.neighbours()
.asSequence()
.filter { it in grid && grid[it] <= grid[currPos] + 1 }
.map { PathFindingMove(1, StateForPart1(grid, it, end)) }
override fun estimatedCostToGo(): Long =
currPos.manhattanDistanceTo(end).toLong()
override fun isGoal(): Boolean = currPos == end
override fun equals(other: Any?) = other is StateForPart1 && currPos == other.currPos
override fun hashCode() = currPos.hashCode()
}
private fun Input.part1(): Int {
val path = findPath(StateForPart1(grid, start, end)) ?: error("no path found")
return path.nodes.size - 1
}
private class StateForPart2(
val grid: Grid<Int>,
val currPos: Point,
) : PathFindingState<StateForPart2> {
override fun nextMoves(): Sequence<PathFindingMove<StateForPart2>> =
currPos.neighbours()
.asSequence()
.filter { it in grid && grid[it] >= grid[currPos] - 1 }
.map { PathFindingMove(1, StateForPart2(grid, it)) }
override fun estimatedCostToGo(): Long =
grid.positions()
.filter { grid[it] == 'a'.code }
.minOf { currPos manhattanDistanceTo it }
.toLong()
override fun isGoal(): Boolean = grid[currPos] == 'a'.code
override fun equals(other: Any?) = other is StateForPart2 && currPos == other.currPos
override fun hashCode() = currPos.hashCode()
}
private fun Input.part2(): Int {
val startState = StateForPart2(grid, end)
val path = findPath(startState) ?: error("no path found")
return path.nodes.size - 1
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 2,934 | advent-of-code-2022 | Apache License 2.0 |
src/main/Day10.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day10
import utils.readInput
private const val filename = "Day10"
fun part1(filename: String): Int =
readInput(filename)
.readProgram()
.signalStrengths()
.filterIndexed { index, _ -> index in 20..220 step 40 }
.sum()
fun part2(filename: String): String = readInput(filename).readProgram().render()
fun main() {
println(part1(filename))
println(part2(filename))
}
class Cpu {
private var x: Int = 1
private fun execute(instruction: Instruction): Sequence<Cpu.() -> Unit> =
when (instruction) {
is Instruction.Addx -> sequenceOf({}, { x += instruction.value })
is Instruction.Noop -> sequenceOf({})
}
fun execute(program: Program): List<Int> =
listOf(1, 1) +
program.flatMap(::execute).map { change ->
change()
x
}
}
sealed interface Instruction {
data class Addx(val value: Int) : Instruction
object Noop : Instruction
}
typealias Program = List<Instruction>
fun Program.signalStrengths(): Sequence<Int> =
Cpu().execute(this).asSequence().mapIndexed { index, value -> index * value }
fun List<String>.readProgram(): Program = map { line ->
when {
line == "noop" -> Instruction.Noop
line.startsWith("addx ") -> Instruction.Addx(line.removePrefix("addx ").toInt())
else -> error("Unknown instruction: $line")
}
}
fun Program.render(): String {
val output = (1..6).map { CharArray(40) }
Cpu().execute(this).asSequence().drop(1).take(240).withIndex().chunked(40).chunked(6).forEach {
it.withIndex().forEach { (row, values) ->
values.withIndex().forEach { (position, value) ->
output[row][position] = pixel(position, value.value)
}
}
}
return output.joinToString("\n") { it.concatToString() }
}
fun pixel(position: Int, value: Int): Char = if (position in value - 1..value + 1) '#' else '.'
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 1,983 | aoc-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day16.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInputLines
object Day16 : Day {
override val input = Terrain.from(readInputLines(16))
override fun part1() = dfs(30)
override fun part2() = dfs(26, part2 = true)
private fun dfs(
minutes: Int,
current: Valve = input.allValves.getValue("AA"),
remaining: Set<Valve> = input.flowingValves,
cache: MutableMap<State, Int> = mutableMapOf(),
part2: Boolean = false
): Int {
return minutes * current.flow + cache.getOrPut(State(current.name, minutes, remaining)) {
maxOf(remaining
.filter { input.distances.getValue(current.name).getValue(it.name) < minutes }
.takeIf { it.isNotEmpty() }
?.maxOf {
val time = minutes - 1 - input.distances.getValue(current.name).getValue(it.name)
dfs(time, it, remaining - it, cache, part2)
}
?: 0,
if (part2) dfs(26, remaining = remaining) else 0)
}
}
data class Terrain(val allValves: Map<String, Valve>) {
val flowingValves = allValves.values.filter { it.flow > 0 }.toSet()
val distances = distances()
private fun distances(): Map<String, Map<String, Int>> {
return allValves.keys.map { valve ->
val distances = mutableMapOf<String, Int>().withDefault { Int.MAX_VALUE }.apply { put(valve, 0) }
val toVisit = mutableListOf(valve)
while (toVisit.isNotEmpty()) {
val current = toVisit.removeFirst()
allValves.getValue(current).leads.forEach { neighbour ->
val newDistance = distances.getValue(current) + 1
if (newDistance < distances.getValue(neighbour)) {
distances[neighbour] = newDistance
toVisit.add(neighbour)
}
}
}
distances
}.associateBy { it.keys.first() }
}
companion object {
fun from(input: List<String>) = Terrain(input.map { parse(it) }.associateBy { it.name })
private fun parse(line: String): Valve {
val valve = line.substring(6, 8)
val flow = line.substringAfter('=').substringBefore(';').toInt()
val leadsTo = line.substringAfter("to valve").substringAfter(" ").split(',').map { it.trim() }
return Valve(valve, flow, leadsTo)
}
}
}
data class Valve(val name: String, val flow: Int, val leads: List<String>)
data class State(val current: String, val minutes: Int, val opened: Set<Valve>)
} | 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 2,902 | aoc2022 | MIT License |
src/day07/Day07.kt | robin-schoch | 572,718,550 | false | {"Kotlin": 26220} | package day07
import AdventOfCodeSolution
fun main() {
Day07.run()
}
interface CalucalteSize {
val size: Long
}
data class File(val name: String, override val size: Long) : CalucalteSize
data class Directory(val parent: Directory?, val childDirectories: MutableMap<String, Directory>, val files: MutableList<File>) : CalucalteSize {
override val size: Long
get() = childDirectories.values.sumOf { it.size } + files.sumOf { it.size }
fun countAllByMaxSizeOf(maxSize: Int = 100000): Long {
return when {
size > maxSize -> 0L
else -> size
} + childDirectories.values.sumOf { it.countAllByMaxSizeOf() }
}
fun findSmallestDirBiggerThan(minSize: Long): Long? {
val smallest = childDirectories.values.mapNotNull { it.findSmallestDirBiggerThan(minSize) }.minOrNull()
return if (size >= minSize) smallest ?: size else smallest
}
companion object {
fun mkdir(parent: Directory): Directory = Directory(parent, mutableMapOf(), mutableListOf())
fun root() = Directory(null, mutableMapOf(), mutableListOf())
}
}
object Day07 : AdventOfCodeSolution<Long, Long> {
private const val fileSystemSpace = 70000000L
private const val minSystemSpaceRequired = 30000000L
override val testSolution1 = 95437L
override val testSolution2 = 24933642L
private fun buildDirectoryTree(root: Directory, dir: Directory, terminalOuput: List<String>): Directory {
if (terminalOuput.isEmpty()) return root
return when (terminalOuput[0]) {
"$ ls" -> buildDirectoryTree(root, dir, dir.readlines(terminalOuput.drop(1)))
else -> buildDirectoryTree(root, dir.move(root, terminalOuput[0]), terminalOuput.drop(1))
}
}
private fun Directory.move(root: Directory, instruction: String): Directory = with(instruction.split(" ")[2]) {
when (this) {
".." -> parent ?: error("no parent dir found $this")
"/" -> root
else -> childDirectories[this] ?: error("child not found $this")
}
}
private fun Directory.readlines(terminalOuput: List<String>): List<String> {
terminalOuput.takeWhile { it[0] != '$' }.forEach {
with(it.split(" ")) {
when (this[0]) {
"dir" -> childDirectories[this[1]] = Directory.mkdir(this@readlines)
else -> files.add(File(this[1], this[0].toLong()))
}
}
}
return terminalOuput.dropWhile { it[0] != '$' }
}
override fun part1(input: List<String>): Long {
val root = Directory.root()
buildDirectoryTree(root, root, input)
return root.countAllByMaxSizeOf()
}
override fun part2(input: List<String>): Long {
val root = Directory.root()
buildDirectoryTree(root, root, input)
return root.findSmallestDirBiggerThan(minSystemSpaceRequired - (fileSystemSpace - root.size))
?: error("not enough space")
}
} | 0 | Kotlin | 0 | 0 | fa993787cbeee21ab103d2ce7a02033561e3fac3 | 3,035 | aoc-2022 | Apache License 2.0 |
08/src/commonMain/kotlin/Main.kt | daphil19 | 725,415,769 | false | {"Kotlin": 131380} | expect fun getLines(): List<String>
fun main() {
var lines = getLines()
// part 1 test input
// lines = """RL
//
//AAA = (BBB, CCC)
//BBB = (DDD, EEE)
//CCC = (ZZZ, GGG)
//DDD = (DDD, DDD)
//EEE = (EEE, EEE)
//GGG = (GGG, GGG)
//ZZZ = (ZZZ, ZZZ)""".lines()
// part 2 test input
// lines = """LR
//
//11A = (11B, XXX)
//11B = (XXX, 11Z)
//11Z = (11B, XXX)
//22A = (22B, XXX)
//22B = (22C, 22C)
//22C = (22Z, 22Z)
//22Z = (22B, 22B)
//XXX = (XXX, XXX)""".lines()
// part1(lines)
part2(lines)
}
data class Node(val parent: String, val left: String, val right: String, val parentOcc: Int = 0, val leftOcc: Int = 0, val rightOcc: Int = 0)
fun part1(lines: List<String>) = printDuration {
val directions = lines[0]
val tree = lines.drop(2).map { line ->
val (parent, children) = line.split(" = ")
val (left, right) = children.drop(1).dropLast(1).split(", ")
Node(parent, left, right)
}.associateBy { it.parent }
// TODO check for cycle?
var index = 0
var steps = 0L
var cur = "AAA"
while (cur != "ZZZ") {
cur = when(directions[index]) {
'R' -> tree[cur]!!.right
'L' -> tree[cur]!!.left
else -> TODO()
}
index = (index + 1) % directions.length
steps++
}
println(steps)
}
// https://rosettacode.org/wiki/Least_common_multiple#Kotlin
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
fun part2(lines: List<String>) = printDuration {
// I wish coroutines worked in this current setup...
val directions = lines[0]
val tree = lines.drop(2).map { line ->
val (parent, children) = line.split(" = ")
val (left, right) = children.drop(1).dropLast(1).split(", ")
Node(parent, left, right)
}.associateBy { it.parent }
tree.keys.filter { it.last() == 'A' }.map { start ->
var index = 0
var steps = 0L
var cur = start
// hopefully no crossover
while (cur.last() != 'Z') {
cur = when(directions[index]) {
'R' -> tree[cur]!!.right
'L' -> tree[cur]!!.left
else -> TODO()
}
index = (index + 1) % directions.length
steps++
}
steps
}.reduce { acc, l -> lcm(acc, l) }
}
| 0 | Kotlin | 0 | 0 | 70646b330cc1cea4828a10a6bb825212e2f0fb18 | 2,384 | advent-of-code-2023 | Apache License 2.0 |
src/Day03.kt | EnyediPeti | 573,882,116 | false | {"Kotlin": 8717} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val rucksack = convertToRucksack(it)
val item = findSameItem(rucksack)
getItemPriority(item)
}
}
fun part2(input: List<String>): Int {
return createElfGroupList(input).sumOf {
getItemPriority(getSameItemFromGroups(it))
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun createElfGroupList(input: List<String>): MutableList<MutableList<String>> {
val elfGroupList: MutableList<MutableList<String>> = mutableListOf()
var group: MutableList<String> = mutableListOf()
input.forEachIndexed { index, string ->
if (index % 3 == 0) {
group = mutableListOf()
}
group.add(string)
if (index % 3 == 2) {
elfGroupList.add(group)
}
}
return elfGroupList
}
fun getSameItemFromGroups(group: List<String>): Char {
val mergedString = group.joinToString("")
val groupedList = mergedString.groupBy { it }
val filteredList = groupedList.filter { it.value.size >= 3 }.map { it.key }
filteredList.forEach {
if (
group[0].contains(it) &&
group[1].contains(it) &&
group[2].contains(it)
) {
return it
}
}
return 'a'
}
fun convertToRucksack(string: String): Rucksack {
return Rucksack(
compartment1 = string.take(string.length / 2),
compartment2 = string.takeLast(string.length / 2)
)
}
fun findSameItem(rucksack: Rucksack): Char {
with(rucksack) {
return compartment1.first {
compartment2.contains(it)
}
}
}
fun getItemPriority(item: Char): Int {
return if (item.isLowerCase()) {
item - 'a' + 1
} else {
item - 'A' + 27
}
}
class Rucksack(val compartment1: String, val compartment2: String) | 0 | Kotlin | 0 | 0 | 845ef2275540a6454a97a9e4c71f239a5f2dc295 | 2,150 | AOC2022 | Apache License 2.0 |
src/Day02.kt | Nplu5 | 572,211,950 | false | {"Kotlin": 15289} | import GameResult.DRAW
import GameResult.LOOSE
import GameResult.WIN
import Sign.Companion.fromString
fun main() {
fun part1(input: List<String>): Int {
return input.map { line ->
line.split(" ").let { playPairs ->
Game(fromString(playPairs[0]), fromString(playPairs[1]))
}
}.sumOf { strategy ->
strategy.calculatePlayerOneScore()
}
}
fun part2(input: List<String>): Int {
return input.map { line ->
line.split(" ").let { playPairs ->
val playTwo = Strategy(playPairs[1]).getSecondPlay(fromString(playPairs[0]))
Game(fromString(playPairs[0]), playTwo)
}
}.sumOf { strategy ->
strategy.calculatePlayerOneScore()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
sealed class Sign{
protected abstract val score: Int
abstract fun scoreAgainst(enemySign: Sign): Int
abstract fun getDesiredResultSign(gameResult: GameResult): Sign
companion object{
fun fromString(code: String): Sign {
return when(code){
"X",
"A" -> Rock
"Y",
"B" -> Paper
"Z",
"C" -> Scissor
else -> throw IllegalArgumentException("Unknown code: $code")
}
}
}
protected val looseScore = 0
protected val drawScore = 3
protected val winScore = 6
}
object Rock: Sign(){
override val score: Int = 1
override fun scoreAgainst(enemySign: Sign): Int {
return when(enemySign){
Rock -> drawScore + score
Paper -> looseScore + score
Scissor -> winScore + score
}
}
override fun getDesiredResultSign(gameResult: GameResult): Sign {
return when(gameResult){
LOOSE -> Scissor
DRAW -> Rock
WIN -> Paper
}
}
}
object Paper: Sign(){
override val score: Int = 2
override fun scoreAgainst(enemySign: Sign): Int {
return when(enemySign){
Rock -> winScore + score
Paper -> drawScore + score
Scissor -> looseScore + score
}
}
override fun getDesiredResultSign(gameResult: GameResult): Sign {
return when(gameResult){
LOOSE -> Rock
DRAW -> Paper
WIN -> Scissor
}
}
}
object Scissor: Sign(){
override val score: Int = 3
override fun scoreAgainst(enemySign: Sign): Int {
return when(enemySign){
Rock -> looseScore + score
Paper -> winScore + score
Scissor -> drawScore + score
}
}
override fun getDesiredResultSign(gameResult: GameResult) :Sign {
return when(gameResult){
LOOSE -> Paper
DRAW -> Scissor
WIN -> Rock
}
}
}
class Game(private val playOne: Sign, private val playTwo: Sign){
fun calculatePlayerOneScore(): Int {
return playTwo.scoreAgainst(playOne)
}
}
enum class GameResult{
LOOSE,
DRAW,
WIN;
}
class Strategy(strategy: String){
private val desiredResult: GameResult
init {
desiredResult = when(strategy){
"X" -> LOOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException("Desired result unknown: $strategy")
}
}
fun getSecondPlay(playOne: Sign): Sign {
return playOne.getDesiredResultSign(desiredResult)
}
} | 0 | Kotlin | 0 | 0 | a9d228029f31ca281bd7e4c7eab03e20b49b3b1c | 3,742 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2022/Day24.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2022
import utils.Vertex
import utils.checkEquals
private enum class Dir { UP, DOWN, LEFT, RIGHT }
private typealias Tracking = Pair<Int, Vertex>
private val Tracking.minutes get() = first
private val Tracking.pos get() = second
private data class Blizzard(private var _pos: Vertex, val dir: Dir, val boundsRange: IntRange) {
val pos: Vertex
get() = _pos
fun moveAndGet(steps: Int = 1): Vertex {
_pos = when (dir) {
Dir.UP -> if (pos.up(steps).y in boundsRange) pos.up(steps) else pos.copy(y = boundsRange.last)
Dir.DOWN -> if (pos.down(steps).y in boundsRange) pos.down(steps) else pos.copy(y = 1)
Dir.LEFT -> if (pos.left(steps).x in boundsRange) pos.left(steps) else pos.copy(x = boundsRange.last)
Dir.RIGHT -> if (pos.right(steps).x in boundsRange) pos.right(steps) else pos.copy(x = 1)
}
return _pos
}
}
fun main() {
fun List<String>.goToExtractionPoint(directedScanTimes: Int = 1): Int {
val start = this.first().indexOfFirst { it == '.' }.let { Vertex(x = it, y = 0) }
val target = this.last().indexOfFirst { it == '.' }.let { Vertex(x = it, y = this.lastIndex) }
val xBounds = 1..this[1].trim('#').length
val yBounds = 1..this.drop(1).dropLast(1).size
val blizzards = this.flatMapIndexed { i, s ->
s.mapIndexedNotNull { j, c ->
val (dir, bounds) = when (c) {
'>' -> Dir.RIGHT to xBounds
'<' -> Dir.LEFT to xBounds
'v' -> Dir.DOWN to yBounds
'^' -> Dir.UP to yBounds
else -> return@mapIndexedNotNull null
}
return@mapIndexedNotNull Blizzard(_pos = Vertex(x = j, y = i), dir = dir, boundsRange = bounds)
}
}
val runningReduceMinutes = mutableListOf(0 to start)
repeat(directedScanTimes) {
val queue = ArrayDeque<Tracking>(listOf(runningReduceMinutes.last()))
val seen = hashSetOf<Tracking>()
val movesHistory = hashMapOf(0 to blizzards.map { it.pos }.toSet())
while (queue.any()) {
val expedition = queue.removeFirst()
if (expedition in seen) continue
seen += expedition
val next = movesHistory.computeIfAbsent(expedition.minutes + 1) {
blizzards.map { it.moveAndGet() }.toSet()
}
val neighbors = with(expedition.pos) { setOf(this@with, down(), right(), left(), up()) }
//only needed for second part, else its always target
val des = if (runningReduceMinutes.last().pos == start) target else start
if (des in neighbors) {
runningReduceMinutes.add(expedition.minutes + 1 to des)
break
}
neighbors.filter {
it == runningReduceMinutes.last().pos ||
(it.x in xBounds && it.y in yBounds && it !in next)
}
.map { expedition.minutes + 1 to it }.also(queue::addAll)
}
}
return runningReduceMinutes.last().minutes
}
fun part1(input: List<String>) = input.goToExtractionPoint()
fun part2(input: List<String>) = input.goToExtractionPoint(directedScanTimes = 3)
// parts execution
val testInput = readInput("Day24_test")
val input = readInput("Day24")
part1(testInput).checkEquals(18)
part1(input)
.checkEquals(225)
// .sendAnswer(part = 1, day = "24", year = 2022)
part2(testInput).checkEquals(54)
part2(input)
.checkEquals(711)
// .sendAnswer(part = 2, day = "24", year = 2022)
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 3,819 | Kotlin-AOC-2023 | Apache License 2.0 |
src/main/kotlin/com/sk/set0/39. Combination Sum.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set0
import java.util.*
// https://leetcode.com/problems/combination-sum/discuss/16502/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partitioning)
class Solution39 {
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
val res = ArrayList<ArrayList<Int>>()
backtrack(ArrayList(), target, 0, candidates, res)
return res
}
private fun backtrack(
path: ArrayList<Int>,
target: Int,
startIdx: Int,
candidates: IntArray,
ans: ArrayList<ArrayList<Int>>
) {
when {
target < 0 -> return
target == 0 -> ans.add(ArrayList(path)) // we got one answer, copy to final answer
else -> {
for (i in startIdx..candidates.lastIndex) {
path.add(candidates[i])
backtrack(path, target - candidates[i], i, candidates, ans)
path.removeAt(path.lastIndex) // remove current element, we have gone through this path
}
}
}
}
// https://leetcode.com/problems/combination-sum/solutions/16509/iterative-java-dp-solution/?envType=study-plan-v2&envId=top-interview-150
fun combinationSum2(cands: IntArray, t: Int): List<List<Int>> {
Arrays.sort(cands) // sort candidates to try them in asc order
val dp = ArrayList<ArrayList<ArrayList<Int>>>()
for (i in 1..t) { // run through all targets from 1 to t
val newList = ArrayList<ArrayList<Int>>() // combs for curr i
// run through all candidates <= i
var j = 0
while (j < cands.size && cands[j] <= i) {
// special case when curr target is equal to curr candidate
if (i == cands[j]){
newList.add(arrayListOf(cands[j]))
} else {
for (l in dp[i - cands[j] - 1]) {
if (cands[j] <= l[0]) {
val cl = ArrayList<Int>()
cl.add(cands[j])
cl.addAll(l)
newList.add(cl)
}
}
}
j++
}
dp.add(newList)
}
return dp[t - 1]
}
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,385 | leetcode-kotlin | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/fstaudt/aoc2021/day3/Day3.kt | fstaudt | 433,733,254 | true | {"Kotlin": 9482, "Rust": 1574} | package com.github.fstaudt.aoc2021.day3
import com.github.fstaudt.aoc2021.day3.Day3.BinaryCounter.Companion.toBinaryCounter
import com.github.fstaudt.aoc2021.shared.Day
import com.github.fstaudt.aoc2021.shared.readInputLines
fun main() {
Day3().run()
}
class Day3 : Day {
override val input = readInputLines(3)
override fun part1() = input.map { it.toBinaryCounter() }.fold(BinaryCounter()) { a, b -> a.plus(b) }.run { gamma() * epsilon() }
override fun part2() = oxygen() * co2()
private fun oxygen(): Int {
var data = input
var index = 0
while (data.size > 1 && data[0].length > index) {
val mostCommonBytes = data.map { it.toBinaryCounter() }.fold(BinaryCounter()) { a, b -> a.plus(b) }.mostCommonBytes()
data = data.filter { it.substring(index, index + 1) == "${mostCommonBytes[index]}" }
index++
}
return data.single().toInt(2)
}
private fun co2(): Int {
var data = input
var index = 0
while (data.size > 1 && data[0].length > index) {
val lessCommonBytes = data.map { it.toBinaryCounter() }.fold(BinaryCounter()) { a, b -> a.plus(b) }.lessCommonBytes()
data = data.filter { it.substring(index, index + 1) == "${lessCommonBytes[index]}" }
index++
}
return data.single().toInt(2)
}
data class BinaryCounter(val bytes: List<Int>? = null, val count: Int = 0) {
companion object {
fun String.toBinaryCounter() = BinaryCounter(toCharArray().map { it.digitToInt() })
}
fun plus(other: BinaryCounter): BinaryCounter {
return BinaryCounter(
bytes?.zip(other.bytes!!) { a, b -> a + b } ?: other.bytes,
count + 1)
}
fun gamma() = bytes!!.map { it.toMostCommon() }.joinToString("") { "$it" }.toInt(2)
fun epsilon() = bytes!!.map { it.toLessCommon() }.joinToString("") { "$it" }.toInt(2)
fun mostCommonBytes() = bytes!!.map { it.toMostCommon() }
fun lessCommonBytes() = bytes!!.map { it.toLessCommon() }
private fun Int.toMostCommon() = if (2 * this >= count) 1 else 0
private fun Int.toLessCommon() = 1 - toMostCommon()
}
}
| 0 | Kotlin | 0 | 0 | f2ee9bca82711bc9aae115400ecff6db5d683c9e | 2,258 | aoc2021 | MIT License |
src/com/kingsleyadio/adventofcode/y2023/Day08.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.lcm
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val (directions, network) = readInput(2023, 8).useLines { sequence ->
val lines = sequence.iterator()
val directions = lines.next()
lines.next()
val network = buildMap {
while (lines.hasNext()) {
val (src, dest) = lines.next().split(" = ")
val (left, right) = dest.substring(1..<dest.lastIndex).split(", ")
put(src, left to right)
}
}
directions to network
}
part1(directions, network)
part2(directions, network)
}
private fun part1(directions: String, network: Network) {
val moves = network.countMoves(directions, "AAA") { it == "ZZZ" }
println(moves)
}
private fun part2(directions: String, network: Network) {
val start = network.keys.filter { it.endsWith('A') }
val moves = start.map { s -> network.countMoves(directions, s) { it.endsWith('Z')} }
val result = moves.fold(1L) { acc, move -> lcm(acc, move.toLong()) }
println(result)
}
private inline fun Network.countMoves(directions: String, start: String, end: (String) -> Boolean): Int {
var moves = 0
var directionIndex = 0
var current = start
while (!end(current)) {
val direction = directions[directionIndex]
val (left, right) = getValue(current)
current = if (direction == 'L') left else right
directionIndex = (directionIndex + 1) % directions.length
moves++
}
return moves
}
private typealias Network = Map<String, Pair<String, String>>
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,685 | adventofcode | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.