kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day11/Day11.kt | package day11
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day11/Day11.txt")
val answer1 = part1(data.toMutableList())
val answer2 = part2(data.toMutableList())
println("🎄 Day 11 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private fun parse(path: String): List<Int> =
File(path)
.readLines()
.flatMap { it.map(Char::digitToInt) }
private fun adjacentNodes(x: Int, y: Int): List<Pair<Int, Int>> =
listOfNotNull(
if (x - 1 >= 0 && y - 1 >= 0) x - 1 to y - 1 else null,
if ( y - 1 >= 0) x to y - 1 else null,
if (x + 1 < 10 && y - 1 >= 0) x + 1 to y - 1 else null,
if (x - 1 >= 0 ) x - 1 to y else null,
if (x + 1 < 10 ) x + 1 to y else null,
if (x - 1 >= 0 && y + 1 < 10) x - 1 to y + 1 else null,
if ( y + 1 < 10) x to y + 1 else null,
if (x + 1 < 10 && y + 1 < 10) x + 1 to y + 1 else null,
)
private fun step(energy: MutableList<Int>): Int {
var flashCount = 0
val flashQueue = ArrayDeque<Pair<Int, Int>>(100)
for (y in 0 until 10) {
for (x in 0 until 10) {
val index = y * 10 + x
if (++energy[index] > 9) {
flashQueue.addLast(x to y)
energy[index] = 0
}
}
}
while (flashQueue.isNotEmpty()) {
val (x, y) = flashQueue.removeLast()
for ((nx, ny) in adjacentNodes(x, y)) {
val index = ny * 10 + nx
if (energy[index] != 0 && ++energy[index] > 9) {
flashQueue.addLast(nx to ny)
energy[index] = 0
}
}
++flashCount
}
return flashCount
}
private fun part1(energy: MutableList<Int>) =
(0 until 100)
.sumOf { step(energy) }
private fun part2(energy: MutableList<Int>) =
generateSequence(1) { it + 1 }
.first { step(energy) == 100 }
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day11/Day11Kt.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class day11.Day11Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day11/Day11.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day10/Day10.kt | package day10
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day10/Day10.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 10 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private fun parse(path: String) =
File(path).readLines()
private fun part1(lines: List<String>): Long {
var sum = 0L
for (line in lines) {
val stack = ArrayDeque<Char>()
for (char in line) {
when (char) {
'(' -> stack.addLast(')')
'[' -> stack.addLast(']')
'{' -> stack.addLast('}')
'<' -> stack.addLast('>')
else -> if (char != stack.removeLast()) {
when (char) {
')' -> sum += 3
']' -> sum += 57
'}' -> sum += 1197
'>' -> sum += 25137
}
break
}
}
}
}
return sum
}
private fun part2(lines: List<String>): Long {
val scores = mutableListOf<Long>()
outer@
for (line in lines) {
val stack = ArrayDeque<Char>()
for (char in line) {
when (char) {
'(' -> stack.addFirst(')')
'[' -> stack.addFirst(']')
'{' -> stack.addFirst('}')
'<' -> stack.addFirst('>')
else -> if (char != stack.removeFirst()) {
continue@outer
}
}
}
val score = stack.fold(0) { acc: Long, expected ->
when (expected) {
')' -> acc * 5 + 1
']' -> acc * 5 + 2
'}' -> acc * 5 + 3
'>' -> acc * 5 + 4
else -> error("Invalid closing character")
}
}
scores.add(score)
}
return scores.sorted().run { this[size / 2] }
} | [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day10/Day10Kt.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class day10.Day10Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day10/Day10.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day17/Day17.kt | package day17
import java.io.File
import kotlin.math.abs
import kotlin.math.max
fun main() {
val data = parse("src/main/kotlin/day17/Day17.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 17 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Target(
val x1: Int,
val x2: Int,
val y1: Int,
val y2: Int,
)
private fun parse(path: String): Target {
val regex = """target area: x=(-?\d+)\.\.(-?\d+), y=(-?\d+)\.\.(-?\d+)""".toRegex()
val contents = File(path).readText()
val (x1, x2, y1, y2) = regex.find(contents)!!.destructured
return Target(x1.toInt(), x2.toInt(), y1.toInt(), y2.toInt())
}
// Frankly, this problem is very confusing to me, and I doubt this solution
// will work for any input that adheres to the description. But it worked for
// me, and I don't feel interested in making this any more flexible ¯\_(ツ)_/¯
private fun part1(target: Target): Int =
(abs(target.y1) - 1).let { n -> n * (n + 1) / 2 }
private fun Target.isReachedBy(vx: Int, vy: Int): Boolean {
var (x, y) = 0 to 0
var (dx, dy) = vx to vy
while (x <= x2 && y >= y1) {
x += dx
y += dy
if (x in x1..x2 && y in y1..y2) {
return true
}
dx = max(dx - 1, 0)
dy -= 1
}
return false
}
private fun part2(target: Target): Int {
val (vx0, vx1) = 1 to target.x2
val (vy0, vy1) = target.y1 to part1(target)
var counter = 0
for (vy in vy0..vy1) {
for (vx in vx0..vx1) {
if (target.isReachedBy(vx, vy)) {
++counter
}
}
}
return counter
}
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day17/Day17Kt.class",
"javap": "Compiled from \"Day17.kt\"\npublic final class day17.Day17Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day17/Day17.txt\n 2: invokestati... |
iproduct__course-kotlin__89884f8/07-functions-lambdas/src/main/kotlin/lambdas.kt | package course.kotlin.functions
fun <T> max(collection: Collection<T>, comparatorFn: (T, T) -> Int): T? {
var maxElem: T? = null
for (e in collection) {
if (maxElem == null) {
maxElem = e
} else if (e != null && comparatorFn(e, maxElem) > 0)
maxElem = e
}
return maxElem
}
fun compare(a: String, b: String): Int = a.length - b.length
fun main() {
val strings = listOf("Orange", "Banana", "Pineapple", "Papaya", "Apple", "Plum")
println(max(strings) { a, b -> a.length - b.length })
val sum1: (Int, Int) -> Int = { x: Int, y: Int -> x + y }
val sum = { x: Int, y: Int -> x + y }
val ints = listOf(1, 2, 3)
val product = ints.fold(1) { acc, e -> acc * e }
run { println("...") }
ints.filter { it > 0 } // this literal is of type '(it: Int) -> Boolean'
ints.filter {
val shouldFilter = it > 0
shouldFilter
}
ints.filter {
val shouldFilter = it > 0
return@filter shouldFilter
}
strings.filter { it.length == 5 }.sortedBy { it }.map { it.uppercase() }
val map = mapOf(1 to "x", 2 to "y", 3 to "z")
map.forEach { _, value -> println("$value!") }
// // destructuring
// map.mapValues { entry -> "${entry.value}!" }
// map.mapValues { (key, value) -> "$value!" }
// map.mapValues { (_, value) -> "$value!" }
// map.mapValues { (_, value): Map.Entry<Int, String> -> "$value!" }
// map.mapValues { (_, value: String) -> "$value!" }
//
// //anonimous functions
// fun(x: Int, y: Int): Int = x + y
// fun(x: Int, y: Int): Int {
// return x + y
// }
// ints.filter(fun(item) = item > 0)
//
//with receiver
val sum2: Int.(Int) -> Int = { other -> plus(other) }
val sum3 = fun Int.(other: Int): Int = this + other
println(sum2(1, 2))
println(sum3(1, 2))
}
| [
{
"class_path": "iproduct__course-kotlin__89884f8/course/kotlin/functions/LambdasKt$main$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class course.kotlin.functions.LambdasKt$main$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public course.kotlin.function... |
PacktPublishing__Kotlin-Quick-Start-Guide__5c781d2/Chapter06/KotlinCollectionsApi.kt | package quickstartguide.kotlin.chapter5
fun filterEvensThenSquare(numbers: Collection<Int>) {
val result: List<String> = numbers.filter { n -> n % 2 == 0 }
.map { n -> n * n }
.sorted()
.takeWhile { n -> n < 1000 }
.map { n -> n.toString() }
}
// FILTERING
fun drop() {
val numbers = listOf(1, 2, 3, 4, 5)
val dropped = numbers.drop(2)
}
fun filter() {
val numbers = listOf(1, 2, 3, 4, 5)
val smallerThan3 = numbers.filter { n -> n < 3 }
}
fun filterNot() {
val numbers = listOf(1, 2, 3, 4, 5)
val largerThan3 = numbers.filterNot { n -> n < 3 }
}
fun take() {
val numbers = listOf(1, 2, 3, 4, 5)
val first2 = numbers.take(2)
}
// AGGREGATE
fun any() {
val numbers = listOf(1, 2, 3, 4, 5)
val hasEvens = numbers.any { n -> n % 2 == 0 }
}
fun all() {
val numbers = listOf(1, 2, 3, 4, 5)
val allEven = numbers.all { n -> n % 2 == 0 }
}
fun count() {
val numbers = listOf(1, 2, 3, 4, 5)
val evenCount = numbers.count { n -> n % 2 == 0 }
}
fun forEach() {
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { n -> println(n) }
}
fun max() {
val numbers = listOf(1, 2, 3, 4, 5)
val max = numbers.max()
}
fun min() {
val numbers = listOf(1, 2, 3, 4, 5)
val min = numbers.min()
}
fun sum() {
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.sum()
}
// TRANSFORMING
fun map() {
val numbers = listOf(1, 2, 3, 4, 5)
val strings = numbers.map { n -> n.toString() }
}
fun flatMap() {
val numbers = listOf(1, 2, 3, 4, 5)
val multiplesOf10 = numbers.flatMap { n -> listOf(n, n * 10) }
}
fun groupBy() {
val strings = listOf("abc", "ade", "bce", "bef")
val groupped = strings.groupBy { s -> s[0] }
}
fun associateBy() {
val numbers = listOf(1, 2, 3, 4, 5)
val groupped = numbers.associateBy { n -> n.toString() }
}
// ITEMS
fun contains() {
val numbers = listOf(1, 2, 3, 4, 5)
val contains10 = numbers.contains(10)
}
fun first() {
val numbers = listOf(1, 2, 3, 4, 5)
val firstEven = numbers.first { n -> n % 2 == 0 }
}
fun firstOrNull() {
val numbers = listOf(1, 2, 3, 4, 5)
val firstLargerThan10 = numbers.firstOrNull { n -> n > 10 }
}
fun last() {
val numbers = listOf(1, 2, 3, 4, 5)
val lastEven = numbers.last { n -> n % 2 == 0 }
}
fun lastOrNull() {
val numbers = listOf(1, 2, 3, 4, 5)
val lastLargerThan10 = numbers.lastOrNull { n -> n > 10 }
}
fun single() {
val numbers = listOf(1, 2, 3, 4, 5)
val number5 = numbers.single { n -> n > 4 }
}
fun singleOrNull() {
val numbers = listOf(1, 2, 3, 4, 5)
val smallerThan1 = numbers.singleOrNull { n -> n < 1 }
}
// SORTING
fun reversed() {
val numbers = listOf(1, 2, 3, 4, 5)
val reversed = numbers.reversed()
}
fun sorted() {
val numbers = listOf(2, 1, 5, 3, 4)
val sorted = numbers.sorted()
}
fun sortedDescending() {
val numbers = listOf(2, 1, 5, 3, 4)
val sortedDesc = numbers.sortedDescending()
}
| [
{
"class_path": "PacktPublishing__Kotlin-Quick-Start-Guide__5c781d2/quickstartguide/kotlin/chapter5/KotlinCollectionsApiKt.class",
"javap": "Compiled from \"KotlinCollectionsApi.kt\"\npublic final class quickstartguide.kotlin.chapter5.KotlinCollectionsApiKt {\n public static final void filterEvensThenSquar... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day09/Solution.kt | package day09
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
val dx = arrayOf(0, 1, 0, -1)
val dy = arrayOf(-1, 0, 1, 0)
fun part1(lines: Input): Int {
var answer = 0
for (x in lines.indices) {
outer@for (y in lines[x].indices) {
for (d in 0 until 4) {
val xx = x + dx[d]
val yy = y + dy[d]
if (xx in lines.indices && yy in lines[xx].indices) {
if (lines[xx][yy] <= lines[x][y]) continue@outer
}
}
answer += lines[x][y].code - '0'.code + 1
}
}
return answer
}
fun part2(lines: Input): Int {
class DSU(size: Int) {
private val parent = IntArray(size) { it }
val size = IntArray(size) { 1 }
fun getParent(v: Int): Int = if (v == parent[v]) v else getParent(parent[v]).also { parent[v] = it }
fun unite(v: Int, u: Int): Boolean {
val vp = getParent(v)
val up = getParent(u)
if (up != vp) {
parent[up] = vp
size[vp] += size[up]
return true
}
return false
}
}
val dsu = DSU(lines.size * lines[0].length)
for (x in lines.indices) {
for (y in lines[x].indices) {
if (lines[x][y] == '9') continue
for (d in 0 until 4) {
val xx = x + dx[d]
val yy = y + dy[d]
if (xx in lines.indices && yy in lines[xx].indices) {
if (lines[xx][yy] <= lines[x][y]) {
dsu.unite(yy * lines.size + xx, y * lines.size + x)
}
}
}
}
}
val map = buildMap {
for (x in lines.indices) {
for (y in lines[x].indices) {
val root = dsu.getParent(y * lines.size + x)
val size = dsu.size[root]
put(root, size)
}
}
}
return map.values.sortedDescending().take(3).fold(1, Int::times)
}
check(part1(readInput("test-input.txt")) == 15)
check(part2(readInput("test-input.txt")) == 1134)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day09/$s")).readLines()
}
private typealias Input = List<String> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day09/SolutionKt$main$part2$DSU.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day09.SolutionKt$main$part2$DSU {\n private final int[] parent;\n\n private final int[] size;\n\n public day09.SolutionKt$main$part2$DSU(int);\n Co... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day08/Solution.kt | package day08
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(lines: Input): Int {
return lines.sumOf { entry ->
val (_, reading) = entry.split("|")
reading.split(" ")
.filter { it.isNotBlank() }
.count { it.length in setOf(2, 3, 4, 7) }
}
}
fun part2(lines: Input): Int {
fun String.normalize() = String(this.toCharArray().sortedArray())
fun decode(digits: List<String>): Array<String> {
val map = arrayOfNulls<String>(10)
map[1] = digits.find { it.length == 2 }
map[7] = digits.find { it.length == 3 }
map[4] = digits.find { it.length == 4 }
map[8] = digits.find { it.length == 7 }
val zeroSixOrNine = digits.filter { it.length == 6 }
check(zeroSixOrNine.size == 3)
map[6] = zeroSixOrNine.find { !it.toSet().containsAll(map[1]!!.toSet()) }
map[9] = zeroSixOrNine.find { it.toSet().containsAll(map[4]!!.toSet()) }
map[0] = zeroSixOrNine.find { it != map[6] && it != map[9] }
val twoThreeOrFive = digits.filter { it.length == 5 }
check(twoThreeOrFive.size == 3)
map[3] = twoThreeOrFive.find { it.toSet().containsAll(map[1]!!.toSet()) }
map[5] = twoThreeOrFive.find { map[6]!!.toSet().containsAll(it.toSet()) }
map[2] = twoThreeOrFive.find { it != map[3] && it != map[5] }
return map.requireNoNulls()
}
return lines.sumOf { entry ->
val (digits, number) = entry.split("|")
val map = decode(digits.split(" ").filter { it.isNotBlank() }.map { it.normalize() })
number.split(" ")
.filter { it.isNotBlank() }
.map { it.normalize() }
.map { map.indexOf(it) }
.fold(0) { acc, i -> acc * 10 + i } as Int
}
}
check(part1(readInput("test-input.txt")) == 26)
check(part2(readInput("test-input.txt")) == 61229)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day08/$s")).readLines()
}
private typealias Input = List<String> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day08/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day08.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day06/Solution.kt | package day06
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
val mem = Array(2) {
Array(9) {
LongArray(257) { -1 }
}
}
fun model(daysLeft: Int, day: Int, part: Int): Long {
require(daysLeft in 0..8)
require(part in 0..1)
val lastDay = if (part == 0) 80 else 256
require(day in 0..lastDay)
mem[part][daysLeft][day].let {
if (it != -1L) return it
}
val res = if (day >= lastDay) 1 else if (daysLeft == 0) {
model(6, day + 1, part) + model(8, day + 1, part)
} else {
model(daysLeft - 1, day + 1, part)
}
return res.also {
mem[part][daysLeft][day] = res
}
}
fun part1(input: Input): Long {
return input.sumOf { model(it, 0, 0) }
}
fun part2(input: Input): Long {
return input.sumOf { model(it, 0, 1) }
}
check(part1(readInput("test-input.txt")) == 5934L)
println(part1(readInput("input.txt")))
part2(readInput("test-input.txt")).let {
check(it == 26984457539L) { it }
}
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day06/$s")).readLines().first().split(",").map { it.toInt() }
}
private typealias Input = List<Int> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day06/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day06.SolutionKt {\n public static final void main();\n Code:\n 0: iconst_0\n 1: istore_1\n 2: iconst_2\n 3: anewarray #8 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day23/Solution.kt | package day23
import java.nio.file.Files
import java.nio.file.Paths
import java.util.TreeSet
import kotlin.math.absoluteValue
import kotlin.system.measureTimeMillis
fun main() {
val amphipods = "ABCD"
val step = listOf(1, 10, 100, 1000)
val rooms = listOf(3, 5, 7, 9)
fun Input.isFinal(): Boolean {
for (i in this[0]) {
if (i != '.' && i != '#') return false
}
for (i in amphipods.indices) {
for (j in 1 until this.size) {
if (this[j][rooms[i]] != amphipods[i]) {
return false
}
}
}
return true
}
fun Input.swap(x1: Int, y1: Int, x2: Int, y2: Int): Input = map { it.toCharArray() }.run {
this[x1][y1] = this[x2][y2].also {
this[x2][y2] = this[x1][y1]
}
map { String(it) }
}
fun generateNextStates(list: List<String>) = buildList {
for (i in list[0].indices) {
if (list[0][i] !in amphipods) continue
val amphipod = list[0][i].code - 'A'.code // move from hallway to the final room.
val roomId = rooms[amphipod]
val target = list.indexOfLast { it[roomId] == '.' }
if (target == -1) continue
if (list.subList(0, target).any { it[roomId] != '.' }) continue
if (list.subList(target + 1, list.size).any { it[roomId] != amphipods[amphipod] }) continue
if (list[0].substring(minOf(i + 1, roomId), maxOf(roomId, i - 1)).any { it != '.' }) continue
val nextState = list.swap(0, i, target, roomId)
val distance = (i - roomId).absoluteValue + target
add(nextState to distance * step[amphipod])
}
for ((index, roomId) in rooms.withIndex()) {
if (list.all { it[roomId] == '.' || it[roomId] == amphipods[index] }) continue
for (i in 1 until list.size) {
if (list[i][roomId] == '.') continue
val amphipod = list[i][roomId].code - 'A'.code // move from starting room to the hallway.
for (range in listOf(roomId + 1 until list[0].length, roomId - 1 downTo 0)) {
for (j in range) {
if (list[0][j] != '.') break
if (j in rooms) continue
val nextState = list.swap(0, j, i, roomId)
val distance = (j - roomId).absoluteValue + i
add(nextState to distance * step[amphipod])
}
}
break
}
}
}
fun part1(input: Input): Int {
val stateIds = mutableMapOf<List<String>, Int>()
val states = mutableListOf<List<String>>()
val costs = mutableListOf<Int>()
val queue = TreeSet(Comparator.comparingInt<Int> { costs[it] }.thenComparingInt { it })
stateIds[input] = states.size
states.add(input)
costs.add(0)
queue.add(0)
while (queue.isNotEmpty()) {
val id = queue.pollFirst()!!
if (states[id].isFinal()) {
return costs[id]
}
for ((state, delta) in generateNextStates(states[id])) {
val newCost = costs[id] + delta
val stateId = stateIds.computeIfAbsent(state) { states.size }
if (stateId == states.size) {
states.add(state)
costs.add(newCost)
queue.add(stateId)
} else if (newCost < costs[stateId]) {
check(queue.remove(stateId))
costs[stateId] = newCost
queue.add(stateId)
}
}
}
error("Polundra!")
}
fun part2(input: Input): Int {
return part1(
buildList {
add(input[0])
add(input[1])
add(" #D#C#B#A#")
add(" #D#B#A#C#")
add(input[2])
}
)
}
check(part1(readInput("test-input.txt")) == 12521)
check(part2(readInput("test-input.txt")) == 44169)
val millis = measureTimeMillis {
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
System.err.println("Done in $millis ms")
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day23/$s")).readLines().subList(1, 4)
}
private typealias Input = List<String>
| [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day23/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day23.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String ABCD\n 2: astore_0\n 3: iconst_4\n ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day24/Solution.kt | package day24
import java.nio.file.Files
import java.nio.file.Paths
import java.util.TreeMap
import kotlin.system.measureTimeMillis
fun main() {
fun Char.registerId() = code - 'w'.code
val alu = longArrayOf(0, 0, 0, 0)
var nextInput = -1
fun String.parseCommand(): Command {
return if (startsWith("inp ")) {
Command { alu[this[4].registerId()] = nextInput.toLong().also { check(it in 1..9) } }
} else {
val (cmd, a, b) = split(" ")
check(a.length == 1)
val register = a.first().registerId()
val value = { if (b.first() in "wxyz") alu[b.first().registerId()] else b.toLong() }
when (cmd) {
"add" -> Command { alu[register] += value() }
"mul" -> Command { alu[register] *= value() }
"div" -> Command { alu[register] /= value() }
"mod" -> Command { alu[register] %= value() }
"eql" -> Command { alu[register] = if (alu[register] == value()) 1 else 0 }
else -> error("Unknown command $cmd")
}
}
}
fun solve(input: Input, comparator: Comparator<Int>): Long {
check(input.size % 14 == 0)
val commands = input.map(String::parseCommand).chunked(input.size / 14)
data class State(val digit: Int, val prevZ: Long) : Comparable<State> {
override fun compareTo(other: State) = comparator.compare(this.digit, other.digit)
}
val mem = Array(15) { TreeMap<Long, State>() }
mem[0][0] = State(0, Long.MIN_VALUE)
val pow26 = generateSequence(1L) { it * 26 }.takeWhile { it < Int.MAX_VALUE }.toList()
for (len in 1..14) {
val threshold = pow26.getOrElse(15 - len) { Long.MAX_VALUE }
for (digit in 1..9) {
nextInput = digit
for (z in mem[len - 1].keys) {
if (z > threshold) break // We won't get Z=0 in the end if current Z is too big.
alu.fill(0); alu['z'.registerId()] = z
commands[len - 1].forEach { it.execute() }
mem[len].merge(alu['z'.registerId()], State(digit, z), ::maxOf)
}
}
}
val (answer, _, _) = mem.foldRight(Triple(0L, 1L, 0L)) { map, (acc, pow10, z) ->
val (digit, prevZ) = map[z]!!
Triple(acc + digit * pow10, pow10 * 10, prevZ)
}
return answer
}
fun part1(input: Input): Long {
return solve(input, Comparator.naturalOrder())
}
fun part2(input: Input): Long {
return solve(input, Comparator.reverseOrder())
}
val millis = measureTimeMillis {
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
System.err.println("Done in $millis ms")
}
private fun interface Command {
fun execute()
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day24/$s")).readLines()
}
private typealias Input = List<String>
| [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day24/SolutionKt$main$solve$2.class",
"javap": "Compiled from \"Solution.kt\"\nfinal class day24.SolutionKt$main$solve$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function2<day24.SolutionKt$main$solve$State, day24... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day12/Solution.kt | package day12
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun buildGraph(lines: Input): Map<String, List<String>> = buildMap<String, MutableList<String>> {
for (line in lines) {
val (v, w) = line.split("-")
val vList = getOrPut(v) { mutableListOf() }
val wList = getOrPut(w) { mutableListOf() }
vList.add(w)
wList.add(v)
}
}
fun dfs(vertex: String, graph: Map<String, List<String>>, visited: Set<String>, visitedTwice: Boolean): Int {
if (vertex == "end") return 1
var sum = 0
for (next in graph[vertex]!!) {
if (next !in visited) {
val nextVisited = if (next.first().isLowerCase()) visited + next else visited
sum += dfs(next, graph, nextVisited, visitedTwice)
} else if (next != "start" && !visitedTwice) {
sum += dfs(next, graph, visited, true)
}
}
return sum
}
fun part1(lines: Input): Int {
val graph = buildGraph(lines)
return dfs("start", graph, setOf("start"), true)
}
fun part2(lines: Input): Int {
val graph = buildGraph(lines)
return dfs("start", graph, setOf("start"), false)
}
check(part1(readInput("test-input.txt")) == 226)
check(part2(readInput("test-input.txt")) == 3509)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day12/$s")).readLines()
}
private typealias Input = List<String> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day12/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day12.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day15/Solution.kt | package day15
import java.nio.file.Files
import java.nio.file.Paths
import java.util.TreeSet
import kotlin.system.measureTimeMillis
fun main() {
fun part1(input: Input): Int {
val costs = Array(input.size) {
IntArray(input[it].size) { Int.MAX_VALUE }
}
val priorityQueue = TreeSet(
Comparator
.comparingInt<Pair<Int, Int>> { costs[it.first][it.second] }
.thenComparingInt { it.first }
.thenComparingInt { it.second }
)
costs[0][0] = 0
priorityQueue.add(0 to 0)
val dx = arrayOf(-1, 0, 1, 0)
val dy = arrayOf(0, 1, 0, -1)
while (priorityQueue.isNotEmpty()) {
val (x, y) = priorityQueue.pollFirst()!!
if (x == input.lastIndex && y == input[x].lastIndex) {
return costs[x][y]
}
for (d in 0 until 4) {
val xx = x + dx[d]
val yy = y + dy[d]
if (xx in input.indices && yy in input[xx].indices) {
val newCost = costs[x][y] + input[xx][yy]
if (newCost < costs[xx][yy]) {
priorityQueue.remove(xx to yy)
costs[xx][yy] = newCost
priorityQueue.add(xx to yy)
}
}
}
}
error("Polundra!")
}
fun part2(input: Input): Int {
val newInput = List(input.size * 5) { xx ->
val x = xx % input.size
List(input[x].size * 5) { yy ->
val y = yy % input[x].size
val diagonal = xx / input.size + yy / input[x].size
(input[x][y] - 1 + diagonal) % 9 + 1
}
}
return part1(newInput)
}
check(part1(readInput("test-input.txt")) == 40)
check(part2(readInput("test-input.txt")) == 315)
val timeSpent = measureTimeMillis {
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
System.err.println("In ${timeSpent}ms")
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day15/$s")).readLines().map { it.map { it.code - '0'.code } }
}
private typealias Input = List<List<Int>> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day15/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day15.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day14/Solution.kt | package day14
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(input: Input): Int {
fun iterate(template: String, rules: Map<String, String>) = buildString {
append(template[0])
for (i in 1 until template.length) {
rules[template.substring(i - 1, i + 1)]?.let {
append(it)
}
append(template[i])
}
}
val rules = input.second.toMap()
var template = input.first
repeat(10) {
template = iterate(template, rules)
}
return template
.groupBy { it }
.values
.map { it.size }
.let { it.maxOrNull()!! - it.minOrNull()!! }
}
fun part2(input: Input): Long {
val rules = input.second.toMap()
val mem = Array(41) {
mutableMapOf<String, Map<Char, Long>>()
}
fun combine(
lhs: Map<Char, Long>,
rhs: Map<Char, Long>,
): Map<Char, Long> {
val sum = (lhs.keys + rhs.keys).associateWith {
lhs.getOrDefault(it, 0) + rhs.getOrDefault(it, 0)
}
return sum
}
fun rec(pair: String, depth: Int): Map<Char, Long> {
mem[depth][pair]?.let { return it }
if (depth == 0 || !rules.containsKey(pair)) {
return mapOf(pair.first() to 1L).also { mem[depth][pair] = it }
}
val between = rules[pair]!!
return combine(
rec(pair[0] + between, depth - 1),
rec(between + pair[1], depth - 1)
).also { mem[depth][pair] = it }
}
val origin = input.first + "$"
var answer = emptyMap<Char, Long>()
for (i in 0 until origin.lastIndex) {
answer = combine(answer, rec(origin.substring(i, i + 2), 40))
}
return answer.values.let {
it.maxOrNull()!! - it.minOrNull()!!
}
}
check(part1(readInput("test-input.txt")) == 1588)
check(part2(readInput("test-input.txt")) == 2188189693529L)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day14/$s")).readLines().let { lines ->
val origin = lines.first()
val rules = lines.drop(2).map {
val (a, b) = it.split(" -> ")
a to b
}
origin to rules
}
}
private typealias Input = Pair<String, List<Pair<String, String>>> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day14/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day14.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day13/Solution.kt | package day13
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun log(field: Array<BooleanArray>) = buildString {
for (y in field[0].indices) {
for (x in field.indices) {
append(if (field[x][y]) '#' else '.')
}
append('\n')
}
}.let { System.err.println(it) }
fun fold(field: Array<BooleanArray>, fold: Pair<Boolean, Int>): Array<BooleanArray> =
if (fold.first) {
val foldX = fold.second
check(field[foldX].none { it })
val maxX = maxOf(foldX, field.size - 1 - foldX)
Array(maxX) { xx ->
BooleanArray(field[xx].size) { yy ->
val x1 = foldX - (maxX - xx)
val x2 = foldX + (maxX - xx)
(x1 >= 0 && field[x1][yy]) || (x2 < field.size && field[x2][yy])
}
}
} else {
val foldY = fold.second
val maxY = maxOf(foldY, field[0].size - foldY - 1)
check(field.none { it[foldY] })
Array(field.size) { xx ->
BooleanArray(maxY) { yy ->
val y1 = foldY - (maxY - yy)
val y2 = foldY + (maxY - yy)
(y1 >= 0 && field[xx][y1]) || (y2 < field[xx].size && field[xx][y2])
}
}
}
fun part1(input: Input): Int {
val maxX = input.first.maxOf { it.first }
val maxY = input.first.maxOf { it.second }
val field = Array(maxX + 1) {
BooleanArray(maxY + 1)
}
for ((x, y) in input.first) {
field[x][y] = true
}
return fold(field, input.second.first()).sumOf { it.count { it } }
}
fun part2(input: Input): Int {
val maxX = input.first.maxOf { it.first }
val maxY = input.first.maxOf { it.second }
var field = Array(maxX + 1) {
BooleanArray(maxY + 1)
}
for ((x, y) in input.first) {
field[x][y] = true
}
for (fold in input.second) {
field = fold(field, fold)
}
log(field)
return 42
}
check(part1(readInput("test-input.txt")) == 17)
check(part2(readInput("test-input.txt")) == 42)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day13/$s")).readLines().let { lines ->
val coordinates = lines
.filter { !it.startsWith("fold along ") }
.filter { it.isNotBlank() }
.map {
val (x, y) = it.split(",").map { it.toInt() }
Pair(x, y)
}
val folds = lines
.filter { it.startsWith("fold along ") }
.map {
val (axis, coordinate) = it.substring("fold along ".length).split("=")
val axisRes = when(axis) {
"x" -> true
"y" -> false
else -> error("unknown axis: $axis")
}
Pair(axisRes, coordinate.toInt())
}
Pair(coordinates, folds)
}
}
private typealias Input = Pair<List<Pair<Int, Int>>, List<Pair<Boolean, Int>>> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day13/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day13.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day25/Solution.kt | package day25
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.system.measureTimeMillis
fun main() {
fun part1(input: Input): Int {
val field = input.map { it.toCharArray() }
var moves = 0
val herds = ">v"
val di = intArrayOf(0, 1)
val dj = intArrayOf(1, 0)
val moved = arrayOf<ArrayList<Pair<Int, Int>>>(arrayListOf(), arrayListOf())
do {
moves++
moved.forEach { it.clear() }
repeat(2) { herd ->
for (i in field.indices) {
for (j in field[i].indices) {
if (field[i][j] == herds[herd]) {
val ii = (i + di[herd]) % field.size
val jj = (j + dj[herd]) % field[ii].size
if (field[ii][jj] == '.') {
moved[herd].add(i to j)
}
}
}
}
for ((i, j) in moved[herd]) {
val ii = (i + di[herd]) % field.size
val jj = (j + dj[herd]) % field[ii].size
field[ii][jj] = field[i][j]
field[i][j] = '.'
}
}
} while (moved.any { it.isNotEmpty() })
return moves
}
check(part1(readInput("test-input.txt")) == 58)
val millis = measureTimeMillis {
println(part1(readInput("input.txt")))
}
System.err.println("Done in $millis ms")
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day25/$s")).readLines()
}
private typealias Input = List<String>
| [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day25/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day25.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day22/Solution.kt | package day22
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.system.measureTimeMillis
fun main() {
fun MutableList<Int>.inPlaceDistinct() {
sort()
var ptr = 1
for (i in 1 until this.size) {
if (this[i] != this[i - 1]) {
this[ptr++] = this[i]
}
}
while (size > ptr) {
removeLast()
}
}
fun solve(input: Input): Long {
val all = Array(3) { mutableListOf<Int>() }
for ((_, cuboid) in input) {
for (i in cuboid.indices) {
all[i].addAll(cuboid[i])
}
}
all.forEach { it.inPlaceDistinct() }
val (xs, ys, zs) = all
val state = Array(xs.size - 1) { Array(ys.size - 1) { BooleanArray(zs.size - 1) } }
for ((on, cuboid) in input) {
val (xRange, yRange, zRange) = cuboid.mapIndexed { index, interval ->
val (from, to) = interval.map { all[index].binarySearch(it) }
from until to
}
for (x in xRange) {
for (y in yRange) {
for (z in zRange) {
state[x][y][z] = on
}
}
}
}
var answer = 0L
for (i in state.indices) {
for (j in state[i].indices) {
for (k in state[i][j].indices) {
if (state[i][j][k]) {
answer += 1L * (xs[i + 1] - xs[i]) * (ys[j + 1] - ys[j]) * (zs[k + 1] - zs[k])
}
}
}
}
return answer
}
fun part1(input: Input): Int {
return solve(
input.filter { (_, cuboid) ->
cuboid.all { (from, to) -> from in -50..50 && to in -49..51 }
}
).toInt()
}
fun part2(input: Input): Long {
return solve(input)
}
check(part1(readInput("test-input.txt")) == 590784)
check(part2(readInput("test-input2.txt")) == 2758514936282235L)
val millis = measureTimeMillis {
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
System.err.println("Done in $millis ms")
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day22/$s")).readLines().map { line ->
val on = line.startsWith("on ")
if (!on) check(line.startsWith("off "))
val list = line.substring(if (on) 3 else 4).split(",").mapIndexed { index, range ->
check(range.matches("${"xyz"[index]}=-?\\d+..-?\\d+".toRegex()))
val (from, to) = range.substring(2).split("..").map { it.toInt() }
listOf(from, to + 1)
}
Pair(on, list)
}
}
private typealias Input = List<Pair<Boolean, List<List<Int>>>> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day22/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day22.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day04/Solution.kt | package day04
import java.io.BufferedReader
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun solveBoard(board: Board, sequence: List<Int>): Pair<Int, Int> {
val rows = IntArray(5) { 5 }
val cols = IntArray(5) { 5 }
var sum = board.sumOf { it.sum() }
for ((index, number) in sequence.withIndex()) {
for (r in rows.indices) {
for (c in cols.indices) {
if (board[r][c] == number) {
rows[r]--
cols[c]--
sum -= number
}
}
}
if (rows.any { it == 0 } || cols.any { it == 0 }) {
return Pair(index, sum * number)
}
}
error("Polundra!")
}
fun part1(input: Pair<List<Int>, List<Board>>): Int {
val (sequence, boards) = input
return boards
.map { solveBoard(it, sequence) }
.minByOrNull { it.first }!!
.second
}
fun part2(input: Pair<List<Int>, List<Board>>): Int {
val (sequence, boards) = input
return boards
.map { solveBoard(it, sequence) }
.maxByOrNull { it.first }!!
.second
}
check(part1(readInput("test-input.txt")) == 4512)
check(part2(readInput("test-input.txt")) == 1924)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Pair<List<Int>, List<Board>> {
val reader = Files.newBufferedReader(Paths.get("src/day04/$s"))
val sequence = reader.readLine()!!.split(",").map { it.toInt() }
val boards = ArrayList<Board>()
while (true) boards.add(
List(5) {
val row = reader.readNonBlankLine() ?: return Pair(sequence, boards)
check(row.isNotBlank())
row.split(" ").filter { it.isNotBlank() }.map { it.toInt() }
}
)
}
private fun BufferedReader.readNonBlankLine(): String? = readLine()?.ifBlank { readNonBlankLine() }
typealias Board = List<List<Int>> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day04/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day04.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day03/Solution.kt | package day03
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(numbers: List<String>): Int {
val count = IntArray(numbers[0].length)
for (num in numbers) {
for ((index, bit) in num.withIndex()) {
count[index] += if (bit == '1') 1 else 0
}
}
val gamma = count
.map { if (it + it > numbers.size) 1 else 0 }
.joinToString("") { it.toString() }
.toInt(2)
val epsilon = count
.map { if (it + it > numbers.size) 0 else 1 }
.joinToString("") { it.toString() }
.toInt(2)
return gamma * epsilon
}
fun part2(report: List<String>): Int {
tailrec fun filter(list: List<String>, position: Int, predicate: (char: Char, mostCommon: Char) -> Boolean): String {
if (list.size == 1) return list.first()
val sum = list.sumOf { it[position].code - '0'.code }
val mostCommon = if (sum + sum >= list.size) '1' else '0'
return filter(
list.filter {
predicate(it[position], mostCommon)
},
position + 1,
predicate
)
}
val oxygenGeneratorRating = filter(report, 0) { char, mostCommon ->
char == mostCommon
}.toInt(2)
val co2ScrubberRating = filter(report, 0) { char, mostCommon ->
char != mostCommon
}.toInt(2)
return oxygenGeneratorRating * co2ScrubberRating
}
check(part1(readInput("test-input.txt")) == 198)
check(part2(readInput("test-input.txt")) == 230)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): List<String> {
return Files.newBufferedReader(Paths.get("src/day03/$s")).readLines().filterNot { it.isBlank() }.also { list ->
check(list.all { it.length == list[0].length })
}
} | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day03/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day03.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day05/Solution.kt | package day05
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.math.sign
fun main() {
fun part1(lines: List<Line>): Int {
val maxX = lines.maxOf { maxOf(it.first.first, it.second.first) }
val maxY = lines.maxOf { maxOf(it.first.second, it.second.second) }
val map = Array(maxX + 1) {
IntArray(maxY + 1)
}
lines
.filter { it.first.first == it.second.first || it.first.second == it.second.second }
.forEach { (from, to) ->
for (x in minOf(from.first, to.first) .. maxOf(from.first, to.first)) {
for (y in minOf(from.second, to.second) .. maxOf(from.second, to.second)) {
map[x][y]++
}
}
}
return map.sumOf { row -> row.count { it > 1 } }
}
fun part2(lines: List<Line>): Int {
val maxX = lines.maxOf { maxOf(it.first.first, it.second.first) }
val maxY = lines.maxOf { maxOf(it.first.second, it.second.second) }
val map = Array(maxX + 1) {
IntArray(maxY + 1)
}
for ((from, to) in lines) {
val dx = (to.first - from.first).sign
val dy = (to.second - from.second).sign
var x = from.first
var y = from.second
map[x][y]++
while (x != to.first || y != to.second) {
x += dx
y += dy
map[x][y]++
}
}
return map.sumOf { row -> row.count { it > 1 } }
}
check(part1(readInput("test-input.txt")) == 5)
check(part2(readInput("test-input.txt")) == 12)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): List<Line> {
return Files.newBufferedReader(Paths.get("src/day05/$s")).readLines().map {
val (from, to) = it.split(" -> ")
val (x1, y1) = from.split(",").map { it.toInt() }
val (x2, y2) = to.split(",").map { it.toInt() }
Pair(x1, y1) to Pair(x2, y2)
}
}
typealias Point = Pair<Int, Int>
typealias Line = Pair<Point, Point> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day05/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day05.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day18/Solution.kt | package day18
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(input: Input): Int {
return input.reduce { acc, snailfish ->
SnailfishPair(acc, snailfish).reduce()
}.magnitude()
}
fun part2(input: Input): Int {
return input.maxOf { lhs ->
input.maxOf { rhs ->
if (lhs != rhs) SnailfishPair(lhs, rhs).reduce().magnitude()
else Int.MIN_VALUE
}
}
}
check(part1(readInput("test-input.txt")) == 4140)
check(part2(readInput("test-input.txt")) == 3993)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun Snailfish.reduce(): Snailfish =
reduceExplode(0)?.first?.reduce()
?: reduceSplit()?.reduce()
?: this
private fun Snailfish.reduceExplode(depth: Int): Triple<Snailfish, Int, Int>? {
fun propagateRight(snailfish: Snailfish, add: Int): Snailfish = if (add == 0) snailfish else
when (snailfish) {
is SnailfishNumber -> SnailfishNumber(snailfish.value + add)
is SnailfishPair -> SnailfishPair(snailfish.lhs, propagateRight(snailfish.rhs, add))
}
fun propagateLeft(snailfish: Snailfish, add: Int): Snailfish = if (add == 0) snailfish else
when (snailfish) {
is SnailfishNumber -> SnailfishNumber(snailfish.value + add)
is SnailfishPair -> SnailfishPair(propagateLeft(snailfish.lhs, add), snailfish.rhs)
}
return when (this) {
is SnailfishNumber -> null
is SnailfishPair -> if (depth == 4) {
check(lhs is SnailfishNumber && rhs is SnailfishNumber)
Triple(SnailfishNumber(0), lhs.value, rhs.value)
} else {
lhs.reduceExplode(depth + 1)
?.let { (snailfish, left, right) ->
Triple(SnailfishPair(snailfish, propagateLeft(rhs, right)), left, 0)
}
?: rhs.reduceExplode(depth + 1)
?.let { (snailfish, left, right) ->
Triple(SnailfishPair(propagateRight(lhs, left), snailfish), 0, right)
}
}
}
}
private fun Snailfish.reduceSplit(): SnailfishPair? = when(this) {
is SnailfishNumber -> if (value < 10) null else
SnailfishPair(SnailfishNumber(value / 2), SnailfishNumber((value + 1) / 2))
is SnailfishPair ->
lhs.reduceSplit()?.let { SnailfishPair(it, rhs) } ?:
rhs.reduceSplit()?.let { SnailfishPair(lhs, it) }
}
private fun Snailfish.magnitude(): Int = when(this) {
is SnailfishNumber -> value
is SnailfishPair -> 3 * lhs.magnitude() + 2 * rhs.magnitude()
}
private sealed interface Snailfish
private data class SnailfishPair(
val lhs: Snailfish,
val rhs: Snailfish,
) : Snailfish
private data class SnailfishNumber(
val value: Int,
) : Snailfish
private class Parser(private val input: String) : AutoCloseable {
private var ptr = 0
fun parseSnailfish(): Snailfish = if (input[ptr] == '[') {
parsePair()
} else {
parseNumber()
}
private fun parseNumber(): SnailfishNumber {
check(input[ptr] in '0'..'9')
var res = 0
while (ptr < input.length && input[ptr].isDigit()) {
res = 10 * res + input[ptr++].code - '0'.code
}
return SnailfishNumber(res)
}
private fun parsePair(): SnailfishPair {
check(input[ptr++] == '[')
val lhs = parseSnailfish()
check(input[ptr++] == ',')
val rhs = parseSnailfish()
check(input[ptr++] == ']')
return SnailfishPair(lhs, rhs)
}
override fun close() {
check(ptr == input.length)
}
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day18/$s")).readLines().map { line ->
Parser(line).use { it.parseSnailfish() }
}
}
private typealias Input = List<Snailfish> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day18/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day18.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day20/Solution.kt | package day20
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun wrap(field: List<String>, surrounding: Char = '.'): List<String> {
val length = field.first().length
val darkRow = buildString(length) { repeat(length) { append(surrounding) } }
val fix = List(3) { darkRow }
return (fix + field + fix).map { "$surrounding$surrounding$surrounding$it$surrounding$surrounding$surrounding" }
}
fun iterate(wrapped: List<String>, decoder: String): List<String> {
return buildList(wrapped.size - 2) {
for (i in 1 until wrapped.lastIndex) {
add(
buildString(wrapped[i].length - 2) {
for (j in 1 until wrapped[i].lastIndex) {
var index = 0
for (di in -1..1) {
for (dj in -1..1) {
index = 2 * index + if (wrapped[i + di][j + dj] == '#') 1 else 0
}
}
append(decoder[index])
}
}
)
}
}
}
fun part1(input: Input): Int {
return iterate(
iterate(wrap(input.second), input.first).let { wrap(it, it.first().first()) },
input.first
).sumOf {
it.count { it == '#' }
}
}
fun part2(input: Input): Int {
var image = wrap(input.second)
repeat(50) {
val next = iterate(image, input.first)
image = wrap(next, next.first().first())
}
return image.sumOf { it.count { it == '#' } }
}
check(part1(readInput("test-input.txt")) == 35)
check(part2(readInput("test-input.txt")) == 3351)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day20/$s")).readLines().let { lines ->
Pair(
lines.first(),
lines.drop(2).filter { it.isNotBlank() }
)
}
}
private typealias Input = Pair<String, List<String>> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day20/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day20.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day16/Solution.kt | package day16
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(input: Input): Int {
fun dfs(packet: Packet): Int {
var sum = packet.version
if (packet is Operation) {
for (subPacket in packet.subPackets) {
sum += dfs(subPacket)
}
}
return sum
}
Parser(input).use { parser ->
return dfs(parser.parsePacket())
}
}
fun part2(input: Input): Long {
fun evaluate(packet: Packet): Long = when(packet) {
is Literal -> packet.value
is Operation -> when(packet.typeId) {
0 -> packet.subPackets.sumOf { evaluate(it) }
1 -> packet.subPackets.fold(1L) { acc, subPacket -> acc * evaluate(subPacket) }
2 -> packet.subPackets.minOf { evaluate(it) }
3 -> packet.subPackets.maxOf { evaluate(it) }
5, 6, 7 -> {
check(packet.subPackets.size == 2)
val (lhs, rhs) = packet.subPackets.map { evaluate(it) }
when (packet.typeId) {
5 -> if (lhs > rhs) 1 else 0
6 -> if (lhs < rhs) 1 else 0
7 -> if (lhs == rhs) 1 else 0
else -> error("unexpected packet type ID: ${packet.typeId}")
}
}
else -> error("unexpected packet type ID: ${packet.typeId}")
}
}
Parser(input).use { parser ->
return evaluate(parser.parsePacket())
}
}
check(part1("D2FE28".toBinaryString()) == 6)
check(part1("38006F45291200".toBinaryString()) == 9)
check(part1("EE00D40C823060".toBinaryString()) == 14)
check(part1("8A004A801A8002F478".toBinaryString()) == 16)
check(part1("620080001611562C8802118E34".toBinaryString()) == 12)
check(part1("C0015000016115A2E0802F182340".toBinaryString()) == 23)
check(part1("A0016C880162017C3686B18A3D4780".toBinaryString()) == 31)
check(part2("C200B40A82".toBinaryString()) == 3L)
check(part2("04005AC33890".toBinaryString()) == 54L)
check(part2("880086C3E88112".toBinaryString()) == 7L)
check(part2("CE00C43D881120".toBinaryString()) == 9L)
check(part2("D8005AC2A8F0".toBinaryString()) == 1L)
check(part2("F600BC2D8F".toBinaryString()) == 0L)
check(part2("9C005AC2F8F0".toBinaryString()) == 0L)
check(part2("9C0141080250320F1802104A08".toBinaryString()) == 1L)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private sealed interface Packet {
val version: Int
val typeId: Int
}
private data class Literal(
override val version: Int,
override val typeId: Int,
val value: Long
) : Packet
private data class Operation(
override val version: Int,
override val typeId: Int,
val subPackets: List<Packet>
) : Packet
private class Parser(val string: String): AutoCloseable {
private var ptr = 0
fun parsePacket(): Packet {
val version = parseNum(3)
val typeId = parseNum(3)
return if (typeId == 4) {
Literal(version, typeId, parseLiteralValue())
} else {
Operation(version, typeId, parseSubPackets())
}
}
private fun parseSubPackets(): List<Packet> {
val lengthType = parseNum(1)
val length = parseNum(if (lengthType == 0) 15 else 11)
val subPacketsStart = ptr
val subPackets = mutableListOf<Packet>()
fun parseNext(): Boolean = when (lengthType) {
0 -> ptr - subPacketsStart < length
1 -> subPackets.size < length
else -> error("unexpected length type: $lengthType")
}
while (parseNext()) {
subPackets.add(parsePacket())
}
when (lengthType) {
0 -> check(ptr - subPacketsStart == length)
1 -> check(subPackets.size == length)
}
return subPackets
}
private fun parseLiteralValue(): Long {
var value = 0L
do {
val last = parseNum(1) == 0
value = (value shl 4) + parseNum(4)
} while (!last)
return value
}
private fun parseNum(len: Int): Int {
return string.substring(ptr, ptr + len).toInt(2).also {
ptr += len
}
}
override fun close() {
while (ptr < string.length) {
check(string[ptr++] == '0')
}
}
}
private fun String.toBinaryString() =
map {
it.toString()
.toInt(16)
.toString(2)
.padStart(4, '0')
}.joinToString("") { it }
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day16/$s")).readLines().first().toBinaryString()
}
private typealias Input = String | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day16/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day16.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String D2FE28\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day11/Solution.kt | package day11
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun iterate(octopuses: Input): Int {
var flashes = 0
val queue = mutableListOf<Pair<Int, Int>>()
val flashed = Array(octopuses.size) { BooleanArray(octopuses[it].size) }
for ((i, row) in octopuses.withIndex()) {
for (j in row.indices) {
row[j]++
if (row[j] > 9) {
flashed[i][j] = true
queue.add(i to j)
}
}
}
var head = 0
while (head < queue.size) {
val (i, j) = queue[head++]
octopuses[i][j] = 0
flashes++
for (di in -1..1) {
for (dj in -1..1) {
val ii = i + di
val jj = j + dj
if (ii !in octopuses.indices || jj !in octopuses[ii].indices) continue
if (!flashed[ii][jj]) {
octopuses[ii][jj]++
if (octopuses[ii][jj] > 9) {
flashed[ii][jj] = true
queue.add(ii to jj)
}
}
}
}
}
return flashes
}
fun part1(octopuses: Input): Int {
var flashes = 0
repeat(100) {
flashes += iterate(octopuses)
}
return flashes
}
fun part2(octopuses: Input): Int {
repeat(100500) {
val flashes = iterate(octopuses)
if (flashes == 100) return it + 1
}
error("POLUNDRA")
}
check(part1(readInput("test-input.txt")) == 1656)
check(part2(readInput("test-input.txt")) == 195)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day11/$s"))
.readLines()
.map {
it
.map { it.code - '0'.code }
.toMutableList()
}
}
private typealias Input = List<MutableList<Int>> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day11/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day11.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day10/Solution.kt | package day10
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
val matching = mapOf(
'(' to ')',
'[' to ']',
'{' to '}',
'<' to '>',
)
fun part1(lines: Input): Int {
val points = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137,
)
return lines.sumOf {
val stack = mutableListOf<Char>()
for (elem in it) {
if (matching.containsKey(elem)) {
stack.add(elem)
} else {
if (matching[stack.last()] != elem) {
return@sumOf points[elem]!!
} else {
stack.removeAt(stack.lastIndex)
}
}
}
0
}
}
fun part2(lines: Input): Long {
val points = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
return lines.map { line ->
val stack = mutableListOf<Char>()
for (elem in line) {
if (matching.containsKey(elem)) {
stack.add(elem)
} else {
if (matching[stack.last()] != elem) {
return@map 0
} else {
stack.removeAt(stack.lastIndex)
}
}
}
stack.reversed().map { matching[it] }.fold(0L) { acc, c -> acc * 5 + points[c]!! }
}.filter { it != 0L }.sorted().let {
it[it.size / 2]
}
}
check(part1(readInput("test-input.txt")) == 26397)
check(part2(readInput("test-input.txt")) == 288957L)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day10/$s")).readLines()
}
private typealias Input = List<String> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day10/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day10.SolutionKt {\n public static final void main();\n Code:\n 0: iconst_4\n 1: anewarray #8 // class kotlin/Pair\n 4: astor... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day17/Solution.kt | package day17
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
fun part1(input: Input): Int {
val (xRange, yRange) = input.toList().map { it.first..it.second }
require(xRange.first > 0 && xRange.last >= xRange.first)
require(yRange.last < 0 && yRange.last >= yRange.first)
// assume we can find X such that X * (X + 1) / 2 in xRange and X <= Y * 2 + 1
// works for my test case, YMMW
val y = yRange.first.absoluteValue - 1
return y * (y + 1) / 2
}
fun part2(input: Input): Int {
val (xRange, yRange) = input.toList().map { it.first..it.second }
require(xRange.first > 0 && xRange.last >= xRange.first)
require(yRange.last < 0 && yRange.last >= yRange.first)
var answer = 0
for (xv in 1..xRange.last) {
for (yv in yRange.first..yRange.first.absoluteValue) {
var (cx, cy) = 0 to 0
var (cxv, cyv) = xv to yv
while (true) {
cx += cxv.also { cxv -= cxv.sign }
cy += cyv--
if (cx in xRange && cy in yRange) {
answer++
break
}
if (cx > xRange.last || cy < yRange.first) break
}
}
}
return answer
}
// illustrate(7, 2, readInput("test-input.txt"))
// illustrate(6, 3, readInput("test-input.txt"))
// illustrate(9, 0, readInput("test-input.txt"))
// illustrate(17, -4, readInput("test-input.txt"))
// illustrate(6, 9, readInput("test-input.txt"))
// illustrate(6, 10, readInput("test-input.txt"))
check(part1(readInput("test-input.txt")) == 45)
check(part2(readInput("test-input.txt")) == 112)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun illustrate(xv: Int, yv: Int, target: Input) {
val (txRange, tyRange) = target
val tx = txRange.first..txRange.second
val ty = tyRange.first..tyRange.second
var (cx, cy) = 0 to 0
var (cxv, cyv) = xv to yv
val visited = mutableListOf<Pair<Int, Int>>()
while (cx <= tx.last && cy >= ty.last) {
cx += cxv.also { cxv -= cxv.sign }
cy += cyv--
visited.add(cx to cy)
}
val minX = minOf(minOf(0, tx.first), visited.minOf { it.first })
val maxX = maxOf(maxOf(0, tx.last), visited.maxOf { it.first })
val minY = minOf(minOf(0, ty.first), visited.minOf { it.second })
val maxY = maxOf(maxOf(0, ty.last), visited.maxOf { it.second })
val output = Array(maxY - minY + 1) {
CharArray(maxX - minX + 1) { '.' }
}
for (x in tx) {
for (y in ty) {
output[maxY - y][x - minX] = 'T'
}
}
output[maxY - 0][0 - minX] = 'S'
for ((x, y) in visited) {
output[maxY - y][x - minX] = '#'
}
println("($xv, $yv) -> $target")
println(output.joinToString("\n") { String(it) })
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day17/$s")).readLine()!!.let { line ->
val (xRange, yRange) = line.substring("target area: ".length).split(", ")
val (xMin, xMax) = xRange.substring("x=".length).split("..").map { it.toInt() }
val (yMin, yMax) = yRange.substring("y=".length).split("..").map { it.toInt() }
Pair(xMin to xMax, yMin to yMax)
}
}
private typealias Input = Pair<Pair<Int, Int>, Pair<Int, Int>> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day17/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day17.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day21/Solution.kt | package day21
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(input: Input): Int {
var rolled = 0
val score = intArrayOf(0, 0)
val position = input.map { it - 1 }.toIntArray()
var current = 0
while (score.all { it < 1000 }) {
var move = 0
repeat(3) {
move += (rolled++) % 100 + 1
}
position[current] = (position[current] + move) % 10
score[current] += position[current] + 1
current = 1 - current
}
return rolled * score.find { it < 1000 }!!
}
fun part2(input: Input): Long {
val mem = Array(10) {
Array(10) {
Array(21) {
arrayOfNulls<Pair<Long, Long>?>(21)
}
}
}
fun rec(
firstPosition: Int,
secondPosition: Int,
firstScore: Int,
secondScore: Int,
): Pair<Long, Long> {
check(firstScore < 21)
if (secondScore >= 21) return Pair(0L, 1L)
mem[firstPosition][secondPosition][firstScore][secondScore]?.let { return it }
var firstWins = 0L
var secondWins = 0L
for (i in 1..3) {
for (j in 1..3) {
for (k in 1..3) {
val newPosition = (firstPosition + (i + j + k)) % 10
val (second, first) = rec(
firstPosition = secondPosition,
secondPosition = newPosition,
firstScore = secondScore,
secondScore = firstScore + newPosition + 1
)
firstWins += first
secondWins += second
}
}
}
return Pair(firstWins, secondWins).also {
mem[firstPosition][secondPosition][firstScore][secondScore] = it
}
}
val (first, second) = rec(
firstPosition = input[0] - 1,
secondPosition = input[1] - 1,
firstScore = 0,
secondScore = 0
)
return maxOf(first, second)
}
check(part1(readInput("test-input.txt")) == 739785)
check(part2(readInput("test-input.txt")) == 444356092776315L)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day21/$s")).readLines().mapIndexed { index, line ->
check(line.startsWith("Player ${index + 1} starting position: "))
line.substring("Player ${index + 1} starting position: ".length).toInt()
}
}
private typealias Input = List<Int> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day21/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day21.SolutionKt {\n public static final void main();\n Code:\n 0: ldc #8 // String test-input.txt\n 2: invokestatic #12 ... |
vadimsemenov__advent-of-code__8f31d39/2021/src/day19/Solution.kt | package day19
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.math.absoluteValue
import kotlin.system.measureTimeMillis
fun main() {
val rotations = createRotations()
fun fullMap(input: Input): MutableList<Pair<Point, List<Point>>> {
val fixed = mutableListOf(Point(0, 0, 0) to input.first())
val remaining = input.withIndex().drop(1).toMutableList()
val tried = Array(input.size) { HashSet<Int>() }
while (remaining.isNotEmpty()) {
remaining.removeAll { (index, beacons) ->
for ((scannerIndex, scannerAndBeacons) in fixed.withIndex()) {
if (scannerIndex in tried[index]) continue
tried[index] += scannerIndex
for (rotation in rotations) {
val rotated = beacons.map { it.rotate(rotation) }
val (shift, frequency) = buildMap {
for (a in rotated) {
for (b in scannerAndBeacons.second) {
this.compute(b - a) { _, prev ->
1 + (prev ?: 0)
}
}
}
}.maxByOrNull { it.value }!!
if (frequency >= 12) {
fixed += shift to rotated.map { it + shift }
return@removeAll true
}
}
}
return@removeAll false
}
}
return fixed
}
fun part1(input: Input): Int {
return fullMap(input).map { it.second }.flatten().toSet().size
}
fun part2(input: Input): Int {
val scanners = fullMap(input).map { it.first }
return scanners.maxOf { a ->
scanners.maxOf { b ->
(a - b).magnitude()
}
}
}
check(part1(readInput("test-input.txt")) == 79)
check(part2(readInput("test-input.txt")) == 3621)
val millis = measureTimeMillis {
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
System.err.println("Done in $millis ms.")
}
private fun createRotations(): List<List<List<Int>>> {
fun createMatrices(sin: Int, cos: Int): List<List<List<Int>>> = listOf(
listOf( // Rx
listOf(1, 0, 0),
listOf(0, cos, sin),
listOf(0, -sin, cos),
),
listOf( // Ry
listOf(cos, 0, -sin),
listOf( 0, 1, 0),
listOf(sin, 0, cos),
),
listOf( // Rz
listOf( cos, sin, 0),
listOf(-sin, cos, 0),
listOf( 0, 0, 1),
),
)
return listOf(
1 to 0,
0 to 1,
-1 to 0,
0 to -1,
).flatMap { (cos, sin) ->
createMatrices(sin, cos)
}.let {
buildSet {
for (a in it) for (b in it) add(a * b)
check(size == 24)
}.toList()
}
}
private operator fun List<List<Int>>.times(other: List<List<Int>>): List<List<Int>> {
require(this.first().size == other.size)
return List(this.size) { i ->
List(other.first().size) { j ->
other.indices.sumOf { k ->
this[i][k] * other[k][j]
}
}
}
}
private data class Point(val x: Int, val y: Int, val z: Int)
private operator fun Point.plus(other: Point) =
Point(x + other.x, y + other.y, z + other.z)
private operator fun Point.minus(other: Point) =
Point(x - other.x, y - other.y, z - other.z)
private fun Point.rotate(rotation: List<List<Int>>): Point {
val (x, y, z) = (listOf(listOf(x, y, z)) * rotation).first()
return Point(x, y, z)
}
private fun Point.magnitude(): Int = x.absoluteValue + y.absoluteValue + z.absoluteValue
private fun readInput(s: String): Input {
return buildList<MutableList<Point>> {
Files.newBufferedReader(Paths.get("src/day19/$s")).forEachLine { line ->
if (line == "--- scanner $size ---") {
add(mutableListOf())
} else if (line.isNotBlank()) {
val (x, y, z) = line.split(",").map { it.toInt() }
last().add(Point(x, y, z))
}
}
}
}
private typealias Input = List<List<Point>> | [
{
"class_path": "vadimsemenov__advent-of-code__8f31d39/day19/SolutionKt.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class day19.SolutionKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method createRotations:()Ljava/util/List;\n 3: a... |
amedee__adventofcode__02e8e07/src/main/kotlin/be/amedee/adventofcode/aoc2015/day01/Day01.kt | package be.amedee.adventofcode.aoc2015.day01
import java.io.BufferedReader
import java.io.InputStreamReader
/**
* Single move to the next floor, up or down.
*
* @return do we go up or down
*/
fun move(): (String) -> Int =
{
when (it) {
"(" -> 1
")" -> -1
else -> 0
}
}
/**
* The entire list of elevator instructions.
*
* @return at which floor Santa ends up
*/
fun followInstructions(): (String) -> Int =
{ instructionList ->
instructionList
.toList()
.sumOf { move()(it.toString()) }
}
/**
* Find the position of the first character that causes Santa to enter the
* basement (floor -1). The first character in the instructions has
* position 1, the second character has position 2, and so on.
*/
fun findBasementPosition(instructions: String): Int {
var floor = 0
return instructions.indexOfFirst {
when (it) {
'(' -> floor++
')' -> floor--
}
floor == -1
} + 1
}
class Day01 {
fun readElevatorInstructionsFromFile(fileName: String): String {
val packageName = javaClass.`package`.name.replace(".", "/")
val filePath = "/$packageName/$fileName"
val inputStream = javaClass.getResourceAsStream(filePath)
return BufferedReader(InputStreamReader(inputStream!!)).use { it.readText().trim() }
}
}
/**
* Santa is trying to deliver presents in a large apartment building,
* but he can't find the right floor - the directions he got are a little confusing.
*/
fun main() {
val inputFile = "input"
val puzzleInput = Day01().readElevatorInstructionsFromFile(inputFile)
val endFloor = followInstructions()(puzzleInput)
println("Santa ends up on floor $endFloor.")
val basementPosition = findBasementPosition(puzzleInput)
when (basementPosition) {
0 -> println("Santa never enters the basement.")
else -> println("Santa enters the basement at character position ${"%,d".format(basementPosition)}.")
}
}
| [
{
"class_path": "amedee__adventofcode__02e8e07/be/amedee/adventofcode/aoc2015/day01/Day01.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class be.amedee.adventofcode.aoc2015.day01.Day01 {\n public be.amedee.adventofcode.aoc2015.day01.Day01();\n Code:\n 0: aload_0\n 1: invokespeci... |
amedee__adventofcode__02e8e07/src/main/kotlin/be/amedee/adventofcode/aoc2015/day02/Day02.kt | package be.amedee.adventofcode.aoc2015.day02
import java.io.BufferedReader
import java.io.InputStreamReader
fun getSurfaceArea(
length: Int,
width: Int,
height: Int,
) = 2 * ((length * width) + (width * height) + (height * length))
fun getSlack(
length: Int,
width: Int,
height: Int,
) = minOf(length * width, width * height, height * length)
fun calculateWrappingPaperOrder(presentDimensions: List<Triple<Int, Int, Int>>): Int {
var totalSquareFeet = 0
presentDimensions.forEach { (l, w, h) ->
val surfaceArea = getSurfaceArea(l, w, h)
val slack = getSlack(l, w, h)
totalSquareFeet += surfaceArea + slack
}
return totalSquareFeet
}
class Day02 {
fun readPresentDimensionsFromFile(fileName: String): List<Triple<Int, Int, Int>> {
val packageName = javaClass.`package`.name.replace(".", "/")
val filePath = "/$packageName/$fileName"
val inputStream = javaClass.getResourceAsStream(filePath)
val presentDimensions = mutableListOf<Triple<Int, Int, Int>>()
if (inputStream != null) {
BufferedReader(InputStreamReader(inputStream)).useLines { lines ->
lines.forEach { line ->
val dimensions = line.split("x").map { it.toInt() }
if (dimensions.size == 3) {
presentDimensions.add(Triple(dimensions[0], dimensions[1], dimensions[2]))
}
}
}
}
return presentDimensions
}
}
fun main() {
val inputFile = "input"
val presentDimensions = Day02().readPresentDimensionsFromFile(inputFile)
val totalSquareFeet = calculateWrappingPaperOrder(presentDimensions)
println("Elves should order ${"%,d".format(totalSquareFeet)} square feet of wrapping paper.")
}
| [
{
"class_path": "amedee__adventofcode__02e8e07/be/amedee/adventofcode/aoc2015/day02/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class be.amedee.adventofcode.aoc2015.day02.Day02Kt {\n public static final int getSurfaceArea(int, int, int);\n Code:\n 0: iconst_2\n 1: iloa... |
SeanShubin__factor-analysis__a0ae7f3/ratio/src/main/kotlin/com/seanshubin/factor/analysis/ratio/Ratio.kt | package com.seanshubin.factor.analysis.ratio
data class Ratio(val numerator: Int, val denominator: Int) : Comparable<Ratio> {
init {
require(denominator != 0){
"Denominator must not be zero in $numerator/$denominator"
}
}
operator fun plus(that: Ratio): Ratio {
val lcm = leastCommonMultiple(denominator, that.denominator)
return Ratio(numerator * lcm / denominator + that.numerator * lcm / that.denominator, lcm).simplify()
}
operator fun minus(that: Ratio): Ratio = (this + -that).simplify()
operator fun times(that: Ratio): Ratio = Ratio(numerator * that.numerator, denominator * that.denominator).simplify()
operator fun times(that: Int): Ratio = this * Ratio(that,1)
operator fun div(that: Ratio): Ratio = (this * that.recriprocal()).simplify()
operator fun unaryMinus(): Ratio = Ratio(-numerator, denominator).simplify()
fun recriprocal(): Ratio = Ratio(denominator, numerator).simplify()
fun withDenominator(newDenominator: Int): Ratio = Ratio(numerator * newDenominator / denominator, newDenominator)
override fun compareTo(that: Ratio): Int {
val lcm = leastCommonMultiple(denominator, that.denominator)
return (numerator * lcm / denominator).compareTo(that.numerator * lcm / that.denominator)
}
override fun toString(): String = if(denominator == 1) "$numerator" else "$numerator/$denominator"
fun simplify(): Ratio = simplifyFactor().simplifySign()
private fun simplifySign(): Ratio =
if (denominator < 0) Ratio(-numerator, -denominator)
else this
private fun simplifyFactor(): Ratio {
val gcf = greatestCommonFactor(numerator, denominator)
return Ratio(numerator / gcf, denominator / gcf)
}
companion object {
val ZERO = Ratio(0,1)
val ONE = Ratio(1,1)
fun greatestCommonFactor(a: Int, b: Int): Int =
if (b == 0) a
else greatestCommonFactor(b, a % b)
fun leastCommonMultiple(a: Int, b: Int): Int =
if (a == 0 && b == 0) 0
else a * b / greatestCommonFactor(a, b)
val regex = Regex("""(-?\d+)/(-?\d+)""")
fun parse(s: String): Ratio {
val matchResult = regex.matchEntire(s)
if (matchResult == null) throw RuntimeException("Value '$s' could did not match expression $regex")
val numerator = matchResult.groupValues[1].toInt()
val denominator = matchResult.groupValues[2].toInt()
return Ratio(numerator, denominator).simplify()
}
fun Int.toRatio():Ratio = Ratio(this, 1)
fun List<Ratio>.toRatioArray():Array<Ratio> = toTypedArray()
operator fun Int.div(x:Ratio):Ratio = ONE / x
fun List<Ratio>.sum():Ratio {
var sum: Ratio = ZERO
for (element in this) {
sum += element
}
return sum
}
}
val toDouble: Double get() = numerator.toDouble() / denominator.toDouble()
}
| [
{
"class_path": "SeanShubin__factor-analysis__a0ae7f3/com/seanshubin/factor/analysis/ratio/Ratio.class",
"javap": "Compiled from \"Ratio.kt\"\npublic final class com.seanshubin.factor.analysis.ratio.Ratio implements java.lang.Comparable<com.seanshubin.factor.analysis.ratio.Ratio> {\n public static final co... |
joseluisgs__Kotlin-NumericMatrixProcessor__b0d49e4/src/main/kotlin/processor/Matrix.kt | package processor
import kotlin.system.exitProcess
fun main() {
doMenuActions()
}
/**
* Menu and Actions
* @param data List of data
* @param index Index of data
*/
private fun doMenuActions() {
do {
val menu = readMenuOption()
when (menu) {
0 -> exit()
1 -> addMatrices()
2 -> multiplyByConstant()
3 -> multiplyMatrices()
4 -> transposeMatrix()
5 -> determinantMatrix()
6 -> inverseMatrix()
}
} while (menu != 0)
}
/**
* Inverse of a Matrix
*/
fun inverseMatrix() {
val m = readMatrix("")
inverseMatrix(m)
}
/**
* Calculate the inverse of a Matrix
*/
fun inverseMatrix(mat: Array<Array<Double>>) {
/*
If det(A) != 0
A-1 = adj(A)/det(A)
Else
"Inverse doesn't exist"
*/
val det = determinantMatrix(mat, mat.size, mat.size)
if (det != 0.0) {
val adj = Array(mat.size) { Array(mat.size) { 0.0 } }
adjoint(mat, adj, mat.size)
// Find Inverse using formula "inverse(A) = adj(A)/det(A)"
// Find Inverse using formula "inverse(A) = adj(A)/det(A)"
val inverse = Array(mat.size) { Array(mat.size) { 0.0 } }
for (i in mat.indices)
for (j in mat.indices)
inverse[i][j] = adj[i][j] / det
printMatrix(inverse)
} else {
println("This matrix doesn't have an inverse.")
}
}
/**
* Determinat of a Matrix
*/
fun determinantMatrix() {
val m = readMatrix("")
val determinant = determinantMatrix(m, m.size, m.size)
println("The result is:")
println(determinant)
}
/**
* Function to get cofactor (sub matrix) of mat(p)(q) in temp[][]. n is current dimension of mat[][]
* @param mat Matrix
* @param temp Matrix
* @param p Row
* @param q Column
* @param n Size of matrix
*/
fun getCofactor(
mat: Array<Array<Double>>, temp: Array<Array<Double>>,
p: Int, q: Int, n: Int
) {
var i = 0
var j = 0
// Looping for each element of
// the matrix
for (row in 0 until n) {
for (col in 0 until n) {
// Copying into temporary matrix
// only those element which are
// not in given row and column
if (row != p && col != q) {
temp[i][j++] = mat[row][col]
// Row is filled, so increase
// row index and reset col
// index
if (j == n - 1) {
j = 0
i++
}
}
}
}
}
/**
* Calculate Determinant of a Matrix Recursive
* @param mat Matrix
* @param n Size of actual Matrix
* @param Size of Matrix Original Matrix
* @return Determinant of Matrix
*/
fun determinantMatrix(mat: Array<Array<Double>>, n: Int, Size: Int): Double {
var det = 0.0 // Initialize result
// Base case : if matrix contains single
// element
if (n == 1) return mat[0][0]
// To store cofactors
val temp = Array(Size) { Array(Size) { 0.0 } }
// To store sign multiplier
var sign = 1
// Iterate for each element of first row
for (f in 0 until n) {
// Getting Cofactor of mat[0][f]
getCofactor(mat, temp, 0, f, n)
det += (sign * mat[0][f] * determinantMatrix(temp, n - 1, Size))
// terms are to be added with
// alternate sign
sign = -sign
}
return det
}
/**
* Get adjoint of A(N)(N) in adj(N)(N).
*/
fun adjoint(mat: Array<Array<Double>>, adj: Array<Array<Double>>, Size: Int) {
if (Size == 1) {
adj[0][0] = 1.0
return
}
// temp is used to store cofactors of A[][]
var sign = 1
val temp = Array(Size) { Array(Size) { 0.0 } }
for (i in 0 until Size) {
for (j in 0 until Size) {
// Get cofactor of A[i][j]
getCofactor(mat, temp, i, j, Size)
// sign of adj[j][i] positive if sum of row
// and column indexes is even.
sign = if ((i + j) % 2 == 0) 1 else -1
// Interchanging rows and columns to get the
// transpose of the cofactor matrix
adj[j][i] = sign * determinantMatrix(temp, Size - 1, Size)
}
}
}
/**
* Menu Options Transpose Matrix
*/
fun transposeMatrix() {
var menu = 0
do {
menu = readMenuTranposeOption()
when (menu) {
1 -> {
transposeMain()
menu = 0
}
2 -> {
transposeSide()
menu = 0
}
3 -> {
transposeVertical()
menu = 0
}
4 -> {
transposeHorizontal()
menu = 0
}
}
} while (menu != 0)
doMenuActions()
}
/**
* Trasnpose Horizontal Matrix
*/
fun transposeHorizontal() {
val m = readMatrix("")
transposeHorizontal(m)
}
/**
* Trasnpose Horizontal Matrix
* @param m Matrix
*/
fun transposeHorizontal(mat: Array<Array<Double>>) {
val mT = Array(mat[0].size) { Array(mat.size) { 0.0 } }
val n = mat.size
for (i in 0 until n) {
for (j in 0 until n) {
mT[(n - 1) - i][j] = mat[i][j]
}
}
println("Transpose Vertical")
printMatrix(mT)
}
/**
* Transpose Vertical Matrix
*/
fun transposeVertical() {
val m = readMatrix("")
transposeVertical(m)
}
/**
* Tranpose Vertical Matrix
* @param m Matrix
*/
fun transposeVertical(mat: Array<Array<Double>>) {
val mT = Array(mat[0].size) { Array(mat.size) { 0.0 } }
val n = mat.size
for (i in 0 until n) {
for (j in 0 until n) {
mT[i][(n - 1) - j] = mat[i][j]
}
}
println("Transpose Vertical")
printMatrix(mT)
}
/**
* Tranpose Side Diagonal
*/
fun transposeSide() {
val m = readMatrix("")
transposeSide(m)
}
/**
* Tranpose Side Diagonal
* @param m Matrix
*/
fun transposeSide(mat: Array<Array<Double>>) {
val mT = Array(mat[0].size) { Array(mat.size) { 0.0 } }
val n = mat.size
for (i in mat.indices) {
for (j in 0 until mat[0].size) {
mT[(n - 1) - j][(n - 1) - i] = mat[i][j]
}
}
printMatrix(mT)
}
/**
* Transpose Matrix Main Diagonal
*/
fun transposeMain() {
val m = readMatrix("")
transposeMain(m)
}
/**
* Transpose Matrix Side Diagonal
*
*/
fun transposeMain(mat: Array<Array<Double>>) {
val mT = Array(mat[0].size) { Array(mat.size) { 0.0 } }
for (i in mat.indices) {
for (j in 0 until mat[0].size) {
mT[j][i] = mat[i][j]
}
}
printMatrix(mT)
}
/**
* Reads Menu Transpose Matrix
* @return Menu option
*/
fun readMenuTranposeOption(): Int {
var option: Int
do {
println("1. Main diagonal")
println("2. Side diagonal")
println("3. Vertical line")
println("4. Horizontal line")
print("Your choice: ")
option = readLine()!!.toIntOrNull() ?: -1
if (option !in 1..4) {
println("Incorrect option! Try again.")
}
} while (option !in 1..4)
return option
}
/**
* Multiply Matrices
*/
fun multiplyMatrices() {
val m1 = readMatrix("first")
val m2 = readMatrix("second")
multiplayMatrices(m1, m2)
}
/**
* Multiply Matrices
* @param m1 First Matrix
* @param m2 Second Matrix
*/
fun multiplayMatrices(m1: Array<Array<Double>>, m2: Array<Array<Double>>) {
// m1. columns == m2.rows
if (m1[0].size != m2.size) {
println("The operation cannot be performed.")
} else {
//
val m3 = Array(m1.size) { Array(m2[0].size) { 0.0 } }
for (i in m1.indices) {
for (j in 0 until m2[0].size) {
for (k in m2.indices) {
m3[i][j] += m1[i][k] * m2[k][j]
}
}
}
// imprimimos la matriz resultado
printMatrix(m3)
}
}
/**
* Multiply matrix by constant
*/
fun multiplyByConstant() {
val m = readMatrix("")
val c = readConstant()
matrixByNumber(m, c)
}
/**
* Reads the constant
*/
fun readConstant(): Double {
var c: Double
do {
print("Enter constant: ")
c = readLine()!!.toDoubleOrNull() ?: Double.MAX_VALUE
} while (c == Double.MAX_VALUE)
return c
}
/**
* Add Matrices
*/
fun addMatrices() {
val m1 = readMatrix("first")
val m2 = readMatrix("second")
addMatrices(m1, m2)
}
/**
* Reads Menu
* @return Menu option
*/
fun readMenuOption(): Int {
var option: Int
do {
println("1. Add matrices")
println("2. Multiply matrix by a constant")
println("3. Multiply matrices")
println("4. Transpose matrix")
println("5. Calculate a determinant")
println("6. Inverse matrix")
println("0. Exit")
print("Your choice: ")
option = readLine()!!.toIntOrNull() ?: -1
if (option !in 0..6) {
println("Incorrect option! Try again.")
}
} while (option !in 0..6)
return option
}
/**
* Exits the program.
*/
fun exit() {
exitProcess(0)
}
/**
* Multiply matrix by number
* @param m Matrix
* @param c Number
*/
fun matrixByNumber(matrix: Array<Array<Double>>, c: Double) {
val res = Array(matrix.size) { Array(matrix[0].size) { 0.0 } }
for (i in matrix.indices) {
for (j in 0 until matrix[i].size) {
res[i][j] = c * matrix[i][j]
}
}
printMatrix(res)
}
/**
* Print a Matrix
* @param m Matrix
*/
fun printMatrix(m: Array<Array<Double>>) {
// println()
println("The result is: ")
for (i in m.indices) {
for (j in m[i].indices) {
print("${m[i][j]} ")
}
println()
}
}
/**
* Add two matrices
* @param m1 first matrix
* @param m2 second matrix
*/
fun addMatrices(m1: Array<Array<Double>>, m2: Array<Array<Double>>) {
if (m1.size != m2.size || m1[0].size != m2[0].size) {
println("The operation cannot be performed.")
} else {
val m3 = Array(m1.size) { Array(m1[0].size) { 0.0 } }
for (i in m1.indices) {
for (j in m1[i].indices) {
m3[i][j] = m1[i][j] + m2[i][j]
}
}
// imprimimos la matriz resultado
printMatrix(m3)
}
}
/**
* Read a matrix from the console
* @return a matrix
*/
fun readMatrix(type: String): Array<Array<Double>> {
print("Enter size of $type matrix: ")
val (f, c) = readLine()!!.split(" ").map { it.toInt() }
val matrix = Array(f) { Array(c) { 0.0 } }
println("Enter $type matrix: ")
for (i in 0 until f) {
val line = readLine()!!.split(" ").map { it.toDouble() }
for (j in 0 until c) {
matrix[i][j] = line[j]
}
}
return matrix
}
| [
{
"class_path": "joseluisgs__Kotlin-NumericMatrixProcessor__b0d49e4/processor/MatrixKt.class",
"javap": "Compiled from \"Matrix.kt\"\npublic final class processor.MatrixKt {\n public static final void main();\n Code:\n 0: invokestatic #9 // Method doMenuActions:()V\n 3: ret... |
chengw315__daily-study__501b881/letcode/src/main/java/daily/LeetCode154.kt | package daily
fun main() {
val solution = Solution154()
//1
val array = solution.minArray(intArrayOf(3, 4, 5, 1, 2))
//1
val array1 = solution.minArray(intArrayOf(1, 2, 3, 4, 5))
//5
val array2 = solution.minArray(intArrayOf(5, 15, 5, 5, 5))
//4
val array4 = solution.minArray(intArrayOf(5, 15, 4, 5, 5))
//1
val array3 = solution.minArray(intArrayOf(5, 5, 5, 1, 2))
}
class Solution154 {
fun minArray(numbers: IntArray): Int {
//未旋转
if (numbers[0] < numbers[numbers.size-1]) return numbers[0]
return lbs(numbers,0,numbers.size-1)
}
/**
* 向左二分查找 (left,right]
*/
fun lbs(numbers: IntArray,left:Int,right:Int):Int {
if(left>=right-1) return numbers[right]
val mid = (left+right)/2
return if(numbers[right] > numbers[mid]) lbs(numbers,left,mid)
else if(numbers[right] < numbers[mid]) lbs(numbers,mid,right)
else Math.min(lbs(numbers, left, mid),lbs(numbers, mid, right))
}
} | [
{
"class_path": "chengw315__daily-study__501b881/daily/LeetCode154Kt.class",
"javap": "Compiled from \"LeetCode154.kt\"\npublic final class daily.LeetCode154Kt {\n public static final void main();\n Code:\n 0: new #8 // class daily/Solution154\n 3: dup\n 4: i... |
chengw315__daily-study__501b881/letcode/src/main/java/daily/LeetCodeLCP13.kt | package daily
import java.util.*
fun main() {
//16
val i = SolutionLCP13().minimalSteps(arrayOf("S#O", "M..", "M.T"));
//-1
val i1 = SolutionLCP13().minimalSteps(arrayOf("S#O", "M.#", "M.T"));
//17
val i2 = SolutionLCP13().minimalSteps(arrayOf("S#O", "M.T", "M.."));
}
class SolutionLCP13 {
data class Point(val x:Int,val y:Int)
fun minimalSteps(maze: Array<String>): Int {
var xS = 0
var yS = 0
var xT = 0
var yT = 0
var numofO = 0
var numofM = 0
val hashMapO = HashMap<Point, Int>()
val hashMapM = HashMap<Point, Int>()
for (i in maze.indices) {
for (j in maze[i].indices) {
when(maze[i][j]) {
'O'-> hashMapO.put(Point(i,j),numofO++)
'M'-> hashMapM.put(Point(i,j),numofM++)
'S'-> {
xS = i
yS = j
}
'T'-> {
xT = i
yT = j
}
}
}
}
//result = 所有最小(M->O)之和 + 最小(S->O->M0 + M1->T - M1->O)
//需要统计的只有:
// 1. S->所有O的最短距离;————>BFS
val minS2Os = IntArray(numofO){Int.MAX_VALUE}
// 2. 所有O->最近M的最短距离;————>BFS
val minO2Ms = IntArray(numofO){Int.MAX_VALUE}
val minPointO2Ms = Array<Point>(numofO) { Point(0,0) }
// 2. 所有M->最近O的最短距离;————>BFS
val minM2Os = IntArray(numofM){Int.MAX_VALUE}
// 3. 所有M->T的最短距离;————BFS (2.和3.可以在同一轮BFS解决)
val minM2Ts = IntArray(numofM){Int.MAX_VALUE}
//BFS(S) S->所有O的最短距离
val queue = LinkedList<Point>()
var deep = 0
queue.offer(Point(xS,yS))
var colors = Array(maze.size) {BooleanArray(maze[0].length) {false} }
while (!queue.isEmpty()) {
val size = queue.size
for (i in 0 until size) {
val pop = queue.poll()
if(colors[pop.x][pop.y]) continue
colors[pop.x][pop.y] = true
if(maze[pop.x][pop.y] == '#') continue
if(maze[pop.x][pop.y] == 'O') {
minS2Os[hashMapO[pop]!!] = Math.min(deep, minS2Os[hashMapO[pop]!!])
}
if(pop.x > 0) queue.offer(Point(pop.x - 1,pop.y))
if(pop.x < maze.size - 1) queue.offer(Point(pop.x + 1,pop.y))
if(pop.y > 0) queue.offer(Point(pop.x,pop.y - 1))
if(pop.y < maze[pop.x].length - 1) queue.offer(Point(pop.x,pop.y + 1))
deep++
}
}
// 2. 所有O->最近M的最短距离;————>BFS
loop@ for (O in hashMapO.keys) {
queue.clear()
deep = 0
queue.offer(O)
colors = Array(maze.size) {BooleanArray(maze[0].length) {false} }
while (!queue.isEmpty()) {
val size = queue.size
for (i in 0 until size) {
val pop = queue.pop()
if(colors[pop.x][pop.y]) continue
colors[pop.x][pop.y] = true
if(maze[pop.x][pop.y] == '#') continue
if(maze[pop.x][pop.y] == 'M') {
minO2Ms[hashMapO[O]!!] = deep
minPointO2Ms[hashMapO[O]!!] = pop
continue@loop
}
if(pop.x > 0) queue.offer(Point(pop.x - 1,pop.y))
if(pop.x < maze.size - 1) queue.offer(Point(pop.x + 1,pop.y))
if(pop.y > 0) queue.offer(Point(pop.x,pop.y - 1))
if(pop.y < maze[pop.x].length - 1) queue.offer(Point(pop.x,pop.y + 1))
deep++
}
}
}
loop2@for (M in hashMapM.keys) {
queue.clear()
deep = 0
queue.offer(M)
colors = Array(maze.size) {BooleanArray(maze[0].length) {false} }
var findO = false
var findT = false
while (!queue.isEmpty()) {
val size = queue.size
for (i in 0 until size) {
val pop = queue.pop()
if(colors[pop.x][pop.y]) continue
colors[pop.x][pop.y] = true
if(maze[pop.x][pop.y] == '#') continue
if(!findO && maze[pop.x][pop.y] == 'O') {
minM2Os[hashMapM[M]!!] = deep
findO = true
}
if(!findT && maze[pop.x][pop.y] == 'T') {
minM2Ts[hashMapM[M]!!] = deep
findT = true
}
if(findO && findT) continue@loop2
if(pop.x > 0) queue.offer(Point(pop.x - 1,pop.y))
if(pop.x < maze.size - 1) queue.offer(Point(pop.x + 1,pop.y))
if(pop.y > 0) queue.offer(Point(pop.x,pop.y - 1))
if(pop.y < maze[pop.x].length - 1) queue.offer(Point(pop.x,pop.y + 1))
deep++
}
}
}
//最小(S->O->M0 + M1->T - M1->O)
var minS2O2MAndM2TSubM2O = Int.MAX_VALUE
for (i in minS2Os.indices) for (j in minO2Ms.indices) for (x in minM2Os.indices) for (y in minM2Ts.indices) minS2O2MAndM2TSubM2O = if(minPointO2Ms[j] == getKey(hashMapM,x)) minS2O2MAndM2TSubM2O else Math.min(minS2O2MAndM2TSubM2O, minS2Os[i] + minM2Os[j] - minM2Os[x] + minM2Ts[y])
return minM2Os.sum() + minS2O2MAndM2TSubM2O
}
private fun getKey(hashMapM: HashMap<Point, Int>, x: Int): Point {
for ((k,v) in hashMapM) {
if (v == x) return k
}
return Point(1,1)
}
}
| [
{
"class_path": "chengw315__daily-study__501b881/daily/LeetCodeLCP13Kt.class",
"javap": "Compiled from \"LeetCodeLCP13.kt\"\npublic final class daily.LeetCodeLCP13Kt {\n public static final void main();\n Code:\n 0: new #8 // class daily/SolutionLCP13\n 3: dup\n ... |
chengw315__daily-study__501b881/letcode/src/main/java/daily/LeetCode167.kt | package daily
fun main() {
val solution = Solution167()
//4,5
val twoSum4 = solution.twoSum(intArrayOf(1,2,3,4,4,8,9,75), 8)
//2,3
val twoSum3 = solution.twoSum(intArrayOf(5,25,75), 100)
//1,2
val twoSum = solution.twoSum(intArrayOf(2, 7, 11, 15), 9)
//1,5
val twoSum2 = solution.twoSum(intArrayOf(-995, -856, 456, 7856, 65454), 64459)
}
/**
* 两数之和——找到数组中两数之和等于目标的索引(索引以1开始),输出一个答案
*/
class Solution167 {
fun twoSum(numbers: IntArray, target: Int): IntArray {
var a = 0
var b = 0
for (i in numbers.indices) {
b = numbers.binarySearch(target - numbers[i])
if(b == i) b = numbers.binarySearch(target - numbers[i], b + 1)
if(b > 0) {
b++
a = i + 1
break
}
}
return intArrayOf(a,b)
}
} | [
{
"class_path": "chengw315__daily-study__501b881/daily/LeetCode167Kt.class",
"javap": "Compiled from \"LeetCode167.kt\"\npublic final class daily.LeetCode167Kt {\n public static final void main();\n Code:\n 0: new #8 // class daily/Solution167\n 3: dup\n 4: i... |
chengw315__daily-study__501b881/letcode/src/main/java/daily/LeetCode309.kt | package daily
fun main() {
val solution = Solution309()
//10
val i8 = solution.maxProfit(intArrayOf(8,6,4,3,3,2,3,5,8,3,8,2,6))
//13
val i7 = solution.maxProfit(intArrayOf(1,7,2,4,11))
//6
val i4 = solution.maxProfit(intArrayOf(3, 3, 5, 0, 0, 3, 1, 4))
//3
val i = solution.maxProfit(intArrayOf(1, 2, 3, 0, 2))
//3
val i2 = solution.maxProfit(intArrayOf(1, 4, 2))
//1
val i3 = solution.maxProfit(intArrayOf(2, 1, 2, 0, 1))
//6
val i5 = solution.maxProfit(intArrayOf(1, 4, 2, 7))
//10
val i6 = solution.maxProfit(intArrayOf(1, 2, 7, 4, 11))
}
/**
* 买卖股票的最佳时期(含冰冻期)
*/
class Solution309 {
fun maxProfit(prices: IntArray): Int {
if(prices.size < 2) {
return 0
}
if(prices.size == 2) {
return if(prices[1] - prices[0] > 0) prices[1] - prices[0] else 0
}
var result = 0
var hold = false
var freeze = false
var buy = 0
var i = 0
while (i < prices.size - 3) {
if(freeze) {
freeze = false
i++
continue
}
//空仓,观望:明天跌 或 明天涨但后天有抄底的机会
if(!hold && (downTomorrow(prices,i)
|| dltTomorrow(prices, i) <= dltTomorrow(prices,i+2) && dltTomorrow(prices,i) + dltTomorrow(prices,i+1) <= 0)) {
i++
continue
}
//空仓,买
if(!hold) {
buy = prices[i++]
hold = true
continue
}
//持仓,卖:明天跌而且后天没涨回来 或 明天涨但后天有抄底的机会
if(hold && (
downTomorrow(prices,i) && dltTomorrow(prices,i) + dltTomorrow(prices,i+1) <= 0
|| upTomorrow(prices,i) && dltTomorrow(prices, i) <= dltTomorrow(prices,i+2) && dltTomorrow(prices,i) + dltTomorrow(prices,i+1) <= 0
)) {
hold = false
freeze = true
result += prices[i++] - buy
continue
}
//观望
i++
}
//最后三天的决策
//持仓,只能卖一次,最高那天卖
if(hold) {
result += Math.max(prices[prices.size - 3], Math.max(prices[prices.size - 2],prices[prices.size - 1])) - buy
} else if(freeze) {
//空仓冰冻期 Math.max(第三天-第二天,0)
result += Math.max(dltTomorrow(prices,prices.size-2),0)
} else {
//空仓,Math.max(第二天-第一天,第三天 - 前两天中低的一天,0)
val best = prices[prices.size - 1] - Math.min(prices[prices.size - 2], prices[prices.size - 3])
result += Math.max(prices[prices.size-2] - prices[prices.size - 3],Math.max(best,0))
}
return result
}
private fun dltTomorrow(prices: IntArray, i: Int) = prices[i + 1] - prices[i]
private fun upTomorrow(prices: IntArray, i: Int): Boolean {
return prices[i + 1] > prices[i]
}
private fun downTomorrow(prices: IntArray, i: Int): Boolean {
return prices[i + 1] <= prices[i]
}
} | [
{
"class_path": "chengw315__daily-study__501b881/daily/LeetCode309Kt.class",
"javap": "Compiled from \"LeetCode309.kt\"\npublic final class daily.LeetCode309Kt {\n public static final void main();\n Code:\n 0: new #8 // class daily/Solution309\n 3: dup\n 4: i... |
chengw315__daily-study__501b881/letcode/src/main/java/daily/LeetCode10.kt | package letcode10
fun main() {
val solution = Solution10()
//false
val match9 = solution.isMatch("aaa", "aaaa")
//true
val match8 = solution.isMatch("ab", ".*..")
//true
val match7 = solution.isMatch("aab", "c*a*b*")
//false
val match = solution.isMatch("aa", "a")
//true
val match1 = solution.isMatch("aa", "a*")
//true
val match4 = solution.isMatch("aaa", ".*")
//true
val match5 = solution.isMatch("aba", ".*")
//true
val match2 = solution.isMatch("aab", "c*a*b")
//false
val match3 = solution.isMatch("mississippi", "mis*is*p*.")
//false
val match6 = solution.isMatch("a", ".*..a*")
}
/**
* 含元字符.和*(.前字符匹配1~n次;*前字符匹配0~n次)的正则表达式匹配
*/
class Solution10 {
fun isMatch(s: String, p: String): Boolean {
return isMatch(s, s.length - 1, p, p.length - 1)
}
fun isMatch(s: String, endS: Int, p: String, endP: Int): Boolean {
if (endS < 0 && canBeEmpty(p, endP)) return true
if (endS < 0 || endP < 0) return false
return p[endP] != '*' && (p[endP] == '.' || s[endS] == p[endP]) && isMatch(s, endS - 1, p, endP - 1)
|| p[endP] == '*' && endP > 0 && isMatchStar(s, endS, p, endP)
}
fun isMatchStar(s: String, endS: Int, p: String, endP: Int): Boolean {
if (endS < 0 && canBeEmpty(p, endP)) return true
if (endS < 0 || endP <= 0) return false
//匹配*前一个字符 或是匹配*前第两个字符
return (p[endP - 1] == '.' || s[endS] == p[endP - 1]) && isMatchStar(s, endS - 1, p, endP)
|| endP > 1 && isMatch(s, endS, p, endP - 2)
}
/**
* 可以是空串
*/
private fun canBeEmpty(p: String, endP: Int): Boolean {
var flag = false
for (i in endP downTo 0) {
if (flag && p[i] != '*')
flag = false
else if (!flag && p[i] == '*')
flag = true
else if (!flag && p[i] != '*')
return false
}
return true
}
} | [
{
"class_path": "chengw315__daily-study__501b881/letcode10/LeetCode10Kt.class",
"javap": "Compiled from \"LeetCode10.kt\"\npublic final class letcode10.LeetCode10Kt {\n public static final void main();\n Code:\n 0: new #8 // class letcode10/Solution10\n 3: dup\n ... |
mantono__linear-regression__0c7cb0f/src/main/kotlin/com/mantono/lingress/Spread.kt | package com.mantono.lingress
fun median(c: Collection<Number>): Double = c.asSequence().median()
fun mean(c: Collection<Number>): Double = c.map { it.toDouble() }.average()
fun range(c: Collection<Number>): Double = c.asSequence().range()
fun variance(c: Collection<Number>): Double = c.asSequence().variance()
fun standardDeviation(c: Collection<Number>): Double = Math.sqrt(variance(c))
fun Sequence<Number>.median(): Double
{
val size = this.asSequence().count()
val evenSize = size % 2 == 0
val elementsToDrop: Int = when(evenSize)
{
true -> ((size/2.0) - 1).toInt()
false -> size/2
}
return this.map { it.toDouble() }
.sorted()
.drop(elementsToDrop)
.take(if(evenSize) 2 else 1)
.average()
}
fun Sequence<Number>.range(): Double
{
val min: Double = map { it.toDouble() }.min() ?: 0.0
val max: Double = map { it.toDouble() }.max() ?: 0.0
return max - min
}
fun Sequence<Number>.variance(): Double
{
val doubleSequence: Sequence<Double> = map { it.toDouble() }
val mean = doubleSequence.average()
val sum = doubleSequence
.map { it - mean }
.map { Math.pow(it, 2.0) }
.sum()
return sum/count()
}
fun Sequence<Number>.standardDeviation(): Double = Math.sqrt(variance()) | [
{
"class_path": "mantono__linear-regression__0c7cb0f/com/mantono/lingress/SpreadKt.class",
"javap": "Compiled from \"Spread.kt\"\npublic final class com.mantono.lingress.SpreadKt {\n public static final double median(java.util.Collection<? extends java.lang.Number>);\n Code:\n 0: aload_0\n 1... |
mantono__linear-regression__0c7cb0f/src/main/kotlin/com/mantono/lingress/Regression.kt | package com.mantono.lingress
data class RegressionLine(val m: Double, val b: Double)
{
fun y(x: Double): Double = m*x+b
fun x(y: Double): Double = (y-b)/m
operator fun get(x: Double): Double = y(x)
override fun toString(): String = "y = $m * x + $b"
}
data class Point(val x: Double, val y: Double)
{
constructor(independent: Number, dependent: Number): this(independent.toDouble(), dependent.toDouble())
}
fun residual(line: RegressionLine, point: Point): Double
{
val predictedY = line[point.x]
val actualY = point.y
return actualY - predictedY
}
fun sumOfSquaredErrors(line: RegressionLine, data: Collection<Point>): Double
{
return data.asSequence()
.map {squaredError(line, it)}
.sum()
}
fun squaredError(line: RegressionLine, p: Point): Double = Math.pow(residual(line, p), 2.0)
fun rootMeanSquareError(line: RegressionLine, data: Collection<Point>): Double
{
if(data.isEmpty())
return Double.NaN
if(data.size == 1)
return 0.0
val squaredErr = sumOfSquaredErrors(line, data) / (data.size - 1)
return Math.sqrt(squaredErr)
}
fun totalVariationInY(data: Collection<Point>): Double
{
val avg = data.asSequence()
.map { it.y }
.average()
return data
.asSequence()
.map { it.y - avg }
.map { Math.pow(it, 2.0) }
.sum()
}
inline fun squared(n: Double): Double = Math.pow(n, 2.0)
fun regressionLineFrom(c: Collection<Point>): RegressionLine
{
val xMean = c.asSequence()
.map { it.x }
.average()
val yMean = c.asSequence()
.map { it.y }
.average()
val xyMean = c.asSequence()
.map { it.x * it.y }
.average()
val xSquaredMean = c.asSequence()
.map {squared(it.x)}
.average()
val m: Double = (xMean * yMean - (xyMean)) / (Math.pow(xMean, 2.0) - xSquaredMean)
val b: Double = yMean - (m * xMean)
return RegressionLine(m, b)
} | [
{
"class_path": "mantono__linear-regression__0c7cb0f/com/mantono/lingress/RegressionKt.class",
"javap": "Compiled from \"Regression.kt\"\npublic final class com.mantono.lingress.RegressionKt {\n public static final double residual(com.mantono.lingress.RegressionLine, com.mantono.lingress.Point);\n Code:... |
skipoleschris__event-modeller__4e7fe75/src/main/kotlin/uk/co/skipoles/eventmodeller/visualisation/render/CenteredMultiLineStringRenderer.kt | package uk.co.skipoles.eventmodeller.visualisation.render
import java.awt.Graphics2D
import java.awt.geom.Rectangle2D
internal fun Graphics2D.drawCentredMultiLineString(
s: String,
x: Int,
y: Int,
width: Int,
height: Int
) {
val lines = divideIntoLines("", s, width, areaForString(this))
val linesThatFit = mostLinesThatFitHeight(lines, height)
val totalHeight = linesThatFit.sumOf { it.area.height }.toInt()
var yPosition = y + ((height - totalHeight) / 2)
linesThatFit.forEach {
drawString(it.s, (x + ((width - it.area.width.toInt()) / 2)), yPosition)
yPosition += it.area.height.toInt()
}
}
private data class LineWithArea(val s: String, val area: Rectangle2D)
private fun divideIntoLines(
current: String,
remainder: String,
maxWidth: Int,
findArea: (String) -> Rectangle2D
): List<LineWithArea> {
if (remainder.isEmpty()) return listOf(LineWithArea(current, findArea(current)))
val nextWord = remainder.takeWhile { it != ' ' }
val line = if (current.isEmpty()) nextWord else "$current $nextWord"
val lineArea = findArea(line)
return if (lineArea.width < (maxWidth - 2)) { // Line is shorter than max width
divideIntoLines(line, remainder.drop(nextWord.length + 1), maxWidth, findArea)
} else if (current.isEmpty()) { // Line is longer than max width and is a single word
val longestSubstring = longestSubstringThatFitsWidth(line, maxWidth, findArea)
listOf(LineWithArea(longestSubstring, findArea(longestSubstring))) +
divideIntoLines("", remainder.drop(longestSubstring.length), maxWidth, findArea)
} else { // Line is longer than max width, so needs a line break
listOf(LineWithArea(current, findArea(current))) +
divideIntoLines("", remainder.trim(), maxWidth, findArea)
}
}
private fun longestSubstringThatFitsWidth(
word: String,
maxWidth: Int,
findArea: (String) -> Rectangle2D
) =
word
.fold(Pair("", false)) { res, ch ->
val (s, state) = res
if (state) res
else {
val test = s + ch
val testArea = findArea(test)
if (testArea.width < (maxWidth - 2)) Pair(test, false) else Pair(s, true)
}
}
.first
private fun mostLinesThatFitHeight(lines: List<LineWithArea>, maxHeight: Int) =
lines
.fold(Pair(listOf<LineWithArea>(), false)) { result, line ->
val (validLines, done) = result
if (done) result
else {
val newHeight = validLines.sumOf { it.area.height } + line.area.height
if (newHeight < (maxHeight - 2)) Pair(validLines + line, false)
else Pair(validLines, true)
}
}
.first
private fun areaForString(graphics: Graphics2D): (String) -> Rectangle2D =
fun(s: String) = graphics.font.getStringBounds(s, graphics.fontRenderContext)
| [
{
"class_path": "skipoleschris__event-modeller__4e7fe75/uk/co/skipoles/eventmodeller/visualisation/render/CenteredMultiLineStringRendererKt.class",
"javap": "Compiled from \"CenteredMultiLineStringRenderer.kt\"\npublic final class uk.co.skipoles.eventmodeller.visualisation.render.CenteredMultiLineStringRend... |
jabrena__functional-rosetta-stone__c722696/problems/src/main/kotlin/org/fundamentals/fp/euler/EulerProblem03.kt | package org.fundamentals.fp.euler
/**
* Largest prime factor
* https://projecteuler.net/problem=3
*
* The prime factors of 13195 are 5, 7, 13 and 29.
*
* What is the largest prime factor of the number 600851475143 ?
*
* Scenario 13195
*
* Given primeFactor
* When 13195
* Then 29 [5, 7, 13, 29]
*
* Scenario 600851475143
*
* Given primeFactor
* When 600851475143
* Then ?
*/
fun KotlinSolution03(limit : Long) : Long {
return limit.primeFactors().max()!!
}
/**
* Checks if this number is a multiple of the provided number _(eg. this % other == 0)_.
*
* _Reference: [http://mathworld.wolfram.com/Multiple.html]_
*
* @return true if the receiver is a multiple of the provided number
*/
infix fun Long.isMultipleOf(other: Long) = this % other == 0L
/**
* Returns the square root of the receiver _(eg. from Math.sqrt)_.
*
* _Reference: [http://mathworld.wolfram.com/SquareRoot.html]_
*
* @return the square root of the receiver
*/
fun Double.squareRoot() = Math.sqrt(this)
/**
* @see [Double.squareRoot]
*/
fun Double.sqrt() = this.squareRoot()
/**
* Returns the integer part of the receiver _(eg. removes the decimal part)_.
*
* Example: `10.25 becomes 10`
*
* _Reference: [http://mathworld.wolfram.com/FloorFunction.html]_
*
* @return the integer part of the receiver
*/
fun Double.floor() = this.toLong()
/**
* @see [Double.squareRoot]
*/
fun Long.sqrt() = this.toDouble().sqrt()
/**
* Checks if the receiver number is a prime number _(eg. only divisors are 1 and itself)_.
*
* _Reference: [http://mathworld.wolfram.com/PrimeNumber.html]_
*
* @return true if the receiver number is a prime
*/
fun Long.isPrime() = this > 1 && (2..this.sqrt().floor()).all { !(this isMultipleOf it) }
/**
* Returns a List containing all prime factors of the receiver numbers _(eg. factorization of receiver into its consituent primes)_.
*
* _Reference: [http://mathworld.wolfram.com/PrimeFactor.html]_
*
* @return a List containing all prime factors of the receiver number
*/
fun Long.primeFactors(): List<Long> = if (isPrime()) listOf(this) else {
val nextPrimeFactor = (2..this.sqrt().floor()).find { this isMultipleOf it && it.isPrime() }
if (nextPrimeFactor == null) emptyList()
else listOf(nextPrimeFactor) + (this / nextPrimeFactor).primeFactors()
} | [
{
"class_path": "jabrena__functional-rosetta-stone__c722696/org/fundamentals/fp/euler/EulerProblem03Kt.class",
"javap": "Compiled from \"EulerProblem03.kt\"\npublic final class org.fundamentals.fp.euler.EulerProblem03Kt {\n public static final long KotlinSolution03(long);\n Code:\n 0: lload_0\n ... |
vamsitallapudi__HackerEarth__9349fa7/src/main/algorithms/searching/IceCreamParlour.kt | package main.algorithms.searching
import java.util.*
import kotlin.collections.*
import kotlin.ranges.*
import kotlin.text.*
// Complete the whatFlavors function below.
fun whatFlavors(menu: Array<Int>, money: Int): Array<Int>? {
val sortedMenu = menu.clone()
Arrays.sort(sortedMenu)
for ( i in 0 until sortedMenu.size) {
val compliment = money - sortedMenu[i]
val location = Arrays.binarySearch(sortedMenu, i+1, sortedMenu.size, compliment)
if(location >=0 && location < sortedMenu.size && sortedMenu[location] == compliment) {
return getIndicesFromValue(menu, sortedMenu[i], compliment)
}
}
return null
}
fun getIndicesFromValue(menu: Array<Int>, value1: Int, value2: Int): Array<Int> {
val index1 = indexOf(menu,value1, -1)
val index2 = indexOf(menu,value2,index1)
val indices:Array<Int> = Array(2){0}
indices[0] = Math.min(index1,index2)
indices[1] = Math.max(index1,index2)
return indices
}
fun indexOf(array:Array<Int>, value:Int, excludeIndex:Int) :Int{
for( i in 0 until array.size) {
if(array[i] == value && i != excludeIndex) {
return i
}
}
return -1
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val t = scan.nextLine().trim().toInt()
for (tItr in 1..t) {
val money = scan.nextLine().trim().toInt()
val n = scan.nextLine().trim().toInt()
val cost = scan.nextLine().trim().split(" ").map{ it.trim().toInt() }.toTypedArray()
(whatFlavors(cost,money)?.map { print("${it+1} ") })
println()
}
}
| [
{
"class_path": "vamsitallapudi__HackerEarth__9349fa7/main/algorithms/searching/IceCreamParlourKt.class",
"javap": "Compiled from \"IceCreamParlour.kt\"\npublic final class main.algorithms.searching.IceCreamParlourKt {\n public static final java.lang.Integer[] whatFlavors(java.lang.Integer[], int);\n Co... |
vamsitallapudi__HackerEarth__9349fa7/src/main/algorithms/searching/BinarySearchRecursive.kt | package main.algorithms.searching
fun main(args: Array<String>) {
val input = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() // to read an array (from user input)
val eleToSearch = readLine()!!.trim().toInt() // to read the element to be searched (from user input)
val pos = binarySearchRecursive(input, eleToSearch, 0, input.size -1)
if(pos >= 0 ) {
println(pos) // to print position at last
} else {
println("Position not found")
}
}
fun binarySearchRecursive(input: IntArray, eleToSearch: Int, low:Int, high:Int): Int {
while(low <=high) {
val mid = (low + high) /2
when {
eleToSearch > input[mid] -> return binarySearchRecursive(input, eleToSearch, mid+1, high) // element is greater than middle element of array, so it will be in right half. Recursion will call the right half again
eleToSearch < input[mid] -> return binarySearchRecursive(input, eleToSearch, low, mid-1) //element is less than middle element of array, so it will be in left half of the array. Recursion will call the left half again.
eleToSearch == input[mid] -> return mid // element found.
}
}
return -1
}
| [
{
"class_path": "vamsitallapudi__HackerEarth__9349fa7/main/algorithms/searching/BinarySearchRecursiveKt.class",
"javap": "Compiled from \"BinarySearchRecursive.kt\"\npublic final class main.algorithms.searching.BinarySearchRecursiveKt {\n public static final void main(java.lang.String[]);\n Code:\n ... |
vamsitallapudi__HackerEarth__9349fa7/src/main/algorithms/sorting/MergeSort.kt | package main.algorithms.sorting
fun main(args: Array<String>) {
val array = readLine()!!.split(" ").map { it.toInt() }.toIntArray() // 1) Read the input and split into array
mergeSort(array)
for(i in array) println(i)
}
fun mergeSort(array : IntArray, helper:IntArray = IntArray(array.size), low:Int = 0, high : Int = array.size-1) {
if(low < high) {
val middle:Int = (low+high)/2 // 2) calculating the middle element
mergeSort(array, helper, low, middle) // 3) to sort left half
mergeSort(array, helper, middle+1, high) // 4) to sort right half
merge(array, helper, low, middle, high) // 5) Merge them
}
}
fun merge (array: IntArray, helper: IntArray, low: Int, middle:Int, high: Int){
// a) copying both halves into helper array
for(i in low..high) helper[i] = array[i]
var helperLeft = low
var helperRight = middle + 1 // b) helper variables
var current = low
/*Iterate through helper array. Compare the left and right half, copying back the smaller element
* from the two halves into original array*/
while (helperLeft <= middle && helperRight <= high) { // c) condition to check helper left and helper right
if(helper[helperLeft] <= helper[helperRight]) { // d) Check if value at helperLeft index is less than that of value at helper right
array[current] = helper[helperLeft]
helperLeft++
} else { // e) right element is smaller than left element
array[current] = helper[helperRight]
helperRight++
}
current++
}
// f) copy the rest of leftside of array into target
val remaining = middle - helperLeft
for (i in 0..remaining) {
array[current + i] = helper[helperLeft + i]
}
} | [
{
"class_path": "vamsitallapudi__HackerEarth__9349fa7/main/algorithms/sorting/MergeSortKt.class",
"javap": "Compiled from \"MergeSort.kt\"\npublic final class main.algorithms.sorting.MergeSortKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9... |
vamsitallapudi__HackerEarth__9349fa7/src/main/algorithms/sorting/QuickSort.kt | package main.algorithms.sorting
fun main(args: Array<String>) {
val array = readLine()!!.split(" ").map { it.toInt() }.toIntArray() // 1) Read the input and split into array
quickSort(array, 0, array.size-1)
for(i in array) println(i)
}
fun quickSort(array: IntArray, left: Int, right: Int) {
val index = partition (array, left, right)
if(left < index-1) { // 2) Sorting left half
quickSort(array, left, index-1)
}
if(index < right) { // 3) Sorting right half
quickSort(array,index, right)
}
}
fun partition(array: IntArray, l: Int, r: Int): Int {
var left = l
var right = r
val pivot = array[(left + right)/2] // 4) Pivot Point
while (left <= right) {
while (array[left] < pivot) left++ // 5) Find the elements on left that should be on right
while (array[right] > pivot) right-- // 6) Find the elements on right that should be on left
// 7) Swap elements, and move left and right indices
if (left <= right) {
swapArray(array, left,right)
left++
right--
}
}
return left
}
fun swapArray(a: IntArray, b: Int, c: Int) {
val temp = a[b]
a[b] = a[c]
a[c] = temp
}
| [
{
"class_path": "vamsitallapudi__HackerEarth__9349fa7/main/algorithms/sorting/QuickSortKt.class",
"javap": "Compiled from \"QuickSort.kt\"\npublic final class main.algorithms.sorting.QuickSortKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9... |
vamsitallapudi__HackerEarth__9349fa7/src/main/basicprogramming/implementation/kotlin/BatmanAndTicTacToe.kt | package main.basicprogramming.implementation.kotlin
fun main(args: Array<String>) {
var testCases:Int = readLine()!!.toInt()
while(testCases-- > 0) {
val line1 = readLine()!!
val line2 = readLine()!!
val line3 = readLine()!!
val line4 = readLine()!!
if(ticTacToeLogic(line1,line2,line3,line4)) println("YES") else println("NO")
}
}
fun ticTacToeLogic(line1:String, line2:String, line3:String, line4:String) : Boolean {
// TODO: need to change some logic in case of expected next move
// case -1 row check:
if(checkPattern(line1) || checkPattern(line2) || checkPattern(line3) || checkPattern(line4)) return true
// case -2 column check
else if(performColumnCheck(line1,line2,line3,line4)) return true
// case -3 diagonal check
else if(performDiagonalCheck(line1, line2, line3, line4)) return true
return false
}
fun performDiagonalCheck(line1: String, line2: String, line3: String, line4: String): Boolean {
// diagonals with 4 nodes
val diagonalString1 = (line1[0].toString() + line2[1] + line3[2] + line4[3])
val diagonalString2 = (line1[3].toString() + line2[2] + line3[1] + line4[0])
// small diagonals with 3 nodes
val diagonalString3 = (line1[1].toString() + line2[2] + line3[3])
val diagonalString4 = (line1[2].toString() + line2[1] + line3[0])
val diagonalString5 = (line2[0].toString() + line3[1] + line4[2])
val diagonalString6 = (line2[2].toString() + line3[1] + line4[0])
val diagonalString7 = (line2[3].toString() + line3[2] + line4[1])
return (checkPattern(diagonalString1) || checkPattern(diagonalString2) || checkPattern(diagonalString3) || checkPattern(diagonalString4) || checkPattern(diagonalString5) || checkPattern(diagonalString6) || checkPattern(diagonalString7))
}
fun performColumnCheck(line1: String, line2: String, line3: String, line4: String): Boolean {
for(i in 0..3) {
val columnString = (line1[i].toString()+line2[i]+line3[i]+line4[i])
if(checkPattern(columnString)) return true
}
return false
}
fun checkPattern(str:String) : Boolean{
return str.contains("xx.") || str.contains(".xx") || str.contains("x.x")
}
| [
{
"class_path": "vamsitallapudi__HackerEarth__9349fa7/main/basicprogramming/implementation/kotlin/BatmanAndTicTacToeKt.class",
"javap": "Compiled from \"BatmanAndTicTacToe.kt\"\npublic final class main.basicprogramming.implementation.kotlin.BatmanAndTicTacToeKt {\n public static final void main(java.lang.S... |
imdudu1__algorithm-diary__ee7df89/jvm/src/main/kotlin/boj/ChickenDelivery.kt | package boj
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*
import kotlin.math.abs
class ChickenDelivery constructor(private val map: Array<Array<Int>>) {
private val stores: List<Point> by lazy { getObjects(2) }
private val houses: List<Point> by lazy { getObjects(1) }
fun solution(m: Int): Int {
val openStores = BooleanArray(stores.size)
var result = Int.MAX_VALUE
combination(0, m, 0, openStores) {
val t = houses.asSequence().map { house ->
stores.asSequence().filterIndexed { index, _ -> openStores[index] }
.map { it.distance(house) }.minOf { it }
}.sum()
result = result.coerceAtMost(t)
}
return result
}
private fun combination(s: Int, m: Int, c: Int, visited: BooleanArray, action: () -> Unit) {
if (c == m) {
action()
return
}
for (i in s until stores.size) {
if (visited[i]) continue
visited[i] = true
combination(i, m, c + 1, visited, action)
visited[i] = false
}
}
data class Point constructor(val x: Int, val y: Int) {
fun distance(other: Point) = abs(x - other.x) + abs(y - other.y)
}
private fun getObjects(type: Int): List<Point> {
val result = LinkedList<Point>()
for (i in map.indices) {
for (j in map[0].indices) {
if (map[i][j] == type) {
result.add(Point(j, i))
}
}
}
return result
}
}
fun chickenDelivery(args: Array<String>) {
val br = BufferedReader(InputStreamReader(System.`in`))
val (n, m) = br.readLine().trim().split(" ").map { it.toInt() }
val map = Array(n) { br.readLine().trim().split(" ").map { it.toInt() }.toTypedArray() }
val solution = ChickenDelivery(map)
print(solution.solution(m))
}
| [
{
"class_path": "imdudu1__algorithm-diary__ee7df89/boj/ChickenDelivery.class",
"javap": "Compiled from \"ChickenDelivery.kt\"\npublic final class boj.ChickenDelivery {\n private final java.lang.Integer[][] map;\n\n private final kotlin.Lazy stores$delegate;\n\n private final kotlin.Lazy houses$delegate;\... |
imdudu1__algorithm-diary__ee7df89/jvm/src/main/kotlin/boj/CoffeeShopII.kt | package boj
import java.io.BufferedReader
import java.io.InputStreamReader
class CoffeeShopII constructor(private val numbers: Array<Long>) {
private val segmentTree: Array<Long> = Array(numbers.size * 4) { 0 }
init {
initTree(0, numbers.size - 1)
}
private fun initTree(begin: Int, end: Int, root: Int = 1): Long {
if (begin == end) {
segmentTree[root] = numbers[begin]
return numbers[begin]
}
val mid = (begin + end) / 2
segmentTree[root] =
initTree(begin, mid, root * 2) + initTree(mid + 1, end, root * 2 + 1)
return segmentTree[root]
}
private fun updateTree(begin: Int, end: Int, target: Int, diff: Long, root: Int = 1) {
if (target in begin..end) {
segmentTree[root] += diff
if (begin != end) {
val mid = (begin + end) / 2
updateTree(begin, mid, target, diff, root * 2)
updateTree(mid + 1, end, target, diff, root * 2 + 1)
}
}
}
fun sum(x: Int, y: Int): Long = rangeSum(0, numbers.size - 1, x, y)
private fun rangeSum(begin: Int, end: Int, x: Int, y: Int, root: Int = 1): Long {
if (y < begin || end < x) {
return 0
}
if (x <= begin && end <= y) {
return segmentTree[root]
}
val mid = (begin + end) / 2
return rangeSum(begin, mid, x, y, root * 2) + rangeSum(mid + 1, end, x, y, root * 2 + 1)
}
fun update(pos: Int, n: Long) {
val diff = getDiff(pos, n)
numbers[pos] = n
updateTree(0, numbers.size - 1, pos, diff)
}
private fun getDiff(pos: Int, n: Long): Long {
return n - numbers[pos]
}
}
fun coffeeShopII(args: Array<String>) {
val br = BufferedReader(InputStreamReader(System.`in`))
val (_, q) = br.readLine().trim().split(" ").map(String::toInt)
val nums = br.readLine().trim().split(" ").map(String::toLong).toTypedArray()
val solution = CoffeeShopII(nums)
repeat(q) {
var (x, y, a, b) = br.readLine().trim().split(" ").map(String::toLong)
if (x > y) {
x = y.also { y = x }
}
println(solution.sum((x - 1).toInt(), (y - 1).toInt()))
solution.update((a - 1).toInt(), b)
}
}
| [
{
"class_path": "imdudu1__algorithm-diary__ee7df89/boj/CoffeeShopIIKt.class",
"javap": "Compiled from \"CoffeeShopII.kt\"\npublic final class boj.CoffeeShopIIKt {\n public static final void coffeeShopII(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // Strin... |
vorpal-research__kparsec__3238c73/src/main/kotlin/ru/spbstu/kparsec/examples/tip/constraint/Equalities.kt | package ru.spbstu.kparsec.examples.tip.constraint
import java.util.*
sealed class Node {
abstract operator fun contains(v: Node): Boolean
}
data class Var(val id: String = dict[currentId].also { ++currentId }) : Node() {
override fun contains(v: Node): Boolean = v == this
override fun toString() = id
companion object {
val dict = ('a'..'z').map{ it.toString() } + (0..100).map { "t" + it }
var currentId = 0
}
}
data class Fun(val name: String, val arguments: List<Node>) : Node() {
override fun contains(v: Node): Boolean = v == this || arguments.any { it.contains(v) }
override fun toString() = "$name(${arguments.joinToString()})"
}
data class Equality(val lhv: Node, val rhv: Node) {
override fun toString() = "$lhv = $rhv"
}
fun collectVariables(n: Node, set: MutableSet<Var>): Unit = when(n) {
is Var -> set += n
is Fun -> n.arguments.forEach { collectVariables(it, set) }
}
fun collectVariables(eq: Equality, set: MutableSet<Var>) {
collectVariables(eq.lhv, set)
collectVariables(eq.rhv, set)
}
class Solver(input: List<Equality>) {
data class Exception(val eq: Equality): kotlin.Exception("Unsolvable equation: $eq")
val que: Queue<Equality> = ArrayDeque(input)
val subst: MutableMap<Var, Node> = mutableMapOf()
val Equality.rrhv get() = subst[rhv] ?: rhv
val Equality.rlhv get() = subst[lhv] ?: lhv
val unsolvedVariables: MutableSet<Var> = mutableSetOf()
init {
input.forEach { collectVariables(it, unsolvedVariables) }
}
fun substitute(v: Node): Node = when {
v is Var && v in subst -> substitute(subst[v]!!)
else -> v
}
fun delete(eq: Equality): Boolean = eq.rlhv != eq.rrhv
fun decompose(eq: Equality): Boolean {
val lhv = eq.rlhv
val rhv = eq.rrhv
when {
lhv is Fun && rhv is Fun -> {
if(lhv.name == rhv.name && lhv.arguments.size == rhv.arguments.size) {
lhv.arguments.zip(rhv.arguments) { l, r ->
que.add(Equality(substitute(l), substitute(r)))
}
return false
} else throw Exception(eq)
}
else -> return true
}
}
fun swap(eq: Equality): Boolean {
val lhv = eq.rlhv
val rhv = eq.rrhv
if(rhv is Var && lhv !is Var) {
que.add(Equality(rhv, lhv))
return false
}
return true
}
fun eliminate(eq: Equality): Boolean {
val lhv = eq.rlhv
val rhv = eq.rrhv
if(lhv is Var) {
if(lhv in rhv) throw Exception(eq)
unsolvedVariables -= lhv
subst[lhv] = rhv
return false
}
return true
}
fun solve() {
while(que.isNotEmpty()) {
val v = que.poll()!!
when {
delete(v) && decompose(v) && swap(v) && eliminate(v) -> que.add(v)
}
}
}
fun expand(witness: Var, n: Node): Node = when(n) {
witness -> witness
in unsolvedVariables -> n
is Var -> expand(witness, substitute(n))
is Fun -> n.copy(arguments = n.arguments.map { expand(witness, it) })
}
fun result(): List<Equality> {
return subst.entries.map { (k, v) ->
Equality(k, expand(k, v))
}
}
}
| [
{
"class_path": "vorpal-research__kparsec__3238c73/ru/spbstu/kparsec/examples/tip/constraint/EqualitiesKt.class",
"javap": "Compiled from \"Equalities.kt\"\npublic final class ru.spbstu.kparsec.examples.tip.constraint.EqualitiesKt {\n public static final void collectVariables(ru.spbstu.kparsec.examples.tip... |
hi-dhl__Leetcode-Solutions-with-Java-And-Kotlin__b5e34ac/00-code(源代码)/src/com/hi/dhl/algorithms/offer/_13/kotlin/Solution.kt | package com.hi.dhl.algorithms.offer._13.kotlin
import java.util.*
/**
* <pre>
* author: dhl
* desc :
* </pre>
*/
class Solution {
fun movingCount(m: Int, n: Int, k: Int): Int {
val robot = Array(m, { IntArray(n) })
return dfs(robot, 0, 0, m, n, k)
}
fun dfs(robot: Array<IntArray>, x: Int, y: Int, m: Int, n: Int, k: Int): Int {
if (x > m - 1 || y > n - 1 || robot[x][y] == -1 || count(x) + count(y) > k) {
return 0
}
robot[x][y] = -1
return dfs(robot, x + 1, y, m, n, k) + dfs(robot, x, y + 1, m, n, k) + 1
}
fun bfs(m: Int, n: Int, k: Int): Int {
val robot = Array(m, { IntArray(n) })
val queue = LinkedList<IntArray>()
var res = 0
queue.offer(intArrayOf(0, 0))
while (!queue.isEmpty()) {
val (x, y) = queue.poll()
if (x > m - 1 || y > n - 1 || robot[x][y] == -1 || count(x) + count(y) > k) {
continue;
}
robot[x][y] = -1
res += 1
queue.offer(intArrayOf(x + 1, y))
queue.offer(intArrayOf(x, y + 1))
}
return res
}
fun count(x: Int): Int {
var sx = x
var count = 0
while (sx > 0) {
count += sx % 10
sx = sx / 10
}
return count
}
}
fun main() {
val solution = Solution()
println(solution.bfs(38, 15, 9))
} | [
{
"class_path": "hi-dhl__Leetcode-Solutions-with-Java-And-Kotlin__b5e34ac/com/hi/dhl/algorithms/offer/_13/kotlin/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class com.hi.dhl.algorithms.offer._13.kotlin.Solution {\n public com.hi.dhl.algorithms.offer._13.kotlin.Solution();\n Co... |
hi-dhl__Leetcode-Solutions-with-Java-And-Kotlin__b5e34ac/00-code(源代码)/src/com/hi/dhl/algorithms/offer/_17/kotlin/Solution.kt | package com.hi.dhl.algorithms.offer._17.kotlin
/**
* <pre>
* author: dhl
* date : 2020/8/5
* desc :
* </pre>
*/
class Solution {
// 方法一
fun printNumbers2(n: Int): IntArray {
var max = 1;
for (i in 1..n) {
max = max * 10;
}
val result = IntArray(max - 1)
for (i in 1 until max) {
result[i - 1] = i
}
return result;
}
// 方法二
val defNum = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
var index = 0;
fun printNumbers(n: Int): IntArray {
val num = CharArray(n)
var max = 1
// kotlin 中使用 Math.pow 要求参数都是double类型,所以这里自动生成对应的位数
for (i in 1..n) {
max = max * 10;
}
val result = IntArray(max - 1)
dfs(num, result, 0) // 开始递归遍历
return result;
}
fun dfs(num: CharArray, result: IntArray, x: Int) {
if (x == num.size) {
// 生成的数字前面可能有 0 例如:000,001,002... 等等
// parstInt 方法去删除高位多余的 0
val res = parstInt(num);
// 过滤掉第一个数字 0
if (res > 0) {
result[index] = res
index = index + 1
}
return;
}
for (c in defNum) {
num[x] = c
dfs(num, result, x + 1)
}
}
fun parstInt(num: CharArray): Int {
var sum = 0
var isNotZero = false
for (c in num) {
// 生成的数字前面可能有 0 例如:000,001,002... 等等
// 过滤掉高位多余的 0
if (!isNotZero) {
if (c == '0') {
continue
} else {
isNotZero = true
}
}
sum = sum * 10 + (c - '0')
}
return sum;
}
} | [
{
"class_path": "hi-dhl__Leetcode-Solutions-with-Java-And-Kotlin__b5e34ac/com/hi/dhl/algorithms/offer/_17/kotlin/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class com.hi.dhl.algorithms.offer._17.kotlin.Solution {\n private final char[] defNum;\n\n private int index;\n\n public ... |
Petikoch__TicTacToe_FP_CTDD_Kotlin__f24fa2e/src/main/kotlin/ch/petikoch/examples/tictactoe_fp/TicTacToe.kt | package ch.petikoch.examples.tictactoe_fp
import ch.petikoch.examples.tictactoe_fp.Field.*
fun main() {
var gameState = GameState() // "store"
while (gameState.winner == null && !gameState.board.values.any { it == null }) {
println(gameState) // "view"
val textInput = readLine()
val field = convertTextInput(textInput) // "action"
gameState = play(gameState, field) // "reduce"
}
println(gameState)
}
private fun convertTextInput(textInput: String?): Field {
return Field.values().find { it.name == textInput }!!
}
fun play(gameState: GameState, field: Field): GameState {
val newBoard = gameState.board.plus(field to gameState.currentPlayer)
return GameState(
currentPlayer = gameState.currentPlayer.other(),
board = newBoard,
winner = findWinner(newBoard)
)
}
private fun findWinner(newBoard: Map<Field, Player?>): Player? {
return winningConditions.firstOrNull { areSame(newBoard, it) }?.let { newBoard[it.first] }
}
private val winningConditions: List<Triple<Field, Field, Field>> = listOf(
Triple(TL, TM, TR),
Triple(ML, MM, MR)
// ...
)
private fun areSame(board: Map<Field, Player?>,
triple: Triple<Field, Field, Field>): Boolean {
return board[triple.first] == board[triple.second] &&
board[triple.first] == board[triple.third]
}
data class GameState(
val currentPlayer: Player = Player.X,
val board: Map<Field, Player?> = mapOf(),
val winner: Player? = null
)
enum class Player {
X, O;
fun other(): Player = if (this == X) O else X
}
enum class Field {
TL, TM, TR,
ML, MM, MR,
BL, BM, BR
}
| [
{
"class_path": "Petikoch__TicTacToe_FP_CTDD_Kotlin__f24fa2e/ch/petikoch/examples/tictactoe_fp/TicTacToeKt.class",
"javap": "Compiled from \"TicTacToe.kt\"\npublic final class ch.petikoch.examples.tictactoe_fp.TicTacToeKt {\n private static final java.util.List<kotlin.Triple<ch.petikoch.examples.tictactoe_... |
aquatir__code-samples__eac3328/code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/algo/unions.kt | package com.codesample.algo
abstract class Union<T>() {
/** Make two elements point to same union */
abstract fun union(fst: T, snd: T)
/** Return true if two elements are connected or false otherwise. Same elements are always considered connected */
abstract fun connected(fst: T, snd: T): Boolean
}
fun Union<Int>.printConnected(fst: Int, snd: Int) {
if (this.connected(fst, snd))
println("'$fst' and '$snd' are connected") else
println("'$fst' and '$snd' are NOT connected")
}
/** Union with fast 'connected' operation O(1) and slow 'union' O(n)
*
* The entries are connected if and only if they have the same index.
* Implementation is NOT thread-safe!*/
class QuickFindUnion<T> : Union<T>() {
/** Next created union index. Incremented each time a new element in added to this union in 'connected' call */
private var nextUnionIndex = 0
/** Map element to index of union */
private val elements: MutableMap<T, Int> = mutableMapOf()
override fun union(fst: T, snd: T) {
// Maybe insert new element and return if two elements are the same
if (fst == snd) {
oldIndexOrInsertAndIndex(fst)
return
}
val fstIndex = oldIndexOrInsertAndIndex(fst)
val sndIndex = oldIndexOrInsertAndIndex(snd)
if (fstIndex == sndIndex) return // both are already in the union
else {
// Element in union with index 'fstIndex' will now be in secondIndex. Other elements are not changed
for (elem in elements) {
if (elem.value == fstIndex) {
elements[elem.key] = sndIndex
}
}
}
}
override fun connected(fst: T, snd: T): Boolean {
// Assume same element in always connected to itself
if (fst == snd) return true
val fstIndex = oldIndexOrNull(fst)
val sndIndex = oldIndexOrNull(snd)
return fstIndex != null && sndIndex != null && fstIndex == sndIndex
}
private fun exist(elem: T) = elements.containsKey(elem)
/** Get set index of element OR insert element in brand new union */
private fun oldIndexOrInsertAndIndex(elem: T): Int {
return if (exist(elem)) elements.getValue(elem)
else {
val curIndex = nextUnionIndex
elements[elem] = curIndex
nextUnionIndex++
curIndex
}
}
private fun oldIndexOrNull(elem: T): Int? = elements[elem]
}
//
//
//
// Quick Union Union!
//
//
/** Union with fast 'union' operation O(1) and 'slow' 'connected' operation O(n) in worst case,
* but can be optimized to O(log(n)) [QuickUnionUnionOptimized].
* The idea is to add elements as children on union operation which will create long-long trees */
class QuickUnionUnion<T> : Union<T>() {
/** Each element may or may not have a parent. If no parent available -> it's a root of tree */
private val elementToParent: MutableMap<T, T?> = mutableMapOf()
override fun union(fst: T, snd: T) {
insertIfNotExist(fst)
insertIfNotExist(snd)
elementToParent[root(fst)] = root(snd)
}
override fun connected(fst: T, snd: T): Boolean = root(fst) == root(snd)
// Can do like this but harder to read
// private fun insertIfNotExist(elem: T) = elementToParent.computeIfAbsent(elem) { null }
private fun insertIfNotExist(elem: T) {
if (!elementToParent.containsKey(elem)) {
elementToParent[elem] = null
}
}
private fun root(elem: T): T {
var prev = elem
var current = elementToParent[prev]
while (current != null) {
prev = current
current = elementToParent[prev]
}
return prev
}
}
//
//
// Quick Union Union Optimized!
//
//
/** Union with fast 'union' operation O(1) and 'slow' 'connected' operation O(log(n)).
*
* There are 2 optimizations:
* 1. When joining 2 trees -> put smaller one to a root of a larger one (do not let large tree grow further)
* 2. When finding a root of tree -> rebind all children closer to root */
class QuickUnionUnionOptimized<T> : Union<T>() {
/** Each element may or may not have a parent. If no parent available -> it's a root of tree */
private val elementToParent: MutableMap<T, T?> = mutableMapOf()
override fun union(fst: T, snd: T) {
insertIfNotExist(fst)
insertIfNotExist(snd)
// OPTIMIZATION 1 HERE!
// Pick smaller of two trees when linking unions
val rootFst = root(fst)
val rootSnd = root(snd)
if (rootFst.size < rootSnd.size) {
elementToParent[rootFst.root] = rootSnd.root
} else {
elementToParent[rootSnd.root] = rootFst.root
}
}
override fun connected(fst: T, snd: T): Boolean = root(fst).root == root(snd).root
// Can do comment below but seems harder to read
// private fun insertIfNotExist(elem: T) = elementToParent.computeIfAbsent(elem) { null }
private fun insertIfNotExist(elem: T) {
if (!elementToParent.containsKey(elem)) {
elementToParent[elem] = null
}
}
data class RootAndLength<T>(val root: T, val size: Int)
private fun root(elem: T): RootAndLength<T> {
var size = 0
var prev = elem
var current = elementToParent[prev]
while (current != null) {
val oldPrev = prev
prev = current
current = elementToParent[prev]
size++
// OPTIMIZATION 2 HERE!
// Shrink tree on each iteration by rebinding the farthest element 1 step closer to root
elementToParent[oldPrev] = prev
}
return RootAndLength(prev, size)
}
}
//
//
// main() for testing
//
//
fun main() {
// pick one of 3 implementations
// val quickFindUnion = QuickFindUnion<Int>()
// val quickFindUnion = QuickUnionUnion<Int>()
val quickFindUnion = QuickUnionUnionOptimized<Int>()
with(quickFindUnion) {
union(1, 2)
union(6, 5)
union(2, 5)
union(3, 7)
this.printConnected(1, 2) // true
this.printConnected(2, 5) // true
this.printConnected(5, 6) // true
this.printConnected(0, 5) // false
this.printConnected(6, 2) // true
this.printConnected(7, 3) // true
this.printConnected(0, 0) // true
this.printConnected(0, 4) // false
}
}
| [
{
"class_path": "aquatir__code-samples__eac3328/com/codesample/algo/UnionsKt.class",
"javap": "Compiled from \"unions.kt\"\npublic final class com.codesample.algo.UnionsKt {\n public static final void printConnected(com.codesample.algo.Union<java.lang.Integer>, int, int);\n Code:\n 0: aload_0\n ... |
CWKSC__MyLib_Kotlin__01c8453/MyLib_Kotlin/src/main/kotlin/algorithm/dp/LCS.kt | package algorithm.dp
sealed class LCS {
companion object {
private fun longestOne(A: String, B: String): String {
return if (A.length >= B.length) A else B
}
fun recursionTopDown(A: String, B: String): String {
if (A.isEmpty() || B.isEmpty()) return "";
val aLast = A.last()
val bLast = B.last()
val subA = A.dropLast(1)
val subB = B.dropLast(1)
return if (aLast == bLast) {
recursionTopDown(subA, subB) + aLast
} else {
longestOne(
recursionTopDown(subA, B),
recursionTopDown(A, subB)
)
}
}
fun recursionBottomUp(LCS: String, remainA: String, remainB: String): String {
if (remainA.isEmpty() || remainB.isEmpty()) return LCS
val aFirst = remainA.first()
val bFirst = remainB.first()
val subA = remainA.drop(1)
val subB = remainB.drop(1)
return if (aFirst == bFirst) {
recursionBottomUp(LCS, subA, subB) + aFirst
} else {
longestOne(
recursionBottomUp(LCS, subA, remainB),
recursionBottomUp(LCS, remainA, subB)
)
}
}
fun recursionTopDownIndex(A: String, B: String, indexA: Int, indexB: Int): String {
if (indexA < 0 || indexB < 0) return "";
val a = A[indexA]
val b = B[indexB]
return if (a == b) {
recursionTopDownIndex(A, B, indexA - 1, indexB - 1) + a
} else {
longestOne(
recursionTopDownIndex(A, B, indexA - 1, indexB),
recursionTopDownIndex(A, B, indexA, indexB - 1),
)
}
}
fun dp(A: String, B: String): Array<IntArray> {
val aLength = A.length
val bLength = B.length
val dp = Array(aLength + 1) { IntArray(bLength + 1) { 0 } }
val direction = Array(aLength + 1) { CharArray(bLength + 1) { ' ' } }
for (row in 0 until aLength) {
for (col in 0 until bLength) {
if (A[row] == B[col]) {
dp[row + 1][col + 1] = dp[row][col] + 1
direction[row + 1][col + 1] = '\\';
} else if (dp[row][col + 1] >= dp[row + 1][col]) {
dp[row + 1][col + 1] = dp[row][col + 1]
direction[row + 1][col + 1] = '^';
} else {
dp[row + 1][col + 1] = dp[row + 1][col]
direction[row + 1][col + 1] = '<';
}
}
}
return dp
}
fun printDp(dp: Array<IntArray>, direction: Array<CharArray>) {
val aLength = dp.size
val bLength = dp[0].size
for (row in 0..aLength) {
for (col in 0..bLength) {
print("${dp[row][col]}${direction[row][col]} ")
}
println()
}
}
fun backtracking(dp: Array<IntArray>, direction: Array<CharArray>, A: String): String {
val aLength = dp.size
val bLength = dp[0].size
var LCS = ""
var row: Int = aLength
var col: Int = bLength
while (direction[row][col] != ' ') {
when (direction[row][col]) {
'\\' -> {
LCS += A.get(row - 1)
row -= 1
col -= 1
}
'<' -> col -= 1
'^' -> row -= 1
}
}
return LCS
}
}
} | [
{
"class_path": "CWKSC__MyLib_Kotlin__01c8453/algorithm/dp/LCS$Companion.class",
"javap": "Compiled from \"LCS.kt\"\npublic final class algorithm.dp.LCS$Companion {\n private algorithm.dp.LCS$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.... |
boti996__fish_dsl__dd0ac20/src/main/kotlin/boti996/dsl/proba/models/Bonus.kt | package boti996.dsl.proba.models
/**
* this defines bonus-effect ID-s
*/
enum class BonusEffect(val literal: String) {
REGENERATION("regeneration"),
STRENGTH("strength"),
DEFENSE("defense")
}
/**
* bonus type: this defines a set of [BonusEffect]-s
*/
enum class BonusType {
ANOXIA {
override fun _getBonus(): Map<BonusEffect, Float> = mutableMapOf(
BonusEffect.REGENERATION to 2.0f,
BonusEffect.STRENGTH to 4.0f
)
},
EXTRA_STRENGTH {
override fun _getBonus(): Map<BonusEffect, Float> = mutableMapOf(
BonusEffect.STRENGTH to 6.0f
)
},
EXTRA_DEFENSE {
override fun _getBonus(): Map<BonusEffect, Float> = mutableMapOf(
BonusEffect.DEFENSE to 2.0f
)
},
EXTRA_HEAL {
override fun _getBonus(): Map<BonusEffect, Float> = mutableMapOf(
BonusEffect.REGENERATION to 1.5f
)
};
protected abstract fun _getBonus(): Map<BonusEffect, Float>
/**
* return a set of [BonusEffect]-s
* @param multiplier optional, multiplies [BonusEffect]-s
*/
fun getBonus(multiplier: Float = 1.0f): Map<BonusEffect, Float> {
val map = _getBonus() as MutableMap
map.keys.forEach { key -> map[key] = map[key]!!.times(multiplier) }
return map
}
}
/**
* [Bonus] can be set on object to take effect
*/
interface BonusAcceptor {
fun setBonus(bonus: Bonus)
}
/**
* wrapper for [BonusType] with a multiplier parameter
* @param multiplier multiplies [BonusEffect]-s
*/
data class Bonus(val bonus: BonusType, var multiplier: Float = 1.0f) {
fun getBonus(): Map<BonusEffect, Float> = bonus.getBonus(multiplier)
override fun equals(other: Any?): Boolean {
return other is Bonus &&
bonus == other.bonus &&
multiplier == other.multiplier
}
override fun hashCode(): Int {
var result = bonus.hashCode()
result = 31 * result + multiplier.hashCode()
return result
}
}
/**
* object has accessible [Bonus]-s
*/
interface BonusProvider<T : Enum<T>> {
fun getBonuses(modifierType: T? = null): List<Bonus>
}
| [
{
"class_path": "boti996__fish_dsl__dd0ac20/boti996/dsl/proba/models/Bonus.class",
"javap": "Compiled from \"Bonus.kt\"\npublic final class boti996.dsl.proba.models.Bonus {\n private final boti996.dsl.proba.models.BonusType bonus;\n\n private float multiplier;\n\n public boti996.dsl.proba.models.Bonus(bo... |
ThijsBoehme__portfolio-design-patterns-udemy__9bdb5be/src/main/kotlin/behavioural_patterns/interpreter/Interpreter.kt | package behavioural_patterns.interpreter
import java.util.stream.Collectors
interface Element {
fun eval(): Int
}
class Integer(private val value: Int): Element {
override fun eval(): Int {
return value
}
}
class BinaryOperation: Element {
lateinit var type: Type
lateinit var left: Element
lateinit var right: Element
override fun eval(): Int {
return when (type) {
Type.ADDITION -> left.eval() + right.eval()
Type.SUBTRACTION -> left.eval() - right.eval()
}
}
enum class Type {
ADDITION, SUBTRACTION
}
}
class Token(
val type: Type,
val text: String
) {
override fun toString(): String {
return "`$text`"
}
enum class Type {
INTEGER, PLUS, MINUS, LEFTPARENTHESIS, RIGHTPARENTHESIS
}
}
fun lex(input: String): List<Token> {
val result = ArrayList<Token>()
var i = 0
while (i < input.length) {
when (input[i]) {
'+' -> result.add(Token(Token.Type.PLUS, "+"))
'-' -> result.add(Token(Token.Type.MINUS, "-"))
'(' -> result.add(Token(Token.Type.LEFTPARENTHESIS, "("))
')' -> result.add(Token(Token.Type.RIGHTPARENTHESIS, ")"))
else -> {
val builder = StringBuilder("${input[i]}")
for (j in (i + 1) until input.length) {
if (input[j].isDigit()) {
builder.append(input[j])
++i
} else {
result.add(Token(Token.Type.INTEGER, builder.toString()))
break
}
}
}
}
i++
}
return result
}
fun parse(tokens: List<Token>): Element {
val result = BinaryOperation()
var hasLeftHandSide = false
var i = 0
while (i < tokens.size) {
val token = tokens[i]
when (token.type) {
Token.Type.INTEGER -> {
val integer = Integer(token.text.toInt())
if (hasLeftHandSide) result.right = integer
else {
result.left = integer
hasLeftHandSide = true
}
}
Token.Type.PLUS -> result.type = BinaryOperation.Type.ADDITION
Token.Type.MINUS -> result.type = BinaryOperation.Type.SUBTRACTION
Token.Type.LEFTPARENTHESIS -> {
var j = i // Location of right parenthesis (assumes no nesting of parentheses)
while (j < tokens.size) {
if (tokens[j].type == Token.Type.RIGHTPARENTHESIS) break
j++
}
val subExpression = tokens.stream()
.skip((i + 1).toLong())
.limit((j - i - 1).toLong())
.collect(Collectors.toList())
val element = parse(subExpression)
if (hasLeftHandSide) result.right = element
else {
result.left = element
hasLeftHandSide = true
}
i = j
}
Token.Type.RIGHTPARENTHESIS -> {
}
}
i++
}
return result
}
fun main() {
val input = "(13+4)-(12+1)"
val tokens: List<Token> = lex(input)
println(tokens.stream().map { it.toString() }.collect(Collectors.joining("_")))
val parsed = parse(tokens)
println("$input = ${parsed.eval()}")
}
| [
{
"class_path": "ThijsBoehme__portfolio-design-patterns-udemy__9bdb5be/behavioural_patterns/interpreter/InterpreterKt$WhenMappings.class",
"javap": "Compiled from \"Interpreter.kt\"\npublic final class behavioural_patterns.interpreter.InterpreterKt$WhenMappings {\n public static final int[] $EnumSwitchMapp... |
manan025__DS-Algo-Zone__c185dce/Kotlin/binary_Search.kt | package com.company
fun main(args: Array<String>) {
// please pass sorted array in input always because binary search will always run in sorted array
val i = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray()
val key = readLine()!!.trim().toInt()
val ans = binarySearch(i, key)
if(ans >= 0 ) {
println(ans)
} else {
println("Position not found")
}
}
fun binarySearch(input: IntArray, key: Int) : Int{
var i = 0
var j = input.size
var mid : Int
while(i < j) {
mid = (i +j) / 2
when {
key == input[mid] -> return mid
key >input[mid] -> i = mid+1
key < input[mid] -> j = mid-1;
}
}
return -1
}
// sample input 1 :
// 1, 2, 3, 4, 5, 6
// 3
// output : 2
// sample input 2 :
// 4 5 2 3 6
// 3
// output : position not found
// Time Complexity = O(log(n)) for worst case and would be O(1) in best case
// space complexity = O(1)
| [
{
"class_path": "manan025__DS-Algo-Zone__c185dce/com/company/Binary_SearchKt.class",
"javap": "Compiled from \"binary_Search.kt\"\npublic final class com.company.Binary_SearchKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
AoEiuV020__DataStructuresTraining__6161b96/lib/src/main/kotlin/aoeiuv020/DynamicProgramming.kt | package aoeiuv020
import java.util.*
typealias StringBuilder = java.lang.StringBuilder
/**
* 最长公共子序列,
* 输出所有子序列,
* Created by AoEiuV020 on 2017/05/14.
*/
object DynamicProgramming {
enum class Last {
XY, X, Y, E
}
fun longestCommonSubsequence(x: String, y: String): List<String> = longestCommonSubsequence(x.toCharArray(), y.toCharArray())
private fun longestCommonSubsequence(x: CharArray, y: CharArray): List<String> {
val c = Array(x.size, {
Array(y.size, {
Pair(0, Last.XY)
})
})
var i = x.size - 1
var j = y.size - 1
_lcs(c, x, y, i, j)
return collect(c, x, y, i, j).map(StringBuilder::toString).distinct().sorted()
}
private fun collect(c: Array<Array<Pair<Int, Last>>>, x: CharArray, y: CharArray, i: Int, j: Int): MutableList<StringBuilder> = if (i < 0 || j < 0) mutableListOf<StringBuilder>(StringBuilder())
else when (c[i][j].second) {
Last.X -> collect(c, x, y, i - 1, j)
Last.Y -> collect(c, x, y, i, j - 1)
Last.E -> (collect(c, x, y, i - 1, j) + collect(c, x, y, i, j - 1)).toMutableList()
Last.XY -> {
collect(c, x, y, i - 1, j - 1).map {
it.append(x[i])
}.toMutableList()
}
}
private fun _lcs(c: Array<Array<Pair<Int, Last>>>, x: CharArray, y: CharArray, i: Int, j: Int): Int = when {
i == -1 || j == -1 -> 0
x[i] == y[j] -> {
val xy = _lcs(c, x, y, i - 1, j - 1) + 1
c[i][j] = Pair(xy, Last.XY)
c[i][j].first
}
else -> {
val x1 = _lcs(c, x, y, i - 1, j)
val y1 = _lcs(c, x, y, i, j - 1)
c[i][j] = if (x1 > y1) {
Pair(x1, Last.X)
} else if (x1 < y1) {
Pair(y1, Last.Y)
} else {
Pair(x1, Last.E)
}
c[i][j].first
}
}
}
| [
{
"class_path": "AoEiuV020__DataStructuresTraining__6161b96/aoeiuv020/DynamicProgramming$Last.class",
"javap": "Compiled from \"DynamicProgramming.kt\"\npublic final class aoeiuv020.DynamicProgramming$Last extends java.lang.Enum<aoeiuv020.DynamicProgramming$Last> {\n public static final aoeiuv020.DynamicPr... |
jerrycychen__algoexpert__c853c59/017. Find Three Largest Numbers/FindThreeLargestNumbers.kt | package com.algoexpert.program
fun findThreeLargestNumbers(array: List<Int>): List<Int> {
val threeLargest = mutableListOf(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)
for (num in array) {
updateLargest(threeLargest, num)
}
return threeLargest
}
fun updateLargest(threeLargest: MutableList<Int>, num: Int) {
if (num > threeLargest[2]) {
shiftAndUpdate(threeLargest, num, 2)
} else if (num > threeLargest[1]) {
shiftAndUpdate(threeLargest, num, 1)
} else if (num > threeLargest[0]) {
shiftAndUpdate(threeLargest, num, 0)
}
}
fun shiftAndUpdate(threeLargest: MutableList<Int>, num: Int, index: Int) {
for (i in 0 until index + 1) {
if (i == index) {
threeLargest[i] = num
} else {
threeLargest[i] = threeLargest[i + 1]
}
}
}
| [
{
"class_path": "jerrycychen__algoexpert__c853c59/com/algoexpert/program/FindThreeLargestNumbersKt.class",
"javap": "Compiled from \"FindThreeLargestNumbers.kt\"\npublic final class com.algoexpert.program.FindThreeLargestNumbersKt {\n public static final java.util.List<java.lang.Integer> findThreeLargestNu... |
SHvatov__bio-relatives-kt__f85c144/bio-common/src/main/kotlin/bio/relatives/common/utils/MathUtils.kt | package bio.relatives.common.utils
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sqrt
/**
* Based on the provided [values] calculates the median value.
* @author Created by <NAME> on 28.01.2021
*/
fun <T : Number> calculateMedianVale(values: List<T>): Double =
with(values.map { it.toDouble() }.sorted()) {
val middle = size / 2
return@with when {
size % 2 != 0 -> get(middle)
isNotEmpty() -> (get(middle) - get(middle - 1)) / 2.0
else -> 0.0
}
}
/**
* For provided [values] array calculates the root mean square value.
*/
fun <T : Number> calculateRootMeanSquare(values: List<T>): Double {
values.ifEmpty { return 0.0 }
val squareSum = values.map { it.toDouble().pow(2) }.sum()
return sqrt(squareSum / values.size)
}
/**
* Returns the average quality value of the [values] list.
*/
fun <T : Number> calculateAverageQuality(values: List<T>): Double {
return values.map { it.toDouble() }.sum() / values.size
}
/**
* Takes a map, where key is some arithmetic value, and value is its calculation error,
* and calculates the relative error rate of addition of all this values.
*/
fun <T : Number> calculateAdditionRelativeErrorRate(valueToError: Map<T, T>): Double {
return valueToError.map { it.value.toDouble() }.sum() /
valueToError.map { it.key.toDouble() }.sum()
}
/**
* Rounds a [valueToRound] to [placesNum] decimal places
*/
fun round(valueToRound: Double, placesNum: Byte): Double =
(valueToRound * 10.0.pow(placesNum.toDouble())).roundToInt() / 10.0.pow(placesNum.toDouble())
| [
{
"class_path": "SHvatov__bio-relatives-kt__f85c144/bio/relatives/common/utils/MathUtilsKt.class",
"javap": "Compiled from \"MathUtils.kt\"\npublic final class bio.relatives.common.utils.MathUtilsKt {\n public static final <T extends java.lang.Number> double calculateMedianVale(java.util.List<? extends T>)... |
alexjlockwood__bees-and-bombs-compose__0d7a86b/app/src/main/java/com/alexjlockwood/beesandbombs/demos/utils/MathUtils.kt | package com.alexjlockwood.beesandbombs.demos.utils
import kotlin.math.pow
import kotlin.math.sqrt
const val PI = Math.PI.toFloat()
const val TWO_PI = 2 * PI
const val HALF_PI = PI / 2
/**
* Calculates the cartesian distance between two points.
*/
fun dist(x1: Float, y1: Float, x2: Float, y2: Float): Float {
return sqrt(((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)))
}
/**
* Calculates a number between two numbers at a specific increment.
*/
fun lerp(a: Float, b: Float, t: Float): Float {
return a + (b - a) * t
}
/**
* Re-maps a number from one range to another.
*/
fun map(value: Float, start1: Float, stop1: Float, start2: Float, stop2: Float): Float {
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1))
}
/**
* Converts the angle measured in radians to an approximately equivalent angle measured in degrees.
*/
fun Float.toDegrees(): Float {
return Math.toDegrees(toDouble()).toFloat()
}
fun ease(p: Float): Float {
return 3 * p * p - 2 * p * p * p
}
fun ease(p: Float, g: Float): Float {
return if (p < 0.5f) {
0.5f * (2 * p).pow(g)
} else {
1 - 0.5f * (2 * (1 - p)).pow(g)
}
}
| [
{
"class_path": "alexjlockwood__bees-and-bombs-compose__0d7a86b/com/alexjlockwood/beesandbombs/demos/utils/MathUtilsKt.class",
"javap": "Compiled from \"MathUtils.kt\"\npublic final class com.alexjlockwood.beesandbombs.demos.utils.MathUtilsKt {\n public static final float PI;\n\n public static final float... |
franmosteiro__advent-of-code__dad555d/2020/kotlin/src/main/kotlin/io/franmosteiro/aoc2020/Day08.kt | package io.franmosteiro.aoc2020
/**
* Advent of Code 2020 - Day 8: Handheld Halting -
* Problem Description: http://adventofcode.com/2020/day/8
*/
class Day08(input: List<String>) {
private val orders: List<Order> = input.map {
val (name, offset) = it.split("\\s".toRegex())
Order(name, offset.toInt())
}
fun resolvePartOne(): Int {
val (position, accumulator) = Program().run(orders)
return accumulator
}
fun resolvePartTwo(): Int {
orders.forEachIndexed { i, order ->
when (order.name) {
"jmp" -> orders.toMutableList().also { orders -> orders[i] = Order("nop", order.offset) }
"nop" -> orders.toMutableList().also { orders -> orders[i] = Order("jmp", order.offset) }
else -> null
}?.let {
val (position, accumulator) = Program().run(it)
if (position == orders.size) {
return accumulator
}
}
}
return -1
}
data class Program(
var position: Int = 0,
var accumulator: Int = 0,
var executedOrdersPositions: MutableSet<Int> = mutableSetOf()) {
fun run(orders: List<Order>): Pair<Int, Int> {
while (true) {
if (position in executedOrdersPositions || position >= orders.size) {
return position to accumulator
}
executedOrdersPositions.add(position)
val currentOrder = orders[position]
when (currentOrder.name) {
"jmp" -> position += currentOrder.offset
"nop" -> position++
"acc" -> {
accumulator += currentOrder.offset
position++
}
}
}
}
}
data class Order(
val name: String,
val offset: Int,
)
}
| [
{
"class_path": "franmosteiro__advent-of-code__dad555d/io/franmosteiro/aoc2020/Day08.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class io.franmosteiro.aoc2020.Day08 {\n private final java.util.List<io.franmosteiro.aoc2020.Day08$Order> orders;\n\n public io.franmosteiro.aoc2020.Day08(java.ut... |
franmosteiro__advent-of-code__dad555d/2020/kotlin/src/main/kotlin/io/franmosteiro/aoc2020/Day09.kt | package io.franmosteiro.aoc2020
/**
* Advent of Code 2020 - Day 9: Encoding Error -
* Problem Description: http://adventofcode.com/2020/day/9
*/
class Day09(input: List<String>) {
private val seriesOfNumbers = input.map{ it.toLong() }
private var invalidNumber = -1
private val requiredSum: Long = 1398413738
fun resolvePartOne(preambleBatchSize: Int = 5): Int =
seriesOfNumbers.windowed(preambleBatchSize + 1, 1)
.first { !it.isValid() }
.last()
.also { invalidNumber = it.toInt() }.toInt()
fun resolvePartTwo(): Int {
val slice = contiguousRangeSlice(seriesOfNumbers)
return (slice.minOrNull()!! + slice.maxOrNull()!!).toInt()
}
private fun List<Long>.isValid(): Boolean =
any { itNumber -> ((last() - itNumber) in this) && (last() != itNumber) && ((last() - itNumber) != itNumber) }
private fun contiguousRangeSlice(seriesOfNumbers: List<Long>): List<Long> {
var acc = 0L
var first = 0
var second = 0
while( second < seriesOfNumbers.size) {
if(acc == requiredSum) {
return seriesOfNumbers.slice(first..second)
}
if(acc > requiredSum) {
acc -= seriesOfNumbers[first++]
continue
}
acc += seriesOfNumbers[second++]
}
error("No slice equal to $requiredSum")
}
}
| [
{
"class_path": "franmosteiro__advent-of-code__dad555d/io/franmosteiro/aoc2020/Day09.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class io.franmosteiro.aoc2020.Day09 {\n private final java.util.List<java.lang.Long> seriesOfNumbers;\n\n private int invalidNumber;\n\n private final long requi... |
franmosteiro__advent-of-code__dad555d/2020/kotlin/src/main/kotlin/io/franmosteiro/aoc2020/Day07.kt | package io.franmosteiro.aoc2020
/**
* Advent of Code 2020 - Day 7: Handy Haversacks -
* Problem Description: http://adventofcode.com/2020/day/7
*/
class Day07(input: List<String>) {
private val allBags: List<Bag>
private val MY_BAG = "shiny gold"
companion object {
private val bagPattern = """(\w+ \w+) bags contain (.*)""".toRegex()
private val bagChildsPattern = """(\d+) (\w+ \w+) bags?""".toRegex()
fun fromString(line: String): Bag {
val (name, rest) = bagPattern.matchEntire(line)!!.destructured
val contains = bagChildsPattern.findAll(rest).map { match ->
val (c, n) = match.destructured
c.toInt() to Bag(n, emptyList())
}.toList()
return Bag(name, contains)
}
}
init {
val bags = input.map { fromString(it) }
fun buildRules(name: String): Bag {
val containedBags = bags.first { it.color == name }.contains.map {
it.first to buildRules(it.second.color)
}
return Bag(name, containedBags)
}
allBags = bags.map { buildRules(it.color) }
}
fun resolvePartOne(): Int =
allBags.count { it.canHold(MY_BAG) }
fun resolvePartTwo(): Int =
allBags.first { it.color == MY_BAG }.numContains()
data class Bag(val color : String,
val contains : List<Pair<Int, Bag>> = emptyList()){
fun canHold(what: String): Boolean {
return contains.any { it.second.color == what || it.second.canHold(what) }
}
fun numContains(): Int {
return contains.sumBy {
it.first * (it.second.numContains() + 1)
}
}
}
}
| [
{
"class_path": "franmosteiro__advent-of-code__dad555d/io/franmosteiro/aoc2020/Day07.class",
"javap": "Compiled from \"Day07.kt\"\npublic final class io.franmosteiro.aoc2020.Day07 {\n public static final io.franmosteiro.aoc2020.Day07$Companion Companion;\n\n private final java.util.List<io.franmosteiro.ao... |
franmosteiro__advent-of-code__dad555d/2020/kotlin/src/main/kotlin/io/franmosteiro/aoc2020/Day04.kt | package io.franmosteiro.aoc2020
/**
* Advent of Code 2020 - Day 4: Passport Processing -
* Problem Description: http://adventofcode.com/2020/day/4
*/
class Day04(input: String) {
private val passports = input.split("\\n\\n".toRegex()).map { line ->
line.split("\\s".toRegex()).associate {
val (field, value) = it.split(":")
field to value
}
}
fun resolvePartOne(): Int {
val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
return passports.count { passport -> requiredFields.all { it in passport } }
}
fun resolvePartTwo(): Int = passports.count { valid(it) }
private fun valid(field: Map<String, String>): Boolean {
return field["byr"]?.toIntOrNull() in 1920..2002 &&
field["iyr"]?.toIntOrNull() in 2010..2020 &&
field["eyr"]?.toIntOrNull() in 2020..2030 &&
field["ecl"] in listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") &&
field["pid"]?.matches("\\d{9}".toRegex()) == true &&
field["hcl"]?.matches("#[0-9a-f]{6}".toRegex()) == true &&
when (field["hgt"]?.takeLast(2)) {
"cm" -> field["hgt"]?.dropLast(2)?.toIntOrNull() in 150..193
"in" -> field["hgt"]?.dropLast(2)?.toIntOrNull() in 59..76
else -> false
}
}
}
| [
{
"class_path": "franmosteiro__advent-of-code__dad555d/io/franmosteiro/aoc2020/Day04.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class io.franmosteiro.aoc2020.Day04 {\n private final java.util.List<java.util.Map<java.lang.String, java.lang.String>> passports;\n\n public io.franmosteiro.aoc2... |
reactivedevelopment__aoc-2022-2__dac4682/src/main/kotlin/com/adventofcode/Day.kt | package com.adventofcode
import com.adventofcode.Figure.*
import com.adventofcode.Game.game
import com.adventofcode.Game.rightScores
import com.adventofcode.Round.*
enum class Round(val scores: Long) {
Win(6),
Lose(0),
Draw(3),
}
enum class Figure(val scores: Long) {
Rock(1) {
override fun roundWith(other: Figure): Round {
return when (other) {
Rock -> Draw
Scissors -> Win
Paper -> Lose
}
}
},
Paper(2) {
override fun roundWith(other: Figure): Round {
return when (other) {
Paper -> Draw
Rock -> Win
Scissors -> Lose
}
}
},
Scissors(3) {
override fun roundWith(other: Figure): Round {
return when (other) {
Scissors -> Draw
Rock -> Lose
Paper -> Win
}
}
};
abstract fun roundWith(other: Figure): Round
}
fun parseFigure(s: String): Figure {
return when (s) {
"A" -> Rock
"B" -> Paper
"C" -> Scissors
else -> throw IllegalStateException()
}
}
object Game {
var leftScores = 0L; private set
var rightScores = 0L; private set
fun game(left: Figure, right: Figure) {
leftScores += left.scores
leftScores += left.roundWith(right).scores
rightScores += right.scores
rightScores += right.roundWith(left).scores
}
}
fun tryBruteforceGame(other: Figure, needScores: Long): Figure {
for (me in setOf(Rock, Paper, Scissors)) {
if (me.roundWith(other).scores == needScores) {
return me
}
}
throw IllegalStateException()
}
fun tryWin(other: Figure): Figure {
return tryBruteforceGame(other, Win.scores)
}
fun tryLose(other: Figure): Figure {
return tryBruteforceGame(other, Lose.scores)
}
fun tryDraw(other: Figure): Figure {
return tryBruteforceGame(other, Draw.scores)
}
fun selectRightFigure(left: Figure, prompt: String): Figure {
return when (prompt) {
"X" -> tryLose(left)
"Y" -> tryDraw(left)
"Z" -> tryWin(left)
else -> throw IllegalStateException()
}
}
fun process(line: String) {
val (leftMarker, rightPrompt) = line.split(' ')
val left = parseFigure(leftMarker)
val right = selectRightFigure(left, rightPrompt)
game(left, right)
}
fun solution(): Long {
return rightScores
}
fun main() {
::main
.javaClass
.getResourceAsStream("/input")!!
.bufferedReader()
.forEachLine(::process)
println(solution())
} | [
{
"class_path": "reactivedevelopment__aoc-2022-2__dac4682/com/adventofcode/DayKt$main$2.class",
"javap": "Compiled from \"Day.kt\"\nfinal class com.adventofcode.DayKt$main$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.lang.String, kotlin.Unit> {\n public... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/treesandgraphs/EvaluateDivision.kt | package treesandgraphs
private data class Vertex(val name: String, val edges: MutableList<Pair<Vertex, Double>>) {
var visited = false
}
class EvaluateDivision {
private val vertexes = mutableMapOf<String, Vertex>()
private fun dfs(v: Vertex, target: Vertex, value: Double): Pair<Boolean, Double> {
v.visited = true
if (v === target) {
return true to value
}
for (e in v.edges) {
if (!e.first.visited) {
val r = dfs(e.first, target, value * e.second)
if (r.first) {
return r
}
}
}
return false to -1.0
}
fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray {
for (i in equations.indices) {
val v1 = vertexes[equations[i][0]] ?: Vertex(equations[i][0], mutableListOf())
val v2 = vertexes[equations[i][1]] ?: Vertex(equations[i][1], mutableListOf())
v1.edges.add(v2 to values[i])
v2.edges.add(v1 to 1.0 / values[i])
vertexes[v1.name] = v1
vertexes[v2.name] = v2
}
val ret = DoubleArray(queries.size) { -1.0 }
for ((i, q) in queries.withIndex()) {
var v1 = vertexes[q[0]]
var v2 = vertexes[q[1]]
if (v1 != null && v2 != null) {
for (entry in vertexes.entries) {
entry.value.visited = false
}
ret[i] = dfs(v1, v2, 1.0).second
}
}
return ret
}
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/treesandgraphs/EvaluateDivision.class",
"javap": "Compiled from \"EvaluateDivision.kt\"\npublic final class treesandgraphs.EvaluateDivision {\n private final java.util.Map<java.lang.String, treesandgraphs.Vertex> vertexes;\n\n public treesandgra... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/treesandgraphs/MostStonesRemovedWithSameRowOrColumn.kt | package treesandgraphs
private var xIndex = mapOf<Int, List<Int>>()
private var yIndex = mapOf<Int, List<Int>>()
private var visited = booleanArrayOf()
private fun dfs(stones: Array<IntArray>, index: Int): Int {
visited[index] = true
var sum = 0
for (i in xIndex[stones[index][0]]!!) {
if (!visited[i]) {
sum += dfs(stones, i) + 1
}
}
for (i in yIndex[stones[index][1]]!!) {
if (!visited[i]) {
sum += dfs(stones, i) + 1
}
}
return sum
}
fun removeStones(stones: Array<IntArray>): Int {
xIndex = stones.indices.groupBy({stones[it][0]},{it})
yIndex = stones.indices.groupBy({stones[it][1]},{it})
visited = BooleanArray(stones.size) { false }
var stonesToRemove = 0
for (i in stones.indices) {
if (!visited[i]) {
stonesToRemove += dfs(stones, i)
}
}
return stonesToRemove
}
fun main() {
println(removeStones(arrayOf(intArrayOf(0, 0), intArrayOf(0, 1), intArrayOf(1, 0),
intArrayOf(1, 2), intArrayOf(2, 1), intArrayOf(2, 2))))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/treesandgraphs/MostStonesRemovedWithSameRowOrColumnKt.class",
"javap": "Compiled from \"MostStonesRemovedWithSameRowOrColumn.kt\"\npublic final class treesandgraphs.MostStonesRemovedWithSameRowOrColumnKt {\n private static java.util.Map<java.lang... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/treesandgraphs/LongestIncreasingPathInMatrix.kt | package treesandgraphs
private var memo: Array<IntArray>? = null
private fun dfs(matrix: Array<IntArray>, i: Int, j: Int): Int {
if (memo!![i][j] != -1) {
return memo!![i][j]
}
var maxLength = 0
if (i > 0 && matrix[i - 1][j] > matrix[i][j])
maxLength = maxOf(maxLength, dfs(matrix, i - 1, j))
if (j > 0 && matrix[i][j - 1] > matrix[i][j])
maxLength = maxOf(maxLength, dfs(matrix, i, j - 1))
if (i < matrix.lastIndex && matrix[i + 1][j] > matrix[i][j])
maxLength = maxOf(maxLength, dfs(matrix, i + 1, j))
if (j < matrix[i].lastIndex && matrix[i][j + 1] > matrix[i][j])
maxLength = maxOf(maxLength, dfs(matrix, i, j + 1))
memo!![i][j] = maxLength + 1
return maxLength + 1
}
fun longestIncreasingPath(matrix: Array<IntArray>): Int {
memo = Array<IntArray>(matrix.size) { IntArray(matrix[it].size) { -1 } }
var maxLength = 0
for (i in matrix.indices) {
for (j in matrix[i].indices) {
maxLength = maxOf(maxLength, dfs(matrix, i, j))
}
}
return maxLength
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/treesandgraphs/LongestIncreasingPathInMatrixKt.class",
"javap": "Compiled from \"LongestIncreasingPathInMatrix.kt\"\npublic final class treesandgraphs.LongestIncreasingPathInMatrixKt {\n private static int[][] memo;\n\n private static final int ... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/design/SearchAutocompleteSystem.kt | package design
class AutocompleteSystem(sentences: Array<String>, times: IntArray) {
private class TrieNode {
var leafTimes = 0
val children = mutableMapOf<Char, TrieNode>()
}
private val trieRoot = TrieNode()
private var currentNode: TrieNode
private val prefix = StringBuilder()
init {
for (i in sentences.indices) {
var cur = trieRoot
for (c in sentences[i]) {
if (c !in cur.children) {
cur.children[c] = TrieNode()
}
cur = cur.children[c]!!
}
cur.leafTimes = times[i]
}
currentNode = trieRoot
}
private fun dfsTraverse(prefix: StringBuilder, currentNode: TrieNode, sentencesList: MutableList<Pair<String, Int>>) {
if (currentNode.leafTimes > 0) {
sentencesList.add(prefix.toString() to currentNode.leafTimes)
}
for (entry in currentNode.children.entries.iterator()) {
prefix.append(entry.key)
dfsTraverse(prefix, entry.value, sentencesList)
prefix.deleteCharAt(prefix.lastIndex)
}
}
fun input(c: Char): List<String> {
if (c == '#') {
currentNode.leafTimes++
currentNode = trieRoot
prefix.delete(0, prefix.length)
return listOf<String>()
}
if (c !in currentNode.children) {
currentNode.children[c] = TrieNode()
}
currentNode = currentNode.children[c]!!
prefix.append(c)
val sentencesList = mutableListOf<Pair<String, Int>>()
dfsTraverse(prefix, currentNode, sentencesList)
sentencesList.sortWith(object: Comparator<Pair<String, Int>> {
override fun compare(a: Pair<String, Int>, b: Pair<String, Int>): Int = when {
a.second != b.second -> -a.second + b.second
else -> a.first.compareTo(b.first)
}
})
return if (sentencesList.size < 3) {
sentencesList.map {it.first}
} else {
sentencesList.subList(0, 3).map {it.first}
}
}
}
fun main() {
val obj = AutocompleteSystem(arrayOf("i love you", "island", "iroman", "i love leetcode"), intArrayOf(5, 3, 2, 2))
println(obj.input('i')) // return ["i love you", "island", "i love leetcode"]. There are four sentences that have prefix "i". Among them, "ironman" and "i love leetcode" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode" should be in front of "ironman". Also we only need to output top 3 hot sentences, so "ironman" will be ignored.
println(obj.input(' ')) // return ["i love you", "i love leetcode"]. There are only two sentences that have prefix "i ".
println(obj.input('a')) // return []. There are no sentences that have prefix "i a".
println(obj.input('#')) // return []. The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search.
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/design/SearchAutocompleteSystemKt.class",
"javap": "Compiled from \"SearchAutocompleteSystem.kt\"\npublic final class design.SearchAutocompleteSystemKt {\n public static final void main();\n Code:\n 0: new #8 /... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/recursion/WordSearchII.kt | package recursion
class WordSearchII {
class TrieNode {
val children = HashMap<Char, TrieNode>()
var isLeaf = false
}
private val ret = mutableSetOf<String>()
private var board: Array<CharArray> = arrayOf<CharArray>()
private var m: Int = -1
private var n: Int = -1
private var visited: BooleanArray = booleanArrayOf()
private fun find(i: Int, j: Int, cur: TrieNode, sb: StringBuilder) {
if (board[i][j] in cur.children) {
visited[i * n + j] = true
sb.append(board[i][j])
val next = cur.children[board[i][j]]!!
if (next.isLeaf) {
ret.add(sb.toString())
}
if (i > 0 && !visited[(i - 1) * n + j]) find(i - 1, j, next, sb)
if (i < m - 1 && !visited[(i + 1) * n + j]) find(i + 1, j, next, sb)
if (j > 0 && !visited[i * n + j - 1]) find(i, j - 1, next, sb)
if (j < n - 1 && !visited[i * n + j + 1]) find(i, j + 1, next, sb)
sb.deleteCharAt(sb.lastIndex)
visited[i * n + j] = false
}
}
// O(m * n * max(word length))
fun findWords(board: Array<CharArray>, words: Array<String>): List<String> {
this.board = board
val trieRoot = TrieNode()
for (word in words) {
var cur = trieRoot
for (ch in word) {
if (ch !in cur.children) {
cur.children[ch] = TrieNode()
}
cur = cur.children[ch]!!
}
cur.isLeaf = true
}
m = board.size
n = board[0].size
for (i in 0 until m) {
for (j in 0 until n) {
visited = BooleanArray(m * n) {false}
val sb = StringBuilder()
find(i, j, trieRoot, sb)
}
}
return ret.toList()
}
}
fun main() {
println(WordSearchII().findWords(arrayOf(
charArrayOf('a','b','c','e'),
charArrayOf('x','x','c','d'),
charArrayOf('x','x','b','a')),
arrayOf("abc","abcd")))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/recursion/WordSearchIIKt.class",
"javap": "Compiled from \"WordSearchII.kt\"\npublic final class recursion.WordSearchIIKt {\n public static final void main();\n Code:\n 0: new #8 // class recursion/WordSearchII... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/recursion/AndroidUnlockPatterns.kt | package recursion
private val visited = BooleanArray(9) {false}
fun valid(i: Int, j: Int, ni: Int, nj: Int): Boolean {
val di = Math.abs(i - ni)
val dj = Math.abs(j - nj)
return if ((di == 2 && dj == 2) || (di == 0 && dj == 2) || (di == 2 && dj == 0)) {
val mi = (i + ni) / 2
val mj = (j + nj) / 2
visited[3 * mi + mj]
} else {
true
}
}
fun traverse(i: Int, j: Int, m: Int, n: Int, length: Int): Int {
visited[3 * i + j] = true
var counter = 0
if (length >= m && length <= n) {
counter++
}
for (ni in 0..2) {
for (nj in 0..2) {
if (!visited[3 * ni + nj] && valid(i, j, ni, nj)) {
counter += traverse(ni, nj, m, n, length + 1)
}
}
}
visited[3 * i + j] = false
return counter
}
fun numberOfPatterns(m: Int, n: Int): Int {
var counter = 0
for (i in 0..2) {
for (j in 0..2) {
counter += traverse(i, j, m, n, 1)
}
}
return counter
}
fun main() {
println(numberOfPatterns(1, 2))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/recursion/AndroidUnlockPatternsKt.class",
"javap": "Compiled from \"AndroidUnlockPatterns.kt\"\npublic final class recursion.AndroidUnlockPatternsKt {\n private static final boolean[] visited;\n\n public static final boolean valid(int, int, int,... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/recursion/WordSquares.kt | package recursion
val squares: MutableList<MutableList<String>> = mutableListOf()
data class TrieNode(val children: MutableMap<Char, TrieNode>)
val root = TrieNode(mutableMapOf())
fun traverse(square: MutableList<String>, cur: TrieNode, word: StringBuilder, words: Array<String>) {
if (word.length == words[0].length) {
square.add(word.toString())
search(square, words)
square.removeAt(square.lastIndex)
}
for (entry in cur.children.entries) {
word.append(entry.key)
traverse(square, entry.value, word, words)
word.deleteCharAt(word.lastIndex)
}
}
fun search(square: MutableList<String>, words: Array<String>) {
val n = square.size
if (square.size == words[0].length) {
squares.add(ArrayList(square))
return
}
// following tries for finding the given prefix of n characters
var cur = root
val sb = StringBuilder()
for (i in 0 until n) {
if (square[i][n] in cur!!.children) {
sb.append(square[i][n])
cur = cur.children[square[i][n]]!!
} else {
break
}
}
// traversing the rest of the trie since all words fit
if (sb.length == n) {
traverse(square, cur, sb, words)
}
}
//O(m^n)
fun wordSquares(words: Array<String>): List<List<String>> {
for(word in words) {
var cur = root
for (ch in word) {
if (ch !in cur.children) {
cur.children[ch] = TrieNode(mutableMapOf())
}
cur = cur.children[ch]!!
}
}
search(ArrayList(words[0].length), words)
return squares
}
fun main() {
println(wordSquares(arrayOf("area","lead","wall","lady","ball")))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/recursion/WordSquaresKt.class",
"javap": "Compiled from \"WordSquares.kt\"\npublic final class recursion.WordSquaresKt {\n private static final java.util.List<java.util.List<java.lang.String>> squares;\n\n private static final recursion.TrieNode... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/sortingandsearching/MedianOfTwoSortedArrays.kt | package sortingandsearching
// O(log(min(m, n)))
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val a = if (nums1.size < nums2.size) nums1 else nums2
val b = if (nums1.size < nums2.size) nums2 else nums1
var l = 0
var r = a.size
var i: Int
var j: Int
var found: Boolean
do {
i = (l + r) / 2
j = (a.size + b.size) / 2 - i
found = true
if (i > 0 && i <= a.size && j >= 0 && j < b.size && a[i - 1] > b[j]) {
r = i - 1
found = false
}
if (i >= 0 && i < a.size && j > 0 && j <= b.size && b[j - 1] > a[i]) {
l = i + 1
found = false
}
} while (!found)
val left = maxOf(
if (i > 0 && i <= a.size) a[i - 1] else Int.MIN_VALUE,
if (j > 0 && j <= b.size) b[j - 1] else Int.MIN_VALUE)
val right = minOf(
if (i >= 0 && i < a.size) a[i] else Int.MAX_VALUE,
if (j >= 0 && j < b.size) b[j] else Int.MAX_VALUE)
return if ((a.size + b.size) % 2 == 0)
(left + right) / 2.0
else
right / 1.0
}
fun main() {
println(findMedianSortedArrays(intArrayOf(2,3,4,5,6,7), intArrayOf(1)))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/sortingandsearching/MedianOfTwoSortedArraysKt.class",
"javap": "Compiled from \"MedianOfTwoSortedArrays.kt\"\npublic final class sortingandsearching.MedianOfTwoSortedArraysKt {\n public static final double findMedianSortedArrays(int[], int[]);\n ... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/sortingandsearching/CountOfSmallerNumbersAfterSelf.kt | package sortingandsearching
private const val OFFSET = 10000
private const val SIZE = 2 * 10000 + 1
private val segmentTree = IntArray(4 * SIZE) { 0 }
private fun update(vertex: Int, left: Int, right: Int, pos: Int, value: Int) {
if (left == right) {
segmentTree[vertex] += value
return
}
val middle = (left + right) / 2
if (pos <= middle) {
update(2 * vertex, left, middle, pos, value)
} else {
update(2 * vertex + 1,middle + 1, right, pos, value)
}
segmentTree[vertex] = segmentTree[2 * vertex] + segmentTree[2 * vertex + 1]
}
private fun query(vertex: Int, left: Int, right: Int, queryLeft: Int, queryRight: Int): Int {
if (left == queryLeft && right == queryRight) {
return segmentTree[vertex]
}
val middle = (left + right) / 2
return when {
queryRight <= middle -> query(2 * vertex, left, middle, queryLeft, queryRight)
queryLeft > middle -> query(2 * vertex + 1, middle + 1, right, queryLeft, queryRight)
else -> query(2 * vertex, left, middle, queryLeft, middle) +
query(2 * vertex + 1, middle + 1, right, middle + 1, queryRight)
}
}
// O(N*logN)
private fun countSmaller(nums: IntArray): List<Int> {
val ret = mutableListOf<Int>()
// O(N * logN)
for (num in nums.reversed()) {
// O(logN)
update(1, 0, SIZE, num + OFFSET, 1)
// O(logN)
ret.add(query(1, 0, SIZE, 0, num + OFFSET - 1))
}
return ret.reversed()
}
fun main() {
println(countSmaller(intArrayOf(5,2,6,1)))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/sortingandsearching/CountOfSmallerNumbersAfterSelfKt.class",
"javap": "Compiled from \"CountOfSmallerNumbersAfterSelf.kt\"\npublic final class sortingandsearching.CountOfSmallerNumbersAfterSelfKt {\n private static final int OFFSET;\n\n private ... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/dynamicprogramming/SplitArrayLargestSum.kt | package dynamicprogramming
private var memo = arrayOf<IntArray>()
fun dp(nums: IntArray, m: Int, index: Int): Int {
if (memo[m][index] != -1) {
return memo[m][index]
}
if (m == 1) {
var sum = 0
for (i in index .. nums.lastIndex) {
sum += nums[i]
}
memo[m][index] = sum
return sum
}
var sum = nums[index]
var bestDivide = Int.MAX_VALUE
for (i in index + 1 .. nums.lastIndex) {
val divide = maxOf(sum, dp(nums, m - 1, i))
bestDivide = minOf(divide, bestDivide)
sum += nums[i]
}
memo[m][index] = bestDivide
return bestDivide
}
fun splitArray(nums: IntArray, m: Int): Int {
memo = Array(m + 1) { IntArray(nums.size) { -1 } }
return dp(nums, m, 0)
}
fun main() {
println(splitArray(intArrayOf(7,2,5,10,8), 2))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/dynamicprogramming/SplitArrayLargestSumKt.class",
"javap": "Compiled from \"SplitArrayLargestSum.kt\"\npublic final class dynamicprogramming.SplitArrayLargestSumKt {\n private static int[][] memo;\n\n public static final int dp(int[], int, int);... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/dynamicprogramming/LongestPalindromicSubstring.kt | package dynamicprogramming
private var memo: Array<Array<Boolean?>>? = null
fun isPalindrome(s: String, i: Int, j: Int): Boolean {
if (memo!![i][j] != null) {
return memo!![i][j]!!
}
if (i == j) {
memo!![i][j] = true
return true
}
if (i == j - 1) {
memo!![i][j] = s[i] == s[j]
return s[i] == s[j]
}
val res = s[i] == s[j] && isPalindrome(s, i + 1, j - 1)
memo!![i][j] = res
return res
}
// O(N^2)
fun longestPalindrome(s: String): String {
memo = Array(s.length) {Array<Boolean?>(s.length) {null} }
var ti = s.lastIndex
var tj = 0
for (i in s.indices) {
for (j in i..s.lastIndex) {
if (isPalindrome(s, i, j) && j - i > tj - ti) {
ti = i
tj = j
}
}
}
return s.substring(ti, tj + 1)
}
fun main() {
println(longestPalindrome("ac"))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/dynamicprogramming/LongestPalindromicSubstringKt.class",
"javap": "Compiled from \"LongestPalindromicSubstring.kt\"\npublic final class dynamicprogramming.LongestPalindromicSubstringKt {\n private static java.lang.Boolean[][] memo;\n\n public st... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/dynamicprogramming/MaximumProductSubarray.kt | package dynamicprogramming
fun processSubarray(a: Int, b: Int, negatives: Int, nums: IntArray): Int {
if (a > b) {
return 0
}
if (a == b) {
return nums[a]
}
var i = a
var j = b
var leftProd = 1
var rightProd = 1
if (negatives % 2 == 1) {
while (nums[i] > 0) {
leftProd *= nums[i]
i++
}
while (nums[j] > 0) {
rightProd *= nums[j]
j--
}
if (i == j) {
return maxOf(leftProd, rightProd)
}
return if (-leftProd * nums[i] > -rightProd * nums[j]) {
for (k in i..j - 1) {
leftProd *= nums[k]
}
leftProd
} else {
for (k in j downTo i + 1) {
rightProd *= nums[k]
}
rightProd
}
} else {
var prod = 1
for (k in a..b) {
prod *= nums[k]
}
return prod
}
}
fun maxProduct(nums: IntArray): Int {
var maxProd = Int.MIN_VALUE
var begin = 0
var negatives = 0
for (i in nums.indices) {
if (nums[i] < 0) {
negatives++
}
if (nums[i] == 0) {
val prod = processSubarray(begin, i - 1, negatives, nums)
maxProd = maxOf(prod, maxProd, 0)
negatives = 0
begin = i + 1
}
}
val prod = processSubarray(begin, nums.lastIndex, negatives, nums)
maxProd = maxOf(prod, maxProd)
return maxProd
}
fun main() {
println(maxProduct(intArrayOf(2,3,-2,4)))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/dynamicprogramming/MaximumProductSubarrayKt.class",
"javap": "Compiled from \"MaximumProductSubarray.kt\"\npublic final class dynamicprogramming.MaximumProductSubarrayKt {\n public static final int processSubarray(int, int, int, int[]);\n Code... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/arraysandstrings/NextClosestTime.kt | package arraysandstrings
fun isValid(arr: IntArray): Boolean {
var hour = arr[0] * 10 + arr[1]
var minute = arr[2] * 10 + arr[3]
return hour < 24 && minute < 60
}
fun totalMinutes(arr: IntArray): Int {
var hour = arr[0] * 10 + arr[1]
var minute = arr[2] * 10 + arr[3]
return hour * 60 + minute
}
fun diff(minutes1: Int, minutes2: Int): Int {
return when {
minutes2 > minutes1 -> minutes2 - minutes1
minutes2 > minutes1 -> 60*24 - minutes1 + minutes2
else -> 60*24
}
}
var base: Int = 0
var baseArr: IntArray = intArrayOf()
var minDiff = 60*24 + 1
var res: IntArray = intArrayOf()
fun Char.digitToInt() = this.toInt() - '0'.toInt()
fun traverse(arr: IntArray, start: Int) {
if (start > arr.lastIndex) {
if (isValid(arr)) {
val curDiff = diff(base, totalMinutes(arr))
if (curDiff in 1 until minDiff) {
minDiff = curDiff
res = arr
}
//println(arr.contentToString())
}
return
}
for (j in baseArr.indices) {
val newArr = arr.clone()
newArr[start] = baseArr[j]
traverse(newArr, start + 1)
}
}
fun nextClosestTime(time: String): String {
val arr = intArrayOf(
time[0].digitToInt(),
time[1].digitToInt(),
time[3].digitToInt(),
time[4].digitToInt())
base = totalMinutes(arr)
baseArr = arr.clone()
traverse(arr, 0)
return "${res[0]}${res[1]}:${res[2]}${res[3]}"
}
fun main() {
println(nextClosestTime("19:34"))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/arraysandstrings/NextClosestTimeKt.class",
"javap": "Compiled from \"NextClosestTime.kt\"\npublic final class arraysandstrings.NextClosestTimeKt {\n private static int base;\n\n private static int[] baseArr;\n\n private static int minDiff;\n\n ... |
e-freiman__LeetcodeGoogleInterview__fab7f27/src/main/kotlin/arraysandstrings/MinimumCostToHireKWorkers.kt | package arraysandstrings
import java.util.PriorityQueue
fun mincostToHireWorkers(quality: IntArray, wage: IntArray, k: Int): Double {
val x = wage.indices.sortedWith {a, b ->
val ra = wage[a].toDouble() / quality[a].toDouble()
val rb = wage[b].toDouble() / quality[b].toDouble()
if (ra < rb) -1 else 1
}
val pq = PriorityQueue<Int>(k) {a, b -> b - a}
var minGroupPay = Double.MAX_VALUE
var sum = 0
for (i in x.indices) {
val cost = wage[x[i]].toDouble() / quality[x[i]].toDouble()
pq.add(quality[x[i]])
sum += quality[x[i]]
if (pq.size > k) {
sum -= pq.poll()
}
if (pq.size == k) {
minGroupPay = minOf(sum.toDouble() * cost, minGroupPay)
}
}
return minGroupPay
}
fun main() {
println(mincostToHireWorkers(intArrayOf(10,20,5), intArrayOf(70,50,30), 2))
}
| [
{
"class_path": "e-freiman__LeetcodeGoogleInterview__fab7f27/arraysandstrings/MinimumCostToHireKWorkersKt.class",
"javap": "Compiled from \"MinimumCostToHireKWorkers.kt\"\npublic final class arraysandstrings.MinimumCostToHireKWorkersKt {\n public static final double mincostToHireWorkers(int[], int[], int);... |
LostMekka__ray-marcher-kt__ee42321/src/main/kotlin/de/lostmekka/raymarcher/Point.kt | package de.lostmekka.raymarcher
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
data class Point(val x: Double, val y: Double, val z: Double) {
constructor(x: Number, y: Number, z: Number) : this(x.toDouble(), y.toDouble(), z.toDouble())
val length by lazy { sqrt(squaredLength) }
val squaredLength by lazy { x * x + y * y + z * z }
val isNormalized by lazy { squaredLength == 1.0 }
val absoluteValue: Point by lazy { Point(abs(x), abs(y), abs(z)) }
val normalized: Point by lazy { length.takeIf { it != 0.0 }?.let { Point(x / it, y / it, z / it) } ?: Point.zero }
companion object {
val zero = Point(.0, .0, .0)
val right = Point(1.0, .0, .0)
val left = Point(-1.0, .0, .0)
val up = Point(.0, 1.0, .0)
val down = Point(.0, -1.0, .0)
val forward = Point(.0, .0, 1.0)
val backward = Point(.0, .0, -1.0)
}
}
operator fun Point.plus(other: Point) = Point(x + other.x, y + other.y, z + other.z)
operator fun Point.minus(other: Point) = Point(x - other.x, y - other.y, z - other.z)
operator fun Point.unaryMinus() = Point(-x, -y, -z)
operator fun Point.times(scalar: Double) = Point(x * scalar, y * scalar, z * scalar)
operator fun Point.div(scalar: Double) = Point(x / scalar, y / scalar, z / scalar)
infix fun Point.dot(other: Point) = x * other.x + y * other.y + z * other.z
infix fun Point.cross(other: Point) = Point(
x * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x
)
private fun square(scalar: Double) = scalar * scalar
infix fun Point.distanceTo(other: Point) = sqrt(squaredDistanceTo(other))
infix fun Point.squaredDistanceTo(other: Point) = square(x - other.x) + square(y - other.y) + square(z - other.z)
infix fun Point.floorMod(other: Point) = Point(
(x % other.x + other.x) % other.x,
(y % other.y + other.y) % other.y,
(z % other.z + other.z) % other.z
)
data class Matrix(
val a00: Double, val a10: Double, val a20: Double,
val a01: Double, val a11: Double, val a21: Double,
val a02: Double, val a12: Double, val a22: Double
)
operator fun Matrix.times(p: Point) = Point(
a00 * p.x + a10 * p.y + a20 * p.z,
a01 * p.x + a11 * p.y + a21 * p.z,
a02 * p.x + a12 * p.y + a22 * p.z
)
fun xRotationMatrix(angle: Double): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(
1.0, 0.0, 0.0,
0.0, cos, -sin,
0.0, sin, cos
)
}
fun yRotationMatrix(angle: Double): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(
cos, 0.0, sin,
0.0, 1.0, 0.0,
-sin, 0.0, cos
)
}
fun zRotationMatrix(angle: Double): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(
cos, -sin, 0.0,
sin, cos, 0.0,
0.0, 0.0, 1.0
)
}
| [
{
"class_path": "LostMekka__ray-marcher-kt__ee42321/de/lostmekka/raymarcher/PointKt.class",
"javap": "Compiled from \"Point.kt\"\npublic final class de.lostmekka.raymarcher.PointKt {\n public static final de.lostmekka.raymarcher.Point plus(de.lostmekka.raymarcher.Point, de.lostmekka.raymarcher.Point);\n ... |
rbrincke__nontransitive-dice__fc5aa03/src/main/kotlin/io/rbrincke/dice/core/Solver.kt | package io.rbrincke.dice.core
/**
* Sets up a solver that is able to find allocations of [labels] that lead to non-transitive
* elements. The number of resulting elements equals the size of [labelGroupSizes], and each
* element will contain precisely the number specified in [labelGroupSizes].
*
* @param labels labels that are to be allocated to elements
* @param labelGroupSizes the group sizes in which labels should be allocated (sum of all elements must equal the size of [labels])
* @param elementCreator function that describes how to to create an element from a list of [labels]
*/
class Solver<S, T : Element<T>>(
private val labels: List<S>,
private val labelGroupSizes: List<Int>,
private val elementCreator: (List<S>) -> T
) {
init {
check(labelGroupSizes.isNotEmpty())
check(labelGroupSizes.all { it > 0 }) {
"Input set sizes must all be strictly positive."
}
check(labelGroupSizes.sum() == labels.size) {
"Input set element count does not equal the total of combination sizes."
}
}
private fun permutationToElementSet(permutation: List<Int>): Combination<T> {
val target = labelGroupSizes.mapIndexed { index, i ->
index to ArrayList<S>(i)
}.toMap()
permutation.mapIndexed { index, i ->
target.getValue(i).add(labels[index])
}
val elements = target.values.map { elementCreator.invoke(it) }
return Combination(elements)
}
/**
* Find any non-transitive [Combination]s.
*/
fun solve(): List<Combination<T>> {
// Perform permutation on a mask to avoid duplicate groupings due
// to group-internal ordering differences.
val mask = mutableListOf<Int>()
labelGroupSizes.forEachIndexed { idx, count ->
repeat(count) { mask.add(idx) }
}
check(mask.size == labels.size)
// Fix the first item to slot 0 to avoid identical solutions
// with rotated positions.
return MultisetPermutationIterator(mask.drop(1))
.asSequence()
.map { listOf(0) + it }
.map(::permutationToElementSet)
.filter { it.isNonTransitive() }
.toList()
}
}
| [
{
"class_path": "rbrincke__nontransitive-dice__fc5aa03/io/rbrincke/dice/core/Solver.class",
"javap": "Compiled from \"Solver.kt\"\npublic final class io.rbrincke.dice.core.Solver<S, T extends io.rbrincke.dice.core.Element<? super T>> {\n private final java.util.List<S> labels;\n\n private final java.util.... |
rbrincke__nontransitive-dice__fc5aa03/src/main/kotlin/io/rbrincke/dice/core/MultisetPermutationIterator.kt | package io.rbrincke.dice.core
/**
* Multiset permutation iterator. Not thread safe.
*
* See *"Loopless Generation of Multiset Permutations using a Constant Number
* of Variables by Prefix Shifts."*, <NAME>, 2009.
*/
class MultisetPermutationIterator<E : Comparable<E>>(input: Collection<E>) : Iterator<List<E>> {
private val nodes: List<Node<E>>
private var head: Node<E>
private var i: Node<E>? = null
private var afteri: Node<E>
private var pristine = true
init {
check(input.isNotEmpty())
nodes = initializeNodeList(input)
head = nodes[0]
if (input.size > 1) {
i = nodes[nodes.size - 2]
}
afteri = nodes[nodes.size - 1]
}
private fun initializeNodeList(input: Collection<E>): List<Node<E>> {
val nodes = input.reversed().map { Node(it) }.toList()
for (i in 0 until nodes.size - 1) {
nodes[i].next = nodes[i + 1]
}
return nodes
}
/**
* Returns `true` if another permutation is available. (In other words, returns
* true if the next call to [next] would return a permutation rather than
* throwing an exception).
*/
override fun hasNext(): Boolean {
return pristine || afteri.next != null || afteri.value < head.value
}
/**
* Returns the next permutation.
* @throws NoSuchElementException if there are no more permutations
*/
override fun next(): List<E> {
if (!hasNext()) {
throw NoSuchElementException()
}
if (pristine) {
pristine = false
return visit(head)
}
val afteriNext = afteri.next
val beforek: Node<E> = if (afteriNext != null && i!!.value >= afteriNext.value) {
afteri
} else {
i!!
}
val k = beforek.next
checkNotNull(k)
beforek.next = k.next
k.next = head
if (k.value < head.value) {
i = k
}
afteri = i!!.next!!
head = k
return visit(head)
}
private fun visit(node: Node<E>): List<E> {
val values = ArrayList<E>(nodes.size)
values.add(node.value)
var current = node
while (current.next != null) {
current = current.next!!
values.add(current.value)
}
return values
}
}
private class Node<E : Comparable<E>>(val value: E) {
var next: Node<E>? = null
}
| [
{
"class_path": "rbrincke__nontransitive-dice__fc5aa03/io/rbrincke/dice/core/MultisetPermutationIterator.class",
"javap": "Compiled from \"MultisetPermutationIterator.kt\"\npublic final class io.rbrincke.dice.core.MultisetPermutationIterator<E extends java.lang.Comparable<? super E>> implements java.util.It... |
rbrincke__nontransitive-dice__fc5aa03/src/main/kotlin/io/rbrincke/dice/core/Combination.kt | package io.rbrincke.dice.core
class Combination<T : Element<T>>(private val elements: List<T>) {
init {
check(elements.isNotEmpty()) { "Elements may not be empty." }
}
/**
* Matches element 1 to 2, ..., N - 1 to N, N to 1.
*/
private val elementPairs = elements.mapIndexed { currentIdx, current ->
val other = elements[(currentIdx + 1) % elements.size]
current to other
}
/**
* For the N elements in this set, compute the probability that die 1 beats die 2,
* ..., N - 1 beats N, N beats 1.
*/
private val dominanceProbabilities = elementPairs.map { (current, other) ->
current.beats(other)
}
val elementPairDominanceProbabilities = elementPairs.zip(dominanceProbabilities)
/**
* True if element 1 beats element 2, ..., N - 1 beats N, N beats 1, false otherwise.
*/
fun isNonTransitive() = dominanceProbabilities.all { v -> v > 0.5 }
/**
* Least of the probabilities that element 1 beats element 2, ..., N - 1 beats N, N beats 1.
*/
fun leastDominance() = dominanceProbabilities.minOrNull() ?: throw IllegalStateException("Empty set.")
/**
* Probability that element 1 beats element 2, ..., N - 1 beats N, N beats 1.
*/
fun dominance() = dominanceProbabilities.toList()
/**
* Pretty prints this combination.
*/
fun prettyPrint() = elementPairDominanceProbabilities.joinToString { (elements, probability) ->
val (current, other) = elements
"$current beats $other with probability $probability"
}
}
interface Element<in E> {
/**
* Probability that this element beats the other element [E]. If draws are possible,
* they are assumed to be resolved by a coin toss.
*/
fun beats(other: E): Double
}
| [
{
"class_path": "rbrincke__nontransitive-dice__fc5aa03/io/rbrincke/dice/core/Combination.class",
"javap": "Compiled from \"Combination.kt\"\npublic final class io.rbrincke.dice.core.Combination<T extends io.rbrincke.dice.core.Element<? super T>> {\n private final java.util.List<T> elements;\n\n private fi... |
AkshayChordiya__advent-of-code-kotlin-2022__ad60a71/src/com/akshay/adventofcode/Day05.kt | package com.akshay.adventofcode
import java.io.File
data class Move(val quantity: Int, val source: Int, val target: Int) {
companion object {
fun of(line: String): Move {
return line
.split(" ")
.filterIndexed { index, _ -> index % 2 == 1 }
.map { it.toInt() }
.let { Move(it[0], it[1] - 1, it[2] - 1) }
}
}
}
/**
* Advent of Code 2022 - Day 5 (Supply Stacks)
* http://adventofcode.com/2022/day/5
*/
class Day05 {
fun partOne(stacks: List<ArrayDeque<Char>>, moves: List<Move>): String {
moves.forEach { move -> repeat(move.quantity) { stacks[move.target].addFirst(stacks[move.source].removeFirst()) } }
return stacks.map { it.first() }.joinToString(separator = "")
}
fun partTwo(stacks: List<ArrayDeque<Char>>, moves: List<Move>): String {
moves.forEach { step ->
stacks[step.source]
.subList(0, step.quantity)
.asReversed()
.map { stacks[step.target].addFirst(it) }
.map { stacks[step.source].removeFirst() }
}
return stacks.map { it.first() }.joinToString(separator = "")
}
fun populateStacks(lines: List<String>, onCharacterFound: (Int, Char) -> Unit) {
lines
.filter { it.contains("[") }
.forEach { line ->
line.mapIndexed { index, char ->
if (char.isLetter()) {
val stackNumber = index / 4
val value = line[index]
onCharacterFound(stackNumber, value)
}
}
}
}
}
fun main() {
val lines = File("input.txt").readLines()
val day05 = Day05()
// Calculate number of stacks needed
val stacks = List(9) { ArrayDeque<Char>() }
// Fill the stacks
day05.populateStacks(lines) { stackNumber, value ->
stacks[stackNumber].addLast(value)
}
// Get the moves
val moves = lines.filter { it.contains("move") }.map { Move.of(it) }
// Perform the moves
println(day05.partOne(stacks.map { ArrayDeque(it) }.toList(), moves))
println(day05.partTwo(stacks, moves))
} | [
{
"class_path": "AkshayChordiya__advent-of-code-kotlin-2022__ad60a71/com/akshay/adventofcode/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class com.akshay.adventofcode.Day05Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io... |
why168__JavaProjects__c642d97/Kotlinlang/src/examples/longerExamples/Maze.kt | package examples.longerExamples
import java.util.*
/**
* Let's Walk Through a Maze.
*
* Imagine there is a maze whose walls are the big 'O' letters.
* Now, I stand where a big 'I' stands and some cool prize lies
* somewhere marked with a '$' sign. Like this:
*
* OOOOOOOOOOOOOOOOO
* O O
* O$ O O
* OOOOO O
* O O
* O OOOOOOOOOOOOOO
* O O I O
* O O
* OOOOOOOOOOOOOOOOO
*
* I want to get the prize, and this program helps me do so as soon
* as I possibly can by finding a shortest path through the maze.
*
* @author Edwin.Wu
* @version 2018/2/3 下午7:10
* @since JDK1.8
*/
/**
* Declare a point class.
*/
data class Point(val i: Int, val j: Int)
/**
* This function looks for a path from max.start to maze.end through
* free space (a path does not go through walls). One can move only
* straight up, down, left or right, no diagonal moves allowed.
*/
fun findPath(maze: Maze): List<Point>? {
val previous = hashMapOf<Point, Point>()
val queue = LinkedList<Point>()
val visited = hashSetOf<Point>()
queue.offer(maze.start)
visited.add(maze.start)
while (!queue.isEmpty()) {
val cell = queue.poll()
if (cell == maze.end) break
for (newCell in maze.neighbors(cell.i, cell.j)) {
if (newCell in visited) continue
previous.put(newCell, cell)
queue.offer(newCell)
visited.add(cell)
}
}
if (previous[maze.end] == null) return null
val path = arrayListOf<Point>()
var current = previous[maze.end]!!
while (current != maze.start) {
path.add(0, current)
current = previous[current]!!
}
return path
}
/**
* Find neighbors of the (i, j) cell that are not walls
*/
fun Maze.neighbors(i: Int, j: Int): List<Point> {
val result = arrayListOf<Point>()
addIfFree(i - 1, j, result)
addIfFree(i, j - 1, result)
addIfFree(i + 1, j, result)
addIfFree(i, j + 1, result)
return result
}
fun Maze.addIfFree(i: Int, j: Int, result: MutableList<Point>) {
if (i !in 0..height - 1) return
if (j !in 0..width - 1) return
if (walls[i][j]) return
result.add(Point(i, j))
}
/**
* A data class that represents a maze
*/
class Maze(
// Number or columns
val width: Int,
// Number of rows
val height: Int,
// true for a wall, false for free space
val walls: Array<BooleanArray>,
// The starting point (must not be a wall)
val start: Point,
// The target point (must not be a wall)
val end: Point
) {
}
/** A few maze examples here */
fun main(args: Array<String>) {
walkThroughMaze("I $")
walkThroughMaze("I O $")
walkThroughMaze("""
O $
O
O
O
O I
""")
walkThroughMaze("""
OOOOOOOOOOO
O $ O
OOOOOOO OOO
O O
OOOOO OOOOO
O O
O OOOOOOOOO
O OO
OOOOOO IO
""")
walkThroughMaze("""
OOOOOOOOOOOOOOOOO
O O
O$ O O
OOOOO O
O O
O OOOOOOOOOOOOOO
O O I O
O O
OOOOOOOOOOOOOOOOO
""")
}
// UTILITIES
fun walkThroughMaze(str: String) {
val maze = makeMaze(str)
println("Maze:")
val path = findPath(maze)
for (i in 0..maze.height - 1) {
for (j in 0..maze.width - 1) {
val cell = Point(i, j)
print(
if (maze.walls[i][j]) "O"
else if (cell == maze.start) "I"
else if (cell == maze.end) "$"
else if (path != null && path.contains(cell)) "~"
else " "
)
}
println("")
}
println("Result: " + if (path == null) "No path" else "Path found")
println("")
}
/**
* A maze is encoded in the string s: the big 'O' letters are walls.
* I stand where a big 'I' stands and the prize is marked with
* a '$' sign.
*
* Example:
*
* OOOOOOOOOOOOOOOOO
* O O
* O$ O O
* OOOOO O
* O O
* O OOOOOOOOOOOOOO
* O O I O
* O O
* OOOOOOOOOOOOOOOOO
*/
fun makeMaze(s: String): Maze {
val lines = s.split('\n')
val longestLine = lines.toList().maxBy { it.length } ?: ""
val data = Array(lines.size) { BooleanArray(longestLine.length) }
var start: Point? = null
var end: Point? = null
for (line in lines.indices) {
for (x in lines[line].indices) {
val c = lines[line][x]
when (c) {
'O' -> data[line][x] = true
'I' -> start = Point(line, x)
'$' -> end = Point(line, x)
}
}
}
return Maze(longestLine.length, lines.size, data,
start ?: throw IllegalArgumentException("No starting point in the maze (should be indicated with 'I')"),
end ?: throw IllegalArgumentException("No goal point in the maze (should be indicated with a '$' sign)"))
}
| [
{
"class_path": "why168__JavaProjects__c642d97/examples/longerExamples/Maze.class",
"javap": "Compiled from \"Maze.kt\"\npublic final class examples.longerExamples.Maze {\n private final int width;\n\n private final int height;\n\n private final boolean[][] walls;\n\n private final examples.longerExampl... |
soniro__nonogram-solver__6cc0f04/src/main/kotlin/de/soniro/nonogramsolver/Nonogram.kt | package de.soniro.nonogramsolver
import de.soniro.nonogramsolver.Cell.*
enum class Cell(val char: Char) {
FILL('\u2588'),
EMPTY(' '),
NOT_FILLED('X'),
UNKNOWN('?');
override fun toString(): String = "$char"
}
class Nonogram(val rows: Array<IntArray>, val columns: Array<IntArray>) {
val grid: Array<Array<Any>>
private val columnOffset: Int
private val rowOffset: Int
init {
columnOffset = longestSubArray(rows)
rowOffset = longestSubArray(columns)
grid = Array(numberOfRows()) { row ->
Array<Any>(numberOfColumns()) { column ->
if (row > columnOffset && column > rowOffset) UNKNOWN else EMPTY
}
}
writeColumns()
writeRows()
}
private fun writeColumns() =
(rowOffset downTo 1).forEach { i ->
(0..columns.size - 1).forEach { j ->
if (columns[j].size >= i) {
grid[rowOffset - i][columnOffset + j] = columns[j][columns[j].size - i]
}
}
}
private fun writeRows() =
(columnOffset downTo 1).forEach { i ->
(0..rows.size - 1).forEach { j ->
if (rows[j].size >= i) {
grid[rowOffset + j][columnOffset - i] = rows[j][rows[j].size - i]
}
}
}
private fun numberOfColumns(): Int = columnOffset + columns.size
private fun numberOfRows(): Int = rowOffset + rows.size
private fun longestSubArray(array: Array<IntArray>): Int = array.maxBy { it.size }!!.size
fun print() = grid.forEach { row ->
row.forEach { cell -> print("$cell ") }
println()
}
fun fillTrivialRows() =
rows.forEachIndexed { index, row -> fillRowIfTrivial(index, row) }
fun fillRowIfTrivial(currentRowIndex: Int, row: IntArray) {
if (row.sum() + row.size - 1 == columns.size) {
var index = columnOffset
val rowIndex = rowOffset + currentRowIndex
row.forEach { value ->
repeat(value) {
grid[rowIndex][index] = FILL
index++
}
if (index < numberOfColumns() - 1) {
grid[rowIndex][index] = NOT_FILLED
index++
}
}
}
}
fun fillTrivialColumns() {
for ((currentColumnIndex, column) in columns.withIndex()) {
if (column.sum() + column.size - 1 == rows.size) {
var index = rowOffset
val columnIndex = columnOffset + currentColumnIndex
for (value in column) {
repeat(value) {
grid[index][columnIndex] = FILL
index++
}
if (index < numberOfRows() - 1) {
grid[index][columnIndex] = NOT_FILLED
index++
}
}
}
}
}
fun writeColumn(columnWithContent: Array<Cell>, columnIndex: Int) {
columnWithContent.forEachIndexed { cellIndex, cell ->
grid[cellIndex + rowOffset][columnIndex] = cell
}
}
} | [
{
"class_path": "soniro__nonogram-solver__6cc0f04/de/soniro/nonogramsolver/Nonogram.class",
"javap": "Compiled from \"Nonogram.kt\"\npublic final class de.soniro.nonogramsolver.Nonogram {\n private final int[][] rows;\n\n private final int[][] columns;\n\n private final java.lang.Object[][] grid;\n\n pr... |
MikeDepies__NeatKotlin__215f13f/neat-core/src/main/kotlin/neat/novelty/Levenshtein.kt | package neat.novelty
import kotlin.math.min
fun levenshtein(lhs: CharSequence, rhs: CharSequence): Int {
if (lhs == rhs) {
return 0
}
if (lhs.isEmpty()) {
return rhs.length
}
if (rhs.isEmpty()) {
return lhs.length
}
val lhsLength = lhs.length + 1
val rhsLength = rhs.length + 1
var cost = Array(lhsLength) { it }
var newCost = Array(lhsLength) { 0 }
for (i in 1 until rhsLength) {
newCost[0] = i
for (j in 1 until lhsLength) {
val match = if (lhs[j - 1] == rhs[i - 1]) 0 else 1
val costReplace = cost[j - 1] + match
val costInsert = cost[j] + 1
val costDelete = newCost[j - 1] + 1
newCost[j] = min(min(costInsert, costDelete), costReplace)
}
val swap = cost
cost = newCost
newCost = swap
}
return cost[lhsLength - 1]
}
fun levenshtein(lhs: List<Int>, rhs: List<Int>): Int {
if (lhs == rhs) {
return 0
}
if (lhs.isEmpty()) {
return rhs.size
}
if (rhs.isEmpty()) {
return lhs.size
}
val lhsLength = lhs.size + 1
val rhsLength = rhs.size + 1
var cost = Array(lhsLength) { it }
var newCost = Array(lhsLength) { 0 }
for (i in 1 until rhsLength) {
newCost[0] = i
for (j in 1 until lhsLength) {
val match = if (lhs[j - 1] == rhs[i - 1]) 0 else 1
val costReplace = cost[j - 1] + match
val costInsert = cost[j] + 1
val costDelete = newCost[j - 1] + 1
newCost[j] = min(min(costInsert, costDelete), costReplace)
}
val swap = cost
cost = newCost
newCost = swap
}
return cost[lhsLength - 1]
} | [
{
"class_path": "MikeDepies__NeatKotlin__215f13f/neat/novelty/LevenshteinKt.class",
"javap": "Compiled from \"Levenshtein.kt\"\npublic final class neat.novelty.LevenshteinKt {\n public static final int levenshtein(java.lang.CharSequence, java.lang.CharSequence);\n Code:\n 0: aload_0\n 1: ldc... |
kristofersokk__Google-coding-competitions__3ebd59d/src/main/kotlin/roundC2021/smallerstrings.kt | package roundC2021
import kotlin.math.max
import kotlin.math.min
fun main() {
val cases = readLine()!!.toInt()
(1..cases).forEach { caseIndex ->
val (N, K) = readLine()!!.split(" ").map { it.toLong() }
val S = readLine()!!
if (N == 1L) {
val y = max(min((S[0].letterNr).code.toLong(), K), 0)
println("Case #$caseIndex: $y")
} else {
val maxi = (N.toInt() - 1) / 2
val result = algorithm(S, K, 0, maxi)
println("Case #$caseIndex: $result")
}
}
}
private fun Long.modPow(power: Long, mod: Long): Long {
if (power == 0L) {
return 1L
}
if (power == 1L) {
return this % mod
}
val halfPower = this.modPow(power / 2L, mod)
return if (power % 2 == 0L) {
(halfPower * halfPower) % mod
} else {
val halfPlusOnePower = (halfPower * this) % mod
(halfPower * halfPlusOnePower) % mod
}
}
private fun algorithm(S: String, K: Long, index: Int, maxi: Int): Long {
if (index > maxi) {
return 0
}
val possibleSmallerLetters = max(min((S[index].letterNr).code.toLong(), K), 0)
var result = (possibleSmallerLetters * K.modPow((maxi - index).toLong(), 1000000007)).appropriateMod()
if (K >= S[index].letterNr.code.toLong()) {
if (index == maxi) {
if (S.length % 2 == 0) {
val half = S.substring(0..index)
if (half + half.reversed() < S) {
result += 1
}
} else {
val half = S.substring(0 until index)
if (half + S[index] + half.reversed() < S) {
result += 1
}
}
} else {
result = (result + algorithm(S, K, index + 1, maxi)).appropriateMod()
}
}
return result.appropriateMod()
}
private val Char.letterNr: Char
get() = this - 97
private fun Long.appropriateMod() =
((this % 1000000007) + 1000000007) % 1000000007
| [
{
"class_path": "kristofersokk__Google-coding-competitions__3ebd59d/roundC2021/SmallerstringsKt.class",
"javap": "Compiled from \"smallerstrings.kt\"\npublic final class roundC2021.SmallerstringsKt {\n public static final void main();\n Code:\n 0: invokestatic #12 // Method kotlin... |
jerome-fosse__kotlin-koans__e202925/src/iii_conventions/MyDate.kt | package iii_conventions
import iii_conventions.TimeInterval.*
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) {
fun nextDay(): MyDate = this + DAY
operator fun compareTo(other: MyDate): Int {
if (this.year == other.year) {
if (this.month == other.month) {
return this.dayOfMonth.compareTo(other.dayOfMonth)
} else {
return this.month.compareTo(other.month)
}
} else {
return this.year.compareTo(other.year)
}
}
operator fun rangeTo(other: MyDate): DateRange {
return DateRange(this, other)
}
operator fun plus(ti: TimeInterval): MyDate {
return this.plus(RepeatedTimeInterval(ti))
}
operator fun plus(ti: RepeatedTimeInterval): MyDate {
fun addDays(myDate: MyDate, days: Int): MyDate {
fun isLeapYear(year: Int): Boolean = year % 4 == 0
fun loop(md: MyDate, toadd: Int, added: Int): MyDate {
val remainingDays = when(md.month) {
0,2,4,6,7,9,11 -> 31 - md.dayOfMonth
1 -> if (isLeapYear(md.year)) 29 - md.dayOfMonth else 28 - md.dayOfMonth
else -> 30 - md.dayOfMonth
}
return when {
toadd == 0 -> md
toadd <= remainingDays -> md.copy(dayOfMonth = md.dayOfMonth + toadd)
month < 11 -> loop(md.copy(month = md.month + 1, dayOfMonth = 1), toadd - remainingDays - 1, added + remainingDays + 1)
else -> loop(md.copy(year = md.year + 1, month = 0, dayOfMonth = 1), toadd - remainingDays - 1, added + remainingDays + 1)
}
}
return loop(myDate, days, 0)
}
fun addYear(n: Int): MyDate = this.copy(year = year + 1 * n)
return when(ti.timeInterval) {
DAY -> addDays(this, 1 * ti.times)
WEEK -> addDays(this, 7 * ti.times)
YEAR -> addYear(ti.times)
}
}
}
enum class TimeInterval {
DAY,
WEEK,
YEAR;
operator fun times(n: Int): RepeatedTimeInterval = RepeatedTimeInterval(this, n)
}
data class RepeatedTimeInterval(val timeInterval: TimeInterval, val times: Int = 1)
class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> {
override fun iterator(): Iterator<MyDate> {
fun loop(collection: Collection<MyDate>, start: MyDate, end: MyDate): Iterator<MyDate> {
return when {
start < end -> loop(collection.plus(start), start.nextDay(), end)
start == end -> collection.plus(start).iterator()
else -> collection.iterator()
}
}
return loop(ArrayList(), start, endInclusive)
}
operator fun contains(myDate : MyDate) : Boolean {
return myDate >= start && myDate <= endInclusive
}
} | [
{
"class_path": "jerome-fosse__kotlin-koans__e202925/iii_conventions/MyDate$WhenMappings.class",
"javap": "Compiled from \"MyDate.kt\"\npublic final class iii_conventions.MyDate$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 ... |
mopsalarm__Pr0__6e974f9/app/src/main/java/com/pr0gramm/app/services/Graph.kt | package com.pr0gramm.app.services
/**
* A simple graph of double values.
*/
data class Graph(val firstX: Double, val lastX: Double, val points: List<Graph.Point>) {
constructor(points: List<Graph.Point>) : this(points.first().x, points.last().x, points)
val range = firstX.rangeTo(lastX)
val first get() = points.first()
val last get() = points.last()
val isEmpty: Boolean
get() = points.isEmpty()
val maxValue: Double
get() {
return points.maxOf { it.y }
}
val minValue: Double
get() {
return points.minOf { it.y }
}
operator fun get(idx: Int): Point {
return points[idx]
}
data class Point(val x: Double, val y: Double)
fun sampleEquidistant(steps: Int, start: Double = range.start, end: Double = range.endInclusive): Graph {
return Graph((0 until steps).map { idx ->
// the x position that is at the sampling point
val x = start + (end - start) * idx / (steps - 1)
val y = valueAt(x)
Point(x, y)
})
}
fun valueAt(x: Double): Double {
// find first point that is right of our query point.
val largerIndex = points.indexOfFirst { it.x >= x }
if (largerIndex == -1) {
// we did not found a point that is right of x, so we take the value of the
// right most point we know.
return last.y
}
if (largerIndex == 0) {
// the left-most point is already right of x, so take value of the first point.
return first.y
}
// get points a and b.
val a = points[largerIndex - 1]
val b = points[largerIndex]
// interpolate the value at x between a.x and b.x using m as the ascend
val m = (b.y - a.y) / (b.x - a.x)
return a.y + m * (x - a.x)
}
}
fun <T> optimizeValuesBy(values: List<T>, get: (T) -> Double): List<T> {
return values.filterIndexed { idx, value ->
val v = get(value)
idx == 0 || idx == values.size - 1 || get(values[idx - 1]) != v || v != get(values[idx + 1])
}
}
| [
{
"class_path": "mopsalarm__Pr0__6e974f9/com/pr0gramm/app/services/Graph$Point.class",
"javap": "Compiled from \"Graph.kt\"\npublic final class com.pr0gramm.app.services.Graph$Point {\n private final double x;\n\n private final double y;\n\n public com.pr0gramm.app.services.Graph$Point(double, double);\n... |
romanthekat__advent_of_code__f410f71/2019/task_13/src/main/kotlin/task_13/App.kt | package task_13
import java.io.File
import java.lang.RuntimeException
class App {
fun solveFirst(input: String): Int {
val tiles = HashMap<Point, Tile>()
val computer = IntcodeComputer(input)
while (!computer.isHalt) {
val x = computer.run()
val y = computer.run()
val tileId = computer.run()
tiles[Point(x.toInt(), y.toInt())] = Tile.of(tileId.toInt())
}
return tiles.filterValues { it == Tile.BLOCK }.size
}
//TODO pretty bad code
fun solveSecond(input: String): Long {
val tiles = HashMap<Point, Tile>()
val computer = IntcodeComputer(input)
computer.state[0] = 2 //add coins
var score = 0L
while (!computer.isHalt) {
val x = computer.run()
val y = computer.run()
val tileId = computer.run()
if (isScoreOutput(x, y)) {
score = tileId
} else {
tiles[Point(x.toInt(), y.toInt())] = Tile.of(tileId.toInt())
}
val (paddleFound, paddlePos) = get(tiles, Tile.HORIZONTAL_PADDLE)
val (ballFound, ballPos) = get(tiles, Tile.BALL)
if (paddleFound && ballFound) {
when {
ballPos.x < paddlePos.x -> {
setInput(computer, -1)
}
ballPos.x > paddlePos.x -> {
setInput(computer, 1)
}
else -> {
setInput(computer, 0)
}
}
}
}
return score
}
private fun setInput(computer: IntcodeComputer, input: Int) {
if (computer.inputValues.size < 1) {
computer.addInput(input.toLong())
} else {
computer.inputValues[0] = input.toLong()
}
}
private fun get(tiles: HashMap<Point, Tile>, tileToFind: Tile): Pair<Boolean, Point> {
for ((point, tile) in tiles) {
if (tile == tileToFind) {
return Pair(true, point)
}
}
return Pair(false, Point(-1, -1))
}
private fun printTiles(tiles: HashMap<Point, Tile>) {
val minX = tiles.minBy { it.key.x }!!.key.x
val maxX = tiles.maxBy { it.key.x }!!.key.x
val minY = tiles.minBy { it.key.y }!!.key.y
val maxY = tiles.maxBy { it.key.y }!!.key.y
for (y in minY..maxY) {
for (x in minX..maxX) {
val tile = tiles[Point(x, y)]
if (tile != null) {
print(tile.symbol)
}
}
println()
}
}
private fun isScoreOutput(x: Long, y: Long) = x == -1L && y == 0L
}
enum class Tile(val symbol: Char) {
EMPTY(' '),
WALL('#'),
BLOCK('█'),
HORIZONTAL_PADDLE('P'),
BALL('O');
companion object {
fun of(id: Int): Tile {
return when (id) {
0 -> EMPTY
1 -> WALL
2 -> BLOCK
3 -> HORIZONTAL_PADDLE
4 -> BALL
else -> throw RuntimeException("unknown tile id $id")
}
}
}
}
data class Point(val x: Int, val y: Int)
class IntcodeComputer(input: String) {
var isHalt = false
var state = getStateByInput(input)
private var ptr = 0
private var relativeBase = 0
private val extendedMemory = HashMap<Int, Long>()
var inputValues = mutableListOf<Long>()
private var outputValue = 0L
fun addInput(vararg input: Long): IntcodeComputer {
input.forEach { inputValues.add(it) }
return this
}
fun run(stopAtOutput: Boolean = true): Long {
var ptrInc = 0
while (true) {
var finished = false
isHalt = false
val num = state[ptr]
var opcode = num
var firstOperandMode = Mode.POSITION
var secondOperandMode = Mode.POSITION
var thirdOperandMode = Mode.POSITION
if (num.specifiesParamMode()) {
val parameterModes = num.toString()
opcode = parameterModes[parameterModes.length - 1].toString().toLong()
firstOperandMode = getOperandMode(parameterModes, parameterModes.length - 3)
secondOperandMode = getOperandMode(parameterModes, parameterModes.length - 4)
thirdOperandMode = getOperandMode(parameterModes, parameterModes.length - 5)
}
when (opcode) {
1L -> {
ptrInc = opcodeAdd(firstOperandMode, secondOperandMode, thirdOperandMode)
}
2L -> {
ptrInc = opcodeMult(firstOperandMode, secondOperandMode, thirdOperandMode)
}
3L -> {
ptrInc = opcodeSaveTo(firstOperandMode, getInput(inputValues))
}
4L -> {
val result = opcodeGetFrom(firstOperandMode)
outputValue = result.first
ptrInc = result.second
if (stopAtOutput) finished = true
}
5L -> {
ptr = opcodeJumpIfTrue(firstOperandMode, secondOperandMode)
ptrInc = 0
}
6L -> {
ptr = opcodeJumpIfFalse(firstOperandMode, secondOperandMode)
ptrInc = 0
}
7L -> {
ptrInc = opcodeLessThan(firstOperandMode, secondOperandMode, thirdOperandMode)
}
8L -> {
ptrInc = opcodeEquals(firstOperandMode, secondOperandMode, thirdOperandMode)
}
9L -> {
ptrInc = opcodeAdjustRelativeBase(firstOperandMode)
}
99L -> {
isHalt = true
}
else -> {
println("unknown value of $num")
}
}
ptr += ptrInc
if (finished || isHalt) break
}
return outputValue
}
private fun getInput(inputValues: MutableList<Long>): Long {
val result = inputValues[0]
inputValues.removeAt(0)
return result
}
private fun getOperandMode(parameterModes: String, index: Int): Mode {
return if (index < 0) {
Mode.POSITION
} else {
Mode.of(parameterModes[index])
}
}
fun Long.specifiesParamMode(): Boolean {
return this > 99
}
fun opcodeAdd(firstOperand: Mode, secondOperand: Mode, thirdOperandMode: Mode): Int {
val first = get(firstOperand, ptr + 1)
val second = get(secondOperand, ptr + 2)
val resultPtr = getIndex(thirdOperandMode, ptr + 3)
setByIndex(resultPtr, first + second)
return 4
}
fun opcodeMult(firstOperand: Mode, secondOperand: Mode, thirdOperandMode: Mode): Int {
val first = get(firstOperand, ptr + 1)
val second = get(secondOperand, ptr + 2)
val resultPtr = getIndex(thirdOperandMode, ptr + 3)
setByIndex(resultPtr, first * second)
return 4
}
fun opcodeSaveTo(firstOperand: Mode, input: Long): Int {
val resultPtr = getIndex(firstOperand, ptr + 1)
setByIndex(resultPtr, input)
return 2
}
fun opcodeGetFrom(firstOperandMode: Mode): Pair<Long, Int> {
val result = get(firstOperandMode, ptr + 1)
//getByIndex(relativeBase + getByIndex(index).toInt())
return Pair(result, 2)
}
fun opcodeJumpIfTrue(firstOperand: Mode, secondOperand: Mode): Int {
val first = get(firstOperand, ptr + 1)
val second = get(secondOperand, ptr + 2)
return if (first != 0L) {
second.toInt()
} else {
ptr + 3
}
}
fun opcodeJumpIfFalse(firstOperand: Mode, secondOperand: Mode): Int {
val first = get(firstOperand, ptr + 1)
val second = get(secondOperand, ptr + 2)
return if (first == 0L) {
second.toInt()
} else {
ptr + 3
}
}
fun opcodeLessThan(firstOperand: Mode, secondOperand: Mode, thirdOperandMode: Mode): Int {
val first = get(firstOperand, ptr + 1)
val second = get(secondOperand, ptr + 2)
val resultPtr = getIndex(thirdOperandMode, ptr + 3)
setByIndex(resultPtr, if (first < second) 1 else 0)
return 4
}
fun opcodeEquals(firstOperand: Mode, secondOperand: Mode, thirdOperandMode: Mode): Int {
val first = get(firstOperand, ptr + 1)
val second = get(secondOperand, ptr + 2)
val resultPtr = getIndex(thirdOperandMode, ptr + 3)
setByIndex(resultPtr, if (first == second) 1 else 0)
return 4
}
fun opcodeAdjustRelativeBase(firstOperand: Mode): Int {
val first = get(firstOperand, ptr + 1)
relativeBase += first.toInt()
return 2
}
private fun getStateByInput(input: String) = input.split(',').map { it.toLong() }.toMutableList()
fun get(operand: Mode, ptr: Int): Long {
return when (operand) {
Mode.POSITION -> getPositionMode(ptr)
Mode.IMMEDIATE -> getImmediateMode(ptr)
Mode.RELATIVE -> getRelativeMode(ptr, relativeBase)
}
}
fun getIndex(operand: Mode, ptr: Int): Int {
return when (operand) {
Mode.POSITION -> getByIndex(ptr).toInt()
Mode.RELATIVE -> relativeBase + getByIndex(ptr).toInt()
else -> throw RuntimeException("Can't use $operand to get address to write")
}
}
fun getPositionMode(index: Int): Long = getByIndex(getByIndex(index).toInt())
fun getImmediateMode(index: Int): Long = getByIndex(index)
fun getRelativeMode(index: Int, relativeBase: Int): Long = getByIndex(relativeBase + getByIndex(index).toInt())
fun getByIndex(index: Int): Long {
if (index >= state.size) {
return extendedMemory.getOrDefault(index, 0)
}
return state[index]
}
fun setByIndex(index: Int, value: Long) {
if (index >= state.size) {
extendedMemory[index] = value
} else {
state[index] = value
}
}
enum class Mode {
POSITION, IMMEDIATE, RELATIVE;
companion object {
fun of(value: Char): Mode {
return when (value) {
'0' -> POSITION
'1' -> IMMEDIATE
'2' -> RELATIVE
else -> throw RuntimeException("Unknown mode value of $value")
}
}
}
}
}
fun main() {
val app = App()
val input = File("input.txt").readLines()[0]
println(app.solveFirst(input))
println(app.solveSecond(input))
} | [
{
"class_path": "romanthekat__advent_of_code__f410f71/task_13/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class task_13.AppKt {\n public static final void main();\n Code:\n 0: new #8 // class task_13/App\n 3: dup\n 4: invokespecial #11 ... |
romanthekat__advent_of_code__f410f71/2019/task_10/src/main/kotlin/task_10/App.kt | package task_10
import java.io.File
import java.lang.Integer.max
import java.lang.Integer.min
class App {
fun solveFirst(input: List<String>): Int {
val map = Map(input)
var (_, asteroids) = map.getBestLocation()
return asteroids.size
}
fun solveSecond(input: List<String>): Int {
return -1
}
}
class Map(input: List<String>) {
var map = mutableListOf<List<Int>>()
var asteroids = mutableListOf<Point>()
init {
for ((y, line) in input.withIndex()) {
val row = mutableListOf<Int>()
for ((x, value) in line.withIndex()) {
val fieldValue = value.getFieldValue()
if (fieldValue.isAsteroid()) {
asteroids.add(Point(x, y))
}
row.add(fieldValue)
}
map.add(row)
}
}
fun getBestLocation(): Pair<Point, List<Point>> {
var bestPosition = Point(0, 0)
var bestVisibleAsteroids = listOf<Point>()
//TODO use channels
for (asteroid in asteroids) {
val visibleAsteroids = getVisibleAsteroids(asteroid, asteroids)
if (visibleAsteroids.size > bestVisibleAsteroids.size) {
bestPosition = asteroid
bestVisibleAsteroids = visibleAsteroids
}
}
return Pair(bestPosition, bestVisibleAsteroids)
}
private fun getVisibleAsteroids(asteroid: Point, asteroids: MutableList<Point>): List<Point> {
val visibleAsteroids = mutableListOf<Point>()
for (asteroidToCheck in asteroids) {
if (asteroid == asteroidToCheck) {
continue
}
if (hiddenByAsteroids(asteroids, asteroid, asteroidToCheck)) {
continue
}
visibleAsteroids.add(asteroidToCheck)
}
return visibleAsteroids
}
private fun hiddenByAsteroids(asteroids: MutableList<Point>, fromPoint: Point, toPoint: Point): Boolean {
for (asteroid in asteroids) {
if (fromPoint != asteroid && toPoint != asteroid
&& isOnSegment(asteroid, fromPoint, toPoint)) {
return true
}
}
return false
}
fun isOnSegment(point: Point, lineStart: Point, lineEnd: Point): Boolean {
val isOnLine = ((lineStart.y - lineEnd.y) * point.x
+ (lineEnd.x - lineStart.x) * point.y
+ (lineStart.x * lineEnd.y - lineEnd.x * lineStart.y) == 0)
if (!isOnLine) {
return false
}
return point.x > min(lineStart.x, lineEnd.x) && point.x < max(lineStart.x, lineEnd.x)
&& point.y > min(lineStart.y, lineEnd.y) && point.y < max(lineStart.y, lineEnd.y)
}
fun Char.getFieldValue(): Int {
return when (this) {
'.' -> 0
'#' -> 1
else -> throw RuntimeException("unknown value of '$this'")
}
}
fun Int.isAsteroid(): Boolean {
return this == 1
}
data class Point(val x: Int, val y: Int)
}
fun main() {
val app = App()
val input = File("input.txt").readLines()
println(app.solveFirst(input))
println(app.solveSecond(input))
} | [
{
"class_path": "romanthekat__advent_of_code__f410f71/task_10/AppKt.class",
"javap": "Compiled from \"App.kt\"\npublic final class task_10.AppKt {\n public static final void main();\n Code:\n 0: new #8 // class task_10/App\n 3: dup\n 4: invokespecial #11 ... |
ununhexium__samples__11aca6b/src/main/java/sudoku/Sudoku.kt | package sudoku
data class Grid(val given: List<List<Int>>)
data class Guess(val position: Pair<Int,Int>, val number:Int)
data class Proposal(val original:Sudoku, val proposition: List<Guess>)
fun main(args: Array<String>) {
// val grid1 = parse()
}
typealias Sudoku = List<List<Int>>
fun parse(text: List<String>): Sudoku {
val parsed = text.map {
it.trim()
}.filter {
it.isNotEmpty()
}.map {
it.filter {
it in ('0'..'9')
}.map {
it.toInt() - '0'.toInt()
}
}
if (parsed.size != 9) {
throw IllegalArgumentException("The grid is not 9 lines long")
}
if (parsed.map { it.size }.any { it != 9 }) {
throw IllegalArgumentException("All lines must be 9 numbers long")
}
return parsed
}
/**
* Lists all the values contained in the given rectangle, bounds inclusive.
*/
fun listValues(
sudoku: Sudoku,
startRow: Int,
startColumn: Int,
endRow: Int,
endColumn: Int
): List<Int> {
return (startRow..endRow).flatMap { row ->
(startColumn..endColumn).map { col ->
sudoku[row][col]
}
}.filter { it != 0 }
}
fun listExistingValuesInSquare(
sudoku: Sudoku,
row: Int,
column: Int
): List<Int> {
val sRow = row / 3
val sCol = column / 3
return listValues(
sudoku,
sRow * 3,
sCol * 3,
(sRow + 1) * 3 - 1,
(sCol + 1) * 3 - 1
)
}
fun listExistingValuesInRow(sudoku: Sudoku, row: Int) =
listValues(sudoku, row, 0, row, 8)
fun listExistingValuesInColumn(sudoku: Sudoku, column: Int) =
listValues(sudoku, 0, column, 8, column)
fun options(sudoku: Sudoku, row: Int, column: Int): List<Int> {
val rowValues = listExistingValuesInRow(sudoku, row)
val columnValues = listExistingValuesInColumn(sudoku, column)
val squareValues = listExistingValuesInSquare(sudoku, row, column)
return (1..9).filter {
it !in rowValues && it !in columnValues && it !in squareValues
}
}
fun reject(origin: Sudoku, proposal: Sudoku, row: Int, col: Int): Boolean {
val opt = options(origin, row, col)
return proposal[row][col] !in opt
}
fun accept(proposal: Sudoku) =
proposal.flatMap {
it.map {
it
}
}.any {
it == 0
}.not()
fun first(original: Sudoku) = original
fun next(proposal: Sudoku, row: Int, col: Int): Sudoku {
val current = proposal[row][col]
val currentPosition = row to col
val nextPosition = when (current) {
9 -> next(row, col)
else -> {
currentPosition
}
}
val nextNumber = when (current) {
9 -> 1
else -> current + 1
}
// TODO: change
return proposal
}
fun next(row: Int, col: Int) =
when (col) {
9 -> row + 1 to 1
else -> row to col + 1
}
| [
{
"class_path": "ununhexium__samples__11aca6b/sudoku/SudokuKt.class",
"javap": "Compiled from \"Sudoku.kt\"\npublic final class sudoku.SudokuKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokes... |
ununhexium__samples__11aca6b/src/main/java/strassenbahn/ThriftTicket.kt | package strassenbahn
import java.util.LinkedList
import kotlin.math.max
interface Ticket {
fun getPrice(area: Int): Float
val description: String
val adultCapacity: Int
val childrenCapacity: Int
val allowedTrips: Int
}
data class Wanted(
val area: Int,
val adults: Int = 0,
val children: Int = 0,
val tripsPerPeople: Int = 1
) {
fun noPassenger() = (adults + children) <= 0
}
class TicketImpl(
override val description: String,
val prices: Map<Int, Number>,
override val adultCapacity: Int = 0,
override val childrenCapacity: Int = 0,
override val allowedTrips: Int = 1
) : Ticket {
override fun getPrice(area: Int): Float {
return prices[area]?.toFloat() ?: throw IllegalArgumentException("No price for area $area")
}
override fun toString() = description
}
data class Proposition(val tickets: Map<Ticket, Int>) {
// constructor(pairs: List<Pair<Ticket, Int>>): this(pairs.toMap())
// constructor(pair: Pair<Ticket, Int>): this(listOf(pair).toMap())
companion object {
val EMPTY = Proposition(mapOf())
}
fun getPrice(area: Int, trips: Int = 1) =
tickets.map {
// are many tickets are needed to make the desired number of trips
val ticketsCount = Math.ceil(trips / it.key.allowedTrips.toDouble()).toInt()
it.key.getPrice(area) * it.value * ticketsCount
}.sum()
val flatTickets: List<Ticket> by lazy {
tickets.flatMap { entry ->
List(entry.value) { entry.key }
}
}
val adultSeats =
flatTickets.sumBy {
it.adultCapacity
}
val childrenSeats =
flatTickets.sumBy {
it.childrenCapacity
}
operator fun plus(ticket: Ticket): Proposition {
val new = this.tickets.toMutableMap()
new[ticket] = (this.tickets[ticket] ?: 0) + 1
return Proposition(new)
}
fun canAccommodate(wanted: Wanted) =
listOf(
// strict adult and child separation
{ this.adultSeats >= wanted.adults && this.childrenSeats >= wanted.children },
// children use adult ticket
{
val freeAdultSeats = this.adultSeats - wanted.adults
val freeChildrenSeats = (this.childrenSeats + freeAdultSeats) - wanted.children
if (freeAdultSeats < 0) {
// not enough seats for adults
false
}
else {
freeChildrenSeats >= 0
}
}
).any {
it()
}
}
/**
* Find the cheapest price given a request and an offer
*/
fun cheapestPrice(wanted: Wanted, offer: List<Ticket>): Proposition {
if (wanted.noPassenger()) {
throw IllegalArgumentException("Need at least 1 traveler")
}
return browseAllPropositions(
wanted,
offer.sortedByDescending { it.adultCapacity }
)
}
fun browseAllPropositions(
wanted: Wanted,
offer: List<Ticket>
): Proposition {
var bestSoFar = Proposition.EMPTY
var bestPriceSoFar = Float.MAX_VALUE
/**
* The Int, an index, is there to know which element in the offer list
* was used to create the proposition and avoid repeating propositions
*/
val queue = LinkedList<Pair<Int, Proposition>>(listOf(0 to bestSoFar))
/**
* we may have to look for solutions which don't use all the seats
* but we must not look for too long in that direction as this is:
* 1. leading to OutOfMemory because a solution which can accomodate only chlidren isn't suited for adults
* TODO: tune ratios
*/
val maxChildrenToAdultRatio = offer.maxCAratio()
val maxAdultToChildrenRatio = offer.maxACratio()
val extraAdultsCapacity = offer.maxBy {
it.adultCapacity
}!!.adultCapacity + wanted.adults * maxAdultToChildrenRatio
val extraChildrenCapacity = offer.maxBy {
it.childrenCapacity
}!!.childrenCapacity + wanted.children * maxChildrenToAdultRatio
while (queue.isNotEmpty()) {
val (index, current) = queue.removeAt(0)
val price = current.getPrice(wanted.area, wanted.tripsPerPeople)
if (price < bestPriceSoFar) {
if (current.canAccommodate(wanted)) {
bestSoFar = current
bestPriceSoFar = price
}
for (i in index until offer.size) {
val new = current + offer[i]
// Don't look too far
val noExcessAdultsCapacity = new.adultSeats <= wanted.adults + extraAdultsCapacity
val noExcessChildrenCapacity = new.childrenSeats <= wanted.children + extraChildrenCapacity
// stop searching when it's more expansive than an existing solution
val newPrice = new.getPrice(wanted.area, wanted.tripsPerPeople)
if (noExcessAdultsCapacity && noExcessChildrenCapacity && newPrice < bestPriceSoFar) {
queue.add(i to new)
}
}
}
}
return bestSoFar
}
private fun <E : Ticket> List<E>.maxCAratio(): Double {
val found = this.map {
if (it.adultCapacity > 0) it.childrenCapacity / it.adultCapacity else 0
}.max() ?: 1
// don't return 0
return max(1.0, found.toDouble())
}
private fun <E : Ticket> List<E>.maxACratio(): Double {
val found = this.map {
if (it.childrenCapacity > 0) it.adultCapacity / it.childrenCapacity else 0
}.max() ?: 1
// don't return 0
return max(1.0, found.toDouble())
}
| [
{
"class_path": "ununhexium__samples__11aca6b/strassenbahn/ThriftTicketKt.class",
"javap": "Compiled from \"ThriftTicket.kt\"\npublic final class strassenbahn.ThriftTicketKt {\n public static final strassenbahn.Proposition cheapestPrice(strassenbahn.Wanted, java.util.List<? extends strassenbahn.Ticket>);\n... |
anurudhp__aoc2021__ed497f8/day16.kt | package quick.start
enum class Op(val i: Int) {
Sum(0),
Prod(1),
Min(2),
Max(3),
Lit(4),
Gt(5),
Lt(6),
Eq(7);
companion object {
fun fromInt(i: Int) = Op.values().first { it.i == i }
}
}
class Packet(version: Int, op: Op, lit: Long, children: List<Packet>) {
val version = version
val op = op
val children = children
val lit = lit
// literal
constructor(v: Int, l: Long) : this(v, Op.Lit, l, emptyList()) {}
// recursive
constructor(v: Int, op: Op, ch: List<Packet>) : this(v, op, 0, ch) {}
fun versionTotal(): Int {
return version + children.map { it.versionTotal() }.sum()
}
fun eval(): Long {
if (this.op == Op.Lit) return this.lit
val res = children.map { it.eval() }
if (op == Op.Sum) return res.sum()
if (op == Op.Prod) return res.reduce(Long::times)
if (op == Op.Min) return res.minOrNull()!!
if (op == Op.Max) return res.maxOrNull()!!
val (lhs, rhs) = res
var cond = false
if (op == Op.Gt) cond = lhs > rhs
if (op == Op.Lt) cond = lhs < rhs
if (op == Op.Eq) cond = lhs == rhs
return if (cond) 1 else 0
}
}
fun parseLit(s: String): Pair<Long, String> {
var s = s
var res = 0L
var done = false
while (!done) {
res = res * 16 + s.substring(1, 5).toLong(2)
done = s[0] == '0'
s = s.substring(5)
}
return Pair(res, s)
}
fun parsePacket(s: String): Pair<Packet, String> {
val v = s.substring(0, 3).toInt(2)
val ty = Op.fromInt(s.substring(3, 6).toInt(2))
val s = s.substring(6)
if (ty == Op.Lit) {
val (l, s) = parseLit(s)
return Pair(Packet(v, l), s)
}
if (s[0] == '0') { // length of packets
val len = s.substring(1, 16).toInt(2)
val ss = s.substring(16 + len)
var s = s.substring(16, 16 + len)
var ps = mutableListOf<Packet>()
while (!s.isEmpty()) {
val (p, ss) = parsePacket(s)
s = ss
ps.add(p)
}
return Pair(Packet(v, ty, ps), ss)
} else { // num. packets
val num = s.substring(1, 12).toInt(2)
var s = s.substring(12)
var ps = mutableListOf<Packet>()
for (i in 1..num) {
val (p, ss) = parsePacket(s)
s = ss
ps.add(p)
}
return Pair(Packet(v, ty, ps), s)
}
}
fun parseFull(s: String): Packet {
val (p, s) = parsePacket(s)
assert(s.all { it == '0' })
return p
}
fun main() {
val inp = readLine()!!
val data = ('1' + inp).toBigInteger(16).toString(2).drop(1)
val packet = parseFull(data)
println(packet.versionTotal())
println(packet.eval())
}
| [
{
"class_path": "anurudhp__aoc2021__ed497f8/quick/start/Day16Kt.class",
"javap": "Compiled from \"day16.kt\"\npublic final class quick.start.Day16Kt {\n public static final kotlin.Pair<java.lang.Long, java.lang.String> parseLit(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 ... |
tschulte__docToolchain-aoc-2019__afcaede/day14/kotlin/corneil/src/main/kotlin/solution.kt | package com.github.corneil.aoc2019.day14
import java.io.File
typealias ChemicalQty = Pair<Long, String>
data class ReactionFormula(val inputs: List<ChemicalQty>, val output: ChemicalQty)
fun readChemicalQty(it: String): ChemicalQty {
val tokens = it.trim().split(" ")
require(tokens.size == 2)
return ChemicalQty(tokens[0].toLong(), tokens[1].trim())
}
fun readReaction(input: String): ReactionFormula {
val inputs = input.substringBefore("=>").split(",").map {
readChemicalQty(it)
}
return ReactionFormula(inputs, readChemicalQty(input.substringAfter("=>")))
}
fun readReactions(input: List<String>) = input.map { readReaction(it) }
fun add(value: MutableMap<String, Long>, output: ChemicalQty) {
val qty = value[output.second]
if (qty != null) {
value[output.second] = qty + output.first
} else {
value[output.second] = output.first
}
}
fun produce(
output: ChemicalQty,
formulae: Map<String, ReactionFormula>,
sideEffect: MutableMap<String, Long>,
used: MutableMap<String, Long>
) {
val remain = sideEffect[output.second]
if (remain != null && remain > 0L) {
useRemainingChemicals(remain, output, formulae, sideEffect, used)
} else {
val formula = formulae[output.second]
if (formula != null) {
applyFormula(output, formula, formulae, sideEffect, used)
} else {
// This is usually the ORE
add(used, output)
}
}
}
fun useRemainingChemicals(
remain: Long,
output: ChemicalQty,
formulae: Map<String, ReactionFormula>,
sideEffect: MutableMap<String, Long>,
used: MutableMap<String, Long>
) {
if (remain >= output.first) {
val qty = remain - output.first
sideEffect[output.second] = qty
require(qty >= 0) { "Expected Qty to be zero or greater for ${output.second} not $qty" }
} else {
sideEffect.remove(output.second)
produce(ChemicalQty(output.first - remain, output.second), formulae, sideEffect, used)
}
}
fun applyFormula(
output: ChemicalQty,
formula: ReactionFormula,
formulae: Map<String, ReactionFormula>,
sideEffect: MutableMap<String, Long>,
used: MutableMap<String, Long>
) {
val repeats = if (output.first < formula.output.first) {
1L
} else {
output.first / formula.output.first +
if (output.first % formula.output.first == 0L) 0L else 1L
}
val produced = apply(formula, repeats, formulae, sideEffect, used)
if (output.first < produced.first) {
sideEffect[output.second] = produced.first - output.first
}
}
fun apply(
formula: ReactionFormula,
repeats: Long,
formulae: Map<String, ReactionFormula>,
sideEffect: MutableMap<String, Long>,
used: MutableMap<String, Long>
): ChemicalQty {
formula.inputs.forEach {
produce(ChemicalQty(it.first * repeats, it.second), formulae, sideEffect, used)
}
return ChemicalQty(formula.output.first * repeats, formula.output.second)
}
fun determineInputForOutput(input: String, output: ChemicalQty, formulae: List<ReactionFormula>): Long {
val formula = formulae.map { it.output.second to it }.toMap()
val used = mutableMapOf<String, Long>()
val sideEffect = mutableMapOf<String, Long>()
produce(output, formula, sideEffect, used)
println("$output = $used, Side Effects = $sideEffect")
return used[input] ?: 0L
}
fun executeReactions(
increment: Long,
input: ChemicalQty,
output: String,
formula: Map<String, ReactionFormula>,
used: MutableMap<String, Long>
): Pair<Long, Long> {
val sideEffect = mutableMapOf<String, Long>()
var inc = increment
var counter = 0L
while (input.first > used[input.second] ?: 0L) {
produce(ChemicalQty(inc, output), formula, sideEffect, used)
counter += inc
if (counter % 10000L == 0L) {
print("produce $output for $input = $counter\r")
}
val usedSoFar = used[input.second] ?: 0L
if (inc == 100L && (10L * usedSoFar / input.first > 7L)) {
inc = 10L
} else if (inc == 10L && (10L * usedSoFar / input.first > 8L)) {
inc = 1L
}
}
println("Used = $used, Side Effect = $sideEffect")
return Pair(counter, inc)
}
fun determineOuputForInput(input: ChemicalQty, output: String, formulae: List<ReactionFormula>): Long {
val formula = formulae.map { it.output.second to it }.toMap()
val used = mutableMapOf<String, Long>()
var increment = 1000L // Start with 100 and drop down to save some time
var counter: Long
do {
increment /= 10L
val pair = executeReactions(increment, input, output, formula, used)
counter = pair.first
increment = pair.second
} while (increment > 1L) // If last increment isn't 1 redo
val result = if (used[input.second] == input.first) counter else counter - 1L
println("output $input = $result")
return result
}
fun main(args: Array<String>) {
val fileName = if (args.size > 1) args[0] else "input.txt"
val formulae = readReactions(File(fileName).readLines())
val output = determineInputForOutput("ORE", ChemicalQty(1L, "FUEL"), formulae)
println("Output = ORE = $output")
require(output == 612880L) // ensure check for refactoring
val fuel = determineOuputForInput(ChemicalQty(1000000000000L, "ORE"), "FUEL", formulae)
println("Fuel = $fuel")
require(fuel == 2509120L)
}
| [
{
"class_path": "tschulte__docToolchain-aoc-2019__afcaede/com/github/corneil/aoc2019/day14/SolutionKt.class",
"javap": "Compiled from \"solution.kt\"\npublic final class com.github.corneil.aoc2019.day14.SolutionKt {\n public static final kotlin.Pair<java.lang.Long, java.lang.String> readChemicalQty(java.la... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/strings/special/SubstrCount.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.strings.special
import java.lang.Integer.max
import java.util.*
fun subStrCount(string: String): Long =
cntSubstringsWithSameChars(string) + cntSubstringsWithSameCharsExceptMiddle(string)
private fun cntSubstringsWithSameCharsExceptMiddle(string: String): Long {
fun withinBounds(index: Int, offset: Int): Boolean =
((index - offset) >= 0) && ((index + offset) < string.length)
fun substringIsValid(currChar: Char, index: Int, offset: Int): Boolean =
if (withinBounds(index, offset)) {
val lChar = string[index - offset]
val rChar = string[index + offset]
(lChar == currChar) && (rChar == currChar)
} else false
var substringCnt = 0L
var index = 1
while (index < string.length - 1) {
val currChar = string[index - 1]
if (string[index] == currChar) {
index++
continue
}
val offset = generateSequence(1) { it + 1 }
.takeWhile { offset -> substringIsValid(currChar, index, offset) }
.count()
substringCnt += offset
index += max(offset, 1)
}
return substringCnt
}
private fun cntSubstringsWithSameChars(string: String): Long =
string.drop(1).fold(CharCounterHolder(string.first())) { counter, char ->
if (char == counter.char) counter.increment()
else counter.switchChar(char)
}.countValue()
private data class CharCounterHolder(
val char: Char,
val currentCount: Long = 1L,
val partialResult: Long = 0
) {
fun increment(): CharCounterHolder =
copy(currentCount = currentCount + 1)
fun switchChar(char: Char) =
CharCounterHolder(char = char, partialResult = countValue())
fun countValue() = partialResult + (currentCount * (currentCount + 1) / 2)
}
fun main() {
val scan = Scanner(System.`in`)
scan.nextLine()
val s = scan.nextLine()
val result = subStrCount(s)
println(result)
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/strings/special/SubstrCountKt.class",
"javap": "Compiled from \"SubstrCount.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.strings.special.SubstrCountKt {\n pu... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/dynamic/candies/Candies.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.dynamic.candies
import java.util.*
import kotlin.math.max
import kotlin.math.min
fun candies(grades: Array<Int>): Long {
val size = grades.size
val gradeByIndex = saveGrading(grades)
val startIndicesWithDirections = buildStartIndicesWithDirections(gradeByIndex, size)
val stopIndicesSet = buildStopIndicesSet(gradeByIndex, size)
fun canMove(index: Int, direction: Direction): Boolean = when (direction) {
Direction.LEFT -> index > 0
Direction.RIGHT -> index < size - 1
}
val candiesDistribution = Array(size) { 1 }
fun expandFrom(startIndex: Int, direction: Direction) {
var currentIndx = startIndex
while (currentIndx !in stopIndicesSet && canMove(currentIndx, direction)) {
val currentCandies = candiesDistribution[currentIndx]
currentIndx = direction.next(currentIndx)
candiesDistribution[currentIndx] = max(currentCandies + 1, candiesDistribution[currentIndx])
}
}
startIndicesWithDirections.forEach { (startIndex, directions) ->
directions.forEach { direction -> expandFrom(startIndex, direction) }
}
return candiesDistribution.fold(0L) { acc, i -> acc + i }
}
private fun saveGrading(grades: Array<Int>): (Int) -> Int = { index -> when {
index < 0 -> Int.MAX_VALUE
index >= grades.size -> Int.MAX_VALUE
else -> grades[index]
} }
private fun buildStartIndicesWithDirections(gradeByIndex: (Int) -> Int, size: Int): List<Pair<Int, List<Direction>>> =
(0 until size).filter { index ->
gradeByIndex(index) <= min(gradeByIndex(index - 1), gradeByIndex(index + 1))
}.map { index -> when {
gradeByIndex(index) == gradeByIndex(index + 1) -> index to listOf(Direction.LEFT)
gradeByIndex(index) == gradeByIndex(index - 1) -> index to listOf(Direction.RIGHT)
else -> index to listOf(Direction.LEFT, Direction.RIGHT)
} }
private fun buildStopIndicesSet(gradeByIndex: (Int) -> Int, size: Int): Set<Int> =
(0 until size).filter { index ->
gradeByIndex(index) >= max(gradeByIndex(index - 1), gradeByIndex(index + 1))
}.toSet()
enum class Direction {
LEFT,
RIGHT
}
fun Direction.next(index: Int): Int = when (this) {
Direction.LEFT -> index - 1
Direction.RIGHT -> index + 1
}
fun main() {
val scan = Scanner(System.`in`)
val n = scan.nextLine().trim().toInt()
val arr = Array(n) { 0 }
for (i in 0 until n) {
val arrItem = scan.nextLine().trim().toInt()
arr[i] = arrItem
}
val result = candies(arr)
println(result)
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/dynamic/candies/CandiesKt$WhenMappings.class",
"javap": "Compiled from \"Candies.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.dynamic.candies.CandiesKt$WhenMa... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/hashmaps/triplets/CountTriplets.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.hashmaps.triplets
import java.util.*
fun countTriplets(array: LongArray, ratio: Long): Long {
fun modR(iv: IndexedValue<Long>) = iv.value % ratio == 0L
fun divR(iv: IndexedValue<Long>) = IndexedValue(iv.index, iv.value / ratio)
fun List<IndexedValue<Long>>.indexes() = map { (index, _) -> index }
fun candidates(power: Int) =
(0 until power).fold(array.withIndex()) { curArr, _ ->
curArr.filter(::modR).map(::divR)
}.groupBy { (_, value) -> value }
.mapValues { (_, indexedValues) -> indexedValues.indexes() }
val (iCandidates, jCandidates, kCandidates) =
listOf(0, 1, 2).map(::candidates)
val commonBases = kCandidates.keys.filter { v ->
(v in iCandidates) && (v in jCandidates)
}
return commonBases.map { v ->
val kvCandidates = kCandidates.getValue(v)
val jvCandidates = jCandidates.getValue(v)
val ivCandidates = iCandidates.getValue(v)
countTriplesForSingleBaseValue(ivCandidates, jvCandidates, kvCandidates)
}.sum()
}
private fun countTriplesForSingleBaseValue(
ivCandidates: List<Int>,
jvCandidates: List<Int>,
kvCandidates: List<Int>
): Long {
var i = 0
var j = 0
var k = 0
var iCnt = 0L
var jCnt = 0L
var kCnt = 0L
while ((k < kvCandidates.size) && (i < ivCandidates.size) && (j < jvCandidates.size)) {
val ivc = ivCandidates[i]
val jvc = jvCandidates[j]
val kvc = kvCandidates[k]
when {
kvc <= jvc -> {
kCnt += jCnt
k++
}
jvc <= ivc -> {
jCnt += iCnt
j++
}
else -> {
i++
iCnt += 1L
}
}
}
while ((k < kvCandidates.size) && (j < jvCandidates.size)) {
val jvc = jvCandidates[j]
val kvc = kvCandidates[k]
when {
kvc <= jvc -> {
kCnt += jCnt
k++
}
else -> {
jCnt += iCnt
j++
}
}
}
if ((k < kvCandidates.size) && (kvCandidates[k] > jvCandidates.last())) {
kCnt += jCnt * (kvCandidates.size - k)
}
return kCnt
}
fun main() {
val scanner = Scanner(System.`in`)
val nr = scanner.nextLine().trim().split(" ")
val r = nr[1].toLong()
val array = scanner.nextLine().trim().split(" ").map { it.toLong() }.toLongArray()
val result = countTriplets(array, r)
println(result)
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/hashmaps/triplets/CountTripletsKt.class",
"javap": "Compiled from \"CountTriplets.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.hashmaps.triplets.CountTriplets... |
slobanov__kotlin-hackerrank__2cfdf85/src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/warmUpChallenges/clouds/JumpingOnClouds.kt | package ru.amai.study.hackerrank.practice.interviewPreparationKit.warmUpChallenges.clouds
import java.util.*
private const val MAX_CLOUDS = 100
private const val MIN_CLOUDS = 2
fun jumpingOnClouds(clouds: Array<Int>): Int {
checkRequirement(clouds)
fun isThunder(cloud: Int) = cloud == 1
val (totalPenalty, _) = clouds.withIndex()
.fold(0 to PenaltyState.EVEN) { (penalty, penaltyState), (indx, cloud) ->
if (isThunder(cloud) && penaltyState.isApplicable(indx)) {
(penalty + 1) to penaltyState.flip()
} else penalty to penaltyState
}
return (clouds.size + totalPenalty) / 2
}
private fun checkRequirement(clouds: Array<Int>) {
require(clouds.all { it in listOf(0, 1) }) {
"clouds must be numbered 0 or 1; got ${clouds.contentToString()}"
}
require(clouds.size in MIN_CLOUDS..MAX_CLOUDS) {
"number of clouds should be <= $MAX_CLOUDS and >= $MIN_CLOUDS; got ${clouds.size}"
}
require(clouds.first() == 0) { "first cloud should be 0; got ${clouds.first()}" }
require(clouds.last() == 0) { "last cloud should be 0; got ${clouds.last()}" }
require(
clouds.toList()
.zipWithNext()
.map { (curr, next) -> curr + next }.all { it != 2 }
) { "there should not be two consecutive 1's in clouds; got ${clouds.contentToString()}" }
}
enum class PenaltyState {
EVEN,
ODD;
fun flip() = when (this) {
EVEN -> ODD
ODD -> EVEN
}
fun isApplicable(indx: Int) = when (this) {
EVEN -> indx % 2 == 0
ODD -> indx % 2 == 1
}
}
fun main() {
val scanner = Scanner(System.`in`)
scanner.nextLine().trim()
val clouds = scanner.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray()
val result = jumpingOnClouds(clouds)
println(result)
}
| [
{
"class_path": "slobanov__kotlin-hackerrank__2cfdf85/ru/amai/study/hackerrank/practice/interviewPreparationKit/warmUpChallenges/clouds/JumpingOnCloudsKt.class",
"javap": "Compiled from \"JumpingOnClouds.kt\"\npublic final class ru.amai.study.hackerrank.practice.interviewPreparationKit.warmUpChallenges.clou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.