kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
rolf-rosenbaum__aoc-2022__59cd426/src/main/day09/day09.kt | package day09
import Point
import kotlin.math.sign
import readInput
typealias Segment = Point
enum class Direction { R, U, D, L }
val regex = """([RUDL]) (\d+)""".toRegex()
val start = Segment(0, 0)
fun main() {
val input = readInput("main/day09/Day09")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
return input.toSteps().tailPositions(2).size
}
fun part2(input: List<String>): Int {
return input.toSteps().tailPositions(10).size
}
private fun List<Direction>.tailPositions(length: Int) =
tailPositions(Rope(Array(length) { Point(0, 0) }.toList()))
private fun List<Direction>.tailPositions(rope: Rope) = iterator().let { directions ->
generateSequence(rope) {
if (directions.hasNext()) it.step(directions.next())
else null
}.takeWhile { it != null }.map { it.tail() }.distinct().toList()
}
fun List<String>.toSteps(): List<Direction> {
val directions = mutableListOf<Direction>()
forEach {
regex.matchEntire(it)?.destructured?.let { (direction, steps) ->
repeat(steps.toInt()) {
directions.add(Direction.valueOf(direction))
}
} ?: error("invalid input")
}
return directions
}
data class Rope(val segments: List<Segment> = emptyList()) {
fun step(direction: Direction): Rope {
var newRope = Rope().add(head().move(direction))
segments.drop(1).forEach { segment ->
val head = newRope.tail()
newRope =
if (segment.isAdjacentTo(head)) newRope.add(segment)
else newRope.add(Segment((head.x - segment.x).sign + segment.x, (head.y - segment.y).sign + segment.y))
}
return newRope
}
private fun head() = segments.first()
fun tail(): Segment = segments.last()
private fun add(segment: Segment) = copy(segments = segments + segment)
}
fun Segment.isAdjacentTo(other: Segment): Boolean {
return other.x in (x - 1..x + 1) && other.y in (y - 1..y + 1)
}
fun Segment.move(direction: Direction) =
when (direction) {
Direction.R -> copy(x = x + 1)
Direction.U -> copy(y = y + 1)
Direction.D -> copy(y = y - 1)
Direction.L -> copy(x = x - 1)
} | [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day09/Day09Kt$WhenMappings.class",
"javap": "Compiled from \"day09.kt\"\npublic final class day09.Day09Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method day... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day08/day08.kt | package day08
import Point
import readInput
typealias Forest = List<Tree>
fun main() {
val input = readInput("main/day08/Day08")
val forest = input.flatMapIndexed { y, line ->
line.mapIndexed { x, height ->
Tree(x, y, height.digitToInt())
}
}
println(part1(forest))
println(part2(forest))
}
fun part1(forest: Forest): Int {
return forest.count {
it.isVisibleFromLeft(forest) || it.isVisibleFromRight(forest) || it.isVisibleFromTop(forest) || it.isVisibleFromBottom(forest)
}
}
fun part2(forest: Forest): Int {
return forest.maxOf {
it.scenicScore(forest.associateBy { tree -> Point(tree.x, tree.y) })
}
}
data class Tree(val x: Int, val y: Int, val height: Int) {
operator fun compareTo(other: Tree) = this.height.compareTo(other.height)
override fun equals(other: Any?): Boolean {
return if (other is Tree) x == other.x && y == other.y else false
}
override fun hashCode(): Int {
return x.hashCode() * 31 + y.hashCode()
}
fun isVisibleFromLeft(otherTrees: Forest): Boolean = otherTrees.none { it.y == y && it >= this && it.x < this.x }
fun isVisibleFromRight(otherTrees: Forest): Boolean = otherTrees.none { it.y == y && it >= this && it.x > this.x }
fun isVisibleFromTop(otherTrees: Forest): Boolean = otherTrees.none { it.x == x && it >= this && it.y < this.y }
fun isVisibleFromBottom(otherTrees: Forest): Boolean = otherTrees.none { it.x == x && it >= this && it.y > this.y }
fun scenicScore(treeMap: Map<Point, Tree>): Int {
return countVisibleTreesLeft(treeMap) * countVisibleTreesDown(treeMap) * countVisibleTreesRight(treeMap) * countVisibleTreesUp(treeMap)
}
private fun countVisibleTreesLeft(treeMap: Map<Point, Tree>): Int {
var result = 0
var xpos = x - 1
while (xpos >= 0 && this > treeMap[Point(xpos, y)]!!) {
result++
xpos--
}
return result + if (xpos < 0) 0 else 1
}
private fun countVisibleTreesRight(treeMap: Map<Point, Tree>): Int {
val maxX = treeMap.maxOf { it.key.x }
var result = 0
var xpos = x + 1
while (xpos <= maxX && this > treeMap[Point(xpos, y)]!!) {
result++
xpos++
}
return result + if (xpos > maxX) 0 else 1
}
private fun countVisibleTreesUp(treeMap: Map<Point, Tree>): Int {
var result = 0
var ypos = y - 1
while (ypos >= 0 && this > treeMap[Point(x, ypos)]!!) {
result++
ypos--
}
return result + if (ypos < 0) 0 else 1
}
private fun countVisibleTreesDown(treeMap: Map<Point, Tree>): Int {
val maxY = treeMap.maxOf { it.key.y }
var result = 0
var ypos = y + 1
while (ypos <= maxY && this > treeMap[Point(x, ypos)]!!) {
result++
ypos++
}
return result + if (ypos > maxY) 0 else 1
}
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day08/Day08Kt.class",
"javap": "Compiled from \"day08.kt\"\npublic final class day08.Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String main/day08/Day08\n 2: invokestatic #14 ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day23/day23.kt | package day23
import Point
import readInput
private typealias Grove = Set<Point>
var directionsToCheck = mutableListOf(
Point::northernNeighbours,
Point::southernNeighbours,
Point::westernNeighbours,
Point::easternNeighbours
)
fun main() {
val input = readInput("main/day23/Day23")
println(year_2017.day23.part1(input))
println(year_2017.day23.part2(input))
}
fun part1(input: List<String>): Int {
return generateSequence(input.toGrove()) { step(it).second }.drop(10).first().let { tenth ->
(1 + tenth.maxOf { it.x } - tenth.minOf { it.x }) *
(1 + tenth.maxOf { it.y } - tenth.minOf { it.y }) - tenth.size
}
}
fun part2(input: List<String>): Int {
directionsToCheck = mutableListOf(
Point::northernNeighbours,
Point::southernNeighbours,
Point::westernNeighbours,
Point::easternNeighbours
)
return generateSequence(emptySet<Point>() to input.toGrove()) { result ->
step(result.second)
}.takeWhile {
it.first != it.second
}.count()
}
private fun step(grove: Set<Point>): Pair<Grove, Grove> {
val proposedSteps = grove.proposedSteps()
directionsToCheck.add(directionsToCheck.removeFirst())
val stepsByElf = proposedSteps.associateBy { it.first }
val possiblePositions = proposedSteps.associateTo(mutableMapOf()) { (_, next) ->
next to proposedSteps.count { it.second == next }
}.filter {
it.value == 1
}.keys
return grove to grove.map { elf ->
if (possiblePositions.contains(stepsByElf[elf]?.second))
stepsByElf[elf]!!.second
else
elf
}.toSet()
}
fun Grove.proposedSteps(): List<Pair<Point, Point>> {
val proposedSteps = mutableListOf<Pair<Point, Point>>()
forEach { elf ->
if (elf.allNeighbours().any { this.contains(it) }) {
val direction = directionsToCheck.firstOrNull { findNeighbours ->
findNeighbours.invoke(elf).dropLast(1).none { this.contains(it) }
}
if (direction != null) {
proposedSteps.add(elf to (elf + direction.invoke(elf).last()))
}
}
}
return proposedSteps
}
fun List<String>.toGrove() =
flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, s ->
if (s == '#') Point(x, y) else null
}
}.toSet()
fun Point.northernNeighbours(): List<Point> {
return listOf(
Point(x - 1, y - 1),
Point(x, y - 1),
Point(x + 1, y - 1),
Point(0, -1),
)
}
fun Point.southernNeighbours(): List<Point> {
return listOf(
Point(x - 1, y + 1),
Point(x, y + 1),
Point(x + 1, y + 1),
Point(0, 1),
)
}
fun Point.easternNeighbours(): List<Point> {
return listOf(
Point(x + 1, y - 1),
Point(x + 1, y),
Point(x + 1, y + 1),
Point(1, 0),
)
}
fun Point.westernNeighbours(): List<Point> {
return listOf(
Point(x - 1, y - 1),
Point(x - 1, y),
Point(x - 1, y + 1),
Point(-1, 0),
)
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day23/Day23Kt$directionsToCheck$3.class",
"javap": "Compiled from \"day23.kt\"\nfinal class day23.Day23Kt$directionsToCheck$3 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<Point, java.util.List<? extends Point>>... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day24/day24.kt | package day24
import Point
import day24.Blizzard.DOWN
import day24.Blizzard.LEFT
import day24.Blizzard.RIGHT
import day24.Blizzard.UP
import day24.Blizzard.WALL
import readInput
typealias Valley = Map<Point, List<Blizzard>>
private val initialValley = readInput("main/day24/Day24").toValley()
private val maxX = initialValley.keys.maxOf { it.x }
private val minX = initialValley.keys.minOf { it.x }
private val maxY = initialValley.keys.maxOf { it.y }
private val minY = initialValley.keys.minOf { it.y }
private val start = initialValley.filter { it.key.y == minY }.keys.first { initialValley[it]!!.isEmpty() }
private val exit = initialValley.filter { it.key.y == maxY }.keys.first { initialValley[it]!!.isEmpty() }
private val walls = initialValley.filter { it.value.firstOrNull() == WALL }
private val valleySequence = generateSequence(initialValley) { it.step() }.take(1000).toList()
fun main() {
println(part1())
println(part2())
}
fun part1(): Int {
return findPath()
}
fun part2(): Int {
val toGoal = findPath()
val backToStart = findPath(entry = exit, currentStep = toGoal, goal = start)
return findPath(currentStep = backToStart)
}
fun findPath(entry: Point = start, currentStep: Int = 0, goal: Point = exit): Int {
val pathsToCheck = mutableListOf(State(entry, currentStep))
val checked = mutableSetOf<State>()
while (pathsToCheck.isNotEmpty()) {
val current = pathsToCheck.removeFirst()
if (current !in checked) {
val nextValley = valleySequence[current.step + 1]
val neighbours = validNeighboursFor(current.point).filter { nextValley.isOpenAt(it) }
if (goal in neighbours) return current.step + 1
checked += current
neighbours.forEach {
pathsToCheck.add(State(it, current.step + 1))
}
}
}
error("lost in the vally of blizzards")
}
fun List<String>.toValley(): Valley {
val valley = mutableMapOf<Point, List<Blizzard>>()
mapIndexed { y, line ->
line.mapIndexed { x, c ->
val p = Point(x, y)
when (c) {
'^' -> valley[p] = listOf(UP)
'v' -> valley[p] = listOf(DOWN)
'<' -> valley[p] = listOf(LEFT)
'>' -> valley[p] = listOf(RIGHT)
'#' -> valley[p] = listOf(WALL)
else -> valley[p] = emptyList()
}
}
}
return valley
}
fun validNeighboursFor(p: Point) = p.neighbours(true)
.filterNot { it in walls }
.filter { it.x in (minX..maxX) }
.filter { it.y in (minY..maxY) }
fun Valley.isOpenAt(p: Point): Boolean = this[p].isNullOrEmpty()
fun Valley.step(): Valley =
mutableMapOf<Point, MutableList<Blizzard>>(
// start and goal must always be in the map
start to mutableListOf(),
exit to mutableListOf()
).let { result ->
(minX..maxX).forEach { x ->
(minY..maxY).forEach { y ->
val here = Point(x, y)
val blizzards = this[here]
if (!blizzards.isNullOrEmpty()) {
blizzards.forEach { blizzard ->
var newLocation = here + blizzard.offset
if (newLocation in walls) {
newLocation = when (blizzard) {
LEFT -> Point(maxX - 1, y)
RIGHT -> Point(minX + 1, y)
UP -> Point(x, maxY - 1)
DOWN -> Point(x, minY + 1)
WALL -> Point(x, y) // walls do not move
}
}
if (result[newLocation] == null) result[newLocation] = mutableListOf(blizzard)
else result[newLocation]!!.add(blizzard)
}
}
}
}
result
}
enum class Blizzard(val offset: Point) {
LEFT(Point(-1, 0)),
RIGHT(Point(1, 0)),
UP(Point(0, -1)),
DOWN(Point(0, 1)),
WALL(Point(0, 0)),
}
data class State(val point: Point, val step: Int) | [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day24/Day24Kt$WhenMappings.class",
"javap": "Compiled from \"day24.kt\"\npublic final class day24.Day24Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method day... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day12/day12.kt | package day12
import Point
import readInput
typealias Grid = MutableMap<Point, Char>
fun main() {
val input = readInput("main/day12/Day12")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int = input.solveFor('S')
fun part2(input: List<String>): Int = input.solveFor('a')
fun List<String>.solveFor(start: Char): Int {
val grid = parse()
val startPoint = grid.filter { it.value == 'S' }.keys.first()
val goal = grid.filterValues { it == 'E' }.keys.first()
grid[goal] = 'z'
return grid.filter { it.value == start }.mapNotNull {
grid[startPoint] = 'a'
distance(it.key, goal, grid)
}.minOf { it }
}
private fun distance(start: Point, goal: Point, grid: Grid): Int? {
// the metaphor is to "flood" the terrain with water, always going in all 4 directions if the neighbouring point is not too high
// and keep track of the distance.
// As soon as the goal is "wet", we have our result
val lake = mutableMapOf(start to 0)
var distance = 0
var currentSize = 0
do {
currentSize = lake.size
distance = grid.floodValley(lake, distance)
} while (!lake.containsKey(goal) && lake.size > currentSize)
if (lake.size <= currentSize) {
// there is no valid path from start to goal
return null
}
return distance
}
fun Grid.floodValley(lake: MutableMap<Point, Int>, distance: Int): Int {
lake.filterValues { it == distance }.forEach { (point, _) ->
point.neighbours().filter {
this[it] != null && this[it]!! - this[point]!! <= 1
}.forEach {
if (!lake.containsKey(it)) lake[it] = distance + 1
}
}
return distance + 1
}
fun List<String>.parse(): Grid {
val result = mutableMapOf<Point, Char>()
forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
result[Point(x, y)] = c
}
}
return result
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day12/Day12Kt.class",
"javap": "Compiled from \"day12.kt\"\npublic final class day12.Day12Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String main/day12/Day12\n 2: invokestatic #14 ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day15/day15.kt | package day15
import Point
import day15.CavePoint.Sensor
import kotlin.math.abs
import readInput
import union
val regex = """.+x=(-?\d+).*y=(-?\d+):.*x=(-?\d+).*y=(-?\d+)""".toRegex()
const val prd_row = 2_000_000
const val test_row = 10
val prd_range = 0..4000000
val test_range = 0..20
typealias Cave = MutableSet<CavePoint>
sealed class CavePoint(open val location: Point) {
data class BeaconExcluded(override val location: Point) : CavePoint(location)
data class Sensor(override val location: Point, val beacon: Point) : CavePoint(beacon) {
val beaconDistance
get() = location.distanceTo(beacon)
}
override fun equals(other: Any?): Boolean {
return if (other is CavePoint) location == other.location else false
}
override fun hashCode(): Int {
return location.hashCode()
}
}
fun main() {
val input = readInput("main/day15/Day15_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val cave = input.parse()
val row = if (input.size < 20) test_row else prd_row
cave.markNoBeaconArea(row)
val beaconLocations = cave.filterIsInstance<Sensor>().map { it.beacon }.toSet()
return cave.count { it.location.y == row && it.location !in beaconLocations }
}
fun part2(input: List<String>): Long {
val cave = input.parse()
val range = if (input.size > 20) prd_range else test_range
range.forEach { row ->
cave.lineRangesFor(row).reduce { acc, range -> (acc.union(range)) ?: return (acc.last + 1) * 4_000_000L + row }
}
return -1
}
fun Cave.markNoBeaconArea(row: Int) {
val sensors = filterIsInstance<Sensor>()
sensors.forEach { sensor ->
(sensor.location.x - sensor.beaconDistance..sensor.location.x + sensor.beaconDistance).forEach { x ->
val candidate = Point(x, row)
if (candidate.distanceTo(sensor.location) <= sensor.beaconDistance) add(CavePoint.BeaconExcluded(candidate))
}
}
}
fun Cave.lineRangesFor(row: Int): List<IntRange> {
return filterIsInstance<Sensor>().map { sensor ->
val distance = sensor.beaconDistance - abs(row - sensor.location.y)
sensor.location.x - distance..sensor.location.x + distance
}.sortedBy { it.first }
}
fun List<String>.parse(): Cave = map {
regex.matchEntire(it)?.destructured?.let { (sX, sY, bX, bY) ->
Sensor(location = Point(x = sX.toInt(), y = sY.toInt()), beacon = Point(bX.toInt(), bY.toInt()))
} ?: error("PARSER PROBLEM")
}.toMutableSet()
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day15/Day15Kt.class",
"javap": "Compiled from \"day15.kt\"\npublic final class day15.Day15Kt {\n private static final kotlin.text.Regex regex;\n\n public static final int prd_row;\n\n public static final int test_row;\n\n private static final kotlin.ran... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day14/day14.kt | package day14
import kotlin.math.max
import kotlin.math.min
import readInput
private typealias Cave = MutableSet<Point>
private typealias Rock = Point
private typealias Grain = Point
private data class Point(val x: Int, val y: Int)
private val source = Point(500, 0)
fun main() {
val input = readInput("main/day14/Day14_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val cave = input.parseTosSolidRock()
return cave.pourSand()
}
fun part2(input: List<String>): Int {
val cave = input.parseTosSolidRock()
val maxX = cave.maxOf { it.x } //.also { println("max x: $it") }
val minX = cave.minOf { it.x } //.also { println("min x: $it") }
val floorY = cave.maxOf { it.y } + 2
cave.addRock(Point(minX - 1500, floorY), Point(maxX + 1500, floorY))
return cave.pourSand()
}
private fun Cave.pourSand(): Int {
val startSize = size
do {
val droppedGrain = source.fall(this)
if (droppedGrain != null) add(droppedGrain)
if (size % 1000 == 0) println(size)
} while (droppedGrain != null)
return size - startSize
}
private fun Grain.fall(cave: Cave): Grain? {
if (cave.contains(source))
return null
if (down().y > cave.maxOf { it.y }) return null
if (!cave.contains(down())) return down().fall(cave)
if (!cave.contains(downLeft())) return downLeft().fall(cave)
if (!cave.contains(downRight())) return downRight().fall(cave)
return this
}
private fun Cave.addRock(start: Point, end: Point) {
val startX = min(start.x, end.x)
val startY = min(start.y, end.y)
val endX = max(start.x, end.x)
val endY = max(start.y, end.y)
(startX..endX).forEach { x ->
(startY..endY).forEach { y ->
add(Rock(x, y))
}
}
}
private fun List<String>.parseTosSolidRock(): Cave {
val cave = mutableSetOf<Point>()
map { line ->
line.split(" -> ")
.map { it.split(", ") }
.windowed(2) { (start, end) ->
cave.addRock(
rock(start.first()),
rock(end.first())
)
}
}
return cave
}
private fun rock(point: String): Rock {
return point.split(",").map { it.toInt() }.let { (x, y) ->
Point(x, y)
}
}
private fun Grain.down() = copy(y = y + 1)
private fun Grain.downLeft() = copy(x = x - 1, y = y + 1)
private fun Grain.downRight() = copy(x = x + 1, y = y + 1)
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day14/Day14Kt.class",
"javap": "Compiled from \"day14.kt\"\npublic final class day14.Day14Kt {\n private static final day14.Point source;\n\n public static final void main();\n Code:\n 0: ldc #8 // String main/day14/Day... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day13/day13.kt | package day13
import java.util.*
import readInput
import second
sealed interface Packet : Comparable<Packet> {
data class ListPacket(val packets: MutableList<Packet> = mutableListOf()) : Packet {
override fun compareTo(other: Packet): Int {
return when (other) {
is IntPacket -> this.compareTo(other.toListPacket())
is ListPacket -> packets.compareTo(other.packets)
}
}
private fun Iterable<Packet>.compareTo(other: Iterable<Packet>): Int {
val left = Stack<Packet>()
this.reversed().forEach { left.push(it) }
val right = Stack<Packet>()
other.reversed().forEach { right.push(it) }
while (left.isNotEmpty()) {
val l = left.pop()
val r = if (right.isNotEmpty()) right.pop() else return 1
val comp = l.compareTo(r)
if (comp != 0) return comp
}
// left is empty is right also empty?
return if (right.isEmpty()) 0 else -1
}
}
data class IntPacket(val value: Int) : Packet {
override fun compareTo(other: Packet): Int {
return when (other) {
is ListPacket -> toListPacket().compareTo(other)
is IntPacket -> value.compareTo(other.value)
}
}
}
fun toListPacket(): Packet = ListPacket(mutableListOf(this))
companion object {
fun parse(input: String): Packet =
toPacket(
input.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex())
.filter { it.isNotBlank() }
.filterNot { it == "," }
.iterator()
)
private fun toPacket(input: Iterator<String>): Packet {
val packets = mutableListOf<Packet>()
while (input.hasNext()) {
when (val symbol = input.next()) {
"]" -> return ListPacket(packets)
"[" -> packets.add(toPacket(input))
else -> packets.add(IntPacket(symbol.toInt()))
}
}
return ListPacket(packets)
}
}
}
fun main() {
val input = readInput("main/day13/Day13")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val list = input.filter(String::isNotBlank).map {
Packet.parse(it)
}.chunked(2)
return list.mapIndexed { index, signals ->
if (signals.first() < signals.second())
index + 1
else
0
}.sum()
}
fun part2(input: List<String>): Int {
val firstDivider = Packet.parse("[[2]]")
val secondDivider = Packet.parse("[[6]]")
val list = (input.filter(String::isNotBlank).map {
Packet.parse(it)
} + listOf(firstDivider, secondDivider)).sorted()
return (list.indexOf(firstDivider) + 1) * (list.indexOf(secondDivider) + 1)
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day13/Day13Kt.class",
"javap": "Compiled from \"day13.kt\"\npublic final class day13.Day13Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String main/day13/Day13\n 2: invokestatic #14 ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day25/day25.kt | package day25
import kotlin.math.pow
import kotlin.math.roundToLong
import readInput
val UNSNAFU = mapOf(
"=" to -2.0,
"-" to -1.0,
"0" to 0.0,
"1" to 1.0,
"2" to 2.0,
)
fun main() {
val input = readInput("main/day25/Day25")
println(part1(input))
}
fun part1(input: List<String>): String {
val numbers = input.associateBy { it.unsnafucate() }
return numbers.keys.sum().snafucate()
}
fun Long.snafucate(): String {
return generateSequence(this) { (it + 2) / 5 }
.takeWhile { it != 0L }.toList()
.map { "012=-"[(it % 5).toInt()] }
.joinToString("").reversed()
}
fun String.unsnafucate(): Long {
return indices.sumOf {
(5.0.pow(it) * UNSNAFU[this[length - it - 1].toString()]!!.toLong()).roundToLong()
}
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day25/Day25Kt.class",
"javap": "Compiled from \"day25.kt\"\npublic final class day25.Day25Kt {\n private static final java.util.Map<java.lang.String, java.lang.Double> UNSNAFU;\n\n public static final java.util.Map<java.lang.String, java.lang.Double> getU... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day22/day22.kt | package day22
import Point
import day22.Direction.DOWN
import day22.Direction.LEFT
import day22.Direction.RIGHT
import day22.Direction.UP
import readInput
typealias Board = Map<Point, Char>
const val WALL = '#'
const val OPEN = '.'
fun main() {
val input = readInput("main/day22/Day22")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val board = input.parseBoard()
val directions = input.readDirections()
var currentDirection = RIGHT
var position = board.filter { it.key.y == 1 }.minBy { it.key.x }.key
var index = 0
while (index < directions.length) {
var steps = ""
while (index < directions.length && directions[index].isDigit()) {
steps += directions[index]
index++
}
val numSteps = steps.toInt()
repeat(numSteps) {
position = board.nextTileFrom(position, currentDirection)
}
if (index < directions.length) {
currentDirection = if (directions[index] == 'L') currentDirection.left() else currentDirection.right()
index++
}
}
return position.y * 1000 + position.x * 4 + currentDirection.facing
}
fun part2(input: List<String>): Int {
val board = input.parseBoard()
val directions = input.readDirections()
var currentDirection = RIGHT
var position = board.filter { it.key.y == 1 }.minBy { it.key.x }.key
var index = 0
while (index < directions.length) {
var steps = ""
while (index < directions.length && directions[index].isDigit()) {
steps += directions[index]
index++
}
val numSteps = steps.toInt()
repeat(numSteps) {
val (pos, dir) = board.nextTileOnCubeFrom(position, currentDirection)
position = pos
currentDirection = dir
}
if (index < directions.length) {
currentDirection = if (directions[index] == 'L') currentDirection.left() else currentDirection.right()
index++
}
}
return position.y * 1000 + position.x * 4 + currentDirection.facing
}
fun List<String>.parseBoard(): Board {
val board = mutableMapOf<Point, Char>()
this.takeWhile { it.isNotBlank() }.mapIndexed { y, line ->
line.mapIndexed { x, c ->
if (c == OPEN || c == WALL) board[Point(x + 1, y + 1)] = c
}
}
return board
}
fun List<String>.readDirections() = this.dropLastWhile { it.isBlank() }.last()
fun Board.nextTileFrom(p: Point, direction: Direction): Point = when (direction) {
UP -> {
var next = Point(p.x, p.y - 1)
if (this[next] == WALL) next = p
if (this[next] == null) next = keys.filter { it.x == p.x }.maxBy { it.y }
if (this[next] == WALL) next = p
next
}
DOWN -> {
var next = Point(p.x, p.y + 1)
if (this[next] == WALL) next = p
if (this[next] == null) next = keys.filter { it.x == p.x }.minBy { it.y }
if (this[next] == WALL) next = p
next
}
RIGHT -> {
var next = Point(p.x + 1, p.y)
if (this[next] == WALL) next = p
if (this[next] == null) next = keys.filter { it.y == p.y }.minBy { it.x }
if (this[next] == WALL) next = p
next
}
LEFT -> {
var next = Point(p.x - 1, p.y)
if (this[next] == WALL) next = p
if (this[next] == null) next = keys.filter { it.y == p.y }.maxBy { it.x }
if (this[next] == WALL) next = p
next
}
}
fun Board.nextTileOnCubeFrom(p: Point, direction: Direction): Pair<Point, Direction> {
return when (direction) {
UP -> nextPositionAndDirection(Point(p.x, p.y - 1), p, direction)
DOWN -> nextPositionAndDirection(Point(p.x, p.y + 1), p, direction)
RIGHT -> nextPositionAndDirection(Point(p.x + 1, p.y), p, direction)
LEFT -> nextPositionAndDirection(Point(p.x - 1, p.y), p, direction)
}
}
private fun Board.nextPositionAndDirection(next: Point, p: Point, direction: Direction): Pair<Point, Direction> {
var next1 = next
var newDirection = direction
if (this[next1] == WALL) next1 = p
if (this[next1] == null) {
val (pos, dir) = gotoNextSide(p, direction)
next1 = pos
newDirection = dir
}
if (this[next1] == WALL) {
next1 = p
newDirection = direction
}
return next1 to newDirection
}
private fun sideOf(pos: Point): Char {
if (pos.x in 51..100 && pos.y in 1..50) return 'A'
if (pos.x in 101..150 && pos.y in 1..50) return 'B'
if (pos.x in 51..100 && pos.y in 51..100) return 'C'
if (pos.x in 51..100 && pos.y in 101..150) return 'D'
if (pos.x in 1..50 && pos.y in 101..150) return 'E'
if (pos.x in 1..50 && pos.y in 151..200) return 'F'
error("Side does not exist for $pos")
}
fun gotoNextSide(position: Point, direction: Direction): Pair<Point, Direction> {
var nextDir = direction
val side = sideOf(position)
var nextPos = position
val sideLength = 50
if (side == 'A' && direction == UP) {
nextDir = RIGHT
nextPos = Point(1, 3 * sideLength + position.x - sideLength) // nextSide = F
} else if (side == 'A' && direction == LEFT) {
nextDir = RIGHT
nextPos = Point(1, 2 * sideLength + (sideLength - position.y)) // nextSide = E
} else if (side == 'B' && direction == UP) {
nextDir = UP
nextPos = Point(position.x - 2 * sideLength, 201) // nextSide = F
} else if (side == 'B' && direction == RIGHT) {
nextDir = LEFT
nextPos = Point(101, (sideLength - position.y) + 2 * sideLength) // nextSide = D
} else if (side == 'B' && direction == DOWN) {
nextDir = LEFT
nextPos = Point(101, sideLength + (position.x - 2 * sideLength)) // nextSide = C
} else if (side == 'C' && direction == RIGHT) {
nextDir = UP
nextPos = Point((position.y - sideLength) + 2 * sideLength, sideLength) // nextSide = B
} else if (side == 'C' && direction == LEFT) {
nextDir = DOWN
nextPos = Point(position.y - sideLength, 101) // nextSide = E
} else if (side == 'E' && direction == LEFT) {
nextDir = RIGHT
nextPos = Point(51, sideLength - (position.y - 2 * sideLength)) // nextSide = 'A'
} else if (side == 'E' && direction == UP) {
nextDir = RIGHT
nextPos = Point(51, sideLength + position.x) // nextSide = C
} else if (side == 'D' && direction == DOWN) {
nextDir = LEFT
nextPos = Point(101, 3 * sideLength + (position.x - sideLength)) // nextSide = F
} else if (side == 'D' && direction == RIGHT) {
nextDir = LEFT
nextPos = Point(151, sideLength - (position.y - sideLength * 2)) // nextSide = B
} else if (side == 'F' && direction == RIGHT) {
nextDir = UP
nextPos = Point((position.y - 3 * sideLength) + sideLength, 151) // nextSide = D
} else if (side == 'F' && direction == LEFT) {
nextDir = DOWN
nextPos = Point(sideLength + (position.y - 3 * sideLength), 1) // nextSide = 'A'
} else if (side == 'F' && direction == DOWN) {
nextDir = DOWN
nextPos = Point(position.x + 2 * sideLength, 1) // nextSide = B
}
return nextPos to nextDir
}
enum class Direction(val facing: Int) {
UP(3), DOWN(1), RIGHT(0), LEFT(2);
fun right() = when (this) {
UP -> RIGHT
DOWN -> LEFT
RIGHT -> DOWN
LEFT -> UP
}
fun left() = when (this) {
UP -> LEFT
DOWN -> RIGHT
RIGHT -> UP
LEFT -> DOWN
}
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day22/Day22Kt.class",
"javap": "Compiled from \"day22.kt\"\npublic final class day22.Day22Kt {\n public static final char WALL;\n\n public static final char OPEN;\n\n public static final void main();\n Code:\n 0: ldc #8 ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day04/day04.kt | package day04
import fullyContains
import overlapsWith
import readInput
fun part1(input: List<String>): Int = input.solve(IntRange::fullyContains)
fun part2(input: List<String>): Int = input.solve(IntRange::overlapsWith)
val regex by lazy { """(\d+)-(\d+),(\d+)-(\d+)""".toRegex() }
fun main() {
val input = readInput("main/day04/Day04")
println(part1(input))
println(part2(input))
}
private fun List<String>.solve(check: IntRange.(IntRange) -> Boolean) =
map { it.toRangesPairs() }.count { it.first.check(it.second) }
fun String.toRangesPairs(): Pair<IntRange, IntRange> {
return regex.matchEntire(this)?.destructured?.let { (a, b, c, d) ->
a.toInt()..b.toInt() to c.toInt()..d.toInt()
} ?: error("invalid line")
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day04/Day04Kt.class",
"javap": "Compiled from \"day04.kt\"\npublic final class day04.Day04Kt {\n private static final kotlin.Lazy regex$delegate;\n\n public static final int part1(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1:... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day02/day02.kt | package day02
import readInput
import reverse
import second
const val ROCK = "A"
const val PAPER = "B"
const val SCISSORS = "C"
const val ROCK_ = "X"
const val PAPER_ = "Y"
const val SCISSORS_ = "Z"
const val LOSE = "X"
const val DRAW = "Y"
const val WIN = "Z"
fun part1(input: List<String>): Int {
return input.toPairs().sumOf {
when (it) {
ROCK to ROCK_ -> 1 + 3
ROCK to PAPER_ -> 2 + 6
ROCK to SCISSORS_ -> 3 + 0
PAPER to ROCK_ -> 1 + 0
PAPER to PAPER_ -> 2 + 3
PAPER to SCISSORS_ -> 3 + 6
SCISSORS to ROCK_ -> 1 + 6
SCISSORS to PAPER_ -> 2 + 0
SCISSORS to SCISSORS_ -> 3 + 3
else -> error("invalid pair")
}.toInt()
}
}
fun part2(input: List<String>): Int {
return input.toPairs().sumOf {
when (it.reverse()) {
LOSE to ROCK -> 0 + 3
DRAW to ROCK -> 3 + 1
WIN to ROCK -> 6 + 2
LOSE to PAPER -> 0 + 1
DRAW to PAPER -> 3 + 2
WIN to PAPER -> 6 + 3
LOSE to SCISSORS -> 0 + 2
DRAW to SCISSORS -> 3 + 3
WIN to SCISSORS -> 6 + 1
else -> error("invalid pair")
}.toInt()
}
}
fun main() {
val input = readInput("main/day02/Day02")
println(part1(input))
println(part2(input))
}
fun List<String>.toPairs() = map {
it.split(" ").let { pair ->
pair.first() to pair.second()
}
} | [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day02/Day02Kt.class",
"javap": "Compiled from \"day02.kt\"\npublic final class day02.Day02Kt {\n public static final java.lang.String ROCK;\n\n public static final java.lang.String PAPER;\n\n public static final java.lang.String SCISSORS;\n\n public sta... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day05/day05.kt | package day05
import java.util.*
import readInput
val stackIndices = listOf(1, 5, 9, 13, 17, 21, 25, 29, 33)
var stacks: List<Stack<Char>> = emptyList()
var moves: List<Move> = emptyList()
val regex by lazy { """move (\d+) from (\d) to (\d)""".toRegex() }
fun main() {
val input = readInput("main/day05/Day05")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): String {
input.parse()
rearrange(::movingSingleCrate)
return message()
}
fun part2(input: List<String>): String {
input.parse()
rearrange(::movingPartialStack)
return message()
}
private fun List<String>.parse(numOfRows: Int = 8, numOfStacks: Int = 9) {
stacks = take(numOfRows).parseToStacks(numOfStacks)
moves = drop(numOfRows + 2).parseMoves()
}
private fun rearrange(move: (Move, List<Stack<Char>>) -> Unit) {
moves.forEach {
move(it, stacks)
}
}
private fun movingSingleCrate(move: Move, stacks: List<Stack<Char>>) {
repeat(move.numberOfCrates) { _ ->
stacks[move.to - 1].push(stacks[move.from - 1].pop())
}
}
private fun movingPartialStack(move: Move, stacks: List<Stack<Char>>) {
val tmp = mutableListOf<Char>()
repeat(move.numberOfCrates) { _ ->
tmp.add(stacks[move.from - 1].pop())
}
tmp.reversed().forEach { c ->
stacks[move.to - 1].push(c)
}
}
private fun message() = stacks.map {
it.pop()
}.joinToString("")
fun List<String>.parseMoves(): List<Move> {
return this.map {
regex.matchEntire(it)?.destructured?.let { (count, from, to) ->
Move(from.toInt(), to.toInt(), count.toInt())
} ?: error("")
}
}
fun List<String>.parseToStacks(numOfStacks: Int): List<Stack<Char>> {
val result = mutableListOf<Stack<Char>>()
repeat(numOfStacks) { result.add(Stack()) }
this.reversed().forEach { s ->
s.forEachIndexed { index, c ->
if (index in stackIndices) {
if (c != ' ') result[(index / 4)].push(c)
}
}
}
return result
}
data class Move(val from: Int, val to: Int, val numberOfCrates: Int) | [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day05/Day05Kt.class",
"javap": "Compiled from \"day05.kt\"\npublic final class day05.Day05Kt {\n private static final java.util.List<java.lang.Integer> stackIndices;\n\n private static java.util.List<? extends java.util.Stack<java.lang.Character>> stacks;... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day18/day18.kt | package day18
import readInput
fun main() {
val input = readInput("main/day18/Day18")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int = input.toCubes().surfaceArea()
fun part2(input: List<String>): Int = exteriorSurfaceArea(input.toCubes())
private fun List<String>.toCubes() = map { line ->
val (x, y, z) = line.split(",")
Cube(x.toInt(), y.toInt(), z.toInt())
}
private fun List<Cube>.surfaceArea(): Int = sumOf { it.neighbours().filter { c -> c !in this }.size }
private fun exteriorSurfaceArea(cubes: List<Cube>): Int {
val minX = cubes.minOf { it.x } - 1
val maxX = cubes.maxOf { it.x } + 1
val minY = cubes.minOf { it.y } - 1
val maxY = cubes.maxOf { it.y } + 1
val minZ = cubes.minOf { it.z } - 1
val maxZ = cubes.maxOf { it.z } + 1
val surface = mutableSetOf<Cube>()
val queue = mutableListOf(Cube(minX, minY, minZ))
while (queue.isNotEmpty()) {
val current = queue.removeLast()
if (current in cubes) continue
val (x, y, z) = current
if (x !in minX..maxX || y !in minY..maxY || z !in minZ..maxZ) continue
if (surface.add(current)) queue.addAll(current.neighbours())
}
return cubes.sumOf { it.neighbours().filter { c -> c in surface }.size }
}
data class Cube(val x: Int, val y: Int, val z: Int) {
fun neighbours() = listOf(
Cube(x + 1, y, z), Cube(x - 1, y, z),
Cube(x, y + 1, z), Cube(x, y - 1, z),
Cube(x, y, z + 1), Cube(x, y, z - 1)
)
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day18/Day18Kt.class",
"javap": "Compiled from \"day18.kt\"\npublic final class day18.Day18Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String main/day18/Day18\n 2: invokestatic #14 ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day20/day20.kt | package day20
import readInput
const val encryptionKey = 811589153L
fun main() {
val input = readInput("main/day20/Day20_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Long {
val original = input.mapIndexed { index, s -> Num(originalPosition = index, number = s.toLong()) }.toMutableList()
val mixed = mix(original)
return summedCoordinates(mixed)
}
fun part2(input: List<String>): Long {
val original = input.mapIndexed { index, s ->
Num(originalPosition = index, number = s.toLong() * encryptionKey)
}.toMutableList()
val mixed = generateSequence(original) { mix(original, it).toMutableList() }.drop(10).first()
return summedCoordinates(mixed)
}
private fun mix(list: MutableList<Num>, original: MutableList<Num> = list, position: Int = 0): List<Num> {
if (position == list.size) return list
val index = list.indexOfFirst {
it == original.firstOrNull { o ->
o.originalPosition == position
}
}
val current = list[index]
var newIndex = (index + current.number) % (list.size - 1)
if (newIndex <= 0) newIndex += list.size - 1
list.removeAt(index)
list.add(newIndex.toInt(), current.move())
return mix(list = list, original = list, position = position + 1)
}
private fun summedCoordinates(mixed: List<Num>): Long {
val zero = mixed.indexOfFirst { it.number == 0L }
val a = mixed[(zero + 1000) % mixed.size].number
val b = mixed[(zero + 2000) % mixed.size].number
val c = mixed[(zero + 3000) % mixed.size].number
return a + b + c
}
data class Num(val originalPosition: Int, val currentPosition: Int = originalPosition, val number: Long, val moved: Int = 0) {
fun move() = copy(moved = moved + 1)
} | [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day20/Day20Kt.class",
"javap": "Compiled from \"day20.kt\"\npublic final class day20.Day20Kt {\n public static final long encryptionKey;\n\n public static final void main();\n Code:\n 0: ldc #8 // String main/day20/Day2... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day16/day16.kt | package day16
import kotlin.math.max
import readInput
const val START = "AA"
val flowRegex = """(\d+)""".toRegex()
val valveRegex = """[A-Z]{2}""".toRegex()
var totalTime = 30
var maxPressureRelease = 0
var allValves: Map<String, Valve> = mapOf()
var shortestPaths: MutableMap<String, MutableMap<String, Int>> = mutableMapOf()
fun main() {
val input = readInput("main/day16/Day16_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
prepareSearch(input)
checkAllPaths(0, START, emptySet(), 0)
return maxPressureRelease
}
fun part2(input: List<String>): Int {
totalTime = 26
prepareSearch(input)
checkAllPaths(0, START, emptySet(), 0, true)
return maxPressureRelease
}
private fun prepareSearch(input: List<String>) {
maxPressureRelease = 0
val valves = input.map { it.parse() }
allValves = valves.associateBy { it.id }
shortestPaths =
shortestPathsFromEachTunnelToAllOtherTunnels(
valves.associate {
it.id to it.neighbouringValves.associateWith { 1 }
.toMutableMap()
}.toMutableMap()
)
}
private fun checkAllPaths(currentPressureRelease: Int, currentValveId: String, visited: Set<String>, time: Int, withElefant: Boolean = false) {
maxPressureRelease = max(maxPressureRelease, currentPressureRelease)
shortestPaths[currentValveId]!!.forEach { (valveId, distance) ->
if (!visited.contains(valveId) && time + distance + 1 < totalTime) {
checkAllPaths(
currentPressureRelease = currentPressureRelease + (totalTime - time - distance - 1) * allValves[valveId]?.flow!!,
currentValveId = valveId,
visited = visited + valveId,
time = time + distance + 1,
withElefant = withElefant
)
}
}
if (withElefant) {
checkAllPaths(currentPressureRelease, START, visited, 0, false)
}
}
private fun shortestPathsFromEachTunnelToAllOtherTunnels(shortestPaths: MutableMap<String, MutableMap<String, Int>>): MutableMap<String, MutableMap<String, Int>> {
shortestPaths.keys.forEach { a ->
shortestPaths.keys.forEach { b ->
shortestPaths.keys.forEach { c ->
val ab = shortestPaths[b]?.get(a) ?: 100
val ac = shortestPaths[a]?.get(c) ?: 100
val bc = shortestPaths[b]?.get(c) ?: 100
if (ab + ac < bc)
shortestPaths[b]?.set(c, ab + ac)
}
}
}
shortestPaths.values.forEach {
it.keys.mapNotNull { key -> if (allValves[key]?.flow == 0) key else null }
.forEach { uselessValve ->
it.remove(uselessValve)
}
}
return shortestPaths
}
fun String.parse(): Valve {
val valves = valveRegex.findAll(this).map { it.groupValues.first() }.toList()
val flow = flowRegex.findAll(this).first().groupValues.first().toInt()
val tunnels = valves.drop(1)
return Valve(id = valves.first(), flow = flow, neighbouringValves = tunnels)
}
data class Valve(val id: String, val flow: Int, val neighbouringValves: List<String>)
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day16/Day16Kt.class",
"javap": "Compiled from \"day16.kt\"\npublic final class day16.Day16Kt {\n public static final java.lang.String START;\n\n private static final kotlin.text.Regex flowRegex;\n\n private static final kotlin.text.Regex valveRegex;\n\n ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day10/day10.kt | package day10
import readInput
fun main() {
val input = readInput("main/day10/Day10")
println(part1(input))
part2(input)
}
fun part1(input: List<String>): Int {
val cycles = input.toCycles()
val interestingCycles = listOf(20, 60, 100, 140, 180, 220)
return interestingCycles.sumOf { cycles[it - 1] * it }
}
fun part2(input: List<String>) {
val cycleMap = input.toCycles()
val crt = cycleMap.mapIndexed { index, register ->
val sprite = register - 1..register + 1
if (index % 40 in sprite) "#" else " "
}
crt.forEachIndexed { index, s ->
print(s)
if (index % 40 == 39) println()
}
}
private fun List<String>.toCycles(): List<Int> {
var x = 1
val cycles = mutableListOf<Int>()
forEach {
if (it.startsWith("noop")) {
cycles.add(x)
} else {
repeat(2) { cycles.add(x) }
x += it.split(" ").last().toInt()
}
}
return cycles
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day10/Day10Kt.class",
"javap": "Compiled from \"day10.kt\"\npublic final class day10.Day10Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String main/day10/Day10\n 2: invokestatic #14 ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day17/day17.kt | package day17
import Point
import day17.Direction.DOWN
import day17.Direction.LEFT
import day17.Direction.RIGHT
import findPattern
import readInput
import second
const val leftWall = 0
const val rightWall = 6
typealias TetrisCave = MutableSet<Point>
typealias TetrisRock = Set<Point>
data class Jets(val jets: List<Direction>) {
private var index = 0
fun next() = jets[index++ % jets.size]
}
enum class Direction {
DOWN, LEFT, RIGHT
}
val fallingRocks = listOf(
setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0)),
setOf(Point(1, 0), Point(0, 1), Point(1, 1), Point(2, 1), Point(1, 2)),
setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, 1), Point(2, 2)),
setOf(Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3)),
setOf(Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1))
)
fun main() {
val input = readInput("main/day17/Day17")
val heightDiffs = heightDiffs(input)
val (rocksBeforePattern, patternSize) = heightDiffs.findPattern(1650)
println("$rocksBeforePattern, $patternSize")
println("Part1: ${solve(heightDiffs, rocksBeforePattern, patternSize, 2022)}")
println("Part1: ${solve(heightDiffs, rocksBeforePattern, patternSize, 1000000000000L)}")
}
private fun solve(heightDiffs: List<Int>, rocksBeforePattern: Int, patternSize: Int, numberOfRocks: Long): Long {
val rocksLeft = numberOfRocks - rocksBeforePattern
val pattern = heightDiffs.drop(rocksBeforePattern - 1).take(patternSize)
val patternSum = pattern.sum()
return heightDiffs.take(rocksBeforePattern).sum() +
(rocksLeft / patternSize * patternSum +
pattern.take((rocksLeft - rocksLeft / patternSize * patternSize).toInt()).sum())
}
fun heightDiffs(input: List<String>): List<Int> {
val cave = emptyCaveWithFloor()
val jets = input.first().parse()
return (0..5000).map {
var rock = cave.nextRock(shapeFor(it))
do {
rock = cave.moveRock(rock, jets.next()).first
val result = cave.moveRock(rock, DOWN)
rock = result.first
} while (result.second)
cave.addAll(rock)
cave.height()
}.windowed(2).map { (it.second() - it.first()).toInt() }
}
private fun shapeFor(it: Int) = fallingRocks[it % fallingRocks.size]
private fun emptyCaveWithFloor() = mutableSetOf(
Point(0, 0),
Point(1, 0),
Point(2, 0),
Point(3, 0),
Point(4, 0),
Point(5, 0),
Point(6, 0),
)
private fun TetrisCave.height() = maxOf { it.y }.toLong()
fun TetrisCave.moveRock(rock: TetrisRock, direction: Direction): Pair<TetrisRock, Boolean> {
var movedRock: TetrisRock = rock
var rockMoved = false
when (direction) {
DOWN -> {
val probedRock = rock.map { Point(it.x, it.y - 1) }
if (probedRock.none { this.contains(it) }) {
movedRock = probedRock.toSet()
rockMoved = true
}
}
LEFT -> {
val probedRock = rock.map { Point(it.x - 1, it.y) }
if (probedRock.none { this.contains(it) || it.x < leftWall }) {
movedRock = probedRock.toSet()
rockMoved = true
}
}
RIGHT -> {
val probedRock = rock.map { Point(it.x + 1, it.y) }
if (probedRock.none { this.contains(it) || it.x > rightWall }) {
movedRock = probedRock.toSet()
rockMoved = true
}
}
}
return movedRock to rockMoved
}
fun TetrisCave.nextRock(rock: TetrisRock): TetrisRock {
val xOffset = 2
val yOffset = maxOf { it.y } + 4
return rock.map { Point(it.x + xOffset, it.y + yOffset) }.toSet()
}
fun String.parse(): Jets = map {
when (it) {
'<' -> LEFT
'>' -> RIGHT
else -> error("illegal input")
}
}.let { Jets(it) }
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day17/Day17Kt$WhenMappings.class",
"javap": "Compiled from \"day17.kt\"\npublic final class day17.Day17Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method day... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day21/day21.kt | package day21
import readInput
fun main() {
val input = readInput("main/day21/Day21")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Long {
val monkeys = input.map { it.toMonkey() }.associateBy { it.name }
return solvePart1(monkeys.toMutableMap(), monkeys["root"]!!)
}
fun part2(input: List<String>): Long {
var humanNumber = 1000000000000L
val monkeys = input.map { it.toMonkey() }.associateBy { it.name }
while (true) {
if (humanNumber % 10000L == 0L) println(humanNumber)
if (checkForMatch(monkeys.toMutableMap(), humanNumber)) return humanNumber
humanNumber++
}
return -1
}
fun checkForMatch(monkeys: MutableMap<String, Monkey>, humanNumber: Long): Boolean {
val rootMonkey = monkeys["root"]!!
val human = monkeys["humn"]!!.copy(number = humanNumber)
monkeys["humn"] = human
val firstMonkey = monkeys[rootMonkey.op?.first!!]!!
val secondMonkey = monkeys[rootMonkey.op.second]!!
val first = solvePart1(monkeys, firstMonkey)
val second = solvePart1(monkeys, secondMonkey)
return (first != null && first == second)
}
fun solvePart1(monkeys: MutableMap<String, Monkey>, current: Monkey): Long =
if (current.number != null) {
current.number
} else {
val firstMonkey = monkeys[current.op?.first] ?: error("out of monkeys")
val secondMonkey = monkeys[current.op?.second] ?: error("out of monkeys")
val firstNumber = solvePart1(monkeys, firstMonkey)
monkeys[firstMonkey.name] = firstMonkey.copy(number = firstNumber)
val secondNumber = solvePart1(monkeys, secondMonkey)
monkeys[secondMonkey.name] = secondMonkey.copy(number = secondNumber)
val func = current.op?.operator?.func!!
func.invoke(firstNumber, secondNumber)
}
fun String.toMonkey(): Monkey {
return split(": ").let { (name, rest) ->
if (rest.all(Char::isDigit)) {
Monkey(name = name, number = rest.toLong())
} else {
rest.split(" ").let { (first, op, second) ->
Monkey(name = name, op = MonkeyOp(first = first, second = second, operator = Operator.fromString(op)))
}
}
}
}
data class Monkey(val name: String, val number: Long? = null, val op: MonkeyOp? = null)
data class MonkeyOp(val first: String, val second: String, val operator: Operator)
enum class Operator(val func: (Long, Long) -> Long) {
PLUS({ a, b -> a + b }),
MINUS({ a, b -> a - b }),
TIMES({ a, b -> a * b }),
DIV({ a, b -> a / b });
fun opposite() = when (this) {
PLUS -> MINUS
MINUS -> PLUS
TIMES -> DIV
DIV -> TIMES
}
companion object {
fun fromString(operation: String) =
when (operation.trim()) {
"+" -> PLUS
"-" -> MINUS
"*" -> TIMES
"/" -> DIV
else -> error("illegal operation")
}
}
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day21/Day21Kt.class",
"javap": "Compiled from \"day21.kt\"\npublic final class day21.Day21Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String main/day21/Day21\n 2: invokestatic #14 ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/day19/day19.kt | package day19
import day19.Resource.CLAY
import day19.Resource.GEODE
import day19.Resource.NONE
import day19.Resource.OBSIDIAN
import day19.Resource.ORE
import kotlin.math.max
import readInput
val regex = """.+ (\d+).+ (\d+) .+ (\d+) .+ (\d+) .+ (\d+) .+ (\d+).+ (\d+) .*""".toRegex()
fun main() {
val input = readInput("main/day19/Day19_test")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val bluePrints = input.toBlueprints()
return bluePrints.sumOf { it.id * it.maxGeodes(0) }
}
fun part2(input: List<String>): Long {
return -1
}
enum class Resource {
NONE, ORE, CLAY, OBSIDIAN, GEODE
}
fun List<String>.toBlueprints() = map { line ->
regex.matchEntire(line)?.destructured?.let { (id, oreRobotOre, clayRoboTOre, obsidianRobotOre, obsidianRobotClay, geodeRobotOre, geodeRobotObsidian) ->
BluePrint(
id = id.toInt(),
oreRobotTemplate = OreRobot(cost = listOf(Cost(ORE, oreRobotOre.toInt()))),
clayRobotTemplate = ClayRobot(cost = listOf(Cost(ORE, clayRoboTOre.toInt()))),
obsidianRobotTemplate = ObsidianRobot(cost = listOf(Cost(ORE, obsidianRobotOre.toInt()), Cost(CLAY, obsidianRobotClay.toInt()))),
geodeRobotTemplate = GeodeRobot(cost = listOf(Cost(ORE, geodeRobotOre.toInt()), Cost(OBSIDIAN, geodeRobotObsidian.toInt()))),
)
} ?: error("PARSER ERROR")
}
data class Cost(val resource: Resource, val amount: Int)
data class BluePrint(
val id: Int,
val oreRobotTemplate: OreRobot,
val clayRobotTemplate: ClayRobot,
val obsidianRobotTemplate: ObsidianRobot,
val geodeRobotTemplate: GeodeRobot
) {
private val allTemplates = listOf(oreRobotTemplate, clayRobotTemplate, obsidianRobotTemplate, geodeRobotTemplate).reversed()
fun maxGeodes(
maxSoFar: Int,
robots: List<Robot> = listOf(oreRobotTemplate.instance()),
resources: MutableList<Resource> = mutableListOf(),
timeLeft: Int = 24
): Int {
if (timeLeft > 0) {
val buildableRobots = buildableRobots(resources)
buildableRobots.forEach { newRobot ->
newRobot.cost.forEach { repeat(it.amount) { _ -> resources.remove(it.resource) } }
return maxGeodes(
max(maxSoFar, resources.count { it == GEODE }),
robots + newRobot,
resources.filter { it != NONE }.toMutableList(),
timeLeft - 1
)
}
robots.forEach { resources.add(it.resource) }
return maxGeodes(max(maxSoFar, resources.count { it == GEODE }), robots, resources, timeLeft - 1)
} else return maxSoFar
}
private fun buildableRobots(resources: List<Resource>): MutableList<Robot> {
return allTemplates.filter {
it.canBeBuiltFrom(resources)
}.map {
it.instance()
}.toMutableList()
}
}
sealed interface Robot {
val resource: Resource
val cost: List<Cost>
fun canBeBuiltFrom(resources: List<Resource>): Boolean
fun instance(): Robot
}
data class OreRobot(override val resource: Resource = ORE, override val cost: List<Cost>) : Robot {
override fun canBeBuiltFrom(resources: List<Resource>): Boolean {
return cost.all { cost ->
resources.count {
it == cost.resource
} >= cost.amount
}
}
override fun instance(): Robot {
return copy()
}
}
data class ClayRobot(override val resource: Resource = CLAY, override val cost: List<Cost>) : Robot {
override fun canBeBuiltFrom(resources: List<Resource>): Boolean {
return cost.all { cost ->
resources.count {
it == cost.resource
} >= cost.amount
}
}
override fun instance(): Robot {
return copy()
}
}
data class ObsidianRobot(override val resource: Resource = OBSIDIAN, override val cost: List<Cost>) : Robot {
override fun canBeBuiltFrom(resources: List<Resource>): Boolean {
return cost.all { cost ->
resources.count {
it == cost.resource
} >= cost.amount
}
}
override fun instance(): Robot {
return copy()
}
}
data class GeodeRobot(override val resource: Resource = GEODE, override val cost: List<Cost>) : Robot {
override fun canBeBuiltFrom(resources: List<Resource>): Boolean {
return cost.all { cost ->
resources.count {
it == cost.resource
} >= cost.amount
}
}
override fun instance(): Robot {
return copy()
}
}
//object NoOp : Robot {
// override val resource: Resource
// get() = NONE
// override val cost: List<Cost>
// get() = emptyList()
//
// override fun canBeBuiltFrom(resources: List<Resource>): Boolean = true
//
// override fun instance(): Robot {
// return this
// }
//}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/day19/Day19Kt.class",
"javap": "Compiled from \"day19.kt\"\npublic final class day19.Day19Kt {\n private static final kotlin.text.Regex regex;\n\n public static final kotlin.text.Regex getRegex();\n Code:\n 0: getstatic #11 //... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/year_2016/day12/day16.kt | package year_2016.day12
import readInput
fun main() {
val input = readInput("main/year_2016/day12/Day12")
println(part1(input))
println(part2(input))
}
val registers = mutableMapOf(
"a" to 0,
"b" to 0,
"c" to 0,
"d" to 0,
)
fun part1(input: List<String>): Int {
var index = 0
while (index < input.size) {
val line = input[index]
when (line.substring(0, 3)) {
"cpy" -> {
val (_, x, reg) = line.split(" ")
if (x in listOf("a", "b", "c", "d"))
registers[reg] = registers[x]!!
else
registers[reg] = x.toInt()
index++
}
"inc" -> {
val (_, reg) = line.split(" ")
registers[reg] = registers[reg]!! + 1
index++
}
"dec" -> {
val (_, reg) = line.split(" ")
registers[reg] = registers[reg]!! - 1
index++
}
"jnz" -> {
val (_, x, y) = line.split(" ")
if (x.all { it.isDigit() }) {
if (x.toInt() != 0) index += y.toInt()
} else {
if (registers[x] != 0)
index += y.toInt()
else index++
}
}
}
}
return registers["a"]!!
}
fun part2(input: List<String>): Int {
registers["c"] = 1
return part1(input)
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/year_2016/day12/Day16Kt.class",
"javap": "Compiled from \"day16.kt\"\npublic final class year_2016.day12.Day16Kt {\n private static final java.util.Map<java.lang.String, java.lang.Integer> registers;\n\n public static final void main();\n Code:\n ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/year_2016/day15/day15.kt | package year_2016.day15
import readInput
val reg = """\b\d+\b""".toRegex()
fun main() {
val input = readInput("main/year_2016/day15/Day15")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
return part2(input.dropLast(1))
}
fun part2(input: List<String>): Int {
val discs = input.map(String::toDisc)
var time = 0
while (true) {
if (discs.all {
(it.layer + it.startingPosition + time) % it.positions == 0
})
return time
time++
}
}
data class Disc(
val layer: Int,
val positions: Int,
val startingPosition: Int
)
fun String.toDisc(): Disc {
val (layer, positions, _, startingPosition) = reg.findAll(this).toList()
return Disc(layer.value.toInt(), positions.value.toInt(), startingPosition.value.toInt())
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/year_2016/day15/Day15Kt.class",
"javap": "Compiled from \"day15.kt\"\npublic final class year_2016.day15.Day15Kt {\n private static final kotlin.text.Regex reg;\n\n public static final kotlin.text.Regex getReg();\n Code:\n 0: getstatic #11 ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/year_2016/day18/day18.kt | package year_2016.day18
const val input: Row = ".^^.^^^..^.^..^.^^.^^^^.^^.^^...^..^...^^^..^^...^..^^^^^^..^.^^^..^.^^^^.^^^.^...^^^.^^.^^^.^.^^.^."
typealias Row = String
fun main() {
println(part1())
println(part2())
}
fun part1(): Int = generateSequence(input) { s -> s.nextRow() }.take(40).sumOf { it.count { c -> c == '.' } }
fun part2(): Int = generateSequence(input) { s -> s.nextRow() }.take(400000).sumOf { it.count { c -> c == '.' } }
fun Row.nextRow(): Row {
return this.mapIndexed { index, c ->
if (leftIsTrap(index) && centerIsTrap(index) && !rightIsTrap(index)) '^'
else if (!leftIsTrap(index) && centerIsTrap(index) && rightIsTrap(index)) '^'
else if (leftIsTrap(index) && !centerIsTrap(index) && !rightIsTrap(index)) '^'
else if (!leftIsTrap(index) && !centerIsTrap(index) && rightIsTrap(index)) '^'
else '.'
}.joinToString("")
}
fun Row.leftIsTrap(i: Int) = i > 0 && this[i - 1] == '^'
fun Row.rightIsTrap(i: Int) = i < length - 1 && this[i + 1] == '^'
fun Row.centerIsTrap(i: Int) = this[i] == '^'
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/year_2016/day18/Day18Kt.class",
"javap": "Compiled from \"day18.kt\"\npublic final class year_2016.day18.Day18Kt {\n public static final java.lang.String input;\n\n public static final void main();\n Code:\n 0: invokestatic #10 /... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/year_2018/day18/day18.kt | package year_2018.day18
import Point
import findPattern
import readInput
typealias Forest = Map<Point, Char>
private const val TREE = '|'
private const val OPEN = '.'
private const val LUMBER_YARD = '#'
fun main() {
val input = readInput("main/year_2018/day18/Day18")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val forest = input.parse()
return forest.resourceValueList(11).last()
}
fun part2(input: List<String>): Int {
val stepCount = 1000000000
val forest = input.parse()
val resourceValueList = forest.resourceValueList()
val (stepsBeforePattern, patternSize) = resourceValueList.findPattern()
val indexInCycle = (stepCount - stepsBeforePattern) % patternSize
return resourceValueList.drop(stepsBeforePattern)[indexInCycle]
}
fun Forest.step(): Forest = this.keys.associateWith { here ->
when (this[here]) {
OPEN -> if (this.countNeighborsOfKind(here, TREE) >= 3) TREE else OPEN
TREE -> if (this.countNeighborsOfKind(here, LUMBER_YARD) >= 3) LUMBER_YARD else TREE
LUMBER_YARD -> if (countNeighborsOfKind(here, LUMBER_YARD) > 0 && countNeighborsOfKind(here, TREE) > 0) LUMBER_YARD else OPEN
else -> error("Something went wrong: $here, ${this[here]}")
}
}
private fun Forest.resourceValue(): Int = count { it.value == LUMBER_YARD } * count { it.value == TREE }
fun Forest.resourceValueList(n: Int = 600): List<Int> = generateSequence(this) { it.step() }.take(n).map { it.resourceValue() }.toList()
fun Forest.countNeighborsOfKind(p: Point, c: Char) = p.allNeighbours().count { this[it] == c }
fun List<String>.parse(): Forest = mutableMapOf<Point, Char>().apply {
forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
this[Point(x, y)] = c
}
}
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/year_2018/day18/Day18Kt.class",
"javap": "Compiled from \"day18.kt\"\npublic final class year_2018.day18.Day18Kt {\n private static final char TREE;\n\n private static final char OPEN;\n\n private static final char LUMBER_YARD;\n\n public static final v... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/year_2017/day07/day07.kt | package year_2017.day07
import kotlin.math.absoluteValue
import readInput
import second
fun part1(input: List<String>): String {
val programs = input.map(String::parse)
return programs.findBottomProgram()
}
fun part2(input: List<String>): Int {
val programs = input.map(String::parse)
allPrograms = programs.associateBy { it.name }.toMutableMap()
return allPrograms[programs.findBottomProgram()]!!.findImbalance()
}
var allPrograms: Map<String, Program> = mapOf()
fun main() {
val input = readInput("main/year_2017/day07/Day07")
println(part1(input))
println(part2(input))
}
fun Collection<Program>.findBottomProgram(): String {
val allNames = this.flatMap { p -> listOf(p.name.trim()) + p.programsCarried.map { it.trim() } }
val nameCounts = allNames.associateBy { s -> allNames.count { it == s } }
return nameCounts[1]!!
}
data class Program(
val name: String,
val weight: Int,
val programsCarried: List<String>
) {
private fun totalWeightCarried(): Int {
return weight + programsCarried
.sumOf { name ->
allPrograms[name.trim()]!!.totalWeightCarried()
}
}
private fun childrenAreBalanced() =
programsCarried.map { allPrograms[it.trim()]!!.totalWeightCarried() }.distinct().size == 1
fun findImbalance(imbalance: Int? = null): Int =
if (imbalance != null && childrenAreBalanced()) {
weight - imbalance
} else {
val subTrees = programsCarried.groupBy { allPrograms[it.trim()]!!.totalWeightCarried() }
val outOfBalanceTree = subTrees.minBy { it.value.size }.value.first().trim()
allPrograms[outOfBalanceTree]!!.findImbalance(imbalance = imbalance ?: subTrees.keys.reduce { a, b -> a - b }.absoluteValue)
}
}
fun String.parse(): Program {
return this.split("->").let {
val split = it.first().split((" ("))
val name = split.first().trim()
val weight = split.second().trim().dropLast(1).toInt()
val programs = if (it.size > 1) {
it.second().split((", ").trim())
} else emptyList()
Program(name.trim(), weight, programs.map(String::trim))
}
} | [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/year_2017/day07/Day07Kt.class",
"javap": "Compiled from \"day07.kt\"\npublic final class year_2017.day07.Day07Kt {\n private static java.util.Map<java.lang.String, year_2017.day07.Program> allPrograms;\n\n public static final java.lang.String part1(java.u... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/year_2017/day23/day23.kt | package year_2017.day23
import readInput
import second
val registers = mutableMapOf(
'a' to 0,
'b' to 0,
'c' to 0,
'd' to 0,
'e' to 0,
'f' to 0,
'g' to 0,
'h' to 0,
)
fun part1(input: List<String>): Int {
val instructions = input.map(String::toInstruction)
return runInstructions(instructions)
}
private fun runInstructions(instructions: List<Instruction>): Int {
var counter = 0
var index = 0
while (index in instructions.indices) {
print("index $index, counter $counter \r")
val instruction = instructions[index]
when (instruction.command) {
"set" -> {
registers[instruction.x] = if (instruction.yIsNumber()) instruction.y.toInt() else registers[instruction.y.first()]!!
index++
}
"sub" -> {
registers[instruction.x] =
registers[instruction.x]!! - if (instruction.yIsNumber()) instruction.y.toInt() else registers[instruction.y.first()]!!
index++
}
"mul" -> {
registers[instruction.x] =
registers[instruction.x]!! * if (instruction.yIsNumber()) instruction.y.toInt() else registers[instruction.y.first()]!!
counter++
index++
}
"jnz" -> {
val v = if (instruction.x.isDigit()) instruction.x.digitToInt() else registers[instruction.x]!!
if (v != 0) index += instruction.y.toInt()
else index++
}
else -> error("unknown instruction ${instruction.command}")
}
}
return counter
}
fun part2(input: List<String>): Int {
val start = input.first().split(" ")[2].toInt() * 100 + 100000
return (start..start + 17000 step 17).count {
!it.toBigInteger().isProbablePrime(5)
}
}
fun main() {
val input = readInput("main/year_2017/day23/Day23")
println(part1(input))
println(part2(input))
}
fun String.toInstruction(): Instruction {
return this.split(" ").let {
Instruction(command = it.first(), x = it.second().first(), y = it[2])
}
}
data class Instruction(val command: String, val x: Char, val y: String) {
fun yIsNumber() = y.first().isDigit() || y.first() == '-'
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/year_2017/day23/Day23Kt.class",
"javap": "Compiled from \"day23.kt\"\npublic final class year_2017.day23.Day23Kt {\n private static final java.util.Map<java.lang.Character, java.lang.Integer> registers;\n\n public static final java.util.Map<java.lang.Char... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/year_2017/day02/day03.kt | package year_2017.day02
import readInput
fun part1(input: List<String>): Int = input.map { line ->
line.split(" ").map { it.toInt() }.sortedDescending()
}.sumOf { it.first() - it.last() }
fun part2(input: List<String>): Int = input.map { line ->
line.split(" ").map { it.toInt() }.sortedDescending()
}.sumOf { line ->
line.findDivisionResult()
}
fun main() {
val input = readInput("main/year_2017/day02/Day02")
println(part1(input))
println(part2(input))
}
fun List<Int>.findDivisionResult(): Int {
forEachIndexed { index, candidate ->
(index + 1 until size).forEach {
if (candidate % this[it] == 0) return candidate / this[it]
}
}
error("no even division found")
}
| [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/year_2017/day02/Day03Kt.class",
"javap": "Compiled from \"day03.kt\"\npublic final class year_2017.day02.Day03Kt {\n public static final int part1(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
rolf-rosenbaum__aoc-2022__59cd426/src/main/year_2017/day11/day11.kt | package year_2017.day11
import kotlin.math.absoluteValue
import readInput
fun part1(input: List<String>): Int {
val directions = input.first().split(",")
val origin = HexPoint(0, 0, 0)
val endPoint = directions.fold(origin) { point, dir ->
point.step(dir)
}
return origin.distance(endPoint)
}
fun part2(input: List<String>): Int {
val directions = input.first().split(",")
val origin = HexPoint(0, 0, 0)
val steps = mutableListOf(origin)
directions.forEach { dir ->
steps.add(steps.last().step(dir))
}
return steps.maxOf { it.distance(origin) }
}
fun main() {
val input = readInput("main/year_2017/day11/Day11")
println(part1(input))
println(part2(input))
}
data class HexPoint(val x: Int, val y: Int, val z: Int) {
fun step(direction: String): HexPoint =
when (direction) {
"n" -> HexPoint(x, y + 1, z - 1)
"s" -> HexPoint(x, y - 1, z + 1)
"ne" -> HexPoint(x + 1, y, z - 1)
"nw" -> HexPoint(x - 1, y + 1, z)
"se" -> HexPoint(x + 1, y - 1, z)
"sw" -> HexPoint(x - 1, y, z + 1)
else -> error("illegal direction")
}
fun distance(other: HexPoint): Int =
maxOf(
(this.x - other.x).absoluteValue,
(this.y - other.y).absoluteValue,
(this.z - other.z).absoluteValue
)
} | [
{
"class_path": "rolf-rosenbaum__aoc-2022__59cd426/year_2017/day11/Day11Kt.class",
"javap": "Compiled from \"day11.kt\"\npublic final class year_2017.day11.Day11Kt {\n public static final int part1(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
aurelioklv__enigma__2110e20/src/main/kotlin/enigma/util/Util.kt | package com.aurelioklv.enigma.util
val alphabet = ('A'..'Z').joinToString(separator = "")
val defaultWiring: Map<Char, Char> = ('A'..'Z').associateWith { it }
fun validateWiring(wiring: Map<Char, Char>, kind: String) {
require(wiring.isNotEmpty()) {
"Wiring is empty"
}
require(wiring.all { (key, value) ->
key.isLetter() && key.isUpperCase() && value.isLetter() && value.isUpperCase()
}) {
"Each character should be an uppercase letter"
}
when (kind) {
in listOf("rotor", "plugboard") -> {
require(alphabet.all { wiring.containsKey(it) && wiring.containsValue(it) })
}
"reflector" -> {
require(wiring.all { (key, value) -> wiring.getOrDefault(value, ' ') == key }) {
"Invalid wiring $wiring"
}
}
}
wiring.mapKeys { it.key.uppercaseChar() }.mapValues { it.value.uppercaseChar() }
}
fun String.toWiring(kind: String): Map<Char, Char> {
val input = this.uppercase()
val result = when (kind) {
in listOf("rotor", "reflector") -> {
require(input.length == alphabet.length) {
"String must be ${alphabet.length} characters long. Got ${input.length}"
}
alphabet.zip(input).toMap()
}
"plugboard" -> {
val wiring = input.chunked(2).flatMap { pair ->
pair.map { it to pair[(pair.indexOf(it) + 1) % 2] }
}.toMap().toMutableMap()
val existingChar = input.toSet()
wiring += defaultWiring.filterKeys { it !in existingChar }
wiring
}
else -> {
throw IllegalArgumentException("Unknown kind: $kind")
}
}
return result
}
fun String.toListOfInt(): List<Int> {
return map { char ->
when {
char.isLetter() -> char.uppercaseChar().minus('A')
else -> throw IllegalArgumentException("Invalid character: $char")
}
}
} | [
{
"class_path": "aurelioklv__enigma__2110e20/com/aurelioklv/enigma/util/UtilKt.class",
"javap": "Compiled from \"Util.kt\"\npublic final class com.aurelioklv.enigma.util.UtilKt {\n private static final java.lang.String alphabet;\n\n private static final java.util.Map<java.lang.Character, java.lang.Charact... |
xu33liang33__actioninkotlin__cdc74e4/src/chapter07/Intro_运算符重载.kt | package chapter07
import java.lang.IndexOutOfBoundsException
import java.math.BigDecimal
import java.time.LocalDate
import kotlin.ranges.ClosedRange as ClosedRange1
/**
*
*运算符重载
* BigDecimal运算
* 约定 operator
*
* a * b | times
* a / b | div
* a % b | mod
* a + b | plus
* a - b | minus
*
*/
fun main(args: Array<String>) {
BigDecimal.ZERO
var p1 = Point(10, 20)
val p2 = Point(30, 40)
println(p1 + p2)
println(p1.plus(p2))
p1 += p2
println(p1)
println(p2 * 5.toDouble())
var bd = BigDecimal.ZERO
println(++bd)
val a = Point(10, 20) == Point(10, 20)
println("equal: $a")
val p111 = Person722("Alice", "Smith")
val p222 = Person722("Bob", "Johnson")
println(p111 < p222)
println(p2[1])
println('a' in "abc")
}
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
fun and(other: Point): Point {
return Point(x + other.x, y + other.y)
}
/**
* Point(10,20) == Point(10,20)
*/
override fun equals(obj: Any?): Boolean {
if (obj === this) return true
if (obj !is Point) return false
return obj.x == x && obj.y == y
}
}
operator fun Point.times(scale: Double): Point {
return Point((x * scale).toInt(), (y * scale).toInt())
}
/**
*
* 重载一元运算符
*
* +a | unaryPlus
* -a | unaryMinus
* !a | not
* ++a,a++ | inc
* --a,a-- | dec
*
*/
operator fun Point.unaryMinus(): Point {
return Point(-x, -y)
}
operator fun BigDecimal.inc() = this + BigDecimal.ONE
/**
* 比较运算符
*
* equals
* == 运算符
*
*/
/**
*
* 排序运算符
* compareTo 接口
*
*/
class Person722(val firstName: String, val lastName: String) : Comparable<Person722> {
override fun compareTo(other: Person722): Int {
return compareValuesBy(this, other, Person722::lastName, Person722::firstName)
}
}
/**
* 集合与区别的约定
* a[b] 下标运算符 "get"和"set"
*
*
*/
operator fun Point.get(index: Int): Int {
return when (index) {
0 -> x
1 -> y
else ->
throw IndexOutOfBoundsException("Invalid coordinate $index")
}
}
/**
* "in"的约定
* contains
*
*
*/
data class Rectangle732(val upperLeft: Point, val lowerRight: Point)
operator fun Rectangle732.contains(p: Point): Boolean {
return p.x in upperLeft.x until lowerRight.x &&
p.y in upperLeft.y until lowerRight.y
}
/**
* rangeTo 约定
* ".."符号 1..10
*实现了Comparable 接口就不需要实现rangeTo了~因为标准库已经实现
*/
//operator fun<T:Comparable<T>> T.rangeTo(that:T) : kotlin.ranges.ClosedRange<T> {
// 1..10
//}
/**
* for循环中使用iterator的约定
*
*
*
*/
| [
{
"class_path": "xu33liang33__actioninkotlin__cdc74e4/chapter07/Intro_运算符重载Kt.class",
"javap": "Compiled from \"Intro_运算符重载.kt\"\npublic final class chapter07.Intro_运算符重载Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // S... |
xu33liang33__actioninkotlin__cdc74e4/src/chapter08/_8_1_2/_8_1_6_去除重复代码.kt | package chapter08._8_1_2
data class SiteVisit(
val path: String,
val dutation: Double,
val os: OS
)
//函数类型和lambda 一起去除重复代码
enum class OS { WINDOWS, LINUX, MAC, IOS, ANDROID }
fun main(args: Array<String>) {
val log = listOf(
SiteVisit("/", 34.0, OS.WINDOWS),
SiteVisit("/", 22.0, OS.MAC),
SiteVisit("/login", 12.0, OS.WINDOWS),
SiteVisit("/signup", 8.0, OS.IOS),
SiteVisit("/", 16.3, OS.ANDROID)
)
println(log.filter { it.os == OS.WINDOWS }
.map(SiteVisit::dutation))
//计算windows平均时间
val averageWindows = log.filter { it.os == OS.WINDOWS }
.map(SiteVisit::dutation)
.average()
println(averageWindows)
// println(log.filter { it.os == OS.WINDOWS }
// .map(SiteVisit::dutation))
val averageMobile = log.filter {
it.os in setOf(OS.IOS, OS.ANDROID)
}
.map(SiteVisit::dutation)
.average()
println(averageMobile)
/**
* 普通去重方法
*/
println()
println("log.averageDuration(OS.ANDROID)")
println(log.averageDuration(OS.ANDROID))
println("------------------------")
/**
* 将需要的条件抽到函数类型参数中
*/
println(log.averageDurationFor {
it.os in setOf(OS.ANDROID, OS.IOS)
})
println(log.averageDurationFor {
it.os == OS.IOS && it.path == "/signup"
})
}
/**
* 普通方法去重
*/
fun List<SiteVisit>.averageDuration(os: OS) = filter { it.os == os }
.map(SiteVisit::dutation)
.average()
/**
* 将需要的条件抽到函数类型参数中
* 不仅抽取重复数据,也能抽取重复行为
*/
fun List<SiteVisit>.averageDurationFor(predicate: (SiteVisit) -> Boolean) =
filter(predicate)
.map(SiteVisit::dutation)
.average()
| [
{
"class_path": "xu33liang33__actioninkotlin__cdc74e4/chapter08/_8_1_2/_8_1_6_去除重复代码Kt.class",
"javap": "Compiled from \"_8_1_6_去除重复代码.kt\"\npublic final class chapter08._8_1_2._8_1_6_去除重复代码Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
al-volkov__spbu_2020_kotlin_homeworks__5049681/src/main/kotlin/homework_5/Task1.kt | package homework_5
import java.io.File
fun String.isNumber() = this.toIntOrNull() != null
enum class OperationType(val operation: String) {
Addition("+"),
Multiplication("*"),
Subtraction("-"),
Division("/")
}
interface ArithmeticTreeNode {
fun getValue(): Int
override fun toString(): String
}
class Operand(private val value: Int) : ArithmeticTreeNode {
override fun getValue() = value
override fun toString() = value.toString()
}
class Operation(
private val type: OperationType,
private val leftNode: ArithmeticTreeNode,
private val rightNode: ArithmeticTreeNode
) : ArithmeticTreeNode {
override fun getValue(): Int {
return when (type) {
OperationType.Addition -> leftNode.getValue() + rightNode.getValue()
OperationType.Multiplication -> leftNode.getValue() * rightNode.getValue()
OperationType.Subtraction -> leftNode.getValue() - rightNode.getValue()
OperationType.Division -> leftNode.getValue() / rightNode.getValue()
}
}
override fun toString(): String = "(${type.operation} $leftNode $rightNode)"
}
class ArithmeticTree(path: String) {
private val root: ArithmeticTreeNode
init {
val input = File(path).readText().replace("(", "").replace(")", "").split(" ")
root = parseRecursive(input).node
}
data class RecursiveResult(val node: ArithmeticTreeNode, val newList: List<String>)
private fun parseRecursive(list: List<String>): RecursiveResult {
if (list.first().isNumber()) {
return RecursiveResult(Operand(list.first().toInt()), list.slice(1..list.lastIndex))
} else {
val type = when (list.first()) {
"+" -> OperationType.Addition
"*" -> OperationType.Multiplication
"-" -> OperationType.Subtraction
"/" -> OperationType.Division
else -> throw IllegalArgumentException("arithmetic expression is not correct")
}
var result = parseRecursive(list.slice(1..list.lastIndex))
val leftNode = result.node
result = parseRecursive(result.newList)
val rightNode = result.node
return RecursiveResult(Operation(type, leftNode, rightNode), result.newList)
}
}
override fun toString() = root.toString()
fun getValue() = root.getValue()
}
| [
{
"class_path": "al-volkov__spbu_2020_kotlin_homeworks__5049681/homework_5/Task1Kt.class",
"javap": "Compiled from \"Task1.kt\"\npublic final class homework_5.Task1Kt {\n public static final boolean isNumber(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 // St... |
mayabot__mynlp__b980da3/mynlp/src/main/java/com/mayabot/nlp/algorithm/TopIntMinK.kt | package com.mayabot.nlp.algorithm
/**
* Top K 最小值。
*/
class TopIntMinK(private val k: Int) {
private val heap = FloatArray(k)
private val idIndex = IntArray(k) { -1 }
var size = 0
fun push(id: Int, score: Float) {
if (size < k) {
heap[size] = score
idIndex[size] = id
size++
if (size == k) {
buildMinHeap()
}
} else {
// 如果这个数据小于最大值,那么有资格进入
if (score < heap[0]) {
heap[0] = score
idIndex[0] = id
topify(0)
}
}
}
fun result(): ArrayList<Pair<Int, Float>> {
val top = Math.min(k, size)
val list = ArrayList<Pair<Int, Float>>(top)
for (i in 0 until top) {
list += idIndex[i] to heap[i]
}
list.sortBy { it.second }
return list
}
private fun buildMinHeap() {
for (i in k / 2 - 1 downTo 0) {
topify(i)// 依次向上将当前子树最大堆化
}
}
private fun topify(i: Int) {
val l = 2 * i + 1
val r = 2 * i + 2
var max: Int
if (l < k && heap[l] > heap[i])
max = l
else
max = i
if (r < k && heap[r] > heap[max]) {
max = r
}
if (max == i || max >= k)
// 如果largest等于i说明i是最大元素
// largest超出heap范围说明不存在比i节点大的子女
return
swap(i, max)
topify(max)
}
private fun swap(i: Int, j: Int) {
val tmp = heap[i]
heap[i] = heap[j]
heap[j] = tmp
val tmp2 = idIndex[i]
idIndex[i] = idIndex[j]
idIndex[j] = tmp2
}
} | [
{
"class_path": "mayabot__mynlp__b980da3/com/mayabot/nlp/algorithm/TopIntMinK$result$$inlined$sortBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class com.mayabot.nlp.algorithm.TopIntMinK$result$$inlined$sortBy$1<T> implements java.util.Comparator {\n public com.mayabot.nlp.algorithm... |
mayabot__mynlp__b980da3/mynlp/src/main/java/com/mayabot/nlp/module/nwd/ValueObjects.kt | package com.mayabot.nlp.module.nwd
import kotlin.math.*
class IntCount {
var value : Int = 1
}
/**
* 词和词数量
*/
class WordCount(val word: String, val count: Int) : Comparable<WordCount> {
override fun compareTo(other: WordCount): Int {
return other.count.compareTo(count)
}
}
data class NewWord(
val word: String,
val len: Int,
val freq: Int,
val docFreq: Int,
/**
* 互信息。内聚程度
*/
val mi: Float,
val avg_mi: Float,
/**
* 左右最低熵.和两侧的黏连程度
*/
val entropy: Float,
val le: Float,
val re: Float,
val idf: Float,
val isBlock: Boolean
) {
var score: Float = 0f
/**
* 内置打分公式
*/
fun doScore() {
var ac = abs(le - re)
if (ac == 0.0f) {
ac = 0.00000000001f
}
score = avg_mi + log2((le * exp(re) + re * exp(le)) / ac)
// score = avg_mi + entropy + idf * 1.5f + len * freq / docFreq
if (isBlock) score += 1000
}
}
fun HashMap<Char, IntCount>.addTo(key: Char, count: Int) {
this.getOrPut(key) {
IntCount()
}.value += count
}
class WordInfo(val word: String) {
companion object {
val empty = HashMap<Char, IntCount>()
val emptySet = HashSet<Int>()
}
var count = 0
var mi = 0f
var mi_avg = 0f
// 是否被双引号 书名号包围
var isBlock = false
var entropy = 0f
var left = HashMap<Char, IntCount>(10)
var right = HashMap<Char, IntCount>(10)
var docSet = HashSet<Int>()
var score = 0f
var idf = 0f
var doc = 0
var le = 0f
var re = 0f
// var tfIdf =0f
fun tfIdf(docCount: Double, ziCount: Double) {
val doc = docSet.size + 1
idf = log10(docCount / doc).toFloat()
// tfIdf = (idf * (count/ziCount)).toFloat()
docSet = emptySet
this.doc = doc - 1
}
fun entropy() {
var leftEntropy = 0f
for (entry in left) {
val p = entry.value.value / count.toFloat()
leftEntropy -= (p * ln(p.toDouble())).toFloat()
}
var rightEntropy = 0f
for (entry in right) {
val p = entry.value.value / count.toFloat()
rightEntropy -= (p * ln(p.toDouble())).toFloat()
}
le = leftEntropy
re = rightEntropy
entropy = min(leftEntropy, rightEntropy)
left = empty
right = empty
}
}
| [
{
"class_path": "mayabot__mynlp__b980da3/com/mayabot/nlp/module/nwd/ValueObjectsKt.class",
"javap": "Compiled from \"ValueObjects.kt\"\npublic final class com.mayabot.nlp.module.nwd.ValueObjectsKt {\n public static final void addTo(java.util.HashMap<java.lang.Character, com.mayabot.nlp.module.nwd.IntCount>... |
mayabot__mynlp__b980da3/mynlp/src/main/java/com/mayabot/nlp/fasttext/utils/TopMaxK.kt | package com.mayabot.nlp.fasttext.utils
import java.util.*
import kotlin.math.min
/**
* 求最大Top K
* 内部是小顶堆
*
* @author jimichan
*/
class TopMaxK<T>(private val k: Int=10 ) {
private val heap: FloatArray = FloatArray(k)
private val idIndex: MutableList<T?> = MutableList(k){null}
var size = 0
fun push(id: T, score: Float) {
if (size < k) {
heap[size] = score
idIndex[size] = id
size++
if (size == k) {
buildMinHeap()
}
} else { // 如果这个数据大于最下值,那么有资格进入
if (score > heap[0]) {
heap[0] = score
idIndex[0] = id
mintopify(0)
}
}
}
fun canPush(score: Float): Boolean {
if (size < k) {
return true
} else { // 如果这个数据大于最下值,那么有资格进入
if (score > heap[0]) {
return true
}
}
return false
}
fun result(): ArrayList<Pair<T, Float>> {
val top = min(k, size)
val list = ArrayList<Pair<T, Float>>(top)
for (i in 0 until top) {
val v = idIndex[i]
val s = heap[i]
if(v!=null){
list += v to s
}
}
list.sortByDescending { it.second }
return list
}
private fun buildMinHeap() {
for (i in k / 2 - 1 downTo 0) { // 依次向上将当前子树最大堆化
mintopify(i)
}
}
/**
* 让heap数组符合堆特性
*
* @param i
*/
private fun mintopify(i: Int) {
val l = 2 * i + 1
val r = 2 * i + 2
var min = 0
min = if (l < k && heap[l] < heap[i]) {
l
} else {
i
}
if (r < k && heap[r] < heap[min]) {
min = r
}
if (min == i || min >= k) {
// 如果largest等于i说明i是最大元素
// largest超出heap范围说明不存在比i节点大的子女
return
}
swap(i, min)
mintopify(min)
}
private fun swap(i: Int, j: Int) {
val tmp = heap[i]
heap[i] = heap[j]
heap[j] = tmp
val tmp2 = idIndex[i]
idIndex[i] = idIndex[j]
idIndex[j] = tmp2
}
} | [
{
"class_path": "mayabot__mynlp__b980da3/com/mayabot/nlp/fasttext/utils/TopMaxK$result$$inlined$sortByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class com.mayabot.nlp.fasttext.utils.TopMaxK$result$$inlined$sortByDescending$1<T> implements java.util.Comparator {\n public c... |
daincredibleholg__AdventOfCode2023__4aa7c68/src/main/kotlin/io/steinh/aoc/day06/BoatRace.kt | package io.steinh.aoc.day06
class BoatRace(private val input: BoatRaceStats) {
fun calculateWaysToBeatTheRecord(): Int {
val possibleWins = buildList {
input.timeToDistance.forEach { (time, distance) ->
add(
buildList {
for (i in 1..time) {
if (((time - i).times(i)) > distance) {
add(i)
}
}
}
)
}
}
return possibleWins.map { it.size }.reduce { acc, next -> acc * next }
}
fun calculateForOneLargeRace(): Int {
val longTime = input.timeToDistance.keys.map { it.toString() }.reduce { acc, next -> "$acc$next" }.toLong()
val longDistance =
input.timeToDistance.values.map { it.toString() }.reduce { acc, next -> "$acc$next" }.toLong()
var count = 0
for (i in 1..longTime) {
if ((longTime - i).times(i) > longDistance) {
count++
}
}
return count
}
}
data class BoatRaceStats(
val timeToDistance: Map<Int, Int>
)
fun interpretStats(input: String): BoatRaceStats {
val inputLines = input.split("\n")
val times = "(\\d+)".toRegex().findAll(inputLines[0])
.map {
it.groupValues[0].toInt()
}
.toList()
val distances = "(\\d+)".toRegex().findAll(inputLines[1])
.map {
it.groupValues[0].toInt()
}
.toList()
return BoatRaceStats(
timeToDistance = times.zip(distances) { t, d -> t to d }.toMap()
)
}
fun main() {
val input = {}.javaClass.classLoader?.getResource("day06/input.txt")?.readText()!!
val boatRace = BoatRace(interpretStats(input))
val partOneResult = boatRace.calculateWaysToBeatTheRecord()
println("Result for day 06, part I: $partOneResult")
val partTwoResult = boatRace.calculateForOneLargeRace()
println("Result for day 06, part II: $partTwoResult")
}
| [
{
"class_path": "daincredibleholg__AdventOfCode2023__4aa7c68/io/steinh/aoc/day06/BoatRace.class",
"javap": "Compiled from \"BoatRace.kt\"\npublic final class io.steinh.aoc.day06.BoatRace {\n private final io.steinh.aoc.day06.BoatRaceStats input;\n\n public io.steinh.aoc.day06.BoatRace(io.steinh.aoc.day06.... |
daincredibleholg__AdventOfCode2023__4aa7c68/src/main/kotlin/io/steinh/aoc/day01/Trebuchet.kt | package io.steinh.aoc.day01
class Trebuchet {
fun String.replace(vararg pairs: Pair<String, String>): String =
pairs.fold(this) { acc, (old, new) -> acc.replace(old, new, ignoreCase = true) }
fun calibrate(input: List<String>): Int {
val transformedStrings = transform(input)
return transformedStrings.sumOf {
s -> "${ s.first { it.isDigit() }}${ s.last { it.isDigit() }}".toInt()
}
}
private fun transform(input: List<String>): List<String> {
val regex = Regex("^(one|two|three|four|five|six|seven|eight|nine)")
return buildList {
for (line in input) {
var transformed = ""
for (i in line.indices) {
if (line[i].isDigit()) {
transformed += line[i]
} else {
transformed += when (regex.find(line.substring(i))?.value) {
"one" -> "1"
"two" -> "2"
"three" -> "3"
"four" -> "4"
"five" -> "5"
"six" -> "6"
"seven" -> "7"
"eight" -> "8"
"nine" -> "9"
else -> ""
}
}
}
add(transformed)
}
}
}
}
fun main() {
val input = {}.javaClass.classLoader?.getResource("day01/input.txt")?.readText()?.lines()
val trebuchet = Trebuchet()
val sum = trebuchet.calibrate(input!!)
print("Result 1: $sum")
}
| [
{
"class_path": "daincredibleholg__AdventOfCode2023__4aa7c68/io/steinh/aoc/day01/TrebuchetKt.class",
"javap": "Compiled from \"Trebuchet.kt\"\npublic final class io.steinh.aoc.day01.TrebuchetKt {\n public static final void main();\n Code:\n 0: invokedynamic #25, 0 // InvokeDynamic #0:... |
daincredibleholg__AdventOfCode2023__4aa7c68/src/main/kotlin/io/steinh/aoc/day04/Scratchcard.kt | package io.steinh.aoc.day04
class Scratchcard {
fun calculatePoints(lines: List<String>) = getMatchingNumbers(lines).sum()
fun calculateNumberOfCardsWon(lines: List<String>): Int {
val givenNumberOfCards = lines.size
val numberOfCards = initCardStack(givenNumberOfCards)
for (line in lines) {
val firstSplit = line.split(":")
val cardId = firstSplit[0].substringAfter("Card ").trim().toInt()
println("Processing card #$cardId:")
val instancesOfThisCard = numberOfCards[cardId]
println("\texisting instances: $instancesOfThisCard")
val numberOfMatches = extractWinningNumbers(firstSplit[1]).size
println("\tno. matching numbers: $numberOfMatches")
if (numberOfMatches == 0) {
println("\tNo matches, continuing to next card. Done processing card #$cardId")
continue
}
val start = cardId + 1
if (start <= givenNumberOfCards) {
val end =
if (cardId + numberOfMatches < givenNumberOfCards)
cardId + numberOfMatches
else
givenNumberOfCards
println("\tWill add $instancesOfThisCard instances to cards ##" + (start..end))
for (i in start..end) {
numberOfCards[i] = numberOfCards[i]!! + instancesOfThisCard!!
println("\t\tAdded $instancesOfThisCard to card #$i. This card has now ${numberOfCards[i]} " +
"instances.")
}
}
println("\tDone processing card $cardId\n")
}
return numberOfCards
.map { it.value }
.sum()
}
private fun initCardStack(givenNumberOfCards: Int): MutableMap<Int, Int> {
val result = mutableMapOf<Int, Int>()
for (i in 1..givenNumberOfCards) {
result[i] = 1
}
return result
}
private fun getMatchingNumbers(lines: List<String>) = buildList {
for (line in lines) {
val firstSplit = line.split(":")
val intersection = extractWinningNumbers(firstSplit[1])
var result = 0
for (i in 1..intersection.size) {
result = if (i == 1) 1 else result * 2
}
add(result)
}
}
private fun extractWinningNumbers(matchesAndGuesses: String): Set<Int> {
val winnersAndGuesses = matchesAndGuesses.split("|")
val winners = winnersAndGuesses[0].split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
val guesses = winnersAndGuesses[1].split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
val intersection = winners.intersect(guesses.toSet())
return intersection
}
}
fun main() {
val lines = {}.javaClass.classLoader?.getResource("day04/input.txt")?.readText()?.lines()!!
val scratchcard = Scratchcard()
val resultPart1 = scratchcard.calculatePoints(lines)
val resultPart2 = scratchcard.calculateNumberOfCardsWon(lines)
println("Result day 04, part I: $resultPart1")
println("Result day 04, part II: $resultPart2")
}
| [
{
"class_path": "daincredibleholg__AdventOfCode2023__4aa7c68/io/steinh/aoc/day04/Scratchcard.class",
"javap": "Compiled from \"Scratchcard.kt\"\npublic final class io.steinh.aoc.day04.Scratchcard {\n public io.steinh.aoc.day04.Scratchcard();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
daincredibleholg__AdventOfCode2023__4aa7c68/src/main/kotlin/io/steinh/aoc/day03/GearRatios.kt | package io.steinh.aoc.day03
class GearRatios {
fun addUpPartNumbers(lines: List<String>): Int {
var result = 0
for (lineIndex in lines.indices) {
val line = lines[lineIndex]
val numberMatches = "(\\d+)".toRegex().findAll(line)
for (numberMatch in numberMatches) {
var startPos = numberMatch.groups[0]!!.range.first()
if (startPos > 0) {
startPos -= 1
}
val endPos = numberMatch.groups[0]!!.range.last() + 1
val startLineId = if (lineIndex > 0) lineIndex - 1 else 0
val endLineId = if (lineIndex < lines.lastIndex) lineIndex + 1 else lineIndex
if (hasAdjacentSymbol(lines, startLineId, endLineId, startPos, endPos)) {
result += numberMatch.groups[0]!!.value.toInt()
}
}
}
return result
}
fun calculateGearRatioSum(lines: List<String>): Int {
var result = 0
for (lineIndex in lines.indices) {
val line = lines[lineIndex]
val asteriskMatches = "([*])".toRegex().findAll(line)
for (match in asteriskMatches) {
result += searchAndCalculate(lines, lineIndex, match.groups[0]!!.range)
}
}
return result
}
private fun searchAndCalculate(lines: List<String>, lineIndex: Int, range: IntRange): Int {
val minLineId = if (lineIndex > 0) lineIndex - 1 else 0
val maxLineId = if (lineIndex < lines.lastIndex) lineIndex + 1 else lineIndex
val foundNumbers = mutableListOf<Int>()
for (i in minLineId..maxLineId) {
val line = lines[i]
val numberMatches = "(\\d+)".toRegex().findAll(line)
for (match in numberMatches) {
val matchRange = match.groups[0]!!.range
val startAt = if (matchRange.first() > 0) matchRange.first() - 1 else 0
val endAt = matchRange.last() + 1
if ((startAt..endAt).contains(range.first())) {
foundNumbers.add(match.groups[0]!!.value.toInt())
}
}
}
if (foundNumbers.size == 2) {
return foundNumbers.first() * foundNumbers.last()
}
return 0
}
private fun hasAdjacentSymbol(
lines: List<String>,
startLineId: Int,
endLineId: Int,
startPos: Int,
endPos: Int
): Boolean {
var result = false
for (i in startLineId..endLineId) {
val max = if (endPos >= lines[i].length) lines[i].length - 1 else endPos
val subString = lines[i].substring(startPos..max)
result = result || subString.any { it != '.' && !it.isDigit() }
}
return result
}
}
fun main() {
val gearRatios = GearRatios()
val lines = {}.javaClass.classLoader?.getResource("day03/input.txt")?.readText()?.lines()!!
val resultPart1 = gearRatios.addUpPartNumbers(lines)
val resultPart2 = gearRatios.calculateGearRatioSum(lines)
print ("Result Day 3, Part I: $resultPart1\n")
print ("Result Day 3, Part II: $resultPart2\n")
}
| [
{
"class_path": "daincredibleholg__AdventOfCode2023__4aa7c68/io/steinh/aoc/day03/GearRatiosKt.class",
"javap": "Compiled from \"GearRatios.kt\"\npublic final class io.steinh.aoc.day03.GearRatiosKt {\n public static final void main();\n Code:\n 0: new #8 // class io/stein... |
daincredibleholg__AdventOfCode2023__4aa7c68/src/main/kotlin/io/steinh/aoc/day02/CubeConundrum.kt | package io.steinh.aoc.day02
class CubeConundrum {
fun sumIds(lines: List<String>, bagLimits: List<CubeCount>): Int {
val processed = analyze(lines)
var sum = 0
for (game in processed) {
var match = true
for (entry in game.value) {
for (limit in bagLimits) {
match = match && entry.any { it.color == limit.color && it.count <= limit.count }
}
}
if (match) {
print("Game ${game.key} is possible\n")
sum += game.key
}
}
return sum
}
fun powerOfTheFewest(lines: List<String>): Int {
val processed = analyze(lines)
val fewest = getFewest(processed)
var result = 0
for (game in fewest) {
val value = game.value.map { it.count }.reduce { acc, i -> acc * i }
result += value
}
return result
}
private fun getFewest(processed: Map<Int, List<List<CubeCount>>>): Map<Int, List<CubeCount>> {
val result = mutableMapOf<Int, List<CubeCount>>()
for (game in processed) {
var red = 0
var green = 0
var blue = 0
for (set in game.value) {
for (entry in set) {
when (entry.color) {
"red" -> red = if (red < entry.count) entry.count else red
"green" -> green = if (green < entry.count) entry.count else green
"blue" -> blue = if (blue < entry.count) entry.count else blue
}
}
}
result[game.key] = listOf(
CubeCount(red, "red"),
CubeCount(green, "green"),
CubeCount(blue, "blue")
)
}
return result
}
private fun analyze(lines: List<String>): Map<Int, List<List<CubeCount>>> {
val result: MutableMap<Int, List<List<CubeCount>>> = mutableMapOf()
for (line in lines) {
val gameId = "Game (\\d+)".toRegex().find(line)!!.groupValues[1].toInt()
val drawnSets = line.split(": ").last().split(";")
val sets = buildList {
for (set in drawnSets) {
add(
buildList {
var redCubes = 0
var greenCubes = 0
var blueCubes = 0
for (matches in "(\\d+) (red|green|blue)".toRegex().findAll(set)) {
val cnt = matches.groups[1]!!.value.toInt()
when (matches.groups[2]!!.value) {
"red" -> redCubes += cnt
"green" -> greenCubes += cnt
"blue" -> blueCubes += cnt
}
}
add(CubeCount(redCubes, "red"))
add(CubeCount(blueCubes, "blue"))
add(CubeCount(greenCubes, "green"))
})
}
}
result.put(gameId, sets)
}
return result
}
}
data class CubeCount(
val count: Int,
val color: String,
)
fun main() {
val input = {}.javaClass.classLoader?.getResource("day02/input.txt")?.readText()?.lines()!!
val bagLimits = listOf(
CubeCount(12, "red"),
CubeCount(13, "green"),
CubeCount(14, "blue")
)
val cubeConundrum = CubeConundrum()
val result = cubeConundrum.sumIds(input, bagLimits)
val resultPart2 = cubeConundrum.powerOfTheFewest(input)
print("Solution for Day 2, Part I: $result\n")
print("Solution for Day 2, Part II: $resultPart2\n")
}
| [
{
"class_path": "daincredibleholg__AdventOfCode2023__4aa7c68/io/steinh/aoc/day02/CubeConundrumKt.class",
"javap": "Compiled from \"CubeConundrum.kt\"\npublic final class io.steinh.aoc.day02.CubeConundrumKt {\n public static final void main();\n Code:\n 0: invokedynamic #25, 0 // Invok... |
daincredibleholg__AdventOfCode2023__4aa7c68/src/main/kotlin/io/steinh/aoc/day05/Almanac.kt | package io.steinh.aoc.day05
class Almanac(private val sourceData: Input) {
fun lowestLocation(): Long {
val list = mutableListOf<Long>()
sourceData.seeds.forEach {
val soil = getSoilForSeed(it)
val fertilizer = getFertilizerForSoil(soil)
val water = getWaterForFertilizer(fertilizer)
val light = getLightForWater(water)
val temperature = getTemperatureForLight(light)
val humidity = getHumidityForTemperature(temperature)
list.add(getLocationForHumidity(humidity))
}
list.sort()
return list.first()
}
fun lowestLocationForSeedRanges(): Long {
var lowestLocationFound = 0L
sourceData.seeds.chunked(2).forEach { seedRange ->
for(it in seedRange.first()..(seedRange.first() + seedRange.last())) {
val soil = getSoilForSeed(it)
val fertilizer = getFertilizerForSoil(soil)
val water = getWaterForFertilizer(fertilizer)
val light = getLightForWater(water)
val temperature = getTemperatureForLight(light)
val humidity = getHumidityForTemperature(temperature)
val location = getLocationForHumidity(humidity)
lowestLocationFound =
if (lowestLocationFound == 0L || location < lowestLocationFound)
location
else lowestLocationFound
}
}
return lowestLocationFound
}
private fun getSoilForSeed(seed: Long) =
filterFromMapping(seed, sourceData.seedToSoilMappings)
private fun getFertilizerForSoil(soil: Long) =
filterFromMapping(soil, sourceData.soilToFertilizerMappings)
private fun getWaterForFertilizer(fertilizer: Long) =
filterFromMapping(fertilizer, sourceData.fertilizerToWaterMappings)
private fun getLightForWater(water: Long) =
filterFromMapping(water, sourceData.waterToLightMappings)
private fun getTemperatureForLight(light: Long) =
filterFromMapping(light, sourceData.lightToTemperatureMappings)
private fun getHumidityForTemperature(temperature: Long) =
filterFromMapping(temperature, sourceData.temperatureToHumidityMappings)
private fun getLocationForHumidity(humidity: Long) =
filterFromMapping(humidity, sourceData.humidityToLocationMappings)
private fun filterFromMapping(id: Long, mappings: List<Mapping>): Long =
mappings
.filter {
it.sourceRangeStart.contains(id)
}.map {
it.destinationRangeStart.first + (id - it.sourceRangeStart.first)
}.ifEmpty {
listOf(id)
}.first()
}
fun main() {
val rawInput = {}.javaClass.classLoader?.getResource("day05/input.txt")?.readText()!!
val inputProcessor = AlmanacInputProcessor()
val input = inputProcessor.transform(rawInput)
val instance = Almanac(input)
val resultOne = instance.lowestLocation()
println("Result for day 05, part I: $resultOne")
val resultTwo = instance.lowestLocationForSeedRanges()
println("Result for day 05, part II: $resultTwo")
}
| [
{
"class_path": "daincredibleholg__AdventOfCode2023__4aa7c68/io/steinh/aoc/day05/AlmanacKt.class",
"javap": "Compiled from \"Almanac.kt\"\npublic final class io.steinh.aoc.day05.AlmanacKt {\n public static final void main();\n Code:\n 0: invokedynamic #25, 0 // InvokeDynamic #0:invoke... |
daincredibleholg__AdventOfCode2023__4aa7c68/src/main/kotlin/io/steinh/aoc/day05/AlmanacInputProcessor.kt | package io.steinh.aoc.day05
class AlmanacInputProcessor {
companion object {
const val LENGTH_POSITION = 3
}
fun transform(input: String): Input {
return Input(
extractSeeds(input),
extractBlockFor("seed-to-soil", input),
extractBlockFor("soil-to-fertilizer", input),
extractBlockFor("fertilizer-to-water", input),
extractBlockFor("water-to-light", input),
extractBlockFor("light-to-temperature", input),
extractBlockFor("temperature-to-humidity", input),
extractBlockFor("humidity-to-location", input)
)
}
private fun extractSeeds(input: String): List<Long> {
val spaceSeperatedSeeds = "^seeds: ([\\d ]+)\n".toRegex().find(input) ?: return emptyList()
return spaceSeperatedSeeds.groupValues[1].split(" ").map { it.toLong() }
}
private fun extractBlockFor(prefix: String, input: String): List<Mapping> {
val rawMappings = "$prefix map:.*([\\d \\n]+)".toRegex().findAll(input)
return rawMappings.flatMap {
"(\\d+) (\\d+) (\\d+)\\n?".toRegex().findAll(it.groupValues[1])
.map { mappings -> extractMapping(mappings) }
}.toList()
}
private fun extractMapping(matchResult: MatchResult): Mapping {
var length = matchResult.groupValues[LENGTH_POSITION].toLong()
if (length > 0) {
length -= 1
}
val destinationRangeStart = matchResult.groupValues[1].toLong()
val sourceRangeStart = matchResult.groupValues[2].toLong()
return Mapping(destinationRangeStart..(destinationRangeStart+length),
sourceRangeStart..(sourceRangeStart+length))
}
}
data class Mapping(
val destinationRangeStart: LongRange,
val sourceRangeStart: LongRange,
)
data class Input(
val seeds: List<Long>,
val seedToSoilMappings: List<Mapping>,
val soilToFertilizerMappings: List<Mapping>,
val fertilizerToWaterMappings: List<Mapping>,
val waterToLightMappings: List<Mapping>,
val lightToTemperatureMappings: List<Mapping>,
val temperatureToHumidityMappings: List<Mapping>,
val humidityToLocationMappings: List<Mapping>,
)
| [
{
"class_path": "daincredibleholg__AdventOfCode2023__4aa7c68/io/steinh/aoc/day05/AlmanacInputProcessor$Companion.class",
"javap": "Compiled from \"AlmanacInputProcessor.kt\"\npublic final class io.steinh.aoc.day05.AlmanacInputProcessor$Companion {\n private io.steinh.aoc.day05.AlmanacInputProcessor$Compani... |
kirvader__AutomatedSoccerRecordingWithAndroid__9dfbebf/movement/src/main/java/com/hawkeye/movement/utils/AngleMeasure.kt | package com.hawkeye.movement.utils
import kotlin.math.PI
fun cos(angle: AngleMeasure): Float = kotlin.math.cos(angle.radian())
fun sin(angle: AngleMeasure): Float = kotlin.math.sin(angle.radian())
fun abs(angle: AngleMeasure): AngleMeasure = Degree(kotlin.math.abs(angle.degree()))
fun sign(angle: AngleMeasure): Float {
return if (angle > Degree(0f)) {
1f
} else if (angle < Degree(0f)) {
-1f
} else {
0f
}
}
fun min(a: AngleMeasure, b: AngleMeasure): AngleMeasure =
Degree(kotlin.math.min(a.degree(), b.degree()))
fun max(a: AngleMeasure, b: AngleMeasure): AngleMeasure =
Degree(kotlin.math.max(a.degree(), b.degree()))
interface AngleMeasure : Comparable<AngleMeasure> {
fun degree(): Float {
return this.radian() * 180.0f / PI.toFloat()
}
fun radian(): Float {
return this.degree() * PI.toFloat() / 180.0f
}
override operator fun compareTo(angle: AngleMeasure): Int {
val deltaAngle = this.degree() - angle.degree()
if (deltaAngle < -eps) {
return -1
}
if (deltaAngle > eps) {
return 1
}
return 0
}
operator fun plus(angle: AngleMeasure): AngleMeasure {
return Degree(this.degree() + angle.degree())
}
operator fun minus(angle: AngleMeasure): AngleMeasure {
return Degree(this.degree() - angle.degree())
}
operator fun times(factor: Float): AngleMeasure {
return Degree(this.degree() * factor)
}
operator fun div(factor: Float): AngleMeasure {
return Degree(this.degree() / factor)
}
companion object {
private const val eps = 0.00001f
}
}
class Radian(private val angle: Float) : AngleMeasure {
override fun degree(): Float = angle * 180.0f / PI.toFloat()
override fun radian(): Float = angle
}
class Degree(private val angle: Float) : AngleMeasure {
override fun degree(): Float = angle
override fun radian(): Float = angle * PI.toFloat() / 180.0f
}
| [
{
"class_path": "kirvader__AutomatedSoccerRecordingWithAndroid__9dfbebf/com/hawkeye/movement/utils/AngleMeasure$DefaultImpls.class",
"javap": "Compiled from \"AngleMeasure.kt\"\npublic final class com.hawkeye.movement.utils.AngleMeasure$DefaultImpls {\n public static float degree(com.hawkeye.movement.utils... |
clechasseur__adventofcode2020__f3e8840/src/main/kotlin/org/clechasseur/adventofcode2020/math/Math.kt | package org.clechasseur.adventofcode2017.math
import kotlin.math.abs
fun <T> permutations(elements: List<T>): Sequence<List<T>> {
if (elements.size == 1) {
return sequenceOf(listOf(elements.first()))
}
return elements.asSequence().flatMap { elem ->
val subIt = permutations(elements - elem).iterator()
generateSequence { when (subIt.hasNext()) {
true -> listOf(elem) + subIt.next()
false -> null
} }
}
}
fun generatePairSequence(firstRange: IntRange, secondRange: IntRange): Sequence<Pair<Int, Int>> {
return generateSequence(firstRange.first to secondRange.first) { when (it.second) {
secondRange.last -> when (it.first) {
firstRange.last -> null
else -> it.first + 1 to secondRange.first
}
else -> it.first to it.second + 1
} }
}
fun factors(n: Long): List<Long> {
return generateSequence(1L) { when {
it < n -> it + 1L
else -> null
} }.filter { n % it == 0L }.toList()
}
fun greatestCommonDenominator(a: Long, b: Long): Long {
// https://en.wikipedia.org/wiki/Euclidean_algorithm
require(a > 0L && b > 0L) { "Can only find GCD for positive numbers" }
var rm = b
var r = a % rm
while (r != 0L) {
val rm2 = rm
rm = r
r = rm2 % rm
}
return rm
}
fun leastCommonMultiple(a: Long, b: Long): Long {
// https://en.wikipedia.org/wiki/Least_common_multiple
require(a > 0L && b > 0L) { "Can only find LCM for positive numbers" }
return a / greatestCommonDenominator(a, b) * b
}
fun reduceFraction(numerator: Long, denominator: Long): Pair<Long, Long> {
require(denominator != 0L) { "Divide by zero error" }
return when (numerator) {
0L -> 0L to 1L
else -> {
val gcd = greatestCommonDenominator(abs(numerator), abs(denominator))
(numerator / gcd) to (denominator / gcd)
}
}
}
| [
{
"class_path": "clechasseur__adventofcode2020__f3e8840/org/clechasseur/adventofcode2017/math/MathKt.class",
"javap": "Compiled from \"Math.kt\"\npublic final class org.clechasseur.adventofcode2017.math.MathKt {\n public static final <T> kotlin.sequences.Sequence<java.util.List<T>> permutations(java.util.L... |
mdenburger__aoc-2020__b965f46/src/main/kotlin/day09/Day09.kt | package day09
import java.io.File
fun main() {
val numbers = File("src/main/kotlin/day09/day09-input.txt").readLines().map { it.toLong() }.toLongArray()
val window = 25
val invalidNumber = answer1(numbers, window)
println("Answer 1: $invalidNumber")
println("Answer 2: " + answer2(numbers, invalidNumber))
}
private fun answer1(numbers: LongArray, window: Int): Long {
for (start in 0 until numbers.size - window) {
val next = numbers[start + window]
if (!numbers.containsSum(start, start + window, next)) {
return next
}
}
error("No answer found")
}
private fun LongArray.containsSum(start: Int, end: Int, sum: Long): Boolean {
for (i in start until end) {
val first = get(i)
for (j in i + 1 until end) {
val second = get(j)
if (first != second && first + second == sum) {
return true
}
}
}
return false
}
private fun answer2(numbers: LongArray, sum: Long): Long {
for (start in numbers.indices) {
numbers.findRangeSumsTo(start, sum)?.let {
return it.minOrNull()!! + it.maxOrNull()!!
}
}
error("No answer found")
}
private fun LongArray.findRangeSumsTo(start: Int, sum: Long): List<Long>? {
val range = mutableListOf<Long>()
var rangeSum = 0L
for (i in start until size) {
range += get(i)
rangeSum += get(i)
if (rangeSum == sum) {
return range
}
if (rangeSum > sum) {
return null
}
}
return null
}
| [
{
"class_path": "mdenburger__aoc-2020__b965f46/day09/Day09Kt.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class day09.Day09Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
mdenburger__aoc-2020__b965f46/src/main/kotlin/day08/Day08.kt | package day08
import java.io.File
data class Operation(val name: String, val argument: Int)
class Program(private val operations: List<Operation>) {
private var instruction = 0
private var accumulator = 0
private val visited = BooleanArray(operations.size)
fun run(): Int {
while (instruction < operations.size && !visited[instruction]) {
visited[instruction] = true
val operation = operations[instruction]
when (operation.name) {
"nop" -> instruction += 1
"acc" -> {
accumulator += operation.argument
instruction += 1
}
"jmp" -> instruction += operation.argument
else -> error("unknown operation: ${operation.name}")
}
}
return accumulator
}
fun terminated() = instruction >= operations.size
}
fun main() {
val operations = File("src/main/kotlin/day08/day08-input.txt").readLines().map {
val (operationName, argument) = it.split(" ")
Operation(operationName, argument.toInt())
}
println("Answer 1: " + operations.run())
println("Answer 2: " + operations.modifyAndRun())
}
fun List<Operation>.run() = Program(this).run()
fun List<Operation>.modifyAndRun(): Int? {
forEachIndexed { index, operation ->
when (operation.name) {
"jmp", "nop" -> {
val modifiedOperations = toMutableList()
val modifiedOperationName = when (operation.name) {
"jmp" -> "nop"
"nop" -> "jmp"
else -> operation.name
}
modifiedOperations[index] = Operation(modifiedOperationName, operation.argument)
val program = Program(modifiedOperations)
val result = program.run()
if (program.terminated()) {
return result
}
}
}
}
return null
}
| [
{
"class_path": "mdenburger__aoc-2020__b965f46/day08/Day08Kt.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class day08.Day08Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
mdenburger__aoc-2020__b965f46/src/main/kotlin/day10/Day10Second.kt | package day10
import java.io.File
import kotlin.math.pow
fun main() {
val differences = File("src/main/kotlin/day10/day10-input.txt")
.readLines()
.map { it.toInt() }
.sorted()
.let { listOf(0) + it + listOf(it.last() + 3) }
.windowed(2)
.map { it[1] - it[0] }
val permutationsOfOnes = listOf(0, 1, 2, 4, 7)
val sublistCount = longArrayOf(0, 0, 0, 0, 0)
var numberOfOnes = 0
differences.forEach { diff ->
if (diff == 1) {
numberOfOnes++
} else {
sublistCount[numberOfOnes]++
numberOfOnes = 0
}
}
var answer = 1L
for (i in 2 until sublistCount.size) {
val permutations = permutationsOfOnes[i].pow(sublistCount[i])
if (permutations > 0) {
answer *= permutations
}
}
println(answer)
}
fun Int.pow(n: Long) = toDouble().pow(n.toDouble()).toLong()
| [
{
"class_path": "mdenburger__aoc-2020__b965f46/day10/Day10SecondKt.class",
"javap": "Compiled from \"Day10Second.kt\"\npublic final class day10.Day10SecondKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ... |
PeteShepley__advent-of-code__f9679c1/2019/DEC02/src/main/kotlin/day2/App.kt | package day2
class Computer(val program: Array<Int>) {
private var pointer: Int = 0
fun execute() {
while (pointer < program.size) {
when (program[pointer]) {
1 -> {
add()
pointer += 4
}
2 -> {
mult()
pointer += 4
}
99 -> pointer = program.size
}
}
}
override fun toString(): String {
return program.joinToString(" ")
}
private fun add() {
val op1 = program[program[pointer + 1]]
val op2 = program[program[pointer + 2]]
val loc = program[pointer + 3]
program[loc] = op1 + op2
}
private fun mult() {
val op1 = program[program[pointer + 1]]
val op2 = program[program[pointer + 2]]
val loc = program[pointer + 3]
program[loc] = op1 * op2
}
}
fun copyOfProgram(): Array<Int> {
return arrayOf(1, 0, 0, 3, 1, 1, 2, 3, 1, 3, 4, 3, 1, 5, 0, 3, 2, 1, 10, 19, 1, 6, 19, 23, 2, 23, 6, 27, 2, 6, 27, 31, 2, 13, 31, 35, 1, 10, 35, 39, 2, 39, 13, 43, 1, 43, 13, 47, 1, 6, 47, 51, 1, 10, 51, 55, 2, 55, 6, 59, 1, 5, 59, 63, 2, 9, 63, 67, 1, 6, 67, 71, 2, 9, 71, 75, 1, 6, 75, 79, 2, 79, 13, 83, 1, 83, 10, 87, 1, 13, 87, 91, 1, 91, 10, 95, 2, 9, 95, 99, 1, 5, 99, 103, 2, 10, 103, 107, 1, 107, 2, 111, 1, 111, 5, 0, 99, 2, 14, 0, 0)
}
fun main(args: Array<String>) {
for (noun in 0..99) {
print('*')
for (verb in 0..99) {
print('.')
val testProgram = copyOfProgram()
testProgram[1] = noun
testProgram[2] = verb
val comp = Computer(testProgram)
comp.execute()
if (comp.program[0] == 19690720) {
println("Noun: $noun Verb: $verb")
}
}
}
}
| [
{
"class_path": "PeteShepley__advent-of-code__f9679c1/day2/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class day2.AppKt {\n public static final java.lang.Integer[] copyOfProgram();\n Code:\n 0: bipush 121\n 2: anewarray #9 // class java/lang/Int... |
LukasHavemann__microservice-transformer__8638fe7/src/main/kotlin/de/havemann/transformer/domain/sortkey/SortKey.kt | package de.havemann.transformer.domain.sortkey
import java.util.*
import java.util.Comparator.comparing
import kotlin.reflect.KProperty1
/**
* Sorting is determined through the use of the ‘sort’ query string parameter. The value of this parameter is a
* comma-separated list of sort keys. Sort directions can optionally be appended to each sort key, separated by the ‘:’
* character.
*
* The supported sort directions are either ‘asc’ for ascending or ‘desc’ for descending.
*
* The caller may (but is not required to) specify a sort direction for each key. If a sort direction is not specified
* for a key, then a default is set by the server.
*/
data class SortKey(val key: String, val ordering: Ordering) {
companion object {
/**
* Transforms a list of {@link SortKey} to a {@link Comparator}
*/
fun <Entity, Value : Comparable<Value>> toComparator(
sortKeys: List<SortKey>,
sortKeyToProperty: Map<String, KProperty1<Entity, Value?>>
): Comparator<Entity> {
return sortKeys
.stream()
.filter { sortKeyToProperty[it.key] != null }
.map { sortKey ->
val property = sortKeyToProperty[sortKey.key]
val sortingFunction: (t: Entity) -> Value = { property?.call(it)!! }
sortKey.ordering.adjust(comparing(sortingFunction))
}
.reduce { a, b -> a.thenComparing(b) }
.orElseThrow { IllegalArgumentException("list shouldn't be empty") }
}
}
}
enum class Ordering(val key: String) {
ASCENDING("asc"),
DESCENDING("desc");
/**
* reverses the given comparator if ordering is descending
*/
fun <T> adjust(comparator: Comparator<T>): Comparator<T> {
return if (this == DESCENDING) comparator.reversed() else comparator
}
companion object {
/**
* determines Ordering form given string
*/
fun detect(token: String): Ordering {
return values().asSequence()
.filter { it.key == token }
.firstOrNull()
?: throw IllegalArgumentException(token)
}
}
}
| [
{
"class_path": "LukasHavemann__microservice-transformer__8638fe7/de/havemann/transformer/domain/sortkey/SortKey$Companion.class",
"javap": "Compiled from \"SortKey.kt\"\npublic final class de.havemann.transformer.domain.sortkey.SortKey$Companion {\n private de.havemann.transformer.domain.sortkey.SortKey$C... |
Mindera__skeletoid__881de79/base/src/main/java/com/mindera/skeletoid/utils/versioning/Versioning.kt | package com.mindera.skeletoid.utils.versioning
import kotlin.math.sign
object Versioning {
/**
* Compares two version strings.
* Credits to: https://gist.github.com/antalindisguise/d9d462f2defcfd7ae1d4
*
* Use this instead of String.compareTo() for a non-lexicographical
* comparison that works for version strings. e.g. "1.10".compareTo("1.6").
*
* @note It does not work if "1.10" is supposed to be equal to "1.10.0".
*
* @param str1 a string of ordinal numbers separated by decimal points.
* @param str2 a string of ordinal numbers separated by decimal points.
* @return The result is a negative integer if str1 is _numerically_ less than str2.
* The result is a positive integer if str1 is _numerically_ greater than str2.
* The result is zero if the strings are _numerically_ equal.
*/
fun compareVersions(str1: String, str2: String): Int {
if (str1.isBlank() || str2.isBlank()) {
throw IllegalArgumentException("Invalid Version")
}
val vals1 = str1.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val vals2 = str2.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var i = 0
// set index to first non-equal ordinal or length of shortest version string
while (i < vals1.size && i < vals2.size && vals1[i] == vals2[i]) {
i++
}
// compare first non-equal ordinal number
return run {
// compare first non-equal ordinal number
if (i < vals1.size && i < vals2.size) {
vals1[i].toInt().compareTo(vals2[i].toInt())
} else {
// the strings are equal or one string is a substring of the other
// e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
vals1.size - vals2.size
}
}.sign
}
}
| [
{
"class_path": "Mindera__skeletoid__881de79/com/mindera/skeletoid/utils/versioning/Versioning.class",
"javap": "Compiled from \"Versioning.kt\"\npublic final class com.mindera.skeletoid.utils.versioning.Versioning {\n public static final com.mindera.skeletoid.utils.versioning.Versioning INSTANCE;\n\n pri... |
AhmedTawfiqM__ProblemSolving__a569265/src/palindrome_int/PalindRomeInt.kt | package palindrome_int
//https://leetcode.com/problems/palindrome-number
object PalindRomeInt {
private fun isPalindrome(input: Int): Boolean {
if (input < 0 || input >= Int.MAX_VALUE) return false
if (input in 0..9) return true
var original = input
var reversed = 0
while (original != 0) {
reversed = (reversed * 10) + original % 10
original /= 10
}
return input == reversed
}
@JvmStatic
fun main(args: Array<String>) {
println(isPalindrome(121))
println(isPalindrome(-121))
println(isPalindrome(10))
}
}
/**
* Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
**/ | [
{
"class_path": "AhmedTawfiqM__ProblemSolving__a569265/palindrome_int/PalindRomeInt.class",
"javap": "Compiled from \"PalindRomeInt.kt\"\npublic final class palindrome_int.PalindRomeInt {\n public static final palindrome_int.PalindRomeInt INSTANCE;\n\n private palindrome_int.PalindRomeInt();\n Code:\n ... |
AhmedTawfiqM__ProblemSolving__a569265/src/palindrome_int/PalindRomeString.kt | package palindrome_int
//https://leetcode.com/problems/palindrome-number
object PalindRomeString {
private fun isPalindrome(input: Int): Boolean {
if (input < 0 || input >= Int.MAX_VALUE) return false
if (input in 0..9) return true
val original = input.toString()
original.forEachIndexed { index, num ->
if (num != original[original.length - (index+1)])
return false
}
return true
}
@JvmStatic
fun main(args: Array<String>) {
println(isPalindrome(121))
println(isPalindrome(-121))
println(isPalindrome(10))
}
}
/**
* Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
**/ | [
{
"class_path": "AhmedTawfiqM__ProblemSolving__a569265/palindrome_int/PalindRomeString.class",
"javap": "Compiled from \"PalindRomeString.kt\"\npublic final class palindrome_int.PalindRomeString {\n public static final palindrome_int.PalindRomeString INSTANCE;\n\n private palindrome_int.PalindRomeString()... |
AhmedTawfiqM__ProblemSolving__a569265/src/common_prefix/CommonPrefix.kt | package common_prefix
//https://leetcode.com/problems/longest-common-prefix/
object CommonPrefix {
private fun longestCommonPrefix(list: Array<String>): String {
if (list.isEmpty()) return ""
var prefix = list[0]
list.forEach {
while (it.indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length - 1)
}
}
return prefix
}
@JvmStatic
fun main(args: Array<String>) {
println(longestCommonPrefix(arrayOf("flower", "flow", "flight")))
println(longestCommonPrefix(arrayOf("dog", "racecar", "car")))
println(longestCommonPrefix(arrayOf("ahmed", "sahm", "wassbah")))
}
}
/*
* Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
**/ | [
{
"class_path": "AhmedTawfiqM__ProblemSolving__a569265/common_prefix/CommonPrefix.class",
"javap": "Compiled from \"CommonPrefix.kt\"\npublic final class common_prefix.CommonPrefix {\n public static final common_prefix.CommonPrefix INSTANCE;\n\n private common_prefix.CommonPrefix();\n Code:\n 0: ... |
jack-bolles__GildedRose-Refactoring-Kata-Kotlin__2036281/src/main/kotlin/com/gildedrose/Item.kt | package com.gildedrose
data class Item(val name: String, val sellIn: Int, val quality: Int) {
override fun toString(): String {
return this.name + ", " + this.sellIn + ", " + this.quality
}
}
fun Item.ageBy(days: Int): Item {
return copy(
sellIn = remainingSellInAfter(days),
quality = qualityIn(days)
)
}
private fun Item.remainingSellInAfter(days: Int): Int {
return when (name) {
"Sulfuras, Hand of Ragnaros" -> sellIn
else -> sellIn - days
}
}
private fun Item.qualityIn(days: Int): Int {
return when {
name == "Backstage passes to a TAFKAL80ETC concert" ->
boundedQuality(quality + this.incrementQualityFor(days))
name == "Sulfuras, Hand of Ragnaros" ->
quality
name == "Aged Brie" ->
boundedQuality(quality + days)
name.startsWith("Conjured") ->
boundedQuality(quality + -2 * days)
else -> boundedQuality(quality + -1 * days)
}
}
private fun boundedQuality(rawQuality: Int): Int {
return Integer.min(50, Integer.max(0, rawQuality))
}
private fun Item.incrementQualityFor(days: Int): Int {
val daysToSell = sellIn
return (1 until days + 1)
.fold(0) { total, e -> total + accelerateQualityWhenExpiring(daysToSell - e, quality) }
}
private fun accelerateQualityWhenExpiring(sellIn: Int, startingQuality: Int): Int {
return when {
sellIn < 0 -> -startingQuality
sellIn <= 5 -> 3
sellIn <= 10 -> 2
else -> 1
}
}
| [
{
"class_path": "jack-bolles__GildedRose-Refactoring-Kata-Kotlin__2036281/com/gildedrose/Item.class",
"javap": "Compiled from \"Item.kt\"\npublic final class com.gildedrose.Item {\n private final java.lang.String name;\n\n private final int sellIn;\n\n private final int quality;\n\n public com.gildedros... |
Kraktun__java_web_frameworks_cmp__28c5739/code/supportLib/src/main/java/it/unipd/stage/sl/lib/rsa/RsaUtils.kt | package it.unipd.stage.sl.lib.rsa
import java.math.BigInteger
/*
The following functions come from
https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Key_generation
*/
/**
* @return true is a big integer is probably prime with certainty 15
*/
fun BigInteger.isPrime(): Boolean {
// not 100% correct, but error is very low and for this type of application it's good enough
return this.isProbablePrime(15)
}
/**
* @param n1 a non null positive big integer
* @param n2 a non null positive big integer
* @return true if n1 and n2 are coprime
*/
fun areCoprime(n1: BigInteger, n2: BigInteger): Boolean {
return gcd(n1, n2) == BigInteger.ONE
}
/**
* from https://www.geeksforgeeks.org/euclidean-algorithms-basic-and-extended/
* @param a a non null positive big integer
* @param b a non null positive big integer
* @return greatest common divisor between a and b
*/
fun gcd(a: BigInteger, b: BigInteger): BigInteger {
return if (a == BigInteger.ZERO) b else gcd(b % a, a)
}
/**
* @param n1 a non null positive big integer
* @param n2 a non null positive big integer
* @return least common multiple between n1 and n2
*/
fun lcm(n1: BigInteger, n2: BigInteger): BigInteger {
return n1.multiply(n2).divide(gcd(n1, n2))
}
/**
* Returns modulo inverse of 'a' with respect to 'm' using extended Euclid
* Algorithm Assumption: 'a' and 'm' are coprimes
* from https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
*
* @param a non null positive big integer
* @param m non null positive big integer
*/
fun modInverse(a: BigInteger, m: BigInteger): BigInteger {
// note: mapping to rsa: a = e, m= y, result = d
var a1 = a
var m1 = m
val m0 = m1
var y = BigInteger.ZERO
var x = BigInteger.ONE
if (m1 == BigInteger.ONE) return BigInteger.ZERO
while (a1 > BigInteger.ONE) {
// q is the quotient
val q = a1 / m1
var t = m1
// m is the remainder now, process same as Euclid's algo
m1 = a1 % m1
a1 = t
t = y
// Update x and y
y = x - q * y
x = t
}
// Make x positive
if (x < BigInteger.ZERO) x += m0
return x
}
/**
* Naive approach to factorize a number.
* Note that this does not always return all factors, but a set such that
* each element of the set may be a factor multiple times
* and/or the last factor is obtained from the set as n/prod(set)
*
* @param n non null positive big integer
* @return set of factors
*/
fun factorize(n: BigInteger): Set<BigInteger> {
val set = mutableSetOf<BigInteger>()
// first test 2 and 3
if (n % BigInteger("2") == BigInteger.ZERO) set.add(BigInteger("2")) // for some reason BigInteger.TWO does not work with shadowjar
if (n % BigInteger("3") == BigInteger.ZERO) set.add(BigInteger("3"))
// use 6k+1 rule
var i = BigInteger("5")
while (i*i <= n) {
if (n%i == BigInteger.ZERO) {
set.add(i)
}
if (n%(i+ BigInteger("2")) == BigInteger.ZERO) {
set.add(i+ BigInteger("2"))
}
i += BigInteger("6")
}
return set
}
/**
* Return a list of all the prime factors of n
*
* @param n non null positive big integer
* @return list of prime factors (may be repated)
*/
fun factorizeFull(n: BigInteger): List<BigInteger> {
val list = mutableListOf<BigInteger>()
val set = factorize(n)
list.addAll(set)
val prod = set.reduce { acc, bigInteger -> acc*bigInteger }
var residual = n / prod
while (residual > BigInteger.ONE) {
set.forEach{
while (residual % it == BigInteger.ZERO) {
list.add(it)
residual /= it
}
}
if (residual.isPrime()) {
list.add(residual)
break
}
}
return list
} | [
{
"class_path": "Kraktun__java_web_frameworks_cmp__28c5739/it/unipd/stage/sl/lib/rsa/RsaUtilsKt.class",
"javap": "Compiled from \"RsaUtils.kt\"\npublic final class it.unipd.stage.sl.lib.rsa.RsaUtilsKt {\n public static final boolean isPrime(java.math.BigInteger);\n Code:\n 0: aload_0\n 1: ld... |
coil-kt__coil__75ed843/internal/test-utils/src/commonMain/kotlin/coil3/test/utils/maths.kt | package coil3.test.utils
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sqrt
/**
* Returns the cross correlation between two arrays.
*
* https://en.wikipedia.org/wiki/Cross-correlation
*/
fun crossCorrelation(x: IntArray, y: IntArray): Double {
require(x.count() == y.count()) { "Input arrays must be of equal size." }
val xVar = x.variance()
val yVar = y.variance()
val squaredVariance = sqrt(xVar * yVar)
val xAvg = x.average()
val yAvg = y.average()
val count = x.count()
var sum = 0.0
for (index in 0 until count) {
sum += (x[index] - xAvg) * (y[index] - yAvg)
}
return sum / count / squaredVariance
}
/**
* Returns the cross correlation between two arrays.
*
* https://en.wikipedia.org/wiki/Cross-correlation
*/
fun crossCorrelation(x: ByteArray, y: ByteArray): Double {
require(x.count() == y.count()) { "Input arrays must be of equal size." }
val xVar = x.variance()
val yVar = y.variance()
val squaredVariance = sqrt(xVar * yVar)
val xAvg = x.average()
val yAvg = y.average()
val count = x.count()
var sum = 0.0
for (index in 0 until count) {
sum += (x[index] - xAvg) * (y[index] - yAvg)
}
return sum / count / squaredVariance
}
/**
* Returns an average value of elements in the array.
*/
fun IntArray.variance(): Double {
if (isEmpty()) return Double.NaN
val average = average()
return sumOf { (it - average).pow(2) } / count()
}
/**
* Returns an average value of elements in the array.
*/
fun ByteArray.variance(): Double {
if (isEmpty()) return Double.NaN
val average = average()
return sumOf { (it - average).pow(2) } / count()
}
/**
* Round the given value to the nearest [Double] with [precision] number of decimal places.
*/
fun Double.round(precision: Int): Double {
val multiplier = 10.0.pow(precision)
return (this * multiplier).roundToInt() / multiplier
}
| [
{
"class_path": "coil-kt__coil__75ed843/coil3/test/utils/MathsKt.class",
"javap": "Compiled from \"maths.kt\"\npublic final class coil3.test.utils.MathsKt {\n public static final double crossCorrelation(int[], int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String x\n ... |
JIghtuse__simple-search-engine-hyperskill__4634a62/src/search/Main.kt | package search
import java.io.File
import java.lang.IllegalArgumentException
typealias Dataset = List<String>
typealias InvertedIndex = Map<String, List<Int>>
fun toLowercaseWords(s: String) = s.split(" ").map(String::lowercase)
fun ask(prompt: String): String {
println(prompt)
return readln()
}
fun scanInputFile(filePath: String): Pair<Dataset, InvertedIndex> {
val lines = mutableListOf<String>()
val invertedIndex = mutableMapOf<String, MutableList<Int>>()
var lineIndex = 0
val file = File(filePath)
file.forEachLine {
lines.add(it)
for (word in toLowercaseWords(it).filter(String::isNotEmpty)) {
val positions = invertedIndex.getOrDefault(word, mutableListOf())
positions.add(lineIndex)
invertedIndex[word] = positions
}
lineIndex += 1
}
return lines to invertedIndex
}
fun printPeople(dataset: Dataset) {
println("=== List of people ===")
dataset.forEach(::println)
}
fun reportResult(matchedItems: Dataset) {
if (matchedItems.isNotEmpty()) {
println("${matchedItems.size} persons found:")
printPeople(matchedItems)
} else {
println("No matching people found.")
}
}
enum class MatchOption {
ALL,
ANY,
NONE,
}
fun toMatchOption(s: String): MatchOption {
return MatchOption.valueOf(s.uppercase())
}
class Searcher(private val dataset: Dataset, private val invertedIndex: InvertedIndex) {
fun search(query: String, matchOption: MatchOption): Dataset {
return when (matchOption) {
MatchOption.ALL -> ::searchAll
MatchOption.ANY -> ::searchAny
MatchOption.NONE -> ::searchNone
}(toLowercaseWords(query))
}
private fun searchAny(queryWords: List<String>): Dataset {
return queryWords.flatMap { word ->
invertedIndex
.getOrDefault(word, mutableListOf())
.map { dataset[it] }
}
}
private fun searchAll(queryWords: List<String>): Dataset {
if (queryWords.isEmpty()) return listOf()
return queryWords
.map { word ->
invertedIndex
.getOrDefault(word, mutableListOf())
.toSet()
}
.reduce { acc, indices -> acc.intersect(indices) }
.map { dataset[it] }
}
private fun searchNone(queryWords: List<String>): Dataset {
if (queryWords.isEmpty()) return dataset
val allIndices = (0..dataset.lastIndex)
val anyIndices = queryWords
.flatMap { word ->
invertedIndex
.getOrDefault(word, mutableListOf())
}
.toSet()
return allIndices
.subtract(anyIndices)
.map { dataset[it] }
}
}
fun createSearcherAndDataset(dataFilePath: String): Pair<Searcher, Dataset> {
val (dataset, invertedIndex) = scanInputFile(dataFilePath)
return Searcher(dataset, invertedIndex) to dataset
}
fun matchOptionToQueryPrompt(matchOption: MatchOption): String {
return when (matchOption) {
MatchOption.NONE -> "Enter a name or email to search none matching people."
MatchOption.ANY -> "Enter a name or email to search any matching people."
MatchOption.ALL -> "Enter a name or email to search all matching people."
}
}
fun searchAndReportResult(searcher: Searcher) {
val matchOption = toMatchOption(ask("Select a matching strategy: ALL, ANY, NONE"))
val query = ask(matchOptionToQueryPrompt(matchOption))
val matchedItems = searcher.search(query, matchOption)
reportResult(matchedItems)
}
data class MenuItem(val name: String, val action: () -> Unit)
class Menu(exitItemNumber: Int, private val items: Map<Int, MenuItem>) {
private val exitItem = exitItemNumber.toString()
init {
require(!items.containsKey(exitItemNumber))
}
val prompt = buildString {
append("=== Menu ===")
append("\n")
items
.entries
.forEach { command ->
append("${command.key}. ${command.value.name}")
append("\n")
}
append("$exitItem. Exit")
append("\n")
}
fun run(userChoice: String): Boolean {
if (userChoice == exitItem) {
return false
}
try {
val menuIndex = userChoice.toInt()
require(items.containsKey(menuIndex))
items[menuIndex]!!.action()
} catch (e: IllegalArgumentException) {
println("Incorrect option! Try again.")
}
return true
}
}
fun main(args: Array<String>) {
require(args.size == 2)
require(args[0] == "--data")
val (searcher, dataset) = createSearcherAndDataset(args[1])
val menu = Menu(
0,
mapOf(
1 to MenuItem("Find a person") { searchAndReportResult(searcher) },
2 to MenuItem("Print all people") { printPeople(dataset) })
)
while (true) {
val moreToRun = menu.run(ask(menu.prompt))
if (!moreToRun) break
}
println("Bye!")
}
| [
{
"class_path": "JIghtuse__simple-search-engine-hyperskill__4634a62/search/MainKt$WhenMappings.class",
"javap": "Compiled from \"Main.kt\"\npublic final class search.MainKt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 ... |
kevinvanleer__cyclotrack__c936057/app/src/main/java/com/kvl/cyclotrack/Statistics.kt | package com.kvl.cyclotrack
import kotlin.math.pow
fun List<Double>.average(): Double =
this.reduce { acc, d -> acc + d } / this.size
fun average(newValue: Double, sampleSize: Int, lastAverage: Double): Double =
(lastAverage * (sampleSize - 1) + newValue) / sampleSize
fun List<Double>.sampleVariance(): Double {
val avg = this.average()
return this.fold(0.0, { acc, d -> acc + (d - avg).pow(2.0) }) / (this.size - 1)
}
fun sampleVariance(
newValue: Double,
oldVariance: Double,
sampleSize: Int,
oldAverage: Double,
): Double {
return (oldVariance * (sampleSize - 2) / (sampleSize - 1)) + ((newValue - oldAverage).pow(
2.0) / sampleSize)
}
fun List<Double>.populationVariance(): Double {
val avg = this.average()
return this.fold(0.0, { acc, d -> acc + (d - avg).pow(2.0) }) / this.size
}
fun exponentialSmoothing(alpha: Double, current: Double, last: Double) =
(alpha * current) + ((1 - alpha) * last)
fun doubleExponentialSmoothing(
alpha: Double,
current: Double,
smoothLast: Double,
trendLast: Double,
) =
alpha * current + ((1 - alpha) * (smoothLast + trendLast))
fun doubleExponentialSmoothingTrend(
beta: Double,
smooth: Double,
smoothLast: Double,
trendLast: Double,
) =
beta * (smooth - smoothLast) + (1 - beta) * trendLast
fun smooth(alpha: Double, data: Array<Pair<Double, Double>>): List<Pair<Double, Double>> {
var smoothedFirst = data[0].first
var smoothedSecond = data[0].second
return data.map { datum ->
smoothedFirst = exponentialSmoothing(alpha, datum.first, smoothedFirst)
smoothedSecond = exponentialSmoothing(alpha, datum.second, smoothedSecond)
Pair(smoothedFirst, smoothedSecond)
}
}
fun doubleSmooth(alpha: Double, beta: Double, data: Array<Double>): List<Double> {
var smoothed: Double = data[0]
var trend: Double = data[1] - data[0]
var smoothedLast = smoothed
return data.map { datum ->
smoothed = doubleExponentialSmoothing(alpha, datum, smoothedLast, trend)
trend = doubleExponentialSmoothingTrend(beta, smoothed, smoothedLast, trend)
smoothedLast = smoothed
smoothed
}
}
fun isRangeGreaterThan(left: Pair<Double, Double>, right: Double): Boolean {
val leftRange = Pair(left.first - left.second, left.first + left.second)
return leftRange.first > right
}
fun isRangeLessThan(left: Pair<Double, Double>, right: Double): Boolean {
val leftRange = Pair(left.first - left.second, left.first + left.second)
return leftRange.second < right
}
fun isRangeGreaterThan(left: Pair<Double, Double>, right: Pair<Double, Double>): Boolean {
val leftRange = Pair(left.first - left.second, left.first + left.second)
val rightRange = Pair(right.first - right.second, right.first + right.second)
return leftRange.first > rightRange.second
}
fun isRangeLessThan(left: Pair<Double, Double>, right: Pair<Double, Double>): Boolean {
val leftRange = Pair(left.first - left.second, left.first + left.second)
val rightRange = Pair(right.first - right.second, right.first + right.second)
return leftRange.second < rightRange.first
}
fun leastSquaresFitSlope(data: List<Pair<Double, Double>>): Double {
//https://stats.libretexts.org/Bookshelves/Introductory_Statistics/Book%3A_Introductory_Statistics_(Shafer_and_Zhang)/10%3A_Correlation_and_Regression/10.04%3A_The_Least_Squares_Regression_Line
var sumx = 0.0
var sumy = 0.0
var sumxsq = 0.0
var sumxy = 0.0
data.forEach {
sumx += it.first
sumy += it.second
sumxsq += it.first * it.first
sumxy += it.first * it.second
}
val ssxy = sumxy - ((1.0 / data.size) * sumx * sumy)
val ssxx = sumxsq - ((1.0 / data.size) * sumx * sumx)
return ssxy / ssxx
}
fun accumulateAscentDescent(elevationData: List<Pair<Double, Double>>): Pair<Double, Double> {
var totalAscent = 0.0
var totalDescent = 0.0
var altitudeCursor = elevationData[0]
elevationData.forEach { sample ->
if (isRangeGreaterThan(sample, altitudeCursor)) {
totalAscent += sample.first - altitudeCursor.first
altitudeCursor = sample
}
if (isRangeLessThan(sample, altitudeCursor)) {
totalDescent += sample.first - altitudeCursor.first
altitudeCursor = sample
}
}
return Pair(totalAscent, totalDescent)
} | [
{
"class_path": "kevinvanleer__cyclotrack__c936057/com/kvl/cyclotrack/StatisticsKt.class",
"javap": "Compiled from \"Statistics.kt\"\npublic final class com.kvl.cyclotrack.StatisticsKt {\n public static final double average(java.util.List<java.lang.Double>);\n Code:\n 0: aload_0\n 1: ldc ... |
wdfHPY__kotlinStudy__d879b02/协程/collection/CollectionComparable.kt | package com.lonbon.kotlin.collection
/**
* 排序 Comparable.
* 1. 存在自然排序。针对一个类需要自然排序的话,那么需要实现的Comparable接口。并且实现Comparable接口。
* 2.
*/
class CollectionComparable {
}
fun main() {
/* val v1 = Version(1, 2)
val v2 = Version(2, 1)
println(v1 > v2)*/
collectionPolymerization()
}
/**
* 定义自然排序的话 -> 正值表示大
* 负值表示小
* 0 代表两个对象相等
*/
data class Version(
val majorVersion: Int,
val subVersion: Int
) : Comparable<Version> {
/**
* 实现Comparable来定义自然顺序。
*/
override fun compareTo(other: Version): Int {
if (this.majorVersion != other.majorVersion) {
return this.majorVersion - this.majorVersion
} else if (this.subVersion != other.subVersion) {
return this.subVersion - other.subVersion
} else {
return 0
}
}
}
/*
* 定义非自然顺序。
* 当不可以为类来定义自然顺序的时候,此时需要定义一个非自然的顺序。
* */
fun notNatureComparable() {
/**
* 定义一个比较器。Comparator()并且实现compareTo()方法。
*/
val comparator = Comparator<String> { t, t2 ->
t.length - t2.length
}
val list = listOf("aaa", "bb", "c")
//可以调用kotlin的sortedWith方法。传入了一个Comparator即可。
println(list.sortedWith(comparator).joinToString())
//如果想快速定义一个的Comparator对象的话,可以使用 compareBy方法。该方法可以快速的定义出一个Comparator对象。
//定义comparator对象时,需要标注其类型。
val comparator2 = compareBy<String> {
it.length
}
}
fun collectionSort() {
val list = listOf(1, 2, 3, 4, 5)
val listVersion = listOf(
Version(1, 1),
Version(1, 2),
Version(2, 3),
Version(2, 1)
)
println(list.sorted())
println(list.sortedDescending())
println(listVersion.sortedDescending())
println(listVersion.sortedDescending())
/**
* sorted()和sortedDescending() 两个函数。可以针对存在自然排序的集合进行排序。
* sorted() 是自然排序的正序。sortedDescending()是自然排序的倒序。
*/
/**
* 自定义排序规则。通常存在两个函数sortedBy()
*/
val listNumber = listOf("one", "two", "three", "four", "five")
//sortedBy的底层还是调用sortedWith(comparableBy{})
println(listNumber.sortedBy {
it.length
}.joinToString())
println(listNumber.sortedByDescending {
it.length
}.joinToString())
//sortWith可以使用自己的提供的Comparator
}
/**
* 集合的倒序。kotlin
* 1. reversed() 创建一个集合的副本,其中的元素的是接受者排序的逆序。
* 2. asReversed()
* 3. reverse() 将集合逆转。
*/
fun collectionReversed() {
val list = mutableListOf(1, 2, 3, 4, 5, 6)
val reverse = list.reversed()
val reverse2 = list.asReversed()
list.add(7)
println(reverse) //由于是创建的副本的,所以那么原Collection的更改不会影响到新的倒序的Collection
println(reverse2) //asRevered和reversed不相同。这个函数是针对引用来。原Collection的变化可以导致新的Collection变化。
println(list.joinToString())
}
/**
* shuffled洗牌算法。
*/
fun collectionShuffled() {
val list = listOf(1, 2, 3, 4, 5)
//list.shuffled()同样是创建集合的副本然后执行洗牌
println(list.shuffled())
}
/*
* 集合的聚合操作: 按照某一种规则将集合聚合成一个值。
* */
fun collectionPolymerization() {
val list = listOf(1, 543, 6, 89)
val min = list.min() //最小值
val max = list.max()
val average = list.average()
val sum = list.sum()
println(min)
println(max)
println(average)
println(sum)
//更高级的sum求和函数sumBy() .在集合的基础上调用上it函数
println(list.sumBy {
it * 2
})
println(list.sumByDouble {
it.toDouble() / 2
})
val numbers = listOf<Int>(1, 2, 3, 4)
val sum2 =
numbers.reduce { sum, element -> sum + element } // s = 5 T = 2、10、4 -> 5 + 2 -> 7 + 10 -> 17 + 4 = 21
val sum3 = numbers.fold(0) { sum, ele ->
sum + ele * 2 // 0 + 5 + 2 + 10 + 4 ->
}
/**
* reduce的初始值是第一个元素。在第一个元素的基础上,一直向后进行迭代调用值来调用相对应的方法。
* 在对元素进行reduce的时候,此时如果集合为空的集合,那么此时会产生异常。
* 而 fold的初始化的不是第一个元素,而是另外提供的一个初始化值。包括第一个值内一次和初始化做一定的操作。
* 当list为空的时候,此时不会产生异常,会返回初始值。
*/
println(sum2)
println(sum3)
//fold 和 reduce 默认都是从集合的 left -> right。如何需要从集合的右侧开始进行规约。 foldRight() 或者 reduceRight()
//通过查看源码发现。参数的顺序产生变化。第二个参数变成累加值。
val sum4 = numbers.foldRight(0) { sum, ele ->
ele + sum * 2 // 0 + 5 + 2 + 10 + 4 ->
}
//如果需要加上针对Index的判断的话,那么也存在函数
val sum5 = numbers.foldIndexed(0) { index, sum, ele ->
if (index % 2 == 0)
sum + ele
else
sum + ele * 2
//0 + 1 + 4 + 3 + 8
}
println(sum4)
println(sum5)
} | [
{
"class_path": "wdfHPY__kotlinStudy__d879b02/com/lonbon/kotlin/collection/CollectionComparable.class",
"javap": "Compiled from \"CollectionComparable.kt\"\npublic final class com.lonbon.kotlin.collection.CollectionComparable {\n public com.lonbon.kotlin.collection.CollectionComparable();\n Code:\n ... |
daf276__AdventOfCode__d397cfe/2021/src/main/kotlin/aoc/day2.kt | package aoc.day2
sealed class Instruction {
data class FORWARD(val value: Int) : Instruction()
data class DOWN(val value: Int) : Instruction()
data class UP(val value: Int) : Instruction()
}
fun parseInstructions(input: List<String>): List<Instruction> =
input.map { it.split(" ") }.map { (instruction, value) ->
when (instruction) {
"forward" -> Instruction.FORWARD(value.toInt())
"down" -> Instruction.DOWN(value.toInt())
"up" -> Instruction.UP(value.toInt())
else -> throw Exception("This when is exhaustive")
}
}
fun part1(input: List<Instruction>): Int {
val (pos, depth) = input.fold(Pair(0, 0)) { sum, add ->
when (add) {
is Instruction.FORWARD -> sum.copy(first = sum.first + add.value)
is Instruction.DOWN -> sum.copy(second = sum.second + add.value)
is Instruction.UP -> sum.copy(second = sum.second - add.value)
}
}
return pos * depth
}
fun part2(input: List<Instruction>): Int {
val (pos, depth, aim) = input.fold(Triple(0, 0, 0)) { sum, add ->
when (add) {
is Instruction.FORWARD -> sum.copy(
first = sum.first + add.value,
second = sum.second + sum.third * add.value
)
is Instruction.DOWN -> sum.copy(third = sum.third + add.value)
is Instruction.UP -> sum.copy(third = sum.third - add.value)
}
}
return pos * depth
}
| [
{
"class_path": "daf276__AdventOfCode__d397cfe/aoc/day2/Day2Kt.class",
"javap": "Compiled from \"day2.kt\"\npublic final class aoc.day2.Day2Kt {\n public static final java.util.List<aoc.day2.Instruction> parseInstructions(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc ... |
swstack__algo-expert-solutions__3ddad97/src/main/kotlin/algo/expert/solutions/medium/MinCoinsForChange.kt | package algo.expert.solutions.medium
import java.lang.Integer.min
// Solution: Dynamic programming
fun minNumberOfCoinsForChange(n: Int, denoms: List<Int>): Int {
val coins = IntArray(n + 1) { -1 }
coins[0] = 0
for (d in denoms.sorted()) {
for (i in 1 until coins.size) {
if (d <= i) {
val remaining = i - d
val remainingCoins = coins[remaining]
if (remainingCoins != -1) {
if (coins[i] == -1) {
coins[i] = 1 + remainingCoins
} else {
coins[i] = min(coins[i], 1 + remainingCoins)
}
}
}
}
}
return coins[n]
}
// Solution: Build a tree of all possible combinations -- very inefficient
class TreeNode(var value: Int) {
var children: MutableList<TreeNode> = mutableListOf()
}
fun minNumberOfCoinsForChangeTreeNaive(n: Int, denoms: List<Int>): Int {
val root = buildTree(TreeNode(n), denoms)
val shortest = findShortestBranchEqualToZero(root, 0)
return shortest
}
fun buildTree(node: TreeNode, denoms: List<Int>): TreeNode {
for (d in denoms) {
if (node.value - d >= 0) {
node.children.add(TreeNode(node.value - d))
}
}
for (c in node.children) {
buildTree(c, denoms)
}
return node
}
fun findShortestBranchEqualToZero(node: TreeNode, depth: Int): Int {
if (node.value == 0) {
return depth
}
if (node.children.isEmpty()) {
return Integer.MAX_VALUE
}
val lengths = mutableListOf<Int>()
for (c in node.children) {
lengths.add(findShortestBranchEqualToZero(c, depth + 1))
}
return lengths.min()!!
}
// Solution: Build optimized tree (without using actual tree data structure)
// - Build out the tree breadth-first
// - Stop on the first branch to equal 0 instead of building out the entire tree
// - Stop building branches < 0
fun minNumberOfCoinsForChangeTreeOptimized(n: Int, denoms: List<Int>): Int {
return treeOptimizedHelper(listOf(n), denoms, 1)
}
fun treeOptimizedHelper(row: List<Int>, denoms: List<Int>, depth: Int): Int {
if (row.isEmpty()) {
return Integer.MAX_VALUE
}
val nextRow = mutableListOf<Int>()
for (node in row) {
for (d in denoms) {
if (node - d == 0) {
return depth
}
if (node - d > 0) {
nextRow.add(node - d)
}
}
}
return treeOptimizedHelper(nextRow, denoms, depth + 1)
} | [
{
"class_path": "swstack__algo-expert-solutions__3ddad97/algo/expert/solutions/medium/MinCoinsForChangeKt.class",
"javap": "Compiled from \"MinCoinsForChange.kt\"\npublic final class algo.expert.solutions.medium.MinCoinsForChangeKt {\n public static final int minNumberOfCoinsForChange(int, java.util.List<j... |
ajoz__kotlin-workshop__49ba07d/aoc2016/src/main/kotlin/io/github/ajoz/sequences/Sequences.kt | package io.github.ajoz.sequences
/**
* Returns a sequence containing the results of applying the given [transform] function to each element in the original
* sequence and the result of previous application. For the case of first element in the sequence the [initial] value
* will be used as the "previous result" and passed to [transform] function.
* @param initial Initial element from which the scan should take place.
* @param transform Two argument function used to perform scan operation.
*/
fun <T, R> Sequence<T>.scan(initial: R, transform: (R, T) -> R): Sequence<R> {
return TransformingScanSequence(this, initial, transform)
}
/**
* A sequence which returns the results of applying the given [transformer] function to the values in the underlying
* [sequence]. Each [transformer] is given a previously calculated value and a new value. In case of the first element
* of the given [sequence] the [transformer] function will use [initial] as the "previously calculated value".
*/
internal class TransformingScanSequence<T, R>
constructor(private val sequence: Sequence<T>,
private val initial: R,
private val transformer: (R, T) -> R) : Sequence<R> {
override fun iterator(): Iterator<R> = object : Iterator<R> {
val iterator = sequence.iterator()
var previous = initial
override fun next(): R {
val mapped = transformer(previous, iterator.next())
previous = mapped
return mapped
}
override fun hasNext(): Boolean {
return iterator.hasNext()
}
}
}
/**
* Returns first repeated element in the [Sequence]. Can throw a [NoSuchElementException] if the [Sequence] doesn't have
* elements or there are no repeating elements
*/
fun <T> Sequence<T>.firstRepeated(): T {
val set = HashSet<T>()
for (element in this) {
if (set.contains(element)) return element
else set.add(element)
}
throw NoSuchElementException("Sequence contains no repeating elements")
}
| [
{
"class_path": "ajoz__kotlin-workshop__49ba07d/io/github/ajoz/sequences/SequencesKt.class",
"javap": "Compiled from \"Sequences.kt\"\npublic final class io.github.ajoz.sequences.SequencesKt {\n public static final <T, R> kotlin.sequences.Sequence<R> scan(kotlin.sequences.Sequence<? extends T>, R, kotlin.j... |
keivanshamlu__All-cities__631b1d7/utility/bases/src/main/java/com/shamlou/bases/dataStructure/RadixTree.kt | package com.shamlou.bases.dataStructure
import java.util.*
/**
* (In the following comparisons, it is assumed that the keys are of length k
* and the data structure contains n members.)
*/
class RadixTree<T>(private val root: Node<T> = Node(false)) {
/**
* checks whether tree is empty or not
*/
fun isEmpty(): Boolean = root.edges.isEmpty()
/**
* compare two strings and will return first index which two strings differ
*/
private fun getFirstMismatchLetter(word: String, edgeWord: String): Int {
for (i in 1 until word.length.coerceAtMost(edgeWord.length)) {
if (word[i] != edgeWord[i]) return i
}
return NO_MISMATCH
}
/**
* get list of objects and will insert them all into radix tree
*/
fun insertAll(items : List<Item<T>>){
items.map { insert(it) }
}
/**
* get an object and will insert it to radix tree
*/
fun insert(item: Item<T>) {
var current = root
var currIndex = 0
//Iterative approach
while (currIndex < item.label.length) {
val transitionChar = item.label.lowercase()[currIndex]
val curEdge = current.getTransition(transitionChar)
//Updated version of the input word
val currStr = item.label.lowercase().substring(currIndex)
//There is no associated edge with the first character of the current string
//so simply add the rest of the string and finish
if (curEdge == null) {
current.addEdge(transitionChar,Edge(currStr, Node(true, item)))
break
}
var splitIndex = getFirstMismatchLetter(currStr, curEdge.label)
if (splitIndex == NO_MISMATCH) {
//The edge and leftover string are the same length
//so finish and update the next node as a word node
if (currStr.length == curEdge.label.length) {
curEdge.next.isLeaf = true
curEdge.next.item = item
break
} else if (currStr.length < curEdge.label.length) {
//The leftover word is a prefix to the edge string, so split
val suffix = curEdge.label.substring(currStr.length)
curEdge.label = currStr
val newNext = Node<T>(true, item)
val afterNewNext = curEdge.next
curEdge.next = newNext
newNext.addEdge(suffix, afterNewNext)
break
} else {
//There is leftover string after a perfect match
splitIndex = curEdge.label.length
}
} else {
//The leftover string and edge string differed, so split at point
val suffix = curEdge.label.substring(splitIndex)
curEdge.label = curEdge.label.substring(0, splitIndex)
val prevNext = curEdge.next
curEdge.next = Node(false)
curEdge.next.addEdge(suffix, prevNext)
}
//Traverse the tree
current = curEdge.next
currIndex += splitIndex
}
}
/**
* searches for a prefix in radix tree
* first of all search for particular node and then calls [getAllChildren]
* and it will get all children of that node which is found data
*/
fun search(word: String): List<T> {
if(word.isEmpty())return emptyList()
var current = root
var currIndex = 0
while (currIndex < word.length) {
val transitionChar = word.lowercase()[currIndex]
val edge = current.getTransition(transitionChar) ?: kotlin.run {
return listOf()
}
currIndex += edge.label.length
current = edge.next
}
return current.getAllChildren(word.lowercase())
}
companion object {
private const val NO_MISMATCH = -1
}
}
/**
* represents edges of a node, containts the lable
* of edge and the node the edge is referring to
*/
class Edge<T>(var label: String, var next: Node<T>)
/**
* holds item and the key that radix tree works with
*/
class Item<T>(var label: String, var item: T)
/**
* represents node of the radix tree, contains group
* of edges that are hold a tree map so it's sorted
* alphanumeric all the time so whenever we call [getAllChildren]
* we get a list of <T> which is in alphanumeric order
*/
class Node<T>(var isLeaf: Boolean, var item: Item<T>? = null) {
// i used TreeMap so it can keep everything sorted
var edges: TreeMap<Char, Edge<T>> = TreeMap()
/**
* get the edge that a Char is referring in treemap
*/
fun getTransition(transitionChar: Char): Edge<T>? {
return edges[transitionChar]
}
/**
* adds a edge in edges treemap
*/
fun addEdge(label: String, next: Node<T>) {
edges[label[0]] = Edge(label, next)
}
/**
* adds a edge in edges treemap
*/
fun addEdge(char : Char , edge: Edge<T>){
edges[char] = edge
}
/**
* gets a node in radix tree and the prefix text of that node
* recursively calls itself until it reaches leaves and then
* it will add them to a list
*/
fun getAllChildren(tillNow: String): List<T> {
val list = mutableListOf<T>()
if (isLeaf && item?.label?.lowercase()?.startsWith(tillNow) == true && item?.item != null) {
item?.item?.let { return listOf(it) }
}
edges.map {
if (it.value.next.isLeaf) list.add(it.value.next.item!!.item)
else list.addAll(
it.value.next.getAllChildren(
StringBuilder()
.append(tillNow)
.append(it.value.label)
.toString()
)
)
}
return list
}
} | [
{
"class_path": "keivanshamlu__All-cities__631b1d7/com/shamlou/bases/dataStructure/RadixTree.class",
"javap": "Compiled from \"RadixTree.kt\"\npublic final class com.shamlou.bases.dataStructure.RadixTree<T> {\n public static final com.shamlou.bases.dataStructure.RadixTree$Companion Companion;\n\n private ... |
hasanhaja__UoB-Codefest__c4c84db/src/year2018/dec/level6/ktSolutions.kt | package year2018.dec.level6
fun ktchallenge1(s: String): Int {
val expression: List<String> = s.trim().split(" ")
return evaluate(expression)
}
private enum class Ops(val symbol: String) {
ADD("+"),
MINUS("-"),
MULTIPLY("*"),
DIVIDE("/"),
}
private fun evaluate(expression: List<String>): Int {
var total = 0
var currentOp = Ops.ADD
for (value in expression) {
try {
val current = value.toInt()
when (currentOp) {
Ops.ADD -> total += current
Ops.MINUS -> total -= current
Ops.MULTIPLY -> total *= current
Ops.DIVIDE -> total /= current
}
} catch (e: Exception) {
when (value) {
Ops.ADD.symbol -> currentOp = Ops.ADD
Ops.MINUS.symbol -> currentOp = Ops.MINUS
Ops.MULTIPLY.symbol -> currentOp = Ops.MULTIPLY
Ops.DIVIDE.symbol -> currentOp = Ops.DIVIDE
else -> e.printStackTrace()
}
}
}
return total
}
fun ktchallenge2(array: IntArray, a: Int): IntArray {
val result = IntArray(2)
for (i in 0 until array.size) {
for (j in i+1 until array.size) {
when (a) {
array[i] + array[j]-> {
result[0] = i
result[1] = j
}
}
}
}
return result
}
fun ktchallenge3(array1: IntArray, array2: IntArray): Int = (reverseArray(array1).sum() + reverseArray(array2).sum())
private fun reverseArray(array: IntArray): IntArray {
return array.
map { it.toString().reversed().toInt() }.
toIntArray()
}
fun <T> ktchallenge4(c: Class<T>, a: Double, b: Double): T? {
return null
}
fun ktchallenge5(s: String, a: Int): Int {
var text = s
// replace ops with op with spaces
// for this case only
text = text.replace("+", " + ")
// Index of "r" in return
val returnIndex = text.indexOf("return")
val semiIndex = text.indexOf(";")
// replace i with a (this will do it for all, but it doesn't matter
text = text.replace("i", a.toString())
val expression = text.slice(returnIndex+6 until semiIndex )
return ktchallenge1(expression)
} | [
{
"class_path": "hasanhaja__UoB-Codefest__c4c84db/year2018/dec/level6/KtSolutionsKt.class",
"javap": "Compiled from \"ktSolutions.kt\"\npublic final class year2018.dec.level6.KtSolutionsKt {\n public static final int ktchallenge1(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
mxrpr__learning__0082d8b/src/main/kotlin/leveinshtein.kt | package com.mxr.example
import kotlin.system.measureNanoTime
/**
* For learning purposes
*
* Two solutions:
* 1. create Leveinshtein class
* 2. extend CharSequence functionality
*/
class Leveinshtein {
fun leveinshteinDistance(lhs: String, rhs: String): Int {
if (lhs === rhs) return 0
if (lhs.isEmpty()) return rhs.length
if (rhs.isEmpty()) return lhs.length
val res = Array(lhs.length){ IntArray(rhs.length)}
for (i in 0 until lhs.length)
res[i][0] = i
for (j in 0 until rhs.length)
res[0][j] = j
var subst = 0
for (j in 1 until rhs.length) {
for (i in 1 until lhs.length) {
subst = if (lhs[i] == rhs[j]) 0 else 1
val deletion = res[i-1][j] + 1
val insertion = res[i][j-1] +1
val substitution = res[i-1][j-1] + subst
res[i][j] = Math.min(Math.min(deletion, insertion), substitution)
}
}
return res[lhs.length-1][rhs.length-1]
}
private fun cost(a: Char, b: Char ): Int = if (a == b) 0 else 1
}
/**
* Extend the CharSequence
*/
fun CharSequence.leveinshtein(lhs: String): Int{
if (this === lhs) return 0
if (lhs.isEmpty()) return this.length
if (this.isEmpty()) return lhs.length
val res = Array(lhs.length){ IntArray(this.length)}
for (i in 0 until lhs.length)
res[i][0] = i
for (j in 0 until this.length)
res[0][j] = j
var subst = 0
for (j in 1 until this.length) {
for (i in 1 until lhs.length) {
subst = if (lhs[i] == this[j]) 0 else 1
val deletion = res[i-1][j] + 1
val insertion = res[i][j-1] +1
val substitution = res[i-1][j-1] + subst
res[i][j] = Math.min(Math.min(deletion, insertion), substitution)
}
}
return res[lhs.length-1][this.length-1]
}
fun main(args: Array<String>) {
val lev = Leveinshtein()
var time = measureNanoTime {
println(lev.leveinshteinDistance("rosettacode", "raisethysword"))
}
println("time: $time")
time = measureNanoTime {
println("rosettacode".leveinshtein("raisethysword"))
}
println("time: $time")
} | [
{
"class_path": "mxrpr__learning__0082d8b/com/mxr/example/LeveinshteinKt.class",
"javap": "Compiled from \"leveinshtein.kt\"\npublic final class com.mxr.example.LeveinshteinKt {\n public static final int leveinshtein(java.lang.CharSequence, java.lang.String);\n Code:\n 0: aload_0\n 1: ldc ... |
eniltonangelim__AlgorithmicToolbox__031bccb/src/main/kotlin/algorithmic_toolbox/week6/PlacingParentheses.kt | package algorithmic_toolbox.week6
import java.util.*
import kotlin.math.max
import kotlin.math.min
fun getMaximValue(exp: String): Long {
val n = exp.length / 2 + 1
var min = Array(n){ LongArray(n) }
var max = Array(n){ LongArray(n) }
for (i in 0 until n) {
min[i][i] = (exp[i * 2] - '0').toLong()
max[i][i] = (exp[i * 2] - '0').toLong()
}
for (s in 1 until n ) {
for (z in 0 .. n -1 -s) {
val j = s + z
val minAndMax = getMinAndMax(exp, z, j, min, max)
min[z][j] = minAndMax[0]
max[z][j] = minAndMax[1]
}
}
return max[0][n - 1]
}
fun getMinAndMax(exp: String, i: Int, j: Int,
w: Array<LongArray>, W: Array<LongArray> ): LongArray {
var minAndMax = longArrayOf(Long.MAX_VALUE, Long.MIN_VALUE)
for (k in i until j) {
val op = exp[k * 2 + 1]
val a = eval(w[i][k], w[k+1][j], op)
val b = eval(w[i][k], W[k+1][j], op)
val c = eval(W[i][k], w[k+1][j], op)
val d = eval(W[i][k], W[k+1][j], op)
minAndMax[0] = min(a, min(b, min(c, min(d, minAndMax[0]))))
minAndMax[1] = max(a, max(b, max(c, max(d, minAndMax[1]))))
}
return minAndMax
}
fun eval(a: Long, b: Long, op: Char): Long = when (op) {
'+' -> a + b
'-' -> a - b
'*' -> a * b
else -> {
assert(false)
0
}
}
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val exp = scanner.next()
println(getMaximValue(exp))
}
| [
{
"class_path": "eniltonangelim__AlgorithmicToolbox__031bccb/algorithmic_toolbox/week6/PlacingParenthesesKt.class",
"javap": "Compiled from \"PlacingParentheses.kt\"\npublic final class algorithmic_toolbox.week6.PlacingParenthesesKt {\n public static final long getMaximValue(java.lang.String);\n Code:\n... |
eniltonangelim__AlgorithmicToolbox__031bccb/src/main/kotlin/algorithmic_toolbox/week2/FibonnaciWarmup.kt | package algorithmic_toolbox.week2
import java.util.*
fun calcFib(n: Long): Long {
return if (n <= 1) n else calcFib(n - 1) + calcFib(n - 2)
}
fun power(n: Long, x: Int = 2): Long {
if (x == 0)
return n
return power(n * n, x - 1)
}
fun lastDigitOfNumber(n: Long): Long {
var fibAList = LongArray((n+1).toInt())
fibAList[0] = 0
fibAList[1] = 1
if ( n < 2) return n
for (i in 2..n) {
fibAList[i.toInt()] = (fibAList[(i-1).toInt()] + fibAList[(i-2).toInt()]) % 10
}
return fibAList[n.toInt()]
}
fun getPisanoPeriod(m: Long): Long {
var period = 0L
var previous = 0L
var current = 1L
for (i in 2 until m*m) {
val tmpPrevious = previous
previous = current
current = (tmpPrevious+current) % m
if (previous == 0L && current == 1L){
period = i - 1
break
}
}
return period
}
fun calcFibMod(n: Long, m: Long): Long {
if ( n <= 1)
return n
val pisanoPeriod = getPisanoPeriod(m)
val remainder = n % pisanoPeriod
var previous = 0L
var current = 1L
for (i in 0 until remainder-1) {
val tmpPrevious = previous
previous = current
current = (tmpPrevious+current) % m
}
return current % m
}
fun calcLastDigitOfTheSumFibonacci(n: Long): Long {
if (n <= 2) return n
var fibAList = LongArray((n + 1).toInt())
fibAList[0] = 0L
fibAList[1] = 1L
for (i in 2..n) {
fibAList[i.toInt()] = (fibAList[(i - 1).toInt()] + fibAList[(i - 2).toInt()]) % 10
}
return fibAList.sum() % 10
}
fun calcLastDigitOfTheSumFibonacci(m: Long, n: Long): Long {
val pisanoPeriod = 60 // pisanoPeriod(10) = 60
var fibAList = LongArray(pisanoPeriod - 1)
fibAList[0] = 0L
fibAList[1] = 1L
for (i in 2 until pisanoPeriod - 1) {
fibAList[i] = (fibAList[i-1] + fibAList[i-2]) % 10
}
var begin = m % pisanoPeriod
var end = n % pisanoPeriod
if (end < begin) end += pisanoPeriod
var result = 0L
for (i in begin..end) {
result += fibAList[(i % pisanoPeriod).toInt()]
}
return result % 10
}
fun calcLastDigitOfTheSumOfSquaresFibonacci(n: Long): Long {
val pisanoPeriod = 60
val horizontal = lastDigitOfNumber((n +1) % pisanoPeriod)
val vertical = lastDigitOfNumber( n % pisanoPeriod)
return (horizontal * vertical) % 10
}
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val n = scanner.nextLong()
println(calcFib(n))
} | [
{
"class_path": "eniltonangelim__AlgorithmicToolbox__031bccb/algorithmic_toolbox/week2/FibonnaciWarmupKt.class",
"javap": "Compiled from \"FibonnaciWarmup.kt\"\npublic final class algorithmic_toolbox.week2.FibonnaciWarmupKt {\n public static final long calcFib(long);\n Code:\n 0: lload_0\n 1... |
HSAR__KotlinHeroes__69a1187/src/main/kotlin/io/hsar/practice3/ProblemE.kt | package io.hsar.practice3
/*
https://codeforces.com/contest/1298/problem/E
Input:
10 4
5 4 1 5 4 3 7 1 2 5
4 6
2 1
10 8
3 5
Output:
5 4 0 5 3 3 9 0 2 5
*/
fun findNumberOfValidMentees(skillsLookup: List<Pair<Int, Int>>, quarrelsLookup: Map<Int, Set<Int>>, skillLevel: Int, index: Int): Int {
var mentees = 0
skillsLookup
.forEach { (otherIndex, otherSkillLevel) ->
if (otherSkillLevel < skillLevel) {
if (!quarrelsLookup[index]!!.contains(otherIndex)) // not in quarrel
{
mentees++
}
} else {
return mentees
}
}
return mentees
}
fun main() {
val (numberOfProgrammers, numberOfQuarrels) = readLine()!!
.split(" ")
.map { it.toInt() }
.let { splitArray ->
splitArray[0] to splitArray[1]
}
val skillLevels = readLine()!!
.split(" ")
.map { it.toInt() }
val quarrels = (0 until numberOfQuarrels)
.map {
readLine()!!
.split(" ")
.map { it.toInt() }
}
val quarrelsLookup = List(numberOfProgrammers)
{ index -> index + 1 to mutableSetOf<Int>() }
.toMap()
// fill in quarrels
quarrels.forEach { quarrel ->
val personA = quarrel[0]
val personB = quarrel[1]
quarrelsLookup[personA]!!.add(personB)
quarrelsLookup[personB]!!.add(personA)
}
val skillsLookup = skillLevels
.mapIndexed { index, skillLevel ->
index + 1 to skillLevel
}
.sortedBy { (_, skillLevel) -> skillLevel }
val results = skillLevels
.mapIndexed { index, skillLevel ->
findNumberOfValidMentees(skillsLookup, quarrelsLookup, skillLevel, index + 1)
}
println(results.joinToString(" "))
} | [
{
"class_path": "HSAR__KotlinHeroes__69a1187/io/hsar/practice3/ProblemEKt.class",
"javap": "Compiled from \"ProblemE.kt\"\npublic final class io.hsar.practice3.ProblemEKt {\n public static final int findNumberOfValidMentees(java.util.List<kotlin.Pair<java.lang.Integer, java.lang.Integer>>, java.util.Map<ja... |
josue-lubaki__Rational__cbeb74d/src/ca/josue/rational/Rational.kt | package ca.josue.rational
import java.math.BigInteger
class Rational (private val numerator: BigInteger, private val denominator: BigInteger) : Comparable<Rational>{
init {
if (denominator == BigInteger.ZERO)
throw IllegalArgumentException("Denominator cannot be 0")
}
// Redefinition des opérateurs
operator fun plus(other: Rational): Rational {
val num = (numerator * other.denominator) + (denominator * other.numerator)
val den = denominator * other.denominator
return num.divBy(den)
}
operator fun minus(other: Rational) : Rational{
val num = (numerator * other.denominator) - (denominator * other.numerator)
val den = denominator * other.denominator
return num.divBy(den)
}
operator fun times(other: Rational): Rational{
return (numerator * other.numerator).divBy(denominator * other.denominator)
}
operator fun div(other: Rational):Rational{
return (numerator * other.denominator).divBy(denominator * other.numerator)
}
operator fun unaryMinus(): Rational = Rational(numerator.negate(),denominator)
override fun compareTo(other: Rational): Int {
return (numerator * other.denominator).compareTo(denominator * other.numerator)
}
private fun simplify(rational: Rational): Rational{
val greatCommonDivisor = rational.numerator.gcd(rational.denominator)
val num = rational.numerator / greatCommonDivisor
val den = rational.denominator / greatCommonDivisor
return Rational(num, den)
}
private fun formatRational(): String = "$numerator/$denominator"
override fun equals(other: Any?): Boolean {
if (this === other) return true
other as Rational
val thisSimplified = simplify(this)
val otherSimplified = simplify(other)
val thisAsDouble = thisSimplified.numerator.toDouble() / thisSimplified.denominator.toDouble()
val otherAsDouble = otherSimplified.numerator.toDouble() / otherSimplified.denominator.toDouble()
return thisAsDouble == otherAsDouble
}
override fun toString(): String {
val shouldBeOneNumber = denominator == BigInteger.ONE || numerator % denominator == BigInteger.ZERO
return when {
shouldBeOneNumber -> (numerator / denominator).toString()
else -> {
val thisSimplified = simplify(this)
if (thisSimplified.denominator < BigInteger.ZERO || (thisSimplified.numerator < BigInteger.ZERO && thisSimplified.denominator < BigInteger.ZERO)){
Rational(thisSimplified.numerator.negate(), thisSimplified.denominator.negate()).formatRational()
}
else{
Rational(thisSimplified.numerator, thisSimplified.denominator).formatRational()
}
}
}
}
override fun hashCode(): Int {
var result = numerator.hashCode()
result = 31 * result + denominator.hashCode()
return result
}
}
fun String.toRational():Rational{
val ratio = split('/')
return when (ratio.size) {
1 -> Rational(ratio[0].toBigInteger(), BigInteger.ONE)
2 -> Rational(ratio[0].toBigInteger(), ratio[1].toBigInteger())
else -> throw IllegalArgumentException("Invalid format")
}
}
// Infix
infix fun Int.divBy(other: Int):Rational = Rational(toBigInteger(), other.toBigInteger())
infix fun Long.divBy(other: Long): Rational = Rational(toBigInteger(), other.toBigInteger())
infix fun BigInteger.divBy(other: BigInteger) = Rational(this, other)
fun main() {
val half = 1 divBy 2
val third = 1 divBy 3
val sum: Rational = half + third
println(5 divBy 6 == sum)
val difference: Rational = half - third
println(1 divBy 6 == difference)
val product: Rational = half * third
println(1 divBy 6 == product)
val quotient: Rational = half / third
println(3 divBy 2 == quotient)
val negation: Rational = -half
println(-1 divBy 2 == negation)
println((2 divBy 1).toString() == "2")
println((-2 divBy 4).toString() == "-1/2")
println("117/1098".toRational().toString() == "13/122")
val twoThirds = 2 divBy 3
println(half < twoThirds)
println(half in third..twoThirds)
println(2000000000L divBy 4000000000L == 1 divBy 2)
println("912016490186296920119201192141970416029".toBigInteger() divBy
"1824032980372593840238402384283940832058".toBigInteger() == 1 divBy 2)
} | [
{
"class_path": "josue-lubaki__Rational__cbeb74d/ca/josue/rational/RationalKt.class",
"javap": "Compiled from \"Rational.kt\"\npublic final class ca.josue.rational.RationalKt {\n public static final ca.josue.rational.Rational toRational(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc ... |
jksolbakken__aoc2022__afc771f/src/main/kotlin/jks/Day2.kt | package jks
import java.io.File
import java.lang.RuntimeException
import jks.Item.PAPER
import jks.Item.ROCK
import jks.Item.SCISSORS
import jks.Result.DRAW
import jks.Result.LOSER
import jks.Result.WINNER
fun main() {
val uri = object {}::class.java.getResource("/day2_input")?.toURI()
?: throw RuntimeException("oh noes!")
val lines = File(uri).readLines()
val sumPart1 = lines
.map { chars -> Round(toItem(chars[0]), toItem(chars[2])) }
.map { round -> Pair(round, result(round)) }
.sumOf { (round, result) -> round.myItem.points + result.points }
println("Part 1: $sumPart1")
val sumPart2 = lines
.map { chars -> Pair(toItem(chars[0]), toResult(chars[2])) }
.map { Pair(it, itemForDesiredResult(it.first, it.second)) }
.sumOf { (othersItemAndResult, myItem) -> myItem.points + othersItemAndResult.second.points }
println("Part 2: $sumPart2")
}
data class Round(val opponentsItem: Item, val myItem: Item)
enum class Item(val points: Int){
ROCK(1),
PAPER(2),
SCISSORS(3)
}
enum class Result(val points: Int) {
WINNER(6),
DRAW(3),
LOSER(0)
}
private fun result(round: Round): Result = when (round) {
Round(ROCK, ROCK) -> DRAW
Round(ROCK, PAPER) -> WINNER
Round(ROCK, SCISSORS) -> LOSER
Round(PAPER, ROCK) -> LOSER
Round(PAPER, PAPER) -> DRAW
Round(PAPER, SCISSORS) -> WINNER
Round(SCISSORS, ROCK) -> WINNER
Round(SCISSORS, PAPER) -> LOSER
Round(SCISSORS, SCISSORS) -> DRAW
else -> throw RuntimeException("$round is not valid")
}
private fun toItem(c: Char) = when (c) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> throw RuntimeException("oh noes!")
}
private fun toResult(c: Char) = when (c) {
'X' -> LOSER
'Y' -> DRAW
'Z' -> WINNER
else -> throw RuntimeException("oh noes!")
}
private fun itemForDesiredResult(othersItem: Item, desiredResult: Result) = when {
desiredResult == DRAW -> othersItem
othersItem == ROCK && desiredResult == WINNER -> PAPER
othersItem == ROCK && desiredResult == LOSER -> SCISSORS
othersItem == PAPER && desiredResult == WINNER -> SCISSORS
othersItem == PAPER && desiredResult == LOSER -> ROCK
othersItem == SCISSORS && desiredResult == WINNER -> ROCK
othersItem == SCISSORS && desiredResult == LOSER -> PAPER
else -> throw RuntimeException("oh noes!")
}
| [
{
"class_path": "jksolbakken__aoc2022__afc771f/jks/Day2Kt.class",
"javap": "Compiled from \"Day2.kt\"\npublic final class jks.Day2Kt {\n public static final void main();\n Code:\n 0: new #8 // class jks/Day2Kt$main$uri$1\n 3: dup\n 4: invokespecial #11 ... |
klnusbaum__aoc2023__d30db24/src/problems/day2/daytwo.kt | package problems.day2
import java.io.File
private const val gamesFile = "input/day2/games.txt"
fun main() {
part1()
part2()
}
private data class Round(val red: Int, val green: Int, val blue: Int)
private data class Game(val id: Int, val rounds: List<Round>) {
fun allRedUnder(max: Int) = rounds.all { it.red <= max }
fun allGreenUnder(max: Int) = rounds.all { it.green <= max }
fun allBlueUnder(max: Int) = rounds.all { it.blue <= max }
fun power() = maxRed() * maxGreen() * maxBlue()
private fun maxRed() = rounds.maxOf { it.red }
private fun maxGreen() = rounds.maxOf { it.green }
private fun maxBlue() = rounds.maxOf { it.blue }
}
private fun part1() {
val idSum = File(gamesFile).bufferedReader().useLines { sumIDs(it) }
println("ID sum is $idSum")
}
private fun sumIDs(lines: Sequence<String>) =
lines.map { it.toGame() }
.filter { it.allRedUnder(12) and it.allGreenUnder(13) and it.allBlueUnder(14) }
.map { it.id }
.sum()
private fun String.toGame(): Game =
Game(
this.substringBefore(":").toGameID(),
this.substringAfter(":").toRounds(),
)
private fun String.toGameID(): Int = this.trim().removePrefix("Game ").toInt()
private fun String.toRounds(): List<Round> = this.trim().split(";").map { it.toRound() }
private fun String.toRound(): Round {
var red = 0
var green = 0
var blue = 0
this.split(",").map { it.trim() }.forEach {
val amount = it.substringBefore(" ").toInt()
when (it.substringAfter(" ")) {
"red" -> red = amount
"blue" -> blue = amount
"green" -> green = amount
}
}
return Round(red, green, blue)
}
private fun part2() {
val powerSum = File(gamesFile).bufferedReader().useLines { sumPower(it) }
println("Power sum is $powerSum")
}
private fun sumPower(lines: Sequence<String>) = lines.map { it.toGame().power() }.sum() | [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day2/DaytwoKt.class",
"javap": "Compiled from \"daytwo.kt\"\npublic final class problems.day2.DaytwoKt {\n private static final java.lang.String gamesFile;\n\n public static final void main();\n Code:\n 0: invokestatic #9 // ... |
klnusbaum__aoc2023__d30db24/src/problems/day1/dayone.kt | package problems.day1
import java.io.File
private const val calibrationValues = "input/day1/calibration_values.txt"
fun main() {
part1()
part2()
}
private fun part1() {
val sum = File(calibrationValues)
.bufferedReader()
.useLines { sumLines(it) }
println("Sum of values is $sum")
}
private fun sumLines(lines: Sequence<String>) = lines.map { parseLine(it) }.sum()
private fun parseLine(input: String): Int {
val numbers = input.filter { c -> c in '0'..'9' }
return "${numbers.first()}${numbers.last()}".toInt()
}
private fun part2() {
val sum = File(calibrationValues)
.bufferedReader()
.useLines { sumLinesV2(it) }
println("Sum of values is $sum")
}
private fun sumLinesV2(lines: Sequence<String>) = lines.map { parseLineV2(it) }.sum()
private fun parseLineV2(input: String): Int {
val first = input.findAnyOf(numTargets)?.second?.toNumString()
val last = input.findLastAnyOf(numTargets)?.second?.toNumString()
return "$first$last".toInt()
}
private val numTargets = listOf(
"1", "2", "3", "4", "5", "6", "7", "8", "9",
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
)
private fun String.toNumString() = when (this) {
"one" -> "1"
"two" -> "2"
"three" -> "3"
"four" -> "4"
"five" -> "5"
"six" -> "6"
"seven" -> "7"
"eight" -> "8"
"nine" -> "9"
else -> this
} | [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day1/DayoneKt.class",
"javap": "Compiled from \"dayone.kt\"\npublic final class problems.day1.DayoneKt {\n private static final java.lang.String calibrationValues;\n\n private static final java.util.List<java.lang.String> numTargets;\n\n public static... |
klnusbaum__aoc2023__d30db24/src/problems/day4/part1/part1.kt | package problems.day4.part1
import java.io.File
import kotlin.math.pow
//private const val testFile = "input/day4/test.txt"
private const val cardsFile = "input/day4/cards.txt"
fun main() {
val cardValueSum = File(cardsFile).bufferedReader().useLines { sumCardValues(it) }
println("Card Values Sum: $cardValueSum")
}
private fun sumCardValues(lines: Sequence<String>) = lines.map { it.toCard() }.sumOf { it.value() }
private fun String.toCard() = Card(
id = this.toCardID(),
winningNumbers = this.toWinningNumbers(),
possessedNumbers = this.toPossessedNumbers()
)
private fun String.toCardID(): Int = this.substringBefore(":").substringAfter(" ").trim().toInt()
private fun String.toWinningNumbers() =
this.substringAfter(":").substringBefore("|").trim().split(" ").filter { it != "" }.map { it.toInt() }
.toSet()
private fun String.toPossessedNumbers(): Set<Int> =
this.substringAfter("|").trim().split(" ").filter { it != "" }.map { it.trim().toInt() }.toSet()
private data class Card(val id: Int, val winningNumbers: Set<Int>, val possessedNumbers: Set<Int>) {
fun value(): Int = 2.0.pow(numMatching() - 1).toInt()
fun numMatching() = winningNumbers.intersect(possessedNumbers).count()
}
| [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day4/part1/Part1Kt.class",
"javap": "Compiled from \"part1.kt\"\npublic final class problems.day4.part1.Part1Kt {\n private static final java.lang.String cardsFile;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day3/part2/part2.kt | package problems.day3.part2
import java.io.File
//private const val testFile = "input/day3/test.txt"
private const val part_numbers = "input/day3/part_numbers.txt"
fun main() {
val gearRatioSum = File(part_numbers).bufferedReader().useLines { sumGearRatios(it) }
println("Part Number Sum: $gearRatioSum")
}
private fun sumGearRatios(lines: Sequence<String>): Int {
val possibleGears = mutableMapOf<Int, Map<Int, Int>>()
val stars = mutableMapOf<Int, Set<Int>>()
lines.forEachIndexed {row, line ->
val res = parseLine(line)
possibleGears[row] = res.possibleGears
stars[row] = res.stars
}
return stars.flatMap { it.value.toRowCols(it.key) }
.mapNotNull { it.gearRatio(possibleGears) }
.sum()
}
private fun parseLine(line: String) = LineResult(
accumulateNumbers(line),
recordStarts(line),
)
private data class LineResult(val possibleGears: Map<Int, Int>, val stars: Set<Int>)
private fun accumulateNumbers(line: String): Map<Int, Int> {
val accumulator = PossibleGearAccumulator()
line.forEach { accumulator.nextChar(it) }
return accumulator.end()
}
private fun recordStarts(line: String): Set<Int> {
val stars = mutableSetOf<Int>()
line.forEachIndexed { index, c -> if (c == '*') stars.add(index)}
return stars
}
private fun Pair<Int, Int>.gearRatio(possibleGears: Map<Int, Map<Int, Int>>) : Int? {
val adjacentNumbers = mutableSetOf<Int>()
for (i in this.first-1..this.first+1) {
for(j in this.second-1..this.second+1) {
val number = possibleGears[i]?.get(j)
if (number != null) {
adjacentNumbers.add(number)
}
}
}
if (adjacentNumbers.count() != 2) {
return null
}
return adjacentNumbers.fold(1) {acc, next -> acc * next}
}
private fun Set<Int>.toRowCols(row: Int): List<Pair<Int, Int>> = this.map {row to it}
private class PossibleGearAccumulator() {
private val possibleGears = mutableMapOf<Int,Int>()
private val currentNumber = StringBuilder()
private var currentCol = 0
private var currentStartCol = 0
private var currentEndCol = 0
private var currentState = State.OUT_NUMBER
private enum class State {
IN_NUMBER, OUT_NUMBER
}
fun nextChar(character: Char) {
when {
(character in '0'..'9') and (currentState == State.OUT_NUMBER) -> {
currentState = State.IN_NUMBER
currentNumber.append(character)
currentStartCol = currentCol
currentEndCol = currentCol
}
(character in '0'..'9') and (currentState == State.IN_NUMBER) -> {
currentNumber.append(character)
currentEndCol = currentCol
}
(character !in '0'..'9') and (currentState == State.IN_NUMBER) -> {
currentState = State.OUT_NUMBER
recordPossiblePN()
currentNumber.clear()
}
}
currentCol++
}
private fun recordPossiblePN() {
val number = currentNumber.toString().toInt()
for (i in currentStartCol..currentEndCol) {
possibleGears[i] = number
}
}
fun end(): Map<Int, Int> {
if (currentState == State.IN_NUMBER) {
recordPossiblePN()
}
return possibleGears
}
} | [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day3/part2/Part2Kt.class",
"javap": "Compiled from \"part2.kt\"\npublic final class problems.day3.part2.Part2Kt {\n private static final java.lang.String part_numbers;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day3/part1/part1.kt | package problems.day3.part1
import java.io.File
//private const val testFile = "input/day3/test.txt"
private const val part_numbers = "input/day3/part_numbers.txt"
fun main() {
val partNumberSum = File(part_numbers).bufferedReader().useLines { sumPartNumbers(it) }
println("Part Number Sum: $partNumberSum")
}
private fun sumPartNumbers(lines: Sequence<String>): Int {
val possiblePNs: MutableList<PossiblePN> = mutableListOf()
val symbols: MutableMap<Int, Set<Int>> = mutableMapOf()
lines.forEachIndexed {row, line ->
val res = parseLine(line, row)
possiblePNs.addAll(res.possiblePNs)
symbols[row] = res.symbols
}
return possiblePNs.filter { it.adjacentToSymbol(symbols) }.sumOf { it.value }
}
private fun parseLine(line: String, row: Int) = LineResult(
accumulateNumbers(line, row),
recordSymbols(line),
)
private fun accumulateNumbers(line: String, row: Int): List<PossiblePN> {
val accumulator = PossiblePNAccumulator(row)
line.forEach { accumulator.nextChar(it) }
return accumulator.end()
}
private fun recordSymbols(line: String): Set<Int> {
val symbols = mutableSetOf<Int>()
line.forEachIndexed { index, c -> if (c.isSymbol()) symbols.add(index)}
return symbols
}
private fun Char.isSymbol() = (this !in '0'..'9') and (this != '.')
private data class PossiblePN(val value: Int, val row: Int, val startCol: Int, val endCol: Int) {
fun adjacentToSymbol(symbols: Map<Int, Set<Int>>): Boolean {
return aboveRowContainsSymbol(symbols) or
rowContainsSymbol(symbols) or
belowRowContainsSymbols(symbols)
}
private fun aboveRowContainsSymbol(symbols: Map<Int, Set<Int>>) = checkRowSegment(symbols, row - 1)
private fun rowContainsSymbol(symbols: Map<Int, Set<Int>>): Boolean {
val targetRow = symbols[row] ?: return false
return targetRow.contains(startCol - 1) or targetRow.contains(endCol + 1)
}
private fun belowRowContainsSymbols(symbols: Map<Int, Set<Int>>) = checkRowSegment(symbols, row + 1)
private fun checkRowSegment(symbols: Map<Int, Set<Int>>, row: Int): Boolean {
val targetRow = symbols[row] ?: return false
for (col in startCol - 1..endCol + 1) {
if (targetRow.contains(col)) return true
}
return false
}
}
private data class LineResult(val possiblePNs: List<PossiblePN>, val symbols: Set<Int>)
private class PossiblePNAccumulator(private val row: Int) {
private val possiblePNs = mutableListOf<PossiblePN>()
private val currentNumber = StringBuilder()
private var currentCol = 0
private var currentStartCol = 0
private var currentEndCol = 0
private var currentState = State.OUT_NUMBER
private enum class State {
IN_NUMBER, OUT_NUMBER
}
fun nextChar(character: Char) {
when {
(character in '0'..'9') and (currentState == State.OUT_NUMBER) -> {
currentState = State.IN_NUMBER
currentNumber.append(character)
currentStartCol = currentCol
currentEndCol = currentCol
}
(character in '0'..'9') and (currentState == State.IN_NUMBER) -> {
currentNumber.append(character)
currentEndCol = currentCol
}
(character !in '0'..'9') and (currentState == State.IN_NUMBER) -> {
currentState = State.OUT_NUMBER
recordPossiblePN()
currentNumber.clear()
}
}
currentCol++
}
private fun recordPossiblePN() {
possiblePNs.add(
PossiblePN(
value = currentNumber.toString().toInt(),
row = row,
startCol = currentStartCol,
endCol = currentEndCol,
)
)
}
fun end(): List<PossiblePN> {
if (currentState == State.IN_NUMBER) {
recordPossiblePN()
}
return possiblePNs
}
} | [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day3/part1/Part1Kt.class",
"javap": "Compiled from \"part1.kt\"\npublic final class problems.day3.part1.Part1Kt {\n private static final java.lang.String part_numbers;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day5/part2/part2.kt | package problems.day5.part2
import java.io.File
import java.util.*
//const val testFile = "input/day5/test.txt"
const val inputFile = "input/day5/input.txt"
fun main() {
val lowestLocationNum = File(inputFile).bufferedReader().useLines { lowestLocationNumber(it) }
println("Lowest Location Num: $lowestLocationNum")
}
private fun lowestLocationNumber(lines: Sequence<String>): Long? {
val almanac = lines.fold(AlmanacBuilder()) { builder, line -> builder.nextLine(line) }.build()
for (i in 0..<Long.MAX_VALUE) {
if (almanac.locationHasSeed(i)) {
return i
}
}
return null
}
private class Almanac(val seeds: TreeMap<Long,Long>, val reverseMaps: Map<String, OverrideMap>) {
fun locationHasSeed(location: Long): Boolean {
val humidity = reverseMaps["humidity-to-location"]?.get(location) ?: return false
val temperature = reverseMaps["temperature-to-humidity"]?.get(humidity) ?: return false
val light = reverseMaps["light-to-temperature"]?.get(temperature) ?: return false
val water = reverseMaps["water-to-light"]?.get(light) ?: return false
val fertilizer = reverseMaps["fertilizer-to-water"]?.get(water) ?: return false
val soil = reverseMaps["soil-to-fertilizer"]?.get(fertilizer) ?: return false
val seed = reverseMaps["seed-to-soil"]?.get(soil) ?: return false
val floorSeed = seeds.floorEntry(seed) ?: return false
return floorSeed.key <= seed && seed <= floorSeed.value
}
}
private class AlmanacBuilder {
private var state = State.SEEDS
private var currentMapName = ""
private var currentMap = TreeMap<Long, Override>()
private val maps = mutableMapOf<String, OverrideMap>()
private val seeds = TreeMap<Long, Long>()
fun nextLine(line: String): AlmanacBuilder {
when (state) {
State.SEEDS -> {
seeds.putAll(line.toSeeds())
state = State.SEEDS_BLANK
}
State.SEEDS_BLANK -> state = State.HEADER
State.HEADER -> {
currentMapName = line.substringBefore(" ")
currentMap = TreeMap<Long, Override>()
state = State.MAP
}
State.MAP -> {
if (line != "") {
addOverride(line)
} else {
recordMap()
state = State.HEADER
}
}
}
return this
}
fun addOverride(line: String) {
val overrides = line.split(" ").map { it.toLong() }
val dstStart = overrides[0]
val dstEnd = overrides[0] + overrides[2] - 1
val srcStart = overrides[1]
currentMap[dstStart] = Override(dstStart, dstEnd, srcStart)
}
fun recordMap() {
maps[currentMapName] = OverrideMap(currentMap)
}
fun build(): Almanac {
if (state == State.MAP) {
recordMap()
}
return Almanac(seeds, maps)
}
private enum class State {
SEEDS,
SEEDS_BLANK,
HEADER,
MAP,
}
}
private fun String.toSeeds(): TreeMap<Long, Long> {
val seedRanges = TreeMap<Long,Long>()
val pairs = this.substringAfter(":").trim().split(" ").iterator()
while (pairs.hasNext()) {
val start = pairs.next().toLong()
val length = pairs.next().toLong()
seedRanges[start] = start+length-1
}
return seedRanges
}
private class OverrideMap(val overrides: TreeMap<Long, Override>) {
operator fun get(key: Long): Long {
val possibleOverride = overrides.headMap(key, true).lastEntry()?.value ?: return key
if (key <= possibleOverride.dstEnd) {
return possibleOverride.srcStart + (key - possibleOverride.dstStart)
}
return key
}
}
private data class Override(val dstStart: Long, val dstEnd: Long, val srcStart: Long) | [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day5/part2/Part2Kt.class",
"javap": "Compiled from \"part2.kt\"\npublic final class problems.day5.part2.Part2Kt {\n public static final java.lang.String inputFile;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day5/part1/part1.kt | package problems.day5.part1
import java.io.File
import java.util.*
//private const val testFile = "input/day5/test.txt"
private const val inputFile = "input/day5/input.txt"
fun main() {
val lowestLocationNum = File(inputFile).bufferedReader().useLines { lowestLocationNumber(it) }
println("Lowest Location Num: $lowestLocationNum")
}
private fun lowestLocationNumber(lines: Sequence<String>): Long {
val almanac = lines.fold(AlmanacBuilder()) { builder, line -> builder.nextLine(line) }.build()
return almanac.seeds.mapNotNull { almanac.seedLocation(it) }.min()
}
private class Almanac(val seeds: List<Long>, val maps: Map<String, OverrideMap>) {
fun seedLocation(seed: Long): Long? {
val soil = maps["seed-to-soil"]?.get(seed) ?: return null
val fertilizer = maps["soil-to-fertilizer"]?.get(soil) ?: return null
val water = maps["fertilizer-to-water"]?.get(fertilizer) ?: return null
val light = maps["water-to-light"]?.get(water) ?: return null
val temperature = maps["light-to-temperature"]?.get(light) ?: return null
val humidity = maps["temperature-to-humidity"]?.get(temperature) ?: return null
val location = maps["humidity-to-location"]?.get(humidity) ?: return null
return location
}
}
private class AlmanacBuilder {
private var state = State.SEEDS
private var currentMapName = ""
private var currentMap = TreeMap<Long, Override>()
private val maps = mutableMapOf<String, OverrideMap>()
private val seeds = mutableListOf<Long>()
fun nextLine(line: String): AlmanacBuilder {
when (state) {
State.SEEDS -> {
seeds.addAll(line.toSeeds())
state = State.SEEDS_BLANK
}
State.SEEDS_BLANK -> state = State.HEADER
State.HEADER -> {
currentMapName = line.substringBefore(" ")
currentMap = TreeMap<Long, Override>()
state = State.MAP
}
State.MAP -> {
if (line != "") {
addOverride(line)
} else {
recordMap()
state = State.HEADER
}
}
}
return this
}
fun addOverride(line: String) {
val overrides = line.split(" ").map { it.toLong() }
val srcStart = overrides[1]
val srcEnd = overrides[1] + overrides[2] - 1
val dstStart = overrides[0]
currentMap[srcStart] = Override(srcStart, srcEnd, dstStart)
}
fun recordMap() {
maps[currentMapName] = OverrideMap(currentMap)
}
fun build(): Almanac {
if (state == State.MAP) {
recordMap()
}
return Almanac(seeds, maps)
}
private enum class State {
SEEDS,
SEEDS_BLANK,
HEADER,
MAP,
}
}
private fun String.toSeeds() = this.substringAfter(":").trim().split(" ").map { it.toLong() }
private class OverrideMap(val overrides: TreeMap<Long, Override>) {
operator fun get(key: Long): Long {
val possibleOverride = overrides.headMap(key, true).lastEntry()?.value ?: return key
if (key <= possibleOverride.srcEnd) {
return possibleOverride.dstStart + (key - possibleOverride.srcStart)
}
return key
}
}
private data class Override(val srcStart: Long, val srcEnd: Long, val dstStart: Long) | [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day5/part1/Part1Kt.class",
"javap": "Compiled from \"part1.kt\"\npublic final class problems.day5.part1.Part1Kt {\n private static final java.lang.String inputFile;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day7/part2/part2.kt | package problems.day7.part2
import java.io.File
private const val inputFile = "input/day7/input.txt"
//private const val testFile = "input/day7/test.txt"
fun main() {
val scoreSum = File(inputFile).bufferedReader().useLines { sumScores(it) }
println("Sum of scores is $scoreSum")
}
private fun sumScores(lines: Sequence<String>): Int {
return lines.map { it.toHand() }
.sorted()
.foldIndexed(0) { index, acc, hand -> acc + ((index + 1) * hand.bid) }
}
private data class Hand(val cards: List<Card>, val bid: Int, val handType: HandType) : Comparable<Hand> {
override fun compareTo(other: Hand): Int {
if (this.handType == other.handType) {
return this.cards.compareTo(other.cards)
}
return this.handType.compareTo(other.handType)
}
}
private fun List<Card>.compareTo(other: List<Card>): Int {
for (pair in this.asSequence().zip(other.asSequence())) {
if (pair.first != pair.second) {
return pair.first.compareTo(pair.second)
}
}
return 0
}
private fun String.toHand(): Hand {
val cards = this.substringBefore(" ").map { it.toCard() }
val bid = this.substringAfter(" ").toInt()
val handType = cards.toHandType()
return Hand(cards, bid, handType)
}
private enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND,
}
private fun List<Card>.toHandType(): HandType {
val typeHistogram = mutableMapOf<Card, UInt>()
for (card in this) {
typeHistogram[card] = typeHistogram.getOrDefault(card, 0u) + 1u
}
return strongestHandType(typeHistogram)
}
private fun strongestHandType(typeHistogram: Map<Card, UInt>): HandType = when (typeHistogram[Card.JOKER]) {
null -> simpleHandType(typeHistogram)
0u -> simpleHandType(typeHistogram)
5u -> HandType.FIVE_OF_A_KIND
else -> typeHistogram.keys.filter { it != Card.JOKER }.maxOf {
val possibleHistogram = typeHistogram.toMutableMap()
possibleHistogram[Card.JOKER] = possibleHistogram[Card.JOKER]!! - 1u
possibleHistogram[it] = possibleHistogram[it]!! + 1u
strongestHandType(possibleHistogram)
}
}
private fun simpleHandType(typeHistogram: Map<Card, UInt>): HandType = when {
typeHistogram.any { it.value == 5u } -> HandType.FIVE_OF_A_KIND
typeHistogram.any { it.value == 4u } -> HandType.FOUR_OF_A_KIND
typeHistogram.any { it.value == 3u } and typeHistogram.any { it.value == 2u } -> HandType.FULL_HOUSE
typeHistogram.any { it.value == 3u } -> HandType.THREE_OF_A_KIND
typeHistogram.filter { it.value == 2u }.count() == 2 -> HandType.TWO_PAIR
typeHistogram.any { it.value == 2u } -> HandType.ONE_PAIR
else -> HandType.HIGH_CARD
}
private enum class Card {
JOKER,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
QUEEN,
KING,
ACE,
}
private fun Char.toCard() = when (this) {
'J' -> Card.JOKER
'2' -> Card.TWO
'3' -> Card.THREE
'4' -> Card.FOUR
'5' -> Card.FIVE
'6' -> Card.SIX
'7' -> Card.SEVEN
'8' -> Card.EIGHT
'9' -> Card.NINE
'T' -> Card.TEN
'Q' -> Card.QUEEN
'K' -> Card.KING
'A' -> Card.ACE
else -> throw IllegalArgumentException("Char $this does not have a corresponding card")
}
| [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day7/part2/Part2Kt.class",
"javap": "Compiled from \"part2.kt\"\npublic final class problems.day7.part2.Part2Kt {\n private static final java.lang.String inputFile;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day7/part1/part1.kt | package problems.day7.part1
import java.io.File
private const val inputFile = "input/day7/input.txt"
//private const val testFile = "input/day7/test.txt"
fun main() {
val scoreSum = File(inputFile).bufferedReader().useLines { sumScores(it) }
println("Sum of scores is $scoreSum")
}
private fun sumScores(lines: Sequence<String>): Int {
return lines.map { it.toHand() }
.sorted()
.foldIndexed(0) { index, acc, hand -> acc + ((index + 1) * hand.bid) }
}
private data class Hand(val cards: List<Card>, val bid: Int, val handType: HandType) : Comparable<Hand> {
override fun compareTo(other: Hand): Int {
if (this.handType == other.handType) {
return this.cards.compareTo(other.cards)
}
return this.handType.compareTo(other.handType)
}
}
private fun List<Card>.compareTo(other: List<Card>): Int {
for (pair in this.asSequence().zip(other.asSequence())) {
if (pair.first != pair.second) {
return pair.first.compareTo(pair.second)
}
}
return 0
}
private fun String.toHand(): Hand {
val cards = this.substringBefore(" ").map { it.toCard() }
val bid = this.substringAfter(" ").toInt()
val handType = cards.toHandType()
return Hand(cards, bid, handType)
}
private enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND,
}
private fun List<Card>.toHandType(): HandType {
val typeHistogram = mutableMapOf<Card, UInt>()
for (card in this) {
typeHistogram[card] = typeHistogram.getOrDefault(card, 0u) + 1u
}
return when {
typeHistogram.any { it.value == 5u } -> HandType.FIVE_OF_A_KIND
typeHistogram.any { it.value == 4u } -> HandType.FOUR_OF_A_KIND
typeHistogram.any { it.value == 3u } and typeHistogram.any { it.value == 2u } -> HandType.FULL_HOUSE
typeHistogram.any { it.value == 3u } -> HandType.THREE_OF_A_KIND
typeHistogram.filter { it.value == 2u }.count() == 2 -> HandType.TWO_PAIR
typeHistogram.any { it.value == 2u } -> HandType.ONE_PAIR
else -> HandType.HIGH_CARD
}
}
private enum class Card {
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE,
}
private fun Char.toCard() = when (this) {
'2' -> Card.TWO
'3' -> Card.THREE
'4' -> Card.FOUR
'5' -> Card.FIVE
'6' -> Card.SIX
'7' -> Card.SEVEN
'8' -> Card.EIGHT
'9' -> Card.NINE
'T' -> Card.TEN
'J' -> Card.JACK
'Q' -> Card.QUEEN
'K' -> Card.KING
'A' -> Card.ACE
else -> throw IllegalArgumentException("Char $this does not have a corresponding card")
} | [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day7/part1/Part1Kt.class",
"javap": "Compiled from \"part1.kt\"\npublic final class problems.day7.part1.Part1Kt {\n private static final java.lang.String inputFile;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day8/part2/part2.kt | package problems.day8.part2
import java.io.File
//private const val test3 = "input/day8/test3.txt"
private const val inputFile = "input/day8/input.txt"
fun main() {
val stepsCount = File(inputFile).bufferedReader().useLines { numSteps(it) }
println("Number of steps $stepsCount")
}
private fun numSteps(lines: Sequence<String>): Long {
val (instructions, rules) = lines.fold(RuleSetBuilder()) { builder, line -> builder.nextLine(line) }.build()
val startingLocations = rules.keys.filter { it.endsWith("A") }
val cycleLengths = startingLocations.map { cycleLength(it, instructions.copy(), rules) }.map { it.toLong() }
return leastCommonMultiple(cycleLengths)
}
private fun cycleLength(startPos: String, instructions: Instructions, rules: Map<String, Rule>): Int {
var currentLocation = startPos
while (!currentLocation.endsWith("Z")) {
val nextDirection = instructions.next()
val nextRule = rules[currentLocation] ?: throw IllegalArgumentException("No such location: $currentLocation")
currentLocation =
if (nextDirection == 'L') {
nextRule.left
} else {
nextRule.right
}
}
return instructions.directionCount
}
private fun leastCommonMultiple(numbers: List<Long>): Long =
numbers.reduce { a, b -> leastCommonMultipleOfPair(a, b) }
private fun leastCommonMultipleOfPair(a: Long, b: Long): Long =
(a * b) / greatestCommonDivisor(a, b)
private fun greatestCommonDivisor(a: Long, b: Long): Long = when {
a == 0L -> b
b == 0L -> a
a > b -> greatestCommonDivisor(a % b, b)
else -> greatestCommonDivisor(a, b % a)
}
private class Instructions(val directions: String) : Iterator<Char> {
var directionCount = 0
override fun hasNext() = true
override fun next(): Char {
val next = directions[directionCount % directions.count()]
directionCount++
return next
}
fun copy() = Instructions(this.directions)
}
private data class Rule(val left: String, val right: String)
private fun String.toRule(): Rule {
val left = this.substringBefore(", ").trimStart { it == '(' }
val right = this.substringAfter(", ").trimEnd { it == ')' }
return Rule(left, right)
}
private data class ParseResult(val instructions: Instructions, val rules: Map<String, Rule>)
private class RuleSetBuilder {
private var state = State.INSTRUCTIONS
private var instructions: Instructions? = null
private val rules = mutableMapOf<String, Rule>()
private enum class State {
INSTRUCTIONS,
BLANK,
RULES,
}
fun nextLine(line: String): RuleSetBuilder {
when (state) {
State.INSTRUCTIONS -> {
instructions = Instructions(line)
state = State.BLANK
}
State.BLANK -> {
state = State.RULES
}
State.RULES -> {
rules[line.substringBefore(" =")] = line.substringAfter("= ").toRule()
}
}
return this
}
fun build() = ParseResult(
instructions ?: throw IllegalArgumentException("missing instructions"),
rules
)
}
| [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day8/part2/Part2Kt.class",
"javap": "Compiled from \"part2.kt\"\npublic final class problems.day8.part2.Part2Kt {\n private static final java.lang.String inputFile;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day8/part1/part1.kt | package problems.day8.part1
import java.io.File
//private const val test1file = "input/day8/test1.txt"
//private const val test2file = "input/day8/test2.txt"
private const val inputFile = "input/day8/input.txt"
fun main() {
val stepsCount = File(inputFile).bufferedReader().useLines { numSteps(it) }
println("Number of steps $stepsCount")
}
private fun numSteps(lines: Sequence<String>): Int {
val (instructions, rules) = lines.fold(RuleSetBuilder()) { builder, line -> builder.nextLine(line) }.build()
var currentLocation = "AAA"
while (currentLocation != "ZZZ") {
val nextDirection = instructions.next()
val nextRule = rules[currentLocation] ?: throw IllegalArgumentException("No such location: $currentLocation")
currentLocation = if (nextDirection == 'L') {
nextRule.left
} else {
nextRule.right
}
}
return instructions.directionCount
}
private class Instructions(val directions: String) : Iterator<Char> {
var directionCount = 0
override fun hasNext() = true
override fun next(): Char {
val next = directions[directionCount % directions.count()]
directionCount++
return next
}
}
private data class Rule(val left: String, val right: String)
private fun String.toRule(): Rule {
val left = this.substringBefore(", ").trimStart { it == '(' }
val right = this.substringAfter(", ").trimEnd { it == ')' }
return Rule(left, right)
}
private data class ParseResult(val instructions: Instructions, val rules: Map<String, Rule>)
private class RuleSetBuilder {
private var state = State.INSTRUCTIONS
private var instructions: Instructions? = null
private val rules = mutableMapOf<String, Rule>()
private enum class State {
INSTRUCTIONS,
BLANK,
RULES,
}
fun nextLine(line: String): RuleSetBuilder {
when (state) {
State.INSTRUCTIONS -> {
instructions = Instructions(line)
state = State.BLANK
}
State.BLANK -> {
state = State.RULES
}
State.RULES -> {
rules[line.substringBefore(" =")] = line.substringAfter("= ").toRule()
}
}
return this
}
fun build() = ParseResult(
instructions ?: throw IllegalArgumentException("missing instructions"),
rules
)
} | [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day8/part1/Part1Kt.class",
"javap": "Compiled from \"part1.kt\"\npublic final class problems.day8.part1.Part1Kt {\n private static final java.lang.String inputFile;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day6/part2/part2.kt | package problems.day6.part2
import java.io.File
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
private const val inputFile = "input/day6/input.txt"
//const val testFile = "input/day6/test.txt"
fun main() {
val numberOfBeats = File(inputFile).bufferedReader().useLines { multiplyNumBeats(it) }
println("The number of ways to be the current max is: $numberOfBeats")
}
private fun multiplyNumBeats(lines: Sequence<String>): Long {
val iterator = lines.iterator()
val time = iterator.next().toTime()
val maxes = iterator.next().toMax()
return Race(time, maxes).numBeats()
}
private fun String.toTime(): Long {
return this.substringAfter("Time: ")
.replace(" ","")
.toLong()
}
private fun String.toMax(): Long {
return this.substringAfter("Distance: ")
.replace(" ","")
.toLong()
}
private data class Race(val time: Long, val currentMax: Long) {
fun numBeats(): Long {
val a = -1
val b = time
val c = -currentMax
val discriminant = sqrt(((b * b) - (4.0 * a * c)))
val low = (-b + discriminant) / (2 * a)
val high = (-b - discriminant) / (2 * a)
val flooredHigh = floor(high)
val ceiledLow = ceil(low)
var numBeats = (flooredHigh - ceiledLow).toLong() + 1
if (flooredHigh == high) {
numBeats--
}
if (ceiledLow == low) {
numBeats--
}
return numBeats
}
}
| [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day6/part2/Part2Kt.class",
"javap": "Compiled from \"part2.kt\"\npublic final class problems.day6.part2.Part2Kt {\n private static final java.lang.String inputFile;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day6/part1/part1.kt | package problems.day6.part1
import java.io.File
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
private const val inputFile = "input/day6/input.txt"
//private const val testFile = "input/day6/test.txt"
fun main() {
val productOfNumBeats = File(inputFile).bufferedReader().useLines { multiplyNumBeats(it) }
println("Product of number of ways to beat all races: $productOfNumBeats")
}
private fun multiplyNumBeats(lines: Sequence<String>): Int {
val iterator = lines.iterator()
val times = iterator.next().toTimes()
val maxes = iterator.next().toMaxes()
val races = times.zip(maxes) { time, max -> Race(time, max) }
return races.map { it.numBeats() }.fold(1) { acc, next -> next * acc }
}
private fun String.toTimes(): List<Int> {
return this.substringAfter("Time: ")
.trim()
.split("\\s+".toRegex())
.map { it.toInt() }
}
private fun String.toMaxes(): List<Int> {
return this.substringAfter("Distance: ")
.trim()
.split("\\s+".toRegex())
.map { it.toInt() }
}
private data class Race(val time: Int, val currentMax: Int) {
fun numBeats(): Int {
val a = -1
val b = time
val c = -currentMax
val discriminant = sqrt(((b * b) - (4.0 * a * c)))
val low = (-b + discriminant) / (2 * a)
val high = (-b - discriminant) / (2 * a)
val flooredHigh = floor(high)
val ceiledLow = ceil(low)
var numBeats = (flooredHigh - ceiledLow).toInt() + 1
if (flooredHigh == high) {
numBeats--
}
if (ceiledLow == low) {
numBeats--
}
return numBeats
}
}
| [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day6/part1/Part1Kt.class",
"javap": "Compiled from \"part1.kt\"\npublic final class problems.day6.part1.Part1Kt {\n private static final java.lang.String inputFile;\n\n public static final void main();\n Code:\n 0: new #10 ... |
klnusbaum__aoc2023__d30db24/src/problems/day10/part1/part1.kt | package problems.day10.part1
import java.io.File
private const val testFile1 = "input/day10/test1.txt"
private const val inputFile = "input/day10/input.txt"
fun main() {
val farthestTileDistance = File(inputFile).bufferedReader().useLines { farthestTileDistance(it) }
println("The tile farthest from start is $farthestTileDistance tiles away")
}
fun farthestTileDistance(it: Sequence<String>): Int {
val board = it.fold(BoardBuilder()) { builder, line -> builder.nextLine(line) }.build()
// println("Board: ${board.tiles}")
// println("start: ${board.startRow} ${board.startCol}")
val totalDistance = board.totalPipeDistance()
return totalDistance / 2
}
private class BoardBuilder {
private val tiles = mutableMapOf<Location, Tile>()
private var start: Location? = null
private var rowIndex = 0
fun nextLine(line: String): BoardBuilder {
line.forEachIndexed { colIndex, c ->
val tile = c.toTile()
val location = Location(rowIndex, colIndex)
if (tile is Tile.Start) {
start = location
}
tiles[location] = tile
}
rowIndex++
return this
}
fun build() = Board(
tiles,
start ?: throw IllegalArgumentException("No location found for start"),
)
}
private class Board(val tiles: Map<Location, Tile>, val start: Location) {
fun totalPipeDistance(): Int {
var previousLocation = start
var (currentLocation, currentTile) = nextFromStart()
var distance = 1
while (currentLocation != start) {
val (nextLocation, nextTile) = nextTile(previousLocation, currentLocation, currentTile)
previousLocation = currentLocation
currentLocation = nextLocation
currentTile = nextTile
distance++
}
return distance
}
private fun nextFromStart(): Pair<Location, Tile> {
val northernLocation = start.toNorth()
val northernTile = tiles[northernLocation]
if (northernTile?.opensOn(Direction.SOUTH) == true) {
return Pair(northernLocation, northernTile)
}
val southernLocation = start.toSouth()
val southernTile = tiles[southernLocation]
if (southernTile?.opensOn(Direction.NORTH) == true) {
return Pair(southernLocation, southernTile)
}
val westernLocation = start.toWest()
val westernTile = tiles[westernLocation]
if (westernTile?.opensOn(Direction.EAST) == true) {
return Pair(westernLocation, westernTile)
}
val easternLocation = start.toEast()
val easternTile = tiles[easternLocation]
if (easternTile?.opensOn(Direction.WEST) == true) {
return Pair(easternLocation, easternTile)
}
throw IllegalArgumentException("No tile accessible from start")
}
private fun nextTile(
previousLocation: Location,
currentLocation: Location,
currentTile: Tile
): Pair<Location, Tile> {
if (currentTile.opensOn(Direction.NORTH)) {
val northernLocation = currentLocation.toNorth()
val northernTile = tiles[northernLocation]
if (northernTile?.opensOn(Direction.SOUTH) == true && northernLocation != previousLocation) {
return Pair(northernLocation, northernTile)
}
}
if (currentTile.opensOn(Direction.SOUTH)) {
val southernLocation = currentLocation.toSouth()
val southernTile = tiles[southernLocation]
if (southernTile?.opensOn(Direction.NORTH) == true && southernLocation != previousLocation) {
return Pair(southernLocation, southernTile)
}
}
if (currentTile.opensOn(Direction.WEST)) {
val westernLocation = currentLocation.toWest()
val westernTile = tiles[westernLocation]
if (westernTile?.opensOn(Direction.EAST) == true && westernLocation != previousLocation) {
return Pair(westernLocation, westernTile)
}
}
if (currentTile.opensOn(Direction.EAST)) {
val easternLocation = currentLocation.toEast()
val easternTile = tiles[easternLocation]
if (easternTile?.opensOn(Direction.WEST) == true && easternLocation != previousLocation) {
return Pair(easternLocation, easternTile)
}
}
throw IllegalArgumentException("No next tile from $currentLocation")
}
}
private data class Location(val row: Int, val col: Int) {
fun toNorth(): Location = Location(row - 1, col)
fun toSouth(): Location = Location(row + 1, col)
fun toWest(): Location = Location(row, col - 1)
fun toEast(): Location = Location(row, col + 1)
}
private sealed class Tile {
data class Pipe(val first: Direction, val second: Direction) : Tile()
data object Ground : Tile()
data object Start : Tile()
fun opensOn(direction: Direction) = when (this) {
is Pipe -> this.first == direction || this.second == direction
is Start -> true
else -> false
}
}
private fun Char.toTile(): Tile = when (this) {
'|' -> Tile.Pipe(Direction.NORTH, Direction.SOUTH)
'-' -> Tile.Pipe(Direction.EAST, Direction.WEST)
'L' -> Tile.Pipe(Direction.NORTH, Direction.EAST)
'J' -> Tile.Pipe(Direction.NORTH, Direction.WEST)
'7' -> Tile.Pipe(Direction.SOUTH, Direction.WEST)
'F' -> Tile.Pipe(Direction.SOUTH, Direction.EAST)
'S' -> Tile.Start
else -> Tile.Ground
}
private enum class Direction {
NORTH,
SOUTH,
EAST,
WEST,
} | [
{
"class_path": "klnusbaum__aoc2023__d30db24/problems/day10/part1/Part1Kt.class",
"javap": "Compiled from \"part1.kt\"\npublic final class problems.day10.part1.Part1Kt {\n private static final java.lang.String testFile1;\n\n private static final java.lang.String inputFile;\n\n public static final void ma... |
PathFinder-SSAFY__PathFinder__57e9a94/client/PathFinder/app/src/main/java/com/dijkstra/pathfinder/util/KalmanFilter3D.kt | package com.dijkstra.pathfinder.util
class KalmanFilter3D(
initialState: List<Double>,
initialCovariance: List<List<Double>>
) {
private var state = initialState
private var covariance = initialCovariance
private val processNoise = listOf(
listOf(0.1, 0.0, 0.0),
listOf(0.0, 0.1, 0.0),
listOf(0.0, 0.0, 0.1)
)
fun update(measurement: List<Double>, measurementNoise: List<Double>): List<Double> {
val kalmanGain = calculateKalmanGain(measurementNoise)
val innovation = measurement.zip(state) { m, s -> m - s }
state = state.zip(
kalmanGain.map { row ->
row.zip(innovation) { x, y ->
x * y
}.sum()
}
).map { it.first + it.second }
covariance = updateCovariance(kalmanGain)
return state
}
private fun calculateKalmanGain(measurementNoise: List<Double>): List<List<Double>> {
val sum = covariance.zip(processNoise) { a, b -> a.zip(b) { x, y -> x + y } }
val sumDiagonal = sum.indices.map { sum[it][it] }
val noisePlusSumDiagonal = measurementNoise.zip(sumDiagonal) { x, y -> x + y }
return covariance.map { row -> row.zip(noisePlusSumDiagonal) { x, y -> x / y } }
}
private fun updateCovariance(kalmanGain: List<List<Double>>): List<List<Double>> {
val gainTimesCovariance =
kalmanGain.map { row -> row.zip(covariance) { x, col -> x * col.sum() } }
val identityMinusGain = gainTimesCovariance.indices.map { i ->
gainTimesCovariance[i].mapIndexed { j, value -> if (i == j) 1.0 - value else -value }
}
return identityMinusGain.map { row -> row.zip(covariance) { x, col -> x * col.sum() } }
}
}
| [
{
"class_path": "PathFinder-SSAFY__PathFinder__57e9a94/com/dijkstra/pathfinder/util/KalmanFilter3D.class",
"javap": "Compiled from \"KalmanFilter3D.kt\"\npublic final class com.dijkstra.pathfinder.util.KalmanFilter3D {\n private java.util.List<java.lang.Double> state;\n\n private java.util.List<? extends ... |
fitzf__leetcode__a2ea7df/src/main/kotlin/men/zhangfei/leetcode/medium/Problem0003.kt | package men.zhangfei.leetcode.medium
/**
* 3. 无重复字符的最长子串
* https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
*/
class Problem0003 {
companion object {
/**
* 滑动窗口算法
* 1. 使用 HashSet 作为滑动窗口,存储字符
* 2. 设置窗口的左边和右边索引为 0 val l = 0, val r = 0
* 3. 循环判断窗口中是否包含字符串【s】右边索引下的字符,直到窗口滑动到字符串的末尾
* a. 不包含:右边索引右移 r++ 并更新窗口的最大长度 max = max(已存储的最大长度, 当前窗口长度)
* b. 包含:左边索引右移 l++ 如果移动后的左边索引到末尾的长度不大于已存在的最大长度的话 跳出循环
*/
fun slidingWindow(s: String): Int = when {
s.isEmpty() -> 0
s.length == 1 -> 1
else -> {
var max = 0
val len = s.length
var l = 0
var r = 0
val set: MutableSet<Char> = mutableSetOf()
while (r < len) {
if (set.contains(s[r])) {
set.remove(s[l++])
if (len - l <= max) {
break
}
} else {
set.add(s[r++])
max = max.coerceAtLeast(r - l)
}
}
max
}
}
/**
* 优化的滑动窗口
* 0. 初始化窗口左边和右边的索引为 0 l = 0, r = 0
* 1. 窗口右边索引递增循环 r++; r < s.length
* 2. 如果当前右边索引下的字符已经存在,则判断 当前左边索引 > (该字符上次索引 + 1) l > (map[s[\r]] + 1)
* a. 是:则说明 (该字符上次索引 + 1) 至 当前左边索引中有其它重复字符,所以忽略,不改变左边索引 l
* b. 否:将左边索引移动到 (该字符上次索引 + 1) 的位置 l = (map[s[\r]] + 1)
* 4. 更新最长子串长度 max = max(已存储的最大长度, 当前窗口长度)
* 5. 将当前右边索引和字符存入 HashMap<字符,索引>. e.g. {"a": 0, "b": 1}
* 6. 转到 1 步
*/
fun optimizedSlidingWindow(s: String): Int = when {
s.isEmpty() -> 0
s.length == 1 -> 1
else -> {
var max = 0
val len = s.length
var l = 0
var c: Char
val map: HashMap<Char, Int> = hashMapOf()
for (r in 0 until len) {
c = s[r]
map[c]?.let {
// 防止左边索引回跳
l = l.coerceAtLeast(it + 1)
}
max = max.coerceAtLeast(r - l + 1)
map[c] = r
}
max
}
}
}
} | [
{
"class_path": "fitzf__leetcode__a2ea7df/men/zhangfei/leetcode/medium/Problem0003.class",
"javap": "Compiled from \"Problem0003.kt\"\npublic final class men.zhangfei.leetcode.medium.Problem0003 {\n public static final men.zhangfei.leetcode.medium.Problem0003$Companion Companion;\n\n public men.zhangfei.l... |
fitzf__leetcode__a2ea7df/src/main/kotlin/men/zhangfei/leetcode/medium/Problem0139.kt | package men.zhangfei.leetcode.medium
import java.util.LinkedList
import java.util.Queue
/**
* 139. 单词拆分
* https://leetcode-cn.com/problems/word-break/
*/
class Problem0139 {
companion object {
/**
* 动态规划
* 字符串 s 可以被拆分成子字符串 s1 和 s2
* 如果这些子字符串都可以独立地被拆分成符合要求的子字符串,那么整个字符串 s 也可以满足
* e.g. s = "catsanddog", wordDict = ["cats", "dog", "sand", "and", "cat"]
* s1 = "catsand", s2 = "dog"
* s1-1 = "cats", s1-2 = "and"
* s1-1, s1-2 满足, 所以 s1 也满足, s1, s2 都满足,所以 s 也满足
*/
fun dp(s: String, wordDict: List<String>): Boolean {
val len = s.length
val dp = BooleanArray(len + 1)
// 空字符串总是字典的一部分, 剩余为 false
dp[0] = true
for (r in 1..len) {
// 通过下标 l 将字符串 s[0, r) 拆分成 s1, s2
for (l in 0 until r) {
// 检查 s1 s[0, j) 是否满足条件 检查 s2 s[j, r) 是否满足条件,如果满足,说明 s[0, r) 满足 dp[r] = true
if (dp[l] && wordDict.contains(s.substring(l, r))) {
dp[r] = true
break
}
}
}
return dp[len]
}
/**
* 宽度优先搜索
*/
fun bfs(s: String, wordDict: List<String>): Boolean {
val len = s.length
val queue: Queue<Int> = LinkedList()
val visited = IntArray(len)
queue.add(0)
var start: Int
while (!queue.isEmpty()) {
start = queue.remove()
if (0 == visited[start]) {
for (end in (start + 1)..len) {
if (wordDict.contains(s.substring(start, end))) {
queue.add(end)
if (end == len) {
return true
}
}
}
visited[start] = 1
}
}
return false
}
}
} | [
{
"class_path": "fitzf__leetcode__a2ea7df/men/zhangfei/leetcode/medium/Problem0139.class",
"javap": "Compiled from \"Problem0139.kt\"\npublic final class men.zhangfei.leetcode.medium.Problem0139 {\n public static final men.zhangfei.leetcode.medium.Problem0139$Companion Companion;\n\n public men.zhangfei.l... |
xfornesa__aoc2022__dc14292/src/main/kotlin/day04/Problem.kt | package day04
fun solveProblem01(input: List<String>): Long {
return input.stream()
.map { it.split(",") }
.map {
val (left, right) = it
val (left_l, left_h) = left.split("-").map { it.toInt() }
val (right_l, right_h) = right.split("-").map { it.toInt() }
left_l <= right_l && right_h <= left_h || right_l <= left_l && left_h <= right_h
}
.filter { it }
.count()
}
fun solveProblem02(input: List<String>): Long {
return input.stream()
.map { it.split(",") }
.map {
val (left, right) = it
val (left_l, left_h) = left.split("-").map { it.toInt() }
val (right_l, right_h) = right.split("-").map { it.toInt() }
right_l in left_l..left_h
|| right_h in left_l..left_h
|| left_l in right_l..right_h
|| left_h in right_l..right_h
}
.filter { it }
.count()
}
| [
{
"class_path": "xfornesa__aoc2022__dc14292/day04/ProblemKt.class",
"javap": "Compiled from \"Problem.kt\"\npublic final class day04.ProblemKt {\n public static final long solveProblem01(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #10 // String ... |
xfornesa__aoc2022__dc14292/src/main/kotlin/day03/Problem.kt | package day03
fun solveProblem01(input: List<String>): Int {
val commonTypes = mutableListOf<Char>()
input.forEach {
val first = it.substring(0 until it.length/2)
val second = it.substring((it.length / 2) until it.length)
val commonType = commonType(first, second)
commonTypes.add(commonType)
}
return commonTypes.sumOf { toScore(it) }
}
fun toScore(it: Char): Int {
return if (it.isLowerCase())
it.minus('a') + 1
else
it.minus('A') + 27
}
fun commonType(first: String, second: String): Char {
val occurrencesFirst = HashSet<Char>()
first.forEach {
occurrencesFirst.add(it)
}
val occurrencesSecond = HashSet<Char>()
second.forEach {
occurrencesSecond.add(it)
}
val common = first.asIterable().toSet() intersect second.asIterable().toSet()
return common.first()
}
fun solveProblem02(input: List<String>): Int {
val windowed = input.windowed(3, 3)
return windowed.map {
findCommonTypes(it)
}.sumOf {
toScore(it)
}
}
fun findCommonTypes(it: List<String>): Char {
val (first, second, third) = it
val occurrencesFirst = HashSet<Char>()
first.forEach {
occurrencesFirst.add(it)
}
val occurrencesSecond = HashSet<Char>()
second.forEach {
occurrencesSecond.add(it)
}
val occurrencesThird = HashSet<Char>()
third.forEach {
occurrencesThird.add(it)
}
val common = first.toSet() intersect second.toSet() intersect third.toSet()
return common.first()
}
| [
{
"class_path": "xfornesa__aoc2022__dc14292/day03/ProblemKt.class",
"javap": "Compiled from \"Problem.kt\"\npublic final class day03.ProblemKt {\n public static final int solveProblem01(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #10 // String i... |
xfornesa__aoc2022__dc14292/src/main/kotlin/day02/Problem.kt | package day02
fun solveProblem01(input: List<Pair<String, String>>): Int {
var score = 0
input.forEach {
score += round01(it)
}
return score
}
// A for Rock, B for Paper, and C for Scissors
// X for Rock, Y for Paper, and Z for Scissors
// score: (1 for Rock, 2 for Paper, and 3 for Scissors) + (0 if you lost, 3 if the round was a draw, and 6 if you won)
private fun round01(pair: Pair<String, String>): Int {
var figureScore = 0
when (pair.second) {
"X" -> figureScore = 1
"Y" -> figureScore = 2
"Z" -> figureScore = 3
}
var winningScore = 0
when (pair) {
Pair("A", "X") -> winningScore = 3
Pair("A", "Y") -> winningScore = 6
Pair("A", "Z") -> winningScore = 0
Pair("B", "X") -> winningScore = 0
Pair("B", "Y") -> winningScore = 3
Pair("B", "Z") -> winningScore = 6
Pair("C", "X") -> winningScore = 6
Pair("C", "Y") -> winningScore = 0
Pair("C", "Z") -> winningScore = 3
}
return figureScore + winningScore
}
fun solveProblem02(input: List<Pair<String, String>>): Int {
var score = 0
input.forEach {
score += round02(it)
}
return score
}
// A for Rock, B for Paper, and C for Scissors
// X for lose, Y for draw, and Z for win
// score: (1 for Rock, 2 for Paper, and 3 for Scissors) + (0 if you lost, 3 if the round was a draw, and 6 if you won)
private fun round02(pair: Pair<String, String>): Int {
var winningScore = 0
when (pair.second) {
"X" -> winningScore = 0
"Y" -> winningScore = 3
"Z" -> winningScore = 6
}
var figureScore = 0
when (pair) {
// rock
Pair("A", "X") -> figureScore = 3 // lose with scissors
Pair("A", "Y") -> figureScore = 1 // draw with rock
Pair("A", "Z") -> figureScore = 2 // win with paper
// paper
Pair("B", "X") -> figureScore = 1 // lose with rock
Pair("B", "Y") -> figureScore = 2 // draw with paper
Pair("B", "Z") -> figureScore = 3 // win with scissors
// scissors
Pair("C", "X") -> figureScore = 2 // lose with paper
Pair("C", "Y") -> figureScore = 3 // draw with scissors
Pair("C", "Z") -> figureScore = 1 // win with rock
}
return figureScore + winningScore
}
| [
{
"class_path": "xfornesa__aoc2022__dc14292/day02/ProblemKt.class",
"javap": "Compiled from \"Problem.kt\"\npublic final class day02.ProblemKt {\n public static final int solveProblem01(java.util.List<kotlin.Pair<java.lang.String, java.lang.String>>);\n Code:\n 0: aload_0\n 1: ldc ... |
xfornesa__aoc2022__dc14292/src/main/kotlin/day05/Problem.kt | package day05
import java.util.*
fun solveProblem01(input: List<String>): String {
val stackInput = Stack<String>()
val movements = mutableListOf<String>()
var stackHalf = true
for (value in input) {
if (value.isEmpty()) {
stackHalf = false
continue
}
if (stackHalf) {
stackInput.push(value)
} else {
movements.add(value)
}
}
val stacks = buildInitialStack(stackInput)
for (movement in movements) {
val (num, from, to) = parseMovement(movement)
repeat(num) {
val value = stacks[from]?.pop()
stacks[to]?.push(value)
}
}
return (1..stacks.size)
.mapNotNull { stacks[it]?.pop() }
.joinToString("")
}
fun parseMovement(movement: String): List<Int> {
val regex = """move (\d+) from (\d+) to (\d+)""".toRegex()
val matchResult = regex.find(movement)
val destructured = matchResult!!.destructured
return destructured.toList().map { it.toInt() }
}
fun buildInitialStack(stackInput: Stack<String>): MutableMap<Int, Stack<String>> {
val result = mutableMapOf<Int, Stack<String>>()
val keys = stackInput
.pop()
.trim().split("\\s+".toRegex())
.map {
it.toInt()
}
keys
.forEach {
result[it] = Stack<String>()
}
val rowLength = keys.count()*4 - 1
for (value in stackInput.reversed()) {
val row = value.padEnd(rowLength)
row.asSequence()
.windowed(3, 4)
.forEachIndexed { index, letters ->
val letter = letters.filter { it.isLetter() }.joinToString("")
if (letter.isNotBlank()) {
result[index+1]?.push(letter)
}
}
}
return result
}
fun solveProblem02(input: List<String>): String {
val stackInput = Stack<String>()
val movements = mutableListOf<String>()
var stackHalf = true
for (value in input) {
if (value.isEmpty()) {
stackHalf = false
continue
}
if (stackHalf) {
stackInput.push(value)
} else {
movements.add(value)
}
}
val stacks = buildInitialStack(stackInput)
for (movement in movements) {
val (num, from, to) = parseMovement(movement)
val temp = Stack<String>()
repeat(num) {
val value = stacks[from]?.pop()
temp.push(value)
}
repeat(num) {
val value = temp.pop()
stacks[to]?.push(value)
}
}
return (1..stacks.size)
.mapNotNull { stacks[it]?.pop() }
.joinToString("")
}
| [
{
"class_path": "xfornesa__aoc2022__dc14292/day05/ProblemKt.class",
"javap": "Compiled from \"Problem.kt\"\npublic final class day05.ProblemKt {\n public static final java.lang.String solveProblem01(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
P3tran__CodilityLessonsKotlin__15c6065/src/lesson8/EquiLeader.kt | package lesson8
import java.util.*
/*
* Find leaders in 2 array slices by checking if leader exists
* and using prefix occurrences sums after, on all array slices
* */
class EquiLeader {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val result = solution(intArrayOf(4, 3, 4, 4, 4, 2))
println("result : $result")
}
fun solution(A: IntArray): Int {
if (A.size < 2)
return 0
val stack = Stack<Int>()
for (i in A.indices) {
stack.push(A[i])
}
for (i in A.indices) {
when {
stack.isEmpty() -> stack.push(A[i])
stack.peek() != A[i] -> stack.pop()
else -> stack.push(A[i])
}
}
if (stack.size == 0)
return 0
val candidate = stack.pop()
var candidateOccurrences = 0
val sumOccurrences = IntArray(A.size) {0}
var equis = 0
for (i in A.indices) {
if (A[i] == candidate) {
candidateOccurrences++
if (i > 0)
sumOccurrences[i] = sumOccurrences[i - 1] + 1
else
sumOccurrences[i] = 1
} else {
if (i > 0)
sumOccurrences[i] = sumOccurrences[i - 1]
else
sumOccurrences[i] = 0
}
}
if (candidateOccurrences > (A.size / 2)) {
println("we have a leader $candidate")
for (i in A.indices) {
println("in index $i : ")
println("sum occ from start: ${sumOccurrences[i]}, occur from end: ${sumOccurrences[A.size-1] - sumOccurrences[i]}")
println("compared to ${i+1/2} and compared to ${(A.size -1 - i)/2 }")
if(sumOccurrences[i] > (i+1).toDouble() /2 && ((sumOccurrences[A.size-1] - sumOccurrences[i]) > (A.size -1 - i).toDouble() /2 )) {
equis++
println("bingo")
}
}
return equis
}
return 0
}
}
} | [
{
"class_path": "P3tran__CodilityLessonsKotlin__15c6065/lesson8/EquiLeader$Companion.class",
"javap": "Compiled from \"EquiLeader.kt\"\npublic final class lesson8.EquiLeader$Companion {\n private lesson8.EquiLeader$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // M... |
fi-jb__leetcode__f0d59da/src/main/kotlin/fijb/leetcode/algorithms/A5LongestPalindromicSubstring.kt | package fijb.leetcode.algorithms
// https://leetcode.com/problems/longest-palindromic-substring/
object A5LongestPalindromicSubstring {
fun longestPalindrome(s: String): String {
var max = Pair(0, 0)
for (i in s.indices) max = maxPairOf(max, maxPairOf(getOddPair(s, i), getEvenPair(s, i)))
return s.substring(max.first, max.second)
}
// "aba" for example
private fun getOddPair(s: String, point: Int): Pair<Int, Int> {
var i = 0
while (point - i - 1 >= 0 && point + i + 1 <= s.length - 1 && s[point - i - 1] == s[point + i + 1]) i ++
return Pair(maxOf(0, point - i), minOf(s.length, point + i) + 1)
}
// "abba" for example
private fun getEvenPair(s: String, point: Int): Pair<Int, Int> {
var i = 0
if (point + 1 > s.length - 1 || s[point] != s[point + 1]) return Pair(0, 0)
while (point - i - 1 >= 0 && point + i + 2 <= s.length - 1 && s[point - i - 1] == s[point + i + 2]) i ++
return Pair(maxOf(0, point - i), minOf(s.length, point + i + 1) + 1)
}
private fun maxPairOf(p1: Pair<Int, Int>, p2: Pair<Int, Int>) =
if (p1.second - p1.first >= p2.second - p2.first) p1 else p2
}
| [
{
"class_path": "fi-jb__leetcode__f0d59da/fijb/leetcode/algorithms/A5LongestPalindromicSubstring.class",
"javap": "Compiled from \"A5LongestPalindromicSubstring.kt\"\npublic final class fijb.leetcode.algorithms.A5LongestPalindromicSubstring {\n public static final fijb.leetcode.algorithms.A5LongestPalindro... |
fi-jb__leetcode__f0d59da/src/main/kotlin/fijb/leetcode/algorithms/A2AddTwoNumbers.kt | package fijb.leetcode.algorithms
//https://leetcode.com/problems/add-two-numbers/
object A2AddTwoNumbers {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var result : ListNode? = null
var it: ListNode? = null
var it1 = l1
var it2 = l2
var dev = 0
while (it1 != null) {
var sum =
if (it2 == null) it1.`val` + dev
else it1.`val` + it2.`val` + dev
dev = sum / 10
sum %= 10
if (result == null) {
result = ListNode(sum)
it = result
}
else {
it?.next = ListNode(sum)
it = it?.next
}
it1 = it1.next
it2 = it2?.next
}
while (it2 != null) {
var sum = it2.`val` + dev
dev = sum / 10
sum %= 10
it?.next = ListNode(sum)
it = it?.next
it2 = it2.next
}
if (dev != 0) it?.next = ListNode(dev)
return result
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
override fun toString(): String {
val result = StringBuilder()
var it : ListNode? = this
while (it != null) {
result.append("${it.`val`} ")
it = it.next
}
return "[" + result.toString().trim().replace(" ", ",") + "]"
}
override fun equals(other: Any?): Boolean {
var it1: ListNode? = this
var it2: ListNode? = other as ListNode
while (it1 != null) {
if (it1.`val` != it2?.`val`) return false
it1 = it1.next
it2 = it2.next
}
if (it2 != null) return false
return true
}
override fun hashCode(): Int {
var result = `val`
result = 31 * result + (next?.hashCode() ?: 0)
return result
}
}
}
| [
{
"class_path": "fi-jb__leetcode__f0d59da/fijb/leetcode/algorithms/A2AddTwoNumbers$ListNode.class",
"javap": "Compiled from \"A2AddTwoNumbers.kt\"\npublic final class fijb.leetcode.algorithms.A2AddTwoNumbers$ListNode {\n private int val;\n\n private fijb.leetcode.algorithms.A2AddTwoNumbers$ListNode next;\... |
fi-jb__leetcode__f0d59da/src/main/kotlin/fijb/leetcode/algorithms/A4MedianOfTwoSortedArrays.kt | package fijb.leetcode.algorithms
//https://leetcode.com/problems/median-of-two-sorted-arrays/
object A4MedianOfTwoSortedArrays {
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val nums = arrayListOf<Int>()
var i1 = 0
var i2 = 0
val s = (nums1.size + nums2.size)
while (i1 < nums1.size && i2 < nums2.size) {
if (i1 + i2 > s) break
if (nums1[i1] < nums2[i2]) nums.add( nums1[i1 ++] )
else nums.add( nums2[i2 ++] )
}
val h = s / 2
val h1 = minOf(nums1.size, h + 1)
val h2 = minOf(nums2.size, h + 1)
while (i1 < h1) nums.add( nums1[i1 ++] )
while (i2 < h2) nums.add( nums2[i2 ++] )
return if (s % 2 == 0) 0.5 * (nums[h - 1] + nums[h]) else nums[h].toDouble()
}
}
| [
{
"class_path": "fi-jb__leetcode__f0d59da/fijb/leetcode/algorithms/A4MedianOfTwoSortedArrays.class",
"javap": "Compiled from \"A4MedianOfTwoSortedArrays.kt\"\npublic final class fijb.leetcode.algorithms.A4MedianOfTwoSortedArrays {\n public static final fijb.leetcode.algorithms.A4MedianOfTwoSortedArrays INS... |
DPNT-Sourcecode__CHK-dkni01__2955860/bin/main/solutions/CHK/CheckoutSolution.kt | package solutions.CHK
object CheckoutSolution {
val prices = hashMapOf(
"A" to 50,
"B" to 30,
"C" to 20,
"D" to 15,
"E" to 40,
"F" to 10,
"G" to 20,
"H" to 10,
"I" to 35,
"J" to 60,
"K" to 80,
"L" to 90,
"M" to 15,
"N" to 40,
"O" to 10,
"P" to 50,
"Q" to 30,
"R" to 50,
"S" to 30,
"T" to 20,
"U" to 40,
"V" to 50,
"W" to 20,
"X" to 90,
"Z" to 50,
"Y" to 10
)
const val PRICE_A = 50
const val PRICE_B = 30
const val PRICE_C = 20
const val PRICE_D = 15
const val PRICE_E = 40
const val PRICE_F = 10
const val A_OFFER3 = 130
const val A_OFFER5 = 200
const val B_OFFER2 = 45
fun checkout(skus: String): Int {
if (skus.any { !listOf('A', 'B', 'C', 'D', 'E', 'F').contains(it) }) {
return -1
}
// calculating As
val offerA5 = calculateOffer(
PRICE_A,
skus.count { it == 'A' } * PRICE_A,
5,
A_OFFER5
)
val offerA3 = calculateOffer(
PRICE_A,
offerA5.second,
3,
A_OFFER3
)
val totalA = offerA5.first + offerA3.first + offerA3.second
// calculating Es
val offerE = calculateOffer(
PRICE_E,
skus.count { it == 'E' } * PRICE_E,
2,
1
)
val adjustedBCount = skus.count { it == 'B' } - offerE.first
// calculating Bs
val newB = calculateOffer(
PRICE_B,
adjustedBCount * PRICE_B,
2,
B_OFFER2
)
val totalB = newB.first + newB.second
// calculating Fs
val offerF = calculateOffer(
PRICE_F,
skus.count { it == 'F' } * PRICE_F,
3,
1
)
val totalF = (skus.count { it == 'F' } * PRICE_F) - (offerF.first * PRICE_F)
return totalA +
(if (totalB <= 0) 0 else totalB) +
(skus.count { it == 'C' } * PRICE_C) +
(skus.count { it == 'D' } * PRICE_D) +
(skus.count { it == 'E' } * PRICE_E) +
totalF
}
private fun calculateOffer(
price: Int,
total: Int,
multiplier: Int,
offer: Int
) : Pair<Int, Int> {
val leftover = total % (price * multiplier)
val reduced = ((total - leftover) / (price * multiplier)) * offer
return Pair(reduced, leftover)
}
}
| [
{
"class_path": "DPNT-Sourcecode__CHK-dkni01__2955860/solutions/CHK/CheckoutSolution.class",
"javap": "Compiled from \"CheckoutSolution.kt\"\npublic final class solutions.CHK.CheckoutSolution {\n public static final solutions.CHK.CheckoutSolution INSTANCE;\n\n private static final java.util.HashMap<java.l... |
schnell18__kotlin-koans__7c1e281/src/iii_conventions/MyDate.kt | package iii_conventions
data class RepeatedTimeInterval(val interval: TimeInterval, val repeat : Int = 1)
enum class TimeInterval {
DAY(),
WEEK(),
YEAR();
operator fun times(i: Int): RepeatedTimeInterval {
return RepeatedTimeInterval(this, i)
}
}
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) {
operator fun compareTo(date2: MyDate): Int {
return when {
this.year != date2.year -> this.year.compareTo(date2.year)
this.month != date2.month -> this.month.compareTo(date2.month)
else -> this.dayOfMonth.compareTo(date2.dayOfMonth)
}
}
fun nextDay(days : Int = 1) : MyDate {
var d = this.dayOfMonth
var m = this.month
var y = this.year
val daysOfMonth = when (m) {
1, 3, 5, 7, 8, 10, 12 -> 31
2 -> if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) 29 else 28
else -> 30
}
var remainder = 0
when {
days <= daysOfMonth - this.dayOfMonth -> d += days
days <= daysOfMonth - this.dayOfMonth + 28 -> {
d += days - daysOfMonth
m += 1
}
else -> {
remainder = days - 28 - (daysOfMonth - this.dayOfMonth)
d = 28
m += 1
}
}
if (m > 12) {
m = 1
y += 1
}
val result = MyDate(y, m, d)
if (remainder > 0) {
return result.nextDay(remainder)
}
return result
}
}
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
class DateRange(val start: MyDate, val endInclusive: MyDate) {
operator fun contains(d: MyDate) = start <= d && d <= endInclusive
operator fun iterator(): Iterator<MyDate> {
return object : Iterator<MyDate> {
var currentDate = start.copy()
override fun hasNext(): Boolean {
return currentDate <= endInclusive
}
override fun next(): MyDate {
val retDate = currentDate
currentDate = currentDate.nextDay()
return retDate
}
}
}
}
| [
{
"class_path": "schnell18__kotlin-koans__7c1e281/iii_conventions/MyDate.class",
"javap": "Compiled from \"MyDate.kt\"\npublic final class iii_conventions.MyDate {\n private final int year;\n\n private final int month;\n\n private final int dayOfMonth;\n\n public iii_conventions.MyDate(int, int, int);\n... |
aesdeef__advent-of-code-2021__4561bcf/kotlin/day01/sonarSweep.kt | package day01
import java.io.File
fun main() {
val depths = parseInput()
val part1 = countIncreases(depths)
val slidingWindows = getSlidingWindows(depths)
val part2 = countIncreases(slidingWindows)
println(part1)
println(part2)
}
fun parseInput(): List<Int> {
return File("../../input/01.txt")
.readLines()
.map { it.toInt() }
}
fun countIncreases(measurements: List<Int>): Int {
return (measurements.dropLast(1) zip measurements.drop(1))
.count { it.first < it.second }
}
fun getSlidingWindows(depths: List<Int>): List<Int> {
return zipSum(
zipSum(
depths.dropLast(2),
depths.dropLast(1).drop(1)
),
depths.drop(2)
)
}
fun zipSum(first: List<Int>, second: List<Int>): List<Int> {
return (first zip second).map{ it.first + it.second }
}
| [
{
"class_path": "aesdeef__advent-of-code-2021__4561bcf/day01/SonarSweepKt.class",
"javap": "Compiled from \"sonarSweep.kt\"\npublic final class day01.SonarSweepKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method parseInput:()Ljava/util/List;\n 3: ... |
aesdeef__advent-of-code-2021__4561bcf/kotlin/day02/deep.kt | package day02
import java.io.File
data class Instruction(val command: String, val value: Int)
fun main() {
val instructions = parseInput()
val part1 = solvePart1(instructions)
val part2 = solvePart2(instructions)
println(part1)
println(part2)
}
fun parseInput(): List<Instruction> {
return File("../../input/02.txt")
.readLines()
.map { it.split(" ") }
.map { Instruction(it[0], it[1].toInt()) }
}
fun solvePart1(instructions: List<Instruction>): Int {
var horizontal = 0
var depth = 0
instructions.forEach {
val (command, value) = it
when (command) {
"forward" -> horizontal += value
"down" -> depth += value
"up" -> depth -= value
}
}
return horizontal * depth
}
fun solvePart2(instructions: List<Instruction>): Int {
var aim = 0
var horizontal = 0
var depth = 0
instructions.forEach {
val (command, value) = it
when (command) {
"forward" -> {
horizontal += value
depth += aim * value
}
"down" -> aim += value
"up" -> aim -= value
}
}
return horizontal * depth
}
| [
{
"class_path": "aesdeef__advent-of-code-2021__4561bcf/day02/DeepKt.class",
"javap": "Compiled from \"deep.kt\"\npublic final class day02.DeepKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method parseInput:()Ljava/util/List;\n 3: astore_0\n 4... |
joakimgy__tower-defence__0d6915b/src/main/kotlin/utils/AlgorithmAStar.kt | package utils
interface Graph {
interface Vertex
interface Edge<T : Vertex> {
val a: T
val b: T
}
}
abstract class AlgorithmAStar<V : Graph.Vertex, E : Graph.Edge<V>>(
private val edges: List<E>
) : Graph {
private val V.neighbors: List<V>
get() = edges
.asSequence()
.filter { it.a == this || it.b == this }
.map { listOf(it.a, it.b) }
.flatten()
.filterNot { it == this }
.distinct()
.toList()
private val E.cost: Double
get() = costToMoveThrough(this)
private fun findRoute(from: V, to: V): E? {
return edges.find {
(it.a == from && it.b == to) || (it.a == to && it.b == from)
}
}
private fun findRouteOrElseCreateIt(from: V, to: V): E {
return findRoute(from, to) ?: createEdge(from, to)
}
private fun generatePath(currentPos: V, cameFrom: Map<V, V>): List<V> {
val path = mutableListOf(currentPos)
var current = currentPos
while (cameFrom.containsKey(current)) {
current = cameFrom.getValue(current)
path.add(0, current)
}
return path.toList()
}
abstract fun costToMoveThrough(edge: E): Double
abstract fun createEdge(from: V, to: V): E
fun findPath(begin: V, end: V): Pair<List<V>, Double> {
val cameFrom = mutableMapOf<V, V>()
val openVertices = mutableSetOf(begin)
val closedVertices = mutableSetOf<V>()
val costFromStart = mutableMapOf(begin to 0.0)
val estimatedRoute = findRouteOrElseCreateIt(from = begin, to = end)
val estimatedTotalCost = mutableMapOf(begin to estimatedRoute.cost)
while (openVertices.isNotEmpty()) {
val currentPos = openVertices.minByOrNull { estimatedTotalCost.getValue(it) }!!
// Check if we have reached the finish
if (currentPos == end) {
// Backtrack to generate the most efficient path
val path = generatePath(currentPos, cameFrom)
// First Route to finish will be optimum route
return Pair(path, estimatedTotalCost.getValue(end))
}
// Mark the current vertex as closed
openVertices.remove(currentPos)
closedVertices.add(currentPos)
(currentPos.neighbors - closedVertices).forEach { neighbour ->
val routeCost = findRouteOrElseCreateIt(from = currentPos, to = neighbour).cost
val cost: Double = costFromStart.getValue(currentPos) + routeCost
if (cost < costFromStart.getOrDefault(neighbour, Double.MAX_VALUE)) {
if (!openVertices.contains(neighbour)) {
openVertices.add(neighbour)
}
cameFrom[neighbour] = currentPos
costFromStart[neighbour] = cost
val estimatedRemainingRouteCost = findRouteOrElseCreateIt(from = neighbour, to = end).cost
estimatedTotalCost[neighbour] = cost + estimatedRemainingRouteCost
}
}
}
throw IllegalArgumentException("No Path from Start $begin to Finish $end")
}
}
| [
{
"class_path": "joakimgy__tower-defence__0d6915b/utils/AlgorithmAStar.class",
"javap": "Compiled from \"AlgorithmAStar.kt\"\npublic abstract class utils.AlgorithmAStar<V extends utils.Graph$Vertex, E extends utils.Graph$Edge<V>> implements utils.Graph {\n private final java.util.List<E> edges;\n\n public... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.