kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
sviams__aoc23__4914a54/src/main/kotlin/day1.kt
object day1 { val digitMap = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9" ) fun firstAndLast(input: String): String { val onlyDigits = input.toCharArray().filter { it.isDigit() } val res = "" + onlyDigits.first() + onlyDigits.last() return res } fun replaceSpelledOutDigits(input: String): String { val res = input.fold("") { acc, c -> val next = acc + c if (digitMap.keys.any { next.contains(it) }) { digitMap.entries.fold(next) { acc2, (spelledOut, asDigit) -> acc2.replace(spelledOut, asDigit) } + c } else next } return res } fun pt1(input: List<String>): Int = input.map { firstAndLast(it).toInt() }.sum() fun pt2(input: List<String>): Int = input.map { firstAndLast(replaceSpelledOutDigits(it)).toInt() }.sum() }
[ { "class_path": "sviams__aoc23__4914a54/day1.class", "javap": "Compiled from \"day1.kt\"\npublic final class day1 {\n public static final day1 INSTANCE;\n\n private static final java.util.Map<java.lang.String, java.lang.String> digitMap;\n\n private day1();\n Code:\n 0: aload_0\n 1: invoke...
sviams__aoc23__4914a54/src/main/kotlin/day3.kt
import kotlin.math.max import kotlin.math.min object day3 { data class Number(val chars: String, val startIndex: Int, val row: Int) { fun toInt() = chars.toInt() val range by lazy { IntRange(startIndex, startIndex+chars.length-1) } fun isAdjacentToSymbol(world: List<Line>): Boolean = (-1 .. 1).fold(emptyList<Symbol>()) { acc, offset -> acc + getSymbolsInRange(world, row+offset, range) }.any() } data class Symbol(val char: Char, val col: Int, val row: Int) { fun isGearSymbol() = char == '*' val range by lazy { IntRange(col-1, col+1) } fun adjacentNumbers(world: List<Line>): List<Number> = (-1 .. 1).fold(emptyList()) { acc, offset -> acc + getNumbersInRange(world, row+offset, range) } fun gearRatio(world: List<Line>): Int { val nums = adjacentNumbers(world).map { it.toInt() } return nums.first() * nums.last() } } fun getNumbersInRange(world: List<Line>, row: Int, range: IntRange) = if (row < 0 || row >= world.size) emptyList() else world[row].numbers.filter { range.intersect(it.range).any() } fun getSymbolsInRange(world: List<Line>, row: Int, range: IntRange) = if (row < 0 || row >= world.size) emptyList() else world[row].symbols.filter { range.intersect(it.range).any() } data class Line(val numbers: List<Number>, val symbols: List<Symbol>) tailrec fun numbersFromLine(line: String, row: Int, res: List<Number> = emptyList(), currentNum: String = "", currentStart: Int = -1, index: Int = 0): List<Number> { if (index == line.length) return if (!currentNum.isEmpty()) res + Number(currentNum, currentStart, row) else res val atIndex = line[index] val newCurrentNum = if (atIndex.isDigit()) currentNum + atIndex else "" val newStart = if (currentNum == "" && atIndex.isDigit()) index else currentStart val newRes = if (!atIndex.isDigit() && !currentNum.isEmpty()) res + Number(currentNum, currentStart, row) else res return numbersFromLine(line, row, newRes, newCurrentNum, newStart, index+1) } fun parseInput(input: List<String>) = input.foldIndexed(emptyList<Line>()) { row, linesRes, line -> val nums = numbersFromLine(line, row) val symbols = line.foldIndexed(emptyList<Symbol>()) { col, acc, c -> if (!c.isDigit() && c != '.') acc + Symbol(c, col, row) else acc } linesRes + Line(nums, symbols) } fun pt1(input: List<String>): Int { val world = parseInput(input) return world.fold(0) { acc, line -> val hasAdjacent = line.numbers.filter { it.isAdjacentToSymbol(world) } acc + hasAdjacent.sumOf { it.toInt() } } } fun pt2(input: List<String>): Int { val world = parseInput(input) return world.fold(0) { acc, line -> val actualGears = line.symbols.filter {it.isGearSymbol() && it.adjacentNumbers(world).size == 2 } acc + actualGears.sumOf { it.gearRatio(world) } } } }
[ { "class_path": "sviams__aoc23__4914a54/day3$Line.class", "javap": "Compiled from \"day3.kt\"\npublic final class day3$Line {\n private final java.util.List<day3$Number> numbers;\n\n private final java.util.List<day3$Symbol> symbols;\n\n public day3$Line(java.util.List<day3$Number>, java.util.List<day3$S...
sviams__aoc23__4914a54/src/main/kotlin/day4.kt
object day4 { data class Card(val id: Int, val winning: List<Int>, val mine: List<Int>) { val matches by lazy { mine.intersect(winning) } val value by lazy { if (matches.isEmpty()) 0 else ( 0 until matches.size-1).fold(1) { acc, i -> acc * 2 } } val copies by lazy { matches.indices.fold(emptyList<Int>()) { acc, i -> acc.plus(id+i+1) } } } fun parseInput(input: List<String>): List<Card> = input.fold(emptyList<Card>()) { acc, line -> val (id) = Regex("""Card\s+(\d+):""").find(line)!!.destructured val parts = line.split(':').last().split('|') val winning = parts[0].split(' ').filterNot { it.isEmpty() }.map { it.toInt() } val mine = parts[1].split(' ').filterNot { it.isEmpty() }.map { it.toInt() } acc + Card(id.toInt(), winning, mine) } fun pt1(input: List<String>): Int = parseInput(input).sumOf { it.value } fun pt2(input: List<String>): Int = parseInput(input) .reversed() .fold(emptyMap<Int, Int>()) { res, card -> res + (card.id to (1 + card.copies.sumOf { res[it]!! }))}.values.sum() }
[ { "class_path": "sviams__aoc23__4914a54/day4.class", "javap": "Compiled from \"day4.kt\"\npublic final class day4 {\n public static final day4 INSTANCE;\n\n private day4();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retur...
cuuzis__adventofcode__35e56aa/2020/december09.kt
import java.io.File /** * https://adventofcode.com/2020/day/9 */ fun main() { val weakNumber = star1() println(weakNumber) // 85848519 println(star2(weakNumber)) // 13414198 } private fun input(): List<String> { return File("2020/december09.txt").readLines(); } private val preambleSize = 25 private fun star1(): Long { val lines = input().map(String::toLong) for (lineNum in preambleSize until lines.size) { val num = lines[lineNum] var isWeak = true for (i in lineNum - preambleSize until lineNum) { val num1 = lines[i] for (j in i + 1 until lineNum) { val num2 = lines[j]; if (num1 + num2 == num) { isWeak = false } } } if (isWeak) { return num } } return -1L } private fun star2(weakNumber: Long): Long { val lines = input().map(String::toLong) var start = 0 var end = 1 var sum = lines[0] + lines[1] while (start < end && end < lines.size) { if (sum < weakNumber) { // increase window end++ sum += lines[end] } else if (sum > weakNumber) { // decrease window sum -= lines[start] start++ } else if (sum == weakNumber) { // find min + max within window var min = lines[start] var max = lines[start] for (i in start..end) { if (lines[i] > max) { max = lines[i] } else if (lines[i] < min) { min = lines[i] } } return min + max } } return -1L }
[ { "class_path": "cuuzis__adventofcode__35e56aa/December09Kt.class", "javap": "Compiled from \"december09.kt\"\npublic final class December09Kt {\n private static final int preambleSize;\n\n public static final void main();\n Code:\n 0: invokestatic #10 // Method star1:()J\n ...
cuuzis__adventofcode__35e56aa/2020/december10.kt
import java.io.File /** * https://adventofcode.com/2020/day/10 */ fun main() { println(star1()) // 1998 println(star2()) // 347250213298688 } private fun input(): List<String> { return File("2020/december10.txt").readLines(); } private fun star1(): Int { val adapters = input().map(String::toLong).sorted() var prev = 0L var ones = 0 var threes = 0 for (curr in adapters) { if (curr - prev == 3L) { threes++ } else if (curr - prev == 1L) { ones++ } prev = curr } // your device's built-in adapter is always 3 higher than the highest adapter threes++ //println("${ones} * ${threes}") return ones * threes } private fun star2(): Long { val adapters = input().map(String::toLong).sorted() var prev1 = 0L var prev1paths = 1L var prev2 = -99L var prev2paths = 1L var prev3 = -99L var prev3paths = 1L for (curr in adapters) { var pathsToCurr = 0L if (curr - prev1 <= 3L) { pathsToCurr += prev1paths } if (curr - prev2 <= 3L) { pathsToCurr += prev2paths } if (curr - prev3 <= 3L) { pathsToCurr += prev3paths } prev3 = prev2 prev2 = prev1 prev1 = curr prev3paths = prev2paths prev2paths = prev1paths prev1paths = pathsToCurr } return prev1paths }
[ { "class_path": "cuuzis__adventofcode__35e56aa/December10Kt.class", "javap": "Compiled from \"december10.kt\"\npublic final class December10Kt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method star1:()I\n 3: istore_0\n 4: getstatic #16 ...
kormeian__kotlin_koans__550c822/Generics/Generic functions/src/Task.kt
fun <T, C : MutableCollection<T>> Collection<T>.partitionTo( first: C, second: C, predicate: (T) -> Boolean ): Pair<C, C> { this.forEach { if (predicate(it)) first.add(it) else second.add(it) } return Pair(first, second) } fun partitionWordsAndLines() { val (words, lines) = listOf("a", "a b", "c", "d e") .partitionTo(ArrayList(), ArrayList()) { s -> !s.contains(" ") } check(words == listOf("a", "c")) check(lines == listOf("a b", "d e")) } fun partitionLettersAndOtherSymbols() { val (letters, other) = setOf('a', '%', 'r', '}') .partitionTo(HashSet(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z' } check(letters == setOf('a', 'r')) check(other == setOf('%', '}')) }
[ { "class_path": "kormeian__kotlin_koans__550c822/TaskKt.class", "javap": "Compiled from \"Task.kt\"\npublic final class TaskKt {\n public static final <T, C extends java.util.Collection<T>> kotlin.Pair<C, C> partitionTo(java.util.Collection<? extends T>, C, C, kotlin.jvm.functions.Function1<? super T, java...
aquatir__code-samples__eac3328/code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/algo/sorts.kt
fun <T> swap(array: Array<T>, fstIndex: Int, sndIndex: Int) { val fstValue = array[fstIndex] array[fstIndex] = array[sndIndex] array[sndIndex] = fstValue } /** Selection sort: Find the smallest -> insert it to next position */ fun <T : Comparable<T>> selectionSort(array: Array<T>) { for (i in array.indices) { var curMinIndex = i for (j in (i + 1) until array.size) { if (array[j] < array[curMinIndex]) { curMinIndex = j } } swap(array, i, curMinIndex) } } /** Insertion sort: Assume everything before i is sorted. * Add another element to sorted part -> swap elements until current element is in it's correct place */ fun <T : Comparable<T>> insertionSort(array: Array<T>) { for (i in array.indices) { for (j in i downTo 1) { if (array[j] < array[j - 1]) { swap(array, j, j - 1) } else { break } } } } /** h-sort with sequence 3x+1 */ fun <T : Comparable<T>> shellSort(array: Array<T>) { var h = 1 while (h < array.size / 3) { h = 3 * h + 1 // 1, 4, 13, 40... } while (h >= 1) { // h-sort array here with step == h for (i in h until array.size) { for (j in i downTo h step h) { if (array[j] < array[j - h]) { swap(array, j, j - h) } else { continue } } } h /= 3 } } fun <T : Comparable<T>> mergeSort(array: Array<T>) { fun sort(array: Array<T>, auxArray: Array<T>, startIndex: Int, endIndex: Int) { if (endIndex <= startIndex) return val middle = startIndex + ((endIndex - startIndex) / 2) sort(array, auxArray, startIndex = 0, endIndex = middle) sort(array, auxArray, startIndex = middle + 1, endIndex = endIndex) merge(array, auxArray, leftStart = 0, leftEnd = middle, rightStart = middle + 1, rightEnd = endIndex) } val aux = array.copyOf() sort(array, aux, startIndex = 0, endIndex = array.lastIndex) } fun <T : Comparable<T>> bottomUpMergeSort(array: Array<T>) { val aux = array.copyOf() val n = array.size var step = 1 while (step < n) { // this will iterate over arrays of 2, than 4, than 8, until the end var index = 0 while (index < n - step) { merge( array, aux, leftStart = index, leftEnd = index + step - 1, rightStart = index + step, rightEnd = minOf(n - 1, index + step + step - 1) ) index += step + step } step += step } /* * Implementation can be much shorter for language which support 3 part for-loops. It will be as simpel as * for (step = 1; step < n; step = step + step) { * for (i = 0; i < n - step; i += step + step) { * merge (array, aux, i, i + step - 1, i + step, minOf(n - 1, i + step + step - 1) * } * } */ } fun <T : Comparable<T>> merge( array: Array<T>, auxArray: Array<T>, leftStart: Int, leftEnd: Int, rightStart: Int, rightEnd: Int ) { for (i in leftStart..rightEnd) { auxArray[i] = array[i] } var left = leftStart var right = rightStart for (index in leftStart..rightEnd) { when { left > leftEnd -> { array[index] = auxArray[right] right++ } right > rightEnd -> { array[index] = auxArray[left] left++ } auxArray[left] <= auxArray[right] -> { array[index] = auxArray[left]; left++ } else -> { array[index] = auxArray[right]; right++ } } } } fun <T : Comparable<T>> quickSort(array: Array<T>) { fun partition(array: Array<T>, startLeft: Int, startRight: Int): Int { /* First element is used as partition element After outer while(true) loop completes, all element to the left of startLeft will be lower and all element to right of it will be higher. Here we start with startLeft and startRight + 1 because the first thing we do before comparing is ++left and --right */ var left = startLeft var right = startRight + 1 while (true) { while (array[++left] < array[startLeft]) { if (left == startRight) { break } } while (array[startLeft] < array[--right]) { if (right == startLeft) { break } } if (left >= right) break swap(array, left, right) } swap(array, startLeft, right) return right // right is now in place } fun sort(array: Array<T>, startLeft: Int, startRight: Int) { if (startRight <= startLeft) return val inCorrectPlaceIndex = partition(array, startLeft, startRight) sort(array, startLeft, inCorrectPlaceIndex - 1) sort(array, inCorrectPlaceIndex + 1, startRight) } array.shuffle() sort(array, 0, array.lastIndex) }
[ { "class_path": "aquatir__code-samples__eac3328/SortsKt.class", "javap": "Compiled from \"sorts.kt\"\npublic final class SortsKt {\n public static final <T> void swap(T[], int, int);\n Code:\n 0: aload_0\n 1: ldc #10 // String array\n 3: invokestatic #16 ...
nerok__Advent-of-code-2021__4dee925/src/main/kotlin/day8.kt
import java.io.File import java.util.* fun main(args: Array<String>) { day8part2() } fun day8part1() { val countArray = IntArray(8) { 0 } val input = File("day8input.txt").bufferedReader().readLines() input.map { line -> line.split(" | ").map { it.split(" ") }.let { it.first() to it.last() } }.map { entry -> entry.first.groupBy { it.length } to entry.second.groupBy { it.length } }.map { it.second }.forEach { it.forEach { countArray[it.key] += it.value.size } } val countMap = countArray.mapIndexed { index, i -> index to i }.toMap() println("Score: ${countMap[2]!!.plus(countMap[3]!!).plus(countMap[4]!!).plus(countMap[7]!!)}") } fun day8part2() { val countArray = IntArray(8) { 0 } val input = File("day8input.txt").bufferedReader().readLines() input.map { line -> line.split(" | ").map { it.split(" ") }.let { it.first().map { it.toSortedSet() } to it.last().map { it.toSortedSet() } } }.map { val map = predictPairs(it.first) Integer.parseInt(it.second.map { map[it] }.let { it.joinToString("") }) }.also { println(it) }.also { println(it.sum()) } } fun predictPairs(x: List<SortedSet<Char>>): MutableMap<SortedSet<Char>, Int> { val map = x.associateWith { -1 }.toMutableMap() map.forEach { when (it.key.size) { 2 -> { map[it.key] = 1 } 3 -> { map[it.key] = 7 } 4 -> { map[it.key] = 4 } 7 -> { map[it.key] = 8 } else -> { } } } map.filter { it.key.size == 6 }.forEach { if (it.key.containsAll(map.filterValues { it == 4 }.keys.first())) { map[it.key] = 9 } else if (it.key.containsAll(map.filterValues { it == 1 }.keys.first())) { map[it.key] = 0 } else { map[it.key] = 6 } } map.filter { it.value == -1 }.forEach { if (it.key.containsAll(map.filterValues { it == 7 }.keys.first())) { map[it.key] = 3 } else if (map.filterValues { it == 9 }.keys.first().containsAll(it.key)) { map[it.key] = 5 } else { map[it.key] = 2 } } return map }
[ { "class_path": "nerok__Advent-of-code-2021__4dee925/Day8Kt.class", "javap": "Compiled from \"day8.kt\"\npublic final class Day8Kt {\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 ...
nerok__Advent-of-code-2021__4dee925/src/main/kotlin/day3.kt
import java.io.File fun main(args: Array<String>) { day3part2() } fun day3part1() { val countArray = IntArray(12) { 0 } val input = File("day3input.txt").bufferedReader().readLines() input.map { it.mapIndexed { index, value -> if (value == '1') { countArray[index] = (countArray[index] + 1) } else { countArray[index] = (countArray[index] - 1) } } } countArray.forEach { print(if (it > 0) "1" else "0") } } fun day3part2() { val input = File("day3input.txt") .bufferedReader() .readLines() .map { line -> line.split("") .filter { it.isNotEmpty() } .map { it.toInt() } } val majority = getMajority(input, 0) val highset = input.filter { it[0] == majority } val lowset = input.filter { it[0] != majority } val oxygenRating = higherReduction(highset) val CO2Rating = smallerReduction(lowset) val oxygenRatingDecimal = Integer.parseInt(oxygenRating.joinToString(separator = "") { it.toString() }, 2) val CO2RatingDecimal = Integer.parseInt(CO2Rating.joinToString(separator = "") { it.toString() }, 2) println(oxygenRatingDecimal) println(CO2RatingDecimal) println("${oxygenRatingDecimal*CO2RatingDecimal}") } private fun getMajority(input: List<List<Int>>, index: Int): Int { return input.map { it[index] }.let { if (it.sum()*2 == it.size) { 1 } else if (it.sum() == 2 && it.size == 3) { 1 } else if (it.sum() > it.size / 2) 1 else 0 } } fun higherReduction(set: List<List<Int>>): List<Int> { var reductionSet = set var index = 1 while (reductionSet.size > 1) { val majority = getMajority(reductionSet, index) reductionSet = reductionSet.filter { it[index] == majority } index += 1 } return reductionSet.first() } fun smallerReduction(set: List<List<Int>>): List<Int> { var reductionSet = set var index = 1 while (reductionSet.size > 1) { val majority = getMajority(reductionSet, index) reductionSet = reductionSet.filter { it[index] != majority } index += 1 } return reductionSet.first() }
[ { "class_path": "nerok__Advent-of-code-2021__4dee925/Day3Kt.class", "javap": "Compiled from \"day3.kt\"\npublic final class Day3Kt {\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 ...
nerok__Advent-of-code-2021__4dee925/src/main/kotlin/day4.kt
import java.io.File fun main(args: Array<String>) { day4() } fun day4() { val input = File("day4input.txt").bufferedReader() val drawings = input.readLine().split(",").map { it.toInt() } input.readLines() .asSequence() .windowed(6, step = 6) .map { board -> board.filter { it.isNotEmpty() } } .map { board -> board.map { row -> row.split(" ") .filter { it.isNotEmpty() } .map { it.toInt() } .toMutableList() } } .map { board -> calculateScore(board, drawings) } //.minByOrNull for part 1 //.maxByOrNull for part 2 .maxByOrNull { it.first }!!.also { println(it) } } fun calculateScore(bingoBoard: List<MutableList<Int>>, drawing: List<Int>): Pair<Int, Int> { drawing.forEachIndexed { drawNumber, draw -> bingoBoard.mapIndexed { index, ints -> if (ints.contains(draw)) { index to ints.indexOf(draw) } else { null } }.filterNotNull().forEach { coordinate -> bingoBoard[coordinate.first][coordinate.second] = 0 if (bingoBoard[coordinate.first].none { it != 0 }) { return drawNumber to bingoBoard.sumOf { it.sum() } * drawing[drawNumber] } else if (bingoBoard.map { row -> row[coordinate.second] }.none { it != 0 }) { return drawNumber to bingoBoard.sumOf { it.sum() } * drawing[drawNumber] } } } return 0 to 0 }
[ { "class_path": "nerok__Advent-of-code-2021__4dee925/Day4Kt.class", "javap": "Compiled from \"day4.kt\"\npublic final class Day4Kt {\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 ...
nerok__Advent-of-code-2021__4dee925/src/main/kotlin/day5.kt
import java.io.File import kotlin.math.abs fun main(args: Array<String>) { val lines = File("day5input.txt").reader() var coordinates = mutableListOf<List<Pair<Int, Int>>>() var size = 0 lines.forEachLine { fileLine -> fileLine .split("->") .map { coordinates -> coordinates .split(",") .map { coordinate -> Integer.parseInt(coordinate.filter { !it.isWhitespace() }).also { if (it > size) { size = it } } }.let { it.first() to it.last() } }.let { coordinatePair -> if (coordinatePair.first().first == coordinatePair.last().first) { val lowerEnd = minOf(coordinatePair.first().second, coordinatePair.last().second) val higherEnd = maxOf(coordinatePair.first().second, coordinatePair.last().second) return@let IntRange(lowerEnd, higherEnd).map { coordinatePair.first().first to it } } else if (coordinatePair.first().second == coordinatePair.last().second) { val lowerEnd = minOf(coordinatePair.first().first, coordinatePair.last().first) val higherEnd = maxOf(coordinatePair.first().first, coordinatePair.last().first) return@let IntRange(lowerEnd, higherEnd).map { it to coordinatePair.first().second } } else { val firstDistance = abs(coordinatePair.first().first - coordinatePair.last().first) val secondDistance = abs(coordinatePair.first().second - coordinatePair.last().second) if (firstDistance == secondDistance) { val lowerFirst = minOf(coordinatePair.first().first, coordinatePair.last().first) val higherFirst = maxOf(coordinatePair.first().first, coordinatePair.last().first) val firstRange = IntRange(lowerFirst, higherFirst).toList() val lowerSecond = minOf(coordinatePair.first().second, coordinatePair.last().second) val higherSecond = maxOf(coordinatePair.first().second, coordinatePair.last().second) val secondRange = IntRange(lowerSecond, higherSecond).toList() val reverseFirst = coordinatePair.first().first != firstRange.first() val reverseSecond = coordinatePair.first().second != secondRange.first() return@let firstRange.mapIndexed { index, i -> if (reverseFirst xor reverseSecond) { i to secondRange[secondDistance - index] } else { i to secondRange[index] } } } else { return@let emptyList() } } }.let { coordinates.add(it) } } var area = Array(size+1) { IntArray(size+1) { 0 } } coordinates.flatten().forEach { area[it.second][it.first] = area[it.second][it.first] + 1 } val hotpoints = area.map { it.filter { it > 1 } }.flatten().count().also { println(it) } }
[ { "class_path": "nerok__Advent-of-code-2021__4dee925/Day5Kt.class", "javap": "Compiled from \"day5.kt\"\npublic final class Day5Kt {\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 ...
Pleiterson__desafios-bootcamps-dio__003eda6/Kotlin/Solucionando problemas em Kotlin/PrimoRapido.kt
// Primo Rápido /* Mariazinha sabe que um Número Primo é aquele que pode ser dividido somente por 1 (um) e por ele mesmo. Por exemplo, o número 7 é primo, pois pode ser dividido apenas pelo número 1 e pelo número 7 sem que haja resto. Então ela pediu para você fazer um programa que aceite diversos valores e diga se cada um destes valores é primo ou não. Acontece que a paciência não é uma das virtudes de Mariazinha, portanto ela quer que a execução de todos os casos de teste que ela selecionar (instâncias) aconteçam no tempo máximo de um segundo, pois ela odeia esperar. - Entrada A primeira linha da entrada contém um inteiro N (1 ≤ N ≤ 200), correspondente ao número de casos de teste. Seguem N linhas, cada uma contendo um valor inteiro X (1 < X < 231) que pode ser ou não, um número primo. - Saída Para cada caso de teste imprima a mensagem “Prime” (Primo) ou “Not Prime” (Não Primo), de acordo com o exemplo abaixo. */ import kotlin.math.sqrt fun main(args: Array<String>) { val n = readLine()!!.toInt() for (i in 0 until n) { val x = readLine()!!.toDouble() val prime = isPrime(x) print(prime) } } fun print(prime: Boolean) { if (prime) { print("Prime\n") } else print("Not Prime\n") } fun isPrime(num: Double): Boolean { if (num < 2) return false if (num % 2 == 0.0) return num == 2.0 val root = sqrt(num).toInt() var i = 3 while (i <= root) { if (num % i == 0.0) return false i += 2 } return true }
[ { "class_path": "Pleiterson__desafios-bootcamps-dio__003eda6/PrimoRapidoKt.class", "javap": "Compiled from \"PrimoRapido.kt\"\npublic final class PrimoRapidoKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n ...
Pleiterson__desafios-bootcamps-dio__003eda6/Kotlin/Solucionando problemas em Kotlin/Figurinhas.kt
// Figurinhas /* Ricardo e Vicente são aficionados por figurinhas. Nas horas vagas, eles arrumam um jeito de jogar um “bafo” ou algum outro jogo que envolva tais figurinhas. Ambos também têm o hábito de trocarem as figuras repetidas com seus amigos e certo dia pensaram em uma brincadeira diferente. Chamaram todos os amigos e propuseram o seguinte: com as figurinhas em mãos, cada um tentava fazer uma troca com o amigo que estava mais perto seguindo a seguinte regra: cada um contava quantas figurinhas tinha. Em seguida, eles tinham que dividir as figurinhas de cada um em pilhas do mesmo tamanho, no maior tamanho que fosse possível para ambos. Então, cada um escolhia uma das pilhas de figurinhas do amigo para receber. Por exemplo, se Ricardo e Vicente fossem trocar as figurinhas e tivessem respectivamente 8 e 12 figuras, ambos dividiam todas as suas figuras em pilhas de 4 figuras (Ricardo teria 2 pilhas e Vicente teria 3 pilhas) e ambos escolhiam uma pilha do amigo para receber. - Entrada A primeira linha da entrada contém um único inteiro N (1 ≤ N ≤ 3000), indicando o número de casos de teste. Cada caso de teste contém 2 inteiros F1 (1 ≤ F1 ≤ 1000) e F2 (1 ≤ F2 ≤ 1000) indicando, respectivamente, a quantidade de figurinhas que Ricardo e Vicente têm para trocar. - Saída Para cada caso de teste de entrada haverá um valor na saída, representando o tamanho máximo da pilha de figurinhas que poderia ser trocada entre dois jogadores. */ fun main(args: Array<String>) { val lista = mutableListOf<Int>() for (i in 1..readLine()!!.toInt()) { val input = readLine()!!.split(" ").map { it.toInt() } if(input.size == 2){ val valorMdc = mdc(input[0], input[1]) lista.add(valorMdc) } } for (i in lista){ println(i) } } // máximo divisor comum (chamada recursiva) fun mdc(n1: Int, n2: Int): Int { var resto: Int var n1 = n1 var n2 = n2 do{ resto = n1%n2 n1 = n2 n2 = resto }while (resto != 0) return n1 }
[ { "class_path": "Pleiterson__desafios-bootcamps-dio__003eda6/FigurinhasKt.class", "javap": "Compiled from \"Figurinhas.kt\"\npublic final class FigurinhasKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n ...
manan025__DS-Algo-Zone__c185dce/Kotlin/min_number_of_1.kt
import java.lang.Integer.min import java.util.* /* KOTLIN PROGRAM TO FIND THE ROWS WITH MINIMUM NUMBER OF 1s INPUT FORMAT : number of rows and number of column ||THE ARRAY || OUTPUT FORMAT: ith row which has the least number of 1s the elements of row which has the least number of 1s INPUT: 5 4 1 1 1 2 1 1 5 2 0 0 1 1 1 1 2 2 1 0 1 1 OUTPUT: 2 row: 1 1 5 2 3 row: 0 0 1 1 4 row: 1 1 2 2 Time complexity : O(N^2); Space complexity : O(N^2); */ fun main() { val scanner = Scanner(System.`in`) val noOfRows: Int = scanner.nextInt() val noOfColumns: Int = scanner.nextInt() val array = Array(noOfRows) { IntArray(noOfColumns) } val noOf1sPerRow = IntArray(noOfRows) { 0 } readInputArray(array, noOfRows, noOfColumns) val minNoOf1s = findMin1s(array, noOfRows, noOf1sPerRow) printRowsWithMin1s(array, minNoOf1s, noOf1sPerRow) } fun readInputArray(array: Array<IntArray>, noOfRows: Int, noOfColumns: Int) { val scanner = Scanner(System.`in`) for (rowIndex in 0 until noOfRows) { for (columnIndex in 0 until noOfColumns) { array[rowIndex][columnIndex] = scanner.nextInt() } } } fun findMin1s(array: Array<IntArray>, noOfRows: Int, noOf1sPerRow: IntArray): Int { var minNoOf1s = Int.MAX_VALUE; for (i in 0 until noOfRows) { noOf1sPerRow[i] = array[i].fold(0) { prev, curr -> prev + (if (curr == 1) 1 else 0) } minNoOf1s = min(minNoOf1s, noOf1sPerRow[i]) } return minNoOf1s; } fun printRowsWithMin1s(array: Array<IntArray>, minNoOf1s: Int, noOf1sPerRow: IntArray) { for (i in array.indices) { if (minNoOf1s == noOf1sPerRow[i]) { println("${i + 1} row:") println(array[i].joinToString(" ")) } } }
[ { "class_path": "manan025__DS-Algo-Zone__c185dce/Min_number_of_1Kt.class", "javap": "Compiled from \"min_number_of_1.kt\"\npublic final class Min_number_of_1Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/util/Scanner\n 3: dup\n 4: g...
manan025__DS-Algo-Zone__c185dce/Kotlin/QuickSort.kt
import java.util.* /* Sample Input & Output : --------------------- The first line of the input contains an integer 'n' denoting the size of the array The second line of the input contains 'n' no integers SAMPLE INPUT & OUTPUT 1 INPUT : 4 98 76 54 32 OUTPUT : 32 54 76 98 SAMPLE INPUT & OUTPUT 2 INPUT : 5 45 45 23 65 12 OUTPUT: 12 23 45 45 65 ------------------------ Time Complexity : Best Case Complexity - O(n*logn) Worst Case Complexity - O(n2) ------------------------ Space Complexity : The space complexity of quicksort is O(n*logn) */ class QuickSort(private val array: IntArray) { private fun partition(start: Int, end: Int): Int { val pivot: Int = array[end] // pivot is the last element var i = start - 1; /** * At start of each iteration, array will satisfy following * elements less than or equal to pivot are between start index and ith index * elements greater than pivot are between (i + 1)th index and (j - 1)th index */ for (j in start until end) { if (array[j] <= pivot) { i += 1 swap(i, j) } } swap(i + 1, end); // After this swap pivot will get to its sorted position return i + 1; } private fun swap(index1: Int, index2: Int) { array[index1] = array[index2].also { array[index2] = array[index1] } } fun sort(start: Int, end: Int) { if (start < end) { val partitionIndex = partition(start, end); sort(start, partitionIndex - 1) sort(partitionIndex + 1, end) } } fun printElements() { println(array.joinToString(" ")) } } fun main() { val scanner = Scanner(System.`in`) val noOfElements = scanner.nextInt() val array = IntArray(noOfElements) readInputArray(array, scanner) val quickSort = QuickSort(array) quickSort.sort(0, array.size - 1) quickSort.printElements() } fun readInputArray(array: IntArray, scanner: Scanner) { for (i in array.indices) { array[i] = scanner.nextInt() } }
[ { "class_path": "manan025__DS-Algo-Zone__c185dce/QuickSort.class", "javap": "Compiled from \"QuickSort.kt\"\npublic final class QuickSort {\n private final int[] array;\n\n public QuickSort(int[]);\n Code:\n 0: aload_1\n 1: ldc #9 // String array\n 3: invoke...
mdtausifahmad__adventofcode2022__13295fd/src/Day04.kt
import java.io.File fun main(){ val numberOfCommonPairs = File("src/Day04.txt") .readText() .split("\n") .flatMap { it.lines() } .sumOf { val split = it.split(",") overLappingAssignmentPair(split[0].split("-"), split[1].split("-")) } println(numberOfCommonPairs) } fun pairsInRangeOfEachOther(firstPair: List<String>,secondPair: List<String>) : Int{ val firstPairInsideSecond = firstPair[0].toInt() >= secondPair[0].toInt() && firstPair[1].toInt() <= secondPair[1].toInt() val secondPairInsideFirst = secondPair[0].toInt() >= firstPair[0].toInt() && secondPair[1].toInt() <= firstPair[1].toInt() return if (firstPairInsideSecond.or(secondPairInsideFirst)) 1 else 0 } fun overLappingAssignmentPair(firstPair: List<String>,secondPair: List<String>) : Int{ val firstPairOverlappingSecond = firstPair[0].toInt() in secondPair[0].toInt()..secondPair[1].toInt() || firstPair[1].toInt() in secondPair[0].toInt()..secondPair[1].toInt() val secondPairOverlappingFirst = secondPair[0].toInt() in firstPair[0].toInt()..firstPair[1].toInt() || secondPair[1].toInt() in firstPair[0].toInt()..firstPair[1].toInt() return if (firstPairOverlappingSecond.or(secondPairOverlappingFirst)) 1 else 0 }
[ { "class_path": "mdtausifahmad__adventofcode2022__13295fd/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
mdtausifahmad__adventofcode2022__13295fd/src/Day03.kt
import java.io.File fun main(){ val groupSize = 3 val sumOfPriorities = File("src/Day03.txt") .readText() .also { println(it) } .split("\n") .flatMap { it.lines() } .map { getCommonCharacters(it) } .flatMap { it.map { elf -> getPriority(elf) } } .sum() println(sumOfPriorities) val sunOfPriorities = File("src/Day03.txt") .readText() .split("\n") .chunked(3) .map { getBadgesFromRuckSacks(it) } .sumOf { getPriority(it) } println(sunOfPriorities) } fun getPriority(char: Char): Int { return when { char.isLowerCase() -> char - 'a' + 1 char.isUpperCase() -> char - 'A' + 27 else -> error("Check Input") } } fun getCommonCharacters(input: String): Set<Char> { val (firstCompartment,secondCompartment) = input.chunked(input.length / 2) return firstCompartment.toSet() intersect secondCompartment.toSet() } fun getBadgesFromRuckSacks(ruckSacks: List<String>): Char{ val (first, second, third) = ruckSacks return(first.toSet() intersect second.toSet() intersect third.toSet()).single() } fun solution1(){ File("src/Day03.txt") .readText() .split("\n") .flatMap { it.lines() } .map { it.chunked(it.length /2) } .map { it[0].toSet() intersect it[1].toSet() } .sumOf { getPriority(it.first()) } }
[ { "class_path": "mdtausifahmad__adventofcode2022__13295fd/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: istore_0\n 2: new #8 // class java/io/File\n 5: du...
mdtausifahmad__adventofcode2022__13295fd/src/Day02.kt
import java.io.File fun main(){ val score = File("src/Day02.txt") .readText() .split("\n") .flatMap { it.lines() } .map { it.split(" ") } .sumOf { getPointOfRoundSecondPart(it[0].first(), it[1].first()) } println(score) } fun getPointOfRound(first: Char, second: Char): Int { return when (second) { 'X' -> { return when (first) { 'A' -> 1 + 3 'B' -> 1 'C' -> 1 + 6 else -> error("Check Input") } } 'Y' -> { return when (first) { 'A' -> 2 + 6 'B' -> 2 + 3 'C' -> 2 else -> error("Check Input") } } 'Z' -> { return when (first) { 'A' -> 3 'B' -> 3 + 6 'C' -> 3 + 3 else -> error("Check Input") } } else -> error("Check Input") } } fun getPointOfRoundSecondPart(first: Char, second: Char): Int { return when (second) { 'X' -> { return when (first) { 'A' -> 3 'B' -> 1 'C' -> 2 else -> error("Check Input") } } 'Y' -> { return when (first) { 'A' -> 1 + 3 'B' -> 2 + 3 'C' -> 3 + 3 else -> error("Check Input") } } 'Z' -> { return when (first) { 'A' -> 2 + 6 'B' -> 3 + 6 'C' -> 1 + 6 else -> error("Check Input") } } else -> error("Check Input") } }
[ { "class_path": "mdtausifahmad__adventofcode2022__13295fd/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
sysion__DataStructureAlgorithmKt__6f9afda/Lapindrome.kt
/** * https://www.codechef.com/problems/LAPIN * * * Lapindromes Problem Code: LAPIN * * Lapindrome is defined as a string which when split in the middle, gives two halves * having the same characters and same frequency of each character. If there are odd * number of characters in the string, we ignore the middle character and check for * lapindrome. For example gaga is a lapindrome, since the two halves ga and ga have * the same characters with same frequency. Also, abccab, rotor and xyzxy are a few * examples of lapindromes. Note that abbaab is NOT a lapindrome. The two halves * contain the same characters but their frequencies do not match. * * Your task is simple. Given a string, you need to tell if it is a lapindrome. * * Input: * First line of input contains a single integer T, the number of test cases. * Each test is a single line containing a string S composed of only lowercase English * alphabet. * * Output: * For each test case, output on a separate line: "YES" if the string is a lapindrome * and "NO" if it is not. * * Constraints: * 1 ≤ T ≤ 100 * 2 ≤ |S| ≤ 1000, where |S| denotes the length of S * * * Example: * Input: * 6 * gaga * abcde * rotor * xyzxy * abbaab * ababc * * Output: * YES * NO * YES * YES * NO * NO */ fun main(){ //val inpString = "gaga" //val inpString = "abcde" //val inpString = "rotor" val inpString = "xyzxy" //val inpString = "abbaab" //val inpString = "ababc" //val inpString = "gotrej" //val inpString = "abcabcbb" //val inpString = "bbbbb" //val inpString = "pwwkew" //val inpString = "" LapindromeCheck(inpString) } fun LapindromeCheck(inputString: String): String{ var isLapindrome = "NO" var strLen = inputString.trim().length var evenOdd = if (strLen % 2 == 0) 0 else 1 if (strLen == 0) { println("Is BLANK a Lapindrome? : $isLapindrome") return isLapindrome } var charArray1 = inputString.substring(0, evenOdd+strLen/2).toCharArray() var charArray2 = inputString.substring(strLen/2, strLen).toCharArray() //println(charArray1) //println(charArray2) //println(charArray1.sorted().toString()) //println(charArray2.sorted().toString()) if (charArray1.sorted() == charArray2.sorted()) isLapindrome = "YES" //var charArray1 = inputString.toList().slice(0..evenOdd+strLen/2) //var charArray2 = inputString.toList().slice(-1+strLen/2..strLen-1) //println(charArray1) //println(charArray2) println("Is $inputString a Lapindrome? : $isLapindrome") return isLapindrome }
[ { "class_path": "sysion__DataStructureAlgorithmKt__6f9afda/LapindromeKt.class", "javap": "Compiled from \"Lapindrome.kt\"\npublic final class LapindromeKt {\n public static final void main();\n Code:\n 0: ldc #8 // String xyzxy\n 2: astore_0\n 3: aload_0\n ...
sysion__DataStructureAlgorithmKt__6f9afda/TwoSumEqualToTarget.kt
/** * https://leetcode.com/problems/two-sum/ * * Two Sum Less Than K * * Given an array of integers nums and an integer target, return indices of the * two numbers such that they add up to target. * * You may assume that each input would have exactly one solution, and you may * not use the same element twice. * * You can return the answer in any order. * * Example 1: * Input: nums = [2,7,11,15], target = 9 * Output: [0,1] * Output: Because nums[0] + nums[1] == 9, we return [0, 1]. * * Example 2: * Input: nums = [3,2,4], target = 6 * Output: [1,2] * * Example 3: * Input: nums = [3,3], target = 6 * Output: [0,1] * * Constraints: * * 2 <= nums.length <= 10^3 * -10^9 <= nums[i] <= 10^9 * -10^9 <= target <= 10^9 * Only one valid answer exists. */ import java.util.Arrays fun main(){ //val inputArray: IntArray = intArrayOf(2,7,11,15) //val targetSum = 9 //val inputArray: IntArray = intArrayOf(3,2,4) //val targetSum = 6 val inputArray: IntArray = intArrayOf(3,3) val targetSum = 6 SumTwoNumbersEqualToTarget(inputArray, targetSum) } fun SumTwoNumbersEqualToTarget(intArray: IntArray, target: Int): IntArray { var result: IntArray = IntArray(2) val sumCheck: HashMap<Int, Int> = hashMapOf<Int, Int>() var sumPair = 0 for (cnt in intArray.indices){ sumPair = target - intArray[cnt] if (sumCheck.containsKey(sumPair)) { result[0] = sumCheck[sumPair]!! result[1] = cnt } sumCheck[intArray[cnt]] = cnt } println(Arrays.toString(result)) return result }
[ { "class_path": "sysion__DataStructureAlgorithmKt__6f9afda/TwoSumEqualToTargetKt.class", "javap": "Compiled from \"TwoSumEqualToTarget.kt\"\npublic final class TwoSumEqualToTargetKt {\n public static final void main();\n Code:\n 0: iconst_2\n 1: newarray int\n 3: astore_1\n ...
sysion__DataStructureAlgorithmKt__6f9afda/TwoSumLessThanTarget.kt
/** * https://leetcode.com/problems/two-sum-less-than-k/ * * 1. Two Sum Less Than K * * Given an array A of integers and integer K, return the maximum S such that * there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying * this equation, return -1. * * Example 1: * Input: A = [34,23,1,24,75,33,54,8], K = 60 * Output: 58 * Explanation: * We can use 34 and 24 to sum 58 which is less than 60. * * Example 2: * Input: A = [10,20,30], K = 15 * Output: -1 * Explanation: * In this case it's not possible to get a pair sum less that 15. * * Note: * 1 <= A.length <= 100 * 1 <= A[i] <= 1000 * 1 <= K <= 2000 */ fun main(){ //val inputArray: IntArray = intArrayOf(34,23,1,24,75,33,54,8) //var targetSum = 60; val inputArray: IntArray = intArrayOf(10,20,30) var targetSum = 15; SumTwoNumbersLessThanTarget(inputArray, targetSum) } fun SumTwoNumbersLessThanTarget(intArray: IntArray, target: Int): Int { var SumLessThanTarget = -1 return SumLessThanTarget }
[ { "class_path": "sysion__DataStructureAlgorithmKt__6f9afda/TwoSumLessThanTargetKt.class", "javap": "Compiled from \"TwoSumLessThanTarget.kt\"\npublic final class TwoSumLessThanTargetKt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: newarray int\n 3: astore_1\n ...
ngothanhtuan1203__rectangle_find_fourth_point__5544f73/src/main/kotlin/main.kt
fun main(args: Array<String>) { print( "answer1:${ solution( listOf( intArrayOf(1, 4), intArrayOf(3, 4), intArrayOf(3, 10) ).toTypedArray() ).contentToString() }\n" ) print( "answer2:${ solution( listOf( intArrayOf(1, 1), intArrayOf(2, 2), intArrayOf(1, 2) ).toTypedArray() ).contentToString() }" ) } /** * Follow direction from pointA to pointB */ fun getVector(pointA: IntArray, pointB: IntArray): IntArray = intArrayOf(pointB[0] - pointA[0], pointB[1] - pointA[1]) fun dotProduct(vectorA: IntArray, vectorB: IntArray): Int = vectorA[0] * vectorB[0] + vectorA[1] * vectorB[1] /** * Use vector to calculate the fourth point. * There is 2 problem need to be addressed * 1. define 2 vectors make the angle * 2. define the last point. * E.g: * Have rectangle ABCD: AB and BC combine to a angle at B when: vectorAB dotProduct vectorBC = 0 * So B is the angle point --> vectorBA = vectorCD hence we can get D point (fourth point) */ fun solution(v: Array<IntArray>): IntArray { if (v.size != 3) { throw Exception("Illegal parameter") } val length = v.size for (i in 0..length) { val subV = v.withIndex().filter { (j) -> j != i }.map { (j, value) -> value } val pA = v[i] val pB = subV[0] val pC = subV[1] val vectorAB = getVector(pA, pB) val vectorAC = getVector(pA, pC) val vectorBA = getVector(pB, pA) if (dotProduct(vectorAB, vectorAC) == 0) { val xD = pC[0] - vectorBA[0] val yD = pC[1] - vectorBA[1] return intArrayOf(xD, yD) } } throw Exception("Not found") }
[ { "class_path": "ngothanhtuan1203__rectangle_find_fourth_point__5544f73/MainKt.class", "javap": "Compiled from \"main.kt\"\npublic final class MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: i...
perihanmirkelam__ProjectEuler__a24ac44/src/main/kotlin/P014_LongestCollatzSequence.kt
/** * P14-Longest Collatz sequence * The following iterative sequence is defined for the set of positive integers: * n → n/2 (n is even) * n → 3n + 1 (n is odd) * Using the rule above and starting with 13, we generate the following sequence: * 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 * It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. * Which starting number, under one million, produces the longest chain? * NOTE: Once the chain starts the terms are allowed to go above one million. */ fun p14() { var term: Long var termCount: Int var greatestTermCount = 0 var greatest = 0L repeat(1_000_000) { termCount = 1 term = it.toLong() while (term > 1) { term = if (term % 2 == 0L) term / 2 else 3 * term + 1 termCount++ } if(termCount > greatestTermCount) { greatest = it.toLong() greatestTermCount = termCount } } println("A14: $greatest") }
[ { "class_path": "perihanmirkelam__ProjectEuler__a24ac44/P014_LongestCollatzSequenceKt.class", "javap": "Compiled from \"P014_LongestCollatzSequence.kt\"\npublic final class P014_LongestCollatzSequenceKt {\n public static final void p14();\n Code:\n 0: lconst_0\n 1: lstore 6\n 3:...
perihanmirkelam__ProjectEuler__a24ac44/src/main/kotlin/P011_LargestProductInAGrid.kt
/** * P11-Largest product in a grid * In the 20×20 grid below, four numbers along a diagonal line have been marked in red. * The product of these numbers is 26 × 63 × 78 × 14 = 1788696. * What is the greatest product of four adjacent numbers in the same direction * (up, down, left, right, or diagonally) in the 20×20 grid? */ fun p11() { val grid = "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" var greatest = 0 val rows: List<List<Int>> = grid.chunked(59).map { x -> x.split(" ").map { it.toInt() } } // vertical adjacent for (row in rows) for (i in 0..16) greatest = maxOf(greatest, row[i] * row[i + 1] * row[i + 2] * row[i + 3]) // horizontal adjacent for (j in 0..16) for (i in 0 until 20) greatest = maxOf(greatest, rows[j][i] * rows[j + 1][i] * rows[j + 2][i] * rows[j + 3][i]) // diagonal top left to bottom right adjacent for (j in 0..16) for (i in 0..16) greatest = maxOf(greatest, rows[j][i] * rows[j + 1][i + 1] * rows[j + 2][i + 2] * rows[j + 3][i + 3]) // diagonal top right to bottom left adjacent for (j in 19 downTo 3) for (i in 0..16) greatest = maxOf(greatest, rows[j][i] * rows[j - 1][i + 1] * rows[j - 2][i + 2] * rows[j - 3][i + 3]) println("A11: $greatest") }
[ { "class_path": "perihanmirkelam__ProjectEuler__a24ac44/P011_LargestProductInAGridKt.class", "javap": "Compiled from \"P011_LargestProductInAGrid.kt\"\npublic final class P011_LargestProductInAGridKt {\n public static final void p11();\n Code:\n 0: ldc #8 // String 08 02...
perihanmirkelam__ProjectEuler__a24ac44/src/main/kotlin/P018_MaximumPathSum.kt
/** * P18-Maximum Path Sum * By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. * 3 * 7 4 * 2 4 6 * 8 5 9 3 * That is, 3 + 7 + 4 + 9 = 23. * Find the maximum total from top to bottom of the triangle below: * 75 * 95 64 * 17 47 82 * 18 35 87 10 * 20 04 82 47 65 * 19 01 23 75 03 34 * 88 02 77 73 07 63 67 * 99 65 04 28 06 16 70 92 * 41 41 26 56 83 40 80 70 33 * 41 48 72 33 47 32 37 16 94 29 * 53 71 44 65 25 43 91 52 97 51 14 * 70 11 33 28 77 73 17 78 39 68 17 57 * 91 71 52 38 17 14 91 43 58 50 27 29 48 * 63 66 04 68 89 53 67 30 73 16 69 87 40 31 * 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 * NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. * However, Problem 67, is the same challenge with a triangle containing one-hundred rows; * it cannot be solved by brute force, and requires a clever method! ;o) */ const val str = "75\n" + "95 64\n" + "17 47 82\n" + "18 35 87 10\n" + "20 04 82 47 65\n" + "19 01 23 75 03 34\n" + "88 02 77 73 07 63 67\n" + "99 65 04 28 06 16 70 92\n" + "41 41 26 56 83 40 80 70 33\n" + "41 48 72 33 47 32 37 16 94 29\n" + "53 71 44 65 25 43 91 52 97 51 14\n" + "70 11 33 28 77 73 17 78 39 68 17 57\n" + "91 71 52 38 17 14 91 43 58 50 27 29 48\n" + "63 66 04 68 89 53 67 30 73 16 69 87 40 31\n" + "04 62 98 27 23 09 70 98 73 93 38 53 60 04 23" val rows: List<List<Int>> = str.split("\n").map { x -> x.split(" ").map { it.toInt() } } fun p18() { print(getMax(0, 0, 0)) } fun getMax(sum: Int, i: Int, j: Int): Int { if (i > rows.lastIndex) { println("Total: $sum") return sum } println("-> ${rows[i][j]} [$i,$j] sum: ${sum + rows[i][j]}") return maxOf(getMax(sum + rows[i][j], i+1, j), getMax(sum + rows[i][j], i+1,j+1)) }
[ { "class_path": "perihanmirkelam__ProjectEuler__a24ac44/P018_MaximumPathSumKt.class", "javap": "Compiled from \"P018_MaximumPathSum.kt\"\npublic final class P018_MaximumPathSumKt {\n public static final java.lang.String str;\n\n private static final java.util.List<java.util.List<java.lang.Integer>> rows;\...
perihanmirkelam__ProjectEuler__a24ac44/src/main/kotlin/P021_AmicableNumber.kt
/** * P21 - Amicable Numbers * * Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). * If d(a) = b and d(b) = a, where a ≠ b, * then a and b are an amicable pair and each of a and b are called amicable numbers. * * For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. * The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. * * Evaluate the sum of all the amicable numbers under 10000. */ fun p21() { val pairs: MutableList<Pair<Int, Int>> = mutableListOf((0 to 0)) val boundary = 10000 var n: Int; var dn: Int for (i in 1..boundary) { n = i dn = 0 for (j in 1 until n) if (n % j == 0) dn += j pairs.add(n to dn) } fun d(x: Int): Int = pairs[x].second var a: Int; var b: Int; var sum = 0 for (i in pairs) { a = i.first b = i.second if (a < boundary && b < boundary && a != b && a == d(b) && b == d(a)) sum += a } println("A21: $sum") }
[ { "class_path": "perihanmirkelam__ProjectEuler__a24ac44/P021_AmicableNumberKt.class", "javap": "Compiled from \"P021_AmicableNumber.kt\"\npublic final class P021_AmicableNumberKt {\n public static final void p21();\n Code:\n 0: iconst_1\n 1: anewarray #8 // class kotlin/...
perihanmirkelam__ProjectEuler__a24ac44/src/main/kotlin/P023_NonAbundantSums.kt
/** * P23-Non-Abundant Sums * * A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. * For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, * which means that 28 is a perfect number. * * A number n is called deficient if the sum of its proper divisors is less than n * and it is called abundant if this sum exceeds n. * * As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, * the smallest number that can be written as the sum of two abundant numbers is 24. * By mathematical analysis, it can be shown that all integers greater than 28123 * can be written as the sum of two abundant numbers. * However, this upper limit cannot be reduced any further by analysis * even though it is known that the greatest number that cannot be expressed as the sum of * two abundant numbers is less than this limit. * * Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. */ fun p23() { val upperLimit = 28123; val minAbundant = 12; var sumOfDivisors = 1 val abundantList = mutableListOf<Int>() val nonAbundantSum = (1 until upperLimit).toMutableList() for (x in minAbundant until upperLimit) { for (j in 2 until x) if (x % j == 0) sumOfDivisors += j if (sumOfDivisors > x) abundantList.add(x) sumOfDivisors = 1 } for (x in 1 until upperLimit) for (abundant in abundantList) { if (x - abundant >= minAbundant) if (abundantList.contains(x - abundant)) { nonAbundantSum.remove(x) break } else break } println("A23: ${nonAbundantSum.sum()}") }
[ { "class_path": "perihanmirkelam__ProjectEuler__a24ac44/P023_NonAbundantSumsKt.class", "javap": "Compiled from \"P023_NonAbundantSums.kt\"\npublic final class P023_NonAbundantSumsKt {\n public static final void p23();\n Code:\n 0: sipush 28123\n 3: istore_0\n 4: bipush 12...
aochsner__adventofcode2018__7c42ec9/kotlin/aoc2018/src/main/kotlin/Day11.kt
class Day11 { fun part1(serialNumber: Int) : Pair<Int, Int> { val powerGrid = Array(300) { x -> Array(300) { y -> getPowerLevel(x+1, y+1, serialNumber) } } return findLargestSquare(powerGrid, 3).key } private fun findLargestSquare(powerGrid: Array<Array<Int>>, gridSize: Int): Map.Entry<Pair<Int, Int>, Int> { val squareMap = mutableMapOf<Pair<Int, Int>, Int>() for (x in 0..(300-gridSize)) { for (y in 0..(300-gridSize)) { var squareSum = 0 for (rx in 0..(gridSize-1)) { for (ry in 0..(gridSize-1)) { squareSum += powerGrid[x + rx][y + ry] } } squareMap[Pair(x + 1, y + 1)] = squareSum } } return squareMap.maxBy { it.value }!! } fun part2(serialNumber: Int) : Triple<Int, Int, Int> { val powerGrid = Array(300) { x -> Array(300) { y -> getPowerLevel(x+1, y+1, serialNumber) } } val tripleMap = mutableMapOf<Triple<Int, Int, Int>, Int>() for (size in 1..300) { val largeSquare = findLargestSquare(powerGrid, size) tripleMap[Triple(largeSquare.key.first, largeSquare.key.second, size)] = largeSquare.value } return tripleMap.maxBy { it.value }!!.key } fun getPowerLevel(x: Int, y: Int, serialNumber: Int): Int { val rackId = x + 10 var powerLevel = rackId * y powerLevel += serialNumber powerLevel *= rackId powerLevel = (powerLevel / 100) % 10 return powerLevel - 5 } }
[ { "class_path": "aochsner__adventofcode2018__7c42ec9/Day11.class", "javap": "Compiled from \"Day11.kt\"\npublic final class Day11 {\n public Day11();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final kotl...
aochsner__adventofcode2018__7c42ec9/kotlin/aoc2018/src/main/kotlin/Day12.kt
import java.io.File class Day12 { fun part1(lines: List<String>): Int { val puzzle = Puzzle(lines) val pots = puzzle.generate(20) return pots.asSequence().mapIndexed { index, char -> if (char == '#') index-(4*20) else 0 }.sum() } fun part2(lines: List<String>): Int { val puzzle = Puzzle(lines) val pots = puzzle.generate(10000) return pots.asSequence().mapIndexed { index, char -> if (char == '#') index-(4*10000) else 0 }.sum() } } class Puzzle(lines: List<String>) { val initialState = """^initial state: (.+)$""".toRegex().find(lines[0])!!.destructured.component1() val rules = (2 until lines.size).associate { val (pattern, plant) = """^(.+) => (.)$""".toRegex().find(lines[it])!!.destructured pattern to plant[0] } fun generate(iterations: Int): String { var state = initialState repeat(iterations) { state = "....$state...." val nextGeneration = ".".repeat(state.length).toCharArray() (2 until state.length-2).forEach {index -> nextGeneration[index] = rules.getOrDefault(state.slice(index-2..index+2), '.') } state = String(nextGeneration) println(state) } return state } }
[ { "class_path": "aochsner__adventofcode2018__7c42ec9/Day12.class", "javap": "Compiled from \"Day12.kt\"\npublic final class Day12 {\n public Day12();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final int ...
aochsner__adventofcode2018__7c42ec9/kotlin/aoc2018/src/main/kotlin/Day02.kt
class Day02 { fun solvePart1(rawValues : List<String>): Int { val (twos, threes) = rawValues.fold(Pair(0,0)) { sum, element -> val counts = element.asSequence().groupingBy { it }.eachCount() Pair(sum.first + if (counts.values.contains(2)) 1 else 0, sum.second + if(counts.values.contains(3)) 1 else 0) } return twos * threes } fun solvePart2(rawValues : List<String>): String { return rawValues.mapIndexed { i, outer -> rawValues.drop(i).mapNotNull { val diffIndexes = diffIndexes(outer, it) if (diffIndexes.first == 1) { outer.removeRange(diffIndexes.second, diffIndexes.second+1) } else null } } .flatten() .first() } fun diffIndexes(a: String, b: String): Pair<Int, Int> { var index = 0 val diff = a.mapIndexed { i, char -> if (char != b[i]) { index = i 1 } else 0 }.sum() return Pair(diff, index) } }
[ { "class_path": "aochsner__adventofcode2018__7c42ec9/Day02$solvePart1$lambda$1$$inlined$groupingBy$1.class", "javap": "Compiled from \"_Sequences.kt\"\npublic final class Day02$solvePart1$lambda$1$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lang.Character, java.lang.Character> {\n fin...
cyprienroche__GoogleHashCode20__5196612/src/main/kotlin/InputData.kt
import java.util.Scanner class InputData(private val scanner: Scanner) { private val totalBooks: Int = scanner.nextInt() private val totalLibraries: Int = scanner.nextInt() val totalDaysGiven: Day = Day(scanner.nextInt()) private val scores: List<Int> = List(totalBooks) { scanner.nextInt() } val libraries: Map<Library, List<Book>> val orderedBookIndexByScore = scores.withIndex().sortedBy { it.value } private val bookIndexToScore = (0 until totalBooks).zip(scores).toMap() init { val libs = mutableMapOf<Library, List<Book>>() for (i in 0 until totalLibraries) { val numBooksInLibrary = scanner.nextInt() val lib = Library(i, Day(scanner.nextInt()), scanner.nextInt(), 0) val xs = List(numBooksInLibrary) { scanner.nextInt() } val books = xs.map { Book(it, lib, bookIndexToScore[it]?:0) } lib.maxScore = books.map { it.score }.max()?:0 libs[lib] = books } libraries = libs } val libsSorted = libraries.keys.sortedWith(Comparator { o1, o2 -> if (o2 == null) 1 else o1?.compareTo(o2)?:-1 }) } data class Library(val id: Int, val signUp: Day, val booksPerDay: Int, var maxScore: Int): Comparable<Library> { override fun compareTo(other: Library): Int = when { maxScore != other.maxScore -> -1 * maxScore.compareTo(other.maxScore) signUp != other.signUp -> signUp.compareTo(other.signUp) else -> -1 * booksPerDay.compareTo(other.booksPerDay) } } data class Day(val size: Int): Comparable<Day> { override fun compareTo(other: Day): Int = size.compareTo(other.size) } data class Book(val id: Int, val lib: Library, val score: Int)
[ { "class_path": "cyprienroche__GoogleHashCode20__5196612/InputData$special$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class InputData$special$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public InputData$special$$inlined$sortedBy$1();\n Code:\n ...
nmx__aoc2022__33da213/src/main/kotlin/Day04.kt
fun main(args: Array<String>) { fun toRange(str: String): IntRange { val (lo, hi) = str.split("-") return IntRange(lo.toInt(), hi.toInt()) } fun rangesFullyContained(a: IntRange, b: IntRange): Boolean { return (a.first <= b.first && a.last >= b.last) || (b.first <= a.first && b.last >= a.last) } fun rangesOverlap(a: IntRange, b: IntRange): Boolean { return (a.first <= b.first && a.last >= b.first) || (b.first <= a.first && b.last >= a.first) } fun rowMeetsCriteria(row: String, func: (a: IntRange, b:IntRange) -> Boolean): Boolean { if (row.isEmpty()) return false val (left, right) = row.split(",") val leftRange = toRange(left) val rightRange = toRange(right) return func(leftRange, rightRange) } fun partN(input: String, func: (a: IntRange, b:IntRange) -> Boolean) { var sum = 0 input.split("\n").forEach { if (rowMeetsCriteria(it, func)) sum++ } println(sum) } fun part1(input: String) { partN(input, ::rangesFullyContained) } fun part2(input: String) { partN(input, ::rangesOverlap) } val input = object {}.javaClass.getResource("Day04.txt").readText() part1(input) part2(input) }
[ { "class_path": "nmx__aoc2022__33da213/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\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 ...
nmx__aoc2022__33da213/src/main/kotlin/Day05.kt
fun main(args: Array<String>) { fun parseStacks(input: List<String>): Pair<List<MutableList<Char>>, List<String>> { val stackLabels = input.find { s -> s.startsWith(" 1") }!! val numStacks = stackLabels.split(" ").last { s -> !s.isEmpty() }.toInt() val stacks = mutableListOf<MutableList<Char>>() for (i in 1..numStacks) { stacks.add(mutableListOf()) } var i = 0 while (!input[i].startsWith(" 1")) { val line = input[i] var j = 0 while (j < numStacks) { val c = line[j * 4 + 1] if (c != ' ') { stacks[j].add(c) } j += 1 } i++ } return Pair(stacks, input.subList(i + 2, input.size)) } fun executeMoves(stacks: List<MutableList<Char>>, moves: List<String>, reverseOrder: Boolean) { moves.filter{ it.isNotEmpty() }.forEach { val (num, src, dst) = it.split(" ").mapNotNull { s -> s.toIntOrNull() } if (reverseOrder) { for (i in num - 1 downTo 0) { stacks[dst - 1].add(0, stacks[src - 1].removeAt(i)) } } else { for (i in 1..num) { stacks[dst - 1].add(0, stacks[src - 1].removeAt(0)) } } } } fun resultString(stacks: List<List<Char>>): String { return stacks.map { it.first() }.joinToString("") } fun part1(input: String) { val (stacks, moves) = parseStacks(input.split("\n")) executeMoves(stacks, moves, false) println(resultString(stacks)) } fun part2(input: String) { val (stacks, moves) = parseStacks(input.split("\n")) executeMoves(stacks, moves, true) println(resultString(stacks)) } val input = object {}.javaClass.getResource("Day05.txt").readText() part1(input) part2(input) }
[ { "class_path": "nmx__aoc2022__33da213/Day05Kt$main$input$1.class", "javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt$main$input$1 {\n Day05Kt$main$input$1();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retur...
nmx__aoc2022__33da213/src/main/kotlin/Day08.kt
fun main(args: Array<String>) { class Tree(val height: Int) { var visited = false var viewScore = 0 override fun toString(): String { return "$height${if (visited) '*' else ' '} " } } fun countRows(input: List<String>): Int { return input.size } fun countCols(input: List<String>): Int { return input[0].length } fun visit(tree: Tree, maxHeight: Int): Int { return if (tree.height > maxHeight) { tree.visited = true tree.height } else { maxHeight } } fun countFromTop(grid: Array<Array<Tree>>) { for (col in 0 until grid[0].size) { var maxHeight = -1 for (row in 0 until grid.size) { maxHeight = visit(grid[row][col], maxHeight) } } } fun countFromRight(grid: Array<Array<Tree>>) { for (row in 0 until grid.size) { var maxHeight = -1 for (col in grid.size - 1 downTo 0) { maxHeight = visit(grid[row][col], maxHeight) } } } fun countFromBottom(grid: Array<Array<Tree>>) { for (col in 0 until grid[0].size) { var maxHeight = -1 for (row in grid.size - 1 downTo 0) { maxHeight = visit(grid[row][col], maxHeight) } } } fun countFromLeft(grid: Array<Array<Tree>>) { for (row in 0 until grid.size) { var maxHeight = -1 for (col in 0 until grid.size) { maxHeight = visit(grid[row][col], maxHeight) } } } fun part1(grid: Array<Array<Tree>>) { countFromTop(grid) countFromRight(grid) countFromBottom(grid) countFromLeft(grid) grid.forEach{ it.forEach { it2 -> print(it2)} println() } val visibleCount = grid.sumOf { it.filter { tree -> tree.visited }.size } println("Visible: $visibleCount") } fun viewScoreUp(grid: Array<Array<Tree>>, treeRow: Int, treeCol: Int): Int { val height = grid[treeRow][treeCol].height var score = 0 for (row in treeRow - 1 downTo 0) { score++ if (grid[row][treeCol].height >= height) { break } } return score } fun viewScoreRight(grid: Array<Array<Tree>>, treeRow: Int, treeCol: Int): Int { val height = grid[treeRow][treeCol].height var score = 0 for (col in treeCol + 1 until grid[treeRow].size) { score++ if (grid[treeRow][col].height >= height) { break } } return score } fun viewScoreDown(grid: Array<Array<Tree>>, treeRow: Int, treeCol: Int): Int { val height = grid[treeRow][treeCol].height var score = 0 for (row in treeRow + 1 until grid.size) { score++ if (grid[row][treeCol].height >= height) { break } } return score } fun viewScoreLeft(grid: Array<Array<Tree>>, treeRow: Int, treeCol: Int): Int { val height = grid[treeRow][treeCol].height var score = 0 for (col in treeCol - 1 downTo 0) { score++ if (grid[treeRow][col].height >= height) { break } } return score } fun calcViewScore(grid: Array<Array<Tree>>, row: Int, col: Int) { grid[row][col].viewScore = viewScoreUp(grid, row, col) if (grid[row][col].viewScore == 0) return grid[row][col].viewScore *= viewScoreRight(grid, row, col) if (grid[row][col].viewScore == 0) return grid[row][col].viewScore *= viewScoreDown(grid, row, col) if (grid[row][col].viewScore == 0) return grid[row][col].viewScore *= viewScoreLeft(grid, row, col) } fun part2(grid: Array<Array<Tree>>) { for (row in 0 until grid.size) { for (col in 0 until grid[row].size) { calcViewScore(grid, row, col) } } grid.forEach{ it.forEach { it2 -> print("${it2.viewScore} ") } println() } val bestViewScore = grid.maxOf { it -> it.maxOf { tree -> tree.viewScore }} println("Best view score: $bestViewScore") } val input = object {}.javaClass.getResource("Day08.txt").readText().trim().split("\n") val rows = countRows(input) val cols = countCols(input) val protoGrid: Array<Array<Tree?>> = Array(rows) { arrayOfNulls(cols) } input.forEachIndexed { rowIdx, row -> row.forEachIndexed { colIdx, height -> protoGrid[rowIdx][colIdx] = Tree(height.digitToInt()) } } val grid = protoGrid as Array<Array<Tree>> part1(grid) part2(grid) }
[ { "class_path": "nmx__aoc2022__33da213/Day08Kt$main$Tree.class", "javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt$main$Tree {\n private final int height;\n\n private boolean visited;\n\n private int viewScore;\n\n public Day08Kt$main$Tree(int);\n Code:\n 0: aload_0\n 1: in...
nmx__aoc2022__33da213/src/main/kotlin/Day07.kt
fun main(args: Array<String>) { val TOTAL_DISK_SPACE = 70000000 val UNUSED_SPACE_NEEDED = 30000000 abstract class Node(val name: String, var size: Int) { abstract fun calcSize(): Int abstract fun sumMatchingSizes(): Int } class File(name: String, size: Int): Node(name, size) { override fun calcSize(): Int { return size } override fun sumMatchingSizes(): Int { return 0 } } class Dir(name: String, val parent: Dir?): Node(name, 0) { val children = mutableMapOf<String, Node>() override fun calcSize(): Int { size = children.values.sumOf { it.calcSize() } return size } override fun sumMatchingSizes(): Int { return (if (size <= 100000) size else 0) + children.values.sumOf { it.sumMatchingSizes() } } fun findSmallestDirWithMinSize(minSize: Int): Dir? { val me = if (size >= minSize) this else null val descendantCandidates = children.values.mapNotNull { if (it !is Dir) null else it.findSmallestDirWithMinSize(minSize) } return (listOfNotNull(me) + descendantCandidates).minWithOrNull(compareBy { it.size }) } } fun executeLine(cwd: Dir, lines: List<String>, startLineNum: Int): Pair<Dir, Int> { var lineNum = startLineNum val tokens = lines[lineNum++].split(" ") if (tokens[0] != "$") { throw Exception("Expected prompt, got ${tokens[0]}") } when (tokens[1]) { "cd" -> { val targetDir = tokens[2] when (targetDir) { "/" -> { if (cwd.parent != null) { throw Exception("unexpected cd to root after start") } // else ignore } ".." -> { return Pair(cwd.parent!!, lineNum) } else -> { // assume "cd X" never precedes the ls output for its parent return Pair(cwd.children.getValue(targetDir) as Dir, lineNum) } } } "ls" -> { if (cwd.children.isNotEmpty()) { throw Exception("already listed ${cwd.name}") } else { while (lineNum < lines.size && lines[lineNum].isNotEmpty() && !lines[lineNum].startsWith("$") ) { val (dirOrSize, name) = lines[lineNum++].split(" ") val child = if (dirOrSize == "dir") { Dir(name, cwd) } else { File(name, dirOrSize.toInt()) } if (cwd.children.containsKey(name)) throw Exception("$name already exists") cwd.children[name] = child } } return Pair(cwd, lineNum) } else -> { throw Exception("bad token ${tokens[1]}") } } return Pair(cwd, lineNum) } fun loadFileSystem(input: String): Dir { val lines = input.split("\n") val root = Dir("/", null) var cwd = root var lineNum = 0 while (lineNum < lines.size && lines[lineNum].isNotEmpty()) { val res = executeLine(cwd, lines, lineNum) cwd = res.first lineNum = res.second } root.calcSize() return root } fun part1(root: Dir) { println("Part 1 sum of matching sizes: " + root.sumMatchingSizes()) } fun part2(root: Dir) { val freeSpace = TOTAL_DISK_SPACE - root.size val spaceNeeded = UNUSED_SPACE_NEEDED - freeSpace if (spaceNeeded <= 0) { throw Exception("There's already enough free space") } println("Needed space: $spaceNeeded") val toDelete = root.findSmallestDirWithMinSize(spaceNeeded) println("Dir to delete: ${toDelete!!.name} ${toDelete!!.size}") } val input = object {}.javaClass.getResource("Day07.txt").readText() val root = loadFileSystem(input) part1(root) part2(root) }
[ { "class_path": "nmx__aoc2022__33da213/Day07Kt$main$Dir.class", "javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt$main$Dir extends Day07Kt$main$Node {\n private final Day07Kt$main$Dir parent;\n\n private final java.util.Map<java.lang.String, Day07Kt$main$Node> children;\n\n public Day07Kt$...
nmx__aoc2022__33da213/src/main/kotlin/Day03.kt
fun main(args: Array<String>) { fun findCommonElement(strings: List<String>): Char { val sets = strings.map { it.toSet() } val intersection = sets.reduce { acc, set -> acc.intersect(set) } if (intersection.size != 1) { throw RuntimeException("expected exactly one match, found ${intersection.size}") } return intersection.elementAt(0) } fun findMispackedTypeInRow(row: String): Char? { if (row.isEmpty()) return null val left = row.substring(0, row.length / 2) val right = row.substring(row.length / 2, row.length) return findCommonElement(listOf(left, right)) } fun scoreType(type: Char?): Int { return if (type == null) { 0 } else if (type.isLowerCase()) { type - 'a' + 1 } else { type - 'A' + 27 } } fun findBadge(rows: List<String>): Char { return findCommonElement(rows) } fun part1(input: String) { var sum = 0 input.split("\n").forEach { val type = findMispackedTypeInRow(it) sum += scoreType(type) } println(sum) } fun part2(input: String) { val lines = input.split("\n") var i = 0 var sum = 0 while (i < lines.size && lines[i].isNotEmpty()) { val badge = findBadge(lines.subList(i, i + 3)) sum += scoreType(badge) i += 3 } println(sum) } val input = object {}.javaClass.getResource("Day03.txt").readText() part1(input) part2(input) }
[ { "class_path": "nmx__aoc2022__33da213/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\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 ...
nmx__aoc2022__33da213/src/main/kotlin/Day02.kt
fun main(args: Array<String>) { class Shape( val draw: Char, val defeats: Char, val score: Int ) val shapes = buildMap<Char, Shape> { put('X', Shape('A', 'C', 1)) // Rock smashes Scissors put('Y', Shape('B', 'A', 2)) // Paper covers Rock put('Z', Shape('C', 'B', 3)) // Scissors cuts Paper } class OpponentShape(win: Char, lose: Char, draw: Char) { val win = shapes[win]!! val lose = shapes[lose]!! val draw = shapes[draw]!! } val opponentShapes = buildMap<Char, OpponentShape> { put('A', OpponentShape('Y', 'Z', 'X')) put('B', OpponentShape('Z', 'X', 'Y')) put('C', OpponentShape('X', 'Y', 'Z')) } fun scoreRow(row: String, secondColumIsWLD: Boolean): Int { if (row.isEmpty()) return 0 val opponent = row[0] val shape = if (secondColumIsWLD) { val opponentShape = opponentShapes[opponent]!! when (row[2]) { 'X' -> opponentShape.lose 'Y' -> opponentShape.draw 'Z' -> opponentShape.win else -> throw RuntimeException("unhandled input") } } else { shapes[row[2]]!! } return shape.score + when (opponent) { shape.defeats -> 6 shape.draw -> 3 else -> 0 } } fun partN(input: String, secondColumIsWLD: Boolean) { var score = 0 input.split("\n").forEach { score += scoreRow(it, secondColumIsWLD) } println(score) } fun part1(input: String) { partN(input, false) } fun part2(input: String) { partN(input, true) } val input = object {}.javaClass.getResource("Day02.txt").readText() part1(input) part2(input) }
[ { "class_path": "nmx__aoc2022__33da213/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\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 ...
kannix68__advent_of_code_2021__fc98894/day01.kt
/** * Advent of Code 2021 Day 1 solution. * This is currently a fairly minimalistic code. */ import java.io.File val testin = """ 199 200 208 210 200 207 240 269 260 263 """.trimIndent() /** * Get diff of List "as series", first element will be null. */ private fun diff(ints: List<Int>): List<Int?> { val diffs = ints.mapIndexed { idx, elem -> if (idx == 0) null else elem - ints[idx - 1] } return diffs } private fun getIncsCount(inp: String): Int { //val ints = listOf(1, 2, 3, 2, 1) val ints = inp.split("\n").map { it.toInt() }; val diffs = diff(ints) val incs = diffs.filterNotNull().filter { it > 0 }.size //println(ints) //println(diffs) return incs } private fun getIncs3Count(inp: String): Int { //val ints = listOf(1, 2, 3, 2, 1) var ints = inp.split("\n").map{ it.toInt() }; //println(ints.windowed(3)) //println(ints.windowed(3).map{it.sum()}) ints = ints.windowed(3).map{it.sum()} val diffs = diff(ints) val incs = diffs.filterNotNull().filter{ it > 0 }.size //println(ints) //println(diffs) return incs } fun main(args: Array<String>){ var incs = getIncsCount(testin) println("rc=$incs") val inp = File("./in/day01.in").readText().trim() incs = getIncsCount(inp) println("rc=$incs") incs = getIncs3Count(testin) println("rc=$incs") incs = getIncs3Count(inp) println("rc=$incs") }
[ { "class_path": "kannix68__advent_of_code_2021__fc98894/Day01Kt.class", "javap": "Compiled from \"day01.kt\"\npublic final class Day01Kt {\n private static final java.lang.String testin;\n\n public static final java.lang.String getTestin();\n Code:\n 0: getstatic #11 // Field ...
FasihMuhammadVirk__Concepts-in-Kotlin__089dedc/PF/9. Functions/Function_Exercise.kt
import java.util.* import kotlin.collections.ArrayList //Write a function that takes in two integers and return their sums fun sum_numbers(x:Int , y:Int ):Int = x + y //A function that reverse the value of the string fun reverse_string(s:String):String = s.reversed() //take an array of integer and return their average fun sum_array(a: Array<Int>):Int = a.sum() //String and Character and Return how many time it appear in String fun appaerance_of_char(s: String,c: Char):Int{ var result: Int = 0 for (i in s){ if (i == c) { result =+1 } } return result } //aaray of string and return the longest string fun longest_string(s: Array<String>){ var result:String = " " for (i in s ) { if (i.length > result.length) { result = i } } println(result) } //Return a list conatining only even numbers fun even_number(array: Array<Int>){ var arr = ArrayList<Int>(0) for (i in array){ if(i%2 == 0) { arr.add(i) } } println(arr) } //return the number of word in the string fun number_of_words(s:String):Int = s.length //retunr the smallest number fun smallest_number(s: Array<Int>):Int{ var result:Int = s[0] for (i in s ) { if (i < result) { result = i } } return result } //Vowel in the string fun vowel_string(s: Array<String>){ var arr = ArrayList<String>() var vol = arrayOf('a','e','i','o','u','A','E','I','O','U') for (i in s ) { if (vol.contains(i[0])) { arr.add(i) } } println(arr) } //Main fun main(){ var arrs = arrayOf("Iam","Shiza","TunTun","Fasih") var arr = arrayOf(1,2,3,4,5,6,7,8,9) println(Arrays.toString(arrs)) println(Arrays.toString(arr)) println() println("Sum of Number 2 and 2") println(sum_numbers(2,2)) println() println("Reversing the String 'Fasih'") println(reverse_string("Fasih")) println() println("Printing the sum of the Given Int Array") println(sum_array(arr)) println() println("Findin the Occurance of 'F' in Fasih") println(appaerance_of_char("Fasih",'F')) println() println("Printing the Even Number in Int Array") even_number(arr) println() println("Printing the Number of Words in 'Fasih'") println(number_of_words("Fasih")) println() println("Printing the smallest Number in Int Array") println(smallest_number(arr)) println() println("Printing the Word Start with Vowel in String Array") vowel_string(arrs) println() println("Printing the Longest String in String Array") longest_string(arrs) }
[ { "class_path": "FasihMuhammadVirk__Concepts-in-Kotlin__089dedc/Function_ExerciseKt.class", "javap": "Compiled from \"Function_Exercise.kt\"\npublic final class Function_ExerciseKt {\n public static final int sum_numbers(int, int);\n Code:\n 0: iload_0\n 1: iload_1\n 2: iadd\n 3:...
feczkob__Kotlin-Koans__b954a54/Generics/Generic functions/src/Task.kt
import java.util.* fun <K, C : MutableCollection<K>> Collection<K>.partitionTo( one: C, two: C, pred: Collection<K>.(K) -> Boolean, ): Pair<MutableCollection<K>, MutableCollection<K>> { // * solution 1 // this.forEach { // if (pred(it)) { // one += it // } else { // two += it // } // } // * solution 2 val (a, b) = this.partition { pred(it) } one.addAll(a) two.addAll(b) return Pair(one, two) } fun partitionWordsAndLines() { val (words, lines) = listOf("a", "a b", "c", "d e") .partitionTo(ArrayList(), ArrayList()) { s -> !s.contains(" ") } check(words == listOf("a", "c")) check(lines == listOf("a b", "d e")) } fun partitionLettersAndOtherSymbols() { val (letters, other) = setOf('a', '%', 'r', '}') .partitionTo(HashSet(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z' } check(letters == setOf('a', 'r')) check(other == setOf('%', '}')) }
[ { "class_path": "feczkob__Kotlin-Koans__b954a54/TaskKt.class", "javap": "Compiled from \"Task.kt\"\npublic final class TaskKt {\n public static final <K, C extends java.util.Collection<K>> kotlin.Pair<java.util.Collection<K>, java.util.Collection<K>> partitionTo(java.util.Collection<? extends K>, C, C, kot...
arcadioramos__google-code-jam__57451e0/solutions/mediansort/medianSort.kt
fun main(){ var (a, b, c) = readLine()!!.split(' ') var testCases = a.toInt() var numOfElemnts = b.toInt() var numOfQueries = c.toInt() while(testCases > 0){ if(!medianSort(numOfElemnts, numOfQueries)) return } testCases = testCases - 1 } // Median Sort fun medianSort( nE: Int, nQ: Int): Boolean{ var nQL = nQ var numbers = intArrayOf(1,2) for (i in 3..nE+1){ var left = 0 var right = numbers.size-1 while (right - left >= 1 && nQL > 0){ var leftP = left + ((right-left)/3) var rightP = right - ((right-left)/3) println(" ${numbers[leftP]} ${numbers[rightP]} ${i}") System.out.flush() var med = readLine()!!.toInt() nQL = nQL-1 if(med == numbers[leftP]){ right = leftP - 1 if(left == right){ right += 1 } }else if(med == numbers[rightP]){ left = rightP + 1 if(left == right){ left -= 1 } }else{ left = leftP + 1 right = rightP - 1 if(left == right){ left -= 1 } } } numbers = insertAt(numbers, i, left) } return output(numbers) } fun output(numbers: IntArray): Boolean{ println(numbers.contentToString()) System.out.flush() var response = readLine()!!.toInt() return response == 1 } fun insertAt(arr: IntArray, key: Int, index: Int): IntArray{ val array = arr.copyOf(arr.size + 1) for(i in 0 until index){ array[i] = arr[i] } array[index] = key for(i in index+1..arr.size){ array[i] = arr[i-1] } return array }
[ { "class_path": "arcadioramos__google-code-jam__57451e0/MedianSortKt.class", "javap": "Compiled from \"medianSort.kt\"\npublic final class MedianSortKt {\n public static final void main();\n Code:\n 0: invokestatic #12 // Method kotlin/io/ConsoleKt.readLine:()Ljava/lang/String;\n ...
ronhombre__MontgomeryArithmeticKotlinExample__24eac84/src/main/kotlin/Main.kt
//These values below should be saved since we assume that Q is a constant. //The Q value for Kyber (ML-KEM). This is a prime number ((2^8 * 13) + 1) const val Q: Short = 3329 //Negative Modular Inverse of Q base 2^16 const val Q_INV = -62209 //Base 2^16. const val R_shift = 16 //R const val R = 1 shl R_shift //R * R = R^2 const val R_squared = R.toLong() shl R_shift fun main() { println("Short Int Montgomery Arithmetic in Kotlin") println("Author: <NAME>\n") val a: Short = 3228 val b: Short = 3228 val aMont = toMontgomeryForm(a) val bMont = toMontgomeryForm(b) val mulMont = montgomeryMultiply(aMont, bMont) //Simple Test Case println("Modulo : " + (a * b % Q)) println("Montgomery: " + montgomeryReduce(mulMont.toInt())) //Comprehensive Test Case comprehensiveTest() } fun comprehensiveTest() { //0 up to 32768 (excluding 32768). println("Running comprehensive test [0, 32768)...") var count = 0 var correct = 0 for(i in 0..<Short.MAX_VALUE.toInt()) { count++ val certain = (i * (Q - 1) % Q).toShort() val aMont = toMontgomeryForm(i.toShort()) val bMont = toMontgomeryForm((Q - 1).toShort()) val mulMont = montgomeryMultiply(aMont, bMont) val guess = montgomeryReduce(mulMont.toInt()) if(guess == certain) correct++ else println("$i/$certain/$guess") } println("Ratio(Correct/Total/Ratio): $correct/$count/" + (correct/count.toDouble() * 100) + "%") } //Convert values to Montgomery Form fun toMontgomeryForm(a: Short): Short { //Here R_squared % Q can be precomputed and Barrett Reduction can be used for a % Q. // (a * R_squared) % Q = ((a % Q) * (R_squared % Q)) % Q return montgomeryReduce((a * R_squared % Q).toInt()) } /* * Montgomery Reduction (REDC) * Source: Montgomery modular multiplication. (2023, November 28). In Wikipedia. https://en.wikipedia.org/wiki/Montgomery_modular_multiplication */ fun montgomeryReduce(t: Int): Short { //N = Q //N' = Q_INV //TN' mod R //Modulo for base 2 values is a simple AND operation. val m = (t * Q_INV) and ((R shl 1) - 1) //0xFFFF //(T + mN) / R val u = (t + m * Q) ushr R_shift return if (u >= Q) (u - Q).toShort() else u.toShort() } fun montgomeryMultiply(a: Short, b: Short): Short { val t = a * b //Automatically converts to Int return montgomeryReduce(t) }
[ { "class_path": "ronhombre__MontgomeryArithmeticKotlinExample__24eac84/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n public static final short Q;\n\n public static final int Q_INV;\n\n public static final int R_shift;\n\n public static final int R;\n\n public static ...
JonahBreslow__advent-of-code-kotlin-2022__c307ff2/src/Day04.kt
import java.io.File import kotlin.math.min fun main () { fun parseInput(input: String) : List<List<Set<Int>>>{ return File(input) .readLines() .map { it.split(",") } .map{ val set1 = (it[0].split("-")[0].toInt() until it[0].split("-")[1].toInt()+1).map{it}.toSet() val set2 = (it[1].split("-")[0].toInt() until it[1].split("-")[1].toInt()+1).map{it}.toSet() listOf(set1, set2) } } fun part1(input: String) : Int{ val overlaps = parseInput(input) .map{ if((it[0].intersect(it[1]).size) == min(it[0].size, it[1].size)){ 1 } else { 0 } } return overlaps.sum() } fun part2(input: String) : Int{ val overlaps = parseInput(input) .map{ if((it[0].intersect(it[1]).size) > 0 ){ 1 } else { 0 } } return overlaps.sum() } val testFile = "data/day4_test.txt" check(part1(testFile) == 2) check(part2(testFile) == 4) val inputFile = "data/day4.txt" println(part1(inputFile)) println(part2(inputFile)) }
[ { "class_path": "JonahBreslow__advent-of-code-kotlin-2022__c307ff2/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String data/day4_test.txt\n 2: astore_0\n 3: aload_...
JonahBreslow__advent-of-code-kotlin-2022__c307ff2/src/Day03.kt
import java.io.File val Char.priority: Int get(): Int { return when (this){ in 'a'..'z' -> this -'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("Check your input! $this") } } fun main () { fun parseInput(input: String): ArrayList<Pair<String, String>> { val data = File(input).readLines() var parsed: ArrayList<Pair<String, String>> = arrayListOf() for (pack in data){ val size = pack.length / 2 val compartments = pack.chunked(size) val pair = Pair(compartments[0], compartments[1]) parsed.add(pair) } return parsed } fun part1(input: String): Int { val knapsacks = parseInput(input) var res: Int = 0 for (pack in knapsacks){ var f = pack.first.toSet() var b = pack.second.toSet() var item = (f intersect b).first() res += item.priority } return res } fun part2(input: String) : Int { val knapsacks = parseInput(input) var res: Int = 0 var allItems: MutableList<Set<Char>> = mutableListOf() var iter = 0 for (pack in knapsacks){ var bagContents = (pack.first.toSet() union pack.second.toSet()) allItems += bagContents if (iter % 3 == 2){ val common = (allItems[0] intersect allItems[1] intersect allItems[2]).first() res += common.priority allItems = mutableListOf() } ++iter } return res } val testInput: String = "data/day3_test.txt" check(part1(testInput) == 157) check(part2(testInput) == 70) val input: String = "data/day3.txt" println(part1(input)) println(part2(input)) }
[ { "class_path": "JonahBreslow__advent-of-code-kotlin-2022__c307ff2/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final int getPriority(char);\n Code:\n 0: iload_0\n 1: istore_1\n 2: bipush 97\n 4: iload_1\n 5: if_i...
JonahBreslow__advent-of-code-kotlin-2022__c307ff2/src/Day02.kt
import java.io.File fun main(){ fun read_file(file_path: String) : List<String> { val text = File(file_path).readLines() return text } val fix = mapOf("A" to "X", "B" to "Y", "C" to "Z") fun part1(x: String) : Int { val me: String = x[2].toString() val opp: String = fix.getValue(x[0].toString()) var score: Int = 0 // draw if (opp == me) score += 3 // Win if (opp == "X" && me == "Y") score +=6 if (opp == "Y" && me == "Z") score +=6 if (opp == "Z" && me == "X") score +=6 score += mapOf("X" to 1, "Y" to 2, "Z" to 3).getValue(me) return score } fun part2(x: String): Int { val result: String = x[2].toString() val opp: String = x[0].toString() var me: String = "A" var score: Int = 0 // draw if (result == "Y"){ score += 3 me = opp } // lose if (result == "X"){ if (opp == "A") me = "C" if (opp == "B") me = "A" if (opp == "C") me = "B" } // win if (result == "Z"){ score += 6 if (opp == "A") me = "B" if (opp == "B") me = "C" if (opp == "C") me = "A" } score += mapOf("A" to 1, "B" to 2, "C" to 3).getValue(me) return score } val testFile = read_file("data/day2_test.txt") check(testFile.map { part1(it)}.sum() == 15) check(testFile.map { part2(it)}.sum() == 12) val file = read_file("data/day2.txt") println(file.map { part1(it)} .sum()) println(file.map { part2(it)} .sum()) }
[ { "class_path": "JonahBreslow__advent-of-code-kotlin-2022__c307ff2/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: anewarray #8 // class kotlin/Pair\n 4: astore_1\n ...
JonahBreslow__advent-of-code-kotlin-2022__c307ff2/src/Day01.kt
import java.io.File fun main() { fun readFile(file_path: String) : List<String> { val text = File(file_path).readLines() return text } fun create_elves_calories(input: List<String>): List<Int>{ var calories = mutableListOf<Int>() var counter:Int = 0 for (food in input){ when(food){ "" -> { calories.add(counter) counter = 0 } else -> { counter += food.toInt() } } } return calories } fun get_max_calories(input: List<Int>, n_elves: Int): Int { val sorted_elves = input.sortedDescending() val res = sorted_elves.take(n_elves) return res.sum() } fun part1(input: String): Int { val text = readFile(input) val elfList = create_elves_calories(text) return get_max_calories(elfList, n_elves=1) } fun part2(input: String): Int { val text = readFile(input) val elfList = create_elves_calories(text) return get_max_calories(elfList, n_elves=3) } // test if implementation meets criteria from the description, like: check(part1("data/day1_test.txt") == 24000) println(part1("data/day1.txt")) println(part2("data/day1.txt")) }
[ { "class_path": "JonahBreslow__advent-of-code-kotlin-2022__c307ff2/Day01Kt.class", "javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String data/day1_test.txt\n 2: invokestatic #12 ...
BrightOS__os_3__7f4a263/src/main/kotlin/Main.kt
import java.io.File fun parseInputFile(file: File): Pair<ArrayList<Process>, Int> { var resultNumberOfTicks = 0 val list = arrayListOf<Process>().apply { file.forEachLine { it.split(" ").let { add( Process( name = it[0], numberOfTicks = it[1].toInt(), appearanceTime = if (it.size > 2) it[2].toInt() else 0 ).let { resultNumberOfTicks += it.numberOfTicks it } ) } } } return Pair(list, resultNumberOfTicks) } fun main() { val numberOfActualTicks: Int var numberOfWaitTicks = 0 var numberOfAbstractTicks = 0 var currentTick = 0 val processList = parseInputFile( // File("test1") File("test2") ).let { numberOfActualTicks = it.second it.first } val ticks = arrayListOf<String>() println(numberOfActualTicks) repeat(numberOfActualTicks) { processList.filter { it.appearanceTime <= currentTick && it.ticksLeft > 0 }.let { sublist -> if (sublist.isNotEmpty()) sublist.minBy { it.ticksLeft }.let { ticks.add(it.name) it.ticksLeft-- } else { ticks.add("_") } } currentTick++ } processList.forEach { process -> print( "${process.name} ${process.numberOfTicks} ${process.appearanceTime} " ) currentTick = 0 ticks.subList(0, ticks.indexOfLast { it.contains(process.name) } + 1).forEach { processName -> print(processName.contains(process.name).let { if (currentTick < process.appearanceTime) " " else { if (!it) numberOfWaitTicks++ numberOfAbstractTicks++ if (it) "И" else "Г" } }) currentTick++ } println() } // println(ticks) println("Efficiency: ${"%.${2}f".format((numberOfWaitTicks.toFloat() / numberOfAbstractTicks * 100))}%") } data class Process( val name: String, val numberOfTicks: Int, val appearanceTime: Int, var ticksLeft: Int = numberOfTicks )
[ { "class_path": "BrightOS__os_3__7f4a263/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n public static final kotlin.Pair<java.util.ArrayList<Process>, java.lang.Integer> parseInputFile(java.io.File);\n Code:\n 0: aload_0\n 1: ldc #10 ...
TimBo93__AdventOfCode2021__6995010/Day 12/src/main/kotlin/main.kt
import java.io.File class Route ( val from: String, val to: String ){ fun reverse(): Route { return Route(to, from) } } class Transitions { private var allTransitions = mutableMapOf<String, MutableList<String>>() fun addTransition (r: Route) { addRoute(r) addRoute(r.reverse()) } private fun addRoute(r: Route) { if(allTransitions.containsKey(r.from)) { allTransitions[r.from]!!.add(r.to) return } allTransitions[r.from] = mutableListOf(r.to) } fun getTransitionFrom(node: String): List<String> { return allTransitions[node]!!.toList() } } fun initStatePartOne() : State = State("start", listOf("start"), true) fun initStatePartTwo() : State = State("start", listOf("start"), false) class State(val agentPosition: String, private val alreadyVisitedNodes: List<String>, private val hasAlreadyVisitedOneCaveTwice: Boolean) { fun moveTo(target: String) : State { val newList = alreadyVisitedNodes.toMutableList() val hasAlreadyVisitedOneCaveTwiceNow = hasAlreadyVisitedOneCaveTwice || hasAlreadyVisited(target) if(canVisitOnlyTwice(target)) { newList.add(target) } return State(target, newList, hasAlreadyVisitedOneCaveTwiceNow) } fun canVisitNode(node: String): Boolean { if(node == "start") { return false } if(canVisitOnlyTwice(node) && hasAlreadyVisitedOneCaveTwice && hasAlreadyVisited(node)) { return false } return true } private fun hasAlreadyVisited(node: String) = alreadyVisitedNodes.contains(node) private fun canVisitOnlyTwice(node: String) = node.lowercase() == node } var numPathes = 0 class TravelEngine(private val transitions: Transitions) { fun travel(initState: State) { val route = "start" travel(initState, route) } private fun travel(currentState: State, route: String) { if(currentState.agentPosition == "end") { numPathes += 1 println(route) return } getAllPossibleMoves(currentState).forEach { val newState = currentState.moveTo(it) travel(newState, "$route -> $it") } } private fun getAllPossibleMoves(state: State) = sequence<String> { transitions.getTransitionFrom(state.agentPosition).forEach{ if(state.canVisitNode(it)) { yield (it) } } } } fun main(args: Array<String>) { val transitions = Transitions() File("input.txt").forEachLine { val parts = it.split("-") transitions.addTransition(Route(parts[0], parts[1])) } val travelEngine = TravelEngine(transitions) travelEngine.travel(initStatePartOne()) println("Number of paths: $numPathes") numPathes = 0 travelEngine.travel(initStatePartTwo()) println("Number of paths (Part Two): $numPathes") }
[ { "class_path": "TimBo93__AdventOfCode2021__6995010/MainKt.class", "javap": "Compiled from \"main.kt\"\npublic final class MainKt {\n private static int numPathes;\n\n public static final State initStatePartOne();\n Code:\n 0: new #9 // class State\n 3: dup\n ...
salvaMsanchez__curso-intro-kotlin__a2fa5b8/ejercicio4A.kt
// Parte 1: Crea una lista “listaRandom” de 100 elementos compuesta de números aleatorios comprendidos entre el 0 y el 9. // Imprime la lista por pantalla // Parte 2: Crea una lista vacía “listaResultado” en cuya posición… // Posición 0 se debe contar cuantos 0 hay en la listaRandom. // Posición 1 se debe contar cuantos 1 hay en la listaRandom. // etc. con todos los números. fun main() { var listaRandom:ArrayList<Int> = listaRandom() imprimirListaRandom(listaRandom) var listaResultado:ArrayList<Int> = listaResultado(listaRandom) imprimirListaResultado(listaResultado) println() sumaListaResultado(listaResultado) } fun listaRandom() : ArrayList<Int> { var listaRandom:ArrayList<Int> = arrayListOf() repeat(100) { var numRandom:Int = (0..9).random() listaRandom.add(numRandom) } return listaRandom } fun imprimirListaRandom(listaRandom:ArrayList<Int>) { for (num in listaRandom) println(num) } fun listaResultado(listaRandom:ArrayList<Int>) : ArrayList<Int> { var listaResultado:ArrayList<Int> = arrayListOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0) for (num in listaRandom) { when(num) { 0 -> listaResultado[0] = listaResultado[0] + 1 1 -> listaResultado[1] = listaResultado[1] + 1 2 -> listaResultado[2] = listaResultado[2] + 1 3 -> listaResultado[3] = listaResultado[3] + 1 4 -> listaResultado[4] = listaResultado[4] + 1 5 -> listaResultado[5] = listaResultado[5] + 1 6 -> listaResultado[6] = listaResultado[6] + 1 7 -> listaResultado[7] = listaResultado[7] + 1 8 -> listaResultado[8] = listaResultado[8] + 1 9 -> listaResultado[9] = listaResultado[9] + 1 } } return listaResultado } fun imprimirListaResultado(listaResultado:ArrayList<Int>) { listaResultado.forEachIndexed { index, i -> println("- El número $index aparece $i veces") } } fun sumaListaResultado(listaResultado:ArrayList<Int>) { var sumaTotal:Int = 0 for (num in listaResultado) { sumaTotal = sumaTotal + num } println("Hay $sumaTotal números") }
[ { "class_path": "salvaMsanchez__curso-intro-kotlin__a2fa5b8/Ejercicio4AKt.class", "javap": "Compiled from \"ejercicio4A.kt\"\npublic final class Ejercicio4AKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method listaRandom:()Ljava/util/ArrayList;\n 3...
becsegal__advent-of-code-2022__a4b744a/src/Day04.kt
import java.io.File fun main() { // assumes sorted fun List<Int>.fullyContains(innerList: List<Int>): Boolean { return this.first() <= innerList.first() && this.last() >= innerList.last() } // assumes sorted fun List<Int>.overlaps(otherList: List<Int>): Boolean { return (this.first() <= otherList.last() && this.last() >= otherList.first()) } fun part1(filename: String): Int? { var count: Int = 0; File(filename).forEachLine { val ranges = it.split(",") val range1: List<Int> = ranges[0].split("-").map{ it.toInt() } val range2: List<Int> = ranges[1].split("-").map{ it.toInt() } if (range1.fullyContains(range2) || range2.fullyContains(range1)) { count += 1 } } return count; } fun part2(filename: String): Int? { var count: Int = 0; File(filename).forEachLine { val ranges = it.split(",") val range1: List<Int> = ranges[0].split("-").map{ it.toInt() } val range2: List<Int> = ranges[1].split("-").map{ it.toInt() } if (range1.overlaps(range2)) { count += 1 } } return count; } println("part 1: " + part1("input_day04.txt")) println("part 2: " + part2("input_day04.txt")) }
[ { "class_path": "becsegal__advent-of-code-2022__a4b744a/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/lang/StringBuilder\n 3: dup\n 4: invokespecial #11 ...
becsegal__advent-of-code-2022__a4b744a/src/Day05.kt
import java.io.File fun main() { var stacks: ArrayList<ArrayList<String?>> = ArrayList() var instructions: ArrayList<List<Int>> = ArrayList() fun initializeStackLine(row: List<String?>) { row.forEachIndexed { index, value -> if (stacks.size <= index) { stacks.add(ArrayList<String?>()) } if (value != null) stacks[index].add(value); } } fun initalizeStacksAndInstructions(filename: String) { stacks = ArrayList() instructions = ArrayList() val elementRegex: Regex = "[A-Z]".toRegex() val movesRegex: Regex = """\d+""".toRegex() File(filename).forEachLine { if (it.contains("[")) { val elements = it.chunked(4).map{ elementRegex.find(it)?.value } initializeStackLine(elements) } else if (it.contains("move")) { instructions.add(movesRegex.findAll(it).map{ it.value.toInt() }.toList()) } } } fun part1(filename: String): String { initalizeStacksAndInstructions(filename) instructions.forEach { val nTimes = it[0] val fromStackNum = it[1] - 1 val toStackNum = it[2] - 1 repeat(nTimes) { val fromStack = stacks[fromStackNum] val moveVal = fromStack.removeAt(0) stacks[toStackNum].add(0, moveVal) } } return stacks.map{ if (it.size > 0) it[0] else "" }.joinToString(separator="") } fun part2(filename: String): String { initalizeStacksAndInstructions(filename) instructions.forEach { val nTimes = it[0] val fromStackNum = it[1] - 1 val toStackNum = it[2] - 1 var removeFrom: Int = nTimes - 1; repeat(nTimes) { val fromStack = stacks[fromStackNum] val moveVal = fromStack.removeAt(removeFrom) stacks[toStackNum].add(0, moveVal) removeFrom -= 1 } } return stacks.map{ if (it.size > 0) it[0] else "" }.joinToString(separator="") } println("part 1: " + part1("input_day05.txt")) println("part 2: " + part2("input_day05.txt")) }
[ { "class_path": "becsegal__advent-of-code-2022__a4b744a/Day05Kt.class", "javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/jvm/internal/Ref$ObjectRef\n 3: dup\n 4: invokesp...
becsegal__advent-of-code-2022__a4b744a/src/Day03.kt
import java.io.File fun main() { val letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun mispackedCharacter(contents: String): String { val compartmentAContents: CharArray = contents.substring(0, contents.length/2).toCharArray() val compartmentBContents: CharArray = contents.substring(contents.length/2).toCharArray() return compartmentAContents.intersect(compartmentBContents.asIterable()).first().toString() } fun commonCharacter(str1: String, str2: String, str3: String): String { return str1.toCharArray().intersect( str2.toCharArray().asIterable() ).intersect( str3.toCharArray().asIterable() ).first().toString() } fun part1(filename: String): Int? { var priorityTotal: Int = 0; File(filename).forEachLine { val char: String = mispackedCharacter(it) priorityTotal += letters.indexOf(char) + 1 } return priorityTotal; } fun part2(filename: String): Int? { var priorityTotal: Int = 0; var threesie: ArrayList<String> = ArrayList(); File(filename).forEachLine { threesie.add(it) if (threesie.size == 3) { val char: String = commonCharacter(threesie[0], threesie[1], threesie[2]) priorityTotal += letters.indexOf(char) + 1 threesie = ArrayList() } } return priorityTotal; } println("part 1: " + part1("input_day03.txt")) println("part 2: " + part2("input_day03.txt")) }
[ { "class_path": "becsegal__advent-of-code-2022__a4b744a/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n 2: ast...
becsegal__advent-of-code-2022__a4b744a/src/Day02.kt
import java.io.File fun main() { val notationToShape = mapOf( "A" to "Rock", "B" to "Paper", "C" to "Scissors", "X" to "Rock", "Y" to "Paper", "Z" to "Scissors" ) val shapePoints = mapOf( "Rock" to 1, "Paper" to 2, "Scissors" to 3 ) val winOver = mapOf( "A" to "B", // A-Rock loses to B-Paper "B" to "C", // B-Paper loses to C-Scissors "C" to "A" // C-Scissors loses to A-Rock ) val loseTo = mapOf( "A" to "C", // A-Rock beats C-Scissors "B" to "A", // B-Paper beats A-Rock "C" to "B" // C-Scissors beats B-Paper ) fun scoreRoundForPlayer(player: String?, opponent: String): Int { val playerShape = notationToShape[player]; val opponentShape = notationToShape[opponent]; var score: Int = shapePoints[playerShape] ?: 0; if (playerShape === opponentShape) { score += 3; } else if ( (playerShape == "Rock" && opponentShape == "Scissors") || (playerShape == "Paper" && opponentShape == "Rock") || (playerShape == "Scissors" && opponentShape == "Paper") ) { score += 6; } return score; } fun chooseShapeForResult(opponentNotation: String, result: String): String? { if (result == "Y") { // Draw return opponentNotation; } else if (result == "X") { // Lose return loseTo[opponentNotation]; } else { return winOver[opponentNotation]; } } fun part1(filename: String): Int? { var score: Int = 0; File(filename).forEachLine { val shapes = it.split(" "); score += scoreRoundForPlayer(shapes[1], shapes[0]) } return score; } fun part2(filename: String): Int? { var score: Int = 0; File(filename).forEachLine { val notation = it.split(" "); val playerShapeNotation = chooseShapeForResult(notation[0], notation[1]); score += scoreRoundForPlayer(playerShapeNotation, notation[0]) } return score; } println(part1("input_day02.txt")) println(part2("input_day02.txt")) }
[ { "class_path": "becsegal__advent-of-code-2022__a4b744a/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: bipush 6\n 2: anewarray #8 // class kotlin/Pair\n 5: astore_1\n 6...
zlataovce__aoc23__0f5317f/src/main/kotlin/day5B.kt
import kotlin.math.max import kotlin.math.min fun main() = println( generateSequence(::readLine) .joinToString("\n") .split("\n\n") .let { p -> Pair( p[0].substringAfter(": ") .split(' ') .map(String::toLong), p.drop(1) .map { s -> s.split('\n') .drop(1) .map { l -> l.split(' ').let { (a, b, c) -> Triple(a.toLong(), b.toLong(), c.toLong()) } } } ) } .let { (seed, fs) -> seed.chunked(2) .map { (a, b) -> fs // this is so awful, why does it work .fold(listOf(a to a + b)) { y, t -> mutableListOf<Pair<Long, Long>>().also { l -> l.addAll( t.fold(y) { r, (dst, src, len) -> r.flatMap { (x, y) -> buildList { (x to min(y, src)) .takeIf { it.second > it.first } ?.let(::add) (max(src + len, x) to y) .takeIf { it.second > it.first } ?.let(::add) (max(x, src) to min(src + len, y)) .takeIf { it.second > it.first } ?.let { l.add((it.first - src + dst) to (it.second - src + dst)) } } } } ) } } .minOf { min(it.first, it.second) } } } .min() )
[ { "class_path": "zlataovce__aoc23__0f5317f/Day5BKt.class", "javap": "Compiled from \"day5B.kt\"\npublic final class Day5BKt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field Day5BKt$main$1.INSTANCE:LDay5BKt$main$1;\n 3: checkcast #14 ...
aisanu__advent-of-code__25dfe70/src/main/kotlin/Day3.kt
object Day3 { // TODO: How to fix this mess fun manhattanDistance(est: Long): Long { val last = (1..Long.MAX_VALUE).takeWhile { Day3.bottomRightValue(it) <= est }.last() val box = Day3.bottomRightValue(last) var diff = est - box val n = 2 * last var (x, y) = (last - 1) to -(last - 1) if(diff > 0L){ x++ diff-- for(i in 1..n - 1) { if(diff <= 0) break y++ diff-- } for(i in 1..n) { if(diff <= 0) break x-- diff-- } for(i in 1..n) { if(diff <= 0) break y-- diff-- } for(i in 1..n) { if(diff <= 0) break x++ diff-- } } return Math.abs(x) + Math.abs(y) } fun bottomRightValue(x: Long): Long { require(x > 0) { "Only non negative number allowed" } return when(x) { 1L -> 1 else -> bottomRightValue(x - 1) + 8 * (x - 1) } } fun populateMapsky(first: Int, output: MutableMap<Pair<Int, Int>, Long>) { val start = bottomRightValue(first.toLong()) val end = bottomRightValue((first + 1).toLong()) var diff = end - start - 1 var x = first var y = -(first - 1) var n = (first) * 2 output[x to y] = sumNeighboor(output, x, y) if(diff > 0L){ for(i in 1..n - 1) { if(diff <= 0) break y++ diff-- output[x to y] output[x to y] = sumNeighboor(output, x, y) } for(i in 1..n) { if(diff <= 0) break x-- diff-- output[x to y] = sumNeighboor(output, x, y) } for(i in 1..n) { if(diff <= 0) break y-- diff-- output[x to y] = sumNeighboor(output, x, y) } for(i in 1..n) { if(diff <= 0) break x++ diff-- output[x to y] = sumNeighboor(output, x, y) } } } fun sumNeighboor(map: MutableMap<Pair<Int, Int>, Long>, x: Int, y: Int): Long { val retVal = map.getOrDefault((x + 1) to (y + 0), 0L) + map.getOrDefault((x + 1) to (y + 1), 0L) + map.getOrDefault((x + 0) to (y + 1), 0L) + map.getOrDefault((x + -1) to (y + 1), 0L) + map.getOrDefault((x + -1) to (y + 0), 0L) + map.getOrDefault((x + -1) to (y + -1), 0L) + map.getOrDefault((x + 0) to (y + -1), 0L) + map.getOrDefault((x + 1) to (y + -1), 0L) if(retVal >= 277678) println("Found at ($x, $y): $retVal") return retVal } }
[ { "class_path": "aisanu__advent-of-code__25dfe70/Day3.class", "javap": "Compiled from \"Day3.kt\"\npublic final class Day3 {\n public static final Day3 INSTANCE;\n\n private Day3();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
aisanu__advent-of-code__25dfe70/src/main/kotlin/Day2.kt
object Day2 { fun part1Solution(input: String): Long = splitRows(input) .map { splitColumns(it) } .map { minMaxDiff(it) } .sum() fun part2Solution(input: String): Long = splitRows(input) .map { splitColumns(it) } .map { wholeDivider(it) } .sum() fun minMaxDiff(input: List<Long>): Long { val min = requireNotNull(input.min()) { "Cannot found min" } val max = requireNotNull(input.max()) { "Cannot found max" } return Math.abs(max - min) } fun wholeDivider(input: List<Long>): Long = input.mapIndexed { index, value -> val result = input.drop(index + 1).find { it % value == 0L || value % it == 0L } result?.let { Math.max(result, value) / Math.min(result, value) } }.filterNotNull().first() fun splitRows(input: String): List<String> = input.split("\n").filter { it.isNotBlank() } fun splitColumns(input: String): List<Long> = input.split(Regex("[ \t]")).map { it.toLong() } }
[ { "class_path": "aisanu__advent-of-code__25dfe70/Day2.class", "javap": "Compiled from \"Day2.kt\"\npublic final class Day2 {\n public static final Day2 INSTANCE;\n\n private Day2();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
pocmo__AdventOfCode2021__73bbb6a/src/day6/day6.kt
import java.io.File fun readFishMap(): MutableMap<Int, Long> { val fishes = File("day6.txt") .readLines()[0] .split(",") .map { it.toInt() } val map = mutableMapOf<Int, Long>() fishes.forEach { fish -> val count = map.getOrDefault(fish, 0) map[fish] = count + 1 } return map } fun MutableMap<Int, Long>.simulateLanternFishes() { val reproducingFishes = get(0) ?: 0 for (i in 1 .. 8) { val count = get(i) ?: 0 put(i - 1, count) } put(8, reproducingFishes) val sixFishesCount = get(6) ?: 0 put(6, sixFishesCount + reproducingFishes) } fun part2() { val map = readFishMap() println(map) repeat(256) { map.simulateLanternFishes() } println(map) val fishCount = map.values.sum() println("Total fishes: $fishCount") } fun part1() { val map = readFishMap() println(map) repeat(80) { map.simulateLanternFishes() } println(map) val fishCount = map.values.sum() println("Total fishes: $fishCount") } fun main() { part2() }
[ { "class_path": "pocmo__AdventOfCode2021__73bbb6a/Day6Kt.class", "javap": "Compiled from \"day6.kt\"\npublic final class Day6Kt {\n public static final java.util.Map<java.lang.Integer, java.lang.Long> readFishMap();\n Code:\n 0: new #10 // class java/io/File\n 3: du...
chaking__study__a394f10/Algorithm/HackerRank/src/OrganizingContainersOfBalls.kt
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* // Complete the organizingContainers function below. fun organizingContainers(container: Array<Array<Int>>) : String = when (MyOrganizingContainers(container)) { true -> "Possible" else -> "Impossible" } fun MyOrganizingContainers(containers: Array<Array<Int>>): Boolean { val cons = Array(containers.size) { 0 } val types = Array(containers.size) { 0 } containers.forEachIndexed { containerIndex, container -> container.forEachIndexed { typeIndex, type -> cons[containerIndex] += type types[typeIndex] += type } } println(Arrays.deepToString(cons)) println(Arrays.deepToString(types)) val consList = cons.sortedArray().toList() val typesList = types.sortedArray().toList() return consList == typesList } fun main(args: Array<String>) { val inputs = listOf( arrayOf(arrayOf(1, 3, 1), arrayOf(2, 1, 2), arrayOf(3, 3, 3)) , arrayOf(arrayOf(0, 2, 1), arrayOf(1, 1, 1), arrayOf(2, 0, 0)) ) inputs .map { organizingContainers(it) } .forEach { println(it) } }
[ { "class_path": "chaking__study__a394f10/OrganizingContainersOfBallsKt.class", "javap": "Compiled from \"OrganizingContainersOfBalls.kt\"\npublic final class OrganizingContainersOfBallsKt {\n public static final java.lang.String organizingContainers(java.lang.Integer[][]);\n Code:\n 0: aload_0\n ...
chaking__study__a394f10/Algorithm/HackerRank/src/BigNumberMultiplication.kt
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* // Complete the plusMinus function below. fun multipliedBigNumbers(number1: String, number2: String): String { return realMul(number1.toCharArray(), number2.toCharArray()).joinToString("") } fun realMul(number1: CharArray, number2: CharArray): CharArray { val results = (0..9).map { mulSingle(number1, it) } results.map { it.joinToString { "" } }.forEach{println(it)} return charArrayOf('3', '4') } fun mulSingle(number1: CharArray, target: Int): CharArray { val result = CharArray(number1.size + 1){ '0' } number1.reversed().forEachIndexed { index, c -> val r = c.toInt() * target if (r > 9) result[index + 1] = 1.toChar() val sum = result[index].toInt() + r % 10 if (sum > 9 ) result[index + 1] = (result[index + 1].toInt() + 1).toChar() result[index] = (result[index].toInt() + sum % 10).toChar() } return result } fun input() { val scan = Scanner(System.`in`) val arr = scan.nextLine().split(" ").map{ it.trim() }.toTypedArray() multipliedBigNumbers(arr[0], arr[1]) } fun auto() { val result = multipliedBigNumbers("4819", "9") println(result) } fun main(args: Array<String>) { // input() auto() }
[ { "class_path": "chaking__study__a394f10/BigNumberMultiplicationKt.class", "javap": "Compiled from \"BigNumberMultiplication.kt\"\npublic final class BigNumberMultiplicationKt {\n public static final java.lang.String multipliedBigNumbers(java.lang.String, java.lang.String);\n Code:\n 0: aload_0\n ...
chaking__study__a394f10/Algorithm/HackerRank/src/BiggerIsGreater.kt
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* fun recursive(w: String, best: String, bestFlag: Boolean, next: String, nextFlag: Boolean, index: Int): String { val subset = w.substring(1) val subsets = subset.mapIndexed { subIndex, char -> var a: CharArray = w.toCharArray() val temp = a[index] a[index] = char a[subIndex] = temp a.joinToString("") } subsets.sorted().forEach{ println(it) } println(subsets) return "" } // Complete the biggerIsGreater function below. fun biggerIsGreater(w: String): String { return recursive(w, w, false, "", false, 0) } fun main(args: Array<String>) { // val inputs = arrayOf("ab", "bb", "hefg", "dhck", "dkhc") val inputs = arrayOf("hefg") inputs.forEach { (biggerIsGreater(it)) } // inputs.forEach { println(biggerIsGreater(it)) } }
[ { "class_path": "chaking__study__a394f10/BiggerIsGreaterKt.class", "javap": "Compiled from \"BiggerIsGreater.kt\"\npublic final class BiggerIsGreaterKt {\n public static final java.lang.String recursive(java.lang.String, java.lang.String, boolean, java.lang.String, boolean, int);\n Code:\n 0: aloa...
JohannaGudmandsen__aoc-2022__21daaa4/src/Day09.kt
import java.io.File import kotlin.collections.* class Position(var X:Int, var Y:Int) fun moveTail(head:Position, tail:Position){ if (head.X > tail.X + 1){ tail.X++ if (head.Y > tail.Y){ tail.Y++ } else if (head.Y < tail.Y){ tail.Y-- } } else if (head.X < tail.X - 1){ tail.X-- if (head.Y > tail.Y){ tail.Y++ } else if (head.Y < tail.Y){ tail.Y-- } } else if (head.Y > tail.Y + 1){ tail.Y++ if (head.X > tail.X){ tail.X++ } else if (head.X < tail.X){ tail.X-- } } else if (head.Y < tail.Y - 1 ){ tail.Y-- if (head.X > tail.X){ tail.X++ } else if (head.X < tail.X){ tail.X-- } } } fun Day09() { val input = File("src/input/day09.txt").readLines() var head = Position(500,500) var tailTask1 = Position(500,500) var tailsTask2 = ArrayList<Position>() tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) tailsTask2.add(Position(500, 500)) var visitedPositionsTask1 = ArrayList<String>() var visitedPositionsTask2 = ArrayList<String>() for(line in input){ var instruction = line.split(" ") var direction = instruction[0] var times = instruction[1].toInt() for(i in 0..times-1 step 1){ if (direction == "R"){ head.X++ } else if (direction == "L"){ head.X-- } else if (direction == "U"){ head.Y++ } else { // "D" head.Y-- } moveTail(head, tailTask1) visitedPositionsTask1.add(tailTask1.X.toString() + tailTask1.Y.toString()) var prevTail = head for(tailTask2 in tailsTask2){ moveTail(prevTail, tailTask2) prevTail = tailTask2 } visitedPositionsTask2.add(tailsTask2.last().X.toString() + tailsTask2.last().Y.toString()) } } var task1 = visitedPositionsTask1.distinct().count() var task2 = visitedPositionsTask2.distinct().count() println("Day 9 Task 1: $task1") // 6563 println("Day 9 Task 2: $task2") // 2653 }
[ { "class_path": "JohannaGudmandsen__aoc-2022__21daaa4/Day09Kt.class", "javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt {\n public static final void moveTail(Position, Position);\n Code:\n 0: aload_0\n 1: ldc #9 // String head\n 3: invokestatic...
JohannaGudmandsen__aoc-2022__21daaa4/src/Day08.kt
import java.io.File import kotlin.collections.* fun getViewingScore(height:Int, trees:List<Int>):Int{ var viewingScore = 0 for (tree in trees){ viewingScore++ if (tree >= height){ break; } } return viewingScore; } fun Day08() { val input = File("src/input/day08.txt").readLines() var forest = input.map { treeLine -> treeLine.map { tree -> Integer.parseInt("" + tree) }} var task1 = 0 var task2 = 0 for (i in 0..forest.size-1 step 1){ var treeLine = forest[i] for (j in 0..treeLine.size-1 step 1){ val treeHeight = treeLine[j] // Check right var treesToRight = treeLine.subList(j+1, treeLine.size) var viewingscoreRight = getViewingScore(treeHeight, treesToRight) // Check left var treesToLeft = treeLine.subList(0, j).reversed() var viewingscoreLeft = getViewingScore(treeHeight, treesToLeft) // Check down var treesToDown = forest.subList(i+1, forest.size).map { it -> it.get(j) } var viewingscoreDown = getViewingScore(treeHeight, treesToDown) // Check up var treesToUp = forest.subList(0, i).map { it -> it.get(j) }.reversed() var viewingscoreUp = getViewingScore(treeHeight, treesToUp) val visible = !treesToRight.any { it -> it >= treeHeight } || !treesToLeft.any { it -> it >= treeHeight } || !treesToUp.any { it -> it >= treeHeight } || !treesToDown.any { it -> it >= treeHeight } if (visible){ task1++ } var totalViewingScore = viewingscoreRight * viewingscoreLeft * viewingscoreDown * viewingscoreUp if (totalViewingScore > task2){ task2 = totalViewingScore } } } println("Day 8 Task 1: $task1") //1794 println("Day 8 Task 2: $task2") // 199272 }
[ { "class_path": "JohannaGudmandsen__aoc-2022__21daaa4/Day08Kt.class", "javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final int getViewingScore(int, java.util.List<java.lang.Integer>);\n Code:\n 0: aload_1\n 1: ldc #10 // String tr...
JohannaGudmandsen__aoc-2022__21daaa4/src/Day11.kt
import java.io.File import kotlin.collections.* class Test(var divisibleBy:Int, var trueThrowsToMonkey:Int, var falseThrowsToMonkey:Int) class Operation(var type:String, var rightValue:String, var leftValue:String) class Monkey(var id:Int, var items:ArrayList<Long>, var op:Operation, var test:Test, var inspect:Long) fun doOneRound(monkeys:ArrayList<Monkey>, divideWorryLevelBy3:Boolean, modWorryLevelWith:Int){ for (monkey in monkeys){ for (item in monkey.items){ monkey.inspect++ var left:Long var right:Long if (monkey.op.rightValue.all { it -> it.isDigit() }){ right = monkey.op.rightValue.toLong() } else { right = item } if (monkey.op.leftValue.all { it -> it.isDigit() }){ left = monkey.op.leftValue.toLong() } else { left = item } var worryLevel:Long if (monkey.op.type == "+"){ worryLevel = (left + right) } else { worryLevel = (left * right) } if (divideWorryLevelBy3){ worryLevel /= 3 } else { worryLevel = worryLevel % modWorryLevelWith } if (worryLevel.mod(monkey.test.divisibleBy.toLong()) == 0.toLong()){ var throwToMonkey = monkeys.filter { it -> it.id == monkey.test.trueThrowsToMonkey }.first() throwToMonkey.items.add(worryLevel) } else { var throwToMonkey = monkeys.filter { it -> it.id == monkey.test.falseThrowsToMonkey }.first() throwToMonkey.items.add(worryLevel) } } monkey.items = ArrayList<Long>() } } fun Day11() { val input = File("src/input/day11.txt").readLines() var monkeysTask1 = ArrayList<Monkey>() var monkeysTask2 = ArrayList<Monkey>() var modWorryLevelWith = 1 for(i in 0..input.size-1 step 7){ var monkeyId = input[i].filter { it.isDigit() }.toInt() var startingItems = input[i+1].split(":")[1].split(",").map { it.filter { it.isDigit() }.toLong() } var op = input[i+2].split("=")[1].split(" ") var divisibleBy = input[i+3].filter { it.isDigit() }.toInt() modWorryLevelWith = modWorryLevelWith * divisibleBy var ifTrueThrowToMonkey = input[i+4].filter { it.isDigit() }.toInt() var ifFalseThrowToMonkey = input[i+5].filter { it.isDigit() }.toInt() var monkeyTask1 = Monkey( monkeyId, ArrayList<Long>(startingItems), Operation(op[2], op[1], op[3]), Test(divisibleBy, ifTrueThrowToMonkey, ifFalseThrowToMonkey), 0) var monkeyTask2 = Monkey( monkeyId, ArrayList<Long>(startingItems), Operation(op[2], op[1], op[3]), Test(divisibleBy, ifTrueThrowToMonkey, ifFalseThrowToMonkey), 0) monkeysTask1.add(monkeyTask1) monkeysTask2.add(monkeyTask2) } for (i in 0..19 step 1){ doOneRound(monkeysTask1, true, modWorryLevelWith) } for (i in 0..9999 step 1){ doOneRound(monkeysTask2, false, modWorryLevelWith) } var inspectList = monkeysTask1.map { it -> it.inspect }.sortedDescending() var task1 = inspectList[0] * inspectList[1] var inspectListTask2 = monkeysTask2.map { it -> it.inspect }.sortedDescending() var task2:Long = inspectListTask2[0].toLong() * inspectListTask2[1].toLong() println("Day 11 Task 1: $task1") // 55216 println("Day 11 Task 2: $task2") // 12848882750 }
[ { "class_path": "JohannaGudmandsen__aoc-2022__21daaa4/Day11Kt.class", "javap": "Compiled from \"Day11.kt\"\npublic final class Day11Kt {\n public static final void doOneRound(java.util.ArrayList<Monkey>, boolean, int);\n Code:\n 0: aload_0\n 1: ldc #10 // String mon...
atig05__HACKTOBERFEST-2021__a13b4a7/DSA/kotlin-programming/happy_number.kt
/* kotlin program to check happy numbers A happy number is a number, if we reach to 1 after replacing the number by the squares of the digits of the number Following examples will help to understand better:- Input: n = 19 Output: True 19 is Happy Number, 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1 As we reached to 1, 19 is a Happy Number. Input: n = 20 Output: False 20 is not a happy number 2^2 + 0^2 = 4 4^2 = 16 As we cannot reach to 1, 20 is not a happy number */ import java.util.* fun squaredSum(n: Int): Int{ var sum_of_square:Int = 0 var c:Int = n while(c!=0){ sum_of_square += c%10 * (c % 10) c /= 10 } return sum_of_square } //defining a boolean function to check whether the number is happy number or not fun Happynumber(number: Int): Boolean { var slow: Int var fast: Int fast = number slow = fast do { slow = squaredSum(slow) fast = squaredSum(squaredSum(fast)) } while (slow != fast) return slow == 1 } //Testing code fun main(){ val input = Scanner(System.`in`) println("Enter the number which you want to check") val n = input.nextInt() if (Happynumber(n)) println("$n is a Happy number") else println("$n is not a happy number") } /* Enter the number which you want to check 19 19 is a Happy number Enter the number which you want to check 20 20 is not a happy number */ /* Time complexity :- O(N) Space complexity :- O(1), which is constant */
[ { "class_path": "atig05__HACKTOBERFEST-2021__a13b4a7/Happy_numberKt.class", "javap": "Compiled from \"happy_number.kt\"\npublic final class Happy_numberKt {\n public static final int squaredSum(int);\n Code:\n 0: iconst_0\n 1: istore_1\n 2: iload_0\n 3: istore_2\n 4: iload_...
teemu-rossi__AdventOfCode__16fe605/day3/day3/src/main/kotlin/Day8.kt
val digits = mapOf( 0 to "abcefg", // 6 1 to "cf", // 2 2 to "acdeg", // 5 3 to "acdfg", // 5 4 to "bcdf", // 4 5 to "abdfg", // 5 6 to "abdefg", // 6 7 to "acf", // 3 8 to "abcdefg", // 7 9 to "abcdfg" // 6 ) fun main() { val values = generateSequence(::readLine) .mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } } .toList() var uniqCount = 0 var totalSum = 0 for (line in values) { val split = line.split(" ") val possibleSignals = split.take(10) val valueShown = split.takeLast(4) uniqCount += valueShown.count { it.length == 2 || it.length == 7 || it.length == 3 || it.length == 4 } val mapping = mutableMapOf( "a" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "b" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "c" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "d" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "e" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "f" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "g" to mutableListOf("a", "b", "c", "d", "e", "f", "g") ) val digitMapping = mutableMapOf<String, Int>() fun mustBeDigit(sig: String, digit: Int) { for (c in sig) { mapping[c.toString()]!!.removeIf { it !in digits[digit]!! } } digitMapping[sig] = digit } for (sig in possibleSignals) { when (sig.length) { 2 -> mustBeDigit(sig, 1) 4 -> mustBeDigit(sig, 4) 3 -> mustBeDigit(sig, 7) 7 -> mustBeDigit(sig, 8) } } val seven = possibleSignals.first { it.length == 3 }.toList().map { it.toString() } val four = possibleSignals.first { it.length == 4 }.toList().map { it.toString() } val one = possibleSignals.first { it.length == 2 }.toList().map { it.toString() } // seven has 'aaaa' in addition to one // mapping["a"] = (seven - one).toMutableList() // four has 'bb' and 'dddd' in addition to one // val bOrD = four - one // mapping["b"]!!.removeIf { it !in bOrD } fun mustBeSegment(input: String, real: String) { mapping[input]!!.removeAll { it != real } mapping.keys.forEach { key -> if (key != input) { mapping[key]!!.removeAll { it == real } } } } // count instances in digits for (segment in "abcdefg".toList().map { it.toString() }) { val count = possibleSignals.count { segment in it } when (count) { 6 -> mustBeSegment(segment, "b") // 8 -> mustBeSegment(segment, "c") // 7 -> "d" tai "g" 4 -> mustBeSegment(segment, "e") 9 -> mustBeSegment(segment, "f") } } repeat(10) { for ((k, v) in mapping.toMap()) { if (v.size == 1) { for ((k2, v2) in mapping.toMap()) { if (k2 != k) { mapping[k2]!!.removeAll { it == v.first() } } } } } } val mappedDigits = buildString { for (v in valueShown) { val mapped = v.toList().mapNotNull { mapping[it.toString()]?.first() }.sorted().joinToString("") val digit = digits.filter { (k, v) -> v == mapped }.keys.first() append(digit) } } totalSum += mappedDigits.toInt() println("$line --> $mappedDigits") for ((k, v) in mapping) { println("$k ${v.joinToString("")}") } } println("uniqCount = $uniqCount, totalSum=$totalSum") } // 0: 1: 2: 3: 4: // aaaa .... aaaa aaaa .... // b c . c . c . c b c // b c . c . c . c b c // .... .... dddd dddd dddd // e f . f e . . f . f // e f . f e . . f . f // gggg .... gggg gggg .... // // 5: 6: 7: 8: 9: // aaaa aaaa aaaa aaaa aaaa // b . b . . c b c b c // b . b . . c b c b c // dddd dddd .... dddd dddd // . f e f . f e f . f // . f e f . f e f . f // gggg gggg .... gggg gggg // //println("a 8: ${digits.values.count { it.contains("a") }}") //println("b 6: ${digits.values.count { it.contains("b") }}") //println("c 8: ${digits.values.count { it.contains("c") }}") //println("d 7: ${digits.values.count { it.contains("d") }}") //println("e 4: ${digits.values.count { it.contains("e") }}") //println("f 9: ${digits.values.count { it.contains("f") }}") //println("g 7: ${digits.values.count { it.contains("g") }}") //
[ { "class_path": "teemu-rossi__AdventOfCode__16fe605/Day8Kt$main$values$1.class", "javap": "Compiled from \"Day8.kt\"\nfinal class Day8Kt$main$values$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<java.lang.String> {\n public static final Day8Kt$main$values$1 I...
teemu-rossi__AdventOfCode__16fe605/day3/day3/src/main/kotlin/Main.kt
fun main(args: Array<String>) { println("Hello World!") val values = generateSequence(::readLine) .mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } } .toList() values.forEach { println(it) } val bits = values.maxOf { it.length } val gamma = buildString { for (i in 0 until bits) { val mostCommon = if (values.countOnes(i) >= (values.size + 1) / 2) "1" else "0" append(mostCommon) } } println("gamma=$gamma") val epsilon = gamma.map { if (it == '0') '1' else '0' }.joinToString(separator = "") println("epsilon=$epsilon") println("power=${gamma.toInt(2) * epsilon.toInt(2)}") // oxygen generator rating val list1 = values.toMutableList() var oxygenGen: Int? = null for (i in 0 until bits) { val mostCommon = if (list1.countOnes(i) >= (list1.size + 1) / 2) "1" else "0" println("mostCommon[$i]=$mostCommon (ones=${list1.countOnes(i)} list size=${list1.size}}") list1.removeIf { it[i] != mostCommon[0] } if (list1.size <= 1) { println("oxygen generator: ${list1.firstOrNull()}") oxygenGen = list1.firstOrNull()?.toInt(2) break } } // CO2 scrubber rating val list2 = values.toMutableList() var scrubber: Int? = null for (i in 0 until bits) { val leastCommon = if (list2.countOnes(i) < (list2.size + 1) / 2) "1" else "0" list2.removeIf { it[i] != leastCommon[0] } if (list2.size <= 1) { println("scrubber first: ${list2.firstOrNull()}") scrubber = list2.firstOrNull()?.toInt(2) break } } println("oxygenGen=$oxygenGen co2scrubber=$scrubber multi=${oxygenGen?.times(scrubber ?: 0)}") } fun List<String>.countOnes(index: Int): Int = count { it[index] == "1"[0] }
[ { "class_path": "teemu-rossi__AdventOfCode__16fe605/MainKt$main$values$1.class", "javap": "Compiled from \"Main.kt\"\nfinal class MainKt$main$values$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<java.lang.String> {\n public static final MainKt$main$values$1 I...
teemu-rossi__AdventOfCode__16fe605/day3/day3/src/main/kotlin/Day4.kt
val CARD_WIDTH = 5 val CARD_HEIGHT = 5 fun List<Int>.isBingo(inputs: List<Int>) = this.all { inputs.contains(it) } data class BingoCard( val numbers: List<Int> ) { fun get(row: Int, column: Int): Int = numbers[row * CARD_WIDTH + column] fun getRow(row: Int) = (0 until CARD_WIDTH).map { get(row, it) } fun getColumn(column: Int) = (0 until CARD_HEIGHT).map { get(it, column) } fun isBingo(inputs: List<Int>): Boolean { for (row in 0 until CARD_HEIGHT) { if (getRow(row).isBingo(inputs)) { return true } } for (col in 0 until CARD_WIDTH) { if (getColumn(col).isBingo(inputs)) { return true } } return false } fun getScore(inputs: List<Int>): Int = numbers.filter { it !in inputs }.sum() } fun main(args: Array<String>) { println("Hello World!") val values = generateSequence(::readLine) .mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } } .toList() val bingoInput = values.first().split(",").map { it.toInt() } val boards = values .drop(1) .windowed(CARD_HEIGHT, step = CARD_HEIGHT) .map { list -> BingoCard(list.joinToString(" ").split(" ").filter { it.isNotBlank() }.map { num -> num.toInt() }) } for (i in bingoInput.indices) { val inputs = bingoInput.take(i) val winner = boards.firstOrNull { it.isBingo(inputs) } if (winner != null) { println("score: ${winner.getScore(inputs)}") println("result: ${winner.getScore(inputs) * bingoInput[i - 1]}") break } } val boards2 = boards.toMutableList() for (i in 1 until bingoInput.size) { val inputs = bingoInput.take(i) println("i=$i inputs=$inputs") val winners = boards2.filter { it.isBingo(inputs) } if (winners.size == 1 && boards2.size == 1) { println("2nd score: ${winners.first().getScore(inputs)}") println("2nd result: ${winners.first().getScore(inputs) * inputs.last()}") break } println("removed $winners, remaining ${boards2.size}") boards2.removeAll(winners) } }
[ { "class_path": "teemu-rossi__AdventOfCode__16fe605/Day4Kt$main$values$1.class", "javap": "Compiled from \"Day4.kt\"\nfinal class Day4Kt$main$values$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<java.lang.String> {\n public static final Day4Kt$main$values$1 I...
teemu-rossi__AdventOfCode__16fe605/day3/day3/src/main/kotlin/Day13.kt
data class PointI(val x: Int, val y: Int) fun main(args: Array<String>) { val values = generateSequence(::readLine) .mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } } .toList() val coords = values .filter { it.contains(",") } .map { val (x, y) = it.split(",") PointI(x.toInt(), y.toInt()) } val folds = mutableListOf<(PointI) -> PointI>() values .filter { it.contains("=") } .forEach { val (a, b) = it.split("=") val axis = a.last() val coord = b.toInt() if (axis == 'x') { folds += { point -> point.copy(x = if (point.x > coord) 2 * coord - point.x else point.x) } } else if (axis == 'y') { folds += { point -> point.copy(y = if (point.y > coord) 2 * coord - point.y else point.y) } } } val foldedCoords1 = coords.map { point -> folds.take(1).fold(point) { i, p -> p(i) } }.toSet() println("foldedCoords1.size=${foldedCoords1.size}") val foldedCoords2 = coords.map { point -> folds.fold(point) { i, p -> p(i) } }.toSet() println("foldedCoords2.size=${foldedCoords2.size}") for (y in 0..foldedCoords2.maxOf { it.y }) { println(buildString { for (x in 0..foldedCoords2.maxOf { it.x }) { if (PointI(x, y) in foldedCoords2) append("#") else append(".") } }) } }
[ { "class_path": "teemu-rossi__AdventOfCode__16fe605/Day13Kt.class", "javap": "Compiled from \"Day13.kt\"\npublic final class Day13Kt {\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 ...
teemu-rossi__AdventOfCode__16fe605/day3/day3/src/main/kotlin/Day5.kt
import kotlin.math.abs import kotlin.math.max import kotlin.math.min data class Point(val x: Int, val y: Int) { companion object { fun from(string: String): Point { val s = string.split(",").mapNotNull { it.trim().takeUnless { it.isEmpty() } } require(s.size == 2) return Point(s[0].toInt(), s[1].toInt()) } } } data class Line(val a: Point, val b: Point) { companion object { fun from(string: String): Line { val s = string.split("->").mapNotNull { it.trim().takeUnless { it.isEmpty() } } require(s.size == 2) return Line(Point.from(s[0]), Point.from(s[1])) } } } data class Field( val numbers: MutableList<Int>, val span: Int ) { fun get(x: Int, y: Int): Int = numbers[y * span + x] fun inc(x: Int, y: Int) = set(x, y, get(x ,y) + 1) fun set(x: Int, y: Int, value: Int) { numbers[y * span + x] = value } fun incLine(line: Line) { val minx = min(line.a.x, line.b.x) val maxx = max(line.a.x, line.b.x) val miny = min(line.a.y, line.b.y) val maxy = max(line.a.y, line.b.y) if (line.a.x == line.b.x) { for (y in min(line.a.y, line.b.y)..max(line.a.y, line.b.y)) { inc(line.a.x, y) } } else if (line.a.y == line.b.y) { for (x in min(line.a.x, line.b.x)..max(line.a.x, line.b.x)) { inc(x, line.a.y) } } else if (maxx - minx == maxy - miny) { var x = line.a.x var y = line.a.y val dx = if (line.b.x > line.a.x) 1 else -1 val dy = if (line.b.y > line.a.y) 1 else -1 do { inc(x, y) x += dx y += dy } while (x != line.b.x) inc(x, y) } else { assert(false) { "Invalid line $line" } } } } fun main(args: Array<String>) { val values = generateSequence(::readLine) .mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } } .toList() val lines = values.map { Line.from(it) } val width = lines.maxOf { max(it.a.x, it.b.x) } + 1 val height = lines.maxOf { max(it.a.y, it.b.y) } + 1 val field = Field(MutableList(width * height) { 0 }, width) for (line in lines) { field.incLine(line) } val count = field.numbers.count { it >= 2 } println(count) }
[ { "class_path": "teemu-rossi__AdventOfCode__16fe605/Day5Kt$main$values$1.class", "javap": "Compiled from \"Day5.kt\"\nfinal class Day5Kt$main$values$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<java.lang.String> {\n public static final Day5Kt$main$values$1 I...
3mtee__exercism-kotlin__6e3eb88/yacht/src/main/kotlin/YachtCategory.kt
internal fun countDices(dices: List<Int>, digit: Int) = dices.filter { it == digit }.sum() enum class YachtCategory(val score: (dices: List<Int>) -> Int) { YACHT({ if (it.toSet().size == 1) 50 else 0 }), ONES({ countDices(it, 1) }), TWOS({ countDices(it, 2) }), THREES({ countDices(it, 3) }), FOURS({ countDices(it, 4) }), FIVES({ countDices(it, 5) }), SIXES({ countDices(it, 6) }), FULL_HOUSE({ dices -> dices .groupingBy { it } .eachCount() .let { if (it.values.toSet() != setOf(2,3)) { emptyMap() } else { it } } .entries .filter { it.value == 2 || it.value == 3 } .sumOf { it.key * it.value } }), FOUR_OF_A_KIND({ dices -> dices .groupingBy { it } .eachCount() .entries .filter { it.value >= 4 } .sumOf { it.key * 4 } }), LITTLE_STRAIGHT({ if (it.sorted() == listOf(1, 2, 3, 4, 5)) 30 else 0 }), BIG_STRAIGHT({ if (it.sorted() == listOf(2, 3, 4, 5, 6)) 30 else 0 }), CHOICE({ it.sum() }) }
[ { "class_path": "3mtee__exercism-kotlin__6e3eb88/YachtCategory$_init_$lambda$11$$inlined$groupingBy$1.class", "javap": "Compiled from \"_Collections.kt\"\npublic final class YachtCategory$_init_$lambda$11$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lang.Integer, java.lang.Integer> {\n ...
3mtee__exercism-kotlin__6e3eb88/forth/src/main/kotlin/Forth.kt
class Forth { companion object { private val OPS: Map<String, (List<Int>) -> List<Int>> = mapOf( "+" to { require(it.size >= 2) { "tsk-tsk-tsk" } it.dropLast(2) + it.takeLast(2).sum() }, "-" to { require(it.size >= 2) { "tsk-tsk-tsk" } it.dropLast(2) + it.takeLast(2).reduce { acc, i -> acc - i } }, "*" to { require(it.size >= 2) { "tsk-tsk-tsk" } it.dropLast(2) + it.takeLast(2).reduce { acc, i -> acc * i } }, "/" to { require(it.size >= 2 && it[1] != 0) { "tsk-tsk-tsk" } it.dropLast(2) + it.takeLast(2).reduce { acc, i -> acc / i } }, "dup" to { require(it.isNotEmpty()) { "tsk-tsk-tsk" } it + it.last() }, "drop" to { require(it.isNotEmpty()) { "tsk-tsk-tsk" } it.dropLast(1) }, "swap" to { require(it.size >= 2) { "tsk-tsk-tsk" } val sub = it.takeLast(2) it.dropLast(2) + sub.last() + sub[0] }, "over" to { require(it.size >= 2) { "tsk-tsk-tsk" } it + it[it.size - 2] } ) } fun evaluate(vararg line: String) = processReplacements(line.asList()) .fold(listOf<List<Int>>()) { acc, s -> acc + listOf(evaluateLine(s)) } .flatMap { it.toList() } private fun processReplacements(lines: List<String>): List<String> { val replacements = mutableMapOf<String, String>() return lines.mapNotNull { val line = it.lowercase() if (line.matches(Regex(":.*;"))) { updateReplacementsMap(line, replacements) null } else { prepareLine(line, replacements) } } } private fun updateReplacementsMap( line: String, replacements: MutableMap<String, String> ) { val commandDefinition = line.substring(1, line.length - 2).trim() val spaceIndex = commandDefinition.indexOf(" ") val key = commandDefinition.substring(0, spaceIndex) require(key.toDoubleOrNull() == null) { "You can't redefine a number" } val value = commandDefinition.substring(spaceIndex + 1) replacements[key] = prepareLine(value, replacements) } private fun prepareLine(line: String, replacements: MutableMap<String, String>) = line.split(" ") .map { token -> if (replacements.containsKey(token)) { replacements[token] } else { token } } .joinToString(" ") private fun evaluateLine(line: String): List<Int> { return line.lowercase().split(" ") .fold(listOf()) { acc, c -> when { c.toIntOrNull() != null -> acc + c.toInt() c in OPS.keys -> OPS[c]!!.invoke(acc) else -> throw IllegalArgumentException("Incorrect input") } } } }
[ { "class_path": "3mtee__exercism-kotlin__6e3eb88/Forth$Companion.class", "javap": "Compiled from \"Forth.kt\"\npublic final class Forth$Companion {\n private Forth$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: re...
3mtee__exercism-kotlin__6e3eb88/complex-numbers/src/main/kotlin/ComplexNumbers.kt
import kotlin.math.* data class ComplexNumber(val real: Double = 0.0, val imag: Double = 0.0) { val abs = sqrt(real * real + imag * imag) operator fun plus(other: ComplexNumber): ComplexNumber { return ComplexNumber(this.real + other.real, this.imag + other.imag) } operator fun minus(other: ComplexNumber): ComplexNumber { return ComplexNumber(this.real - other.real, this.imag - other.imag) } operator fun times(other: ComplexNumber): ComplexNumber { val real = this.real * other.real - this.imag * other.imag val imag = this.real * other.imag + this.imag * other.real return ComplexNumber(real, imag) } operator fun div(other: ComplexNumber): ComplexNumber { val real = (this.real * other.real + this.imag * other.imag) / (other.real * other.real + other.imag * other.imag) val imag = (this.imag * other.real - this.real * other.imag) / (other.real * other.real + other.imag * other.imag) return ComplexNumber(real, imag) } fun conjugate(): ComplexNumber = ComplexNumber(this.real, -this.imag) } fun exponential(c: ComplexNumber): ComplexNumber = if (c.real == 0.0) { ComplexNumber(cos(c.imag), sin(c.imag)) } else { ComplexNumber(E.pow(c.real)) * exponential(ComplexNumber(imag = c.imag)) }
[ { "class_path": "3mtee__exercism-kotlin__6e3eb88/ComplexNumbersKt.class", "javap": "Compiled from \"ComplexNumbers.kt\"\npublic final class ComplexNumbersKt {\n public static final ComplexNumber exponential(ComplexNumber);\n Code:\n 0: aload_0\n 1: ldc #9 // String...
3mtee__exercism-kotlin__6e3eb88/wordy/src/main/kotlin/Wordy.kt
import kotlin.math.pow object Wordy { private const val PREFIX = "What is " private const val SUFFIX = "?" private val operations = mapOf<String, (a: Int, b: Int) -> Int>( "+" to { a, b -> a + b }, "-" to { a, b -> a - b }, "*" to { a, b -> a * b }, "/" to { a, b -> a / b }, "^" to { a, b -> a.toDouble().pow(b).toInt() }, ) fun answer(input: String): Int { return clearInput(input) .also { validateInput(it) } .split(" ") .asSequence() .also { if (it.count() == 1) return it.first().toInt() } .zipWithNext() .foldIndexed(0) { index, acc, piece -> when { index == 0 -> piece.first.toInt() index % 2 == 1 -> operations[piece.first]!!.invoke(acc, piece.second.toInt()) else -> acc } } } private fun validateInput(input: String) { if (!input.matches(Regex("^-?\\d+( [+\\-*/^] -?\\d+)*"))) { throw IllegalArgumentException("Wrong input") } } private fun clearInput(input: String): String = input .replace(PREFIX, "") .replace("plus", "+") .replace("minus", "-") .replace("multiplied by", "*") .replace("divided by", "/") .replace(Regex("raised to the (\\d+)th power"), "^ $1") .replace(SUFFIX, "") }
[ { "class_path": "3mtee__exercism-kotlin__6e3eb88/Wordy.class", "javap": "Compiled from \"Wordy.kt\"\npublic final class Wordy {\n public static final Wordy INSTANCE;\n\n private static final java.lang.String PREFIX;\n\n private static final java.lang.String SUFFIX;\n\n private static final java.util.Map...
everyevery__algorithm_code__e9a93f2/leetcode/990-SatisfiabilityOfEqualityEquations/Solution.kt
class Solution { class Some () { val parent = IntArray(26) {it} val rank = IntArray(26) {it} fun union(a: Int, b: Int): Unit { val pa = find(a) val pb = find(b) if (rank[a] > rank[b]) { parent[pb] = pa rank[pa] += rank[pb] } else { parent[pa] = pb rank[pb] += rank[pa] } } fun find (n: Int): Int { var p = parent[n] while (p != parent[p]) { parent[p] = parent[parent[p]] p = parent[p] } return p } } fun equationsPossible(equations: Array<String>): Boolean { val s = Some() for (eq in equations) { if (eq[1] == '=') { s.union(eq[0] - 'a', eq[3] - 'a') } } for (eq in equations) { if (eq[1] == '!') { val a = s.find(eq[0] - 'a') val b = s.find(eq[3] - 'a') if (a == b) { return false } } } return true } } //class Solution { // fun CharArray.replace(from: Char, to: Char) { // for (i in this.indices) { // if (this[i] == from) { // this[i] = to // } // } // } // // // fun equationsPossible(equations: Array<String>): Boolean { // val vars = "abcdefghijklmnopqrstuvwxyz".toCharArray() // val vals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray() // for (rel in equations) { // val v1 = rel[0].toInt() - 'a'.toInt(); // val v2 = rel[3].toInt() - 'a'.toInt(); // if (rel[1] == '=') { // if (vals[v1] != vals[v2]) { // vals.replace(vals[v1], vals[v2]) // } // } // } // for (rel in equations) { // val v1 = rel[0].toInt() - 'a'.toInt(); // val v2 = rel[3].toInt() - 'a'.toInt(); // if (rel[1] == '!') { // if (vals[v1] == vals[v2]) { // return false // } // } // } // return true // } //}
[ { "class_path": "everyevery__algorithm_code__e9a93f2/Solution.class", "javap": "Compiled from \"Solution.kt\"\npublic final class Solution {\n public Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n publi...
jamesrweb__advent-of-code__1180a7f/2022/05 - Supply Stacks/src/Main.kt
import java.io.File import java.util.* data class Crate constructor(val value: String) data class Stacks constructor(val list: HashMap<Int, MutableList<Crate>>) { fun viewResult(): String { return this.list.tops().joinToString("") } companion object Static { fun fromCrates(crates: String): Stacks { val stacksList = hashMapOf<Int, MutableList<Crate>>() val stackKeys = crates.lines().last().filterNot { it.isWhitespace() }.map { it.digitToInt() } crates.lines().dropLast(1).map { line -> line.chunked(4).toMutableList().insertWhile({ chunk -> chunk.size < stackKeys.size }, "").map { item -> if (item.trim() == "") { Optional.empty<Crate>() } else { val char = item.replace("[", "").replace("]", "").trim().take(1) val crate = Crate(char) Optional.of<Crate>(crate) } } }.forEach { it.forEachIndexed { index, optional -> if (optional.isPresent) { stacksList.getOrPut(index + 1) { mutableListOf() }.add(optional.get()) } } } return Stacks(stacksList) } } } fun executeMoves(moves: List<String>, stacks: Stacks, retainOrder: Boolean): Stacks { moves.forEach { line -> val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") val result = regex.find(line)?.destructured val count = result?.component1()?.toInt() val from = result?.component2()?.toInt() val to = result?.component3()?.toInt() if (count == null || from == null || to == null) { throw Exception("Something went wrong. count = $count, from = $from, to = $to") } val lastFrom = stacks.list.getOrDefault(from, mutableListOf()) val nextFrom = lastFrom.drop(count).toMutableList() val nextTo = stacks.list.getOrDefault(to, mutableListOf()) if (retainOrder) { nextTo.prependAll(lastFrom.take(count)) } else { nextTo.prependAll(lastFrom.take(count).reversed()) } stacks.list[to] = nextTo.toMutableList() stacks.list[from] = nextFrom } return stacks } fun main() { val path = System.getProperty("user.dir") val contents = File("${path}/src/input.txt").readText(Charsets.UTF_8) val (crates, instructions) = contents.split("\n\n") val moves = instructions.lines().filterNot { it.trim() == "" } val partOne = executeMoves(moves, Stacks.fromCrates(crates), false) val partTwo = executeMoves(moves, Stacks.fromCrates(crates), true) println("Part One: ${partOne.viewResult()}") println("Part Two: ${partTwo.viewResult()}") } private fun <T> MutableList<T>.prependAll(elements: List<T>) { addAll(0, elements) } private fun <K> HashMap<K, MutableList<Crate>>.tops(): List<String> { return this.values.flatMap { it.take(1) }.map { it.value } } private fun <E> MutableList<E>.insertWhile(transform: (MutableList<E>) -> Boolean, value: E): MutableList<E> { while (transform(this)) { this.add(this.size, value) } return this }
[ { "class_path": "jamesrweb__advent-of-code__1180a7f/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n public static final Stacks executeMoves(java.util.List<java.lang.String>, Stacks, boolean);\n Code:\n 0: aload_0\n 1: ldc #10 // Str...
19-2-SKKU-OSS__2019-2-OSS-L5__2b55676/Kotlin/EdmondsKarp/EdmondsKarp.kt
import java.util.Scanner import java.util.* //FloydWarshall fun main(args: Array<String>){ println("FloydWarshall"); var capacity = Array<IntArray>(51, {IntArray(51)}) var flow = Array<IntArray>(51, {IntArray(51)}) var visited = IntArray(51){0} val V = 5; //V : number of vertices //E : number of edges capacity[1][2] = 3; //There is pipe between 1 and 2 that has 2 unit of capcity. capacity[2][3] = 3; capacity[3][4] = 5; capacity[4][5] = 4; capacity[2][5] = 6; capacity[2][1] = 3; capacity[3][2] = 3; capacity[4][3] = 5; capacity[5][4] = 4; capacity[5][2] = 6; val start: Int = 1; val end: Int = 5; var q: Queue<Int> = LinkedList(); var maxflow: Int = 0; while(true){ for(i in 1..V){ visited[i] = 0 } q.add(start) while(!q.isEmpty()){ val front = q.poll(); for(i in 1..V){ if(front != i && capacity[front][i] != 0){ if(capacity[front][i] - flow[front][i] > 0 && visited[i] == 0){ q.add(i) visited[i] = front; if(i == end){ break; } } } } }//end of while(q empty) if(visited[end] == 0) break; //there is no possible way anymore //find minimum of capacity on the way var allowable_flow: Int = 99999999 var prev = end; while(true){ if(allowable_flow > (capacity[visited[prev]][prev] - flow[visited[prev]][prev])){ allowable_flow = capacity[visited[prev]][prev] - flow[visited[prev]][prev]; } prev = visited[prev] if(prev == start) break; } prev = end; //update the flow (current flowing amount) while(true){ flow[visited[prev]][prev] += allowable_flow flow[prev][visited[prev]] += allowable_flow prev = visited[prev] if(prev == start) break; } maxflow = maxflow + allowable_flow } println(maxflow) }
[ { "class_path": "19-2-SKKU-OSS__2019-2-OSS-L5__2b55676/EdmondsKarpKt.class", "javap": "Compiled from \"EdmondsKarp.kt\"\npublic final class EdmondsKarpKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n ...
mikegehard__AdventOfCode2017Kotlin__d582688/src/main/kotlin/Day2.kt
import kotlin.math.absoluteValue data class Spreadsheet(private val rows: List<Row>) { companion object { fun from(s: String): Spreadsheet = Spreadsheet( s.split("\n") .filter { it.isNotBlank() } .map { Row.from(it) } ) } fun checksum(rowCalculation: (Row) -> Int) = rows.map(rowCalculation).sum() } data class Row(val cells: List<Cell>) { companion object { fun from(s: String): Row = Row( s.split(" ") .map(Integer::parseInt) .sorted() .map { Cell(it) } ) } val difference: Int get() = (cells.first().value - cells.last().value).absoluteValue val division: Int get() = permutations() .first { (a, b) -> a.value.rem(b.value) == 0 } .run { first.value / second.value } } data class Cell(val value: Int) fun Row.permutations(): List<Pair<Cell, Cell>> = cells .associate { key -> key to cells.filter { it != key } } .map { (cell, others) -> others.map { Pair(cell, it) } } .flatten()
[ { "class_path": "mikegehard__AdventOfCode2017Kotlin__d582688/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class Day2Kt {\n public static final java.util.List<kotlin.Pair<Cell, Cell>> permutations(Row);\n Code:\n 0: aload_0\n 1: ldc #10 // String ...
andremion__SlidingPuzzle__8f8b9c4/shared/src/commonMain/kotlin/io/github/andremion/slidingpuzzle/domain/puzzle/PuzzleState.kt
package io.github.andremion.slidingpuzzle.domain.puzzle import kotlin.math.sqrt data class PuzzleState @Throws(IllegalArgumentException::class) constructor( val tiles: List<Int> ) { data class TilePosition( val row: Int, val column: Int ) val matrixSize = sqrt(tiles.size.toDouble()).toInt() init { require(sqrt(tiles.size.toDouble()) % 1.0 == 0.0) { "The tiles must represent a square matrix" } val check = List(tiles.size) { it } require(tiles.sorted() == check) { "The tiles must contain only a range from zero to the size - 1" } } override fun toString(): String { val maxTileLength = tiles.max().toString().length return "\n" + tiles.chunked(matrixSize) .joinToString(separator = "\n") { row -> row.joinToString(separator = "") { tile -> "[${tile.toString().padStart(length = maxTileLength)}]" } } } } /** * Get the position of the tile in the matrix. */ fun PuzzleState.getPosition(tile: Int): PuzzleState.TilePosition { val indexOf = tiles.indexOf(tile) indexOf != -1 || error("Tile #$tile not found") return PuzzleState.TilePosition( row = indexOf / matrixSize, column = indexOf % matrixSize ) } /** * Get the next possible states (successors) which can be reached from the current state. */ fun PuzzleState.getSuccessors(): List<PuzzleState> { val states = mutableListOf<PuzzleState>() val blankPosition = getPosition(0) var newPosition: PuzzleState.TilePosition if (blankPosition.row > 0) { // can we move up? newPosition = blankPosition.copy(row = blankPosition.row - 1) states.add(permuted(blankPosition, newPosition)) } if (blankPosition.row < matrixSize - 1) { // can we move down? newPosition = blankPosition.copy(row = blankPosition.row + 1) states.add(permuted(blankPosition, newPosition)) } if (blankPosition.column > 0) { // can we move left? newPosition = blankPosition.copy(column = blankPosition.column - 1) states.add(permuted(blankPosition, newPosition)) } if (blankPosition.column < matrixSize - 1) { // can we move right? newPosition = blankPosition.copy(column = blankPosition.column + 1) states.add(permuted(blankPosition, newPosition)) } return states } fun PuzzleState.permuted(a: PuzzleState.TilePosition, b: PuzzleState.TilePosition): PuzzleState { val indexA = indexOf(a) val indexB = indexOf(b) val permuted = buildList { addAll(tiles) val tmp = this[indexB] this[indexB] = this[indexA] this[indexA] = tmp } return PuzzleState(permuted) } fun PuzzleState.indexOf(position: PuzzleState.TilePosition): Int = position.row * matrixSize + position.column
[ { "class_path": "andremion__SlidingPuzzle__8f8b9c4/io/github/andremion/slidingpuzzle/domain/puzzle/PuzzleState$TilePosition.class", "javap": "Compiled from \"PuzzleState.kt\"\npublic final class io.github.andremion.slidingpuzzle.domain.puzzle.PuzzleState$TilePosition {\n private final int row;\n\n private...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day07/Day07a.kt
package com.marcdenning.adventofcode.day07 import java.io.File import java.util.* import java.util.regex.Pattern import java.util.stream.Collectors fun main(args: Array<String>) { var numberOfColors = 0 Scanner(File(args[0])).use { scanner -> numberOfColors += getAncestorsOfTargetColor(parseRules(scanner), args[1]).size } println("Number of colors: $numberOfColors") } /** * Extract map of color to rule pairings from a Scanner. Rules are a map of color to number of bags. */ fun parseRules(scanner: Scanner): Map<String, Map<String, Int>> = mapOf( * scanner.findAll("([\\w\\s]+)\\sbags\\scontain\\s([\\d\\s\\w\\,]+)\\.\\n?").map { Pair(it.group(1), parseRulesForColor(it.group(2))) }.collect(Collectors.toList()).toTypedArray() ) fun parseRulesForColor(rulesString: String): Map<String, Int> { if ("no other bags" == rulesString) { return emptyMap() } return mapOf( *rulesString.split(',') .map { val matcher = Pattern.compile("(\\d+)\\s([\\w\\s]+)\\sbags?").matcher(it.trim()) matcher.matches() Pair(matcher.group(2), matcher.group(1).toInt()) }.toTypedArray() ) } fun getAncestorsOfTargetColor(rules: Map<String, Map<String, Int>>, targetColor: String): Set<String> { // find colors that immediately contain the target color val immediateParentRules = rules.filter { entry -> entry.value.containsKey(targetColor) } // recurse through map for immediate parent colors to find their parents if (immediateParentRules.isEmpty()) { return emptySet() } return immediateParentRules.keys union immediateParentRules.map { getAncestorsOfTargetColor(rules, it.key) } .reduce { s1, s2 -> s1 union s2} }
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day07/Day07aKt.class", "javap": "Compiled from \"Day07a.kt\"\npublic final class com.marcdenning.adventofcode.day07.Day07aKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day23/Day23a.kt
package com.marcdenning.adventofcode.day23 import java.util.Collections.* fun main(args: Array<String>) { var cups = args[0].map { Integer.parseInt(it + "") } val moves = args[1].toInt() for (i in 1..moves) { cups = moveCups(cups) } println(getCupsStateString(cups)) } /** * Conduct moves for 1 round: * * 1. Pick up 3 cups that are immediately clockwise of the current cup. They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle. * 2. Pick destination cup: the cup with a label equal to the current cup's label minus one. If this would select one of the cups that was just picked up, the crab will keep subtracting one until it finds a cup that wasn't just picked up. If at any point in this process the value goes below the lowest value on any cup's label, it wraps around to the highest value on any cup's label instead. * 3. Places the cups just picked up so that they are immediately clockwise of the destination cup. They keep the same order as when they were picked up. * 4. Select a new current cup: the cup which is immediately clockwise of the current cup. * * @param cups current state of cups, current cup is always index 0 * @return new state of cups after a round */ fun moveCups(cups: List<Int>): List<Int> { val movedCups = mutableListOf(*cups.toTypedArray()) val removedCups = mutableListOf<Int>() for (i in 1..3) { removedCups.add(movedCups.removeAt(1)) } val destinationCupIndex = findDestinationCupIndex(movedCups) movedCups.addAll(destinationCupIndex + 1, removedCups) rotate(movedCups, -1) return movedCups } fun findDestinationCupIndex(cups: List<Int>): Int { val currentCup = cups[0] var destinationCup = currentCup - 1 if (cups.contains(destinationCup)) { return cups.indexOf(destinationCup) } do { destinationCup-- if (destinationCup < min(cups)) { destinationCup = max(cups) } } while (!cups.contains(destinationCup)) return cups.indexOf(destinationCup) } fun getCupsStateString(cups: List<Int>): String { val assembledCups = mutableListOf(*cups.toTypedArray()) val indexOf1 = assembledCups.indexOf(1) rotate(assembledCups, -indexOf1) assembledCups.remove(1) return assembledCups.joinToString(separator = "", transform = {i -> "" + i}) }
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day23/Day23aKt.class", "javap": "Compiled from \"Day23a.kt\"\npublic final class com.marcdenning.adventofcode.day23.Day23aKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day12/Day12b.kt
package com.marcdenning.adventofcode.day12 import java.io.File import kotlin.math.abs fun main(args: Array<String>) { var ship = Ship( Coordinates(0, 0, 90), Coordinates(10, 1, 0) ) File(args[0]).readLines().map { parseInstruction(it) } .forEach { ship = moveShipToWaypoint(ship, it) } println("Manhattan distance: ${abs(ship.shipCoordinates.x) + abs(ship.shipCoordinates.y)}") } fun moveShipToWaypoint(ship: Ship, instruction: Pair<Char, Int>): Ship { return when (instruction.first) { FORWARD -> { val xMovement = instruction.second * ship.waypointCoordinates.x val yMovement = instruction.second * ship.waypointCoordinates.y Ship(Coordinates( ship.shipCoordinates.x + xMovement, ship.shipCoordinates.y + yMovement, ship.shipCoordinates.orientation ), Coordinates( ship.waypointCoordinates.x, ship.waypointCoordinates.y, ship.waypointCoordinates.orientation )) } NORTH -> Ship( Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation), Coordinates(ship.waypointCoordinates.x, ship.waypointCoordinates.y + instruction.second, ship.waypointCoordinates.orientation) ) SOUTH -> Ship( Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation), Coordinates(ship.waypointCoordinates.x, ship.waypointCoordinates.y - instruction.second, ship.waypointCoordinates.orientation) ) EAST -> Ship( Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation), Coordinates(ship.waypointCoordinates.x + instruction.second, ship.waypointCoordinates.y, ship.waypointCoordinates.orientation) ) WEST -> Ship( Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation), Coordinates(ship.waypointCoordinates.x - instruction.second, ship.waypointCoordinates.y, ship.waypointCoordinates.orientation) ) LEFT -> when (instruction.second) { 90 -> rotateWaypointLeft(ship) 180 -> rotateWaypointLeft(rotateWaypointLeft(ship)) 270 -> rotateWaypointLeft(rotateWaypointLeft(rotateWaypointLeft(ship))) else -> throw Exception() } RIGHT -> when (instruction.second) { 90 -> rotateWaypointRight(ship) 180 -> rotateWaypointRight(rotateWaypointRight(ship)) 270 -> rotateWaypointRight(rotateWaypointRight(rotateWaypointRight(ship))) else -> throw Exception() } else -> throw Exception() } } fun rotateWaypointLeft(ship: Ship) = Ship( Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation), Coordinates(-ship.waypointCoordinates.y, ship.waypointCoordinates.x, ship.waypointCoordinates.orientation) ) fun rotateWaypointRight(ship: Ship) = Ship( Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation), Coordinates(ship.waypointCoordinates.y, -ship.waypointCoordinates.x, ship.waypointCoordinates.orientation) ) data class Ship( val shipCoordinates: Coordinates, val waypointCoordinates: Coordinates )
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day12/Day12bKt.class", "javap": "Compiled from \"Day12b.kt\"\npublic final class com.marcdenning.adventofcode.day12.Day12bKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day12/Day12a.kt
package com.marcdenning.adventofcode.day12 import java.io.File import java.util.regex.Pattern import kotlin.math.abs const val FORWARD = 'F' const val NORTH = 'N' const val SOUTH = 'S' const val EAST = 'E' const val WEST = 'W' const val RIGHT = 'R' const val LEFT = 'L' fun main(args: Array<String>) { var currentCoordinates = Coordinates(0, 0, 90) File(args[0]).readLines().map { parseInstruction(it) } .forEach { currentCoordinates = moveShipScalar(currentCoordinates, it) } println("Manhattan distance: ${abs(currentCoordinates.x) + abs(currentCoordinates.y)}") } fun parseInstruction(instruction: String): Pair<Char, Int> { val matcher = Pattern.compile("(\\w){1}(\\d+)").matcher(instruction) matcher.matches() return Pair(matcher.group(1)[0], matcher.group(2).toInt()) } fun moveShipScalar(startingCoordinates: Coordinates, instruction: Pair<Char, Int>): Coordinates { return when (instruction.first) { FORWARD -> { return when (startingCoordinates.orientation) { 0 -> Coordinates(startingCoordinates.x, startingCoordinates.y + instruction.second, startingCoordinates.orientation) 90 -> Coordinates(startingCoordinates.x + instruction.second, startingCoordinates.y, startingCoordinates.orientation) 180 -> Coordinates(startingCoordinates.x, startingCoordinates.y - instruction.second, startingCoordinates.orientation) 270 -> Coordinates(startingCoordinates.x - instruction.second, startingCoordinates.y, startingCoordinates.orientation) else -> throw Exception() } } NORTH -> Coordinates(startingCoordinates.x, startingCoordinates.y + instruction.second, startingCoordinates.orientation) SOUTH -> Coordinates(startingCoordinates.x, startingCoordinates.y - instruction.second, startingCoordinates.orientation) EAST -> Coordinates(startingCoordinates.x + instruction.second, startingCoordinates.y, startingCoordinates.orientation) WEST -> Coordinates(startingCoordinates.x - instruction.second, startingCoordinates.y, startingCoordinates.orientation) RIGHT -> Coordinates(startingCoordinates.x, startingCoordinates.y, (startingCoordinates.orientation + instruction.second) % 360) LEFT -> { var newOrientation = startingCoordinates.orientation - instruction.second if (newOrientation < 0) { newOrientation += 360 } Coordinates(startingCoordinates.x, startingCoordinates.y, newOrientation) } else -> throw Exception() } } data class Coordinates( val x: Long, val y: Long, val orientation: Int )
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day12/Day12aKt.class", "javap": "Compiled from \"Day12a.kt\"\npublic final class com.marcdenning.adventofcode.day12.Day12aKt {\n public static final char FORWARD;\n\n public static final char NORTH;\n\n public static ...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day05/Day05a.kt
package com.marcdenning.adventofcode.day05 import java.io.File import java.util.* import java.util.regex.MatchResult import java.util.stream.Stream private const val NUMBER_OF_ROWS = 128 private const val NUMBER_OF_COLUMNS = 8 fun main(args: Array<String>) { Scanner(File(args[0])).use { scanner -> val maxSeatId = scanner.findAll("[BF]{7}[LR]{3}") .map(::getSeatId) .max { o1, o2 -> o1 - o2 } .orElseThrow() println("Max seat ID: $maxSeatId") } } fun extractRow(seat: String) = seat.substring(0..6) fun extractColumn(seat: String) = seat.substring(7..9) fun determineRow(specifier: String, index: Int, lower: Int, upper: Int): Int { if (index == specifier.length - 1) { return if (specifier[index] == 'F') lower else upper } else if (specifier[index] == 'F') { return determineRow(specifier, index + 1, lower, lower + ((upper - lower) / 2)) } else { return determineRow(specifier, index + 1, upper - ((upper - lower) / 2), upper) } } fun determineColumn(specifier: String, index: Int, lower: Int, upper: Int): Int { if (index == specifier.length - 1) { return if (specifier[index] == 'L') lower else upper } else if (specifier[index] == 'L') { return determineColumn(specifier, index + 1, lower, lower + ((upper - lower) / 2)) } else { return determineColumn(specifier, index + 1, upper - ((upper - lower) / 2), upper) } } fun getSeatId(matchResult: MatchResult): Int { val rowId = extractRow(matchResult.group()) val columnId = extractColumn(matchResult.group()) return 8 * determineRow(rowId, 0, 0, NUMBER_OF_ROWS - 1) + determineColumn(columnId, 0, 0, NUMBER_OF_COLUMNS - 1) }
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day05/Day05aKt$main$1$maxSeatId$1.class", "javap": "Compiled from \"Day05a.kt\"\nfinal class com.marcdenning.adventofcode.day05.Day05aKt$main$1$maxSeatId$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kot...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day18/Day18b.kt
package com.marcdenning.adventofcode.day18 import java.io.File fun main(args: Array<String>) { val sum = File(args[0]).readLines().map { evaluateExpressionInverse(it) }.sum() println("Sum of all operations: $sum") } fun evaluateExpressionInverse(expression: String) = evaluateExpressionTree(buildTreeFromExpression(expression)) fun buildTreeFromExpression(expression: String): ExpressionNode { val expressionTree = ExpressionNode('+', ExpressionNode('0')) var currentNode = expressionTree for (char in expression) { if (char != ' ') { currentNode = currentNode.addChar(char) } } return expressionTree } fun evaluateExpressionTree(node: ExpressionNode): Long { if (node.left == null && node.right == null) { return ("" + node.char).toLong() } return when (node.char) { '+' -> evaluateExpressionTree(node.left!!) + evaluateExpressionTree(node.right!!) '*' -> evaluateExpressionTree(node.left!!) * evaluateExpressionTree(node.right!!) else -> throw Exception() } } data class ExpressionNode( var char: Char, var left: ExpressionNode? = null, var right: ExpressionNode? = null ) { fun addChar(newChar: Char): ExpressionNode { return when { char.isDigit() && (newChar == '+' || newChar == '*') -> { left = ExpressionNode(char) char = newChar this } (char == '+' || char == '*') && (newChar.isDigit() || newChar == '(') -> { right = ExpressionNode(newChar) right!! } char == '(' && newChar.isDigit() -> { left = ExpressionNode(newChar) this } char == '(' && (newChar == '+' || newChar == '*') -> { char = newChar this } newChar == ')' -> this else -> throw Exception() } } }
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day18/Day18bKt.class", "javap": "Compiled from \"Day18b.kt\"\npublic final class com.marcdenning.adventofcode.day18.Day18bKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day16/Day16a.kt
package com.marcdenning.adventofcode.day16 import java.io.File import java.util.regex.Pattern fun main(args: Array<String>) { val inputLines = File(args[0]).readLines() val separatorLineIndex = inputLines.indexOf("") val rules = inputLines.subList(0, separatorLineIndex).map { line -> parseRule(line) } println("Ticket scanning error rate: ${getTicketScanningErrorRate(rules, inputLines)}") } fun getTicketScanningErrorRate(rules: List<Rule>, inputLines: List<String>): Int { val nearbyTicketsLineIndex = inputLines.indexOf("nearby tickets:") + 1 return inputLines.subList(nearbyTicketsLineIndex, inputLines.size).flatMap { ticket -> ticket.split(',').map { value -> value.toInt() } }.filter { value -> rules.all { rule -> !(rule as Rule).isNumberValid(value) } }.sum() } fun parseRule(ruleString: String): Rule { val matcher = Pattern.compile("([\\w\\s]+):\\s(\\d+)\\-(\\d+)\\sor\\s(\\d+)\\-(\\d+)").matcher(ruleString) if (!matcher.matches()) { throw Exception() } return Rule( matcher.group(1), matcher.group(2).toInt()..matcher.group(3).toInt(), matcher.group(4).toInt()..matcher.group(5).toInt() ) } data class Rule( val fieldName: String, val range1: IntRange, val range2: IntRange ) { fun isNumberValid(int: Int): Boolean { return range1.contains(int) || range2.contains(int) } }
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day16/Day16aKt.class", "javap": "Compiled from \"Day16a.kt\"\npublic final class com.marcdenning.adventofcode.day16.Day16aKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day11/Day11b.kt
package com.marcdenning.adventofcode.day11 import java.io.File private const val FLOOR = '.' private const val EMPTY = 'L' private const val OCCUPIED = '#' fun main(args: Array<String>) { val floorPlanMatrix = File(args[0]).readLines().map { it.toCharArray() }.toTypedArray() println("Number of occupied seats: ${countSeats(findSteadyFloorPlanByVisibility(floorPlanMatrix), OCCUPIED)}") } fun fillSeatsByVisibility(floorPlanMatrix: Array<CharArray>): Array<CharArray> { val outputFloorPlanMatrix = floorPlanMatrix.map { it.copyOf() }.toTypedArray() for ((rowIndex, row) in floorPlanMatrix.withIndex()) { for ((columnIndex, seat) in row.withIndex()) { if (seat == EMPTY && countVisibleSeats(floorPlanMatrix, rowIndex, columnIndex, OCCUPIED) == 0) { outputFloorPlanMatrix[rowIndex][columnIndex] = OCCUPIED } } } return outputFloorPlanMatrix } fun emptySeatsByVisibility(floorPlanMatrix: Array<CharArray>): Array<CharArray> { val outputFloorPlanMatrix = floorPlanMatrix.map { it.copyOf() }.toTypedArray() for ((rowIndex, row) in floorPlanMatrix.withIndex()) { for ((columnIndex, seat) in row.withIndex()) { if (seat == OCCUPIED && countVisibleSeats(floorPlanMatrix, rowIndex, columnIndex, OCCUPIED) >= 5) { outputFloorPlanMatrix[rowIndex][columnIndex] = EMPTY } } } return outputFloorPlanMatrix } fun findSteadyFloorPlanByVisibility(floorPlanMatrix: Array<CharArray>): Array<CharArray> { var lastFloorPlan = Array(floorPlanMatrix.size) { CharArray(floorPlanMatrix[0].size) } var currentFloorPlan = floorPlanMatrix.copyOf() var isFillTurn = true while (!lastFloorPlan.contentDeepEquals(currentFloorPlan)) { lastFloorPlan = currentFloorPlan if (isFillTurn) { currentFloorPlan = fillSeatsByVisibility(currentFloorPlan) isFillTurn = false } else { currentFloorPlan = emptySeatsByVisibility(currentFloorPlan) isFillTurn = true } } return currentFloorPlan } fun countVisibleSeats(floorPlanMatrix: Array<CharArray>, rowIndex: Int, columnIndex: Int, targetSeat: Char): Int { val directions = listOf( Pair(-1, 0), Pair(-1, 1), Pair(0, 1), Pair(1, 1), Pair(1, 0), Pair(1, -1), Pair(0, -1), Pair(-1, -1) ) var countOfSeats = 0 for (directionPair in directions) { if (findVisibleSeatInDirection(floorPlanMatrix, rowIndex, columnIndex, directionPair.first, directionPair.second) == targetSeat) { countOfSeats++ } } return countOfSeats } fun findVisibleSeatInDirection(floorPlanMatrix: Array<CharArray>, rowIndex: Int, columnIndex: Int, rowIncrement: Int, columnIncrement: Int): Char { if (rowIndex + rowIncrement < 0 || rowIndex + rowIncrement >= floorPlanMatrix.size || columnIndex + columnIncrement < 0 || columnIndex + columnIncrement >= floorPlanMatrix[rowIndex].size) { return ' ' } val cell = floorPlanMatrix[rowIndex + rowIncrement][columnIndex + columnIncrement] if (cell == EMPTY || cell == OCCUPIED) { return cell } return findVisibleSeatInDirection(floorPlanMatrix, rowIndex + rowIncrement, columnIndex + columnIncrement, rowIncrement, columnIncrement) }
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day11/Day11bKt.class", "javap": "Compiled from \"Day11b.kt\"\npublic final class com.marcdenning.adventofcode.day11.Day11bKt {\n private static final char FLOOR;\n\n private static final char EMPTY;\n\n private static...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day11/Day11a.kt
package com.marcdenning.adventofcode.day11 import java.io.File import java.lang.Integer.max import java.lang.Integer.min private const val FLOOR = '.' private const val EMPTY = 'L' private const val OCCUPIED = '#' fun main(args: Array<String>) { val floorPlanMatrix = File(args[0]).readLines().map { it.toCharArray() }.toTypedArray() println("Number of occupied seats: ${countSeats(findSteadyFloorPlan(floorPlanMatrix), OCCUPIED)}") } fun fillSeats(floorPlanMatrix: Array<CharArray>): Array<CharArray> { val outputFloorPlanMatrix = floorPlanMatrix.map { it.copyOf() }.toTypedArray() for ((rowIndex, row) in floorPlanMatrix.withIndex()) { for ((columnIndex, seat) in row.withIndex()) { if (seat == EMPTY && countSeats(getAdjascentSeats(floorPlanMatrix, rowIndex, columnIndex), OCCUPIED) == 0) { outputFloorPlanMatrix[rowIndex][columnIndex] = OCCUPIED } } } return outputFloorPlanMatrix } fun emptySeats(floorPlanMatrix: Array<CharArray>): Array<CharArray> { val outputFloorPlanMatrix = floorPlanMatrix.map { it.copyOf() }.toTypedArray() for ((rowIndex, row) in floorPlanMatrix.withIndex()) { for ((columnIndex, seat) in row.withIndex()) { if (seat == OCCUPIED && countSeats(getAdjascentSeats(floorPlanMatrix, rowIndex, columnIndex), OCCUPIED) >= 4) { outputFloorPlanMatrix[rowIndex][columnIndex] = EMPTY } } } return outputFloorPlanMatrix } fun getAdjascentSeats(floorPlanMatrix: Array<CharArray>, rowIndex: Int, columnIndex: Int): Array<CharArray> { val startRow = max(0, rowIndex - 1) val startColumn = max(0, columnIndex - 1) val endRow = min(floorPlanMatrix.size - 1, rowIndex + 1) val endColumn = min(floorPlanMatrix[0].size - 1, columnIndex + 1) val adjascentSeatMatrix = floorPlanMatrix.copyOfRange(startRow, endRow + 1) .map { row -> row.copyOfRange(startColumn, endColumn + 1) } .toTypedArray() adjascentSeatMatrix[rowIndex - startRow][columnIndex - startColumn] = ' ' return adjascentSeatMatrix } fun findSteadyFloorPlan(floorPlanMatrix: Array<CharArray>): Array<CharArray> { var lastFloorPlan = Array(floorPlanMatrix.size) { CharArray(floorPlanMatrix[0].size) } var currentFloorPlan = floorPlanMatrix.copyOf() var isFillTurn = true while (!lastFloorPlan.contentDeepEquals(currentFloorPlan)) { lastFloorPlan = currentFloorPlan if (isFillTurn) { currentFloorPlan = fillSeats(currentFloorPlan) isFillTurn = false } else { currentFloorPlan = emptySeats(currentFloorPlan) isFillTurn = true } } return currentFloorPlan } fun countSeats(floorPlanMatrix: Array<CharArray>, seatType: Char): Int = floorPlanMatrix.map { row -> row.map { seat -> if (seat == seatType) 1 else 0 }.sum() }.sum()
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day11/Day11aKt.class", "javap": "Compiled from \"Day11a.kt\"\npublic final class com.marcdenning.adventofcode.day11.Day11aKt {\n private static final char FLOOR;\n\n private static final char EMPTY;\n\n private static...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day17/Day17a.kt
package com.marcdenning.adventofcode.day17 import java.io.File const val ACTIVE = '#' const val INACTIVE = '.' fun main(args: Array<String>) { val numberOfBootCycles = args[1].toInt() var pocketDimension = arrayOf(File(args[0]).readLines().map { it.toCharArray() }.toTypedArray()) for (i in 1..numberOfBootCycles) { pocketDimension = conductBootCycle(pocketDimension) } println( "Number of active cubes after $numberOfBootCycles boot cycles: ${ countCubesWithState( pocketDimension, ACTIVE ) }" ) } /** * Execute a single boot cycle. Each cube simultaneously changes state according to rules: * * 1. If a cube is active and exactly 2 or 3 of its neighbors are also active, the cube remains active. Otherwise, the cube becomes inactive. * 2. If a cube is inactive but exactly 3 of its neighbors are active, the cube becomes active. Otherwise, the cube remains inactive. * * @return new matrix of cube states, will grow continuously */ fun conductBootCycle(pocketDimension: Array<Array<CharArray>>): Array<Array<CharArray>> { val expandedPocketDimension = Array(pocketDimension.size + 2) { Array(pocketDimension[0].size + 2) { CharArray(pocketDimension[0][0].size + 2) { INACTIVE } } } // Copy existing dimension map into expanded map pocketDimension.forEachIndexed { planeIndex, plane -> plane.forEachIndexed { rowIndex, row -> row.forEachIndexed { charIndex, char -> expandedPocketDimension[planeIndex + 1][rowIndex + 1][charIndex + 1] = char } } } // Apply active/inactive rules expandedPocketDimension.forEachIndexed { planeIndex, plane -> plane.forEachIndexed { rowIndex, row -> row.forEachIndexed { charIndex, char -> val countOfActiveAdjacentCubes = countCubesWithState( getAdjacentCubes(expandedPocketDimension, Coordinates(charIndex, rowIndex, planeIndex)), ACTIVE ) if (char == ACTIVE && countOfActiveAdjacentCubes !in 2..3) { expandedPocketDimension[planeIndex][rowIndex][charIndex] = INACTIVE } else if (char == INACTIVE && countOfActiveAdjacentCubes == 3) { expandedPocketDimension[planeIndex][rowIndex][charIndex] = ACTIVE } } } } // Trim completely inactive edges return expandedPocketDimension } /** * Get all cubes adjacent to given coordinates. This is 26 cubes, with each coordinate value offset by 1. * * @return matrix of adjascent cubes, including target coordinates as space character */ fun getAdjacentCubes(pocketDimension: Array<Array<CharArray>>, coordinates: Coordinates): Array<Array<CharArray>> { val adjacentCubes = Array(3) { Array(3) { CharArray(3) { INACTIVE } } } for (z in -1..1) { for (y in -1..1) { for (x in -1..1) { if (z == 0 && y == 0 && x == 0) { adjacentCubes[1][1][1] = ' ' } else if (coordinates.z + z !in pocketDimension.indices || coordinates.y + y !in pocketDimension[coordinates.z + z].indices || coordinates.x + x !in pocketDimension[coordinates.z + z][coordinates.y + y].indices ) { adjacentCubes[z + 1][y + 1][x + 1] = INACTIVE } else { adjacentCubes[z + 1][y + 1][x + 1] = pocketDimension[coordinates.z + z][coordinates.y + y][coordinates.x + x] } } } } return adjacentCubes } fun countCubesWithState(pocketDimension: Array<Array<CharArray>>, cubeState: Char) = pocketDimension.map { plane -> plane.map { row -> row.map { cube -> if (cube == cubeState) 1 else 0 }.sum() }.sum() }.sum() data class Coordinates( val x: Int, val y: Int, val z: Int )
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day17/Day17aKt.class", "javap": "Compiled from \"Day17a.kt\"\npublic final class com.marcdenning.adventofcode.day17.Day17aKt {\n public static final char ACTIVE;\n\n public static final char INACTIVE;\n\n public stati...
marcdenning__advent-of-code-2020__b227acb/src/main/kotlin/com/marcdenning/adventofcode/day21/Day21a.kt
package com.marcdenning.adventofcode.day21 import java.io.File fun main(args: Array<String>) { val foods = File(args[0]).readLines().map { Food(getIngredients(it), getIdentifiedAllergens(it)) } val allIngredientsList = foods.flatMap { it.ingredients } val safeIngredients = getSafeIngredients(foods) val countOfInstancesOfSafeIngredients = allIngredientsList.count { safeIngredients.contains(it) } println("Number of instances of ingredients with no known allergens: $countOfInstancesOfSafeIngredients") } fun getSafeIngredients(foods: List<Food>): Set<String> { val allIngredientsList = foods.flatMap { it.ingredients } val allIngredientsSet = allIngredientsList.toSet() val allAllergensSet = foods.flatMap { it.allergens }.toSet() val ingredientsContainingAllergens = mutableSetOf<String>() for (allergen in allAllergensSet) { ingredientsContainingAllergens.addAll(getCommonIngredientsForAllergen(foods, allergen)) } return allIngredientsSet.subtract(ingredientsContainingAllergens) } fun getCommonIngredientsForAllergen(foods: List<Food>, allergen: String): List<String> { return foods .filter { it.allergens.contains(allergen) } .map { it.ingredients } .reduce { acc, list -> acc.intersect(list).toList() } } fun getIngredients(description: String): List<String> = description.split('(')[0].split(' ').filter { it.isNotBlank() }.toList() fun getIdentifiedAllergens(description: String) = description.split('(')[1].removePrefix("contains").split(',').map { it.removeSuffix(")").trim() }.toList() data class Food( val ingredients: List<String>, val allergens: List<String> )
[ { "class_path": "marcdenning__advent-of-code-2020__b227acb/com/marcdenning/adventofcode/day21/Day21aKt.class", "javap": "Compiled from \"Day21a.kt\"\npublic final class com.marcdenning.adventofcode.day21.Day21aKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1...
waterlink__inference__159f87b/common/inference.kt
package com.tddfellow.inference data class Relation(val name: String, val subject: String, val relative: String) { private fun matcherFor(getter: (Relation) -> String): (Relation) -> Boolean { val value = getter(this) return if (value == "?") { { getter(it) != "?" } } else { { getter(it) == value } } } val extractors: List<(Relation) -> String> = listOf( { it -> it.name }, { it -> it.subject }, { it -> it.relative } ) val matchers = extractors.map { matcherFor(it) } val freeExtractors = extractors.filter { it(this) == "?" } fun match(other: Relation): Boolean { return matchers.all { it(other) } } } val relations = mutableListOf<Relation>() fun _clear() { relations.clear() } fun query(relation: Relation): List<Relation> { if (!relations.contains(relation)) { relations.add(relation) } return relations.filter { relation.match(it) } } fun query(relationString: String): List<Relation> { return query(relationFromString(relationString)) } fun relationFromString(relationString: String): Relation { val found = relations .map { relationString.split(it.name) + listOf(it.name) } .find { it.count() == 3 } return if (found == null) { newRelationFromString(relationString) } else { Relation(found[2], found[0], found[1]) } } fun newRelationFromString(relationString: String): Relation { val components = relationString.split("?") if (components.count() != 3) { throw RuntimeException("New relation should be in format '? <relation name> ?'") } return Relation(components[1], "?", "?") } fun join( left: List<Relation>, leftValue: (Relation) -> String, right: List<Relation>, rightValue: (Relation) -> String): List<String> { return left.flatMap { relation -> right.map { rightValue(it) } .filter { it == leftValue(relation) } }.distinct() } fun join( left: String, leftValue: (Relation) -> String, right: String, rightValue: (Relation) -> String): List<String> { val leftRelation = relationFromString(left) val rightRelation = relationFromString(right) return join( query(leftRelation), leftValue, query(rightRelation), rightValue) } fun join(left: String, right: String): List<String> { val leftRelation = relationFromString(left) if (leftRelation.freeExtractors.count() == 0) { throw RuntimeException("join(left, right): left should have at least one '?' token") } val rightRelation = relationFromString(right) if (rightRelation.freeExtractors.count() == 0) { throw RuntimeException("join(left, right): right should have at least one '?' token") } return join( query(leftRelation), leftRelation.freeExtractors.first(), query(rightRelation), rightRelation.freeExtractors.first() ) }
[ { "class_path": "waterlink__inference__159f87b/com/tddfellow/inference/InferenceKt.class", "javap": "Compiled from \"inference.kt\"\npublic final class com.tddfellow.inference.InferenceKt {\n private static final java.util.List<com.tddfellow.inference.Relation> relations;\n\n public static final java.util...
PacktPublishing__Hands-On-Object-Oriented-Programming-with-Kotlin__1d36b57/src/main/kotlin/Chapter05/Map.kt
package Chapter5 fun createMap(){ val map: Map<Int,String> = mapOf( Pair(1,"One"), Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three"), 4 to "Four", 5 to "Five") for(pair in map){ println("${pair.key} ${pair.value}") } val setOfPairs = map.entries for ((key, value) in setOfPairs) { println("$key $value") } } fun mapFunctions(){ val map: Map<Int,String> = mapOf( Pair(1,"One"), Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three"), 4 to "Four", 5 to "Five") //Check if map is empty or not if( map.isNotEmpty()) { println("Map size is ${map.size}" ) val setofkeys = map.keys println("Keys $setofkeys") val setofvalues = map.values println("Values $setofvalues") var key = 1 if(map.containsKey(key)) { val value = map.get(key) println("key: $key value: $value") } } } fun mapDaysOfWeek01(day: Int): String? { var result : String? val daysOfWeek: Map<Int, String> = mapOf(1 to "Monday", 2 to "Tuesday", 3 to "Wednesday", 4 to "Thrusday", 5 to "Firday", 6 to "Saturday", 7 to "Sunday") result = daysOfWeek.get(day) return result } fun mapDaysOfWeek02(day: Int): String { var result : String val daysOfWeek: Map<Int, String> = mapOf(1 to "Monday", 2 to "Tuesday", 3 to "Wednesday", 4 to "Thrusday", 5 to "Firday", 6 to "Saturday", 7 to "Sunday") result = daysOfWeek.getOrDefault(day, "Invalid input") return result } fun mutableMapPutFunction(){ val map : MutableMap<Int,String> = mutableMapOf ( Pair(1,"One"), Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three")) map.put(4 ,"Four") var result = map.put(4 ,"FOUR") println(map) println("Put " + result) result = map.put(1 ,"One") println(map) println("Put " + result) } fun mutableMapRemove(){ val map : MutableMap<Int,String> = mutableMapOf ( Pair(1,"One"),Pair(2,"Two"), Pair(3,"Three"), Pair(4,"Four")) println(map) var result = map.remove(4) println("Remove " + result) var success = map.remove(2,"Two") println("Remove " + success) println(map) } fun clearAndPutAll(){ val map : MutableMap<Int,String> = mutableMapOf ( Pair(1,"One"), Pair(2,"Two"), Pair(3,"Three")) println(map) val miniMap = mapOf(Pair(4,"Four"),Pair(5,"Five")) map.putAll(miniMap) println(map) map.clear() println(map) map.putAll(miniMap) println(map) } fun main(args: Array<String>) { mutableMapPutFunction() }
[ { "class_path": "PacktPublishing__Hands-On-Object-Oriented-Programming-with-Kotlin__1d36b57/Chapter5/MapKt.class", "javap": "Compiled from \"Map.kt\"\npublic final class Chapter5.MapKt {\n public static final void createMap();\n Code:\n 0: bipush 6\n 2: anewarray #8 ...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day07/Solution.kt
package day07 import java.io.File import kotlin.system.measureTimeMillis data class DirectoryTree ( val name: String, val size: Int = 0, val children: List<DirectoryTree> = listOf() ) { val fullSize: Int by lazy { size + children.sumOf { it.fullSize } } fun getDirectorySizeList(): List<Int> = if (size == 0) { listOf(fullSize) + children.flatMap { it.getDirectorySizeList() } } else emptyList() } fun sumDirectoriesUnderSize(tree: DirectoryTree, maxSize: Int): Int = (tree.fullSize.takeIf { it <= maxSize } ?: 0) + tree.children.filter { it.size == 0 }.sumOf { sumDirectoriesUnderSize(it, maxSize) } fun findSmallerDirectoryToDelete(tree: DirectoryTree): Int { val availableSpace = 70000000 - tree.fullSize val neededSpace = 30000000 - availableSpace assert(neededSpace > 0) return tree.getDirectorySizeList().sorted().first { it >= neededSpace } } fun addToTreeAtNode(tree: DirectoryTree, levels: List<String>, size: Int, name: String): DirectoryTree { return if (levels.isEmpty()) { tree.copy(children = tree.children + DirectoryTree(name, size)) } else { val nextLevel = levels.first() val nextChild = tree.children.first { it.name == nextLevel } tree.copy(children = tree.children.filter{ it.name != nextLevel} + addToTreeAtNode(nextChild, levels.drop(1), size, name) ) } } fun parseFileAndBuildTree() = File("src/main/kotlin/day07/input.txt") .readLines() .fold(Pair(emptyList<String>(), DirectoryTree("/"))) { acc, it -> if ( it.startsWith("$")) { Regex("cd ([.a-z]+)").find(it) ?.groupValues ?.let { if (it[1] == "..") { Pair( acc.first.dropLast(1), acc.second ) } else { Pair( acc.first + it[1], acc.second ) } }?: acc } else { val (sizeType, fileName) = it.split(' ') Pair( acc.first, addToTreeAtNode( acc.second, acc.first, if (sizeType == "dir") 0 else sizeType.toInt(), fileName ) ) } }.second fun main() { val elapsed = measureTimeMillis { val tree = parseFileAndBuildTree() println("The sum of the directory which size is under 100000 is ${sumDirectoriesUnderSize(tree, 100000)}") println("The size of the smallest directory to delete is ${findSmallerDirectoryToDelete(tree)}") } println("The whole thing needed $elapsed to finish") }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day07/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day07.SolutionKt {\n public static final int sumDirectoriesUnderSize(day07.DirectoryTree, int);\n Code:\n 0: aload_0\n 1: ldc #9 ...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day09/Solution.kt
package day09 import java.io.File import kotlin.math.abs data class Position( val x: Int = 0, val y: Int = 0 ) { fun doAStep(direction: Direction): Position { return when (direction) { Direction.UP -> this.copy(y = y+1) Direction.DOWN -> this.copy(y = y-1) Direction.LEFT -> this.copy(x = x-1) Direction.RIGHT -> this.copy(x = x+1) } } fun follow(position: Position): Position = if ( abs(x - position.x) <= 1 && abs(y - position.y) <= 1) this else if ( y == position.y) this.copy(x = x + if (position.x > x) 1 else -1) else if ( x == position.x) this.copy(y = y + if (position.y > y) 1 else -1) else this.copy(x = x + if (position.x > x) 1 else -1, y = y + if (position.y > y) 1 else -1) } class Rope( length: Int = 0, nodes: List<Position> = emptyList() ) { private val nodes = nodes.ifEmpty { List(length) { Position() } } private fun updateRecursive(headPosition: Position, nodes: List<Position>): List<Position> { return if(nodes.isEmpty()) emptyList() else { val newHead = nodes.first().follow(headPosition) listOf(newHead) + updateRecursive(newHead, nodes.subList(1, nodes.size)) } } fun doAStep(direction: Direction): Rope { val newHead = nodes.first().doAStep(direction) return Rope( nodes = listOf(newHead) + updateRecursive(newHead, nodes.subList(1, nodes.size)) ) } fun getTailPosition() = nodes.last() } enum class Direction { UP, DOWN, LEFT, RIGHT; companion object { fun from(s: String): Direction { return when (s) { "U" -> UP "D" -> DOWN "L" -> LEFT "R" -> RIGHT else -> throw Exception() } } } } fun parseTailMovementAndCountPositions(size: Int) = File("src/main/kotlin/day09/input.txt") .readLines() .fold(Pair(Rope(size), setOf(Position()))) { acc, line -> val (d, amount) = line.split(" ") val direction = Direction.from(d) (0 until amount.toInt()).fold(acc) { innerAcc, _ -> val newRope = innerAcc.first.doAStep(direction) Pair( newRope, innerAcc.second + newRope.getTailPosition() ) } }.second.size fun main() { println("The number of positions the short rope visited at least once is: ${parseTailMovementAndCountPositions(2)}") println("The number of positions the long rope visited at least once is: ${parseTailMovementAndCountPositions(10)}") }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day09/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day09.SolutionKt {\n public static final int parseTailMovementAndCountPositions(int);\n Code:\n 0: new #8 // class java/io/File...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day12/Solution.kt
package day12 import java.io.File fun Char.distance(other: Char) = if (this == 'E') other - 'z' else if (this == 'S') other - 'a' else if (other == 'E') 'z' - this else if (other == 'S') 'a' - this else other - this data class DijkstraParams( val dist: MutableMap<Pair<Int, Int>, Distance> = mutableMapOf(), val prev: MutableMap<Pair<Int, Int>, Pair<Int, Int>?> = mutableMapOf(), val queue: MutableList<Pair<Int, Int>> = mutableListOf() ) data class Distance( val distance: Int = Int.MAX_VALUE ) { operator fun plus(cost: Int): Distance = if(distance == Int.MAX_VALUE) throw Exception("Cannot sum to infinity") else Distance(distance + cost) fun isLess(other: Distance) = distance < other.distance } data class Node( val height: Char, val links: Map<Pair<Int, Int>, Int> ) { fun distance(node: Node) = height.distance(node.height) } data class Graph( val nodes: Map<Pair<Int, Int>, Node> = emptyMap(), val start: Pair<Int, Int> = Pair(0, 0), val end: Pair<Int, Int> = Pair(0, 0) ) { fun addNode(x: Int, y: Int, value: Char, vararg links: Triple<Int, Int, Char>?): Graph { val newNode = Node( when (value) { 'S' -> 'a' 'E' -> 'z' else -> value}, links .filterNotNull() .fold(emptyMap()) { acc, it -> acc + (Pair(it.first, it.second) to 1)} ) return when(value) { 'S' -> this.copy(nodes = nodes + (Pair(x,y) to newNode), start = Pair(x, y)) 'E' -> this.copy(nodes = nodes + (Pair(x,y) to newNode), end = Pair(x, y)) else -> this.copy(nodes = nodes + (Pair(x,y) to newNode)) } } private tailrec fun stepsToStart(end: Pair<Int, Int>, nodes: Map<Pair<Int, Int>, Pair<Int, Int>?>, acc: Int = 0): Int = if(nodes[end] != null) stepsToStart(nodes[end]!!, nodes, acc+1) else acc fun findShortestPathWithDijkstra(): Int { val params = DijkstraParams() nodes.keys.onEach { params.dist[it] = Distance(if (it == start) 0 else Int.MAX_VALUE) params.prev[it] = null params.queue.add(it) } while(params.queue.contains(end)) { val minVertex = params.dist.filter { params.queue.contains(it.key) }.minBy { it.value.distance }.key nodes[minVertex]!!.links.filter { nodes[minVertex]!!.distance(nodes[it.key]!!) <= 1 }.entries.onEach { if (params.queue.contains(it.key)) { val newDist = params.dist[minVertex]!! + it.value if (newDist.isLess(params.dist[it.key]!!)) { params.dist[it.key] = newDist params.prev[it.key] = minVertex } } } params.queue.remove(minVertex) } return stepsToStart(end, params.prev) } fun findShortestPathWithBFS(): Int { val queue = mutableListOf(Pair(end,0)) val explored = mutableSetOf(end) var current = queue.first() while(queue.isNotEmpty() && nodes[queue.first().first]!!.height != 'a') { current = queue.first() val validLinks = nodes[current.first]!!.links.keys .filter { !explored.contains(it) && nodes[it]!!.distance(nodes[current.first]!!) <= 1 } queue.addAll(validLinks.map { Pair(it, current.second+1) }) explored.addAll(validLinks) queue.removeAt(0) } return current.second } } fun parseInputFile() = File("src/main/kotlin/day12/input.txt") .readLines() .fold(emptyList<List<Char>>()) { acc, it -> acc + listOf(it.toCharArray().toList()) } fun getGraph() = parseInputFile() .let { rows -> (rows.indices).fold(Graph()) { acc, r -> (rows[r].indices).fold(acc) { graph, c -> graph.addNode( r, c, rows[r][c], if (r == 0) null else Triple(r-1, c, rows[r-1][c]), if (c == 0) null else Triple(r, c-1, rows[r][c-1]), if (r == rows.size-1) null else Triple(r+1, c, rows[r+1][c]), if (c == rows[r].size-1) null else Triple(r, c+1, rows[r][c+1]) ) } } } fun main() { println("The shortest path is made up of ${getGraph().findShortestPathWithDijkstra()} steps") println("The shortest hiking path is made up of ${getGraph().findShortestPathWithBFS()} steps") }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day12/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day12.SolutionKt {\n public static final int distance(char, char);\n Code:\n 0: iload_0\n 1: bipush 69\n 3: if_icmpne 13\n 6:...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day15/Solution.kt
package day15 import java.io.File import kotlin.math.abs import kotlin.system.measureTimeMillis fun manhattanDistance(x1: Long, y1: Long, x2: Long, y2: Long) = abs(x1-x2) + abs(y1-y2) class LineScan( initStart: Long, initEnd: Long ) { val start = minOf(initStart, initEnd) val end = maxOf(initStart, initEnd) fun union(other: LineScan): List<LineScan> = if(other.start-1 > end || other.end+1 < start) listOf(this, other) else listOf(LineScan( minOf(other.start, start), maxOf(other.end, end))) fun union(others: List<LineScan>): List<LineScan> = others.fold(Pair(this, emptyList<LineScan>())) { acc, it -> val united = acc.first.union(it) Pair( united.first(), acc.second + united.drop(1) ) }.let {listOf(it.first) + it.second } } class SensorScan( val x: Long, val y: Long, private val beaconX: Long, private val beaconY: Long ) { val radius = manhattanDistance(x, y, beaconX, beaconY) fun contains(newX: Long, newY: Long) = manhattanDistance(x, y, newX, newY) <= radius fun hasBeacon(newX: Long, newY: Long) = newX == beaconX && newY == beaconY fun lineScanAtHeight(height: Long) = LineScan( x - (radius - abs(y-height)), x + (radius - abs(y-height)) ) } fun List<SensorScan>.findXBoundaries() = this.fold(Pair(this.first(), this.first())) { acc, scan -> Pair( scan.takeIf { it.x < acc.first.x } ?: acc.first, scan.takeIf { it.x > acc.second.x } ?: acc.second ) }.let { Pair(it.first.x - it.first.radius, it.second.x + it.second.radius) } fun List<SensorScan>.uniqueExcludedPosition(y: Long) = this.filter { abs(y-it.y) <= it.radius } .fold(emptyList<LineScan>()) { acc, it -> it.lineScanAtHeight(y).union(acc) } fun parseInputFile() = File("src/main/kotlin/day15/input.txt") .readLines() .fold(emptyList<SensorScan>()) { acc, it -> Regex("Sensor at x=(-?[0-9]+), y=(-?[0-9]+): closest beacon is at x=(-?[0-9]+), y=(-?[0-9]+)") .find(it)!! .let{ acc + SensorScan( it.groupValues[1].toLong(), it.groupValues[2].toLong(), it.groupValues[3].toLong(), it.groupValues[4].toLong() ) } } fun findBeaconFreePoints(row: Long) = parseInputFile() .let { scans -> val boundaries = scans.findXBoundaries() (boundaries.first .. boundaries.second).fold(0) { acc, it -> if ( scans.any{ scan -> scan.contains(it, row) } && scans.all { scan -> !scan.hasBeacon(it, row) }) acc + 1 else acc } } fun findBeacon(range: Long) = parseInputFile() .let {scans -> (0L .. range).fold(emptyList<Long>()) { acc, y -> val lineScan = scans.uniqueExcludedPosition(y) if(lineScan.size == 1 && lineScan.first().start <= 0L && lineScan.first().end >= range ) acc else if(lineScan.size == 1 && lineScan.first().start > 0L) acc + listOf(y + lineScan.first().start*4000000L) else if(lineScan.size == 1 && lineScan.first().end < range) acc + listOf(y + lineScan.first().end*4000000L) else acc + listOf(y + (lineScan.minBy { it.end }.end+1)*4000000L) } } fun main() { measureTimeMillis { println("In the row where y=2000000, the positions cannot contain a beacon are: ${findBeaconFreePoints(10)}") val beacons = findBeacon(4000000L) if (beacons.size > 1) println("I did not find any beacon") else println("The beacon tuning frequency is: ${beacons.first()}") }.let { println("The whole process took: $it milliseconds") } }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day15/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day15.SolutionKt {\n public static final long manhattanDistance(long, long, long, long);\n Code:\n 0: lload_0\n 1: lload 4\n 3: lsub\n...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day13/Solution.kt
package day13 import java.io.File abstract class Node : Comparable<Node> class IntNode( val value: Int ): Node() { override fun compareTo(other: Node): Int = if (other is IntNode) this.value.compareTo(other.value) else ListNode(listOf(this)).compareTo(other) } class ListNode( val children: List<Node> ): Node() { override fun compareTo(other: Node): Int = if(other is IntNode) this.compareTo(ListNode(listOf(other))) else { if (this.children.isEmpty() && (other as ListNode).children.isEmpty()) 0 else if (this.children.isEmpty()) -1 else if ((other as ListNode).children.isEmpty()) 1 else if (this.children.first().compareTo(other.children.first()) == 0) ListNode(this.children.drop(1)).compareTo(ListNode(other.children.drop(1))) else this.children.first().compareTo(other.children.first()) } } //fun compareTrees(tree1: Node, tree2: Node): Int = // if(tree1 is IntNode && tree2 is IntNode) tree1.value.compareTo(tree2.value) // else if (tree1 is ListNode && tree2 is IntNode) compareTrees(tree1, ListNode(listOf(tree2))) // else if (tree1 is IntNode && tree2 is ListNode) compareTrees(ListNode(listOf(tree1)), tree2) // else { // val l1 = tree1 as ListNode // val l2 = tree2 as ListNode // if (l1.children.isEmpty() && l2.children.isEmpty()) 0 // else if (l1.children.isEmpty()) -1 // else if (l2.children.isEmpty()) 1 // else if (compareTrees(l1.children.first(), l2.children.first()) == 0) // compareTrees(ListNode(l1.children.drop(1)), ListNode(l2.children.drop(1))) // else compareTrees(l1.children.first(), l2.children.first()) // } tailrec fun parseListContent(rawContent: String, innerLists: List<Char> = emptyList(), parsed: List<String> = emptyList()): List<String> = if (rawContent.isEmpty()) parsed else if(rawContent.startsWith("[")) parseListContent( rawContent.substring(1, rawContent.length), innerLists + '[', if (innerLists.isEmpty()) parsed + listOf("[") else parsed.dropLast(1) + listOf(parsed.last() + '[') ) else if(innerLists.isEmpty() && rawContent.startsWith(",")) parseListContent( rawContent.substring(1, rawContent.length), innerLists, parsed) else if(innerLists.isEmpty() && rawContent.matches(Regex("^[0-9]+.*"))) parseListContent( rawContent.replace(Regex("^[0-9]+"), ""), innerLists, parsed + listOf(Regex("^[0-9]+").find(rawContent)!!.value)) else if(rawContent.startsWith("]")) parseListContent( rawContent.substring(1, rawContent.length), innerLists.dropLast(1), parsed.dropLast(1) + listOf(parsed.last() + "]")) else parseListContent( rawContent.substring(1, rawContent.length), innerLists, parsed.dropLast(1) + listOf(parsed.last() + rawContent[0])) fun parseTree(rawString: String): Node = if(rawString.first() == '[' && rawString.last() == ']') { val rawParams = parseListContent(rawString.substring(1, rawString.length-1)) val nodes = rawParams.map { parseTree(it) } ListNode(nodes) } else if (rawString.matches(Regex("^[0-9]+$"))) IntNode(rawString.toInt()) else throw Exception("Invalid state") fun parseInputFile() = File("src/main/kotlin/day13/input.txt") .readText() .split(Regex("\r?\n")) .filter{ it.isNotBlank() } .fold(emptyList<Node>()) { acc, it -> acc + parseTree(it) } fun findSumOfIndicesInRightOrder() = parseInputFile() .chunked(2) .foldIndexed(0) { index, acc, it -> if(it[0] < it[1]) acc + index + 1 else acc } fun findDecoderKey() = parseInputFile().let{ val dividerStart = ListNode(listOf(ListNode(listOf(IntNode(2))))) val dividerEnd = ListNode(listOf(ListNode(listOf(IntNode(6))))) val sortedList = (it + listOf(dividerStart, dividerEnd)).sorted() sortedList.foldIndexed(Pair(0, 0)) { index, acc, node -> Pair( index.takeIf { node.compareTo(dividerStart) == 0 } ?: acc.first, index.takeIf { node.compareTo(dividerEnd) == 0 } ?: acc.second ) }.let { p -> (p.first+1) * (p.second+1) } } fun main() { println("The sum of the indices of the ordered pairs is ${findSumOfIndicesInRightOrder()}") println("The decoder key for the distress signal is ${findDecoderKey()}") }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day13/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day13.SolutionKt {\n public static final java.util.List<java.lang.String> parseListContent(java.lang.String, java.util.List<java.lang.Character>, java.util.List<ja...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day03/Solution.kt
package day03 import java.io.File fun getItemsPriorities() = ('a'..'z').foldIndexed(mapOf<Char, Int>()) { index, acc, c -> acc + (c to index+1) } + ('A' .. 'Z').foldIndexed(mapOf()) { index, acc, c -> acc + (c to index + 27) } fun getItemsFromFile() = File("src/main/kotlin/day03/input.txt") .readLines() .fold(listOf<Pair<List<Char>, List<Char>>>()) { acc, line -> acc + Pair( line.subSequence(0, line.length/2).toList(), line.subSequence(line.length/2, line.length).toList() ) } fun findCommonItemAndSumPriorities() = getItemsFromFile() .fold(0) { acc, items -> (items.first.toSet().intersect(items.second.toSet()) .firstOrNull() ?.let { getItemsPriorities()[it] } ?: 0) + acc } fun findBadgesAndSumPriorities() = getItemsFromFile() .chunked(3) .fold(0) { acc, group -> (group.fold(emptySet<Char>()) { intersected, backpack -> intersected.ifEmpty { backpack.first.toSet() + backpack.second.toSet() }.intersect( backpack.first.toSet() + backpack.second.toSet() ) }.firstOrNull() ?.let { getItemsPriorities()[it] } ?: 0) + acc } fun main() { println("The sum of the priorities of the common items in the compartments is: ${findCommonItemAndSumPriorities()}") println("The sum of the priorities of the group badges is: ${findBadgesAndSumPriorities()}") }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day03/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day03.SolutionKt {\n public static final java.util.Map<java.lang.Character, java.lang.Integer> getItemsPriorities();\n Code:\n 0: new #10 ...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day02/Solution.kt
package day02 import java.io.File import java.lang.Exception enum class MoveTypes { ROCK, PAPER, SCISSORS } fun getWinningMove(move: Move) = when(move.type) { MoveTypes.ROCK -> Move("B") MoveTypes.PAPER -> Move("C") MoveTypes.SCISSORS -> Move("A") } fun getLosingMove(move: Move) = when(move.type) { MoveTypes.ROCK -> Move("C") MoveTypes.PAPER -> Move("A") MoveTypes.SCISSORS -> Move("B") } class Move( code: String ): Comparable<Move> { val type = when(code) { "A" -> MoveTypes.ROCK "B" -> MoveTypes.PAPER "C" -> MoveTypes.SCISSORS "X" -> MoveTypes.ROCK "Y" -> MoveTypes.PAPER "Z" -> MoveTypes.SCISSORS else -> throw Exception() } override fun compareTo(other: Move): Int { if(type == other.type) return 0 return when(type) { MoveTypes.ROCK -> { if(other.type == MoveTypes.SCISSORS) return 1 else return -1 } MoveTypes.PAPER -> { if(other.type == MoveTypes.ROCK) return 1 else return -1 } MoveTypes.SCISSORS -> { if(other.type == MoveTypes.PAPER) return 1 else return -1 } } } fun value(): Int = when(type) { MoveTypes.ROCK -> 1 MoveTypes.PAPER -> 2 MoveTypes.SCISSORS -> 3 } } class Match( private val yourMove: Move, private val otherMove: Move ) { fun score(): Int { return if (yourMove < otherMove) yourMove.value() else if (yourMove > otherMove) 6 + yourMove.value() else 3 + yourMove.value() } } fun getListOfMatchesFromFile() = File("src/main/kotlin/day022/input.txt") .readLines() .fold(listOf<Pair<String, String>>()) { moves, it -> val (opponentMove, yourMove) = it.split(" ") moves + Pair(opponentMove, yourMove) } fun interpretPairsAsMatches() = getListOfMatchesFromFile() .map { Match( Move(it.second), Move(it.first) ) } fun interpretPairsAsResults() = getListOfMatchesFromFile() .map { when(it.second) { "X" -> Match(getLosingMove(Move(it.first)), Move(it.first)) "Y" -> Match(Move(it.first), Move(it.first)) "Z" -> Match(getWinningMove(Move(it.first)), Move(it.first)) else -> throw Exception() } } fun getTotalScore() = interpretPairsAsMatches().sumOf { it.score() } fun getTotalScoreWithOutcome() = interpretPairsAsResults().sumOf { it.score() } fun main() { println("The total score if the second row is the move is: ${getTotalScore()}") println("The total score if the second row is the outcome is: ${getTotalScoreWithOutcome()}") }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day02/SolutionKt$WhenMappings.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day02.SolutionKt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 ...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day05/Solution.kt
package day05 import java.io.File import java.util.* data class Move( val qty: Int, val source: String, val dest: String ) fun parseStack(rawInput: List<String>): Map<String, Stack<Char>> = (1 .. 9).fold(emptyMap()) { acc, it -> acc + (it.toString() to rawInput .last() .indexOf(it.toString()) .let { index -> rawInput .reversed() .subList(1, rawInput.size) .fold(Stack<Char>()) { stack, line -> if (line.length > index && line[index] != ' ') stack.push(line[index]) stack } }) } fun parseCommands(rawCommands: List<String>) = rawCommands.mapNotNull { line -> Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)") .find(line) ?.groups ?.toList() ?.let { Move( it[1]!!.value.toInt(), it[2]!!.value, it[3]!!.value ) } } fun parseInputFile() = File("src/main/kotlin/day05/input.txt") .readLines() .fold(Pair<List<String>, List<String>>(emptyList(), emptyList())) { acc, line -> if (line.startsWith("move")) Pair(acc.first, acc.second + line) else if (line.isEmpty()) acc else Pair(acc.first + line, acc.second) }.let { Pair( parseStack(it.first), parseCommands(it.second) ) } fun findFinalConfigurationMovingOneCrateAtTime() = parseInputFile() .let { input -> input.second.forEach {move -> repeat((1 .. move.qty).count()) { if (input.first[move.source]!!.isNotEmpty()) input.first[move.dest]!!.push(input.first[move.source]!!.pop()) } } (1..9).fold("") { acc, it -> acc + input.first[it.toString()]!!.peek() } } fun findFinalConfigurationMovingMultipleCratesAtTime() = parseInputFile() .let { input -> input.second.forEach { move -> (1 .. move.qty).fold(emptyList<Char>()) { acc, _ -> if (input.first[move.source]!!.isNotEmpty()) acc + input.first[move.source]!!.pop() else acc }.reversed().forEach { input.first[move.dest]!!.push(it) } } (1..9).fold("") { acc, it -> acc + input.first[it.toString()]!!.peek() } } fun main() { println("The top crates at the end using the CrateMover 9000 are: ${findFinalConfigurationMovingOneCrateAtTime()}") println("The top crates at the end using the CrateMover 9001 are: ${findFinalConfigurationMovingMultipleCratesAtTime()}") }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day05/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day05.SolutionKt {\n public static final java.util.Map<java.lang.String, java.util.Stack<java.lang.Character>> parseStack(java.util.List<java.lang.String>);\n C...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day11/SolutionPart2.kt
package day11 import java.io.File import java.lang.Exception class IntModule( initial: Int = 0, oldModuleMap: Map<Int, Int>? = null ) { private val moduleMap = oldModuleMap ?: listOf(2,3,5,7,11,13,17,19,23).fold(emptyMap()) { acc, it -> acc + (it to initial%it)} operator fun plus(increment: Int): IntModule = moduleMap.keys.fold(emptyMap<Int, Int>()) { acc, it -> acc + (it to (moduleMap[it]!! + increment)%it) }.let { IntModule(oldModuleMap = it) } operator fun times(increment: Int): IntModule = moduleMap.keys.fold(emptyMap<Int, Int>()) { acc, it -> acc + (it to (moduleMap[it]!! * increment)%it) }.let { IntModule(oldModuleMap = it) } fun squared(): IntModule = moduleMap.keys.fold(emptyMap<Int, Int>()) { acc, it -> acc + (it to (moduleMap[it]!! * moduleMap[it]!!)%it) }.let { IntModule(oldModuleMap = it) } fun isDivisibleBy(other: Int): Boolean = moduleMap[other] == 0 } data class MonkeyModule( val id: Int, val items: List<IntModule>, val operation: (IntModule) -> IntModule, val nextMonkey: (IntModule) -> Int, val monkeyActivity: Long = 0 ) { fun doATurn(monkeys: List<MonkeyModule>, verbose: Boolean = false): List<MonkeyModule> { if (items.isEmpty()) return monkeys val updatedMonkeys = items.fold(monkeys) { acc, item -> if (verbose) println("Monkey $id inspects an item with a worry level of $item.") val newLevel = operation(item) if (verbose) println("\tWorry level is now $newLevel.") val receiverMonkeyId = nextMonkey(newLevel) if (verbose) println("\tItem with worry level $newLevel is thrown to monkey $receiverMonkeyId.") val receiverMonkey = acc.first { it.id == receiverMonkeyId } acc.filter { it.id != receiverMonkeyId } + receiverMonkey.copy( items = receiverMonkey.items + newLevel ) } return updatedMonkeys.filter { it.id != id } + this.copy(items = emptyList(), monkeyActivity = monkeyActivity + items.size) } } fun parseNextMonkeyWithModule(input: String): (IntModule) -> Int { val divisor = Regex("Test: divisible by ([0-9]+)").find(input)!!.groupValues[1].toInt() val ifTrue = Regex("If true: throw to monkey ([0-9]+)").find(input)!!.groupValues[1].toInt() val ifFalse = Regex("If false: throw to monkey ([0-9]+)").find(input)!!.groupValues[1].toInt() return { it -> if (it.isDivisibleBy(divisor)) ifTrue else ifFalse} } fun parseOperationWithModule(rawOperation: String): (IntModule) -> IntModule { Regex("new = ([0-9a-z]+) ([*+-]) ([0-9a-z]+)") .find(rawOperation)!! .groupValues .let { groups -> val first = groups[1] val op = groups[2] val second = groups[3] return if(first == "old" && second == "old") { when(op) { "+" -> { it -> it * 2 } "*" -> { it -> it.squared() } else -> throw Exception("Operation not supported") } } else { when(op) { "+" -> { it -> it + second.toInt() } "*" -> { it -> it * second.toInt() } else -> throw Exception("Operation not supported") } } } } fun parseInputFileWithModule() = File("src/main/kotlin/day11/input.txt") .readText() .split(Regex("\r?\n\r?\n")) .fold(emptyList<MonkeyModule>()) { acc, rawMonkey -> val monkeyId = Regex("Monkey ([0-9]+)").find(rawMonkey)!!.groupValues[1].toInt() val items = Regex("[0-9]+").findAll( Regex("Starting items: ([0-9]+,? ?)+").find(rawMonkey)!!.value ).toList().map { IntModule(it.value.toInt()) } val operation = parseOperationWithModule( Regex("Operation: new = [a-z0-9]+ [*+-] [a-z0-9]+").find(rawMonkey)!!.value ) val nextMonkey = parseNextMonkeyWithModule(rawMonkey) acc + MonkeyModule( monkeyId, items, operation, nextMonkey ) } fun findMonkeyBusinessAfterNthRound(rounds: Int): Long { val monkeys = parseInputFileWithModule() val ids = (monkeys.indices) val finalMonkeys = (0 until rounds).fold(monkeys) { m, _ -> ids.fold(m) { acc, id -> val monkey = acc.first { it.id == id } monkey.doATurn(acc) } } val monkeyActivity = finalMonkeys.map { it.monkeyActivity }.sortedDescending() return monkeyActivity[0] * monkeyActivity[1] } fun main() { println("The level of monkey business after 10000 rounds is ${findMonkeyBusinessAfterNthRound(10000)}") }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day11/SolutionPart2Kt.class", "javap": "Compiled from \"SolutionPart2.kt\"\npublic final class day11.SolutionPart2Kt {\n public static final kotlin.jvm.functions.Function1<day11.IntModule, java.lang.Integer> parseNextMonkeyWithModule(java.lang.Stri...