kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
iam-abbas__cs-algorithms__d04aa8f/Kotlin/merge_sort_in_kotlin.kt | fun merge(A: Array<Int>, p: Int, q: Int, r: Int) {
var left = A.copyOfRange(p, q + 1)
var right = A.copyOfRange(q + 1, r + 1)
var i = 0
var j = 0
for (k in p..r) {
if ((i <= left.size - 1) && ((j >= right.size) || (left[i] <= right[j]))) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
}
fun merge_sort(A: Array<Int>, p: Int, r: Int) {
if (p < r) {
var q = (p + r) / 2
merge_sort(A, p, q)
merge_sort(A, q + 1, r)
merge(A, p, q, r)
}
}
fun main(arg: Array<String>) {
print("Enter no. of elements :")
var n = readLine()!!.toInt()
println("Enter elements : ")
var A = Array(n, { 0 })
for (i in 0 until n)
A[i] = readLine()!!.toInt()
merge_sort(A, 0, A.size - 1)
println("Sorted array is : ")
for (i in 0 until n)
print("${A[i]} ")
}
| [
{
"class_path": "iam-abbas__cs-algorithms__d04aa8f/Merge_sort_in_kotlinKt.class",
"javap": "Compiled from \"merge_sort_in_kotlin.kt\"\npublic final class Merge_sort_in_kotlinKt {\n public static final void merge(java.lang.Integer[], int, int, int);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day02.kt | class Day02 {
fun part1(input: List<String>): Int {
return input.map { it.split(" ") }
.map { (opponentCode, myCode) -> HandShape.fromOpponentCode(opponentCode) to HandShape.fromElfCode(myCode) }
.sumOf { (opponentHandShape, myHandShape) -> HandScorer.score(opponentHandShape, myHandShape) }
}
fun part2(input: List<String>): Int {
return input.map { it.split(" ") }
.map { (opponentCode, command) -> HandShape.fromOpponentCode(opponentCode) to command }
.sumOf { (opponentHandShape, command) ->
HandScorer.score(
opponentHandShape,
HandShape.decodeHand(opponentHandShape, command)
)
}
}
object HandScorer {
fun score(opponentHand: HandShape, myHandShape: HandShape): Int {
return myHandShape.score + resultScore(opponentHand, myHandShape)
}
private fun resultScore(opponentHand: HandShape, myHandShape: HandShape): Int {
return when (opponentHand) {
myHandShape -> 3
HandShape.defeats[myHandShape] -> 6
else -> 0
}
}
}
enum class HandShape(val opponentCode: String, val elfCode: String, val score: Int) {
ROCK("A", "X", 1),
PAPER("B", "Y", 2),
SCISSORS("C", "Z", 3);
companion object {
val defeats = mapOf(
ROCK to SCISSORS,
PAPER to ROCK,
SCISSORS to PAPER
)
fun fromOpponentCode(code: String) = values().first { it.opponentCode == code }
fun fromElfCode(code: String) = values().first { it.elfCode == code }
fun decodeHand(opponentHand: HandShape, command: String): HandShape {
return when (command) {
"X" -> defeats[opponentHand]!!
"Y" -> opponentHand
"Z" -> defeats.entries.first { it.value == opponentHand }.key
else -> throw IllegalStateException()
}
}
}
}
} | [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day02$HandShape.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02$HandShape extends java.lang.Enum<Day02$HandShape> {\n public static final Day02$HandShape$Companion Companion;\n\n private final java.lang.String opponentCode;\n... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day15.kt | import kotlin.math.abs
class Day15 {
fun part1(input: List<String>, lookupRow: Int): Int {
val sensors = mapToSensors(input)
val minRange = sensors.minOf { sensor ->
minOf(
sensor.position.x,
sensor.beacon.x,
sensor.position.x - sensor.distanceToBeacon()
)
}
val maxRange = sensors.maxOf { sensor ->
maxOf(
sensor.position.x,
sensor.beacon.x,
sensor.position.x + sensor.distanceToBeacon()
)
}
return (minRange..maxRange).count { x ->
val point = Point(x, lookupRow)
sensors.any { sensor -> sensor.beacon != point && sensor.position.distance(point) <= sensor.distanceToBeacon() }
}
}
fun part2(input: List<String>, limit: Int): Long {
val sensors = mapToSensors(input)
val pointNotCovered = findPositionNotCoveredByBeacon(limit, sensors)
return pointNotCovered.x.toLong() * 4000000 + pointNotCovered.y.toLong()
}
private fun findPositionNotCoveredByBeacon(limit: Int, sensors: List<Sensor>): Point {
for (y in 0..limit) {
var point = Point(0, y)
while (point.x <= limit) {
val coveredBySensor = pointCoveredBySensor(sensors, point)
if (coveredBySensor == null) {
return point
} else {
val maxCovered = coveredBySensor.maxDistanceCovered(point.y)
point = Point(maxCovered.x + 1, maxCovered.y)
}
}
}
error("Should find one...")
}
private fun pointCoveredBySensor(sensors: List<Sensor>, point: Point): Sensor? {
return sensors.find { it.isInRange(point) }
}
private fun mapToSensors(input: List<String>) =
input.map { it.split(": closest beacon is at ") }
.map { (point1, point2) ->
Sensor(
point1.substringAfter("Sensor at ").mapToPoint(),
point2.mapToPoint()
)
}
data class Sensor(val position: Point, val beacon: Point) {
fun distanceToBeacon(): Int {
return position.distance(beacon)
}
fun isInRange(other: Point): Boolean {
return position.distance(other) <= position.distance(beacon)
}
fun maxDistanceCovered(row: Int): Point {
return Point(position.x + abs(distanceToBeacon() - abs(row - position.y)), row)
}
}
data class Point(val x: Int, val y: Int) {
fun distance(other: Point): Int {
return abs(other.x - x) + abs(other.y - y)
}
}
private fun String.mapToPoint(): Point {
val (x, y) = split(", ")
return Point(x.substringAfter("x=").toInt(), y.substringAfter("y=").toInt())
}
}
| [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day15.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15 {\n public Day15();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day09.kt | import kotlin.math.abs
class Day09 {
fun part1(input: List<String>): Int {
val movement = input.map { it.split(" ") }
.flatMap { (direction, step) -> (1..step.toInt()).map { direction.toDirection() } }
return simulateMoves(movement, 2).size
}
fun part2(input: List<String>): Int {
val movement = input.map { it.split(" ") }
.flatMap { (direction, step) -> (1..step.toInt()).map { direction.toDirection() } }
return simulateMoves(movement, 10).size
}
private fun simulateMoves(moves: List<Direction>, knotsNumber: Int): Set<Point> {
val knots = MutableList(knotsNumber) { Point(0, 0) }
val visitedTail = mutableSetOf<Point>()
visitedTail.add(knots.last())
moves.forEach { direction ->
knots[0] = knots[0].move(direction)
for ((headIndex, tailIndex) in knots.indices.zipWithNext()) {
val head = knots[headIndex]
val tail = knots[tailIndex]
if (!tail.isAdjacentTo(head)) {
knots[tailIndex] = tail.moveTowards(head)
}
}
visitedTail.add(knots.last())
}
return visitedTail
}
private fun Point.move(direction: Direction): Point {
return when (direction) {
Direction.UP -> Point(x, y + 1)
Direction.DOWN -> Point(x, y - 1)
Direction.LEFT -> Point(x - 1, y)
Direction.RIGHT -> Point(x + 1, y)
}
}
private fun Point.isAdjacentTo(other: Point): Boolean {
return abs(x - other.x) <= 1 && abs(y - other.y) <= 1
}
private fun Point.moveTowards(head: Point): Point {
return Point(
x + (head.x - x).coerceIn(-1..1),
y + (head.y - y).coerceIn(-1..1)
)
}
data class Point(val x: Int, val y: Int)
enum class Direction { UP, DOWN, LEFT, RIGHT }
private fun String.toDirection(): Direction {
return when (this) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> error("wrong direction $this")
}
}
}
| [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day09$WhenMappings.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class Day09$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method Day09$Direct... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day03.kt | class Day03 {
fun part1(input: List<String>): Int {
return input
.map { Rucksack(it) }
.flatMap { it.getCompartmentIntersection() }
.sumOf { it.toPriorityScore() }
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map { (elf1, elf2, elf3) -> Triple(Rucksack(elf1), Rucksack(elf2), Rucksack(elf3)) }
.map { it.first.getCompartmentIntersectionFrom(it.second, it.third).single() }
.sumOf { it.toPriorityScore() }
}
class Rucksack(private val content: String) {
fun getCompartmentIntersection(): Set<Char> {
val splitIndex = if (content.length % 2 == 0) content.length / 2 else content.length / 2 + 1
val first = content.take(splitIndex).toSet()
val second = content.substring(splitIndex).toSet()
return first.intersect(second)
}
fun getCompartmentIntersectionFrom(other: Rucksack, another: Rucksack): Set<Char> {
return content.toSet()
.intersect(other.content.toSet())
.intersect(another.content.toSet())
}
}
private fun Char.toPriorityScore(): Int {
return when {
// Lowercase item types a through z have priorities 1 through 26.
isLowerCase() -> this - 'a' + 1
// Uppercase item types A through Z have priorities 27 through 52.
isUpperCase() -> this - 'A' + 27
else -> error("Wrong input")
}
}
} | [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day03$Rucksack.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03$Rucksack {\n private final java.lang.String content;\n\n public Day03$Rucksack(java.lang.String);\n Code:\n 0: aload_1\n 1: ldc #9 ... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day05.kt | import kotlin.collections.HashMap
class Day05 {
fun part1(input: String): String {
return getTopCrates(input, CrateMoverModel.CrateMover9000)
}
fun part2(input: String): String {
return getTopCrates(input, CrateMoverModel.CrateMover9001)
}
private fun getTopCrates(input: String, modelType: CrateMoverModel): String {
val (cranes, instructions) = input.split("\n\n")
val cranesNumber = cranes.parseCranesNumber()
val boxes = cranes.lines().dropLast(1).flatMap { line -> line.mapToBoxes(cranesNumber) }
val craneOperator = CraneOperator(cranesNumber, modelType, boxes)
val craneInstructions = instructions.parseToCommands()
craneOperator.executeCommands(craneInstructions)
return craneOperator.getTopCrates()
}
private fun String.parseCranesNumber() = lines()
.last()
.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.count()
private fun String.parseToCommands() = lines().map {
val (p1, p2) = it.split(" from ")
val moveQuantity = p1.replace("move ", "").toInt()
val (from, to) = p2.split(" to ")
CraneCommand(moveQuantity, from.toInt(), to.toInt())
}
data class Box(val index: Int, val content: String)
data class CraneCommand(val quantity: Int, val from: Int, val to: Int)
enum class CrateMoverModel { CrateMover9000, CrateMover9001 }
private fun String.mapToBoxes(size: Int): List<Box> {
return (1..size)
.map { craneNumber -> Box(craneNumber, this.parseBoxFromCraneNumber(craneNumber)) }
.filter { it.content.isNotBlank() }
}
private fun String.parseBoxFromCraneNumber(n: Int): String {
val craneRow = n - 1
return substring(4 * craneRow + 1, 4 * craneRow + 2)
}
private class CraneOperator(numberOfCranes: Int, private val modelType: CrateMoverModel, boxes: List<Box>) {
private val boxStacks: HashMap<Int, ArrayDeque<String>> = HashMap()
init {
(1..numberOfCranes).forEach { boxStacks[it] = ArrayDeque() }
boxes.forEach { putBoxInCrane(it) }
}
private fun putBoxInCrane(box: Box) {
boxStacks[box.index]?.addFirst(box.content)
}
fun executeCommands(commands: List<CraneCommand>) {
commands.forEach { command ->
val toMove = (1..command.quantity).map { boxStacks[command.from]?.removeLast()!! }
when (modelType) {
CrateMoverModel.CrateMover9000 -> {
boxStacks[command.to]?.addAll(toMove)
}
CrateMoverModel.CrateMover9001 -> {
boxStacks[command.to]?.addAll(toMove.reversed())
}
}
}
}
fun getTopCrates(): String {
return boxStacks.values.joinToString(separator = "") { it.last() }
}
}
} | [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day05$CraneOperator$WhenMappings.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class Day05$CraneOperator$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 ... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day12.kt | import java.util.*
class Day12 {
fun part1(input: List<String>): Int {
val area = mapToArea(input)
return area.traverseFromStart()
}
fun part2(input: List<String>): Int {
return mapToArea(input).traverseFromEnd()
}
private fun mapToArea(input: List<String>): Area {
var finishPoint: Point? = null
var startingPoint: Point? = null
val field: Map<Point, Int> = input.flatMapIndexed { y, row ->
row.mapIndexed { x, heightCode ->
val point = Point(x, y)
val height = heightCode.decodeHeight()
when (heightCode) {
'E' -> point to height.also { finishPoint = point }
'S' -> point to height.also { startingPoint = point }
else -> point to height
}
}
}.toMap()
return Area(startingPoint!!, finishPoint!!, field)
}
private fun Char.decodeHeight(): Int {
return when (this) {
'S' -> 'a' - 'a'
'E' -> 'z' - 'a'
in 'a'..'z' -> this - 'a'
else -> error("Wrong level value $this")
}
}
data class Area(
val startingPoint: Point,
val destination: Point,
val field: Map<Point, Int>
) {
fun traverseFromStart(): Int {
val canMove: (Int, Int) -> Boolean = { nextPlace, currentPlace -> nextPlace - currentPlace <= 1 }
val isDestination: (Path) -> Boolean = { it.point == destination }
return traverse(canMove, isDestination, startingPoint)
}
fun traverseFromEnd(): Int {
val canMove: (Int, Int) -> Boolean = { nextPlace, currentPlace -> currentPlace - nextPlace <= 1 }
val isDestination: (Path) -> Boolean = { field[it.point] == 0 }
return traverse(canMove, isDestination, destination)
}
private fun traverse(
canMove: (Int, Int) -> Boolean,
isDestination: (Path) -> Boolean,
startingPoint: Point
): Int {
val toBeEvaluated = PriorityQueue<Path>().apply { add(Path(startingPoint, 0)) }
val visited = mutableSetOf<Point>()
while (toBeEvaluated.isNotEmpty()) {
val currentPlace = toBeEvaluated.poll()
if (isDestination(currentPlace)) {
return currentPlace.distanceSoFar
}
if (currentPlace.point !in visited) {
visited.add(currentPlace.point)
currentPlace.point
.neighbors()
.filter { nextPlace -> nextPlace in field }
.filter { nextPlace -> canMove(field.getValue(nextPlace), field.getValue(currentPlace.point)) }
.map { nextPlace -> Path(nextPlace, currentPlace.distanceSoFar + 1) }
.forEach { path -> toBeEvaluated.offer(path) }
}
}
error("No path found to destination")
}
}
data class Path(val point: Point, val distanceSoFar: Int) : Comparable<Path> {
override fun compareTo(other: Path): Int {
return distanceSoFar - other.distanceSoFar
}
}
data class Point(val x: Int, val y: Int) {
fun neighbors(): List<Point> {
return listOf(
Point(x, y + 1),
Point(x, y - 1),
Point(x + 1, y),
Point(x - 1, y)
)
}
}
}
| [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day12$Area.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class Day12$Area {\n private final Day12$Point startingPoint;\n\n private final Day12$Point destination;\n\n private final java.util.Map<Day12$Point, java.lang.Integer> field;\n... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day13.kt | class Day13 {
fun part1(input: String): Int {
return input.split("\n\n").map { it.lines() }
.map { (packet, other) -> packet.mapToPacketData() to other.mapToPacketData() }
.mapIndexed { index, pair -> if (pair.first.compareTo(pair.second) < 1) index + 1 else 0 }
.sum()
}
fun part2(input: String): Int {
val packets = input.split("\n\n").map { it.lines() }
.flatMap { (packet, other) -> listOf(packet.mapToPacketData(), other.mapToPacketData()) }
val dividerPacket2 = "[[6]]".mapToPacketData()
val dividerPacket1 = "[[2]]".mapToPacketData()
val ordered = (packets + dividerPacket1 + dividerPacket2).sorted()
return (ordered.indexOf(dividerPacket1) + 1) * (ordered.indexOf(dividerPacket2) + 1)
}
private fun String.mapToPacketData(): PacketData {
val bracketsAndNumbers = split(Regex("((?<=[\\[\\],])|(?=[\\[\\],]))"))
.filter { it.isNotBlank() }
.filter { it != "," }
.iterator()
return mapIteratorToPacketData(bracketsAndNumbers)
}
private fun mapIteratorToPacketData(input: Iterator<String>): PacketData {
val packets = mutableListOf<PacketData>()
while (input.hasNext()) {
when (val symbol = input.next()) {
"]" -> return ListPacketData(packets)
"[" -> packets.add(mapIteratorToPacketData(input))
else -> packets.add(IntPacketData(symbol.toInt()))
}
}
return ListPacketData(packets)
}
sealed class PacketData : Comparable<PacketData>
data class IntPacketData(val data: Int) : PacketData() {
override fun compareTo(other: PacketData): Int {
return when (other) {
is IntPacketData -> data.compareTo(other.data)
is ListPacketData -> ListPacketData(listOf(this)).compareTo(other)
}
}
}
data class ListPacketData(val data: List<PacketData>) : PacketData() {
override fun compareTo(other: PacketData): Int {
return when (other) {
is IntPacketData -> compareTo(ListPacketData(listOf(other)))
is ListPacketData -> data.zip(other.data)
.map { (packet1, packet2) -> packet1.compareTo(packet2) }
.firstOrNull { it != 0 } ?: data.size.compareTo(other.data.size)
}
}
}
}
| [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day13.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13 {\n public Day13();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day14.kt | class Day14 {
fun part1(input: List<String>): Int {
val rocks = mapToRocks(input)
return Cave(rocks).dropSand()
}
fun part2(input: List<String>): Int {
val rocks = mapToRocks(input)
return Cave(rocks, true).dropSandWithFloor()
}
private fun mapToRocks(input: List<String>) = input.flatMap {
it.split(" -> ")
.windowed(2)
.flatMap { (line1, line2) -> mapToPoints(line1, line2) }
}.toSet()
private fun mapToPoints(line1: String, line2: String): List<Point> {
val (p1x, p1y) = line1.split(",").map { it.toInt() }
val (p2x, p2y) = line2.split(",").map { it.toInt() }
val xRange = if (p1x <= p2x) p1x..p2x else p2x..p1x
val yRange = if (p1y <= p2y) p1y..p2y else p2y..p1y
return (xRange).flatMap { x -> (yRange).map { y -> Point(x, y) } }
}
data class Point(val x: Int, val y: Int) {
fun possibleMovesDown(): List<Point> {
return listOf(
Point(x, y + 1),
Point(x - 1, y + 1),
Point(x + 1, y + 1)
)
}
}
class Cave(rocks: Set<Point>, withFloor: Boolean = false) {
private val sandPoint = Point(500, 0)
private val rocksAndFloor = mutableSetOf<Point>()
private val sand = mutableSetOf<Point>()
private var lowestRock = 0
init {
rocksAndFloor.addAll(rocks)
lowestRock = if (withFloor) {
val floorLevel = rocks.map { it.y }.max() + 2
val floor = createFloor(rocks, floorLevel)
rocksAndFloor.addAll(floor)
floorLevel
} else {
rocks.map { it.y }.max()
}
}
private fun createFloor(rocks: Set<Point>, floorLevel: Int): List<Point> {
val offset = rocks.map { it.y }.max()
val minX = rocks.map { it.x }.min() - offset
val maxX = rocks.map { it.x }.max() + offset
return (minX..maxX).map { Point(it, floorLevel) }
}
fun dropSand(): Int {
var nextSpot = findLandingPlace(sandPoint)
while (nextSpot != null && nextSpot != sandPoint) {
sand.add(nextSpot)
nextSpot = findLandingPlace(sandPoint)
}
draw()
return sand.size
}
fun dropSandWithFloor(): Int {
return dropSand() + 1
}
private fun findLandingPlace(current: Point): Point? {
if (current.y > lowestRock) return null
val nextPoint = current.possibleMovesDown().firstOrNull { it !in rocksAndFloor && it !in sand }
return when (nextPoint) {
null -> current
else -> findLandingPlace(nextPoint)
}
}
private fun draw() {
val all = mutableListOf<Point>().apply {
addAll(rocksAndFloor)
addAll(sand)
}
val minX = all.map { it.x }.min()
val maxX = all.map { it.x }.max()
val maxY = all.map { it.y }.max()
for (y in 0..maxY) {
for (x in minX..maxX) {
when (Point(x, y)) {
Point(500, 0) -> print('+')
in rocksAndFloor -> print('#')
in sand -> print('o')
else -> print('.')
}
if (x == maxX) {
println()
}
}
}
}
}
}
| [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day14$Cave.class",
"javap": "Compiled from \"Day14.kt\"\npublic final class Day14$Cave {\n private final Day14$Point sandPoint;\n\n private final java.util.Set<Day14$Point> rocksAndFloor;\n\n private final java.util.Set<Day14$Point> sand;\n\n pri... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day08.kt | class Day08 {
fun part1(input: List<String>): Int {
return TreeArea(input).getVisibleTrees()
}
fun part2(input: List<String>): Int {
return TreeArea(input).getBestScore()
}
class TreeArea(input: List<String>) {
private val trees: Array<Array<Tree>>
private val size: Int
init {
val arr: Array<Array<Tree>> = parseTreeArea(input)
this.trees = arr
this.size = trees.size - 1
}
private fun parseTreeArea(input: List<String>): Array<Array<Tree>> {
return input.mapIndexed { rowId, row ->
row.mapIndexed { columnId, height ->
Tree(columnId, rowId, height.digitToInt())
}.toTypedArray()
}.toTypedArray()
}
fun getVisibleTrees(): Int {
return trees.flatMap { row -> row.map { isTreeVisible(it) } }.count { it }
}
fun getBestScore(): Int {
return trees.flatMap { row -> row.map { getTreeScore(it) } }.max()
}
private fun isTreeVisible(tree: Tree): Boolean = isVisibleVertically(tree) || isVisibleHorizontally(tree)
private fun isVisibleVertically(tree: Tree): Boolean {
return if (tree.rowId == 0 || tree.rowId == size) {
true
} else {
val visibleTop = (tree.rowId - 1 downTo 0).all { tree.height > trees[it][tree.columnId].height }
val visibleBottom = (tree.rowId + 1..size).all { tree.height > trees[it][tree.columnId].height }
visibleTop || visibleBottom
}
}
private fun isVisibleHorizontally(tree: Tree): Boolean {
return if (tree.columnId == 0 || tree.columnId == size) {
true
} else {
val visibleLeft = (tree.columnId - 1 downTo 0).all { tree.height > trees[tree.rowId][it].height }
val visibleRight = (tree.columnId + 1..size).all { tree.height > trees[tree.rowId][it].height }
visibleLeft || visibleRight
}
}
private fun getTreeScore(tree: Tree): Int = getScoreVertically(tree) * getScoreHorizontally(tree)
private fun getScoreVertically(tree: Tree): Int {
return if (tree.rowId == 0 || tree.rowId == size) {
1
} else {
val scoreTop = (tree.rowId - 1 downTo 0)
.map { trees[it][tree.columnId] }
.takeUntil { it.height >= tree.height }.count()
val scoreBottom = (tree.rowId + 1..size)
.map { trees[it][tree.columnId] }
.takeUntil { it.height >= tree.height }.count()
scoreTop * scoreBottom
}
}
private fun getScoreHorizontally(tree: Tree): Int {
return if (tree.columnId == 0 || tree.columnId == size) {
1
} else {
val scoreLeft = (tree.columnId - 1 downTo 0)
.map { trees[tree.rowId][it] }
.takeUntil { it.height >= tree.height }.count()
val scoreRight = (tree.columnId + 1..size)
.map { trees[tree.rowId][it] }
.takeUntil { it.height >= tree.height }.count()
scoreLeft * scoreRight
}
}
}
data class Tree(val columnId: Int, val rowId: Int, val height: Int)
}
private fun <T> Iterable<T>.takeUntil(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
list.add(item)
if (predicate(item))
break
}
return list
}
| [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day08.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class Day08 {\n public Day08();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day07.kt | class Day07 {
fun part1(input: List<String>): Long {
val hashMapOf = directoriesMap(input)
return hashMapOf.values.filter { it <= 100_000 }.sum()
}
private fun directoriesMap(input: List<String>): MutableMap<String, Long> {
val hashMapOf = mutableMapOf<String, Long>()
var path = ""
for (line in input) {
when (line.getTyp()) {
CommandType.COMMAND_CD_ROOT -> path = ""
CommandType.COMMAND_CD_UP -> {
path = path.substringBeforeLast("/")
}
CommandType.COMMAND_CD -> {
val tempPath = line.substringAfter("$ cd ")
path = "$path/$tempPath"
}
CommandType.COMMAND_DIR -> ""
CommandType.DIR -> ""
CommandType.SIZE -> {
val tempSize = line.substringBefore(" ").toInt()
var tempDir = path
while (true) {
val previous = hashMapOf.getOrDefault(tempDir, 0)
hashMapOf[tempDir] = previous + tempSize
if (tempDir.isEmpty()) break
tempDir = tempDir.substringBeforeLast("/", "")
}
}
}
}
return hashMapOf
}
private enum class CommandType { COMMAND_CD_ROOT, COMMAND_CD, COMMAND_CD_UP, COMMAND_DIR, DIR, SIZE }
private fun String.getTyp(): CommandType {
return when {
this.startsWith("$ cd /") -> CommandType.COMMAND_CD_ROOT
this.startsWith("$ cd ..") -> CommandType.COMMAND_CD_UP
this.startsWith("$ cd ") -> CommandType.COMMAND_CD
this.startsWith("$ ls") -> CommandType.COMMAND_DIR
this.startsWith("dir ") -> CommandType.DIR
else -> CommandType.SIZE
}
}
fun part2(input: List<String>): Long {
val total = 70_000_000
val required = 30_000_000
val directoriesMap = directoriesMap(input)
val used = directoriesMap.getOrDefault("", 0)
val unusedSpace = total - used
val deficit = required - unusedSpace
return directoriesMap.values.filter { it >= deficit }.min()
}
}
| [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day07$WhenMappings.class",
"javap": "Compiled from \"Day07.kt\"\npublic final class Day07$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method Day07$Comman... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day11.kt | class Day11 {
fun part1(input: String): Long {
val monkeys = input.split("\n\n").map { it.toMonkey() }.toTypedArray()
val rounds = 20
val stressReducerFormula: (Long) -> Long = { it / 3 }
repeat(rounds) { round ->
monkeys.forEach {
it.handleItems(stressReducerFormula).forEach {
(item, monkey) -> monkeys[monkey].passItem(item)
}
}
}
return monkeys.map { it.handledItemsCount }.sortedDescending().take(2).reduce { acc, i -> acc * i }
}
fun part2(input: String): Long {
val monkeys = input.split("\n\n").map { it.toMonkey() }.toTypedArray()
val rounds = 10000
val lcm = monkeys.map { it.divisor.toLong() }.reduce(Long::times)
val stressReducerFormula: (Long) -> Long = { it % lcm }
repeat(rounds) {
monkeys.forEach {
it.handleItems(stressReducerFormula).forEach { (itemToPass, monkeyNumber) ->
monkeys[monkeyNumber].passItem(itemToPass)
}
}
}
val map = monkeys.map { it.handledItemsCount }
return map.sortedDescending().take(2).reduce { acc, i -> acc * i }
}
data class Monkey(
private val items: MutableList<Long>,
private val newStressLevelFormula: (Long) -> Long,
val divisor: Int,
private val passToOnSuccess: Int,
private val passToOnFailure: Int,
var handledItemsCount: Long = 0L
) {
fun handleItems(stressReducerFormula: (Long) -> Long): List<Pair<Long, Int>> {
val handledItems = items.map {
handledItemsCount++
handleItem(it, stressReducerFormula)
}
items.clear()
return handledItems
}
private fun handleItem(item: Long, stressReducerFormula: (Long) -> Long): Pair<Long, Int> {
val newStressLevel = newStressLevelFormula(item)
val levelAfterBoredMonkey = stressReducerFormula(newStressLevel)
return levelAfterBoredMonkey to if (levelAfterBoredMonkey % divisor == 0L) passToOnSuccess else passToOnFailure
}
fun passItem(item: Long) {
items.add(item)
}
}
private fun String.toMonkey(): Monkey {
val lines = split("\n")
val monkeyNumber = lines[0].toMonkeyNumber()
val items = lines[1].toItems()
val operation = lines[2].mapToOperation()
val divisor = lines[3].toDivisor()
val passToOnSuccess = lines[4].toSuccessMonkey()
val passToOnFailure = lines[5].toFailureMonkey()
return Monkey(items, operation, divisor, passToOnSuccess, passToOnFailure)
}
private fun String.toMonkeyNumber() = substringAfter("Monkey ").dropLast(1).toInt()
private fun String.toItems() = trim()
.substringAfter("Starting items: ")
.split(", ")
.map { it.toLong() }
.toMutableList()
private fun String.toDivisor() = trim().substringAfter("Test: divisible by ").toInt()
private fun String.toSuccessMonkey() = trim().substringAfter("If true: throw to monkey ").toInt()
private fun String.toFailureMonkey() = trim().substringAfter("If false: throw to monkey ").toInt()
private fun String.mapToOperation(): (Long) -> Long {
val (sign, value) = trim().substringAfter("Operation: new = old ").split(" ")
return when (sign) {
"*" -> { old -> old * if (value == "old") old else value.toLong() }
"+" -> { old -> old + if (value == "old") old else value.toLong() }
else -> error("wrong operation $this")
}
}
}
| [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day11.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class Day11 {\n public Day11();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day10.kt | import java.lang.StringBuilder
class Day10 {
fun part1(input: List<String>): Int {
val cyclesToCheck = (20..220 step 40).toList()
var result = 0
val instructions = listOf(1) + input.flatMap { it.toOperation() }
instructions.reduceIndexed { cycle, acc, instruction ->
if (cycle in cyclesToCheck) {
result += cycle * acc
}
acc + instruction
}
return result
}
fun part2(input: List<String>): String {
val crtCyclesToCheck = (40..220 step 40).toList()
var spritePosition = 0
val instructions = listOf(1) + input.flatMap { it.toOperation() }
val crtScreen = StringBuilder()
instructions.reduceIndexed { cycle, acc, instruction ->
crtScreen.append(if ((cycle - 1) % 40 in spritePosition - 1 .. spritePosition + 1) '#' else '.')
if (cycle in crtCyclesToCheck) {
crtScreen.appendLine()
}
spritePosition = acc + instruction
acc + instruction
}
val screen = crtScreen.toString()
println("====== Result ======")
println(screen)
println("====================")
return screen
}
private fun String.toOperation(): List<Int> {
return when {
this == "noop" -> listOf(0)
this.startsWith("addx") -> listOf(0, this.substringAfter("addx ").toInt())
else -> error("wrong operation $this")
}
}
}
| [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day10.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class Day10 {\n public Day10();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final... |
dliszewski__advent-of-code-2022__76d5eea/src/main/kotlin/Day04.kt | class Day04 {
fun part1(input: List<String>): Int {
return input
.map { it.toRanges() }
.count { (range1, range2) -> range1 includeRange range2 }
}
fun part2(input: List<String>): Int {
return input
.map { it.toRanges() }
.count { (range1, range2) -> range1 overlapRange range2 }
}
private fun String.toRanges(): Pair<IntRange, IntRange> {
val (range1, range2) = split(",")
return Pair(range1.toRange(), range2.toRange())
}
private infix fun IntRange.includeRange(other: IntRange): Boolean {
return (first <= other.first && last >= other.last)
|| (other.first <= first && other.last >= last)
}
private infix fun IntRange.overlapRange(other: IntRange): Boolean {
return (first <= other.last && other.first <= last)
|| (first <= other.last && other.first <= last)
}
private fun String.toRange(): IntRange {
val (from, to) = split("-")
return from.toInt()..to.toInt()
}
} | [
{
"class_path": "dliszewski__advent-of-code-2022__76d5eea/Day04.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04 {\n public Day04();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final... |
kipwoker__aoc2022__d8aeea8/src/Utils.kt | import java.io.File
import kotlin.math.max
import kotlin.math.min
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
fun <T> assert(actual: T, expected: T) {
if (actual == expected) {
return
}
throw Exception("Actual $actual Expected $expected")
}
data class Interval(val start: Int, val end: Int) {
companion object {
fun merge(intervals: List<Interval>): List<Interval> {
var sorted = intervals.sortedBy { i -> i.start }
var hasOverlap = true
while (hasOverlap && sorted.size > 1) {
hasOverlap = false
val bucket = sorted.toMutableList<Interval?>()
var i = 0
while (i < bucket.size - 1) {
if (bucket[i] != null && bucket[i + 1] != null && bucket[i]!!.hasOverlap(bucket[i + 1]!!)) {
hasOverlap = true
val merged = bucket[i]!!.merge(bucket[i + 1]!!)
bucket[i] = null
bucket[i + 1] = merged
}
i += 1
}
sorted = bucket.filterNotNull()
}
return sorted
}
}
fun hasFullOverlap(other: Interval): Boolean {
return hasFullOverlap(this, other) || hasFullOverlap(other, this)
}
fun hasOverlap(other: Interval): Boolean {
return hasOverlap(this, other) || hasOverlap(other, this)
}
fun merge(other: Interval): Interval {
return Interval(min(this.start, other.start), max(this.end, other.end))
}
private fun hasFullOverlap(x: Interval, y: Interval): Boolean {
return x.start >= y.start && x.end <= y.end
}
private fun hasOverlap(x: Interval, y: Interval): Boolean {
return x.start >= y.start && x.start <= y.end
}
fun countPoints(excludePoints: Set<Int>? = null): Int {
var count = end - start + 1
if (excludePoints == null) {
return count
}
for (p in excludePoints) {
if (p in start..end) {
--count
}
}
return count
}
fun minStart(x: Int): Interval {
if (x < start) {
return Interval(x, end)
}
return this
}
fun maxEnd(x: Int): Interval {
if (x > end) {
return Interval(start, x)
}
return this
}
fun isInside(t: Int): Boolean {
return t in start..end
}
}
data class Point(val x: Int, val y: Int) {
fun sum(other: Point): Point {
return Point(this.x + other.x, this.y + other.y)
}
}
enum class Direction {
Up,
Down,
Left,
Right
}
object DirectionManager {
private val directions = arrayOf(Direction.Up, Direction.Right, Direction.Down, Direction.Left)
fun turn(current: Direction, target: Direction): Direction {
if (target == Direction.Down || target == Direction.Up) {
throw RuntimeException("Illegal action $current -> $target")
}
val d = if (target == Direction.Left) -1 else 1
val index = (directions.indexOf(current) + d + directions.size) % directions.size
return directions[index]
}
}
enum class Sign {
Eq,
Less,
More
}
enum class ExecutionMode {
Test1,
Test2,
Exec1,
Exec2
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/UtilsKt.class",
"javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String name\n ... |
kipwoker__aoc2022__d8aeea8/src/Day14.kt | import kotlin.math.max
import kotlin.math.min
enum class CaveCell {
Air,
Rock,
Sand
}
enum class SandFallResult {
Stuck,
Fall
}
val caveSize = 1000
fun main() {
class Cave(val map: Array<Array<CaveCell>>) {
fun getBounds(): Pair<Point, Point> {
var minX = caveSize
var minY = caveSize
var maxX = 0
var maxY = 0
for (y in 0 until caveSize) {
for (x in 0 until caveSize) {
if (map[x][y] != CaveCell.Air) {
minX = min(minX, x)
minY = min(minY, y)
maxX = max(maxX, x)
maxY = max(maxY, y)
}
}
}
return Point(minX, minY) to Point(maxX, maxY)
}
}
fun parse(input: List<String>): Cave {
val cave = Cave(Array(caveSize) { _ -> Array(caveSize) { _ -> CaveCell.Air } })
val pointBlocks = input.map { line ->
line
.split('-')
.map { pair ->
val parts = pair.split(',')
Point(parts[0].toInt(), parts[1].toInt())
}
}
for (pointBlock in pointBlocks) {
for (i in 0..pointBlock.size - 2) {
val left = pointBlock[i]
val right = pointBlock[i + 1]
if (left.x != right.x && left.y != right.y) {
println("Unexpected $left -> $right")
throw RuntimeException()
}
if (left.x == right.x) {
val x = left.x
for (dy in min(left.y, right.y)..max(left.y, right.y)) {
cave.map[x][dy] = CaveCell.Rock
}
}
if (left.y == right.y) {
val y = left.y
for (dx in min(left.x, right.x)..max(left.x, right.x)) {
cave.map[dx][y] = CaveCell.Rock
}
}
}
}
return cave
}
fun print(cave: Cave) {
val window = 0
val (minPoint, maxPoint) = cave.getBounds()
for (y in (minPoint.y - window)..(maxPoint.y + window)) {
for (x in (minPoint.x - window)..(maxPoint.x + window)) {
val sign = when (cave.map[x][y]) {
CaveCell.Air -> '.'
CaveCell.Rock -> '#'
CaveCell.Sand -> 'o'
}
print(sign)
}
println()
}
}
fun playSand(cave: Cave): SandFallResult {
val (_, maxPoint) = cave.getBounds()
var sx = 500
var sy = 0
while (sy < maxPoint.y) {
if (cave.map[sx][sy + 1] == CaveCell.Air) {
++sy
} else if (cave.map[sx - 1][sy + 1] == CaveCell.Air) {
--sx
++sy
} else if (cave.map[sx + 1][sy + 1] == CaveCell.Air) {
++sx
++sy
} else {
cave.map[sx][sy] = CaveCell.Sand
return SandFallResult.Stuck
}
}
return SandFallResult.Fall
}
fun play1(cave: Cave): Int {
var counter = 0
while (playSand(cave) != SandFallResult.Fall) {
// print(cave)
++counter
}
return counter
}
fun play2(cave: Cave): Int {
val (_, maxPoint) = cave.getBounds()
for (x in 0 until caveSize) {
cave.map[x][maxPoint.y + 2] = CaveCell.Rock
}
var counter = 0
while (playSand(cave) != SandFallResult.Fall && cave.map[500][0] != CaveCell.Sand) {
++counter
}
return counter + 1
}
fun part1(input: List<String>): Int {
val cave = parse(input)
return play1(cave)
}
fun part2(input: List<String>): Int {
val cave = parse(input)
return play2(cave)
}
val testInput = readInput("Day14_test")
assert(part1(testInput), 24)
assert(part2(testInput), 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day14Kt.class",
"javap": "Compiled from \"Day14.kt\"\npublic final class Day14Kt {\n private static final int caveSize;\n\n public static final int getCaveSize();\n Code:\n 0: getstatic #10 // Field caveSize:I\n 3: ireturn\n\n ... |
kipwoker__aoc2022__d8aeea8/src/Day04.kt |
fun main() {
fun parse(lines: List<String>): List<Pair<Interval, Interval>> {
return lines.map { line ->
val intervals = line
.split(',')
.map { range ->
val rangeParts = range.split('-')
Interval(rangeParts[0].toInt(), rangeParts[1].toInt())
}
intervals[0]to intervals[1]
}
}
fun part1(input: List<String>): Int {
return parse(input)
.filter { (left, right) -> left.hasFullOverlap(right) }
.size
}
fun part2(input: List<String>): Int {
return parse(input)
.filter { (left, right) -> left.hasOverlap(right) }
.size
}
val testInput = readInput("Day04_test")
assert(part1(testInput), 2)
assert(part2(testInput), 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day04_test\n 2: invokestatic #14 // Method UtilsKt.readI... |
kipwoker__aoc2022__d8aeea8/src/Day18.kt |
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
class Day18 {
data class Point(val xs: Array<Int>) {
fun isBetween(minPoint: Point, maxPoint: Point): Boolean {
return xs
.zip(minPoint.xs)
.zip(maxPoint.xs)
.all { p ->
val x = p.first.first
val min = p.first.second
val max = p.second
x in min..max
}
}
fun add(index: Int, value: Int): Point {
val new = xs.copyOf()
new[index] += value
return Point(new)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Point
if (!xs.contentEquals(other.xs)) return false
return true
}
override fun hashCode(): Int {
return xs.contentHashCode()
}
}
fun parse(input: List<String>): Set<Point> {
return input.map { line ->
val xs = line.split(',').map { it.toInt() }.toTypedArray()
Point(xs)
}.toSet()
}
fun getNeighbors(point: Point): Set<Point> {
val range = listOf(-1, 1)
return point.xs.flatMapIndexed { index, _ -> range.map { dx -> point.add(index, dx) } }.toSet()
}
fun part1(input: List<String>): String {
val points = parse(input)
var result = 0L
for (point in points) {
var coverage = 6
val neighbors = getNeighbors(point)
coverage -= neighbors.count { points.contains(it) }
result += coverage
}
return result.toString()
}
fun part2(input: List<String>): String {
val points = parse(input)
var result = 0L
val dimension = points.first().xs.size
val max = (0 until dimension).map { d -> points.maxOf { p -> p.xs[d] } }
val min = (0 until dimension).map { d -> points.minOf { p -> p.xs[d] } }
val maxPoint = Point(max.map { it + 1 }.toTypedArray())
val minPoint = Point(min.map { it - 1 }.toTypedArray())
val visited = mutableSetOf<Point>()
val q = ArrayDeque(listOf(minPoint))
while (q.isNotEmpty()) {
val point = q.removeFirst()
val neighbors = getNeighbors(point).filter { n -> n.isBetween(minPoint, maxPoint) }
for (neighbor in neighbors) {
if (neighbor in points) {
++result
} else if (neighbor !in visited) {
visited.add(neighbor)
q.addLast(neighbor)
}
}
}
return result.toString()
}
}
@OptIn(ExperimentalTime::class)
@Suppress("DuplicatedCode")
fun main() {
val solution = Day18()
val name = solution.javaClass.name
fun test() {
val expected1 = "64"
val expected2 = "58"
val testInput = readInput("${name}_test")
println("Test part 1")
assert(solution.part1(testInput), expected1)
println("> Passed")
println("Test part 2")
assert(solution.part2(testInput), expected2)
println("> Passed")
println()
println("=================================")
println()
}
fun run() {
val input = readInput(name)
val elapsed1 = measureTime {
println("Part 1: " + solution.part1(input))
}
println("Elapsed: $elapsed1")
println()
val elapsed2 = measureTime {
println("Part 2: " + solution.part2(input))
}
println("Elapsed: $elapsed2")
println()
}
test()
run()
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day18$Point.class",
"javap": "Compiled from \"Day18.kt\"\npublic final class Day18$Point {\n private final java.lang.Integer[] xs;\n\n public Day18$Point(java.lang.Integer[]);\n Code:\n 0: aload_1\n 1: ldc #9 // String x... |
kipwoker__aoc2022__d8aeea8/src/Day24.kt | import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
class Day24 {
data class Valley(val blizzards: Map<Point, List<Direction>>, val maxY: Int, val maxX: Int)
data class Moment(val expedition: Point, val minutesSpent: Int)
fun parse(input: List<String>): Valley {
val blizzards = mutableMapOf<Point, List<Direction>>()
val walls = mutableSetOf<Point>()
for ((y, line) in input.withIndex()) {
for ((x, cell) in line.withIndex()) {
when (cell) {
'#' -> walls.add(Point(x, y))
'>' -> blizzards[Point(x, y)] = listOf(Direction.Right)
'<' -> blizzards[Point(x, y)] = listOf(Direction.Left)
'^' -> blizzards[Point(x, y)] = listOf(Direction.Up)
'v' -> blizzards[Point(x, y)] = listOf(Direction.Down)
}
}
}
return Valley(blizzards, input.size - 1, input[0].length - 1)
}
fun nextPosition(direction: Direction, position: Point, valley: Valley): Point {
val d = when (direction) {
Direction.Up -> Point(0, -1)
Direction.Down -> Point(0, 1)
Direction.Left -> Point(-1, 0)
Direction.Right -> Point(1, 0)
}
val newPosition = position.sum(d)
if (newPosition.x <= 0) {
return Point(valley.maxX - 1, newPosition.y)
}
if (newPosition.x >= valley.maxX) {
return Point(1, newPosition.y)
}
if (newPosition.y <= 0) {
return Point(newPosition.x, valley.maxY - 1)
}
if (newPosition.y >= valley.maxY) {
return Point(newPosition.x, 1)
}
return newPosition
}
fun print(valley: Valley) {
for (y in 0..valley.maxY) {
for (x in 0..valley.maxX) {
val point = Point(x, y)
if (x == 0 || x == valley.maxX || y == 0 || y == valley.maxY) {
print('#')
} else if (point !in valley.blizzards.keys) {
print('.')
} else {
val directions = valley.blizzards[point]!!
if (directions.size == 1) {
when (directions.first()) {
Direction.Up -> print('^')
Direction.Down -> print('v')
Direction.Left -> print('<')
Direction.Right -> print('>')
}
} else {
print(directions.size)
}
}
}
println()
}
println()
}
fun next(valley: Valley): Valley {
val blizzards = valley.blizzards.flatMap { blizzard ->
blizzard.value.map { direction -> nextPosition(direction, blizzard.key, valley) to direction }
}.groupBy({ x -> x.first }, { x -> x.second })
val newValley = Valley(blizzards, valley.maxY, valley.maxX)
return newValley
}
fun getAvailableMoves(current: Point, start: Point, target: Point, valley: Valley): Set<Point> {
return listOf(
Point(0, 0), // wait
Point(0, -1),
Point(0, 1),
Point(-1, 0),
Point(1, 0)
)
.map { p -> p.sum(current) }
.filter { p ->
(p.x > 0 && p.x < valley.maxX && p.y > 0 && p.y < valley.maxY) ||
p == target || p == start
}
.filter { p -> !valley.blizzards.containsKey(p) }
.toSet()
}
fun search(start: Point, target: Point, initValleyState: Valley): Pair<Int, Valley> {
val valleyStates = mutableListOf(initValleyState)
print(initValleyState)
val q = ArrayDeque<Moment>()
val visited = mutableSetOf<Moment>()
val initMoment = Moment(start, 0)
q.addLast(initMoment)
visited.add(initMoment)
while (q.isNotEmpty()) {
val moment = q.removeFirst()
val nextMinute = moment.minutesSpent + 1
val nextValleyState = if (valleyStates.size > nextMinute) {
valleyStates[nextMinute]
} else {
valleyStates.add(next(valleyStates.last()))
valleyStates.last()
}
val availableMoves = getAvailableMoves(moment.expedition, start, target, nextValleyState)
if (target in availableMoves) {
return nextMinute to nextValleyState
}
for (move in availableMoves) {
val nextMoment = Moment(move, nextMinute)
if (nextMoment !in visited) {
visited.add(nextMoment)
q.addLast(nextMoment)
}
}
}
return -1 to initValleyState
}
fun part1(input: List<String>): String {
val valley = parse(input)
val start = Point(1, 0)
val target = Point(valley.maxX - 1, valley.maxY)
val count = search(start, target, valley).first
return count.toString()
}
fun part2(input: List<String>): String {
val valley = parse(input)
val start = Point(1, 0)
val target = Point(valley.maxX - 1, valley.maxY)
val forward = search(start, target, valley)
val r1 = forward.first
println("R1 $r1")
val reward = search(target, start, forward.second)
val r2 = reward.first
println("R2 $r2")
val again = search(start, target, reward.second)
val r3 = again.first
println("R3 $r3")
return (r1 + r2 + r3).toString()
}
}
@OptIn(ExperimentalTime::class)
@Suppress("DuplicatedCode")
fun main() {
val solution = Day24()
val name = solution.javaClass.name
val execution = setOf(
ExecutionMode.Test1,
ExecutionMode.Test2,
ExecutionMode.Exec1,
ExecutionMode.Exec2
)
fun test() {
val expected1 = "18"
val expected2 = "54"
val testInput = readInput("${name}_test")
if (execution.contains(ExecutionMode.Test1)) {
println("Test part 1")
assert(solution.part1(testInput), expected1)
println("> Passed")
}
if (execution.contains(ExecutionMode.Test2)) {
println("Test part 2")
assert(solution.part2(testInput), expected2)
println("> Passed")
println()
}
println("=================================")
println()
}
fun run() {
val input = readInput(name)
if (execution.contains(ExecutionMode.Exec1)) {
val elapsed1 = measureTime {
println("Part 1: " + solution.part1(input))
}
println("Elapsed: $elapsed1")
println()
}
if (execution.contains(ExecutionMode.Exec2)) {
val elapsed2 = measureTime {
println("Part 2: " + solution.part2(input))
}
println("Elapsed: $elapsed2")
println()
}
}
test()
run()
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day24$WhenMappings.class",
"javap": "Compiled from \"Day24.kt\"\npublic final class Day24$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method Direction.values:()[LDirec... |
kipwoker__aoc2022__d8aeea8/src/Day23.kt | import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
class Day23 {
fun parse(input: List<String>): Set<Point> {
return input.flatMapIndexed { y, line ->
line.mapIndexed { x, c ->
if (c == '#') {
Point(x, y)
} else {
null
}
}
}.filterNotNull().toSet()
}
private val directions = arrayOf(Direction.Up, Direction.Down, Direction.Left, Direction.Right)
fun getNext(direction: Direction): Direction {
val index = (directions.indexOf(direction) + 1 + directions.size) % directions.size
return directions[index]
}
fun getNeighbors(point: Point): List<Point> {
return (-1..1)
.flatMap { x ->
(-1..1)
.map { y -> Point(point.x + x, point.y + y) }
}
.filter { p -> p != point }
}
fun canMove(point: Point, neighbors: List<Point>, direction: Direction): Point? {
return when (direction) {
Direction.Up -> if (neighbors.none { p -> p.y == point.y - 1 }) Point(point.x, point.y - 1) else null
Direction.Down -> if (neighbors.none { p -> p.y == point.y + 1 }) Point(point.x, point.y + 1) else null
Direction.Left -> if (neighbors.none { p -> p.x == point.x - 1 }) Point(point.x - 1, point.y) else null
Direction.Right -> if (neighbors.none { p -> p.x == point.x + 1 }) Point(point.x + 1, point.y) else null
}
}
fun move(points: Set<Point>, direction: Direction): Set<Point> {
val proposals = mutableMapOf<Point, Point>()
for (point in points) {
val neighbors = getNeighbors(point).filter { it in points }
if (neighbors.isEmpty()) {
continue
}
var cursor = direction
while (true) {
val target = canMove(point, neighbors, cursor)
if (target != null) {
proposals[point] = target
break
}
cursor = getNext(cursor)
if (cursor == direction) {
break
}
}
}
val reverseMap = proposals.asIterable().groupBy({ pair -> pair.value }, { pair -> pair.key })
val moves = reverseMap.filter { it.value.size == 1 }.map { it.value[0] to it.key }.toMap()
return points
.filter { p -> !moves.containsKey(p) }
.union(moves.values)
.toSet()
}
fun play1(points: Set<Point>): Set<Point> {
var direction = Direction.Up
var cursor = points
for (i in 1..10) {
cursor = move(cursor, direction)
direction = getNext(direction)
}
return cursor
}
fun play2(points: Set<Point>): Int {
var direction = Direction.Up
var cursor = points
var i = 0
do {
val newCursor = move(cursor, direction)
direction = getNext(direction)
val same = newCursor == cursor
cursor = newCursor
++i
} while (!same)
return i
}
fun print(points: Set<Point>) {
val maxX = points.maxOf { p -> p.x }
val maxY = points.maxOf { p -> p.y }
val minX = points.minOf { p -> p.x }
val minY = points.minOf { p -> p.y }
for (y in (minY - 1)..(maxY + 1)) {
for (x in (minX - 1)..(maxX + 1)) {
if (Point(x, y) in points) {
print('#')
} else {
print('.')
}
}
println()
}
println()
}
fun part1(input: List<String>): String {
val points = parse(input)
val result = play1(points)
return calc(result)
}
private fun calc(result: Set<Point>): String {
val maxX = result.maxOf { p -> p.x }
val maxY = result.maxOf { p -> p.y }
val minX = result.minOf { p -> p.x }
val minY = result.minOf { p -> p.y }
val dx = maxX - minX + 1
val dy = maxY - minY + 1
println("dx $dx dy $dy size ${result.size}")
val answer = dx * dy - result.size
return answer.toString()
}
fun part2(input: List<String>): String {
val points = parse(input)
val result = play2(points)
return result.toString()
}
}
@OptIn(ExperimentalTime::class)
@Suppress("DuplicatedCode")
fun main() {
val solution = Day23()
val name = solution.javaClass.name
val execution = setOf(
ExecutionMode.Test1,
ExecutionMode.Test2,
ExecutionMode.Exec1,
ExecutionMode.Exec2
)
fun test() {
val expected1 = "110"
val expected2 = "20"
val testInput = readInput("${name}_test")
if (execution.contains(ExecutionMode.Test1)) {
println("Test part 1")
assert(solution.part1(testInput), expected1)
println("> Passed")
}
if (execution.contains(ExecutionMode.Test2)) {
println("Test part 2")
assert(solution.part2(testInput), expected2)
println("> Passed")
println()
}
println("=================================")
println()
}
fun run() {
val input = readInput(name)
if (execution.contains(ExecutionMode.Exec1)) {
val elapsed1 = measureTime {
println("Part 1: " + solution.part1(input))
}
println("Elapsed: $elapsed1")
println()
}
if (execution.contains(ExecutionMode.Exec2)) {
val elapsed2 = measureTime {
println("Part 2: " + solution.part2(input))
}
println("Elapsed: $elapsed2")
println()
}
}
test()
run()
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day23Kt.class",
"javap": "Compiled from \"Day23.kt\"\npublic final class Day23Kt {\n public static final void main();\n Code:\n 0: new #8 // class Day23\n 3: dup\n 4: invokespecial #11 // Method Day2... |
kipwoker__aoc2022__d8aeea8/src/Day13.kt | import java.util.Comparator
fun main() {
class TreeNode(
val value: Int?,
val parent: TreeNode?,
val str: String?,
var children: MutableList<TreeNode> = mutableListOf()
)
class TreeNodeComparator(val f: (o1: TreeNode?, o2: TreeNode?) -> Int) : Comparator<TreeNode> {
override fun compare(o1: TreeNode?, o2: TreeNode?): Int {
return f(o1, o2)
}
}
fun parseTree(input: String): TreeNode {
val root = TreeNode(null, null, input)
var currentNode = root
var level = 0
val size = input.length
var i = 0
while (i < size) {
var c = input[i]
when (c) {
'[' -> {
val child = TreeNode(null, currentNode, null)
currentNode.children.add(child)
currentNode = child
level++
}
']' -> {
currentNode = currentNode.parent!!
level--
}
',' -> {
}
in '0'..'9' -> {
var number = ""
while (c in '0'..'9') {
number += c
++i
c = input[i]
}
--i
val child = TreeNode(number.toInt(), currentNode, null)
currentNode.children.add(child)
}
}
++i
}
return root
}
fun parse(input: List<String>): List<Pair<TreeNode, TreeNode>> {
return input
.chunked(3)
.map { chunk ->
parseTree(chunk[0]) to parseTree(chunk[1])
}
}
fun compare(left: Int, right: Int): Boolean? {
if (left == right) {
return null
}
return left < right
}
fun compare(left: TreeNode, right: TreeNode): Boolean? {
if (left.value != null && right.value != null) {
return compare(left.value, right.value)
}
if (left.value == null && right.value == null) {
var i = 0
while (i < left.children.size || i < right.children.size) {
if (left.children.size < right.children.size && i >= left.children.size) {
return true
}
if (left.children.size > right.children.size && i >= right.children.size) {
return false
}
val leftChild = left.children[i]
val rightChild = right.children[i]
val result = compare(leftChild, rightChild)
if (result != null) {
return result
}
++i
}
}
if (left.value != null) {
val subNode = TreeNode(null, left.parent, null)
val subChild = TreeNode(left.value, subNode, null)
subNode.children.add(subChild)
return compare(subNode, right)
}
if (right.value != null) {
val subNode = TreeNode(null, right.parent, null)
val subChild = TreeNode(right.value, subNode, null)
subNode.children.add(subChild)
return compare(left, subNode)
}
return null
}
fun part1(input: List<String>): Int {
val pairs = parse(input)
return pairs
.map { item -> compare(item.first, item.second) }
.mapIndexed { index, r -> if (r == true) index + 1 else 0 }
.sum()
}
fun part2(input: List<String>): Int {
val input1 = input.toMutableList()
input1.add("\n")
input1.add("[[2]]")
input1.add("[[6]]")
input1.add("\n")
val pairs = parse(input1)
val comparator = TreeNodeComparator { o1, o2 ->
when (compare(o1!!, o2!!)) {
true -> -1
false -> 1
else -> 0
}
}
return pairs
.flatMap { item -> listOf(item.first, item.second) }
.sortedWith(comparator)
.mapIndexed { index, treeNode ->
if (treeNode.str == "[[2]]" || treeNode.str == "[[6]]") {
index + 1
} else {
1
}
}
.reduce { acc, i -> acc * i }
}
val testInput = readInput("Day13_test")
assert(part1(testInput), 13)
assert(part2(testInput), 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day13Kt$main$TreeNodeComparator.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13Kt$main$TreeNodeComparator implements java.util.Comparator<Day13Kt$main$TreeNode> {\n private final kotlin.jvm.functions.Function2<Day13Kt$main$TreeNode, Day13Kt... |
kipwoker__aoc2022__d8aeea8/src/Day05.kt | import java.util.Stack
class CrateStack(val crates: Stack<Char>)
class Move(val quantity: Int, val startIdx: Int, val endIdx: Int)
class State(val stacks: Array<CrateStack>, val moves: Array<Move>) {
fun applyMoves() {
for (move in moves) {
for (i in 1..move.quantity) {
val crate = stacks[move.startIdx].crates.pop()
stacks[move.endIdx].crates.push(crate)
}
}
}
fun applyMoves2() {
for (move in moves) {
val batch = mutableListOf<Char>()
for (i in 1..move.quantity) {
val crate = stacks[move.startIdx].crates.pop()
batch.add(crate)
}
batch.asReversed().forEach { crate ->
stacks[move.endIdx].crates.push(crate)
}
}
}
fun getTops(): String {
return String(stacks.map { it.crates.peek() }.toCharArray())
}
}
fun main() {
fun parseStacks(input: List<String>): Array<CrateStack> {
val idxs = mutableListOf<Int>()
val idxInput = input.last()
for ((index, item) in idxInput.toCharArray().withIndex()) {
if (item != ' ') {
idxs.add(index)
}
}
val result = Array(idxs.size) { _ -> CrateStack(Stack<Char>()) }
val cratesInput = input.asReversed().slice(1 until input.size)
for (line in cratesInput) {
for ((localIdx, idx) in idxs.withIndex()) {
if (line.length > idx && line[idx] != ' ') {
result[localIdx].crates.push(line[idx])
}
}
}
return result
}
fun parseMoves(input: List<String>): Array<Move> {
return input
.map { line ->
val parts = line.split(' ')
Move(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1)
}.toTypedArray()
}
fun parse(input: List<String>): State {
val separatorIdx = input.lastIndexOf("")
val stacksInput = input.slice(0 until separatorIdx)
val movesInput = input.slice(separatorIdx + 1 until input.size)
return State(parseStacks(stacksInput), parseMoves(movesInput))
}
fun part1(input: List<String>): String {
val state = parse(input)
state.applyMoves()
return state.getTops()
}
fun part2(input: List<String>): String {
val state = parse(input)
state.applyMoves2()
return state.getTops()
}
val testInput = readInput("Day05_test")
assert(part1(testInput), "CMZ")
assert(part2(testInput), "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day05_test\n 2: invokestatic #14 // Method UtilsKt.readI... |
kipwoker__aoc2022__d8aeea8/src/Day15.kt | import kotlin.math.abs
fun main() {
data class Signal(val sensor: Point, val beacon: Point) {
fun getDistance(): Int {
return abs(sensor.x - beacon.x) + abs(sensor.y - beacon.y)
}
}
fun parse(input: List<String>): List<Signal> {
val regex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex()
return input.map { line ->
val (sensorX, sensorY, beaconX, beaconY) = regex
.matchEntire(line)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $line")
Signal(Point(sensorX.toInt(), sensorY.toInt()), Point(beaconX.toInt(), beaconY.toInt()))
}
}
fun getIntervals(
signals: List<Signal>,
row: Int
): List<Interval> {
val intervals = mutableListOf<Interval>()
for (signal in signals) {
val distance = signal.getDistance()
val diff = abs(signal.sensor.y - row)
if (diff <= distance) {
val delta = distance - diff
val interval = Interval(signal.sensor.x - delta, signal.sensor.x + delta)
// println("$signal diff: $diff delta: $delta distance: $distance interval: $interval")
intervals.add(interval)
}
}
val merged = Interval.merge(intervals)
// println("Merged: $merged")
return merged
}
fun part1(signals: List<Signal>, row: Int): Int {
val merged = getIntervals(signals, row)
val points = signals
.flatMap { s -> listOf(s.beacon, s.sensor) }
.filter { p -> p.y == row }
.map { p -> p.x }
.toSet()
return merged.sumOf { i -> i.countPoints(points) }
}
fun part2(signals: List<Signal>, limit: Int): Long {
for (row in 0..limit) {
val intervals = getIntervals(signals, row)
if (intervals.size == 2) {
val left = intervals[0]
val right = intervals[1]
if (left.end + 1 == right.start - 1) {
return (left.end + 1) * 4000000L + row
} else {
println("Error: $left $right $row")
throw RuntimeException()
}
}
if (intervals.size != 1) {
println("Error: ${intervals.size} $row")
throw RuntimeException()
}
}
return -1
}
val testInput = readInput("Day15_test")
assert(part1(parse(testInput), 10), 26)
assert(part2(parse(testInput), 20), 56000011L)
val input = readInput("Day15")
println(part1(parse(input), 2000000))
println(part2(parse(input), 4000000))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day15Kt.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day15_test\n 2: invokestatic #14 // Method UtilsKt.readI... |
kipwoker__aoc2022__d8aeea8/src/Day21.kt | import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
enum class MathOperator {
Plus,
Minus,
Multiply,
Divide
}
class Day21 {
data class Monkey(val name: String, var value: Long?, val left: String?, val right: String?, val op: MathOperator?)
fun parseOperator(value: String): MathOperator {
return when (value) {
"*" -> MathOperator.Multiply
"+" -> MathOperator.Plus
"-" -> MathOperator.Minus
"/" -> MathOperator.Divide
else -> throw RuntimeException("Unknown op $value")
}
}
fun parse(input: List<String>): List<Monkey> {
return input.map { line ->
val parts = line.split(' ')
if (parts.size == 4) {
Monkey(parts[0], null, parts[1], parts[3], parseOperator(parts[2]))
} else {
Monkey(parts[0], parts[1].toLong(), null, null, null)
}
}
}
fun calc1(name: String, map: Map<String, Monkey>): Long {
val monkey = map.getValue(name)
if (monkey.value != null) {
return monkey.value!!
}
val left = calc1(monkey.left!!, map)
val right = calc1(monkey.right!!, map)
val result = when (monkey.op!!) {
MathOperator.Plus -> left + right
MathOperator.Minus -> left - right
MathOperator.Multiply -> left * right
MathOperator.Divide -> left / right
}
monkey.value = result
return result
}
fun calc2(name: String, map: Map<String, Monkey>): Long {
val monkey = map.getValue(name)
if (monkey.value != null) {
return monkey.value!!
}
val left = calc2(monkey.left!!, map)
val right = calc2(monkey.right!!, map)
if (monkey.name == "root") {
return right - left
}
val result = when (monkey.op!!) {
MathOperator.Plus -> left + right
MathOperator.Minus -> left - right
MathOperator.Multiply -> left * right
MathOperator.Divide -> left / right
}
monkey.value = result
return result
}
fun part1(input: List<String>): String {
val monkeys = parse(input)
val monkeyMap = monkeys.associateBy { it.name }
val result = calc1("root", monkeyMap)
return result.toString()
}
fun part2(input: List<String>): String {
var r = 5000000000000L
var l = 0L
while (r - l > 1) {
val h = (r + l) / 2
val monkeys = parse(input)
val monkeyMap = monkeys.associateBy { it.name }
monkeyMap["humn"]!!.value = h
val result = calc2("root", monkeyMap)
if (result != 0L) {
if (result < 0) {
l = h
} else {
r = h
}
continue
}
return h.toString()
}
return "Not Found"
}
}
@OptIn(ExperimentalTime::class)
@Suppress("DuplicatedCode")
fun main() {
val solution = Day21()
val name = solution.javaClass.name
val execution = setOf(
ExecutionMode.Test1,
ExecutionMode.Test2,
ExecutionMode.Exec1,
ExecutionMode.Exec2
)
fun test() {
val expected1 = "152"
val expected2 = "301"
val testInput = readInput("${name}_test")
if (execution.contains(ExecutionMode.Test1)) {
println("Test part 1")
assert(solution.part1(testInput), expected1)
println("> Passed")
}
if (execution.contains(ExecutionMode.Test2)) {
println("Test part 2")
assert(solution.part2(testInput), expected2)
println("> Passed")
println()
}
println("=================================")
println()
}
fun run() {
val input = readInput(name)
if (execution.contains(ExecutionMode.Exec1)) {
val elapsed1 = measureTime {
println("Part 1: " + solution.part1(input))
}
println("Elapsed: $elapsed1")
println()
}
if (execution.contains(ExecutionMode.Exec2)) {
val elapsed2 = measureTime {
println("Part 2: " + solution.part2(input))
}
println("Elapsed: $elapsed2")
println()
}
}
test()
run()
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day21Kt.class",
"javap": "Compiled from \"Day21.kt\"\npublic final class Day21Kt {\n public static final void main();\n Code:\n 0: new #8 // class Day21\n 3: dup\n 4: invokespecial #11 // Method Day2... |
kipwoker__aoc2022__d8aeea8/src/Day17.kt | import kotlin.math.max
class Rock(val cells: List<Point>, var shift: Point) {
fun getCoords(): List<Point> {
return cells.map { x -> x.sum(shift) }
}
fun hasCollision(points: Set<Point>, move: Point): Boolean {
val newPosition = this.getCoords()
.map { it.sum(move) }
val hasBoundsCollision = newPosition.any { p -> p.x == -1 || p.y == -1 || p.x == 7 }
if (hasBoundsCollision) {
return true
}
val hasCollision = newPosition
.intersect(points)
.isNotEmpty()
if (hasCollision) {
return true
}
return false
}
companion object {
fun create(index: Int, init: Point): Rock {
return when (val number = index % 5) {
// ####
0 -> Rock(
listOf(
Point(0, 0),
Point(1, 0),
Point(2, 0),
Point(3, 0)
),
init
)
// +
1 -> Rock(
listOf(
Point(1, 0),
Point(0, 1),
Point(1, 1),
Point(2, 1),
Point(1, 2)
),
init
)
// _|
2 -> Rock(
listOf(
Point(0, 0),
Point(1, 0),
Point(2, 0),
Point(2, 1),
Point(2, 2)
),
init
)
// |
3 -> Rock(
listOf(
Point(0, 0),
Point(0, 1),
Point(0, 2),
Point(0, 3)
),
init
)
// square
4 -> Rock(
listOf(
Point(0, 0),
Point(1, 0),
Point(0, 1),
Point(1, 1)
),
init
)
else -> throw RuntimeException("Unexpected $number")
}
}
}
}
@Suppress("DuplicatedCode")
fun main() {
data class State(
val stoppedRocksCount: Long,
val ground: Set<Point>,
val maxY: Int
)
fun parse(input: List<String>): List<Direction> {
return input[0].toCharArray().map { c -> if (c == '<') Direction.Left else Direction.Right }
}
fun print(rocks: List<Rock>) {
val points = rocks.flatMap { r -> r.getCoords() }.toSet()
val maxY = points.maxOf { c -> c.y }
for (y in maxY downTo 0) {
for (x in 0..6) {
if (points.contains(Point(x, y))) {
print('#')
} else {
print('.')
}
}
println()
}
println()
println()
}
fun calculateState(
topLevelMap: MutableMap<Int, Int>,
stopped: Long,
maxY: Int
): State {
val minY = topLevelMap.minOf { t -> t.value }
val newGround = topLevelMap.map { t -> Point(t.key, (t.value - minY)) }.toSet()
return State(stopped, newGround, maxY)
}
fun removeUnreachable(
topLevelMap: MutableMap<Int, Int>,
ground: MutableSet<Point>
) {
val minLevel = topLevelMap.values.min()
ground.removeIf { it.y < minLevel }
}
fun actualizeTopLevels(
coords: List<Point>,
topLevelMap: MutableMap<Int, Int>
) {
for (coord in coords) {
val top = topLevelMap[coord.x]
if (top == null || top < coord.y) {
topLevelMap[coord.x] = coord.y
}
}
}
fun play(directions: List<Direction>, rocksLimit: Long, initGround: Set<Point>): List<State> {
var directionIterator = 0
var rockIterator = 0
var shift = Point(2, 3)
val ground = initGround.toMutableSet()
var stopped = 0L
val topLevelMap = mutableMapOf<Int, Int>()
var activeRock: Rock? = null
var maxY = 0
val states = mutableListOf<State>()
val dy = Point(0, -1)
while (stopped < rocksLimit) {
if (activeRock == null) {
activeRock = Rock.create(rockIterator, shift)
++rockIterator
}
val direction = directions[directionIterator]
val dx = if (direction == Direction.Left) Point(-1, 0) else Point(1, 0)
if (!activeRock.hasCollision(ground, dx)) {
activeRock.shift = activeRock.shift.sum(dx)
}
if (!activeRock.hasCollision(ground, dy)) {
activeRock.shift = activeRock.shift.sum(dy)
} else {
++stopped
val coords = activeRock.getCoords()
actualizeTopLevels(coords, topLevelMap)
ground.addAll(coords)
removeUnreachable(topLevelMap, ground)
maxY = max(maxY, topLevelMap.values.max() + 1)
shift = Point(shift.x, maxY + 3)
activeRock = null
}
directionIterator = (directionIterator + 1) % directions.size
if (directionIterator == 0) {
states.add(calculateState(topLevelMap, stopped, maxY))
if (states.size > 1) {
break
}
}
}
if (states.size <= 1) {
states.add(calculateState(topLevelMap, stopped, maxY))
}
return states
}
fun findMax(directions: List<Direction>, totalRocks: Long): Long {
val defaultGround = (0..6).map { Point(it, -1) }.toSet()
val states = play(directions, totalRocks, defaultGround).reversed()
val lastRocksCount = states[0].stoppedRocksCount
val maxY = states[0].maxY
val leftRocks = totalRocks - lastRocksCount
if (leftRocks == 0L) {
return maxY.toLong()
}
val deltaRocks = lastRocksCount - states[1].stoppedRocksCount
val deltaY = states[0].maxY - states[1].maxY
val mult = leftRocks / deltaRocks
val sliceY = deltaY * mult
val restRocks = leftRocks % deltaRocks
val (_, _, maxY1) = play(
directions,
restRocks,
states[0].ground
)[0]
return maxY + sliceY + maxY1 - 1
}
fun part1(input: List<String>): Long {
return findMax(parse(input), 2022L)
}
fun part2(input: List<String>): Long {
return findMax(parse(input), 1000000000000L)
}
// ==================================================================== //
val day = "17"
fun test() {
val testInput = readInput("Day${day}_test")
assert(part1(testInput), 3068L)
assert(part2(testInput), 1514285714288L)
}
fun run() {
val input = readInput("Day$day")
println(part1(input))
println(part2(input))
}
// test()
run()
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day17Kt.class",
"javap": "Compiled from \"Day17.kt\"\npublic final class Day17Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String 17\n 2: astore_0\n 3: aload_0\n 4: invokestatic #12 ... |
kipwoker__aoc2022__d8aeea8/src/Day07.kt | import java.math.BigInteger
enum class NodeType { File, Dir }
class Node(val parent: Node?, val children: MutableMap<String, Node>, val alias: String, val size: BigInteger?, val type: NodeType) {
var totalSize = BigInteger.ZERO
fun getRoot(): Node {
var currentNode = this
while (currentNode.parent != null) {
currentNode = currentNode.parent!!
}
return currentNode
}
fun calculateTotalSize(): BigInteger {
if (type == NodeType.File) {
totalSize = size!!
return totalSize
}
totalSize = children.values.sumOf { it.calculateTotalSize() }
return totalSize
}
fun sumBy(threshold: BigInteger): BigInteger {
var result = BigInteger.ZERO
if (type == NodeType.Dir && totalSize <= threshold) {
result += totalSize
}
return result + children.values.sumOf { it.sumBy(threshold) }
}
fun printNode() {
printNode(0)
}
fun printNode(indentLevel: Int) {
val indent = (0..indentLevel).map { ' ' }.joinToString("")
val typeMsg = if (type == NodeType.Dir) "dir" else "file, size=$size"
println("$indent- $alias ($typeMsg)")
children.values.forEach { it.printNode(indentLevel + 2) }
}
fun getDirSizes(): List<BigInteger> {
val result = mutableListOf(totalSize)
result.addAll(children.values.flatMap { it.getDirSizes() })
return result
}
}
fun main() {
fun ensureDirExists(node: Node, alias: String) {
if (node.children[alias] == null) {
node.children[alias] = Node(node, mutableMapOf(), alias, null, NodeType.Dir)
}
}
fun ensureFileExists(node: Node, alias: String, size: BigInteger) {
if (node.children[alias] == null) {
node.children[alias] = Node(node, mutableMapOf(), alias, size, NodeType.File)
}
}
fun parse(input: List<String>): Node {
val root = Node(null, mutableMapOf(), "/", null, NodeType.Dir)
var pointer = root
var lineIdx = 0
val totalSize = input.size
while (lineIdx < totalSize) {
val line = input[lineIdx]
println("Command: $line")
if (line == "$ cd /") {
pointer = pointer.getRoot()
++lineIdx
} else if (line == "$ cd ..") {
pointer = pointer.parent!!
++lineIdx
} else if (line.startsWith("$ cd")) {
val dirAlias = line.split(' ')[2]
ensureDirExists(pointer, dirAlias)
pointer = pointer.children[dirAlias]!!
++lineIdx
} else if (line == "$ ls") {
var listIdx = lineIdx + 1
while (listIdx < totalSize && !input[listIdx].startsWith("$")) {
val node = input[listIdx]
if (node.startsWith("dir")) {
val dirAlias = node.split(' ')[1]
ensureDirExists(pointer, dirAlias)
} else {
val parts = node.split(' ')
val size = parts[0].toBigInteger()
val fileAlias = parts[1]
ensureFileExists(pointer, fileAlias, size)
}
++listIdx
}
lineIdx = listIdx
} else {
println("Unexpected line: $line")
return root
}
println("Root")
root.printNode()
println()
}
return root
}
fun part1(input: List<String>): BigInteger {
val root = parse(input)
root.calculateTotalSize()
return root.sumBy(BigInteger.valueOf(100000))
}
fun part2(input: List<String>): BigInteger {
val root = parse(input)
root.calculateTotalSize()
val threshold = root.totalSize - BigInteger.valueOf(40000000)
return root.getDirSizes().filter { it >= threshold }.min()
}
val testInput = readInput("Day07_test")
assert(part1(testInput), BigInteger.valueOf(95437L))
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day07Kt.class",
"javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day07_test\n 2: invokestatic #14 // Method UtilsKt.readI... |
kipwoker__aoc2022__d8aeea8/src/Day01.kt | fun main() {
fun getStructure(input: List<String>): MutableList<List<Int>> {
val result = mutableListOf<List<Int>>()
var bucket = mutableListOf<Int>()
result.add(bucket)
input.forEach { line ->
run {
if (line.isBlank()) {
bucket = mutableListOf()
result.add(bucket)
} else {
bucket.add(line.toInt())
}
}
}
return result
}
fun part1(input: List<String>): Int {
val structure = getStructure(input)
return structure.maxOf { it.sum() }
}
fun part2(input: List<String>): Int {
val structure = getStructure(input)
return structure
.map { it.sum() }
.sortedByDescending { it }
.take(3)
.sumOf { it }
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day01Kt$main$part2$$inlined$sortedByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class Day01Kt$main$part2$$inlined$sortedByDescending$1<T> implements java.util.Comparator {\n public Day01Kt$main$part2$$inlined$sortedByDescending$1... |
kipwoker__aoc2022__d8aeea8/src/Day06.kt |
fun main() {
fun getDiffIndex(input: List<String>, diffCount: Int): Int {
val line = input[0].toCharArray()
for (i in 0..line.size - diffCount) {
if (line.slice(i until i + diffCount).toSet().size == diffCount) {
return i + diffCount
}
}
return -1
}
fun part1(input: List<String>): Int {
return getDiffIndex(input, 4)
}
fun part2(input: List<String>): Int {
return getDiffIndex(input, 14)
}
assert(part1(readInput("Day06_test_1")), 7)
assert(part1(readInput("Day06_test_2")), 5)
assert(part1(readInput("Day06_test_3")), 11)
assert(part2(readInput("Day06_test_1")), 19)
assert(part2(readInput("Day06_test_2")), 23)
assert(part2(readInput("Day06_test_3")), 26)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day06Kt.class",
"javap": "Compiled from \"Day06.kt\"\npublic final class Day06Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day06_test_1\n 2: invokestatic #14 // Method UtilsKt.rea... |
kipwoker__aoc2022__d8aeea8/src/Day03.kt |
fun main() {
fun getPriority(ch: Char): Long {
if (ch in 'A'..'Z') {
return ch - 'A' + 27L
}
return ch - 'a' + 1L
}
fun part1(input: List<String>): Long {
return input.sumOf { line ->
line
.chunkedSequence(line.length / 2)
.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.sumOf {
getPriority(it)
}
}
}
fun part2(input: List<String>): Long {
return input
.chunked(3)
.sumOf { group ->
group
.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.sumOf {
getPriority(it)
}
}
}
check(getPriority('a') == 1L)
check(getPriority('z') == 26L)
check(getPriority('A') == 27L)
check(getPriority('Z') == 52L)
val testInput = readInput("Day03_test")
check(part1(testInput) == 157L)
check(part2(testInput) == 70L)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: bipush 97\n 2: invokestatic #10 // Method main$getPriority:(C)J\n 5: lconst_1\n 6... |
kipwoker__aoc2022__d8aeea8/src/Day09.kt | import kotlin.math.abs
class Command(val direction: Direction, val count: Int)
fun main() {
fun parse(input: List<String>): List<Command> {
return input.map { line ->
val parts = line.split(' ')
val direction = when (parts[0]) {
"U" -> Direction.Up
"D" -> Direction.Down
"L" -> Direction.Left
"R" -> Direction.Right
else -> throw RuntimeException()
}
Command(direction, parts[1].toInt())
}
}
fun move(point: Point, direction: Direction): Point {
return when (direction) {
Direction.Up -> Point(point.x, point.y + 1)
Direction.Down -> Point(point.x, point.y - 1)
Direction.Left -> Point(point.x - 1, point.y)
Direction.Right -> Point(point.x + 1, point.y)
}
}
fun isTouching(head: Point, tail: Point): Boolean {
return abs(head.x - tail.x) <= 1 && abs(head.y - tail.y) <= 1
}
fun getDelta(head: Int, tail: Int): Int {
if (head == tail) {
return 0
}
if (head > tail) {
return 1
}
return -1
}
fun tryMoveTail(head: Point, tail: Point): Point {
if (isTouching(head, tail)) {
return tail
}
val dx = getDelta(head.x, tail.x)
val dy = getDelta(head.y, tail.y)
return Point(tail.x + dx, tail.y + dy)
}
fun traverse(commands: List<Command>, totalSize: Int): Int {
val visited = mutableSetOf<Point>()
var head = Point(0, 0)
val size = totalSize - 2
val middle = (1..size).map { Point(0, 0) }.toMutableList()
var tail = Point(0, 0)
visited.add(tail)
for (command in commands) {
for (i in 1..command.count) {
head = move(head, command.direction)
var pointer = head
for (j in 0 until size) {
middle[j] = tryMoveTail(pointer, middle[j])
pointer = middle[j]
}
tail = tryMoveTail(pointer, tail)
visited.add(tail)
}
}
return visited.count()
}
fun part1(input: List<String>): Int {
val commands = parse(input)
return traverse(commands, 2)
}
fun part2(input: List<String>): Int {
val commands = parse(input)
return traverse(commands, 10)
}
val testInput = readInput("Day09_test")
assert(part1(testInput), 13)
assert(part2(testInput), 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day09Kt$WhenMappings.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method Direction.values:()[LD... |
kipwoker__aoc2022__d8aeea8/src/Day02.kt | enum class Figure(val score: Int) {
Rock(1),
Paper(2),
Scissors(3)
}
fun main() {
fun createFigure(value: String): Figure {
return when (value) {
"A" -> Figure.Rock
"B" -> Figure.Paper
"C" -> Figure.Scissors
"X" -> Figure.Rock
"Y" -> Figure.Paper
"Z" -> Figure.Scissors
else -> throw Exception("Value unsupported $value")
}
}
fun compare(f1: Figure, f2: Figure): Int {
if (f1 == f2) {
return 3
}
if (
f1 == Figure.Paper && f2 == Figure.Scissors ||
f1 == Figure.Rock && f2 == Figure.Paper ||
f1 == Figure.Scissors && f2 == Figure.Rock
) {
return 6
}
return 0
}
fun readTurns(lines: List<String>): List<Pair<Figure, Figure>> {
return lines.map {
val parts = it.split(' ')
Pair(createFigure(parts[0]), createFigure(parts[1]))
}
}
fun createFigure2(first: Figure, value: String): Figure {
if (value == "Y") {
return first
}
if (value == "X") {
return when (first) {
Figure.Rock -> Figure.Scissors
Figure.Paper -> Figure.Rock
Figure.Scissors -> Figure.Paper
}
}
return when (first) {
Figure.Rock -> Figure.Paper
Figure.Paper -> Figure.Scissors
Figure.Scissors -> Figure.Rock
}
}
fun readTurns2(lines: List<String>): List<Pair<Figure, Figure>> {
return lines.map {
val parts = it.split(' ')
val first = createFigure(parts[0])
Pair(first, createFigure2(first, parts[1]))
}
}
fun play(turns: List<Pair<Figure, Figure>>): Long {
var result = 0L
turns.map {
compare(it.first, it.second) + it.second.score
}.forEach {
result += it
}
return result
}
fun part1(input: List<String>): Long {
return play(readTurns(input))
}
fun part2(input: List<String>): Long {
return play(readTurns2(input))
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15L)
check(part2(testInput) == 12L)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day02_test\n 2: invokestatic #14 // Method UtilsKt.readI... |
kipwoker__aoc2022__d8aeea8/src/Day12.kt | class Day12Input(
val graph: Map<Point, Int>,
val start: Point,
val end: Point
)
data class Trace(val weight: Int, val current: Point, val prev: Point?, val distance: Int)
fun main() {
fun getNeighbors(point: Point, graph: Map<Point, Int>): List<Point> {
return listOf(
Point(point.x - 1, point.y),
Point(point.x + 1, point.y),
Point(point.x, point.y - 1),
Point(point.x, point.y + 1)
).filter { graph.contains(it) }
}
fun search(graph: Map<Point, Int>, startPoints: List<Point>, endPoint: Point): Int {
val visited = startPoints.toMutableSet()
val queue = ArrayDeque(
startPoints.map { start -> Trace(graph[start]!!, start, null, 0) }
)
while (queue.isNotEmpty()) {
val item = queue.removeFirst()
if (item.current == endPoint) {
return item.distance
}
val source = item.current
val sourceWeight = graph[source]!!
for (target in getNeighbors(source, graph)) {
val targetWeight = graph[target]!!
if (targetWeight - sourceWeight > 1 || target in visited) {
continue
}
visited.add(target)
queue.addLast(Trace(targetWeight, target, source, item.distance + 1))
}
}
return -1
}
fun parse(input: List<String>): Day12Input {
var start = Point(0, 0)
var end = Point(0, 0)
val graph = input.mapIndexed { i, line ->
line.mapIndexed { j, cell ->
val value: Int = when (cell) {
'S' -> {
start = Point(i, j)
1
}
'E' -> {
end = Point(i, j)
'z' - 'a' + 1
}
else ->
(cell - 'a' + 1)
}
Point(i, j) to value
}
}.flatten().toMap()
return Day12Input(graph, start, end)
}
fun part1(input: List<String>): Int {
val day12Input = parse(input)
return search(day12Input.graph, listOf(day12Input.start), day12Input.end)
}
fun part2(input: List<String>): Int {
val day12Input = parse(input)
val startPoints = day12Input.graph.filter { it.value == 1 }.map { it.key }
return search(day12Input.graph, startPoints, day12Input.end)
}
val testInput = readInput("Day12_test")
assert(part1(testInput), 31)
assert(part2(testInput), 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day12Kt.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class Day12Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day12_test\n 2: invokestatic #14 // Method UtilsKt.readI... |
kipwoker__aoc2022__d8aeea8/src/Day11.kt | import kotlin.math.pow
data class Modifier(val op: Char, val value: Int)
data class Condition(val divisibleBy: Int, val ifTrue: Int, val ifFalse: Int)
data class Monkey(
val index: Int,
val queue: MutableList<Long>,
val modifier: Modifier,
val condition: Condition,
var inspectionCount: Long
)
fun main() {
fun parse(input: List<String>): List<Monkey> {
val chunks = input.chunked(7)
return chunks.map { it ->
val index = it[0].toInt()
val items = it[1].split(',').map { x -> x.toLong() }.toMutableList()
val modifierParts = it[2].split(' ')
val modifier = Modifier(modifierParts[0][0], modifierParts[1].toInt())
val divisibleBy = it[3].toInt()
val ifTrue = it[4].toInt()
val ifFalse = it[5].toInt()
val condition = Condition(divisibleBy, ifTrue, ifFalse)
Monkey(index, items, modifier, condition, 0)
}
}
fun applyModifier(value: Long, modifier: Modifier): Long {
return when (modifier.op) {
'^' -> value.toDouble().pow(modifier.value.toDouble()).toLong()
'+' -> value + modifier.value
'*' -> value * modifier.value
else -> throw RuntimeException("Unknown modifier $modifier")
}
}
fun applyCondition(value: Long, condition: Condition): Int {
return if (value % condition.divisibleBy == 0L) condition.ifTrue else condition.ifFalse
}
fun printState(monkeys: List<Monkey>) {
for (monkey in monkeys) {
println("Monkey ${monkey.index}: ${monkey.queue}")
}
}
fun printCounts(monkeys: List<Monkey>) {
for (monkey in monkeys) {
println("Monkey ${monkey.index}: ${monkey.inspectionCount}")
}
}
fun play(monkeys: List<Monkey>, iterationsCount: Int, worryReducer: (v: Long) -> Long) {
val overflowBreaker = monkeys.map { it.condition.divisibleBy }.reduce { acc, i -> acc * i }
for (i in 1..iterationsCount) {
for (monkey in monkeys) {
for (item in monkey.queue) {
val worryLevel = applyModifier(item, monkey.modifier)
val newLevel = worryReducer(worryLevel) % overflowBreaker
val newIndex = applyCondition(newLevel, monkey.condition)
monkeys[newIndex].queue.add(newLevel)
++monkey.inspectionCount
}
monkey.queue.clear()
}
if (i % 20 == 0){
println("Iteration $i")
printCounts(monkeys)
println()
}
}
}
fun calculateResult(monkeys: List<Monkey>): Long {
val ordered = monkeys.sortedBy { -it.inspectionCount }
return ordered[0].inspectionCount * ordered[1].inspectionCount
}
fun part1(input: List<String>): Long {
val monkeys = parse(input)
play(monkeys, 20) { x -> x / 3 }
return calculateResult(monkeys)
}
fun part2(input: List<String>): Long {
val monkeys = parse(input)
play(monkeys, 10000) { x -> x }
return calculateResult(monkeys)
}
val testInput = readInput("Day11_test")
assert(part1(testInput), 10605L)
assert(part2(testInput), 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day11Kt$main$calculateResult$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class Day11Kt$main$calculateResult$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public Day11Kt$main$calculateResult$$inlined$sortedBy$1... |
kipwoker__aoc2022__d8aeea8/src/Day10.kt | class Operation(val cycles: Int, val add: Int)
fun main() {
fun parse(input: List<String>): List<Operation> {
return input.map { line ->
if (line == "noop") {
Operation(1, 0)
} else {
val modifier = line.split(' ')[1].toInt()
Operation(2, modifier)
}
}
}
fun part1(input: List<String>): Long {
val ops = parse(input)
var x = 1
var result = 0L
val maxIndex = 220
var seekIndex = 20
val hop = 40
var cycleCounter = 0
for (op in ops) {
for (cycle in 1..op.cycles) {
++cycleCounter
if (cycleCounter == seekIndex) {
result += x * seekIndex
if (seekIndex == maxIndex) {
return result
}
seekIndex += hop
}
}
x += op.add
}
return result
}
fun isSprite(cycleCounter: Int, x: Int, lineIndex: Int, hop: Int): Boolean {
val lineValue = cycleCounter - (hop * lineIndex)
return lineValue >= x - 1 && lineValue <= x + 1
}
fun part2(input: List<String>): Long {
val ops = parse(input)
var x = 1
var lineIndex = 0
val maxIndex = 240
var seekIndex = 40
val hop = 40
var cycleCounter = 0
for (op in ops) {
for (cycle in 1..op.cycles) {
if (isSprite(cycleCounter, x, lineIndex, hop)) {
print("#")
} else {
print(".")
}
++cycleCounter
if (cycleCounter == seekIndex) {
println()
if (seekIndex == maxIndex) {
return 0
}
seekIndex += hop
++lineIndex
}
}
x += op.add
}
return 0
}
val testInput = readInput("Day10_test")
assert(part1(testInput), 13140L)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day10Kt.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class Day10Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day10_test\n 2: invokestatic #14 // Method UtilsKt.readI... |
kipwoker__aoc2022__d8aeea8/src/Day08.kt | import kotlin.math.max
class Tree(val value: Int, var visible: Boolean)
fun main() {
fun parse(input: List<String>): List<List<Tree>> {
return input.map { line ->
line.toCharArray().map {
Tree(it.digitToInt(), false)
}
}
}
fun findVisible(trees: List<List<Tree>>): Int {
val size = trees.size
val lastIdx = size - 1
for (i in 0..lastIdx) {
var maxLeft = -1
var maxRight = -1
for (j in 0..lastIdx) {
val cellLeft = trees[i][j]
if (cellLeft.value > maxLeft) {
cellLeft.visible = true
maxLeft = cellLeft.value
}
val cellRight = trees[i][lastIdx - j]
if (cellRight.value > maxRight) {
cellRight.visible = true
maxRight = cellRight.value
}
}
}
for (i in 0..lastIdx) {
var maxTop = -1
var maxBottom = -1
for (j in 0..lastIdx) {
val cellTop = trees[j][i]
if (cellTop.value > maxTop) {
cellTop.visible = true
maxTop = cellTop.value
}
val cellBottom = trees[lastIdx - j][i]
if (cellBottom.value > maxBottom) {
cellBottom.visible = true
maxBottom = cellBottom.value
}
}
}
return trees.sumOf { x -> x.count { y -> y.visible } }
}
fun findMax(center: Int, range: IntProgression, getter: (x: Int) -> Tree): Int {
var count = 0
for (i in range) {
val cell = getter(i)
if (cell.value >= center) {
return count + 1
}
++count
}
return count
}
fun findScenic(trees: List<List<Tree>>): Int {
val size = trees.size
val lastIdx = size - 1
var maxScenic = -1
for (i in 0..lastIdx) {
for (j in 0..lastIdx) {
val center = trees[i][j].value
val left = findMax(center, j - 1 downTo 0) { x -> trees[i][x] }
val right = findMax(center, j + 1..lastIdx) { x -> trees[i][x] }
val top = findMax(center, i - 1 downTo 0) { x -> trees[x][j] }
val bottom = findMax(center, i + 1..lastIdx) { x -> trees[x][j] }
val scenic = top * left * bottom * right
maxScenic = max(scenic, maxScenic)
}
}
return maxScenic
}
fun part1(input: List<String>): Int {
val trees = parse(input)
return findVisible(trees)
}
fun part2(input: List<String>): Int {
val trees = parse(input)
return findScenic(trees)
}
val testInput = readInput("Day08_test")
assert(part1(testInput), 21)
assert(part2(testInput), 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kipwoker__aoc2022__d8aeea8/Day08Kt.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day08_test\n 2: invokestatic #14 // Method UtilsKt.readI... |
knivey__adventofcode__14a8a23/Day11/Day11part2.kt |
import java.io.File
enum class Tile(val c: String) {
FLOOR("."),
FILLED("#"),
EMPTY("L"),
UNKNOWN("?");
fun from(c: Char) : Tile {
when (c) {
'.' -> return FLOOR
'#' -> return FILLED
'L' -> return EMPTY
}
return UNKNOWN;
}
override fun toString(): String {
return c
}
}
fun main() {
val map: ArrayList<ArrayList<Tile>> = File("input.txt").readLines().asSequence()
.map { line -> line.asSequence() }
.map { it.map {t -> Tile.UNKNOWN.from(t)} }
.map { it.toCollection(ArrayList()) }
.toCollection(ArrayList())
val maxY = map.size -1
val maxX = map[0].size -1
var changes = 1
var iterations = 0
while (changes != 0) {
changes = 0
val mapc = copyMap(map)
for ((y, row) in mapc.withIndex()) {
for ((x, tile) in row.withIndex()) {
if(tile == Tile.FLOOR) {
//print(".")
continue
}
var occupied : Int = 0
for(vec in genVecs(x, y, maxX, maxY)) {
for (v in vec) {
if (mapc[v.y][v.x] == Tile.FILLED) {
occupied++
break
}
if (mapc[v.y][v.x] == Tile.EMPTY) {
break
}
}
}
if(occupied >= 5)
if(tile != Tile.EMPTY) {
map[y][x] = Tile.EMPTY
changes++
}
if(occupied == 0)
if(tile != Tile.FILLED) {
map[y][x] = Tile.FILLED
changes++
}
//print(occupied)
}
//print("\n")
}
if(changes != 0)
iterations++
if(iterations > 100000) {
println("giving up");
break;
}
//println("Changed: $changes ------")
//map.forEach{ println(it.joinToString("")) }
//println("------------------------")
}
val filled = map
.flatten()
.filter {it == Tile.FILLED}
.count()
println("$filled seats filled")
}
fun copyMap(map: ArrayList<ArrayList<Tile>>): ArrayList<ArrayList<Tile>>{
val mapc: ArrayList<ArrayList<Tile>> = arrayListOf()
for(m: ArrayList<Tile> in map) {
mapc.add(m.clone() as java.util.ArrayList<Tile>)
}
return mapc;
}
data class Coord(val x: Int, val y: Int) {
}
//Boy this seems silly
//Will update later to make something that take (stepx, stepy)
fun genVecs(x:Int, y:Int, maxX: Int, maxY:Int) : List<List<Coord>> {
val out: MutableList<MutableList<Coord>> = mutableListOf()
/**
* 123
* 0o4
* 765
*/
for (v in 0..7) {
var list: MutableList<Coord> = mutableListOf()
when (v) {
0 -> list = (x-1 downTo 0).map { Coord(it, y) }.toMutableList()
1 -> {
for (i in x-1 downTo 0) {
val j = y - (x - i)
if (j >= 0)
list.add(Coord(i, j))
}
}
2 -> list = (y-1 downTo 0).map { Coord(x, it) }.toMutableList()
3 -> {
for (i in x+1..maxX) {
val j = y - (i - x)
if (j in 0..maxY)
list.add(Coord(i, j))
}
}
4 -> list = (x+1..maxX).map { Coord(it, y) }.toMutableList()
5 -> {
for (i in x+1..maxX) {
val j = y + (i - x)
if (j in 0..maxY)
list.add(Coord(i, j))
}
}
6 -> list = (y+1..maxY).map { Coord(x, it) }.toMutableList()
7 -> {
for (i in x-1 downTo 0) {
val j = y - (i - x)
if (j in 0..maxY)
list.add(Coord(i, j))
}
}
}
out.add(list)
}
return out
} | [
{
"class_path": "knivey__adventofcode__14a8a23/Day11part2Kt.class",
"javap": "Compiled from \"Day11part2.kt\"\npublic final class Day11part2Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
Javran__exercism-solutions__15891b1/kotlin/pig-latin/src/main/kotlin/PigLatin.kt | object PigLatin {
// List of char sequence that should be considered a single cluster of vowel / consonant.
// Longer elements must appear first.
private val clusters: List<Pair<String, Boolean>> = listOf(
"sch" to false, "thr" to false,
"xr" to true, "yt" to true,
"ch" to false, "qu" to false, "th" to false, "rh" to false,
"a" to true, "e" to true, "i" to true, "o" to true, "u" to true,
"y" to false
)
private data class SplitResult(
val head: String,
val headIsVowel: Boolean,
val tail: String
)
// Splits a non-empty word by first vowel / consonant cluster.
// INVARIANT: head + tail == <input word>, where head and tail are from SplitResult.
private fun splitFirstCluster(word: String): SplitResult {
for ((prefix, prefixIsVowel) in clusters) {
if (word.startsWith(prefix)) {
return SplitResult(prefix, prefixIsVowel, word.substring(prefix.length))
}
}
return SplitResult(word.substring(0, 1), false, word.substring(1))
}
// Translates a single word into Pig Latin. It is assumed that the word is not empty.
private fun translateWord(word: String): String {
val (head, headIsVowel, tail) = splitFirstCluster(word)
return when {
headIsVowel ->
// Rule 1
word + "ay"
tail.startsWith("y") ->
// Rule 4
tail + head + "ay"
tail.startsWith("qu") ->
// Rule 3
tail.substring(2) + head + "quay"
else ->
// Rule 2
tail + head + "ay"
}
}
fun translate(phrase: String): String =
phrase.split(" ").map(::translateWord).joinToString(" ")
}
| [
{
"class_path": "Javran__exercism-solutions__15891b1/PigLatin.class",
"javap": "Compiled from \"PigLatin.kt\"\npublic final class PigLatin {\n public static final PigLatin INSTANCE;\n\n private static final java.util.List<kotlin.Pair<java.lang.String, java.lang.Boolean>> clusters;\n\n private PigLatin();... |
babangsund__sorting-algorithms__0f05c41/merge-sort/mergeSort.kt | fun <T:Comparable<T>> merge(a: List<T>, b: List<T>): List<T> {
if (a.isEmpty() && b.isNotEmpty()) return b
if (b.isEmpty() && a.isNotEmpty()) return a
val (ah, at) = Pair(a[0], a.drop(1))
val (bh, bt) = Pair(b[0], b.drop(1))
return when {
ah >= bh -> listOf(bh) + merge(a, bt)
else -> listOf(ah) + merge(at, b)
}
}
fun <T:Comparable<T>> mergeSort(list: List<T>): List<T> {
val len = list.count()
if (len < 2) return list
val half = kotlin.math.ceil((len.toDouble() / 2)).toInt()
val (left, right) = list.chunked(half)
return merge(mergeSort(left), mergeSort(right))
}
fun main() {
val sorted = mergeSort(listOf(6, 5, 2, 3, 0, 1))
println("sorted: $sorted")
}
| [
{
"class_path": "babangsund__sorting-algorithms__0f05c41/MergeSortKt.class",
"javap": "Compiled from \"mergeSort.kt\"\npublic final class MergeSortKt {\n public static final <T extends java.lang.Comparable<? super T>> java.util.List<T> merge(java.util.List<? extends T>, java.util.List<? extends T>);\n C... |
mikhail-dvorkin__algorithms__5ad1705/numberTheory.kt | private fun largestPrimeDivisors(n: Int): IntArray {
val largestPrimeDivisors = IntArray(n + 1) { it }
for (i in 2..n) {
if (largestPrimeDivisors[i] < i) continue
var j = i * i
if (j > n) break
do {
largestPrimeDivisors[j] = i
j += i
} while (j <= n)
}
return largestPrimeDivisors
}
private fun divisorsOf(n: Int, largestPrimeDivisors: IntArray): IntArray {
if (n == 1) return intArrayOf(1)
val p = largestPrimeDivisors[n]
if (p == n) return intArrayOf(1, n)
var m = n / p
var counter = 2
while (m % p == 0) {
m /= p
counter++
}
val divisorsOfM = divisorsOf(m, largestPrimeDivisors)
val result = IntArray(divisorsOfM.size * counter)
for (i in divisorsOfM.indices) {
var d = divisorsOfM[i]
for (j in 0 until counter) {
result[i * counter + j] = d
d *= p
}
}
return result
}
| [
{
"class_path": "mikhail-dvorkin__algorithms__5ad1705/NumberTheoryKt.class",
"javap": "Compiled from \"numberTheory.kt\"\npublic final class NumberTheoryKt {\n private static final int[] largestPrimeDivisors(int);\n Code:\n 0: iconst_0\n 1: istore_2\n 2: iload_0\n 3: iconst_1\n ... |
teodor-vasile__aoc-2022-kotlin__2fcfe95/src/main/kotlin/Day009.kt | import kotlin.math.abs
import kotlin.math.sign
class Day009 {
companion object {
private val visitedTails = mutableSetOf<Point>()
}
var initialPoint = State(Point(0, 0), Point(0, 0))
fun moveTheSnake(input: List<String>): Int {
println(input.size)
input.forEach {
makeMove(initialPoint, it[2].digitToInt(), it[0].toPoint())
}
println(visitedTails)
return visitedTails.size
}
data class State(
val head: Point,
val tail: Point
)
data class Point(
val x: Int,
val y: Int
) {
infix operator fun plus(that: Point) =
Point(this.x + that.x, this.y + that.y)
fun moveTowards(other: Point): Point =
Point(
(other.x - x).sign + x,
(other.y - y).sign + y
)
}
private fun makeMove(initialState: State, numberOfTimes: Int, direction: Point): State {
var head = initialState.head
var tail = initialState.tail
repeat(numberOfTimes) {
// println("Step " + (it + 1) + " head $head and tail $tail")
head += direction
tail = moveTailAbs(tail, head)
initialPoint = State(head, tail)
// println("after move $initialPoint")
}
return State(head, tail)
}
private fun moveTailAbs(tailInitial: Point, headAfter: Point): Point {
val result =
if (abs(headAfter.x - abs(tailInitial.x)) <= 1 && abs(headAfter.y - abs(tailInitial.y)) <= 1) {
// if ((headAfter.x - tailInitial.x).absoluteValue <= 1 && (headAfter.y - tailInitial.y).absoluteValue <= 1) {
tailInitial
} else {
/*Point(
(headAfter.x - tailInitial.x).sign + tailInitial.x,
(headAfter.y - tailInitial.y).sign + tailInitial.y
)*/
tailInitial.moveTowards(headAfter)
}
visitedTails.add(result)
return result
}
private fun Char.toPoint(): Point {
return when (this) {
'R' -> Point(1, 0)
'L' -> Point(-1, 0)
'U' -> Point(0, 1)
'D' -> Point(0, -1)
else -> {
error("Value not valid")
}
}
}
}
| [
{
"class_path": "teodor-vasile__aoc-2022-kotlin__2fcfe95/Day009$Point.class",
"javap": "Compiled from \"Day009.kt\"\npublic final class Day009$Point {\n private final int x;\n\n private final int y;\n\n public Day009$Point(int, int);\n Code:\n 0: aload_0\n 1: invokespecial #9 ... |
teodor-vasile__aoc-2022-kotlin__2fcfe95/src/main/kotlin/Day11.kt |
class Day11 {
fun solvePart1(input: String): Int {
// parse the input
val monkeys = input.split("\n\n")
.map { monkey ->
Monkey(
items = getListOfItems(monkey),
operator = getOperator(monkey),
worryMultiplier = getWorryMultiplier(monkey),
divisibleBy = getDivisibleBy(monkey),
actionIsTrue = getActionIsTrue(monkey),
actionIsFalse = getActionIsFalse(monkey),
operationsPerformed = 0
)
}
repeat(20) {doOperations(monkeys)}
monkeys.forEach { println(it) }
println()
return monkeys.sortedByDescending { monkey -> monkey.operationsPerformed }
.take(2)
.map { it.operationsPerformed }
.fold(1) { acc, value -> acc * value }
}
private fun doOperations(monkeys: List<Monkey>) {
monkeys.forEach {monkey ->
if (monkey.items.isNotEmpty()) {
convertWorryMultiplier(monkey)
calculateWorryLevel(monkey)
monkeyGetsBored(monkey)
throwToMonkey(monkey, monkeys)
}
}
}
data class Monkey(
var items: ArrayDeque<Int>,
val operator: String,
val worryMultiplier: String,
val divisibleBy: Int,
val actionIsTrue: Int,
val actionIsFalse: Int,
var operationsPerformed: Int
)
private fun throwToMonkey(monkey: Monkey, monkeys: List<Monkey>) {
repeat(monkey.items.count()) {
if (monkeyGetsBored(monkey) % monkey.divisibleBy == 0) {
monkeys[monkey.actionIsTrue].items.addLast(monkeyGetsBored(monkey))
monkey.items.removeFirst()
monkey.operationsPerformed++
} else {
monkeys[monkey.actionIsFalse].items.addLast(monkeyGetsBored(monkey))
monkey.items.removeFirst()
monkey.operationsPerformed++
}
}
}
private fun monkeyGetsBored(monkey: Monkey): Int {
return calculateWorryLevel(monkey) / 3
}
private fun convertWorryMultiplier(monkey: Monkey): Int {
return if (monkey.worryMultiplier == "old") monkey.items.first() else monkey.worryMultiplier.toInt()
}
private fun calculateWorryLevel(monkey: Monkey): Int {
return when (monkey.operator) {
"*" -> monkey.items.first() * convertWorryMultiplier(monkey)
"/" -> monkey.items.first() / convertWorryMultiplier(monkey)
"+" -> monkey.items.first() + convertWorryMultiplier(monkey)
"-" -> monkey.items.first() - convertWorryMultiplier(monkey)
else -> error("invalid operation")
}
}
private fun getListOfItems(monkey: String): ArrayDeque<Int> {
val worryMultiplier =
monkey.lines()
.find { it.trim().startsWith("Starting") }
.let {
it!!.substring(18, it.length)
.split(",")
.map { it.trim().toInt() }
}
return ArrayDeque(worryMultiplier)
}
private fun getWorryMultiplier(monkey: String): String {
val worryMultiplier = monkey.lines()
.find { it.trim().startsWith("Operation") }
.let {
it!!.substring(25, it.length)
}
return worryMultiplier
}
private fun getOperator(monkey: String): String {
val worryMultiplier =
monkey.lines()
.find { it.trim().startsWith("Operation") }
.let {
it!!.substring(23, 24)
}
return worryMultiplier
}
private fun getDivisibleBy(lines: String): Int {
val regex = """Test: divisible by (\d+)""".toRegex()
val divisibleBy = regex.find(lines)
val (value) = divisibleBy!!.destructured
return value.toInt()
}
private fun getActionIsTrue(lines: String): Int {
val regex = """If true: throw to monkey (\d+)""".toRegex()
val divisibleBy = regex.find(lines)
val (value) = divisibleBy!!.destructured
return value.toInt()
}
private fun getActionIsFalse(lines: String): Int {
val regex = """If false: throw to monkey (\d+)""".toRegex()
val divisibleBy = regex.find(lines)
val (value) = divisibleBy!!.destructured
return value.toInt()
}
} | [
{
"class_path": "teodor-vasile__aoc-2022-kotlin__2fcfe95/Day11.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class Day11 {\n public Day11();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final ... |
teodor-vasile__aoc-2022-kotlin__2fcfe95/src/main/kotlin/Day005.kt | class Day005 {
data class Instruction(val count: Int, val source: Int, val target: Int)
fun part1(lines: List<String>): String {
val numberOfContainers = lines.first { it.trim().startsWith("1") }.trim().last().digitToInt()
val containers = List(numberOfContainers) { ArrayDeque<Char>() }
createContainers(lines, containers as MutableList<ArrayDeque<Char>>)
val instructions: List<Instruction> = getInstructions(lines)
instructions.forEach { instruction ->
repeat(instruction.count) {
if (containers[instruction.source - 1].isNotEmpty()) {
containers[instruction.target - 1].addFirst(containers[instruction.source - 1].removeFirst())
}
}
}
return containers.map { it.first() }.joinToString("")
}
fun part2(lines: List<String>): String {
val numberOfContainers = lines.first { it.trim().startsWith("1") }.trim().last().digitToInt()
val containers = List(numberOfContainers) { ArrayDeque<Char>() }.toMutableList()
createContainers(lines, containers)
val instructions: List<Instruction> = getInstructions(lines)
instructions.forEach { instr ->
containers[instr.target - 1].addAll(0, containers[instr.source - 1].take(instr.count))
repeat(instr.count) { containers[instr.source - 1].removeFirst() }
}
return containers.map { it.first() }.joinToString("")
}
private fun getInstructions(lines: List<String>): List<Instruction> {
val regex = """move (\d+) from (\d+) to (\d+)""".toRegex()
val instructions: List<Instruction> = lines
.dropWhile { !it.trim().startsWith("move") }
.map {
val matchResult = regex.find(it)
val (count, source, target) = matchResult!!.destructured
Instruction(count.toInt(), source.toInt(), target.toInt())
}
return instructions
}
private fun createContainers(
lines: List<String>,
containers: MutableList<ArrayDeque<Char>>,
) {
lines
.takeWhile { !it.trim().startsWith("1") }
.map { line ->
line.slice(1..line.length step 4)
.mapIndexed { containerNumber, value ->
if (value.isLetter()) containers[containerNumber].addLast(value)
}
}
}
}
| [
{
"class_path": "teodor-vasile__aoc-2022-kotlin__2fcfe95/Day005$Instruction.class",
"javap": "Compiled from \"Day005.kt\"\npublic final class Day005$Instruction {\n private final int count;\n\n private final int source;\n\n private final int target;\n\n public Day005$Instruction(int, int, int);\n Cod... |
teodor-vasile__aoc-2022-kotlin__2fcfe95/src/main/kotlin/Day003.kt | class Day003 {
fun part1(input: List<String>): Int {
var prioritiesSum = 0
for (rucksack in input) {
val firstHalf = rucksack.subSequence(0, rucksack.length / 2)
val lastHalf = rucksack.subSequence(rucksack.length / 2, rucksack.length)
for (char in lastHalf) {
if (firstHalf.contains(char)) {
val itemPriority = if (char.isLowerCase()) char.code - 96 else char.code - 38
prioritiesSum += itemPriority
break
}
}
}
return prioritiesSum
}
fun part2(input: List<String>): Int {
val chunkedInput = input.chunked(3)
var prioritiesSum = 0
for (chunk in chunkedInput) {
for (char in chunk[0]) {
if (chunk[1].contains(char) && chunk[2].contains(char)) {
val itemPriority = if (char.isLowerCase()) char.code - 96 else char.code - 38
prioritiesSum += itemPriority
break
}
}
}
return prioritiesSum
// check out zipWithNext() for this solution
// and intersect() method
// single() to return one value
}
}
| [
{
"class_path": "teodor-vasile__aoc-2022-kotlin__2fcfe95/Day003.class",
"javap": "Compiled from \"Day003.kt\"\npublic final class Day003 {\n public Day003();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public fi... |
teodor-vasile__aoc-2022-kotlin__2fcfe95/src/main/kotlin/Day004.kt | class Day004 {
var counter = 0
fun part1(elfPairs: List<List<String>>): Int {
for (elfPair in elfPairs) {
val firstElf = elfPair[0].split('-').map { it.toInt() }
val secondElf = elfPair[1].split('-').map { it.toInt() }
countContainingRanges(firstElf, secondElf)
}
return counter
}
fun part1Functional(elfPairs: List<List<String>>): Int {
elfPairs.forEach { elfPair ->
val firstElf = elfPair[0].split('-').map { it.toInt() }
val secondElf = elfPair[1].split('-').map { it.toInt() }
countContainingRanges(firstElf, secondElf)
}
return counter
}
private fun countContainingRanges(firstElf: List<Int>, secondElf: List<Int>) {
if ((firstElf[0] >= secondElf[0] && firstElf[1] <= secondElf[1]) ||
(secondElf[0] >= firstElf[0] && secondElf[1] <= firstElf[1])
) {
counter++
}
}
fun part2(elfPairs: List<List<String>>): Int {
for (elfPair in elfPairs) {
val firstElf = elfPair[0].split('-').map { it.toInt() }
val secondElf = elfPair[1].split('-').map { it.toInt() }
if ((firstElf[1] >= secondElf[0] && firstElf[1] <= secondElf[1]) ||
(secondElf[1] >= firstElf[0] && secondElf[1] <= firstElf[1])
) {
counter++
}
}
return counter
}
fun test() {
val pair = Pair("primu", "ultimu")
pair.first
}
// transform to Pair<IntRange, IntRange> -> you can use first and last in an IntRange
// substringBefore() method also useful
// .count() -> how many of the items in the set match the predicate
// https://todd.ginsberg.com/post/advent-of-code/2022/day4/
}
| [
{
"class_path": "teodor-vasile__aoc-2022-kotlin__2fcfe95/Day004.class",
"javap": "Compiled from \"Day004.kt\"\npublic final class Day004 {\n private int counter;\n\n public Day004();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ... |
SwampThingTom__AoC2022__a7825f7/21-MonkeyMath/MonkeyMath.kt | // Monkey Math
// https://adventofcode.com/2022/day/21
import java.io.File
import java.util.ArrayDeque
typealias MonkeyMap = Map<String, List<String>>
typealias MutableValuesMap = MutableMap<String, Long>
fun debugPrint(msg: String, show: Boolean = false) = if (show) { println(msg) } else {}
fun readInput(): List<String> = File("input.txt").useLines { it.toList() }
fun parseMonkey(line: String): Pair<String, List<String>> {
val components = line.split(": ")
val value = components[1].split(" ")
return components[0] to value
}
fun solvePart1(monkeys: MonkeyMap): Long {
val values: MutableValuesMap = mutableMapOf()
return solveFor("root", monkeys, values)
}
fun solvePart2(monkeys: MonkeyMap): Long {
val values: MutableValuesMap = mutableMapOf()
val rootExpr = monkeys["root"]!!
val (humnMonkey, otherMonkey) = whichMonkeyLeadsToHumn(rootExpr[0], rootExpr[2], monkeys)
val expectedValue = solveFor(otherMonkey, monkeys, values)
return solveForHumn(humnMonkey, expectedValue, monkeys, values)
}
fun whichMonkeyLeadsToHumn(lhs: String, rhs: String, monkeys: MonkeyMap): Pair<String, String> =
if (leadsToHumn(lhs, monkeys)) Pair(lhs, rhs) else Pair(rhs, lhs)
fun leadsToHumn(monkey: String, monkeys: MonkeyMap): Boolean {
if (monkey == "humn") return true
val expr = monkeys[monkey]!!
if (expr.size == 1) return false
return leadsToHumn(expr[0], monkeys) || leadsToHumn(expr[2], monkeys)
}
fun solveForHumn(monkey: String, expectedValue: Long, monkeys: MonkeyMap, values: MutableValuesMap): Long {
if (monkey == "humn") {
return expectedValue
}
val expr = monkeys[monkey]!!
assert(expr.size == 3)
val (humnMonkey, otherMonkey) = whichMonkeyLeadsToHumn(expr[0], expr[2], monkeys)
val knownValue = solveFor(otherMonkey, monkeys, values)
val newExpectedValue = evaluateInverse(expr[1], expectedValue, knownValue, humnMonkey == expr[0])
return solveForHumn(humnMonkey, newExpectedValue, monkeys, values)
}
fun solveFor(monkey: String, monkeys: MonkeyMap, values: MutableValuesMap): Long {
val value = values[monkey]
if (value is Long) {
return value
}
val expr = monkeys[monkey]!!
if (expr.size == 1) {
values[monkey] = expr[0].toLong()
return values[monkey]!!
}
assert(expr.size == 3)
val lhs = values[expr[0]] ?: solveFor(expr[0], monkeys, values)
val rhs = values[expr[2]] ?: solveFor(expr[2], monkeys, values)
values[monkey] = evaluate(expr[1], lhs, rhs)
return values[monkey]!!
}
fun evaluate(op: String, lhs: Long, rhs: Long): Long {
return when (op) {
"+" -> lhs + rhs
"-" -> lhs - rhs
"*" -> lhs * rhs
"/" -> lhs / rhs
else -> throw IllegalArgumentException("Unexpected operator.")
}
}
fun evaluateInverse(op: String, lhs: Long, rhs: Long, lhsIsHumn: Boolean): Long {
return when (op) {
"+" -> lhs - rhs
"-" -> if (lhsIsHumn) lhs + rhs else rhs - lhs
"*" -> lhs / rhs
"/" -> lhs * rhs
else -> throw IllegalArgumentException("Unexpected operator.")
}
}
fun main() {
val input = readInput()
val monkeys: MonkeyMap = input.map { parseMonkey(it) }.toMap()
val part1 = solvePart1(monkeys)
println("Part 1: $part1")
val part2 = solvePart2(monkeys)
println("Part 2: $part2")
}
| [
{
"class_path": "SwampThingTom__AoC2022__a7825f7/MonkeyMathKt.class",
"javap": "Compiled from \"MonkeyMath.kt\"\npublic final class MonkeyMathKt {\n public static final void debugPrint(java.lang.String, boolean);\n Code:\n 0: aload_0\n 1: ldc #9 // String msg\n ... |
thomasnield__traveling_salesman_demo__f6d2098/src/main/kotlin/CitiesAndDistances.kt | import java.util.concurrent.ThreadLocalRandom
data class CityPair(val city1: Int, val city2: Int)
class City(val id: Int, val name: String, val x: Double, val y: Double) {
override fun toString() = name
fun distanceTo(other: City) =CitiesAndDistances.distances[CityPair(id, other.id)]?:0.0
}
object CitiesAndDistances {
val citiesById = CitiesAndDistances::class.java.getResource("cities.csv").readText().lines()
.asSequence()
.map { it.split(",") }
.map { City(it[0].toInt(), it[1], it[2].toDouble(), it[3].toDouble()) }
.map { it.id to it }
.toMap()
val citiesByString = citiesById.entries.asSequence()
.map { it.value.name to it.value }
.toMap()
val cities = citiesById.values.toList()
val distances = CitiesAndDistances::class.java.getResource("distances.csv").readText().lines()
.asSequence()
.map { it.split(",") }
.map { CityPair(it[0].toInt(), it[1].toInt()) to it[2].toDouble() }
.toMap()
val distancesByStartCityId = distances.entries.asSequence()
.map { it.key.city1 to (cities[it.key.city2] to it.value) }
.groupBy({it.first},{it.second})
val randomCity get() = ThreadLocalRandom.current().nextInt(0,CitiesAndDistances.cities.count()).let { CitiesAndDistances.cities[it] }
}
operator fun Map<CityPair,String>.get(city1: Int, city2: Int) = get(CityPair(city1,city2))
operator fun Map<CityPair,String>.get(city1: City, city2: City) = get(CityPair(city1.id,city2.id))
| [
{
"class_path": "thomasnield__traveling_salesman_demo__f6d2098/CitiesAndDistancesKt.class",
"javap": "Compiled from \"CitiesAndDistances.kt\"\npublic final class CitiesAndDistancesKt {\n public static final java.lang.String get(java.util.Map<CityPair, java.lang.String>, int, int);\n Code:\n 0: alo... |
jacobprudhomme__advent-of-code-2022__9c2b080/src/day04/Day04.kt | import java.io.File
fun main() {
fun readInput(name: String) = File("src/day04", name)
.readLines()
fun processInput(line: String): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val (range1, range2, _) = line.split(",").map { range ->
range.split("-").map { it.toInt() }.let { (start, end, _) ->
Pair(start, end)
}
}
return Pair(range1, range2)
}
fun sign(n: Int): Int =
if (n > 0) { 1 }
else if (n < 0) { -1 }
else { 0 }
fun Pair<Int, Int>.contains(otherRange: Pair<Int, Int>): Boolean {
val startDiff = this.first - otherRange.first
val endDiff = this.second - otherRange.second
return (sign(startDiff) >= 0) and (sign(endDiff) <= 0)
}
fun Pair<Int, Int>.overlaps(otherRange: Pair<Int, Int>): Boolean =
(this.first <= otherRange.second) and (otherRange.first <= this.second)
fun part1(input: List<String>): Int {
var count = 0
for (line in input) {
val (range1, range2) = processInput(line)
if (range1.contains(range2) or range2.contains(range1)) {
++count
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
for (line in input) {
val (range1, range2) = processInput(line)
if (range1.overlaps(range2)) {
++count
}
}
return count
}
val input = readInput("input")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "jacobprudhomme__advent-of-code-2022__9c2b080/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String input\n 2: invokestatic #12 // Method ... |
jacobprudhomme__advent-of-code-2022__9c2b080/src/day05/Day05.kt | import java.io.File
typealias CrateStacks = Array<ArrayDeque<Char>>
typealias CraneProcedure = List<Triple<Int, Int, Int>>
fun main() {
fun readInput(name: String) = File("src/day05", name)
.readLines()
fun processInput(input: List<String>): Pair<CrateStacks, CraneProcedure> {
val craneProcedureStrs = input.takeLastWhile { it.isNotEmpty() }
val craneProcedure: CraneProcedure = craneProcedureStrs.map { procedure ->
Regex("\\d+")
.findAll(procedure)
.map(MatchResult::value)
.map(String::toInt)
.toList()
.let { (num, from, to, _) -> Triple(num, from-1, to-1) }
}
val (crateStacksStrs, stackNumbersStr) = input
.takeWhile { it.isNotEmpty() }
.let { Pair(it.dropLast(1).reversed(), it.last()) }
val numStacks = Regex("\\d+")
.findAll(stackNumbersStr)
.count()
val crateStacks = Array(numStacks) { ArrayDeque<Char>() }
for (line in crateStacksStrs) {
val cratesAtLevel = line.chunked(4) { it.filter(Char::isLetter) }
cratesAtLevel.forEachIndexed { i, crate ->
if (crate.isNotEmpty()) {
crateStacks[i].addLast(crate.first())
}
}
}
return Pair(crateStacks, craneProcedure)
}
fun part1(input: List<String>): String {
val (crateStacks, craneProcedure) = processInput(input)
for ((num, from, to) in craneProcedure) {
repeat(num) {
val crate = crateStacks[from].removeLast()
crateStacks[to].addLast(crate)
}
}
return crateStacks.map { it.last() }.joinToString("")
}
fun part2(input: List<String>): String {
val (crateStacks, craneProcedure) = processInput(input)
for ((num, from, to) in craneProcedure) {
val crates = crateStacks[from].takeLast(num)
repeat(num) {
crateStacks[from].removeLast()
}
crateStacks[to].addAll(crates)
}
return crateStacks.map { it.last() }.joinToString("")
}
val input = readInput("input")
println(part1(input))
println(part2(input))
} | [
{
"class_path": "jacobprudhomme__advent-of-code-2022__9c2b080/Day05Kt$main$processInput$craneProcedure$1$2.class",
"javap": "Compiled from \"Day05.kt\"\nfinal class Day05Kt$main$processInput$craneProcedure$1$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.l... |
jacobprudhomme__advent-of-code-2022__9c2b080/src/day11/Day11.kt | import java.io.File
import java.lang.IllegalArgumentException
import java.math.BigInteger
import java.util.PriorityQueue
class Monkey(
val heldItems: MutableList<Int>,
val applyOperation: (Int) -> BigInteger,
val decide: (Int) -> Int
) {
var inspectedItems: BigInteger = BigInteger.ZERO
fun inspect() { ++inspectedItems }
}
fun main() {
fun readInput(name: String) = File("src/day11", name)
.readLines()
fun iterateInput(input: List<String>) = sequence {
var currMonkey = input.takeWhile { it.isNotBlank() }.drop(1)
var rest = input.dropWhile { it.isNotBlank() }.drop(1)
while (currMonkey.isNotEmpty()) {
yield(currMonkey)
currMonkey = rest.takeWhile { it.isNotBlank() }
.let { if (it.isNotEmpty()) { it.drop(1) } else { it } }
rest = rest.dropWhile { it.isNotBlank() }
.let { if (it.isNotEmpty()) { it.drop(1) } else { it } }
}
}
fun processOperation(
opStr: String,
leftArg: String,
rightArg: String
): (Int) -> BigInteger {
val operation: (BigInteger, BigInteger) -> BigInteger = when (opStr) {
"+" -> { m, n -> m + n }
"*" -> { m, n -> m * n }
else -> throw IllegalArgumentException("We should never get here")
}
return if ((leftArg == "old") and (rightArg == "old")) {
{ n -> operation(n.toBigInteger(), n.toBigInteger()) }
} else if (leftArg == "old") {
{ n -> operation(n.toBigInteger(), rightArg.toBigInteger()) }
} else if (rightArg == "old") {
{ n -> operation(leftArg.toBigInteger(), n.toBigInteger()) }
} else {
{ _ -> operation(leftArg.toBigInteger(), rightArg.toBigInteger()) }
}
}
fun gcd(m: Int, n: Int): Int {
var a = m
var b = n
while (b > 0) {
val temp = b
b = a % b
a = temp
}
return a
}
fun lcm(m: Int, n: Int): Int = (m * n) / gcd(m, n)
fun processInput(input: List<String>): Pair<Array<Monkey>, Int> {
val monkeys = mutableListOf<Monkey>()
val testValues = mutableListOf<Int>()
for (monkeyStr in iterateInput(input)) {
val initItems = monkeyStr[0].substring(18).split(", ").map(String::toInt)
val (leftArg, op, rightArg, _) = monkeyStr[1].substring(19).split(" ")
val testValue = monkeyStr[2].substring(21).toInt()
val trueResult = monkeyStr[3].substring(29).toInt()
val falseResult = monkeyStr[4].substring(30).toInt()
val monkey = Monkey(
initItems.toMutableList(),
processOperation(op, leftArg, rightArg)
) { n -> if (n % testValue == 0) { trueResult } else { falseResult } }
monkeys.add(monkey)
testValues.add(testValue)
}
return Pair(monkeys.toTypedArray(), testValues.reduce { acc, value -> lcm(acc, value) })
}
fun doRound(monkeys: Array<Monkey>, spiraling: Boolean = false, lcm: Int = 1) {
for (monkey in monkeys) {
while (monkey.heldItems.isNotEmpty()) {
val currItem = monkey.heldItems.removeFirst()
monkey.inspect()
val worryLevel = monkey.applyOperation(currItem)
.let { if (spiraling) { it % lcm.toBigInteger() } else { it.div(3.toBigInteger()) } }
.toInt()
val monkeyToCatch = monkey.decide(worryLevel)
monkeys[monkeyToCatch].heldItems.add(worryLevel)
}
}
}
fun multiplyTwoLargest(monkeys: Array<Monkey>): BigInteger {
val monkeysByInspectedElements = PriorityQueue(monkeys.map { -it.inspectedItems }) // Induce max-queue
return monkeysByInspectedElements.poll() * monkeysByInspectedElements.poll()
}
fun part1(input: List<String>): BigInteger {
val (monkeys, _) = processInput(input)
repeat(20) {
doRound(monkeys)
}
return multiplyTwoLargest(monkeys)
}
fun part2(input: List<String>): BigInteger {
val (monkeys, lcm) = processInput(input)
repeat(10000) {
doRound(monkeys, spiraling=true, lcm=lcm)
}
return multiplyTwoLargest(monkeys)
}
val input = readInput("input")
println(part1(input))
println(part2(input))
} | [
{
"class_path": "jacobprudhomme__advent-of-code-2022__9c2b080/Day11Kt$main$iterateInput$1.class",
"javap": "Compiled from \"Day11.kt\"\nfinal class Day11Kt$main$iterateInput$1 extends kotlin.coroutines.jvm.internal.RestrictedSuspendLambda implements kotlin.jvm.functions.Function2<kotlin.sequences.SequenceSc... |
jacobprudhomme__advent-of-code-2022__9c2b080/src/day03/Day03.kt | import java.io.File
fun main() {
fun readInput(name: String) = File("src/day03", name)
.readLines()
fun getItemPriority(item: Char): Int =
if (item.isLowerCase()) {
item.code - 96
} else {
item.code - 38
}
fun part1(input: List<String>): Int {
var sumOfPriorities = 0
for (line in input) {
val numItemsInFirstRucksack = line.length / 2
val itemsInFirstRucksack = line.take(numItemsInFirstRucksack).toSet()
val seenInSecondRucksack = mutableSetOf<Char>()
for (item in line.takeLast(numItemsInFirstRucksack)) {
if (itemsInFirstRucksack.contains(item) and !seenInSecondRucksack.contains(item)) {
sumOfPriorities += getItemPriority(item)
seenInSecondRucksack.add(item)
}
}
}
return sumOfPriorities
}
fun part2(input: List<String>): Int {
var sumOfPriorities = 0
var group = arrayListOf<Set<Char>>()
for (line in input) {
group.add(line.toSet())
if (group.size == 3) {
val itemsCommonToAllRucksacks = group.reduce { acc, currRucksack -> acc.intersect(currRucksack) }
val item = itemsCommonToAllRucksacks.first()
sumOfPriorities += getItemPriority(item)
group = arrayListOf()
}
}
return sumOfPriorities
}
val input = readInput("input")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "jacobprudhomme__advent-of-code-2022__9c2b080/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String input\n 2: invokestatic #12 // Method ... |
jacobprudhomme__advent-of-code-2022__9c2b080/src/day09/Day09.kt | import java.io.File
import java.lang.IllegalArgumentException
import kotlin.math.abs
typealias Pos = Pair<Int, Int>
enum class Direction {
UP,
RIGHT,
DOWN,
LEFT,
}
fun main() {
fun readInput(name: String) = File("src/day09", name)
.readLines()
fun convertToDirection(dirStr: String): Direction =
when (dirStr) {
"U" -> Direction.UP
"R" -> Direction.RIGHT
"D" -> Direction.DOWN
"L" -> Direction.LEFT
else -> throw IllegalArgumentException("We should never get here")
}
fun moveHead(headPos: Pos, dir: Direction): Pos =
when (dir) {
Direction.UP -> headPos.let { (x, y) -> Pair(x, y+1) }
Direction.RIGHT -> headPos.let { (x, y) -> Pair(x+1, y) }
Direction.DOWN -> headPos.let { (x, y) -> Pair(x, y-1) }
Direction.LEFT -> headPos.let { (x, y) -> Pair(x-1, y) }
}
fun moveTail(headPos: Pos, tailPos: Pos): Pos {
val horizontalDist = abs(headPos.first - tailPos.first)
val verticalDist = abs(headPos.second - tailPos.second)
return if ((horizontalDist == 2) or (verticalDist == 2)) {
if (horizontalDist == 0) {
tailPos.let { (x, y) -> Pair(x, (y + headPos.second).div(2)) }
} else if (verticalDist == 0) {
tailPos.let { (x, y) -> Pair((x + headPos.first).div(2), y) }
} else if (horizontalDist == 1) {
tailPos.let { (_, y) -> Pair(headPos.first, (y + headPos.second).div(2)) }
} else if (verticalDist == 1) {
tailPos.let { (x, _) -> Pair((x + headPos.first).div(2), headPos.second) }
} else {
tailPos.let { (x, y) -> Pair((x + headPos.first).div(2), (y + headPos.second).div(2)) }
}
} else {
tailPos
}
}
fun move(headPos: Pos, tailPos: Pos, dir: Direction): Pair<Pos, Pos> {
val nextHeadPos = moveHead(headPos, dir)
val nextTailPos = moveTail(nextHeadPos, tailPos)
return Pair(nextHeadPos, nextTailPos)
}
fun part1(input: List<String>): Int {
var currHeadPosition = Pair(0, 0)
var currTailPosition = Pair(0, 0)
val seenPositions = mutableSetOf(currTailPosition)
for (line in input) {
val (dir, steps) = line.split(" ").let { (dirStr, stepsStr, _) ->
Pair(convertToDirection(dirStr), stepsStr.toInt())
}
repeat(steps) {
val (nextHeadPosition, nextTailPosition) = move(currHeadPosition, currTailPosition, dir)
currHeadPosition = nextHeadPosition
currTailPosition = nextTailPosition
seenPositions.add(currTailPosition)
}
}
return seenPositions.count()
}
fun part2(input: List<String>): Int {
val currPositions = MutableList(10) { Pair(0, 0) }
val seenPositions = mutableSetOf(currPositions.last())
for (line in input) {
val (dir, steps) = line.split(" ").let { (dirStr, stepsStr, _) ->
Pair(convertToDirection(dirStr), stepsStr.toInt())
}
repeat(steps) {
currPositions[0] = moveHead(currPositions[0], dir)
for (knotIndex in currPositions.indices.drop(1)) {
currPositions[knotIndex] = moveTail(currPositions[knotIndex-1], currPositions[knotIndex])
}
seenPositions.add(currPositions.last())
}
}
return seenPositions.count()
}
val input = readInput("input")
println(part1(input))
println(part2(input))
} | [
{
"class_path": "jacobprudhomme__advent-of-code-2022__9c2b080/Day09Kt$WhenMappings.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method Dire... |
jacobprudhomme__advent-of-code-2022__9c2b080/src/day02/Day02.kt | import java.io.File
import java.lang.IllegalArgumentException
enum class Result(val score: Int) {
LOSE(0),
DRAW(3),
WIN(6),
}
enum class Move(val value: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun against(other: Move): Result = when (other.value) {
((value + 1) % 3) + 1 -> Result.WIN
value -> Result.DRAW
else -> Result.LOSE
}
fun obtainsAgainst(result: Result): Move = when (result) {
Result.WIN -> fromValue((value % 3) + 1)
Result.LOSE -> fromValue(((value + 1) % 3) + 1)
else -> this
}
companion object {
fun fromValue(value: Int): Move = when (value) {
1 -> ROCK
2 -> PAPER
3 -> SCISSORS
else -> throw IllegalArgumentException("We should never get here")
}
}
}
fun main() {
fun readInput(name: String) = File("src/day02", name)
.readLines()
fun decryptMove(encryptedMove: String): Move = when (encryptedMove) {
"A", "X" -> Move.ROCK
"B", "Y" -> Move.PAPER
"C", "Z" -> Move.SCISSORS
else -> throw IllegalArgumentException("We should never get here")
}
fun decryptResult(encryptedResult: String): Result = when (encryptedResult) {
"X" -> Result.LOSE
"Y" -> Result.DRAW
"Z" -> Result.WIN
else -> throw IllegalArgumentException("We should never get here")
}
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val (theirMove, myMove, _) = line.split(" ").map { decryptMove(it) }
score += myMove.value + myMove.against(theirMove).score
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (line in input) {
val (theirMove, myResult) = line.split(" ").let { (theirMoveStr, myResultStr, _) ->
Pair(decryptMove(theirMoveStr), decryptResult(myResultStr))
}
score += theirMove.obtainsAgainst(myResult).value + myResult.score
}
return score
}
val input = readInput("input")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "jacobprudhomme__advent-of-code-2022__9c2b080/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String input\n 2: invokestatic #12 // Method ... |
jacobprudhomme__advent-of-code-2022__9c2b080/src/day08/Day08.kt | import java.io.File
class Matrix<T>(private val mtx: List<List<T>>) {
fun dimensions(): Pair<Int, Int> = Pair(mtx.size, mtx[0].size)
fun getRow(rowIdx: Int): List<T> = mtx[rowIdx]
fun getColumn(colIdx: Int): List<T> = mtx.map { row -> row[colIdx] }
fun forEachIndexed(f: (rowIndex: Int, columnIndex: Int, T) -> Unit) {
this.mtx.forEachIndexed { rowIndex, row ->
row.forEachIndexed { columnIndex, item ->
f(rowIndex, columnIndex, item)
}
}
}
}
fun main() {
fun readInput(name: String) = File("src/day08", name)
.readLines()
fun smallerToLeft(mtx: Matrix<Int>, thisTree: Int, pos: Pair<Int, Int>): Int {
val row = mtx.getRow(pos.first).subList(0, pos.second)
return row.takeLastWhile { tree -> tree < thisTree }.count()
}
fun smallerToRight(mtx: Matrix<Int>, thisTree: Int, pos: Pair<Int, Int>): Int {
val row = mtx.getRow(pos.first).subList(pos.second + 1, mtx.dimensions().second)
return row.takeWhile { tree -> tree < thisTree }.count()
}
fun smallerAbove(mtx: Matrix<Int>, thisTree: Int, pos: Pair<Int, Int>): Int {
val col = mtx.getColumn(pos.second).subList(0, pos.first)
return col.takeLastWhile { tree -> tree < thisTree }.count()
}
fun smallerBelow(mtx: Matrix<Int>, thisTree: Int, pos: Pair<Int, Int>): Int {
val col = mtx.getColumn(pos.second).subList(pos.first + 1, mtx.dimensions().first)
return col.takeWhile { tree -> tree < thisTree }.count()
}
fun isVisibleFromADirection(mtx: Matrix<Int>, tree: Int, pos: Pair<Int, Int>): Boolean {
val (height, width) = mtx.dimensions()
return ((smallerToLeft(mtx, tree, pos) == pos.second)
or (smallerToRight(mtx, tree, pos) == width - pos.second - 1)
or (smallerAbove(mtx, tree, pos) == pos.first)
or (smallerBelow(mtx, tree, pos) == height - pos.first - 1))
}
fun calculateVisibilityScore(mtx: Matrix<Int>, tree: Int, pos: Pair<Int, Int>): Int {
val (row, col) = pos
val (height, width) = mtx.dimensions()
var stl = smallerToLeft(mtx, tree, pos)
if (stl < col) { ++stl }
var str = smallerToRight(mtx, tree, pos)
if (str < width - col - 1) { ++str }
var sa = smallerAbove(mtx, tree, pos)
if (sa < row) { ++sa }
var sb = smallerBelow(mtx, tree, pos)
if (sb < height - row - 1) { ++sb }
return (stl * str * sa * sb)
}
fun part1(input: List<String>): Int {
val grid = Matrix(input.map { row -> row.map(Char::digitToInt) })
val treesSeen = mutableSetOf<Pair<Int, Int>>()
var count = 0
grid.forEachIndexed { rowIdx, colIdx, tree ->
if ((Pair(rowIdx, colIdx) !in treesSeen) and isVisibleFromADirection(grid, tree, Pair(rowIdx, colIdx))) {
count += 1
treesSeen.add(Pair(rowIdx, colIdx))
}
}
return count
}
fun part2(input: List<String>): Int {
val grid = Matrix(input.map { row -> row.map(Char::digitToInt) })
val treesSeen = mutableSetOf<Pair<Int, Int>>()
var maxScoreSeenSoFar = 0
grid.forEachIndexed { rowIdx, colIdx, tree ->
if (Pair(rowIdx, colIdx) !in treesSeen) {
val visibilityScore = calculateVisibilityScore(grid, tree, Pair(rowIdx, colIdx))
if (visibilityScore > maxScoreSeenSoFar) {
maxScoreSeenSoFar = visibilityScore
}
treesSeen.add(Pair(rowIdx, colIdx))
}
}
return maxScoreSeenSoFar
}
val input = readInput("input")
println(part1(input))
println(part2(input))
} | [
{
"class_path": "jacobprudhomme__advent-of-code-2022__9c2b080/Day08Kt.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String input\n 2: invokestatic #12 // Method ... |
jacobprudhomme__advent-of-code-2022__9c2b080/src/day01/Day01.kt | import java.io.File
fun main() {
fun readInput(name: String) = File("src/day01", name)
.readLines()
fun part1(input: List<String>): Int {
var maxSoFar = 0
var currentSum = 0
for (line in input) {
if (line.isEmpty()) {
if (currentSum > maxSoFar) {
maxSoFar = currentSum
}
currentSum = 0
} else {
currentSum += line.toInt()
}
}
return if (currentSum > maxSoFar) currentSum else maxSoFar
}
fun part2(input: List<String>): Int {
val maxesSoFar = intArrayOf(0, 0, 0)
var currentSum = 0
for (line in input) {
if (line.isEmpty()) {
val (idx, smallestMaxSoFar) = maxesSoFar.withIndex().minBy { (_, maxVal) -> maxVal }
if (currentSum > smallestMaxSoFar) {
maxesSoFar[idx] = currentSum
}
currentSum = 0
} else {
currentSum += line.toInt()
}
}
val (idx, smallestMaxSoFar) = maxesSoFar.withIndex().minBy { (_, maxVal) -> maxVal }
if (currentSum > smallestMaxSoFar) {
maxesSoFar[idx] = currentSum
}
return maxesSoFar.sum()
}
val input = readInput("input")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "jacobprudhomme__advent-of-code-2022__9c2b080/Day01Kt.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String input\n 2: invokestatic #12 // Method ... |
nothingelsematters__university__d442a3d/advanced-algorithms/kotlin/src/bO2CMax.kt | import java.io.File
import java.util.Scanner
fun scheduleO2CMax(p1: List<Long>, p2: List<Long>): Pair<Long, List<List<Long>>> {
fun fill(schedule: MutableList<Long>, times: List<Long>, indices: Sequence<Int>, init: Long = 0) =
indices.fold(init) { sum, index ->
schedule[index] = sum
sum + times[index]
}
fun i() = p1.asSequence().withIndex().filter { (index, i) -> i <= p2[index] }.map { it.index }
fun j() = p1.asSequence().withIndex().filter { (index, i) -> i > p2[index] }.map { it.index }
val x = i().maxByOrNull { p1[it] }
val y = j().maxByOrNull { p2[it] }
return if (x == null || y != null && p1[x] < p2[y]) {
val (cMax, schedule) = scheduleO2CMax(p2, p1)
cMax to listOf(schedule[1], schedule[0])
} else {
val cMax = maxOf(p1.sum(), p2.sum(), p1.asSequence().zip(p2.asSequence()).maxOf { (a, b) -> a + b })
val first = MutableList(p1.size) { 0L }
fill(first, p1, i() - x)
fill(first, p1, sequenceOf(x), cMax - p1[x])
fill(first, p1, j(), cMax - p1[x] - j().sumOf { p1[it] })
val second = MutableList(p2.size) { 0L }
fill(second, p2, sequenceOf(x))
fill(second, p2, i() - x, p2[x])
fill(second, p2, j(), cMax - j().sumOf { p2[it] })
cMax to listOf(first, second)
}
}
fun main() {
val input = Scanner(File("o2cmax.in").bufferedReader())
val n = input.nextInt()
val p1 = List(n) { input.nextLong() }
val p2 = List(n) { input.nextLong() }
val (c, schedule) = scheduleO2CMax(p1, p2)
File("o2cmax.out").printWriter().use { output ->
output.println(c)
schedule.forEach { line ->
line.forEach { output.print("$it ") }
output.println()
}
}
}
| [
{
"class_path": "nothingelsematters__university__d442a3d/BO2CMaxKt.class",
"javap": "Compiled from \"bO2CMax.kt\"\npublic final class BO2CMaxKt {\n public static final kotlin.Pair<java.lang.Long, java.util.List<java.util.List<java.lang.Long>>> scheduleO2CMax(java.util.List<java.lang.Long>, java.util.List<j... |
nothingelsematters__university__d442a3d/advanced-algorithms/kotlin/src/lPIntreeP1LMax.kt | import java.io.File
import java.util.Scanner
fun schedulePIntreeP1LMax(
deadlines: MutableList<Int>,
m: Int,
fromTo: Map<Int, Int>,
toFrom: Map<Int, List<Int>>,
): Pair<Int, List<Int>> {
val i = deadlines.indices.find { it !in fromTo }!!
val deque = ArrayDeque<Int>()
deque += i
while (deque.isNotEmpty()) {
val j = deque.removeFirst()
toFrom[j].orEmpty().forEach { k ->
deadlines[k] = minOf(deadlines[k], deadlines[j] - 1)
deque.addLast(k)
}
}
var f = 0
val r = MutableList(deadlines.size) { 0 }
val q = MutableList(deadlines.size) { 0 }
val x = MutableList(deadlines.size) { 0 }
deadlines.asSequence().withIndex().sortedBy { it.value }.map { it.index }.forEach { i ->
val t = maxOf(r[i], f)
x[i] = t
q[t] += 1
if (q[t] == m) {
f = t + 1
}
fromTo[i]?.let { j -> r[j] = maxOf(r[j], t + 1) }
}
val l = deadlines.asSequence().zip(x.asSequence()).maxOf { (d, c) -> c + 1 - d }
return l to x
}
fun main() {
val input = Scanner(File("pintreep1l.in").bufferedReader())
val n = input.nextInt()
val m = input.nextInt()
val deadlines = MutableList(n) { input.nextInt() }
val fromTo = mutableMapOf<Int, Int>()
val toFrom = mutableMapOf<Int, MutableList<Int>>()
repeat(n - 1) {
val from = input.nextInt() - 1
val to = input.nextInt() - 1
fromTo[from] = to
toFrom.getOrPut(to) { mutableListOf() }.add(from)
}
val (lMax, schedule) = schedulePIntreeP1LMax(deadlines, m, fromTo, toFrom)
File("pintreep1l.out").printWriter().use { output ->
output.println(lMax)
schedule.forEach { output.print("$it ") }
}
}
| [
{
"class_path": "nothingelsematters__university__d442a3d/LPIntreeP1LMaxKt$schedulePIntreeP1LMax$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class LPIntreeP1LMaxKt$schedulePIntreeP1LMax$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public LPIntreeP1LMaxK... |
nothingelsematters__university__d442a3d/advanced-algorithms/kotlin/src/fP1PrecFMax.kt | import java.io.File
import java.math.BigInteger
import java.util.Scanner
private fun scheduleP1PrecFMax(
times: List<Int>,
functions: List<(Int) -> BigInteger>,
prec: Map<Int, List<Int>>,
): Pair<BigInteger, List<Int>> {
val n = times.size
val children = MutableList(n) { 0 }
prec.forEach { (_, row) -> row.forEach { i -> children[i] += 1 } }
val excluded = (0 until n).toMutableSet()
var p = times.sum()
val reverseSchedule = MutableList(n) { 0 }
for (k in n - 1 downTo 0) {
val j = excluded.asSequence().filter { children[it] == 0 }.minBy { functions[it](p) }
excluded.remove(j)
reverseSchedule[k] = j
p -= times[j]
prec[j]?.forEach { children[it] -= 1 }
}
val schedule = MutableList(n) { 0 }
reverseSchedule.fold(0) { sum, it ->
schedule[it] = sum
sum + times[it]
}
val fMaxMin = (0 until n)
.maxOfOrNull { functions[it](schedule[it] + times[it]) } ?: 0.toBigInteger()
return fMaxMin to schedule
}
fun main() {
val inputFile = Scanner(File("p1precfmax.in").bufferedReader())
val n = inputFile.nextInt()
val times = List(n) { inputFile.nextInt() }
val functions = List(n) {
val m = inputFile.nextInt()
val coefficients = List(m + 1) { inputFile.nextInt() };
{ x: Int ->
coefficients.asSequence()
.withIndex()
.sumOf { (i, it) -> x.toBigInteger().pow(coefficients.size - 1 - i) * it.toBigInteger() }
}
}
val d = inputFile.nextInt()
val prec = buildMap {
for (i in 0 until d) {
val from = inputFile.nextInt() - 1
val to = inputFile.nextInt() - 1
val list: MutableList<Int> = getOrPut(to) { mutableListOf() }
list += from
}
}
val (fMaxMin, schedule) = scheduleP1PrecFMax(times, functions, prec)
File("p1precfmax.out").printWriter().use { output ->
output.println(fMaxMin.toString())
for (i in schedule) {
output.print("$i ")
}
}
}
| [
{
"class_path": "nothingelsematters__university__d442a3d/FP1PrecFMaxKt.class",
"javap": "Compiled from \"fP1PrecFMax.kt\"\npublic final class FP1PrecFMaxKt {\n private static final kotlin.Pair<java.math.BigInteger, java.util.List<java.lang.Integer>> scheduleP1PrecFMax(java.util.List<java.lang.Integer>, jav... |
nothingelsematters__university__d442a3d/advanced-algorithms/kotlin/src/h1PrecPmtnRFMax.kt | import java.io.File
import java.util.Scanner
private fun <T> MutableList<T>.addAll(vararg ts: T) = addAll(ts)
data class Job(
val time: Long,
var release: Long,
val index: Int,
val f: (Long) -> Long,
val times: MutableList<Long> = mutableListOf(),
)
private data class Block(val start: Long, var time: Long = 0, val jobs: MutableList<Job> = mutableListOf()) {
val end: Long
get() = start + time
fun add(job: Job) {
jobs += job
time += job.time
}
}
private fun topologicalSort(jobs: List<Job>, edges: List<List<Int>>, reverseEdges: List<List<Int>>): List<Job> {
fun depthFirstSearch(
edges: List<List<Int>>,
jobs: List<Job>,
currentVertex: Int,
result: MutableList<Job>,
used: MutableSet<Int>,
) {
if (currentVertex in used) return
used += currentVertex
edges[currentVertex]
.asSequence()
.filter { it !in used }
.forEach { depthFirstSearch(edges, jobs, it, result, used) }
result += jobs[currentVertex]
}
val result = mutableListOf<Job>()
val used = mutableSetOf<Int>()
jobs.indices
.asSequence()
.filter { it !in used && reverseEdges[it].isEmpty() }
.forEach { depthFirstSearch(edges, jobs, it, result, used) }
return result
}
private fun createBlocks(jobs: List<Job>): List<Block> = buildList {
jobs.forEach { job ->
val block = if (lastOrNull()?.let { it.end >= job.release } == true) {
last()
} else {
Block(job.release).also { add(it) }
}
block.add(job)
}
}
private fun decompose(edges: List<List<Int>>, block: Block): Long {
val end = block.end
val used = mutableSetOf<Int>()
val minimumJobIndex = block.jobs
.indices
.reversed()
.asSequence()
.map { it to block.jobs[it] }
.filter { (_, job) -> edges[job.index].none { it in used }.also { used += job.index } }
.minBy { (_, job) -> job.f(end) }
.first
val deleted = block.jobs[minimumJobIndex]
block.jobs.removeAt(minimumJobIndex)
val newBlocks = createBlocks(block.jobs)
return if (newBlocks.isEmpty()) {
deleted.times.addAll(block.start, block.end)
deleted.f(end)
} else {
if (block.start < newBlocks.first().start) {
deleted.times.addAll(block.start, newBlocks.first().start)
}
newBlocks.asSequence()
.windowed(2)
.map { (left, right) -> left.end to right.start }
.filter { (start, end) -> start < end }
.forEach { deleted.times.addAll(it.toList()) }
if (block.end > newBlocks.last().end) {
deleted.times.addAll(newBlocks.last().end, block.end)
}
maxOf(deleted.f(end), newBlocks.maxOf { decompose(edges, it) })
}
}
fun schedule1PrecPmtnRFMax(jobs: List<Job>, edges: List<List<Int>>, reverseEdges: List<List<Int>>): Long {
val topologicalSorted = topologicalSort(jobs, edges, reverseEdges)
topologicalSorted.asReversed().forEach { job ->
edges[job.index]
.asSequence()
.map { jobs[it] }
.forEach { it.release = maxOf(it.release, job.release + job.time) }
}
return createBlocks(topologicalSorted.sortedBy { it.release }).maxOf { decompose(edges, it) }
}
fun main() {
val scanner = Scanner(File("p1precpmtnrifmax.in").bufferedReader())
val n = scanner.nextInt()
val times = List(n) { scanner.nextLong() }
val releases = List(n) { scanner.nextLong() }
val m = scanner.nextInt()
val edges = List(n) { mutableListOf<Int>() }
val reverseEdges = List(n) { mutableListOf<Int>() }
repeat(m) {
val (from, to) = List(2) { scanner.nextInt() - 1 }
edges[from] += to
reverseEdges[to] += from
}
val jobs = List(n) {
val (a, b, c) = List(3) { scanner.nextLong() }
Job(times[it], releases[it], it, { time -> a * time * time + b * time + c })
}
val fMax = schedule1PrecPmtnRFMax(jobs, edges, reverseEdges)
File("p1precpmtnrifmax.out").printWriter().use { output ->
output.println(fMax)
jobs.forEach { job ->
output.write("${job.times.size / 2} ")
job.times.forEach { output.print("$it ") }
output.println()
}
}
}
| [
{
"class_path": "nothingelsematters__university__d442a3d/H1PrecPmtnRFMaxKt$schedule1PrecPmtnRFMax$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class H1PrecPmtnRFMaxKt$schedule1PrecPmtnRFMax$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public H1PrecPmtnR... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day15.kt | import kotlin.math.abs
object Day15 {
const val EXPECTED_PART1_CHECK_ANSWER = 26
const val EXPECTED_PART2_CHECK_ANSWER = 56000011L
const val PART1_CHECK_ROW = 10
const val PART1_ROW = 2_000_000
const val PART2_CHECK_MAX = 20
const val PART2_MAX = 4_000_000
const val PART2_MULTIPLY_VALUE = 4_000_000
}
fun main() {
fun String.parseSensorAndBeaconCoordinatess(): Pair<Coordinates, Coordinates> {
val (sensorX, sensorY, beaconX, beaconY) = Regex("Sensor at x=([-\\d]+), y=([-\\d]+): closest beacon is at x=([-\\d]+), y=([-\\d]+)")
.matchEntire(this)
?.destructured ?: error("Should match regex")
return Coordinates(sensorX.toInt(), sensorY.toInt()) to Coordinates(beaconX.toInt(), beaconY.toInt())
}
data class RowInfo(val positionsCovered: Int, val notCovered: Coordinates?)
fun rowInfo(
row: Int,
gridMin: Int,
gridMax: Int,
sensorAndBeaconCoordinates: List<Pair<Coordinates, Coordinates>>
): RowInfo {
val coveredRangesOnRow = mutableListOf<IntRange>()
for (sensorAndBeaconCoordinate in sensorAndBeaconCoordinates) {
val sensorLocation = sensorAndBeaconCoordinate.first
val beaconLocation = sensorAndBeaconCoordinate.second
val distance = abs(sensorLocation.x - beaconLocation.x) + abs(sensorLocation.y - beaconLocation.y)
val positionsCoveredAtSensorRow = distance * 2 + 1
val yDistanceToCheckRow = abs(sensorLocation.y - row)
val positionsCoveredAtCheckRow = positionsCoveredAtSensorRow - yDistanceToCheckRow * 2
if (positionsCoveredAtCheckRow > 0) {
val xFrom = maxOf(gridMin, sensorLocation.x - (positionsCoveredAtCheckRow / 2))
val xTo = minOf(gridMax, sensorLocation.x + (positionsCoveredAtCheckRow / 2))
val range = xFrom..xTo
coveredRangesOnRow.add(range)
val overlappingRanges =
coveredRangesOnRow
.filter { range.first in it || range.last in it || it.first in range || it.last in range }
if (overlappingRanges.isNotEmpty()) {
val mergedRange = overlappingRanges.reduce { acc, intRange ->
minOf(acc.first, intRange.first)..maxOf(
acc.last,
intRange.last
)
}
coveredRangesOnRow.add(mergedRange)
overlappingRanges.forEach { coveredRangesOnRow.remove(it) }
}
}
}
val coveredCount = coveredRangesOnRow.sumOf { it.count() }
val notCovered = if (gridMax - gridMin - coveredCount >= 0) {
// find in ranges the open position..
if (coveredRangesOnRow.size == 1) {
if (coveredRangesOnRow[0].first > gridMin) {
gridMin
} else {
gridMax
}
} else {
coveredRangesOnRow
.sortedBy { it.first }
.windowed(2)
.first { it.first().last + 1 < it[1].first }
.let { it.first().last + 1 }
}
} else null
return RowInfo(coveredCount, if (notCovered != null) Coordinates(notCovered, row) else null)
}
fun part1(input: List<String>, checkRow: Int): Int {
val sensorAndBeaconCoordinates = input.map(String::parseSensorAndBeaconCoordinatess)
val (min, max) = sensorAndBeaconCoordinates.flatMap { listOf(it.first, it.second) }.findMinAndMax()
val beaconCoordinates = sensorAndBeaconCoordinates.map { it.second }
val beaconsOnCheckRow = beaconCoordinates.toSet().filter { it.y == checkRow }.size
return rowInfo(checkRow, min.x, max.x, sensorAndBeaconCoordinates).positionsCovered - beaconsOnCheckRow
}
fun part2(input: List<String>, max: Int): Long {
val sensorAndBeaconCoordinates = input.map(String::parseSensorAndBeaconCoordinatess)
var notCoveredRow: RowInfo? = null
for (row in max downTo 0) {
val rowInfo = rowInfo(row, 0, max, sensorAndBeaconCoordinates)
println("Row $row")
if (rowInfo.notCovered != null) {
notCoveredRow = rowInfo
break
}
}
if (notCoveredRow != null) {
return notCoveredRow.notCovered!!.x.toLong() * Day15.PART2_MULTIPLY_VALUE + notCoveredRow.notCovered!!.y
}
return -1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
println("Checking")
check(part1(testInput, Day15.PART1_CHECK_ROW) == Day15.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput, Day15.PART2_CHECK_MAX) == Day15.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
println("On real data")
val input = readInput("Day15")
println(part1(input, Day15.PART1_ROW))
println(part2(input, Day15.PART2_MAX))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day15.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15 {\n public static final Day15 INSTANCE;\n\n public static final int EXPECTED_PART1_CHECK_ANSWER;\n\n public static final long EXPECTED_PART2_CHECK_ANSWER;\n\n public static f... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day19.kt | object Day19 {
const val EXPECTED_PART1_CHECK_ANSWER = 33
const val EXPECTED_PART2_CHECK_ANSWER = 3472
val BLUEPRINT_REGEX =
Regex("Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.")
const val PART1_MINUTES = 24
}
enum class RobotCurrency {
ORE, CLAY, OBSIDIAN
}
enum class RobotType {
ORE_COLLECTOR, CLAY_COLLECTOR, OBSIDIAN_COLLECTOR, GEODE_CRACKING
}
data class RobotBuildCost(val amount: Int, val currency: RobotCurrency)
data class Blueprint(
val id: Int,
val buildCosts: Map<RobotType, Set<RobotBuildCost>>,
)
data class CollectingState(
val minutesDone: Int = 0,
val orePerMinute: Int = 1,
val clayPerMinute: Int = 0,
val obsidianPerMinute: Int = 0,
val geoCrackedPerMinute: Int = 0,
val ore: Int = 0,
val clay: Int = 0,
val obs: Int = 0,
val geoCracked: Int = 0,
)
fun main() {
fun List<String>.parseBlueprints() =
map {
val (id, oreRobotOre, clayRobotOre, obsRobotOre, obsRobotClay, geoRobotOre, geoRobotObs) = Day19.BLUEPRINT_REGEX.matchEntire(
it
)?.destructured ?: error("Oops")
Blueprint(
id.toInt(),
mapOf(
RobotType.ORE_COLLECTOR to setOf(RobotBuildCost(oreRobotOre.toInt(), RobotCurrency.ORE)),
RobotType.CLAY_COLLECTOR to setOf(RobotBuildCost(clayRobotOre.toInt(), RobotCurrency.ORE)),
RobotType.OBSIDIAN_COLLECTOR to setOf(RobotBuildCost(obsRobotOre.toInt(), RobotCurrency.ORE), RobotBuildCost(obsRobotClay.toInt(), RobotCurrency.CLAY)),
RobotType.GEODE_CRACKING to setOf(RobotBuildCost(geoRobotOre.toInt(), RobotCurrency.ORE), RobotBuildCost(geoRobotObs.toInt(), RobotCurrency.OBSIDIAN)),
)
)
}
fun findBest(
blueprint: Blueprint,
minutesToRun: Int,
state: CollectingState,
): Int {
val minutesLeft = minutesToRun - state.minutesDone
return blueprint.buildCosts
.maxOf { (robotType, buildCosts) ->
if (
(robotType == RobotType.ORE_COLLECTOR && state.orePerMinute > 5) ||
(robotType == RobotType.CLAY_COLLECTOR && state.clayPerMinute > 5) ||
(robotType == RobotType.OBSIDIAN_COLLECTOR && state.obsidianPerMinute > 5)
){
-1
} else {
val minutesPerCurrency = buildCosts.map {
when (it.currency) {
RobotCurrency.ORE -> if (state.ore >= it.amount) 0 else if (state.orePerMinute > 0) it.amount - state.ore / state.orePerMinute else -1
RobotCurrency.CLAY -> if (state.clay >= it.amount) 0 else if (state.clayPerMinute > 0) it.amount - state.clay / state.clayPerMinute else -1
RobotCurrency.OBSIDIAN -> if (state.obs >= it.amount) 0 else if (state.obsidianPerMinute > 0) it.amount - state.obs / state.obsidianPerMinute else -1
}
}
val canNotMake = minutesPerCurrency.any { it == -1 }
val minutesUntilWeCanMakeRobot = minutesPerCurrency.max() + 1
if (canNotMake || minutesUntilWeCanMakeRobot >= minutesLeft) {
state.copy(
minutesDone = minutesToRun,
ore = state.ore + state.orePerMinute * minutesLeft,
clay = state.clay + state.clayPerMinute * minutesLeft,
obs = state.obs + state.obsidianPerMinute * minutesLeft,
geoCracked = state.geoCracked + state.geoCrackedPerMinute * minutesLeft,
).geoCracked
} else {
findBest(
blueprint,
minutesToRun,
state.copy(
minutesDone = state.minutesDone + minutesUntilWeCanMakeRobot,
ore = state.ore + (minutesUntilWeCanMakeRobot * state.orePerMinute) - (buildCosts.firstOrNull { it.currency == RobotCurrency.ORE }?.amount
?: 0),
clay = state.clay + (minutesUntilWeCanMakeRobot * state.clayPerMinute) - (buildCosts.firstOrNull { it.currency == RobotCurrency.CLAY }?.amount
?: 0),
obs = state.obs + (minutesUntilWeCanMakeRobot * state.obsidianPerMinute) - (buildCosts.firstOrNull { it.currency == RobotCurrency.OBSIDIAN }?.amount
?: 0),
geoCracked = state.geoCracked + (minutesUntilWeCanMakeRobot * state.geoCrackedPerMinute),
orePerMinute = state.orePerMinute + if (robotType == RobotType.ORE_COLLECTOR) 1 else 0,
clayPerMinute = state.clayPerMinute + if (robotType == RobotType.CLAY_COLLECTOR) 1 else 0,
obsidianPerMinute = state.obsidianPerMinute + if (robotType == RobotType.OBSIDIAN_COLLECTOR) 1 else 0,
geoCrackedPerMinute = state.geoCrackedPerMinute + if (robotType == RobotType.GEODE_CRACKING) 1 else 0,
)
)
}
}
}
}
fun part1(input: List<String>): Int {
val bluePrints = input.parseBlueprints()
println(bluePrints)
bluePrints.forEach { bluePrint -> println("${bluePrint.id}: ${findBest(bluePrint, 24 /*Day19.PART1_MINUTES*/, CollectingState())}") }
return 1
}
fun part2(input: List<String>): Int {
return 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
check(part1(testInput) == Day19.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day19.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day19Kt$WhenMappings.class",
"javap": "Compiled from \"Day19.kt\"\npublic final class Day19Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method RobotCurrency... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Utils.kt | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
/**
* Converts string to md5 hash.
*/
fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray()))
.toString(16)
.padStart(32, '0')
data class Location(val x: Int, val y: Int)
enum class Direction(val move: Coordinates) {
WEST(Coordinates(-1, 0)),
NORTH(Coordinates(0, -1)),
EAST(Coordinates(1, 0)),
SOUTH(Coordinates(0, 1));
fun next() = when (this) {
WEST -> EAST
NORTH -> SOUTH
EAST -> NORTH
SOUTH -> WEST
}
}
data class Coordinates(val x: Int, val y: Int) {
operator fun plus(distance: Coordinates): Coordinates = Coordinates(this.x + distance.x, this.y + distance.y)
fun move(direction: Direction) = when (direction) {
Direction.NORTH -> Coordinates(x, y - 1)
Direction.SOUTH -> Coordinates(x, y + 1)
Direction.EAST -> Coordinates(x + 1, y)
Direction.WEST -> Coordinates(x - 1, y)
}
fun adjacentPositions(includeDiagonal: Boolean = true): Set<Coordinates> =
adjacentPositions(Direction.NORTH, includeDiagonal) +
adjacentPositions(Direction.EAST, includeDiagonal) +
adjacentPositions(Direction.SOUTH, includeDiagonal) +
adjacentPositions(Direction.WEST, includeDiagonal)
fun adjacentPositions(direction: Direction, includeDiagonal: Boolean = true): Set<Coordinates> =
when (direction) {
Direction.NORTH -> setOf(
this + Coordinates(0, -1),
) + if (includeDiagonal) setOf(
this + Coordinates(-1, -1),
this + Coordinates(1, -1),
) else emptySet()
Direction.EAST -> setOf(
this + Coordinates(1, 0),
) + if (includeDiagonal) setOf(
this + Coordinates(1, -1),
this + Coordinates(1, 1),
) else emptySet()
Direction.SOUTH -> setOf(
this + Coordinates(0, 1),
) + if (includeDiagonal) setOf(
this + Coordinates(1, 1),
this + Coordinates(-1, 1),
) else emptySet()
Direction.WEST -> setOf(
this + Coordinates(-1, 0),
) + if (includeDiagonal) setOf(
this + Coordinates(-1, -1),
this + Coordinates(-1, 1),
) else emptySet()
}
}
data class BigCoordinates(val x: Long, val y: Long)
data class Point3D(val x: Int, val y: Int, val z: Int)
fun List<Coordinates>.findMinAndMax(): Pair<Coordinates, Coordinates> =
fold(Coordinates(Int.MAX_VALUE, Int.MAX_VALUE) to Coordinates(0, 0)) { (min, max), (x, y) ->
Coordinates(
minOf(min.x, x),
minOf(min.y, y)
) to Coordinates(
maxOf(max.x, x),
maxOf(max.y, y)
)
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/UtilsKt.class",
"javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String na... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day04.kt | object Day04 {
const val EXPECTED_PART1_CHECK_ANSWER = 2
const val EXPECTED_PART2_CHECK_ANSWER = 4
}
fun main() {
fun String.parseToIntRangePerElf(): Pair<IntRange, IntRange> =
this
.split(",")
.map { it.split("-") }
.map { (it[0].toInt())..(it[1].toInt()) }
.let { it[0] to it[1] }
fun part1(input: List<String>): Int =
input
.map { it.parseToIntRangePerElf() }
.count { it.first.minus(it.second).isEmpty() || it.second.minus(it.first).isEmpty() }
fun part2(input: List<String>): Int =
input
.map { it.parseToIntRangePerElf() }
.count { (firstElfSections, secondElfSections) ->
firstElfSections.any { secondElfSections.contains(it) } || firstElfSections.any {
secondElfSections.contains(
it
)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == Day04.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day04.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day04_test\n 2: invokestatic #14 // Method Util... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day16.kt | import java.util.*
object Day16 {
const val EXPECTED_PART1_CHECK_ANSWER = 1651
const val EXPECTED_PART2_CHECK_ANSWER = 1707
const val START_VALVE_NAME = "AA"
const val RUNTIME_MINS_PART1 = 30
const val RUNTIME_MINS_PART2 = 26
}
data class Valve(val name: String, val flowRate: Int) {
private var _accessibleValves: Set<Valve> = emptySet()
val accessibleValves
get() = _accessibleValves
fun addAccessibleValve(valve: Valve) {
_accessibleValves += valve
}
}
fun main() {
fun List<String>.parseValves(): MutableMap<String, Valve> {
val paths = mutableMapOf<String, List<String>>()
val valves = mutableMapOf<String, Valve>()
forEach { valveString ->
val (name, flowRate, accessibleValves) = Regex(
"Valve (.+) has flow rate=(\\d+); tunnels? leads? to valves? (.*)"
)
.matchEntire(valveString)?.destructured ?: error("Valve line not matched")
if (valves.contains(name)) error("Duplicate valve name detected")
paths[name] = accessibleValves.split(',').map(String::trim)
valves[name] = Valve(name, flowRate.toInt())
}
paths.forEach { (name, accessibleValves) ->
accessibleValves.forEach { accessibleValveName ->
valves[name]?.addAccessibleValve(
valves[accessibleValveName] ?: error("Could not find accessible valve")
)
}
}
return valves
}
fun shortestPathDistance(start: Valve, dest: Valve): Int {
val queue = LinkedList<Pair<Valve, Int>>()
val visited = mutableSetOf<Valve>()
queue.add(start to 0)
visited.add(start)
while (queue.isNotEmpty()) {
val (valve, distance) = queue.remove()
if (valve == dest) {
return distance
}
for (accessibleValve in valve.accessibleValves) {
if (!visited.contains(accessibleValve)) {
queue.add(accessibleValve to distance + 1)
visited.add(accessibleValve)
}
}
}
error("No shortest path found for $start to $dest")
}
data class Opener(val currentLocation: Valve, val minutesRemaining: Int)
fun releasedPressure(
distances: Map<Valve, Map<Valve, Int>>,
openenersData: List<Opener>,
opened: List<Valve> = emptyList(),
releasedPressure: Int = 0,
): Int {
val openerData = openenersData.maxBy { it.minutesRemaining }
return distances[openerData.currentLocation]!!.filter { it.key !in opened }
.maxOfOrNull { (nextValve, distance) ->
val newMinutesRemaining = openerData.minutesRemaining - distance - 1
if (newMinutesRemaining > 0) {
releasedPressure(
distances,
openenersData = openenersData.minus(openerData) + Opener(nextValve, newMinutesRemaining),
opened = opened + nextValve,
releasedPressure = releasedPressure + nextValve.flowRate * newMinutesRemaining,
)
} else {
releasedPressure
}
} ?: releasedPressure
}
fun part1(input: List<String>, startValveName: String): Int {
val valvesMap = input.parseValves()
val distances = valvesMap.values.associateWith { startValve ->
valvesMap.values.filter { it.flowRate > 0 }.associateWith { destValve ->
shortestPathDistance(startValve, destValve)
}
}
return releasedPressure(
distances,
openenersData = listOf(Opener(valvesMap[startValveName]!!, Day16.RUNTIME_MINS_PART1)),
)
}
fun part2(input: List<String>): Int {
val valvesMap = input.parseValves()
val distances = valvesMap.values.associateWith { startValve ->
valvesMap.values.filter { it.flowRate > 0 }.associateWith { destValve ->
shortestPathDistance(startValve, destValve)
}
}
val result = releasedPressure(
distances,
openenersData = listOf(
Opener(valvesMap[Day16.START_VALVE_NAME]!!, Day16.RUNTIME_MINS_PART2),
Opener(valvesMap[Day16.START_VALVE_NAME]!!, Day16.RUNTIME_MINS_PART2)
),
)
println("Part 2 result $result")
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
println("Part 1 check")
check(part1(testInput, Day16.START_VALVE_NAME) == Day16.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
println("Part 2 check")
check(part2(testInput) == Day16.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day16")
println("Part 1")
println(part1(input, Day16.START_VALVE_NAME))
println("Part 2")
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day16Kt$main$Opener.class",
"javap": "Compiled from \"Day16.kt\"\npublic final class Day16Kt$main$Opener {\n private final Valve currentLocation;\n\n private final int minutesRemaining;\n\n public Day16Kt$main$Opener(Valve, int);\n Code:\n 0: ... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day23.kt | import Day23.draw
import Day23.proposeMoves
object Day23 {
const val EXPECTED_PART1_CHECK_ANSWER = 110
const val EXPECTED_PART2_CHECK_ANSWER = 20
sealed interface GridCell
object Empty : GridCell
object Elf : GridCell
class Grid {
private val rows = mutableListOf<List<GridCell>>()
var width: Int = 0
private set
var height: Int = 0
private set
fun addRow(cells: List<Day23.GridCell>) {
rows += cells
width = rows.maxOf { it.size }
height = rows.size
}
fun doStep() {
}
}
fun Array<Coordinates>.draw() {
val fromX = minOf { it.x }
val toX = maxOf { it.x }
val fromY = minOf { it.y }
val toY = maxOf { it.y }
for (y in fromY..toY) {
for (x in fromX..toX) {
if (Coordinates(x, y) in this) {
print('#')
} else {
print('.')
}
}
println()
}
}
fun Array<Coordinates>.proposeMoves(
directions: Array<Direction>,
directionStartIdx: Int
): List<Pair<Coordinates, Coordinates>> = mapNotNull { elf ->
if (intersect(elf.adjacentPositions().toSet()).isNotEmpty()) {
var proposedMove: Pair<Coordinates, Coordinates>? = null
var directionIdx = directionStartIdx
var directionsDoneCount = 0
while (proposedMove == null && directionIdx < directions.size && directionsDoneCount++ <= directions.size) {
if (intersect(elf.adjacentPositions(directions[directionIdx])).isEmpty()) {
proposedMove = Pair(elf, elf + directions[directionIdx].move)
}
directionIdx = (directionIdx + 1) % directions.size
}
proposedMove
} else {
null
}
}
}
fun main() {
fun List<String>.parseElfsMap(): Array<Coordinates> = flatMapIndexed { row, line ->
line.mapIndexedNotNull { col, cell ->
when (cell) {
'.' -> null
'#' -> Coordinates(col, row)
else -> error("Unknown cell content $cell")
}
}
}.toTypedArray()
fun part1(input: List<String>, doDraw: Boolean): Int {
val elfs = input.parseElfsMap()
if (doDraw) {
elfs.draw()
println()
}
val directions = arrayOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST)
var directionStartIdx = 0
repeat(10) {
val proposedMoves = elfs.proposeMoves(directions, directionStartIdx)
val allNewPositions = proposedMoves.map { it.second }
proposedMoves.forEach { (currentPosition, proposedPosition) ->
if (allNewPositions.count { it == proposedPosition } == 1) {
elfs[elfs.indexOf(currentPosition)] = proposedPosition
}
}
directionStartIdx = (directionStartIdx + 1) % directions.size
if (doDraw) {
elfs.draw()
println()
}
}
val fromX = elfs.minOf { it.x }
val toX = elfs.maxOf { it.x }
val fromY = elfs.minOf { it.y }
val toY = elfs.maxOf { it.y }
return (fromY..toY).sumOf { y -> (fromX..toX).count { x -> !elfs.contains(Coordinates(x, y)) } }
}
fun part2(input: List<String>): Int {
val elfs = input.parseElfsMap()
val directions = arrayOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST)
var directionStartIdx = 0
var round = 0
var atLeastOneElfMoved: Boolean
do {
atLeastOneElfMoved = false
val proposedMoves = elfs.proposeMoves(directions, directionStartIdx)
val allNewPositions = proposedMoves.map { it.second }
proposedMoves.forEach { (currentPosition, proposedPosition) ->
if (allNewPositions.count { it == proposedPosition } == 1) {
elfs[elfs.indexOf(currentPosition)] = proposedPosition
atLeastOneElfMoved = true
}
}
directionStartIdx = (directionStartIdx + 1) % directions.size
round++
} while (atLeastOneElfMoved)
return round
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day23_test")
check(part1(testInput, true) == Day23.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day23.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day23")
println(part1(input, false))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day23Kt.class",
"javap": "Compiled from \"Day23.kt\"\npublic final class Day23Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day23_test\n 2: invokestatic #14 // Method Util... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day13.kt | object Day13 {
const val EXPECTED_PART1_CHECK_ANSWER = 13
const val EXPECTED_PART2_CHECK_ANSWER = 140
const val PACKET_COMBOS_NR_OF_LINES = 3
val NONE_NUMBER_CHARS = listOf('[', ']', ',')
const val DIVIDER_PACKET_ONE = 2
const val DIVIDER_PACKET_TWO = 6
val DIVIDER_PACKETS: List<List<Any>> = listOf(
listOf(listOf(DIVIDER_PACKET_ONE)),
listOf(listOf(DIVIDER_PACKET_TWO))
)
}
fun main() {
fun String.parse(): List<Any> {
val stack = ArrayDeque<MutableList<Any>>()
var idx = 0
do {
when (this[idx]) {
'[' -> {
stack.addFirst(mutableListOf())
idx++
}
']' -> {
if (stack.size > 1) {
val innerList = stack.removeFirst()
stack.first().add(innerList)
}
idx++
}
in '0'..'9' -> {
var nrStr: String = this[idx].toString()
while (this[++idx] !in Day13.NONE_NUMBER_CHARS) {
nrStr += this[idx]
}
stack.first().add(nrStr.toInt())
}
else -> idx++
}
} while (idx < this.length)
check(stack.size == 1) { "Stack should only have root left" }
return stack.first()
}
operator fun List<Any>.compareTo(other: List<Any>): Int {
for (leftIdx in this.indices) {
val firstValue = this[leftIdx]
if (leftIdx < other.size) {
val secondValue = other[leftIdx]
when {
firstValue is Int && secondValue is Int -> {
if (firstValue != secondValue) return firstValue.compareTo(secondValue)
}
else -> {
val firstValueList = if (firstValue is Int) listOf(firstValue) else firstValue as List<Any>
val secondValueList = if (secondValue is Int) listOf(secondValue) else secondValue as List<Any>
if (firstValueList != secondValueList) {
return firstValueList.compareTo(secondValueList)
}
}
}
} else {
return 1
}
}
return -1
}
fun part1(input: List<String>): Int {
val pairs = input.chunked(Day13.PACKET_COMBOS_NR_OF_LINES).map { it[0].parse() to it[1].parse() }
val compareResults = pairs.map { it.first.compareTo(it.second) }
return compareResults.foldIndexed(0) { index, acc, compareResult ->
if (compareResult < 0) acc + index + 1 else acc
}
}
fun part2(input: List<String>): Int {
val pairs = input.filter { it.isNotBlank() }.map { it.parse() } + Day13.DIVIDER_PACKETS
val sorted = pairs.sortedWith { o1, o2 -> o1!!.compareTo(o2!!) }
val result = Day13.DIVIDER_PACKETS.map {
sorted.indexOf(it) + 1
}.reduce(Int::times)
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == Day13.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day13.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day13.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13 {\n public static final Day13 INSTANCE;\n\n public static final int EXPECTED_PART1_CHECK_ANSWER;\n\n public static final int EXPECTED_PART2_CHECK_ANSWER;\n\n public static fi... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day08.kt | object Day08 {
const val EXPECTED_PART1_CHECK_ANSWER = 21
const val EXPECTED_PART2_CHECK_ANSWER = 8
}
fun main() {
fun List<String>.parseTreeGrid(): List<List<Int>> =
this.map { it.toList() }.map { it.map { chr -> chr.digitToInt() } }
fun List<List<Int>>.isVisible(x: Int, y: Int): Boolean {
if (x == 0 || y == 0 || x == this[0].size - 1 || y == this.size - 1) return true
val heightOfTree = this[y][x]
if (this[y].subList(0, x).all { it < heightOfTree }) return true
if (this[y].subList(x + 1, this[y].size).all { it < heightOfTree }) return true
val treesInSameVerticalRow = this.fold(emptyList<Int>()) { acc, row -> acc + row[x] }
if (treesInSameVerticalRow.subList(0, y).all { it < heightOfTree }) return true
if (treesInSameVerticalRow.subList(y + 1, treesInSameVerticalRow.size).all { it < heightOfTree }) return true
return false
}
fun List<List<Int>>.scenicScore(x: Int, y: Int): Int {
val heightOfTree = this[y][x]
val treesToTheLeft = this[y].subList(0, x)
val leftTreesVisible = treesToTheLeft
.takeLastWhile { it < heightOfTree }.size
.let { if (it == treesToTheLeft.size) it else it + 1 } // accommodate for edges
val treesToTheRight = this[y].subList(x + 1, this[y].size)
val rightTreesVisible = treesToTheRight
.takeWhile { it < heightOfTree }.size
.let { if (it == treesToTheRight.size) it else it + 1 } // accommodate for edges
val treesInSameVerticalRow = this.fold(emptyList<Int>()) { acc, row -> acc + row[x] }
val treesToTheTop = treesInSameVerticalRow.subList(0, y)
val upTreesVisible = treesToTheTop
.takeLastWhile { it < heightOfTree }.size
.let { if (it == treesToTheTop.size) it else it + 1 } // accommodate for edge
val treesToTheBottom = treesInSameVerticalRow.subList(y + 1, treesInSameVerticalRow.size)
val downTreesVisible = treesToTheBottom
.takeWhile { it < heightOfTree }.size
.let { if (it == treesToTheBottom.size) it else it + 1 } // accommodate for edge
return leftTreesVisible * rightTreesVisible * upTreesVisible * downTreesVisible
}
fun part1(input: List<String>): Int {
val treeGrid = input.parseTreeGrid()
var treesVisible = 0
for (xIndex in treeGrid[0].indices) {
for (yIndex in treeGrid.indices) {
if (treeGrid.isVisible(xIndex, yIndex)) {
treesVisible++
}
}
}
return treesVisible
}
fun part2(input: List<String>): Int {
val treeGrid = input.parseTreeGrid()
var highestScenicScore = 0
for (xIndex in treeGrid[0].indices) {
for (yIndex in treeGrid.indices) {
val scenicScore = treeGrid.scenicScore(xIndex, yIndex)
highestScenicScore = maxOf(scenicScore, highestScenicScore)
}
}
return highestScenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == Day08.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day08.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day08.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class Day08 {\n public static final Day08 INSTANCE;\n\n public static final int EXPECTED_PART1_CHECK_ANSWER;\n\n public static final int EXPECTED_PART2_CHECK_ANSWER;\n\n private Day08();... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day05.kt | object Day05 {
const val dayNumber = "05"
const val EXPECTED_PART1_CHECK_ANSWER = "CMZ"
const val EXPECTED_PART2_CHECK_ANSWER = "MCD"
const val STACK_SETUP_ENTRY_WITH_SPACE_SIZE = 4
const val STACK_SETUP_ENTRY_SIZE = 3
}
fun main() {
fun List<String>.parseStackSetup(): List<MutableList<Char>> {
val stacks = mutableListOf<MutableList<Char>>()
for (lineIdx in this.size - 2 downTo 0) {
val line = this[lineIdx]
var stackIndex = 0
var stackEntryStartPosition = 0
while (stackEntryStartPosition < line.length) {
if (stacks.size < stackIndex + 1) {
stacks += mutableListOf<Char>()
}
val stackEntry = line.substring(
stackEntryStartPosition until (stackEntryStartPosition + Day05.STACK_SETUP_ENTRY_SIZE)
)
if (stackEntry.isNotBlank()) {
stacks[stackIndex].add(stackEntry[1])
}
stackIndex++
stackEntryStartPosition = stackIndex * Day05.STACK_SETUP_ENTRY_WITH_SPACE_SIZE
}
}
return stacks
}
fun parseAndApplyMoves(
input: List<String>,
applyMove: (stacks: List<MutableList<Char>>, move: Triple<Int, Int, Int>) -> Unit
): String {
val indexOfEmptyLine = input.indexOf("")
val stackSetup = input.subList(0, indexOfEmptyLine).parseStackSetup()
val moves = input.subList(indexOfEmptyLine + 1, input.size)
val moveTemplate = Regex("move (\\d+) from (\\d+) to (\\d+)")
moves.forEach { move ->
moveTemplate.matchEntire(move)?.apply {
val (amount, from, to) = this.destructured
applyMove(stackSetup, Triple(amount.toInt(), from.toInt(), to.toInt()))
}
}
return stackSetup.map { stack -> stack.last() }.joinToString(separator = "")
}
fun part1(input: List<String>): String {
return parseAndApplyMoves(input) { stacks, (amount, from, to) ->
repeat(amount) { _ ->
val toMove = stacks[from - 1].removeLast()
stacks[to - 1].add(toMove)
}
}
}
fun part2(input: List<String>): String {
return parseAndApplyMoves(input) { stacks, (amount, from, to) ->
val removedChars = (1..amount).map { _ -> stacks[from - 1].removeLast() }
stacks[to - 1].addAll(removedChars.reversed())
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${Day05.dayNumber}_test")
check(part1(testInput) == Day05.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day05.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day${Day05.dayNumber}")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day05_test\n 2: invokestatic #14 // Method Util... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day11.kt | object Day11 {
const val EXPECTED_PART1_CHECK_ANSWER = 10605L
const val EXPECTED_PART2_CHECK_ANSWER = 2713310158
const val PART1_RUNS = 20
const val PART2_RUNS = 10_000
const val WORRY_LEVEL_DIVISION_AMOUNT = 3
val MONKEY_LINE_ITEMS = Regex("\\s+Starting items: ([, \\d]+)")
val MONKEY_LINE_OPERATION = Regex("\\s+Operation: new = old ([+*]) (\\w+)")
val MONKEY_LINE_TEST = Regex("\\s+Test: divisible by (\\d+)")
val MONKEY_LINE_THROW = Regex("\\s+If (true|false): throw to monkey (\\d+)")
}
data class Item(var worryLevel: Long)
class Monkey(
startingItems: List<Item>,
val operation: (Long) -> Long,
val testDivisibleBy: Int,
private val testTrueDestinationMonkey: Int,
private val testFalseDestinationMonkey: Int,
private val relieve: Boolean = true,
) {
private val items: MutableList<Item> = startingItems.toMutableList()
var itemsInspected = 0
private set
fun addItems(items: List<Item>) {
this.items.addAll(items)
}
fun turn(worryReduceVale: Int): Map<Int, List<Item>> {
val itemsToThrow = mutableMapOf<Int, List<Item>>()
for (item in items) {
item.worryLevel = operation(item.worryLevel)
if (relieve) {
item.worryLevel /= Day11.WORRY_LEVEL_DIVISION_AMOUNT
}
item.worryLevel %= worryReduceVale
itemsToThrow.compute(
if (item.worryLevel % testDivisibleBy == 0L) testTrueDestinationMonkey else testFalseDestinationMonkey
) { _, currentItems ->
(currentItems ?: emptyList()) + item
}
itemsInspected++
}
items.clear()
return itemsToThrow
}
}
class MonkeyBusiness(private val monkeys: List<Monkey>) {
private val worryReduceVale = monkeys.map { it.testDivisibleBy }.reduce(Int::times)
private fun round() {
monkeys.forEach { monkey ->
val itemsToPass = monkey.turn(worryReduceVale)
itemsToPass.forEach { (toMonkey, items) ->
monkeys[toMonkey].addItems(items)
}
}
}
fun process(numberOfRounds: Int): Long {
repeat(numberOfRounds) {
round()
}
return monkeys.map { it.itemsInspected }.sortedDescending().take(2).let { it[0].toLong() * it[1].toLong() }
}
}
fun main() {
fun List<String>.parseMonkeyBusiness(doRelieve: Boolean = true): MonkeyBusiness {
val monkeys = mutableListOf<Monkey>()
var inputIdx = 1
while (inputIdx < size) {
val (itemsWorryLevels) = Day11.MONKEY_LINE_ITEMS.matchEntire(this[inputIdx++])!!.destructured
val items = itemsWorryLevels.split(",").map(String::trim).map { Item(it.toLong()) }
val (operation, operationValue) = Day11.MONKEY_LINE_OPERATION.matchEntire(this[inputIdx++])!!.destructured
val (testDivisibleValue) = Day11.MONKEY_LINE_TEST.matchEntire(this[inputIdx++])!!.destructured
val (_, throwToWhenTrue) = Day11.MONKEY_LINE_THROW.matchEntire(this[inputIdx++])!!.destructured
val (_, throwToWhenFalse) = Day11.MONKEY_LINE_THROW.matchEntire(this[inputIdx++])!!.destructured
monkeys.add(
Monkey(
items,
{
val operand = when (operationValue) {
"old" -> it
else -> operationValue.toLong()
}
when (operation) {
"*" -> it * operand
"+" -> it + operand
else -> error("Unknown operation $operation")
}
},
testDivisibleValue.toInt(),
throwToWhenTrue.toInt(),
throwToWhenFalse.toInt(),
doRelieve,
)
)
inputIdx += 2
}
return MonkeyBusiness(monkeys)
}
fun part1(input: List<String>): Long {
val monkeyBusiness = input.parseMonkeyBusiness()
return monkeyBusiness.process(Day11.PART1_RUNS)
}
fun part2(input: List<String>): Long {
val monkeyBusiness = input.parseMonkeyBusiness(false)
return monkeyBusiness.process(Day11.PART2_RUNS)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == Day11.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day11.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day11.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class Day11 {\n public static final Day11 INSTANCE;\n\n public static final long EXPECTED_PART1_CHECK_ANSWER;\n\n public static final long EXPECTED_PART2_CHECK_ANSWER;\n\n public static ... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day09.kt | import kotlin.math.abs
import kotlin.math.sign
object Day09 {
const val EXPECTED_PART1_CHECK_ANSWER = 13
const val EXPECTED_PART2_CHECK_ANSWER = 1
const val TAIL_SIZE_PART_2 = 9
}
enum class MovementDirection { U, D, L, R }
fun main() {
data class Location(val x: Int, val y: Int) {
fun move(direction: MovementDirection) = when (direction) {
MovementDirection.U -> copy(y = y + 1)
MovementDirection.D -> copy(y = y - 1)
MovementDirection.R -> copy(x = x + 1)
MovementDirection.L -> copy(x = x - 1)
}
fun moveAfterPrecursor(precursorPosition: Location): Location {
val xDiff = precursorPosition.x - x
val yDiff = precursorPosition.y - y
if (abs(xDiff) > 1 || abs(yDiff) > 1) {
return copy(
x = x + (xDiff + xDiff.sign) / 2,
y = y + (yDiff + yDiff.sign) / 2,
)
}
return this
}
}
fun part1(input: List<String>): Int {
val tailVisitedPositions = mutableSetOf<Location>()
var currentHeadPosition = Location(0, 0)
var currentTailPosition = Location(0, 0)
tailVisitedPositions.add(currentTailPosition)
input.forEach { movement ->
val directionAndSteps = movement.split(" ")
val (direction, steps) = Pair(MovementDirection.valueOf(directionAndSteps[0]), directionAndSteps[1].toInt())
repeat(steps) {
currentHeadPosition = currentHeadPosition.move(direction)
currentTailPosition = currentTailPosition.moveAfterPrecursor(currentHeadPosition)
tailVisitedPositions.add(currentTailPosition)
}
}
return tailVisitedPositions.size
}
fun part2(input: List<String>): Int {
val tailVisitedPositions = mutableSetOf<Location>()
var currentHeadPosition = Location(0, 0)
val trailPositions = MutableList(Day09.TAIL_SIZE_PART_2) { Location(0, 0) }
tailVisitedPositions.add(trailPositions.last())
input.forEach { movement ->
val directionAndSteps = movement.split(" ")
val (direction, steps) = Pair(MovementDirection.valueOf(directionAndSteps[0]), directionAndSteps[1].toInt())
repeat(steps) {
currentHeadPosition = currentHeadPosition.move(direction)
trailPositions.forEachIndexed { idx, trailPosition ->
val newTrailPosition =
trailPosition.moveAfterPrecursor(if (idx == 0) currentHeadPosition else trailPositions[idx - 1])
trailPositions[idx] = newTrailPosition
}
tailVisitedPositions.add(trailPositions.last())
}
}
return tailVisitedPositions.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == Day09.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day09.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day09Kt$main$Location.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt$main$Location {\n private final int x;\n\n private final int y;\n\n public Day09Kt$main$Location(int, int);\n Code:\n 0: aload_0\n 1: invokesp... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day07.kt | object Day07 {
const val EXPECTED_PART1_CHECK_ANSWER = 95437
const val EXPECTED_PART2_CHECK_ANSWER = 24933642
const val DIR_SIZE_THRESHOLD = 100_000
const val FS_TOTAL_SIZE = 70_000_000
const val FS_NEEDED_FREE_SPACE = 30_000_000
}
sealed class Entry(val name: String)
class File(name: String, val size: Int) : Entry(name)
class Dir(name: String, val parentDir: Dir? = null) : Entry(name) {
private var content: List<Entry> = emptyList()
fun add(entry: Entry): Entry {
content += entry
return this
}
fun dirContent() = content
}
fun main() {
val fileListingRegex = Regex("(\\d+) (\\S+)")
fun parseDirTree(input: List<String>): Dir {
val rootDir = Dir("/")
var currentDir = rootDir
input.drop(1).forEach { entry ->
when {
entry.startsWith("$ cd ..") -> {
if (currentDir.parentDir != null) {
currentDir = currentDir.parentDir!!
}
}
entry.startsWith("$ cd") -> {
val newDir = Dir(entry.substring("$ cd ".length), currentDir)
currentDir.add(newDir)
currentDir = newDir
}
entry.matches(fileListingRegex) -> {
val match = fileListingRegex.matchEntire(entry)
if (match != null) {
currentDir.add(File(match.groupValues[2], match.groupValues[1].toInt()))
}
}
}
}
return rootDir
}
fun dirSizes(dir: Dir, sizes: MutableList<Int>): Int {
var totalDirSize = 0
dir.dirContent().forEach { subEntry ->
totalDirSize += when (subEntry) {
is File -> subEntry.size
is Dir -> dirSizes(subEntry, sizes)
}
}
sizes += totalDirSize
return totalDirSize
}
fun part1(input: List<String>): Int {
val rootDir = parseDirTree(input)
val sizesOfDirs = mutableListOf<Int>()
dirSizes(rootDir, sizesOfDirs)
return sizesOfDirs.filter { it <= Day07.DIR_SIZE_THRESHOLD }.sum()
}
fun part2(input: List<String>): Int {
val rootDir = parseDirTree(input)
val sizesOfDirs = mutableListOf<Int>()
val rootDirSize = dirSizes(rootDir, sizesOfDirs)
val currentFreeSpace = Day07.FS_TOTAL_SIZE - rootDirSize
val needToFreeUp = Day07.FS_NEEDED_FREE_SPACE - currentFreeSpace
return sizesOfDirs.filter { it >= needToFreeUp }.sorted()[0]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == Day07.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day07.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day07Kt.class",
"javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc #10 ... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day10.kt | object Day10 {
const val EXPECTED_PART1_CHECK_ANSWER = 13140
const val EXPECTED_PART2_CHECK_ANSWER = 1
val CYCLE_PROBE_POINTS = listOf(20, 60, 100, 140, 180, 220)
const val CRT_LINE_WIDTH = 40
}
sealed class CpuInstruction(val cycles: Int)
class Noop : CpuInstruction(1)
class AddX(val arg: Int) : CpuInstruction(2)
class Cpu(val instructions: List<CpuInstruction>) : ClockListener {
private var instructionPointer: Int = 0
private var instructionCyclesDone: Int = 0
private val x: MutableList<Int> = mutableListOf(1)
fun isDone() = instructionPointer >= instructions.size
fun xAtCycle(cycle: Int) = x[cycle - 1]
fun x() = x.last()
override fun tickStart(cycle: Int) {
// NOOP
}
override fun tickEnd(cycle: Int) {
instructionCyclesDone++
val currentXValue = if (x.isEmpty()) 1 else x.last()
when (val currentInstruction = instructions[instructionPointer]) {
is Noop -> {
x.add(currentXValue)
instructionPointer++
instructionCyclesDone = 0
}
is AddX -> {
if (currentInstruction.cycles == instructionCyclesDone) {
x.addAll(listOf(currentXValue, currentXValue + currentInstruction.arg))
instructionPointer++
instructionCyclesDone = 0
}
}
}
}
}
class Crt(private val cpu: Cpu) : ClockListener {
override fun tickStart(cycle: Int) {
val crtPos = cycle - 1
val lineNumber = crtPos / Day10.CRT_LINE_WIDTH
val positionInLine = crtPos - lineNumber * Day10.CRT_LINE_WIDTH
print(if (positionInLine in (cpu.x() - 1)..(cpu.x() + 1)) "#" else ".")
if (crtPos > 0 && cycle % Day10.CRT_LINE_WIDTH == 0) println()
}
override fun tickEnd(cycle: Int) {
// NOOP
}
}
interface ClockListener {
fun tickStart(cycle: Int)
fun tickEnd(cycle: Int)
}
fun main() {
fun List<String>.parseInstructions(): List<CpuInstruction> =
map { it.split(" ") }.map {
when (it[0]) {
"noop" -> Noop()
"addx" -> AddX(it[1].toInt())
else -> error("Unknown operation ${it[0]}")
}
}
fun part1(input: List<String>): Int {
val cpu = Cpu(input.parseInstructions())
var cycle = 1
while (!cpu.isDone()) {
cpu.tickStart(cycle)
cpu.tickEnd(cycle)
cycle++
}
return Day10.CYCLE_PROBE_POINTS.sumOf { cpu.xAtCycle(it) * it }
}
fun part2(input: List<String>): Int {
println("\n\n")
val cpu = Cpu(input.parseInstructions())
val crt = Crt(cpu)
var cycle = 1
while (!cpu.isDone()) {
cpu.tickStart(cycle)
crt.tickStart(cycle)
cpu.tickEnd(cycle)
crt.tickEnd(cycle)
cycle++
}
return 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == Day10.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day10.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day10.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class Day10 {\n public static final Day10 INSTANCE;\n\n public static final int EXPECTED_PART1_CHECK_ANSWER;\n\n public static final int EXPECTED_PART2_CHECK_ANSWER;\n\n private static f... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day06.kt | import kotlin.system.measureNanoTime
object Day06 {
const val EXPECTED_PART1_CHECK_ANSWER = 7
const val EXPECTED_PART2_CHECK_ANSWER = 19
const val MARKER_PACKET_LENGTH = 4
const val MARKER_MESSAGE_LENGTH = 14
}
fun main() {
fun String.findLengthUntilMarker(markerLength: Int): Int {
var pointerInData = 0
var potentialMarker = ""
do {
when (val indexOfDuplicate = potentialMarker.indexOf(this[pointerInData])) {
-1 -> potentialMarker += this[pointerInData]
else -> potentialMarker = potentialMarker.drop(indexOfDuplicate + 1) + this[pointerInData]
}
pointerInData++
} while (potentialMarker.length < markerLength && pointerInData < this.length)
return pointerInData
}
fun String.findLengthUntilMarkerWindowed(markerLength: Int) =
windowedSequence(markerLength) { it.toSet().size }.indexOfFirst { it == markerLength } + markerLength
fun part1(input: List<String>): Int {
val windowedDuration = measureNanoTime {
input.first().findLengthUntilMarkerWindowed(Day06.MARKER_PACKET_LENGTH)
}
val nonWindowedDuration = measureNanoTime {
input.first().findLengthUntilMarker(Day06.MARKER_PACKET_LENGTH)
}
println("Windowed: $windowedDuration, Non windowed: $nonWindowedDuration")
return input.first().findLengthUntilMarkerWindowed(Day06.MARKER_PACKET_LENGTH)
}
fun part2(input: List<String>): Int {
val windowedDuration = measureNanoTime {
input.first().findLengthUntilMarkerWindowed(Day06.MARKER_MESSAGE_LENGTH)
}
val nonWindowedDuration = measureNanoTime {
input.first().findLengthUntilMarker(Day06.MARKER_MESSAGE_LENGTH)
}
println("Windowed: $windowedDuration, Non windowed: $nonWindowedDuration")
return input.first().findLengthUntilMarkerWindowed(Day06.MARKER_MESSAGE_LENGTH)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == Day06.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day06.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day06Kt.class",
"javap": "Compiled from \"Day06.kt\"\npublic final class Day06Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day06_test\n 2: invokestatic #14 // Method Util... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day12.kt | import java.util.LinkedList
object Day12 {
const val EXPECTED_PART1_CHECK_ANSWER = 31
const val EXPECTED_PART2_CHECK_ANSWER = 29
const val CHAR_START = 'S'
const val CHAR_DESTINATION = 'E'
const val CHAR_LOWEST = 'a'
}
fun main() {
fun List<String>.parseData(): Array<CharArray> =
map { it.toCharArray() }.toTypedArray()
fun Array<CharArray>.findLocationOfChar(char: Char) =
this.indexOfFirst { it.contains(char) }.let { vertIndex -> Location(this[vertIndex].indexOf(char), vertIndex) }
fun Array<CharArray>.findLocationsOfChar(char: Char): List<Location> {
val locationsOfChar = mutableListOf<Location>()
this.forEachIndexed { yIndex, listOfChars ->
listOfChars.forEachIndexed { xIndex, possibleChar ->
if (char == possibleChar) {
locationsOfChar.add(Location(xIndex, yIndex))
}
}
}
return locationsOfChar
}
fun Array<CharArray>.getValueAt(location: Location) = this[location.y][location.x]
fun Array<CharArray>.width() = this[0].size
fun Array<CharArray>.height() = this.size
fun Char.mapToHeightValue() = when (this) {
Day12.CHAR_START -> 'a'
Day12.CHAR_DESTINATION -> 'z'
else -> this
}
fun findShortestPath(grid: Array<CharArray>, start: Location): Int {
val destination = grid.findLocationOfChar('E')
val queue = LinkedList<Pair<Location, Int>>()
val visited = mutableSetOf<Location>()
queue.add(start to 0)
visited.add(start)
do {
val locationAndDistance = queue.remove()
val locationHeight = grid.getValueAt(locationAndDistance.first).mapToHeightValue()
if (locationAndDistance.first == destination) {
return locationAndDistance.second
}
val adjCells = listOf(
Location(locationAndDistance.first.x - 1, locationAndDistance.first.y),
Location(locationAndDistance.first.x + 1, locationAndDistance.first.y),
Location(locationAndDistance.first.x, locationAndDistance.first.y - 1),
Location(locationAndDistance.first.x, locationAndDistance.first.y + 1),
).filter { it.x >= 0 && it.y >= 0 && it.x < grid.width() && it.y < grid.height() }
for (adjLocation in adjCells) {
val height = grid.getValueAt(adjLocation).mapToHeightValue()
if ((height - locationHeight <= 1) && !visited.contains(
adjLocation
)
) {
queue.add(adjLocation to locationAndDistance.second + 1)
visited.add(adjLocation)
}
}
} while (queue.isNotEmpty())
return -1
}
fun part1(input: List<String>): Int {
val grid = input.parseData()
return findShortestPath(grid, grid.findLocationOfChar(Day12.CHAR_START))
}
fun part2(input: List<String>): Int {
val grid = input.parseData()
val locationsOfLowest = grid.findLocationsOfChar(Day12.CHAR_LOWEST) + grid.findLocationOfChar(Day12.CHAR_START)
return locationsOfLowest.map { findShortestPath(grid, it) }.filter { it != -1 }.also { println(it) }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == Day12.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day12.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day12.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class Day12 {\n public static final Day12 INSTANCE;\n\n public static final int EXPECTED_PART1_CHECK_ANSWER;\n\n public static final int EXPECTED_PART2_CHECK_ANSWER;\n\n public static fi... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day20.kt | import java.util.LinkedList
object Day20 {
const val EXPECTED_PART1_CHECK_ANSWER = 3
const val EXPECTED_PART2_CHECK_ANSWER = 1623178306L
val ANSWER_POSITIONS = setOf(1000, 2000, 3000)
const val DECRYPTION_KEY = 811589153L
}
fun main() {
fun List<String>.parse() = map(String::toLong).foldIndexed(LinkedList<Pair<Long, Int>>()) { idx, acc, nr ->
acc.add(nr to idx)
acc
}
fun LinkedList<Pair<Long, Int>>.mixIt(orgList: List<Pair<Long, Int>>) {
orgList.forEach { nrAndOrgIndex ->
val nr = nrAndOrgIndex.first
val currentIndex = indexOf(nrAndOrgIndex)
val uncappedNewIndex = currentIndex + nr
val moveToIndex = uncappedNewIndex.mod(lastIndex)
remove(nrAndOrgIndex)
add(moveToIndex, nrAndOrgIndex)
}
}
fun part1(input: List<String>): Int {
val numbers = input.parse()
val newList = LinkedList(numbers)
newList.mixIt(numbers)
println(newList)
val indexOfZero = newList.indexOf(newList.find { it.first == 0L })
val result = Day20.ANSWER_POSITIONS.sumOf {
val indexOfNr = indexOfZero + it
val wrappedIndex = indexOfNr % newList.size
newList[wrappedIndex].first
}
return result.toInt()
}
fun part2(input: List<String>): Long {
val numbers = input.parse().map { Pair(it.first * Day20.DECRYPTION_KEY, it.second) }
val newList = LinkedList(numbers)
repeat(10) { newList.mixIt(numbers) }
println(newList)
val indexOfZero = newList.indexOf(newList.find { it.first == 0L })
val result = Day20.ANSWER_POSITIONS.map(Int::toLong).sumOf {
val indexOfNr = indexOfZero + it
val wrappedIndex = indexOfNr % newList.size
newList[wrappedIndex.toInt()].first
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
check(part1(testInput) == Day20.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day20.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day20Kt.class",
"javap": "Compiled from \"Day20.kt\"\npublic final class Day20Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day20_test\n 2: invokestatic #14 // Method Util... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day25.kt | import kotlin.math.pow
object Day25 {
const val EXPECTED_PART1_CHECK_ANSWER = "2=-1=0"
const val EXPECTED_PART2_CHECK_ANSWER = 1
}
fun main() {
fun fivesValueForDigit(char: Char) = when (char) {
'2' -> 2
'1' -> 1
'0' -> 0
'-' -> -1
'=' -> -2
else -> error("Unknown char $char")
}
fun digitForFivesValue(value: Long) = when (value) {
0L -> '0'
1L -> '1'
2L -> '2'
3L -> '='
4L -> '-'
else -> error("Unsupported value $value")
}
fun convertFivePowerNumberToDecimalNumber(fivePowerNumber: String): Long {
return fivePowerNumber.reversed().foldIndexed(0L) { idx, total, curFive ->
total + fivesValueForDigit(curFive) * (5.toDouble().pow(idx).toLong())
}
}
fun convertDecimalNumberToFivePowerNumber(decimalNumber: Long): String {
if (decimalNumber == 0L) return "0"
return generateSequence(decimalNumber to "") { (rest, totalNumber) ->
val low = rest % 5
(rest + 2) / 5 to digitForFivesValue(low) + totalNumber
}.first { it.first <= 0L }.second
}
fun part1(input: List<String>): String {
val sumInDecimal = input.sumOf { convertFivePowerNumberToDecimalNumber(it) }
val snafuValue = convertDecimalNumberToFivePowerNumber(sumInDecimal)
return snafuValue
}
fun part2(input: List<String>): Int {
return 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
val input = readInput("Day25")
val part1TestResult = part1(testInput)
println("Part 1 test: $part1TestResult")
check(part1TestResult == Day25.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
println(part1(input))
val part2TestResult = part2(testInput)
println("Part 2 test: $part2TestResult")
check(part2TestResult == Day25.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day25Kt.class",
"javap": "Compiled from \"Day25.kt\"\npublic final class Day25Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day25_test\n 2: invokestatic #14 // Method Util... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day03.kt | object Day03 {
const val EXPECTED_PART1_CHECK_ANSWER = 157
const val EXPECTED_PART2_CHECK_ANSWER = 70
const val ELF_GROUP_SIZE = 3
}
fun main() {
fun Char.mapToItemValue() = if (this.isUpperCase()) (this.minus('A') + 27) else (this.minus('a') + 1)
fun part1(input: List<String>): Int {
return input.sumOf {
val compartment1 = it
.take(it.length / 2)
val compartment2 = it
.takeLast(it.length / 2)
val inBothCompartments = compartment1.toSet().intersect(compartment2.toSet())
val itemValue = if (inBothCompartments.isEmpty()) 0 else inBothCompartments.first().mapToItemValue()
itemValue
}
}
fun part2(input: List<String>): Int {
val commonItemsValues = input.chunked(Day03.ELF_GROUP_SIZE) {
it
.map { rucksackContent -> rucksackContent.toSet() }
.foldIndexed(emptySet<Char>()) { idx, acc, chars -> if (idx == 0) chars else acc.intersect(chars) }
.firstOrNull()
?.mapToItemValue()
?: 0
}
return commonItemsValues.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == Day03.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day03.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day03_test\n 2: invokestatic #14 // Method Util... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day02.kt |
const val SCORE_ROCK = 1
const val SCORE_PAPER = 2
const val SCORE_SCISSORS = 3
const val DRAW = 'Y'
const val LOSE = 'X'
const val WIN = 'Z'
const val EXPECTED_PART1_CHECK_ANSWER = 15
const val EXPECTED_PART2_CHECK_ANSWER = 12
const val POS_THEIR_CHOICE = 0
const val POS_OUR_CHOICE = 2
const val SCORE_WIN = 6
const val SCORE_DRAW = 3
const val SCORE_LOSE = 0
enum class Shape(val shapeScore: Int) {
Rock(SCORE_ROCK),
Paper(SCORE_PAPER),
Scissors(SCORE_SCISSORS);
companion object {
fun from(char: Char): Shape =
when (char) {
'A', 'X' -> Rock
'B', 'Y' -> Paper
'C', 'Z' -> Scissors
else -> error("Unknown value $char")
}
}
}
val BEATS = mapOf(
Shape.Rock to Shape.Scissors,
Shape.Paper to Shape.Rock,
Shape.Scissors to Shape.Paper,
)
val BEATEN_BY = mapOf(
Shape.Scissors to Shape.Rock,
Shape.Rock to Shape.Paper,
Shape.Paper to Shape.Scissors,
)
fun main() {
fun getScore(theirs: Shape, ours: Shape) = when {
ours == theirs -> ours.shapeScore + SCORE_DRAW
BEATS[ours] == theirs -> ours.shapeScore + SCORE_WIN
else -> ours.shapeScore + SCORE_LOSE
}
fun part1(input: List<String>): Int {
return input.sumOf {
val theirs = Shape.from(it[POS_THEIR_CHOICE])
val ours = Shape.from(it[POS_OUR_CHOICE])
getScore(theirs, ours)
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val theirs = Shape.from(it[POS_THEIR_CHOICE])
val ours = when (it[POS_OUR_CHOICE]) {
DRAW -> theirs
LOSE -> BEATS[theirs]!!
WIN -> BEATEN_BY[theirs]!!
else -> error("Wrong input")
}
getScore(theirs, ours)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == EXPECTED_PART1_CHECK_ANSWER)
check(part2(testInput) == EXPECTED_PART2_CHECK_ANSWER)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final int SCORE_ROCK;\n\n public static final int SCORE_PAPER;\n\n public static final int SCORE_SCISSORS;\n\n public static final char DRAW;\n\n publi... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day18.kt | object Day18 {
const val EXPECTED_PART1_CHECK_ANSWER = 64
const val EXPECTED_PART2_CHECK_ANSWER = 58
}
fun main() {
val air = mutableMapOf<Point3D, Boolean>()
fun List<String>.parsePoints() =
map { line ->
val xyz = line.split(',')
Point3D(xyz[0].toInt(), xyz[1].toInt(), xyz[2].toInt())
}
fun Point3D.sides() =
listOf(
Triple(-1, 0, 0),
Triple(0, 1, 0),
Triple(1, 0, 0),
Triple(0, -1, 0),
Triple(0, 0, 1),
Triple(0, 0, -1),
).map { (xMove, yMove, zMove) ->
Point3D(x + xMove, y +yMove, z + zMove)
}
fun addToCache(points: Iterable<Point3D>, isAir: Boolean): Boolean {
points.forEach { air[it] = isAir }
return isAir
}
fun Point3D.outsideRange(pMin: Point3D, pMax: Point3D) = x < pMin.x || x > pMax.x || y < pMin.y || y > pMax.y || z < pMin.z || z > pMax.z
fun Point3D.isAir(points: List<Point3D>, pMin: Point3D, pMax: Point3D): Boolean {
air[this]?.let { return it }
val frontier = ArrayDeque(listOf(this))
val visited = mutableSetOf<Point3D>()
while (!frontier.isEmpty()) {
val current = frontier.removeFirst()
when {
!visited.add(current) -> continue
current in air -> return addToCache(visited, air.getValue(current))
current.outsideRange(pMin, pMax) -> return addToCache(visited, false)
else -> frontier.addAll(current.sides().filter { it !in points })
}
}
return addToCache(visited, true)
}
fun part1(input: List<String>): Int {
val points = input.parsePoints()
return points.sumOf { point ->
point.sides().count { it !in points }
}
}
fun part2(input: List<String>): Int {
val points = input.parsePoints()
val pMin = Point3D(points.minOf { it.x }, points.minOf { it.y }, points.minOf { it.z })
val pMax = Point3D(points.maxOf { it.x }, points.maxOf { it.y }, points.maxOf { it.z })
val result = points.sumOf { point ->
point.sides().filter { it !in points }.count { !it.isAir(points, pMin, pMax) }
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
check(part1(testInput) == Day18.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day18.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day18.class",
"javap": "Compiled from \"Day18.kt\"\npublic final class Day18 {\n public static final Day18 INSTANCE;\n\n public static final int EXPECTED_PART1_CHECK_ANSWER;\n\n public static final int EXPECTED_PART2_CHECK_ANSWER;\n\n private Day18();... |
dizney__aoc-2022-in-kotlin__f684a4e/src/Day01.kt | const val PART1_EXPECTED_HIGHEST_CALORIES = 24000
const val PART2_EXPECTED_HIGHEST_3_CALORIES_SUM = 45000
const val PART2_TOP_ELF_COUNT = 3
fun main() {
fun elfTotals(input: List<String>, idx: Int = 0, elfAmount: Int = 0, totals: List<Int> = emptyList()): List<Int> {
if (idx >= input.size) return totals + elfAmount
return elfTotals(
input,
idx + 1,
if (input[idx].isBlank()) 0 else elfAmount + input[idx].toInt(),
if (input[idx].isBlank()) totals + elfAmount else totals
)
}
fun part1(input: List<String>): Int {
return elfTotals(input).maxOf { it }
}
fun part2(input: List<String>): Int {
val elfTotals = elfTotals(input)
return elfTotals.sortedDescending().take(PART2_TOP_ELF_COUNT).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == PART1_EXPECTED_HIGHEST_CALORIES)
check(part2(testInput) == PART2_EXPECTED_HIGHEST_3_CALORIES_SUM)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
// fun part1(input: List<String>): Int {
// var currentMax = 0
// var elfTotal = 0
// input.forEach {
// if (it.isBlank()) {
// if (elfTotal > currentMax) {
// currentMax = elfTotal
// }
// elfTotal = 0
// } else {
// elfTotal += it.toInt()
// }
// }
// return currentMax
// }
//
}
| [
{
"class_path": "dizney__aoc-2022-in-kotlin__f684a4e/Day01Kt.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final int PART1_EXPECTED_HIGHEST_CALORIES;\n\n public static final int PART2_EXPECTED_HIGHEST_3_CALORIES_SUM;\n\n public static final int PART2_TOP_ELF_C... |
Jeff-Gillot__word-clique__4b11007/src/main/kotlin/Main.kt | import java.io.File
import kotlin.system.measureTimeMillis
fun main() {
val time = measureTimeMillis {
// Read the words and keep only 5 letters words
val textWords = File(Signature::class.java.getResource("words_alpha.txt")!!.toURI())
.readLines()
.filter { it.length == 5 }
// Let's group the words by their signature and only keep the words that have 5 distinct letters
// Also the signature is the same for anagrams since we don't keep track of the order of letters in the signature
val wordsBySignature: Map<Signature, List<String>> = textWords
.groupBy { it.toSignature() }
.filterKeys { it.distinctLetters() == 5 }
// We get the letters and the number of time those letters appears in each signature
// We'll use that to start with the least common letters first
val letterCount = letters.values
.associateWith { letter -> wordsBySignature.keys.fold(0) { acc, signature -> if (letter in signature) acc + 1 else acc } }.toList()
.sortedBy { it.second }
.toMap()
println("--- Letters and occurrences")
letterCount.forEach { (letterSignature, count) -> println("${letterSignature.letter()} -> $count") }
// Fortunately all of those methods keep the order so it's very useful
val orderedLetters = letterCount.keys
// We group the word signatures by the first of the letter from the ordered letters
// This works because we will try to fill in the letters using the same order
val wordsByLetter = wordsBySignature
.keys
.groupBy { word -> orderedLetters.first { letter -> letter in word } }
println("--- Letters and words count associated to it")
wordsByLetter.forEach { (letterSignature, words) -> println("${letterSignature.letter()} -> ${words.size}") }
println("--- Starting the solver loop")
var solution = listOf(WordGroup(emptyList(), Signature.empty))
orderedLetters.forEachIndexed { index, letter ->
val newSolution = mutableListOf<WordGroup>()
//This is all the letters that we tried to add so far + the current one
val expectedLetters = letterCount.keys.take(index + 1).merge()
//We add the previous groups that have all the letters - 1 (we want solution that have 25 of the 26 letters so we can have 1 gap)
solution
.filter { it.signature.commonLetters(expectedLetters).distinctLetters() >= index }
.let { newSolution.addAll(it) }
val wordsToCheck = wordsByLetter[letter] ?: emptyList()
println("${lettersInverted[letter]} -> Words to check ${wordsToCheck.size}")
// Do a cartesian product of the current solutions and words for this letter
// Ignore any word that creates has duplicate letters or that do not have enough distinct letters (1 gap max)
wordsToCheck
.flatMap { word ->
solution
.filter { word !in it }
.map { it + word }
.filter { it.signature.commonLetters(expectedLetters).distinctLetters() >= index }
}
.let { newSolution.addAll(it) }
// Update the solution with the new result
solution = newSolution
println("${lettersInverted[letter]} -> Current solution ${solution.size}")
}
// Now that we the solutions but we probably want to output it
// The solution removed the anagrams and only contains the signatures we need to transform that back into words
val words = solution
.flatMap { it.toWords(wordsBySignature) }
.onEach { println(it.joinToString(" ")) }
println()
println("Total possibilities including anagrams: ${words.size}")
println()
println("Total possibilities excluding anagrams: ${solution.size}")
}
println("${time / 1000.0} seconds")
}
// The signature is a bitset representation of the word each bit represent whether a letter is present or not
@JvmInline
value class Signature(private val value: Int) {
operator fun plus(other: Signature): Signature = Signature(value or other.value)
operator fun contains(other: Signature): Boolean = value and other.value != 0
fun distinctLetters(): Int = value.countOneBits()
fun commonLetters(other: Signature) = Signature(value and other.value)
fun letter(): Char {
if (distinctLetters() == 1) {
return lettersInverted[this]!!
} else {
throw IllegalStateException("There is more than one letter in this signature")
}
}
companion object {
val empty = Signature(0)
}
}
fun Iterable<Signature>.merge(): Signature = fold(Signature.empty) { acc, signature -> acc + signature }
data class WordGroup(
val words: List<Signature>,
val signature: Signature,
) {
operator fun contains(word: Signature): Boolean = word in signature
operator fun plus(word: Signature): WordGroup = WordGroup(words + word, signature + word)
fun toWords(wordsBySignature: Map<Signature, List<String>>): List<List<String>> {
return words
.map { wordSignature -> wordsBySignature[wordSignature]!! }
.fold(emptyList()) { acc, words ->
if (acc.isEmpty()) {
words.map { listOf(it) }
} else {
words.flatMap { word -> acc.map { it + word } }
}
}
}
}
// Each letter has its own signature
val letters = mapOf(
'a' to Signature(0b00000000000000000000000001),
'b' to Signature(0b00000000000000000000000010),
'c' to Signature(0b00000000000000000000000100),
'd' to Signature(0b00000000000000000000001000),
'e' to Signature(0b00000000000000000000010000),
'f' to Signature(0b00000000000000000000100000),
'g' to Signature(0b00000000000000000001000000),
'h' to Signature(0b00000000000000000010000000),
'i' to Signature(0b00000000000000000100000000),
'j' to Signature(0b00000000000000001000000000),
'k' to Signature(0b00000000000000010000000000),
'l' to Signature(0b00000000000000100000000000),
'm' to Signature(0b00000000000001000000000000),
'n' to Signature(0b00000000000010000000000000),
'o' to Signature(0b00000000000100000000000000),
'p' to Signature(0b00000000001000000000000000),
'q' to Signature(0b00000000010000000000000000),
'r' to Signature(0b00000000100000000000000000),
's' to Signature(0b00000001000000000000000000),
't' to Signature(0b00000010000000000000000000),
'u' to Signature(0b00000100000000000000000000),
'v' to Signature(0b00001000000000000000000000),
'w' to Signature(0b00010000000000000000000000),
'x' to Signature(0b00100000000000000000000000),
'y' to Signature(0b01000000000000000000000000),
'z' to Signature(0b10000000000000000000000000),
)
val lettersInverted = mapOf(
Signature(0b00000000000000000000000001) to 'a',
Signature(0b00000000000000000000000010) to 'b',
Signature(0b00000000000000000000000100) to 'c',
Signature(0b00000000000000000000001000) to 'd',
Signature(0b00000000000000000000010000) to 'e',
Signature(0b00000000000000000000100000) to 'f',
Signature(0b00000000000000000001000000) to 'g',
Signature(0b00000000000000000010000000) to 'h',
Signature(0b00000000000000000100000000) to 'i',
Signature(0b00000000000000001000000000) to 'j',
Signature(0b00000000000000010000000000) to 'k',
Signature(0b00000000000000100000000000) to 'l',
Signature(0b00000000000001000000000000) to 'm',
Signature(0b00000000000010000000000000) to 'n',
Signature(0b00000000000100000000000000) to 'o',
Signature(0b00000000001000000000000000) to 'p',
Signature(0b00000000010000000000000000) to 'q',
Signature(0b00000000100000000000000000) to 'r',
Signature(0b00000001000000000000000000) to 's',
Signature(0b00000010000000000000000000) to 't',
Signature(0b00000100000000000000000000) to 'u',
Signature(0b00001000000000000000000000) to 'v',
Signature(0b00010000000000000000000000) to 'w',
Signature(0b00100000000000000000000000) to 'x',
Signature(0b01000000000000000000000000) to 'y',
Signature(0b10000000000000000000000000) to 'z',
)
fun String.toSignature(): Signature = map { letters[it]!! }.merge() | [
{
"class_path": "Jeff-Gillot__word-clique__4b11007/MainKt$main$lambda$20$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class MainKt$main$lambda$20$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public MainKt$main$lambda$20$$inlined$sortedBy$1();\n Code:... |
jjrodcast__CompetitiveProblems__a91868c/leetcode/UniquePathsTwo.kt | /*
Enlace al problema:
https://leetcode.com/problems/unique-paths-ii/
La solución se encuentra dentro de la función `uniquePathsWithObstacles`, el resto del código es para
ejecutarlo de manera local.
Explanation:
Given the grid:
[0,0,0]
[0,1,0]
[0,0,0]
Initial information:
*) We are at position (0,0) and the target is (2,2)
*) Inside the grid there are obstacles (1's)
Question:
How many paths can we find from initial position to target position?
Solution
--------
1) Add a new `row` and `column` to the grid.
[I,0,0,0]
[0,X,0,0]
[0,0,T,0]
[0,0,0,0]
2) Check if initial position is and obstacle, if true assign `0` otherwise `1`
[1,0,0,0]
[0,X,0,0]
[0,0,T,0]
[0,0,0,0]
3) Now check for the first `row` and the first `column` and if is and
obstacle assign `0` otherwise the previous value (in this case just `row` or `column`)
[1,1,1,1]
[1,X,0,0]
[1,0,T,0]
[1,0,0,0]
4) Finally we pre-calculate all the other values to the target.
To do this we need to assign to the current value (x,y) the sum
of the paths that can lead us to the `target` which are:
(row, col-1) and (row-1, col)
* If there is an obstacle in the current position (x,y), we assign `0`
[1,1,1,1]
[1,0,1,2]
[1,1,2,4]
[1,2,4,8]
Time complexity: O(m*n)
*/
class Solution {
fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int {
val rows = obstacleGrid.size
val cols = obstacleGrid[0].size
val grid = Array(rows + 1) { IntArray(cols + 1) { 0 } }
grid[0][0] = if (obstacleGrid[0][0] == 0) 1 else 0
for (i in 1 until rows) if (obstacleGrid[i][0] == 0) grid[i][0] = grid[i - 1][0]
for (i in 1 until cols) if (obstacleGrid[0][i] == 0) grid[0][i] = grid[0][i - 1]
for (i in 1 until rows) {
for (j in 1 until cols) {
grid[i][j] = if (obstacleGrid[i][j] == 0) grid[i - 1][j] + grid[i][j - 1] else 0
}
}
return grid[rows - 1][cols - 1]
}
}
fun main() {
// Class for Solution
val solution = Solution()
// Test #1: Input grid
val grid = arrayOf(
intArrayOf(0, 0, 0),
intArrayOf(0, 1, 0),
intArrayOf(0, 0, 0)
)
// Test #1: Output solution
println(solution.uniquePathsWithObstacles(grid))
} | [
{
"class_path": "jjrodcast__CompetitiveProblems__a91868c/UniquePathsTwoKt.class",
"javap": "Compiled from \"UniquePathsTwo.kt\"\npublic final class UniquePathsTwoKt {\n public static final void main();\n Code:\n 0: new #8 // class Solution\n 3: dup\n 4: invok... |
polydisc__codelibrary__be589a7/kotlin/MaxBipartiteMatchingEV.kt | // https://en.wikipedia.org/wiki/Matching_(graph_theory)#In_unweighted_bipartite_graphs in O(V * E)
fun maxMatching(graph: Array<out List<Int>>): Int {
val n1 = graph.size
val n2 = (graph.flatMap { it }.maxOrNull() ?: -1) + 1
val matching = IntArray(n2) { -1 }
return (0 until n1).sumOf { findPath(graph, it, matching, BooleanArray(n1)) }
}
fun findPath(graph: Array<out List<Int>>, u1: Int, matching: IntArray, vis: BooleanArray): Int {
vis[u1] = true
for (v in graph[u1]) {
val u2 = matching[v]
if (u2 == -1 || !vis[u2] && findPath(graph, u2, matching, vis) == 1) {
matching[v] = u1
return 1
}
}
return 0
}
// Usage example
fun main(args: Array<String>) {
val g = (1..2).map { arrayListOf<Int>() }.toTypedArray()
g[0].add(0)
g[0].add(1)
g[1].add(1)
println(2 == maxMatching(g))
}
| [
{
"class_path": "polydisc__codelibrary__be589a7/MaxBipartiteMatchingEVKt.class",
"javap": "Compiled from \"MaxBipartiteMatchingEV.kt\"\npublic final class MaxBipartiteMatchingEVKt {\n public static final int maxMatching(java.util.List<java.lang.Integer>[]);\n Code:\n 0: aload_0\n 1: ldc ... |
cznno__advent-of-code-kotlin__423e711/src/Day02.kt | import java.nio.file.Files
import java.nio.file.Path
object Day02 {
private val map1 = mapOf("X" to 1, "Y" to 2, "Z" to 3)
private val map2 = mapOf(
"A X" to 3, "A Y" to 6, "A Z" to 0,
"B X" to 0, "B Y" to 3, "B Z" to 6,
"C X" to 6, "C Y" to 0, "C Z" to 3,
)
private val list = listOf(
"001", "012", "020",
"100", "111", "122",
"202", "210", "221"
)
fun toDigi(t: String): Char {
return when (t) {
"X", "A" -> '0'
"Y", "B" -> '1'
else -> '2'
}
}
fun part1(data: List<String>) {
var sum = 0
for (s in data) {
val k = s.split(" ")
val m = toDigi(k[0])
val n = toDigi(k[1])
for (t in list) {
if (t[0] == m && t[1] == n) {
sum += when (t[1]) {
'0' -> 1
'1' -> 2
else -> 3
}
sum += when (t[2]) {
'0' -> 0
'1' -> 3
else -> 6
}
}
}
// sum += map1[s.split(" ")[1]]!!
// sum += map2[s]!!
}
println(sum) //8890
}
fun part2(data: List<String>) {
var sum = 0
for (s in data) {
val k = s.split(" ")
val m = toDigi(k[0])
val n = toDigi(k[1])
for (t in list) {
if (t[0] == m && t[2] == n) {
sum += when (t[1]) {
'0' -> 1
'1' -> 2
else -> 3
}
sum += when (t[2]) {
'0' -> 0
'1' -> 3
else -> 6
}
}
}
}
println(sum)
}
}
fun main() {
val data = Files.readAllLines(Path.of("./input/Day02.txt"))
Day02.part1(data)
Day02.part2(data)
}
| [
{
"class_path": "cznno__advent-of-code-kotlin__423e711/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String ./input/Day02.txt\n 2: iconst_0\n 3: anewarray #10 ... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Utils.kt | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
import kotlin.math.absoluteValue
import kotlin.math.sign
fun Boolean.toInt() = if (this) 1 else 0
fun IntProgression.isRange() = step.sign > 0
operator fun <T> List<List<T>>.get(ind: Pair<Int, Int>) = this[ind.first][ind.second]
operator fun <T> List<MutableList<T>>.set(ind: Pair<Int, Int>, value: T) {
this[ind.first][ind.second] = value
}
fun <T> List<List<T>>.indexPairs(predicate: (T) -> Boolean = { true }) =
this.indices.flatMap { i ->
this.first().indices.map { j -> i to j }
}.filter { predicate(this[it]) }
operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>) = first + other.first to second + other.second
operator fun Pair<Int, Int>.minus(other: Pair<Int, Int>) = first - other.first to second - other.second
fun Pair<Int, Int>.diff() = (second - first).absoluteValue
operator fun <T, K> Pair<T, K>.compareTo(other: Pair<T, K>) where T : Comparable<T>, K : Comparable<K> =
if (first == other.first) second.compareTo(other.second) else first.compareTo(other.first)
infix fun Pair<Int, Int>.manhattan(other: Pair<Int, Int>) =
(first - other.first).absoluteValue + (second - other.second).absoluteValue
/**
* Pairs intersect as ranges.
*/
fun <T> Pair<T, T>.intersect(other: Pair<T, T>) where T : Comparable<T> =
if (this.compareTo(other) < 0) second >= other.first else first <= other.second
/**
* One of pairs fully includes other as range.
*/
fun <T, K> Pair<T, K>.include(other: Pair<T, K>) where T : Comparable<T>, K : Comparable<K> =
first.compareTo(other.first).sign + second.compareTo(other.second).sign in -1..1
/**
* Returns list of pairs with indexes of non-diagonal neighbours' shifts in 2D array.
*/
fun neighbours() =
(-1..1).flatMap { i ->
(-1..1).filter { j -> (i + j).absoluteValue == 1 }.map { j -> i to j }
}
/**
* Returns list of pairs with indexes of given point non-diagonal neighbours in 2D array.
*/
fun neighbours(point: Pair<Int, Int>) = neighbours().map { it + point }
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
/**
* Reads blocks of lines separated by empty line.
*/
fun readBlocks(name: String) = File("src", "$name.txt")
.readText()
.trim('\n')
.split("\n\n")
.map { it.split('\n') }
/**
* Reads blocks separated by empty line.
*/
fun readRawBlocks(name: String) = File("src", "$name.txt")
.readText()
.trim('\n')
.split("\n\n")
/**
* Converts string to md5 hash.
*/
fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray()))
.toString(16)
.padStart(32, '0')
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/UtilsKt.class",
"javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final int toInt(boolean);\n Code:\n 0: iload_0\n 1: ifeq 8\n 4: iconst_1\n 5: goto 9\n 8: iconst_... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day14.kt | private data class CurrentUnit(var pile: Int = 500, var height: Int = 0) {
fun diagonalMove(piles: Map<Int, Set<Int>>): Boolean {
if (piles[pile - 1] == null || !piles[pile - 1]!!.contains(height + 1)) {
pile--
height++
return true
}
if (piles[pile + 1] == null || !piles[pile + 1]!!.contains(height + 1)) {
pile++
height++
return true
}
return false
}
fun reset(): Boolean {
if (pile == 500 && height == 0) return false
pile = 500
height = 0
return true
}
}
private fun getPoints(input: List<String>) = input.map { line ->
line.split(" -> ")
.map { it.split(',').map(String::toInt) }
.map { (first, second) -> first to second }
}
private fun getPiles(points: List<List<Pair<Int, Int>>>): MutableMap<Int, MutableSet<Int>> {
val piles = mutableMapOf<Int, MutableSet<Int>>()
points.forEach { line ->
line.zipWithNext().forEach { (start, end) ->
val (minPoint, maxPoint) = if (start < end) start to end else end to start
val (x, y) = maxPoint - minPoint
for (i in 0..x) {
for (j in 0..y) {
piles.computeIfAbsent(minPoint.first + i) { mutableSetOf() }.add(minPoint.second + j)
}
}
}
}
return piles
}
private fun Set<Int>.fallUnitOrNull(height: Int) = this.filter { it > height }.minOrNull()
fun main() {
fun part1(input: List<String>): Int {
val piles = getPiles(getPoints(input))
var cnt = 0
val point = CurrentUnit()
while (true) {
val pile = piles[point.pile]
point.height = pile?.fallUnitOrNull(point.height) ?: return cnt
point.height--
if (point.diagonalMove(piles)) continue
pile.add(point.height)
cnt++
point.reset()
}
}
fun part2(input: List<String>): Int {
val piles = getPiles(getPoints(input))
val floor = piles.values.maxOf { it.max() } + 2
var cnt = 0
val point = CurrentUnit()
while (true) {
val pile = piles.computeIfAbsent(point.pile) { mutableSetOf(floor) }
point.height = pile.fallUnitOrNull(point.height) ?: floor
point.height--
if (point.height != floor - 1 && point.diagonalMove(piles)) continue
pile.add(point.height)
cnt++
if (!point.reset()) return cnt
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day14Kt.class",
"javap": "Compiled from \"Day14.kt\"\npublic final class Day14Kt {\n private static final java.util.List<java.util.List<kotlin.Pair<java.lang.Integer, java.lang.Integer>>> getPoints(java.util.List<java.lang.String>);\n Code:\n ... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day04.kt | private fun rangesPairList(input: List<String>) = input.map { "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex().find(it)!!.destructured }
.map { (l1, l2, r1, r2) -> (l1.toInt() to l2.toInt()) to (r1.toInt() to r2.toInt()) }
fun main() {
fun part1(input: List<String>) = rangesPairList(input).sumOf { (first, second) -> first.include(second).toInt() }
fun part2(input: List<String>) = rangesPairList(input).sumOf { (first, second) -> first.intersect(second).toInt() }
// 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))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n private static final java.util.List<kotlin.Pair<kotlin.Pair<java.lang.Integer, java.lang.Integer>, kotlin.Pair<java.lang.Integer, java.lang.Integer>>> rangesPairL... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day05.kt | import java.util.*
private fun stackPeeks(input: List<List<String>>, move: (List<Stack<Char>>, Int, Int, Int) -> Unit): String {
val (towers, instructions) = input
val stacksSize = towers.last().split("\\s+".toRegex()).last().toInt()
val stacks = List(stacksSize) { Stack<Char>() }
for (i in (0 until towers.size - 1).reversed()) {
for (j in 1 until towers[i].length step 4) {
if (towers[i][j] != ' ') {
stacks[j / 4].push(towers[i][j])
}
}
}
for (instruction in instructions) {
val (amount, from, to) = "move (\\d+) from (\\d+) to (\\d+)".toRegex().find(instruction)!!.destructured
move(stacks, amount.toInt(), from.toInt(), to.toInt())
}
return stacks.map { it.peek() }.joinToString("")
}
fun main() {
fun part1(input: List<List<String>>) =
stackPeeks(input) { stacks: List<Stack<Char>>, amount: Int, from: Int, to: Int ->
repeat(amount) { stacks[to - 1].push(stacks[from - 1].pop()) }
}
fun part2(input: List<List<String>>) =
stackPeeks(input) { stacks: List<Stack<Char>>, amount: Int, from: Int, to: Int ->
stacks[to - 1].addAll(stacks[from - 1].takeLast(amount))
repeat(amount) { stacks[from - 1].pop() }
}
// test if implementation meets criteria from the description, like:
val testInput = readBlocks("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readBlocks("Day05")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n private static final java.lang.String stackPeeks(java.util.List<? extends java.util.List<java.lang.String>>, kotlin.jvm.functions.Function4<? super java.util.List... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day15.kt | import kotlin.math.absoluteValue
private const val TEST_LINE = 10
private const val LINE = 2_000_000
private const val TEST_SIZE = 20
private const val SIZE = 4_000_000
private val template = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex()
private fun getCoordinates(input: List<String>) = input.map { template.matchEntire(it)!!.destructured }
.map { (x, y, bx, by) -> (x.toInt() to y.toInt()) to (bx.toInt() to by.toInt()) }
private fun MutableSet<Pair<Int, Int>>.addRange(other: Pair<Int, Int>) {
for (pair in this) {
if (pair.include(other)) {
if (other.diff() > pair.diff()) {
remove(pair)
addRange(other)
}
return
}
}
for (pair in this) {
if (pair.intersect(other)) {
remove(pair)
addRange(
pair.first.coerceAtMost(other.first)
to pair.second.coerceAtLeast(other.second)
)
return
}
}
add(other)
}
private fun Set<Pair<Int, Int>>.amount() = sumOf { it.diff() + 1 }
private fun fillLine(
coordinates: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>,
line: Int,
leastX: Int = Int.MIN_VALUE,
mostX: Int = Int.MAX_VALUE,
): Set<Pair<Int, Int>> {
val xs = mutableSetOf<Pair<Int, Int>>()
for ((sensor, beacon) in coordinates) {
val beaconDistance = sensor.manhattan(beacon)
val lineDistance = (line - sensor.second).absoluteValue
val rangeWidth = beaconDistance - lineDistance
if (rangeWidth < 0) continue
xs.addRange(
(sensor.first - rangeWidth).coerceAtLeast(leastX)
to (sensor.first + rangeWidth).coerceAtMost(mostX)
)
}
return xs
}
private fun frequency(x: Int, y: Int) = 1L * SIZE * x + y
fun main() {
fun part1(input: List<String>, line: Int) = fillLine(getCoordinates(input), line).amount() - 1
fun part2(input: List<String>, size: Int): Long? {
val coordinates = getCoordinates(input)
for (line in 0..size) {
val xs = fillLine(coordinates, line, 0, size)
if (xs.amount() != size + 1) {
if (xs.size == 2) {
assert(xs.first().second + 1 == xs.last().first - 1)
return frequency(xs.first().second + 1, line)
}
assert(xs.size == 1)
return frequency(if (xs.first().first == 0) size else 0, line)
}
}
return null
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, TEST_LINE) == 26)
check(part2(testInput, TEST_SIZE) == 56_000_011L)
val input = readInput("Day15")
println(part1(input, LINE))
println(part2(input, SIZE))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day15Kt.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15Kt {\n private static final int TEST_LINE;\n\n private static final int LINE;\n\n private static final int TEST_SIZE;\n\n private static final int SIZE;\n\n private ... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day07.kt | private const val MAX_DIR_SIZE = 100_000
private const val DISK_SPACE = 70_000_000
private const val UPDATE_SIZE = 30_000_000
private data class FS(
val name: String,
val parent: FS?, // null for root dir only.
) {
val files: MutableList<Int> = mutableListOf()
val folders: MutableList<FS> = mutableListOf()
var size: Int = 0
get() {
if (field == 0) field = files.sum() + folders.sumOf { it.size }
return field
}
fun fill(instructions: List<String>): FS {
var curDir = this
for (instruction in instructions) {
when {
instruction.startsWith("cd ") -> curDir = curDir.handleCd(instruction)
instruction.startsWith("ls ") -> curDir.handleLs(instruction)
else -> error("Incorrect input")
}
}
return this
}
private fun handleCd(instruction: String): FS {
val dir = instruction.split(" ").last()
if (dir == "/") return this
return if (dir == "..") this.parent!! else this.cd(dir)
}
private fun cd(name: String) = this.folders.first { it.name == name } // presuming absolute paths unique.
private fun handleLs(instruction: String): FS {
val content = instruction.split(" ").drop(1).chunked(2).map { it.first() to it.last() }
for ((first, second) in content) {
when {
first == "dir" -> this.folders.add(FS(second, this))
first.toIntOrNull() != null -> this.files.add(first.toInt()) // presuming file names unique.
else -> error("Incorrect input")
}
}
return this
}
fun <T> map(f: (FS) -> T): List<T> {
val res = mutableListOf(f(this))
res.addAll(folders.flatMap { it.map(f) })
return res
}
fun print(indent: Int = 0) {
repeat(indent) { print(" - ") }
println(this)
folders.map { it.print(indent + 1) }
}
override fun toString() = "FS($name, $files, $size)"
}
fun getInstructions(input: List<String>) = input.joinToString(" ").split("$ ").drop(1).map(String::trim)
fun main() {
fun part1(input: List<String>) =
FS("/", null).fill(getInstructions(input)).map { it.size }.filter { it <= MAX_DIR_SIZE }.sum()
fun part2(input: List<String>): Int {
val root = FS("/", null)
root.fill(getInstructions(input))
val sizes = root.map { it.size }
val required = UPDATE_SIZE - (DISK_SPACE - sizes.first())
return sizes.filter { it >= required }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readBlocks("Day07_test").first()
check(part1(testInput) == 95_437)
check(part2(testInput) == 24_933_642)
val input = readBlocks("Day07").first()
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day07Kt.class",
"javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt {\n private static final int MAX_DIR_SIZE;\n\n private static final int DISK_SPACE;\n\n private static final int UPDATE_SIZE;\n\n public static final java.util.Lis... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day13.kt | private val DIVIDER_PACKETS = listOf("[[2]]", "[[6]]")
private sealed interface Signal : Comparable<Signal?> {
override operator fun compareTo(signal: Signal?): Int
}
private data class SingleSignal(val element: Int) : Signal {
fun toMultiSignal() = MultiSignal(listOf(this))
override fun compareTo(signal: Signal?) = when (signal) {
null -> 1
is SingleSignal -> element.compareTo(signal.element)
is MultiSignal -> toMultiSignal().compareTo(signal)
}
}
private data class MultiSignal(val items: List<Signal>) : Signal {
override fun compareTo(signal: Signal?): Int = when (signal) {
null -> 1
is SingleSignal -> compareTo(signal.toMultiSignal())
is MultiSignal -> items.mapIndexed { i, e -> e.compareTo(signal.items.getOrNull(i)) }.firstOrNull { it != 0 }
?: items.size.compareTo(signal.items.size)
}
}
private fun parseSignal(input: String): Signal {
val res = mutableListOf<Signal>()
var values = input.substring(1, input.length - 1)
while (values.contains(',')) {
val number = values.substringBefore(',').toIntOrNull()
res += if (number != null) {
SingleSignal(number)
} else {
val list = values.firstInnerList()
parseSignal(list).also { values = values.substringAfter(list) }
}
values = values.substringAfter(',')
}
if (values.contains('[')) {
res += parseSignal(values)
} else if (values.isNotEmpty()) {
res += SingleSignal(values.toInt())
}
return MultiSignal(res)
}
private fun String.firstInnerList(): String {
var balance = 0
for (i in indices) {
when (get(i)) {
'[' -> balance++
']' -> balance--
}
if (balance == 0) return substring(0, i + 1) // assuming given string starts with '['.
}
return this
}
fun main() {
fun part1(input: List<List<String>>) =
input.map { (first, second) -> parseSignal(first) to parseSignal(second) }.withIndex()
.filter { (_, value) -> value.first < value.second }.sumOf { (i) -> i + 1 }
fun part2(input: List<List<String>>): Int {
val signals = input.flatten().toMutableList()
signals.addAll(DIVIDER_PACKETS)
val sortedSignals = signals.map(::parseSignal).sorted()
return DIVIDER_PACKETS.map { sortedSignals.indexOf(parseSignal(it)) + 1 }.reduce(Int::times)
}
// test if implementation meets criteria from the description, like:
val testInput = readBlocks("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readBlocks("Day13")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day13Kt.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13Kt {\n private static final java.util.List<java.lang.String> DIVIDER_PACKETS;\n\n private static final Signal parseSignal(java.lang.String);\n Code:\n 0: new ... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day03.kt | private fun compartments(input: List<String>) = input.map { it.trim().chunked(it.length / 2) }
private fun groups(input: List<String>) = input.windowed(3, 3)
private fun List<List<String>>.intersect() = flatMap { it.map(String::toSet).reduce(Set<Char>::intersect) }
private fun Char.toPriority() = if (isLowerCase()) this - 'a' + 1 else this - 'A' + 27
fun main() {
fun part1(input: List<String>) = compartments(input).intersect().sumOf { it.toPriority() }
fun part2(input: List<String>) = groups(input).intersect().sumOf { it.toPriority() }
// 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))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n private static final java.util.List<java.util.List<java.lang.String>> compartments(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: che... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day02.kt | private const val RPS_SIZE = 3
private fun String.toInt() = when (this) {
"A", "X" -> 1
"B", "Y" -> 2
"C", "Z" -> 3
else -> error("Incorrect input")
}
private fun Pair<Int, Int>.game1() = second + when {
first % RPS_SIZE + 1 == second -> 6
first == second -> 3
(first + 1) % RPS_SIZE + 1 == second -> 0
else -> error("Incorrect input game 1")
}
private fun Pair<Int, Int>.game2() = when (second) {
1 -> (first + 1) % RPS_SIZE + 1
2 -> 3 + first
3 -> 6 + first % RPS_SIZE + 1
else -> error("Incorrect input game 2")
}
private fun parseInput(input: List<String>) =
input.map { it.trim().split(' ', limit = 2) }.map { it.first().toInt() to it.last().toInt() }
fun main() {
fun part1(input: List<String>) = parseInput(input).sumOf { it.game1() }
fun part2(input: List<String>) = parseInput(input).sumOf { it.game2() }
// 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))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n private static final int RPS_SIZE;\n\n private static final int toInt(java.lang.String);\n Code:\n 0: aload_0\n 1: astore_1\n 2: aload_1\n ... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day12.kt | var start = 0 to 0
var end = 0 to 0
private fun heights(input: List<String>) =
input.mapIndexed { i, line ->
line.mapIndexed { j, char ->
when (char) {
'S' -> 'a'.also { start = i to j }
'E' -> 'z'.also { end = i to j }
else -> char
} - 'a'
}
}
private fun dijkstra(heights: List<List<Int>>, start: Pair<Int, Int>): List<List<Int>> {
val distances = List(heights.size) { MutableList(heights.first().size) { Int.MAX_VALUE } }
val unvisited = distances.indexPairs().toMutableSet()
distances[start] = 0
var cur = start
while (true) {
unvisited.remove(cur)
neighbours(cur).filter { (i, j) -> i in distances.indices && j in distances.first().indices }
.filter { unvisited.contains(it) }.forEach {
if (heights[it] <= heights[cur] + 1) {
distances[it] = distances[it].coerceAtMost(distances[cur] + 1)
}
}
val next = unvisited.minByOrNull { distances[it] }
if (next == null || distances[next] == Int.MAX_VALUE) break
cur = next
}
return distances
}
fun main() {
fun part1(input: List<String>) = dijkstra(heights(input), start)[end]
fun part2(input: List<String>): Int {
val heights = heights(input)
return heights.indexPairs { it == 0 }.minOf { dijkstra(heights, it)[end] }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day12Kt.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class Day12Kt {\n private static kotlin.Pair<java.lang.Integer, java.lang.Integer> start;\n\n private static kotlin.Pair<java.lang.Integer, java.lang.Integer> end;\n\n public sta... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day11.kt | private val template = """
Monkey (\d+):
Starting items: (.*?)
Operation: new = old (.) (.+)
Test: divisible by (\d+)
If true: throw to monkey (\d+)
If false: throw to monkey (\d+)
""".trim().toRegex()
private data class MonkeyBusiness(
val items: MutableList<ULong>,
val op: (ULong, ULong) -> ULong,
val value: String,
val divider: ULong,
val onTrue: Int,
val onFalse: Int,
var inspected: ULong = 0U,
) {
fun throwDecision(worryLevel: ULong) = if (worryLevel % divider == 0.toULong()) onTrue else onFalse
fun roundEnd() {
inspected += items.size.toUInt()
items.clear()
}
}
private fun parseMonkeys(input: List<String>) = input.map { monkey ->
val (_, list, sign, value, divider, onTrue, onFalse) = template.matchEntire(monkey)!!.destructured
val items = list.split(", ").map(String::toULong).toMutableList()
val operation: (ULong, ULong) -> ULong = when (sign.first()) {
'+' -> ULong::plus
'*' -> ULong::times
else -> error("Incorrect input")
}
MonkeyBusiness(items, operation, value, divider.toULong(), onTrue.toInt(), onFalse.toInt())
}
private fun throwRounds(monkeys: List<MonkeyBusiness>, times: Int, calming: (ULong) -> ULong): ULong {
val greatDivider = monkeys.map { it.divider }.reduce(ULong::times)
repeat(times) {
for (monkey in monkeys) {
for (item in monkey.items) {
val numberValue = monkey.value.toULongOrNull() ?: item
val worryLevel = calming(monkey.op(item, numberValue)) % greatDivider
monkeys[monkey.throwDecision(worryLevel)].items.add(worryLevel)
}
monkey.roundEnd()
}
}
return monkeys.map { it.inspected }.sorted().takeLast(2).reduce(ULong::times)
}
fun main() {
fun part1(input: List<String>) = throwRounds(parseMonkeys(input), 20) { it / 3U }
fun part2(input: List<String>) = throwRounds(parseMonkeys(input), 10_000) { it }
// test if implementation meets criteria from the description, like:
val testInput = readRawBlocks("Day11_test")
check(part1(testInput) == 10_605.toULong())
check(part2(testInput) == 2_713_310_158.toULong())
val input = readRawBlocks("Day11")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day11Kt$parseMonkeys$1$operation$2.class",
"javap": "Compiled from \"Day11.kt\"\nfinal class Day11Kt$parseMonkeys$1$operation$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function2<kotlin.ULong, kotlin.ULong, ... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day10.kt | private const val SCREEN_WIDTH = 40
private const val SCREEN_SIZE = 6 * SCREEN_WIDTH
private const val SIGNAL_STRENGTH = SCREEN_WIDTH / 2
private fun cycleSignals(input: List<String>): List<Int> {
val signals = MutableList(2 * input.size + 1) { 1 }
var cycle = 0
for (i in input.indices) {
signals[cycle + 1] = signals[cycle]
val instruction = input[i].split(" ")
if (instruction.first() == "addx") {
signals[++cycle + 1] = signals[cycle] + instruction.last().toInt()
}
cycle++
}
return signals
}
fun main() {
fun part1(input: List<String>): Int {
val signals = cycleSignals(input)
return (SIGNAL_STRENGTH..SCREEN_SIZE - SIGNAL_STRENGTH step SCREEN_WIDTH).sumOf { it * signals[it - 1] }
}
fun part2(input: List<String>): String {
val signals = cycleSignals(input).take(SCREEN_SIZE)
return signals.chunked(SCREEN_WIDTH) { line ->
line.mapIndexed { ind, signal -> if (signal in ind - 1..ind + 1) '#' else '.' }.joinToString("")
}.joinToString("\n")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13_140)
println(part2(testInput))
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day10Kt.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class Day10Kt {\n private static final int SCREEN_WIDTH;\n\n private static final int SCREEN_SIZE;\n\n private static final int SIGNAL_STRENGTH;\n\n private static final java.ut... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day09.kt | import kotlin.math.absoluteValue
import kotlin.math.sign
private data class Cell(var x: Int = 0, var y: Int = 0) {
fun move(other: Cell) {
x += other.x
y += other.y
}
fun isAttached(other: Cell) = (x - other.x).absoluteValue < 2 && (y - other.y).absoluteValue < 2
fun follow(other: Cell) {
x += (other.x - x).sign
y += (other.y - y).sign
}
}
private fun moveTheRope(moves: List<String>, rope: List<Cell>): Int {
val res = HashSet<Cell>()
res.add(Cell())
for (move in moves) {
val (direction, value) = move.split(" ")
val step = when (direction) {
"R" -> Cell(1)
"L" -> Cell(-1)
"U" -> Cell(y = 1)
"D" -> Cell(y = -1)
else -> error("incorrect input")
}
for (i in 0 until value.toInt()) {
rope.first().move(step)
for (j in 1 until rope.size) {
if (rope[j].isAttached(rope[j - 1])) continue
rope[j].follow(rope[j - 1])
}
res.add(rope.last().copy())
}
}
return res.size
}
fun main() {
fun part1(input: List<String>) = moveTheRope(input, List(2) { Cell() })
fun part2(input: List<String>) = moveTheRope(input, List(10) { Cell() })
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day09Kt.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt {\n private static final int moveTheRope(java.util.List<java.lang.String>, java.util.List<Cell>);\n Code:\n 0: new #9 // class jav... |
ShuffleZZZ__advent-of-code-kotlin__5a3cff1/src/Day08.kt | private fun getGrid(input: List<String>) = input.map { it.map(Char::digitToInt).toTypedArray() }.toTypedArray()
private fun observeLines(grid: Array<Array<Int>>, res: Array<BooleanArray>, lineInds: IntRange, rowInds: IntProgression) {
val maxRowInd = if (rowInds.isRange()) 0 else grid.first().size - 1
for (i in lineInds) {
var max = grid[i + 1][maxRowInd]
for (j in rowInds) {
if (grid[i + 1][j + 1] > max) {
res[i][j] = true
max = grid[i + 1][j + 1]
}
}
}
if (rowInds.isRange()) observeLines(grid, res, lineInds, rowInds.reversed())
}
private fun observeRows(grid: Array<Array<Int>>, res: Array<BooleanArray>, lineInds: IntProgression, rowInds: IntRange) {
val maxLineInd = if (lineInds.isRange()) 0 else grid.size - 1
for (j in rowInds) {
var max = grid[maxLineInd][j + 1]
for (i in lineInds) {
if (grid[i + 1][j + 1] > max) {
res[i][j] = true
max = grid[i + 1][j + 1]
}
}
}
if (lineInds.isRange()) observeRows(grid, res, lineInds.reversed(), rowInds)
}
private fun scenicScore(grid: Array<Array<Int>>, spot: Pair<Int, Int>) =
neighbours().map { observeTree(grid, spot, it) }.reduce(Int::times)
private fun observeTree(grid: Array<Array<Int>>, spot: Pair<Int, Int>, shift: Pair<Int, Int>): Int {
var dist = 0
var indexes = spot + shift
while (indexes.first in grid.indices && indexes.second in grid.first().indices) {
dist++
if (grid[indexes.first][indexes.second] >= grid[spot.first][spot.second]) break
indexes += shift
}
return dist
}
fun main() {
fun part1(input: List<String>): Int {
val grid = getGrid(input)
val n = grid.size
val m = grid.first().size
val res = Array(n - 2) { BooleanArray(m - 2) { false } }
observeLines(grid, res, res.indices, res.first().indices)
observeRows(grid, res, res.indices, res.first().indices)
return res.sumOf { it.count { e -> e } } + 2 * (n + m - 2)
}
fun part2(input: List<String>): Int {
val grid = getGrid(input)
val res = Array(grid.size - 2) { IntArray(grid.first().size - 2) { 0 } }
for (i in res.indices) {
for (j in res.indices) {
res[i][j] = scenicScore(grid, i + 1 to j + 1)
}
}
return res.maxOf { it.max() }
}
// 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))
}
| [
{
"class_path": "ShuffleZZZ__advent-of-code-kotlin__5a3cff1/Day08Kt.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n private static final java.lang.Integer[][] getGrid(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: checkcast #9 /... |
Kirchberg__BigDataPL__b6a459a/LR6/src/main/kotlin/Task2V1.kt | // Списки (стеки, очереди) I(1..n) и U(1..n) содержат результаты n измерений тока и напряжения на неизвестном
// сопротивлении R. Найти приближенное число R методом наименьших квадратов.
import kotlin.math.pow
// Create a class LeastSquaresR that takes two lists of measurements, currents, and voltages
class LeastSquaresR(private val currents: List<Double>, private val voltages: List<Double>) {
// Check if the input lists have the same size
init {
require(currents.size == voltages.size) { "Currents and voltages lists must have the same size" }
}
// Implement a method that calculates the least squares approximation of R based on the input data
fun calculateR(): Double {
// Calculate the sum of the product of each current and voltage measurement
val sumIU = currents.zip(voltages) { i, u -> i * u }.sum()
// Calculate the sum of the square of each current measurement
val sumISquared = currents.map { it.pow(2) }.sum()
// Calculate the number of measurements
val n = currents.size
// Calculate the approximate value of the unknown resistance R using the least squares method
val r = sumIU / sumISquared
return r
}
}
fun task2V1() {
// Provide sample data: two lists of current and voltage measurements
val currents = listOf(0.5, 1.0, 1.5, 2.0, 2.5)
val voltages = listOf(1.0, 2.1, 3.1, 4.1, 5.0)
// Create a LeastSquaresR object with the sample data
val leastSquaresR = LeastSquaresR(currents, voltages)
// Calculate the approximate value of the unknown resistance R
val r = leastSquaresR.calculateR()
// Print the result
println("The approximate value of the unknown resistance R is: $r Ω")
} | [
{
"class_path": "Kirchberg__BigDataPL__b6a459a/Task2V1Kt.class",
"javap": "Compiled from \"Task2V1.kt\"\npublic final class Task2V1Kt {\n public static final void task2V1();\n Code:\n 0: iconst_5\n 1: anewarray #8 // class java/lang/Double\n 4: astore_1\n 5: ... |
Kirchberg__BigDataPL__b6a459a/LR7/src/main/kotlin/Task1V3.kt | // В тексте нет слов, начинающихся одинаковыми буквами. Напечатать слова текста в таком порядке, чтобы последняя буква
// каждого слова совпадала с первой буквой последующего слова. Если все слова нельзя напечатать в таком порядке, найти
// такую цепочку, состоящую из наибольшего количества слов.
// The WordChainFinder class takes a list of words and finds the longest word chain
class WordChainFinder(private val words: List<String>) {
// A recursive method to find a word chain given a current chain and a list of remaining words
private fun findWordChain(currentChain: List<String>, remainingWords: List<String>): List<String> {
// If there are no remaining words, return the current chain
if (remainingWords.isEmpty()) {
return currentChain
}
// Get the last letter of the last word in the current chain
val lastLetter = currentChain.last().last()
// Find the candidate words in the remaining words that start with the last letter of the current chain
val candidates = remainingWords.filter { it.first() == lastLetter }
// If there are no candidates, return the current chain
if (candidates.isEmpty()) {
return currentChain
}
// For each candidate word, extend the current chain with the candidate and remove it from the remaining words
val chains = candidates.map { candidate ->
val newRemainingWords = remainingWords.toMutableList().apply { remove(candidate) }
findWordChain(currentChain + candidate, newRemainingWords)
}
// Return the longest chain found among the chains extended with the candidates
return chains.maxByOrNull { it.size } ?: currentChain
}
// The findLongestWordChain method finds the longest word chain by starting a search from each word in the list
fun findLongestWordChain(): List<String> {
return words.map { word ->
val remainingWords = words.toMutableList().apply { remove(word) }
findWordChain(listOf(word), remainingWords)
}.maxByOrNull { it.size } ?: emptyList()
}
}
fun task1V3() {
// Provide an example input text
val text = "java android kotlin rust"
// Split the input text into words
val words = text.split(" ")
// Create a WordChainFinder object with the list of words
val wordChainFinder = WordChainFinder(words)
// Call the findLongestWordChain method to find the longest chain of words
val longestWordChain = wordChainFinder.findLongestWordChain()
// Print the longest word chain to the console
println("Longest word chain: ${longestWordChain.joinToString(", ")}")
} | [
{
"class_path": "Kirchberg__BigDataPL__b6a459a/Task1V3Kt.class",
"javap": "Compiled from \"Task1V3.kt\"\npublic final class Task1V3Kt {\n public static final void task1V3();\n Code:\n 0: ldc #8 // String java android kotlin rust\n 2: astore_0\n 3: aload_0\n ... |
austin226__codeforces-kt__4377021/contest1904/src/main/kotlin/D1.kt | // https://codeforces.com/contest/1904/problem/D1
private fun String.splitWhitespace() = split("\\s+".toRegex())
private fun readInt(): Int = readln().toInt()
private fun readInts(): List<Int> = readln().splitWhitespace().map { it.toInt() }
fun canABecomeB(n: Int, a: MutableList<Int>, b: List<Int>): Boolean {
// If any b[i] < a[a], return false
if ((0..<n).any { i -> b[i] < a[i] }) {
return false
}
for (g in 0..n) {
for (i in 0..<n) {
if (b[i] == g && a[i] < g) {
// Find an l to the left
var l = i
while (l > 0 && a[l - 1] <= g && b[l - 1] >= g) {
l--
}
// Find r
var r = i
while (r < n - 1 && a[r + 1] <= g && b[r + 1] >= g) {
r++
}
if (!(l..r).any { j -> a[j] == g }) {
return false
}
for (j in l..r) {
a[j] = g
}
}
}
}
return a == b
}
fun main() {
val t = readInt()
(0..<t).forEach { _ ->
val n = readInt()
val a = readInts().toMutableList()
val b = readInts()
// operation: Choose l and r, where 1 <= l <= r <= n
// let x = max(a[l]..a[r])
// Set all a[l]..a[r] to max
// Output YES if a can become b with any number of operations
// Output NO if not
if (canABecomeB(n, a, b)) {
println("YES")
} else {
println("NO")
}
}
}
| [
{
"class_path": "austin226__codeforces-kt__4377021/D1Kt.class",
"javap": "Compiled from \"D1.kt\"\npublic final class D1Kt {\n private static final java.util.List<java.lang.String> splitWhitespace(java.lang.String);\n Code:\n 0: aload_0\n 1: checkcast #9 // class java/la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.