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/Day11/Solution.kt | cweinberger | 572,873,688 | false | {"Kotlin": 42814} | package Day11
import readInput
object Solution {
data class Monkey(
var startingItems: MutableList<ULong>,
val operation: Char,
val operationValue: String,
val testDivisibleBy: ULong,
val monkeyTrue: Int,
val monkeyFalse: Int,
var activities: ULong = 0UL,
) {
override fun toString(): String {
return """
Starting items: ${startingItems.joinToString(", ")}
Operation: new = $operation
Test: divisible by $testDivisibleBy
If true: throw to monkey $monkeyTrue
If false: throw to monkey $monkeyFalse
""".trimIndent()
}
}
fun parseInput(input: List<String>): List<Monkey> {
val monkeys = mutableListOf<Monkey>()
input.chunked(7).forEach { monkeyInput ->
val startingItems = monkeyInput[1].split(": ").last().split(", ").map { it.toULong() }
val operation = monkeyInput[2].split(" = ").last().split(" ")[1].first()
val operationValue = monkeyInput[2].split(" = ").last().split(" ")[2]
val testDivisibleBy = monkeyInput[3].split(" by ").last().toULong()
val monkeyTrue = monkeyInput[4].split(" monkey ").last().toInt()
val monkeyFalse = monkeyInput[5].split(" monkey ").last().toInt()
monkeys.add(
Monkey(
startingItems = startingItems.toMutableList(),
operation = operation,
operationValue = operationValue,
testDivisibleBy = testDivisibleBy,
monkeyTrue = monkeyTrue,
monkeyFalse = monkeyFalse
)
)
}
return monkeys
}
fun applyOperation(item: ULong, operation: Char, operationValue: String, divideWorryLevelBy: Int?) : ULong {
var newValue = item
val opValue = if (operationValue == "old") item else operationValue.toULong()
when (operation) {
'*' -> newValue = item * opValue
'+' -> newValue = item + opValue
}
return (if(divideWorryLevelBy == null) newValue else (newValue/divideWorryLevelBy.toULong()))
}
fun runRound(monkeys: List<Monkey>, divideWorryLevelBy: Int? = null, superModulo: ULong? = null): List<Monkey> {
monkeys.forEach { monkey ->
monkey.startingItems.forEach { item ->
var worryLevel = applyOperation(item, monkey.operation, monkey.operationValue, divideWorryLevelBy)
superModulo?.let { worryLevel %= it }
if(worryLevel % monkey.testDivisibleBy == 0UL) {
monkeys[monkey.monkeyTrue].startingItems.add(worryLevel)
} else {
monkeys[monkey.monkeyFalse].startingItems.add(worryLevel)
}
}
monkey.activities += monkey.startingItems.count().toULong()
monkey.startingItems = mutableListOf()
}
return monkeys
}
fun part1(input: List<String>) : ULong {
val monkeys = parseInput(input)
repeat(20) {
runRound(monkeys, 3)
}
monkeys.forEach { println(""); println(it) }
return monkeys
.sortedByDescending { it.activities }
.take(2)
.let { it.first().activities * it.last().activities }
}
fun part2(input: List<String>) : ULong {
val monkeys = parseInput(input)
repeat(10000) {
// congruence https://en.wikipedia.org/wiki/Modular_arithmetic
val superModulo = monkeys
.map { it.testDivisibleBy }
.reduce{ acc, elem -> acc * elem }
runRound(monkeys, null, superModulo)
}
monkeys.forEach { println(it.activities) }
return monkeys
.sortedByDescending { it.activities }
.take(2)
.let { it.first().activities * it.last().activities }
}
}
fun main() {
val testInput = readInput("Day11/TestInput")
val input = readInput("Day11/Input")
println("\n=== Part 1 - Test Input ===")
println(Solution.part1(testInput))
println("\n=== Part 1 - Final Input ===")
println(Solution.part1(input))
println("\n=== Part 2 - Test Input ===")
println(Solution.part2(testInput))
println("\n=== Part 2 - Final Input ===")
println(Solution.part2(input))
}
| 0 | Kotlin | 0 | 0 | 883785d661d4886d8c9e43b7706e6a70935fb4f1 | 4,487 | aoc-2022 | Apache License 2.0 |
src/year2023/day15/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2023.day15
import arrow.core.nonEmptyListOf
import utils.ProblemPart
import utils.readInputs
import utils.runAlgorithm
fun main() {
val (realInput, testInputs) = readInputs(2023, 15, transform = List<String>::first)
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(1320),
algorithm = ::part1,
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(145),
algorithm = ::part2,
),
)
}
private fun part1(input: String) = input.splitToSequence(',').sumOf(::computeHash)
private fun computeHash(step: String): Long {
return step.asSequence()
.map { it.code }
.fold(0L) { hash, value -> (hash + value) * 17 % 256 }
}
private fun part2(input: String): Long {
return input.splitToSequence(',')
.mapNotNull(operationRegex::matchEntire)
.buildBoxes()
.asSequence()
.map { box ->
box.asSequence()
.mapIndexed { index, lens -> (index + 1) * lens.value }
.sum()
}
.withIndex()
.sumOf { (index, boxValue) -> (index + 1) * boxValue }
}
private fun Sequence<MatchResult>.buildBoxes(): List<Map<String, Long>> {
return fold(List(256) { mutableMapOf<String, Long>() }) { boxes, operation ->
val lensId = operation.groupValues[1]
val targetBox = computeHash(lensId).toInt()
if (operation.groupValues[2] == "-") boxes[targetBox].remove(lensId)
else boxes[targetBox][lensId] = operation.groupValues[3].toLong()
boxes
}
}
private val operationRegex = "([a-z]+)(?:(-)|=(\\d+))".toRegex()
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 1,751 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-18.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.Coord3D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import com.github.ferinagy.adventOfCode.searchGraph
import com.github.ferinagy.adventOfCode.singleStep
import kotlin.math.max
import kotlin.math.min
fun main() {
val input = readInputLines(2022, "18-input")
val testInput1 = readInputLines(2022, "18-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 droplets = input.map {
val (a, b, c) = it.split(',')
Coord3D(a.toInt(), b.toInt(), c.toInt())
}
return droplets.sumOf {
it.neighbors().count { it !in droplets }
}
}
private fun part2(input: List<String>): Int {
val droplets = input.map {
val (a, b, c) = it.split(',')
Coord3D(a.toInt(), b.toInt(), c.toInt())
}.toSet()
var (minX, minY, minZ) = droplets.first()
var (maxX, maxY, maxZ) = droplets.first()
droplets.forEach {
minX = min(minX, it.x - 1)
minY = min(minY, it.y - 1)
minZ = min(minZ, it.z - 1)
maxX = max(maxX, it.x + 1)
maxY = max(maxY, it.y + 1)
maxZ = max(maxZ, it.z + 1)
}
val pockets = mutableSetOf<Coord3D>()
fun Coord3D.inPocket() = searchGraph(
start = this,
isDone = { it.x == minX || it.x == maxX || it.y == minY || it.y == maxY || it.z == minZ || it.z == maxZ },
nextSteps = {
if (it in pockets) emptySet() else (it.neighbors().toSet() - droplets).singleStep()
}
) == -1
return droplets.sumOf { drop ->
drop.neighbors().count {
if (it in droplets) {
false
} else if (it.inPocket()) {
pockets += it
false
} else true
}
}
}
private fun Coord3D.neighbors() = listOf(
copy(x = x + 1),
copy(x = x - 1),
copy(y = y + 1),
copy(y = y - 1),
copy(z = z + 1),
copy(z = z - 1),
)
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,210 | advent-of-code | MIT License |
src/Day05.kt | Jaavv | 571,865,629 | false | {"Kotlin": 14896} | // https://adventofcode.com/2022/day/5
fun main() {
val testInput = readInput("Day05_test")
val input = readInput("Day05")
val parse = input.map { it.split("\n") }.flatten()
val emptySpaceIndex = parse.indexOfFirst { it.isBlank() }
val padding = parse[emptySpaceIndex - 1].length + 1
val crates = parse.slice(0 until emptySpaceIndex - 1)
val paddedCrates = crates.map { it.padEnd(padding, ' ').chunked(4) }.reversed()
val parsedCrates = parseCrates(paddedCrates)
val moves = parse.slice(emptySpaceIndex + 1 until parse.size)
val initialStackPart1 = List(parsedCrates.size) { index -> index + 1 to parsedCrates[index] }.toMap()
val initialStackPart2 = initialStackPart1.map { it.key to it.value.toMutableList() }.toMap() // deepcopy
day05Part1(moves, initialStackPart1)
val finalStackPart1 = initialStackPart1.values.joinToString("") { it.last() }
println(finalStackPart1) //LJSVLTWQM
day05Part2(moves, initialStackPart2)
val finalStackPart2 = initialStackPart2.values.joinToString("") { it.last() }
println(finalStackPart2) //BRQWDBBJM
}
fun parseCrates(input: List<List<String>>): List<MutableList<String>> {
val crates = List(input[0].size) { mutableListOf<String>() }
for (i in input[0].indices) {
for (value in input) {
if (value[i].isNotBlank()) crates[i].add(value[i].filter { it.isLetter() })
}
}
return crates
}
fun moveCrate(instruction: Instruction, crates: Map<Int, MutableList<String>>) {
repeat(instruction.move) {
val topCrate = crates[instruction.from]?.last()
crates[instruction.from]?.removeLast()
if (topCrate != null) {
crates[instruction.to]?.add(topCrate)
}
}
}
fun moveCrates(instruction: Instruction, crates: Map<Int, MutableList<String>>) {
val topCrates = crates[instruction.from]?.takeLast(instruction.move)
repeat(instruction.move) {
crates[instruction.from]?.removeLast()
}
if (topCrates != null) {
crates[instruction.to]?.addAll(topCrates)
}
}
data class Instruction(val move: Int, val from: Int, val to: Int)
fun instructionParser(input: String): Instruction {
val parse = input.split(" ").chunked(2).associate { it.first() to it.last().toInt() }
return Instruction(move = parse["move"]!!, from = parse["from"]!!, to = parse["to"]!!)
}
fun day05Part1(input: List<String>, crates: Map<Int, MutableList<String>>) {
input.map { move ->
val instruction = instructionParser(move)
moveCrate(instruction, crates)
}
}
fun day05Part2(input: List<String>, crates: Map<Int, MutableList<String>>) {
input.map { move ->
val instruction = instructionParser(move)
moveCrates(instruction, crates)
}
}
| 0 | Kotlin | 0 | 0 | 5ef23a16d13218cb1169e969f1633f548fdf5b3b | 2,781 | advent-of-code-2022 | Apache License 2.0 |
src/day05/Day05.kt | tiginamaria | 573,173,440 | false | {"Kotlin": 7901} | package day05
import readInput
import java.lang.Integer.min
import java.util.Stack
data class Move(val count: Int, val from: Int, val to: Int)
fun main() {
fun parseStacks(stacksInput: List<String>, stacksNums: String): List<Stack<Char>> {
val positions = (1..stacksNums.length step 4)
val stacks = positions.map { Stack<Char>() }.toList()
stacksInput.reversed().forEach { level ->
positions.forEachIndexed { i, p ->
if (p < level.length && level[p].isLetter()) {
stacks[i].add(level[p])
}
}
}
return stacks
}
fun parseMoves(moveInput: List<String>): List<Move> {
val moveRegex = Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)")
return moveInput.map {
val (count, from, to) = moveRegex.findAll(it).first().groupValues.drop(1).map { it.toInt() }
Move(count, from - 1, to - 1)
}
}
fun applyMoves(stacks: List<Stack<Char>>, moves: List<Move>) {
moves.forEach { move ->
(1..min(move.count, stacks[move.from].size)).forEach {
stacks[move.to].push(stacks[move.from].pop())
}
}
}
fun applyMultiMoves(stacks: List<Stack<Char>>, moves: List<Move>) {
moves.forEach { move ->
(1..min(move.count, stacks[move.from].size)).map {
stacks[move.from].pop()
}.reversed().forEach { stacks[move.to].push(it) }
}
}
fun part1(input: List<String>): String {
val stacksInput = input.takeWhile { !it.startsWith(" 1") }
val stacksNums = input.findLast { it.startsWith(" 1") }!!
val stacksMoves = input.takeLastWhile { it.startsWith('m') }
val stacks = parseStacks(stacksInput, stacksNums)
val moves = parseMoves(stacksMoves)
applyMoves(stacks, moves)
return stacks.map { it.peek() }.joinToString("")
}
fun part2(input: List<String>): String {
val stacksInput = input.takeWhile { !it.startsWith(" 1") }
val stacksNums = input.findLast { it.startsWith(" 1") }!!
val stacksMoves = input.takeLastWhile { it.startsWith('m') }
val stacks = parseStacks(stacksInput, stacksNums)
val moves = parseMoves(stacksMoves)
applyMultiMoves(stacks, moves)
return stacks.map { it.peek() }.joinToString("")
}
val input = readInput("Day05", 5)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bf81cc9fbe11dce4cefcb80284e3b19c4be9640e | 2,511 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/ab/advent/day03/Models.kt | battagliandrea | 574,137,910 | false | {"Kotlin": 27923} | package com.ab.advent.day03
data class Group(val rucksacks: List<Rucksack>){
val priority: Int = rucksacks.sumOf { it.commonItem.value.toPriority() }
}
data class ChankedGroup(val chunks: List<List<Rucksack>>){
val priority: Int = chunks
.map { c -> c.map { it.id } }
.map {(sack1, sack12, sack13) -> sack1.first{ it in sack12 && it in sack13}}
.sumOf { it.toPriority() }
}
class Rucksack(
val id :String,
val compartment1: List<Item>,
val compartment2: List<Item>
) {
val commonItem = compartment1.first{ it in compartment2}
}
data class Item(
val value: Char
)
fun Char.toPriority(): Int = if(this.isLowerCase()) this - 'a' + 1 else this - 'A' + 27
fun String.toItem(): List<Item> =
this.map { value -> Item(value = value) }
fun List<String>.toGroup() = this.toRucksacks().let(::Group)
fun List<String>.toChunkedGroup() = this.toRucksacks().chunked(3)
.let(::ChankedGroup)
private fun List<String>.toRucksacks() =
this.map { it.chunked(it.length / 2) }
.map {(compartment1, compartment2) -> Rucksack(compartment1 + compartment2, compartment1.toItem(), compartment2.toItem()) }
| 0 | Kotlin | 0 | 0 | cb66735eea19a5f37dcd4a31ae64f5b450975005 | 1,164 | Advent-of-Kotlin | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2023/Day07.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2023
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
import ru.timakden.aoc.year2023.Day07.HandType.*
/**
* [Day 7: Camel Cards](https://adventofcode.com/2023/day/7).
*/
object Day07 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2023/Day07")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
return input.map { s ->
val (hand, bid) = s.split(" ")
HandP1(hand) to bid.toInt()
}.sortedWith { h1, h2 ->
h1.first.compareTo(h2.first)
}.mapIndexed { index, (_, bid) ->
bid * (index + 1)
}.sum()
}
fun part2(input: List<String>): Int {
return input.map { s ->
val (hand, bid) = s.split(" ")
HandP2(hand) to bid.toInt()
}.sortedWith { h1, h2 ->
h1.first.compareTo(h2.first)
}.mapIndexed { index, (_, bid) ->
bid * (index + 1)
}.sum()
}
private data class HandP1(val hand: String) : Comparable<HandP1> {
private val type: HandType
get() {
val labels = hand.groupingBy { it }.eachCount()
return when (labels.size) {
1 -> FIVE_OF_A_KIND
2 -> if (labels.values.any { it == 4 }) FOUR_OF_A_KIND else FULL_HOUSE
3 -> if (labels.values.any { it == 3 }) THREE_OF_A_KIND else TWO_PAIR
4 -> ONE_PAIR
else -> HIGH_CARD
}
}
override fun compareTo(other: HandP1): Int {
if (type.ordinal == other.type.ordinal) {
for (i in 0..hand.lastIndex) {
val thisLabel = hand[i]
val otherLabel = other.hand[i]
val compareResult = labelComparator.compare(thisLabel, otherLabel)
if (compareResult != 0) return compareResult
}
} else return type.ordinal.compareTo(other.type.ordinal)
return 0
}
companion object {
private val labelComparator = Comparator { c1: Char, c2: Char ->
val labelToStrength = mapOf(
'2' to 0,
'3' to 1,
'4' to 2,
'5' to 3,
'6' to 4,
'7' to 5,
'8' to 6,
'9' to 7,
'T' to 8,
'J' to 9,
'Q' to 10,
'K' to 11,
'A' to 12,
)
checkNotNull(labelToStrength[c1]) - checkNotNull(labelToStrength[c2])
}
}
}
private data class HandP2(val hand: String) : Comparable<HandP2> {
private val type: HandType
get() {
val labels = hand.groupingBy { it }.eachCount()
val jokers = labels.filterKeys { it == 'J' }.values.singleOrNull() ?: 0
val others = labels.filterKeys { it != 'J' }
.toSortedMap(labelComparator.reversed())
.toMutableMap()
others.maxByOrNull { it.value }?.key?.let {
others[it] = jokers + checkNotNull(others[it])
}
if (jokers == 5) return FIVE_OF_A_KIND
return when (others.size) {
1 -> FIVE_OF_A_KIND
2 -> if (others.values.any { it == 4 }) FOUR_OF_A_KIND else FULL_HOUSE
3 -> if (others.values.any { it == 3 }) THREE_OF_A_KIND else TWO_PAIR
4 -> ONE_PAIR
else -> HIGH_CARD
}
}
override fun compareTo(other: HandP2): Int {
if (type.ordinal == other.type.ordinal) {
for (i in 0..hand.lastIndex) {
val thisLabel = hand[i]
val otherLabel = other.hand[i]
val compareResult = labelComparator.compare(thisLabel, otherLabel)
if (compareResult != 0) return compareResult
}
} else return type.ordinal.compareTo(other.type.ordinal)
return 0
}
companion object {
private val labelComparator = Comparator { c1: Char, c2: Char ->
val labelToStrength = mapOf(
'J' to 0,
'2' to 1,
'3' to 2,
'4' to 3,
'5' to 4,
'6' to 5,
'7' to 6,
'8' to 7,
'9' to 8,
'T' to 9,
'Q' to 10,
'K' to 11,
'A' to 12,
)
checkNotNull(labelToStrength[c1]) - checkNotNull(labelToStrength[c2])
}
}
}
enum class HandType {
HIGH_CARD, // 23456, [1, 1, 1, 1, 1]
ONE_PAIR, // A23A4, [2, 1, 1, 1]
TWO_PAIR, // 23432, [2, 2, 1]
THREE_OF_A_KIND, // TTT98, [3, 1, 1]
FULL_HOUSE, // 23332, [3, 2]
FOUR_OF_A_KIND, // AA8AA, [4, 1]
FIVE_OF_A_KIND // AAAAA, [5]
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 5,416 | advent-of-code | MIT License |
src/day02/Day02.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day02
import readInput
enum class RPS(val points: Int) {
Rock(1),
Paper(2),
Scissors(3)
}
enum class RoundResult(val points: Int) {
Loose(0),
Draw(3),
Win(6)
}
data class TournamentPair(val opponentChoice: RPS, val roundResult: RoundResult)
val inputLineRegex = """([ABC]) ([XYZ])""".toRegex()
fun parseInput(inputLines: List<String>): Iterable<TournamentPair> {
val pairs = mutableListOf<TournamentPair>()
for (line in inputLines) {
val (opponentChoiceLetter, roundResultLetter) =
inputLineRegex.matchEntire(line)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $line")
val opponentChoice = when (opponentChoiceLetter) {
"A" -> RPS.Rock
"B" -> RPS.Paper
"C" -> RPS.Scissors
else -> throw IllegalArgumentException("Incorrect opponent choice $opponentChoiceLetter")
}
val roundResult = when (roundResultLetter) {
"X" -> RoundResult.Loose
"Y" -> RoundResult.Draw
"Z" -> RoundResult.Win
else -> throw IllegalArgumentException("Incorrect my choice $roundResultLetter")
}
pairs.add(TournamentPair(opponentChoice, roundResult))
}
return pairs
}
fun main() {
fun calculateScore(pair: TournamentPair): Int {
return when (pair.roundResult) {
RoundResult.Loose -> 0 + when (pair.opponentChoice) {
RPS.Rock -> RPS.Scissors.points
RPS.Paper -> RPS.Rock.points
RPS.Scissors -> RPS.Paper.points
}
RoundResult.Draw -> 3 + pair.opponentChoice.points
RoundResult.Win -> 6 + when (pair.opponentChoice) {
RPS.Rock -> RPS.Paper.points
RPS.Paper -> RPS.Scissors.points
RPS.Scissors -> RPS.Rock.points
}
}
}
// fun part1(input: List<String>): Int {
// val pairs = parseInput(input)
// return pairs.sumOf { calculateScore(it) }
// }
fun part2(input: List<String>): Int {
val pairs = parseInput(input)
return pairs.sumOf { calculateScore(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("sample_data", 2)
//check(part1(testInput) == 15)
val input = readInput("main_data", 2)
//println(part1(input))
check(part2(testInput) == 12)
println(part2(testInput))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 2,542 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | marciprete | 574,547,125 | false | {"Kotlin": 13734} | fun main() {
fun getColumn(matrix: Array<IntArray>, col: Int): IntArray {
val nums = IntArray(matrix.size)
for (i in nums.indices) {
nums[i] = matrix[i][col]
}
return nums
}
fun getMatrix(input: List<String>): Array<IntArray> {
val matrix = Array(input.get(0).length) { IntArray(input.get(0).length) }
input.forEachIndexed { row, line ->
line.forEachIndexed { col, num ->
matrix[row][col] = num.digitToInt()
}
}
return matrix
}
fun part1(input: List<String>): Int {
val matrix = getMatrix(input)
var sum = matrix.size + 2 * (matrix.size - 1)
for (x in 1..matrix.size - 2) {
var left = -1
for (y in 0..matrix[0].size - 2) {
val current = matrix[x][y]
val top = getColumn(matrix, y).take(x).max()
val right = matrix[x].takeLast(matrix.size - y - 1).max()
val bottom = getColumn(matrix, y).takeLast(matrix.size - 1 - x).max()
if (current > top || current > left || current > right || current > bottom) {
left = maxOf(left, current)
sum++
}
}
}
return sum
}
fun sight(array: List<Int>, top: Int): Int {
var count = 0
for (n in array) {
if (top > n) {
count++
} else if (top == n) {
count++
break
} else {
break
}
}
return count
}
fun part2(input: List<String>): Int {
val results = mutableListOf<Int>()
val matrix = getMatrix(input)
for (x in 1..matrix.size - 2) {
for (y in 1..matrix[0].size - 2) {
val top = getColumn(matrix, y).take(x)
val current = matrix[x][y]
val left = matrix[x].take(y)
val right = matrix[x].takeLast(matrix.size - (y + 1))
val bottom = getColumn(matrix, y).takeLast(matrix.size - (x + 1))
results.add(
sight(top.asReversed(), current) *
sight(left.asReversed(), current) *
sight(right, current) *
sight(bottom, current)
)
}
}
return results.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 4)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6345abc8f2c90d9bd1f5f82072af678e3f80e486 | 2,735 | Kotlin-AoC-2022 | Apache License 2.0 |
src/Day04.kt | hrach | 572,585,537 | false | {"Kotlin": 32838} | fun main() {
fun part1(input: List<String>): Int {
return input
.filter { it.isNotBlank() }
.map {
val (a, b) = it.split(",")
val (aa, ab) = a.split("-").map { it.toInt() }
val (ba, bb) = b.split("-").map { it.toInt() }
IntRange(aa, ab) to IntRange(ba, bb)
}
.count { (a, b) ->
(a.first in b && a.last in b) ||
(b.first in a && b.last in a)
}
}
fun part2(input: List<String>): Int {
return input
.filter { it.isNotBlank() }
.map {
val (a, b) = it.split(",")
val (aa, ab) = a.split("-").map { it.toInt() }
val (ba, bb) = b.split("-").map { it.toInt() }
IntRange(aa, ab) to IntRange(ba, bb)
}
.count { (a, b) ->
(a.first in b || a.last in b) ||
(b.first in a || b.last in a)
}
}
val testInput = readInput("Day04_test")
check(part1(testInput), 2)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 40b341a527060c23ff44ebfe9a7e5443f76eadf3 | 917 | aoc-2022 | Apache License 2.0 |
src/Day18.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | import java.util.*
private data class Region3D(val mn: Point3D, val mx: Point3D) {
fun contains(point: Point3D): Boolean {
val (x1, y1, z1) = mn
val (x2, y2, z2) = mx
val (x, y, z) = point
return (x1..x2).contains(x)
&& (y1..y2).contains(y)
&& (z1..z2).contains(z)
}
/** returns sequence of points inside this region */
fun points() = sequence {
val (x1, y1, z1) = mn
val (x2, y2, z2) = mx
(x1..x2).forEach { x ->
(y1..y2).forEach { y ->
(z1..z2).forEach { z ->
yield(Point3D(x, y, z))
}
}
}
}
}
data class Point3D(val x: Int, val y: Int, val z: Int) {
fun adjacentPoints(): List<Point3D> {
val tmp = listOf(-1, 1)
return tmp.flatMap {
listOf(
Point3D(x + it, y, z),
Point3D(x, y + it, z),
Point3D(x, y, z + it),
)
}
}
}
private fun Point3D.regionTo(o: Point3D) = Region3D(this, o)
private fun parseCube(input: String): Point3D {
val (x, y, z) = input.split(",").map { it.toInt() }
return Point3D(x, y, z)
}
/** return "bounding box" of the cubes, extending one unit in each direction */
private fun bbox(cubes: List<Point3D>): Pair<Point3D, Point3D> {
return Point3D(
x = cubes.minOf { it.x } - 1,
y = cubes.minOf { it.y } - 1,
z = cubes.minOf { it.z } - 1,
) to Point3D(
x = cubes.maxOf { it.x } + 1,
y = cubes.maxOf { it.y } + 1,
z = cubes.maxOf { it.z } + 1,
)
}
/** returns surface area of structure consisting of specified cubes */
private fun surfaceArea(cubes: List<Point3D>): Int {
val processed = mutableSetOf<Point3D>()
var surface = 0
cubes.forEach {
surface += 6
// subtract touching surfaces
surface -= it.adjacentPoints().count { adj -> adj in processed } * 2
processed.add(it)
}
return surface
}
/** find hollow space inside the list of cubes, return list of cube needed to fill such hollow */
private fun findHollow(cubes: List<Point3D>): List<Point3D> {
val (mn, mx) = bbox(cubes)
val areaLimit = mn.regionTo(mx)
// bfs to find all reachable nodes
val existing = cubes.toMutableSet()
val q: Queue<Point3D> = LinkedList()
q.add(mn)
while (!q.isEmpty()) {
val cur = q.remove()
cur.adjacentPoints()
.filter { areaLimit.contains(it) }
.filter { it !in existing }
.forEach { q.add(it); existing.add(it) }
}
return areaLimit.points().filter { it !in existing }.toList()
}
fun main() {
fun part1(input: List<String>) = surfaceArea(input.map(::parseCube))
fun part2(input: List<String>) = input.map(::parseCube).let {
surfaceArea(it) - surfaceArea(findHollow(it))
}
val testInput = readInput("Day18_test")
println(part1(testInput))
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18")
println("Part 1")
println(part1(input))
println("Part 2")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 3,191 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/year2021/Day13.kt | drademacher | 725,945,859 | false | {"Kotlin": 76037} | package year2021
import Point
import readFile
fun main() {
val input = parseInput(readFile("2021", "day13"))
val testInput = parseInput(readFile("2021", "day13_test"))
check(part1(testInput) == 17)
println("Part 1:" + part1(input))
println("Part 2:")
val (width, height) = part2(input)
input.paper.print(width, height)
}
private fun parseInput(readText: String): Day13Input {
val (rawPoints, rawFolds) = readText.split("\n\n")
val points =
rawPoints
.split("\n")
.filter { it != "" }
.map { it.split(",").map { it.toInt() } }
.map { Point(it[0], it[1]) }
val foldInstructions =
rawFolds
.split("\n")
.filter { it != "" }
.map { it.split(" ").last().split("=") }
.map { FoldInstruction(Axis.valueOf(it[0].uppercase()), it[1].toInt()) }
return Day13Input(Paper.fromPoints(points), foldInstructions)
}
private fun part1(input: Day13Input): Int {
input.paper.fold(input.foldInstructions.first())
return input.paper.dots()
}
private fun part2(input: Day13Input): Pair<Int, Int> {
input.foldInstructions.forEach { foldInstruction -> input.paper.fold(foldInstruction) }
val width = input.foldInstructions.filter { it.axis == Axis.X }.minOf { it.at }
val height = input.foldInstructions.filter { it.axis == Axis.Y }.minOf { it.at }
return Pair(width, height)
}
data class Day13Input(val paper: Paper, val foldInstructions: List<FoldInstruction>)
data class FoldInstruction(val axis: Axis, val at: Int)
enum class Axis { X, Y }
data class Paper(val dots: Array<Array<Boolean>>) {
fun fold(foldInstruction: FoldInstruction) {
when (foldInstruction.axis) {
Axis.X -> foldVertically(foldInstruction.at)
Axis.Y -> foldHorizontally(foldInstruction.at)
}
}
private fun foldHorizontally(at: Int) {
for (y in 0..at) {
for (x in dots[0].indices) {
dots[y][x] = dots[y][x] || dots[at + at - y][x]
}
}
for (y in at + 1 until dots.size) {
for (x in dots[y].indices) {
dots[y][x] = false
}
}
}
private fun foldVertically(at: Int) {
for (y in dots.indices) {
for (x in 0..at) {
dots[y][x] = dots[y][x] || dots[y][at + at - x]
}
}
for (y in dots.indices) {
for (x in at + 1 until dots[y].size) {
dots[y][x] = false
}
}
}
fun dots(): Int = dots.sumOf { it.count { it } }
fun print(
x: Int = dots[0].size,
y: Int = dots.size,
) {
dots
.take(y)
.map { it.take(x).map { if (it) "█" else " " }.joinToString("") }
.forEach(::println)
}
companion object {
fun fromPoints(points: List<Point>): Paper {
val maxY = points.maxOf { it.y } + 1
val maxX = points.maxOf { it.x } + 1
val paper = Paper(Array(maxY) { Array(maxX) { false } })
points.forEach { paper.dots[it.y][it.x] = true }
return paper
}
}
}
| 0 | Kotlin | 0 | 0 | 4c4cbf677d97cfe96264b922af6ae332b9044ba8 | 3,221 | advent_of_code | MIT License |
src/Day09.kt | Fedannie | 572,872,414 | false | {"Kotlin": 64631} | import kotlin.math.abs
import kotlin.math.sign
const val FIELD_SIZE = 610
fun main() {
fun parseInput(input: List<String>): List<Pair<Int, Int>> {
return input.map {
val (direction, stepsStr) = it.split(' ')
val steps = stepsStr.toInt()
when (direction) {
"D" -> steps to 0
"U" -> -steps to 0
"L" -> 0 to -steps
"R" -> 0 to steps
else -> 0 to 0
}
}
}
class Field(size: Int, length: Int) {
private val field = Array(size) { BooleanArray(size) { false } }
val rope = Array(length) { size / 2 to size / 2 }
val visited: Int
get() {
return this.field.sumOf { it.count { it }}
}
fun dist(pointA: Pair<Int, Int>, pointB: Pair<Int, Int>): Int {
return abs(pointA.first - pointB.first).coerceAtLeast(abs(pointA.second - pointB.second))
}
fun performAction(dy: Int, dx: Int) {
for (y in 1 .. abs(dy).coerceAtLeast(abs(dx))) {
rope[0] = rope[0].first + dy.sign to rope[0].second + dx.sign
for (i in 1 until rope.size) {
if (dist(rope[i], rope[i - 1]) > 1) {
rope[i] = rope[i].first + (rope[i - 1].first - rope[i].first).sign to rope[i].second + (rope[i - 1].second - rope[i].second).sign
}
}
field[rope.last().first][rope.last().second] = true
}
}
}
fun run(input: List<String>, ropeLength: Int): Int {
val directions = parseInput(input)
val field = Field(FIELD_SIZE, ropeLength)
directions.forEach { field.performAction(it.first, it.second) }
return field.visited
}
fun part1(input: List<String>): Int = run(input, 2)
fun part2(input: List<String>): Int = run(input, 10)
val testInput = readInputLines("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInputLines(9)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f | 1,898 | Advent-of-Code-2022-in-Kotlin | Apache License 2.0 |
src/day09/Day09.kt | pientaa | 572,927,825 | false | {"Kotlin": 19922} | package day09
import day09.Direction.DOWN
import day09.Direction.LEFT
import day09.Direction.RIGHT
import day09.Direction.UP
import readLines
import kotlin.math.abs
fun main() {
fun applyMoves(input: List<String>, knots: List<Knot>) {
input.map { line ->
val (direction, steps) = line.split(" ")
repeat(steps.toInt()) {
knots.onEach { knot ->
knot.move(Direction(direction))
}
}
}
}
fun part1(input: List<String>): Int {
val head = Knot(id = 0)
val tail = Knot(id = 1, following = head)
applyMoves(input, listOf(head, tail))
return tail.visited.size
}
fun part2(input: List<String>): Int {
val knots = (1..9)
.fold(mutableListOf(Knot(id = 0))) { acc: MutableList<Knot>, index: Int ->
acc.add(Knot(index, acc.last()))
acc
}
applyMoves(input, knots)
return knots.last().visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("day09/Day09_test")
val input = readLines("day09/Day09")
println(part1(input))
println(part2(input))
}
private infix fun Pair<Int, Int>.isExactlyFarInOneAxis(distance: Int): Boolean =
(first == 0 && abs(second) == distance) || (abs(first) == distance && second == 0)
data class Knot(
val id: Int,
val following: Knot? = null,
val position: Position = Position(0, 0),
val visited: MutableSet<Position> = mutableSetOf()
) {
init {
visited.add(position.copy())
}
fun move(direction: Direction) {
when (following) {
null -> position.move(direction)
else -> {
val distance = position distanceTo following.position
val directions = distance.getDirections()
if (distance isFurtherThanMoves 2 || distance isExactlyFarInOneAxis 2)
directions.forEach { position.move(it) }
}
}
visited.add(position.copy())
}
}
private fun Pair<Int, Int>.getDirections() = listOfNotNull(first.getDirection(Axis.X), second.getDirection(Axis.Y))
private infix fun Pair<Int, Int>.isFurtherThanMoves(overallDistance: Int): Boolean =
(abs(first) + abs(second)) > overallDistance
private fun Int.getDirection(axis: Axis): Direction? =
when {
this > 0 && axis == Axis.X -> RIGHT
this < 0 && axis == Axis.X -> LEFT
this > 0 && axis == Axis.Y -> UP
this < 0 && axis == Axis.Y -> DOWN
else -> null
}
data class Position(var x: Int = 0, var y: Int = 0) {
fun move(direction: Direction): Position {
when (direction) {
RIGHT -> x += 1
LEFT -> x -= 1
UP -> y += 1
DOWN -> y -= 1
}
return this
}
infix fun distanceTo(position: Position): Pair<Int, Int> {
return Pair(position.x - x, position.y - y)
}
}
enum class Axis {
X,
Y
}
enum class Direction {
RIGHT,
LEFT,
UP,
DOWN;
companion object {
operator fun invoke(from: String) = when (from) {
"R" -> RIGHT
"L" -> LEFT
"U" -> UP
"D" -> DOWN
else -> throw Exception()
}
}
}
| 0 | Kotlin | 0 | 0 | 63094d8d1887d33b78e2dd73f917d46ca1cbaf9c | 3,371 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day09.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2021
import se.saidaspen.aoc.util.*
fun main() = Day09.run()
object Day09 : Day(2021, 9) {
override fun part1() : Any {
val map = toMap(input)
val lowpoints = map.keys.filter { p -> (p.neighborsSimple().mapNotNull { map[it] }.all { it.toString().toInt() > map[p].toString().toInt() })}
return lowpoints.sumOf {map[it].toString().toInt() + 1 }
}
override fun part2() : Any {
val map = toMap(input)
val flowsMap = map.keys.map { P(it, flowsTo2(it, map)) }.filter { it.second != null }.toMap()
val toLowPoints = flowsMap.keys.map { findLp(it, flowsMap) }
val basins = toLowPoints.groupBy { it.second }
val topThree = basins.entries.map { it.value.size }.sortedByDescending { it }.take(3)
return topThree[0] * topThree[1] * topThree[2]
}
private fun findLp(it: P<Int, Int>, flowsMap: Map<P<Int, Int>, Pair<Int, Int>?>): P<P<Int, Int>, P<Int, Int>> {
var p = it
while (flowsMap.containsKey(p)) {
val n = flowsMap[p]!!
if (p == n) {
return P(it, p)
}
p = n
}
return P(it, p)
}
private fun flowsTo2(p: Pair<Int, Int>, map: MutableMap<Pair<Int, Int>, Char>): Pair<Int, Int>? {
if (map[p].toString().toInt() == 9) {
return null
}
val lowestN = p.neighborsSimple()
.filter { map[it] != null }
.filter { it.first >= 0 && it.second >= 0 }
.filter { map[it].toString().toInt() != 9 }
.minByOrNull { map[it].toString().toInt() }
return if (map[lowestN].toString().toInt() < map[p].toString().toInt()) lowestN else p
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,737 | adventofkotlin | MIT License |
src/day11/Day11.kt | ivanovmeya | 573,150,306 | false | {"Kotlin": 43768} | package day11
import readInput
fun main() {
data class Test(val testDivider: Long, val predicate: (Long) -> Boolean, val trueMonkey: Int, val falseMonkey: Int)
data class Monkey(
val worries: ArrayDeque<Long>,
val operation: (Long) -> Long,
val test: Test,
var inspections: Int = 0
) {
override fun toString(): String {
return "items=${worries.joinToString(",")}, inspectionTimes = $inspections"
}
}
fun String.contentPart() = substring(indexOfFirst { it == ':' } + 1)
fun String.toWorries(): List<Long> {
return contentPart().split(',').map { it.trim().toLong() }
}
fun String.toOperation(): (Long) -> Long {
val operationRaw = contentPart()
val mathOperationRaw = operationRaw[operationRaw.indexOf("old") + 4]
val rightOperandRaw = operationRaw.split(' ').last()
val operation: (Long) -> Long = { old ->
val rightOperand = if (rightOperandRaw.last().isDigit()) {
rightOperandRaw.trim().toLong()
} else {
old
}
when (mathOperationRaw) {
'*' -> old * rightOperand
'+' -> old + rightOperand
else -> old + rightOperand
}
}
return operation
}
fun parseMonkeys(input: List<String>): Array<Monkey> {
val monkeysRaw = input.chunked(7)
return monkeysRaw.map { monkeyRaw ->
val worries = monkeyRaw[1].toWorries()
val operation = monkeyRaw[2].toOperation()
val testOperand = monkeyRaw[3].contentPart().substringAfter("by ").toLong()
val trueMonkey = monkeyRaw[4].contentPart().substringAfter("monkey ").toInt()
val falseMonkey = monkeyRaw[5].contentPart().substringAfter("monkey ").toInt()
Monkey(
worries = ArrayDeque(worries),
operation = operation,
test = Test(
testDivider = testOperand,
predicate = { it % testOperand == 0L },
trueMonkey = trueMonkey,
falseMonkey = falseMonkey
),
)
}.toTypedArray()
}
fun topTwoMonkeysBusinessMultiplied(monkeys: Array<Monkey>, rounds: Int, worryReliefMultiplier: Int = 1): Long {
val lcm = monkeys
.map { it.test.testDivider }
.fold(1) { acc: Long, divider: Long -> acc * divider }
repeat(rounds) {
monkeys.forEach { monkey ->
while (monkey.worries.isNotEmpty()) {
val worry = monkey.worries.removeFirst()
monkey.inspections++
val newWorry = (monkey.operation(worry) / worryReliefMultiplier.toLong()) % lcm
val monkeyToThrowIndex = if (monkey.test.predicate(newWorry)) {
monkey.test.trueMonkey
} else {
monkey.test.falseMonkey
}
monkeys[monkeyToThrowIndex].worries.addLast(newWorry)
}
}
}
val business = monkeys.sortedByDescending { it.inspections }.take(2).fold(1L) { acc: Long, monkey: Monkey ->
acc * monkey.inspections
}
return business
}
fun part1(input: List<String>): Long {
val monkeys = parseMonkeys(input)
return topTwoMonkeysBusinessMultiplied(monkeys, 20, 3)
}
fun part2(input: List<String>): Long {
val monkeys = parseMonkeys(input)
return topTwoMonkeysBusinessMultiplied(monkeys, 10000, 1)
}
val testInput = readInput("day11/input_test")
val test1Result = part1(testInput)
val test2Result = part2(testInput)
println(test1Result)
println(test2Result)
check(test1Result == 10605L) { "Part ONE failed" }
check(test2Result == 2713310158L) { "Part TWO failed" }
val input = readInput("day11/input")
val part1 = part1(input)
val part2 = part2(input)
check(part1 == 61503L)
check(part2 == 14081365540L)
println(part1)
println(part2)
} | 0 | Kotlin | 0 | 0 | 7530367fb453f012249f1dc37869f950bda018e0 | 4,188 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/2021/Day5.kt | mstar95 | 317,305,289 | false | null | package `2021`
import days.Day
import java.lang.Integer.max
import java.lang.Integer.min
class Day5 : Day(5) {
override fun partOne(): Any {
val lanes = inputList.map {
it.split(" -> ")
.map { it.split(",").map { it.toInt() } }
.map { Point(it[0], it[1]) }
}.map { Line(it[0], it[1]) }
val simple = lanes.filter { it.a.x == it.b.x || it.a.y == it.b.y }
val xd = simple.flatMap { it.draw() }.groupBy { it }.mapValues { it.value.size }.filter { it.value > 1 }
return xd.count()
}
override fun partTwo(): Any {
val lanes = inputList.map {
it.split(" -> ")
.map { it.split(",").map { it.toInt() } }
.map { Point(it[0], it[1]) }
}.map { Line(it[0], it[1]) }
val xd = lanes.flatMap { it.draw() }.groupBy { it }.mapValues { it.value.size }.filter { it.value > 1 }
return xd.count()
}
fun product(x: Point, y: Point, z: Point): Int {
val x1: Int = z.x - x.x
val y1: Int = z.y - x.y
val x2: Int = y.x - x.x
val y2: Int = y.y - x.y
return x1 * y2 - x2 * y1
}
fun sameLine(x: Point, y: Point, z: Point): Boolean {
return min(x.x, y.x) <= x.x && x.x <= max(x.x, y.x) && min(
x.y,
y.y
) <= z.y && z.y <= max(x.y, y.y)
}
fun cross(A: Point, B: Point, C: Point, D: Point): Boolean {
val v1: Int = product(C, D, A)
val v2: Int = product(C, D, B)
val v3: Int = product(A, B, C)
val v4: Int = product(A, B, D)
if ((v1 > 0 && v2 < 0 || v1 < 0 && v2 > 0) && (v3 > 0 && v4 < 0 || v3 < 0 && v4 > 0)) return true
if (v1 == 0 && sameLine(C, D, A)) return true
if (v2 == 0 && sameLine(C, D, B)) return true
if (v3 == 0 && sameLine(A, B, C)) return true
return (v4 == 0 && sameLine(A, B, D))
}
data class Point(val x: Int, val y: Int)
data class Line(val a: Point, val b: Point) {
private fun downToUp(x: Int, y: Int): IntProgression = if (x < y) (x..y) else (x downTo y)
fun draw() = if (a.x == b.x || a.y == b.y) drawHorizotnal() else draw45()
fun drawHorizotnal() = downToUp(a.x, b.x).flatMap { x ->
downToUp(a.y, b.y).map { y ->
Point(x, y)
}
}
fun draw45() = downToUp(a.x, b.x).zip(downToUp(a.y, b.y)) { a, b -> Point(a, b) }
}
}
| 0 | Kotlin | 0 | 0 | ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81 | 2,470 | aoc-2020 | Creative Commons Zero v1.0 Universal |
src/Day18.kt | frungl | 573,598,286 | false | {"Kotlin": 86423} | import java.util.*
fun main() {
fun part1(input: List<String>): Int {
val lava = input.map { it.split(',').toList().map { it.toInt() } }
val dirs = listOf(
listOf(1, 0, 0),
listOf(0, 1, 0),
listOf(0, 0, 1),
listOf(-1, 0, 0),
listOf(0, -1, 0),
listOf(0, 0, -1),
)
val lavaSet = lava.toSet()
return lava.sumOf { pos ->
dirs.count {
val find = listOf(pos[0] + it[0], pos[1] + it[1], pos[2] + it[2])
!lavaSet.contains(find)
}
}
}
fun part2(input: List<String>): Int {
val lava = input.map { it.split(',').toList().map { it.toInt() } }
val dirs = listOf(
listOf(1, 0, 0),
listOf(0, 1, 0),
listOf(0, 0, 1),
listOf(-1, 0, 0),
listOf(0, -1, 0),
listOf(0, 0, -1),
)
val lavaSet = lava.toMutableSet()
for(x in (0..21)) {
for(y in (0..21)) {
for(z in (0..21)) {
val pos = listOf(x, y, z)
if(lavaSet.contains(pos))
continue
val vis = mutableSetOf(pos)
val q = LinkedList<List<Int>>()
q.addFirst(pos)
var cnt = 4000
while(cnt > 0) {
if(q.isEmpty()) break;
val nw = q.last
q.removeLast()
dirs.forEach {
val nxt = listOf(nw[0] + it[0], nw[1] + it[1], nw[2] + it[2])
if(!lavaSet.contains(nxt) && !vis.contains(nxt)) {
q.addFirst(nxt)
vis.add(nxt)
cnt--
}
}
}
if(cnt > 0) {
lavaSet.addAll(vis)
}
}
}
}
return lava.sumOf { pos ->
dirs.count {
val find = listOf(pos[0] + it[0], pos[1] + it[1], pos[2] + it[2])
!lavaSet.contains(find)
}
}
}
val testInput = readInput("Day18_test")
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d4cecfd5ee13de95f143407735e00c02baac7d5c | 2,515 | aoc2022 | Apache License 2.0 |
src/main/kotlin/aoc2021/day12.kt | sodaplayer | 434,841,315 | false | {"Kotlin": 31068} | package aoc2021
import aoc2021.utils.loadInput
fun main() {
val pattern = Regex("""(\w+)-(\w+)""")
val edges = loadInput("/2021/day12")
.bufferedReader()
.readLines()
.map {
val (u, v) = pattern.find(it)!!.destructured
Edge(u, v).normalize()
}
.manualPrune()
val dotfile = edges.toDOT()
println(dotfile)
}
val pruneable = listOf("CT")
fun Iterable<Edge>.manualPrune() =
this.filterNot {
pruneable.contains(it.u) || pruneable.contains(it.v)
}
data class Edge(val u: String, val v: String): Comparable<Edge> {
companion object {
val vertexComparator: VertexComparator = VertexComparator()
}
class VertexComparator: Comparator<String> {
override fun compare(a: String?, b: String?): Int {
return when {
a == b -> 0
a == "start" -> -1
a == "end" -> 1
b == "start" -> 1
b == "end" -> -1
else -> (a ?: "~").compareTo(b ?: "~")
}
}
}
override fun compareTo(other: Edge): Int =
compareBy<Edge, String>(vertexComparator) { it.u }
.thenComparing(compareBy<Edge, String>(vertexComparator) { it.v })
.compare(this, other)
fun normalize(): Edge =
if (vertexComparator.compare(u, v) <= 0) this
else Edge(v, u)
}
fun String.isBig() = this.first().isUpperCase()
fun String.isSmall() = this.first().isLowerCase()
fun Iterable<Edge>.toDOT(): String =
listOf("graph caves {")
.plus(this.sorted().map { (u, v) -> "$u -- $v" }.toList())
.plus(this
.flatMap { (u, v) -> listOf(u, v) }
.asSequence()
.distinct()
.filter { it.isBig() }
.map { "$it [style=filled]" }
.sorted()
)
.plus("start [shape=rarrow]")
.plus("end [shape=doublecircle]")
.plus("}")
.joinToString("\n")
| 0 | Kotlin | 0 | 0 | 2d72897e1202ee816aa0e4834690a13f5ce19747 | 2,008 | aoc-kotlin | Apache License 2.0 |
src/day17/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day17
import assert
import println
import readInput
import java.util.*
enum class Direction(val row: Int, val column: Int) {
UP(-1, 0),
DOWN(1, 0),
LEFT(0, -1),
RIGHT(0, 1);
val opposite by lazy {
when (this) {
UP -> DOWN
RIGHT -> LEFT
DOWN -> UP
LEFT -> RIGHT
}
}
}
fun main() {
data class Position(val row: Int, val column: Int) {
fun move(direction: Direction) = Position(row + direction.row, column + direction.column)
}
data class State(val position: Position, val direction: Direction, val stepsMadeInDirection: Int) {
fun forward(): State = State(position.move(direction), direction, stepsMadeInDirection + 1)
fun turns(): List<State> = Direction.entries
.filter { it != direction && it != direction.opposite}
.map { State(position.move(it), it, 1) }
}
data class QueueItem(val weight: Int, val state: State): Comparable<QueueItem> {
override fun compareTo(other: QueueItem) = weight.compareTo(other.weight)
}
data class PathConfiguration(val minForward: Int, val maxForward: Int)
class PathFinder(input: List<String>, val pathConfig: PathConfiguration) {
val map = input.map { row -> row.map { it.toString().toInt() } }.toList()
val height = map.size
val width = map.first().size
val exit = Position(height - 1, width - 1)
private fun getWeight(position: Position): Int {
return map[position.row][position.column]
}
private fun isValidNext(position: Position): Boolean {
if (position.row < 0 || position.row >= height) return false
if (position.column < 0 || position.column >= width) return false
return true
}
fun nextSteps(currentState: State): List<State> {
val result = mutableSetOf<State>()
if (currentState.stepsMadeInDirection >= pathConfig.minForward) {
result.addAll(currentState.turns())
}
if (currentState.stepsMadeInDirection < pathConfig.maxForward) {
result += currentState.forward()
}
return result.toList()
}
fun getMinPathHeat(): Int {
val queue = PriorityQueue<QueueItem>()
val stepRight = State(Position(0, 0), Direction.RIGHT, 0)
val stepDown = State(Position(0, 0), Direction.DOWN, 0)
val seen = mutableSetOf(stepRight, stepDown)
queue.add(QueueItem(0, stepRight))
queue.add(QueueItem(0, stepDown))
while (queue.isNotEmpty()) {
val queueItem = queue.poll()
if (queueItem.state.position == exit && queueItem.state.stepsMadeInDirection >= pathConfig.minForward)
return queueItem.weight
nextSteps(queueItem.state)
.filter { isValidNext(it.position) }
.filter { !seen.contains(it)}
.forEach {
queue.add(QueueItem(queueItem.weight + getWeight(it.position), it))
seen.add(it)
}
}
return 0
}
}
val largeCruciblesConfig = PathConfiguration(0, 3)
PathFinder(readInput("day17/test1"), largeCruciblesConfig)
.getMinPathHeat()
.assert(102)
"Part 1:".println()
PathFinder(readInput("day17/input"), largeCruciblesConfig)
.getMinPathHeat()
.assert(817)
.println()
val ultraCruciblesConfig = PathConfiguration(4, 10)
PathFinder(readInput("day17/test1"), ultraCruciblesConfig)
.getMinPathHeat()
.assert(94)
PathFinder(readInput("day17/test2"), ultraCruciblesConfig)
.getMinPathHeat()
.assert(71)
"Part 2:".println()
PathFinder(readInput("day17/input"), ultraCruciblesConfig)
.getMinPathHeat()
.assert(925)
.println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 4,026 | advent-of-code-2023 | Apache License 2.0 |
src/Day03.kt | jdpaton | 578,869,545 | false | {"Kotlin": 10658} | fun main() {
fun part1() {
val testInput = readInput("Day03_test")
var sum = 0
testInput.forEach { line ->
val compartmentOne = line.substring(0, (line.length/2)).toCharArray()
val compartmentTwo = line.substring(line.length/2, line.length).toCharArray()
check(compartmentOne.size == compartmentTwo.size)
val commonChars = compartmentOne.filterIndexed{ i: Int, c: Char -> compartmentTwo.contains(c) }
val commonCharsTwo = compartmentTwo.filterIndexed{ i: Int, c: Char -> compartmentOne.contains(c) }
val commonSet = (commonChars + commonCharsTwo).toSet()
commonSet.forEach {
sum += getScore(it)
}
}
println("Pt1 final score: $sum")
}
fun part2() {
val testInput = readInput("Day03_test")
var groupIncr = 0
val groupMap = mutableMapOf<Int,MutableList<String>>()
var currGroup = 0
var totalScore = 0
testInput.forEachIndexed { idx,line ->
if(!groupMap.containsKey(groupIncr)) {
groupMap[groupIncr] = mutableListOf()
}
groupMap[groupIncr]?.add(line)
currGroup += 1
if(currGroup >= 3) {
groupIncr += 1
currGroup = 0
}
}
groupMap.forEach {
val currentInterest = it.value[0].toCharArray()
.intersect(it.value[1].toCharArray().toList().toSet())
.intersect(it.value[2].toCharArray().toList().toSet())
check(currentInterest.size == 1)
totalScore += getScore(currentInterest.first())
}
println("Pt2 final score: $totalScore")
}
part1()
part2()
}
fun getScore(char: Char): Int {
var currentScore = 1
val scoreMap = mutableMapOf<Char, Int>()
for (char in 'a'..'z') {
scoreMap[char] = currentScore
currentScore += 1
}
for (char in 'A'..'Z') {
scoreMap[char] = currentScore
currentScore += 1
}
return scoreMap.getOrDefault(char,0)
}
| 0 | Kotlin | 0 | 0 | f6738f72e2a6395815840a13dccf0f6516198d8e | 2,126 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day05/Day05.kt | MaxBeauchemin | 573,094,480 | false | {"Kotlin": 60619} | package day05
import readInput
import java.util.*
data class Instruction(
val moveCount: Int,
val origin: Int,
val destination: Int
)
fun main() {
val instructionRegex = """move ([0-9]+) from ([0-9]+) to ([0-9]+)""".toRegex()
// 1: 1, 2: 5, 3: 9, 4: 13
fun crateKeyToLineIndex(key: Int): Int {
return if (key == 1) 1
else ((key - 1) * 4) + 1
}
fun parseInput(input: List<String>): Pair<Map<Int, Stack<String>>, List<Instruction>> {
val indexOfStackNames = input.indexOfFirst { it.replace(" ", "").toIntOrNull() != null }
val crateKeys = input[indexOfStackNames].split(" ").mapNotNull { it.toIntOrNull() }
val crateLines = input.slice(0 until indexOfStackNames)
val crateStacks = mutableMapOf<Int, Stack<String>>()
crateLines.reversed().map { str ->
val charList = str.toList()
crateKeys.forEach { key ->
val idx = crateKeyToLineIndex(key)
if (idx < charList.size) {
val crateContent = charList[idx].toString()
if (crateContent.isNotBlank()) {
if (crateStacks.containsKey(key)) {
crateStacks[key]!!.push(crateContent)
} else {
crateStacks[key] = Stack<String>().also { it.push(crateContent) }
}
}
}
}
}
val instructionLines = input.slice(indexOfStackNames + 1 until input.size)
val instructions = instructionLines.mapNotNull { str ->
instructionRegex.find(str)?.let { matchResult ->
val (moveCount, origin, destination) = matchResult.destructured
Instruction(
moveCount.toInt(),
origin.toInt(),
destination.toInt()
)
}
}
return crateStacks.toMap() to instructions
}
fun part1(input: List<String>): String {
val (crateStacks, instructions) = parseInput(input)
instructions.forEach { i ->
repeat(i.moveCount) {
crateStacks[i.origin]!!.pop().also { crateContent ->
crateStacks[i.destination]!!.push(crateContent)
}
}
}
return crateStacks.entries.sortedBy { it.key }.joinToString("") { it.value.peek() }
}
fun part2(input: List<String>): String {
val (crateStacks, instructions) = parseInput(input)
// ugly but simple
val tempStack = Stack<String>()
instructions.forEach { i ->
repeat(i.moveCount) {
crateStacks[i.origin]!!.pop().also { crateContent ->
tempStack.push(crateContent)
}
}
repeat(i.moveCount) {
crateStacks[i.destination]!!.push(tempStack.pop())
}
}
return crateStacks.entries.sortedBy { it.key }.joinToString("") { it.value.peek() }
}
val testInput = readInput("Day05_test")
val input = readInput("Day05")
println("Part 1 [Test] : ${part1(testInput)}")
check(part1(testInput) == "CMZ")
println("Part 1 [Real] : ${part1(input)}")
println("Part 2 [Test] : ${part2(testInput)}")
check(part2(testInput) == "MCD")
println("Part 2 [Real] : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 38018d252183bd6b64095a8c9f2920e900863a79 | 3,444 | advent-of-code-2022 | Apache License 2.0 |
src/year2023/day14/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2023.day14
import arrow.core.nonEmptyListOf
import utils.ProblemPart
import utils.findCycle
import utils.readInputs
import utils.runAlgorithm
import utils.transpose
fun main() {
val (realInput, testInputs) = readInputs(2023, 14)
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(136),
algorithm = ::part1,
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(64),
algorithm = ::part2,
),
)
}
private fun part1(input: List<String>): Long {
return input.transpose().asSequence()
.flatMap(rockRegex::findAll)
.sumOf { rockPositions ->
val rockCount = rockPositions.value.count { it == 'O' }
rockPositions.range.asSequence()
.take(rockCount)
.sumOf { input.first().length - it }
.toLong()
}
}
private val rockRegex = "(?<=\\A|#)[^#]*?O[^#]*?(?=\\z|#)".toRegex()
private fun part2(input: List<String>): Long {
val cycle = generateSequence(input, ::executeCycle).findCycle()
val endStateIndex = (1000_000_000 - cycle.loopStart) % cycle.loopSize + cycle.loopStart
return cycle.steps[endStateIndex].northLoad()
}
private fun executeCycle(startState: List<String>): List<String> {
return startState.transpose()
.moveAllRocks(left = true)
.transpose()
.moveAllRocks(left = true)
.transpose()
.moveAllRocks(left = false)
.transpose()
.moveAllRocks(left = false)
}
private fun List<String>.moveAllRocks(left: Boolean): List<String> = map { line ->
line.splitToSequence(rockZoneRegex).joinToString(separator = "") { zone ->
zone.asSequence()
.sortedWith { a, b ->
when {
a == 'O' -> 1
b == 'O' -> -1
else -> 0
}
}
.joinToString(separator = "")
.let { if (left) it.reversed() else it }
}
}
private fun List<String>.northLoad(): Long {
return asReversed()
.asSequence()
.withIndex()
.sumOf { (index, line) ->
(index + 1) * line.count { it == 'O' }.toLong()
}
}
private val rockZoneRegex = "(?<=#)|(?=#)".toRegex()
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 2,391 | Advent-of-Code | Apache License 2.0 |
src/Day11.kt | mikrise2 | 573,939,318 | false | {"Kotlin": 62406} | import java.util.LinkedList
import java.util.Queue
fun main() {
data class Monkey(
val items: Queue<Long>,
val operation: (Long) -> Long,
val divisibleBy: Long,
val trueMonkey: Int,
val falseMonkey: Int,
)
fun progress(input: List<String>, div: Boolean, repeats: Int): Long {
val monkeys = input.filter { it.isNotEmpty() }.chunked(6).map {
val items = it[1].trim().split(" ").filterIndexed { index, _ -> index > 1 }.map { number ->
if (number.contains(",")) number.replace(",", "").toLong()
else number.toLong()
}.toMutableList()
val operation = { numberInt: Long ->
val split = it[2].trim().split(" ")
when (split[4]) {
"*" -> {
if (split[5] != "old")
numberInt * split[5].toLong()
else {
numberInt * numberInt
}
}
else -> {
if (split[5] != "old")
numberInt + split[5].toLong()
else {
numberInt + numberInt
}
}
}
}
val dividedBy = it[3].trim().split(" ")[3].toLong()
val trueMonkey = it[4].trim().split(" ")[5].toInt()
val falseMonkey = it[5].trim().split(" ")[5].toInt()
Monkey(LinkedList(items), operation, dividedBy, trueMonkey, falseMonkey)
}
val divisor = monkeys.fold(1L) { acc, monkey -> acc * monkey.divisibleBy }
val monkeyInspects = MutableList(monkeys.size) { 0L }
repeat(repeats) {
monkeys.forEachIndexed { index, monkey ->
while (monkey.items.isNotEmpty()) {
monkeyInspects[index]++
val withOperation = monkey.operation(monkey.items.poll())
val element = if(div) (withOperation.toFloat() / 3).toLong() else
(withOperation % divisor)
if (element % monkey.divisibleBy == 0L) {
monkeys[monkey.trueMonkey].items.add(element)
} else {
monkeys[monkey.falseMonkey].items.add(element)
}
}
}
}
return monkeyInspects.sortedDescending().take(2).fold(1L) { acc, number -> acc * number }
}
fun part1(input: List<String>): Long {
return progress(input, true, 20)
}
fun part2(input: List<String>): Long {
return progress(input, false, 10000)
}
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8 | 2,842 | Advent-of-code | Apache License 2.0 |
src/Day05.kt | MatthiasDruwe | 571,730,990 | false | {"Kotlin": 47864} | fun main() {
fun part1(input: List<String>): String {
val start = input.subList(0, input.indexOf(""))
val actions = input.subList(input.indexOf("") + 1, input.size).map {
val items = it.split(" ")
Triple(items[1].toInt(), items[3].toInt(), items[5].toInt())
}
val items = start
.map { line -> line.chunked(4).map { if (it[1] == ' ') null else it[1] } }
.asReversed()
.drop(1)
.transpose()
.map { it.filterNotNull().toMutableList() }
.toMutableList()
actions.forEach {
val away = items[it.second-1].takeLast(it.first)
items[it.second-1] = items[it.second-1].dropLast(it.first).toMutableList()
items[it.third-1].addAll(away.reversed())
}
return items.map { it.last() }.joinToString("")
}
fun part2(input: List<String>): String {
val start = input.subList(0, input.indexOf(""))
val actions = input.subList(input.indexOf("") + 1, input.size).map {
val items = it.split(" ")
Triple(items[1].toInt(), items[3].toInt(), items[5].toInt())
}
val items = start
.map { line -> line.chunked(4).map { if (it[1] == ' ') null else it[1] } }
.asReversed()
.drop(1)
.transpose()
.map { it.filterNotNull().toMutableList() }
.toMutableList()
actions.forEach {
val away = items[it.second-1].takeLast(it.first)
items[it.second-1] = items[it.second-1].dropLast(it.first).toMutableList()
items[it.third-1].addAll(away)
}
return items.map { it.last() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_example")
check(part1(testInput) == "CMZ" )
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f35f01cea5075cfe7b4a1ead9b6480ffa57b4989 | 2,037 | Advent-of-code-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day9/Day9.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day9
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputLines
object Day9 : Day {
override val input = readInputLines(9)
.map { l -> l.toCharArray().map { it.digitToInt() } }
.flatMapIndexed { y, i -> i.mapIndexed { x, v -> (Position(x, y) to v) } }
.toMap()
override fun part1() = input.lowPoints().values.sumOf { it + 1 }
override fun part2(): Int {
return input.lowPoints()
.map { input.basin(mapOf(it.toPair())) }
.sortedDescending()
.take(3)
.fold(1) { a, c -> a * c }
}
data class Position(val x: Int, val y: Int) {
fun adjacent() = listOf(copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1))
}
private fun Map<Position, Int>.lowPoints() = filter { (k, v) -> k.adjacent().mapNotNull { input[it] }.all { it > v } }
private fun Map<Position, Int>.basin(initial: Map<Position, Int>): Int {
val next = initial.flatMap { nextBasinCells(it.key, it.value, initial) }.toMap()
val all = initial + next
if (next.isNotEmpty()) {
return basin(all)
}
return all.values.count()
}
private fun Map<Position, Int>.nextBasinCells(position: Position, value: Int, cells: Map<Position, Int>): List<Pair<Position, Int>> {
return position.adjacent().mapNotNull { p -> get(p)?.takeIf { !cells.containsKey(p) && it > value && it != 9 }?.let { p to it } }
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 1,541 | aoc2021 | MIT License |
src/day07/Main.kt | nikwotton | 572,814,041 | false | {"Kotlin": 77320} | package day07
import day07.FileSystemThing.Dir
import java.io.File
const val workingDir = "src/day07"
fun main() {
val sample = File("$workingDir/sample.txt")
val input1 = File("$workingDir/input_1.txt")
println("Step 1a: ${runStep1(sample)}")
println("Step 1b: ${runStep1(input1)}")
println("Step 2a: ${runStep2(sample)}")
println("Step 2b: ${runStep2(input1)}")
}
fun runStep1(input: File): String = input.readLines().toFileStructure().sumOfSmall()
fun List<String>.toFileStructure(): Dir {
val fileSystem = Dir(null, "/", mutableListOf())
var currentDir: Dir? = fileSystem
forEach {
when {
it.startsWith("$") -> {
if (it == "$ cd /") currentDir = fileSystem
else if (it == "$ cd ..") currentDir = currentDir?.parent
else if (it.startsWith("$ cd ")) {
val dirName = it.removePrefix("$ cd ")
val childDir = currentDir?.children?.filterIsInstance<Dir>()?.firstOrNull { it.name == dirName } ?: Dir(currentDir, dirName, mutableListOf()).also { currentDir!!.children.add(it) }
currentDir = childDir
} else if (it == "$ ls") Unit
else TODO("Need to handle $it")
}
it.startsWith("dir ") -> Unit
it.split(" ")[0].toIntOrNull() != null -> {
val (size, name) = it.split(" ")
currentDir!!.children.add(FileSystemThing.File(currentDir!!, size.toInt(), name))
}
else -> TODO("Need to handle: $it")
}
}
return fileSystem
}
fun Dir.flattenToDir(): List<Dir> =
children.filterIsInstance<Dir>().flatMap { it.flattenToDir() } + this
fun Dir.sumOfSmall(): String =
flattenToDir().map { it.size() }.filter { it <= 100_000 }.sum().toString()
fun FileSystemThing.size(): Int = when (this) {
is Dir -> children.sumOf { it.size() }
is FileSystemThing.File -> this.size
}
sealed class FileSystemThing {
abstract val parent: Dir?
data class File(override val parent: Dir, val size: Int, val name: String) : FileSystemThing()
data class Dir(override val parent: Dir?, val name: String, val children: MutableList<FileSystemThing>) : FileSystemThing()
}
fun runStep2(input: File): String = input.readLines().toFileStructure().smallestBigEnough()
fun Dir.smallestBigEnough(): String {
val totalSize = 70_000_000
val needed = 30_000_000
val sizes = flattenToDir().map { it.size() }
val usedSpace = size()
val minToDelete = needed - (totalSize - usedSpace)
return sizes.filter { it > minToDelete }.min().toString()
}
| 0 | Kotlin | 0 | 0 | dee6a1c34bfe3530ae6a8417db85ac590af16909 | 2,654 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/Day06.kt | ekureina | 433,709,362 | false | {"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386} | import java.lang.Integer.parseInt
fun main() {
val part1Iterations = 80
val part2Iterations = 256
data class LanternFish(val timer: Int)
fun updateLanternFish(fish: List<LanternFish>): List<LanternFish> {
val oldFish = fish.map { singleFish ->
if (singleFish.timer == 0) {
LanternFish(6)
} else {
LanternFish(singleFish.timer - 1)
}
}
val newFish = (0 until fish.count { singleFish -> singleFish.timer == 0 }).map {
LanternFish(8)
}
return listOf(oldFish, newFish).flatten()
}
fun part1(input: List<String>): Int {
val lanternFish = input.first().split(",").map(::parseInt).map(::LanternFish)
return (0 until part1Iterations).fold(lanternFish) { fish, _ ->
updateLanternFish(fish)
}.size
}
fun part2(input: List<String>): Long {
val lanternFish = input.first().split(",").map(::parseInt).map(::LanternFish)
var timerMap = lanternFish.associate { fish ->
fish.timer to lanternFish.count { it == fish }.toLong()
}.toMutableMap()
(0 until part2Iterations).forEach { _ ->
val newCounts = timerMap.keys.flatMap { count ->
if (count == 0) {
listOf(8 to timerMap[count]!!, 6 to timerMap[count]!!)
} else {
listOf((count - 1) to timerMap[count]!!)
}
}
val combinedCount = newCounts.filter { count -> count.first == 6 }.sumOf { count -> count.second }
timerMap = newCounts.associate { it }.toMutableMap()
if (combinedCount > 0) {
timerMap[6] = combinedCount
}
}
return timerMap.values.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 5934) { "${part1(testInput)}" }
check(part2(testInput) == 26984457539L) { "${part2(testInput)}" }
val input = readInput("Day06")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 391d0017ba9c2494092d27d22d5fd9f73d0c8ded | 2,159 | aoc-2021 | MIT License |
algorithms/src/main/kotlin/com/kotlinground/algorithms/dynamicprogramming/longestcommonsubsequence/longestCommonSubsequence.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 483489, "Shell": 7283, "Python": 1725} | package com.kotlinground.algorithms.dynamicprogramming.longestcommonsubsequence
import kotlin.math.max
/**
* LCS is a classic problem. Let dp[i][j] be the LCS for string text1 ends at index i and string text2 ends at index j.
* If text1[i]==text2[j], then dp[i][j] would be 1+dp[i−1][j−1]. Otherwise, we target the largest LCS if we skip one
* character from either text1 or text2, i.e. dp[i][j]=max(dp[i−1][j],dp[i][j−1]).
*
* Complexity:
* Where m is the length of text1 and n is the length of text2
* - Time complexity: O(m*n)
* - Space complexity: O(m*n)
*/
fun longestCommonSubsequence(text1: String, text2: String): Int {
val text1Length = text1.length
val text2Length = text2.length
val dp = Array(text1Length + 1) { IntArray(text2Length + 1) }
for (i in 0 until text1Length + 1) {
for (j in 0 until text2Length + 1) {
if (i == 0 || j == 0) {
// setting first row and first column to be zero(initial readings)
dp[i][j] = 0
} else if (text1[i - 1] == text2[j - 1]) {
/* if match found, then store value of previous diagonal element(dp[i - 1][j - 1]) and increase the
value by 1 i.e. a new character match is found
*/
dp[i][j] = dp[i - 1][j - 1] + 1
} else {
/*
otherwise, choose maximum of either previous element, either in row(dp[i][j -1]) or column(dp[i][j - 1])
*/
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])
}
}
}
// dp[text1Length][text2Length] would hold the value of the LCS obtained
return dp[text1Length][text2Length]
}
| 1 | Kotlin | 1 | 0 | 5e3e45b84176ea2d9eb36f4f625de89d8685e000 | 1,710 | KotlinGround | MIT License |
src/Day08.kt | gsalinaslopez | 572,839,981 | false | {"Kotlin": 21439} | fun main() {
fun buildTreeGrid(input: List<String>) =
Array(input.size) { i -> Array(input[i].length) { j -> input[i][j].digitToInt() } }
fun part1(treeGrid: Array<Array<Int>>): Int {
val markerGrid = Array(treeGrid.size) { i ->
Array(treeGrid[i].size) { j ->
i == 0 || i == treeGrid.size - 1 || j == 0 || j == treeGrid[i].size - 1
}
}
// left to right swipe
for (i in treeGrid.indices) {
var maxSoFar = -1
treeGrid[i].forEachIndexed { j, treeHeight ->
if (treeHeight > maxSoFar) {
markerGrid[i][j] = true
}
maxSoFar = maxOf(maxSoFar, treeHeight)
}
}
// right to left swipe
for (i in treeGrid.indices) {
var maxSoFar = -1
for (j in treeGrid.size - 1 downTo 0) {
if (treeGrid[i][j] > maxSoFar) {
markerGrid[i][j] = true
}
maxSoFar = maxOf(maxSoFar, treeGrid[i][j])
}
}
// up to down swipe
for (j in treeGrid[0].indices) {
var maxSoFar = -1
for (i in treeGrid.indices) {
if (treeGrid[i][j] > maxSoFar) {
markerGrid[i][j] = true
}
maxSoFar = maxOf(maxSoFar, treeGrid[i][j])
}
}
// down to up swipe
for (j in treeGrid[0].indices) {
var maxSoFar = -1
for (i in treeGrid.size - 1 downTo 0) {
if (treeGrid[i][j] > maxSoFar) {
markerGrid[i][j] = true
}
maxSoFar = maxOf(maxSoFar, treeGrid[i][j])
}
}
return markerGrid.sumOf { row -> row.count { it } }
}
fun part2(treeGrid: Array<Array<Int>>): Int {
var maxSoFar = -1
for (i in 1 until treeGrid.size - 1) {
for (j in 1 until treeGrid[i].size - 1) {
// right
var rightCount = 1
for (k in j + 1 until treeGrid[i].size - 1) {
if (treeGrid[i][k] >= treeGrid[i][j]) {
break
}
rightCount++
}
// left
var leftCount = 1
if (j > 0) {
for (k in j - 1 downTo 1) {
if (treeGrid[i][k] >= treeGrid[i][j]) {
break
}
leftCount++
}
}
// down
var downCount = 1
for (k in i + 1 until treeGrid.size - 1) {
if (treeGrid[k][j] >= treeGrid[i][j]) {
break
}
downCount++
}
// up
var upCount = 1
if (i > 0) {
for (k in i - 1 downTo 1) {
if (treeGrid[k][j] >= treeGrid[i][j]) {
break
}
upCount++
}
}
maxSoFar = maxOf(maxSoFar, (leftCount * rightCount * upCount * downCount))
}
}
return maxSoFar
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(buildTreeGrid(testInput)) == 21)
check(part2(buildTreeGrid(testInput)) == 8)
val input = readInput("Day08")
println(part1(buildTreeGrid(input)))
println(part2(buildTreeGrid(input)))
}
| 0 | Kotlin | 0 | 0 | 041c7c3716bfdfdf4cc89975937fa297ea061830 | 3,735 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day16.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | import kotlin.collections.ArrayDeque
import kotlin.math.max
private const val EXPECTED_1 = 46
private const val EXPECTED_2 = 51
private class Day16(isTest: Boolean) : Solver(isTest) {
data class Point(val y: Int, val x: Int, val dir: Int)
val dirs = listOf(0 to -1, 1 to 0, 0 to 1, -1 to 0)
val field = readAsLines().map { it.toCharArray() }
val Y = field.size
val X = field[0].size
fun energized(startPoint: Point): Int {
val seen = mutableSetOf<Point>()
var points = ArrayDeque<Point>()
points.add(startPoint)
fun newDir(ch: Char, dir: Int): List<Int> {
return when (ch) {
'.' -> listOf(dir)
'|' -> if (dir == 1 || dir == 3) {
listOf(0, 2)
} else {
listOf(dir)
}
'-' -> if (dir == 0 || dir == 2) {
listOf(1, 3)
} else {
listOf(dir)
}
'/' -> listOf(
when (dir) {
0 -> 1
1 -> 0
2 -> 3
3 -> 2
else -> error("wrong dir: $dir")
}
)
'\\' -> listOf(
when (dir) {
0 -> 3
1 -> 2
2 -> 1
3 -> 0
else -> error("wrong dir: $dir")
}
)
else -> error("wrong ch: $ch")
}
}
while (points.isNotEmpty()) {
val p = points.removeFirst()
val nx = p.x + dirs[p.dir].first
val ny = p.y + dirs[p.dir].second
if (nx in 0..<X && ny in 0..<Y) {
for (newDir in newDir(field[ny][nx], p.dir)) {
val np = Point(ny, nx, newDir)
if (np !in seen) {
seen.add(np)
points.add(np)
}
}
}
}
return seen.distinctBy { it.y to it.x }.size
}
fun part1() = energized(Point(0, -1, 1))
fun part2(): Any {
var result = 0
for (y in 0..<Y) {
result = max(result, energized(Point(y, -1, 1)))
result = max(result, energized(Point(y, X, 3)))
}
for (x in 0..<X) {
result = max(result, energized(Point(-1, x, 2)))
result = max(result, energized(Point(Y, x, 0)))
}
return result
}
}
fun main() {
val testInstance = Day16(true)
val instance = Day16(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 3,029 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/kotlin/day02/Day02.kt | W3D3 | 726,573,421 | false | {"Kotlin": 81242} | package day02
import common.InputRepo
import common.readSessionCookie
import common.solve
import util.splitIntoPair
fun main(args: Array<String>) {
val day = 2
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay02Part1, ::solveDay02Part2)
}
fun solveDay02Part1(input: List<String>): Int {
val games = input.map { parseGameRecord(it) }
println(games)
var sum = 0
for ((id, pulls) in games) {
val invalidPull = pulls.find { map ->
map.getOrDefault(Color.RED, 0) > 12 ||
map.getOrDefault(Color.GREEN, 0) > 13 ||
map.getOrDefault(Color.BLUE, 0) > 14
}
if (invalidPull != null) {
println(invalidPull)
println(id)
} else {
sum += id
}
}
return sum
}
fun solveDay02Part2(input: List<String>): Int {
val games = input.map { parseGameRecord(it) }
println(games)
val sum = games.sumOf {
val pulls = it.pulls
val redPull = pulls.maxBy { map ->
map.getOrDefault(Color.RED, 0)
}.getOrDefault(Color.RED, 0)
val greenPull = pulls.maxBy { map ->
map.getOrDefault(Color.GREEN, 0)
}.getOrDefault(Color.GREEN, 0)
val bluePull = pulls.maxBy { map ->
map.getOrDefault(Color.BLUE, 0)
}.getOrDefault(Color.BLUE, 0)
redPull * greenPull * bluePull
}
return sum
}
enum class Color {
BLUE, RED, GREEN,
}
private fun parseGameRecord(line: String): GameRecord {
val moveRegex = """Game (\d+): (.*)$""".toRegex()
return moveRegex.matchEntire(line)
?.destructured
?.let { (id, pulls) ->
GameRecord(id.toInt(), pulls.split(';').map { s ->
s.split(',').map {
it.trim().splitIntoPair(" ")
.let { pair -> Pair(Color.valueOf(pair.second.uppercase()), pair.first.toInt()) }
}.toMap()
})
}
?: throw IllegalArgumentException("Bad input '$line'")
}
data class GameRecord(val id: Int, val pulls: List<Map<Color, Int>>)
| 0 | Kotlin | 0 | 0 | da174508f6341f85a1a92159bde3ecd5dcbd3c14 | 2,159 | AdventOfCode2023 | Apache License 2.0 |
src/Day12.kt | thorny-thorny | 573,065,588 | false | {"Kotlin": 57129} | enum class Direction(val dColumn: Int, val dRow: Int) {
Up(0, -1),
Down(0, 1),
Left(-1, 0),
Right(1, 0),
}
fun main() {
fun findMinSteps(input: List<String>, stepsDelta: (Int, Int) -> Int): Int {
var start = 0 to 0
var end = 0 to 0
var heightMap = input.mapIndexed { rowIndex, row ->
row.mapIndexed { columnIndex, mapChar ->
when (mapChar) {
'S' -> {
start = rowIndex to columnIndex
'a'
}
'E' -> {
end = rowIndex to columnIndex
'z'
}
else -> mapChar
} - 'a'
}
}
val rows = heightMap.size
val columns = heightMap.first().size
var stepsMap = List(rows) { MutableList(columns) { Int.MAX_VALUE } }
val updated = ArrayDeque<Pair<Int, Int>>(rows * columns)
stepsMap[start.first][start.second] = 0
updated.addLast(start)
while (updated.size > 0) {
val position = updated.removeLast()
val positionHeight = heightMap[position.first][position.second]
Direction.values().forEach { direction ->
val neighbour = Pair(position.first + direction.dRow, position.second + direction.dColumn)
if (neighbour.first in 0 until rows && neighbour.second in 0 until columns) {
val nextSteps = stepsMap[position.first][position.second] + stepsDelta(positionHeight, heightMap[neighbour.first][neighbour.second])
val isReachable = heightMap[neighbour.first][neighbour.second] - positionHeight <= 1
val isOptimizible = stepsMap[neighbour.first][neighbour.second] > nextSteps
if (isReachable && isOptimizible) {
stepsMap[neighbour.first][neighbour.second] = nextSteps
updated.addLast(neighbour)
}
}
}
}
return stepsMap[end.first][end.second]
}
fun part1(input: List<String>): Int {
return findMinSteps(input) { _, _ -> 1 }
}
fun part2(input: List<String>): Int {
return findMinSteps(input) { a, b -> when (a to b) {
(0 to 0) -> 0
else -> 1
}}
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 843869d19d5457dc972c98a9a4d48b690fa094a6 | 2,615 | aoc-2022 | Apache License 2.0 |
src/Day15.kt | kipwoker | 572,884,607 | false | null | import kotlin.math.abs
fun main() {
data class Signal(val sensor: Point, val beacon: Point) {
fun getDistance(): Int {
return abs(sensor.x - beacon.x) + abs(sensor.y - beacon.y)
}
}
fun parse(input: List<String>): List<Signal> {
val regex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex()
return input.map { line ->
val (sensorX, sensorY, beaconX, beaconY) = regex
.matchEntire(line)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $line")
Signal(Point(sensorX.toInt(), sensorY.toInt()), Point(beaconX.toInt(), beaconY.toInt()))
}
}
fun getIntervals(
signals: List<Signal>,
row: Int
): List<Interval> {
val intervals = mutableListOf<Interval>()
for (signal in signals) {
val distance = signal.getDistance()
val diff = abs(signal.sensor.y - row)
if (diff <= distance) {
val delta = distance - diff
val interval = Interval(signal.sensor.x - delta, signal.sensor.x + delta)
// println("$signal diff: $diff delta: $delta distance: $distance interval: $interval")
intervals.add(interval)
}
}
val merged = Interval.merge(intervals)
// println("Merged: $merged")
return merged
}
fun part1(signals: List<Signal>, row: Int): Int {
val merged = getIntervals(signals, row)
val points = signals
.flatMap { s -> listOf(s.beacon, s.sensor) }
.filter { p -> p.y == row }
.map { p -> p.x }
.toSet()
return merged.sumOf { i -> i.countPoints(points) }
}
fun part2(signals: List<Signal>, limit: Int): Long {
for (row in 0..limit) {
val intervals = getIntervals(signals, row)
if (intervals.size == 2) {
val left = intervals[0]
val right = intervals[1]
if (left.end + 1 == right.start - 1) {
return (left.end + 1) * 4000000L + row
} else {
println("Error: $left $right $row")
throw RuntimeException()
}
}
if (intervals.size != 1) {
println("Error: ${intervals.size} $row")
throw RuntimeException()
}
}
return -1
}
val testInput = readInput("Day15_test")
assert(part1(parse(testInput), 10), 26)
assert(part2(parse(testInput), 20), 56000011L)
val input = readInput("Day15")
println(part1(parse(input), 2000000))
println(part2(parse(input), 4000000))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 2,805 | aoc2022 | Apache License 2.0 |
src/Day07.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | private interface Node {
fun dirSize(): Int
}
private data class Dir(val name: String, val parent: Dir?) : HashMap<String, Node>(), Node {
private var dirSize = -1
override fun dirSize(): Int {
if (dirSize == -1) {
dirSize = values.sumOf { it.dirSize() }
}
return dirSize
}
fun iterate(): List<Dir> {
val list = mutableListOf<Dir>()
for (dir in values.filterIsInstance<Dir>()) {
list.add(dir)
list.addAll(dir.iterate())
}
return list
}
}
private data class File(val name: String, val size: Int, val parent: Dir) : Node {
override fun dirSize(): Int {
return size
}
}
fun main() {
val changeDir = "\\$ cd (?<dir>.*)".toRegex()
val list = "\\$ ls".toRegex()
val file = "(?<size>\\d+) (?<name>.*)".toRegex()
fun List<String>.parse(): Dir {
val root = Dir(name = "/", parent = null)
var currenLoc = root
fun parseDir(dir: String) {
currenLoc = when (dir) {
"/" -> root
".." -> currenLoc.parent ?: throw Exception("cant go to parent of ${currenLoc.name}")
else -> {
val childDir = currenLoc.values.filterIsInstance(Dir::class.java).firstOrNull { it.name == dir }
if (childDir == null) {
val newDir = Dir(dir, currenLoc)
currenLoc[dir] = newDir
newDir
} else {
childDir
}
}
}
}
fun parseList(index: Int) {
var resultIndex = index + 1
while (resultIndex < this.size && this[resultIndex].first() != '$') {
val fileLine = this[resultIndex]
if (fileLine.startsWith("dir")) {
resultIndex += 1
continue
}
val matchesFile = file.matchEntire(fileLine)
val name = matchesFile?.groups?.get("name")?.value ?: throw Exception("Cant parse")
val size = matchesFile.groups["size"]?.value?.toInt() ?: throw Exception("Cant parse")
currenLoc[name] = File(name, size, currenLoc)
resultIndex += 1
}
}
for (i in indices) {
val line = this[i]
val matchesChangeDir = changeDir.matchEntire(line)
val matchesList = list.matchEntire(line)
if (matchesChangeDir?.groups != null) {
val dir = matchesChangeDir.groups["dir"]?.value ?: throw Exception("Cant parse")
parseDir(dir)
} else if (matchesList != null) {
parseList(i)
}
}
return root
}
fun part1(input: List<String>): Int =
input.parse().iterate().map { it.dirSize() }.filter { it <= 100000 }.sum()
fun part2(input: List<String>): Int {
val totalSpace = 70000000
val neededSpace = 30000000
val root = input.parse()
val unusedSpace = totalSpace - root.dirSize()
val needToFreeSpace = neededSpace - unusedSpace
return root.iterate()
.map { it }
.sortedBy { it.dirSize() }
.first { it.dirSize() > needToFreeSpace }
.dirSize()
}
val testInput = readInput("Day07_test")
val input = readInput("Day07")
assert(part1(testInput), 95437)
println(part1(input))
assert(part2(testInput), 24933642)
println(part2(input))
}
// Time: 00:40
| 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 3,611 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/startat/aoc2023/Day5.kt | Arondc | 727,396,875 | false | {"Kotlin": 194620} | package de.startat.aoc2023
data class SparseMapping(val srcStart : Long, val destStart : Long, val length : Long){
val sourceRange = srcStart..<srcStart+length
}
data class SparseRangeMap(val from : String, val to: String, private val mappings : MutableList<SparseMapping> = mutableListOf()){
fun addMappings(sparseMapping : SparseMapping) {
mappings.add(sparseMapping)
}
fun map(source: Long): Long = mappings.asSequence().filter { r -> r.sourceRange.contains(source) }
.map { r -> source-r.srcStart + r.destStart }.elementAtOrElse(0) { _ -> source }
}
data class Almanac(val seeds: List<Pair<String,Long>>, val mappings : List<SparseRangeMap>) {
fun map(source: Pair<String,Long>) : Pair<String, Long> =
mappings.filter { m -> m.from == source.first }.map { m -> Pair(m.to, m.map(source.second))}.first()
fun mapComplete(source : Pair<String, Long>) : Pair<String, Long>{
var lastResult = source
try {
while (true) {
lastResult = map(lastResult)
}
} catch (e: NoSuchElementException){
return lastResult
}
}
}
fun String.toSparseMapping() : SparseMapping {
val values = this.split(" ")
val destRangeStart = values[0].toLong()
val sourceRangeStart = values[1].toLong()
val rangeLength = values[2].toLong()
return SparseMapping(sourceRangeStart, destRangeStart,rangeLength)
}
class Day5 {
val seedsLineStart = "seeds:"
val mapRegex = Regex("(.*)-to-(.*) map")
public fun star1() {
val almanac = buildAlmanac(day5Input)
//println(almanac)
val results = almanac.seeds.map { s-> almanac.mapComplete(s)}.sortedBy { r -> r.second }.toList()
println(results)
}
private fun buildAlmanac(input : String): Almanac {
var seeds: List<Pair<String,Long>> = mutableListOf()
val srms: MutableList<SparseRangeMap> = mutableListOf()
var currentSrm = SparseRangeMap("dummy", "dummy")
input.lines().forEach { line ->
if (line.startsWith(seedsLineStart)) {
seeds = line.substringAfter(": ").split(" ").map { "seed" to it.toLong() }.toList()
} else if (line.endsWith("map:")) {
val match = mapRegex.find(line)!!
val from = match.groupValues[1]
val to = match.groupValues[2]
currentSrm = SparseRangeMap(from, to)
srms.add(currentSrm)
} else if (line.split(" ").count() == 3) {
currentSrm.addMappings(line.toSparseMapping())
}
}
val almanac = Almanac(seeds, srms)
return almanac
}
public fun star2() {
}
}
val day5TestInput = """
seeds: 79 14 55 13
seed-to-soil map:
50 98 2
52 50 48
soil-to-fertilizer map:
0 15 37
37 52 2
39 0 15
fertilizer-to-water map:
49 53 8
0 11 42
42 0 7
57 7 4
water-to-light map:
88 18 7
18 25 70
light-to-temperature map:
45 77 23
81 45 19
68 64 13
temperature-to-humidity map:
0 69 1
1 0 69
humidity-to-location map:
60 56 37
56 93 4
""".trimIndent()
val day5Input = """
seeds: 1367444651 99920667 3319921504 153335682 67832336 139859832 2322838536 666063790 1591621692 111959634 442852010 119609663 733590868 56288233 2035874278 85269124 4145746192 55841637 864476811 347179760
seed-to-soil map:
873256303 3438158294 3400501
3338810960 408700040 99469568
876656804 586381004 55967396
2937187724 3352513245 85645049
3633224442 4294716315 250981
4063203128 3993405594 231764168
628606346 884567853 85164246
1848085960 2225191252 328179324
1686068310 2992301693 162017650
1456962076 179593806 229106234
0 1520731987 239660433
2759350898 1833519805 177836826
494634602 642348400 67929420
3022832773 758696310 125871543
3563677889 4225169762 69546553
2637775123 710277820 48418490
3148704316 969732099 112580498
3261284814 2623022420 77526146
489910414 174869618 4724188
1187482559 2700548566 269479517
713770592 2139594657 85596595
850982693 2970028083 22273610
932624200 2013609609 125985048
799367187 1082312597 51615506
3633475423 3563677889 429727705
562564022 3283192654 66042324
2181319395 2553370576 69651844
2250971239 1133928103 386803884
3438280528 3349234978 3278267
2686193613 513223719 73157285
239660433 1760392420 73127385
487657436 2011356631 2252978
312787818 0 174869618
1058609248 3154319343 128873311
2176265284 508169608 5054111
soil-to-fertilizer map:
297032819 3559164217 26523093
323555912 2482284077 316032053
74171080 3214516077 10202585
3176226661 2368836568 113447509
2918425623 1610395638 257801038
3933490965 2171144546 103908097
1218064889 55976272 92496985
2591090931 0 23819721
1798514394 148473257 159960710
2288143061 1868196676 302947870
639587965 3736262447 6060799
3609511269 699586127 40962058
1575586870 3249692350 47378699
1310561874 2798316130 265024996
3650473327 2308711439 60125129
1958475104 483393073 178493006
259332771 661886079 37700048
907741932 980768687 228854035
1185908338 23819721 32156551
3437918904 3874038292 163360770
645648764 3297071049 262093168
2648569448 1432515231 29635673
1647939257 3585687310 150575137
3710598456 1209622722 222892509
2678205121 740548185 240220502
84373665 308433967 174959106
2614910652 2275052643 33658796
1622965569 3224718662 24973688
3289674170 1462150904 148244734
3601279674 3791635617 8231595
0 3799867212 74171080
2136968110 3063341126 151174951
1136595967 3742323246 49312371
fertilizer-to-water map:
0 478733437 191375707
2494518625 3362803490 180386054
1605510969 1985802816 27464898
3545871802 2267467733 385725819
1580307385 1113809296 8335179
2267467733 4179194655 34953467
1588642564 52640953 16868405
768087626 69509358 314799711
2835042306 4002148814 177045841
320920516 1122144475 447167110
1082887337 670109144 443700152
3218018460 3543189544 156036618
1921732119 1569311585 321765324
1632975867 384309069 40704472
1526587489 425013541 53719896
3140697718 2802291105 77320742
1726321292 1891076909 94725907
3070918618 2732512005 69779100
1673680339 0 52640953
3374055078 3830332090 171816724
2755723853 2653193552 79318453
3012088147 3242981522 58830471
2363412697 3699226162 131105928
1821047199 2013267714 100684920
2302421200 3301811993 60991497
191375707 2113952634 129544809
3931597621 2879611847 363369675
2674904679 4214148122 80819174
water-to-light map:
3219102205 2181622520 201394006
920319894 2563844887 124975374
739491533 2383016526 180828361
653894144 112244681 85597389
3420496211 0 112244681
3657404452 197842070 151065180
2385949305 1028427888 284402820
3532740892 1312830708 124663560
379827855 754361599 274066289
0 374533744 379827855
1070921762 1437494268 744128252
1815050014 3237570341 372982025
2670352125 2688820261 548750080
1045295268 348907250 25626494
2188032039 3610552366 197917266
light-to-temperature map:
2153765789 597465407 100160624
2781845200 2181361650 40610317
667326513 1345068833 191904517
2473693610 3180449558 308151590
3613083869 2293229230 341401182
1062907936 2938916666 34067323
1451871003 2221971967 71257263
3954485051 4137063579 102141117
4192502901 3838513492 49627103
1389629967 2876675630 62241036
1593277643 2972983989 143397067
859231030 2634630412 203676906
4056626168 790528713 68145539
1523128266 2838307318 38368312
503645468 3488601148 84794865
1333867367 4239204696 55762600
2902105909 1961894500 219467150
3268371481 858674252 266627384
2253926413 1125301636 219767197
4124771707 3888140595 67731194
1159014133 3663660258 174853234
3121573059 1536973350 56534177
4242130004 1593507527 52837292
3534998865 697626031 78085004
1096975259 503645468 62038874
588440333 3116381056 64068502
2052224391 3955871789 101541398
3178107236 3573396013 90264245
1736674710 1646344819 315549681
1561496578 565684342 31781065
2822455517 4057413187 79650392
652508835 775711035 14817678
temperature-to-humidity map:
539306376 906765326 12587914
0 164719538 374586838
3299714596 2417002864 137882274
3574681727 1862289721 10695948
1377359247 1111480860 147188226
2546515862 3738486436 38563842
2519543212 3564238204 26972650
1619134727 3777050278 31686173
551894290 728868054 177897272
3834998050 3919246788 238635651
729791562 919353240 625999
1524547473 3627710187 94587254
2399595894 3277935618 48769514
1340859914 3591210854 36499333
2585079704 2011159197 185411491
3723551203 3452791357 111446847
2895131743 2873352765 404582853
374586838 0 164719538
1776907125 1258669086 373340162
2881001532 2859222554 14130211
2217932998 2606381854 181662896
2166436282 2554885138 51496716
2448365408 2788044750 71177804
1650820900 3326705132 126086225
1110579441 1632009248 230280473
3437596870 4157882439 137084857
730417561 539306376 189561678
4294065877 1110579441 901419
2150247287 3722297441 16188995
2770491195 3808736451 110510337
3585377675 1872985669 138173528
4073633701 2196570688 220432176
humidity-to-location map:
3656475570 3037182697 7397903
682722270 547529272 780546181
266636474 1328075453 316323944
1591860664 3642496089 50700992
1642561656 266636474 280892798
1923454454 1644399397 1264527167
3979139381 3408096655 6045369
3663873473 4002979627 291987669
3955861142 3208017899 23278239
582960418 3414142024 99761852
3187981621 3231296138 176800517
3364782138 3044580600 163437299
1463268451 3513903876 128592213
3528219437 2908926564 128256133
4175159701 3693197081 119807595
3985184750 3813004676 189974951
""".trimIndent() | 0 | Kotlin | 0 | 0 | 660d1a5733dd533aff822f0e10166282b8e4bed9 | 10,260 | AOC2023 | Creative Commons Zero v1.0 Universal |
src/Day09.kt | petoS6 | 573,018,212 | false | {"Kotlin": 14258} | import java.lang.Math.abs
import kotlin.math.sign
data class P(val x: Int, val y: Int)
private fun P.isCloseTo(other: P) =
(x == other.x && y == other.y) ||
(x == other.x + 1 && y == other.y) ||
(x == other.x - 1 && y == other.y) ||
(x == other.x && y == other.y + 1) ||
(x == other.x && y == other.y - 1) ||
(x == other.x - 1 && y == other.y - 1) ||
(x == other.x + 1 && y == other.y + 1) ||
(x == other.x - 1 && y == other.y + 1) ||
(x == other.x + 1 && y == other.y - 1)
fun main() {
fun part1(lines: List<String>): Int {
val points = mutableListOf<P>()
points.add(P(0, 4))
var h = P(0, 4)
var t = P(0, 4)
lines.forEach { line ->
val splitted = line.split(" ")
val direction = splitted[0]
val count = splitted[1].toInt()
repeat(count) {
when(direction) {
"R" -> {
h = h.copy(x = h.x + 1)
if (t.isCloseTo(h).not()) t = h.copy(x = h.x - 1)
}
"L" -> {
h = h.copy(x = h.x - 1)
if (t.isCloseTo(h).not()) t = h.copy(x = h.x + 1)
}
"U" -> {
h = h.copy(y = h.y - 1)
if (t.isCloseTo(h).not()) t = h.copy(y = h.y + 1)
}
"D" -> {
h = h.copy(y = h.y + 1)
if (t.isCloseTo(h).not()) t = h.copy(y = h.y - 1)
}
}
points.add(t)
}
}
return points.distinct().size
}
fun part2(lines: List<String>) = rope(lines, 10)
val testInput = readInput("Day09.txt")
println(part1(testInput))
println(part2(testInput))
}
fun move(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> =
if(abs(head.first - tail.first) > 1 || abs(head.second - tail.second) > 1) {
val tailX = if (head.first == tail.first) 0 else (head.first - tail.first).sign
val tailY = if (head.second == tail.second) 0 else (head.second - tail.second).sign
tail.first + tailX to tail.second + tailY
} else tail
fun rope(lines: List<String>, length: Int) : Int {
val rope = Array(length) { 0 to 0}
val tailVisited = mutableSetOf<Pair<Int, Int>>()
tailVisited.add(rope.last())
for (instr in lines) {
val (dir: String, dist: String) = instr.split(" ")
val step = when (dir) {
"R" -> 1 to 0
"L" -> -1 to 0
"U" -> 0 to 1
"D" -> 0 to -1
else -> error("Unknown")
}
repeat(dist.toInt()) {
rope[0] = rope[0].first + step.first to rope[0].second + step.second
for (i in 0 until rope.lastIndex) {
rope[i + 1] = move(rope[i], rope[i+1])
}
tailVisited += rope.last()
}
}
return tailVisited.size
} | 0 | Kotlin | 0 | 0 | 40bd094155e664a89892400aaf8ba8505fdd1986 | 2,686 | kotlin-aoc-2022 | Apache License 2.0 |
src/Day02.kt | Maririri | 572,844,816 | false | null | fun main() {
// A = X = 1 for Rock, B = Y = 2 for Paper, and C = Z = 3 for Scissors
// 0 - you lost, 3 - draw, and 6 - you won
// A - X(1) = 1 + 3 = 4
// A - Y(2) = 2 + 6 = 8
// A - Z(3) = 3 + 0 = 3
// B - X(1) = 1 + 0 = 1
// B - Y(2) = 2 + 3 = 5
// B - Z(3) = 3 + 6 = 9
// C + X(1) = 1 + 6 = 7
// C + Y(2) = 2 + 0 = 2
// C + Z(3) = 3 + 3 = 6
fun part1(input: List<String>): Int {
val rules = mapOf(
"A X" to 4,
"A Y" to 8,
"A Z" to 3,
"B X" to 1,
"B Y" to 5,
"B Z" to 9,
"C X" to 7,
"C Y" to 2,
"C Z" to 6,
)
return input.sumOf { rules[it]!! }
}
// A for Rock, B for Paper, and C for Scissors
// X = 0 - you lost, Y = 3 - draw, and Z = 6 - you won
// A - X(0) = 0 + 3 = 3
// A - Y(3) = 3 + 1 = 4
// A - Z(6) = 6 + 2 = 8
// B - X(0) = 0 + 1 = 1
// B - Y(3) = 3 + 2 = 5
// B - Z(6) = 6 + 3 = 9
// C + X(0) = 0 + 2 = 2
// C + Y(3) = 3 + 3 = 6
// C + Z(6) = 6 + 1 = 7
fun part2(input: List<String>): Int {
val rules = mapOf(
"A X" to 3,
"A Y" to 4,
"A Z" to 8,
"B X" to 1,
"B Y" to 5,
"B Z" to 9,
"C X" to 2,
"C Y" to 6,
"C Z" to 7,
)
return input.sumOf { rules[it]!! }
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
val input2 = readInput("Day02")
println(part1(input))
println(part2(input2))
}
| 0 | Kotlin | 0 | 0 | ffda30a2c538ef1cb1e15cac14d424f807727769 | 1,678 | AdventOfCode2022 | Apache License 2.0 |
src/Day03.kt | jsebasct | 572,954,137 | false | {"Kotlin": 29119} |
fun main() {
fun getPriority(letter: Char): Int {
return if (letter.isLowerCase()) {
val range = 'a'..'z'
val res = range.indexOfFirst { letter == it }
res + 1
} else {
val range = 'A'..'Z'
val res = range.indexOfFirst { letter == it }
res + 27
}
}
fun getCompartments(rucksack: String): Pair<String, String> {
val endIndex = rucksack.length/2
val first = rucksack.substring(0, endIndex)
// println("first: $first")
val second = rucksack.substring(endIndex, rucksack.length)
// println("second: $second")
return first to second
}
fun getFoundLetter(compartments: Pair<String, String>): Char {
var foundLetter = 'X'
for (letter in compartments.first) {
for (letter2 in compartments.second) {
if (letter == letter2) {
foundLetter = letter
break
}
}
}
return foundLetter
}
fun part31(input: List<String>): Int {
val priorities = input.map { rucksack ->
val comps = getCompartments(rucksack)
val foundLetter = getFoundLetter(comps)
println(foundLetter)
getPriority(foundLetter)
}
println(priorities)
val sum = priorities.fold(0) { sum, p -> sum + p}
return sum
}
fun part32(input: List<String>): Int {
val commonLetters = mutableListOf<Char>()
for (index in 0..input.lastIndex step 3) {
println("index: $index")
val v1 = input[index]
val v2 = input[index+1]
val v3 = input[index+2]
//encontrar commun
var commonLetter = 'X'
for (letter in v1) {
if (letter in v2 && letter in v3) {
commonLetter = letter
break
}
}
println("commonLetter $index: $commonLetter")
commonLetters.add(commonLetter)
}
val res = commonLetters.map { getPriority(it) }.sum()
return res
// val priorities = input.map { rucksack ->
// val comps = getCompartments(rucksack)
// val foundLetter = getFoundLetter(comps)
// println(foundLetter)
// getPriority(foundLetter)
// }
//
// println(priorities)
//
// val sum = priorities.fold(0) { sum, p -> sum + p}
// return sum
// return input.size
}
// val resa = getPriority('Z')
// println("priority a: $resa")
val input = readInput("Day03_test")
println("total: ${part31(input)}")
println("Part two")
println("total parte 2: ${part32(input)}")
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day02_test")
// check(part2(testInput) == 45000)
}
| 0 | Kotlin | 0 | 0 | c4a587d9d98d02b9520a9697d6fc269509b32220 | 2,977 | aoc2022 | Apache License 2.0 |
src/Day02.kt | aaronbush | 571,776,335 | false | {"Kotlin": 34359} | sealed class RpsPlay(val points: Int) {
companion object {
fun of(s: String): RpsPlay {
return when (s) {
"A" -> ROCK
"X" -> ROCK
"B" -> PAPER
"Y" -> PAPER
"C" -> SCISSORS
"Z" -> SCISSORS
else -> throw IllegalArgumentException("unknown")
}
}
}
}
object ROCK : RpsPlay(1)
object PAPER : RpsPlay(2)
object SCISSORS : RpsPlay(3)
enum class RPS_RESULT {
WIN, LOSE, DRAW
}
operator fun RpsPlay.compareTo(other: RpsPlay): Int {
return if (other == this) {
0
} else {
when (this) {
ROCK -> if (other == PAPER) -1 else 1
PAPER -> if (other == SCISSORS) -1 else 1
SCISSORS -> if (other == ROCK) -1 else 1
}
}
}
fun main() {
fun String.asResult(): RPS_RESULT {
return when (this) {
"X" -> RPS_RESULT.LOSE
"Y" -> RPS_RESULT.DRAW
"Z" -> RPS_RESULT.WIN
else -> throw IllegalArgumentException(this)
}
}
fun getScores(results: List<Pair<RpsPlay, RPS_RESULT>>) = results.map {
it.first.points to
when (it.second) {
RPS_RESULT.WIN -> 6
RPS_RESULT.DRAW -> 3
else -> 0
}
}
fun part1(input: List<String>): Int {
val plays = input.map {
val plays = it.split(" ")
RpsPlay.of(plays[0]) to RpsPlay.of(plays[1])
}
// println(plays)
val results = plays.map {
it.second to if (it.first == it.second)
RPS_RESULT.DRAW
else if (it.first < it.second)
RPS_RESULT.WIN
else
RPS_RESULT.LOSE
}
// println(results)
val scores = getScores(results)
// println(scores)
return scores.sumOf { it.first + it.second }
}
fun part2(input: List<String>): Int {
val expects = input.map {
val plays = it.split(" ")
RpsPlay.of(plays[0]) to plays[1].asResult()
}
val results = expects.map {
when (it.second) {
RPS_RESULT.DRAW -> it.first
RPS_RESULT.LOSE -> {
when (it.first) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
RPS_RESULT.WIN -> {
when (it.first) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
} to it.second
}
val scores = getScores(results)
// println(scores)
return scores.sumOf { it.first + it.second }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d76106244dc7894967cb8ded52387bc4fcadbcde | 3,181 | aoc-2022-kotlin | Apache License 2.0 |
src/Day14.kt | armandmgt | 573,595,523 | false | {"Kotlin": 47774} | import java.awt.Point
fun main() {
val pointPattern = Regex("(\\d+),(\\d+)")
class Line(def: String) {
val points: List<Point>
init {
this.points = def.split(" -> ").map {
val (x, y) = pointPattern.find(it)!!.destructured
Point(x.toInt(), y.toInt())
}
}
fun contains(point: Point): Boolean {
return points.windowed(2).any { (start, end) ->
when {
start.y == end.y -> point.y == start.y && (minOf(start.x, end.x)..maxOf(start.x, end.x)).contains(point.x)
start.x == end.x -> point.x == start.x && (minOf(start.y, end.y)..maxOf(start.y, end.y)).contains(point.y)
else -> throw IllegalArgumentException("Line is neither vertical nor horizontal")
}
}
}
}
fun newGrainPos(grain: Point, grains: MutableList<Point>, lines: List<Line>): Point {
return listOf(Point(grain.x, grain.y + 1), Point(grain.x - 1, grain.y + 1), Point(grain.x + 1, grain.y + 1)).firstOrNull {
!grains.contains(it) && lines.none { line -> line.contains(it) }
} ?: grain
}
fun part1(input: List<String>): Int {
val lines = input.map { Line(it) }
val lowestY = lines.maxOf { it.points.maxOf { p -> p.y } }
val grains = mutableListOf<Point>()
while (true) {
var grain = Point(500, 0)
do {
val prevPos = grain
grain = newGrainPos(grain, grains, lines)
} while (grain.y != prevPos.y && grain.y < lowestY)
if (grain.y >= lowestY) return grains.size
grains.add(grain)
}
}
fun part2(input: List<String>): Int {
val lines = input.map { Line(it) }
val lowestY = lines.maxOf { it.points.maxOf { p -> p.y } }
val grains = mutableListOf<Point>()
while (true) {
var grain = Point(500, 0)
do {
val prevPos = grain
grain = newGrainPos(grain, grains, lines)
} while (grain.y != prevPos.y && grain.y < lowestY + 1)
if (grain == Point(500, 0)) return grains.size + 1
grains.add(grain)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("resources/Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("resources/Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 0d63a5974dd65a88e99a70e04243512a8f286145 | 2,579 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2015/Day09.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2015
import ru.timakden.aoc.util.Permutations
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 9: All in a Single Night](https://adventofcode.com/2015/day/9).
*/
object Day09 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2015/Day09")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
var result = Int.MAX_VALUE
val locations = mutableSetOf<String>()
val distances = mutableMapOf<String, Int>()
input.apply {
mapTo(locations) { it.substringBefore(" to ") }
mapTo(locations) { it.substringAfter(" to ").substringBefore(" = ") }
associateByTo(distances,
{ it.substringBefore(" = ").replace(" to ", "") },
{ it.substringAfter(" = ").toInt() })
associateByTo(distances,
{ it.substringAfter(" to ").substringBefore(" = ") + it.substringBefore(" to ") },
{ it.substringAfter(" = ").toInt() })
}
val routes = Permutations.of(locations)
routes.forEach { route ->
val list = route.toList()
val length = list.indices
.filter { it != list.lastIndex }
.sumOf { distances[list[it] + list[it + 1]] ?: 0 }
if (length < result) result = length
}
return result
}
fun part2(input: List<String>): Int {
var result = Int.MIN_VALUE
val locations = mutableSetOf<String>()
val distances = mutableMapOf<String, Int>()
input.apply {
mapTo(locations) { it.substringBefore(" to ") }
mapTo(locations) { it.substringAfter(" to ").substringBefore(" = ") }
associateByTo(distances,
{ it.substringBefore(" = ").replace(" to ", "") },
{ it.substringAfter(" = ").toInt() })
associateByTo(distances,
{ it.substringAfter(" to ").substringBefore(" = ") + it.substringBefore(" to ") },
{ it.substringAfter(" = ").toInt() })
}
val routes = Permutations.of(locations)
routes.forEach { route ->
val list = route.toList()
val length = list.indices
.filter { it != list.lastIndex }
.sumOf { distances[list[it] + list[it + 1]] ?: 0 }
if (length > result) result = length
}
return result
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 2,614 | advent-of-code | MIT License |
jvm/src/main/kotlin/io/prfxn/aoc2021/day23.kt | prfxn | 435,386,161 | false | {"Kotlin": 72820, "Python": 362} | // Amphipod (https://adventofcode.com/2021/day/23)
package io.prfxn.aoc2021
fun main() {
val pods = ('A'..'D').toList()
val energiesByPod = pods.asSequence().zip(generateSequence(1) { it * 10 }).toMap()
fun readInput(lines: Sequence<String>): Map<CP, Char> {
val coi = pods.toSet() + '.'
return lines
.flatMapIndexed { r, line ->
line.mapIndexedNotNull { c, char ->
if (char in coi)
(r to c) to char
else null
}
}
.toMap()
}
fun getRoomCellsByPod(state: Map<CP, Char>) =
pods.asSequence().zip(
state.keys
.groupBy { (_, c) -> c }
.asSequence()
.mapNotNull { (_, cells) ->
if (cells.size >= 3)
cells.sortedBy { it.first }.drop(1)
else null
}
).toMap()
fun getCellGroups(state: Map<CP, Char>, roomCellsByPod: Map<Char, List<CP>>): List<Set<CP>> {
val roomCells = roomCellsByPod.values.flatten().toSet()
val entrywayCells =
state.keys.filter { (r, c) -> (r to c) !in roomCells && ((r + 1) to c) in roomCells }.toSet()
val hallwayCells =
state.keys.filter { it !in roomCells && it !in entrywayCells }.toSet()
return listOf(
roomCells,
entrywayCells,
hallwayCells
)
}
fun printState(state: Map<CP, Char> ) {
val roomCellsByPod = getRoomCellsByPod(state)
println("#############")
println("#${(1..11).map { state[1 to it] }.joinToString("")}#")
println("###" + pods.map { state[roomCellsByPod[it]!![0]] }.joinToString("#") + "###")
(1 until roomCellsByPod.values.first().size).forEach { r ->
println(" #" + pods.map { state[roomCellsByPod[it]!![r]] }.joinToString("#") + "#")
}
println(" #########")
}
fun getPath(state: Map<CP, Char>, start: CP, end: CP): List<CP>? {
val (r1, c1) = start
val (r2, c2) = end
val rr = if (r1 > r2) r1.downTo(r2) else (r1..r2)
val cr = if (c1 > c2) c1.downTo(c2) else (c1..c2)
return sequenceOf(
rr.filter { it != r2 }.map { r -> r to c1 } + cr.map { c -> r2 to c },
cr.filter { it != c2 }.map { c -> r1 to c } + rr.map { r -> r to c2 }
).find { p -> p.drop(1).all { cell -> state[cell] == '.' } }
}
fun getLeastEnergy(startState: Map<CP, Char>, endState: Map<CP, Char>): Int {
val roomCellsByPod = getRoomCellsByPod(startState)
val (roomCells, entrywayCells, hallwayCells) = getCellGroups(startState, roomCellsByPod)
fun allowRoomExit(state: Map<CP, Char>, cell: CP): Boolean {
val pod = state[cell]!!
val podRoomCells = roomCellsByPod[pod]!!
return cell !in podRoomCells ||
podRoomCells.filter { (r, _) -> r > cell.first }.any { state[it] != pod }
}
fun allowRoomEntry(state: Map<CP, Char>, cell: CP, pod: Char): Boolean {
val podRoomCells = roomCellsByPod[pod]!!
return cell in podRoomCells &&
podRoomCells.filter { (r, _) -> r > cell.first }.all { state[it] == pod }
}
val energyAndPrevOf =
PriorityMap(sequenceOf(startState to (0 to startState))) { (a, _), (b, _) -> a - b }
val explored = mutableSetOf<Map<CP, Char>>()
// get unexplored next states and corresponding transition energies
fun getNextFrom(state: Map<CP, Char>): Sequence<Pair<Map<CP, Char>, Int>> =
(
// region room to room
roomCells.asSequence()
.filter { state[it] in pods && allowRoomExit(state, it) }
.flatMap { start ->
val pod = state[start]!!
roomCells.asSequence().filter { state[it] == '.' && allowRoomEntry(state, it, pod) }
.map { end -> Triple(pod, start, end) }
} /* endregion */ +
// region hallway to room
hallwayCells.asSequence()
.filter { state[it] in pods }
.flatMap { start ->
val pod = state[start]!!
roomCells.asSequence()
.filter { state[it] == '.' && allowRoomEntry(state, it, pod) }
.map { end -> Triple(pod, start, end) }
} /* endregion */ +
// region room to hallway
roomCells.asSequence()
.filter { state[it] in pods && allowRoomExit(state, it) }
.flatMap { start ->
val pod = state[start]!!
hallwayCells.asSequence()
.filter { state[it] == '.' }
.map { end -> Triple(pod, start, end) }
} /* endregion */
)
.mapNotNull { (pod, start, end) ->
getPath(state, start, end)?.let { path ->
(state + mapOf(start to '.', end to pod))
.takeIf { it !in explored }
?.let { nextState ->
nextState to (path.size - 1) * energiesByPod[pod]!!
}
}
}
return generateSequence {
if (endState in explored) null
else {
val (here, energyAndPrev) = energyAndPrevOf.extract()
val (energy, _) = energyAndPrev
getNextFrom(here).forEach { (nextState, transitionEnergy) ->
val nextEnergy = energy + transitionEnergy
if (nextState !in energyAndPrevOf || nextEnergy < energyAndPrevOf[nextState]!!.first)
energyAndPrevOf[nextState] = nextEnergy to here
}
explored.add(here)
energy
}
}.last()
}
fun getEndState(state: Map<CP, Char>): Map<CP, Char> {
val roomCellsByPod = getRoomCellsByPod(state)
val (_, entrywayCells, hallwayCells) = getCellGroups(state, roomCellsByPod)
return (
(hallwayCells.asSequence() + entrywayCells.asSequence())
.map { it to '.' } +
roomCellsByPod.asSequence()
.flatMap { (pod, cells) -> cells.asSequence().map { cell -> cell to pod } }
).toMap()
}
// answer 1
val startState = textResourceReader("input/23.txt").useLines { lines -> readInput(lines) }
val endState = getEndState(startState)
println(getLeastEnergy(startState, endState))
// answer 2
fun getAltStartState(startState: Map<CP, Char>): Map<CP, Char> =
startState +
sequenceOf("DCBA", "DBAC")
.flatMapIndexed { r, str ->
str.mapIndexed { c, char -> (r to c) to char }
}
.map { (cell, char) ->
val (r, c) = cell
(r + 3 to c * 2 + 3) to char
}
.toMap() +
startState.keys.asSequence()
.filter { (r, _) -> r == 3 }
.map { (r, c) -> (r + 2 to c) to startState[r to c]!! }
.toMap()
val altStateState = getAltStartState(startState)
val altEndState = getEndState(altStateState)
println(getLeastEnergy(altStateState, altEndState))
}
/** output
13455
43567
*/
| 0 | Kotlin | 0 | 0 | 148938cab8656d3fbfdfe6c68256fa5ba3b47b90 | 7,752 | aoc2021 | MIT License |
src/day12/Day12.kt | MaxBeauchemin | 573,094,480 | false | {"Kotlin": 60619} | package day12
import readInput
import java.lang.Math.abs
import java.util.*
class Graph {
val nodes: MutableSet<Node> = HashSet()
fun findByKey(key: String) = nodes.find { it.key == key }!!
}
class Node(
val key: String,
val elevation: Int,
val isStart: Boolean,
val isEnd: Boolean
) {
var shortestPath: List<Node> = LinkedList()
var distance = Int.MAX_VALUE
var adjacentNodes: MutableMap<Node, Int> = HashMap()
// Reversed Direction (End to Start)
fun addNeighborConditionally(neighbor: Node) {
if (abs(this.elevation - neighbor.elevation) <= 1) {
this.adjacentNodes.put(neighbor, 1)
neighbor.adjacentNodes.put(this, 1)
} else if (neighbor.elevation < this.elevation) {
neighbor.adjacentNodes.put(this, 1)
} else {
this.adjacentNodes.put(neighbor, 1)
}
}
}
fun calculateShortestPathFromSource(source: Node) {
source.distance = 0
val settledNodes: MutableSet<Node> = HashSet()
val unsettledNodes: MutableSet<Node> = HashSet()
unsettledNodes.add(source)
while (unsettledNodes.size != 0) {
val currentNode: Node = getLowestDistanceNode(unsettledNodes)
unsettledNodes.remove(currentNode)
currentNode.adjacentNodes.forEach { (t, u) ->
if (!settledNodes.contains(t)) {
calculateMinimumDistance(t, u, currentNode)
unsettledNodes.add(t)
}
}
settledNodes.add(currentNode)
}
}
fun getLowestDistanceNode(unsettledNodes: Set<Node>): Node {
var lowestDistanceNode: Node? = null
var lowestDistance = Int.MAX_VALUE
for (node in unsettledNodes) {
val nodeDistance = node.distance
if (nodeDistance < lowestDistance) {
lowestDistance = nodeDistance
lowestDistanceNode = node
}
}
return lowestDistanceNode!!
}
fun calculateMinimumDistance(evaluationNode: Node, edgeWeigh: Int, sourceNode: Node) {
val sourceDistance = sourceNode.distance
if (sourceDistance + edgeWeigh < evaluationNode.distance) {
evaluationNode.distance = sourceDistance + edgeWeigh
val shortestPath = LinkedList(sourceNode.shortestPath)
shortestPath.add(sourceNode)
evaluationNode.shortestPath = shortestPath
}
}
fun main() {
fun parse(input: List<String>): Graph {
val graph = Graph()
// Top -> Down
// Left -> Right
input.forEachIndexed { o, row ->
row.forEachIndexed { i, char ->
val isStart = char == 'S'
val isEnd = char == 'E'
val elevation = if (isStart) 0 else if (isEnd) 25 else char.code - 97
val currNode = Node("$o $i", elevation, isStart, isEnd)
graph.nodes.add(currNode)
// Check Neighbor Up
if (o > 0) {
graph.findByKey("${o - 1} $i").also { neighbor ->
currNode.addNeighborConditionally(neighbor)
}
}
// Check Neighbor Left
if (i > 0) {
graph.findByKey("$o ${i - 1}").also { neighbor ->
currNode.addNeighborConditionally(neighbor)
}
}
}
}
return graph
}
fun part1(input: List<String>): Int {
val graph = parse(input)
calculateShortestPathFromSource(graph.nodes.find { it.isEnd }!!)
return graph.nodes.find { it.isStart }!!.distance
}
fun part2(input: List<String>): Int {
val graph = parse(input)
calculateShortestPathFromSource(graph.nodes.find { it.isEnd }!!)
return graph.nodes.filter { it.elevation == 0 }.minOf { it.distance }
}
val testInput = readInput("Day12_test")
val input = readInput("Day12")
println("Part 1 [Test] : ${part1(testInput)}")
check(part1(testInput) == 31)
println("Part 1 [Real] : ${part1(input)}")
println("Part 2 [Test] : ${part2(testInput)}")
check(part2(testInput) == 29)
println("Part 2 [Real] : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 38018d252183bd6b64095a8c9f2920e900863a79 | 4,177 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | bjornchaudron | 574,072,387 | false | {"Kotlin": 18699} | fun main() {
fun part1(input: List<String>): Int {
val grid = input.flatMapIndexed { y, line -> line.mapIndexed { x, c -> Point(x, y) to c } }.toMap()
return findShortestPath(grid, goal = 'S')
}
fun part2(input: List<String>): Int {
val grid = input.flatMapIndexed { y, line -> line.mapIndexed { x, c -> Point(x, y) to c } }.toMap()
return findShortestPath(grid, goal = 'a')
}
// test if implementation meets criteria from the description, like:
val day = "12"
val testInput = readLines("Day${day}_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readLines("Day$day")
println(part1(input))
println(part2(input))
}
// Breadth-first search
fun findShortestPath(grid: Grid<Char>, goal: Char): Int {
val start = grid.entries.first { it.value == 'E' }.key
val distances = grid.keys.associateWith { Int.MAX_VALUE }.toMutableMap()
distances[start] = 0
val q = ArrayDeque<Point>()
q.add(start)
while (q.isNotEmpty()) {
val current = q.removeFirst()
current.validNeighbours(grid)
.forEach { neighbour ->
val newDistance = distances[current]!! + 1
if (grid[neighbour] == goal) return newDistance
if (newDistance < distances[neighbour]!!) {
distances[neighbour] = newDistance
q.addLast(neighbour)
}
}
}
error("No path found")
}
private fun Point.validNeighbours(grid: Grid<Char>) =
neighbours.filter { it in grid && grid[it]!!.elevation - grid[this]!!.elevation >= -1
}
private val Char.elevation: Int
get() = when (this) {
'S' -> 'a'.code
'E' -> 'z'.code
else -> this.code
} | 0 | Kotlin | 0 | 0 | f714364698966450eff7983fb3fda3a300cfdef8 | 1,796 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | msernheim | 573,937,826 | false | {"Kotlin": 32820} | fun main() {
fun findFirstOrNull(input: List<String>, target: Char): Coord? {
for (i in input.indices) {
for (j in input[i].indices) {
when (input[i][j]) {
target -> return Coord(j, i)
}
}
}
return null
}
fun withinReach(current: Char, next: Char): Boolean {
return current.code >= next.code - 1
}
fun allowedMove(current: Char, next: Char): Boolean {
return when (current) {
'S' -> next == 'a' || next == 'b'
'y' -> withinReach(current, next) || next == 'E'
'z' -> withinReach(current, next) || next == 'E'
else -> next != 'E' && withinReach(current, next)
}
}
fun getNeighbours(path: List<Coord>, input: List<String>): List<Coord> {
val current = path.last()
val neighbors = listOf(
Coord(current.X - 1, current.Y),
Coord(current.X + 1, current.Y),
Coord(current.X, current.Y - 1),
Coord(current.X, current.Y + 1)
)
return neighbors.filter { coord ->
!path.contains(coord) &&
coord.X >= 0 && coord.X < input[current.Y].length && //check X inside grid
coord.Y >= 0 && coord.Y < input.size && //check Y inside grid
allowedMove(input[current.Y][current.X], input[coord.Y][coord.X]) //check altitude
}.toList()
}
fun anyPathReachedGoal(paths: MutableList<List<Coord>>, end: Coord): Boolean {
paths.forEach { path -> if (path.last() == end) return true }
return false
}
fun getShortestPath(start: Coord, end: Coord, input: List<String>): Int {
var paths = mutableListOf<List<Coord>>()
var toRemove = mutableListOf<List<Coord>>()
var toAdd = mutableListOf<List<Coord>>()
paths.add(mutableListOf(start))
while (paths.isNotEmpty() && !anyPathReachedGoal(paths, end)) {
paths.forEach { path ->
val current = path.last()
val neighbours = getNeighbours(
path,
input
)
if (neighbours.isNotEmpty()) {
neighbours.forEach { coord -> toAdd.add(path.plus(coord)) }
}
toRemove.add(path)
}
paths.removeAll(toRemove)
paths.addAll(toAdd)
paths = paths.distinctBy { coords -> coords.last() }.toMutableList()
toRemove.clear()
toAdd.clear()
}
return if (paths.isNotEmpty()) paths.filter { path -> path.last() == end }.sortedBy { path -> path.size }.first().size - 1 else -1
}
fun part1(input: List<String>): Int {
val waypoints = Pair(findFirstOrNull(input, 'S'), findFirstOrNull(input, 'E'))
return getShortestPath(waypoints.first!!, waypoints.second!!, input)
}
fun findAllStarts(input: List<String>): List<Coord> {
val starts = mutableListOf<Coord>()
input.forEachIndexed { y, row ->
row.forEachIndexed { x, c ->
if (c == 'a' || c == 'S') starts.add(Coord(x, y))
}
}
return starts
}
fun part2(input: List<String>): Int {
val starts = findAllStarts(input)
val end = findFirstOrNull(input, 'E')!!
return starts.map { start -> getShortestPath(start, end, input) }.filter { i -> i > 0 }.minOf { it }
}
val input = readInput("Day12")
val part1 = part1(input)
val part2 = part2(input)
println("Result part1: $part1")
println("Result part2: $part2")
}
| 0 | Kotlin | 0 | 3 | 54cfa08a65cc039a45a51696e11b22e94293cc5b | 3,687 | AoC2022 | Apache License 2.0 |
src/day11/Day11.kt | PoisonedYouth | 571,927,632 | false | {"Kotlin": 27144} | package day11
import readInput
data class Monkey(
val index: Int,
val items: MutableList<Long>,
val worryOperation: (Long) -> Long,
val throwOperation: (Long) -> Int,
val divisor: Int,
var inspections: Long = 0
) {
companion object {
fun from(input: List<String>): Monkey {
val index = input[0].substringAfter("Monkey ").first().digitToInt()
val items = input[1].substringAfter(" Starting items: ").split(", ").map { it.toLong() }.toMutableList()
val (_, operator, operationNumber) = input[2].substringAfter(" Operation: new = ").split(" ")
fun worryOperation(value: Long): Long {
val operationNumberCalculated = operationNumber.toLongOrNull() ?: value
return when (operator) {
"+" -> value + operationNumberCalculated
"*" -> value * operationNumberCalculated
else -> error("Invalid input!")
}
}
val test = input[3].substringAfter(" Test: divisible by ").toLong()
val success = input[4].substringAfter(" If true: throw to monkey ").toInt()
val fail = input[5].substringAfter(" If false: throw to monkey ").toInt()
fun throwOperation(value: Long): Int {
return if (value % test == 0L) {
success
} else {
fail
}
}
return Monkey(
index = index,
items = items,
worryOperation = ::worryOperation,
throwOperation = ::throwOperation,
divisor = test.toInt()
)
}
}
}
fun main() {
fun calculateInspectionProduct(monkeys: List<Monkey>, iterations: Int, reduceOperation: (Long) -> Long): Long {
repeat(iterations) {
monkeys.forEach { monkey ->
repeat(monkey.items.size) {
monkey.inspections++
val item = monkey.items.removeFirst()
val result = reduceOperation(monkey.worryOperation(item))
val destination = monkey.throwOperation(result)
monkeys[destination].apply {
this.items += result
}
}
}
}
return monkeys.sortedByDescending { it.inspections }.let { it[0].inspections * it[1].inspections }
}
fun part1(input: List<String>): Long {
val monkeys = input.chunked(7).map { Monkey.from(it) }.toMutableList()
return calculateInspectionProduct(
monkeys = monkeys,
iterations = 20,
reduceOperation = {
it / 3
}
)
}
fun part2(input: List<String>): Long {
val monkeys = input.chunked(7).map { Monkey.from(it) }.toMutableList()
val reduce = monkeys.map { it.divisor }.reduce { acc, i -> acc * i }
return calculateInspectionProduct(
monkeys = monkeys,
iterations = 10000,
reduceOperation = {
it % reduce
}
)
}
val input = readInput("day11/Day11")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 1 | 0 | dbcb627e693339170ba344847b610f32429f93d1 | 3,301 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day02.kt | rweekers | 573,305,041 | false | {"Kotlin": 38747} | fun main() {
fun part1(input: List<String>): Int {
return input
.asSequence()
.map { it.split(" ") }
.map { Pair(RockPaperScissors.fromABCSyntax(it[0]), RockPaperScissors.fromXYZSyntax(it[1])) }
.map { it.second.totalScore(it.first) }
.sum()
}
fun part2(input: List<String>): Int {
return input
.asSequence()
.map { it.split(" ") }
.map { Pair(RockPaperScissors.fromABCSyntax(it.first()), it[1]) }
.map { Pair(it.first, it.first.determineMove(it.second)) }
.map { it.second.totalScore(it.first) }
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class RockPaperScissors(private val s: String, private val s1: String, private val worth: Int) {
ROCK("A", "X", 1),
PAPER("B", "Y", 2),
SCISSORS("C", "Z", 3);
private fun score(other: RockPaperScissors): Int {
if (this == other) {
return 3
}
if (winsFrom(other)) {
return 6
}
return 0
}
private fun winningMove(): RockPaperScissors {
return when (this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
private fun losingMove(): RockPaperScissors {
return when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
fun determineMove(shouldWin: String): RockPaperScissors {
return when (shouldWin) {
"X" -> this.losingMove()
"Y" -> this
"Z" -> this.winningMove()
else -> {
throw IllegalArgumentException()
}
}
}
private fun winsFrom(other: RockPaperScissors): Boolean {
return (this == ROCK && other == SCISSORS ||
this == PAPER && other == ROCK ||
this == SCISSORS && other == PAPER)
}
fun totalScore(other: RockPaperScissors): Int {
return score(other) + this.worth
}
companion object {
fun fromABCSyntax(s: String): RockPaperScissors {
return enumValues<RockPaperScissors>()
.first { it.s == s }
}
fun fromXYZSyntax(s: String): RockPaperScissors {
return enumValues<RockPaperScissors>()
.first { it.s1 == s }
}
}
}
| 0 | Kotlin | 0 | 1 | 276eae0afbc4fd9da596466e06866ae8a66c1807 | 2,656 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day3.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.InputParser
const val SYMBOL = -1
const val NOTHING = -2
const val GEAR = -3
object EngineSchematicParser : InputParser<List<MutableList<Int>>> {
override fun parse(input: String) = input.split("\n").map {
it.map { c ->
when {
c.isDigit() -> c.digitToInt()
c == '.' -> NOTHING
c == '*' -> GEAR
else -> SYMBOL
}
}.toMutableList()
}
}
fun main() {
aoc(EngineSchematicParser) {
puzzle { 2023 day 3 }
fun Int.isSymbol() = this in listOf(SYMBOL, GEAR)
fun MutableList<Int>.partNumber(previousLine: List<Int>, startIndex: Int, nextLine: List<Int>): Int {
var endIndex = startIndex
// find value
var value = ""
while (endIndex < size && get(endIndex) >= 0) {
value = "$value${get(endIndex)}"
this[endIndex] = NOTHING
endIndex++
}
// determine if it is a partnumber or not
val p1 = (startIndex - 1).coerceAtLeast(0)
val p2 = (endIndex).coerceAtMost(size - 1)
return if (previousLine.slice(p1..p2).any { it.isSymbol() }
|| slice(p1..p2).any { it.isSymbol() }
|| nextLine.slice(p1..p2).any { it.isSymbol() }) {
value.toInt()
} else {
0
}
}
part1 { input ->
val emptyLine = List(input.size) { NOTHING }
input.mapIndexed { y, line ->
line.mapIndexed { x, i ->
if (i > 0) {
line.partNumber(
previousLine = if (y == 0) emptyLine else input[y - 1],
startIndex = x,
nextLine = if (y == input.size - 1) emptyLine else input[y + 1]
)
} else 0
}.sum()
}.sum()
}
fun List<Int>.adjacentNumbers(startIndex: Int): List<Int> {
return ((startIndex - 1).coerceAtLeast(0) .. (startIndex + 1).coerceAtMost(size - 1)).mapNotNull {
if (get(it) >= 0) {
var range: IntRange = it..it
while (range.first > 0 && get(range.first - 1) >= 0) range = range.first - 1..range.last
while (range.last < size - 1 && get(range.last + 1) >= 0) range = range.first..range.last + 1
range
} else null
}
.toSet()
.map { slice(it).joinToString("").toInt() }
}
part2 { input ->
input.mapIndexed { y, line ->
line.mapIndexed { x, i ->
if (i == GEAR) {
buildList {
addAll(line.adjacentNumbers(x))
if (y > 0) addAll(input[y - 1].adjacentNumbers(x))
if (y < input.size - 1) addAll(input[y + 1].adjacentNumbers(x))
}
.takeIf { it.size == 2 }
?.let { it[0] * it[1] } ?: 0
} else 0
}.sum()
}.sum()
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 3,444 | aoc-2023 | The Unlicense |
src/Day02.kt | armatys | 573,477,313 | false | {"Kotlin": 4015} | fun main() {
fun part1(input: List<String>): Int {
return input.fold(0) { acc, line ->
val figures = line.split(" ", limit = 2).toPair(String::toFigure, String::toFigure)
acc + figures.matchScore()
}
}
fun part2(input: List<String>): Int {
return input.fold(0) { acc, line ->
val guide = line.split(" ", limit = 2)
.toPair(String::toFigure, String::toOutcome)
val figures = guide.first to guide.pickSecondFigure()
acc + figures.matchScore()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
private fun <T, U, W> List<T>.toPair(firstTransform: (T) -> U, secondTransform: (T) -> W): Pair<U, W> =
firstTransform(first()) to secondTransform(last())
private fun String.toFigure(): Figure = when (this) {
"A", "X" -> Figure.Rock
"B", "Y" -> Figure.Paper
"C", "Z" -> Figure.Scissors
else -> error("Unknown figure: $this")
}
private fun String.toOutcome(): Outcome = when (this) {
"X" -> Outcome.Loss
"Y" -> Outcome.Draw
"Z" -> Outcome.Win
else -> error("Unknown outcome: $this")
}
private infix fun Figure.against(other: Figure): Int {
if (this == other) return 3
return when (this) {
Figure.Rock -> if (other == Figure.Scissors) 6 else 0
Figure.Paper -> if (other == Figure.Rock) 6 else 0
Figure.Scissors -> if (other == Figure.Paper) 6 else 0
}
}
private fun Figure.shapeScore(): Int = when (this) {
Figure.Rock -> 1
Figure.Paper -> 2
Figure.Scissors -> 3
}
private fun Pair<Figure, Figure>.matchScore(): Int {
return (second against first) + second.shapeScore()
}
private fun Pair<Figure, Outcome>.pickSecondFigure(): Figure {
if (second == Outcome.Draw) return first
return when (first) {
Figure.Rock -> if (second == Outcome.Win) Figure.Paper else Figure.Scissors
Figure.Paper -> if (second == Outcome.Win) Figure.Scissors else Figure.Rock
Figure.Scissors -> if (second == Outcome.Win) Figure.Rock else Figure.Paper
}
}
private enum class Figure { Rock, Paper, Scissors }
private enum class Outcome { Loss, Draw, Win }
| 0 | Kotlin | 0 | 0 | 95e93f7e10cbcba06e2ef88c1785779fbaa7c90f | 2,405 | kotlin-aoc-2022 | Apache License 2.0 |
src/day5/Day05.kt | MatthewWaanders | 573,356,006 | false | null | package day5
import utils.readInput
import java.util.Stack
fun main() {
val testInput = readInput("Day05_test", "day5")
check(part1(testInput) == "CMZ")
val input = readInput("Day05", "day5")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): String {
val (stacks, moves) = parseInput(input)
moves.forEach {move -> repeat((1..move.first).count()) { stacks[move.third].push(stacks[move.second].pop()) } }
return parseStacksToOutput(stacks)
}
fun part2(input: List<String>): String {
val (stacks, moves) = parseInput(input)
moves.forEach {move -> (1..move.first).map { stacks[move.second].pop() }.reversed().forEach {stacks[move.third].push(it)} }
return parseStacksToOutput(stacks)
}
fun parseInput(input: List<String>): Pair<List<Stack<String>>, List<Triple<Int, Int, Int>>> {
val (stacksInput, movesInput) = input.fold(listOf<List<String>>(emptyList(), emptyList())) { acc, it -> if (it.startsWith("move")) listOf(acc[0], listOf(*(acc[1].toTypedArray()), it)) else if (it.trim().startsWith("[")) listOf(listOf(*(acc[0].toTypedArray()), it), acc[1]) else acc}
val stacks = parseStackInputToStacks(stacksInput.reversed().map { parseLineAsStackInput(it)})
val moves = parseMovesInputToMoves(movesInput)
return Pair(stacks, moves)
}
fun parseLineAsStackInput(input: String) =
input
.toList()
.chunked(4)
.map { it[1] }
.foldIndexed(emptyList<Pair<String, Int>>()) { index, acc, it -> if (it.isWhitespace()) acc else acc + Pair(it.toString(), index)}
fun parseStackInputToStacks(input: List<List<Pair<String, Int>>>) = List(input.first().maxOf { it.second } + 1) {Stack<String>()}.apply { input.forEach {line -> line.forEach { stackInput -> this[stackInput.second].add(stackInput.first) } } }
fun parseMovesInputToMoves(input: List<String>) = input.map { movesDescription -> movesDescription.split(" ").let { Triple(it[1].toInt(), it[3].toInt()-1, it[5].toInt()-1) } }
fun parseStacksToOutput(stacks: List<Stack<String>>) = stacks.joinToString("") { it.pop() } | 0 | Kotlin | 0 | 0 | f58c9377edbe6fc5d777fba55d07873aa7775f9f | 2,090 | aoc-2022 | Apache License 2.0 |
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day08.kt | JamJaws | 725,792,497 | false | {"Kotlin": 30656} | package com.jamjaws.adventofcode.xxiii.day
import com.jamjaws.adventofcode.xxiii.readInput
import java.math.BigInteger
class Day08 {
fun part1(text: List<String>): Long {
val path = text.first()
val nodes = parseNodes(text)
return getNumberOfStepsUntil("AAA", path, nodes) { node -> node == "ZZZ" }
}
private fun String.getNode(
lr: Char,
nodes: Map<String, Node>,
): String = nodes.getValue(this).let { if (lr == 'L') it.left else it.right }
fun part2(text: List<String>): Long {
val path = text.first()
val nodes = parseNodes(text)
val steps = nodes.keys.filter { it.endsWith('A') }
.map { getNumberOfStepsUntil(it, path, nodes) { node -> node.endsWith('Z') } }
return steps.map(BigInteger::valueOf)
.reduce { acc, bigInteger ->
acc.lcm(bigInteger)
}.toLong()
}
private fun parseNodes(text: List<String>) = text.drop(2)
.map { it.replace("[()]".toRegex(), "").split(" = ", ", ") }
.associateBy({ (key) -> key }) { (_, left, right) -> Node(left, right) }
private fun BigInteger.lcm(number: BigInteger): BigInteger = multiply(number).abs().divide(gcd(number))
private tailrec fun getNumberOfStepsUntil(
node: String,
path: String,
nodes: Map<String, Node>,
steps: Long = 0,
predicate: (String) -> Boolean,
): Long = if (predicate(node)) {
steps
} else {
getNumberOfStepsUntil(
node.getNode(path[(steps % path.length).toInt()], nodes),
path,
nodes,
steps + 1,
predicate
)
}
}
data class Node(val left: String, val right: String)
fun main() {
val answer1 = Day08().part1(readInput("Day08"))
println(answer1)
val answer2 = Day08().part2(readInput("Day08"))
println(answer2)
}
| 0 | Kotlin | 0 | 0 | e2683305d762e3d96500d7268e617891fa397e9b | 1,915 | advent-of-code-2023 | MIT License |
y2020/src/main/kotlin/adventofcode/y2020/Day04.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2020
import adventofcode.io.AdventSolution
fun main() = Day04.solve()
object Day04 : AdventSolution(2020, 4, "Passport Processing")
{
override fun solvePartOne(input: String): Int
{
val keys = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
return input
.splitToSequence("\n\n")
.map(::parseToDocument)
.count { keys.all(it::containsKey) }
}
override fun solvePartTwo(input: String): Int
{
val hclValidator = "#[a-f0-9]{6}".toRegex()
val eclValidator = "amb|blu|brn|gry|grn|hzl|oth".toRegex()
val pidValidator = "[0-9]{9}".toRegex()
val validators = sequenceOf<Validator>(
{ (it["byr"]?.toIntOrNull() ?: 0) in 1920..2002 },
{ (it["iyr"]?.toIntOrNull() ?: 0) in 2010..2020 },
{ (it["eyr"]?.toIntOrNull() ?: 0) in 2020..2030 },
{
val hgt = it.getOrDefault("hgt", "")
when (hgt.takeLast(2))
{
"cm" -> (hgt.dropLast(2).toIntOrNull() ?: 0) in 150..193
"in" -> (hgt.dropLast(2).toIntOrNull() ?: 0) in 59..76
else -> false
}
},
{ it.getOrDefault("hcl", "").let(hclValidator::matches) },
{ it.getOrDefault("ecl", "").let(eclValidator::matches) },
{ it.getOrDefault("pid", "").let(pidValidator::matches) }
)
return input
.splitToSequence("\n\n")
.map(::parseToDocument)
.count { document -> validators.all { v -> v(document) } }
}
private fun parseToDocument(input: String) = input
.splitToSequence(' ', '\n')
.map { it.split(':') }
.associate { (k, v) -> k to v }
}
private typealias Validator = (Map<String, String>) -> Boolean
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,868 | advent-of-code | MIT License |
src/Day12.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} | fun main() {
fun setupGrid(input: List<String>, grid: MutableMap<Coordinates, GridPosition>): Pair<Coordinates, Coordinates> {
var start = Coordinates(-1,-1)
var end = Coordinates(-1,-1)
for(row in input.indices) {
for(col in input[0].indices) {
val height = when(input[row][col]) {
'S' -> { start = Coordinates(row,col); 0 }
'E' -> { end = Coordinates(row,col); 25 }
else -> { input[row][col].code - 'a'.code }
}
val coord = Coordinates(row, col)
val pos = GridPosition(coord, height)
grid[Coordinates(row, col)] = pos
}
}
return Pair(start, end)
}
fun solveMinSteps(active: MutableSet<Path>, grid: MutableMap<Coordinates, GridPosition>, end: Coordinates): Int {
val visited = mutableSetOf<Coordinates>()
while (active.isNotEmpty()) {
val current = active.minByOrNull { it.cost }!!
if (current.position.coordinates == end) {
return current.cost
}
visited.add(current.position.coordinates)
active.remove(current)
val possibilities = grid[current.position.coordinates]!!.getPossibleMoves(grid).filter { !visited.contains(it.coordinates) }
for(possibility in possibilities) {
val alreadyActive = active.find { it.position == possibility }
if (alreadyActive != null) {
if (alreadyActive.cost > current.cost+1) {
active.remove(alreadyActive)
active.add(Path(possibility, current.cost+1))
}
} else {
active.add(Path(possibility, current.cost+1))
}
}
}
throw IllegalStateException("Didn't find result")
}
fun part1(input: List<String>): Int {
val grid = mutableMapOf<Coordinates, GridPosition>()
val (start, end) = setupGrid(input, grid)
val active = mutableSetOf(Path(grid[start]!!, 0))
return solveMinSteps(active, grid, end)
}
fun part2(input: List<String>): Int {
val grid = mutableMapOf<Coordinates, GridPosition>()
val (start, end) = setupGrid(input, grid)
val active = grid.filter { (coord, pos) -> pos.height == 0 }.map { (coord, pos) -> Path(pos, 0) }.toMutableSet()
return solveMinSteps(active, grid, end)
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
data class GridPosition(
val coordinates: Coordinates,
val height: Int
) {
fun getPossibleMoves(grid: Map<Coordinates, GridPosition>): List<GridPosition> {
val north = grid[coordinates.add(Coordinates(-1, 0))]
val south = grid[coordinates.add(Coordinates(1, 0))]
val west = grid[coordinates.add(Coordinates(0, -1))]
val east = grid[coordinates.add(Coordinates(0, 1))]
return listOfNotNull(north, south, west, east).filter { it.height <= height+1 }
}
}
data class Path(
val position: GridPosition,
val cost: Int
) | 0 | Kotlin | 0 | 0 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 3,319 | aoc2022 | Apache License 2.0 |
src/day07/Day07.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day07
import java.io.File
fun main() {
val data = parse("src/day07/Day07.txt")
println("🎄 Day 07 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data)}")
println()
println("[Part 2]")
println("Answer: ${part2(data)}")
}
private data class Hand(
val cards: String,
val bid: Int,
)
private fun String.toHand(): Hand {
val (cards, bid) = split(" ")
return Hand(cards, bid.toInt())
}
private fun parse(path: String): List<Hand> =
File(path)
.readLines()
.map(String::toHand)
// From weakest to strongest.
private val HAND_TYPES = listOf(
listOf(1, 1, 1, 1, 1),
listOf(2, 1, 1, 1),
listOf(2, 2, 1),
listOf(3, 1, 1),
listOf(3, 2),
listOf(4, 1),
listOf(5),
)
private val PART1_LETTER_MAPPINGS = mapOf(
'T' to 0x9UL,
'J' to 0xAUL,
'Q' to 0xBUL,
'K' to 0xCUL,
'A' to 0xDUL,
)
private val PART2_LETTER_MAPPINGS = mapOf(
'J' to 0x0UL,
'T' to 0x9UL,
'Q' to 0xAUL,
'K' to 0xBUL,
'A' to 0xCUL,
)
private fun String.toCode(mappings: Map<Char, ULong>): ULong =
fold(0UL) { acc, card ->
// If the card doesn't correspond to a letter, it must be a digit.
(acc shl 4) or (mappings[card] ?: (card.digitToInt() - 1).toULong())
}
private fun String.toFrequencies(): List<Int> =
this.groupingBy { it }
.eachCount()
.values
.sortedDescending()
private fun solve(data: List<Pair<ULong, Hand>>): Int =
data.sortedBy { (code, _) -> code }
.mapIndexed { index, (_, hand) -> (index + 1) * hand.bid }
.sum()
private fun Hand.encoded1(): ULong {
val code = cards.toCode(PART1_LETTER_MAPPINGS)
val type = HAND_TYPES.indexOf(cards.toFrequencies())
return (type shl 20).toULong() or code
}
private fun part1(data: List<Hand>): Int =
solve(data.map { hand -> hand.encoded1() to hand })
private fun Hand.encoded2(): ULong {
val code = cards.toCode(PART2_LETTER_MAPPINGS)
val frequencies = cards
.filter { it != 'J' }
.toFrequencies()
.toMutableList()
val jokers = cards.count { it == 'J' }
if (frequencies.size > 0) {
frequencies[0] += jokers
} else {
frequencies.add(jokers)
}
val type = HAND_TYPES.indexOf(frequencies)
return (type shl 20).toULong() or code
}
private fun part2(data: List<Hand>): Int =
solve(data.map { hand -> hand.encoded2() to hand })
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 2,576 | advent-of-code-2023 | MIT License |
src/Day11.kt | Totwart123 | 573,119,178 | false | null | import kotlin.math.round
fun main() {
class Monkey(
val number: Int,
val items: MutableList<Long>,
val operation: String,
val operationValue: String,
val test: Int,
val testTrue: Int,
val testFalse: Int,
var itemsInspected: Long = 0
) {
override fun toString(): String {
return "Monkey(number=$number, items=$items, operation='$operation', operationValue=$operationValue, test=$test, testTrue=$testTrue, testFalse=$testFalse, itemsInspected=$itemsInspected)"
}
}
fun getMonkey(monkyInfo: List<String>): Monkey {
val monkey = monkyInfo[0].split(": ").last().split(" ").last().dropLast(1).toInt()
val items = monkyInfo[1].split(": ").last().split(",").map { it.trim().toLong() }.toMutableList()
val operation = monkyInfo[2].split(": ").last().split(" ")[3]
check(listOf("-", "+", "*", "/").contains(operation)) { operation }
val operationValue = monkyInfo[2].split(": ").last().split(" ")[4]
check(monkyInfo[2].split(": ").last().split(" ")[2] == "old")
check(operationValue.toIntOrNull() != null || operationValue == "old")
check(monkyInfo[3].split(": ").last().split(" ").first() == "divisible")
val test = monkyInfo[3].split(": ").last().split(" ").last().toInt()
val testTrue = monkyInfo[4].split(": ").last().split(" ").last().toInt()
val testFalse = monkyInfo[5].split(": ").last().split(" ").last().toInt()
return Monkey(monkey, items, operation, operationValue, test, testTrue, testFalse)
}
fun calcMonkeys(input: List<String>, worryLevel: Int = 3, rounds: Int = 20): List<Monkey> {
val monkeys = input.windowed(6, 7).map { getMonkey(it) }
for (i in 0 until rounds){
monkeys.forEach {monkey ->
if (monkey.items.isNotEmpty()) {
monkey.items.forEach {itemValue ->
var item = itemValue
val operationValue = if (monkey.operationValue == "old") item else monkey.operationValue.toLong()
when(monkey.operation){
"-" -> item -= operationValue
"+" -> item += operationValue
"*" -> item *= operationValue
"/" -> item /= operationValue
}
item /= worryLevel
if(item % monkey.test == 0L){
monkeys.first { it.number == monkey.testTrue }.items.add(item)
}
else{
monkeys.first { it.number == monkey.testFalse }.items.add(item)
}
}
monkey.itemsInspected += monkey.items.size
monkey.items.clear()
}
}
}
return monkeys
}
fun part1(input: List<String>): Long {
val monkeys = calcMonkeys(input, 3, 20)
val sortedMonkeys = monkeys.sortedByDescending { it.itemsInspected };
return sortedMonkeys[0].itemsInspected * sortedMonkeys[1].itemsInspected
}
fun part2(input: List<String>): Long {
val monkeys = input.windowed(6, 7).map { getMonkey(it) }
var bigMod = 1
monkeys.forEach { bigMod *= it.test }
for (i in 0 until 10000){
monkeys.forEach {monkey ->
if (monkey.items.isNotEmpty()) {
monkey.items.forEach {itemValue ->
var item = itemValue
val operationValue = if (monkey.operationValue == "old") item else monkey.operationValue.toLong()
when(monkey.operation){
"-" -> item -= operationValue
"+" -> item += operationValue
"*" -> item *= operationValue
"/" -> item /= operationValue
}
item %= bigMod
if(item % monkey.test == 0L){
monkeys.first { it.number == monkey.testTrue }.items.add(item)
}
else{
monkeys.first { it.number == monkey.testFalse }.items.add(item)
}
}
monkey.itemsInspected += monkey.items.size
monkey.items.clear()
}
}
}
val sortedMonkeys = monkeys.sortedByDescending { it.itemsInspected }
return sortedMonkeys[0].itemsInspected * sortedMonkeys[1].itemsInspected
}
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 33e912156d3dd4244c0a3dc9c328c26f1455b6fb | 4,999 | AoC | Apache License 2.0 |
src/main/kotlin/adventofcode2022/solution/day_12.kt | dangerground | 579,293,233 | false | {"Kotlin": 51472} | package adventofcode2022.solution
import adventofcode2022.util.readDay
import java.util.Objects
import java.util.PriorityQueue
fun main() {
Day12("12").solve()
}
class Day12(private val num: String) {
private val inputText = readDay(num)
fun solve() {
println("Day $num Solution")
println("* Part 1: ${solution1()}")
println("* Part 2: ${solution2()}")
}
fun solution1(): Int {
val (map, start, end) = parse()
val edges = findAllowedEdges(map)
return edges.route(start, end)
}
private fun parse(): Triple<HeightMap, Point, Point> {
val map = HeightMap()
var start = Point(-1, -1)
var end = Point(-1, -1)
inputText.lines().forEachIndexed { y, line ->
val row = mutableMapOf<Int, Char>()
line.toCharArray().forEachIndexed { x, c ->
when (c) {
'S' -> {
start = Point(x, y)
row[x] = 'a'
}
'E' -> {
end = Point(x, y)
row[x] = 'z'
}
else -> {
row[x] = c
}
}
}
map[y] = row
}
return Triple(map, start, end)
}
private fun findAllowedEdges(map: HeightMap): EdgesList {
val edges = EdgesList()
for (y in 0 until map.height()) {
for (x in 0 until map.width()) {
val allowedHeight = map.get(x, y)!! + 1
val left = map.get(x - 1, y)
if (left != null && left <= allowedHeight) {
edges.add(Point(x, y), Point(x - 1, y))
}
val right = map.get(x + 1, y)
if (right != null && right <= allowedHeight) {
edges.add(Point(x, y), Point(x + 1, y))
}
val up = map.get(x, y - 1)
if (up != null && up <= allowedHeight) {
edges.add(Point(x, y), Point(x, y - 1))
}
val down = map.get(x, y + 1)
if (down != null && down <= allowedHeight) {
edges.add(Point(x, y), Point(x, y + 1))
}
}
}
return edges
}
fun solution2(): Long {
val (map, start, end) = parse()
val starts = mutableListOf<Point>()
for (y in 0 until map.height()) {
for (x in 0 until map.width()) {
if (map.get(x, y) == 'a'.code) {
starts.add(Point(x, y))
}
}
}
val edges = findAllowedEdges(map)
return starts.map { edges.route(it, end)}.filter { it > 0 }.minOf { it }.toLong()
}
}
data class Point(val x: Int, val y: Int, var cost: Int = 0) : Comparable<Point> {
override fun hashCode(): Int {
return Objects.hash(x, y)
}
override fun compareTo(other: Point) = cost.compareTo(other.cost)
override fun equals(other: Any?): Boolean {
return other is Point
&& other.x == x
&& other.y == y
}
}
typealias HeightMap = HashMap<Int, Map<Int, Char>>
fun HeightMap.height() = size
fun HeightMap.width() = get(0)?.size ?: 0
fun HeightMap.get(x: Int, y: Int) = get(y)?.get(x)?.code
class EdgesList {
private val data = mutableMapOf<Point, MutableSet<Point>>()
fun add(p1: Point, p2: Point) {
data.putIfAbsent(p1, mutableSetOf())
data[p1]!!.add(p2)
}
fun route(start: Point, goal: Point): Int {
if (start == goal) {
println("Found ${start.cost}")
return start.cost
}
val queue = PriorityQueue<Point>()
val visited = mutableSetOf<Point>()
queue.add(start)
visited.add(start)
var i = 0
while (queue.isNotEmpty()) {
i++
val current = queue.poll()
if (current == goal) {
println("Found ${current.cost}")
return current.cost
} else {
data[current]
?.filter { !visited.contains(it) }
?.map { Point(it.x, it.y, current.cost + 1) }
?.filter { !queue.containsPoint(it) }
?.let {
queue.addAll(it)
}
}
visited.add(current)
}
return 0
}
fun PriorityQueue<Point>.containsPoint(p: Point): Boolean {
return this.toList().find { it.x == p.x && it.y == p.y && it.cost == p.cost } != null
}
} | 0 | Kotlin | 0 | 0 | f1094ba3ead165adaadce6cffd5f3e78d6505724 | 4,732 | adventofcode-2022 | MIT License |
solutions/src/Day13.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
val packetPairs = input.split { it.isBlank() }.map { it[0] to it[1] }
return packetPairs.mapIndexed { index, (packet1, packet2) ->
val (packet1List, packet2List) = parseToLists(packet1, packet2)
if (compareLists(packet1List, packet2List) <= 0) {
index + 1
} else {
0
}
}.sum()
}
fun part2(input: List<String>): Int {
val bonusPackets = listOf("[[2]]", "[[6]]")
val packetPairs = input.filter { it.isNotBlank() } + bonusPackets
val sortedPackets = packetPairs.sortedWith { packet1, packet2 ->
val (packet1List, packet2List) = parseToLists(packet1, packet2)
val compareResult = compareLists(packet1List, packet2List)
when {
compareResult < 0 -> -1
compareResult > 0 -> 1
else -> 0
}
}
val firstDividerPacketIndex = sortedPackets.indexOf("[[2]]") + 1
val secondDividerPacketIndex = sortedPackets.indexOf("[[6]]") + 1
return firstDividerPacketIndex * secondDividerPacketIndex
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private fun <T> List<T>.split(predicate: (T) -> Boolean): List<List<T>> =
fold(mutableListOf(mutableListOf<T>())) { acc, t ->
if (predicate(t)) {
acc.add(mutableListOf())
} else {
acc.last().add(t)
}
acc
}.filterNot { it.isEmpty() }
private fun parseToLists(packet1: String, packet2: String): Pair<List<Any>, List<Any>> {
val packet1List = mutableListOf<Any>()
parseToList(packet1, packet1List)
val packet2List = mutableListOf<Any>()
parseToList(packet2, packet2List)
return packet1List to packet2List
}
private fun parseToList(value: String, list: MutableList<Any>): Int {
var newTotalIndex = 0
while (newTotalIndex < value.length - 1) {
when (value[newTotalIndex]) {
'[' -> {
val subList = mutableListOf<Any>()
list.add(subList)
val remainder = value.substring(newTotalIndex + 1)
val newIndex = parseToList(remainder, subList)
newTotalIndex += newIndex
}
']' -> {
newTotalIndex++
break
}
',' -> Unit
else -> {
var number = ""
while (value[newTotalIndex].isDigit()) {
number += value[newTotalIndex]
newTotalIndex++
}
list.add(number.toInt())
continue
}
}
newTotalIndex++
}
return newTotalIndex
}
private fun compareLists(packet1List: List<*>, packet2List: List<*>): Int {
val minSize = min(packet1List.size, packet2List.size)
for (i in 0 until minSize) {
val packet1Item = packet1List[i]!!
val packet2Item = packet2List[i]!!
val diff = compareValues(packet1Item, packet2Item)
if (diff < 0) {
return -1
} else if (diff > 0) {
return 1
}
}
return packet1List.size - packet2List.size
}
private fun compareValues(packet1Item: Any, packet2Item: Any): Int = when {
packet1Item is Int && packet2Item is Int -> {
packet1Item.toInt() - packet2Item.toInt()
}
packet1Item is Int && packet2Item is List<*> -> {
compareLists(listOf(packet1Item), packet2Item)
}
packet2Item is Int && packet1Item is List<*> -> {
compareLists(packet1Item, listOf(packet2Item))
}
packet1Item is List<*> && packet2Item is List<*> -> {
compareLists(packet1Item, packet2Item)
}
else -> throw Exception("Cannot compare $packet1Item to $packet2Item one is not an Int or List<*>")
}
| 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 4,154 | advent-of-code-22 | Apache License 2.0 |
src/day07/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day07
import println
import readInput
import kotlin.math.pow
enum class HandType(val weight: Int, val sequencePattern: List<Int>) {
FIVE_OF_A_KIND(7, listOf(5)),
FOUR_OF_A_KIND(6, listOf(4, 1)),
FULL_HOUSE(5, listOf(3, 2)),
THREE_OF_A_KIND(4, listOf(3, 1, 1)),
TWO_PAIR(3, listOf(2, 2, 1)),
ONE_PAIR(2, listOf(2, 1, 1, 1)),
HIGH_CARD(1, listOf(1 ,1, 1, 1, 1))
}
fun main() {
class CardRules(val cardWeights: String, val withJoker: Boolean,
val numberOfCards: Int = 5,
val joker: Char = 'J'
)
class Hand {
var cards: String = ""
var bid: Int = 0
var weight: Long = 0
constructor(cards: String, bid: Int, cardRules: CardRules) {
this.cards = cards
this.bid = bid
this.weight = getWeight(cards, cardRules)
kotlin.io.println(cards + " -> "+ weight.toString(16))
}
fun getHandType(cardRules: CardRules): HandType {
val cardsCount = mutableMapOf<Char, Int>()
cards.forEach {
cardsCount[it] = cardsCount.getOrDefault(it, 0) + 1
}
var handSequencePattern = cardsCount.values.sortedDescending()
if (cardRules.withJoker) {
var numberOfJokers = cardsCount.getOrDefault(cardRules.joker, 0)
if (numberOfJokers > 0 && numberOfJokers != cardRules.numberOfCards) {
var tmp = cardsCount.filter { it.key != cardRules.joker }.values
.sortedDescending()
.toMutableList()
tmp[0] += numberOfJokers
handSequencePattern = tmp
}
}
return HandType.values().find { it.sequencePattern == handSequencePattern }!!
}
fun getWeight(cards: String, cardRules: CardRules): Long {
var result = 0L
cards.forEachIndexed {index, char ->
var cardWeight = cardRules.cardWeights.indexOf(char)
result += (cardWeight * 16.0.pow(cardRules.numberOfCards - 1 - index.toDouble())).toLong()
}
var handType = getHandType(cardRules)
return result + (handType.weight * 16.0.pow(cardRules.numberOfCards)).toLong()
}
}
class CamelCardsGame {
var hands: List<Hand> = emptyList()
constructor(input: List<String>, cardRules: CardRules) {
for (row in input) {
var handDetails = row.split(" ");
hands += Hand(handDetails[0], handDetails[1].trim().toInt(), cardRules)
}
}
fun getTotalScore(): Long {
var sortedHands = hands.sortedBy { it.weight }
var result = 0L;
sortedHands.forEachIndexed {index, hand ->
result += (index + 1) * hand.bid
}
return result
}
}
val ruleSet1 = CardRules("23456789TJQKA", false)
val ruleSet2 = CardRules("J23456789TQKA", true)
var testGameEngine = CamelCardsGame(readInput("day07/test1"), ruleSet1)
check(testGameEngine.getTotalScore() == 6440L)
val gameEngine = CamelCardsGame(readInput("day07/input"), ruleSet1)
gameEngine.getTotalScore().println()
var testGameEngine2 = CamelCardsGame(readInput("day07/test1"), ruleSet2)
check(testGameEngine2.getTotalScore() == 5905L)
val gameEngine2 = CamelCardsGame(readInput("day07/input"), ruleSet2)
gameEngine2.getTotalScore().println()
} | 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 3,542 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/com/staricka/adventofcode2023/days/Day5.kt | mathstar | 719,656,133 | false | {"Kotlin": 107115} | package com.staricka.adventofcode2023.days
import com.staricka.adventofcode2023.framework.Day
import java.util.TreeMap
import kotlin.math.min
data class Mapping(val destinationStart: Long, val sourceStart: Long, val length: Long) {
fun inRange(value: Long): Boolean = value >= sourceStart && value < sourceStart + length
fun mapValue(value: Long): Long = destinationStart + (value - sourceStart)
companion object {
fun fromString(input: String): Mapping {
val split = input.split(" ")
return Mapping(split[0].toLong(), split[1].toLong(), split[2].toLong())
}
}
}
data class Range(val start: Long, val length: Long) {
companion object {
fun fromStartEnd(start: Long, end: Long): Range {
return Range(start, end - start + 1)
}
}
}
class Mappings(val sourceType: String, val destinationType: String) {
private val entries = TreeMap<Long, Mapping>()
fun addMapping(mapping: Mapping) {
entries[mapping.sourceStart] = mapping
}
fun getMapping(value: Long): Long {
val potentialMatch = entries.floorEntry(value)
if (potentialMatch == null || !potentialMatch.value.inRange(value)) return value
return potentialMatch.value.mapValue(value)
}
fun getMappingForRange(input: Range): List<Range> {
val result = ArrayList<Range>()
var start = input.start
while (start < input.start + input.length) {
val floorMapping = entries.floorEntry(start)
if (floorMapping != null && floorMapping.value.inRange(start)) {
val end = min(
floorMapping.value.sourceStart + floorMapping.value.length - 1,
input.start + input.length - 1
)
result.add(Range.fromStartEnd(floorMapping.value.mapValue(start), floorMapping.value.mapValue(end)))
start = end + 1
} else {
val ceilMapping = entries.ceilingEntry(start)
val end =
if (ceilMapping != null) {
min(
input.start + input.length - 1,
ceilMapping.value.sourceStart - 1
)
} else {
input.start + input.length - 1
}
result.add(Range.fromStartEnd(start, end))
start = end + 1
}
}
return result
}
companion object {
fun fromString(input: String): Mappings {
val split = input.split(" ")[0].split("-")
return Mappings(split[0], split[2])
}
}
}
fun getLocationForSeed(seed: Long, mappings: Map<String, Mappings>): Long? {
var value: Long? = seed
var type: String? = "seed"
while (type != "location" && value != null && type != null) {
val relevantMapping = mappings[type]
type = relevantMapping?.destinationType
value = relevantMapping?.getMapping(value)
}
return value
}
fun getLocationForSeedRanges(seeds: List<Range>, mappings: Map<String, Mappings>): List<Range> {
var values: List<Range> = seeds
var type: String? = "seed"
while (type != "location" && type != null) {
val relevantMapping = mappings[type]
type = relevantMapping?.destinationType
values = values.flatMap { relevantMapping!!.getMappingForRange(it) }
}
return values
}
typealias Seeds = List<Long>
fun String.toSeeds(): Seeds {
return this.split(":")[1].trim().split(" ").map { it.toLong() }
}
fun String.toSeedsFromRange(): List<Range> {
val nums = this.toSeeds()
var i = 0
val result = ArrayList<Range>()
while (i < nums.size) {
result.add(Range(nums[i], nums[i+1]))
i += 2
}
return result
}
class Day5: Day {
override fun part1(input: String): Long {
var seeds: Seeds? = null
val mappings = HashMap<String, Mappings>()
var currentMappings: Mappings? = null
input.lines().forEach{
if (seeds == null) {
seeds = it.toSeeds()
} else if (it.isBlank()) {
currentMappings = null
} else if (currentMappings == null) {
currentMappings = Mappings.fromString(it)
mappings[currentMappings!!.sourceType] = currentMappings!!
} else {
currentMappings!!.addMapping(Mapping.fromString(it))
}
}
return seeds!!.mapNotNull { getLocationForSeed(it, mappings) }.min()
}
override fun part2(input: String): Long {
var seeds: List<Range>? = null
val mappings = HashMap<String, Mappings>()
var currentMappings: Mappings? = null
input.lines().forEach{
if (seeds == null) {
seeds = it.toSeedsFromRange()
} else if (it.isBlank()) {
currentMappings = null
} else if (currentMappings == null) {
currentMappings = Mappings.fromString(it)
mappings[currentMappings!!.sourceType] = currentMappings!!
} else {
currentMappings!!.addMapping(Mapping.fromString(it))
}
}
return getLocationForSeedRanges(seeds!!, mappings).minBy { it.start }.start
}
} | 0 | Kotlin | 0 | 0 | 8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa | 5,380 | adventOfCode2023 | MIT License |
kotlin/2021/round-1a/prime-time/src/main/kotlin/OldSimplerSolution.kts | ShreckYe | 345,946,821 | false | null | import kotlin.math.E
import kotlin.math.exp
import kotlin.math.pow
fun main() {
val t = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val m = readLine()!!.toInt()
val pns = List(m) {
val lineInputs = readLine()!!.split(' ')
Pn(lineInputs[0].toInt(), lineInputs[1].toLong())
}
val y = ans(pns)
println("Case #${ti + 1}: $y")
}
fun ans(pns: List<Pn>): Long {
val upperBound = pns.sum()
val minProductGroupSum = (0..upperBound)
.first { exp(it.toDouble() / E) >= upperBound - it }
val maxProductGroupSum = (minProductGroupSum..upperBound)
.last { maxPrime.toDouble().pow(it.toDouble() / maxPrime) <= upperBound - it }
val pnMap = LongArray(maxPrime + 1)
pns.forEach { pnMap[it.p] = it.n }
return (minProductGroupSum..maxProductGroupSum).asSequence()
.map { upperBound - it }
.firstOrNull { sumEqProduct ->
val factorPns = decompose(sumEqProduct, maxPrime)
if (factorPns !== null) {
val sumGroupPnMap = pnMap.copyOf().also {
for ((p, n) in factorPns) {
val rn = it[p] - n
if (rn >= 0)
it[p] = rn
else
return@firstOrNull false
}
}
val sumGroupPns =
sumGroupPnMap.asSequence().withIndex().map { Pn(it.index, it.value) }.filter { it.n > 0 }
sumGroupPns.sum() == sumEqProduct
} else false
} ?: 0
}
data class Pn(val p: Int, val n: Long)
fun List<Pn>.sum() = sumOf { it.p * it.n }
fun Sequence<Pn>.sum() = sumOf { it.p * it.n }
/*const*/ val maxPrime = 499
fun decompose(number: Long, maxPrime: Int): List<Pn>? {
require(number >= 1)
val pns = ArrayList<Pn>(maxPrime)
var number = number
for (p in 2..maxPrime) {
if (number == 1L) break
var n = 0L
while (number % p == 0L) {
number /= p
n++
}
pns.add(Pn(p, n))
}
if (number == 1L) return pns
return null
} | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 2,167 | google-code-jam | MIT License |
src/Day02.kt | aemson | 577,677,183 | false | {"Kotlin": 7385} | import GameChoices.ROCK
import GameChoices.PAPER
import GameChoices.SCISSORS
fun main() {
val inputData = readInput("Day02_input")
val rock =
GameOption(
choice = ROCK,
choicePoint = 1,
firstPlayerChoice = 'A',
secondPlayerChoice = 'X',
winOver = SCISSORS,
loseOver = PAPER
)
val paper =
GameOption(
choice = PAPER,
choicePoint = 2,
firstPlayerChoice = 'B',
secondPlayerChoice = 'Y',
winOver = ROCK,
loseOver = SCISSORS
)
val scissors = GameOption(
choice = SCISSORS,
choicePoint = 3,
firstPlayerChoice = 'C',
secondPlayerChoice = 'Z',
winOver = PAPER,
loseOver = ROCK
)
val gameRules = listOf(rock, paper, scissors)
val pointsMap = mapOf("win" to 6, "lost" to 0, "draw" to 3)
partOneGamePoints(inputData, gameRules, pointsMap)
partTwoGamePoints(inputData, gameRules, pointsMap)
}
private fun partOneGamePoints(
inputData: List<String>,
gameRules: List<GameOption>,
pointsMap: Map<String, Int>
) {
val gamePoints = inputData.map { game ->
val playerChoices = game.split(" ")
val firstPlayerChoice = playerChoices[0].single()
val secondPlayerChoice = playerChoices[1].single()
val firstPlayer = gameRules.find { it.firstPlayerChoice == firstPlayerChoice }
val secondPlayer = gameRules.find { it.secondPlayerChoice == secondPlayerChoice }
calculatePoints(secondPlayer, firstPlayer, pointsMap)
}
println("Part 1 -> Game Point Total: ${gamePoints.sumOf { it!! }}")
}
/**
* X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win
* */
fun partTwoGamePoints(
inputData: List<String>,
gameRules: List<GameOption>,
pointsMap: Map<String, Int>
) {
val newRule = mapOf('X' to "lost", 'Y' to "draw", 'Z' to "win")
val gamePoints = inputData.map { game ->
val playerChoices = game.split(" ")
val firstPlayerChoice = playerChoices[0].single()
val secondPlayerChoice = playerChoices[1].single()
val firstPlayer = gameRules.find { it.firstPlayerChoice == firstPlayerChoice }
val secondPlayer = when (secondPlayerChoice) {
'X' -> gameRules.first { it.choice == firstPlayer?.winOver }
'Y' -> gameRules.first { it.choice == firstPlayer?.choice }
else -> gameRules.first { it.choice == firstPlayer?.loseOver }
}
calculatePoints(secondPlayer, firstPlayer, pointsMap)
}
println("Part 2 -> Game Point Total: ${gamePoints.sumOf { it!! }}")
}
private fun calculatePoints(
secondPlayer: GameOption?,
firstPlayer: GameOption?,
pointsMap: Map<String, Int>
) = if (secondPlayer?.winOver == firstPlayer?.choice) {
secondPlayer?.choicePoint?.plus(pointsMap["win"] ?: 6)
} else if (firstPlayer?.winOver == secondPlayer?.choice) {
secondPlayer?.choicePoint?.plus(pointsMap["lost"] ?: 0)
} else {
secondPlayer?.choicePoint?.plus(pointsMap["draw"] ?: 3)
}
enum class GameChoices {
ROCK,
PAPER,
SCISSORS
}
data class GameOption(
var choice: GameChoices,
val choicePoint: Int,
val firstPlayerChoice: Char,
val secondPlayerChoice: Char,
var winOver: GameChoices,
var loseOver: GameChoices,
) | 0 | Kotlin | 0 | 0 | ffec4b848ed5c2ba9b2f2bfc5b991a2019c8b3d4 | 3,420 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/be/seppevolkaerts/day2/Day2.kt | Cybermaxke | 727,453,020 | false | {"Kotlin": 35118} | package be.seppevolkaerts.day2
import kotlin.math.max
class Game(
val id: Int,
val sets: List<CubeSet>
)
class CubeSet(
val cubes: Map<String, Int>
)
fun parseGame(string: String): Game {
val idAndSets = string.split(':', limit = 2)
val id = idAndSets[0].replace("Game ", "").toInt()
val sets = idAndSets[1]
.splitToSequence(';')
.map { setContent ->
val cubes = setContent.splitToSequence(',')
.associate { cubesAndColor ->
val split = cubesAndColor.trim().split(' ')
split[1] to split[0].toInt()
}
CubeSet(cubes)
}
.toList()
return Game(id, sets)
}
fun parseGames(iterable: Iterable<String>) = iterable.map { parseGame(it) }
fun sumOfPossibleGameIds(iterable: Iterable<String>): Int {
val games = parseGames(iterable)
val limits = mapOf("red" to 12, "green" to 13, "blue" to 14)
return games.asSequence()
.filter { game -> game.sets.all { set -> set.cubes.all { (color, quantity) -> quantity <= limits[color]!! } } }
.sumOf { game -> game.id }
}
fun sumOfPower(iterable: Iterable<String>): Int {
val games = parseGames(iterable)
return games.asSequence()
.map { game ->
val cubes = mutableMapOf<String, Int>()
game.sets.forEach { set ->
set.cubes.forEach { (color, quantity) ->
cubes.compute(color) { _, currentValue ->
if (currentValue == null) quantity else max(currentValue, quantity)
}
}
}
cubes.values.reduce { acc, i -> acc * i }
}
.sum()
}
| 0 | Kotlin | 0 | 1 | 56ed086f8493b9f5ff1b688e2f128c69e3e1962c | 1,536 | advent-2023 | MIT License |
src/Day04.kt | tbilou | 572,829,933 | false | {"Kotlin": 40925} | fun main() {
// "2-4,6-8"
// [[2-4],[6-8]]
// [[2,3,4],[6,7,8]]
fun parseInput(input: List<String>) = input
.map { p -> p.split(',') }
.map { (r1, r2) -> listOf(r1.toRange(), r2.toRange()).sortedBy { it.size } }
fun part1(input: List<String>): Int {
return parseInput(input)
.map { (l1, l2) -> l1.subtract(l2).size }
.count { i -> i == 0 }
}
fun part2(input: List<String>): Int {
return parseInput(input)
.map { (l1, l2) -> (l1+l2).size - (l1+l2).toSet().size}
.count { it > 0 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
// test if implementation meets criteria from the description, like:
val testInput2 = readInput("Day04_test")
check(part2(testInput2) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun String.toRange(): List<Int> {
return this.split('-').toRange()
}
private fun List<String>.toRange(): List<Int> {
return (first().toInt()..last().toInt()).toList()
}
| 0 | Kotlin | 0 | 0 | de480bb94785492a27f020a9e56f9ccf89f648b7 | 1,188 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Main.kt | NiksonJD | 628,972,288 | false | null | package processor
import kotlin.math.pow
fun input(prompt: String) = println(prompt).run { readln() }
fun inputList(prompt: String) = input(prompt).split(" ").map { it.toInt() }
val inputListDouble = { readln().split(" ").map { it.toDouble() } }
val menuMap = mapOf(
"1" to ::addMatrices, "2" to ::multiplyByConstant, "3" to ::multiplyMatrices, "4" to ::transposeMatrix,
"5" to ::determinantMatrix, "6" to ::inverseMatrix
)
fun addMatrices() {
val (a, b) = inputMatrices(2).also { println("The result is:") }
a.zip(b) { row1, row2 -> println(row1.zip(row2) { value1, value2 -> value1.plus(value2) }.joinToString(" ")) }
}
fun multiplyByConstant() {
val a = inputMatrices(1)[0]
val constant = input("Enter constant:").toDouble().also { println("The result is:") }
a.map { row -> println(row.map { v -> v.times(constant) }.joinToString(" ")) }
}
fun multiplyMatrices() {
val (a, b) = inputMatrices(2).also { println("The result is:") }
val c = List(a.size) { i -> List(b[0].size) { j -> a[i].zip(b.map { row -> row[j] }).sumOf { (a, b) -> a * b } } }
c.forEach { row -> println(row.joinToString(" ")) }
}
fun transposeMatrix() {
val choice = input("\n1. Main diagonal\n2. Side diagonal\n3. Vertical line\n4. Horizontal line\nYour choice:")
val a = inputMatrices(1)[0]
val transposed = List(a.size) { Array(a[0].size) { 0.0 } }
val (s, column) = a.run { size to get(0).size }
when (choice) {
"1" -> a.forEachIndexed { i, row -> row.forEachIndexed { j, v -> transposed[j][i] = v } }
"2" -> a.forEachIndexed { i, row -> row.forEachIndexed { j, v -> transposed[column - j - 1][s - i - 1] = v } }
"3" -> a.forEachIndexed { i, row -> row.forEachIndexed { j, v -> transposed[i][column - j - 1] = v } }
"4" -> a.forEachIndexed { i, row -> row.forEachIndexed { j, v -> transposed[s - i - 1][j] = v } }
}
transposed.forEach { row -> println(row.joinToString(" ")) }
}
fun determinantMatrix() = println("The result is:\n${determinant(inputMatrices(1)[0])}")
fun determinant(m: List<List<Double>>): Double {
return if (m.size == 1) m[0][0] else {
(m.indices).sumOf { j ->
(-1.0).pow(j) * m[0][j] *
determinant(m.subList(1, m.size).map { it.subList(0, j) + it.subList(j + 1, it.size) })
}
}
}
fun inverseMatrix() {
val m = inputMatrices(1)[0].map { it }.toMutableList()
if (determinant(m) == 0.0) println("This matrix doesn't have an inverse.").also { return }
val im = MutableList(m.size) { i -> List(m.size) { j -> if (i == j) 1.0 else 0.0 } }
(0 until m.size).forEach { i ->
val pivot = m[i][i]
m[i] = m[i].map { it / pivot }
im[i] = im[i].map { it / pivot }
(0 until m.size).filter { it != i }.forEach { k ->
val factor = m[k][i]
m[k] = m[k].zip(m[i]).map { (a, b) -> a - b * factor }
im[k] = im[k].zip(im[i]).map { (a, b) -> a - b * factor }
}
}
println("The result is:").also { im.forEach { row -> println(row.joinToString(" ")) } }
}
fun inputMatrices(count: Int): Array<List<List<Double>>> {
val array = Array(count) { listOf<List<Double>>() }
for (i in 1..count) {
val order = if (count == 2) if (i == 1) "first" else "second" else ""
inputList("Enter size of $order matrix:").also { println("Enter matrix:") }
.let { array[i - 1] = List(it[0]) { inputListDouble() } }
}
return array
}
fun main() {
val menu = "\n1. Add matrices\n2. Multiply matrix by a constant\n3. Multiply matrices\n4. Transpose matrix" +
"\n5. Calculate a determinant\n6. Inverse matrix\n0. Exit\nYour choice:"
while (true) {
val answer = input(menu); if (answer == "0") break else menuMap[answer]?.invoke()
}
} | 0 | Kotlin | 0 | 0 | 823db67ed40be631865b53233dfd71dad72b32c4 | 3,821 | Kotlin_NumericMatrixProcessor | Apache License 2.0 |
src/main/kotlin/day10/solver.kt | derekaspaulding | 317,756,568 | false | null | package day10
import java.io.File
fun buildJoltageAdapterChain(joltages: List<Int>) = joltages.sorted()
fun solveFirstProblem(joltages: List<Int>): Int {
val chain = buildJoltageAdapterChain(joltages)
var oneJoltDifferences = 0
// There is always a final 3 jolt difference from the end of the chain to the device
var threeJoltDifferences = 1
for (i in 0..chain.lastIndex) {
// getOrNull handles the first element that doesn't have an element before it
val joltageDifference = chain[i] - (chain.getOrNull(i - 1) ?: 0)
if (joltageDifference == 1) {
oneJoltDifferences += 1
} else if (joltageDifference == 3) {
threeJoltDifferences += 1
}
}
return oneJoltDifferences * threeJoltDifferences
}
fun solveProblemTwo(joltages: List<Int>): Long {
val comboMap = mutableMapOf<Int, Long>()
var lookupHits = 0
fun getCombinations(
lastJoltage: Int,
remainingJoltages: List<Int>,
): Long {
if (remainingJoltages.isEmpty()) {
// When we are out of adapters, there's the final connection to the
return 1
}
val lookupValue = comboMap[remainingJoltages.hashCode()]
if (lookupValue != null) {
lookupHits += 1
return lookupValue
}
val possibleCombinations = remainingJoltages.withIndex()
.filter { it.value - lastJoltage <= 3 }
.map { Pair(it.value, remainingJoltages.subList(it.index + 1, remainingJoltages.size)) }
val nextCombinations = possibleCombinations.map {
val combo = getCombinations(it.first, it.second)
comboMap[it.second.hashCode()] = combo
combo
}
return nextCombinations.reduce { acc, combo -> acc + combo }
}
val chain = buildJoltageAdapterChain(joltages)
return getCombinations(0, chain)
}
fun main() {
val joltages = File("src/main/resources/day10/input.txt")
.useLines { it.toList() }
.map { it.toInt() }
val solution1 = solveFirstProblem(joltages)
println("Product of 1 jolt and 3 jolt differences: $solution1")
val combinations = solveProblemTwo(joltages)
println("Possible combinations: $combinations")
} | 0 | Kotlin | 0 | 0 | 0e26fdbb3415fac413ea833bc7579c09561b49e5 | 2,274 | advent-of-code-2020 | MIT License |
src/y2015/Day02.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2015
import util.readInput
object Day02 {
private fun parse(input: List<String>): List<Triple<Int, Int, Int>> {
return input.map {
it.split('x').map { it.toInt() }
}.map { Triple(it.first(), it.last(), it[1]) }
}
fun part1(input: List<String>): Long {
val parsed = parse(input)
return parsed.map {
areas(it)
}.sumOf { it.first + it.second }.toLong()
}
private fun areas(sides: Triple<Int, Int, Int>): Pair<Int, Int> {
val (a, b, c) = sides
val sideAreas = listOf(a*b, b*c, a*c)
return sideAreas.sum() * 2 to sideAreas.min()
}
fun part2(input: List<String>): Int {
val parsed = parse(input)
return parsed.sumOf {
volume(it) + smallestCircumference(it)
}
}
private fun volume(sides: Triple<Int, Int, Int>): Int {
val (a, b, c) = sides
return a * b * c
}
private fun smallestCircumference(sides: Triple<Int, Int, Int>): Int {
val (a, b, c) = sides
return ((a + b + c) - listOf(a, b, c).max()) * 2
}
}
fun main() {
val testInput = """
1x1x10
""".trimIndent().split("\n")
println("------Tests------")
println(Day02.part1(testInput))
println(Day02.part2(testInput))
println("------Real------")
val input = readInput("resources/2015/day02")
println(Day02.part1(input))
println(Day02.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,458 | advent-of-code | Apache License 2.0 |
src/Day13.kt | cagriyildirimR | 572,811,424 | false | {"Kotlin": 34697} | fun day13Part1() {
val input = readInput("Day13")
var count = 0
for (i in input.indices step 3) {
if (compare2(input[i], input[i + 1])) count += (1 + i / 3)
}
println(count)
}
fun compare2(left: String, right: String): Boolean {
val (l, ls) = firstAndRest(left)
val (r, rs) = firstAndRest(right)
return when {
(left.isEmpty()) -> true
(right.isEmpty()) -> false
(l == "[" && r == "]") -> false
(r == "[" && l == "]") -> true
(l == "[" && r != "[") -> compare2(ls, "$r]$rs")
(r == "[" && l != "[") -> compare2("$l]$ls", rs)
(l == "]" && r != "]") -> true
(r == "]" && l != "]") -> false
r.length > l.length -> true
l.length > r.length -> false
r > l -> true
l > r -> false
else -> compare2(ls, rs)
}
}
fun firstAndRest(ss: String): Pair<String, String> {
if (ss.isEmpty()) return Pair("", "")
val f = ss.first()
val first = if (f in "[]") f.toString() else ss.takeWhile { it in "0123456789" }
val rest = ss.drop(first.length).trimStart(',')
return Pair(first, rest)
}
fun day13Part2() {
val input = readInput("Day13").filter { !it.isEmpty() }.toMutableList()
val two = "[[2]]"
val six = "[[6]]"
input.add(two)
input.add(six)
input.sortWith { o1, o2 -> if (compare2(o1, o2)) -1 else 1 }
println((input.indexOf(two) + 1) * (input.indexOf(six) + 1) )
} | 0 | Kotlin | 0 | 0 | 343efa0fb8ee76b7b2530269bd986e6171d8bb68 | 1,452 | AoC | Apache License 2.0 |
src/main/kotlin/Day12.kt | Vampire | 572,990,104 | false | {"Kotlin": 57326} | import kotlin.math.min
typealias Distance = Int
fun main() {
data class Node(val x: Int, val y: Int) {
var height: Int? = null
var n: Node? = null
var e: Node? = null
var s: Node? = null
var w: Node? = null
var distance: Distance = Distance.MAX_VALUE
}
fun Char.toHeight() = when (this) {
'S' -> 0
'E' -> 'z'.code - 'a'.code
else -> code - 'a'.code
}
fun buildGraph(input: List<String>): Triple<Array<Array<Node>>, Node, Node> {
val nodes = Array(input.size) { y -> Array(input[y].length) { x -> Node(x, y) } }
var start: Node? = null
var end: Node? = null
for (y in input.indices) {
val line = input[y]
for (x in line.indices) {
val char = line[x]
val node = nodes[y][x]
node.height = char.toHeight()
when (char) {
'S' -> start = node
'E' -> end = node
}
}
}
for (y in nodes.indices) {
val line = nodes[y]
for (x in line.indices) {
val node = line[x]
if ((x > 0) && (nodes[y][x - 1].height!! <= (node.height!! + 1))) {
node.w = nodes[y][x - 1]
}
if ((x < (line.size - 1)) && (nodes[y][x + 1].height!! <= (node.height!! + 1))) {
node.e = nodes[y][x + 1]
}
if ((y > 0) && (nodes[y - 1][x].height!! <= (node.height!! + 1))) {
node.n = nodes[y - 1][x]
}
if ((y < (nodes.size - 1)) && (nodes[y + 1][x].height!! <= (node.height!! + 1))) {
node.s = nodes[y + 1][x]
}
}
}
return Triple(nodes, start!!, end!!)
}
fun findShortestPath(
nodes: Array<Array<Node>>,
start: Node,
end: Node,
shortestPath: Distance = Distance.MAX_VALUE
): Distance? {
val visited = mutableSetOf<Node>()
val unvisited = nodes.flatten().toMutableSet()
unvisited.forEach { it.distance = Distance.MAX_VALUE }
start.distance = 0
var current = start
while (current.distance != Distance.MAX_VALUE) {
listOfNotNull(current.n, current.e, current.s, current.w)
.intersect(unvisited)
.forEach {
it.distance = min(current.distance + 1, it.distance)
check(it.distance >= 0) {
"Algorithm error"
}
}
visited.add(current)
unvisited.remove(current)
if (current == end) {
return end.distance
} else if (
visited
.filter {
listOfNotNull(it.n, it.e, it.s, it.w)
.intersect(unvisited)
.isNotEmpty()
}
.all { it.distance >= shortestPath }
) {
return shortestPath
} else {
current = unvisited.minBy(Node::distance)
}
}
return null
}
fun part1(input: List<String>): Distance {
val (nodes, start, end) = buildGraph(input)
return findShortestPath(nodes, start, end)!!
}
fun part2(input: List<String>): Distance {
val (nodes, _, end) = buildGraph(input)
return nodes
.flatten()
.filter { it.height == 0 }
.fold(Distance.MAX_VALUE) { shortestPath, node ->
findShortestPath(nodes, node, end, shortestPath) ?: shortestPath
}
}
val testInput = readStrings("Day12_test")
check(part1(testInput) == 31)
val input = readStrings("Day12")
println(part1(input))
check(part2(testInput) == 29)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f | 4,010 | aoc-2022 | Apache License 2.0 |
src/Day12.kt | realpacific | 573,561,400 | false | {"Kotlin": 59236} | import java.util.*
private data class Step(val position: Coordinate) {
fun generateNextSteps(heightmap: Array<Array<Char>>): List<Step> {
return arrayOf(
Step(this.position.first + 1 to this.position.second),
Step(this.position.first - 1 to this.position.second),
Step(this.position.first to this.position.second + 1),
Step(this.position.first to this.position.second - 1),
).filter { this.isPossible(heightmap, it) }
}
private fun isPossible(heightmap: Array<Array<Char>>, next: Step): Boolean {
val fromElevation = heightmap[this.position.first][this.position.second]
val toElevation = heightmap.getOrNull(next.position.first)?.getOrNull(next.position.second) ?: return false
val srcHeight = calculateHeight(fromElevation)
val destHeight = calculateHeight(toElevation)
return srcHeight <= destHeight + 1
}
}
private fun calculateHeight(elevation: Char): Int {
if (elevation == 'S') return 'a'.code
if (elevation == 'E') return 'z'.code
return elevation.code
}
fun main() {
fun print(shortestDistanceMatrix: List<MutableList<Int>>, heightmap: Array<Array<Char>>) {
for (row in shortestDistanceMatrix.indices) {
for (colIndex in shortestDistanceMatrix.first().indices) {
val elevation = heightmap[row][colIndex]
val distance = shortestDistanceMatrix[row][colIndex]
print(("$distance|$elevation").padEnd(4) + " ")
}
println()
}
}
/**
* Start from [endCoordinate], breadth first calculate distance of its neighbours
*/
fun buildShortestPathMatrix(heightmap: Array<Array<Char>>, endCoordinate: Coordinate): List<MutableList<Int>> {
val steps: Queue<MutableList<Step>> = ArrayDeque()
steps.add(mutableListOf(Step(endCoordinate)))
val shortestDistanceMatrix = List(heightmap.size) {
MutableList(heightmap.first().size) {
Int.MAX_VALUE
}
}
shortestDistanceMatrix[endCoordinate.first][endCoordinate.second] = 0 // distance of E from destination is 0
val visited = mutableSetOf<Step>()
visited.add(steps.first().first()) // add E to visited
while (steps.isNotEmpty()) {
val currentSteps = steps.remove()
currentSteps
.forEach { currentStep ->
visited.add(currentStep)
val nextMoves = currentStep.generateNextSteps(heightmap)
.onEach { next ->
shortestDistanceMatrix[next.position.first][next.position.second] =
minOf(
shortestDistanceMatrix[currentStep.position.first][currentStep.position.second] + 1,
shortestDistanceMatrix[next.position.first][next.position.second]
)
}
.filter { it !in visited }
.toMutableList()
.onEach { visited.add(it) }
steps.add(nextMoves)
}
}
// print(shortestDistanceMatrix, heightmap)
return shortestDistanceMatrix
}
fun part1(input: List<String>): Int {
var endCoordinate = 0 to 0
var startCoordinate = 0 to 0
val heightmap = Array(input.size) { row ->
Array(input.first().length) { col ->
val elevation = input[row][col]
if (elevation == 'E') endCoordinate = row to col
if (elevation == 'S') startCoordinate = row to col
elevation
}
}
return buildShortestPathMatrix(heightmap, endCoordinate)[startCoordinate.first][startCoordinate.second]
}
fun part2(input: List<String>): Int {
var endCoordinate = 0 to 0
val possibleStartLocation = mutableListOf<Coordinate>()
val heightmap = Array(input.size) { row ->
Array(input.first().length) { col ->
val elevation = input[row][col]
if (elevation == 'E') endCoordinate = row to col
if (elevation == 'S' || elevation == 'a') possibleStartLocation.add(row to col)
elevation
}
}
val path = buildShortestPathMatrix(heightmap, endCoordinate)
return possibleStartLocation.minOf { path[it.first][it.second] }
}
run {
val input = readInput("Day12_test")
println(part1(input))
println(part2(input))
}
run {
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
}
| 0 | Kotlin | 0 | 0 | f365d78d381ac3d864cc402c6eb9c0017ce76b8d | 4,794 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | Miguel1235 | 726,260,839 | false | {"Kotlin": 21105} | private fun obtainNewSequence(sequence: List<Int>): List<Int> {
val newSequence: List<Int> = mutableListOf()
for (i in 1..<sequence.size) {
val curr = sequence[i]
val prev = sequence[i - 1]
newSequence.addLast(curr - prev)
}
return newSequence
}
private val string2IntList = { input: String -> input.split(" ").map { it.toInt() } }
private val isZeroSequence = { sequence: List<Int> -> sequence.filter { it == 0 }.size == sequence.size }
private fun obtainSequences(history: String): List<List<Int>> {
val sequence = string2IntList(history)
val sequences: List<List<Int>> = mutableListOf(sequence)
do {
val newSeq = obtainNewSequence(sequences.last())
sequences.addLast(newSeq)
} while (!isZeroSequence(newSeq))
return sequences
}
private val predictNextHistoryValue =
{ sequences: List<List<Int>> -> sequences.fold(0) { acc: Int, sq: List<Int> -> acc + sq.last() } }
private fun predictValPart2(sequences: List<List<Int>>): Int {
val sp = fillPlaceHolders(sequences)
for (i in sp.size - 1 downTo 1) {
val prev = sp[i]
val curr = sp[i - 1]
val x = curr[1] - prev.first()
sp[i - 1][0] = x
}
return sp.first().first()
}
private fun fillPlaceHolders(sequences: List<List<Int>>): List<MutableList<Int>> {
val sequenceWithPlaceHolders: MutableList<MutableList<Int>> = mutableListOf()
for (sequence in sequences) {
if (isZeroSequence(sequence)) {
sequence.addFirst(0)
sequenceWithPlaceHolders.addLast(sequence.toMutableList())
continue
}
sequence.addFirst(999)
sequenceWithPlaceHolders.addLast(sequence.toMutableList())
}
return sequenceWithPlaceHolders
}
private val part1 = { input: List<String> ->
input.fold(0) { acc: Int, history -> acc + predictNextHistoryValue(obtainSequences(history)) }
}
private val part2 =
{ input: List<String> -> input.fold(0) { acc: Int, history -> acc + predictValPart2(obtainSequences(history)) } }
fun main() {
val testInput = readInput("Day09_test")
check(part1(testInput) == 114)
check(part2(testInput) == 2)
val input = readInput("Day09")
check(part1(input) == 1581679977)
check(part2(input) == 889)
}
| 0 | Kotlin | 0 | 0 | 69a80acdc8d7ba072e4789044ec2d84f84500e00 | 2,289 | advent-of-code-2023 | MIT License |
src/Day04.kt | msernheim | 573,937,826 | false | {"Kotlin": 32820} | fun main() {
fun sectionsToInterval(sections: String): IntRange {
val split = sections.split("-")
return when {
split.size > 1 -> IntRange(split[0].toInt(), split[1].toInt())
else -> IntRange(sections.toInt(), sections.toInt())
}
}
fun isOverlapping(rangeA: IntRange, rangeB: IntRange): Boolean {
return when {
rangeA.first < rangeB.first -> rangeA.last >= rangeB.last
rangeB.first < rangeA.first -> rangeB.last >= rangeA.last
else -> true
}
}
fun part1(input: List<String>): Int {
var count = 0
input.forEach { pair ->
val intervals = pair.split(",").map { elf -> sectionsToInterval(elf) }
if (isOverlapping(intervals[0], intervals[1])) count++
}
return count
}
fun hasAnyOverlap(rangeA: IntRange, rangeB: IntRange): Boolean {
return when {
rangeA.first < rangeB.first -> rangeB.contains(rangeA.last) || rangeA.last > rangeB.last
rangeB.first < rangeA.first -> rangeA.contains(rangeB.last) || rangeB.last > rangeA.last
else -> true
}
}
fun part2(input: List<String>): Int {
var count = 0
input.forEach { pair ->
val intervals = pair.split(",").map { elf -> sectionsToInterval(elf) }
if (hasAnyOverlap(intervals[0], intervals[1])) count++
}
return count
}
val input = readInput("Day04")
val part1 = part1(input)
val part2 = part2(input)
println("Result part1: $part1")
println("Result part2: $part2")
}
| 0 | Kotlin | 0 | 3 | 54cfa08a65cc039a45a51696e11b22e94293cc5b | 1,637 | AoC2022 | Apache License 2.0 |
2022/src/main/kotlin/day8_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.IntGrid
import utils.Solution
import utils.Vec2i
import utils.takeWhileInclusive
fun main() {
Day8Imp.run()
}
object Day8Imp : Solution<IntGrid>() {
override val name = "day8"
override val parser = IntGrid.singleDigits
override fun part1(input: IntGrid): Int {
val rows = input.rows.flatMap { row -> getAscending(row.cells) + getAscending(row.cells.reversed()) }
val cols = input.columns.flatMap { col -> getAscending(col.cells) + getAscending(col.cells.reversed()) }
val trees = (rows + cols).distinct().sortedBy { it.y * 10 + it.x }
return trees.count()
}
override fun part2(input: IntGrid): Int {
return input.coords.maxOf { scenicScore(it, input) }
}
private fun scenicScore(coord: Vec2i, grid: IntGrid): Int {
val height = grid[coord]
val left = getVisibleDistance(height, grid.rows[coord.y].values.take(coord.x).reversed())
val right = getVisibleDistance(height, grid.rows[coord.y].values.drop(coord.x + 1))
val up = getVisibleDistance(height, grid[coord.x].values.take(coord.y).reversed())
val down = getVisibleDistance(height, grid[coord.x].values.drop(coord.y + 1))
return left * right * up * down
}
private fun getAscending(trees: Collection<Pair<Vec2i, Int>>): Collection<Vec2i> {
var curMax = Integer.MIN_VALUE
val ret = mutableListOf<Vec2i>()
for (tree in trees) {
if (tree.second > curMax) {
ret.add(tree.first)
curMax = tree.second
}
}
return ret
}
private fun getVisibleDistance(anchor: Int, trees: Collection<Int>): Int {
return trees.takeWhileInclusive { it < anchor }.count()
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,641 | aoc_kotlin | MIT License |
src/Day16.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | data class Room(val rate: Int, val dest: List<String>)
fun main() {
val leftMatcher = "Valve\\s(?<valve>\\w{2}).+rate=(?<rate>\\d+)".toRegex()
fun parse(input: List<String>): Map<String, Room> {
val tunnelsMap = mutableMapOf<String, Room>()
for (line in input) {
val (left, right) = line.split(';')
val groups = leftMatcher.matchEntire(left)!!.groups
val valve = groups["valve"]!!.value
val rate = groups["rate"]!!.value.toInt()
val tmp = right.removePrefix(" tunnels lead to valves ").
removePrefix(" tunnel leads to valve ")
tunnelsMap[valve] = Room(rate, tmp.split(", "))
}
return tunnelsMap
}
fun traverse(tunnels: Map<String, Room>, curValve: String, minutesLeft: Int, initialStates: Set<String>): Map<Set<String>, Int> {
// <Room, Time left> -> best score
val cache = mutableMapOf<Triple<String, Set<String>, Int>, Int>()
// Room -> time from valve on
val states = mutableMapOf<String, Boolean>()
val stateScore = mutableMapOf<Set<String>, Int>()
for (valve in tunnels.keys) {
if (tunnels[valve]!!.rate > 0) {
states[valve] = false
}
if (initialStates.contains(valve)) {
states[valve] = true
}
}
fun inner(curValve: String, minutesLeft: Int, scoreSoFar: Int, openedValves: Set<String>) {
if (stateScore.getOrDefault(openedValves, -1) < scoreSoFar) {
stateScore[openedValves] = scoreSoFar
}
val cacheKey = Triple(curValve, openedValves, minutesLeft)
if (cache.getOrDefault(cacheKey, -1) >= scoreSoFar) {
return
}
cache[cacheKey] = scoreSoFar
if (minutesLeft < 2 || openedValves.size == states.size) {
return
}
val rate = tunnels[curValve]!!.rate
for (dest in tunnels[curValve]!!.dest) {
// if valve is already turned on, it is meaningless to turn it off again
if (rate > 0 && !states[curValve]!!) {
states[curValve] = true
inner(
dest,
minutesLeft - 2,
scoreSoFar + (minutesLeft - 1) * rate,
states.filterValues { it }.keys
)
states[curValve] = false
}
inner(dest, minutesLeft - 1, scoreSoFar, openedValves)
}
}
inner(curValve, minutesLeft, 0, states.filterValues { it }.keys)
return stateScore
}
fun part1(input: List<String>): Int {
return traverse(parse(input), "AA", 30, emptySet()).values.max()
}
fun part2(input: List<String>): Int {
val minutesLeft = 26
val parsed = parse(input)
val openedValves = traverse(parsed, "AA", minutesLeft, emptySet())
return openedValves.toList().parallelStream().map{
(opened, value) -> traverse(parsed, "AA", minutesLeft, opened).values.max() + value
}.toList().max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 3,530 | aoc2022 | Apache License 2.0 |
src/day05/Day05.kt | skokovic | 573,361,100 | false | {"Kotlin": 12166} | package day05
import readInputText
val moveRegex = """move\s+(\d+)\s+from\s+(\d+)\s+to\s+(\d+)""".toRegex()
data class Move(val count: Int, val from: Int, val to: Int)
fun createStacks(str: String): Map<Int, ArrayDeque<Char>> {
val lines = str.lines()
val stackNums = lines[lines.size - 1].trim().split("\\s+".toRegex())
val stacks = stackNums.associate { it.toInt() to ArrayDeque<Char>() }
lines.dropLast(1).reversed().forEach {
for (i in 1 until it.length step 4) {
if (it[i] != ' ') {
stacks[i/4+1]?.addLast(it[i])
}
}
}
return stacks
}
fun createMoves(str: String): List<Move> {
val lines = str.lines()
val moves = lines.map {
val (count, from, to) = moveRegex.matchEntire(it)!!.destructured
Move(count.toInt(), from.toInt(), to.toInt())
}.toList()
return moves
}
fun moveStacks(stacks: Map<Int, ArrayDeque<Char>>, moves: List<Move>, reverse: Boolean = false): Map<Int, ArrayDeque<Char>> {
moves.forEach {
val tempQueue = ArrayDeque<Char>()
for(i in 0 until it.count){
tempQueue.addLast(stacks[it.from]!!.removeLast())
}
if(reverse && !tempQueue.isEmpty()) tempQueue.reverse()
for(c in tempQueue){
stacks[it.to]!!.addLast(c)
}
}
return stacks
}
fun main() {
fun part1(stacks: Map<Int, ArrayDeque<Char>>, moves: List<Move>): String {
val movedStacks = moveStacks(stacks, moves)
return movedStacks.values.map { it.removeLast() }.joinToString("")
}
fun part2(stacks: Map<Int, ArrayDeque<Char>>, moves: List<Move>): String {
val movedStacks = moveStacks(stacks, moves, true)
return movedStacks.values.map { it.removeLast() }.joinToString("")
}
val input = readInputText("Day05")
val (stackString, moveString) = input.split("\n\n")
val stacks = createStacks(stackString)
val moves = createMoves(moveString)
val copy = hashMapOf<Int, ArrayDeque<Char>>()
stacks.forEach {
val tempArr = ArrayDeque<Char>()
tempArr.addAll(it.value)
copy[it.key] = tempArr
}
println(part1(stacks, moves))
println(part2(copy, moves))
}
| 0 | Kotlin | 0 | 0 | fa9aee3b5dd09b06bfd5c232272682ede9263970 | 2,231 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/anahoret/aoc2022/day19/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day19
import java.io.File
import kotlin.math.max
import kotlin.math.min
import kotlin.system.measureTimeMillis
typealias ResourcePile = Map<Resource, Int>
enum class Resource(val priority: Int) {
ORE(0),
CLAY(1),
OBSIDIAN(2),
GEODE(3)
}
class Blueprint(val id: Int, val robotCosts: Map<Resource, ResourcePile>) {
companion object {
private val blueprintRegex =
"Blueprint (.*): Each ore robot costs (.*) ore. Each clay robot costs (.*) ore. Each obsidian robot costs (.*) ore and (.*) clay. Each geode robot costs (.*) ore and (.*) obsidian.".toRegex()
fun parse(str: String): Blueprint {
val groups = blueprintRegex.find(str)!!.groupValues.mapNotNull(String::toIntOrNull)
val id = groups[0]
val oreRobotCost = mapOf(Resource.ORE to groups[1])
val clayRobotCost = mapOf(Resource.ORE to groups[2])
val obsidianRobotCost = mapOf(Resource.ORE to groups[3], Resource.CLAY to groups[4])
val geodeRobotCost = mapOf(Resource.ORE to groups[5], Resource.OBSIDIAN to groups[6])
return Blueprint(
id,
mapOf(
Resource.ORE to oreRobotCost,
Resource.CLAY to clayRobotCost,
Resource.OBSIDIAN to obsidianRobotCost,
Resource.GEODE to geodeRobotCost
)
)
}
}
override fun toString(): String {
return "Blueprint $id: Each ore robot costs ${robotCosts[Resource.ORE]!![Resource.ORE]} ore. Each clay robot costs ${robotCosts[Resource.CLAY]!![Resource.ORE]} ore. Each obsidian robot costs ${robotCosts[Resource.OBSIDIAN]!![Resource.ORE]} ore and ${robotCosts[Resource.OBSIDIAN]!![Resource.CLAY]} clay. Each geode robot costs ${robotCosts[Resource.GEODE]!![Resource.ORE]} ore and ${robotCosts[Resource.GEODE]!![Resource.OBSIDIAN]} obsidian."
}
fun getCost(resource: Resource): ResourcePile {
return robotCosts.getValue(resource)
}
}
fun parseBlueprints(str: String): List<Blueprint> {
return str.split("\n").map(Blueprint.Companion::parse)
}
fun main() {
val input = File("src/main/kotlin/com/anahoret/aoc2022/day19/input.txt")
.readText()
.trim()
val blueprints = parseBlueprints(input)
// Part 1
part1(blueprints).also { println("P1: ${it}ms") }
// Part 2
part2(blueprints).also { println("P2: ${it}ms") }
}
private fun part1(blueprints: List<Blueprint>) = measureTimeMillis {
blueprints.sumOf { it.id * evaluate(it, 24) }
.also(::println)
}
private fun part2(blueprints: List<Blueprint>) = measureTimeMillis {
blueprints.take(3).productOf { evaluate(it, 32) }
.also(::println)
}
inline fun <T> Iterable<T>.productOf(selector: (T) -> Int): Int {
var product = 1
for (element in this) {
product *= selector(element)
}
return product
}
data class CacheEntry(
val timeLeft: Int,
val storageOre: Int,
val storageClay: Int,
val storageObsidian: Int,
val storageGeode: Int,
val robotOre: Int,
val robotClay: Int,
val robotObsidian: Int,
val robotGeode: Int
)
fun evaluate(blueprint: Blueprint, time: Int): Int {
val maxOrePrice = blueprint.robotCosts.maxOf { it.value[Resource.ORE] ?: 0 }
val maxClayPrice = blueprint.robotCosts.maxOf { it.value[Resource.CLAY] ?: 0 }
val maxObsidianPrice = blueprint.robotCosts.maxOf { it.value[Resource.OBSIDIAN] ?: 0 }
val resourcesSortedByPriority = Resource.values()
.sortedByDescending(Resource::priority) + null
var maxGeodes = 0
val cache = hashSetOf<CacheEntry>()
fun loop(
timeLeft: Int,
storageOre: Int,
storageClay: Int,
storageObsidian: Int,
storageGeode: Int,
robotOre: Int,
robotClay: Int,
robotObsidian: Int,
robotGeode: Int
) {
if (robotOre > maxOrePrice || robotClay > maxClayPrice || robotObsidian > maxObsidianPrice) return
if (timeLeft == 0) {
maxGeodes = max(maxGeodes, storageGeode)
return
}
val potentialGeodes = storageGeode + timeLeft * ((robotGeode + robotGeode + timeLeft) / 2)
if (potentialGeodes <= maxGeodes) return
val cacheEntry = CacheEntry(
timeLeft,
storageOre,
storageClay,
storageObsidian,
storageGeode,
robotOre,
robotClay,
robotObsidian,
robotGeode
)
if (cache.contains(cacheEntry)) return
cache.add(cacheEntry)
val postProdOre = storageOre + robotOre
val postProdClay = storageClay + robotClay
val postProdObsidian = storageObsidian + robotObsidian
val postProdGeode = storageGeode + robotGeode
val canSpendOre = maxOrePrice * timeLeft
val canSpendClay = maxClayPrice * timeLeft
val canSpendObsidian = maxObsidianPrice * timeLeft
resourcesSortedByPriority.forEach { robotTypeToBuild ->
if (robotTypeToBuild != null) {
val cost = blueprint.getCost(robotTypeToBuild)
val canBuild = storageOre >= cost.getOrDefault(Resource.ORE, 0) &&
storageClay >= cost.getOrDefault(Resource.CLAY, 0) &&
storageObsidian >= cost.getOrDefault(Resource.OBSIDIAN, 0)
if (!canBuild) return@forEach
val newStorageOre = postProdOre - (cost[Resource.ORE] ?: 0)
val newStorageClay = postProdClay - (cost[Resource.CLAY] ?: 0)
val newStorageObsidian = postProdObsidian - (cost[Resource.OBSIDIAN] ?: 0)
val newStorageGeode = postProdGeode - (cost[Resource.GEODE] ?: 0)
val newRobotOre = if (robotTypeToBuild == Resource.ORE) robotOre + 1 else robotOre
val newRobotClay = if (robotTypeToBuild == Resource.CLAY) robotClay + 1 else robotClay
val newRobotObsidian = if (robotTypeToBuild == Resource.OBSIDIAN) robotObsidian + 1 else robotObsidian
val newRobotGeode = if (robotTypeToBuild == Resource.GEODE) robotGeode + 1 else robotGeode
loop(
timeLeft - 1,
min(canSpendOre, newStorageOre),
min(canSpendClay, newStorageClay),
min(canSpendObsidian, newStorageObsidian),
newStorageGeode,
newRobotOre,
newRobotClay,
newRobotObsidian,
newRobotGeode
)
} else {
loop(
timeLeft - 1,
min(canSpendOre, postProdOre),
min(canSpendClay, postProdClay),
min(canSpendObsidian, postProdObsidian),
postProdGeode,
robotOre,
robotClay,
robotObsidian,
robotGeode
)
}
}
}
loop(
time,
storageOre = 0,
storageClay = 0,
storageObsidian = 0,
storageGeode = 0,
robotOre = 1,
robotClay = 0,
robotObsidian = 0,
robotGeode = 0
)
return maxGeodes
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 7,408 | advent-of-code-2022 | Apache License 2.0 |
src/Day02_first.kt | ChristianNavolskyi | 573,154,881 | false | {"Kotlin": 29804} | import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
enum class Weapon(val opponent: Char, val me: Char, val value: Int) {
ROCK('A', 'X', 1), PAPER('B', 'Y', 2), SCISSORS('C', 'Z', 3);
companion object {
private val opponentMap: Map<Char, Weapon> = mapOf(Pair('A', ROCK), Pair('B', PAPER), Pair('C', SCISSORS))
private val meMap: Map<Char, Weapon> = mapOf(Pair('X', ROCK), Pair('Y', PAPER), Pair('Z', SCISSORS))
fun byOpponent(opponent: Char): Weapon = opponentMap[opponent]!!
fun byMe(me: Char): Weapon = meMap[me]!!
}
}
class Fight(
private val opponent: Weapon,
private val me: Weapon
) {
fun evaluate(): Int = me.value + when (me) {
Weapon.ROCK -> pointsRock[opponent]!!
Weapon.PAPER -> pointsPaper[opponent]!!
Weapon.SCISSORS -> pointsScissors[opponent]!!
}
companion object {
val pointsRock: Map<Weapon, Int> = mapOf(Pair(Weapon.ROCK, 3), Pair(Weapon.PAPER, 0), Pair(Weapon.SCISSORS, 6))
val pointsPaper: Map<Weapon, Int> = mapOf(Pair(Weapon.ROCK, 6), Pair(Weapon.PAPER, 3), Pair(Weapon.SCISSORS, 0))
val pointsScissors: Map<Weapon, Int> = mapOf(Pair(Weapon.ROCK, 0), Pair(Weapon.PAPER, 6), Pair(Weapon.SCISSORS, 3))
}
}
@ExperimentalTime
fun main() {
fun part1(input: List<String>): Int {
return input.map {
val parts = it.split(" ")
Fight(Weapon.byOpponent(parts[0].first()), Weapon.byMe(parts[1].first()))
}.sumOf { it.evaluate() }
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
// check(part2(testInput) == 45000)
val input = readLines("Day02")
val firstTime = measureTime {
part1(input)
part1(input)
part1(input)
part1(input)
}.div(4)
println("Times")
println("First part took: $firstTime")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 222e25771039bdc5b447bf90583214bf26ced417 | 2,114 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | import kotlin.math.abs
object Day15 {
const val EXPECTED_PART1_CHECK_ANSWER = 26
const val EXPECTED_PART2_CHECK_ANSWER = 56000011L
const val PART1_CHECK_ROW = 10
const val PART1_ROW = 2_000_000
const val PART2_CHECK_MAX = 20
const val PART2_MAX = 4_000_000
const val PART2_MULTIPLY_VALUE = 4_000_000
}
fun main() {
fun String.parseSensorAndBeaconCoordinatess(): Pair<Coordinates, Coordinates> {
val (sensorX, sensorY, beaconX, beaconY) = Regex("Sensor at x=([-\\d]+), y=([-\\d]+): closest beacon is at x=([-\\d]+), y=([-\\d]+)")
.matchEntire(this)
?.destructured ?: error("Should match regex")
return Coordinates(sensorX.toInt(), sensorY.toInt()) to Coordinates(beaconX.toInt(), beaconY.toInt())
}
data class RowInfo(val positionsCovered: Int, val notCovered: Coordinates?)
fun rowInfo(
row: Int,
gridMin: Int,
gridMax: Int,
sensorAndBeaconCoordinates: List<Pair<Coordinates, Coordinates>>
): RowInfo {
val coveredRangesOnRow = mutableListOf<IntRange>()
for (sensorAndBeaconCoordinate in sensorAndBeaconCoordinates) {
val sensorLocation = sensorAndBeaconCoordinate.first
val beaconLocation = sensorAndBeaconCoordinate.second
val distance = abs(sensorLocation.x - beaconLocation.x) + abs(sensorLocation.y - beaconLocation.y)
val positionsCoveredAtSensorRow = distance * 2 + 1
val yDistanceToCheckRow = abs(sensorLocation.y - row)
val positionsCoveredAtCheckRow = positionsCoveredAtSensorRow - yDistanceToCheckRow * 2
if (positionsCoveredAtCheckRow > 0) {
val xFrom = maxOf(gridMin, sensorLocation.x - (positionsCoveredAtCheckRow / 2))
val xTo = minOf(gridMax, sensorLocation.x + (positionsCoveredAtCheckRow / 2))
val range = xFrom..xTo
coveredRangesOnRow.add(range)
val overlappingRanges =
coveredRangesOnRow
.filter { range.first in it || range.last in it || it.first in range || it.last in range }
if (overlappingRanges.isNotEmpty()) {
val mergedRange = overlappingRanges.reduce { acc, intRange ->
minOf(acc.first, intRange.first)..maxOf(
acc.last,
intRange.last
)
}
coveredRangesOnRow.add(mergedRange)
overlappingRanges.forEach { coveredRangesOnRow.remove(it) }
}
}
}
val coveredCount = coveredRangesOnRow.sumOf { it.count() }
val notCovered = if (gridMax - gridMin - coveredCount >= 0) {
// find in ranges the open position..
if (coveredRangesOnRow.size == 1) {
if (coveredRangesOnRow[0].first > gridMin) {
gridMin
} else {
gridMax
}
} else {
coveredRangesOnRow
.sortedBy { it.first }
.windowed(2)
.first { it.first().last + 1 < it[1].first }
.let { it.first().last + 1 }
}
} else null
return RowInfo(coveredCount, if (notCovered != null) Coordinates(notCovered, row) else null)
}
fun part1(input: List<String>, checkRow: Int): Int {
val sensorAndBeaconCoordinates = input.map(String::parseSensorAndBeaconCoordinatess)
val (min, max) = sensorAndBeaconCoordinates.flatMap { listOf(it.first, it.second) }.findMinAndMax()
val beaconCoordinates = sensorAndBeaconCoordinates.map { it.second }
val beaconsOnCheckRow = beaconCoordinates.toSet().filter { it.y == checkRow }.size
return rowInfo(checkRow, min.x, max.x, sensorAndBeaconCoordinates).positionsCovered - beaconsOnCheckRow
}
fun part2(input: List<String>, max: Int): Long {
val sensorAndBeaconCoordinates = input.map(String::parseSensorAndBeaconCoordinatess)
var notCoveredRow: RowInfo? = null
for (row in max downTo 0) {
val rowInfo = rowInfo(row, 0, max, sensorAndBeaconCoordinates)
println("Row $row")
if (rowInfo.notCovered != null) {
notCoveredRow = rowInfo
break
}
}
if (notCoveredRow != null) {
return notCoveredRow.notCovered!!.x.toLong() * Day15.PART2_MULTIPLY_VALUE + notCoveredRow.notCovered!!.y
}
return -1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
println("Checking")
check(part1(testInput, Day15.PART1_CHECK_ROW) == Day15.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput, Day15.PART2_CHECK_MAX) == Day15.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
println("On real data")
val input = readInput("Day15")
println(part1(input, Day15.PART1_ROW))
println(part2(input, Day15.PART2_MAX))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 5,153 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2023/Day15.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
class Day15 {
fun part1(input: String): Int = input
.split(',', '\n')
.filter { it.isNotEmpty() }
.sumOf { getHash(it) }
fun part2(input: String): Int {
val lensHashMap = IntRange(0, 255).map { mutableListOf<Pair<String, Int>>() }.toMutableList()
val instructions = input.split(',', '\n').filter { it.isNotEmpty() }
for (instruction in instructions) {
val lens = instruction.takeWhile { it != '=' && it != '-' }
val hash = getHash(lens)
val lenses = lensHashMap[hash]
if (instruction.endsWith('-')) {
lenses.removeIf { it.first == lens }
} else {
val focalLength = instruction.split('=')[1].toInt()
val idx = lenses.indexOfFirst { it.first == lens }
if (idx == -1) {
lenses.add(lens to focalLength)
} else {
lenses[idx] = lens to focalLength
}
}
}
return lensHashMap
.withIndex()
.map { (boxIdx, lenses) ->
lenses.withIndex()
.map { Lens(boxId = boxIdx, slotNumber = it.index + 1, focalLength = it.value.second) }
}
.flatten()
.sumOf { it.calculateFocusPower() }
}
private fun getHash(value: String): Int {
var hash = 0
value.forEach { hash = (hash + it.code) * 17 % 256 }
return hash
}
data class Lens(val boxId: Int, val slotNumber: Int, val focalLength: Int) {
fun calculateFocusPower(): Int = (boxId + 1) * slotNumber * focalLength
}
}
fun main() {
val day15 = Day15()
val input = readInputAsString("day15.txt")
println("15, part 1: ${day15.part1(input)}")
println("15, part 2: ${day15.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 1,877 | advent-of-code-2023 | MIT License |
src/main/kotlin/com/sk/set0/56. Merge Intervals.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set0
import java.util.LinkedList
import java.util.Stack
class Solution56 {
fun merge(intervals: Array<IntArray>): Array<IntArray> {
if (intervals.isEmpty()) return emptyArray()
intervals.sortBy { it[0] } // sort with start time
val result = ArrayList<IntArray>()
for (i in intervals.indices) {
val curr = intervals[i]
if (i == 0) {
result.add(curr)
continue
}
val pre = result.last()
if (curr[0] <= pre[1]) { // Is curr start overlap with previous interval?
pre[1] = maxOf(pre[1], curr[1])
} else { // Its start of new interval
result.add(curr)
}
}
return result.toTypedArray()
}
}
// ================================================================================================
//region-Solution-2
private class Solution2 {
private var graph = HashMap<IntArray, MutableList<IntArray>>()
private var nodesInComp = HashMap<Int, MutableList<IntArray>>()
private var visited = HashSet<IntArray>()
// return whether two intervals overlap (inclusive)
private fun overlap(a: IntArray, b: IntArray): Boolean {
return a[0] <= b[1] && b[0] <= a[1]
}
// build a graph where an undirected edge between intervals u and v exists
// iff u and v overlap.
private fun buildGraph(intervals: Array<IntArray>) {
graph.clear()
nodesInComp.clear()
visited.clear()
for (interval in intervals) {
graph[interval] = LinkedList()
}
for (interval1 in intervals) {
for (interval2 in intervals) {
if (overlap(interval1, interval2)) {
graph[interval1]?.add(interval2)
graph[interval2]?.add(interval1)
}
}
}
}
// merges all the nodes in this connected component into one interval.
private fun mergeNodes(nodes: List<IntArray>): IntArray {
val min: Int = nodes.minBy { ints -> ints[0] }[0] ?: 0
val max: Int = nodes.maxBy { ints -> ints[1] }[1] ?: 0
return intArrayOf(min, max)
}
// use depth-first search to mark all nodes in the same connected component
// with the same integer.
private fun markComponentDFS(start: IntArray, compNumber: Int) {
val stack = Stack<IntArray>()
stack.add(start)
while (!stack.isEmpty()) {
val node = stack.pop()
if (!visited.contains(node)) {
visited.add(node)
if (nodesInComp[compNumber] == null) {
nodesInComp[compNumber] = LinkedList()
}
nodesInComp[compNumber]?.add(node)
graph[node]?.forEach { stack.add(it) }
}
}
}
// gets the connected components of the interval overlap graph.
private fun buildComponents(intervals: Array<IntArray>) {
nodesInComp = HashMap()
visited = HashSet()
var compNumber = 0
for (interval in intervals) {
if (!visited.contains(interval)) {
markComponentDFS(interval, compNumber)
compNumber++
}
}
}
fun merge(intervals: Array<IntArray>): Array<IntArray> {
buildGraph(intervals)
buildComponents(intervals)
// for each component, merge all intervals into one interval.
val merged: MutableList<IntArray> = LinkedList()
for (element in nodesInComp.values) {
merged.add(mergeNodes(element))
}
return merged.toTypedArray()
}
}
//endregion
//region - similar question
/**
* https://leetcode.com/problems/meeting-rooms/
*/
//endregion
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 3,809 | leetcode-kotlin | Apache License 2.0 |
src/Day04.kt | szymon-kaczorowski | 572,839,642 | false | {"Kotlin": 45324} | fun main() {
fun part1(input: List<String>): Int {
return input.map {
it.split(",")
}.map {
var firstElf = it[0].split("-")
var secondElf = it[1].split("-")
(firstElf[0].toInt()..firstElf[1].toInt()) to (secondElf[0].toInt()..secondElf[1].toInt())
}.filter {
println(it)
(it.first.start <= it.second.start && it.first.endInclusive >= it.second.endInclusive)
||
(it.second.start <= it.first.start && it.second.endInclusive >= it.first.endInclusive)
}.size.also { println(it) }
}
fun part2(input: List<String>): Int {
return input.map {
it.split(",")
}.map {
var firstElf = it[0].split("-")
var secondElf = it[1].split("-")
(firstElf[0].toInt()..firstElf[1].toInt()) to (secondElf[0].toInt()..secondElf[1].toInt())
}.filter {
println(it)
(it.first.start <= it.second.start
&& it.first.endInclusive >= it.second.start)
||
(it.second.start <= it.first.start
&& it.second.endInclusive >= it.first.start)
}.size.also { println(it) }
}
// 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 | 1d7ab334f38a9e260c72725d3f583228acb6aa0e | 1,559 | advent-2022 | Apache License 2.0 |
src/Day13.kt | jwklomp | 572,195,432 | false | {"Kotlin": 65103} | fun main() {
/**
* Custom compare to compare nested arrays based on the integers in them.
*/
fun compareFn(left: Any, right: Any): Int {
// both integers
if (left is Int && right is Int) return left.compareTo(right)
// both lists
if (left is List<*> && right is List<*>) {
var i = 0
while (i < left.size && i < right.size) {
val compareResult = compareFn(left[i]!!, right[i]!!)
if (compareResult != 0) return compareResult
i++
}
return left.size.compareTo(right.size)
}
// Int vs List
if (left is Int) return compareFn(listOf(left), right)
// List vs Int
if (right is Int) return compareFn(left, listOf(right))
error("illegal state")
}
fun part1(input: List<String>): Int =
input
.asSequence()
.filter { it != "" }
.map { parseStringToNestedArray(it) }
.chunked(2)
.mapIndexed { index, it -> if (compareFn(it.first(), it.last()) == -1) index + 1 else 0 }
.sum()
fun part2(input: List<String>): Int {
val dv1 = parseStringToNestedArray("[[2]]")
val dv2 = parseStringToNestedArray("[[6]]")
val list = (input
.filter { it != "" }
.map { parseStringToNestedArray(it) } + listOf(dv1, dv2))
.sortedWith { a, b -> compareFn(a, b) }
val index1 = list.indexOf(dv1) + 1
val index2 = list.indexOf(dv2) + 1
return (index1 * index2)
}
val testInput = readInput("Day13_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1b1121cfc57bbb73ac84a2f58927ab59bf158888 | 1,797 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day04/Day04.kt | TheRishka | 573,352,778 | false | {"Kotlin": 29720} | package day04
import readInput
import kotlin.math.max
import kotlin.math.min
fun main() {
/*
//
min(7, 8) <= min(24, 8) = true // actually true
min(2, 37) <= min(75, 51) = true // actually true
min(47,20) <= min(78, 39)
// approach 1
min(24, 8) - max(7, 8) = 8 - 8 = 0
min(75, 51) - max(2, 37) = 51 - 37 = 14
min(78, 39) - max(47, 20) = 39 - 47 = -8
min(91, 53) - max(53, 34) = 53 - 53 = 0
min(78, 39) - max(47, 20) = 39 - 47 = -8
min(78, 39) - max(47, 20) = 39 - 47 = -8
(min(endInclusive, other.endInclusive) - max(start, other.start))
.coerceAtLeast(0.0)
*/
fun isContainedIn(first: IntRange, second: IntRange) = when {
first.first <= second.first && first.last >= second.last -> true
second.first <= first.first && second.last >= first.last -> true
else -> false
}
fun isOverlapped(first: IntRange, second: IntRange) = when {
//2..75, 37..90
//37..90, 2..75
isContainedIn(first, second) -> true
first.first <= second.first && first.last >= second.first -> true
second.first <= first.first && second.last >= first.first -> true
else -> false
}
fun part1(input: List<Pair<IntRange, IntRange>>): Int {
var containedCounter = 0
input.forEach {
if (isContainedIn(it.first, it.second)) {
containedCounter++
}
}
return containedCounter
}
fun part2(input: List<Pair<IntRange, IntRange>>): Int {
var overlapCounter = 0
input.forEach {
if (isOverlapped(it.first, it.second)) {
overlapCounter++
}
}
return overlapCounter
}
val input = readInput("day04/Day04")
val elfPairs = input.chunked(1) {
it[0].split(",")
}.map {
stringToIntRange(it[0]) to stringToIntRange(it[1])
}
println(part1(elfPairs))
println(part2(elfPairs))
}
fun stringToIntRange(input: String) = with(input.split("-")) {
IntRange(get(0).toInt(), get(1).toInt())
}
| 0 | Kotlin | 0 | 1 | 54c6abe68c4867207b37e9798e1fdcf264e38658 | 2,097 | AOC2022-Kotlin | Apache License 2.0 |
src/Day09.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
fun isEnd(head: Pair<Int, Int>, tail: Pair<Int, Int>): Boolean {
return head.first - 1 <= tail.first && head.first + 1 >= tail.first && head.second - 1 <= tail.second && head.second + 1 >= tail.second
}
fun step(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
val newX = if (head.first > tail.first) {
tail.first + 1
} else if (head.first < tail.first) {
tail.first - 1
} else {
tail.first
}
val newY = if (head.second > tail.second) {
tail.second + 1
} else if (head.second < tail.second) {
tail.second - 1
} else {
tail.second
}
return Pair(newX, newY)
}
fun part1(input: List<String>): Int {
var head = Pair(0, 0)
var tail = Pair(0, 0)
val set = mutableSetOf(tail)
for (it in input) {
val direction = it.substringBefore(' ')
val steps = it.substringAfter(' ').toInt()
for (count in 1..steps) {
head = when (direction) {
"R" -> Pair(head.first + 1, head.second)
"L" -> Pair(head.first - 1, head.second)
"U" -> Pair(head.first, head.second + 1)
else -> Pair(head.first, head.second - 1)
}
while (!isEnd(head, tail)) {
tail = step(head, tail)
set.add(tail)
}
}
}
return set.size
}
fun part2(input: List<String>): Int {
val rope = MutableList(10) { Pair(0, 0) }
val set = hashSetOf(Pair(0, 0))
for (it in input) {
val direction = it.substringBefore(' ')
val steps = it.substringAfter(' ').toInt()
for (count in 1..steps) {
rope[0] = when (direction) {
"R" -> Pair(rope[0].first + 1, rope[0].second)
"L" -> Pair(rope[0].first - 1, rope[0].second)
"U" -> Pair(rope[0].first, rope[0].second + 1)
else -> Pair(rope[0].first, rope[0].second - 1)
}
for (i in 1 until rope.size) {
while (!isEnd(rope[i - 1], rope[i])) {
rope[i] = step(rope[i - 1], rope[i])
if (i == rope.size - 1) {
set.add(rope[i])
}
}
}
}
}
return set.size
}
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 2,869 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | Misano9699 | 572,108,457 | false | null | fun main() {
fun splitInTwo(rucksack: String): List<Set<Char>> =
listOf(rucksack.take(rucksack.length / 2).toSet(), rucksack.takeLast(rucksack.length / 2).toSet())
fun priority(item: Char): Int = when {
item.isLowerCase() -> item.code - 96 // lowercase a starts at 97 in ASCII table
else -> item.code - 38 // uppercase A starts at 65
}
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val compartments = splitInTwo(rucksack)
priority(compartments[0].toSet().intersect(compartments[1].toSet()).first())
}
}
fun part2(input: List<String>): Int {
val rucksacks = input.splitIntoNumberOfLists(3)
return rucksacks.sumOf {
priority(it[0].toSet().intersect((it[1].toSet().intersect(it[2].toSet()))).first())
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
val input = readInput("Day03")
check(part1(testInput).also { println("Answer test input part1: $it") } == 157)
println("Answer part1: " + part1(input))
check(part2(testInput).also { println("Answer test input part2: $it") } == 70)
println("Answer part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | adb8c5e5098fde01a4438eb2a437840922fb8ae6 | 1,273 | advent-of-code-2022 | Apache License 2.0 |
Algorithms/src/main/kotlin/LargestPalindromicNumber.kt | ILIYANGERMANOV | 557,496,216 | false | {"Kotlin": 74485} | /**
* # Largest Palindromic Number
* Problem:
* https://leetcode.com/problems/largest-palindromic-number/
*/
class LargestPalindromicNumber {
fun largestPalindromic(num: String): String {
val digits = intArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
for (c in num) {
val digit = c.digitToInt()
digits[digit] += 1
}
val available = digits.mapIndexed { digit, count ->
digit to count
}.filter { (_, count) ->
count > 0
}.sortedWith { (digit1, count1), (digit2, count2) ->
/**
* Returns zero if the arguments are equal,
* a negative number if the first argument is less than the second,
* or a positive number if the first argument is greater than the second.
*/
val oneRank = (if (count1 > 1) 100 else 0) + digit1
val twoRank = (if (count2 > 1) 100 else 0) + digit2
twoRank - oneRank// sort descending
}
val mirror = mirror(available)
val palindrome = palindrome(mirror)
// Filter leading 0's
return if (palindrome.first() == '0') {
palindrome.replace("0", "").takeIf { it.isNotEmpty() } ?: "0"
} else palindrome
}
private fun palindrome(mirror: Pair<String, String?>): String {
val (str, left) = mirror
return if (left != null)
str + left + str.reversed()
else str + str.reversed()
}
private fun mirror(available: List<Pair<Int, Int>>): Pair<String, String?> {
fun biggestLeftover(currentDigit: Int, secondLeft: String?): Int {
val secondLeftSafe = secondLeft?.toInt() ?: 0
val next = available.getOrNull(1)?.first
?: return maxOf(currentDigit, secondLeftSafe)
return if (next > currentDigit) {
maxOf(next, secondLeftSafe)
} else maxOf(currentDigit, secondLeftSafe)
}
if (available.isEmpty()) return "" to null
val (digit, count) = available.first()
return if (count.isEven()) {
val first = digit.toString().repeat(count / 2)
val (secondStr, secondLeft) = mirror(available.drop(1))
first + secondStr to secondLeft
} else {
if (count > 1) {
// not even; count >= 3
val first = digit.toString().repeat((count - 1) / 2)
val (secondStr, secondLeft) = mirror(available.drop(1))
first + secondStr to biggestLeftover(
currentDigit = digit,
secondLeft = secondLeft
).toString()
} else {
// count = 1
"" to digit.toString()
}
}
}
private fun Int.isEven(): Boolean = this % 2 == 0
} | 0 | Kotlin | 0 | 1 | 4abe4b50b61c9d5fed252c40d361238de74e6f48 | 2,857 | algorithms | MIT License |
src/Day07.kt | kmakma | 574,238,598 | false | null | fun main() {
fun buildFileSystem(input: List<String>): Directory {
val root = Directory(null, "/")
var currentDir: Directory = root
val iter = input.iterator()
while (iter.hasNext()) {
val line = iter.next()
when {
line == "$ cd /" -> currentDir = root
line == "$ ls" -> continue
line == "$ cd .." -> currentDir = currentDir.parent!!
line.startsWith("$ cd") -> currentDir = currentDir.cd(line)
else -> currentDir.new(line)
}
}
return root
}
fun part1(input: Directory): Long {
return input.sumOfUnderSize(100_000)
}
fun part2(input: Directory): Long? {
// 70M: available, free 30M required
val missingSpace = 30_000_000 - 70_000_000L + input.size
return input.smallestDirBigger(missingSpace)
}
val input = buildFileSystem(readInput("Day07"))
println(part1(input))
println(part2(input))
}
interface FileSystem {
fun sumOfUnderSize(sizeLimit: Long): Long
fun smallestDirBigger(minimum: Long): Long?
val parent: Directory?
val name: String
val size: Long
}
class Day07File(override val parent: Directory, override val name: String, override val size: Long) : FileSystem {
override fun sumOfUnderSize(sizeLimit: Long): Long = 0L
override fun smallestDirBigger(minimum: Long) = null // we don't want a file
}
class Directory(override val parent: Directory?, override val name: String) : FileSystem {
override val size: Long
get() = content.values.sumOf { it.size }
private val content: MutableMap<String, FileSystem> = mutableMapOf()
operator fun get(line: String): FileSystem {
return content[line.removePrefix("$ cd ")] ?: error("$name has no such file: $line")
}
fun cd(line: String): Directory {
val file = this[line]
return if (file is Directory) file else error("$name has no such dir: $line")
}
fun new(line: String) {
when {
line.startsWith("dir") -> {
val newName = line.removePrefix("dir ")
content.putIfAbsent(newName, Directory(this, newName))
}
line.startsWith('$') -> error("bad new file $line")
else -> {
val (size, newName) = line.split(' ', limit = 2)
content.putIfAbsent(newName, Day07File(this, newName, size.toLong()))
}
}
}
override fun sumOfUnderSize(sizeLimit: Long): Long {
return content.values.sumOf { it.sumOfUnderSize(sizeLimit) } + if (size <= sizeLimit) size else 0
}
override fun smallestDirBigger(minimum: Long): Long? {
if (this.size < minimum) return null // we could filter it instead using null, but that's good enough
return content.values
.mapNotNull { it.smallestDirBigger(minimum) }
.minOrNull()
?: this.size
}
}
| 0 | Kotlin | 0 | 0 | 950ffbce2149df9a7df3aac9289c9a5b38e29135 | 3,009 | advent-of-kotlin-2022 | Apache License 2.0 |
2021/app/src/main/kotlin/net/sympower/aok2021/tonis/Day03.kt | tonisojandu | 573,036,346 | false | {"Rust": 158858, "Kotlin": 15806, "Shell": 1265} | package net.sympower.aok2021.tonis
fun main() {
println("1st: ${day03Part01("/Day03.in")}")
println("2nd: ${day03Part02("/Day03.in")}")
}
fun day03Part01(fileIn: String): Int {
val numbers = readLineFromResource(fileIn) { it }
val threshold = numbers.size / 2
val overThreshold = numbers
.map { it.toCharArray() }
.flatMap { chars -> Array(chars.size) { it }.filter { chars[chars.size - it - 1] == '1' } }
.groupBy { it }
.map { it.key to it.value.size }
.filter { it.second > threshold } // no explanation if there are equal amounts
.map { it.first }
.toSet()
val maxShift = overThreshold.maxOf { it }
val gammaRate = overThreshold.shiftAndReduce()
val epsilonRate = Array(maxShift) { it }.filter { !overThreshold.contains(it) }.shiftAndReduce()
return gammaRate * epsilonRate
}
fun day03Part02(fileIn: String): Int {
val numbers = readLineFromResource(fileIn) { it.toCharArray() }
val maxLength = numbers.maxOf { it.size }
val largest = Array(maxLength) { it }
.fold(numbers) { lastLargest, onIndex -> keepLargest(lastLargest, onIndex) }
.first()
.binaryToInt()
val smallest = Array(maxLength) { it }
.fold(numbers) { lastLargest, onIndex -> keepSmallest(lastLargest, onIndex) }
.first()
.binaryToInt()
return largest * smallest
}
fun keepSmallest(from: List<CharArray>, onIndex: Int): List<CharArray> {
return preferGroup(from, onIndex, '0') { it.value.size }
}
fun keepLargest(from: List<CharArray>, onIndex: Int): List<CharArray> {
return preferGroup(from, onIndex, '1') { -it.value.size }
}
fun preferGroup(
from: List<CharArray>,
onIndex: Int,
finallyPreferring: Char,
preferring: (Map.Entry<Char, List<CharArray>>) -> Int
): List<CharArray> {
if (from.size == 1) {
return from
}
val groupsOrderedBySize = from.groupBy { it[onIndex] }
.entries
.sortedBy(preferring)
.map { it.value }
if (groupsOrderedBySize[0].size == groupsOrderedBySize[1].size) {
return if (groupsOrderedBySize[0][0][onIndex] == finallyPreferring) {
groupsOrderedBySize[0]
} else {
groupsOrderedBySize[1]
}
}
return groupsOrderedBySize.first()
}
fun CharArray.binaryToInt(): Int {
return Array(this.size) { it }
.filter { this[this.size - it - 1] == '1' }
.shiftAndReduce()
}
fun Iterable<Int>.shiftAndReduce(): Int {
return this.map { 1 shl it }.reduce { a, b -> a or b }
} | 0 | Rust | 0 | 0 | 5ee0c3fb2e461dcfd4a3bdd7db3efae9a4d5aabd | 2,422 | to-advent-of-code | MIT License |
src/main/kotlin/utils/rangeUtils.kt | corneil | 572,437,852 | false | {"Kotlin": 93311, "Shell": 595} | package utils
/**
* This will return a range that combine the 2 range.
* It may result in one or more items since the 2 ranges may not overlap.
* The assumption is that ranges have an end that is the same or a higher value than the start.
*/
fun IntRange.intersect(r: IntRange): List<IntRange> {
val minR = if (first > r.first) r else this
val maxR = if (first > r.first) this else r
return when {
minR.first <= maxR.first && minR.last >= maxR.last -> listOf(minR)
maxR.first <= minR.first && maxR.last >= minR.last -> listOf(maxR)
minR.first < maxR.first && minR.last < maxR.first -> listOf(minR, maxR)
minR.last >= maxR.first && minR.last <= maxR.last -> listOf(minR.first..maxR.last)
else -> error("Invalid $minR, $maxR")
}
}
/**
* This removes a specific value from the range.
* This may result in more than one result if the input does fall inside the range excluding the start or end.
* The assumption is that ranges have an end that is the same or a higher value than the start.
*/
fun IntRange.exclude(input: Int): List<IntRange> = if (input in this) {
val split = mutableListOf<IntRange>()
if((first == input) && (last == input)) {
// do nothing
} else if (first == input) {
split.add((input + 1)..last)
} else if (last == input) {
split.add(first until input)
} else {
if (first < input + 1)
split.add(first until input)
if (input + 1 < last) {
split.add(input + 1..last)
}
}
split.toList()
} else {
listOf(this)
}
/**
* This will combine overlapping ranges and return a list with the smallest number of ranges that satisfies the requirements.
* The assumption is that ranges have an end that is the same or a higher value than the start.
*/
fun joinRanges(ranges: List<IntRange>): List<IntRange> {
if (ranges.isEmpty()) return emptyList()
val result = mutableSetOf<IntRange>()
result.addAll(ranges)
val drop = mutableSetOf<IntRange>()
fun intersectRange(range: IntRange) {
val input = result.sortedBy { it.first }.toList()
input.forEach {
val lst = it.intersect(range).toSet()
result.addAll(lst)
if (!lst.contains(range)) {
drop.add(range)
}
if (!lst.contains(it)) {
drop.add(it)
}
}
result.removeAll(drop)
}
ranges.forEach { range ->
intersectRange(range)
}
do {
val before = result.toSet()
intersectRange(result.maxByOrNull { it.first }!!)
} while (result != before)
return result.sortedBy { it.first }
}
| 0 | Kotlin | 0 | 0 | dd79aed1ecc65654cdaa9bc419d44043aee244b2 | 2,517 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day21/Day21.kt | gautemo | 317,316,447 | false | null | package day21
import shared.getLines
fun nonAllergensCount(input: List<String>): Int{
val foods = toAllergenInIngredient(input)
val allergens = mutableSetOf<String>()
val ingredients = mutableSetOf<String>()
foods.forEach {
allergens.addAll(it.allergens)
ingredients.addAll(it.ingredients)
}
val ingredientsWithAllergen = mutableListOf<String>()
for(allergen in allergens){
val canContain = foods.filter { it.allergens.contains(allergen) }.map { it.ingredients }.reduce { acc, list -> (acc intersect list).toList() }
ingredientsWithAllergen.addAll(canContain)
}
val ingredientsAllergenFree = ingredients subtract ingredientsWithAllergen
return ingredientsAllergenFree.sumBy { ingredient -> foods.count { food -> food.ingredients.contains(ingredient) } }
}
fun toAllergenInIngredient(input: List<String>): List<Food>{
return input.map { line ->
val allergensSection = Regex("""\(contains.+\)""").find(line)
val allergens = allergensSection!!.value.replace("(contains ", "").replace(")", "").split(',').map { it.trim() }
val ingredients = line.replace(Regex("""\(contains.+\)"""), "").split(" ").filter { it.isNotBlank() }
Food(ingredients, allergens)
}
}
class Food(val ingredients: List<String>, val allergens: List<String>)
fun main(){
val input = getLines("day21.txt")
val nonAllergenIngredientsCount = nonAllergensCount(input)
println(nonAllergenIngredientsCount)
val dangerous = dangerousList(input)
println(dangerous)
}
fun dangerousList(input: List<String>): String{
val foods = toAllergenInIngredient(input)
val allergens = mutableSetOf<String>()
val ingredients = mutableSetOf<String>()
foods.forEach {
allergens.addAll(it.allergens)
ingredients.addAll(it.ingredients)
}
val allergenMap = mutableMapOf<String, Set<String>>()
for(allergen in allergens){
val canContain = foods.filter { it.allergens.contains(allergen) }.map { it.ingredients }.reduce { acc, list -> (acc intersect list).toList() }
allergenMap[allergen] = canContain.toSet()
}
while (allergenMap.any { it.value.size > 1 }){
for(allergen in allergenMap){
if(allergen.value.size == 1){
for(other in allergenMap.filter { it.key != allergen.key }){
allergenMap[other.key] = other.value subtract allergen.value
}
}
}
}
return allergenMap.toList().sortedBy { it.first }.joinToString(","){ it.second.first() }
} | 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 2,582 | AdventOfCode2020 | MIT License |
src/Day08.kt | wmichaelshirk | 573,031,182 | false | {"Kotlin": 19037} | fun <T> Iterable<T>.takeUntil(predicate: (T) -> Boolean): Iterable<T> {
var shouldContinue = true
return takeWhile {
val result = shouldContinue
shouldContinue = !predicate(it)
result
}
}
fun main() {
fun part1(input: List<String>): Int {
val width = input[0].length
val length = input.size
return (0 until (width * length))
.count { index ->
val x = index % width
val y = index.floorDiv(width)
val row = input[y].map { it.digitToInt() }
val col = input.map { it[x].digitToInt() }
val hgt = row[x]
(x == 0) ||
(x == width - 1) ||
(y == 0) ||
(y == length - 1) ||
(row.take(x).maxOrNull() ?: -1 < hgt) ||
(row.drop(x + 1).maxOrNull() ?: -1 < hgt) ||
(col.take(y).maxOrNull() ?: -1 < hgt) ||
(col.drop(y + 1).maxOrNull() ?: -1 < hgt)
}
}
fun part2(input: List<String>): Int {
val width = input[0].length
val length = input.size
val maxScore = (0 until (width * length))
.maxOfOrNull { index ->
val x = index % width
val y = index.floorDiv(width)
val row = input[y].map { it.digitToInt() }
val col = input.map { it[x].digitToInt() }
val hgt = row[x]
val north = col.take(y).reversed().takeUntil { it >= hgt }.count()
val south = col.drop(y + 1).takeUntil { it >= hgt }.count()
val west = row.take(x).reversed().takeUntil { it >= hgt }.count()
val east = row.drop(x + 1).takeUntil { it >= hgt }.count()
north * west * east * south
} ?: -1
return maxScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | b748c43e9af05b9afc902d0005d3ba219be7ade2 | 2,219 | 2022-Advent-of-Code | Apache License 2.0 |
src/Day05.kt | xabgesagtx | 572,139,500 | false | {"Kotlin": 23192} | fun main() {
fun part1(input: List<String>): String {
val stacks = input.initialStackValues
input.moveLines.forEach { line ->
stacks.doMove9000(line)
}
return stacks.entries.sortedBy { it.key }.map { it.value.last() }.joinToString("")
}
fun part2(input: List<String>): String {
val stacks = input.initialStackValues
input.moveLines.forEach { line ->
stacks.doMove9001(line)
}
return stacks.entries.sortedBy { it.key }.map { it.value.last() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
private val List<String>.numberOfStacks: Int
get() {
val stackNumberLine = first { line -> line.trim().startsWith("1") }
return stackNumberLine.trim().split(" ").filter { it.isNotBlank() }.map { it.toInt() }.max()
}
private fun String.valueForStack(stack: Int): Char? {
val n = stack - 1
return this[n * 4 + 1].takeIf { it.isLetter() }
}
private val List<String>.initialStackLines: List<String>
get() = takeWhile { line -> !line.trim().startsWith("1") }.reversed()
private val List<String>.initialStackValues: Map<Int, MutableList<Char>>
get() {
val numberOfStacks = numberOfStacks
val stackLines = initialStackLines
return (1..numberOfStacks).associateWith { currentStack ->
stackLines.mapNotNull { line ->
line.valueForStack(currentStack)
}.toMutableList()
}
}
private val List<String>.moveLines: List<String>
get() {
return filter { it.startsWith("move") }
}
private fun Map<Int, MutableList<Char>>.doMove9000(command: String) {
val (numberOfItems, from, to) = command.split(" ").mapNotNull { it.toIntOrNull() }
repeat(numberOfItems) { this[to]!!.add(this[from]!!.removeLast()) }
}
private fun Map<Int, MutableList<Char>>.doMove9001(command: String) {
val (numberOfItems, from, to) = command.split(" ").mapNotNull { it.toIntOrNull() }
val items = (0 until numberOfItems).map {
this[from]!!.removeLast()
}.reversed()
this[to]!!.addAll(items)
} | 0 | Kotlin | 0 | 0 | 976d56bd723a7fc712074066949e03a770219b10 | 2,365 | advent-of-code-2022 | Apache License 2.0 |
solutions/aockt/y2023/Y2023D15.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.parse
import io.github.jadarma.aockt.core.Solution
object Y2023D15 : Solution {
/**
* A lens boxing operation.
* @property label The label of the lens to apply the operation on.
* @property box The ID of the box the operation should be performed in.
*/
private sealed class Operation(val label: String) {
val box: Int = hash(label)
/** An operation that should remove a lens from a box. */
class Remove(label: String) : Operation(label)
/** An operation that should replace or add a lens to a box. */
class Add(label: String, val focalLength: Int) : Operation(label)
}
/** A lens with a [focalLength] and identified by a [label]. */
private data class Lens(val label: String, val focalLength: Int)
/** An array of 256 boxes with lenses. */
private class HashBox {
private val boxes: Map<Int, MutableList<Lens>> = (0..<256).associateWith { mutableListOf() }
/** Apply the [operation] on the boxes and update their state. */
fun apply(operation: Operation): HashBox = apply {
val box = boxes.getValue(operation.box)
when (operation) {
is Operation.Add -> {
val lens = Lens(operation.label, operation.focalLength)
val existingLens = box.indexOfFirst { it.label == operation.label }
if (existingLens == -1) box.add(lens)
else box[existingLens] = lens
}
is Operation.Remove -> box.removeIf { it.label == operation.label }
}
}
/** Returns the total focusing power of all the lenses in all the boxes. */
val focusingPower: Int
get() = boxes.entries
.flatMap { (box, lenses) -> lenses.mapIndexed { slot, lens -> Triple(box, slot, lens) } }
.sumOf { (box, slot, lens) -> box.inc() * slot.inc() * lens.focalLength }
}
/** Calculates the Holiday ASCII String Helper value for the [string]. */
private fun hash(string: String): Int = string.fold(0) { hash, c -> hash.plus(c.code).times(17).rem(256) }
/** Parses the [input] and returns the list of [Operation]s described in the manual. */
private fun parseInput(input: String): List<Operation> = parse {
val addRegex = Regex("""^([a-z]+)=(\d)$""")
val removeRegex = Regex("""^([a-z]+)-$""")
input
.split(',')
.map {
val add = addRegex.matchEntire(it)
val remove = removeRegex.matchEntire(it)
when {
add != null -> Operation.Add(add.groupValues[1], add.groupValues[2].toInt())
remove != null -> Operation.Remove(remove.groupValues[1])
else -> error("Input does not match regex.")
}
}
}
override fun partOne(input: String) = input.split(',').sumOf(::hash)
override fun partTwo(input: String) = parseInput(input).fold(HashBox(), HashBox::apply).focusingPower
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,109 | advent-of-code-kotlin-solutions | The Unlicense |
src/day2/Day02.kt | armanaaquib | 572,849,507 | false | {"Kotlin": 34114} | package day2
import readInput
fun main() {
fun parseInput(input: List<String>) = input.map { it.split(" ") }
fun part1(input: List<String>): Int {
val data = parseInput(input)
val shapeScores = mapOf(Pair("X", 1), Pair("Y", 2), Pair("Z", 3))
val scores = mapOf(
Pair(listOf("A", "X"), 3),
Pair(listOf("A", "Y"), 6),
Pair(listOf("A", "Z"), 0),
Pair(listOf("B", "X"), 0),
Pair(listOf("B", "Y"), 3),
Pair(listOf("B", "Z"), 6),
Pair(listOf("C", "X"), 6),
Pair(listOf("C", "Y"), 0),
Pair(listOf("C", "Z"), 3),
)
var score = 0
for (round in data) {
score += shapeScores[round[1]]!!
score += scores[round]!!
}
return score
}
fun part2(input: List<String>): Int {
val data = parseInput(input)
val shapeScores = mapOf(Pair("X", 1), Pair("Y", 2), Pair("Z", 3))
val scores = mapOf(Pair("X", 0), Pair("Y", 3), Pair("Z", 6))
val wins = mapOf(
Pair("A", "Y"),
Pair("B", "Z"),
Pair("C", "X"),
)
val draws = mapOf(
Pair("A", "X"),
Pair("B", "Y"),
Pair("C", "Z"),
)
val loses = mapOf(
Pair("A", "Z"),
Pair("B", "X"),
Pair("C", "Y"),
)
val choices = mapOf(
Pair("X", loses),
Pair("Y", draws),
Pair("Z", wins),
)
var score = 0
for (round in data) {
val o = round[0]
val m = round[1]
score += scores[m]!!
score += shapeScores[choices[m]!![o]]!!
}
return score
}
// test if implementation meets criteria from the description, like:
check(part1(readInput("Day02_test")) == 15)
println(part1(readInput("Day02")))
check(part2(readInput("Day02_test")) == 12)
println(part2(readInput("Day02")))
}
| 0 | Kotlin | 0 | 0 | 47c41ceddacb17e28bdbb9449bfde5881fa851b7 | 2,030 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/twentytwentytwo/Day11.kt | JanGroot | 317,476,637 | false | {"Kotlin": 80906} | package twentytwentytwo
import java.math.BigInteger
fun main() {
val input = {}.javaClass.getResource("input-11.txt")!!.readText().split("\n\n");
val day = Day11(input)
println(day.part1())
println(day.part2())
}
class Day11(private val input: List<String>) {
fun part1(): Long {
val monkeys = input.map { it ->
val lines = it.lines()
val items = lines[1].split(": ")[1].split(", ").map { it.toBigInteger() }.toMutableList()
val op = lines[2].split("= ")[1]
val test = lines[3].split("by ")[1].toInt()
val targetTrue = lines[4].split("monkey ")[1].toInt()
val targetFalse = lines[5].split("monkey ")[1].toInt()
Monkey(items, op, test, targetTrue, targetFalse)
}
repeat(20) {
monkeys.forEachIndexed { i, it ->
println("$i : $it")
while (it.items.isNotEmpty()) {
var x = it.items.removeLast()
x = it.operate(x).divide(BigInteger.valueOf(3))
if (it.test(x)) monkeys[it.targetTrue ].items.add(x) else monkeys[it.targetFalse ].items.add(x)
}
}
}
val (a, b) = monkeys.sortedByDescending { monkey -> monkey.count }.map { it.count }.also { println(it) }
return a *b
}
fun part2(): Long {
val monkeys = input.map { it ->
val lines = it.lines()
val items = lines[1].split(": ")[1].split(", ").map { it.toBigInteger() }.toMutableList()
val op = lines[2].split("= ")[1]
val test = lines[3].split("by ")[1].toInt()
val targetTrue = lines[4].split("monkey ")[1].toInt()
val targetFalse = lines[5].split("monkey ")[1].toInt()
Monkey(items, op, test, targetTrue, targetFalse)
}
val modTotal = monkeys.map { it.test }.reduce { acc, i -> acc * i }.toBigInteger()
repeat(10_000) {
monkeys.forEachIndexed { i, it ->
while (it.items.isNotEmpty()) {
var x = it.items.removeLast()
x = it.operate(x).mod(modTotal)
if (it.test(x)) monkeys[it.targetTrue ].items.add(x) else monkeys[it.targetFalse ].items.add(x)
}
}
}
val (a, b) = monkeys.sortedByDescending { monkey -> monkey.count }.map { it.count }.also { println(it) }
return a *b
}
}
data class Monkey(val items: MutableList<BigInteger>, val op: String, val test: Int, val targetTrue: Int, val targetFalse: Int) {
var count = 0L
fun operate(item: BigInteger): BigInteger {
count++
return when (op) {
"old * old" -> item * item
"old + 2" -> item + BigInteger.valueOf(2)
"old + 1" -> item + BigInteger.valueOf(1)
"old + 8" -> item + BigInteger.valueOf(8)
"old + 4" -> item + BigInteger.valueOf(4)
"old + 5" -> item + BigInteger.valueOf(5)
"old * 17" -> item * BigInteger.valueOf(17)
"old * 13" -> item * BigInteger.valueOf(13)
else -> error("unknown op")
}
}
fun test(item: BigInteger) = item.mod(test.toBigInteger()) == BigInteger.ZERO
}
| 0 | Kotlin | 0 | 0 | 04a9531285e22cc81e6478dc89708bcf6407910b | 3,278 | aoc202xkotlin | The Unlicense |
src/day07/Day07.kt | EndzeitBegins | 573,569,126 | false | {"Kotlin": 111428} | package day07
import readInput
import readTestInput
import java.nio.file.Path
import kotlin.io.path.Path
import kotlin.io.path.div
private fun List<String>.toFileIndex(): Map<Path, Int> {
var path = Path("/")
val fileIndex = mutableMapOf<Path, Int>()
for (line in this) {
if (line.startsWith("$ cd")) {
val target = line.drop(5)
path = path.resolve(target).normalize()
} else {
val listedFileRegex = """^(\d+) (.+)$""".toRegex()
val regexMatch = listedFileRegex.matchEntire(line)
if (regexMatch != null) {
val (fileSize, fileName) = regexMatch.destructured
val filePath = path / fileName
fileIndex[filePath] = fileSize.toInt()
}
}
}
return fileIndex
}
private fun Map<Path, Int>.crawlForDirectories(): Set<Path> {
val directories: Set<Path> = flatMap { (file, _) ->
val directories = mutableListOf<Path>()
var path: Path? = file.parent
while (path != null) {
directories.add(path)
path = path.parent
}
directories
}.toSet()
return directories
}
private fun Set<Path>.calculateSizes(
fileIndex: Map<Path, Int>
): Map<Path, Int> {
val directorySizes: Map<Path, Int> = associateWith { directoryPath ->
fileIndex
.filterKeys { filePath -> filePath.startsWith(directoryPath) }
.values
.sum()
}
return directorySizes
}
private fun part1(input: List<String>): Int {
val fileIndex = input.toFileIndex()
val directories: Set<Path> = fileIndex.crawlForDirectories()
val directorySizes: Map<Path, Int> = directories.calculateSizes(fileIndex)
return directorySizes
.filterValues { directorySize -> directorySize <= 100000 }
.values
.sum()
}
private fun part2(input: List<String>): Int {
val fileIndex = input.toFileIndex()
val directories: Set<Path> = fileIndex.crawlForDirectories()
val directorySizes: Map<Path, Int> = directories.calculateSizes(fileIndex)
val spaceAvailable = 70000000
val spaceUsed = directorySizes.values.max()
val spaceFree = spaceAvailable - spaceUsed
val spaceRequired = 30000000
val spaceToClear = spaceRequired - spaceFree
return directorySizes
.filterValues { directorySize -> directorySize >= spaceToClear }
.minBy { (_, directorySize) -> directorySize }
.value
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day07")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebebdf13cfe58ae3e01c52686f2a715ace069dab | 2,792 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day18.kt | Fedannie | 572,872,414 | false | {"Kotlin": 64631} | class Coord3(val x: Int, val y: Int, val z: Int) {
private val delta = listOf(-1, 1)
val neighbours: List<Coord3>
get() {
val result = MutableList(0) { Coord3(0, 0, 0) }
for (d in delta) {
result.add(Coord3(x + d, y, z))
result.add(Coord3(x, y + d, z))
result.add(Coord3(x, y, z + d))
}
return result
}
override fun equals(other: Any?): Boolean {
return other is Coord3 && x == other.x && y == other.y && z == other.z
}
override fun hashCode(): Int {
return ((x to y) to z).hashCode()
}
override fun toString(): String {
return "{x=$x, y=$y, z=$z}"
}
}
fun main() {
fun parseInput(input: List<String>): List<Coord3> {
return input.map { it.split(",").map { it.toInt() } }.map { Coord3(it[0], it[1], it[2]) }
}
fun countFreeSides(cube: Coord3, valid: (Coord3) -> Boolean): Int = cube.neighbours.count { valid(it) }
fun part1(input: List<String>): Int {
val cubes = parseInput(input)
val setCubes = cubes.toSet()
return cubes.sumOf { countFreeSides(it) { !setCubes.contains(it) } }
}
fun markOuterWater(lava: Set<Coord3>): HashSet<Coord3> {
val visited = HashSet<Coord3>()
val from = lava.flatMap { listOf(it.x, it.y, it.z) }.min() - 1
val to = lava.flatMap { listOf(it.x, it.y, it.z) }.max() + 1
val borders = from .. to
fun valid(cube: Coord3): Boolean = cube.x in borders && cube.y in borders && cube.z in borders && !visited.contains(cube) && !lava.contains(cube)
val queue = MutableList(1) { Coord3(from, from, from) }
while (queue.isNotEmpty()) {
val current = queue.removeFirst()
if (!valid(current)) continue
visited.add(current)
queue.addAll(current.neighbours.filter { valid(it) })
}
return visited
}
fun part2(input: List<String>): Int {
val cubes = parseInput(input)
val water = markOuterWater(cubes.toSet())
return cubes.sumOf { countFreeSides(it) { water.contains(it) } }
}
val testInput = readInputLines("Day18_test")
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInputLines(18)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f | 2,182 | Advent-of-Code-2022-in-Kotlin | Apache License 2.0 |
src/Day02.kt | mvanderblom | 573,009,984 | false | {"Kotlin": 25405} | val ROCK = 1
val PAPER = 2
val SCICCORS = 3
val LOSS = 0
val TIE = 3
val WIN = 6
val inputMapping = mapOf(
"A" to ROCK,
"B" to PAPER,
"C" to SCICCORS
)
fun <K, V> Map<K, V>.pivot(): Map<V, List<K>> = this.entries.groupBy({it.value}, {it.key})
fun <K, V> List<Pair<K, V>>.toMap(): Map<K, V> = this.associate { it.first to it.second }
val outcomesByGameState = mapOf(
(ROCK to SCICCORS) to LOSS,
(PAPER to ROCK) to LOSS,
(SCICCORS to PAPER) to LOSS,
(SCICCORS to ROCK) to WIN,
(ROCK to PAPER) to WIN,
(PAPER to SCICCORS) to WIN,
(SCICCORS to SCICCORS) to TIE,
(ROCK to ROCK) to TIE,
(PAPER to PAPER) to TIE
)
val gameStatesByOutcome = outcomesByGameState
.pivot()
.mapValues { (_, values) -> values.toMap() }
fun main() {
val replyMaping = mapOf(
"X" to ROCK,
"Y" to PAPER,
"Z" to SCICCORS
)
val desiredOutcomeMapping = mapOf(
"X" to LOSS,
"Y" to TIE,
"Z" to WIN
)
val dayName = 2.toDayName()
fun part1(input: List<String>): Int = input
.map { it.split(" ") }
.map { (userMove, reply) -> inputMapping.getValue(userMove) to replyMaping.getValue(reply) }
.sumOf { gameState -> outcomesByGameState.getValue(gameState) + gameState.second}
fun part2(input: List<String>): Int = input
.map { it.split(" ") }
.map { (userMove, desiredOutcome) -> inputMapping.getValue(userMove) to desiredOutcomeMapping.getValue(desiredOutcome) }
.map { (userMove, desiredOutcome) -> desiredOutcome to gameStatesByOutcome.getValue(desiredOutcome).getValue(userMove) }
.sumOf { (outcome, reply) -> outcome + reply }
val testInput = readInput("${dayName}_test")
val input = readInput(dayName)
val testOutputPart1 = part1(testInput)
testOutputPart1 isEqualTo 15
val outputPart1 = part1(input)
outputPart1 isEqualTo 14264
val testOutputPart2 = part2(testInput)
testOutputPart2 isEqualTo 12
val outputPart2 = part2(input)
outputPart2 isEqualTo 12382
}
| 0 | Kotlin | 0 | 0 | ba36f31112ba3b49a45e080dfd6d1d0a2e2cd690 | 2,176 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/solutions/constantTime/iteration4/GCDTaxCalculator.kt | daniel-rusu | 669,564,782 | false | {"Kotlin": 70755} | package solutions.constantTime.iteration4
import dataModel.base.Money
import dataModel.base.Money.Companion.cents
import dataModel.base.TaxBracket
import dataModel.base.TaxCalculator
import solutions.constantTime.iteration3.MemorizedBracketTaxCalculator
import dataModel.v2.AccumulatedTaxBracket
import dataModel.v2.toAccumulatedBrackets
/**
* This is expected to be thousands of times more efficient than the [MemorizedBracketTaxCalculator].
*
* A detailed writeup is available here:
* https://itnext.io/impossible-algorithm-computing-income-tax-in-constant-time-716b3c36c012
*/
class GCDTaxCalculator(taxBrackets: List<TaxBracket>) : TaxCalculator {
private val greatestCommonDivisor = computeBracketSizeGCD(taxBrackets)
private val highestBracket: AccumulatedTaxBracket
private val roundedDownIncomeToBracket: Map<Money, AccumulatedTaxBracket>
init {
val accumulatedBrackets = taxBrackets.toAccumulatedBrackets()
highestBracket = accumulatedBrackets.last()
roundedDownIncomeToBracket = associateGCDMultiplesToTaxBrackets(accumulatedBrackets)
}
override fun computeTax(income: Money): Money {
val roundedDownIncome = income / greatestCommonDivisor * greatestCommonDivisor
return roundedDownIncomeToBracket[roundedDownIncome]?.computeTotalTax(income)
?: highestBracket.computeTotalTax(income)
}
/** Create a map associating each multiple of the GCD with its corresponding tax bracket */
private fun associateGCDMultiplesToTaxBrackets(
accumulatedBrackets: List<AccumulatedTaxBracket>,
): Map<Money, AccumulatedTaxBracket> {
val gcdAmount = Money.ofCents(greatestCommonDivisor)
var bracketIndex = 0
return generateSequence(0.cents) { it + gcdAmount }
.takeWhile { it < accumulatedBrackets.last().from }
// create a hashMap as "associateWith" creates a LinkedHashMap by default which uses more memory
.associateWithTo(HashMap()) { income ->
if (income >= accumulatedBrackets[bracketIndex].to!!) {
bracketIndex++
}
accumulatedBrackets[bracketIndex]
}
}
}
/** Computes the [gcd] of all the bracket sizes (in pennies) */
private fun computeBracketSizeGCD(taxBrackets: List<TaxBracket>): Long {
return taxBrackets.asSequence()
.filter { it.to != null } // ignore the last unbounded bracket
.map { it.to!!.cents - it.from.cents }
.reduceOrNull { result, size -> gcd(result, size) }
?: 1
}
/** Computes the greatest common divisor of [a] and [b] */
private fun gcd(a: Long, b: Long): Long = when (a) {
0L -> b
else -> gcd(b % a, a)
}
| 0 | Kotlin | 0 | 1 | 166d8bc05c355929ffc5b216755702a77bb05c54 | 2,728 | tax-calculator | MIT License |
src/Day07.kt | 6234456 | 572,616,769 | false | {"Kotlin": 39979} | data class Node(val name:String, val value: Int = -1, val children: MutableList<Node> = mutableListOf<Node>()){
fun size():Int{
if (!isDir()) return value
return children.fold(0){acc, node -> acc + node.size() }
}
fun isDir():Boolean = value < 0
}
fun main() {
fun buildTree(input: List<String>):Node{
val queue = java.util.LinkedList<Node>()
val tmp = java.util.LinkedList<Node>()
val regDigit = """^(\d+)\s+.+$""".toRegex()
val head = Node("/")
var current = head
queue.add(head)
input.forEach {
if (it.startsWith("dir")){
val n = Node(current.name + it.replaceFirst("dir ", "") + "/")
tmp.add(n)
current.children.add(n)
}else if(regDigit.matches(it)){
val arr = it.split(" ")
val n = Node(current.name + arr.last(), arr.first().toInt())
current.children.add(n)
}else{
if (it == "\$ ls"){
while (tmp.isNotEmpty()){
// Attention: addFirst
queue.addFirst(tmp.poll())
}
current = queue.poll()
}
}
}
return head
}
val map:MutableMap<Node, Int> = mutableMapOf()
fun walk(node: Node):Int{
if (!map.containsKey(node)){
map[node] = if (node.isDir()){
node.children.fold(0){
acc, n -> acc + walk(n)
}
} else node.value
}
return map[node]!!
}
fun part1(input: List<String>): Int {
walk(buildTree(input).apply {
println("size of root: ${this.size()}")
})
return map.filter { it.key.isDir() && it.value < 100000 }.values.fold(0){acc, i -> acc + i }
}
fun part2(input: List<String>): Int {
val root = buildTree(input)
walk(root)
val treeSet = java.util.TreeSet<Int>()
map.filter { it.key.isDir()}.values.forEach {
treeSet.add(it)
}
return treeSet.ceiling( map[root]!! - 40000000) ?: map[root]!!
}
var input = readInput("Test07")
println(part1(input))
println(part2(input))
input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b6d683e0900ab2136537089e2392b96905652c4e | 2,402 | advent-of-code-kotlin-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.