kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
Neonader__Advent-of-Code-2022__4d0cb6f/src/main/kotlin/day08/DayEight.kt | package day08
import java.io.File
val fileList = File("puzzle_input/day08.txt").useLines { it.toList() }
val forest = fileList.map { row -> row.toList().map { col -> col.code } }
val width = forest[0].size
val height = forest.size
fun visible(row: Int, col: Int): Boolean {
val tree = forest[row][col]
if (
row == 0 || row == height ||
col == 0 || col == width
) return true
var visible = true
// visible from above
for (otherTree in forest.slice(0 until row))
visible = visible && otherTree[col] < tree
if (visible) return true
// visible from left
visible = true
for (otherTree in forest[row].slice(0 until col))
visible = visible && otherTree < tree
if (visible) return true
// visible from right
visible = true
for (otherTree in forest[row].slice(col + 1 until width))
visible = visible && otherTree < tree
if (visible) return true
// visible from below
visible = true
for (otherTree in forest.slice(row + 1 until height))
visible = visible && otherTree[col] < tree
return visible
}
fun scenicScore(row: Int, col: Int): Int {
val tree = forest[row][col]
var score = 1
if (
row == 0 ||
row == height ||
col == 0 ||
col == width
) return 0
// up distance
var distance = 0
for (otherTree in forest.slice(row - 1 downTo 0)) {
distance++
if (otherTree[col] >= tree) break
}
score *= distance
// left distance
distance = 0
for (otherTree in forest[row].slice(col - 1 downTo 0)) {
distance++
if (otherTree >= tree) break
}
score *= distance
// right distance
distance = 0
for (otherTree in forest[row].slice(col + 1 until width)) {
distance++
if (otherTree >= tree) break
}
score *= distance
// down distance
distance = 0
for (otherTree in forest.slice(row + 1 until height)) {
distance++
if (otherTree[col] >= tree) break
}
score *= distance
return score
}
fun a(): Int {
var sum = 0
for (row in 0 until height) for (col in 0 until width)
if (visible(row, col)) sum++
return sum
}
fun b(): Int {
var max = 0
for (row in 0 until height) for (col in 0 until width)
if (scenicScore(row, col) > max)
max = scenicScore(row, col)
return max
} | [
{
"class_path": "Neonader__Advent-of-Code-2022__4d0cb6f/day08/DayEightKt.class",
"javap": "Compiled from \"DayEight.kt\"\npublic final class day08.DayEightKt {\n private static final java.util.List<java.lang.String> fileList;\n\n private static final java.util.List<java.util.List<java.lang.Integer>> fores... |
Neonader__Advent-of-Code-2022__4d0cb6f/src/main/kotlin/day12/DayTwelve.kt | package day12
import java.io.File
import kotlin.math.min
val fileList = File("puzzle_input/day12.txt").readLines()
// the rows of 'S' and 'E' respectively
val startLine = fileList.indexOfFirst { line -> line.contains('S') }
val goalLine = fileList.indexOfFirst { line -> line.contains('E') }
// the coordinates of 'S' and 'E' respectively
val player = Pair(startLine, fileList[startLine].indexOf('S'))
val goal = Pair(goalLine, fileList[goalLine].indexOf('E'))
// the puzzle input with 'S' -> 'a' and 'E' -> 'z'
val heightMap = fileList.map { line -> line.replaceFirst('S', 'a').replaceFirst('E', 'z') }
// a map of the amount of steps required to reach a point
val stepMap = fileList.map { line -> line.map { 0 }.toMutableList() }
val stepBackMap = stepMap
fun step(row: Int, col: Int) {
val height = heightMap[row][col]
val steps = stepMap[row][col] + 1
// step up
if (row != 0 && (stepMap[row - 1][col] > steps || stepMap[row - 1][col] == 0) && heightMap[row - 1][col] <= height + 1) {
stepMap[row - 1][col] = steps
step(row - 1, col)
}
// step down
if (row != heightMap.lastIndex && (stepMap[row + 1][col] > steps || stepMap[row + 1][col] == 0) && heightMap[row + 1][col] <= height + 1) {
stepMap[row + 1][col] = steps
step(row + 1, col)
}
// step left
if (col != 0 && (stepMap[row][col - 1] > steps || stepMap[row][col - 1] == 0) && heightMap[row][col - 1] <= height + 1) {
stepMap[row][col - 1] = steps
step(row, col - 1)
}
// step right
if (col != heightMap[0].lastIndex && (stepMap[row][col + 1] > steps || stepMap[row][col + 1] == 0) && heightMap[row][col + 1] <= height + 1) {
stepMap[row][col + 1] = steps
step(row, col + 1)
}
}
fun stepBack(row: Int, col: Int) {
val height = heightMap[row][col]
val steps = stepMap[row][col] + 1
// step up
if (row != 0 && (stepBackMap[row - 1][col] > steps || stepMap[row - 1][col] == 0) && heightMap[row - 1][col] >= height - 1) {
stepBackMap[row - 1][col] = steps
stepBack(row - 1, col)
}
// step down
if (row != heightMap.lastIndex && (stepBackMap[row + 1][col] > steps || stepMap[row + 1][col] == 0) && heightMap[row + 1][col] >= height - 1) {
stepBackMap[row + 1][col] = steps
stepBack(row + 1, col)
}
// step left
if (col != 0 && (stepBackMap[row][col - 1] > steps || stepMap[row][col - 1] == 0) && heightMap[row][col - 1] >= height - 1) {
stepBackMap[row][col - 1] = steps
stepBack(row, col - 1)
}
// step right
if (col != heightMap[0].lastIndex && (stepBackMap[row][col + 1] > steps || stepMap[row][col + 1] == 0) && heightMap[row][col + 1] >= height - 1) {
stepBackMap[row][col + 1] = steps
stepBack(row, col + 1)
}
}
fun a(): Int {
step(player.first, player.second)
return stepMap[goal.first][goal.second]
}
fun b(): Int {
stepBack(goal.first, goal.second)
var minSteps = Int.MAX_VALUE
stepBackMap.forEachIndexed { row, line -> line.forEachIndexed { col, steps -> if (heightMap[row][col] == 'a' && steps != 0) minSteps = min(steps, minSteps) } }
return minSteps
} | [
{
"class_path": "Neonader__Advent-of-Code-2022__4d0cb6f/day12/DayTwelveKt.class",
"javap": "Compiled from \"DayTwelve.kt\"\npublic final class day12.DayTwelveKt {\n private static final java.util.List<java.lang.String> fileList;\n\n private static final int startLine;\n\n private static final int goalLin... |
NicoMincuzzi__adventofcode-2021__345b69c/src/main/kotlin/com/github/nicomincuzzi/Day2Dive.kt | package com.github.nicomincuzzi
import kotlin.math.abs
class Day2Dive {
fun horizontalPositionAndDepth(commands: List<Pair<String, Int>>): Int {
val result = hashMapOf<String, Int>()
for (command in commands) {
if (calculateHorizontalPosition(result, command)) continue
if (calculateDepth(result, command)) continue
when (command.first) {
"forward" -> result[command.first] = command.second
"down" -> result["depth"] = command.second * -1
else -> result["depth"] = command.second
}
}
return calculatePlannedCourse(result, "depth")
}
private fun calculateHorizontalPosition(result: HashMap<String, Int>, command: Pair<String, Int>): Boolean {
if (result.containsKey(command.first) && command.first == "forward") {
result[command.first] = result[command.first]?.plus(command.second)!!
return true
}
return false
}
fun horizontalPositionAndDepthPartTwo(commands: List<Pair<String, Int>>): Int {
val result = hashMapOf<String, Int>()
for (command in commands) {
if (calculateHorizontalPositionTwoPart(result, command)) continue
if (calculateDepth(result, command)) continue
when (command.first) {
"forward" -> {
result[command.first] = command.second
calculateAim(result, command)
}
"down" -> result["depth"] = command.second * -1
else -> result["depth"] = command.second
}
}
return calculatePlannedCourse(result, "aim")
}
private fun calculateHorizontalPositionTwoPart(result: HashMap<String, Int>, command: Pair<String, Int>): Boolean {
if (result.containsKey(command.first) && command.first == "forward") {
result[command.first] = result[command.first]?.plus(command.second)!!
calculateAim(result, command)
return true
}
return false
}
private fun calculateAim(result: HashMap<String, Int>, command: Pair<String, Int>) {
if (!result.containsKey("depth")) {
return
}
if (result.containsKey("aim")) {
result["aim"] = result["aim"]?.plus(result["depth"]!! * command.second)!!
return
}
result["aim"] = result["depth"]!! * command.second
}
private fun calculateDepth(result: HashMap<String, Int>, command: Pair<String, Int>): Boolean {
if (result.containsKey("depth")) {
var updateValue = 1
if (command.first == "down")
updateValue = -1
result["depth"] = result["depth"]?.plus(command.second * updateValue)!!
return true
}
return false
}
private fun calculatePlannedCourse(result: HashMap<String, Int>, value: String) =
result["forward"]!! * abs(result[value]!!)
}
| [
{
"class_path": "NicoMincuzzi__adventofcode-2021__345b69c/com/github/nicomincuzzi/Day2Dive.class",
"javap": "Compiled from \"Day2Dive.kt\"\npublic final class com.github.nicomincuzzi.Day2Dive {\n public com.github.nicomincuzzi.Day2Dive();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
keeferrourke__aoc2021__44677c6/src/main/kotlin/com/adventofcode/Day05.kt | package com.adventofcode
import kotlin.math.roundToInt
data class Point(val x: Int, val y: Int) : Comparable<Point> {
override fun compareTo(other: Point): Int {
val xeq = x.compareTo(other.x)
return if (xeq != 0) xeq else y.compareTo(other.y)
}
}
data class Line(val start: Point, val end: Point) {
val isHorizontal: Boolean = start.y == end.y
val isVertical: Boolean = start.x == end.x
private val slope: Double
get() =
if (isVertical) Double.NaN
else (start.y - end.y).toDouble() / (start.x - end.x)
val points: List<Point> by lazy {
when {
isVertical -> (minOf(start.y, end.y)..maxOf(start.y, end.y)).map { y -> Point(start.x, y) }
isHorizontal -> (minOf(start.x, end.x)..maxOf(start.x, end.x)).map { x -> Point(x, start.y) }
else -> interpolate()
}
}
private fun interpolate(): List<Point> {
val (x1, y1) = minOf(start, end)
val (x2, _) = maxOf(start, end)
return (x1..x2).map { x ->
Point(x, (y1 + (x - x1) * slope).roundToInt())
}
}
}
private fun parse(input: String): List<Line> = input.lines()
.map { line ->
val (a, _, b) = line.split(" ")
val (x1, y1) = a.split(",").map { it.toInt() }
val (x2, y2) = b.split(",").map { it.toInt() }
Line(Point(x1, y1), Point(x2, y2))
}
fun findVents(input: String, excludeDiagonals: Boolean) = when (excludeDiagonals) {
true -> findVents(input) { it.isVertical || it.isHorizontal }
false -> findVents(input) { true }
}
private fun findVents(input: String, filter: (Line) -> Boolean): Int = parse(input)
.filter(filter)
.flatMap { it.points }
.fold(mutableMapOf<Point, Int>()) { acc, point ->
acc.apply { merge(point, 1) { v, _ -> v + 1 } }
}
.count { it.value > 1 }
fun day05(input: String, args: List<String> = listOf("p1")) {
when (args.first().lowercase()) {
"p1" -> println(findVents(input, excludeDiagonals = true))
"p2" -> println(findVents(input, excludeDiagonals = false))
}
} | [
{
"class_path": "keeferrourke__aoc2021__44677c6/com/adventofcode/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class com.adventofcode.Day05Kt {\n private static final java.util.List<com.adventofcode.Line> parse(java.lang.String);\n Code:\n 0: aload_0\n 1: checkcast #... |
keeferrourke__aoc2021__44677c6/src/main/kotlin/com/adventofcode/Day06.kt | package com.adventofcode
private const val DAYS_TO_REPRODUCE = 7
private const val DAYS_TO_MATURE = 2
data class Generation(val distribution: Map<Int, Long>) {
private fun fillGaps(sparseMap: Map<Int, Long>): Map<Int, Long> {
val result = mutableMapOf<Int, Long>()
for (i in 0..DAYS_TO_MATURE + DAYS_TO_REPRODUCE) {
result[i] = sparseMap[i] ?: 0
}
return result
}
val size: Long = distribution.values.sum()
fun next(): Generation {
val generation = fillGaps(distribution).toSortedMap().values.toList()
val toReproduce = generation[0]
val nextGeneration = generation.drop(1).toMutableList()
nextGeneration[DAYS_TO_REPRODUCE - 1] += toReproduce
nextGeneration[DAYS_TO_REPRODUCE + DAYS_TO_MATURE - 1] = toReproduce
return Generation(nextGeneration.mapIndexed { idx, it -> idx to it }.toMap())
}
}
fun computeFishPopulation(input: String, afterDays: Int = 80) =
computeFishPopulation(parse(input), afterDays)
private fun computeFishPopulation(initialPopulation: List<Int>, afterDays: Int = 80): Long {
val populationFreqMap = initialPopulation.groupingBy { it }
.eachCount()
.map { (k, v) -> k to v.toLong() }
.toMap()
var generation = Generation(populationFreqMap)
for (i in 1..afterDays) {
generation = generation.next()
}
return generation.size
}
private fun parse(input: String): List<Int> =
input.lineSequence()
.flatMap { it.split(",") }
.map { it.toInt() }
.toList()
fun day06(input: String, args: List<String> = listOf()) {
when (args[0].lowercase()) {
"p1" -> computeFishPopulation(input, 80)
"p2" -> computeFishPopulation(input, 256)
}
} | [
{
"class_path": "keeferrourke__aoc2021__44677c6/com/adventofcode/Day06Kt.class",
"javap": "Compiled from \"Day06.kt\"\npublic final class com.adventofcode.Day06Kt {\n private static final int DAYS_TO_REPRODUCE;\n\n private static final int DAYS_TO_MATURE;\n\n public static final long computeFishPopulatio... |
keeferrourke__aoc2021__44677c6/src/main/kotlin/com/adventofcode/Day03.kt | package com.adventofcode
data class Diagnostic(val rowView: List<String>) {
private val colView: List<String> by lazy { readColumns(rowView) }
private fun readColumns(rows: List<String>): List<String> {
val columns = mutableMapOf<Int, String>()
for (row in rows) {
for (j in row.indices) {
columns.merge(j, "${row[j]}") { v, _ -> v + row[j] }
}
}
return columns.entries.map { it.value }
}
private fun mostCommonBit(bitString: String): Char? {
val counts = bitString.groupingBy { it }.eachCount()
return when {
counts['1']!! > counts['0']!! -> '1'
counts['0']!! > counts['1']!! -> '0'
else -> null
}
}
private fun negateBit(bit: Char) = when (bit) {
'1' -> '0'
'0' -> '1'
else -> error("Expected bit")
}
val powerConsumption: Int
get() {
val (gamma, epsilon) = colView.fold("" to "") { (gamma, epsilon), column ->
val most = mostCommonBit(column) ?: '1'
(gamma + most) to (epsilon + negateBit(most))
}
return gamma.toInt(2) * epsilon.toInt(2)
}
private fun o2RatingStrategy(bitString: String): Char =
mostCommonBit(bitString) ?: '1'
private fun co2RatingStrategy(bitString: String): Char =
negateBit(o2RatingStrategy(bitString))
private fun getRating(strategy: (String) -> Char): Int {
var readings = rowView
var step = 0
var columns = readColumns(readings)
do {
val bit = strategy(columns[step])
readings = readings.filter { it[step] == bit }
columns = readColumns(readings)
step += 1
} while (readings.size > 1)
return readings.first().toInt(2)
}
val o2Rating: Int get() = getRating(this::o2RatingStrategy)
val co2Rating: Int get() = getRating(this::co2RatingStrategy)
val lifeSupportRating: Int get() = o2Rating * co2Rating
}
fun day03(input: String, args: List<String> = listOf("p1")) {
when (args.first().lowercase()) {
"p1" -> println(Diagnostic(input.lines()).powerConsumption)
"p2" -> println(Diagnostic(input.lines()).lifeSupportRating)
}
} | [
{
"class_path": "keeferrourke__aoc2021__44677c6/com/adventofcode/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class com.adventofcode.Day03Kt {\n public static final void day03(java.lang.String, java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #... |
keeferrourke__aoc2021__44677c6/src/main/kotlin/com/adventofcode/Day02.kt | package com.adventofcode
/**
* [https://adventofcode.com/2021/day/2]
*/
enum class Command {
FORWARD, DOWN, UP;
companion object {
fun of(string: String) = when (string) {
"forward" -> FORWARD
"down" -> DOWN
"up" -> UP
else -> error("Unknown command")
}
}
}
private data class Position(val x: Int, val y: Int, val aim: Int)
fun commands(input: String): List<Pair<Command, Int>> = input.trim().lines()
.map {
val (first, second) = it.trim().split(" ", "\t")
Command.of(first) to second.toInt()
}
private fun diveBadly(pos: Position, command: Command, magnitude: Int): Position {
return when (command) {
Command.FORWARD -> pos.copy(x = pos.x + magnitude)
Command.UP -> pos.copy(y = pos.y - magnitude)
Command.DOWN -> pos.copy(y = pos.y + magnitude)
}
}
private fun diveCorrectly(pos: Position, command: Command, magnitude: Int): Position {
return when (command) {
Command.FORWARD -> pos.copy(x = pos.x + magnitude, y = pos.y + magnitude * pos.aim)
Command.UP -> pos.copy(aim = pos.aim - magnitude)
Command.DOWN -> pos.copy(aim = pos.aim + magnitude)
}
}
fun dive(commands: List<Pair<Command, Int>>, strategy: Strategy): Int = commands
.fold(Position(0, 0, 0)) { pos, (command, magnitude) ->
when (strategy) {
Strategy.BADLY -> diveBadly(pos, command, magnitude)
Strategy.CORRECTLY -> diveCorrectly(pos, command, magnitude)
}
}
.run { x * y }
enum class Strategy { BADLY, CORRECTLY }
fun day02(input: String, args: List<String> = listOf("p1")) {
when (args.first().lowercase()) {
"p1" -> println(dive(commands(input), Strategy.BADLY))
"p2" -> println(dive(commands(input), Strategy.CORRECTLY))
}
}
| [
{
"class_path": "keeferrourke__aoc2021__44677c6/com/adventofcode/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class com.adventofcode.Day02Kt {\n public static final java.util.List<kotlin.Pair<com.adventofcode.Command, java.lang.Integer>> commands(java.lang.String);\n Code:\n ... |
keeferrourke__aoc2021__44677c6/src/main/kotlin/com/adventofcode/Day01.kt | package com.adventofcode
/**
* [https://adventofcode.com/2021/day/1]
*/
fun sonarSweep(readings: Sequence<Int>, window: Int = 1): Int = readings
.windowed(window)
.map { it.sum() }
.fold(listOf<Pair<Int, DepthChange>>()) { acc, windowedSum ->
acc + (acc.lastOrNull()?.let { windowedSum to DepthChange.of(it.first, windowedSum) }
?: (windowedSum to DepthChange.NONE))
}
.count { it.second == DepthChange.INCREASE }
enum class DepthChange {
NONE, INCREASE, DECREASE;
companion object {
fun of(prev: Int, next: Int): DepthChange {
val change = next - prev
return when {
change > 0 -> INCREASE
change < 0 -> DECREASE
else -> NONE
}
}
}
}
fun day01(input: String, args: List<String> = listOf("1")) {
val readings = input.lineSequence().map { it.toInt() }
val window = args.first().toInt()
println(sonarSweep(readings, window))
}
| [
{
"class_path": "keeferrourke__aoc2021__44677c6/com/adventofcode/Day01Kt.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class com.adventofcode.Day01Kt {\n public static final int sonarSweep(kotlin.sequences.Sequence<java.lang.Integer>, int);\n Code:\n 0: aload_0\n 1: ldc ... |
wanglikun7342__Leetcode-Kotlin__d7fb5ff/src/main/kotlin/com/eric/leetcode/MaxAreaOfIsland.kt | package com.eric.leetcode
class MaxAreaOfIsland {
private lateinit var grid: Array<IntArray>
private lateinit var seen: Array<BooleanArray>
private var count = 0
var dr = intArrayOf(1, -1, 0, 0)
var dc = intArrayOf(0, 0, 1, -1)
private fun getArea(r: Int, c: Int): Int {
count++
if (r < 0 || r >= grid.size || c < 0 || c >= grid[0].size ||
seen[r][c] || grid[r][c] == 0)
return 0
seen[r][c] = true
return 1 + getArea(r + 1, c) + getArea(r - 1, c) + getArea(r, c - 1) + getArea(r, c + 1)
}
fun maxAreaOfIsland(grid: Array<IntArray>): Int {
this.grid = grid
seen = Array(grid.size) { BooleanArray(grid[0].size) }
var ans = 0
for (r in grid.indices) {
for (c in grid[0].indices) {
count = 0
ans = maxOf(ans, getArea(r, c))
println("r: $r, c: $c, count: $count")
}
}
return ans
}
fun maxAreaOfIsland2(grid: Array<IntArray>): Int {
this.grid = grid
seen = Array(grid.size) { BooleanArray(grid[0].size) }
var queue = mutableListOf<IntArray>()
var ans = 0
for (r in grid.indices) {
for (c in grid[0].indices) {
if (!seen[r][c] && grid[r][c] == 1) {
var shape = 0
seen[r][c] = true
queue.add(intArrayOf(r, c))
while (queue.isNotEmpty()) {
var node = queue.removeAt(0)
var rIndex = node[0]
var cIndex = node[1]
shape++
for (k in 0..3) {
val nr = rIndex + dr[k]
val nc = cIndex + dc[k]
if (nr in grid.indices &&
nc in grid[0].indices &&
grid[nr][nc] == 1 && !seen[nr][nc]) {
queue.add(intArrayOf(nr, nc))
seen[nr][nc] = true
}
}
}
ans = maxOf(ans, shape)
}
}
}
return ans
}
}
fun main(args: Array<String>) {
val grid = arrayOf(
intArrayOf(0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0),
intArrayOf(0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0),
intArrayOf(0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0),
intArrayOf(0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0),
intArrayOf(0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0),
intArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0),
intArrayOf(0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0),
intArrayOf(0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0))
val grid2 = arrayOf(intArrayOf(1, 1))
val maxAreaOfIsland = MaxAreaOfIsland()
println("result: " + maxAreaOfIsland.maxAreaOfIsland2(grid))
} | [
{
"class_path": "wanglikun7342__Leetcode-Kotlin__d7fb5ff/com/eric/leetcode/MaxAreaOfIslandKt.class",
"javap": "Compiled from \"MaxAreaOfIsland.kt\"\npublic final class com.eric.leetcode.MaxAreaOfIslandKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc ... |
wanglikun7342__Leetcode-Kotlin__d7fb5ff/src/main/kotlin/com/eric/leetcode/SatisfiabilityOfEqualityEquations.kt | package com.eric.leetcode
class SatisfiabilityOfEqualityEquations {
private class UnionFind(n: Int) {
private val parent: Array<Int> = Array(n) {
it
}
fun find(input: Int): Int {
var x = input
while (x != parent[x]) {
parent[x] = parent[parent[x]]
x = parent[x]
}
return x
}
fun union(x:Int, y:Int) {
val rootX = find(x)
val rootY = find(y)
parent[rootX] = rootY
}
fun isConnected(x: Int, y: Int): Boolean {
return find(x) == find(y)
}
}
fun equationsPossible(equations: Array<String>): Boolean {
val unionFind = UnionFind(26)
for (equation in equations) {
if (equation[1] == '=') {
val index1 = equation[0] - 'a'
val index2 = equation[3] - 'a'
unionFind.union(index1, index2)
}
}
for (equation in equations) {
if (equation[1] == '!') {
val index1 = equation[0] - 'a'
val index2 = equation[3] - 'a'
if (unionFind.isConnected(index1, index2)) {
// 如果合并失败,表示等式有矛盾,根据题意,返回 false
return false
}
}
}
// 如果检查了所有不等式,都没有发现矛盾,返回 true
return true
}
}
fun main(args: Array<String>) {
val equations = arrayOf("a==c","c==d","d!=a")
val satisfiabilityOfEqualityEquations = SatisfiabilityOfEqualityEquations()
println(satisfiabilityOfEqualityEquations.equationsPossible(equations))
} | [
{
"class_path": "wanglikun7342__Leetcode-Kotlin__d7fb5ff/com/eric/leetcode/SatisfiabilityOfEqualityEquations$UnionFind.class",
"javap": "Compiled from \"SatisfiabilityOfEqualityEquations.kt\"\nfinal class com.eric.leetcode.SatisfiabilityOfEqualityEquations$UnionFind {\n private final java.lang.Integer[] pa... |
wanglikun7342__Leetcode-Kotlin__d7fb5ff/src/main/kotlin/com/eric/leetcode/MinimumPathSum.kt | package com.eric.leetcode
class MinimumPathSum {
fun minPathSum(grid: Array<IntArray>): Int {
val dp = Array(grid.size) { Array(grid[0].size) { 0 } }
for (i in grid.indices) {
for (j in grid[0].indices) {
if (i == 0 && j == 0) {
dp[0][0] = grid[0][0]
} else if (i == 0) {
dp[0][j] = dp[0][j - 1] + grid[i][j]
} else if (j == 0) {
dp[i][0] = dp[i - 1][0] + grid[i][j]
} else {
dp[i][j] = minOf(dp[i - 1][j] + grid[i][j], dp[i][j - 1] + grid[i][j])
}
}
}
return dp[dp.lastIndex][dp[0].lastIndex]
}
}
fun main(args: Array<String>) {
val input = arrayOf(intArrayOf(1, 3, 1), intArrayOf(1, 5, 1), intArrayOf(4, 2, 1))
val minimumPathSum = MinimumPathSum()
println(minimumPathSum.minPathSum(input))
} | [
{
"class_path": "wanglikun7342__Leetcode-Kotlin__d7fb5ff/com/eric/leetcode/MinimumPathSumKt.class",
"javap": "Compiled from \"MinimumPathSum.kt\"\npublic final class com.eric.leetcode.MinimumPathSumKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc ... |
wanglikun7342__Leetcode-Kotlin__d7fb5ff/src/main/kotlin/com/eric/leetcode/FindTheShortestSuperstring.kt | package com.eric.leetcode
class FindTheShortestSuperstring {
fun shortestSuperstring(A: Array<String>): String {
val list = A.toMutableList()
while (list.size > 1) {
var x = 0
var y = 1
for (iv in list.withIndex()) {
for (index in iv.index + 1..list.lastIndex) {
if (getOverlapping(iv.value, list[index]) > getOverlapping(list[x], list[y])) {
x = iv.index
y = index
}
}
}
val a = list[x]
val b = list[y]
list.remove(a)
list.remove(b)
list.add(getOverlappingString(a, b))
}
return list.single()
}
private fun getOverlapping(x: String, y: String): Int {
return x.length + y.length - getOverlappingString(x, y).length
}
private fun getOverlappingString(str1: String, str2: String): String {
var result = ""
loop@ for (iv in str1.withIndex()) {
if (iv.value != str2[0]) {
continue
}
for (index in iv.index..str1.lastIndex) {
if (str1[index] != str2[index - iv.index]) {
continue@loop
}
}
result = str1 + str2.substring(str1.length-iv.index..str2.lastIndex)
break
}
loop@ for (iv in str2.withIndex()) {
if (iv.value != str1[0]) {
continue
}
for (index in iv.index..str2.lastIndex) {
if (str2[index] != str1[index - iv.index]) {
continue@loop
}
}
val newResult = str2 + str1.substring(str2.length-iv.index..str1.lastIndex)
if (newResult.length < result.length || result == "") {
result = newResult
}
break
}
if (result == "") {
result = str1 + str2
}
return result
}
}
fun main(args: Array<String>) {
val inputArray = arrayOf("sssv","svq","dskss","sksss")
val findTheShortestSuperstring = FindTheShortestSuperstring()
println(findTheShortestSuperstring.shortestSuperstring(inputArray))
} | [
{
"class_path": "wanglikun7342__Leetcode-Kotlin__d7fb5ff/com/eric/leetcode/FindTheShortestSuperstring.class",
"javap": "Compiled from \"FindTheShortestSuperstring.kt\"\npublic final class com.eric.leetcode.FindTheShortestSuperstring {\n public com.eric.leetcode.FindTheShortestSuperstring();\n Code:\n ... |
wanglikun7342__Leetcode-Kotlin__d7fb5ff/src/main/kotlin/com/eric/leetcode/ArithmeticSlicesIISubsequence.kt | package com.eric.leetcode
import java.util.HashMap
/**
* 暴力解法,DFS
*/
//class ArithmeticSlicesIISubsequence {
//
// var num = 0
//
//
// fun numberOfArithmeticSlices(A: IntArray): Int {
// num = 0
// for (index in A.indices) {
// dfs(A, index, Long.MIN_VALUE, 1)
// }
// return num
// }
//
// private fun dfs(A: IntArray, s: Int, gap: Long, arraySize: Int) {
// if (gap == Long.MIN_VALUE) {
// for (index in s + 1..A.lastIndex) {
//
// dfs(A, index, A[index].toLong() - A[s].toLong(), arraySize + 1)
// }
// } else {
// for (index in s + 1..A.lastIndex) {
// if (gap != A[index].toLong() - A[s].toLong()) {
// continue
// } else {
// if (arraySize >= 2) {
// num++
// }
// }
// dfs(A, index, gap, arraySize + 1)
// }
// }
// }
//}
class ArithmeticSlicesIISubsequence {
fun numberOfArithmeticSlices(A: IntArray): Int {
var result = 0
val cnt = Array(A.size, { mutableMapOf<Int, Int>()})
for (i in A.indices) {
for (j in 0 until i) {
val delta = A[i].toLong() - A[j].toLong()
if (delta < Integer.MIN_VALUE || delta > Integer.MAX_VALUE) {
continue
}
val diff = delta.toInt()
val sum = cnt[j].getOrDefault(diff, 0)
val origin = cnt[i].getOrDefault(diff, 0)
cnt[i].put(delta.toInt(), origin + sum + 1)
result += sum
}
}
return result
}
}
fun main(args: Array<String>) {
val input = intArrayOf(2,2,3,3,4,5)
val arithmeticSlicesIISubsequence = ArithmeticSlicesIISubsequence()
println(arithmeticSlicesIISubsequence.numberOfArithmeticSlices(input))
} | [
{
"class_path": "wanglikun7342__Leetcode-Kotlin__d7fb5ff/com/eric/leetcode/ArithmeticSlicesIISubsequence.class",
"javap": "Compiled from \"ArithmeticSlicesIISubsequence.kt\"\npublic final class com.eric.leetcode.ArithmeticSlicesIISubsequence {\n public com.eric.leetcode.ArithmeticSlicesIISubsequence();\n ... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day15.kt | package com.codelicia.advent2021
import java.util.*
import kotlin.math.min
class Day15(val input: String) {
// Split the input string into a 2D grid of integers
private val grid = input.split("\n").map { it ->
it.toCharArray().map { it.digitToInt() }
}
private val maxRow = grid.lastIndex
private val maxColumn = grid.last().lastIndex
fun part1(): Int {
val dp = Array(maxRow + 1) { IntArray(maxColumn + 1) { Int.MAX_VALUE } }
dp[0][0] = 0
for (i in 0..maxRow) {
for (j in 0..maxColumn) {
if (i > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j] + grid[i][j])
if (j > 0) dp[i][j] = min(dp[i][j], dp[i][j - 1] + grid[i][j])
}
}
return dp[maxRow][maxColumn]
}
fun part2(): Int {
val heap: PriorityQueue<Node> = PriorityQueue()
heap.add(Node(0, 0, 0))
val g = enlargeMap().split("\n").map { it ->
it.toCharArray().map { it.digitToInt() }
}
val visited: MutableSet<Pair<Int, Int>> = mutableSetOf()
while (heap.isNotEmpty()) {
val node = heap.poll()
val cost = node.cost
val x = node.x
val y = node.y
if (x == g.lastIndex && y == g.last().lastIndex) {
return cost
}
if (x to y in visited) continue
visited.add(x to y)
for ((nx, ny) in listOf(x to y-1, x to y+1, x-1 to y, x+1 to y)) {
if (nx < 0 || ny < 0 || nx > g.lastIndex || ny > g.last().lastIndex) continue
if (nx to ny in visited) continue
heap.add(Node(cost + g[nx][ny], nx, ny))
}
}
error("Could not find the shortest path")
}
fun Int.inc(i: Int): Int = if (this + i > 9) (this + i) % 9 else this+i
fun enlargeMap(): String {
// pad right
var s : String = ""
for (i in 0..maxRow) {
repeat(5) {
repeatIdx -> s += grid[i].map { it.inc(repeatIdx) }.joinToString("")
}
s += "\n"
}
// pad bottom
repeat(4) { rp ->
var paddedGrid = s.split("\n").map { it -> it.toCharArray().map { it.digitToInt() } }
for (i in 0..maxRow) {
s += paddedGrid[i].map { it.inc(rp+1) }.joinToString("") + "\n"
}
}
return s.trim()
}
private class Node(val cost: Int, val x: Int, val y: Int) : Comparable<Node> {
override fun compareTo(other: Node): Int = cost.compareTo(other.cost)
}
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day15.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class com.codelicia.advent2021.Day15 {\n private final java.lang.String input;\n\n private final java.util.List<java.util.List<java.lang.Integer>> grid;\n\n private ... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day03.kt | package com.codelicia.advent2021
import java.util.SortedMap
class Day03(private val input: List<String>) {
private val bitLength = input.first().length
private fun List<Int>.toInt() =
this.joinToString("").toInt(2)
private fun List<Int>.gamma() = this.toInt()
private fun List<Int>.epsilon() = this.map(::invertBit).toInt()
private fun SortedMap<Int, Int>.bit(): Int =
if (this.getValue(0) > this.getValue(1)) 0 else 1
private fun SortedMap<Int, Int>.invBit(): Int =
if (this.getValue(0) > this.getValue(1)) 1 else 0
private fun Set<String>.countBits(n: Int): List<SortedMap<Int, Int>> =
listOf(
this.map { v -> v[n].digitToInt() }
.groupingBy { it }
.eachCount()
.toSortedMap()
)
private val diagnosticReport = buildList {
repeat(bitLength) { i ->
val mostCommonBit = input
.groupingBy { it[i].digitToInt() }
.eachCount()
.maxBy { it.value }
.key
add(mostCommonBit)
}
}
private fun invertBit(n: Int) = if (n == 1) 0 else 1
private fun calculateRating(
remainingNumbers: Set<String>,
predicate: (String, Int, List<SortedMap<Int, Int>>) -> Boolean,
index: Int = 0,
): Int {
if (remainingNumbers.count() == 1) return remainingNumbers.first().toInt(radix = 2)
val sortedList = remainingNumbers.countBits(index)
val filteredNumbers = remainingNumbers.filterNot { v -> predicate(v, index, sortedList) }.toSet()
return calculateRating(filteredNumbers, predicate, index + 1)
}
fun part1(): Int = diagnosticReport.gamma() * diagnosticReport.epsilon()
fun part2(): Int {
val binaryNumbers = input.toSet()
val co2ScrubberRating = calculateRating(
binaryNumbers,
{ v, n, sl -> v[n].digitToInt() == sl[0].invBit() }
)
val oxygenGeneratorRating = calculateRating(
binaryNumbers,
{ v, n, sl -> v[n].digitToInt() == sl[0].bit() }
)
return oxygenGeneratorRating * co2ScrubberRating
}
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day03$countBits$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Collections.kt\"\npublic final class com.codelicia.advent2021.Day03$countBits$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lang.Integer, ja... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day13.kt | package com.codelicia.advent2021
import kotlin.math.max
class Day13(val input: String) {
fun solve(folds: Int): Int {
val (dots, fold) = input.split("\n\n")
val xs = dots.split("\n").map { it.split(",").map { s -> s.toInt() } }
val xMax = xs.maxOf { it[0] }
val yMax = xs.maxOf { it[1] }
var grid = Array(yMax + 1) { IntArray(xMax + 1) { 0 } }
for ((x, y) in xs) {
grid[y][x] = 1;
}
val foldInstructions = fold.split("\n").map { it.split(" ").last().split("=") }
foldInstructions.forEachIndexed { loop, inst ->
if (loop >= folds) return@forEachIndexed
val (direction, value) = inst
// Fold Y
if (direction == "y") {
val stay = grid.filterIndexed { k, _ -> k < value.toInt() }
val fold = grid.filterIndexed { k, _ -> k > value.toInt() }.reversed()
repeat(stay.size) { index ->
grid[index] = stay[index].mapIndexed { i, v -> max(fold[index][i], v) }.toIntArray()
}
grid = grid.copyOfRange(0, stay.lastIndex + 1)
}
// Fold X
if (direction == "x") {
val stay = grid.map { it.filterIndexed { k, _ -> k < value.toInt() } }
val fold = grid.map { it.filterIndexed { k, _ -> k > value.toInt() }.reversed() }
repeat(stay.size) { index ->
grid[index] = stay[index].mapIndexed { i, v -> max(fold[index][i], v) }.toIntArray()
}
}
}
return grid.sumOf { row -> row.sum() }
}
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day13.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class com.codelicia.advent2021.Day13 {\n private final java.lang.String input;\n\n public com.codelicia.advent2021.Day13(java.lang.String);\n Code:\n 0: aloa... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day08.kt | package com.codelicia.advent2021
class Day08(private val signals: List<String>) {
data class SegmentMap(
val map: Map<String, Int>,
val decodedNumber: Int
) {
companion object {
private fun String.order() =
this.split("").sortedDescending().joinToString(separator = "")
fun of(input: String): SegmentMap {
val (segment, numbers) = input.split(" | ")
val segmentSplit = segment.split(" ")
// Hacky ones
val sixDigits = segmentSplit.filter { it.length == 6 }
val fiveDigits = segmentSplit.filter { it.length == 5 }
// Easy discoverable
val one = segmentSplit.first { it.length == 2 }
val four = segmentSplit.first { it.length == 4 }
val seven = segmentSplit.first { it.length == 3 }
val eight = segmentSplit.first { it.length == 7 }
// Tricky
val nine = sixDigits.first { it.split("").containsAll(four.split("")) }
val zero = sixDigits.filter { !it.split("").containsAll(nine.split("")) }
.first { it.split("").containsAll(one.split("")) }
val six = sixDigits.filter { !it.split("").containsAll(nine.split("")) }
.first { !it.split("").containsAll(one.split("")) }
val three = fiveDigits.first { it.split("").containsAll(one.split("")) }
val five = fiveDigits.first { six.split("").containsAll(it.split("")) }
val two = fiveDigits.filter { !it.split("").containsAll(three.split("")) }
.first { !it.split("").containsAll(five.split("")) }
val map = mutableMapOf<String, Int>()
map[zero.order()] = 0
map[one.order()] = 1
map[two.order()] = 2
map[three.order()] = 3
map[four.order()] = 4
map[five.order()] = 5
map[six.order()] = 6
map[seven.order()] = 7
map[eight.order()] = 8
map[nine.order()] = 9
val number = numbers.split(" ").map {
map[it.order()]!!
}
return SegmentMap(map, number.joinToString(separator = "").toInt())
}
}
}
private val easyDigits = listOf(2, 3, 4, 7)
fun part1(): Int =
signals.map { it.split(" | ")[1].split(" ") }
.map { segments ->
segments.map {
when {
easyDigits.contains(it.length) -> 1
else -> 0
}
}
}.sumOf { it.sum() }
fun part2(): Int =
signals.map { SegmentMap.of(input = it) }
.sumOf { it.decodedNumber }
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day08.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class com.codelicia.advent2021.Day08 {\n private final java.util.List<java.lang.String> signals;\n\n private final java.util.List<java.lang.Integer> easyDigits;\n\n ... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day05.kt | package com.codelicia.advent2021
import kotlin.math.max
import kotlin.math.min
typealias Vent = Pair<Int, Int>
typealias VentLine = Pair<Vent, Vent>
class Day05(input: String) {
private val vents: List<VentLine> = input.trimIndent()
.lines()
.map { x ->
val xs = x.split(" -> ")
Vent(xs[0]) to Vent(xs[1])
}
fun part1(): Int = overlaps { vent -> vent.isDiagonal() }
fun part2(): Int = overlaps { false }
private fun VentLine.diagonalRange(): List<Vent> =
(if (first.second < second.second) horizontalRange().reversed() else horizontalRange())
.zip(if (first.first < second.first) verticalRange().reversed() else verticalRange())
private fun VentLine.horizontalRange(): IntRange =
min(first.first, second.first)..max(first.first, second.first)
private fun VentLine.verticalRange(): IntRange =
min(first.second, second.second)..max(first.second, second.second)
private fun VentLine.isDiagonal() =
first.first != second.first && first.second != second.second
private fun VentLine.isHorizontal() =
first.first != second.first
private fun VentLine.isVertical() =
first.second != second.second
private fun overlaps(predicate: (VentLine) -> Boolean): Int =
vents.map { line ->
return@map when {
predicate(line) -> emptyList<String>()
line.isDiagonal() -> line.diagonalRange().map { "${it.first},${it.second}" }
line.isHorizontal() -> line.horizontalRange().map { "$it,${line.first.second}" }
line.isVertical() -> line.verticalRange().map { "${line.first.first},$it" }
else -> emptyList<String>()
}
}
.flatten()
.groupingBy { it }
.eachCount()
.count { it.value > 1 }
companion object {
private fun Vent(s: String): Vent =
s.split(",").first().toInt() to s.split(",").last().toInt()
}
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class com.codelicia.advent2021.Day05Kt {\n}\n",
"javap_err": ""
},
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day05$Compan... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day16.kt | package com.codelicia.advent2021
class Day16(val input: String) {
private fun hexToBinary(input: String): List<Char> =
input.map { it.digitToInt(16).toString(2).padStart(4, '0') }.flatMap { it.toList() }
private var transmission: Iterator<Char> = hexToBinary(input).iterator()
fun Iterator<Char>.next(size: Int): String =
(1..size).map { next() }.joinToString("")
fun part1(): Long = getPacket(transmission).first
fun part2(): Long = getPacket(transmission).second
// Version -> Count
private fun getPacket(transmission: Iterator<Char>): Pair<Long, Long> {
val subPackets = mutableListOf<Long>()
val version = transmission.next(3).toInt(2)
val typeId = transmission.next(3).toInt(2)
var versionSum = version.toLong()
when (typeId) {
4 -> {
var keepCounting = true;
var count = ""
while (keepCounting) {
val lastBit = transmission.next(1)
if (lastBit == "0") keepCounting = false;
val rest = transmission.next(4)
count += rest
}
subPackets.add(count.toLong(2))
}
else -> {
val type = transmission.next(1).toInt(2)
when (type) {
0 -> { // 15
val subPacketsLength = transmission.next(15).toInt(2)
val subPacketBits = transmission.next(subPacketsLength).toCharArray()
val iterator = subPacketBits.iterator()
while (iterator.hasNext()) {
val p = getPacket(iterator)
versionSum += p.first
subPackets.add(p.second)
}
return versionSum to subPackets.operateBy(typeId)
}
1 -> { // 11
val subPacketsLength = transmission.next(11).toInt(2)
repeat (subPacketsLength) {
val p = getPacket(transmission)
versionSum += p.first
subPackets.add(p.second)
}
return versionSum to subPackets.operateBy(typeId)
}
}
}
}
return versionSum to subPackets.operateBy(typeId)
}
fun MutableList<Long>.operateBy(id: Int) =
when (id) {
0 -> sumOf { it }
1 -> reduce { acc, cur -> acc * cur }
2 -> minOf { it }
3 -> maxOf { it }
5 -> if (this[0] > this[1]) 1 else 0
6 -> if (this[0] < this[1]) 1 else 0
7 -> if (this[0] == this[1]) 1 else 0
else -> first()
}
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day16.class",
"javap": "Compiled from \"Day16.kt\"\npublic final class com.codelicia.advent2021.Day16 {\n private final java.lang.String input;\n\n private java.util.Iterator<java.lang.Character> transmission;\n\n public com.codel... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day09.kt | package com.codelicia.advent2021
import java.util.Stack
class Day09(private val input: List<String>) {
private fun parseHeightmap(xs: List<String>): List<List<Int>> =
xs.map { it.toCharArray().map(Char::digitToInt) }
private fun <T> List<List<T>>.getLocation(p: Pair<Int, Int>): T? =
this.getOrNull(p.first)?.getOrNull(p.second)
private fun Pair<Int, Int>.adjacentLocations() =
listOf(
this.first - 1 to this.second,
this.first + 1 to this.second,
this.first to this.second + 1,
this.first to this.second - 1
)
private fun Stack<Int>.riskLevel(): Int =
this.size + this.sum()
fun part1(): Int {
val heightmap = parseHeightmap(input)
val lowPoints = Stack<Int>()
heightmap.forEachIndexed { y, row ->
row.forEachIndexed { x, cell ->
var currentCellIsLower = true
for (adjacent in (y to x).adjacentLocations()) {
val adjacentCell = heightmap.getLocation(adjacent)
if (adjacentCell != null && adjacentCell <= cell) currentCellIsLower = false
}
if (currentCellIsLower) lowPoints.add(cell)
}
}
return lowPoints.riskLevel()
}
fun part2(): Int {
val heightmap = parseHeightmap(input)
val basins = mutableListOf<MutableList<Int>>()
heightmap.forEachIndexed { y, row ->
row.forEachIndexed { x, cell ->
var currentCellIsLower = true
for (adjacent in (y to x).adjacentLocations()) {
val adjacentCell = heightmap.getLocation(adjacent)
if (adjacentCell != null && adjacentCell < cell) currentCellIsLower = false
}
if (currentCellIsLower) {
basins.add(findSmallerFrom(heightmap, y to x, mutableSetOf())!!)
}
}
}
return basins.map { it.size }.sortedDescending().take(3).reduce {
x, y -> x * y
}
}
private fun findSmallerFrom(heightmap: List<List<Int>>, p: Pair<Int, Int>, visited: MutableSet<Pair<Int, Int>>): MutableList<Int>? {
val cell = heightmap.getLocation(p) ?: return null
val lowPoints = mutableListOf<Int>()
lowPoints.add(cell)
visited.add(p)
for (adjacent in p.adjacentLocations()) {
val adjacentCell = heightmap.getLocation(adjacent)
if (adjacentCell != null && adjacentCell > cell && adjacentCell != 9 && false == visited.contains(adjacent)) {
val x = findSmallerFrom(heightmap, adjacent, visited)
if (x != null) {
lowPoints.addAll(x)
}
}
}
return lowPoints
}
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day09.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class com.codelicia.advent2021.Day09 {\n private final java.util.List<java.lang.String> input;\n\n public com.codelicia.advent2021.Day09(java.util.List<java.lang.Stri... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day10.kt | package com.codelicia.advent2021
import java.util.Stack
class Day10(private val input: List<String>) {
private val scoreTable: Map<String, Long> = mapOf(
")" to 3L,
"]" to 57L,
"}" to 1197L,
">" to 25137L,
)
private val scoreTableForIncomplete: Map<String, Long> = mapOf(
"(" to 1L,
"[" to 2L,
"{" to 3L,
"<" to 4L,
)
private val openChar = listOf("(", "[", "{", "<")
private val closeChar = listOf(")", "]", "}", ">")
fun part1(): Long {
val queue = input.map { line -> ArrayDeque(line.split("")) }
val order = ArrayDeque<String>()
var points = 0L
for (line in queue) {
for (char in line.indices) {
val lineChar = line[char]
if (lineChar.isBlank()) continue
if (openChar.contains(lineChar)) {
order.add(lineChar)
} else {
val removed = order.removeLast()
if (openChar.zip(closeChar).first { it.first == removed }.second != lineChar) {
points += scoreTable[lineChar]!!
}
}
}
}
return points
}
fun part2(): Long {
val queue = input.map { line -> ArrayDeque(line.split("")) }
val closing = Stack<Long>()
for (line in queue) {
val order = ArrayDeque<String>()
var error = false
for (char in line.indices) {
val lineChar = line[char]
if (lineChar.isBlank() || error == true) continue
if (openChar.contains(lineChar)) {
order.add(lineChar)
} else {
val removed = order.removeLast()
if (openChar.zip(closeChar).first { it.first == removed }.second != lineChar) {
error = true
continue
}
}
}
if (order.isNotEmpty() && error == false) {
order.reversed().fold(0L) { acc, s ->
(acc * 5) + scoreTableForIncomplete[s]!!
}
.also { closing.add(it) }
}
}
closing.sort()
return closing[closing.size.floorDiv(2)]
}
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day10.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class com.codelicia.advent2021.Day10 {\n private final java.util.List<java.lang.String> input;\n\n private final java.util.Map<java.lang.String, java.lang.Long> score... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day12.kt | package com.codelicia.advent2021
import java.util.Stack
class Day12(mapOfTheRemainingCaves: List<String>) {
data class Vertex(val label: String)
private val map = mapOfTheRemainingCaves
.map { cave -> cave.split("-") }
.map { cave -> cave.first() to cave.last() }
private val graph = buildMap<Vertex, MutableList<Vertex>> {
for (i in map) {
this.putIfAbsent(Vertex(i.first), mutableListOf())
this.putIfAbsent(Vertex(i.second), mutableListOf())
this[Vertex(i.first)]!!.add(Vertex(i.second))
this[Vertex(i.second)]!!.add(Vertex(i.first))
}
}
fun part1(): Int = solve(fun(_) = true)
fun part2(): Int {
return solve(fun(visited: HashMap<String, Int>): Boolean {
return visited.toMap().filter { it.value > 1 }.filter { it.key.lowercase() == it.key }.values.isNotEmpty()
})
}
private fun solve(predicate: (HashMap<String, Int>) -> Boolean): Int {
val queue = Stack<Vertex>()
queue.add(Vertex("start"))
val results = mutableListOf<String>()
while (queue.isNotEmpty()) bfs(graph, predicate, queue, results, "start")
return results.size
}
private fun bfs(
graph: Map<Vertex, MutableList<Vertex>>,
predicate: (HashMap<String, Int>) -> Boolean,
queue: Stack<Vertex>,
results: MutableList<String>,
path: String,
visited: HashMap<String, Int> = hashMapOf()
) {
val vertex = queue.pop()
if (vertex.label == "end") {
results.add(path)
return
}
val count = visited.getOrElse(vertex.label) { 0 }
visited[vertex.label] = count + 1
val neighbours = graph[vertex]!!
for (neighbour in neighbours) {
if (neighbour.label != "start") {
val satisfiesPredicate = predicate(visited)
if (neighbour.label.lowercase() == neighbour.label && visited.contains(neighbour.label) && satisfiesPredicate == true) continue
queue.add(neighbour)
bfs(graph, predicate, queue, results, "$path,${neighbour.label}", HashMap(visited))
}
}
}
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day12.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class com.codelicia.advent2021.Day12 {\n private final java.util.List<kotlin.Pair<java.lang.String, java.lang.String>> map;\n\n private final java.util.Map<com.codeli... |
codelicia__adventofcode__df0cfd5/2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day04.kt | package com.codelicia.advent2021
class Day04(input: String) {
private val newline = "\n"
private val section = "\n\n"
private val sections = input.split(section)
private val draws = sections[0].trim().split(",").map(String::toInt)
private val cards : List<BingoBoard> = buildList {
for (i in 1 until sections.size) {
val numbers = sections[i].split(newline).map { it.split(" ").filter(String::isNotBlank).map(String::toInt) }
add(BingoBoard(numbers.map { row -> row.map { it to false } }))
}
}
class BingoBoard(private var numbers: List<List<Pair<Int, Boolean>>>) {
fun mark(number: Int) {
numbers = numbers.map {
it.map { pair ->
if (pair.first == number) pair.first to true else pair
}
}
}
fun unmarkedSum(): Int = numbers.flatten().filter { !it.second }.sumOf { it.first }
fun hasBingo(): Boolean {
val diagonal = List(numbers[0].size) { column -> List(numbers[0].size) { numbers[it][column] } }
val merge = numbers + diagonal
merge.forEach { row ->
row.forEach { _ ->
if (row.count { it.second } == row.size) return true
}
}
return false
}
}
private fun cardsScore(): MutableSet<Pair<Int, Int>> {
val cardsInBingoOrder = mutableSetOf<Pair<Int, Int>>()
draws.forEach { numberCalled ->
cards.forEach { it.mark(numberCalled) }
val isBingo = cards.filter { it.hasBingo() }
isBingo.forEach { card ->
if (false == cardsInBingoOrder.map { it.first }.contains(card.hashCode())) {
cardsInBingoOrder.add(card.hashCode() to numberCalled * card.unmarkedSum())
}
}
}
return cardsInBingoOrder
}
fun part1(): Int = cardsScore().first().second
fun part2(): Int = cardsScore().last().second
} | [
{
"class_path": "codelicia__adventofcode__df0cfd5/com/codelicia/advent2021/Day04.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class com.codelicia.advent2021.Day04 {\n private final java.lang.String newline;\n\n private final java.lang.String section;\n\n private final java.util.List<java.la... |
damcyb__BasicsOfCryptography__1dd03a2/StreamCiphers/src/main/kotlin/utils/BBSAnalyzer.kt | package utils
import java.math.BigDecimal
class BBSAnalyzer {
fun countOnes(bbs: String): Int = bbs.count { c: Char -> c == '1'}
fun countSeries(bbs: String, character: Char): Map<Int, Int> {
val occurrencesMap: MutableMap<Int, Int> = initializeOccurrencesMap()
var lastFoundChar: Char = 'x'
var counter: Int = 0
var position: Int = 0
bbs.forEach { char: Char ->
if ((char == lastFoundChar) and (position != bbs.length - 1)) {
counter++
} else if ((char == lastFoundChar) and (position == bbs.length - 1)) {
val flattenCounter = flatCounter(++counter)
if (lastFoundChar == character) {
incrementOccurrencesMap(occurrencesMap, flattenCounter)
}
counter = 0
} else if ((char != lastFoundChar) and (position == bbs.length - 1)) {
val flattenCounter = flatCounter(counter)
if (lastFoundChar == character) {
incrementOccurrencesMap(occurrencesMap, flattenCounter)
}
counter = 1
if (char == character) {
incrementOccurrencesMap(occurrencesMap, counter)
}
} else {
val flattenCounter = flatCounter(counter)
if ((position != 0) and (lastFoundChar == character)) {
incrementOccurrencesMap(occurrencesMap, flattenCounter)
}
lastFoundChar = char
counter = 1
}
position++
}
return occurrencesMap
}
fun checkIfLongSeriesExists(bbs: String): Boolean {
var counter: Int = 0
var lastFoundChar: Char = 'x'
bbs.forEach { char -> Char
counter = if (lastFoundChar == char) counter++ else 0
}
return counter >= 26
}
fun pokerize(bbs: String): Map<String, Int> {
val partitions: List<String> = divideStringIntoPartitions(bbs)
return groupPartitions(partitions)
}
fun calculatePokerScore(partitions: Map<String, Int>): BigDecimal {
val fraction = BigDecimal(16).divide(BigDecimal(5000))
return partitions.values
.sumOf { Math.pow(it.toDouble(), 2.0) }.toBigDecimal()
.multiply(fraction)
.minus(BigDecimal(5000))
}
private fun divideStringIntoPartitions(input: String): List<String> = input.chunked(4)
private fun groupPartitions(partitions: List<String>): Map<String, Int> =
partitions
.groupBy { it }
.mapValues { it.value.size }
private fun flatCounter(counter: Int): Int = if (counter < 6) counter else 6
private fun incrementOccurrencesMap(occurrencesMap: MutableMap<Int, Int>, counter: Int) {
occurrencesMap.merge(counter, 1, Int::plus)
}
private fun initializeOccurrencesMap() = mutableMapOf(
1 to 0,
2 to 0,
3 to 0,
4 to 0,
5 to 0,
6 to 0
)
} | [
{
"class_path": "damcyb__BasicsOfCryptography__1dd03a2/utils/BBSAnalyzer$incrementOccurrencesMap$1.class",
"javap": "Compiled from \"BBSAnalyzer.kt\"\nfinal class utils.BBSAnalyzer$incrementOccurrencesMap$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function2<java.lang... |
KentVu__CSProblems__52cb15d/model/src/main/java/com/kentvu/csproblems/Playground.kt | package com.kentvu.csproblems
import kotlin.reflect.full.hasAnnotation
import kotlin.reflect.full.memberFunctions
class Playground {
@Target(AnnotationTarget.FUNCTION)
annotation class AlgoFunction
@OptIn(ExperimentalStdlibApi::class)
val algos: List<String> get() {
return Playground::class.memberFunctions.filter {
it.hasAnnotation<AlgoFunction>()
}.map { it.name }.toList()
}
// https://www.hackerrank.com/challenges/insertion-sort/problem
@AlgoFunction
fun insertionSortDec(arr: IntArray): Int {
val max = arr.max()!!
val bit = BIT(max)
bit.update(arr[0], 1)
var swaps = 0
for (i in 1 until arr.size) {
// Get count of elements smaller than arr[i]
swaps += bit.sum(arr[i])
bit.update(arr[i], 1)
}
return swaps
}
@AlgoFunction
fun insertionSortAsc(arr: IntArray): Long {
val max = arr.max()!!
val bit = BIT(max)
bit.update(arr[arr.lastIndex], 1)
var swaps = 0L
for (i in arr.lastIndex - 1 downTo 0) {
swaps += bit.sum(arr[i] - 1) // Get count of elements smaller than arr[i]
bit.update(arr[i], 1)
}
return swaps
}
fun invoke(algo: String, vararg args: Any?): Any? {
return Playground::class.memberFunctions.first { it.name == algo }.run {
call(this@Playground, *args)
}
}
}
class BIT(max: Int) {
private val bit: Array<Int>
init {
//val max = arr.max()!!
// build
bit = Array(max + 1) { i -> 0 }
// for (v in arr) {
// bit[v]++
// }
}
fun update(v: Int, inc: Int) {
var index = v
// Traverse all ancestors and add 'val'
while (index <= bit.size - 1) {
// Add 'val' to current node of BI Tree
bit[index] += inc
// Update index to that of parent in update View
index += index and -index
}
}
fun sum(v: Int): Int {
var sum = 0 // Initialize result
// Traverse ancestors of BITree[index]
var index = v
while (index > 0) {
// Add current element of BITree to sum
sum += bit[index]
// Move index to parent node in getSum View
index -= index and -index
}
return sum
}
fun mark(v: Int) {
if (bit[v] == 0) {
update(v, 1)
}
}
}
| [
{
"class_path": "KentVu__CSProblems__52cb15d/com/kentvu/csproblems/Playground.class",
"javap": "Compiled from \"Playground.kt\"\npublic final class com.kentvu.csproblems.Playground {\n public com.kentvu.csproblems.Playground();\n Code:\n 0: aload_0\n 1: invokespecial #8 // M... |
arindamxd__kotlin-development__d9393b8/app/src/main/java/com/arindam/kotlin/ds/GFG.kt | package com.arindam.kotlin.ds
/**
* Kotlin program to find out all combinations of positive numbers that add up to given number.
*
* Created by <NAME> on 29/7/19.
*/
fun main() {
val k = 5
findCombinations(k)
}
/**
* @param arr array to store the combination
* @param index next location in array
* @param num given number
* @param reducedNum reduced number
*/
fun findCombinationsUtil(arr: IntArray, index: Int, num: Int, reducedNum: Int) {
// Base condition
if (reducedNum < 0)
return
// If combination is
// found, print it
if (reducedNum == 0) {
for (i in 0 until index)
print(arr[i].toString() + " ")
println()
return
}
// Find the previous number
// stored in arr[]. It helps
// in maintaining increasing
// order
val prev = if (index == 0) 1 else arr[index - 1]
// note loop starts from
// previous number i.e. at
// array location index - 1
for (k in prev..num) {
// next element of
// array is k
arr[index] = k
// call recursively with
// reduced number
findCombinationsUtil(arr, index + 1, num, reducedNum - k)
}
}
/**
* Function to find out all combinations of positive numbers that add up to given number.
* It uses findCombinationsUtil()
*
* @param n max n elements
*/
fun findCombinations(n: Int) {
// array to store the combinations
// It can contain max n elements
val arr = IntArray(n)
// find all combinations
findCombinationsUtil(arr, 0, n, n)
}
| [
{
"class_path": "arindamxd__kotlin-development__d9393b8/com/arindam/kotlin/ds/GFGKt.class",
"javap": "Compiled from \"GFG.kt\"\npublic final class com.arindam.kotlin.ds.GFGKt {\n public static final void main();\n Code:\n 0: iconst_5\n 1: istore_0\n 2: iload_0\n 3: invokestatic ... |
walkmansit__AlgoHub__2497fcc/src/main/kotlin/Algorithms/MaxSubarraySum/DivideAndConquer.kt | package Algorithms.MaxSubarraySum
class DivideAndConquer {
companion object {
fun findMaxSubarraySum(array: IntArray): Int {
return findMaxSubarrayDiapason(array, 0, array.size - 1).third
}
private fun findMaxSubarrayDiapason(
array: IntArray,
low: Int,
high: Int
): Triple<Int, Int, Int> { //left,right,sun
if (low == high)
return Triple(low, high, array[low])
val mid = (low + high) / 2
val leftValues = findMaxSubarrayDiapason(array, low, mid)
val rightValues = findMaxSubarrayDiapason(array, mid + 1, high)
val middleValues = findMaxSubarrayCrosslines(array, low, mid, high)
return if (leftValues.third >= rightValues.third && leftValues.third >= middleValues.third)
leftValues
else if (rightValues.third >= leftValues.third && rightValues.third >= middleValues.third)
rightValues
else middleValues
}
private fun findMaxSubarrayCrosslines(
array: IntArray,
low: Int,
mid: Int,
high: Int
): Triple<Int, Int, Int> { //left,right,sun
var leftSum = Int.MIN_VALUE
var rightSum = Int.MIN_VALUE
var leftIdx = mid
var rightIdx = mid + 1
if (low == high)
return Triple(low, high, array[low])
var sum = 0
for (i in mid downTo low) {
sum += array[i]
if (sum > leftSum) {
leftIdx = i
leftSum = sum
}
}
sum = 0
for (i in mid + 1..high) {
sum += array[i]
if (sum > rightSum) {
rightIdx = i
rightSum = sum
}
}
return Triple(leftIdx, rightIdx, leftSum + rightSum)
}
}
}
| [
{
"class_path": "walkmansit__AlgoHub__2497fcc/Algorithms/MaxSubarraySum/DivideAndConquer$Companion.class",
"javap": "Compiled from \"DivideAndConquer.kt\"\npublic final class Algorithms.MaxSubarraySum.DivideAndConquer$Companion {\n private Algorithms.MaxSubarraySum.DivideAndConquer$Companion();\n Code:\... |
CX-Checkout__rvpk01__9209c41/src/main/kotlin/befaster/solutions/Item.kt | package befaster.solutions
sealed abstract class Item(open val price: Price)
object A : Item(50)
object B : Item(30)
object C : Item(20)
object D : Item(15)
object E : Item(40)
object Invalid : Item(-1)
typealias Basket = List<Item>
typealias Price = Int
interface Deal {
val howManyYouNeedToBuy: Int
}
data class NAtPriceOf(val item: Item, override val howManyYouNeedToBuy: Int, val priceOf: Price): Deal {
fun reducedPrice(numberOfItems: Int): Price {
return (numberOfItems % howManyYouNeedToBuy) * item.price + (numberOfItems / howManyYouNeedToBuy) * priceOf
}
}
data class BuyItemGetItemFree(
val whatYouGetForFree: Item,
val whatYouNeedToBuy: Item,
override val howManyYouNeedToBuy: Int,
val howManyYouGetForFree: Int) : Deal {
fun reducedPrice(howManyYouHave: Int, howManyOfOther: Int): Price {
val numberOfDiscounts = howManyOfOther / howManyYouNeedToBuy
val result = ((howManyYouHave - numberOfDiscounts) * whatYouGetForFree.price)
return Math.max(0, result)
}
}
object NoDeal: Deal {
override val howManyYouNeedToBuy: Int = 1
}
val offers = mapOf(
A to listOf(NAtPriceOf(A, 3,130), NAtPriceOf(A, 5, 200)),
B to listOf(BuyItemGetItemFree(B, E, 2, 1), NAtPriceOf(B, 2, 45))
)
class Checkout(basket: Basket) {
companion object {
fun priceFor(items: String): Price = Checkout(Scanner().getBasketFor(items)).total
}
val total: Price = if(basket.contains(Invalid)) -1 else {
val groupedItems = basket.groupBy { it }
val priceForItems = groupedItems.map { group ->
val deals = offers[group.key] ?: listOf(NoDeal)
val reducedPrice = getPriceFor(group.key, group.value.size, deals, groupedItems)
reducedPrice.min()!!
}.sum()
priceForItems
}
fun getPriceFor(item: Item, numberOfItems: Int, deals: List<Deal>, group: Map<Item, List<Item>>): List<Int> {
fun go(list: List<Item>): List<Int> {
return when {
list.isEmpty() -> listOf(0)
else -> (listOf(numberOfItems) + deals.map { it.howManyYouNeedToBuy }).flatMap { howMany ->
deals.map {
when (it) {
is NAtPriceOf -> it.reducedPrice(howMany) + go(list.drop(howMany)).min()!!
is BuyItemGetItemFree -> it.reducedPrice(list.size, group[it.whatYouNeedToBuy].orEmpty().size) + go(list.drop(it.howManyYouNeedToBuy)).min()!!
else -> item.price * howMany + go(list.drop(howMany)).min()!!
}
}
}
}
}
return go(group[item].orEmpty())
}
}
class Scanner {
fun getBasketFor(itemsScanned: String): Basket = itemsScanned.map {
when (it) {
'A' -> A
'B' -> B
'C' -> C
'D' -> D
'E' -> E
else -> Invalid
}
}
} | [
{
"class_path": "CX-Checkout__rvpk01__9209c41/befaster/solutions/Item.class",
"javap": "Compiled from \"Item.kt\"\npublic abstract class befaster.solutions.Item {\n private final int price;\n\n private befaster.solutions.Item(int);\n Code:\n 0: aload_0\n 1: invokespecial #9 ... |
Sardorbekcyber__aoc-2022-in-kotlin__56f29c8/src/day04/Day04.kt | package day04
import java.io.File
fun main() {
fun part1(input: String) : Long {
val data = input.split("\n").sumOf { line ->
val parts = line.split(",")
val firstPart = parts[0].split("-")
val secondPart = parts[1].split("-")
val firstStart = firstPart.first().toInt()
val firstEnd = firstPart.last().toInt()
val secondStart = secondPart.first().toInt()
val secondEnd = secondPart.last().toInt()
when {
firstStart <= secondStart && firstEnd >= secondEnd -> 1L
firstStart >= secondStart && firstEnd <= secondEnd -> 1L
else -> 0L
}
}
return data
}
fun part2(input: String) : Long {
val data = input.split("\n").sumOf { line ->
val parts = line.split(",")
val firstPart = parts[0].split("-")
val secondPart = parts[1].split("-")
val firstStart = firstPart.first().toInt()
val firstEnd = firstPart.last().toInt()
val secondStart = secondPart.first().toInt()
val secondEnd = secondPart.last().toInt()
when {
secondEnd < firstStart -> 0L
firstEnd < secondStart -> 0L
else -> 1L
}
}
return data
}
val testInput = File("src/day04/Day04_test.txt").readText()
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 2L)
check(part2(testInput) == 4L)
val input = File("src/day04/Day04.txt").readText()
println(part1(input))
println(part2(input))
} | [
{
"class_path": "Sardorbekcyber__aoc-2022-in-kotlin__56f29c8/day04/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class day04.Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ... |
Sardorbekcyber__aoc-2022-in-kotlin__56f29c8/src/day03/Day03.kt | package day03
import java.io.File
fun main() {
val letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun part1(input: String) : Int {
val data = input.split("\n")
var sum = 0
for (line in data) {
val secondHalf = line.substring(line.length/2)
for (char in line){
if (secondHalf.contains(char, false)){
sum += letters.indexOf(char) + 1
break
}
}
}
return sum
}
fun part2(input: String) : Int {
val data = input.split("\n").chunked(3)
var sum = 0
for (group in data){
val firstSet = mutableSetOf<Char>()
val secondSet = mutableSetOf<Char>()
val thirdSet = mutableSetOf<Char>()
var setNum = 1
val groupAll = group.joinToString(",")
for (char in groupAll){
if (char == ','){
setNum++
continue
}
when (setNum) {
1 -> firstSet.add(char)
2 -> secondSet.add(char)
else -> thirdSet.add(char)
}
}
for (char in firstSet){
if (secondSet.contains(char) && thirdSet.contains(char)){
sum += letters.indexOf(char) + 1
break
}
}
}
return sum
}
val testInput = File("src/day03/Day03_test.txt").readText()
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = File("src/day03/Day03.txt").readText()
println(part1(input))
println(part2(input))
} | [
{
"class_path": "Sardorbekcyber__aoc-2022-in-kotlin__56f29c8/day03/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class day03.Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX... |
Sardorbekcyber__aoc-2022-in-kotlin__56f29c8/src/day02/Day02.kt | package day02
import java.io.File
fun main() {
fun part1(input: String) : Long {
val lostSet = setOf("A Z", "B X", "C Y")
val winSet = setOf("A Y", "B Z", "C X")
val drawSet = setOf("A X", "B Y", "C Z")
val scoreMap = mapOf('X' to 1, 'Y' to 2, 'Z' to 3)
val data = input.split("\n").sumOf {
val gameScore = when(it){
in lostSet -> 0L
in drawSet -> 3L
in winSet -> 6L
else -> throw IllegalArgumentException()
}
gameScore + scoreMap.getOrDefault(it.last(), 0)
}
return data
}
fun part2(input: String) : Long {
val winSet = setOf("A B", "B C", "C A")
val lostSet = setOf("A C", "B A", "C B")
val drawSet = setOf("A A", "B B", "C C")
val scoreMap = mapOf('A' to 1, 'B' to 2, 'C' to 3)
val data = input.split("\n").sumOf { game ->
val (gameScore, myScore) = when(game.last()){
'X' -> 0L to scoreMap.getOrDefault(lostSet.first { it.first() == game.first() }.last(), 0)
'Y' -> 3L to scoreMap.getOrDefault(drawSet.first { it.first() == game.first() }.last(), 0)
'Z' -> 6L to scoreMap.getOrDefault(winSet.first { it.first() == game.first() }.last(), 0)
else -> throw IllegalArgumentException()
}
gameScore + myScore
}
return data
}
val testInput = File("src/day02/Day02_test.txt").readText()
println(part2(testInput))
check(part2(testInput) == 12L)
val input = File("src/day02/Day02.txt").readText()
println(part1(input))
println(part2(input))
} | [
{
"class_path": "Sardorbekcyber__aoc-2022-in-kotlin__56f29c8/day02/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class day02.Day02Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ... |
laech__intellij-jump__a404fe4/src/main/java/com/gitlab/lae/intellij/jump/Tree.kt | package com.gitlab.lae.intellij.jump
data class TreePath<out K>(val keys: List<K>)
operator fun <K> TreePath<K>.plus(key: K) = TreePath(keys + key)
sealed class Tree<out K, out V>
data class TreeLeaf<out V>(val value: V) : Tree<Nothing, V>() {
override fun toString() = "TreeLeaf($value)"
}
data class TreeNode<out K, out V>(val nodes: List<Pair<K, Tree<K, V>>>) : Tree<K, V>() {
constructor(vararg nodes: Pair<K, Tree<K, V>>) : this(nodes.toList())
override fun toString() = "TreeNode(\n ${nodes.joinToString(",\n").replace("\n", "\n ")}\n)"
}
val emptyPath = TreePath<Nothing>(emptyList())
val emptyTree = TreeNode<Nothing, Nothing>(emptyList())
fun <V> treeOf(items: Collection<V>, nodeSize: Int): Tree<Int, V> =
join(items.map(::TreeLeaf).toList(), nodeSize)
private fun <V> join(nodes: Collection<Tree<Int, V>>, nodeSize: Int): Tree<Int, V> =
when {
nodeSize < 1 -> throw IllegalArgumentException("nodeSize=$nodeSize")
nodes.size <= 1 -> nodes.firstOrNull() ?: emptyTree
nodes.size <= nodeSize ->
nodes.withIndex().map { (index, value) -> index to value }.let(::TreeNode)
else ->
nodes
.asSequence()
.chunked(nodeSize)
.map { join(it, nodeSize) }
.let { join(it.toList(), nodeSize) }
}
fun <K, V, R> Tree<K, V>.mapKey(mapper: (K) -> R): Tree<R, V> =
when (this) {
is TreeLeaf -> this
is TreeNode ->
nodes.map { (key, value) -> mapper(key) to value.mapKey(mapper) }.let(::TreeNode)
}
fun <K, V> Tree<K, V>.asSequence(path: TreePath<K> = emptyPath): Sequence<Pair<TreePath<K>, V>> =
when (this) {
is TreeLeaf -> sequenceOf(path to value)
is TreeNode -> nodes.asSequence().flatMap { (key, value) -> value.asSequence(path + key) }
}
operator fun <K, V> Tree<K, V>.get(key: K): Tree<K, V>? =
when (this) {
is TreeNode -> nodes.firstOrNull { (k) -> k == key }?.second
else -> null
}
| [
{
"class_path": "laech__intellij-jump__a404fe4/com/gitlab/lae/intellij/jump/TreeKt.class",
"javap": "Compiled from \"Tree.kt\"\npublic final class com.gitlab.lae.intellij.jump.TreeKt {\n private static final com.gitlab.lae.intellij.jump.TreePath emptyPath;\n\n private static final com.gitlab.lae.intellij.... |
codetreats__aoc2023__3cd4aa5/src/main/kotlin/net/codetreats/aoc/common/Dijkstra.kt | package net.codetreats.aoc.common
class Dijkstra {
/**
* Calculate the minimum distance between startNode and endNode.
* The algorithm expects, that there are exactly [nodeCount] nodes with names from 0 to [nodeCount - 1]
* @param: nodeCount the total number of nodes
* @param: startNOde the name of the start node
* @param: endNode the name of the end node
* @param: edges defines all edges. An edge starts at the key of the map and ends in 0 .. n other nodes.
* A target node is of type [EdgeDistance],
* which contains the name of the target node and the distance between the key and the target
*/
fun shortestPath(nodeCount: Int, startNode: Int, endNode: Int, edges: Map<Int, Set<EdgeDistance>>) : DijkstraResult {
val distances = IntArray(nodeCount) { Integer.MAX_VALUE}
val preds = IntArray(nodeCount) { -1 }
distances[startNode] = 0
val queue : MutableList<Int> = mutableListOf(0)
val added = mutableSetOf<Int>(0)
while(queue.isNotEmpty()) {
val u : Int = queue.minBy { distances[it] }!!
queue.remove(u)
if (u == endNode) {
return DijkstraResult(preds, distances[u])
}
edges[u]!!.forEach { v ->
if (v.node !in queue && v.node !in added) {
queue.add(v.node)
added.add(v.node)
}
if (v.node in queue) {
val newDistance = distances[u] + v.weight
if (newDistance < distances[v.node]) {
distances[v.node] = newDistance
preds[v.node] = u
}
}
}
}
throw IllegalStateException("Algorithm finished without result")
}
}
data class EdgeDistance(val node: Int, val weight: Int)
data class DijkstraResult(val preds: IntArray, val length: Int) {
fun shortestPath(from: Int, to: Int) : List<Int> {
val path = mutableListOf(to)
while (path.last() != from) {
path.add(preds[path.last()])
}
return path.reversed()
}
} | [
{
"class_path": "codetreats__aoc2023__3cd4aa5/net/codetreats/aoc/common/Dijkstra.class",
"javap": "Compiled from \"Dijkstra.kt\"\npublic final class net.codetreats.aoc.common.Dijkstra {\n public net.codetreats.aoc.common.Dijkstra();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
codetreats__aoc2023__3cd4aa5/src/main/kotlin/net/codetreats/aoc/day02/Game.kt | package net.codetreats.aoc.day02
import kotlin.math.max
data class Game(val id: Int, val extractions: List<Extraction>) {
fun isPossible(input: Map<String, Int>) =
extractions.map { it.dices }.flatten().none { input[it.color]!! < it.amount }
fun power(): Int {
val min = mutableMapOf("green" to 0, "red" to 0, "blue" to 0)
extractions.map { it.dices }.flatten().forEach { dices ->
min[dices.color] = max(dices.amount, min[dices.color]!!)
}
return min.map { it.value }.reduce { min1, min2 -> min1 * min2 }
}
companion object {
fun from(line: String): Game {
val id = line.split(":")[0].split(" ")[1].toInt()
val extractions: List<Extraction> = line.split(":")[1].trim().split(";").map { Extraction.from(it.trim()) }
return Game(id, extractions)
}
}
}
data class Extraction(val dices: List<ColorDices>) {
companion object {
fun from(part: String): Extraction =
Extraction(part.trim().split(",").map { ColorDices.from(it.trim()) })
}
}
data class ColorDices(val color: String, val amount: Int) {
companion object {
fun from(part: String): ColorDices {
val amount = part.split(" ")[0].trim().toInt()
val color = part.split(" ")[1].trim()
return ColorDices(color, amount)
}
}
} | [
{
"class_path": "codetreats__aoc2023__3cd4aa5/net/codetreats/aoc/day02/Game.class",
"javap": "Compiled from \"Game.kt\"\npublic final class net.codetreats.aoc.day02.Game {\n public static final net.codetreats.aoc.day02.Game$Companion Companion;\n\n private final int id;\n\n private final java.util.List<n... |
ssynhtn__leetcode__511f658/src/com/ssynhtn/medium/UniquePermutations.kt | package com.ssynhtn.medium
import java.util.*
class UniquePermutations {
fun permuteUnique(nums: IntArray): List<List<Int>> {
nums.sort()
val collection = mutableListOf<List<Int>>()
permute(nums, 0, collection)
return collection
}
private fun permute(nums: IntArray, fixCount: Int, collection: MutableList<List<Int>>) {
if (!checkIncreasing(nums, fixCount)) {
return
}
if (fixCount == nums.size) {
collection.add(nums.toList())
return
}
permute(nums, fixCount + 1, collection)
val index = fixCount
for (i in index + 1 until nums.size) {
if (nums[i] == nums[i - 1]) continue
shiftRight(nums, index, i)
permute(nums, fixCount + 1, collection)
shiftLeft(nums, index, i)
}
}
private fun shiftLeft(nums: IntArray, index: Int, i: Int) {
val temp = nums[index]
System.arraycopy(nums, index + 1, nums, index, i - index)
nums[i] = temp
}
private fun shiftRight(nums: IntArray, index: Int, i: Int) {
val temp = nums[i]
System.arraycopy(nums, index, nums, index + 1, i - index)
nums[index] = temp
}
private fun checkIncreasing(nums: IntArray, fixCount: Int): Boolean {
for (i in fixCount until nums.size - 1) {
if (nums[i] > nums[i + 1]) {
// println("bad " + nums.toList() + ", fixCount " + fixCount)
return false;
}
}
// println("good " + nums.toList() + ", fixCount " + fixCount)
return true;
}
fun swap(nums: IntArray, i: Int, j: Int) {
val temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
}
fun main(args: Array<String>) {
val nums = intArrayOf(0, 0, 1, 2)
val res = UniquePermutations().permuteUnique(nums)
println(res)
} | [
{
"class_path": "ssynhtn__leetcode__511f658/com/ssynhtn/medium/UniquePermutationsKt.class",
"javap": "Compiled from \"UniquePermutations.kt\"\npublic final class com.ssynhtn.medium.UniquePermutationsKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc ... |
ssynhtn__leetcode__511f658/src/com/ssynhtn/medium/NQueens.kt | package com.ssynhtn.medium
class NQueens {
fun solveNQueens2(n: Int): Int {
val table = Array<CharArray>(n, {i -> CharArray(n)})
for (i in 0 until n) {
for (j in 0 until n) {
table[i][j] = '.'
}
}
return putQueens(table, 0)
}
private fun putQueens(table: Array<CharArray>, fixedRows: Int): Int {
if (fixedRows == table.size) {
return 1
}
var count = 0
for (col in 0 until table.size) {
if (checkHasConflictWithPrev(table, fixedRows, col)) continue
table[fixedRows][col] = 'Q'
count += putQueens(table, fixedRows + 1)
table[fixedRows][col] = '.'
}
return count
}
fun solveNQueens(n: Int): List<List<String>> {
val table = Array<CharArray>(n, {i -> CharArray(n)})
for (i in 0 until n) {
for (j in 0 until n) {
table[i][j] = '.'
}
}
val collection = mutableListOf<List<String>>()
putQueens(table, 0, collection)
return collection
}
private fun putQueens(table: Array<CharArray>, fixedRows: Int, collection: MutableList<List<String>>) {
if (fixedRows == table.size) {
collection.add(table.map { chs -> String(chs) })
return
}
for (col in 0 until table.size) {
if (checkHasConflictWithPrev(table, fixedRows, col)) continue
table[fixedRows][col] = 'Q'
putQueens(table, fixedRows + 1, collection)
table[fixedRows][col] = '.'
}
}
private fun checkHasConflictWithPrev(table: Array<CharArray>, row: Int, col: Int): Boolean {
for (i in 0 until row) {
var j = col - row + i
if (j >= 0 && j < table.size) {
if (table[i][j] == 'Q') {
return true
}
}
j = row + col - i
if (j >= 0 && j < table.size) {
if (table[i][j] == 'Q') {
return true
}
}
j = col
if (j >= 0 && j < table.size) {
if (table[i][j] == 'Q') {
return true
}
}
}
return false
}
}
fun main(args: Array<String>) {
println(NQueens().solveNQueens2(4))
// var queenPlacements = NQueens().solveNQueens(4)
// for (table in queenPlacements) {
// println(table.joinToString("\n"))
// println()
// }
} | [
{
"class_path": "ssynhtn__leetcode__511f658/com/ssynhtn/medium/NQueensKt.class",
"javap": "Compiled from \"NQueens.kt\"\npublic final class com.ssynhtn.medium.NQueensKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // Strin... |
ssynhtn__leetcode__511f658/src/com/ssynhtn/medium/MaximumSubarray.kt | package com.ssynhtn.medium
class MaximumSubarray {
fun maxSubArrayDivConquer(nums: IntArray): Int {
return maxSubArrayDivConquer(nums, 0, nums.size)[0] // max, left max, right max, total, each requiring at least length one
}
// end > start
fun maxSubArrayDivConquer(nums: IntArray, start: Int, end: Int): IntArray {
if (end - start == 1) {
val ans = nums[start]
return intArrayOf(ans, ans, ans, ans)
}
val mid = (start + end) / 2
val max1 = maxSubArrayDivConquer(nums, start, mid)
val max2 = maxSubArrayDivConquer(nums, mid, end)
// val total = max1[3] + max2[3]
// val leftMax = Math.max(max1[1], max1[3] + max2[1])
// val rightMax = Math.max(max2[2], max2[3] + max1[2])
// val max = Math.max(max1[0], Math.max(max2[0], max1[2] + max2[1]))
max1[0] = Math.max(max1[0], Math.max(max2[0], max1[2] + max2[1]))
max1[1] = Math.max(max1[1], max1[3] + max2[1])
max1[2] = Math.max(max2[2], max2[3] + max1[2])
max1[3] = max1[3] + max2[3]
return max1
}
fun maxSubArray(nums: IntArray): Int {
var max = Int.MIN_VALUE
var sum = 0
for (num in nums) {
if (num > max) {
max = num
}
sum += num
if (sum > max) {
max = sum
}
if (sum < 0) {
sum = 0
}
}
return max
}
}
fun main(args: Array<String>) {
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(-2,1,-3,4,-1,2,1,-5,4)))
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(1)))
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(0)))
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(-1)))
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(-2147483647)))
} | [
{
"class_path": "ssynhtn__leetcode__511f658/com/ssynhtn/medium/MaximumSubarray.class",
"javap": "Compiled from \"MaximumSubarray.kt\"\npublic final class com.ssynhtn.medium.MaximumSubarray {\n public com.ssynhtn.medium.MaximumSubarray();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
ssynhtn__leetcode__511f658/src/com/ssynhtn/medium/Permutations.kt | package com.ssynhtn.medium
class Permutations {
var swapCount = 0;
fun permute(nums: IntArray): List<List<Int>> {
val collect = mutableListOf<List<Int>>()
permute(nums, 0, collect)
return collect
}
fun permute2(nums: IntArray): List<List<Int>> {
val collect = mutableListOf<List<Int>>()
swapPermute2(nums, nums.size, collect)
return collect
}
/**
* 将最后size个进行permute, 结果添加到collect, 并且使得最后size个的顺序与输入相比为倒序
* pre: size >= 1
*/
fun swapPermute2(nums: IntArray, size: Int, collect: MutableList<List<Int>>) {
if (size == 1) {
collect.add(nums.toList())
return
}
swapPermute2(nums, size - 1, collect)
val index = size - 1
var j = 0;
var i = index - 2
while (j < index) {
if (j < index) {
val temp = nums[index]
nums[index] = nums[j]
nums[j] = temp
swapPermute2(nums, size - 1, collect)
j += 2;
}
if (i >= 0) {
val temp = nums[i]
nums[i] = nums[index]
nums[index] = temp
swapPermute2(nums, size - 1, collect)
i -= 2;
}
}
if (j == size) {
reverse(nums, 0, index - 1)
}
}
private fun reverse(nums: IntArray, i: Int, j: Int) {
var start = i
var end = j
while (start < end) {
val temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start++;
end--;
}
}
fun permute(nums: IntArray, fixCount: Int, collect: MutableList<List<Int>>) {
if (fixCount >= nums.size - 1) {
collect.add(nums.toList())
return
}
permute(nums, fixCount + 1, collect)
for (i in fixCount + 1 until nums.size) {
val temp = nums[fixCount]
nums[fixCount] = nums[i]
nums[i] = temp
permute(nums, fixCount + 1, collect)
nums[i] = nums[fixCount]
nums[fixCount] = temp
swapCount += 2
}
}
}
fun main(args: Array<String>) {
val nums = intArrayOf(1,2,3)
val nums2 = nums.clone()
val perm = Permutations()
val perm2 = Permutations()
// val ps = perm.permute(nums)
val ps2 = perm2.permute2(nums)
// println(ps)
// println(nums.toList())
println("swap count " + perm.swapCount)
println("==2== ")
println(ps2)
// println(nums2.toList())
println("swap count2 " + perm2.swapCount)
}
| [
{
"class_path": "ssynhtn__leetcode__511f658/com/ssynhtn/medium/Permutations.class",
"javap": "Compiled from \"Permutations.kt\"\npublic final class com.ssynhtn.medium.Permutations {\n private int swapCount;\n\n public com.ssynhtn.medium.Permutations();\n Code:\n 0: aload_0\n 1: invokespecia... |
ezAuton__ezAuton__b08c522/Core/src/main/kotlin/com/github/ezauton/core/utils/math/AlgebraUtils.kt | package com.github.ezauton.core.utils.math
/**
* @param map
* @return If is odd function
*/
fun hasOddSymmetry(map: Map<out Double, Double>): Boolean {
return map.entries.stream().allMatch { entry ->
val key = entry.key
val value = entry.value
val symmetricEntry = map[-key]?.toDouble()
symmetricEntry != null && symmetricEntry == -value
}
}
/**
* @param map
* @return If is even function
*/
fun hasEvenSymmetry(map: Map<out Double, Double>): Boolean {
return map.entries.stream().allMatch { entry ->
val key = entry.key
val value = entry.value
val symmetricValue = map[-key]?.toDouble()
symmetricValue != null && symmetricValue == value
}
}
/**
* Solve for the roots of a quadratic of the form ax^2 + bx + c
*
* @param a x^2 coefficient
* @param b x coefficient
* @param c added constant
* @return roots of the quadratic
*/
fun quadratic(a: Double, b: Double, c: Double): Set<Double> {
val toReturn = HashSet<Double>()
val discriminate = discriminate(a, b, c)
if (discriminate < 0) {
return toReturn
} else if (discriminate == 0.0) {
toReturn.add(-b / (2 * a))
} else {
val LHS = -b / (2 * a)
val RHS = Math.sqrt(discriminate) / (2 * a)
toReturn.add(LHS + RHS)
toReturn.add(LHS - RHS)
}
return toReturn
}
/**
* Solve for the discriminant of a quadratic of the form ax^2 + bx + c
*
* @param a x^2 coefficient
* @param b x coefficient
* @param c added thing
* @return roots of the quadratic
* @see MathUtils.Algebra.quadratic
*/
fun discriminate(a: Double, b: Double, c: Double): Double {
return b * b - 4.0 * a * c
}
| [
{
"class_path": "ezAuton__ezAuton__b08c522/com/github/ezauton/core/utils/math/AlgebraUtilsKt.class",
"javap": "Compiled from \"AlgebraUtils.kt\"\npublic final class com.github.ezauton.core.utils.math.AlgebraUtilsKt {\n public static final boolean hasOddSymmetry(java.util.Map<? extends java.lang.Double, jav... |
lm41__pro-train-kotlin__bba220a/src/main/kotlin/o9referenzdatentypen/Fraction.kt | package o9referenzdatentypen
/**
* Programmieren Trainieren Seite 192
* W.9.2 <NAME>
*
* Erweitert um [Fraction.divide] und weitere helper wie [Fraction.shorten] und [Fraction.gcd]
* */
fun main() {
val a = Fraction(numerator = 1, denominator = 2)
val b = Fraction(numerator = 1, denominator = 4)
val f = Fraction(numerator = 8, denominator = 4)
val c = a.add(b)
val d = a.multiply(b)
println(c.toString())
println(d.toString())
println(f)
println(b.divide(a))
}
/**
* Represents a fraction with a numerator and a denominator.
*
* @property numerator The numerator of the fraction.
* @property denominator The denominator of the fraction.
*/
data class Fraction(
private val numerator: Int,
private val denominator: Int
) {
/**
* Adds [other] to this fraction and returns the result as a new fraction.
*
* @param other The fraction to add to this fraction.
* @return A new fraction that is the sum of this fraction and [other].
*/
fun add(other: Fraction): Fraction {
val newNumerator = (this.numerator * other.denominator) + (other.numerator * this.denominator)
val newDominator = this.denominator * other.denominator
return this.copy(numerator = newNumerator, denominator = newDominator).shorten()
}
/**
* Multiplies this fraction by [other] and returns the result as a new fraction.
*
* @param other The fraction to multiply with this fraction.
* @return A new fraction that is the product of this fraction and [other].
*/
fun multiply(other: Fraction): Fraction {
val newNumerator = this.numerator * other.numerator
val newDominator = this.denominator * other.denominator
return this.copy(numerator = newNumerator, denominator = newDominator).shorten()
}
/**
* Divides this fraction by [other] and returns the result as a new fraction.
*
* @param other The fraction to divide this fraction by.
* @return A new fraction that is the quotient of this fraction divided by [other].
*/
fun divide(other: Fraction) : Fraction {
return this.multiply(other.copy(numerator = other.denominator, denominator = other.numerator))
}
/**
* Returns a new fraction that is a simplified version of this fraction.
*
* @return A new fraction that has the same value as this fraction but with the numerator and denominator
* divided by their greatest common divisor.
*/
private fun shorten(): Fraction {
val gcd = gcd()
return this.copy(numerator = this.numerator / gcd, denominator = this.denominator / gcd)
}
/**
* Calculates and returns the greatest common divisor (GCD) of the numerator and denominator of this Fraction.
* This function uses the Euclidean algorithm to calculate the GCD.
*
* @return the GCD of the numerator and denominator of this Fraction.
*/
private fun gcd(): Int {
var num1 = this.numerator
var num2 = this.denominator
while (num2 != 0) {
val remainder = num1 % num2
num1 = num2
num2 = remainder
}
return num1
}
/**
* Returns a string representation of this fraction.
*
* If the denominator of the fraction is 1, only the numerator is returned. Otherwise,
* the string representation of the numerator and denominator is returned.
*
* @return A string representation of this fraction.
*/
override fun toString(): String {
val gcd = gcd()
val copy = this.copy(numerator = this.numerator / gcd, denominator = this.denominator / gcd)
return if (copy.denominator == 1) {
"${copy.numerator}"
} else "${copy.numerator}/${copy.denominator}"
}
}
| [
{
"class_path": "lm41__pro-train-kotlin__bba220a/o9referenzdatentypen/Fraction.class",
"javap": "Compiled from \"Fraction.kt\"\npublic final class o9referenzdatentypen.Fraction {\n private final int numerator;\n\n private final int denominator;\n\n public o9referenzdatentypen.Fraction(int, int);\n Cod... |
DPNT-Sourcecode__CHK-cvvr01__326235b/src/main/kotlin/solutions/CHK/CheckoutSolution.kt | package solutions.CHK
object CheckoutSolution {
fun checkout(skus: String): Int {
val skuList = skus.map { it.toString() }
if (containsInvalidSkus(skuList)) {
return -1
}
val checkoutItemsMap = getCheckoutItemsMap(skuList)
val items = setupItems()
return getSumOfItems(checkoutItemsMap, items)
}
private fun getSumOfItems(checkoutItemsMap: Map<Char, Int>, items: List<Item>): Int {
val remainingCheckoutItemsMap = removeFreeItems(checkoutItemsMap, items).toMutableMap()
val totalBundlePrice = setupBundleOffers().sumOf {
applyMostExpensiveBundle(remainingCheckoutItemsMap, items, it)
}
val remainingItemsSum = remainingCheckoutItemsMap.entries.sumOf { (sku, quantity) ->
calculateItemCost(sku, quantity, items) ?: return -1
}
return totalBundlePrice + remainingItemsSum
}
private fun calculateItemCost(sku: Char, quantity: Int, items: List<Item>): Int? {
val item = items.find { it.sku == sku } ?: return null
return calculateCostWithSpecialOffers(item, quantity)
}
private fun calculateCostWithSpecialOffers(item: Item, quantity: Int): Int {
val sortedSpecialOffers = item.specialOffers.sortedByDescending { it.quantity }
var totalCost = 0
var remainingQuantity = quantity
for (specialOffer in sortedSpecialOffers) {
if (specialOffer.price != null) {
val applicableTimes = remainingQuantity / specialOffer.quantity
totalCost += applicableTimes * specialOffer.price
remainingQuantity -= applicableTimes * specialOffer.quantity
} else if (specialOffer.freeSku != null) {
remainingQuantity -= specialOffer.quantity
totalCost += item.price * specialOffer.quantity
}
}
totalCost += remainingQuantity * item.price
return totalCost
}
private fun applyMostExpensiveBundle(checkoutItemsMap: MutableMap<Char, Int>, items: List<Item>, bundleOffer: BundleOffer): Int {
var totalBundlePrice = 0
while (canFormBundle(checkoutItemsMap, bundleOffer.skus, bundleOffer.quantity)) {
val sortedEligibleItems = items.filter { it.sku in bundleOffer.skus && checkoutItemsMap.getOrDefault(it.sku, 0) > 0 }
.sortedByDescending { it.price }
val selectedItems = selectItemsForBundle(checkoutItemsMap, sortedEligibleItems, bundleOffer.quantity)
if (selectedItems.isNotEmpty()) {
selectedItems.forEach { sku ->
checkoutItemsMap[sku] = checkoutItemsMap[sku]!! - 1
if (checkoutItemsMap[sku]!! <= 0) {
checkoutItemsMap.remove(sku)
}
}
totalBundlePrice += bundleOffer.price
} else {
break
}
}
return totalBundlePrice
}
private fun canFormBundle(checkoutItemsMap: Map<Char, Int>, skus: List<Char>, bundleQuantity: Int): Boolean {
return checkoutItemsMap.filterKeys { it in skus }.values.sum() >= bundleQuantity
}
private fun selectItemsForBundle(checkoutItemsMap: Map<Char, Int>, sortedItems: List<Item>, bundleQuantity: Int): List<Char> {
val selectedItems = mutableListOf<Char>()
var count = 0
for (item in sortedItems) {
val availableQuantity = checkoutItemsMap.getOrDefault(item.sku, 0)
val quantityToAdd = minOf(availableQuantity, bundleQuantity - count)
repeat(quantityToAdd) { selectedItems.add(item.sku) }
count += quantityToAdd
if (count >= bundleQuantity) break
}
return if (count >= bundleQuantity) selectedItems else listOf()
}
private fun removeFreeItems(checkoutItemsMap: Map<Char, Int>, items: List<Item>): Map<Char, Int> {
val updatedCheckoutItemsMap = checkoutItemsMap.toMutableMap()
checkoutItemsMap.forEach { (sku, quantity) ->
items.find { it.sku == sku }?.let { item ->
processItemForFreeOffers(updatedCheckoutItemsMap, item, quantity)
}
}
return updatedCheckoutItemsMap.filter { it.value > 0 }
}
private fun processItemForFreeOffers(updatedCheckoutItemsMap: MutableMap<Char, Int>, item: Item, quantity: Int) {
item.specialOffers.sortedByDescending { it.quantity }
.forEach { offer ->
applySpecialOffer(updatedCheckoutItemsMap, offer, quantity)
}
}
private fun applySpecialOffer(updatedCheckoutItemsMap: MutableMap<Char, Int>, offer: SpecialOffer, quantity: Int) {
var applicableTimes = quantity / offer.quantity
while (applicableTimes > 0 && offer.freeSku != null) {
val freeItemQuantity = updatedCheckoutItemsMap[offer.freeSku]
if (freeItemQuantity != null && freeItemQuantity > 0) {
updatedCheckoutItemsMap[offer.freeSku] = freeItemQuantity - 1
applicableTimes--
} else {
break
}
}
}
private fun getCheckoutItemsMap(skuList: List<String>): Map<Char, Int> {
return skuList
.flatMap { it.toList() }
.groupingBy { it }
.eachCount()
}
private fun containsInvalidSkus(skuList: List<String>): Boolean {
return skuList.any { it.none(Char::isLetter) }
}
private fun setupItems(): List<Item> {
return listOf(
Item('A', 50, listOf(SpecialOffer(3, 130), SpecialOffer(5, 200))),
Item('B', 30, listOf(SpecialOffer(2, 45))),
Item('C', 20),
Item('D', 15),
Item('E', 40, listOf(SpecialOffer(2, freeSku = 'B'))),
Item('F', 10, listOf(SpecialOffer(3, freeSku = 'F'))),
Item('G', 20),
Item('H', 10, listOf(SpecialOffer(5, price = 45), SpecialOffer(10, price = 80))),
Item('I', 35),
Item('J', 60),
Item('K', 70, listOf(SpecialOffer(2, price = 120))),
Item('L', 90),
Item('M', 15),
Item('N', 40, listOf(SpecialOffer(3, freeSku = 'M'))),
Item('O', 10),
Item('P', 50, listOf(SpecialOffer(5, price = 200))),
Item('Q', 30, listOf(SpecialOffer(3, price = 80))),
Item('R', 50, listOf(SpecialOffer(3, freeSku = 'Q'))),
Item('S', 20),
Item('T', 20),
Item('U', 40, listOf(SpecialOffer(4, freeSku = 'U'))),
Item('V', 50, listOf(SpecialOffer(2, price = 90), SpecialOffer(3, price = 130))),
Item('W', 20),
Item('X', 17),
Item('Y', 20),
Item('Z', 21),
)
}
private fun setupBundleOffers(): List<BundleOffer> {
return listOf(
BundleOffer(
3,
45,
listOf('S', 'T', 'X', 'Y', 'Z'),
),
)
}
}
data class Item(
val sku: Char,
val price: Int,
val specialOffers: List<SpecialOffer> = emptyList(),
)
data class SpecialOffer(
val quantity: Int,
val price: Int? = null,
val freeSku: Char? = null
)
data class BundleOffer(
val quantity: Int,
val price: Int,
val skus: List<Char> = emptyList(),
)
| [
{
"class_path": "DPNT-Sourcecode__CHK-cvvr01__326235b/solutions/CHK/CheckoutSolution$applyMostExpensiveBundle$$inlined$sortedByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class solutions.CHK.CheckoutSolution$applyMostExpensiveBundle$$inlined$sortedByDescending$1<T> implemen... |
vikaskushwaha9oct__intstar__27ee780/intstar-mcalculus/src/main/kotlin/intstar/mcalculus/Prelude.kt | package intstar.mcalculus
import java.nio.ByteBuffer.wrap
import java.util.*
import kotlin.math.abs
typealias InputStream = java.io.InputStream
const val INFINITY = Double.POSITIVE_INFINITY
const val NEG_INFINITY = Double.NEGATIVE_INFINITY
fun <T> Iterable<T>.sumsToOne(valueFn: (T) -> Double): Boolean {
return abs(sumByDouble(valueFn) - 1) < 0.00001
}
fun Double.isDefined(): Boolean {
return !isNaN() && (-0.0).compareTo(this) != 0
}
fun <T> iteratorOf(vararg elements: T): Iterator<T> {
return elements.iterator()
}
sealed class Interval {
abstract fun compareStart(other: Interval): Int
abstract fun intersectsWith(other: Interval): Boolean
abstract fun anchors(): List<Double>
}
data class OpenInterval(val low: Double, val high: Double) : Interval() {
init {
require(low.isDefined() && high.isDefined()) { "Low and high should have a defined value" }
require(high > low) { "High should be > low for open interval" }
}
override fun compareStart(other: Interval): Int {
return when (other) {
is OpenInterval -> low.compareTo(other.low)
is PointInterval -> low.compareTo(other.value).let { if (it == 0) 1 else it }
}
}
override fun intersectsWith(other: Interval): Boolean {
return when (other) {
is OpenInterval -> low >= other.low && low < other.high || other.low >= low && other.low < high
is PointInterval -> other.value > low && other.value < high
}
}
override fun anchors(): List<Double> {
return listOf(low, high)
}
}
data class PointInterval(val value: Double) : Interval() {
init {
require(value.isDefined() && value.isFinite()) { "Point interval value should be defined and finite" }
}
override fun compareStart(other: Interval): Int {
return when (other) {
is OpenInterval -> value.compareTo(other.low).let { if (it == 0) -1 else it }
is PointInterval -> value.compareTo(other.value)
}
}
override fun intersectsWith(other: Interval): Boolean {
return when (other) {
is OpenInterval -> value > other.low && value < other.high
is PointInterval -> value == other.value
}
}
override fun anchors(): List<Double> {
return listOf(value)
}
}
fun Iterable<Interval>.isSortedByStart(): Boolean {
return zipWithNext { a, b -> a.compareStart(b) <= 0 }.all { it }
}
fun Iterable<Interval>.isDisjoint(allowConnected: Boolean = true): Boolean {
val map = TreeMap<Double, MutableList<Interval>>()
for (interval in this) {
for (anchor in interval.anchors()) {
val closestIntervals = mutableSetOf<Interval>()
map.floorEntry(anchor)?.value?.let { closestIntervals.addAll(it) }
map.ceilingEntry(anchor)?.value?.let { closestIntervals.addAll(it) }
if (closestIntervals.any { interval.intersectsWith(it) }) {
return false
}
}
interval.anchors().forEach { map.getOrPut(it, { mutableListOf() }).add(interval) }
}
return allowConnected || map.values.none { it.size == 3 }
}
fun Iterable<Interval>.isDisconnected(): Boolean {
return isDisjoint(false)
}
fun <T> Iterable<T>.isSortedByStart(intervalsFn: (T) -> Iterable<Interval>): Boolean {
return map { intervalsFn(it).first() }.isSortedByStart()
}
fun <T> Iterable<T>.isDisjoint(intervalsFn: (T) -> Iterable<Interval>): Boolean {
return flatMap { intervalsFn(it) }.isDisjoint()
}
class ByteString(bytes: ByteArray = EMPTY_BYTE_ARRAY) : Iterable<Byte> {
private val bytes = if (bytes.isNotEmpty()) bytes.copyOf() else EMPTY_BYTE_ARRAY
fun byteAt(index: Int): Byte {
return bytes[index]
}
fun size(): Int {
return bytes.size
}
fun toByteArray(): ByteArray {
return bytes.copyOf()
}
fun asString(): String {
return Charsets.UTF_8.newDecoder().decode(wrap(bytes)).toString()
}
override fun equals(other: Any?): Boolean {
return this === other || (javaClass == other?.javaClass && bytes.contentEquals((other as ByteString).bytes))
}
override fun hashCode(): Int {
return bytes.contentHashCode()
}
override fun iterator(): ByteIterator {
return bytes.iterator()
}
override fun toString(): String {
return bytes.joinToString(" ") { "%02x".format(it) }
}
}
private val EMPTY_BYTE_ARRAY = ByteArray(0)
| [
{
"class_path": "vikaskushwaha9oct__intstar__27ee780/intstar/mcalculus/PreludeKt.class",
"javap": "Compiled from \"Prelude.kt\"\npublic final class intstar.mcalculus.PreludeKt {\n public static final double INFINITY;\n\n public static final double NEG_INFINITY;\n\n private static final byte[] EMPTY_BYTE_... |
vikaskushwaha9oct__intstar__27ee780/intstar-mcalculus/src/main/kotlin/intstar/mcalculus/Measurement.kt | package intstar.mcalculus
data class Measurement(
val left: DerivedMeasure,
val comparison: Comparison,
val right: Measure,
val confidence: List<ConfidenceValue>
) {
init {
require(confidence.sumsToOne { it.value }) { "Total confidence should be 1" }
require(confidence.isDisjoint { it.intervals }) { "Intervals should be disjoint" }
require(confidence.isSortedByStart { it.intervals }) { "Confidence values should be sorted by interval starts" }
}
}
data class ConfidenceValue(val intervals: List<Interval>, val value: Double) {
init {
require(value > 0 && value <= 1) { "Confidence value should be > 0 and <= 1" }
require(intervals.isNotEmpty()) { "Intervals within a confidence value should not be empty" }
require(intervals.isDisconnected()) { "Intervals within a confidence value should be disconnected" }
require(intervals.isSortedByStart()) { "Intervals within a confidence value should be sorted by their starts" }
}
}
enum class Comparison(val symbol: String) {
EQUALS("="),
LESS_THAN("<"),
GREATER_THAN(">"),
LESS_THAN_EQUALS("<="),
GREATER_THAN_EQUALS(">=")
}
sealed class Measure
data class ConstantMeasure(val value: Double) : Measure() {
init {
require(value.isDefined()) { "Constant measure should have a defined value" }
}
}
data class DerivedMeasure(val concept: Concept, val measurable: IdEntityConcept) : Measure()
sealed class Concept
data class RelationConcept(val left: EntityConcept, val right: EntityConcept) : Concept()
sealed class EntityConcept : Concept()
data class IdEntityConcept(val value: String) : EntityConcept()
data class ByteEntityConcept(val value: ByteString) : EntityConcept()
data class MeasurementEntityConcept(val value: List<Measurement>) : EntityConcept()
| [
{
"class_path": "vikaskushwaha9oct__intstar__27ee780/intstar/mcalculus/Measurement.class",
"javap": "Compiled from \"Measurement.kt\"\npublic final class intstar.mcalculus.Measurement {\n private final intstar.mcalculus.DerivedMeasure left;\n\n private final intstar.mcalculus.Comparison comparison;\n\n p... |
serbanghita__kotlin-pocs__bca5629/src/com/kotlin/pocs/predicates/Predicates.kt | package com.kotlin.pocs.predicates
fun main(args: Array<String>): Unit {
// val n = listOf(1,2,3,4,5,6,7,8);
// val pred = { value: Int -> value > 5 }
//
// println(n.all(pred))
// println(n.any(pred))
// println(n.count { it > 5 })
//
// println(n.find(pred))
val players = listOf(
Player(1, "AAA", listOf(Point(1,1), Point(1,2))),
Player(2, "BBB", listOf(Point(1,1), Point(11,22))),
Player(3, "CCC", listOf(Point(1,1), Point(111,222)))
)
val p1 = players
.asSequence()
.filter {
println("filter($it)")
it.id > 1
}
.map {
println("map($it)");
"${it.id} + ${it.name}"
}
// val p2 = players
// //.asSequence()
// .flatMap { it -> it.points }
// .distinct()
// println(p1)
for(player in p1) {
println(player);
}
// println(p2)
/**
filter(com.kotlin.pocs.predicates.Player@7eda2dbb)
filter(com.kotlin.pocs.predicates.Player@6576fe71)
filter(com.kotlin.pocs.predicates.Player@76fb509a)
map(com.kotlin.pocs.predicates.Player@6576fe71)
map(com.kotlin.pocs.predicates.Player@76fb509a)
2 + BBB
3 + CCC
*/
/**
kotlin.sequences.TransformingSequence@2b71fc7e
filter(com.kotlin.pocs.predicates.Player@4b85612c)
filter(com.kotlin.pocs.predicates.Player@277050dc)
map(com.kotlin.pocs.predicates.Player@277050dc)
2 + BBB
filter(com.kotlin.pocs.predicates.Player@5c29bfd)
map(com.kotlin.pocs.predicates.Player@5c29bfd)
3 + CCC
*/
}
class Player(var id: Int = 0, var name: String = "", var points: List<Point>) {
}
data class Point(var x: Int = 0, var y: Int = 0) {
}
| [
{
"class_path": "serbanghita__kotlin-pocs__bca5629/com/kotlin/pocs/predicates/PredicatesKt.class",
"javap": "Compiled from \"Predicates.kt\"\npublic final class com.kotlin.pocs.predicates.PredicatesKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc ... |
ascheja__aoc2020__f115063/day5/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day5
fun main() {
val testCodes = listOf(
"FBFBBFFRLR",
"BFFFBBFRRR",
"FFFBBBFRRR",
"BBFFBBFRLL"
)
testCodes.forEach { testCode ->
println(SeatCoordinates.ofSeatCode(testCode))
}
ClassLoader.getSystemResourceAsStream("input.txt")!!.bufferedReader().useLines { lines ->
val maxSeatId = lines.filterNot(String::isEmpty)
.map(SeatCoordinates.Companion::ofSeatCode)
.map(SeatCoordinates::seatId)
.maxOrNull()
println("max seat id: $maxSeatId")
}
ClassLoader.getSystemResourceAsStream("input.txt")!!.bufferedReader().useLines { lines ->
val emptySeatId = lines.filterNot(String::isEmpty)
.map(SeatCoordinates.Companion::ofSeatCode)
.map(SeatCoordinates::seatId)
.sorted()
.windowed(2, 1)
.first { (a, b) -> b - a == 2 }[0] + 1
println("empty seat id: $emptySeatId")
}
}
data class SeatCoordinates(val row: Int, val column: Int, val seatId: Int = row * 8 + column) {
companion object {
private fun codeToNumber(code: String, highChar: Char): Int {
return code.map { c -> if (c == highChar) 1 else 0 }.reduce { a, b -> a * 2 + b }
}
fun ofSeatCode(code: String): SeatCoordinates {
val (rowCode, columnCode) = code.chunked(7)
return SeatCoordinates(codeToNumber(rowCode, 'B'), codeToNumber(columnCode, 'R'))
}
}
}
| [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day5/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class net.sinceat.aoc2020.day5.AppKt {\n public static final void main();\n Code:\n 0: iconst_4\n 1: anewarray #10 // class java/lang/String\... |
ascheja__aoc2020__f115063/day12/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day12
import kotlin.math.abs
fun main() {
println(readInstructions("testinput.txt").calculateManhattanDistancePart1())
println(readInstructions("input.txt").calculateManhattanDistancePart1())
println(readInstructions("testinput.txt").calculateManhattanDistancePart2())
println(readInstructions("input.txt").calculateManhattanDistancePart2())
}
fun List<Instruction>.calculateManhattanDistancePart1(): Int {
var facing = 90
var xDistance = 0
var yDistance = 0
for (instruction in this) {
when (instruction) {
is Forward -> when (facing) {
0 -> yDistance += instruction.distance
90 -> xDistance += instruction.distance
180 -> yDistance -= instruction.distance
270 -> xDistance -= instruction.distance
}
is TurnLeft -> {
val rawFacing = facing - instruction.degrees
facing = if (rawFacing < 0) {
rawFacing + 360
} else rawFacing
}
is TurnRight -> {
val rawFacing = facing + instruction.degrees
facing = if (rawFacing >= 360) {
rawFacing % 360
} else rawFacing
}
is North -> yDistance += instruction.distance
is East -> xDistance += instruction.distance
is South -> yDistance -= instruction.distance
is West -> xDistance -= instruction.distance
}
}
return abs(xDistance) + abs(yDistance)
}
data class Point(val x: Int, val y: Int)
fun Point.north(amount: Int) = Point(x, y + amount)
fun Point.east(amount: Int) = Point(x + amount, y)
fun Point.south(amount: Int) = Point(x, y - amount)
fun Point.west(amount: Int) = Point(x - amount, y)
fun Point.rotateLeft() = Point(-y, x)
fun Point.rotateRight() = Point(y, -x)
fun List<Instruction>.calculateManhattanDistancePart2(): Int {
var waypoint = Point(10, 1)
var xDistance = 0
var yDistance = 0
for (instruction in this) {
when (instruction) {
is Forward -> {
xDistance += waypoint.x * instruction.distance
yDistance += waypoint.y * instruction.distance
}
is TurnLeft -> repeat(instruction.degrees / 90) {
waypoint = waypoint.rotateLeft()
}
is TurnRight -> repeat(instruction.degrees / 90) {
waypoint = waypoint.rotateRight()
}
is North -> waypoint = waypoint.north(instruction.distance)
is East -> waypoint = waypoint.east(instruction.distance)
is South -> waypoint = waypoint.south(instruction.distance)
is West -> waypoint = waypoint.west(instruction.distance)
}
}
return abs(xDistance) + abs(yDistance)
}
sealed class Instruction
class Forward(val distance: Int) : Instruction()
class TurnLeft(val degrees: Int) : Instruction()
class TurnRight(val degrees: Int) : Instruction()
class North(val distance: Int) : Instruction()
class East(val distance: Int) : Instruction()
class South(val distance: Int) : Instruction()
class West(val distance: Int) : Instruction()
fun readInstructions(fileName: String): List<Instruction> {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
lines.filter(String::isNotBlank).map { line ->
val instructionType = line[0]
val instructionArgument = line.removePrefix(instructionType.toString()).toInt()
when (instructionType) {
'F' -> Forward(instructionArgument)
'L' -> TurnLeft(instructionArgument)
'R' -> TurnRight(instructionArgument)
'N' -> North(instructionArgument)
'E' -> East(instructionArgument)
'S' -> South(instructionArgument)
'W' -> West(instructionArgument)
else -> TODO("unhandled instruction type '$instructionType'")
}
}.toList()
}
}
| [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day12/AppKt$readInstructions$1$1.class",
"javap": "Compiled from \"App.kt\"\nfinal class net.sinceat.aoc2020.day12.AppKt$readInstructions$1$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.lang.S... |
ascheja__aoc2020__f115063/day15/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day15
fun main() {
println("1, 3, 2, ... = ${theElvesGamePart1(listOf(1, 3, 2)).nth(2020)}")
println("2, 1, 3, ... = ${theElvesGamePart1(listOf(2, 1, 3)).nth(2020)}")
println("1, 2, 3, ... = ${theElvesGamePart1(listOf(1, 2, 3)).nth(2020)}")
println("2, 3, 1, ... = ${theElvesGamePart1(listOf(2, 3, 1)).nth(2020)}")
println("3, 2, 1, ... = ${theElvesGamePart1(listOf(3, 2, 1)).nth(2020)}")
println("3, 1, 2, ... = ${theElvesGamePart1(listOf(3, 1, 2)).nth(2020)}")
println("5,2,8,16,18,0,1, ... = ${theElvesGamePart1(listOf(5, 2, 8, 16, 18, 0, 1)).nth(2020)}")
println("5,2,8,16,18,0,1, ... = ${theElvesGamePart1(listOf(5, 2, 8, 16, 18, 0, 1)).nth(30000000)}")
}
fun theElvesGamePart1(startingNumbers: List<Int>) = sequence {
val memory = mutableMapOf<Int, Int>()
startingNumbers.subList(0, startingNumbers.size - 1).forEachIndexed { index, number ->
yield(number)
memory[number] = index + 1
}
var lastSpokenNumber = startingNumbers.last()
var turn = startingNumbers.size
while (true) {
yield(lastSpokenNumber)
val nextSpokenNumber = memory[lastSpokenNumber]?.let { turn - it } ?: 0
memory[lastSpokenNumber] = turn
turn++
lastSpokenNumber = nextSpokenNumber
}
}
fun Sequence<Int>.nth(n: Int): Int {
return drop(n - 1).first()
}
| [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day15/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class net.sinceat.aoc2020.day15.AppKt {\n public static final void main();\n Code:\n 0: new #8 // class java/lang/StringBuilder\n 3: ... |
ascheja__aoc2020__f115063/day14/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day14
import kotlin.properties.Delegates
fun main() {
println(part1InstructionProcessor(readInstructions("testinput.txt")))
println(part1InstructionProcessor(readInstructions("input.txt")))
println(part2InstructionProcessor(readInstructions("testinput2.txt")))
println(part2InstructionProcessor(readInstructions("input.txt")))
}
fun part1InstructionProcessor(instructions: List<Instruction>): Long {
var currentMask: Mask by Delegates.notNull()
val memory = mutableMapOf<Long, Long>()
for (instruction in instructions) {
when (instruction) {
is SetMask -> currentMask = instruction.mask
is WriteMemory -> memory[instruction.address] = currentMask.apply(instruction.value)
}
}
return memory.values.sum()
}
fun part2InstructionProcessor(instructions: List<Instruction>): Long {
var currentMask: Mask by Delegates.notNull()
val memory = mutableMapOf<Long, Long>()
for (instruction in instructions) {
when (instruction) {
is SetMask -> currentMask = instruction.mask
is WriteMemory -> {
val addresses = currentMask.addressMasks(instruction.address)
addresses.forEach { address ->
memory[address] = instruction.value
}
}
}
}
return memory.values.sum()
}
class Mask(private val value: String) {
private val orMask: Long = value.replace('X', '0').toLong(2)
private val andMask: Long = value.replace('X', '1').toLong(2)
fun apply(value: Long): Long {
return value and andMask or orMask
}
fun addressMasks(address: Long): List<Long> {
return maskAddress(address.toString(2).padStart(36, '0'), value).map { it.toLong(2) }.toList()
}
companion object {
private fun maskAddress(address: String, mask: String): Sequence<String> {
if (mask.isEmpty() || address.length != mask.length) {
return emptySequence()
}
val maskHead = mask.first()
val addressHead = address.first()
val maskTail = mask.substring(1 until mask.length)
val addressTail = address.substring(1 until address.length)
if (maskTail.isEmpty()) {
return sequence {
when (maskHead) {
'0' -> yield("$addressHead")
'1' -> yield("1")
'X' -> {
yield("0")
yield("1")
}
}
}
}
return sequence {
when (maskHead) {
'0' -> yieldAll(maskAddress(addressTail, maskTail).map { "$addressHead$it" })
'1' -> yieldAll(maskAddress(addressTail, maskTail).map { "1$it" })
'X' -> {
val tails = maskAddress(addressTail, maskTail).toList()
yieldAll(tails.map { "0$it" })
yieldAll(tails.map { "1$it" })
}
}
}
}
}
}
sealed class Instruction
data class SetMask(val mask: Mask) : Instruction()
data class WriteMemory(val address: Long, val value: Long) : Instruction()
fun readInstructions(fileName: String): List<Instruction> {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
lines.filter(String::isNotBlank).map { line -> line.split("=").map(String::trim) }.map { (left, right) ->
if (left == "mask") {
return@map SetMask(Mask(right))
}
WriteMemory(left.removePrefix("mem[").removeSuffix("]").toLong(), right.toLong())
}.toList()
}
}
| [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day14/AppKt$readInstructions$1$1.class",
"javap": "Compiled from \"App.kt\"\nfinal class net.sinceat.aoc2020.day14.AppKt$readInstructions$1$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.lang.S... |
ascheja__aoc2020__f115063/day13/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day13
fun main() {
run {
val (currentTime, busIds) = readInputPart1("testinput.txt")
val (busId, nextDeparture) = busIds.nextDepartures(currentTime).minByOrNull { (_, nextDeparture) ->
nextDeparture
}!!
println("$busId x ($nextDeparture - $currentTime) = ${busId * (nextDeparture - currentTime)}")
}
run {
val (currentTime, busIds) = readInputPart1("input.txt")
val (busId, nextDeparture) = busIds.nextDepartures(currentTime).minByOrNull { (_, nextDeparture) ->
nextDeparture
}!!
println("$busId x ($nextDeparture - $currentTime) = ${busId * (nextDeparture - currentTime)}")
println()
}
run {
println(readInputPart2("testinput.txt").findFirstConsecutiveDepartures())
}
run {
println(readInputPart2("input.txt").findFirstConsecutiveDepartures())
}
}
fun List<Pair<Int, Int>>.findFirstConsecutiveDepartures(): Long {
var time = 0L
var stepSize = 1L
for ((busId, offset) in this) {
while ((time + offset) % busId != 0L) {
time += stepSize
}
stepSize *= busId
}
return time
}
fun List<Int>.nextDepartures(currentTime: Int): Map<Int, Int> {
return associate { busId ->
Pair(
busId,
(currentTime / busId) * busId + busId
)
}
}
fun readInputPart1(fileName: String): Pair<Int, List<Int>> {
val lines = ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().readLines()
val currentTime = lines[0].toInt()
val busIds = lines[1].split(",").mapNotNull(String::toIntOrNull)
return Pair(currentTime, busIds)
}
fun readInputPart2(fileName: String): List<Pair<Int, Int>> {
val lines = ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().readLines()
return lines[1].split(",").map(String::toIntOrNull).mapIndexed { index, busId ->
if (busId == null) {
return@mapIndexed null
}
Pair(busId, index)
}.filterNotNull()
}
| [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day13/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class net.sinceat.aoc2020.day13.AppKt {\n public static final void main();\n Code:\n 0: iconst_0\n 1: istore_0\n 2: ldc #8 // S... |
ascheja__aoc2020__f115063/day9/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day9
import java.util.LinkedList
fun main() {
val testInput = parseInput("testinput.txt")
val testBuffer = RingBuffer.fromSequence(testInput, 5)
println(lookForFirstInvalidNumber(testBuffer, testInput))
val input = parseInput("input.txt")
val invalidNumber = run {
lookForFirstInvalidNumber(RingBuffer.fromSequence(input, 25), input)
}
println(invalidNumber!!)
for (windowSize in 2 .. Integer.MAX_VALUE) {
println("sequence length: $windowSize")
for (window in input.windowed(windowSize, 1)) {
val sum = window.sum()
when {
sum == invalidNumber -> {
println("found it: ${window.minOrNull()!! + window.maxOrNull()!!}")
return
}
sum > invalidNumber -> {
break
}
}
}
}
}
fun lookForFirstInvalidNumber(buffer: RingBuffer, input: Sequence<Long>): Long? {
for (nr in input.drop(buffer.size)) {
if (nr !in buffer.allSums()) {
return nr
}
buffer.add(nr)
}
return null
}
fun RingBuffer.allSums() = sequence {
for (i in 0 until size) {
val first = get(i)
for (k in i until size) {
val second = get(k)
yield(first + second)
}
}
}
fun parseInput(fileName: String) = sequence {
ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
yieldAll(lines.filter(String::isNotBlank).map(String::toLong))
}
}
class RingBuffer(private val inner: LinkedList<Long>) : List<Long> by inner {
fun add(element: Long) {
inner.removeFirst()
inner.add(element)
}
companion object {
fun fromSequence(sequence: Sequence<Long>, preambleLength: Int): RingBuffer {
val preamble = LinkedList(sequence.take(preambleLength).toList())
return RingBuffer(preamble)
}
}
} | [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day9/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class net.sinceat.aoc2020.day9.AppKt {\n public static final void main();\n Code:\n 0: ldc #8 // String testinput.txt\n 2: invokestati... |
ascheja__aoc2020__f115063/day16/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day16
import kotlin.properties.Delegates
fun main() {
run {
val parseResult = parseInput("testinput.txt")
println(parseResult.calculateScanningErrorRate())
}
run {
val parseResult = parseInput("input.txt")
println(parseResult.calculateScanningErrorRate())
}
run {
val parseResult = parseInput("testinput2.txt").filterCompletelyInvalid()
val assignedFields = parseResult.assignFields()
println(assignedFields)
}
run {
val parseResult = parseInput("input.txt").filterCompletelyInvalid()
val assignedFields = parseResult.assignFields()
println(assignedFields)
val departureFields = assignedFields.filterKeys { it.startsWith("departure") }
println(departureFields.values.map { index -> parseResult.myTicket[index].toLong() }.reduce { acc, i -> acc * i })
}
}
fun ParseResult.filterCompletelyInvalid(): ParseResult {
return ParseResult(
rules,
myTicket,
nearbyTickets.filter { ticket ->
ticket.all { value -> rules.values.any { rule -> value in rule } }
}
)
}
fun ParseResult.assignFields(): Map<String, Int> {
val ticketColumns = myTicket.indices.map { index ->
nearbyTickets.map { ticket -> ticket[index] }
}
val candidates = ticketColumns.map { columnValues ->
rules.filter { (_, rule) ->
columnValues.all { it in rule }
}.map { it.key }
}
val alreadyUsed = mutableSetOf<String>()
return candidates.withIndex().sortedBy { it.value.size }.associate { (index, values) ->
val remaining = values.filterNot { it in alreadyUsed }.single()
alreadyUsed.add(remaining)
Pair(remaining, index)
}
}
fun ParseResult.calculateScanningErrorRate(): Int {
return nearbyTickets.map { ticket ->
ticket.filterNot { value -> rules.values.any { rule -> value in rule } }.sum()
}.sum()
}
data class Rule(val range1: IntRange, val range2: IntRange) {
operator fun contains(value: Int) = value in range1 || value in range2
}
data class ParseResult(val rules: Map<String, Rule>, val myTicket: List<Int>, val nearbyTickets: List<List<Int>>)
private enum class FileSection {
RULES,
MY_TICKET,
OTHER_TICKETS
}
fun parseInput(fileName: String): ParseResult {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
var section = FileSection.RULES
val rules = mutableMapOf<String, Rule>()
var myTicket by Delegates.notNull<List<Int>>()
val nearbyTickets = mutableListOf<List<Int>>()
lines.filter(String::isNotBlank).forEach { line ->
when (line) {
"your ticket:" -> section = FileSection.MY_TICKET
"nearby tickets:" -> section = FileSection.OTHER_TICKETS
else -> if (section == FileSection.RULES) {
val (fieldName, ruleRangesString) = line.split(":").map(String::trim)
val rule = ruleRangesString.split(" or ")
.map { ruleRangeString ->
ruleRangeString.split("-")
.map(String::toInt)
.let { (start, endInclusive) -> start..endInclusive }
}.let { (range1, range2) -> Rule(range1, range2) }
rules[fieldName] = rule
} else {
val ticket = line.split(",").map(String::toInt)
if (section == FileSection.MY_TICKET) {
myTicket = ticket
} else {
nearbyTickets.add(ticket)
}
}
}
}
ParseResult(rules, myTicket, nearbyTickets)
}
} | [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day16/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class net.sinceat.aoc2020.day16.AppKt {\n static final kotlin.reflect.KProperty<java.lang.Object>[] $$delegatedProperties;\n\n public static final void main();\n Code:\n ... |
ascheja__aoc2020__f115063/day11/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day11
import kotlin.math.abs
import kotlin.math.sign
import net.sinceat.aoc2020.day11.Part1EvolutionRules.evolveUntilStable
fun main() {
with (Part1EvolutionRules) {
run {
val fullyEvolvedGrid = readGrid("testinput.txt").evolveUntilStable().last()
Grid.compare(
readGrid("testoutput.txt"),
fullyEvolvedGrid
)
println(fullyEvolvedGrid.occupiedSeats)
}
run {
val fullyEvolvedGrid = readGrid("input.txt").evolveUntilStable().last()
println(fullyEvolvedGrid.occupiedSeats)
}
}
with (Part2EvolutionRules) {
run {
val fullyEvolvedGrid = readGrid("testinput.txt").evolveUntilStable().last()
Grid.compare(
readGrid("testoutputp2.txt"),
fullyEvolvedGrid
)
println(fullyEvolvedGrid.occupiedSeats)
}
run {
val fullyEvolvedGrid = readGrid("input.txt").evolveUntilStable().last()
println(fullyEvolvedGrid.occupiedSeats)
}
}
}
private fun readGrid(fileName: String): Grid {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
Grid(lines.filter(String::isNotBlank).map(String::toList).toList())
}
}
private class Grid(val data: List<List<Char>>) {
companion object {
fun compare(grid1: Grid, grid2: Grid) {
if (grid1.width != grid2.width || grid1.data.size != grid2.data.size) {
println("grid dimensions not equal")
return
}
for ((a, b) in grid1.data.zip(grid2.data)) {
val aString = a.joinToString("")
val bString = b.joinToString("")
println("$aString $bString ${if (aString == bString) "OK" else "ERROR"}")
}
}
}
val width = data[0].size
val occupiedSeats by lazy {
data.sumBy { row -> row.count { it == '#' } }
}
override fun toString(): String {
return data.joinToString("\n") { it.joinToString("") }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Grid) return false
if (width != other.width) return false
if (data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = data.hashCode()
result = 31 * result + width
return result
}
}
private data class Point(val row: Int, val column: Int) {
operator fun plus(v: Vector) = Point(row + v.rowDir, column + v.colDir)
}
private data class Vector(val rowDir: Int, val colDir: Int) {
fun extend(): Vector {
return Vector(
rowDir.sign * (abs(rowDir) + 1),
colDir.sign * (abs(colDir) + 1)
)
}
}
private abstract class GridEvolutionRules {
protected abstract val acceptableNeighbors: Int
protected abstract fun Grid.hasVisibleNeighbor(start: Point, vector: Vector): Boolean
private fun Grid.countNeighbors(rowNr: Int, columnNr: Int): Int {
val vectors = listOf(
Vector(-1, -1),
Vector(-1, 0),
Vector(-1, 1),
Vector(0, -1),
Vector(0, 1),
Vector(1, -1),
Vector(1, 0),
Vector(1, 1),
)
val p = Point(rowNr, columnNr)
return vectors.count { vector -> hasVisibleNeighbor(p, vector) }
}
fun Grid.evolve(): Grid {
return Grid(
List(data.size) { rowNr ->
List(width) { columnNr ->
val status = data[rowNr][columnNr]
if (status == '.') {
'.'
} else {
val neighbors = countNeighbors(rowNr, columnNr)
when {
neighbors == 0 -> '#'
neighbors > acceptableNeighbors -> 'L'
else -> status
}
}
}
}
)
}
fun Grid.evolveUntilStable(): Sequence<Grid> = sequence {
var current = this@evolveUntilStable
while (true) {
val next = current.evolve()
if (current == next) {
break
}
current = next
yield(current)
}
}
}
private object Part1EvolutionRules : GridEvolutionRules() {
override val acceptableNeighbors: Int = 3
override fun Grid.hasVisibleNeighbor(start: Point, vector: Vector): Boolean {
val p = start + vector
if (p.row !in data.indices || p.column !in 0 until width) {
return false
}
return when (data[p.row][p.column]) {
'#' -> true
else -> false
}
}
}
private object Part2EvolutionRules : GridEvolutionRules() {
override val acceptableNeighbors: Int = 4
override tailrec fun Grid.hasVisibleNeighbor(start: Point, vector: Vector): Boolean {
val p = start + vector
if (p.row !in data.indices || p.column !in 0 until width) {
return false
}
return when (data[p.row][p.column]) {
'#' -> true
'L' -> false
else -> hasVisibleNeighbor(start, vector.extend())
}
}
} | [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day11/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class net.sinceat.aoc2020.day11.AppKt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field net/sinceat/aoc2020/day11/Part1Evol... |
ascheja__aoc2020__f115063/day10/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day10
fun main() {
println(differences(parseFile("testinput.txt")))
println(differences(parseFile("input.txt")))
println(with(Cached()) { parseFile("testinput.txt").combinations() })
println(
with(Cached()) {
val result = parseFile("input.txt").combinations()
result
}
)
}
fun parseFile(fileName: String): List<Int> {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
lines.filter(String::isNotBlank).map(String::toInt).sorted().toList()
}
}
fun differences(input: List<Int>): Int {
var oneDiffs = 0
var threeDiffs = 1
var lastJoltage = 0
for (adapterJoltage in input) {
when (adapterJoltage - lastJoltage) {
1 -> oneDiffs++
3 -> threeDiffs++
}
lastJoltage = adapterJoltage
}
return oneDiffs * threeDiffs
}
class Cached {
private val cache = mutableMapOf<Pair<List<Int>, Int>, Long>()
fun List<Int>.combinations(last: Int = 0): Long {
return cache.computeIfAbsent(Pair(this, last)) {
if (isEmpty()) {
return@computeIfAbsent 0
}
val head = first()
val diff = head - last
if (diff > 3) {
return@computeIfAbsent 0
}
val tail = subList(1, size)
if (tail.isEmpty()) {
return@computeIfAbsent 1
}
return@computeIfAbsent tail.combinations(last) + tail.combinations(head)
}
}
}
| [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day10/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class net.sinceat.aoc2020.day10.AppKt {\n public static final void main();\n Code:\n 0: ldc #8 // String testinput.txt\n 2: invokesta... |
ascheja__aoc2020__f115063/day17/src/main/kotlin/App.kt | package net.sinceat.aoc2020.day17
fun main() {
run {
var grid = Grid(readInput("testinput.txt") { x, y -> GridPoint3d(x, y, 0) }, ::drawGrid3d)
(1 .. 6).forEach {
grid = grid.evolve()
}
println(grid.countActive())
println()
}
run {
var grid = Grid(readInput("input.txt") { x, y -> GridPoint3d(x, y, 0) }, ::drawGrid3d)
(1 .. 6).forEach {
grid = grid.evolve()
}
println(grid.countActive())
println()
}
run {
var grid = Grid(readInput("testinput.txt") { x, y -> GridPoint4d(x, y, 0, 0) }, ::drawGrid4d)
(1 .. 6).forEach {
grid = grid.evolve()
}
println(grid.countActive())
println()
}
run {
var grid = Grid(readInput("input.txt") { x, y -> GridPoint4d(x, y, 0, 0) }, ::drawGrid4d)
(1 .. 6).forEach {
grid = grid.evolve()
}
println(grid.countActive())
println()
}
}
fun <T> readInput(fileName: String, mapper: (Int, Int) -> T): Map<T, Char> {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
lines.filter(String::isNotEmpty).flatMapIndexed { yIndex, line ->
line.toCharArray().mapIndexed { xIndex, char -> if (char == '#') mapper(xIndex, yIndex) else null }.filterNotNull()
}.associateWith { '#' }
}
}
fun <T : GridPoint<T>> Grid<T>.evolve(): Grid<T> {
val allActive = data.filterValues { it == '#' }.keys
val remainingActive = allActive.filter { gridPoint ->
gridPoint.neighbors().filter { it in allActive }.count() in 2 .. 3
}
val goingActive = allActive.flatMap { activeNeighbor ->
val inactiveNeighbors = activeNeighbor.neighbors().filter { it !in allActive }
inactiveNeighbors.map { inactiveNeighbor -> Pair(inactiveNeighbor, activeNeighbor) }
}.groupBy { it.first }
.mapValues { (_, pairs) -> pairs.map { it.second }.distinct().count() }
.filterValues { it == 3 }
.keys
return Grid((remainingActive + goingActive).associateWith { '#' }, formatter)
}
fun <T : GridPoint<T>> Grid<T>.countActive(): Int {
return data.size
}
fun drawGrid3d(data: Map<GridPoint3d, Char>) = buildString {
if (data.isEmpty()) {
return ""
}
val xs = data.keys.map(GridPoint3d::x)
val ys = data.keys.map(GridPoint3d::y)
val zs = data.keys.map(GridPoint3d::z)
val xRange = xs.minOrNull()!! .. xs.maxOrNull()!!
val yRange = ys.minOrNull()!! .. ys.maxOrNull()!!
val zRange = zs.minOrNull()!! .. zs.maxOrNull()!!
for (z in zRange) {
appendLine("z=$z")
for (y in yRange) {
for (x in xRange) {
append(data[GridPoint3d(x, y, z)] ?: '.')
}
appendLine()
}
appendLine()
}
}
fun drawGrid4d(data: Map<GridPoint4d, Char>) = buildString {
if (data.isEmpty()) {
return ""
}
val xs = data.keys.map(GridPoint4d::x)
val ys = data.keys.map(GridPoint4d::y)
val zs = data.keys.map(GridPoint4d::z)
val ws = data.keys.map(GridPoint4d::w)
val xRange = xs.minOrNull()!! .. xs.maxOrNull()!!
val yRange = ys.minOrNull()!! .. ys.maxOrNull()!!
val zRange = zs.minOrNull()!! .. zs.maxOrNull()!!
val wRange = ws.minOrNull()!! .. ws.maxOrNull()!!
for (w in wRange) {
for (z in zRange) {
appendLine("z=$z,w=$w")
for (y in yRange) {
for (x in xRange) {
append(data[GridPoint4d(x, y, z, w)] ?: '.')
}
appendLine()
}
appendLine()
}
}
}
interface GridPoint<T : GridPoint<T>> {
fun neighbors(): List<T>
operator fun compareTo(other: T): Int
}
data class GridPoint3d(val x: Int, val y: Int, val z: Int) : GridPoint<GridPoint3d> {
override fun neighbors(): List<GridPoint3d> {
return sequence {
for (nx in (x - 1) .. (x + 1)) {
for (ny in (y - 1) .. (y + 1)) {
for (nz in (z - 1) .. (z + 1)) {
if (nx == x && ny == y && nz == z) {
continue
}
yield(GridPoint3d(nx, ny, nz))
}
}
}
}.toList()
}
override fun compareTo(other: GridPoint3d): Int {
val xCmp = x.compareTo(other.x)
if (xCmp != 0) {
return xCmp
}
val yCmp = y.compareTo(other.y)
if (yCmp != 0) {
return yCmp
}
return z.compareTo(other.z)
}
}
data class GridPoint4d(val x: Int, val y: Int, val z: Int, val w: Int) : GridPoint<GridPoint4d> {
override fun neighbors(): List<GridPoint4d> {
return sequence {
for (nx in (x - 1) .. (x + 1)) {
for (ny in (y - 1) .. (y + 1)) {
for (nz in (z - 1) .. (z + 1)) {
for (nw in (w - 1) .. (w + 1)) {
if (nx == x && ny == y && nz == z && nw == w) {
continue
}
yield(GridPoint4d(nx, ny, nz, nw))
}
}
}
}
}.toList()
}
override fun compareTo(other: GridPoint4d): Int {
val cmp3d = reduce().compareTo(other.reduce())
if (cmp3d != 0) return cmp3d
return w.compareTo(other.w)
}
private fun reduce(): GridPoint3d = GridPoint3d(x, y, z)
}
class Grid<T : GridPoint<T>>(val data: Map<T, Char>, val formatter: (Map<T, Char>) -> String) {
override fun toString(): String = formatter(data)
}
| [
{
"class_path": "ascheja__aoc2020__f115063/net/sinceat/aoc2020/day17/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class net.sinceat.aoc2020.day17.AppKt {\n public static final void main();\n Code:\n 0: iconst_0\n 1: istore_0\n 2: aconst_null\n 3: astore_1\n ... |
markburk__potential-lamp__d28656b/src/main/kotlin/com/mobiento/aoc/Day04.kt | package com.mobiento.aoc
fun Pair<Int, Int>.toSequence(): Set<Int> {
val result = arrayListOf<Int>()
for (x in first .. second) {
result.add(x)
}
return result.toSet()
}
class Day04 {
companion object {
val regex = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex()
}
fun part1(input: List<String>): Int {
return input.sumOf { line ->
regex.matchEntire(line)?.groups?.let { matchGroups ->
val firstPair = Pair(extractIntVal(matchGroups, 1), extractIntVal(matchGroups, 2))
val secondPair = Pair(extractIntVal(matchGroups, 3), extractIntVal(matchGroups, 4))
calculatePairForPartOne(firstPair, secondPair)
} ?: 0
}
}
private fun extractIntVal(matchGroups: MatchGroupCollection, index: Int): Int {
val group = matchGroups[index]
val value = group?.value
return value?.toInt() ?: 0
}
private fun calculatePairForPartOne(first: Pair<Int, Int>, second: Pair<Int, Int>): Int {
return if (isEncompassing(first, second)) 1 else 0
}
fun isEncompassing(firstPair: Pair<Int, Int>, secondPair: Pair<Int, Int>): Boolean {
return (firstPair.first >= secondPair.first && firstPair.second <= secondPair.second) ||
(secondPair.first >= firstPair.first && secondPair.second <= firstPair.second)
}
fun part2(input: List<String>): Int {
return input.sumOf { line ->
regex.matchEntire(line)?.groups?.let { matchGroups ->
val firstPair = Pair(extractIntVal(matchGroups, 1), extractIntVal(matchGroups, 2))
val secondPair = Pair(extractIntVal(matchGroups, 3), extractIntVal(matchGroups, 4))
calculatePairForPartTwo(firstPair, secondPair)
} ?: 0
}
}
fun isOverlapping(first: Pair<Int, Int>, second: Pair<Int, Int>): Boolean {
return first.toSequence().intersect(second.toSequence()).isNotEmpty()
}
fun calculatePairForPartTwo(first: Pair<Int, Int>, second: Pair<Int, Int>): Int {
return if (isOverlapping(first, second)) 1 else 0
}
} | [
{
"class_path": "markburk__potential-lamp__d28656b/com/mobiento/aoc/Day04$Companion.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class com.mobiento.aoc.Day04$Companion {\n private com.mobiento.aoc.Day04$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 //... |
markburk__potential-lamp__d28656b/src/main/kotlin/com/mobiento/aoc/Day02.kt | package com.mobiento.aoc
class Day02 {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
line.split(" ").takeIf { it.size >= 2 }?.let { parts ->
scoreForRoundPart1(parts[0], parts[1])
} ?: 0
}
}
fun scoreForRoundPart1(a: String, b: String): Int {
val opponentChoice = Choice.fromOpponentChoice(a)
val playerChoice = Choice.fromPlayerChoice(b)
val outcome = calculateOutcome(opponentChoice, playerChoice)
return outcome.value + playerChoice.value
}
fun part2(input: List<String>): Int {
return input.sumOf { line ->
line.split(" ").takeIf { it.size >= 2 }?.let { parts ->
scoreForRoundPart2(parts[0], parts[1])
} ?: 0
}
}
fun scoreForRoundPart2(a: String, b: String): Int {
val opponentChoice = Choice.fromOpponentChoice(a)
val expectedOutcome = Outcome.fromSource(b)
val playerChoice = playerChoiceForOutcome(opponentChoice, expectedOutcome)
return expectedOutcome.value + playerChoice.value
}
enum class Outcome(val source: String, val value: Int) {
LOSE("X", 0),
DRAW("Y", 3),
WIN("Z", 6);
companion object {
fun fromSource(source: String): Outcome {
return values().find { it.source == source } ?: throw Exception("No matching source: $source")
}
}
}
enum class Choice(val opponentChoice: String, val playerChoice: String, val value: Int) {
ROCK("A", "X", 1),
PAPER("B", "Y", 2),
SCISSORS("C", "Z", 3);
companion object {
fun fromPlayerChoice(choice: String): Choice {
return values().find { it.playerChoice == choice } ?: throw Exception("No matching choice for $choice")
}
fun fromOpponentChoice(choice: String): Choice {
return values().find { it.opponentChoice == choice } ?: throw Exception("No matching choice for $choice")
}
}
}
private fun playerChoiceForOutcome(opponentChoice: Choice, expectedOutcome: Outcome): Choice {
return when (opponentChoice) {
Choice.ROCK -> when (expectedOutcome) {
Outcome.LOSE -> Choice.SCISSORS
Outcome.DRAW -> Choice.ROCK
Outcome.WIN -> Choice.PAPER
}
Choice.PAPER -> when (expectedOutcome) {
Outcome.LOSE -> Choice.ROCK
Outcome.DRAW -> Choice.PAPER
Outcome.WIN -> Choice.SCISSORS
}
Choice.SCISSORS -> when(expectedOutcome) {
Outcome.LOSE -> Choice.PAPER
Outcome.DRAW -> Choice.SCISSORS
Outcome.WIN -> Choice.ROCK
}
}
}
private fun calculateOutcome(opponentChoice: Choice, playerChoice: Choice): Outcome {
return when (opponentChoice) {
Choice.ROCK -> when (playerChoice) {
Choice.ROCK -> Outcome.DRAW
Choice.PAPER -> Outcome.WIN
Choice.SCISSORS -> Outcome.LOSE
}
Choice.PAPER -> when (playerChoice) {
Choice.ROCK -> Outcome.LOSE
Choice.PAPER -> Outcome.DRAW
Choice.SCISSORS -> Outcome.WIN
}
Choice.SCISSORS -> when (playerChoice) {
Choice.ROCK -> Outcome.WIN
Choice.PAPER -> Outcome.LOSE
Choice.SCISSORS -> Outcome.DRAW
}
}
}
} | [
{
"class_path": "markburk__potential-lamp__d28656b/com/mobiento/aoc/Day02$Choice.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class com.mobiento.aoc.Day02$Choice extends java.lang.Enum<com.mobiento.aoc.Day02$Choice> {\n public static final com.mobiento.aoc.Day02$Choice$Companion Companion;\n\... |
markburk__potential-lamp__d28656b/src/main/kotlin/com/mobiento/aoc/Day03.kt | package com.mobiento.aoc
class Day03 {
private val priority: Map<Char, Int> = hashMapOf<Char, Int>().apply {
var priority = 0
for (c in 'a' .. 'z') {
this[c] = ++priority
}
for (c in 'A' .. 'Z') {
this[c] = ++priority
}
}
fun part1(input: List<String>): Int {
return input.sumOf { line ->
getPriority(findCommonItem(getFirstCompartmentItems(line), getSecondCompartmentItems(line)))
}
}
fun getFirstCompartmentItems(contents: String): String {
return contents.substring(0, contents.length / 2)
}
fun getSecondCompartmentItems(contents: String): String {
return contents.substring(contents.length / 2)
}
fun findCommonItem(firstItems: String, secondItems: String): Char {
return firstItems.toSet().intersect(secondItems.toSet()).firstOrNull() ?: ' '
}
fun getPriority(letter: Char): Int {
return priority[letter] ?: 0
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3).sumOf {
getPriority(findCommonItem(it[0], it[1], it[2]))
}
}
fun findCommonItem(first: String, second: String, third: String): Char {
return first.toSet().intersect(second.toSet()).intersect(third.toSet()).firstOrNull() ?: ' '
}
} | [
{
"class_path": "markburk__potential-lamp__d28656b/com/mobiento/aoc/Day03.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class com.mobiento.aoc.Day03 {\n private final java.util.Map<java.lang.Character, java.lang.Integer> priority;\n\n public com.mobiento.aoc.Day03();\n Code:\n 0: alo... |
Clausr__advent_of_code__dd33c88/src/main/aoc2022/Day12.kt | package aoc2022
import java.util.*
typealias Coordinates = Pair<Int, Int>
private fun Coordinates.getNeighbors(): List<Coordinates> {
val leftOf = Coordinates(first - 1, second)
val rightOf = Coordinates(first + 1, second)
val topOf = Coordinates(first, second - 1)
val bottomOf = Coordinates(first, second + 1)
return listOfNotNull(leftOf, rightOf, topOf, bottomOf)
}
class Day12(input: List<String>) {
private val heightMap = input.parseHeightMap()
data class HeightMap(val elevations: Map<Coordinates, Int>, val start: Coordinates, val end: Coordinates) {
fun shortestPath(
start: Coordinates,
isGoal: (Coordinates) -> Boolean,
canMove: (Int, Int) -> Boolean
): Int {
val seen = mutableSetOf<Coordinates>()
val prioQueue = PriorityQueue<PathCost>().apply { add(PathCost(start, 0)) }
while (prioQueue.isNotEmpty()) {
val nextCoord = prioQueue.poll()
if (nextCoord.coordinates !in seen) {
seen += nextCoord.coordinates
val neighbors = nextCoord.coordinates.getNeighbors()
.filter { it in elevations }
.filter { canMove(elevations.getValue(nextCoord.coordinates), elevations.getValue(it)) }
if (neighbors.any { isGoal(it) }) return nextCoord.cost + 1
prioQueue.addAll(neighbors.map { PathCost(it, nextCoord.cost + 1) })
}
}
throw IllegalStateException("No path...")
}
}
private class PathCost(val coordinates: Coordinates, val cost: Int) : Comparable<PathCost> {
override fun compareTo(other: PathCost): Int {
return this.cost.compareTo(other.cost)
}
}
private fun List<String>.parseHeightMap(): HeightMap {
var start: Coordinates? = null
var end: Coordinates? = null
val elevations = this.flatMapIndexed { y, row ->
row.mapIndexed { x, char ->
val here = Coordinates(x, y)
here to when (char) {
'S' -> 0.also { start = here }
'E' -> 25.also { end = here }
else -> char - 'a'
}
}
}.toMap()
return HeightMap(elevations, start!!, end!!)
}
fun solvePart1(): Int {
return heightMap.shortestPath(
start = heightMap.start,
isGoal = { it == heightMap.end },
canMove = { from, to -> to - from <= 1 }
)
}
fun solvePart2(): Int {
return heightMap.shortestPath(
start = heightMap.end,
isGoal = { heightMap.elevations[it] == 0 },
canMove = { from, to -> from - to <= 1 }
)
}
} | [
{
"class_path": "Clausr__advent_of_code__dd33c88/aoc2022/Day12$PathCost.class",
"javap": "Compiled from \"Day12.kt\"\nfinal class aoc2022.Day12$PathCost implements java.lang.Comparable<aoc2022.Day12$PathCost> {\n private final kotlin.Pair<java.lang.Integer, java.lang.Integer> coordinates;\n\n private fina... |
Clausr__advent_of_code__dd33c88/src/main/aoc2022/Day13.kt | package aoc2022
class Day13(val input: String) {
sealed class Packets : Comparable<Packets> {
data class Single(val value: Int) : Packets()
data class Multi(val packets: List<Packets>) : Packets()
private fun Single.toList() = Multi(listOf(this))
override fun compareTo(other: Packets): Int {
when {
this is Single && other is Single -> {
return this.value.compareTo(other.value)
}
this is Multi && other is Multi -> {
repeat(minOf(this.packets.size, other.packets.size)) { i ->
val comparison = this.packets[i].compareTo(other.packets[i])
if (comparison != 0) {
return comparison
}
}
return this.packets.size.compareTo(other.packets.size)
}
else -> when {
this is Single -> return this.toList().compareTo(other)
other is Single -> return this.compareTo(other.toList())
}
}
throw IllegalStateException("Bad comparison: $this :: $other")
}
companion object {
fun parse(input: String): Packets {
val list = input.substring(1, input.lastIndex)
return Multi(
if (list.isEmpty()) {
emptyList()
} else {
buildList {
var index = 0
while (index < list.length) {
if (list[index] == '[') {
val parenthesis = ArrayDeque<Unit>()
parenthesis.addLast(Unit)
var p = index + 1
while (parenthesis.isNotEmpty()) {
if (list[p] == '[') {
parenthesis.addLast(Unit)
} else if (list[p] == ']') {
parenthesis.removeLast()
}
p++
}
add(parse(list.substring(index, p)))
index = p + 1
} else {
var nextIndex = list.indexOf(',', startIndex = index + 1)
if (nextIndex == -1) {
nextIndex = list.lastIndex + 1
}
add(Single(list.substring(index, nextIndex).toInt()))
index = nextIndex + 1
}
}
}
}
)
}
}
}
private fun String.parseInputPairs(): List<Pair<Packets, Packets>> {
val pairs = this.split("\n\n").map { it.split("\n") }
return pairs.map { Pair(Packets.parse(it[0]), Packets.parse(it[1])) }
}
private fun String.parseInput(): List<Packets> {
return this.split("\n").filter(String::isNotEmpty).map { Packets.parse(it) }
}
fun solvePart1(): Int {
val res = input.parseInputPairs().mapIndexed { index, pair ->
if (pair.first < pair.second) {
index + 1
} else {
0
}
}.sum()
return res
}
fun solvePart2(): Int {
val firstDivider = Packets.parse("[[2]]")
val secondDivider = Packets.parse("[[6]]")
val packets = input.parseInput().plus(listOf(firstDivider, secondDivider)).sorted()
return (packets.indexOf(firstDivider) + 1) * (packets.indexOf(secondDivider) + 1)
}
} | [
{
"class_path": "Clausr__advent_of_code__dd33c88/aoc2022/Day13$Packets$Single.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class aoc2022.Day13$Packets$Single extends aoc2022.Day13$Packets {\n private final int value;\n\n public aoc2022.Day13$Packets$Single(int);\n Code:\n 0: aload_0... |
Clausr__advent_of_code__dd33c88/src/main/aoc2022/Day11.kt | package aoc2022
class Day11(input: List<String>) {
private val monkeys = input.parseMonkeys()
fun solvePart1(): Long {
rounds(numRounds = 20) { it / 3 }
return monkeys.business()
}
fun solvePart2(): Long {
val testProduct = monkeys.map { it.test }.reduce(Long::times)
rounds(numRounds = 10_000) { it % testProduct }
return monkeys.business()
}
private fun List<Monkey>.business(): Long =
sortedByDescending { it.interactions }.let { it[0].interactions * it[1].interactions }
private fun rounds(numRounds: Int, changeToWorryLevel: (Long) -> Long) {
repeat(numRounds) {
monkeys.forEach { it.inspectItems(monkeys, changeToWorryLevel) }
}
}
private fun List<String>.parseMonkeys(): List<Monkey> {
return chunked(7).map { attribute ->
val operationValue = attribute[2].substringAfterLast(" ")
val operation: (Long) -> Long = when {
operationValue == "old" -> ({ it * it })
'*' in attribute[2] -> ({ it * operationValue.toLong() })
else -> ({ it + operationValue.toLong() })
}
Monkey(
items = attribute[1].substringAfter(": ").split(", ").map { it.toLong() }.toMutableList(),
test = attribute[3].substringAfterLast(" ").toLong(),
operation = operation,
testTrue = attribute[4].split(" ").last().toInt(),
testFalse = attribute[5].split(" ").last().toInt()
)
}
}
}
data class Monkey(
val items: MutableList<Long>, //Worry level
val operation: (Long) -> Long,
val test: Long,
val testTrue: Int,
val testFalse: Int
) {
var interactions: Long = 0
fun inspectItems(monkeys: List<Monkey>, changeToWorryLevel: (Long) -> Long) {
items.forEach { item ->
val worry = changeToWorryLevel(operation(item))
val target = if (worry % test == 0L) testTrue else testFalse
monkeys[target].items.add(worry)
}
interactions += items.size
items.clear()
}
} | [
{
"class_path": "Clausr__advent_of_code__dd33c88/aoc2022/Day11.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class aoc2022.Day11 {\n private final java.util.List<aoc2022.Monkey> monkeys;\n\n public aoc2022.Day11(java.util.List<java.lang.String>);\n Code:\n 0: aload_1\n 1: ldc ... |
Clausr__advent_of_code__dd33c88/src/main/aoc2023/Day02.kt | package aoc2023
class Day02(input: List<String>) {
private val parsedInput = input.map {
val gameId = it.substringBefore(":").split(" ").last().toInt()
println("GameID: $gameId")
val rawThrows = it.substringAfter(": ")
val reveals = rawThrows.split("; ")
val cubesInReveals = reveals.map {
it.split(", ").map {
val reveal = it.split(" ")
reveal.first().toInt() to reveal.last()
}
}
Game(gameId, cubesInReveals)
}
data class Game(
val id: Int,
val throws: List<List<Pair<Int, String>>>
)
// Rules: only 12 red cubes, 13 green cubes, and 14 blue cubes
fun solvePart1(): Int {
val result = parsedInput.sumOf { game ->
val possible = game.throws.all { t ->
t.all { t1 ->
when {
t1.second == "red" -> t1.first <= 12
t1.second == "green" -> t1.first <= 13
t1.second == "blue" -> t1.first <= 14
else -> {
println("Lel"); false
}
}
}
}
if (possible) game.id else 0
}
return result
}
fun solvePart2(): Int {
return parsedInput.sumOf { game ->
val flat = game.throws.flatten()
val r = flat.filter { it.second == "red" }.maxOf { it.first }
val g = flat.filter { it.second == "green" }.maxOf { it.first }
val b = flat.filter { it.second == "blue" }.maxOf { it.first }
r * g * b
}
}
} | [
{
"class_path": "Clausr__advent_of_code__dd33c88/aoc2023/Day02$Game.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class aoc2023.Day02$Game {\n private final int id;\n\n private final java.util.List<java.util.List<kotlin.Pair<java.lang.Integer, java.lang.String>>> throws;\n\n public aoc2023.D... |
Clausr__advent_of_code__dd33c88/src/main/aoc2023/Day01.kt | package aoc2023
class Day01(val input: List<String>) {
fun solvePart1(): Int {
val sum = input.sumOf {
addFirstAndLastDigit(it)
}
return sum
}
private fun addFirstAndLastDigit(line: String): Int {
val first = line.first { it.isDigit() }
val last = line.last { it.isDigit() }
return "$first$last".toInt()
}
val words = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9
)
private fun String.possibleWordsAt(startingAt: Int): List<String> =
(3..5).map { len ->
substring(startingAt, (startingAt + len).coerceAtMost(length))
}
fun solvePart2(): Int {
val sum = input.sumOf {
addFirstAndLastDigit(
it.mapIndexedNotNull { index, c ->
if (c.isDigit()) c
else
it.possibleWordsAt(index).firstNotNullOfOrNull {candidate ->
words[candidate]
}
}.joinToString()
)
}
return sum
}
} | [
{
"class_path": "Clausr__advent_of_code__dd33c88/aoc2023/Day01.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class aoc2023.Day01 {\n private final java.util.List<java.lang.String> input;\n\n private final java.util.Map<java.lang.String, java.lang.Integer> words;\n\n public aoc2023.Day01(java... |
Clausr__advent_of_code__dd33c88/src/main/aoc2018/Day10.kt | package aoc2018
class Day10(input: List<String>) {
private val lights = input.map(Light::from)
fun solvePart1(): String {
val message = Sky(lights).getMessageWithLeastArea()
println(message.second)
return message.first
}
fun solvePart2(): Int {
val message = Sky(lights).getMessageWithLeastArea()
return message.second
}
data class Light(var x: Int, var y: Int, val velocityX: Int, val velocityY: Int) {
fun move(direction: Direction) = when (direction) {
Direction.Forward -> {
x += velocityX
y += velocityY
}
Direction.Backward -> {
x -= velocityX
y -= velocityY
}
}
companion object {
fun from(line: String): Light {
val (x, y) = line.substringAfter("<").substringBefore(">").trimAndSplitBy(",")
val (velocityX, velocityY) = line.substringAfterLast("<").substringBeforeLast(">").trimAndSplitBy(",")
return Light(x.toInt(), y.toInt(), velocityX.toInt(), velocityY.toInt())
}
}
}
enum class Direction {
Forward, Backward
}
data class Sky(val lights: List<Light>) {
/**
* For this to make sense, we assume that the message shows itself when the area of all the lights are the smallest
* This might be naïve, but it seems to work with this task.
* It would've failed if the stars all started from the center of the sky
*/
fun getMessageWithLeastArea(): Pair<String, Int> {
var lastArea = Long.MAX_VALUE
var currentArea = calculateCurrentArea()
var seconds = 0
while (lastArea > currentArea) {
moveLights()
seconds += 1
lastArea = currentArea
currentArea = calculateCurrentArea()
}
// We're out of the loop since the lastArea is smaller than the current area,
// so that means we're 1 second too far ahead... Luckily we can just go back in time.
moveLights(direction = Direction.Backward)
return this.toString() to seconds - 1
}
private fun moveLights(direction: Direction = Direction.Forward) = lights.forEach { it.move(direction) }
private val rangeY
get() = IntRange(lights.minOf { it.y }, lights.maxOf { it.y })
private val rangeX
get() = IntRange(lights.minOf { it.x }, lights.maxOf { it.x })
private fun calculateCurrentArea(): Long =
(rangeX.last - rangeX.first).toLong() * (rangeY.last - rangeY.first).toLong()
override fun toString(): String {
val lightSet = lights.map { it.x to it.y }.toSet()
return rangeY.joinToString(separator = "\n") { y ->
rangeX.map { x ->
if (x to y in lightSet) '#' else '.'
}.joinToString("")
}
}
}
}
private fun String.trimAndSplitBy(delimiter: String) = replace("\\s".toRegex(), "").split(delimiter)
| [
{
"class_path": "Clausr__advent_of_code__dd33c88/aoc2018/Day10$Light$WhenMappings.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class aoc2018.Day10$Light$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // ... |
crepppy__coding-challenges__9bcfed8/src/main/kotlin/com/jackchapman/codingchallenges/hackerrank/QueensAttack.kt | package com.jackchapman.codingchallenges.hackerrank
import kotlin.math.abs
/**
* Problem: [Queen's Attack II](https://www.hackerrank.com/challenges/queens-attack-2/)
*
* Given a chess board and a list of obstacles, find the number of valid moves a queen can make
* @param size The size of the chess board
* @param k The number of obstacles on the board
* @param obstacles An array of obstacles represented as an array of two integers (it's y and x coordinate)
* @return The number of valid moves a queen could make
*/
fun queensAttack(size: Int, k: Int, y: Int, x: Int, obstacles: Array<IntArray>): Int {
val closest = obstacles.asSequence()
.filter { it[0] == y || it[1] == x || abs(it[0] - y) == abs(it[1] - x) }
.groupBy { (if (it[0] > y) 1 else if (it[0] < y) 2 else 0) or (if (it[1] > x) 4 else if (it[1] < x) 8 else 0) }
.mapValues { (dir, arr) ->
when {
dir and 1 != 0 -> arr.minByOrNull { it[0] }!!
dir and 2 != 0 -> arr.maxByOrNull { it[0] }!!
dir and 4 != 0 -> arr.minByOrNull { it[1] }!!
dir and 8 != 0 -> arr.maxByOrNull { it[1] }!!
else -> throw IllegalStateException()
}
}
return arrayOf(1, 2, 4, 5, 6, 8, 9, 10).sumOf {
val obstacle = closest[it] ?: return@sumOf minOf(
if (it and 1 != 0) size - y else Int.MAX_VALUE,
if (it and 2 != 0) y - 1 else Int.MAX_VALUE,
if (it and 4 != 0) size - x else Int.MAX_VALUE,
if (it and 8 != 0) x - 1 else Int.MAX_VALUE,
)
maxOf(abs(obstacle[0] - y), abs(obstacle[1] - x)) - 1
}
} | [
{
"class_path": "crepppy__coding-challenges__9bcfed8/com/jackchapman/codingchallenges/hackerrank/QueensAttackKt.class",
"javap": "Compiled from \"QueensAttack.kt\"\npublic final class com.jackchapman.codingchallenges.hackerrank.QueensAttackKt {\n public static final int queensAttack(int, int, int, int, int... |
crepppy__coding-challenges__9bcfed8/src/main/kotlin/com/jackchapman/codingchallenges/hackerrank/EmasSupercomputer.kt | package com.jackchapman.codingchallenges.hackerrank
typealias Plus = List<Pair<Int, Int>>
/**
* Problem: [Ema's Supercomputer](https://www.hackerrank.com/challenges/two-pluses/)
*
* Given a matrix of good (`G`) cells and bad (`B`) cells, find 2 pluses made of
* good cells whose area has the greatest product
* @param grid A 2D character matrix made of good and bad cells
* @return The product of the 2 largest pluses
*/
fun twoPluses(grid: Array<String>): Int {
val m = grid.map { it.toCharArray() }
return m.maxOf { i, j ->
var firstRadius = 0
var curMax = 0
var firstPlus = cross(i, j, firstRadius)
while (firstPlus.isValid(m)) {
curMax = maxOf(curMax, firstPlus.size * m.maxOf(i, j) { y, x ->
var secondRadius = 0
var secondPlus: Plus
do secondPlus = cross(y, x, secondRadius++)
while (secondPlus.isValid(m) && secondPlus.none { it in firstPlus })
secondPlus.size - 4
})
firstPlus = cross(i, j, ++firstRadius)
}
curMax
}
}
/**
* Returns the largest value among all values produced by selector function applied to each element in the matrix
* @see Iterable.maxOf
*/
private inline fun List<CharArray>.maxOf(startY: Int = 0, startX: Int = 0, receiver: (Int, Int) -> Int) =
(startY until size).maxOf { i -> (startX until first().size).maxOf { j -> receiver(i, j) } }
/**
* Ensures that each index in a list of indices is inside a given matrix and is a 'good' cell
*/
private fun Plus.isValid(matrix: List<CharArray>): Boolean =
none { (y, x) -> y !in matrix.indices || x !in matrix[0].indices } && map { (y, x) -> matrix[y][x] }.none { it != 'G' }
/**
* Given an index of the centre of a plus, determine all the indices of each of the cells in the plus
*/
private fun cross(row: Int, col: Int, n: Int): Plus =
((col - n until col) + (col + 1..col + n)).map { row to it } + (row - n..row + n).map { it to col } | [
{
"class_path": "crepppy__coding-challenges__9bcfed8/com/jackchapman/codingchallenges/hackerrank/EmasSupercomputerKt.class",
"javap": "Compiled from \"EmasSupercomputer.kt\"\npublic final class com.jackchapman.codingchallenges.hackerrank.EmasSupercomputerKt {\n public static final int twoPluses(java.lang.S... |
arryaaas__Matrix-Calculator__393d2e9/app/src/main/java/com/arya/matrixcalculator/logic/InverseOperation.kt | package com.arya.matrixcalculator.logic
object InverseOperation {
// const val N = 3
// Function to get cofactor of A[p][q] in temp[][]. n is current
// dimension of A[][]
private fun getCofactor(A: Array<Array<Float>>, temp: Array<Array<Float>>, p: Int, q: Int, n: Int) {
var i = 0
var j = 0
// Looping for each element of the matrix
for (row in 0 until n) {
for (col in 0 until n) { // Copying into temporary matrix only those element
// which are not in given row and column
if (row != p && col != q) {
temp[i][j++] = A[row][col]
// Row is filled, so increase row index and
// reset col index
if (j == n - 1) {
j = 0
i++
}
}
}
}
}
/* Recursive function for finding determinant of matrix.
n is current dimension of A[][]. */
private fun determinant(A: Array<Array<Float>>, n: Int): Float {
val x = A.size
var d = 0F // Initialize result
// Base case : if matrix contains single element
if (n == 1) return A[0][0]
val temp: Array<Array<Float>> // To store cofactors
temp = Array(x) {Array(x) {0f} } //Array(N) { FloatArray(N) }
var sign = 1 // To store sign multiplier
// Iterate for each element of first row
for (f in 0 until n) { // Getting Cofactor of A[0][f]
getCofactor(
A,
temp,
0,
f,
n
)
d += sign * A[0][f] * determinant(
temp,
n - 1
)
// terms are to be added with alternate sign
sign = -sign
}
return d
}
// Function to get adjoint of A[N][N] in adj[N][N].
private fun adjoint(A: Array<Array<Float>>, adj: Array<Array<Float>>) {
val n = A.size
if (n == 1) {
adj[0][0] = 1F
return
}
// temp is used to store cofactors of A[][]
var sign: Int
val temp = Array(n) {Array(n) {0f} }
for (i in 0 until n) {
for (j in 0 until n) { // Get cofactor of A[i][j]
getCofactor(
A,
temp,
i,
j,
n
)
// sign of adj[j][i] positive if sum of row
// and column indexes is even.
sign = if ((i + j) % 2 == 0) 1 else -1
// Interchanging rows and columns to get the
// transpose of the cofactor matrix
adj[j][i] = sign * determinant(
temp,
n - 1
)
}
}
}
// Function to calculate and store inverse, returns false if
// matrix is singular
private fun inverse(
A: Array<Array<Float>>,
inverse: Array<Array<Float>>
): Boolean { // Find determinant of A[][]
val n = A.size
val det =
determinant(A, n)
if (det == 0F) {
print("Singular matrix, can't find its inverse")
return false
}
// Find adjoint
val adj = Array(n) {Array(n) {0f} }//Array(N) { IntArray(N) }
adjoint(A, adj)
// Find Inverse using formula "inverse(A) = adj(A)/det(A)"
for (i in 0 until n) for (j in 0 until n) inverse[i][j] =
adj[i][j] / det
return true
}
fun mainInverse(
matrix1: Array<Array<Float>>,
matrixResult: Array<Array<Float>>
) {
val n = matrix1.size
val adj =
Array(n) {Array(n) {0f} } // To store adjoint of A[][]
val inv =
Array(n) {Array(n) {0f} } // To store inverse of A[][]
adjoint(matrix1, adj)
if (inverse(
matrix1,
inv
)
)
for (i: Int in inv.indices)
for (j: Int in inv[0].indices)
matrixResult[i][j] = inv[i][j]
}
} | [
{
"class_path": "arryaaas__Matrix-Calculator__393d2e9/com/arya/matrixcalculator/logic/InverseOperation.class",
"javap": "Compiled from \"InverseOperation.kt\"\npublic final class com.arya.matrixcalculator.logic.InverseOperation {\n public static final com.arya.matrixcalculator.logic.InverseOperation INSTAN... |
PartlyFluked__PASS-android__d2540dc/app/src/main/java/com/example/SecretService/KylesMathPack.kt | package com.example.SecretService
/**
* Created by menta on 29/03/2018.
*/
import java.lang.Math.pow
fun List<Int>.innerProduct(B:List<Int>): Int {
return zip(B)
.map { it.first * it.second }
.sum()
}
fun List<Int>.vandermond(): List<List<Int>> {
return map { xval -> List<Int>(size, {it:Int -> pow(xval.toDouble(), it.toDouble()).toInt()}) }
}
fun List<Int>.polyeval(input: Int): Int {
return foldIndexed(0, {index:Int, soFar:Int, next:Int -> soFar + next*pow(input.toDouble(), index.toDouble()).toInt()})
//foldRight(0, { soFar, alpha -> alpha + soFar * input })
}
fun List<Int>.polyAdd(summand:List<Int>): List<Int> {
return mapIndexed{index, next -> next + summand.get(index)}
}
fun List<Int>.polyMult(multipland: List<Int>): List<Int> {
return foldIndexed( multipland , { index, soFar, next -> soFar
.polyAdd(List<Int>( index,{0}) + multipland.map{it*next} )
})
}
fun List<List<Int>>.transpose(): List<List<Int>> {
return mapIndexed{ rownum, row -> row.mapIndexed{ colnum, col -> get(colnum)[rownum] }
}
}
fun List<List<Int>>.submatrix( droprow: Int, dropcol: Int ): List<List<Int>> {
return filterIndexed { index, _ -> index != droprow }
.map { it.filterIndexed { index, _ -> index != dropcol } }
.fold( listOf(), { current, next -> current.plusElement(next) } )
}
fun List<List<Int>>.det(): Int {
return if (size > 1) mapIndexed { colnum, _ -> submatrix(0, colnum).det() }
.mapIndexed { index, entry -> entry * pow(-1.0, index.toDouble()).toInt() }
.innerProduct( get(0) ) else get(0)[0]
}
fun List<List<Int>>.cofactor(): List<List<Int>> {
return mapIndexed { rownum: Int, row: List<Int> -> row.mapIndexed { colnum, _ -> submatrix(rownum, colnum).det()* pow(-1.0, (colnum+rownum).toDouble()).toInt() }
}
}
fun List<List<Int>>.invert(): List<List<Int>>{
return cofactor()
.transpose()
.map{ row -> row
.map{ entry -> entry }} //divide det()
}
fun List<List<Int>>.matrixMultiplyRight( B: List<List<Int>> ): List<List<Int>> {
return mapIndexed { rownum:Int, brow -> brow
.mapIndexed { colnum:Int, _ -> brow
.innerProduct( B.transpose()[colnum] )
}
}
} | [
{
"class_path": "PartlyFluked__PASS-android__d2540dc/com/example/SecretService/KylesMathPackKt.class",
"javap": "Compiled from \"KylesMathPack.kt\"\npublic final class com.example.SecretService.KylesMathPackKt {\n public static final int innerProduct(java.util.List<java.lang.Integer>, java.util.List<java.l... |
salamanders__nrsc5-chopper__c19094a/src/main/kotlin/info/benjaminhill/fm/chopper/TimedEvent.kt | package info.benjaminhill.fm.chopper
import java.time.Duration
import java.time.Instant
/**
* A timed event is a pair of "stuff (state) that happened at time (ts)"
* The idea is to keep a collection (ArrayDeque?) of these to record when things first happened.
*/
data class InstantState<T>(
val ts: Instant,
val state: T,
)
data class DurationState<T>(
val duration: Duration,
val state: T,
)
fun <T> List<InstantState<T>>.toDurations(
contiguous: Boolean = false,
maxTtl: Duration
) = if (contiguous) {
maxContiguousDurations(maxTtl)
} else {
sumDurations(maxTtl)
}
private fun <T> List<InstantState<T>>.sumDurations(
maxTtl: Duration,
): List<DurationState<T>> =
this.asSequence().zipWithNext().map { (is0, is1) ->
DurationState(
state = is0.state,
duration = Duration.between(is0.ts, is1.ts).coerceAtMost(maxTtl),
)
}.groupingBy { it.state }
.fold(Duration.ZERO) { acc, elt ->
acc + elt.duration
}.map {
DurationState(
duration = it.value,
state = it.key
)
}.toList()
/**
* Longest contiguous duration
*/
private fun <T> List<InstantState<T>>.maxContiguousDurations(
maxTtl: Duration,
): List<DurationState<T>> {
val maxContiguous = mutableMapOf<T, Duration>()
this.distinctBy { it.state }.forEach {
maxContiguous[it.state] = Duration.ZERO
}
var currentState: T? = null
var currentDuration: Duration = Duration.ZERO
this.zipWithNext().forEach { (event0, event1): Pair<InstantState<T>, InstantState<T>> ->
val (ts0, state0) = event0
val (ts1, _) = event1
if (currentState != state0) {
currentState = state0
currentDuration = Duration.ZERO
}
currentDuration += Duration.between(ts0, ts1).coerceAtMost(maxTtl)
if (currentDuration > maxContiguous[currentState]) {
maxContiguous[currentState!!] = currentDuration
}
}
return maxContiguous.map {
DurationState(
duration = it.value,
state = it.key
)
}
}
| [
{
"class_path": "salamanders__nrsc5-chopper__c19094a/info/benjaminhill/fm/chopper/TimedEventKt$sumDurations$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Sequences.kt\"\npublic final class info.benjaminhill.fm.chopper.TimedEventKt$sumDurations$$inlined$groupingBy$1 implements kotlin.collections.G... |
valery1707__problem-solving__76d175f/src/main/kotlin/name/valery1707/problem/leet/code/IntegerToRomanK.kt | package name.valery1707.problem.leet.code
/**
* # 12. Integer to Roman
*
* Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
*
* | Symbol | Value |
* |--------|-------|
* | `I` | `1` |
* | `V` | `5` |
* | `X` | `10` |
* | `L` | `50` |
* | `C` | `100` |
* | `D` | `500` |
* | `M` | `1000` |
*
* For example, `2` is written as `II` in Roman numeral, just two ones added together.
* `12` is written as `XII`, which is simply `X + II`.
* The number `27` is written as `XXVII`, which is `XX + V + II`.
*
* Roman numerals are usually written largest to smallest from left to right.
* However, the numeral for four is not `IIII`.
* Instead, the number four is written as `IV`.
* Because the one is before the five we subtract it making four.
* The same principle applies to the number nine, which is written as `IX`.
* There are six instances where subtraction is used:
* * `I` can be placed before `V` (`5`) and `X` (`10`) to make `4` and `9`.
* * `X` can be placed before `L` (`50`) and `C` (`100`) to make `40` and `90`.
* * `C` can be placed before `D` (`500`) and `M` (`1000`) to make `400` and `900`.
*
* Given an integer, convert it to a roman numeral.
*
* ### Constraints
* * `1 <= num <= 3999`
*
* <a href="https://leetcode.com/problems/integer-to-roman/">12. Integer to Roman</a>
*/
interface IntegerToRomanK {
fun intToRoman(num: Int): String
@Suppress("EnumEntryName", "unused")
enum class Implementation : IntegerToRomanK {
simple {
//Should be static
private val mapper = sortedMapOf(
Comparator.reverseOrder(),
1 to "I", 5 to "V", 10 to "X", 50 to "L", 100 to "C", 500 to "D", 1000 to "M",
4 to "IV", 9 to "IX", 40 to "XL", 90 to "XC", 400 to "CD", 900 to "CM",
)
override fun intToRoman(num: Int): String {
var v = num
val s = StringBuilder()
for ((int, roman) in mapper) {
while (v >= int) {
s.append(roman)
v -= int
}
}
return s.toString()
}
},
optimized {
//Should be static
private val mapper = sortedMapOf(
Comparator.reverseOrder(),
1 to "I", 5 to "V", 10 to "X", 50 to "L", 100 to "C", 500 to "D", 1000 to "M",
4 to "IV", 9 to "IX", 40 to "XL", 90 to "XC", 400 to "CD", 900 to "CM",
)
override fun intToRoman(num: Int): String {
var v = num
val s = StringBuilder()
for ((int, roman) in mapper) {
if (v >= int) {
s.append(roman.repeat(v / int))
v %= int
}
}
return s.toString()
}
},
arrays {
//Should be static
private val integers = intArrayOf(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
private val romans = arrayOf("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
override fun intToRoman(num: Int): String {
var v = num
var i = 0
val s = StringBuilder()
while (i < integers.size && v > 0) {
val int = integers[i]
if (v >= int) {
s.append(romans[i].repeat(v / int))
v %= int
}
i++
}
return s.toString()
}
},
}
}
| [
{
"class_path": "valery1707__problem-solving__76d175f/name/valery1707/problem/leet/code/IntegerToRomanK.class",
"javap": "Compiled from \"IntegerToRomanK.kt\"\npublic interface name.valery1707.problem.leet.code.IntegerToRomanK {\n public abstract java.lang.String intToRoman(int);\n}\n",
"javap_err": ""... |
valery1707__problem-solving__76d175f/src/main/kotlin/name/valery1707/problem/leet/code/CanPlaceFlowersK.kt | package name.valery1707.problem.leet.code
import kotlin.math.max
import kotlin.math.roundToInt
/**
* # 605. Can Place Flowers
*
* You have a long flowerbed in which some of the plots are planted, and some are not.
* However, flowers cannot be planted in **adjacent** plots.
*
* Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means *empty* and `1` means not *empty*, and an integer `n`,
* return *if* `n` new flowers can be planted in the `flowerbed` without violating the no-adjacent-flowers rule.
*
* ### Constraints
* * `1 <= flowerbed.length <= 2 * 10^4`
* * `flowerbed[i]` is `0` or `1`
* * There are no two adjacent flowers in `flowerbed`
* * `0 <= n <= flowerbed.length`
*
* @see <a href="https://leetcode.com/problems/can-place-flowers/">605. Can Place Flowers</a>
*/
interface CanPlaceFlowersK {
fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean
@Suppress("EnumEntryName", "unused")
enum class Implementation : CanPlaceFlowersK {
regexp {
override fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean {
//Цветов больше чем возможных мест в принципе
if (n > (flowerbed.size / 2.0).roundToInt()) {
return false
}
//0 цветов всегда поместится
if (n == 0) {
return true
}
val str = flowerbed
.joinToString(separator = "", prefix = "0", postfix = "0", transform = Int::toString)
val count = "00+".toRegex()
.findAll(str)
.map { it.value.length }
//"0"->[1]->0
//"00"->[2]->0
//"000"->[3]->1
//"0000"->[4]->1
//"00000"->[5]->2
//"000000"->[6]->2
//"0000000"->[7]->3
.map { (it + 1) / 2 - 1 }
.filter { it > 0 }.sum()
return n <= count
}
},
indexes {
override fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean {
//Цветов больше чем возможных мест в принципе
if (n > (flowerbed.size / 2.0).roundToInt()) {
return false
}
//0 цветов всегда поместится
if (n == 0) {
return true
}
val count: (curr: Int, prev: Int) -> Int = { curr, prev ->
val count = curr - prev - 1
//1->0, 2->0, 3->1, 4->1, 5->2, 6->2
max(0, (count + 1) / 2 - 1)
}
var possible = 0
var prevUsed = -2
for (i in flowerbed.indices) {
if (flowerbed[i] == 1) {
possible += count(i, prevUsed)
prevUsed = i
}
}
possible += count(flowerbed.lastIndex + 2, prevUsed)
return n <= possible
}
},
}
}
| [
{
"class_path": "valery1707__problem-solving__76d175f/name/valery1707/problem/leet/code/CanPlaceFlowersK$Implementation$regexp$canPlaceFlowers$str$1.class",
"javap": "Compiled from \"CanPlaceFlowersK.kt\"\nfinal class name.valery1707.problem.leet.code.CanPlaceFlowersK$Implementation$regexp$canPlaceFlowers$s... |
valery1707__problem-solving__76d175f/src/main/kotlin/name/valery1707/problem/leet/code/FizzBuzzK.kt | package name.valery1707.problem.leet.code
/**
* # 412. Fizz Buzz
*
* Given an integer `n`, return a string array answer (**1-indexed**) where:
* * `answer[i] == "FizzBuzz"` if `i` is divisible by `3` and `5`.
* * `answer[i] == "Fizz"` if `i` is divisible by `3`.
* * `answer[i] == "Buzz"` if `i` is divisible by `5`.
* * `answer[i] == i` (as a string) if none of the above conditions are true.
*
* ### Constraints
* * `1 <= n <= 10^4`
*
* <a href="https://leetcode.com/problems/fizz-buzz/">412. Fizz Buzz</a>
*/
interface FizzBuzzK {
fun fizzBuzz(n: Int): List<String>
@Suppress("EnumEntryName", "unused")
enum class Implementation : FizzBuzzK {
pure {
override fun fizzBuzz(n: Int): List<String> {
return (1..n).map {
val div3 = it % 3 == 0
val div5 = it % 5 == 0
if (div3 && div5) "FizzBuzz"
else if (div3) "Fizz"
else if (div5) "Buzz"
else it.toString()
}
}
},
mutable {
override fun fizzBuzz(n: Int): List<String> {
val res = ArrayList<String>(n)
for (it in 1..n) {
val div3 = it % 3 == 0
val div5 = it % 5 == 0
res.add(
if (div3 && div5) "FizzBuzz"
else if (div3) "Fizz"
else if (div5) "Buzz"
else it.toString()
)
}
return res
}
},
}
}
| [
{
"class_path": "valery1707__problem-solving__76d175f/name/valery1707/problem/leet/code/FizzBuzzK.class",
"javap": "Compiled from \"FizzBuzzK.kt\"\npublic interface name.valery1707.problem.leet.code.FizzBuzzK {\n public abstract java.util.List<java.lang.String> fizzBuzz(int);\n}\n",
"javap_err": ""
}... |
valery1707__problem-solving__76d175f/src/main/kotlin/name/valery1707/problem/leet/code/ConcatenationOfConsecutiveBinaryNumbersK.kt | package name.valery1707.problem.leet.code
import java.math.BigInteger
/**
* # 1680. Concatenation of Consecutive Binary Numbers
*
* Given an integer `n`, return the **decimal value** of the binary string formed by concatenating the binary representations of `1` to `n` in order,
* **modulo** `10^9 + 7`.
*
* ### Constraints
* * `1 <= n <= 10^5`
*
* @see <a href="https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/">1680. Concatenation of Consecutive Binary Numbers</a>
*/
interface ConcatenationOfConsecutiveBinaryNumbersK {
fun concatenatedBinary(n: Int): Int
@Suppress("EnumEntryName", "unused")
enum class Implementation : ConcatenationOfConsecutiveBinaryNumbersK {
naive {
override fun concatenatedBinary(n: Int): Int {
val modulo = (1e9 + 7).toLong().toBigInteger()
return (1..n)
.joinToString(separator = "") { it.toString(2) }
.toBigInteger(2)
.mod(modulo)
.intValueExact()
}
},
sumThenModulo_fold {
override fun concatenatedBinary(n: Int): Int {
val modulo = (1e9 + 7).toLong().toBigInteger()
return n.downTo(1)
.fold(Pair(BigInteger.ZERO, 0)) { sumAndShift, item ->
val shift = sumAndShift.second
val sum = item.toBigInteger().shl(shift).plus(sumAndShift.first)
Pair(sum, shift + item.toString(2).length)
}
.first
.mod(modulo)
.intValueExact()
}
},
sumThenModulo_for {
override fun concatenatedBinary(n: Int): Int {
val modulo = (1e9 + 7).toLong().toBigInteger()
var sum = BigInteger.ZERO
var shift = 0
for (item in n.downTo(1)) {
sum = item.toBigInteger().shl(shift).plus(sum)
shift += item.toString(2).length
}
return sum.mod(modulo).intValueExact()
}
},
/**
* @see <a href="https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/discuss/2612207/Java-oror-Explained-in-Detailoror-Fast-O(N)-Solutionoror-Bit-Manipulation-and-Math">Java || 👍Explained in Detail👍 || Fast O(N) Solution✅ || Bit Manipulation & Math</a>
*/
cheehwatang {
override fun concatenatedBinary(n: Int): Int {
val modulo = (1e9 + 7).toLong()
return (1..n)
.fold(Pair(0L, 0)) { sumAndShift, item ->
// Если мы на текущем элементе перешли на новую степень двойки
val shift = if (item.and(item - 1) == 0) sumAndShift.second + 1 else sumAndShift.second
// Предыдущую накопленную сумму смещаем на количество бит у текущего числа и добавляем к нему текущее число
val sum = sumAndShift.first.shl(shift) + item
// Чтобы не выскочить за границу Int нужно ограничить сумму по указанному модулю
Pair(sum % modulo, shift)
}
.first
.toInt()
}
},
}
}
| [
{
"class_path": "valery1707__problem-solving__76d175f/name/valery1707/problem/leet/code/ConcatenationOfConsecutiveBinaryNumbersK$Implementation$sumThenModulo_fold.class",
"javap": "Compiled from \"ConcatenationOfConsecutiveBinaryNumbersK.kt\"\nfinal class name.valery1707.problem.leet.code.ConcatenationOfCon... |
valery1707__problem-solving__76d175f/src/main/kotlin/name/valery1707/problem/leet/code/BinaryGapK.kt | package name.valery1707.problem.leet.code
import kotlin.math.max
/**
* # 868. Binary Gap
*
* Given a positive integer `n`, find and return the **longest distance** between any two **adjacent** `1`'s in the *binary representation* of `n`.
* If there are no two adjacent `1`'s, return `0`.
*
* Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s).
* The **distance** between two `1`'s is the absolute difference between their bit positions.
* For example, the two `1`'s in "1001" have a distance of `3`.
*
* ### Constraints
* * `1 <= n <= 10^9`
*
* @see <a href="https://leetcode.com/problems/binary-gap/">868. Binary Gap</a>
*/
interface BinaryGapK {
fun binaryGap(n: Int): Int
@Suppress("EnumEntryName", "unused")
enum class Implementation : BinaryGapK {
naive {
override fun binaryGap(n: Int): Int {
var max = 0
var mask = 1
var curr = 0
var prev = -1
while (mask < n) {
if (n.and(mask) == mask) {
if (prev in 0 until curr) {
max = max(curr - prev, max)
}
prev = curr
}
mask = mask shl 1
curr++
}
return max
}
},
}
}
| [
{
"class_path": "valery1707__problem-solving__76d175f/name/valery1707/problem/leet/code/BinaryGapK.class",
"javap": "Compiled from \"BinaryGapK.kt\"\npublic interface name.valery1707.problem.leet.code.BinaryGapK {\n public abstract int binaryGap(int);\n}\n",
"javap_err": ""
},
{
"class_path": "... |
valery1707__problem-solving__76d175f/src/main/kotlin/name/valery1707/problem/leet/code/RomanToIntegerK.kt | package name.valery1707.problem.leet.code
/**
* # 13. Roman to Integer
*
* Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
*
* | Symbol | Value |
* |--------|-------|
* | `I` | `1` |
* | `V` | `5` |
* | `X` | `10` |
* | `L` | `50` |
* | `C` | `100` |
* | `D` | `500` |
* | `M` | `1000` |
*
* For example, `2` is written as `II` in Roman numeral, just two ones added together.
* `12` is written as `XII`, which is simply `X + II`.
* The number `27` is written as `XXVII`, which is `XX + V + II`.
*
* Roman numerals are usually written largest to smallest from left to right.
* However, the numeral for four is not `IIII`.
* Instead, the number four is written as `IV`.
* Because the one is before the five we subtract it making four.
* The same principle applies to the number nine, which is written as `IX`.
* There are six instances where subtraction is used:
* * `I` can be placed before `V` (`5`) and `X` (`10`) to make `4` and `9`.
* * `X` can be placed before `L` (`50`) and `C` (`100`) to make `40` and `90`.
* * `C` can be placed before `D` (`500`) and `M` (`1000`) to make `400` and `900`.
*
* Given a roman numeral, convert it to an integer.
*
* ### Constraints
* * `1 <= s.length <= 15`
* * `s` contains only the characters (`'I', 'V', 'X', 'L', 'C', 'D', 'M'`)
* * It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`
*
* <a href="https://leetcode.com/problems/roman-to-integer/">13. Roman to Integer</a>
*/
interface RomanToIntegerK {
fun romanToInt(s: String): Int
@Suppress("EnumEntryName", "unused")
enum class Implementation : RomanToIntegerK {
/**
* Parse only valid values.
*/
maps {
//Should be static
private val values = mapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000)
private val prefix = mapOf('I' to setOf('V', 'X'), 'X' to setOf('L', 'C'), 'C' to setOf('D', 'M'))
override fun romanToInt(s: String): Int {
val max = s.length - 1
var sum = 0
var i = 0
while (i <= max) {
val c = s[i]
sum += if (c in prefix && i < max && s[i + 1] in prefix[c]!!) {
values[s[++i]]!! - values[c]!!
} else {
values[c]!!
}
i++
}
return sum
}
},
/**
* Logic:
* * Parse valid `IV`:
* * `prev == 0 && curr == 5 => sum = 0 + 5`
* * `prev == 5 && curr == 1 => sum = 5 - 1`
* * `sum == 4`
* * Parse also invalid `IM`:
* * `prev == 0 && curr == 1000 => sum = 0 + 1000`
* * `prev == 1000 && curr == 1 => sum = 1000 - 1`
* * `sum == 999`
*/
switch {
override fun romanToInt(s: String): Int {
var sum = 0
var prev = 0
for (i in (s.length - 1).downTo(0)) {
val curr = when (s[i]) {
'I' -> 1
'V' -> 5
'X' -> 10
'L' -> 50
'C' -> 100
'D' -> 500
'M' -> 1000
else -> 0
}
sum += if (curr >= prev) curr else -curr
prev = curr
}
return sum
}
},
}
}
| [
{
"class_path": "valery1707__problem-solving__76d175f/name/valery1707/problem/leet/code/RomanToIntegerK$Implementation.class",
"javap": "Compiled from \"RomanToIntegerK.kt\"\npublic abstract class name.valery1707.problem.leet.code.RomanToIntegerK$Implementation extends java.lang.Enum<name.valery1707.problem... |
iafsilva__codility-lessons__5d86aef/src/main/kotlin/lesson3/FrogJmp.kt | package lesson3
/**
* A small frog wants to get to the other side of the road.
*
* The frog is currently located at position X and wants to get to a position greater than or equal to Y.
*
* The small frog always jumps a fixed distance, D.
*
* Count the minimal number of jumps that the small frog must perform to reach its target.
*
* Write a function:
*
* fun solution(X: Int, Y: Int, D: Int): Int
*
* that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
*
* For example, given:
* ```
* X = 10
* Y = 85
* D = 30
* ```
* the function should return 3, because the frog will be positioned as follows:
* ```
* after the first jump, at position 10 + 30 = 40
* after the second jump, at position 10 + 30 + 30 = 70
* after the third jump, at position 10 + 30 + 30 + 30 = 100
* ```
* Write an efficient algorithm for the following assumptions:
*
* - X, Y and D are integers within the range [1..1,000,000,000];
* - X ≤ Y.
*/
class FrogJmp {
fun solution(x: Int, y: Int, d: Int): Int {
val distance = y - x
val jumps = distance / d
// If the jumps are 1.1, that means 2 jumps.
return if (distance % d == 0) jumps else jumps + 1
}
}
| [
{
"class_path": "iafsilva__codility-lessons__5d86aef/lesson3/FrogJmp.class",
"javap": "Compiled from \"FrogJmp.kt\"\npublic final class lesson3.FrogJmp {\n public lesson3.FrogJmp();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ... |
iafsilva__codility-lessons__5d86aef/src/main/kotlin/lesson3/PermMissingElem.kt | package lesson3
/**
* An array A consisting of N different integers is given.
*
* The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
*
* Your goal is to find that missing element.
*
* Write a function:
*
* fun solution(A: IntArray): Int
*
* that, given an array A, returns the value of the missing element.
*
* For example, given array A such that:
* ```
* A[0] = 2
* A[1] = 3
* A[2] = 1
* A[3] = 5
* ```
* the function should return 4, as it is the missing element.
*
* Write an efficient algorithm for the following assumptions:
*
* - N is an integer within the range [0..100,000];
* - the elements of A are all distinct;
* - each element of array A is an integer within the range [1..(N + 1)].
*/
class PermMissingElem {
fun solution(a: IntArray): Int {
// First edge case: missing is the first nr
if (a.isEmpty()) return 1
a.sort()
for (i in a.indices) {
// Index 0 must be 1, Index 1 must be 2, and so on.
// Whenever that's not true, we found our missing nr
if (a[i] != i + 1) return i + 1
}
// Second edge case: missing is the last nr
return a.size + 1
}
}
| [
{
"class_path": "iafsilva__codility-lessons__5d86aef/lesson3/PermMissingElem.class",
"javap": "Compiled from \"PermMissingElem.kt\"\npublic final class lesson3.PermMissingElem {\n public lesson3.PermMissingElem();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lan... |
iafsilva__codility-lessons__5d86aef/src/main/kotlin/lesson2/CyclicRotation.kt | package lesson2
/**
* An array A consisting of N integers is given.
*
* Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place.
*
* For example, the rotation of array A = [[3, 8, 9, 7, 6]] is [[6, 3, 8, 9, 7]] (elements are shifted right by one index and 6 is moved to the first place).
*
* The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
* Write a function:
*
* fun solution(A: IntArray, K: Int): IntArray
*
* that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
*
* For example, given:
* A = [[3, 8, 9, 7, 6]]
* K = 3
* the function should return [9, 7, 6, 3, 8].
*
* Three rotations were made:
* ```
* [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
* [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
* [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
* ```
*
* For another example, given:
* A = [[0, 0, 0]]
* K = 1
* the function should return [[0, 0, 0]]
*
* Given:
* A = [[1, 2, 3, 4]]
* K = 4
* the function should return [[1, 2, 3, 4]]
*
* Assume that:
* - N and K are integers within the range [[0..100]];
* - each element of array A is an integer within the range [[−1,000..1,000]].
*
* In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
*/
class CyclicRotation {
fun solution(a: IntArray, k: Int): IntArray {
// If no rotation or rotation leaves the array as is, return immediately
if (k == 0 || a.isEmpty() || k % a.size == 0) return a
// Reduce to the minimum amount of rotations needed
val minK = k - (a.size * (k / a.size))
val initialArray = a.toCollection(ArrayDeque())
for (i in 1..minK) initialArray.addFirst(initialArray.removeLast())
return initialArray.toIntArray()
}
}
| [
{
"class_path": "iafsilva__codility-lessons__5d86aef/lesson2/CyclicRotation.class",
"javap": "Compiled from \"CyclicRotation.kt\"\npublic final class lesson2.CyclicRotation {\n public lesson2.CyclicRotation();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Ob... |
iafsilva__codility-lessons__5d86aef/src/main/kotlin/lesson2/OddOccurrencesInArray.kt | package lesson2
/**
* A non-empty array A consisting of N integers is given.
* The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
*
* For example, in array A such that:
* ```
* A[0] = 9 A[1] = 3 A[2] = 9
* A[3] = 3 A[4] = 9 A[5] = 7
* A[6] = 9
* ```
* the elements at indexes 0 and 2 have value 9,
* the elements at indexes 1 and 3 have value 3,
* the elements at indexes 4 and 6 have value 9,
* the element at index 5 has value 7 and is unpaired.
*
* Write a function:
*
* fun solution(A: IntArray): Int
*
* that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
*
* For example, given array A such that:
* ```
* A[0] = 9 A[1] = 3 A[2] = 9
* A[3] = 3 A[4] = 9 A[5] = 7
* A[6] = 9
* ```
* the function should return 7, as explained in the example above.
*
* Write an efficient algorithm for the following assumptions:
* - N is an odd integer within the range [1..1,000,000];
* - each element of array A is an integer within the range [1..1,000,000,000];
* - all but one of the values in A occur an even number of times.
*/
class OddOccurrencesInArray {
fun solution(a: IntArray): Int {
var unpairedElement = 0
for (element in a) unpairedElement = unpairedElement xor element
return unpairedElement
}
} | [
{
"class_path": "iafsilva__codility-lessons__5d86aef/lesson2/OddOccurrencesInArray.class",
"javap": "Compiled from \"OddOccurrencesInArray.kt\"\npublic final class lesson2.OddOccurrencesInArray {\n public lesson2.OddOccurrencesInArray();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
iafsilva__codility-lessons__5d86aef/src/main/kotlin/lesson1/BinaryGap.kt | package lesson1
/**
* A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
*
* For example:
* - The number 9 has binary representation 1001 and contains a binary gap of length 2.
* - The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3.
* - The number 20 has binary representation 10100 and contains one binary gap of length 1.
* - The number 15 has binary representation 1111 and has no binary gaps.
* - The number 32 has binary representation 100000 and has no binary gaps.
*
* Write a function:
*
* class Solution { public int solution(int N); }
*
* that, given a positive integer N, returns the length of its longest binary gap.
* The function should return 0 if N doesn't contain a binary gap.
*
* For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
* Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [1..2,147,483,647].
*/
class BinaryGap {
fun solution(n: Int): Int {
var longestBinaryGap = 0
var currentBinaryGap = 0
var isCounting = false
// Get binary representation
val binaryString = Integer.toBinaryString(n)
for (char in binaryString) {
when {
// If we were already counting means binary gap ended
char == '1' && isCounting -> {
if (currentBinaryGap > longestBinaryGap) {
longestBinaryGap = currentBinaryGap
}
currentBinaryGap = 0
}
// When finding a 1 start counting
char == '1' -> isCounting = true
// When counting -> increment our binary gap
char == '0' && isCounting -> currentBinaryGap++
}
}
return longestBinaryGap
}
}
| [
{
"class_path": "iafsilva__codility-lessons__5d86aef/lesson1/BinaryGap.class",
"javap": "Compiled from \"BinaryGap.kt\"\npublic final class lesson1.BinaryGap {\n public lesson1.BinaryGap();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\... |
cweckerl__aoc__612badf/src/d09/Main.kt | package d09
import java.io.File
import kotlin.math.pow
import kotlin.math.sqrt
fun main() {
fun dist(p1: Pair<Int, Int>, p2: Pair<Int, Int>) = sqrt(
(p1.first - p2.first).toDouble().pow(2) +
(p1.second - p2.second).toDouble().pow(2)
)
fun part1(input: List<String>) {
var h = Pair(0, 0)
var t = Pair(0, 0)
var prev = Pair(0, 0)
val visited = mutableSetOf<Pair<Int, Int>>()
visited.add(prev)
input.forEach {
val (d, m) = it.split(' ')
// dist, mag
repeat(m.toInt()) {
prev = h
h = when (d) {
"U" -> h.copy(second = h.second + 1)
"D" -> h.copy(second = h.second - 1)
"L" -> h.copy(first = h.first - 1)
else -> h.copy(first = h.first + 1)
}
if (dist(h, t) > sqrt(2.0)) {
t = prev.copy()
visited.add(t)
}
}
}
println(visited.size)
}
fun part2(input: List<String>) {
val p = MutableList(10) { Pair(0, 0) }
var prev = Pair(0, 0)
val visited = mutableSetOf<Pair<Int, Int>>()
visited.add(prev)
input.forEach { line ->
val (d, m) = line.split(' ')
repeat(m.toInt()) {
prev = p[0]
p[0] = when (d) {
"U" -> p[0].copy(second = p[0].second + 1)
"D" -> p[0].copy(second = p[0].second - 1)
"L" -> p[0].copy(first = p[0].first - 1)
else -> p[0].copy(first = p[0].first + 1)
}
for (i in 0 until p.size - 1) {
if (dist(p[i], p[i + 1]) > sqrt(2.0)) {
val dx = prev.first - p[1].first
val dy = prev.second - p[1].second
val indices = mutableSetOf(1)
for (j in i + 1 until p.size - 1) {
if (dist(p[j], p[j + 1]) != 1.0) {
break
}
indices.add(j + 1)
}
indices.forEach { p[it] = p[it].copy(p[it].first + dx, p[it].second + dy) }
visited.add(p.last())
}
}
}
}
println(visited.size)
}
val input = File("src/d09/input").readLines()
part1(input)
part2(input)
} | [
{
"class_path": "cweckerl__aoc__612badf/d09/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class d09.MainKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 // Str... |
cweckerl__aoc__612badf/src/d07/Main.kt | package d07
import java.io.File
fun main() {
data class Trie(
val dir: String,
val children: MutableMap<String, Trie> = mutableMapOf(),
val parent: Trie? = null,
var dirSize: Long = 0L
)
// combining parts for this day
val input = File("src/d07/input").readLines()
val root = Trie("/")
var curr = root
input.drop(1).forEach {
if (it.startsWith("$ cd")) {
val dir = it.split(' ')[2]
curr = if (dir == "..") curr.parent!! else curr.children[dir]!!
} else if (it.startsWith("dir")) {
val dir = it.split(' ')[1]
curr.children[dir] = Trie(dir = "${curr.dir}/$dir", parent = curr)
} else if (!it.startsWith("$ ls")) {
curr.dirSize += it.split(' ')[0].toLong()
}
}
val sizes = mutableMapOf<String, Long>()
fun traverse(root: Trie): Long {
val tmp = root.dirSize + root.children.values.sumOf { traverse(it) }
sizes[root.dir] = tmp
return tmp
}
traverse(root)
println(sizes.values.sumOf { if (it <= 100000) it else 0 }) // part 1
val total = sizes["/"]!!
println(sizes.values.filter { 70000000 - total + it >= 30000000 }.min()) // part 2
}
| [
{
"class_path": "cweckerl__aoc__612badf/d07/MainKt$main$Trie.class",
"javap": "Compiled from \"Main.kt\"\npublic final class d07.MainKt$main$Trie {\n private final java.lang.String dir;\n\n private final java.util.Map<java.lang.String, d07.MainKt$main$Trie> children;\n\n private final d07.MainKt$main$Tri... |
cweckerl__aoc__612badf/src/d08/Main.kt | package d08
import java.io.File
fun main() {
fun part1(input: List<String>) {
var trees = 0
val visited = mutableMapOf<Int, Char>()
for (i in input.indices) {
for (j in input[0].indices) {
if (i == 0 || i == input.size - 1 || j == 0 || j == input[0].length - 1) {
if (i == 0) visited[j] = input[i][j]
trees++
} else {
val tree = input[i][j]
val left = input[i].substring(0, j)
val right = input[i].substring(j + 1)
if (tree > visited[j]!!) {
trees++
visited[j] = tree
} else if (tree > left.max() || tree > right.max() || tree > input.drop(i + 1).maxOf { it[j] }) {
trees++
}
}
}
}
println(trees)
}
fun part2(input: List<String>) {
var score = 0
for (i in input.indices) {
for (j in input[0].indices) {
if (!(i == 0 || i == input.size - 1 || j == 0 || j == input[0].length - 1)) {
val tree = input[i][j]
val left = input[i].substring(0, j).reversed().toList()
val right = input[i].substring(j + 1).toList()
val up = input.subList(0, i).reversed().map { it[j] }
val down = input.drop(i + 1).map { it[j] }
val paths = arrayOf(up, down, left, right)
val tmp = paths.map {
var count = 0
for (t in it) {
count++
if (tree <= t) break
}
count
}.reduce(Int::times)
if (tmp > score) score = tmp
}
}
}
println(score)
}
val input = File("src/d08/input").readLines()
part1(input)
part2(input)
}
| [
{
"class_path": "cweckerl__aoc__612badf/d08/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class d08.MainKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 // Str... |
cweckerl__aoc__612badf/src/d05/Main.kt | package d05
import java.io.File
import java.util.LinkedList
fun main() {
fun part1(input: List<String>) {
val (a, b) = input.partition { !Regex("""move \d+ from \d+ to \d+""").matches(it) }
val crates = mutableMapOf<Int, LinkedList<Char>>()
a.forEach { line ->
line.forEachIndexed { i, c ->
if (c.isLetter()) {
val n = (i / 4) + 1
crates.getOrPut(n) { LinkedList<Char>() }.addLast(c)
}
}
}
b.forEach {
val (n, src, dst) = Regex("""move (\d+) from (\d+) to (\d+)""").find(it)!!.destructured
(0 until n.toInt()).forEach { _ ->
val tmp = crates[src.toInt()]!!.removeFirst()
crates[dst.toInt()]!!.addFirst(tmp)
}
}
crates.toSortedMap().forEach { print(it.value.peekFirst()) }
print('\n')
}
fun part2(input: List<String>) {
val (a, b) = input.partition { !Regex("""move \d+ from \d+ to \d+""").matches(it) }
val crates = mutableMapOf<Int, LinkedList<Char>>()
a.forEach { line ->
line.forEachIndexed { i, c ->
if (c.isLetter()) {
val n = (i / 4) + 1
crates.getOrPut(n) { LinkedList<Char>() }.addLast(c)
}
}
}
b.forEach {
val (n, src, dst) = Regex("""move (\d+) from (\d+) to (\d+)""").find(it)!!.destructured
val crane = LinkedList<Char>()
(0 until n.toInt()).forEach { _ ->
val tmp = crates[src.toInt()]!!.removeFirst()
crane.addFirst(tmp)
}
crane.forEach { c -> crates[dst.toInt()]!!.addFirst(c) }
}
crates.toSortedMap().forEach { print(it.value.peekFirst()) }
print('\n')
}
val input = File("src/d05/input").readLines()
part1(input)
part2(input)
}
| [
{
"class_path": "cweckerl__aoc__612badf/d05/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class d05.MainKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 // Str... |
aklemba__adventOfCode2023__2432d30/src/main/kotlin/pl/klemba/aoc/day4/Main.kt | package pl.klemba.aoc.day4
import java.io.File
import kotlin.math.pow
fun main() {
// ----- PART 1 -----
File(inputPath)
.readLines()
.sumOf { card -> getNumberOfPointsForCard(card) }
.let { println(it) }
// ----- PART 2 -----
val cardList = File(inputPath)
.readLines()
val amountOfScratchCards = IntArray(cardList.size) { 1 }
cardList
.foldIndexed(amountOfScratchCards) { index, acc, card -> calculateNumberOfCards(card, acc, index) }
.sum()
.let { println(it) }
}
fun getNumberOfPointsForCard(card: String): Int {
val amountOfMatchingNumbers = getNumberOfMatchingNumbers(card)
return if (amountOfMatchingNumbers == 1) 1 else 2.0.pow(amountOfMatchingNumbers - 1).toInt()
}
fun getNumberOfMatchingNumbers(card: String): Int {
val winningNumbers = getWinningNumbers(card)
val numbersYouHave = getNumbersYouHave(card)
return winningNumbers.intersect(numbersYouHave.toSet()).size
}
fun getWinningNumbers(card: String): List<Int> =
winningNumbersRegex.find(card)
?.value
?.removeRange(0, 2)
?.trim()
?.split(" ", " ")
?.map { it.toInt() }
?: throw IllegalStateException("No winning numbers found!")
fun getNumbersYouHave(card: String): List<Int> =
numbersYouHaveRegex.find(card)
?.value
?.removeRange(0, 2)
?.trim()
?.split(" ", " ")
?.map { it.toInt() }
?: throw IllegalStateException("No your numbers found!")
fun calculateNumberOfCards(card: String, acc: IntArray, index: Int): IntArray {
val numberOfPoints = getNumberOfMatchingNumbers(card)
val numberOfCards = acc[index]
repeat(numberOfPoints) { i ->
acc[index + i + 1] += numberOfCards
}
return acc
}
private val winningNumbersRegex = Regex(""": +\d+(?: +\d+)+""")
private val numbersYouHaveRegex = Regex("""\| +\d+(?: +\d+)+""")
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day4/input.txt" | [
{
"class_path": "aklemba__adventOfCode2023__2432d30/pl/klemba/aoc/day4/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class pl.klemba.aoc.day4.MainKt {\n private static final kotlin.text.Regex winningNumbersRegex;\n\n private static final kotlin.text.Regex numbersYouHaveRegex;\n\n priva... |
aklemba__adventOfCode2023__2432d30/src/main/kotlin/pl/klemba/aoc/day3/Main.kt | package pl.klemba.aoc.day3
import java.io.File
fun main() {
// ----- PART 1 -----
File(inputPath)
.readLines()
.let { schematic ->
schematic.mapIndexed { lineIndex, line ->
numberRegex.findAll(line)
.filter { schematic.checkIfAdjacentToASymbol(it.range, lineIndex) }
.map { it.value.toInt() }
.sum()
}.sum()
.let { println(it) }
}
// ----- PART 2 -----
val schematic = File(inputPath)
.readLines()
val numbersSchematic = schematic.mapIndexed { lineIndex, line ->
numberRegex.findAll(line)
.filter { schematic.checkIfAdjacentToASymbol(it.range, lineIndex) }
.toList()
}
schematic.mapIndexed { lineIndex, line ->
gearRegex.findAll(line)
.map {
numbersSchematic.sumGearRatio(it.range, lineIndex)
}
.sum()
}.sum()
.let { println(it) }
}
private fun List<List<MatchResult>>.sumGearRatio(range: IntRange, lineIndex: Int): Int {
val listOfAdjacentNumbers = mutableListOf<MatchResult>()
if (lineIndex != 0) {
listOfAdjacentNumbers.addAll(this[lineIndex - 1].getNumbersForIndex(range, this[0].lastIndex))
}
if (lineIndex != this.lastIndex) {
listOfAdjacentNumbers.addAll(this[lineIndex + 1].getNumbersForIndex(range, this[0].lastIndex))
}
listOfAdjacentNumbers.addAll(this[lineIndex].getNumbersForIndex(range, this[0].lastIndex))
return if (listOfAdjacentNumbers.size == 2) {
listOfAdjacentNumbers.map { it.value.toInt() }.reduce { acc, value -> acc * value }
}
else 0
}
private fun List<MatchResult>.getNumbersForIndex(range: IntRange, lastIndex: Int): List<MatchResult> {
val rangeToCheck = getRangeToCheck(range, lastIndex)
return this.filter { it.isAdjacentToGear(rangeToCheck) }
}
private fun MatchResult.isAdjacentToGear(rangeToCheck: IntRange) = range.intersect(rangeToCheck).isNotEmpty()
private fun List<String>.checkIfAdjacentToASymbol(numberIndices: IntRange, lineIndex: Int): Boolean {
// check top and bottom
if (lineIndex != 0) {
if (this[lineIndex - 1].checkIfSymbolsExistForRange(numberIndices, this[0].lastIndex)) return true
}
if (lineIndex != this.lastIndex) {
if (this[lineIndex + 1].checkIfSymbolsExistForRange(numberIndices, this[0].lastIndex)) return true
}
// check sides
if (numberIndices.first != 0) {
if (this[lineIndex][numberIndices.first - 1].isASymbol()) return true
}
if (numberIndices.last != this[lineIndex].lastIndex) {
if (this[lineIndex][numberIndices.last + 1].isASymbol()) return true
}
return false
}
private fun String.checkIfSymbolsExistForRange(indexRange: IntRange, lineLastIndex: Int): Boolean {
val rangeToCheck: IntRange = getRangeToCheck(indexRange, lineLastIndex)
return substring(rangeToCheck).any { it.isASymbol() }
}
private fun getRangeToCheck(indexRange: IntRange, lineLastIndex: Int): IntRange {
val rangeToCheck: IntRange = when {
indexRange.first == 0 -> IntRange(0, indexRange.last + 1)
indexRange.last == lineLastIndex -> IntRange(indexRange.first - 1, indexRange.last)
else -> IntRange(indexRange.first - 1, indexRange.last + 1)
}
return rangeToCheck
}
private fun Char.isASymbol() = this.isDigit().not() && this != '.'
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day3/input.txt"
private val numberRegex = Regex("\\d+")
private val gearRegex = Regex("\\*") | [
{
"class_path": "aklemba__adventOfCode2023__2432d30/pl/klemba/aoc/day3/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class pl.klemba.aoc.day3.MainKt {\n private static final java.lang.String inputPath;\n\n private static final kotlin.text.Regex numberRegex;\n\n private static final kot... |
aklemba__adventOfCode2023__2432d30/src/main/kotlin/pl/klemba/aoc/day2/Main.kt | package pl.klemba.aoc.day2
import java.io.File
fun main() {
// ----- PART 1 -----
File(inputPath)
.readLines()
.foldIndexed(0) { index, acc, line -> if (line.meetsRequirements) acc + index + 1 else acc }
.let { println(it) }
// ----- PART 2 -----
File(inputPath)
.readLines()
.map { it.maxRgb }
.sumOf { it.red * it.green * it.blue }
.let { println(it) }
}
private val String.maxRgb: Rgb
get() = Rgb(
red = highestCubeNumber(this, redRegex),
green = highestCubeNumber(this, greenRegex),
blue = highestCubeNumber(this, blueRegex)
)
data class Rgb(var red: Int, var green: Int, var blue: Int)
private val String.meetsRequirements: Boolean
get() {
if (highestCubeNumber(this, redRegex) > MAX_RED) return false
if (highestCubeNumber(this, greenRegex) > MAX_GREEN) return false
if (highestCubeNumber(this, blueRegex) > MAX_BLUE) return false
return true
}
private fun highestCubeNumber(rawLine: String, regex: Regex): Int =
regex
.findAll(rawLine)
.map { it.destructured.component1().toInt() }
.sortedDescending()
.firstOrNull()
?: 0
private val redRegex = Regex(" (\\d*) red")
private val greenRegex = Regex(" (\\d*) green")
private val blueRegex = Regex(" (\\d*) blue")
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day2/input.txt"
private const val MAX_RED = 12
private const val MAX_GREEN = 13
private const val MAX_BLUE = 14
| [
{
"class_path": "aklemba__adventOfCode2023__2432d30/pl/klemba/aoc/day2/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class pl.klemba.aoc.day2.MainKt {\n private static final kotlin.text.Regex redRegex;\n\n private static final kotlin.text.Regex greenRegex;\n\n private static final kotl... |
aklemba__adventOfCode2023__2432d30/src/main/kotlin/pl/klemba/aoc/day5/Main.kt | package pl.klemba.aoc.day5
import java.io.File
fun main() {
// ----- PART 1 -----
val almanac = File(inputPath)
.readLines()
val seeds: List<Long> = getSeeds(almanac)
println("Seeds: $seeds")
val mappings = getMappings(almanac)
mappings
.forEach { println(it) }
seeds
.map { seed -> seed.mapToLocation(mappings) }
.let {
println("Resultlist: $it")
println(it.min())
}
// ----- PART 2 -----
val almanac2 = File(inputPath)
.readLines()
val seedRanges: List<LongRange> = getSeedRangesPart2(almanac2)
val mappings2 = getMappings(almanac2)
seedRanges
.fold(Long.MAX_VALUE) { acc, longRange -> findMinLocationOf(longRange, mappings2).let { location -> if (location < acc) location else acc } }
.let { println(it) }
}
fun getMappings(almanac: List<String>): ArrayList<ArrayList<MappingPattern>> {
val mappings = ArrayList<ArrayList<MappingPattern>>()
return almanac
.fold(mappings) { acc, line -> addToMappingsList(line, acc) }
}
private fun String.hasThreeNumbers() = getMappingLine() != null
private fun String.getMappingLine() = mappingLineRegex.matchEntire(this)
fun addToMappingsList(line: String, acc: ArrayList<ArrayList<MappingPattern>>): java.util.ArrayList<java.util.ArrayList<MappingPattern>> {
when {
line.endsWith("map:") -> {
acc.add(ArrayList())
}
line.hasThreeNumbers() -> {
acc.last().add(getMappingPattern(line))
}
}
return acc
}
fun getMappingPattern(line: String) =
line.getMappingLine()
?.destructured
?.let { (destinationValue, sourceValue, rangeValue ) -> mapToMappingPattern(destinationValue.toLong(), sourceValue.toLong(), rangeValue.toLong()) }
?: throw IllegalStateException("Mapping pattern not found! Wierd since it has been checked before!")
fun mapToMappingPattern(destinationValue: Long, sourceValue: Long, rangeValue: Long) =
MappingPattern(LongRange(sourceValue, sourceValue + rangeValue), destinationValue - sourceValue)
fun getSeeds(almanac: List<String>): List<Long> =
numberRegex.findAll(almanac[0])
.map { it.destructured.component1().toLong() }
.toList()
fun getSeedRangesPart2(almanac: List<String>): List<LongRange> =
getSeeds(almanac)
.chunked(2)
.map { LongRange(it[0], it[0] + it[1]) }
private fun Long.mapToLocation(mappings: java.util.ArrayList<java.util.ArrayList<MappingPattern>>) =
mappings
.fold(this) { acc, mappingPatterns ->
mappingPatterns.find { it.sourceRange.contains(acc) }
?.let { pattern -> pattern.valueShift + acc }
?: acc
}
fun findMinLocationOf(longRange: LongRange, almanac2: ArrayList<ArrayList<MappingPattern>>) =
longRange
.fold(Long.MAX_VALUE) { acc, seed -> seed.mapToLocation(almanac2).let { location -> if (location < acc) location else acc } }
/**
* @param sourceRange range of IDs which can be mapped by this pattern
* @param valueShift parameter indicating needed value shift (addition of the value to source ID) to achieve the mapping result
*/
data class MappingPattern(val sourceRange: LongRange, val valueShift: Long)
private val numberRegex = Regex(""" (\d+)""")
private val mappingLineRegex = Regex("""(\d+) (\d+) (\d+)""")
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day5/input.txt" | [
{
"class_path": "aklemba__adventOfCode2023__2432d30/pl/klemba/aoc/day5/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class pl.klemba.aoc.day5.MainKt {\n private static final kotlin.text.Regex numberRegex;\n\n private static final kotlin.text.Regex mappingLineRegex;\n\n private static f... |
aklemba__adventOfCode2023__2432d30/src/main/kotlin/pl/klemba/aoc/day1/Main.kt | package pl.klemba.aoc.day1
import java.io.File
fun main2() {
// ----- PART 1 -----
File(inputPath)
.readLines()
.map { extractCalibrationValue(it) }
.reduce { accumulator, calibrationValue -> accumulator + calibrationValue }
.let { println(it) }
// ----- PART 2 -----
File(inputPath)
.readLines()
.map { rawLine -> formatToDigits(rawLine) }
.map { extractCalibrationValue(it) }
.reduce { accumulator, calibrationValue -> accumulator + calibrationValue }
.let { println(it) }
}
fun formatToDigits(rawLine: String): String {
var calibrationValue = ""
var rawLineLeftToCheck = rawLine
while (rawLineLeftToCheck.isNotEmpty()) {
rawLineLeftToCheck.getDigitAtStart()?.let { calibrationValue += it }
rawLineLeftToCheck = rawLineLeftToCheck.substring(1)
}
return calibrationValue
}
private fun String.getDigitAtStart(): Int? {
println("length: " + this.length)
if (first().isDigit()) return first().digitToInt()
digitNames
.forEach { mapEntry -> if (startsWith(mapEntry.key)) return mapEntry.value }
return null
}
fun extractCalibrationValue(line: String): Int {
val firstDigit = line.first { it.isDigit() }
val lastDigit = line.last { it.isDigit() }
return "$firstDigit$lastDigit".toInt()
}
fun transformDigitNames(line: String) =
digitNames.keys
.fold(line) { accumulator, digitName -> accumulator.transformDigitName(digitName) }
private fun String.transformDigitName(digitName: String): String =
this.replace(digitName, digitNames[digitName].toString())
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day1/input.txt"
private val digitNames: Map<String, Int> = listOf(
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
).mapIndexed { index, digitName -> digitName to index + 1 }
.toMap() | [
{
"class_path": "aklemba__adventOfCode2023__2432d30/pl/klemba/aoc/day1/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class pl.klemba.aoc.day1.MainKt {\n private static final java.lang.String inputPath;\n\n private static final java.util.Map<java.lang.String, java.lang.Integer> digitName... |
aklemba__adventOfCode2023__2432d30/src/main/kotlin/pl/klemba/aoc/day10/Main.kt | package pl.klemba.aoc.day10
import java.io.File
fun main() {
// ----- PART 1 -----
val pipeField = File(inputPath)
.readLines()
// Find starting point
val startingIndex: Coordinates = pipeField.findStartingIndex()
println("Starting index: ${startingIndex}")
// Find one of the pipes that create the loop with starting point
// Check top first as it is clearly visible that is starts from top
val topCoordinates = startingIndex.copy(y = startingIndex.y - 1)
println("Top coordinates: ${topCoordinates}")
val char: Char = pipeField[topCoordinates.y][topCoordinates.x]
val actor = char.mapToActor()
// Go through the pipes
var nextStep = NextStep(Direction.N, actor as Actor.Pipe, topCoordinates)
var pipeCount = 1
while(nextStep.pipe !is Actor.StartingPoint) {
pipeCount++
nextStep = pipeField.followThePipeAndCount(nextStep.originDirection, nextStep.pipe as Actor.Pipe, nextStep.pipeCoordinates)
}
println(pipeCount/2)
}
private fun List<String>.followThePipeAndCount(
originDirection: Direction,
pipe: Actor.Pipe,
pipeCoordinates: Coordinates,
): NextStep {
val nextDirection = when (originDirection.oppositeDirection) {
pipe.direction1 -> pipe.direction2
pipe.direction2 -> pipe.direction1
else -> throw IllegalStateException("One direction has to be the same as origin")
}
val nextCoordinates = calculateNextCoordinates(nextDirection, pipeCoordinates)
println("Symbol: ${this[nextCoordinates.y][nextCoordinates.x]}")
val actor = this[nextCoordinates.y][nextCoordinates.x].mapToActor()
println("Next direction: ${nextDirection}, next coordinates: ${nextCoordinates}")
return NextStep(nextDirection, actor, nextCoordinates)
}
class NextStep(val originDirection: Direction,
val pipe: Actor,
val pipeCoordinates: Coordinates)
private fun calculateNextCoordinates(nextDirection: Direction, pipeCoordinates: Coordinates): Coordinates {
val coordinatesChange = when (nextDirection) {
Direction.N -> Coordinates(0, -1)
Direction.W -> Coordinates(-1, 0)
Direction.S -> Coordinates(0, 1)
Direction.E -> Coordinates(1, 0)
}
return pipeCoordinates.copyWithCoordinatesChange(coordinatesChange)
}
private fun Char.mapToActor(): Actor {
if (this == 'S') return Actor.StartingPoint
return Actor.Pipe
.getByChar(this)
?: throw IllegalStateException("It has to be a pipe!")
}
private fun List<String>.findStartingIndex(): Coordinates {
map { startingPointRegex.find(it) }
.forEachIndexed { lineIndex, matchResult ->
if (matchResult != null) return Coordinates(
matchResult.range.first,
lineIndex
)
}
throw IllegalStateException("Missing starting point!")
}
data class Coordinates(val x: Int, val y: Int) {
fun copyWithCoordinatesChange(coordinatesChange: Coordinates) =
copy(x = this.x + coordinatesChange.x, y = this.y + coordinatesChange.y)
}
private val startingPointRegex = Regex("S")
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day10/input.txt"
enum class Direction {
N,
W,
S,
E;
val oppositeDirection: Direction
get() = when (this) {
N -> S
W -> E
E -> W
S -> N
}
}
sealed class Actor {
object StartingPoint : Actor()
sealed class Pipe(val direction1: Direction, val direction2: Direction, val charEquivalent: Char) : Actor() {
object N_S : Pipe(Direction.N, Direction.S, '|')
object N_E : Pipe(Direction.N, Direction.E, 'L')
object W_E : Pipe(Direction.W, Direction.E, '-')
object W_N : Pipe(Direction.W, Direction.N, 'J')
object S_W : Pipe(Direction.S, Direction.W, '7')
object E_S : Pipe(Direction.E, Direction.S, 'F')
companion object {
fun getByChar(char: Char): Pipe? = when (char) {
N_S.charEquivalent -> N_S
N_E.charEquivalent -> N_E
W_E.charEquivalent -> W_E
W_N.charEquivalent -> W_N
S_W.charEquivalent -> S_W
E_S.charEquivalent -> E_S
else -> null
}
}
}
} | [
{
"class_path": "aklemba__adventOfCode2023__2432d30/pl/klemba/aoc/day10/MainKt$WhenMappings.class",
"javap": "Compiled from \"Main.kt\"\npublic final class pl.klemba.aoc.day10.MainKt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 ... |
greyovo__PicQuery__4c95be2/app/src/main/java/me/grey/picquery/common/Algorithm.kt | package me.grey.picquery.common
import kotlin.math.acos
import kotlin.math.asin
import kotlin.math.pow
import kotlin.math.sqrt
fun calculateSimilarity(vectorA: FloatArray, vectorB: FloatArray): Double {
var dotProduct = 0.0
var normA = 0.0
var normB = 0.0
for (i in vectorA.indices) {
dotProduct += vectorA[i] * vectorB[i]
normA += vectorA[i] * vectorA[i]
normB += vectorB[i] * vectorB[i]
}
normA = sqrt(normA)
normB = sqrt(normB)
return dotProduct / (normA * normB)
}
fun calculateSphericalDistanceLoss(vector1: FloatArray, vector2: FloatArray): Double {
require(vector1.size == vector2.size) { "Vector dimensions do not match" }
var dotProduct = 0.0
var norm1 = 0.0
var norm2 = 0.0
for (i in vector1.indices) {
dotProduct += vector1[i] * vector2[i]
norm1 += vector1[i] * vector1[i]
norm2 += vector2[i] * vector2[i]
}
norm1 = sqrt(norm1)
norm2 = sqrt(norm2)
val cosineSimilarity = dotProduct / (norm1 * norm2)
val distanceLoss = acos(cosineSimilarity)
return distanceLoss
}
fun sphericalDistLoss(x: FloatArray, y: FloatArray): Double {
val xNormalized: DoubleArray = normalizeVector(x)
val yNormalized: DoubleArray = normalizeVector(y)
val difference = computeDifference(xNormalized, yNormalized)
val magnitude = computeMagnitude(difference)
return computeResult(magnitude)
}
fun normalizeVector(vector: FloatArray): DoubleArray {
val norm = computeNorm(vector)
return vector.map { it / norm }.toDoubleArray()
}
fun computeNorm(vector: FloatArray): Double {
var sumOfSquares = 0.0
for (element in vector) {
sumOfSquares += element.pow(2)
}
return sqrt(sumOfSquares)
}
fun computeDifference(x: DoubleArray, y: DoubleArray): DoubleArray {
return x.zip(y).map { (xValue, yValue) -> xValue - yValue }.toDoubleArray()
}
fun computeMagnitude(diff: DoubleArray): Double {
var sumOfSquares = 0.0
for (element in diff) {
sumOfSquares += element.pow(2)
}
return sqrt(sumOfSquares)
}
fun computeResult(magnitude: Double): Double {
return asin(magnitude / 2.0).pow(2) * 2.0
} | [
{
"class_path": "greyovo__PicQuery__4c95be2/me/grey/picquery/common/AlgorithmKt.class",
"javap": "Compiled from \"Algorithm.kt\"\npublic final class me.grey.picquery.common.AlgorithmKt {\n public static final double calculateSimilarity(float[], float[]);\n Code:\n 0: aload_0\n 1: ldc ... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2017/Day24ElectromagneticMoat.kt | package adventofcode2017
class Day24ElectromagneticMoat
data class Port(val sideA: Int, val sideB: Int) {
val strength: Int
get() = sideA + sideB
}
class Bridge(val ports: List<Port> = listOf()) {
fun totalStrength(): Int = ports.sumOf { it.strength }
val totalLength: Int = ports.size
override fun toString(): String {
return buildString {
append("[Strength: ${totalStrength()}]: ")
ports.forEach {
append("[")
append(it.sideA)
append("/")
append(it.sideB)
append("]")
append(" - ")
}
}
}
}
class BridgeBuilder(input: List<String>) {
val constructedBridges = mutableSetOf<Bridge>()
val ports: List<Port>
val strongestBridge: Int
get() {
return if (constructedBridges.isNotEmpty()) {
constructedBridges.maxOf { it.totalStrength() }
}
else 0
}
fun longestStrongestBridge(): Int {
val maxLength = constructedBridges.maxOf { bridge -> bridge.totalLength }
return constructedBridges.filter { bridge -> bridge.totalLength == maxLength }.maxOf { it.totalStrength() }
}
init {
ports = input.map { portConfiguration ->
val parts = portConfiguration.split("/")
Port(parts[0].toInt(), parts[1].toInt())
}
}
fun buildBridge(
usedPorts: List<Port> = mutableListOf(),
currentEnding: Int = 0,
remainingPorts: List<Port> = ports
) {
val eligiblePorts = findMatchingPorts(currentEnding, remainingPorts)
if (eligiblePorts.isNotEmpty()) {
eligiblePorts.forEach { eligible ->
val otherPorts = remainingPorts.filter { it != eligible }
val otherEnd = if (eligible.sideA == currentEnding) eligible.sideB else eligible.sideA
constructedBridges.add(Bridge(usedPorts + eligible))
buildBridge(usedPorts + eligible, otherEnd, otherPorts)
}
} else {
constructedBridges.add(Bridge(usedPorts))
}
}
private fun findMatchingPorts(pins: Int, ports: List<Port>): List<Port> {
return ports.filter { port -> port.sideA == pins || port.sideB == pins }
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2017/Day24ElectromagneticMoat.class",
"javap": "Compiled from \"Day24ElectromagneticMoat.kt\"\npublic final class adventofcode2017.Day24ElectromagneticMoat {\n public adventofcode2017.Day24ElectromagneticMoat();\n Code:\n 0: al... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2017/Day03SpiralMemory.kt | package adventofcode2017
import adventofcode2017.Direction.*
import kotlin.math.absoluteValue
class Day03SpiralMemory
data class Coordinate(val x: Int, val y: Int)
enum class Direction {
RIGHT,
LEFT,
UP,
DOWN
}
class SpiralMemory(private val input: Int = 1) {
private val memory = mutableMapOf<Int, Coordinate>()
private val stressTestMemory = mutableMapOf<Coordinate, Int>()
private var maxX = 1
private var minX = -1
private var maxY = 1
private var minY = -1
private var currentDirection = RIGHT
init {
buildMemory()
}
private fun buildMemory() {
var currentValue = 1
var currentPosition = Coordinate(0, 0)
while (currentValue <= input) {
memory[currentValue++] = currentPosition
currentPosition = getNextPosition(currentPosition)
}
}
private fun buildStressTestMemory(targetValue: Int) {
var currentValue = 1
var currentPosition = Coordinate(0, 0)
stressTestMemory[currentPosition] = currentValue
currentPosition = getNextPosition(currentPosition)
do {
currentValue = sumOfNeighborsAtPos(currentPosition.x, currentPosition.y)
stressTestMemory[currentPosition] = currentValue
currentPosition = getNextPosition(currentPosition)
} while (currentValue < targetValue)
}
fun stressTest(targetValue: Int): Int {
buildStressTestMemory(targetValue)
return stressTestMemory.values.last()
}
private fun sumOfNeighborsAtPos(x: Int, y: Int): Int {
val offsets = listOf(
-1 to 0,
-1 to 1,
-1 to -1,
0 to 1,
0 to -1,
1 to 0,
1 to 1,
1 to -1
)
val neighbors = offsets.mapNotNull { offset ->
stressTestMemory.keys.find { it.x == x + offset.first && it.y == y + offset.second }
}
return stressTestMemory.filter { it.key in neighbors }.values.sum()
}
fun manhattanDistanceForCell(value: Int): Int {
memory[value]?.let { coordinate ->
return (coordinate.x.absoluteValue + coordinate.y.absoluteValue)
} ?: return 0
}
private fun getNextPosition(currentPosition: Coordinate): Coordinate {
when (currentDirection) {
RIGHT -> {
return if (currentPosition.x == maxX) {
currentDirection = UP
maxX++
Coordinate(currentPosition.x, currentPosition.y - 1)
} else {
Coordinate(currentPosition.x + 1, currentPosition.y)
}
}
UP -> {
return if (currentPosition.y == minY) {
currentDirection = LEFT
minY--
Coordinate(currentPosition.x - 1, currentPosition.y)
} else {
Coordinate(currentPosition.x, currentPosition.y - 1)
}
}
LEFT -> {
return if (currentPosition.x == minX) {
currentDirection = DOWN
minX--
Coordinate(currentPosition.x, currentPosition.y + 1)
} else {
Coordinate(currentPosition.x - 1, currentPosition.y)
}
}
DOWN -> {
return if (currentPosition.y == maxY) {
currentDirection = RIGHT
maxY++
Coordinate(currentPosition.x + 1, currentPosition.y)
} else {
Coordinate(currentPosition.x, currentPosition.y + 1)
}
}
}
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2017/Day03SpiralMemory.class",
"javap": "Compiled from \"Day03SpiralMemory.kt\"\npublic final class adventofcode2017.Day03SpiralMemory {\n public adventofcode2017.Day03SpiralMemory();\n Code:\n 0: aload_0\n 1: invokespeci... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2017/Day25TheHaltingProblem.kt | package adventofcode2017
class Day25TheHaltingProblem
data class StateResult(val writeValue: Int, val nextDirection: Int, val nextState: TuringState)
data class StateRule(val ruleOnNull: StateResult, val ruleOnOne: StateResult)
sealed class TuringState {
object A : TuringState()
object B : TuringState()
object C : TuringState()
object D : TuringState()
object E : TuringState()
object F : TuringState()
companion object {
fun fromChar(state: Char): TuringState = when (state) {
'A' -> A
'B' -> B
'C' -> C
'D' -> D
'E' -> E
else -> F
}
}
}
class TuringMachine(stateRules: List<String>) {
val states = mutableMapOf<TuringState, StateRule>()
var currentState: TuringState = TuringState.A
var currentPosition = 0
val tape = mutableMapOf(0 to 0)
val checksum: Int
get() = tape.values.sum()
init {
stateRules.windowed(9, 10) { lines ->
states[TuringState.fromChar(lines[0][9])] = parseRule(lines.subList(1, 9))
}
}
private fun parseRule(input: List<String>): StateRule {
/* Sample
In state A:
If the current value is 0:
- Write the value 1.
- Move one slot to the right.
- Continue with state B.
If the current value is 1:
- Write the value 0.
- Move one slot to the left.
- Continue with state D.
*/
val writeValueOnNull = input[1][22].code - 48
val nextDirectionOnNull = when (input[2][27]) {
'r' -> 1
else -> -1
}
val nextStateOnNull = TuringState.fromChar(input[3][26])
val writeValueOnOne = input[5][22].code - 48
val nextDirectionOnOne = when (input[6][27]) {
'r' -> 1
else -> -1
}
val nextStateOnOne = TuringState.fromChar(input[7][26])
val resultOnNull = StateResult(writeValueOnNull, nextDirectionOnNull, nextStateOnNull)
val resultOnOne = StateResult(writeValueOnOne, nextDirectionOnOne, nextStateOnOne)
return StateRule(resultOnNull, resultOnOne)
}
fun run(numberOfSteps: Int) {
repeat(numberOfSteps) { step() }
}
fun step() {
val tapeValue = tape[currentPosition] ?: 0
val currentStateRule = states.get(currentState)
require(currentStateRule != null)
val nextStateRule = if (tapeValue == 0) currentStateRule.ruleOnNull else currentStateRule.ruleOnOne
with(nextStateRule) {
tape[currentPosition] = writeValue
currentPosition += nextDirection
currentState = nextState
}
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2017/Day25TheHaltingProblem.class",
"javap": "Compiled from \"Day25TheHaltingProblem.kt\"\npublic final class adventofcode2017.Day25TheHaltingProblem {\n public adventofcode2017.Day25TheHaltingProblem();\n Code:\n 0: aload_0\n ... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2017/Day07RecursiveCircus.kt | package adventofcode2017
class Day07RecursiveCircus
data class RCProgram(val name: String, val weight: Int, val dependants: List<String>)
data class WeightedChild(
val name: String,
val parent: String,
val weight: Int,
val dependants: List<String>,
val dependantsWeight: Int
)
class RCTower(val programms: List<RCProgram>) {
val childWeights = mutableListOf<WeightedChild>()
var childsInequality = 0
companion object {
fun fromLines(input: List<String>): RCTower {
return RCTower(input.map { parseInputLine(it) })
}
private fun parseInputLine(line: String): RCProgram {
// sample: fbmhsy (58) -> lqggzbu, xwete, vdarulb, rkobinu, ztoyd, vozjzra
val name = line.substringBefore(" ")
val weight = line.substringAfter("(").substringBefore(")").toInt()
val dependants = when {
line.contains("->") -> line.substringAfter("-> ").split(", ")
else -> emptyList()
}
return RCProgram(name, weight, dependants)
}
}
fun getDependantsCount(programname: String): Int {
val program = programms.find { it.name == programname }
program?.let {
if (program.dependants.isEmpty()) {
return 1
} else {
return program.dependants.sumOf { getDependantsCount(it) }
}
}
return 0
}
fun getDependantsWeightSum(programname: String) = getDependantsWeights(programname).sum()
fun getDependantsWeights(programname: String): List<Int> {
val program = programms.find { it.name == programname }
program?.dependants?.let {
if (program.dependants.isEmpty()) {
return listOf(program.weight)
} else {
val childrenWeights = program.dependants.flatMap { getDependantsWeights(it) }
return listOf(program.weight) + childrenWeights
}
}
return listOf()
}
fun checkChildsForEqualWeight(programname: String): Int {
buildWeightedChildList()
val program = programms.find { it.name == programname }
program?.dependants?.let {
if (program.dependants.isNotEmpty()) {
program.dependants.forEach { checkChildsForEquality(it) }
}
return childsInequality
}
return childsInequality
}
fun checkChildsForEquality(programname: String): Int {
val program = programms.find { it.name == programname }
program?.dependants?.let {
if (program.dependants.isNotEmpty()) {
val children =
program.dependants.map { childWeights.find { child -> child.name == it } }
.sortedBy { it?.dependantsWeight }
val distinct = children.last()
val others = children.first()
distinct?.let {
others?.let {
val difference = Math.abs(distinct.dependantsWeight - others.dependantsWeight)
if (difference != 0) {
childsInequality = distinct.weight - difference
}
}
}
}
program.dependants.forEach { checkChildsForEquality(it) }
}
return childsInequality
}
fun findRoot(): String = programms.maxByOrNull { program -> getDependantsCount(program.name) }?.name ?: ""
private fun buildWeightedChildList() {
val root = findRoot()
addToWeightedChildList(root)
}
private fun addToWeightedChildList(programname: String) {
val program = programms.find { it.name == programname }
program?.dependants?.let {
if (program.dependants.isEmpty()) return
for (childname in program.dependants) {
val child = programms.find { it.name == childname }
childWeights.add(
WeightedChild(
child!!.name,
programname,
child.weight,
child.dependants,
getDependantsWeightSum(child.name)
)
)
addToWeightedChildList(childname)
}
}
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2017/Day07RecursiveCircus.class",
"javap": "Compiled from \"Day07RecursiveCircus.kt\"\npublic final class adventofcode2017.Day07RecursiveCircus {\n public adventofcode2017.Day07RecursiveCircus();\n Code:\n 0: aload_0\n 1:... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2017/Day08LikeRegisters.kt | package adventofcode2017
import adventofcode2017.Comparator.*
import adventofcode2017.RegisterOperation.*
class Day08LikeRegisters
enum class RegisterOperation {
INC, DEC
}
enum class Comparator {
LT, LET, EQ, NE, GET, GT
}
data class Register(val name: String, var value: Int = 0) {
fun inc(incValue: Int) {
value += incValue
}
fun dec(decValue: Int) {
value -= decValue
}
}
data class Instruction(val register: String, val operation: RegisterOperation, val value: Int, val condition: String) {
val comparator: Comparator
val compareValue: Int
val registerToCheck: String
init {
val parts = condition.split(" ")
registerToCheck = parts[0]
compareValue = parts[2].toInt()
val comp = parts[1]
comparator = when {
comp == "<" -> LT
comp == "<=" -> LET
comp == "==" -> EQ
comp == "!=" -> NE
comp == ">=" -> GET
else -> GT
}
}
companion object {
fun fromLineInput(input: String): Instruction {
// Example: vk inc 880 if pnt == 428
val parts = input.split(" ")
val operation = if (parts[1] == "inc") INC else DEC
return Instruction(parts[0], operation, parts[2].toInt(), input.substringAfter("if "))
}
}
fun evaluate(registerValue: Int) = when (comparator) {
LT -> registerValue < compareValue
LET -> registerValue <= compareValue
EQ -> registerValue == compareValue
NE -> registerValue != compareValue
GET -> registerValue >= compareValue
GT -> registerValue > compareValue
}
}
class RegisterMachine {
private val instructions = mutableListOf<Instruction>()
private val registers = mutableListOf<Register>()
var registerMax = 0
val highestRegister: Int
get() = registers.maxByOrNull { it.value }?.value ?: 0
fun readInstructions(input: List<String>) {
input.forEach { instructions.add(Instruction.fromLineInput(it)) }
instructions.forEach { registers.add(Register(it.register)) }
}
fun runInstructions() {
instructions.forEach { instruction ->
val registerName = instruction.register
val registerToCheckName = instruction.registerToCheck
val (register, registerToCheck) = findRegisters(registerName, registerToCheckName)
if (checkCondition(registerToCheck, instruction)) {
register?.run {
when (instruction.operation) {
INC -> inc(instruction.value)
DEC -> dec(instruction.value)
}
if (value > registerMax) registerMax = value
}
}
}
}
private fun checkCondition(registerToCheck: Register?, instruction: Instruction): Boolean {
return registerToCheck?.let {
instruction.evaluate(registerToCheck.value)
} ?: false
}
private fun findRegisters(registerName: String, registerToCheckName: String): Pair<Register?, Register?> {
val register = registers.find { it.name == registerName }
val registerToCheck = registers.find { it.name == registerToCheckName }
return register to registerToCheck
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2017/Day08LikeRegisters.class",
"javap": "Compiled from \"Day08LikeRegisters.kt\"\npublic final class adventofcode2017.Day08LikeRegisters {\n public adventofcode2017.Day08LikeRegisters();\n Code:\n 0: aload_0\n 1: invokes... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2017/Day21FractalArt.kt | package adventofcode2017
class Day21FractalArt
data class FractalRule(val original: String, val transformed: String)
class FractalArt(ruleLines: List<String>) {
val rules: List<FractalRule>
val fractals: MutableList<Fractal> = mutableListOf()
val activePixels: Int
get() = fractals.sumOf { it.activePixels }
val startingFractal = Fractal(
mutableListOf(
mutableListOf('.', '#', '.'),
mutableListOf('.', '.', '#'),
mutableListOf('#', '#', '#')
)
)
init {
rules = ruleLines.map { FractalRule(it.substringBefore(" ="), it.substringAfter("> ")) }
fractals.add(startingFractal)
}
fun enhance() {
val result = mutableListOf<Fractal>()
fractals.forEach { fractal ->
result.addAll(transformFractal(fractal))
}
fractals.clear()
fractals.addAll(result)
}
fun transformFractal(origin: Fractal): List<Fractal> {
val result = mutableListOf<Fractal>()
if (origin.size < 4) {
result.add(Fractal.fromLine(transform(origin)))
} else {
result.add(Fractal.fromLine(transform(origin.topLeft)))
result.add(Fractal.fromLine(transform(origin.topRight)))
result.add(Fractal.fromLine(transform(origin.bottomLeft)))
result.add(Fractal.fromLine(transform(origin.bottomRight)))
}
return result
}
fun printFractals() {
fractals.forEach { print(it) }
}
private fun transform(origin: String): String {
return transform(Fractal.fromLine(origin))
}
private fun transform(origin: Fractal): String {
val patterns = mutableListOf<String>()
repeat(if (origin.size == 2) 4 else 8) {
origin.rotateRight()
patterns.add(origin.toString())
}
origin.flipVertical()
patterns.add(origin.toString())
origin.flipVertical()
origin.flipHorizontal()
patterns.add(origin.toString())
origin.flipHorizontal()
val result = rules.firstOrNull { it.original in patterns }?.transformed ?: ""
if (result == "") {
println("No Match")
}
return result
}
}
data class Fractal(var lines: List<MutableList<Char>>) {
val size: Int = lines[0].size
val activePixels: Int
get() = lines.sumOf { line -> line.count { it == '#' } }
val topLeft: String
get() {
return buildString {
append(lines[0][0])
append(lines[0][1])
append("/")
append(lines[1][0])
append(lines[1][1])
}
}
val topRight: String
get() {
return buildString {
append(lines[0][2])
append(lines[0][3])
append("/")
append(lines[1][2])
append(lines[1][3])
}
}
val bottomLeft: String
get() {
return buildString {
append(lines[2][0])
append(lines[2][1])
append("/")
append(lines[3][0])
append(lines[3][1])
}
}
val bottomRight: String
get() {
return buildString {
append(lines[2][2])
append(lines[2][3])
append("/")
append(lines[3][2])
append(lines[3][3])
}
}
fun rotateRight() {
if (size == 2) {
val tmp = lines[0][0]
lines[0][0] = lines[1][0]
lines[1][0] = lines[1][1]
lines[1][1] = lines[0][1]
lines[0][1] = tmp
} else {
val tmp = lines[0][0]
lines[0][0] = lines[1][0]
lines[1][0] = lines[2][0]
lines[2][0] = lines[2][1]
lines[2][1] = lines[2][2]
lines[2][2] = lines[1][2]
lines[1][2] = lines[0][2]
lines[0][2] = lines[0][1]
lines[0][1] = tmp
}
}
fun rotateLeft() {
if (size == 2) {
val tmp = lines[0][0]
lines[0][0] = lines[0][1]
lines[0][1] = lines[1][1]
lines[1][1] = lines[1][0]
lines[1][0] = tmp
} else {
val tmp = lines[0][0]
lines[0][0] = lines[0][1]
lines[0][1] = lines[0][2]
lines[0][2] = lines[1][2]
lines[1][2] = lines[2][2]
lines[2][2] = lines[2][1]
lines[2][1] = lines[2][0]
lines[2][0] = lines[1][0]
lines[1][0] = tmp
}
}
fun flipHorizontal() {
if (size == 2) {
var tmp = lines[0][0]
lines[0][0] = lines[1][0]
lines[1][0] = tmp
tmp = lines[0][1]
lines[0][1] = lines[1][1]
lines[1][1] = tmp
} else {
var tmp = lines[0][0]
lines[0][0] = lines[2][0]
lines[2][0] = tmp
tmp = lines[0][1]
lines[0][1] = lines[2][1]
lines[2][1] = tmp
tmp = lines[0][2]
lines[0][2] = lines[2][2]
lines[2][2] = tmp
}
}
fun flipVertical() {
if (size == 2) {
var tmp = lines[0][0]
lines[0][0] = lines[0][1]
lines[0][1] = tmp
tmp = lines[1][0]
lines[1][0] = lines[1][1]
lines[1][1] = tmp
} else {
var tmp = lines[0][0]
lines[0][0] = lines[0][2]
lines[0][2] = tmp
tmp = lines[1][0]
lines[1][0] = lines[1][2]
lines[1][2] = tmp
tmp = lines[2][0]
lines[2][0] = lines[2][2]
lines[2][2] = tmp
}
}
fun displayAsGrid() {
lines.forEach { println(it.joinToString("")) }
}
override fun toString(): String {
return lines.map { it.joinToString("") }.joinToString("/")
}
companion object {
fun fromLine(input: String) = Fractal(input.split("/").map { it.toCharArray().toMutableList() })
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2017/Day21FractalArt.class",
"javap": "Compiled from \"Day21FractalArt.kt\"\npublic final class adventofcode2017.Day21FractalArt {\n public adventofcode2017.Day21FractalArt();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2019/Day06UniversalOrbitMap.kt | package adventofcode2019
class Day06UniversalOrbitMap
data class OrbitObject(val code: String)
data class Orbit(val center: OrbitObject, val satelite: OrbitObject)
class SpaceOrbit(val orbitMap: List<String>) {
val orbits: List<Orbit>
init {
orbits = orbitMap.map {
val (center, satelite) = it.split(")").take(2)
Orbit(OrbitObject(center), OrbitObject(satelite))
}
}
fun orbitsCount(): Int {
return orbits.sumOf { orbit -> findObjectDepth(orbit.satelite, 0) }
}
private fun findObjectDepth(orbitObject: OrbitObject, currentDepth: Int = 0): Int {
val center = orbits.firstOrNull { it.satelite == orbitObject }?.center
return if (center == null) {
currentDepth
} else {
findObjectDepth(center, currentDepth + 1)
}
}
fun findYouSanDistance(): Int {
val youMap = mutableMapOf<OrbitObject, Int>()
val sanMap = mutableMapOf<OrbitObject, Int>()
var parent = orbits.firstOrNull { it.satelite.code == "YOU" }?.center
var distance = 0
while (parent != null) {
youMap[parent] = distance++
parent = orbits.firstOrNull { it.satelite.code == parent?.code }?.center
}
parent = orbits.first { it.satelite.code == "SAN" }.center
distance = 0
while (parent != null) {
sanMap[parent] = distance++
parent = orbits.firstOrNull { it.satelite.code == parent?.code }?.center
}
val intersection = youMap.keys.first { sanMap.contains(it) }
val youDistance = youMap[intersection] ?: 0
val sanDistance = sanMap[intersection] ?: 0
return youDistance + sanDistance
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2019/Day06UniversalOrbitMap.class",
"javap": "Compiled from \"Day06UniversalOrbitMap.kt\"\npublic final class adventofcode2019.Day06UniversalOrbitMap {\n public adventofcode2019.Day06UniversalOrbitMap();\n Code:\n 0: aload_0\n ... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2019/Day03CrossedWires.kt | package adventofcode2019
import kotlin.math.abs
class Day03CrossedWires
data class DistanceCoordinate(
val distance: Int,
val coordinate: Pair<Int, Int>
)
data class GravityWire(val coordinates: List<Pair<Int, Int>> = emptyList()) {
val distanceCoordinates = mutableListOf<DistanceCoordinate>()
fun buildPathFromString(input: String) {
var currentX = 0
var currentY = 0
var distance = 0
val parts = input.split(",")
parts.forEach { part ->
val dist = part.substring(1).toInt()
when (part.first()) {
'R' -> {
repeat(dist) {
distanceCoordinates.add(DistanceCoordinate(++distance, ++currentX to currentY))
}
}
'D' -> {
repeat(dist) {
distanceCoordinates.add(DistanceCoordinate(++distance, currentX to ++currentY))
}
}
'L' -> {
repeat(dist) {
distanceCoordinates.add(DistanceCoordinate(++distance, --currentX to currentY))
}
}
else -> {
repeat(dist) {
distanceCoordinates.add(DistanceCoordinate(++distance, currentX to --currentY))
}
}
}
}
}
companion object {
var currentX = 0
var currentY = 0
var path = mutableListOf<Pair<Int, Int>>()
fun fromString(input: String): GravityWire {
if (input.isBlank()) return GravityWire()
currentX = 0
currentY = 0
path = mutableListOf()
val parts = input.split(",")
parts.forEach { direction ->
move(direction.first(), direction.substring(1))
}
return GravityWire(path.toList())
}
private fun move(direction: Char, distance: String) {
val dist = distance.toInt()
when (direction) {
'R' -> {
repeat(dist) {
path.add(++currentX to currentY)
}
}
'D' -> {
repeat(dist) {
path.add(currentX to ++currentY)
}
}
'L' -> {
repeat(dist) {
path.add(--currentX to currentY)
}
}
else -> {
repeat(dist) {
path.add(currentX to --currentY)
}
}
}
}
}
}
class FuelManagementSystem(firstWireDirections: String = "", secondWireDirections: String = "") {
var firstWire: GravityWire
var secondWire: GravityWire
init {
firstWire = GravityWire.fromString(firstWireDirections)
secondWire = GravityWire.fromString(secondWireDirections)
}
fun findClosestTwistDistance(): Int {
val intersections = mutableListOf<Pair<Int, Int>>()
firstWire.coordinates.forEach { firstCoordinate ->
secondWire.coordinates.forEach { secondCoordinate ->
if (firstCoordinate == secondCoordinate) intersections.add(firstCoordinate)
}
}
val closestTwist = intersections.sortedBy { abs(it.first) + abs(it.second) }.first()
return abs(closestTwist.first) + abs(closestTwist.second)
}
fun findClosestTwistDistanceSteps(): Int {
val intersections = mutableListOf<Int>()
firstWire.distanceCoordinates.forEach { firstCoordinate ->
secondWire.distanceCoordinates.forEach { secondCoordinate ->
if (firstCoordinate.coordinate == secondCoordinate.coordinate) intersections.add(firstCoordinate.distance + secondCoordinate.distance)
}
}
return intersections.min()
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2019/Day03CrossedWires.class",
"javap": "Compiled from \"Day03CrossedWires.kt\"\npublic final class adventofcode2019.Day03CrossedWires {\n public adventofcode2019.Day03CrossedWires();\n Code:\n 0: aload_0\n 1: invokespeci... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2019/Day10MonitoringStation.kt | package adventofcode2019
import java.lang.Math.toDegrees
import kotlin.math.abs
import kotlin.math.atan2
class Day10MonitoringStation
data class Asteroid(
val x: Int,
val y: Int,
var isVaborized: Boolean = false
)
class Ceres(map: List<String>) {
val asteroids: List<Asteroid>
init {
asteroids = map.flatMapIndexed { y, line ->
line.mapIndexed { x, element ->
if (element == '#') Asteroid(x, y) else null
}
}.filterNotNull()
}
fun detectionsFromBestLocation(): Int {
val (bestX, bestY) = detectBestLocation()
return asteroids.size - 1 - (hiddenAsteroidsFrom(bestX, bestY))
}
fun detectBestLocation(): Pair<Int, Int> {
val (bestX, bestY) = asteroids.minBy { asteroid -> hiddenAsteroidsFrom(asteroid.x, asteroid.y) }
return bestX to bestY
}
fun vaborize(): Int {
val (bestX, bestY) = detectBestLocation()
val groupsByAngle = asteroids
.filterNot { asteroid -> (asteroid.x == bestX && asteroid.y == bestY) }
.groupBy { asteroid -> calculateAngleFromNorth(bestX, bestY, asteroid.x, asteroid.y) }.toSortedMap()
var counter = 0
var nextAsteroidToVaborize: Asteroid?
while (true) {
groupsByAngle.forEach { group ->
nextAsteroidToVaborize = group.value
.filter { asteroid -> asteroid.isVaborized == false }
.sortedBy { asteroid -> manhattanDistance(bestX, bestY, asteroid.x, asteroid.y) }.firstOrNull()
nextAsteroidToVaborize?.let {
it.isVaborized = true
if (counter == 199) {
return (it.x * 100) + it.y
}
counter++
}
}
}
}
fun hiddenAsteroidsFrom(x: Int, y: Int): Int {
val u = if (upNeighborsCount(x, y) > 0) upNeighborsCount(x, y) - 1 else 0
val d = if (downNeighborsCount(x, y) > 0) downNeighborsCount(x, y) - 1 else 0
val l = if (leftNeighborsCount(x, y) > 0) leftNeighborsCount(x, y) - 1 else 0
val r = if (rightNeighborsCount(x, y) > 0) rightNeighborsCount(x, y) - 1 else 0
val a = hiddenBySameAngleCount(x, y)
return u + d + l + r + a
}
fun upNeighborsCount(x: Int, y: Int) = asteroids.count { asteroid -> asteroid.x == x && asteroid.y < y }
fun downNeighborsCount(x: Int, y: Int) = asteroids.count { asteroid -> asteroid.x == x && asteroid.y > y }
fun leftNeighborsCount(x: Int, y: Int) = asteroids.count { asteroid -> asteroid.x < x && asteroid.y == y }
fun rightNeighborsCount(x: Int, y: Int) = asteroids.count { asteroid -> asteroid.x > x && asteroid.y == y }
fun hiddenBySameAngleCount(x: Int, y: Int): Int {
val matches = asteroids.filterNot { asteroid -> asteroid.x == x || asteroid.y == y }
.groupBy { asteroid -> calculateAngleFromNorth(x, y, asteroid.x, asteroid.y) }
var totalCount = 0
matches.forEach { group ->
totalCount += if (group.value.size > 1) group.value.size - 1 else 0
}
return totalCount
}
fun calculateAngleFromNorth(referenceX: Int, referenceY: Int, asteroidX: Int, asteroidY: Int): Double {
val angle = toDegrees(
atan2(
(asteroidY - referenceY).toDouble(),
(asteroidX - referenceX).toDouble()
)
) + 90
return if (angle < 0) angle + 360 else angle
}
fun manhattanDistance(referenceX: Int, referenceY: Int, asteroidX: Int, asteroidY: Int) =
abs(referenceX - asteroidX) + abs(referenceY - asteroidY)
}
| [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2019/Day10MonitoringStation.class",
"javap": "Compiled from \"Day10MonitoringStation.kt\"\npublic final class adventofcode2019.Day10MonitoringStation {\n public adventofcode2019.Day10MonitoringStation();\n Code:\n 0: aload_0\n ... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2019/Day12TheNbodyProblem.kt | package adventofcode2019
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sqrt
class Day12TheNbodyProblem
data class MoonVelocity(var x: Int, var y: Int, var z: Int) {
val kineticEnergy: Int
get() = abs(x) + abs(y) + abs(z)
}
data class JupiterMoon(val id: Int, var x: Int, var y: Int, var z: Int, val velocity: MoonVelocity) {
val totalEnergy: Int
get() = (abs(x) + abs(y) + abs(z)) * velocity.kineticEnergy
val currentState: List<Int>
get() = listOf(x, y, z, velocity.x, velocity.y, velocity.z)
val currentCoordinates: List<Int>
get() = listOf(x, y, z)
fun applyGravityFromPeer(peer: JupiterMoon) {
if (x < peer.x) velocity.x++
else if (x > peer.x) velocity.x--
if (y < peer.y) velocity.y++
else if (y > peer.y) velocity.y--
if (z < peer.z) velocity.z++
else if (z > peer.z) velocity.z--
}
fun adjustCoordinatesByVelocity() {
x += velocity.x
y += velocity.y
z += velocity.z
}
}
class JupiterOrbit(moonCoordinates: List<String>) {
val moons: List<JupiterMoon>
init {
moons = moonCoordinates.mapIndexed { index, coordinates -> parseMoon(index, coordinates) }
}
private fun parseMoon(id: Int, coordinates: String): JupiterMoon {
val x = coordinates.substringAfter("x=").substringBefore(",").toInt()
val y = coordinates.substringAfter("y=").substringBefore(",").toInt()
val z = coordinates.substringAfter("z=").substringBefore(">").toInt()
return JupiterMoon(id, x, y, z, MoonVelocity(0, 0, 0))
}
fun step(stepCount: Int) {
repeat(stepCount) {
applyGravity()
applyVelocity()
}
}
fun stepsUntilCircle(): Long {
val startingX: List<Pair<Int, Int>> = moons.map { it.x to it.velocity.x }
val startingY: List<Pair<Int, Int>> = moons.map { it.y to it.velocity.y }
val startingZ: List<Pair<Int, Int>> = moons.map { it.z to it.velocity.z }
var foundX: Long? = null
var foundY: Long? = null
var foundZ: Long? = null
var stepCount = 0L
do {
stepCount++
step(1)
foundX = if (foundX == null && startingX == moons.map { it.x to it.velocity.x }) stepCount else foundX
foundY = if (foundY == null && startingY == moons.map { it.y to it.velocity.y }) stepCount else foundY
foundZ = if (foundZ == null && startingZ == moons.map { it.z to it.velocity.z }) stepCount else foundZ
} while (foundX == null || foundY == null || foundZ == null)
return lcm(foundX, foundY, foundZ)
}
fun lcm(vararg numbers: Long): Long {
val groups = mutableListOf<List<Pair<Long, Long>>>()
for (n in numbers) {
groups.add(groupNumbers(factorize(n)))
}
val numberGroups = groups.flatMap { it }
val orderedGroups =
numberGroups.map { g -> g.first to numberGroups.filter { it.first == g.first }.maxOf { it.second } }.toSet()
return orderedGroups.fold(1) { acc, pair -> acc * (pair.first.pow(pair.second)) }
}
private fun Long.pow(exponent: Long) = Math.pow(this.toDouble(), exponent.toDouble()).toInt()
fun factorize(number: Long): List<Long> {
val result: ArrayList<Long> = arrayListOf()
var n = number
while (n % 2L == 0L) {
result.add(2)
n /= 2
}
val squareRoot = sqrt(number.toDouble()).toInt()
for (i in 3..squareRoot step 2) {
while (n % i == 0L) {
result.add(i.toLong())
n /= i
}
}
if (n > 2) {
result.add(n)
}
return result
}
fun groupNumbers(nums: List<Long>): List<Pair<Long, Long>> {
val groups = nums.groupBy { it }
val groupCounts = groups.map { it.key to it.value.size.toLong() }
return groupCounts
}
private fun applyGravity() {
val oldState = moons.toList()
moons.forEach { moon ->
oldState.filter { it.id != moon.id }.forEach { moon.applyGravityFromPeer(it) }
}
}
private fun applyVelocity() {
moons.forEach { it.adjustCoordinatesByVelocity() }
}
fun totalEnergy() = moons.sumOf { moon -> moon.totalEnergy }
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2019/Day12TheNbodyProblem.class",
"javap": "Compiled from \"Day12TheNbodyProblem.kt\"\npublic final class adventofcode2019.Day12TheNbodyProblem {\n public adventofcode2019.Day12TheNbodyProblem();\n Code:\n 0: aload_0\n 1:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.