path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day02.kt | xNakero | 572,621,673 | false | {"Kotlin": 23869} | class Day02 {
private val rules: Map<String, Rules> = mapOf(
"A" to Rules("Y", "Z", "X"),
"B" to Rules("Z", "X", "Y"),
"C" to Rules("X", "Y", "Z")
)
private val points: Map<String, Int> = mapOf(
"X" to 1,
"Y" to 2,
"Z" to 3,
)
fun part1() = parseData()
.sumOf {
when {
isWin(it) -> 6 + points[it.player]!!
isDraw(it) -> 3 + points[it.player]!!
else -> points[it.player]!!
}
}
fun part2() = parseData()
.sumOf { match ->
when (match.player) {
"X" -> rules[match.opponent]!!.loses.let { points[it] }!!
"Y" -> rules[match.opponent]!!.draws.let { points[it] }!! + 3
else -> rules[match.opponent]!!.wins.let { points[it] }!! + 6
}
}
private fun parseData() = readInput("day02").map { Match(it[0].toString(), it[2].toString()) }
private fun isWin(match: Match): Boolean = rules[match.opponent]!!.wins == match.player
private fun isDraw(match: Match): Boolean = rules[match.opponent]!!.draws == match.player
}
data class Match(val opponent: String, val player: String)
data class Rules(val wins: String, val loses: String, val draws: String)
fun main() {
val day02 = Day02()
println(day02.part1())
println(day02.part2())
} | 0 | Kotlin | 0 | 0 | c3eff4f4c52ded907f2af6352dd7b3532a2da8c5 | 1,400 | advent-of-code-2022 | Apache License 2.0 |
src/day02/Day02.kt | lpleo | 572,702,403 | false | {"Kotlin": 30960} | package day02
import readInput
enum class Symbol(val encode: String, val value: Int) {
ROCK("A,X", 1),
PAPER("B,Y", 2),
SCISSOR("C,Z", 3);
companion object {
fun getSymbolByEncode(encode: String): Symbol? {
return Symbol.values().firstOrNull { symbol: Symbol ->
symbol.encode.split(",").any { encodeValue -> encodeValue == encode }
}
}
fun getWinningOver(symbol: Symbol): Symbol {
if (symbol == ROCK) return PAPER
if (symbol == SCISSOR) return ROCK
return SCISSOR
}
fun getLosingOver(symbol: Symbol): Symbol {
if (symbol == ROCK) return SCISSOR
if (symbol == SCISSOR) return PAPER
return ROCK
}
}
}
fun main() {
fun calculateAmount(otherSymbol: Symbol?, mySymbol: Symbol?): Int? {
val amount = mySymbol?.value
if (otherSymbol == Symbol.SCISSOR && mySymbol == Symbol.ROCK ||
otherSymbol == Symbol.ROCK && mySymbol == Symbol.PAPER ||
otherSymbol == Symbol.PAPER && mySymbol == Symbol.SCISSOR) {
return amount?.plus(6)
}
if (otherSymbol == mySymbol) {
return amount?.plus(3)
}
return amount;
}
fun calcResult1(symbols: List<String>): Int? {
val otherSymbol = Symbol.getSymbolByEncode(symbols[0])
val mySymbol = Symbol.getSymbolByEncode(symbols[1])
return calculateAmount(otherSymbol, mySymbol)
}
fun calcResult2(symbols: List<String>): Int? {
val otherSymbol = Symbol.getSymbolByEncode(symbols[0])
if ("Z" == symbols[1]) {
return calculateAmount(otherSymbol, Symbol.getWinningOver(otherSymbol!!))
}
if ("X" == symbols[1]) {
return calculateAmount(otherSymbol, Symbol.getLosingOver(otherSymbol!!));
}
return calculateAmount(otherSymbol, otherSymbol);
}
fun part1(input: List<String>): Int {
return input.map { row -> row.split(" ") }.map { symbols -> calcResult1(symbols) }.reduce { x, y -> x?.plus(y!!) }!!
}
fun part2(input: List<String>): Int {
return input.map { row -> row.split(" ") }.map { symbols -> calcResult2(symbols) }.reduce { x, y -> x?.plus(y!!) }!!
}
val testInput = readInput("files/Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("files/Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 115aba36c004bf1a759b695445451d8569178269 | 2,530 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day14.kt | w8mr | 572,700,604 | false | {"Kotlin": 140954} | package aoc2022
import aoc.*
import aoc.parser.*
import java.util.*
class Day14 {
data class Line(val start: Coord, val end: Coord)
class State(val ls: List<Line>) {
fun build(): MutableMap<Int, TreeSet<Int>> {
val map = mutableMapOf<Int, TreeSet<Int>>()
ls.forEach { (start, end) ->
(minOf(start.x, end.x)..maxOf(start.x, end.x)).forEach { x ->
(minOf(start.y, end.y)..maxOf(start.y, end.y)).forEach { y ->
insert(map, x, y)
}
}
}
return map
}
val blocked: MutableMap<Int, TreeSet<Int>> = build()
private fun insert(map: MutableMap<Int, TreeSet<Int>>, x: Int, y: Int) {
map.compute(x) {
_, set -> when (set) {
null -> {
val s = TreeSet<Int>()
s.add(y)
s
}
else -> {
set.add(y)
set
}
}
}
}
private fun insert(x: Int, y: Int) = insert(blocked, x,y )
private fun findIntersect(x: Int, y: Int): Int? =
blocked[x]?.asSequence()?.dropWhile { i -> i < y }?.firstOrNull()
fun simulateSandDrop(): Boolean {
var x = 500
var y: Int? = 0
while (true) {
y = findIntersect(x, y!!)
if ((y == null) || (y == 0 && x ==500)){
return false
} else {
if (y == findIntersect(x - 1, y)) {
if (y == findIntersect(x + 1, y)) {
insert(x, y - 1)
return true
} else {
x++
}
} else {
x--
}
}
}
}
}
fun createLine(coords: List<Coord>): List<Line> =
coords.zipWithNext(::Line)
val coord = seq(number() followedBy ",", number(), ::Coord)
val line = coord sepBy " -> " followedBy "\n" map ::createLine
val lines = zeroOrMore(line) map { it.flatten() }
private fun solve(lines: List<Line>): Int {
val state = State(lines)
var count = -1
do {
count++
val r = state.simulateSandDrop()
} while (r)
return count
}
fun part1(input: String): Int {
val lines = lines.parse(input)
return solve(lines)
}
fun part2(input: String): Int {
val lines = lines.parse(input)
val lowestY = lines.fold(0) { acc, (start, end) -> maxOf(acc, start.y, end.y) }
val bottomY = lowestY + 2
val linesWithBottom = lines + listOf(Line(Coord(499-bottomY, bottomY), Coord(501+bottomY, bottomY)))
return solve(linesWithBottom)
}
}
| 0 | Kotlin | 0 | 0 | e9bd07770ccf8949f718a02db8d09daf5804273d | 3,016 | aoc-kotlin | Apache License 2.0 |
src/Day15.kt | dmstocking | 575,012,721 | false | {"Kotlin": 40350} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class Sensor(val x: Int, val y: Int, val bx: Int, val by: Int) {
val radius: Int = abs(bx - x) + abs(by - y)
companion object {
private val parseRegex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex()
fun parse(line: String): Sensor {
val result = parseRegex.matchEntire(line)!!
val (x, y, bx, by) = result.groupValues.drop(1).map { it.toInt() }
return Sensor(x, y, bx, by)
}
}
}
fun List<IntRange>.merge(): List<IntRange> {
var prev = this
var next = fold(emptyList<IntRange>()) { ranges, next ->
var found = false
ranges
.map { range ->
if (range.overlaps(next)) {
found = true
min(next.first, range.first)..max(next.last, range.last)
} else {
range
}
}
.let { ranges ->
if (found) {
ranges
} else {
ranges.plusElement(next)
}
}
}
while (next != prev) {
prev = next
next = next.fold(emptyList()) { ranges, next ->
var found = false
ranges
.map { range ->
if (range.overlaps(next) || next.overlaps(range)) {
found = true
min(next.first, range.first)..max(next.last, range.last)
} else {
range
}
}
.let { ranges ->
if (found) {
ranges
} else {
ranges.plusElement(next)
}
}
}
}
return next
}
fun main() {
fun part1(input: List<String>, row: Int): Int {
return input
.map { Sensor.parse(it) }
.let { sensors ->
val beaconsOnRow = sensors
.map { (_, _, x, y) -> x to y }
.filter { (_, y) -> y == row }
.map { (x) -> x }
return sensors
.flatMap { sensor ->
val (x, y, bx, by) = sensor
val distanceToRow = abs(row - y)
val halfOverlap = sensor.radius - distanceToRow
if (halfOverlap >= 0) {
(x-halfOverlap)..(x+halfOverlap)
} else {
emptyList()
}
}
.toSet()
.minus(beaconsOnRow)
.size
}
}
fun part2(input: List<String>): Long {
val sensors = input.map { Sensor.parse(it) }
(0..4_000_000).forEach { row ->
sensors
.mapNotNull { sensor ->
val (x, y, _, _) = sensor
val distanceToRow = abs(row - y)
val halfOverlap = sensor.radius - distanceToRow
if (halfOverlap >= 0) {
(x-halfOverlap)..(x+halfOverlap)
} else {
null
}
}
.merge()
.let { ranges ->
// 100% not complete solution. If there was a range that went outside 0..4_000_000 this wouldn't
// work. But that happened to not occur in this problem.
if (ranges.size >= 2) {
val column = (ranges.maxOf { it.first } - 1).toLong()
return column * 4_000_000L + row.toLong()
}
}
}
throw Exception()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10).also { println(it) } == 26)
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e49d9247340037e4e70f55b0c201b3a39edd0a0f | 4,221 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day05/Day05.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day05
import Lines
import groupByBlanks
import runDay
import toStack
import kotlin.collections.ArrayDeque
fun main() {
fun part1(input: List<String>): String = input.parsed()
.moveCrates { stacks, instruction ->
repeat(instruction.count) {
val container = stacks[instruction.from].removeLast()
stacks[instruction.to].add(container)
}
}
.getTopCrate()
fun part2(input: List<String>): String = input.parsed()
.moveCrates { stacks, instruction ->
(1..instruction.count)
.map {
stacks[instruction.from].removeLast()
}
.reversed()
.let { stacks[instruction.to].addAll(it) }
}
.getTopCrate()
(object {}).runDay(
part1 = ::part1,
part1Check = "CMZ",
part2 = ::part2,
part2Check = "MCD"
)
}
private fun Stacks.getTopCrate() = map { it.last() }
.let {
String(it.toCharArray())
}
private fun ParsedInput.moveCrates(processInstruction: (Stacks, Instruction) -> Unit): Stacks = let { pair ->
val instructions = pair.second
val stacks = pair.first
instructions.forEach { processInstruction(stacks, it) }
stacks
}
private typealias ParsedInput = Pair<Stacks, List<Instruction>>
private fun Lines.parsed() =
groupByBlanks().let {
Pair(it[0].toStacks(), it[1].toInstructions())
}
private typealias Stacks = List<ArrayDeque<Char>>
fun List<String>.toStacks(): Stacks = reversed().let {
Pair(
it.first().toColumns(),
it.drop(1)
)
}.let { pair ->
pair.first.map { column ->
pair.second.map {
if (it.length > column) {
it[column]
} else {
' '
}
}.filter { it != ' ' }.toStack()
}
}.toList()
private val columnRegex = Regex("""\d+""")
private fun String.toColumns() =
columnRegex.findAll(this)
.map { it.range.first }
private data class Instruction(
val count: Int,
val from: Int,
val to: Int,
)
private const val COUNT = "count"
private const val FROM = "from"
private const val TO = "to"
private val instructionRegex =
Regex("""move (?<$COUNT>\d+) from (?<$FROM>\d+) to (?<$TO>\d+)""")
private fun List<String>.toInstructions(): List<Instruction> =
mapNotNull {
instructionRegex.find(it)
}.map {
Instruction(
count = it.groups[COUNT]!!.value.toInt(),
from = it.groups[FROM]!!.value.toInt() - 1,
to = it.groups[TO]!!.value.toInt() - 1,
)
}
| 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 2,654 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | import kotlin.math.abs
import kotlin.math.sign
class Knot(var x: Int, var y: Int)
fun solve(input: List<String>, ropeLength: Int): Int {
val totalSteps = mutableMapOf("L" to 0, "R" to 0, "U" to 0, "D" to 0)
input.forEach { x ->
run {
val (direction, count) = x.split(" ")
totalSteps[direction] = totalSteps[direction]!! + count.toInt()
}
}
val grid =
MutableList(totalSteps["U"]!! + totalSteps["D"]!! + 1) { _ -> MutableList(totalSteps["R"]!! + totalSteps["L"]!! + 1) { _ -> 0 } }
val rope = List(ropeLength) { _ -> Knot(totalSteps["L"]!!, totalSteps["U"]!!) }
grid[rope.last().y][rope.last().x] = 1
for (instruction in input) {
val direction = instruction.split(" ")[0]
val count = instruction.split(" ")[1].toInt()
repeat (count) {
when (direction) {
"L" -> rope[0].x -= 1
"R" -> rope[0].x += 1
"U" -> rope[0].y -= 1
"D" -> rope[0].y += 1
}
for (i in 1 until rope.size) {
if (abs(rope[i - 1].x - rope[i].x) > 1 || abs(rope[i - 1].y - rope[i].y) > 1) {
rope[i].x += (rope[i - 1].x - rope[i].x).sign
rope[i].y += (rope[i - 1].y - rope[i].y).sign
}
}
grid[rope.last().y][rope.last().x] = 1
}
}
// grid.forEach{line -> run { println(line.joinToString("")) }}
return grid.sumOf { line -> line.sum() }
}
fun main() {
println("Day 09")
val input = readInput("Day09")
println(solve(input, 2))
println(solve(input, 10))
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 1,649 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | A55enz10 | 573,364,112 | false | {"Kotlin": 15119} | import java.util.*
enum class Sign {ROCK, PAPER, SCISSORS}
fun main() {
fun part1(input: List<String>): Int {
val valueToSignP1 = mapOf("A" to Sign.ROCK, "B" to Sign.PAPER, "C" to Sign.SCISSORS)
val valueToSignP2 = mapOf("X" to Sign.ROCK, "Y" to Sign.PAPER, "Z" to Sign.SCISSORS)
val game = Game()
input.forEach {
val signs = it.split(" ")
game.playRound(valueToSignP1[signs[0]], valueToSignP2[signs[1]])
}
return game.scorePlayer2
}
fun getValueToPlay(sign1: Sign?, s2: String): Sign? {
val signToWin = mapOf(Sign.SCISSORS to Sign.ROCK, Sign.ROCK to Sign.PAPER, Sign.PAPER to Sign.SCISSORS)
val signToLose = mapOf(Sign.SCISSORS to Sign.PAPER, Sign.ROCK to Sign.SCISSORS, Sign.PAPER to Sign.ROCK)
return when (s2) {
"X" -> signToLose[sign1]
"Z" -> signToWin[sign1]
else -> sign1
}
}
fun part2(input: List<String>): Int {
val valueToSignP1 = mapOf("A" to Sign.ROCK, "B" to Sign.PAPER, "C" to Sign.SCISSORS)
val game = Game()
input.forEach {
val signs = it.split(" ")
game.playRound(valueToSignP1[signs[0]], getValueToPlay(valueToSignP1[signs[0]], signs[1]))
}
return game.scorePlayer2
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
class Game {
private val pointPerSign: Map<Sign, Int> = mapOf(Sign.ROCK to 1, Sign.PAPER to 2, Sign.SCISSORS to 3)
private var comparatorWheel = listOf(Sign.ROCK, Sign.PAPER, Sign.SCISSORS)
private var scorePlayer1 = 0
var scorePlayer2 = 0
fun playRound(signPlayer1: Sign?, signPlayer2: Sign?) {
scorePlayer1 += pointPerSign[signPlayer1]?: 0
scorePlayer2 += pointPerSign[signPlayer2]?: 0
// rotate the wheel until the player1 sign is center
Collections.rotate(comparatorWheel, 1-comparatorWheel.indexOf(signPlayer1))
when (1.compareTo(comparatorWheel.indexOf(signPlayer2))) {
-1 -> scorePlayer2 += 6
0 -> {
scorePlayer1 += 3
scorePlayer2 += 3
}
1 -> scorePlayer1 += 6
}
}
}
| 0 | Kotlin | 0 | 1 | 8627efc194d281a0e9c328eb6e0b5f401b759c6c | 2,265 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | mlidal | 572,869,919 | false | {"Kotlin": 20582} | import java.lang.IllegalArgumentException
fun main() {
fun sumPriorities(input: List<Char>) : Int {
return input.sumOf { char: Char ->
val value = if (char.isUpperCase()) {
char.code - 'A'.code + 27
} else {
char.code - 'a'.code + 1
}
value
}
}
fun part1(input: List<String>): Int {
val sharedItems = mutableListOf<Char>()
input.forEach {
val parts = listOf(it.substring(0, it.length / 2), it.substring(it.length / 2))
val duplicates = parts[0].filter { char -> parts[1].contains(char) }.toSet()
sharedItems.addAll(duplicates)
}
val sum = sumPriorities(sharedItems)
return sum
}
fun parseLine2(line: String) : Pair<Hand, Hand> {
val hands = line.split(" ").take(2)
if (hands.size == 2) {
val other = Hand.getHand(hands[0])
val mine = Hand.getHand(other, Result.parseResult(hands[1]))
return Pair(other, mine)
} else {
throw IllegalArgumentException("Unable to parse line $line")
}
}
fun findBadge(input: List<String>) : Char {
return input[0].first { input[1].contains(it) && input[2].contains(it) }
}
fun part2(input: List<String>): Int {
val groups = input.chunked(3)
val badges = groups.map { findBadge(it) }
return sumPriorities(badges)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
println()
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bea7801ed5398dcf86a82b633a011397a154a53d | 1,763 | AdventOfCode2022 | Apache License 2.0 |
src/year2021/03/Day03.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2021.`03`
import readInput
fun main() {
fun parse(input: List<String>): List<List<Boolean>> {
return input
.map { line ->
line.split("")
.filter { it.isNotBlank() }
.map { bitline ->
when (bitline) {
"0" -> false
"1" -> true
else -> error("Illegal: $bitline")
}
}
}
}
fun parseToPairsOfCounts(items: List<List<Boolean>>): List<Pair<Int, Int>> {
val result = List(items.first().size) { index ->
val ones = items.count {
it[index]
}
val zeroes = items.count {
it[index].not()
}
zeroes to ones
}
return result
}
fun part1Extraction(
result: List<Pair<Int, Int>>,
zeroChar: Char,
oneChar: Char,
): Int {
val epsilon = result.map { (zero, one) ->
when {
zero > one -> oneChar
zero < one -> zeroChar
else -> error("Illegal")
}
}
.joinToString("") { it.toString() }
.toInt(2)
return epsilon
}
fun part1(input: List<String>): Int {
val items = parse(input)
val result = parseToPairsOfCounts(items)
val epsilon = part1Extraction(result, '0', '1')
val gamma = part1Extraction(result, '1', '0')
return gamma * epsilon
}
fun part2subpart1(
input: List<String>,
zeroChar: Char,
oneChar: Char,
): List<String> {
var buffItems = input
var index = 0
while (buffItems.size > 1) {
val boolsPairs = parse(buffItems)
val result = parseToPairsOfCounts(boolsPairs)
val (zero, one) = result[index]
buffItems = when {
zero > one -> buffItems.filter { it[index] == zeroChar }
zero < one -> buffItems.filter { it[index] == oneChar }
else -> buffItems.filter { it[index] == oneChar }
}
index++
}
return buffItems
}
fun part2(input: List<String>): Int {
val num1 = part2subpart1(input, '0', '1').first().toInt(2)
val num2 = part2subpart1(input, '1', '0').first().toInt(2)
return num1 * num2
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part2(testInput) == 230)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 2,737 | KotlinAdventOfCode | Apache License 2.0 |
src/Day03.kt | stevennoto | 573,247,572 | false | {"Kotlin": 18058} | fun main() {
fun part1(input: List<String>): Int {
// Split each string into 2 halves, find intersection = char that's in both halves, map to numeric value
return input.map {
val firstHalf = it.substring(0, it.length/2)
val secondHalf = it.substring(it.length/2)
firstHalf.toCharArray().intersect(secondHalf.toList()).first()
}.map {
if (it in 'A'..'Z') (it - 'A' + 27) else (it - 'a' + 1)
}.sum()
}
fun part2(input: List<String>): Int {
// Group input into sets of 3, find intersection of all 3, map to numeric value
return input.chunked(3).map {
val intersectOfFirstTwo = it[0].toCharArray().intersect(it[1].toList())
intersectOfFirstTwo.intersect(it[2].toList()).first()
}.map {
if (it in 'A'..'Z') (it - 'A' + 27) else (it - 'a' + 1)
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 42941fc84d50b75f9e3952bb40d17d4145a3036b | 1,190 | adventofcode2022 | Apache License 2.0 |
2023/src/main/kotlin/Day19.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import Day19.Rule.Outcome
import java.util.regex.Pattern
private enum class Category { X, M, A, S }
private typealias Part = Map<Category, Int>
private typealias PartRange = Map<Category, IntRange>
object Day19 {
fun part1(input: String): Int {
val system = parse(input)
val acceptedParts = system.parts.filter { part -> processPart(system.workflows, part) }
return acceptedParts.sumOf { it.values.sum() }
}
private fun processPart(workflows: Map<String, Workflow>, part: Part): Boolean {
var workflow = workflows["in"]!!
while (true) {
when (val next = processWorkflow(workflow, part)) {
is Rule.Jump -> workflow = workflows[next.workflow]!!
is Rule.Result -> return next.accepted
}
}
}
private fun processWorkflow(workflow: Workflow, part: Part): Outcome {
workflow.rules.forEach { rule ->
if (rule is Outcome) {
return rule
}
if (rule is Rule.ConditionalJump && matchesRule(rule, part)) {
return rule.outcome
}
}
throw IllegalStateException("Should always match last rule!")
}
private fun matchesRule(rule: Rule.ConditionalJump, part: Part): Boolean {
val rating = part[rule.category]!!
return when (rule.comparison) {
Comparison.LESS_THAN -> rating < rule.value
Comparison.GREATER_THAN -> rating > rule.value
}
}
//////////////////////////////////////////////////////
fun part2(input: String): Long {
val system = parse(input)
val initialPart = Category.entries.associateWith { (1..4000) }
val initialWorkflow = system.workflows["in"]!!
return processRange(system.workflows, initialWorkflow, initialPart)
}
private fun processRange(workflows: Map<String, Workflow>, workflow: Workflow, partRange: PartRange): Long {
when (val rule = workflow.rules.first()) {
is Rule.ConditionalJump -> {
val currRange = partRange[rule.category]!!
val trueRange: IntRange
val falseRange: IntRange
when (rule.comparison) {
Comparison.LESS_THAN -> {
trueRange = (currRange.first..<rule.value)
falseRange = (rule.value..currRange.last)
}
Comparison.GREATER_THAN -> {
falseRange = (currRange.first..rule.value)
trueRange = (rule.value + 1..currRange.last)
}
}
val truePartRange = partRange + mapOf(rule.category to trueRange)
val falsePartRange = partRange + mapOf(rule.category to falseRange)
val trueOutcome = when (rule.outcome) {
is Rule.Jump -> processRange(workflows, workflows[rule.outcome.workflow]!!, truePartRange)
is Rule.Result -> if (rule.outcome.accepted) truePartRange.numCombinations() else 0
}
val falseOutcome =
processRange(workflows, workflow.copy(rules = workflow.rules.drop(1)), falsePartRange)
return trueOutcome + falseOutcome
}
is Rule.Jump -> return processRange(workflows, workflows[rule.workflow]!!, partRange)
is Rule.Result -> return if (rule.accepted) partRange.numCombinations() else 0
}
}
private fun PartRange.numCombinations() = this.values.map { it.last - it.first + 1L }.reduce(Long::times)
private enum class Comparison { LESS_THAN, GREATER_THAN }
private sealed class Rule {
data class ConditionalJump(
val category: Category,
val comparison: Comparison,
val value: Int,
val outcome: Outcome
) : Rule()
sealed class Outcome : Rule()
data class Jump(val workflow: String) : Outcome()
data class Result(val accepted: Boolean) : Outcome()
}
private data class Workflow(val name: String, val rules: List<Rule>)
private data class System(val workflows: Map<String, Workflow>, val parts: List<Part>)
//////////////////////////////////////////////////////
private fun parse(input: String): System {
val (workflows, parts) = input.split(Pattern.compile("\\r?\\n\\r?\\n"))
return System(
workflows.splitNewlines().map { parseWorkflow(it) }.associateBy { it.name },
parts.splitNewlines().map { parsePart(it) }
)
}
private val WORKFLOW_REGEX = Regex("(\\w+)\\{(.*)}")
private val RULE_REGEX = Regex("([xmas])([<>])(\\d+):(\\w+)")
private val RATING_REGEX = Regex("([xmas])=(\\d+)")
private fun parseWorkflow(workflow: String): Workflow {
val workflowMatch = WORKFLOW_REGEX.matchEntire(workflow)!!
return Workflow(
name = workflowMatch.groupValues[1],
rules = workflowMatch.groupValues[2].splitCommas().map {
when (it) {
"A" -> Rule.Result(true)
"R" -> Rule.Result(false)
else -> {
val ruleMatch = RULE_REGEX.matchEntire(it)
if (ruleMatch == null) {
Rule.Jump(it)
} else {
Rule.ConditionalJump(
category = Category.valueOf(ruleMatch.groupValues[1].uppercase()),
comparison = when (ruleMatch.groupValues[2][0]) {
'<' -> Comparison.LESS_THAN
else -> Comparison.GREATER_THAN
},
value = ruleMatch.groupValues[3].toInt(),
outcome = when (val outcome = ruleMatch.groupValues[4]) {
"A" -> Rule.Result(true)
"R" -> Rule.Result(false)
else -> Rule.Jump(outcome)
},
)
}
}
}
}
)
}
private fun parsePart(part: String): Part {
return part.substring(1, part.length - 1).splitCommas().associate {
val match = RATING_REGEX.matchEntire(it)!!
Category.valueOf(match.groupValues[1].uppercase()) to match.groupValues[2].toInt()
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 5,745 | advent-of-code | MIT License |
src/main/kotlin/Day7.kt | Ostkontentitan | 434,500,914 | false | {"Kotlin": 73563} | import kotlin.math.abs
fun puzzleDaySevenPartOne() {
val input = readInput(7)[0]
val initialPositions = parseCrabPositions(input)
val distances = calculateFuelConsumptions(initialPositions) { target, position -> abs(position - target) }
val (optimalPoint, leastFuelConsumption) = distances.first()
println("Shortest fuel consumption of $leastFuelConsumption required for position $optimalPoint")
}
fun puzzleDaySevenPartTwo() {
val input = readInput(7)[0]
val initialPositions = parseCrabPositions(input)
val distances = calculateFuelConsumptions(initialPositions) { target, position ->
val diff = abs(position - target)
(1..diff).sumOf { it }
}
val (optimalPoint, leastFuelConsumption) = distances.first()
println("Adjusted optimal is $leastFuelConsumption matching position $optimalPoint")
}
fun calculateFuelConsumptions(positions: List<Int>, fuelCalculation: (Int, Int) -> (Int)): List<Pair<Int, Int>> {
val sortedPositions = positions.sorted()
val firstCrab = sortedPositions.first()
val lastCrab = sortedPositions.last()
return (firstCrab..lastCrab).map { target ->
target to sortedPositions.sumOf { fuelCalculation(target, it) }
}.sortedBy { it.second }
}
fun parseCrabPositions(input: String) = input.split(",").map { it.toInt() }
| 0 | Kotlin | 0 | 0 | e0e5022238747e4b934cac0f6235b92831ca8ac7 | 1,335 | advent-of-kotlin-2021 | Apache License 2.0 |
src/Day08.kt | iownthegame | 573,926,504 | false | {"Kotlin": 68002} | import kotlin.math.max
fun main() {
fun parseTrees(input: List<String>): Array<List<Int>> {
var treeHeights = arrayOf<List<Int>>()
for (line in input) {
val heights = line.map { it.toString().toInt() }
treeHeights += heights
}
return treeHeights
}
fun calculateMaxTreePerRow(treeHeights: Array<List<Int>>, startCol: Int, direction: Int): Array<Array<Int>> {
val rows = treeHeights.size
val cols = treeHeights[0].size
val endCol = startCol + direction * cols
val maxHeights = Array(rows) {Array(cols) {0} }
for (i in 0 until rows) {
var j = startCol
var currentMax = 0
while (j != endCol) {
currentMax = if (j == startCol) {
treeHeights[i][j]
} else {
maxOf(currentMax, treeHeights[i][j])
}
maxHeights[i][j] = currentMax
j += direction
}
}
return maxHeights
}
fun calculateMaxTreePerCol(treeHeights: Array<List<Int>>, startRow: Int, direction: Int): Array<Array<Int>> {
val rows = treeHeights.size
val cols = treeHeights[0].size
val endRow = startRow + direction * rows
val maxHeights = Array(rows) {Array(cols) {0} }
for (j in 0 until cols) {
var i = startRow
var currentMax = 0
while (i != endRow) {
currentMax = if (i == startRow) {
treeHeights[i][j]
} else {
maxOf(currentMax, treeHeights[i][j])
}
maxHeights[i][j] = currentMax
i += direction
}
}
return maxHeights
}
fun part1(input: List<String>): Int {
val treeHeights = parseTrees(input)
val rows = treeHeights.size
val cols = treeHeights[0].size
val maxTreeHeightsFromLeft = calculateMaxTreePerRow(treeHeights, startCol = 0, direction = 1)
val maxTreeHeightFromRight = calculateMaxTreePerRow(treeHeights, startCol = cols -1, direction = -1)
val maxTreeHeightFromTop = calculateMaxTreePerCol(treeHeights, startRow = 0, direction = 1)
val maxTreeHeightFromBottom = calculateMaxTreePerCol(treeHeights, startRow = rows - 1, direction = -1)
var visibleCount = rows * 2 + cols * 2 - 4 // edges of trees
for (i in 1 until rows - 1) {
for (j in 1 until cols - 1) {
val treeHeight = treeHeights[i][j]
if (treeHeight > maxTreeHeightsFromLeft[i][j-1] ||
treeHeight > maxTreeHeightFromRight[i][j+1] ||
treeHeight > maxTreeHeightFromTop[i-1][j] ||
treeHeight > maxTreeHeightFromBottom[i+1][j]
) {
visibleCount += 1
}
}
}
return visibleCount
}
fun part2(input: List<String>): Int {
val treeHeights = parseTrees(input)
val rows = treeHeights.size
val cols = treeHeights[0].size
var highestScore =0
for (i in 1 until rows - 1) {
for (j in 1 until cols - 1) {
var viewDistances = arrayOf<Int>()
val treeHeight = treeHeights[i][j]
// left
var distance = 0
var jj = j - 1
while (jj >= 0) {
distance += 1
if (treeHeights[i][jj] >= treeHeight) {
// time to block the view
break
}
jj -= 1
}
viewDistances += distance
// right
distance = 0
jj = j + 1
while (jj <= cols - 1) {
distance += 1
if (treeHeights[i][jj] >= treeHeight) {
// time to block the view
break
}
jj += 1
}
viewDistances += distance
// top
distance = 0
var ii = i - 1
while (ii >= 0) {
distance += 1
if (treeHeights[ii][j] >= treeHeight) {
// time to block the view
break
}
ii -= 1
}
viewDistances += distance
// bottom
distance = 0
ii = i + 1
while (ii <= rows - 1) {
distance += 1
if (treeHeights[ii][j] >= treeHeight) {
// time to block the view
break
}
ii += 1
}
viewDistances += distance
val currentScore = viewDistances.reduce { acc, it -> acc * it }
highestScore = max(highestScore, currentScore)
}
}
return highestScore
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day08_sample")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readTestInput("Day08")
println("part 1 result: ${part1(input)}")
println("part 2 result: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 4e3d0d698669b598c639ca504d43cf8a62e30b5c | 5,514 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | polbins | 573,082,325 | false | {"Kotlin": 9981} | fun main() {
fun part1(input: List<String>): Int {
var result = 0
for (s in input) {
val intList = s.split("-", ",")
.map { it.toInt() }
val left = intList[0] to intList[1]
val right = intList[2] to intList[3]
if (left.withinRange(right) || right.withinRange(left)) {
result++
}
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
for (s in input) {
val intList = s.split("-", ",")
.map { it.toInt() }
val left = intList[0] to intList[1]
val right = intList[2] to intList[3]
if (left.overlaps(right) || right.overlaps(left)) {
result++
}
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput1 = readInput("Day04_test")
check(part1(testInput1) == 2)
val input1 = readInput("Day04")
println(part1(input1))
val testInput2 = readInput("Day04_test")
check(part2(testInput2) == 4)
val input2 = readInput("Day04")
println(part2(input2))
}
private fun Pair<Int, Int>.withinRange(other: Pair<Int, Int>): Boolean {
return first >= other.first && second <= other.second
}
private fun Pair<Int, Int>.overlaps(other: Pair<Int, Int>): Boolean {
return (first >= other.first && first <= other.second) ||
(second >= other.first && second <= other.second)
}
| 0 | Kotlin | 0 | 0 | fb9438d78fed7509a4a2cf6c9ea9e2eb9d059f14 | 1,378 | AoC-2022 | Apache License 2.0 |
src/day02/Day02.kt | xxfast | 572,724,963 | false | {"Kotlin": 32696} | package day02
import day02.Hand.*
import day02.Outcome.*
import readLines
enum class Hand { Rock, Paper, Scissors; }
enum class Outcome { Loss, Draw, Win }
val Hand.score: Int get() = ordinal + 1
val Outcome.score: Int get() = ordinal * 3
val String.hand: Hand get() = when (this) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> error("Invalid hand")
}
val String.outcome: Outcome get() = when (this) {
"X" -> Loss
"Y" -> Draw
"Z" -> Win
else -> error("Invalid outcome")
}
infix fun Hand.against(elf: Hand): Outcome = when {
this == elf -> Draw
this == elf.winner -> Win
else -> Loss
}
val Hand.winner: Hand get() = when (this) {
Rock -> Paper
Paper -> Scissors
Scissors -> Rock
}
val Hand.loser: Hand get() = when (this) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
fun handFor(outcome: Outcome, with: Hand): Hand = when (outcome) {
Loss -> with.loser
Win -> with.winner
Draw -> with
}
fun main() {
fun format(input: List<String>): List<List<String>> = input
.map { row -> row.split(" ") }
fun part1(input: List<String>): Int = format(input)
.map { (elf, you) -> elf.hand to you.hand }
.sumOf { (elf, you) -> you.score + (you against elf).score }
fun part2(input: List<String>): Int = format(input)
.map { (elf, game) -> elf.hand to game.outcome }
.sumOf { (elf, outcome) -> handFor(outcome, with = elf).score + outcome.score }
// test if implementation meets criteria from the description, like:
val testInput: List<String> = readLines("day02/test.txt")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input: List<String> = readLines("day02/input.txt")
check(part1(input) == 14069)
check(part2(input) == 12411)
}
| 0 | Kotlin | 0 | 1 | a8c40224ec25b7f3739da144cbbb25c505eab2e4 | 1,752 | advent-of-code-22 | Apache License 2.0 |
src/Day11.kt | Jintin | 573,640,224 | false | {"Kotlin": 30591} | import java.lang.RuntimeException
fun main() {
data class Monkey(
val list: MutableList<MutableList<Long>>,
var op: String,
val extraOp: (Monkey, Long) -> Long,
val divide: Int,
val success: Int,
val fail: Int,
) {
var count: Long = 0
fun check(index: Int, monkeys: List<Monkey>) {
while (list.size > 0) {
count++
val values = list.removeLast()
for (i in monkeys.indices) {
values[i] = extraOp(monkeys[i], operate(values[i]))
}
monkeys[
if (values[index] % divide == 0L) {
success
} else {
fail
}
].list.add(values)
}
}
private fun operate(value: Long): Long {
val list = op.split(" ")
val first = if (list[0] == "old") value else list[0].toLong()
val sec = if (list[2] == "old") value else list[2].toLong()
return when (list[1]) {
"+" -> first + sec
"-" -> first - sec
"*" -> first * sec
"/" -> first / sec
else -> throw RuntimeException("illegal op")
}
}
}
fun buildMonkeys(input: List<String>, extraOp: (Monkey, Long) -> Long): List<Monkey> {
val size = input.size / 7 + 1
return input.windowed(6, 7)
.map { lines ->
val list = lines[1].substringAfter(": ").split(", ").map {
val value = it.toLong()
MutableList(size) { value }
}.toMutableList()
val op = lines[2].substringAfter("new = ")
val d = lines[3].substringAfter("by ").toInt()
val s = lines[4].substringAfterLast(" ").toInt()
val f = lines[5].substringAfterLast(" ").toInt()
Monkey(list, op, extraOp, d, s, f)
}.toMutableList()
}
fun part1(input: List<String>): Long {
val monkeys = buildMonkeys(input) { _: Monkey, l: Long ->
l / 3
}
repeat(20) {
monkeys.forEachIndexed { index, monkey ->
monkey.check(index, monkeys)
}
}
val list = monkeys.sortedByDescending { it.count }
return list[0].count * list[1].count
}
fun part2(input: List<String>): Long {
val monkeys = buildMonkeys(input) { monkey: Monkey, l: Long ->
l % monkey.divide
}
repeat(10000) {
monkeys.forEachIndexed { index, monkey ->
monkey.check(index, monkeys)
}
}
val list = monkeys.sortedByDescending { it.count }
return list[0].count * list[1].count
}
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 4aa00f0d258d55600a623f0118979a25d76b3ecb | 3,000 | AdventCode2022 | Apache License 2.0 |
src/main/kotlin/com/anahoret/aoc2022/day16/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day16
import java.io.File
import kotlin.math.max
import kotlin.system.measureTimeMillis
data class Valve(val name: String, val flowRate: Long, var tunnels: List<String>)
fun parse(str: String): List<Valve> {
val regex = "Valve (.+) has flow rate=(\\d+); tunnels* leads* to valves* (.+)".toRegex()
return str.split("\n")
.map { line ->
val (_, name, rate, tunnels) = regex.find(line)!!.groupValues
Valve(name, rate.toLong(), tunnels.split(",").map(String::trim))
}
}
private fun findBestScore(
valves: List<Valve>,
totalTime: Int,
distanceCalculator: DistanceCalculator,
threshold: Long = -1
): Long {
var maxRelease = 0L
val totalReleaseOfAllValves = valves.sumOf(Valve::flowRate)
fun loop(
visited: List<Valve>,
rest: List<Valve>,
released: Long,
timeLeft: Int = totalTime
) {
val visitedReleasePerTick = visited.sumOf(Valve::flowRate)
if (rest.isEmpty() || timeLeft < 3) {
val totalReleased = released + timeLeft * visitedReleasePerTick
maxRelease = max(maxRelease, totalReleased)
return
}
val potentialRelease = released + 2 * visitedReleasePerTick + (timeLeft - 2) * totalReleaseOfAllValves
if (potentialRelease <= maxRelease || potentialRelease <= threshold) {
return
}
rest.forEach { rv ->
val timeToMoveAndTurnOn = distanceCalculator.distanceBetween(visited.last(), rv) + 1
if (timeLeft < timeToMoveAndTurnOn + 1) {
val totalReleased = released + timeLeft * visitedReleasePerTick
maxRelease = max(maxRelease, totalReleased)
return@forEach
}
val releasedWhileMovingAndTurningOn = timeToMoveAndTurnOn * visitedReleasePerTick
loop(
visited = visited + rv,
rest = rest.filter { it != rv },
released = released + releasedWhileMovingAndTurningOn,
timeLeft = timeLeft - timeToMoveAndTurnOn
)
}
}
val start = valves.find { it.name == "AA" }!!
loop(listOf(start), valves.filter { it.flowRate > 0 }, 0)
return maxRelease
}
class DistanceCalculator(valves: List<Valve>) {
private val distanceCache = mutableMapOf<Pair<Valve, Valve>, Int>()
private val valvesMap = valves.associateBy(Valve::name)
private val tunnelMap = valves.associate { it.name to it.tunnels.map(valvesMap::getValue) }
fun distanceBetween(v1: Valve, v2: Valve): Int {
val cacheKey = if (v1.name < v2.name) v1 to v2 else v2 to v1
val cached = distanceCache[cacheKey]
if (cached != null) {
return cached
}
val visited = mutableSetOf<Valve>()
val queue = ArrayDeque<Pair<Valve, Int>>()
queue.add(v1 to 0)
while (queue.isNotEmpty()) {
val v = queue.removeFirst()
if (v.first == v2) {
distanceCache[cacheKey] = v.second
return v.second
}
visited.add(v.first)
val tunnels = tunnelMap.getValue(v.first.name)
tunnels.forEach { if (it !in visited) queue.addLast(it to v.second + 1) }
}
distanceCache[v1 to v2] = -1
return -1
}
}
fun main() {
val input = File("src/main/kotlin/com/anahoret/aoc2022/day16/input.txt")
.readText()
.trim()
val valves = parse(input)
val distanceCalculator = DistanceCalculator(valves)
// Part 1
part1(valves, distanceCalculator).also { println("P1: ${it}ms") }
// Part 2
part2(valves, distanceCalculator).also { println("P2: ${it}ms") }
}
private fun part1(valves: List<Valve>, distanceCalculator: DistanceCalculator) = measureTimeMillis {
findBestScore(valves, totalTime = 30, distanceCalculator)
.also { println(it) }
}
private fun part2(valves: List<Valve>, distanceCalculator: DistanceCalculator) = measureTimeMillis {
fun <T> split(l: List<T>, acc: List<List<T>> = emptyList()): List<List<T>> {
if (l.isEmpty()) return acc
if (acc.isEmpty()) return split(l.drop(1), listOf(listOf(l.first())))
return split(l.drop(1), acc + acc.map { ae ->
ae + l.first()
})
}
val start = valves.first { it.name == "AA" }
val nonZeroValves = valves.filter { it.flowRate > 0 }
val candidates = split(nonZeroValves)
.map { left ->
(listOf(start) + left) to (listOf(start) + nonZeroValves.filter { it !in left })
}
candidates.fold(0L) { maxRelease, (l, r) ->
val release = if (l.size < r.size) {
val ls = findBestScore(l, totalTime = 26, distanceCalculator)
val rs = findBestScore(r, totalTime = 26, distanceCalculator, threshold = maxRelease - ls)
ls + rs
} else {
val rs = findBestScore(r, totalTime = 26, distanceCalculator)
val ls = findBestScore(l, totalTime = 26, distanceCalculator, threshold = maxRelease - rs)
ls + rs
}
max(maxRelease, release)
}.also(::println)
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 5,208 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2020/Day16.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2020
import com.nibado.projects.advent.*
object Day16 : Day {
private val ruleRegex = "([a-z ]+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)".toRegex()
private val values = resourceStrings(2020, 16)
private val rules = values[0].split("\n").map { it.matchGroups(ruleRegex).drop(1) }.map { groups ->
groups.let { (name, a1, a2, b1, b2) -> Rule(name, listOf(a1.toInt()..a2.toInt(), b1.toInt()..b2.toInt())) }
}
private val myTicket = values[1].split("\n").drop(1).first().let { it.split(",").map { it.toInt() } }
private val nearBy = values[2].split("\n").drop(1).map { it.split(",").map { it.toInt() } }
private fun match(value: Int) = rules.any { rule -> rule.ranges.any { value in it } }
override fun part1() : Int = nearBy.flatten().filterNot { match(it) }.sum()
override fun part2() : Long {
val options = myTicket.map { rules.map { it.name }.toMutableSet() }
nearBy.filterNot { t -> t.any { !match(it) } }.forEach { ticket ->
ticket.forEachIndexed { index, value ->
val validRules = rules.filter { r -> r.ranges.any { value in it } }.map { it.name }.toSet()
options[index].removeIf { !validRules.contains(it) }
}
}
while(options.any { it.size > 1 }) {
val uniques = options.filter { it.size == 1 }.flatten()
options.filter { it.size > 1 }.forEach { it.removeAll(uniques) }
}
return options.mapIndexedNotNull { index, set -> if(set.first().startsWith("departure")) index else null }
.map { myTicket[it].toLong() }
.reduce { a, b -> a * b }
}
data class Rule(val name: String, val ranges: List<IntRange>)
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,763 | adventofcode | MIT License |
src/Day09.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | import kotlin.math.abs
/**
* [Day09](https://adventofcode.com/2022/day/9)
*/
private class Day09 {
data class Point(val x: Int, val y: Int)
enum class Direction(val dx: Int, val dy: Int) {
LEFT(-1, 0),
UP(0, -1),
RIGHT(1, 0),
DOWN(0, 1);
companion object {
fun parse(direction: String): Direction = when (direction) {
"L" -> LEFT
"U" -> UP
"R" -> RIGHT
"D" -> DOWN
else -> throw RuntimeException()
}
}
}
}
fun main() {
fun move(point: Day09.Point, direction: Day09.Direction): Day09.Point =
Day09.Point(point.x + direction.dx, point.y + direction.dy)
fun moveTail(head: Day09.Point, tail: Day09.Point): Day09.Point {
return if (abs(head.x - tail.x) > 1 || abs(head.y - tail.y) > 1) {
Day09.Point(head.x - (head.x - tail.x) / 2, head.y - (head.y - tail.y) / 2)
} else {
tail
}
}
fun part1(input: List<String>): Int {
val visited = mutableSetOf<Day09.Point>()
var head = Day09.Point(0, 0)
var tail = Day09.Point(0, 0)
visited.add(tail)
input.forEach { line ->
val (d, n) = line.split(" ").let { (d, n) ->
Day09.Direction.parse(d) to n.toInt()
}
repeat(n) {
head = move(head, d)
tail = moveTail(head, tail)
visited.add(tail)
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val visited = mutableSetOf<Day09.Point>()
val points = Array(10) {
Day09.Point(0, 0)
}
visited.add(points.last())
input.forEach { line ->
val (d, n) = line.split(" ").let { (d, n) ->
Day09.Direction.parse(d) to n.toInt()
}
repeat(n) {
points[0] = move(points[0], d)
for (i in 1..9) {
points[i] = moveTail(points[i - 1], points[i])
}
visited.add(points.last())
}
}
return visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInputLarge = readInput("Day09_test_large")
check(part2(testInputLarge) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 2,588 | aoc-in-kotlin-2022 | Apache License 2.0 |
src/Day09.kt | zuevmaxim | 572,255,617 | false | {"Kotlin": 17901} | import java.awt.Point
import kotlin.math.abs
private val move = hashMapOf("U" to (0 to 1), "D" to (0 to -1), "L" to (-1 to 0), "R" to (1 to 0))
private fun List<String>.toSteps() = sequence {
val p = Point(0, 0)
for (line in this@toSteps) {
val (step, count) = line.split(" ")
val (dx, dy) = move[step]!!
repeat(count.toInt()) {
p.translate(dx, dy)
yield(p.x to p.y)
}
}
}
private fun Sequence<Pair<Int, Int>>.nextElement(): Sequence<Pair<Int, Int>> {
val point = Point(0, 0)
return this.map { (headX, headY) ->
val dx = headX - point.x
val dy = headY - point.y
if (abs(dx) > 1 || abs(dy) > 1) {
val dxx = if (dx == 0) 0 else dx / abs(dx)
val dyy = if (dy == 0) 0 else dy / abs(dy)
point.translate(dxx, dyy)
}
point.x to point.y
}
}
private fun part1(input: List<String>) = input.toSteps().nextElement().toHashSet().size
private fun part2(input: List<String>): Int {
var seq = input.toSteps()
repeat(9) {
seq = seq.nextElement()
}
return seq.toHashSet().size
}
fun main() {
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 34356dd1f6e27cc45c8b4f0d9849f89604af0dfd | 1,362 | AOC2022 | Apache License 2.0 |
foundations/find-pair-with-given-sum-array/Main.kt | ivan-magda | 102,283,964 | false | null | import java.util.*
import kotlin.collections.HashMap
/**
* Naive Solution O(n^2).
* <p>
* Naive solution would be to considered every pair in a given array
* and return if desired sum is found.
*/
fun findPairWithGivenSumNaive(array: Array<Int>, sum: Int): Pair<Int, Int>? {
for (i in 0 until array.size) {
(i + 1 until array.size)
.filter { array[i] + array[it] == sum }
.forEach { return Pair(array[i], array[it]) }
}
return null
}
/**
* O(nlogn) solution using Sorting.
* <p>
* The idea is to sort the given array in ascending order and maintain search space by maintaining
* two indexes (low and high) that initially points to two end-points of the array.
* Then we loop till low is less than high index and reduce search space array[low until high] at each iteration of the loop.
* We compare sum of elements present at index low and high with desired sum and increment low if sum is less
* than the desired sum else we decrement high is sum is more than the desired sum.
* Finally, we return if pair found in the array.
*/
fun findPairWithGivenSumSort(array: Array<Int>, sum: Int): Pair<Int, Int>? {
Arrays.sort(array)
var low = 0
var high = array.lastIndex
while (low < high) {
val currentSum = array[low] + array[high]
when {
currentSum == sum -> return Pair(array[low], array[high])
currentSum < sum -> low++
else -> high--
}
}
return null
}
/**
* O(n) solution using Hashing.
* <p>
* We can use map to easily solve this problem in linear time. The idea is to insert each element of the array[i]
* in a map. We also checks if difference (array[i], sum - array[i]) already exists in the map or not.
* If the difference is seen before, we print the pair and return.
*/
fun findPairWithGivenSumHashing(array: Array<Int>, sum: Int): Pair<Int, Int>? {
val map = HashMap<Int, Int>(array.size)
for (i in 0 until array.size) {
val difference = sum - array[i]
if (map.containsKey(difference)) {
return Pair(difference, array[i])
}
map.put(array[i], i)
}
return null
}
fun main(args: Array<String>) {
val array = arrayOf(8, 2, 5, 9, 21, 2, 3)
println("Array: ${Arrays.toString(array)}")
println("Naive, search for 7: ${findPairWithGivenSumNaive(array, 7)}")
println("Sort, search for 7: ${findPairWithGivenSumSort(array.clone(), 7)}")
println("Hashing, search for 7: ${findPairWithGivenSumHashing(array, 7)}")
}
| 0 | Kotlin | 0 | 2 | da06ec75cbd06c8e158aec86ca813e72bd22a2dc | 2,560 | introduction-algorithms | MIT License |
y2023/src/main/kotlin/adventofcode/y2023/Day08.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
import adventofcode.util.collections.cycle
import adventofcode.util.math.lcm
fun main() {
Day08.solve()
}
object Day08 : AdventSolution(2023, 8, "<NAME>") {
override fun solvePartOne(input: String): Int {
val (turns, graph) = parse(input)
return turns.map { it == 'L' }
.cycle()
.scan("AAA") { pos, turnLeft ->
graph.getValue(pos).let { (l, r) -> if (turnLeft) l else r }
}
.indexOf("ZZZ")
}
override fun solvePartTwo(input: String): Long {
val (turns, graph) = parse(input)
fun turnSequence() = turns.map { it == 'L' }.cycle()
val start = graph.keys.filter { it.endsWith("A") }.toSet()
val target = graph.keys.filter { it.endsWith("Z") }.toSet()
val paths = start.map { initial ->
turnSequence().scan(initial) { pos, turnLeft ->
graph.getValue(pos).let { (l, r) -> if (turnLeft) l else r }
}
}
val cycles = paths.map { it.indexOfFirst(target::contains) }
return cycles.map(Int::toLong).reduce(::lcm)
/*
Some testing of the behavior of the input
val prefix = positions.map { it.indexOfFirst { it in target } }
val cycle = buildSequence().zip(prefix) { pos, pre -> pos.drop(pre + 1).indexOfFirst { it in target } }
prefix.let(::println)
cycle.let(::println)
*/
/*
The input is very kind:
- each path has only one exit,
- cycles are a multiple of the turn instructions length
- and the cycle length from that target is the same length as the initial walk from start.
So no fiddliness, just find the point where all cycles line up, using LCM
*/
}
}
private fun parse(input: String): Directions {
val (turns, nodes) = input.split("\n\n")
val map = nodes.lines().associate {
val (node, left, right) = "[0-9A-Z]+".toRegex().findAll(it).map(MatchResult::value).toList()
node to Pair(left, right)
}
return Directions(turns, map)
}
private data class Directions(val turns: String, val map: Map<String, Pair<String, String>>) | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,327 | advent-of-code | MIT License |
y2019/src/main/kotlin/adventofcode/y2019/Day22.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2019
import adventofcode.io.AdventSolution
import adventofcode.util.SimpleParser
import java.math.BigInteger
import java.math.BigInteger.ONE
import java.math.BigInteger.ZERO
fun main() = Day22.solve()
object Day22 : AdventSolution(2019, 22, "Slam Shuffle") {
override fun solvePartOne(input: String) = parseInput(input)
.composeShufflingRoutine(10007.toBigInteger())
.evaluate(2019.toBigInteger())
override fun solvePartTwo(input: String) = parseInput(input)
.composeShufflingRoutine(119315717514047.toBigInteger())
.repeat(101741582076661)
.evaluateInverse(2020.toBigInteger())
private val parser = SimpleParser<ShufflingStep>().apply {
rule("deal into new stack") { ShufflingStep.NewStack }
rule("cut (-?\\d+)") { (n) -> ShufflingStep.Cut(n.toBigInteger()) }
rule("deal with increment (\\d+)") { (n) -> ShufflingStep.Increment(n.toBigInteger()) }
}
private fun parseInput(input: String): Sequence<ShufflingStep> =
input.lineSequence().mapNotNull { parser.parse(it) }
private fun Sequence<ShufflingStep>.composeShufflingRoutine(deckSize: BigInteger): LinearEquation = this
.map { it.toLinearEquation(deckSize) }
.reduce { acc, exp -> exp.compose(acc) }
private fun ShufflingStep.toLinearEquation(deckSize: BigInteger) = when (this) {
ShufflingStep.NewStack -> LinearEquation(deckSize - ONE, deckSize - ONE, deckSize)
is ShufflingStep.Cut -> LinearEquation(ONE, deckSize - n, deckSize)
is ShufflingStep.Increment -> LinearEquation(n, ZERO, deckSize)
}
private sealed class ShufflingStep {
object NewStack : ShufflingStep()
class Cut(val n: BigInteger) : ShufflingStep()
class Increment(val n: BigInteger) : ShufflingStep()
}
private data class LinearEquation(val a: BigInteger, val b: BigInteger, val m: BigInteger) {
fun evaluate(s: BigInteger) = (s * a + b) % m
fun evaluateInverse(s: BigInteger) = (s - b).mod(m) * a.modInverse(m) % m
fun compose(other: LinearEquation) = LinearEquation((a * other.a) % m, (a * other.b + b) % m, m)
fun repeat(exp: Long): LinearEquation {
val repeatedSquaring = generateSequence(this) { it.compose(it) }
val binaryExpansion = generateSequence(exp) { it / 2 }.takeWhile { it > 0 }.map { it % 2 == 1L }
return repeatedSquaring.zip(binaryExpansion) { partial, occurs -> partial.takeIf { occurs } }
.filterNotNull()
.reduce(LinearEquation::compose)
}
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,667 | advent-of-code | MIT License |
src/Day15.kt | arksap2002 | 576,679,233 | false | {"Kotlin": 31030} | import kotlin.math.abs
fun main() {
fun dist(x: Long, y: Long, x1: Long, y1: Long): Long = abs(x - x1) + abs(y - y1)
fun part1(input: List<String>): Long {
val arr = mutableListOf<Boolean>()
val n = 100_000_000
val y: Long = 2000000
for (i in -n..n) {
arr.add(false)
}
val hashSet: HashSet<Long> = hashSetOf()
for (line in input) {
val sensorX = line.split(" ")[2].substring(2, line.split(" ")[2].length - 1).toLong()
val sensorY = line.split(" ")[3].substring(2, line.split(" ")[3].length - 1).toLong()
val beaconX = line.split(" ")[8].substring(2, line.split(" ")[8].length - 1).toLong()
val beaconY = line.split(" ")[9].substring(2).toLong()
if (beaconY == y) hashSet.add(beaconX)
for (i in -n..n) {
if (dist(sensorY, sensorX, beaconY, beaconX) >= dist(sensorY, sensorX, y, i.toLong())) {
arr[i + n] = true
}
}
}
var result: Long = 0
for (i in arr.indices) {
if (arr[i] && !hashSet.contains((i - n).toLong())) {
result++
}
}
return result
}
fun good(x: Long): Boolean = x in 0..4000000
fun fullCheck(input: List<String>, y: Long, x: Long): Boolean {
for (line in input) {
val sensorX = line.split(" ")[2].substring(2, line.split(" ")[2].length - 1).toLong()
val sensorY = line.split(" ")[3].substring(2, line.split(" ")[3].length - 1).toLong()
val beaconX = line.split(" ")[8].substring(2, line.split(" ")[8].length - 1).toLong()
val beaconY = line.split(" ")[9].substring(2).toLong()
if (dist(sensorY, sensorX, beaconY, beaconX) >= dist(sensorY, sensorX, y, x)) {
return false
}
}
return true
}
fun part2(input: List<String>): Long {
for (line in input) {
val sensorX = line.split(" ")[2].substring(2, line.split(" ")[2].length - 1).toLong()
val sensorY = line.split(" ")[3].substring(2, line.split(" ")[3].length - 1).toLong()
val beaconX = line.split(" ")[8].substring(2, line.split(" ")[8].length - 1).toLong()
val beaconY = line.split(" ")[9].substring(2).toLong()
val d = dist(sensorY, sensorX, beaconY, beaconX) + 1
for (y in sensorY - d..sensorY + d) {
val x1 = d - abs(sensorY - y) + sensorX
val x2 = abs(sensorY - y) - d + sensorX
if (good(y) && good(x1) && fullCheck(input, y, x1)) return 4000000 * x1 + y
if (good(y) && good(x2) && fullCheck(input, y, x2)) return 4000000 * x2 + y
}
}
return -1
}
val input = readInput("Day15")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | a24a20be5bda37003ef52c84deb8246cdcdb3d07 | 2,910 | advent-of-code-kotlin | Apache License 2.0 |
src/day12/day12.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day12
import readInput
private fun parse(input: List<String>): Array<CharArray> {
val result = Array(input.size) { CharArray(input[0].length) }
for ((row, line) in input.withIndex()) {
for ((col, item) in line.withIndex()) {
result[row][col] = item
}
}
return result
}
private fun helperBFS(
grid: Array<CharArray>,
inputs: Set<Char>
): Int {
val queue = ArrayDeque<Input>()
val visited = Array<BooleanArray>(grid.size) { BooleanArray(grid[0].size) }
for (row in 0 until grid.size) {
for (col in 0 until grid[0].size) {
val item = grid[row][col]
if (inputs.contains(item)) queue.addFirst(Input(row, col, 0))
}
}
var min = Int.MAX_VALUE
while (queue.isNotEmpty()) {
val item = queue.removeLast()
if (visited[item.row][item.col]) continue
val currentChar = grid[item.row][item.col]
if (currentChar == 'E') {
return item.counter
}
visited[item.row][item.col] = true
val changes = listOf(
intArrayOf(0, 1),
intArrayOf(0, -1),
intArrayOf(1, 0),
intArrayOf(-1, 0)
)
for (change in changes) {
val newRow = item.row + change[0]
val newCol = item.col + change[1]
if (newCol < 0 || newCol > grid[0].size - 1 || newRow < 0 || newRow > grid.size - 1) {
continue
}
val nextItem = grid[newRow][newCol]
val value = (if (nextItem == 'E') 'z' else nextItem) - if (currentChar == 'S') 'a' else currentChar
if (value <= 1) {
queue.addFirst(
Input(
row = newRow,
col = newCol,
counter = item.counter + 1
)
)
}
}
}
return min
}
private data class Input(
val row: Int,
val col: Int,
val counter: Int
)
private fun part1(input: List<String>): Int {
val grid = parse(input)
return helperBFS(grid, setOf('S'))
}
private fun part2(input: List<String>): Int {
val grid = parse(input)
return helperBFS(grid, setOf('S', 'a'))
}
fun main() {
val input = readInput("day12/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 2,375 | aoc-2022 | Apache License 2.0 |
src/Day01.kt | richardmartinsen | 572,910,850 | false | {"Kotlin": 14993} | fun main() {
fun part1(input: List<String>): Int {
return input.foldIndexed(Pair(listOf<List<Int>>(), listOf<Int>())) { idx, acc, line ->
when {
idx + 1 == input.size -> {
Pair(acc.first + listOf(acc.second + line.toInt()), listOf())
}
line.isEmpty() -> {
Pair(acc.first + listOf(acc.second), listOf())
}
else -> {
Pair(acc.first, acc.second + line.toInt())
}
}
}.first.maxOf { list ->
list.sumOf { it }
}
}
fun part2(input: List<String>): Int {
return input.foldIndexed(Pair(listOf<List<Int>>(), listOf<Int>())) { idx, acc, line ->
when {
idx + 1 == input.size -> {
Pair(acc.first + listOf(acc.second + line.toInt()), listOf())
}
line.isEmpty() -> {
Pair(acc.first + listOf(acc.second), listOf())
}
else -> {
Pair(acc.first, acc.second + line.toInt())
}
}
}.first.map { list ->
list.sumOf { it }
}.sortedDescending().take(3).sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
check(part1(input) == 70296)
check(part2(input) == 205381)
}
| 0 | Kotlin | 0 | 0 | bd71e11a2fe668d67d7ee2af5e75982c78cbe193 | 1,444 | adventKotlin | Apache License 2.0 |
src/Day12.kt | TinusHeystek | 574,474,118 | false | {"Kotlin": 53071} | import extensions.grid.*
class HeightNode(point: Point, val character: Char) : PathNode(point) {
var elevation: Int = 0
init {
elevation = when (character) {
'S' -> 'a' - 'a'
'E' -> 'z' - 'a'
else -> character - 'a'
}
}
override fun toString(): String = "$point - $character[$elevation]"
}
typealias Heightmap = Triple<List<List<HeightNode>>, HeightNode, HeightNode>
val Heightmap.grid: List<List<HeightNode>> get() = first
val Heightmap.startNode: HeightNode get() = second
val Heightmap.endNode: HeightNode get() = third
class Day12 : Day(12) {
private fun buildHeightmap (input: String) : Heightmap {
val map = input.lines()
.mapIndexed { y, row ->
row.mapIndexed { x, character -> HeightNode(x to y, character) }
}
return Heightmap(map,
map.flatten().first{ it.character == 'S' },
map.flatten().first{ it.character == 'E' })
}
// --- Part 1 ---
override fun part1ToInt(input: String): Int {
val map = buildHeightmap(input)
val grid = Grid(map.grid)
val aStar = PathfindingAStar(grid, grid.directional4)
val pathNodes = aStar.findPath(map.startNode.point, map.endNode.point) {
currentNode, neighbourNode -> neighbourNode.elevation <= currentNode.elevation + 1 }
return pathNodes.count() - 1
}
// --- Part 2 ---
override fun part2ToInt(input: String): Int {
val map = buildHeightmap(input)
val grid = Grid(map.grid)
val aStar = PathfindingAStar(grid, grid.directional4)
val startPoints = map.grid.flatten().filter { it.character == 'a' }
val allPaths = startPoints.map {
aStar.findPath(it.point, map.endNode.point) {
currentNode, neighbourNode -> neighbourNode.elevation <= currentNode.elevation + 1 }
}
val shortestPath = allPaths.filter{ it.isNotEmpty() }.minOf { it.count() }
return shortestPath - 1
}
}
fun main() {
Day12().printToIntResults(31, 29)
}
| 0 | Kotlin | 0 | 0 | 80b9ea6b25869a8267432c3a6f794fcaed2cf28b | 2,119 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/Day12.kt | vw-anton | 574,945,231 | false | {"Kotlin": 33295} | fun main() {
val lines = readFile("input/12.txt")
.map { it.toList() }
val graph = createGraph(lines)
part1(graph)
part2(graph, getAPositions(lines))
}
private fun part1(graph: Graph<String, Int>) {
val (_, value) = shortestPath(graph, "S", "E")
println("part1: $value")
}
private fun part2(graph: Graph<String, Int>, allAs: List<String>) {
val result = allAs.map {
val (_, value) = shortestPath(graph, it, "E")
value.toInt() to it
}.minBy { it.first }
println("part 2: ${result.first}")
}
fun getAPositions(lines: List<List<Char>>): List<String> {
val result = mutableListOf<String>()
lines.forEachIndexed { row, line ->
line.forEachIndexed { col, char ->
if (char == 'a')
result.add(charToNode(char, row, col))
}
}
return result
}
private fun createGraph(lines: List<List<Char>>): Graph<String, Int> {
val graph = GraphImpl<String, Int>(directed = true, defaultCost = 1)
lines.forEachIndexed { row, line ->
line.forEachIndexed { col, char ->
val currentNode = charToNode(char, row, col)
val left = line.getOrNull(col - 1)
val top = lines.getOrNull(row - 1)?.getOrNull(col)
val right = line.getOrNull(col + 1)
val bottom = lines.getOrNull(row + 1)?.getOrNull(col)
left?.run {
if (climbDistance(char, left) <= 1) {
graph.addArc(currentNode to charToNode(this, row, col - 1))
}
}
top?.run {
if (climbDistance(char, top) <= 1) {
graph.addArc(currentNode to charToNode(this, row - 1, col))
}
}
right?.run {
if (climbDistance(char, right) <= 1) {
graph.addArc(currentNode to charToNode(this, row, col + 1))
}
}
bottom?.run {
if (climbDistance(char, bottom) <= 1) {
graph.addArc(currentNode to charToNode(this, row + 1, col))
}
}
}
}
return graph
}
private fun climbDistance(a: Char, b: Char): Int {
var start = a
var end = b
start = when (start) {
'S' -> 'a'
'E' -> 'z'
else -> start
}
end = when (end) {
'S' -> 'a'
'E' -> 'z'
else -> end
}
return end - start
}
private fun charToNode(char: Char, row: Int, col: Int): String = when (char) {
'S' -> "S"
'E' -> "E"
else -> "$row/$col" // e.g. 0/1
} | 0 | Kotlin | 0 | 0 | a823cb9e1677b6285bc47fcf44f523e1483a0143 | 2,615 | aoc2022 | The Unlicense |
src/day05/Day05.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day05
import readInput
typealias Day05InputType1 = Pair<Map<Int, List<Char>>, List<Triple<Int, Int, Int>>>
fun main() {
fun part1(input: Day05InputType1): String {
val crateStatus = input.first.mapValues { it.value.toMutableList() }
input.second.forEach {
for (i in 0 until it.first) {
val popped = crateStatus[it.second]?.removeLast()!!
crateStatus[it.third]?.add(popped)
}
}
return String(crateStatus.map { it.value.last() }.toCharArray())
}
fun part2(input: Day05InputType1): String {
val crateStatus = input.first.mapValues { it.value.toMutableList() }
input.second.forEach {
val toAdd = mutableListOf<Char>()
for (i in 0 until it.first) {
toAdd.add(crateStatus[it.second]?.removeLast()!!)
}
crateStatus[it.third]?.addAll(toAdd.reversed())
}
return String(crateStatus.map { it.value.last() }.toCharArray())
}
fun preprocess(input: List<String>): Day05InputType1 {
val stackSize = input.indexOfFirst { it[1] == '1' }
val bucketCount = input.first { it[1] == '1' }.length / 4 + 1
val crateStatus = mutableMapOf<Int, List<Char>>()
for (stackPos in 1 .. bucketCount) {
val stack = mutableListOf<Char>().also { crateStatus[stackPos] = it }
for (pos in stackSize - 1 downTo 0) {
val crate = input[pos].getOrNull(4 * (stackPos - 1) + 1)
if (crate != null && crate.isLetter()) {
stack.add(crate)
}
}
}
val commands = input.subList(bucketCount + 1, input.size).filter { it != "" }.map {
val split = it.split(" ")
Triple(split[1].toInt(), split[3].toInt(), split[5].toInt())
}
return Pair(crateStatus, commands)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(5, true)
check(part1(preprocess(testInput)) == "CMZ")
val input = readInput(5)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) == "MCD")
println(part2(preprocess(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 2,249 | advent-of-code-2022 | Apache License 2.0 |
src/day15/fr/Day15_1.kt | BrunoKrantzy | 433,844,189 | false | {"Kotlin": 63580} | package day15.fr
import java.io.File
private fun readChars(): CharArray = readLn().toCharArray()
private fun readLn() = readLine()!! // string line
private fun readSb() = StringBuilder(readLn())
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single long
private fun readDouble() = readLn().toDouble() // single double
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints
private fun readLongs() = readStrings().map { it.toLong() } // list of longs
private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles
private fun readIntArray() = readStrings().map { it.toInt() }.toIntArray() // Array of ints
private fun readLongArray() = readStrings().map { it.toLong() }.toLongArray() // Array of longs
fun readInput(name: String) = File("src", "$name.txt").readLines()
class ShortestPath (nbV: Int) {
private val nVertex = nbV
private fun minDistance(dist: IntArray, sptSet: Array<Boolean?>): Int {
// Initialize min value
var min = Int.MAX_VALUE
var minIndex = -1
for (v in 0 until nVertex) if (sptSet[v] == false && dist[v] <= min) {
min = dist[v]
minIndex = v
}
return minIndex
}
// A utility function to print the constructed distance array
fun printSolution(dist: IntArray) {
println("Vertex \t\t Distance from Source")
for (i in 0 until nVertex) println(i.toString() + " \t\t " + dist[i])
}
// Function that implements Dijkstra's single source shortest path
// algorithm for a graph represented using adjacency matrix representation
fun dijkstra(graph: Array<IntArray>, src: Int) : IntArray {
val dist = IntArray(nVertex)
// The output array. dist[i] will hold the shortest distance from src to i
// sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
val sptSet = arrayOfNulls<Boolean>(nVertex)
// Initialize all distances as INFINITE and stpSet[] as false
for (i in 0 until nVertex) {
dist[i] = Int.MAX_VALUE
sptSet[i] = false
}
// Distance of source vertex from itself is always 0
dist[src] = 0
// Find shortest path for all vertices
for (count in 0 until nVertex - 1) {
// Pick the minimum distance vertex from the set of vertices
// not yet processed. u is always equal to src in first iteration.
val u = minDistance(dist, sptSet)
// Mark the picked vertex as processed
sptSet[u] = true
// Update dist value of the adjacent vertices of the picked vertex.
for (v in 0 until nVertex)
// Update dist[v] only if is not in sptSet, there is an edge from u to v, and total
// weight of path from src to v through u is smaller than current value of dist[v]
if (!sptSet[v]!! && graph[u][v] != 0 && dist[u] != Int.MAX_VALUE && dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v]
}
// return the constructed distance array
return dist
}
}
fun main() {
var rep = 0L
//val vInGrille = day11.fr.readInput("test15")
val vInGrille = day11.fr.readInput("input15")
val vH = vInGrille.size
val vL = vInGrille[0].length
val vTabGrille = Array (vH) { Array(vL) { -1 } }
// chargement tableau
for (i in 0 until vH) {
val vLi = vInGrille[i]
for (j in vLi.indices) {
vTabGrille[i][j] = vLi[j].code - 48
}
}
var lstVertex = mutableListOf<Triple<Int, Int, Int>>()
var nNode = 0
// lecture tableau
for (lig in 0 until vH) {
for (col in 0 until vL) {
nNode = col
if (lig == 0) {
if (col == 0) {
lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1]))
lstVertex.add(Triple(nNode, nNode+vL, vTabGrille[lig+1][col]))
}
else if (col == vL-1) {
lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1]))
lstVertex.add(Triple(nNode, nNode+vL, vTabGrille[lig+1][col]))
}
else {
lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1]))
lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1]))
lstVertex.add(Triple(nNode, nNode+vL, vTabGrille[lig+1][col]))
}
}
else if (lig == vH - 1) {
nNode = col + (vL * (lig))
if (col == 0) {
lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1]))
lstVertex.add(Triple(nNode, nNode-vL, vTabGrille[lig-1][col]))
}
else if (col == vL - 1) {
lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1]))
lstVertex.add(Triple(nNode, nNode-vL, vTabGrille[lig-1][col]))
}
else {
lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1]))
lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1]))
lstVertex.add(Triple(nNode, nNode-vL, vTabGrille[lig-1][col]))
}
}
else { // lignes intérieures
nNode = col + (vL * (lig))
if (col == 0) {
lstVertex.add(Triple(nNode, nNode-vL, vTabGrille[lig-1][col]))
lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1]))
lstVertex.add(Triple(nNode, nNode+vL, vTabGrille[lig+1][col]))
}
else if (col == vL - 1) {
lstVertex.add(Triple(nNode, nNode-vL, vTabGrille[lig-1][col]))
lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1]))
lstVertex.add(Triple(nNode, nNode+vL, vTabGrille[lig+1][col]))
}
else {
lstVertex.add(Triple(nNode, nNode-vL, vTabGrille[lig-1][col]))
lstVertex.add(Triple(nNode, nNode+1, vTabGrille[lig][col+1]))
lstVertex.add(Triple(nNode, nNode-1, vTabGrille[lig][col-1]))
lstVertex.add(Triple(nNode, nNode+vL, vTabGrille[lig+1][col]))
}
}
}
}
val nbVertex = lstVertex.size
val nbS = vH * vL
val source = 0
val graph: Array<IntArray> = Array (nbS) { IntArray(nbS) { 0 } }
for (v in lstVertex) {
val s1 = v.first
val s2 = v.second
val pV = v.third
graph[s1][s2] = pV
}
val obShortPath = ShortestPath(nbS)
val taBDist = obShortPath.dijkstra(graph, source)
obShortPath.printSolution(taBDist)
}
| 0 | Kotlin | 0 | 0 | 0d460afc81fddb9875e6634ee08165e63c76cf3a | 7,066 | Advent-of-Code-2021 | Apache License 2.0 |
scripts/Day12.kts | matthewm101 | 573,325,687 | false | {"Kotlin": 63435} | import java.io.File
import java.util.*
data class Pos(val x: Int, val y: Int) {
fun up() = Pos(x, y-1)
fun down() = Pos(x, y+1)
fun left() = Pos(x-1, y)
fun right() = Pos(x+1, y)
fun neighbors() = listOf(up(), down(), left(), right())
}
data class Grid(val raw: List<String>) {
val width = raw[0].length
val height = raw.size
val start = (0 until width).flatMap { x -> (0 until height).map { y -> if (at(Pos(x,y)) == 'S') Pos(x,y) else null } }.filterNotNull().first()
val end = (0 until width).flatMap { x -> (0 until height).map { y -> if (at(Pos(x,y)) == 'E') Pos(x,y) else null } }.filterNotNull().first()
fun at(pos: Pos) = raw[pos.y][pos.x]
fun elev(pos: Pos) = if (at(pos) == 'E') 26 else if (at(pos) == 'S') 1 else at(pos) - 'a' + 1
fun inbounds(pos: Pos) = (pos.x in 0 until width) && (pos.y in 0 until height)
fun validUpwardsMove(pos1: Pos, pos2: Pos) = inbounds(pos1) && inbounds(pos2) && (elev(pos2) - elev(pos1) <= 1)
fun validDownwardsMove(pos1: Pos, pos2: Pos) = inbounds(pos1) && inbounds(pos2) && (elev(pos1) - elev(pos2) <= 1)
}
val grid = Grid(File("../inputs/12.txt").readLines())
data class State(val steps: Int, val pos: Pos) : Comparable<State> {
override fun compareTo(other: State): Int {
return steps - other.steps
}
fun nextValidUpStates() = pos.neighbors().filter { grid.validUpwardsMove(pos, it) }.map { State(steps+1, it) }
fun nextValidDownStates() = pos.neighbors().filter { grid.validDownwardsMove(pos, it) }.map { State(steps+1, it) }
}
run {
val queue: PriorityQueue<State> = PriorityQueue()
val start = State(0,grid.start)
queue.add(start)
val visited: MutableSet<Pos> = mutableSetOf()
while (queue.isNotEmpty()) {
val state = queue.remove()
if (state.pos == grid.end) {
println("The shortest path from the start to the goal takes ${state.steps} steps.")
break
}
if (state.pos !in visited) {
visited += state.pos
queue.addAll(state.nextValidUpStates().filter { it.pos !in visited })
}
}
}
run {
val queue: PriorityQueue<State> = PriorityQueue()
val start = State(0,grid.end)
queue.add(start)
val visited: MutableSet<Pos> = mutableSetOf()
while (queue.isNotEmpty()) {
val state = queue.remove()
if (grid.elev(state.pos) == 1) {
println("The shortest path from any low point to a goal takes ${state.steps} steps.")
break
}
if (state.pos !in visited) {
visited += state.pos
queue.addAll(state.nextValidDownStates().filter { it.pos !in visited })
}
}
} | 0 | Kotlin | 0 | 0 | bbd3cf6868936a9ee03c6783d8b2d02a08fbce85 | 2,762 | adventofcode2022 | MIT License |
src/Day05/Day05.kt | ctlevi | 578,257,705 | false | {"Kotlin": 10889} | data class Move(val amount: Int, val from: Int, val to: Int)
fun main() {
fun parseInput(input: List<String>): Pair<List<MutableList<Char>>, List<Move>> {
val blankLineIndex = input.indexOf("")
val paletCountIndex = blankLineIndex - 1
val paletCount = input[paletCountIndex].last().digitToInt()
val paletStacks = List(paletCount, { mutableListOf<Char>() })
for (i in 0 until paletCountIndex) {
val crateRow = input[i]
for (paletStackIndex in 0 until paletCount) {
val crateCharPosition = paletStackIndex + 1 + (paletStackIndex * 3)
if (crateCharPosition < crateRow.length && crateRow[crateCharPosition] != ' ') {
paletStacks[paletStackIndex].add(0, crateRow[crateCharPosition])
}
}
}
val movesIndex = blankLineIndex + 1
val moves = (movesIndex until input.size).map {
val split = input[it].split(" ")
Move(amount = split[1].toInt(), from = split[3].toInt(), to = split[5].toInt())
}
return Pair(paletStacks, moves);
}
fun part1(input: List<String>): String {
val (paletStacks, moves) = parseInput(input)
for (move in moves) {
repeat(move.amount) {
val fromStack = paletStacks[move.from - 1]
val toStack = paletStacks[move.to - 1]
val last = fromStack.removeLast()
toStack.add(last)
}
}
val topStacks = paletStacks.joinToString("") {
it.last().toString()
}
return topStacks
}
fun part2(input: List<String>): String {
val (paletStacks, moves) = parseInput(input)
for (move in moves) {
val fromStack = paletStacks[move.from - 1]
val toStack = paletStacks[move.to - 1]
val moved = (0 until move.amount).map { fromStack.removeLast() }.reversed()
toStack.addAll(moved)
}
val topStacks = paletStacks.joinToString("") {
it.last().toString()
}
return topStacks
}
val testInput = readInput("Day05/test")
val testResult = part1(testInput)
"Test Result: ${testResult}".println()
val input = readInput("Day05/input")
"Part 1 Result: ${part1(input)}".println()
"Part 2 Result: ${part2(input)}".println()
}
| 0 | Kotlin | 0 | 0 | 0fad8816e22ec0df9b2928983713cd5c1ac2d813 | 2,418 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/days/Day10.kt | nuudles | 316,314,995 | false | null | package days
class Day10 : Day(10) {
fun calculate(list: List<Int>): Pair<Int, Int> {
var lastValue = 0
var oneCount = 0
var threeCount = 0
list
.sorted()
.forEach { value ->
when (value) {
lastValue + 1 -> oneCount++
lastValue + 3 -> threeCount++
}
lastValue = value
}
return oneCount to threeCount + 1
}
override fun partOne() =
calculate(inputList.map { it.toInt() })
.let { it.first * it.second }
// Brute force
fun combinationCount(current: Int, list: List<Int>): Int {
if (list.count() == 0) {
return 1
} else if (current < list.first() - 3) {
return 0
}
val potentials = mutableListOf<Int>()
for (i in 0 until list.count()) {
if (list[i] > current + 3) {
break
}
potentials.add(i)
}
return potentials.sumBy { index ->
combinationCount(
list[index],
list.subList(index + 1, list.count())
)
}
}
fun combinations(list: List<Int>): Long {
var map = mapOf(0 to 1L)
val sortedList = list.sorted()
val target = sortedList.last()
sortedList
.forEach { value ->
val nextMap = mutableMapOf<Int, Long>()
map.forEach { (mapValue, count) ->
if (value - mapValue <= 3) {
nextMap[value] = (nextMap[value] ?: 0) + count
nextMap[mapValue] = (nextMap[mapValue] ?: 0) + count
}
}
map = nextMap
}
return map[target] ?: 0
}
override fun partTwo() =
combinations(inputList.map { it.toInt() })
}
| 0 | Kotlin | 0 | 0 | 5ac4aac0b6c1e79392701b588b07f57079af4b03 | 1,927 | advent-of-code-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/aoc2023/Day13.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2023
import readInput
import separateBy
import to2dCharArray
object Day13 {
private fun searchHorizontalReflectionLine(input: Array<CharArray>, smudges: Int = 0): Int? {
for (y in 1..<input.first().size) {
var distanceToCheck = 0
var remainingSmudges = smudges
while (remainingSmudges >= 0) {
distanceToCheck++
if (y - distanceToCheck < 0 || y + distanceToCheck - 1 == input.first().size) {
if (remainingSmudges == 0) {
return y
} else {
break
}
}
remainingSmudges -= input.indices.count { x -> input[x][y - distanceToCheck] != input[x][y + distanceToCheck - 1] }
}
}
return null
}
private fun searchVerticalReflectionLine(input: Array<CharArray>, smudges: Int = 0): Int? {
for (x in 1..<input.size) {
var distanceToCheck = 0
var remainingSmudges = smudges
while (remainingSmudges >= 0) {
distanceToCheck++
if (x - distanceToCheck < 0 || x + distanceToCheck - 1 == input.size) {
if (remainingSmudges == 0) {
return x
} else {
break
}
}
remainingSmudges -= input.first().indices.count { y -> input[x - distanceToCheck][y] != input[x + distanceToCheck - 1][y] }
}
}
return null
}
private fun findReflectionValue(input: List<String>, smudges: Int = 0): Int {
val array = input.to2dCharArray()
val vertical = searchVerticalReflectionLine(array, smudges)
return if (vertical != null) {
vertical
} else {
val horizontal = searchHorizontalReflectionLine(array, smudges)
if (horizontal != null) {
horizontal * 100
} else {
throw IllegalArgumentException("No reflection line found for $input")
}
}
}
fun part1(input: List<String>) = input.separateBy { it.isEmpty() }.sumOf { findReflectionValue(it) }
fun part2(input: List<String>) = input.separateBy { it.isEmpty() }.sumOf { findReflectionValue(it, smudges = 1) }
}
fun main() {
val testInput = readInput("Day13_test", 2023)
check(Day13.part1(testInput) == 405)
check(Day13.part2(testInput) == 400)
val input = readInput("Day13", 2023)
println(Day13.part1(input))
println(Day13.part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 2,632 | adventOfCode | Apache License 2.0 |
src/Day04.kt | akijowski | 574,262,746 | false | {"Kotlin": 56887, "Shell": 101} | data class Assignment(val start: Int, val end: Int) {
fun fullyContains(other: Assignment): Boolean {
return start >= other.start && end <= other.end
}
fun overlaps(other: Assignment): Boolean {
return end >= other.start
}
}
fun toAssignments(ids: List<String>): Pair<Assignment, Assignment> {
val x = ids.first().split("-")
val y = ids.last().split("-")
return Assignment(x.first().toInt(), x.last().toInt()) to Assignment(y.first().toInt(), y.last().toInt())
}
fun main() {
fun part1(input: List<String>): Int {
return input.map { it.split(",") }
.map { toAssignments(it) }
.count { it.first.fullyContains(it.second) || it.second.fullyContains(it.first) }
}
fun part2(input: List<String>): Int {
return input.map { it.split(",") }
.map { toAssignments(it) }
.count { it.first.overlaps(it.second) && it.second.overlaps(it.first) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 84d86a4bbaee40de72243c25b57e8eaf1d88e6d1 | 1,204 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day02.kt | margaret-lin | 575,169,915 | false | {"Kotlin": 9536} | package main.kotlin
import main.kotlin.Gesture.*
import main.kotlin.Outcome.*
/*
* this solution is credited to Sebastian from Advent of Code 2022 live stream
* */
fun main() {
println(part1())
println(part2())
}
private var input = readInput("day02_input").map {
val (a, b) = it.split(" ")
a[0] to b[0]
// [(A, Y), (B, X), (C, Z)]
}
private fun part1(): Int {
return input.sumOf { (opponent, you) ->
calculateScore(opponent.toGesture(), you.toGesture())
}
}
private fun part2(): Int {
return input.sumOf { (opponent, you) ->
val yourHand = handForDesiredOutcome(opponent.toGesture(), you.toOutcome())
calculateScore(opponent.toGesture(), yourHand)
}
}
private fun calculateScore(opponent: Gesture, me: Gesture): Int {
val outcome = calculateOutcome(me, opponent)
return me.points + outcome.points
}
enum class Outcome(val points: Int) {
WIN(6),
DRAW(3),
LOSS(0)
}
private fun calculateOutcome(first: Gesture, second: Gesture): Outcome = when {
first == second -> DRAW
first.beats() == second -> WIN
else -> LOSS
}
private fun handForDesiredOutcome(opponent: Gesture, desiredOutcome: Outcome): Gesture {
return when (desiredOutcome) {
DRAW -> opponent
LOSS -> opponent.beats()
WIN -> opponent.beatenBy()
}
}
fun Gesture.beatenBy(): Gesture {
return when (this) {
SCISSORS -> ROCK
ROCK -> PAPER
PAPER -> SCISSORS
}
}
fun Gesture.beats(): Gesture {
return when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
fun Char.toGesture(): Gesture {
return when (this) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> error("Unknown main.kotlin.input $this")
}
}
fun Char.toOutcome(): Outcome {
return when (this) {
'X' -> LOSS
'Y' -> DRAW
'Z' -> WIN
else -> error("Unknown main.kotlin.input $this")
}
}
enum class Gesture(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3)
}
| 0 | Kotlin | 0 | 0 | 7ef7606a04651ef88f7ca96f4407bae7e5de8a45 | 2,094 | advent-of-code-kotlin-22 | Apache License 2.0 |
src/Day05.kt | defvs | 572,381,346 | false | {"Kotlin": 16089} | fun main() {
data class Move(val items: Int, val from: Int, val to: Int)
fun <T> List<List<T>>.transpose(): List<List<T>> {
// Check if the matrix is empty
if (this.isEmpty()) return emptyList()
// Get the number of rows and columns in the matrix
val numRows = this.size
val numCols = this.maxBy { it.size }.size
// Create a new matrix for the transposed matrix
val transposed = MutableList(numCols) { mutableListOf<T?>() }
// Transpose the matrix, padding each row with null values if necessary
for (i in 0 until numRows) {
val row = this[i]
for (j in 0 until numCols) {
val value = if (j < row.size) row[j] else null
transposed[j].add(value)
}
}
// Return the transposed matrix as an immutable List
return transposed.map { it.toList().filterNotNull() }
}
fun parseCratesInput(input: List<String>): Pair<List<ArrayDeque<Char?>>, List<Move>> {
// Parse the input
val initialStacks = input
.takeWhile { it.isNotEmpty() }.dropLast(1)
.map { it.chunked(4) { it.singleOrNull { it != '[' && it != ']' && it != ' ' } } }
.transpose()
.map { it.reversed() }
.map { ArrayDeque(it) }
val moves = input
.dropWhile { it.isNotBlank() }.drop(1)
.map { it.split(" ") }
.map { Move(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1) }
return Pair(initialStacks, moves)
}
fun part1(input: List<String>): String {
val (initialStacks, moves) = parseCratesInput(input)
moves.forEach { (items, from, to) ->
for (i in 1..minOf(items, initialStacks[from].size)) initialStacks[to].add(initialStacks[from].removeLast())
}
return initialStacks.joinToString("") { it.removeLast()!!.toString() }
}
fun part2(input: List<String>): String {
val (initialStacks, moves) = parseCratesInput(input)
moves.forEach { (items, from, to) ->
(1..minOf(items, initialStacks[from].size)).map { _ ->
initialStacks[from].removeLast()
}.reversed().forEach { initialStacks[to].add(it) }
}
return initialStacks.joinToString("") { it.removeLast()!!.toString() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput).also { println("Test 1 result was: $it") } == "CMZ")
check(part2(testInput).also { println("Test 2 result was: $it") } == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | caa75c608d88baf9eb2861eccfd398287a520a8a | 2,398 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day05/Day05.kt | banshay | 572,450,866 | false | {"Kotlin": 33644} | package day05
import readInput
import java.util.*
fun main() {
fun part1(input: List<String>): String {
val (stacksUnparsed, instructionStrings) = input.splitAtEmpty()
val instructions = instructionStrings.map { it.parseInstruction() }
val cargoArea = stacksUnparsed.parseStacks()
instructions.forEach { cargoArea.applyInstruction(it) }
return cargoArea.topOfEachStack()
}
fun part2(input: List<String>): String {
val (stacksUnparsed, instructionStrings) = input.splitAtEmpty()
val instructions = instructionStrings.map { it.parseInstruction() }
val cargoArea = stacksUnparsed.parseStacks9001()
instructions.forEach { cargoArea.applyInstruction(it) }
return cargoArea.topOfEachStack()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
val input = readInput("Day05")
println("test part1: ${part1(testInput)}")
println("result part1: ${part1(input)}")
println("test part2: ${part2(testInput)}")
println("result part2: ${part2(input)}")
}
fun List<String>.splitAtEmpty(): List<List<String>> = this
.flatMapIndexed { index, x ->
when {
index == 0 || index == this.lastIndex -> listOf(index)
x.isEmpty() -> listOf(index - 1, index + 1)
else -> emptyList()
}
}
.windowed(size = 2, step = 2) { (from, to) -> this.slice(from..to) }
fun List<String>.parseStacks(): CargoArea = CargoArea(generateStacks(this))
fun List<String>.parseStacks9001(): CargoArea9001 = CargoArea9001(generateStacks(this))
private fun List<String>.generateStacks(strings: List<String>): Map<Int, Stack<Char>> {
val reversedList = strings.reversed().toMutableList()
//stack numbers
val stackNumbersString = reversedList.removeAt(0)
val matches = Regex("""(\d+)+""").findAll(stackNumbersString)
val stacks = matches.flatMap { it.destructured.toList() }
.map { it.toInt() to Stack<Char>() }
.toMap()
val stackIndexMap = stacks.keys.associateWith { stackNumbersString.indexOf(it.toString()) }
reversedList.forEach { horizontalCargoLine ->
stacks.forEach { stackEntry ->
val stackIndex = stackIndexMap[stackEntry.key]!!
if (stackIndex < horizontalCargoLine.length) {
val stackElement: Char = horizontalCargoLine.elementAt(stackIndex)
if (stackElement != ' ') {
stackEntry.value.push(stackElement)
}
}
}
}
return stacks
}
fun String.parseInstruction(): Instruction {
val (number, from, to) = Regex("""move (\d+) from (\d+) to (\d+)""").find(this)!!.destructured
return Instruction(number.toInt(), from.toInt(), to.toInt())
}
data class Instruction(val number: Int, val source: Int, val target: Int)
open class CargoArea(open val stacks: Map<Int, Stack<Char>>) {
open fun applyInstruction(instruction: Instruction) {
val source = stacks[instruction.source]!!
val target = stacks[instruction.target]!!
for (i in 1..instruction.number) {
target.push(source.pop())
}
}
fun topOfEachStack(): String {
return stacks.values
.mapNotNull {
try {
it.peek()
} catch (e: EmptyStackException) {
null
}
}
.joinToString("")
}
}
class CargoArea9001(override val stacks: Map<Int, Stack<Char>>) : CargoArea(stacks) {
override fun applyInstruction(instruction: Instruction) {
val source = stacks[instruction.source]!!
val target = stacks[instruction.target]!!
val tempStack = Stack<Char>()
for (i in 1..instruction.number) {
tempStack.push(source.pop())
}
while (!tempStack.empty()) {
target.push(tempStack.pop())
}
}
}
| 0 | Kotlin | 0 | 0 | c3de3641c20c8c2598359e7aae3051d6d7582e7e | 3,990 | advent-of-code-22 | Apache License 2.0 |
src/Day14.kt | punx120 | 573,421,386 | false | {"Kotlin": 30825} | import kotlin.math.max
fun main() {
class Waterfall(val map: Array<CharArray>, val depth: Int)
fun parseInput(input: List<String>): Waterfall {
val map = Array(1000) { CharArray(200) { '.' } }
var depth = 0
for (line in input) {
val l = line.split("->").map { it.trim().split(",") }.map { Pair(it[0].toInt(), it[1].toInt()) }
var p = l[0]
map[p.first][p.second] = '#'
for (i in 1 until l.size) {
val n = l[i]
if (n.first < p.first) {
for (x in n.first..p.first) {
map[x][p.second] = '#'
depth = max(p.second, depth)
}
} else if (n.first > p.first) {
for (x in p.first..n.first) {
map[x][p.second] = '#'
depth = max(p.second, depth)
}
} else if (n.second < p.second) {
for (y in n.second..p.second) {
map[n.first][y] = '#'
depth = max(y, depth)
}
} else if (n.second > p.second) {
for (y in p.second..n.second) {
map[n.first][y] = '#'
depth = max(y, depth)
}
}
p = n
}
}
return Waterfall(map, depth)
}
fun move(map: Array<CharArray>, pair: Pair<Int, Int>): Pair<Int, Int> {
if (map[pair.first][pair.second + 1] == '.') {
return Pair(pair.first, pair.second+1)
} else if (map[pair.first][pair.second + 1] != '.') {
if (map[pair.first - 1][pair.second + 1] == '.') {
return Pair(pair.first - 1, pair.second + 1)
} else if (map[pair.first + 1][pair.second + 1] == '.') {
return Pair(pair.first + 1, pair.second + 1)
}
}
return pair
}
fun drop(map: Waterfall) : Boolean {
var p = Pair(500, 0)
while (true) {
val n = move(map.map, p)
if (n.second > map.depth + 2) {
return true
}
if (n == p) {
break
} else {
p = n
}
}
if (map.map[p.first][p.second] != '.') {
return true
}
map.map[p.first][p.second] = 'o'
return false
}
fun part1(input: List<String>, floor: Boolean): Int {
val map = parseInput(input)
if (floor) {
for (i in map.map.indices) {
map.map[i][map.depth + 2] = '#'
}
}
var i = 0
while (true) {
if (drop(map)) {
break
}
++i
}
return i
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
println(part1(testInput, false))
println(part1(testInput, true))
val input = readInput("Day14")
println(part1(input, false))
println(part1(input, true))
}
| 0 | Kotlin | 0 | 0 | eda0e2d6455dd8daa58ffc7292fc41d7411e1693 | 3,197 | aoc-2022 | Apache License 2.0 |
2021/src/main/kotlin/com/trikzon/aoc2021/Day4.kt | Trikzon | 317,622,840 | false | {"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397} | package com.trikzon.aoc2021
fun main() {
val input = getInputStringFromFile("/day4.txt")
println(dayFourPartOne(input))
println(dayFourPartTwo(input))
}
fun dayFourPartOne(input: String): Int {
val lines = input.lines().filter { line -> line.isNotEmpty() }
val drawnNumbers = lines[0].split(',').map { str -> str.trim().toInt() }
val boards = ArrayList<Board>()
for (i in 1 until lines.size step 5) {
val numbers = "${lines[i]} ${lines[i + 1]} ${lines[i + 2]} ${lines[i + 3]} ${lines[i + 4]}"
boards.add(Board(numbers.split(' ').filter { str -> str.isNotEmpty() }.map { str -> str.trim().toInt() }))
}
for (drawnNumber in drawnNumbers) {
for (board in boards) {
board.mark(drawnNumber)
if (board.checkForBingo()) {
return board.sumOfUnmarked() * drawnNumber
}
}
}
return 0
}
fun dayFourPartTwo(input: String): Int {
val lines = input.lines().filter { line -> line.isNotEmpty() }
val drawnNumbers = lines[0].split(',').map { str -> str.trim().toInt() }
var boards = ArrayList<Board>()
for (i in 1 until lines.size step 5) {
val numbers = "${lines[i]} ${lines[i + 1]} ${lines[i + 2]} ${lines[i + 3]} ${lines[i + 4]}"
boards.add(Board(numbers.split(' ').filter { str -> str.isNotEmpty() }.map { str -> str.trim().toInt() }))
}
for (drawnNumber in drawnNumbers) {
for (board in boards) {
board.mark(drawnNumber)
if (board.checkForBingo() && boards.size == 1) {
return drawnNumber * board.sumOfUnmarked()
}
}
boards = boards.filter { board -> !board.complete } as ArrayList<Board>
}
return 0
}
class Board(numbers: List<Int>) {
private val numbers = Array(5 * 5) { 0 }
private val marked = Array(5 * 5) { false }
var complete = false
init {
for (i in numbers.indices) {
this.numbers[i] = numbers[i]
}
}
fun mark(num: Int) {
for (i in numbers.indices) {
if (numbers[i] == num) {
marked[i] = true
break
}
}
}
fun checkForBingo(): Boolean {
// check rows
for (i in 0 until 5) {
if (marked[i * 5] && marked[i * 5 + 1] && marked[i * 5 + 2] && marked[i * 5 + 3] && marked[i * 5 + 4]) {
complete = true
return true
}
}
// check columns
for (i in 0 until 5) {
if (marked[i] && marked[i + 5] && marked[i + 10] && marked[i + 15] && marked[i + 20]) {
complete = true
return true
}
}
return false
}
fun sumOfUnmarked(): Int {
var accumulator = 0
for (i in numbers.indices) {
if (!marked[i]) {
accumulator += numbers[i]
}
}
return accumulator
}
}
| 0 | Kotlin | 1 | 0 | d4dea9f0c1b56dc698b716bb03fc2ad62619ca08 | 2,976 | advent-of-code | MIT License |
src/adventofcode/day09/Day09.kt | bstoney | 574,187,310 | false | {"Kotlin": 27851} | package adventofcode.day09
import adventofcode.AdventOfCodeSolution
import kotlin.math.abs
fun main() {
Solution.solve()
}
object Solution : AdventOfCodeSolution<Int>() {
override fun solve() {
solve(9, 13, 36)
}
override fun part1TestFile(inputFile: String) = "${inputFile}_test-part1"
override fun part1(input: List<String>): Int {
return getTailLocations(input)
.toSet()
.size
}
override fun part2TestFile(inputFile: String) = "${inputFile}_test-part2"
override fun part2(input: List<String>): Int {
return getTailLocations(input, 9)
.toSet()
.size
}
private fun getTailLocations(input: List<String>, followingKnots: Int = 1): Sequence<Location> {
val headSequence: Sequence<Location> = getMovements(input)
.runningFold(HeadLocation(0, 0)) { head, move -> head.move(move) }
return (0 until followingKnots)
.fold(headSequence) { s, _ ->
s.runningFold(KnotLocation(0, 0)) { tail, head -> tail.follow(head) }
}
}
private fun getMovements(input: List<String>) = input.asSequence()
.map { it.split(" ", limit = 2) }
.flatMap { (direction, distance) ->
(1..distance.toInt())
.map { Movement(Direction.valueOf(direction)) }
}
interface Location {
val x: Int
val y: Int
}
data class HeadLocation(override val x: Int, override val y: Int) : Location {
fun move(movement: Movement): HeadLocation = when (movement.direction) {
Direction.U -> HeadLocation(x, y + 1)
Direction.D -> HeadLocation(x, y - 1)
Direction.L -> HeadLocation(x - 1, y)
Direction.R -> HeadLocation(x + 1, y)
}
}
data class KnotLocation(override val x: Int, override val y: Int) : Location {
fun follow(previous: Location): KnotLocation {
val dx = previous.x - x
val dy = previous.y - y
return KnotLocation(x + moveBy(dx, dy), y + moveBy(dy, dx))
}
private fun moveBy(da: Int, db: Int): Int {
return if (da == 0 || abs(da) <= 1 && abs(db) <= 1) {
0
} else {
da / abs(da)
}
}
}
data class Movement(val direction: Direction)
enum class Direction {
U, D, L, R
}
}
| 0 | Kotlin | 0 | 0 | 81ac98b533f5057fdf59f08940add73c8d5df190 | 2,438 | fantastic-chainsaw | Apache License 2.0 |
src/day09/Day09.kt | palpfiction | 572,688,778 | false | {"Kotlin": 38770} | package day09
import readInput
import java.lang.IllegalArgumentException
import kotlin.math.absoluteValue
enum class Direction {
UP, DOWN, RIGHT, LEFT
}
fun String.toDirection(): Direction = when (this) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"R" -> Direction.RIGHT
"L" -> Direction.LEFT
else -> throw IllegalArgumentException()
}
data class Motion(val direction: Direction, val steps: Int)
data class Position(val x: Int, val y: Int) {
override fun toString() = "($x, $y)"
}
fun Position.distanceFrom(position: Position): Distance {
return this.x - position.x to this.y - position.y
}
data class State(val head: Position, val tail: Position) {
override fun toString() = "head: $head; tail: $tail"
}
fun Position.move(direction: Direction): Position = when (direction) {
Direction.UP -> this.copy(y = y + 1)
Direction.DOWN -> this.copy(y = y - 1)
Direction.RIGHT -> this.copy(x = x + 1)
Direction.LEFT -> this.copy(x = x - 1)
}
typealias Distance = Pair<Int, Int>
fun Distance.isVertical(): Boolean = this.first == 0 && this.second != 0
fun Distance.isHorizontal(): Boolean = this.first != 0 && this.second == 0
fun main() {
fun parseMotions(input: List<String>): List<Motion> =
input.map { it.split(" ") }.map { (direction, steps) -> Motion(direction.toDirection(), steps.toInt()) }
fun Position.shouldFollow(position: Position): Boolean {
val distance = position.distanceFrom(this)
return distance.first.absoluteValue >= 2 ||
distance.second.absoluteValue >= 2
}
fun moveHead(state: State, direction: Direction) = state.copy(head = state.head.move(direction))
fun Position.follow(position: Position): Position {
if (!this.shouldFollow(position)) return this
val distance = position.distanceFrom(this)
val newTailPosition = when {
distance.isHorizontal() -> {
val (x) = distance
if (x > 0) this.copy(x = this.x + 1)
else this.copy(x = this.x - 1)
}
distance.isVertical() -> {
val (_, y) = distance
if (y > 0) this.copy(y = this.y + 1)
else this.copy(y = this.y - 1)
}
// is diagonal
else -> {
val (x, y) = distance
this.copy(x = this.x + x / x.absoluteValue, y = this.y + y / y.absoluteValue)
}
}
return newTailPosition
}
fun moveTail(state: State) = state.copy(tail = state.tail.follow(state.head))
fun part1(input: List<String>): Int {
val initialState = State(Position(0, 0), Position(0, 0))
val states = mutableListOf(initialState)
parseMotions(input)
.map { motion -> List(motion.steps) { motion.direction } }
.flatten()
.fold(initialState) { state, direction -> moveTail(moveHead(state, direction)).also { states.add(it) } }
return states
.distinctBy { it.tail }
.count()
}
fun part2(input: List<String>): Int {
val rope = MutableList(10) { Position(0, 0) }
val tailPositions = mutableListOf(Position(0, 0))
val directions = parseMotions(input)
.map { motion -> List(motion.steps) { motion.direction } }
.flatten()
for (direction in directions) {
rope.forEachIndexed { i, knot ->
rope[i] = if (i == 0) knot.move(direction)
else knot.follow(rope[i - 1])
}
tailPositions.add(rope[9])
}
return tailPositions
.distinct()
.count()
}
val testInput = readInput("/day09/Day09_test")
println(part1(testInput))
println(part2(testInput))
//check(part1(testInput) == 157)
//check(part2(testInput) == 70)
val input = readInput("/day09/Day09")
//println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7 | 4,005 | advent-of-code | Apache License 2.0 |
src/main/kotlin/io/pg/advent/day3/Main.kt | pgdejardin | 159,992,959 | false | null | package io.pg.advent.day3
import io.pg.advent.utils.FileUtil
fun main() {
val lines = FileUtil.loadFile("/day3.txt")
val inches = calculateFabricOverlap(lines)
println("Overlap inches: $inches")
val id = findIDofNotOverlapFabric(lines)
println("Fabric ID which is not overlapping: $id")
}
fun findIDofNotOverlapFabric(lines: List<String>): String {
val overlappingCoords = transformLinesToCoords(lines).flatten().groupBy { it }.filterValues { it.size > 1 }.keys
return lines.map { it.toClaim() }.first { it.coordinates().intersect(overlappingCoords).isEmpty() }.id
}
fun calculateFabricOverlap(lines: List<String>): Int {
val coords = transformLinesToCoords(lines)
return coords.flatten()
.groupBy { it }
.filterValues { it.size > 1 }
.size
}
fun transformLinesToCoords(lines: List<String>): List<List<Pair<Int, Int>>> = lines.map { transformInputToCoord(it) }
fun transformInputToCoord(input: String): List<Pair<Int, Int>> {
val claim = input.toClaim()
val xRange = claim.fromLeft..(claim.fromLeft + claim.width - 1)
val yRange = claim.fromTop..(claim.fromTop + claim.height - 1)
return xRange.flatMap { x -> yRange.map { y -> Pair(x, y) } }.sortedBy { it.first }
}
fun String.toClaim(): Claim {
// "#1 @ 0,0: 1x1"
val id = this.substring(1).substringBefore("@").trim()
val leftAndTop = this.substringAfter("@").substringBefore(":").trim().split(",")
val widthAndHeight = this.substringAfter(":").split("x")
return Claim(
id,
leftAndTop.first().trim().toInt(),
leftAndTop.last().trim().toInt(),
widthAndHeight.first().trim().toInt(),
widthAndHeight.last().trim().toInt()
)
}
data class Claim(
val id: String,
val fromLeft: Int,
val fromTop: Int,
val width: Int,
val height: Int
) {
fun coordinates(): List<Pair<Int, Int>> {
val xRange = this.fromLeft..(this.fromLeft + this.width - 1)
val yRange = this.fromTop..(this.fromTop + this.height - 1)
return xRange.flatMap { x -> yRange.map { y -> Pair(x, y) } }.sortedBy { it.first }
}
}
| 0 | Kotlin | 0 | 0 | 259cb440369e9e0a5ce8fc522e672753014efdf2 | 2,039 | advent-of-code-2018 | MIT License |
src/main/kotlin/dev/paulshields/aoc/Day3.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 3: Binary Diagnostic
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.readFileAsStringList
fun main() {
println(" ** Day 3: Binary Diagnostic ** \n")
val diagnosticsReport = readFileAsStringList("/Day3DiagnosticsReport.txt")
val powerConsumption = decodePowerConsumptionFromDiagnosticsReport(diagnosticsReport)
println("The power consumption provided by the diagnostics report is $powerConsumption")
val lifeSupportRating = decodeLifeSupportRatingFromDiagnosticsReport(diagnosticsReport)
println("The life support rating provided by the diagnostics report is $lifeSupportRating")
}
fun decodePowerConsumptionFromDiagnosticsReport(report: List<String>): Int {
val bitsGroupedByIndex = groupBitsInReportByIndex(report)
val gammaRate = findMostCommonBitsInReportByIndex(bitsGroupedByIndex)
.joinToString("")
.toInt(2)
val epsilonRate = findLeastCommonBitsInReportByIndex(bitsGroupedByIndex)
.joinToString("")
.toInt(2)
return gammaRate * epsilonRate
}
fun decodeLifeSupportRatingFromDiagnosticsReport(report: List<String>): Int {
val oxygenGeneratorRating = findNumberMatchingBitCriteria(report, ::findMostCommonBitsInReportByIndex)
val co2ScrubberRating = findNumberMatchingBitCriteria(report, ::findLeastCommonBitsInReportByIndex)
return oxygenGeneratorRating * co2ScrubberRating
}
private fun groupBitsInReportByIndex(report: List<String>) =
report.map(::toIndexedListOfChars)
.flatten()
.groupBy(keySelector = { it.first }, valueTransform = { it.second })
.map { it.value }
private fun toIndexedListOfChars(input: String) =
input.toList().mapIndexed { index, char -> Pair(index, char) }
private fun findMostCommonBitsInReportByIndex(bitsGroupedByIndex: List<List<Char>>) =
bitsGroupedByIndex.map(::getMostCommonChar)
private fun findLeastCommonBitsInReportByIndex(bitsGroupedByIndex: List<List<Char>>) =
bitsGroupedByIndex.map(::getLeastCommonChar)
private fun getMostCommonChar(input: List<Char>) =
input.sortedByDescending { it }.groupBy { it }.maxByOrNull { it.value.size }?.key ?: '1'
private fun getLeastCommonChar(input: List<Char>) =
input.sortedBy { it }.groupBy { it }.minByOrNull { it.value.size }?.key ?: '0'
fun findNumberMatchingBitCriteria(report: List<String>, matchingBitCriteriaGenerator: (List<List<Char>>) -> List<Char>): Int {
var index = 0
var filteredReport = report
while (filteredReport.size > 1) {
val bitsGroupedByIndex = groupBitsInReportByIndex(filteredReport)
val bitToMatch = matchingBitCriteriaGenerator(bitsGroupedByIndex)[index]
filteredReport = filteredReport.filter { it[index] == bitToMatch }
++index
}
return filteredReport.first().toInt(2)
}
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 2,813 | AdventOfCode2021 | MIT License |
app/src/y2021/day05/Day05HydrothermalVenture.kt | henningBunk | 432,858,990 | false | {"Kotlin": 124495} | package y2021.day05
import common.Answers
import common.AocSolution
import common.annotations.AoCPuzzle
import helper.Point
import kotlin.math.sign
typealias VentMap = List<MutableList<Int>>
fun main(args: Array<String>) {
Day05HydrothermalVenture().solveThem()
}
@AoCPuzzle(2021, 5)
class Day05HydrothermalVenture : AocSolution {
override val answers = Answers(samplePart1 = 5, samplePart2 = 12, part1 = 7468, part2 = 22364)
override fun solvePart1(input: List<String>): Any = input
.parseToLines()
.filter { line -> !line.isDiagonal() }
.countProblematicVents()
override fun solvePart2(input: List<String>): Any = input
.parseToLines()
.countProblematicVents()
}
fun List<String>.parseToLines(): List<Line> = map {
val (fromX, fromY, toX, toY) = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex().find(it)?.destructured
?: error("Parsing error")
Line(Point(fromX.toInt(), fromY.toInt()), Point(toX.toInt(), toY.toInt()))
}
fun List<Line>.countProblematicVents(): Int {
val mapSize = determineMapSize(this)
return fold(emptyMap(mapSize)) { ventMap, line ->
ventMap.apply { drawLine(line) }
}.flatten().count { it > 1 }
}
fun determineMapSize(lines: List<Line>): Point = lines
.flatMap { line -> listOf(line.a, line.b) }
.let { points -> Point(points.maxOf { it.x } + 1, points.maxOf { it.y } + 1) }
fun emptyMap(size: Point): VentMap {
return List(size.y) { MutableList(size.x) { 0 } }
}
fun VentMap.drawLine(line: Line) {
fun addVent(point: Point) {
this[point.y][point.x] += 1
}
val (from, to) = line
val direction = (to - from).let { Point(it.x.sign, it.y.sign) }
var current = from
while (current != to) {
addVent(current)
current += direction
}
addVent(to)
}
data class Line(val a: Point, val b: Point) {
fun isDiagonal() = a.x != b.x && a.y != b.y
}
| 0 | Kotlin | 0 | 0 | 94235f97c436f434561a09272642911c5588560d | 1,929 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2022/day12/day12.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2022.day12
import biz.koziolek.adventofcode.*
fun main() {
val inputFile = findInput(object {})
val heightMap = parseHeightMap(inputFile.bufferedReader().readLines())
val elevationGraph = buildElevationGraph(heightMap)
println("Fewest steps from S to E: ${findFewestStepsFromStartToEnd(elevationGraph)}")
println("Fewest steps from any a to E: ${findFewestStepsFromZeroToEnd(elevationGraph)}")
}
fun parseHeightMap(lines: Iterable<String>): Map<Coord, Char> =
lines.parse2DMap().toMap()
data class ElevationNode(
val label: Char,
val height: Int,
val coord: Coord,
) : GraphNode {
override val id = "${label}__${coord.x}_${coord.y}"
override fun toGraphvizString(exactXYPosition: Boolean, xyPositionScale: Float): String = id
}
fun buildElevationGraph(heightMap: Map<Coord, Char>): Graph<ElevationNode, UniDirectionalGraphEdge<ElevationNode>> =
buildGraph {
heightMap.forEach { (coord, label) ->
val currentHeight = labelToHeight(label)
val currentNode = ElevationNode(label, currentHeight, coord)
heightMap.getAdjacentCoords(coord, includeDiagonal = false)
.map { adjCoord ->
val adjLabel = heightMap[adjCoord]!!
val adjHeight = labelToHeight(adjLabel)
ElevationNode(adjLabel, adjHeight, adjCoord)
}
.filter { it.height <= currentHeight + 1 }
.forEach { add(UniDirectionalGraphEdge(currentNode, it)) }
}
}
fun labelToHeight(label: Char): Int =
when (label) {
'S' -> labelToHeight('a')
'E' -> labelToHeight('z')
in 'a'..'z' -> label - 'a'
else -> throw IllegalArgumentException("Unexpected heightMap label: '$label'")
}
fun findFewestStepsFromStartToEnd(elevationGraph: Graph<ElevationNode, UniDirectionalGraphEdge<ElevationNode>>): Int {
val start = elevationGraph.nodes.find { it.label == 'S' }
?: throw IllegalStateException("Start not found")
val end = elevationGraph.nodes.find { it.label == 'E' }
?: throw IllegalStateException("End not found")
val shortestPath = elevationGraph.findShortestPath(start, end)
return shortestPath.size - 1
}
fun findFewestStepsFromZeroToEnd(elevationGraph: Graph<ElevationNode, UniDirectionalGraphEdge<ElevationNode>>): Int {
val starts = elevationGraph.nodes.filter { it.height == 0 }.toSet()
val end = elevationGraph.nodes.find { it.label == 'E' }
?: throw IllegalStateException("End not found")
val shortestPath = elevationGraph.findShortestPath(starts, end)
return shortestPath.size - 1
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 2,703 | advent-of-code | MIT License |
src/day20/Day20.kt | maxmil | 578,287,889 | false | {"Kotlin": 32792} | package day20
import println
import readInput
fun String.value() = map { c -> if (c == '#') "1" else "0" }.joinToString("").toInt(2)
fun enhance(image: List<String>, enhancement: String): List<String> =
(1..image.size - 2).map { y ->
(1..image[0].length - 2).map { x ->
val square = image[y - 1].substring(x - 1..x + 1) +
image[y].substring(x - 1..x + 1) +
image[y + 1].substring(x - 1..x + 1)
enhancement[square.value()]
}.joinToString("")
}
fun padImage(baseImage: List<String>, infinite: String): List<String> {
val blankLine = infinite.repeat(baseImage[0].length)
return (listOf(blankLine, blankLine) + baseImage + listOf(blankLine, blankLine)).map { row ->
infinite.repeat(2) + row + infinite.repeat(2)
}
}
fun repeatedEnhance(input: List<String>, times: Int): List<String> {
val enhancement = input[0]
var image = input.drop(2)
var infinite = "."
repeat(times) {
image = enhance(padImage(image, infinite), enhancement)
infinite = enhancement[infinite.repeat(9).value()].toString()
}
return image
}
fun List<String>.countLight() = fold(0) { acc, s -> acc + s.count { it == '#' } }
fun part1(input: List<String>) = repeatedEnhance(input, 2).countLight()
fun part2(input: List<String>) = repeatedEnhance(input, 50).countLight()
fun main() {
check(part1(readInput("day20/input_test")) == 35)
check(part2(readInput("day20/input_test")) == 3351)
val input = readInput("day20/input")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 246353788b1259ba11321d2b8079c044af2e211a | 1,605 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/net/mguenther/adventofcode/day7/Day7.kt | mguenther | 115,937,032 | false | null | package net.mguenther.adventofcode.day7
/**
* @author <NAME> (<EMAIL>)
*/
data class Node(val id: String, val weight: Int, val successors: List<String>)
class Graph(nodes: List<Node>) {
private val nodes = nodes
fun inDegreeOf(fromId: String): Int {
return nodes
.filter { node -> node.successors.contains(fromId) }
.size
}
fun rootNodes(): List<Node> {
return nodes
.filter { node -> inDegreeOf(node.id) == 0 }
.toList()
}
fun node(id: String): Node = nodes.first { node -> node.id.equals(id) }
fun weightOf(id: String): Int {
val node = node(id)
return node.weight + node.successors.sumBy { s -> weightOf(s) }
}
fun offBalance(): List<Int> {
return rootNodes().map { n -> n.successors.map { s -> weightOf(s) }.distinct().reduce { l, r -> Math.abs(l - r) } }
}
fun findOffBalance(): Int {
val root = rootNodes().get(0)
return findOffBalance(root, 0)
}
// findOffBalance is not a general solution, but tied to the given problem instance, since
// we lose a bit of information with distinctBy and have to select the offending candidate
// by either maxBy or minBy. in case of the given problem, maxBy yields the correct solution
// but this does not have to be the case
private fun findOffBalance(root: Node, off: Int): Int {
val candidates = root.successors.map { s -> Pair(s, weightOf(s)) }.distinctBy { p -> p.second }
if (candidates.size == 1) {
// if there is only one candidate left, we found the offending node
// and have to subtract the off value from its weight
return root.weight - off
} else {
// we haven't found the culprit yet, so we have to check the candidate
// that has the differing value and go one layer deeper
val newOff = candidates.map { c -> c.second }.reduce { l, r -> Math.abs(l - r) }
return findOffBalance(node(candidates.maxBy { p -> p.second }!!.first), newOff)
}
}
}
| 0 | Kotlin | 0 | 0 | c2f80c7edc81a4927b0537ca6b6a156cabb905ba | 2,156 | advent-of-code-2017 | MIT License |
src/Day09.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | import kotlin.math.abs
fun main() {
data class Position(val x: Int, val y: Int) {
operator fun plus(dir: String) = when (dir) {
"R" -> Position(x + 1, y)
"L" -> Position(x - 1, y)
"U" -> Position(x, y + 1)
else -> Position(x, y - 1)
}
}
data class Move(val dir: String, val steps: Int)
val startingPos = Position(0, 0)
fun parseMoves(input: List<String>): List<Move> {
return input.map { it.split(" ").let { (dir, steps) -> Move(dir, steps.toInt()) } }
}
fun updateTail(head: Position, tail: Position): Position {
val diffX = head.x - tail.x
val absX = abs(diffX)
val diffY = head.y - tail.y
val absY = abs(diffY)
return when {
//diagonal step
absX > 1 && absY > 0 || absY > 1 && absX > 0 -> Position(
tail.x + diffX / absX,
tail.y + diffY / absY
)
absX > 1 -> Position(tail.x + diffX / absX, tail.y)
absY > 1 -> Position(tail.x, tail.y + diffY / absY)
else -> tail
}
}
fun part1(input: List<String>): Int {
val moves = parseMoves(input)
var head = startingPos
var tail = startingPos
val visited = mutableSetOf(tail)
for (move in moves) {
repeat(move.steps) {
head += move.dir
tail = updateTail(head, tail)
visited += tail
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val moves = parseMoves(input)
val rope = MutableList(10) { startingPos }
val visited = mutableSetOf(rope.last())
for (move in moves) {
repeat(move.steps) {
rope[0] = rope[0] + move.dir
for (i in 1..rope.lastIndex) {
rope[i] = updateTail(rope[i - 1], rope[i])
}
visited += rope.last()
}
}
return visited.size
}
// test if implementation meets criteria from the description, like:
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 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 2,428 | AdventOfCode2022 | Apache License 2.0 |
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day16/Day16.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2020.day16
import eu.janvdb.aocutil.kotlin.MatchFinder
import eu.janvdb.aocutil.kotlin.readGroupedLines
fun main() {
val (fields, tickets) = readInput()
part1(tickets, fields)
part2(tickets, fields)
}
private fun readInput(): Pair<List<TicketField>, List<Ticket>> {
val groupedLines = readGroupedLines(2020, "input16.txt")
assert(groupedLines.size == 3)
assert(groupedLines[1][0] == "your ticket:")
assert(groupedLines[2][0] == "nearby tickets:")
val fields = groupedLines[0].map(TicketField::read)
val myTickets = groupedLines[1].drop(1).map(Ticket::read)
val otherTickets = groupedLines[2].drop(1).map(Ticket::read)
val allTickets = myTickets + otherTickets
return Pair(fields, allTickets)
}
private fun part1(allTickets: List<Ticket>, fields: List<TicketField>) {
val invalidValues = allTickets.flatMap { it.getInvalidValues(fields) }
val invalidSum = invalidValues.sum()
println(invalidSum)
}
private fun part2(tickets: List<Ticket>, fields: List<TicketField>) {
val validTickets = tickets.filter { it.hasInvalidValues(fields) }
val indices = IntRange(0, fields.size - 1).toList()
val match = MatchFinder.findMatch(fields, indices) { field, index ->
validTickets.all { ticket -> field.matches(ticket.values[index]) }
}
println(match)
val myTicket = tickets[0]
val result = match.filterKeys { it.name.startsWith("departure") }
.map { myTicket.values[it.value] }
.foldRight(1L, { x, y -> x * y })
println(result)
}
| 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 1,479 | advent-of-code | Apache License 2.0 |
src/Day02.kt | rifkinni | 573,123,064 | false | {"Kotlin": 33155, "Shell": 125} | enum class RockPaperScissors(val score: Int)
{
ROCK(1),
PAPER(2),
SCISSORS(3);
fun winsOver(): RockPaperScissors {
return when(this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
fun losesTo(): RockPaperScissors {
return when(this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
companion object {
fun fromChar(input: Char): RockPaperScissors {
return when(input) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> throw Exception()
}
}
}
}
enum class Outcome(val score: Int)
{
WIN(6),
DRAW(3),
LOSE(0);
fun shapeForOutcome(opponent: RockPaperScissors): RockPaperScissors {
return when (this) {
DRAW -> opponent
LOSE -> opponent.winsOver()
WIN -> opponent.losesTo()
}
}
companion object {
fun fromChar(input: Char): Outcome {
return when(input) {
'X' -> LOSE
'Y' -> DRAW
'Z' -> WIN
else -> throw Exception()
}
}
}
}
class Game(private val opponent: RockPaperScissors, private val player: RockPaperScissors)
{
constructor(opponent: RockPaperScissors, outcome: Outcome) : this(opponent, outcome.shapeForOutcome(opponent))
fun score(): Int
{
return player.score + scoreWinner()
}
private fun scoreWinner(): Int {
val outcome = if (player == opponent) {
Outcome.DRAW
} else if (player.losesTo() == opponent) {
Outcome.LOSE
} else if (player.winsOver() == opponent) {
Outcome.WIN
} else { throw Exception() }
return outcome.score
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { Game(RockPaperScissors.fromChar(it[0]), RockPaperScissors.fromChar(it[2])).score() }
}
fun part2(input: List<String>): Int {
return input.sumOf { Game(RockPaperScissors.fromChar(it[0]), Outcome.fromChar(it[2])).score() }
}
// 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 | c2f8ca8447c9663c0ce3efbec8e57070d90a8996 | 2,513 | 2022-advent | Apache License 2.0 |
src/Day07.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | data class Directory(
val name: String,
val head: String?,
val directories: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf(),
)
data class File(
val name: String,
val size: Int,
)
fun main() {
fun computeDirectorySize(directory: Directory): Int {
val subdirectorySizes = directory.directories.sumOf { computeDirectorySize(it) }
val fileSizes = directory.files.sumOf { it.size }
return subdirectorySizes + fileSizes
}
fun List<String>.toDirectorySizes(): List<Int> {
val directories = mutableListOf<Directory>()
var currentDirectory = Directory("/", null)
directories.add(currentDirectory)
this
.drop(1)
.filter { it != "$ ls" }
.forEach {
val splitInput = it.split(" ")
when {
it.startsWith("$ cd") -> {
currentDirectory = when (val directoryName = splitInput.last()) {
".." -> directories.first { directory -> directory.name == currentDirectory.head && currentDirectory in directory.directories }
else -> currentDirectory.directories.first { directory -> directory.name == directoryName }
}
}
it.startsWith("dir") -> {
val newDirectory = Directory(splitInput.last(), currentDirectory.name)
directories.add(newDirectory)
currentDirectory.directories.add(newDirectory)
}
else -> currentDirectory.files.add(File(splitInput.last(), splitInput.first().toInt()))
}
}
return directories.map { computeDirectorySize(it) }
}
fun part1(input: List<String>): Int =
input
.toDirectorySizes()
.filter { it < 100000 }
.sum()
fun part2(input: List<String>): Int {
val directorySizes = input.toDirectorySizes()
val maxSpace = 70000000
val updateSpace = 30000000
val unusedSpace = maxSpace - directorySizes.first()
val wantedSpace = updateSpace - unusedSpace
return directorySizes
.sorted()
.first { it > wantedSpace }
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 2,568 | AdventOfCode2022 | Apache License 2.0 |
src/Day13.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | import kotlin.math.min
fun Input.split(): List<Input> {
val r = mutableListOf<Input>()
var curr = mutableListOf<String>()
for (l in this) {
if (l == "") {
r.add(curr)
curr = mutableListOf()
} else
curr.add(l)
}
r.add(curr)
return r
}
fun String.isReflection(start: Int): Boolean {
var a = substring(0, start)
var b = substring(start)
val len = min(a.length, b.length)
if (a.length == len)
b = b.take(len)
else a = a.takeLast(len)
return a.reversed() == b
}
fun String.diff(start: Int): Long {
var a = substring(0, start)
var b = substring(start)
val len = min(a.length, b.length)
if (a.length == len)
b = b.take(len)
else a = a.takeLast(len)
return a.reversed().zip(b).sumOf { if (it.first == it.second) 0L else 1L }
}
fun Input.testHorizontal(tolerance: Long = 0L): Long {
for (i in 1..<this[0].length) {
if (this.sumOf { it.diff(i) } == tolerance)
return i.toLong()
}
return 0
}
fun Input.testVertical(tolerance: Long = 0L): Long {
return (this[0].length - 1 downTo 0).map { i ->
this.map { it[i] }.joinToString("")
}.testHorizontal(tolerance)
}
fun main() {
fun part1(input: List<String>): Long {
return input.split().sumOf {
it.testHorizontal() + it.testVertical() * 100
}
}
fun part2(input: List<String>): Long {
return input.split().sumOf {
it.testHorizontal(1) + it.testVertical(1) * 100
}
}
val input = readInput("Day13")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 1,659 | aoc-2023 | Apache License 2.0 |
src/Day05.kt | dustinlewis | 572,792,391 | false | {"Kotlin": 29162} | fun main() {
fun part1(input: List<String>): String {
// println(input)
// val splitIndex = input.indexOf("")
// val stackData = input.subList(0, splitIndex - 1)
// val transitionData = input.subList(splitIndex + 1, input.lastIndex)
val (transitionData, stackData) = input.partition { it.contains("move") }
// println(stackData)
// println(transitionData)
val stacks = (1..9).associateWith { ArrayDeque<String>() }
stackData
.reversed()
.drop(2)
.map { s ->
s.chunked(4).map {
if(it.isBlank()) "" else it.replace("""[\[\] ]""".toRegex(), "")
}
}
.forEach { crates ->
crates.forEachIndexed { index, letter ->
if (letter.isNotEmpty()) {
stacks[index + 1]?.addLast(letter)
}
}
}
// [qty, start, dest]
// [2, 2, 8]
val transitions = transitionData.map { it.split(" ").mapNotNull { s -> s.toIntOrNull() } }
transitions.forEach { (quantity, start, destination) ->
for(i in 1..quantity) {
stacks[destination]?.addLast(stacks[start]?.removeLast().orEmpty())
}
}
return stacks.values.fold("") { acc, stack -> acc + stack.last() }
}
fun part2(input: List<String>): String {
val (transitionData, stackData) = input.partition { it.contains("move") }
val stacks = (1..9).associateWith { ArrayDeque<String>() }
stackData
.reversed()
.drop(2)
.map { s ->
s.chunked(4).map {
if(it.isBlank()) "" else it.replace("""[\[\] ]""".toRegex(), "")
}
}
.forEach { crates ->
crates.forEachIndexed { index, letter ->
if (letter.isNotEmpty()) {
stacks[index + 1]?.addLast(letter)
}
}
}
// [qty, start, dest]
// [2, 2, 8]
val transitions = transitionData.map { it.split(" ").mapNotNull { s -> s.toIntOrNull() } }
transitions.forEach { (quantity, start, destination) ->
val temp = ArrayDeque<String>()
for(i in 1..quantity) {
temp.addLast(stacks[start]?.removeLast().orEmpty())
}
for(i in 1..quantity) {
stacks[destination]?.addLast(temp.removeLast())
}
}
return stacks.values.fold("") { acc, stack -> acc + stack.last() }
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c8d1c9f374c2013c49b449f41c7ee60c64ef6cff | 2,767 | aoc-2022-in-kotlin | Apache License 2.0 |
2021/src/day05/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day05
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.math.sign
fun main() {
fun part1(lines: List<Line>): Int {
val maxX = lines.maxOf { maxOf(it.first.first, it.second.first) }
val maxY = lines.maxOf { maxOf(it.first.second, it.second.second) }
val map = Array(maxX + 1) {
IntArray(maxY + 1)
}
lines
.filter { it.first.first == it.second.first || it.first.second == it.second.second }
.forEach { (from, to) ->
for (x in minOf(from.first, to.first) .. maxOf(from.first, to.first)) {
for (y in minOf(from.second, to.second) .. maxOf(from.second, to.second)) {
map[x][y]++
}
}
}
return map.sumOf { row -> row.count { it > 1 } }
}
fun part2(lines: List<Line>): Int {
val maxX = lines.maxOf { maxOf(it.first.first, it.second.first) }
val maxY = lines.maxOf { maxOf(it.first.second, it.second.second) }
val map = Array(maxX + 1) {
IntArray(maxY + 1)
}
for ((from, to) in lines) {
val dx = (to.first - from.first).sign
val dy = (to.second - from.second).sign
var x = from.first
var y = from.second
map[x][y]++
while (x != to.first || y != to.second) {
x += dx
y += dy
map[x][y]++
}
}
return map.sumOf { row -> row.count { it > 1 } }
}
check(part1(readInput("test-input.txt")) == 5)
check(part2(readInput("test-input.txt")) == 12)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): List<Line> {
return Files.newBufferedReader(Paths.get("src/day05/$s")).readLines().map {
val (from, to) = it.split(" -> ")
val (x1, y1) = from.split(",").map { it.toInt() }
val (x2, y2) = to.split(",").map { it.toInt() }
Pair(x1, y1) to Pair(x2, y2)
}
}
typealias Point = Pair<Int, Int>
typealias Line = Pair<Point, Point> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 1,928 | advent-of-code | Apache License 2.0 |
src/main/kotlin/mkuhn/aoc/Day07.kt | mtkuhn | 572,236,871 | false | {"Kotlin": 53161} | package mkuhn.aoc
import mkuhn.aoc.util.readInput
import mkuhn.aoc.util.splitToPair
fun main() {
val input = readInput("Day07")
println(day07part1(input))
println(day07part2(input))
}
fun day07part1(input: List<String>): Int =
FileStructure().apply {
expandByCommands(input.associateCommandsToOutput().drop(1))
}.dirList.map { it.tallySize() }
.filter { it <= 100000 }
.sum()
fun day07part2(input: List<String>): Int =
FileStructure().apply {
expandByCommands(input.associateCommandsToOutput().drop(1))
}.let { structure ->
structure.dirList.map { it.tallySize() }
.filter { it >= 30000000 - (70000000 - structure.root.tallySize()) }
.min()
}
fun List<String>.associateCommandsToOutput(): List<Pair<String, List<String>>> =
this.fold(mutableListOf<Pair<String, MutableList<String>>>()) { acc, a ->
if (a.startsWith("$")) acc += a.drop(2) to mutableListOf<String>()
else acc.last().second += a
acc
}
class FileStructure(val root: FileNode = FileNode("/", 0, true, null),
val dirList: MutableList<FileNode> = mutableListOf(root)) {
fun expandByCommands(commands: List<Pair<String, List<String>>>) {
var currentNode = root
commands.forEach { command ->
when {
command.first == "ls" -> command.second.forEach {
currentNode.addFromLsResult(it).apply { if(this.isDirectory) dirList += this }
}
command.first.startsWith("cd") ->
currentNode = when(command.first.splitToPair(' ').second) {
"/" -> root
".." -> currentNode.parent!!
else -> currentNode.children.first { it.name == command.first.splitToPair(' ').second }
}
}
}
}
}
data class FileNode(val name: String, val size: Int, val isDirectory: Boolean,
val parent: FileNode?, val children: MutableList<FileNode> = mutableListOf(), var totalSize: Int? = null) {
fun addFromLsResult(lsResult: String): FileNode =
lsResult.splitToPair(' ')
.let { result ->
when(result.first) {
"dir" -> FileNode(result.second, 0, true, this)
else -> FileNode(result.second, result.first.toInt(), false, this)
}
}.apply { this@FileNode.children += this }
fun tallySize(): Int = totalSize?:(this.size + children.sumOf { it.tallySize() }).apply { totalSize = this }
} | 0 | Kotlin | 0 | 1 | 89138e33bb269f8e0ef99a4be2c029065b69bc5c | 2,609 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | NatoNathan | 572,672,396 | false | {"Kotlin": 6460} | enum class Play(val score: Int) {
Rock(1),
Paper(2),
Scissors(3);
fun getResult(player: Play): Result = when {
this == player -> Result.Draw
this == Rock && player != Paper -> Result.Win
this == Scissors && player != Rock -> Result.Win
this == Paper && player != Scissors -> Result.Win
else -> Result.Lose
}
companion object {
fun pickPlay(other: Play, neededResult: Result) = values()
.filter { it.getResult(other) == neededResult }
.maxBy { it.score }
fun decodePlay(input: String): Play = when (input) {
"A","X" -> Rock
"B","Y" -> Paper
"C","Z" -> Scissors
else -> throw Exception("Not a valid play")
}
}
}
enum class Result(val score: Int) {
Win(6),
Draw(3),
Lose(0);
companion object {
fun decodeResult(input: String): Result = when(input) {
"X" -> Lose
"Y" -> Draw
"Z"-> Win
else -> throw Exception("Not a valid result")
}
}
}
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEach { s ->
val (other, you) = s.split(" ").map { Play.decodePlay(it) }
sum += you.getResult(other).score + you.score
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.forEach {
val (otherStr, neededResultStr) = it.split(" ")
val neededResult = Result.decodeResult(neededResultStr)
sum += Play.pickPlay(Play.decodePlay(otherStr),neededResult).score + neededResult.score
}
return 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))
}
| 0 | Kotlin | 0 | 0 | c0c9e2a2d0ca2503afe33684a3fbba1f9eefb2b0 | 1,983 | advent-of-code-kt | Apache License 2.0 |
src/day03/Day03.kt | GrinDeN | 574,680,300 | false | {"Kotlin": 9920} | fun main() {
fun findSharedCharacter(pair: Pair<String, String>): Char {
return pair.first.toCharArray()
.filter { pair.second.contains(it) }
.toSet()
.toList()[0]
}
fun findSharedCharacter(triple: Triple<String, String, String>): Char {
return triple.first.toCharArray()
.filter { triple.second.contains(it) && triple.third.contains(it) }
.toSet()
.toList()[0]
}
fun part1(input: List<String>): Int {
val racksackPairs = input.map { Pair(it.substring(0, it.length/2), it.substring(it.length/2)) }
return racksackPairs
.map { findSharedCharacter(it) }
.sumOf { if (it.isLowerCase()) it.code - 96 else it.code - 38 }
}
fun part2(input: List<String>): Int {
val tripleRacksacks = input.windowed(3, 3).map { Triple(it[0], it[1], it[2]) }
return tripleRacksacks
.map { findSharedCharacter(it) }
.sumOf { if (it.isLowerCase()) it.code - 96 else it.code - 38 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day03/Day03_test")
check(part1(testInput) == 157)
val input = readInput("day03/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f25886a7a3112c330f80ec2a3c25a2ff996d8cf8 | 1,317 | aoc-2022 | Apache License 2.0 |
2021/src/main/kotlin/days/Day8.kt | pgrosslicht | 160,153,674 | false | null | package days
import Day
import com.google.common.collect.Collections2
import kotlin.math.pow
class Day8 : Day(8) {
override fun partOne(): Int {
val easyDigits = setOf(2, 3, 4, 7)
return dataList.map {
val split = it.split("|")
split.last().split(" ")
}.sumOf { it.count { s -> easyDigits.contains(s.length) } }
}
override fun partTwo(): Long {
val inputs = dataList.map { it.split(" | ").let { s -> s.first().split(" ") to s.last().split(" ") } }
return inputs.sumOf { input ->
Collections2.permutations("abcdefg".toList()).firstNotNullOf { tryPermutation(it, input) }
}
}
private fun tryPermutation(perm: List<Char>, input: Pair<List<String>, List<String>>): Long? {
if (input.first.any { tryDigit(perm, it) == null }) return null
return input.second.mapIndexed { i, s -> tryDigit(perm, s)!! * (10L.pow(3 - i)) }.sum()
}
private fun tryDigit(perm: List<Char>, s: String): Int? {
return when (s.toList().map { perm[it - 'a'] }.sorted().joinToString("")) {
"ab" -> 1
"acdfg" -> 2
"abcdf" -> 3
"abef" -> 4
"bcdef" -> 5
"bcdefg" -> 6
"abd" -> 7
"abcdefg" -> 8
"abcdef" -> 9
"abcdeg" -> 0
else -> null
}
}
}
private fun Long.pow(i: Int): Long = this.toDouble().pow(i).toLong()
fun main() = Day.mainify(Day8::class)
| 0 | Kotlin | 0 | 0 | 1f27fd65651e7860db871ede52a139aebd8c82b2 | 1,501 | advent-of-code | MIT License |
src/Day05.kt | SeanDijk | 575,314,390 | false | {"Kotlin": 29164} | fun main() {
data class Command(val fromIndex: Int, val toIndex: Int, val times: Int)
data class Input(val stacks: List<ArrayDeque<String>>, val commands: List<Command>)
fun parseInput(input: List<String>): Input {
println("---------- Parse ----------")
// Split at the blank line
val splitIndex = input.indexOf("")
val amountOfStacks = input[splitIndex - 1].split(' ')
.asSequence()
.filter { it.isNotBlank() }
.map { it.toInt() }
.last()
val stackLines = input.subList(0, splitIndex - 1) // - 1 since we don't care about the stack indexes here
val commandLines = input.subList(splitIndex + 1, input.size) // + 1 to skip the blank line
val stacks: List<ArrayDeque<String>> = (0 until amountOfStacks).map { ArrayDeque() }
println("Found $amountOfStacks stacks")
stackLines.forEach { line ->
// Chunks of 4, so each chunk is part of 1 stack
line.chunked(4).forEachIndexed { index, string ->
if (string.isNotBlank()) {
val trimmed = string.trim().removeSurrounding("[", "]")
println("Add '$trimmed' to stack ${index + 1}")
// Add first because we parse from top to bottom.
stacks[index].addFirst(trimmed)
}
}
}
val commands = commandLines.asSequence()
.map { commandString ->
val (times, fromIndex, toIndex) = commandString.filter { !it.isLetter() }
.trim()
.replace(" ", " ")
.split(' ')
Command(fromIndex.toInt() - 1, toIndex.toInt() - 1, times.toInt())
}
.toList()
println("---------- End Parse ----------")
return Input(stacks, commands)
}
fun part1(lines: List<String>): String {
val input = parseInput(lines)
with(input) {
commands.forEach {
for (i in (0 until it.times)) {
stacks[it.toIndex].addLast(stacks[it.fromIndex].removeLast())
}
}
return stacks.map { it.last() }.reduce{acc, s -> acc + s }
}
}
fun part2(lines: List<String>): String {
val input = parseInput(lines)
with(input) {
commands.forEach { command ->
val from = stacks[command.fromIndex]
val to = stacks[command.toIndex]
(0 until command.times).asSequence()
.map { from.removeLast() }
.toList()
.reversed()
.forEach { to.addLast(it) }
}
return stacks.map { it.last() }.reduce{acc, s -> acc + s }
}
}
val test = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent().lines()
println(part1(test))
println(part1(readInput("Day05")))
println(part2(test))
println(part2(readInput("Day05")))
}
| 0 | Kotlin | 0 | 0 | 363747c25efb002fe118e362fb0c7fecb02e3708 | 3,233 | advent-of-code-2022 | Apache License 2.0 |
src/Day08/Day08.kt | Trisiss | 573,815,785 | false | {"Kotlin": 16486} | fun main() {
fun getNumberVisibleTree(listTree: List<Int>, element: Int, isRevert: Boolean = false): Int {
val range = if (isRevert) listTree.indices.reversed() else listTree.indices
var count = 0
for (i in range) {
if (listTree[i] >= element) {
return count + 1
}
count++
}
return listTree.size
}
fun isVisible(treeMap: List<List<Int>>, position: Pair<Int, Int>): Boolean {
if (position.first == 0 || position.first == treeMap.lastIndex) return true
if (position.second == 0 || position.second == treeMap[position.first].lastIndex) return true
val element = treeMap[position.first][position.second]
val list = mutableListOf<Int>()
for (i in treeMap.indices) {
list.add(treeMap[i][position.second])
}
val sublistStart = treeMap[position.first].subList(0, position.second)
val sublistEnd = treeMap[position.first].subList(position.second + 1, treeMap[position.first].size)
if (sublistStart.max() < element || sublistEnd.max() < element) return true
val sublistTop = list.subList(0, position.first)
val sublistBottom = list.subList(position.first + 1, list.size)
if (sublistTop.max() < element || sublistBottom.max() < element) return true
return false
}
fun getScenicScore(treeMap: List<List<Int>>, position: Pair<Int, Int>): Int {
val multipleList = mutableListOf<Int>()
if (position.first == 0 || position.first == treeMap.lastIndex) return 0
if (position.second == 0 || position.second == treeMap[position.first].lastIndex) return 0
val element = treeMap[position.first][position.second]
val list = mutableListOf<Int>()
for (i in treeMap.indices) {
list.add(treeMap[i][position.second])
}
val sublistStart = treeMap[position.first].subList(0, position.second)
val sublistEnd = treeMap[position.first].subList(position.second + 1, treeMap[position.first].size)
val sublistTop = list.subList(0, position.first)
val sublistBottom = list.subList(position.first + 1, list.size)
multipleList.add(getNumberVisibleTree(sublistStart, element, true))
multipleList.add(getNumberVisibleTree(sublistEnd, element))
multipleList.add(getNumberVisibleTree(sublistTop, element, true))
multipleList.add(getNumberVisibleTree(sublistBottom, element))
return multipleList.reduce { mult, el -> mult * el }
}
fun populateTreeMap(input: List<String>): List<List<Int>> {
val treeMap = mutableListOf<MutableList<Int>>()
input.forEachIndexed { indexLine, line ->
val list = mutableListOf<Int>()
val test = line.split("").filter { it.isNotEmpty() }
test.forEachIndexed { indexColumn, column ->
list.add(indexColumn, column.toInt())
}
treeMap.add(indexLine, list)
}
return treeMap
}
fun part1(input: List<String>): Int {
val treeMap = populateTreeMap(input)
val treeMapBool = mutableListOf<MutableList<Boolean>>()
treeMap.forEachIndexed { indexLine, line ->
val list = mutableListOf<Boolean>()
line.forEachIndexed { indexCol, col ->
val isVisible = isVisible(treeMap, indexLine to indexCol)
list.add(indexCol, isVisible)
}
treeMapBool.add(indexLine, list)
}
return treeMapBool.sumOf { it.count { it } }
}
fun part2(input: List<String>): Int {
val treeMap = populateTreeMap(input)
val treeMapScenic = mutableListOf<List<Int>>()
treeMap.forEachIndexed { indexLine, line ->
val list = mutableListOf<Int>()
line.forEachIndexed { indexCol, col ->
val scenicScore = getScenicScore(treeMap, indexLine to indexCol)
list.add(indexCol, scenicScore)
}
treeMapScenic.add(indexLine, list)
}
return treeMapScenic.maxOf { it.max() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08/Day08_test")
val p1result = part1(testInput)
// println(p1result)
// check(p1result == 21)
val p2result = part2(testInput)
// println(p2result)
// check(p2result == 8)
val input = readInput("Day08/Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cb81a0b8d3aa81a3f47b62962812f25ba34b57db | 4,540 | AOC-2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2022/day13/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2022.day13
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val input = parseInput()
part1(input)
part2(input)
}
fun part1(input: List<*>) {
val result = input
.asSequence()
.windowed(2, 2)
.withIndex()
.sumOf { (index, list) ->
val (left, right) = list
if (checkIsRightOrder(left, right) == Result.PASS) index + 1 else 0
}
println(result)
}
fun part2(input: List<*>) {
val modified = input.toMutableList()
val dp1 = listOf(listOf(2))
val dp2 = listOf(listOf(6))
modified.add(dp1)
modified.add(dp2)
modified.sortWith { a, b ->
when (checkIsRightOrder(a, b)) {
Result.PASS -> -1
Result.FAIL -> 1
else -> 0
}
}
val result = (modified.indexOf(dp1) + 1) * (modified.indexOf(dp2) + 1)
println(result)
}
fun parseInput(): List<*> = buildList {
readInput(2022, 13).forEachLine { if (it.isNotEmpty()) add(parseLine(it)) }
}
fun parseLine(line: String): List<*> {
val stack = ArrayDeque<MutableList<Any>>()
val sb = StringBuilder()
for (index in 0 until line.lastIndex) {
when (val char = line[index]) {
'[' -> stack.addLast(mutableListOf())
']' -> {
if (sb.isNotEmpty()) {
stack.last().add(sb.toString().toInt())
sb.clear()
}
val list = stack.removeLast()
stack.last().add(list)
}
',' -> if (sb.isNotEmpty()) {
stack.last().add(sb.toString().toInt())
sb.clear()
}
else -> sb.append(char)
}
}
if (sb.isNotEmpty()) stack.last().add(sb.toString().toInt())
return stack.last()
}
fun checkIsRightOrder(left: Any?, right: Any?): Result {
return if (left is List<*> && right is List<*>) {
for (index in left.indices) {
if (right.lastIndex < index) return Result.FAIL
val tempResult = checkIsRightOrder(left[index], right[index])
if (tempResult != Result.UNDEFINED) return tempResult
}
if (right.size > left.size) Result.PASS else Result.UNDEFINED
} else if (left is Int && right is Int) when {
left < right -> Result.PASS
left > right -> Result.FAIL
else -> Result.UNDEFINED
} else if (left is Int) checkIsRightOrder(listOf(left), right)
else checkIsRightOrder(left, listOf(right))
}
enum class Result {
PASS, FAIL, UNDEFINED
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 2,607 | adventofcode | Apache License 2.0 |
src/Day11_MonkeyBusiness.kt | sherviiin | 575,114,981 | false | {"Kotlin": 14948} | fun main() {
check(10605 == findHighestChance(input = readInput("Day11_sample_data"), rounds = 20, divideBy3 = true).toInt())
println(findHighestChance(input = readInput("Day11"), rounds = 10000, divideBy3 = false))
}
fun findHighestChance(input: List<String>, rounds: Int, divideBy3: Boolean): Long {
val monkeys = mutableListOf<Monkey>()
input.forEach { l ->
val line = l.trim()
if (line.startsWith("Monkey")) {
val id = line.removePrefix("Monkey ").removeSuffix(":").toInt()
monkeys.add(Monkey(id, mutableListOf()))
}
if (line.trim().startsWith("Starting items:")) {
val items = line.removePrefix("Starting items: ").split(", ").map { it.toLong() }
monkeys.last().items.addAll(items)
}
if (line.startsWith("Operation: new = old ")) {
val split = line.removePrefix("Operation: new = old ").split(" ")
monkeys.last().operation = Operation(Operator.fromString(split[0]), split[1])
}
if (line.startsWith("Test: divisible by ")) {
val condition = line.removePrefix("Test: divisible by ").toLong()
monkeys.last().condition = condition
}
if (line.startsWith("If true: throw to monkey ")) {
val id = line.removePrefix("If true: throw to monkey ").toInt()
monkeys.last().trueTargetMonkey = id
}
if (line.startsWith("If false: throw to monkey ")) {
val id = line.removePrefix("If false: throw to monkey ").toInt()
monkeys.last().falseTargetMonkey = id
}
}
round(monkeys, rounds, divideBy3)
monkeys.sortByDescending { it.inspected }
return monkeys.take(2).map { it.inspected }.reduce { i, j -> i * j }
}
fun round(monkeys: List<Monkey>, rounds: Int, divideBy3: Boolean) {
val base = monkeys.fold(1L) { acc, monkey -> acc * monkey.condition }
repeat(rounds) {
monkeys.forEach { monkey ->
val itemsIterator = monkey.items.iterator()
while (itemsIterator.hasNext()) {
val item = itemsIterator.next()
var worryLevel = monkey.operation!!.let { op ->
val operand = if (op.operand == "old") item else op.operand.toLong()
when (op.operator) {
Operator.Add -> item + operand
Operator.Divide -> item / operand
Operator.Multiply -> item * operand
Operator.Subtract -> item - operand
}
}
if (divideBy3) {
worryLevel /= 3
} else {
worryLevel = worryLevel.mod(base)
}
if (worryLevel % monkey.condition == 0L) {
monkeys.first { it.id == monkey.trueTargetMonkey }.items.add(worryLevel)
} else {
monkeys.first { it.id == monkey.falseTargetMonkey }.items.add(worryLevel)
}
monkey.inspected++
itemsIterator.remove()
}
}
}
}
data class Monkey(
val id: Int,
val items: MutableList<Long>,
var operation: Operation? = null,
var condition: Long = 0,
var trueTargetMonkey: Int = 0,
var falseTargetMonkey: Int = 0,
var inspected: Long = 0
)
sealed class Operator {
object Multiply : Operator()
object Divide : Operator()
object Add : Operator()
object Subtract : Operator()
companion object {
fun fromString(string: String): Operator {
return when (string) {
"*" -> Multiply
"/" -> Divide
"-" -> Subtract
"+" -> Add
else -> throw UnsupportedOperationException()
}
}
}
}
data class Operation(val operator: Operator, val operand: String) | 0 | Kotlin | 0 | 1 | 5e52c1b26ab0c8eca8d8d93ece96cd2c19cbc28a | 3,942 | advent-of-code | Apache License 2.0 |
src/Day25.kt | RusticFlare | 574,508,778 | false | {"Kotlin": 78496} | import kotlin.math.max
private data class CarryOverState(val previousDigit: Int, val carryOver: Int) {
init {
require(previousDigit in Snafu.validDigits) { "Invalid previousValue <$previousDigit>" }
}
companion object {
val INITIAL = CarryOverState(previousDigit = 0, carryOver = 0)
}
}
private fun List<Int>.padZeros(newSize: Int) = plus(List(newSize - size) { 0 })
private data class Snafu(val digits: List<Int>) {
init {
require(digits.all { it in validDigits }) { digits }
}
operator fun plus(other: Snafu): Snafu {
val zipSize = max(digits.size, other.digits.size)
val carryOverStates = digits.padZeros(zipSize).zip(other.digits.padZeros(zipSize), transform = Int::plus)
.runningFold(CarryOverState.INITIAL) { (_, carryOver), digit ->
var value = digit + carryOver
var toCarryOver = 0
while (value !in validDigits) {
when {
value < validDigits.first -> {
value += 5
toCarryOver -= 1
}
value > validDigits.last -> {
value -= 5
toCarryOver += 1
}
}
}
CarryOverState(previousDigit = value, carryOver = toCarryOver)
}.drop(1)
return Snafu(
carryOverStates.map { it.previousDigit } + carryOverStates.last().carryOver
)
}
override fun toString(): String = digits.reversed()
.dropWhile { it == 0 }
.joinToString(separator = "") {
when (it) {
0, 1, 2 -> it.toString()
-1 -> "-"
-2 -> "="
else -> error(it)
}
}
companion object {
val validDigits = -2..2
fun parse(input: String) = Snafu(
input.reversed().map {
it.digitToIntOrNull() ?: when (it) {
'-' -> -1
'=' -> -2
else -> error(it)
}
}
)
}
}
fun main() {
fun part1(input: List<String>): String {
return input.map { Snafu.parse(it) }
.reduce(Snafu::plus)
.toString()
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day25_test")
check(part1(testInput) == "2=-1=0")
// check(part2(testInput) == 4)
val input = readLines("Day25")
with(part1(input)) {
check(this == "2-2--02=1---1200=0-1")
println(this)
}
// with(part2(input)) {
// check(this == 569)
// println(this)
// }
}
| 0 | Kotlin | 0 | 1 | 10df3955c4008261737f02a041fdd357756aa37f | 2,877 | advent-of-code-kotlin-2022 | Apache License 2.0 |
lib/src/main/kotlin/com/bloidonia/advent/day18/Day18.kt | timyates | 433,372,884 | false | {"Kotlin": 48604, "Groovy": 33934} | package com.bloidonia.advent.day18
import com.bloidonia.advent.readList
import kotlin.math.ceil
import kotlin.math.floor
data class Num(val n: Int, val level: Int)
data class SnailFish(val values: List<Num>) {
operator fun plus(other: SnailFish) =
SnailFish(values.map { Num(it.n, it.level + 1) } + other.values.map { Num(it.n, it.level + 1) })
private fun explode(): SnailFish? {
if (values.none { it.level > 4 }) return null
val idx = values.indexOfFirst { it.level > 4 }
val pair = values.subList(idx, idx + 2)
val lhs = values.take(idx).let {
if (it.isNotEmpty()) {
it.take(it.size - 1) + Num(it.last().n + pair[0].n, it.last().level)
} else {
it
}
}
val rhs = values.drop(idx + 2).let {
if (it.isNotEmpty()) {
listOf(Num(it[0].n + pair[1].n, it[0].level)) + it.drop(1)
} else {
it
}
}
return SnailFish(lhs + Num(0, pair[0].level - 1) + rhs)
}
fun split(): SnailFish? {
if (values.none { it.n >= 10 }) return null
val idx = values.indexOfFirst { it.n >= 10 }
val num = values[idx]
return SnailFish(
values.take(idx) + listOf(
Num(floor(num.n / 2.0).toInt(), num.level + 1),
Num(ceil(num.n / 2.0).toInt(), num.level + 1)
) + values.drop(idx + 1)
)
}
private fun magnitude(lhs: Num, rhs: Num) = Num((3 * lhs.n) + (2 * rhs.n), lhs.level - 1)
fun magnitude(): Int {
if (values.size == 1) {
return values[0].n
}
val maxLevel = values.maxOf { it.level }
val first = values.indexOfFirst { it.level == maxLevel }
val newFish = SnailFish(values.take(first) + magnitude(values[first], values[first + 1]) + values.drop(first + 2))
return newFish.magnitude()
}
fun reduce(): SnailFish {
var data: SnailFish = this
while(true) {
val exploded = data.explode()
if (exploded != null) {
data = exploded
continue
}
val split = data.split()
if (split != null) {
data = split
continue
}
break
}
return data
}
override fun toString() = values.joinToString(",") { "${it.n}(${it.level})" }
}
fun String.toSnailFish(): SnailFish {
var level = 0
return SnailFish(this
.replace("[", ".[.")
.replace("]", ".].")
.split("[,.]".toPattern())
.filter { it.isNotEmpty() }
.mapNotNull {
when (it) {
"[" -> {
level++
null
}
"]" -> {
level--
null
}
else -> Num(it.toInt(), level)
}
})
}
fun <T, S> Collection<T>.cartesianProduct(other: Iterable<S>): List<Pair<T, S>> {
return cartesianProduct(other) { first, second -> first to second }
}
fun <T, S, V> Collection<T>.cartesianProduct(other: Iterable<S>, transformer: (first: T, second: S) -> V): List<V> {
return this.flatMap { first -> other.map { second -> transformer.invoke(first, second) } }
}
fun main() {
val input = readList("/day18input.txt") { it.toSnailFish() }
println(input.reduce { a, b -> (a + b).reduce() }.magnitude())
println(input.cartesianProduct(input).map { (a, b) -> (a + b).reduce().magnitude() }.maxOf { it })
} | 0 | Kotlin | 0 | 1 | 9714e5b2c6a57db1b06e5ee6526eb30d587b94b4 | 3,612 | advent-of-kotlin-2021 | MIT License |
src/year2023/day11/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2023.day11
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import year2023.solveIt
fun main() {
val day = "11"
val expectedTest1 = 374L
val expectedTest2 = 82000210L
fun getDistance(
expansionItems: Set<Int>, factor: Long, a: Int, b: Int
): Long {
val expansionsX = (min(a, b)..max(a, b)).count { expansionItems.contains(it) }
return abs(b - a) + factor * expansionsX - expansionsX
}
fun getDistance(g1: Pair<Int, Int>, g2: Pair<Int, Int>, expansionLines: Set<Int>, expansionColumns: Set<Int>, factor: Long): Long {
val dx = getDistance(expansionColumns, factor, g1.second, g2.second)
val dy = getDistance(expansionLines, factor, g1.first, g2.first)
return dx + dy
}
fun getIt(input: List<String>, expansionFactor: Long): Long {
val galaxies = input.flatMapIndexed { l, line -> line.mapIndexedNotNull { c, char -> if (char == '#') l to c else null } }
val galaxiesConnections = galaxies.flatMapIndexed { index: Int, gal: Pair<Int, Int> -> galaxies.drop(index + 1).map { gal to it } }
val expansionLines = input.indices.filter { idx -> galaxies.none { it.first == idx } }.toSet()
val expansionColumns = input[0].indices.filter { idx -> galaxies.none { it.second == idx } }.toSet()
return galaxiesConnections.stream().parallel().mapToLong { c-> getDistance(c.first, c.second, expansionLines, expansionColumns, expansionFactor) }.sum()
}
fun part1(input: List<String>): Long {
return getIt(input, 2L)
}
fun part2(input: List<String>): Long {
return getIt(input, 1000000L)
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test")
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 1,757 | adventOfCode | Apache License 2.0 |
src/day02/Day02.kt | barbulescu | 572,834,428 | false | {"Kotlin": 17042} | package day02
import day02.Choice.*
import readInput
fun main() {
val total = readInput("day02/Day02")
.map { line -> line.split("\\s".toRegex()) }
.map { BattleV1(it) }
.sumOf { it.calculate() }
println("Total: $total")
val total2 = readInput("day02/Day02")
.map { line -> line.split("\\s".toRegex()) }
.map { BattleV2(it) }
.sumOf { it.calculate() }
println("Total2: $total2")
}
private data class BattleV1(val opponent: Choice, val you: Choice) {
constructor(line: List<String>) : this(line[0].firstPlayer(), line[1].secondPlayer())
fun calculate(): Int = you.value + battle(you, opponent)
}
private data class BattleV2(val opponent: Choice, val you: Choice) {
constructor(line: List<String>) : this(line[0].firstPlayer(), line[1].desiredOutcome(line[0].firstPlayer()))
fun calculate(): Int = you.value + battle(you, opponent)
}
private fun battle(choice1: Choice, choice2: Choice): Int {
return when {
choice1 == choice2 -> 3
choice1 == ROCK && choice2 == SCISSORS -> 6
choice1 == SCISSORS && choice2 == PAPER -> 6
choice1 == PAPER && choice2 == ROCK -> 6
else -> 0
}
}
private enum class Choice(val value: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3)
}
private fun String.firstPlayer(): Choice = when (this) {
"A" -> ROCK
"B" -> PAPER
"C" -> SCISSORS
else -> error("Invalid choice $this")
}
private fun String.secondPlayer(): Choice = when (this) {
"X" -> ROCK
"Y" -> PAPER
"Z" -> SCISSORS
else -> error("Invalid choice $this")
}
private fun String.desiredOutcome(opponent: Choice): Choice = when (this) {
"X" -> opponent.losingValue()
"Y" -> opponent
"Z" -> opponent.winningValue()
else -> error("Invalid choice $this")
}
private fun Choice.losingValue() : Choice {
return when(this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
private fun Choice.winningValue() : Choice {
return when(this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
} | 0 | Kotlin | 0 | 0 | 89bccafb91b4494bfe4d6563f190d1b789cde7a4 | 2,123 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/ru/glukhov/aoc/Day2.kt | cobaku | 576,736,856 | false | {"Kotlin": 25268} | package ru.glukhov.aoc
import java.io.BufferedReader
enum class Element(val value: String, val weight: Int) {
ROCK("A", 1), PAPER("B", 2), SCISSORS("C", 3);
companion object {
fun rockPaperScissors(row: String): Int = row.split(" ")
.let { Pair(Element.parse(it[0]), Element.parse(it[1])) }
.let { Element.play(it.second, it.first).weight + it.second.weight }
fun normalize(row: String): String = row.replace("X", "A").replace("Y", "B").replace("Z", "C")
fun parse(char: String): Element = Element.values().find { element -> element.value == char }
?: throw IllegalArgumentException("Element for $char not found")
private fun play(a: Element, b: Element): Result = if (a == b) Result.DRAW
else when (a) {
ROCK -> if (b == PAPER) Result.LOSE else Result.WIN
PAPER -> if (b == SCISSORS) Result.LOSE else Result.WIN
SCISSORS -> if (b == ROCK) Result.LOSE else Result.WIN
}
}
}
enum class Result(val code: String, val weight: Int) {
LOSE("X", 0), DRAW("Y", 3), WIN("Z", 6);
companion object {
private fun parse(char: String): Result = Result.values().find { result -> result.code == char }
?: throw IllegalArgumentException("Element for $char not found")
private fun guessMyElement(element: Element, result: Result): Element = if (result == DRAW) element
else when (element) {
Element.ROCK -> if (result == LOSE) Element.SCISSORS else Element.PAPER
Element.PAPER -> if (result == LOSE) Element.ROCK else Element.SCISSORS
Element.SCISSORS -> if (result == LOSE) Element.PAPER else Element.ROCK
}
fun rockPaperScissors(row: String): Int = row.split(" ").let { Pair(Element.parse(it[0]), Result.parse(it[1])) }
.let { Result.guessMyElement(it.first, it.second).weight + it.second.weight }
}
}
fun main() {
Problem.forDay("day2").use { solveFirst(it) }.let { println("Result of the first problem is $it") }
Problem.forDay("day2").use { solveSecond(it) }.let { println("Result of the second problem is $it") }
}
private fun solveFirst(input: BufferedReader): Int =
input.lines().mapToInt { Element.rockPaperScissors(Element.normalize(it)) }.sum()
private fun solveSecond(input: BufferedReader): Int = input.lines().mapToInt { Result.rockPaperScissors(it) }.sum() | 0 | Kotlin | 0 | 0 | a40975c1852db83a193c173067aba36b6fe11e7b | 2,426 | aoc2022 | MIT License |
src/Day04.kt | hiteshchalise | 572,795,242 | false | {"Kotlin": 10694} | fun main() {
fun part1(input: List<String>): Int {
val fullyOverlappingRangeList = input.filter { line ->
val (first, second) = line.split(",")
val firstRange = first.split('-').map { it.toInt() }
val secondRange = second.split('-').map { it.toInt() }
// Checking if secondRange is fully overlapped by firstRange
if (firstRange.first() <= secondRange.first()
&& firstRange.last() >= secondRange.last()
) true
// Checking if firstRange is fully overlapped by secondRange
else firstRange.first() >= secondRange.first()
&& firstRange.last() <= secondRange.last()
}
return fullyOverlappingRangeList.size
}
fun part2(input: List<String>): Int {
val partialOverlappingRangeList = input.filter { line ->
val (first, second) = line.split(",")
val firstRange = first.split('-').map { it.toInt() }
val secondRange = second.split('-').map { it.toInt() }
if (firstRange.first() <= secondRange.first()
&& firstRange.last() >= secondRange.first()
) true
else firstRange.first() >= secondRange.first()
&& firstRange.first() <= secondRange.last()
}
return partialOverlappingRangeList.size
}
// 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 | e4d66d8d1f686570355b63fce29c0ecae7a3e915 | 1,655 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/lucaszeta/adventofcode2020/day10/day10.kt | LucasZeta | 317,600,635 | false | null | package com.lucaszeta.adventofcode2020.day10
import com.lucaszeta.adventofcode2020.ext.getResourceAsText
const val CHARGING_OUTLET_JOLTAGE = 0
fun main() {
val bagAdapterJoltages = getResourceAsText("/day10/adapters-output-joltage.txt")
.split("\n")
.filter { it.isNotEmpty() }
.map { it.toInt() }
val connections = addFirstAndLastJoltages(bagAdapterJoltages)
val differencesMap = connections.findJoltageGroupDifferences()
val possibleArrangements = connections.calculateTotalArrangements()
println(
"Product of 1-jolt difference by 3-jolt difference: %d".format(
differencesMap.getValue(1) * differencesMap.getValue(3)
)
)
println("Possible adapter arrangements: $possibleArrangements")
}
fun List<Int>.findJoltageGroupDifferences(): Map<Int, Int> {
return findDifferences(this)
.groupBy { it }
.mapValues { it.value.size }
}
fun List<Int>.calculateTotalArrangements(): Long {
val differences = findDifferences(this).joinToString("")
val sequencesOfOne = "(1+)".toRegex().findAll(differences)
return sequencesOfOne.map {
calculatePossibleArrangementsForSize(it.groupValues[1].length).toLong()
}.reduce(Long::times)
}
fun calculatePossibleArrangementsForSize(size: Int): Int {
val arrangementSequence = mutableListOf(1, 1, 2)
return if (size < arrangementSequence.size) {
arrangementSequence[size]
} else {
repeat(size - arrangementSequence.size + 1) {
val lastThreeValues = (arrangementSequence.size - 3) until arrangementSequence.size
arrangementSequence.add(
arrangementSequence.slice(lastThreeValues).reduce(Int::plus)
)
}
arrangementSequence.last()
}
}
fun findDifferences(joltageList: List<Int>): List<Int> {
val sortedValues = joltageList.sorted()
return sortedValues
.mapIndexed { index, joltage ->
if (index > 0) {
joltage - sortedValues[index - 1]
} else 0
}
.filter { it != 0 }
}
fun findDeviceAdapterJoltage(bagAdapterJoltages: List<Int>) =
(bagAdapterJoltages.maxOrNull() ?: 0) + 3
fun addFirstAndLastJoltages(bagAdapterJoltages: List<Int>) = bagAdapterJoltages
.toMutableList()
.apply {
add(CHARGING_OUTLET_JOLTAGE)
add(findDeviceAdapterJoltage(bagAdapterJoltages))
}
.toList()
| 0 | Kotlin | 0 | 1 | 9c19513814da34e623f2bec63024af8324388025 | 2,441 | advent-of-code-2020 | MIT License |
src/main/kotlin/com/ryanmoelter/advent/day02/RockPaperScissors.kt | ryanmoelter | 573,615,605 | false | {"Kotlin": 84397} | package com.ryanmoelter.advent.day02
import com.ryanmoelter.advent.day02.Result.*
import com.ryanmoelter.advent.day02.Shape.*
enum class Shape(val value: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
infix fun vs(other: Shape) = when (this) {
ROCK -> when (other) {
ROCK -> DRAW
PAPER -> LOSE
SCISSORS -> WIN
}
PAPER -> when (other) {
ROCK -> WIN
PAPER -> DRAW
SCISSORS -> LOSE
}
SCISSORS -> when (other) {
ROCK -> LOSE
PAPER -> WIN
SCISSORS -> DRAW
}
}
}
enum class Result(val value: Int) {
WIN(6), LOSE(0), DRAW(3);
fun getMine(other: Shape): Shape = when (this) {
WIN -> when (other) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
LOSE -> when (other) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
DRAW -> other
}
}
class Match(other: Shape, mine: Shape) {
val value = mine.value + (mine vs other).value
constructor(other: Shape, result: Result) : this(other, result.getMine(other))
}
fun Char.toShape() = when (this) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> error("Invalid: $this")
}
fun Char.toResult() = when (this) {
'X' -> LOSE
'Y' -> DRAW
'Z' -> WIN
else -> error("Invalid: $this")
}
fun main() {
println(calculateScoreByResults(day02Input))
}
fun calculateScoreByResults(input: String): Int = input.lineSequence()
.filter { it.isNotBlank() }
.map { line -> line.split(' ').map { it.first() } }
.map { Match(it[0].toShape(), it[1].toResult()) }
.map { it.value }
.sum()
fun calculateScoreByShapes(input: String): Int = input.lineSequence()
.filter { it.isNotBlank() }
.map { line -> line.split(' ').map { it.first() }.map { it.toShape() } }
.map { Match(it[0], it[1]) }
.map { it.value }
.sum()
| 0 | Kotlin | 0 | 0 | aba1b98a1753fa3f217b70bf55b1f2ff3f69b769 | 1,837 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | meierjan | 572,860,548 | false | {"Kotlin": 20066} | import Interval.Companion.parseLine
import java.util.*
import kotlin.io.path.createTempDirectory
data class CrateStack(
val stacks: List<Stack<Char>>
) {
companion object {
fun parse(text: List<String>): CrateStack {
val stackNumber = text.first().length / 4 + 1
val stacks = MutableList(stackNumber) { Stack<Char>() }
val divider = text.indexOfFirst { it.isEmpty() }
val crateDefinition = text.subList(0, divider - 1)
crateDefinition.reversed().forEach {
it.chunked(4).forEachIndexed { index, crate ->
if (crate.isNotBlank()) {
val letter = crate.trim().trimStart('[').trimEnd(']').first()
stacks[index].push(letter)
}
}
}
return CrateStack(stacks)
}
}
}
data class MovementDefinition(
val amount: Int,
val from: Int,
val to: Int
) {
companion object {
fun parse(text: List<String>): List<MovementDefinition> {
val divider = text.indexOfFirst { it.isEmpty() }
val movementDefinition = text.subList(divider + 1, text.size)
return movementDefinition.map {
val splitDefinition = it.split(" ")
MovementDefinition(
amount = splitDefinition[1].toInt(),
from = splitDefinition[3].toInt() - 1,
to = splitDefinition[5].toInt() - 1
)
}
}
}
}
fun day5_part1(input: List<String>): String {
val crateStack = CrateStack.parse(input)
val movements = MovementDefinition.parse(input)
movements.forEach { operation ->
val amount = operation.amount
repeat(amount) {
crateStack.stacks[operation.to].push(crateStack.stacks[operation.from].pop())
}
}
return crateStack.stacks.map { it.pop() }.joinToString("")
}
fun day5_part2(input: List<String>): String {
val crateStack = CrateStack.parse(input)
val movements = MovementDefinition.parse(input)
movements.forEach { operation ->
val amount = operation.amount
val crates = mutableListOf<Char>()
repeat(amount) {
crates.add(crateStack.stacks[operation.from].pop())
}
for (crateToMove in crates.reversed()) {
crateStack.stacks[operation.to].push(crateToMove)
}
}
return crateStack.stacks.map { it.pop() }.joinToString("")
}
fun main() {
// // test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_1_test")
println(day5_part1(testInput))
check(day5_part1(testInput) == "CMZ")
val input = readInput("Day05_1")
println(day5_part1(input))
println(day5_part2(testInput))
check(day5_part2(testInput) == "MCD")
println(day5_part2(input))
}
| 0 | Kotlin | 0 | 0 | a7e52209da6427bce8770cc7f458e8ee9548cc14 | 2,937 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/aoc2023/day7/day7Solver.kt | Advent-of-Code-Netcompany-Unions | 726,531,711 | false | {"Kotlin": 94973} | package aoc2023.day7
import lib.*
suspend fun main() {
setupChallenge().solveChallenge()
}
data class Hand(val cards: List<Int>, val bid: Long)
fun setupChallenge(): Challenge<List<Hand>> {
return setup {
day(7)
year(2023)
parser {
it.readLines()
.map { it.split(" ") }
.map { Hand(it[0].getCardValue(), it[1].toLong()) }
}
partOne {
val ranks = it.sortedWith(part1comparator)
ranks.mapIndexed { index, hand ->
hand.bid * (index + 1)
}
.sum().toString()
}
partTwo {
val ranks = it.sortedWith(part2comparator)
ranks.mapIndexed { index, hand ->
hand.bid * (index + 1L)
}
.sum().toString()
}
}
}
fun String.getCardValue(): List<Int> {
return this.map {
when (it) {
'A' -> 14
'K' -> 13
'Q' -> 12
'J' -> 11
'T' -> 10
else -> it.digitToInt()
}
}
}
fun List<Int>.getMatchCounts(): List<Int> {
val jokers = this.count { it == 1 }
if(jokers in 1..4) {
val res = this.filter { it != 1 }.groupBy { it }.values.map { it.size }.sortedDescending().toIntArray()
res[0] += jokers
return res.toList()
}
return this.groupBy { it }.values.map { it.size }.sortedDescending()
}
fun List<Int>.compareTo(other: List<Int>): Int {
this.zip(other).forEach {
if(it.first != it.second) {
return it.first.compareTo(it.second)
}
}
return this.size.compareTo(other.size)
}
val part1comparator = Comparator<Hand> { a, b ->
val aCounts = a.cards.getMatchCounts()
val bCounts = b.cards.getMatchCounts()
val res = aCounts.compareTo(bCounts)
if(res == 0) a.cards.compareTo(b.cards) else res
}
val part2comparator = Comparator<Hand> { a, b ->
val aCards = a.cards.map { if (it == 11) 1 else it }
val bCards = b.cards.map { if (it == 11) 1 else it }
val aCounts = aCards.getMatchCounts()
val bCounts = bCards.getMatchCounts()
val res = aCounts.compareTo(bCounts)
if(res == 0) aCards.compareTo(bCards) else res
} | 0 | Kotlin | 0 | 0 | a77584ee012d5b1b0d28501ae42d7b10d28bf070 | 2,260 | AoC-2023-DDJ | MIT License |
src/twentytwo/Day05.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentytwo
import java.util.*
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("Day05_test")
println(part1(testInput))
check(part1(testInput) == "CMZ")
println(part2(testInput))
check(part2(testInput) == "MCD")
println("---")
val input = readInputLines("Day05_input")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): String {
val (stackInputLines, moveInputLines) = input.split("")
val stacks = inputToStacks(stackInputLines)
val moves = moveInputLines.map { StackMove.create(it) }
moves.forEach { move ->
executeMoveWith9000(stacks, move)
}
val topItems = stacks.map { it.pop() }
return topItems.joinToString(separator = "")
}
private fun inputToStacks(input: List<String>): List<Stack<Char>> {
val chunked = input.map { stackInputLine -> // [N] [C] [P]
stackInputLine.chunked(4).map {
it[1] // [N]
}
}
val stacks = List(chunked.last().size) { Stack<Char>() }
chunked.dropLast(1).reversed().forEach { line ->
line.forEachIndexed { index, entry ->
if (entry != ' ') {
stacks[index].push(entry)
}
}
}
return stacks
}
private fun executeMoveWith9000(stacks: List<Stack<Char>>, move: StackMove) {
for (i in 0 until move.quantity) {
val char = stacks[move.fromStack-1].pop()
stacks[move.toStack-1].push(char)
}
}
private fun executeMoveWith9001(stacks: List<Stack<Char>>, move: StackMove) {
val tempStack = Stack<Char>()
for (i in 0 until move.quantity) {
val char = stacks[move.fromStack-1].pop()
tempStack.push(char)
}
while (tempStack.isNotEmpty()) {
stacks[move.toStack-1].push(tempStack.pop())
}
}
private data class StackMove(val quantity: Int, val fromStack: Int, val toStack: Int) {
companion object {
fun create(input: String): StackMove {
val inputParts = input.split(" ")
return StackMove(
quantity = inputParts[1].toInt(),
fromStack = inputParts[3].toInt(),
toStack = inputParts[5].toInt(),
)
}
}
}
private fun part2(input: List<String>): String {
val (stackInputLines, moveInputLines) = input.split("")
val stacks = inputToStacks(stackInputLines)
val moves = moveInputLines.map { StackMove.create(it) }
moves.forEach { move ->
executeMoveWith9001(stacks, move)
}
val topItems = stacks.map { it.pop() }
return topItems.joinToString(separator = "")
}
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 2,672 | advent-of-code-solutions | Apache License 2.0 |
src/main/kotlin/d12/D12_1.kt | MTender | 734,007,442 | false | {"Kotlin": 108628} | package d12
import input.Input
fun parseInput(lines: List<String>): List<SpringRow> {
return lines.map { line ->
val parts = line.split(" ")
val springs = parts[0].trim { it == '.' }.replace("\\.+".toRegex(), ".")
val groups = parts[1].split(",").map { it.toInt() }
SpringRow(springs, groups)
}
}
fun permutations(current: String, active: Int, inactive: Int): List<String> {
if (active < 0 || inactive < 0) return listOf()
if (active == 0 && inactive == 0) return listOf(current)
return permutations("$current.", active - 1, inactive) +
permutations("$current#", active, inactive - 1)
}
fun replaceUnknowns(template: String, permutation: String): String {
var result = template
var pI = 0
for (i in template.indices) {
if (template[i] != '?') continue
result = result.replaceRange(i, i + 1, permutation[pI++].toString())
}
return result
}
fun matches(row: String, groups: List<Int>): Boolean {
val inactiveGroups = row.split("\\.+".toRegex()).toMutableList()
inactiveGroups.removeIf { it.isEmpty() }
for (i in inactiveGroups.indices) {
if (inactiveGroups[i].length != groups[i]) return false
}
return true
}
fun main() {
val lines = Input.read("input.txt")
val springRows = parseInput(lines)
var count = 0
for (row in springRows) {
val currentInactiveCount = row.springs.count { it == '#' }
val unknownCount = row.springs.count { it == '?' }
val requiredInactiveCount = row.groups.sum() - currentInactiveCount
val requiredActiveCount = unknownCount - requiredInactiveCount
val permutations = permutations("", requiredActiveCount, requiredInactiveCount)
var rowCount = 0
for (permutation in permutations) {
val filledRow = replaceUnknowns(row.springs, permutation)
if (matches(filledRow, row.groups)) rowCount++
}
count += rowCount
}
println(count)
} | 0 | Kotlin | 0 | 0 | a6eec4168b4a98b73d4496c9d610854a0165dbeb | 2,013 | aoc2023-kotlin | MIT License |
src/Day01.kt | pmatsinopoulos | 730,162,975 | false | {"Kotlin": 10493} | val ZERO_TO_DIGITS = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9"
)
private fun calibrate(s: String): Int = "${s.first { it.isDigit() }}${s.last { it.isDigit() }}".toInt()
private fun calibrate2(s: String): Int {
return calibrate(s.mapIndexedNotNull { index, c ->
if (c.isDigit()) {
c
} else {
s.possibleWordsAtIndex(index).firstNotNullOfOrNull { candidate ->
ZERO_TO_DIGITS[candidate]
}
}
}.joinToString())
}
private fun String.possibleWordsAtIndex(index: Int): List<String> {
return (3..5).map { len ->
substring(index, (index + len).coerceAtMost(length))
}
}
// 53551
fun main() {
fun part1(input: List<String>): Int = input.sumOf { s -> calibrate(s) }
fun part2(input: List<String>): Int = input.sumOf { s -> calibrate2(s) }
// test if implementation meets criteria from the description, like:
var testInput = readInput("Day01_test")
check(part1(testInput) == 142)
testInput = readInput("Day01_test2")
check(part2(testInput) == 281)
val input = readInput("Day01")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | f913207842b2e6491540654f5011127d203706c6 | 1,296 | advent-of-code-kotlin-template | Apache License 2.0 |
src/Day07.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | fun main() {
fun part1(input: List<String>): Int {
val rootDir = fillTree(input)
return getSumSizesLess100K(rootDir)
}
fun part2(input: List<String>): Int {
val rootDir = fillTree(input)
return getDeletingDirSize(rootDir)
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private class Directory(val parent: Directory?) {
val directories = mutableMapOf<String, Directory>()
val files = mutableMapOf<String, File>()
}
private class File(val size: Int)
private fun fillTree(input: List<String>): Directory {
var result: Directory? = null
var currentDirectory: Directory? = null
for (s in input) {
when {
s.startsWith("$ ls") -> {}
s.startsWith("$ cd") -> {
val dirname = s.substring(5)
currentDirectory = when (dirname) {
"/" -> {
result = Directory(null)
result
}
".." -> currentDirectory?.parent
else -> currentDirectory?.directories?.get(dirname)
}
}
else -> {
if (s.startsWith("dir")) {
val name = s.substring(4)
currentDirectory?.directories?.put(name,
Directory(currentDirectory))
}
else {
val substr = s.split(" ")
currentDirectory?.files?.put(substr[1],
File(substr[0].toInt())
)
}
}
}
}
return result!!
}
private fun getSumSizesLess100K(rootDir: Directory): Int {
var result = 0
fun getSum(rootDir: Directory): Int {
var innerResult = rootDir.files
.map { it.value.size }
.sum()
for(directory in rootDir.directories.values)
innerResult += getSum(directory)
if (innerResult <= 100000 )
result += innerResult
return innerResult
}
getSum(rootDir)
return result
}
private const val FULL_SPACE = 70000000
private const val NEED_TO_FREE = 30000000
private fun getDeletingDirSize(rootDir: Directory): Int {
val sizeList = mutableListOf<Int>()
fun getSum(rootDir: Directory): Int{
var innerResult = rootDir.files
.map { it.value.size }
.sum()
for(directory in rootDir.directories.values)
innerResult += getSum(directory)
sizeList.add(innerResult)
return innerResult
}
val fullSum = getSum(rootDir)
val freeSize = FULL_SPACE - fullSum
var minDirSize = fullSum
sizeList.forEach {
if (freeSize + it >= NEED_TO_FREE && it < minDirSize) {
minDirSize = it
}
}
return minDirSize
}
| 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 3,025 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/kr/co/programmers/P12978.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/411
class P12978 {
companion object {
const val INF = 500_001 // 최대 시간은 K + 1
}
fun solution(N: Int, road: Array<IntArray>, k: Int): Int {
if (N == 1) return 1
// 행노드 -> 열노드간의 거리를 2차원 배열에 담는다.
val graph = makeGraph(N, road)
// 노드 방문 여부
val visited = BooleanArray(N + 1)
// 이동 시간
val times = IntArray(N + 1) {
if (it >= 2) INF else 0
}
var node = 1 // 1번 마을에서 시작
while (node != INF) {
visited[node] = true
// 갈 수 있는 노드 계산
for (i in 1..N) {
if (visited[i]) continue
if (graph[node][i] == INF) continue
// 시간 갱신
if (times[node] + graph[node][i] < times[i]) {
times[i] = times[node] + graph[node][i]
}
}
// 가장 최소 시간를 가지는 노드를 구한다.
node = run {
var min = INF
var idx = INF
for (i in 1 .. N) {
if (!visited[i] && times[i] < min) {
min = times[i]
idx = i
}
}
idx
}
}
// K 시간 이하로 배달이 가능한 노드 개수 세기
var answer = 0
for (i in 1 until times.size) {
if (times[i] <= k) answer++
}
return answer
}
private fun makeGraph(N: Int, road: Array<IntArray>): Array<IntArray> {
val graph = Array(N + 1) {
IntArray(N + 1)
}
// 디폴트를 0 또는 INF
for (i in 1..N) {
for (j in 1..N) {
if (i == j) continue
graph[i][j] = INF
}
}
// 마을간에 여러개의 길이 있을 수 있으므로 최단 거리만 남긴다.
for (r in road) {
if (r[2] < graph[r[0]][r[1]]) {
graph[r[0]][r[1]] = r[2]
}
if (r[2] < graph[r[1]][r[0]]) {
graph[r[1]][r[0]] = r[2]
}
}
return graph
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 2,356 | algorithm | MIT License |
src/Day08.kt | petoS6 | 573,018,212 | false | {"Kotlin": 14258} | fun main() {
fun part1(lines: List<String>): Int {
val matrix = lines.map {
it.map { it.toString().toInt() }
}
var visible = 0
matrix.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, tree ->
val leftVisible = row.filterIndexed { index, _ -> index < colIndex }.all { it < tree }
val rightVisible = row.filterIndexed { index, _ -> index > colIndex }.all { it < tree }
val topVisible = matrix.map { it[colIndex] }.filterIndexed { index, _ -> index < rowIndex }.all { it < tree }
val bottomVisible = matrix.map { it[colIndex] }.filterIndexed { index, _ -> index > rowIndex }.all { it < tree }
if (leftVisible || rightVisible || topVisible || bottomVisible) visible++
}
}
return visible
}
fun part2(lines: List<String>): Int {
val matrix = lines.map {
it.map { it.toString().toInt() }
}
val scenics = mutableListOf<Int>()
matrix.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, tree ->
val left = row.filterIndexed { index, _ -> index < colIndex }
val right = row.filterIndexed { index, _ -> index > colIndex }
val top = matrix.map { it[colIndex] }.filterIndexed { index, _ -> index < rowIndex }
val bottom = matrix.map { it[colIndex] }.filterIndexed { index, _ -> index > rowIndex }
val leftScenic = ((left .reversed().indexOfFirst { it >= tree }).takeIf { it != -1 }?.plus(1)) ?: left.size
val rightScenic = ((right .indexOfFirst { it >= tree }).takeIf { it != -1 }?.plus(1)) ?: right.size
val topScenic = ((top .reversed().indexOfFirst { it >= tree }).takeIf { it != -1 }?.plus(1)) ?: top.size
val bottomScenic = ((bottom.indexOfFirst { it >= tree }).takeIf { it != -1 }?.plus(1)) ?: bottom.size
scenics.add(leftScenic * rightScenic * topScenic * bottomScenic)
}
}
return scenics.max()
}
val testInput = readInput("Day08.txt")
println(part1(testInput))
println(part2(testInput))
} | 0 | Kotlin | 0 | 0 | 40bd094155e664a89892400aaf8ba8505fdd1986 | 2,052 | kotlin-aoc-2022 | Apache License 2.0 |
src/Day15.kt | iownthegame | 573,926,504 | false | {"Kotlin": 68002} | import java.math.BigDecimal
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Sensor(val position: Position, val beaconPosition: Position)
fun main() {
fun parseMap(input: List<String>): MutableList<Sensor> {
// Sensor at x=20, y=1: closest beacon is at x=15, y=3
val sensors = mutableListOf<Sensor>()
for (line in input) {
val splits = line.split(": ")
val sensorSplits = splits.first().split(", ")
val beaconSplits = splits.last().split(", ")
val sensorX = sensorSplits.last().split("=").last().toInt()
val sensorY = sensorSplits.first().split("=").last().toInt()
val beaconX = beaconSplits.last().split("=").last().toInt()
val beaconY = beaconSplits.first().split("=").last().toInt()
val sensor = Sensor(Position(sensorX, sensorY), Position(beaconX, beaconY))
sensors.add(sensor)
}
return sensors
}
fun distance(positionA: Position, positionB: Position): Int {
return abs(positionA.x - positionB.x) + abs(positionA.y - positionB.y)
}
fun mergeRanges(ranges: Array<Array<Int>>): Array<Array<Int>>{
var newRanges = arrayOf<Array<Int>>()
var previousRange: Array<Int>? = null
for ((index, range) in ranges.withIndex()) {
if (index == 0) {
previousRange = range
continue
}
if (range.first() - previousRange!!.last() > 1) {
// no intersection
newRanges += previousRange
previousRange = range
continue
}
previousRange = arrayOf(previousRange.first(), max(previousRange.last(), range.last()))
}
newRanges += previousRange!! // last one
return newRanges
}
fun getCoverRanges(sensors: MutableList<Sensor>, targetX: Int, excludeBeacon: Boolean, minX: Int?, maxX: Int?): Array<Array<Int>>{
var coverRanges = arrayOf<Array<Int>>()
for (sensor in sensors) {
val sensorPoint = sensor.position
val beaconPoint = sensor.beaconPosition
val distance = distance(sensorPoint, beaconPoint)
val targetPoint = Position(targetX, sensorPoint.y)
val targetDistance = distance(targetPoint, sensorPoint)
val coverageDistance = distance - targetDistance
if (coverageDistance > 0) {
var left = sensorPoint.y - coverageDistance
var right = sensorPoint.y + coverageDistance
if (excludeBeacon && left == beaconPoint.y) {
left += 1
}
if (excludeBeacon && right == beaconPoint.y) {
right -= 1
}
if (minX != null) {
left = max(minX, left)
}
if (maxX != null) {
right = min(maxX, right)
}
coverRanges += arrayOf(left, right)
}
}
return coverRanges
}
fun part1(input: List<String>, targetX: Int): Int {
val sensors = parseMap(input)
var coverRanges = getCoverRanges(sensors, targetX, true, null, null)
coverRanges.sortBy { it.first() }
// println("ranges (before merge): ${coverRanges.map { "[" + it.joinToString(", ") + "]" }}")
coverRanges = mergeRanges(coverRanges)
// println("ranges: ${coverRanges.map { "[" + it.joinToString(", ") + "]" }}")
return coverRanges.sumOf { it.last() - it.first() + 1 }
}
fun part2(input: List<String>, fromX: Int, toX: Int): BigDecimal {
val sensors = parseMap(input)
var distressBeaconPoint: Position? = null
for (x in fromX..toX) {
var coverRanges = getCoverRanges(sensors, x, false, 0, 4000000)
coverRanges.sortBy { it.first() }
// println("ranges (before merge): ${coverRanges.map { "[" + it.joinToString(", ") + "]" }}")
coverRanges = mergeRanges(coverRanges)
// println("ranges for x: $x: ${coverRanges.map { "[" + it.joinToString(", ") + "]" }}")
if (coverRanges.size == 2) {
distressBeaconPoint = Position(x, coverRanges.first().last() + 1)
}
}
// println("distressBeaconPoint: $distressBeaconPoint")
return BigDecimal(distressBeaconPoint!!.y).multiply(BigDecimal(4000000)).plus(BigDecimal(distressBeaconPoint.x))
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day15_sample")
check(part1(testInput, 10) == 26)
check(part2(testInput, 0, 20) == BigDecimal(56000011))
val input = readTestInput("Day15")
println("part 1 result: ${part1(input, 2000000)}")
println("part 2 result: ${part2(input, 0, 4000000).toPlainString()}")
}
| 0 | Kotlin | 0 | 0 | 4e3d0d698669b598c639ca504d43cf8a62e30b5c | 4,951 | advent-of-code-2022 | Apache License 2.0 |
src/Day16.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | import kotlin.math.max
enum class Direction {
LEFT, RIGHT, UP, DOWN
}
fun MutableInput<Char>.getDirection(i: Int, j: Int, d: Direction): List<Direction> {
return when (d) {
Direction.LEFT -> when (this[i][j]) {
'.', '-' -> listOf(d)
'\\' -> listOf(Direction.UP)
'/' -> listOf(Direction.DOWN)
'|' -> listOf(Direction.UP, Direction.DOWN)
else -> error("Asd")
}
Direction.RIGHT -> when (this[i][j]) {
'.', '-' -> listOf(d)
'\\' -> listOf(Direction.DOWN)
'/' -> listOf(Direction.UP)
'|' -> listOf(Direction.UP, Direction.DOWN)
else -> error("Asd")
}
Direction.UP -> when (this[i][j]) {
'.', '|' -> listOf(d)
'\\' -> listOf(Direction.LEFT)
'/' -> listOf(Direction.RIGHT)
'-' -> listOf(Direction.LEFT, Direction.RIGHT)
else -> error("Asd")
}
Direction.DOWN -> when (this[i][j]) {
'.', '|' -> listOf(d)
'\\' -> listOf(Direction.RIGHT)
'/' -> listOf(Direction.LEFT)
'-' -> listOf(Direction.LEFT, Direction.RIGHT)
else -> error("Asd")
}
}
}
fun MutableInput<Char>.activate(
i: Int = 0,
j: Int = 0,
d: Direction = Direction.RIGHT,
visited: MutableSet<Pair<RowCol, Direction>>
) {
if (i < 0 || j < 0 || i >= this.size || j >= this[0].size || visited.contains((i to j) to d))
return
val next = getDirection(i, j, d)
visited.add((i to j) to d)
next.forEach {
when (it) {
Direction.LEFT -> activate(i, j - 1, it, visited)
Direction.RIGHT -> activate(i, j + 1, it, visited)
Direction.UP -> activate(i - 1, j, it, visited)
Direction.DOWN -> activate(i + 1, j, it, visited)
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val newInput = input.toMutableInput { it }
val visited = mutableSetOf<Pair<RowCol, Direction>>()
newInput.activate(visited = visited)
return visited.distinctBy { it.first }.size
}
fun part2(input: List<String>): Int {
val newInput = input.toMutableInput { it }
var maxCount = 0
for (i in newInput.indices) {
val visited = mutableSetOf<Pair<RowCol, Direction>>()
newInput.activate(i, j = 0, d = Direction.RIGHT, visited = visited)
val visited2 = mutableSetOf<Pair<RowCol, Direction>>()
newInput.activate(i, j = newInput[0].size - 1, d = Direction.LEFT, visited = visited2)
maxCount = max(maxCount, max(visited.distinctBy { it.first }.size, visited2.distinctBy { it.first }.size))
}
for (j in newInput[0].indices) {
val visited = mutableSetOf<Pair<RowCol, Direction>>()
newInput.activate(i = 0, j = j, d = Direction.DOWN, visited = visited)
val visited2 = mutableSetOf<Pair<RowCol, Direction>>()
newInput.activate(i = newInput.size - 1, j = j, d = Direction.UP, visited = visited2)
maxCount = max(maxCount, max(visited.distinctBy { it.first }.size, visited2.distinctBy { it.first }.size))
}
return maxCount
}
val input = readInput("Day16")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 3,373 | aoc-2023 | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day11/Day11.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day11
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputLines
object Day11 : Day {
override val input = readInputLines(11)
.map { l -> l.toCharArray().map { it.digitToInt() } }
.flatMapIndexed { y, i -> i.mapIndexed { x, v -> (Position(x, y) to v) } }
.toMap()
override fun part1() = with(input.toMutableMap()) { (0 until 100).fold(0) { a, _ -> a + step() } }
override fun part2(): Int {
with(input.toMutableMap()) {
repeat(Int.MAX_VALUE) { step ->
step()
if (all { it.value == 0 }) return step + 1
}
error("No result found")
}
}
private fun MutableMap<Position, Int>.step(): Int {
replaceAll { _, v -> v + 1 }
val count = asSequence().filter { (_, v) -> v == 10 }.map { (k) -> flash(k) }.sum()
asSequence().filter { (_, v) -> v == -1 }.forEach { (k) -> this[k] = 0 }
return count
}
private fun MutableMap<Position, Int>.flash(position: Position): Int {
this[position] = -1
return asSequence().filter { (k) -> k in position.adjacent() }
.filter { (_, v) -> v != -1 }
.onEach { (k, v) -> this[k] = v + 1 }
.filter { (k, v) -> getOrDefault(k, 0) >= 10 }
.fold(1) { a, (k) -> a + flash(k) }
}
data class Position(val x: Int, val y: Int) {
fun adjacent(): List<Position> {
return (0..2)
.flatMap { x -> (0..2).map { x to it } }
.map { (x, y) -> this.x + x - 1 to this.y + y - 1 }
.filter { (x, y) -> this != Position(x, y) }
.map { (x, y) -> Position(x, y) }
}
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 1,791 | aoc2021 | MIT License |
src/day9.kt | eldarbogdanov | 577,148,841 | false | {"Kotlin": 181188} | val di = listOf(-1, 0, 1, 0);
val dj = listOf(0, 1, 0, -1);
val dirMap: Map<String, Int> = mapOf("U" to 0, "R" to 1, "D" to 2, "L" to 3);
fun dist(a: Pair<Int, Int>, b: Pair<Int, Int>): Int {
return Math.max(Math.abs(a.first - b.first), Math.abs(a.second - b.second));
}
fun dist2(a: Pair<Int, Int>, b: Pair<Int, Int>): Int {
return Math.abs(a.first - b.first) + Math.abs(a.second - b.second);
}
fun newPos(oldPos: Pair<Int, Int>, leader: Pair<Int, Int>, dir: Int): Pair<Int, Int> {
if (dist(oldPos, leader) <= 1) {
return oldPos;
}
if (dir != -1) {
val candidate = Pair(oldPos.first + di[dir], oldPos.second + dj[dir]);
if (dist2(leader, candidate) == 1) {
return candidate;
}
}
var best = oldPos;
for(dii in -1..1) {
for(djj in -1..1) {
val candidate = Pair(oldPos.first + dii, oldPos.second + djj);
if (dist2(leader, candidate) == 1) {
best = candidate;
}
}
}
if (dist2(leader, best) == 1) return best;
for(dii in -1..1) {
for(djj in -1..1) {
val candidate = Pair(oldPos.first + dii, oldPos.second + djj);
if (dist(leader, candidate) == 1) {
best = candidate;
}
}
}
return best;
}
fun main() {
val input = ""
val st: MutableSet<Pair<Int, Int>> = mutableSetOf(Pair(0, 0));
var snake: MutableList<Pair<Int, Int>> = mutableListOf();
val knots = 10;
for(i in 1..knots) {
snake.add(Pair(0, 0));
}
for(s in input.split("\n")) {
val dir = dirMap[s.split(" ")[0]]!!;
val num = Integer.parseInt(s.split(" ")[1]);
for(k in 1..num) {
val newSnake: MutableList<Pair<Int, Int>> = mutableListOf();
newSnake.add(Pair(snake[0].first + di[dir], snake[0].second + dj[dir]));
for(knot in 1 until knots) {
newSnake.add(newPos(snake[knot], newSnake[knot - 1], dir));
}
st.add(newSnake[knots - 1]);
snake = newSnake;
//println(snake);
}
}
println(st.size);
}
| 0 | Kotlin | 0 | 0 | bdac3ab6cea722465882a7ddede89e497ec0a80c | 2,158 | aoc-2022 | Apache License 2.0 |
src/y2023/Day06.kt | a3nv | 574,208,224 | false | {"Kotlin": 34115, "Java": 1914} | package y2023
import utils.readInput
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
fun main() {
/**
* Equation speed * (time - speed) represents parabola. In this case upside-down U shaped because time - speed is a negative value.
*/
fun part1(input: List<String>): Long {
val times = input.first().substringAfter("Time:").split(" ")
.filter { it.isNotBlank() }.map { it.trim().toLong() }
val distances = input.last().substringAfter("Distance:").split(" ")
.filter { it.isNotBlank() }.map { it.trim().toLong() }
val pairs = times.zip(distances)
var number = 1L
pairs.forEach {
val t = it.first.toDouble()
val d = it.second
val maxSpeed = t / 2 // since it's a parabola maxSpeed will be reached at the middle of time
val maxDistance = (maxSpeed * (t - maxSpeed)).toLong() // max distance, which is y-coordinate.
if (maxDistance > d) { // if it's greater than distance d then there must be lower and higher speeds that their corresponding distances are exactly d.
val sqrtPart = sqrt((t * t / 4) - d) // this is the root of a standard quadratic equation 'speed * (time - speed) = d' for speed
val lowSpeed = ceil(t / 2 - sqrtPart).toLong() // finding roots of the equation
val highSpeed = floor(t / 2 + sqrtPart).toLong()
val count = (highSpeed - lowSpeed + 1).coerceAtLeast(0L)
number *= count
} else {
number = 0L
}
}
return number
}
fun part2(input: List<String>): Long {
return 0
}
// test if implementation meets criteria from the description, like:
var testInput = readInput("y2023", "Day06_test_part1")
println(part1(testInput))
// check(part1(testInput) == 35)
// println(part2(testInput))
// check(part2(testInput) == 2286)
val input = readInput("y2023", "Day06")
println(part1(input))
// check(part1(input) == 2563)
// check(part2(input) == 70768)
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ab2206ab5030ace967e08c7051becb4ae44aea39 | 2,156 | advent-of-code-kotlin | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/fstaudt/aoc2021/day4/Day4.kt | fstaudt | 433,733,254 | true | {"Kotlin": 9482, "Rust": 1574} | package com.github.fstaudt.aoc2021.day4
import com.github.fstaudt.aoc2021.day4.Day4.BingoBoard.Companion.toBingoBoard
import com.github.fstaudt.aoc2021.shared.Day
import com.github.fstaudt.aoc2021.shared.readInputLines
fun main() {
Day4().run()
}
class Day4 : Day {
override val input = readInputLines(4)
private val numbers = input[0].split(",").map { it.toInt() }
private val bingoBoards = input.drop(1).filter { it.isNotBlank() }.chunked(5).map { it.toBingoBoard() }
override fun part1(): Int {
var index = 0
while (bingoBoards.none { it.isWinner() } && index < numbers.size) {
bingoBoards.forEach { it.playNumber(numbers[index]) }
index++
}
return numbers[index - 1] * bingoBoards.first { it.isWinner() }.score()
}
override fun part2(): Int {
var remainingBingoBoards = bingoBoards
var index = 0
while (remainingBingoBoards.size > 1 && index < numbers.size) {
remainingBingoBoards.forEach { it.playNumber(numbers[index]) }
remainingBingoBoards = bingoBoards.filter { !it.isWinner() }
index++
}
val lastBingoBoard = remainingBingoBoards[0]
while (!lastBingoBoard.isWinner() && index < numbers.size) {
lastBingoBoard.playNumber(numbers[index])
index++
}
return numbers[index - 1] * lastBingoBoard.score()
}
data class BingoBoardNumber(val number: Int, var checked: Boolean = false)
data class BingoBoard(val lines: List<List<BingoBoardNumber>>) {
private val columns: List<List<BingoBoardNumber>> = lines[0].mapIndexed { i, _ -> lines.map { it[i] } }
companion object {
fun List<String>.toBingoBoard() = BingoBoard(map { it.toBingoBoardLine() })
private fun String.clean() = trimStart().replace(Regex(" +"), " ")
private fun String.toBingoBoardLine() = clean().split(" ").map { BingoBoardNumber(it.toInt()) }
}
fun isWinner() = lines.any { line -> line.all { it.checked } } || columns.any { column -> column.all { it.checked } }
fun playNumber(number: Int) = lines.forEach { line -> line.forEach { if (number == it.number) it.checked = true } }
fun score() = lines.sumOf { line -> line.filter { !it.checked }.sumOf { it.number } }
}
}
| 0 | Kotlin | 0 | 0 | f2ee9bca82711bc9aae115400ecff6db5d683c9e | 2,358 | aoc2021 | MIT License |
src/main/kotlin/dp/ConstructAVLT.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
import kotlin.math.ceil
import kotlin.math.log2
// similar to ConstructBST, now we should construct an AVL Tree with its property
// that for every node, the height difference between its left child and right
// child should not differ by more than 1
// here we define a NULL node having height -1,
// and a root node with no children is an AVL Tree with height 0
// your input is still an array of frequencies being accessed (see ConstructBST
// for more details)
fun main(args: Array<String>) {
val freq = oneArrayOf(5, 8, 2, 1, 9, 5)
println(freq.avlCost())
}
fun OneArray<Int>.avlCost(): Int {
val f = this
val n = size
val F = OneArray(n) { OneArray(n) { 0 } }
for (i in 1 until n) {
for (j in i..n) {
F[i, j] = if (i == j) f[i] else F[i, j - 1] + f[j]
}
}
// dp(i, k, h): min cost for constructing an AVL Tree of height h and storing
// values from the subarray i to k
// memoization structure: 3d array dp[1 until n, 2..n, 1..H] where H is O(log n)
// representing the max height of such AVL Tree
val H = ceil(2 * log2(n.toDouble())).toInt()
val dp = OneArray(n + 1) { OneArray(n + 1) { OneArray(H) { 0 } } }
// space complexity: O(n^3 log n)
val handler = { i: Int, k: Int, h: Int ->
when (h) {
0 -> if (i == k) f[i] else tree.bintree.INF
-1 -> if (i == k + 1) 0 else tree.bintree.INF
else -> tree.bintree.INF
}
}
// we want min_h { dp(h, 1, n) }
var min = tree.bintree.INF
for (h in 1..H) {
for (i in 1..n) {
for (k in i..n) {
dp[i, k, h] = when {
h <= -1 && i > k -> 0
h != -1 && i > k -> tree.bintree.INF
else -> F[i, k] + ((i..k).map { r ->
min(
dp[i, r, h - 1, handler] + dp[r + 1, k, h - 2, handler],
dp[i, r - 1, h - 2, handler] + dp[r + 1, k, h - 1, handler],
dp[i, r - 1, h - 1, handler] + dp[r + 1, k, h - 1, handler])
}.min() ?: tree.bintree.INF)
}
if (i == 1 && k == n) {
min = min(min, dp[i, k, h])
}
}
}
}
// time complexity: O(n^3 log n)
return min
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,031 | AlgoKt | MIT License |
src/Day07.kt | wujingwe | 574,096,169 | false | null | class Day07 {
sealed class Node(val name: String, val parent: Node? = null) {
val children = mutableMapOf<String, Node>()
}
class Directory(name: String, parent: Node? = null) : Node(name, parent)
class File(name: String, val size: Int, parent: Node) : Node(name, parent)
fun parse(inputs: List<String>): Node {
val root: Node = Directory("/")
var current = root
inputs.forEach { command ->
if (command.startsWith("$ cd ..")) {
current = current.parent!!
} else if (command.startsWith("$ cd")) {
val name = command.split(" ")[2]
val folder = current.children.getOrPut(name) { Directory(name, current) }
current = folder
} else if (command.startsWith("$ ls")) {
// Do nothing
} else {
val (type, name) = command.split(" ")
if (type == "dir") {
current.children[name] = Directory(name, current)
} else {
val size = type.toInt()
current.children[name] = File(name, size, current)
}
}
}
return root
}
fun traverse(node: Node, predicate: (Int) -> Boolean): List<Int> {
val res = mutableListOf<Int>()
traverse(node, res, predicate)
return res
}
private fun traverse(node: Node, res: MutableList<Int>, predicate: (Int) -> Boolean): Int {
return if (node is File) {
node.size
} else {
val total = node.children.values.fold(0) { acc, child ->
acc + traverse(child, res, predicate)
}
if (predicate(total)) {
res.add(total)
}
total
}
}
}
fun main() {
fun part1(inputs: List<String>): Int {
val day07 = Day07()
val root = day07.parse(inputs)
return day07.traverse(root) { size -> size <= 100000 }.sum()
}
fun part2(inputs: List<String>): Int {
val day07 = Day07()
val root = day07.parse(inputs)
val total = day07.traverse(root) { true }.max()
val unused = 70000000 - total
val target = 30000000 - unused
return day07.traverse(root) { size -> size >= target }.min()
}
val testInput = readInput("../data/Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("../data/Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a5777a67d234e33dde43589602dc248bc6411aee | 2,585 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day09/Day09.kt | banshay | 572,450,866 | false | {"Kotlin": 33644} | package day09
import readInput
fun main() {
fun part1(input: List<String>): Int {
val head = Head(0 to 0, null)
val tail = createRopeSegment(0 to 0, 1, head)!!
val visitedTailSpots = mutableSetOf<Pair<Int, Int>>()
val moves = input.map { it.toMove() }
val size = moves.maxOf { it.steps } + 1
moves.forEach {
for (i in 0 until it.steps) {
head.move(it.direction)
visitedTailSpots.add(tail.position)
// visualize(size, head, tail, visitedTailSpots)
}
}
return visitedTailSpots.count()
}
fun part2(input: List<String>): Int {
val start = 11 to 5
val head = Head(start, null)
var tail = createRopeSegment(start, 9, head)!!
while (tail.next != null) {
tail = tail.next!!
}
val visitedTailSpots = mutableSetOf<Pair<Int, Int>>()
val moves = input.map { it.toMove() }
val size = moves.maxOf { it.steps } + 1
moves.forEach {
for (i in 0 until it.steps) {
head.move(it.direction)
visitedTailSpots.add(tail.position)
// visualize(size, head, tail, visitedTailSpots)
}
// visualize(size, head, tail, visitedTailSpots)
}
return visitedTailSpots.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
val testInput2 = readInput("Day09_test2")
val input = readInput("Day09")
println("test part1: ${part1(testInput)}")
println("result part1: ${part1(input)}")
println("test part2: ${part2(testInput2)}")
println("result part2: ${part2(input)}")
}
fun createRopeSegment(start: Pair<Int, Int>, segments: Int, prev: Rope, counter: Int = 1): Rope? {
if (segments <= 0) {
return null
}
val segment = Tail(counter, start, prev, null)
prev.next = segment
segment.next = createRopeSegment(start, segments - 1, segment, counter + 1)
return segment
}
fun segmentToList(segment: Rope?): List<Rope> {
if (segment != null) {
return listOf(segment) + segmentToList(segment.next)
}
return listOf()
}
fun visualize(size: Int, head: Head, tail: Rope, visits: Set<Pair<Int, Int>>) {
val segmentPositions =
segmentToList(head)
.drop(1)
.dropLast(1)
.mapIndexed { index, rope -> rope.position to index + 1 }.toMap()
println(segmentPositions)
val field = List(size) { row ->
List(size) { col ->
when {
col to row == head.position -> "H"
segmentPositions.containsKey(col to row) -> segmentPositions[col to row]
col to row == tail.position -> "T"
visits.contains(col to row) -> "#"
else -> "."
}
}
}.reversed()
field.forEach { row -> println(row.joinToString("")) }
println()
println()
}
interface Rope {
var position: Pair<Int, Int>
var next: Rope?
fun follow()
}
class Head(override var position: Pair<Int, Int>, override var next: Rope?) : Rope {
fun move(direction: Direction) {
position = when (direction) {
Direction.UP -> position.first to position.second + 1
Direction.DOWN -> position.first to position.second - 1
Direction.LEFT -> position.first - 1 to position.second
Direction.RIGHT -> position.first + 1 to position.second
}
next?.follow()
}
override fun follow() {
TODO("Not yet implemented")
}
}
class Tail(
private val segment: Int,
override var position: Pair<Int, Int>,
private val ahead: Rope?,
override var next: Rope?
) : Rope {
override fun follow() {
position = when (ahead?.position?.minus(position)) {
0 to 2 -> position.first to position.second + 1 //UP
2 to 0 -> position.first + 1 to position.second //RIGHT
0 to -2 -> position.first to position.second - 1 //DOWN
-2 to 0 -> position.first - 1 to position.second //LEFT
1 to 2, 2 to 1, 2 to 2 -> position.first + 1 to position.second + 1 //UP_RIGHT
1 to -2, 2 to -1, 2 to -2 -> position.first + 1 to position.second - 1 //DOWN_RIGHT
-2 to -1, -1 to -2, -2 to -2 -> position.first - 1 to position.second - 1 //DOWN_LEFT
-2 to 1, -1 to 2, -2 to 2 -> position.first - 1 to position.second + 1 //UP_LEFT
else -> position
}
next?.follow()
}
}
enum class Direction(val code: String) {
UP("U"), DOWN("D"), LEFT("L"), RIGHT("R");
companion object {
private val map = Direction.values().associateBy { it.code }
infix fun from(value: String) = map[value]!!
}
}
data class Move(val direction: Direction, val steps: Int)
fun String.toMove() = Move(Direction.from(substringBefore(" ")), substringAfter(" ").toInt())
infix fun Pair<Int, Int>.minus(other: Pair<Int, Int>) = first - other.first to second - other.second
| 0 | Kotlin | 0 | 0 | c3de3641c20c8c2598359e7aae3051d6d7582e7e | 5,135 | advent-of-code-22 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day15.kt | codelicia | 627,407,402 | false | {"Kotlin": 49578, "PHP": 554, "Makefile": 293} | package com.codelicia.advent2021
import java.util.*
import kotlin.math.min
class Day15(val input: String) {
// Split the input string into a 2D grid of integers
private val grid = input.split("\n").map { it ->
it.toCharArray().map { it.digitToInt() }
}
private val maxRow = grid.lastIndex
private val maxColumn = grid.last().lastIndex
fun part1(): Int {
val dp = Array(maxRow + 1) { IntArray(maxColumn + 1) { Int.MAX_VALUE } }
dp[0][0] = 0
for (i in 0..maxRow) {
for (j in 0..maxColumn) {
if (i > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j] + grid[i][j])
if (j > 0) dp[i][j] = min(dp[i][j], dp[i][j - 1] + grid[i][j])
}
}
return dp[maxRow][maxColumn]
}
fun part2(): Int {
val heap: PriorityQueue<Node> = PriorityQueue()
heap.add(Node(0, 0, 0))
val g = enlargeMap().split("\n").map { it ->
it.toCharArray().map { it.digitToInt() }
}
val visited: MutableSet<Pair<Int, Int>> = mutableSetOf()
while (heap.isNotEmpty()) {
val node = heap.poll()
val cost = node.cost
val x = node.x
val y = node.y
if (x == g.lastIndex && y == g.last().lastIndex) {
return cost
}
if (x to y in visited) continue
visited.add(x to y)
for ((nx, ny) in listOf(x to y-1, x to y+1, x-1 to y, x+1 to y)) {
if (nx < 0 || ny < 0 || nx > g.lastIndex || ny > g.last().lastIndex) continue
if (nx to ny in visited) continue
heap.add(Node(cost + g[nx][ny], nx, ny))
}
}
error("Could not find the shortest path")
}
fun Int.inc(i: Int): Int = if (this + i > 9) (this + i) % 9 else this+i
fun enlargeMap(): String {
// pad right
var s : String = ""
for (i in 0..maxRow) {
repeat(5) {
repeatIdx -> s += grid[i].map { it.inc(repeatIdx) }.joinToString("")
}
s += "\n"
}
// pad bottom
repeat(4) { rp ->
var paddedGrid = s.split("\n").map { it -> it.toCharArray().map { it.digitToInt() } }
for (i in 0..maxRow) {
s += paddedGrid[i].map { it.inc(rp+1) }.joinToString("") + "\n"
}
}
return s.trim()
}
private class Node(val cost: Int, val x: Int, val y: Int) : Comparable<Node> {
override fun compareTo(other: Node): Int = cost.compareTo(other.cost)
}
} | 2 | Kotlin | 0 | 0 | df0cfd5c559d9726663412c0dec52dbfd5fa54b0 | 2,617 | adventofcode | MIT License |
src/main/kotlin/de/niemeyer/aoc2022/Day16.kt | stefanniemeyer | 572,897,543 | false | {"Kotlin": 175820, "Shell": 133} | /**
* Advent of Code 2022, Day 16: Proboscidea Volcanium
* Problem Description: https://adventofcode.com/2022/day/16
*
* The searchPaths functions comes from <NAME> https://todd.ginsberg.com/post/advent-of-code/2022/day16
*/
package de.niemeyer.aoc2022
import de.niemeyer.aoc.utils.Resources.resourceAsList
import com.github.shiguruikai.combinatoricskt.combinations
import de.niemeyer.aoc.search.Edge
import de.niemeyer.aoc.search.Vertex
import de.niemeyer.aoc.search.dijkstra
import de.niemeyer.aoc.utils.getClassName
fun main() {
var shortestPathCosts = mutableMapOf<String, MutableMap<String, Int>>()
var cages: Map<String, Valve> = mapOf()
fun parseInput(input: List<String>): Map<String, Valve> {
return input.map { Valve.of(it) }.associateBy { it.name }
}
fun searchPaths(
from: String,
maxTime: Int,
visited: Set<String> = emptySet(),
usedTime: Int = 0,
totalFlow: Int = 0
): Int =
shortestPathCosts
.getValue(from)
.asSequence()
.filterNot { (nextValve, _) -> nextValve in visited }
.filter { (_, traversalCost) -> usedTime + traversalCost + 1 < maxTime }
.maxOfOrNull { (nextValve, traversalCost) ->
searchPaths(
nextValve,
maxTime,
visited + nextValve,
usedTime + traversalCost + 1,
totalFlow + ((maxTime - usedTime - traversalCost - 1) * cages.getValue(nextValve).flowRate)
)
} ?: totalFlow
fun part1(input: Map<String, Valve>): Int {
cages = input
return searchPaths("AA", 30)
}
fun part2(input: Map<String, Valve>): Int {
cages = input
return shortestPathCosts.keys.filter { it != "AA" }
.combinations(shortestPathCosts.size / 2)
.map { it.toSet() }
.maxOf { halfOfTheRooms ->
searchPaths("AA", 26, halfOfTheRooms) +
searchPaths("AA", 26, shortestPathCosts.keys - halfOfTheRooms)
}
}
val name = getClassName()
val testInput = parseInput(resourceAsList(fileName = "${name}_test.txt"))
val puzzleInput = parseInput(resourceAsList(fileName = "${name}.txt"))
shortestPathCosts = findShortestsPaths(testInput)
check(part1(testInput) == 1_651)
shortestPathCosts = findShortestsPaths(puzzleInput)
val puzzleResultPart1 = part1(puzzleInput)
println(puzzleResultPart1)
check(puzzleResultPart1 == 1_906)
shortestPathCosts = findShortestsPaths(testInput)
check(part2(testInput) == 1_707)
shortestPathCosts = findShortestsPaths(puzzleInput)
val puzzleResultPart2 = part2(puzzleInput)
println(puzzleResultPart2)
check(puzzleResultPart2 == 2_548)
}
class Valve(val name: String, val flowRate: Int, val neighbors: List<String>, val vertex: Vertex) {
companion object {
fun of(input: String): Valve {
val (nameS, flowRateS, neighborList) = inputValveLineRegex
.matchEntire(input)
?.destructured
?: error("Incorrect valve input line $input")
val neighborsL = neighborList.split(", ")
return Valve(nameS, flowRateS.toInt(), neighborsL, Vertex(nameS))
}
}
}
fun Map<String, Valve>.toGraph(): Map<Vertex, List<Edge>> =
map {
it.value.vertex to
it.value.neighbors.map { neighbor ->
Edge(this[neighbor]!!.vertex, 1) // it takes 1 minute to move from one valve to another
}
}.toMap()
fun findShortestsPaths(input: Map<String, Valve>): MutableMap<String, MutableMap<String, Int>> {
val graph = input.toGraph()
val paths = mutableMapOf<String, MutableMap<String, Int>>()
val start = input["AA"]
val relevantValves = input.values.filter { it.flowRate > 0 || it == start }.map { it.name }
relevantValves.forEach { from ->
val fromValve = input.getValue(from)
paths[from] = mutableMapOf()
relevantValves.forEach { to ->
if (from != to) {
val distances = dijkstra(graph, fromValve.vertex)
distances.forEach { dist ->
if (dist.key.name != fromValve.name && dist.key.name in relevantValves) {
paths[fromValve.name, dist.key.name] = dist.value
}
}
}
}
}
return paths
}
val inputValveLineRegex = """Valve (\S+) has flow rate=(\d+); tunnel[s]? lead[s]? to valve[s]? (.+)""".toRegex()
private operator fun Map<String, MutableMap<String, Int>>.set(key1: String, key2: String, value: Int) {
getValue(key1)[key2] = value
}
private operator fun Map<String, Map<String, Int>>.get(
key1: String,
key2: String,
defaultValue: Int = Int.MAX_VALUE
): Int =
get(key1)?.get(key2) ?: defaultValue
| 0 | Kotlin | 0 | 0 | ed762a391d63d345df5d142aa623bff34b794511 | 4,969 | AoC-2022 | Apache License 2.0 |
src/year2015/day15/Day15.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2015.day15
import readInput
import kotlin.math.max
fun main() {
// test if implementation meets criteria from the description, like:
// val testInput = readInput("2015", "Day15_test")
// check(part1(testInput), 0)
// check(part2(testInput), 0)
val input = readInput("2015", "Day15")
println(part1(input)) // 500 is too low
println(part2(input))
}
private fun part1(input: List<String>) = getBestScore(input.map { Ingredient.of(it) }.toSet())
private fun part2(input: List<String>) = getBestScore(
input.map { Ingredient.of(it) }.toSet(),
caloriesTarget = 500,
)
private data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int,
) {
companion object {
private val pattern =
"(\\w+): capacity (-?\\d+), durability (-?\\d+), flavor (-?\\d+), texture (-?\\d+), calories (-?\\d+)".toRegex()
fun of(string: String): Ingredient {
val groups = pattern.matchEntire(string)?.groupValues ?: error("Not matching pattern: $string")
return Ingredient(
name = groups[1],
capacity = groups[2].toInt(),
durability = groups[3].toInt(),
flavor = groups[4].toInt(),
texture = groups[5].toInt(),
calories = groups[6].toInt(),
)
}
}
}
private fun getBestScore(
ingredients: Set<Ingredient>,
remainingTeaSpoons: Int = 100,
capacityScore: Int = 0,
durabilityScore: Int = 0,
flavorScore: Int = 0,
textureScore: Int = 0,
calories: Int = 0,
caloriesTarget: Int? = null,
): Int {
if (remainingTeaSpoons == 0 && (caloriesTarget == null || calories == caloriesTarget))
return listOf(capacityScore, durabilityScore, flavorScore, textureScore)
.map { max(0, it) }
.reduce(Int::times)
else if (remainingTeaSpoons == 0) return 0
val ingredient = ingredients.first()
val remainingIngredients = ingredients - ingredient
return if (remainingIngredients.isEmpty()) getBestScore(
ingredients = remainingIngredients,
remainingTeaSpoons = 0,
capacityScore = capacityScore + ingredient.capacity * remainingTeaSpoons,
durabilityScore = durabilityScore + ingredient.durability * remainingTeaSpoons,
flavorScore = flavorScore + ingredient.flavor * remainingTeaSpoons,
textureScore = textureScore + ingredient.texture * remainingTeaSpoons,
calories = calories + ingredient.calories * remainingTeaSpoons,
caloriesTarget = caloriesTarget,
)
else (0..remainingTeaSpoons).maxOf {
getBestScore(
ingredients = remainingIngredients,
remainingTeaSpoons = remainingTeaSpoons - it,
capacityScore = capacityScore + ingredient.capacity * it,
durabilityScore = durabilityScore + ingredient.durability * it,
flavorScore = flavorScore + ingredient.flavor * it,
textureScore = textureScore + ingredient.texture * it,
calories = calories + ingredient.calories * it,
caloriesTarget = caloriesTarget,
)
}
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 3,244 | AdventOfCode | Apache License 2.0 |
src/Day15.kt | maciekbartczak | 573,160,363 | false | {"Kotlin": 41932} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.system.measureTimeMillis
fun main() {
fun part1(input: List<String>, height: Int): Int {
val (sensors, beacons) = parseInput(input)
val sensorRanges = sensors
.map { it.getSensorXRange(height) }
val start = sensorRanges.minOf { it.first }
val end = sensorRanges.maxOf { it.last }
val beaconsAtHeight = beacons.getCountAtHeight(height)
// +1 because of the x=0
return abs(start - end) + 1 - beaconsAtHeight
}
fun part2(input: List<String>, rangeLimit: Int): Long {
val (sensors, _) = parseInput(input)
// because there is only one uncovered point it must be somewhere at sensorDistance + 1
// that way we can greatly reduce the number of points to check since sensors number is quite low (23)
val distressBeacon = sensors
.flatMap { it.getEdgePoints(rangeLimit) }
.first { candidate -> sensors.none { it.isPositionWithinRange(candidate) } }
return distressBeacon.first * 4000000L + distressBeacon.second
}
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
val input = readInput("Day15")
println(part1(input, 2000000))
val part2Time = measureTimeMillis {
println(part2(input, 4000000))
}
println("part 2 took ${part2Time}ms")
}
private class Sensor(
val position: Pair<Int, Int>,
val range: Int
) {
companion object {
fun of(sensorPosition: Pair<Int, Int>, beaconPosition: Pair<Int, Int>): Sensor {
return Sensor(
sensorPosition,
sensorPosition.manhattanDistance(beaconPosition)
)
}
}
fun isPositionWithinRange(position: Pair<Int, Int>): Boolean {
return position.first in getSensorXRange(position.second)
}
fun getSensorXRange(y: Int): IntRange {
val yDiff = abs(position.second - y)
if (yDiff > range) {
return IntRange.EMPTY
}
val range = range - yDiff
return position.first - range..position.first + range
}
fun getEdgePoints(limit: Int): List<Pair<Int, Int>> {
val points = mutableListOf<Pair<Int, Int>>()
val yStart = max(min(position.second - range - 1, limit), 0)
val yEnd = max(min(position.second + range + 1, limit), 0)
for (y in yStart..yEnd) {
val xRange = getSensorXRange(y)
if (xRange.isEmpty()) {
points.add(position.first to y)
} else {
if (xRange.first in 1..limit) {
points.add(xRange.first - 1 to y)
}
if (xRange.last in -1..limit) {
points.add(xRange.last + 1 to y)
}
}
}
return points
}
}
private fun Pair<Int, Int>.manhattanDistance(other: Pair<Int, Int>): Int {
return abs(this.first - other.first) + abs(this.second - other.second)
}
private fun String.extractPositions(): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val pattern = """x=(-?\d+), y=(-?\d+).*x=(-?\d+), y=(-?\d+)"""
val match = pattern.toRegex().find(this) ?: throw IllegalStateException()
val sensorPosition = match.groupValues[1].toInt() to match.groupValues[2].toInt()
val beaconPosition = match.groupValues[3].toInt() to match.groupValues[4].toInt()
return sensorPosition to beaconPosition
}
private fun Set<Pair<Int, Int>>.getCountAtHeight(height: Int): Int {
return this.count { it.second == height }
}
private fun parseInput(input: List<String>): Pair<List<Sensor>, Set<Pair<Int, Int>>> {
val sensors = mutableListOf<Sensor>()
val beacons = mutableSetOf<Pair<Int, Int>>()
input.forEach {
val (sensor, beacon) = it.extractPositions()
sensors.add(Sensor.of(sensor, beacon))
beacons.add(beacon)
}
return sensors to beacons
} | 0 | Kotlin | 0 | 0 | 53c83d9eb49d126e91f3768140476a52ba4cd4f8 | 4,026 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/se/brainleech/adventofcode/aoc2022/Aoc2022Day02.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2022
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
class Aoc2022Day02 {
companion object {
private const val ROCK = "A"
private const val PAPER = "B"
private const val SCISSORS = "C"
private const val LOSE = "X"
private const val DRAW = "Y"
private const val WIN = "Z"
}
private fun String.score(): Int {
val (opponent, you_encoded) = this.split(" ")
val baseScore = (you_encoded[0] - 'X') + 1
val you = ('A' + (you_encoded[0] - 'X')).toString()
return baseScore +
if ((opponent == ROCK && you == PAPER) || (opponent == PAPER && you == SCISSORS) || (opponent == SCISSORS && you == ROCK)) 6
else if ((opponent == ROCK && you == ROCK) || (opponent == PAPER && you == PAPER) || (opponent == SCISSORS && you == SCISSORS)) 3
else if ((opponent == ROCK && you == SCISSORS) || (opponent == PAPER && you == ROCK) || (opponent == SCISSORS && you == PAPER)) 0
else Int.MIN_VALUE
}
private fun String.scoreByExpectedOutcome(): Int {
val (opponent, you) = this.split(" ")
val move =
if ((opponent == ROCK && you == WIN) || (opponent == PAPER && you == DRAW) || (opponent == SCISSORS && you == LOSE)) PAPER
else if ((opponent == PAPER && you == WIN) || (opponent == SCISSORS && you == DRAW) || (opponent == ROCK && you == LOSE)) SCISSORS
else if ((opponent == SCISSORS && you == WIN) || (opponent == ROCK && you == DRAW) || (opponent == PAPER && you == LOSE)) ROCK
else "?"
val encoded = ('X' + (move[0] - 'A')).toString()
return ("$opponent $encoded").score()
}
fun part1(input: List<String>): Int {
return input
.map { it.score() }
.reduce { total, score -> total.plus(score) }
}
fun part2(input: List<String>): Int {
return input
.map { it.scoreByExpectedOutcome() }
.reduce { total, score -> total.plus(score) }
}
}
fun main() {
val solver = Aoc2022Day02()
val prefix = "aoc2022/aoc2022day02"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(15, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(12, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
} | 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 2,541 | adventofcode | MIT License |
2017/src/ten/BalancingTowersChallenge.kt | Mattias1 | 116,139,424 | false | null | package ten
class BalancingTowersChallenge {
fun getBase(input: List<String>): BalancingTower {
val towers = buildTowerMap(input)
return getTowerBase(towers.values)
}
private fun buildTowerMap(input: List<String>): Map<String, BalancingTower> {
return input.map { BalancingTower(it) }.associateBy { it.Name }
}
private fun getTowerBase(towers: Collection<BalancingTower>): BalancingTower {
return towers.first { t ->
towers.none { it.OtherNames.contains(t.Name) }
}
}
fun getImbalancedFixWeight(input: List<String>): Int {
val towers = buildTowerMap(input)
val root = getTowerBase(towers.values)
return buildTowerTree(towers, root)
}
private fun buildTowerTree(towers: Map<String, BalancingTower>, currentRoot: BalancingTower): Int {
if (currentRoot.OtherNames.isEmpty()) {
currentRoot.TotalWeight = currentRoot.Weight
return 0
}
currentRoot.OtherTowers = currentRoot.OtherNames.map {
val other = towers[it]!!
val fixWeight = buildTowerTree(towers, other)
if (fixWeight > 0) {
return@buildTowerTree fixWeight
}
other
}
currentRoot.TotalWeight = currentRoot.Weight + currentRoot.totalSubWeights()
if (currentRoot.OtherTowers.any { it.TotalWeight != currentRoot.OtherTowers.first().TotalWeight }) {
return getFixWeight(currentRoot.OtherTowers)
}
return 0
}
private fun getFixWeight(towers: List<BalancingTower>): Int {
val a = towers[0]
val b = towers[1]
val c = towers[2]
return when {
a.TotalWeight == b.TotalWeight -> a.TotalWeight - c.totalSubWeights()
a.TotalWeight == c.TotalWeight -> a.TotalWeight - b.totalSubWeights()
else -> b.TotalWeight - a.totalSubWeights()
}
}
}
class BalancingTower {
val Name: String
val Weight: Int
val OtherNames: List<String>
var OtherTowers: List<BalancingTower> = listOf()
var TotalWeight: Int = 0
constructor(input: String) {
val inputs = input.split(' ').filter { it.isNotBlank() }
Name = inputs[0]
Weight = inputs[1].trim('(', ')').toInt()
OtherNames = if (inputs.count() > 2) inputs.drop(3).map { it.trim(',') } else listOf()
}
fun totalSubWeights(): Int {
return OtherTowers.sumBy { it.TotalWeight }
}
}
| 0 | Kotlin | 0 | 0 | 6bcd889c6652681e243d493363eef1c2e57d35ef | 2,592 | advent-of-code | MIT License |
src/Day12.kt | wgolyakov | 572,463,468 | false | null | fun main() {
fun parse(input: List<String>): Triple<List<CharArray>, Pair<Int, Int>, Pair<Int, Int>> {
var start = 0 to 0
var stop = 0 to 0
val map = List(input.size) { CharArray(input[0].length) }
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == 'S') {
start = i to j
map[i][j] = 'a'
} else if (input[i][j] == 'E') {
stop = i to j
map[i][j] = 'z'
} else {
map[i][j] = input[i][j]
}
}
}
return Triple(map, start, stop)
}
fun part1(input: List<String>): Int {
val (map, start, stop) = parse(input)
val distanceMap = List(map.size) { MutableList(map[0].size) { -1 } }
val queue = ArrayDeque<Pair<Int, Int>>()
distanceMap[start.first][start.second] = 0
queue.addLast(start)
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
if (curr == stop)
break
val neighbors = listOf(
curr.first + 1 to curr.second,
curr.first to curr.second + 1,
curr.first - 1 to curr.second,
curr.first to curr.second - 1)
.filter { it.first >= 0 && it.second >= 0 && it.first < map.size && it.second < map[0].size }
.filter { map[it.first][it.second] - map[curr.first][curr.second] <= 1 }
for (next in neighbors) {
if (distanceMap[next.first][next.second] == -1) {
distanceMap[next.first][next.second] = distanceMap[curr.first][curr.second] + 1
queue.addLast(next)
}
}
}
return distanceMap[stop.first][stop.second]
}
fun part2(input: List<String>): Int {
val (map, _, start) = parse(input)
var minDistance = Int.MAX_VALUE
val distanceMap = List(map.size) { MutableList(map[0].size) { -1 } }
val queue = ArrayDeque<Pair<Int, Int>>()
distanceMap[start.first][start.second] = 0
queue.addLast(start)
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
if (map[curr.first][curr.second] == 'a' && distanceMap[curr.first][curr.second] < minDistance)
minDistance = distanceMap[curr.first][curr.second]
val neighbors = listOf(
curr.first + 1 to curr.second,
curr.first to curr.second + 1,
curr.first - 1 to curr.second,
curr.first to curr.second - 1)
.filter { it.first >= 0 && it.second >= 0 && it.first < map.size && it.second < map[0].size }
.filter { map[curr.first][curr.second] - map[it.first][it.second] <= 1 }
for (next in neighbors) {
if (distanceMap[next.first][next.second] == -1) {
distanceMap[next.first][next.second] = distanceMap[curr.first][curr.second] + 1
queue.addLast(next)
}
}
}
return minDistance
}
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 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 2,735 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | slawa4s | 573,050,411 | false | {"Kotlin": 20679} | const val diskSpace = 70000000
const val unusedSpace = 30000000
const val maxDirectorySize = 100000
fun main() {
fun getInputGroupedByOperations(input: List<String>): List<List<String>> {
var indexOperation = 0
return input.groupBy {
if (it.startsWith("\$ cd") or it.startsWith("\$ ls")) indexOperation += 1
indexOperation
}.values.toList()
}
fun initializeFolderTree(inputGrouped: List<List<String>>): FolderTreeImpl {
val folderTree = FolderTreeImpl()
inputGrouped.forEach {
if (it.first().startsWith("\$ cd")) folderTree.go(it.first().split(" ")[2])
if (it.first().startsWith("\$ ls")) folderTree.readDir(it.subList(1, it.size))
}
return folderTree
}
val initializedTree = initializeFolderTree(getInputGroupedByOperations(readInput("Day07")))
println(initializedTree.part1Answer())
println(initializedTree.part2Answer())
}
class FolderTreeImpl {
private var treeRoot: FolderNode = FolderNode(null)
private var currentRoot: FolderNode = treeRoot
fun go(folderName: String) {
currentRoot = when (folderName) {
"/" -> treeRoot
".." -> currentRoot.dad ?: treeRoot
else -> currentRoot.getSubFolderByName(folderName)
}
}
fun readDir(input: List<String>) = input.forEach {
if (it.startsWith("dir")) currentRoot.appendFolder(it.split(" ")[1])
else currentRoot.appendFile(it.split(" ")[1], Integer.parseInt(it.split(" ")[0]))
}
fun part1Answer(): Int = treeRoot.getAllNodesSize().sumOf { if (it <= maxDirectorySize) it else 0 }
fun part2Answer(): Int {
val sortedListOfNodes = treeRoot.getAllNodesSize().sorted()
return sortedListOfNodes.first { diskSpace - sortedListOfNodes.last() + it >= unusedSpace }
}
}
class FolderNode(
val dad: FolderNode?,
private var fromFileNameToFileSize: MutableMap<String, Int> = mutableMapOf(),
private var folders: MutableMap<String, FolderNode> = mutableMapOf(),
) {
private val sizeOfFiles: Int
get() = fromFileNameToFileSize.values.sum()
fun appendFile(fileName: String, size: Int) {
fromFileNameToFileSize[fileName] = size
}
fun appendFolder(folderName: String) {
folders[folderName] = FolderNode(this)
}
fun getSubFolderByName(folderName: String): FolderNode = this.folders[folderName]!!
private fun getAllNodesSizeFold(): MutableList<Pair<Int, Int>> {
val allKids = folders.values.map { it.getAllNodesSizeFold() }.flatten().toMutableList()
allKids.add(Pair(allKids.sumOf { it.second } + sizeOfFiles, sizeOfFiles))
return allKids
}
fun getAllNodesSize(): List<Int> = getAllNodesSizeFold().map { it.first }
}
| 0 | Kotlin | 0 | 0 | cd8bbbb3a710dc542c2832959a6a03a0d2516866 | 2,805 | aoc-2022-in-kotlin | Apache License 2.0 |
src/aoc2021/Day05.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2021
import readInput
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.max
fun main() {
val (year, day) = "2021" to "Day05"
data class Point(val x: Int, val y: Int)
data class Line(val p1: Point, val p2: Point)
data class Info(val lines: List<Line>, val maxX: Int, val maxY: Int)
fun parseInput(input: List<String>): Info {
var maxX = 0
var maxY = 0
val lines = input.map { line ->
val (p1, p2) = line.split("->").map { point ->
val (x, y) = point.trim().split(",").map { it.toInt() }
maxX = maxOf(maxX, x)
maxY = maxOf(maxY, y)
Point(x, y)
}
Line(p1, p2)
}
return Info(lines, maxX, maxY)
}
fun countIntersections(inputInfo: Info, countDiagonals: Boolean): Int {
val grid = Array(inputInfo.maxY + 1) { Array(inputInfo.maxX + 1) { 0 } }
var intersections = 0
inputInfo.lines.filter { line ->
line.p1.x == line.p2.x || line.p1.y == line.p2.y ||
(countDiagonals && abs(line.p1.x - line.p2.x) == abs(line.p1.y - line.p2.y))
}.forEach { line ->
val (p1, p2) = line
val (x1, y1) = p1
val (x2, y2) = p2
when {
x1 == x2 -> {
for (y in min(y1, y2)..max(y1, y2)) {
if (++grid[y][x1] == 2) {
intersections++
}
}
}
y1 == y2 -> {
for (x in min(x1, x2)..max(x1, x2)) {
if (++grid[y1][x] == 2) {
intersections++
}
}
}
else -> {
if (countDiagonals) {
val d = abs(x1 - x2)
val dx = (x2 - x1) / d
val dy = (y2 - y1) / d
for (i in 0..d) {
if (++grid[y1 + dy * i][x1 + dx * i] == 2) {
intersections++
}
}
}
}
}
}
return intersections
}
fun part1(input: List<String>): Int {
val inputInfo = parseInput(input)
return countIntersections(inputInfo, countDiagonals = false)
}
fun part2(input: List<String>): Int {
val inputInfo = parseInput(input)
return countIntersections(inputInfo, countDiagonals = true)
}
val testInput = readInput(name = "${day}_test", year = year)
val input = readInput(name = day, year = year)
check(part1(testInput) == 5)
println(part1(input))
check(part2(testInput) == 12)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 2,891 | aoc-kotlin | Apache License 2.0 |
src/day09/Day09.kt | GrzegorzBaczek93 | 572,128,118 | false | {"Kotlin": 44027} | package day09
import readInput
import utils.withStopwatch
import kotlin.math.pow
import kotlin.math.sqrt
fun main() {
val testInput = readInput("input09_test")
withStopwatch { println(part1(testInput)) }
withStopwatch { println(part2(testInput)) }
val input = readInput("input09")
withStopwatch { println(part1(input)) }
withStopwatch { println(part2(input)) }
}
private fun part1(input: List<String>) = input.execute(2)
private fun part2(input: List<String>) = input.execute(10)
private fun List<String>.execute(ropeSize: Int = 1): Int {
val tailVisitedPlaces = mutableSetOf(0 to 0)
val rope = MutableList(ropeSize) { 0 to 0 }
onEachMove { direction ->
(0 until ropeSize).forEach { index ->
rope[index] = when (index) {
0 -> rope[index].resolvePosition(direction)
else -> rope[index].resolvePosition(rope[index - 1])
}
}
tailVisitedPlaces.add(rope[ropeSize - 1])
}
return tailVisitedPlaces.size
}
private fun List<String>.onEachMove(move: (String) -> Unit) {
map { it.split(" ") }.forEach { (direction, length) ->
repeat(length.toInt()) {
move(direction)
}
}
}
private fun Pair<Int, Int>.resolvePosition(direction: String): Pair<Int, Int> {
val (x, y) = this
return when (direction) {
"R" -> x + 1 to y
"L" -> x - 1 to y
"D" -> x to y - 1
"U" -> x to y + 1
else -> error("Unsupported direction")
}
}
private fun Pair<Int, Int>.resolvePosition(knot: Pair<Int, Int>): Pair<Int, Int> {
val (tx, ty) = this
val (kx, ky) = knot
if (!shouldMoveTail(knot, this)) return this
val diffX = tx - kx
val newX = when {
diffX > 0 -> tx - 1
diffX < 0 -> tx + 1
else -> tx
}
val diffY = ty - ky
val newY = when {
diffY > 0 -> ty - 1
diffY < 0 -> ty + 1
else -> ty
}
return newX to newY
}
private fun shouldMoveTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Boolean {
val (hx, hy) = head
val (tx, ty) = tail
return sqrt((hx - tx.toDouble()).pow(2) + (hy - ty.toDouble()).pow(2)) >= 2
}
| 0 | Kotlin | 0 | 0 | 543e7cf0a2d706d23c3213d3737756b61ccbf94b | 2,201 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day08.kt | zuevmaxim | 572,255,617 | false | {"Kotlin": 17901} | import kotlin.math.max
private fun List<String>.toGrid(): List<IntArray> = this.map { line -> line.map { it.toString().toInt() }.toIntArray() }
private fun List<IntArray>.isVisible(i: Int, j: Int): Boolean {
val vertical = { x: Int -> this[x][j] < this[i][j] }
val horizontal = { x: Int -> this[i][x] < this[i][j] }
return (0 until i).all(vertical) || (i + 1 until size).all(vertical)
|| (0 until j).all(horizontal) || (j + 1 until this[0].size).all(horizontal)
}
private fun part1(input: List<String>): Int {
val g = input.toGrid()
val h = g.size
val w = g[0].size
val exterior = (h + w) * 2 - 4
var interior = 0
for (i in 1 until h - 1) {
for (j in 1 until w - 1) {
if (g.isVisible(i, j)) {
interior++
}
}
}
return exterior + interior
}
private fun List<IntArray>.score(i: Int, j: Int): Int {
var up = 0
for (x in (0 until i).reversed()) {
up++
if (this[x][j] >= this[i][j]) break
}
var down = 0
for (x in (i + 1 until size)) {
down++
if (this[x][j] >= this[i][j]) break
}
var left = 0
for (x in (0 until j).reversed()) {
left++
if (this[i][x] >= this[i][j]) break
}
var right = 0
for (x in (j + 1 until this[0].size)) {
right++
if (this[i][x] >= this[i][j]) break
}
return up * down * left * right
}
private fun part2(input: List<String>): Int {
val g = input.toGrid()
val h = g.size
val w = g[0].size
var max = 0
for (i in 1 until h - 1) {
for (j in 1 until w - 1) {
max = max(max, g.score(i, j))
}
}
return max
}
fun main() {
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 34356dd1f6e27cc45c8b4f0d9849f89604af0dfd | 1,925 | AOC2022 | Apache License 2.0 |
src/day02/Day02.kt | ivanovmeya | 573,150,306 | false | {"Kotlin": 43768} | package day02
import readInput
enum class Figure(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3)
}
enum class RoundScore(val score: Int) {
DRAW(3),
WIN(6),
LOOSE(0)
}
fun main() {
fun Char.toRoundScore() = when(this) {
'X' -> RoundScore.LOOSE
'Y' -> RoundScore.DRAW
'Z' -> RoundScore.WIN
else -> throw IllegalArgumentException("Unknown input: $this")
}
fun Char.toFigure() = when(this) {
'X','A' -> Figure.ROCK
'Y','B' -> Figure.PAPER
'Z','C' -> Figure.SCISSORS
else -> { throw IllegalArgumentException("Unknown figure: $this")}
}
fun roundScorePart1(enemy: Char, you: Char): Int {
val enemyFigure = enemy.toFigure()
val youFigure = you.toFigure()
val scoreForResult = when (enemyFigure) {
youFigure -> 3
Figure.ROCK -> if (youFigure == Figure.SCISSORS) RoundScore.LOOSE.score else RoundScore.WIN.score
Figure.PAPER -> if (youFigure == Figure.ROCK) RoundScore.LOOSE.score else RoundScore.WIN.score
Figure.SCISSORS -> if (youFigure == Figure.PAPER) RoundScore.LOOSE.score else RoundScore.WIN.score
}
return youFigure.score + scoreForResult
}
fun part1(input: List<String>): Int {
return input.sumOf { roundData ->
val (enemy, you) = roundData.split(' ').map { it.first() }
roundScorePart1(enemy, you)
}
}
fun roundScorePart2(enemy: Char, wantedResult: Char): Int {
val enemyFigure = enemy.toFigure()
val figureScore = when (wantedResult.toRoundScore()) {
RoundScore.LOOSE -> when (enemyFigure) {
Figure.PAPER -> Figure.ROCK.score
Figure.ROCK -> Figure.SCISSORS.score
Figure.SCISSORS -> Figure.PAPER.score
}
RoundScore.WIN -> when (enemyFigure) {
Figure.PAPER -> Figure.SCISSORS.score
Figure.ROCK -> Figure.PAPER.score
Figure.SCISSORS -> Figure.ROCK.score
}
RoundScore.DRAW -> when (enemyFigure) {
Figure.PAPER -> Figure.PAPER.score
Figure.ROCK -> Figure.ROCK.score
Figure.SCISSORS -> Figure.SCISSORS.score
}
}
return figureScore + wantedResult.toRoundScore().score
}
fun part2(input: List<String>): Int {
return input.sumOf { roundData ->
val (enemy, you) = roundData.split(' ').map { it.first() }
roundScorePart2(enemy, you)
}
}
val testInput = readInput("day02/Day02_test")
val test1Result = part1(testInput)
val test2Result = part2(testInput)
println(test1Result)
println(test2Result)
check(test1Result == 15)
check(test2Result == 12)
val input = readInput("day02/day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 7530367fb453f012249f1dc37869f950bda018e0 | 2,929 | advent-of-code-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.