path
stringlengths 5
169
| owner
stringlengths 2
34
| repo_id
int64 1.49M
755M
| is_fork
bool 2
classes | languages_distribution
stringlengths 16
1.68k
⌀ | content
stringlengths 446
72k
| issues
float64 0
1.84k
| main_language
stringclasses 37
values | forks
int64 0
5.77k
| stars
int64 0
46.8k
| commit_sha
stringlengths 40
40
| size
int64 446
72.6k
| name
stringlengths 2
64
| license
stringclasses 15
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/day07/Day07.kt
|
martin3398
| 572,166,179 | false |
{"Kotlin": 76153}
|
package day07
import readInput
import kotlin.math.min
abstract class Node(var size: Int = 0)
class InnerNode(val parent: InnerNode?) : Node() {
val successors: MutableMap<String, Node> = mutableMapOf()
}
class Leaf(size: Int): Node(size)
fun main() {
fun buildTree(input: List<String>): InnerNode {
val root = InnerNode(null)
var cur = root
var i = 1
while (i < input.size) {
var line = input[i]
if (line == "\$ ls") {
i++
while (i < input.size && !input[i].startsWith("\$")) {
line = input[i]
val name = line.split(" ").last()
cur.successors[name] = if (line.startsWith("dir")) {
InnerNode(cur)
} else {
Leaf(line.split(" ").first().toInt())
}
i++
}
if (cur.successors.all { it.value is Leaf }) {
cur.size = cur.successors.values.sumOf { it.size }
}
continue
} else if (line == "\$ cd ..") {
cur = cur.parent!!
cur.size = cur.successors.values.sumOf { it.size }
} else {
cur = cur.successors[line.split(" ").last()] as InnerNode
}
i++
}
while (cur != root) {
cur = cur.parent!!
cur.size = cur.successors.values.sumOf { it.size }
}
return root
}
fun getTotalSizeUnderThresh(node: Node, thresh: Int = 100000): Int {
if (node is InnerNode) {
return (if (node.size <= thresh) node.size else 0) + node.successors.values.sumOf { getTotalSizeUnderThresh(it, thresh) }
}
return 0
}
fun part1(input: List<String>): Int {
val tree = buildTree(input)
return getTotalSizeUnderThresh(tree)
}
fun findSmallestOverThresh(node: Node, thresh: Int): Int {
if (node is InnerNode) {
val successorMin = node.successors.values.minOf { findSmallestOverThresh(it, thresh) }
if (node.size < thresh) {
return successorMin
}
return min(successorMin, node.size)
}
return Int.MAX_VALUE
}
fun part2(input: List<String>): Int {
val tree = buildTree(input)
val free = 70000000 - tree.size
val target = 30000000 - free
return findSmallestOverThresh(tree, target)
}
fun preprocess(input: List<String>): List<String> = input
// test if implementation meets criteria from the description, like:
val testInput = readInput(7, true)
check(part1(preprocess(testInput)) == 95437)
val input = readInput(7)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) == 24933642)
println(part2(preprocess(input)))
}
| 0 |
Kotlin
| 0 | 0 |
4277dfc11212a997877329ac6df387c64be9529e
| 2,951 |
advent-of-code-2022
|
Apache License 2.0
|
src/y2023/Day17.kt
|
gaetjen
| 572,857,330 | false |
{"Kotlin": 325874, "Mermaid": 571}
|
package y2023
import util.Cardinal
import util.Pos
import util.get
import util.plus
import util.readInput
import util.timingStatistics
import y2022.Day15.manhattanDist
import y2023.Day14.coerce
import java.util.PriorityQueue
object Day17 {
data class Block(
val pos: Pos,
val heatLoss: Int,
)
private fun parse(input: List<String>): List<List<Block>> {
return input.mapIndexed { row, line ->
line.mapIndexedNotNull { col, c ->
Block(
pos = Pos(row, col),
heatLoss = c.digitToInt()
)
}
}
}
data class Step(
val direction: Cardinal,
val totalHeatLoss: Int,
val pos: Pos,
val consecutiveCount: Int,
val history: List<Pos>
) {
fun heuristic(target: Pos): Int {
return totalHeatLoss + pos.manhattanDist(target)
}
}
data class SearchState(
val pos: Pos,
val consecutiveCount: Int,
val direction: Cardinal
)
fun part1(input: List<String>): Int {
val parsed = parse(input)
val target = parsed.last().last().pos
return shortestPath(target, parsed) { step, dir ->
step.consecutiveCount < 3 || dir != step.direction
}.totalHeatLoss
}
private fun shortestPath(target: Pos, parsed: List<List<Block>>, condition: (s: Step, d: Cardinal) -> Boolean): Step {
val queue = PriorityQueue<Step>(compareBy {
it.heuristic(target)
})
queue.add(Step(Cardinal.EAST, 0, Pos(0, 0), 0, listOf(0 to 0)))
var end: Step? = null
val minsSoFar = mutableMapOf(
SearchState(
pos = Pos(0, 0),
consecutiveCount = 0,
direction = Cardinal.EAST
) to 0
)
while (queue.isNotEmpty()) {
val nextToExpand = queue.poll()!!
if (nextToExpand.pos == target) {
end = nextToExpand
break
}
val nexts = expand(nextToExpand, parsed, target, condition).filter {
val searchState = SearchState(
pos = it.pos,
consecutiveCount = it.consecutiveCount,
direction = it.direction
)
if (minsSoFar[searchState] == null || minsSoFar[searchState]!! > it.totalHeatLoss) {
minsSoFar[searchState] = it.totalHeatLoss
true
} else {
false
}
}
queue.addAll(nexts)
}
return end ?: error("didn't find a path")
}
fun expand(step: Step, blocks: List<List<Block>>, target: Pos, condition: (s: Step, d: Cardinal) -> Boolean): List<Step> {
return Cardinal.entries.filter {
it.relativePos + step.direction.relativePos != 0 to 0 &&
it.of(step.pos).coerce(target) == it.of(step.pos) &&
condition(step, it)
}.map {
val newPos = it.of(step.pos)
Step(
direction = it,
totalHeatLoss = step.totalHeatLoss + blocks[newPos].heatLoss,
pos = newPos,
consecutiveCount = if (it == step.direction) step.consecutiveCount + 1 else 1,
history = step.history + newPos
)
}
}
fun part2(input: List<String>): Int {
val parsed = parse(input)
val target = parsed.last().last().pos
return shortestPath(target, parsed) { step, dir ->
dir == step.direction && step.consecutiveCount < 10 || dir != step.direction && step.consecutiveCount >= 4
}.totalHeatLoss
}
}
fun main() {
val testInput = """
2413432311323
3215453535623
3255245654254
3446585845452
4546657867536
1438598798454
4457876987766
3637877979653
4654967986887
4564679986453
1224686865563
2546548887735
4322674655533
""".trimIndent().split("\n")
println("------Tests------")
println(Day17.part1(testInput))
println(Day17.part2(testInput))
println("------Real------")
val input = readInput(2023, 17)
println("Part 1 result: ${Day17.part1(input)}")
println("Part 2 result: ${Day17.part2(input)}")
timingStatistics { Day17.part1(input) }
timingStatistics { Day17.part2(input) }
}
| 0 |
Kotlin
| 0 | 0 |
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
| 4,516 |
advent-of-code
|
Apache License 2.0
|
src/main/kotlin/ru/timakden/aoc/year2015/Day15.kt
|
timakden
| 76,895,831 | false |
{"Kotlin": 321649}
|
package ru.timakden.aoc.year2015
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 15: Science for Hungry People](https://adventofcode.com/2015/day/15).
*/
object Day15 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2015/Day15")
println("Part One: ${solve(input)}")
println("Part Two: ${solve(input, true)}")
}
}
fun solve(input: List<String>, isPartTwo: Boolean = false): Int {
var highest = Int.MIN_VALUE
val regex = "\\w+:|-?\\d".toRegex()
val ingredients = input.map { Ingredient(regex.findAll(it).map { matchResult -> matchResult.value }.toList()) }
var capacity: Int
var durability: Int
var flavor: Int
var texture: Int
var calories: Int
var total: Int
// TODO: Переделать
(1..100).forEach { i ->
(1..100 - i).forEach { j ->
(1..100 - i - j).forEach { k ->
for (l in 1..100 - i - j - k) {
if (i + j + k + l == 100) {
capacity = ingredients.map { it.capacity }
.zip(listOf(i, j, k, l)).sumOf { it.first * it.second }
durability = ingredients.map { it.durability }
.zip(listOf(i, j, k, l)).sumOf { it.first * it.second }
flavor = ingredients.map { it.flavor }
.zip(listOf(i, j, k, l)).sumOf { it.first * it.second }
texture = ingredients.map { it.texture }
.zip(listOf(i, j, k, l)).sumOf { it.first * it.second }
calories = ingredients.map { it.calories }
.zip(listOf(i, j, k, l)).sumOf { it.first * it.second }
total = if (listOf(capacity, durability, flavor, texture).all { it > 0 })
listOf(capacity, durability, flavor, texture).fold(1) { acc, i -> acc * i }
else 0
when (isPartTwo) {
true -> if (total > highest && calories == 500) highest = total
else -> if (total > highest) highest = total
}
} else if (i + j + k + l > 100) break
}
}
}
}
return highest
}
data class Ingredient(
var name: String,
var capacity: Int,
var durability: Int,
var flavor: Int,
var texture: Int,
var calories: Int
) {
constructor(split: List<String>) : this(
split[0].removeSuffix(":"),
split[1].toInt(),
split[2].toInt(),
split[3].toInt(),
split[4].toInt(),
split[5].toInt()
)
}
}
| 0 |
Kotlin
| 0 | 3 |
acc4dceb69350c04f6ae42fc50315745f728cce1
| 3,041 |
advent-of-code
|
MIT License
|
src/main/kotlin/aoc2023/Day04.kt
|
Ceridan
| 725,711,266 | false |
{"Kotlin": 110767, "Shell": 1955}
|
package aoc2023
import kotlin.math.pow
class Day04 {
fun part1(input: List<String>): Int = input
.sumOf { Card.fromString(it).calculatePoints() }
fun part2(input: List<String>): Int {
val cards = input.map { line -> Card.fromString(line) }
val counts = IntArray(cards.size) { _ -> 1 }
for (card in cards) {
for (j in card.id..<card.id + card.countMatches()) {
if (j >= counts.size) break
counts[j] += counts[card.id - 1]
}
}
return counts.sum()
}
class Card(val id: Int, val winning: Set<Int>, val selected: Set<Int>, var count: Int = 1) {
fun countMatches(): Int {
return winning.intersect(selected).size
}
fun calculatePoints(): Int {
val matches = countMatches()
return if (matches == 0) 0 else 2.0.pow(matches - 1).toInt()
}
companion object {
fun fromString(card: String): Card {
val cardRegex = "^Card +(\\d+): (.*)$".toRegex()
val (cardId, cardResults) = cardRegex.find(card)!!.destructured
val (winningString, selectedString) = cardResults.split("|")
val winning = winningString.split(' ').filter { it.isNotEmpty() }.map { it.toInt() }.toSet()
val selected = selectedString.split(' ').filter { it.isNotEmpty() }.map { it.toInt() }.toSet()
return Card(cardId.toInt(), winning = winning, selected = selected)
}
}
}
}
fun main() {
val day04 = Day04()
val input = readInputAsStringList("day04.txt")
println("04, part 1: ${day04.part1(input)}")
println("04, part 2: ${day04.part2(input)}")
}
| 0 |
Kotlin
| 0 | 0 |
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
| 1,752 |
advent-of-code-2023
|
MIT License
|
src/com/kingsleyadio/adventofcode/y2022/day07/Solution.kt
|
kingsleyadio
| 435,430,807 | false |
{"Kotlin": 134666, "JavaScript": 5423}
|
package com.kingsleyadio.adventofcode.y2022.day07
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val fs = buildFs()
part1(fs)
part2(fs)
}
fun part1(root: Fs) {
var partialSum = 0
root.sumWithATwist(100_000, true) { partialSum += it }
println(partialSum)
}
fun part2(root: Fs) {
val usedSpace = root.size
val availableSpace = 70_000_000 - usedSpace
val neededSpace = 30_000_000 - availableSpace
var toDelete = Int.MAX_VALUE
root.sumWithATwist(neededSpace, false) { toDelete = minOf(toDelete, it) }
println(toDelete)
}
fun Fs.sumWithATwist(limit: Int, checkBelow: Boolean, onHit: (Int) -> Unit): Int {
return when (this) {
is Fs.Directory -> {
val sum = children().sumOf { it.sumWithATwist(limit, checkBelow, onHit) }
if (checkBelow) {
if (sum <= limit) onHit(sum)
} else {
if (sum >= limit) onHit(sum)
}
sum
}
is Fs.File -> size
}
}
private fun buildFs(): Fs {
val root = Fs.Directory("/", null)
var current: Fs.Directory = root
readInput(2022, 7).forEachLine { line ->
val splits = line.split(" ")
if (splits[0] == "$") { // Command
if (splits[1] == "cd") current = when (val destination = splits[2]) {
"/" -> root
".." -> current.parent!!
else -> current.child(destination) as Fs.Directory
}
} else if (splits[0] == "dir") { // Directory listing
current.addChild(Fs.Directory(splits[1], current))
} else { // File listing
current.addChild(Fs.File(splits[1], current, splits[0].toInt()))
}
}
return root
}
sealed interface Fs {
val name: String
val parent: Directory?
val size: Int
class Directory(
override val name: String,
override val parent: Directory?,
) : Fs {
private val children = hashMapOf<String, Fs>()
fun addChild(child: Fs) = children.put(child.name, child)
fun child(name: String) = children.getValue(name)
fun children() = children.values
override val size get() = children.values.sumOf { it.size }
}
class File(
override val name: String,
override val parent: Directory?,
override val size: Int
) : Fs
}
| 0 |
Kotlin
| 0 | 1 |
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
| 2,393 |
adventofcode
|
Apache License 2.0
|
solutions/aockt/y2021/Y2021D15.kt
|
Jadarma
| 624,153,848 | false |
{"Kotlin": 435090}
|
package aockt.y2021
import io.github.jadarma.aockt.core.Solution
import java.util.PriorityQueue
object Y2021D15 : Solution {
/** Represents a discrete point in 2D space. */
private data class Point(val x: Int, val y: Int)
/** A 2D map of risk levels, used for navigation. */
private class ChironRiskMap(val width: Int, val height: Int, private val risk: IntArray) {
operator fun get(point: Point): Int = risk[point.x * width + point.y]
private operator fun contains(point: Point): Boolean = with(point) { x in 0 until height && y in 0 until width }
/** Returns the points that are orthogonally adjacent to this [point] (valid point coordinates assumed). */
private fun neighborsOf(point: Point): List<Point> = buildList(4) {
if (point.x > 0) add(Point(point.x - 1, point.y))
if (point.x < height - 1) add(Point(point.x + 1, point.y))
if (point.y > 0) add(Point(point.x, point.y - 1))
if (point.y < width - 1) add(Point(point.x, point.y + 1))
}
/**
* Calculates the shortest path between the [start] and [end] points, and returns the path and the total risk.
* If no such path exists, the list is empty and the total risk is `-1`.
*/
fun shortestPathBetween(start: Point, end: Point): Pair<List<Point>, Int> {
require(start in this && end in this)
val distance = mutableMapOf<Point, Int>().withDefault { Int.MAX_VALUE }
val previous = mutableMapOf<Point, Point>()
val queue = PriorityQueue<Point> { a, b -> distance.getValue(a) compareTo distance.getValue(b) }
distance[start] = 0
queue.add(start)
while (queue.isNotEmpty()) {
val point = queue.remove()
if (point == end) break
neighborsOf(point).forEach { neighbor ->
val altCost = distance.getValue(point) + this[neighbor]
if (altCost < distance.getValue(neighbor)) {
val isInQueue = distance[neighbor] != null
distance[neighbor] = altCost
previous[neighbor] = point
if (!isInQueue) queue.add(neighbor)
}
}
}
return when (val totalRisk = distance[end]) {
null -> emptyList<Point>() to -1
else -> buildList {
var current = end.also { add(it) }
while (current != start) current = previous.getValue(current).also { add(it) }
}.reversed() to totalRisk
}
}
}
/** Parse the input and return the [ChironRiskMap] as received from the submarine sensors. */
private fun parseInput(input: String): ChironRiskMap {
var width = -1
var height = 0
val risk = input
.lineSequence()
.onEach { if (width == -1) width = it.length else require(it.length == width) }
.onEach { height++ }
.flatMap { line -> line.map { it.digitToInt() } }
.toList()
.toIntArray()
return ChironRiskMap(width, height, risk)
}
override fun partOne(input: String) =
parseInput(input)
.run { shortestPathBetween(Point(0, 0), Point(width - 1, height - 1)) }
.second
override fun partTwo(input: String): Any {
val map = parseInput(input)
val scale = 5
val biggerMap = ChironRiskMap(
width = map.width * scale,
height = map.height * scale,
risk = IntArray(map.width * scale * map.height * scale) { index ->
val point = Point(index / (map.height * scale), index % (map.width * scale))
val pointInOriginal = Point(point.x % map.height, point.y % map.width)
var risk = map[pointInOriginal]
risk += point.x / map.height; if (risk > 9) risk -= 9
risk += point.y / map.width; if (risk > 9) risk -= 9
risk
},
)
return biggerMap
.run { shortestPathBetween(Point(0, 0), Point(width - 1, height - 1)) }
.second
}
}
| 0 |
Kotlin
| 0 | 3 |
19773317d665dcb29c84e44fa1b35a6f6122a5fa
| 4,276 |
advent-of-code-kotlin-solutions
|
The Unlicense
|
src/main/kotlin/day15/Chiton.kt
|
Arch-vile
| 433,381,878 | false |
{"Kotlin": 57129}
|
package day15
import utils.Cursor
import utils.Matrix
import utils.graphs.Node
import utils.graphs.shortestPath
import utils.read
fun main() {
solve().let { println(it) }
}
fun solve(): List<Long> {
val data = read("./src/main/resources/day15Input.txt")
.map { it.windowed(1, 1).map { it.toInt() } }
val dataMatrix = Matrix(data)
return listOf(
solve1(dataMatrix),
solve2(dataMatrix)
)
}
private fun toNodeMatrix(dataMatrix: Matrix<Int>): Matrix<Node<Pair<Cursor, Int>>> {
val matrix = dataMatrix.map { Node(Pair(it.cursor, it.value)) }
matrix.all().map { current ->
val neighbourghs = matrix.getRelativeAt(
current.cursor,
listOf(Cursor(0, -1), Cursor(-1, 0), Cursor(1, 0), Cursor(0, 1))
)
neighbourghs.forEach { neighbour ->
current.value.link(neighbour.value.value.second.toLong(), neighbour.value)
}
}
return matrix
}
fun solve1(dataMatrix: Matrix<Int>): Long {
val matrix = toNodeMatrix(dataMatrix)
return shortestPath(
matrix.get(0, 0).value,
matrix.get(matrix.width() - 1, matrix.height() - 1).value
)!!
}
fun solve2(inputMatrix: Matrix<Int>): Long {
val dataMatrix =
Matrix(inputMatrix.width().toLong() * 5, inputMatrix.height().toLong() * 5) { x, y -> 0 }
var startFrom = inputMatrix
for (y in 0..4) {
var next = startFrom
for (x in 0..4) {
dataMatrix.combine(
next,
Cursor(x * inputMatrix.width(), y * inputMatrix.height())
) { existing, new -> new.value }
next = duplicate(next)
}
startFrom = duplicate(startFrom)
}
val matrix = toNodeMatrix(dataMatrix)
return shortestPath(
matrix.get(0, 0).value,
matrix.get(matrix.width() - 1, matrix.height() - 1).value
)!!
}
private fun duplicate(matrix: Matrix<Int>) = matrix.map {
val newValue = it.value + 1
if (newValue > 9) 1 else newValue
}
| 0 |
Kotlin
| 0 | 0 |
4cdafaa524a863e28067beb668a3f3e06edcef96
| 2,024 |
adventOfCode2021
|
Apache License 2.0
|
src/day04/Day04.kt
|
lpleo
| 572,702,403 | false |
{"Kotlin": 30960}
|
package day04
import readInput
fun main() {
fun part1(input: List<String>): Int {
return input
.asSequence()
.map { row -> row.split(",") }
.map { assignments -> assignments.map { assignment -> assignment.split("-") } }
.map { assignments -> assignments.map { assignment -> arrayOf(assignment[0].toInt(), assignment[1].toInt()) } }
.filter { assignments ->
(assignments[0][0] <= assignments[1][0] && assignments[0][1] >= assignments[1][1]) ||
(assignments[1][0] <= assignments[0][0] && assignments[1][1] >= assignments[0][1])
}.count();
}
fun part2(input: List<String>): Int {
return input
.asSequence()
.map { row -> row.split(",") }
.map { assignments -> assignments.map { assignment -> assignment.split("-") } }
.map { assignments -> assignments.map { assignment -> arrayOf(assignment[0].toInt(), assignment[1].toInt()) } }
.filter { assignments ->
(assignments[1][0] <= assignments[0][0] && assignments[0][0] <= assignments[1][1]) ||
(assignments[1][0] <= assignments[0][1] && assignments[0][1] <= assignments[1][1]) ||
(assignments[0][0] <= assignments[1][0] && assignments[1][0] <= assignments[0][1]) ||
(assignments[0][0] <= assignments[1][1] && assignments[1][1] <= assignments[0][1])
}.count();
}
val testInput = readInput("files/Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("files/Day04")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
115aba36c004bf1a759b695445451d8569178269
| 1,799 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day07.kt
|
Redstonecrafter0
| 571,787,306 | false |
{"Kotlin": 19087}
|
class VFile(val name: String, val size: Int = -1) {
val children: MutableMap<String, VFile> = mutableMapOf()
val isDir: Boolean
get() = size < 0
val dirSize: Int
get() = if (isDir) children.values.sumOf { it.dirSize } else size
override fun toString(): String {
return "VFile(name=$name, size=$size, dirSize=$dirSize, isDir=$isDir)"
}
fun resolve(path: List<String>): VFile {
return if (path.isEmpty()) {
this
} else {
children.values.first { it.name == path.first() }.resolve(path.subList(1, path.size))
}
}
fun flat(): List<VFile> {
return listOf(this) + children.map { (_, v) -> v.flat() }.flatten()
}
}
fun main() {
fun buildFileTree(input: List<String>): VFile {
val dirStack = mutableListOf<String>()
val root = VFile("/")
for (i in input) {
if (i.startsWith("$ ")) {
val cmd = i.substring(2).split(" ")
if (cmd[0] == "cd") {
when (cmd[1]) {
"/" -> dirStack.clear()
".." -> dirStack.removeLast()
else -> dirStack += cmd[1]
}
}
} else {
val (size, name) = i.split(" ")
if (size == "dir") {
root.resolve(dirStack).children += name to VFile(name)
} else {
root.resolve(dirStack).children += name to VFile(name, size.toInt())
}
}
}
return root
}
fun part1(input: List<String>): Int {
val root = buildFileTree(input)
return root.flat().filter { it.isDir && it.dirSize in 0..100000 }.sumOf { it.dirSize }
}
fun part2(input: List<String>): Int {
val root = buildFileTree(input)
val missingFree = 30000000 - (70000000 - root.dirSize)
return root.flat().filter { it.isDir && it.dirSize >= missingFree }.minBy { it.dirSize }.dirSize
}
// 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 |
e5dbabe247457aabd6dd0f0eb2eb56f9e4c68858
| 2,347 |
Advent-of-Code-2022
|
Apache License 2.0
|
y2015/src/main/kotlin/adventofcode/y2015/Day15.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2015
import adventofcode.io.AdventSolution
object Day15 : AdventSolution(2015, 15, "Science for Hungry People") {
override fun solvePartOne(input: String): Int {
val ingredients = parseInput(input)
return partition(100)
.map { ingredients.zip(it, Ingredient::scale).reduce(Ingredient::plus) }
.maxOf(Ingredient::score)
}
override fun solvePartTwo(input: String): Int {
val ingredients = parseInput(input)
return partition(100)
.map { ingredients.zip(it, Ingredient::scale).reduce(Ingredient::plus) }
.filter { it.calories == 500 }
.maxOf(Ingredient::score)
}
private fun partition(max: Int) = sequence {
for (a in 0..max)
for (b in 0..max - a) {
for (c in 0..max - a - b) {
val d = max - a - b - c
yield(listOf(a, b, c, d))
}
}
}
}
private fun parseInput(distances: String) = distances.lines()
.mapNotNull {
Regex("(\\w+): capacity (-?\\d+), durability (-?\\d+), flavor (-?\\d+), texture (-?\\d+), calories (-?\\d+)").matchEntire(
it
)
}
.map { it.destructured }
.map { (name, cap, d, f, t, cal) ->
Ingredient(name, cap.toInt(), d.toInt(), f.toInt(), t.toInt(), cal.toInt())
}
data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
) {
fun scale(n: Int) = Ingredient(
this.name,
this.capacity * n,
this.durability * n,
this.flavor * n,
this.texture * n,
this.calories * n
)
infix operator fun plus(b: Ingredient) = Ingredient(
"cookie",
this.capacity + b.capacity,
this.durability + b.durability,
this.flavor + b.flavor,
this.texture + b.texture,
this.calories + b.calories
)
fun score() = this.capacity.coerceAtLeast(0) *
this.durability.coerceAtLeast(0) *
this.flavor.coerceAtLeast(0) *
this.texture.coerceAtLeast(0)
}
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 2,186 |
advent-of-code
|
MIT License
|
src/Day07.kt
|
zfz7
| 573,100,794 | false |
{"Kotlin": 53499}
|
val sizes = mutableMapOf<String, Int>()
val folders = mutableMapOf<String, List<String>>()
fun main() {
setUp(readFile("Day07"))
println(folders)
println(sizes)
println(day7A())
println(day7B())
}
fun day7A(): Int = sizes.toList().sumOf {if(!it.first.contains("FILE") && it.second<=100000) it.second else 0}
fun day7B(): Int {
val spaceNeeded = -(70000000 - 30000000 - sizes["/"]!!)
return sizes.toList().filter { it.second > spaceNeeded }.sortedBy { it.second }.first().second
}
fun setUp(input: String) {
val cmds = input.split("\n")
val dirTrace = ArrayDeque<String>()
cmds.forEach {
if(it == "$ cd .."){
dirTrace.removeFirst()
}
if (it =="$ cd /") {
folders["/"] = listOf()
dirTrace.addFirst("/")
}
if (it.startsWith("$ cd ") && it != "$ cd .." && it != "$ cd /") {
dirTrace.addFirst(it.substring(5))
folders[dirTrace.reversed().joinToString (separator = "/",postfix="")] = listOf()
}
if (it.startsWith("dir ")) {
folders[dirTrace.reversed().joinToString (separator = "/",postfix="")] = folders[dirTrace.reversed().joinToString (separator = "/",postfix="")]!!.plus(listOf(dirTrace.reversed().joinToString (separator = "/",postfix="")+"/"+ it.substring(4)))
}
if (it.split(" ")[0].toIntOrNull() != null) {
sizes[dirTrace.reversed().joinToString (separator = "/",postfix="") + "/FILE_" + it.split(" ")[1]] = it.split(" ")[0].toInt()
folders[dirTrace.reversed().joinToString (separator = "/",postfix="")] = folders[dirTrace.reversed().joinToString (separator = "/",postfix="")]!!.plus(listOf(dirTrace.reversed().joinToString (separator = "/",postfix="")+ "/FILE_" + it.split(" ")[1]))
}
}
calcDirSizes("/")
}
fun calcDirSizes(dir: String): Int {
sizes[dir] = folders[dir]!!.sumOf { item: String ->
if (sizes.containsKey(item))
sizes[item]!!
else {
sizes[item] = calcDirSizes(item)
sizes[item]!!
}
}
return sizes[dir]!!
}
| 0 |
Kotlin
| 0 | 0 |
c50a12b52127eba3f5706de775a350b1568127ae
| 2,124 |
AdventOfCode22
|
Apache License 2.0
|
src/Day02.kt
|
astrofyz
| 572,802,282 | false |
{"Kotlin": 124466}
|
fun main() {
fun part1(input: List<String>): Int {
val scoreMap = mapOf("X" to 1, "Y" to 2, "Z" to 3)
val gameMap = mapOf("A Y" to 6, "B Z" to 6, "C X" to 6, "A X" to 3, "B Y" to 3, "C Z" to 3)
var totalSum = 0
for (game in input){
totalSum += gameMap.getOrDefault(game, 0) + scoreMap.getOrDefault(game.split(" ")[1], 0)
}
return totalSum
}
fun part2(input: List<String>): Int {
val scoreMap = mapOf("A" to 1, "B" to 2, "C" to 3)
val scoreGameMap = mapOf("X" to 0, "Y" to 3, "Z" to 6)
infix fun Int.modulo(modulus: Int): Int {
val remainder = this % modulus
return if (remainder >= 0) remainder else remainder + modulus
}
val gameRule = listOf("A", "B", "C")
val dirMap = mapOf("X" to -1, "Y" to 0, "Z" to 1)
var totalSum = 0
for (game in input){
val (elfTurn, turnRes) = game.split(" ")
val idxNew = gameRule.indexOf(elfTurn)+dirMap.getOrDefault(turnRes, 0)
val myTurn = gameRule[idxNew modulo gameRule.size]
totalSum += scoreMap.getOrDefault(myTurn, 0) + scoreGameMap.getOrDefault(turnRes, 0)
}
return totalSum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
| 1,486 |
aoc22
|
Apache License 2.0
|
src/Day15.kt
|
ricardorlg-yml
| 573,098,872 | false |
{"Kotlin": 38331}
|
import kotlin.math.abs
val numberRegex = """(-?\d+)""".toRegex()
class Day15Solver(private val data: List<String>) {
private var minX = 0L
private var maxX = 0L
private val sensors = parseInput()
class Sensor(
val sensorX: Long,
val sensorY: Long,
private val closestBeaconX: Long,
private val closetBeaconY: Long,
) {
val distance = abs(closestBeaconX - sensorX) + abs(closetBeaconY - sensorY)
fun distanceTo(x: Long, y: Long) = abs(sensorX - x) + abs(sensorY - y)
fun isClosestBeacon(x: Long, y: Long) = closestBeaconX == x && closetBeaconY == y
override fun toString(): String {
return "Sensor location: $sensorX, $sensorY Distance: $distance"
}
}
private fun isNotAvailableSpot(sensor: Sensor, x: Long, y: Long): Boolean {
return !sensor.isClosestBeacon(x, y) && sensor.distance >= sensor.distanceTo(x, y)
}
private fun validSpot(x: Long, y: Long): Boolean {
return sensors.none { it.distanceTo(x, y) <= it.distance }
}
private fun parseInput(): List<Sensor> {
var maxDistance = Long.MIN_VALUE
var minBeaconX = Long.MAX_VALUE
var maxBeaconX = Long.MIN_VALUE
return data.map { line ->
val (sx, sy, bx, by) = numberRegex.findAll(line).map { it.groupValues[1].toLong() }.toList()
val sensor = Sensor(sx, sy, bx, by)
minBeaconX = minOf(minBeaconX, bx)
maxBeaconX = maxOf(maxBeaconX, bx)
maxDistance = maxOf(maxDistance, sensor.distance)
minX = minBeaconX - maxDistance
maxX = maxBeaconX + maxDistance
sensor
}
}
fun solvePart1(row: Long): Long {
return (minX..maxX).fold(0L) { unavailableSpots, col ->
if (sensors.any { isNotAvailableSpot(it, col, row) })
unavailableSpots + 1
else
unavailableSpots
}
}
/**
* given that only 1 beacon is available then it should be at distance + 1 from any sensor
* so just iterate over all points that are at distance + 1 from any sensor and check if the position is available
*/
fun solvePart2(max: Long): Long {
val multiplier = 4_000_000L
for (sensor in sensors) {
for (xDistance in 0..sensor.distance) {
val yDistance = sensor.distance + 1 - xDistance
//check all possible combinations of x and y distance which means sensor x plus or minus new distance and sensor y plus or minus new distance
signs.map { (signX, signY) ->
sensor.sensorX + xDistance * signX to sensor.sensorY + yDistance * signY
}.filter { (beaconX, beaconY) ->
beaconX in 0..max && beaconY in 0..max
}.firstOrNull { (beaconX, beaconY) ->
validSpot(beaconX, beaconY)
}?.let { (beaconX, beaconY) ->
return beaconX * multiplier + beaconY
}
}
}
throw IllegalStateException("No valid spot found")
}
}
fun main() {
// val data = readInput("Day15_test")
val data = readInput("Day15")
val solver = Day15Solver(data)
// println(solver.solvePart1(10))
// println(solver.solvePart2(20))
println(solver.solvePart1(2_000_000))
println(solver.solvePart2(4_000_000))
}
| 0 |
Kotlin
| 0 | 0 |
d7cd903485f41fe8c7023c015e4e606af9e10315
| 3,441 |
advent_code_2022
|
Apache License 2.0
|
src/poyea/aoc/mmxxii/day12/Day12.kt
|
poyea
| 572,895,010 | false |
{"Kotlin": 68491}
|
package poyea.aoc.mmxxii.day12
import kotlin.Int.Companion.MAX_VALUE
import kotlin.collections.ArrayDeque
import kotlin.collections.HashSet
import poyea.aoc.utils.readInput
fun find_start(grid: List<CharArray>, pred: (c: Char) -> Boolean): List<Pair<Int, Int>> {
val start_points = mutableListOf<Pair<Int, Int>>()
grid.forEachIndexed { i, it ->
it.forEachIndexed { j, ij ->
if (pred(ij)) {
start_points.add(Pair(i, j))
}
}
}
return start_points
}
fun inside(grid: List<CharArray>, point: Pair<Int, Int>): Boolean {
return point.first >= 0 &&
point.second >= 0 &&
point.first < grid.size &&
point.second < grid[0].size
}
fun get_neighbour(grid: List<CharArray>, point: Pair<Int, Int>): List<Pair<Int, Int>> {
val lst = mutableListOf<Pair<Int, Int>>()
val (x, y) = point
if (inside(grid, Pair(x + 1, y))) {
lst.add(Pair(x + 1, y))
}
if (inside(grid, Pair(x - 1, y))) {
lst.add(Pair(x - 1, y))
}
if (inside(grid, Pair(x, y + 1))) {
lst.add(Pair(x, y + 1))
}
if (inside(grid, Pair(x, y - 1))) {
lst.add(Pair(x, y - 1))
}
return lst
}
fun get_steps(grid: List<CharArray>, point: Pair<Int, Int>): Int {
val q = ArrayDeque<Pair<Int, Int>>()
val s = ArrayDeque<Int>()
val vis = HashSet<Pair<Int, Int>>()
q.addFirst(point)
s.addFirst(0)
while (q.isNotEmpty()) {
val current = q.removeFirst()
val current_steps = s.removeFirst()
if (vis.contains(current)) {
continue
}
vis.add(current)
var current_height = grid[current.first][current.second]
if (current_height == 'E') return current_steps
if (current_height == 'S') current_height = 'a'
get_neighbour(grid, current).forEach {
val height = grid[it.first][it.second]
if (height <= current_height + 1 && !vis.contains(it)) {
if (height != 'E' || current_height == 'z') {
q.addLast(it)
s.addLast(current_steps + 1)
}
}
}
}
return MAX_VALUE
}
fun part1(input: String): Int {
val grid = input.split('\n').map { it -> it.toCharArray() }
val start = find_start(grid, { c -> c == 'S' })
return get_steps(grid, start[0])
}
fun part2(input: String): Int {
val grid = input.split('\n').map { it -> it.toCharArray() }
val lst = find_start(grid, { c -> c == 'S' || c == 'a' })
return lst.map { get_steps(grid, it) }.min()
}
fun main() {
println(part1(readInput("Day12")))
println(part2(readInput("Day12")))
}
| 0 |
Kotlin
| 0 | 1 |
fd3c96e99e3e786d358d807368c2a4a6085edb2e
| 2,689 |
aoc-mmxxii
|
MIT License
|
src/Day15.kt
|
Kvest
| 573,621,595 | false |
{"Kotlin": 87988}
|
import java.util.*
import kotlin.math.abs
import kotlin.math.max
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
val testInput = readInput("Day15_test")
val (testSensors, testBeacons) = parseInput(testInput)
check(part1(testSensors, testBeacons, targetLine = 10) == 26)
check(part2(testSensors, bound = 20) == 56000011L)
val input = readInput("Day15")
val (sensors, beacons) = parseInput(input)
println(part1(sensors, beacons, targetLine = 2_000_000))
println(part2(sensors, bound = 4_000_000))
}
private fun part1(sensors: List<Sensor>, beacons: Set<XY>, targetLine: Int): Int {
val intervals = calculateLineCoverage(sensors, targetLine)
val beaconsOnLine = beacons.filter { beacon ->
beacon.y == targetLine
}.count()
return intervals.sumOf { it.size } - beaconsOnLine
}
private fun part2(sensors: List<Sensor>, bound: Int): Long {
for (y in 0..bound) {
val intervals = calculateLineCoverage(sensors, y)
if (intervals[0].first > 0) {
return y.toLong()
}
for (i in 1..intervals.lastIndex) {
if (intervals[i].first - intervals[i - 1].last > 1) {
return (intervals[i - 1].last + 1) * 4_000_000L + y
}
}
if (intervals.last().last < bound) {
return (intervals.last().last + 1) * 4_000_000L + y
}
}
error("Not found")
}
private val ROW_FORMAT = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
private fun parseInput(input: List<String>): Pair<List<Sensor>, Set<XY>> {
val sensors = mutableListOf<Sensor>()
val beacons = mutableSetOf<XY>()
input.forEach {
val match = ROW_FORMAT.find(it)
val (x, y, beaconX, beaconY) = requireNotNull(match).destructured
val radius = abs(x.toInt() - beaconX.toInt()) + abs(y.toInt() - beaconY.toInt())
sensors.add(Sensor(x = x.toInt(), y = y.toInt(), radius = radius))
beacons.add(XY(x = beaconX.toInt(), y = beaconY.toInt()))
}
return Pair(sensors, beacons)
}
private fun calculateLineCoverage(sensors: List<Sensor>, line: Int): List<IntRange> {
val intervals = sensors
.mapNotNull { sensor ->
val count = sensor.radius - abs(sensor.y - line)
if (count > 0) {
((sensor.x - count)..(sensor.x + count))
} else {
null
}
}
.sortedBy { it.first }
val result = LinkedList<IntRange>()
//collapse intervals if possible
result.addLast(intervals.first())
for (i in 1..intervals.lastIndex) {
if (result.last.last >= intervals[i].first) {
val tmp = result.pollLast()
result.addLast(tmp.first..max(tmp.last, intervals[i].last))
} else {
result.addLast(intervals[i])
}
}
return result
}
private data class Sensor(
val x: Int,
val y: Int,
val radius: Int,
)
| 0 |
Kotlin
| 0 | 0 |
6409e65c452edd9dd20145766d1e0ea6f07b569a
| 3,001 |
AOC2022
|
Apache License 2.0
|
src/year2021/Day15.kt
|
drademacher
| 725,945,859 | false |
{"Kotlin": 76037}
|
package year2021
import Point
import readLines
import java.util.PriorityQueue
fun main() {
val input = parseInput(readLines("2021", "day15"))
val testInput = parseInput(readLines("2021", "day15_test"))
check(part1(testInput) == 40)
println("Part 1:" + part1(input))
check(part2(testInput) == 315)
println("Part 2:" + part2(input))
}
private fun parseInput(lines: List<String>): Day15Input =
lines
.map { it.split("").filter { it != "" }.map { it.toInt() } }
private fun part1(input: List<List<Int>>): Int? {
return searchCheapestPathToBottomRIght(input)
}
private fun part2(input: List<List<Int>>): Int? {
val yMax = input.size
val xMax = input[0].size
val newInput = MutableList(5 * yMax) { MutableList(5 * xMax) { 0 } }
for (y in 0 until yMax * 5) {
for (x in 0 until xMax * 5) {
val incrementedWithOverflow = input[y % yMax][x % xMax] + (y / yMax) + (x / xMax)
newInput[y][x] = if (incrementedWithOverflow > 9) incrementedWithOverflow - 9 else incrementedWithOverflow
}
}
return searchCheapestPathToBottomRIght(newInput)
}
private fun searchCheapestPathToBottomRIght(input: List<List<Int>>): Int? {
val goal = Point(input.first().size - 1, input.size - 1)
val frontier = PriorityQueue<Pair<Point, Int>> { a, b -> a.second - b.second }
val visited = mutableSetOf<Point>()
frontier.add(Pair(Point(0, 0), 0))
while (frontier.isNotEmpty()) {
val next = frontier.poll()
if (visited.contains(next.first)) {
continue
}
if (next.first == goal) {
return next.second
}
visited.add(next.first)
getOrthogonalNeighbors(input, next.first)
.map { Pair(it, next.second + input[it.y][it.x]) }
.forEach(frontier::add)
}
return null
}
private fun getOrthogonalNeighbors(
input: Day15Input,
point: Point,
): Set<Point> {
val result = mutableSetOf<Point>()
if (point.x > 0) result.add(Point(point.x - 1, point.y))
if (point.x < input[point.y].size - 1) result.add(Point(point.x + 1, point.y))
if (point.y > 0) result.add(Point(point.x, point.y - 1))
if (point.y < input.size - 1) result.add(Point(point.x, point.y + 1))
return result
}
private typealias Day15Input = List<List<Int>>
fun List<List<Int>>.get(
x: Int,
y: Int,
) = this.getOrNull(y)?.getOrNull(x)
| 0 |
Kotlin
| 0 | 0 |
4c4cbf677d97cfe96264b922af6ae332b9044ba8
| 2,438 |
advent_of_code
|
MIT License
|
src/Day14.kt
|
bigtlb
| 573,081,626 | false |
{"Kotlin": 38940}
|
fun main() {
class Scan(input: List<String>, val withFloor:Boolean=false) {
init {
rocks = input.flatMap {
it.split(" -> ").map {
it.split(",").let { (x, y) -> Loc(x.toInt(), y.toInt()) }
}
.windowed(2).flatMap { (from, to) ->
when {
from.first != to.first -> listOf(from.first, to.first).sorted()
.let { (a, b) -> (a..b).map { Loc(it, from.second) } }
from.second != to.second -> listOf(from.second, to.second).sorted()
.let { (a, b) -> (a..b).map { Loc(from.first, it) } }
else -> listOf()
}
}
}.toSet()
bounds = Pair(rocks.minOf { it.first }, rocks.maxOf { it.first })
bottom = rocks.maxOf{it.second}
if (withFloor){
//rocks += (bounds.first-1000..bounds.second+1000).map{Loc(it,bottom+2)}
bottom += 2
}
}
fun pourSand(source: Loc): Set<Loc> {
var spot: Loc?
do {
spot = dropGrain(source)
} while (spot != null)
printChart()
return sand
}
private fun printChart() {
var chart = rocks.union(sand)
val bounds = Pair(sand.minOf { it.first }, sand.maxOf { it.first })
(0..chart.maxOf { it.second }).map { y ->
(bounds.first-1..bounds.second+1).map {
val test = Loc(it, y)
when {
rocks.contains(test) -> print("#")
sand.contains(test) -> print("o")
else -> print(".")
}
}
println()
}
println("\n\n")
}
private fun dropGrain(source: Loc): Loc? {
val testChart = rocks.union(sand)
if (testChart.contains(source)) return null
var lastPlace: Loc? = source+Loc(0,-1)
generateSequence(0) { it + 1 }.takeWhile { y ->
if (lastPlace == null || y > bottom || (y>1 && lastPlace == source)) {
lastPlace = null
false
} else {
var test = listOf(lastPlace!! + Loc(0, 1), lastPlace!! + Loc(-1, 1), lastPlace!! + Loc(1, 1))
.firstOrNull { (!withFloor || it.second < bottom) && !(testChart.contains(it)) }
if (test == null) {
false
} else {
lastPlace = test!!
true
}
}
}.lastOrNull()
lastPlace?.let { sand.add(lastPlace!!) }
return lastPlace
}
private var bottom: Int
private val bounds: Pair<Int, Int>
var rocks: Set<Loc>
val sand = mutableSetOf<Loc>()
}
fun part1(input: List<String>): Int = Scan(input).pourSand(Loc(500, 0)).count()
fun part2(input: List<String>): Int = Scan(input, true).pourSand(Loc(500, 0)).count()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
println("checked")
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
d8f76d3c75a30ae00c563c997ed2fb54827ea94a
| 3,574 |
aoc-2022-demo
|
Apache License 2.0
|
src/2022/Day24.kt
|
ttypic
| 572,859,357 | false |
{"Kotlin": 94821}
|
package `2022`
import readInput
fun main() {
fun part1(input: List<String>): Int {
return Maze.readMaze(input).solve()
}
fun part2(input: List<String>): Int {
var maze = Maze.readMaze(input)
val startToGoal = maze.solve()
maze = maze.reverse()
val backToStart = maze.solve(startToGoal)
maze = maze.reverse()
return maze.solve(backToStart)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day24_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInput("Day24")
println(part1(input))
println(part2(input))
}
fun List<Pair<Direction, Point>>.tick(wallX: Int, wallY: Int): List<Pair<Direction, Point>> {
return map {(direction, point) ->
direction to point.nextBlizzard(direction, wallX, wallY)
}
}
fun Point.nextBlizzard(direction: Direction, wallX: Int, wallY: Int): Point {
return when(direction) {
Direction.north -> if (y == 1) Point(x, wallY - 1) else Point(x, y - 1)
Direction.south -> if (y == wallY - 1) Point(x, 1) else Point(x, y + 1)
Direction.west -> if (x == 1) Point(wallX - 1, y) else Point(x - 1, y)
Direction.east -> if (x == wallX - 1) Point(1, y) else Point(x + 1, y)
}
}
class Maze(private var blizzards: List<List<Pair<Direction, Point>>>, private val wallX: Int, private val wallY: Int, private val entry: Point, private val exit: Point, private val period: Int) {
private var visitedPoints: MutableSet<Pair<Int, Point>> = mutableSetOf()
fun solve(initialStep: Int = 0): Int {
val nextToVisit = mutableListOf(initialStep to entry)
while (nextToVisit.isNotEmpty()) {
val (step, point) = nextToVisit.removeFirst()
val atom = step % period
if (point == exit) return step - 1
if (visitedPoints.contains(atom to point)) continue
visitedPoints.add(atom to point)
val blizzard = blizzards[atom].groupBy { it.second }
val nearestPoints = Direction.values().map { direction ->
point.toDirection(direction)
} + point
nearestPoints.filter { !blizzard.contains(it) && (it == exit || it == entry || it.x in 1 until wallX && it.y in 1 until wallY) }.forEach {
nextToVisit.add((step + 1) to it)
}
}
error("Can't find the exit")
}
fun reverse(): Maze {
return Maze(blizzards, wallX, wallY, exit, entry, period)
}
fun print(atom: Int) {
val blizzard = blizzards[atom].groupBy { it.second }
println((1 until wallY).joinToString(separator = "\n") { y ->
(1 until wallX).joinToString(separator = "") { x ->
if (blizzard.contains(Point(x, y))) {
val points = blizzard[Point(x, y)]!!
if (points.size != 1) {
"${points.size}"
} else {
when(points.first().first) {
Direction.north -> "^"
Direction.east -> ">"
Direction.west -> "<"
Direction.south -> "v"
}
}
} else {
"."
}
}
})
}
companion object {
fun readMaze(input: List<String>): Maze {
fun getDirection(char: Char): Direction {
return when(char) {
'^' -> Direction.north
'>' -> Direction.east
'<' -> Direction.west
'v' -> Direction.south
else -> error("Illegal state")
}
}
val initialBlizzards = input.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, char ->
if (char == '#' || char == '.') null else getDirection(char) to Point(x, y)
}
}
val wallY = input.size - 1
val wallX = input.first().length - 1
val period = (wallY - 1) * (wallX - 1) / gcd(wallY - 1L, wallX - 1L).toInt()
val blizzards = generateSequence(initialBlizzards) { it.tick(wallX, wallY) }.take(period).toList()
return Maze(blizzards, wallX, wallY, Point(1, 0), Point(wallX - 1, wallY), period)
}
}
}
| 0 |
Kotlin
| 0 | 0 |
b3e718d122e04a7322ed160b4c02029c33fbad78
| 4,564 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/main/kotlin/dev/tasso/adventofcode/_2022/day10/Day10.kt
|
AndrewTasso
| 433,656,563 | false |
{"Kotlin": 75030}
|
package dev.tasso.adventofcode._2022.day10
import dev.tasso.adventofcode.Solution
class Day10 : Solution<Int> {
override fun part1(input: List<String>): Int =
input.asSequence()
.map { inputLine -> inputLine.split(" ") }
.map{ splitLine ->
Instruction(splitLine[0], if (splitLine.size == 2) splitLine[1].toInt() else 0) }
//Break each multi cycle instruction down to single cycle actions
.fold(emptyList<Int>()) { perCycleIncreases, instruction ->
perCycleIncreases.plus( if(instruction.name == "addx") listOf(0, instruction.value) else listOf(0)) }
.fold(listOf(1)) { perCycleValues, increase ->
perCycleValues.plus(perCycleValues.last() + increase) }
.withIndex()
.filter{ (cycleIndex, _) -> (cycleIndex + 1) % 40 == 20 }
.sumOf { (cycleIndex, cycleValue) -> (cycleIndex + 1) * cycleValue }
override fun part2(input: List<String>): Int {
input.asSequence()
.map { inputLine -> inputLine.split(" ") }
.map{ splitLine ->
Instruction(splitLine[0], if (splitLine.size == 2) splitLine[1].toInt() else 0) }
//Break each multi cycle instruction down to single cycle actions
.fold(emptyList<Int>()) { perCycleIncreases, instruction ->
perCycleIncreases.plus( if(instruction.name == "addx") listOf(0, instruction.value) else listOf(0)) }
.fold(listOf(1)) { perCycleValues, increase ->
perCycleValues.plus(perCycleValues.last() + increase) }
//We had one too many cycles defined, drop the last
.dropLast(1)
.withIndex()
.map { (cycleIndex, cycleValue) ->
if(getPixelRange(cycleValue).contains(cycleIndex % 40)) '#' else '.' }
.chunked(40)
.joinToString(separator = System.lineSeparator()) { it.joinToString(separator = "") }
.let{ crtImage -> println(crtImage) }
return 1
}
private data class Instruction(val name: String, val value: Int = 0)
private fun getPixelRange(pixelPosition: Int) : ClosedRange<Int> = (pixelPosition - 1 .. pixelPosition + 1)
}
| 0 |
Kotlin
| 0 | 0 |
daee918ba3df94dc2a3d6dd55a69366363b4d46c
| 2,259 |
advent-of-code
|
MIT License
|
solutions/aockt/y2023/Y2023D13.kt
|
Jadarma
| 624,153,848 | false |
{"Kotlin": 435090}
|
package aockt.y2023
import aockt.util.parse
import io.github.jadarma.aockt.core.Solution
object Y2023D13 : Solution {
/**
* Notes on the terrain of Lava Island, but without any lava...
* @param data The terrain reading, first element is first row, then going upwards. Should only contain `[#.]`.
*/
private class LavaIslandMap(data: List<String>) {
// The terrain readings, transposed to make symmetry scanning, well... symmetrical!
private val byRow: List<BooleanArray>
private val byColumn: List<BooleanArray>
init {
require(data.isNotEmpty()) { "No data to process." }
val height = data.size
val width = data.first().length
require(data.all { it.length == width }) { "Map is not perfect grid." }
byRow = List(height) { BooleanArray(width) }
byColumn = List(width) { BooleanArray(height) }
for (y in 0..<height) {
for (x in 0..<width) {
val state = when (data[y][x]) {
'.' -> false
'#' -> true
else -> error("Invalid map state.")
}
byRow[height - 1 - y][x] = state
byColumn[x][height - 1 - y] = state
}
}
}
/** Returns the total amount of differences between the contents, 0 meaning perfect match. */
private fun BooleanArray.compareTo(other: BooleanArray): Int {
require(size == other.size) { "Cannot compare collections of different sizes." }
return indices.count { index -> this[index] != other[index] }
}
/**
* Find symmetries in the [pattern], allowing for exactly this amount of [smudges].
* For each symmetry line found, returns the number of lines below it.
*/
private fun findSymmetries(pattern: List<BooleanArray>, smudges: Int): List<Int> = buildList {
for (mirror in 1..<pattern.size) {
var errors = 0
for (reflectionLine in 1..minOf(mirror, pattern.size - mirror)) {
val above = pattern[mirror + reflectionLine - 1]
val below = pattern[mirror - reflectionLine]
errors += above.compareTo(below)
if (errors > smudges) break
}
if (errors == smudges) add(mirror)
}
}
/**
* Summarize your notes on the observed volcanic pattern.
* @param smudges How many smudges to expect there to be, exactly.
* @return The sum between the total amount of columns to the left of each vertical reflection and 100 times
* the total amount of rows above each horizontal reflection.
*/
fun summarize(smudges: Int): Int {
val horizontal = findSymmetries(byRow, smudges)
val vertical = findSymmetries(byColumn, smudges)
return horizontal.sum() * 100 + vertical.sum()
}
}
/** Parse the [input] and return the list of [LavaIslandMap]s. */
private fun parseInput(input: String): List<LavaIslandMap> = parse {
val inputRegex = Regex("""^[.#]+$""")
input
.splitToSequence("\n\n")
.map { map -> map.lines().reversed() }
.onEach { points -> points.all { it.matches(inputRegex) } }
.map(::LavaIslandMap)
.toList()
}
override fun partOne(input: String) = parseInput(input).sumOf { it.summarize(smudges = 0) }
override fun partTwo(input: String) = parseInput(input).sumOf { it.summarize(smudges = 1) }
}
| 0 |
Kotlin
| 0 | 3 |
19773317d665dcb29c84e44fa1b35a6f6122a5fa
| 3,718 |
advent-of-code-kotlin-solutions
|
The Unlicense
|
src/main/kotlin/day16.kt
|
p88h
| 317,362,882 | false | null |
internal data class Range(val name: String, val a: Pair<Int, Int>, val b: Pair<Int, Int>) {
var invalid = HashSet<Int>()
var pos = -1
}
internal val pattern = "([a-z ]+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)".toRegex()
internal fun parseRange(input: String): Range {
pattern.matchEntire(input)!!.destructured.let { (n, a1, a2, b1, b2) ->
return Range(n, a1.toInt() to a2.toInt(), b1.toInt() to b2.toInt())
}
}
internal fun validFor(range: Range, value: Int): Boolean {
return (value in range.a.first..range.a.second) || (value in range.b.first..range.b.second)
}
fun main(args: Array<String>) {
var ranges = ArrayList<Range>()
var state = 0
var errors = 0
var ticket : List<Int>? = null
var others = ArrayList<List<Int>>()
for (line in allLines(args, "day16.in")) {
if (line.isEmpty()) {
state += 1
} else when (state) {
0 -> ranges.add(parseRange(line))
1, 3 -> state += 1 // headers
2 -> ticket = line.split(',').map { it.toInt() }.toList()
4 -> {
val tkt = line.split(',').map { it.toInt() }
val err = tkt.filter { ranges.none { r -> validFor(r, it) } }
if (err.isEmpty()) {
others.add(tkt)
tkt.forEachIndexed { pos, n ->
ranges.forEach {
if (!it.invalid.contains(pos) && !validFor(it, n)) {
it.invalid.add(pos)
}
}
}
} else {
errors += err.sum()
}
}
}
}
println(errors)
var prod = 1L
// naive elimination seems to handle this...
while (ranges.any { it.pos == -1 } ) {
var r = ranges.first{ it.invalid.size == ranges.size - 1 }
val p = (0 until ranges.size).first { !r.invalid.contains(it) }
r.pos = p
ranges.forEach { it.invalid.add(p) }
println("${r.name}: $p")
if (r.name.startsWith("departure")) prod *= ticket!![p].toLong()
}
println(prod)
}
| 0 |
Kotlin
| 0 | 5 |
846ad4a978823563b2910c743056d44552a4b172
| 2,176 |
aoc2020
|
The Unlicense
|
src/day07/Day07.kt
|
TimberBro
| 572,681,059 | false |
{"Kotlin": 20536}
|
package day07
import readInput
data class File(val name: String, val size: Int)
class Directory(private val name: String) {
var parentDirectory: Directory? = null
val files = ArrayList<File>()
var directories = ArrayList<Directory>()
fun addChild(directory: Directory) {
directories.add(directory)
directory.parentDirectory = this
}
fun calculateSize(): Int {
return files
.asSequence()
.map { it.size }
.sum() +
directories
.asSequence()
.map { it.calculateSize() }
.sum()
}
override fun toString(): String {
return name
}
fun findIndexByName(name: String): Int {
var result = -1
for (i in 0..directories.size) {
val currentDirectory = directories[i]
if (currentDirectory.name == name) {
result = i
break
}
}
return result
}
}
fun main() {
fun directoriesSet(rootDirectory: Directory, set: HashSet<Directory>) {
rootDirectory.calculateSize()
set.add(rootDirectory)
set.addAll(rootDirectory.directories)
for (directory in rootDirectory.directories) {
directory.calculateSize()
directoriesSet(directory, set)
}
}
fun parseFileSystem(input: List<String>): Directory {
val rootDirectory = Directory("/")
var currentDirectory = rootDirectory
val foldersRegex = "dir (\\w+)".toRegex()
val commandRegex = "\\\$ cd (\\w+)".toRegex()
val filesRegex = "\\d+.+".toRegex()
val moveBackRegex = "\\\$ cd ..".toRegex()
input.asSequence()
//.onEach { println(it) }
.map {
when {
it.matches(foldersRegex) -> currentDirectory.addChild(Directory(it.split(" ")[1]))
it.matches(filesRegex) -> currentDirectory.files.add(
File(
it.split(" ")[1],
it.split(" ")[0].toInt()
)
)
it.matches(commandRegex) -> currentDirectory =
currentDirectory.directories[currentDirectory.findIndexByName(it.split(" ")[2])]
it.matches(moveBackRegex) -> currentDirectory =
currentDirectory.parentDirectory!!
else -> {}
}
}.count()
return rootDirectory
}
fun part1(input: List<String>): Int {
val rootDirectory = parseFileSystem(input)
val allDirectories = HashSet<Directory>()
directoriesSet(rootDirectory, allDirectories)
return allDirectories.asSequence()
.map { it.calculateSize() }
.filter { it <= 100000 }
.sum()
}
fun part2(input: List<String>): Int {
val rootDirectory = parseFileSystem(input)
val allDirectories = HashSet<Directory>()
directoriesSet(rootDirectory, allDirectories)
val unusedSpace = 70000000 - rootDirectory.calculateSize()
val requiredSpace = 30000000 - unusedSpace
return allDirectories.asSequence()
.map { it.calculateSize() }
.filter { it > requiredSpace }
.min()
}
val testInput = readInput("day07/Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("day07/Day07")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
516a98e5067d11f0e6ff73ae19f256d8c1bfa905
| 3,749 |
AoC2022
|
Apache License 2.0
|
src/main/kotlin/day12/Day12.kt
|
jakubgwozdz
| 571,298,326 | false |
{"Kotlin": 85100}
|
package day12
import bfs
import execute
import readAllText
fun part1(input: String): Int = input.lineSequence().filterNot(String::isBlank)
.toList()
.let { lines ->
val start = lines.indexOfFirst { it.contains("S") }.let { r -> r to lines[r].indexOf('S') }
val end = lines.indexOfFirst { it.contains("E") }.let { r -> r to lines[r].indexOf('E') }
bfs(graphOp = lines::possibleUp,
start = start,
initial = 0,
moveOp = { l, _ -> l + 1 },
endOp = { it == end }
)!!
}
fun part2(input: String): Int = input.lineSequence().filterNot(String::isBlank)
.toList()
.let { lines ->
val end = lines.indexOfFirst { it.contains("E") }.let { r -> r to lines[r].indexOf('E') }
bfs(graphOp = lines::possibleDown,
start = end,
initial = 0,
moveOp = { l, _ -> l + 1 },
endOp = { (r, c) -> lines[r][c] == 'a' }
)!!
}
fun List<String>.possibleUp(from: Pair<Int, Int>): List<Pair<Int, Int>> = possibleMoves(from) { curr, next ->
(next.isLowerCase() && curr.isLowerCase() && next <= curr) || next == curr + 1 ||
(curr == 'S' && next == 'a') || (curr == 'z' && next == 'E')
}
fun List<String>.possibleDown(from: Pair<Int, Int>): List<Pair<Int, Int>> = possibleMoves(from) { curr, next ->
(next.isLowerCase() && curr.isLowerCase() && next >= curr) || next == curr - 1 ||
(curr == 'E' && next == 'z')
}
fun List<String>.possibleMoves(from: Pair<Int, Int>, predicate: (Char, Char) -> Boolean) = buildList {
val lines = this@possibleMoves
val (r, c) = from
val curr = lines[r][c]
if (r - 1 in lines.indices && predicate(curr, lines[r - 1][c])) add(r - 1 to c)
if (r + 1 in lines.indices && predicate(curr, lines[r + 1][c])) add(r + 1 to c)
if (c - 1 in lines[r].indices && predicate(curr, lines[r][c - 1])) add(r to c - 1)
if (c + 1 in lines[r].indices && predicate(curr, lines[r][c + 1])) add(r to c + 1)
}
fun main() {
val input = readAllText("local/day12_input.txt")
val test = """
Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi
""".trimIndent()
execute(::part1, test, 31)
execute(::part1, input, 449)
execute(::part2, test, 29)
execute(::part2, input, 443)
}
| 0 |
Kotlin
| 0 | 0 |
7589942906f9f524018c130b0be8976c824c4c2a
| 2,343 |
advent-of-code-2022
|
MIT License
|
src/day1/puzzle01.kt
|
brendencapps
| 572,821,792 | false |
{"Kotlin": 70597}
|
package day1
import Puzzle
import PuzzleInput
import java.io.File
import java.util.PriorityQueue
fun day1Puzzle() {
Day1PuzzleSolution1(1).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 24000))
Day1PuzzleSolution1(2).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 35000))
Day1PuzzleSolution1(3).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 45000))
Day1PuzzleSolution1(4).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 51000))
Day1PuzzleSolution1(5).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 55000))
Day1PuzzleSolution1(1).solve(Day1PuzzleInput("inputs/day1/caloriesInput.txt", 66487))
Day1PuzzleSolution2(1).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 24000))
Day1PuzzleSolution2(2).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 35000))
Day1PuzzleSolution2(3).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 45000))
Day1PuzzleSolution2(4).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 51000))
Day1PuzzleSolution2(5).solve(Day1PuzzleInput("inputs/day1/exampleData.txt", 55000))
Day1PuzzleSolution2(3).solve(Day1PuzzleInput("inputs/day1/caloriesInput.txt", 197301))
}
class Day1PuzzleInput(private val input: String, expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) {
fun sumTop(op: (List<Int>) -> Int): Int {
val calorieList = File(input)
.readText()
.split("\r\n\r\n")
.map { elf -> elf.lines().sumOf { calories -> calories.toInt() } }
return op(calorieList)
}
}
class Day1PuzzleSolution1(private val numElves: Int) : Puzzle<Int, Day1PuzzleInput>() {
override fun solution(input: Day1PuzzleInput): Int {
return input.sumTop { calorieList ->
val topCalories = PriorityQueue<Int>()
for(calories in calorieList) {
topCalories.add(calories)
if(topCalories.size > numElves) { topCalories.poll() }
}
topCalories.sum()
}
}
}
class Day1PuzzleSolution2(private val numElves: Int) : Puzzle<Int, Day1PuzzleInput>() {
override fun solution(input: Day1PuzzleInput): Int {
return input.sumTop { calorieList ->
calorieList.sortedDescending().take(numElves).sum()
}
}
}
| 0 |
Kotlin
| 0 | 0 |
00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3
| 2,290 |
aoc_2022
|
Apache License 2.0
|
src/main/kotlin/org/elm/workspace/solver/Solver.kt
|
klazuka
| 104,530,474 | false | null |
package org.elm.workspace.solver
import org.elm.workspace.Constraint
import org.elm.workspace.Version
import org.elm.workspace.solver.SolverResult.DeadEnd
import org.elm.workspace.solver.SolverResult.Proceed
typealias PkgName = String
interface Pkg {
val name: PkgName
val version: Version
val elmConstraint: Constraint
val dependencies: Map<PkgName, Constraint>
}
fun Version.satisfies(constraint: Constraint): Boolean = constraint.contains(this)
interface Repository {
val elmCompilerVersion: Version
operator fun get(name: PkgName): List<Pkg>
}
/**
* Attempt to find a solution for the constraints given by [deps] using the Elm packages
* that we know about in [repo].
*/
fun solve(deps: Map<PkgName, Constraint>, repo: Repository): Map<PkgName, Version>? {
val solutions = mapOf<PkgName, Version>()
return when (val res = Solver(repo).solve(deps, solutions)) {
DeadEnd -> null
is Proceed -> res.solutions
}
}
private sealed class SolverResult {
object DeadEnd : SolverResult()
data class Proceed(
val pending: Map<PkgName, Constraint>,
val solutions: Map<PkgName, Version>
) : SolverResult()
}
private class Solver(private val repo: Repository) {
fun solve(deps: Map<PkgName, Constraint>, solutions: Map<PkgName, Version>): SolverResult {
// Pick a dep to solve
val (dep, restDeps) = deps.pick()
if (dep == null) return Proceed(deps, solutions)
// Figure out which versions of the dep actually exist
var candidates = repo[dep.name]
.filter { it.version.satisfies(dep.constraint) }
.sortedByDescending { it.version }
// Further restrict the candidates if a pending solution has already bound the version of this dep.
val solvedVersion = solutions[dep.name]
if (solvedVersion != null)
candidates = candidates.filter { it.version == solvedVersion }
// Speculatively try each candidate version to see if it is a partial solution
loop@ for (candidate in candidates) {
if (repo.elmCompilerVersion !in candidate.elmConstraint) continue@loop
val tentativeDeps = restDeps.combine(candidate.dependencies) ?: continue@loop
val tentativeSolutions = solutions + (dep.name to candidate.version)
when (val res = solve(tentativeDeps, tentativeSolutions)) {
DeadEnd -> continue@loop
is Proceed -> return solve(res.pending, res.solutions)
}
}
return DeadEnd
}
}
private data class Dep(val name: PkgName, val constraint: Constraint)
private fun Map<PkgName, Constraint>.pick(): Pair<Dep?, Map<PkgName, Constraint>> {
// Pick a dep/constraint (Elm compiler picks by pkg name in lexicographically ascending order)
val dep = minByOrNull { it.key } ?: return (null to this)
return Dep(dep.key, dep.value) to minus(dep.key)
}
private fun Map<PkgName, Constraint>.combine(other: Map<PkgName, Constraint>): Map<PkgName, Constraint>? =
keys.union(other.keys)
.associateWith { key ->
val v1 = this[key]
val v2 = other[key]
when {
v1 != null && v2 != null -> {
v1.intersect(v2) ?: return null
}
v1 != null -> v1
v2 != null -> v2
else -> error("impossible")
}
}
| 167 |
Kotlin
| 61 | 371 |
1d9f3d4578f89e7f26b3e7ded63b29fd18790f1e
| 3,564 |
intellij-elm
|
MIT License
|
advent-of-code-2022/src/main/kotlin/Day08.kt
|
jomartigcal
| 433,713,130 | false |
{"Kotlin": 72459}
|
//Day 08: Treetop Tree House
//https://adventofcode.com/2022/day/8
import java.io.File
data class Tree(val index: Pair<Int, Int>, val height: Int)
fun main() {
val trees = mutableListOf<Tree>()
val input = File("src/main/resources/Day08.txt").readLines()
input.forEachIndexed { x, line ->
line.toList().forEachIndexed { y, height ->
trees.add(Tree(x to y, height.digitToInt()))
}
}
countVisibleTrees(trees)
findTopScenicScore(trees)
}
private fun countVisibleTrees(trees: List<Tree>) {
val count = trees.count { tree ->
isVisible(trees, tree)
}
println(count)
}
private fun isVisible(trees: List<Tree>, tree: Tree): Boolean {
val right = getTreesToTheRight(trees, tree).find {
it.height >= tree.height
}
val left = getTreesToTheLeft(trees, tree).find {
it.height >= tree.height
}
val top = getTreesAbove(trees, tree).find {
it.height >= tree.height
}
val bottom = getTreesBelow(trees, tree).find {
it.height >= tree.height
}
return left == null || right == null || top == null || bottom == null
}
private fun getTreesToTheRight(trees: List<Tree>, tree: Tree): List<Tree> {
return trees.filter {
it.index.first == tree.index.first && it.index.second > tree.index.second
}
}
private fun getTreesToTheLeft(trees: List<Tree>, tree: Tree): List<Tree> {
return trees.filter {
it.index.first == tree.index.first && it.index.second < tree.index.second
}
}
private fun getTreesAbove(trees: List<Tree>, tree: Tree): List<Tree> {
return trees.filter {
it.index.first < tree.index.first && it.index.second == tree.index.second
}
}
private fun getTreesBelow(trees: List<Tree>, tree: Tree): List<Tree> {
return trees.filter {
it.index.first > tree.index.first && it.index.second == tree.index.second
}
}
private fun findTopScenicScore(trees: List<Tree>) {
val highestScenicScore = trees.maxOf { tree ->
val right = findViewingDistance(getTreesToTheRight(trees, tree), tree.height)
val top = findViewingDistance(getTreesAbove(trees, tree).reversed(), tree.height)
val left = findViewingDistance(getTreesToTheLeft(trees, tree).reversed(), tree.height)
val bottom = findViewingDistance(getTreesBelow(trees, tree), tree.height)
right * top * left * bottom
}
println(highestScenicScore)
}
private fun findViewingDistance(trees: List<Tree>, height: Int): Int {
var count = 0
trees.forEach { tree ->
if (tree.height < height) {
count++
} else {
count++
return count
}
}
return count
}
| 0 |
Kotlin
| 0 | 0 |
6b0c4e61dc9df388383a894f5942c0b1fe41813f
| 2,717 |
advent-of-code
|
Apache License 2.0
|
archive/2022/Day18.kt
|
mathijs81
| 572,837,783 | false |
{"Kotlin": 167658, "Python": 725, "Shell": 57}
|
import kotlin.collections.ArrayDeque
private const val EXPECTED_1 = 64
private const val EXPECTED_2 = 58
private class Day18(isTest: Boolean) : Solver(isTest) {
val data = readAsLines().map { line ->
line.split(",").map { it.toInt() }
}.toSet()
val dirs = listOf(
listOf(1, 0, 0),
listOf(-1, 0, 0),
listOf(0, 1, 0),
listOf(0, -1, 0),
listOf(0, 0, 1),
listOf(0, 0, -1),
)
operator fun List<Int>.plus(dir: List<Int>) = listOf(this[0] + dir[0], this[1] + dir[1], this[2] + dir[2])
val bounds = (0..2).map { coord -> data.minOf { it[coord] } to data.maxOf { it[coord] } }
fun part1() = data.sumOf { point -> dirs.count { dir -> point + dir !in data } }
fun isInside(point: List<Int>, result: MutableMap<List<Int>, Boolean>, seen: MutableSet<List<Int>>): Boolean {
if(point in data || point in seen) return true
if((point zip bounds).any { (p, b) -> p !in b.first..b.second }) return false
result[point]?.let { return it }
seen.add(point)
return if (dirs.all { isInside(point + it, result, seen) }) {
seen.forEach { result[it] = true }
true
} else {
seen.forEach { result[it] = false }
false
}
}
val insidePoints = mutableMapOf<List<Int>, Boolean>()
fun part2() = data.sumOf { point ->
dirs.count { dir -> !isInside(point + dir, insidePoints, mutableSetOf()) }
}
}
fun main() {
val testInstance = Day18(true)
val instance = Day18(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("test part1 correct")
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("test part2 correct")
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 |
Kotlin
| 0 | 2 |
92f2e803b83c3d9303d853b6c68291ac1568a2ba
| 1,955 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day11.kt
|
p357k4
| 573,068,508 | false |
{"Kotlin": 59696}
|
import java.math.BigInteger
data class Monkey(
val starting: List<Long>,
val operation: List<String>,
val divisor: Long,
val monkeyTrue: Int,
val monkeyFalse: Int
)
fun main() {
fun simulation(
monkeys: Array<Monkey>,
state: Array<List<Long>>,
inspections: Array<Long>,
n: Int
) {
val relax = if (n == 20) 3 else 1
val p = monkeys.map { it.divisor }.fold(1L) { a, b -> a * b }
for (i in 1..n) {
for (k in monkeys.indices) {
val monkey = monkeys[k]
val items = state[k]
for (item in items) {
val factor = if (monkey.operation[2] == "old") item else monkey.operation[2].toLong()
val level = (if (monkey.operation[1] == "*") item * factor else item + factor) / relax
if ((level % monkey.divisor) == 0L) {
state[monkey.monkeyTrue] = state[monkey.monkeyTrue] + level % p
} else {
state[monkey.monkeyFalse] = state[monkey.monkeyFalse] + level % p
}
inspections[k]++
}
state[k] = listOf()
}
}
}
fun analysis(input: String, n: Int): Long {
val monkeys = input
.split("\n\n")
.map { entry ->
val lines = entry.lines()
val items = lines[1]
.substringAfter(" Starting items: ")
.split(",")
.map { it.trim().toLong() }
val operation = lines[2]
.substringAfter(" Operation: new = ")
.split(" ")
val divisor = lines[3]
.substringAfter(" Test: divisible by ")
.toLong()
val monkeyTrue = lines[4]
.substringAfter(" If true: throw to monkey ")
.toInt()
val monkeyFalse = lines[5]
.substringAfter(" If false: throw to monkey ")
.toInt()
Monkey(items, operation, divisor, monkeyTrue, monkeyFalse)
}
.toTypedArray()
val state = monkeys.map { it.starting }.toTypedArray()
val inspections = monkeys.map { 0L }.toTypedArray()
simulation(monkeys, state, inspections, n)
val sorted = inspections.sortedDescending()
return sorted[0] * sorted[1]
}
fun part1(input: String): Long {
return analysis(input, 20);
}
fun part2(input: String): Long {
return analysis(input, 10000);
}
// test if implementation meets criteria from the description, like:
val testInputExample = readText("Day11_example")
check(part1(testInputExample) == 10605L)
check(part2(testInputExample) == 2713310158L)
val testInput = readText("Day11_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 |
Kotlin
| 0 | 0 |
b9047b77d37de53be4243478749e9ee3af5b0fac
| 3,038 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/day04/Day04.kt
|
spyroid
| 433,555,350 | false | null |
package day04
import readInput
fun main() {
data class Cell(var value: Int = 0, var marked: Boolean = false)
class Board(data: List<String>) {
val cells: Array<Array<Cell>> = Array(5) { Array(5) { Cell() } }
init {
data.forEachIndexed { idx1, line ->
line.trim().split("\\s+".toRegex()).forEachIndexed { idx2, v ->
cells[idx1][idx2].value = v.toInt()
}
}
}
val countCol = IntArray(5) { 0 };
var score = 0
fun markAndGetScore(marker: Int): Int {
if (score != 0) return score
var sumOfUnmarked = 0
var fullRow = false
cells.forEachIndexed { _, cells2 ->
val countRow = cells2.onEachIndexed { col, cell ->
if (cell.value == marker) {
cell.marked = true
countCol[col]++
}
if (!cell.marked) sumOfUnmarked += cell.value
}.count { it.marked }
if (countRow == 5) fullRow = true
}
if (fullRow || countCol.any { it == 5 }) score = marker * sumOfUnmarked
return score
}
}
fun getInput(seq: List<String>) = seq[0].split(",").map { it.toInt() }.toList()
fun getBoards(seq: List<String>) = seq.asSequence().drop(2).windowed(5, 6).map { Board(it) }.toList()
fun part1(seq: List<String>): Int {
val randomInput = getInput(seq)
val boards = getBoards(seq)
return randomInput.map { marker -> boards.maxOf { it.markAndGetScore(marker) } }.first() { it > 0 }
}
fun part2(seq: List<String>): Int {
val boards = getBoards(seq)
return getInput(seq).asSequence().map { marker ->
boards.filter { it.score == 0 }.map { it.markAndGetScore(marker) }.minOf { it }
}.first { it > 0 }
}
val testSeq = readInput("day04/test")
val inputSeq = readInput("day04/input")
val res1 = part1(testSeq)
check(res1 == 4512) { "Expected 4512 but got $res1" }
println("Part1: ${part1(inputSeq)}")
val res2 = part2(testSeq)
check(res2 == 1924) { "Expected 1924 but got $res2" }
println("Part2: ${part2(inputSeq)}")
}
| 0 |
Kotlin
| 0 | 0 |
939c77c47e6337138a277b5e6e883a7a3a92f5c7
| 2,288 |
Advent-of-Code-2021
|
Apache License 2.0
|
src/main/kotlin/days/y2023/day17_a/Day17.kt
|
jewell-lgtm
| 569,792,185 | false |
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
|
package days.y2023.day17_a
import util.InputReader
import kotlin.math.abs
typealias PuzzleLine = String
typealias PuzzleInput = List<PuzzleLine>
class Day17(val input: PuzzleInput) {
val grid = input.toGrid()
fun partOne(): Int {
return minOf(
grid.bestDistanceTo(grid.end, Direction.X),
grid.bestDistanceTo(grid.end, Direction.Y)
)
}
}
private operator fun Grid2d.get(at: Position): Int {
return this.heatLoss[at.y][at.x]
}
private fun Position.compareTo(other: Position) =
this.distanceTo(Position(0, 0))
.compareTo(
other.distanceTo(Position(0, 0))
)
// up to and including
private fun Position.positionsBetween(position: Position): Set<Position> {
val result = mutableSetOf<Position>()
require(position.y == this.y || position.x == this.x)
for (y in minOf(position.y, y)..maxOf(position.y, y)) {
result.add(Position(y, position.x))
}
for (x in minOf(position.x, x)..maxOf(position.x, x)) {
result.add(Position(this.y, x))
}
return result - this
}
private fun Grid2d.positionIsValid(position: Position): Boolean {
return position.y in heatLoss.indices && position.x in heatLoss[position.y].indices
}
data class Position(val y: Int, val x: Int) {
fun neighbors(grid: Grid2d): Set<Position> {
return setOf(
Position(y - 1, x),
Position(y + 1, x),
Position(y, x - 1),
Position(y, x + 1)
).filter { grid.positionIsValid(it) }.toSet()
}
}
fun Position.distanceTo(other: Position): Int {
return abs(y - other.y) + abs(x - other.x)
}
data class Grid2d(val heatLoss: List<List<Int>>) {
fun positions() = heatLoss.indices.flatMap { y ->
heatLoss[y].indices.map { x ->
Position(y = y, x = x)
}
}
val bestDistances =
mapOf(
Direction.X to mutableMapOf(Position(0, 0) to 0),
Direction.Y to mutableMapOf(Position(0, 0) to 0)
)
fun bestDistanceTo(point: Position, fromDirection: Direction): Int {
if (bestDistances[fromDirection]!!.containsKey(point)) {
return bestDistances[fromDirection]!![point]!!
}
val possiblePreviousPositions = listOf(-3, -2, -1, 1, 2, 3).map { offset ->
when (fromDirection) {
Direction.X -> Position(point.y, point.x + offset)
Direction.Y -> Position(point.y + offset, point.x)
}
}.filter { positionIsValid(it) }
val distance =
possiblePreviousPositions.minOf { bestDistanceTo(it, fromDirection.other()) + calcCost(it, point) }
return distance.also { bestDistances[fromDirection]!![point] = it }
}
fun calcCost(from: Position, to: Position): Int {
val positionsBetween = from.positionsBetween(to)
return positionsBetween.sumOf { this[it] }
}
}
enum class Direction {
X, Y
}
fun Direction.other(): Direction = when (this) {
Direction.X -> Direction.Y
Direction.Y -> Direction.X
}
val Grid2d.start: Position
get() = Position(y = 0, x = 0)
val Grid2d.end: Position
get() = Position(y = heatLoss.size - 1, x = heatLoss[0].size - 1)
val Grid2d.weights: List<List<Int>>
get() = heatLoss.map { line -> line.map { 10 - it } }
fun Grid2d.goalDistance(a: Position): Int {
return a.distanceTo(end)
}
fun PuzzleInput.toGrid(): Grid2d {
return Grid2d(map { line -> line.map { it.toString().toInt() } })
}
fun main() {
val year = 2023
val day = 17
val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day)
val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day)
fun partOne(input: PuzzleInput) = Day17(input).partOne()
println("Example 1: ${partOne(InputReader.getExampleLines(year, day, "example1s"))}")
println("Example 1: ${partOne(exampleInput)}")
println("Part 1: ${partOne(puzzleInput)}")
}
| 0 |
Kotlin
| 0 | 0 |
b274e43441b4ddb163c509ed14944902c2b011ab
| 3,974 |
AdventOfCode
|
Creative Commons Zero v1.0 Universal
|
solutions/aockt/y2021/Y2021D09.kt
|
Jadarma
| 624,153,848 | false |
{"Kotlin": 435090}
|
package aockt.y2021
import io.github.jadarma.aockt.core.Solution
object Y2021D09 : Solution {
/** Represents a discrete point in 2D space. */
private data class Point(val x: Int, val y: Int)
/** Represents the scanning of the lava tubes inside the cave system. */
private class LavaTubesMap(val width: Int, val height: Int, private val data: IntArray) {
init {
require(data.size == width * height) { "The map size does not match given data." }
require(data.all { it in 0..9 }) { "Map data contains invalid readings." }
}
operator fun get(point: Point) = data[point.x * width + point.y]
/** Return all the local minima from the map. */
fun lowPoints(): List<Point> = buildList {
for (x in 0 until height) {
for (y in 0 until width) {
val point = Point(x, y)
val value = this@LavaTubesMap[point]
if (adjacentTo(point).all { get(it) > value }) add(point)
}
}
}
/** Return a list of all basins, represented as the set of points that it contains. */
fun basins(): List<Set<Point>> {
val visited = mutableSetOf<Point>()
return lowPoints().map { searchBasin(it, visited) }
}
/** Return all the points orthogonally adjacent to the [point], adjusting for map borders. */
private fun adjacentTo(point: Point): List<Point> = buildList(8) {
with(point) {
if (x > 0) add(Point(x - 1, y))
if (x < height - 1) add(Point(x + 1, y))
if (y > 0) add(Point(x, y - 1))
if (y < width - 1) add(Point(x, y + 1))
}
}
/** Recursively build a basin starting [from] a point, and keeping track of [visited] points. */
private fun searchBasin(from: Point, visited: MutableSet<Point>): Set<Point> = buildSet {
add(from)
adjacentTo(from)
.filter { this@LavaTubesMap[it] < 9 }
.filter { it !in visited }
.forEach {
add(it)
visited.add(it)
addAll(searchBasin(from = it, visited))
}
}
}
/** Parse the [input] and return the [LavaTubesMap] associated to the cave system reading. */
private fun parseInput(input: String): LavaTubesMap {
var width = -1
var height = 0
val data = input
.lineSequence()
.onEach {
height++
if (width == -1) width = it.length else require(it.length == width)
}
.flatMap { line -> line.map { it.digitToInt() } }
.toList()
.toIntArray()
return LavaTubesMap(width, height, data)
}
override fun partOne(input: String) =
parseInput(input).run {
lowPoints().sumOf { this[it] + 1 }
}
override fun partTwo(input: String) =
parseInput(input)
.basins()
.sortedByDescending { it.size }
.take(3)
.fold(1) { acc, basin -> acc * basin.size }
}
| 0 |
Kotlin
| 0 | 3 |
19773317d665dcb29c84e44fa1b35a6f6122a5fa
| 3,213 |
advent-of-code-kotlin-solutions
|
The Unlicense
|
src/Day21.kt
|
SimoneStefani
| 572,915,832 | false |
{"Kotlin": 33918}
|
// FIXME improve name with better namespacing
data class Monkey21(
val name: String,
val number: Long? = null,
val left: String? = null,
val operator: String? = null,
val right: String? = null,
) {
fun resolve(left: Long, right: Long): Long = when (operator) {
"+" -> left + right
"-" -> left - right
"*" -> left * right
"/" -> left / right
else -> -1
}
fun derive(value: Long, other: Long, left: Boolean): Long = when (operator) {
"+" -> value - other
"-" -> if (left) value + other else other - value
"*" -> value / other
"/" -> if (left) value * other else other / value
else -> -1
}
companion object {
fun fromLine(line: String): Monkey21 {
val parts = line.split(" ")
val name = parts[0].trim(':')
return if (parts.size == 2) {
Monkey21(name, parts[1].toLong())
} else {
Monkey21(name, left = parts[1], operator = parts[2], right = parts[3])
}
}
}
}
class Troop(private val monkeys: Map<String, Monkey21>, private val tree: HashMap<String, String>) {
fun yelledByRoot(name: String): Long {
val monkey = monkeys[name]!!
return monkey.number ?: monkey.resolve(yelledByRoot(monkey.left!!), yelledByRoot(monkey.right!!))
}
fun yelledByHuman(name: String): Long {
val parent = tree[name]!!
val parentMonkey = monkeys[parent]!!
val left = parentMonkey.left!! == name
val other = if (left) yelledByRoot(parentMonkey.right!!) else yelledByRoot(parentMonkey.left!!)
return if (parent == "root") other else parentMonkey.derive(yelledByHuman(parent), other, left)
}
companion object {
fun fromLines(lines: List<String>): Troop {
val tree = HashMap<String, String>()
return lines.map { line ->
Monkey21.fromLine(line).also { monkey ->
monkey.right?.let { tree[it] = monkey.name }
monkey.left?.let { tree[it] = monkey.name }
}
}.associateBy { it.name }.let { Troop(it, tree) }
}
}
}
fun main() {
fun part1(input: List<String>): Long {
return Troop.fromLines(input).yelledByRoot("root")
}
fun part2(input: List<String>): Long {
return Troop.fromLines(input).yelledByHuman("humn")
}
val testInput = readInput("Day21_test")
check(part1(testInput) == 152L)
check(part2(testInput) == 301L)
val input = readInput("Day21")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
b3244a6dfb8a1f0f4b47db2788cbb3d55426d018
| 2,655 |
aoc-2022
|
Apache License 2.0
|
src/main/kotlin/day14/solution.kt
|
bukajsytlos
| 433,979,778 | false |
{"Kotlin": 63913}
|
package day14
import java.io.File
import java.util.*
fun main() {
var template: List<Char> = LinkedList()
var pairInsertionsRules: Map<Pair<Char, Char>, Char> = emptyMap()
File("src/main/kotlin/day14/input.txt").useLines { linesSequence ->
val linesIterator = linesSequence.iterator()
template = List(1) { linesIterator.next() }.first().toCollection(LinkedList<Char>())
linesIterator.next()
pairInsertionsRules = linesIterator.asSequence().map {
(it.substringBefore(" -> ").first() to it.substringBefore(" -> ").last()) to it.substringAfter(" -> ")
.first()
}.toMap()
}
val edgeCharacters = arrayOf(template.first(), template.last()).groupBy { it }.mapValues { it.value.count() }
val initialPairCount: Map<Pair<Char, Char>, Long> =
template.windowed(2).map { it[0] to it[1] }.groupBy { it }.mapValues { it.value.size.toLong() }
val pairCountAfter10Steps = (0..9).fold(initialPairCount) { acc, _ ->
acc.react(pairInsertionsRules)
}
val characterCountAfter10Steps = pairCountAfter10Steps.frequencies(edgeCharacters)
println(characterCountAfter10Steps.maxMinDiff())
val pairCountAfter40Steps = (0..29).fold(pairCountAfter10Steps) { acc, _ ->
acc.react(pairInsertionsRules)
}
val characterCountAfter40Steps = pairCountAfter40Steps.frequencies(edgeCharacters)
println(characterCountAfter40Steps.maxMinDiff())
}
fun Map<Pair<Char, Char>, Long>.react(pairInsertionsRules: Map<Pair<Char, Char>, Char>): Map<Pair<Char, Char>, Long> =
buildMap {
[email protected] { entry ->
val originalPair = entry.key
val newChar = pairInsertionsRules.getValue(originalPair)
val pairOne = originalPair.first to newChar
val pairTwo = newChar to originalPair.second
val originalPairCount = entry.value
merge(pairOne, originalPairCount) { a, b -> a + b }
merge(pairTwo, originalPairCount) { a, b -> a + b }
}
}
fun Map<Pair<Char, Char>, Long>.frequencies(edgeCharacters: Map<Char, Int>): Map<Char, Long> =
this.flatMap { listOf(it.key.first to it.value, it.key.second to it.value) }
.groupBy({ it.first }, { it.second })
.mapValues { it.value.sum() + (edgeCharacters[it.key] ?: 0) }
fun Map<Char, Long>.maxMinDiff() = this.maxOf { it.value } / 2 - this.minOf { it.value } / 2
| 0 |
Kotlin
| 0 | 0 |
f47d092399c3e395381406b7a0048c0795d332b9
| 2,436 |
aoc-2021
|
MIT License
|
src/main/kotlin/twentytwentytwo/Day24.kt
|
JanGroot
| 317,476,637 | false |
{"Kotlin": 80906}
|
package twentytwentytwo
fun main() {
val tinput = {}.javaClass.getResource("input-24-1.txt")!!.readText().linesFiltered { it.isNotEmpty() };
val input = {}.javaClass.getResource("input-24.txt")!!.readText().linesFiltered { it.isNotEmpty() };
val test = Day24(tinput)
val day = Day24(input)
println(test.part1())
println(test.part2())
println(day.part1())
println(day.part2())
}
class Day24(private val input: List<String>) {
var blizzards: Map<Pair<Int, Int>, List<Char>> = input.mapIndexed { y, row ->
row.mapIndexed { x, s -> (x to y) to s }.filter { it.second != '.' }
}.flatten().groupBy({ it.first }, { it.second })
val rows = input.size
val cols = input.first().length
val start = input.first().indexOf('.') to 0
val end = input.last().indexOf('.') to input.size
fun part1(): Int {
return stormWalker(start, end)
}
fun part2(): Int {
blizzards = input.mapIndexed { y, row ->
row.mapIndexed { x, s -> (x to y) to s }.filter { it.second != '.' }
}.flatten().groupBy({ it.first }, { it.second })
var part1 = stormWalker(start, end)
var part2 = stormWalker(end, start)
var part3 = stormWalker(start, end)
return part1 + part2 + part3
}
private fun stormWalker(start: Pair<Int, Int>, destination: Pair<Int, Int>): Int {
var options = setOf(start) // start
var end = destination
repeat(10000) { it ->
blizzards = blizzards.map { (k, v) ->
v.map { c -> k.next(c) }
}.flatten().groupBy({ it.first }, { it.second })
options = options.flatMap { it.options().filter { o -> o !in blizzards.keys } }.toSet()
if (options.contains(end)) {
return it
}
}
error("ooops")
}
fun Pair<Int, Int>.next(c: Char): Pair<Pair<Int, Int>, Char> =
when (c) {
'#' -> this to c
'<' -> ((if (first == 1) cols - 2 else first - 1) to second) to c
'>' -> ((if (first == cols - 2) 1 else first + 1) to second) to c
'v' -> (first to (if (second == rows - 2) 1 else second + 1)) to c
'^' -> (first to (if (second == 1) rows - 2 else second - 1)) to c
else -> error("oops")
}
fun Pair<Int, Int>.options(): Set<Pair<Int, Int>> {
return setOf(
first to second,
first to second - 1,
first to second + 1,
first + 1 to second,
first - 1 to second,
).filter { it.first >= 0 && it.second >= 0 }.toSet()
}
}
| 0 |
Kotlin
| 0 | 0 |
04a9531285e22cc81e6478dc89708bcf6407910b
| 2,638 |
aoc202xkotlin
|
The Unlicense
|
src/Day11.kt
|
flex3r
| 572,653,526 | false |
{"Kotlin": 63192}
|
fun main() {
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Long = run(input, rounds = 20) { level, _ -> level / 3 }
private fun part2(input: List<String>): Long = run(input, rounds = 10_000) { level, lcm -> level % lcm }
private fun run(input: List<String>, rounds: Int, keepingItManageable: (Long, Long) -> Long): Long {
val monkeys = parseMonkeys(input)
val lcm = monkeys.map(Monkey::testDivisor).reduce(Long::times)
repeat(rounds) {
monkeys.forEach { monkey ->
monkey.items.forEach { item ->
monkey.numberOfInspections++
val newItemLevel = keepingItManageable(monkey.operation(item), lcm)
val newIndex =
if (newItemLevel % monkey.testDivisor == 0L) monkey.testIndexTrue else monkey.testIndexFalse
monkeys[newIndex].items.add(newItemLevel)
}
monkey.items.clear()
}
}
return monkeys.map(Monkey::numberOfInspections).sortedDescending().take(2).reduce(Long::times)
}
private fun parseMonkeys(input: List<String>): List<Monkey> {
val grouped = input.partitionBy { it.isEmpty() }
return grouped.map { lines ->
val argument = lines[2].substringAfterLast(" ").takeIf { it != "old" }?.toLong()
Monkey(
items = lines[1].substringAfter("items: ").split(", ").map { it.toLong() }.toMutableList(),
testDivisor = lines[3].substringAfter("by ").toLong(),
testIndexTrue = lines[4].substringAfter("monkey ").toInt(),
testIndexFalse = lines[5].substringAfter("monkey ").toInt(),
operation = when (lines[2].substringAfter("old ").first()) {
'*' -> { old: Long -> old * (argument ?: old) }
else -> { old: Long -> old + (argument ?: old) }
}
)
}
}
private data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val testDivisor: Long,
val testIndexTrue: Int,
val testIndexFalse: Int,
var numberOfInspections: Long = 0
)
| 0 |
Kotlin
| 0 | 0 |
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
| 2,258 |
aoc-22
|
Apache License 2.0
|
src/year2023/Day12.kt
|
drademacher
| 725,945,859 | false |
{"Kotlin": 76037}
|
package year2023
import readLines
fun main() {
val input = readLines("2023", "day12")
val testInput = readLines("2023", "day12_test")
check(part1(testInput) == 21L)
println("Part 1:" + part1(input))
check(part2(testInput) == 525152L)
println("Part 2:" + part2(input))
}
private fun part1(input: List<String>): Long {
val arrangements =
input.map { row ->
memory = HashMap()
val visualMap = row.takeWhile { !it.isWhitespace() }
val groups = row.dropWhile { !it.isDigit() }.split(",").map { it.toInt() }
calculateNumberOfArrangements(visualMap, 0, groups)
}
return arrangements.sum()
}
private fun part2(input: List<String>): Long {
val arrangementsWithUnfoldedInput =
input.map { row ->
memory = HashMap()
val visualMap = row.takeWhile { !it.isWhitespace() }
val groups = row.dropWhile { !it.isDigit() }.split(",").map { it.toInt() }
val unfoldedVisualMap = (1..5).joinToString("?") { visualMap }
val unfoldedGroups = (1..5).flatMap { groups }
calculateNumberOfArrangements(unfoldedVisualMap, 0, unfoldedGroups)
}
return arrangementsWithUnfoldedInput.sum()
}
private var memory = HashMap<Pair<Int, List<Int>>, Long>()
private fun calculateNumberOfArrangements(
visualMap: String,
currentIndex: Int,
currentGroups: List<Int>,
): Long {
if (currentIndex == visualMap.length && currentGroups.isEmpty()) {
return 1
} else if (currentIndex >= visualMap.length) {
return 0
}
if (memory[Pair(currentIndex, currentGroups)] != null) {
return memory[Pair(currentIndex, currentGroups)]!!
}
val result =
when (visualMap[currentIndex]) {
'.' -> calculateForCurrentIsDot(visualMap, currentIndex, currentGroups)
'#' -> calculateForCurrentIsHash(visualMap, currentIndex, currentGroups)
'?' -> calculateForCurrentIsDot(visualMap, currentIndex, currentGroups) + calculateForCurrentIsHash(visualMap, currentIndex, currentGroups)
else -> throw IllegalStateException("s[current]=${visualMap[currentIndex]} is illegal")
}
memory[Pair(currentIndex, currentGroups)] = result
return result
}
private fun calculateForCurrentIsDot(
visualMap: String,
currentIndex: Int,
currentGroups: List<Int>,
): Long {
return calculateNumberOfArrangements(visualMap, currentIndex + 1, currentGroups)
}
private fun calculateForCurrentIsHash(
visualMap: String,
currentIndex: Int,
currentGroups: List<Int>,
): Long {
if (currentGroups.isEmpty()) {
return 0
}
val firstGroup = currentGroups.first()
if (currentIndex + firstGroup > visualMap.length) {
return 0
}
val nextGroupIsNotDot = visualMap.drop(currentIndex).take(firstGroup).all { it == '#' || it == '?' }
val isLastGroup = currentGroups.size == 1
val nextSymbolIsNotHash = currentIndex + firstGroup == visualMap.length || visualMap[currentIndex + firstGroup] != '#'
if (nextGroupIsNotDot && (isLastGroup || nextSymbolIsNotHash)) {
val offset = if (isLastGroup) 0 else 1
return calculateNumberOfArrangements(visualMap, currentIndex + firstGroup + offset, currentGroups.drop(1))
}
return 0
}
| 0 |
Kotlin
| 0 | 0 |
4c4cbf677d97cfe96264b922af6ae332b9044ba8
| 3,358 |
advent_of_code
|
MIT License
|
src/day02/Day02.kt
|
MaxBeauchemin
| 573,094,480 | false |
{"Kotlin": 60619}
|
package day02
import readInput
enum class RPSChoice(val defaultPoints: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun beats(other: RPSChoice): Boolean {
return when (this) {
ROCK -> other == SCISSORS
PAPER -> other == ROCK
SCISSORS -> other == PAPER
}
}
companion object {
fun fromString(input: String): RPSChoice {
return when (input) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw Exception("Can't Parse Input into RPSChoice")
}
}
fun desiredChoice(opponentChoice: RPSChoice, desiredGameResult: GameResult): RPSChoice {
return when (desiredGameResult) {
GameResult.WIN -> RPSChoice.values().find { it.beats(opponentChoice) }!!
GameResult.DRAW -> opponentChoice
GameResult.LOSS -> RPSChoice.values().find { opponentChoice.beats(it) }!!
}
}
}
}
enum class GameResult(val points: Int) {
WIN(6),
DRAW(3),
LOSS(0);
companion object {
fun fromString(input: String): GameResult {
return when (input) {
"X" -> LOSS
"Y" -> DRAW
"Z" -> WIN
else -> throw Exception("Can't Parse Input into GameResult")
}
}
}
}
fun main() {
fun calcRoundPoints(opponentChoice: RPSChoice, yourChoice: RPSChoice): Int {
val roundResult = if (opponentChoice == yourChoice) {
// Draw
GameResult.DRAW
} else if (yourChoice.beats(opponentChoice)) {
// Win
GameResult.WIN
} else {
// Loss
GameResult.LOSS
}
return yourChoice.defaultPoints + roundResult.points
}
// Output -> Opponent Choice / Your Recommended Choice
fun parseRoundPart1(input: String): Pair<RPSChoice, RPSChoice> {
return input.split(" ").let { tokens ->
if (tokens.size != 2) throw Exception("Invalid Round Input")
RPSChoice.fromString(tokens[0]) to RPSChoice.fromString(tokens[1])
}
}
fun part1(input: List<String>): Int {
return input.sumOf { round ->
parseRoundPart1(round).let { (opponentChoice, yourRecommendedChoice) ->
calcRoundPoints(opponentChoice, yourRecommendedChoice)
}
}
}
// Output -> Opponent Choice / Desired Game Result
fun parseRoundPart2(input: String): Pair<RPSChoice, GameResult> {
return input.split(" ").let { tokens ->
if (tokens.size != 2) throw Exception("Invalid Round Input")
RPSChoice.fromString(tokens[0]) to GameResult.fromString(tokens[1])
}
}
fun part2(input: List<String>): Int {
return input.sumOf { round ->
parseRoundPart2(round).let { (opponentChoice, desiredGameResult) ->
RPSChoice.desiredChoice(opponentChoice, desiredGameResult).let { yourChoice ->
calcRoundPoints(opponentChoice, yourChoice)
}
}
}
}
val testInput = readInput("Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
println(part2(testInput))
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
38018d252183bd6b64095a8c9f2920e900863a79
| 3,461 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day12.kt
|
flex3r
| 572,653,526 | false |
{"Kotlin": 63192}
|
fun main() {
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val (start, end, hills) = parseHills(input)
return bfs(start) { hill -> hill.neighbors(hills).filter { it.height - hill.height <= 1 } }
.first { (_, it) -> hills[it.y][it.x] == end }
.index
}
private fun part2(input: List<String>): Int {
val (_, end, hills) = parseHills(input)
return bfs(end) { hill -> hill.neighbors(hills).filter { hill.height - it.height <= 1 } }
.first { (_, it) -> hills[it.y][it.x].char == 'a' }
.index
}
private fun parseHills(input: List<String>): HillData {
lateinit var start: Hill
lateinit var end: Hill
val hills = input.mapIndexed { y, row ->
row.mapIndexed { x, c ->
when (c) {
'S' -> Hill('a', x, y).also { start = it }
'E' -> Hill('z', x, y).also { end = it }
else -> Hill(c, x, y)
}
}
}
return HillData(start, end, hills)
}
private data class HillData(val start: Hill, val end: Hill, val hills: List<List<Hill>>)
private data class Hill(val char: Char, val x: Int, val y: Int, val height: Int = char.code) {
fun neighbors(hills: List<List<Hill>>)= buildList {
if (y - 1 >= 0) add(hills[y - 1][x])
if (y + 1 <= hills.lastIndex) add(hills[y + 1][x])
if (x - 1 >= 0) add(hills[y][x - 1])
if (x + 1 <= hills[y].lastIndex) add(hills[y][x + 1])
}
}
| 0 |
Kotlin
| 0 | 0 |
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
| 1,637 |
aoc-22
|
Apache License 2.0
|
src/Day05.kt
|
Redstonecrafter0
| 571,787,306 | false |
{"Kotlin": 19087}
|
fun main() {
fun parse(input: List<String>): Pair<List<MutableList<Char>>, List<Triple<Int, Int, Int>>> {
val gapIndex = input.indexOf("")
val cratesRange = 0 until input[gapIndex - 1].split(" ").last().toInt()
val cratesVertical = input
.subList(0, gapIndex - 1)
.map { cratesRange.map { i -> it.getOrNull(i * 4 + 1).let { s -> if (s == ' ') null else s } } }
.reversed()
val stacks = cratesRange.map { mutableListOf<Char>() }
cratesVertical.forEach {
for (i in cratesRange) {
stacks[i] += it[i] ?: continue
}
}
val inputs = input.subList(gapIndex + 1, input.size).map { it.split(" ") }.map { Triple(it[1].toInt(), it[3].toInt(), it[5].toInt()) }
return stacks to inputs
}
fun part1(input: List<String>): String {
val (stacks, inputs) = parse(input)
inputs.forEach { (first, second, third) ->
for (i in 1..first) {
stacks[third - 1] += stacks[second - 1].last()
stacks[second - 1].removeLast()
}
}
return stacks.map { it.last() }.toCharArray().concatToString()
}
fun part2(input: List<String>): String {
val (stacks, inputs) = parse(input)
inputs.forEach { (first, second, third) ->
stacks[third - 1] += stacks[second - 1].subList(stacks[second - 1].size - first, stacks[second - 1].size)
for (i in 1..first) {
stacks[second - 1].removeLast()
}
}
return stacks.map { it.last() }.toCharArray().concatToString()
}
// 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 | 0 |
e5dbabe247457aabd6dd0f0eb2eb56f9e4c68858
| 1,946 |
Advent-of-Code-2022
|
Apache License 2.0
|
src/day24/Day24.kt
|
Volifter
| 572,720,551 | false |
{"Kotlin": 65483}
|
package day24
import utils.*
val DIRECTIONS = listOf(
Coords(0, 0),
Coords(1, 0),
Coords(-1, 0),
Coords(0, 1),
Coords(0, -1)
)
data class Coords(var x: Int, var y: Int) {
fun wrapIn(size: Coords): Coords =
Coords(
Math.floorMod(x, size.x),
Math.floorMod(y, size.y)
)
operator fun plus(other: Coords): Coords = Coords(x + other.x, y + other.y)
operator fun contains(other: Coords): Boolean =
other.x in 0 until x
&& other.y in 0 until y
}
data class Blizzard(var position: Coords, private val direction: Coords) {
fun move(size: Coords) {
position = (position + direction).wrapIn(size)
}
}
class Field(input: List<String>) {
val size: Coords = Coords(input.first().length - 2, input.size - 2)
val start: Coords = Coords(input.first().indexOf('.') - 1, -1)
val end: Coords = Coords(input.last().indexOf('.') - 1, size.y)
private val blizzards: List<Blizzard> =
input.slice(1..size.y).flatMapIndexed { y, row ->
row.slice(1..size.x).mapIndexedNotNull { x, c ->
when (c) {
'>' -> Coords(1, 0)
'<' -> Coords(-1, 0)
'v' -> Coords(0, 1)
'^' -> Coords(0, -1)
else -> null
}?.let { Blizzard(Coords(x, y), it) }
}
}
private val blizzardPositions get() = sequence {
while (true) {
yield(blizzards.map { it.position }.toSet())
blizzards.forEach { it.move(size) }
}
}
fun solve(targets: List<Coords>): Int {
val targetsIterator = targets.asSequence().iterator()
var target = targetsIterator.next()
val blizzardsIterator = blizzardPositions.iterator()
var blizzards = blizzardsIterator.next()
return generateSequence(setOf(start)) { stack ->
stack
.flatMap { position ->
DIRECTIONS.mapNotNull { dir ->
(position + dir).takeIf {
(
it in size
|| it == start
|| it == end
) && it !in blizzards
}
}
}
.let { nextStack ->
blizzards = blizzardsIterator.next()
if (target in nextStack)
setOf(target)
.takeIf { targetsIterator.hasNext() }
?.also { target = targetsIterator.next() }
else
nextStack
}
?.toSet()
}.count() - 1
}
}
fun part1(input: List<String>): Int =
Field(input).run { solve(listOf(end)) }
fun part2(input: List<String>): Int =
Field(input).run { solve(listOf(end, start, end)) }
fun main() {
val testInput = readInput("Day24_test")
expect(part1(testInput), 18)
expect(part2(testInput), 54)
val input = readInput("Day24")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
c2c386844c09087c3eac4b66ee675d0a95bc8ccc
| 3,217 |
AOC-2022-Kotlin
|
Apache License 2.0
|
graph/LowestCommonAncestor.kt
|
wangchaohui
| 737,511,233 | false |
{"Kotlin": 36737}
|
class SparseTable<T>(list: List<T>, private val merge: (T, T) -> T) {
private val n = list.size
private val logN = n.takeHighestOneBit().countTrailingZeroBits()
private val table = mutableListOf(list.toList()).apply {
for (i in 1..logN) {
val lastRangeSize = 1 shl i - 1
add(List(n - lastRangeSize * 2 + 1) { j ->
merge(this[i - 1][j], this[i - 1][j + lastRangeSize])
})
}
}
private val logs = IntArray(n).apply {
for (i in 2..<size) this[i] = this[i / 2] + 1
}
/** Query for range [l, r] */
fun query(l: Int, r: Int): T {
val log = logs[r - l]
return merge(table[log][l], table[log][r - (1 shl log) + 1])
}
}
data class Graph(val maxVertexId: Int) {
private val adjacencyList = Array(maxVertexId + 1) { mutableListOf<Int>() }
fun addEdge(u: Int, v: Int) {
adjacencyList[u] += v
adjacencyList[v] += u
}
class VertexEulerTour(
val firstVisitedPosition: IntArray,
val vertexEulerTour: List<Pair<Int, Int>>, // depth to vertexId
)
fun buildVertexEulerTour(start: Int): VertexEulerTour {
val firstVisitedPosition = IntArray(maxVertexId + 1) { -1 }
val vertexEulerTour = mutableListOf<Pair<Int, Int>>()
fun dfs(u: Int, depth: Int) {
firstVisitedPosition[u] = vertexEulerTour.size
vertexEulerTour += depth to u
for (v in adjacencyList[u]) {
if (firstVisitedPosition[v] == -1) {
dfs(v, depth + 1)
vertexEulerTour += depth to u
}
}
}
dfs(start, 0)
return VertexEulerTour(firstVisitedPosition, vertexEulerTour)
}
}
class LowestCommonAncestor(graph: Graph, root: Int) {
private val vertexEulerTour = graph.buildVertexEulerTour(root)
private val sparseTable = SparseTable(vertexEulerTour.vertexEulerTour) { a, b ->
if (a.first < b.first) a else b
}
fun lca(u: Int, v: Int): Int {
val uPos = vertexEulerTour.firstVisitedPosition[u]
val vPos = vertexEulerTour.firstVisitedPosition[v]
return sparseTable.query(min(uPos, vPos), max(uPos, vPos)).second
}
}
| 0 |
Kotlin
| 0 | 0 |
241841f86fdefa9624e2fcae2af014899a959cbe
| 2,257 |
kotlin-lib
|
Apache License 2.0
|
src/main/kotlin/com/hjk/advent22/Day15.kt
|
h-j-k
| 572,485,447 | false |
{"Kotlin": 26661, "Racket": 3822}
|
package com.hjk.advent22
import kotlin.math.abs
object Day15 {
fun part1(input: List<String>, row: Int): Long = noBeaconsOn(input.mapNotNull(Sensor::parse), row)
.fold(0L to Long.MIN_VALUE) { (count, last), range ->
if (count == 0L) (range.last - last.coerceAtLeast(range.first)) to range.last else count to last
}.first
fun part2(input: List<String>, max: Int): Long = input.mapNotNull(Sensor::parse).let { sensors ->
(0..max).reversed().asSequence().mapNotNull { row ->
noBeaconsOn(sensors, row).takeIf { it.size == 2 }?.let { (a, _) -> 4000000 * (a.last + 1) + row }
}.first()
}
private fun noBeaconsOn(sensors: List<Sensor>, row: Int): List<LongRange> =
sensors.mapNotNull { it.getEmptyOnRow(row) }.sortedBy { it.first }.fold(listOf()) { acc, range ->
if (acc.lastOrNull()?.let { it.last + 1 >= range.first } == true)
acc.dropLast(1) + acc.last().let { setOf(it.first..(it.last.coerceAtLeast(range.last))) }
else acc + setOf(range)
}
private data class Sensor(val point: Point2d, val beacon: Point2d) {
private val distance = (point - beacon)
fun getEmptyOnRow(row: Int): LongRange? = (distance - abs(row - point.y).toLong()).takeIf { it > 0L }
?.let { delta -> (point.x - delta)..(point.x + delta) }
companion object {
private val regex =
"Sensor at x=([0-9-]+), y=([0-9-]+): closest beacon is at x=([0-9-]+), y=([0-9-]+)".toRegex()
fun parse(line: String): Sensor? = regex.matchEntire(line)?.destructured?.let { (sX, sY, bX, bY) ->
Sensor(
point = Point2d(x = sX.toInt(), y = sY.toInt()),
beacon = Point2d(x = bX.toInt(), y = bY.toInt())
)
}
}
}
private operator fun LongRange.contains(other: LongRange) = other.first in this && other.last in this
}
| 0 |
Kotlin
| 0 | 0 |
20d94964181b15faf56ff743b8646d02142c9961
| 1,974 |
advent22
|
Apache License 2.0
|
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day22/Day22.kt
|
janvdbergh
| 318,992,922 | false |
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
|
package eu.janvdb.aoc2021.day22
import eu.janvdb.aocutil.kotlin.readLines
import kotlin.math.max
import kotlin.math.min
const val FILENAME = "input22.txt"
fun main() {
val instructions = readLines(2021, FILENAME).map(Instruction::parse)
part(instructions.filter { it.region.xMin>=-50 && it.region.xMax<=50 && it.region.yMin>=-50 && it.region.yMax<=50 && it.region.zMin>=-50 && it.region.zMax<=50})
part(instructions)
}
private fun part(instructions: List<Instruction>) {
var currentRegion = CombinedRegion()
instructions.forEach { currentRegion = currentRegion.apply(it) }
println(currentRegion.volume)
}
data class Region(val xMin: Int, val xMax: Int, val yMin: Int, val yMax: Int, val zMin: Int, val zMax: Int) {
val notEmpty get() = xMin <= xMax && yMin <= yMax && zMin <= zMax
val volume get() = 1L * (xMax - xMin + 1) * (yMax - yMin + 1) * (zMax - zMin + 1)
fun subtract(other: Region): Sequence<Region> {
if (other.xMin > xMax || other.xMax < xMin || other.yMin > yMax || other.yMax < yMin || other.zMin > zMax || other.zMax < zMin)
return sequenceOf(this)
return sequenceOf(
Region(xMin, other.xMin - 1, yMin, yMax, zMin, zMax),
Region(other.xMax + 1, xMax, yMin, yMax, zMin, zMax),
Region(max(other.xMin, xMin), min(other.xMax, xMax), yMin, other.yMin - 1, zMin, zMax),
Region(max(other.xMin, xMin), min(other.xMax, xMax), other.yMax + 1, yMax, zMin, zMax),
Region(max(other.xMin, xMin), min(other.xMax, xMax), max(other.yMin, yMin), min(other.yMax, yMax), zMin, other.zMin - 1),
Region(max(other.xMin, xMin), min(other.xMax, xMax), max(other.yMin, yMin), min(other.yMax, yMax), other.zMax + 1, zMax),
).filter(Region::notEmpty)
}
fun subtract(others: List<Region>): List<Region> {
var current = listOf(this)
others.forEach { other -> current = current.flatMap { it.subtract(other) } }
return current
}
}
data class CombinedRegion(val regions: List<Region> = listOf()) {
val volume get() = regions.map(Region::volume).sum()
fun apply(instruction: Instruction): CombinedRegion {
val newRegions = if (instruction.isAdd)
regions + instruction.region.subtract(regions)
else
regions.flatMap { it.subtract(instruction.region) }
return CombinedRegion(newRegions)
}
}
class Instruction(val region: Region, val isAdd: Boolean) {
companion object {
val regex = Regex("(on|off) x=(-?\\d+)..(-?\\d+),y=(-?\\d+)..(-?\\d+),z=(-?\\d+)..(-?\\d+)")
fun parse(line: String): Instruction {
val matchResult = regex.matchEntire(line)!!
return Instruction(
Region(
matchResult.groupValues[2].toInt(), matchResult.groupValues[3].toInt(),
matchResult.groupValues[4].toInt(), matchResult.groupValues[5].toInt(),
matchResult.groupValues[6].toInt(), matchResult.groupValues[7].toInt()
),
isAdd = matchResult.groupValues[1] == "on"
)
}
}
}
| 0 |
Java
| 0 | 0 |
78ce266dbc41d1821342edca484768167f261752
| 2,840 |
advent-of-code
|
Apache License 2.0
|
dcp_kotlin/src/main/kotlin/dcp/day200/day200.kt
|
sraaphorst
| 182,330,159 | false |
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
|
package dcp.day200
// day200.kt
// By <NAME>, 2019.
import kotlin.math.max
import kotlin.math.min
data class Interval(val start: Double, val end: Double): Comparable<Interval> {
operator fun contains(that: Interval): Boolean = start <= that.start && end >= that.end
operator fun contains(value: Double): Boolean = value in start..end
override fun compareTo(other: Interval): Int {
return COMPARATOR.compare(this, other)
}
fun intersection(other: Interval): Interval? {
// If there is a gap, then there is no intersection.
if (end < other.start || other.end < start)
return null
return Interval(max(start, other.start), min(end, other.end))
}
companion object {
fun makeInterval(start: Double, end: Double): Interval? {
return if (start > end) null else Interval(start, end)
}
private val COMPARATOR = Comparator.comparingDouble<Interval>(Interval::end)
}
}
// This is the non-functional, efficient implementation of findStabbingSet.
// We sort the intervals and then only have to traverse them. Since we allow for nullability, this takes
// O(n log n) complexity and O(n) space: if we eliminate nullibility, we could do it in constant space.
fun smallestStabbingSet(intervals: List<Interval?>): Set<Double> {
// Filter out the nulls, sort by increasing order on the last element, and then take
// the largest number in the current interval.
// Consume intervals until we reach an interval that requires a new stabbing number.
val sortedIntervals = intervals.filterNotNull().sorted()
val stabbingSet = mutableListOf<Double>()
var lastStab: Double? = null
for (interval in sortedIntervals) {
if (lastStab == null || (lastStab !in interval)) {
lastStab = interval.end
stabbingSet.add(lastStab)
}
}
return stabbingSet.toSet()
}
// A functional programming approach: higher complexity and space required, i.e. O(n^2) in each case.
// This will not return the same stabbing set, but the sizes should be the same and they should both be solutions.
fun smallestStabSetFP(intervals: List<Interval?>): Set<Double> {
// We want a set of all intersections of the intervals, and then filter to the minimal intervals, i.e.
// we want the intersection for every pair of intervals (including every interval with itself so that the set
// contains the original intervals) and then we filter out intervals that contain other intervals.
// What is left behind is a set of intervals that is disjoint but has points that cover all the initial
// intervals, so we can just pick one point from each one to get the stab set.
val definedIntervals = intervals.filterNotNull()
val allIntersections = definedIntervals.flatMap { i1 ->definedIntervals.map { i2 -> i1.intersection(i2) } }.filterNotNull().distinct()
val maximalIntervals = allIntersections.filter { i1-> allIntersections.none { i2 -> i1 != i2 && i2 in i1 } }
// Any point from each of the maximalIntervals would do.
return maximalIntervals.map { it.start }.toSet()
}
| 0 |
C++
| 1 | 0 |
5981e97106376186241f0fad81ee0e3a9b0270b5
| 3,156 |
daily-coding-problem
|
MIT License
|
src/Day05.kt
|
ThijsBoehme
| 572,628,902 | false |
{"Kotlin": 16547}
|
/*
Followed along with the Kotlin by JetBrains livestream, with some personal adjustments
*/
private data class Move(
val quantity: Int,
val source: Int,
val target: Int,
) {
companion object {
fun of(line: String): Move {
return line.split(" ")
.filterIndexed { index, _ -> index % 2 == 1 }
.map { it.toInt() }
.let { Move(it[0], it[1] - 1, it[2] - 1) }
}
}
}
private class Day05 {
fun numberOfStacks(lines: List<String>) =
lines.dropWhile { it.contains("[") }
.first()
.split(" ")
.filter { it.isNotBlank() }
.maxOf { it.toInt() }
fun populateStacks(lines: List<String>, onCharacterFound: (Int, Char) -> Unit) {
lines.filter { it.contains("[") }
.map { line ->
line.mapIndexed { index, c ->
if (c.isLetter()) {
val stackNumber = index / 4
val value = line[index]
onCharacterFound(stackNumber, value)
}
}
}
}
}
fun main() {
fun parse(input: List<String>): Pair<List<ArrayDeque<Char>>, List<Move>> {
val day05 = Day05()
val numberOfStacks = day05.numberOfStacks(input)
val stacks = List(numberOfStacks) { ArrayDeque<Char>() }
day05.populateStacks(input) { stackNumber, value -> stacks[stackNumber].addLast(value) }
val moves = input.filter { it.contains("move") }
.map { Move.of(it) }
return Pair(stacks, moves)
}
fun part1(input: List<String>): String {
val (stacks, moves) = parse(input)
moves.forEach { step ->
repeat(step.quantity) {
stacks[step.target].addFirst(stacks[step.source].removeFirst())
}
}
return stacks.map { it.first() }.joinToString("")
}
fun part2(input: List<String>): String {
val (stacks, moves) = parse(input)
moves.forEach { step ->
stacks[step.source].take(step.quantity)
.asReversed()
.forEach {
stacks[step.target].addFirst(it)
stacks[step.source].removeFirst()
}
}
return stacks.map { it.first() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
707e96ec77972145fd050f5c6de352cb92c55937
| 2,668 |
Advent-of-Code-2022
|
Apache License 2.0
|
day12/day12.kt
|
carolhmj
| 231,454,053 | false | null |
import kotlin.math.*
import java.io.File
data class Moon(val position : IntArray, val velocity : IntArray = intArrayOf(0,0,0))
data class IndexAndValue<T>(val index : Int, val value : T)
fun <T, U> cartesianProductIndexed(c1: Collection<T>, c2: Collection<U>): List<Pair<IndexAndValue<T>, IndexAndValue<U>>> {
return c1.mapIndexed { lhsIdx, lhsElem -> c2.mapIndexed { rhsIdx, rhsElem -> IndexAndValue(lhsIdx, lhsElem) to IndexAndValue(rhsIdx, rhsElem) } }.flatten()
}
fun sumArrays(a : IntArray, b : IntArray) : IntArray {
return a.zip(b).map {(x, y) -> x + y}.toIntArray()
}
fun sumAbs(a : IntArray) : Int {
return a.map { abs(it) }.sum()
}
fun calculateEnergy(moons : List<Moon>) : Int {
return moons.map { sumAbs(it.position) * sumAbs(it.velocity) }.sum()
}
fun step(moons : List<Moon>) : List<Moon> {
val accelerations = cartesianProductIndexed(moons, moons).map { (moonA, moonB) ->
moonA.index to moonA.value.position.zip(moonB.value.position).map { (posA : Int, posB : Int) ->
(posB - posA).sign
}.toIntArray()
}.groupBy({ it.first }, { it.second }).map { (k, v) -> k to v.reduce({ acc : IntArray, curr : IntArray -> sumArrays(acc, curr) }) }
val updatedMoons = accelerations.map { (idx, acceleration) ->
val newVelocity = sumArrays(moons[idx].velocity, acceleration)
val newPosition = sumArrays(moons[idx].position, newVelocity)
Moon(newPosition, newVelocity)
}
return updatedMoons
}
fun readInput(filename : String) : List<Moon> {
return File(filename).readLines().map {
val (x, y, z) = """<x=(-?\d+), y=(-?\d+), z=(-?\d+)>""".toRegex().find(it)!!.destructured
Moon(intArrayOf(x.toInt(), y.toInt(), z.toInt()))
}
}
fun main() {
// var moons = listOf(Moon(intArrayOf(-1,0,2)), Moon(intArrayOf(2,-10,-7)), Moon(intArrayOf(4,-8,8)), Moon(intArrayOf(3,5,-1)))
// var moons = listOf(Moon(intArrayOf(-8,-10,0)), Moon(intArrayOf(5,5,10)), Moon(intArrayOf(2,-7,3)), Moon(intArrayOf(9,-8,-3)))
var moons = readInput("input.txt")
println("Input moons ${moons}")
var steps = 1000
for (i in 1..steps) {
moons = step(moons)
}
println("moons after loop ${moons}")
val energy = calculateEnergy(moons)
println("Calculated energy ${energy}")
}
| 0 |
Rust
| 0 | 0 |
a10106877f180e989360b80c76048b2d4161b370
| 2,312 |
aoc2019
|
MIT License
|
src/Day07.kt
|
buczebar
| 572,864,830 | false |
{"Kotlin": 39213}
|
private const val TOTAL_DISK_SPACE = 70000000L
private const val SPACE_NEEDED_FOR_UPDATE = 30000000L
fun main() {
fun part1(fileTree: TreeNode): Long {
return fileTree.getAllSubdirectories().filter { it.totalSize <= 100_000 }.sumOf { it.totalSize }
}
fun part2(fileTree: TreeNode): Long {
val spaceAvailable = TOTAL_DISK_SPACE - fileTree.totalSize
val spaceToBeFreed = SPACE_NEEDED_FOR_UPDATE - spaceAvailable
return fileTree.getAllSubdirectories().sortedBy { it.totalSize }
.firstOrNull { it.totalSize > spaceToBeFreed }?.totalSize ?: 0L
}
val testInput = readInput("Day07_test")
val testInputFileTree = buildFileTree(testInput)
check(part1(testInputFileTree) == 95_437L)
check(part2(testInputFileTree) == 24_933_642L)
val input = readInput("Day07")
val inputFileTree = buildFileTree(input)
println(part1(inputFileTree))
println(part2(inputFileTree))
}
private fun buildFileTree(consoleLog: List<String>): TreeNode {
val rootNode = DirNode("/", null)
var currentNode = rootNode as TreeNode
consoleLog.forEach { line ->
when {
line.isCdCommand() -> {
val (_, _, name) = line.splitWords()
currentNode = when (name) {
".." -> currentNode.parent ?: return@forEach
"/" -> rootNode
else -> currentNode.getChildByName(name)
}
}
line.isDir() -> {
val (_, name) = line.splitWords()
currentNode.addChild(DirNode(name))
}
line.isFile() -> {
val (size, name) = line.splitWords()
currentNode.addChild(FileNode(name, size.toLong()))
}
}
}
return rootNode
}
private fun String.isDir() = startsWith("dir")
private fun String.isFile() = "\\d+ [\\w.]+".toRegex().matches(this)
private fun String.isCdCommand() = startsWith("$ cd")
private abstract class TreeNode(private val name: String, var parent: TreeNode?, val children: MutableList<TreeNode>?) {
open val totalSize: Long
get() {
return children?.sumOf { it.totalSize } ?: 0
}
fun addChild(node: TreeNode) {
node.parent = this
children?.add(node)
}
fun getChildByName(name: String): TreeNode {
return children?.firstOrNull { it.name == name } ?: this
}
fun getAllSubdirectories(): List<DirNode> {
return getAllSubNodes().filterIsInstance<DirNode>()
}
private fun getAllSubNodes(): List<TreeNode> {
val result = mutableListOf<TreeNode>()
if (children != null) {
for (child in children) {
result.addAll(child.getAllSubNodes())
result.add(child)
}
}
return result
}
}
private class DirNode(name: String, parent: TreeNode? = null, children: MutableList<TreeNode> = mutableListOf()) :
TreeNode(name, parent, children)
private class FileNode(name: String, override val totalSize: Long, parent: DirNode? = null) :
TreeNode(name, parent, null)
| 0 |
Kotlin
| 0 | 0 |
cdb6fe3996ab8216e7a005e766490a2181cd4101
| 3,150 |
advent-of-code
|
Apache License 2.0
|
src/day05/Day05.kt
|
Ciel-MC
| 572,868,010 | false |
{"Kotlin": 55885}
|
package day05
import readInput
import java.util.*
fun main() {
fun parseCrateStack(input: List<String>): Map<Int, Stack<Char>> {
return buildMap {
input.reversed().forEach { row ->
row.chunked(4).map { it.trim().removeSurrounding("[", "]") }
.map { it.firstOrNull() }
.forEachIndexed { index, c ->
if (c == null) return@forEachIndexed
this.getOrPut(index+1) { Stack() }.push(c)
}
}
}
}
data class Instruction(val amount: Int, val from: Int, val to: Int)
val instructionRegex = Regex("""move (\d+) from (\d+) to (\d+)""")
fun parseInstructions(input: String): Instruction {
val (amount, from, to) = instructionRegex.matchEntire(input)?.destructured ?: error("Invalid input")
return Instruction(amount.toInt(), from.toInt(), to.toInt())
}
fun List<String>.indexOfEndOfStacks(): Int {
return this.indexOfFirst { "[" !in it }
}
fun <T> List<T>.splitAt(index: Int): Pair<List<T>, List<T>> {
return this.take(index) to this.drop(index)
}
fun part1(input: List<String>): String {
val (stack, instruction) = input.splitAt(input.indexOfEndOfStacks())
val stacks = parseCrateStack(stack)
val instructions = instruction.drop(1).map(::parseInstructions)
instructions.forEach { (amount, from, to) ->
repeat(amount) {
stacks[to]!!.push(stacks[from]!!.pop())
}
}
return stacks.entries
.sortedBy { it.key }
.map { it.value.peek() }
.joinToString("")
}
fun part2(input: List<String>): String {
val (stack, instruction) = input.splitAt(input.indexOfEndOfStacks())
val stacks = parseCrateStack(stack)
val instructions = instruction.drop(1).map(::parseInstructions)
val crane = Stack<Char>()
instructions.forEach { (amount, from, to) ->
repeat(amount) {
crane.push(stacks[from]!!.pop())
}
repeat(amount) {
stacks[to]!!.push(crane.pop())
}
}
return stacks.entries
.sortedBy { it.key }
.map { it.value.peek() }
.joinToString("")
}
val testInput = readInput(5, true)
part1(testInput).let { check(it == "CMZ") { println(it) } }
part2(testInput).let { check(it == "MCD") { println(it) } }
val input = readInput(5)
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
7eb57c9bced945dcad4750a7cc4835e56d20cbc8
| 2,645 |
Advent-Of-Code
|
Apache License 2.0
|
src/year2023/day15/Day15.kt
|
lukaslebo
| 573,423,392 | false |
{"Kotlin": 222221}
|
package year2023.day15
import check
import readInput
fun main() {
val testInput = readInput("2023", "Day15_test")
check(part1(testInput), 1320)
check(part2(testInput), 145)
val input = readInput("2023", "Day15")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = input.first().split(',').sumOf { it.hash() }
private fun part2(input: List<String>): Int {
val boxes = List(256) { LinkedHashMap<String, Int>() }
for (operation in input.parseOperations()) {
val box = boxes[operation.label.hash()]
when (operation) {
is Put -> box[operation.label] = operation.focalLength
is Remove -> box.remove(operation.label)
}
}
return boxes.focalPower()
}
private fun String.hash(): Int = fold(0) { acc, c ->
((acc + c.code) * 17) % 256
}
private sealed interface Operation {
val label: String
}
private data class Remove(override val label: String) : Operation
private data class Put(override val label: String, val focalLength: Int) : Operation
private fun List<String>.parseOperations() = first().split(',').map { line ->
if (line.endsWith("-")) Remove(line.dropLast(1))
else Put(line.substringBefore("="), line.substringAfter("=").toInt())
}
private fun List<Map<String, Int>>.focalPower() = flatMapIndexed { boxIndex, box ->
box.entries.mapIndexed { lensIndex, (_, focusLength) ->
(boxIndex + 1) * (lensIndex + 1) * focusLength
}
}.sum()
| 0 |
Kotlin
| 0 | 1 |
f3cc3e935bfb49b6e121713dd558e11824b9465b
| 1,493 |
AdventOfCode
|
Apache License 2.0
|
src/main/kotlin/com/dmc/advent2022/Day02.kt
|
dorienmc
| 576,916,728 | false |
{"Kotlin": 86239}
|
// --- Day 2: Rock Paper Scissors ---
package com.dmc.advent2022
class Day02 : Day<Int> {
override val index = 2
override fun part1(input: List<String>): Int {
return input.sumOf { calcScore1(it.split(" ")) }
}
override fun part2(input: List<String>): Int {
return input.sumOf { calcScore2(it.split(" ")) }
}
}
enum class OutCome(val score: Int) {
LOSE(0),
DRAW(3),
WIN(6);
fun getOppositeOutcome() : OutCome {
return when(this) {
DRAW -> DRAW
WIN -> LOSE
LOSE -> WIN
}
}
}
enum class Shape(val score: Int, val vsRock: OutCome, val vsPaper: OutCome, val vsSciccor: OutCome) {
ROCK(1, OutCome.DRAW, OutCome.LOSE, OutCome.WIN),
PAPER(2, OutCome.WIN, OutCome.DRAW, OutCome.LOSE),
SCISSORS(3, OutCome.LOSE, OutCome.WIN, OutCome.DRAW);
fun outcome(otherShape: Shape) : OutCome {
return when (otherShape) {
ROCK -> this.vsRock
PAPER -> this.vsPaper
SCISSORS -> this.vsSciccor
}
}
fun getExpectedOutcome(outCome: OutCome) : Shape {
return when (outCome) {
this.vsPaper -> PAPER
this.vsRock -> ROCK
else -> SCISSORS
}
}
}
fun String.toShape(): Shape {
return when (this) {
"A","X" -> Shape.ROCK
"B","Y" -> Shape.PAPER
else -> Shape.SCISSORS
}
}
fun String.toOutCome() : OutCome {
return when (this) {
"X" -> OutCome.LOSE
"Y" -> OutCome.DRAW
else -> OutCome.WIN
}
}
fun calcScore1(input: List<String>) : Int {
return calcScore1(input[0].toShape(),input[1].toShape())
}
fun calcScore1(opponent: Shape, myShape: Shape) : Int {
// Shape score
val shapeScore = myShape.score
// Did I win?
val outcomeScore = myShape.outcome(opponent).score
// Add it
return shapeScore + outcomeScore
}
fun calcScore2(input: List<String>) : Int {
return calcScore2(input[0].toShape(),input[1].toOutCome())
}
fun calcScore2(opponent: Shape, expectedOutCome: OutCome) : Int {
// Determine shape (note that Shape.getExpectedOutcome is the outcome for the opponent)
val myShape = opponent.getExpectedOutcome(expectedOutCome.getOppositeOutcome())
// Add it
return myShape.score + expectedOutCome.score
}
fun main() {
val day = Day02()
// test if implementation meets criteria from the description, like:
val testInput = readInput(day.index, true)
check(day.part1(testInput) == 15)
val input = readInput(day.index)
day.part1(input).println()
day.part2(input).println()
}
| 0 |
Kotlin
| 0 | 0 |
207c47b47e743ec7849aea38ac6aab6c4a7d4e79
| 2,634 |
aoc-2022-kotlin
|
Apache License 2.0
|
src/main/kotlin/面试题 17.24. 最大子矩阵.kts
|
ShreckYe
| 206,086,675 | false | null |
import kotlin.test.assertContentEquals
class Solution {
data class SumFromC1(val c1: Int, val sum: Long)
fun getMaxMatrix(matrix: Array<IntArray>): IntArray {
val m = matrix.size
val n = matrix.first().size
// empty submatrices not allowed
val prefixSumsAtC = Array(n) { c ->
(0 until m).map { r -> matrix[r][c] }.runningFold(0L) { acc, n -> acc + n }
}
val maxWithR1R2C2 = Array(m) { Array(m) { Array<SumFromC1?>(n) { null } } }
for (r1 in 0 until m)
for (r2 in r1 until m) {
val maxWithC2 = maxWithR1R2C2[r1][r2]
for (c2 in 0 until n) {
val columnSum = prefixSumsAtC[c2].let { it[r2 + 1] - it[r1] }
val column = SumFromC1(c2, columnSum)
maxWithC2[c2] =
if (c2 == 0) column
else maxWithC2[c2 - 1]!!.let {
if (it.sum > 0) SumFromC1(it.c1, it.sum + columnSum) else column
}
}
}
return maxWithR1R2C2.asSequence().withIndex().flatMap { (r1, array) ->
array.asSequence().withIndex()
.drop(r1)
.flatMap { (r2, array) ->
array.asSequence() // for LeetCode's Kotlin version
.mapIndexed { c2, sumFromC1 ->
intArrayOf(r1, sumFromC1!!.c1, r2, c2) to sumFromC1.sum
}
}
}.maxByOrNull { it.second }!!.first // for LeetCode's Kotlin version
//.maxByOrNull { it.second }!!.first
}
/** Adapted from [kotlin.collections.runningFold] for LeetCode's Kotlin version. */
inline fun <T, R> List<T>.runningFold(initial: R, operation: (acc: R, T) -> R): List<R> {
val size = size
if (size == 0) return listOf(initial)
val result = ArrayList<R>(size + 1).apply { add(initial) }
var accumulator = initial
for (element in this) {
accumulator = operation(accumulator, element)
result.add(accumulator)
}
return result
}
}
val solution = Solution()
// question sample
assertContentEquals(
intArrayOf(0, 1, 0, 1),
solution.getMaxMatrix(
arrayOf(
intArrayOf(-1, 0),
intArrayOf(0, -1)
)
)
)
// my own tests
assertContentEquals(
intArrayOf(0, 0, 0, 0),
solution.getMaxMatrix(arrayOf(intArrayOf(1)))
)
assertContentEquals(
intArrayOf(1, 1, 1, 1),
solution.getMaxMatrix(Array(3) { IntArray(3) { -1 } }.also { it[1][1] = 1 })
)
| 0 |
Kotlin
| 0 | 0 |
20e8b77049fde293b5b1b3576175eb5703c81ce2
| 2,653 |
leetcode-solutions-kotlin
|
MIT License
|
src/Day02.kt
|
fedochet
| 573,033,793 | false |
{"Kotlin": 77129}
|
private enum class GameMove {
ROCK, PAPER, SCISSORS;
val winsOver: GameMove
get() = when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
val loosesTo: GameMove
get() = when (this) {
SCISSORS -> ROCK
ROCK -> PAPER
PAPER -> SCISSORS
}
}
private enum class GameOutcome {
WIN, LOOSE, DRAW
}
fun main() {
fun parseMove(c: Char): GameMove = when (c) {
'A', 'X' -> GameMove.ROCK
'B', 'Y' -> GameMove.PAPER
'C', 'Z' -> GameMove.SCISSORS
else -> error("Unknown char '$c'")
}
fun parseOutcome(c: Char): GameOutcome = when (c) {
'X' -> GameOutcome.LOOSE
'Y' -> GameOutcome.DRAW
'Z' -> GameOutcome.WIN
else -> error("Unknown char '$c'")
}
fun matchResult(player: GameMove, opponent: GameMove): GameOutcome = when {
player.winsOver == opponent -> GameOutcome.WIN
player.loosesTo == opponent -> GameOutcome.LOOSE
player == opponent -> GameOutcome.DRAW
else -> error("Unexpected combination of moves: $player vs $opponent")
}
fun matchScore(player: GameMove, opponent: GameMove): Int {
val initialScore = when (player) {
GameMove.ROCK -> 1
GameMove.PAPER -> 2
GameMove.SCISSORS -> 3
}
val resultScore = when (matchResult(player, opponent)) {
GameOutcome.WIN -> 6
GameOutcome.LOOSE -> 0
GameOutcome.DRAW -> 3
}
return initialScore + resultScore
}
fun part1(input: List<String>): Int {
return input.sumOf { match ->
val (opponentChar, _, playerChar) = match.toList()
val playerMove = parseMove(playerChar)
val opponentMove = parseMove(opponentChar)
matchScore(playerMove, opponentMove)
}
}
fun moveForOutcome(outcome: GameOutcome, opponent: GameMove): GameMove = when (outcome) {
GameOutcome.DRAW -> opponent
GameOutcome.WIN -> opponent.loosesTo
GameOutcome.LOOSE -> opponent.winsOver
}
fun part2(input: List<String>): Int {
return input.sumOf { match ->
val (opponentChar, _, outcomeChar) = match.toList()
val opponentMove = parseMove(opponentChar)
val outcome = parseOutcome(outcomeChar)
val playerMove = moveForOutcome(outcome, opponentMove)
matchScore(playerMove, opponentMove)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
975362ac7b1f1522818fc87cf2505aedc087738d
| 2,825 |
aoc2022
|
Apache License 2.0
|
src/day12/Day12.kt
|
iulianpopescu
| 572,832,973 | false |
{"Kotlin": 30777}
|
package day12
import readInput
import kotlin.math.min
private const val DAY = "12"
private const val DAY_TEST = "day${DAY}/Day${DAY}_test"
private const val DAY_INPUT = "day${DAY}/Day${DAY}"
fun main() {
val directions = listOf(0 to 1, 0 to -1, 1 to 0, -1 to 0)
fun findShortestPaths(
input: List<String>,
startPosition: Pair<Int, Int>,
climbCheck: (Int, Int, Int, Int) -> Boolean
): Array<Array<Int>> {
val steps = Array(input.size) { Array(input.first().length) { Int.MAX_VALUE } }
steps[startPosition.first][startPosition.second] = 0
val queue = ArrayDeque<Pair<Int, Int>>()
queue.add(startPosition)
while (queue.isNotEmpty()) {
val (x, y) = queue.removeFirst()
directions
.map { (dx, dy) -> x + dx to y + dy }
.filter { (newX, newY) -> newX in input.indices && newY in input[newX].indices }
.filter { (newX, newY) -> climbCheck(x, y, newX, newY) && steps[newX][newY] > steps[x][y] + 1 }
.forEach { (newX, newY) ->
steps[newX][newY] = steps[x][y] + 1
queue.add(newX to newY)
}
}
return steps
}
fun part1(input: List<String>): Int {
var startPosition: Pair<Int, Int>? = null
var endPosition: Pair<Int, Int>? = null
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == 'S')
startPosition = i to j
else if (input[i][j] == 'E')
endPosition = i to j
}
}
val climbCheck = { x: Int, y: Int, newX: Int, newY: Int ->
input[x][y].value >= input[newX][newY].value || input[x][y].value + 1 == input[newX][newY].value
}
return findShortestPaths(input, startPosition!!, climbCheck)[endPosition!!.first][endPosition.second]
}
fun part2(input: List<String>): Int {
var startPosition: Pair<Int, Int>? = null
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == 'E')
startPosition = i to j
}
}
val climbCheck = { x: Int, y: Int, newX: Int, newY: Int ->
input[x][y].value <= input[newX][newY].value || input[x][y].value - 1 == input[newX][newY].value
}
val steps = findShortestPaths(input, startPosition!!, climbCheck)
var minSteps = Int.MAX_VALUE
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == 'a')
minSteps = min(minSteps, steps[i][j])
}
}
return minSteps
}
// 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_INPUT)
println(part1(input)) // 370
println(part2(input)) // 363
}
private val Char.value: Char
get() = when (this) {
'S' -> 'a'
'E' -> 'z'
else -> this
}
| 0 |
Kotlin
| 0 | 0 |
4ff5afb730d8bc074eb57650521a03961f86bc95
| 3,165 |
AOC2022
|
Apache License 2.0
|
src/Day11.kt
|
ambrosil
| 572,667,754 | false |
{"Kotlin": 70967}
|
import kotlin.math.floor
fun main() {
data class Monkey(
val items: MutableList<Long>,
val operation: String,
val divisor: Long,
val trueMonkey: Int,
val falseMonkey: Int,
var inspections: Long = 0
)
fun parse(input: List<String>) =
input
.joinToString("\n")
.split("\n\n")
.map {
val (itemsInput, operationInput, testInput, trueInput, falseInput) = it.split("\n").drop(1)
val items = itemsInput.substringAfter("items: ")
.split(",")
.map { s -> s.trim().toLong() }
.toMutableList()
val operation = operationInput.substringAfter("new =").trim()
val divisibleBy = testInput.substringAfter("by ").toLong()
val trueMonkey = trueInput.substringAfter("monkey ").toInt()
val falseMonkey = falseInput.substringAfter("monkey ").toInt()
Monkey(items, operation, divisibleBy, trueMonkey, falseMonkey)
}
fun operation(operation: String, item: Long): Long {
val expression = operation.replace("old", item.toString())
val (n1, op, n2) = expression.split(" ")
return when (op) {
"+" -> n1.toLong() + n2.toLong()
"*" -> n1.toLong() * n2.toLong()
else -> error("wrong operation $op")
}
}
fun common(input: List<String>, maxIterations: Int, nextWorryLevel: (operationResult: Long, magicNumber: Long) -> Long): Long {
val monkeys = parse(input)
val magicNumber = monkeys.map { it.divisor }.reduce { acc, i ->
acc * i
}
repeat(maxIterations) {
monkeys.forEach {
it.items.forEach { item ->
it.inspections++
val operationResult = operation(it.operation, item)
val worryLevel = nextWorryLevel(operationResult, magicNumber)
if (worryLevel divisibleBy it.divisor) {
monkeys[it.trueMonkey].items += worryLevel
} else {
monkeys[it.falseMonkey].items += worryLevel
}
}
it.items.clear()
}
}
return monkeys
.map { it.inspections }
.sorted()
.takeLast(2)
.reduce { acc, i ->
acc * i
}
}
fun part1(input: List<String>): Long {
return common(input, 20) { operationResult, _ ->
floor(operationResult / 3.0).toLong()
}
}
fun part2(input: List<String>): Long {
return common(input, 10000) { operationResult, magicNumber ->
operationResult % magicNumber
}
}
val input = readInput("inputs/Day11")
println(part1(input))
println(part2(input))
}
infix fun Long.divisibleBy(divisor: Long) = this % divisor == 0L
| 0 |
Kotlin
| 0 | 0 |
ebaacfc65877bb5387ba6b43e748898c15b1b80a
| 3,021 |
aoc-2022
|
Apache License 2.0
|
src/Day07/Day07.kt
|
brhliluk
| 572,914,305 | false |
{"Kotlin": 16006}
|
fun main() {
val TOTAL_SPACE = 70000000
val REQUIRED_SPACE = 30000000
fun parseFs(input: List<String>): Folder {
val root = Folder("/", null)
var currentFolder = root
input.forEach { line ->
if (line.startsWith("$")) {
val command = line.trimStart('$').trim().split(" ")
when (command.first()) {
"cd" -> {
currentFolder = when (command.last()) {
".." -> currentFolder.parent!!
"/" -> root
else -> currentFolder.contents.first { it is Folder && it.name == command.last() } as Folder
}
}
"ls" -> { /* Nothing? */
}
else -> error("Unknown command")
}
} else {
val content = line.split(" ")
when (content.first()) {
"dir" -> currentFolder.contents.add(Folder(content.last(), currentFolder))
else -> currentFolder.contents.add(File(content.last(), content.first().toInt()))
}
}
}
return root
}
fun part1(input: List<String>): Int {
val root = parseFs(input)
return root.folders.map { folder ->
folder.getSmallerThan(setOf()).map { it.size }.sumOf { it }
}.sumOf { it }
}
fun part2(input: List<String>): Int {
val root = parseFs(input)
val needsToBeFreed = REQUIRED_SPACE - (TOTAL_SPACE - root.size)
return root.folders.map { folder ->
val largeFolders = folder.getLargerThan(setOf(), needsToBeFreed).ifEmpty { return@map Int.MAX_VALUE }
largeFolders.map { it.size }.minOf { it }
}.minOf { it }
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
class Folder(override val name: String, val parent: Folder?, val contents: MutableList<FS> = mutableListOf()) : FS {
override val size get() = contents.sumOf { it.size }
val folders get() = contents.filterIsInstance<Folder>()
fun getSmallerThan(smallerFolders: Set<Folder>, maxSize: Int = 100000): Set<Folder> {
val smallFolders = mutableSetOf(smallerFolders)
folders.forEach {
smallFolders.add(it.getSmallerThan(setOf(), maxSize))
}
val result = smallerFolders union smallFolders.flatten().toSet()
return if (size < maxSize) result + this@Folder else result
}
fun getLargerThan(largerFolders: Set<Folder>, minSize: Int): Set<Folder> {
if (size < minSize) return largerFolders
val largeFolders = mutableSetOf(largerFolders)
folders.forEach {
largeFolders.add(it.getLargerThan(setOf(), minSize))
}
val result = largerFolders union largeFolders.flatten().toSet()
return result + this@Folder
}
}
class File(override val name: String, override val size: Int) : FS
interface FS {
val name: String
val size: Int
}
| 0 |
Kotlin
| 0 | 0 |
96ac4fe0c021edaead8595336aad73ef2f1e0d06
| 3,108 |
kotlin-aoc
|
Apache License 2.0
|
src/Day05.kt
|
muellerml
| 573,601,715 | false |
{"Kotlin": 14872}
|
import com.sun.org.apache.xpath.internal.operations.Bool
fun main() {
fun part1(input: List<String>): String {
return performMoves(input, reversed = true)
}
fun part2(input: List<String>): String {
return performMoves(input, reversed = false)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day05_test")
val result = part1(testInput)
println(result)
check(result == "CMZ")
val input = readInput("day05")
println("Part1: " + part1(input))
val result2 = part2(testInput)
println(result2)
check(result2 == "MCD")
println("Part2: " + part2(input))
}
data class Move(
val numTake: Int,
val from: Int,
val to: Int,
)
private fun performMoves(input: List<String>, reversed: Boolean): String {
val stack = input.takeWhile { it.isNotEmpty() }
val moves = input.takeLastWhile { it.isNotEmpty() }
val stacks = stack.dropLast(1).map {
it.windowed(4,4, partialWindows = true).map { it.trim() }
}
val sortedStacks = mutableMapOf<Int, List<String>>()
stacks.forEach {list ->
list.forEachIndexed { index, s ->
if (s.isNotEmpty()) {
val charList = sortedStacks.getOrPut(index) { mutableListOf() }
val value = s.removePrefix("[").removeSuffix("]")
sortedStacks[index] = charList + value
}
}
}
val sorted = sortedStacks.toSortedMap()
val regex = Regex("""move (\d+) from (\d+) to (\d+)""")
val parsedMoves = moves.map { regex.find(it) }.map {
val (numTake, from, to) = it!!.destructured
Move(numTake.toInt(), from.toInt(), to.toInt())
}
val result = parsedMoves.fold(sorted) { sorted, move ->
val originalFrom = sorted[move.from - 1]!!
val taken = originalFrom.take(move.numTake)
sorted.compute(move.from - 1) { _, list -> list!!.drop(move.numTake) }
sorted.compute(move.to - 1) { _, list -> (if (reversed) taken.reversed() else taken) + list!! }
val result = sorted
result
}
return result.map { (_, value) -> value.first() }.joinToString("")
}
| 0 |
Kotlin
| 0 | 0 |
028ae0751d041491009ed361962962a64f18e7ab
| 2,193 |
aoc-2022
|
Apache License 2.0
|
src/day12/Day12.kt
|
EndzeitBegins
| 573,569,126 | false |
{"Kotlin": 111428}
|
package day12
import readInput
import readTestInput
private data class Node(
val elevation: Int,
val rawElevation: Char,
)
private data class Coordinate(val x: Int, val y: Int)
private infix fun Int.to(y: Int) = Coordinate(x = this, y = y)
private fun List<String>.toNodeMap(): Map<Coordinate, Node> =
flatMapIndexed { y, row ->
row.mapIndexed { x, elevation ->
val coordinate = Coordinate(x, y)
val node = Node(
elevation = when (elevation) {
in 'a'..'z' -> elevation - 'a'
'S' -> 0
'E' -> 26
else -> error("Elevation '$elevation' is not supported!")
},
rawElevation = elevation,
)
coordinate to node
}
}.toMap()
private fun Node.canBeReachedFrom(node: Node): Boolean =
this.elevation - node.elevation <= 1
private typealias Path = List<Node>
private fun Map<Coordinate, Node>.findShortestPaths(
vararg startNodeCoordinates: Coordinate
): Map<Coordinate, Path?> {
val shortestPaths: MutableMap<Coordinate, Path?> =
this.mapValues { _ -> null }.toMutableMap()
val nodesToScan = mutableListOf(*startNodeCoordinates)
for (startNodeCoordinate in startNodeCoordinates) {
shortestPaths[startNodeCoordinate] = emptyList()
}
while (nodesToScan.isNotEmpty()) {
val nodeCoordinates = nodesToScan.removeFirst()
val node = getValue(nodeCoordinates)
val adjacentNodeCoordinates = listOf(
nodeCoordinates.x - 1 to nodeCoordinates.y,
nodeCoordinates.x + 1 to nodeCoordinates.y,
nodeCoordinates.x to nodeCoordinates.y - 1,
nodeCoordinates.x to nodeCoordinates.y + 1,
)
val path: Path = (shortestPaths[nodeCoordinates] ?: emptyList()) + node
for (adjacentNodeCoordinate in adjacentNodeCoordinates) {
val adjacentNode = get(adjacentNodeCoordinate)
if (adjacentNode != null && adjacentNode.canBeReachedFrom(node)) {
val currentPath = shortestPaths[adjacentNodeCoordinate]
val currentDistance = currentPath?.size ?: Int.MAX_VALUE
if (path.size < currentDistance) {
shortestPaths[adjacentNodeCoordinate] = path
nodesToScan.add(adjacentNodeCoordinate)
}
}
}
}
return shortestPaths
}
private fun part1(input: List<String>): Int {
val nodeMap = input.toNodeMap()
val startNodeCoordinate = nodeMap.entries
.single { (_, node) -> node.rawElevation == 'S' }
.key
val endNodeCoordinate = nodeMap.entries
.single { (_, node) -> node.rawElevation == 'E' }
.key
val shortestPaths: Map<Coordinate, Path?> =
nodeMap.findShortestPaths(startNodeCoordinate)
return checkNotNull(shortestPaths[endNodeCoordinate.x to endNodeCoordinate.y]).size
}
private fun part2(input: List<String>): Int {
val nodeMap = input.toNodeMap()
val startNodeCoordinates = nodeMap.entries
.filter { (_, node) -> node.rawElevation in setOf('S', 'a') }
.map { it.key }
val endNodeCoordinate = nodeMap.entries
.single { (_, node) -> node.rawElevation == 'E' }
.key
val shortestPaths: Map<Coordinate, Path?> =
nodeMap.findShortestPaths(*startNodeCoordinates.toTypedArray())
return checkNotNull(shortestPaths[endNodeCoordinate.x to endNodeCoordinate.y]).size
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day12")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
ebebdf13cfe58ae3e01c52686f2a715ace069dab
| 3,835 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/main/kotlin/com/briarshore/aoc2022/day03/Puzzle.kt
|
steveswing
| 579,243,154 | false |
{"Kotlin": 47151}
|
package com.briarshore.aoc2022.day03
import println
import readInput
import kotlin.streams.asSequence
fun main() {
val lowerRange = IntRange('a'.code, 'z'.code) // 97 - 122 -> 1 - 26 = c - 96
val upperRange = IntRange('A'.code, 'Z'.code) // 65 - 90 -> 27 - 52 = c - 38
fun translateToPriority(item: Int): Int {
return when {
lowerRange.contains(item) -> item - 96
upperRange.contains(item) -> item - 38
else -> {
throw Exception("Invalid Character value")
}
}
}
fun sharedFold(input: List<String>): MutableList<MutableList<Set<Char>>> =
input.foldIndexed(mutableListOf()) { index: Int, acc: MutableList<MutableList<Set<Char>>>, s: String ->
if (index % 3 == 0) {
acc.add(mutableListOf())
}
acc.last().add(s.toSet())
acc
}
fun mapToCharSet(contents: String): Set<Char> = contents.toSet()
fun mapToIntSet(contents: String): Set<Int> = contents
.chars()
.map(::translateToPriority)
.asSequence()
.toHashSet()
fun part1(contents: List<String>): Int {
return contents.map { Pair(it.slice(IntRange(0, it.length / 2 - 1)), it.slice(IntRange(it.length / 2, it.length - 1))) }
.map { Pair(mapToCharSet(it.first), mapToCharSet(it.second)) }
// .map { Pair(mapToIntSet(it.first), mapToIntSet(it.second)) }
// .filter { it.first.size == it.second.size }
.sumOf { translateToPriority(it.first.intersect(it.second).first().code) }
}
fun part2(contents: List<String>): Int {
return sharedFold(contents)
.map { it.fold(mutableSetOf()) { acc: Set<Char>, contents: Set<Char> ->
if (acc.isEmpty()) {
contents
} else {
acc.intersect(contents)
}
}}
.map { it.first() }
.map { it.code }
.sumOf(::translateToPriority)
}
val sampleInput = readInput("d3p1-sample")
check(part1(sampleInput) == 157)
check(part2(sampleInput) == 70)
val input = readInput("d3p1-input")
val part1 = part1(input)
"part1 $part1".println()
val part2 = part2(input)
"part2 $part2".println()
}
| 0 |
Kotlin
| 0 | 0 |
a0d19d38dae3e0a24bb163f5f98a6a31caae6c05
| 2,335 |
2022-AoC-Kotlin
|
Apache License 2.0
|
src/Day02.kt
|
sushovan86
| 573,586,806 | false |
{"Kotlin": 47064}
|
interface CalculateScore {
fun moveScore(): Int
fun outcome(): Int
fun totalScore(): Int = moveScore() + outcome()
}
data class Round(
val opponentMove: String,
val selfMove: String
)
class Strategy1Score(private val round: Round) : CalculateScore {
override fun moveScore(): Int = when (round.selfMove) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> error("Invalid self move ${round.selfMove}")
}
override fun outcome(): Int = (round.opponentMove + round.selfMove).let { move ->
when (move) {
"AX", "BY", "CZ" -> 3
"BX", "CY", "AZ" -> 0
"CX", "AY", "BZ" -> 6
else -> error("Invalid combination of ${round.opponentMove} and ${round.selfMove}")
}
}
}
class Strategy2Score(private val round: Round) : CalculateScore {
override fun moveScore(): Int = (round.opponentMove + round.selfMove).let { move ->
when (move) {
"AY", "BX", "CZ" -> 1
"BY", "CX", "AZ" -> 2
"CY", "AX", "BZ" -> 3
else -> error("Invalid combination of ${round.opponentMove} and ${round.selfMove}")
}
}
override fun outcome(): Int = when (round.selfMove) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> error("Invalid self move ${round.selfMove}")
}
}
fun String.toRound() = this.split(" ")
.let {
Round(it[0], it[1])
}
fun main() {
fun part2(lines: List<String>): Int = lines
.map(String::toRound)
.map(::Strategy2Score)
.sumOf(Strategy2Score::totalScore)
fun part1(lines: List<String>): Int = lines
.map(String::toRound)
.map(::Strategy1Score)
.sumOf(Strategy1Score::totalScore)
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val actualInput = readInput("Day02")
println(part1(actualInput))
println(part2(actualInput))
}
| 0 |
Kotlin
| 0 | 0 |
d5f85b6a48e3505d06b4ae1027e734e66b324964
| 1,975 |
aoc-2022
|
Apache License 2.0
|
app/src/main/kotlin/codes/jakob/aoc/solution/Day04.kt
|
loehnertz
| 725,944,961 | false |
{"Kotlin": 59236}
|
package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.splitByLines
object Day04 : Solution() {
private val numbersPattern = Regex("\\b\\d{1,2}\\b")
override fun solvePart1(input: String): Any {
return parseScratchCards(input)
.map { card ->
card.matchingNumbers.fold(0) { accumulator, _ ->
if (accumulator == 0) 1 else accumulator * 2
}
}
.sum()
}
override fun solvePart2(input: String): Any {
val cards: Map<Int, ScratchCard> = parseScratchCards(input).associateBy { it.index }
val cardsToEvaluate: ArrayDeque<ScratchCard> = ArrayDeque<ScratchCard>().also { deque ->
deque.addAll(cards.values)
}
tailrec fun evaluateCards(evaluatedCount: Int = 0): Int {
if (cardsToEvaluate.isEmpty()) return evaluatedCount
val card: ScratchCard = cardsToEvaluate.removeFirst()
val matchingNumbers: Set<Int> = card.matchingNumbers
val newCards: List<ScratchCard> = if (matchingNumbers.isNotEmpty()) {
((card.index + 1)..(card.index + matchingNumbers.count())).mapNotNull { newCardIndex ->
cards[newCardIndex]
}
} else emptyList()
cardsToEvaluate.addAll(newCards)
return evaluateCards(evaluatedCount + 1)
}
return evaluateCards()
}
private fun parseScratchCards(input: String): List<ScratchCard> {
return input.splitByLines()
.mapIndexed { index, line ->
val numbers = line.substringAfter(": ")
val (winningSequence, ownSequence) = numbers.split(" | ")
val winningNumbers = numbersPattern.findAll(winningSequence).map { it.value.toInt() }.toList()
val ownNumbers = numbersPattern.findAll(ownSequence).map { it.value.toInt() }.toList()
ScratchCard(index + 1, winningNumbers, ownNumbers)
}
}
data class ScratchCard(
val index: Int,
val winningNumbers: List<Int>,
val ownNumbers: List<Int>,
) {
val matchingNumbers: Set<Int> = this.winningNumbers.intersect(this.ownNumbers)
}
}
fun main() {
Day04.solve()
}
| 0 |
Kotlin
| 0 | 0 |
6f2bd7bdfc9719fda6432dd172bc53dce049730a
| 2,289 |
advent-of-code-2023
|
MIT License
|
src/jvmMain/kotlin/day04/initial/Day04.kt
|
liusbl
| 726,218,737 | false |
{"Kotlin": 109684}
|
package day04.initial
import java.io.File
fun main() {
// solvePart1() // Solution: 21138, time: 07:09
solvePart2() // Solution: 7185540, time: 08:21
}
fun solvePart2() {
// val input = File("src/jvmMain/kotlin/day04/input/input_part1_test.txt")
val input = File("src/jvmMain/kotlin/day04/input/input.txt")
val lines = input.readLines()
val matchList = lines.map { line ->
val (winningLine, yourLine) = line.split(":")[1].split("|").map { it.trim() }
val winning = winningLine.split(" ").filter { it.isNotBlank() }.map { it.toInt() }
val your = yourLine.split(" ").filter { it.isNotBlank() }.map { it.toInt() }
val number = line.split(":")[0].replace("Card", "").trim().toInt()
Match(
number = number,
copies = 1,
winning = winning,
your = your
)
}.toMutableList()
var index = 0
println("Round $index, \n${matchList.joinToString("\n")}\n")
while (index <= matchList.size - 1) {
val match = matchList[index]
val additions = matchList.subList(index + 1, index + 1 + match.yourWinning.size)
.map { it.copy(copies = match.copies) }
((index + 1)..(index + match.yourWinning.size)).forEachIndexed { loopIndex, additionIndex ->
val addition = additions[loopIndex]
matchList[additionIndex] = addition.copy(copies = addition.copies + matchList[additionIndex].copies)
}
println("Round $index, \n${matchList.joinToString("\n")}\n")
index++
}
println(matchList.sumOf { it.copies })
}
data class Match(
val number: Int,
val copies: Int,
val winning: List<Int>,
val your: List<Int>
) {
val yourWinning = your.filter { winning.contains(it) }
override fun toString(): String {
return "Match(number=$number, copies=$copies, winning=$winning, your=$your, yourWinning=$yourWinning)"
}
}
fun solvePart1() {
val input = File("src/jvmMain/kotlin/day04/input/input.txt")
// val input = File("src/jvmMain/kotlin/day04/input/input_part1_test.txt")
val lines = input.readLines()
val res = lines.map { line ->
val (winningLine, yourLine) = line.split(":")[1].split("|").map { it.trim() }
val winning = winningLine.split(" ").filter { it.isNotBlank() }.map { it.toInt() }
val your = yourLine.split(" ").filter { it.isNotBlank() }.map { it.toInt() }
your.filter { winning.contains(it) }
}.filter { it.isNotEmpty() }.sumOf { yourWinningNumbers ->
yourWinningNumbers.fold(1) { acc, next ->
acc * 2
} / 2
}
println(res)
val result = "result"
println(result)
}
| 0 |
Kotlin
| 0 | 0 |
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
| 2,698 |
advent-of-code
|
MIT License
|
src/main/kotlin/_2022/Day13.kt
|
novikmisha
| 572,840,526 | false |
{"Kotlin": 145780}
|
package _2022
import readGroupedInput
import kotlin.math.max
fun main() {
fun parseListFromString(str: String): List<Any> {
val trimmedStr = str.removePrefix("[")
.removeSuffix("]")
.trim()
val resultList = mutableListOf<Any>()
var elementStartPosition = 0
var arrayStartCounter = 0
for (i in trimmedStr.indices) {
if (trimmedStr[i] == '[') {
arrayStartCounter += 1
} else if (trimmedStr[i] == ']') {
arrayStartCounter -= 1
if (arrayStartCounter == 0) {
resultList.add(parseListFromString(trimmedStr.substring(elementStartPosition, i + 1)))
elementStartPosition = i + 2
}
} else if (trimmedStr[i] != ',') {
continue
} else {
if (arrayStartCounter == 0 && i > elementStartPosition) {
resultList.add(trimmedStr.substring(elementStartPosition, i).toInt())
elementStartPosition = i + 1
}
}
}
if (elementStartPosition < trimmedStr.length) {
resultList.add(trimmedStr.substring(elementStartPosition, trimmedStr.length).toInt())
}
return resultList
}
fun getValueAsList(second: Any?): List<*> {
val rightAsList: List<*> = if (second is List<*>) {
second
} else {
listOf(second)
}
return rightAsList
}
fun leftIsSmaller(left: List<*>, right: List<*>): Int {
val maxArraySize = max(left.size, right.size)
for (pair in left.take(maxArraySize).zip(right.take(maxArraySize))) {
val first = pair.first
val second = pair.second
val areNotInts = first !is Int || second !is Int
if (areNotInts) {
val leftAsList: List<*> = getValueAsList(first)
val rightAsList: List<*> = getValueAsList(second)
val leftIsSmaller = leftIsSmaller(leftAsList, rightAsList)
if (leftIsSmaller != 0) {
return leftIsSmaller
}
} else if ((first as Int) != (second as Int)) {
val compareIntResult = (first - second).coerceIn(-1..1)
if (compareIntResult != 0) {
return compareIntResult
}
}
}
return (left.size - right.size).coerceIn(-1..1)
}
fun part1(input: List<List<String>>): Int {
val result = mutableListOf<Int>()
input.forEachIndexed { pairIndex, pair ->
val (left, right) = pair.map { parseListFromString(it) }
val leftIsSmaller = leftIsSmaller(left, right)
if (leftIsSmaller == -1) {
result.add(pairIndex + 1)
}
}
return result.sum()
}
fun part2(input: List<List<String>>): Int {
val firstFlag = parseListFromString("[[2]]")
val secondFlag = parseListFromString("[[6]]")
val list = mutableListOf(firstFlag, secondFlag)
list.addAll(input.flatten().map { parseListFromString(it) })
val sortedList = list.sortedWith { first: List<*>, second: List<*> -> leftIsSmaller(first, second) }
return (sortedList.indexOf(firstFlag) + 1) * (sortedList.indexOf(secondFlag) + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readGroupedInput("Day13_test")
println(part1(testInput))
println(part2(testInput))
val input = readGroupedInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
0c78596d46f3a8bf977bf356019ea9940ee04c88
| 3,705 |
advent-of-code
|
Apache License 2.0
|
codeforces/vk2021/qual/e3_slow.kt
|
mikhail-dvorkin
| 93,438,157 | false |
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
|
package codeforces.vk2021.qual
import kotlin.math.log2
import kotlin.math.roundToInt
private fun permutation(comparisons: List<Boolean>, n: Int): Pair<Int, List<Int>> {
var pos = 0
fun permutation(m: Int): List<Int> {
if (m <= 1) return List(m) { 0 }
val left = m / 2
val right = m - left
val permutationLeft = permutation(left)
val permutationRight = permutation(right)
val leftNumbers = mutableListOf<Int>()
val rightNumbers = mutableListOf<Int>()
for (i in 0 until m) {
val half = if (leftNumbers.size < left && rightNumbers.size < right) {
if (comparisons.getOrElse(pos++) { false }) rightNumbers else leftNumbers
} else if (leftNumbers.size < left) leftNumbers else rightNumbers
half.add(i)
}
return permutationLeft.map { leftNumbers[it] } + permutationRight.map { rightNumbers[it] }
}
val permutation = permutation(n)
return pos - comparisons.size to permutation
}
private fun solve(comparisons: List<Boolean>): List<Int> {
if (comparisons.size < 1000) {
for (n in 1..comparisons.size + 2) {
val (error, permutation) = permutation(comparisons, n)
if (error == 0) return permutation
}
error("")
}
var low = comparisons.size / (log2(comparisons.size.toDouble()).roundToInt() + 1)
var high = (low + 8) * 3
val tried = BooleanArray(high)
while (low + 1 < high) {
val n = (low + high) / 2
val (error, permutation) = permutation(comparisons, n)
if (error == 0) return permutation
tried[n] = true
if (error < 0) low = n else high = n
}
error("")
}
fun main() {
val comparisons = readLn().map { it == '1' }
val permutation = solve(comparisons)
println(permutation.size)
println(permutation.joinToString(" ") { (it + 1).toString() })
}
private fun readLn() = readLine()!!
| 0 |
Java
| 1 | 9 |
30953122834fcaee817fe21fb108a374946f8c7c
| 1,746 |
competitions
|
The Unlicense
|
src/Day03.kt
|
cypressious
| 572,916,585 | false |
{"Kotlin": 40281}
|
fun main() {
fun bitSums(input: List<String>): IntArray {
val sums = IntArray(input[0].length)
for (s in input) {
for ((index, c) in s.withIndex()) {
if (c == '1') {
sums[index]++
}
}
}
return sums
}
fun part1(input: List<String>): Int {
val sums = bitSums(input)
var gamma = 0
var epsilon = 0
val bitCount = input[0].length
val count = input.size
for (index in sums.indices) {
if (sums[index] > count / 2) {
gamma = gamma or (1 shl bitCount - index - 1)
} else {
epsilon = epsilon or (1 shl bitCount - index - 1)
}
}
return gamma * epsilon
}
fun determine(input: List<String>, keepMostCommon: Boolean): Int {
val bit1 = if (keepMostCommon) '1' else '0'
val bit2 = if (!keepMostCommon) '1' else '0'
val candidates = input.toMutableList()
for (index in input[0].indices) {
if (candidates.size == 1) {
break
}
val sums = bitSums(candidates)
val keepBit = when {
sums[index] * 2 == candidates.size -> bit1
sums[index] > candidates.size / 2 -> bit1
else -> bit2
}
candidates.removeIf { it[index] != keepBit }
}
return Integer.parseInt(candidates.single(), 2)
}
fun part2(input: List<String>): Int {
return determine(input, true) * determine(input, false)
}
// 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))
}
| 0 |
Kotlin
| 0 | 0 |
169fb9307a34b56c39578e3ee2cca038802bc046
| 1,908 |
AdventOfCode2021
|
Apache License 2.0
|
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day14/Day14.kt
|
janvdbergh
| 318,992,922 | false |
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
|
package eu.janvdb.aoc2021.day14
import eu.janvdb.aocutil.kotlin.readGroupedLines
const val FILENAME = "input14.txt"
const val NUMBER_OF_STEPS = 40
fun main() {
val lines = readGroupedLines(2021, FILENAME)
val template = PolymerizationTemplate.parse(lines[0][0])
template.printValues()
val rules = lines[1].map(InsertionRule::parse)
var updatedTemplate = template
for (i in 0 until NUMBER_OF_STEPS) {
updatedTemplate = updatedTemplate.applyRules(rules)
updatedTemplate.printValues()
}
}
data class ElementCombination(val element1: Char, val element2: Char)
data class PolymerizationTemplate(val combinations: Map<ElementCombination, Long>) {
fun applyRules(rules: List<InsertionRule>): PolymerizationTemplate {
val newCombinations = mutableMapOf<ElementCombination, Long>()
combinations.forEach { pair ->
val rule = rules.find { it.startCombination == pair.key }
rule?.resultCombinations?.forEach { resultingPair ->
val currentValue = newCombinations.getOrDefault(resultingPair, 0L)
newCombinations[resultingPair] = currentValue + pair.value
}
}
return PolymerizationTemplate(newCombinations)
}
fun printValues() {
val elementsPerType = combinations.asSequence()
.flatMap { sequenceOf(Pair(it.key.element1, it.value), Pair(it.key.element2, it.value)) }
.groupingBy { it.first }
.aggregate { _, acc: Long?, element, _ -> (acc ?: 0L) + element.second }
.map { entry -> Pair(entry.key, (entry.value + 1) / 2) }
// This is a bit of a heck. Most characters occur double, except first and last.
// By adding one to them and using integer division, the correct number gets out.
val min = elementsPerType.minByOrNull { it.second }!!
val max = elementsPerType.maxByOrNull { it.second }!!
println("Length:${combinations.size - 1} Min:${min} Max:${max} Difference: ${max.second - min.second}")
}
companion object {
fun parse(line: String): PolymerizationTemplate {
val pairs = mutableMapOf<ElementCombination, Long>()
for (i in 0 until line.length - 1) {
val pair = ElementCombination(line[i], line[i + 1])
val currentValue = pairs.getOrDefault(pair, 0L)
pairs[pair] = currentValue + 1L
}
return PolymerizationTemplate(pairs)
}
}
}
data class InsertionRule(val startCombination: ElementCombination, val resultCombinations: List<ElementCombination>) {
companion object {
fun parse(line: String): InsertionRule {
val parts = line.split("->").map(String::trim)
val startCombination = ElementCombination(parts[0][0], parts[0][1])
val resultCombination1 = ElementCombination(parts[0][0], parts[1][0])
val resultCombination2 = ElementCombination(parts[1][0], parts[0][1])
return InsertionRule(startCombination, listOf(resultCombination1, resultCombination2))
}
}
}
| 0 |
Java
| 0 | 0 |
78ce266dbc41d1821342edca484768167f261752
| 2,774 |
advent-of-code
|
Apache License 2.0
|
src/Day08.kt
|
hoppjan
| 433,705,171 | false |
{"Kotlin": 29015, "Shell": 338}
|
fun main() {
fun part1(input: List<SevenSegmentDisplayPuzzle>) =
input.sumOf { puzzle ->
puzzle.output.filter { display ->
display.isOne() || display.isFour() || display.isSeven() || display.isEight()
}.size
}
fun part2(input: List<SevenSegmentDisplayPuzzle>) =
input.sumOf { puzzle ->
puzzle.output.map {
val mapping = puzzle.correctMapping()
digits.indexOf(
it.rewireWith(mapping)
)
}.joinToString(separator = "").toInt()
}
// test if implementation meets criteria from the description
val testInput = SevenSegmentInputReader.read("Day08_test")
// testing part 1
val testSolution1 = 26
val testOutput1 = part1(testInput)
printTestResult(1, testOutput1, testSolution1)
check(testOutput1 == testSolution1)
// testing part 2
val testSolution2 = 61229
val testOutput2 = part2(testInput)
printTestResult(2, testOutput2, testSolution2)
check(testOutput2 == testSolution2)
// the actual
val input = SevenSegmentInputReader.read("Day08")
printResult(1, part1(input).also { check(it == 237) })
printResult(2, part2(input).also { check(it == 1_009_098) })
}
fun String.isOne() = length == 2
fun String.isFour() = length == 4
fun String.isSeven() = length == 3
fun String.isEight() = length == 7
data class SevenSegmentDisplayPuzzle(val hints: List<String>, val output: List<String>) {
val allDisplays = hints + output
}
// the segments turned on in each number/index
val digits = listOf("123567", "36", "13457", "13467", "2346", "12467", "124567", "136", "1234567", "123467")
const val SEGMENTS = "abcdefg"
// what am i doing?
fun String.rewireWith(mapping: String) =
map { mapping.indexOf(it) + 1 }
.sorted()
.joinToString(separator = "")
// this is madness!
fun String.allPossibleMappings(result: String = ""): List<String> =
if (isEmpty())
listOf(result)
else
flatMapIndexed { index, char ->
removeRange(index, index + 1)
.allPossibleMappings(result + char)
}
// Hello world, we are brute forcing again!
fun SevenSegmentDisplayPuzzle.correctMapping(): String {
var possibleMappings = SEGMENTS.allPossibleMappings()
allDisplays.forEach { display ->
possibleMappings = possibleMappings.filter { mapping ->
display.rewireWith(mapping) in digits
}
}
return possibleMappings.last() // last remaining mapping
}
| 0 |
Kotlin
| 0 | 0 |
04f10e8add373884083af2a6de91e9776f9f17b8
| 2,582 |
advent-of-code-2021
|
Apache License 2.0
|
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day03/Day03.kt
|
janvdbergh
| 318,992,922 | false |
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
|
package eu.janvdb.aoc2022.day03
import eu.janvdb.aocutil.kotlin.assertTrue
import eu.janvdb.aocutil.kotlin.readLines
//const val FILENAME = "input03-test.txt"
const val FILENAME = "input03.txt"
fun main() {
val priorityLists = readLines(2022, FILENAME)
.map(::toPriorities)
.toList()
part1(priorityLists)
part2(priorityLists)
}
fun part1(priorityLists: List<List<Int>>) {
val priorities = priorityLists
.map(::split)
.map { it.first.intersect(it.second).sum() }
.sum()
println(priorities)
}
fun part2(priorityLists: List<List<Int>>) {
val groups = priorityLists
.mapIndexed { index, list -> Pair(index, list) }
.groupBy { it.first / 3 }
.map { it.value }
.map { it.map { it.second.toSet() } }
assertTrue(groups.size * 3 == priorityLists.size)
val unique = groups.map { it.reduce(Set<Int>::intersect) }
println(unique)
println(unique.sumOf { it.sum() })
}
fun <T> split(list: List<T>): Pair<List<T>, List<T>> {
val mid = list.size / 2
assertTrue(mid * 2 == list.size)
val result = Pair(list.subList(0, mid), list.subList(mid, list.size))
assertTrue(result.first.size == mid)
assertTrue(result.second.size == mid)
return result
}
fun toPriorities(part: String): List<Int> {
return part.toCharArray().asSequence()
.map(::mapToPriority)
.toList()
}
fun mapToPriority(ch: Char): Int {
if (ch in 'a'..'z') return ch - 'a' + 1
return ch - 'A' + 27
}
| 0 |
Java
| 0 | 0 |
78ce266dbc41d1821342edca484768167f261752
| 1,396 |
advent-of-code
|
Apache License 2.0
|
src/Day08.kt
|
nordberg
| 573,769,081 | false |
{"Kotlin": 47470}
|
fun main() {
data class Tree(val x: Int, val y: Int)
fun findVisibleTreesInRow(treeRow: List<Int>): Set<Int> {
val visibleTrees = mutableSetOf(0, treeRow.indices.max())
var highestSoFar = Int.MIN_VALUE
treeRow.forEachIndexed { index, height ->
if (height > highestSoFar) {
visibleTrees.add(index)
highestSoFar = height
}
}
highestSoFar = Int.MIN_VALUE
val maxIdx = treeRow.indices.max()
for (index in maxIdx downTo 0) {
val height = treeRow[index]
if (height > highestSoFar) {
visibleTrees.add(index)
highestSoFar = height
}
}
return visibleTrees
}
fun part1(input: List<String>): Int {
val visibleTrees = mutableSetOf<Tree>()
val gridOfTrees = mutableListOf<MutableList<Int>>()
input.forEach { gridOfTrees.add(it.map { t -> t.code }.toMutableList()) }
val maxIndex = input.indices.max()
for (y in 0 until gridOfTrees.size) {
visibleTrees.addAll(findVisibleTreesInRow(gridOfTrees[y]).map { x -> Tree(x, y) })
}
for (x in 0 until gridOfTrees.size) {
val col = gridOfTrees.map { it[x] }
val visibleColIndices = findVisibleTreesInRow(col)
val zipRowWithCol = (0..maxIndex).zip(visibleColIndices)
visibleTrees.addAll(zipRowWithCol.map { (_, y) -> Tree(x, y) })
}
return visibleTrees.size
}
fun findScenicScore(forest: List<List<Int>>, tree: Tree): Int {
val treeHeight = forest[tree.y][tree.x]
val visionDist = mutableListOf<Int>()
for (up in tree.y - 1 downTo 0) {
if (forest[up][tree.x] >= treeHeight || up == 0) {
visionDist.add(tree.y - up)
break
}
}
val forestSize = forest.indices.max()
for (down in tree.y + 1 .. forestSize) {
if (forest[down][tree.x] >= treeHeight || down == forestSize) {
visionDist.add(down - tree.y)
break
}
}
for (left in tree.x - 1 downTo 0) {
if (forest[tree.y][left] >= treeHeight || left == 0) {
visionDist.add(tree.x - left)
break
}
}
for (right in tree.x + 1 .. forestSize) {
if (forest[tree.y][right] >= treeHeight || right == forestSize) {
visionDist.add(right - tree.x)
break
}
}
return visionDist.reduce { acc, r -> acc * r }
}
fun part2(input: List<String>): Int {
val gridOfTrees = mutableListOf<MutableList<Int>>()
input.forEach { gridOfTrees.add(it.map { t -> t.code }.toMutableList()) }
val maxIdx = gridOfTrees.indices.max()
var maxScenicScore = Int.MIN_VALUE
for (y in 1 until maxIdx) {
for (x in 1 until maxIdx) {
val scenicScore = findScenicScore(gridOfTrees, Tree(x, y))
maxScenicScore = maxScenicScore.coerceAtLeast(scenicScore)
}
}
return maxScenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part2(testInput) == 8)
val input = readInput("Day08")
//println(part1(input))
println(part2(input))
fun printForest(maxIndex: Int, visibleTrees: MutableSet<Tree>) {
(0..maxIndex).forEach { y ->
(0..maxIndex).forEach { x ->
if (visibleTrees.contains(Tree(x, y))) {
print("X")
} else {
print("O")
}
}
println()
}
}
}
| 0 |
Kotlin
| 0 | 0 |
3de1e2b0d54dcf34a35279ba47d848319e99ab6b
| 3,822 |
aoc-2022
|
Apache License 2.0
|
src/Day05.kt
|
tomoki1207
| 572,815,543 | false |
{"Kotlin": 28654}
|
data class Operation(val move: Int, val from: Int, val to: Int)
fun main() {
fun buildStacks(input: List<String>, stackCount: Int): List<ArrayDeque<Char>> {
return input.map { line ->
(1..stackCount).map { stackNo ->
line.getOrElse(1 + (stackNo - 1) * 4) { ' ' }
}
}.let { list ->
val stacks = (0 until stackCount).map { ArrayDeque<Char>() }
// transpose
list.reversed().forEach { crates ->
for (i in (0 until stackCount)) {
val crate = crates[i]
if (!crate.isWhitespace()) {
stacks[i].add(crate)
}
}
}
stacks
}
}
fun buildOperations(input: List<String>): List<Operation> {
val operation = "^move (\\d+) from (\\d+) to (\\d+)$".toRegex()
return input.map {
val groups = operation.find(it)!!.groupValues
Operation(groups[1].toInt(), groups[2].toInt(), groups[3].toInt())
}
}
fun part1(input: List<String>, stackHeight: Int, stackCount: Int): String {
val stacks = buildStacks(input.take(stackHeight), stackCount)
val operations = buildOperations(input.drop(stackHeight + 2))
operations.forEach { operation ->
val from = stacks[operation.from - 1]
val to = stacks[operation.to - 1]
repeat(operation.move) {
from.removeLast().let { to.add(it) }
}
}
return stacks.map { it.last() }.joinToString("")
}
fun part2(input: List<String>, stackHeight: Int, stackCount: Int): String {
val stacks = buildStacks(input.take(stackHeight), stackCount)
val operations = buildOperations(input.drop(stackHeight + 2))
operations.forEach { operation ->
val from = stacks[operation.from - 1]
val to = stacks[operation.to - 1]
(0 until operation.move)
.map { from.removeLast() }
.reversed()
.let { to.addAll(it) }
}
return stacks.map { it.last() }.joinToString("")
}
val testInput = readInput("Day05_test")
check(part1(testInput, 3, 3) == "CMZ")
check(part2(testInput, 3, 3) == "MCD")
val input = readInput("Day05")
println(part1(input, 8, 9))
println(part2(input, 8, 9))
}
| 0 |
Kotlin
| 0 | 0 |
2ecd45f48d9d2504874f7ff40d7c21975bc074ec
| 2,434 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/Day15.kt
|
dakr0013
| 572,861,855 | false |
{"Kotlin": 105418}
|
import java.awt.Point
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>, testRow: Int = 2_000_000): Int {
val sensors = parseSensors(input)
val beaconCountInTestRow = sensors.map { it.closestBeacon }.toSet().count { it.y == testRow }
return merge(sensors.mapNotNull { it.getCoverageForRow(testRow) }).sumOf { it.size() } -
beaconCountInTestRow
}
fun part2(input: List<String>, maxSearchSpace: Int = 4_000_000): Long {
val sensors = parseSensors(input)
for (y in 0..maxSearchSpace) {
val rowCoverages =
merge(sensors.mapNotNull { it.getCoverageForRow(y) }).filter {
it.first <= maxSearchSpace
}
when (rowCoverages.size) {
1 -> {
val coverageRange = rowCoverages.first()
val isLowerBoundNotCovered = !coverageRange.contains(0)
if (isLowerBoundNotCovered) {
return tuningFrequency(0, y)
}
val isUpperBoundNotCovered = !coverageRange.contains(maxSearchSpace)
if (isUpperBoundNotCovered) {
return tuningFrequency(maxSearchSpace, y)
}
}
2 -> {
val firstCoverageRange = rowCoverages.minBy { it.first }
val xOfDistressBeacon = firstCoverageRange.last + 1
return tuningFrequency(xOfDistressBeacon, y)
}
else -> error("contains multiple possible positions for distress beacon, should not happen")
}
}
error("no distress beacon found, should not happen")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
assertEquals(26, part1(testInput, 10))
assertEquals(56000011, part2(testInput, 20))
val input = readInput("Day15")
println(part1(input))
println(part2(input))
}
private fun parseSensors(input: List<String>): List<Sensor> {
val inputPattern =
Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
return input
.map { line -> inputPattern.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() } }
.map { Sensor(Point(it[0], it[1]), Point(it[2], it[3])) }
}
private data class Sensor(val position: Point, val closestBeacon: Point) {
val distanceToClosestBeacon = manhattenDistance(position, closestBeacon)
fun getCoverageForRow(y: Int): XRange? {
val xDiffMax = distanceToClosestBeacon - (position.y - y).absoluteValue
return if (xDiffMax >= 0) {
(position.x - xDiffMax)..(position.x + xDiffMax)
} else {
null
}
}
}
private fun merge(ranges: List<IntRange>): List<IntRange> {
val rangesToMerge = ranges.toMutableList()
val result = mutableListOf<IntRange>()
var currentRange = rangesToMerge.removeFirst()
while (rangesToMerge.isNotEmpty()) {
val nextRange = rangesToMerge.firstOrNull { it.canMerge(currentRange) }
if (nextRange == null) {
result.add(currentRange)
currentRange = rangesToMerge.removeFirst()
} else {
rangesToMerge.remove(nextRange)
currentRange = currentRange.merge(nextRange)
}
}
return result.apply { add(currentRange) }
}
private fun IntRange.canMerge(other: IntRange): Boolean =
contains(other.first) ||
contains(other.last) ||
other.contains(first) ||
other.contains(last) ||
last + 1 == other.first ||
other.last + 1 == first
private fun IntRange.merge(other: IntRange) = min(first, other.first)..max(last, other.last)
private fun IntRange.size() = (last - first) + 1
private fun tuningFrequency(x: Int, y: Int): Long = x * 4_000_000L + y
private fun manhattenDistance(p1: Point, p2: Point): Int =
(p1.x - p2.x).absoluteValue + (p1.y - p2.y).absoluteValue
typealias XRange = IntRange
| 0 |
Kotlin
| 0 | 0 |
6b3adb09f10f10baae36284ac19c29896d9993d9
| 3,845 |
aoc2022
|
Apache License 2.0
|
src/day12/Day12.kt
|
molundb
| 573,623,136 | false |
{"Kotlin": 26868}
|
package day12
import readInput
// Copied from online https://github.com/zanmagerl/advent-of-code/blob/master/2022/src/twentytwo/days/Day12.kt
fun main() {
val input = readInput(parent = "src/day12", name = "Day12_input").map {
it.toCharArray().toList()
}
println(partOne(input))
println(partTwo(input))
}
data class Hill(val x: Int, val y: Int, val pathLength: Int = 0) {
override fun equals(other: Any?): Boolean {
if (other is Hill) return this.x == other.x && this.y == other.y
return super.equals(other)
}
}
private fun findHill(map: List<List<Char>>, searched: Char): Hill {
map.mapIndexed { row, chars -> chars.mapIndexed { column, char -> if (char == searched) return Hill(column, row) } }
throw IllegalArgumentException("There is no such hill in the map")
}
private fun isInMap(hill: Hill, map: List<List<Char>>): Boolean {
return hill.y in map.indices && hill.x in map[0].indices
}
private fun measureHeight(hill: Hill, map: List<List<Char>>): Int {
return when (val elevation = map[hill.y][hill.x]) {
'S' -> 'a'.code
'E' -> 'z'.code
else -> elevation.code
} - 'a'.code
}
private fun breadthFirstSearch(
startHill: Hill,
isAtDestination: (Hill) -> Boolean,
isValidRoute: (Hill, Hill) -> Boolean,
): Int {
val hills = ArrayDeque<Hill>()
val visited = mutableSetOf<Hill>()
hills.add(startHill)
while (hills.isNotEmpty()) {
val hill = hills.removeFirst()
if (visited.contains(hill)) continue
if (isAtDestination(hill)) {
return hill.pathLength
}
listOf(0 to 1, -1 to 0, 0 to -1, 1 to 0)
.map { Hill(hill.x + it.first, hill.y + it.second, hill.pathLength + 1) }
.filter { isValidRoute(hill, it) }
.map { hills.add(it) }
visited.add(hill)
}
return -1
}
private fun partOne(map: List<List<Char>>): Int {
val startPoint = findHill(map, 'S')
val endPoint = findHill(map, 'E')
return breadthFirstSearch(
startPoint,
isAtDestination = { hill -> hill == endPoint },
isValidRoute = { previousHill, currentHill ->
isInMap(currentHill, map) && (measureHeight(
currentHill,
map
) - measureHeight(previousHill, map) <= 1)
}
)
}
/**
* Same as part 1, but we start at the end and search for the hill with elevation equal to 0
*/
private fun partTwo(map: List<List<Char>>): Int {
val startPoint = findHill(map, 'E')
return breadthFirstSearch(
startPoint,
isAtDestination = { hill -> measureHeight(hill, map) == 0 },
isValidRoute = { previousHill, currentHill ->
isInMap(currentHill, map) && (measureHeight(
previousHill,
map
) - measureHeight(currentHill, map) <= 1)
}
)
}
| 0 |
Kotlin
| 0 | 0 |
a4b279bf4190f028fe6bea395caadfbd571288d5
| 2,936 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/com/briarshore/aoc2022/day13/DistressSignalPuzzle.kt
|
steveswing
| 579,243,154 | false |
{"Kotlin": 47151}
|
package com.briarshore.aoc2022.day13
import kotlinx.serialization.json.*
import println
import kotlin.math.max
import readInput
fun <L, R> List<L>.zipWithPadding(that: List<R>): List<Pair<L?, R?>> =
buildList { for (i in 0 until max([email protected], that.size)) add([email protected](i) to that.getOrNull(i)) }
fun JsonArray.zipWithPadding(that: JsonArray) = this.toList().zipWithPadding(that.toList())
fun isInCorrectOrder(left: JsonArray, right: JsonArray) = left < right
operator fun JsonArray.compareTo(that: JsonArray): Int {
val stack = ArrayDeque<Pair<JsonElement?, JsonElement?>>().apply { [email protected](that).reversed().forEach(::addFirst) }
while (stack.isNotEmpty()) {
val (left, right) = stack.removeFirst()
when {
left == null && right != null -> return -1
left != null && right == null -> return 1
left is JsonPrimitive && right is JsonPrimitive -> when {
left.int < right.int -> return -1
left.int == right.int -> continue
left.int > right.int -> return 1
}
left is JsonArray && right is JsonArray -> left.zipWithPadding(right).reversed().forEach(stack::addFirst)
left is JsonPrimitive && right is JsonArray -> stack.addFirst(JsonArray(listOf(left)) to right)
left is JsonArray && right is JsonPrimitive -> stack.addFirst(left to JsonArray(listOf(right)))
else -> error("Invalid comparison")
}
}
error("Comparison failed")
}
fun dividerPacket(number: Int): JsonArray = JsonArray(listOf(JsonArray(listOf(JsonPrimitive(number)))))
fun main() {
fun parse(lines: List<String>) = lines.filter { it.isNotEmpty() }.map { Json.parseToJsonElement(it).jsonArray }
fun part1(lines: List<String>): Int = lines
.asSequence()
.chunked(3)
.map { parse(it) }
.map { isInCorrectOrder(it[0], it[1]) }
.mapIndexed { index, result -> (index + 1).takeIf { result } ?: 0 }
.sumOf { it }
fun part2(lines: List<String>): Int {
val divider2 = dividerPacket(2)
val divider6 = dividerPacket(6)
return buildList { addAll(parse(lines)); add(divider2); add(divider6) }
.sortedWith(JsonArray::compareTo)
.mapIndexed { index, it -> if (it == divider2 || it == divider6) index + 1 else 1 }
.fold(1) { acc, it -> acc * it }
}
val sampleInput = readInput("d13-sample")
val part1Sample = part1(sampleInput)
"part1Sample $part1Sample".println()
check(part1Sample == 13)
val part2Sample = part2(sampleInput)
"part2Sample $part2Sample".println()
check(part2Sample == 140)
val input = readInput("d13-input")
val part1 = part1(input)
"part1 $part1".println()
check(part1 == 5905)
val part2 = part2(input)
"part2 $part2".println()
check(part2 == 21691)
}
| 0 |
Kotlin
| 0 | 0 |
a0d19d38dae3e0a24bb163f5f98a6a31caae6c05
| 3,030 |
2022-AoC-Kotlin
|
Apache License 2.0
|
src/day8/day8.kt
|
bienenjakob
| 573,125,960 | false |
{"Kotlin": 53763}
|
package day8
import inputTextOfDay
import testTextOfDay
val heights = mutableListOf<MutableList<Int>>()
val visibility = mutableListOf<MutableList<Boolean>>()
val scenicScore = mutableListOf<MutableList<Int>>()
fun parseInput(text: String) {
heights.clear()
visibility.clear()
scenicScore.clear()
text.lines()
.forEach { line ->
heights.add(line.map { it.digitToInt() }.toMutableList())
visibility.add(line.map { false }.toMutableList())
scenicScore.add(line.map { -1 }.toMutableList())
}
}
fun part1(text: String): Int {
parseInput(text)
visibility.forEachIndexed { r, row ->
row.indices.forEach{ c ->
visibility[r][c] = isVisible(r, c, heights)
}
}
return visibility.flatten().count { it }
}
fun isVisible(row: Int, col: Int, heights: List<List<Int>>): Boolean {
val max = heights.size - 1
// edge is always visible
if (row == 0 || col == 0 || row == max || col == max) return true
// trees to the
val left = heights[row].take(col)
val right = heights[row].drop(col + 1)
val top = heights.map { line -> line[col] }.take(row)
val bottom = heights.map { line -> line[col] }.drop(row + 1)
// visible if all trees in at least one direction are smaller
return listOf(right, left, top, bottom).any { it.max() < heights[row][col] }
}
fun part2(text: String): Int {
parseInput(text)
scenicScore.forEachIndexed { r, row ->
row.forEachIndexed { c, _ ->
scenicScore[r][c] = getScore(r, c, heights)
}
}
return scenicScore.flatten().max()
}
fun getScore(row: Int, col: Int, heights: List<List<Int>>): Int {
val max = heights.size - 1
if (row == 0 || col == 0 || row == max || col == max) return 0
// trees to the
val left = heights[row].take(col).reversed()
val right = heights[row].drop(col + 1)
val top = heights.map { line -> line[col] }.take(row)
val bottom = heights.map { line -> line[col] }.drop(row + 1)
var l = left.indexOfFirst { it >= heights[row][col] } + 1
var r = right.indexOfFirst { it >= heights[row][col] } + 1
var u = top.take(row).reversed().indexOfFirst { it >= heights[row][col] } + 1
var d = bottom.drop(row + 1).indexOfFirst { it >= heights[row][col] } + 1
if (l == 0) l = left.size
if (r == 0) r = right.size
if (u == 0) u = top.size
if (d == 0) d = bottom.size
return l * r * u * d
}
fun main() {
val day = 8
val testInput = testTextOfDay(day)
println("Test1: " + part1(testInput))
println("Test2: " + part2(testInput))
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = inputTextOfDay(day)
println("Part1: " + part1(input))
println("Part2: " + part2(input))
check(part1(input) == 1543)
check(part2(input) == 595080)
}
| 0 |
Kotlin
| 0 | 0 |
6ff34edab6f7b4b0630fb2760120725bed725daa
| 2,883 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/main/kotlin/day09.kt
|
tobiasae
| 434,034,540 | false |
{"Kotlin": 72901}
|
class Day09 : Solvable("09") {
override fun solveA(input: List<String>): String {
val grid = getGrid(input)
val lowPoints = getLowPoints(grid).map { grid[it.first][it.second] }
return (lowPoints.size + lowPoints.sum()).toString()
}
override fun solveB(input: List<String>): String {
val grid = getGrid(input)
return getLowPoints(grid)
.map { expandBasin(grid, it).size }
.sortedDescending()
.take(3)
.reduce { l, r -> l * r }
.toString()
}
private fun getGrid(input: List<String>): List<List<Int>> {
return input.map { it.split("").let { it.subList(1, it.size - 1) }.map(String::toInt) }
}
private fun getLowPoints(grid: List<List<Int>>): List<Pair<Int, Int>> {
val lowPoints = mutableListOf<Pair<Int, Int>>()
grid.forEachIndexed { row, r ->
r.forEachIndexed { col, c ->
val left = if (col > 0) r[col - 1] else 10
val right = if (col + 1 < r.size) r[col + 1] else 10
val upper = if (row > 0) grid[row - 1][col] else 10
val lower = if (row + 1 < grid.size) grid[row + 1][col] else 10
if (c < left && c < right && c < upper && c < lower) lowPoints.add(Pair(row, col))
}
}
return lowPoints
}
private fun expandBasin(grid: List<List<Int>>, point: Pair<Int, Int>): Set<Pair<Int, Int>> {
val basin = mutableSetOf<Pair<Int, Int>>(point)
listOf(
Pair(point.first - 1, point.second),
Pair(point.first + 1, point.second),
Pair(point.first, point.second - 1),
Pair(point.first, point.second + 1)
)
.forEach {
if (!basin.contains(it) && flowsTo(grid, it, point)) {
basin.addAll(expandBasin(grid, it))
}
}
return basin
}
private fun flowsTo(grid: List<List<Int>>, from: Pair<Int, Int>, to: Pair<Int, Int>): Boolean {
val fromY = from.first
val fromX = from.second
if (fromY < 0 || fromY >= grid.size || fromX < 0 || fromX >= grid.first().size) return false
if (grid[fromY][fromX] == 9) return false
return grid[fromY][fromX] > grid[to.first][to.second]
}
}
| 0 |
Kotlin
| 0 | 0 |
16233aa7c4820db072f35e7b08213d0bd3a5be69
| 2,403 |
AdventOfCode
|
Creative Commons Zero v1.0 Universal
|
src/day07/Day07.kt
|
taer
| 573,051,280 | false |
{"Kotlin": 26121}
|
package day07
import readInput
sealed class FS(){
class Directory(val name: String, val parent: Directory?, val children: MutableList<FS> = mutableListOf()): FS(){
override fun toString(): String {
return "dir: $name"
}
}
class File(val name: String, val size: Int): FS(){
override fun toString(): String {
return "file: $name"
}
}
}
fun FS.Directory.files(): List<FS.File>{
return this.children.flatMap{
when (it){
is FS.Directory -> it.files()
is FS.File -> listOf(it)
}
}
}
fun FS.Directory.dirs(): List<FS.Directory> {
return children.flatMap {
when (it) {
is FS.Directory -> it.dirs() + it
is FS.File -> listOf()
}
}
}
fun main() {
val part1Limit = 100000
fun parseMessy(input: List<String>): FS.Directory {
val root = FS.Directory("/", null, mutableListOf())
var curr = root
input.drop(1).forEach {
when (it.first()) {
'$' -> {
if (it == "$ ls") {
//cheaty noop
} else if (it == "$ cd ..") {
curr = curr.parent!!
} else {
val target = it.replace("$ cd ", "")
curr = curr.children.filterIsInstance<FS.Directory>().find { it.name == target }!!
}
}
else -> {
if (it.startsWith("dir")) {
curr.children.add(FS.Directory(it.replace("dir ", ""), parent = curr))
} else {
val split = it.split(" ")
val size = split[0].toInt()
val name = split[1]
curr.children.add(FS.File(name, size))
}
}
}
}
return root
}
fun part1(input: List<String>): Int {
val root = parseMessy(input)
val xx = root.dirs()
.map {
it.files().sumOf { it.size }
}.filter { it < part1Limit }
.sum()
return xx
}
val totalSize = 70000000
val neededFreeSpace = 30000000
fun part2(input: List<String>): Int {
val root = parseMessy(input)
val usedSapce = root.files().sumOf { it.size }
val currentFreeSapace = totalSize-usedSapce
val needToFree = neededFreeSpace - currentFreeSapace
val xx = root.dirs()
.map {
it.files().sumOf { it.size }
}
return xx.first { it > needToFree }
}
val testInput = readInput("day07", true)
val input = readInput("day07")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
println(part1(input))
println(part2(input))
check(part1(input) == 1306611)
check(part2(input) == 13210366)
}
| 0 |
Kotlin
| 0 | 0 |
1bd19df8949d4a56b881af28af21a2b35d800b22
| 2,990 |
aoc2022
|
Apache License 2.0
|
gcj/y2020/round1a/c.kt
|
mikhail-dvorkin
| 93,438,157 | false |
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
|
package gcj.y2020.round1a
private fun solve(): Long {
val (hei, wid) = readInts()
val a = List(hei) { readInts().toMutableList() }
val nei = List(DX.size) { d -> List(hei) { x -> MutableList(wid) { y ->
val xx = x + DX[d]; val yy = y + DY[d]
a.getOrNull(xx)?.getOrNull(yy)?.let { xx to yy }
} } }
var ans = 0L
var sum = a.flatten().fold(0L, Long::plus)
var toCheck = (0 until hei).flatMap { x -> (0 until wid).map { y -> x to y } }
while (true) {
ans += sum
val eliminated = toCheck.filter { (x, y) ->
val neighbors = nei.mapNotNull { it[x][y] }.map { (xx, yy) -> a[xx][yy] }
a[x][y] * neighbors.size < neighbors.sum()
}.takeIf { it.isNotEmpty() } ?: return ans
toCheck = eliminated.flatMap { (x, y) ->
sum -= a[x][y]
a[x][y] = 0
DX.indices.mapNotNull { d ->
val (xx, yy) = nei[d xor 2][x][y] ?: return@mapNotNull null
nei[d][xx][yy] = nei[d][x][y]
xx to yy
}
}.toSet().minus(eliminated).toList()
}
}
private val DX = intArrayOf(1, 0, -1, 0)
private val DY = intArrayOf(0, 1, 0, -1)
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 |
Java
| 1 | 9 |
30953122834fcaee817fe21fb108a374946f8c7c
| 1,297 |
competitions
|
The Unlicense
|
src/Day08.kt
|
illarionov
| 572,508,428 | false |
{"Kotlin": 108577}
|
fun main() {
fun part1(input: List<List<Int>>): Int {
return input.indices.sumOf { y ->
input[y].indices.count { x ->
input.isVisible(x, y)
}
}
}
fun part2(input: List<List<Int>>): Int {
return input.indices.maxOf { y ->
input[y].indices.maxOf { x ->
input.scenicScore(x, y)
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
.parseDigits()
val part1TestResult = part1(testInput)
println(part1TestResult)
check(part1TestResult == 21)
val input = readInput("Day08")
.parseDigits()
val part1Result = part1(input)
println(part1Result)
//check(part1Result == 1672)
val part2Result = part2(input)
println(part2Result)
//check(part2Result == 327180)
}
fun List<List<Int>>.isVisible(x: Int, y: Int): Boolean {
val checkedValue = this[y][x]
val maxX = this[0].lastIndex
val maxY = this.lastIndex
return (0 until x).all { l -> this[y][l] < checkedValue }
|| (0 until y).all { t -> this[t][x] < checkedValue }
|| (x + 1..maxX).all { r -> this[y][r] < checkedValue }
|| (y + 1..maxY).all { b -> this[b][x] < checkedValue }
}
fun List<List<Int>>.scenicScore(x: Int, y: Int): Int {
val checkedValue = this[y][x]
val maxX = this[0].lastIndex
val maxY = this.lastIndex
val visibleLeft = (x - 1 downTo 0)
.countUntil { l -> this[y][l] >= checkedValue }
val visibleRight = (x + 1..maxX)
.countUntil { r -> this[y][r] >= checkedValue }
val visibleTop = (y - 1 downTo 0)
.countUntil { t -> this[t][x] >= checkedValue }
val visibleBottom = (y + 1..maxY)
.countUntil { b -> this[b][x] >= checkedValue }
return visibleLeft * visibleRight * visibleTop * visibleBottom
}
fun List<String>.parseDigits(): List<List<Int>> {
return map { s -> s.map { c -> c - '0' } }
}
inline fun <T> Iterable<T>.countUntil(predicate: (T) -> Boolean): Int {
var count = 0
for (item in this) {
count += 1
if (predicate(item))
break
}
return count
}
| 0 |
Kotlin
| 0 | 0 |
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
| 2,233 |
aoc22-kotlin
|
Apache License 2.0
|
src/main/kotlin/apoy2k/aoc2023/problem2/Problem2.kt
|
ApoY2k
| 725,965,251 | false |
{"Kotlin": 2769}
|
package apoy2k.aoc2023.problem2
import apoy2k.aoc2023.readInput
import java.util.regex.Pattern
import kotlin.math.max
fun main() {
val games = readInput("problem2.txt")
val part1 = part1(games)
val part2 = part2(games)
println("Part 1: $part1")
println("Part 2: $part2")
}
private fun part1(games: List<String>) = games.sumOf { game ->
val allPullsOk = game.split(";").all { pulls ->
val blues = colorAmount(pulls, bluePattern)
val greens = colorAmount(pulls, greenPattern)
val reds = colorAmount(pulls, redPattern)
reds <= 12 && greens <= 13 && blues <= 14
}
val id = gamePattern.matcher(game).let {
it.find()
it.group(1).toInt()
}
if (allPullsOk) id else 0
}
private fun part2(games: List<String>) = games.sumOf { game ->
val pulls = mutableMapOf(
"blues" to 0,
"greens" to 0,
"reds" to 0,
)
game.split(";").forEach {
pulls["blues"] = max(colorAmount(it, bluePattern), pulls["blues"] ?: 0)
pulls["greens"] = max(colorAmount(it, greenPattern), pulls["greens"] ?: 0)
pulls["reds"] = max(colorAmount(it, redPattern), pulls["reds"] ?: 0)
}
(pulls["blues"] ?: 0) * (pulls["greens"] ?: 0) * (pulls["reds"] ?: 0)
}
private fun colorAmount(game: String, pattern: Pattern) = pattern.matcher(game).let {
if (it.find()) it.group(1).toInt() else 0
}
private val gamePattern = "Game (\\d+):".toPattern()
private val bluePattern = "(\\d+) blue".toPattern()
private val greenPattern = "(\\d+) green".toPattern()
private val redPattern = "(\\d+) red".toPattern()
| 0 |
Kotlin
| 0 | 0 |
4d428feac36813acb8541b69d6fb821669714882
| 1,615 |
aoc2023
|
The Unlicense
|
src/Day09.kt
|
juliantoledo
| 570,579,626 | false |
{"Kotlin": 34375}
|
import kotlin.math.abs
fun main() {
data class Point(var x: Int, var y: Int)
fun printMatrix(points: Set<Point>) {
val maxX = points.maxBy{point -> point.x}
val minX = points.minBy{point -> point.x}
val maxY = points.maxBy{point -> point.y}
val minY = points.minBy{point -> point.y}
val newPoints: List<Point> = points.map { point -> Point(point.x + abs(minX.x), point.y + abs(minY.y)) }
val width = maxX.x - minX.x + 1
val height = maxY.y - minY.y + 1
var matrix = MutableList(height) { MutableList<String>(width) { "." }}
matrix[newPoints.first().y][newPoints.first().x] = "s"
newPoints.drop(1).forEach { point ->
matrix[point.y][point.x] = "#"
}
matrix.forEach{ item ->
println(item.joinToString(separator = ""))
}
println()
}
fun near(head: Point, tail: Point): Boolean {
return (head.x - tail.x) in (-1..1).toList() && (head.y - tail.y) in (-1..1).toList()
}
fun solve(input: List<String>, knots: Int ): Int {
val points = (1..knots).map { Point(0, 0) }
val head = points.first()
val tail = points[1]
val visited = mutableSetOf<Point>()
visited.add(tail.copy())
input.forEach { line ->
line.splitTo(" ") { dir, moves ->
repeat(moves.toInt()) {
when (dir) {
"L" -> { head.x = head.x - 1 }
"R" -> { head.x = head.x + 1 }
"U" -> { head.y = head.y - 1 }
"D" -> { head.y = head.y + 1 }
}
for (i in 0 until points.size-1) {
if (!near(points[i], points[i+1])) {
points[i+1].x += Integer.signum(points[i].x - points[i+1].x)
points[i+1].y += Integer.signum(points[i].y - points[i+1].y)
}
}
visited.add(points.last().copy())
}
}
}
printMatrix(visited)
return visited.size
}
check(solve(readInput("Day09_test"), 2) == 13)
println("Part1: " + solve(readInput("Day09_input"), 2))
check(solve(readInput("Day09_test2"), 10) == 36)
println("Part2: " + solve(readInput("Day09_input"), 10))
}
| 0 |
Kotlin
| 0 | 0 |
0b9af1c79b4ef14c64e9a949508af53358335f43
| 2,404 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/Day02.kt
|
hrach
| 572,585,537 | false |
{"Kotlin": 32838}
|
enum class G(val score: Int) {
Rock(1),
Paper(2),
Scissor(3),
}
fun main() {
fun points(b: G, a: G): Int {
return when {
a == b -> 3
(a == G.Rock && b == G.Scissor) || (a == G.Paper && b == G.Rock) || (a == G.Scissor && b == G.Paper) -> 6
else -> 0
}
}
fun part1(input: List<String>): Int {
return input
.filter { it.isNotBlank() }
.sumOf {
val a = when (it[0]) {
'A' -> G.Rock
'B' -> G.Paper
'C' -> G.Scissor
else -> error(input)
}
val b = when (it.get(2)) {
'X' -> G.Rock
'Y' -> G.Paper
'Z' -> G.Scissor
else -> error(input)
}
points(a, b) + b.score
}
}
fun part2(input: List<String>): Int {
return input
.filter { it.isNotBlank() }
.also(::println)
.sumOf {
println(it)
val a = when (it[0]) {
'A' -> G.Rock
'B' -> G.Paper
'C' -> G.Scissor
else -> error(input)
}
when (it[2]) {
'X' -> 0 + when (a) {
G.Rock -> G.Scissor
G.Paper -> G.Rock
G.Scissor -> G.Paper
}.score
'Y' -> 3 + a.score
'Z' -> 6 + when (a) {
G.Rock -> G.Paper
G.Paper -> G.Scissor
G.Scissor -> G.Rock
}.score
else -> error(input)
}
}
}
val testInput = readInput("Day02_test")
check(part1(testInput), 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 1 |
40b341a527060c23ff44ebfe9a7e5443f76eadf3
| 1,374 |
aoc-2022
|
Apache License 2.0
|
src/Day09.kt
|
ricardorlg-yml
| 573,098,872 | false |
{"Kotlin": 38331}
|
import kotlin.math.abs
import kotlin.math.sign
class Day09Solver(input: List<String>) {
data class Knot(val isTail: Boolean, var knotX: Int = 0, var knotY: Int = 0) {
infix fun moveTo(direction: String) {
when (direction) {
"U" -> knotY -= 1
"D" -> knotY += 1
"L" -> knotX -= 1
"R" -> knotX += 1
}
}
infix fun isAwayFrom(other: Knot): Boolean {
return abs(knotX - other.knotX) > 1 || abs(knotY - other.knotY) > 1
}
infix fun moveTo(other: Knot) {
val dx = (other.knotX - knotX).sign
val dy = (other.knotY - knotY).sign
knotX += dx
knotY += dy
}
}
private tailrec fun moveKnots(
rope: List<Knot>,
direction: String,
moveHead: Boolean = true,
visited: MutableSet<Knot>,
) {
val head = rope[0]
val next = if (head.isTail) return else rope[1]
if (moveHead) {
head moveTo direction
}
if (next isAwayFrom head) {
next moveTo head
if (next.isTail)
visited.add(next.copy())
moveKnots(rope.drop(1), direction, false, visited)
}
}
private val movements = input.map { it.substringBefore(" ") to it.substringAfter(" ").toInt() }
fun solve(totalKnots: Int): Int {
val visitedKnotsByTail = mutableSetOf<Knot>()
val rope = (1..totalKnots).map { knot -> Knot(knot == totalKnots) }
movements.forEach { (direction, times) ->
repeat(times) {
moveKnots(rope, direction, visited = visitedKnotsByTail)
}
}
return visitedKnotsByTail.size + 1
}
}
fun main() {
val testInputPart1 = readInput("Day09_test")
val testInputPart2 = readInput("Day09_test2")
check(Day09Solver(testInputPart1).solve(2).also { println(it) } == 13)
check(Day09Solver(testInputPart2).solve(10).also { println(it) } == 36)
val input = readInput("Day09")
val solver = Day09Solver(input)
println(solver.solve(2))
println(solver.solve(10))
}
| 0 |
Kotlin
| 0 | 0 |
d7cd903485f41fe8c7023c015e4e606af9e10315
| 2,179 |
advent_code_2022
|
Apache License 2.0
|
src/main/kotlin/mkuhn/aoc/Day15.kt
|
mtkuhn
| 572,236,871 | false |
{"Kotlin": 53161}
|
package mkuhn.aoc
import mkuhn.aoc.util.Point
import mkuhn.aoc.util.overlaps
import mkuhn.aoc.util.readInput
import kotlin.math.abs
fun main() {
val input = readInput("Day15")
println(day15part1(input, 2000000))
println(day15part2(input, 0..4000000, 0..4000000))
}
fun day15part1(input: List<String>, yToCheck: Int): Int {
val sensorPairs = input.parseInputToPointPairs()
val sensorsToDist = sensorPairs.map { it.first to it.first.manhattanDistance(it.second) }
val notInRange = sensorsToDist.pointsInRangeOfSensorsAtY(yToCheck, sensorPairs.maxWidthForPointPairs())
val beaconsInRow = sensorPairs.map { it.second }.distinct().count { it.y == yToCheck }
return notInRange.size - beaconsInRow
}
fun day15part2(input: List<String>, xBounds: IntRange, yBounds: IntRange): Long {
val sensorPairs = input.parseInputToPointPairs()
val sensorsToDist = sensorPairs.map { it.first to it.first.manhattanDistance(it.second) }
val foundBeacon = yBounds.asSequence()
.flatMap { y -> sensorsToDist.pointsNotInRangeOfSensorsAtY(y, xBounds) }
.first()
return (foundBeacon.x.toLong()*4000000L)+foundBeacon.y.toLong()
}
val sensorRegex = """Sensor at x=([0-9-]+), y=([0-9-]+): closest beacon is at x=([0-9-]+), y=([0-9-]+)""".toRegex()
fun List<String>.parseInputToPointPairs(): List<Pair<Point, Point>> =
mapNotNull { line ->
sensorRegex.matchEntire(line)?.destructured?.let { (x1, y1, x2, y2) ->
Point(x1.toInt(), y1.toInt()) to Point(x2.toInt(), y2.toInt())
}
}
fun List<Pair<Point, Int>>.pointsInRangeOfSensorsAtY(y: Int, xBounds: IntRange): List<Point> {
return xBounds.map { Point(it, y) }.filter { p -> !p.outOfRange(this) }
}
fun List<Pair<Point, Int>>.pointsNotInRangeOfSensorsAtY(y: Int, xBounds: IntRange): List<Point> =
this.map { it.findSensorXRangeAtY(y) }
.fold(listOf(xBounds)) { acc, r -> acc.removeRange(r) } //remove beacon ranges from full x range
.flatMap { it.toSet() } //extract remaining x
.map { Point(it, y) }
fun Pair<Point, Int>.findSensorXRangeAtY(y: Int): IntRange {
val xDistance = abs(this.second - abs(this.first.y - y))
val leftX = this.first.x - xDistance
val rightX = this.first.x + xDistance
return if(Point(leftX, y).manhattanDistance(this.first) > this.second) IntRange.EMPTY
else leftX .. rightX
}
fun List<IntRange>.removeRange(removeRange: IntRange): List<IntRange> =
this.flatMap { r ->
if(removeRange overlaps r) {
val newRanges = mutableListOf<IntRange>()
if(removeRange.last > r.first) { newRanges += removeRange.last+1 .. r.last }
if(removeRange.first < r.last) { newRanges += r.first until removeRange.first }
newRanges
}
else { listOf(r) }
}
fun List<Pair<Point, Point>>.maxWidthForPointPairs() =
(minOfOrNull { it.first.x - it.first.manhattanDistance(it.second) }?:0)..
(maxOfOrNull { it.first.x + it.first.manhattanDistance(it.second) }?:0)
fun Point.outOfRange(sensors: List<Pair<Point, Int>>): Boolean {
return sensors.none { it.first.manhattanDistance(this) <= it.second }
}
| 0 |
Kotlin
| 0 | 1 |
89138e33bb269f8e0ef99a4be2c029065b69bc5c
| 3,175 |
advent-of-code-2022
|
Apache License 2.0
|
src/Day08.kt
|
jordan-thirus
| 573,476,470 | false |
{"Kotlin": 41711}
|
fun main() {
fun parseTrees(input: List<String>): List<List<Tree>> {
return input.map { row ->
row.map { tree ->
Tree(tree.digitToInt())
}
}
}
fun isTreeVisibleFromDirection(trees: List<List<Tree>>, rangeX: IntProgression, rangeY: IntProgression) {
for (x in rangeX) {
var maxHeight = 0
for (y in rangeY) {
//detect if tree is on an edge
if (x == rangeX.first || y == rangeY.first
|| trees[y][x].height > maxHeight
) {
trees[y][x].visible = true
maxHeight = trees[y][x].height
}
}
}
for (y in rangeY) {
var maxHeight = 0
for (x in rangeX) {
//detect if tree is on an edge
if (x == rangeX.first || y == rangeY.first
|| trees[y][x].height > maxHeight
) {
trees[y][x].visible = true
maxHeight = trees[y][x].height
}
}
}
}
fun part1(input: List<String>): Int {
val trees = parseTrees(input)
val yRange = trees.indices
val xRange = trees[0].indices
//west / north
isTreeVisibleFromDirection(trees, xRange, yRange)
//east / south
isTreeVisibleFromDirection(trees, xRange.reversed(), yRange.reversed())
return trees.sumOf { row ->
row.count { tree -> tree.visible }
}
}
fun getViewInDirection(treeHeight: Int, treesPast: List<Int>): Int{
val v = treesPast.indexOfFirst { h -> h >= treeHeight }
if(v == -1) return treesPast.size + 1
return v + 1
}
fun part2(input: List<String>): Int {
val trees = parseTrees(input)
val westEdge = trees[0].lastIndex
val southEdge = trees.lastIndex
//west
for (x in trees[0].indices) {
for (y in trees.indices) {
when (x) {
0 -> trees[y][x].viewWest = 0
1 -> trees[y][x].viewWest = 1
else -> {
val heights = trees[y].subList(1, x).map { tree -> tree.height }.reversed()
trees[y][x].viewWest = getViewInDirection(trees[y][x].height, heights)
}
}
}
}
//east
for (x in trees[0].indices) {
for (y in trees.indices) {
when (x) {
westEdge -> trees[y][x].viewEast = 0
westEdge-1 -> trees[y][x].viewEast = 1
else -> {
val heights = trees[y].subList(x + 1, westEdge).map { tree -> tree.height }
trees[y][x].viewEast =
getViewInDirection(trees[y][x].height, heights)
}
}
}
}
//north
for (x in trees[0].indices) {
for (y in trees.indices) {
when (y) {
0 -> trees[y][x].viewNorth = 0
1 -> trees[y][x].viewNorth = 1
else -> {
val heights = trees.subList(1, y).map { row -> row[x] }.map { tree -> tree.height }.reversed()
trees[y][x].viewNorth = getViewInDirection(trees[y][x].height, heights)
}
}
}
}
//south
for (x in trees[0].indices) {
for (y in trees.indices) {
when (y) {
southEdge -> trees[y][x].viewSouth = 0
southEdge-1 -> trees[y][x].viewSouth = 1
else -> {
val heights = trees.subList(y + 1, southEdge).map { row -> row[x] }.map { tree -> tree.height }
trees[y][x].viewSouth =
getViewInDirection(trees[y][x].height, heights)
}
}
}
}
// trees.forEach { row ->
// row.forEach { tree -> print("${tree.scenicScore}\t") }
// println()
// }
return trees.maxOf { row -> row.maxOf { tree -> tree.scenicScore } }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
data class Tree(
val height: Int, var visible: Boolean = false,
var viewWest: Int = 1, var viewEast: Int = 1,
var viewNorth: Int = 1, var viewSouth: Int = 1
) {
val scenicScore: Int
get() = viewWest * viewEast * viewNorth * viewSouth
}
| 0 |
Kotlin
| 0 | 0 |
59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e
| 4,885 |
advent-of-code-2022
|
Apache License 2.0
|
src/day15/Day15.kt
|
ritesh-singh
| 572,210,598 | false |
{"Kotlin": 99540}
|
package day15
import readInput
import java.awt.Point
import kotlin.math.abs
fun main() {
data class SensorBeacon(
val sensor: Point,
val beacon: Point,
val manhattanDistance: Int
)
fun parseInput(input: List<String>): List<SensorBeacon> {
val sensorBeacons = mutableListOf<SensorBeacon>()
input.forEach {
it.split(":").map { it.trim() }.map {
it.substringAfter("at").trim()
}.let {
val (sx, sy) = it[0].split(",").mapIndexed { index, s ->
if (index == 0) s.trim().substringAfter("x=").trim().toInt()
else s.trim().substringAfter("y=").trim().toInt()
}
val (bx, by) = it[1].split(",").mapIndexed { index, s ->
if (index == 0) s.trim().substringAfter("x=").trim().toInt()
else s.trim().substringAfter("y=").trim().toInt()
}
val dist = abs(sx - bx) + abs(sy - by)
sensorBeacons.add(
SensorBeacon(
sensor = Point(sx, sy),
beacon = Point(bx, by),
manhattanDistance = dist
)
)
}
}
return sensorBeacons
}
fun part1(input: List<String>, Y: Int): Int {
val sensorBeacons = parseInput(input)
val intersectionsRange = mutableListOf<IntRange>()
sensorBeacons.forEach {
val x = it.manhattanDistance - abs(Y - it.sensor.y)
// intersection distance
if (x > 0) intersectionsRange.add(it.sensor.x - x..it.sensor.x + x)
}
var set: Set<Int> = emptySet()
for (i in 0 until intersectionsRange.size) {
set = set.union(intersectionsRange[i])
}
return set.size - 1 // -1, exclude beacon in the row
}
fun part2(input: List<String>, limit: Int): Long {
val sensorBeacons = parseInput(input)
fun findPoint(): Point? {
for (x in 0..limit) {
var y = 0
while (y <= limit) {
val sensor = sensorBeacons.find {
(abs(it.sensor.x - x) + abs(it.sensor.y - y)) <= it.manhattanDistance
} ?: return Point(x, y)
y = sensor.sensor.y + sensor.manhattanDistance - abs(x - sensor.sensor.x) + 1
}
}
return null
}
return findPoint()?.let {
(it.x.toLong() * 4000000) + it.y.toLong()
} ?: error("No single point found")
}
val testInput = readInput("/day15/Day15_test")
println(part1(testInput, 10))
println(part2(testInput, 20))
println("----------------------")
val input = readInput("/day15/Day15")
println(part1(input, 2000000))
println(part2(input,4000000))
}
| 0 |
Kotlin
| 0 | 0 |
17fd65a8fac7fa0c6f4718d218a91a7b7d535eab
| 2,936 |
aoc-2022-kotlin
|
Apache License 2.0
|
src/Day03.kt
|
afranken
| 572,923,112 | false |
{"Kotlin": 15538}
|
fun main() {
/**
* Lower case letters start at 97. a -> 1, so a -> ASCII-code - 96 since values start at 1
* Upper case letter start at 65. A -> 65, so A -> ASCII-code - 38 since values start at 28
* https://www.ascii-code.com/
*/
fun codeFromChar(it: Char) = if (it.isUpperCase()) it.code - 38 else it.code - 96
fun part1(input: List<String>): Int {
return input
.asSequence()
.filterNot(String::isBlank)
.map(String::toList)
.map { it.subList(0, it.size / 2).toSet()
.intersect(it.subList(it.size / 2, it.size).toSet())
}
.filter {
it.size == 1 //some lines contain two duplicates. Not sure why
}
.map {
it.first() //all sets have only one element.
}
.sumOf(::codeFromChar)
}
fun part2(input: List<String>): Int {
return input
.asSequence()
.filterNot(String::isBlank)
.chunked(3) {
it.map(String::toSet)
.reduce(Set<Char>::intersect) //interset three lists at once
}
.filter {
it.size == 1 //some lines contain two duplicates. Not sure why
}
.map {
it.first() //all sets have only one element.
}
.sumOf(::codeFromChar)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 157)
val part2Test = part2(testInput)
println(part2Test)
check(part2Test == 70)
val input = readInput("Day03")
val part1 = part1(input)
println(part1)
check(part1 == 7917)
val part2 = part2(input)
println(part2)
check(part2 == 2585)
}
| 0 |
Kotlin
| 0 | 0 |
f047d34dc2a22286134dc4705b5a7c2558bad9e7
| 1,907 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
src/main/kotlin/advent/day9/SmokeBasin.kt
|
hofiisek
| 434,171,205 | false |
{"Kotlin": 51627}
|
package advent.day9
import advent.*
import java.io.File
data class Point(val height: Int, val position: Position)
/**
* Just calculate the risk level for all points that are lower than all of their adjacent point
*/
fun part1(input: File) = loadHeightmap(input)
.let { heightmap ->
heightmap.flatten()
.filter { it.height < heightmap.adjacents(it.position).minOf { it.height } }
.sumOf { it.height + 1 }
}
data class Basin(val points: Set<Point>) {
val size: Int
get() = points.size
fun contains(point: Point) = points.contains(point)
override fun toString() = buildString {
append("Basin(\n\t")
append(points.joinToString(",\n\t"))
append(",\n\tlowPoint=${points.minByOrNull { it.height }}")
append(",\n\tsize=$size")
append("\n)")
}
}
data class GraphNode(val point: Point, val edgesTo: Set<Point>) {
val height: Int by point::height
}
/**
* Represent the heightmap as a graph where each point is a node with edges to its adjacent
* points. Then find all basins by running BFS from each node, skipping the highest nodes (nodes with height == 9)
* and nodes that already belong to some basin.
*/
fun part2(input: File): Int = loadHeightmap(input)
.let(Matrix<Point>::toGraph)
.let(Matrix<GraphNode>::detectBasins)
.sortedBy { it.points.size }
.takeLast(3)
.onEach(::println)
.map { it.size }
.reduce(Int::times)
fun Matrix<Point>.toGraph(): Matrix<GraphNode> = map { rowPoints ->
rowPoints.map { point -> GraphNode(point, adjacents(point.position)) }
}.let(::Matrix)
fun Matrix<GraphNode>.detectBasins() = flatten().fold(emptySet<Basin>()) { basins, currentNode ->
when {
currentNode.height == 9 -> basins // skip the highest points
basins.any { it.contains(currentNode.point) } -> basins // skip points that already belong to some basin
else ->
// run bfs starting in the current node and add it to the set of basins
basins + runBfs(queue = ArrayDeque(listOf(currentNode)))
.map(GraphNode::point)
.toSet()
.let(::Basin)
}
}
fun Matrix<GraphNode>.runBfs(
queue: ArrayDeque<GraphNode>,
acc: List<GraphNode> = emptyList()
): List<GraphNode> =
if (queue.isEmpty()) {
acc
} else {
val curr = queue.removeFirst()
val suitableAdjacents = curr.edgesTo
.filter { it.height != 9 } // the highest points are ignored
.filter { edgeTo -> acc.none { it.point == edgeTo }} // filter out visited nodes
.filter { edgeTo -> queue.none { it.point == edgeTo }} // filter out open nodes
.map { getOrThrow(it.position) }
runBfs(ArrayDeque((queue + suitableAdjacents).toList()), acc + curr)
}
fun loadHeightmap(input: File): Matrix<Point> = input.readLines()
.map { it.split("").filterNot(String::isBlank).map(String::toInt) }
.mapIndexed { rowIdx, row ->
row.mapIndexed { colIdx, height -> Point(height, Position(rowIdx, colIdx)) }
}.let(::Matrix)
fun main() {
// with(loadInput(day = 9, filename = "input_example.txt")) {
with(loadInput(day = 9)) {
println(part1(this))
println(part2(this))
}
}
| 0 |
Kotlin
| 0 | 2 |
3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb
| 3,289 |
Advent-of-code-2021
|
MIT License
|
src/Day04.kt
|
fonglh
| 573,269,990 | false |
{"Kotlin": 48950, "Ruby": 1701}
|
fun main() {
fun fullyContains(firstElf: List<Int>, secondElf: List<Int>): Boolean {
val min1 = firstElf[0]
val max1 = firstElf[1]
val min2 = secondElf[0]
val max2 = secondElf[1]
return (min1 <= min2 && max1 >= max2) ||
(min2 <= min1 && max2 >= max1)
}
fun overlaps(firstElf: List<Int>, secondElf: List<Int>): Boolean {
val min1 = firstElf[0]
val max1 = firstElf[1]
val min2 = secondElf[0]
val max2 = secondElf[1]
// https://stackoverflow.com/a/3269471
return min1 <= max2 && min2 <= max1
}
fun overlapsObvious(firstElf: List<Int>, secondElf: List<Int>): Boolean {
val min1 = firstElf[0]
val max1 = firstElf[1]
val min2 = secondElf[0]
val max2 = secondElf[1]
return min2 in min1 .. max1 ||
max2 in min1 .. max1 ||
min1 in min2 .. max2 ||
max1 in min2 .. max2
}
fun part1(input: List<String>): Int {
var count = 0
input.forEach {
val elfAssignments = it.split(",")
val firstElf = elfAssignments[0].split("-").map { element -> element.toInt() }
val secondElf = elfAssignments[1].split("-").map { element -> element.toInt() }
if (fullyContains(firstElf, secondElf)) {
count += 1
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
input.forEach {
val elfAssignments = it.split(",")
val firstElf = elfAssignments[0].split("-").map { element -> element.toInt() }
val secondElf = elfAssignments[1].split("-").map { element -> element.toInt() }
if (overlaps(firstElf, secondElf)) {
count += 1
}
}
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 |
ef41300d53c604fcd0f4d4c1783cc16916ef879b
| 2,153 |
advent-of-code-2022
|
Apache License 2.0
|
src/problems/day8/part2/part2.kt
|
klnusbaum
| 733,782,662 | false |
{"Kotlin": 43060}
|
package problems.day8.part2
import java.io.File
//private const val test3 = "input/day8/test3.txt"
private const val inputFile = "input/day8/input.txt"
fun main() {
val stepsCount = File(inputFile).bufferedReader().useLines { numSteps(it) }
println("Number of steps $stepsCount")
}
private fun numSteps(lines: Sequence<String>): Long {
val (instructions, rules) = lines.fold(RuleSetBuilder()) { builder, line -> builder.nextLine(line) }.build()
val startingLocations = rules.keys.filter { it.endsWith("A") }
val cycleLengths = startingLocations.map { cycleLength(it, instructions.copy(), rules) }.map { it.toLong() }
return leastCommonMultiple(cycleLengths)
}
private fun cycleLength(startPos: String, instructions: Instructions, rules: Map<String, Rule>): Int {
var currentLocation = startPos
while (!currentLocation.endsWith("Z")) {
val nextDirection = instructions.next()
val nextRule = rules[currentLocation] ?: throw IllegalArgumentException("No such location: $currentLocation")
currentLocation =
if (nextDirection == 'L') {
nextRule.left
} else {
nextRule.right
}
}
return instructions.directionCount
}
private fun leastCommonMultiple(numbers: List<Long>): Long =
numbers.reduce { a, b -> leastCommonMultipleOfPair(a, b) }
private fun leastCommonMultipleOfPair(a: Long, b: Long): Long =
(a * b) / greatestCommonDivisor(a, b)
private fun greatestCommonDivisor(a: Long, b: Long): Long = when {
a == 0L -> b
b == 0L -> a
a > b -> greatestCommonDivisor(a % b, b)
else -> greatestCommonDivisor(a, b % a)
}
private class Instructions(val directions: String) : Iterator<Char> {
var directionCount = 0
override fun hasNext() = true
override fun next(): Char {
val next = directions[directionCount % directions.count()]
directionCount++
return next
}
fun copy() = Instructions(this.directions)
}
private data class Rule(val left: String, val right: String)
private fun String.toRule(): Rule {
val left = this.substringBefore(", ").trimStart { it == '(' }
val right = this.substringAfter(", ").trimEnd { it == ')' }
return Rule(left, right)
}
private data class ParseResult(val instructions: Instructions, val rules: Map<String, Rule>)
private class RuleSetBuilder {
private var state = State.INSTRUCTIONS
private var instructions: Instructions? = null
private val rules = mutableMapOf<String, Rule>()
private enum class State {
INSTRUCTIONS,
BLANK,
RULES,
}
fun nextLine(line: String): RuleSetBuilder {
when (state) {
State.INSTRUCTIONS -> {
instructions = Instructions(line)
state = State.BLANK
}
State.BLANK -> {
state = State.RULES
}
State.RULES -> {
rules[line.substringBefore(" =")] = line.substringAfter("= ").toRule()
}
}
return this
}
fun build() = ParseResult(
instructions ?: throw IllegalArgumentException("missing instructions"),
rules
)
}
| 0 |
Kotlin
| 0 | 0 |
d30db2441acfc5b12b52b4d56f6dee9247a6f3ed
| 3,221 |
aoc2023
|
MIT License
|
src/main/kotlin/day15/Day15.kt
|
daniilsjb
| 434,765,082 | false |
{"Kotlin": 77544}
|
package day15
import java.io.File
import java.util.*
fun main() {
val data = parse("src/main/kotlin/day15/Day15.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 15 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Graph(
val size: Int,
val vertices: List<Int>,
)
private data class Vertex(
val x: Int,
val y: Int,
)
private data class Path(
val target: Vertex,
val distance: Int,
) : Comparable<Path> {
override fun compareTo(other: Path): Int =
distance.compareTo(other.distance)
}
private fun parse(path: String): Graph {
val lines = File(path).readLines()
val size = lines.size
val nodes = lines.flatMap { line ->
line.map(Char::digitToInt)
}
return Graph(size, nodes)
}
private fun Graph.distanceAt(vertex: Vertex): Int {
val dx = vertex.x / size
val dy = vertex.y / size
val px = vertex.x % size
val py = vertex.y % size
val combinedCost = vertices[py * size + px] + dx + dy
return (combinedCost - 1) % 9 + 1
}
private fun Vertex.edges(target: Vertex): List<Vertex> =
listOfNotNull(
if (x - 1 > 0) Vertex(x - 1, y) else null,
if (x + 1 <= target.x) Vertex(x + 1, y) else null,
if (y - 1 > 0) Vertex(x, y - 1) else null,
if (y + 1 <= target.y) Vertex(x, y + 1) else null,
)
private fun findPath(graph: Graph, target: Vertex): Int {
val source = Vertex(0, 0)
val distances = mutableMapOf(source to 0)
val frontier = PriorityQueue<Path>()
.apply { add(Path(target = source, distance = 0)) }
while (frontier.isNotEmpty()) {
val (vertex, distance) = frontier.poll()
if (vertex == target) {
return distance
}
if (distance > distances.getValue(vertex)) continue
for (edge in vertex.edges(target)) {
val distanceToEdge = distance + graph.distanceAt(edge)
if (distanceToEdge < distances.getOrDefault(edge, Int.MAX_VALUE)) {
distances[edge] = distanceToEdge
frontier.add(Path(edge, distanceToEdge))
}
}
}
error("Could not find the shortest path.")
}
private fun part1(graph: Graph): Int =
findPath(graph, target = Vertex(graph.size - 1, graph.size - 1))
private fun part2(graph: Graph): Int =
findPath(graph, target = Vertex(graph.size * 5 - 1, graph.size * 5 - 1))
| 0 |
Kotlin
| 0 | 1 |
bcdd709899fd04ec09f5c96c4b9b197364758aea
| 2,560 |
advent-of-code-2021
|
MIT License
|
src/main/kotlin/com/ginsberg/advent2022/Day12.kt
|
tginsberg
| 568,158,721 | false |
{"Kotlin": 113322}
|
/*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 12 - Hill Climbing Algorithm
* Problem Description: http://adventofcode.com/2022/day/12
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day12/
*/
package com.ginsberg.advent2022
import java.util.PriorityQueue
class Day12(input: List<String>) {
private val heightMap: HeightMap = parseInput(input)
fun solvePart1(): Int = heightMap.shortestPath(
begin = heightMap.start,
isGoal = { it == heightMap.end },
canMove = { from, to -> to - from <= 1 }
)
fun solvePart2(): Int = heightMap.shortestPath(
begin = heightMap.end,
isGoal = { heightMap.elevations[it] == 0 },
canMove = { from, to -> from - to <= 1 }
)
private class HeightMap(val elevations: Map<Point2D, Int>, val start: Point2D, val end: Point2D) {
fun shortestPath(
begin: Point2D,
isGoal: (Point2D) -> Boolean,
canMove: (Int, Int) -> Boolean
): Int {
val seen = mutableSetOf<Point2D>()
val queue = PriorityQueue<PathCost>().apply { add(PathCost(begin, 0)) }
while (queue.isNotEmpty()) {
val nextPoint = queue.poll()
if (nextPoint.point !in seen) {
seen += nextPoint.point
val neighbors = nextPoint.point.cardinalNeighbors()
.filter { it in elevations }
.filter { canMove(elevations.getValue(nextPoint.point), elevations.getValue(it)) }
if (neighbors.any { isGoal(it) }) return nextPoint.cost + 1
queue.addAll(neighbors.map { PathCost(it, nextPoint.cost + 1) })
}
}
throw IllegalStateException("No valid path from $start to $end")
}
}
private data class PathCost(val point: Point2D, val cost: Int) : Comparable<PathCost> {
override fun compareTo(other: PathCost): Int =
this.cost.compareTo(other.cost)
}
private fun parseInput(input: List<String>): HeightMap {
var start: Point2D? = null
var end: Point2D? = null
val elevations = input.flatMapIndexed { y, row ->
row.mapIndexed { x, char ->
val here = Point2D(x, y)
here to when (char) {
'S' -> 0.also { start = here }
'E' -> 25.also { end = here }
else -> char - 'a'
}
}
}.toMap()
return HeightMap(elevations, start!!, end!!)
}
}
| 0 |
Kotlin
| 2 | 26 |
2cd87bdb95b431e2c358ffaac65b472ab756515e
| 2,638 |
advent-2022-kotlin
|
Apache License 2.0
|
aoc-2023/src/main/kotlin/nerok/aoc/aoc2023/day02/Day02.kt
|
nerok
| 572,862,875 | false |
{"Kotlin": 113337}
|
package nerok.aoc.aoc2023.day02
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
data class RGB(
val red: Long,
val green: Long,
val blue: Long
) {
fun mergeMax(other: RGB): RGB {
return RGB(
red = maxOf(this.red, other.red),
green = maxOf(this.green, other.green),
blue = maxOf(this.blue, other.blue),
)
}
fun aboveLimit(limit: RGB): Boolean {
if (this.red > limit.red) return true
if (this.green > limit.green) return true
if (this.blue > limit.blue) return true
return false
}
fun power(): Long {
return this.red * this.green * this.blue
}
}
fun String.toRGB(): RGB {
var red = 0L
var green = 0L
var blue = 0L
this
.split(",")
.map { it.trim() }
.map {
if (it.contains("red")) {
red = it.split(" ").first().toLongOrNull() ?: 0L
}
if (it.contains("green")) {
green = it.split(" ").first().toLongOrNull() ?: 0L
}
if (it.contains("blue")) {
blue = it.split(" ").first().toLongOrNull() ?: 0L
}
}
return RGB(red, green, blue)
}
fun main() {
fun part1(input: List<String>): Long {
val limit = RGB(12,13,14)
return input.map { game ->
val parsed = game.split(":")
val gameid = parsed.first().removePrefix("Game ").toLong()
val data = parsed.last().split(";").map { c ->
c.toRGB()
}.reduce { acc, rgb -> acc.mergeMax(rgb) }
gameid to data
}.filterNot {
it.second.aboveLimit(limit)
}.sumOf { it.first }
}
fun part2(input: List<String>): Long {
return input.map { game ->
val data = game
.split(":")
.last()
.split(";")
.map { c ->
c.toRGB()
}
.reduce { acc, rgb -> acc.mergeMax(rgb) }
data.power()
}.sumOf { it }
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day02_test")
check(part1(testInput) == 8L)
check(part2(testInput) == 2286L)
val input = Input.readInput("Day02")
println("Part1:")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println("Part2:")
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
| 0 |
Kotlin
| 0 | 0 |
7553c28ac9053a70706c6af98b954fbdda6fb5d2
| 2,564 |
AOC
|
Apache License 2.0
|
2021/src/main/kotlin/day8_func.kt
|
madisp
| 434,510,913 | false |
{"Kotlin": 388138}
|
import utils.Parser
import utils.Solution
import utils.cut
import utils.mapItems
fun main() {
Day8Func.run()
}
object Day8Func : Solution<List<Day8Func.Key>>() {
override val name = "day8"
override val parser = Parser.lines.mapItems {
it.cut("|") { input, output -> Key(input.split(' '), output.split(' ')) }
}
override fun part1(keys: List<Key>): Int {
return keys.flatMap {
it.output.filter { out -> out.length in setOf(2, 3, 4, 7) }
}.count()
}
override fun part2(input: List<Key>): Number? {
return input.map {
val p = solve(it.digits)
it.output.map { A[remap(it, p)] }.joinToString(separator = "").toInt()
}.sum()
}
fun permutations(input: String): List<String> {
if (input.length == 1) {
return listOf(input)
}
return input.toCharArray().flatMapIndexed { index, char ->
permutations(input.substring(0 until index) + input.substring(index + 1)).map {
char + it
}
}
}
val P = permutations("abcdefg")
val A = mapOf(
"abcefg" to '0',
"cf" to '1',
"acdeg" to '2',
"acdfg" to '3',
"bcdf" to '4',
"abdfg" to '5',
"abdefg" to '6',
"acf" to '7',
"abcdefg" to '8',
"abcdfg" to '9'
)
fun remap(key: String, perm: String): String {
return key.toCharArray().map {
when (it) {
'a' -> perm[0]
'b' -> perm[1]
'c' -> perm[2]
'd' -> perm[3]
'e' -> perm[4]
'f' -> perm[5]
'g' -> perm[6]
else -> throw IllegalStateException("Bad input, bad!")
}
}.sorted().joinToString(separator = "")
}
fun solve(digits: List<String>): String {
val solved = P.filter { p -> digits.map { remap(it, p) }.toSet() == A.keys }
return solved.first()
}
data class Key(val digits: List<String>, val output: List<String>)
}
| 0 |
Kotlin
| 0 | 1 |
3f106415eeded3abd0fb60bed64fb77b4ab87d76
| 1,842 |
aoc_kotlin
|
MIT License
|
src/main/de/ddkfm/Day5.kt
|
DDKFM
| 433,861,159 | false |
{"Kotlin": 13522}
|
package de.ddkfm
import kotlin.math.*
data class Point(
val x : Int,
val y : Int
)
data class Line(
val p1 : Point,
val p2 : Point
) {
val directionVektor = Point(p2.x - p1.x, p2.y - p1.y)
val unitVektor = Point(directionVektor.x.divideOr0(directionVektor.x.absoluteValue), directionVektor.y.divideOr0(directionVektor.y.absoluteValue))
val length = max(directionVektor.x.divideOr0(unitVektor.x), directionVektor.y.divideOr0(unitVektor.y))
fun getPoints() : List<Point> {
return (0..length).map { n -> Point(p1.x + n * unitVektor.x, p1.y + n * unitVektor.y) }
}
fun Int.divideOr0(b : Int) : Int {
if(b == 0)
return 0
return this / b
}
}
class Day5 : DayInterface<List<String>, Int> {
override fun part1(input: List<String>): Int {
val lines = input.map {
val points = it.split(" -> ").map { it.split(",").map { it.toInt() } }
return@map Line(p1 = Point(points[0][0], points[0][1]), p2 = Point(points[1][0], points[1][1]))
}
val straightLines = lines.filter { abs(it.unitVektor.x + it.unitVektor.y) == 1 }
//straightLines.printLines()
//straightLines.print()
return straightLines
.map { it.getPoints() }
.flatten()
.groupBy { it }
.filter { it.value.size > 1 }
.keys.size
}
fun List<Line>.printLines() {
this.forEach { line ->
println("[--]${line.p1.x},${line.p1.y} -> ${line.p2.x}, ${line.p2.y}")
println(line.getPoints().joinToString(separator = ",") { "(${it.x}, ${it.y})" })
}
}
fun List<Line>.print() {
val flattenPoints = this.map { it.p1 }.union(this.map { it.p2 })
val xMax = flattenPoints.maxOf { it.x }
val yMax = flattenPoints.maxOf { it.y }
val points = this.map { it.getPoints() }.flatten()
(0 .. yMax).forEach { y ->
(0 .. xMax).forEach { x ->
val matchedPoints = points.filter { it.x == x && it.y == y }
if(matchedPoints.isNotEmpty()) {
print("${matchedPoints.size} ")
} else {
print(". ")
}
}
print("\n")
}
}
override fun part2(input: List<String>): Int {
val lines = input.map {
val points = it.split(" -> ").map { it.split(",").map { it.toInt() } }
return@map Line(p1 = Point(points[0][0], points[0][1]), p2 = Point(points[1][0], points[1][1]))
}
//lines.print()
return lines
.map { it.getPoints() }
.flatten()
.groupBy { it }
.filter { it.value.size > 1 }
.keys.size
}
}
| 0 |
Kotlin
| 0 | 0 |
6e147b526414ab5d11732dc32c18ad760f97ff59
| 2,784 |
AdventOfCode21
|
MIT License
|
src/Day03.kt
|
fedochet
| 573,033,793 | false |
{"Kotlin": 77129}
|
fun main() {
fun itemPriority(itemType: Char): Int = when (itemType) {
in 'a'..'z' -> (itemType - 'a') + 1
in 'A'..'Z' -> (itemType - 'A') + 27
else -> error("Unexpected item type '$itemType'")
}
fun findCommonItems(left: String, right: String): String {
val commonItems = left.toSet() intersect right.toSet()
return String(commonItems.toCharArray())
}
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
require(rucksack.length % 2 == 0)
val left = rucksack.substring(0, rucksack.length / 2)
val right = rucksack.substring(rucksack.length / 2)
val commonItem = findCommonItems(left, right).singleOrNull()
?: error("There are multiple common items between $left and $right")
itemPriority(commonItem)
}
}
fun part2(input: List<String>): Int {
require(input.size % 3 == 0)
return input
.windowed(size = 3, step = 3)
.sumOf { group ->
val (one, two, three) = group
val commonItems = findCommonItems(findCommonItems(one, two), three)
val commonItem = commonItems.singleOrNull()
?: error("There are multiple common items in the group: $group")
itemPriority(commonItem)
}
}
// 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 | 1 |
975362ac7b1f1522818fc87cf2505aedc087738d
| 1,675 |
aoc2022
|
Apache License 2.0
|
facebook/y2020/round1/a2.kt
|
mikhail-dvorkin
| 93,438,157 | false |
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
|
package facebook.y2020.round1
import java.util.*
private fun solve(M: Int = 1_000_000_007): Int {
val (n, k) = readInts()
val (L, w, h) = List(3) { readInts().toMutableList().also { list ->
val (a, b, c, d) = readInts()
for (i in k until n) {
list.add(((a.toLong() * list[i - 2] + b.toLong() * list[i - 1] + c) % d + 1).toInt())
}
}}
data class Group(val xFrom: Int, val xTo: Int, val vertical: Long)
fun perimeter(g: Group): Long = 2 * (g.xTo - g.xFrom) + g.vertical
val groups = TreeMap<Int, Group>()
var ans = 1
var perimeter = 0L
for (i in h.indices) {
var new = Group(L[i], L[i] + w[i], 2L * h[i])
while (true) {
var g = groups.floorEntry(new.xFrom)?.value
if (g == null || g.xTo < new.xFrom) g = groups.ceilingEntry(new.xFrom)?.value
if (g != null && g.xFrom > new.xTo) g = null
if (g != null && new.xFrom > g.xTo) g = null
if (g == null) break
perimeter -= perimeter(g)
groups.remove(g.xFrom)
new = Group(minOf(g.xFrom, new.xFrom), maxOf(g.xTo, new.xTo), g.vertical + new.vertical - 2 * h[i])
}
groups[new.xFrom] = new
perimeter += perimeter(new)
ans = ((ans.toLong() * (perimeter % M)) % M).toInt()
}
return ans
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 |
Java
| 1 | 9 |
30953122834fcaee817fe21fb108a374946f8c7c
| 1,439 |
competitions
|
The Unlicense
|
src/main/kotlin/biz/koziolek/adventofcode/year2021/day08/day8.kt
|
pkoziol
| 434,913,366 | false |
{"Kotlin": 715025, "Shell": 1892}
|
package biz.koziolek.adventofcode.year2021.day08
import biz.koziolek.adventofcode.findInput
fun main() {
val inputFile = findInput(object {})
val lines = inputFile.bufferedReader().readLines()
println("There are ${countEasyDigitsInOutput(lines)} digits 1,4,7,8 in output")
val notes = parseNotes(lines)
val sum = notes.sumOf { decodeNumber(it.output, solveWireConnections(it)) }
println("Sum of all output si: $sum")
}
data class Note(val patterns: List<String>, val output: List<String>)
fun countEasyDigitsInOutput(lines: List<String>): Int {
return parseNotes(lines)
.sumOf { note -> note.output.count { out -> out.length in listOf(2, 3, 4, 7) } }
}
fun parseNotes(lines: List<String>): List<Note> =
lines
.map { it.split('|') }
.map { Note(
patterns = it[0].trim().split(' '),
output = it[1].trim().split(' ')
) }
fun solveWireConnections(note: Note): Map<Char, Char> {
val wireMap = HashMap<Char, Char>()
val signalsCF = note.patterns.single { it.length == 2 }.toSet()
val signalsACF = note.patterns.single { it.length == 3 }.toSet()
val signalsBCDF = note.patterns.single { it.length == 4 }.toSet()
val signalsABCDEFG = note.patterns.single { it.length == 7 }.toSet()
val signals235 = note.patterns.filter { it.length == 5 }.map { it.toSet() }
val signals069 = note.patterns.filter { it.length == 6 }.map { it.toSet() }
val signalA = (signalsACF - signalsCF).single()
wireMap[signalA] = 'a'
val signalsADG = signals235.flatten()
.groupBy { it }
.filter { it.value.size == 3 }
.keys
val signalG = (signalsADG - signalsBCDF - signalsACF).single()
wireMap[signalG] = 'g'
val signalD = (signalsADG - signalA - signalG).single()
wireMap[signalD] = 'd'
val signalB = (signalsBCDF - signalsCF - signalD).single()
wireMap[signalB] = 'b'
val signalsABFG = signals069.flatten()
.groupBy { it }
.filter { it.value.size == 3 }
.keys
val signalF = (signalsABFG - signalA - signalB - signalG).single()
wireMap[signalF] = 'f'
val signalE = (signalsABCDEFG - signalA - signalB - signalsCF - signalD - signalG).single()
wireMap[signalE] = 'e'
val signalC = (signalsABCDEFG - signalA - signalB - signalD - signalE - signalF - signalG).single()
wireMap[signalC] = 'c'
return wireMap
}
fun decodeDigit(signals: String, wireMap: Map<Char, Char>): Int {
val segments = signals.toSet()
.map { wireMap[it] }
.joinToString(separator = "")
.let { sortString(it) }
return when (segments) {
"abcefg" -> 0
"cf" -> 1
"acdeg" -> 2
"acdfg" -> 3
"bcdf" -> 4
"abdfg" -> 5
"abdefg" -> 6
"acf" -> 7
"abcdefg" -> 8
"abcdfg" -> 9
else -> throw IllegalArgumentException("Unknown segments: $segments")
}
}
private fun sortString(string: String): String =
string.toSet().sortedBy { it }.joinToString(separator = "")
fun decodeNumber(strings: List<String>, wireMap: Map<Char, Char>): Int =
strings
.map { decodeDigit(it, wireMap) }
.fold(0) { sum, digit -> 10 * sum + digit }
| 0 |
Kotlin
| 0 | 0 |
1b1c6971bf45b89fd76bbcc503444d0d86617e95
| 3,362 |
advent-of-code
|
MIT License
|
src/main/kotlin/com/github/wakingrufus/aoc/Day6.kt
|
wakingrufus
| 159,674,364 | false | null |
package com.github.wakingrufus.aoc
import kotlin.math.absoluteValue
data class Coordinate(val x: Int, val y: Int) {
fun manhattanDistance(other: Coordinate): Int =
(this.x - other.x).absoluteValue + (this.y - other.y).absoluteValue
}
class Day6 {
fun part1(input: List<String>): Int {
return findLargestArea(input.map(this::parseCoordinate))
}
fun part2(input: List<String>): Int {
return safeZoneSize(input.map(this::parseCoordinate), 10000)
}
fun allPoints(coordinates: List<Coordinate>): List<Pair<Int, Int>> {
val xMax = coordinates.maxBy { it.x }?.x ?: 1
val xMin = coordinates.minBy { it.x }?.x ?: 0
val yMax = coordinates.maxBy { it.y }?.y ?: 1
val yMin = coordinates.minBy { it.y }?.y ?: 0
return xMin.rangeTo(xMax)
.flatMap { x ->
yMin.rangeTo(yMax)
.map { y ->
x to y
}
}
}
fun safeZoneSize(coordinates: List<Coordinate>, distance: Int): Int {
return allPoints(coordinates)
.filter { point ->
coordinates.sumBy {
it.manhattanDistance(Coordinate(point.first, point.second))
} < distance
}
.count()
}
fun findLargestArea(coordinates: List<Coordinate>): Int {
return allPoints(coordinates)
.map { point -> findClosestCoordinate(coordinates, point.first, point.second) }
.groupBy { it }
.maxBy { it.value.size }?.value?.size ?: 0
}
fun findClosestCoordinate(coordinates: List<Coordinate>, x: Int, y: Int): Coordinate? {
val thisCoordinate = Coordinate(x, y)
val allDistances = coordinates.map {
it to it.manhattanDistance(thisCoordinate)
}
val min = allDistances.minBy { it.second }
return if (allDistances.count { it.second == min?.second } > 1) null else min?.first
}
fun parseCoordinate(line: String): Coordinate {
return line.split(",")
.map(String::trim)
.map(String::toInt)
.let {
Coordinate(x = it[0], y = it[1])
}
}
}
| 0 |
Kotlin
| 0 | 0 |
bdf846cb0e4d53bd8beda6fdb3e07bfce59d21ea
| 2,331 |
advent-of-code-2018
|
MIT License
|
day-14/src/main/kotlin/ExtendedPolymerization.kt
|
diogomr
| 433,940,168 | false |
{"Kotlin": 92651}
|
fun main() {
println("Part One Solution: ${partOne()}")
println("Part Two Solution: ${partTwo()}")
println("Part Two Solution Non Recursive: ${partTwoNonRecursive()}")
}
private fun partOne(): Int {
var template = readInputLines()[0].toCharArray().toList()
val rules = readRules()
for (step in 1..10) {
val result = mutableListOf<Char>()
result.add(template[0])
for (i in template.indices) {
if (i + 1 !in template.indices) {
break
}
val pair = "${template[i]}${template[i + 1]}"
result.add(rules[pair]!![0])
result.add(template[i + 1])
}
template = result
}
val charCount = template.groupingBy { it }.eachCount()
return charCount.maxOf { it.value } - charCount.minOf { it.value }
}
private fun partTwo(): Long {
val template = readInputLines()[0].toCharArray().toList()
val rules = readRules()
var letterCounter = mapOf(template[0] to 1L)
val cache = mutableMapOf<Pair<Int, Pair<Char, Char>>, Map<Char, Long>>()
template.indices.take(template.size - 1)
.forEach {
val result = stepThrough(Pair(template[it], template[it + 1]), rules, 40, cache)
letterCounter = merge(letterCounter, result)
}
return letterCounter.maxOf { it.value } - letterCounter.minOf { it.value }
}
private fun partTwoNonRecursive(): Long {
val template = readInputLines()[0].toCharArray().toList()
val rules = readRules()
var pairCounter = mutableMapOf<Pair<Char, Char>, Long>()
template.indices.take(template.size - 1)
.forEach {
val pair = Pair(template[it], template[it + 1])
pairCounter.merge(pair, 1L) { old, new -> old + new }
}
for (i in 1..40) {
val newCounter = mutableMapOf<Pair<Char, Char>, Long>()
pairCounter.forEach {
val (left, right) = it.key
val middle = rules["$left$right"]
newCounter.merge(Pair(left, middle!![0]), it.value) { old, new -> old + new }
newCounter.merge(Pair(middle[0], right), it.value) { old, new -> old + new }
}
pairCounter = newCounter
}
val charCount = mutableMapOf<Char, Long>()
pairCounter.forEach {
charCount.merge(it.key.first, it.value) { old, new -> old + new }
}
// First key is always chosen to handle overlaps so the last element of the template is missing in the final pair
charCount.merge(template[template.size - 1], 1L) { old, new -> old + new }
return charCount.maxOf { it.value } - charCount.minOf { it.value }
}
private fun stepThrough(
pair: Pair<Char, Char>,
rules: Map<String, String>,
iter: Int,
cache: MutableMap<Pair<Int, Pair<Char, Char>>, Map<Char, Long>>
): Map<Char, Long> {
cache[Pair(iter, pair)]?.let {
return it
}
val (left, right) = pair
val middle = rules["$left$right"]!![0]
if (iter == 1) {
return if (middle == right) mapOf(middle to 2L) else mapOf(middle to 1L, right to 1L)
}
val newIteration = iter - 1
val leftMidPair = Pair(left, middle)
val leftMid = stepThrough(leftMidPair, rules, newIteration, cache).apply {
cache[Pair(newIteration, leftMidPair)] = this
}
val midRightPair = Pair(middle, right)
val midRight = stepThrough(midRightPair, rules, newIteration, cache).apply {
cache[Pair(newIteration, Pair(middle, right))] = this
}
return merge(leftMid, midRight)
}
fun merge(first: Map<Char, Long>, second: Map<Char, Long>): Map<Char, Long> {
val result = first.toMutableMap()
second.forEach { entry ->
result.merge(entry.key, entry.value) { old, new ->
old + new
}
}
return result
}
private fun readRules(): Map<String, String> {
val pairToMidValue = mutableMapOf<String, String>()
readInputLines().drop(1)
.forEach {
val (pair, value) = it.split(" -> ")
pairToMidValue[pair] = value
}
return pairToMidValue
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 |
Kotlin
| 0 | 0 |
17af21b269739e04480cc2595f706254bc455008
| 4,270 |
aoc-2021
|
MIT License
|
src/main/day21/day21.kt
|
rolf-rosenbaum
| 572,864,107 | false |
{"Kotlin": 80772}
|
package day21
import readInput
fun main() {
val input = readInput("main/day21/Day21")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Long {
val monkeys = input.map { it.toMonkey() }.associateBy { it.name }
return solvePart1(monkeys.toMutableMap(), monkeys["root"]!!)
}
fun part2(input: List<String>): Long {
var humanNumber = 1000000000000L
val monkeys = input.map { it.toMonkey() }.associateBy { it.name }
while (true) {
if (humanNumber % 10000L == 0L) println(humanNumber)
if (checkForMatch(monkeys.toMutableMap(), humanNumber)) return humanNumber
humanNumber++
}
return -1
}
fun checkForMatch(monkeys: MutableMap<String, Monkey>, humanNumber: Long): Boolean {
val rootMonkey = monkeys["root"]!!
val human = monkeys["humn"]!!.copy(number = humanNumber)
monkeys["humn"] = human
val firstMonkey = monkeys[rootMonkey.op?.first!!]!!
val secondMonkey = monkeys[rootMonkey.op.second]!!
val first = solvePart1(monkeys, firstMonkey)
val second = solvePart1(monkeys, secondMonkey)
return (first != null && first == second)
}
fun solvePart1(monkeys: MutableMap<String, Monkey>, current: Monkey): Long =
if (current.number != null) {
current.number
} else {
val firstMonkey = monkeys[current.op?.first] ?: error("out of monkeys")
val secondMonkey = monkeys[current.op?.second] ?: error("out of monkeys")
val firstNumber = solvePart1(monkeys, firstMonkey)
monkeys[firstMonkey.name] = firstMonkey.copy(number = firstNumber)
val secondNumber = solvePart1(monkeys, secondMonkey)
monkeys[secondMonkey.name] = secondMonkey.copy(number = secondNumber)
val func = current.op?.operator?.func!!
func.invoke(firstNumber, secondNumber)
}
fun String.toMonkey(): Monkey {
return split(": ").let { (name, rest) ->
if (rest.all(Char::isDigit)) {
Monkey(name = name, number = rest.toLong())
} else {
rest.split(" ").let { (first, op, second) ->
Monkey(name = name, op = MonkeyOp(first = first, second = second, operator = Operator.fromString(op)))
}
}
}
}
data class Monkey(val name: String, val number: Long? = null, val op: MonkeyOp? = null)
data class MonkeyOp(val first: String, val second: String, val operator: Operator)
enum class Operator(val func: (Long, Long) -> Long) {
PLUS({ a, b -> a + b }),
MINUS({ a, b -> a - b }),
TIMES({ a, b -> a * b }),
DIV({ a, b -> a / b });
fun opposite() = when (this) {
PLUS -> MINUS
MINUS -> PLUS
TIMES -> DIV
DIV -> TIMES
}
companion object {
fun fromString(operation: String) =
when (operation.trim()) {
"+" -> PLUS
"-" -> MINUS
"*" -> TIMES
"/" -> DIV
else -> error("illegal operation")
}
}
}
| 0 |
Kotlin
| 0 | 2 |
59cd4265646e1a011d2a1b744c7b8b2afe482265
| 3,006 |
aoc-2022
|
Apache License 2.0
|
src/day12/Day12.kt
|
ayukatawago
| 572,742,437 | false |
{"Kotlin": 58880}
|
package day12
import readInput
fun main() {
val testInput = readInput("day12/test")
val elevationMap = testInput.map { it.map { c -> c.toElevation() } }
val startRow = testInput.indexOfFirst { it.contains('S') }
val startColumn = testInput[startRow].indexOfFirst { it == 'S' }
val endRow = testInput.indexOfFirst { it.contains('E') }
val endColumn = testInput[endRow].indexOfFirst { it == 'E' }
part1(elevationMap, startPoint = Point(startRow, startColumn), endPoint = Point(endRow, endColumn))
part2(elevationMap, startPoint = Point(endRow, endColumn))
}
private fun part1(elevationMap: List<List<Int>>, startPoint: Point, endPoint: Point) {
println(common(elevationMap, true, startPoint) { point -> point == endPoint })
}
private fun part2(elevationMap: List<List<Int>>, startPoint: Point) {
println(common(elevationMap, false, startPoint) { point -> elevationMap[point.row][point.column] == 0 })
}
private fun common(
elevationMap: List<List<Int>>,
shouldClimb: Boolean,
startPoint: Point,
condition: (Point) -> Boolean
): Int {
val visitedMap = Array(elevationMap.size) { BooleanArray(elevationMap[0].size) { false } }
visitedMap[startPoint.row][startPoint.column] = true
val canMove: (Int) -> Boolean = if (shouldClimb) {
{ diff -> diff <= 1 }
} else {
{ diff -> diff >= -1 }
}
var steps = 0
var visitedPoints = listOf(startPoint)
while (visitedPoints.isNotEmpty() && visitedPoints.none { condition(it) }) {
val newVisitedPoints = mutableSetOf<Point>()
visitedPoints.forEach {
val currentElevation = elevationMap[it.row][it.column]
if (it.row + 1 in visitedMap.indices) {
val diff = elevationMap[it.row + 1][it.column] - currentElevation
if (canMove(diff) && !visitedMap[it.row + 1][it.column]) {
newVisitedPoints.add(Point(it.row + 1, it.column))
visitedMap[it.row + 1][it.column] = true
}
}
if (it.row - 1 in visitedMap.indices) {
val diff = elevationMap[it.row - 1][it.column] - currentElevation
if (canMove(diff) && !visitedMap[it.row - 1][it.column]) {
newVisitedPoints.add(Point(it.row - 1, it.column))
visitedMap[it.row - 1][it.column] = true
}
}
if (it.column + 1 in visitedMap[0].indices) {
val diff = elevationMap[it.row][it.column + 1] - currentElevation
if (canMove(diff) && !visitedMap[it.row][it.column + 1]) {
newVisitedPoints.add(Point(it.row, it.column + 1))
visitedMap[it.row][it.column + 1] = true
}
}
if (it.column - 1 in visitedMap[0].indices) {
val diff = elevationMap[it.row][it.column - 1] - currentElevation
if (canMove(diff) && !visitedMap[it.row][it.column - 1]) {
newVisitedPoints.add(Point(it.row, it.column - 1))
visitedMap[it.row][it.column - 1] = true
}
}
}
steps++
visitedPoints = newVisitedPoints.toList()
}
return steps
}
private data class Point(val row: Int, val column: Int)
private fun Char.toElevation(): Int =
when (this) {
'S' -> 0
'E' -> 'z' - 'a'
else -> this - 'a'
}
| 0 |
Kotlin
| 0 | 0 |
923f08f3de3cdd7baae3cb19b5e9cf3e46745b51
| 3,469 |
advent-of-code-2022
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.