kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
nerok__Advent-of-code-2021__7553c28/src/main/kotlin/day9.kt | import java.io.File
fun main(args: Array<String>) {
day9part2()
}
fun day9part1() {
var coordinates = mutableListOf<List<Int>>()
val input = File("day9input.txt").bufferedReader().readLines()
input.mapIndexed { index, line ->
line.split("")
.filterNot { it == "" }
.map { it.toInt() }
.let { coordinates.add(index, it) }
}
findLocalMinimas(coordinates).map { coordinates[it.first][it.second]+1 }.sum().also { println(it) }
}
fun day9part2() {
var coordinates = mutableListOf<List<Int>>()
val input = File("day9input.txt").bufferedReader().readLines()
input.mapIndexed { index, line ->
line.split("")
.filterNot { it == "" }
.map { it.toInt() }
.let { coordinates.add(index, it) }
}
val limits = findBasinLimits(coordinates)
println("Total size: ${coordinates.size * coordinates.first().size}")
println("Nines: ${limits.size}")
val score = clusterBaisins(coordinates, limits)
.map { it.value.size }
.sorted()
.also { "Non-nines: ${println(it.sum())}" }
.takeLast(3)
.reduce { acc: Int, i: Int ->
acc * i
}
println("Score $score")
}
fun clusterBaisins(map: MutableList<List<Int>>, basinLimits: Set<Pair<Int,Int>>): Map<Int, Set<Pair<Int,Int>>> {
var nextCluster = 0
val clusterMap = mutableMapOf<Int, Set<Pair<Int,Int>>>()
val clusterIndex = mutableMapOf<Pair<Int,Int>, Int>()
map.forEachIndexed { rowIndex, row ->
row.forEachIndexed { index, point ->
if (point == 9) return@forEachIndexed
val columnNeighbours = when (rowIndex) {
0 -> {
listOf(rowIndex+1 to index to clusterIndex.getOrDefault(rowIndex+1 to index, -1))
}
map.size - 1 -> {
listOf(rowIndex-1 to index to clusterIndex.getOrDefault(rowIndex-1 to index, -1))
}
else -> {
listOf(
rowIndex-1 to index to clusterIndex.getOrDefault(rowIndex-1 to index, -1),
rowIndex+1 to index to clusterIndex.getOrDefault(rowIndex+1 to index, -1)
)
}
}
val rowNeighbours = when(index) {
0 -> {
listOf(rowIndex to index + 1 to clusterIndex.getOrDefault(rowIndex to index + 1, -1))
}
row.size - 1 -> {
listOf(rowIndex to index - 1 to clusterIndex.getOrDefault(rowIndex to index - 1, -1))
}
else -> {
listOf(
rowIndex to index-1 to clusterIndex.getOrDefault(rowIndex to index-1, -1),
rowIndex to index+1 to clusterIndex.getOrDefault(rowIndex to index+1, -1)
)
}
}
val neighbours = columnNeighbours + rowNeighbours
if (neighbours.none { it.second != -1 }) {
val neighbourhood = (neighbours.map { it.first } + (rowIndex to index))
.filter { map[it.first][it.second] != 9 }
.toSet()
clusterMap[nextCluster] = neighbourhood
neighbourhood.forEach {
clusterIndex[it] = nextCluster
}
nextCluster = nextCluster.inc()
}
else {
val neighbourhood = (neighbours.map { it.first } + (rowIndex to index))
.filter { map[it.first][it.second] != 9 }
.toMutableSet()
var cluster = -1
neighbourhood.map {
if (cluster == -1) {
cluster = clusterIndex.getOrDefault(it, -1)
}
else {
val neighbourIndex = clusterIndex[it]
if (neighbourIndex != null && cluster != neighbourIndex) {
println("Cluster: $cluster, neighbour: ${neighbourIndex}, it: $it")
val newCluster = minOf(cluster, neighbourIndex)
val neighbourhood1 = clusterMap.getOrDefault(neighbourIndex, emptySet())
clusterMap.remove(neighbourIndex)
val neighbourhood2 = clusterMap.getOrDefault(cluster, emptySet())
clusterMap.remove(cluster)
val newNeighbourhood = neighbourhood1 + neighbourhood2
newNeighbourhood.forEach { clusterIndex[it] = newCluster }
clusterMap[newCluster] = newNeighbourhood
}
}
}
neighbourhood.forEach {
clusterIndex[it] = cluster
}
clusterMap[cluster]?.let { neighbourhood.addAll(it) }
clusterMap[cluster] = neighbourhood
}
}
}
return clusterMap
}
fun findBasinLimits(map: MutableList<List<Int>>): Set<Pair<Int,Int>> {
val limits = mutableSetOf<Pair<Int,Int>>()
map.forEachIndexed { rowIndex, row ->
row.forEachIndexed { index, point ->
if (point == 9) limits.add(rowIndex to index)
}
}
return limits
}
fun findLocalMinimas(map: MutableList<List<Int>>): List<Pair<Int,Int>> {
val minimas = mutableListOf<Pair<Int,Int>>()
map.forEachIndexed { rowIndex, row ->
row.forEachIndexed { index, point ->
val possibleMinima = when (index) {
0 -> {
point < row[index+1]
}
row.size-1 -> {
point < row[index-1]
}
else -> {
(point < row[index-1]) && (point < row[index+1])
}
}
//println("Row $rowIndex, column $index: $possibleMinima")
if (!possibleMinima) {
return@forEachIndexed
}
val localMinima = when (rowIndex) {
0 -> {
point < map[rowIndex+1][index]
}
map.size-1 -> {
point < map[rowIndex-1][index]
}
else -> {
(point < map[rowIndex-1][index]) && (point < map[rowIndex+1][index])
}
}
if (localMinima) {
minimas.add(rowIndex to index)
}
}
}
return minimas
} | [
{
"class_path": "nerok__Advent-of-code-2021__7553c28/Day9Kt.class",
"javap": "Compiled from \"day9.kt\"\npublic final class Day9Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic #15 ... |
lhDream__wuziqi__c83c58c/src/test/kotlin/Test.kt | import java.util.*
import kotlin.math.abs
// 棋盘大小
const val BOARD_SIZE = 15
// 评估函数(简化版本,根据棋局评估得分)
// 五子棋中针对当前局面的评估函数
fun evaluate(board: Array<Array<Int>>, player: Int): Int {
val opponent = if (player == 2) 1 else 2
var score = 0
// 检查每个位置的行、列、对角线是否存在连续的棋子
for (i in 0 until BOARD_SIZE) {
for (j in 0 until BOARD_SIZE) {
// 检查水平、垂直和对角线上的棋子情况
val directions = arrayOf(
intArrayOf(1, 0), intArrayOf(1, -1),
intArrayOf(0, -1), intArrayOf(-1, -1),
intArrayOf(-1, 0), intArrayOf(-1, 1),
intArrayOf(0, 1), intArrayOf(1, 1)
)
for (dir in directions) {
var countPlayer = 0
var countOpponent = 0
var association = 0
for (k in 0 until 6) {
val r = i + k * dir[0]
val c = j + k * dir[1]
if (r in 0 until BOARD_SIZE && c in 0 until BOARD_SIZE) {
if (board[r][c] == player) {
countPlayer++
} else if (board[r][c] == opponent) {
countOpponent++
}
association = association * 10 + board[r][c]
} else {
break
}
}
score += when(association){
22222 -> 50000 // 活五
22220, 22202, 22022, 20222 -> 10000 // 活四
122220, 122202, 122022, 120222, 102222, 22221 -> 5000 // 冲四
222, 2202, 2022, 2220 -> 2000 // 活三
12220, 12202, 12022, 10222, 2221 -> 1000 // 眠三
22, 202, 20 -> 500 // 活二
1220, 1202, 1020, 210, 2120 -> 200 // 眠二
else -> 0
}
}
}
}
return score
}
// Minimax 算法
fun minimax(board: Array<Array<Int>>, depth: Int, player: Int): Int {
if (depth == 0) {
return evaluate(board,player)
}
var bestScore = 0
val opponent = if (player == 2) 1 else 2
for (i in 0 until BOARD_SIZE) {
for (j in 0 until BOARD_SIZE) {
if (board[i][j] == 0) {
board[i][j] = opponent
val score = minimax(board, depth - 1, opponent)
board[i][j] = 0
bestScore = maxOf(bestScore, score)
}
}
}
return bestScore
}
// 寻找最佳下棋位置
fun findBestMove(board: Array<Array<Int>>,player: Int): Pair<Int, Int> {
var bestScore = Int.MIN_VALUE
var bestMove = Pair(-1, -1)
for (i in 0 until BOARD_SIZE) {
for (j in 0 until BOARD_SIZE) {
if (board[i][j] == 0) {
board[i][j] = player // 模拟落子
var score = minimax(board, 3, player) // 这里设定最大搜索深度为3
score = score * major[i][j] + major[i][j] // 位置价值
board[i][j] = 0 // 撤销落子
if (score > bestScore) {
bestScore = score // 更新最高分
bestMove = Pair(i, j) // 更新最佳落子位置
}
}
}
}
return bestMove
}
// 初始化位置价值矩阵
fun initMatrix(matrix:Array<Array<Int>>){
val centerX = matrix.size / 2
val centerY = matrix.size / 2
for (i in matrix.indices) {
for (j in matrix.indices) {
val distance = abs(i - centerX) + abs(j - centerY)
matrix[i][j] = matrix.size - distance
}
}
}
// 位置价值矩阵
val major = Array(BOARD_SIZE) { Array(BOARD_SIZE) { 0 } }
// 主函数
fun main() {
initMatrix(major)
val board = Array(BOARD_SIZE) { Array(BOARD_SIZE) { 0 } }
// 模拟当前棋盘状态
val scan = Scanner(System.`in`)
while (true){
// ...
val (x,y) = findBestMove(board,2)
board[x][y] = 2
println("Best Move: ${x}, $y")
for (i in board.indices){
println(board[i].contentToString())
}
val p = scan.nextLine().split(",")
board[p[0].toInt()][p[1].toInt()] = 1
}
}
| [
{
"class_path": "lhDream__wuziqi__c83c58c/TestKt.class",
"javap": "Compiled from \"Test.kt\"\npublic final class TestKt {\n public static final int BOARD_SIZE;\n\n private static final java.lang.Integer[][] major;\n\n public static final int evaluate(java.lang.Integer[][], int);\n Code:\n 0: alo... |
alexiscrack3__algorithms-kotlin__a201986/src/main/kotlin/SubArray.kt | class SubArray {
fun getLengthOfLongestContiguousSubarray(array: Array<Int>): Int {
var maxLength = 1
for (i in 0 until array.size - 1) {
var minimum = array[i]
var maximum = array[i]
for (j in i + 1 until array.size) {
minimum = Math.min(minimum, array[j])
maximum = Math.max(maximum, array[j])
if (maximum - minimum == j - i) {
maxLength = Math.max(maxLength, maximum - minimum + 1)
}
}
}
return maxLength
}
fun getSmallestPositiveNumber(array: Array<Int>): Int {
var result = 1
var i = 0
while (i < array.size && array[i] <= result) {
result += array[i]
i++
}
return result
}
fun getSmallestSubarrayWithSumGreaterThanValue(array: Array<Int>, value: Int): Int {
var minLength = array.size + 1
for (start in 0 until array.size) {
// Initialize sum starting with current start
var sum = array[start]
// If first element itself is greater
if (sum > value) {
return 1
}
for (end in start + 1 until array.size) {
sum += array[end]
// If sum becomes more than x and length of
// this subarray is smaller than current smallest
// length, update the smallest length (or result)
val length = end - start + 1
if (sum > value && length < minLength) {
minLength = length
}
}
}
return minLength
}
}
| [
{
"class_path": "alexiscrack3__algorithms-kotlin__a201986/SubArray.class",
"javap": "Compiled from \"SubArray.kt\"\npublic final class SubArray {\n public SubArray();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n ... |
goetz-markgraf__battleship_2024__ebd9504/src/main/kotlin/Main.kt | import java.lang.Integer.max
import java.lang.Integer.min
import kotlin.math.abs
enum class Function {
CHECK, PLACE
}
enum class Player {
PLAYER1, PLAYER2
}
data class Position(
val col: Int,
val row: Int
)
data class Ship(
var parts: List<Position>
)
typealias Field = Array<Array<Int>>
data class GameState(
val field1: Field,
val field2: Field,
val ships1: List<Ship>,
val ships2: List<Ship>
)
fun main() {
var gameState = createGameState()
showField(gameState, Player.PLAYER1)
while (true) {
print("Enter ship coordinates: ")
gameState = place(gameState, Player.PLAYER1)
showField(gameState, Player.PLAYER1)
}
}
fun createGameState(): GameState {
val field1 = Array(10) { Array(10) { 0 } }
val field2 = Array(10) { Array(10) { 0 } }
return GameState(field1, field2, emptyList(), emptyList())
}
fun showField(gameState: GameState, player: Player) {
for (row in '0'..'9') {
print("\t $row")
}
println()
val tabVertLine = "\t${9474.toChar()}"
val ships = if (player == Player.PLAYER1) gameState.ships1 else gameState.ships2
for (col in 0 until 10) {
print(" " + (col + 65).toChar() + tabVertLine)
for (row in 0 until 10) {
var shipFound = false
ships.forEach {
it.parts.forEach {
if (it.row == row && it.col == col) {
shipFound = true
}
}
}
if (shipFound) {
print("██")
}
print(tabVertLine)
}
println()
}
}
fun place(gameState: GameState, player: Player): GameState {
val location = readln().lowercase()
println("inside place")
val ships = (if (player == Player.PLAYER1) gameState.ships1 else gameState.ships2).toMutableList()
if (inputIsValid(Function.PLACE, location)) {
val coordinates = convertPair(location)
val firstPos =
Pair(min(coordinates.first.row, coordinates.second.row), min(coordinates.first.col, coordinates.second.col))
val lastPos =
Pair(max(coordinates.first.row, coordinates.second.row), max(coordinates.first.col, coordinates.second.col))
println(coordinates)
val n = mutableListOf<Position>()
for (row in firstPos.first..lastPos.first) {
for (col in firstPos.second..lastPos.second) {
if (isCellOccupied(gameState, player, Position(col, row))) {
println("This cell is occupied")
return gameState
} else {
println("set at $row,$col")
n.add(Position(col, row))
}
}
}
ships.addLast(Ship(n))
}
return if (player == Player.PLAYER1) {
gameState.copy(ships1 = ships)
} else {
gameState.copy(ships2 = ships)
}
}
fun isCellOccupied(gameState: GameState, player: Player, position: Position): Boolean {
val ships = if (player == Player.PLAYER1) gameState.ships1 else gameState.ships2
return ships.any { ship -> ship.parts.any { it == position } }
}
fun convertPair(input: String): Pair<Position, Position> {
println("in convertPair $input")
return Pair(convert(input.substring(0, 2)), convert(input.substring(2, 4)))
}
fun convert(input: String): Position {
println("in convert $input")
val rowChar = input[0]
val columnChar = input[1]
val row = rowChar - 'a'
val column = columnChar.toString().toInt()
return Position(row, column)
}
fun check() {
val pos = readln().lowercase()
if (inputIsValid(Function.CHECK, pos)) {
}
}
fun inputIsValid(function: Function, input: String): Boolean {
println(function)
when (function) {
Function.CHECK -> {
if (input.length == 2 && input[0] in 'a'..'j' && input[1] in '0'..'9') {
return true
} else {
println("Enter the cell index in format \"letternumber\", for example \"a0a3\"")
return false
}
}
Function.PLACE -> {
if (input.length == 4 &&
input[0] in 'a'..'j' && input[1] in '0'..'9' &&
input[2] in 'a'..'j' && input[3] in '0'..'9' &&
(input[0] == input[2] || input[1] == input[3]) &&
abs(input[0] - input[2]) <= 3 &&
abs(input[1] - input[3]) <= 3
) {
return true
} else {
println("Enter the cell indexes in format \"letternumberletternumber\" for placing ship, for example \"a0b0\"")
return false
}
}
}
}
| [
{
"class_path": "goetz-markgraf__battleship_2024__ebd9504/MainKt$WhenMappings.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method Function.va... |
jomartigcal__kotlin-heroes__ad16779/practice-4/src/practice4e.kt | // Special Permutation
// https://codeforces.com/contest/1347/problem/E
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
fun main() {
val lines = readInt()
for (line in 1..lines) {
val number = readInt()
if (number < 4) {
println("-1")
} else {
println(getPermutation(number).joinToString(" "))
}
}
}
fun getPermutation(number: Int): List<Int> {
val permutations = mutableSetOf<Int>()
val numbers = (1..number).map { it } as MutableList
val evens = numbers.filter { it % 2 == 0}
permutations.addAll(evens)
val odds = numbers.filter { it % 2 != 0}.reversed()
permutations.add(evens.last()-3)
permutations.addAll(odds)
return permutations.toList()
}
| [
{
"class_path": "jomartigcal__kotlin-heroes__ad16779/Practice4eKt.class",
"javap": "Compiled from \"practice4e.kt\"\npublic final class Practice4eKt {\n private static final java.lang.String readLn();\n Code:\n 0: invokestatic #11 // Method kotlin/io/ConsoleKt.readLine:()Ljava/lan... |
andrewrlee__adventOfCode2021__aace0fc/src/main/kotlin/Day15.kt | import java.io.File
import java.nio.charset.Charset.defaultCharset
import kotlin.streams.toList
typealias ChitonGrid = Map<Pair<Int, Int>, Day15.Square>
object Day15 {
private fun toCoordinates(row: Int, line: String) = line.chars()
.map(Character::getNumericValue)
.toList()
.mapIndexed { col, value -> (col to row) to Square((col to row), value) }
private fun draw(coordinates: Collection<Square>) {
println("\n")
val maxCols = coordinates.maxOf { it.coord.first }
val maxRows = coordinates.maxOf { it.coord.second }
(0..maxRows).forEach { row ->
(0..maxCols).forEach { col ->
print(coordinates.find { it.coord == Pair(col, row) }?.let { it.risk } ?: ".")
}
println()
}
}
data class Square(
var coord: Pair<Int, Int>,
var risk: Int,
var distance: Int = Int.MAX_VALUE,
var parent: Square? = null
): Comparable<Square> {
fun getNeighbours(
validCells: ChitonGrid,
remaining: Collection<Square>,
deltas: List<Pair<Int, Int>> = listOf(
-1 to 0, 0 to -1,
1 to 0, 0 to 1,
)
) = deltas.asSequence()
.map { (x2, y2) -> coord.first + x2 to coord.second + y2 }
.mapNotNull { validCells[it] }
.filter { remaining.contains(it) }
override fun compareTo(other: Square): Int {
return this.distance.compareTo(other.distance)
}
}
object Part1 {
val chitonGrid = {
File("day15/input-real.txt")
.readLines(defaultCharset())
.mapIndexed(::toCoordinates)
.flatten()
.associate { it }
}
fun run() {
val grid = chitonGrid()
grid.values.first().distance = 0
val queue = grid.values.toMutableList()
while (queue.isNotEmpty()) {
val next = queue.minOrNull()!!
queue.remove(next)
val neighbours = next.getNeighbours(grid, queue)
neighbours.forEach {
if (next.distance + next.risk < it.distance) {
it.distance = next.distance + next.risk
it.parent = next
}
}
}
var end = grid.values.last()
val parents = mutableListOf(end)
while(end.parent != null) {
end = end.parent!!
parents.add(end)
}
draw(parents)
parents.reversed().forEach { println("${it.coord} ${it.risk} ${it.distance}") }
parents.sumOf { it.risk }.also { println(it - grid.values.first().risk) }
}
}
object Part2 {
private fun toCoordinates(row: Int, line: List<Int>) = line
.mapIndexed { col, value -> (col to row) to Square((col to row), value) }
fun run() {
val grid = File("day15/input-real.txt")
.readLines(defaultCharset())
.map { it.map (Character::getNumericValue) }
.map { vals -> (0..4).flatMap{ i -> vals.map { round(it, i) }}}.let{
grid -> (0..4).flatMap{ i -> grid.map { row -> row.map { round(it, i) } }}
}.mapIndexed { i, it -> toCoordinates(i, it) }
.flatten()
.associate { it }
grid.values.first().distance = 0
val queue = grid.values.toMutableList()
val total = queue.size
var count = 0
while (queue.isNotEmpty()) {
if (count++ % 500 == 0) {
println("$count/$total (${queue.size})")
}
val next = queue.minOrNull()!!
queue.remove(next)
val neighbours = next.getNeighbours(grid, queue)
neighbours.forEach {
if (next.distance + next.risk < it.distance) {
it.distance = next.distance + next.risk
it.parent = next
}
}
}
var end = grid.values.last()
val parents = mutableListOf(end)
while(end.parent != null) {
end = end.parent!!
parents.add(end)
}
draw(parents)
parents.reversed().forEach { println("${it.coord} ${it.risk} ${it.distance}") }
parents.sumOf { it.risk }.also { println(it - grid.values.first().risk) }
}
}
private fun round(it: Int, i: Int): Int {
val x = it + i
val y = x - 9
return if (y > 0) y else x
}
}
fun main() {
Day15.Part1.run()
Day15.Part2.run() // 21 mins!
} | [
{
"class_path": "andrewrlee__adventOfCode2021__aace0fc/Day15.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15 {\n public static final Day15 INSTANCE;\n\n private Day15();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":... |
andrewrlee__adventOfCode2021__aace0fc/src/main/kotlin/Day14.kt | import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
import kotlin.collections.Map.Entry
object Day14 {
object Part1 {
private fun toRule(s: String): Pair<List<Char>, Char> {
val (pair, value) = s.split(" -> ")
return pair.toCharArray().let { listOf(it[0], it[1]) } to value[0]
}
private fun step(
input: List<Char>,
rules: Map<List<Char>, Char>
) = input.windowed(2, 1)
.flatMap { p ->
rules[p]?.let { listOf(p[0], it) } ?: listOf(p[0])
} + input.last()
fun run() {
val lines = File("day14/input-real.txt").readLines(UTF_8)
val input = lines.first().toCharArray().toList()
val rules = lines.drop(2).associate(::toRule)
val result = generateSequence(input) { step(it, rules) }.drop(10).first()
val freqs = result.groupingBy { it }.eachCount().entries
val max = freqs.maxOf { it.value }
val min = freqs.minOf { it.value }
println(max - min)
}
}
object Part2 {
private fun toRule(s: String): Pair<List<Char>, Char> {
val (pair, value) = s.split(" -> ")
return pair.toCharArray().let { listOf(it[0], it[1]) } to value[0]
}
private fun toTransitions() = { (k, v): Entry<List<Char>, Char> ->
(k[0] to k[1]) to listOf(k[0] to v, v to k[1]) }
private fun step(
values: MutableMap<Pair<Char, Char>, Long>,
transitions: Map<Pair<Char, Char>, List<Pair<Char, Char>>>
): MutableMap<Pair<Char, Char>, Long> {
val newValues = values.flatMap { (k, v) ->
val new = transitions[k]!!
new.map { it to v }
}.groupBy({ it.first }, { it.second }).mapValues { it.value.sum() }
return newValues.toMutableMap();
}
fun run() {
val lines = File("day14/input-real.txt").readLines(UTF_8)
val input = lines.first().toCharArray().toList()
val rules = lines.drop(2).associate(::toRule)
val transitions = rules.map(toTransitions()).toMap()
val initialFreqs = input
.windowed(2, 1)
.map { it[0] to it[1] }
.groupingBy { it }
.eachCount()
.mapValues { it.value.toLong() }
.toMutableMap()
val result = generateSequence(initialFreqs) { step(it, transitions) }.drop(40).first()
val freqs = result.entries
.groupBy({ it.key.first }, { it.value })
.mapValues { it.value.sum() }
.toMutableMap().also {
// Add single last character in
it[input.last()] = 1L + it[input.last()]!!
}
val max = freqs.maxOf { it.value }
val min = freqs.minOf { it.value }
println(max - min)
}
}
}
fun main() {
Day14.Part1.run()
Day14.Part2.run()
}
| [
{
"class_path": "andrewrlee__adventOfCode2021__aace0fc/Day14Kt.class",
"javap": "Compiled from \"Day14.kt\"\npublic final class Day14Kt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field Day14$Part1.INSTANCE:LDay14$Part1;\n 3: invokevirtual #15 ... |
andrewrlee__adventOfCode2021__aace0fc/src/main/kotlin/Day16.kt | import Day16.Type.EQUAL_TO
import Day16.Type.G_THAN
import Day16.Type.LITERAL
import Day16.Type.L_THAN
import Day16.Type.MAX
import Day16.Type.MIN
import Day16.Type.PRODUCT
import Day16.Type.SUM
import java.io.File
import java.math.BigInteger
import java.nio.charset.Charset.defaultCharset
object Day16 {
enum class Type(val code: Int) {
SUM(0),
PRODUCT(1),
MIN(2),
MAX(3),
LITERAL(4),
G_THAN(5),
L_THAN(6),
EQUAL_TO(7);
companion object {
fun fromCode(code: Int) = values().first { it.code == code }
}
}
private fun String.toBinary() = BigInteger(this, 16).toString(2).let {
String.format("%4s", it).replace(" ", "0").toCharArray().toList()
}
sealed class Packet(
open val version: Int,
open val type: Type,
) {
abstract fun getTotalVersion(): Int
abstract fun evaluate(): Long
}
data class Literal(
override val version: Int,
val literal: Long
) : Packet(version, LITERAL) {
override fun getTotalVersion() = version
override fun evaluate(): Long = literal
}
data class Operator(
override val version: Int,
override val type: Type,
val payload: List<Packet>
) : Packet(version, type) {
override fun getTotalVersion() = version + (payload.sumOf { it.getTotalVersion() })
override fun evaluate() = when (type) {
SUM -> payload.sumOf { it.evaluate() }
PRODUCT -> payload.fold(1L) { acc, i -> acc * i.evaluate() }
MIN -> payload.minOf { it.evaluate() }
MAX -> payload.maxOf { it.evaluate() }
G_THAN -> if (payload[0].evaluate() > payload[1].evaluate()) 1 else 0
L_THAN -> if (payload[0].evaluate() < payload[1].evaluate()) 1 else 0
EQUAL_TO -> if (payload[0].evaluate() == payload[1].evaluate()) 1 else 0
else -> throw RuntimeException("unexpected type")
}
}
data class BinaryString(var input: List<Char>) {
fun isNotEmpty() = input.isNotEmpty() && input.size > 3
fun readString(length: Int): String {
val chars = mutableListOf<Char>()
var index = 0
var realCount = 0
do {
when (val c = input[index]) {
'%' -> {}
else -> {
chars.add(c)
realCount++
}
}
index++
} while (realCount != length)
input = input.subList(index, input.size)
return chars.joinToString("")
}
fun readSection(length: Int): BinaryString {
val chars = mutableListOf<Char>()
var index = 0
var realCount = 0
do {
val c = input[index]
when (c) {
'%' -> {}
else -> {
realCount++
}
}
chars.add(c)
index++
} while (realCount != length)
input = input.subList(index, input.size)
return BinaryString(chars)
}
fun readInt(length: Int): Int {
val string = readString(length)
return Integer.parseInt(string, 2)
}
}
private fun readPackets(input: BinaryString): MutableList<Packet> {
val packets = mutableListOf<Packet>()
while (input.isNotEmpty()) {
packets.add(input.readPacket())
}
return packets
}
private fun BinaryString.readPacket(): Packet {
val version = this.readInt(3)
return when (val type = Type.fromCode(this.readInt(3))) {
LITERAL -> readLiteral(version, this)
else -> readOperator(version, type, this)
}
}
private fun readOperator(version: Int, type: Type, input: BinaryString): Packet {
val packets = when (input.readString(1)) {
"0" -> {
val size = input.readInt(15)
readPackets(input.readSection(size))
}
"1" -> {
val numberOfPackets = input.readInt(11)
(0 until numberOfPackets).map { input.readPacket() }
}
else -> throw RuntimeException("unexpected val")
}
return Operator(version, type, packets)
}
private fun readLiteral(version: Int, input: BinaryString): Packet {
val parts = mutableListOf<Char>()
var finish: Boolean
do {
val (a, b, c, d, e) = input.readString(5).toList()
parts.addAll(listOf(b, c, d, e))
finish = a == '0'
} while (!finish)
val value = BigInteger(parts.joinToString(""), 2).longValueExact()
return Literal(version, value)
}
val input = {
File("day16/input-real.txt")
.readText(defaultCharset())
.map { it.toString().toBinary() }
.flatMap { it + '%' }
.let { BinaryString(it) }
}
object Part1 {
fun run() = println(input().readPacket().getTotalVersion())
}
object Part2 {
fun run() = println(input().readPacket().evaluate())
}
}
fun main() {
Day16.Part1.run()
Day16.Part2.run()
} | [
{
"class_path": "andrewrlee__adventOfCode2021__aace0fc/Day16$Packet.class",
"javap": "Compiled from \"Day16.kt\"\npublic abstract class Day16$Packet {\n private final int version;\n\n private final Day16$Type type;\n\n private Day16$Packet(int, Day16$Type);\n Code:\n 0: aload_0\n 1: invoke... |
andrewrlee__adventOfCode2021__aace0fc/src/main/kotlin/Day10.kt | import Day10.Type.CLOSE
import Day10.Type.OPEN
import java.io.File
import java.nio.charset.Charset.defaultCharset
import java.util.Stack
object Day10 {
data class Bracket(val bracketType: BracketType, val type: Type)
enum class Type { OPEN, CLOSE }
enum class BracketType(val open: Char, val close: Char, val points: Int, val autoCompleteScore: Int) {
SQUARE('[', ']', 57, 2),
ROUND('(', ')', 3, 1),
BRACE('{', '}', 1197, 3),
ANGLE('<', '>', 25137, 4);
fun match(c: Char): Type? = when (c) {
open -> OPEN
close -> CLOSE
else -> null
}
}
fun String.toBrackets() = this.map { c ->
BracketType.values().firstNotNullOf { b ->
b.match(c)?.let { Bracket(b, it) }
}
}
object Part1 {
private fun findInvalid(brackets: List<Bracket>): BracketType? {
val stack = Stack<Bracket>()
brackets.forEach {
if (it.type == CLOSE) {
val opening = stack.pop()
if (it.bracketType != opening.bracketType) {
return it.bracketType
}
} else {
stack.push(it)
}
}
return null
}
fun run() {
File("day10/input-real.txt")
.readLines(defaultCharset())
.mapNotNull { findInvalid(it.toBrackets()) }
.map { it.points }
.reduce(Int::plus)
.also { println(it) }
}
}
object Part2 {
private fun complete(brackets: List<Bracket>): Long? {
val stack = Stack<Bracket>()
brackets.forEach {
if (it.type == CLOSE) {
val opening = stack.pop()
if (it.bracketType != opening.bracketType) {
return null
}
} else {
stack.push(it)
}
}
if (stack.isEmpty()) {
return null
}
return stack.reversed().fold(0L) { acc, b -> (acc * 5) + b.bracketType.autoCompleteScore }
}
fun run() {
File("day10/input-real.txt").readLines(defaultCharset())
.mapNotNull { complete(it.toBrackets()) }
.sorted()
.also { println(it[it.size/2]) }
}
}
}
fun main() {
Day10.Part1.run()
Day10.Part2.run()
} | [
{
"class_path": "andrewrlee__adventOfCode2021__aace0fc/Day10$BracketType.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class Day10$BracketType extends java.lang.Enum<Day10$BracketType> {\n private final char open;\n\n private final char close;\n\n private final int points;\n\n private final... |
andrewrlee__adventOfCode2021__aace0fc/src/main/kotlin/Day17.kt | object Day17 {
// val targetArea = 20..30 to -10..-5
val targetArea = 248..285 to -85..-56
data class Coord(val x: Int, val y: Int) {
constructor(coord: Pair<Int, Int>) : this(coord.first, coord.second)
}
private fun Pair<IntRange, IntRange>.toCoords(): List<Coord> {
val (xs, ys) = this
return xs.flatMap { row -> ys.map { col -> Coord(row, col) } }
}
private fun Pair<IntRange, IntRange>.draw(path: List<Coord>) {
val targetArea = this.toCoords()
println("\n")
val maxCols = (path + targetArea).maxOf { it.x } + 2
val maxRows = (path + targetArea).maxOf { it.y } + 2
val minRows = (path + targetArea).minOf { it.y } - 2
(minRows..maxRows).reversed().forEach { row ->
print(row.toString().padStart(3, ' ') + " ")
(0..maxCols).forEach { col ->
print(
when {
path.contains(Coord(col, row)) -> "#"
targetArea.contains(Coord(col, row)) -> "T"
else -> "."
}
)
}
println()
}
}
private fun Pair<IntRange, IntRange>.outOfBounds(point: Coord): Boolean {
val (xs, ys) = this
val (x, y) = point
return x > xs.last || y < ys.first
}
fun Pair<IntRange, IntRange>.within(point: Coord): Boolean {
val (xs, ys) = this
val (x, y) = point
return xs.contains(x) && ys.contains(y)
}
private fun fire(x: Int, y: Int): List<Coord> {
val velocity = generateSequence(x to y) { (x, y) ->
(when {
x > 0 -> x - 1
x < 0 -> x + 1
else -> 0
}) to y - 1
}.iterator()
return generateSequence(Coord(0 to 0)) { (x, y) ->
val (x2, y2) = velocity.next()
Coord((x + x2) to (y + y2))
}
.takeWhile { targetArea.within(it) || !targetArea.outOfBounds(it) }
.toList()
}
object Part1 {
fun run() {
val paths = (0..100).flatMap { x ->
(0..100).map { y ->
(x to y) to fire(x, y)
}
}
.filter { (_, path) -> targetArea.within(path.last()) }
.sortedBy { (_, path) -> path.maxByOrNull { it.y }!!.y }
println(paths.maxOf { (_, path) -> path.maxOf{ it.y } })
targetArea.draw(fire(23, 84))
}
}
object Part2 {
fun run() {
val paths = (20..300).flatMap { x ->
(-100..100).map { y ->
(x to y) to fire(x, y)
}
}
.filter { (_, path) -> targetArea.within(path.last()) }
.map {(velocity, _) -> velocity}
println(paths.size)
}
}
}
fun main() {
Day17.Part1.run()
Day17.Part2.run()
} | [
{
"class_path": "andrewrlee__adventOfCode2021__aace0fc/Day17.class",
"javap": "Compiled from \"Day17.kt\"\npublic final class Day17 {\n public static final Day17 INSTANCE;\n\n private static final kotlin.Pair<kotlin.ranges.IntRange, kotlin.ranges.IntRange> targetArea;\n\n private Day17();\n Code:\n ... |
andrewrlee__adventOfCode2021__aace0fc/src/main/kotlin/Day11.kt | import java.io.File
import java.nio.charset.Charset.defaultCharset
import kotlin.streams.toList
typealias OctopusGrid = Map<Pair<Int, Int>, Day11.Octopus>
object Day11 {
private fun toCoordinates(row: Int, line: String) = line.chars()
.map(Character::getNumericValue)
.toList()
.mapIndexed { col, value -> (row to col) to Octopus((row to col), value) }
val octopusGrid = {
File("day11/input-Day11.kt.txt")
.readLines(defaultCharset())
.mapIndexed(::toCoordinates)
.flatten()
.associate { it }
}
data class Octopus(var coord: Pair<Int, Int>, var score: Int, var hasFlashed: Boolean = false) {
fun increment() = score++
private fun needsToFlash() = score > 9 && !hasFlashed
private fun flash() {
hasFlashed = true
}
fun reset() = if (hasFlashed) {
hasFlashed = false; score = 0; 1
} else 0
private fun getNeighbours(
validCells: OctopusGrid,
deltas: List<Pair<Int, Int>> = listOf(
-1 to 0, 0 to -1,
1 to 0, 0 to 1,
-1 to -1, 1 to 1,
-1 to 1, 1 to -1
)
) = deltas.asSequence()
.map { (x2, y2) -> coord.first + x2 to coord.second + y2 }
.mapNotNull { validCells[it] }
fun check(grid: OctopusGrid) {
if (this.needsToFlash()) {
this.flash()
this.getNeighbours(grid).forEach { it.increment(); it.check(grid) }
}
}
}
private fun OctopusGrid.step(): Int {
this.values.forEach { it.increment() }
this.values.forEach { oct -> oct.check(this) }
return this.values.sumOf { it.reset() }
}
object Part1 {
fun run() {
val grid = octopusGrid()
val count = (0..99).map { grid.step() }.sum()
println(count)
}
}
object Part2 {
private fun OctopusGrid.isNotComplete(): Boolean {
val flashCount = this.step()
return flashCount != this.size
}
fun run() {
val grid = octopusGrid()
var count = 0
do {
count++
} while (grid.isNotComplete())
println(count)
}
}
}
fun main() {
Day11.Part1.run()
Day11.Part2.run()
} | [
{
"class_path": "andrewrlee__adventOfCode2021__aace0fc/Day11$Part1.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class Day11$Part1 {\n public static final Day11$Part1 INSTANCE;\n\n private Day11$Part1();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java... |
andrewrlee__adventOfCode2021__aace0fc/src/main/kotlin/Day13.kt | import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
object Day13 {
data class Coord(val x: Int, val y: Int) {
constructor(coord: Pair<Int, Int>) : this(coord.first, coord.second)
}
enum class Direction {
x {
override fun extract(c: Coord) = c.x
override fun adjust(c: Coord, value: Int) = Coord((c.x - (c.x - value) * 2) to c.y)
},
y {
override fun extract(c: Coord) = c.y
override fun adjust(c: Coord, value: Int) = Coord(c.x to (c.y - (c.y - value) * 2))
};
abstract fun extract(coord: Coord): Int
abstract fun adjust(coord: Coord, value: Int): Coord
}
private fun toCoordinates(line: String) = line
.split(",".toRegex())
.map(Integer::parseInt)
.let { Coord(it[0] to it[1]) }
private fun toInstructions(line: String): Pair<Direction, Int> {
val (axis, value) = "fold along (.)=(.+)".toRegex().find(line)!!.destructured
return Direction.valueOf(axis) to Integer.parseInt(value)
}
private fun fold(instruction: Pair<Direction, Int>, coordinates: Collection<Coord>): Set<Coord> {
val (top, bottom) = coordinates.partition { instruction.first.extract(it) > instruction.second }
val adjusted = top.map { instruction.first.adjust(it, instruction.second) }
return bottom.toMutableSet() + adjusted
}
private fun draw(coordinates: Collection<Coord>) {
println("\n")
println("Contains: ${coordinates.size}")
val maxCols = coordinates.maxOf { it.x }
val maxRows = coordinates.maxOf { it.y }
(0..maxRows).forEach { row ->
(0..maxCols).forEach { col ->
print(if (coordinates.contains(Coord(col, row))) "#" else ".")
}
println()
}
}
object Part1 {
fun run() {
val (instr, coords) = File("day13/input-real.txt")
.readLines(UTF_8)
.partition { it.startsWith("fold along") }
val coordinates = coords.filter { it.isNotBlank() }.map(::toCoordinates)
val instructions = instr.map(::toInstructions)
val first = fold(instructions.first(), coordinates)
println(first.size)
}
}
object Part2 {
fun run() {
val (instr, coords) = File("day13/input-real.txt")
.readLines(UTF_8)
.partition { it.startsWith("fold along") }
val coordinates: Collection<Coord> = coords.filter { it.isNotBlank() }.map(::toCoordinates)
val instructions = instr.map(::toInstructions)
val result = instructions.fold(coordinates) { acc, i -> fold(i, acc) }
draw(result)
// L R G P R E C B
}
}
}
fun main() {
Day13.Part1.run()
Day13.Part2.run()
}
| [
{
"class_path": "andrewrlee__adventOfCode2021__aace0fc/Day13.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13 {\n public static final Day13 INSTANCE;\n\n private Day13();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":... |
andrewrlee__adventOfCode2021__aace0fc/src/main/kotlin/Day09.kt | import java.io.File
import java.nio.charset.Charset.defaultCharset
import kotlin.streams.toList
typealias Coordinate = Pair<Int, Int>
typealias Basin = Set<Coordinate>
typealias ValidCells = Set<Coordinate>
object Day09 {
fun toCoordinates(row: Int, line: String) = line.chars()
.map(Character::getNumericValue)
.toList()
.mapIndexed { col, value -> (row to col) to value }
fun getSurroundingCoordinates(
validCells: ValidCells,
coord: Coordinate,
seenCoordinates: HashSet<Coordinate>,
deltas: List<Pair<Int, Int>> = listOf(0 to 1, 1 to 0, 0 to -1, -1 to 0)
) = deltas.asSequence()
.map { (x2, y2) -> coord.first + x2 to coord.second + y2 }
.filter { validCells.contains(it) }
.filter { !seenCoordinates.contains(it) }
fun findBasin(validCells: ValidCells, coordinate: Coordinate, seenCoordinates: HashSet<Coordinate>): Basin? {
if (seenCoordinates.contains(coordinate)) return null
seenCoordinates.add(coordinate)
val basin = mutableSetOf(coordinate)
getSurroundingCoordinates(validCells, coordinate, seenCoordinates)
.filter { !seenCoordinates.contains(it) }
.map { findBasin(validCells, it, seenCoordinates) }
.filterNotNull()
.forEach { basin.addAll(it) }
return basin
}
fun run() {
val file = File("day09/input-real.txt")
val cells = file.readLines(defaultCharset())
.mapIndexed(::toCoordinates)
.flatten()
val (highs, unseen) = cells.partition { it.second == 9 }
val validCells = cells.map { it.first }.toSet()
val seenCoordinates = highs.map { it.first }.toHashSet()
val toCheck = unseen.map { it.first }
val basins = toCheck.fold(mutableListOf<Basin>()) { basins, coordinate ->
findBasin(validCells, coordinate, seenCoordinates)?.let { basins.add(it) }
basins
}
val result = basins.map { it.size }.sortedDescending().take(3).reduce(Int::times)
println(result)
}
}
fun main() {
Day09.run()
} | [
{
"class_path": "andrewrlee__adventOfCode2021__aace0fc/Day09.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class Day09 {\n public static final Day09 INSTANCE;\n\n private Day09();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":... |
daily-boj__RanolP__74294a4/P2529.kt | enum class InequationType {
LT, // <
GT, // >
KT, // Nothing
}
data class Minmax(val min: Long, val max: Long)
fun solve(previous: Int, choice: Long, seq: List<InequationType>, available: Set<Int>): Minmax {
var min = 9999999999L
var max = 0L
if (seq.isEmpty()) {
return Minmax(choice, choice)
}
for (i in available) {
val canUse = when (seq[0]) {
InequationType.KT -> true
InequationType.LT -> previous < i
InequationType.GT -> previous > i
}
if (!canUse) {
continue
}
val result = solve(i, choice * 10 + i, seq.subList(1, seq.size), available - i)
min = minOf(min, result.min)
max = maxOf(max, result.max)
}
return Minmax(min, max)
}
fun main(args: Array<out String>) {
val k = readLine()!!.toInt()
val a = listOf(InequationType.KT) + readLine()!!.split(' ')
.asSequence()
.filter { it.isNotEmpty() }
.map { if (it == "<") InequationType.LT else InequationType.GT }
.toList()
val (min, max) = solve(0, 0L, a, (0..9).toSet())
println(max.toString().padStart(k + 1, '0'))
println(min.toString().padStart(k + 1, '0'))
} | [
{
"class_path": "daily-boj__RanolP__74294a4/P2529Kt$WhenMappings.class",
"javap": "Compiled from \"P2529.kt\"\npublic final class P2529Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method InequationType.values:... |
daily-boj__RanolP__74294a4/16117/solution.kt | fun main(args: Array<out String>) {
val (height, width) = readLine()!!.split(" ").map { it.toInt() }
val realMap = List(height * 2) {
if (it % 2 == 0) {
List(width * 2) { 0L }
} else {
readLine()!!.split(" ").flatMap { listOf(0L, it.toLong()) }
}
}
fun getSafe(map: List<List<Long>>, x: Int, y: Int): Long =
if (y in 0 until 2 * height && x in 0 until 2 * width) map[y][x]
else 0
val intDP = List(height * 2) {
MutableList(width * 2) { 0L }
}
for (x in (0 until width * 2).reversed()) {
for (y in (0 until height * 2).reversed()) {
val here = realMap[y][x]
val best = maxOf(
getSafe(realMap, x + 1, y - 1) + getSafe(intDP, x + 2, y - 2),
getSafe(realMap, x + 2, y) + getSafe(intDP, x + 4, y),
getSafe(realMap, x + 1, y + 1) + getSafe(intDP, x + 2, y + 2)
)
intDP[y][x] = here + best
}
}
val max = (0 until height * 2).fold(0L) { acc, y -> maxOf(acc, getSafe(intDP, 0, y), getSafe(intDP, 1, y)) }
println(max)
}
| [
{
"class_path": "daily-boj__RanolP__74294a4/SolutionKt.class",
"javap": "Compiled from \"solution.kt\"\npublic final class SolutionKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic #15... |
daily-boj__RanolP__74294a4/P9735.kt | import kotlin.math.*
data class QuadraticEquation(val a: Long, val b: Long, val c: Long) {
fun solve(): Set<Double> {
val discriminant = b.toDouble() * b.toDouble() - 4.0 * a.toDouble() * c.toDouble()
if (discriminant < 0) {
return emptySet()
}
val sqrtedDiscriminant = sqrt(discriminant)
return setOf((-b + sqrtedDiscriminant) / 2 / a, (-b - sqrtedDiscriminant) / 2 / a)
}
}
fun syntheticDivision(a: Long, b: Long, c: Long, d: Long): Set<Double> {
if (d == 0L) {
return setOf(0.0) + QuadraticEquation(a, b, c).solve()
}
for (i in 1..sqrt(abs(d.toDouble())).toLong()) {
if (d % i != 0L) {
continue
}
for (e in listOf(i, -i, d / i, -d / i)) {
val newA = a
val newB = e * newA + b
val newC = e * newB + c
val newD = e * newC + d
if (newD == 0L) {
return setOf(e.toDouble()) + QuadraticEquation(newA, newB, newC).solve()
}
}
}
return emptySet()
}
fun gcd(a: Long, b: Long): Long =
if (b == 0L) a
else gcd(b, a % b)
fun main(args: Array<out String>) {
(0 until readLine()!!.toLong()).joinToString("\n") {
val (a, b, c, d) = readLine()!!.split(" ").map { it.toLong() }
syntheticDivision(a, b, c, d).toList().sorted().joinToString(" ") { String.format("%f", it) }
}.let(::println)
} | [
{
"class_path": "daily-boj__RanolP__74294a4/P9735Kt.class",
"javap": "Compiled from \"P9735.kt\"\npublic final class P9735Kt {\n public static final java.util.Set<java.lang.Double> syntheticDivision(long, long, long, long);\n Code:\n 0: lload 6\n 2: lconst_0\n 3: lcmp\n 4... |
lmisea__lab-algos-2__948a9e5/proyecto-1/codigo/VerificadorTSP.kt | /**
* Verificador de soluciones para el problema del vendedor viajero
* Recibe como argumentos el archivo de instancia y el archivo de solucion
* Imprime si la solucion es correcta o no y muestra algunos errores si los hay
*/
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
/**
* Funcion: distancia2D(p1: Pair<Int, Int>, p2: Pair<Int, Int>)
* Entradas: p1 y p2, dos pares de enteros que representan las coordenadas de dos puntos
* Salidas: La distancia euclidiana entre los dos puntos
* Descripcion: Calcula la distancia euclidiana entre dos puntos en el plano
*/
fun distancia2D(p1: Pair<Double, Double>, p2: Pair<Double, Double>): Double {
val x = p1.first - p2.first
val y = p1.second - p2.second
return Math.sqrt((x * x + y * y).toDouble())
}
/**
* Funcion: distanciaRuta(ciudades: Array<Pair<Int, Int>>)
* Entradas: ciudades, un arreglo de pares de enteros que representan las coordenadas de las ciudades
* Salidas: La distancia total de la ruta que recorre todas las ciudades en el orden dado
* Descripcion: Calcula la distancia total de la ruta que recorre todas las ciudades en el orden dado
*/
fun distanciaRuta(ciudades: Array<Pair<Double, Double>>): Int {
var acc: Double = 0.0
for (i in 0 until ciudades.size - 1) {
acc += distancia2D(ciudades[i], ciudades[i + 1])
}
return acc.toInt()
}
/**
* Funcion: checkSolution(ciudadesInstancia: Array<Pair<Int, Int>>, ciudadesSolucion: Array<Pair<Int, Int>>)
* Entradas: ciudadesInstancia, un arreglo de pares de enteros que representan las coordenadas de las ciudades de la instancia
* ciudadesSolucion, un arreglo de pares de enteros que representan las coordenadas de las ciudades de la solucion
* Salidas: true si la solucion es correcta, false en otro caso
* Descripcion: Verifica que la solucion dada sea correcta
*/
fun checkSolution(indicesInstancia: Array<Int>, indicesSolucion: Array<Int>): Boolean {
// Verificar que la solucion tenga todas las ciudades de la instancia
for (i in 0 until indicesInstancia.size) {
if (!indicesInstancia.contains(indicesSolucion[i])) {
println("La solución no contiene la ciudad ${indicesSolucion[i] + 1}.")
return false
}
}
// Verificar que la solucion no tenga ciudades repetidas
for (i in 0 until indicesSolucion.size) {
for (j in i + 1 until indicesSolucion.size) {
if (indicesSolucion[i] == indicesSolucion[j]) {
println("La solución tiene la ciudad ${indicesSolucion[i] + 1} repetida.")
return false
}
}
}
return true
}
/**
* Funcion: ciudadesFaltantes(ciudadesInstancia: Array<Pair<Int, Int>>, ciudadesSolucion: Array<Pair<Int, Int>>)
* Entradas: indicesInstancia, un arreglo de pares de enteros que representan las coordenadas de las ciudades de la instancia
* indicesSolucion, un arreglo de pares de enteros que representan las coordenadas de las ciudades de la solucion
* Salidas: Imprime (en caso de que sea necesario) las ciudades que faltan en la solucion
*/
fun ciudadesFaltantes(indicesInstancia: Array<Int>, indicesSolucion: Array<Int>){
for (i in 0 until indicesSolucion.size){
if (!indicesInstancia.contains(indicesSolucion[i])){
println("La ciudad ${indicesSolucion[i]+1} no se encuentra en la instancia")
}
}
}
fun main(args: Array<String>) {
// args[0] es el archivo de instancia
// args[1] es el archivo de solucion
val archivoInstancia = File(args[0])
val archivoSolucion = File(args[1])
// Leer las ciudades de la instancia
val lectorInstancia = BufferedReader(FileReader(archivoInstancia, Charsets.UTF_8))
lectorInstancia.readLine() // Ignorar primera linea. Es el nombre del archivo
lectorInstancia.readLine() // Ignorar segunda linea. Es el comentario
val numeroCiudadesInstancia = lectorInstancia.readLine().split(":")[1].trim().toInt()
lectorInstancia.readLine() // Ignorar linea. Es el comentario
val indicesInstancia = Array<Int>(numeroCiudadesInstancia, { 0 })
for (i in 0 until numeroCiudadesInstancia) {
val indice = lectorInstancia.readLine().trim().toInt()
indicesInstancia[i] = indice - 1
}
lectorInstancia.close()
// Leer las ciudades de la solucion
val lectorSolucion = BufferedReader(FileReader(archivoSolucion, Charsets.UTF_8))
lectorSolucion.readLine() // Ignorar primera linea. Es el nombre del archivo
lectorSolucion.readLine() // Ignorar segunda linea. Es el comentario
val numeroCiudadesSolucion = lectorSolucion.readLine().split(":")[1].trim().toInt()
lectorSolucion.readLine() // Ignorar linea. Es el comentario
val indicesSolucion = Array<Int>(numeroCiudadesSolucion, { 0 })
for (i in 0 until numeroCiudadesSolucion) {
val indice = lectorSolucion.readLine().trim().toInt()
indicesSolucion[i] = indice-1
}
lectorSolucion.close()
// Verificar que la solucion sea correcta
if (!checkSolution(indicesInstancia, indicesSolucion)) {
// Si la solucion no es correcta, terminar el programa
println("Solución incorrecta!!")
ciudadesFaltantes(indicesInstancia, indicesSolucion)
return
}
println("Es una solución correcta!!")
println("Se visitaron todas las ciudades de la instancia, solo una vez cada una.")
} | [
{
"class_path": "lmisea__lab-algos-2__948a9e5/VerificadorTSPKt.class",
"javap": "Compiled from \"VerificadorTSP.kt\"\npublic final class VerificadorTSPKt {\n public static final double distancia2D(kotlin.Pair<java.lang.Double, java.lang.Double>, kotlin.Pair<java.lang.Double, java.lang.Double>);\n Code:\... |
lmisea__lab-algos-2__948a9e5/parcial-1-Juan/AsignarCupo.kt | fun swapDual(A: Array<Int>, B: Array<Int>, i: Int, j: Int): Unit {
val aux: Int = A[i]
A[i] = A[j]
A[j] = aux
val temp: Int = B[i]
B[i] = B[j]
B[j] = temp
}
fun compararEstudiantes(A: Array<Int>, B: Array<Int>, i: Int, j: Int): Boolean{
return A[i] < A[j] || (A[i] == A[j] && B[i] <= B[j])
}
fun parent(i: Int): Int {
return i / 2
}
fun left(i: Int): Int {
return 2 * i
}
fun right(i: Int): Int {
return 2 * i + 1
}
fun maxHeapify(A: Array<Int>, B: Array<Int>, i: Int, heapSize: Int): Unit {
val l: Int = left(i)
val r: Int = right(i)
var largest: Int = i
if (l <= heapSize && compararEstudiantes(A, B, i, l)) {
largest = l
}
if (r <= heapSize && compararEstudiantes(A, B, largest, r)) {
largest = r
}
if (largest != i) {
swapDual(A, B, i, largest)
maxHeapify(A, B, largest, heapSize)
}
}
fun buildMaxHeap(A: Array<Int>, B: Array<Int>, heapSize: Int): Unit {
for (i in heapSize / 2 downTo 0) {
maxHeapify(A, B, i, heapSize)
}
}
fun heapSort(A: Array<Int>, B: Array<Int>): Unit {
val heapSize: Int = A.size - 1
buildMaxHeap(A, B, heapSize)
for (i in heapSize downTo 1) {
swapDual(A, B, 0, i)
maxHeapify(A, B, 0, i - 1)
}
}
fun main(args: Array<String>) {
val cupos = args[0].toInt()
if (cupos < 0){
throw Exception("El número de cupos debe ser positivo")
}
else if (cupos == 0){
println("NO HAY CUPOS")
return
}
if ((args.size)%2 != 1){
throw Exception("Falta un estudiante por NFC o carnet")
}
val numeroEstudiantes = (args.size - 1)/2
if (cupos >= numeroEstudiantes){
println("TODOS FUERON ADMITIDOS")
return
}
val carnets: Array<Int> = Array(numeroEstudiantes){0}
val NCFs: Array<Int> = Array(numeroEstudiantes){0}
for (i in 0 until numeroEstudiantes){
carnets[i] = args[i*2 + 1].toInt()
NCFs[i] = args[i*2 + 2].toInt()
}
heapSort(NCFs, carnets)
for (i in 0 until cupos){
println(carnets[i])
}
} | [
{
"class_path": "lmisea__lab-algos-2__948a9e5/AsignarCupoKt.class",
"javap": "Compiled from \"AsignarCupo.kt\"\npublic final class AsignarCupoKt {\n public static final void swapDual(java.lang.Integer[], java.lang.Integer[], int, int);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
mr-kaffee__aoc-2022-kotlin__313432b/src/Day01.kt | import java.io.File
fun main() {
fun part1(elves: List<Int>): Int {
return elves.fold(0) { mx, calories -> maxOf(mx, calories) }
}
fun part2(elves: List<Int>): Int {
return elves.fold(mutableListOf(0, 0, 0)) { mx, calories ->
if (calories > mx[0]) {
mx[2] = mx[1]
mx[1] = mx[0]
mx[0] = calories
} else if (calories > mx[1]) {
mx[2] = mx[1]
mx[1] = calories
} else if (calories > mx[2]) {
mx[2] = calories
}
mx
}.sum()
}
val t0 = System.currentTimeMillis()
// input parsing
val input = File("src", "Day01.txt").readText()
val elves = input
.trim().split("\n\n")
.map { elf -> elf.lines().sumOf { line -> line.toInt() } }
.toList()
val tParse = System.currentTimeMillis()
// part 1
val exp1 = 67658
val sol1 = part1(elves)
val t1 = System.currentTimeMillis()
check(sol1 == exp1) { "Expected solution for part 1: $exp1, found $sol1" }
// part 2
val exp2 = 200158
val sol2 = part2(elves)
val t2 = System.currentTimeMillis()
check(sol2 == exp2) { "Expected solution for part 1: $exp2, found $sol2" }
// results
println("Solved puzzle 2022/01")
println(" parsed input in ${tParse - t0}ms")
println(" solved part 1 in ${t1 - tParse}ms => $sol1")
println(" solved part 2 in ${t2 - t1}ms => $sol2")
println(" ---")
println(" total time: ${t2 - t0}ms")
}
| [
{
"class_path": "mr-kaffee__aoc-2022-kotlin__313432b/Day01Kt.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: invokestatic #12 // Method java/lang/System.currentTimeMillis:()J\n 3: lstore_0\n 4: ... |
ambrosil__aoc-2022__ebaacfc/src/Utils.kt | import java.io.File
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
fun String.allInts() = allIntsInString(this)
fun allIntsInString(line: String): List<Int> {
return """-?\d+""".toRegex().findAll(line)
.map { it.value.toInt() }
.toList()
}
fun <T> List<T>.nth(n: Int): T =
this[n % size]
inline fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): Int {
for (i in this.indices.reversed()) {
if (predicate(this[i])) {
return i
}
}
return -1
}
data class Point(var x: Int = 0, var y: Int = 0) {
operator fun plus(other: Point): Point {
return Point(this.x + other.x, this.y + other.y)
}
fun adjacents(): Set<Point> =
setOf(
copy(x = x - 1),
copy(x = x + 1),
copy(y = y - 1),
copy(y = y + 1)
)
fun set(x: Int, y: Int) {
this.x = x
this.y = y
}
operator fun plusAssign(p: Point) {
x += p.x
y += p.y
}
operator fun minus(point: Point): Point {
return Point(x + point.x, y - point.y)
}
}
inline fun List<List<Char>>.forEach(block: (row: Int, col: Int) -> Unit) {
for (i in indices) {
val inner = this[i]
for (j in inner.indices) {
block(i, j)
}
}
}
fun List<List<Char>>.maxOf(block: (row: Int, col: Int) -> Int): Int {
var max = 0
forEach { row, col ->
val value = block(row, col)
max = if (value > max) value else max
}
return max
}
fun List<List<Char>>.count(block: (row: Int, col: Int) -> Boolean): Int {
var count = 0
forEach { row, col ->
count += if (block(row, col)) 1 else 0
}
return count
} | [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/UtilsKt.class",
"javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String name\n ... |
ambrosil__aoc-2022__ebaacfc/src/Day14.kt | import Type.*
enum class Type { NONE, SAND, WALL }
fun main() {
fun parse(input: List<String>): MutableMap<Point, Type> {
val terrain = mutableMapOf<Point, Type>()
val walls = input.map { it.split(" -> ")
.map { it.split(",") }
.map { (x, y) -> Point(x.toInt(), y.toInt()) }
}
walls.forEach { wall ->
wall.reduce { p1, p2 ->
val xRange = if (p1.x > p2.x) {
p2.x..p1.x
} else {
p1.x..p2.x
}
val yRange = if (p1.y > p2.y) {
p2.y..p1.y
} else {
p1.y..p2.y
}
for (x in xRange) {
terrain[Point(x, p1.y)] = WALL
}
for (y in yRange) {
terrain[Point(p1.x, y)] = WALL
}
p2
}
}
return terrain
}
fun findMaxY(terrain: MutableMap<Point, Type>): Int {
return terrain.keys.maxOf { it.y }
}
fun addSand(terrain: MutableMap<Point, Type>): Boolean {
val maxY = findMaxY(terrain)
val sandPoint = Point(500, 0)
while (true) {
sandPoint += Point(0, 1)
if (sandPoint.y > maxY) {
return false
}
val type = terrain[sandPoint] ?: NONE
when (type) {
NONE -> continue
SAND, WALL -> {
val leftType = terrain[sandPoint + Point(-1, 0)] ?: NONE
when (leftType) {
NONE -> sandPoint += Point(-1, 0)
WALL, SAND -> {
val rightType = terrain[sandPoint + Point(+1, 0)] ?: NONE
if (rightType == NONE) {
sandPoint += Point(+1, 0)
} else {
terrain[sandPoint + Point(0, -1)] = SAND
return true
}
}
}
}
}
}
}
fun addSand2(terrain: MutableMap<Point, Type>, maxY: Int): Boolean {
val sandPoint = Point(500, 0)
while (true) {
sandPoint += Point(0, 1)
if (sandPoint.y >= maxY+2) {
terrain[sandPoint + Point(0, -1)] = SAND
return true
}
val type = terrain[sandPoint] ?: NONE
when (type) {
NONE -> continue
SAND, WALL -> {
val leftType = terrain[sandPoint + Point(-1, 0)] ?: NONE
when (leftType) {
NONE -> sandPoint += Point(-1, 0)
WALL, SAND -> {
val rightType = terrain[sandPoint + Point(+1, 0)] ?: NONE
if (rightType == NONE) {
sandPoint += Point(+1, 0)
} else {
val restPoint = sandPoint + Point(0, -1)
terrain[restPoint] = SAND
if (restPoint.x == 500 && restPoint.y == 0) {
return false
}
return true
}
}
}
}
}
}
}
fun part1(input: List<String>): Int {
val terrain = parse(input)
var counter = 0
while (addSand(terrain)) {
counter++
}
return counter
}
fun part2(input: List<String>): Int {
val terrain = parse(input)
val maxY = findMaxY(terrain)
var counter = 0
while (addSand2(terrain, maxY)) {
counter++
}
return counter+1
}
val input = readInput("inputs/Day14")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day14Kt.class",
"javap": "Compiled from \"Day14.kt\"\npublic final class Day14Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day14\n 2: invokestatic #14 // Method UtilsKt.re... |
ambrosil__aoc-2022__ebaacfc/src/Day04.kt | fun main() {
fun part1(input: List<String>) =
input
.readRanges()
.count { (first, second) ->
first contains second || second contains first
}
fun part2(input: List<String>) =
input
.readRanges()
.count { (first, second) ->
first overlaps second
}
val input = readInput("inputs/Day04")
println(part1(input))
println(part2(input))
}
fun List<String>.readRanges() =
this.map {
it.split(",").map { s ->
val (start, end) = s.split("-")
start.toInt()..end.toInt()
}
}
infix fun IntRange.contains(second: IntRange) = this.first <= second.first && this.last >= second.last
infix fun IntRange.overlaps(second: IntRange) = (this intersect second).isNotEmpty()
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day04\n 2: invokestatic #14 // Method UtilsKt.re... |
ambrosil__aoc-2022__ebaacfc/src/Day12.kt | fun main() {
class Terrain constructor(input: List<String>) {
val distances: HashMap<Point, Int> = HashMap()
var queue: ArrayDeque<Point> = ArrayDeque()
var heightmap: List<List<Char>> = input.map { it.toList() }
fun enqueue(point: Point, distance: Int) {
if (distances[point] == null || distances[point]!! > distance) {
queue += point
distances[point] = distance
}
}
fun find(c: Char): Point {
heightmap.forEach { x, y ->
if (heightmap[x][y] == c) {
return Point(x, y)
}
}
error("Not found $c")
}
fun height(point: Point): Int {
val height = heightmap[point.x][point.y]
return when (height) {
'S' -> 0
'E' -> 'z' - 'a'
else -> height - 'a'
}
}
fun minSteps(start: Point, end: Point): Int {
enqueue(start, 0)
while (queue.isNotEmpty()) {
val point = queue.removeFirst()
val distance = distances[point]!! + 1
val height = height(point)
walk(Point(point.x-1, point.y), distance, height)
walk(Point(point.x+1, point.y), distance, height)
walk(Point(point.x, point.y-1), distance, height)
walk(Point(point.x, point.y+1), distance, height)
}
return distances[end] ?: Int.MAX_VALUE
}
fun walk(p: Point, distance: Int, height: Int) {
if (p.x !in heightmap.indices || p.y !in 0 until heightmap[0].size) return
if (height <= height(p) + 1) {
enqueue(p, distance)
}
}
}
fun part1(input: List<String>): Int {
val terrain = Terrain(input)
val start = terrain.find('E')
val end = terrain.find('S')
return terrain.minSteps(start, end)
}
fun part2(input: List<String>): Int {
val endingPoints = mutableListOf<Point>()
val terrain = Terrain(input)
terrain.heightmap
.forEach { x, y ->
val c = terrain.heightmap[x][y]
if (c == 'a' || c == 'S') {
endingPoints += Point(x, y)
}
}
val start = terrain.find('E')
terrain.minSteps(start, endingPoints[0])
return endingPoints.minOf { terrain.distances[it] ?: Int.MAX_VALUE }
}
val input = readInput("inputs/Day12")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day12Kt$main$Terrain.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class Day12Kt$main$Terrain {\n private final java.util.HashMap<Point, java.lang.Integer> distances;\n\n private kotlin.collections.ArrayDeque<Point> queue;\n\n private java.util.Li... |
ambrosil__aoc-2022__ebaacfc/src/Day16.kt | fun main() {
val day16 = Day16(readInput("inputs/Day16"))
println(day16.part1())
println(day16.part2())
}
class Day16(input: List<String>) {
private val valves = input.map(Valve::from).associateBy(Valve::name)
private val usefulValves = valves.filter { it.value.rate > 0 }
private val distances = computeDistances()
fun part1() = traverse(minutes = 30)
fun part2() = traverse(minutes = 26, elephantGoesNext = true)
private fun traverse(
minutes: Int,
current: Valve = valves.getValue("AA"),
remaining: Set<Valve> = usefulValves.values.toSet(),
cache: MutableMap<State, Int> = mutableMapOf(),
elephantGoesNext: Boolean = false
): Int {
val currentScore = minutes * current.rate
val currentState = State(current.name, minutes, remaining)
return currentScore + cache.getOrPut(currentState) {
val validValves = remaining.filter { next -> distances[current.name]!![next.name]!! < minutes }
var maxCurrent = 0
if (validValves.isNotEmpty()) {
maxCurrent = validValves.maxOf { next ->
val remainingMinutes = minutes - 1 - distances[current.name]!![next.name]!!
traverse(remainingMinutes, next, remaining - next, cache, elephantGoesNext)
}
}
maxOf(maxCurrent, if (elephantGoesNext) traverse(minutes = 26, remaining = remaining) else 0)
}
}
private fun computeDistances(): Map<String, Map<String, Int>> {
return valves.keys.map { valve ->
val distances = mutableMapOf<String, Int>().withDefault { Int.MAX_VALUE }.apply { put(valve, 0) }
val toVisit = mutableListOf(valve)
while (toVisit.isNotEmpty()) {
val current = toVisit.removeFirst()
valves[current]!!.next.forEach { adj ->
val newDistance = distances[current]!! + 1
if (newDistance < distances.getValue(adj)) {
distances[adj] = newDistance
toVisit.add(adj)
}
}
}
distances
}.associateBy { it.keys.first() }
}
private data class State(val current: String, val minutes: Int, val opened: Set<Valve>)
private data class Valve(val name: String, val rate: Int, val next: List<String>) {
companion object {
fun from(line: String): Valve {
return Valve(
name = line.substringAfter("Valve ").substringBefore(" "),
rate = line.substringAfter("rate=").substringBefore(";").toInt(),
next = line.substringAfter("to valve").substringAfter(" ").split(", ")
)
}
}
}
} | [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day16$State.class",
"javap": "Compiled from \"Day16.kt\"\nfinal class Day16$State {\n private final java.lang.String current;\n\n private final int minutes;\n\n private final java.util.Set<Day16$Valve> opened;\n\n public Day16$State(java.lang.String, int, jav... |
ambrosil__aoc-2022__ebaacfc/src/Day22.kt | fun main() {
val d = Day22(readInput("inputs/Day22"))
println(d.part1())
println(d.part2())
}
class Day22(input: List<String>) {
private val blockedPlaces: Set<Point> = parseBlockedPlaces(input)
private val instructions: List<Instruction> = Instruction.ofList(input)
fun part1(): Int =
followInstructions(CubeFacing(1)).score()
fun part2(): Int =
followInstructions(CubeFacing(11)).score()
private fun followInstructions(startingCube: CubeFacing): Orientation {
var cube = startingCube
var orientation = Orientation(cube.topLeft, Facing.East)
instructions.forEach { instruction ->
when (instruction) {
is Left -> orientation = orientation.copy(facing = orientation.facing.left)
is Right -> orientation = orientation.copy(facing = orientation.facing.right)
is Move -> {
var keepMoving = true
repeat(instruction.steps) {
if (keepMoving) {
var nextOrientation = orientation.move()
var nextCube = cube
if (nextOrientation.location !in cube) {
with(cube.transition(orientation.facing)) {
nextOrientation = Orientation(move(orientation.location), enter)
nextCube = destination
}
}
if (nextOrientation.location in blockedPlaces) {
keepMoving = false
} else {
orientation = nextOrientation
cube = nextCube
}
}
}
}
}
}
return orientation
}
private fun parseBlockedPlaces(input: List<String>): Set<Point> =
input
.takeWhile { it.isNotBlank() }
.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, c ->
if (c == '#') Point(x, y) else null
}
}.toSet()
private data class Orientation(val location: Point, val facing: Facing) {
fun score(): Int =
(1000 * (location.y + 1)) + (4 * (location.x + 1)) + facing.points
fun move(): Orientation =
copy(location = location + facing.offset)
}
private sealed class Instruction {
companion object {
fun ofList(input: List<String>): List<Instruction> =
input
.dropWhile { it.isNotBlank() }
.drop(1)
.first()
.trim()
.let { """\d+|[LR]""".toRegex().findAll(it) }
.map { it.value }
.filter { it.isNotBlank() }
.map { symbol ->
when (symbol) {
"L" -> Left
"R" -> Right
else -> Move(symbol.toInt())
}
}.toList()
}
}
private class Move(val steps: Int) : Instruction()
private object Left : Instruction()
private object Right : Instruction()
sealed class Facing(val points: Int, val offset: Point) {
abstract val left: Facing
abstract val right: Facing
object North : Facing(3, Point(0, -1)) {
override val left = West
override val right = East
}
object East : Facing(0, Point(1, 0)) {
override val left = North
override val right = South
}
object South : Facing(1, Point(0, 1)) {
override val left = East
override val right = West
}
object West : Facing(2, Point(-1, 0)) {
override val left = South
override val right = North
}
}
class CubeFacing(
val id: Int,
val size: Int,
val topLeft: Point,
val north: Transition,
val east: Transition,
val south: Transition,
val west: Transition
) {
val minX: Int = topLeft.x
val maxX: Int = topLeft.x + size - 1
val minY: Int = topLeft.y
val maxY: Int = topLeft.y + size - 1
operator fun contains(place: Point): Boolean =
place.x in (minX..maxX) && place.y in (minY..maxY)
fun scaleDown(point: Point): Point =
point - topLeft
fun scaleUp(point: Point): Point =
point + topLeft
fun transition(direction: Facing): Transition =
when (direction) {
Facing.North -> north
Facing.East -> east
Facing.South -> south
Facing.West -> west
}
companion object {
private val instances = mutableMapOf<Int, CubeFacing>()
operator fun invoke(id: Int): CubeFacing =
instances.getValue(id)
private operator fun plus(instance: CubeFacing) {
instances[instance.id] = instance
}
init {
CubeFacing + CubeFacing(
id = 1,
size = 50,
topLeft = Point(50, 0),
north = Transition(1, 5, Facing.North, Facing.North),
east = Transition(1, 2, Facing.East, Facing.East),
south = Transition(1, 3, Facing.South, Facing.South),
west = Transition(1, 2, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 2,
size = 50,
topLeft = Point(100, 0),
north = Transition(2, 2, Facing.North, Facing.North),
east = Transition(2, 1, Facing.East, Facing.East),
south = Transition(2, 2, Facing.South, Facing.South),
west = Transition(2, 1, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 3,
size = 50,
topLeft = Point(50, 50),
north = Transition(3, 1, Facing.North, Facing.North),
east = Transition(3, 3, Facing.East, Facing.East),
south = Transition(3, 5, Facing.South, Facing.South),
west = Transition(3, 3, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 4,
size = 50,
topLeft = Point(0, 100),
north = Transition(4, 6, Facing.North, Facing.North),
east = Transition(4, 5, Facing.East, Facing.East),
south = Transition(4, 6, Facing.South, Facing.South),
west = Transition(4, 5, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 5,
size = 50,
topLeft = Point(50, 100),
north = Transition(5, 3, Facing.North, Facing.North),
east = Transition(5, 4, Facing.East, Facing.East),
south = Transition(5, 1, Facing.South, Facing.South),
west = Transition(5, 4, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 6,
size = 50,
topLeft = Point(0, 150),
north = Transition(6, 4, Facing.North, Facing.North),
east = Transition(6, 6, Facing.East, Facing.East),
south = Transition(6, 4, Facing.South, Facing.South),
west = Transition(6, 6, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 11,
size = 50,
topLeft = Point(50, 0),
north = Transition(11, 16, Facing.North, Facing.East),
east = Transition(11, 12, Facing.East, Facing.East),
south = Transition(11, 13, Facing.South, Facing.South),
west = Transition(11, 14, Facing.West, Facing.East)
)
CubeFacing + CubeFacing(
id = 12,
size = 50,
topLeft = Point(100, 0),
north = Transition(12, 16, Facing.North, Facing.North),
east = Transition(12, 15, Facing.East, Facing.West),
south = Transition(12, 13, Facing.South, Facing.West),
west = Transition(12, 11, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 13,
size = 50,
topLeft = Point(50, 50),
north = Transition(13, 11, Facing.North, Facing.North),
east = Transition(13, 12, Facing.East, Facing.North),
south = Transition(13, 15, Facing.South, Facing.South),
west = Transition(13, 14, Facing.West, Facing.South)
)
CubeFacing + CubeFacing(
id = 14,
size = 50,
topLeft = Point(0, 100),
north = Transition(14, 13, Facing.North, Facing.East),
east = Transition(14, 15, Facing.East, Facing.East),
south = Transition(14, 16, Facing.South, Facing.South),
west = Transition(14, 11, Facing.West, Facing.East)
)
CubeFacing + CubeFacing(
id = 15,
size = 50,
topLeft = Point(50, 100),
north = Transition(15, 13, Facing.North, Facing.North),
east = Transition(15, 12, Facing.East, Facing.West),
south = Transition(15, 16, Facing.South, Facing.West),
west = Transition(15, 14, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 16,
size = 50,
topLeft = Point(0, 150),
north = Transition(16, 14, Facing.North, Facing.North),
east = Transition(16, 15, Facing.East, Facing.North),
south = Transition(16, 12, Facing.South, Facing.South),
west = Transition(16, 11, Facing.West, Facing.South)
)
}
}
}
data class Transition(val sourceId: Int, val destinationId: Int, val exit: Facing, val enter: Facing) {
private val byDirection = Pair(exit, enter)
private val source: CubeFacing by lazy { CubeFacing(sourceId) }
val destination: CubeFacing by lazy { CubeFacing(destinationId) }
private fun Point.rescale(): Point =
destination.scaleUp(source.scaleDown(this))
private fun Point.flipRescaled(): Point =
destination.scaleUp(source.scaleDown(this).flip())
private fun Point.flip(): Point =
Point(y, x)
fun move(start: Point): Point = when (byDirection) {
Pair(Facing.North, Facing.North) -> Point(start.rescale().x, destination.maxY)
Pair(Facing.East, Facing.East) -> Point(destination.minX, start.rescale().y)
Pair(Facing.West, Facing.West) -> Point(destination.maxX, start.rescale().y)
Pair(Facing.South, Facing.South) -> Point(start.rescale().x, destination.minY)
Pair(Facing.North, Facing.East) -> Point(destination.minX, start.flipRescaled().y)
Pair(Facing.East, Facing.North) -> Point(start.flipRescaled().x, destination.maxY)
Pair(Facing.East, Facing.West) -> Point(destination.maxX, destination.maxY - source.scaleDown(start).y)
Pair(Facing.West, Facing.East) -> Point(destination.minX, destination.maxY - source.scaleDown(start).y)
Pair(Facing.West, Facing.South) -> Point(start.flipRescaled().x, destination.minY)
Pair(Facing.South, Facing.West) -> Point(destination.maxX, start.flipRescaled().y)
else -> throw IllegalStateException("No transition from $exit to $enter")
}
}
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day22Kt.class",
"javap": "Compiled from \"Day22.kt\"\npublic final class Day22Kt {\n public static final void main();\n Code:\n 0: new #8 // class Day22\n 3: dup\n 4: ldc #10 // String inp... |
ambrosil__aoc-2022__ebaacfc/src/Day17.kt | import java.io.File
import kotlin.math.absoluteValue
fun main() {
val day17 = Day17(File("src/inputs/Day17.txt").readText())
println(day17.part1())
println(day17.part2())
}
class Day17(input: String) {
private val jets = jets(input)
private val shapes = shapes()
private val cave = (0..6).map { Point(it, 0) }.toMutableSet()
private val down = Point(0, 1)
private val up = Point(0, -1)
private var jetCounter = 0
private var blockCounter = 0
fun part1(): Int {
repeat(2022) {
simulate()
}
return cave.height()
}
fun part2(): Long =
calculateHeight(1000000000000L - 1)
private fun simulate() {
var currentShape = shapes.nth(blockCounter++).moveToStart(cave.minY())
do {
val jetShape = currentShape * jets.nth(jetCounter++)
if (jetShape in (0..6) && jetShape.intersect(cave).isEmpty()) {
currentShape = jetShape
}
currentShape = currentShape * down
} while (currentShape.intersect(cave).isEmpty())
cave += (currentShape * up)
}
private fun calculateHeight(targetBlockCount: Long): Long {
data class State(val ceiling: List<Int>, val blockIdx: Int, val jetIdx: Int)
val seen: MutableMap<State, Pair<Int, Int>> = mutableMapOf()
while (true) {
simulate()
val state = State(cave.heuristicPrevious(), blockCounter % shapes.size, jetCounter % jets.size)
if (state in seen) {
val (blockCountAtLoopStart, heightAtLoopStart) = seen.getValue(state)
val blocksPerLoop = blockCounter - 1L - blockCountAtLoopStart
val totalLoops = (targetBlockCount - blockCountAtLoopStart) / blocksPerLoop
val remainingBlocks = (targetBlockCount - blockCountAtLoopStart) - (totalLoops * blocksPerLoop)
val heightGainedSinceLoop = cave.height() - heightAtLoopStart
repeat (remainingBlocks.toInt()) {
simulate()
}
return cave.height() + heightGainedSinceLoop * (totalLoops - 1)
}
seen[state] = blockCounter - 1 to cave.height()
}
}
private operator fun IntRange.contains(set: Set<Point>): Boolean = set.all { it.x in this }
private operator fun Set<Point>.times(point: Point): Set<Point> = map { it + point }.toSet()
private fun Set<Point>.minY(): Int = minOf { it.y }
private fun Set<Point>.height(): Int = minY().absoluteValue
private fun Set<Point>.heuristicPrevious(): List<Int> {
return groupBy { it.x }
.map { pointList -> pointList.value.minBy { it.y } }
.let {
val normalTo = minY()
it.map { point -> normalTo - point.y }
}
}
private fun Set<Point>.moveToStart(ceilingHeight: Int): Set<Point> =
map { it + Point(2, ceilingHeight - 4) }.toSet()
private fun shapes(): List<Set<Point>> =
listOf(
setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0)),
setOf(Point(1, 0), Point(0, -1), Point(1, -1), Point(2, -1), Point(1, -2)),
setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, -1), Point(2, -2)),
setOf(Point(0, 0), Point(0, -1), Point(0, -2), Point(0, -3)),
setOf(Point(0, 0), Point(1, 0), Point(0, -1), Point(1, -1))
)
private fun jets(input: String): List<Point> =
input.map {
when (it) {
'>' -> Point(1, 0)
'<' -> Point(-1, 0)
else -> throw IllegalStateException("Wrong jet $it")
}
}
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day17.class",
"javap": "Compiled from \"Day17.kt\"\npublic final class Day17 {\n private final java.util.List<Point> jets;\n\n private final java.util.List<java.util.Set<Point>> shapes;\n\n private final java.util.Set<Point> cave;\n\n private final Point down... |
ambrosil__aoc-2022__ebaacfc/src/Day23.kt | fun main() {
val d = Day23(readInput("inputs/Day23"))
println(d.part1())
println(d.part2())
}
class Day23(input: List<String>) {
private val startingPositions = parseInput(input)
private val nextTurnOffsets: List<List<Point>> = createOffsets()
fun part1(): Int {
val locations = (0 until 10).fold(startingPositions) { carry, round -> carry.playRound(round) }
val gridSize = ((locations.maxOf { it.x } - locations.minOf { it.x }) + 1) * ((locations.maxOf { it.y } - locations.minOf { it.y }) + 1)
return gridSize - locations.size
}
fun part2(): Int {
var thisTurn = startingPositions
var roundId = 0
do {
val previousTurn = thisTurn
thisTurn = previousTurn.playRound(roundId++)
} while (previousTurn != thisTurn)
return roundId
}
fun Point.neighbors(): Set<Point> =
setOf(
Point(x - 1, y - 1),
Point(x, y - 1),
Point(x + 1, y - 1),
Point(x - 1, y),
Point(x + 1, y),
Point(x - 1, y + 1),
Point(x, y + 1),
Point(x + 1, y + 1)
)
private fun Set<Point>.playRound(roundNumber: Int): Set<Point> {
val nextPositions = this.toMutableSet()
val movers: Map<Point, Point> = this
.filter { elf -> elf.neighbors().any { it in this } }
.mapNotNull { elf ->
nextTurnOffsets.indices.map { direction -> nextTurnOffsets[(roundNumber + direction) % 4] }
.firstNotNullOfOrNull { offsets ->
if (offsets.none { offset -> (elf + offset) in this }) elf to (elf + offsets.first())
else null
}
}.toMap()
val safeDestinations = movers.values.groupingBy { it }.eachCount().filter { it.value == 1 }.keys
movers
.filter { (_, target) -> target in safeDestinations }
.forEach { (source, target) ->
nextPositions.remove(source)
nextPositions.add(target)
}
return nextPositions
}
private fun createOffsets(): List<List<Point>> =
listOf(
listOf(Point(0, -1), Point(-1, -1), Point(1, -1)), // N
listOf(Point(0, 1), Point(-1, 1), Point(1, 1)), // S
listOf(Point(-1, 0), Point(-1, -1), Point(-1, 1)), // W
listOf(Point(1, 0), Point(1, -1), Point(1, 1)), // E
)
private fun parseInput(input: List<String>): Set<Point> =
input.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
if (char == '#') Point(x, y) else null
}
}.toSet()
} | [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day23Kt.class",
"javap": "Compiled from \"Day23.kt\"\npublic final class Day23Kt {\n public static final void main();\n Code:\n 0: new #8 // class Day23\n 3: dup\n 4: ldc #10 // String inp... |
ambrosil__aoc-2022__ebaacfc/src/Day15.kt | import kotlin.math.abs
import kotlin.math.sign
fun main() {
fun List<IntRange>.union(): List<IntRange> {
val sorted = sortedBy { it.first }
val init = mutableListOf(sorted.first())
return sortedBy { it.first }.fold(init) { acc, r ->
val last = acc.last()
if (r.first <= last.last) {
acc[acc.lastIndex] = (last.first..maxOf(last.last, r.last))
} else {
acc += r
}
acc
}
}
fun Point.frequency() = (x * 4_000_000L) + y
infix fun Point.distanceTo(other: Point): Int {
return abs(x - other.x) + abs(y - other.y)
}
infix fun Point.lineTo(other: Point): List<Point> {
val xDelta = (other.x - x).sign
val yDelta = (other.y - y).sign
val steps = maxOf(abs(x - other.x), abs(y - other.y))
return (1..steps).scan(this) { prev, _ -> Point(prev.x + xDelta, prev.y + yDelta) }
}
fun Point.findRange(y: Int, distance: Int): IntRange? {
val width = distance - abs(this.y - y)
return (this.x - width..this.x + width).takeIf { it.first <= it.last }
}
fun parse(input: List<String>): MutableList<Pair<Point, Point>> {
return input.map {
val sensorX = it.substringAfter("Sensor at x=").substringBefore(",").toInt()
val sensorY = it.substringBefore(":").substringAfter("y=").toInt()
val beaconX = it.substringAfter("closest beacon is at x=").substringBefore(",").toInt()
val beaconY = it.substringAfterLast("y=").toInt()
Pair(Point(sensorX, sensorY), Point(beaconX, beaconY))
}
.toMutableList()
}
fun part1(input: List<String>): Int {
val pairs = parse(input)
val y = 2_000_000
return pairs
.mapNotNull { (sensor, beacon) ->
val distance = sensor distanceTo beacon
sensor.findRange(y, distance)
}
.union()
.sumOf { it.last - it.first }
}
fun part2(input: List<String>): Long {
val pairs = parse(input)
val cave = 0..4_000_000L
return pairs.firstNotNullOf { (sensor, beacon) ->
val distance = sensor distanceTo beacon
val up = Point(sensor.x, sensor.y - distance - 1)
val down = Point(sensor.x, sensor.y + distance + 1)
val left = Point(sensor.x - distance - 1, sensor.y)
val right = Point(sensor.x + distance + 1, sensor.y)
(up.lineTo(right) + right.lineTo(down) + down.lineTo(left) + left.lineTo(up))
.filter { it.x in cave && it.y in cave }
.firstOrNull { point ->
pairs.all { (sensor, beacon) ->
sensor distanceTo point > sensor distanceTo beacon
}
}
}.frequency()
}
val input = readInput("inputs/Day15")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day15Kt$main$union$$inlined$sortedBy$2.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class Day15Kt$main$union$$inlined$sortedBy$2<T> implements java.util.Comparator {\n public Day15Kt$main$union$$inlined$sortedBy$2();\n Code:\n 0: alo... |
ambrosil__aoc-2022__ebaacfc/src/Day24.kt | fun main() {
val d = Day24(readInput("inputs/Day24"))
println(d.part1())
println(d.part2())
}
class Day24(input: List<String>) {
private val initialMapState: MapState = MapState.of(input)
private val start: Point = Point(input.first().indexOfFirst { it == '.' }, 0)
private val goal: Point = Point(input.last().indexOfFirst { it == '.' }, input.lastIndex)
fun part1(): Int =
solve().first
fun part2(): Int {
val toGoal = solve()
val backToStart = solve(goal, start, toGoal.second, toGoal.first)
val backToGoal = solve(start, goal, backToStart.second, backToStart.first)
return backToGoal.first
}
private fun solve(
startPlace: Point = start,
stopPlace: Point = goal,
startState: MapState = initialMapState,
stepsSoFar: Int = 0
): Pair<Int, MapState> {
val mapStates = mutableMapOf(stepsSoFar to startState)
val queue = mutableListOf(PathAttempt(stepsSoFar, startPlace))
val seen = mutableSetOf<PathAttempt>()
while (queue.isNotEmpty()) {
val thisAttempt = queue.removeFirst()
if (thisAttempt !in seen) {
seen += thisAttempt
val nextMapState = mapStates.computeIfAbsent(thisAttempt.steps + 1) { key ->
mapStates.getValue(key - 1).nextState()
}
if (nextMapState.isOpen(thisAttempt.location)) queue.add(thisAttempt.next())
val neighbors = thisAttempt.location.adjacents()
if (stopPlace in neighbors) return Pair(thisAttempt.steps + 1, nextMapState)
neighbors
.filter { it == start || (nextMapState.inBounds(it) && nextMapState.isOpen(it)) }
.forEach { neighbor ->
queue.add(thisAttempt.next(neighbor))
}
}
}
throw IllegalStateException("No paths found")
}
private data class PathAttempt(val steps: Int, val location: Point) {
fun next(place: Point = location): PathAttempt =
PathAttempt(steps + 1, place)
}
private data class MapState(val boundary: Point, val blizzards: Set<Blizzard>) {
private val unsafeSpots = blizzards.map { it.location }.toSet()
fun isOpen(place: Point): Boolean =
place !in unsafeSpots
fun inBounds(place: Point): Boolean =
place.x > 0 && place.y > 0 && place.x <= boundary.x && place.y <= boundary.y
fun nextState(): MapState =
copy(blizzards = blizzards.map { it.next(boundary) }.toSet())
companion object {
fun of(input: List<String>): MapState =
MapState(
Point(input.first().lastIndex - 1, input.lastIndex - 1),
input.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
when (char) {
'>' -> Blizzard(Point(x, y), Point(1, 0))
'<' -> Blizzard(Point(x, y), Point(-1, 0))
'v' -> Blizzard(Point(x, y), Point(0, 1))
'^' -> Blizzard(Point(x, y), Point(0, -1))
else -> null
}
}
}.toSet()
)
}
}
private data class Blizzard(val location: Point, val offset: Point) {
fun next(boundary: Point): Blizzard {
var nextLocation = location + offset
when {
nextLocation.x == 0 -> nextLocation = Point(boundary.x, location.y)
nextLocation.x > boundary.x -> nextLocation = Point(1, location.y)
nextLocation.y == 0 -> nextLocation = Point(location.x, boundary.y)
nextLocation.y > boundary.y -> nextLocation = Point(location.x, 1)
}
return copy(location = nextLocation)
}
}
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day24$Blizzard.class",
"javap": "Compiled from \"Day24.kt\"\nfinal class Day24$Blizzard {\n private final Point location;\n\n private final Point offset;\n\n public Day24$Blizzard(Point, Point);\n Code:\n 0: aload_1\n 1: ldc #9 ... |
ambrosil__aoc-2022__ebaacfc/src/Day05.kt | fun main() {
data class Common(val input: List<String>) {
lateinit var moves: List<String>
lateinit var stacks: List<ArrayDeque<Char>>
init {
parse()
}
fun parse() {
val map = input.groupBy {
when {
it.contains("move") -> "moves"
it.contains("[") -> "crates"
else -> "garbage"
}
}
val maxStringLength = map["crates"]!!.maxOf { it.length }
val crates = map["crates"]!!
.map {
it.padEnd(maxStringLength)
.toList()
.chunked(4)
.map { list -> list[1] }
}
val rowLength = crates.first().size
stacks = List(rowLength) { ArrayDeque() }
crates.forEach {
it.forEachIndexed {
i, c -> stacks[i].addLast(c)
}
}
moves = map["moves"]!!.map {
it.replace("move", "")
.replace("from", "")
.replace("to", "")
.trim()
}
}
}
fun part1(input: List<String>): String {
val common = Common(input)
common.moves.forEach {
val (count, from, to) = it.split(" ").filterNot { s -> s.isBlank() }.map { n -> n.toInt() }
repeat (count) {
var element: Char
do {
element = common.stacks[from - 1].removeFirst()
} while(element == ' ')
common.stacks[to-1].addFirst(element)
}
}
return List(common.stacks.size) { i ->
common.stacks[i].removeFirst()
}.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val main = Common(input)
main.moves.forEach {
val (count, from, to) = it.split(" ").filterNot { s -> s.isBlank() }.map { n -> n.toInt() }
val cratesToMove = mutableListOf<Char>()
repeat (count) {
if (main.stacks[from -1].isNotEmpty()) {
var element: Char
do {
element = main.stacks[from - 1].removeFirst()
if (element != ' ') {
cratesToMove.add(element)
}
} while (element == ' ')
}
}
cratesToMove.reversed().forEach { c ->
main.stacks[to - 1].addFirst(c)
}
}
return List(main.stacks.size) { i ->
main.stacks[i].removeFirst()
}.joinToString(separator = "")
}
val input = readInput("inputs/Day05")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day05\n 2: invokestatic #14 // Method UtilsKt.re... |
ambrosil__aoc-2022__ebaacfc/src/Day21.kt | fun main() {
data class Monkey(val name: String, val expr: String)
fun Monkey.evaluateExpr(map: MutableMap<String, Long>): Long? {
val parts = this.expr.split(" ")
if (parts.size == 1) {
return parts[0].toLong()
}
val name1 = parts.first()
val name2 = parts.last()
val operator = parts[1]
if (operator == "=") {
if (name1 in map) {
map[name2] = map[name1]!!
} else if (name2 in map) {
map[name1] = map[name2]!!
}
} else {
if (name1 in map && name2 in map) {
val value1 = map[name1]!!
val value2 = map[name2]!!
return when (operator) {
"+" -> value1 + value2
"-" -> value1 - value2
"*" -> value1 * value2
"/" -> value1 / value2
else -> null
}
}
}
return null
}
fun Monkey.variants(): List<Monkey> {
val parts = this.expr.split(" ")
if (parts.size == 1) {
return listOf(this)
}
val name1 = parts.first()
val name2 = parts.last()
val operator = parts[1]
return when (operator) {
"+" -> listOf(this, Monkey(name1, "$name - $name2"), Monkey(name2, "$name - $name1"))
"-" -> listOf(this, Monkey(name1, "$name + $name2"), Monkey(name2, "$name1 - $name"))
"*" -> listOf(this, Monkey(name1, "$name / $name2"), Monkey(name2, "$name / $name1"))
"/" -> listOf(this, Monkey(name1, "$name * $name2"), Monkey(name2, "$name1 / $name"))
else -> listOf(this)
}
}
fun List<Monkey>.calc(need: String): Long {
val map = mutableMapOf<String, Long>()
while (need !in map) {
forEach {
if (map[it.name] == null) {
it.evaluateExpr(map)?.let { result ->
map[it.name] = result
}
}
}
}
return map[need]!!
}
fun part1(input: List<String>) =
input.map {
val (name, expr) = it.split(": ")
Monkey(name, expr)
}
.calc("root")
fun part2(input: List<String>) =
input.flatMap {
val (name, expr) = it.split(": ")
when (name) {
"root" -> Monkey(name, expr.replace("+", "=")).variants()
else -> Monkey(name, expr).variants()
}
}
.filterNot { it.name == "humn" && it.expr.split(" ").size == 1 }
.calc("humn")
val input = readInput("inputs/Day21")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day21Kt.class",
"javap": "Compiled from \"Day21.kt\"\npublic final class Day21Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day21\n 2: invokestatic #14 // Method UtilsKt.re... |
ambrosil__aoc-2022__ebaacfc/src/Day07.kt | fun main() {
data class Node(val name: String, var size: Int = 0, val dir: Boolean = false, val parent: Node? = null) {
fun propagateSize() {
var curr = parent
while (curr != null) {
curr.size += size
curr = curr.parent
}
}
}
data class Common(val input: List<String>) {
val nodes = mutableListOf<Node>()
val root = Node(name = "/")
init {
var currentDir = root
input
.map { it.split(" ") }
.forEach {
val (first, second) = it
if (first == "$" && second == "cd") {
when (val dirName = it[2]) {
".." -> currentDir = currentDir.parent!!
"/" -> currentDir = root
else -> {
currentDir = Node(name = dirName, dir = true, parent = currentDir)
nodes.add(currentDir)
}
}
} else if (first.isNumber()) {
nodes.add(Node(name = second, size = first.toInt(), parent = currentDir))
}
}
nodes.filterNot { it.dir }
.forEach { it.propagateSize() }
}
}
fun part1(input: List<String>): Int {
val common = Common(input)
return common.nodes
.filter { it.dir && it.size <= 100000 }
.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val common = Common(input)
val freeSpace = 70000000 - common.root.size
return common.nodes
.filter { it.dir }
.fold(70000000) { acc, item ->
if (freeSpace + item.size >= 30000000 && acc > item.size) {
item.size
} else {
acc
}
}
}
val input = readInput("inputs/Day07")
println(part1(input))
println(part2(input))
}
private fun String.isNumber(): Boolean {
return toIntOrNull() != null
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day07Kt$main$Common.class",
"javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt$main$Common {\n private final java.util.List<java.lang.String> input;\n\n private final java.util.List<Day07Kt$main$Node> nodes;\n\n private final Day07Kt$main$Node ro... |
ambrosil__aoc-2022__ebaacfc/src/Day10.kt | fun main() {
data class Step(val cycle: Int, val sum: Int)
fun run(input: List<String>): MutableList<Step>{
var cycle = 1
var sum = 1
val steps = mutableListOf<Step>()
input.forEach {
when (it) {
"noop" -> steps.add(Step(cycle++, sum))
else -> {
val (_, amount) = it.split(" ")
steps += Step(cycle++, sum)
steps += Step(cycle++, sum)
sum += amount.toInt()
}
}
}
return steps
}
fun part1(input: List<String>): Int {
val cycles = List(6) { i -> 20 + i * 40 }
return run(input)
.filter { it.cycle in cycles }
.sumOf { it.cycle * it.sum }
}
fun part2(input: List<String>) {
run(input)
.map {
val sprite = it.sum - 1..it.sum + 1
if ((it.cycle - 1) % 40 in sprite) "🟨" else "⬛"
}
.chunked(40)
.forEach { println(it.joinToString("")) }
}
val input = readInput("inputs/Day10")
println(part1(input))
part2(input)
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day10Kt$main$Step.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class Day10Kt$main$Step {\n private final int cycle;\n\n private final int sum;\n\n public Day10Kt$main$Step(int, int);\n Code:\n 0: aload_0\n 1: invokespecial #9 ... |
ambrosil__aoc-2022__ebaacfc/src/Day18.kt | fun main() {
data class Cube(val x: Int, val y: Int, val z: Int)
fun Cube.adjacents(): List<Cube> {
return listOf(
Cube(x+1, y, z), Cube(x-1, y, z),
Cube(x, y+1, z), Cube(x, y-1, z),
Cube(x, y, z+1), Cube(x, y, z-1),
)
}
fun parse(input: List<String>): Set<Cube> {
return input.map {
it.split(",").map { n -> n.toInt() }
}
.map { (x, y, z) -> Cube(x, y, z) }
.toSet()
}
fun part1(input: List<String>): Int {
val cubes = parse(input)
return cubes.sumOf { (it.adjacents() - cubes).size }
}
fun part2(input: List<String>): Int {
val cubes = parse(input)
val xRange = cubes.minOf { it.x } - 1..cubes.maxOf { it.x } + 1
val yRange = cubes.minOf { it.y } - 1..cubes.maxOf { it.y } + 1
val zRange = cubes.minOf { it.z } - 1..cubes.maxOf { it.z } + 1
val queue = ArrayDeque<Cube>().apply { add(Cube(xRange.first, yRange.first, zRange.first)) }
val seen = mutableSetOf<Cube>()
var sides = 0
queue.forEach { current ->
if (current !in seen) {
seen += current
current.adjacents()
.filter { it.x in xRange && it.y in yRange && it.z in zRange }
.forEach { adj -> if (adj in cubes) sides++ else queue.add(adj) }
}
}
return sides
}
val input = readInput("inputs/Day18")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day18Kt$main$Cube.class",
"javap": "Compiled from \"Day18.kt\"\npublic final class Day18Kt$main$Cube {\n private final int x;\n\n private final int y;\n\n private final int z;\n\n public Day18Kt$main$Cube(int, int, int);\n Code:\n 0: aload_0\n ... |
ambrosil__aoc-2022__ebaacfc/src/Day11.kt | import kotlin.math.floor
fun main() {
data class Monkey(
val items: MutableList<Long>,
val operation: String,
val divisor: Long,
val trueMonkey: Int,
val falseMonkey: Int,
var inspections: Long = 0
)
fun parse(input: List<String>) =
input
.joinToString("\n")
.split("\n\n")
.map {
val (itemsInput, operationInput, testInput, trueInput, falseInput) = it.split("\n").drop(1)
val items = itemsInput.substringAfter("items: ")
.split(",")
.map { s -> s.trim().toLong() }
.toMutableList()
val operation = operationInput.substringAfter("new =").trim()
val divisibleBy = testInput.substringAfter("by ").toLong()
val trueMonkey = trueInput.substringAfter("monkey ").toInt()
val falseMonkey = falseInput.substringAfter("monkey ").toInt()
Monkey(items, operation, divisibleBy, trueMonkey, falseMonkey)
}
fun operation(operation: String, item: Long): Long {
val expression = operation.replace("old", item.toString())
val (n1, op, n2) = expression.split(" ")
return when (op) {
"+" -> n1.toLong() + n2.toLong()
"*" -> n1.toLong() * n2.toLong()
else -> error("wrong operation $op")
}
}
fun common(input: List<String>, maxIterations: Int, nextWorryLevel: (operationResult: Long, magicNumber: Long) -> Long): Long {
val monkeys = parse(input)
val magicNumber = monkeys.map { it.divisor }.reduce { acc, i ->
acc * i
}
repeat(maxIterations) {
monkeys.forEach {
it.items.forEach { item ->
it.inspections++
val operationResult = operation(it.operation, item)
val worryLevel = nextWorryLevel(operationResult, magicNumber)
if (worryLevel divisibleBy it.divisor) {
monkeys[it.trueMonkey].items += worryLevel
} else {
monkeys[it.falseMonkey].items += worryLevel
}
}
it.items.clear()
}
}
return monkeys
.map { it.inspections }
.sorted()
.takeLast(2)
.reduce { acc, i ->
acc * i
}
}
fun part1(input: List<String>): Long {
return common(input, 20) { operationResult, _ ->
floor(operationResult / 3.0).toLong()
}
}
fun part2(input: List<String>): Long {
return common(input, 10000) { operationResult, magicNumber ->
operationResult % magicNumber
}
}
val input = readInput("inputs/Day11")
println(part1(input))
println(part2(input))
}
infix fun Long.divisibleBy(divisor: Long) = this % divisor == 0L
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day11Kt$main$Monkey.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class Day11Kt$main$Monkey {\n private final java.util.List<java.lang.Long> items;\n\n private final java.lang.String operation;\n\n private final long divisor;\n\n private final in... |
ambrosil__aoc-2022__ebaacfc/src/Day13.kt | private sealed class Packet : Comparable<Packet> {
companion object {
fun of(input: String): Packet =
of(input.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex())
.filter { it.isNotBlank() }
.filter { it != "," }
.iterator()
)
private fun of(input: Iterator<String>): Packet {
val packets = mutableListOf<Packet>()
while (input.hasNext()) {
when (val symbol = input.next()) {
"]" -> return ListPacket(packets)
"[" -> packets.add(of(input))
else -> packets.add(IntPacket(symbol.toInt()))
}
}
return ListPacket(packets)
}
}
}
private class IntPacket(val amount: Int) : Packet() {
fun asList(): Packet = ListPacket(listOf(this))
override fun compareTo(other: Packet): Int =
when (other) {
is IntPacket -> amount.compareTo(other.amount)
is ListPacket -> asList().compareTo(other)
}
}
private class ListPacket(val subPackets: List<Packet>) : Packet() {
override fun compareTo(other: Packet): Int =
when (other) {
is IntPacket -> compareTo(other.asList())
is ListPacket -> subPackets.zip(other.subPackets)
.map { it.first.compareTo(it.second) }
.firstOrNull { it != 0 } ?: subPackets.size.compareTo(other.subPackets.size)
}
}
fun main() {
fun parse(input: List<String>): Sequence<Packet> {
return input.asSequence().filter { it.isNotBlank() }.map { Packet.of(it) }
}
fun part1(input: List<String>): Int {
return parse(input)
.chunked(2)
.mapIndexed { index, (first, second) ->
if (first < second) index + 1 else 0
}.sum()
}
fun part2(input: List<String>): Int {
val packets = parse(input)
val divider1 = Packet.of("[[2]]")
val divider2 = Packet.of("[[6]]")
val ordered = (packets + divider1 + divider2).sorted()
return (ordered.indexOf(divider1) + 1) * (ordered.indexOf(divider2) + 1)
}
val input = readInput("inputs/Day13")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day13Kt.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day13\n 2: invokestatic #14 // Method UtilsKt.re... |
ambrosil__aoc-2022__ebaacfc/src/Day03.kt | fun main() {
fun Set<Char>.score(): Int {
val c = single()
return if (c.isLowerCase()) {
1 + (c - 'a')
} else {
27 + (c - 'A')
}
}
fun String.halve(): List<String> {
val half = length / 2
return listOf(substring(0, half), substring(half))
}
fun part1(input: List<String>) =
input.sumOf { item ->
val (first, second) = item.halve()
(first intersect second).score()
}
fun part2(input: List<String>) =
input
.chunked(3)
.sumOf {
it.fold(it[0].toSet()) {
acc, s -> acc intersect s
}
.score()
}
val input = readInput("inputs/Day03")
println(part1(input))
println(part2(input))
}
infix fun String.intersect(o: String) = toSet() intersect o.toSet()
infix fun Set<Char>.intersect(o: String) = this intersect o.toSet()
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day03\n 2: invokestatic #14 // Method UtilsKt.re... |
ambrosil__aoc-2022__ebaacfc/src/Day02.kt | import Sign.*
import java.lang.RuntimeException
enum class Sign { ROCK, PAPER, SCISSORS }
data class Round(val opponent: Sign, val mine: Sign) {
private fun signPoints() =
when (mine) {
ROCK -> 1
PAPER -> 2
SCISSORS -> 3
}
private fun matchPoints() =
when (mine) {
ROCK -> when (opponent) {
ROCK -> 3
PAPER -> 0
SCISSORS -> 6
}
PAPER -> when (opponent) {
ROCK -> 6
PAPER -> 3
SCISSORS -> 0
}
SCISSORS -> when (opponent) {
ROCK -> 0
PAPER -> 6
SCISSORS -> 3
}
}
fun totalPoints() = signPoints() + matchPoints()
}
fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.split(" ") }
.map {
it.map { sign ->
when (sign) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw RuntimeException()
}
}
}
.map { (opponent, mine) -> Round(opponent, mine) }
.sumOf { it.totalPoints() }
}
fun part2(input: List<String>): Int {
val signs = listOf(ROCK, SCISSORS, PAPER)
return input
.map { it.split(" ") }
.map { (opponentSign, mySign) ->
val opponent = when (opponentSign) {
"A" -> ROCK
"B" -> PAPER
"C" -> SCISSORS
else -> throw RuntimeException()
}
val mine = when (mySign) {
"X" -> signs[(signs.indexOf(opponent) + 1) % signs.size]
"Y" -> opponent
"Z" -> signs[(signs.indexOf(opponent) + 2) % signs.size]
else -> throw RuntimeException()
}
Round(opponent, mine)
}
.sumOf { it.totalPoints() }
}
val input = readInput("inputs/Day02")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day02\n 2: invokestatic #14 // Method UtilsKt.re... |
ambrosil__aoc-2022__ebaacfc/src/Day09.kt | import kotlin.math.abs
import kotlin.math.sign
fun main() {
infix fun Point.follow(head: Point) {
val dx = head.x - x
val dy = head.y - y
if (abs(dx) > 1 || abs(dy) > 1) {
this += Point(dx.sign, dy.sign)
}
}
fun part1(input: List<String>): Int {
val head = Point(0, 0)
val tail = Point(0, 0)
val visited = mutableSetOf<Point>()
input.map {
it.split(" ")
}.forEach { (direction, amount) ->
val dirVector = when (direction) {
"U" -> Point(0, +1)
"D" -> Point(0, -1)
"L" -> Point(-1, 0)
"R" -> Point(+1, 0)
else -> error("wrong direction $direction")
}
for (i in 0 until amount.toInt()) {
head += dirVector
tail.follow(head)
visited.add(tail.copy())
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val knots = MutableList(10) { Point(0, 0) }
val visited = mutableSetOf<Point>()
input.map {
it.split(" ")
}.forEach { (direction, amount) ->
val dirVector = when (direction) {
"U" -> Point(0, +1)
"D" -> Point(0, -1)
"L" -> Point(-1, 0)
"R" -> Point(+1, 0)
else -> error("wrong direction $direction")
}
for (i in 0 until amount.toInt()) {
knots.forEachIndexed { index, knot ->
if (index == 0) {
knot += dirVector
} else {
knot follow knots[index-1]
}
if (index == 9) {
visited.add(knot.copy())
}
}
}
}
return visited.size
}
val input = readInput("inputs/Day09")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day09Kt.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day09\n 2: invokestatic #14 // Method UtilsKt.re... |
ambrosil__aoc-2022__ebaacfc/src/Day08.kt | fun main() {
fun part1(input: List<String>): Int {
val matrix = input.map { it.toList() }
return matrix.count { row, col -> matrix.visible(row, col) }
}
fun part2(input: List<String>): Int {
val matrix = input.map { it.toList() }
return matrix.maxOf { row, col -> matrix.score(row, col) }
}
val input = readInput("inputs/Day08")
println(part1(input))
println(part2(input))
}
fun List<List<Char>>.score(row: Int, col: Int) = scoreUp(row, col) * scoreDown(row, col) * scoreLeft(row, col) * scoreRight(row, col)
fun List<List<Char>>.scoreUp(row: Int, col: Int): Int {
var count = 0
for (i in row-1 downTo 0) {
count++
if (this[i][col] >= this[row][col]) {
break
}
}
return count
}
fun List<List<Char>>.scoreDown(row: Int, col: Int): Int {
var count = 0
for (i in row+1 until size) {
count++
if (this[i][col] >= this[row][col]) {
break
}
}
return count
}
fun List<List<Char>>.scoreLeft(row: Int, col: Int): Int {
var count = 0
for (i in col-1 downTo 0) {
count++
if (this[row][i] >= this[row][col]) {
break
}
}
return count
}
fun List<List<Char>>.scoreRight(row: Int, col: Int): Int {
var count = 0
for (i in col+1 until first().size) {
count++
if (this[row][i] >= this[row][col]) {
break
}
}
return count
}
fun List<List<Char>>.visibleUp(row: Int, col: Int): Boolean {
for (i in 0 until row) {
if (this[i][col] >= this[row][col]) {
return false
}
}
return true
}
fun List<List<Char>>.visibleDown(row: Int, col: Int): Boolean {
for (i in row+1 until size) {
if (this[i][col] >= this[row][col]) {
return false
}
}
return true
}
fun List<List<Char>>.visibleLeft(row: Int, col: Int): Boolean {
for (i in 0 until col) {
if (this[row][i] >= this[row][col]) {
return false
}
}
return true
}
fun List<List<Char>>.visibleRight(row: Int, col: Int): Boolean {
for (i in col+1 until first().size) {
if (this[row][i] >= this[row][col]) {
return false
}
}
return true
}
fun List<List<Char>>.visible(row: Int, col: Int): Boolean {
if (row == 0 || col == 0) {
return true
} else if (row == size-1 || col == first().size-1) {
return true
}
return visibleUp(row, col) || visibleDown(row, col) || visibleRight(row, col) || visibleLeft(row, col)
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day08Kt.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day08\n 2: invokestatic #14 // Method UtilsKt.re... |
ambrosil__aoc-2022__ebaacfc/src/Day01.kt | fun main() {
fun part1(input: List<String>): Int {
var elfNum = 0
return input.groupBy { if (it.isBlank()) elfNum++; elfNum }
.map { elf -> elf.value.filterNot { calories -> calories.isBlank() } }
.maxOf { it.sumOf { n -> n.toInt() } }
}
fun part2(input: List<String>): Int {
var elfNum = 0
return input.groupBy { if (it.isBlank()) elfNum++; elfNum }
.map { elf -> elf.value.filterNot { calories -> calories.isBlank() } }
.map { it.sumOf { n -> n.toInt() } }
.sortedDescending()
.take(3)
.sum()
}
val input = readInput("inputs/Day01")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "ambrosil__aoc-2022__ebaacfc/Day01Kt.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String inputs/Day01\n 2: invokestatic #14 // Method UtilsKt.re... |
jkesanen__adventofcode__e4be057/2023/src/main/kotlin/Advent2306.kt | import java.io.File
import kotlin.math.max
class Advent2306 {
private fun chargeToDistance(charge: Long, duration: Long): Long {
val timeLeft = duration - charge
return charge * max(0, timeLeft)
}
private fun getBestResults(filename: String): List<Pair<Long, Long>> {
val times = mutableListOf<Long>()
val distances = mutableListOf<Long>()
File(this::class.java.getResource(filename)!!.file).forEachLine { line ->
val parts = line.split(":")
when (parts[0]) {
"Time" -> times += Regex("""\d+""").findAll(parts[1]).map { it.value.toLong() }.toList()
"Distance" -> distances += Regex("""\d+""").findAll(parts[1]).map { it.value.toLong() }.toList()
}
}
assert(times.size == distances.size)
val races = mutableListOf<Pair<Long, Long>>()
for (i in 0..<times.size) {
races += Pair(times[i], distances[i])
}
return races
}
fun getWaysToWin1(filename: String): Int {
val races = getBestResults(filename)
var waysToWinMultiplied = 0
races.forEach {
val duration = it.first
val distance = it.second
var wins = 0
for (charge in 0..<duration) {
if (chargeToDistance(charge, duration) > distance) {
wins++
}
}
waysToWinMultiplied = if (waysToWinMultiplied == 0) {
wins
} else {
waysToWinMultiplied * wins
}
}
return waysToWinMultiplied
}
private fun getResult(filename: String): Pair<Long, Long> {
var duration = 0L
var distance = 0L
File(this::class.java.getResource(filename)!!.file).forEachLine { line ->
val parts = line.split(":")
when (parts[0]) {
"Time" -> duration = parts[1].replace(" ", "").toLong()
"Distance" -> distance = parts[1].replace(" ", "").toLong()
}
}
return Pair(duration, distance)
}
fun getWaysToWin2(filename: String): Int {
val result = getResult(filename)
var waysToWin = 0
for (charge in 0..<result.first) {
if (chargeToDistance(charge, result.first) > result.second) {
++waysToWin
}
}
return waysToWin
}
}
| [
{
"class_path": "jkesanen__adventofcode__e4be057/Advent2306.class",
"javap": "Compiled from \"Advent2306.kt\"\npublic final class Advent2306 {\n public Advent2306();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n p... |
fufaevlad__hyperskill_test_cinema_room_manager__b81d03b/cinema_manager.kt | var ifCount = 0
var elseCount = 0
const val cheapSeatCoast = 8
const val expSeatCoast = 10
fun main() {
val (rows,seats) = greeting()
val cinema = mutListCreator(rows)
boardFiller(cinema,rows,seats)
multipleChoise(cinema,rows,seats)
}
fun greeting(): Pair<Int,Int>{
println("Enter the number of rows:")
val rows = readln().toInt()
println("Enter the number of seats in each row:")
val seats = readln().toInt()
return Pair(rows,seats)
}
fun mutListCreator(rows:Int):MutableList<MutableList<String>>{
val outList = mutableListOf<MutableList<String>>()
for(i in 0 until rows){
val a = mutableListOf<String>()
outList.add(a)
}
return outList
}
fun boardFiller(list: MutableList<MutableList<String>>, rows:Int, columns:Int){
for(j in 0 until columns) {
for (i in 0 until rows) {
list[i].add("S ")
}
}
}
fun boardPrint(list:MutableList<MutableList<String>>,rows:Int,seats:Int){
println("Cinema:")
print(" ")
for(i in 1 until seats+1){
print("$i ")
}
println()
for(i in 0 until rows) {
println("${i+1} ${list[i].joinToString("")}")
}
}
fun seatChoise(list:MutableList<MutableList<String>>,rows:Int,seats:Int){
println("Enter a row number:")
val r = readln().toInt()
println("Enter a seat number in that row:")
val s = readln().toInt()
if(r>rows||s>seats) {
println("Wrong input!")
seatChoise(list, rows, seats)
} else if(list[r-1][s-1] == "B "){
println("That ticket has already been purchased!")
seatChoise(list,rows,seats)
} else {
if (rows * seats <= 60) {
println("Ticket price: $$expSeatCoast")
ifCount++
} else if (rows * seats > 60) {
if (r <= rows / 2) {
println("Ticket price: $$expSeatCoast")
ifCount++
} else if (r > rows / 2) {
println("Ticket price: $$cheapSeatCoast")
elseCount++
}
}
list[r - 1][s - 1] = "B "
}
}
fun statistics(rows:Int,seats:Int){
val allTicets = ifCount + elseCount
val allSeats = rows*seats
val percentage:Double = allTicets.toDouble()/allSeats.toDouble()*100
val formatPercentage = "%.2f".format(percentage)
val currentIncome = (ifCount * expSeatCoast) + (elseCount * cheapSeatCoast)
var totalIncome = 0
if(rows*seats <= 60) {
totalIncome = rows*seats*expSeatCoast
} else if(rows*seats > 60){
totalIncome = rows/2*expSeatCoast*seats + (rows - rows/2)*cheapSeatCoast*seats
}
println("Number of purchased tickets: $allTicets")
println("Percentage: $formatPercentage%")
println("Current income: $$currentIncome")
println("Total income: $$totalIncome")
}
fun multipleChoise(list:MutableList<MutableList<String>>,rows:Int,seats:Int){
println("1. Show the seats")
println("2. Buy a ticket")
println("3. Statistics")
println("0. Exit")
val num = readln().toInt()
when(num){
1 -> {
boardPrint(list, rows, seats)
multipleChoise(list, rows, seats)
}
2 -> {
seatChoise(list, rows, seats)
boardPrint(list, rows, seats)
multipleChoise(list, rows, seats)
}
3-> {
statistics(rows, seats)
multipleChoise(list, rows, seats)
}
}
}
| [
{
"class_path": "fufaevlad__hyperskill_test_cinema_room_manager__b81d03b/Cinema_managerKt.class",
"javap": "Compiled from \"cinema_manager.kt\"\npublic final class Cinema_managerKt {\n private static int ifCount;\n\n private static int elseCount;\n\n public static final int cheapSeatCoast;\n\n public st... |
ersushantsood__kotlinSamples__94aab4e/src/main/kotlin/LambdasCollections.kt | fun main() {
val li = listOf<Int>(1,2,3,4)
println(li.filter({i:Int -> i%2 ==0}))
//Map operation
println (li.map { it * 2 })
val lstNumbers = listOf<Number>(Number("one",1),Number("two",2),Number("three",3))
println("Numbers:"+lstNumbers.map { it.name })
//Find and groupBy
val list = listOf(1,2,3,4)
//The function find returns the first element of the collection that satisfies the condition set in the lambda.
// It is the same function as firstOrNull, which is a longer but also clearer name
println("Finding the first match as per the lambda condition: "+list.find { it % 2 ==0 })
println("Finding the last match as per the lambda condition: "+list.findLast { it % 2 == 0 })
val animal_collection = listOf(Animal("Lion","carnivore"),Animal("Tiger","carnivore"),
Animal("Elephant","herbivore"),Animal("Rabbit","herbivore"))
val animal_groups = animal_collection.groupBy { it.type }
println("Group of Herbivores and Carnivores:"+animal_groups)
//Fold Operation
//In the previous example, the first time we start with 0 and added all elements until the end.
// In the second case, with start with 15 and subtracted alle elements.
// Basically, the provided value is used as argument for start in the first cycle, then start becomes the value returned by the previous cycle.
var items_list = listOf<Int>(5,10,25)
println("Folding the collection:"+items_list.fold(0, {start,element -> element+start}))
println("Folding the collection by Subtracting the items: "+items_list.fold(25,{start,element -> start-element}))
//So, in the first case the function behaves like this:
//
//start = 0, element = 5 -> result 5
//start = 5, element = 10 -> result 15
//start = 15, element = 25 -> result 40
//flatten operation : The function flatten creates one collection from a supplied list of collections.
var lists = listOf<List<Int>>(listOf(1,2), listOf(4,5))
var flattened_list = lists.flatten()
println("Flattened List: "+flattened_list)
//Flatmap operation : flatMap use the provided lambda to map each element of the initial collection to a new collection,
// then it merges all the collections into one collection.
val lists_numbers = listOf<Number>(Number("one",1),Number("two",2),Number("three",3))
println(lists_numbers.flatMap { listOf(it.value) })
//In this example, we create one list with all the values of the property value of each element of type Number. These are the steps to arrive to this result:
//
//each element is mapped to a new collection, with these three new lists
//listOf(1)
//listOf(2)
//listOf(3)
//then the these three lists are merged in one list, listOf(3,3,5)
//Notice that the initial collection does not affect the kind of collection that is returned. That is to say, even if you start with a set you end up with a generic collection
}
data class Number(val name: String, val value : Int)
data class Animal(val name: String, val type: String)
| [
{
"class_path": "ersushantsood__kotlinSamples__94aab4e/LambdasCollectionsKt.class",
"javap": "Compiled from \"LambdasCollections.kt\"\npublic final class LambdasCollectionsKt {\n public static final void main();\n Code:\n 0: iconst_4\n 1: anewarray #8 // class java/lang/... |
Lank891__Advent-of-Code-2021__4164b70/Day 05 - Kotlin/source.kt | import java.io.File
import kotlin.math.sign
const val boardSize: Int = 1000;
typealias XY = Pair<Int, Int>;
typealias VentPath = Pair<XY, XY>;
typealias Board = Array<Array<Int>>
fun ventPathToString(path: VentPath): String {
return "Path (${path.first.first}, ${path.first.second}) -> (${path.second.first}, ${path.second.second})"
}
fun printBoard(board: Board) {
for(y in 0 until boardSize){
for(x in 0 until boardSize) {
print("${if (board[x][y] == 0) '.' else board[x][y]} ");
}
println();
}
}
fun isVentPathOblique(path: VentPath): Boolean {
return path.first.first != path.second.first && path.first.second != path.second.second;
}
fun commaSeparatedNumbersToXY(numbers: String): XY {
val split: List<Int> = numbers.split(",").map{ str: String -> str.toInt()}
return Pair(split[0], split[1]);
}
fun inputLineToVentPath(line: String): VentPath {
val splits: List<String> = line.split("->").map{ str: String -> str.trim()};
return Pair(commaSeparatedNumbersToXY(splits[0]), commaSeparatedNumbersToXY(splits[1]));
}
fun addNotObliqueVent(board: Board, path: VentPath) {
fun getXRange(path: VentPath): IntProgression {
return if(path.first.first < path.second.first){
(path.second.first downTo path.first.first)
} else {
(path.first.first downTo path.second.first)
}
}
fun getYRange(path: VentPath): IntProgression {
return if(path.first.second < path.second.second){
(path.second.second downTo path.first.second)
} else {
(path.first.second downTo path.second.second)
}
}
for(x in getXRange(path)) {
for(y in getYRange(path)) {
board[x][y]++;
}
}
}
fun addObliqueVent(board: Board, path: VentPath) {
val (left: XY, right: XY) = if (path.first.first < path.second.first) Pair(path.first, path.second) else Pair(path.second, path.first);
var yVal: Int = left.second;
val yDiff: Int = -sign((left.second - right.second).toDouble()).toInt();
for(x in left.first..right.first) {
board[x][yVal] += 1;
yVal += yDiff;
}
}
fun getOverlappedCells(board: Board): Int {
var sum: Int = 0;
for(column in board) {
for(cell in column) {
if(cell > 1) {
sum++;
}
}
}
return sum;
}
fun main(args: Array<String>) {
val vents: List<VentPath> = File("./input.txt").readLines().map{ str: String -> inputLineToVentPath(str)};
val (obliqueVents: List<VentPath>, notObliqueVents: List<VentPath>) = vents.partition { vent: VentPath -> isVentPathOblique(vent) };
/*
println("--- OBLIQUE VENTS ---")
obliqueVents.forEach { vent: VentPath -> println(ventPathToString(vent))};
println("--- NOT OBLIQUE VENTS ---")
notObliqueVents.forEach { vent: VentPath -> println(ventPathToString(vent))};
*/
val board: Board = Array(boardSize) { _ -> Array(boardSize) { _ -> 0 } };
// Part 1
notObliqueVents.forEach { vent: VentPath -> addNotObliqueVent(board, vent) };
println("Part 1 overlapped cells: ${getOverlappedCells(board)}");
//printBoard(board);
// Part 2
obliqueVents.forEach { vent: VentPath -> addObliqueVent(board, vent) };
println("Part 2 overlapped cells: ${getOverlappedCells(board)}");
//printBoard(board);
} | [
{
"class_path": "Lank891__Advent-of-Code-2021__4164b70/SourceKt.class",
"javap": "Compiled from \"source.kt\"\npublic final class SourceKt {\n public static final int boardSize;\n\n public static final java.lang.String ventPathToString(kotlin.Pair<kotlin.Pair<java.lang.Integer, java.lang.Integer>, kotlin.... |
Matheus-Inacioal__AtividadesKotlinQualificaResolucao__9ce1df3/AtvRevisao/Atv3.kt | fun main() {
val numbers = mutableListOf<Int>()
println("Digite uma série de números separados por espaços (ou '0' para sair):")
while (true) {
val input = readLine()
if (input == "0") {
break
}
val number = input?.toIntOrNull()
if (number != null) {
numbers.add(number)
} else {
println("Entrada inválida. Por favor, digite um número válido ou 'q' para sair.")
}
}
if (numbers.isEmpty()) {
println("Nenhum número foi inserido.")
} else {
println("Média: ${calculateAverage(numbers)}")
val (max, min) = findMaxAndMin(numbers)
println("Maior número: $max")
println("Menor número: $min")
val (evenCount, oddCount) = countEvenAndOdd(numbers)
println("Quantidade de números pares: $evenCount")
println("Quantidade de números ímpares: $oddCount")
}
}
fun calculateAverage(numbers: List<Int>): Double {
val sum = numbers.sum()
return sum.toDouble() / numbers.size
}
fun findMaxAndMin(numbers: List<Int>): Pair<Int, Int> {
val max = numbers.maxOrNull() ?: Int.MIN_VALUE
val min = numbers.minOrNull() ?: Int.MAX_VALUE
return Pair(max, min)
}
fun countEvenAndOdd(numbers: List<Int>): Pair<Int, Int> {
val evenCount = numbers.count { it % 2 == 0 }
val oddCount = numbers.size - evenCount
return Pair(evenCount, oddCount)
}
| [
{
"class_path": "Matheus-Inacioal__AtividadesKotlinQualificaResolucao__9ce1df3/Atv3Kt.class",
"javap": "Compiled from \"Atv3.kt\"\npublic final class Atv3Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/util/ArrayList\n 3: dup\n 4: in... |
ReciHub__FunnyAlgorithms__24518dd/Rat Maze Problem/RatMaze.kt | /**
* @created October 2, 2019
* Kotlin Program that solves Rat in a maze problem using backtracking.
*/
class RatMaze {
// Size of the maze.
private var n: Int = 0 // Just in case. Primitive types cannot be lateinit.
private lateinit var solution: Array<IntArray>
private lateinit var maze: Array<IntArray>
/**
* This function solves the Maze problem using
* Backtracking. It mainly uses solveMazeUtil()
* to solve the problem. It returns false if no
* path is possible, otherwise return true and
* prints the path in the form of 1s. Please note
* that there may be more than one solutions, this
* function prints one of the feasible solutions.
*/
fun solve(maze: Array<IntArray>): Boolean {
n = maze.size
this.maze = maze
solution = Array(n) { IntArray(n) }
if (!solveMazeUtil(0, 0)) {
println("Solution does not exist.")
return false
}
printSolution()
return true
}
/**
* A recursive utility function to solve Maze problem.
*/
private fun solveMazeUtil(row: Int, column: Int): Boolean {
// if (row ; column) is the goal then return true
if (row == n - 1 && column == n - 1) {
solution[row][column] = 1
return true
}
// Check if maze[row][column] is valid.
if (isSafe(row, column)) {
solution[row][column] = 1
// Move horizontally
if (solveMazeUtil(row, column + 1)) {
return true
}
// Move vertically
if (solveMazeUtil(row + 1, column)) {
return true
}
// If none of the above movements works then
// BACKTRACK: remove mark on row, column as part of solution path
solution[row][column] = 0
return false
}
return false
}
/**
* Checks that the coordinates "row" and "column" are valid.
*/
private fun isSafe(row: Int, column: Int): Boolean {
return row in 0..(n - 1) &&
column in 0..(n - 1) &&
maze[row][column] == 1
}
/**
* A utility function to print solution matrix.
* solution[n][n]
*/
private fun printSolution() {
(0..(n - 1)).forEach { row ->
(0..(n - 1)).forEach { column ->
print(" ${solution[row][column]}")
}
println()
}
}
}
fun main() {
// Valid Maze
val maze01 = arrayOf(
intArrayOf(1, 0, 0, 0),
intArrayOf(1, 1, 0, 1),
intArrayOf(0, 1, 0, 0),
intArrayOf(1, 1, 1, 1)
)
// Valid Maze
val maze02 = arrayOf(
intArrayOf(1, 0, 0),
intArrayOf(1, 1, 0),
intArrayOf(0, 1, 1)
)
// Invalid Maze
val maze03 = arrayOf(
intArrayOf(1, 0, 0),
intArrayOf(0, 0, 0),
intArrayOf(0, 0, 1)
)
val mazes = arrayListOf<Array<IntArray>>()
mazes.add(maze01)
mazes.add(maze02)
mazes.add(maze03)
val ratMaze = RatMaze()
for (i in 0 until mazes.size) {
println("Solving Maze ${i + 1}")
println()
ratMaze.solve(mazes[i])
println()
}
} | [
{
"class_path": "ReciHub__FunnyAlgorithms__24518dd/RatMaze.class",
"javap": "Compiled from \"RatMaze.kt\"\npublic final class RatMaze {\n private int n;\n\n private int[][] solution;\n\n private int[][] maze;\n\n public RatMaze();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
ReciHub__FunnyAlgorithms__24518dd/BellmanFord/bellmanford.kt | class Edge(val source: Int, val destination: Int, val weight: Int)
class Graph(val vertices: Int, val edges: List<Edge>) {
fun bellmanFord(startVertex: Int) {
val distance = IntArray(vertices) { Int.MAX_VALUE }
distance[startVertex] = 0
for (i in 1 until vertices) {
for (edge in edges) {
if (distance[edge.source] != Int.MAX_VALUE && distance[edge.source] + edge.weight < distance[edge.destination]) {
distance[edge.destination] = distance[edge.source] + edge.weight
}
}
}
for (edge in edges) {
if (distance[edge.source] != Int.MAX_VALUE && distance[edge.source] + edge.weight < distance[edge.destination]) {
println("Graph contains a negative-weight cycle.")
return
}
}
for (i in 0 until vertices) {
println("Shortest distance from vertex $startVertex to vertex $i is ${distance[i]}")
}
}
}
fun main() {
val vertices = 5
val edges = listOf(
Edge(0, 1, -1),
Edge(0, 2, 4),
Edge(1, 2, 3),
Edge(1, 3, 2),
Edge(1, 4, 2),
Edge(3, 2, 5),
Edge(3, 1, 1),
Edge(4, 3, -3)
)
val graph = Graph(vertices, edges)
val startVertex = 0
graph.bellmanFord(startVertex)
}
| [
{
"class_path": "ReciHub__FunnyAlgorithms__24518dd/BellmanfordKt.class",
"javap": "Compiled from \"bellmanford.kt\"\npublic final class BellmanfordKt {\n public static final void main();\n Code:\n 0: iconst_5\n 1: istore_0\n 2: bipush 8\n 4: anewarray #8 ... |
emergent__ProjectEuler__d04f502/Kotlin/problem021.kt | // Problem 21 - Project Euler
// http://projecteuler.net/index.php?section=problems&id=21
import kotlin.math.*
fun divisors(x: Int): List<Int> {
val lim = ceil(sqrt(x.toDouble())).toInt()
return (1..lim)
.map { n ->
if (x % n == 0) listOf(n, x/n) else null
}
.filterNotNull()
.flatten()
.distinct()
.toList()
}
fun d(x: Int) = divisors(x).sum() - x
fun amicable_pair(x: Int): Int? {
val dx = d(x)
return if (d(dx) == x && dx != x) dx else null
}
fun main(args: Array<String>) {
val ans = (1..10000-1).map { amicable_pair(it) }
.filterNotNull()
.filter { it < 10000 }
.sum()
println(ans)
}
| [
{
"class_path": "emergent__ProjectEuler__d04f502/Problem021Kt.class",
"javap": "Compiled from \"problem021.kt\"\npublic final class Problem021Kt {\n public static final java.util.List<java.lang.Integer> divisors(int);\n Code:\n 0: iload_0\n 1: i2d\n 2: invokestatic #14 ... |
emergent__ProjectEuler__d04f502/Kotlin/problem011.kt | // Problem 11 - Project Euler
// http://projecteuler.net/index.php?section=problems&id=11
fun main(args: Array<String>) {
val d = """
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
"""
.trim()
.split("\n")
.map { it.split(" ").map { it.toInt() } }
var ans = 0;
for (i in 0..20-1) {
for (j in 0..20-1) {
val right = if (j < 17) d[i][j] * d[i][j+1] * d[i][j+2] * d[i][j+3] else 0
val down = if (i < 17) d[i][j] * d[i+1][j] * d[i+2][j] * d[i+3][j] else 0
val dr = if (i < 17 && j < 17) d[i][j] * d[i+1][j+1] * d[i+2][j+2] * d[i+3][j+3] else 0
val dl = if (i < 17 && j >= 3) d[i][j] * d[i+1][j-1] * d[i+2][j-2] * d[i+3][j-3] else 0
ans = listOf(right, down, dr, dl, ans).max() ?: ans
}
}
println(ans)
}
| [
{
"class_path": "emergent__ProjectEuler__d04f502/Problem011Kt.class",
"javap": "Compiled from \"problem011.kt\"\npublic final class Problem011Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invoke... |
alexy2008__HelloPrime__dac2f59/original/Kotlin/KtHelloPrime.kt | import kotlin.math.ceil
import kotlin.math.pow
fun primeByEuler(page: Int, prime: KtPrime) {
val num = BooleanArray(page)
for (i in 2 until page) {
if (!num[i]) prime.add(i.toLong())
for (j in 0 until prime.size() ){
if (i.toLong() * prime.getitem(j) >= page) break
num[(i * prime.getitem(j)).toInt()] = true
if (i % prime.getitem(j) == 0L) break
}
}
}
fun primeByEratosthenesInterval(pos: Long, page: Int, prime: KtPrime) {
val num = BooleanArray(page)
for (i in 0 until prime.size()) {
val p = prime.getitem(i)
if (p * p >= pos + page) break
for (j in ceil(pos * 1.0 / p).toLong() until ((pos + page - 1) / p).toLong() + 1)
num[(j * p - pos).toInt()] = true
}
for (i in num.indices) if (!num[i]) prime.add(pos + i)
}
fun main(args: Array<String>) {
println("Hello sample.Prime! I'm Kotlin :-)")
val limit = args[0].toLong()
val page = args[1].toInt()
val mode = args[2].toInt()
val prime = KtPrime(limit, page, mode)
println("使用分区埃拉托色尼筛选法计算${prime.getDfString(limit)}以内素数:")
val costTime = kotlin.system.measureTimeMillis {
//首先使用欧拉法得到种子素数组
primeByEuler(page, prime)
prime.generateResults(page.toLong())
//循环使用埃拉托色尼法计算分区
for (i in 1 until limit/page) {
val pos = page * i
primeByEratosthenesInterval(pos, page, prime)
prime.generateResults(pos + page)
}
}
prime.printTable()
System.out.printf("Kotline finished within %.0e the %dth prime is %d; time cost: %d ms \n",
limit.toDouble(), prime.maxInd, prime.maxPrime, costTime)
}
class KtPrime(limit: Long, page: Int, private val mode: Int) {
var maxInd: Long = 0
var maxPrime: Long = 0
private val maxKeep: Int = (Math.sqrt(limit.toDouble()) / Math.log(Math.sqrt(limit.toDouble())) * 1.3).toInt()
var reserve = ((Math.sqrt(limit.toDouble()) + page) / Math.log(Math.sqrt(limit.toDouble()) + page) * 1.3).toInt()
private val primeList: ArrayList<Long> = ArrayList(reserve)
private val seqList = ArrayList<String>()
private val interList = ArrayList<String>()
private var prevNo: Long = 0
fun getitem(index: Int): Long {
return primeList[index]
}
fun size(): Int {
return primeList.size
}
fun add(p: Long) {
primeList.add(p)
maxInd++
}
fun generateResults(inter: Long) {
if (mode > 0) {
putSequence(prevNo)
putInterval(inter)
prevNo = maxInd
}
maxPrime = primeList[primeList.size - 1]
freeUp()
}
private fun putInterval(inter: Long) {
val s: String
if (inter % 10.0.pow(inter.toString().length - 1.toDouble()) == 0.0) {
s = "${getDfString(inter)}|$maxInd|${getitem(size() - 1)}"
interList.add(s)
if (mode > 1) println("[In:]$s")
}
}
private fun putSequence(beginNo: Long) {
for (i in beginNo.toString().length - 1 until maxInd.toString().length) {
for (j in 1..9) {
val seq = (j * 10.0.pow(i.toDouble())).toLong()
if (seq < beginNo) continue
if (seq >= maxInd) return
val l = getitem(size() - 1 - (maxInd - seq).toInt())
var s = getDfString(seq) + "|" + l
seqList.add(s)
if (mode > 1) println("==>[No:]$s")
}
}
}
private fun freeUp() {
if (maxInd > maxKeep) primeList.subList(maxKeep, primeList.size - 1).clear()
}
fun printTable() {
if (mode < 1) return
println("## 素数序列表")
println("序号|数值")
println("---|---")
seqList.forEach { x: String? -> println(x) }
println("## 素数区间表")
println("区间|个数|最大值")
println("---|---|---")
interList.forEach { x: String? -> println(x) }
}
fun getDfString(l: Long): String {
var s = l.toString()
when {
l % 1000000000000L == 0L -> {
s = s.substring(0, s.length - 12) + "万亿"
}
l % 100000000L == 0L -> {
s = s.substring(0, s.length - 8) + "亿"
}
l % 10000 == 0L -> {
s = s.substring(0, s.length - 4) + "万"
}
}
return s
}
init {
println("内存分配:$reserve")
}
} | [
{
"class_path": "alexy2008__HelloPrime__dac2f59/KtHelloPrimeKt.class",
"javap": "Compiled from \"KtHelloPrime.kt\"\npublic final class KtHelloPrimeKt {\n public static final void primeByEuler(int, KtPrime);\n Code:\n 0: aload_1\n 1: ldc #9 // String prime\n 3... |
gavq__kakuro-kotlin__413f26d/src/main/kotlin/main.kt | fun pad2(n: Int): String {
val s = "$n"
return if (s.length < 2) " $s" else s
}
interface ICell {
fun draw(): String
}
interface IDown {
val down: Int
}
interface IAcross {
val across: Int
}
// singleton
object EmptyCell : ICell {
override fun toString() = "EmptyCell"
override fun draw() = " ----- "
}
data class DownCell(override val down: Int) : ICell, IDown {
override fun draw() = " ${pad2(down)}\\-- "
}
data class AcrossCell(override val across: Int) : ICell, IAcross {
override fun draw() = " --\\${pad2(across)} "
}
data class DownAcrossCell(override val down: Int, override val across: Int) : ICell, IDown, IAcross {
override fun draw() = " ${pad2(down)}\\${pad2(across)} "
}
data class ValueCell(val values: Set<Int>) : ICell {
override fun draw(): String {
return when (values.size) {
1 -> " ${values.first()} "
else -> (1..9).joinToString(separator = "", prefix = " ", transform = ::drawOneValue)
}
}
fun isPossible(n: Int) = values.contains(n)
private fun drawOneValue(it: Int) = if (it in values) "$it" else "."
}
fun da(d: Int, a: Int) = DownAcrossCell(d, a)
fun d(d: Int) = DownCell(d)
fun a(a: Int) = AcrossCell(a)
fun e() = EmptyCell
fun v() = ValueCell(setOf(1, 2, 3, 4, 5, 6, 7, 8, 9))
fun v(vararg args: Int) = ValueCell(args.toSet())
fun v(args: List<Int>) = ValueCell(args.toSet())
data class SimplePair<T>(val first: T, val second: T)
fun drawRow(row: Collection<ICell>): String {
return row.joinToString(separator = "", postfix = "\n", transform = ICell::draw)
}
fun drawGrid(grid: Collection<Collection<ICell>>): String {
return grid.joinToString(transform = ::drawRow)
}
fun <T> allDifferent(nums: Collection<T>): Boolean {
return nums.size == HashSet(nums).size
}
fun <T> product(colls: List<Set<T>>): List<List<T>> {
return when (colls.size) {
0 -> emptyList()
1 -> colls[0].map { listOf(it) }
else -> {
val head = colls[0]
val tail = colls.drop(1)
val tailProd = product(tail)
return head.flatMap { x -> tailProd.map { listOf(x) + it } }
}
}
}
fun permuteAll(vs: List<ValueCell>, target: Int): List<List<Int>> {
val values = vs.map { it.values }
return product(values)
.filter { target == it.sum() }
}
fun <T> transpose(m: List<List<T>>): List<List<T>> {
return when {
m.isEmpty() -> emptyList()
else -> {
(1..m[0].size)
.map { m.map { col -> col[it - 1] } }
}
}
}
fun <T> partitionBy(f: (T) -> Boolean, coll: List<T>): List<List<T>> {
return when {
coll.isEmpty() -> emptyList()
else -> {
val head = coll[0]
val fx = f(head)
val group = coll.takeWhile { fx == f(it) }
listOf(group) + partitionBy(f, coll.drop(group.size))
}
}
}
fun <T> partitionAll(n: Int, step: Int, coll: List<T>): List<List<T>> {
return when {
coll.isEmpty() -> emptyList()
else -> {
listOf(coll.take(n)) + partitionAll(n, step, coll.drop(step))
}
}
}
fun <T> partitionN(n: Int, coll: List<T>): List<List<T>> = partitionAll(n, n, coll)
fun solveStep(cells: List<ValueCell>, total: Int): List<ValueCell> {
val finalIndex = cells.size - 1
val perms = permuteAll(cells, total)
.filter { cells.last().isPossible(it[finalIndex]) }
.filter { allDifferent(it) }
return transpose(perms).map { v(it) }
}
fun gatherValues(line: List<ICell>): List<List<ICell>> {
return partitionBy({ it is ValueCell }, line)
}
fun pairTargetsWithValues(line: List<ICell>): List<SimplePair<List<ICell>>> {
return partitionN(2, gatherValues(line))
.map { SimplePair(it[0], if (1 == it.size) emptyList() else it[1]) }
}
fun solvePair(accessor: (ICell) -> Int, pair: SimplePair<List<ICell>>): List<ICell> {
val notValueCells = pair.first
return when {
pair.second.isEmpty() -> notValueCells
else -> {
val valueCells = pair.second.map { it as ValueCell }
val total = accessor(notValueCells.last())
val newValueCells = solveStep(valueCells, total)
notValueCells + newValueCells
}
}
}
fun solveLine(line: List<ICell>, f: (ICell) -> Int): List<ICell> {
return pairTargetsWithValues(line)
.map { solvePair(f, it) }
.flatten()
}
fun solveRow(row: List<ICell>): List<ICell> {
return solveLine(row, { (it as IAcross).across })
}
fun solveColumn(column: List<ICell>): List<ICell> {
return solveLine(column, { (it as IDown).down })
}
fun solveGrid(grid: List<List<ICell>>): List<List<ICell>> {
val rowsDone = grid.map(::solveRow)
val colsDone = transpose(rowsDone).map(::solveColumn)
return transpose(colsDone)
}
fun solver(grid: List<List<ICell>>): List<List<ICell>> {
println(drawGrid(grid))
val g = solveGrid(grid)
return if (g == grid) g else solver(g)
}
| [
{
"class_path": "gavq__kakuro-kotlin__413f26d/MainKt$drawRow$1.class",
"javap": "Compiled from \"main.kt\"\nfinal class MainKt$drawRow$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<ICell, java.lang.String> {\n public static final MainKt$drawRow$1 INSTANCE;\n\... |
TonnyL__Windary__39f85cd/Kotlin/src/CombinationSumII.kt | /**
* Given a collection of candidate numbers (C) and a target number (T),
* find all unique combinations in C where the candidate numbers sums to T.
*
* Each number in C may only be used once in the combination.
*
* Note:
* All numbers (including target) will be positive integers.
* The solution set must not contain duplicate combinations.
* For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
* A solution set is:
* [
* [1, 7],
* [1, 2, 5],
* [2, 6],
* [1, 1, 6]
* ]
*
* Accepted.
*/
class CombinationSumII {
fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> {
if (candidates.isEmpty()) {
return emptyList()
}
val lists = mutableListOf<List<Int>>()
candidates.sort()
dfs(candidates, target, ArrayList(), lists, 0)
return lists
}
private fun dfs(candidates: IntArray, target: Int, path: MutableList<Int>, ret: MutableList<List<Int>>, index: Int) {
if (target < 0) {
return
}
if (target == 0) {
ret.add(ArrayList(path))
return
}
for (i in index until candidates.size) {
if (i != index && candidates[i] == candidates[i - 1]) {
continue
}
path.add(candidates[i])
dfs(candidates, target - candidates[i], path, ret, i + 1)
path.removeAt(path.size - 1)
}
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/CombinationSumII.class",
"javap": "Compiled from \"CombinationSumII.kt\"\npublic final class CombinationSumII {\n public CombinationSumII();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ... |
TonnyL__Windary__39f85cd/Kotlin/src/UniqueBinarySearchTreesII.kt | /**
* Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
*
* For example,
* Given n = 3, your program should return all 5 unique BST's shown below.
*
* 1 3 3 2 1
* \ / / / \ \
* 3 2 1 1 3 2
* / / \ \
* 2 1 2 3
*
* Accepted.
*/
class UniqueBinarySearchTreesII {
fun generateTrees(n: Int): List<TreeNode?> {
val list = mutableListOf<TreeNode>()
return if (n <= 0) {
list
} else gen(1, n)
}
private fun gen(start: Int, end: Int): List<TreeNode?> {
val list = mutableListOf<TreeNode?>()
if (start > end) {
list.add(null)
return list
}
if (start == end) {
list.add(TreeNode(start))
return list
}
for (i in start..end) {
for (m in gen(start, i - 1)) {
gen(i + 1, end).mapTo(list) {
TreeNode(i).apply {
left = m
right = it
}
}
}
}
return list
}
data class TreeNode(
var `val`: Int,
var left: TreeNode? = null,
var right: TreeNode? = null
)
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/UniqueBinarySearchTreesII.class",
"javap": "Compiled from \"UniqueBinarySearchTreesII.kt\"\npublic final class UniqueBinarySearchTreesII {\n public UniqueBinarySearchTreesII();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method jav... |
TonnyL__Windary__39f85cd/Kotlin/src/ThreeSum.kt | /**
* Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
* Find all unique triplets in the array which gives the sum of zero.
*
* Note: The solution set must not contain duplicate triplets.
*
* For example, given array S = [-1, 0, 1, 2, -1, -4],
*
* A solution set is:
* [
* [-1, 0, 1],
* [-1, -1, 2]
* ]
*
* Accepted.
*/
class ThreeSum {
fun threeSum(nums: IntArray): List<List<Int>> {
nums.sort()
val set = mutableSetOf<Triple>()
for (first in 0 until nums.size - 2) {
if (nums[first] > 0) {
break
}
val target = 0 - nums[first]
var second = first + 1
var third = nums.size - 1
while (second < third) {
when {
nums[second] + nums[third] == target -> {
set.add(Triple(nums[first], nums[second], nums[third]))
while (second < third && nums[second] == nums[second + 1]) {
second++
}
while (second < third && nums[third] == nums[third - 1]) {
third--
}
second++
third--
}
nums[second] + nums[third] < target -> second++
else -> third--
}
}
}
return mutableListOf<List<Int>>().apply {
addAll(set.map { arrayListOf(it.a, it.b, it.c) })
}
}
internal data class Triple(
val a: Int,
val b: Int,
val c: Int
)
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/ThreeSum.class",
"javap": "Compiled from \"ThreeSum.kt\"\npublic final class ThreeSum {\n public ThreeSum();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final jav... |
TonnyL__Windary__39f85cd/Kotlin/src/SubsetsII.kt | /**
* Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
*
* Note: The solution set must not contain duplicate subsets.
*
* For example,
* If nums = [1,2,2], a solution is:
*
* [
* [2],
* [1],
* [1,2,2],
* [2,2],
* [1,2],
* []
* ]
*
* Accepted.
*/
class SubsetsII {
fun subsetsWithDup(nums: IntArray): List<List<Int>> {
if (nums.isEmpty()) {
return emptyList()
}
val lists = mutableListOf<List<Int>>()
if (nums.size == 1) {
// Add the empty list.
lists.add(emptyList())
lists.add(listOf(nums[0]))
return lists
}
nums.sort()
for (list in subsetsWithDup(nums.copyOfRange(0, nums.size - 1))) {
val l = mutableListOf(nums[nums.size - 1])
l.addAll(list)
if (!lists.contains(l)) {
lists.add(l)
}
if (!lists.contains(list)) {
lists.add(list)
}
}
return lists
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/SubsetsII.class",
"javap": "Compiled from \"SubsetsII.kt\"\npublic final class SubsetsII {\n public SubsetsII();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final... |
TonnyL__Windary__39f85cd/Kotlin/src/ThreeSumClosest.kt | /**
* Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
* Return the sum of the three integers.
* You may assume that each input would have exactly one solution.
*
* For example, given array S = {-1 2 1 -4}, and target = 1.
*
* The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
*
* Accepted.
*/
class ThreeSumClosest {
fun threeSumClosest(nums: IntArray, target: Int): Int {
nums.sort()
var result = nums[0] + nums[1] + nums[2]
for (i in 0 until nums.size - 2) {
var l = i + 1
var r = nums.size - 1
while (l < r) {
val tmp = nums[i] + nums[l] + nums[r]
if (tmp == target) {
return tmp
}
if (Math.abs(tmp - target) < Math.abs(result - target)) {
result = tmp
}
if (tmp < target) {
l++
} else if (tmp > target) {
r--
}
}
}
return result
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/ThreeSumClosest.class",
"javap": "Compiled from \"ThreeSumClosest.kt\"\npublic final class ThreeSumClosest {\n public ThreeSumClosest();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
TonnyL__Windary__39f85cd/Kotlin/src/LetterCombinationsOfAPhoneNumber.kt | /**
* Given a digit string, return all possible letter combinations that the number could represent.
*
* A mapping of digit to letters (just like on the telephone buttons) is given below.
*
* Input:Digit string "23"
* Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
* Note:
* Although the above answer is in lexicographical order, your answer could be in any order you want.
*
* Accepted.
*/
class LetterCombinationsOfAPhoneNumber {
fun letterCombinations(digits: String): List<String> {
val dict = arrayOf(" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz")
val results = mutableListOf<String>()
if (digits.isEmpty()) {
return emptyList()
}
if (digits.length == 1) {
dict[Integer.valueOf(digits)].toCharArray()
.mapTo(results) {
it.toString()
}
return results
}
val list = letterCombinations(digits.substring(1, digits.length))
val sb = StringBuilder()
for (c in dict[Integer.valueOf(digits.substring(0, 1))].toCharArray()) {
for (s in list) {
sb.append(c.toString()).append(s)
results.add(sb.toString())
sb.setLength(0)
}
}
return results
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/LetterCombinationsOfAPhoneNumber.class",
"javap": "Compiled from \"LetterCombinationsOfAPhoneNumber.kt\"\npublic final class LetterCombinationsOfAPhoneNumber {\n public LetterCombinationsOfAPhoneNumber();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
TonnyL__Windary__39f85cd/Kotlin/src/SearchInRotatedSortedArrayII.kt | import java.util.Arrays
/**
* Follow up for "Search in Rotated Sorted Array":
* What if duplicates are allowed?
*
* Would this affect the run-time complexity? How and why?
*
* Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
*
* (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
*
* Write nums function to determine if nums given target is in the array.
*
* The array may contain duplicates.
*
* Accepted.
*/
class SearchInRotatedSortedArrayII {
fun search(nums: IntArray, target: Int): Boolean {
if (nums.isEmpty()) {
return false
}
var start = 0
var end = nums.size - 1
while (start <= end) {
val mid = start + (end - start) / 2
if (nums[mid] == target) {
return true
}
if (nums[mid] < nums[end]) { // right half sorted
if (target > nums[mid] && target <= nums[end]) {
return Arrays.binarySearch(nums, mid, end + 1, target) >= 0
} else {
end = mid - 1
}
} else if (nums[mid] > nums[end]) { // left half sorted
if (target >= nums[start] && target < nums[mid]) {
return Arrays.binarySearch(nums, start, mid + 1, target) >= 0
} else {
start = mid + 1
}
} else {
end--
}
}
return false
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/SearchInRotatedSortedArrayII.class",
"javap": "Compiled from \"SearchInRotatedSortedArrayII.kt\"\npublic final class SearchInRotatedSortedArrayII {\n public SearchInRotatedSortedArrayII();\n Code:\n 0: aload_0\n 1: invokespecial #8 /... |
TonnyL__Windary__39f85cd/Kotlin/src/Permutations.kt | /**
* Given a collection of distinct numbers, return all possible permutations.
*
* For example,
* [1,2,3] have the following permutations:
* [
* [1,2,3],
* [1,3,2],
* [2,1,3],
* [2,3,1],
* [3,1,2],
* [3,2,1]
* ]
*
* Accepted.
*/
class Permutations {
fun permute(nums: IntArray): List<List<Int>> {
val results = mutableListOf<List<Int>>()
if (nums.isEmpty()) {
return results
}
if (nums.size == 1) {
return results.apply {
add(mutableListOf(nums[0]))
}
}
val ints = IntArray(nums.size - 1)
System.arraycopy(nums, 0, ints, 0, nums.size - 1)
for (list in permute(ints)) {
for (i in 0..list.size) {
val tmp = mutableListOf<Int>()
tmp.addAll(list)
tmp.add(i, nums[nums.size - 1])
results.add(tmp)
}
}
return results
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/Permutations.class",
"javap": "Compiled from \"Permutations.kt\"\npublic final class Permutations {\n public Permutations();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n ... |
TonnyL__Windary__39f85cd/Kotlin/src/MinimumPathSum.kt | /**
* Given a m x n grid filled with non-negative numbers,
* find a path from top left to bottom right which minimizes the sum of all numbers along its path.
*
* Note: You can only move either down or right at any point in time.
*
* Example 1:
* [[1,3,1],
* [1,5,1],
* [4,2,1]]
* Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
*
* Accepted.
*/
class MinimumPathSum {
fun minPathSum(grid: Array<IntArray>): Int {
if (grid.isEmpty()) {
return 0
}
if (grid.size == 1) {
if (grid[0].isEmpty()) {
return 0
}
if (grid[0].size == 1) {
return grid[0][0]
}
}
val matrix = Array(grid.size) {
IntArray(grid[0].size)
}
matrix[0][0] = grid[0][0]
(1 until grid.size).forEach {
matrix[it][0] = matrix[it - 1][0] + grid[it][0]
}
(1 until grid[0].size).forEach {
matrix[0][it] = matrix[0][it - 1] + grid[0][it]
}
(1 until grid.size).forEach { i ->
(1 until grid[0].size).forEach {
matrix[i][it] = Math.min(matrix[i - 1][it] + grid[i][it], matrix[i][it - 1] + grid[i][it])
}
}
return matrix[grid.size - 1][grid[0].size - 1]
}
} | [
{
"class_path": "TonnyL__Windary__39f85cd/MinimumPathSum.class",
"javap": "Compiled from \"MinimumPathSum.kt\"\npublic final class MinimumPathSum {\n public MinimumPathSum();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retu... |
TonnyL__Windary__39f85cd/Kotlin/src/NextPermutation.kt | /**
* Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
*
* If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
*
* The replacement must be in-place, do not allocate extra memory.
*
* Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
* 1,2,3 → 1,3,2
* 3,2,1 → 1,2,3
* 1,1,5 → 1,5,1
*
* Accepted.
*/
class NextPermutation {
fun nextPermutation(nums: IntArray) {
var i = nums.size - 2
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--
}
if (i >= 0) {
var j = nums.size - 1
while (nums[j] <= nums[i]) {
j--
}
swap(nums, i, j)
}
reverse(nums, i + 1, nums.size - 1)
}
private fun swap(nums: IntArray, i: Int, j: Int) {
val tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
}
private fun reverse(nums: IntArray, i: Int, j: Int) {
var tmpI = i
var tmpJ = j
while (tmpI < tmpJ) {
swap(nums, tmpI++, tmpJ--)
}
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/NextPermutation.class",
"javap": "Compiled from \"NextPermutation.kt\"\npublic final class NextPermutation {\n public NextPermutation();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
TonnyL__Windary__39f85cd/Kotlin/src/UniqueBinarySearchTrees.kt | /**
* Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
*
* For example,
* Given n = 3, there are a total of 5 unique BST's.
*
* 1 3 3 2 1
* \ / / / \ \
* 3 2 1 1 3 2
* / / \ \
* 2 1 2 3
*
* Two solutions are all accepted.
*/
class UniqueBinarySearchTrees {
// Recursive solution. Accepted.
/*fun numTrees(n: Int): Int {
if (n == 0 || n == 1) return 1
return (1..n).sumBy {
numTrees(it - 1) * numTrees(n - it)
}
}*/
// Dynamic programming.
fun numTrees(n: Int): Int {
val array = IntArray(n + 2, { 0 })
array[0] = 1
array[1] = 1
for (i in 2..n) {
for (j in 0 until i) {
array[i] += array[j] * array[i - j - 1]
}
}
return array[n]
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/UniqueBinarySearchTrees.class",
"javap": "Compiled from \"UniqueBinarySearchTrees.kt\"\npublic final class UniqueBinarySearchTrees {\n public UniqueBinarySearchTrees();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/O... |
TonnyL__Windary__39f85cd/Kotlin/src/Combinations.kt | /**
* Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
*
* For example,
* If n = 4 and k = 2, a solution is:
*
* [
* [2,4],
* [3,4],
* [2,3],
* [1,2],
* [1,3],
* [1,4],
* ]
*/
class Combinations {
// Iterative solution.
// Accepted.
fun combine(n: Int, k: Int): List<List<Int>> {
var results = mutableListOf<List<Int>>()
if (n == 0 || k == 0 || k > n) {
return results
}
(1..n + 1 - k).mapTo(results) {
listOf(it)
}
for (i in 2..k) {
val tmp = mutableListOf<List<Int>>()
for (list in results) {
for (m in list[list.size - 1] + 1..n - (k - i)) {
val newList = mutableListOf<Int>()
newList.addAll(list)
newList.add(m)
tmp.add(newList)
}
}
results = tmp
}
return results
}
// Recursive solution.
// Accepted.
/*fun combine(n: Int, k: Int): List<List<Int>> {
val results = mutableListOf<List<Int>>()
if (n == 0 || k == 0 || k > n) {
return results
}
if (k == 1) {
(1..n).mapTo(results) {
listOf(it)
}
return results
}
for (list in combine(n, k - 1)) {
for (i in list[list.size - 1] until n) {
val tmp = mutableListOf<Int>()
tmp.addAll(list)
tmp.add(i + 1)
results.add(tmp)
}
}
return results*/
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/Combinations.class",
"javap": "Compiled from \"Combinations.kt\"\npublic final class Combinations {\n public Combinations();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n ... |
TonnyL__Windary__39f85cd/Kotlin/src/FourSum.kt | /**
* Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
* Find all unique quadruplets in the array which gives the sum of target.
*
* Note: The solution set must not contain duplicate quadruplets.
*
* For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
*
* A solution set is:
* [
* [-1, 0, 0, 1],
* [-2, -1, 1, 2],
* [-2, 0, 0, 2]
* ]
*
* Accepted.
*/
class FourSum {
// Accepted. 1600ms.
/*fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val set = mutableSetOf<List<Int>>()
nums.sort()
for (i in 0 until nums.size - 3) {
for (j in i + 1 until nums.size - 2) {
for (k in j + 1 until nums.size - 1) {
for (m in k + 1 until nums.size) {
val sum = nums[i] + nums[j] + nums[k] + nums[m]
if (sum > target) {
continue
}
if (sum == target) {
set.add(listOf(nums[i], nums[j], nums[k], nums[m]))
}
}
}
}
}
return ArrayList(set)
}*/
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val results = mutableListOf<List<Int>>()
nums.sort()
for (i in 0 until nums.size - 3) {
for (j in i + 1 until nums.size - 2) {
var left = j + 1
var right = nums.size - 1
while (left < right) {
val sum = nums[i] + nums[j] + nums[left] + nums[right]
when {
sum == target -> {
val tmp = ArrayList<Int>(4)
tmp.add(nums[i])
tmp.add(nums[j])
tmp.add(nums[left])
tmp.add(nums[right])
if (!results.contains(tmp)) {
results.add(tmp)
}
left++
right--
}
sum < target -> left++
else -> right--
}
}
}
}
return results
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/FourSum.class",
"javap": "Compiled from \"FourSum.kt\"\npublic final class FourSum {\n public FourSum();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final java.ut... |
TonnyL__Windary__39f85cd/Kotlin/src/WordSearch.kt | /**
* Given a 2D board and a word, find if the word exists in the grid.
*
* The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring.
* The same letter cell may not be used more than once.
*
* For example,
* Given board =
*
* [
* ['A','B','C','E'],
* ['S','F','C','S'],
* ['A','D','E','E']
* ]
* word = "ABCCED", -> returns true,
* word = "SEE", -> returns true,
* word = "ABCB", -> returns false.
*
* Accepted.
*/
class WordSearch {
fun exist(board: Array<CharArray>, word: String): Boolean {
if (board.isEmpty() || board[0].isEmpty()) {
return false
}
for (i in board.indices) {
(0 until board[0].size)
.filter {
search(board, i, it, word, 0)
}
.forEach {
return true
}
}
return false
}
private fun search(board: Array<CharArray>, i: Int, j: Int, word: String, index: Int): Boolean {
if (index >= word.length) {
return true
}
if (i < 0 || i >= board.size || j < 0 || j >= board[0].size || board[i][j] != word[index]) {
return false
}
board[i][j] = (board[i][j].toInt() xor 255).toChar()
val res = (search(board, i - 1, j, word, index + 1)
|| search(board, i + 1, j, word, index + 1)
|| search(board, i, j - 1, word, index + 1)
|| search(board, i, j + 1, word, index + 1))
board[i][j] = (board[i][j].toInt() xor 255).toChar()
return res
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/WordSearch.class",
"javap": "Compiled from \"WordSearch.kt\"\npublic final class WordSearch {\n public WordSearch();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public f... |
TonnyL__Windary__39f85cd/Kotlin/src/CombinationSum.kt | /**
* Given a set of candidate numbers (C) (without duplicates) and a target number (T),
* find all unique combinations in C where the candidate numbers sums to T.
*
* The same repeated number may be chosen from C unlimited number of times.
*
* Note:
* All numbers (including target) will be positive integers.
* The solution set must not contain duplicate combinations.
* For example, given candidate set [2, 3, 6, 7] and target 7,
* A solution set is:
* [
* [7],
* [2, 2, 3]
* ]
*
* Accepted.
*/
class CombinationSum {
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
if (candidates.isEmpty()) {
return emptyList()
}
val lists = mutableListOf<List<Int>>()
candidates.sort()
dfs(candidates, target, mutableListOf(), lists, 0)
return lists
}
private fun dfs(candidates: IntArray, target: Int, path: MutableList<Int>, ret: MutableList<List<Int>>, index: Int) {
if (target < 0) {
return
}
if (target == 0) {
ret.add(ArrayList(path))
return
}
for (i in index until candidates.size) {
path.add(candidates[i])
dfs(candidates, target - candidates[i], path, ret, i)
path.removeAt(path.size - 1)
}
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/CombinationSum.class",
"javap": "Compiled from \"CombinationSum.kt\"\npublic final class CombinationSum {\n public CombinationSum();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retu... |
TonnyL__Windary__39f85cd/Kotlin/src/PermutationsII.kt | /**
* Given a collection of numbers that might contain duplicates, return all possible unique permutations.
*
* For example,
* [1,1,2] have the following unique permutations:
* [
* [1,1,2],
* [1,2,1],
* [2,1,1]
* ]
*
* Accepted.
*/
class PermutationsII {
fun permuteUnique(nums: IntArray): List<List<Int>> {
val results = mutableListOf<List<Int>>()
if (nums.isEmpty()) {
return results
}
if (nums.size == 1) {
return results.apply {
add(mutableListOf(nums[0]))
}
}
val ints = IntArray(nums.size - 1)
System.arraycopy(nums, 0, ints, 0, nums.size - 1)
val set = mutableSetOf<List<Int>>()
for (list in permuteUnique(ints)) {
for (i in 0..list.size) {
val tmp = mutableListOf<Int>()
tmp.addAll(list)
tmp.add(i, nums[nums.size - 1])
set.add(tmp)
}
}
return results.apply { addAll(set) }
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/PermutationsII.class",
"javap": "Compiled from \"PermutationsII.kt\"\npublic final class PermutationsII {\n public PermutationsII();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retu... |
TonnyL__Windary__39f85cd/Kotlin/src/LongestPalindromicSubstring.kt | /**
* Given a string s, find the longest palindromic substring in s.
* You may assume that the maximum length of s is 1000.
*
* Example:
*
* Input: "babad"
*
* Output: "bab"
*
* Note: "aba" is also a valid answer.
* Example:
*
* Input: "cbbd"
*
* Output: "bb"
*
* Accepted.
*/
class LongestPalindromicSubstring {
fun longestPalindrome(s: String?): String? {
if (s == null || s.length <= 1) {
return s
}
var maxLength = 0
var startIndex = 0
for (index in 0 until s.length) {
var leftIndex = index
var rightIndex = index
while (leftIndex >= 0 && rightIndex < s.length && s[leftIndex] == s[rightIndex]) {
val current = rightIndex - leftIndex + 1
if (current > maxLength) {
maxLength = current
startIndex = leftIndex
}
leftIndex--
rightIndex++
}
leftIndex = index
rightIndex = index + 1
while (leftIndex >= 0 && rightIndex < s.length && s[leftIndex] == s[rightIndex]) {
val current = rightIndex - leftIndex + 1
if (current > maxLength) {
maxLength = current
startIndex = leftIndex
}
leftIndex--
rightIndex++
}
}
return s.substring(startIndex, maxLength + startIndex)
}
}
| [
{
"class_path": "TonnyL__Windary__39f85cd/LongestPalindromicSubstring.class",
"javap": "Compiled from \"LongestPalindromicSubstring.kt\"\npublic final class LongestPalindromicSubstring {\n public LongestPalindromicSubstring();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Me... |
TonnyL__Windary__39f85cd/Kotlin/src/SearchA2DMatrix.kt | /**
* Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
*
* Integers in each row are sorted from left to right.
* The first integer of each row is greater than the last integer of the previous row.
* For example,
*
* Consider the following matrix:
*
* [
* [1, 3, 5, 7],
* [10, 11, 16, 20],
* [23, 30, 34, 50]
* ]
* Given target = 3, return true.
*
* Accepted.
*/
class SearchA2DMatrix {
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
if (matrix.isEmpty() || matrix[0].isEmpty()) {
return false
}
for (i in 0 until matrix.size - 1) {
if (matrix[i][0] == target || matrix[i + 1][0] == target) {
return true
} else if (matrix[i][0] < target && matrix[i + 1][0] > target) {
return matrix[i].binarySearch(target) >= 0
}
}
return matrix[matrix.size - 1].binarySearch(target) >= 0
}
} | [
{
"class_path": "TonnyL__Windary__39f85cd/SearchA2DMatrix.class",
"javap": "Compiled from \"SearchA2DMatrix.kt\"\npublic final class SearchA2DMatrix {\n public SearchA2DMatrix();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ... |
InertExpert2911__Kotlin-Projects__9ec619b/listFunctions.kt | // GATHERING A LIST OF VALUES
fun getListOfNumbers() : List<Int> {
var myList = mutableListOf <Int> ()
for(i in 1..7){
println("Enter a number:")
var Number = Integer.valueOf(readLine())
myList.add(Number)
}
return myList
}
// FINDING THE MAX VALUE
fun findMax(maxList : List<Int>) : Int {
var largestNumber = maxList[0]
// The loop runs for every element in the list and compares it with the largest number. If the conditional is true then, the largest number is updated.
for(j in maxList){
if(j > largestNumber){
largestNumber = j
}
}
return largestNumber
}
// FINDING THE MIN VALUE
fun findMin(minList : List<Int>) : Int {
var smallestNumber = minList[0]
// The loop runs for every element in the list and compares it with the smallest number. If the conditional is true then, the smallest number is updated.
for(k in minList){
if(k < smallestNumber){
smallestNumber = k
}
}
return smallestNumber
}
// FINDING THE AVERAGE
fun findAverage(listAvg : List<Int>) : Int {
var sum = 0
for(l in listAvg){
sum += l
}
return sum / listAvg.size
}
// FINDING IF A LIST CONTAINS A VALUE
fun checkIfListContains(checkList : List<Int>, numToCheck : Int) : Boolean {
for(m in checkList){
if(m == numToCheck){
return true
}
}
return false
}
// MAIN FUNCTION
fun main() {
// OUTPUT OF THE LIST
var values = getListOfNumbers()
println(values)
// OUTPUT FOR THE MAX VALUE
var largestValue = findMax(values)
println("The largest number is $largestValue")
// OUTPUT FOR THE MIN VALUE
var smallestValue = findMin(values)
println("The smallest number is $smallestValue")
// OUTPUT OF THE AVERAGE
var average = findAverage(values)
println("The average is $average")
// TO CHECK IF A VALUE CONTAINS
println("Enter the number you want to check:")
var numToFind = Integer.valueOf(readLine())
var containsValue = checkIfListContains(values, numToFind)
if(containsValue == true){
println("Number Found !!!!")
} else {
println("Number Not Found ???? WTF !!!")
}
}
// ADDITIONAL CHALLENGES
// 1. Create a function that returns the difference between the largest and smallest number in the list.
// ANS: For the first prompt, use the logic from findMin() and findMax() to find the smallest and largest numbers. Then, return the difference between the two.
/*
// FUNC THAT RETURNS THE DIFF BW MIN AND MAX
fun minMaxDiff(minMaxDiffList : List<Int>) : Int{
//LARGEST
var largest = findMax(minMaxDiffList)
//SMALLEST
var smallest = findMin(minMaxDiffList)
// DIFF
var difference = largest - smallest
return difference
}
fun main() {
// LARGEST - SMALLEST
var diff = minMaxDiff(values)
println("The minMaxDiff is $diff")
}
*/
// 2. Create a function that takes in a list of numbers and returns a list with all the values squared.
// ANS: For the second prompt, create an empty list. Then, loop through each element of the list argument; inside the loop, add the value of the element multiplied by itself.
/*
//SQUARE
fun squareNum(sqList : List<Int>) : List<Int> {
for(z in sqList){
// sqList[z] = z * z
var num = z * z
// sqList[0]
// sqList.remove()
sqList.add(num)
}
return sqList
}
EROORS WORK IT OUT
*/
| [
{
"class_path": "InertExpert2911__Kotlin-Projects__9ec619b/ListFunctionsKt.class",
"javap": "Compiled from \"listFunctions.kt\"\npublic final class ListFunctionsKt {\n public static final java.util.List<java.lang.Integer> getListOfNumbers();\n Code:\n 0: new #10 // class ... |
codinasion__codinasion__98267f3/program/program/find-the-adjoint-of-a-matrix/FindTheAdjointOfAMatrix.kt | fun main() {
val matrixA = listOf(
listOf(1, 2, 3),
listOf(4, 5, 6),
listOf(7, 8, 9)
)
val matrixAdjoint = calculateAdjoint(matrixA)
println("Input (A): $matrixA")
println("Matrix of Adjoint (A*): $matrixAdjoint")
}
fun calculateAdjoint(matrix: List<List<Int>>): List<List<Int>> {
val matrixCofactors = calculateCofactors(matrix)
return transpose(matrixCofactors)
}
fun calculateCofactors(matrix: List<List<Int>>): List<List<Int>> {
return matrix.mapIndexed { i, row ->
row.indices.map { j ->
getCofactor(matrix, i, j)
}
}
}
fun transpose(matrix: List<List<Int>>): List<List<Int>> {
if (matrix.isEmpty() || matrix[0].isEmpty())
return emptyList()
val numRows = matrix.size
val numCols = matrix[0].size
return List(numCols) { col ->
List(numRows) { row ->
matrix[row][col]
}
}
}
fun getCofactor(matrix: List<List<Int>>, row: Int, col: Int): Int {
val sign = if ((row + col) % 2 == 0) 1 else -1
val subMatrix = getSubMatrix(matrix, row, col)
return sign * determinant(subMatrix)
}
fun getSubMatrix(matrix: List<List<Int>>, rowToRemove: Int, colToRemove: Int): List<List<Int>> {
return matrix
.filterIndexed { i, _ -> i != rowToRemove }
.map { row -> row.filterIndexed { j, _ -> j != colToRemove } }
}
fun determinant(matrix: List<List<Int>>): Int {
if (matrix.size == 2)
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
return matrix.indices.sumOf { i ->
val sign = if (i % 2 == 0) 1 else -1
val subMatrix = getSubMatrix(matrix, 0, i)
sign * matrix[0][i] * determinant(subMatrix)
}
} | [
{
"class_path": "codinasion__codinasion__98267f3/FindTheAdjointOfAMatrixKt.class",
"javap": "Compiled from \"FindTheAdjointOfAMatrix.kt\"\npublic final class FindTheAdjointOfAMatrixKt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: anewarray #8 // class j... |
Kvest__AOC2022__6409e65/src/Utils.kt | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
import kotlin.math.abs
typealias Matrix = Array<IntArray>
typealias BooleanMatrix = Array<BooleanArray>
typealias Int3DMatrix = Array<Array<IntArray>>
typealias Boolean3DMatrix = Array<Array<BooleanArray>>
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
/**
* Converts string to md5 hash.
*/
fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray()))
.toString(16)
.padStart(32, '0')
operator fun IntRange.contains(other: IntRange): Boolean = first <= other.first && other.last <= last
val IntRange.size
get() = abs(this.last - this.first) + 1
data class XY(val x: Int, val y: Int)
data class MutableXY(var x: Int, var y: Int) {
fun toXY() = XY(x = x, y = y)
}
data class IJ(val i: Int, val j: Int)
data class MutableIJ(var i: Int, var j: Int) {
fun toIJ() = IJ(i = i, j = j)
}
fun BooleanMatrix.deepCopyOf(): BooleanMatrix = Array(this.size) { i -> this[i].copyOf() }
data class Item(val steps: Int, val ij: IJ) : Comparable<Item> {
override fun compareTo(other: Item): Int {
return this.steps - other.steps
}
}
/**
* Create all possible combinations from the list's elements
*/
fun <T> List<T>.allCombinations(): List<List<T>> {
val results = mutableListOf<List<T>>()
repeat(this.size + 1) { count ->
combine(data = ArrayList(count), results, start = 0, index = 0, count = count)
}
return results
}
/**
* Create all possible combinations with size "count " from the list's elements
* @param count - count of the elements in each combination
*/
fun <T> List<T>.combinations(count: Int): List<List<T>> {
val results = mutableListOf<List<T>>()
combine(data = ArrayList(count), results, start = 0, index = 0, count = count)
return results
}
private fun <T> List<T>.combine(
data: ArrayList<T>,
results: MutableList<List<T>>,
start: Int,
index: Int,
count: Int,
) {
// Current combination is ready to be added to the result
if (index == count) {
results.add(ArrayList(data))
return
}
// replace index with all possible elements. The condition
// "this.lastIndex - i + 1 >= (count - 1) - index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
var i = start
while (i <= this.lastIndex && (this.lastIndex - i + 1 >= (count - 1) - index)) {
if (data.lastIndex < index) {
data.add(this[i])
} else {
data[index] = this[i]
}
combine(data, results, start = i + 1, index = index + 1, count = count)
i++
}
}
| [
{
"class_path": "Kvest__AOC2022__6409e65/UtilsKt.class",
"javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String name\n 3... |
Kvest__AOC2022__6409e65/src/Day14.kt | import kotlin.math.max
import kotlin.math.min
fun main() {
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
private val SAND_START_POINT = XY(500, 0)
private fun part1(input: List<String>): Int {
val points = mutableSetOf<XY>()
parseInput(input, points)
val bottom = points.maxOf { it.y }
val rocksCount = points.size
solve(bottom, points, SAND_START_POINT, exitOnBottom = true)
return points.size - rocksCount
}
private fun part2(input: List<String>): Int {
val points = mutableSetOf<XY>()
parseInput(input, points)
val bottom = points.maxOf { it.y } + 2
val rocksCount = points.size
solve(bottom, points, SAND_START_POINT, exitOnBottom = false)
return points.size - rocksCount
}
private fun parseInput(input: List<String>, points: MutableSet<XY>) {
input
.map { it.split(" -> ") }
.forEach { row ->
row.windowed(2, 1) { (from, to) ->
val xFrom = from.substringBefore(",").toInt()
val yFrom = from.substringAfter(",").toInt()
val xTo = to.substringBefore(",").toInt()
val yTo = to.substringAfter(",").toInt()
for (x in min(xFrom, xTo)..max(xFrom, xTo)) {
for (y in min(yFrom, yTo)..max(yFrom, yTo)) {
points.add(XY(x = x, y = y))
}
}
}
}
}
private fun solve(bottom: Int, points: MutableSet<XY>, point: XY, exitOnBottom: Boolean): Boolean {
if (points.contains(point)) {
return false
}
if (point.y == bottom) {
return exitOnBottom
}
if (solve(bottom, points, XY(x = point.x, y = point.y + 1), exitOnBottom)) return true
if (solve(bottom, points, XY(x = point.x - 1, y = point.y + 1), exitOnBottom)) return true
if (solve(bottom, points, XY(x = point.x + 1, y = point.y + 1), exitOnBottom)) return true
points.add(point)
return false
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day14Kt.class",
"javap": "Compiled from \"Day14.kt\"\npublic final class Day14Kt {\n private static final XY SAND_START_POINT;\n\n public static final void main();\n Code:\n 0: ldc #8 // String Day14_test\n 2: invokestatic ... |
Kvest__AOC2022__6409e65/src/Day04.kt | fun main() {
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
return input
.map(String::parseSectionRanges)
.count { it.first in it.second || it.second in it.first }
}
private fun part2(input: List<String>): Int {
return input
.map(String::parseSectionRanges)
.count { it.first.first in it.second || it.second.first in it.first }
}
private val ROW_FORMAT = Regex("(\\d+)-(\\d+),(\\d+)-(\\d+)")
private fun String.parseSectionRanges(): Pair<IntRange, IntRange> {
val match = ROW_FORMAT.find(this)
val (a, b, c, d) = requireNotNull(match).destructured
return IntRange(a.toInt(), b.toInt()) to IntRange(c.toInt(), d.toInt())
}
| [
{
"class_path": "Kvest__AOC2022__6409e65/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n private static final kotlin.text.Regex ROW_FORMAT;\n\n public static final void main();\n Code:\n 0: ldc #8 // String Day04_test\n 2: invo... |
Kvest__AOC2022__6409e65/src/Day15.kt | import java.util.*
import kotlin.math.abs
import kotlin.math.max
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
val testInput = readInput("Day15_test")
val (testSensors, testBeacons) = parseInput(testInput)
check(part1(testSensors, testBeacons, targetLine = 10) == 26)
check(part2(testSensors, bound = 20) == 56000011L)
val input = readInput("Day15")
val (sensors, beacons) = parseInput(input)
println(part1(sensors, beacons, targetLine = 2_000_000))
println(part2(sensors, bound = 4_000_000))
}
private fun part1(sensors: List<Sensor>, beacons: Set<XY>, targetLine: Int): Int {
val intervals = calculateLineCoverage(sensors, targetLine)
val beaconsOnLine = beacons.filter { beacon ->
beacon.y == targetLine
}.count()
return intervals.sumOf { it.size } - beaconsOnLine
}
private fun part2(sensors: List<Sensor>, bound: Int): Long {
for (y in 0..bound) {
val intervals = calculateLineCoverage(sensors, y)
if (intervals[0].first > 0) {
return y.toLong()
}
for (i in 1..intervals.lastIndex) {
if (intervals[i].first - intervals[i - 1].last > 1) {
return (intervals[i - 1].last + 1) * 4_000_000L + y
}
}
if (intervals.last().last < bound) {
return (intervals.last().last + 1) * 4_000_000L + y
}
}
error("Not found")
}
private val ROW_FORMAT = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
private fun parseInput(input: List<String>): Pair<List<Sensor>, Set<XY>> {
val sensors = mutableListOf<Sensor>()
val beacons = mutableSetOf<XY>()
input.forEach {
val match = ROW_FORMAT.find(it)
val (x, y, beaconX, beaconY) = requireNotNull(match).destructured
val radius = abs(x.toInt() - beaconX.toInt()) + abs(y.toInt() - beaconY.toInt())
sensors.add(Sensor(x = x.toInt(), y = y.toInt(), radius = radius))
beacons.add(XY(x = beaconX.toInt(), y = beaconY.toInt()))
}
return Pair(sensors, beacons)
}
private fun calculateLineCoverage(sensors: List<Sensor>, line: Int): List<IntRange> {
val intervals = sensors
.mapNotNull { sensor ->
val count = sensor.radius - abs(sensor.y - line)
if (count > 0) {
((sensor.x - count)..(sensor.x + count))
} else {
null
}
}
.sortedBy { it.first }
val result = LinkedList<IntRange>()
//collapse intervals if possible
result.addLast(intervals.first())
for (i in 1..intervals.lastIndex) {
if (result.last.last >= intervals[i].first) {
val tmp = result.pollLast()
result.addLast(tmp.first..max(tmp.last, intervals[i].last))
} else {
result.addLast(intervals[i])
}
}
return result
}
private data class Sensor(
val x: Int,
val y: Int,
val radius: Int,
) | [
{
"class_path": "Kvest__AOC2022__6409e65/Day15Kt$calculateLineCoverage$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class Day15Kt$calculateLineCoverage$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public Day15Kt$calculateLineCoverage$$inlined$sortedBy$1... |
Kvest__AOC2022__6409e65/src/Day22.kt | fun main() {
val testInput = readInput("Day22_test")
val testMap = testInput.subList(0, testInput.size - 2).toMap()
val testPath = testInput.last().parsePath()
check(part1(testMap, testPath) == 6032)
check(part2(testMap, testMap.buildTestCubeAdjacentMap(), testPath) == 5031)
val input = readInput("Day22")
val map = input.subList(0, input.size - 2).toMap()
val path = input.last().parsePath()
println(part1(map, path))
println(part2(map, map.buildCubeAdjacentMap(), path))
}
private const val VOID = 0
private const val OPEN = 1
private const val WALL = 2
private const val RIGHT = 0
private const val DOWN = 1
private const val LEFT = 2
private const val UP = 3
private fun part1(map: Matrix, path: List<PathItem>): Int {
val adjacentMap = map.buildAdjacentMap()
return solve(map, adjacentMap, path)
}
private fun part2(map: Matrix, adjacentMap: Int3DMatrix, path: List<PathItem>): Int = solve(map, adjacentMap, path)
private fun solve(map: Matrix, adjacentMap: Int3DMatrix, path: List<PathItem>): Int {
// "You begin the path in the leftmost open tile of the top row of tiles."
val position = MutableIJ(
i = 0,
j = map[0].indexOfFirst { it == OPEN }
)
var rotation = RIGHT
path.forEach { pathItem ->
when (pathItem) {
is PathItem.Move -> {
for (k in 1..pathItem.stepsCount) {
val i = adjacentMap[position.i][position.j][rotation * 3]
val j = adjacentMap[position.i][position.j][rotation * 3 + 1]
if (map[i][j] == WALL) {
break
}
rotation = adjacentMap[position.i][position.j][rotation * 3 + 2]
position.i = i
position.j = j
}
}
PathItem.RotationLeft -> rotation = if (rotation == RIGHT) UP else rotation - 1
PathItem.RotationRight -> rotation = if (rotation == UP) RIGHT else rotation + 1
}
}
return 1_000 * (position.i + 1) + 4 * (position.j + 1) + rotation
}
private fun List<String>.toMap(): Matrix {
val iSize = this.size
val jSize = this.maxOf { it.length }
val result = Array(iSize) { i ->
IntArray(jSize) { j ->
when (this[i].getOrNull(j)) {
'.' -> OPEN
'#' -> WALL
else -> VOID
}
}
}
return result
}
private fun Matrix.buildAdjacentMap(): Int3DMatrix {
return Array(this.size) { i ->
Array(this[i].size) { j ->
if (this[i][j] != VOID) {
var jRight = (j + 1) % this[i].size
while (this[i][jRight] == VOID) {
jRight = (jRight + 1) % this[i].size
}
var iDown = (i + 1) % this.size
while (this[iDown][j] == VOID) {
iDown = (iDown + 1) % this.size
}
var jLeft = if (j > 0) (j - 1) else this[i].lastIndex
while (this[i][jLeft] == VOID) {
jLeft = if (jLeft > 0) (jLeft - 1) else this[i].lastIndex
}
var iUp = if (i > 0) (i - 1) else this.lastIndex
while (this[iUp][j] == VOID) {
iUp = if (iUp > 0) (iUp - 1) else this.lastIndex
}
intArrayOf(
i, jRight, RIGHT,
iDown, j, DOWN,
i, jLeft, LEFT,
iUp, j, UP
)
} else {
intArrayOf()
}
}
}
}
private fun Matrix.buildCubeAdjacentMap(): Int3DMatrix {
val result = Array(this.size) { i ->
Array(this[i].size) { j ->
if (this[i][j] != VOID) {
intArrayOf(
i, j + 1, RIGHT,
i + 1, j, DOWN,
i, j - 1, LEFT,
i - 1, j, UP
)
} else {
intArrayOf()
}
}
}
val cubeSize = this.size / 4
//Link cube edges
/*
22221111
22221111
22221111
22221111
3333
3333
3333
3333
55554444
55554444
55554444
55554444
6666
6666
6666
6666
*/
//Link 1 <-> 3 edges
repeat(cubeSize) { delta ->
result[cubeSize - 1][2 * cubeSize + delta][3 * DOWN] = cubeSize + delta
result[cubeSize - 1][2 * cubeSize + delta][3 * DOWN + 1] = 2 * cubeSize - 1
result[cubeSize - 1][2 * cubeSize + delta][3 * DOWN + 2] = LEFT
result[cubeSize + delta][2 * cubeSize - 1][3 * RIGHT] = cubeSize - 1
result[cubeSize + delta][2 * cubeSize - 1][3 * RIGHT + 1] = 2 * cubeSize + delta
result[cubeSize + delta][2 * cubeSize - 1][3 * RIGHT + 2] = UP
}
//Link 1 <-> 4 edges
repeat(cubeSize) { delta ->
result[cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT] = 2 * cubeSize + delta
result[cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT + 1] = 2 * cubeSize - 1
result[cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT + 2] = LEFT
result[2 * cubeSize + delta][2 * cubeSize - 1][3 * RIGHT] = cubeSize - delta - 1
result[2 * cubeSize + delta][2 * cubeSize - 1][3 * RIGHT + 1] = 3 * cubeSize - 1
result[2 * cubeSize + delta][2 * cubeSize - 1][3 * RIGHT + 2] = LEFT
}
//Link 1 <-> 6 edges
repeat(cubeSize) { delta ->
result[0][2 * cubeSize + delta][3 * UP] = 4 * cubeSize - 1
result[0][2 * cubeSize + delta][3 * UP + 1] = delta
result[0][2 * cubeSize + delta][3 * UP + 2] = UP
result[4 * cubeSize - 1][delta][3 * DOWN] = 0
result[4 * cubeSize - 1][delta][3 * DOWN + 1] = 2 * cubeSize + delta
result[4 * cubeSize - 1][delta][3 * DOWN + 2] = DOWN
}
//Link 2 <-> 5 edges
repeat(cubeSize) { delta ->
result[cubeSize - delta - 1][cubeSize][3 * LEFT] = 2 * cubeSize + delta
result[cubeSize - delta - 1][cubeSize][3 * LEFT + 1] = 0
result[cubeSize - delta - 1][cubeSize][3 * LEFT + 2] = RIGHT
result[2 * cubeSize + delta][0][3 * LEFT] = cubeSize - delta - 1
result[2 * cubeSize + delta][0][3 * LEFT + 1] = cubeSize
result[2 * cubeSize + delta][0][3 * LEFT + 2] = RIGHT
}
//Link 2 <-> 6 edges
repeat(cubeSize) { delta ->
result[0][cubeSize + delta][3 * UP] = 3 * cubeSize + delta
result[0][cubeSize + delta][3 * UP + 1] = 0
result[0][cubeSize + delta][3 * UP + 2] = RIGHT
result[3 * cubeSize + delta][0][3 * LEFT] = 0
result[3 * cubeSize + delta][0][3 * LEFT + 1] = cubeSize + delta
result[3 * cubeSize + delta][0][3 * LEFT + 2] = DOWN
}
//Link 3 <-> 5 edges
repeat(cubeSize) { delta ->
result[2 * cubeSize - delta - 1][cubeSize][3 * LEFT] = 2 * cubeSize
result[2 * cubeSize - delta - 1][cubeSize][3 * LEFT + 1] = cubeSize - delta - 1
result[2 * cubeSize - delta - 1][cubeSize][3 * LEFT + 2] = DOWN
result[2 * cubeSize][cubeSize - delta - 1][3 * UP] = 2 * cubeSize - delta - 1
result[2 * cubeSize][cubeSize - delta - 1][3 * UP + 1] = cubeSize
result[2 * cubeSize][cubeSize - delta - 1][3 * UP + 2] = RIGHT
}
//Link 4 <-> 6 edges
repeat(cubeSize) { delta ->
result[3 * cubeSize - 1][cubeSize + delta][3 * DOWN] = 3 * cubeSize + delta
result[3 * cubeSize - 1][cubeSize + delta][3 * DOWN + 1] = cubeSize - 1
result[3 * cubeSize - 1][cubeSize + delta][3 * DOWN + 2] = LEFT
result[3 * cubeSize + delta][cubeSize - 1][3 * RIGHT] = 3 * cubeSize - 1
result[3 * cubeSize + delta][cubeSize - 1][3 * RIGHT + 1] = cubeSize + delta
result[3 * cubeSize + delta][cubeSize - 1][3 * RIGHT + 2] = UP
}
return result
}
private fun Matrix.buildTestCubeAdjacentMap(): Int3DMatrix {
val result = Array(this.size) { i ->
Array(this[i].size) { j ->
if (this[i][j] != VOID) {
intArrayOf(
i, j + 1, RIGHT,
i + 1, j, DOWN,
i, j - 1, LEFT,
i - 1, j, UP
)
} else {
intArrayOf()
}
}
}
val cubeSize = this.size / 3
val leftTop = cubeSize * 2
//Link cube edges
/*
1111
1111
1111
1111
222233334444
222233334444
222233334444
222233334444
55556666
55556666
55556666
55556666
*/
//Link 1 <-> 2
repeat(cubeSize) { delta ->
result[0][leftTop + delta][3 * UP] = cubeSize
result[0][leftTop + delta][3 * UP + 1] = cubeSize - delta - 1
result[0][leftTop + delta][3 * UP + 2] = DOWN
result[cubeSize][cubeSize - delta - 1][3 * UP] = 0
result[cubeSize][cubeSize - delta - 1][3 * UP + 1] = leftTop + delta
result[cubeSize][cubeSize - delta - 1][3 * UP + 2] = DOWN
}
//Link 1 <-> 3
repeat(cubeSize) { delta ->
result[delta][leftTop][3 * LEFT] = cubeSize
result[delta][leftTop][3 * LEFT + 1] = cubeSize + delta
result[delta][leftTop][3 * LEFT + 2] = DOWN
result[cubeSize][cubeSize + delta][3 * UP] = delta
result[cubeSize][cubeSize + delta][3 * UP + 1] = leftTop
result[cubeSize][cubeSize + delta][3 * UP + 2] = RIGHT
}
//Link 1 <-> 6
repeat(cubeSize) { delta ->
result[delta][3 * cubeSize - 1][3 * RIGHT] = 3 * cubeSize - delta - 1
result[delta][3 * cubeSize - 1][3 * RIGHT + 1] = 4 * cubeSize - 1
result[delta][3 * cubeSize - 1][3 * RIGHT + 2] = LEFT
result[3 * cubeSize - delta - 1][4 * cubeSize - 1][3 * RIGHT] = delta
result[3 * cubeSize - delta - 1][4 * cubeSize - 1][3 * RIGHT + 1] = 3 * cubeSize - 1
result[3 * cubeSize - delta - 1][4 * cubeSize - 1][3 * RIGHT + 2] = LEFT
}
//Link 2 <-> 5
repeat(cubeSize) { delta ->
result[2 * cubeSize - 1][delta][3 * DOWN] = 3 * cubeSize - 1
result[2 * cubeSize - 1][delta][3 * DOWN + 1] = 3 * cubeSize - delta - 1
result[2 * cubeSize - 1][delta][3 * DOWN + 2] = UP
result[3 * cubeSize - 1][3 * cubeSize - delta - 1][3 * DOWN] = 2 * cubeSize - 1
result[3 * cubeSize - 1][3 * cubeSize - delta - 1][3 * DOWN + 1] = delta
result[3 * cubeSize - 1][3 * cubeSize - delta - 1][3 * DOWN + 2] = UP
}
//Link 2 <-> 6
repeat(cubeSize) { delta ->
result[cubeSize + delta][0][3 * LEFT] = 3 * cubeSize - 1
result[cubeSize + delta][0][3 * LEFT + 1] = 4 * cubeSize - delta - 1
result[cubeSize + delta][0][3 * LEFT + 2] = UP
result[3 * cubeSize - 1][4 * cubeSize - delta - 1][3 * DOWN] = cubeSize + delta
result[3 * cubeSize - 1][4 * cubeSize - delta - 1][3 * DOWN + 1] = 0
result[3 * cubeSize - 1][4 * cubeSize - delta - 1][3 * DOWN + 2] = RIGHT
}
//Link 3 <-> 5
repeat(cubeSize) { delta ->
result[2 * cubeSize - 1][2 * cubeSize - delta - 1][3 * DOWN] = 2 * cubeSize + delta
result[2 * cubeSize - 1][2 * cubeSize - delta - 1][3 * DOWN + 1] = 2 * cubeSize
result[2 * cubeSize - 1][2 * cubeSize - delta - 1][3 * DOWN + 2] = RIGHT
result[2 * cubeSize + delta][2 * cubeSize][3 * LEFT] = 2 * cubeSize - 1
result[2 * cubeSize + delta][2 * cubeSize][3 * LEFT + 1] = 2 * cubeSize - delta - 1
result[2 * cubeSize + delta][2 * cubeSize][3 * LEFT + 2] = UP
}
//Link 4 <-> 6
repeat(cubeSize) { delta ->
result[2 * cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT] = 2 * cubeSize
result[2 * cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT + 1] = 3 * cubeSize + delta
result[2 * cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT + 2] = DOWN
result[2 * cubeSize][3 * cubeSize + delta][3 * UP] = 2 * cubeSize - delta - 1
result[2 * cubeSize][3 * cubeSize + delta][3 * UP + 1] = 3 * cubeSize - 1
result[2 * cubeSize][3 * cubeSize + delta][3 * UP + 2] = LEFT
}
return result
}
private val PATH_FORMAT = Regex("(R|L|\\d+)")
private fun String.parsePath(): List<PathItem> {
return PATH_FORMAT.findAll(this)
.map {
when (it.value) {
"R" -> PathItem.RotationRight
"L" -> PathItem.RotationLeft
else -> PathItem.Move(it.value.toInt())
}
}
.toList()
}
private sealed interface PathItem {
class Move(val stepsCount: Int) : PathItem
object RotationRight : PathItem
object RotationLeft : PathItem
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day22Kt.class",
"javap": "Compiled from \"Day22.kt\"\npublic final class Day22Kt {\n private static final int VOID;\n\n private static final int OPEN;\n\n private static final int WALL;\n\n private static final int RIGHT;\n\n private static final int DOWN;\n\n ... |
Kvest__AOC2022__6409e65/src/Day23.kt | import kotlin.math.max
import kotlin.math.min
fun main() {
val testInput = readInput("Day23_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
private val DIRECTIONS = listOf(
//N, NE, NW
listOf(
intArrayOf(-1, 0),
intArrayOf(-1, 1),
intArrayOf(-1, -1)
),
//S, SE, SW
listOf(
intArrayOf(1, 0),
intArrayOf(1, 1),
intArrayOf(1, -1)
),
//W, NW, SW
listOf(
intArrayOf(0, -1),
intArrayOf(-1, -1),
intArrayOf(1, -1)
),
//E, NE, SE
listOf(
intArrayOf(0, 1),
intArrayOf(-1, 1),
intArrayOf(1, 1)
),
)
private val ALL_ADJACENT = listOf(
intArrayOf(-1, -1),
intArrayOf(-1, 0),
intArrayOf(-1, 1),
intArrayOf(0, 1),
intArrayOf(1, 1),
intArrayOf(1, 0),
intArrayOf(1, -1),
intArrayOf(0, -1),
)
private fun part1(input: List<String>): Int {
var elves = input.toElves()
val moveMap = mutableMapOf<IJ, IJ>()
val counts = mutableMapOf<IJ, Int>()
repeat(10) { iterationNumber ->
moveMap.clear()
counts.clear()
elves.calculateMoves(iterationNumber, moveMap, counts)
elves = elves.applyMoves(moveMap, counts)
}
var iFrom = elves.first().i
var jFrom = elves.first().j
var iTo = iFrom
var jTo = jFrom
elves.forEach {
iFrom = min(iFrom, it.i)
jFrom = min(jFrom, it.j)
iTo = max(iTo, it.i)
jTo = max(jTo, it.j)
}
var count = 0
for (i in iFrom..iTo) {
for (j in jFrom..jTo) {
if (IJ(i, j) !in elves) {
++count
}
}
}
return count
}
private fun part2(input: List<String>): Int {
var elves = input.toElves()
var iterationNumber = 0
val moveMap = mutableMapOf<IJ, IJ>()
val counts = mutableMapOf<IJ, Int>()
while (true) {
moveMap.clear()
counts.clear()
elves.calculateMoves(iterationNumber, moveMap, counts)
if (moveMap.isEmpty()) {
break
}
elves = elves.applyMoves(moveMap, counts)
++iterationNumber
}
return iterationNumber + 1
}
private fun List<String>.toElves(): Set<IJ> {
return this.flatMapIndexed { i, row ->
row.mapIndexedNotNull { j, ch ->
if (ch == '#') {
IJ(i, j)
} else {
null
}
}
}.toSet()
}
private fun Set<IJ>.calculateMoves(
iterationNumber: Int,
moveMap: MutableMap<IJ, IJ>,
counts: MutableMap<IJ, Int>
) {
this.forEach { elf ->
val shouldMove = ALL_ADJACENT.any { delta ->
IJ(elf.i + delta[0], elf.j + delta[1]) in this
}
if (shouldMove) {
val moveDirection = DIRECTIONS.indices.firstNotNullOfOrNull { i ->
DIRECTIONS[(i + iterationNumber) % DIRECTIONS.size].takeIf { dir ->
dir.all { delta -> IJ(elf.i + delta[0], elf.j + delta[1]) !in this }
}
}
if (moveDirection != null) {
val newLocation = IJ(elf.i + moveDirection[0][0], elf.j + moveDirection[0][1])
moveMap[elf] = newLocation
counts[newLocation] = counts.getOrDefault(newLocation, 0) + 1
}
}
}
}
private fun Set<IJ>.applyMoves(
moveMap: MutableMap<IJ, IJ>,
counts: MutableMap<IJ, Int>
): Set<IJ> {
return this.map { elf ->
moveMap[elf]?.takeIf { counts[it] == 1 } ?: elf
}.toSet()
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day23Kt.class",
"javap": "Compiled from \"Day23.kt\"\npublic final class Day23Kt {\n private static final java.util.List<java.util.List<int[]>> DIRECTIONS;\n\n private static final java.util.List<int[]> ALL_ADJACENT;\n\n public static final void main();\n Code:... |
Kvest__AOC2022__6409e65/src/Day05.kt | import java.util.*
fun main() {
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): String =
solve(input) { stacks, cmd ->
repeat(cmd.count) {
stacks[cmd.to].push(stacks[cmd.from].pop())
}
}
private fun part2(input: List<String>): String {
val stack = LinkedList<Char>()
return solve(input) { stacks, cmd ->
repeat(cmd.count) {
stack.push(stacks[cmd.from].pop())
}
while (stack.isNotEmpty()) {
stacks[cmd.to].push(stack.pop())
}
}
}
private fun solve(input: List<String>, reorderStrategy: (List<LinkedList<Char>>, Command) -> Unit): String {
val dividerIndex = input.indexOfFirst { it.isEmpty() }
val stacks = input
.subList(0, dividerIndex)
.toInitialStacks()
input
.subList(dividerIndex + 1, input.lastIndex + 1)
.map(String::toCommand)
.forEach { cmd ->
reorderStrategy(stacks, cmd)
}
return stacks.joinToString(separator = "") {
it.pop().toString()
}
}
private fun List<String>.toInitialStacks(): List<LinkedList<Char>> {
val count = this.last()
.trim()
.drop(
this.last()
.lastIndexOf(' ')
)
.toInt()
val list = List(count) { LinkedList<Char>() }
this.subList(0, this.lastIndex)
.asReversed()
.forEach { row ->
var i = 1
while (i <= row.lastIndex) {
if (row[i].isLetter()) {
list[i / 4].push(row[i])
}
i += 4
}
}
return list
}
private val COMMAND_FORMAT = Regex("move (\\d+) from (\\d+) to (\\d+)")
private fun String.toCommand(): Command {
val match = COMMAND_FORMAT.find(this)
val (move, from, to) = requireNotNull(match).destructured
return Command(from = from.toInt() - 1, to = to.toInt() - 1, count = move.toInt())
}
private class Command(val from: Int, val to: Int, val count: Int) | [
{
"class_path": "Kvest__AOC2022__6409e65/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n private static final kotlin.text.Regex COMMAND_FORMAT;\n\n public static final void main();\n Code:\n 0: ldc #8 // String Day05_test\n 2: ... |
Kvest__AOC2022__6409e65/src/Day21.kt | fun main() {
val testInput = readInput("Day21_test")
val testOperations = testInput.toOperations()
check(part1(testOperations) == 152L)
check(part2(testOperations) == 301L)
val input = readInput("Day21")
val operations = input.toOperations()
println(part1(operations))
println(part2(operations))
}
private fun part1(operations: Map<String, MathOperation>): Long = getValue("root", operations)
private const val TARGET_OPERATION = "humn"
private fun part2(operations: Map<String, MathOperation>): Long {
val rootOp = operations.getValue("root")
val operand1Depends = dependsOn(rootOp.operand1, TARGET_OPERATION, operations)
val targetValue = getValue(
name = if (operand1Depends) rootOp.operand2 else rootOp.operand1,
operations = operations
)
return correctToValue(
name = if (operand1Depends) rootOp.operand1 else rootOp.operand2,
targetValue = targetValue,
targetOperationName = TARGET_OPERATION,
operations = operations
)
}
private fun correctToValue(
name: String,
targetValue: Long,
targetOperationName: String,
operations: Map<String, MathOperation>
): Long {
if (name == targetOperationName) {
return targetValue
}
val op = operations.getValue(name)
val operand1Depends = dependsOn(op.operand1, TARGET_OPERATION, operations)
val anotherOperandValue = getValue(
name = if (operand1Depends) op.operand2 else op.operand1,
operations = operations
)
val nextName = if (operand1Depends) op.operand1 else op.operand2
val nextTargetValue = when (op) {
is MathOperation.Divide ->
if (operand1Depends) {
targetValue * anotherOperandValue
} else {
anotherOperandValue / targetValue
}
is MathOperation.Minus ->
if (operand1Depends) {
targetValue + anotherOperandValue
} else {
anotherOperandValue - targetValue
}
is MathOperation.Multiply -> targetValue / anotherOperandValue
is MathOperation.Plus -> targetValue - anotherOperandValue
is MathOperation.Value -> error("Should not be here")
}
return correctToValue(nextName, nextTargetValue, targetOperationName, operations)
}
private fun dependsOn(
operationName: String,
targetDependency: String,
operations: Map<String, MathOperation>
): Boolean {
if (operationName == targetDependency) {
return true
}
return when (val op = operations.getValue(operationName)) {
is MathOperation.Value -> false
else ->
dependsOn(op.operand1, targetDependency, operations) || dependsOn(op.operand2, targetDependency, operations)
}
}
private fun getValue(name: String, operations: Map<String, MathOperation>): Long {
return when (val op = operations.getValue(name)) {
is MathOperation.Divide -> getValue(op.operand1, operations) / getValue(op.operand2, operations)
is MathOperation.Minus -> getValue(op.operand1, operations) - getValue(op.operand2, operations)
is MathOperation.Multiply -> getValue(op.operand1, operations) * getValue(op.operand2, operations)
is MathOperation.Plus -> getValue(op.operand1, operations) + getValue(op.operand2, operations)
is MathOperation.Value -> op.value
}
}
private fun List<String>.toOperations(): Map<String, MathOperation> = this.associate { row ->
val name = row.substringBefore(":")
val operationStr = row.substringAfter(": ")
val operation = when {
operationStr.contains('+') ->
MathOperation.Plus(
operand1 = operationStr.substringBefore(" + "),
operand2 = operationStr.substringAfter(" + ")
)
operationStr.contains('-') ->
MathOperation.Minus(
operand1 = operationStr.substringBefore(" - "),
operand2 = operationStr.substringAfter(" - ")
)
operationStr.contains('/') ->
MathOperation.Divide(
operand1 = operationStr.substringBefore(" / "),
operand2 = operationStr.substringAfter(" / ")
)
operationStr.contains('*') ->
MathOperation.Multiply(
operand1 = operationStr.substringBefore(" * "),
operand2 = operationStr.substringAfter(" * ")
)
else -> MathOperation.Value(operationStr.toLong())
}
name to operation
}
private sealed interface MathOperation {
class Value(val value: Long) : MathOperation
class Plus(val operand1: String, val operand2: String) : MathOperation
class Minus(val operand1: String, val operand2: String) : MathOperation
class Multiply(val operand1: String, val operand2: String) : MathOperation
class Divide(val operand1: String, val operand2: String) : MathOperation
}
private val MathOperation.operand1: String
get() = when (this) {
is MathOperation.Divide -> this.operand1
is MathOperation.Minus -> this.operand1
is MathOperation.Multiply -> this.operand1
is MathOperation.Plus -> this.operand1
is MathOperation.Value -> error("MathOperation.Value doesn't have operands")
}
private val MathOperation.operand2: String
get() = when (this) {
is MathOperation.Divide -> this.operand2
is MathOperation.Minus -> this.operand2
is MathOperation.Multiply -> this.operand2
is MathOperation.Plus -> this.operand2
is MathOperation.Value -> error("MathOperation.Value doesn't have operands")
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day21Kt.class",
"javap": "Compiled from \"Day21.kt\"\npublic final class Day21Kt {\n private static final java.lang.String TARGET_OPERATION;\n\n public static final void main();\n Code:\n 0: ldc #8 // String Day21_test\n 2:... |
Kvest__AOC2022__6409e65/src/Day17.kt | import java.util.*
fun main() {
val testInput = readInput("Day17_test")[0]
check(part1(testInput) == 3068)
check(part2(testInput) == 1514285714288L)
val input = readInput("Day17")[0]
println(part1(input))
println(part2(input))
}
private const val PART1_ROCKS_COUNT = 2022
private const val PART2_ROCKS_COUNT = 1_000_000_000_000L
private fun part1(input: String): Int {
val shifter = Shifter(input)
val cave = LinkedList<Int>()
val generator = RockGenerator()
repeat(PART1_ROCKS_COUNT) {
val rock = generator.nextRock()
cave.fall(rock, shifter)
}
return cave.size
}
private const val PATTERN_SIZE = 20
private fun part2(input: String): Long {
val shifter = Shifter(input)
val cave = LinkedList<Int>()
val generator = RockGenerator()
var pattern: List<Int>? = null
var patternFoundIteration = 0L
var patternFoundCaveSize = 0
var skippedCaveSize = 0L
var count = PART2_ROCKS_COUNT
while (count > 0) {
val rock = generator.nextRock()
cave.fall(rock, shifter)
--count
//State of the cave repeats iteratively. Find this repetition and use it to skip the huge amount of calculations
if (pattern == null) {
//Try to find pattern
val index = cave.findPattern(PATTERN_SIZE)
if (index >= 0) {
pattern = cave.takeLast(PATTERN_SIZE)
patternFoundIteration = count
patternFoundCaveSize = cave.size
}
} else {
//Wait for the next repetition of the pattern
if (cave.subList(cave.size - PATTERN_SIZE, cave.size) == pattern) {
val rocksPerIteration = patternFoundIteration - count
val caveIncreasePerIteration = cave.size - patternFoundCaveSize
val skippedIterations = count / rocksPerIteration
skippedCaveSize = skippedIterations * caveIncreasePerIteration
count %= rocksPerIteration
}
}
}
return skippedCaveSize + cave.size
}
private fun List<Int>.findPattern(patternSize: Int): Int {
if (this.size < 2 * patternSize) {
return -1
}
val tail = this.subList(this.size - patternSize, this.size)
for (i in (this.size - patternSize) downTo patternSize) {
if (tail == this.subList(i - patternSize, i)) {
return i
}
}
return -1
}
private fun LinkedList<Int>.fall(rock: IntArray, shifter: Shifter) {
val caveRows = IntArray(rock.size)
//First 4 shifts happen before rock will rich the most top row of the cave
repeat(4) {
shifter.next().invoke(rock, caveRows)
}
var bottom = this.lastIndex
while (true) {
if (bottom == -1) {
break
}
for (i in caveRows.lastIndex downTo 1) {
caveRows[i] = caveRows[i - 1]
}
caveRows[0] = this[bottom]
val canFall = rock.foldIndexed(true) { i, acc, value -> acc && (value and caveRows[i] == 0) }
if (canFall) {
--bottom
} else {
break
}
shifter.next().invoke(rock, caveRows)
}
rock.forEachIndexed { i, value ->
if ((bottom + i + 1) in this.indices) {
this[bottom + i + 1] = this[bottom + i + 1] or value
} else {
this.addLast(value)
}
}
}
private const val LEFT_BORDER = 0b1000000
private const val RIGHT_BORDER = 0b0000001
class Shifter(private val pattern: String) {
private var current: Int = 0
private val left: (IntArray, IntArray) -> Unit = { rock, caveRows ->
val canShift = rock.foldIndexed(true) { i, acc, value ->
acc && ((value and LEFT_BORDER) == 0) && ((value shl 1) and caveRows[i] == 0)
}
if (canShift) {
rock.forEachIndexed { i, value -> rock[i] = value shl 1 }
}
}
private val right: (IntArray, IntArray) -> Unit = { rock, caveRows ->
val canShift = rock.foldIndexed(true) { i, acc, value ->
acc && (value and RIGHT_BORDER == 0) && ((value shr 1) and caveRows[i] == 0)
}
if (canShift) {
rock.forEachIndexed { i, value -> rock[i] = value shr 1 }
}
}
fun next(): (IntArray, IntArray) -> Unit {
return (if (pattern[current] == '<') left else right).also {
current = (current + 1) % pattern.length
}
}
}
private class RockGenerator {
private var i = 0
val rocks = listOf(
intArrayOf(
0b0011110,
),
intArrayOf(
0b0001000,
0b0011100,
0b0001000,
),
intArrayOf(
0b0011100,
0b0000100,
0b0000100,
),
intArrayOf(
0b0010000,
0b0010000,
0b0010000,
0b0010000,
),
intArrayOf(
0b0011000,
0b0011000,
),
)
fun nextRock(): IntArray {
return rocks[i].copyOf().also {
i = (i + 1) % rocks.size
}
}
}
| [
{
"class_path": "Kvest__AOC2022__6409e65/Day17Kt.class",
"javap": "Compiled from \"Day17.kt\"\npublic final class Day17Kt {\n private static final int PART1_ROCKS_COUNT;\n\n private static final long PART2_ROCKS_COUNT;\n\n private static final int PATTERN_SIZE;\n\n private static final int LEFT_BORDER;\... |
Kvest__AOC2022__6409e65/src/Day07.kt | import java.util.*
fun main() {
val testInput = readInput("Day07_test")
val testRoot = buildFileSystem(testInput)
val testSizeCache = mutableMapOf<Node, Long>()
check(part1(testRoot, testSizeCache) == 95437L)
check(part2(testRoot, testSizeCache) == 24933642L)
val input = readInput("Day07")
val root = buildFileSystem(input)
val sizeCache = mutableMapOf<Node, Long>()
println(part1(root, sizeCache))
println(part2(root, sizeCache))
}
private const val MAX = 100000L
private fun part1(root: Node, sizeCache: MutableMap<Node, Long>): Long {
var result = 0L
root.visit { node ->
if (node.isDir) {
val size = sizeCache.getOrPut(node, node::size)
if (size < MAX) {
result += size
}
}
}
return result
}
private const val TOTAL_SPACE = 70000000L
private const val TARGET_FREE_SPACE = 30000000L
private fun part2(root: Node, sizeCache: MutableMap<Node, Long>): Long {
val rootSize = sizeCache.getOrPut(root, root::size)
val spaceToFreeUp = TARGET_FREE_SPACE - (TOTAL_SPACE - rootSize)
var result = Long.MAX_VALUE
root.visit { node ->
if (node.isDir) {
val size = sizeCache.getOrPut(node, node::size)
if (size >= spaceToFreeUp && size < result) {
result = size
}
}
}
return result
}
private fun buildFileSystem(commands: List<String>): Node {
val root = Node.Dir()
val navigationStack = LinkedList<Node>()
var i = 0
while (i <= commands.lastIndex) {
val cmd = commands[i++]
when {
cmd.startsWith("$ cd /") -> {
navigationStack.clear()
navigationStack.push(root)
}
cmd.startsWith("$ cd ..") -> navigationStack.pop()
cmd.startsWith("$ cd ") -> {
val destinationName = cmd.substringAfter("$ cd ")
val destination = navigationStack.peek().getChild(destinationName)
navigationStack.push(destination)
}
cmd.startsWith("$ ls") -> {
val targetNode = navigationStack.peek()
while (i <= commands.lastIndex && !commands[i].startsWith("$")) {
val item = commands[i++]
if (item.startsWith("dir")) {
targetNode.addChild(
name = item.substringAfter("dir "),
child = Node.Dir()
)
} else {
targetNode.addChild(
name = item.substringAfter(" "),
child = Node.File(
size = item.substringBefore(" ").toLong()
)
)
}
}
}
}
}
return root
}
sealed interface Node {
val isDir: Boolean
fun getChild(name: String): Node
fun addChild(name: String, child: Node)
fun size(): Long
fun visit(action: (Node) -> Unit)
class Dir : Node {
private val children = mutableMapOf<String, Node>()
override val isDir: Boolean
get() = true
override fun getChild(name: String): Node = children[name] ?: error("Child $name not found")
override fun addChild(name: String, child: Node) {
children[name] = child
}
override fun size(): Long {
return children.values.fold(0) { acc, node -> acc + node.size() }
}
override fun visit(action: (Node) -> Unit) {
children.forEach { it.value.visit(action) }
action(this)
}
}
class File(val size: Long) : Node {
override val isDir: Boolean
get() = false
override fun getChild(name: String): Node = error("getChild is not applicable for File")
override fun addChild(name: String, child: Node) = error("addChild is not applicable for File")
override fun size(): Long = size
override fun visit(action: (Node) -> Unit) {
action(this)
}
}
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day07Kt.class",
"javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt {\n private static final long MAX;\n\n private static final long TOTAL_SPACE;\n\n private static final long TARGET_FREE_SPACE;\n\n public static final void main();\n Code:\n ... |
Kvest__AOC2022__6409e65/src/Day06.kt | fun main() {
val testInput = readInput("Day06_test")
check(part1(testInput[0]) == 5)
check(part1(testInput[1]) == 6)
check(part1(testInput[2]) == 10)
check(part1(testInput[3]) == 11)
check(part2(testInput[0]) == 23)
check(part2(testInput[1]) == 23)
check(part2(testInput[2]) == 29)
check(part2(testInput[3]) == 26)
val input = readInput("Day06")
println(part1(input[0]))
println(part2(input[0]))
}
private fun part1(input: String): Int = findUniqueSequence(input, 4)
private fun part2(input: String): Int = findUniqueSequence(input, 14)
private fun findUniqueSequence(input: String, targetCount: Int): Int {
val counts = mutableMapOf<Char, Int>()
repeat(targetCount - 1) { i ->
counts[input[i]] = counts.getOrDefault(input[i], 0) + 1
}
for (i in (targetCount - 1)..input.lastIndex) {
counts[input[i]] = counts.getOrDefault(input[i], 0) + 1
if (counts.size == targetCount) {
return i + 1
}
if (counts[input[i - targetCount + 1]] == 1) {
counts.remove(input[i - targetCount + 1])
} else {
counts[input[i - targetCount + 1]] = counts.getValue(input[i - targetCount + 1]) - 1
}
}
error("Not found")
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day06Kt.class",
"javap": "Compiled from \"Day06.kt\"\npublic final class Day06Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day06_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day16.kt | import java.util.*
import kotlin.math.max
fun main() {
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
private const val PART1_MINUTES = 30
private const val PART2_MINUTES = 26
private const val START_VALVE = "AA"
private fun part1(input: List<String>): Int {
val valves = input.parseInputAndOptimize()
val bitsMapper = valves.calcBitsMapper()
return solve(
minutesLeft = PART1_MINUTES,
name = START_VALVE,
openedBitmask = 0,
valves = valves,
bitsMapper = bitsMapper
)
}
private fun part2(input: List<String>): Int {
val valves = input.parseInputAndOptimize()
val bitsMapper = valves.calcBitsMapper()
val valvesToOpen = bitsMapper.keys.toList() - START_VALVE
val allBits = valvesToOpen.fold(0L) { acc, valve -> acc or bitsMapper.getValue(valve) }
val memo = mutableMapOf<Long, Int>()
//Brut-force all possible variants where some valves will be opened by me and the rest - by elephant
return valvesToOpen.allCombinations()
.map { valves ->
valves.fold(0L) { acc, valve -> acc or bitsMapper.getValue(valve) }
}
.maxOf { valveBits ->
val otherBits = allBits and valveBits.inv()
val first = memo.getOrPut(valveBits) {
solve(
minutesLeft = PART2_MINUTES,
name = START_VALVE,
openedBitmask = valveBits,
valves = valves,
bitsMapper = bitsMapper
)
}
val second = memo.getOrPut(otherBits) {
solve(
minutesLeft = PART2_MINUTES,
name = START_VALVE,
openedBitmask = otherBits,
valves = valves,
bitsMapper = bitsMapper
)
}
first + second
}
}
private fun solve(
minutesLeft: Int,
name: String,
openedBitmask: Long,
valves: Map<String, Valve>,
bitsMapper: Map<String, Long>,
memo: MutableMap<String, Int> = mutableMapOf()
): Int {
val key = "${minutesLeft}_${name}_$openedBitmask"
if (key in memo) {
return memo.getValue(key)
}
val valve = valves.getValue(name)
val resultInc = valve.rate * minutesLeft
var result = resultInc
valve.destinations.forEach { (nextName, timeToReachAndOpen) ->
val nextBit = bitsMapper.getValue(nextName)
if (minutesLeft > timeToReachAndOpen && (openedBitmask and nextBit) == 0L) {
result = max(
result,
resultInc + solve(
minutesLeft = minutesLeft - timeToReachAndOpen,
name = nextName,
openedBitmask = (openedBitmask or nextBit),
valves = valves,
bitsMapper = bitsMapper,
memo = memo
)
)
}
}
memo[key] = result
return result
}
private val ROW_FORMAT = Regex("Valve ([A-Z]+) has flow rate=(\\d+); tunnel[s]? lead[s]? to valve[s]? ([A-Z, ]+)")
private fun List<String>.parseInputAndOptimize(): Map<String, Valve> {
val rates = mutableMapOf<String, Int>()
val tunnelsFromValve = mutableMapOf<String, List<String>>()
this.forEach {
val match = ROW_FORMAT.find(it)
val (valve, rate, tunnels) = requireNotNull(match).destructured
rates[valve] = rate.toInt()
tunnelsFromValve[valve] = tunnels.split(", ")
}
// Consider only valves with rate > 0
// Don't forget to add START valve
return rates.filter { it.value > 0 || it.key == START_VALVE }
.mapValues { (name, rate) ->
Valve(
rate = rate,
destinations = buildTunnelsChains(name, tunnelsFromValve, rates)
)
}
}
private fun buildTunnelsChains(
start: String,
tunnels: Map<String, List<String>>,
rates: Map<String, Int>
): List<Destination> {
return buildList {
val queue = PriorityQueue<Pair<String, Int>> { a, b -> a.second - b.second }
queue.offer(start to 0)
val visited = mutableSetOf<String>()
while (queue.isNotEmpty()) {
val (name, time) = queue.poll()
if (name in visited) {
continue
}
visited.add(name)
if (rates.getValue(name) > 0 && name != start) {
add(Destination(name, time + 1)) //add 1 minute for opening
}
tunnels[name]?.forEach { next ->
queue.offer(next to time + 1)
}
}
}
}
private fun Map<String, Valve>.calcBitsMapper(): Map<String, Long> {
var i = 1L
return this.mapValues {
val res = i
i = i shl 1
res
}
}
private data class Valve(
val rate: Int,
val destinations: List<Destination>
)
private data class Destination(
val name: String,
val timeToReachAndOpen: Int
) | [
{
"class_path": "Kvest__AOC2022__6409e65/Day16Kt.class",
"javap": "Compiled from \"Day16.kt\"\npublic final class Day16Kt {\n private static final int PART1_MINUTES;\n\n private static final int PART2_MINUTES;\n\n private static final java.lang.String START_VALVE;\n\n private static final kotlin.text.Re... |
Kvest__AOC2022__6409e65/src/Day20.kt | fun main() {
val testInput = readInput("Day20_test")
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Long = solve(input, String::toLong, mixesCount = 1)
private fun part2(input: List<String>): Long = solve(input, String::part2Converter, mixesCount = 10)
private fun String.part2Converter(): Long = this.toLong() * 811589153L
private fun solve(input: List<String>, converter: String.() -> Long, mixesCount: Int): Long {
val nodes = input.map { LinkedNode(it.converter()) }
var zeroIndex = -1
for (i in nodes.indices) {
nodes[i].next = if (i < nodes.lastIndex) nodes[i + 1] else nodes.first()
nodes[i].prev = if (i > 0) nodes[i - 1] else nodes.last()
if (nodes[i].value == 0L) {
zeroIndex = i
}
}
repeat(mixesCount) {
nodes.forEach { node ->
val count = correctMovesCount(node.value, nodes.size)
if (count > 0) {
var target = node
repeat(count) {
target = target.next
}
//delete node from chain
node.prev.next = node.next
node.next.prev = node.prev
//insert node to the new position
node.next = target.next
target.next.prev = node
target.next = node
node.prev = target
}
}
}
var node = nodes[zeroIndex]
var result = 0L
repeat(3_001) {
if (it == 1_000 || it == 2_000 || it == 3_000) {
result += node.value
}
node = node.next
}
return result
}
private fun correctMovesCount(count: Long, size: Int): Int {
return if (count > 0) {
//reduce the full cycles
(count % (size - 1)).toInt()
} else {
//(size + (count % (size - 1)) - 1) - this converts negative steps to positive steps
// % (size - 1) - this reduce the full cycles when the steps count is more than the items in the chain
((size + (count % (size - 1)) - 1) % (size - 1)).toInt()
}
}
private class LinkedNode(val value: Long) {
lateinit var next: LinkedNode
lateinit var prev: LinkedNode
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day20Kt.class",
"javap": "Compiled from \"Day20.kt\"\npublic final class Day20Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day20_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day25.kt | fun main() {
val testInput = readInput("Day25_test")
check(part1(testInput) == "2=-1=0")
val input = readInput("Day25")
println(part1(input))
}
private fun part1(input: List<String>): String {
val sum = input.sumOf(String::SNAFUToInt)
return sum.toSNAFU()
}
private fun String.SNAFUToInt(): Long {
var result = 0L
var pow = 1L
for (i in this.lastIndex downTo 0) {
result += when (this[i]) {
'-' -> -pow
'=' -> -2L * pow
else -> this[i].digitToInt() * pow
}
pow *= 5L
}
return result
}
private fun Long.toSNAFU(): String {
var tmp = this
var result = ""
while (tmp != 0L) {
val rem = tmp % 5L
tmp /= 5L
if (rem <= 2) {
result = rem.toString() + result
} else {
++tmp
result = when (rem) {
3L -> "="
4L -> "-"
else -> error(Unit)
} + result
}
}
return result
}
| [
{
"class_path": "Kvest__AOC2022__6409e65/Day25Kt.class",
"javap": "Compiled from \"Day25.kt\"\npublic final class Day25Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day25_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day13.kt | fun main() {
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
return input.windowed(size = 2, step = 3)
.map { list -> list.map { it.parseList() } }
.mapIndexed { index, (first, second) ->
if (checkOrder(first.values, second.values) == Order.RIGHT) index + 1 else 0
}
.sum()
}
private fun part2(input: List<String>): Int {
val dividerPackets = listOf(
"[[2]]".parseList(),
"[[6]]".parseList(),
)
val originalPackets = input
.filter { it.isNotEmpty() }
.map(String::parseList)
return (originalPackets + dividerPackets)
.sortedWith(ListValueComparator)
.mapIndexed { index, listValue ->
if (listValue in dividerPackets) index + 1 else 1
}
.reduce { acc, value -> acc * value }
}
private object ListValueComparator : Comparator<ListValue> {
override fun compare(left: ListValue, right: ListValue): Int =
checkOrder(left.values, right.values).value
}
private fun String.parseList(
fromIndex: Int = 0,
finishedIndex: IntArray = intArrayOf(fromIndex)
): ListValue {
check(this[fromIndex] == '[') { "This is not start of the list" }
var current = fromIndex + 1
val result = mutableListOf<Value>()
while (current <= this.lastIndex) {
when (this[current]) {
',' -> ++current
']' -> break
'[' -> {
val nested = this.parseList(current, finishedIndex)
result.add(nested)
current = finishedIndex[0] + 1
}
else -> {
val to = this.indexOfAny(chars = charArrayOf(',', ']'), startIndex = current)
val intValue = this.substring(current, to).toInt()
result.add(IntValue(intValue))
current = if (this[to] == ',') {
to + 1
} else {
to
}
}
}
}
finishedIndex[0] = current
return ListValue(result)
}
private fun checkOrder(left: List<Value>, right: List<Value>): Order {
for (i in left.indices) {
if (i > right.lastIndex) {
return Order.WRONG
}
val leftItem = left[i]
val rightItem = right[i]
if (leftItem is IntValue && rightItem is IntValue) {
if (leftItem.value < rightItem.value) return Order.RIGHT
if (leftItem.value > rightItem.value) return Order.WRONG
} else {
val result = checkOrder(
left = if (leftItem is ListValue) leftItem.values else listOf(leftItem),
right = if (rightItem is ListValue) rightItem.values else listOf(rightItem)
)
if (result != Order.UNKNOWN) return result
}
}
return if (left.size < right.size) Order.RIGHT else Order.UNKNOWN
}
private sealed interface Value
private class IntValue(val value: Int) : Value
private class ListValue(val values: List<Value>) : Value
private enum class Order(val value: Int) {
UNKNOWN(0), RIGHT(-1), WRONG(1)
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day13Kt.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day13_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day03.kt | fun main() {
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
return input.sumOf(::calculatePriority)
}
private fun part2(input: List<String>): Int {
return input
.chunked(3) { group ->
commonPriority(group[0], group[1], group[2])
}
.sum()
}
private fun calculatePriority(row: String): Int {
val second = row.takeLast(row.length / 2).toSet()
row.forEach { ch ->
if (ch in second) {
return ch.toPriority()
}
}
error("Not found")
}
private fun commonPriority(first: String, second: String, third: String): Int {
val secondSet = second.toSet()
val thirdSet = third.toSet()
first.forEach { ch ->
if (ch in secondSet && ch in thirdSet) {
return ch.toPriority()
}
}
error("Not found")
}
private fun Char.toPriority(): Int {
return if (this.isLowerCase()) {
1 + code - 'a'.code
} else {
27 + code - 'A'.code
}
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day03_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day02.kt | fun main() {
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
return input.sumOf(String::toScore)
}
private fun part2(input: List<String>): Int {
return input
.map(String::correctMove)
.sumOf(String::toScore)
}
private val SCORES = mapOf(
"AX" to 4,
"AY" to 8,
"AZ" to 3,
"BX" to 1,
"BY" to 5,
"BZ" to 9,
"CX" to 7,
"CY" to 2,
"CZ" to 6,
)
private fun String.toScore(): Int {
return SCORES.getValue("${this[0]}${this[2]}")
}
private val CORRECTIONS = mapOf(
"AX" to "A Z",
"AY" to "A X",
"AZ" to "A Y",
"BX" to "B X",
"BY" to "B Y",
"BZ" to "B Z",
"CX" to "C Y",
"CY" to "C Z",
"CZ" to "C X",
)
private fun String.correctMove(): String {
return CORRECTIONS.getValue("${this[0]}${this[2]}")
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n private static final java.util.Map<java.lang.String, java.lang.Integer> SCORES;\n\n private static final java.util.Map<java.lang.String, java.lang.String> CORRECTIONS;\n\n public ... |
Kvest__AOC2022__6409e65/src/Day12.kt | import java.util.*
fun main() {
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>, ): Int = solve(input, startMarkers = setOf('S'))
private fun part2(input: List<String>, ): Int = solve(input, startMarkers = setOf('S', 'a'))
private fun solve(input: List<String>, startMarkers: Set<Char>): Int {
val area = input.toMatrix()
val starts = input.findAllChars(startMarkers)
val end = input.findChar('E')
val visited = mutableSetOf<IJ>()
val queue = PriorityQueue<Item>()
starts.forEach {
queue.offer(Item(0, it))
}
while (queue.isNotEmpty()) {
val (steps, ij) = queue.poll()
if (ij in visited) {
continue
}
if (ij == end) {
return steps
}
val (i, j) = ij
if (i > 0 && (area[i - 1][j] - area[i][j]) <= 1) {
queue.offer(Item(steps + 1, IJ(i - 1, j)))
}
if (j > 0 && (area[i][j - 1] - area[i][j]) <= 1) {
queue.offer(Item(steps + 1, IJ(i, j - 1)))
}
if (i < area.lastIndex && (area[i + 1][j] - area[i][j]) <= 1) {
queue.offer(Item(steps + 1, IJ(i + 1, j)))
}
if (j < area[i].lastIndex && (area[i][j + 1] - area[i][j]) <= 1) {
queue.offer(Item(steps + 1, IJ(i, j + 1)))
}
visited.add(ij)
}
error("Path not found")
}
private fun List<String>.toMatrix(): Matrix {
return Array(this.size) { i ->
IntArray(this[i].length) { j ->
when (this[i][j]) {
'S' -> 0
'E' -> 'z'.code - 'a'.code
else -> this[i][j].code - 'a'.code
}
}
}
}
private fun List<String>.findChar(target: Char): IJ {
this.forEachIndexed { i, row ->
row.forEachIndexed { j, ch ->
if (ch == target) {
return IJ(i, j)
}
}
}
error("$target not found")
}
private fun List<String>.findAllChars(targets: Set<Char>): List<IJ> {
val result = mutableListOf<IJ>()
this.forEachIndexed { i, row ->
row.forEachIndexed { j, ch ->
if (ch in targets) {
result.add(IJ(i, j))
}
}
}
return result
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day12Kt.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class Day12Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day12_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day24.kt | import java.util.*
fun main() {
val testInput = readInput("Day24_test")
val testMap = BlizzardMap(testInput)
check(part1(testMap) == 18)
check(part2(testMap) == 54)
val input = readInput("Day24")
val map = BlizzardMap(input)
println(part1(map))
println(part2(map))
}
private fun part1(map: BlizzardMap): Int {
val initialMap = map[0]
val startI = 0
val startJ = initialMap[startI].indexOfFirst { it }
val targetI = initialMap.lastIndex
val targetJ = initialMap[targetI].indexOfFirst { it }
return solve(
map = map,
startMinute = 0,
startI = startI,
startJ = startJ,
targetI = targetI,
targetJ = targetJ,
)
}
private fun part2(map: BlizzardMap): Int {
val initialMap = map[0]
val startI = 0
val startJ = initialMap[startI].indexOfFirst { it }
val targetI = initialMap.lastIndex
val targetJ = initialMap[targetI].indexOfFirst { it }
val m1 = solve(
map = map,
startMinute = 0,
startI = startI,
startJ = startJ,
targetI = targetI,
targetJ = targetJ,
)
val m2 = solve(
map = map,
startMinute = m1,
startI = targetI,
startJ = targetJ,
targetI = startI,
targetJ = startJ,
)
val m3 = solve(
map = map,
startMinute = m2,
startI = startI,
startJ = startJ,
targetI = targetI,
targetJ = targetJ,
)
return m3
}
private fun solve(
map: BlizzardMap,
startMinute: Int,
startI: Int,
startJ: Int,
targetI: Int,
targetJ: Int
): Int {
val queue = PriorityQueue<Item>()
queue.offer(Item(startMinute, IJ(startI, startJ)))
val visited = mutableSetOf<Int>()
while (queue.isNotEmpty()) {
val (minute, ij) = queue.poll()
val (i, j) = ij
val key = minute * 1_000_000 + i * 1_000 + j
if (key in visited) {
continue
}
visited.add(key)
if (i == targetI && j == targetJ) {
return minute
}
val currentMap = map[minute + 1]
if (currentMap[i][j]) {
queue.offer(Item(minute + 1, IJ(i, j)))
}
if (i > 0 && currentMap[i - 1][j]) {
queue.offer(Item(minute + 1, IJ(i - 1, j)))
}
if (i < currentMap.lastIndex && currentMap[i + 1][j]) {
queue.offer(Item(minute + 1, IJ(i + 1, j)))
}
if (j > 0 && currentMap[i][j - 1]) {
queue.offer(Item(minute + 1, IJ(i, j - 1)))
}
if (j < currentMap[i].lastIndex && currentMap[i][j + 1]) {
queue.offer(Item(minute + 1, IJ(i, j + 1)))
}
}
error("Path not found")
}
private class BlizzardMap(initialState: List<String>) {
private val cache = mutableListOf<BooleanMatrix>()
private val template: BooleanMatrix
private val blizzards: List<Blizzard>
init {
blizzards = buildList {
initialState.forEachIndexed { i, row ->
row.forEachIndexed { j, ch ->
when (ch) {
'>' -> add(Blizzard(MutableIJ(i, j), BlizzardDirection.RIGHT))
'v' -> add(Blizzard(MutableIJ(i, j), BlizzardDirection.DOWN))
'<' -> add(Blizzard(MutableIJ(i, j), BlizzardDirection.LEFT))
'^' -> add(Blizzard(MutableIJ(i, j), BlizzardDirection.UP))
}
}
}
}
template = Array(initialState.size) { i ->
BooleanArray(initialState[i].length) { j ->
initialState[i][j] != '#'
}
}
//generate default map
generateNextMap()
}
operator fun get(i: Int): BooleanMatrix {
while (cache.lastIndex < i) {
generateNextMap()
}
return cache[i]
}
private fun generateNextMap() {
val next = template.deepCopyOf()
blizzards.forEach {
with(it) {
next[position.i][position.j] = false
//Also, move blizzard to the new position
when (direction) {
BlizzardDirection.RIGHT -> position.j = if (position.j < (template[0].lastIndex - 1)) {
position.j + 1
} else {
1
}
BlizzardDirection.DOWN -> position.i = if (position.i < (template.lastIndex - 1)) {
position.i + 1
} else {
1
}
BlizzardDirection.LEFT -> position.j = if (position.j > 1) {
position.j - 1
} else {
template[0].lastIndex - 1
}
BlizzardDirection.UP -> position.i = if (position.i > 1) {
position.i - 1
} else {
template.lastIndex - 1
}
}
}
}
cache.add(next)
}
}
private enum class BlizzardDirection { RIGHT, DOWN, LEFT, UP }
private class Blizzard(
val position: MutableIJ,
val direction: BlizzardDirection,
)
| [
{
"class_path": "Kvest__AOC2022__6409e65/Day24Kt.class",
"javap": "Compiled from \"Day24.kt\"\npublic final class Day24Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day24_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day09.kt | import kotlin.math.abs
import kotlin.math.sign
fun main() {
val testInput1 = readInput("Day09_test1")
val testInput2 = readInput("Day09_test2")
check(part1(testInput1) == 13)
check(part2(testInput1) == 1)
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int = solve(input, ropeSize = 2)
private fun part2(input: List<String>): Int = solve(input, ropeSize = 10)
private fun solve(input: List<String>, ropeSize: Int): Int {
val rope = List(ropeSize) { MutableXY(0, 0) }
val adjacentKnots = rope.windowed(2, 1)
val head = rope.first()
val tail = rope.last()
val visitedCells = mutableSetOf<XY>()
var dx = 0
var dy = 0
input.forEach { action ->
val cnt = action.substringAfter(" ").toInt()
when {
action.startsWith("L") -> {
dx = -1
dy = 0
}
action.startsWith("R") -> {
dx = 1
dy = 0
}
action.startsWith("U") -> {
dx = 0
dy = 1
}
action.startsWith("D") -> {
dx = 0
dy = -1
}
}
repeat(cnt) {
head.x += dx
head.y += dy
adjacentKnots.forEach { (first, second) ->
adjustKnotes(first, second)
}
visitedCells.add(tail.toXY())
}
}
return visitedCells.size
}
private fun adjustKnotes(first: MutableXY, second: MutableXY) {
if (abs(first.x - second.x) >= 2 || abs(first.y - second.y) >= 2) {
second.x = second.x + 1 * (first.x - second.x).sign
second.y = second.y + 1 * (first.y - second.y).sign
}
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day09Kt.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day09_test1\n 2: invokestatic #14 // Method UtilsKt.readInp... |
Kvest__AOC2022__6409e65/src/Day19.kt | import kotlin.math.max
import kotlin.math.min
fun main() {
val testInput = readInput("Day19_test")
val testBlueprints = testInput.map(Blueprint.Companion::fromString)
check(part1(testBlueprints) == 33)
val input = readInput("Day19")
val blueprints = input.map(Blueprint.Companion::fromString)
println(part1(blueprints))
println(part2(blueprints))
}
private fun part1(blueprints: List<Blueprint>): Int {
return blueprints.sumOf {
it.number * calculateMaxGeodes(it, 24)
}
}
private fun part2(blueprints: List<Blueprint>): Int {
return calculateMaxGeodes(blueprints[0], 32) *
calculateMaxGeodes(blueprints[1], 32) *
calculateMaxGeodes(blueprints[2], 32)
}
private fun calculateMaxGeodes(
blueprint: Blueprint,
minutesLeft: Int,
memo: MutableMap<Long, Int> = mutableMapOf(),
oreRobotsCount: Int = 1,
clayRobotsCount: Int = 0,
obsidianRobotsCount: Int = 0,
geodesRobotsCount: Int = 0,
oreCount: Int = 0,
clayCount: Int = 0,
obsidianCount: Int = 0,
geodesCount: Int = 0,
): Int {
if (minutesLeft == 0) {
return geodesCount
}
//Throw out resources, which can't be potentially spend by the end of the minutesLeft.
//This reduces a lot of recursive calls because it collapse overlapping states
val oreForKey = min(oreCount, minutesLeft * blueprint.oreMax)
val clayForKey = min(clayCount, minutesLeft * blueprint.clayMax)
val obsidianForKey = min(obsidianCount, minutesLeft * blueprint.obsidianMax)
val key = minutesLeft * 1_000_000_000_000_000_000L +
oreRobotsCount * 10_000_000_000_000_000L +
clayRobotsCount * 100_000_000_000_000L +
obsidianRobotsCount * 1000_000_000_000L +
geodesRobotsCount * 10_000_000_000L +
oreForKey * 100_000_000L +
clayForKey * 1_000_000L +
obsidianForKey * 10_000L +
geodesCount * 100L
if (key in memo) {
return memo.getValue(key)
}
var result = 0
val canBuildOreRobot = oreCount >= blueprint.oreForOreRobot && oreRobotsCount < blueprint.oreMax
val canBuildClayRobot = oreCount >= blueprint.oreForClayRobot && clayRobotsCount < blueprint.clayMax
val canBuildObsidianRobot =
oreCount >= blueprint.oreForObsidianRobot && clayCount >= blueprint.clayForObsidianRobot && obsidianCount <= blueprint.obsidianMax
val canBuildGeodeRobot = oreCount >= blueprint.oreForGeodeRobot && obsidianCount >= blueprint.obsidianForGeodeRobot
if (canBuildGeodeRobot) {
result = max(
result,
calculateMaxGeodes(
blueprint = blueprint,
minutesLeft = minutesLeft - 1,
memo = memo,
oreRobotsCount = oreRobotsCount,
clayRobotsCount = clayRobotsCount,
obsidianRobotsCount = obsidianRobotsCount,
geodesRobotsCount = geodesRobotsCount + 1,
oreCount = oreCount + oreRobotsCount - blueprint.oreForGeodeRobot,
clayCount = clayCount + clayRobotsCount,
obsidianCount = obsidianCount + obsidianRobotsCount - blueprint.obsidianForGeodeRobot,
geodesCount = geodesCount + geodesRobotsCount
)
)
}
if (canBuildObsidianRobot) {
result = max(
result,
calculateMaxGeodes(
blueprint = blueprint,
minutesLeft = minutesLeft - 1,
memo = memo,
oreRobotsCount = oreRobotsCount,
clayRobotsCount = clayRobotsCount,
obsidianRobotsCount = obsidianRobotsCount + 1,
geodesRobotsCount = geodesRobotsCount,
oreCount = oreCount + oreRobotsCount - blueprint.oreForObsidianRobot,
clayCount = clayCount + clayRobotsCount - blueprint.clayForObsidianRobot,
obsidianCount = obsidianCount + obsidianRobotsCount,
geodesCount = geodesCount + geodesRobotsCount
)
)
}
if (canBuildClayRobot) {
result = max(
result,
calculateMaxGeodes(
blueprint = blueprint,
minutesLeft = minutesLeft - 1,
memo = memo,
oreRobotsCount = oreRobotsCount,
clayRobotsCount = clayRobotsCount + 1,
obsidianRobotsCount = obsidianRobotsCount,
geodesRobotsCount = geodesRobotsCount,
oreCount = oreCount + oreRobotsCount - blueprint.oreForClayRobot,
clayCount = clayCount + clayRobotsCount,
obsidianCount = obsidianCount + obsidianRobotsCount,
geodesCount = geodesCount + geodesRobotsCount
)
)
}
if (canBuildOreRobot) {
result = max(
result,
calculateMaxGeodes(
blueprint = blueprint,
minutesLeft = minutesLeft - 1,
memo = memo,
oreRobotsCount = oreRobotsCount + 1,
clayRobotsCount = clayRobotsCount,
obsidianRobotsCount = obsidianRobotsCount,
geodesRobotsCount = geodesRobotsCount,
oreCount = oreCount + oreRobotsCount - blueprint.oreForOreRobot,
clayCount = clayCount + clayRobotsCount,
obsidianCount = obsidianCount + obsidianRobotsCount,
geodesCount = geodesCount + geodesRobotsCount
)
)
}
result = max(
result,
calculateMaxGeodes(
blueprint = blueprint,
minutesLeft = minutesLeft - 1,
memo = memo,
oreRobotsCount = oreRobotsCount,
clayRobotsCount = clayRobotsCount,
obsidianRobotsCount = obsidianRobotsCount,
geodesRobotsCount = geodesRobotsCount,
oreCount = oreCount + oreRobotsCount,
clayCount = clayCount + clayRobotsCount,
obsidianCount = obsidianCount + obsidianRobotsCount,
geodesCount = geodesCount + geodesRobotsCount
)
)
memo[key] = result
return result
}
private val BLUEPRINT_FORMAT =
Regex("Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.")
private class Blueprint(
val number: Int,
val oreForOreRobot: Int,
val oreForClayRobot: Int,
val oreForObsidianRobot: Int,
val clayForObsidianRobot: Int,
val oreForGeodeRobot: Int,
val obsidianForGeodeRobot: Int,
) {
val oreMax: Int by lazy { maxOf(oreForOreRobot, oreForClayRobot, oreForObsidianRobot, oreForGeodeRobot) }
val clayMax: Int
get() = clayForObsidianRobot
val obsidianMax: Int
get() = obsidianForGeodeRobot
companion object {
fun fromString(str: String): Blueprint {
val match = BLUEPRINT_FORMAT.find(str)
val (number, oreForOreRobot, oreForClayRobot, oreForObsidianRobot, clayForObsidianRobot, oreForGeodeRobot, obsidianForGeodeRobot) = requireNotNull(
match
).destructured
return Blueprint(
number.toInt(),
oreForOreRobot.toInt(),
oreForClayRobot.toInt(),
oreForObsidianRobot.toInt(),
clayForObsidianRobot.toInt(),
oreForGeodeRobot.toInt(),
obsidianForGeodeRobot.toInt()
)
}
}
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day19Kt.class",
"javap": "Compiled from \"Day19.kt\"\npublic final class Day19Kt {\n private static final kotlin.text.Regex BLUEPRINT_FORMAT;\n\n public static final void main();\n Code:\n 0: ldc #8 // String Day19_test\n 2... |
Kvest__AOC2022__6409e65/src/Day18.kt | import kotlin.math.max
fun main() {
val testInput = readInput("Day18_test")
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val cubes = input.to3DMatrix()
return solve(input, cubes)
}
private fun part2(input: List<String>): Int {
val cubes = input.to3DMatrix()
val water = fillWithWater(cubes)
return solve(input, water)
}
private fun solve(input: List<String>, emptyCubes: Boolean3DMatrix): Int {
return input.sumOf {
var cnt = 0
val (xStr,yStr,zStr) = it.split(",")
val x = xStr.toInt()
val y = yStr.toInt()
val z = zStr.toInt()
if (emptyCubes.isEmpty(x + 1, y, z)) cnt++
if (emptyCubes.isEmpty(x - 1, y, z)) cnt++
if (emptyCubes.isEmpty(x, y + 1, z)) cnt++
if (emptyCubes.isEmpty(x, y - 1, z)) cnt++
if (emptyCubes.isEmpty(x, y, z + 1)) cnt++
if (emptyCubes.isEmpty(x, y, z - 1)) cnt++
cnt
}
}
private fun List<String>.to3DMatrix(): Boolean3DMatrix {
var xMax = 0
var yMax = 0
var zMax = 0
this.forEach {
val (x,y,z) = it.split(",")
xMax = max(xMax, x.toInt())
yMax = max(yMax, y.toInt())
zMax = max(zMax, z.toInt())
}
val result = Array(xMax + 1) {
Array(yMax + 1) {
BooleanArray(zMax + 1)
}
}
this.forEach {
val (x, y, z) = it.split(",")
result[x.toInt()][y.toInt()][z.toInt()] = true
}
return result
}
private fun fillWithWater(cubes: Boolean3DMatrix): Boolean3DMatrix {
val result = Array(cubes.size) {
Array(cubes[0].size) {
BooleanArray(cubes[0][0].size) { true }
}
}
val xLastIndex = cubes.lastIndex
val yLastIndex = cubes[0].lastIndex
val zLastIndex = cubes[0][0].lastIndex
for (x in cubes.indices) {
for (y in cubes[0].indices) {
fill(cubes, result, x, y, 0)
fill(cubes, result, x, y, zLastIndex)
}
}
for (x in cubes.indices) {
for (z in cubes[0][0].indices) {
fill(cubes, result, x, 0, z)
fill(cubes, result, x, yLastIndex, z)
}
}
for (y in cubes[0].indices) {
for (z in cubes[0][0].indices) {
fill(cubes, result, 0, y, z)
fill(cubes, result, xLastIndex, y, z)
}
}
return result
}
private fun fill(cubes: Boolean3DMatrix, water: Boolean3DMatrix, x: Int, y: Int, z: Int) {
if (!water.isXYZInside(x, y, z) || cubes[x][y][z] || !water[x][y][z]) {
return
}
water[x][y][z] = false
fill(cubes, water, x + 1, y, z)
fill(cubes, water, x - 1, y, z)
fill(cubes, water, x, y + 1, z)
fill(cubes, water, x, y - 1, z)
fill(cubes, water, x, y, z + 1)
fill(cubes, water, x, y, z - 1)
}
private fun Boolean3DMatrix.isEmpty(x: Int, y: Int, z: Int): Boolean {
return if (this.isXYZInside(x, y, z)) {
!this[x][y][z]
} else {
true
}
}
private fun Boolean3DMatrix.isXYZInside(x: Int, y: Int, z: Int): Boolean {
return (x in this.indices && y in this[x].indices && z in this[x][y].indices)
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day18Kt.class",
"javap": "Compiled from \"Day18.kt\"\npublic final class Day18Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day18_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day08.kt | fun main() {
val testInput = readInput("Day08_test").toMatrix()
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08").toMatrix()
println(part1(input))
println(part2(input))
}
private fun part1(input: Matrix): Int {
val width = input[0].size
val height = input.size
var result = height * 2 + width * 2 - 4
val used = Array(height) { BooleanArray(width) { false } }
val row = IntArray(width) { input[0][it] }
val column = IntArray(height) { input[it][0] }
fun updateResult(i: Int, j: Int) {
if (!used[i][j]) {
++result
used[i][j] = true
}
}
fun checkItem(i: Int, j: Int) {
if (input[i][j] > column[i]) {
updateResult(i, j)
column[i] = input[i][j]
}
if (input[i][j] > row[j]) {
updateResult(i, j)
row[j] = input[i][j]
}
}
//top-to-bottom, left-to-right pass
for (i in 1..(height - 2)) {
for (j in 1..(width - 2)) {
checkItem(i, j)
}
}
for (i in 1..(height - 2)) {
column[i] = input[i][width - 1]
}
for (j in 1..(width - 2)) {
row[j] = input[height - 1][j]
}
//bottom-to-top, right-to-left pass
for (i in (height - 2) downTo 1) {
for (j in (width - 2) downTo 1) {
checkItem(i, j)
}
}
return result
}
private fun part2(input: Matrix): Int {
var result = 0
val width = input[0].size
val height = input.size
for (i in 1..(height - 2)) {
for (j in 1..(width - 2)) {
val digit = input[i][j]
var top = i - 1
while (top > 0 && digit > input[top][j]) {
--top
}
var left = j - 1
while (left > 0 && digit > input[i][left]) {
--left
}
var right = j + 1
while (right < width - 1 && digit > input[i][right]) {
++right
}
var bottom = i + 1
while (bottom < height - 1 && digit > input[bottom][j]) {
++bottom
}
val mul = (i - top) * (j - left) * (right - j) * (bottom - i)
if (mul > result) {
result = mul
}
}
}
return result
}
private fun List<String>.toMatrix(): Matrix {
return Array(this.size) { i ->
IntArray(this[i].length) { j ->
this[i][j].digitToInt()
}
}
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day08Kt.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day08_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day01.kt | fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
return input.toCalories().maxOrNull() ?: 0
}
private fun part2(input: List<String>): Int {
return input
.toCalories()
.sorted()
.takeLast(3)
.sum()
}
private fun List<String>.toCalories(): List<Int> {
val result = mutableListOf<Int>()
var current = 0
this.forEach { row ->
if (row.isEmpty()) {
result.add(current)
current = 0
} else {
current += row.toInt()
}
}
result.add(current)
return result
}
| [
{
"class_path": "Kvest__AOC2022__6409e65/Day01Kt.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day01_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
Kvest__AOC2022__6409e65/src/Day11.kt | import java.util.*
fun main() {
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Long {
val monkeys = input.toMonkeys()
val worryLevelAdjuster = WorryLevelAdjuster { worryLevel ->
worryLevel / 3
}
return solve(monkeys, roundsCount = 20, worryLevelAdjuster)
}
private fun part2(input: List<String>): Long {
val monkeys = input.toMonkeys()
//Use divider in order to avoid overflow of the worryLevel's variable
val divider = monkeys.fold(1L) { acc, monkey -> acc * monkey.test.testValue }
val worryLevelAdjuster = WorryLevelAdjuster { worryLevel ->
worryLevel % divider
}
return solve(monkeys, roundsCount = 10_000, worryLevelAdjuster)
}
private fun solve(
monkeys: List<Monkey>,
roundsCount: Int,
worryLevelAdjuster: WorryLevelAdjuster
): Long {
val counts = LongArray(monkeys.size) { 0 }
val redirectListener = RedirectListener { monkeyNumber, worryLevel ->
monkeys[monkeyNumber].items.addLast(worryLevel)
}
repeat(roundsCount) {
monkeys.forEachIndexed { index, monkey ->
//monkey will inspect "monkey.items.size" in this round
counts[index] += monkey.items.size.toLong()
monkey.round(worryLevelAdjuster, redirectListener)
}
}
counts.sortDescending()
return counts[0] * counts[1]
}
private fun List<String>.toMonkeys(): List<Monkey> = this.chunked(7).map(List<String>::toMonkey)
private fun List<String>.toMonkey(): Monkey {
val initialItems = this[1]
.substringAfter("Starting items: ")
.split(", ")
.map { it.toLong() }
val operation = Operation.fromString(this[2])
val testValue = this[3].substringAfter("Test: divisible by ").toLong()
val trueDestination = this[4].substringAfter("If true: throw to monkey ").toInt()
val falseDestination = this[5].substringAfter("If false: throw to monkey ").toInt()
val test = Test(
testValue = testValue,
trueDestination = trueDestination,
falseDestination = falseDestination
)
return Monkey(initialItems, operation, test)
}
private fun interface RedirectListener {
fun redirect(monkeyNumber: Int, worryLevel: Long)
}
private fun interface WorryLevelAdjuster {
fun adjust(worryLevel: Long): Long
}
private class Monkey(
initialItems: List<Long>,
val operation: Operation,
val test: Test
) {
val items = LinkedList(initialItems)
fun round(worryLevelAdjuster: WorryLevelAdjuster, redirectListener: RedirectListener) {
while (items.isNotEmpty()) {
var worryLevel = items.pollFirst()
worryLevel = operation.perform(worryLevel)
worryLevel = worryLevelAdjuster.adjust(worryLevel)
val monkeyNumber = test.test(worryLevel)
redirectListener.redirect(monkeyNumber, worryLevel)
}
}
}
sealed interface Operation {
fun perform(worryLevel: Long): Long
companion object {
fun fromString(operation: String): Operation {
return when {
operation.contains("Operation: new = old * old") -> SqrOperation
operation.contains("Operation: new = old +") -> AdditionOperation(
incValue = operation.substringAfter("Operation: new = old + ").toLong()
)
operation.contains("Operation: new = old *") -> MultiplicationOperation(
factor = operation.substringAfter("Operation: new = old * ").toLong()
)
else -> error("Unknown operation $operation")
}
}
}
class AdditionOperation(private val incValue: Long) : Operation {
override fun perform(worryLevel: Long): Long = worryLevel + incValue
}
class MultiplicationOperation(private val factor: Long) : Operation {
override fun perform(worryLevel: Long): Long = worryLevel * factor
}
object SqrOperation : Operation {
override fun perform(worryLevel: Long): Long = worryLevel * worryLevel
}
}
private class Test(
val testValue: Long,
val trueDestination: Int,
val falseDestination: Int,
) {
fun test(worryLevel: Long): Int = if (worryLevel % testValue == 0L) trueDestination else falseDestination
} | [
{
"class_path": "Kvest__AOC2022__6409e65/Day11Kt.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class Day11Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day11_test\n 2: invokestatic #14 // Method UtilsKt.readInpu... |
getupminaaa__Algorithm__01187e2/Algorithm/src/main/kotlin/programmers/level1/personalInfoCollectionValidityPeriod.kt | import java.util.*
fun main() {
val solution = Solution()
val terms: Array<String> = arrayOf("A 6", "B 12", "C 3")
val privacies: Array<String> = arrayOf("2021.05.02 A", "2021.07.01 B", "2022.02.19 C", "2022.02.20 C")
solution.solution(today = "2022.05.19", terms, privacies)
}
class Solution {
fun solution(today: String, terms: Array<String>, privacies: Array<String>): IntArray {
var answer: IntArray = intArrayOf()
//오늘 날짜 변환
var tDates: Int = 0
val todayArray: List<String> = today.split(".", ".")
tDates += todayArray[0].toInt() * 12 * 28
tDates += todayArray[1].toInt() * 28
tDates += todayArray[2].toInt()
for (i in privacies.indices) {
var pDates: Int = 0
val privaciesArray: List<String> = privacies[i].split(".", ".", " ")
pDates += privaciesArray[0].toInt() * 12 * 28
pDates += privaciesArray[1].toInt() * 28
pDates += privaciesArray[2].toInt()
for (j in terms.indices) {
if (terms[j].split("\\s+".toRegex()).first() == privaciesArray[3]) {
pDates += terms[j].split("\\s+".toRegex()).last().toInt() * 28
if (tDates >= pDates) {
answer += i + 1
}
}
}
}
print(Arrays.toString(answer))
return answer
}
} | [
{
"class_path": "getupminaaa__Algorithm__01187e2/PersonalInfoCollectionValidityPeriodKt.class",
"javap": "Compiled from \"personalInfoCollectionValidityPeriod.kt\"\npublic final class PersonalInfoCollectionValidityPeriodKt {\n public static final void main();\n Code:\n 0: new #8 ... |
saikatsgupta__aoc-2022-in-kotlin__2c491a9/src/Day03.kt | fun main() {
fun Char.getPriority(): Int {
return when {
isUpperCase() -> code - 'A'.code + 27
else -> code - 'a'.code + 1
}
}
fun part1(input: List<String>): Int {
return input.sumOf {
val compartment1 = it.take(it.length / 2)
val compartment2 = it.takeLast(it.length / 2)
(compartment1.toSet() intersect compartment2.toSet()).single().getPriority()
}
}
fun part2(input: List<String>): Int {
return (input.indices step 3)
.map { listOf(input[it].toSet(), input[it + 1].toSet(), input[it + 2].toSet()) }
.sumOf { ((it[0] intersect it[1]) intersect it[2]).single().getPriority() }
}
}
| [
{
"class_path": "saikatsgupta__aoc-2022-in-kotlin__2c491a9/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: return\n\n public static void main(java.lang.String[]);\n Code:\n 0: invokestatic #9 ... |
iam-abbas__cs-algorithms__d04aa8f/Kotlin/heap_sort_in_kotlin.kt | var heapSize = 0
fun left(i: Int): Int {
return 2 * i
}
fun right(i: Int): Int {
return 2 * i + 1
}
fun swap(A: Array<Int>, i: Int, j: Int) {
var temp = A[i]
A[i] = A[j]
A[j] = temp
}
fun max_heapify(A: Array<Int>, i: Int) {
var l = left(i);
var r = right(i);
var largest: Int;
if ((l <= heapSize - 1) && (A[l] > A[i])) {
largest = l;
} else
largest = i
if ((r <= heapSize - 1) && (A[r] > A[l])) {
largest = r
}
if (largest != i) {
swap(A, i, largest);
max_heapify(A, largest);
}
}
fun buildMaxheap(A: Array<Int>) {
heapSize = A.size
for (i in heapSize / 2 downTo 0) {
max_heapify(A, i)
}
}
fun heap_sort(A: Array<Int>) {
buildMaxheap(A)
for (i in A.size - 1 downTo 1) {
swap(A, i, 0)
heapSize = heapSize - 1
max_heapify(A, 0)
}
}
fun main(arg: Array<String>) {
print("Enter no. of elements :")
var n = readLine()!!.toInt()
println("Enter elements : ")
var A = Array(n, { 0 })
for (i in 0 until n)
A[i] = readLine()!!.toInt()
heap_sort(A)
println("Sorted array is : ")
for (i in 0 until n)
print("${A[i]} ")
}
| [
{
"class_path": "iam-abbas__cs-algorithms__d04aa8f/Heap_sort_in_kotlinKt.class",
"javap": "Compiled from \"heap_sort_in_kotlin.kt\"\npublic final class Heap_sort_in_kotlinKt {\n private static int heapSize;\n\n public static final int getHeapSize();\n Code:\n 0: getstatic #10 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.