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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AdventOfCodeDay21/src/nativeMain/kotlin/Day21.kt | bdlepla | 451,510,571 | false | {"Kotlin": 165771} | private data class GameState(
val player1: PlayerState,
val player2: PlayerState,
val player1Turn: Boolean = true
) {
fun next(die: Int): GameState =
GameState(
if (player1Turn) player1.next(die) else player1,
if (!player1Turn) player2.next(die) else player2,
player1Turn = !player1Turn
)
fun isWinner(scoreNeeded: Int = 1000): Boolean =
player1.score >= scoreNeeded || player2.score >= scoreNeeded
fun minScore(): Int =
minOf(player1.score, player2.score)
}
private data class PlayerState(val place: Int, val score: Int = 0) {
fun next(die: Int): PlayerState {
val nextPlace = (place + die - 1) % 10 + 1
return PlayerState(
place = nextPlace,
score = score + nextPlace
)
}
}
class Day21(private val lines:List<String>) {
fun solvePart1() = solve()
fun solvePart2() = playQuantum().max()
private fun solve():Long {
val (p1Start, p2Start) = parseInput(lines)
val dice = Dice()
val player1 = Player(1, p1Start, dice)
val player2 = Player(2, p2Start, dice)
while (true) {
if (player1.playTurn() > 999) break
if (player2.playTurn() > 999) break
}
val losingScore = if (player1.score() > 999) player2.score() else player1.score()
val numberDiceRolls = dice.numberOfRolls().toLong()
val ret = numberDiceRolls * losingScore
//println("losing score $losingScore * dice rolls $numberDiceRolls = $ret")
return ret
}
private fun parseInput(lines:List<String>):Pair<Int,Int> {
val start1 = lines[0].substringAfterLast(" ").toInt()
val start2 = lines[1].substringAfterLast(" ").toInt()
return start1 to start2
}
private val quantumDieFrequency: Map<Int, Long> =
mapOf(3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1)
private val stateMemory: MutableMap<GameState, WinCounts> = mutableMapOf()
private val player1Start = parseInput(lines).first
private val player2Start = parseInput(lines).second
private val initialGameState = GameState(PlayerState(player1Start), PlayerState(player2Start))
private fun playQuantum(state: GameState = initialGameState): WinCounts =
when {
state.isWinner(21) ->
if (state.player1.score > state.player2.score) WinCounts(1, 0) else WinCounts(0, 1)
state in stateMemory ->
stateMemory.getValue(state)
else ->
quantumDieFrequency.map { (die, frequency) ->
playQuantum(state.next(die)) * frequency
}.reduce { a, b -> a + b }.also { stateMemory[state] = it }
}
private class WinCounts(val player1: Long, val player2: Long) {
operator fun plus(other: WinCounts): WinCounts =
WinCounts(player1 + other.player1, player2 + other.player2)
operator fun times(other: Long): WinCounts =
WinCounts(player1 * other, player2 * other)
fun max(): Long =
maxOf(player1, player2)
}
} | 0 | Kotlin | 0 | 0 | 1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871 | 3,150 | AdventOfCode2021 | The Unlicense |
src/Day07.kt | eo | 574,058,285 | false | {"Kotlin": 45178} | // https://adventofcode.com/2022/day/7
fun main() {
fun parseListDirectoryOutput(lines: List<String>): List<File> =
lines.map { line ->
val (first, second) = line.split(" ")
if (first == "dir") {
Directory(second)
} else {
DataFile(second, first.toInt())
}
}
fun parseInput(input: String): List<Directory> {
val parentDirectories = ArrayDeque<Directory>()
var currentDirectory = Directory("/")
val allDirectories = mutableListOf<Directory>()
val commandsAndOutputs = input
.split("$ ")
.filterNot(String::isEmpty)
.drop(1) // skip root
.map(String::trimEnd)
commandsAndOutputs.forEach { commandAndOutput ->
val commandAndOutputLines = commandAndOutput.lines()
val command = Command.fromString(commandAndOutputLines.first())
when (command.name) {
Command.CHANGE_DIRECTORY -> {
if (command.parameter == "..") {
allDirectories.add(currentDirectory)
currentDirectory = parentDirectories.removeLast()
.withUpdatedFile(currentDirectory)
} else {
parentDirectories.add(currentDirectory)
currentDirectory =
currentDirectory.files
.filterIsInstance<Directory>()
.first { it.name == command.parameter }
}
}
Command.LIST_DIRECTORY -> {
currentDirectory = Directory(
currentDirectory.name,
parseListDirectoryOutput(commandAndOutputLines.drop(1))
)
}
else -> {
error("Invalid command! ${command.name}")
}
}
}
allDirectories.add(currentDirectory)
while (parentDirectories.isNotEmpty()) {
currentDirectory = parentDirectories.removeLast()
.withUpdatedFile(currentDirectory)
allDirectories.add(currentDirectory)
}
return allDirectories
}
fun printFileTree(file: File, level: Int = 0) {
print("\t".repeat(level))
when (file) {
is DataFile -> {
println("${file.name} ${file.size}")
}
is Directory -> {
println("${file.name} ${file.totalSize}")
file.files.forEach {
printFileTree(it, level + 1)
}
}
}
}
fun part1(input: String): Int {
val allDirectories = parseInput(input)
// printFileTree(allDirectories.last())
return allDirectories.filter { it.totalSize <= 100000 }.sumOf(Directory::totalSize)
}
fun part2(input: String): Int {
val totalDiskSpace = 70000000
val neededUnusedSpace = 30000000
val allDirectories = parseInput(input)
val rootDirectory = allDirectories.last()
val unusedSpace = totalDiskSpace - rootDirectory.totalSize
val needToDelete = neededUnusedSpace - unusedSpace
return allDirectories.filter { it.totalSize >= needToDelete }.minOf(Directory::totalSize)
}
val input = readText("Input07")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
private sealed class File(val name: String)
private class DataFile(name: String, val size: Int) : File(name)
private class Directory(name: String, val files: List<File> = emptyList()) : File(name) {
val totalSize: Int by lazy {
files.sumOf {
when (it) {
is DataFile -> it.size
is Directory -> it.totalSize
}
}
}
fun withUpdatedFile(file: File): Directory =
Directory(name, files.map {
if (it.name == file.name) file else it
})
}
private class Command(val name: String, val parameter: String = "") {
companion object {
const val CHANGE_DIRECTORY = "cd"
const val LIST_DIRECTORY = "ls"
fun fromString(commandStr: String) =
if (commandStr.startsWith(CHANGE_DIRECTORY)) {
Command(CHANGE_DIRECTORY, commandStr.substringAfter(" "))
} else if (commandStr.startsWith(LIST_DIRECTORY)) {
Command(LIST_DIRECTORY)
} else {
error("Unknown command! $commandStr")
}
}
}
| 0 | Kotlin | 0 | 0 | 8661e4c380b45c19e6ecd590d657c9c396f72a05 | 4,761 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day12.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.InputParser
import javax.swing.Spring
const val OPERATIONAL = '.'
const val DAMAGED = '#'
const val UNKNOWN = '?'
val cache = mutableMapOf<String, Long>()
data class SpringRow(
val springs: List<Char>,
val configuration: List<Int>,
) {
override fun toString() = "${springs.joinToString("")} ${configuration.joinToString(",")}"
private fun key() = springs.joinToString("") + configuration.joinToString(",") { "$it" }
fun countPossibleArrangements(prefix: String = ""): Long {
cache[key()]?.let { return it }
if (configuration.isEmpty()) {
return if (springs.count { it == DAMAGED } > 0) {
0
} else {
1
}
}
if (configuration.sum() > springs.count { it != OPERATIONAL }) return 0
val minSpaceNeeded = configuration.size + configuration.sum() - 1
if (springs.size < minSpaceNeeded) return 0
return when (springs.first()) {
OPERATIONAL -> SpringRow(springs.drop(1), configuration).countPossibleArrangements(prefix + springs[0])
DAMAGED -> {
if (hasPotentiallyDamagedGroupAtStart(configuration.first())) {
SpringRow(springs.drop(configuration.first() + 1), configuration.drop(1))
.countPossibleArrangements(prefix + "#".repeat(configuration.first()) + ".")
} else {
0
}
}
else -> {
SpringRow(springs.toMutableList().also { it[0] = OPERATIONAL }, configuration)
.countPossibleArrangements(prefix) +
SpringRow(springs.toMutableList().also { it[0] = DAMAGED }, configuration)
.countPossibleArrangements(prefix)
}
}.also {
cache[key()] = it
}
}
fun expanded() = SpringRow(
springs = springs + '?' + springs + '?' + springs + '?' + springs + '?' + springs,
configuration = configuration + configuration + configuration + configuration + configuration
)
private fun hasPotentiallyDamagedGroupAtStart(size: Int): Boolean {
return (springs.take(size).all { it != OPERATIONAL })
&& (springs.size == size || springs[size] != DAMAGED)
}
}
fun String.toSpringRow() = SpringRow(
springs = split(" ")[0].toCharArray().toList(),
configuration = split(" ")[1].split(",").map { it.toInt() },
)
object SpringRowParser : InputParser<List<SpringRow>> {
override fun parse(input: String): List<SpringRow> = input.split("\n").map(String::toSpringRow)
}
fun main() {
aoc(SpringRowParser) {
puzzle { 2023 day 12 }
part1 { input ->
input.sumOf { it.countPossibleArrangements() }
}
part2 { input ->
input.map(SpringRow::expanded).sumOf { it.countPossibleArrangements() }
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 3,090 | aoc-2023 | The Unlicense |
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day09.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2015
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.P
import se.saidaspen.aoc.util.words
fun main() = Day09.run()
object Day09 : Day(2015, 9) {
private val graph = mutableMapOf<P<String, String>, Int>()
private val cities = mutableListOf<String>()
init {
input.lines().map {
val (f, _, t, _, dist) = words(it)
graph[P(f, t)] = dist.toInt()
graph[P(t, f)] = dist.toInt()
}
cities.addAll(graph.keys.flatMap { mutableListOf(it.first, it.second) }.distinct())
}
override fun part1(): Any {
return cities.minOfOrNull { minDistance(graph, mutableListOf(), it) }!!
}
override fun part2(): Any {
return cities.maxOfOrNull { maxDistance(graph, mutableListOf(), it) }!!
}
private fun minDistance(graph: MutableMap<Pair<String, String>, Int>, visited : List<String>, current: String): Int {
val nextVisited = mutableListOf(current)
nextVisited.addAll(visited)
return if (nextVisited.size == cities.size) 0
else {
val toVisit = graph.filter { it.key.first == current }.filter { !visited.contains(it.key.second) }
if (toVisit.isEmpty()) Int.MAX_VALUE
else {
toVisit.map {
val dist = minDistance(graph, nextVisited, it.key.second)
if (dist == Int.MAX_VALUE) Int.MAX_VALUE else dist + it.value
}.min()
}
}
}
private fun maxDistance(graph: MutableMap<Pair<String, String>, Int>, visited : List<String>, current: String): Int {
val nextVisited = mutableListOf(current)
nextVisited.addAll(visited)
return if (nextVisited.size == cities.size) 0
else {
val toVisit = graph.filter { it.key.first == current }.filter { !visited.contains(it.key.second) }
if (toVisit.isEmpty()) Int.MIN_VALUE
else {
toVisit.map {
val dist = maxDistance(graph, nextVisited, it.key.second)
if (dist == Int.MIN_VALUE) Int.MIN_VALUE else dist + it.value
}.max()
}
}
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,225 | adventofkotlin | MIT License |
src/Day12.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | import java.util.PriorityQueue
import kotlin.streams.toList
import kotlin.math.abs
const val START = 83
const val END = 69
fun Vector2.manhattanDist(b: Vector2): Int {
return abs(this.first-b.first) + abs(this.second-b.second)
}
fun main() {
fun readMap(input: List<String>): List<MutableList<Int>> {
return input.map { it.chars().toList().toMutableList() }
}
fun findOnMap(field: List<List<Int>>, needle: Int): Vector2? {
for ((rowIdx, row) in field.withIndex()) {
val colIdx = row.indexOf(needle)
if (colIdx != -1) {
return Pair(rowIdx, colIdx)
}
}
return null
}
fun getNeighbours(field: List<List<Int>>, pos: Vector2): MutableList<Vector2> {
val res: MutableList<Vector2> = mutableListOf()
val (rowIdx, colIdx) = pos
if (rowIdx+1 < field.size && field[rowIdx][colIdx]+1 >= field[rowIdx+1][colIdx]) {
res.add(Vector2(rowIdx+1, colIdx))
}
if (rowIdx-1 >= 0 && field[rowIdx][colIdx]+1 >= field[rowIdx-1][colIdx]) {
res.add(Vector2(rowIdx-1, colIdx))
}
if (colIdx+1 < field[0].size && field[rowIdx][colIdx]+1 >= field[rowIdx][colIdx+1]) {
res.add(Vector2(rowIdx, colIdx+1))
}
if (colIdx-1 >= 0 && field[rowIdx][colIdx]+1 >= field[rowIdx][colIdx-1]) {
res.add(Vector2(rowIdx, colIdx-1))
}
return res
}
fun computeDistance(paths: Map<Vector2, Vector2>, startPos: Vector2, endPos: Vector2): Int {
var curNode = endPos
var totalNodes = 0
while (curNode != startPos) {
if (!paths.containsKey(curNode)) {
return Int.MAX_VALUE
}
curNode = paths[curNode]!!
totalNodes++
}
return totalNodes
}
fun shortestAStar(field: List<MutableList<Int>>, startPos: Vector2, endPos: Vector2, weights: MutableMap<Vector2, Int>): MutableMap<Vector2, Vector2> {
field[startPos.first][startPos.second] = 'a'.code
field[endPos.first][endPos.second] = 'z'.code
weights[startPos] = 0
val paths: MutableMap<Vector2, Vector2> = mutableMapOf()
val frontier = PriorityQueue<Pair<Vector2, Int>>{ a, b -> a.second - b.second}
frontier.add(Pair(startPos, 0))
while (frontier.isNotEmpty()) {
val (curPos, _) = frontier.poll()
if (curPos == endPos) {
break
}
for (nextPos in getNeighbours(field, curPos)) {
val newWeight = weights[curPos]!! + 1
if (!weights.containsKey(nextPos) || weights[nextPos]!! > newWeight) {
weights[nextPos] = newWeight
paths[nextPos] = curPos
frontier.add(Pair(nextPos, newWeight + nextPos.manhattanDist(endPos)))
}
}
}
return paths
}
fun part1(input: List<String>): Int {
val field = readMap(input)
val startPos = findOnMap(field, START)!!
val endPos = findOnMap(field, END)!!
val weights: MutableMap<Vector2, Int> = mutableMapOf(Pair(startPos, 0))
val paths = shortestAStar(field, startPos, endPos, weights)
return computeDistance(paths, startPos, endPos)
}
fun part2(input: List<String>): Int {
val field = readMap(input)
val endPos = findOnMap(field, END)!!
val weights: MutableMap<Vector2, Int> = mutableMapOf()
return field.withIndex().flatMap { (rowIdx, row) ->
row.withIndex().map { (colIdx, e) ->
if (e == 'a'.code) {
val startPos = Vector2(rowIdx, colIdx)
val paths = shortestAStar(field, startPos, endPos, weights)
computeDistance(paths, startPos, endPos)
} else {
Int.MAX_VALUE
}
}
}.min()
}
// test if implementation meets criteria from the description, like:
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 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 4,266 | aoc2022 | Apache License 2.0 |
2021/src/day14/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day14
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(input: Input): Int {
fun iterate(template: String, rules: Map<String, String>) = buildString {
append(template[0])
for (i in 1 until template.length) {
rules[template.substring(i - 1, i + 1)]?.let {
append(it)
}
append(template[i])
}
}
val rules = input.second.toMap()
var template = input.first
repeat(10) {
template = iterate(template, rules)
}
return template
.groupBy { it }
.values
.map { it.size }
.let { it.maxOrNull()!! - it.minOrNull()!! }
}
fun part2(input: Input): Long {
val rules = input.second.toMap()
val mem = Array(41) {
mutableMapOf<String, Map<Char, Long>>()
}
fun combine(
lhs: Map<Char, Long>,
rhs: Map<Char, Long>,
): Map<Char, Long> {
val sum = (lhs.keys + rhs.keys).associateWith {
lhs.getOrDefault(it, 0) + rhs.getOrDefault(it, 0)
}
return sum
}
fun rec(pair: String, depth: Int): Map<Char, Long> {
mem[depth][pair]?.let { return it }
if (depth == 0 || !rules.containsKey(pair)) {
return mapOf(pair.first() to 1L).also { mem[depth][pair] = it }
}
val between = rules[pair]!!
return combine(
rec(pair[0] + between, depth - 1),
rec(between + pair[1], depth - 1)
).also { mem[depth][pair] = it }
}
val origin = input.first + "$"
var answer = emptyMap<Char, Long>()
for (i in 0 until origin.lastIndex) {
answer = combine(answer, rec(origin.substring(i, i + 2), 40))
}
return answer.values.let {
it.maxOrNull()!! - it.minOrNull()!!
}
}
check(part1(readInput("test-input.txt")) == 1588)
check(part2(readInput("test-input.txt")) == 2188189693529L)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day14/$s")).readLines().let { lines ->
val origin = lines.first()
val rules = lines.drop(2).map {
val (a, b) = it.split(" -> ")
a to b
}
origin to rules
}
}
private typealias Input = Pair<String, List<Pair<String, String>>> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 2,289 | advent-of-code | Apache License 2.0 |
src/day04/Day04.kt | maxmil | 578,287,889 | false | {"Kotlin": 32792} | package day04
import println
import readInputAsText
typealias Board = List<List<BingoNumber>>
data class BingoNumber(val number: Int, var called: Boolean = false)
data class CompletedBoard(val number: Int, val board: Board)
fun main() {
fun parseNumbers(input: String) = input.split("\n").first().split(",").map { it.toInt() }
fun parseBoards(input: String) = input.split("\n\n").drop(1).map {
it.split("\n")
.map { row -> row.trim().split(Regex("\\s+")).map { col -> BingoNumber(col.toInt()) } }
}
fun play(numbers: List<Int>, boards: List<Board>): MutableList<CompletedBoard> {
val completedBoards = mutableListOf<CompletedBoard>()
numbers.forEach { number ->
boards.forEach { board ->
if (!completedBoards.map { it.board }.contains(board)) {
board.forEach { row ->
val foundIndex = row.indexOf(BingoNumber(number, false))
if (foundIndex != -1) {
row[foundIndex].called = true
if (row.none { !it.called } || board.map { it[foundIndex] }.none { !it.called }) {
completedBoards.add(CompletedBoard(number, board))
}
}
}
}
}
}
return completedBoards;
}
fun CompletedBoard.score() =
this.number * this.board.sumOf { numbers -> numbers.filter { !it.called }.sumOf { it.number } }
fun part1(input: String): Int {
val numbers = parseNumbers(input)
val boards = parseBoards(input)
return play(numbers, boards).first().score()
}
fun part2(input: String): Int {
val numbers = parseNumbers(input)
val boards = parseBoards(input)
return play(numbers, boards).last().score()
}
val testInput = readInputAsText("day04/Day04_test")
check(part1(testInput) == 4512)
check(part2(testInput) == 1924)
val input = readInputAsText("day04/Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 246353788b1259ba11321d2b8079c044af2e211a | 2,141 | advent-of-code-2021 | Apache License 2.0 |
src/Day11.kt | mikemac42 | 573,071,179 | false | {"Kotlin": 45264} | import java.io.File
fun main() {
val testInput = """Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1"""
val realInput = File("src/Day11.txt").readText()
val part1TestOutput = levelOfMonkeyBusiness(testInput, numRounds = 20, worryDivisor = 3)
println("Part 1 Test Output: $part1TestOutput")
check(part1TestOutput == 10605L)
val part1RealOutput = levelOfMonkeyBusiness(realInput, numRounds = 20, worryDivisor = 3)
println("Part 1 Real Output: $part1RealOutput")
val part2TestOutput = levelOfMonkeyBusiness(testInput, numRounds = 10000)
println("Part 2 Test Output: $part2TestOutput")
check(part2TestOutput == 2713310158L)
val part2RealOutput = levelOfMonkeyBusiness(realInput, numRounds = 10000)
println("Part 2 Real Output: $part2RealOutput")
}
/**
* Returns the product of the number of inspections of the 2 most active monkeys
* after 20 rounds of keep away.
*/
fun levelOfMonkeyBusiness(input: String, numRounds: Int, worryDivisor: Long? = null): Long {
val monkeys = makeMonkeys(input)
val productOfDivisors = monkeys.map { it.divisor }.reduce(Long::times)
repeat(numRounds) {
playRound(monkeys, worryDivisor, productOfDivisors)
// println("== After round ${it + 1} ==")
monkeys.forEachIndexed { index, monkey ->
// println("Monkey $index inspected items ${monkey.inspectionCount} times.")
}
}
val sortedInspectionCounts = monkeys.map { it.inspectionCount }.sortedDescending()
return sortedInspectionCounts[0] * sortedInspectionCounts[1]
}
fun makeMonkeys(input: String): List<Monkey> =
input.split("\n\n").map { section ->
val lines = section.lines()
Monkey(
inspectionCount = 0,
items = lines[1].drop(18).split(", ").map { it.toLong() }.toMutableList(),
operation = lines[2].drop(19).toOperation(),
divisor = lines[3].drop(21).toLong(),
nextMonkeyIfTrue = lines[4].drop(29).toInt(),
nextMonkeyIfFalse = lines[5].drop(30).toInt()
)
}
fun playRound(monkeys: List<Monkey>, worryDivisor: Long?, productOfDivisors: Long) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
monkey.inspectionCount++
var item = monkey.operation(monkey.items.removeFirst())
if (worryDivisor == null) {
item %= productOfDivisors
} else {
item /= worryDivisor
}
val nextMonkey = if (item % monkey.divisor == 0L) monkey.nextMonkeyIfTrue else monkey.nextMonkeyIfFalse
monkeys[nextMonkey].items.add(item)
}
}
}
data class Monkey(
var inspectionCount: Long,
val items: MutableList<Long>,
val operation: (Long) -> Long,
val divisor: Long,
val nextMonkeyIfTrue: Int,
val nextMonkeyIfFalse: Int
)
fun String.toOperation(): (Long) -> Long =
if (this == "old * old") {
{ x: Long -> x * x }
} else if (this.startsWith("old * ")) {
{ x: Long -> x * this.drop(6).toLong() }
} else if (this.startsWith("old + ")) {
{ x: Long -> x + this.drop(6).toLong() }
} else {
throw IllegalArgumentException(this)
}
| 0 | Kotlin | 1 | 0 | 909b245e4a0a440e1e45b4ecdc719c15f77719ab | 3,573 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/2022/Day15_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
private fun part1(entries: List<List<Int>>, Y: Int = 2000000) {
val beaconsAt = mutableSetOf<Int>()
val s = mutableSetOf<Int>()
for (e in entries) {
val dist = abs(e[0] - e[2]) + abs(e[1] - e[3])
if (abs(Y - e[1]) > dist) continue
if (e[3] == Y) beaconsAt.add(e[2])
val xMin = e[0] - (dist - abs(Y - e[1]))
val xMax = e[0] + (dist - abs(Y - e[1]))
for (x in xMin..xMax) s.add(x)
}
println(s.size - beaconsAt.size)
}
private fun part2(entries: List<List<Int>>, N: Int = 4000000) {
val ys = List(N + 1) { mutableListOf<Long>() }
for (e in entries) {
val dist = abs(e[0] - e[2]) + abs(e[1] - e[3])
val yMin = max(0, e[1] - dist)
val yMax = min(e[1] + dist, N)
// for each y, add the range of x to ys, so that the distance of
// point (x, y) from the current entry is at most `dist`
// ranges are stored as xMin * (N+1) + xMax instead of Pair(xMin, yMin) for smaller memory footstep
for (y in yMin..yMax) {
val xMin = max(0, e[0] - (dist - abs(y - e[1])))
val xMax = min(e[0] + (dist - abs(y - e[1])), N)
ys[y].add(xMin.toLong() * (N + 1) + xMax)
}
}
for (y in 0..N) {
if (y % 100000 == 0) println("----- $y -----")
var x = 0L
for (xr in ys[y].sorted()) {
val (xMin, xMax) = xr / (N + 1) to xr % (N + 1)
if (x < xMin) break
x = max(x, xMax + 1)
}
if (x <= N) {
println(x * N + y.toLong())
break
}
}
}
fun main() {
val regex = Regex("Sensor at x=([-0-9]+), y=([-0-9]+): closest beacon is at x=([-0-9]+), y=([-0-9]+)")
val entries = readInput(15).trim().lines()
.map {
val gr = regex.matchEntire(it)!!.groupValues.drop(1)
gr.map {x -> x.toInt()}
}
// separate
part1(entries)
part2(entries)
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 2,016 | adventofcode | Apache License 2.0 |
src/Day12.kt | tbilou | 572,829,933 | false | {"Kotlin": 40925} | import java.util.*
fun main() {
val day = "Day12"
fun reconstructPath(
cameFrom: HashMap<Pair<Int, Int>, Pair<Int, Int>>,
node: Pair<Int, Int>
): MutableList<Pair<Int, Int>> {
var path = mutableListOf(node)
var current = node
while (cameFrom.containsKey(current)) {
current = cameFrom[current]!!
path.add(current)
}
path.removeLast()
return path
}
// Adapted the pseudo-code to kotlin https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode
fun a_star(start: Pair<Int, Int>, goal:Pair<Int,Int>, maze: Maze): List<Pair<Int, Int>> {
var stack: Deque<Pair<Int, Int>> = java.util.ArrayDeque()
stack.push(start)
var cameFrom: HashMap<Pair<Int, Int>, Pair<Int, Int>> = HashMap()
var gScore: HashMap<Pair<Int, Int>, Int> = HashMap()
var fScore: HashMap<Pair<Int, Int>, Int> = HashMap()
for (i in 0..maze.dimension().first - 1) { //row
for (j in 0..maze.dimension().second - 1) { // column
gScore[i to j] = Int.MAX_VALUE
fScore[i to j] = Int.MAX_VALUE
}
}
gScore[start] = 0
fScore[start] = maze.h(maze.getValue(start))
while (stack.isNotEmpty()) {
val current = stack.sortedBy { fScore.get(it) }.first()
if (current == goal) {
val path = reconstructPath(cameFrom, current)
return path
}
stack.remove(current)
// Get neighbours
val neighbours = maze.neighbours(current)
neighbours.forEach { neighbour ->
val tentativeScore = gScore.get(current)?.plus(maze.d(current, neighbour))
if (tentativeScore!! < gScore.get(neighbour)!!) {
cameFrom.put(neighbour, current)
gScore[neighbour] = tentativeScore
fScore[neighbour] = tentativeScore + maze.h(maze.getValue(neighbour))
if (!stack.contains(neighbour)) {
stack.push(neighbour)
}
}
}
}
return emptyList()
}
fun part1(input: List<String>): Int {
val maze = Maze(input)
val start = maze.getStart()
var goal = maze.getGoal()
return a_star(start, goal, maze).size
}
fun part2(input: List<String>): Int {
val maze = Maze(input)
var goal = maze.getGoal()
val all = maze.getAll('a')
.map { start ->
a_star(start, goal, maze)
}.filter { it.isNotEmpty() }
return all.map { it.size }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("$day")
println(part1(input))
println(part2(input))
}
class Maze(input: List<String>) {
val grid = input.map { it.toList().map { it } }
fun getStart():Pair<Int,Int>{
return getFirst('S')
}
fun getGoal():Pair<Int,Int>{
return getFirst('E')
}
private fun getFirst(value: Char): Pair<Int, Int> {
grid.forEachIndexed { row, list ->
val col = list.indexOf(value)
if (col != -1) {
return Pair(row, col)
}
}
error("Value not found")
}
fun getAll(search: Char): List<Pair<Int, Int>> {
val result = mutableListOf<Pair<Int, Int>>()
grid.forEachIndexed { i, row ->
row.forEachIndexed { j, c ->
if (c == search) {
result.add(i to j)
}
}
}
return result
}
fun getValue(a: Pair<Int, Int>): Char {
val c = grid[a.first][a.second]
return when(c){
'S' -> 'a'
'E' -> 'z'
else -> c
}
}
// Our goal is to reach z. any character that gets us closer has priority
fun h(height: Char): Int {
return 'z'.code - height.code
}
// We want to minimize the distance between us and our neighbour.
// letter closer to current are better. Initially I was allowing 0 when traveling between the same letter
// but this doesn't lead to the shortest path. The has to be a penalty when staying in the same letter.
// The more we travel in the same letter the more expensive it becomes.
fun d(current: Pair<Int, Int>, neighbour: Pair<Int, Int>): Int {
val vcurrent = this.getValue(current)
val vneighbour = this.getValue(neighbour)
return if (kotlin.math.abs(vcurrent - vneighbour) == 0) {
1 // Add a penalty when staying in the same letter
} else {
kotlin.math.abs(vcurrent - vneighbour) + 1
}
}
fun dimension(): Pair<Int, Int> {
return Pair(grid.size, grid.first().size)
}
// Needs refactoring.
// Neighbours that are not accessible (next letter) are not returned
fun neighbours(coord: Pair<Int, Int>): List<Pair<Int, Int>> {
var up = if (grid.getOrNull(coord.first - 1) != null) Pair(coord.first - 1, coord.second) else null
var down = if (grid.getOrNull(coord.first + 1) != null) Pair(coord.first + 1, coord.second) else null
var left =
if (grid.get(coord.first).getOrNull(coord.second - 1) != null) Pair(coord.first, coord.second - 1) else null
var right =
if (grid.get(coord.first).getOrNull(coord.second + 1) != null) Pair(coord.first, coord.second + 1) else null
if (up != null && getValue(up) - getValue(coord) > 1) {
up = null
}
if (down != null && getValue(down) - getValue(coord) > 1) {
down = null
}
if (left != null && getValue(left) - getValue(coord) > 1) {
left = null
}
if (right != null && getValue(right) - getValue(coord) > 1) {
right = null
}
return listOfNotNull(up, down, left, right) as List<Pair<Int, Int>>
}
} | 0 | Kotlin | 0 | 0 | de480bb94785492a27f020a9e56f9ccf89f648b7 | 6,180 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | dmstocking | 575,012,721 | false | {"Kotlin": 40350} | import java.lang.Exception
import java.util.Base64
fun parseMonkey(lines: List<String>, constructor: (Long, (Long) -> Long, (Long) -> Int, List<Long>) -> Monkey): Monkey {
val items = lines[1].substring(18).split(", ").map { it.toLong() }
val (a, op, b) = lines[2].substring(19).split(" ")
val operation = { old: Long ->
val a = a.toLongOrNull() ?: old
val b = b.toLongOrNull() ?: old
when (op) {
"*" -> a * b
"+" -> a + b
else -> throw Exception()
}
}
val divisible = lines[3].substring(21).toLong()
val t = lines[4].substring(29).toInt()
val f = lines[5].substring(30).toInt()
return constructor(divisible, operation, { if (it.mod(divisible) == 0L) t else f }, items)
}
open class Monkey(val divisible: Long, protected val operation: (Long) -> Long, private val throwTo: (Long) -> Int, items: List<Long>) {
private val items = ArrayDeque(items.toList())
var inspections = 0L
fun turn() {
while (items.size > 0) {
inspect()
}
}
private fun inspect() {
inspections += 1
items
.removeFirstOrNull()
?.let { evalWorry(it) }
?.let { monkey[throwTo(it)].catch(it) }
}
open fun evalWorry(item: Long): Long {
return operation(item) / 3
}
private fun catch(item: Long) {
items.addLast(item)
}
}
class BadMonkey(divisible: Long, operation: (Long) -> Long, throwTo: (Long) -> Int, items: List<Long>): Monkey(divisible, operation, throwTo, items) {
var mod = 0L
override fun evalWorry(item: Long): Long {
return operation(item) % mod
}
}
var monkey = listOf<Monkey>()
fun main() {
fun part1(input: List<String>): Long {
monkey = input.chunked(7).map { parseMonkey(it, ::Monkey) }
(1..20).forEach { _ ->
monkey.forEach { it.turn() }
}
return monkey.map { it.inspections }.sortedByDescending { it }.take(2).let { (a, b) -> a * b }
}
fun part2(input: List<String>): Long {
val m = input.chunked(7).map { parseMonkey(it, ::BadMonkey) }.map { it as BadMonkey }
monkey = m
val mod = m.map { it.divisible }.reduce(Long::times)
m.forEach { it.mod = mod }
(1..10000).forEach { _ ->
m.forEach { it.turn() }
}
return m
.map { it.inspections }
.sortedByDescending { it }
.take(2)
.let { (a, b) -> a * b }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 10605L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e49d9247340037e4e70f55b0c201b3a39edd0a0f | 2,833 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | splinkmo | 573,209,594 | false | {"Kotlin": 6593} | fun main() {
fun binarySort(searchChar: Char, charList: List<Char>): Boolean{
if (charList.size <= 1){
return charList[0] == searchChar
}
var chunkedValue = if (charList.size % 2 == 0) charList.size/2 else charList.size/2 + 1
return if (searchChar < charList[chunkedValue]) {
var splitChars = charList.chunked(chunkedValue)
binarySort(searchChar, splitChars[0])
} else {
var splitChars = charList.chunked(chunkedValue)
binarySort(searchChar, splitChars[1])
}
}
fun letterScore(letter: Char): Int{
return if (letter.isLowerCase()) letter.code - 96 else letter.code - 38
}
fun part1(input: List<String>): Int {
var priorityScore = 0
var ruckSackList = input.map { it.chunked(it.length/2) }
for (compartments in ruckSackList){
var compartment1 = compartments[0].toList().sorted()
var compartment2 = compartments[1].toList().sorted()
for (item in compartment1){
if (binarySort(item, compartment2)) {
priorityScore += letterScore(item)
break
}
}
}
return priorityScore
}
fun part2(input: List<String>): Int {
var ruckSackGroup = input.chunked(3).flatMap { it -> (it[0].toSet() intersect it[1].toSet()) intersect it[2].toSet() }
return ruckSackGroup.map { it -> letterScore(it) }.sum()
}
val input = readInput("Day03")
//println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 4ead85d0868feec13cc300055beba7830b798345 | 1,599 | advent-code-22 | Apache License 2.0 |
src/main/kotlin/Day4.kt | noamfreeman | 572,834,940 | false | {"Kotlin": 30332} | private val part1ExampleInput = """
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
""".trimIndent()
fun main() {
println("day4")
println()
println("part1")
assertEquals(part1(part1ExampleInput), 2)
assertEquals(part1(readInputFile("day4_input.txt")), 485) // regression for equal ranges.
println(part1(readInputFile("day4_input.txt")))
println()
println("part2")
assertEquals(part2(part1ExampleInput), 4)
println(part2(readInputFile("day4_input.txt")))
}
private fun parseInput(input: String): List<Pair<IntRange, IntRange>> = input
.lines().map { line ->
val (elf1, elf2) = line.split(",")
val range1 = elf1.parseRange()
val range2 = elf2.parseRange()
range1 to range2
}
private fun part1(input: String): Int = parseInput(input)
.count { (range1, range2) ->
range1.contains(range2) || range2.contains(range1)
}
private fun part2(input: String): Int = parseInput(input)
.count { (range1, range2) ->
range1 intersects range2
}
private fun String.parseRange(): IntRange = this
.split("-")
.let {
it[0].toInt()..it[1].toInt()
}
private fun IntRange.contains(other: IntRange): Boolean {
return this.first <= other.first && this.last >= other.last
}
private infix fun IntRange.intersects(other: IntRange): Boolean {
return this.contains(other.first) || this.contains(other.last)
|| other.contains(this.first) || other.contains(this.last)
}
| 0 | Kotlin | 0 | 0 | 1751869e237afa3b8466b213dd095f051ac49bef | 1,523 | advent_of_code_2022 | MIT License |
day06/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | import java.io.File
import java.lang.Double.POSITIVE_INFINITY
import kotlin.math.abs
fun main() {
val input = parseInput(readInputFile())
println("Part I: the solution is ${solvePartI(input)}.")
println("Part II: the solution is ${solvePartII(input)}.")
}
fun readInputFile(): List<String> {
return File(ClassLoader.getSystemResource("input.txt").file).readLines()
}
fun parseInput(input: List<String>): List<Coordinate> {
return input
.map { line -> line.replace(" ", "").split(",") }
.map { splitLine -> Coordinate(splitLine[0].toInt(), splitLine[1].toInt()) }
}
fun solvePartI(coordinates: List<Coordinate>): Int? {
val coordinatesWithFiniteArea = getCoordinatesWithFiniteArea(coordinates)
val area = coordinatesWithFiniteArea.associateTo(mutableMapOf()) { it to 0 }
for (x in getMinX(coordinates)..getMaxX(coordinates)) {
for (y in getMinY(coordinates)..getMaxY(coordinates)) {
val closestCoordinate = getClosestCoordinate(Coordinate(x, y), coordinates)
if (closestCoordinate != null && closestCoordinate in coordinatesWithFiniteArea) {
area[closestCoordinate] = area[closestCoordinate]!! + 1
}
}
}
return area.values.max()
}
fun solvePartII(coordinates: List<Coordinate>): Int {
var result = 0
for (x in getMinX(coordinates)..getMaxX(coordinates)) {
for (y in getMinY(coordinates)..getMaxY(coordinates)) {
if (coordinates.sumBy { calculateTaxicabDistance(Coordinate(x, y), it) } < 10000) {
result++
}
}
}
return result
}
fun getCoordinatesWithFiniteArea(coordinates: List<Coordinate>): List<Coordinate> {
val result = coordinates.toMutableList()
for (x in getMinX(coordinates)..getMaxX(coordinates)) {
val closestCoordinateToTopBorder = getClosestCoordinate(Coordinate(x, getMinY(coordinates)), coordinates)
if (closestCoordinateToTopBorder in result) {
result.remove(closestCoordinateToTopBorder)
}
val closestCoordinateToBottomBorder = getClosestCoordinate(Coordinate(x, getMaxY(coordinates)), coordinates)
if (closestCoordinateToBottomBorder in result) {
result.remove(closestCoordinateToBottomBorder)
}
}
for (y in (getMinY(coordinates) + 1)..(getMaxY(coordinates) - 1)) {
val closestCoordinateToLeftBorder = getClosestCoordinate(Coordinate(getMinX(coordinates), y), coordinates)
if (closestCoordinateToLeftBorder in result) {
result.remove(closestCoordinateToLeftBorder)
}
val closestCoordinateToRightBorder = getClosestCoordinate(Coordinate(getMaxX(coordinates), y), coordinates)
if (closestCoordinateToRightBorder in result) {
result.remove(closestCoordinateToRightBorder)
}
}
return result
}
fun getMinX(coordinates: List<Coordinate>): Int {
return coordinates
.map { it.x }
.min()!!
}
fun getMaxX(coordinates: List<Coordinate>): Int {
return coordinates
.map { it.x }
.max()!!
}
fun getMinY(coordinates: List<Coordinate>): Int {
return coordinates
.map { it.y }
.min()!!
}
fun getMaxY(coordinates: List<Coordinate>): Int {
return coordinates
.map { it.y }
.max()!!
}
fun getClosestCoordinate(location: Coordinate, coordinates: List<Coordinate>): Coordinate? {
var minDistance = POSITIVE_INFINITY.toInt()
var result: Coordinate? = null
coordinates.forEach { coordinate ->
val taxicabDistance = calculateTaxicabDistance(location, coordinate)
if (taxicabDistance == minDistance) {
result = null
minDistance = taxicabDistance
} else if (taxicabDistance < minDistance) {
minDistance = taxicabDistance
result = coordinate
}
}
return result
}
fun calculateTaxicabDistance(coordinate1: Coordinate, coordinate2: Coordinate): Int {
return abs(coordinate1.x - coordinate2.x) + abs(coordinate1.y - coordinate2.y)
}
data class Coordinate(val x: Int, val y: Int)
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 4,179 | AdventOfCode2018 | MIT License |
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day15.kt | clechasseur | 568,233,589 | false | {"Kotlin": 242914} | package io.github.clechasseur.adventofcode.y2015
import kotlin.math.max
object Day15 {
private val input = mapOf(
"Sprinkles" to Ingredient(2, 0, -2, 0, 3),
"Butterscotch" to Ingredient(0, 5, -3, 0, 3),
"Chocolate" to Ingredient(0, 0, 5, -1, 8),
"Candy" to Ingredient(0, -1, 0, 5, 8),
)
fun part1(): Int = recipes(input.keys, 100).maxOf { it.score }
fun part2(): Int = recipes(input.keys, 100).filter { it.calories == 500 }.maxOf { it.score }
private data class Ingredient(val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int)
private class Recipe(val ingredients: Map<String, Int>) {
val score: Int
get() {
var capacity = 0
var durability = 0
var flavor = 0
var texture = 0
ingredients.forEach { (name, teaspoons) ->
capacity += teaspoons * input[name]!!.capacity
durability += teaspoons * input[name]!!.durability
flavor += teaspoons * input[name]!!.flavor
texture += teaspoons * input[name]!!.texture
}
return max(capacity, 0) * max(durability, 0) * max(flavor, 0) * max(texture, 0)
}
val calories: Int
get() = ingredients.asSequence().sumOf { (name, teaspoons) ->
input[name]!!.calories * teaspoons
}
}
private fun recipes(names: Collection<String>, teaspoons: Int): Sequence<Recipe> {
if (names.size == 1) {
return sequenceOf(Recipe(mapOf(names.first() to teaspoons)))
}
return (teaspoons downTo 0).asSequence().flatMap { i ->
recipes(names.drop(1), teaspoons - i).map { subRecipe ->
Recipe(subRecipe.ingredients + mapOf(names.first() to i))
}
}
}
}
| 0 | Kotlin | 0 | 0 | e5a83093156cd7cd4afa41c93967a5181fd6ab80 | 1,928 | adventofcode2015 | MIT License |
src/Day04.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | fun main() {
class Range(val from: Int, val to: Int) {
init {
require(from <= to)
}
fun contains(other: Range): Boolean =
from <= other.from && other.to <= to
fun intersects(other: Range): Boolean =
when {
to < other.from -> false
other.to < from -> false
else -> true
}
}
fun parseRange(range: String): Range {
val (from, to) = range.split("-", limit = 2)
return Range(from.toInt(), to.toInt())
}
fun parsePairOrRanges(pair: String): Pair<Range, Range> {
val ranges = pair.split(",", limit = 2)
val (left, right) = ranges.map { parseRange(it) }
return left to right
}
fun part1(input: List<String>): Int {
return input.count { pairOfRanges ->
val (left, right) = parsePairOrRanges(pairOfRanges)
left.contains(right) || right.contains(left)
}
}
fun part2(input: List<String>): Int {
return input.count { pairOfRanges ->
val (left, right) = parsePairOrRanges(pairOfRanges)
left.intersects(right)
}
}
// 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 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 1,472 | aoc2022 | Apache License 2.0 |
src/Day04.kt | devheitt | 573,207,407 | false | {"Kotlin": 11944} | fun main() {
fun part1(input: List<String>): Int {
//In how many assignment pairs does one range fully contain the other?
var count = 0
for (line in input) {
val pairs = line.split(",")
val firstPair = pairs[0].split("-").map { c -> c.toInt() }
val secondPair = pairs[1].split("-").map { c -> c.toInt() }
if(firstPair[0] <= secondPair[0] && firstPair[1] >= secondPair[1]
|| secondPair[0] <= firstPair[0] && secondPair[1] >= firstPair[1])
count++
}
return count
}
fun part2(input: List<String>): Int {
//In how many assignment pairs do the ranges overlap?
var count = 0
for (line in input) {
val pairs = line.split(",")
val firstPair = pairs[0].split("-").map { c -> c.toInt() }
val secondPair = pairs[1].split("-").map { c -> c.toInt() }
if(firstPair[1] >= secondPair[0] && firstPair[0] <= secondPair[1]
|| secondPair[1] >= firstPair[0] && secondPair[0] <= firstPair[1])
count++
}
return count
}
// 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 | a9026a0253716d36294709a547eaddffc6387261 | 1,435 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/test/kotlin/com/igorwojda/list/maxsublistsum/Solution.kt | igorwojda | 159,511,104 | false | {"Kotlin": 254856} | package com.igorwojda.list.maxsublistsum
import kotlin.math.max
// Time Complexity: O(n)
// Space Complexity: O(1)
// Use "sliding window" - store sum in single variable and with each iteration add (current item)
// and remove (first item before current sub-list)
private object Solution1 {
private fun maxSubListSum(list: List<Int>, numElements: Int): Int? {
if (list.size < numElements) {
return null
}
var maxSum = list.take(numElements).sum()
var tempSum = maxSum
(numElements..list.lastIndex).forEach { index ->
tempSum = tempSum - list[index - numElements] + list[index]
maxSum = max(maxSum, tempSum)
}
return maxSum
}
}
private object Solution2 {
private fun maxSubListSum(list: List<Int>, numElements: Int): Int? {
if (list.size < numElements) {
return null
}
return list.foldIndexed(0 to 0) { i, (sum, max), next ->
(sum + next - (list.getOrNull(i - numElements) ?: 0)).let {
it to if (it > max) it else max
}
}.second
}
}
// Time Complexity: O(n*m)
// Loop through the list and at each index loop again to calculate sum of sublist (from index to index + n)
private object Solution3 {
private fun maxSubListSum(list: List<Int>, numElements: Int): Int? {
if (list.size < numElements) {
return null
}
var maxSum: Int? = null
for (i in 0..list.size - numElements) {
var tempSum: Int? = null
for (j in i until (i + numElements)) {
if (tempSum == null) {
tempSum = list[j]
} else {
tempSum += list[j]
}
}
maxSum = max(maxSum, tempSum)
}
return maxSum
}
private fun max(i1: Int?, i2: Int?): Int? {
return when {
i1 != null && i2 != null -> max(i1, i2)
i1 != null && i2 == null -> i1
i1 == null && i2 != null -> i2
else -> null
}
}
}
private object Solution4 {
private fun maxSubListSum(list: List<Int>, numElements: Int): Int? {
if (list.isEmpty()) return null
return (0..list.size - numElements)
.maxOfOrNull { i -> list.subList(i, i + numElements).sum() }
}
}
private object Solution5 {
private fun maxSubListSum(list: List<Int>, numElements: Int) = list.windowed(numElements)
.toMutableList()
.maxOfOrNull { it.sum() }
}
| 9 | Kotlin | 225 | 895 | b09b738846e9f30ad2e9716e4e1401e2724aeaec | 2,568 | kotlin-coding-challenges | MIT License |
src/main/kotlin/Day15.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | import kotlin.math.absoluteValue
val pattern15 = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""")
data class Position15(val x: Int, val y: Int) {
fun distance(other: Position15): Int {
return (x - other.x).absoluteValue + (y - other.y).absoluteValue
}
}
data class Report(val sensor: Position15, val beacon: Position15) {
val distance: Int
get() = sensor.distance(beacon)
fun minX(y: Int): Int? {
if (!coversRow(y)) {
return null
}
var dist = distance
dist -= (sensor.y - y).absoluteValue
return sensor.x - dist
}
fun maxX(y: Int): Int? {
if (!coversRow(y)) {
return null
}
var dist = distance
dist -= (sensor.y - y).absoluteValue
return sensor.x + dist
}
fun coversRow(y: Int): Boolean {
val dist = distance
return y in ((sensor.y - dist)..(sensor.y + dist))
}
}
fun main() {
fun parse(line: String): Report {
val match = pattern15.matchEntire(line)!!
return Report(Position15(match.groupValues[1].toInt(), match.groupValues[2].toInt()),
Position15(match.groupValues[3].toInt(), match.groupValues[4].toInt()))
}
fun parse(input: List<String>): List<Report> {
return input.map { parse(it) }
}
fun covered(reports: List<Report>, y: Int, excludeBeacons: Boolean = true): MutableSet<Int> {
val covered = mutableSetOf<Int>()
for (report in reports) {
val start = report.minX(y) ?: continue
val end = report.maxX(y) ?: continue
if (excludeBeacons) {
for (i in (start..end)) {
if (y == report.beacon.y && i == report.beacon.x) {
continue
}
covered.add(i)
}
} else {
covered.addAll(start..end)
}
}
return covered
}
fun covered2(reports: List<Report>, y: Int): MutableSet<IntRange> {
val covered = mutableSetOf<IntRange>()
for (report in reports) {
val start = report.minX(y) ?: continue
val end = report.maxX(y) ?: continue
val overlapping = covered.filter { it.overlap(start..end) != null }
if (overlapping.isEmpty()) {
covered.add(start..end)
} else {
covered.removeAll(overlapping.toSet())
covered.add(min(overlapping.minOf { it.first }, start)..max(overlapping.maxOf { it.last }, end))
}
}
return covered
}
fun part1(input: List<String>, y: Int): Int {
val reports = parse(input)
return covered(reports, y).size
}
fun part2(input: List<String>, limit: Int): Long {
val reports = parse(input)
for (y in (0..limit)) {
val co = covered2(reports, y)
co.trim(0, limit)
co.add(-1..-1)
co.add((limit+1)..(limit+1))
if (co.size > 1) {
val closed = co.sortedBy { it.first }.zipWithNext { a: IntRange, b: IntRange ->
val gap = (a.last + 1) until b.first
return@zipWithNext if (gap.isEmpty()) {
null
} else { gap }
}.filterNotNull()
if (closed.isNotEmpty()) {
val x = closed.first().first
println("$x, $y, $closed, ${x * 4000000 + y}")
return x.toLong() * 4000000L + y.toLong()
}
}
}
return -1L
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
val input = readInput("Day15")
println(part1(input, 2000000))
check(part2(testInput, 20) == 56000011L)
println(part2(input, 4000000)) // 698766328
}
private fun MutableSet<IntRange>.trim(lowest: Int, highest: Int) {
val i = iterator()
val toAdd = mutableSetOf<IntRange>()
while (i.hasNext()) {
val range = i.next()
if (range.last < lowest) {
i.remove()
continue
}
if (range.first > highest) {
i.remove()
continue
}
if (range.first < lowest || range.last > highest) {
val newRange = max(range.first, lowest)..min(range.last, highest)
toAdd.add(newRange)
i.remove()
continue
}
}
addAll(toAdd)
}
| 0 | Kotlin | 0 | 0 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 4,634 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | Advice-Dog | 436,116,275 | true | {"Kotlin": 25836} | fun main() {
val zero = 6
val one = 2
val two = 5
val three = 5
val four = 4
val five = 5
val six = 6
val seven = 3
val eight = 7
val nine = 6
val unique = listOf(one, four, seven, eight)
fun part1(input: List<String>): Int {
return input.sumOf {
val (input, output) = it.split("|")
output.split(" ").count { it.length in unique }
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
//val it = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
val (input, output) = it.split("|")
// 0000
// 1 2
// 1 2
// 3333
// 4 5
// 4 5
// 6666
val map = mutableMapOf<Int, String>()
for (i in 0 until 7) {
map[i] = ""
}
val split = input.split(" ")
.filter { it.isNotBlank() }
.map {
it.toSortedSet().joinToString(separator = "") { it.toString() }
}//.filter { it.length in unique }
println(split)
split.forEach {
when (it.length) {
one -> {
map[2] += it
map[5] += it
}
four -> {
map[1] += it
map[3] += it
map[5] += it
}
seven -> {
map[0] += it
map[2] += it
map[5] += it
}
}
}
println(map)
val o = split.find { it.length == one }!!
val f = split.find { it.length == four }!!
val s = split.find { it.length == seven }!!
// x is 0
val x = s.filter { it !in o }
map[0] = x
map[2] = o
map[5] = o
val f2 = f.filter { it !in o }
map[1] = f2
map[3] = f2
println("o: $o")
// 2, 3, 5 all have 5 segments
var new_three = split.find { it.length == three && contains(it, o) }!!
println(new_three)
// these two items are for the 3rd and 6th position
new_three = new_three.filter { it !in s }
println(new_three)
println(f2)
val middleCharacter = new_three.find { it in f2 }.toString()
map[3] = middleCharacter
val firstCharacter = new_three.find { it !in f2 }.toString()
map[6] = firstCharacter
map[1] = f2.find { it.toString() != middleCharacter }.toString()
// find 8 and see what 4th position is
val e = split.find { it.length == eight }!!
println("eight: $e")
val e_find = e.find { character -> !map.any { character in it.value } }
println(e_find)
map[4] = e_find.toString()
// find 2 and see what 2nd position is, use that to set 2nd and 5th position
val one_options = map[2]!!
val two_find =
split.find { s1 -> s1.length == two && !contains(s1, one_options) && !contains(map[1]!!, s1) }!!
println("two find: $two_find does not contain $one_options")
map[2] = two_find.filter { it in one_options }
map[5] = one_options.filter { it !in map[2]!! }
// check(getValue(map, "cdfbe") == 5)
// check(getValue(map, "gcdfa") == 2)
// map.forEach {
// map[it.key] = it.value.split("").distinct().filter { it.isNotBlank() }.joinToString(separator = "") { it }
// }
//
// println(map)
//
// map.forEach {
// val key = it.key
// println("Looking for $it")
// val find = it.value.find { character -> map.all { it.key == key || character !in it.value } }
// println("Found: $find not in any others")
//
// //map[it.key] = it.value.split("").distinct().filter { it.isNotBlank() }.toString()
// }
val builder = StringBuilder()
builder.append(" " + (map[0]?.repeat(4) ?: "....") + "\n")
builder.append((map[1] ?: ".") + " " + (map[2] ?: ".") + "\n")
builder.append((map[1] ?: ".") + " " + (map[2] ?: ".") + "\n")
builder.append(" " + (map[3]?.repeat(4) ?: "....") + "\n")
builder.append((map[4] ?: ".") + " " + (map[5] ?: ".") + "\n")
builder.append((map[4] ?: ".") + " " + (map[5] ?: ".") + "\n")
builder.append(" " + (map[6]?.repeat(4) ?: "....") + "\n")
println(builder.toString())
val reduce = output.split(" ").filter { it.isNotBlank() }
.map {
val value = getValue(map, it)
println("$it: $value")
value
}.joinToString(separator = "") { it.toString() }
println("final: $reduce")
reduce.toInt()
}
}
// test if implementation meets criteria from the description, like:
val testInput = getTestData("Day08")
check(part1(testInput) == 26)
check(part2(testInput) == 61229)
val input = getData("Day08")
println(part1(input))
println(part2(input))
}
fun contains(lhs: String, rhs: String): Boolean {
println("looking for: $lhs in $rhs")
val array = lhs.toCharArray()
return rhs.all { it in array }
}
fun getValue(map: Map<Int, String>, input: String): Int {
when (input.length) {
2 -> return 1
3 -> return 7
4 -> return 4
7 -> return 8
}
val invert = mutableMapOf<String, Int>()
for (entry in map.entries) {
invert[entry.value] = entry.key
}
val positions: List<Int> = input.map { invert[it.toString()]!! }.sorted()
println(positions)
if (positions == listOf(0, 2, 3, 4, 6))
return 2
if (positions == listOf(0, 2, 3, 5, 6))
return 3
if (positions == listOf(0, 1, 3, 5, 6))
return 5
if (positions == listOf(0, 1, 3, 4, 5, 6))
return 6
if (positions == listOf(0, 1, 2, 3, 5, 6))
return 9
return -1
}
| 0 | Kotlin | 0 | 0 | 2a2a4767e7f0976dba548d039be148074dce85ce | 6,358 | advent-of-code-kotlin-template | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2019/Day14.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2019
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.graph.Graph
import com.nibado.projects.advent.resourceLines
import kotlin.math.ceil
typealias ElementAmount = Pair<String, Int>
object Day14 : Day {
private val reactionsReal = resourceLines(2019, 14).map(::parseReaction)
private val reactions = INPUT_A.trim().split("\n").map(::parseReaction)
override fun part1(): Int {
val map = reactions.map { it.output.first to it }.toMap()
//val oreCost = oreCost("FUEL", 1, map, emptyMap<>())
TODO()
//return oreCost
}
fun oreCost(
current: String,
requiredAmount: Int,
map: Map<String, Reaction>,
stock: MutableMap<String, Int>,
depth: Int = 0): Int {
val start = map.getValue(current)
val pre = " ".repeat(depth)
println("$pre$current: $requiredAmount")
var sum = 0
for(i in start.input) {
val currentAmount = stock[i.first] ?: 0
val requiredReactions = ceil(i.second.toDouble() / start.output.second.toDouble()).toInt()
println("$pre- ${i.first} (${i.second} > ${start.output.second}): $requiredReactions")
sum += if(i.first == "ORE") {
requiredReactions * i.second
} else {
oreCost(i.first, requiredReactions * i.second, map, stock, depth + 1)
}
}
return sum
}
fun print(list: List<Reaction>) {
}
override fun part2() = TODO()
fun parseReaction(line: String): Reaction {
fun parseElementAmount(inp: String) = inp.split(", ")
.map { it.split(" ").let { (a, e) -> e to a.toInt() } }
val (input, output) = line.split(" => ")
.let { (input, output) -> parseElementAmount(input) to parseElementAmount(output).first() }
return Reaction(input, output)
}
}
data class Reaction(val input: List<ElementAmount>, val output: ElementAmount)
fun main() {
println(Day14.part1())
}
const val INPUT_A = """
10 ORE => 10 A
1 ORE => 1 B
7 A, 1 B => 1 C
7 A, 1 C => 1 D
7 A, 1 D => 1 E
7 A, 1 E => 1 FUEL
"""
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 2,230 | adventofcode | MIT License |
src/Day9/Day9.kt | tomashavlicek | 571,148,715 | false | {"Kotlin": 23780} | package Day9
import readInput
import kotlin.math.abs
import kotlin.math.hypot
import kotlin.math.max
fun main() {
data class Point(var x: Int = 0, var y: Int = 0)
fun part1(input: List<String>): Int {
val size = 800
val visited = Array(size) { BooleanArray(size) }
val head = Point(250,250)
val oldHead = Point()
val tail = Point(250,250)
visited[250][250] = true
input.forEach { line ->
val (direction, steps) = line.split(' ')
repeat(steps.toInt()) {
oldHead.x = head.x
oldHead.y = head.y
when (direction) {
"R" -> {
head.x++
}
"U" -> {
head.y++
}
"L" -> {
head.x--
}
"D" -> {
head.y--
}
}
val ac = abs(tail.x - head.x).toDouble()
val cb = abs(tail.y - head.y).toDouble()
val distance = hypot(ac, cb)
if (distance >= 2) {
tail.x = oldHead.x
tail.y = oldHead.y
visited[tail.y][tail.x] = true
}
}
}
return visited.sumOf { it.count { it } }
}
fun part2(input: List<String>): Int {
val size = 800
val visited = Array(size) { BooleanArray(size) }
val knots = MutableList(10) { Point(400,400) }
visited[400][400] = true
input.forEach { line ->
val (direction, steps) = line.split(' ')
repeat(steps.toInt()) {
when (direction) {
"R" -> {
knots[0].x++
}
"U" -> {
knots[0].y++
}
"L" -> {
knots[0].x--
}
"D" -> {
knots[0].y--
}
}
for (i in 0 until 9) {
val first = knots[i]
val second = knots[i + 1]
val dx = first.x - second.x
val dy = first.y - second.y
if (max(abs(dx), abs(dy)) > 1) {
second.x += dx.coerceIn(-1, 1)
second.y += dy.coerceIn(-1, 1)
}
}
val tail = knots.last()
visited[tail.y][tail.x] = true
}
}
return visited.sumOf { it.count { it } }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day9/Day9_test")
part2(testInput).apply {
println(this)
check(this == 36)
}
val input = readInput("Day9/Day9")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 899d30e241070903fe6ef8c4bf03dbe678310267 | 3,063 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day12.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | import kotlin.streams.toList
fun main() {
class Node(val name: String) {
val neighbors = HashMap<String, Node>()
fun addNeighbor(n: Node) {
this.neighbors[n.name] = n
n.neighbors[this.name] = this
}
fun isBig() = name[0].isUpperCase()
override fun hashCode(): Int {
return name.hashCode()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Node
if (name != other.name) return false
return true
}
override fun toString(): String {
return name
}
}
fun explore(n: Node, visited: HashMap<Node, Int>, maxVisits: Int,twiceVisit: Boolean ): List<MutableList<Node>> {
if (n.name == "end") return listOf(mutableListOf(n))
// for (nei in n.neighbors.values){
// if (visited.contains(nei) && !nei.isBig()) continue
//
// }
visited[n] = if (visited[n] == null) 1 else visited[n]!! + 1
val newTwiceVisit = twiceVisit || (visited[n]!! > 1 && !n.isBig())
return n.neighbors.values
.filter {
if (it.name == "start") return@filter false
visited[it] == null || it.isBig() || (visited[it]!! == 1 && !newTwiceVisit)
}
.flatMap {
explore(it, HashMap(visited), maxVisits, twiceVisit || newTwiceVisit)
}
.map {
it.add(n)
it
}
}
fun part1(input: Node): Int {
return explore(input, HashMap(), 1, false).count()
}
fun part2(input: Node): Int {
val tmp = explore(input, HashMap(), 2, false)
// println(tmp.joinToString { it.reversed().toString() + "\n" })
return tmp.count()
}
fun preprocessing(input: String): Node {
val nodes = HashMap<String, Node>()
val tmp = input.trim().split("\n").map { it.trim().split("-") }
for (l in tmp) {
val from = l[0]
val to = l[1]
if (nodes[from] == null) nodes[from] = Node(from)
if (nodes[to] == null) nodes[to] = Node(to)
nodes[from]!!.addNeighbor(nodes[to]!!)
}
return nodes["start"]!!
}
val realInp = read_testInput("real12")
val testInp = read_testInput("test12")
// val testInp = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
// println("Test 1: ${part1(preprocessing(testInp))}")
// println("Real 1: ${part1(preprocessing(realInp))}")
// println("-----------")
println("Test 2: ${part2(preprocessing(testInp))}")
println("Real 2: ${part2(preprocessing(realInp))}")
}
| 0 | Kotlin | 0 | 0 | 3e33ab078f8f5413fa659ec6c169cd2f99d0b374 | 2,827 | advent_of_code21_kotlin | Apache License 2.0 |
2k23/aoc2k23/src/main/kotlin/04.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d04
import input.read
fun main() {
println("Part 1: ${part1(read("04.txt"))}")
println("Part 2: ${part2(read("04.txt"))}")
}
fun part1(lines: List<String>): Int {
return lines.map(::Game).sumOf { game -> game.play() }
}
fun part2(lines: List<String>): Int {
val games: List<Game> = lines.map(::Game)
games.forEachIndexed { index, game ->
(0..<game.win()).forEach{ n ->
games[index + 1 + n].addCopies(game.getCopies())
}
}
return games.sumOf() { game ->
game.getCopies()
}
}
class Game(line: String) {
private val id: Int
private val winningNumbers: List<Int>
private val myNumbers: List<Int>
private var copies: Int = 1
init {
line.split(":", limit = 2).let { gameParts ->
id = Regex("Card\\s+(\\d+)").find(gameParts.first())!!.let { gameMatch ->
gameMatch.groupValues[1].toInt()
}
gameParts[1].split("|", limit = 2).let { rawNumbers ->
winningNumbers = rawNumbers[0].trim().split(Regex("\\s+")).map { it.toInt() }
myNumbers = rawNumbers[1].trim().split(Regex("\\s+")).map { it.toInt() }
}
}
}
fun play(): Int {
val winning = win()
return if (winning > 0) {
1 shl (winning - 1)
} else {
0
}
}
fun win(): Int {
return winningNumbers.intersect(myNumbers.toSet()).count()
}
fun addCopies(n: Int) {
copies += n
}
fun getCopies(): Int {
return copies
}
override fun toString(): String {
return "Game $id: ${winningNumbers.joinToString(" ")}: ${myNumbers.joinToString(" ")}: $copies"
}
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 1,737 | aoc | The Unlicense |
src/Day03.kt | niltsiar | 572,887,970 | false | {"Kotlin": 16548} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val first = rucksack.substring(0 until rucksack.length / 2)
val second = rucksack.substring(rucksack.length / 2)
val common = first.toSet() intersect second.toSet()
common.single().priority
}
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.sumOf { elves ->
elves.map { it.toSet() }
.reduce { acc, elf ->
acc.toSet() intersect elf.toSet()
}
.single()
.priority
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
val Char.priority: Int
get() = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> error("bad input")
}
| 0 | Kotlin | 0 | 0 | 766b3e168fc481e4039fc41a90de4283133d3dd5 | 1,143 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/hjk/advent22/Day11.kt | h-j-k | 572,485,447 | false | {"Kotlin": 26661, "Racket": 3822} | package com.hjk.advent22
object Day11 {
fun part1(input: List<String>): Long = process(input, 20, 3, false)
fun part2(input: List<String>): Long = process(input, 10_000, 1, true)
private fun process(input: List<String>, times: Int, divisor: Long, lcmMode: Boolean): Long {
val monkeys = input.chunkedByEmptyLine().map(Monkey::parse).associateBy { it.index }
val common = monkeys.values.map(Monkey::divisor).fold(1L, Long::times).let { if (lcmMode) it else it + 1 }
repeat(times) { monkeys.values.forEach { it.process(monkeys, divisor, common) } }
return monkeys.values.map(Monkey::itemsInspected).sortedDescending().take(2).fold(1L, Long::times)
}
private data class Monkey(
val index: Int,
val levels: MutableList<Long>,
val mapper: (Long) -> Long,
val divisor: Long,
val test: (Long) -> Boolean,
val ifTrue: Int,
val ifFalse: Int
) {
private var seen = 0L
fun itemsInspected() = seen
fun process(monkeys: Map<Int, Monkey>, divisor: Long, common: Long) {
seen += levels.size
levels.map { (mapper(it) / divisor) % common }.partition(test).let { (trueNewLevels, falseNewLevels) ->
trueNewLevels.forEach { monkeys.getValue(ifTrue) += it }
falseNewLevels.forEach { monkeys.getValue(ifFalse) += it }
}
levels.clear()
}
operator fun plusAssign(level: Long) {
levels += level
}
companion object {
fun parse(chunk: List<String>): Monkey {
val (index, rest) = chunk[0] to chunk.drop(1)
val (levels, operation, testLogic, ifTrue, ifFalse) = rest
val (divisor, test) = convertTest(testLogic)
return Monkey(
index = indexRegex.matchEntire(index)!!.destructured.let { (i) -> i.toInt() },
levels = levels.substringAfter(": ").split(", ").map(String::toLong).toMutableList(),
mapper = convertOperation(operation),
divisor = divisor,
test = test,
ifTrue = ifTrue.split(" ").last().toInt(),
ifFalse = ifFalse.split(" ").last().toInt()
)
}
fun convertOperation(operation: String): (Long) -> Long =
operationRegex.matchEntire(operation)!!.destructured.let { (operator, arg) ->
when (operator) {
"+" -> arg.toLongOrNull()?.let { operand -> { it + operand } } ?: { it + it }
"-" -> arg.toLongOrNull()?.let { operand -> { it - operand } } ?: { 0 }
"*" -> arg.toLongOrNull()?.let { operand -> { it * operand } } ?: { it * it }
else -> throw RuntimeException()
}
}
fun convertTest(test: String): Pair<Long, (Long) -> Boolean> =
test.split(" ").last().toLong().let { divisor -> divisor to { it % divisor == 0L } }
val indexRegex = "Monkey (\\d+):".toRegex()
val operationRegex = "\\s+Operation: new = old ([*+-]) (\\d+|old)".toRegex()
}
}
}
| 0 | Kotlin | 0 | 0 | 20d94964181b15faf56ff743b8646d02142c9961 | 3,278 | advent22 | Apache License 2.0 |
src/main/kotlin/day03/Solution.kt | kcchoate | 683,597,644 | false | {"Kotlin": 25162} | package day03
class Solution {
fun solve(items: List<String>): Int {
val sums = countArray(items)
val target = items.size / 2
val gammaRate = count(sums) { if (it < target) 0 else 1 }
val epsilonRate = count(sums) { if (it < target) 1 else 0 }
return gammaRate * epsilonRate
}
private fun countArray(items: List<String>): IntArray {
val sums = IntArray(items[0].length)
for (item in items) {
item.split("")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.forEachIndexed { idx, value -> sums[idx] += value }
}
return sums
}
private fun count(sums: IntArray, transform: (Int) -> Int): Int {
val str = sums.map { transform(it) }.joinToString("")
return str.toInt(2)
}
fun getOxygenGeneratorRating(input: List<String>): Int {
return filter(input) { value, moreCommon -> value == moreCommon }
}
fun getCO2ScrubberRating(input: List<String>): Int {
return filter(input) { value, moreCommon -> value != moreCommon }
}
private fun filter(input:List<String>, predicate: (Int, Int) -> Boolean): Int {
val filtered = input.toMutableList();
for(i in 0..<input[0].length) {
val sums = countArray(filtered)
filtered.retainAll { predicate.invoke(it[i].toString().toInt(), moreCommon(sums[i], filtered)) }
if (filtered.size == 1) {
break
}
}
return filtered[0].toInt(2)
}
private fun moreCommon(value: Int, input: List<String>): Int {
val target = input.size / 2.0
return if (value >= target) 1 else 0
}
fun solve2(input: List<String>): Int {
return getCO2ScrubberRating(input) * getOxygenGeneratorRating(input)
}
}
| 0 | Kotlin | 0 | 1 | 3e7c24bc69a4de168ce0bdff855323c803b9a9a8 | 1,862 | advent-of-kotlin | MIT License |
src/year2023/12/Day12.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`12`
import kotlinx.coroutines.runBlocking
import readInput
private const val CURRENT_DAY = "12"
private fun parseLineInto(
line: String
): Pair<String, List<Int>> {
val splitted = line.split(" ")
val resLine = splitted.first()
val ranges = splitted[1].split(",").mapNotNull { it.toIntOrNull() }
return resLine to ranges
}
private fun unfold(
input: Pair<String, List<Int>>
): Pair<String, List<Int>> {
val first = input.first
val ranges = input.second
val newFirst = buildString {
repeat(5) {
append(first)
if (it != 4) {
append("?")
}
}
}
val newRanges = buildList {
repeat(5) {
addAll(ranges)
}
}
return newFirst to newRanges
}
fun main() {
fun part1(input: List<String>): Long {
cache.clear()
val sum = input.map { parseLineInto(it) }
.asSequence()
.map { (line, indexes) ->
solve(
line = line.toList(),
ranges = indexes.map { it.toLong() }
)
}
.sum()
return sum
}
fun part2(input: List<String>): Long {
cache.clear()
val result = runBlocking {
val sum = input
.map { unfold(parseLineInto(it)) }
.mapIndexed { _, pair ->
solve(
line = pair.first.toList(),
ranges = pair.second.map { it.toLong() }
)
}
.sumOf { it }
sum
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 21L)
val part2Test = part2(testInput)
println(part2Test)
check(part2Test == 525152L)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input)
println(part1)
check(part1 == 7221L)
// Part 2
val part2 = part2(input)
println(part2)
check(part2 == 7139671893722L)
}
fun solve(
line: List<Char>,
ranges: List<Long>,
): Long {
if (line.isEmpty()) {
return if (ranges.isEmpty()) 1 else 0
}
return when (line.first()) {
'.' -> solve(line.drop(1), ranges) // ok
'#' -> findForSprinkle(ranges, line)
'?' -> solve(
line = line.drop(1),
ranges = ranges,
) + findForSprinkle(
ranges = ranges,
line = line,
)
else -> error("Illegal State $line")
}
}
val cache = mutableMapOf<Pair<List<Long>, List<Char>>, Long>()
private fun findForSprinkle(
ranges: List<Long>,
line: List<Char>
): Long {
cache[ranges to line]?.let { return it }
// No Ranges
if (ranges.isEmpty()) return 0
val currentRange = ranges[0]
if (line.size < currentRange) return 0
val isThereAnyDotsInRange = line.take(currentRange.toInt()).any { it == '.' }
if (isThereAnyDotsInRange) return 0
// Length of line is same as LAST range
if (line.size == currentRange.toInt()) {
if (ranges.size == 1) return 1
return 0
}
val rangeEndsWithSprinkle = line[currentRange.toInt()] == '#'
if (rangeEndsWithSprinkle) return 0
return solve(
line = line.drop(currentRange.toInt() + 1),
ranges = ranges.drop(1),
).also { cache[ranges to line] = it }
} | 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 3,590 | KotlinAdventOfCode | Apache License 2.0 |
src/day21/b/day21b.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day21.b
import day21.a.Expr
import day21.a.Num
import day21.a.Op
import day21.a.evaluate
import readInputLines
import shouldBe
fun main() {
val root = read()
val r = solveForUnknown(root.a, root.b)
val answer = (evaluate(r) as Num).value
shouldBe(3006709232464L, answer)
}
/**
* Solve f = g for an unknown variable x, where x appears only once
*
* For example,
*
* f = ( 4 + 2 * ( x - 3 ) ) / 4
*
* and
*
* g = ( 32 - 2 ) * 5
*
* would return
*
* ( ( 32 - 2 ) * 5 * 4 - 4 ) / 2 + 3
*
* which is an expression equal to x
*/
fun solveForUnknown(f: Expr, g: Expr): Expr {
fun hasUnknown(f: Expr) = f.any { it is Var }
fun solve(fx: Expr, c: Expr): Expr {
if (fx is Var) return c
fx as Op
return if (hasUnknown(fx.a)) {
when (fx.op) {
"*" -> solve(fx.a, (Op(c, fx.b, "/")))
"+" -> solve(fx.a, (Op(c, fx.b, "-")))
"-" -> solve(fx.a, (Op(c, fx.b, "+")))
"/" -> solve(fx.a, (Op(c, fx.b, "*")))
else -> throw RuntimeException()
}
} else {
when (fx.op) {
"*" -> solve(fx.b, (Op(c, fx.a, "/")))
"+" -> solve(fx.b, (Op(c, fx.a, "-")))
"-" -> solve(fx.b, (Op(fx.a, c, "-")))
"/" -> solve(fx.b, (Op(fx.a, c, "/")))
else -> throw RuntimeException()
}
}
}
val (exprWithUnknown, constExpr) = if (hasUnknown(f)) Pair(f,g) else Pair(g,f)
return solve(exprWithUnknown, constExpr)
}
class Var(val name: String): Expr() {
override fun toString(): String {
return name
}
}
fun read(): Op {
val sym = HashMap<String, Expr>()
val lines = readInputLines(21).filter { it.isNotBlank() }
val set = HashSet(lines)
while (set.isNotEmpty()) {
val it = set.iterator()
while (it.hasNext()) {
val s = it.next()
val r = s.split(":")
val name = r[0]
if (name == "humn") {
sym[name] = Var("x")
it.remove()
} else {
val e = r[1].substring(1)
if (e.matches(Regex("-?[0-9]+"))) {
sym[name] = Num(e.toLong())
it.remove()
} else {
val t = e.split(" ")
val a = sym[t[0]]
val b = sym[t[2]]
val op = if (name == "root") "=" else t[1]
if (a != null && b != null) {
sym[name] = Op(a, b, op)
it.remove()
}
}
}
}
}
return sym["root"] as Op
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 2,752 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | SeanDijk | 575,314,390 | false | {"Kotlin": 29164} | fun main() {
data class Assignment(val start: Int, val end: Int) {
fun size() = end - start
}
fun parseAssignment(assignmentString: String): Assignment {
val (x, y) = assignmentString.split('-')
return Assignment(x.toInt(), y.toInt())
}
fun part1(input: List<String>): Int {
return input.asSequence()
.filter { line ->
val (biggestAssignment, smallestAssignment) = line.split(',')
.map { parseAssignment(it) }
.sortedByDescending { it.size() }
biggestAssignment.start <= smallestAssignment.start && biggestAssignment.end >= smallestAssignment.end
}
.count()
}
fun part2(input: List<String>): Int {
return input.asSequence()
.filter { line ->
val (assignment1, assignment2) = line.split(',').map { parseAssignment(it) }
(assignment1.start <= assignment2.start && assignment1.end >= assignment2.start) ||
(assignment2.start <= assignment1.start && assignment2.end >= assignment1.start)
}
.count()
}
val test = """
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
""".trimIndent().lines()
println(part1(test))
println(part1(readInput("Day04")))
println(part2(test))
println(part2(readInput("Day04")))
}
| 0 | Kotlin | 0 | 0 | 363747c25efb002fe118e362fb0c7fecb02e3708 | 1,450 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | ivancordonm | 572,816,777 | false | {"Kotlin": 36235} | fun main() {
data class StacksInfo(
val lineStacks: Int,
val positions: List<Int>,
val stacks: MutableList<MutableList<Char>>
)
fun parseInput(input: List<String>): StacksInfo {
val tempInfo = input.mapIndexed { index, value -> index to value }
.first { (_, it) -> it.matches(" \\d+(\\s+\\d+)*".toRegex()) }
val stacksInfo = StacksInfo(
tempInfo.first,
tempInfo.second.mapIndexed { index, c -> if (c.isDigit()) index else null }.filterNotNull(),
MutableList(tempInfo.second.last().digitToInt()) { mutableListOf() }
)
input.take(stacksInfo.lineStacks).reversed().map { line ->
stacksInfo.positions.mapIndexed { i, p ->
if (p < line.length && line[p].isLetter()) stacksInfo.stacks[i].add(
line[p]
)
}
}
return stacksInfo
}
fun part1(input: List<String>): String {
val stacksInfo = parseInput(input)
for (line in input.drop(stacksInfo.lineStacks + 2)) {
val (num, from, to) = "(\\d+)".toRegex().findAll(line).map { it.value.toInt() }.toList()
stacksInfo.stacks[to - 1].addAll(stacksInfo.stacks[from - 1].takeLast(num).reversed())
stacksInfo.stacks[from - 1] = stacksInfo.stacks[from - 1].dropLast(num).toMutableList()
}
return buildString {
for (s in stacksInfo.stacks) append(s.last())
}
}
fun part2(input: List<String>): String {
val stacksInfo = parseInput(input)
for (line in input.drop(stacksInfo.lineStacks + 2)) {
val (num, from, to) = "(\\d+)".toRegex().findAll(line).map { it.value.toInt() }.toList()
stacksInfo.stacks[to - 1].addAll(stacksInfo.stacks[from - 1].takeLast(num))
stacksInfo.stacks[from - 1] = stacksInfo.stacks[from - 1].dropLast(num).toMutableList()
}
return buildString {
for (s in stacksInfo.stacks) append(s.last())
}
}
val testInput = readInput("Day05_test")
val input = readInput("Day05")
println(part1(testInput))
check(part1(testInput) == "CMZ")
println(part1(input))
println(part2(testInput))
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | dc9522fd509cb582d46d2d1021e9f0f291b2e6ce | 2,331 | AoC-2022 | Apache License 2.0 |
src/Day05.kt | mvanderblom | 573,009,984 | false | {"Kotlin": 25405} | import java.util.*
data class Move(val amount: Int, val from: Int, val to: Int )
data class GameState(val stacks: List<Stack<String>>, val moves: List<Move>) {
fun getTopLevelCrates() = stacks.joinToString("") { it.last() }
}
fun String.replaceAll(searches: List<String>, replacement: String): String {
var s = this
searches.forEach{ s = s.replace(it, replacement)}
return s
}
fun main() {
val dayName = 5.toDayName()
fun parseLoadingArea(rows: List<String>): List<Stack<String>> {
var parsedRows = rows
.map { it.chunked(4).map { cell -> cell.replaceAll(listOf(" ", "[", "]"), "") } }
.reversed()
val stacks = (0 until parsedRows.first().size).map { Stack<String>() }
parsedRows.subList(1, parsedRows.size)
.forEach { row -> row
.forEachIndexed{ i, it -> if(it.isNotEmpty()) stacks[i].push(it) }}
return stacks
}
fun parseMoves(moves: List<String>): List<Move> {
return moves
.map { it.replaceAll(listOf("move ", "from ", "to "), "") }
.map { it.split(" ").map { it.toInt() } }
.map { (amount, from, to) -> Move(amount, from, to) }
}
fun parseGameState(input: List<String>): GameState {
val splitPoint = input.indexOfFirst { it.isEmpty() }
val stacks = parseLoadingArea(input.subList(0, splitPoint))
val moves = parseMoves(input.subList(splitPoint + 1, input.size))
return GameState(stacks, moves)
}
fun lafoStrategy(move: Move, state: GameState): Unit {
(0 until move.amount).forEach { _ ->
state.stacks[move.to - 1].push(state.stacks[move.from - 1].pop())
}
}
fun fifoStrategy(move: Move, state: GameState): Unit {
val x = mutableListOf<String>()
(0 until move.amount).forEach { _ ->
x.add(state.stacks[move.from - 1].pop())
}
x.reversed().forEach {
state.stacks[move.to - 1].push(it)
}
}
fun part1(input: List<String>, strategy: (Move, GameState) -> Unit): String {
val state = parseGameState(input)
state.moves.forEach { move -> strategy(move, state)}
return state.getTopLevelCrates()
}
val testInput = readInput("${dayName}_test")
val input = readInput(dayName)
// Part 1
val testOutputPart1 = part1(testInput, ::lafoStrategy)
testOutputPart1 isEqualTo "CMZ"
val outputPart1 = part1(input, ::lafoStrategy)
outputPart1 isEqualTo "MQTPGLLDN"
// Part 2
val testOutputPart2 = part1(testInput, ::fifoStrategy)
testOutputPart2 isEqualTo "MCD"
val outputPart2 = part1(input, ::fifoStrategy)
outputPart2 isEqualTo "LVZPSTTCZ"
}
| 0 | Kotlin | 0 | 0 | ba36f31112ba3b49a45e080dfd6d1d0a2e2cd690 | 2,770 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/de/nosswald/aoc/days/Day05.kt | 7rebux | 722,943,964 | false | {"Kotlin": 34890} | package de.nosswald.aoc.days
import de.nosswald.aoc.Day
// https://adventofcode.com/2023/day/5
object Day05 : Day<Long>(5, "If You Give A Seed A Fertilizer") {
data class RangeEntry(val destinationStart: Long, val sourceStart: Long, val length: Long) {
val sourceRange get(): LongRange {
return sourceStart until sourceStart + length
}
fun destinationForSource(source: Long): Long {
return destinationStart + (source - sourceStart)
}
}
data class ConversionMap(val entries: List<RangeEntry>)
private fun parseInput(input: List<String>): Pair<List<Long>, List<ConversionMap>> {
val seeds = input
.first()
.removePrefix("seeds: ")
.split(" ")
.map(String::toLong)
val maps = input
.drop(2)
.joinToString("\n")
.split("\n\n")
.map { block ->
block
.split("\n")
.drop(1)
.map { line ->
line
.split(" ")
.map(String::toLong)
}
.map {
RangeEntry(it[0], it[1], it[2])
}
}
.map {
ConversionMap(it)
}
return Pair(seeds, maps)
}
override fun partOne(input: List<String>): Long {
val (seeds, maps) = parseInput(input)
return maps.fold(seeds) { acc, map ->
acc.map { source ->
map.entries.find { source in it.sourceRange }?.destinationForSource(source) ?: source
}
}.min()
}
override fun partTwo(input: List<String>): Long {
val (seeds, maps) = parseInput(input)
val seedRanges = seeds
.windowed(2, 2)
.map { it[0] .. it[0] + it[1] }
val reversedMaps = maps.map {
ConversionMap(it.entries.map { old ->
RangeEntry(old.sourceStart, old.destinationStart, old.length)
})
}.reversed()
return generateSequence(0, Long::inc).first { location ->
val seed = reversedMaps.fold(location) { acc, map ->
map.entries.find { acc in it.sourceRange }?.destinationForSource(acc) ?: acc
}
seedRanges.any { seedRange -> seed in seedRange }
}
}
private val exampleInput = """
seeds: 79 14 55 13
seed-to-soil map:
50 98 2
52 50 48
soil-to-fertilizer map:
0 15 37
37 52 2
39 0 15
fertilizer-to-water map:
49 53 8
0 11 42
42 0 7
57 7 4
water-to-light map:
88 18 7
18 25 70
light-to-temperature map:
45 77 23
81 45 19
68 64 13
temperature-to-humidity map:
0 69 1
1 0 69
humidity-to-location map:
60 56 37
56 93 4
""".trimIndent().split("\n").toList()
override val partOneTestExamples: Map<List<String>, Long> = mapOf(
exampleInput to 35
)
override val partTwoTestExamples: Map<List<String>, Long> = mapOf(
exampleInput to 46
)
}
| 0 | Kotlin | 0 | 1 | 398fb9873cceecb2496c79c7adf792bb41ea85d7 | 3,294 | advent-of-code-2023 | MIT License |
src/Day15.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | import kotlin.math.abs
fun Coordinates.distance(to: Coordinates): Int =
abs(x - to.x) + abs(y - to.y)
data class Sensor(
val sensorCoordinates: Coordinates,
val beaconCoordinates: Coordinates,
) {
val distance: Int
get() = sensorCoordinates.distance(beaconCoordinates)
fun withinRange(coordinates: Coordinates): Boolean =
sensorCoordinates.distance(coordinates) <= distance
}
fun main() {
fun MatchResult.toCoordinates(): Coordinates {
val coords = value.split(",")
return Coordinates(
x = coords.first().split("=").last().trim().toInt(),
y = coords.last().split("=").last().trim().toInt(),
)
}
fun parse(input: List<String>): List<Sensor> =
input.map { line ->
val regex = "x=-?\\d+, y=-?\\d+".toRegex()
val matches = regex.findAll(line)
Sensor(
sensorCoordinates = matches.first().toCoordinates(),
beaconCoordinates = matches.last().toCoordinates(),
)
}
fun rowCoverage(
sensor: Sensor,
x: Int,
y: Int,
distance: Int
): Coordinates? {
val relativeDistance = abs(sensor.sensorCoordinates.x - x) + abs(sensor.sensorCoordinates.y - y)
return if (relativeDistance <= distance && Coordinates(x, y) != sensor.beaconCoordinates) {
Coordinates(x = x, y = y)
} else null
}
fun buildInnerCoverage(
coverage: MutableSet<Coordinates>,
sensor: Sensor,
inspectedY: Int? = null
) {
val distance = sensor.distance
val sensorCoordinates = sensor.sensorCoordinates
(sensorCoordinates.x - distance..sensorCoordinates.x + distance).forEach { x ->
if (inspectedY != null) {
rowCoverage(sensor, x, inspectedY, distance)?.let { coverage += it }
} else {
(sensorCoordinates.y - distance..sensorCoordinates.y + distance).forEach { y ->
rowCoverage(sensor, x, y, distance)?.let { coverage += it }
}
}
}
}
fun buildOuterCoverage(
sensor: Sensor,
): List<Coordinates> {
val coverage = mutableListOf<Coordinates>()
val sensorCoordinates = sensor.sensorCoordinates
val distance = sensor.distance + 1
(-distance..distance).forEach { x ->
coverage += Coordinates(sensorCoordinates.x + x, sensorCoordinates.y + x + distance)
}
return coverage
}
fun part1(input: List<String>, y: Int): Int {
val sensors = parse(input)
val totalCoverage = mutableSetOf<Coordinates>()
sensors
.forEach { sensor ->
buildInnerCoverage(totalCoverage, sensor, y)
}
return totalCoverage.count { it.y == y }
}
fun part2(input: List<String>, x: Int): Long {
val sensors = parse(input)
val totalRange = (0..x)
return sensors
.firstNotNullOf { sensor ->
buildOuterCoverage(sensor)
.filter { it.x in totalRange && it.y in totalRange }
.firstOrNull { outerCoordinate -> sensors.none { sensor -> sensor.withinRange(outerCoordinate) } }
}
.let { it.x * 4000000L + it.y }
}
check(part1(readInput("Day15_test"), 10) == 26)
check(part2(readInput("Day15_test"), 20) == 56000011L)
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 4000000))
} | 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 3,574 | AdventOfCode2022 | Apache License 2.0 |
src/Day04.kt | bendh | 573,833,833 | false | {"Kotlin": 11618} | fun main() {
fun String.toIntRange(): IntRange {
val rangeRegex = Regex(pattern = """^\d+-\d+$""")
return if (rangeRegex.matches(this)) {
val values = this.split("-").map { it.toInt() }
values[0]..values[1]
} else {
0..0
}
}
fun hasCompleteOverlap(group1: String, group2: String): Boolean {
val range1 = group1.toIntRange()
val range2 = group2.toIntRange()
val intersection = range1.intersect(range2).sorted()
return intersection.size == range1.count() || intersection.size == range2.count()
}
fun hasOverlap(group1: String, group2: String): Boolean {
val range1 = group1.toIntRange()
val range2 = group2.toIntRange()
val intersection = range1.intersect(range2).sorted()
return intersection.isNotEmpty()
}
fun part1(input: List<String>): Int {
return input.map {
val groups = it.split(",")
hasCompleteOverlap(groups[0], groups[1])
}.count { it }
}
fun part2(input: List<String>): Int {
return input.map {
val groups = it.split(",")
hasOverlap(groups[0], groups[1])
}.count { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day04_test")
check(part2(testInput) == 4)
//
val input = readLines("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e3ef574441b63a99a99a095086a0bf025b8fc475 | 1,488 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2023/Day09.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2023
import readInput
private class History(private val initialSequence: List<Int>) {
companion object {
fun fromString(line: String) = History(line.split(" ").map { char -> char.toInt() })
}
fun getNextValue(): Int {
var currentSequence = initialSequence
val lastValues = mutableListOf(currentSequence.last())
while (currentSequence.sum() != 0) {
currentSequence = getNextSequence(currentSequence)
lastValues.add(currentSequence.last())
}
var currentPrediction = 0
for (i in lastValues.size - 1 downTo 0) {
currentPrediction += lastValues[i]
}
return currentPrediction
}
fun getPreviousValue(): Int {
var currentSequence = initialSequence
val firstValues = mutableListOf(currentSequence.first())
while (currentSequence.sum() != 0) {
currentSequence = getNextSequence(currentSequence)
firstValues.add(currentSequence.first())
}
var currentPrediction = 0
for (i in firstValues.size - 1 downTo 0) {
currentPrediction = firstValues[i] - currentPrediction
}
return currentPrediction
}
private fun getNextSequence(input: List<Int>) = input.windowed(size = 2, step = 1) { it.last() - it.first() }
}
object Day09 {
fun part1(input: List<String>) = input.map { History.fromString(it) }.sumOf { it.getNextValue() }
fun part2(input: List<String>) = input.map { History.fromString(it) }.sumOf { it.getPreviousValue() }
}
fun main() {
val testInput = readInput("Day09_test", 2023)
check(Day09.part1(testInput) == 114)
check(Day09.part2(testInput) == 2)
val input = readInput("Day09", 2023)
println(Day09.part1(input))
println(Day09.part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 1,831 | adventOfCode | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2023/Day03.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2023
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
open class Part3A : PartSolution() {
internal lateinit var symbols: List<Symbol>
internal lateinit var numbers: List<Number>
override fun parseInput(text: String) {
val numbers = mutableListOf<Number>()
val symbols = mutableListOf<Symbol>()
for ((y, line) in text.split("\n").withIndex()) {
var value = ""
for ((x, c) in line.withIndex()) {
if (!c.isDigit() && value.isNotEmpty()) {
numbers.add(Number(value.toInt(), x - value.length, y))
value = ""
} else if (c.isDigit()) {
value += c
}
if (c != '.' && !c.isDigit()) {
symbols.add(Symbol(c, x, y))
}
}
if (value.isNotEmpty()) {
numbers.add(Number(value.toInt(), line.length - value.length, y))
}
}
this.numbers = numbers
this.symbols = symbols
}
override fun getExampleAnswer() = 4361
override fun compute(): Int {
return numbers.filter { num -> symbols.any { num.isAdjacent(it) } }.sumOf { it.value }
}
internal data class Symbol(val value: Char, val x: Int, val y: Int)
internal data class Number(val value: Int, val x: Int, val y: Int) {
fun isAdjacent(pos: Symbol): Boolean {
if (pos.y < y - 1 || pos.y > y + 1) {
return false
}
if (pos.x < x - 1 || pos.x > x + value.toString().length) {
return false
}
return true
}
}
}
class Part3B : Part3A() {
override fun getExampleAnswer() = 467835
override fun compute(): Int {
return symbols.filter { it.value == '*' }.map {
val products = numbers.filter { num -> num.isAdjacent(it) }.map { it.value }
return@map if (products.size == 2) {
products.fold(1) { acc, i -> acc * i }
} else {
0
}
}.sum()
}
}
fun main() {
Day(2023, 3, Part3A(), Part3B())
}
| 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 2,227 | advent-of-code-kotlin | MIT License |
aoc-2023/src/main/kotlin/aoc/aoc2.kts | triathematician | 576,590,518 | false | {"Kotlin": 615974} | import aoc.AocParser.Companion.parselines
import aoc.*
import aoc.util.getDayInput
val day = 2
val testInput = """
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
""".parselines
class GameResult(var red: Int, var green: Int, var blue: Int)
val input = getDayInput(day, 2023)
fun List<String>.parseInput() = associate {
val (game, colors) = it.split(": ")
val gameNum = game.chunkint(1)
val colorBins = colors.splitOn(";") {
val res = GameResult(0, 0, 0)
it.split(",").map {
val (n, col) = it.trim().split(" ")
when (col) {
"red" -> res.red += n.toInt()
"green" -> res.green += n.toInt()
"blue" -> res.blue += n.toInt()
}
}
res
}
gameNum to colorBins
}
// test case
val testResult = testInput.part1()
val testResult2 = testInput.part2()
// part 1
fun List<String>.part1() = parseInput().filter {
it.value.all {
it.red <= 12 && it.green <= 13 && it.blue <= 14
}
}.keys.sum()
val answer1 = input.part1().also { it.print }
// part 2
fun List<String>.part2() = parseInput().map {
(it.value.maxOf { it.red }) *
(it.value.maxOf { it.green }) *
(it.value.maxOf { it.blue })
}.sum()
val answer2 = input.part2().also { it.print }
// print results
AocRunner(day,
test = { "$testResult, $testResult2" },
part1 = { answer1 },
part2 = { answer2 }
).run()
| 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 1,705 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day07/day07.kt | andrew-suprun | 725,670,189 | false | {"Kotlin": 18354, "Python": 17857, "Dart": 8224} | package day07
import java.io.File
data class Bid(val hand: String, val bet: Int)
fun main() {
run(encode1, ::part1)
run(encode2, ::part2)
}
fun run(encode: Map<Char, Char>, rank: (String) -> Char) {
val result = File("input.data").readLines().map { parseHand(it, encode, rank) }.sortedBy { it.hand }.withIndex()
.sumOf { (idx, card) -> (idx + 1) * card.bet }
println(result)
}
fun parseHand(line: String, encode: Map<Char, Char>, type: (String) -> Char): Bid {
val (handStr, bet) = line.split(" ")
val hand = handStr.map { encode[it] }.joinToString(separator = "")
return Bid(hand = type(handStr) + hand, bet = bet.toInt())
}
fun part1(hand: String): Char {
val sizes = hand.map { it }.groupBy { it }.map { it.value.size }.sortedBy { -it }
return type(sizes)
}
fun part2(hand: String): Char {
val g = hand.map { it }.groupBy { it }.map { it.value }.toList().sortedBy { -it.size }.toList()
var bestRank = g[0][0]
if (bestRank == 'J' && g.size > 1) {
bestRank = g[1][0]
}
val sizes =
hand.replace('J', bestRank).map { it }.groupBy { it }.map { it.value.size }.sortedBy { -it }
.toList()
return type(sizes)
}
fun type(sizes: List<Int>): Char = when (sizes[0]) {
1 -> 'a' // high card
2 -> when (sizes[1]) {
1 -> 'b' // pair
else -> 'c' // two pair
}
3 -> when (sizes[1]) {
1 -> 'd' // three of a kind
else -> 'e' // full house
}
4 -> 'f' // four of a kind
5 -> 'g' // 5 aces?
else -> 'x'
}
// encode rank to sortable code
val encode1 = mapOf(
'2' to 'b',
'3' to 'c',
'4' to 'd',
'5' to 'e',
'6' to 'f',
'7' to 'g',
'8' to 'h',
'9' to 'i',
'T' to 'j',
'J' to 'k',
'Q' to 'l',
'K' to 'm',
'A' to 'n',
)
// encode rank to sortable code
val encode2 = mapOf(
'J' to 'a',
'2' to 'b',
'3' to 'c',
'4' to 'd',
'5' to 'e',
'6' to 'f',
'7' to 'g',
'8' to 'h',
'9' to 'i',
'T' to 'j',
'Q' to 'l',
'K' to 'm',
'A' to 'n',
)
//251927063
//255632664 | 0 | Kotlin | 0 | 0 | dd5f53e74e59ab0cab71ce7c53975695518cdbde | 2,137 | AoC-2023 | The Unlicense |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem032.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
import dev.mikeburgess.euler.sequences.permutationsOf
/**
* Problem 32
*
* We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n
* exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
*
* The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand,
* multiplier, and product is 1 through 9 pandigital.
*
* Find the sum of all products whose multiplicand/multiplier/product identity can be written as a
* 1 through 9 pandigital.
*
* HINT: Some products can be obtained in more than one way so be sure to only include it once in
* your sum.
*/
class Problem032 : Problem {
private fun List<Int>.toInt() =
reduce { a, b -> a * 10 + b }
private fun candidateProducts(digits: List<Int>): Pair<Int, Int> {
val candidate1 = digits[0] * digits.subList(1, 5).toInt()
val candidate2 = digits.subList(0, 2).toInt() * digits.subList(2, 5).toInt()
return candidate1 to candidate2
}
private operator fun <T> Pair<T, T>.contains(other: T) =
first == other || second == other
override fun solve(): Long =
permutationsOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
.map { it.subList(0, 4).toInt() to candidateProducts(it.subList(4, 9)) }
.filter { (product, candidates) -> product in candidates }
.map { it.first }
.distinct()
.sum().toLong()
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 1,491 | project-euler | MIT License |
src/Day11.kt | punx120 | 573,421,386 | false | {"Kotlin": 30825} | import java.util.*
fun main() {
val opRegex = "Operation: new = old ([+*]) ([a-z|0-9]+)".toRegex()
class Monkey(val op: (ULong) -> ULong, val div: ULong, val test: (Boolean) -> Int) {
var gcd = 1u.toULong()
var count = 0L
val items: LinkedList<ULong> = LinkedList<ULong>()
fun processItems(monkeys: Map<Int, Monkey>, divideBy3: Boolean) {
for (item in items) {
++count
var value = op.invoke(item)
if (divideBy3) {
value /= 3u
} else {
value %= gcd
}
monkeys[test.invoke(value % div == 0u.toULong())]!!.items.add(value)
}
items.clear()
}
}
fun parseOperation(line: String): (ULong) -> ULong {
val match = opRegex.find(line)
val (op, nb) = match!!.destructured
return if (nb == "old") {
if (op == "+") { i: ULong -> i + i } else { i: ULong -> i * i }
} else {
val n = nb.toULong()
if (op == "+") { i: ULong -> i + n } else { i: ULong -> i * n }
}
}
fun buildMonkeys(input: List<String>) : Map<Int, Monkey> {
val monkeys = mutableMapOf<Int, Monkey>()
val monkeyIdxRegex = "Monkey (\\d+):".toRegex()
for (i in input.indices) {
val find = monkeyIdxRegex.matchEntire(input[i])
if (find != null) {
val idx = find.groupValues[1].toInt()
val elements = input[i + 1].split(':')[1].trim().split(',')
val operation = parseOperation(input[i + 2])
val div = input[i + 3].replace("Test: divisible by ", "").trim().toULong()
val trueMonkey = input[i + 4].replace("If true: throw to monkey ", "").trim().toInt()
val falseMonkey = input[i + 5].replace("If false: throw to monkey ", "").trim().toInt()
val monkey = Monkey(operation, div) { b -> if (b) trueMonkey else falseMonkey }
monkey.items.addAll(elements.map { it.trim().toULong() })
monkeys[idx] = monkey
}
}
return monkeys
}
fun part1(monkeys: Map<Int, Monkey>, round: Int, divideBy3: Boolean): Long {
var mut = 1u.toULong()
monkeys.values.map { mut *= it.div }
monkeys.values.forEach{ it.gcd = mut}
for (r in 1..round) {
for (i in 0 until monkeys.size) {
monkeys[i]!!.processItems(monkeys, divideBy3)
}
}
val sorted = monkeys.values.map { it.count }.sortedDescending()
return sorted[0] * sorted[1]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
println(part1(buildMonkeys(testInput), 20, true))
println(part1(buildMonkeys(testInput), 10000, false))
val input = readInput("Day11")
println(part1(buildMonkeys(input), 20, true))
println(part1(buildMonkeys(input), 10000, false))
}
| 0 | Kotlin | 0 | 0 | eda0e2d6455dd8daa58ffc7292fc41d7411e1693 | 3,064 | aoc-2022 | Apache License 2.0 |
2015/src/main/kotlin/day15.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parse
import utils.Parser
import utils.Solution
import utils.Vec4i
import utils.mapItems
fun main() {
Day15.run(skipTest = false)
}
object Day15 : Solution<List<Day15.Item>>() {
override val name = "day15"
override val parser = Parser.lines.mapItems { parseItem(it) }
const val TARGET_AMOUNT = 100
@Parse("{kind}: capacity {capacity}, durability {durability}, flavor {flavor}, texture {texture}, calories {calories}")
data class Item(
val kind: Kind,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int,
) {
val ingredients = Vec4i(capacity, durability, flavor, texture)
}
enum class Kind {
Frosting, Candy, Butterscotch, Sugar, Cinnamon;
}
private fun score(items: List<Item>, amounts: List<Int>): Int {
val components = items.zip(amounts).map { (item, amount) -> item.ingredients * amount }
.reduce { a, b -> a + b }
.coerceAtLeast(Vec4i(0, 0, 0, 0))
return components.w * components.x * components.y * components.z
}
private fun pickIngredients(remaining: Int, number: Int): List<List<Int>> {
if (remaining == 0) {
return listOf(List(number) { 0 })
}
return (0 .. remaining).flatMap { a ->
if (number == 1) {
listOf(listOf(a))
} else {
pickIngredients(remaining - a, number - 1).map { listOf(a) + it }
}
}
}
override fun part1(input: List<Item>): Int {
val variants = pickIngredients(TARGET_AMOUNT, input.size)
return variants.maxOf { score(input, it) }
}
override fun part2(input: List<Item>): Any? {
val variants = pickIngredients(TARGET_AMOUNT, input.size)
return variants.filter {
input.zip(it).sumOf { (item, amount) -> item.calories * amount } == 500
}.maxOf { score(input, it) }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,826 | aoc_kotlin | MIT License |
src/Day13.kt | jordan-thirus | 573,476,470 | false | {"Kotlin": 41711} | import kotlinx.serialization.json.*
fun main() {
fun compare(left: JsonElement, right: JsonElement): Int {
val isLeftInt = left is JsonPrimitive
val isRightInt = right is JsonPrimitive
if(isLeftInt && isRightInt){
return left.jsonPrimitive.int.compareTo(right.jsonPrimitive.int)
} else if( !isLeftInt && !isRightInt ){
for(i in left.jsonArray.indices){
if(i !in right.jsonArray.indices){
return 1
}
else {
val result = compare(left.jsonArray[i], right.jsonArray[i])
if(result != 0) return result
}
}
if(left.jsonArray.size == right.jsonArray.size){
return 0
}
return -1
} else if (isRightInt){
return compare(left.jsonArray, buildJsonArray { add(right) })
}
else {
return compare(buildJsonArray { add(left) }, right.jsonArray)
}
}
fun part1(input: List<String>): Int {
return input.chunked(3)
.mapIndexed{ index, strings -> Holder(index+1, Json.parseToJsonElement(strings[0]), Json.parseToJsonElement(strings[1])) }
.filter { compare(it.left, it.right) == -1}
.sumOf { it.index }
}
fun part2(input: List<String>): Int {
val decoderKeys = setOf(Json.parseToJsonElement("[[2]]"), Json.parseToJsonElement("[[6]]"))
return input.filter { it != "" }
.map { Json.parseToJsonElement(it) }
.plus(decoderKeys)
.sortedWith { left, right -> compare(left, right) }
.let { (it.indexOf(decoderKeys.first()) + 1) * (it.indexOf(decoderKeys.last()) + 1) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
data class Holder(val index: Int, val left: JsonElement, val right: JsonElement)
| 0 | Kotlin | 0 | 0 | 59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e | 2,138 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/nl/dirkgroot/adventofcode/year2021/Day19.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2021
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
import kotlin.math.abs
class Day19(input: Input) : Puzzle() {
val scanners by lazy {
input.string().split("\n\n".toRegex())
.map { scanner ->
Scanner(
"(-?\\d+),(-?\\d+),(-?\\d+)".toRegex()
.findAll(scanner)
.map { beaconMatch ->
Point3D(beaconMatch.groupValues[1].toInt(), beaconMatch.groupValues[2].toInt(), beaconMatch.groupValues[3].toInt())
}
.toList()
)
}
}
data class Point3D(var x: Int, var y: Int, var z: Int) {
fun getRotations() = listOf(
Point3D(x, y, z), Point3D(x, z, -y), Point3D(x, -z, y), Point3D(x, -y, -z),
Point3D(y, z, x), Point3D(y, x, -z), Point3D(y, -x, z), Point3D(y, -z, -x),
Point3D(z, x, y), Point3D(z, y, -x), Point3D(z, -y, x), Point3D(z, -x, -y),
Point3D(-x, -z, -y), Point3D(-x, -y, z), Point3D(-x, y, -z), Point3D(-x, z, y),
Point3D(-y, -x, -z), Point3D(-y, -z, x), Point3D(-y, z, -x), Point3D(-y, x, z),
Point3D(-z, -y, -x), Point3D(-z, -x, y), Point3D(-z, x, -y), Point3D(-z, y, x),
)
operator fun minus(other: Point3D): Point3D {
return Point3D(x - other.x, y - other.y, z - other.z)
}
operator fun plus(other: Point3D): Point3D {
return Point3D(x + other.x, y + other.y, z + other.z)
}
override fun toString() = "($x, $y, $z)"
}
data class Scanner(val beacons: List<Point3D>, val permutationOf: Scanner? = null, val offset: Point3D = Point3D(0, 0, 0)) {
private val permutations by lazy {
beacons.map { it.getRotations() }
.let { beaconPermutations ->
(0..23).asSequence()
.map { index -> Scanner(beaconPermutations.map { it[index] }) }
}
}
fun findOverlappingPermutation(other: Scanner): Scanner? {
return permutations
.map { permutation ->
permutation.findOverlapOffset(other)?.let { offset ->
val beacons = permutation.beacons.map { it + offset }
Scanner(beacons, this, offset)
}
}
.filterNotNull()
.firstOrNull()
}
private fun findOverlapOffset(other: Scanner): Point3D? {
val myBeaconOffsets = beacons.associateWith { source ->
beacons.map { destination -> destination - source }.toSet()
}
val otherBeaconOffsets = other.beacons.associateWith { source ->
other.beacons.map { destination -> destination - source }.toSet()
}
return myBeaconOffsets.mapNotNull { (beacon, offsets) ->
otherBeaconOffsets.asSequence().filter { (_, otherOffsets) ->
(offsets intersect otherOffsets).size >= 12
}.firstOrNull()?.let { (otherBeacon, _) ->
beacon to otherBeacon
}
}.firstOrNull()?.let { (first, second) ->
second - first
}
}
}
override fun part1(): Int =
adjustedScanners().flatMap { it.beacons }.distinct().size
override fun part2(): Int =
adjustedScanners().map { it.offset }.let { offsets ->
offsets.flatMap { source ->
offsets.map { destination ->
abs(destination.x - source.x) + abs(destination.y - source.y) + abs(destination.z - source.z)
}
}.maxOrNull()!!
}
private fun adjustedScanners(): List<Scanner> {
val todo = scanners.toMutableList()
val adjustedScanners = mutableListOf(todo.removeFirst())
while (todo.isNotEmpty()) {
val overlaps = todo.mapNotNull { scannerInProgress ->
adjustedScanners.asSequence()
.mapNotNull { matchCandidate -> scannerInProgress.findOverlappingPermutation(matchCandidate) }
.firstOrNull()
}
adjustedScanners.addAll(overlaps)
overlaps.forEach { todo.remove(it.permutationOf) }
}
return adjustedScanners
}
}
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 4,488 | adventofcode-kotlin | MIT License |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day12/Day12.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day12
import nl.sanderp.aoc.common.measureDuration
import nl.sanderp.aoc.common.prettyPrint
import nl.sanderp.aoc.common.readResource
fun main() {
val input = readResource("Day12.txt").lines().map { parse(it) }
val (answer1, duration1) = measureDuration<Int> { partOne(input) }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
val (answer2, duration2) = measureDuration<Int> { partTwo(input) }
println("Part two: $answer2 (took ${duration2.prettyPrint()})")
}
private fun parse(line: String): Pair<String, String> {
val (from, to) = line.split('-')
return from to to
}
private fun List<Pair<String, String>>.traverse(
path: List<String>,
isNextCaveValid: (id: String, path: List<String>) -> Boolean
): Set<List<String>> {
val cave = path.last()
return if (cave == "end") setOf(path) else getNextCaves(cave)
.filter { isNextCaveValid(it, path) }
.flatMap { traverse(path + it, isNextCaveValid) }
.toSet()
}
private fun partOne(connections: List<Pair<String, String>>): Int {
val paths = connections.traverse(listOf("start")) { cave, path ->
cave.isLarge || !path.contains(cave)
}
return paths.size
}
private fun partTwo(connections: List<Pair<String, String>>): Int {
val paths = connections.traverse(listOf("start")) { cave, path ->
cave.isLarge || !path.contains(cave) || path.containsNoSmallCaveTwice
}
return paths.size
}
private val List<String>.containsNoSmallCaveTwice get() =
groupingBy { it }.eachCount().filter { it.key.isSmall }.all { it.value <= 1 }
private fun List<Pair<String, String>>.getNextCaves(id: String) =
(filter { it.first == id }.map { it.second } + filter { it.second == id }.map { it.first }).filter { it != "start" }
private val String.isLarge get() = this == this.uppercase()
private val String.isSmall get() = this == this.lowercase() | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,939 | advent-of-code | MIT License |
src/Day03.kt | devheitt | 487,361,256 | false | {"Kotlin": 5549} | fun main() {
fun part1(input: List<String>): Int {
val mostCommon = input[0].map { 0 }.toMutableList()
val lessCommon = input[0].map { 0 }.toMutableList()
input.forEach { line ->
for (i in line.indices) {
if (line[i] == '0')
mostCommon[i]--
else
mostCommon[i]++
}
}
for (i in mostCommon.indices) {
if (mostCommon[i] > 0) {
mostCommon[i] = 1
lessCommon[i] = 0
} else {
mostCommon[i] = 0
lessCommon[i] = 1
}
}
val gammaBinary = mostCommon.joinToString("")
val epsilonBinary = lessCommon.joinToString("")
return gammaBinary.getIntFromBinary() * epsilonBinary.getIntFromBinary()
}
fun part2(input: List<String>): Int {
val oxygenRating = getOxygenRating(input)
println("oxygen rating: $oxygenRating")
val CO2Rating = getCO2Rating(input)
println("CO2 rating: $CO2Rating")
return oxygenRating * CO2Rating
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day03_test")
// check(part1(testInput) == 198)
// check(part2(testInput) == 230)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
/**
* keep the inputs with the most common value in the current bit position
*/
fun getOxygenRating(input: List<String>): Int {
var currentBit = 0
val valueLength = input[0].length
var oxygenList = input
while (currentBit < valueLength && oxygenList.size > 1) {
val oneOccurrences = oxygenList.count { binary -> binary[currentBit] == '1' }
val zeroOccurrences = oxygenList.count { binary -> binary[currentBit] == '0' }
val mostCommonValue = if (oneOccurrences - zeroOccurrences >= 0) '1' else '0'
oxygenList = oxygenList.filter { value -> value[currentBit] == mostCommonValue }
currentBit++
}
return oxygenList[0].getIntFromBinary()
}
/**
* keep the inputs with the less common value in the current bit position
*/
fun getCO2Rating(input: List<String>): Int {
var currentBit = 0
val valueLength = input[0].length
var CO2List = input
while (currentBit < valueLength && CO2List.size > 1) {
val oneOccurrences = CO2List.count { binary -> binary[currentBit] == '1' }
val zeroOccurrences = CO2List.count { binary -> binary[currentBit] == '0' }
val lessCommonValue = if (zeroOccurrences - oneOccurrences <= 0) '0' else '1'
CO2List = CO2List.filter { value -> value[currentBit] == lessCommonValue }
currentBit++
}
return CO2List[0].getIntFromBinary()
}
| 0 | Kotlin | 0 | 0 | cd79f4b6ac78b06cfb9b5ee381ae7427895a68c0 | 2,794 | kotlin-aoc-2021 | Apache License 2.0 |
leetcode/src/daily/hard/Q801.kt | zhangweizhe | 387,808,774 | false | null | package daily.hard
import kotlin.math.min
fun main() {
// 801. 使序列递增的最小交换次数
// https://leetcode.cn/problems/minimum-swaps-to-make-sequences-increasing/
println(minSwap(intArrayOf(1,3,5,4), intArrayOf(1,2,3,7)))
}
fun minSwap(nums1: IntArray, nums2: IntArray): Int {
/**
* 1.状态定义
* noSwapDp[],noSwapDp[i],表示 [0,i] 的元素,nums1 和 nums2 均已成为递增数组,且第 i 个元素没有交换的最小次数
* swapDp[],swapDp[i],表示 [0,i] 的元素,nums1 和 nums2 均已成为递增数组,且第 i 个元素有交换的最小次数
* 2.状态转移方程
* ...nums1[i-1] nums1[i]...
* ...nums2[i-1] nums2[i]...
* 2.1 if (nums1[i-1] < nums1[i] && nums2[i-1] < nums2[i]) 无需操作
* 2.2 if (nums2[i-1] < nums1[i] && nums1[i-1] < nums2[i]) 必须操作
* 2.3 同时满足 2.1、2.2,可以选择 操作 或者 不操作
* 3.初始值
* noSwapDp[0] = 0, swapDp[0] = 1
*/
val n = nums1.size
val noSwapDp = IntArray(n)
val swapDp = IntArray(n)
noSwapDp[0] = 0
swapDp[0] = 1
for (i in 1 until n) {
val a1 = nums1[i-1]
val a2 = nums1[i]
val b1 = nums2[i-1]
val b2 = nums2[i]
if ((a1 < a2 && b1 < b2) && (a1 < b2 && b1 < a2)) {
// 2.3 同时满足 2.1、2.2,可以选择 操作 或者 不操作
// 至于要不要操作,看 noSwapDp[i-1] 和 swapDp[i-1] 哪个更小
val min = min(noSwapDp[i-1], swapDp[i-1])
noSwapDp[i] = min
swapDp[i] = min + 1
}else if (a1 < a2 && b1 < b2) {
// 2.1 if (nums1[i-1] < nums1[i] && nums2[i-1] < nums2[i]) 无需操作
noSwapDp[i] = noSwapDp[i-1]
swapDp[i] = swapDp[i-1] + 1
}else {
// 2.2 if (nums2[i-1] < nums1[i] && nums1[i-1] < nums2[i]) 必须操作
noSwapDp[i] = swapDp[i-1] // 如果 i 不互换,则 i-1 必须互换
swapDp[i] = noSwapDp[i-1] + 1 // 如果 i 互换,则 i-1 必须不互换
}
}
return min(swapDp[n-1], noSwapDp[n-1])
}
fun minSwap1(nums1: IntArray, nums2: IntArray): Int {
// 状态定义,swapDp[i] 表示在 i 位置执行交换,使得 nums1 和 nums2 在 [0,i] 的区间都严格递增的最小交换次数;
// noSwapDp[i] 表示在 i 位置 **不** 执行交换,使得 nums1 和 nums2 在 [0,i] 的区间都严格递增的最小交换次数;
val swapDp = IntArray(nums1.size)
val noSwapDp = IntArray(nums1.size)
// 初始值
swapDp[0] = 1 // 在 0 位置交换
noSwapDp[0] = 0 // 在 0 位置不交换
for (i in 1 until nums1.size) {
if (nums1[i-1] < nums1[i] && nums1[i-1] < nums2[i] && nums2[i-1] < nums1[i] && nums2[i-1] < nums2[i]) {
// 两个数组,在 i-1 的位置,都比 i 位置小
// 所以,i 位置要不要交换都行,取决于 swap[i-1] 和 noSwapDp[i-1] 哪个更小
swapDp[i] = min(swapDp[i-1], noSwapDp[i-1]) + 1
noSwapDp[i] = min(swapDp[i-1], noSwapDp[i-1])
}else if (nums1[i-1] < nums1[i] && nums2[i-1] < nums2[i]) {
// i 位置要不要交换,取决于 i-1 位置有没有交换,如果 i-1 交换了,i 也要跟着交换
swapDp[i] = swapDp[i-1] + 1
noSwapDp[i] = noSwapDp[i-1]
}else if (nums1[i-1] < nums2[i] && nums2[i-1] < nums1[i]) {
// i 位置要不要交换,取决于 i-1 位置有没有交换,如果 i-1 交换了,i 就不要交换
swapDp[i] = noSwapDp[i-1] + 1
noSwapDp[i] = swapDp[i-1]
}
}
return min(swapDp[nums1.size-1], noSwapDp[nums1.size-1])
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 3,731 | kotlin-study | MIT License |
src/poyea/aoc/mmxxii/day21/Day21.kt | poyea | 572,895,010 | false | {"Kotlin": 68491} | package poyea.aoc.mmxxii.day21
import poyea.aoc.utils.readInput
fun part1(input: String): Long {
val numberOf = mutableMapOf<String, Long>()
val children = mutableMapOf<String, Pair<String, String>>()
val operations = mutableMapOf<String, Char>()
input.split("\n").forEach {
val (name, rest) = it.split(": ")
if (rest.any { it.isDigit() }) numberOf[name] = rest.toLong()
else {
children[name] = rest.take(4) to rest.takeLast(4)
operations[name] = rest[5]
}
}
fun traverse(monkey: String): Long {
return if (monkey in numberOf) numberOf[monkey]!!
else {
val (left, right) = children[monkey]!!
val k1 = traverse(left)
val k2 = traverse(right)
numberOf[left] = k1
numberOf[right] = k2
when (operations[monkey]!!) {
'+' -> k1 + k2
'-' -> k1 - k2
'*' -> k1 * k2
else -> k1 / k2
}
}
}
return traverse("root")
}
fun part2(input: String): Long {
val numberOf = mutableMapOf<String, Long>()
val children = mutableMapOf<String, Pair<String, String>>()
val operations = mutableMapOf<String, Char>()
input.split("\n").forEach {
val (name, rest) = it.split(": ")
if (rest.any { it.isDigit() }) numberOf[name] = rest.toLong()
else {
children[name] = rest.take(4) to rest.takeLast(4)
operations[name] = rest[5]
}
}
var trailToHuman = listOf<String>()
fun traverse(monkey: String, trail: List<String> = listOf()): Long {
if (monkey == "humn") trailToHuman = trail.drop(1) + "humn"
return if (monkey in numberOf) numberOf[monkey]!!
else {
val (left, right) = children[monkey]!!
val k1 = traverse(left, trail + monkey)
val k2 = traverse(right, trail + monkey)
numberOf[left] = k1
numberOf[right] = k2
when (operations[monkey]!!) {
'+' -> k1 + k2
'-' -> k1 - k2
'*' -> k1 * k2
else -> k1 / k2
}
}
}
traverse("root")
val (p1, p2) = children["root"]!!
val toEqual = if (p1 == trailToHuman.first()) numberOf[p2]!! else numberOf[p1]!!
val output = trailToHuman.windowed(2).fold(initial = toEqual) { acc, (monkey, next) ->
val (child1, child2) = children[monkey]!!
val other = if (child1 == next) numberOf[child2]!! else numberOf[child1]!!
val isLeft = children[monkey]?.second == next
when (operations[monkey]!!) {
'+' -> acc - other
'-' -> if (isLeft) other - acc else acc + other
'*' -> acc/other
else -> if (isLeft) other/acc else acc*other
}
}
return output
}
fun main() {
println(part1(readInput("Day21")))
println(part2(readInput("Day21")))
}
| 0 | Kotlin | 0 | 1 | fd3c96e99e3e786d358d807368c2a4a6085edb2e | 2,991 | aoc-mmxxii | MIT License |
src/Day05.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | import java.util.Stack
fun main() {
fun stacks(input: List<String>): Map<Int, Stack<Char>> {
val stacks = mutableMapOf<Int, Stack<Char>>()
val stacksArea = input.takeWhile { it.isNotEmpty() }
stacksArea.reversed().drop(1).forEach { row ->
row.windowed(3, 4) { it[1] }.forEachIndexed { index, c ->
if (c.isLetter()) stacks.getOrPut(index) { Stack() }.push(c)
}
}
return stacks
}
fun execute(stacks: Map<Int, Stack<Char>>, input: List<String>): String {
val commands = input.dropWhile { it.isNotEmpty() }.drop(1)
commands.forEach { cmd ->
val (quantity, from, to) = cmd.split(" ").mapNotNull { it.toIntOrNull() }
(0 until quantity).forEach { _ ->
stacks[to - 1]!!.push(stacks[from - 1]!!.pop())
}
}
return stacks.values.map { it.pop() }.joinToString(separator = "")
}
fun execute9001(stacks: Map<Int, Stack<Char>>, input: List<String>): String {
val commands = input.dropWhile { it.isNotEmpty() }.drop(1)
commands.forEach { cmd ->
val (quantity, from, to) = cmd.split(" ").mapNotNull { it.toIntOrNull() }
(0 until quantity).map { stacks[from - 1]!!.pop() }.reversed().forEach {
stacks[to - 1]!!.push(it)
}
}
return stacks.values.map { it.pop() }.joinToString(separator = "")
}
fun part1(input: List<String>): String {
val stacks = stacks(input)
return execute(stacks, input)
}
fun part2(input: List<String>): String {
val stacks = stacks(input)
return execute9001(stacks, input)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ") { "part1 check failed" }
check(part2(testInput) == "MCD") { "part2 check failed" }
val input = readInput("Day05")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 2,039 | aoc2022 | Apache License 2.0 |
src/Day09.kt | andrewgadion | 572,927,267 | false | {"Kotlin": 16973} | import kotlin.math.*
data class Pos(val x: Int, val y: Int) {
fun distance(p: Pos) = max(abs(x - p.x), abs(y - p.y))
}
fun main() {
fun move(rope: List<Pos>, command: String) =
sequence {
val (direction, steps) = command.split(" ")
var lastRope = rope
repeat(steps.toInt()) {
val newHead = when (direction) {
"U" -> Pos(lastRope[0].x, lastRope[0].y + 1)
"D" -> Pos(lastRope[0].x, lastRope[0].y - 1)
"R" -> Pos(lastRope[0].x + 1, lastRope[0].y)
"L" -> Pos(lastRope[0].x - 1, lastRope[0].y)
else -> throw Exception("unknown command")
}
lastRope = lastRope.drop(1).fold(listOf(newHead)) { acc, curKnot ->
acc + if (acc.last().distance(curKnot) > 1) {
Pos(curKnot.x + (acc.last().x - curKnot.x).coerceIn(-1, 1),
curKnot.y + (acc.last().y - curKnot.y).coerceIn(-1, 1)
)
}
else
curKnot
}
yield(lastRope)
}
}
fun moveRope(size: Int, input: List<String>): Int {
val tailPositions = mutableSetOf(Pos(0,0))
var rope = List(size) { Pos(0,0) }
input.forEach { command ->
move(rope, command).forEach {
rope = it
tailPositions.add(it.last())
}
}
return tailPositions.size
}
fun part1(input: List<String>) = moveRope(2, input)
fun part2(input: List<String>) = moveRope(10, input)
val input = readInput("day9")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4d091e2da5d45a786aee4721624ddcae681664c9 | 1,781 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/oocode/CamelCards.kt | ivanmoore | 725,978,325 | false | {"Kotlin": 42155} | package com.oocode
fun camelCardHandsFrom(input: String): CamelCardHands =
CamelCardHands(input.split("\n")
.map { line -> line.split(" ").let { CamelCardHand(it[0]) to it[1].toInt() } })
class CamelCardHands(private val handsWithBids: List<Pair<CamelCardHand, Int>>) {
fun totalWinnings(): Int {
val sortedBy = handsWithBids.sortedBy { it.first }
return sortedBy.foldIndexed(0, { index, accumulator, cardWithBid ->
accumulator + (cardWithBid.second * (index + 1))
})
}
}
data class CamelCardHand(val cards: String) : Comparable<CamelCardHand> {
enum class Type {
HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_A_KIND, FULL_HOUSE, FOUR_OF_A_KIND, FIVE_OF_A_KIND
}
private val labels = "AKQT98765432J".reversed()
override operator fun compareTo(other: CamelCardHand): Int {
if (this.type() == other.type()) {
fun makeEasilyComparable(cards: String) =
cards.map { labels.indexOf(it) }.map { 'a'.plus(it) }.toString()
return makeEasilyComparable(this.cards).compareTo(makeEasilyComparable(other.cards))
}
return this.type().compareTo(other.type())
}
private fun type(): Type {
val cardsWithJSubstituted = cards.replace('J', mostCommonNonJCard())
val groupsOfSameCards = cardsWithJSubstituted.groupBy { it }
if (groupsOfSameCards.size == 1)
return Type.FIVE_OF_A_KIND
if (groupsOfSameCards.size == 2)
if (groupsOfSameCards.map { it.value.size }.max() == 4)
return Type.FOUR_OF_A_KIND
else
return Type.FULL_HOUSE
if (groupsOfSameCards.size == 3)
if (groupsOfSameCards.map { it.value.size }.max() == 3)
return Type.THREE_OF_A_KIND
else
return Type.TWO_PAIR
if (groupsOfSameCards.size == 4)
return Type.ONE_PAIR
else
return Type.HIGH_CARD
}
private fun mostCommonNonJCard() =
if(cards == "JJJJJ") // very special case
'J'
else
cards.groupBy { it }
.filter { it.key != 'J' }
.map { it.value }
.sortedBy { it.size }
.reversed()[0][0] // doesn't matter which one of equal commonality
}
fun camelCardHandFrom(s: String) = CamelCardHand(s)
| 0 | Kotlin | 0 | 0 | 36ab66daf1241a607682e7f7a736411d7faa6277 | 2,397 | advent-of-code-2023 | MIT License |
src/Day05.kt | KristianAN | 571,726,775 | false | {"Kotlin": 9011} | import java.util.*
fun main() {
fun part1(input: List<String>): String = loadInput(input, 8, 9).move { stacks, i, i2, i3 ->
moveOne(stacks, i, i2, i3)
}.second.topToString()
fun part2(input: List<String>): String = loadInput(input, 8, 9).move { stacks, i, i2, i3 ->
moveAll(stacks, i, i2, i3)
}.second.topToString()
val input = readInput("day05")
println(part1(input))
println(part2(input))
}
fun loadQueues(input: List<String>, stacks: Int): List<Stack<Char>> {
val queues = mutableListOf<Stack<Char>>()
(0 until stacks).forEach { _ -> queues.add(Stack()) }
input.reversed().forEach {
it.forEachIndexed { index, char ->
if (char != ' ' && char != '[' && char != ']') queues[index / 4].add(char)
}
}
return queues
}
fun loadInput(input: List<String>, stackHeight: Int, stacks: Int): Pair<List<String>, List<Stack<Char>>> =
Pair(input.subList(stackHeight + 2, input.size), loadQueues(input.subList(0, stackHeight), stacks))
fun List<Stack<Char>>.topToString(): String =
this.map { it.last() }.joinToString("")
fun Pair<List<String>, List<Stack<Char>>>.move(moveFunc: (List<Stack<Char>>, Int, Int, Int) -> Unit): Pair<List<String>, List<Stack<Char>>> {
this.first.forEach { move -> move.parseMoves()
.let { moveFunc(this.second, it.amount, it.from, it.to) }
}
return this
}
fun moveAll(input: List<Stack<Char>>, amount: Int, from: Int, to: Int) = (0 until (amount)).map { _ ->
input[from - 1].pop() }.reversed().forEach { input[to - 1].add(it) }
fun moveOne(input: List<Stack<Char>>, amount: Int, from: Int, to: Int) = (0 until (amount)).forEach { _ ->
input[to - 1].add(input[from - 1].pop()) }
fun String.parseMoves(): Moves = this.split(" ").filter { it.all(Char::isDigit) }
.map { it.toInt() }.let { Moves(it[0], it[1], it[2]) }
data class Moves(val amount: Int, val from: Int, val to: Int) | 0 | Kotlin | 0 | 0 | 3a3af6e99794259217bd31b3c4fd0538eb797941 | 1,960 | AoC2022Kt | Apache License 2.0 |
src/day14/puzzle14.kt | brendencapps | 572,821,792 | false | {"Kotlin": 70597} | package day14
import Puzzle
import PuzzleInput
import java.io.File
import java.lang.Integer.max
import java.lang.Integer.min
fun day14Puzzle() {
Day14PuzzleSolution().solve(Day14PuzzleInput("inputs/day14/example.txt", 24))
Day14PuzzleSolution().solve(Day14PuzzleInput("inputs/day14/input.txt", 1016))
Day14Puzzle2Solution().solve(Day14PuzzleInput("inputs/day14/example.txt", 93))
Day14Puzzle2Solution().solve(Day14PuzzleInput("inputs/day14/input.txt", 25402))
}
private const val maxWidth = 400
private const val maxHeight = 200
open class Day14PuzzleInput(val input: String, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) {
private val grid: Array<IntArray> = Array(maxHeight) { IntArray(maxWidth) { 0 } }
val floor: Int
init {
floor = File(input).readLines().map { rockPath ->
val points = rockPath.split(" -> ").map{rockPoint ->
val coordinates = rockPoint.split(",")
Pair(coordinates[1].toInt(), coordinates[0].toInt() - 500 + maxWidth / 2)
}
for(i in 0 until points.size - 1) {
setRockFaces(points[i], points[i+1])
}
points
}.flatten().maxOf { it.first } + 2
}
fun getGridValue(point: Pair<Int, Int>) : Int {
return grid[point.first][point.second]
}
fun setGridValue(point: Pair<Int, Int>, value: Int) {
grid[point.first][point.second] = value
}
private fun setRockFaces(point1: Pair<Int, Int>, point2: Pair<Int, Int>) {
if(point1.first == point2.first) {
val start = min(point1.second, point2.second)
val finish = max(point1.second, point2.second)
for(i in start .. finish) {
grid[point1.first][i] = 1
}
}
else if(point1.second == point2.second) {
val start = min(point1.first, point2.first)
val finish = max(point1.first, point2.first)
for(i in start .. finish) {
grid[i][point1.second] = 1
}
}
}
}
class Day14PuzzleSolution : Puzzle<Int, Day14PuzzleInput>() {
override fun solution(input: Day14PuzzleInput): Int {
var sand = 0
addAbyssToGrid(input)
while(true) {
var sandPoint = Pair(0, maxWidth / 2)
while(true) {
val next = listOf(
Pair(sandPoint.first + 1, sandPoint.second),
Pair(sandPoint.first + 1, sandPoint.second - 1),
Pair(sandPoint.first + 1, sandPoint.second + 1)).filter {input.getGridValue(it) <= 0}
if(next.isEmpty()) {
sand++
input.setGridValue(sandPoint, 2)
break
}
when(input.getGridValue(next.first())) {
-1 -> return sand
0 -> sandPoint = next.first()
}
}
}
}
private fun addAbyssToGrid(input: Day14PuzzleInput) {
for(col in 0 until maxWidth) {
for(row in maxHeight - 1 downTo 0) {
if(input.getGridValue(Pair(row, col)) == 0) {
input.setGridValue(Pair(row, col), -1)
}
else if(input.getGridValue(Pair(row, col)) == 1) {
break
}
}
}
}
}
class Day14Puzzle2Solution : Puzzle<Int, Day14PuzzleInput>() {
override fun solution(input: Day14PuzzleInput): Int {
var sand = 0
setGridFloor(input)
while(true) {
var sandPoint = Pair(0, 200)
while(true) {
val next = listOf(
Pair(sandPoint.first + 1, sandPoint.second),
Pair(sandPoint.first + 1, sandPoint.second - 1),
Pair(sandPoint.first + 1, sandPoint.second + 1)).filter {input.getGridValue(it) <= 0}
if(next.isEmpty()) {
input.setGridValue(sandPoint, 2)
sand++
if(sandPoint.first == 0) {
return sand
}
break
}
sandPoint = next.first()
}
}
}
private fun setGridFloor(input: Day14PuzzleInput) {
for(col in 0 until 400) {
for(row in 199 downTo input.floor) {
input.setGridValue(Pair(row, col),1)
}
}
}
} | 0 | Kotlin | 0 | 0 | 00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3 | 4,645 | aoc_2022 | Apache License 2.0 |
src/Day02.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | enum class Hand(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
}
fun Char.toHand() = when (this) {
'A', 'X' -> Hand.ROCK
'B', 'Y' -> Hand.PAPER
'C', 'Z' -> Hand.SCISSORS
else -> error("Invalid hand: $this")
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val request = it.first().toHand()
val response = it.last().toHand()
response.score + when (request) {
response -> 3
Hand.ROCK -> if (response == Hand.PAPER) 6 else 0
Hand.PAPER -> if (response == Hand.SCISSORS) 6 else 0
Hand.SCISSORS -> if (response == Hand.ROCK) 6 else 0
}
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val request = it.first().toHand()
when (val outcome = it.last()) {
'X' -> if (request.score == 1) 3 else request.score - 1
'Y' -> 3 + request.score
'Z' -> 6 + (request.score % 3) + 1
else -> error("Invalid outcome: $outcome")
}
}
}
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 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 1,350 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/fr/pturpin/coursera/greedy/MaximumValueOfTheLoot.kt | TurpIF | 159,055,822 | false | null | package fr.pturpin.coursera.greedy
import java.util.*
class MaximumValueOfTheLoot(private val knapsackCapacity: Int) {
private val formatPrecision = 4
private var weightOfCandidates = 0
private val sortedByLowValuationCandidates = PriorityQueue<Item>()
fun addPotentialItem(itemValue: Int, itemWeight: Int) {
addNewCandidate(Item(itemValue, itemWeight))
if (!isLowestCandidateUseful()) {
removeLowestCandidate()
}
}
private fun isLowestCandidateUseful(): Boolean {
if (weightOfCandidates <= knapsackCapacity) {
return true
}
val lowestValuableCandidate = sortedByLowValuationCandidates.element()
return weightOfCandidates - lowestValuableCandidate.weight < knapsackCapacity
}
private fun addNewCandidate(newCandidate: Item) {
sortedByLowValuationCandidates.add(newCandidate)
weightOfCandidates += newCandidate.weight
}
private fun removeLowestCandidate() {
val lowestCandidate = sortedByLowValuationCandidates.remove()
weightOfCandidates -= lowestCandidate.weight
}
fun getMaximalValueOfFractionsOfItemsFittingIn(): Double {
if (knapsackCapacity == 0) {
return 0.0
}
val highestValuationsValue = sortedByLowValuationCandidates.stream()
.skip(1)
.mapToDouble { it.value.toDouble() }
.sum()
val lowestValuableCandidate = sortedByLowValuationCandidates.element()
val partialValue = if (weightOfCandidates <= knapsackCapacity) {
lowestValuableCandidate.value.toDouble()
} else {
val remainingWeight = knapsackCapacity - (weightOfCandidates - lowestValuableCandidate.weight)
lowestValuableCandidate.value * remainingWeight.toDouble() / lowestValuableCandidate.weight
}
return highestValuationsValue + partialValue
}
fun formatOutput(value: Double): String {
val format = "%." + formatPrecision + "f"
return format.format(Locale.US, value)
}
private data class Item(val value: Int, val weight: Int) : Comparable<Item> {
private fun getValueByWeight() = value.toDouble() / weight
override fun compareTo(other: Item): Int {
return getValueByWeight().compareTo(other.getValueByWeight())
}
}
}
fun main(args: Array<String>) {
val (n, knapsackCapacity) = readLine()!!.split(" ").map { it.toInt() }
val maximumValueOfTheLoot = MaximumValueOfTheLoot(knapsackCapacity)
for (i in 0 until n) {
val (value, weight) = readLine()!!.split(" ").map { it.toInt() }
maximumValueOfTheLoot.addPotentialItem(value, weight)
}
val maximalValue = maximumValueOfTheLoot.getMaximalValueOfFractionsOfItemsFittingIn()
print(maximumValueOfTheLoot.formatOutput(maximalValue))
}
| 0 | Kotlin | 0 | 0 | 86860f8214f9d4ced7e052e008b91a5232830ea0 | 2,888 | coursera-algo-toolbox | MIT License |
src/main/kotlin/Day13.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | import kotlinx.serialization.json.*
sealed class Packet: Comparable<Packet>
data class ListPacket(val contents: List<Packet>): Packet() {
override fun compareTo(other: Packet): Int {
return when (other) {
is ListPacket -> {
for (pair in this.contents.zip(other.contents)) {
val cmp = pair.first.compareTo(pair.second)
if (cmp != 0) {
return cmp
}
}
return this.contents.size.compareTo(other.contents.size)
}
is ValPacket -> this.compareTo(ListPacket(listOf(ValPacket(other.number))))
}
}
override fun toString(): String {
return "[" + contents.joinToString(",") + "]"
}
}
data class ValPacket(val number: Int): Packet() {
override fun compareTo(other: Packet): Int {
return when (other) {
is ValPacket -> this.number.compareTo(other.number)
is ListPacket -> ListPacket(listOf(ValPacket(this.number))).compareTo(other)
}
}
override fun toString(): String {
return "$number"
}
}
fun main() {
fun parse(tree: JsonElement): Packet {
return when (tree) {
is JsonArray -> ListPacket(tree.asSequence().map { parse(it) }.toList())
is JsonPrimitive -> ValPacket(tree.int)
else -> error("only support nested arrays of number")
}
}
fun parse(input: List<String>): List<Pair<Packet, Packet>> {
val results = mutableListOf<Pair<Packet, Packet>>()
for ((one, two, blank) in input.chunked(3)) {
val treeOne = Json.parseToJsonElement(one)
val treeTwo = Json.parseToJsonElement(two)
results.add(parse(treeOne) to parse(treeTwo))
check(blank.isBlank())
}
return results.toList()
}
fun part1(input: List<String>): Int {
var result = 0
val pairs = parse(input)
for (i in pairs.withIndex()) {
if (i.value.inRightOrder()) {
result += (i.index + 1)
}
}
return result
}
fun part2(input: List<String>): Int {
val dp1 = parse(Json.parseToJsonElement("[[2]]"))
val dp2 = parse(Json.parseToJsonElement("[[6]]"))
val allPackets = parse(input).flatMap { it.toList() } + listOf(dp1, dp2)
val sorted = allPackets.sorted()
return (sorted.indexOf(dp1) + 1) * (sorted.indexOf(dp2) + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private fun Pair<Packet, Packet>.inRightOrder(): Boolean {
return first <= second
}
| 0 | Kotlin | 0 | 0 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 2,884 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day24/Day24.kt | Arch-vile | 317,641,541 | false | null | package day24
import java.io.File
fun readFile(fileName: String) =
File(fileName).readLines()
fun main(args: Array<String>) {
var steps =
readFile("./src/main/resources/day24Input.txt")
.map {
it
.replace("se", "SE")
.replace("ne", "NE")
.replace("sw", "SW")
.replace("nw", "NW")
.replace("e", "EE")
.replace("w", "WW")
}
.map {
it.windowed(2, 2)
}
var endCoordinates = steps
.map {
it.fold(Pair(0, 0))
{ acc, next ->
val offset = offsetAmount(next)
Pair(acc.first + offset.first, acc.second + offset.second)
}
}
.map { Pair(it.first, it.second) }
val blackTilesMap = endCoordinates.groupBy { it }
.filter { it.value.size % 2 == 1 }
// Part 1
blackTilesMap.count().let { println(it) }
// Part 2
part2(blackTilesMap.keys.toSet())
}
fun nextIn(direction: String, from: Pair<Int, Int>): Pair<Int, Int> {
return offsetAmount(direction).let {
Pair(from.first + it.first, from.second + it.second)
}
}
private fun part2(blackTilesA: Set<Pair<Int, Int>>) {
val loop = generateSequence(blackTilesA) { blackTiles ->
val whiteTiles =
blackTiles
.flatMap { allNeighboursOf(it) }
.filter { isNotABlackTile(it, blackTiles) }
.toSet()
val remainingBlack = blackTiles
.filter {
val neighbours = blackNeighboursOf(it, blackTiles)
neighbours.size == 1 || neighbours.size == 2
}.toSet()
val whiteTurnedToBlack = whiteTiles
.filter {
blackNeighboursOf(it, blackTiles).size == 2
}.toSet()
val currentBlack = remainingBlack.plus(whiteTurnedToBlack)
currentBlack.size.let { println(it) }
currentBlack
}
loop.take(101).toList()
}
fun blackNeighboursOf(tile: Pair<Int, Int>, blackTiles: Set<Pair<Int, Int>>): Set<Pair<Int, Int>> {
return allNeighboursOf(tile)
.filter { blackTiles.contains(it) }
.toSet()
}
fun isNotABlackTile(tile: Pair<Int, Int>, blackTiles: Set<Pair<Int, Int>>) =
!blackTiles.contains(tile)
fun allNeighboursOf(tile: Pair<Int, Int>): Set<Pair<Int, Int>> {
return setOf("EE", "WW", "NW", "NE", "SE", "SW")
.map { offsetAmount(it) }
.map { Pair(it.first, it.second) }
.map { Pair(tile.first + it.first, tile.second + it.second) }
.toSet()
}
fun offsetAmount(direction: String): Pair<Int, Int> {
val long = 1
val short = 1
return when (direction) {
"EE" -> Pair(2 * short, 0)
"WW" -> Pair(-2 * short, 0)
"NW" -> Pair(-1 * short, long)
"NE" -> Pair(short, long)
"SE" -> Pair(short, -1 * long)
"SW" -> Pair(-1 * short, -1 * long)
else -> throw Error("Unknown direction $direction")
}
}
| 0 | Kotlin | 0 | 0 | 12070ef9156b25f725820fc327c2e768af1167c0 | 2,746 | adventOfCode2020 | Apache License 2.0 |
src/main/kotlin/Day03.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | fun main() {
fun priority(only: Char) = when (only) {
in 'A'..'Z' -> (only - 'A') + 27
in 'a'..'z' -> (only - 'a') + 1
else -> error("weird")
}
fun bisect(s: String): Pair<String, String> {
val sz = s.length / 2
return s.slice(0 until sz) to s.substring(sz)
}
fun part1(input: List<String>): Int {
return input.map { bisect(it) }.map { it.first.toSet() to it.second.toSet() }
.map { it.first.intersect(it.second).single() }.sumOf { priority(it) }
}
fun part2(input: List<String>): Int {
return input.chunked(3).map { chunk -> chunk.map { it.toSet() }.reduce { a, b -> a.intersect(b) } }
.map { it.single() }.sumOf { priority(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 991 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | enum class Shape(val alias: Set<Char>, val points: Int) {
Rock(setOf('A', 'X'), 1),
Paper(setOf('B', 'Y'), 2),
Scissors(setOf('C', 'Z'), 3);
fun score(other: Shape): Int {
val outcome = when (other) {
this -> 3
beats[this] -> 6
else -> 0
}
return outcome + points
}
companion object {
val beats = mapOf(
Rock to Scissors,
Paper to Rock,
Scissors to Paper
)
val looses = beats.entries.associate { (k, v) -> v to k }
fun of(ch: Char): Shape = Shape.values().find { it.alias.contains(ch) }!!
}
}
fun main() {
fun part1(input: List<String>): Int {
var result = 0
for (match in input) {
val opponent = Shape.of(match[0])
val me = Shape.of(match[2])
result += me.score(opponent)
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
for (match in input) {
val opponent = Shape.of(match[0])
val outcome = match[2]
result += when(outcome) {
'X' -> Shape.beats[opponent]!!.score(opponent)
'Y' -> opponent.score(opponent)
else -> Shape.looses[opponent]!!.score(opponent)
}
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 1,612 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | ghasemdev | 572,632,405 | false | {"Kotlin": 7010} | private infix fun ClosedRange<Int>.contains(other: ClosedRange<Int>) =
start >= other.start && endInclusive <= other.endInclusive
private infix fun ClosedRange<Int>.overlap(other: ClosedRange<Int>) =
start in other || endInclusive in other
fun main() {
fun counter(input: List<String>, kFunction2: (ClosedRange<Int>, ClosedRange<Int>) -> Boolean): Int {
var counter = 0
for (line in input) {
val (part1, part2) = line.split(",")
val range1 = part1.split("-").map { it.toInt() }.run { IntRange(first(), last()) }
val range2 = part2.split("-").map { it.toInt() }.run { IntRange(first(), last()) }
if ((kFunction2(range1, range2)) || (kFunction2(range2, range1))) {
counter++
}
}
return counter
}
fun part1(input: List<String>): Int = counter(input, ClosedRange<Int>::contains)
fun part2(input: List<String>): Int = counter(input, ClosedRange<Int>::overlap)
// 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 | 1 | 7aa5e7824c0d2cf2dad94ed8832a6b9e4d36c446 | 1,265 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2017/day07/RecursiveCircus.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2017.day07
import com.barneyb.aoc.util.Solver
import java.util.*
fun main() {
Solver.execute(
::parse,
Prog::name,
::correction,
)
}
internal data class Prog(
val name: String,
val weight: Int,
val tower: Collection<Prog> = emptyList(),
) {
val totalWeight: Int = weight + tower.sumOf(Prog::totalWeight)
val balanced = tower.distinctBy { it.totalWeight }.size == 1
}
internal data class Record(
val name: String,
val weight: Int,
val tower: Collection<String>,
) {
companion object {
// kpjxln (44) -> dzzbvkv, gzdxgvj, wsocb, jidxg
val RE_PARSER = Regex("([a-z]+) \\((\\d+)\\)(:? -> ([a-z, ]+))?")
fun parse(str: String): Record {
val (name, weight, _, items) = RE_PARSER.find(str)!!.destructured
return Record(
name,
weight.toInt(),
if (items.isBlank()) emptyList() else items
.split(",")
.map(String::trim)
)
}
}
fun isLeaf() =
tower.isEmpty()
}
internal fun parse(input: String): Prog {
val q = LinkedList<Record>()
val trees = mutableMapOf<String, Prog>()
fun addNonLeaf(r: Record) {
if (r.tower.all(trees::containsKey)) {
trees[r.name] = Prog(
r.name,
r.weight,
r.tower.mapNotNull(trees::remove)
)
} else {
q.add(r)
}
}
for (r in input.trim().lines().map(Record::parse)) {
if (r.isLeaf()) {
trees[r.name] = Prog(r.name, r.weight)
} else {
addNonLeaf(r)
}
}
while (q.isNotEmpty()) {
addNonLeaf(q.remove())
}
assert(trees.size == 1) { "More than one base found?!" }
return trees.values.first()
}
internal fun correction(p: Prog): Int =
if (!p.balanced && p.tower.all(Prog::balanced)) {
val weights = p.tower.groupBy(Prog::totalWeight)
assert(weights.size == 2) { "There's more than one error?!" }
val erroneous = weights.keys.first { weights[it]?.size == 1 }
val expected = weights.keys.first { it != erroneous }
weights[erroneous]!!.first().weight + (expected - erroneous)
} else {
p.tower.firstNotNullOf(::correction)
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 2,366 | aoc-2022 | MIT License |
src/day15/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day15
import assert
import println
import readInput
fun main() {
class Command(val label: String, val command: Char, val focalLength: Int)
class Mirror(val label: String, val focalLength: Int)
class Box(val number: Int, val mirrors: MutableList<Mirror>) {
fun focusingPower(): Int {
return mirrors.mapIndexed { index, mirror ->
(this.number + 1) * (index + 1) * mirror.focalLength
}.sum()
}
}
fun String.hash(): Int {
return this.fold(0) { acc, char ->
(char.code + acc) * 17 % 256
}
}
fun splitToBlocks(input: String): List<String> {
return input.split(",")
}
fun parseCommand(input: String): Command {
val matchResult = Regex("^([a-zA-Z]+)([=-])(\\d*)\$").matchEntire(input)!!
val (label, command, focalLength) = matchResult.destructured
return Command(label, command.first(), focalLength.ifBlank{"0"}.toInt())
}
fun processCommands(boxes: Array<Box>, command: Command) : Array<Box> {
val box = boxes[command.label.hash()]
val sameLabelMirror = box.mirrors.indexOfFirst { it.label == command.label }
when(command.command) {
'=' -> {
if (sameLabelMirror >= 0) {
box.mirrors[sameLabelMirror] = Mirror(command.label, command.focalLength)
} else {
box.mirrors.add(Mirror(command.label, command.focalLength))
}
}
else -> {
if (sameLabelMirror >= 0) {
box.mirrors.removeAt(sameLabelMirror)
}
}
}
return boxes
}
"HASH".hash().assert(52)
splitToBlocks(readInput("day15/test1")[0])
.sumOf { it.hash() }
.assert(1320)
"Part 1:".println()
splitToBlocks(readInput("day15/input")[0])
.sumOf { it.hash() }
.assert(510388)
.println()
fun emptyBoxes(): Array<Box> {
return Array(256) {Box(it, mutableListOf())}
}
splitToBlocks(readInput("day15/test1")[0])
.map(::parseCommand)
.fold(emptyBoxes(), ::processCommands)
.sumOf { it.focusingPower() }
.assert(145)
"Part 2:".println()
splitToBlocks(readInput("day15/input")[0])
.map(::parseCommand)
.fold(emptyBoxes(), ::processCommands)
.sumOf { it.focusingPower() }
.assert(291774)
.println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 2,497 | advent-of-code-2023 | Apache License 2.0 |
src/Day11.kt | dcbertelsen | 573,210,061 | false | {"Kotlin": 29052} | import java.io.File
import kotlin.collections.ArrayDeque
fun main() {
fun readMonkeys(input: List<String>) =
input.map { data ->
val lines = data.split("\n")
Monkey(
ArrayDeque(lines[1].split(": ")[1].split(", ").map { it -> it.toLong() }),
lines[2].split("=")[1].toFunction(),
lines[3].split(" ").last().toInt(),
lines[4].split(" ").last().toInt(),
lines[5].split(" ").last().toInt()
)
}
fun part1(input: List<String>): Int {
val monkeys = readMonkeys(input)
repeat(20) {
monkeys.forEach { monkey ->
while (monkey.hasItems()) {
val (newItem, target) = monkey.inspectNextPt1()
monkeys[target].catch(newItem)
}
}
}
return monkeys.sortedBy { it.inspectionCount }.takeLast(2).fold(1) { acc, m -> acc * m.inspectionCount}
}
fun part2(input: List<String>): Long {
val monkeys = readMonkeys(input)
val checkProduct = monkeys.fold(1) { acc, m -> acc * m.testDiv }
repeat(10000) {
monkeys.forEach { monkey ->
while (monkey.hasItems()) {
val (newItem, target) = monkey.inspectNextPt2()
monkeys[target].catch(newItem % checkProduct)
}
}
}
val topTwo = monkeys.map { it.inspectionCount }.sorted().takeLast(2)
return 1L * topTwo[0] * topTwo[1]
}
val testInput =
"""Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
""".split("\n\n")
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 10605)
check(part2(testInput) == 2713310158L)
val input = File("./src/resources/Day11.txt").readText().split("\n\n")
println(part1(input))
println(part2(input))
}
class Monkey(val items: ArrayDeque<Long>, val op: (Long) -> Long, val testDiv: Int, val ifTrue: Int, val ifFalse: Int) {
var inspectionCount = 0
private set
fun catch(item: Long) {
items.add(item)
}
fun hasItems() = items.any()
private fun inspectNext(divisor: Int): Pair<Long, Int> {
inspectionCount++
val newWorry = op(items.removeFirst()) / divisor
return newWorry to if (newWorry % testDiv == 0L ) ifTrue else ifFalse
}
fun inspectNextPt1(): Pair<Long, Int> = inspectNext(3)
fun inspectNextPt2(): Pair<Long, Int> = inspectNext(1)
}
fun String.toFunction(): (Long) -> Long {
if (this.trim() == "old * old")
return { old -> old * old }
val tokens = this.trim().split(" ")
if (tokens[1] == "+")
return { old: Long -> old + tokens[2].toInt() }
if (tokens[1] == "*")
return { old: Long -> old * tokens[2].toInt() }
return { old: Long -> old * tokens[2].toInt() }
}
| 0 | Kotlin | 0 | 0 | 9d22341bd031ffbfb82e7349c5684bc461b3c5f7 | 3,492 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day02.kt | mvmlisb | 572,859,923 | false | {"Kotlin": 14994} | private enum class GameMove(private val values: List<String>) {
Rock(listOf("A", "X")),
Paper(listOf("B", "Y")),
Scissors(listOf("C", "Z"));
private fun getPoints() = when (this) {
Rock -> 1
Paper -> 2
Scissors -> 3
}
fun fightInFairWay(opponent: GameMove) = (if (this == opponent)
DRAW_POINTS
else
when {
this == Rock && opponent == Scissors ||
this == Scissors && opponent == Paper ||
this == Paper && opponent == Rock -> WINNER_POINTS
else -> LOSER_POINTS
}) + getPoints()
fun fightInPredeterminedWay(opponent: GameMove) = when (this) {
Scissors -> WINNER_POINTS + when (opponent) {
Rock -> Paper
Paper -> Scissors
Scissors -> Rock
}.getPoints()
Rock -> LOSER_POINTS + when (opponent) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}.getPoints()
Paper -> DRAW_POINTS + opponent.getPoints()
}
companion object {
private const val WINNER_POINTS = 6
private const val LOSER_POINTS = 0
private const val DRAW_POINTS = 3
fun fromString(string: String) = values().first { it.values.contains(string) }
}
}
private fun score(fight: (you: GameMove, opponent: GameMove) -> Int) =
readInput("Day02_test").fold(0) { acc: Int, line: String ->
acc + fight(GameMove.fromString(line.substringAfter(" ")), GameMove.fromString(line.substringBefore(" ")))
}
fun main() {
val part1 = score { you, opponent -> you.fightInFairWay(opponent) }
println(part1)
val part2 = score { you, opponent -> you.fightInPredeterminedWay(opponent) }
println(part2)
}
| 0 | Kotlin | 0 | 0 | 648d594ec0d3b2e41a435b4473b6e6eb26e81833 | 1,778 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/day8.kt | Gitvert | 433,947,508 | false | {"Kotlin": 82286} | fun day8() {
val lines: List<String> = readFile("day08.txt")
day8part1(lines)
day8part2(lines)
}
fun day8part1(lines: List<String>) {
val answer = lines
.map { it.split(" | ")[1].split(" ") }
.flatten()
.filter { intArrayOf(2, 3, 4, 7).contains(it.length) }
.size
println("8a: $answer")
}
fun day8part2(lines: List<String>) {
val entries = lines.map { line ->
Entry(
line.split(" | ")[0].split(" ").map { it.toCharArray().sorted().joinToString("") },
line.split(" | ")[1].split(" ").map { it.toCharArray().sorted().joinToString("") }
)
}
val answer = entries.sumOf { decode(it) }
println("8b: $answer")
}
fun decode(entry: Entry): Int {
val signalsToProcess = entry.signals.filter { intArrayOf(5, 6).contains(it.length) }
val digits: MutableList<String> = mutableListOf("TBD", "TBD", "TBD", "TBD", "TBD", "TBD", "TBD", "TBD", "TBD", "TBD")
entry.signals.forEach {
when (it.length) {
2 -> digits[1] = it
3 -> digits[7] = it
4 -> digits[4] = it
7 -> digits[8] = it
}
}
signalsToProcess.filter { it.length == 6 }.forEach {
val number = findNumber(it, digits)
if (number > -1) {
digits[number] = it
}
}
signalsToProcess.filter { it.length == 5 }.forEach {
val number = findNumber(it, digits)
if (number > -1) {
digits[number] = it
}
}
val outputDigits = entry.outputs.map {
digits.indexOf(it)
}
return Integer.valueOf(outputDigits.joinToString(""))
}
fun findNumber(pattern: String, digits: MutableList<String>): Int {
return if (pattern.length == 5) {
if (pattern.split("").containsAll(digits[1].split(""))) {
3
} else if (digits[9].split("").containsAll(pattern.split(""))) {
5
} else {
2
}
} else {
if (pattern.split("").containsAll(digits[4].split(""))) {
9
} else if (pattern.split("").containsAll(digits[7].split(""))) {
0
} else {
6
}
}
}
data class Entry(val signals: List<String>, val outputs: List<String>) | 0 | Kotlin | 0 | 0 | 02484bd3bcb921094bc83368843773f7912fe757 | 2,272 | advent_of_code_2021 | MIT License |
src/Day05.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | fun main() {
fun readScheme(input: List<String>): Array<MutableList<Char>> {
val numberOfCrates = (input.first().length + 1) / 4
val maxHeight = input.indexOfFirst(String::isEmpty) - 1
val crates = Array(numberOfCrates) { mutableListOf<Char>() }
input.take(maxHeight).forEach { line ->
("$line ").chunked(4)
.map { it[1] }
.forEachIndexed { index, c ->
if (c != ' ') {
crates[index].add(0, c)
}
}
}
return crates
}
fun readCommands(input: List<String>): List<Triple<Int, Int, Int>> {
val commandsStartLine = input.indexOfFirst(String::isEmpty) + 1
return input.drop(commandsStartLine)
.map { line ->
val words = line.split(" ")
val count = words[1].toInt()
val from = words[3].toInt() - 1
val to = words[5].toInt() - 1
Triple(count, from, to)
}
}
fun part1(input: List<String>): String {
val crates = readScheme(input)
readCommands(input).forEach { (count, from, to) ->
repeat(count) {
crates[to].add(crates[from].removeLast())
}
}
return crates.joinToString("") { it.last().toString() }
}
fun part2(input: List<String>): String {
val crates = readScheme(input)
readCommands(input).forEach { (count, from, to) ->
val fromCrate = crates[from]
val stack = fromCrate.subList(fromCrate.lastIndex - count + 1, fromCrate.lastIndex + 1)
crates[to].addAll(stack)
stack.clear()
}
return crates.joinToString("") { it.last().toString() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 2,091 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-16.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import com.github.ferinagy.adventOfCode.searchGraph
import kotlin.math.min
fun main() {
val input = readInputLines(2022, "16-input")
val testInput1 = readInputLines(2022, "16-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val caves = VolcanicCaves(input)
val totalTime = 30
val bits = (1 shl caves.openable.size) - 1
return caves.maxPossible(totalTime) - caves.dfs(totalTime, "AA", bits)
}
private fun part2(input: List<String>): Int {
val caves = VolcanicCaves(input)
val totalTime = 26
val bits = (1 shl caves.openable.size) - 1
return caves.maxPossible(totalTime) - caves.aStar(totalTime, "AA", bits)
}
private class VolcanicCaves(input: List<String>) {
val regex = """Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? ((\w+)(, (\w+))*)""".toRegex()
val valves = input.map {
val (from, rate, into) = regex.matchEntire(it)!!.destructured
Valve(from, rate.toInt(), into.split(", ").toSet())
}
val openable = valves.filter { it.rate != 0 }.map { it.name }
val openableByName = openable.mapIndexed { index, s -> s to index }.toMap()
val dists = computeDistances()
fun maxPossible(
time: Int,
bitSet: Int = (1 shl openable.size) - 1
) = calculateWasted(bitSet, time)
private val cache = mutableMapOf<Triple<Int, String, Int>, Int>()
fun dfs(time: Int, position: String, closed: Int): Int {
val key = Triple(time, position, closed)
if (key in cache) return cache[key]!!
var min = calculateWasted(closed, time)
closed.bitIndices(openable.size) { index ->
val next = openable[index]
val d = dists[position]!![next]!! + 1
if (d <= time) {
val wasted = calculateWasted(closed, d)
min = min(dfs(time - d, next, closed.removeBit(index)) + wasted, min)
}
}
cache[key] = min
return min
}
fun aStar(totalTime: Int, start: String, allValves: Int): Int {
data class State(val time: Int, val p1: String, val t1: Int, val p2: String, val t2: Int, val closed: Int)
val best = searchGraph(
start = State(totalTime, start, 0, start, 0, allValves),
isDone = { it.time == 0 },
nextSteps = { state ->
val set = mutableSetOf<Pair<State, Int>>()
if (state.t1 == 0) {
val newClosed = if (state.p1 == start) state.closed else state.closed.removeBit(openableByName[state.p1]!!)
newClosed.bitIndices(openable.size) { index ->
val next = openable[index]
if (next != state.p2) {
val d = dists[state.p1]!![next]!! + 1
set += state.copy(p1 = next, t1 = d, closed = newClosed) to 0
}
}
if (set.isEmpty()) {
set += state.copy(t1 = totalTime, closed = newClosed) to 0
}
} else if (state.t2 == 0) {
set += state.copy(p1 = state.p2, t1 = 0, p2 = state.p1, t2 = state.t1) to 0
} else {
val t = min(state.t1, state.t2).coerceAtMost(state.time)
set += state.copy(time = state.time - t, t1 = state.t1 - t, t2 = state.t2 - t) to calculateWasted(state.closed, t)
}
set
},
)
return best
}
private fun calculateWasted(closed: Int, time: Int) = valves.sumOf {
val open = openableByName[it.name]
if (open != null && open in closed) it.rate * time else 0
}
private fun computeDistances(): Map<String, Map<String, Int>> {
val map = mutableMapOf<String, MutableMap<String, Int>>()
val named = valves.associateBy { it.name }
for (i in valves.indices) {
val m1 = mutableMapOf<String, Int>()
for (j in valves.indices) {
m1[valves[j].name] = valves.size
}
map[valves[i].name] = m1
}
valves.forEach { v ->
map[v.name]!![v.name] = 0
}
valves.forEach { v1 ->
v1.connections.forEach { v2 ->
map[v1.name]!![named[v2]!!.name] = 1
}
}
for (k in valves) {
for (i in valves) {
for (j in valves) {
val newDist = map[i.name]!![k.name]!! + map[k.name]!![j.name]!!
if (map[i.name]!![j.name]!! > newDist) {
map[i.name]!![j.name] = newDist
}
}
}
}
return map
}
}
private fun Int.bitIndices(size: Int, block: (Int) -> Unit) {
var n = 0
var i = 1
while (n < size) {
if (i and this@bitIndices != 0) block(n)
n++
i = i shl 1
}
}
private fun Int.removeBit(index: Int): Int {
val n = 1 shl index
return this and n.inv()
}
private operator fun Int.contains(index: Int): Boolean {
val n = 1 shl index
return this and n != 0
}
private data class Valve(val name: String, val rate: Int, val connections: Set<String>)
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 5,597 | advent-of-code | MIT License |
src/day04/Day04.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day04
import readInput
fun main() {
fun String.toRange(): Pair<Int, Int> {
val split = this.split("-")
return split.first().toInt() to split.last().toInt()
}
fun parse(it: String): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val (firstRange, secondRange) = it.split(",")
return firstRange.toRange() to secondRange.toRange()
}
fun compareContaining(sectionPairs: Pair<Pair<Int, Int>, Pair<Int, Int>>): Boolean {
return (sectionPairs.first.first .. sectionPairs.first.second).toSet().containsAll(
(sectionPairs.second.first .. sectionPairs.second.second).toSet()) ||
(sectionPairs.second.first .. sectionPairs.second.second).toSet().containsAll(
(sectionPairs.first.first .. sectionPairs.first.second).toSet())
}
fun compareOverlapping(sectionPairs: Pair<Pair<Int, Int>, Pair<Int, Int>>): Boolean {
val intersect = (sectionPairs.first.first..sectionPairs.first.second).intersect(
sectionPairs.second.first..sectionPairs.second.second
)
return intersect.isNotEmpty()
}
fun part1(input: List<String>): Int {
return input.map {
parse(it)
}.count {
compareContaining(it)
}
}
fun part2(input: List<String>): Int {
return input.map {
parse(it)
}.count {
compareOverlapping(it)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day04/Day04_test")
println(part1(testInput))
check(part1(testInput) == 2)
val input = readInput("day04/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 1,726 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/year2022/day17/Day17.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day17
import check
import readInput
import kotlin.math.max
import kotlin.system.measureTimeMillis
import kotlin.time.Duration.Companion.milliseconds
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day17_test")
check(part1(testInput), 3068)
check(part2(testInput), 1_514_285_714_288)
val input = readInput("2022", "Day17")
measureTimeMillis { print(part1(input)) }.also { println(" (Part 1 took ${it.milliseconds})") }
measureTimeMillis { print(part2(input)) }.also { println(" (Part 2 took ${it.milliseconds})") }
}
private fun part1(input: List<String>): Long = getTetrisTowerHeight(input, 2022)
private fun part2(input: List<String>): Long = getTetrisTowerHeight(input, 1000000000000)
private fun getTetrisTowerHeight(input: List<String>, rocks: Long): Long {
lastHighestRock = 0
RockType.reset()
val moves = Moves(input.first())
val hall = Array(7) { Array(5_000) { true } }
data class PatternKey(
val moveIndex: Int,
val rockTypeIndex: Int,
val topRow: List<Int>,
)
data class PatternValue(
val highestRock: Int,
val remainingRocks: Long,
)
val patterns = hashMapOf<PatternKey, PatternValue>()
var remainingRocks = rocks
var extraHeight = 0L
while (remainingRocks > 0) {
val rock = Rock(RockType.next(), hall.highestRock())
while (true) {
rock.move(moves.next(), hall)
val settled = rock.moveDown(hall)
if (settled) break
}
remainingRocks--
val patternKey = PatternKey(moves.i, RockType.i, hall.topRows())
val patternValue = PatternValue(hall.highestRock(), remainingRocks)
val pattern = patterns[patternKey]
if (pattern != null && extraHeight == 0L) {
val patternHeight = patternValue.highestRock - pattern.highestRock
val rocksInPattern = pattern.remainingRocks - patternValue.remainingRocks
val patternRepetitions = remainingRocks / rocksInPattern
remainingRocks %= rocksInPattern
extraHeight += patternRepetitions * patternHeight
} else {
patterns[patternKey] = patternValue
}
}
return hall.highestRock() + 1 + extraHeight
}
private enum class Dir {
L, R
}
private class Moves(private val input: String) {
var i = 0
private set
get() = field % input.length
fun next(): Dir {
return if (input[i++] == '>') Dir.R else Dir.L
}
}
private enum class RockType {
HLine, Plus, InvL, VLine, Block;
companion object {
private val types = arrayOf(HLine, Plus, InvL, VLine, Block)
var i = 0
private set
get() = field % types.size
fun reset() {
i = 0
}
fun next(): RockType {
return types[i++]
}
}
}
// rocks appear so that its left edge is two units away from the left wall
// its bottom edge is three units above the highest rock
private class Rock(val type: RockType, highestRock: Int) {
var x = 2
var y = highestRock + 4
fun move(dir: Dir, hall: Array<Array<Boolean>>) {
when (dir) {
Dir.L -> moveLeft(hall)
Dir.R -> moveRight(hall)
}
}
private fun moveLeft(hall: Array<Array<Boolean>>) {
val canMove = when (type) {
RockType.HLine -> x > 0 && hall[x - 1][y]
RockType.Plus -> x > 0 && hall[x][y] && hall[x - 1][y + 1] && hall[x][y + 2]
RockType.InvL -> x > 0 && hall[x - 1][y] && hall[x + 1][y + 1] && hall[x + 1][y + 2]
RockType.VLine -> x > 0 && hall[x - 1][y] && hall[x - 1][y + 1] && hall[x - 1][y + 2] && hall[x - 1][y + 3]
RockType.Block -> x > 0 && hall[x - 1][y] && hall[x - 1][y + 1]
}
if (canMove) x--
}
private fun moveRight(hall: Array<Array<Boolean>>) {
val canMove = when (type) {
RockType.HLine -> x + 4 <= hall.lastIndex && hall[x + 4][y]
RockType.Plus -> x + 3 <= hall.lastIndex && hall[x + 2][y] && hall[x + 3][y + 1] && hall[x + 2][y + 2]
RockType.InvL -> x + 3 <= hall.lastIndex && hall[x + 3][y] && hall[x + 3][y + 1] && hall[x + 3][y + 2]
RockType.VLine -> x + 1 <= hall.lastIndex && hall[x + 1][y] && hall[x + 1][y + 1] && hall[x + 1][y + 2] && hall[x + 1][y + 3]
RockType.Block -> x + 2 <= hall.lastIndex && hall[x + 2][y] && hall[x + 2][y + 1]
}
if (canMove) x++
}
fun moveDown(hall: Array<Array<Boolean>>): Boolean {
val canMove = when (type) {
RockType.HLine -> y > 0 && hall[x][y - 1] && hall[x + 1][y - 1] && hall[x + 2][y - 1] && hall[x + 3][y - 1]
RockType.Plus -> y > 0 && hall[x][y] && hall[x + 1][y - 1] && hall[x + 2][y]
RockType.InvL -> y > 0 && hall[x][y - 1] && hall[x + 1][y - 1] && hall[x + 2][y - 1]
RockType.VLine -> y > 0 && hall[x][y - 1]
RockType.Block -> y > 0 && hall[x][y - 1] && hall[x + 1][y - 1]
}
if (canMove) {
y--
return false
}
settle(hall)
return true
}
private fun settle(hall: Array<Array<Boolean>>) {
when (type) {
RockType.HLine -> {
hall[x][y] = false
hall[x + 1][y] = false
hall[x + 2][y] = false
hall[x + 3][y] = false
}
RockType.Plus -> {
hall[x + 1][y] = false
hall[x][y + 1] = false
hall[x + 1][y + 1] = false
hall[x + 2][y + 1] = false
hall[x + 1][y + 2] = false
}
RockType.InvL -> {
hall[x][y] = false
hall[x + 1][y] = false
hall[x + 2][y] = false
hall[x + 2][y + 1] = false
hall[x + 2][y + 2] = false
}
RockType.VLine -> {
hall[x][y] = false
hall[x][y + 1] = false
hall[x][y + 2] = false
hall[x][y + 3] = false
}
RockType.Block -> {
hall[x][y] = false
hall[x + 1][y] = false
hall[x][y + 1] = false
hall[x + 1][y + 1] = false
}
}
}
}
private var lastHighestRock = -1
private fun Array<Array<Boolean>>.highestRock(): Int {
val from = max(lastHighestRock, 0)
for (y in from..first().lastIndex) {
if (all { it[y] }) {
lastHighestRock = y - 1
return y - 1
}
}
return -1
}
private fun Array<Array<Boolean>>.highestBlockingRow(): Int {
val maxY = max(highestRock(), 0)
val previous = Array(size) { true }
for (y in maxY downTo 0) {
if (mapIndexed { x, col -> !col[y] || !previous[x] }.all { it }) {
return y
}
onEachIndexed { x, col -> previous[x] = col[y] }
}
return -1
}
private fun Array<Array<Boolean>>.topRows(): List<Int> {
val maxY = max(highestRock(), 0)
val minY = highestBlockingRow() + 1
var num = 0
var bit = 0
val nums = arrayListOf<Int>()
var addNum = true
for (x in 0..lastIndex) {
for (y in maxY downTo minY) {
addNum = true
if (this[x][y]) {
num = num or (1 shl bit)
}
bit++
if (bit == 32) {
addNum = false
nums += num
bit = 0
num = 0
}
}
}
if (addNum) nums += num
return nums
}
private fun Array<Array<Boolean>>.print(rock: Rock? = null) {
val maxY = max(rock?.y ?: 0, highestRock())
for (y in maxY downTo 0) {
print("|")
for (x in 0..lastIndex) {
if (rock?.x == x && rock.y == y) print('x')
else if (this[x][y]) print('.')
else print('#')
}
print("|")
println()
}
println("+-------+")
println()
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 8,148 | AdventOfCode | Apache License 2.0 |
src/year2023/24/Day24.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`24`
import readInput
import utils.printlnDebug
import java.math.BigDecimal
private const val CURRENT_DAY = "24"
private data class Point3D(
val x: BigDecimal,
val y: BigDecimal,
val z: BigDecimal,
) {
override fun toString(): String {
return "[$x,$y,$z]"
}
}
private data class PosNSpeed(
val pos: Point3D,
val speed: Point3D,
)
private fun parseLineInto(
line: String
): PosNSpeed {
val (first, second) = line.split("@").filter { it.isNotBlank() }
val (px, py, pz) = first.split(",").map { it.trim() }
val (dx, dy, dz) = second.split(",").map { it.trim() }
return PosNSpeed(
Point3D(px.toBigDecimal(), py.toBigDecimal(), pz.toBigDecimal()),
Point3D(dx.toBigDecimal(), dy.toBigDecimal(), dz.toBigDecimal()),
)
}
data class Solution(
val x: BigDecimal,
val y: BigDecimal,
val t: BigDecimal,
)
private fun solve(
pointNSpeed1: PosNSpeed,
pointNSpeed2: PosNSpeed,
): Solution? {
val px2 = pointNSpeed2.pos.x
val py2 = pointNSpeed2.pos.y
val dx2 = pointNSpeed2.speed.x
val dy2 = pointNSpeed2.speed.y
val px1 = pointNSpeed1.pos.x
val py1 = pointNSpeed1.pos.y
val dx1 = pointNSpeed1.speed.x
val dy1 = pointNSpeed1.speed.y
val y =
runCatching { (px2 * dy1 * dy2 - px1 * dy1 * dy2 + py1 * dx1 * dy2 - py2 * dx2 * dy1) / (dx1 * dy2 - dx2 * dy1) }
.onFailure { return null }
.getOrThrow()
val x = (y - py1) * dx1 / dy1 + px1
val t = (x - px1) / dx1
val t2 = (x - px2) / dx2
return Solution(x, y, minOf(t, t2))
}
private fun findForPairs(items: List<PosNSpeed>): Sequence<Pair<Pair<PosNSpeed, PosNSpeed>, Solution?>> {
return sequence {
items.indices.forEach { i ->
(i + 1..items.indices.last).forEach { j ->
val first = items[i]
val second = items[j]
yield(first to second to solve(items[i], items[j]))
}
}
}
}
fun main() {
fun part1(input: List<String>, range: ClosedRange<BigDecimal>): Int {
val items = input.map {
parseLineInto(it)
}
val seq = findForPairs(items)
val count = seq
.filter { (inputPair, solution) ->
val first = inputPair.first
val second = inputPair.second
printlnDebug { "Hailstone A:$first" }
printlnDebug { "Hailstone B:$second" }
printlnDebug { "Solution : $solution" }
if (solution == null) return@filter false
printlnDebug { "Is Inside: ${solution.x in range && solution.y in range}" }
printlnDebug {}
solution.t > BigDecimal.ZERO
}
.count { (_, solution) ->
if (solution == null) return@count false
solution.x in range && solution.y in range
}
return count
}
/**
* https://sagecell.sagemath.org/
*/
fun part2(input: List<String>): String {
val items = input.map {
parseLineInto(it)
}
val eqn = mutableListOf<String>()
val t = mutableListOf<String>()
val fn = mutableListOf<String>()
eqn.add("var(\'xg yg zg dxg dyg dzg\')")
items.take(4).forEachIndexed { i, posNSpeed ->
eqn.add("var(\'t$i\')")
t.add("t$i")
for (d in 0 until 3) {
val c = "xyz"[d]
val pos = when (c) {
'x' -> posNSpeed.pos.x
'y' -> posNSpeed.pos.y
'z' -> posNSpeed.pos.z
else -> error("")
}
val speed = when (c) {
'x' -> posNSpeed.speed.x
'y' -> posNSpeed.speed.y
'z' -> posNSpeed.speed.z
else -> error("")
}
eqn.add("f$i$d = ${c}g+d${c}g*t${i} == ${pos} + ${speed}*t${i}") // todo return here
fn.add("f$i$d")
}
}
val fns = (fn.joinToString(",") { it })
val ts = t.joinToString(",") { it }
eqn.add("solve([${fns}], [xg,yg,zg,dxg,dyg,dzg,${ts}])")
println(eqn.joinToString("\n") { it })
return eqn.joinToString("\n") { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput, 7f.toBigDecimal()..27f.toBigDecimal())
println(part1Test)
check(part1Test == 2)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input, BigDecimal("200000000000000.0")..BigDecimal("400000000000000.0"))
println(part1)
check(part1 == 15593)
// Part 2
val part2 = part2(input)
println(part2)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 4,895 | KotlinAdventOfCode | Apache License 2.0 |
src/main/kotlin/Day13.kt | SimonMarquis | 570,868,366 | false | {"Kotlin": 50263} | class Day13(val input: List<String>) {
fun part1(): Int = input.windowed(size = 2, step = 3) { (l, r) -> (l to r).parse() }
.withIndex().filter { it.value }
.sumOf { it.index.inc() }
private val dividers = setOf("[[2]]", "[[6]]")
fun part2(): Long = input.asSequence().filter(String::isNotEmpty).plus(dividers)
.sortedWith { o1, o2 -> if ((o1 to o2).parse()) -1 else 1 }
.withIndex().filter { it.value in dividers }
.map { it.index.inc() }.toList()
.product()
private fun String.element(index: Int): IndexedValue<Element?> = when (getOrNull(index)) {
null -> IndexedValue(index, null)
'[' -> IndexedValue(index + 1, Start)
']' -> IndexedValue(index + 1, End)
',' -> element(index.inc())
else -> drop(index).splitToSequence("[", "]", ",").first().let { number ->
IndexedValue(index + number.length, Value(number.toInt()))
}
}
private sealed interface Element
private object Start : Element
private object End : Element
private class Value(val int: Int) : Element
private fun Pair<String, String>.parse(): Boolean {
var (left, right) = this
var indexes = 0 to 0
while (true) {
val (lIdx, l) = left.element(indexes.first)
val (rIdx, r) = right.element(indexes.second)
when {
// Both values are integers
l is Value && r is Value -> {
when {
l.int < r.int -> return true
l.int > r.int -> return false
}
}
// Both values are lists
l is End && r !is End -> return true
r is End && l !is End -> return false
// Mixed types
l is Start && r is Value -> {
right = right.replaceRange(indexes.second, rIdx, "[${r.int}]")
continue
}
l is Value && r is Start -> {
left = left.replaceRange(indexes.first, lIdx, "[${l.int}]")
continue
}
// Both values are Start or End
r == l -> Unit
else -> Unit
}
indexes = indexes.copy(first = lIdx, second = rIdx)
}
}
}
| 0 | Kotlin | 0 | 0 | a2129cc558c610dfe338594d9f05df6501dff5e6 | 2,383 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/Day12.kt | Maetthu24 | 572,844,320 | false | {"Kotlin": 41016} | package year2022
fun main() {
fun part1(input: List<String>): Int {
val letters = "<KEY>"
var start = Pair(0, 0)
var destination = Pair(0, 0)
val visited = mutableListOf<Pair<Int, Int>>()
val grid = input.withIndex().map { (x, line) ->
line.withIndex().map { (y, c) ->
when (c) {
'S' -> {
start = Pair(x, y)
0
}
'E' -> {
destination = Pair(x, y)
25
}
else -> letters.indexOf(c)
}
}
}
val gridX = grid.size
val gridY = grid[0].size
fun Pair<Int, Int>.notVisitedNeighbors(): List<Pair<Int, Int>> {
return buildList {
if (first > 0)
add(Pair(first - 1, second))
if (second > 0)
add(Pair(first, second - 1))
if (first < gridX - 1)
add(Pair(first + 1, second))
if (second < gridY - 1)
add(Pair(first, second + 1))
}.filter { !visited.contains(it) && grid[this.first][this.second] - 1 <= grid[it.first][it.second] }
}
val distances = mutableMapOf<Pair<Int, Int>, Int>()
val queue = mutableListOf<Pair<Int, Int>>()
queue.add(destination)
visited.add(destination)
distances[destination] = 0
while (queue.isNotEmpty()) {
val new = queue.removeFirst()
if (new == start)
break
for (n in new.notVisitedNeighbors()) {
visited.add(n)
distances[n] = distances[new]!! + 1
queue.add(n)
}
}
return distances[start]!!
}
fun part2(input: List<String>): Int {
val letters = "abcdefgh<KEY>"
var start = Pair(0, 0)
var destination = Pair(0, 0)
val visited = mutableListOf<Pair<Int, Int>>()
val grid = input.withIndex().map { (x, line) ->
line.withIndex().map { (y, c) ->
when (c) {
'S' -> {
start = Pair(x, y)
0
}
'E' -> {
destination = Pair(x, y)
25
}
else -> letters.indexOf(c)
}
}
}
val gridX = grid.size
val gridY = grid[0].size
fun Pair<Int, Int>.notVisitedNeighbors(): List<Pair<Int, Int>> {
return buildList {
if (first > 0)
add(Pair(first - 1, second))
if (second > 0)
add(Pair(first, second - 1))
if (first < gridX - 1)
add(Pair(first + 1, second))
if (second < gridY - 1)
add(Pair(first, second + 1))
}.filter { !visited.contains(it) && grid[this.first][this.second] - 1 <= grid[it.first][it.second] }
}
val distances = mutableMapOf<Pair<Int, Int>, Int>()
val queue = mutableListOf<Pair<Int, Int>>()
queue.add(destination)
visited.add(destination)
distances[destination] = 0
var found = Pair(0, 0)
while (queue.isNotEmpty()) {
val new = queue.removeFirst()
if (grid[new.first][new.second] == 0) {
found = new
break
}
for (n in new.notVisitedNeighbors()) {
visited.add(n)
distances[n] = distances[new]!! + 1
queue.add(n)
}
}
return distances[found]!!
}
val day = "12"
// Read inputs
val testInput = readInput("Day${day}_test")
val input = readInput("Day${day}")
// Test & run part 1
val testResult = part1(testInput)
val testExpected = 31
check(testResult == testExpected) { "testResult should be $testExpected, but is $testResult" }
println(part1(input))
// Test & run part 2
val testResult2 = part2(testInput)
val testExpected2 = 29
check(testResult2 == testExpected2) { "testResult2 should be $testExpected2, but is $testResult2" }
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 3b3b2984ab718899fbba591c14c991d76c34f28c | 4,457 | adventofcode-kotlin | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/Day12.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 12: Passage Pathing
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.readFileAsString
fun main() {
println(" ** Day 12: Passage Pathing ** \n")
val caveConnections = readFileAsString("/Day12CaveConnections.txt")
val numberOfPaths = countAllPossiblePathsThroughCaveSystem(caveConnections)
println("The number of possible paths through the system is $numberOfPaths")
val numberOfPathsWithSingleDuplicatedCage = countAllPossiblePathsThroughCaveSystemWithSingleDuplicatedSmallCaveAllowed(caveConnections)
println("The number of possible paths through the system using a single duplicated cave is $numberOfPathsWithSingleDuplicatedCage")
}
fun countAllPossiblePathsThroughCaveSystem(caveConnectionData: String): Int {
val caveConnections = parseCaveConnectionData(caveConnectionData)
val allPaths = findAllPaths(listOf("start"), caveConnections)
return allPaths.size
}
fun countAllPossiblePathsThroughCaveSystemWithSingleDuplicatedSmallCaveAllowed(caveConnectionData: String): Int {
val caveConnections = parseCaveConnectionData(caveConnectionData)
val allPaths = findAllPaths(listOf("start"), caveConnections, true)
return allPaths.size
}
private fun findAllPaths(
pathStart: List<String>,
connections: List<CaveConnection>,
duplicatedSmallCaveAllowed: Boolean = false): List<List<String>> {
val currentCave = pathStart.last()
if (pathStart.last() == "end") return listOf(pathStart)
val allFoundPaths = connections
.filter { it.contains(currentCave) }
.filter { it.otherEnd(currentCave) != "start" }
.filter { caveIsAbleToBePassedThrough(pathStart, it, duplicatedSmallCaveAllowed) }
.map { pathStart.append(it.otherEnd(currentCave)) }
.flatMap { newPath ->
val smallCaveHasBeenDuplicated = newPath.last().isLowerCase() && newPath.count { it == newPath.last() } == 2
findAllPaths(newPath, connections, duplicatedSmallCaveAllowed && !smallCaveHasBeenDuplicated)
}
return if (pathStart.size == 1) allFoundPaths.filter { it.last() == "end" } else allFoundPaths
}
private fun caveIsAbleToBePassedThrough(currentPath: List<String>, nextCaveConnection: CaveConnection, duplicatedSmallCaveAllowed: Boolean) =
nextCaveConnection.otherEnd(currentPath.last()).let {
if (it.isLowerCase() && !duplicatedSmallCaveAllowed) !currentPath.contains(it) else true
}
private fun parseCaveConnectionData(caveConnectionData: String) =
caveConnectionData
.lines()
.map { caveConnection ->
caveConnection.split("-").let { CaveConnection(it[0], it[1]) }
}
data class CaveConnection(val caveA: String, val caveB: String) {
fun contains(cave: String) = caveA == cave || caveB == cave
fun otherEnd(cave: String) = if (caveA == cave) caveB else caveA
}
private fun String.isLowerCase() = this.toCharArray().all { it.isLowerCase() }
private fun <T> List<T>.append(item: T) = this.toMutableList().apply { add(item) }.toList()
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 3,045 | AdventOfCode2021 | MIT License |
src/day12/Day12.kt | Puju2496 | 576,611,911 | false | {"Kotlin": 46156} | package day12
import println
import readInput
import java.util.*
fun main() {
// test if implementation meets criteria from the description, like:
val input = readInput("src/day12", "Day12")
println("Part1")
part1(input)
println("Part2")
part2(input)
}
private fun part1(inputs: List<String>) {
val list = Array(inputs.size) { CharArray(inputs[0].length) }
var startNode = Node(0, 0)
var endNode = Node(0, 0)
inputs.forEachIndexed { i: Int, s: String ->
s.toCharArray().forEachIndexed { j: Int, ch: Char ->
if (ch == 'S')
startNode = Node(i, j)
if (ch == 'E')
endNode = Node(i , j)
list[i][j] = if (ch == 'S') 'a' else if (ch == 'E') 'z' else ch
}
}
val distance = findShortestPath(list, startNode, endNode)
println("distance - $distance")
}
private fun findShortestPath(list: Array<CharArray>, startNode: Node, endNode: Node): Int {
val visited = HashSet<Pair<Int, Int>>()
val queue = ArrayDeque<Node>()
queue.add(startNode)
visited.add(Pair(startNode.row, startNode.col))
while (!queue.isEmpty()) {
val currentNode = queue.pop()
if (currentNode.row == endNode.row && currentNode.col == endNode.col) {
return currentNode.distance
}
val currentChar = list[currentNode.row][currentNode.col]
if (isNext(currentNode.row - 1, currentNode.col, list, currentChar, visited)) {
visited.add(Pair(currentNode.row - 1, currentNode.col))
queue.add(Node(currentNode.row - 1, currentNode.col, currentNode.distance + 1))
}
if (isNext(currentNode.row + 1, currentNode.col, list, currentChar, visited)) {
visited.add(Pair(currentNode.row + 1, currentNode.col))
queue.add(Node(currentNode.row + 1, currentNode.col, currentNode.distance + 1))
}
if (isNext(currentNode.row, currentNode.col - 1, list, currentChar, visited)) {
visited.add(Pair(currentNode.row, currentNode.col - 1))
queue.add(Node(currentNode.row, currentNode.col - 1, currentNode.distance + 1))
}
if (isNext(currentNode.row, currentNode.col + 1, list, currentChar, visited)) {
visited.add(Pair(currentNode.row, currentNode.col + 1))
queue.add(Node(currentNode.row, currentNode.col + 1, currentNode.distance + 1))
}
}
return -1
}
private fun isNext(row: Int, col: Int, list: Array<CharArray>, currentChar: Char, visited: HashSet<Pair<Int, Int>>): Boolean {
if (row !in list.indices || col !in 0 until list[0].size) return false
var isNext = false
val nextChar = list[row][col]
if (currentChar + 1 == nextChar || currentChar >= nextChar) {
if (!visited.contains(Pair(row, col))) {
isNext = true
}
}
return isNext
}
private fun part2(inputs: List<String>) {
val list = Array(inputs.size) { CharArray(inputs[0].length) }
val startNode = ArrayList<Node>()
var endNode = Node(0, 0)
inputs.forEachIndexed { i: Int, s: String ->
s.toCharArray().forEachIndexed { j: Int, ch: Char ->
when (ch) {
'S' -> {
startNode.add(Node(i, j))
list[i][j] = 'a'
}
'a' -> {
startNode.add(Node(i, j))
list[i][j] = ch
}
'E' -> {
endNode = Node(i , j)
list[i][j] = 'z'
}
else -> list[i][j] = ch
}
}
}
var shortestDistance = Int.MAX_VALUE
startNode.forEach {
val distance = findShortestPath(list, it, endNode)
if (distance < shortestDistance && distance > -1)
shortestDistance = distance
}
println("shortest distance - $shortestDistance")
}
data class Node(val row: Int, val col: Int, var distance: Int = 0) | 0 | Kotlin | 0 | 0 | e04f89c67f6170441651a1fe2bd1f2448a2cf64e | 3,995 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | shoresea | 576,381,520 | false | {"Kotlin": 29960} | fun main() {
fun part1(inputs: List<String>): Int {
return inputs.map {
val input = it.split(",")
fullyContainOther(input[0], input[1])
}.count { it }
}
fun part2(inputs: List<String>): Int {
return inputs.map {
val input = it.split(",")
overlaps(input[0], input[1])
}.count { it }
}
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
fun overlaps(r1: String, r2: String): Boolean {
val range1 = r1.split("-").map { it.toInt() }.let { (it[0]..it[1]) }
val range2 = r2.split("-").map { it.toInt() }.let { (it[0]..it[1]) }
return range1.union(range2).size < (range1.toSet().size + range2.toSet().size)
}
fun fullyContainOther(r1: String, r2: String): Boolean {
val range1 = r1.split("-").map { it.toInt() }.let { (it[0]..it[1]) }
val range2 = r2.split("-").map { it.toInt() }.let { (it[0]..it[1]) }
return range1.union(range2) == range1.toSet() || range1.union(range2) == range2.toSet()
} | 0 | Kotlin | 0 | 0 | e5d21eac78fcd4f1c469faa2967a4fd9aa197b0e | 1,050 | AOC2022InKotlin | Apache License 2.0 |
src/main/kotlin/dp/MaxPlusMinus.kt | yx-z | 106,589,674 | false | null | package dp
import util.get
import util.max
import util.min
import util.set
// given a sequence of integers with +/- signs in between
// find the maximum possible value obtained from the sequence (no multiplication) by adding (/)
fun main(args: Array<String>) {
val arr = arrayOf('1', '+', '3', '-', '2', '-', '5', '+', '1', '-', '6', '+', '7')
println(arr.maxPlusMinus())
}
fun Array<Char>.maxPlusMinus(): Int {
// assume that input always starts with a number and ends with a number
// then this[2i] is a digit, for i in 0..(size - 1) / 2
// and this[2i + 1] is a sign, for i in 0 until (size - 1) / 2
val cap = (size - 1) / 2
// let 0 <= i <= j <= cap
// max[i, j] = maximum value obtained from this[2i..2j]
val max = Array(cap + 1) { IntArray(cap + 1) { Int.MIN_VALUE } }
// min[i, j] = minimum value obtained from this[2i..2j]
val min = Array(cap + 1) { IntArray(cap + 1) { Int.MAX_VALUE } }
// the base case is when i == j, max[i, j] == min[i, j] == this[2i]
for (i in 0..cap) {
max[i, i] = this[2 * i].toDigit()
min[i, i] = this[2 * i].toDigit()
}
// first we see that for this[2i..2j], signs appear in 2k + 1, where k in i until j
// note that k != j since o/w 2k + 1 = 2j - 1 > 2j
// so the recursive case is
// max[i, j] = max(max[i, k] + max[k + 1, j], max[i, l] - min[l + 1, j])
// , where k, l in i until j, and this[2k + 1] == '+', this[2l + 1] == '-'
// min[i, j] = min(min[i, k] + min[k + 1, j], min[i, l] - max[l + 1, j])
// , where k, l in i until j, and this[2k + 1] == '+', this[2l + 1] == '-'
// now suppose we want to figure out max[i, j], we need
// max[i, k], i.e. in the max table, in the same row, left of col j
// max[k + 1, j], i.e. in the max table, in the same col, below row i
// min[l + 1, j], i.e. in the min table, in the same col, below row i
// therefore the evaluation order can be
// outer loop: bottom to top
for (i in cap downTo 0) {
// inner loop: left to right
for (j in i + 1..cap) {
// linear searching: no specific order
for (k in i until j) {
if (this[2 * k + 1] == '+') {
// min/max: no specific order
max[i, j] = max(max[i, j], max[i, k] + max[k + 1, j])
min[i, j] = min(min[i, j], min[i, k] + min[k + 1, j])
} else { // this[2 * k + 1] == '-'
max[i, j] = max(max[i, j], max[i, k] - min[k + 1, j])
min[i, j] = min(min[i, j], min[i, k] - max[k + 1, j])
}
}
}
}
return max[0, cap]
}
fun Char.toDigit() = this - '0'
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,457 | AlgoKt | MIT License |
src/Day07.kt | rk012 | 574,169,156 | false | {"Kotlin": 9389} | fun main() {
data class File(
val size: Int,
val name: String,
val dirPath: String
)
data class Filesystem(
val dirs: Set<String>,
val files: Set<File>
)
fun List<String>.parseFileSystem() = drop(1).fold(
Filesystem(emptySet(), emptySet()) to ""
) { (fs, dir), s ->
when {
s.startsWith("$ cd") -> s.split(' ')[2].let { dirName ->
when (dirName) {
"/" -> ""
".." -> dir.split('/').dropLast(1).joinToString("/")
else -> "$dir/$dirName"
}.let { fs to it }
}
s.startsWith("$ ls") -> fs to dir
else -> s.split(' ').let { (type, fname) ->
if (type == "dir") fs.copy(dirs = fs.dirs + "$dir/$fname") to dir
else fs.copy(files = fs.files + File(type.toInt(), fname, dir)) to dir
}
}
}.first
fun Filesystem.getDirSizes() = let { (dirs, files) ->
(dirs + "").map { dir ->
files.filter { it.dirPath.startsWith(dir) }.sumOf { it.size }
}
}
fun part1(input: List<String>) = input.parseFileSystem().getDirSizes().filter { it <= 100_000 }.sum()
fun part2(input: List<String>) = input.parseFileSystem().getDirSizes().let { sizes ->
(30_000_000 - 70_000_000 + sizes.max()).let { minSize ->
sizes.filter { it >= minSize }.min()
}
}
// test if implementation meets criteria from the description, like:
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 | bfb4c56c4d4c8153241fa6aa6ae0e829012e6679 | 1,756 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | import java.util.LinkedList
fun main() {
class Node(val size: Int, val children: List<String>)
fun getFileMap(input: List<String>): Map<String, Node> {
val fileMap = mutableMapOf<String, Node>()
val pathList = LinkedList<String>()
var i = 0
while (i < input.size) {
val splits = input[i].split(" ")
if (splits[1] == "cd") {
if (splits[2] == "..") pathList.removeLast()
else pathList.add(splits[2])
i ++
} else if (splits[1] == "ls") {
i ++
val children = mutableListOf<String>()
while (i < input.size) {
if (input[i].startsWith("$")) break
val parts = input[i].split(" ")
val path = pathList.joinToString("/") + "/" + parts[1]
children += path
if (parts[0] != "dir") {
fileMap[path] = Node(parts[0].toInt(), emptyList())
}
i ++
}
val path = pathList.joinToString("/")
fileMap[path] = Node(-1, children)
}
}
return fileMap
}
fun getDirSizeList(fileMap: Map<String, Node>): List<Int> {
val dirSizeList = mutableListOf<Int>()
fun dfs(path: String): Int {
val node = fileMap[path] ?: return 0
if (node.size != -1) return node.size
val size = node.children.sumOf { dfs(it) }
dirSizeList += size
return size
}
dfs("/")
return dirSizeList
}
fun part1(input: List<String>): Int {
val fileMap = getFileMap(input)
val dirSizeList = getDirSizeList(fileMap)
return dirSizeList.filter { it < 100000 }.sum()
}
fun part2(input: List<String>): Int {
val fileMap = getFileMap(input)
val dirSizeList = getDirSizeList(fileMap)
val needed = 30000000 - (70000000 - dirSizeList.max())
return dirSizeList.filter { it >= needed }.min()
}
println(part1(readInput("data/Day07_test")))
println(part1(readInput("data/Day07")))
println(part2(readInput("data/Day07_test")))
println(part2(readInput("data/Day07")))
}
| 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 2,011 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day09.kt | coolcut69 | 572,865,721 | false | {"Kotlin": 36853} | import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
fun part1(inputs: List<String>): Int {
return followPath(2, inputs)
}
fun part2(inputs: List<String>): Int {
return followPath(10, inputs)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 88)
check(part2(testInput) == 36)
val input = readInput("Day09")
// println(part1(input))
check(part1(input) == 6181)
// println(part2(input))
check(part2(input) == 2386)
}
data class Point(val x: Int = 0, val y: Int = 0) {
fun move(direction: Char): Point =
when (direction) {
'U' -> copy(y = y - 1)
'D' -> copy(y = y + 1)
'L' -> copy(x = x - 1)
'R' -> copy(x = x + 1)
else -> throw IllegalArgumentException("Unknown Direction: $direction")
}
fun moveTowards(other: Point): Point =
Point(
(other.x - x).sign + x,
(other.y - y).sign + y
)
fun touches(other: Point): Boolean =
(x - other.x).absoluteValue <= 1 && (y - other.y).absoluteValue <= 1
}
fun followPath(knots: Int, inputs: List<String>): Int {
val headPath: String = parseInputDay9(inputs)
val rope = Array(knots) { Point() }
val tailVisits = mutableSetOf(Point())
headPath.forEach { direction ->
rope[0] = rope[0].move(direction)
rope.indices.windowed(2, 1) { (head, tail) ->
if (!rope[head].touches(rope[tail])) {
rope[tail] = rope[tail].moveTowards(rope[head])
}
}
tailVisits += rope.last()
}
return tailVisits.size
}
fun parseInputDay9(input: List<String>): String =
input.joinToString("") { row ->
val direction = row.substringBefore(" ")
val numberOfMoves = row.substringAfter(' ').toInt()
direction.repeat(numberOfMoves)
}
| 0 | Kotlin | 0 | 0 | 031301607c2e1c21a6d4658b1e96685c4135fd44 | 1,975 | aoc-2022-in-kotlin | Apache License 2.0 |
kotlin/src/main/kotlin/year2021/Day07.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2021
import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.roundToInt
private fun part1(input: List<Int>): Int {
val median = input[((input.size / 2.0)).roundToInt()]
return input.fold(0) { acc, value -> acc + abs(value - median) }
}
private fun calculateStep(from: Int, to: Int): Int {
var counter = 0
var i = abs(from - to)
while (i > 0) {
counter += i
i--
}
return counter
}
private fun part2(input: List<Int>): Int {
val average = input.fold(0) { acc, value -> acc + value } / input.size.toDouble()
// There should be a mathematician formulae to know which one to choose before calculating them both...
val average1 = floor(average).toInt()
val average2 = ceil(average).toInt()
val fuel1 = input.fold(0) { acc, value -> acc + calculateStep(value, average1) }
val fuel2 = input.fold(0) { acc, value -> acc + calculateStep(value, average2) }
return if (fuel1 < fuel2) fuel1 else fuel2
}
fun main() {
val testInput = readInput("Day07_test")[0].split(",").map { it.toInt() }.sorted()
check(part1(testInput) == 37)
check(part2(testInput) == 168)
val input = readInput("Day07")[0].split(",").map { it.toInt() }.sorted()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 1,318 | advent-of-code | MIT License |
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day21/day21.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2023.day
import eu.janvdb.aocutil.kotlin.point2d.Point2D
import eu.janvdb.aocutil.kotlin.readLines
//const val FILENAME = "input21-test.txt"
const val FILENAME = "input21.txt"
fun main() {
val (map, start) = parseMap(readLines(2023, FILENAME))
var points = setOf(start)
val result = mutableListOf<Int>()
// Take value as indices size/2, size+size/2, 2*size+size/2 to get polynomial
val indices = listOf(map.size / 2, map.size / 2 + map.size, map.size / 2 + 2 * map.size)
(1..indices.last()).forEach {
points = map.takeStep(points)
if (it in indices) {
result.add(points.size)
}
}
println(result)
println(extrapolate(result, (26_501_365L - map.size / 2) / map.size))
}
fun parseMap(lines: List<String>): Pair<Map, Point2D> {
val size = lines.size
val points = (0..<size).asSequence()
.flatMap { y ->
(0..<size).asSequence()
.filter { x -> lines[y][x] != '#' }
.map { x -> Point2D(x, y) }
}
.toSet()
val start = (0..<size).asSequence()
.flatMap { y ->
(0..<size).asSequence()
.filter { x -> lines[y][x] == 'S' }
.map { x -> Point2D(x, y) }
}
.first()
return Pair(Map(size, points), start)
}
fun extrapolate(y: List<Int>, value: Long): Any {
// Taking into account that x[1]=3*x[0] and x[2]=5*x[0] and value = n*x[0]
val a = (y[2] - (2 * y[1]) + y[0]) / 2
val b = y[1] - y[0] - a
val c = y[0]
return value * value * a + value * b + c
}
data class Map(val size: Int, val points: Set<Point2D>) {
fun takeStep(from: Set<Point2D>): Set<Point2D> {
val result = from.asSequence()
.flatMap { point -> sequenceOf(point.left(1), point.right(1), point.up(1), point.down(1)) }
.filter { hasPoint(it) }
.toSet()
return result
}
private fun hasPoint(point: Point2D): Boolean {
val x = point.x % size
val y = point.y % size
val x1 = if (x < 0) x + size else x
val y1 = if (y < 0) y + size else y
return points.contains(Point2D(x1, y1))
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 1,946 | advent-of-code | Apache License 2.0 |
advent-of-code-2022/src/main/kotlin/Day02.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 02: Rock Paper Scissors
//https://adventofcode.com/2022/day/2
import java.io.File
enum class Hand(val opponentCode: Char, val score: Int) {
ROCK('A', 1),
PAPER('B', 2),
SCISSOR('C', 3);
fun versus(opponent: Hand): Boolean {
return when (this) {
ROCK -> opponent == SCISSOR
PAPER -> opponent == ROCK
SCISSOR -> opponent == PAPER
}
}
companion object {
fun fromChar(char: Char): Hand? {
return values().find {
it.opponentCode == char
}
}
}
}
fun main() {
val list = File("src/main/resources/Day02.txt").readLines()
opponentThenYours(list)
opponentThenResult(list)
}
private fun rockPaperScissor(opponent: Hand?, yours: Hand?): Int {
if (opponent == yours) return 3
return if (yours!!.versus(opponent!!)) 6 else 0
}
private fun opponentThenYours(list: List<String>) {
val xyzMap = mapOf('X' to Hand.ROCK, 'Y' to Hand.PAPER, 'Z' to Hand.SCISSOR)
val totalScore = list.sumOf { input ->
val hands = input.split(" ").map { it.toCharArray().first() }
val opponents = Hand.fromChar(hands.first())
val yours = xyzMap[hands.last()]
yours!!.score + rockPaperScissor(opponents, yours)
}
println(totalScore)
}
private fun opponentThenResult(list: List<String>) {
val totalScore = list.sumOf { input ->
val hands = input.split(" ").map { it.toCharArray().first() }
val opponents = Hand.fromChar(hands.first())
val yours = getHandToShow(opponents!!, hands.last())
yours.score + rockPaperScissor(opponents, yours)
}
println(totalScore)
}
private fun getHandToShow(opponent: Hand, result: Char): Hand {
if (result == 'Y') return opponent
return if (result == 'X') {
Hand.values().find {
it != opponent && !it.versus(opponent)
}!!
} else { // if (result == 'Z') {
Hand.values().find {
it.versus(opponent)
}!!
}
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,031 | advent-of-code | Apache License 2.0 |
src/Day02.kt | ivancordonm | 572,816,777 | false | {"Kotlin": 36235} | fun main() {
val scoreMap = mapOf(
Pair("A", "X") to 1 + 3,
Pair("A", "Y") to 2 + 6,
Pair("A", "Z") to 3 + 0,
Pair("B", "X") to 1 + 0,
Pair("B", "Y") to 2 + 3,
Pair("B", "Z") to 3 + 6,
Pair("C", "X") to 1 + 6,
Pair("C", "Y") to 2 + 0,
Pair("C", "Z") to 3 + 3,
)
val choiceMap = mapOf(
Pair("A", "X") to Pair("A", "Z"),
Pair("A", "Y") to Pair("A", "X"),
Pair("A", "Z") to Pair("A", "Y"),
Pair("B", "X") to Pair("B", "X"),
Pair("B", "Y") to Pair("B", "Y"),
Pair("B", "Z") to Pair("B", "Z"),
Pair("C", "X") to Pair("C", "Y"),
Pair("C", "Y") to Pair("C", "Z"),
Pair("C", "Z") to Pair("C", "X"),
)
/*
A, X -> Rock (1)
B, Y -> Paper (2)
C, Z -> Scissors (3)
Rock defeats Scissors, Scissors defeats Paper, Paper defeats Rock
0 loose, 3 draw, 6 win
*/
fun part1(input: List<String>) =
input.mapNotNull { scoreMap[Pair(it.split(" ").first(), it.split(" ").last())] }.sum()
/*
X -> lose
Y -> draw
Z -> win
*/
fun part2(input: List<String>) =
input.mapNotNull { scoreMap[choiceMap[Pair(it.split(" ").first(), it.split(" ").last())]] }.sum()
val testInput = readInput("Day02_test")
val input = readInput("Day02")
println(part1(testInput))
check(part1(testInput) == 15)
println(part1(input))
println(part2(testInput))
check(part2(testInput) == 12)
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | dc9522fd509cb582d46d2d1021e9f0f291b2e6ce | 1,575 | AoC-2022 | Apache License 2.0 |
src/Day24.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | import kotlin.collections.HashSet
fun main() {
class BoundedDirection(private val x: Int, private val y: Int, private var d: Direction) {
fun move(p: Point): Point {
val moved = d.move(p)
if (moved.x > x) return Point(0, p.y)
if (moved.x < 0) return Point(x, p.y)
if (moved.y > y) return Point(p.x, 0)
if (moved.y < 0) return Point(p.x, y)
return moved
}
override fun toString(): String {
return d.d.toString()
}
}
fun generateMoves(p: Point): Sequence<Point> = sequence {
yield(p.move("V"))
yield(p.move(">"))
yield(p.move("^"))
yield(p.move("<"))
yield(p)
}
data class Blizzard(var p: Point, val d: BoundedDirection) {
fun move(): Blizzard = Blizzard(d.move(p), d)
}
fun parseBlizzards(input: List<String>): Pair<List<Blizzard>, Point> {
val lastX = input.size - 3
val lastY = input[0].length - 3
val blizzards = mutableListOf<Blizzard>()
for (row in 1 until input.size - 1) {
input[row].forEachIndexed { column, ch ->
if (ch != '.' && ch != '#') blizzards.add(
Blizzard(
Point(row - 1, column - 1),
BoundedDirection(lastX, lastY, Direction(ch))
)
)
}
}
return blizzards to Point(lastX, lastY)
}
fun movesToExit(start: Point, exit: Point, blizzardsInitial: List<Blizzard>, lastX: Int, lastY: Int): Pair<Int, List<Blizzard>> {
var blizzards = blizzardsInitial
var locations = mutableSetOf(start)
var moves = 0
while (locations.isNotEmpty()) {
blizzards = blizzards.map { it.move() }
locations = locations.flatMap {
if (it == exit) return moves + 1 to blizzards else generateMoves(it)
}
.filterTo(HashSet()) { p -> p.inBounds(lastX, lastY) && blizzards.none { it.p == p } }
moves++
blizzards.forEach { locations.remove(it.p) }
if (locations.isEmpty()) locations.add(start)
}
return -1 to blizzards
}
fun part1(input: List<String>): Int {
val (blizzards, exit) = parseBlizzards(input)
return movesToExit(Point(-1, 0), exit, blizzards, exit.x, exit.y).first
}
fun part2(input: List<String>): Int {
val (blizzards, exit) = parseBlizzards(input)
val (movesToExit, cameToExitBlizzards) = movesToExit(Point(-1, 0), exit, blizzards, exit.x, exit.y)
val (movesToStart, returnedToStartBlizzards) = movesToExit(
Point(exit.x + 1, exit.y),
Point(0, 0),
cameToExitBlizzards,
exit.x, exit.y
)
val (movesToExitAgain, _) = movesToExit(Point(-1, 0), exit, returnedToStartBlizzards, exit.x, exit.y)
return movesToExit + movesToStart + movesToExitAgain
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day24_test")
println(part1(testInput))
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInput("Day24")
println(part1(input))
check(part1(input) == 373)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 3,358 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | Misano9699 | 572,108,457 | false | null | fun main() {
fun fullyContains(range1: Pair<Int,Int>, range2: Pair<Int,Int>) =
range1.first <= range2.first && range1.second >= range2.second || range2.first <= range1.first && range2.second >= range1.second
fun contains(range1: Pair<Int,Int>, range2: Pair<Int, Int>) =
range1.first <= range2.second && range1.second >= range2.first
fun determineRange(elfSections: String): Pair<Int, Int> =
Pair(elfSections.substringBefore("-").toInt(), elfSections.substringAfter("-").toInt())
fun part1(input: List<String>): Int {
return input.map {
fullyContains(determineRange(it.substringBefore(",")), determineRange(it.substringAfter(",")))
}.count { it }
}
fun part2(input: List<String>): Int {
return input.map {
contains(determineRange(it.substringBefore(",")), determineRange(it.substringAfter(",")))
}.count { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val input = readInput("Day04")
check(part1(testInput).also { println("Answer test input part1: $it") } == 2)
println("Answer part1: " + part1(input))
check(part2(testInput).also { println("Answer test input part2: $it") } == 4)
println("Answer part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | adb8c5e5098fde01a4438eb2a437840922fb8ae6 | 1,336 | advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | import java.util.Stack
fun main() {
fun List<String>.readPacketPairs(): List<Pair<DataValue, DataValue>> = plus("")
.chunked(3)
.map { Pair(DataValue.parse(it[0]), DataValue.parse(it[1])) }
fun List<String>.readPackets(): List<DataValue> = filter(String::isNotEmpty)
.map(DataValue.Companion::parse)
fun part1(input: List<String>): Int {
return input.readPacketPairs()
.mapIndexed { index, pair ->
if (pair.first < pair.second) {
index + 1
} else {
0
}
}
.sum()
}
fun part2(input: List<String>): Int {
val divider1 = DataValue.parse("[[2]]")
val divider2 = DataValue.parse("[[6]]")
val packets = input.readPackets().plus(listOf(divider1, divider2)).sorted()
return (packets.indexOf(divider1) + 1) * (packets.indexOf(divider2) + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput).also { println("part1 test: $it") } == 13)
check(part2(testInput).also { println("part2 test: $it") } == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private sealed interface DataValue : Comparable<DataValue> {
data class IntValue(val value: Int) : DataValue {
override fun toString(): String = value.toString()
}
data class ListValue(val value: List<DataValue>) : DataValue {
override fun toString(): String = value.toString()
}
fun IntValue.toList() = ListValue(listOf(this))
override operator fun compareTo(that: DataValue): Int {
when {
this is IntValue && that is IntValue -> {
return this.value.compareTo(that.value)
}
this is ListValue && that is ListValue -> {
repeat(minOf(this.value.size, that.value.size)) { i ->
val comp = this.value[i].compareTo(that.value[i])
if (comp != 0) {
return comp
}
}
return this.value.size.compareTo(that.value.size)
}
else -> when {
this is IntValue -> return this.toList().compareTo(that)
that is IntValue -> return this.compareTo(that.toList())
}
}
error("something wrong")
}
companion object {
fun parse(input: String): DataValue {
val list = input.substring(1, input.lastIndex)
return ListValue(
if (list.isEmpty()) {
emptyList()
} else {
buildList {
var index = 0
while (index < list.length) {
if (list[index] == '[') {
val parenthesis = Stack<Unit>()
parenthesis.push(Unit)
var p = index + 1
while (parenthesis.isNotEmpty()) {
if (list[p] == '[') {
parenthesis.push(Unit)
}
if (list[p] == ']') {
parenthesis.pop()
}
p++
}
add(parse(list.substring(index, p)))
index = p + 1
} else {
var nextIndex = list.indexOf(',', startIndex = index + 1)
if (nextIndex == -1) {
nextIndex = list.lastIndex + 1
}
add(IntValue(list.substring(index, nextIndex).toInt()))
index = nextIndex + 1
}
}
}
}
)
}
}
}
| 0 | Kotlin | 0 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 4,217 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | pimts | 573,091,164 | false | {"Kotlin": 8145} | data class Rucksack(val items: String)
fun Rucksack.uniqueItems() = items.toSet()
fun Rucksack.compartment1() = items.substring(startIndex = 0, endIndex = items.length / 2).toSet()
fun Rucksack.compartment2() = items.substring(startIndex = items.length / 2).toSet()
fun Char.priority() =
if (isLowerCase()) {
this - 'a' + 1
} else {
this - 'A' + 27
}
fun main() {
fun part1(input: List<String>): Int {
return input.map {
val rucksack = Rucksack(it)
rucksack.compartment1() intersect rucksack.compartment2()
}.sumOf { it.single().priority() }
}
fun part2(input: List<String>): Int {
return input.chunked(3) {
val compartment1 = Rucksack(it[0]).uniqueItems()
val compartment2 = Rucksack(it[1]).uniqueItems()
val compartment3 = Rucksack(it[2]).uniqueItems()
compartment1 intersect compartment2 intersect compartment3
}.sumOf {
it.single().priority()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dc7abb10538bf6ad9950a079bbea315b4fbd011b | 1,302 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/org/sjoblomj/adventofcode/day5/Day5.kt | sjoblomj | 161,537,410 | false | null | package org.sjoblomj.adventofcode.day5
import java.io.File
import kotlin.streams.toList
import kotlin.system.measureTimeMillis
private const val inputFile = "src/main/resources/inputs/day5.txt"
fun day5() {
println("== DAY 5 ==")
val timeTaken = measureTimeMillis { calculateAndPrintDay5() }
println("Finished Day 5 in $timeTaken ms\n")
}
private fun calculateAndPrintDay5() {
val content = File(inputFile).readText()
val reducedPolymer = reduce(content)
println("Units left after reactions: ${reducedPolymer.length}")
println("Units left after reactions, once the most problematic unit has been removed: ${removeMostProblematicUnitAndReduce(reducedPolymer).length}")
}
internal fun removeMostProblematicUnitAndReduce(originalPolymer: String): String {
val allUnitsInPolymer = originalPolymer
.toLowerCase()
.chars()
.distinct()
.mapToObj { unit -> unit.toChar() }
.toList()
return allUnitsInPolymer
.map { unit -> removeSingleUnitFromPolymer(originalPolymer, unit) }
.map { polymer -> reduce(polymer) }
.minBy { reducedPolymer -> reducedPolymer.length }
?: throw RuntimeException("Unable to find shortest polymer")
}
internal fun reduce(s: String): String {
var polymer = s.trim()
var i = 0
while (i < polymer.length - 1) {
val unitPair = nextUnitPair(polymer, i)
val unitsReact = unitsReact(unitPair)
if (unitsReact)
polymer = reducePolymer(polymer, unitPair)
i = adjustIndex(i, unitsReact)
}
return polymer
}
private fun nextUnitPair(polymer: String, i: Int) = "${polymer[i]}${polymer[i + 1]}"
private fun unitsReact(unitPair: String) =
unitPair[0].toLowerCase() == unitPair[1].toLowerCase() &&
((unitPair[0].isUpperCase() && unitPair[1].isLowerCase()) ||
(unitPair[0].isLowerCase() && unitPair[1].isUpperCase()))
private fun removeSingleUnitFromPolymer(polymer: String, unit: Char) = polymer.replace(unit.toString(), "", true)
private fun reducePolymer(polymer: String, unitPair: String) = polymer.replace(unitPair, "")
fun adjustIndex(index: Int, unitsReact: Boolean): Int {
return if (unitsReact) {
if (index > 0) index - 1 else 0
} else {
return index + 1
}
}
| 0 | Kotlin | 0 | 0 | 80db7e7029dace244a05f7e6327accb212d369cc | 2,195 | adventofcode2018 | MIT License |
src/Day09.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | import kotlin.math.abs
import kotlin.math.sign
data class Knot(var x: Int, var y: Int, var next: Knot? = null) {
var history = mutableSetOf(0 to 0)
fun move(dir: Direction, count: Int) {
repeat(count) { move(dir) }
}
fun move(dir: Direction) {
when (dir) {
Direction.UP -> x += 1
Direction.DOWN -> x -= 1
Direction.RIGHT -> y += 1
Direction.LEFT -> y -= 1
}
val next = next
if (next != null && !next.isAdjTo(this)) {
next.moveTowards(this)
}
}
fun isAdjTo(other: Knot): Boolean {
return abs( x - other.x) <= 1 && abs(y - other.y) <= 1
}
// called on "tail" only
fun moveTowards(other: Knot) {
other.let {
x += (it.x - x).sign
y += (it.y - y).sign
}
val next = next
if (next != null && !next.isAdjTo(this)) {
next.moveTowards(this)
}
history.add(x to y)
}
}
private data class Command(val dir: Direction, val cnt: Int)
fun main() {
val lines = readInput("Day09")
fun part1(input: List<String>): Int {
val ops = parseOps(input)
val head = Knot(0, 0)
val tail = Knot(0, 0)
head.next = tail
ops.forEach { head.move(it.dir, it.cnt) }
return tail.history.size
}
fun part2(input: List<String>): Int {
val ops = parseOps(input)
val knots = List(10) { Knot (0, 0)}
knots.zipWithNext().forEach { (cur, next) -> cur.next = next }
val head = knots.first()
val tail = knots.last()
ops.forEach { head.move(it.dir, it.cnt) }
return tail.history.size
}
val linesTest = readInput("Day09_test")
println(part1(linesTest))
check(part1(linesTest) == 13)
val linesTest2 = readInput("Day09_test_2")
println(part2(linesTest2))
check(part2(linesTest2) == 36)
println("Part 1")
println(part1(lines))
println("Part 2")
println(part2(lines))
}
private fun parseOps(input: List<String>): List<Command> {
return input.map {
it.split(" ").let { (x, y) ->
Command(
when (x) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
else -> Direction.RIGHT
},
y.toInt()
)
}
}
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 2,450 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/2021/Day8.kt | mstar95 | 317,305,289 | false | null | package `2021`
import days.Day
class Day8 : Day(8) {
val unique = listOf(2, 4, 3, 7)
val numbers = mapOf(
0 to listOf(1, 2, 3, 4, 5, 6),
1 to listOf(2, 3),
2 to listOf(1, 2, 4, 5, 7),
3 to listOf(1, 2, 3, 4, 7),
4 to listOf(2, 3, 6, 7),
5 to listOf(1, 3, 4, 6, 7),
6 to listOf(1, 3, 4, 5, 6, 7),
7 to listOf(1, 2, 3),
8 to listOf(1, 2, 3, 4, 5, 6, 7),
9 to listOf(1, 2, 3, 4, 6, 7),
)
val XD = numbers.map { it.value to it.key }.toMap()
override fun partOne(): Any {
val lines = inputList.map {
it.split("|")
.get(1).split(" ").filter { !it.isBlank() }
}
return lines.map { it.filter { it.length in unique }.size }.sum()
}
override fun partTwo(): Any {
val out = inputList.map {
it.split("|")
.get(1).split(" ").filter { !it.isBlank() }
}
val input = inputList.map {
it.split("|")
.get(0).split(" ").filter { !it.isBlank() }
}
val digits: Map<Int, Char?> = (1..7).map { it to (null as Char?) }.toMap()
val digitsRes: List<Map<Char, Int>> =
input.map { explore(it, digits) }.map {
it.map {
it.value!! to it.key
}.toMap()
}
return digitsRes.zip(out).map { t: Pair<Map<Char, Int>, List<String>> ->
val l: List<String> = t.second.map { s ->
val xd: List<Int> = s.map { c -> t.first[c]!! }.sorted()
XD[xd]!!.toString()
}
val toInt = l.fold("") { a, b -> a + b }.toInt()
toInt
}.sum()
}
fun explore(list: List<String>, digits: Map<Int, Char?>): Map<Int, Char?> {
val uni = list.filter { it.length in unique }.groupBy { it.length }.mapValues { it.value.first() }
val one = uni[2]!!
val seven = uni[3]!!
val pos1 = seven.filter { !one.contains(it) }.first()
val withPos1: Map<Int, Char?> = digits + (1 to pos1)
val firstTry: Map<Int, Char?> = withPos1 + (2 to one.first()) + (3 to one[1])
val secondTry: Map<Int, Char?> = withPos1 + (3 to one.first()) + (2 to one[1])
val r1 = exploreMore(list, firstTry)
if (r1 == null) {
return exploreMore(list, secondTry)!!
}
return r1
}
fun exploreMore(list: List<String>, digits: Map<Int, Char?>): Map<Int, Char?>? {
numbers.forEach { n: Map.Entry<Int, List<Int>> ->
var OK = false
list.forEach { d: String ->
if (d.length == n.value.size) {
var ok = true
n.value.forEach {
val d1 = digits[it]
if (d1 == null) {
d.forEach { i ->
if (i !in digits.values.filterNotNull()) {
val e = exploreMore(list, digits + (it to i))
if (e != null) {
return e
}
}
}
ok = false // O TU BRAKOWALO
} else {
if (!d.contains(d1)) {
ok = false
}
}
}
if (ok) {
OK = true
}
}
}
if (!OK) {
return null
}
}
return digits
}
}
| 0 | Kotlin | 0 | 0 | ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81 | 3,736 | aoc-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/ginsberg/advent2022/Day15.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 15 - Beacon Exclusion Zone
* Problem Description: http://adventofcode.com/2022/day/15
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day15/
*/
package com.ginsberg.advent2022
import kotlin.math.absoluteValue
class Day15(input: List<String>) {
private val sensors: Set<Sensor> = parseInput(input)
fun solvePart1(findRow: Int): Int =
sensors.mapNotNull { it.findRange(findRow) }
.reduce()
.sumOf { it.last - it.first }
fun solvePart2(caveSize: Int): Long {
val cave = (0..caveSize)
return sensors.firstNotNullOf { sensor ->
val up = Point2D(sensor.location.x, sensor.location.y - sensor.distance - 1)
val down = Point2D(sensor.location.x, sensor.location.y + sensor.distance + 1)
val left = Point2D(sensor.location.x - sensor.distance - 1, sensor.location.y)
val right = Point2D(sensor.location.x + sensor.distance + 1, sensor.location.y)
(up.lineTo(right) + right.lineTo(down) + down.lineTo(left) + left.lineTo(up))
.filter { it.x in cave && it.y in cave }
.firstOrNull { candidate -> sensors.none { sensor -> sensor.isInRange(candidate) } }
}.calculateAnswer()
}
private fun Point2D.calculateAnswer(): Long = (x * 4000000L) + y
private class Sensor(val location: Point2D, closestBeacon: Point2D) {
val distance: Int = location.distanceTo(closestBeacon)
fun findRange(y: Int): IntRange? {
val scanWidth = distance - (location.y - y).absoluteValue
return (location.x - scanWidth..location.x + scanWidth).takeIf { it.first <= it.last }
}
fun isInRange(other: Point2D): Boolean =
location.distanceTo(other) <= distance
}
private fun parseInput(input: List<String>): Set<Sensor> =
input
.map { row ->
Sensor(
Point2D(
row.substringAfter("x=").substringBefore(",").toInt(),
row.substringAfter("y=").substringBefore(":").toInt()
),
Point2D(
row.substringAfterLast("x=").substringBefore(",").toInt(),
row.substringAfterLast("=").toInt()
)
)
}.toSet()
}
| 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 2,455 | advent-2022-kotlin | Apache License 2.0 |
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day05.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2022
fun main() {
fun List<ArrayDeque<String>>.printStacks() {
val copy = this.toList().map { ArrayDeque(it) }
println(
(0 until (copy.maxOfOrNull { it.size } ?: 0)).joinToString("\n") {
copy.joinToString { s -> if (s.isNotEmpty()) s.removeLast() else " " }
}
)
}
fun List<ArrayDeque<String>>.toMessage() = this.joinToString("") { it.first().trim('[', ']') }
fun List<String>.toStacks(): List<ArrayDeque<String>> =
this.asSequence()
.takeWhile { !it.contains("1") }
.fold(mutableListOf<ArrayDeque<String>>().also { listOfStacks ->
repeat(this.first().length / 4 + 1) { listOfStacks.add(ArrayDeque()) }
}) { acc, it ->
it.chunked(4)
.asSequence()
.mapIndexed { index, s -> index to s }
.filter { it.second.isNotBlank() }
.forEach { (i, s) -> acc[i].add(s.trim()) }
acc
}
fun List<String>.toProcedures(): List<Triple<Int, Int, Int>> =
this.asSequence()
.dropWhile { !it.contains("move") }
.map {
it.split(" ")
.asSequence()
.filter { it.toIntOrNull() != null }
.map { it.toInt() }
}
.map { it.take(3).toList().let { Triple(it[0], it[1] - 1, it[2] - 1) } }
.toList()
fun part1(input: List<String>): String {
val stacks = input.toStacks()
input.toProcedures().forEach { (count, from, to) ->
repeat(count) {
if (stacks[from].isNotEmpty()) {
stacks[to].addFirst(stacks[from].removeFirst())
}
}
}
return stacks.toMessage()
}
fun part2(input: List<String>): String {
val stacks = input.toStacks()
input.toProcedures().forEach { (count, from, to) ->
if (count < 2) {
stacks[to].addFirst(stacks[from].removeFirst())
} else {
stacks[from].slice(0 until count).reversed().forEach {
stacks[to].addFirst(it)
stacks[from].removeFirst()
}
}
}
return stacks.toMessage()
}
val testInput = readInputLines("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInputLines("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 2,618 | advent-of-code | Apache License 2.0 |
src/Day03.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} | fun main() {
fun getPriority(c: Char): Int {
val asciiCode = c.code
return if (asciiCode >= 'a'.code) {
asciiCode - 'a'.code + 1
} else {
asciiCode - 'A'.code + 27
}
}
fun part1(input: List<String>): Int {
val compartments = input.map {
val midIndex = it.length/2
Pair(it.substring(0,midIndex),it.substring(midIndex))
}
val items: List<Char> = compartments.map { (c1, c2) ->
c1.find { c2.contains(it) }!!
}
val priorities = items.map { getPriority(it) }
return priorities.sum()
}
fun part2(input: List<String>): Int {
val groups = input.chunked(3)
val items: List<Char> = groups.map { chunk ->
chunk[0].find {
chunk[1].contains(it) && chunk[2].contains(it)
}!!
}
val priorities = items.map { getPriority(it) }
return priorities.sum()
}
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 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 1,186 | aoc2022 | Apache License 2.0 |
src/main/kotlin/dec17/Main.kt | dladukedev | 318,188,745 | false | null | package dec17
data class Point2(val x: Int, val y: Int)
data class Point3(val x: Int, val y: Int, val z: Int)
data class Point4(val w: Int, val x: Int, val y: Int, val z: Int)
fun getNeighbors(point: Point3): List<Point3> {
val (x, y, z) = point
return listOf(
Point3(x - 1, y - 1, z - 1),
Point3(x, y - 1, z - 1),
Point3(x + 1, y - 1, z - 1),
Point3(x - 1, y, z - 1),
Point3(x, y, z - 1),
Point3(x + 1, y, z - 1),
Point3(x - 1, y + 1, z - 1),
Point3(x, y + 1, z - 1),
Point3(x + 1, y + 1, z - 1),
Point3(x - 1, y - 1, z),
Point3(x, y - 1, z),
Point3(x + 1, y - 1, z),
Point3(x - 1, y, z),
Point3(x + 1, y, z),
Point3(x - 1, y + 1, z),
Point3(x, y + 1, z),
Point3(x + 1, y + 1, z),
Point3(x - 1, y - 1, z + 1),
Point3(x, y - 1, z + 1),
Point3(x + 1, y - 1, z + 1),
Point3(x - 1, y, z + 1),
Point3(x, y, z + 1),
Point3(x + 1, y, z + 1),
Point3(x - 1, y + 1, z + 1),
Point3(x, y + 1, z + 1),
Point3(x + 1, y + 1, z + 1)
)
}
fun getNeighbors(point: Point4): List<Point4> {
val (w, x, y, z) = point
//w
val points = (-1..1).flatMap { wMod ->
//x
(-1..1).flatMap { xMod ->
//y
(-1..1).flatMap { yMod ->
//z
(-1..1).map { zMod ->
Point4(w + wMod, x + xMod, y + yMod, z + zMod)
}
}
}
}
// Remove Point We are Looking for Neighbors of
return points
.filter {
it != point
}
}
fun parseInput(input: String): HashSet<Point2> {
return input.lines().reversed()
.asSequence()
.mapIndexed { rowIndex, row ->
row.mapIndexed { colIndex, cell ->
val isActive = when (cell) {
'.' -> false
'#' -> true
else -> throw Exception("Invalid Character $cell")
}
Point2(colIndex, rowIndex) to isActive
}
}.flatten()
.filter { it.second }
.map { it.first }
.toHashSet()
}
fun <T> playConwayRound(state: HashSet<T>, getNeighbors: (T) -> List<T>): HashSet<T> {
val nextState = HashSet<T>()
fun getActiveNeighborCount(point: T): Int {
return getNeighbors(point).sumBy { neighbor ->
if (state.contains(neighbor)) {
1
} else {
0
}
}
}
state.map {
val neighbors = getNeighbors(it)
val activeNeighborCount = getActiveNeighborCount(it)
if (activeNeighborCount == 2 || activeNeighborCount == 3) {
nextState.add(it)
}
neighbors
.filter { point -> !state.contains(point) }
.filter { point ->
getActiveNeighborCount(point) == 3
}.forEach { point ->
nextState.add(point)
}
}
return nextState
}
fun play3dConwaysGame(iterations: Int): Int {
val startingState = parseInput(input)
.map { Point3(it.x, it.y, 0) }
.toHashSet()
return (0 until iterations).fold(startingState) { accum, _ ->
playConwayRound(accum) {
getNeighbors(it)
}
}.count()
}
fun play4dConwaysGame(iterations: Int): Int {
val startingState = parseInput(input)
.map { Point4(0, it.x, it.y, 0) }
.toHashSet()
return (0 until iterations).fold(startingState) { accum, _ ->
playConwayRound(accum) {
getNeighbors(it)
}
}.count()
}
fun main() {
println("------------ PART 1 ------------")
val result = play3dConwaysGame(6)
println("result: $result")
println("------------ PART 2 ------------")
val result2 = play4dConwaysGame(6)
println("result: $result2")
} | 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 3,965 | advent-of-code-2020 | MIT License |
src/Day05.kt | AleksanderBrzozowski | 574,061,559 | false | null | fun main() {
data class Instruction(val quantity: Int, val from: Int, val to: Int)
fun readCrates(): Pair<List<ArrayDeque<Char>>, List<Instruction>> {
val input = readInput("Day05_test")
return input.takeWhile { !it.contains("1") }
.reversed()
.foldIndexed(emptyList<ArrayDeque<Char>>()) { index, stacksOfCrates, line ->
val crates = generateSequence(1) { it + 4 }
.takeWhile { it < line.length - 1 }
.map { line[it] }
if (index == 0) {
crates.map { if (it == ' ') ArrayDeque() else ArrayDeque(listOf(it)) }
.toList()
} else {
crates.forEachIndexed { crateIndex, character ->
if (character != ' ') {
stacksOfCrates[crateIndex].addFirst(character)
}
}
stacksOfCrates
}
} to input.reversed().takeWhile { it.isNotBlank() }
.map { line ->
val quantity = line.substringAfter("move ").takeWhile { it.isDigit() }.toInt()
val from = line.substringAfter("from ").takeWhile { it.isDigit() }.toInt()
val to = line.substringAfter("to ").takeWhile { it.isDigit() }.toInt()
Instruction(quantity = quantity, from = from - 1, to = to - 1)
}.reversed()
}
fun applyInstructionsFirstPart(stacksOfCrates: List<ArrayDeque<Char>>, instructions: List<Instruction>) {
instructions.forEach { instruction ->
repeat(instruction.quantity) {
val removed = stacksOfCrates[instruction.from].removeFirst()
stacksOfCrates[instruction.to].addFirst(removed)
}
}
}
fun applyInstructionsSecondPart(stacksOfCrates: List<ArrayDeque<Char>>, instructions: List<Instruction>) {
instructions.forEach { instruction ->
val removed = generateSequence { stacksOfCrates[instruction.from].removeFirst() }
.take(instruction.quantity)
.toList()
.reversed()
removed
.forEach {
stacksOfCrates[instruction.to].addFirst(it)
}
}
}
val (testStacksOfCrates, testInstructions) = readCrates()
applyInstructionsFirstPart(testStacksOfCrates, testInstructions)
println(testStacksOfCrates.joinToString(separator = "") { it.first().toString() })
val (stacksOfCrates, instructions) = readCrates()
applyInstructionsSecondPart(stacksOfCrates, instructions)
println(stacksOfCrates.joinToString(separator = "") { it.first().toString() })
}
| 0 | Kotlin | 0 | 0 | 161c36e3bccdcbee6291c8d8bacf860cd9a96bee | 2,763 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | wujingwe | 574,096,169 | false | null | import java.util.*
fun main() {
fun parse(input: List<String>): Map<Line, List<String>> {
return input.groupBy { s ->
when {
s.isEmpty() -> Line.Space
s.startsWith("move") -> Line.Op
else -> Line.Crate
}
}
}
fun initCargos(crates: List<String>): List<Stack<Char>> {
val stackCount = crates.last().chunked(4).count()
val cargos = mutableListOf<Stack<Char>>().apply {
repeat(stackCount) {
add(Stack())
}
}
crates.reduceRight { line, acc ->
line.chunked(4).forEachIndexed { index, token ->
if (token.contains("[")) {
val cargo = token[1]
cargos[index].push(cargo)
}
}
acc
}
return cargos.toList()
}
fun initOps(ops: List<String>): List<Triple<Int, Int, Int>> {
return ops.map { s ->
val (count, src, dst) = s.split(" ")
.filterIndexed { index, _ -> index == 1 || index == 3 || index == 5 }
.map { it.toInt() }
Triple(count, src, dst)
}
}
fun part1(inputs: List<String>): String {
val groups = parse(inputs)
val crates = groups[Line.Crate]!!
val cargos = initCargos(crates)
val ops = initOps(groups[Line.Op]!!)
ops.forEach { (count, src, dst) ->
repeat(count) {
val cargo = cargos[src - 1].pop()
cargos[dst - 1].push(cargo)
}
}
return cargos.fold(StringBuilder()) { acc, elem ->
acc.append(elem.pop())
}.toString()
}
fun part2(inputs: List<String>): String {
val groups = parse(inputs)
val crates = groups[Line.Crate]!!
val cargos = initCargos(crates)
val ops = initOps(groups[Line.Op]!!)
ops.forEach { (count, src, dst) ->
val temp = Stack<Char>()
repeat(count) {
val cargo = cargos[src - 1].pop()
temp.push(cargo)
}
repeat(count) {
cargos[dst - 1].push(temp.pop())
}
}
return cargos.fold(StringBuilder()) { acc, elem ->
acc.append(elem.pop())
}.toString()
}
val testInput = readInput("../data/Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("../data/Day05")
println(part1(input))
println(part2(input))
}
sealed class Line {
object Space : Line()
object Crate : Line()
object Op : Line()
}
| 0 | Kotlin | 0 | 0 | a5777a67d234e33dde43589602dc248bc6411aee | 2,702 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day18.kt | mikrise2 | 573,939,318 | false | {"Kotlin": 62406} | import java.util.*
fun main() {
val deltas = listOf(
Triple(+1, 0, 0), Triple(-1, 0, 0),
Triple(0, +1, 0), Triple(0, -1, 0),
Triple(0, 0, +1), Triple(0, 0, -1)
)
fun applyDeltas(cube: Triple<Int, Int, Int>): List<Triple<Int, Int, Int>> =
deltas.map { Triple(cube.first + it.first, cube.second + it.second, cube.third + it.third) }
fun lavaCubes(input: List<String>) = input.map {
val split = it.split(',').map { line -> line.toInt() }
Triple(split[0], split[1], split[2])
}.toSet()
fun getAirCubes(lavaCubes: Set<Triple<Int, Int, Int>>): Set<Triple<Int, Int, Int>> {
val airCubes = mutableSetOf<Triple<Int, Int, Int>>()
val visitedCubes = mutableSetOf<Triple<Int, Int, Int>>()
val queue = LinkedList<Triple<Int, Int, Int>>()
queue.add(Triple(30, 30, 30))
while (queue.isNotEmpty()) {
val next = queue.pop()
airCubes.add(next)
visitedCubes.add(next)
applyDeltas(next).forEach {
if (!(kotlin.math.abs(it.first) > 30 || kotlin.math.abs(it.second) > 30 || kotlin.math.abs(it.third) > 30 || it in lavaCubes || it in visitedCubes)) {
queue.add(it)
visitedCubes.add(it)
}
}
}
return airCubes.toSet()
}
fun part1(input: List<String>): Int {
var result = 0
val lavaCubes = lavaCubes(input)
lavaCubes.forEach { cube ->
applyDeltas(cube).forEach {
if (it !in lavaCubes) {
++result
}
}
}
return result
}
fun part2(input: List<String>): Int {
val lavaCubes = lavaCubes(input)
val airCubes = getAirCubes(lavaCubes)
var result = 0
lavaCubes.forEach { cube ->
applyDeltas(cube).forEach {
if (it in airCubes) {
++result
}
}
}
return result
}
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8 | 2,141 | Advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfWaysOfCuttingPizza.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
/**
* 1444. Number of Ways of Cutting a Pizza
* @see <a href="https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/">Source</a>
*/
fun interface NumberOfWaysOfCuttingPizza {
fun ways(pizza: Array<String>, k: Int): Int
}
class NumberOfWaysOfCuttingPizzaPrefixSum : NumberOfWaysOfCuttingPizza {
override fun ways(pizza: Array<String>, k: Int): Int {
val m: Int = pizza.size
val n: Int = pizza[0].length
val dp = Array(k) {
Array(m) {
arrayOfNulls<Int>(n)
}
}
val preSum = Array(m + 1) { IntArray(n + 1) }
for (r in m - 1 downTo 0) {
for (c in n - 1 downTo 0) {
preSum[r][c] =
preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + if (pizza[r][c] == 'A') 1 else 0
}
}
return dfs(m, n, k - 1, 0, 0, dp, preSum)
}
private fun dfs(
m: Int,
n: Int,
k: Int,
r: Int,
c: Int,
dp: Array<Array<Array<Int?>>>,
preSum: Array<IntArray>,
): Int {
if (preSum[r][c] == 0) return 0 // if the remain piece has no apple -> invalid
if (k == 0) return 1 // found valid way after using k-1 cuts
if (dp[k][r][c] != null) return dp[k][r][c]!!
var ans = 0
// cut in horizontal
for (nr in r + 1 until m) {
// cut if the upper piece contains at least one apple
if (preSum[r][c] - preSum[nr][c] > 0) {
ans = (ans + dfs(m, n, k - 1, nr, c, dp, preSum)) % MOD
}
}
// cut in vertical
for (nc in c + 1 until n) {
if (preSum[r][c] - preSum[r][nc] > 0) {
ans = (ans + dfs(m, n, k - 1, r, nc, dp, preSum)) % MOD
}
}
return ans.also { dp[k][r][c] = it }
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,545 | kotlab | Apache License 2.0 |
src/Day15.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | import java.util.stream.IntStream
import kotlin.math.abs
fun main() {
data class Point(val x: Int, val y: Int) {
infix fun distanceTo(beacon: Point) = distanceTo(beacon.x, beacon.y)
fun distanceTo(xx: Int, yy: Int) = abs(x - xx) + abs(y - yy)
}
data class Sensor(val position: Point, val closestBeacon: Point) {
val radius = position distanceTo closestBeacon
}
val regex = "Sensor at x=(.+), y=(.+): closest beacon is at x=(.+), y=(.+)".toRegex()
fun parse(input: List<String>) = input.map {
val (sx, sy, bx, by) = regex.matchEntire(it)!!.destructured.toList().map(String::toInt)
Sensor(Point(sx, sy), Point(bx, by))
}
fun part1(input: List<String>, row: Int): Int {
val sensors = parse(input)
var minX = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
var minY = Int.MAX_VALUE
var maxY = Int.MIN_VALUE
for (sensor in sensors) {
minX = minOf(minX, sensor.position.x - sensor.radius)
maxX = maxOf(maxX, sensor.position.x + sensor.radius)
minY = minOf(minY, sensor.position.y - sensor.radius)
maxY = maxOf(maxY, sensor.position.y + sensor.radius)
}
return IntStream.rangeClosed(minX, maxX).parallel().filter { x ->
val p = Point(x, row)
sensors.any { sensor ->
p != sensor.closestBeacon && sensor.position distanceTo p <= sensor.radius
}
}.count().toInt()
}
fun part2(input: List<String>, max: Int): Long {
val sensors = parse(input)
// idea: if there is only one point not covered by the signal of any sensor,
// it must lie next to the edge of some sensor's signal. iterate over all sensors,
// walk outside its edge and check (conventionally) if the point is outside the
// radius of all sensors.
for (sensor in sensors) {
val (sx, sy) = sensor.position
val walkingDistance = sensor.radius + 1
val fromX = (sx - walkingDistance).coerceAtLeast(0)
val toX = (sx + walkingDistance).coerceAtMost(max)
for (x in fromX..toX) {
val dx = abs(x - sx)
val dy = walkingDistance - dx
// y1 walks along the top half of the "circle"
val y1 = sy - dy
if (y1 in 0..max && sensors.all { it.position.distanceTo(x, y1) > it.radius }) {
return x * 4000000L + y1
}
// y2 walks along the bottom half of the "circle"
val y2 = sy + dy
if (y2 in 0..max && sensors.all { it.position.distanceTo(x, y2) > it.radius }) {
return x * 4000000L + y2
}
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 4000000))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 3,142 | AdventOfCode2022 | Apache License 2.0 |
src/twentytwentytwo/day15/Day15.kt | colinmarsch | 571,723,956 | false | {"Kotlin": 65403, "Python": 6148} | package twentytwentytwo.day15
import readInput
import kotlin.math.abs
fun main() {
// row index -> set of spaces that are covered in that row
val coveredSpots = mutableMapOf<Int, Set<Int>>()
val borderPoints = mutableSetOf<Pair<Int, Int>>()
val beacons = mutableSetOf<Pair<Int, Int>>()
val sensors = mutableSetOf<Triple<Int, Int, Int>>()
fun coverAllSpots(
minDist: Int,
start: Pair<Int, Int>,
) {
if (2000000 in start.second - minDist..start.second + minDist) {
val diff = abs(abs(start.second - 2000000) - minDist)
val cols = (start.first - diff..start.first + diff).filter {
!beacons.contains(Pair(it, 2000000))
}
coveredSpots[2000000] = coveredSpots.getOrDefault(2000000, emptySet()) + cols
}
}
fun uncoverSpots(
minDist: Int,
start: Pair<Int, Int>,
) {
val maxValue = 4000000
for (r in start.second - minDist - 1..start.second + minDist + 1) {
if (r !in 0..maxValue) continue
val diff = abs(abs(start.second - r) - (minDist + 1))
val cols = listOf(start.first - diff, start.first + diff)
for (c in cols) {
if (c !in 0..maxValue) continue
if (!beacons.contains(Pair(c, r))) {
borderPoints.add(Pair(c, r))
}
}
}
}
fun setupSensorsAndKnownBeacons(input: List<String>, uncover: Boolean = false) {
coveredSpots.clear()
input.forEach { line ->
val parts = line.split(" ")
val sx = parts[2].dropLast(1).split("=").last().toInt()
val sy = parts[3].dropLast(1).split("=").last().toInt()
val bx = parts[8].dropLast(1).split("=").last().toInt()
val by = parts[9].split("=").last().toInt()
val minDist = abs(sx - bx) + abs(sy - by)
beacons.add(Pair(bx, by))
sensors.add(Triple(sx, sy, minDist))
if (!uncover) {
coverAllSpots(minDist, Pair(sx, sy))
} else {
uncoverSpots(minDist, Pair(sx, sy))
}
}
}
fun part1(input: List<String>): Int {
setupSensorsAndKnownBeacons(input)
return coveredSpots[2000000]!!.size
}
fun part2(input: List<String>): Long {
setupSensorsAndKnownBeacons(input, true)
for (point in borderPoints) {
if (sensors.all { abs(it.first - point.first) + abs(it.second - point.second) > it.third }) {
return point.first.toLong() * 4000000L + point.second.toLong()
}
}
return 0L
}
val input = readInput("day15", "Day15_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bcd7a08494e6db8140478b5f0a5f26ac1585ad76 | 2,812 | advent-of-code | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.