path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-03.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2022, "03-input") val testInput1 = readInputLines(2022, "03-test1") println("Part1:") part1(testInput1).println() part1(input).println() println() println("Part2:") part2(testInput1).println() part2(input).println() } private fun part1(input: List<String>): Int { val sacks = input.map { val half = it.length / 2 it.substring(0, half) to it.substring(half) } return sacks.map { (a, b) -> (a.toSet() intersect b.toSet()).single() } .sumOf { priorities[it]!! } } private fun part2(input: List<String>): Int { val groups = input.map { it.toSet() }.windowed(3, 3) return groups.map { (a, b, c) -> a intersect b intersect c }.sumOf { priorities[it.single()]!! } } private val priorities = (('a'..'z') + ('A'..'Z')).mapIndexed { i, c -> c to i + 1 }.toMap()
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,032
advent-of-code
MIT License
src/main/day24/day24.kt
rolf-rosenbaum
572,864,107
false
{"Kotlin": 80772}
package day24 import Point import day24.Blizzard.DOWN import day24.Blizzard.LEFT import day24.Blizzard.RIGHT import day24.Blizzard.UP import day24.Blizzard.WALL import readInput typealias Valley = Map<Point, List<Blizzard>> private val initialValley = readInput("main/day24/Day24").toValley() private val maxX = initialValley.keys.maxOf { it.x } private val minX = initialValley.keys.minOf { it.x } private val maxY = initialValley.keys.maxOf { it.y } private val minY = initialValley.keys.minOf { it.y } private val start = initialValley.filter { it.key.y == minY }.keys.first { initialValley[it]!!.isEmpty() } private val exit = initialValley.filter { it.key.y == maxY }.keys.first { initialValley[it]!!.isEmpty() } private val walls = initialValley.filter { it.value.firstOrNull() == WALL } private val valleySequence = generateSequence(initialValley) { it.step() }.take(1000).toList() fun main() { println(part1()) println(part2()) } fun part1(): Int { return findPath() } fun part2(): Int { val toGoal = findPath() val backToStart = findPath(entry = exit, currentStep = toGoal, goal = start) return findPath(currentStep = backToStart) } fun findPath(entry: Point = start, currentStep: Int = 0, goal: Point = exit): Int { val pathsToCheck = mutableListOf(State(entry, currentStep)) val checked = mutableSetOf<State>() while (pathsToCheck.isNotEmpty()) { val current = pathsToCheck.removeFirst() if (current !in checked) { val nextValley = valleySequence[current.step + 1] val neighbours = validNeighboursFor(current.point).filter { nextValley.isOpenAt(it) } if (goal in neighbours) return current.step + 1 checked += current neighbours.forEach { pathsToCheck.add(State(it, current.step + 1)) } } } error("lost in the vally of blizzards") } fun List<String>.toValley(): Valley { val valley = mutableMapOf<Point, List<Blizzard>>() mapIndexed { y, line -> line.mapIndexed { x, c -> val p = Point(x, y) when (c) { '^' -> valley[p] = listOf(UP) 'v' -> valley[p] = listOf(DOWN) '<' -> valley[p] = listOf(LEFT) '>' -> valley[p] = listOf(RIGHT) '#' -> valley[p] = listOf(WALL) else -> valley[p] = emptyList() } } } return valley } fun validNeighboursFor(p: Point) = p.neighbours(true) .filterNot { it in walls } .filter { it.x in (minX..maxX) } .filter { it.y in (minY..maxY) } fun Valley.isOpenAt(p: Point): Boolean = this[p].isNullOrEmpty() fun Valley.step(): Valley = mutableMapOf<Point, MutableList<Blizzard>>( // start and goal must always be in the map start to mutableListOf(), exit to mutableListOf() ).let { result -> (minX..maxX).forEach { x -> (minY..maxY).forEach { y -> val here = Point(x, y) val blizzards = this[here] if (!blizzards.isNullOrEmpty()) { blizzards.forEach { blizzard -> var newLocation = here + blizzard.offset if (newLocation in walls) { newLocation = when (blizzard) { LEFT -> Point(maxX - 1, y) RIGHT -> Point(minX + 1, y) UP -> Point(x, maxY - 1) DOWN -> Point(x, minY + 1) WALL -> Point(x, y) // walls do not move } } if (result[newLocation] == null) result[newLocation] = mutableListOf(blizzard) else result[newLocation]!!.add(blizzard) } } } } result } enum class Blizzard(val offset: Point) { LEFT(Point(-1, 0)), RIGHT(Point(1, 0)), UP(Point(0, -1)), DOWN(Point(0, 1)), WALL(Point(0, 0)), } data class State(val point: Point, val step: Int)
0
Kotlin
0
2
59cd4265646e1a011d2a1b744c7b8b2afe482265
4,166
aoc-2022
Apache License 2.0
src/Day04.kt
fercarcedo
573,142,185
false
{"Kotlin": 60181}
val IntRange.size get() = if (last < first) { 0 } else { last - first + 1 } fun main() { fun calculateRangeIntersection(input: List<String>, intersectionPredicate: (Set<Int>, IntRange, IntRange) -> Boolean) = input.map { line -> val (firstRange, secondRange) = line.split(",").map { val parts = it.split("-").map { number -> number.toInt() } (parts[0]..parts[1]) } intersectionPredicate(firstRange intersect secondRange, firstRange, secondRange) }.count { it } fun part1(input: List<String>) = calculateRangeIntersection(input) { intersection, firstRange, secondRange -> intersection.size == minOf(firstRange.size, secondRange.size) } fun part2(input: List<String>) = calculateRangeIntersection(input) { intersection, _, _ -> intersection.isNotEmpty() } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) // 509 println(part2(input)) // 870 }
0
Kotlin
0
0
e34bc66389cd8f261ef4f1e2b7f7b664fa13f778
1,122
Advent-of-Code-2022-Kotlin
Apache License 2.0
src/Day04.kt
emanguy
573,113,840
false
{"Kotlin": 17921}
data class ElfRange(val start: Int, val stop: Int) { operator fun contains(other: ElfRange) = start <= other.start && stop >= other.stop infix fun partiallyIn(other: ElfRange) = start in other.start..other.stop || stop in other.start..other.stop } fun main() { fun parseInput(inputs: List<String>): List<Pair<ElfRange, ElfRange>> = inputs.map { val (firstAssignment, secondAssignment) = it.split(",") val (firstAssignmentStart, firstAssignmentEnd) = firstAssignment.split("-").map(String::toInt) val (secondAssignmentStart, secondAssignmentEnd) = secondAssignment.split("-").map(String::toInt) Pair( ElfRange(firstAssignmentStart, firstAssignmentEnd), ElfRange(secondAssignmentStart, secondAssignmentEnd) ) } fun part1(inputs: List<String>): Int { return parseInput(inputs).count { it.first in it.second || it.second in it.first } } fun part2(inputs: List<String>): Int { return parseInput(inputs).count { it.first partiallyIn it.second || it.second partiallyIn it.first } } // Verify the sample input works val inputs = readInput("Day04_test") check(part1(inputs) == 2) check(part2(inputs) == 4) val finalInputs = readInput("Day04") println(part1(finalInputs)) println(part2(finalInputs)) }
0
Kotlin
0
1
211e213ec306acc0978f5490524e8abafbd739f3
1,378
advent-of-code-2022
Apache License 2.0
packages/solutions/src/Day04.kt
ffluk3
576,832,574
false
{"Kotlin": 21246, "Shell": 85}
class Range { var min: Int var max: Int constructor(min: Int, max: Int) { this.min = min this.max = max } fun fullyContains(range: Range): Boolean { return (this.min <= range.min && this.max >= range.max) } fun overlaps(range: Range): Boolean { return (this.min <= range.min && this.max >= range.min) || (this.max >= range.max && this.min <= range.max) } } fun main() { fun getRanges(line: String): List<Range> { var ranges = mutableListOf<Range>() var rangeStrings = line.split(",") rangeStrings.forEach { val bounds = it.split("-") ranges.add(Range(bounds[0].toInt(), bounds[1].toInt())) } return ranges } fun part1(input: List<String>): Int { var subsets = 0 input.forEach { val ranges = getRanges(it) if (ranges[0].fullyContains(ranges[1]) || ranges[1].fullyContains(ranges[0])) { subsets += 1 } } return subsets } fun part2(input: List<String>): Int { var subsetsThatOverlap = 0 input.forEach { val ranges = getRanges(it) if (ranges[0].overlaps(ranges[1]) || ranges[1].overlaps(ranges[0])) { subsetsThatOverlap += 1 } } return subsetsThatOverlap } runAdventOfCodeSuite("Day04", ::part1, 2, ::part2, 4) }
0
Kotlin
0
0
f9b68a8953a7452d804990e01175665dffc5ab6e
1,452
advent-of-code-2022
Apache License 2.0
src/net/sheltem/aoc/y2023/Day07.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2023 import net.sheltem.common.count suspend fun main() { Day07().run() } class Day07 : Day<Long>(6440, 5905) { override suspend fun part1(input: List<String>): Long = input.map { line -> line.toPokerHand() }.sorted() .toWinnings() override suspend fun part2(input: List<String>): Long = input.map { line -> line.toPokerHand(true) }.sorted() .toWinnings() } private fun String.toPokerHand(jokerRule: Boolean = false) = this.split(" ").let { PokerHand(it.first(), it.last().toLong(), jokerRule) } private fun List<PokerHand>.toWinnings(): Long = this.foldIndexed(0L) { index, acc, pokerHand -> acc + ((index + 1) * pokerHand.bid) } private data class PokerHand(val hand: String, val bid: Long, val jokerRule: Boolean) : Comparable<PokerHand> { private val cards = listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2').let { if (jokerRule) it - 'J' + 'J' else it } val handCountMap = hand .groupingBy { it.toString() } .eachCount() val maxElement = handCountMap.minus("J").maxByOrNull { it.value } val handMap = if (!jokerRule || hand == "JJJJJ" || hand.count("J") == 0) handCountMap else handCountMap .minus("J") .minus(maxElement!!.key) .plus(maxElement.key.let { it to hand.count(it) + hand.count("J") }) val type: Int get() = when { handMap.size == 1 -> 7 // five of a kind handMap.values.contains(4) -> 6 // four of a kind handMap.size == 2 -> 5 // full house handMap.size == 3 && handMap.values.contains(3) -> 4 // triple handMap.size == 3 && handMap.values.count { it == 2 } == 2 -> 3 // two pair handMap.values.count { it == 2 } == 1 -> 2 // pair handMap.values.sum() == 5 -> 1 // high card else -> (-1).also { println("Could not determine type of $hand | $handCountMap | $handMap") } } override fun compareTo(other: PokerHand): Int = (this.type - other.type).let { typeDifference -> if (typeDifference == 0) { this.hand.zip(other.hand).map { cards.indexOf(it.second) - cards.indexOf(it.first) }.first { it != 0 } } else { typeDifference } } }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,385
aoc
Apache License 2.0
src/main/kotlin/Problem1.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import kotlin.system.measureNanoTime /** * Multiples of 3 or 5 * * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these * multiples is 23. * * Find the sum of all the multiples of 3 or 5 below 1000. * * https://projecteuler.net/problem=1 */ fun main() { val max = 999 val solution1Time = measureNanoTime { solution1(max) } val solution2Time = measureNanoTime { solution2(max) } println(solution1Time) println(solution2Time) } private fun solution1(limit: Int) { val res = (1 .. limit).asSequence() .filter { n -> n % 3 == 0 || n % 5 == 0 } .sum() println(res) } private fun solution2(limit: Int) { val res2 = sumDivisibleBy(3, limit) + sumDivisibleBy(5, limit) - sumDivisibleBy(15, limit) println(res2) } fun sumDivisibleBy(n: Int, max: Int): Int { // e.g. 3 + 6 + 9 + 12 + ... + 999 = 3 (1 + 2 + 3 + 4 + ... + 333) // 333 = 999 / 3 => p = max / n val p = max / n // 1 + 2 + 3 + 4 + ... + p = 1/2 * p * (p + 1) return (n * ( 0.5 * p * (p + 1))).toInt() }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
1,127
project-euler
MIT License
src/day05/Day05.kt
schrami8
572,631,109
false
{"Kotlin": 18696}
package day05 import readInput import java.util.LinkedList fun makeMovementsPart1(stacks: Array<LinkedList<Char>>, count: Int, from: Int, to: Int) { for (i in 1..count) { val toMove = stacks[from].first stacks[from].removeFirst() stacks[to].add(0, toMove) } } fun makeMovementsPart2(stacks: Array<LinkedList<Char>>, count: Int, from: Int, to: Int) { val toMove = stacks[from].take(count) stacks[to].addAll(0, toMove) for (i in 1..count) stacks[from].removeFirst() } fun collectStacks(stacks: Array<LinkedList<Char>>, line: String) { for (i in line.indices) { // fill default stacks if (line[i].isLetter()) { val index = i / 4 // get index of stack stacks[index].addLast(line[i]) } } } fun getTopOfEachStack(stacks: Array<LinkedList<Char>>): String { var topOfEachStack = "" for (stack in stacks) { if (stack.isNotEmpty()) topOfEachStack += stack.first ?: "" } return topOfEachStack } fun main() { fun part1(input: List<String>): String { val stacks = Array(input.first().length / 3) { _ -> LinkedList<Char>() } for (line in input) { if (!line.startsWith("move")) { collectStacks(stacks, line) } else { val movements = line.split(" ") makeMovementsPart1( stacks, movements[1].toInt(), movements[3].toInt() - 1, movements[5].toInt() - 1) } } return getTopOfEachStack(stacks) } fun part2(input: List<String>): String { val stacks = Array(input.first().length / 3) { _ -> LinkedList<Char>() } for (line in input) { if (!line.startsWith("move")) { collectStacks(stacks, line) } else { val movements = line.split(" ") makeMovementsPart2( stacks, movements[1].toInt(), movements[3].toInt() - 1, movements[5].toInt() - 1) } } return getTopOfEachStack(stacks) } // test if implementation meets criteria from the description, like: var testInput = readInput("day05/Day05_test") check(part1(testInput) == "CMZ") val input = readInput("day05/Day05") println(part1(input)) testInput = readInput("day05/Day05_test") check(part2(testInput) == "MCD") println(part2(input)) }
0
Kotlin
0
0
215f89d7cd894ce58244f27e8f756af28420fc94
2,571
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/Day19.kt
chjaeggi
728,738,815
false
{"Kotlin": 87254}
import Operator.GREATER_THAN import Operator.SMALLER_THAN import Status.* import utils.execFileByLine private enum class Status(value: String) { REJECTED("R"), ACCEPTED("A"), UNEVALUATED("") } private fun String.toStatus(): Status = when (this) { "A" -> ACCEPTED "R" -> REJECTED else -> UNEVALUATED } enum class Operator { GREATER_THAN, SMALLER_THAN } private fun Char.toOperator(): Operator = if (this == '<') SMALLER_THAN else GREATER_THAN private data class Workflow( val name: String, val rules: List<Rule>, ) private data class Part( val xmas: Map<Char, Int>, var status: Status = UNEVALUATED ) private data class Rule( val xmasField: Char?, val operator: Operator?, val limit: Int?, val nextWorkflowName: String ) class Day19 { private var solution = 0L fun solveFirst(): Int { val (workflows, parts) = parseInput() val startWorkflow = workflows["in"] parts.forEach { it.runWorkflow(startWorkflow!!, workflows) } return parts.filter { it.status == ACCEPTED }.sumOf { it.xmas.values.sum() } } fun solveSecond(): Long { val (workflows) = parseInput() val startRanges = mapOf( 'x' to 1..4000, 'm' to 1..4000, 'a' to 1..4000, 's' to 1..4000, ) workflows["in"]!!.runRange(startRanges, workflows) return solution } private fun Workflow.runRange( startRanges: Map<Char, IntRange>, allWorkflows: Map<String, Workflow>, ) { // use BFS with if and else clause results see [adjustedRange] val workflowNameAndRangesQueue = ArrayDeque<Pair<String, Map<Char, IntRange>>>() var runningRanges: Map<Char, IntRange>? = null for (rule in rules) { val rangeToTest = runningRanges ?: startRanges workflowNameAndRangesQueue.add(rule.nextWorkflowName to rule.adjustedRange(rangeToTest).first) runningRanges = rule.adjustedRange(rangeToTest).second } while (workflowNameAndRangesQueue.isNotEmpty()) { val nextWorkflowNameAndRangesQueue = workflowNameAndRangesQueue.removeFirst() if (nextWorkflowNameAndRangesQueue.first == "A") { var product = 1L nextWorkflowNameAndRangesQueue.second.values.forEach { product *= it.last.toLong() - it.first.toLong() + 1 } solution += product continue } if (nextWorkflowNameAndRangesQueue.first == "R") { continue } allWorkflows[nextWorkflowNameAndRangesQueue.first]!!.runRange( nextWorkflowNameAndRangesQueue.second, allWorkflows ) } } // return a pair of if to else case = pair of range for the if-clause and range for else-clause private fun Rule.adjustedRange(map: Map<Char, IntRange>): Pair<Map<Char, IntRange>, Map<Char, IntRange>> { if (operator == null) { return map to map } val rest = "xmas".filterNot { it == xmasField } if (operator == SMALLER_THAN) { return buildMap { put(xmasField!!, map[xmasField]!!.first..<limit!!) rest.forEach { put(it, map[it]!!) } } to buildMap { put(xmasField!!, limit!!..<map[xmasField]!!.last + 1) rest.forEach { put(it, map[it]!!) } } } else if (operator == GREATER_THAN) { return buildMap { put(xmasField!!, limit!! + 1..<map[xmasField]!!.last + 1) rest.forEach { put(it, map[it]!!) } } to buildMap { put(xmasField!!, map[xmasField]!!.first..<limit!! + 1) rest.forEach { put(it, map[it]!!) } } } throw IllegalStateException("not possible") } private fun Part.runWorkflow(current: Workflow, workflows: Map<String, Workflow>) { for (rule in current.rules) { if (this.status == UNEVALUATED && evaluateRule(rule)) { val next = rule.nextWorkflowName if (next.toStatus() == REJECTED || next.toStatus() == ACCEPTED) { status = next.toStatus() break } else { runWorkflow(workflows[next]!!, workflows) } } } } private fun Part.evaluateRule(rule: Rule): Boolean { if (rule.xmasField == null || rule.limit == null || rule.operator == null) { return true } if (rule.operator == GREATER_THAN) { if (xmas[rule.xmasField]!! > rule.limit) { return true } } else { if (xmas[rule.xmasField]!! < rule.limit) { return true } } return false } private fun parseInput(): Pair<Map<String, Workflow>, List<Part>> { var isWorkflowLine = true val workflows = mutableMapOf<String, Workflow>() val parts = mutableListOf<Part>() execFileByLine(19) { if (it.isBlank()) { isWorkflowLine = false } else { if (isWorkflowLine) { val name = it.substringBefore("{") val instructions = it.substringAfter("{") .removeSuffix("}") .split(",") val rules = instructions.flatMap { if (it.contains(":")) { it.split(",").map { Rule( it[0], it[1].toOperator(), it.substring(2, it.indexOfFirst { it == ':' }).toInt(), it.substringAfter(":") ) } } else { listOf(Rule(null, null, null, it)) } } workflows[name] = Workflow(name, rules) } else { val groups = it.removeSuffix("}").removePrefix("{").split(',') val xValue = groups[0].substringAfter("=").toInt() val mValue = groups[1].substringAfter("=").toInt() val aValue = groups[2].substringAfter("=").toInt() val sValue = groups[3].substringAfter("=").toInt() parts.add( Part( xmas = mapOf( 'x' to xValue, 'm' to mValue, 'a' to aValue, 's' to sValue ) ) ) } } } return workflows to parts } }
0
Kotlin
1
1
a6522b7b8dc55bfc03d8105086facde1e338086a
7,241
aoc2023
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch3/Problem32.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch3 import dev.bogwalk.util.combinatorics.permutations import dev.bogwalk.util.strings.isPandigital /** * Problem 32: Pandigital Products * * https://projecteuler.net/problem=32 * * Goal: Find the sum of all products whose identity expression can be written as an * N-pandigital number. * * Constraints: 4 <= N <= 9 * * Pandigital Number: An N-digit number that uses all digits from 1 to N exactly once, * e.g. N = 5 -> 15234. * * Identity expression: 39(multiplicand) * 186(multiplier) = 7254(product). * Therefore, 7254 is a product of a pandigital identity expression. * * e.g.: N = 4 * identities = {3 * 4 = 12} * sum = 12 */ class PandigitalProducts { /** * Solution uses helper permutations() to assess all arrangements of the required digits for * a valid identity expression. * * SPEED (WORSE) 884.66ms for N = 9 */ fun sumPandigitalProductsAllPerms(n: Int): Int { // stored as set to ensure no duplicate permutation results val products = mutableSetOf<Int>() // neither multiplicand nor multiplier can have more digits than product val prodMaxDigits = when (n) { 8, 9 -> 4 7 -> 3 else -> 2 } for (perm in permutations(('1'..n.digitToChar()))) { // if multiplicand has 1 digit, it would be found at index 0 for (a in 1..2) { // find start index of product based on multiplicand & product digits val pIndex = a + minOf(prodMaxDigits, n - prodMaxDigits - a) val multiplicand = perm.slice(0 until a) .joinToString("") .toInt() val multiplier = perm.slice(a until pIndex) .joinToString("") .toInt() val product = perm.slice(pIndex..perm.lastIndex) .joinToString("") .toInt() if (multiplicand * multiplier == product) { products.add(product) break } // expressions with < 7 digits can only have multiplier be 1 digit if (n < 7) break } } return products.sum() } /** * Iterative solution assesses the pandigital quality of all identity expressions produced by * multiplier, multiplicand combinations within a specified limit. * * SPEED (BETTER) 97.43ms for N = 9 */ fun sumPandigitalProductsBrute(n: Int): Int { // stored as set to ensure no duplicate permutation results val products = mutableSetOf<Int>() val multiplicandRange = if (n < 7) 2..9 else 2..98 val multiplierMax = when (n) { 8 -> 987 9 -> 9876 else -> 98 } for (a in multiplicandRange) { for (b in (a+1)..multiplierMax) { val prod = a * b if ("$a$b$prod".isPandigital(n)) { products.add(prod) } } } return products.sum() } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,154
project-euler-kotlin
MIT License
src/main/kotlin/Skew.kt
nkkarpov
605,326,618
false
null
import kotlin.math.max fun Uniform(environment: DistributedEnvironment, m: Int, K: Int, T: Int): List<Int> { val cnt = Array(environment.n) { DoubleArray(K) { 0.0 } } val est = Array(environment.n) { DoubleArray(K) { 0.0 } } for (agent in 0 until K) { for (arm in 0 until environment.n) { repeat(T / environment.n) { est[arm][agent] += environment.pull(arm, agent) cnt[arm][agent] += 1.0 } } } val Q = est.indices.sortedBy { est[it].sum() / cnt[it].sum() }.reversed().take(m + 1) println("U,$K,$T,${if (Q.sorted() == (0..m).toList()) 1 else 0},${environment.n * K}") return Q } fun top(environment: DistributedEnvironment, m: Int, K: Int, B: Int): List<Int> { val cnt = Array(environment.n) { DoubleArray(K) { 0.0 } } val est = Array(environment.n) { DoubleArray(K) { 0.0 } } var cntWords = 0 val n = emptyList<Int>().toMutableList() fun mean(arm: Int, agent: Int) = est[arm][agent] / cnt[arm][agent] val Q = mutableListOf<Int>() var I = (0 until environment.n).toMutableList() var t = environment.n while (t > 1) { n.add(t) t /= 2 } n.add(0) fun compute(n: List<Int>, budget: Int): List<Int> { val R = IntArray(n.size - 1) { 0 } var left = 0.toDouble() var right = budget.toDouble() repeat(60) { val ave = (left + right) / 2 for (i in R.indices) { R[i] = (ave / n[i]).toInt() } if (R.indices.sumOf { R[it] * n[it] } <= budget) { left = ave } else { right = ave } } for (i in R.indices) { R[i] = (left / n[i]).toInt() } return R.toList() } val T = compute(n, B) val means = DoubleArray(environment.n) { 0.0 } val delta = DoubleArray(environment.n) { 0.0 } for (r in T.indices) { cntWords += 2 * I.size * K for (agent in 0 until K) { for (arm in 0 until environment.n) { repeat(T[r]) { est[arm][agent] += environment.pull(arm, agent) cnt[arm][agent] += 1.0 } } } for (arm in I) { means[arm] = (0 until K).sumOf { mean(arm, it) } / K } I.sortBy { -means[it] } // println(Q) val m0 = m - Q.size if (m0 < 0) continue val a = means[m0] val b = means[m0 + 1] for (arm in I) delta[arm] = max(a - means[arm], means[arm] - b) I.sortBy { delta[it] } // println(I) // println(I.map { means[it] }) Q.addAll(I.drop(n[r + 1]).filter { means[it] > b }) I = I.take(n[r + 1]).toMutableList() } println("T,$K,$B,${if (Q.sorted() == (0..m).toList()) 1 else 0},$cntWords") return Q }
0
Kotlin
0
0
f0dd06b07bf9ebc5bc199c5280e63103189f5397
2,901
collab-comm
MIT License
src/main/kotlin/dev/bogwalk/batch8/Problem90.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch8 import dev.bogwalk.util.combinatorics.combinations /** * Problem 90: Cube Digit Pairs * * https://projecteuler.net/problem=90 * * Goal: Count the distinct arrangements of M cubes that allow for all square numbers [1, N^2] to * be displayed. * * Constraints: 1 <= M <= 3, 1 <= N < 10^(M/2) * * The 6 faces of each cube has a different digit [0, 9]] on it. Placing the cubes side-by-side * in any order creates a variety of M-digit square numbers <= N^2. For example, when 2 cubes * are used, the arrangement {0, 5, 6, 7, 8, 9} and {1, 2, 3, 4, 6, 7} allows all squares <= 81; * Note that "09" is achievable because '6' can be flipped to represent '9'. * * Arrangements are considered distinct if the combined cubes have different numbers, * regardless of differing order. Note that cubes can share the same numbers as long as they * still are able to display all expected squares. * * e.g.: M = 1, N = 3 * Cube must have {1, 4, 6} or {1, 4, 9} at minimum * Of all possible digit combinations, 55 match this requirement */ class CubeDigitPairs { fun countValidCubes(maxSquare: Int, cubes: Int): Int { val squares = getSquares(maxSquare, cubes) var count = 0 // '9' is represented by '6' for ease of validity check within block val allCubes = combinations("0123456786".toList(), 6).toList() // avoid duplicate arrangements by limiting iteration to only larger cubes for ((i, cube1) in allCubes.withIndex()) { if (cubes > 1) { // must include equivalent cubes for cases when N is lower for (j in i..allCubes.lastIndex) { val cube2 = allCubes[j] // at least 1 cube must have '0' by now, regardless of N value // any further combos will be larger and not include '0' if (cube1[0] != '0' && cube2[0] != '0') break if (cubes > 2) { for (k in j..allCubes.lastIndex) { val cube3 = allCubes[k] // both smaller cubes must have '0' as cube3 will be larger if ((cube1[0] == '0') xor (cube2[0] == '0')) break if (squares.all { it[0] in cube1 && it[1] in cube2 && it[2] in cube3 || it[0] in cube1 && it[1] in cube3 && it[2] in cube2 || it[0] in cube2 && it[1] in cube1 && it[2] in cube3 || it[0] in cube2 && it[1] in cube3 && it[2] in cube1 || it[0] in cube3 && it[1] in cube2 && it[2] in cube1 || it[0] in cube3 && it[1] in cube1 && it[2] in cube2 }) { count++ } } } else { // 2 cubes cannot be equivalent when expected to show squares >= 36 // as amount of necessary digits will exceed 6 if (maxSquare > 5 && cube1 == cube2) continue // 2 cubes cannot display > 9^2 if (squares.all { it[0] in cube1 && it[1] in cube2 || it[0] in cube2 && it[1] in cube1 }) { count++ } } } } else { // one cube cannot display > 3^2 if (squares.all { it[0] in cube1 }) count++ } } return count } /** * Generates a list of square numbers with all '9' represented by '6' and appropriately padded * with leading zeroes. * * Note that certain squares have been removed to avoid redundancy: * 8^2 = 64 = 46 * 10^2 = 100 = 001 * 14^2 = 196 = 31^2 = 961 = 166 * 20^2 = 400 = 004 * 21^2 = 441 = 144 * 23^2 = 529 = 25^2 = 625 = 256 * 30^2 = 900 = 006 */ private fun getSquares(maxN: Int, cubes: Int): List<String> { val squares = mutableListOf<String>() for (i in 1..maxN) { if (i in listOf(8, 10, 14, 20, 21, 23, 25, 30, 31)) continue squares.add((i * i).toString() .replace('9', '6') .padStart(cubes, '0') ) } return squares } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
4,632
project-euler-kotlin
MIT License
main/src/day_3/App.kt
vmariano
434,035,667
false
{"Kotlin": 6341}
package day_3 class MatrixHelpers { companion object { fun reduceMatrix(readsMatrix: Array<Array<String>>, filterIndexes: MutableList<Int>): Array<Array<String>> { val newMatrix = Array(readsMatrix.size) { Array(filterIndexes.size) { "" } } val columnSize = readsMatrix.size for (j in 0 until columnSize) { filterIndexes.forEachIndexed { i, column -> newMatrix[j][i] = readsMatrix[j][column] } } return newMatrix } fun transformMatrixToNumber(readsMatrix: Array<Array<String>>): Int = readsMatrix.reduce { a, c -> a + c[0] }.reduce { a, c -> a + c }.toInt(2) fun transposeInput(input: List<String>): Array<Array<String>> { val numberSize = input.first().length val readsMatrix = Array(numberSize) { Array(input.size) { "" } } input.forEachIndexed { i, number -> val slicesItem = number.split("").filterNot { it.equals("") } slicesItem.forEachIndexed { j, item -> readsMatrix[j][i] = item } } return readsMatrix } fun filterIndexes(row: Array<String>, filterCriteria: String): MutableList<Int> { val filterIndexes = mutableListOf<Int>() row.forEachIndexed() { i, number -> if (number == filterCriteria) { filterIndexes.add(i) } } return filterIndexes } } } fun main() { //--- Part One --- println(partOne()) //--- Part Two --- println(partTwo()) } fun partTwo(): Int { return oxygenGenerationRating() * CO2ScrubberRating() } fun CO2ScrubberRating(): Int { val readsMatrix = MatrixHelpers.transposeInput(FileHelper.loadInputFile("day_3/input.txt")) return filterC02Rating(readsMatrix, 0)} fun filterC02Rating(readsMatrix: Array<Array<String>>, rowIndex: Int): Int { if (readsMatrix[0].size == 1) { return MatrixHelpers.transformMatrixToNumber(readsMatrix) } val row = readsMatrix[rowIndex] val (match, rest) = row.partition { it == ("0") } val filterCriteria = if (match.size <= rest.size) "0" else "1" val filterIndexes = MatrixHelpers.filterIndexes(row, filterCriteria) val newMatrix = MatrixHelpers.reduceMatrix(readsMatrix, filterIndexes) return filterC02Rating(newMatrix, rowIndex+1) } fun oxygenGenerationRating(): Int { val readsMatrix = MatrixHelpers.transposeInput(FileHelper.loadInputFile("day_3/input.txt")) return filterOxygenConditions(readsMatrix, 0) } fun filterOxygenConditions(readsMatrix: Array<Array<String>>, rowIndex: Int): Int { if (readsMatrix[0].size == 1) { return MatrixHelpers.transformMatrixToNumber(readsMatrix) } val row = readsMatrix[rowIndex] val (match, rest) = row.partition { it == ("1") } val filterCriteria = if (match.size >= rest.size) "1" else "0" val filterIndexes = MatrixHelpers.filterIndexes(row, filterCriteria) val newMatrix = MatrixHelpers.reduceMatrix(readsMatrix, filterIndexes) return filterOxygenConditions(newMatrix, rowIndex+1) } fun partOne(): Int { return gammaRate().toInt(2) * epsilonRate().toInt(2) } fun epsilonRate(): String { val readsMatrix = MatrixHelpers.transposeInput( FileHelper.loadInputFile("day_3/input.txt")) var result = "" readsMatrix.forEach { result += if (it.filter { it.equals("1") }.size > it.filter { it.equals("0") }.size) { "0" } else { "1" } } return result } fun gammaRate(): String { val readsMatrix = MatrixHelpers.transposeInput( FileHelper.loadInputFile("day_3/input.txt")) var result = "" readsMatrix.forEach { result += if (it.filter { it.equals("1") }.size > it.filter { it.equals("0") }.size) { "1" } else { "0" } } return result }
0
Kotlin
0
0
68f5be206070143f99c533252e8872e9e71481ef
4,002
advent-of-code-2021
MIT License
src/UsefulStuff.kt
eleung4
574,590,563
false
{"Kotlin": 7285}
fun main() { val input = readInput("numbers") println("Sum: ${sumAllNums(input)}") println("Min: ${findMin(input)}") println("Sum two smallest nums: ${findTwoSmallest(input)}") println("Number of words: ${countWords(wordInput)}") } fun sumAllNums(input: List<String>) : Int { // var total = 0 // for(x in input) { // total += x.toInt() // } // return total return input.map { it.toInt() }.sum() } fun findMin(input : List<String>) : Int { var min = Integer.MAX_VALUE for(x in input) { if(x.toInt()<min) { min = x.toInt() } } return min // return input.map { it.toInt() }.min() } fun findTwoSmallest(input : List<String>) : Int { val sorted = input.map { it.toInt() }.sorted() println(sorted.take(2)) return input.map {it.toInt() }.sorted().take(2).sum() // return sorted[0] + sorted[1] } val wordInput = readInput("sentences") // a word is any string that doesn't contain a space fun countWords(input : List<String>) : Int { var count = 0 for(i in input.indices) { val words = input[0].split( " ") println(words) count += words.size } return count } fun countHWords(input : List < String>) : Int { var count = 0 for (line in input) { val words = line.split(" ") for(i in words.indices) { if(words[i].startsWith("h")) count++ } } return count } // //fun countHWords(input : List<String>) : Int { // var count = 0 // for(line in input) { // count+=line.split(" ").count { // it.startsWith(" h", ignoreCase = true) // } // } // return count //} // for (i in 0<...<input.size-1) // for (i in 0 < until <input.size) // for (i in input.indices)
0
Kotlin
0
0
9013be242f7c2a13f73b297eee9be60655b531ac
1,799
AdventOfCode
Apache License 2.0
src/main/kotlin/kt/kotlinalgs/app/graph/TravellingSalesman.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph Solution().test() data class DirectedWeightedGraphWithAdjMatrix(val matrix: Array<IntArray>) class Solution { fun test() { println("Test") val graph = DirectedWeightedGraphWithAdjMatrix( arrayOf( intArrayOf(0, 10, 15, 20), intArrayOf(10, 0, 35, 25), intArrayOf(15, 35, 0, 30), intArrayOf(20, 25, 30, 0) ) ) val ts = TravellingSalesman() val trip = ts.shortestRoundtrip(graph, 0) println(trip) } } // https://www.geeksforgeeks.org/traveling-salesman-problem-tsp-implementation/ // Time: O(N * N!) // Space: O(N) class TravellingSalesman { fun shortestRoundtrip(graph: DirectedWeightedGraphWithAdjMatrix, start: Int): PathWithSum { val visited = BooleanArray(graph.matrix.size) val path: MutableList<Int> = mutableListOf() return shortestRoundtripRec(graph, start, start, visited, path, 0) } private fun shortestRoundtripRec( graph: DirectedWeightedGraphWithAdjMatrix, start: Int, cur: Int, visited: BooleanArray, path: MutableList<Int>, sum: Int ): PathWithSum { visited[cur] = true path.add(cur) if (graph.matrix.size == path.size) { // include starting point as ending point again path.add(start) val pathWithSum = PathWithSum(path.toMutableList(), sum + graph.matrix[cur][start]) path.removeAt(path.lastIndex) // remove end path.removeAt(path.lastIndex) // remove last city before end visited[cur] = false return pathWithSum } var shortest = PathWithSum(path, Int.MAX_VALUE) graph.matrix.indices.forEach { // no self-loops, early returns to start, or revisits: if (it == cur || it == start || visited[it]) return@forEach val candidate = shortestRoundtripRec( graph, start, it, visited, path, sum + graph.matrix[cur][it] ) shortest = if (candidate.sum < shortest.sum) candidate else shortest } path.remove(cur) visited[cur] = false return shortest } data class PathWithSum( val path: MutableList<Int>, val sum: Int ) }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
2,371
KotlinAlgs
MIT License
src/Day01.kt
petitJAM
572,737,836
false
{"Kotlin": 4868, "Shell": 749}
fun main() { fun part1(input: List<String>): Int { return input .map(String::toIntOrNull) .fold(emptyList<List<Int>>()) { acc, i -> if (i == null) { acc + listOf(emptyList()) } else { acc.dropLast(1) + listOf((acc.lastOrNull() ?: emptyList()) + i) } } .maxOfOrNull { it.sum() } ?: -1 } fun part2(input: List<String>): Int { return input .asSequence() .map(String::toIntOrNull) .fold(emptyList<List<Int>>()) { acc, i -> if (i == null) { acc + listOf(emptyList()) } else { acc.dropLast(1) + listOf((acc.lastOrNull() ?: emptyList()) + i) } } .sortedByDescending(List<Int>::sum) .take(3) .sumOf(List<Int>::sum) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24_000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1965ded0e0ad09b77e001b1b87ac48f47066f479
1,208
adventofcode2022
Apache License 2.0
src/Day05.kt
derivz
575,340,267
false
{"Kotlin": 6141}
import java.util.ArrayDeque fun main() { fun getState(lines: String): Map<Int, ArrayDeque<Char>> { val state = mutableMapOf<Int, ArrayDeque<Char>>() val rules = lines.split("\n\n")[0].split("\n").reversed() val size = rules[0].length rules.map { it.padEnd(size) }.map { it.toCharArray().toList() }.transpose().filter { it[0].isDigit() }.map { it.filter { it != ' ' } }.map { val key = it[0].toString().toInt() val value = it.drop(1).toMutableList() state[key] = value.reversed().toCollection(ArrayDeque()) } return state.toMap() } fun getMove(line: String): List<Int> { return Regex("(\\d+)").findAll(line).map { it.value.toInt() }.toList().slice(0..2) } fun part1(rules: String, lines: String): String { val state = getState(rules) lines.split('\n').forEach { line -> val (num, from, to) = getMove(line) repeat(num) { val value = state[from]!!.pop() state[to]!!.push(value) } } return state.map { it.value.first }.joinToString("") } fun part2(rules: String, lines: String): String { val state = getState(rules) lines.split('\n').forEach { line -> val (num, from, to) = getMove(line) val values = mutableListOf<Char>() repeat(num) { values.add(state[from]!!.pop()) } values.reversed().forEach { state[to]!!.push(it) } } return state.map { it.value.first }.joinToString("") } val input = readInput("Day05") val (rules, moves) = input.split("\n\n").slice(0..1) println(part1(rules, moves)) println(part2(rules, moves)) }
0
Kotlin
0
0
24da2ff43dc3878c4e025f5b737dca31913f40a5
1,746
AoC2022.kt
Apache License 2.0
src/main/kotlin/com/adventofcode/Day06.kt
keeferrourke
434,321,094
false
{"Kotlin": 15727, "Shell": 1301}
package com.adventofcode private const val DAYS_TO_REPRODUCE = 7 private const val DAYS_TO_MATURE = 2 data class Generation(val distribution: Map<Int, Long>) { private fun fillGaps(sparseMap: Map<Int, Long>): Map<Int, Long> { val result = mutableMapOf<Int, Long>() for (i in 0..DAYS_TO_MATURE + DAYS_TO_REPRODUCE) { result[i] = sparseMap[i] ?: 0 } return result } val size: Long = distribution.values.sum() fun next(): Generation { val generation = fillGaps(distribution).toSortedMap().values.toList() val toReproduce = generation[0] val nextGeneration = generation.drop(1).toMutableList() nextGeneration[DAYS_TO_REPRODUCE - 1] += toReproduce nextGeneration[DAYS_TO_REPRODUCE + DAYS_TO_MATURE - 1] = toReproduce return Generation(nextGeneration.mapIndexed { idx, it -> idx to it }.toMap()) } } fun computeFishPopulation(input: String, afterDays: Int = 80) = computeFishPopulation(parse(input), afterDays) private fun computeFishPopulation(initialPopulation: List<Int>, afterDays: Int = 80): Long { val populationFreqMap = initialPopulation.groupingBy { it } .eachCount() .map { (k, v) -> k to v.toLong() } .toMap() var generation = Generation(populationFreqMap) for (i in 1..afterDays) { generation = generation.next() } return generation.size } private fun parse(input: String): List<Int> = input.lineSequence() .flatMap { it.split(",") } .map { it.toInt() } .toList() fun day06(input: String, args: List<String> = listOf()) { when (args[0].lowercase()) { "p1" -> computeFishPopulation(input, 80) "p2" -> computeFishPopulation(input, 256) } }
0
Kotlin
0
0
44677c6ae0ba1a8a8dc80dfa68c17b9c315af8e2
1,661
aoc2021
ISC License
src/Day15Part2.kt
rosyish
573,297,490
false
{"Kotlin": 51693}
import kotlin.math.abs import kotlin.math.max class Day15Part2 { companion object { fun main() { val regex = Regex("-?\\d+") val input = readInput("Day15_input") val multiplier = 4000000 val maxRange = multiplier val sensors = input.asSequence() .mapNotNull { regex.findAll(it).toList() } .map { match -> val (sensorPt, beaconPt) = match .map { it.groupValues.first().toInt() } .chunked(2) .map { Pair(it[0], it[1]) } Sensor(sensorPt, beaconPt) } .toList() val result = sequence { for (y in 0..maxRange) { sensors .mapNotNull { sensor -> sensor.getNonDistressSegment(y) } .sortedWith { p1, p2 -> if (p1.first != p2.first) p1.first - p2.first else p1.second - p2.second } .fold(ArrayDeque<Pair<Int, Int>>()) { merged, interval -> val last = merged.lastOrNull() if (last != null && interval.first in last.first..last.second) { merged.removeLast() merged.add(Pair(last.first, max(last.second, interval.second))) } else { merged.add(interval) } merged } .let { it.zipWithNext().mapNotNull { pairs -> val (p1, p2) = pairs if (p2.first - p1.second > 1) Pair(p1.second + 1, p2.first - 1) else null } } .firstOrNull()?.let { yield(1L * it.first * multiplier + y) } } } println(result.first()) } } private data class Sensor(val position: Pair<Int, Int>, val nearestBeacon: Pair<Int, Int>) { fun getNonDistressSegment(y: Int): Pair<Int, Int>? { val distance = abs(position.first - nearestBeacon.first) + abs(position.second - nearestBeacon.second) val dx = distance - abs(y - position.second) if (dx < 0) return null return Pair(position.first - dx, position.first + dx) } } } fun main() { Day15Part2.main() }
0
Kotlin
0
2
43560f3e6a814bfd52ebadb939594290cd43549f
2,701
aoc-2022
Apache License 2.0
src/y2023/Day13.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.readInput import util.split import util.timingStatistics import util.transpose object Day13 { private fun parse(input: List<String>): List<List<String>> { return input.split { it.isBlank() } } fun part1(input: List<String>): Int { val parsed = parse(input) return parsed.sumOf { block -> val row = reflectionRow(block) val col = reflectionRow(block.map { it.toList() }.transpose()) if (row == null && col != null) { col } else if (col == null && row != null) { row * 100 } else if (col != null && row != null) { println("found both: $col, $row") col } else { error("no solution found") } } } fun <T> reflectionRow(rows: List<T>): Int? { val candidates = rows.zipWithNext().mapIndexedNotNull { idx, (row1, row2) -> if (row1 == row2) idx else null } return candidates.firstNotNullOfOrNull { verify(it + 1, rows) } } fun <T> verify(rowNumber: Int, rows: List<T>): Int? { val zip = rows.take(rowNumber).reversed().zip(rows.drop(rowNumber)) return if (zip.all { (row1, row2) -> row1 == row2 }) rowNumber else null } fun part2(input: List<String>): Int { val parsed = parse(input) return parsed.sumOf { block -> val chars = block.map { it.toList() } val row = offByOneReflectionRow(chars) val col = offByOneReflectionRow(chars.transpose()) if (row == null && col != null) { col } else if (col == null && row != null) { row * 100 } else if (col != null && row != null) { println("found both: $col, $row") col } else { error("no solution found") } } } fun offByOneReflectionRow(rows: List<List<Char>>): Int? { return rows.indices.firstOrNull { idx -> countErrors(rows.take(idx).reversed().zip(rows.drop(idx))) == 1 } } private fun countErrors(zip: List<Pair<List<Char>, List<Char>>>): Int { return zip.sumOf { (row1, row2) -> row1.zip(row2).count { (c1, c2) -> c1 != c2 } } } } fun main() { val testInput = """ #.##..##. ..#.##.#. ##......# ##......# ..#.##.#. ..##..##. #.#.##.#. #...##..# #....#..# ..##..### #####.##. #####.##. ..##..### #....#..# """.trimIndent().split("\n") println("------Tests------") println(Day13.part1(testInput)) println(Day13.part2(testInput)) println("------Real------") val input = readInput(2023, 13) println("Part 1 result: ${Day13.part1(input)}") println("Part 2 result: ${Day13.part2(input)}") timingStatistics { Day13.part1(input) } timingStatistics { Day13.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
3,056
advent-of-code
Apache License 2.0
src/main/kotlin/io/github/aarjavp/aoc/day13/Day13.kt
AarjavP
433,672,017
false
{"Kotlin": 73104}
package io.github.aarjavp.aoc.day13 import io.github.aarjavp.aoc.readFromClasspath import io.github.aarjavp.aoc.split class Day13 { data class Location(val x: Int, val y: Int) class Grid { companion object { const val MISSING_CHAR = '.' const val DOT_CHAR = '#' } private val state: MutableMap<Int, MutableSet<Int>> = mutableMapOf() // row to col (y, x) var rows: Int = 0 private set var columns: Int = 0 private set fun countPoints(): Int = state.values.sumOf { it.size } fun put(x: Int, y: Int) { state.computeIfAbsent(y) { mutableSetOf() }.add(x) rows = maxOf(y + 1, rows) columns = maxOf(x + 1, columns) } fun foldX(along: Int) { require(along < columns) { "unexpected fold outside of current grid. Current size: rows=$rows, columns=$columns, requested: $along" } for (row in state.values) { val toFlip = row.filter { it > along }.map { along - (it - along) } row.removeIf { it >= along } row.addAll(toFlip) } columns = along } fun foldY(along: Int) { require(along < rows) { "unexpected fold outside of current grid. Current size: rows=$rows, columns=$columns, requested: $along" } for ((row, cols) in state.filter { it.key > along }) { val newRow = along - (row - along) val newCols = state.computeIfAbsent(newRow) { mutableSetOf() } newCols.addAll(cols) } state.keys.removeIf { it >= along } rows = along } override fun toString(): String { return StringBuilder(rows * (columns + 1)).apply { for (row in 0 until rows) { val cols = state[row] if (cols == null) { repeat(columns) { append(MISSING_CHAR) } } else { for (col in 0 until columns) { val charToUse = if (col in cols) { DOT_CHAR } else { MISSING_CHAR } append(charToUse) } } appendLine() } }.toString() } } // returns grid and list of fold instructions fun parseInput(input: Sequence<String>): Pair<Grid, List<String>> { val (gridInput, foldInput) = input.split { it.isBlank() }.toList() val grid = parseGrid(gridInput) return grid to foldInput } fun parseGrid(lines: List<String>): Grid { val grid = Grid() for (line in lines) { val (x,y) = line.splitToSequence(",").map { it.toInt() }.toList() grid.put(x, y) } return grid } fun applyFolds(grid: Grid, foldInstructions: Iterable<String>) { for (foldInstruction in foldInstructions) { val line = foldInstruction.substringAfterLast('=').toInt() if (foldInstruction.startsWith("fold along y")) { grid.foldY(line) } else { grid.foldX(line) } } } } fun main() { val solution = Day13() val (grid, foldInstructions) = readFromClasspath("Day13.txt").useLines { input -> solution.parseInput(input) } solution.applyFolds(grid, foldInstructions.take(1)) println(grid.countPoints()) solution.applyFolds(grid, foldInstructions.drop(1)) println(grid.toString()) }
0
Kotlin
0
0
3f5908fa4991f9b21bb7e3428a359b218fad2a35
3,614
advent-of-code-2021
MIT License
src/main/kotlin/com/leonra/adventofcode/advent2023/day04/Day4.kt
LeonRa
726,688,446
false
{"Kotlin": 30456}
package com.leonra.adventofcode.advent2023.day04 import com.leonra.adventofcode.shared.readResource import kotlin.math.pow /** https://adventofcode.com/2023/day/4 */ private object Day4 { fun partOne(): Int { var sum = 0 readResource("/2023/day04/part1.txt") { line -> val winnersAndCard = line.split(": ")[1].split(" | ") val winners = winnersAndCard[0] .split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.toInt() } .toSet() val matches = winnersAndCard[1] .split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.toInt() } .count { it in winners } sum += when(matches) { 0 -> 0 else -> 2.0.pow(matches - 1).toInt() } } return sum } fun partTwo(): Int { var sum = 0 val extrasToCount = mutableMapOf<Int, Int>() readResource("/2023/day04/part1.txt") { line -> val metaAndRest = line.split(":") val winnersAndCard = metaAndRest[1].split(" | ") val cardNumber = metaAndRest[0].split("Card")[1].trim().toInt() val winners = winnersAndCard[0] .split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.toInt() } .toSet() val matches = winnersAndCard[1] .split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.toInt() } .count { it in winners } val copiesOfCard = extrasToCount.getOrDefault(cardNumber, 0) + 1 for (copiedCardNumber in cardNumber + 1 .. cardNumber + matches) { extrasToCount[copiedCardNumber] = extrasToCount.getOrDefault(copiedCardNumber, 0) + copiesOfCard } sum += copiesOfCard } return sum } } private fun main() { println("Part 1 sum: ${Day4.partOne()}") println("Part 2 sum: ${Day4.partTwo()}") }
0
Kotlin
0
0
46bdb5d54abf834b244ba9657d0d4c81a2d92487
2,404
AdventOfCode
Apache License 2.0
src/Day07.kt
Oli2861
572,895,182
false
{"Kotlin": 16729}
import kotlin.math.absoluteValue fun String.getDigits(): Int? { return this.filter { it.isDigit() }.toIntOrNull() } object CommandConstants { const val CD_COMMAND = "$ cd" const val DESTINATION_HOME = "/" const val DESTINATION_UP = ".." } fun evaluateLog(lines: List<String>): MutableMap<String, Long> { val dirMap = HashMap<String, Long>() val currentPathDirectories = ArrayDeque<String>() for (line in lines) { if (line.contains(CommandConstants.CD_COMMAND)) { val destination = line.subSequence( line.indexOf(CommandConstants.CD_COMMAND) + CommandConstants.CD_COMMAND.length, line.length ).filter { !it.isWhitespace() }.toString() when (destination) { CommandConstants.DESTINATION_HOME -> { currentPathDirectories.removeAll(currentPathDirectories) currentPathDirectories.add(CommandConstants.DESTINATION_HOME) } CommandConstants.DESTINATION_UP -> currentPathDirectories.removeLast() else -> currentPathDirectories.add(destination) } } else if (line[0].isDigit()) { val value = line.getDigits() for (index in currentPathDirectories.indices) { val path = currentPathDirectories.subList(0, index + 1).joinToString(",") dirMap[path] = (dirMap[path] ?: 0) + (value ?: 0) } } } return dirMap } fun getDirectoriesSmallerThan(commands: List<String>, value: Int = 100000) = evaluateLog(commands).filter { it.value <= value }.values.sum() fun getSizeOfDirectoryToBeDeleted(updateSize: Int, totalSpace: Int, commands: List<String>): Long { val directories = evaluateLog(commands) val freeSpace = totalSpace - directories[CommandConstants.DESTINATION_HOME]!! val requiredSpace = (freeSpace - updateSize).absoluteValue var searchedDir: MutableMap.MutableEntry<String, Long>? = null var minDiff = directories.values.max() for (directory in directories) { val diff = directory.value - requiredSpace if (diff in 0..minDiff) { minDiff = directory.value - requiredSpace searchedDir = directory } } return searchedDir?.value ?: 0 } fun main() { val input = readInput("Day07_test") val result = getDirectoriesSmallerThan(input) println(result) check(result == 1086293L) val results2 = getSizeOfDirectoryToBeDeleted(30000000, 70000000, input) println(results2) check(results2 == 366028L) }
0
Kotlin
0
0
138b79001245ec221d8df2a6db0aaeb131725af2
2,609
Advent-of-Code-2022
Apache License 2.0
src/day20/Code.kt
fcolasuonno
221,697,249
false
null
package day20 import java.io.File import java.util.* fun main() { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } private val lineStructure = """(\d+)-(\d+)""".toRegex() fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (start, end) = it.toList() (start.toLong())..(end.toLong()) } }.requireNoNulls().toSortedSet(compareBy<LongRange> { it.first }.thenByDescending { it.last }) fun part1(input: SortedSet<LongRange>): Any? { var first = input.first() var overlapping = input.filter { it.last in first || (first.last + 1) in it } while (overlapping.size > 1) { input.removeAll(overlapping) first = first.first..(overlapping.map { it.last }.max()!!) input.add(first) overlapping = input.filter { it.last in first || (first.last + 1) in it } } return first.last + 1 } fun part2(input: SortedSet<LongRange>) = 4294967296L - generateSequence<List<LongRange>>(input.toList()) { reduced -> val seen = mutableSetOf<LongRange>() reduced.mapNotNull { range -> if (seen.none { range.last in it }) { (range.first..reduced.filter { it.last in range || (range.last + 1) in it }.map { it.last }.max()!!).also { seen.add(it) } } else null }.takeIf { reduced != it } }.last().map { it.last - it.first + 1 }.sum()
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
1,616
AOC2016
MIT License
src/main/Day18.kt
ssiegler
572,678,606
false
{"Kotlin": 76434}
package day18 import utils.readInput fun readCubes(filename: String) = readInput(filename) .map { val (x, y, z) = it.split(",").map { it.toInt() } V3(x, y, z) } .toSet() typealias V3 = Triple<Int, Int, Int> fun Set<V3>.surface(): Int = flatMap(V3::neighbors).count { it !in this } private fun V3.neighbors() = listOf( copy(first = first - 1), copy(first = first + 1), copy(second = second - 1), copy(second = second + 1), copy(third = third - 1), copy(third = third + 1), ) fun Set<V3>.exteriorSurface(): Int { val boundingBox = BoundingBox( minOf { it.first } - 1..maxOf { it.first } + 1, minOf { it.second } - 1..maxOf { it.second } + 1, minOf { it.third } - 1..maxOf { it.third } + 1 ) val seen = mutableSetOf<V3>() val queue = ArrayDeque<V3>() queue.addLast(boundingBox.first()) while (queue.isNotEmpty()) { val current = queue.removeFirst() val neighbors = current.neighbors().filter { it in boundingBox } - this - seen seen.addAll(neighbors) queue.addAll(neighbors) } return flatMap(V3::neighbors).count(seen::contains) } typealias BoundingBox = Triple<IntRange, IntRange, IntRange> private fun BoundingBox.first() = V3(first.first, second.first, third.first) operator fun BoundingBox.contains(point: V3): Boolean = point.first in first && point.second in second && point.third in third fun part1(filename: String) = readCubes(filename).surface() fun part2(filename: String) = readCubes(filename).exteriorSurface() private const val filename = "Day18" fun main() { println(part1(filename)) println(part2(filename)) }
0
Kotlin
0
0
9133485ca742ec16ee4c7f7f2a78410e66f51d80
1,769
aoc-2022
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2022/day16/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2022.day16 import com.kingsleyadio.adventofcode.util.readInput import java.util.* fun main() { // nav(arrayOf("A", "B", "C")) val input = parseInput() part1priority(input) // part1a(input) // part2(input) } fun part1priority(input: Map<String, ValveInfo>) { val queue = PriorityQueue<Navi> { a, b -> b.value - a.value } queue.add(Navi("AA", "AA",0, 0)) val naviMap = hashMapOf<String, Navi>() var timeLeft = 30 while (queue.isNotEmpty()) { if (naviMap.size == input.size) break val (from, current, distanceHere, value) = queue.poll() println("$from => $current") val valveInfo = input.getValue(current) val fromNavi = naviMap[from] //if (fromNavi != null && fromNavi.next == current && value <= fromNavi.value) continue naviMap[from] = Navi(from, current, distanceHere, value) // timeLeft -= distanceHere // if (current !in path) { // timeLeft-- // } // if (current in path) continue // if (timeLeft <= 0) break for (next in valveInfo.exits) { val nextValve = input.getValue(next) val distance = shortestDistance(input, current, next).value val navValue = (timeLeft - distance - 1) * nextValve.flowRate //if (current in naviMap && naviMap.getValue(current).next == next && navValue <= naviMap.getValue(current).value) continue queue.add(Navi(current, next, distance, navValue)) } } var current = "AA" var maxValue = 0 var time = 30 while(current in naviMap) { val next = naviMap.remove(current)!! print("${next.next} ") maxValue += (time - next.distance - 1) * input.getValue(next.next).flowRate time -= next.distance + 1 current = next.next } println(maxValue) } data class Navi(val from: String, val next: String, val distance: Int, val value: Int) fun part1v(input: Map<String, ValveInfo>) { var valueSum = 0 var current = "AA" val valvePriority = input.values.sortedByDescending { it.flowRate } var timeLeft = 30 var visitIndex = 0 val visited = mutableSetOf<String>() while (timeLeft > 0 && visited.size < input.size) { println("Time: $timeLeft") while (valvePriority[visitIndex].id in visited || valvePriority[visitIndex].id == current) visitIndex++ val potentialNext = valvePriority[visitIndex] val (distanceToNext, pathToNext) = shortestDistance(input, current, potentialNext.id) val valueOfNext = potentialNext.flowRate * (timeLeft - distanceToNext - 1) val valueOfCurrent = input.getValue(current).flowRate * (timeLeft - 1) println("Current: $current, Next: ${potentialNext.id}") println("D to N: $distanceToNext, P to N: $pathToNext, V of N: $valueOfNext, V of C: $valueOfCurrent") if (current !in visited && valueOfCurrent >= 0 && input.getValue(current).flowRate > 0) { // open current println("Opening $current") visited.add(current) valueSum += valueOfCurrent timeLeft-- println("Time: $timeLeft") } if (potentialNext.flowRate == 0) break // Exhausted all openable valves // go towards the next priority current = pathToNext.getOrElse(1) { potentialNext.id } println("Moving to $current") timeLeft-- // timeLeft -= distanceToNext // current = potentialNext.id // visitIndex++ } println(visited) println(valueSum) println("--------------------------------") } fun part1ca(input: Map<String, ValveInfo>) { val distanceMap = hashMapOf<String, Int>() for ((k, _) in input) { for ((kk, _) in input) { if (k != kk) distanceMap["$k-$kk"] = shortestDistance(input, k, kk).value } } val cache = hashMapOf<String, Int>() var cacheHit = 0; var cacheMiss = 0 fun flowValue(initial: String, path: Array<String>, index: Int, timeLeft: Int): Int { if (index == path.size || timeLeft <= 0) return 0 val current = path[index] val previous = path.getOrNull(index - 1) ?: initial val distance = distanceMap.getValue("$previous-$current") val value = (timeLeft - distance - 1) * input.getValue(current).flowRate val restKey = path.drop(index).joinToString("-") + "-${timeLeft - distance - 1}" if (restKey in cache) cacheHit++ val restValue = cache.getOrPut(restKey) { cacheMiss++ flowValue(initial, path, index + 1, timeLeft - distance - 1) } return value + restValue } val nodes = input.keys.filter { input.getValue(it).flowRate != 0 }.toTypedArray() var max = 0 traverse(nodes, 0) { path -> max = maxOf(max, flowValue("AA", path, 0, 30)) } println("Cache hit: $cacheHit, Cache miss: $cacheMiss") println(max) } fun part1c(input: Map<String, ValveInfo>) { val distanceMap = hashMapOf<String, Int>() for ((k, _) in input) { for ((kk, _) in input) { if (k != kk) distanceMap["$k-$kk"] = shortestDistance(input, k, kk).value } } val nodes = input.keys.filter { input.getValue(it).flowRate != 0 }.toTypedArray() var max = 0 traverse(nodes, 0) { path -> var current = "AA" var timeLeft = 30 var value = 0 for (i in path.indices) { val n = path[i] val distanceToN = distanceMap.getValue("$current-$n") val valueToN = (timeLeft - distanceToN - 1) * input.getValue(n).flowRate if (valueToN < 0) return@traverse value += valueToN timeLeft -= distanceToN + 1 current = n } max = maxOf(max, value) } println(max) } fun part1(input: Map<String, ValveInfo>) { var valueSum = 0 var current = "AA" var timeLeft = 30 val visited = hashSetOf<String>() fun findNext(): Triple<ValveInfo?, Cost, Int> { var valve: ValveInfo? = null var bestCost = Cost(1_000, emptyList()) var bestValue = 0 for ((_, v) in input) { if (v.flowRate == 0 || v.id in visited || v.id == current) continue val cost = shortestDistance(input, current, v.id) val value = v.flowRate * (timeLeft - cost.value - 1) println("Value for $current to ${v.id}: $value") if (value >= bestValue) { bestValue = value bestCost = cost valve = v } } return Triple(valve, bestCost, bestValue) } while (timeLeft > 0 && visited.size < input.size) { println("Time: $timeLeft") val (potentialNext, cost, valueOfNext) = findNext() val (distanceToNext, pathToNext) = cost val valueOfCurrent = input.getValue(current).flowRate * (timeLeft - 1) println("Current: $current, Next: ${potentialNext?.id}") println("D to N: $distanceToNext, P to N: $pathToNext, V of N: $valueOfNext, V of C: $valueOfCurrent") if (current !in visited && valueOfCurrent >= 0 && input.getValue(current).flowRate > 0) { // open current println("Opening $current") visited.add(current) valueSum += valueOfCurrent timeLeft-- println("Time: $timeLeft") } // go towards the next priority potentialNext ?: break current = pathToNext.getOrElse(1) { potentialNext.id } println("Moving to $current") timeLeft-- // timeLeft -= distanceToNext // current = potentialNext.id // visitIndex++ } println(visited) println(valueSum) } fun part2(input: Map<String, ValveInfo>) { } fun shortestDistance(graph: Map<String, ValveInfo>, start: String, end: String): Cost { val costs = hashMapOf<String, Cost>() val queue = PriorityQueue<Path> { a, b -> a.cost - b.cost } queue.add(Path(start, 0, emptyList())) while (queue.isNotEmpty()) { val (valve, cost, from) = queue.poll() if ((costs[valve]?.value ?: -1) in 0..cost) continue costs[valve] = Cost(cost, from) for (next in graph.getValue(valve).exits) { if ((costs[next]?.value ?: -1) >= 0) continue // already fixed cost to this valve queue.add(Path(next, cost + 1, from + valve)) } } return costs.getValue(end) } fun parseInput(): Map<String, ValveInfo> = buildMap { val pattern = "Valve ([A-Z]+) has flow rate=([0-9]+); tunnels? leads? to valves? (.*)".toRegex() readInput(2022, 16).forEachLine { line -> val (valve, rate, ends) = pattern.matchEntire(line)!!.groupValues.drop(1) val exits = ends.split(", ") put(valve, ValveInfo(valve, rate.toInt(), exits)) } } data class ValveInfo(val id: String, val flowRate: Int, val exits: List<String>) data class Cost(val value: Int, val path: List<String>) data class Path(val to: String, val cost: Int, val from: List<String>) fun traverse(nums: Array<String>, start: Int, onPath: (Array<String>) -> Unit) { if (start == nums.size) return onPath(nums) for (i in start..nums.lastIndex) { nums.swap(start, i) traverse(nums, start + 1, onPath) nums.swap(start, i) } } fun <T> Array<T>.swap(src: Int, dst: Int) { val temp = get(src) set(src, get(dst)) set(dst, temp) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
9,473
adventofcode
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day13/day13.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day13 import biz.koziolek.adventofcode.* fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val dotsMap = parseTransparentPaper(lines) val foldInstructions = parseFoldInstructions(lines) val foldedOnce = fold(dotsMap, foldInstructions.take(1)) println("Visible dots after folding once: ${foldedOnce.size}") val fullyFolded = fold(dotsMap, foldInstructions) println("Paper after fully folding:") println(toString(fullyFolded)) } fun parseTransparentPaper(lines: List<String>): Map<Coord, Boolean> = lines.takeWhile { it.isNotEmpty() } .map { it.split(',', limit = 2) } .associate { Coord( x = it[0].toInt(), y = it[1].toInt() ) to true } fun parseFoldInstructions(lines: List<String>): List<Pair<String, Int>> = lines.dropWhile { it.isNotEmpty() } .drop(1) .map { it.split('=', limit = 2) } .map { (prefix, num) -> when (prefix) { "fold along y" -> "up" to num.toInt() "fold along x" -> "left" to num.toInt() else -> throw IllegalArgumentException("Unknown fold command: $prefix=$num") } } fun toString(map: Map<Coord, Boolean>): String { val width = map.getWidth() val height = map.getHeight() return buildString { for (y in 0 until height) { for (x in 0 until width) { val isDot = map[Coord(x, y)] ?: false if (isDot) { append('#') } else { append('.') } } if (y < height - 1) { append("\n") } } } } fun fold(map: Map<Coord, Boolean>, instructions: List<Pair<String, Int>>): Map<Coord, Boolean> = instructions.fold(map) { acc, (direction, value) -> when (direction) { "up" -> foldUp(acc, y = value) "left" -> foldLeft(acc, x = value) else -> throw IllegalArgumentException("Unknown fold direction: $direction") } } fun foldUp(map: Map<Coord, Boolean>, y: Int): Map<Coord, Boolean> = map.mapKeys { (coord, _) -> if (coord.y > y) { coord.copy(y = y - (coord.y - y)) } else { coord } } fun foldLeft(map: Map<Coord, Boolean>, x: Int): Map<Coord, Boolean> = map.mapKeys { (coord, _) -> if (coord.x > x) { coord.copy(x = x - (coord.x - x)) } else { coord } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,628
advent-of-code
MIT License
src/main/kotlin/Day2.kt
noamfreeman
572,834,940
false
{"Kotlin": 30332}
private val part1ExampleInput = """ A Y B X C Z """.trimIndent() private fun main() { println("day1") println() println("part1") assertEquals(part1(part1ExampleInput), 15) println(part1(readInputFile("day2_input.txt"))) // 17_189 println() println("part2") assertEquals(part2(part1ExampleInput), 12) assertEquals(part2(readInputFile("day2_input.txt")), 13_490) } private fun part2(input: String): Int { return input.lines().sumOf {line -> val other = line[0] val me = line[2] part2Score(me, other) } } private fun part1(input: String): Int { val mapping = mapOf( 'X' to 'A', 'Y' to 'B', 'Z' to 'C', ) return input.lines().sumOf { line -> val other = line[0] val me = line[2].interpretWith(mapping) scorePerRound(me, other) } } private fun Char.interpretWith(mapping: Map<Char, Char>): Char { return mapping.getValue(this) } private fun scorePerRound(me: Char, other: Char) = scorePerItem(me) + scorePerPair(me, other) private fun scorePerPair(me: Char, other: Char) = when { me == 'A' && other == 'B' || me == 'B' && other == 'C' || me == 'C' && other == 'A' -> //lose 0 me == other -> 3 else -> 6 } private fun scorePerItem(item: Char) = when (item) { 'A' -> 1 'B' -> 2 'C' -> 3 else -> error("unknown $item") } private fun part2Score(me: Char, other: Char) = when { me == 'Y' && other == 'A' -> 4 me == 'Y' && other == 'B' -> 5 me == 'Y' && other == 'C' -> 6 me == 'X' && other == 'A' -> 3 me == 'X' && other == 'B' -> 1 me == 'X' && other == 'C' -> 2 me == 'Z' && other == 'A' -> 8 me == 'Z' && other == 'B' -> 9 me == 'Z' && other == 'C' -> 7 else -> error("") }
0
Kotlin
0
0
1751869e237afa3b8466b213dd095f051ac49bef
1,917
advent_of_code_2022
MIT License
src/main/kotlin/Day24.kt
clechasseur
258,279,622
false
null
import org.clechasseur.adventofcode2019.Direction import org.clechasseur.adventofcode2019.Pt import org.clechasseur.adventofcode2019.Pt3D object Day24 { private val input = """ ..##. ..#.. ##... #.... ...## """.trimIndent() private val initialState = State(input.lineSequence().map { it.toList() }.toList()) fun part1(): Int { val states = mutableListOf(initialState) while (true) { val newState = states.last().evolve() if (states.indexOf(newState) != -1) { return newState.biodiversity } states.add(newState) } } fun part2(): Int { val initialState3D = State3D(initialState.ground.mapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == '#') Pt3D(x, y, 0) else null } }.flatten().toSet()) return generateSequence(initialState3D) { it.evolve() }.drop(200).first().bugs.size } private data class State(val ground: List<List<Char>>) { val biodiversity: Int get() = generateSequence(1) { it * 2 }.zip(ground.asSequence().flatten()).map { if (it.second == '#') it.first else 0 }.sum() fun evolve() = State(ground.indices.map { y -> ground[y].indices.map { x -> val bugs = numBugsAround(Pt(x, y)) when (ground[y][x]) { '#' -> if (bugs == 1) '#' else '.' '.' -> if (bugs in 1..2) '#' else '.' else -> error("Wrong ground at ($x, $y): ${ground[y][x]}") } } }) private fun numBugsAround(pt: Pt): Int = Direction.values().map { direction -> if (at(pt + direction.displacement) == '#') 1 else 0 }.sum() private fun at(pt: Pt): Char = when { pt.x in ground[0].indices && pt.y in ground.indices -> ground[pt.y][pt.x] else -> '.' } } private data class State3D(val bugs: Set<Pt3D>) { fun evolve(): State3D { val newBugs = (bugs.flatMap { neighbours(it) }.toSet() - bugs).mapNotNull { pt -> val neighbourBugs = neighbours(pt) intersect bugs if (neighbourBugs.size in 1..2) pt else null } val deadBugs = bugs.mapNotNull { pt -> val neighbourBugs = neighbours(pt) intersect bugs if (neighbourBugs.size != 1) pt else null } return State3D(bugs - deadBugs + newBugs) } private fun neighbours(pt: Pt3D): Set<Pt3D> { val pts = Direction.values().mapNotNull { move -> val dest = pt + Pt3D(move.displacement.x, move.displacement.y, 0) if (dest.x in 0..4 && dest.y in 0..4 && dest != Pt3D(2, 2, pt.z)) dest else null }.toMutableSet() if (pt.x == 0) { pts.add(Pt3D(1, 2, pt.z - 1)) } else if (pt.x == 4) { pts.add(Pt3D(3, 2, pt.z - 1)) } if (pt.y == 0) { pts.add(Pt3D(2, 1, pt.z - 1)) } else if (pt.y == 4) { pts.add(Pt3D(2, 3, pt.z - 1)) } if (pt.x == 1 && pt.y == 2) { pts.addAll((0..4).map { y -> Pt3D(0, y, pt.z + 1) }) } else if (pt.x == 3 && pt.y == 2) { pts.addAll((0..4).map { y -> Pt3D(4, y, pt.z + 1) }) } else if (pt.x == 2 && pt.y == 1) { pts.addAll((0..4).map { x -> Pt3D(x, 0, pt.z + 1) }) } else if (pt.x == 2 && pt.y == 3) { pts.addAll((0..4).map { x -> Pt3D(x, 4, pt.z + 1) }) } return pts } } }
0
Kotlin
0
0
187acc910eccb7dcb97ff534e5f93786f0341818
3,766
adventofcode2019
MIT License
src/Day22.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
private class Solution22(val input: List<String>) { companion object { fun wireAsBoard(board: Board) { fun wireRight(tile: Tile, map: Map<Pair<Int, Int>, Tile>): Tile { val newRight = map.getOrDefault( Pair(tile.x + 1, tile.y), board.tiles.filter { it.y == tile.y }.minBy { it.x }) return if (newRight.c == '#') tile else newRight } fun wireDown(tile: Tile, map: Map<Pair<Int, Int>, Tile>): Tile { val newDown = map.getOrDefault( Pair(tile.x, tile.y + 1), board.tiles.filter { it.x == tile.x }.minBy { it.y }) return if (newDown.c == '#') tile else newDown } fun wireLeft(tile: Tile, map: Map<Pair<Int, Int>, Tile>): Tile { val newLeft = map.getOrDefault( Pair(tile.x - 1, tile.y), board.tiles.filter { it.y == tile.y }.maxBy { it.x }) return if (newLeft.c == '#') tile else newLeft } fun wireUp(tile: Tile, map: Map<Pair<Int, Int>, Tile>): Tile { val newUp = map.getOrDefault( Pair(tile.x, tile.y - 1), board.tiles.filter { it.x == tile.x }.maxBy { it.y }) return if (newUp.c == '#') tile else newUp } val map = board.tiles.associateBy { Pair(it.x, it.y) } board.tiles.forEach { tile -> tile.right = wireRight(tile, map) tile.down = wireDown(tile, map) tile.left = wireLeft(tile, map) tile.up = wireUp(tile, map) } } fun wireAsCube(board: Board) { } } fun solve(wire: (Board) -> Unit): Int { val steps = Steps(input.last()) val board = Board(input.takeWhile { it.isNotBlank() }) wire(board) do { val step = steps.next() ?: break when (step) { "R" -> board.turnRight() "L" -> board.turnLeft() else -> board.goForward(step.toInt()) } } while (true) return 1000 * (board.position.y + 1) + 4 * (board.position.x + 1) + board.direction } class Board(input: List<String>) { val right = 0 val down = 1 val left = 2 val up = 3 val tiles = input.flatMapIndexed { y, l -> l.mapIndexed { x, c -> Tile(x, y, c)} }.filterNot { it.c == ' ' } var position = tiles.filter { it.y == 0 }.minBy { it.x } var direction = right fun turnRight() { direction = when (direction) { right -> down down -> left left -> up up -> right else -> throw IllegalArgumentException() } } fun turnLeft() { direction = when (direction) { right -> up down -> right left -> down up -> left else -> throw IllegalArgumentException() } } fun goForward(times: Int) { repeat(times) {when (direction) { right -> position = position.right!! down -> position = position.down!! left -> position = position.left!! up -> position = position.up!! } } } } class Tile(var x: Int, var y: Int, var c: Char) { var right: Tile? = null var down: Tile? = null var left: Tile? = null var up: Tile? = null } class Steps(input: String) { private val steps = mutableListOf<String>() private var count = 0 init { var actualNumber = "" for (c in input) { if (c == 'R' || c == 'L') { if (actualNumber.isNotBlank()) { steps.add(actualNumber) actualNumber = "" } steps.add(c.toString()) } else { actualNumber += c } } if (actualNumber.isNotBlank()) steps.add(actualNumber) } fun next() = if (count < steps.size) steps[count++] else null } } fun main() { val testSolution = Solution22(readInput("Day22_test")) check(testSolution.solve(Solution22::wireAsBoard) == 6032) // check(testSolution.solve(Solution22::wireAsCube) == 0) val solution = Solution22(readInput("Day22")) println(solution.solve(Solution22::wireAsBoard)) // println(solution.solve(Solution22::wireAsCube)) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
4,770
aoc-2022
Apache License 2.0
src/day15/day.kt
LostMekka
574,697,945
false
{"Kotlin": 92218}
package day15 import util.Point import util.extractIntGroups import util.readInput import util.shouldBe import util.without import kotlin.math.abs fun main() { val testInput = readInput(Input::class, testInput = true).parseInput() testInput.part1(10) shouldBe 26 testInput.part2(20) shouldBe 56000011 val input = readInput(Input::class).parseInput() println("output for part1: ${input.part1(2000000)}") println("output for part2: ${input.part2(4000000)}") } private data class Sensor( val pos: Point, val beaconPos: Point, ) private class Input( val sensors: List<Sensor>, ) private val inputRegex = Regex("""^Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""") private fun List<String>.parseInput(): Input { val sensors = map { val (sx, sy, bx, by) = it.extractIntGroups(inputRegex) Sensor(Point(sx, sy), Point(bx, by)) } return Input(sensors) } private fun Input.part1(row: Int): Int { val covered = mutableSetOf<Int>() for (sensor in sensors) { val range = sensor.pos manhattanDistanceTo sensor.beaconPos val dy = abs(row - sensor.pos.y) if (dy > range) continue val dx = range - dy for (x in sensor.pos.x-dx..sensor.pos.x+dx) covered += x } for (sensor in sensors) { if (sensor.pos.y == row) covered -= sensor.pos.x if (sensor.beaconPos.y == row) covered -= sensor.beaconPos.x } return covered.size } private fun Input.part2(size: Int): Long { for (row in 0..size) { var free = listOf(0..size) for (sensor in sensors) { val range = sensor.pos manhattanDistanceTo sensor.beaconPos val dy = abs(row - sensor.pos.y) if (dy > range) continue val dx = range - dy val coveredRange = sensor.pos.x - dx..sensor.pos.x + dx free = free.flatMap { it without coveredRange } } if (free.isNotEmpty()) { return free.single().first * 4000000L + row } } error("nothing found") }
0
Kotlin
0
0
58d92387825cf6b3d6b7567a9e6578684963b578
2,080
advent-of-code-2022
Apache License 2.0
src/Day03/Solution.kt
cweinberger
572,873,688
false
{"Kotlin": 42814}
package Day03 import readInput fun main() { fun String.getCompartments() : Pair<String, String> { return Pair( this.slice(0 until this.length/2), this.slice(this.length/2 until this.length) ) } fun Pair<String, String>.getDuplicateCharacter() : Char { return this.first .first { this.second.contains(it) } } /** * Priorities: * a-z = 1-26 * A-Z = 27-52 * * Char codes: * a-z = 97-... * A-Z = 65-... */ fun Char.toPriority() : Int { return when (this.code) { in 'a'.code .. 'z'.code -> (this.code - 96) in 'A'.code .. 'Z'.code -> (this.code - 38) else -> throw IllegalArgumentException("Unexpected character '$this'") } } fun List<String>.getDuplicateCharacter() : Char { return this.first().first { character -> this .slice(1 until this.size) .map { it.contains(character) } .all { it } } } fun part1(input: List<String>): Int { println("Evaluating ${input.count()} rucksacks") return input.map { rucksack -> rucksack .getCompartments() .getDuplicateCharacter() .toPriority() }.sum() } fun part2(input: List<String>): Int { println("Evaluating ${input.count()} rucksacks") return input.chunked(3) { rucksacks -> rucksacks.getDuplicateCharacter() .toPriority() }.sum() } val testInput = readInput("Day03/TestInput") val input = readInput("Day03/Input") println("=== Part 1 - Test Input ===") println(part1(testInput)) println("=== Part 1 - Final Input ===") println(part1(input)) println("=== Part 2 - Test Input ===") println(part2(testInput)) println("=== Part 2 - Final Input ===") println(part2(input)) }
0
Kotlin
0
0
883785d661d4886d8c9e43b7706e6a70935fb4f1
1,975
aoc-2022
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year22/Day19.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year22 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.product import com.grappenmaker.aoc.splitInts import kotlin.math.max import kotlin.math.min fun PuzzleSet.day19() = puzzle { val costs = inputLines.map { l -> l.splitInts().drop(1).parseCosts() } fun RobotsCost.geodes(state: RobotState, seen: MutableMap<RobotState, Int> = hashMapOf()): Int { if (state.time == 0) return state.geode var result = state.geode val capped = state.cap(this) seen[capped]?.let { return it } nextBuilds(state).forEach { result = max(geodes(it, seen), result) } seen[capped] = result return result } fun RobotsCost.geodes(time: Int) = geodes(RobotState(time = time)) partOne = costs.withIndex().sumOf { (idx, v) -> (idx + 1) * v.geodes(24) }.s() partTwo = costs.take(3).map { it.geodes(32) }.product().s() } fun RobotState.cap(bp: RobotsCost): RobotState { val tm1 = time - 1 fun capResource(amount: Int, cost: Int, robots: Int) = min(cost * time - tm1 * robots, amount) val newOreRobots = minOf(oreRobots, bp.maxOreCost) val newClayRobots = minOf(clayRobots, bp.obbyClayCost) val newObbyRobots = minOf(obbyRobots, bp.geodeObbyCost) return copy( oreRobots = newOreRobots, clayRobots = newClayRobots, obbyRobots = newObbyRobots, ore = capResource(ore, bp.maxOreCost, newOreRobots), clay = capResource(clay, bp.obbyClayCost, newClayRobots), obby = capResource(obby, bp.geodeObbyCost, newObbyRobots), ) } data class RobotsCost( val oreOreCost: Int, val clayOreCost: Int, val obbyOreCost: Int, val obbyClayCost: Int, val geodeOreCost: Int, val geodeObbyCost: Int ) { val maxOreCost = maxOf(oreOreCost, clayOreCost, obbyOreCost, geodeOreCost) } fun List<Int>.parseCosts() = RobotsCost(this[0], this[1], this[2], this[3], this[4], this[5]) fun RobotsCost.nextBuilds(state: RobotState) = buildList { add(state.advance()) if (state.ore >= oreOreCost) add( state.advance( oreRobots = state.oreRobots + 1, ore = state.ore - oreOreCost + state.oreRobots ) ) if (state.ore >= clayOreCost) add( state.advance( clayRobots = state.clayRobots + 1, ore = state.ore - clayOreCost + state.oreRobots ) ) if (state.ore >= obbyOreCost && state.clay >= obbyClayCost) add( state.advance( obbyRobots = state.obbyRobots + 1, ore = state.ore - obbyOreCost + state.oreRobots, clay = state.clay - obbyClayCost + state.clayRobots ) ) if (state.ore >= geodeOreCost && state.obby >= geodeObbyCost) add( state.advance( geodeRobots = state.geodeRobots + 1, ore = state.ore - geodeOreCost + state.oreRobots, obby = state.obby - geodeObbyCost + state.obbyRobots ) ) } data class RobotState( val oreRobots: Int = 1, val clayRobots: Int = 0, val obbyRobots: Int = 0, val geodeRobots: Int = 0, val ore: Int = 0, val clay: Int = 0, val obby: Int = 0, val geode: Int = 0, val time: Int ) fun RobotState.advance( oreRobots: Int = this.oreRobots, clayRobots: Int = this.clayRobots, obbyRobots: Int = this.obbyRobots, geodeRobots: Int = this.geodeRobots, ore: Int = this.ore + this.oreRobots, clay: Int = this.clay + this.clayRobots, obby: Int = this.obby + this.obbyRobots, geode: Int = this.geode + this.geodeRobots, ) = RobotState(oreRobots, clayRobots, obbyRobots, geodeRobots, ore, clay, obby, geode, time - 1)
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
3,690
advent-of-code
The Unlicense
src/Day04.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val ranges = it.split(",") val values = ranges.map { range -> range.split("-").map { number -> number.toInt() } } if ((values[0][0] >= values[1][0] && values[0][1] <= values[1][1]) || (values[1][0] >= values[0][0] && values[1][1] <= values[0][1])) 1 as Int else 0 as Int } } fun part2(input: List<String>): Int { return input.sumOf { val ranges = it.split(",") val values = ranges.map { range -> range.split("-").map { number -> number.toInt() } } if (values[0][1]>=values[1][0] && values[0][0]<=values[1][1]) 1 as Int else 0 as Int } } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
908
Advent-of-code
Apache License 2.0
src/Day04.kt
rinas-ink
572,920,513
false
{"Kotlin": 14483}
import java.lang.Integer.max import java.lang.Integer.min fun main() { fun containingSeg(pair: List<List<Int>>) = listOf(min(pair[0][0], pair[1][0]), max(pair[0][1], pair[1][1])) fun segLen(s: List<Int>) = s[1] - s[0] + 1 fun checkPair1(pair: List<List<Int>>) = (segLen(containingSeg(pair)) == max( segLen(pair[0]), segLen(pair[1]) )).compareTo(false) fun countOverlaps( input: List<String>, func: (List<List<Int>>) -> Int ): Int = input.map { it.split(',', '-').map { it.toInt() }.chunked(2) }.map(func).sum() fun part1(input: List<String>): Int = countOverlaps(input, ::checkPair1) fun checkPair2(pair: List<List<Int>>) = (segLen(containingSeg(pair)) < segLen(pair[0]) + segLen(pair[1])).compareTo(false) fun part2(input: List<String>): Int = countOverlaps(input, ::checkPair2) // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
462bcba7779f7bfc9a109d886af8f722ec14c485
1,130
anvent-kotlin
Apache License 2.0
src/Day02.kt
patrickwilmes
572,922,721
false
{"Kotlin": 6337}
private fun translate(input: String): String = when (input) { "X" -> "A" "Y" -> "B" "Z" -> "C" else -> throw IllegalArgumentException("Not a valid RPS symbol") } private fun getScoreFor(rpc: String): Int = when (rpc) { "A" -> 1 // rock "B" -> 2 // paper "C" -> 3 // scissors else -> throw IllegalArgumentException("Invalid RPC: $rpc") } private fun getScoreFor(opponent: String, own: String): Int { if (opponent == own) return getScoreFor(own) + 3 return when (opponent) { "A" -> if (own == "C") getScoreFor(own) else getScoreFor(own) + 6 "B" -> if (own == "C") getScoreFor(own) + 6 else getScoreFor(own) "C" -> if (own == "A") getScoreFor(own) + 6 else getScoreFor(own) else -> throw IllegalArgumentException("Invalid RPC: $opponent") } } private fun determineMySymbol(opponent: String, roundEnding: String): String { if (roundEnding == "Y") return opponent if (roundEnding == "X") return when(opponent) { "A" -> "C" "B" -> "A" "C" -> "B" else -> throw IllegalArgumentException("No valid condition found") } return when(opponent) { "A" -> "B" "B" -> "C" "C" -> "A" else -> throw IllegalArgumentException("No valid condition found") } } fun main() { fun List<String>.parse(shouldTranslate: Boolean = false) = map { val parts = it.split(" ") val opponent = parts[0] val own = if (shouldTranslate) translate(parts[1]) else parts[1] opponent to own } fun part1(input: List<String>): Int = input.parse(shouldTranslate = true).sumOf { getScoreFor(it.first, it.second) } fun part2(input: List<String>): Int = input.parse().sumOf { val opponent = it.first val own = determineMySymbol(opponent, it.second) getScoreFor(opponent, own) } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
162c8f1b814805285e10ea4e3ab944c21e8be4c5
2,019
advent-of-code-2022
Apache License 2.0
src/main/kotlin/kt/kotlinalgs/app/graph/MinSpanningTreeKruskal.ws.kts
sjaindl
384,471,324
false
null
package com.sjaindl.kotlinalgsandroid.graph import java.util.* /* MinSpanningTreeKruskal - MST weighted undirected graph pick smallest edge (PQ) check for cycle (DFS or UnionFind) */ //https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/ class MinSpanningTreeKruskal<T> { fun minSpanningTree(graph: Graph<T>): List<WeightedEdge<T>> { val mst: MutableList<WeightedEdge<T>> = mutableListOf() val unionFind = UnionFind(graph) // O(V) val sortedEdges = PriorityQueue(graph.edges) // O(E log E) // O (V * (log V + log E)) = O(V log E) // loop is max E because we may consider all edges!! while (mst.size < graph.vertices.size - 1) { //V-1 vertices form a MST .. O(V) val possibleEdge = sortedEdges.poll() // O(log E) val component1 = unionFind.find(possibleEdge.from.value) // O(log V) val component2 = unionFind.find(possibleEdge.to.value) // O(log V) if (component1 == component2) continue //would form a cycle mst.add(possibleEdge) unionFind.union(component1, component2) // O(1) } return mst } } class UnionFind<T>//initially every vertice has its own component (graph: Graph<T>) { private val components: MutableMap<T, T> = mutableMapOf() private val sizes: MutableMap<T, Int> = mutableMapOf() init { graph.vertices.forEach { //initially every vertice has its own component components[it.value] = it.value sizes[it.value] = 1 } } fun find(component: T): T { var curComponent = component while (components[curComponent] != curComponent) { curComponent = components[curComponent]!! } return curComponent } fun union(first: T, second: T) { //union by rank! -> O(log V) if (sizes[first]!! < sizes[second]!!) { components[first] = components[second]!! sizes[second] = sizes[first]!! + sizes[second]!! } else { components[second] = components[first]!! sizes[first] = sizes[first]!! + sizes[second]!! } } } data class Vertice<T>( val value: T, ) class Graph<T>(val vertices: List<Vertice<T>>) { var neighbors: MutableMap<T, MutableList<WeightedEdge<T>>> = mutableMapOf() var edges: MutableList<WeightedEdge<T>> = mutableListOf() fun addEdge(edge: WeightedEdge<T>) { val neighboursFrom = neighbors.getOrDefault(edge.from.value, mutableListOf()) neighboursFrom.add(edge) neighbors[edge.from.value] = neighboursFrom val neighboursTo = neighbors.getOrDefault(edge.to.value, mutableListOf()) neighboursTo.add(edge) neighbors[edge.to.value] = neighboursTo edges.add(edge) } } data class WeightedEdge<T>( val from: Vertice<T>, val to: Vertice<T>, val weight: Int ) : Comparable<WeightedEdge<T>> { override fun compareTo(other: WeightedEdge<T>): Int { return when { this.weight < other.weight -> -1 this.weight == other.weight -> 0 else -> 1 } } } val vertice0 = Vertice(0) val vertice1 = Vertice(1) val vertice2 = Vertice(2) val vertice3 = Vertice(3) val vertice4 = Vertice(4) val vertice5 = Vertice(5) val vertice6 = Vertice(6) val vertice7 = Vertice(7) val vertice8 = Vertice(8) val vertices = listOf( vertice0, vertice1, vertice2, vertice3, vertice4, vertice5, vertice6, vertice7, vertice8 ) val graph = Graph(vertices) graph.addEdge(WeightedEdge(vertice0, vertice1, 4)) graph.addEdge(WeightedEdge(vertice0, vertice7, 8)) graph.addEdge(WeightedEdge(vertice1, vertice2, 8)) graph.addEdge(WeightedEdge(vertice1, vertice7, 11)) graph.addEdge(WeightedEdge(vertice2, vertice3, 7)) graph.addEdge(WeightedEdge(vertice2, vertice5, 4)) graph.addEdge(WeightedEdge(vertice2, vertice8, 2)) graph.addEdge(WeightedEdge(vertice3, vertice4, 9)) graph.addEdge(WeightedEdge(vertice3, vertice5, 14)) graph.addEdge(WeightedEdge(vertice4, vertice5, 10)) graph.addEdge(WeightedEdge(vertice5, vertice6, 2)) graph.addEdge(WeightedEdge(vertice6, vertice7, 1)) graph.addEdge(WeightedEdge(vertice6, vertice8, 6)) graph.addEdge(WeightedEdge(vertice7, vertice8, 7)) MinSpanningTreeKruskal<Int>().minSpanningTree(graph)
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
4,364
KotlinAlgs
MIT License
solutions/aockt/y2023/Y2023D07.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.parse import aockt.y2023.Y2023D07.HandType.* import io.github.jadarma.aockt.core.Solution object Y2023D07 : Solution { /** A type of playing card for Camel Cards. */ private enum class Card(val symbol: Char) : Comparable<Card> { Joker('*'), Two('2'), Three('3'), Four('4'), Five('5'), Six('6'), Seven('7'), Eight('8'), Nine('9'), Ten('T'), Jack('J'), Queen('Q'), King('K'), Ace('A'); companion object { private val symbolMap: Map<Char, Card> = Card.entries.associateBy { it.symbol } fun valueOf(char: Char): Card = symbolMap.getValue(char) } } /** A type of hand */ private enum class HandType { HighCard, OnePair, TwoPair, ThreeOfAKind, FullHouse, FourOfAKind, FiveOfAKind } /** * A dealt hand of Camel Cards. * @property cards The dealt cards, in order. * @property handType What kind of [HandType] the [cards] make up. */ private data class Hand(val cards: List<Card>) : Comparable<Hand> { val handType: HandType = run { require(cards.size == 5) { "A Camel Cards hand must have exactly 5 cards." } val (jokers, plain) = cards.partition { it == Card.Joker } val numberOfJokers = jokers.size val stats: List<Int> = plain.groupingBy { it }.eachCount().values.sortedDescending() if (numberOfJokers >= 4) return@run FiveOfAKind when (stats.first()) { 5 -> FiveOfAKind 4 -> if (numberOfJokers == 1) FiveOfAKind else FourOfAKind 3 -> when (numberOfJokers) { 0 -> if (2 in stats.drop(1)) FullHouse else ThreeOfAKind 1 -> FourOfAKind 2 -> FiveOfAKind else -> error("Impossible state.") } 2 -> when (numberOfJokers) { 0 -> if (2 in stats.drop(1)) TwoPair else OnePair 1 -> if (2 in stats.drop(1)) FullHouse else ThreeOfAKind 2 -> FourOfAKind 3 -> FiveOfAKind else -> error("Impossible state.") } 1 -> when (numberOfJokers) { 3 -> FourOfAKind 2 -> ThreeOfAKind 1 -> OnePair 0 -> HighCard else -> error("Impossible state.") } else -> error("Impossible state.") } } /** Compare this hand to the [other], it either wins based on its [handType], or by the first highest card. */ override fun compareTo(other: Hand) = comparator.compare(this, other) private companion object { val comparator: Comparator<Hand> = compareBy(Hand::handType).thenComparator { a, b -> val index = (0..<5).firstOrNull { a.cards[it] != b.cards[it] } ?: 0 a.cards[index] compareTo b.cards[index] } } } /** * Parse the [input] and returns the list of hands and their associated bids. * @param input The puzzle input. * @param withJokers If true, all Jacks will be instead replaced by Jokers. */ private fun parseInput(input: String, withJokers: Boolean): List<Pair<Hand, Long>> = parse { input .lineSequence() .map { if (withJokers) it.replace('J', '*') else it } .map { it.split(' ', limit = 2) } .map { (hand, bid) -> hand.map(Card.Companion::valueOf).let(::Hand) to bid.toLong() } .toList() } /** Sort a list of hands by rank, and return the sum of their rank multiplied by their respective bid. */ private fun List<Pair<Hand, Long>>.solve() = sortedBy { it.first } .withIndex() .sumOf { it.index.inc() * it.value.second } override fun partOne(input: String) = parseInput(input, withJokers = false).solve() override fun partTwo(input: String) = parseInput(input, withJokers = true).solve() }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
4,084
advent-of-code-kotlin-solutions
The Unlicense
src/Day05.kt
floblaf
572,892,347
false
{"Kotlin": 28107}
fun main() { data class Operation(val count: Int, val from: Int, val to: Int) val input = readInput("Day05") val blankLine = input.indexOfFirst { it.isEmpty() } val crates = input.take(blankLine - 1) .map { line -> line.chunked(4).map { it[1] } } .reversed() val cargo = buildList { for (i in 0 until crates[0].size) { add(buildList { for (l in crates.indices) { val value = crates[l][i] if (value != ' ') { add(value) } } }) } } val operations = input.drop(blankLine + 1) .map { val match = Regex("move (\\d+) from (\\d+) to (\\d+)").find(it)!! val (count, from, to) = match.destructured Operation(count.toInt(), from.toInt() - 1, to.toInt() - 1) } fun part1(cargo: List<List<Char>>, operations: List<Operation>): String { val cargo9000 = cargo.map { ArrayDeque(it) } operations.forEach { operation -> repeat(operation.count) { cargo9000[operation.to].addLast(cargo9000[operation.from].removeLast()) } } return cargo9000.map { it.last() }.joinToString("") } fun part2(cargo: List<List<Char>>, operations: List<Operation>): String { val cargo9001 = cargo.map { ArrayDeque(it) } operations.forEach { operation -> val temp = ArrayDeque<Char>() repeat(operation.count) { temp.addFirst(cargo9001[operation.from].removeLast()) } cargo9001[operation.to].addAll(temp) } return cargo9001.map { it.last() }.joinToString("") } println(part1(cargo, operations)) println(part2(cargo, operations)) }
0
Kotlin
0
0
a541b14e8cb401390ebdf575a057e19c6caa7c2a
1,841
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day7.kt
kevinrobayna
436,414,545
false
{"Ruby": 195446, "Kotlin": 42719, "Shell": 1288}
data class Bag( val tag: String, val count: Int ) fun day7ProblemReader(string: String): Map<String, List<Bag>> { return string .split("\n") .map { line -> line .replace("bags", "bag") .replace(".", "") .replace(" contain", ",") } .associate { line -> val items = line.split(",") .map { it.trim() } .toList() val listOfBags = mutableListOf<Bag>() val key = items[0] for (inx in items.indices) { if (inx != 0) { val tag = items[inx].filter { !it.isDigit() }.trim() val count = items[inx].filter { it.isDigit() } if (count.isEmpty()) { listOfBags.add(Bag(tag, 0)) } else { listOfBags.add(Bag(tag, count.toInt())) } } } key to listOfBags } } // https://adventofcode.com/2020/day/7 class Day7( private val bags: Map<String, List<Bag>>, ) { companion object { const val GOLD = "shiny gold bag" } fun solveAtLeastOneGold(): Int { val isGold = mutableMapOf<String, Lazy<Boolean>>() for ((key: String, items: List<Bag>) in bags) { isGold[key] = lazy(LazyThreadSafetyMode.NONE) { items.any { (tag, _) -> tag == GOLD || isGold[tag]?.value == true } } } return isGold.values.count { it.value } } fun solvePartTwo(): Int { var sum = 0 val deque = ArrayDeque(bags[GOLD].orEmpty()) while (deque.isNotEmpty()) { val bag = deque.removeFirst() sum += bag.count bags[bag.tag]?.forEach { subBag: Bag -> deque.add(Bag(subBag.tag, (bag.count * subBag.count))) } } return sum } } fun main() { val problem = day7ProblemReader(Day6::class.java.getResource("day7.txt").readText()) println("solution = ${Day7(problem).solveAtLeastOneGold()}") println("solution part2 = ${Day7(problem).solvePartTwo()}") }
0
Ruby
0
0
9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577
2,206
adventofcode_2020
MIT License
src/Day14.kt
hrach
572,585,537
false
{"Kotlin": 32838}
class Map { val points = mutableMapOf<Pair<Int, Int>, Char>() @Suppress("unused") fun print() { val minX = points.keys.minBy { it.first }.first val maxX = points.keys.maxBy { it.first }.first val minY = points.keys.minBy { it.second }.second val maxY = points.keys.maxBy { it.second }.second for (y in minY..maxY) { for (x in minX..maxX) { print(points[x to y] ?: '.') } print("\n") } } } fun main() { fun parse(input: List<String>): Map { val map = Map() input.forEach { line -> val points = line .split(" -> ") .map { it.split(",").map { it.toInt() } } points.zipWithNext().forEach { (to, from) -> val xx = minOf(from[0], to[0])..maxOf(from[0], to[0]) val yy = minOf(from[1], to[1])..maxOf(from[1], to[1]) for (x in xx) for (y in yy) map.points[x to y] = '#' } } return map } fun next(map: Map, point: Pair<Int, Int>, bottom: Int? = null): Pair<Int, Int> { if (bottom != null && point.second + 1 >= bottom) return point val down = point.copy(second = point.second + 1) if (map.points.get(down) == null) return down val downLeft = point.copy(point.first - 1, point.second + 1) if (map.points.get(downLeft) == null) return downLeft val downRight = point.copy(point.first + 1, point.second + 1) if (map.points.get(downRight) == null) return downRight return point } fun part1(input: List<String>): Int { val map = parse(input) val bottom = map.points.keys.maxBy { it.second }.second var pos = 500 to 0 var snowFlakes = 1 while (pos.second <= bottom) { val newPos = next(map, pos) if (newPos == pos) { map.points[newPos] = 'o' pos = 500 to 0 snowFlakes += 1 } else { pos = newPos } } return snowFlakes - 1 } fun part2(input: List<String>): Int { val map = parse(input) val bottom = map.points.keys.maxBy { it.second }.second + 2 var pos = 500 to 0 var snowFlakes = 1 while (true) { val newPos = next(map, pos, bottom) if (newPos == 500 to 0) break if (newPos == pos) { map.points[newPos] = 'o' pos = 500 to 0 snowFlakes += 1 } else { pos = newPos } } return snowFlakes } val testInput = readInput("Day14_test") check(part1(testInput), 24) check(part2(testInput), 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
40b341a527060c23ff44ebfe9a7e5443f76eadf3
2,881
aoc-2022
Apache License 2.0
app/src/main/kotlin/day05/Day05.kt
meli-w
433,710,859
false
{"Kotlin": 52501}
package day05 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 5 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay05Part1, ::solveDay05Part2) } fun solveDay05Part1(input: List<String>): Int = parseInput(input) .asSequence() .filter { (c1, c2) -> c1.x == c2.x || c1.y == c2.y } .map { (c1, c2) -> when (c1.x == c2.x) { true -> { horizontalList( c1.x, range = if (c1.y < c2.y) c1.y..c2.y else c2.y..c1.y ) } false -> { verticalList( c1.y, range = if (c1.x < c2.x) c1.x..c2.x else c2.x..c1.x ) } } } .flatten() .groupBy { it } .count { map: Map.Entry<Coordinate, List<Coordinate>> -> map.value.size >= 2 } fun solveDay05Part2(input: List<String>): Int = parseInput(input) .map { (c1, c2) -> when { c1.x == c2.x -> { horizontalList( c1.x, range = if (c1.y < c2.y) c1.y..c2.y else c2.y..c1.y ) } c1.y == c2.y -> { verticalList( c1.y, range = if (c1.x < c2.x) c1.x..c2.x else c2.x..c1.x ) } else -> { when { c1.y < c2.y -> { diagonalList( startX = c1.x, liminater = { if (c1.x < c2.x) it + 1 else it - 1 }, range = if (c1.x < c2.x) c1.y..c2.y else c1.y..c2.y ) } else -> { diagonalList( startX = c2.x, liminater = { if (c1.x < c2.x) it - 1 else it + 1 }, range = if (c1.x < c2.x) c2.y..c1.y else c2.y..c1.y ) } } } } } .flatten() .groupBy { it } .count { map: Map.Entry<Coordinate, List<Coordinate>> -> map.value.size >= 2 } fun horizontalList(x: Int, range: IntRange): List<Coordinate> = mutableListOf<Coordinate>() .apply { range.forEach { this.add(Coordinate(x, it)) } } .toList() fun verticalList(y: Int, range: IntRange): List<Coordinate> = mutableListOf<Coordinate>() .apply { range.forEach { this.add(Coordinate(it, y)) } } .toList() fun diagonalList(startX: Int, liminater: (Int) -> Int, range: IntRange): List<Coordinate> = mutableListOf<Coordinate>() .apply { var x = startX range.forEach { this.add(Coordinate(x, it)) x = liminater(x) } } .toList() fun parseInput(input: List<String>): List<Pair<Coordinate, Coordinate>> = input .map { line -> line .split(" -> ") .let { it.first().toCoordinate() to it.last().toCoordinate() } } private fun String.toCoordinate(): Coordinate { val coordinate = this.split(",") return Coordinate(coordinate.first().toInt(), coordinate.last().toInt()) } data class Coordinate(val x: Int, val y: Int)
0
Kotlin
0
1
f3b96c831d6c8e21de1ac866cf9c64aaae2e5ea1
3,488
AoC-2021
Apache License 2.0
src/main/kotlin/de/consuli/aoc/year2023/days/Day02.kt
ulischulte
572,773,554
false
{"Kotlin": 40404}
package de.consuli.aoc.year2023.days import de.consuli.aoc.common.Day data class Cube(val color: String, val count: Int) class Day02 : Day(2, 2023) { private val limits = mapOf("blue" to 14, "green" to 13, "red" to 12) override fun partOne(testInput: Boolean): Int = getInput(testInput) .filter(::isValidGameLine) .sumOf { it.substringAfter("Game ").substringBefore(":").toInt() } override fun partTwo(testInput: Boolean): Long { return getInput(testInput) .sumOf { gameLine -> val minimumRequiredCubes = mutableMapOf("blue" to 0, "green" to 0, "red" to 0) val cubes = extractCubes(gameLine) cubes.forEach { cube -> if (minimumRequiredCubes[cube.color]!! < cube.count) minimumRequiredCubes[cube.color] = cube.count } minimumRequiredCubes.values.product() } } private fun isValidGameLine(gameLine: String): Boolean { val cubes = extractCubes(gameLine) return cubes.all(::isValidCube) } private fun extractCubes(gameLine: String): List<Cube> { return gameLine.substringAfter(": ").split("; ").flatMap { it.split(", ").map { cube -> val color = cube.substringAfter(" ") val count = cube.substringBefore(" ").toInt() Cube(color, count) } } } private fun isValidCube(cube: Cube): Boolean { return cube.count <= (limits[cube.color] ?: 0) } private fun Collection<Int>.product(): Long = fold(1L) { acc, entry -> entry * acc } }
0
Kotlin
0
2
21e92b96b7912ad35ecb2a5f2890582674a0dd6a
1,677
advent-of-code
Apache License 2.0
src/main/kotlin/Problem23.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
/** * Non-abundant sums * * A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, * the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. * * A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum * exceeds n. * * As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of * two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be * written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even * though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than * this limit. * * Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. * * https://projecteuler.net/problem=23 */ fun main() { println(nonAbundantSums()) } private fun nonAbundantSums(): Int { val limit = 28123 val totalSum = (1..limit).sum() val abundants = buildList { for (n in 12..limit) { if (n.sumOfProperDivisors() > n) { add(n) } } } val abundantsSums = buildSet { for (i in abundants.indices) { for (j in i..abundants.lastIndex) { val sum = abundants[i] + abundants[j] if (sum <= limit) { add(abundants[i] + abundants[j]) } } } } return totalSum - abundantsSums.sum() }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
1,712
project-euler
MIT License
src/main/kotlin/day07.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
class Day07 : Solvable("07") { override fun solveA(input: List<String>): String { val positions = input.first().split(",").map(String::toInt) return binarySearch(positions, this::getFuel).toString() } override fun solveB(input: List<String>): String { val positions = input.first().split(",").map(String::toInt) return binarySearch(positions, this::getExpensiveFuel).toString() } private fun binarySearch(positions: List<Int>, fuelFunc: (List<Int>, Int) -> Int): Int { var l = 0 var r = positions.size - 1 var m = r / 2 while (true) { val m_left = if (m > 1) fuelFunc(positions, m - 1) else Int.MAX_VALUE val m_val = fuelFunc(positions, m) val m_right = if (m < positions.size - 1) fuelFunc(positions, m + 1) else Int.MAX_VALUE if (m_left >= m_val && m_right >= m_val) return m_val if (m_right < m_val) { l = m m = l + Math.max(1, (r - m) / 2) } else if (m_right > m_val) { r = m m = l + Math.max(1, (r - l) / 2) } } } private fun getFuel(positions: List<Int>, meetingPoint: Int): Int { return positions.map { Math.abs(it - meetingPoint) }.sum() } private fun getExpensiveFuel(positions: List<Int>, meetingPoint: Int): Int { return positions.map { Math.abs(it - meetingPoint).expensiveSum() }.sum() } } fun Int.expensiveSum() = (this * (this + 1)) / 2
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
1,534
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day21.kt
robert-iits
573,124,643
false
{"Kotlin": 21047}
import java.lang.IllegalArgumentException import java.math.BigInteger import kotlin.system.measureTimeMillis class Day21 { fun part1(input: List<String>): BigInteger { val monkeys = parseInputToMonkeys(input) val root = getMonkey("root", monkeys) while (root.number == null) { monkeys .filter { it.value.number == null } .forEach { calculateIfPossible(it.key, monkeys) } } return root.number!! } fun part2(input: List<String>): BigInteger { val monkeys = parseInputToMonkeys(input) val root = getMonkey("root", monkeys) while (monkeys[root.monkey1name]?.number != monkeys[root.monkey2name]?.number) { } return getMonkey("humn", monkeys).number!! } private fun calculateIfPossible(monkeyName: String, mapOfMonkeys: Map<String, Monkey>) { val monkey = getMonkey(monkeyName, mapOfMonkeys) if (monkey.number != null) { return } else { val monkey1value = mapOfMonkeys[monkey.monkey1name]?.number val monkey2value = mapOfMonkeys[monkey.monkey2name]?.number if (monkey1value != null && monkey2value != null) { monkey.apply { number = calculate(monkey1value, monkey2value, monkey.operator!!) } //println("applied value ${monkey.number} to $monkeyName") } } } private fun calculate(value1: BigInteger, value2: BigInteger, operator: Char): BigInteger { return when(operator) { '+' -> value1 + value2 '-' -> value1 - value2 '*' -> value1 * value2 '/' -> value1 / value2 else -> throw IllegalArgumentException("unknown operator type: $operator") } } private fun getMonkey(monkeyName: String, mapOfMonkeys: Map<String, Monkey>): Monkey { return mapOfMonkeys[monkeyName] ?: throw IllegalArgumentException("monkey not found: $monkeyName") } fun parseInputToMonkeys(input: List<String>): Map<String, Monkey> { val monkeyMap = mutableMapOf<String, Monkey>() input.forEach { monkey -> monkeyMap += parseInputLineToMonkey(monkey) } return monkeyMap } fun parseInputLineToMonkey(line: String): Map<String, Monkey> { line.split(": ").let { split -> val name = split.first() val valueOrMonkeys = split.last() var value: BigInteger? = null var monkey1name: String? = null var monkey2name: String? = null var operator: Char? = null if (valueOrMonkeys.toBigIntegerOrNull() == null) { valueOrMonkeys.split(" ").let { splitOperation -> require(splitOperation.size == 3) { "unknown operation format!" } monkey1name = splitOperation.first() operator = splitOperation[1].first() monkey2name = splitOperation.last() } } else { value = valueOrMonkeys.toBigInteger() } return mapOf(name to Monkey(monkey1name, monkey2name, operator).apply { this.number = value }) } } } class Monkey( val monkey1name: String? = null, val monkey2name: String? = null, val operator: Char? = null, ) { var number: BigInteger? = null } fun main() { val input = readInput("Day21") println("duration (ms): " + measureTimeMillis { println("part 1: " + Day21().part1(input)) }) println("duration (ms): " + measureTimeMillis { println("part 2: " + Day21().part2(input)) }) }
0
Kotlin
0
0
223017895e483a762d8aa2cdde6d597ab9256b2d
3,654
aoc2022
Apache License 2.0
src/Day07.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
private fun create(a: String, b: String): Node { return if (a == "dir") Node(name = b, inside = hashMapOf()) else Node(name = b, size = a.toInt()) } private class Node( val name: String, val size: Int? = null, val inside: MutableMap<String, Node>? = null, ) { fun advance(name: String): Node { return addIfNeeded(create("dir", name)) } fun addIfNeeded(node: Node): Node { if (node.name !in inside!!) inside[node.name] = node return inside[node.name]!! } fun isDir() = inside != null } private fun build(input: List<String>): Node { val root = create("dir", "") val curPath = mutableListOf(root) var at = 0 while (at < input.size) { val split = input[at].split(" ") when (split[1]) { "cd" -> { if (split[2] == "/") while (curPath.size > 1) curPath.removeLast() else { for (change in split[2].split("/")) { if (change == ".") continue else if (change == "..") curPath.removeLast() else curPath.add(curPath.last().advance(change)) } } } "ls" -> { while (at + 1 < input.size && !input[at + 1].startsWith("$ ")) { at++ val p = input[at].split(" ") curPath.last().addIfNeeded(create(p[0], p[1])) } } } at++ } return root } private fun allDirs(root: Node): List<Pair<Node, Int>> { val found = mutableListOf<Pair<Node, Int>>() fun dfs(cur: Node): Int { if (!cur.isDir()) return cur.size!! var sz = 0 for (i in cur.inside!!) sz += dfs(i.value) found.add(cur to sz) return sz } dfs(root) return found } fun main() { fun part1(input: List<String>): Int { val root = build(input) return allDirs(root).map { it.second }.filter { it <= 100000 }.sum() } fun part2(input: List<String>): Int { val root = build(input) val all = allDirs(root) val used = all.maxOf { it.second } val free = 70000000 - used val needFree = 30000000 - free return all.map { it.second }.filter { it >= needFree }.min() } @Suppress("DuplicatedCode") run { val day = String.format("%02d", 7) val testInput = readInput("Day${day}_test") val input = readInput("Day$day") println("Part 1 test - " + part1(testInput)) println("Part 1 real - " + part1(input)) println("---") println("Part 2 test - " + part2(testInput)) println("Part 2 real - " + part2(input)) } }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
2,767
advent-of-code-2022
Apache License 2.0
src/day9/Code.kt
fcolasuonno
162,470,286
false
null
package day9 import MultiMap import permutations import java.io.File fun main(args: Array<String>) { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } data class Distance(val city1: String, val city2: String, val dist: Int) private val lineStructure = """(\w+) to (\w+) = (\d+)""".toRegex() fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (city1, city2, dist) = it.toList() Distance(city1, city2, dist.toInt()) } }.requireNoNulls().let { distances -> MultiMap<String, String, Int>().apply { distances.forEach { this[it.city1][it.city2] = it.dist this[it.city2][it.city1] = it.dist } } } fun part1(input: MultiMap<String, String, Int>): Any? = input.keys.permutations.map { it.windowed(size = 2).sumBy { (from, to) -> input[from][to] } }.min() fun part2(input: MultiMap<String, String, Int>): Any? = input.keys.permutations.map { it.windowed(size = 2).sumBy { (from, to) -> input[from][to] } }.max()
0
Kotlin
0
0
24f54bf7be4b5d2a91a82a6998f633f353b2afb6
1,255
AOC2015
MIT License
year2019/day18/vault/src/main/kotlin/com/curtislb/adventofcode/year2019/day18/vault/search/KeySearch.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2019.day18.vault.search import com.curtislb.adventofcode.common.collection.mapToMap import com.curtislb.adventofcode.common.collection.replaceAt import com.curtislb.adventofcode.common.geometry.Point import com.curtislb.adventofcode.common.graph.UnweightedGraph import com.curtislb.adventofcode.common.graph.WeightedGraph import com.curtislb.adventofcode.year2019.day18.vault.Vault import com.curtislb.adventofcode.year2019.day18.vault.space.EntranceSpace import com.curtislb.adventofcode.year2019.day18.vault.space.KeySpace /** * A search for the shortest path through [vault] that collects all keys. */ class KeySearch(private val vault: Vault) { /** * A graph with edges from each space in the [vault] to adjacent occupiable spaces. */ private val spaceGraph = object : UnweightedGraph<Point>() { override fun getNeighbors(node: Point): Iterable<Point> = node.cardinalNeighbors().filter { vault[it]?.isOccupiable == true } } /** * A graph with edges from each possible [SearchState] to new [SearchState]s that result from * moving one searcher to the space of a non-held key, weighted by the number of spaces moved. */ inner class StateGraph( private val searchEdges: Map<Point, Map<Point, List<SearchEdge>>> ) : WeightedGraph<SearchState>() { override fun getEdges(node: SearchState): Iterable<Edge<SearchState>> = mutableListOf<Edge<SearchState>>().apply { node.positions.forEachIndexed { index, position -> searchEdges[position]?.forEach { (neighbor, searchEdges) -> val key = vault[neighbor]?.symbol if (key != null && key !in node.heldKeys) { val newPositions = node.positions.replaceAt(index) { neighbor } val newKeys = node.heldKeys.withKey(key) val newState = SearchState(newPositions, newKeys) for (searchEdge in searchEdges) { if (searchEdge.isTraversable(node.heldKeys)) { add(Edge(newState, searchEdge.distance.toLong())) } } } } } } } /** * The minimum search distance while collecting all keys. * * See [minimumSearchDistance] for more details. */ private val searchDistance: Long? by lazy { val searchEdges = findSearchEdges() val stateGraph = StateGraph(searchEdges) val source = SearchState(vault.entranceLocations, KeyCollection()) val allKeys = KeyCollection.from(vault.keyLocations.keys) stateGraph.dijkstraDistance(source) { (_, heldKeys) -> heldKeys == allKeys } } /** * Returns the minimum number of steps a group of searchers (starting from each [EntranceSpace]) * can travel while collecting all keys, or `null` if not all keys can be collected from the * searchers' starting positions. */ fun minimumSearchDistance(): Long? = searchDistance /** * Returns a map from each possible starting position ([EntranceSpace] or [KeySpace]) to a map * from each reachable key position to the [SearchEdge] representation of the path to that key. */ private fun findSearchEdges(): Map<Point, Map<Point, List<SearchEdge>>> { val keyPositions = vault.keyLocations.values.toSet() val startPositions = vault.entranceLocations.toMutableList().apply { addAll(keyPositions) } return startPositions.mapToMap { startPosition -> // Use DFS to find all paths to keys from startPosition val pathsFromStart = spaceGraph.dfsPaths(startPosition) { it in keyPositions } // Create a SearchEdge for each path and store it in the map val edgesFromStart = pathsFromStart.mapToMap { (endPosition, paths) -> endPosition to paths.map { pathPositions -> SearchEdge.fromPath(pathPositions.map { vault[it]!! }) } } startPosition to edgesFromStart } } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
4,270
AdventOfCode
MIT License
src/Day14.kt
jorgecastrejon
573,097,701
false
{"Kotlin": 33669}
import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { val map = getMapFromInput(input) return map.startDropping(stopWhen = { _, y -> y > map.bottom }) } fun part2(input: List<String>): Int { val map = getMapFromInput(input) return map.startDropping(stopWhen = { _, _ -> map.contains(500 to 0) }, limit = map.bottom + 2) } val input = readInput("Day14") println(part1(input)) println(part2(input)) } private fun MutableSet<Pair<Int, Int>>.startDropping(stopWhen: (Int, Int) -> Boolean, limit: Int? = null): Int { var x = 500 var y = 0 var count = 0 while (true) { when { stopWhen(x, y) -> return count y + 1 == limit -> { count++ add(x to y) x = 500 y = 0 } x to y + 1 !in this -> y++ x - 1 to y + 1 !in this -> { x--; y++ } x + 1 to y + 1 !in this -> { x++; y++ } else -> { count++ add(x to y) x = 500 y = 0 } } } } private fun getMapFromInput(input: List<String>): MutableSet<Pair<Int, Int>> { val set: MutableSet<Pair<Int, Int>> = mutableSetOf() input.forEach { path -> path.split(" -> ") .zipWithNext() .forEach { (start, end) -> val (x1, y1) = start.split(",").map(String::toInt) val (x2, y2) = end.split(",").map(String::toInt) val x = x2.compareTo(x1) val y = y2.compareTo(y1) val diffX = abs(x2 - x1) val diffY = abs(y2 - y1) for (i in 0..maxOf(diffX, diffY)) { set.add(x1 + (x * i) to y1 + (y * i)) } } } return set } private val Set<Pair<Int, Int>>.bottom: Int get() = maxOf { (_, y) -> y }
0
Kotlin
0
0
d83b6cea997bd18956141fa10e9188a82c138035
2,019
aoc-2022
Apache License 2.0
src/main/kotlin/adventofcode/year2020/Day17ConwayCubes.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2020 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.year2020.Day17ConwayCubes.Companion.Cube.Cube3d import adventofcode.year2020.Day17ConwayCubes.Companion.Cube.Cube4d class Day17ConwayCubes(customInput: PuzzleInput? = null) : Puzzle(customInput) { override fun partOne() = input .lines() .map { it.toCharArray().map(Char::toString) } .mapIndexed { y, row -> row.mapIndexed { x, state -> Cube3d(x, y, 0) as Cube to state } } .flatten() .toMap() .simulateBootSequence() override fun partTwo() = input .lines() .map { it.toCharArray().map(Char::toString) } .mapIndexed { y, row -> row.mapIndexed { x, state -> Cube4d(x, y, 0, 0) as Cube to state } } .flatten() .toMap() .simulateBootSequence() companion object { private const val ACTIVE = "#" private const val INACTIVE = "." sealed class Cube { abstract fun neighbors(): Set<Cube> data class Cube3d(val x: Int, val y: Int, val z: Int) : Cube() { override fun neighbors() = (-1..1).flatMap { dx -> (-1..1).flatMap { dy -> (-1..1).map { dz -> Cube3d(x + dx, y + dy, z + dz) } } }.minus(this).toSet() } data class Cube4d(val x: Int, val y: Int, val z: Int, val w: Int) : Cube() { override fun neighbors() = (-1..1).flatMap { dx -> (-1..1).flatMap { dy -> (-1..1).flatMap { dz -> (-1..1).map { dw -> Cube4d(x + dx, y + dy, z + dz, w + dw) } } } }.minus(this).toSet() } } fun Map<Cube, String>.simulateBootSequence() = generateSequence(this) { next -> ( next + next.map { (cube, _) -> (listOf(cube) + cube.neighbors()) .mapNotNull { val active = next.getOrDefault(it, INACTIVE) == ACTIVE val activeNeighbors = it.neighbors().count { next.getOrDefault(it, INACTIVE) == ACTIVE } if (active && (activeNeighbors < 2 || activeNeighbors > 3)) { it to INACTIVE } else if (!active && activeNeighbors == 3) { it to ACTIVE } else { null } } .toMap() }.reduce { acc, elem -> acc + elem } ) } .drop(1) .take(6) .last() .values .count { it == ACTIVE } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
3,110
AdventOfCode
MIT License
src/Day09.kt
AlaricLightin
572,897,551
false
{"Kotlin": 87366}
import kotlin.math.abs import kotlin.math.sign fun main() { fun solution(input: List<String>, ropeLength: Int): Int { val visitedSet = mutableSetOf<Coords>() val rope: Array<Coords> = Array(ropeLength) { Coords(0, 0) } visitedSet.add(rope.last()) input.forEach { val headMove = MOVES[it[0]]!! repeat(it.substring(2).toInt()) { rope[0] = getNewCoords(rope[0], headMove) for (i in 1 .. rope.lastIndex) { val ropeKnotMove = getMove(rope[i - 1], rope[i]) if (ropeKnotMove == Move(0, 0)) break rope[i] = getNewCoords(rope[i], ropeKnotMove) } visitedSet.add(rope.last()) } } return visitedSet.size } val testInput = readInput("Day09_test") check(solution(testInput, 2) == 13) check(solution(testInput, 10) == 1) val input = readInput("Day09") println(solution(input, 2)) println(solution(input, 10)) } private val MOVES: Map<Char, Move> = mapOf( 'R' to Move(1, 0), 'D' to Move(0, 1), 'U' to Move(0, -1), 'L' to Move(-1, 0) ) private fun getMove(headCoords: Coords, tailCoords: Coords): Move { return if (abs(headCoords.x - tailCoords.x) > 1 || abs(headCoords.y - tailCoords.y) > 1 ) Move( (headCoords.x - tailCoords.x).sign, (headCoords.y - tailCoords.y).sign ) else Move(0, 0) }
0
Kotlin
0
0
ee991f6932b038ce5e96739855df7807c6e06258
1,499
AdventOfCode2022
Apache License 2.0
src/main/kotlin/problems/Day14.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems class Day14(override val input: String) : Problem { override val number: Int = 14 private val polymerTemplate: String = input.split("\n\n").first() private val pairInsertionRules: Map<String, Char> = input.split("\n\n")[1] .lines() .map { line -> line.split(" -> ") } .associate { (pair, element) -> pair to element.single() } override fun runPartOne(): String { return runProcess(10).toString() } override fun runPartTwo(): String { return runProcess(40).toString() } private fun runProcess(steps: Int): Long { val finalPairs = (1..steps).fold(pairs(polymerTemplate)) { currentPairs, _ -> runStep(currentPairs) } val charHits = characterHits(finalPairs) .map { it.value } return charHits.maxOf { it } - charHits.minOf { it } } private fun pairs(polymer: String): Map<String, Long> { return polymer .zipWithNext() .map { (p1, p2) -> p1 + p2 } .groupingBy { it } .eachCount() .mapValues { it.value.toLong() } } private fun runStep(pairs: Map<String, Long>): Map<String, Long> { return pairs .flatMap { (pair, hits) -> listOf( (pair.first() + pairInsertionRules[pair]!!) to hits, (pairInsertionRules[pair]!! + pair.last()) to hits ) }.groupBy { it.first } .mapValues { (_, values) -> values.sumOf { (_, hits) -> hits } } } private fun characterHits(pairs: Map<String, Long>): Map<Char, Long> { return pairs .flatMap { (entry, value) -> listOf( entry[0] to value, entry[1] to value ) } .plus(polymerTemplate.first() to 1L) .plus(polymerTemplate.last() to 1L) .groupBy { it.first } .mapValues { (_, values) -> values.sumOf { (_, hits) -> hits } / 2 } } private operator fun Char.plus(other: Char): String { return this.plus(other.toString()) } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
2,175
AdventOfCode2021
MIT License
algorithms/src/main/kotlin/com/kotlinground/algorithms/dynamicprogramming/uniquepaths/uniquePaths.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.algorithms.dynamicprogramming.uniquepaths import kotlin.math.min /** * Uses a math formula to determine the number of unique paths. * We need to make n-1 + m-1 steps in total. How many ways to choose from m-1 right steps and n-1 down steps out of the * total steps? */ fun uniquePathsMath(m: Int, n: Int): Int { var ans = 1L var x = m + n - 2 val k = min(n - 1, m - 1) for (i in 1..k) { ans *= x x -= 1 ans /= i } return ans.toInt() } /** * Uses top-down approach with memoization. We begin with the position (0,0). At any position (i,j), we make a recursive * call to (i+1,j) and (i,j+1) to get the number of paths to the right and below the current node. If (i,j) goes out of * bounds, there can exist no path from it, so we simply return 0. If we reach (n-1,m-1), we have found a path and so * in this case we return 1. * * We are using memoization to store already computed value so it will reduce runtime by just accessing the already * computed value * * We are going to traverse all the unique paths, and store the values of the number of unique paths of each cell * in our cache. Slight difference, we can start at m,n and traverse towards 0,0 to get the same result, which allows * us to reuse the function as our recursive function. * * Complexity Analysis: * - Time Complexity: O(m*n) * - Space Complexity: O(m*n) */ fun uniquePathsTopDown(m: Int, n: Int): Int { val cache = hashMapOf<String, Int>() fun uniquePathsHelper(row: Int, col: Int): Int { val search = "$row#$col" return if (cache.containsKey(search)) { cache.getOrDefault(search, 0) } else if (row == 1 || col == 1) { 1 } else if (row == 0 && col == 0) { 0 } else { cache[search] = uniquePathsHelper(row - 1, col) + uniquePathsHelper(row, col - 1) cache.getOrDefault(search, 1) } } return uniquePathsHelper(m, n) } fun uniquePathsBottomUp(m: Int, n: Int): Int { var row = IntArray(n) { 1 } for (i in 0 until m) { val newRow = IntArray(n) { 1 } for (j in n - 2 downTo 0) { newRow[j] = newRow[j + 1] + row[j] } row = newRow } return row[0] }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
2,303
KotlinGround
MIT License
src/Day03.kt
semanticer
577,822,514
false
{"Kotlin": 9812}
import java.lang.Character.isUpperCase fun main() { fun part1(input: List<String>): Int { return input.sumOf { val firstCompartment = it.subSequence(0, it.length / 2) val secondCompartment = it.subSequence(it.length / 2, it.length) val charInBoth = firstCompartment.find { secondCompartment.contains(it) }!! eval(charInBoth) } } fun part2(input: List<String>): Int { return input.windowed(size = 3, step = 3).sumOf { val result = it[0].toSet() intersect it[1].toSet() intersect it[2].toSet() eval(result.first()) } } // 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() } private fun eval(char: Char): Int = (('a'..'z') + ('A'..'Z')).indexOf(char) + 1
0
Kotlin
0
0
9013cb13f0489a5c77d4392f284191cceed75b92
1,005
Kotlin-Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/Day24.kt
dlew
75,886,947
false
null
import java.util.* class Day24 constructor(input: String) { data class Coord(val x: Int, val y: Int) data class Wire(val num: Int, val loc: Coord) data class Path(val from: Int, val to: Int) val maze: List<List<Boolean>> val wires: List<Wire> val distances: Map<Path, Int> init { val wireBuilder = ArrayList<Wire>() maze = input .split('\n') .mapIndexed { y, row -> row.mapIndexed { x, item -> when (item) { '#' -> true '.' -> false else -> { wireBuilder.add(Wire(Integer.valueOf(item.toString()), Coord(x, y))) false } } } } wires = wireBuilder.sortedBy { it.num } // Pre-calculate all distances between wires distances = HashMap<Path, Int>() (0..wires.size - 1).forEach { a -> (a + 1..wires.size - 1).forEach { b -> val fastest = fastestPath(wires[a].loc, wires[b].loc) distances[Path(wires[a].num, wires[b].num)] = fastest distances[Path(wires[b].num, wires[a].num)] = fastest } } } fun fastestSolution(returnToStart: Boolean): Int { return fastest(wires[0], wires - wires[0], returnToStart) } private fun fastest(from: Wire, remainingWires: List<Wire>, returnToStart: Boolean): Int { if (remainingWires.isEmpty()) { if (returnToStart) { return distances[Path(from.num, 0)] ?: throw IllegalStateException() } else { return 0 } } var fastest = Integer.MAX_VALUE remainingWires.forEach { to -> val distance = distances[Path(from.num, to.num)] ?: throw IllegalStateException() val theRest = fastest(to, remainingWires - to, returnToStart) fastest = Math.min(fastest, distance + theRest) } return fastest } fun fastestPath(start: Coord, end: Coord): Int { val visited = HashSet<Coord>() visited.add(start) var lastVisited = listOf(start) var count = 1 while (lastVisited.isNotEmpty()) { val possibilities = lastVisited .flatMap { legalAdjacent(it) } .toSet() .filter { !visited.contains(it) } if (possibilities.contains(end)) { return count } lastVisited = possibilities visited.addAll(lastVisited) count++ } throw IllegalStateException("Should have found a solution!") } fun legalAdjacent(point: Coord): List<Coord> { val possibilities = ArrayList<Coord>() // Up if (!maze[point.y - 1][point.x]) { possibilities.add(Coord(point.x, point.y - 1)) } // Down if (!maze[point.y + 1][point.x]) { possibilities.add(Coord(point.x, point.y + 1)) } // Left if (!maze[point.y][point.x - 1]) { possibilities.add(Coord(point.x - 1, point.y)) } // Right if (!maze[point.y][point.x + 1]) { possibilities.add(Coord(point.x + 1, point.y)) } return possibilities } }
0
Kotlin
2
12
527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd
2,993
aoc-2016
MIT License
src/Day09.kt
andrikeev
574,393,673
false
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
fun main() { fun String.toCommand(): Command = split(" ") .let { (dir, steps) -> Command(Direction.valueOf(dir), steps.toInt()) } fun Position.move(direction: Direction) { when (direction) { Direction.L -> x-- Direction.U -> y++ Direction.R -> x++ Direction.D -> y-- } } fun adjustTail(head: Position, tail: Position) { when { head.x - tail.x == 2 -> { tail.x++ when { tail.y > head.y -> tail.y-- tail.y < head.y -> tail.y++ } } head.x - tail.x == -2 -> { tail.x-- when { tail.y > head.y -> tail.y-- tail.y < head.y -> tail.y++ } } head.y - tail.y == 2 -> { when { tail.x > head.x -> tail.x-- tail.x < head.x -> tail.x++ } tail.y++ } head.y - tail.y == -2 -> { when { tail.x > head.x -> tail.x-- tail.x < head.x -> tail.x++ } tail.y-- } } } fun part1(input: List<String>): Int { val head = Position(0, 0) val tail = Position(0, 0) return input.asSequence() .map(String::toCommand) .map { command -> sequence { repeat(command.steps) { head.move(command.direction) adjustTail(head, tail) yield(tail.copy()) } } } .flatten() .toSet() .count() } fun part2(input: List<String>): Int { val head = Position(0, 0) val knots = Array(9) { Position(0, 0) } return input.asSequence() .map(String::toCommand) .map { command -> sequence { repeat(command.steps) { head.move(command.direction) knots.forEachIndexed { index, knot -> val prevKnot = if (index == 0) head else knots[index - 1] adjustTail(prevKnot, knot) if (index == knots.lastIndex) { yield(knot.copy()) } } } } } .flatten() .toSet() .count() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput).also { println(it) } == 13) val testInput2 = readInput("Day09_test2") check(part2(testInput2).also { println(it) } == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) } private data class Command(val direction: Direction, val steps: Int) private enum class Direction { R, U, L, D, } private data class Position(var x: Int, var y: Int)
0
Kotlin
0
1
1aedc6c61407a28e0abcad86e2fdfe0b41add139
3,227
aoc-2022
Apache License 2.0
src/Day04.kt
melo0187
576,962,981
false
{"Kotlin": 15984}
fun main() { fun List<String>.toSectionAssignmentPairs(): List<Pair<List<Int>, List<Int>>> { fun String.toSectionIdList(): List<Int> = let { split('-', limit = 2) .takeIf { it.size == 2 } ?: throw IllegalArgumentException("String does not describe a section assignment") } .map(String::toInt) .let { (rangeStart, rangeEnd) -> (rangeStart..rangeEnd).toList() } return map { sectionAssignmentPair -> sectionAssignmentPair.split(',', limit = 2) .takeIf { it.size == 2 } ?: throw IllegalArgumentException("String does not describe a section assignment pair") }.map { (firstElfSectionAssignment, secondElfSectionAssignment) -> firstElfSectionAssignment.toSectionIdList() to secondElfSectionAssignment.toSectionIdList() } } fun part1(input: List<String>): Int = input.toSectionAssignmentPairs() .count { (firstElfSectionIdList, secondElfSectionIdList) -> firstElfSectionIdList.containsAll(secondElfSectionIdList) || secondElfSectionIdList.containsAll(firstElfSectionIdList) } fun part2(input: List<String>): Int = input.toSectionAssignmentPairs() .count { (firstElfSectionIdList, secondElfSectionIdList) -> (firstElfSectionIdList intersect secondElfSectionIdList.toSet()).isNotEmpty() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") part1(input).println() part2(input).println() }
0
Kotlin
0
0
97d47b84e5a2f97304a078c3ab76bea6672691c5
1,790
kotlin-aoc-2022
Apache License 2.0
src/Day07.kt
fouksf
572,530,146
false
{"Kotlin": 43124}
import java.io.File import java.util.Deque fun main() { class Dir(val name: String, val parent: Dir?) { val files = HashMap<String, Long>() val children = ArrayList<Dir>() fun getSize(): Long { return children.sumOf { it.getSize() } + files.values.sum() } } fun addDirContent(dir: Dir, iterator: ListIterator<String>) { var content = "" while (iterator.hasNext()) { content = iterator.next() if (content.startsWith("$")) { break } if (content.startsWith("dir")) { val child = Dir(content.split(" ")[1], dir) dir.children.add(child) } else{ dir.files[content.split(" ")[1]] = content.split(" ")[0].toLong() } } if (iterator.hasNext()) { iterator.previous() } } fun parseDirs(input: List<String>): Dir { val base = Dir("/", null) var currentDir = base val lineIterator = input.listIterator() var line = lineIterator.next() while (lineIterator.hasNext()) { line = lineIterator.next() if (line.startsWith("$ ls")) { addDirContent(currentDir, lineIterator) } else if (line.startsWith("$ cd")) { currentDir = if (line.split(" ")[2] == "..") { currentDir.parent!! } else { currentDir.children.find { it.name == line.split(" ")[2] }!! } } else { throw Exception("Hi There!") } } return base } fun getAllDirs(base: Dir): List<Dir> { val allDirs = mutableListOf(base) if (base.children.isNotEmpty()) { allDirs.addAll(base.children.map { getAllDirs(it) }.flatten()) } return allDirs } fun part1(base: Dir): Long { return getAllDirs(base).map { it.getSize() }.filter { it <= 100000 }.sum() } fun part2(base: Dir): Long { val totalSpace = 70000000 val neededSpace = 30000000 val availableSpace = totalSpace - base.getSize() val minToDeleteSpace = neededSpace - availableSpace return getAllDirs(base).map { it.getSize() }.filter { it >= minToDeleteSpace }.min() } // test if implementation meets criteria from the description, like: val dirs = parseDirs(readInput("Day07_test")) // println(part1(dirs)) println(part2(dirs)) val input = parseDirs(readInput("Day07")) // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
701bae4d350353e2c49845adcd5087f8f5409307
2,640
advent-of-code-2022
Apache License 2.0
src/Day01.kt
razvn
573,166,955
false
{"Kotlin": 27208}
fun main() { val day = "Day01" tailrec fun calcMax(acc: Int, max: Int, input: List<String>): Int { val newMax = if (acc > max) acc else max return when { input.isEmpty() -> newMax input.first().isBlank() -> calcMax(0, newMax, input.drop(1)) else -> calcMax(acc + input.first().toInt(), max, input.drop(1)) } } tailrec fun calc3Max(acc: Int, max: List<Int>, input: List<String>): Int { val newMax = (max + acc).sortedDescending().take(3) return when { input.isEmpty() -> newMax.sum() input.first().isBlank() -> calc3Max(0, newMax, input.drop(1)) else -> calc3Max(acc + input.first().toInt(), max, input.drop(1)) } } fun part1(input: List<String>): Int { return calcMax(0, 0, input) } fun part2(input: List<String>): Int { return calc3Max(0, emptyList(), input) } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput(day) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
73d1117b49111e5044273767a120142b5797a67b
1,217
aoc-2022-kotlin
Apache License 2.0
src/Day04.kt
Qdelix
574,590,362
false
null
fun main() { fun part1(input: List<String>): Int { var sum = 0 input.forEach { pair -> val first = pair.substringBefore(",") val second = pair.substringAfter(",") val firstPair = Pair(first.substringBefore("-").toInt(), first.substringAfter("-").toInt()) val secondPair = Pair(second.substringBefore("-").toInt(), second.substringAfter("-").toInt()) if (firstPair.fullyContain(secondPair) || secondPair.fullyContain(firstPair)) { sum += 1 } } return sum } fun part2(input: List<String>): Int { var sum = 0 input.forEach { pair -> val first = pair.substringBefore(",") val second = pair.substringAfter(",") val firstPair = Pair(first.substringBefore("-").toInt(), first.substringAfter("-").toInt()) val secondPair = Pair(second.substringBefore("-").toInt(), second.substringAfter("-").toInt()) if (firstPair.contain(secondPair) || secondPair.contain(firstPair)) { sum += 1 } } return sum } val input = readInput("Day04") println(part1(input)) println(part2(input)) } fun Pair<Int, Int>.fullyContain(pair: Pair<Int, Int>): Boolean { return this.first <= pair.first && this.second >= pair.second } fun Pair<Int, Int>.contain(pair: Pair<Int, Int>): Boolean { return (this.first <= pair.first && this.second >= pair.first) || (this.first >= pair.first && this.second <= pair.first) }
0
Kotlin
0
0
8e5c599d5071d9363c8f33b800b008875eb0b5f5
1,574
aoc22
Apache License 2.0
gcj/y2020/round1b/c_small.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2020.round1b private fun search(init: List<Int>): String { val queue = mutableListOf(init) val dist = mutableMapOf(init to 0) val how = mutableMapOf<List<Int>, Way?>() var index = 0 while (true) { val a = queue[index++] if (a.zipWithNext().all { it.first <= it.second }) return "${dist[a]}\n${how[a]}" for (i in 1 until a.size) for (j in i + 1..a.size) { val b = a.subList(i, j) + a.take(i) + a.drop(j) if (b in dist) continue dist[b] = dist[a]!! + 1 how[b] = Way(i, j, how[a]) queue.add(b) } } } private data class Way(val i: Int, val j: Int, val prev: Way?) { override fun toString(): String = (if (prev == null) "" else prev.toString() + "\n") + "$i ${j - i}" } private fun solve(): String { val (r, s) = readInts() val a = List(s) { List(r) { it } }.flatten() return search(a) } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,091
competitions
The Unlicense
src/main/kotlin/Excercise24.kt
underwindfall
433,989,850
false
{"Kotlin": 55774}
val inputList = getInputAsTest("24") private fun solve(range: IntProgression): Long { val cycleSize = inputList.drop(1).withIndex().first { it.value.startsWith("inp") }.index + 1 val parts = inputList.chunked(cycleSize).map { Values(it) } for (input in range) { var (z, digitPosition, submarineNumber) = Triple(0, 0, "") for (part in parts) { val digit: Int if (part.div == 1) { digit = input.toString().padStart(7, '0')[digitPosition].toString().toInt() digitPosition++ } else digit = z % 26 + part.check z = part.computeZ(digit, z) submarineNumber += digit } if (validNumber(z, submarineNumber)) return submarineNumber.toLong() } return 0 } private fun String.firstInt(includeNegative: Boolean = true) = allInts(includeNegative).first() private fun String.allInts(includeNegative: Boolean = true): List<Int> = (if (includeNegative) "(-?\\d+)" else "(\\d+)").toRegex().findAll(this).map { it.value.toInt() }.toList() private fun validNumber(z: Int, number: String) = z == 0 && number.length == 14 && !number.contains('0') /** Returns the string without the last character. */ private fun String.butLast() = substring(0, length - 1) private inline fun <T> List<T>.second(predicate: (T) -> Boolean): T { return filter { predicate(it) }[1] } data class Values(val div: Int, val check: Int, val offset: Int) { constructor(instructions: Instructions) : this( instructions.first { it.startsWith("div") }.firstInt(), // first DIV instructions.second { it.startsWith("add") }.firstInt(), // second ADD instructions.filter { it.startsWith("add") }.dropLast(1).last().firstInt() // before last ADD ) fun computeZ(w: Int, z: Int): Int { val x = if ((z % 26) + check != w) 1 else 0 return (z / div) * (25 * x + 1) + ((w + offset) * x) } } private fun partOne() = solve(9999999 downTo 1111111) // should start at 1111111, but speed it up starting near the correct answer private fun partTwo() = solve(1111111..9999999) fun main() { println("partOne() ${partOne()}") println("partTwo() ${partTwo()}") } private typealias Instructions = List<String>
0
Kotlin
0
0
4fbee48352577f3356e9b9b57d215298cdfca1ed
2,343
advent-of-code-2021
MIT License
src/Day02.kt
jdpaton
578,869,545
false
{"Kotlin": 10658}
enum class Move{ ROCK, PAPER, SCISSORS } enum class MoveNext { WIN, LOSE, DRAW } data class MoveMapper(val move: Move) { fun beats(): Move { return when(move) { Move.ROCK -> Move.SCISSORS Move.SCISSORS -> Move.PAPER Move.PAPER -> Move.ROCK } } fun draws(): Move { return move } fun loses(): Move { return when(move) { Move.ROCK -> Move.PAPER Move.SCISSORS -> Move.ROCK Move.PAPER -> Move.SCISSORS } } fun score(): Int { return when(move) { Move.ROCK -> 1 Move.PAPER -> 2 Move.SCISSORS -> 3 } } } fun mapMove(move: String): Move { return when(move) { "A", "X" -> Move.ROCK "B", "Y" -> Move.PAPER "C", "Z" -> Move.SCISSORS else -> throw RuntimeException("Unknown move: $move") } } fun mapMyNextMove(move: String): MoveNext { return when(move) { "X" -> MoveNext.LOSE "Y" -> MoveNext.DRAW "Z" -> MoveNext.WIN else -> throw RuntimeException("Unknown move: $move") } } fun main() { fun part1() { val testInput = readInput("Day02_test") var myScore = 0 testInput.forEach { line -> val moves = line.split(" ") val opponentsMove = mapMove(moves[0]) val myMove = mapMove(moves[1]) val mappedMove = MoveMapper(myMove) if (mappedMove.beats() == opponentsMove) { myScore += mappedMove.score() myScore += 6 } else if (mappedMove.draws() == opponentsMove) { myScore += mappedMove.score() myScore += 3 } else { myScore += mappedMove.score() } } println("Final Score pt1: $myScore") } fun part2() { val testInput = readInput("Day02_test") var myScore = 0 testInput.forEach { line -> val moves = line.split(" ") val opponentsMove = MoveMapper(mapMove(moves[0])) when(mapMyNextMove(moves[1])) { MoveNext.DRAW -> { myScore += MoveMapper(opponentsMove.draws()).score() + 3 } MoveNext.LOSE -> { myScore += MoveMapper(opponentsMove.beats()).score() + 0 } MoveNext.WIN -> { myScore += MoveMapper(opponentsMove.loses()).score() + 6 } } } println("Final Score pt2: $myScore") } part1() part2() }
0
Kotlin
0
0
f6738f72e2a6395815840a13dccf0f6516198d8e
2,646
aoc-2022-in-kotlin
Apache License 2.0
src/Day12.kt
Aldas25
572,846,570
false
{"Kotlin": 106964}
fun main() { fun elevation(i: Int, j: Int, grid: List<String>): Int { val c = grid[i][j] if (c in 'a'..'z') return c - 'a' if (c == 'S') return 'a' - 'a' // else c == 'E' return 'z' - 'a' } fun part1(grid: List<String>): Int { val r = grid.size val c = grid[0].length // val visited = Array(r) {Array(c) { false } } val dist = Array(r) {Array(c) { -1 } } val queue = mutableListOf<Pair<Int, Int>>() for (i in 0 until r) for (j in 0 until c) if (grid[i][j] == 'S') { queue.add(Pair(i, j)) dist[i][j] = 0 } while (queue.isNotEmpty()) { val cur = queue.removeFirst() val i = cur.first val j = cur.second if (grid[i][j] == 'E') return dist[i][j] for (adj in listOf(Pair(i-1, j), Pair(i+1, j), Pair(i, j-1), Pair(i, j+1))) { val ni = adj.first val nj = adj.second if (ni < 0 || nj < 0 || ni >= r || nj >= c) continue if (elevation(ni, nj, grid) - elevation(i, j, grid) > 1) continue if (dist[ni][nj] == -1) { dist[ni][nj] = dist[i][j] + 1 queue.add(adj) } } } return -1 } fun part2(grid: List<String>): Int { val r = grid.size val c = grid[0].length // val visited = Array(r) {Array(c) { false } } val dist = Array(r) {Array(c) { -1 } } val queue = mutableListOf<Pair<Int, Int>>() for (i in 0 until r) for (j in 0 until c) if (grid[i][j] == 'E') { queue.add(Pair(i, j)) dist[i][j] = 0 } var ans = Integer.MAX_VALUE while (queue.isNotEmpty()) { val cur = queue.removeFirst() val i = cur.first val j = cur.second if (elevation(i, j, grid) == 'a' - 'a') ans = minOf(ans, dist[i][j]) for (adj in listOf(Pair(i-1, j), Pair(i+1, j), Pair(i, j-1), Pair(i, j+1))) { val ni = adj.first val nj = adj.second if (ni < 0 || nj < 0 || ni >= r || nj >= c) continue if (elevation(ni, nj, grid) - elevation(i, j, grid) < -1) continue if (dist[ni][nj] == -1) { dist[ni][nj] = dist[i][j] + 1 queue.add(adj) } } } return ans } val filename = // "inputs/day12_sample" "inputs/day12" val input = readInput(filename) println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
80785e323369b204c1057f49f5162b8017adb55a
2,910
Advent-of-Code-2022
Apache License 2.0
src/Day04.kt
josemarcilio
572,290,152
false
{"Kotlin": 5535}
fun main() { fun part1(input: List<String>): Int { return input.count { line -> val (dumb, dumber) = line.split(',').map{ it.split('-').map(String::toInt) } val dumbContainsDumber = dumb.first() <= dumber.first() && dumb.last() >= dumber.last() val dumberContainsDumb = dumber.first() <= dumb.first() && dumber.last() >= dumb.last() dumbContainsDumber || dumberContainsDumb } } fun part2(input: List<String>): Int { return input.count { line -> val (dumb, dumber) = line.split(',').map{ it.split('-').map(String::toInt) } val dumbOverlapsDumber = dumb.first() <= dumber.last() var dumberOverlapsDumb = dumb.last() >= dumber.first() dumbOverlapsDumber && dumberOverlapsDumb } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d628345afeb014adce189fddac53a1fcd98479fb
1,098
advent-of-code-2022
Apache License 2.0
src/Day19.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
import kotlin.math.min private enum class Material { Geode, Obsidian, Clay, Ore } private data class Blueprint( val id: Int, val robots: Map<Material, Map<Material, Int>>, val maxRobotRequired: Map<Material, Int> = Material.values().associateWith { material -> robots.maxOf { if (material == Material.Geode) Int.MAX_VALUE else if (it.value.contains(material)) it.value[material]!! else 0 } } ) private data class Inventory( val materials: Map<Material, Int>, val robots: Map<Material, Int> ) private fun blueprints(input: List<String>): List<Blueprint> { val blueprintRegex = """Blueprint (\d+).*""".toRegex() val oreRobotRegex = """.*Each ore robot costs (\d+) ore\..*""".toRegex() val clayRobotRegex = """.*Each clay robot costs (\d+) ore\..*""".toRegex() val obsidianRobotRegex = """.*Each obsidian robot costs (\d+) ore and (\d+) clay\..*""".toRegex() val geodeRobotRegex = """.*Each geode robot costs (\d+) ore and (\d+) obsidian\..*""".toRegex() return input.map { line -> val id = blueprintRegex.matchEntire(line)!!.groupValues[1].toInt() val oreRobot = oreRobotRegex.matchEntire(line)!! val clayRobot = clayRobotRegex.matchEntire(line)!! val obsidianRobot = obsidianRobotRegex.matchEntire(line)!! val geodeRobot = geodeRobotRegex.matchEntire(line)!! Blueprint( id, mapOf( Material.Ore to mapOf(Material.Ore to oreRobot.groupValues[1].toInt()), Material.Clay to mapOf(Material.Ore to clayRobot.groupValues[1].toInt()), Material.Obsidian to mapOf( Material.Ore to obsidianRobot.groupValues[1].toInt(), Material.Clay to obsidianRobot.groupValues[2].toInt() ), Material.Geode to mapOf( Material.Ore to geodeRobot.groupValues[1].toInt(), Material.Obsidian to geodeRobot.groupValues[2].toInt() ) ) ) } } private fun canBuild(robot: Map<Material, Int>, inventory: Inventory): Boolean { return robot.all { robotMaterial -> inventory.materials[robotMaterial.key]!! >= robotMaterial.value } } private fun build(robot: Material, cost: Map<Material, Int>, inventory: Inventory): Inventory { val materials = inventory.materials.toMutableMap() val robots = inventory.robots.toMutableMap() cost.forEach { (material, count) -> if (materials[material]!! - count < 0) { throw IllegalStateException("Not enough material to build") } materials[material] = materials[material]!! - count } robots[robot] = robots[robot]!! + 1 return Inventory(materials, robots) } private fun timeTick(inventory: Inventory): Inventory { val materials = inventory.materials.toMutableMap() inventory.robots.forEach { (robot, productivity) -> materials[robot] = materials[robot]!! + productivity } return Inventory(materials, inventory.robots) } private data class Decision( val built: String, val notToBuilt: Set<Material>, val inventory: Inventory ) private fun simulateMaxGeode( blueprint: Blueprint, inventory: Inventory, time: Int, decisions: List<Decision> ): Pair<Int, List<Decision>> { if (time == 0) { return Pair(inventory.materials[Material.Geode]!!, decisions) } var maxGeode = Int.MIN_VALUE var maxDecision = emptyList<Decision>() val buildableRobots = mutableSetOf<Material>() for (material in Material.values()) { val robot = blueprint.robots[material]!! if (canBuild(robot, inventory)) { if (inventory.robots[material]!! < blueprint.maxRobotRequired[material]!! && !decisions.last().notToBuilt.contains(material)) { // 1. don't build more robot than max material needed in one round // 2. don't build something intentionally skipped last time // simulate build a robot var newInventory = timeTick(inventory) newInventory = build(material, robot, newInventory) val newDecisions = decisions.toMutableList() newDecisions.add(Decision(material.name, emptySet(), newInventory)) val simulationResult = simulateMaxGeode(blueprint, newInventory, time - 1, newDecisions) if (simulationResult.first > maxGeode) { maxGeode = simulationResult.first maxDecision = simulationResult.second } } buildableRobots.add(material) if (material == Material.Geode) { break } } } val newInventory = timeTick(inventory) val newDecisions = decisions.toMutableList() newDecisions.add(Decision("Noop", buildableRobots, newInventory)) val simulationResult = simulateMaxGeode(blueprint, newInventory, time - 1, newDecisions) if (simulationResult.first > maxGeode) { maxGeode = simulationResult.first maxDecision = simulationResult.second } return Pair(maxGeode, maxDecision) } private fun part1(input: List<String>): Int { val blueprints = blueprints(input) val inventory = Inventory( mapOf( Material.Ore to 0, Material.Clay to 0, Material.Obsidian to 0, Material.Geode to 0 ), mapOf( Material.Ore to 1, Material.Clay to 0, Material.Obsidian to 0, Material.Geode to 0 ) ) return blueprints.sumOf { blueprint -> val startTime = System.currentTimeMillis() val simulation = simulateMaxGeode(blueprint, inventory, 24, listOf()) println("part 1 >>>>>>") println("blueprint = ${blueprint}") println("max Geode = ${simulation.first}") println("simulation time = ${System.currentTimeMillis() - startTime}") simulation.first * blueprint.id } } private fun part2(input: List<String>): Int { val blueprints = blueprints(input).subList(0, min(3, input.size)) val inventory = Inventory( mapOf( Material.Ore to 0, Material.Clay to 0, Material.Obsidian to 0, Material.Geode to 0 ), mapOf( Material.Ore to 1, Material.Clay to 0, Material.Obsidian to 0, Material.Geode to 0 ) ) return blueprints.map { blueprint -> val startTime = System.currentTimeMillis() val simulation = simulateMaxGeode(blueprint, inventory, 32, listOf()) println("part 2 >>>>>>") println("blueprint = ${blueprint}") println("max Geode = ${simulation.first}") println("simulation time = ${System.currentTimeMillis() - startTime}") simulation.first }.reduce { acc, numOfGeode -> acc * numOfGeode } } fun main() { val input = readInput("Day19") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
7,130
advent-of-code-2022
Apache License 2.0
src/day02/Day02Answer3.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day02 import readInput /** * Answers from [Advent of Code 2022 Day 2 | Kotlin](https://youtu.be/Fn0SY2yGDSA) */ fun main() { fun score(myShape: Shape1, theirShape: Shape1): Int { return myShape.score + when { theirShape beats myShape -> 0 theirShape beatenBy myShape -> 6 else -> 3 } } fun part1(input: List<String>): Int { return input.sumOf { round -> val theirShape = Shape1(round[0]) val myShape = Shape1(round[2]) score(myShape, theirShape) } } fun part2(input: List<String>): Int { return input.sumOf { round -> val theirShape = Shape1(round[0]) // X - lose // Y - tie // Z - win val myShape = when (round[2]) { 'X' -> theirShape.prev() 'Z' -> theirShape.next() else -> theirShape } score(myShape, theirShape) } } val testInput = readInput("day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day02") println(part1(input)) // 12586 println(part2(input)) // 13193 } data class Shape1 internal constructor(val score: Int) { fun next() = Shape1((score % 3) + 1) fun prev() = if (score == 1) Shape1(3) else Shape1(score - 1) // make shapeA >\<\= shapeB possible, but only work for this case, if try to sort List<Shape1> would be break. operator fun compareTo(other: Shape1): Int { return when (other) { this -> 0 this.next() -> -1 else -> 1 } } } fun Shape1(char: Char): Shape1 { require(char in 'A'..'C' || char in 'X'..'Z') return Shape1( when (char) { 'A', 'X' -> 1 // Rock 'B', 'Y' -> 2 // Paper else -> 3 // Scissors } ) } infix fun Shape1.beats(other: Shape1) = this > other infix fun Shape1.beatenBy(other: Shape1) = this < other
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
2,055
advent-of-code-2022
Apache License 2.0
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day16.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2020 import nl.dirkgroot.adventofcode.util.Input import nl.dirkgroot.adventofcode.util.Puzzle class Day16(input: Input) : Puzzle() { class Notes(val rules: Map<String, (Int) -> Boolean>, val myTicket: List<Int>, val nearbyTickets: List<List<Int>>) private val notes by lazy { input.string().split("\n\n") .let { (rules, myTicket, nearbyTickets) -> Notes(parseRules(rules), parseTicket(myTicket), parseNearbyTickets(nearbyTickets)) } } private val ruleRegex = "(.+): (\\d+)-(\\d+) or (\\d+)-(\\d+)".toRegex() private fun parseRules(rules: String) = rules.split("\n") .map { val match = ruleRegex.matchEntire(it)!! val range1 = match.groups[2]!!.value.toInt()..match.groups[3]!!.value.toInt() val range2 = match.groups[4]!!.value.toInt()..match.groups[5]!!.value.toInt() match.groups[1]!!.value to { value: Int -> value in range1 || value in range2 } } .toMap() private fun parseNearbyTickets(nearbyTickets: String) = nearbyTickets.split("\n") .map { ticket -> parseTicket(ticket) } private fun parseTicket(ticket: String) = ticket.split(",").map { it.toInt() } override fun part1() = notes.nearbyTickets .sumOf { ticket -> ticket.filter { fieldValue -> notes.rules.values.none { it(fieldValue) } }.sum() } override fun part2(): Any { val validTickets = notes.nearbyTickets.filter { ticket -> ticket.all { fieldValue -> notes.rules.values.any { it(fieldValue) } } } val fieldRules = (0..notes.myTicket.lastIndex) .map { fieldIndex -> notes.rules.entries .filter { (_, rule) -> validTickets.all { ticket -> rule(ticket[fieldIndex]) } } .map { it.key } .toMutableList() } while (!fieldRules.all { it.size == 1 }) { fieldRules.forEach { ruleNames -> if (ruleNames.size == 1) { fieldRules.forEach { if (it.size > 1) it.remove(ruleNames[0]) } } } } return fieldRules.withIndex() .filter { (_, names) -> names[0].startsWith("departure") } .fold(1L) { acc, (index, _) -> acc * notes.myTicket[index] } } }
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
2,451
adventofcode-kotlin
MIT License
src/Day03.kt
MT-Jacobs
574,577,538
false
{"Kotlin": 19905}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val splitString: Pair<List<Char>, List<Char>> = it.halve() // since we converted to a set, technically we've destroyed some info about the comparments' contents val leftCompartment = splitString.first.toSet() val rightCompartment = splitString.second.toSet() val commonSet = leftCompartment.intersect(rightCompartment) assert(commonSet.size == 1) { "yo elf you lied to me about comparments having a single common val" } commonSet.first().priority() } } fun part2(input: List<String>): Int { return input.map { it.toSet() } .chunked(3) .sumOf { val first = it[0] val second = it[1] val third = it[2] val commonSet = first.intersect(second).intersect(third) assert(commonSet.size == 1) { "yo elf you lied to me about elves having a common val" } commonSet.first().priority() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") val part1Result = part1(testInput) check(part1Result == 1 + 27) val input = readInput("Day03") println(part1(input)) println(part2(input)) } private val priorityMap: List<Char> = ('a'..'z') + ('A'..'Z') private fun Char.priority(): Int { val result = priorityMap.indexOf(this) + 1 assert(result != 0) { "yo elf you didn't give me a char in your rucksack" } return result }
0
Kotlin
0
0
2f41a665760efc56d531e56eaa08c9afb185277c
1,630
advent-of-code-2022
Apache License 2.0
aoc/src/Hands.kt
aragos
726,211,893
false
{"Kotlin": 16232}
import Card.Companion.toCard import java.io.File fun main() { val lines = File("aoc/inputs/hands.txt").readLines() println(linesToWinnings(lines)) } internal fun linesToWinnings(lines: List<String>): Int { return lines .map { line -> HandWinnings( Hand(line.substring(0, 5).map { it.toCard() }), line.substring(6).toInt() ) } .sortedByDescending(HandWinnings::hand) .mapIndexed { ix, handWinnings -> (ix + 1) * handWinnings.winnings } .sum() } data class HandWinnings(val hand: Hand, val winnings: Int) enum class Card(val representation: Char) { Ace('A'), King('K'), Queen('Q'), // Jack('J'), Ten('T'), Nine('9'), Eight('8'), Seven('7'), Six('6'), Five('5'), Four('4'), Three('3'), Two('2'), Joker('J'); companion object { fun Char.toCard(): Card { for (card in entries) { if (this == card.representation) { return card } } throw IllegalArgumentException("Non-card character '$this'") } } } enum class Type { Five, Four, FullHouse, Three, TwoPair, OnePair, High } class Hand(private val cards: List<Card>) : Comparable<Hand> { private val distribution: Map<Card, Int> = cards.fold(mutableMapOf()) { dist, card -> dist[card] = dist.getOrDefault(card, 0) + 1 dist } private val type: Type get() { return when (distribution.size) { 1 -> Type.Five 2 -> if (distribution.values.any { it == 4 }) Type.Four else Type.FullHouse 3 -> if (distribution.values.any { it == 3 }) Type.Three else Type.TwoPair 4 -> Type.OnePair 5 -> Type.High else -> throw IllegalStateException("Wrong number of cards") } } private val complexType: Type get() { var nonJokers = 0 val distribution = cards.fold(mutableMapOf<Card, Int>()) { dist, card -> if (card != Card.Joker) { dist[card] = dist.getOrDefault(card, 0) + 1 nonJokers++ } dist } val jokers = 5 - nonJokers return when (distribution.size) { 0 -> Type.Five // All jokers 1 -> Type.Five // Jokers become the one other card type 2 -> if (distribution.values.any { it == nonJokers - 1 }) Type.Four else Type.FullHouse 3 -> if (distribution.values.any { it == 3-jokers }) Type.Three else Type.TwoPair 4 -> Type.OnePair 5 -> Type.High else -> throw IllegalStateException("Wrong number of cards") } } override operator fun compareTo(other: Hand): Int { if (this.complexType != other.complexType) { return this.complexType.compareTo(other.complexType) } for (i in 0..4) { if (this.cards[i] != other.cards[i]) { return this.cards[i].compareTo(other.cards[i]) } } return 0 } }
0
Kotlin
0
0
7bca0a857ea42d89435adc658c0ff55207ca374a
2,843
aoc2023
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year20/Day19.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year20 import com.grappenmaker.aoc.PuzzleSet fun PuzzleSet.day19() = puzzle(day = 19) { val (rulesPart, messagesPart) = input.split("\n\n") fun parseRule(rest: String) = when { rest.startsWith("\"") -> CharRule(rest.removeSurrounding("\"").single()) else -> rest.split(" | ").map { CompoundRule(it.split(" ").map(String::toInt)) } .let { it.singleOrNull() ?: OrRule(it) } } val initialRules = rulesPart.lines().associate { l -> val (numPart, rest) = l.split(": ") numPart.toInt() to parseRule(rest) } fun solve(rules: Map<Int, RuleDesc>): String { val toMatch = rules.getValue(0) return messagesPart.lines().count { toMatch.match(it, rules).any(String::isEmpty) }.s() } partOne = solve(initialRules) partTwo = solve( initialRules.toMutableMap().also { it[8] = parseRule("42 | 42 8") it[11] = parseRule("42 31 | 42 11 31") } ) } sealed interface RuleDesc { fun match(on: String, rules: Map<Int, RuleDesc>): List<String> } data class CharRule(val char: Char) : RuleDesc { override fun match(on: String, rules: Map<Int, RuleDesc>) = listOfNotNull(if (on.firstOrNull() == char) on.drop(1) else null) } data class CompoundRule(val references: List<Int>) : RuleDesc { override fun match(on: String, rules: Map<Int, RuleDesc>) = references.fold(listOf(on)) { acc, idx -> acc.flatMap { rules.getValue(idx).match(it, rules) } } } data class OrRule(val references: List<RuleDesc>) : RuleDesc { override fun match(on: String, rules: Map<Int, RuleDesc>) = references.flatMap { it.match(on, rules) } }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,698
advent-of-code
The Unlicense
kotlin/src/com/leetcode/1372_LongestZigZagPathInABinaryTree.kt
programmerr47
248,502,040
false
null
package com.leetcode import com.leetcode.data.TreeNode import java.lang.Integer.max import java.util.* class TreeZigZagNode(var value: Int) { var left: TreeZigZagNode? = null var right: TreeZigZagNode? = null var leftZigZag: Boolean? = null var maxZigZag: Int = 0 } //DFS. Time: O(n). Space: O(log(n)) private class Solution1372 { fun longestZigZag(root: TreeNode?): Int = find(root, true, 0) private fun find(node: TreeNode?, isLeft: Boolean, count: Int): Int { return when { node == null -> count - 1 isLeft -> max(find(node.left, true, 1), find(node.right, false, count + 1)) else -> max(find(node.left, true, count + 1), find(node.right, false, 1)) } } } //BFS in case if the tree is very deep. Time: O(n). Space: O(n) private class Solution1372Old1 { fun longestZigZag(root: TreeNode?): Int = root?.findMax() ?: 0 private fun TreeNode.findMax(): Int { val childQ = LinkedList<TreeNode>() val parentQ = LinkedList<TreeNode?>() val zigZagQ = LinkedList<TreeZigZagNode?>() childQ.add(this) parentQ.add(null) zigZagQ.add(null) var max = 0 while(childQ.isNotEmpty()) { val node = childQ.poll() val parent = parentQ.poll() val zigZagParent = zigZagQ.poll() val zigZag = TreeZigZagNode(node.`val`) if (parent != null) { val zzParent = zigZagParent!! if (node === parent.left) { zzParent.left = zigZag } else { zzParent.right = zigZag } val parentLeft = zzParent.leftZigZag if (parentLeft == null) { zigZag.leftZigZag = zigZag == zzParent.left zigZag.maxZigZag = 1 } else if (parentLeft && zigZag == zzParent.right) { zigZag.leftZigZag = false zigZag.maxZigZag = zzParent.maxZigZag + 1 } else if (!parentLeft && zigZag == zzParent.left) { zigZag.leftZigZag = true zigZag.maxZigZag = zzParent.maxZigZag + 1 } else { zigZag.leftZigZag = zigZag == zzParent.left zigZag.maxZigZag = 1 } } node.left?.let { childQ.push(it) parentQ.push(node) zigZagQ.push(zigZag) } node.right?.let { childQ.push(it) parentQ.push(node) zigZagQ.push(zigZag) } max = max(max, zigZag.maxZigZag) } return max } } fun main() { val solution = Solution1372() println(solution.longestZigZag(node(1) { right = node(1) { right = node(1) { right = node(1) left = node(1) { right = node(1) { right = node(1) } } } left = node(1) } })) println(solution.longestZigZag(node(1) { right = node(1) left = node(1) { right = node(1) { right = node(1) left = node(1) { right = node(1) } } } })) println(solution.longestZigZag(node(1))) } private inline fun node(value: Int, block: TreeNode.() -> Unit = {}) = TreeNode(value).apply(block)
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
3,583
problemsolving
Apache License 2.0
src/test/kotlin/io/noobymatze/aoc/y2023/Day11.kt
noobymatze
572,677,383
false
{"Kotlin": 90710}
package io.noobymatze.aoc.y2023 import io.noobymatze.aoc.Aoc import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.test.Test class Day11 { data class Pos(val row: Int, val col: Int) @Test fun test() { val input = Aoc.getInput(11) .lines() .expandRows() .expandCols() fun dist(a: Pos, b: Pos): Int = abs(a.row - b.row) + abs(a.col - b.col) val galaxies = input.flatMapIndexed { row, line -> line.mapIndexedNotNull { col, c -> if (c == '#') Pos(row, col) else null } } val galaxyPairs = galaxies.allPairs().toSet() println(galaxyPairs.sumOf { dist(it.first, it.second) }) } @Test fun test2() { val input = Aoc.getInput(11) .lines() val rowsToExpand = input.mapIndexedNotNull { i, s -> if (s.all { it == '.' }) i else null } val colsToExpand = input[0].mapIndexedNotNull { col, _ -> if (input.all { it[col] == '.' }) col else null } fun dist(a: Pos, b: Pos): Long { val c = colsToExpand.count { min(a.col, b.col) < it && it < max(a.col, b.col) } val r = rowsToExpand.count { min(a.row, b.row) < it && it < max(a.row, b.row) } val rowDiff = abs(a.row - b.row) + ((r * 1000000) - r) val colDiff = abs(a.col - b.col) + ((c * 1000000) - c) return (rowDiff + colDiff).toLong() } val galaxies = input.flatMapIndexed { row, line -> line.mapIndexedNotNull { col, c -> if (c == '#') Pos(row, col) else null } }.allPairs().toSet() println(galaxies.sumOf { dist(it.first, it.second) }) } private fun List<Pos>.allPairs(): List<Pair<Pos, Pos>> { val result = mutableListOf<Pair<Pos, Pos>>() for ((i, a) in this.withIndex()) { for (j in (1 + i) until size) { result.add(a to this[j]) } } return result } private fun List<String>.expandRows(): List<String> = flatMap { if (it.all { it == '.' }) listOf(it, it) else listOf(it) } private fun List<String>.expandCols(): List<String> { val colsToExpand = this[0].mapIndexedNotNull { col, _ -> if (all { it[col] == '.' }) col else null } println(colsToExpand) return map { val chars = it.toMutableList() for ((i, col) in colsToExpand.withIndex()) { chars.add(col + i, '.') } chars.joinToString("") } } }
0
Kotlin
0
0
da4b9d894acf04eb653dafb81a5ed3802a305901
2,666
aoc
MIT License
2015/src/main/kotlin/day22.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Graph import utils.Parse import utils.Parser import utils.Solution fun main() { Day22.run() } object Day22 : Solution<Day22.Boss>() { override val name = "day22" override val parser = Parser { parseBoss(it) } @Parse("Hit Points: {hp}\nDamage: {dmg}") data class Boss( val hp: Int, val dmg: Int, ) data class Player( val hp: Int, val mana: Int, ) data class Effect( val damage: Int = 0, val armor: Int = 0, val regen: Int = 0, ) enum class Spell( val mana: Int, val damage: Int = 0, val heal: Int = 0, val cooldown: Int = 1, val effect: Effect = Effect(), ) { MagicMissile(mana = 53, damage = 4), Drain(mana = 73, damage = 2, heal = 2), Shield(mana = 113, cooldown = 6, effect = Effect(armor = 7)), Poison(mana = 173, cooldown = 6, effect = Effect(damage = 3)), Recharge(mana = 229, cooldown = 5, effect = Effect(regen = 101)), Pass(0), } data class GameState( val turn: Int = 0, val activeSpells: Map<Spell, Int> = emptyMap(), val boss: Boss, val player: Player = Player(hp = 50, mana = 500), ) fun cast(state: GameState, spell: Spell): GameState { require(state.turn % 2 == 0) { "Cannot cast on boss turn" } require(spell !in state.activeSpells) { "Cannot cast $spell while it's active (cooldown ${state.activeSpells[spell]})" } return state.copy( activeSpells = state.activeSpells + mapOf(spell to spell.cooldown), player = state.player.copy( mana = state.player.mana - spell.mana, hp = state.player.hp + spell.heal, ), boss = state.boss.copy( hp = state.boss.hp - spell.damage, ) ) } fun Map<Spell, Int>.reduceCooldowns(): Map<Spell, Int> { return entries.filter { (_, cd) -> cd > 1 }.associate { (spell, cd) -> spell to cd - 1 } } fun turn(state: GameState): GameState { val shield = state.activeSpells.keys.sumOf { it.effect.armor } val boss = state.boss.copy( hp = state.boss.hp - state.activeSpells.keys.sumOf { it.effect.damage } ) val player = state.player.copy( mana = state.player.mana + state.activeSpells.keys.sumOf { it.effect.regen }, hp = if (state.turn % 2 == 1) { state.player.hp - (boss.dmg - shield).coerceAtLeast(0) } else state.player.hp ) return state.copy( player = player, boss = boss, turn = state.turn + 1, activeSpells = state.activeSpells.reduceCooldowns(), ) } override fun part1(): Int { val start = GameState(boss = input) val g = Graph<GameState, Spell>( edgeFn = { state -> if (state.player.hp <= 0) { // player dead emptyList() } else if (state.turn % 2 == 1) { // boss turn, nothing to do but advance listOf(Spell.Pass to turn(state)) } else { (Spell.entries.toSet() - setOf(Spell.Pass) - state.activeSpells.keys).filter { it.mana <= state.player.mana }.map { it to turn(cast(state, it)) } } }, weightFn = { it.mana } ) return g.shortestPath(start) { state -> state.boss.hp <= 0 }.first } override fun part2(): Int { val start = GameState(boss = input) val g = Graph<GameState, Spell>( edgeFn = { state -> if (state.player.hp <= ((state.turn + 1) % 2)) { // player dead emptyList() } else if (state.turn % 2 == 1) { // boss turn, nothing to do but advance listOf(Spell.Pass to turn(state)) } else { (Spell.entries.toSet() - setOf(Spell.Pass) - state.activeSpells.keys).filter { it.mana <= state.player.mana }.map { it to turn(cast(state.copy(player = state.player.copy(hp = state.player.hp - 1)), it)) } } }, weightFn = { it.mana } ) return g.shortestPath(start) { state -> state.boss.hp <= 0 && state.player.hp > -1 }.first } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
3,989
aoc_kotlin
MIT License
src/Day12.kt
bigtlb
573,081,626
false
{"Kotlin": 38940}
class Day12Graph(val nodes: MutableMap<Loc, Node> = mutableMapOf()) { fun add(node: Node) { nodes[node.loc] = node } fun path(start: Node, end: Node): List<Node>? { initialize(start) var visiting: Node? = start while (visiting != end) { visiting!!.visited = true priorityQueue.remove(visiting) visiting.adjacentNodes.filterNot { it.visited }.forEach { toNode -> priorityQueue.add(toNode) val toDistance = visiting!!.distance + 1 if (toNode.distance > toDistance) { toNode.distance = toDistance toNode.from = visiting } } visiting = priorityQueue.sortedBy { it.distance }.firstOrNull() if (visiting == null) return null } return end.path } private val priorityQueue = mutableSetOf<Node>() private fun initialize(start: Node) { priorityQueue.clear() nodes.values.map { it.visited = false it.from = null if (it.loc != start.loc) { it.distance = Int.MAX_VALUE } else { it.distance = 0 } } } class Node(val loc: Loc, var elevation: Char) { val adjacentNodes: MutableList<Node> = mutableListOf() var distance: Int = Int.MAX_VALUE var visited = false var from: Node? = null val path: List<Node> get() = from?.let { it.path + this } ?: listOf(this) } companion object { fun load(input: List<String>): Triple<Node, Node, MutableMap<Loc, Node>> { var start: Node? = null var end: Node? = null val allNodes: MutableMap<Loc, Node> = mutableMapOf() (0..input.lastIndex).map { y -> (0..input[y].lastIndex).map { x -> val node = Node(Loc(x, y), input[y][x]) node.apply { when (elevation) { 'S' -> { start = this elevation = 'a' } 'E' -> { end = this elevation = 'z' } else -> Unit } } allNodes.put(Loc(x, y), node) } } return Triple(start!!, end!!, allNodes) } fun generateGraph( allNodes: MutableMap<Loc, Node>, start: Node, end: Node ): Day12Graph { val graph = Day12Graph() graph.add(start) graph.add(end) fun adjacentNodes(node: Node): List<Node> = listOf(Loc(-1, 0), Loc(1, 0), Loc(0, -1), Loc(0, 1)).mapNotNull { move -> val newPos = node.loc + move allNodes[newPos]?.let { newNode -> if ((0..node.elevation.code + 1).contains(allNodes[newPos]!!.elevation.code)) { if (!graph.nodes.contains(newNode.loc)) { graph.add(newNode) newNode.adjacentNodes.addAll(adjacentNodes(newNode)) } newNode } else null } } start.adjacentNodes.addAll(adjacentNodes(start)) return graph } } } fun main() { fun part1(input: List<String>): Int { val (start, end, nodes) = Day12Graph.load(input) val path = Day12Graph.generateGraph(nodes, start, end).path(start, end) return path!!.count() - 1 } fun part2(input: List<String>): Int { val (_, end, nodes) = Day12Graph.load(input) return nodes.values.filter { it.elevation == 'a' }.mapNotNull { start -> Day12Graph.generateGraph(nodes, start, end).path(start, end)?.let{it.count() - 1} }.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") val part1 = part1(testInput) check(part1 == 31) check(part2(testInput) == 29) println("checked") val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8f76d3c75a30ae00c563c997ed2fb54827ea94a
4,478
aoc-2022-demo
Apache License 2.0
src/day04/Day04.kt
MaxBeauchemin
573,094,480
false
{"Kotlin": 60619}
package day04 import readInput fun main() { fun IntRange.fullyContains(other: IntRange) = this.first <= other.first && this.last >= other.last fun IntRange.overlaps(other: IntRange): Boolean { return this.first in other || this.last in other || other.first in this || other.last in this } fun toRange(txt: String): IntRange { return txt.split("-").let { it.first().toInt()..it.last().toInt() } } fun parseRanges(input: String): Pair<IntRange, IntRange> { return input.split(",").let { toRange(it.first()) to toRange(it.last()) } } fun part1(input: List<String>): Int { return input.filter { parseRanges(it).let { (firstRange, secondRange) -> firstRange.fullyContains(secondRange) || secondRange.fullyContains(firstRange) } }.size } fun part2(input: List<String>): Int { return input.filter { parseRanges(it).let { (firstRange, secondRange) -> firstRange.overlaps(secondRange) } }.size } val testInput = readInput("Day04_test") val input = readInput("Day04") println("Part 1 [Test] : ${part1(testInput)}") check(part1(testInput) == 2) println("Part 1 [Real] : ${part1(input)}") println("Part 2 [Test] : ${part2(testInput)}") check(part2(testInput) == 4) println("Part 2 [Real] : ${part2(input)}") }
0
Kotlin
0
0
38018d252183bd6b64095a8c9f2920e900863a79
1,461
advent-of-code-2022
Apache License 2.0
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12940.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12940 * * 최대공약수와 최소공배수 * 문제 설명 * 두 수를 입력받아 두 수의 최대공약수와 최소공배수를 반환하는 함수, solution을 완성해 보세요. * 배열의 맨 앞에 최대공약수, 그다음 최소공배수를 넣어 반환하면 됩니다. * 예를 들어 두 수 3, 12의 최대공약수는 3, 최소공배수는 12이므로 solution(3, 12)는 [3, 12]를 반환해야 합니다. * * 제한 사항 * 두 수는 1이상 1000000이하의 자연수입니다. * 입출력 예 * n m return * 3 12 [3, 12] * 2 5 [1, 10] * 입출력 예 설명 * 입출력 예 #1 * 위의 설명과 같습니다. * * 입출력 예 #2 * 자연수 2와 5의 최대공약수는 1, 최소공배수는 10이므로 [1, 10]을 리턴해야 합니다. */ fun main() { solution(3, 12) println(" - - - - - - - - - - ") solution(2, 5) } private fun solution(n: Int, m: Int): IntArray { var answer = intArrayOf(0, 0) answer[0] = findGCD(n, m) answer[1] = findLCM(n, m) println(answer.toList()) return answer } private fun findGCD(a: Int, b: Int): Int { return if (b == 0) { a } else { findGCD(b, a % b) } } private fun findLCM(a: Int, b: Int): Int { val gcd = findGCD(a, b) return a * b / gcd }
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
1,411
HoOne
Apache License 2.0
src/y2023/Day11.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.Pos import util.readInput import util.timingStatistics import util.transpose import y2022.Day15.manhattanDist object Day11 { private fun parse(input: List<String>): List<Pos> { val asChars = input.map { it.toCharArray().toList() }.transpose() val expandedCols = expanded(asChars).toList().transpose() val allExpanded = expanded(expandedCols).toList() return positions(allExpanded) } private fun positions(input: List<List<Char>>): List<Pos> { return input.mapIndexed { row, line -> line.mapIndexedNotNull { col, c -> if (c == '#') Pos(row, col) else null } }.flatten() } private fun expanded(input: List<List<Char>>) : Sequence<List<Char>> = sequence { input.forEach { if ('#' in it) { yield(it) } else { yield(it) yield(it) } } } fun part1(input: List<String>): Int { val parsed = parse(input) return pairWiseDistances(parsed).sum() } private fun pairWiseDistances(parsed: List<Pos>) = parsed.flatMapIndexed { idx, pos -> parsed.drop(idx + 1).map { it.manhattanDist(pos) } } fun part2(input: List<String>): Long { val parsed = parse(input) val originals = positions(input.map { it.toCharArray().toList() }) val expand1Distances = pairWiseDistances(parsed) val originalDistances = pairWiseDistances(originals) val differences = expand1Distances.zip(originalDistances).map { it.first - it.second } return originalDistances.zip(differences).sumOf { //it.first + it.second * 1_000_000L it.first + it.second * 999_999L } } } fun main() { val testInput = """ ...#...... .......#.. #......... .......... ......#... .#........ .........# .......... .......#.. #...#..... """.trimIndent().split("\n") println("------Tests------") println(Day11.part1(testInput)) println(Day11.part2(testInput)) println("------Real------") val input = readInput(2023, 11) println("Part 1 result: ${Day11.part1(input)}") println("Part 2 result: ${Day11.part2(input)}") timingStatistics { Day11.part1(input) } timingStatistics { Day11.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,435
advent-of-code
Apache License 2.0
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day10/Day10.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2022.day10 import nerok.aoc.utils.Input import java.util.* import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: List<String>): Long { var cycle = 0L var xValue = 1L var checkCycle = 20L val checkCyclePeriod = 40L val signalStrengths = emptyList<Long>().toMutableList() input.filter { it.isNotEmpty() }.forEach { line -> when { line.startsWith("noop") -> { cycle++ if (cycle == checkCycle) { signalStrengths.add(checkCycle * xValue) checkCycle += checkCyclePeriod } } line.startsWith("addx") -> { cycle++ if (cycle == checkCycle) { signalStrengths.add(checkCycle * xValue) checkCycle += checkCyclePeriod } cycle++ if (cycle == checkCycle) { signalStrengths.add(checkCycle * xValue) checkCycle += checkCyclePeriod } xValue += line.split(" ").last().toInt() } } } return signalStrengths.sum() } fun part2(input: List<String>): String { var cycle = 0L var xValue = 1L val cyclePeriod = 40L val screen = listOf(Collections.nCopies(40, '.').toCharArray()).toMutableList() fun rowPosition() = (cycle / cyclePeriod).toInt() fun columnPosition() = (cycle % cyclePeriod).toInt() fun cursor() = 1L shl (cyclePeriod.toInt() - (columnPosition() - 2)) fun sprite() = 0b111L shl ((cyclePeriod - (xValue - 1)).toInt()) input.filter { it.isNotEmpty() }.forEach { line -> when { line.startsWith("noop") -> { if (screen.size <= rowPosition()) screen.add(Collections.nCopies(40, '.').toCharArray()) screen[rowPosition()][columnPosition()] = if ((sprite() and cursor()) > 0) '#' else '.' cycle++ } line.startsWith("addx") -> { if (screen.size <= rowPosition()) screen.add(Collections.nCopies(40, '.').toCharArray()) screen[rowPosition()][columnPosition()] = if ((sprite() and cursor()) > 0) '#' else '.' cycle++ if (screen.size <= rowPosition()) screen.add(Collections.nCopies(40, '.').toCharArray()) screen[rowPosition()][columnPosition()] = if ((sprite() and cursor()) > 0) '#' else '.' cycle++ xValue += line.split(" ").last().toInt() } } } return screen.joinToString("\n") { it.joinToString("") } } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day10_test") check(part1(testInput) == 13140L) println(part2(testInput)) val input = Input.readInput("Day10") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
3,345
AOC
Apache License 2.0
src/day24/Day24.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day24 import readInput import readTestInput private data class Position(var x: Int, var y: Int) private enum class Direction { LEFT, RIGHT, UP, DOWN } private data class Blizzard(val position: Position, val direction: Direction) private data class BlizzardValley( val blizzards: List<Blizzard>, val height: Int, val width: Int, ) private fun List<String>.scanBlizzardsInValley(): BlizzardValley { val relevantRows = this.drop(1).dropLast(1) val blizzards = relevantRows.flatMapIndexed { y, row -> row.drop(1).dropLast(1).mapIndexedNotNull { x, block -> val direction = when (block) { '<' -> Direction.LEFT '>' -> Direction.RIGHT '^' -> Direction.UP 'v' -> Direction.DOWN else -> null } if (direction != null) { Blizzard(Position(x = x, y = y), direction) } else null } } return BlizzardValley( blizzards, size - 2, first().length - 2, ) } private fun lcm(lhs: Int, rhs: Int): Int { return if (lhs == 0 || rhs == 0) { 0 } else { (lhs * rhs) / gcd(lhs, rhs) } } private tailrec fun gcd(lhs: Int, rhs: Int): Int { return if (lhs == 0 || rhs == 0) { lhs + rhs } else { val largerValue = maxOf(lhs, rhs) val smallerValue = minOf(lhs, rhs) gcd(largerValue.mod(smallerValue), smallerValue) } } private fun BlizzardValley.freePositionsEachMinute(): Sequence<Array<Position>> { val freePositionsEveryMinute = mutableListOf<Array<Position>>() val roundsUntilCycleRepeats = lcm(height, width) var cycles = 0 return sequence { while (true) { val freePositions = if (cycles <= freePositionsEveryMinute.lastIndex) { freePositionsEveryMinute[cycles] } else { adjustBlizzardPositionsForNextMinute() val freePositions = findAvailablePositions().toTypedArray() freePositionsEveryMinute += freePositions freePositions } cycles = (cycles + 1).mod(roundsUntilCycleRepeats) yield(freePositions) } } } private fun BlizzardValley.adjustBlizzardPositionsForNextMinute() { for (blizzard in blizzards) { when (blizzard.direction) { Direction.LEFT -> { blizzard.position.x = (blizzard.position.x - 1).mod(width) } Direction.RIGHT -> { blizzard.position.x = (blizzard.position.x + 1).mod(width) } Direction.UP -> { blizzard.position.y = (blizzard.position.y - 1).mod(height) } Direction.DOWN -> { blizzard.position.y = (blizzard.position.y + 1).mod(height) } } } } private fun BlizzardValley.findAvailablePositions(): List<Position> { val positionsTakenByBlizzards = blizzards.groupBy { it.position }.keys val freePositions = buildList { for (y in 0 until height) { for (x in 0 until width) { val position = Position(x, y) if (position !in positionsTakenByBlizzards) { add(position) } } } } return freePositions } private fun calculateMinimumDistance( blizzardValley: BlizzardValley, freePositionsEachMinute: Iterator<Array<Position>>, start: Position, target: Position, ): Int { var rounds = 0 var positionsReachable = Array(blizzardValley.height) { BooleanArray(blizzardValley.width) } while (!positionsReachable[target.y][target.x]) { val freePositions = freePositionsEachMinute.next() val positionsReachableNextMinute = Array(blizzardValley.height) { BooleanArray(blizzardValley.width) } for (freePosition in freePositions) { val freeX = freePosition.x val freeY = freePosition.y val neighbors = listOf( freeX - 1 to freeY, // left freeX + 1 to freeY, // right freeX to freeY, // center freeX to freeY - 1, // up freeX to freeY + 1, // down ) val isReachable = neighbors.any { (checkX, checkY) -> val sanitizedX = checkX.coerceIn(0, blizzardValley.width - 1) val sanitizedY = checkY.coerceIn(0, blizzardValley.height - 1) positionsReachable[sanitizedY][sanitizedX] } if (isReachable) { positionsReachableNextMinute[freeY][freeX] = true } } // mark entry as reachable, if there is no blizzard if (start in freePositions) { positionsReachableNextMinute[start.y][start.x] = true } positionsReachable = positionsReachableNextMinute rounds += 1 } return rounds } private fun part1(input: List<String>): Int { val blizzardValley = input.scanBlizzardsInValley() val freePositionsEachMinute = blizzardValley.freePositionsEachMinute().iterator() val rounds = calculateMinimumDistance( blizzardValley = blizzardValley, freePositionsEachMinute = freePositionsEachMinute, start = Position(x = 0, y = 0), target = Position(x = blizzardValley.width - 1, y = blizzardValley.height - 1) ) return rounds + 1 } private fun part2(input: List<String>): Int { val blizzardValley = input.scanBlizzardsInValley() val freePositionsEachMinute = blizzardValley.freePositionsEachMinute().iterator() val firstTripToTarget = calculateMinimumDistance( blizzardValley = blizzardValley, freePositionsEachMinute = freePositionsEachMinute, start = Position(x = 0, y = 0), target = Position(x = blizzardValley.width - 1, y = blizzardValley.height - 1), ) + 1 freePositionsEachMinute.next() val tripToStartForSnack = calculateMinimumDistance( blizzardValley = blizzardValley, freePositionsEachMinute = freePositionsEachMinute, start = Position(x = blizzardValley.width - 1, y = blizzardValley.height - 1), target = Position(x = 0, y = 0), ) + 1 freePositionsEachMinute.next() val secondTripToTarget = calculateMinimumDistance( blizzardValley = blizzardValley, freePositionsEachMinute = freePositionsEachMinute, start = Position(x = 0, y = 0), target = Position(x = blizzardValley.width - 1, y = blizzardValley.height - 1), ) + 1 return firstTripToTarget + tripToStartForSnack + secondTripToTarget } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day24") check(part1(testInput) == 18) check(part2(testInput) == 54) val input = readInput("Day24") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
7,000
advent-of-code-kotlin-2022
Apache License 2.0
src/Day21.kt
jordan-thirus
573,476,470
false
{"Kotlin": 41711}
fun main() { fun buildMonkey(inp: String, input: List<String>): MonkeyEval { val split = inp.split(" ") val name = split[0].substringBefore(":") return if (split.size == 2) { MonkeyEval(name, Operation.RETURN, value = split[1].toLong()) } else { val monkey1Line = input.find { it.startsWith(split[1]) }!! val monkey2Line = input.find { it.startsWith(split[3]) }!! MonkeyEval( name, Operation.get(split[2]), monkey1 = buildMonkey(monkey1Line, input), monkey2 = buildMonkey(monkey2Line, input) ) } } fun part1(input: List<String>): Long { val root = buildMonkey(input.find { it.startsWith("root") }!!, input) return root.yell() } fun part2(input: List<String>): Long { val root = buildMonkey(input.find { it.startsWith("root") }!!, input) var treeContainingHuman: MonkeyEval var value: Long if(root.monkey1!!.containsHuman()){ treeContainingHuman = root.monkey1 value = root.monkey2!!.yell() } else { treeContainingHuman = root.monkey2!! value = root.monkey1.yell() } while(!treeContainingHuman.isHuman){ val monkey1 = treeContainingHuman.monkey1!! val monkey2 = treeContainingHuman.monkey2!! if(monkey1.containsHuman()){ val temp = monkey2.yell() when(treeContainingHuman.operation){ Operation.ADD -> value -= temp Operation.SUBTRACT -> value += temp Operation.MULTIPLY -> value /= temp Operation.DIVIDE -> value *= temp else -> throw Exception("Invalid Operation") } treeContainingHuman = monkey1 } else { val temp = monkey1.yell() when(treeContainingHuman.operation){ Operation.ADD -> value -= temp Operation.SUBTRACT -> value = temp - value //value = temp - monkey2.yell(); value - temp = - monkey2.yell(); temp - value = monkey2.yell() Operation.MULTIPLY -> value /= temp Operation.DIVIDE -> value = temp / value //value = temp / monkey2.yell(); value * monkey2.yell() = temp; monkey2.yell = temp / value else -> throw Exception("Invalid Operation") } treeContainingHuman = monkey2 } } treeContainingHuman.value = value //validate check(root.monkey1.yell() == root.monkey2.yell()) return value } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) } data class MonkeyEval( val name: String, val operation: Operation, var value: Long? = null, val monkey1: MonkeyEval? = null, val monkey2: MonkeyEval? = null ) { fun yell(): Long { return when (operation) { Operation.RETURN -> value!! Operation.ADD -> monkey1!!.yell() + monkey2!!.yell() Operation.SUBTRACT -> monkey1!!.yell() - monkey2!!.yell() Operation.MULTIPLY -> monkey1!!.yell() * monkey2!!.yell() Operation.DIVIDE -> monkey1!!.yell() / monkey2!!.yell() } } val isHuman: Boolean get() = name == "humn" fun containsHuman(): Boolean { return if (isHuman) true else if (value != null) false //there are no children to check else monkey1!!.containsHuman() || monkey2!!.containsHuman() //check children } }
0
Kotlin
0
0
59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e
3,859
advent-of-code-2022
Apache License 2.0
AdventOfCode/2022/aoc22/src/main/kotlin/day5.kt
benhunter
330,517,181
false
{"Rust": 172709, "Python": 143372, "Kotlin": 37623, "Java": 17629, "TypeScript": 3422, "JavaScript": 3124, "Just": 1078}
fun day5() { println("day 5") val filename = "5-input.txt" // val filename = "5-test.txt" val text = getTextFromResource(filename) val input = text.split("\n\n") var inputLines = input[0].split("\n").toMutableList().map { line -> line.chunked(4) } inputLines = inputLines.slice(0 until inputLines.size - 1) val stackHeight = inputLines.size val numStacks = inputLines.maxOf { it.size } val moves = input[1].split("\n").filter { it.isNotEmpty() } inputLines = inputLines.map { line -> line.map { it.trim() } .map { if (it.isEmpty()) "" else it[1].toString() } } val inputStacks = MutableList<MutableList<String>>(numStacks) { MutableList<String>(stackHeight) { "" } } inputLines.forEachIndexed { lineIndex, line -> line.forEachIndexed { crateIndex, crate -> inputStacks[crateIndex][lineIndex] = crate } } inputStacks.forEachIndexed { stackIndex, stack -> inputStacks[stackIndex] = stack.reversed().filter { it.isNotEmpty() }.toMutableList() } val startingStacks = inputStacks.toList() var stacks = startingStacks.toMutableList() inputLines.forEach { debugln(it.toString()) } debugln(numStacks.toString()) debugln(moves.toString()) debugStacks(stacks) moveCrates(moves, stacks, false) var part1 = "" stacks.forEach { part1 += it[it.size - 1] } println("part 1 $part1") // JCMHLVGMG debugln("part 2") stacks = startingStacks.toMutableList() moveCrates(moves, stacks, true) var part2 = "" stacks.forEach { part2 += it[it.size - 1] } println("part 2 $part2") // LVMRWSSPZ } private fun moveCrates( moves: List<String>, stacks: MutableList<MutableList<String>>, moveInOrder: Boolean ) { moves.forEach { move -> val command = move.split(" ") val quantity = command[1].toInt() val from = command[3].toInt() - 1 val to = command[5].toInt() - 1 val moving = stacks[from].slice(stacks[from].size - quantity until stacks[from].size) stacks[from] = stacks[from].slice(0 until stacks[from].size - quantity).toMutableList() if (moveInOrder) stacks[to].addAll(moving.toMutableList()) else stacks[to].addAll(moving.reversed().toMutableList()) debugStacks(stacks) } } fun debugStacks(stacks: MutableList<MutableList<String>>) { if (!DEBUG) return println("Stacks:") val longestStack = stacks.maxOf { it.size } for (i in longestStack - 1 downTo 0) { for (j in 0 until stacks.size) { if (stacks[j].size <= i) print("[ ] ") else print("[${stacks[j][i]}] ") } println() } println("End of Stacks") }
0
Rust
0
1
a424c12f4d95f9d6f8c844e36d6940a2ac11d61d
2,838
coding-challenges
MIT License
src/Day11.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
fun main() { Day11.printSolutionIfTest(10605, 2713310158L) } typealias Operation = (Long) -> Long object Day11 : Day<Long, Long>(11) { override fun part1(lines: List<String>) = parseMonkeys(lines).doRounds(20) { it / 3 }.monkeyBusiness() override fun part2(lines: List<String>):Long { val monkeys = parseMonkeys(lines) return monkeys.doRounds(10000) { it % monkeys.testProduct }.monkeyBusiness() } private fun parseMonkeys(lines: List<String>): Monkeys { val monkeys: MutableList<Monkey> = mutableListOf() lines.forEach { line -> when { line.startsWith("Monkey") -> monkeys.add(Monkey()) line.contains("Starting items: ") -> monkeys.last().items.addAll( line.substringAfter(": ").split(", ").map { it.toLong() }) line.contains("Operation") -> monkeys.last().operation = parseOperation(line.substringAfter("new = old ")) line.contains("Test") -> monkeys.last().test = line.substringAfterLast(" ").toLong() line.contains("If true: ") -> monkeys.last().trueDest = line.substringAfterLast(" ").toInt() line.contains("If false: ") -> monkeys.last().falseDest = line.substringAfterLast(" ").toInt() } } return Monkeys(monkeys) } private fun parseOperation(expr: String): Operation { val op: (Long, Long) -> Long = when (expr[0]) { '+' -> Long::plus '*' -> Long::times else -> throw Error("Unsupported op") } return when (val operand = expr.substringAfterLast(" ")) { "old" -> { a -> op(a, a) } else -> { a -> op(a, operand.toLong()) } } } class Monkeys(private val monkeys: MutableList<Monkey>) { val testProduct: Long = monkeys.map { it.test }.reduce { a, b -> a * b } fun monkeyBusiness() = monkeys.map { monkey -> monkey.inspections }.sortedDescending().take(2).reduce(Long::times) fun doRounds(rounds: Int, reductionStrategy: (Long) -> Long): Monkeys = this.also { repeat(rounds) { round(reductionStrategy) } } private fun round(reductionStrategy: (Long) -> Long) { monkeys.forEach { monkey -> monkey.items.forEach { item -> monkey.inspections++ val newItem = reductionStrategy(monkey.operation(item)) if (newItem % monkey.test == 0L) { monkeys[monkey.trueDest].items.add(newItem) } else { monkeys[monkey.falseDest].items.add(newItem) } } monkey.items.clear() } } } class Monkey { var inspections = 0L var operation: Operation = { a -> a } var test = 0L var trueDest = -1 var falseDest = -1 val items = mutableListOf<Long>() } }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
3,033
advent-of-code-2022
Apache License 2.0
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day19.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.adventofcode.twentytwenty fun List<String>.day19Part1(): Int { val ruleMap = this.filter { it.contains(":") } .associate { rule -> rule.split(":").let { it.first().trim() to it.last().trim() } } .toMutableMap() val ruleList = ruleMap.toRuleList("0") val messages = this.filter { it.contains(":").not() } return messages.count { message -> ruleList.contains(message) } } private fun Map<String, String>.toRuleList(index: String): List<String> { val ruleToBuild = this[index] when { ruleToBuild == null -> throw IllegalArgumentException("Rule does not exist") ruleToBuild.contains("\"") -> { return listOf(ruleToBuild.replace("\"", "").trim()) } ruleToBuild.contains("|") -> { return ruleToBuild.split("|") .map { orRule -> orRule .trim() .split(" ").filter { it.isNotBlank() } .map { this.toRuleList(it) } .combineRules() } .flatten() } else -> { return ruleToBuild .split(" ").filter { it.isNotBlank() } .map { this.toRuleList(it) } .combineRules() } } } private fun List<List<String>>.combineRules(): List<String> { var combinations = this.first() this.drop(1).forEach { ruleToCombine -> val tmpCombinations = mutableListOf<String>() ruleToCombine.forEach { subRule -> combinations.forEach { combination -> tmpCombinations.add(combination + subRule) } } combinations = tmpCombinations } return combinations }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
1,783
AdventOfCode
MIT License
src/net/sheltem/aoc/y2023/Day19.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2023 import net.sheltem.common.multiply import net.sheltem.aoc.y2023.Day19.Part import net.sheltem.aoc.y2023.Day19.RangePart import net.sheltem.aoc.y2023.Day19.Rule import net.sheltem.aoc.y2023.Day19.RuleSet suspend fun main() { Day19().run() } class Day19 : Day<Long>(19114, 167409079868000) { override suspend fun part1(input: List<String>): Long = input.toRuleAndPartLists().filter().sumOf { it.value }.toLong() override suspend fun part2(input: List<String>): Long = input.toRuleAndPartLists().first.let { RangePart(mutableMapOf('x' to startRange, 'm' to startRange, 'a' to startRange, 's' to startRange)).possibilities("in", it) } data class Part(val values: Map<Char, Int>) { val value = values.values.sum() } data class RangePart(val values: Map<Char, List<Int>>) { val value = values.values.map { it.size.toLong() }.multiply() fun filterLarger(char: Char, compare: Int): RangePart = this .copy(values = values.minus(char).plus(char to values[char]!!.filter { it > compare })) fun filterSmaller(char: Char, compare: Int): RangePart = this .copy(values = values.minus(char).plus(char to values[char]!!.filter { it < compare })) } data class RuleSet(val name: String, val rules: List<Rule>) { fun apply(part: Part): String { rules.forEach { rule -> val target = rule.apply(part) if (target != null) { return@apply target } } throw IllegalStateException("RuleSet $this not applicable to part $part") } } data class Rule(val field: Char? = null, val greaterThan: Boolean? = null, val comparator: Int? = null, val target: String) { fun apply(part: Part): String? = when { field == null -> target greaterThan!! -> if (part.values[field]!! > comparator!!) target else null else -> if (part.values[field]!! < comparator!!) target else null } fun apply(rangePart: RangePart): RangePart = if (greaterThan!!) rangePart.filterLarger(field!!, comparator!!) else rangePart.filterSmaller(field!!, comparator!!) fun complement(rangePart: RangePart): RangePart = if (!greaterThan!!) rangePart.filterLarger(field!!, comparator!! - 1) else rangePart.filterSmaller(field!!, comparator!! + 1) } } private fun RangePart.possibilities(ruleSetName: String, ruleSets: Map<String, RuleSet>, step: Int = 0): Long { var possibilities = 0L var workPart = this val rule = ruleSets[ruleSetName]!!.rules[step] if (rule.comparator != null) { val complement = rule.complement(workPart) workPart = rule.apply(workPart) possibilities += complement.possibilities(ruleSetName, ruleSets, step + 1) } return when (rule.target) { "A" -> possibilities + workPart.value "R" -> possibilities else -> { possibilities + workPart.possibilities(rule.target, ruleSets) } } } private fun Pair<Map<String, RuleSet>, List<Part>>.filter(): List<Part> = this.second .filter { it.acceptedBy(this.first) } private fun Part.acceptedBy(ruleSets: Map<String, RuleSet>): Boolean = generateSequence("in") { ruleSets[it]!!.apply(this) }.first { it == "R" || it == "A" } == "A" private fun List<String>.toRuleAndPartLists(): Pair<Map<String, RuleSet>, List<Part>> { val ruleSets = this.takeWhile { it != "" }.associate { line -> val name = line.takeWhile { it.isLetter() } val rules = line.drop(name.length + 1).dropLast(1).split(",").map { it.toRule() } name to RuleSet(name, rules) } val parts = this.takeLastWhile { it != "" } .map { it.drop(1).dropLast(1) } .map { line -> line.toPart() } return ruleSets to parts } private fun String.toRule(): Rule = when { this.contains(">") || this.contains("<") -> Rule(this.first(), this.contains(">"), this.split(":").first().takeLastWhile { it.isDigit() }.toInt(), this.split(":").last()) else -> Rule(target = this) } private fun String.toPart(): Part = this.split(",") .map { it.split("=") } .map { it.last().toInt() } .let { (x, m, a, s) -> Part(mapOf('x' to x, 'm' to m, 'a' to a, 's' to s)) } private val startRange = (1..4000).toList()
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
4,439
aoc
Apache License 2.0
src/main/kotlin/year2021/day-12.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2021 import lib.TraversalBreadthFirstSearch import lib.aoc.Day import lib.aoc.Part fun main() { Day(12, 2021, PartA12(), PartB12()).run() } open class PartA12 : Part() { private data class State(val pos: String, val visited: List<String>) private lateinit var edges: Map<String, List<String>> override fun parse(text: String) { edges = text .split("\n") .map { it.split("-") } .flatMap { listOf(it[0] to it[1], it[1] to it[0]) } .groupBy({ it.first }, { it.second }) } override fun compute(): String { val traversal = TraversalBreadthFirstSearch { s, _ -> nextEdges(s) } .startFrom(State("start", listOf("start"))) return traversal.count { (pos, _) -> pos == "end" }.toString() } private fun nextEdges(state: State): Iterable<State> { val (pos, visited) = state if (pos == "end") { return emptyList() } return edges.getValue(pos) .filter { visitAllowed(it, visited) } .map { State(it, visited + it) } } protected open fun visitAllowed(pos: String, visited: List<String>): Boolean = pos != pos.lowercase() || pos !in visited override val exampleAnswer: String get() = "10" } class PartB12 : PartA12() { override fun visitAllowed(pos: String, visited: List<String>): Boolean { if (pos == "start" && pos in visited) { return false } if (pos != pos.lowercase()) { return true } val visitedLowercase = visited.filter { it == it.lowercase() } val sums = visitedLowercase.groupingBy { it }.eachCount() val visitedTwoTimes = sums.filter { it.value == 2 }.size if (visitedTwoTimes == 1) { return sums.getOrDefault(pos, 0) < 1 } return visitedTwoTimes == 0 } override val exampleAnswer: String get() = "36" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
2,036
Advent-Of-Code-Kotlin
MIT License
src/aoc2023/Day10.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInput fun main() { val (year, day) = "2023" to "Day10" fun parse(input: List<String>): Pair<Array<Array<Tile>>, Tile> { val grid = buildList { val emptyLine = (1..input.first().length + 2).map { '.' }.joinToString("") add(emptyLine) addAll(input.map { ".$it." }) add(emptyLine) } var startTile = Tile() val tiles = Array(grid[0].length) { Array(grid.size) { Tile() } } grid.forEachIndexed { row, line -> line.forEachIndexed { col, tileSymbol -> var isStart = false val moves = when (tileSymbol) { 'S' -> { isStart = true listOf(Move.Up, Move.Down, Move.Left, Move.Right) } '|' -> listOf(Move.Up, Move.Down) '-' -> listOf(Move.Left, Move.Right) 'L' -> listOf(Move.Up, Move.Right) 'J' -> listOf(Move.Up, Move.Left) '7' -> listOf(Move.Left, Move.Down) 'F' -> listOf(Move.Right, Move.Down) else -> emptyList() } val tile = Tile(col, row, moves, isStart) tiles[col][row] = tile if (isStart) { startTile = tile } } } return tiles to startTile } fun getLoopTiles(tiles: Array<Array<Tile>>, startTile: Tile, move: Move): List<Tile> { val loopTiles = mutableListOf(startTile) var fromTile = startTile var currentMove = move while (true) { val nextTile = tiles.from(currentMove, fromTile) if (!nextTile.match(currentMove)) break if (nextTile.isStart) return loopTiles loopTiles.add(nextTile) fromTile = nextTile currentMove = nextTile.moves.firstOrNull { it != currentMove.opposite() } ?: break } return emptyList() } fun loopTiles(tiles: Array<Array<Tile>>, startTile: Tile): List<Tile> { return startTile.moves.map { move -> getLoopTiles(tiles, startTile, move) }.first { it.isNotEmpty() } } fun isTileInsideLoop(tile: Tile, loopTiles: List<Tile>): Boolean { if (tile in loopTiles) return false var count = 0 var j = loopTiles.lastIndex for (i in loopTiles.indices) { val pi = loopTiles[i] val pj = loopTiles[j] if (pi.row > tile.row != pj.row > tile.row && tile.col < (pj.col - pi.col) * (tile.row - pi.row) / (pj.row - pi.row) + pi.col) { count++ } j = i } return count % 2 == 1 } fun part1(input: List<String>): Int { val (tiles, start) = parse(input) val loopTiles = loopTiles(tiles, start) return loopTiles.size / 2 } fun part2(input: List<String>): Int { val (tiles, start) = parse(input) val loopTiles = loopTiles(tiles, start) val interiorTiles = tiles.sumOf { it.count { tile -> isTileInsideLoop(tile, loopTiles) } } return interiorTiles } val testInput1 = readInput(name = "${day}_p1_test1", year = year) val testInput2 = readInput(name = "${day}_p1_test2", year = year) val testInput3 = readInput(name = "${day}_p2_test1", year = year) val testInput4 = readInput(name = "${day}_p2_test2", year = year) val testInput5 = readInput(name = "${day}_p2_test3", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput1), 4) checkValue(part1(testInput2), 8) println(part1(input)) checkValue(part2(testInput3), 4) checkValue(part2(testInput4), 8) checkValue(part2(testInput5), 10) println(part2(input)) } sealed class Move(val dp: Pair<Int, Int>) { data object Up : Move(0 to -1) data object Down : Move(0 to 1) data object Left : Move(-1 to 0) data object Right : Move(1 to 0) fun opposite(): Move = when (this) { Up -> Down Down -> Up Left -> Right Right -> Left } } data class Tile( val col: Int = 0, val row: Int = 0, val moves: List<Move> = emptyList(), val isStart: Boolean = false, ) { fun match(from: Move) = moves.any { it == from.opposite() } } fun Array<Array<Tile>>.from(move: Move, tile: Tile): Tile { val (dc, dr) = move.dp val col = tile.col + dc val row = tile.row + dr return this[col][row] }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
4,635
aoc-kotlin
Apache License 2.0
src/y2022/Day05.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.readInput object Day05 { data class Move( val amount: Int, val from: Int, val to: Int ) private fun transpose(matrix: List<List<Char>>): List<List<Char>> { return List(matrix.last().last().toString().toInt()) { stackIdx -> List(matrix.size - 1) { rowIdx -> matrix[rowIdx][stackIdx] }.reversed() } } private fun stackRowsToColumns(stacks: List<String>): MutableList<MutableList<Char>> { val elements = stacks.map { row -> row.chunked(4).map { it[1] } .toList() } return transpose(elements).map { row -> row.takeWhile { it != ' ' }.toMutableList() }.toMutableList() } fun part1(stacks: List<String>, moves: List<String>): String { val stackLists = stackRowsToColumns(stacks) val parsedMoves = parseMoves(moves) parsedMoves.forEach { applyMove(it, stackLists) } println(stackLists) return stackLists.map { it.last() }.joinToString("") } private fun applyMove(move: Move, stacks: MutableList<MutableList<Char>>) { repeat(move.amount) { stacks[move.to].add(stacks[move.from].last()) stacks[move.from].removeLast() } } private fun parseMoves(moves: List<String>): List<Move> { return moves.map { val splits = it.split(' ') Move(splits[1].toInt(), splits[3].toInt() - 1, splits[5].toInt() - 1) } } fun part2(stacks: List<String>, moves: List<String>): String { val stackLists = stackRowsToColumns(stacks) val parsedMoves = parseMoves(moves) parsedMoves.forEach { applyMove2(it, stackLists) } println(stackLists) return stackLists.map { it.last() }.joinToString("") } private fun applyMove2(move: Move, stacks: MutableList<MutableList<Char>>) { stacks[move.to].addAll(stacks[move.from].takeLast(move.amount)) stacks[move.from] = stacks[move.from].dropLast(move.amount).toMutableList() } } /* [H] [D] [P] [W] [B] [C] [Z] [D] [T] [J] [T] [J] [D] [J] [H] [Z] [H] [H] [W] [S] [M] [P] [F] [R] [P] [Z] [F] [W] [F] [J] [V] [T] [N] [F] [G] [Z] [S] [S] [C] [R] [P] [S] [V] [M] [V] [D] [Z] [F] [G] [H] [Z] [N] [P] [M] [N] [D] 1 2 3 4 5 6 7 8 9 */ fun main() { val input = readInput("resources/2022/day05") val stacks = input.takeWhile { it.isNotEmpty() } val moves = input.dropWhile { it.isNotEmpty() }.drop(1) println(Day05.part1(stacks, moves)) println(Day05.part2(stacks, moves)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,702
advent-of-code
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2022/day19/Day19.kt
jacobhyphenated
573,603,184
false
{"Kotlin": 144303}
package com.jacobhyphenated.advent2022.day19 import com.jacobhyphenated.advent2022.Day /** * Day 19: Not Enough Minerals * * We want to collect geodes using a geode producing robot. * To build the robot we need other materials, and materials to build robots to harvest those materials. * It takes 1 minute for a robot to collect a material and 1 minute to build a robot. * * We have several blueprints that show different ways to manufacture robots (must use one blueprint at a time). * We start with 1 ore producing robot. */ class Day19: Day<List<Blueprint>> { override fun getInput(): List<Blueprint> { return parseInput(readInputFile("day19")) } /** * Find out how many geodes we can collect in 24 minutes. * The in quality level is the blueprint's id (index + 1) * the most geodes you can collect with that blueprint. * Return the sum of all quality levels for the list of blueprints */ override fun part1(input: List<Blueprint>): Int { return input.mapIndexed { i, blueprint -> (i+1) * maximizeGeodes(Manufacture(blueprint), 24) }.sum() } /** * Now we have 32 minutes, but we only have the first 3 blueprints. * Multiply the total number of geodes we collect for each blueprint */ override fun part2(input: List<Blueprint>): Int { val blueprints = input.take(3) return blueprints.fold(1) { acc, blueprint -> acc * maximizeGeodes(Manufacture(blueprint), 32) } } /** * Recursive DFS and memoization * * @param manufacture Represents a comprehensive look at state, including blueprint, robot counts, and material counts * @param minute How many minutes are left * @param solutions a set of known solutions to the problem, used to prune DFS branches * @param duplicates a store of the state (manufacture + minute) that we have already solved. * Used to avoid visiting a DFS branch we have already visited */ private fun maximizeGeodes(manufacture: Manufacture, minute: Int, solutions: MutableSet<Int> = mutableSetOf(0), duplicates: MutableMap<Pair<ManufactureState, Int>, Int> = mutableMapOf()): Int { // Time's up. How many geodes did we collect? if (minute <= 0) { solutions.add( manufacture.materialCounts[Material.GEODE] ?: 0) return manufacture.materialCounts[Material.GEODE] ?: 0 } // Have we seen this state before? If so, use memoization to skip repeating work val currentState = manufacture.exportState() if (Pair(currentState, minute) in duplicates) { return duplicates[Pair(currentState, minute)]!! } // Let's assume we can create a new Geode robot once per minute val n = minute - 1 val currentGeodeProduction = minute * (manufacture.robotCounts[Material.GEODE] ?: 0) val currentGeodeCount = manufacture.materialCounts[Material.GEODE] ?: 0 // use sequence 1+2+3+...+n == (n * (n+1)) / 2 val theoreticalMax = ((n * (n+1)) / 2) + currentGeodeProduction + currentGeodeCount // The theoretical max (best case geode production from current state) must be better than a known solution if (theoreticalMax < solutions.max()) { duplicates[Pair(currentState, minute)] = 0 return 0 } // If we can build a geode robot, do that - no need to explore other options if (manufacture.canBuild(Material.GEODE)) { val newOption = manufacture.copy() newOption.build(Material.GEODE) newOption.materialCounts[Material.GEODE] = (newOption.materialCounts[Material.GEODE] ?: 0) - 1 newOption.collect() return maximizeGeodes(newOption, minute - 1, solutions, duplicates).also { duplicates[Pair(currentState, minute)] = it } } val paths = mutableListOf<Int>() for (material in Material.values()) { // we don't need to build another robot if the robot count >= the max cost needed to build something if ((manufacture.robotCounts[material] ?: 0) >= manufacture.maxMaterialNeeded.getValue(material)) { continue } if (manufacture.canBuild(material)) { val newOption = manufacture.copy() newOption.build(material) // don't count this new robot for this round newOption.materialCounts[material] = (newOption.materialCounts[material] ?: 0) - 1 newOption.collect() paths.add(maximizeGeodes(newOption, minute - 1, solutions, duplicates)) } } val skipBuild = manufacture.copy() skipBuild.collect() paths.add(maximizeGeodes(skipBuild, minute - 1, solutions, duplicates)) return paths.max().also { duplicates[Pair(currentState, minute)] = it } } fun parseInput(input: String): List<Blueprint> { return input.lines().map { line -> val (_, blueprintLine) = line.split(": ") val costMap = blueprintLine.removeSuffix(".").split(". ").associate { robotLine -> val (materialPart, costPart) = robotLine.split(" robot costs ") val material = materialFromString(materialPart.split(" ").last()) val costs = costPart.split(" and ").map { componentPart -> val (cost, mat) = componentPart.split(" ").map { it.trim() } Pair(materialFromString(mat), cost.toInt()) } material to costs } Blueprint(costMap) } } private fun materialFromString(s: String): Material { return when(s) { "ore" -> Material.ORE "clay" -> Material.CLAY "obsidian" -> Material.OBSIDIAN "geode" -> Material.GEODE else -> throw NotImplementedError("Invalid material: $s") } } } class Blueprint( val robotCosts: Map<Material, List<Pair<Material, Int>>> ) enum class Material { ORE, CLAY, OBSIDIAN, GEODE } class Manufacture( private val blueprint: Blueprint, var materialCounts: MutableMap<Material, Int> = mutableMapOf(), var robotCounts: MutableMap<Material, Int> = mutableMapOf(Material.ORE to 1) ){ val maxMaterialNeeded: Map<Material, Int> = Material.values().associateWith { material -> blueprint.robotCosts.values .flatten() .filter { (mat, _) -> mat == material } .maxOfOrNull { (_, cost) -> cost } ?: Int.MAX_VALUE } fun copy(): Manufacture { return Manufacture(blueprint, materialCounts.copyToMutable(), robotCounts.copyToMutable() ) } fun canBuild(material: Material): Boolean { return blueprint.robotCosts.getValue(material).all { (input, cost) -> (materialCounts[input] ?: 0) >= cost } } fun build(material: Material) { blueprint.robotCosts.getValue(material).forEach { (input, cost) -> materialCounts[input] = materialCounts.getValue(input) - cost } robotCounts[material] = (robotCounts[material] ?: 0) + 1 } fun collect() { robotCounts.forEach{ (robot, count) -> materialCounts[robot] = (materialCounts[robot] ?: 0 ) + count } } fun exportState(): ManufactureState { val materials = Material.values().map { material -> materialCounts[material] ?: 0 }.toIntArray() val robots = Material.values().map { material -> robotCounts[material] ?: 0 }.toIntArray() return ManufactureState(materials, robots) } } /** * Optimize for storage and performance using primitive IntArrays * Override equals and hash code implementations for Array types as data classes prefer List<T> */ data class ManufactureState(val materials: IntArray, val robots: IntArray) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ManufactureState if (!materials.contentEquals(other.materials)) return false if (!robots.contentEquals(other.robots)) return false return true } override fun hashCode(): Int { var result = materials.contentHashCode() result = 31 * result + robots.contentHashCode() return result } } fun <K,V> Map<K,V>.copyToMutable(): MutableMap<K,V> { return this.map { (key,value) -> key to value }.toMap().toMutableMap() }
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
8,682
advent2022
The Unlicense
facebook/y2020/round3/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2020.round3 private fun solve(): String { val (n, k) = readInts() data class Measurement(val time: Int, val p: Int, val r: Int) val measurements = List(n) { val (p, r) = readInts() Measurement(it, p, r) } val ps = measurements.map { it.p }.toSet().sorted() var a = Array(k + 1) { n + 1 to 0 } a[0] = 0 to 0 for (p in ps) { val ms = measurements.filter { it.p == p } val b = Array(k + 1) { n + 1 to 0 } for (crosses in 0..ms.size) { if (crosses > 0 && ms[crosses - 1].r == 1) continue var toDelete = 0 for (i in ms.indices) { if (i < crosses && ms[i].r == 1) toDelete++ if (i >= crosses && ms[i].r == 0) toDelete++ } val lastCross = if (crosses == 0) -1 else ms[crosses - 1].time val firstTick = if (crosses == ms.size) n else ms[crosses].time for (q in 0..k) { } } a = b } return "" } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,120
competitions
The Unlicense
src/main/kotlin/aoc23/Day09.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc23 import common.Year23 import aoc23.Day09Domain.Oasis import aoc23.Day09Parser.toOasis import aoc23.Day09Solution.part1Day09 import aoc23.Day09Solution.part2Day09 object Day09 : Year23 { fun List<String>.part1(): Int = part1Day09() fun List<String>.part2(): Int = part2Day09() } object Day09Solution { fun List<String>.part1Day09(): Int = with(toOasis()) { reportWithDifferences { predictNext() } }.sum() fun List<String>.part2Day09(): Int = with(toOasis()) { reportWithDifferences { predictPrevious() } }.sum() } object Day09Domain { data class Oasis( val report: List<List<Int>> ) { fun reportWithDifferences(predict: List<List<Int>>.() -> Int): List<Int> = report .map { history -> history.withDifferences().predict() } fun List<List<Int>>.predictNext(): Int = this.map { it.last() }.sum() fun List<List<Int>>.predictPrevious(): Int = this.map { it.first() } .foldRight(0) { i, acc -> i - acc } private fun List<Int>.withDifferences(): List<List<Int>> = generateSequence(this) { ints -> ints.windowed(2) { (x, y) -> y - x } } .takeWhile { it.any { difference -> difference != 0 } } .toList() } } object Day09Parser { fun List<String>.toOasis(): Oasis = Oasis( report = this.map { history -> history.split(" ").map { it.toInt() } } ) }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
1,580
aoc
Apache License 2.0
src/Day13.kt
cisimon7
573,872,773
false
{"Kotlin": 41406}
fun main() { fun part1(pairs: List<Pair<Packet.Parent, Packet.Parent>>): Int { return pairs.map { (left, right) -> compare(left, right) } .mapIndexed { idx, case -> idx + 1 to case } .filter { (_, case) -> case == true } .sumOf { (idx, _) -> idx } } fun part2(pairs: List<Pair<Packet.Parent, Packet.Parent>>): Int { val divider1 = Packet.Parent(mutableListOf(Packet.Parent(mutableListOf(Packet.Child(2))))) val divider2 = Packet.Parent(mutableListOf(Packet.Parent(mutableListOf(Packet.Child(6))))) val packets = (pairs + (divider1 to divider2)) .map { (left, right) -> listOf(left, right) } .flatten() .sortedWith { first, second -> when (compare(first, second)) { true -> 1 false -> -1 null -> 0 } }.reversed() val idx1 = packets.indexOf(divider1) + 1 val idx2 = packets.indexOf(divider2) + 1 return idx1 * idx2 } fun parse(stringList: List<String>): List<Pair<Packet.Parent, Packet.Parent>> { return stringList.windowed(2, 3).map { line -> packetify(line[0].drop(1)) to packetify(line[1].drop(1)) } } val testInput = readInput("Day13_test") check(part1(parse(testInput)) == 13) check(part2(parse(testInput)) == 140) val input = readInput("Day13_input") println(part1(parse(input))) println(part2(parse(input))) } tailrec fun compare(left: Packet.Parent, right: Packet.Parent): Boolean? { val leftNext = left.children.firstOrNull() val rightNext = right.children.firstOrNull() return when { leftNext is Packet.Parent && rightNext is Packet.Parent -> compare(leftNext, rightNext) ?: compare( Packet.Parent(left.children.drop(1).toMutableList()), Packet.Parent(right.children.drop(1).toMutableList()) ) leftNext is Packet.Child && rightNext is Packet.Child -> if (leftNext.value == rightNext.value) { compare( Packet.Parent(left.children.drop(1).toMutableList()), Packet.Parent(right.children.drop(1).toMutableList()) ) } else leftNext.value < rightNext.value leftNext is Packet.Child && rightNext is Packet.Parent -> compare( Packet.Parent(mutableListOf(Packet.Parent(mutableListOf(leftNext)))), right ) leftNext is Packet.Parent && rightNext is Packet.Child -> compare( left, Packet.Parent(mutableListOf(Packet.Parent(mutableListOf(rightNext)))) ) leftNext == null && rightNext == null -> null leftNext == null && rightNext != null -> true leftNext != null && rightNext == null -> false else -> error("unknown pair") } } tailrec fun packetify( line: String, parent: Packet.Parent = Packet.Parent(), lineage: MutableList<Packet.Parent> = mutableListOf() ): Packet.Parent { return when { line.isEmpty() -> parent line.first() == ',' -> packetify(line.drop(1), parent, lineage) line.first() == '[' -> packetify(line.drop(1), Packet.Parent(), (lineage + parent).toMutableList()) line.first() == ']' -> if (lineage.isEmpty()) parent else { val grandParent = lineage.last() grandParent.children.add(parent) packetify(line.drop(1), grandParent, lineage.dropLast(1).toMutableList()) } else -> { val childIdx = line.indexOfFirst { it == ',' || it == ']' } parent.children.add(Packet.Child(line.take(childIdx).toInt())) packetify(line.drop(childIdx), parent, lineage) } } } sealed interface Packet { class Child(val value: Int) : Packet class Parent(val children: MutableList<Packet> = mutableListOf()) : Packet } /** * --- Day 13: Distress Signal --- * You climb the hill and again try contacting the Elves. However, you instead receive a signal you weren't expecting: a distress signal. * * Your handheld device must still not be working properly; the packets from the distress signal got decoded out of order. You'll need to re-order the list of received packets (your puzzle input) to decode the message. * * Your list consists of pairs of packets; pairs are separated by a blank line. You need to identify how many pairs of packets are in the right order. * * For example: * * [1,1,3,1,1] * [1,1,5,1,1] * * [[1],[2,3,4]] * [[1],4] * * [9] * [[8,7,6]] * * [[4,4],4,4] * [[4,4],4,4,4] * * [7,7,7,7] * [7,7,7] * * [] * [3] * * [[[]]] * [[]] * * [1,[2,[3,[4,[5,6,7]]]],8,9] * [1,[2,[3,[4,[5,6,0]]]],8,9] * Packet data consists of lists and integers. Each list starts with [, ends with ], and contains zero or more comma-separated values (either integers or other lists). Each packet is always a list and appears on its own line. * * When comparing two values, the first value is called left and the second value is called right. Then: * * If both values are integers, the lower integer should come first. If the left integer is lower than the right integer, the inputs are in the right order. If the left integer is higher than the right integer, the inputs are not in the right order. Otherwise, the inputs are the same integer; continue checking the next part of the input. * If both values are lists, compare the first value of each list, then the second value, and so on. If the left list runs out of items first, the inputs are in the right order. If the right list runs out of items first, the inputs are not in the right order. If the lists are the same length and no comparison makes a decision about the order, continue checking the next part of the input. * If exactly one value is an integer, convert the integer to a list which contains that integer as its only value, then retry the comparison. For example, if comparing [0,0,0] and 2, convert the right value to [2] (a list containing 2); the result is then found by instead comparing [0,0,0] and [2]. * Using these rules, you can determine which of the pairs in the example are in the right order: * * == Pair 1 == * - Compare [1,1,3,1,1] vs [1,1,5,1,1] * - Compare 1 vs 1 * - Compare 1 vs 1 * - Compare 3 vs 5 * - Left side is smaller, so inputs are in the right order * * == Pair 2 == * - Compare [[1],[2,3,4]] vs [[1],4] * - Compare [1] vs [1] * - Compare 1 vs 1 * - Compare [2,3,4] vs 4 * - Mixed types; convert right to [4] and retry comparison * - Compare [2,3,4] vs [4] * - Compare 2 vs 4 * - Left side is smaller, so inputs are in the right order * * == Pair 3 == * - Compare [9] vs [[8,7,6]] * - Compare 9 vs [8,7,6] * - Mixed types; convert left to [9] and retry comparison * - Compare [9] vs [8,7,6] * - Compare 9 vs 8 * - Right side is smaller, so inputs are not in the right order * * == Pair 4 == * - Compare [[4,4],4,4] vs [[4,4],4,4,4] * - Compare [4,4] vs [4,4] * - Compare 4 vs 4 * - Compare 4 vs 4 * - Compare 4 vs 4 * - Compare 4 vs 4 * - Left side ran out of items, so inputs are in the right order * * == Pair 5 == * - Compare [7,7,7,7] vs [7,7,7] * - Compare 7 vs 7 * - Compare 7 vs 7 * - Compare 7 vs 7 * - Right side ran out of items, so inputs are not in the right order * * == Pair 6 == * - Compare [] vs [3] * - Left side ran out of items, so inputs are in the right order * * == Pair 7 == * - Compare [[[]]] vs [[]] * - Compare [[]] vs [] * - Right side ran out of items, so inputs are not in the right order * * == Pair 8 == * - Compare [1,[2,[3,[4,[5,6,7]]]],8,9] vs [1,[2,[3,[4,[5,6,0]]]],8,9] * - Compare 1 vs 1 * - Compare [2,[3,[4,[5,6,7]]]] vs [2,[3,[4,[5,6,0]]]] * - Compare 2 vs 2 * - Compare [3,[4,[5,6,7]]] vs [3,[4,[5,6,0]]] * - Compare 3 vs 3 * - Compare [4,[5,6,7]] vs [4,[5,6,0]] * - Compare 4 vs 4 * - Compare [5,6,7] vs [5,6,0] * - Compare 5 vs 5 * - Compare 6 vs 6 * - Compare 7 vs 0 * - Right side is smaller, so inputs are not in the right order * What are the indices of the pairs that are already in the right order? (The first pair has index 1, the second pair has index 2, and so on.) In the above example, the pairs in the right order are 1, 2, 4, and 6; the sum of these indices is 13. * * Determine which pairs of packets are already in the right order. What is the sum of the indices of those pairs? * * Your puzzle answer was 5555. * * --- Part Two --- * Now, you just need to put all of the packets in the right order. Disregard the blank lines in your list of received packets. * * The distress signal protocol also requires that you include two additional divider packets: * * [[2]] * [[6]] * Using the same rules as before, organize all packets - the ones in your list of received packets as well as the two divider packets - into the correct order. * * For the example above, the result of putting the packets in the correct order is: * * [] * [[]] * [[[]]] * [1,1,3,1,1] * [1,1,5,1,1] * [[1],[2,3,4]] * [1,[2,[3,[4,[5,6,0]]]],8,9] * [1,[2,[3,[4,[5,6,7]]]],8,9] * [[1],4] * [[2]] * [3] * [[4,4],4,4] * [[4,4],4,4,4] * [[6]] * [7,7,7] * [7,7,7,7] * [[8,7,6]] * [9] * Afterward, locate the divider packets. To find the decoder key for this distress signal, you need to determine the indices of the two divider packets and multiply them together. (The first packet is at index 1, the second packet is at index 2, and so on.) In this example, the divider packets are 10th and 14th, and so the decoder key is 140. * * Organize all of the packets into the correct order. What is the decoder key for the distress signal? * * Your puzzle answer was 22852. * * Both parts of this puzzle are complete! They provide two gold stars: ** * * At this point, you should return to your Advent calendar and try another puzzle.*/
0
Kotlin
0
0
29f9cb46955c0f371908996cc729742dc0387017
10,078
aoc-2022
Apache License 2.0
src/day07/Day07.kt
barbulescu
572,834,428
false
{"Kotlin": 17042}
package day07 import readInput private val root = Directory(null, "/") fun main() { var currentDirectory = root val content = readInput("day07/Day07").joinToString(separator = "|") content.split("$").asSequence() .map { it.trim() } .filterNot { it.isBlank() } .map { if (it.endsWith("|")) it.dropLast(1) else it } .onEach { println("Line: $it") } .forEach { currentDirectory = executeCommand(currentDirectory, it) } root.calculateTotalSize() println() println("----------------------------") root.printTree("") println("----------------------------") println() val sizes = mutableListOf<Int>() root.collectTotalSizes(sizes) val sum = sizes .filter { it < 100000 } .sum() println("Sum of folder under 100000 is $sum") val totalSpace = 70000000 val necessarySpace = 30000000 val currentFreeSpace = totalSpace - root.totalSize() val spaceToFree = necessarySpace - currentFreeSpace println("current free space: $currentFreeSpace and space to free up $spaceToFree") val directoryToDelete = sizes .filter { it >= spaceToFree } .minOf { it } println("Directory to delete: $directoryToDelete") } private fun executeCommand(currentDirectory: Directory, commandText: String): Directory = when { commandText == "cd /" -> root commandText == "cd .." -> currentDirectory.toParent() commandText.startsWith("cd") -> { val directoryName = commandText.drop(3) currentDirectory.toChild(directoryName) } commandText.startsWith("ls") -> { commandText.drop(3) .split("|") .forEach { command -> println("Command: $command") if (command.startsWith("dir")) { currentDirectory.addDirectory(command.drop(4)) } else { val parts = command.split(" ") currentDirectory.addFile(parts[1], parts[0].toInt()) } } currentDirectory } else -> throw IllegalArgumentException("Unknow command $commandText") } private class Directory(val parent: Directory?, val name: String) { private val files = mutableListOf<File>() private val directories = mutableListOf<Directory>() private var totalSize: Int = 0 fun addFile(filename: String, size: Int): Directory { files.add(File(filename, size)) return this } fun addDirectory(directoryName: String): Directory { directories.add(Directory(this, directoryName)) return this } fun toParent(): Directory { return requireNotNull(parent) { "Already in root directory" } } fun toChild(directoryName: String): Directory { return directories .first { it.name == directoryName } } fun printTree(prefix: String) { println("$prefix- $name (dir, size=$totalSize)") directories.forEach { it.printTree(" $prefix") } files.forEach { println("$prefix - ${it.name} (file, size=${it.size})") } } fun calculateTotalSize() { val subSizes = directories .onEach { it.calculateTotalSize() } .sumOf { it.totalSize } val fileSizes = files.sumOf { it.size } totalSize = subSizes + fileSizes } fun collectTotalSizes(collector: MutableList<Int>) { directories.forEach { it.collectTotalSizes(collector) } collector.add(this.totalSize) } fun totalSize() = totalSize } private data class File(val name: String, val size: Int)
0
Kotlin
0
0
89bccafb91b4494bfe4d6563f190d1b789cde7a4
3,708
aoc-2022-in-kotlin
Apache License 2.0
src/Day24.kt
dakr0013
572,861,855
false
{"Kotlin": 105418}
import java.util.LinkedList import java.util.Queue import kotlin.math.min import kotlin.test.assertEquals fun main() { fun part1(input: List<String>): Int { return Valley(input.drop(1).dropLast(1).map { it.drop(1).dropLast(1) }).minutesToGoal() } fun part2(input: List<String>): Int { return Valley(input.drop(1).dropLast(1).map { it.drop(1).dropLast(1) }) .minutesToGoalBackToStartAndBackToGoal() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day24_test") assertEquals(18, part1(testInput)) assertEquals(54, part2(testInput)) val input = readInput("Day24") println(part1(input)) println(part2(input)) } class Valley(val map: List<String>) { private val maxRows = map.size private val maxCols = map[0].length fun minutesToGoal() = minutesTo(maxRows - 1, maxCols - 1, State(-1, 0, 0)) fun minutesToGoalBackToStartAndBackToGoal(): Int { val minutesPart1 = minutesTo(maxRows - 1, maxCols - 1, State(-1, 0, 0)) val minutesPart1And2 = minutesTo(0, 0, State(maxRows, maxCols - 1, minutesPart1)) return minutesTo(maxRows - 1, maxCols - 1, State(-1, 0, minutesPart1And2)) } private fun minutesTo(targetRow: Int, targetCol: Int, initialState: State): Int { val discoveredStates = mutableSetOf<State>() val queue: Queue<State> = LinkedList() queue.add(initialState) var minMinutes = Int.MAX_VALUE while (queue.isNotEmpty()) { val state = queue.poll() if (state.row == targetRow && state.column == targetCol) { minMinutes = min(minMinutes, state.time + 1) continue } val nextValidStates = state.nextStates().filter { it.isValid() } for (nextState in nextValidStates) { if (!discoveredStates.contains(nextState) && nextState.time < minMinutes) { discoveredStates.add(nextState) queue.add(nextState) } } } return minMinutes } private fun State.isValid(): Boolean { return isStartPosition() || isGoalPosition() || row in 0 until maxRows && column in 0 until maxCols && map[row][(column + time).mod(maxCols)] != '<' && map[row][(column - time).mod(maxCols)] != '>' && map[(row + time).mod(maxRows)][column] != '^' && map[(row - time).mod(maxRows)][column] != 'v' } private fun State.isStartPosition() = row == -1 && column == 0 private fun State.isGoalPosition() = row == maxRows && column == maxCols - 1 inner class State(val row: Int, val column: Int, val time: Int) { fun nextStates() = listOf( State(row, column + 1, time + 1), State(row, column - 1, time + 1), State(row - 1, column, time + 1), State(row + 1, column, time + 1), State(row, column, time + 1), ) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is State) return false if (row != other.row) return false if (column != other.column) return false if (time.mod(maxRows * maxCols) != other.time.mod(maxRows * maxCols)) return false return true } override fun hashCode(): Int { var result = row result = 31 * result + column result = 31 * result + time.mod(maxRows * maxCols) return result } } }
0
Kotlin
0
0
6b3adb09f10f10baae36284ac19c29896d9993d9
3,381
aoc2022
Apache License 2.0
src/main/kotlin/day04/day04.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package main.day04 import utils.readFile import utils.readLines fun main() { fun convertRange(input: String): IntRange { val values = input.split("-") return values[0].toInt()..values[1].toInt() } fun convertRanges(input: List<String>): List<Pair<Set<Int>, Set<Int>>> = input.map { it.split(",") } .map { Pair(convertRange(it[0]).toSet(), convertRange(it[1]).toSet()) } fun calcContains(ranges: List<Pair<Set<Int>, Set<Int>>>): Int { return ranges.count { it.first.containsAll(it.second) || it.second.containsAll(it.first) } } fun calcOverlap(ranges: List<Pair<Set<Int>, Set<Int>>>): Int { return ranges.count { it.first.intersect(it.second).isNotEmpty() } } val test = """2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8""" fun part1() { val testCount = calcContains(convertRanges(readLines(test))) println("Part 1 Test Count = $testCount") check(testCount == 2) val count = calcContains(convertRanges(readFile("day04"))) println("Part 1 Count = $count") check(count == 524) } fun part2() { val testCount = calcOverlap(convertRanges(readLines(test))) println("Part 2 Test Count = $testCount") check(testCount == 4) val count = calcOverlap(convertRanges(readFile("day04"))) println("Part 2 Count = $count") check(count == 798) } println("Day - 04") part1() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
1,390
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/day14/Day14.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day14 import readInput fun main() { data class Location(val x: Int, val y: Int) class Waterfall(val cond:(Location, Int) -> Boolean) { val state = Array(1000) { IntArray(1000) } var max = 0 fun addLine(f: Location, t: Location) { for (x in minOf(f.x, t.x)..maxOf(f.x, t.x)) { for (y in minOf(f.y, t.y)..maxOf(f.y, t.y)) { state[x][y] = 1 max = maxOf(max, y + 1) } } } fun simulate(): Boolean { var p = Location(500, 0) while(p.y < max) { if (state[p.x][p.y + 1] == 0) { p = Location(p.x, p.y + 1) } else if (state[p.x - 1][p.y + 1] == 0) { p = Location(p.x - 1, p.y + 1) } else if (state[p.x + 1][p.y + 1] == 0) { p = Location(p.x + 1, p.y + 1) } else { break } } state[p.x][p.y] = 2 return cond(p, max) } } fun fill(input: List<String>, wf: Waterfall) { input.forEach { line -> line.split(" -> ") .map { it.split(",") .let { (x, y) -> Location(x.toInt(), y.toInt()) } } .windowed(2) .forEach { (f, t) -> wf.addLine(f, t) } } } fun part1(input: List<String>): Int { val wf = Waterfall { p, max -> p.y == max } fill(input, wf) var counter = 0 while (!wf.simulate()) { counter += 1 } return counter } fun part2(input: List<String>): Int { val wf = Waterfall { p, max -> p == Location(500, 0) } fill(input, wf) var counter = 0 while (!wf.simulate()) { counter += 1 } return counter + 1 } val testInput = readInput("day14", "test") val input = readInput("day14", "input") check(part1(testInput) == 24) println(part1(input)) check(part2(testInput) == 93) println(part2(input)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
2,209
aoc2022
Apache License 2.0
src/year2022/day07/Day07.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2022.day07 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2022", "Day07_test") check(part1(testInput), 95437) check(part2(testInput), 24933642) val input = readInput("2022", "Day07") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { return parseDirectoriesByPath(input).values.filter { it.size <= 100_000 }.sumOf { it.size } } private fun part2(input: List<String>): Int { val directoriesByPath = parseDirectoriesByPath(input) val usedSpace = directoriesByPath[listOf("/")]!!.size val minSizeToDelete = usedSpace - 40_000_000 val sortedBySize = directoriesByPath.values.sortedBy { it.size } val dirToDelete = sortedBySize.first { it.size >= minSizeToDelete } return dirToDelete.size } private fun parseDirectoriesByPath(input: List<String>): Map<List<String>, File> { val path = mutableListOf<String>() return buildMap { for (line in input) { if (line == "$ cd ..") path.removeLast() else if (line.startsWith("$ cd")) path += line.split(' ').last() else if (line == "$ ls") put(path.toList(), File(path.toList())) else { val parent = get(path)!! val (info, name) = line.split(' ') val file = File(path + name, isFile = info != "dir", size = info.toIntOrNull() ?: 0) parent.children += file if (file.isFile) { val pathCopy = path.toMutableList() while (pathCopy.isNotEmpty()) { get(pathCopy)!!.size += file.size pathCopy.removeLast() } } else put(file.path, file) } } } } private data class File( val path: List<String>, val children: MutableList<File> = arrayListOf(), val isFile: Boolean = false, var size: Int = 0 )
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,034
AdventOfCode
Apache License 2.0
src/Day03.kt
halirutan
575,809,118
false
{"Kotlin": 24802}
import kotlin.streams.toList class Rucksack(contents: String) { private val contents1: IntArray private val contents2: IntArray init { assert(contents.isNotEmpty() && contents.length.mod(2) == 0) val chars = contents.chars().toArray() ?: throw Error("Converting string to array failed.") contents1 = chars.copyOfRange(0, chars.size.div(2)) contents2 = chars.copyOfRange(chars.size.div(2), chars.size) } fun findSharedItems(): List<Int> { val result = mutableListOf<Int>() val sorted1 = contents1.sorted() val sorted2 = contents2.sorted() var i = 0 var j = 0 while (i < sorted1.size && j < sorted2.size) { if (sorted1[i] == sorted2[j]) { result.add(sorted1[i]) } if (sorted1[i] < sorted2[j]) { i++ } else { j++ } } return result } } fun Int.toRucksackPriority(): Int { return if (this in 65..90) { this - 65 + 27 } else { this - 97 + 1 } } fun main() { fun part1(input: List<String>): Int { return input.sumOf { Rucksack(it).findSharedItems().toSet().sumOf { item -> item.toRucksackPriority() } } } fun part2(input: List<String>): Int { assert(input.size.mod(3) == 0) var result = 0 var i = 0 while (i < input.size) { val r1 = input[i].chars().toList().toSet() val r2 = input[i+1].chars().toList().toSet() val r3 = input[i+2].chars().toList().toSet() i += 3 val commonItem = r1.intersect(r2).intersect(r3) assert(commonItem.size == 1) result += commonItem.sum().toRucksackPriority() } return result } val testInput = readInput("Day03_test") println("Part 1 test: ${part1(testInput)}") val realInput = readInput("Day03") println("Part 1 real: ${part1(realInput)}") println("Part 2 test: ${part2(testInput)}") println("Part 2 real: ${part2(realInput)}") }
0
Kotlin
0
0
09de80723028f5f113e86351a5461c2634173168
2,119
AoC2022
Apache License 2.0
src/Day09.kt
ZiomaleQ
573,349,910
false
{"Kotlin": 49609}
import java.util.Scanner import kotlin.math.pow import kotlin.math.sqrt fun main() { fun part1(input: List<String>): Int { val tail = Node.Tail(0, 0) val head = Node.Head(0, 0) val positions = mutableListOf<Pair<Int, Int>>() for (line in input) { val move = Scanner(line).let { HeadMove(HeadMoveDirection(it.next()[0]), it.nextInt()) } while (move.value > 0) { head.move(move) tail.catchUp(head.x, head.y).also { positions.add(it) } move.value-- } } positions.add(Pair(tail.x, tail.y)) return positions.toSet().size } fun part2(input: List<String>): Int { val nodes = listOf( Node.Head(0, 0), Node.Tail(0, 0), Node.Tail(0, 0), Node.Tail(0, 0), Node.Tail(0, 0), Node.Tail(0, 0), Node.Tail(0, 0), Node.Tail(0, 0), Node.Tail(0, 0), Node.Tail(0, 0), ) val positions = mutableListOf<Pair<Int, Int>>() for (line in input) { val move = Scanner(line).let { HeadMove(HeadMoveDirection(it.next()[0]), it.nextInt()) } while (move.value > 0) { (nodes[0] as Node.Head).move(move) var lastNode = nodes[0] for (index in nodes.indices) { if(index == 0) continue (nodes[index] as Node.Tail).catchUp(lastNode.x, lastNode.y).let { if (index == 9) positions.add(it) } lastNode = nodes[index] } move.value-- } } positions.add(Pair(nodes[9].x, nodes[9].y)) return positions.toSet().size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") // part1(testInput).also { println(it); check(it == 13) } part2(testInput).also { println(it); check(it == 36) } val input = readInput("Day09") println(part1(input)) println(part2(input)) } data class HeadMove(val direction: HeadMoveDirection, var value: Int) private sealed class Node(var x: Int, var y: Int) { class Tail(x: Int, y: Int) : Node(x, y) { fun catchUp(otherX: Int, otherY: Int): Pair<Int, Int> { val oldCords = Pair(x, y) val distance = sqrt((x - otherX).toDouble().pow(2) + (y - otherY).toDouble().pow(2)) if (x != otherX && y != otherY) { if (distance < 2) return oldCords val nextX = if (x < otherX) x + 1 else x - 1 val nextY = if (y < otherY) y + 1 else y - 1 x = nextX y = nextY return oldCords } return if (x != otherX) { if (distance < 2) return oldCords val nextX = if (x < otherX) x + 1 else x - 1 x = nextX oldCords } else { if (distance < 2) return oldCords val nextY = if (y < otherY) y + 1 else y - 1 y = nextY oldCords } } } class Head(x: Int, y: Int) : Node(x, y) { fun move(move: HeadMove) = when (move.direction) { HeadMoveDirection.LEFT -> x -= 1 HeadMoveDirection.RIGHT -> x += 1 HeadMoveDirection.DOWN -> y -= 1 HeadMoveDirection.UP -> y += 1 } } } enum class HeadMoveDirection { RIGHT, LEFT, UP, DOWN } fun HeadMoveDirection(ch: Char): HeadMoveDirection = when (ch) { 'R' -> HeadMoveDirection.RIGHT 'L' -> HeadMoveDirection.LEFT 'U' -> HeadMoveDirection.UP 'D' -> HeadMoveDirection.DOWN //Will not happen else -> HeadMoveDirection.RIGHT }
0
Kotlin
0
0
b8811a6a9c03e80224e4655013879ac8a90e69b5
3,859
aoc-2022
Apache License 2.0