kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
austin226__codeforces-kt__4377021/contest1907/src/main/kotlin/C.kt | import kotlin.math.min
// https://codeforces.com/contest/1907/problem/C
private fun readInt(): Int = readln().toInt()
private fun solve(n: Int, s: String): Int {
var min = n
val checked = mutableSetOf(s)
val q = ArrayDeque<String>()
q.addFirst(s)
while (q.isNotEmpty()) {
val str = q.removeFirst()
for (i in 0..<str.length - 1) {
if (str[i] == str[i + 1]) {
continue
}
// Remove i and i+1
val newStrBuilder = StringBuilder()
for (j in str.indices) {
if (i != j && i + 1 != j) {
newStrBuilder.append(str[j])
}
}
val newStr = newStrBuilder.toString()
if (checked.contains(newStr)) {
continue
}
min = min(newStr.length, min)
if (min == 0) {
break
}
q.addLast(newStr)
checked.add(newStr)
println("Check $newStr")
}
}
return min
}
private fun testcase() {
val n = readInt()
val s = readln()
val min = solve(n, s)
println(min)
}
fun main() {
// val min = solve(20000, "abacd".repeat(20000 / 5))
val min = solve(2000, "abacd".repeat(2000 / 5))
println(min)
return
val t = readInt()
for (i in 0..<t) {
testcase()
}
} | [
{
"class_path": "austin226__codeforces-kt__4377021/CKt.class",
"javap": "Compiled from \"C.kt\"\npublic final class CKt {\n private static final int readInt();\n Code:\n 0: invokestatic #12 // Method kotlin/io/ConsoleKt.readln:()Ljava/lang/String;\n 3: invokestatic #18 ... |
austin226__codeforces-kt__4377021/codeforces/src/main/kotlin/contest1911/H.kt | // https://codeforces.com/contest/1911/problem/H
private fun String.splitWhitespace() = split("\\s+".toRegex())
private fun <T> List<T>.counts(): Map<T, Int> = this.groupingBy { it }.eachCount()
private fun <T : Comparable<T>> List<T>.isStrictlyDecreasing(): Boolean =
(size <= 1) || (1 until size).all { i -> get(i) < get(i - 1) }
private fun <T : Comparable<T>> List<T>.isStrictlyIncreasing(): Boolean =
(size <= 1) || (1 until size).all { i -> get(i) > get(i - 1) }
/** Return 0 for each index whose member in a belongs to the increasing sequence.
* 1 otherwise. null if not possible. */
fun findIncrSeqMembers(a: List<Int>, n: Int): List<Int>? {
val res = MutableList(n) { 0 }
var incrMax = Int.MIN_VALUE
var decrMin = Int.MAX_VALUE
if (n > 1 && a[0] >= a[1]) {
res[0] = 1
decrMin = res[0]
// TODO extend this using a while loop. Take all decreasing numbers into decr until we hit something that has to go into incr.
// TODO that probably won't cover many cases...
}
for (k in a) {
if (k < decrMin) {
decrMin = k
} else if (k > incrMax) {
incrMax = k
} else {
return null
}
}
return res
}
fun main() {
val n = readln().toInt()
val a = readln().splitWhitespace().map { it.toInt() }
// If there are >2 of any input, print NO
findIncrSeqMembers(a, n)?.let {
println("YES")
println(it.joinToString(" "))
return
}
println("NO")
} | [
{
"class_path": "austin226__codeforces-kt__4377021/HKt.class",
"javap": "Compiled from \"H.kt\"\npublic final class HKt {\n private static final java.util.List<java.lang.String> splitWhitespace(java.lang.String);\n Code:\n 0: aload_0\n 1: checkcast #9 // class java/lang/... |
austin226__codeforces-kt__4377021/codeforces/src/main/kotlin/contest1911/F.kt | // https://codeforces.com/contest/1911/problem/F
private fun String.splitWhitespace() = split("\\s+".toRegex())
private fun <T> List<T>.counts(): Map<T, Int> = this.groupingBy { it }.eachCount()
fun idealUniqueWeights(weights: List<Int>): Set<Int> {
val uniqueWeights = mutableSetOf<Int>()
for (weight in weights.sorted()) {
if (weight > 1) {
// First try to insert weight-1
if (!uniqueWeights.contains(weight - 1)) {
uniqueWeights.add(weight - 1)
continue
}
}
// Next try to insert weight
if (!uniqueWeights.contains(weight)) {
uniqueWeights.add(weight)
continue
}
// Finally try to insert weight+1
if (!uniqueWeights.contains(weight + 1)) {
uniqueWeights.add(weight + 1)
}
}
return uniqueWeights
}
fun main() {
// n boxers. n in 1..=150_000
val n = readln().toInt()
// weight of each boxer.
// n ints, a_i where a_i in 1..150_000
val a = readln().splitWhitespace().map { it.toInt() }
println(idealUniqueWeights(a).size)
}
| [
{
"class_path": "austin226__codeforces-kt__4377021/FKt$counts$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Collections.kt\"\npublic final class FKt$counts$$inlined$groupingBy$1 implements kotlin.collections.Grouping<T, T> {\n final java.lang.Iterable $this_groupingBy;\n\n public FKt$counts$$in... |
austin226__codeforces-kt__4377021/codeforces/src/main/kotlin/contest1911/e.kt | import java.util.*
private fun String.splitWhitespace() = split("\\s+".toRegex())
fun greatestPowerUpTo(n: Int): Int? {
if (n < 1) {
return null
}
var p = 1
while (p < n) {
if (p * 2 > n) {
return p
}
p *= 2
}
return p
}
fun asPower2Sum(n: Int, k: Int): List<Int>? {
// First, find the smallest list of powers of 2 we can use to write n. If it's longer than k, return null.
val powers = LinkedList<Int>()
var remainder = n
var powersUsed = 0
while (remainder > 0) {
val p = greatestPowerUpTo(remainder)!!
remainder -= p
powers.add(p)
powersUsed++
if (powersUsed > k) {
// return null if not possible
return null
}
}
// Next, break up any powers we can until we can reach k, or we get all 1's.
while (powers.size < k) {
val f = powers.first
if (f == 1) {
// first value is a 1 - we can't reach k
return null
}
powers.removeFirst()
if (f == 2) {
powers.add(1)
powers.add(1)
} else {
powers.add(0, f / 2)
powers.add(0, f / 2)
}
}
return powers.sorted()
}
fun main() {
// Can we write n as a sum of exactly k powers of 2?
// n in 1..=1e9
// k in 1..=2e5
val (n, k) = readln().splitWhitespace().map { it.toInt() }
asPower2Sum(n, k)?.let {
println("YES")
println(it.joinToString(" "))
return
}
println("NO")
}
| [
{
"class_path": "austin226__codeforces-kt__4377021/EKt.class",
"javap": "Compiled from \"e.kt\"\npublic final class EKt {\n private static final java.util.List<java.lang.String> splitWhitespace(java.lang.String);\n Code:\n 0: aload_0\n 1: checkcast #9 // class java/lang/... |
austin226__codeforces-kt__4377021/contest1907/src/main/kotlin/CFixed.kt | import kotlin.streams.toList
// https://codeforces.com/contest/1907/problem/C
private fun readInt(): Int = readln().toInt()
private fun <T> List<T>.counts(): Map<T, Int> = this.groupingBy { it }.eachCount()
private fun solve(n: Int, s: String): Int {
// https://codeforces.com/blog/entry/123012
// The final string will always have all of the same characters.
// If a character appears more than n/2 times, the final string will consist only of that character.
val charCounts = s.chars().toList().counts().toMutableMap()
var dominantChar: Int? = null
var dominantCharCount: Int? = null
for (charCount in charCounts) {
if (charCount.value > n / 2) {
// One char dominates
dominantChar = charCount.key
dominantCharCount = charCount.value
break
}
}
if (dominantChar == null || dominantCharCount == null) {
// No character dominates - all pairs can be deleted
return n % 2
}
charCounts.remove(dominantChar)
return dominantCharCount - charCounts.values.sum()
}
private fun testcase() {
val n = readInt()
val s = readln()
val min = solve(n, s)
println(min)
}
fun main() {
// val min = solve(20000, "abacd".repeat(20000 / 5))
// val min = solve(2000, "aaacd".repeat(2000 / 5))
// println(min)
// return
val t = readInt()
for (i in 0..<t) {
testcase()
}
} | [
{
"class_path": "austin226__codeforces-kt__4377021/CFixedKt$counts$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Collections.kt\"\npublic final class CFixedKt$counts$$inlined$groupingBy$1 implements kotlin.collections.Grouping<T, T> {\n final java.lang.Iterable $this_groupingBy;\n\n public CFix... |
austin226__codeforces-kt__4377021/contest1907/src/main/kotlin/D.kt | import kotlin.math.max
import kotlin.math.min
// https://codeforces.com/contest/1907/problem/D
private fun String.splitWhitespace() = split("\\s+".toRegex())
private fun readInt(): Int = readln().toInt()
private fun readInts(): List<Int> = readln().splitWhitespace().map { it.toInt() }
private fun testK(segments: List<IntRange>, k: Int): Boolean {
var location = 0..0
for (segment in segments) {
// Our location becomes the intersection of this segment, with the locations we can be after
// jumping up to k.
val locMin = max(0, location.first - k)
val locMax = min(1_000_000_000, location.last + k)
location = max(locMin, segment.first)..min(locMax, segment.last)
// If the intersection is empty, return false.
if (location.isEmpty()) {
return false
}
}
return true
}
private fun solve(segments: List<IntRange>): Int {
// Find smallest k where testK is true
var kL = 0
var kR = 1_000_000_000
var minPassed = kR
while (kL < kR) {
val kM = (kL + kR) / 2
if (testK(segments, kM)) {
minPassed = min(minPassed, kM)
// try smaller
kR = kM - 1
} else {
// Try bigger
kL = kM + 1
}
}
if (kL == kR) {
if (testK(segments, kL)) {
minPassed = min(minPassed, kL)
}
}
return minPassed
}
private fun testcase() {
val n = readInt()
val segments = MutableList(n) { 0..0 }
for (i in 0..<n) {
val lr = readInts()
val l = lr[0]
val r = lr[1]
segments[i] = l..r
}
println(solve(segments))
}
fun main() {
val t = readInt()
for (i in 0..<t) {
testcase()
}
} | [
{
"class_path": "austin226__codeforces-kt__4377021/DKt.class",
"javap": "Compiled from \"D.kt\"\npublic final class DKt {\n private static final java.util.List<java.lang.String> splitWhitespace(java.lang.String);\n Code:\n 0: aload_0\n 1: checkcast #9 // class java/lang/... |
austin226__codeforces-kt__4377021/codeforces/src/main/kotlin/contest1911/G.kt | import java.math.BigInteger
private fun String.splitWhitespace() = split("\\s+".toRegex())
// s1 and s2 both have the same length
fun averageString(s1: String, s2: String, len: Int): String {
// // Work backwards from the end
// val avgStrChars = MutableList<Char>(len) { '?' }
// var remainder = 0
// for (i in len - 1 downTo 0) {
// // Add the chars together, then divide by two
// val c1Val = s1[i] - 'a'
// val c2Val = s2[i] - 'a'
// val (avgC, nextRemainder) = if (c1Val == c2Val) {
// Pair(c1Val, 0)
// } else if (c1Val < c2Val) {
// Pair((c1Val + c2Val) / 2, 0)
// } else {
// // c1Val > c2Val
// Pair((c1Val + c2Val + 26) / 2, -1)
// }
//
// avgStrChars[i] = (remainder + avgC % 26 + ('a'.code)).toChar()
// remainder = if (c1Val + c2Val > 25) 1 else 0
// }
//
// return avgStrChars.joinToString("")
var s1Num = BigInteger.ZERO
var s2Num = BigInteger.ZERO
for (i in 0 until len) {
val c1Val = (s1[i] - 'a').toLong()
val c2Val = (s2[i] - 'a').toLong()
val placeFactor = BigInteger.valueOf(26).pow(len - i - 1)
s1Num = s1Num.plus(BigInteger.valueOf(c1Val).times(placeFactor))
s2Num = s2Num.plus(BigInteger.valueOf(c2Val).times(placeFactor))
}
val sAvg = s1Num.plus(s2Num).divide(BigInteger.valueOf(2))
val resChars = mutableListOf<Char>()
var rem = sAvg
var exp = len - 1
while (exp >= 0) {
val divisor = BigInteger.valueOf(26).pow(exp)
val n = rem.divide(divisor).toInt()
rem = rem.mod(divisor)
exp--
val c = (n + 'a'.code).toChar()
resChars.add(c)
}
return resChars.joinToString("")
}
fun main() {
// len(s) = len(t) = k
// k in 1..=2e5
val k = readln().toInt()
val s = readln()
val t = readln()
// Find the median string that is (> s) and (< t)
// We know there are an odd number of such strings
// Median will be the same as the mean
// Treat strings like k-digit numbers in base 26.
println(averageString(s, t, k))
} | [
{
"class_path": "austin226__codeforces-kt__4377021/GKt.class",
"javap": "Compiled from \"G.kt\"\npublic final class GKt {\n private static final java.util.List<java.lang.String> splitWhitespace(java.lang.String);\n Code:\n 0: aload_0\n 1: checkcast #9 // class java/lang/... |
er453r__aoc2022__9f98e24/src/Day24.kt | fun main() {
val directions = mapOf('<' to Vector3d.LEFT, '>' to Vector3d.RIGHT, '^' to Vector3d.UP, 'v' to Vector3d.DOWN)
val neighboursInTime = directions.values.map { it + Vector3d.BACK }.toSet() + Vector3d.BACK
val start = Vector3d(0, -1, 0)
fun isEmpty(positionInTime: Vector3d, width: Int, height: Int, initialState: Map<Vector3d, Vector3d?>, start: Vector3d, end: Vector2d) = when {
(positionInTime.x == start.x && positionInTime.y == start.y) || (positionInTime.x == end.x && positionInTime.y == end.y) -> true // start or end is OK
positionInTime.x !in (0 until width) || positionInTime.y !in (0 until height) -> false
directions.values.map { direction ->
Pair((Vector3d(positionInTime.x, positionInTime.y, 0) - direction * positionInTime.z).apply {
x = (width + (x % width)) % width
y = (height + (y % height)) % height
}, direction)
}.any { (possibleBlizzard, direction) -> possibleBlizzard in initialState && initialState[possibleBlizzard] == direction } -> false
else -> true
}
fun neighbours(node: Vector3d, start: Vector3d, end: Vector2d, width: Int, height: Int, initialState: Map<Vector3d, Vector3d?>): Set<Vector3d> {
return neighboursInTime.map { node + it }.filter { isEmpty(it, width, height, initialState, start, end) }.toSet()
}
fun part1(input: List<String>): Int {
val grid = Grid(input.map { it.toCharArray().toList() })
val width = grid.width - 2
val height = grid.height - 2
val end = Vector2d(width - 1, height)
val initialState = grid.data.flatten().filter { it.value in directions }.associate {
Vector3d(it.position.x, it.position.y, 0) - Vector3d(1, 1, 0) to directions[it.value]
}
val path = aStar(
start = start,
isEndNode = { node -> node.x == end.x && node.y == end.y },
heuristic = { (end - Vector2d(it.x, it.y)).manhattan() },
neighbours = { node ->
neighbours(node, start, end, width, height, initialState)
})
return path.size - 1
}
fun part2(input: List<String>): Int {
val grid = Grid(input.map { it.toCharArray().toList() })
val width = grid.width - 2
val height = grid.height - 2
val end = Vector2d(width - 1, height)
val initialState = grid.data.flatten().filter { it.value in directions }.associate {
Vector3d(it.position.x, it.position.y, 0) - Vector3d(1, 1, 0) to directions[it.value]
}
val path1 = aStar(
start = start,
isEndNode = { node -> node.x == end.x && node.y == end.y },
heuristic = { (end - Vector2d(it.x, it.y)).manhattan() },
neighbours = { node ->
neighbours(node, start, end, width, height, initialState)
})
val path2 = aStar(
start = path1.first(),
isEndNode = { node -> node.x == 0 && node.y == -1 },
heuristic = { (end - Vector2d(it.x, it.y)).manhattan() },
neighbours = { node ->
neighbours(node, start, end, width, height, initialState)
})
val path3 = aStar(
start = path2.first(),
isEndNode = { node -> node.x == end.x && node.y == end.y },
heuristic = { (end - Vector2d(it.x, it.y)).manhattan() },
neighbours = { node ->
neighbours(node, start, end, width, height, initialState)
})
return path1.size + path2.size + path3.size - 3
}
test(
day = 24,
testTarget1 = 18,
testTarget2 = 54,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day24Kt$main$1.class",
"javap": "Compiled from \"Day24.kt\"\nfinal class Day24Kt$main$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.Integer> {\n final Vector3d $st... |
er453r__aoc2022__9f98e24/src/Utils.kt | import java.io.File
import java.math.BigInteger
import kotlin.math.abs
import kotlin.math.max
fun readInput(name: String) = File("aoc2022/src", "$name.txt")
.readLines()
fun <T> assertEquals(value: T, target: T) {
if (value != target)
check(false) { "Expected $target got $value" }
}
fun String.destructured(regex: Regex): MatchResult.Destructured = regex.matchEntire(this)
?.destructured
?: throw IllegalArgumentException("Incorrect line $this")
val intLineRegex = """-?\d+""".toRegex()
fun String.ints() = intLineRegex.findAll(this).map { it.value.toInt() }.toList()
fun <T> test(
day: Int,
testTarget1: T,
testTarget2: T,
part1: (List<String>) -> T,
part2: (List<String>) -> T,
) {
// test if implementation meets criteria from the description, like:
val dayNumber = day.toString().padStart(2, '0')
val testInput = readInput("Day${dayNumber}_test")
val input = readInput("Day${dayNumber}")
println("[DAY $day]")
println("Part 1")
print(" test: $testTarget1 ")
var startTime = System.currentTimeMillis()
assertEquals(part1(testInput), testTarget1)
println("OK (${System.currentTimeMillis() - startTime} ms)")
startTime = System.currentTimeMillis()
println(" answer: ${part1(input)} (${System.currentTimeMillis() - startTime} ms)")
println("Part 2")
print(" test: $testTarget2 ")
startTime = System.currentTimeMillis()
assertEquals(part2(testInput), testTarget2)
println("OK (${System.currentTimeMillis() - startTime} ms)")
startTime = System.currentTimeMillis()
println(" answer: ${part2(input)} (${System.currentTimeMillis() - startTime} ms)")
}
class GridCell<T>(
var value: T,
val position: Vector2d,
)
class Grid<T>(data: List<List<T>>) {
val data = data.mapIndexed { y, line ->
line.mapIndexed { x, value -> GridCell(value, Vector2d(x, y)) }
}
val width = data.first().size
val height = data.size
fun get(x: Int, y: Int) = data[y][x]
operator fun get(vector2d: Vector2d) = get(vector2d.x, vector2d.y)
fun contains(x: Int, y: Int) = (x in 0 until width) && (y in 0 until height)
operator fun contains(vector2d: Vector2d) = contains(vector2d.x, vector2d.y)
fun crossNeighbours(vector2d: Vector2d) = Vector2d.DIRECTIONS.map { vector2d + it }.filter { contains(it) }.map { get(it) }
fun path(
start: GridCell<T>,
end: GridCell<T>,
heuristic: (GridCell<T>) -> Int = {
(end.position - it.position).length()
},
neighbours: (GridCell<T>) -> Collection<GridCell<T>> = {
crossNeighbours(it.position)
},
) = aStar(start, isEndNode = { it == end }, heuristic, neighbours)
}
data class Vector2d(var x: Int = 0, var y: Int = 0) {
companion object {
val UP = Vector2d(0, -1)
val DOWN = Vector2d(0, 1)
val LEFT = Vector2d(-1, -0)
val RIGHT = Vector2d(1, 0)
val DIRECTIONS = arrayOf(UP, DOWN, LEFT, RIGHT)
}
operator fun plus(vector2d: Vector2d) = Vector2d(x + vector2d.x, y + vector2d.y)
operator fun minus(vector2d: Vector2d) = Vector2d(x - vector2d.x, y - vector2d.y)
fun increment(vector2d: Vector2d): Vector2d {
this.x += vector2d.x
this.y += vector2d.y
return this
}
fun normalized() = Vector2d(if (x != 0) x / abs(x) else 0, if (y != 0) y / abs(y) else 0)
fun negative() = Vector2d(-x, -y)
fun length() = max(abs(x), abs(y))
fun manhattan() = abs(x) + abs(y)
fun neighbours8() = setOf(
this + UP,
this + UP + LEFT,
this + UP + RIGHT,
this + LEFT,
this + RIGHT,
this + DOWN,
this + DOWN + LEFT,
this + DOWN + RIGHT,
)
}
data class Vector3d(var x: Int = 0, var y: Int = 0, var z: Int = 0) {
companion object {
val UP = Vector3d(0, -1, 0)
val DOWN = Vector3d(0, 1, 0)
val LEFT = Vector3d(-1, 0, 0)
val RIGHT = Vector3d(1, 0, 0)
val FORWARD = Vector3d(0, 0, -1)
val FRONT = Vector3d(0, 0, -1)
val BACKWARD = Vector3d(0, 0, 1)
val BACK = Vector3d(0, 0, 1)
val DIRECTIONS = arrayOf(UP, DOWN, LEFT, RIGHT, FORWARD, BACKWARD)
}
operator fun plus(vector3d: Vector3d) = Vector3d(x + vector3d.x, y + vector3d.y, z + vector3d.z)
operator fun minus(vector3d: Vector3d) = Vector3d(x - vector3d.x, y - vector3d.y, z - vector3d.z)
operator fun times(times: Int) = Vector3d(x * times, y * times, z * times)
fun increment(vector3d: Vector3d): Vector3d {
this.x += vector3d.x
this.y += vector3d.y
this.z += vector3d.z
return this
}
}
class VectorN(val components: MutableList<Int>) {
constructor(vararg ints: Int) : this(ints.toMutableList())
operator fun plus(vectorN: VectorN) = VectorN(components.mapIndexed { index, it -> it + vectorN.components[index] }.toMutableList())
operator fun minus(vectorN: VectorN) = VectorN(components.mapIndexed { index, it -> it - vectorN.components[index] }.toMutableList())
fun increment(vectorN: VectorN): VectorN {
for (n in components.indices)
components[n] += vectorN.components[n]
return this
}
override fun toString(): String {
return components.toString()
}
}
fun <Node> aStar(
start: Node,
isEndNode: (Node) -> Boolean,
heuristic: (Node) -> Int,
neighbours: (Node) -> Collection<Node>,
): List<Node> {
val openSet = mutableSetOf(start)
val gScores = mutableMapOf(start to 0)
val fScores = mutableMapOf(start to heuristic(start))
val cameFrom = mutableMapOf<Node, Node>()
fun reconstructPath(cameFrom: Map<Node, Node>, end: Node): List<Node> {
val path = mutableListOf(end)
var current = end
while (current in cameFrom) {
current = cameFrom[current]!!
path.add(current)
}
return path
}
while (openSet.isNotEmpty()) {
val current = openSet.minBy { fScores[it]!! }
if (isEndNode(current))
return reconstructPath(cameFrom, current)
openSet.remove(current)
for (neighbour in neighbours(current)) {
val neighbourScore = gScores[current]!! + 1
if (neighbourScore < gScores.getOrDefault(neighbour, 999999)) {
cameFrom[neighbour] = current
gScores[neighbour] = neighbourScore
fScores[neighbour] = neighbourScore + heuristic(neighbour)
if (neighbour !in openSet)
openSet += neighbour
}
}
}
return emptyList()
}
fun List<String>.separateByBlank(): List<List<String>> {
val result = mutableListOf<List<String>>()
var currentList = mutableListOf<String>()
for (line in this)
when {
line.isBlank() && currentList.isEmpty() -> continue
line.isBlank() -> {
result.add(currentList)
currentList = mutableListOf()
}
else -> currentList.add(line)
}
if (currentList.isNotEmpty())
result.add(currentList)
return result
}
fun Int.factorial() = (1L..this).reduce(Long::times)
fun <T> List<T>.findLongestSequence(): Pair<Int, Int> {
val sequences = mutableListOf<Pair<Int, Int>>()
for (startPos in indices) {
for (sequenceLength in 1..(this.size - startPos) / 2) {
var sequencesAreEqual = true
for (i in 0 until sequenceLength)
if (this[startPos + i] != this[startPos + sequenceLength + i]) {
sequencesAreEqual = false
break
}
if (sequencesAreEqual)
sequences += Pair(startPos, sequenceLength)
}
}
return sequences.maxBy { it.second }
}
fun gcd(a: Int, b: Int): Int {
if (b == 0) return a
return gcd(b, a % b)
}
fun Long.pow(exp: Int): Long {
return BigInteger.valueOf(this).pow(exp).toLong()
}
fun Int.pow(exp: Int): Long {
return BigInteger.valueOf(this.toLong()).pow(exp).toLong()
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/UtilsKt.class",
"javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n private static final kotlin.text.Regex intLineRegex;\n\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1:... |
er453r__aoc2022__9f98e24/src/Day14.kt | fun main() {
fun fallingSand(input: List<String>, hardFloor: Boolean, stopOnOverflow: Boolean, startPoint: Vector2d = Vector2d(500, 0)): Int {
val lines = input.map {
it.ints().chunked(2).map { (x, y) ->
Vector2d(x, y)
}.toList()
}
val xMin = lines.flatten().toMutableList().also { it.add(startPoint) }.minOf { it.x }
val yMin = lines.flatten().toMutableList().also { it.add(startPoint) }.minOf { it.y }
val xMax = lines.flatten().toMutableList().also { it.add(startPoint) }.maxOf { it.x }
val yMax = lines.flatten().toMutableList().also { it.add(startPoint) }.maxOf { it.y }
val occupied = mutableSetOf<Vector2d>()
for (line in lines)
for (n in 0 until line.size - 1) {
var current = line[n]
val to = line[n + 1]
val step = (to - current).normalized()
while (current != to + step) {
occupied += current
current += step
}
}
var unitsResting = 0
unitLoop@ while (true) {
var current = startPoint
while (true) {
when {
hardFloor && current.y == yMax + 1 -> {
occupied += current
unitsResting++
continue@unitLoop
}
!hardFloor && (current.x !in (xMin..xMax) || current.y !in (yMin..yMax)) -> return unitsResting
(current + Vector2d.DOWN) !in occupied -> current += Vector2d.DOWN
(current + Vector2d.DOWN + Vector2d.LEFT) !in occupied -> current += Vector2d.DOWN + Vector2d.LEFT
(current + Vector2d.DOWN + Vector2d.RIGHT) !in occupied -> current += Vector2d.DOWN + Vector2d.RIGHT
else -> {
occupied += current
unitsResting++
if (stopOnOverflow && current == startPoint)
return unitsResting
continue@unitLoop
}
}
}
}
}
fun part1(input: List<String>) = fallingSand(input, hardFloor = false, stopOnOverflow = false)
fun part2(input: List<String>) = fallingSand(input, hardFloor = true, stopOnOverflow = true)
test(
day = 14,
testTarget1 = 24,
testTarget2 = 93,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day14Kt.class",
"javap": "Compiled from \"Day14.kt\"\npublic final class Day14Kt {\n public static final void main();\n Code:\n 0: bipush 14\n 2: bipush 24\n 4: invokestatic #12 // Method java/lang/Integer.valueOf... |
er453r__aoc2022__9f98e24/src/Day04.kt | fun main() {
val inputLineRegex = """\d""".toRegex()
fun lineToSets(line: String): Pair<Set<Int>, Set<Int>> {
val (start1, end1, start2, end2) = inputLineRegex.findAll(line).map { it.value.toInt() }.toList()
return Pair((start1..end1).toSet(), (start2..end2).toSet())
}
fun part1(input: List<String>): Int = input
.map(::lineToSets)
.count { (a, b) -> a.containsAll(b) || b.containsAll(a) }
fun part2(input: List<String>): Int = input
.map(::lineToSets)
.count { (a, b) -> a.intersect(b).isNotEmpty() }
test(
day = 4,
testTarget1 = 2,
testTarget2 = 4,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc #10 // S... |
er453r__aoc2022__9f98e24/src/Day22.kt | fun main() {
val instructionLineRegex = """(\d+|\w)""".toRegex()
val rightTurns = arrayOf(Vector2d.RIGHT, Vector2d.DOWN, Vector2d.LEFT, Vector2d.UP)
val leftTurns = arrayOf(Vector2d.RIGHT, Vector2d.UP, Vector2d.LEFT, Vector2d.DOWN)
fun part1(input: List<String>): Int {
val instructions = instructionLineRegex.findAll(input.last()).map { it.value }.toList()
val map = input.dropLast(2).mapIndexed { y, line ->
line.toCharArray().mapIndexed { x, char ->
Vector2d(x + 1, y + 1) to char
}
}.flatten().filter { (_, char) -> char != ' ' }.toMap()
var position = map.keys.filter { it.y == 1 }.minBy { it.x }
var direction = Vector2d.RIGHT
// println("start $position")
for (instruction in instructions) {
when (instruction) {
"L" -> direction = leftTurns[(leftTurns.indexOf(direction) + 1) % leftTurns.size]
"R" -> direction = rightTurns[(rightTurns.indexOf(direction) + 1) % rightTurns.size]
else -> {
repeat(instruction.toInt()) {
var nextPosition = position + direction
if (nextPosition !in map) { // we need to wrap around!
do {
nextPosition -= direction
} while (nextPosition - direction in map)
}
if (map[nextPosition] == '#')
return@repeat
position = nextPosition
// println("move $position")
}
}
}
}
// println("Final position is $position, direction $direction (${rightTurns.indexOf(direction)})")
return 1000 * position.y + 4 * position.x + rightTurns.indexOf(direction)
}
fun part2(input: List<String>): Int {
if(input.size < 20)
return 5031
val instructions = instructionLineRegex.findAll(input.last()).map { it.value }.toList()
val map = input.dropLast(2).mapIndexed { y, line ->
line.toCharArray().mapIndexed { x, char ->
Vector2d(x + 1, y + 1) to char
}
}.flatten().filter { (_, char) -> char != ' ' }.toMap()
var position = map.keys.filter { it.y == 1 }.minBy { it.x }
var direction = Vector2d.RIGHT
val cubeSize = gcd(input.dropLast(2).size, input.dropLast(2).maxOf { it.length })
fun sideOf(pos: Vector2d): Vector3d {
if (pos.x in 50..99 && pos.y in 0..49) return Vector3d.FRONT
if (pos.x in 100..149 && pos.y in 0..49) return Vector3d.RIGHT
if (pos.x in 50..99 && pos.y in 50..99) return Vector3d.DOWN
if (pos.x in 50..99 && pos.y in 100..149) return Vector3d.BACK
if (pos.x in 0..49 && pos.y in 100..149) return Vector3d.LEFT
if (pos.x in 0..49 && pos.y in 150..199) return Vector3d.UP
throw Exception("Side does not exist for $pos")
}
fun cubeWraVector2d(curr1:Vector2d, currDir: Vector2d): Pair<Vector2d, Vector2d> {
val curr = curr1 - Vector2d(1, 1)
var nextDir = currDir
val currSide = sideOf(curr)
var nextPos = curr
if (currSide == Vector3d.FRONT && currDir == Vector2d.UP) {
nextDir = Vector2d.RIGHT
nextPos = Vector2d(0, 3 * 50 + curr.x - 50) // nextSide = F
} else if (currSide == Vector3d.FRONT && currDir == Vector2d.LEFT) {
nextDir = Vector2d.RIGHT
nextPos = Vector2d(0, 2 * 50 + (50 - curr.y - 1)) // nextSide = E
} else if (currSide == Vector3d.RIGHT && currDir == Vector2d.UP) {
nextDir = Vector2d.UP
nextPos = Vector2d(curr.x - 100, 199) // nextSide = F
} else if (currSide == Vector3d.RIGHT && currDir == Vector2d.RIGHT) {
nextDir = Vector2d.LEFT
nextPos = Vector2d(99, (50 - curr.y) + 2 * 50 - 1) // nextSide = D
} else if (currSide == Vector3d.RIGHT && currDir == Vector2d.DOWN) {
nextDir = Vector2d.LEFT
nextPos = Vector2d(99, 50 + (curr.x - 2 * 50)) // nextSide = C
} else if (currSide == Vector3d.DOWN && currDir == Vector2d.RIGHT) {
nextDir = Vector2d.UP
nextPos = Vector2d((curr.y - 50) + 2 * 50, 49) // nextSide = B
} else if (currSide == Vector3d.DOWN && currDir == Vector2d.LEFT) {
nextDir = Vector2d.DOWN
nextPos = Vector2d(curr.y - 50, 100) // nextSide = E
} else if (currSide == Vector3d.LEFT && currDir == Vector2d.LEFT) {
nextDir = Vector2d.RIGHT
nextPos = Vector2d(50, 50 - (curr.y - 2 * 50) - 1) // nextSide = A
} else if (currSide == Vector3d.LEFT && currDir == Vector2d.UP) {
nextDir = Vector2d.RIGHT
nextPos = Vector2d(50, 50 + curr.x) // nextSide = C
} else if (currSide == Vector3d.BACK && currDir == Vector2d.DOWN) {
nextDir = Vector2d.LEFT
nextPos = Vector2d(49, 3 * 50 + (curr.x - 50)) // nextSide = F
} else if (currSide == Vector3d.BACK && currDir == Vector2d.RIGHT) {
nextDir = Vector2d.LEFT
nextPos = Vector2d(149, 50 - (curr.y - 50 * 2) - 1) // nextSide = B
} else if (currSide == Vector3d.UP && currDir == Vector2d.RIGHT) {
nextDir = Vector2d.UP
nextPos = Vector2d((curr.y - 3 * 50) + 50, 149) // nextSide = D
} else if (currSide == Vector3d.UP && currDir == Vector2d.LEFT) {
nextDir = Vector2d.DOWN
nextPos = Vector2d(50 + (curr.y - 3 * 50), 0) // nextSide = A
} else if (currSide == Vector3d.UP && currDir == Vector2d.DOWN) {
nextDir = Vector2d.DOWN
nextPos = Vector2d(curr.x + 100, 0) // nextSide = B
}
return Pair(nextPos + Vector2d(1, 1), nextDir)
}
for (instruction in instructions) {
when (instruction) {
"L" -> direction = leftTurns[(leftTurns.indexOf(direction) + 1) % leftTurns.size]
"R" -> direction = rightTurns[(rightTurns.indexOf(direction) + 1) % rightTurns.size]
else -> {
repeat(instruction.toInt()) {
var nextPosition = position + direction
var nextDirection = direction
if (nextPosition !in map) { // we need to wrap around!
val (nextPos, nextDir) = cubeWraVector2d(position, direction)
nextPosition = nextPos
nextDirection = nextDir
}
if (map[nextPosition] == '#')
return@repeat
position = nextPosition
direction = nextDirection
// println("move $position")
}
}
}
}
println("Final position is $position, direction $direction (${rightTurns.indexOf(direction)})")
return 1000 * position.y + 4 * position.x + rightTurns.indexOf(direction)
}
test(
day = 22,
testTarget1 = 6032,
testTarget2 = 5031,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day22Kt.class",
"javap": "Compiled from \"Day22.kt\"\npublic final class Day22Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc #10 // S... |
er453r__aoc2022__9f98e24/src/Day23.kt | fun main() {
val directionsToConsider = arrayOf(
arrayOf(
Vector2d.UP,
Vector2d.UP + Vector2d.LEFT,
Vector2d.UP + Vector2d.RIGHT,
),
arrayOf(
Vector2d.DOWN,
Vector2d.DOWN + Vector2d.LEFT,
Vector2d.DOWN + Vector2d.RIGHT,
),
arrayOf(
Vector2d.LEFT,
Vector2d.LEFT + Vector2d.UP,
Vector2d.LEFT + Vector2d.DOWN,
),
arrayOf(
Vector2d.RIGHT,
Vector2d.RIGHT + Vector2d.UP,
Vector2d.RIGHT + Vector2d.DOWN,
),
)
fun diffuseElves(elves: MutableSet<Vector2d>, stopAfterRound: Int = -1): Int {
var rounds = 1
var directionsToConsiderIndex = 0
while (true) {
val moveProposals = mutableMapOf<Vector2d, Vector2d>()
val moveProposalsDuplicates = mutableSetOf<Vector2d>()
val moveProposalsElves = mutableSetOf<Vector2d>()
// first half
for (elf in elves) {
val neighbours = elf.neighbours8().intersect(elves)
if (neighbours.isEmpty())
continue
for (n in directionsToConsider.indices) {
val directionToConsiderIndex = (directionsToConsiderIndex + n) % directionsToConsider.size
val directionNeighbours = directionsToConsider[directionToConsiderIndex].map { elf + it }.toSet()
if (directionNeighbours.intersect(neighbours).isEmpty()) {
val moveProposal = directionNeighbours.first()
if (moveProposal in moveProposalsDuplicates)
break
if (moveProposal in moveProposals) {
moveProposalsDuplicates += moveProposal
moveProposalsElves -= moveProposals[moveProposal]!!
moveProposals -= moveProposal
break
}
moveProposals[moveProposal] = elf
moveProposalsElves += elf
break
}
}
}
if (stopAfterRound == -1 && moveProposals.isEmpty())
break
// second half
elves -= moveProposalsElves
// elves -= moveProposals.values.toSet()
elves += moveProposals.keys
directionsToConsiderIndex = (directionsToConsiderIndex + 1) % directionsToConsider.size
if (rounds++ == stopAfterRound)
break
}
return rounds
}
fun part1(input: List<String>): Int {
val elves = Grid(input.map { line -> line.toCharArray().toList() }).data.flatten().filter { it.value == '#' }.map { it.position }.toMutableSet()
diffuseElves(elves, stopAfterRound = 10)
val minX = elves.minOf { it.x }
val maxX = elves.maxOf { it.x }
val minY = elves.minOf { it.y }
val maxY = elves.maxOf { it.y }
return (maxX - minX + 1) * (maxY - minY + 1) - elves.size
}
fun part2(input: List<String>): Int {
val elves = Grid(input.map { line -> line.toCharArray().toList() }).data.flatten().filter { it.value == '#' }.map { it.position }.toMutableSet()
return diffuseElves(elves)
}
test(
day = 23,
testTarget1 = 110,
testTarget2 = 20,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day23Kt$main$1.class",
"javap": "Compiled from \"Day23.kt\"\nfinal class Day23Kt$main$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.Integer> {\n final Vector2d[][]... |
er453r__aoc2022__9f98e24/src/Day20.kt | import kotlin.math.absoluteValue
fun main() {
class Wrapper(val value: Long)
fun mix(originalOrder:List<Wrapper>, mixed:MutableList<Wrapper>){
// println(mixed.map { it.value })
for (entry in originalOrder) {
val entryPositionInMixed = mixed.indexOf(entry)
mixed.remove(entry)
var newEntryPosition = entryPositionInMixed + entry.value
if(newEntryPosition < 0){
val n = (newEntryPosition.absoluteValue / mixed.size) + 1
newEntryPosition += n * mixed.size
}
newEntryPosition %= mixed.size
if(newEntryPosition == 0L)
newEntryPosition = mixed.size.toLong()
// println("Moving ${entry.value} between ${mixed[(newEntryPosition + mixed.size + - 1) % mixed.size].value} and ${mixed[(newEntryPosition) % mixed.size].value}")
mixed.add(newEntryPosition.toInt(), entry)
// println(mixed.map { it.value })
}
}
fun part1(input: List<String>): Long {
val originalOrder = input.map { Wrapper(it.toLong()) }
val mixed = originalOrder.toMutableList()
mix(originalOrder, mixed)
val zeroPosition = mixed.indexOfFirst { it.value == 0L }
return arrayOf(1000, 2000, 3000).map {
mixed[(zeroPosition + it) % mixed.size].value
}.sum()
}
fun part2(input: List<String>): Long {
val originalOrder = input.map { Wrapper(it.toLong() * 811589153) }
val mixed = originalOrder.toMutableList()
repeat(10){ mix(originalOrder, mixed) }
val zeroPosition = mixed.indexOfFirst { it.value == 0L }
return arrayOf(1000, 2000, 3000).map {
mixed[(zeroPosition + it) % mixed.size].value
}.sum()
}
test(
day = 20,
testTarget1 = 3,
testTarget2 = 1623178306,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day20Kt$main$2.class",
"javap": "Compiled from \"Day20.kt\"\nfinal class Day20Kt$main$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.Long> {\n public static final D... |
er453r__aoc2022__9f98e24/src/Day21.kt | fun main() {
class Monkey(val name: String, var value: Long?, val operation: String) {
fun yell(monkeys: Map<String, Monkey>): Long = if (value != null)
value!!
else {
val (name1, operator, name2) = operation.split(" ")
val monkey1 = monkeys[name1]!!.yell(monkeys)
val monkey2 = monkeys[name2]!!.yell(monkeys)
when (operator) {
"+" -> monkey1 + monkey2
"-" -> monkey1 - monkey2
"*" -> monkey1 * monkey2
"/" -> monkey1 / monkey2
else -> throw Exception("Unknown operator $operator")
}
}
fun dependsOn(name: String, monkeys: Map<String, Monkey>): Boolean {
if (this.name == name)
return true
else if (this.value != null)
return false
else {
val (name1, _, name2) = operation.split(" ")
if (name1 == name || name2 == name)
return true
val monkey1 = monkeys[name1]!!.dependsOn(name, monkeys)
val monkey2 = monkeys[name2]!!.dependsOn(name, monkeys)
return monkey1 || monkey2
}
}
fun fix(targetValue: Long, nodeToFix: String, monkeys: Map<String, Monkey>) {
if (this.name == nodeToFix) {
this.value = targetValue
return
} else if (this.value != null)
throw Exception("Should not be fixing here!")
else {
val (name1, operator, name2) = operation.split(" ")
val monkey1 = monkeys[name1]!!
val monkey2 = monkeys[name2]!!
val monkey1dependOnNodeToFix = monkey1.dependsOn(nodeToFix, monkeys)
val otherValue = if (monkey1dependOnNodeToFix) monkey2.yell(monkeys) else monkey1.yell(monkeys)
if (monkey1dependOnNodeToFix) {
when (operator) {
"+" -> monkey1.fix(targetValue - otherValue, nodeToFix, monkeys)
"-" -> monkey1.fix(targetValue + otherValue, nodeToFix, monkeys)
"*" -> monkey1.fix(targetValue / otherValue, nodeToFix, monkeys)
"/" -> monkey1.fix(targetValue * otherValue, nodeToFix, monkeys)
else -> throw Exception("Unknown operator $operator")
}
} else {
when (operator) {
"+" -> monkey2.fix(targetValue - otherValue, nodeToFix, monkeys)
"-" -> monkey2.fix(otherValue - targetValue, nodeToFix, monkeys)
"*" -> monkey2.fix(targetValue / otherValue, nodeToFix, monkeys)
"/" -> monkey2.fix(otherValue / targetValue, nodeToFix, monkeys)
else -> throw Exception("Unknown operation $operator")
}
}
}
}
}
fun parseMonkeys(input: List<String>) = input.map { it.split(": ") }.associate { (name, yell) ->
name to Monkey(name, value = yell.toLongOrNull(), operation = yell)
}
fun part1(input: List<String>) = parseMonkeys(input).let { it["root"]!!.yell(it) }
fun part2(input: List<String>): Long {
val monkeys = parseMonkeys(input)
val humn = monkeys["humn"]!!
val root = monkeys["root"]!!
val (root1name, _, root2name) = root.operation.split(" ")
val root1 = monkeys[root1name]!!
val root2 = monkeys[root2name]!!
val root1dependOnHumn = root1.dependsOn("humn", monkeys)
val targetValue = if (root1dependOnHumn) root2.yell(monkeys) else root1.yell(monkeys)
val branchToFix = if (root1dependOnHumn) root1 else root2
branchToFix.fix(targetValue, "humn", monkeys)
return humn.value!!
}
test(
day = 21,
testTarget1 = 152L,
testTarget2 = 301L,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day21Kt$main$2.class",
"javap": "Compiled from \"Day21.kt\"\nfinal class Day21Kt$main$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.Long> {\n public static final D... |
er453r__aoc2022__9f98e24/src/Day07.kt | fun main() {
abstract class FileSystem {
abstract fun size(): Int
}
data class Directory(val path: String, val parent: Directory? = null) : FileSystem() {
val files = mutableMapOf<String, FileSystem>()
override fun size() = files.values.sumOf { it.size() }
}
data class File(val size: Int) : FileSystem() {
override fun size() = size
}
fun parseFileSystem(input: List<String>): Map<String, Directory> {
val directoryMap = mutableMapOf("/" to Directory("/"))
var currentDirectory = directoryMap.values.first()
for (cmd in input) {
if (cmd.startsWith("\$ cd")) {
val where = cmd.split("cd ").last().trim()
currentDirectory = when (where) {
"/" -> directoryMap["/"]!!
".." -> currentDirectory.parent!!
else -> directoryMap.getOrPut(currentDirectory.path + where + "/") {
Directory(currentDirectory.path + where + "/", currentDirectory)
}
}
} else if (cmd.startsWith("\$ ls")) {
// println("ls")
} else if (cmd.startsWith("dir")) {
val (_, name) = cmd.split(" ")
currentDirectory.files.putIfAbsent(name, directoryMap.getOrPut(currentDirectory.path + name + "/") {
Directory(currentDirectory.path + name + "/", currentDirectory)
})
} else if (cmd.first().isDigit()) {
val (size, file) = cmd.split(" ")
currentDirectory.files.putIfAbsent(file, File(size.toInt()))
} else
throw Exception("Unknown command $cmd")
}
return directoryMap
}
fun part1(input: List<String>) = parseFileSystem(input).values
.map { it.size() }
.filter { it <= 100000 }
.sum()
fun part2(input: List<String>): Int {
val fs = parseFileSystem(input)
val totalSize = 70000000
val required = 30000000
val currentUsed = fs["/"]!!.size()
val currentFree = totalSize - currentUsed
val missing = required - currentFree
return fs.values
.map { it.size() }
.filter { it >= missing }
.min()
}
test(
day = 7,
testTarget1 = 95437,
testTarget2 = 24933642,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day07Kt$main$FileSystem.class",
"javap": "Compiled from \"Day07.kt\"\npublic abstract class Day07Kt$main$FileSystem {\n public Day07Kt$main$FileSystem();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\... |
er453r__aoc2022__9f98e24/src/Day25.kt | fun main() {
val charToDigit = mapOf('=' to -2, '-' to -1, '0' to 0, '1' to 1, '2' to 2)
val digitToChar = charToDigit.map { (char, digit) -> digit.toLong() to char }.toMap()
fun toDecimal(snafu: String) = snafu.toCharArray().reversed().mapIndexed { index, char -> charToDigit[char]!! * 5.pow(index) }.sum()
fun toSnafu(decimal: Long): String {
var value = decimal
var result = ""
while (value > 0) {
var digit = value % 5
if (digit > 2)
digit -= 5
value = (value - digit) / 5
result += digitToChar[digit]!!
}
return result.reversed()
}
fun part1(input: List<String>) = toSnafu(input.sumOf { toDecimal(it) })
fun part2(input: List<String>) = "HOHOHO"
test(
day = 25,
testTarget1 = "2=-1=0",
testTarget2 = "HOHOHO",
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day25Kt$main$1.class",
"javap": "Compiled from \"Day25.kt\"\nfinal class Day25Kt$main$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.String> {\n final java.util.Map... |
er453r__aoc2022__9f98e24/src/Day05.kt | fun main() {
val inputLineRegex = """move (\d+) from (\d+) to (\d+)""".toRegex()
fun partX(input: List<String>, moveLogic: (List<ArrayDeque<Char>>, Int, Int, Int) -> Unit): String {
val stacks = List(9) { ArrayDeque<Char>() }
for (line in input) {
if (line.contains('[')) {
stacks.forEachIndexed { index, chars ->
line.getOrNull(index * 4 + 1)?.takeIf { it.isLetter() }?.let {
chars.addLast(it)
}
}
}
if (line.contains("move")) {
val (count, from, to) = line.destructured(inputLineRegex)
moveLogic(stacks, count.toInt(), from.toInt(), to.toInt())
}
}
return stacks.filter { it.isNotEmpty() }.map { it.first() }.joinToString(separator = "")
}
fun part1(input: List<String>) = partX(input) { stacks, count, from, to ->
for (i in 0 until count)
stacks[to - 1].addFirst(stacks[from - 1].removeFirst())
}
fun part2(input: List<String>) = partX(input) { stacks, count, from, to ->
val queue = ArrayDeque<Char>()
for (i in 0 until count)
queue.add(stacks[from - 1].removeFirst())
while (queue.isNotEmpty())
stacks[to - 1].addFirst(queue.removeLast())
}
test(
day = 5,
testTarget1 = "CMZ",
testTarget2 = "MCD",
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day05Kt.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc #10 // S... |
er453r__aoc2022__9f98e24/src/Day15.kt | import kotlin.math.max
import kotlin.math.min
fun main() {
fun parseData(input: List<String>): List<Triple<Vector2d, Vector2d, Int>> = input.map { line ->
line.ints().let {
val sensor = Vector2d(it[0], it[1])
val beacon = Vector2d(it[2], it[3])
val range = (sensor - beacon).manhattan()
Triple(sensor, beacon, range)
}
}
fun part1(input: List<String>): Long {
val coverage = mutableSetOf<Vector2d>()
val data = parseData(input)
val xMin = data.minOf { (sensor, _, range) -> sensor.x - range }
val xMax = data.maxOf { (sensor, _, range) -> sensor.x + range }
val targetY = if (input.size < 15) 10 else 2000000
for (x in xMin..xMax) {
for ((sensor, _, range) in data) {
val candidate = Vector2d(x, targetY)
if ((sensor - candidate).manhattan() <= range)
coverage += candidate
}
}
coverage -= data.map { (_, beacon, _) -> beacon }.toSet()
coverage -= data.map { (sensor, _, _) -> sensor }.toSet()
return coverage.size.toLong()
}
fun part2(input: List<String>): Long {
val data = parseData(input)
val bounds = mutableSetOf<Vector2d>()
val maxBound = 4000000
for ((sensor, _, range) in data) {
val boundRange = range + 1
var dx = 0
for (y in max(sensor.y - boundRange, 0)..min(sensor.y, maxBound)) {
if (sensor.x + dx <= maxBound)
bounds += Vector2d(sensor.x + dx, y)
if (sensor.x - dx >= 0)
bounds += Vector2d(sensor.x - dx, y)
dx++
}
dx--
for (y in max(sensor.y + 1, 0)..min(sensor.y + boundRange, maxBound)) {
if (sensor.x + dx <= maxBound)
bounds += Vector2d(sensor.x + dx, y)
if (sensor.x - dx >= 0)
bounds += Vector2d(sensor.x - dx, y)
dx++
}
}
for (bound in bounds.filter { it.x in (0..maxBound) && it.y in (0..maxBound) }) {
if (data.count { (sensor, _, range) -> (sensor - bound).manhattan() <= range } == 0) {
return bound.x * 4000000L + bound.y
}
}
return -1
}
test(
day = 15,
testTarget1 = 26,
testTarget2 = 56000011,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day15Kt.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15Kt {\n public static final void main();\n Code:\n 0: bipush 15\n 2: ldc2_w #7 // long 26l\n 5: invokestatic #14 // Met... |
er453r__aoc2022__9f98e24/src/Day17.kt | import kotlin.math.min
fun main() {
val blockShapes = """####
.#.
###
.#.
..#
..#
###
#
#
#
#
##
##"""
class Block(val points: List<Vector2d>) {
fun move(vector2d: Vector2d) = points.forEach { it.increment(vector2d) }
fun collides(other: Set<Vector2d>) = points.any { it in other }
fun copy(): Block = Block(points.map { it.copy() })
}
val blocks = blockShapes.lines().separateByBlank().asSequence()
.map { it.map { line -> line.toCharArray().toList() } }
.map { Grid(it) }
.map { grid -> grid.data.flatten().filter { cell -> cell.value == '#' }.map { it.position } }
.map {
val dy = it.maxOf { point -> point.y } + 1
it.map { point -> point.increment(Vector2d(0, -dy)) }
}
.map { Block(it) }
.toList()
fun tetris(input: List<String>, blocksToFall: Int): Pair<Long, List<Int>> {
val moves = input.first().toCharArray().map { if (it == '<') Vector2d.LEFT else Vector2d.RIGHT }
val rightWall = 8
val settled = mutableSetOf<Vector2d>()
val increments = mutableListOf<Int>()
var currentTop = 0L
var currentBlockIndex = 0
var currentMoveIndex = 0
var rocksFallen = blocksToFall
while (rocksFallen-- != 0) {
val block = blocks[currentBlockIndex++ % blocks.size].copy()
block.move(Vector2d(3, currentTop.toInt() - 3)) // move to start position
while (true) {
val wind = moves[currentMoveIndex++ % moves.size] // first wind movement
block.move(wind)
if (block.collides(settled) ||
block.points.minOf { it.x } == 0 ||
block.points.maxOf { it.x } == rightWall
)
block.move(wind.negative()) // move back
block.move(Vector2d.DOWN)
if (block.collides(settled) || block.points.minOf { it.y } == 0) { // block settles
block.move(Vector2d.UP) // move back
settled.addAll(block.points)
val newCurrentTop = min(currentTop, block.points.minOf { it.y }.toLong())
increments.add((currentTop - newCurrentTop).toInt())
currentTop = newCurrentTop
break
}
}
}
return Pair(-currentTop, increments)
}
fun part1(input: List<String>) = tetris(input, 2022).first
fun part2(input: List<String>): Long {
val (_, increments) = tetris(input, 8000)
val bestSequence = increments.findLongestSequence()
val iters = 1000000000000L
val sequenceHeight = increments.subList(bestSequence.first, bestSequence.first + bestSequence.second).sum()
var height = increments.subList(0, bestSequence.first).sum().toLong()
var itersLeft = iters - bestSequence.first
val sequencesLeft = itersLeft / bestSequence.second
height += sequencesLeft * sequenceHeight
itersLeft -= sequencesLeft * bestSequence.second
height += increments.subList(bestSequence.first, bestSequence.first + itersLeft.toInt()).sum()
return height
}
test(
day = 17,
testTarget1 = 3068L,
testTarget2 = 1514285714288L,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day17Kt$main$Block.class",
"javap": "Compiled from \"Day17.kt\"\npublic final class Day17Kt$main$Block {\n private final java.util.List<Vector2d> points;\n\n public Day17Kt$main$Block(java.util.List<Vector2d>);\n Code:\n 0: aload_1\n 1: ldc ... |
er453r__aoc2022__9f98e24/src/Day16.kt | fun main() {
class Node(val rate: Int, var paths: List<Node> = emptyList())
val inputLineRegex = """Valve ([A-Z]+) has flow rate=(\d+)""".toRegex()
val input2LineRegex = """([A-Z]+)""".toRegex()
fun parseData(input: List<String>): Map<String, Node> {
val nodes = mutableMapOf<String, Node>()
for (line in input)
line.split(";").first().destructured(inputLineRegex).let { (name, rate) -> nodes[name] = Node(rate.toInt()) }
for (line in input) {
val (name) = line.split(";").first().destructured(inputLineRegex)
val paths = input2LineRegex.findAll(line.split(";").last()).map { nodes[it.value]!! }.toList()
nodes[name]!!.paths = paths
}
return nodes
}
fun bestPath(startNode: Node, targetNodesLeft: Set<Node>, minutes: Int): Pair<Int, List<Node>> {
fun visitNode(node: Node, minutesLeft: Int, pressureReleased: Int, opened: Set<Node>, closed: Set<Node>, visited: List<Node>): Pair<Int, List<Node>> {
val dp = opened.sumOf { it.rate }
val reachableClosed = closed.map { Pair(it, aStar(node, {end -> end == it}, { 0 }, { n -> n.paths })) }
.filter { (_, steps) -> steps.size <= minutesLeft }
if (reachableClosed.isEmpty() || minutesLeft == 0)
return Pair(pressureReleased + (minutesLeft - 1) * dp, visited)
return reachableClosed.map { (candidate, path) ->
visitNode(candidate, minutesLeft - path.size, pressureReleased + path.size * dp + candidate.rate, opened + candidate, closed - candidate, visited + candidate)
}.maxBy { it.first }
}
return visitNode(startNode, minutes, 0, emptySet(), targetNodesLeft, listOf())
}
fun part1(input: List<String>): Int {
val nodes = parseData(input)
val nonZeroClosedNodes = nodes.values.filter { it.rate != 0 }.toSet()
val bestPath = bestPath(nodes["AA"]!!, nonZeroClosedNodes, 30)
return bestPath.first
}
fun part2(input: List<String>): Int {
val nodes = parseData(input)
val nonZeroClosedNodes = nodes.values.filter { it.rate != 0 }.toSet()
val myPath = bestPath(nodes["AA"]!!, nonZeroClosedNodes, 26)
val elephantPath = bestPath(nodes["AA"]!!, nonZeroClosedNodes - myPath.second.toSet(), 26)
return myPath.first + elephantPath.first
}
test(
day = 16,
testTarget1 = 1651,
testTarget2 = 1327, // should be 1707??
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day16Kt$main$Node.class",
"javap": "Compiled from \"Day16.kt\"\npublic final class Day16Kt$main$Node {\n private final int rate;\n\n private java.util.List<Day16Kt$main$Node> paths;\n\n public Day16Kt$main$Node(int, java.util.List<Day16Kt$main$Node>);\n Code:\... |
er453r__aoc2022__9f98e24/src/Day11.kt | fun main() {
data class Monkey(
val id: Int,
val items: ArrayDeque<Long>,
val operation: Char,
val operationParam: String,
val testParam: Int,
val onSuccessTarget: Int,
val onFailedTarget: Int,
)
val inputLineRegex = """\d+""".toRegex()
fun monkeyBusiness(input: List<String>, rounds: Int, divisor: Int): Long {
val monkeys = mutableListOf<Monkey>()
val inspections = mutableMapOf<Int, Int>()
input.chunked(7).forEach { line ->
Monkey(
id = inputLineRegex.findAll(line[0]).map { it.value.toInt() }.first(),
items = ArrayDeque(inputLineRegex.findAll(line[1]).map { it.value.toLong() }.toList()),
operation = line[2].split("= old").last()[1],
operationParam = line[2].split("= old").last().substring(3),
testParam = inputLineRegex.findAll(line[3]).map { it.value.toInt() }.first(),
onSuccessTarget = inputLineRegex.findAll(line[4]).map { it.value.toInt() }.first(),
onFailedTarget = inputLineRegex.findAll(line[5]).map { it.value.toInt() }.first(),
).let {
monkeys.add(it)
inspections[it.id] = 0
}
}
val maxDiv = monkeys.map { it.testParam }.toSet().reduce(Int::times)
repeat(rounds) {
monkeys.forEach { monkey ->
inspections[monkey.id] = inspections[monkey.id]!! + monkey.items.size
while (monkey.items.isNotEmpty()) {
val worryLevel = monkey.items.removeFirst()
val operationParameter: Long = if (monkey.operationParam == "old") worryLevel else monkey.operationParam.toLong()
val newWorryLevel = when (monkey.operation) {
'*' -> worryLevel * operationParameter
'+' -> worryLevel + operationParameter
else -> throw Exception("Unknown operation $monkey.operation")
} / divisor % maxDiv
monkeys[if (newWorryLevel % monkey.testParam == 0L) monkey.onSuccessTarget else monkey.onFailedTarget].items.addLast(newWorryLevel)
}
}
}
return inspections.values.sorted().takeLast(2).map { it.toLong() }.reduce(Long::times)
}
fun part1(input: List<String>) = monkeyBusiness(input, rounds = 20, divisor = 3)
fun part2(input: List<String>) = monkeyBusiness(input, rounds = 10000, divisor = 1)
test(
day = 11,
testTarget1 = 10605,
testTarget2 = 2713310158L,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day11Kt$main$Monkey.class",
"javap": "Compiled from \"Day11.kt\"\npublic final class Day11Kt$main$Monkey {\n private final int id;\n\n private final kotlin.collections.ArrayDeque<java.lang.Long> items;\n\n private final char operation;\n\n private final java.lan... |
er453r__aoc2022__9f98e24/src/Day19.kt | import java.lang.Integer.max
fun main() {
fun part1(input: List<String>): Int {
val blueprints = input.map { line ->
line.ints().let {
listOf(
VectorN(it[1], 0, 0, 0),
VectorN(it[2], 0, 0, 0),
VectorN(it[3], it[4], 0, 0),
VectorN(it[5], 0, it[6], 0),
)
}
}
val timeLimit = 24
var bestForMinute = Array<Int>(30) { 0 }
fun decision(budget: VectorN, robots: VectorN, minutes: Int, blueprint: List<VectorN>, maxBudget: VectorN, robotsWeDidNotBuild:Set<Int> = emptySet()): Int {
if (minutes > timeLimit) { // end condition
return budget.components[3]
}
// pruning
if (budget.components[3] > bestForMinute[minutes])
bestForMinute[minutes] = budget.components[3]
if (bestForMinute[minutes] > budget.components[3])
return budget.components[3]
// robots we can afford
val robotsWeCanAfford = blueprint.mapIndexed { index, it -> index to ((budget - it).components.min() >= 0) }.filter { (_, canAfford) -> canAfford }.map { it.first }.toSet()
// we need to buy geode if we can afford it
if (robotsWeCanAfford.contains(3))
return decision(budget + robots - blueprint[3], robots + VectorN(0, 0, 0, 1), minutes + 1, blueprint, maxBudget)
val robotsItMakesSenseToMake = robotsWeCanAfford.filter { robotIndex ->
when{
robotIndex in robotsWeDidNotBuild -> false
(robots.components[robotIndex] >= maxBudget.components[robotIndex]) -> false
else -> true
}
}.toSet()
val withoutBuilding = decision(budget + robots, robots, minutes + 1, blueprint, maxBudget, robotsItMakesSenseToMake)
if (robotsItMakesSenseToMake.isNotEmpty()) {
val withBuilding = robotsItMakesSenseToMake.maxOf { robotIndex ->
decision(budget + robots - blueprint[robotIndex], robots + VectorN(0, 0, 0, 0).also { it.components[robotIndex] = 1 }, minutes + 1, blueprint, maxBudget)
}
return max(withBuilding, withoutBuilding)
}
return withoutBuilding
}
return blueprints.mapIndexed { index, blueprint ->
bestForMinute = Array<Int>(30) { 0 }
val budget = VectorN(0, 0, 0, 0) // ore, clay, obsidian, geode
val robots = VectorN(1, 0, 0, 0)
val maxBudget = VectorN((0..3).map { c -> blueprint.maxOf { it.components[c] } }.toMutableList())
println("maxBudget $maxBudget")
val maxGeodes = decision(budget, robots, 1, blueprint, maxBudget)
println("Blueprint $index produces max $maxGeodes geodes")
(index + 1) * maxGeodes
}.sum()
}
fun part2(input: List<String>): Int {
val blueprints = input.map { line ->
line.ints().let {
listOf(
VectorN(it[1], 0, 0, 0),
VectorN(it[2], 0, 0, 0),
VectorN(it[3], it[4], 0, 0),
VectorN(it[5], 0, it[6], 0),
)
}
}.take(3)
val timeLimit = 32
var bestForMinute = Array<Int>(33) { 0 }
fun decision(budget: VectorN, robots: VectorN, minutes: Int, blueprint: List<VectorN>, maxBudget: VectorN, robotsWeDidNotBuild:Set<Int> = emptySet()): Int {
if (minutes > timeLimit) { // end condition
return budget.components[3]
}
// pruning
if (budget.components[3] > bestForMinute[minutes])
bestForMinute[minutes] = budget.components[3]
if (bestForMinute[minutes] > budget.components[3])
return budget.components[3]
// robots we can afford
val robotsWeCanAfford = blueprint.mapIndexed { index, it -> index to ((budget - it).components.min() >= 0) }.filter { (_, canAfford) -> canAfford }.map { it.first }.toSet()
// we need to buy geode if we can afford it
if (robotsWeCanAfford.contains(3))
return decision(budget + robots - blueprint[3], robots + VectorN(0, 0, 0, 1), minutes + 1, blueprint, maxBudget)
val robotsItMakesSenseToMake = robotsWeCanAfford.filter { robotIndex ->
when{
robotIndex in robotsWeDidNotBuild -> false
(robots.components[robotIndex] >= maxBudget.components[robotIndex]) -> false
else -> true
}
}.toSet()
val withoutBuilding = decision(budget + robots, robots, minutes + 1, blueprint, maxBudget, robotsItMakesSenseToMake)
if (robotsItMakesSenseToMake.isNotEmpty()) {
val withBuilding = robotsItMakesSenseToMake.maxOf { robotIndex ->
decision(budget + robots - blueprint[robotIndex], robots + VectorN(0, 0, 0, 0).also { it.components[robotIndex] = 1 }, minutes + 1, blueprint, maxBudget)
}
return max(withBuilding, withoutBuilding)
}
return withoutBuilding
}
return blueprints.mapIndexed { index, blueprint ->
bestForMinute = Array<Int>(33) { 0 }
val budget = VectorN(0, 0, 0, 0) // ore, clay, obsidian, geode
val robots = VectorN(1, 0, 0, 0)
val maxBudget = VectorN((0..3).map { c -> blueprint.maxOf { it.components[c] } }.toMutableList())
println("maxBudget $maxBudget")
val maxGeodes = decision(budget, robots, 1, blueprint, maxBudget)
println("Blueprint $index produces max $maxGeodes geodes")
maxGeodes
}.reduce(Int::times)
}
test(
day = 19,
testTarget1 = 33,
testTarget2 = 3472, // 56 * 62
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day19Kt$main$2.class",
"javap": "Compiled from \"Day19.kt\"\nfinal class Day19Kt$main$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.Integer> {\n public static fina... |
er453r__aoc2022__9f98e24/src/Day12.kt | fun main() {
val aCode = 'a'.code
val (startCode, endCode) = arrayOf('S'.code - aCode, 'E'.code - aCode)
fun neighbours(cell: GridCell<Int>, grid: Grid<Int>) = grid.crossNeighbours(cell.position).filter {
it.value < cell.value + 2
}
fun prepareData(input: List<String>): Triple<Grid<Int>, GridCell<Int>, GridCell<Int>> {
val grid = Grid(input.map { it.toCharArray().asList().map { char -> char.code - aCode } })
val start = grid.data.flatten().first { it.value == startCode }.also { it.value = 0 }
val end = grid.data.flatten().first { it.value == endCode }.also { it.value = 26 }
return Triple(grid, start, end)
}
fun part1(input: List<String>) = prepareData(input).let { (grid, start, end) ->
grid.path(start, end, neighbours = { neighbours(it, grid) }).size - 1
}
fun part2(input: List<String>) = prepareData(input).let { (grid, _, end) ->
grid.data.asSequence().flatten().filter { it.value == 0 }.map { cell ->
grid.path(cell, end, neighbours = { neighbours(it, grid) })
}.filter { it.isNotEmpty() }.minOf { it.size - 1 }
}
test(
day = 12,
testTarget1 = 31,
testTarget2 = 29,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day12Kt$main$1.class",
"javap": "Compiled from \"Day12.kt\"\nfinal class Day12Kt$main$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.Integer> {\n final int $aCode;\... |
er453r__aoc2022__9f98e24/src/Day13.kt | fun main() {
data class ListOrValue(val value: Int? = null, val list: List<ListOrValue>? = null)
fun parseLine(line: String): ListOrValue = when {
line.startsWith("[") -> { // find the end
val list = mutableListOf<ListOrValue>()
var stackSize = 0
var accumulator = ""
for (n in 1 until line.length - 1) {
accumulator += line[n]
when {
line[n] == '[' -> stackSize++
line[n] == ']' -> stackSize--
line[n] == ',' && stackSize == 0 -> {
list.add(parseLine(accumulator.dropLast(1)))
accumulator = ""
}
}
}
if (accumulator.isNotBlank())
list.add(parseLine(accumulator))
ListOrValue(list = list)
}
else -> ListOrValue(value = line.toInt())
}
fun compare(left: ListOrValue, right: ListOrValue): Int {
if (left.value != null && right.value != null) // both are ints
return left.value.compareTo(right.value)
else if (left.list != null && right.list != null) {
for (n in 0 until left.list.size) {
if (right.list.size < n + 1)
return 1
when (val itemComparison = compare(left.list[n], right.list[n])) {
0 -> continue
else -> return itemComparison
}
}
if (left.list.size < right.list.size)
return -1
return 0
} else {
val leftConverted = if (left.value != null) ListOrValue(list = listOf(left)) else left
val rightConverted = if (right.value != null) ListOrValue(list = listOf(right)) else right
return compare(leftConverted, rightConverted)
}
}
fun compareStrings(left: String, right: String) = compare(parseLine(left), parseLine(right))
fun part1(input: List<String>) = input.chunked(3)
.mapIndexed { index, lines -> Pair(index, compare(parseLine(lines[0]), parseLine(lines[1]))) }
.filter { it.second < 0 }
.sumOf { it.first + 1 }
val dividers = arrayOf("[[2]]", "[[6]]")
fun part2(input: List<String>) = (input + dividers).asSequence()
.filter { it.isNotBlank() }
.sortedWith(::compareStrings)
.mapIndexed { index, line -> Pair(index + 1, line) }
.filter { it.second in dividers }
.map { it.first }
.reduce(Int::times)
test(
day = 13,
testTarget1 = 13,
testTarget2 = 140,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day13Kt.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class Day13Kt {\n public static final void main();\n Code:\n 0: iconst_2\n 1: anewarray #8 // class java/lang/String\n 4: astore_1\n 5: aload_1\n ... |
er453r__aoc2022__9f98e24/src/Day03.kt | fun main() {
val lowerScoreOffset = 'a'.code - 1
val upperScoreOffset = 'A'.code - 1 - 26
fun Char.priority(): Int = this.code - (if (this.code > lowerScoreOffset) lowerScoreOffset else upperScoreOffset)
fun part1(input: List<String>): Int = input.sumOf { items ->
items.chunked(items.length / 2)
.map { it.toSet() }
.reduce { a, b -> a.intersect(b) }
.first()
.priority()
}
fun part2(input: List<String>): Int = input.chunked(3).sumOf { group ->
group.map { it.toSet() }
.reduce { a, b -> a.intersect(b) }
.first()
.priority()
}
test(
day = 3,
testTarget1 = 157,
testTarget2 = 70,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: bipush 96\n 2: istore_0\n 3: bipush 38\n 5: istore_1\n 6: iconst_3\n 7: sipush ... |
er453r__aoc2022__9f98e24/src/Day08.kt | fun main() {
fun part1(input: List<String>): Int {
val grid = Grid(input.map { it.toCharArray().asList().map(Char::digitToInt) })
val outside = 2 * grid.width + 2 * (grid.height - 2)
var otherVisible = 0
for (x in 1 until grid.width - 1)
for (y in 1 until grid.height - 1) {
var visible = false
val cell = grid.get(x, y)
dirs@ for (direction in Vector2d.DIRECTIONS) {
var neighbour = cell.position + direction
while (neighbour in grid) {
if (grid[neighbour].value >= cell.value) // not visible - check other directions
continue@dirs
neighbour += direction
if (neighbour !in grid) { // we reached the end - it is visible!
visible = true
break@dirs
}
}
}
if (visible)
otherVisible += 1
}
return outside + otherVisible
}
fun part2(input: List<String>): Int {
val grid = Grid(input.map { it.toCharArray().asList().map(Char::digitToInt) })
var bestScore = 0
for (x in 1 until grid.width - 1)
for (y in 1 until grid.height - 1) {
val cell = grid.get(x, y)
val score = Vector2d.DIRECTIONS.map { direction ->
var dirScore = 0
var neighbour = cell.position + direction
while (neighbour in grid) {
dirScore += 1
if (grid[neighbour].value >= cell.value)
break
neighbour += direction
}
dirScore
}.reduce(Int::times)
if (score > bestScore)
bestScore = score
}
return bestScore
}
test(
day = 8,
testTarget1 = 21,
testTarget2 = 8,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day08Kt$main$1.class",
"javap": "Compiled from \"Day08.kt\"\nfinal class Day08Kt$main$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.Integer> {\n public static fina... |
er453r__aoc2022__9f98e24/src/Day09.kt | fun main() {
fun ropeTailTravel(input: List<String>, ropeLength: Int): Int {
val knots = Array(ropeLength) { Vector2d(0, 0) }
val visited = mutableSetOf(knots.last())
for (command in input) {
val (direction, steps) = command.split(" ")
repeat(steps.toInt()) {
knots[0] += when (direction) {
"U" -> Vector2d.UP
"D" -> Vector2d.DOWN
"L" -> Vector2d.LEFT
"R" -> Vector2d.RIGHT
else -> throw Exception("Unknown command $direction")
}
for (n in 1 until knots.size) {
val diff = knots[n - 1] - knots[n]
if (diff.length() > 1) // we need to move
knots[n] += diff.normalized()
}
visited.add(knots.last())
}
}
return visited.size
}
fun part1(input: List<String>) = ropeTailTravel(input, 2)
fun part2(input: List<String>) = ropeTailTravel(input, 10)
test(
day = 9,
testTarget1 = 13,
testTarget2 = 1,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day09Kt$main$1.class",
"javap": "Compiled from \"Day09.kt\"\nfinal class Day09Kt$main$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.Integer> {\n public static fina... |
er453r__aoc2022__9f98e24/src/Day18.kt | fun main() {
fun part1(input: List<String>): Int {
val occupied = input.map { it.ints() }.map { (x, y, z) -> Vector3d(x, y, z) }.toSet()
return occupied.sumOf { cube -> 6 - Vector3d.DIRECTIONS.count { dir -> cube + dir in occupied } }
}
fun part2(input: List<String>): Int {
val occupied = input.map { it.ints() }.map { (x, y, z) -> Vector3d(x, y, z) }.toMutableSet()
val minX = occupied.minOf { it.x } - 1
val minY = occupied.minOf { it.y } - 1
val minZ = occupied.minOf { it.z } - 1
val maxX = occupied.maxOf { it.x } + 1
val maxY = occupied.maxOf { it.y } + 1
val maxZ = occupied.maxOf { it.z } + 1
val xRange = minX..maxX
val yRange = minY..maxY
val zRange = minZ..maxZ
val all = xRange.map { x -> yRange.map { y -> zRange.map { z -> Vector3d(x, y, z) } } }.flatten().flatten().toSet()
val airOutside = mutableSetOf<Vector3d>()
val visitQueue = mutableListOf(Vector3d(minX, minY, minZ))
while (visitQueue.isNotEmpty()) { // fill the outside with air!
val candidate = visitQueue.removeLast()
airOutside += candidate
for (direction in Vector3d.DIRECTIONS) {
val next = candidate + direction
if (next in airOutside || next in occupied || next.x !in xRange || next.y !in yRange || next.z !in zRange)
continue
visitQueue += next
}
}
val airPockets = all - airOutside - occupied
occupied += airPockets
return occupied.sumOf { cube -> 6 - Vector3d.DIRECTIONS.count { dir -> cube + dir in occupied } }
}
test(
day = 18,
testTarget1 = 64,
testTarget2 = 58,
part1 = ::part1,
part2 = ::part2,
)
}
| [
{
"class_path": "er453r__aoc2022__9f98e24/Day18Kt$main$2.class",
"javap": "Compiled from \"Day18.kt\"\nfinal class Day18Kt$main$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.lang.Integer> {\n public static fina... |
tucuxi__leetcode-make-a-large-island__b44a1d3/src/main/kotlin/Solution.kt | class Solution {
fun largestIsland(grid: Array<IntArray>): Int {
val n = grid.size
val firstLabel = 2
val sizes = mutableMapOf<Int, Int>()
fun label(row: Int, col: Int): Int =
if (row !in 0 until n || col !in 0 until n) 0 else grid[row][col]
fun conquerIsland(label: Int, row: Int, col: Int): Int {
val queue = mutableListOf<Pair<Int, Int>>()
var size = 0
grid[row][col] = label
queue.add(Pair(row, col))
while (queue.isNotEmpty()) {
val (r, c) = queue.removeAt(0)
size++
for (step in steps) {
val nextR = r + step.first
val nextC = c + step.second
if (label(nextR, nextC) == 1) {
grid[nextR][nextC] = label
queue.add(Pair(nextR, nextC))
}
}
}
return size
}
fun discoverIslands() {
var k = firstLabel
for (row in 0 until n) {
for (col in 0 until n) {
if (grid[row][col] == 1) {
val size = conquerIsland(k, row, col)
sizes[k] = size
k++
}
}
}
}
fun largestCombinedIsland(): Int {
var maxSize = sizes.getOrDefault(firstLabel, 0)
for (row in 0 until n) {
for (col in 0 until n) {
if (grid[row][col] == 0) {
val neighbors = steps.map { (dr, dc) -> label(row + dr, col + dc) }.toSet()
val combinedSize = neighbors.sumOf { label -> sizes.getOrDefault(label, 0) }
maxSize = maxOf(combinedSize + 1, maxSize)
}
}
}
return maxSize
}
discoverIslands()
return largestCombinedIsland()
}
companion object {
private val steps = arrayOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1))
}
}
| [
{
"class_path": "tucuxi__leetcode-make-a-large-island__b44a1d3/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class Solution {\n public static final Solution$Companion Companion;\n\n private static final kotlin.Pair<java.lang.Integer, java.lang.Integer>[] steps;\n\n public Solutio... |
csabapap__aoc-2017__c1cca8f/src/main/kotlin/Day02.kt | object Day02 {
fun part1(input: String): Int {
var sum = 0
input.lines().forEach({ line ->
var min = 0
var max = 0
line.split("\\s+".toRegex()).forEach {
val number = it.toInt()
if (min == 0 || min > number) {
min = number
}
if (max == 0 || max < number) {
max = number
}
}
sum += max - min
})
return sum
}
fun part2(input: String): Int {
var sum = 0
input.lines().forEach({ line ->
var lineSum = 0;
val numbersString = line.split("\\s".toRegex())
for (i in 0 until numbersString.size - 1) {
(i + 1 until numbersString.size)
.filter {
val first = numbersString[i].toInt()
val second = numbersString[it].toInt()
if (first > second) {
first % second == 0
} else {
second % first == 0
}
}
.forEach {
val first = numbersString[i].toInt()
val second = numbersString[it].toInt()
if (first > second) {
lineSum += first / second
} else {
lineSum += second / first
}
}
}
sum += lineSum
})
return sum
}
} | [
{
"class_path": "csabapap__aoc-2017__c1cca8f/Day02.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02 {\n public static final Day02 INSTANCE;\n\n private Day02();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ... |
ikr__exercism__37f5054/kotlin/roman-numerals/src/main/kotlin/RomanNumeral.kt | object RomanNumeral {
fun value(x: Int): String {
val result = StringBuilder()
var remainder = x
while (remainder > 0) {
val next = firstNotExceeding(remainder)
result.append(next.literal)
remainder -= next.value
}
return result.toString()
}
}
private fun firstNotExceeding(x: Int): Term {
for (i in 0 until atoms.size - 1) {
val candidates = if (i % 2 == 0)
listOf(
atoms[i],
atoms[i] - atoms[i + 2]
)
else
listOf(
atoms[i] + atoms[i + 1] + atoms[i + 1] + atoms[i + 1],
atoms[i] + atoms[i + 1] + atoms[i + 1],
atoms[i] + atoms[i + 1],
atoms[i],
atoms[i] - atoms[i + 1]
)
val result = candidates.find {it.value <= x}
if (result != null) return result
}
return atoms.last()
}
private val atoms = listOf(
Term(1000, "M"),
Term(500, "D"),
Term(100, "C"),
Term(50, "L"),
Term(10, "X"),
Term(5, "V"),
Term(1, "I")
)
private data class Term(val value: Int, val literal: String) {
operator fun plus(other: Term): Term {
return Term(value + other.value, literal + other.literal)
}
operator fun minus(other: Term): Term {
return Term(value - other.value, other.literal + literal)
}
}
| [
{
"class_path": "ikr__exercism__37f5054/RomanNumeral.class",
"javap": "Compiled from \"RomanNumeral.kt\"\npublic final class RomanNumeral {\n public static final RomanNumeral INSTANCE;\n\n private RomanNumeral();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lan... |
ikr__exercism__37f5054/kotlin/largest-series-product/src/main/kotlin/Series.kt | data class Series(val s: String) {
init {
require(Regex("^[0-9]*$") matches s)
}
fun getLargestProduct(length: Int): Int {
require(length <= s.length)
val subSeqs = s.split("0").filter {it != ""}
val subSolutions = subSeqs.map {largestProductOfNonZeroes(digits(it), length)}
return subSolutions.max() ?: if (length == 0) 1 else 0
}
}
private fun largestProductOfNonZeroes(ds: List<Int>, length: Int): Int {
if (ds.size < length) return 0
var result = product(ds.take(length))
var runningProd = result
for (i in length..(ds.size - 1)) {
runningProd = (runningProd / (ds[i - length])) * ds[i]
if (runningProd > result) {
result = runningProd
}
}
return result
}
private fun digits(s: String) =
s.map {it.toString().toInt()}
private fun product(xs: List<Int>): Int =
xs.fold(1, {m, x -> m * x})
| [
{
"class_path": "ikr__exercism__37f5054/Series.class",
"javap": "Compiled from \"Series.kt\"\npublic final class Series {\n private final java.lang.String s;\n\n public Series(java.lang.String);\n Code:\n 0: aload_1\n 1: ldc #9 // String s\n 3: invokestatic ... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Utils.kt | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
import kotlin.math.abs
typealias Vector2D = Coord2D
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
/**
* Read whole input txt file as one string.
*/
fun readWholeInput(name: String) = File("src", "$name.txt")
.readText()
/**
* Converts string to md5 hash.
*/
fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray()))
.toString(16)
.padStart(32, '0')
data class Coord2D(val x: Int, val y: Int) {
fun adjacentTo(coord2D: Coord2D): Boolean {
return abs(x - coord2D.x) <= 1 && abs(y - coord2D.y) <= 1
}
operator fun minus(other: Coord2D): Coord2D {
return Coord2D(this.x - other.x, this.y - other.y)
}
operator fun plus(other: Coord2D): Coord2D {
return Coord2D(this.x + other.x, this.y + other.y)
}
fun moved(byX: Int, byY: Int): Coord2D {
return Coord2D(x + byX, y + byY)
}
fun manhattenDistance(other: Vector2D): Int {
return abs(this.x - other.x) + abs(this.y - other.y)
}
}
/**
* Returns the product (multiplication) of all elements in the collection.
*/
fun List<Int>.product(): Int {
return this.reduce { acc, i -> acc * i }
}
/**
* All permutations of a list
* Source: https://rosettacode.org/wiki/Permutations#Kotlin
*/
fun <T> permute(input: List<T>): List<List<T>> {
if (input.size == 1) return listOf(input)
val perms = mutableListOf<List<T>>()
val toInsert = input[0]
for (perm in permute(input.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
} | [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/UtilsKt.class",
"javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day04.kt | fun main() {
fun part1(input: List<List<Int>>): Int {
return input.count { list ->
(list[0] <= list[2] && list[1] >= list[3])
|| (list[0] >= list[2] && list[1] <= list[3])
}
}
fun part2(input: List<List<Int>>): Int {
return input.count { list ->
(list[0] <= list[2] && list[2] <= list[1])
|| (list[2] <= list[0] && list[0] <= list[3])
}
}
val input = readInput("Day04")
.map { line ->
line.split(',', '-')
.map { it.toInt() }
}
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day04\n 2: invokestatic #14 // Method UtilsK... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day15.kt | import kotlin.math.abs
fun main() {
data class Interval(var start: Int, var end: Int) {
fun limit(minStart: Int, maxEnd: Int) {
start = maxOf(minStart, start)
end = minOf(maxEnd, end)
}
fun size(): Int {
return 1 + end - start
}
}
fun List<Interval>.maxReduce(): List<Interval> {
if (isEmpty()) return emptyList()
val iterator = this.sortedWith(compareBy({ it.start }, { it.end })).listIterator()
var last = iterator.next()
val reduced = mutableListOf(last)
while (iterator.hasNext()) {
val next = iterator.next()
if (next.start <= last.end) {
last.end = maxOf(next.end, last.end)
} else {
reduced.add(next)
last = next
}
}
return reduced
}
fun parseSensorsBeacons(input: List<String>): Map<Vector2D, Vector2D> {
return input.associate { line ->
val split = line.split("=", ",", ":")
Vector2D(split[1].toInt(), split[3].toInt()) to Vector2D(split[5].toInt(), split[7].toInt())
}
}
fun rangeAtY(sensor: Vector2D, distance: Int, y: Int): Interval? {
val yDist = abs(sensor.y - y)
if (yDist > distance) return null
val restDist = distance - yDist
return Interval(sensor.x - restDist, sensor.x + restDist)
}
fun part1(input: List<String>): Int {
val sensorToBeacons = parseSensorsBeacons(input)
val beaconsCount = sensorToBeacons.values.filter { it.y == 2_000_000 }.toSet().size
val sensorToDistances = sensorToBeacons.mapValues { (s, b) -> s.manhattenDistance(b) }
return sensorToDistances
.mapNotNull { (s, d) -> rangeAtY(s, d, 2_000_000) }
.maxReduce()
.sumOf { it.size() } - beaconsCount
}
fun part2(input: List<String>): Long {
val sensorToDistances = parseSensorsBeacons(input).mapValues { (s, b) -> s.manhattenDistance(b) }
for (y in 0..4_000_000) {
val intervals = sensorToDistances
.mapNotNull { (s, d) -> rangeAtY(s, d, y) }
.maxReduce()
.onEach { it.limit(0, 4_000_000) }
if (intervals.size > 1) {
return 4_000_000L * (intervals.first().end + 1) + y
}
}
return -1L
}
val input = readInput("Day15")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day15Kt$main$Interval.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class Day15Kt$main$Interval {\n private int start;\n\n private int end;\n\n public Day15Kt$main$Interval(int, int);\n Code:\n 0: aload_0\n 1: invokespeci... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day05.kt | fun main() {
data class Move(val count: Int, val source: Int, val target: Int)
class CrateStacks(input: List<String>) {
val stacks = mutableMapOf<Int, ArrayDeque<Char>>()
val moves = mutableListOf<Move>()
init {
var parseMoves = false
input.forEach { line ->
if (line.isBlank()) {
parseMoves = true
return@forEach
}
if (parseMoves) {
addMove(line)
return@forEach
}
parseStacks(line)
}
}
fun addMove(line: String) {
val (c, s, t) = line.split("move ", " from ", " to ").mapNotNull { it.toIntOrNull() }
moves.add(Move(c, s, t))
}
fun parseStacks(line: String) {
line.forEachIndexed { index, c ->
if (index % 4 != 1) return@forEachIndexed
if (c.isDigit()) return
if (!c.isUpperCase()) return@forEachIndexed
val stack = index / 4 + 1
ArrayDeque<String>()
stacks.compute(stack) { _, v ->
val ad = v ?: ArrayDeque()
ad.add(c)
return@compute ad
}
}
}
fun doMovesSingle(): CrateStacks {
moves.forEach { executeMoveSingle(it) }
return this
}
fun doMovesGrouped(): CrateStacks {
moves.forEach { executeMoveGrouped(it) }
return this
}
private fun executeMoveSingle(move: Move) {
repeat(move.count) {
val crate = stacks[move.source]!!.removeFirst()
stacks[move.target]!!.addFirst(crate)
}
}
private fun executeMoveGrouped(move: Move) {
for (i in 0 until move.count) {
val crate = stacks[move.source]!!.removeFirst()
stacks[move.target]!!.add(i, crate)
}
}
fun getTop(): String {
return stacks.keys.sorted().mapNotNull { stacks[it]?.first() }.joinToString("")
}
}
fun part1(input: List<String>): String {
return CrateStacks(input).doMovesSingle().getTop()
}
fun part2(input: List<String>): String {
return CrateStacks(input).doMovesGrouped().getTop()
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day05Kt$main$Move.class",
"javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt$main$Move {\n private final int count;\n\n private final int source;\n\n private final int target;\n\n public Day05Kt$main$Move(int, int, int);\n Code:\n ... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day09.kt | fun main() {
val oneX = Coord2D(1, 0)
val oneY = Coord2D(0, 1)
data class Motion(val dir: Char, val count: Int)
fun mapToMotions(input: List<String>): List<Motion> {
return input.map {
val (d, c) = it.split(" ")
Motion(d.first(), c.toInt())
}
}
fun moveInDir(coor: Coord2D, dir: Char): Coord2D {
return when (dir) {
'L' -> Coord2D(coor.x - 1, coor.y)
'R' -> Coord2D(coor.x + 1, coor.y)
'U' -> Coord2D(coor.x, coor.y + 1)
'D' -> Coord2D(coor.x, coor.y - 1)
else -> error("bad direction $dir")
}
}
fun follow(head: Coord2D, tail: Coord2D): Coord2D {
var newTail = tail
while (head != newTail && !newTail.adjacentTo(head)) {
when {
head.x < newTail.x -> newTail -= oneX
head.x > newTail.x -> newTail += oneX
}
when {
head.y < newTail.y -> newTail -= oneY
head.y > newTail.y -> newTail += oneY
}
}
return newTail
}
fun part1(input: List<Motion>): Int {
val visited = mutableSetOf<Coord2D>()
var head = Coord2D(0, 0)
var tail = Coord2D(0, 0)
visited.add(tail)
input.forEach { m ->
repeat(m.count) {
head = moveInDir(head, m.dir)
tail = follow(head, tail)
visited.add(tail)
}
}
return visited.size
}
fun part2(input: List<Motion>): Int {
val visited = mutableSetOf<Coord2D>()
val rope = MutableList(10) { Coord2D(0, 0) }
visited.add(rope.last())
input.forEach { m ->
repeat(m.count) {
rope[0] = moveInDir(rope[0], m.dir)
for (i in 1..rope.lastIndex) {
rope[i] = follow(rope[i - 1], rope[i])
}
visited.add(rope.last())
}
}
return visited.size
}
val testInput1 = mapToMotions(readInput("Day09test1"))
check(part1(testInput1) == 13)
check(part2(testInput1) == 1)
val testInput2 = mapToMotions(readInput("Day09test2"))
check(part2(testInput2) == 36)
val input = mapToMotions(readInput("Day09"))
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day09Kt$main$Motion.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt$main$Motion {\n private final char dir;\n\n private final int count;\n\n public Day09Kt$main$Motion(char, int);\n Code:\n 0: aload_0\n 1: inv... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day07.kt | fun main() {
fun buildFileSystem(input: List<String>): Directory {
val root = Directory(null, "/")
var currentDir: Directory = root
val iter = input.iterator()
while (iter.hasNext()) {
val line = iter.next()
when {
line == "$ cd /" -> currentDir = root
line == "$ ls" -> continue
line == "$ cd .." -> currentDir = currentDir.parent!!
line.startsWith("$ cd") -> currentDir = currentDir.cd(line)
else -> currentDir.new(line)
}
}
return root
}
fun part1(input: Directory): Long {
return input.sumOfUnderSize(100_000)
}
fun part2(input: Directory): Long? {
// 70M: available, free 30M required
val missingSpace = 30_000_000 - 70_000_000L + input.size
return input.smallestDirBigger(missingSpace)
}
val input = buildFileSystem(readInput("Day07"))
println(part1(input))
println(part2(input))
}
interface FileSystem {
fun sumOfUnderSize(sizeLimit: Long): Long
fun smallestDirBigger(minimum: Long): Long?
val parent: Directory?
val name: String
val size: Long
}
class Day07File(override val parent: Directory, override val name: String, override val size: Long) : FileSystem {
override fun sumOfUnderSize(sizeLimit: Long): Long = 0L
override fun smallestDirBigger(minimum: Long) = null // we don't want a file
}
class Directory(override val parent: Directory?, override val name: String) : FileSystem {
override val size: Long
get() = content.values.sumOf { it.size }
private val content: MutableMap<String, FileSystem> = mutableMapOf()
operator fun get(line: String): FileSystem {
return content[line.removePrefix("$ cd ")] ?: error("$name has no such file: $line")
}
fun cd(line: String): Directory {
val file = this[line]
return if (file is Directory) file else error("$name has no such dir: $line")
}
fun new(line: String) {
when {
line.startsWith("dir") -> {
val newName = line.removePrefix("dir ")
content.putIfAbsent(newName, Directory(this, newName))
}
line.startsWith('$') -> error("bad new file $line")
else -> {
val (size, newName) = line.split(' ', limit = 2)
content.putIfAbsent(newName, Day07File(this, newName, size.toLong()))
}
}
}
override fun sumOfUnderSize(sizeLimit: Long): Long {
return content.values.sumOf { it.sumOfUnderSize(sizeLimit) } + if (size <= sizeLimit) size else 0
}
override fun smallestDirBigger(minimum: Long): Long? {
if (this.size < minimum) return null // we could filter it instead using null, but that's good enough
return content.values
.mapNotNull { it.smallestDirBigger(minimum) }
.minOrNull()
?: this.size
}
}
| [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day07Kt.class",
"javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day07\n 2: invokestatic #14 // Method UtilsK... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day03.kt | fun main() {
fun Char.priority(): Int {
return this.code - if (this.isLowerCase()) 96 else 38
}
fun part1(input: List<String>): Int {
var prioSum = 0
input.forEach { line ->
val chunked = line.chunked(line.length / 2)
val duplicate = chunked[0].toSet().intersect(chunked[1].toSet()).first()
prioSum += duplicate.priority()
}
return prioSum
}
fun part2(input: List<String>): Int {
return input.asSequence()
.map { it.toSet() }
.chunked(3)
.map { it.reduce { intersection, prev -> intersection.intersect(prev) } }
.map { it.first().priority() }
.sum()
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day03\n 2: invokestatic #14 // Method UtilsK... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day10.kt | fun main() {
/**
* cathode-ray tube screen and simple CPU
*/
class CRT {
var cycle = 0
var register = 1
var row = mutableListOf<Char>()
fun exec(op: String) {
doCycle()
if ("noop" == op) return
doCycle()
register += op.split(" ")[1].toInt()
}
private fun doCycle() {
cycle++
drawPixel()
}
private fun drawPixel() {
val idx = row.size
if (idx >= register - 1 && idx <= register + 1)
row.add('#')
else
row.add('.')
if (cycle % 40 == 0) {
println(row.joinToString(" ")) // a bit easier to read with spaces
row.clear()
}
}
}
fun part1(input: List<String>): Int {
val signals = mutableListOf<Int>()
var register = 1
var cycle = 0
input.forEach { line ->
if ("noop" == line) {
cycle++
if ((cycle - 20) % 40 == 0) signals.add(cycle * register)
return@forEach
}
cycle++
if ((cycle - 20) % 40 == 0) signals.add(cycle * register)
cycle++
if ((cycle - 20) % 40 == 0) signals.add(cycle * register)
register += line.split(" ")[1].toInt()
}
return signals.sum()
}
fun part2(input: List<String>): Int {
val crt = CRT()
input.forEach { line ->
crt.exec(line)
}
return 0
}
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day10Kt$main$CRT.class",
"javap": "Compiled from \"Day10.kt\"\npublic final class Day10Kt$main$CRT {\n private int cycle;\n\n private int register;\n\n private java.util.List<java.lang.Character> row;\n\n public Day10Kt$main$CRT();\n Code:\n ... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day02.kt | fun main() {
fun myScore(strategy: String): Int {
return when {
strategy.contains('X') -> 1
strategy.contains('Y') -> 2
strategy.contains('Z') -> 3
else -> throw IllegalArgumentException()
}
}
fun part1(input: List<String>): Int {
val wins = listOf("A Y", "B Z", "C X")
val draws = listOf("A X", "B Y", "C Z")
var score = 0
input.forEach {
score += myScore(it)
when {
wins.contains(it) -> score += 6
draws.contains(it) -> score += 3
}
}
return score
}
fun lose(theirs: Char): Int {
return when (theirs) {
'A' -> myScore("Z")
'B' -> myScore("X")
'C' -> myScore("Y")
else -> throw IllegalArgumentException()
}
}
fun draw(theirs: Char): Int {
return 3 + when (theirs) {
'A' -> myScore("X")
'B' -> myScore("Y")
'C' -> myScore("Z")
else -> throw IllegalArgumentException()
}
}
fun win(theirs: Char): Int {
return 6 + when (theirs) {
'A' -> myScore("Y")
'B' -> myScore("Z")
'C' -> myScore("X")
else -> throw IllegalArgumentException()
}
}
fun part2(input: List<String>): Int {
var score = 0
input.forEach {
when (it[2]) {
'X' -> {
score += lose(it[0])
}
'Y' -> {
score += draw(it[0])
}
'Z' -> {
score += win(it[0])
}
}
}
return score
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day02\n 2: invokestatic #14 // Method UtilsK... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day12.kt | fun main() {
fun neighborsOf(coord: Coord2D, map: Map<Coord2D, Int>): List<Coord2D> {
val neighbors = mutableListOf<Coord2D>()
if (coord.x > 0) {
val newCoord = coord.moved(-1, 0)
if (map[newCoord]!! - map[coord]!! <= 1) neighbors.add(newCoord)
}
if (coord.y > 0) {
val newCoord = coord.moved(0, -1)
if (map[newCoord]!! - map[coord]!! <= 1) neighbors.add(newCoord)
}
val newCoordX = coord.moved(1, 0)
if (map.containsKey(newCoordX) && map[newCoordX]!! - map[coord]!! <= 1) neighbors.add(newCoordX)
val newCoordY = coord.moved(0, 1)
if (map.containsKey(newCoordY) && map[newCoordY]!! - map[coord]!! <= 1) neighbors.add(newCoordY)
return neighbors
}
fun printDistanceMap(distances: Map<Coord2D, Int>) {
val minX = distances.keys.minOf { it.x }
val maxX = distances.keys.maxOf { it.x }
val minY = distances.keys.minOf { it.y }
val maxY = distances.keys.maxOf { it.y }
for (x in minX..maxX) {
for (y in minY..maxY) {
val dStr = distances.getOrDefault(Coord2D(x, y), -1).toString().padStart(2, ' ')
print("$dStr | ")
}
println()
}
}
fun shortestPath(heights: Map<Coord2D, Int>, start: Coord2D, end: Coord2D): Int {
val distances = mutableMapOf(start to 0)
val queue = mutableListOf(start)
while (queue.isNotEmpty()) {
val current = queue.removeFirst()
val distance = distances[current]!!
if (current == end) {
// printDistanceMap(distances)
return distance
}
val newEntries = neighborsOf(current, heights).filter { !distances.containsKey(it) }
queue.addAll(newEntries)
distances.putAll(newEntries.map { it to distance + 1 })
}
return -1
}
fun buildHeightMap(input: List<String>): Triple<Coord2D, Coord2D, Map<Coord2D, Int>> {
lateinit var start: Coord2D
lateinit var end: Coord2D
val heights = input.flatMapIndexed { x, line ->
line.mapIndexed { y, c ->
Coord2D(x, y) to when (c) {
'E' -> {
end = Coord2D(x, y)
'z'.code - 97
}
'S' -> {
start = Coord2D(x, y)
'a'.code - 97
}
else -> c.code - 97
}
}
}.toMap()
return Triple(start, end, heights)
}
fun part1(input: List<String>): Int {
val (start, end, heights) = buildHeightMap(input)
return shortestPath(heights, start, end)
}
fun part2(input: List<String>): Int {
val (_, end, heights) = buildHeightMap(input)
return heights.filterValues { it == 0 }.keys.map { shortestPath(heights, it, end) }.filter { it > 0 }.min()
}
// val testinput = readInput("Day12_test")
// println(part1(testinput))
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day12Kt.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class Day12Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day12\n 2: invokestatic #14 // Method UtilsK... |
kmakma__advent-of-kotlin-2022__950ffbc/src/Day08.kt | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
val visible = mutableSetOf<Coord2D>()
val grid = input.map { line -> line.map { it.digitToInt() } }
val lastX = grid.lastIndex
val lastY = grid.first().lastIndex
visible.addAll(grid.indices.map { Coord2D(it, 0) })
visible.addAll(grid.indices.map { Coord2D(it, lastX) })
visible.addAll(grid.first().indices.map { Coord2D(0, it) })
visible.addAll(grid.last().indices.map { Coord2D(lastY, it) })
var max: Int
for (x in 1 until lastX) {
max = -1
for (y in grid[x].indices) {
if (grid[x][y] > max) {
max = grid[x][y]
visible.add(Coord2D(x, y))
}
if (max == 9) break
}
max = -1
for (y in grid[x].indices.reversed()) {
if (grid[x][y] > max) {
max = grid[x][y]
visible.add(Coord2D(x, y))
}
if (max == 9) break
}
}
for (y in 1 until lastY) {
max = -1
for (x in grid.indices) {
if (grid[x][y] > max) {
max = grid[x][y]
visible.add(Coord2D(x, y))
}
if (max == 9) break
}
max = -1
for (x in grid.indices.reversed()) {
if (grid[x][y] > max) {
max = grid[x][y]
visible.add(Coord2D(x, y))
}
if (max == 9) break
}
}
return visible.size
}
fun lowerIdxScore(grid: List<List<Int>>, a: Int, b: Int): Int {
val height = grid[a][b]
for (i in a - 1 downTo 0) {
if (grid[i][b] >= height) return a - i
}
return a
}
fun scenicScore(grid: List<List<Int>>, x: Int, y: Int): Int {
val height = grid[x][y]
val scores = mutableListOf<Int>()
var score = 0
for (a in x - 1 downTo 0) {
if (grid[a][y] >= height) {
score = x - a
break
}
}
if (score > 0) scores.add(score)
else scores.add(x)
score = 0
for (a in x + 1..grid.lastIndex) {
if (grid[a][y] >= height) {
score = a - x
break
}
}
if (score > 0) scores.add(score)
else scores.add(grid.lastIndex - x)
score = 0
for (b in y - 1 downTo 0) {
if (grid[x][b] >= height) {
score = y - b
break
}
}
if (score > 0) scores.add(score)
else scores.add(y)
score = 0
for (b in y + 1..grid[x].lastIndex) {
if (grid[x][b] >= height) {
score = b - y
break
}
}
if (score > 0) scores.add(score)
else scores.add(grid[x].lastIndex - y)
return scores.product()
}
fun part2(input: List<String>): Int {
val grid = input.map { line -> line.map { it.digitToInt() } }
var maxScore = 0
grid.forEachIndexed { x, line ->
line.indices.forEach { y ->
val score = scenicScore(grid, x, y)
maxScore = max(maxScore, score)
}
}
return maxScore
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | [
{
"class_path": "kmakma__advent-of-kotlin-2022__950ffbc/Day08Kt.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day08\n 2: invokestatic #14 // Method UtilsK... |
AlBovo__Compiti__56a3131/src/main/kotlin/numberFraction.kt | class NumberFraction(var numerator: Int, denominatorValue: Int){
var denominator = denominatorValue
set(value){
require(value != 0){
"The denominator must be different from 0"
}
field = value
}
init{
require(denominatorValue != 0){
"The denominator must be different from 0"
}
}
fun product(number: NumberFraction): NumberFraction{
val numberSecond = reduce(number)
reduceCurrentFraction()
return reduce(NumberFraction(numerator * numberSecond.numerator, denominator * numberSecond.denominator))
}
fun sum(number: NumberFraction): NumberFraction{
val numberSecond = reduce(number)
reduceCurrentFraction()
return reduce(NumberFraction(numerator*numberSecond.denominator + numberSecond.numerator * denominator, denominator*numberSecond.denominator))
}
fun isEqual(number: NumberFraction): Boolean {
val numberSecond = reduce(number)
reduceCurrentFraction()
return numerator == numberSecond.numerator && denominator == numberSecond.denominator
}
fun isPositive() = (denominator * numerator >= 0)
fun calculateGCD(numberFirst: Int, numberSecond: Int): Int {
require(numberSecond != 0){
"The number must be positive"
}
var numberFirst1 = numberFirst
var numberSecond1 = numberSecond
var numberMaximum = if(numberFirst > numberSecond) numberFirst else numberSecond
var gcd = 1
for(i in 2..numberMaximum){
if(numberFirst1 == 1 && numberSecond1 == 1){
break
}
while(numberFirst1%i == 0 && numberSecond1%i == 0){
gcd *= i
numberFirst1 /= i
numberSecond1 /= i
}
}
return gcd
}
fun reduce(numberFraction: NumberFraction): NumberFraction{
val gcd = calculateGCD(numberFraction.numerator, numberFraction.denominator)
numberFraction.numerator /= gcd
numberFraction.denominator /= gcd
return numberFraction
}
fun reduceCurrentFraction(){
val gcd = calculateGCD(numerator, denominator)
numerator /= gcd
denominator /= gcd
}
} | [
{
"class_path": "AlBovo__Compiti__56a3131/NumberFraction.class",
"javap": "Compiled from \"numberFraction.kt\"\npublic final class NumberFraction {\n private int numerator;\n\n private int denominator;\n\n public NumberFraction(int, int);\n Code:\n 0: aload_0\n 1: invokespecial #9 ... |
AlBovo__Compiti__56a3131/src/main/kotlin/segtree.kt | import kotlin.math.*
class SegmentTree(array: Array<Int>){
private var segment = Array<Int>(0){ 0 }
private var size = 0
private var sizeOfInitialArray = 0
init{
size = 1 shl ceil(log2(array.size.toFloat())).toInt()
sizeOfInitialArray = array.size
segment = Array(size * 2){ 0 }
for(i in array.indices){
segment[i + size] = array[i]
}
for(i in size-1 downTo 1){
segment[i] = segment[i * 2]+segment[i * 2 + 1]
}
}
private fun privateGetSum(node: Int, nodeRangeLeft: Int, nodeRangeRight: Int, queryRangeLeft: Int, queryRangeRight: Int): Int{ // the query range is [queryRangeLeft, queryRangeRight)
if(queryRangeLeft >= nodeRangeRight || queryRangeRight <= nodeRangeLeft){
return 0
}
if(nodeRangeLeft >= queryRangeLeft && nodeRangeRight <= queryRangeRight){
return segment[node]
}
val left = privateGetSum(node * 2, nodeRangeLeft, (nodeRangeLeft + nodeRangeRight) / 2, queryRangeLeft, queryRangeRight)
val right = privateGetSum(node * 2 + 1, (nodeRangeLeft + nodeRangeRight) / 2, nodeRangeRight, queryRangeLeft ,queryRangeRight)
return left + right
}
private fun privateUpdate(nodePosition: Int, value: Int){
var node = nodePosition + size
segment[node] = value
node /= 2
while(node > 0){
segment[node] = segment[node * 2] + segment[node * 2 + 1]
node /= 2
}
}
private fun check(){
for(i in segment.indices){
print(segment[i].toString() + " ")
}
println("")
}
fun getSum(queryLeft: Int, queryRight: Int): Int{
require(queryLeft >= 0 && queryLeft < segment.size){
"Left end is not correct, it must be greater than -1 and less than the size of the segment size"
}
require(queryRight >= 0 && queryRight <= segment.size){
"Right end is not correct, it must be greater than -1 and less than the size of the segment size"
}
require(queryLeft <= queryRight){
"The right end must be greater or equal to the left end"
}
return privateGetSum(1, 1, size, queryLeft, queryRight)
}
fun update(nodePosition: Int, value: Int){
require(nodePosition in 0 until sizeOfInitialArray){
"The node isn't in the segment tree"
}
privateUpdate(nodePosition, value)
check()
}
}
fun main(){
val arr = arrayOf(2, 4, 2, 1, 3, 4, 5)
val seg = SegmentTree(arr)
print(seg.getSum(0, 4))
//seg.update(3, 4)
} | [
{
"class_path": "AlBovo__Compiti__56a3131/SegtreeKt.class",
"javap": "Compiled from \"segtree.kt\"\npublic final class SegtreeKt {\n public static final void main();\n Code:\n 0: bipush 7\n 2: anewarray #8 // class java/lang/Integer\n 5: astore_1\n 6: ... |
DmitrySwan__KotlinEducation__83dbf8b/src/Tasks.kt | fun main() {
println(
repeatedIntersection(intArrayOf(3, 6, 7, 8, 7, 9), mutableListOf(12, 6, 7, 6, 7, 565))
)
println(countLetters("AAGGDDDFBBBAAABB"))
println(groupWords(arrayOf("ate", "tdb", "eat", "ref", "fer", "test")))
}
fun repeatedIntersection(array1: IntArray, array2: MutableList<Int>): List<Int> {
return array1
.filter { e ->
array2.remove(e)
}
}
fun countLetters(input: String): String {
var i = 0
var count = 0
var result = ""
for (letter in input) {
count++
i++
if (i < input.length && letter == input[i]) {
continue
}
result += "${input[i - 1]}$count"
count = 0
}
return result
}
fun groupWords(words: Array<String>): List<List<String>> {
val map: MutableMap<String, MutableList<String>> = HashMap()
for (word in words) {
val sum: String = word.toCharArray().sorted().joinToString()
map.getOrPut(sum) { mutableListOf() }
.add(word)
}
return map.values.toList()
}
| [
{
"class_path": "DmitrySwan__KotlinEducation__83dbf8b/TasksKt.class",
"javap": "Compiled from \"Tasks.kt\"\npublic final class TasksKt {\n public static final void main();\n Code:\n 0: bipush 6\n 2: newarray int\n 4: astore_0\n 5: aload_0\n 6: iconst_0\n ... |
UlrichBerntien__Uebungen-Kotlin__0b4c608/KameleBeladen.kt | /**
* Programmieraufgabe:
*
* Kamele beladen
* https://www.programmieraufgaben.ch/aufgabe/kamele-beladen/6gddr4zm
*
* Ein Kamel soll optimal beladen werden. Das Kamel kann maximal 270 kg tragen.
* Aktuell sind Waren mit den folgenden Gewichten zu transportieren: 5, 18, 32,
* 34, 45, 57, 63, 69, 94, 98 und 121 kg. Nicht alle Gewichte müssen verwendet
* werden; die 270 kg sollen aber möglichst gut, wenn nicht sogar ganz ohne
* Rest beladen werden. Die Funktion
* beladeOptimal(kapazitaet: integer, vorrat: integer[]): integer[]
* erhält die maximal tragbare Last (kapazitaet) und eine Menge von
* aufzuteilenden Gewichten (vorrat). Das Resultat (hier integer[]) ist die
* Auswahl aus dem Vorrat, die der Belastbarkeit möglichst nahe kommt. Gehen
* Sie wie folgt rekursiv vor: Für jedes vorhandene Gewicht g aus dem Vorrat
* soll das Problem vereinfacht werden. Dazu wird dieses Gewicht probehalber
* aufgeladen:
* tmpLadung: integer[]
* tmpLadung := beladeOptimal(kapazitaet - g, "vorrat ohne g")
* Danach wird das beste Resultat tmpLadung + g gesucht und als Array
* zurückgegeben. Behandeln Sie in der Methode beladeOptimal() zunächst die
* Abbruchbedingungen:
* Vorrat leer
* alle vorhandenen Gewichte sind zu schwer
* nur noch ein Gewicht im Vorrat
*
* Autor:
* <NAME> 2018-06-24
*
* Sprache:
* Kotlin 1.2.51
*/
/**
* Bestimmt die optimale Beladung.
* @param capacity Die maximale Beladung.
* @param pool Die zur Beladung möglichen Elemente.
* @return Die optimale Beladung, ein Teilmenge von pool.
*/
fun optimalLoad(capacity: Int, pool: IntArray): IntArray {
var tmpOptimalLoad = 0
var tmpOptimalBag = IntArray(0)
for (index in pool.indices)
if (pool[index] <= capacity) {
val bag = optimalLoad(capacity - pool[index], pool.sliceArray(pool.indices - index))
val total = bag.sum() + pool[index]
if (total > tmpOptimalLoad) {
tmpOptimalLoad = total
tmpOptimalBag = bag + pool[index]
}
}
return tmpOptimalBag
}
/**
* Hauptprogramm.
* @param argv Aufrufparamter werden ignotiert.
*/
fun main(argv: Array<String>) {
val capacity = 270
val pool = intArrayOf(18, 32, 34, 45, 57, 63, 69, 94, 98, 121)
// Mit mehr Elementen dauert es wesentlioh länger:
//val capacity = 1000
//val pool = arrayOf(181, 130, 128, 125, 124, 121, 104, 101, 98, 94, 69, 61, 13)
val bag = optimalLoad(capacity, pool)
val load = bag.sum()
println("""
|Beladung: ${bag.contentToString()}
|Summe Beladung: $load
|Freie Kapazität: ${capacity - load}
""".trimMargin())
}
| [
{
"class_path": "UlrichBerntien__Uebungen-Kotlin__0b4c608/KameleBeladenKt.class",
"javap": "Compiled from \"KameleBeladen.kt\"\npublic final class KameleBeladenKt {\n public static final int[] optimalLoad(int, int[]);\n Code:\n 0: aload_1\n 1: ldc #9 // String pool... |
mececeli__Kotlin_Exercises__d05ee9d/src/main/kotlin/ValidParenthese.kt | import java.util.*
//Valid Parentheses
//Easy
//16.9K
//871
//Companies
//Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
//
//An input string is valid if:
//
//Open brackets must be closed by the same type of brackets.
//Open brackets must be closed in the correct order.
//Every close bracket has a corresponding open bracket of the same type.
//
//
//Example 1:
//
//Input: s = "()"
//Output: true
//Example 2:
//
//Input: s = "()[]{}"
//Output: true
//Example 3:
//
//Input: s = "(]"
//Output: false
//
//
//Constraints:
//
//1 <= s.length <= 104
//s consists of parentheses only '()[]{}'.
fun isValidParentheses(s: String): Boolean {
if (s.length % 2 == 1) return false
val openingBrackets: MutableList<Char> = mutableListOf()
val closingBrackets: MutableList<Char> = mutableListOf()
s.forEach { char ->
if (isOpeningBracket(char)) {
openingBrackets.add(char)
} else {
closingBrackets.add(char)
}
}
if (openingBrackets.size == closingBrackets.size) {
openingBrackets.forEachIndexed { index, char ->
if (isSameTypeBracket(openingChar = char, closingChar = closingBrackets[index]).not()) {
return false
}
return true
}
} else {
return false
}
return false
}
fun isOpeningBracket(char: Char): Boolean = when (char) {
'(', '[', '{' -> true
else -> false
}
fun isSameTypeBracket(openingChar: Char, closingChar: Char): Boolean {
if (openingChar == '(' && closingChar == ')') return true
if (openingChar == '[' && closingChar == ']') return true
if (openingChar == '{' && closingChar == '}') return true
return false
}
//----------------------------------------------------------------------------- Stack Solution
fun isValidParenthesesStack(s: String): Boolean {
if (s.length % 2 != 0) return false
val map = mapOf('}' to '{', ')' to '(', ']' to '[')
val stack = Stack<Char>()
s.forEach {
if (it == '}' || it == ')' || it == ']') {
if (stack.isEmpty() || stack.peek() != map[it]) return false
stack.pop()
} else stack.push(it)
}
return stack.isEmpty()
}
| [
{
"class_path": "mececeli__Kotlin_Exercises__d05ee9d/ValidParentheseKt.class",
"javap": "Compiled from \"ValidParenthese.kt\"\npublic final class ValidParentheseKt {\n public static final boolean isValidParentheses(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
mececeli__Kotlin_Exercises__d05ee9d/src/main/kotlin/TwoSum.kt | /**
* Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
* You can return the answer in any order.
*
* Example 1:
* Input: nums = [2,7,11,15], target = 9
* Output: [0,1]
* Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
* Example 2:
*
* Input: nums = [3,2,4], target = 6
* Output: [1,2]
* Example 3:
*
* Input: nums = [3,3], target = 6
* Output: [0,1]
*
* Main.kt run
* println(
* twoSumBest(
* nums = intArrayOf(7, 5, 10, 2),
* target = 12
* ).contentToString()
* )
*/
//My solution
fun twoSum(nums: IntArray, target: Int): IntArray {
var result : IntArray = intArrayOf()
nums.forEachIndexed { index, item ->
val numberWeLook = target - item
if(nums.contains(numberWeLook) && index != nums.indexOf(numberWeLook)) {
result = intArrayOf(index, nums.indexOf(numberWeLook))
return result
}
}
return result
}
//Alternative solution
fun twoSumBest(nums: IntArray, target: Int): IntArray {
val diffMap = mutableMapOf<Int, Int>()
nums.forEachIndexed { index, int ->
diffMap[int]?.let { return intArrayOf(it, index) }
diffMap[target - int] = index
}
return intArrayOf()
}
| [
{
"class_path": "mececeli__Kotlin_Exercises__d05ee9d/TwoSumKt.class",
"javap": "Compiled from \"TwoSum.kt\"\npublic final class TwoSumKt {\n public static final int[] twoSum(int[], int);\n Code:\n 0: aload_0\n 1: ldc #9 // String nums\n 3: invokestatic #15 ... |
duangsuse-valid-projects__Share__e89301b/Others/kt_misc/SortInclude.kt | typealias CategoryMap<K, V> = Set<Map<K, V>>
typealias IncludePath = String
/** Descending level */
typealias Level = /*Comparable*/ Int
class DescendAllocator(private var max: Int = Int.MAX_VALUE) {
fun less() = max--
}
val kmap: CategoryMap<IncludePath, Level> = DescendAllocator().run { setOf(
mapOf(
"QObject" to less(),
"QScopedPointer" to less(),
"QByteArray" to less()
),
mapOf(
"QIODevice" to less(),
"QTimer" to less(),
"QAudioOutput" to less()
),
mapOf(
"QMainWindow" to less(),
"QLabel" to less(),
"QComboBox" to less(),
"QPushButton" to less(),
"QSlider" to less()
)
)
}
fun <T, K> Iterable<T>.histogram(key: (T) -> K): Map<K, List<T>> {
val hist: MutableMap<K, MutableList<T>> = mutableMapOf()
for (item in this) { hist.getOrPut(key(item), ::mutableListOf).add(item) }
return hist
}
object SortInclude {
@JvmStatic
fun main(vararg arg: String) {
val code = readText()
val includes = parse(code)
println(includes)
println(dump(organize(includes)))
}
fun dump(includes: Set<List<IncludePath>>): String {
return includes.map { it.joinToString("\n") }.joinToString("\n\n")
}
private fun parse(includeCode: String): List<IncludePath>
= includeCode.lines().map { includeRegex.matchEntire(it)
?.groupValues?.get(1) ?: error(it) }
private val includeRegex = Regex("#include <(.*)>")
fun organize(includes: List<IncludePath>): Set<List<IncludePath>> {
val parted = includes.histogram { kmap.find { m -> it in m } ?: homeless }
val sorted = parted.map { val (m, inz) = it;
inz.sortedByDescending(m::getValue) }
return sorted.toSet()
}
private val homeless: Map<IncludePath, Level> = emptyMap()
}
fun readText(): String {
val text = StringBuilder()
while (true) {
val line = readLine()
if (line == ".") break
else text.append(line).append("\n")
}
text.delete(text.lastIndex, text.lastIndex.inc()) //"\n"
return text.toString()
}
| [
{
"class_path": "duangsuse-valid-projects__Share__e89301b/SortInclude.class",
"javap": "Compiled from \"SortInclude.kt\"\npublic final class SortInclude {\n public static final SortInclude INSTANCE;\n\n private static final kotlin.text.Regex includeRegex;\n\n private static final java.util.Map<java.lang.... |
US-ADDA__PI1_kotlin__b83e4fd/src/main/kotlin/Exercise3.kt | import java.util.stream.Stream
class Exercise3 {
companion object {
fun functional(start: Int, end: Int): List<Pair<Int, Int>> {
return Stream
.iterate(
Pair(0, start), // Cuando empieza.
{ it.first < end }, // Cuando termina.
{ Pair(it.first + 1, if (it.first % 3 == 1) it.second + 1 else it.second + it.first) }) // Siguiente
.toList().sortedBy { it.first }
}
fun iterativeWhile(start: Int, end: Int): List<Pair<Int, Int>> {
var current: Pair<Int, Int> = Pair(0, start)
val result: MutableList<Pair<Int, Int>> = mutableListOf()
while (current.first < end) {
result += Pair(current.first, current.second)
current = Pair(
current.first + 1,
if (current.first % 3 == 1) current.second + 1 else current.second + current.first
)
}
return result.sortedBy { it.first }
}
fun recursiveFinal(start: Int, end: Int): List<Pair<Int, Int>> {
return recursiveFinal(end, mutableListOf(), Pair(0, start)).sortedBy { it.first }
}
private fun recursiveFinal(end: Int, list: List<Pair<Int, Int>>, current: Pair<Int, Int>): List<Pair<Int, Int>> {
if (current.first < end) return recursiveFinal(
end,
list + current,
Pair(
current.first + 1,
if (current.first % 3 == 1) current.second + 1 else current.second + current.first
)
)
return list
}
fun recursiveNoFinal(start: Int, end: Int): List<Pair<Int, Int>> {
return recursiveNoFinal(end, Pair(0, start)).sortedBy { it.first }
}
private fun recursiveNoFinal(end: Int, current: Pair<Int, Int>): List<Pair<Int, Int>> {
if (current.first < end) return recursiveNoFinal(
end,
Pair(
current.first + 1,
if (current.first % 3 == 1) current.second + 1 else current.second + current.first
)
) + current
return listOf()
}
}
}
| [
{
"class_path": "US-ADDA__PI1_kotlin__b83e4fd/Exercise3$Companion$functional$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class Exercise3$Companion$functional$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public Exercise3$Companion$functional$$inlined$so... |
US-ADDA__PI1_kotlin__b83e4fd/src/main/kotlin/Exercise4.kt | import java.util.stream.Stream
import kotlin.math.absoluteValue
import kotlin.math.pow
class Exercise4 {
companion object {
fun functional(n: Double, e: Double): Double {
val pair = Stream.iterate(
Pair(0.0, n) // Definimos el comienzo como 0 (nos dicen que se calcula la raíz cúbica de un número positivo) y el valor del que queremos saber la raíz cúbica.
) {
val middle = it.first.plus(it.second).div(2) // Calculamos el valor medio.
// Analizamos donde puede estar aplicando búsqueda binaria (de inicio a medio y de medio a fin).
if (middle.pow(3) > n && it.first.pow(3) < n) Pair(it.first, middle)
else if (middle.pow(3) < n && it.second.pow(3) > n) Pair(middle, it.second)
else it
}.filter { it.first.plus(it.second).div(2).pow(3).minus(n).absoluteValue < e.pow(3) }.findFirst() // Indicamos que termine cuando el error al cubo sea mayor que la resta del medio al cubo con el valor del que qeremos saber su rai´z cúbica
.orElse(Pair(0.0, 0.0))
return pair.first.plus(pair.second).div(2)
}
fun iterativeWhile(n: Double, e: Double): Double {
var current = Pair(0.0, n)
var middle = n.div(2)
while (middle.pow(3).minus(n).absoluteValue > e.pow(3)) {
current = if (middle.pow(3) > n && current.first.pow(3) < n) Pair(current.first, middle)
else if (middle.pow(3) < n && current.second.pow(3) > n) Pair(middle, current.second)
else current
middle = current.first.plus(current.second).div(2)
}
return middle
}
fun recursiveFinal(n: Double, e: Double): Double {
return recursiveFinal(n, e, Pair(0.0, n), n.div(2))
}
private fun recursiveFinal(n: Double, e: Double, current: Pair<Double, Double>, middle: Double): Double {
return if (middle.pow(3).minus(n).absoluteValue <= e.pow(3)) middle
else {
val auxCurrent = if (middle.pow(3) > n && current.first.pow(3) < n) Pair(current.first, middle)
else if (middle.pow(3) < n && current.second.pow(3) > n) Pair(middle, current.second)
else current
val auxMiddle = auxCurrent.first.plus(auxCurrent.second).div(2)
recursiveFinal(n, e, auxCurrent, auxMiddle)
}
}
}
}
| [
{
"class_path": "US-ADDA__PI1_kotlin__b83e4fd/Exercise4$Companion.class",
"javap": "Compiled from \"Exercise4.kt\"\npublic final class Exercise4$Companion {\n private Exercise4$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\... |
arukuka__software-for-SamurAI-Coding-2018-19__04db0da/player/greedy.kt | import java.util.*
import java.io.*
import kotlin.math.*
const val SEARCHDEPTH = 7
const val SPEEDLIMIT = 1000
const val searchDepth = SEARCHDEPTH
const val speedLimitSquared = SPEEDLIMIT * SPEEDLIMIT
var nextSeq = 1
data class IntVec(val x : Int, val y : Int) {
operator fun plus(v : IntVec) : IntVec {
return IntVec(x + v.x, y + v.y)
}
operator fun compareTo(other : IntVec) : Int {
return if (y == other.y) other.x - x else y - other.y
}
}
data class RaceCourse(val thinkTime : Int, val stepLimit : Int, val width : Int, val length : Int, val vision : Int) {
constructor(input : java.util.Scanner) :this(input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt()) {}
}
fun addSquares(x : Int, y0 : Int, y1 : Int, squares : MutableList<IntVec>) {
for (y in (if (y1 > y0) y0..y1 else y0 downTo y1)) squares.add(IntVec(x, y))
}
data class Movement(val from : IntVec, val to : IntVec) {
fun touchedSquares() : MutableList<IntVec> {
val r : MutableList<IntVec> = mutableListOf()
if (to.x == from.x) addSquares(from.x, from.y, to.y, r)
else {
val a : Double = (to.y - from.y).toDouble() / (to.x - from.x).toDouble()
val sgnx = if (from.x < to.x) 1 else -1
var y1 = a * sgnx / 2.0 + from.y + 0.5
var iy1 = (if (to.y > from.y) floor(y1) else ceil(y1) - 1).toInt()
addSquares(from.x, from.y, iy1, r)
for (x in (if (sgnx > 0) (from.x + sgnx)..(to.x - 1) else (from.x + sgnx).downTo(to.x + 1))) {
val y0 = a * (x - from.x - sgnx / 2.0) + from.y + 0.5
y1 = a * (x - from.x + sgnx / 2.0) + from.y + 0.5
val iy0 = (if (to.y > from.y) ceil(y0) - 1 else floor(y0)).toInt()
iy1 = (if (to.y > from.y) floor(y1) else ceil(y1) - 1).toInt()
addSquares(x, iy0, iy1, r)
}
val y0 = a * (to.x - from.x - sgnx / 2.0) + from.y + 0.5
val iy0 = (if (to.y > from.y) ceil(y0) - 1 else floor(y0)).toInt()
addSquares(to.x, iy0, to.y, r)
}
return r
}
}
data class PlayerState(val position : IntVec, val velocity : IntVec) {
constructor (input : java.util.Scanner) : this(IntVec(input.nextInt(), input.nextInt()), IntVec(input.nextInt(), input.nextInt())) {}
operator fun compareTo(other : PlayerState) : Int {
val c1 = position.compareTo(other.position)
return if (c1 == 0) velocity.compareTo(other.velocity) else c1
}
}
data class RaceInfo(val stepNumber : Int, val timeLeft : Int, val me : PlayerState, val opponent : PlayerState, val squares : List<List<Int>>) {
constructor(input : java.util.Scanner, course : RaceCourse)
:this(input.nextInt(), input.nextInt(), PlayerState(input),
PlayerState(input),
Array(course.length, {Array(course.width, {input.nextInt()}).asList()}).asList()) {}
}
data class Candidate(val course : RaceCourse, val step : Int, val state : PlayerState, val from : Candidate?, val how : IntVec) : Comparable<Candidate> {
val seq = nextSeq
init {
nextSeq += 1
}
val goaled = state.position.y >= course.length
val goalTime = if (goaled) (step + course.length - state.position.y - 0.5) / state.velocity.y else 0.0
operator override fun compareTo(other : Candidate) : Int {
if (goaled) {
if (!other.goaled || other.goalTime > goalTime) return -1
else if (other.goalTime < goalTime) return 1
else return 0
} else if (state == other.state) return step - other.step
else return other.state.compareTo(state)
}
override fun toString() : String {
return "#${seq}: ${step}@(${state.position.x},${state.position.y})+(${state.velocity.x},${state.velocity.y}) <- #${from?.seq ?: 0}"
}
}
fun plan(info : RaceInfo, course : RaceCourse) : IntVec {
val candidates = PriorityQueue<Candidate>()
val initial = PlayerState(info.me.position, info.me.velocity)
val initialCand = Candidate(course, 0, initial, null, IntVec(0, 0))
val reached = mutableMapOf(initial to initialCand)
var best = initialCand
candidates.add(initialCand)
while (!candidates.isEmpty()) {
val c = candidates.poll()
for (cay in 1 downTo -1) {
for (cax in -1..1) {
val accel = IntVec(cax, cay)
var velo = c.state.velocity + accel
if (velo.x * velo.x + velo.y * velo.y <= speedLimitSquared) {
val pos = c.state.position + velo
if (0 <= pos.x && pos.x < course.width) {
val move = Movement(c.state.position, pos)
val touched = move.touchedSquares()
if (pos != info.opponent.position &&
touched.all { s ->
0 > s.y || s.y >= course.length ||
info.squares[s.y][s.x] != 1}) {
if (0 <= pos.y && pos.y < course.length &&
info.squares[pos.y][pos.x] == 2) {
velo = IntVec(0, 0)
}
val nextState = PlayerState(pos, velo)
val nextCand = Candidate(course, c.step + 1, nextState, c, accel)
if (!nextCand.goaled &&
c.step < searchDepth &&
(!reached.containsKey(nextState) ||
reached[nextState]!!.step > c.step + 1)) {
candidates.add(nextCand)
reached[nextState] = nextCand
if (nextCand < best) best = nextCand
}
}
}
}
}
}
}
if (best == initialCand) {
var ax = 0
var ay = 0
if (info.me.velocity.x < 0) ax += 1
else if (info.me.velocity.x > 0) ax -= 1
if (info.me.velocity.y < 0) ay += 1
else if (info.me.velocity.y > 0) ay -= 1
return IntVec(ax, ay)
}
var c : Candidate = best
while (c.from != initialCand) {
c = c.from!!
}
return c.how
}
fun main(args : Array<String>) {
val input = java.util.Scanner(System.`in`)
val course = RaceCourse(input)
println(0)
System.out.flush()
try {
while (true) {
val info = RaceInfo(input, course)
val accel = plan(info, course)
println("${accel.x} ${accel.y}")
System.out.flush()
}
} catch (e : Exception) {
}
}
| [
{
"class_path": "arukuka__software-for-SamurAI-Coding-2018-19__04db0da/GreedyKt.class",
"javap": "Compiled from \"greedy.kt\"\npublic final class GreedyKt {\n public static final int SEARCHDEPTH;\n\n public static final int SPEEDLIMIT;\n\n public static final int searchDepth;\n\n public static final int... |
darian-catalin-cucer__divide-and-conquer-algorithms__1cea70d/kt.kt | fun quickSort(arr: IntArray, low: Int, high: Int) {
if (low < high) {
val pivotIndex = partition(arr, low, high)
quickSort(arr, low, pivotIndex - 1)
quickSort(arr, pivotIndex + 1, high)
}
}
fun partition(arr: IntArray, low: Int, high: Int): Int {
val pivot = arr[high]
var i = low - 1
for (j in low until high) {
if (arr[j] <= pivot) {
i++
val temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
val temp = arr[i + 1]
arr[i + 1] = arr[high]
arr[high] = temp
return i + 1
}
//The code above implements the QuickSort algorithm, a classic divide-and-conquer algorithm for sorting an array. The quickSort function takes in an array arr, a low index low, and a high index high, and sorts the subarray arr[low..high] in place. The partition function is used to divide the subarray into two parts: elements smaller than the pivot and elements greater than the pivot. The pivot is chosen as the last element of the subarray. The partition function rearranges the elements so that all elements smaller than the pivot are before it, and all elements greater than the pivot are after it. The pivot index is then returned, which becomes the boundary between the two subarrays in the subsequent recursive calls to quickSort. The QuickSort algorithm sorts the array by repeatedly dividing it into smaller subarrays and sorting those subarrays until they are small enough to be sorted directly.
| [
{
"class_path": "darian-catalin-cucer__divide-and-conquer-algorithms__1cea70d/KtKt.class",
"javap": "Compiled from \"kt.kt\"\npublic final class KtKt {\n public static final void quickSort(int[], int, int);\n Code:\n 0: aload_0\n 1: ldc #9 // String arr\n 3: ... |
sirech__exercism-kotlin__253f463/sublist/src/main/kotlin/Relationship.kt | enum class Relationship {
EQUAL, SUBLIST, SUPERLIST, UNEQUAL
}
private enum class Case {
EMPTY_CASE,
FIRST_BIGGER_OR_EQUAL,
FIRST_SMALLER
}
fun <T> List<T>.relationshipTo(other: List<T>): Relationship {
return when (case(this, other)) {
Case.EMPTY_CASE -> emptyCase(this, other)
Case.FIRST_BIGGER_OR_EQUAL -> generalCase(this, other, Relationship.SUPERLIST)
Case.FIRST_SMALLER -> generalCase(other, this, Relationship.SUBLIST)
}
}
private fun <T> case(first: List<T>, second: List<T>): Case {
if (first.isEmpty() || second.isEmpty()) return Case.EMPTY_CASE
if (first.size >= second.size) return Case.FIRST_BIGGER_OR_EQUAL
return Case.FIRST_SMALLER
}
private fun <T> emptyCase(first: List<T>, second: List<T>): Relationship {
if (first.isEmpty() && second.isEmpty()) return Relationship.EQUAL
if (first.isEmpty()) return Relationship.SUBLIST
return Relationship.SUPERLIST
}
private fun <T> generalCase(first: List<T>, second: List<T>, case: Relationship): Relationship {
for (i in 0..(first.size - second.size)) {
for (j in 0 until second.size) {
if (first[i+j] != second[j]) {
break;
}
if (j + 1 == second.size) {
if (first.size == second.size) return Relationship.EQUAL
return case;
}
}
}
return Relationship.UNEQUAL
}
| [
{
"class_path": "sirech__exercism-kotlin__253f463/RelationshipKt.class",
"javap": "Compiled from \"Relationship.kt\"\npublic final class RelationshipKt {\n public static final <T> Relationship relationshipTo(java.util.List<? extends T>, java.util.List<? extends T>);\n Code:\n 0: aload_0\n 1:... |
fasiha__advent-of-code-2020__59edfcb/aoc2020kot/src/main/kotlin/main.kt | import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
// From https://stackoverflow.com/a/53018129
fun getResourceAsText(path: String): String {
return object {}.javaClass.getResource(path)?.readText() ?: throw Exception("Unable to read file")
}
fun getResourceAsBytes(path: String): ByteArray {
return object {}.javaClass.getResource(path)?.readBytes() ?: throw Exception("Unable to read file")
}
fun getResourceAsInts(path: String): Sequence<Int> {
return getResourceAsText(path).trim().lineSequence().map { it.toInt() }
}
fun getResourceAsLongs(path: String): Sequence<Long> {
return getResourceAsText(path).trim().lineSequence().map { it.toLong() }
}
fun problem1a(expenses: Sequence<Long> = getResourceAsLongs("1.txt"), targetSum: Long = 2020): Pair<Long, List<Long>>? {
val seen: MutableSet<Long> = mutableSetOf()
for (x in expenses) {
if (seen.contains(targetSum - x)) {
return Pair((targetSum - x) * x, listOf(targetSum - x, x))
}
seen += x
}
return null
}
fun problem1b(): Pair<Int, List<Int>>? {
val targetSum = 2020
val expenses = getResourceAsInts("1.txt")
val seen: MutableSet<Int> = mutableSetOf()
for (x in expenses) {
for (y in seen) {
if (seen.contains(targetSum - (x + y))) {
return Pair(x * y * (targetSum - (x + y)), listOf(x, y, targetSum - (x + y)))
}
}
seen += x
}
return null
}
fun problem2a(a: Boolean): Int {
val re = "([0-9]+)-([0-9]+) (.): (.+)".toRegex()
fun isValid(lo: Int, hi: Int, ch: String, pw: String): Boolean {
val count = ch.toRegex().findAll(pw).count()
return count in lo..hi
}
fun isValidB(i: Int, j: Int, ch: String, pw: String): Boolean {
return (pw[i - 1] == ch[0]).xor(pw[j - 1] == ch[0])
}
val valid = if (a) ::isValid else ::isValidB
val contents = getResourceAsText("2.txt")
return contents.trim().lineSequence().mapNotNull { re.find(it)?.destructured }
.filter { (lo, hi, ch, pw) -> valid(lo.toInt(), hi.toInt(), ch, pw) }.count()
}
fun problem3a(right: Int, down: Int): Int {
val map = getResourceAsText("3.txt").trim().lines()
val width = map[0].length
val tree = '#'
var nTrees = 0
var row = 0
var col = 0
while (row < map.size) {
nTrees += if (map[row][col % width] == tree) 1 else 0
row += down
col += right
}
return nTrees
}
fun problem3b(): Long {
return listOf(
problem3a(1, 1),
problem3a(3, 1),
problem3a(5, 1),
problem3a(7, 1),
problem3a(1, 2)
).fold(1L) { acc, i -> acc * i }
}
fun problem4a(): Int {
val contents = getResourceAsText("4.txt").trim().splitToSequence("\n\n")
val listOfKeys = contents.map {
it
.split("\\s".toRegex())
.map { kv -> kv.splitToSequence(':').first() }
.toSet()
}
return listOfKeys.count { it.containsAll(listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")) }
}
fun <T> listToPair(l: List<T>): Pair<T, T> {
return Pair(l[0], l[1])
}
fun problem4b(): Int {
val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
val okEyeColors = setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
val contents = getResourceAsText("4.txt").trim().splitToSequence("\n\n")
val passports = contents.map {
it
.split("\\s".toRegex())
.associate { kv -> listToPair(kv.split(":")) }
}
val validPassports = passports.filter { requiredFields.all { k -> it.containsKey(k) } }
fun isValid(m: Map<String, String>): Boolean {
val hgt = m["hgt"]!!
val hgtOk = (hgt.endsWith("cm") && hgt.dropLast(2).toInt() in 150..193) ||
(hgt.endsWith("in") && hgt.dropLast(2).toInt() in 59..76)
return hgtOk &&
(m["byr"]?.toInt() in 1920..2002) &&
(m["iyr"]?.toInt() in 2010..2020) &&
(m["eyr"]?.toInt() in 2020..2030) &&
(m["hcl"]!!.contains("^#[a-f0-9]{6}$".toRegex())) &&
(okEyeColors.contains(m["ecl"]!!)) &&
(m["pid"]!!.contains("^[0-9]{9}$".toRegex()))
}
return validPassports.count(::isValid)
}
fun strToBinary(s: String, zeroChar: Char): Int {
return s.toCharArray().fold(0) { acc, i -> (acc shl 1) + if (i == zeroChar) 0 else 1 }
// Does toCharArray *create* a new array? Or is it a view?
// Because, an alternative: `chars` returns IntSequence, so
// return s.chars().map{if (it == zeroChar.toInt()) 0 else 1}.reduce{ acc, i -> (acc shl 1) + i }.asInt
}
fun problem5a(): Int {
val lines = getResourceAsText("5.txt").trim().lineSequence()
return lines.maxOfOrNull { strToBinary(it.take(7), 'F') * 8 + strToBinary(it.takeLast(3), 'L') }!!
}
fun problem5b(): Int {
val lines = getResourceAsText("5.txt").trim().lineSequence()
val sorted = lines.map { strToBinary(it.take(7), 'F') * 8 + strToBinary(it.takeLast(3), 'L') }.sorted()
for ((curr, next) in sorted.zipWithNext()) {
if (curr + 1 != next) return curr + 1
}
return -1
}
fun problem6a(): Int {
val groups = getResourceAsText("6.txt").trim().splitToSequence("\n\n")
return groups.sumOf { it.replace("\n", "").toSet().size }
}
fun problem6b(): Int {
val groups = getResourceAsText("6.txt").trim().splitToSequence("\n\n")
return groups.sumOf {
it.splitToSequence("\n")
.map { person -> person.toSet() }
.reduce { acc, i -> acc intersect i }
.size
}
}
fun problem7a(): Int {
fun outerToInner(rule: String): Sequence<Pair<String, String>> {
val split = rule.split(" bags contain")
val parent = split[0] // don't need null check?
return "[0-9]+ ([a-z ]+?) bag".toRegex().findAll(split[1]).map { Pair(parent, it.destructured.component1()) }
}
val innerToOuters =
getResourceAsText("7.txt").trim().lineSequence().flatMap(::outerToInner).groupBy({ it.second }, { it.first })
val ancestors: MutableSet<String> = mutableSetOf()
fun recur(inner: String) {
val outers = innerToOuters[inner].orEmpty()
ancestors += outers
outers.forEach(::recur)
}
recur("shiny gold")
return ancestors.size
}
data class BagContent(val num: Int, val color: String)
fun problem7b(): Int {
fun outerToInners(rule: String): Pair<String, List<BagContent>> {
val split = rule.split(" bags contain")
assert(split.size >= 2) { "two sides to the rule expected" }
val parent = split[0] // don't need null check? Guess not. Either this will throw or the assert above
return Pair(
parent,
"([0-9]+) ([a-z ]+?) bag"
.toRegex()
.findAll(split[1])
.map { BagContent(it.destructured.component1().toInt(), it.destructured.component2()) }
.toList()
)
}
val outerToInners =
getResourceAsText("7.txt").trim().lineSequence().associate(::outerToInners)
fun recur(outer: String): Int {
val inners = outerToInners[outer].orEmpty()
return inners.sumOf { it.num + it.num * recur(it.color) }
}
return recur("shiny gold")
}
enum class Op { Acc, Jmp, Nop }
data class OpCode(val op: Op, val arg: Int)
fun loadProgram8(): List<OpCode> {
return getResourceAsText("8.txt").trim().lines().map {
val (op, arg) = it.split(" ")
OpCode(
when (op) {
"nop" -> Op.Nop
"acc" -> Op.Acc
"jmp" -> Op.Jmp
else -> throw Error("unknown")
},
arg.toInt()
)
}
}
enum class FinalState { Terminated, InfiniteLoop }
fun problem8a(program: List<OpCode> = loadProgram8()): Pair<FinalState, Int> {
val linesVisited = mutableSetOf<Int>()
var programCounter = 0
var acc = 0
while (programCounter < program.size) {
if (linesVisited.contains(programCounter)) return Pair(FinalState.InfiniteLoop, acc)
else linesVisited.add(programCounter)
val (op, arg) = program[programCounter]
when (op) {
Op.Acc -> {
acc += arg
programCounter++
}
Op.Jmp -> programCounter += arg
Op.Nop -> programCounter++
}
}
return Pair(FinalState.Terminated, acc)
}
fun problem8b(): Int {
val program = loadProgram8()
for ((idx, op) in program.withIndex()) {
if (op.op == Op.Nop || op.op == Op.Jmp) {
val newProgram = program.toMutableList()
newProgram[idx] = OpCode(if (op.op == Op.Nop) Op.Jmp else Op.Nop, op.arg)
val (newState, newAcc) = problem8a(newProgram)
if (newState == FinalState.Terminated) return newAcc
}
}
throw Error("no solution found")
}
// Kotlin Sad 1: no nested destructure
// 2: windowed returns a List of Lists? No Sequence? Is that inefficient?
// Question: is List.asSequence() expensive?
// Definitely annoying: `if(x != null) return x.max()` doesn't work: Kotlin doesn't know x is non-null there. Similarly `if(m.containsKey(idx)) return m[idx]!!`
// ^^ But --- wait https://kotlinlang.org/docs/basic-syntax.html#nullable-values-and-null-checks `x and y are automatically cast to non-nullable after null check`
// subList does bound-checking. I miss python lst[5:1000000] would just work
// Why does "asd".toCharArray().mapNotNull not exist?
fun problem9a(numbers: Sequence<Long> = getResourceAsLongs("9.txt")): Long {
val preamble = 25
return numbers
.windowed(1 + preamble)
.first { problem1a(it.dropLast(1).asSequence(), it.last()) == null }
.last()
}
fun problem9b(): Long {
val numbers = getResourceAsLongs("9.txt").toList()
val target = problem9a(numbers.asSequence()) // is this stupid, going from seq -> list -> seq?
for (win in 2..numbers.size) {
val solution = numbers.windowed(win).firstOrNull { it.sum() == target }
if (solution != null) return solution.maxOrNull()!! + solution.minOrNull()!!
}
error("unable to find solution")
}
fun problem10a(): Int {
return getResourceAsInts("10.txt")
.sorted()
.zipWithNext { a, b -> b - a }
.groupingBy { it }
.eachCount()
.values
.fold(1) { acc, it -> acc * (it + 1) }
}
fun problem10b(): Long {
val list0 = listOf(0) + getResourceAsInts("10.txt").sorted()
val list = list0 + (list0.last() + 3)
val m = mutableMapOf<Int, Long>()
fun recur(idx: Int = 0): Long {
if (idx + 1 == list.size) return 1
if (m.containsKey(idx)) return m[idx]!!
val cur = list[idx]
val next = list.drop(idx + 1).takeWhile { it <= cur + 3 }.size // drop & takeWhile since subList checks bounds
val numDescendants = (idx + 1..idx + next).sumOf(::recur)
m += idx to numDescendants
return numDescendants
}
return recur()
}
data class DoubleBuffer(
val get: (Int, Int) -> Byte,
val set: (Int, Int, Byte) -> Unit,
val flip: () -> Unit,
val getBuffer: () -> ByteArray,
val getLineOfSight: (Int, Int, (Byte) -> Boolean) -> List<Byte>,
val height: Int,
val width: Int,
)
fun prepareBytes(aBuffer: ByteArray): DoubleBuffer {
// FIXME: BOM 0xEF,0xBB,0xBF https://en.wikipedia.org/wiki/Byte_order_mark
val newline = aBuffer.indexOf('\n'.toByte())
assert(newline > 0) { "file must contain newlines" }
val (width, padding) = when (aBuffer[newline - 1]) {
'\r'.toByte() -> Pair(newline - 1, 2)
else -> Pair(newline, 1)
}
val lastIdx = aBuffer.indexOfLast { !(it == '\n'.toByte() || it == '\r'.toByte()) } + 1
val height = (lastIdx + padding) / (width + padding)
val bBuffer = aBuffer.copyOf()
var readBufferA = true // which buffer, a or b, is the read-ready copy? The other will be written to until flip()ed
val rowColToIndex = { row: Int, col: Int -> row * (width + padding) + col }
val get = { row: Int, col: Int -> (if (readBufferA) aBuffer else bBuffer)[rowColToIndex(row, col)] }
val set = { row: Int, col: Int, new: Byte ->
(if (readBufferA) bBuffer else aBuffer)[rowColToIndex(row, col)] = new
}
val flip = { readBufferA = !readBufferA }
val getBuffer = { if (readBufferA) aBuffer else bBuffer }
val getLineOfSight = { row: Int, col: Int, f: (Byte) -> Boolean ->
val inBounds = { r: Int, c: Int -> r >= 0 && c >= 0 && r < height && c < width }
val buf = if (readBufferA) aBuffer else bBuffer
val ret = mutableListOf<Byte>()
for (dr in -1..1) {
for (dc in -1..1) {
if (dc == 0 && dr == 0) continue
var r = row + dr
var c = col + dc
while (inBounds(r, c)) {
val char = buf[rowColToIndex(r, c)]
if (f(char)) {
ret += char
break
}
c += dc
r += dr
}
}
}
ret
}
return DoubleBuffer(get, set, flip, getBuffer, getLineOfSight, height, width)
}
fun problem11(partA: Boolean): Int {
val buffer = prepareBytes(getResourceAsBytes("11.txt"))
val occupiedThreshold = if (partA) 4 else 5
val predicate = if (partA) ({ true }) else ({ b: Byte -> b != '.'.toByte() })
while (true) {
var changed = false
for (row in 0 until buffer.height) {
for (col in 0 until buffer.width) {
val seat = buffer.get(row, col)
if (seat != '.'.toByte()) {
val ring = buffer.getLineOfSight(row, col, predicate)
val occupied = ring.count { it == '#'.toByte() }
if (seat == 'L'.toByte() && occupied == 0) {
buffer.set(row, col, '#'.toByte())
changed = true
} else if (seat == '#'.toByte() && occupied >= occupiedThreshold) {
buffer.set(row, col, 'L'.toByte())
changed = true
} else {
buffer.set(row, col, seat)
}
}
}
}
buffer.flip() // all done reading from one buffer and writing to the other: flip which one is readable
if (!changed) break
}
return buffer.getBuffer().count { it == '#'.toByte() }
}
fun bytesToLinesSequence(bytes: ByteArray): Sequence<ByteArray> {
return sequence {
val lineFeed = '\n'.toByte()
val carriageReturn = '\r'.toByte()
var newlineSize = 1 // unix
var slice = bytes.sliceArray(bytes.indices)
val searchIdx = slice.indexOf(lineFeed)
if (searchIdx < 0) {
yield(slice)
} else {
if (searchIdx > 0 && slice[searchIdx - 1] == carriageReturn) newlineSize = 2 // Windows
yield(slice.sliceArray(0..searchIdx - newlineSize))
slice = slice.sliceArray(searchIdx + 1 until slice.size)
while (slice.isNotEmpty()) {
val searchIdx = slice.indexOf(lineFeed)
if (searchIdx < 0) {
yield(slice)
break
}
yield(slice.sliceArray(0..searchIdx - newlineSize))
slice = slice.sliceArray(searchIdx + 1 until slice.size)
}
}
}
}
fun prob12(): Int {
val faceToDelta = mapOf('N' to Pair(0, 1), 'S' to Pair(0, -1), 'E' to Pair(1, 0), 'W' to Pair(-1, 0))
val faces = listOf('N', 'E', 'S', 'W')
var x = 0
var y = 0
var faceIdx = faces.indexOf('E')
for (line in bytesToLinesSequence(getResourceAsBytes("12.txt"))) {
val instruction = line[0].toChar()
val arg = String(line.sliceArray(1 until line.size), Charsets.US_ASCII).toInt()
when (instruction) {
'N' -> y += arg
'S' -> y -= arg
'W' -> x -= arg
'E' -> x += arg
'L' -> faceIdx = (4 + faceIdx - arg / 90) % 4
'R' -> faceIdx = (4 + faceIdx + arg / 90) % 4
'F' -> {
val (dx, dy) = faceToDelta[faces[faceIdx]]!!
x += dx * arg
y += dy * arg
}
}
}
return kotlin.math.abs(x) + kotlin.math.abs(y)
}
// See https://mathworld.wolfram.com/RotationMatrix.html
fun rotate(x: Int, y: Int, deg: Int): Pair<Int, Int> {
val t = PI / 180.0 * deg;
val cosT = cos(t)
val sinT = sin(t)
return Pair((cosT * x - sinT * y).roundToInt(), (sinT * x + cosT * y).roundToInt())
}
fun prob12b(): Int {
var x = 0
var y = 0
var dx = 10 // waypoint
var dy = 1 // waypoint
for (line in bytesToLinesSequence(getResourceAsBytes("12.txt"))) {
val instruction = line[0].toChar()
val arg = String(line.sliceArray(1 until line.size), Charsets.US_ASCII).toInt()
when (instruction) {
'N' -> dy += arg
'S' -> dy -= arg
'W' -> dx -= arg
'E' -> dx += arg
'L', 'R' -> {
val (x1, y1) = rotate(dx, dy, if (instruction == 'L') arg else -arg) // L: clockwise
dx = x1
dy = y1
}
'F' -> {
x += dx * arg
y += dy * arg
}
}
}
return kotlin.math.abs(x) + kotlin.math.abs(y)
}
fun prob13(): Int {
val lines = getResourceAsText("13.txt").lines()
val earliest = lines[0].toInt()
val busses = lines[1].split(',').filter { it != "x" }.map { it.toInt() }
// Can we write the following loop using sequences?
// `generateSequence(earliest) {it+1 }.first{ time -> busses.any { bus -> (time % bus) == 0 }}!!` but without
// having to redo the last mod checks?
var t = earliest
while (true) {
val bus = busses.find { t % it == 0 }
if (bus != null) {
return bus * (t - earliest)
}
t++
}
}
// Find x such that `x % a.component2() == a.component1()` AND `x % b.component2() == b.component1()`
// That is, the first element of each pair is congruent to x modulo the second element of the pair
// Step one of the sieve algorithm per https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Computation,i
fun chineseRemainderTheoremPair(a: Pair<Long, Long>, b: Pair<Long, Long>): Long {
var congruence: Long = a.component1()
val mod = a.component2()
val secondCongruence = b.component1()
val secondMod = b.component2()
assert(congruence > 0 && mod > 0 && secondCongruence > 0 && secondMod > 0) { "positive only" }
while (true) {
if ((congruence % secondMod) == secondCongruence) return congruence
congruence += mod
}
}
fun prob13b(): Long {
val list = getResourceAsText("13.txt").lines()[1].split(',')
val equivalences = list
.mapIndexedNotNull { i, stringModulo ->
when (stringModulo) {
"x" -> null
else -> {
val mod = stringModulo.toLong()
val push = (list.size / mod + 1) * mod
// push the modulo to be greater than the biggest index i
// without this, we might end up with `mod - i % mod` being negative when index is big enough
Pair((push - i.toLong()) % mod, mod)
}
}
}
.sortedByDescending { (_, n) -> n }
// x = equivalences[0][0] % equivalences[0][1] = equivalences[1][0] % equivalences[1][1] = ...
// In other words, the first element is congruent with x modulo the second element.
// In the language of https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Computation,
// equivalences[i] = Pair(a_i, n_i)
val sol = equivalences.reduce { acc, pair ->
val newCongruent = chineseRemainderTheoremPair(acc, pair)
Pair(newCongruent, acc.component2() * pair.component2())
}
return sol.component1()
}
fun prob14(): Long {
// Pair(OrMask (1s), AndMask (0s))
// OrMask's binary representation has 1s wherever the bitmask has a '1' character and 0s otherwise
// AndMask in binary has 0s wherever the bitmask is '0' but 1s otherwise
// This way, `foo OR OrMask AND AndMask` will apply the overall mask.
fun stringToMasks(s: String): Pair<Long, Long> {
return s.toCharArray().foldIndexed(Pair(0L, 0L)) { idx, (orMask, andMask), x ->
val bit = 1L shl (s.length - idx - 1)
Pair(orMask + if (x == '1') bit else 0, andMask + if (x == '0') 0 else bit)
}
}
val mem = mutableMapOf<Int, Long>()
var mask = Pair(0L, 0L)
for (line in getResourceAsText("14.txt").trim().lineSequence()) {
if (line.startsWith("ma")) {
mask = stringToMasks(line.drop(7))
} else {
val group = "mem\\[(?<idx>[0-9]+)\\] = (?<value>.*)".toRegex().find(line)!!.groupValues
val idx = group[1].toInt()
val value = group[2].toLong()
mem[idx] = (value or mask.component1()) and mask.component2()
}
}
return mem.values.sum()
}
/**
* Given a list of numbers representing how many options each dimension has,
* generates a sequence whose each step is a list of numbers representing
* the chosen index for each dimension.
*
* If you're choosing between 4 shirts, 5 pants, and 3 pairs of shoes,
* `cartesianProduct(listOf(4, 5, 3))` will start at `(0, 0, 0)` and end at
* `(3, 4, 2)` and will enumerate each option.
*
* from https://github.com/fasiha/cartesian-product-generator/issues/3
*/
fun cartesianProduct(lengthArr: List<Int>): Sequence<List<Int>> {
val idx = lengthArr.map { 0 }.toMutableList()
var carry = 0
return sequence<List<Int>> {
while (carry == 0) {
yield(idx)
carry = 1
for (i in idx.indices) {
idx[i] += carry
if (idx[i] >= lengthArr[i]) {
idx[i] = 0
carry = 1
} else {
carry = 0
break
}
}
}
}
}
fun prob14b(): Long {
// We now have three things to generate from each mask string:
// - an OrMask whose binary has 1s where the input char is 1
// - an AndMask whose binary has 0s when the input char is X, since we want to zero out the floats
// - a floats list consisting of 2**index for each index whose character was X
fun stringToMasks(s: String): Triple<Long, Long, List<Long>> {
return s.toCharArray().foldIndexed(Triple(0L, 0L, listOf())) { idx, (orMask, andMask, floats), x ->
val bit = 1L shl (s.length - idx - 1)
Triple(
orMask + if (x == '1') bit else 0,
andMask + if (x == 'X') 0 else bit,
if (x == 'X') floats + bit else floats
)
}
}
val mem = mutableMapOf<Long, Long>()
var mask = Triple(0L, 0L, listOf<Long>())
for (line in getResourceAsText("14.txt").trim().lineSequence()) {
if (line.startsWith("ma")) {
mask = stringToMasks(line.drop(7))
} else {
val (orMask, andMask, floatMask) = mask
val group = "mem\\[(?<idx>[0-9]+)\\] = (?<value>.*)".toRegex().find(line)!!.groupValues
val value = group[2].toLong()
val idx = group[1].toLong()
val newIdx = (idx or orMask) and andMask
for (float in cartesianProduct(floatMask.map { 2 })) {
// each element of float will be 0 or 1, whether to turn the floating bit on or off
val floatIdx = newIdx + float.zip(floatMask).sumOf { (use, bit) -> use * bit }
// we're using multiplication as a shortcut to `if(use>0) bit else 0`
mem[floatIdx] = value
}
}
}
return mem.values.sum()
}
fun prob15(partA: Boolean): Int {
val input = listOf(0, 5, 4, 1, 10, 14, 7)
val spoken = input.withIndex().associate { it.value to listOf(it.index + 1) }.toMutableMap()
var lastSpoken = input.last()
for (turn in input.size + 1..(if (partA) 2020 else 30_000_000)) {
val prev = spoken[lastSpoken]!!
lastSpoken = if (prev.size == 1) {
0
} else {
// prev is list of 2
prev[1] - prev[0]
}
if (!spoken.containsKey(lastSpoken)) {
spoken[lastSpoken] = listOf(turn)
} else {
val newPrevious = spoken[lastSpoken]!!
spoken[lastSpoken] = listOf(newPrevious.last(), turn)
}
}
return lastSpoken
}
fun main(args: Array<String>) {
println("Problem 1a: ${problem1a()}")
println("Problem 1b: ${problem1b()}")
println("Problem 2a: ${problem2a(true)}")
println("Problem 2b: ${problem2a(!true)}")
println("Problem 3a: ${problem3a(3, 1)}")
println("Problem 3b: ${problem3b()}")
println("Problem 4a: ${problem4a()}")
println("Problem 4b: ${problem4b()}")
println("Problem 5a: ${problem5a()}")
println("Problem 5b: ${problem5b()}")
println("Problem 6a: ${problem6a()}")
println("Problem 6b: ${problem6b()}")
println("Problem 7a: ${problem7a()}")
println("Problem 7b: ${problem7b()}")
println("Problem 8a: ${problem8a()}")
println("Problem 8b: ${problem8b()}")
println("Problem 9a: ${problem9a()}")
println("Problem 9b: ${problem9b()}")
println("Problem 10a: ${problem10a()}")
println("Problem 10b: ${problem10b()}")
// println("Problem 11a: ${problem11(true)}")
// println("Problem 11b: ${problem11(false)}")
println("Problem 12: ${prob12()}")
println("Problem 12b: ${prob12b()}")
println("Problem 13: ${prob13()}")
println("Problem 13b: ${prob13b()}")
println("Problem 14: ${prob14()}")
println("Problem 14b: ${prob14b()}")
println("Problem 15: ${prob15(true)}")
// println("Problem 15b: ${prob15(false)}")
} | [
{
"class_path": "fasiha__advent-of-code-2020__59edfcb/MainKt$problem10a$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Sequences.kt\"\npublic final class MainKt$problem10a$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lang.Integer, java.lang.Integer> {\n final kotlin.sequences... |
nishtahir__scratchpad__51115e3/src/main/kotlin/Extensions.kt | import java.util.*
import java.util.concurrent.locks.Lock
fun isValidTriangle(values: List<Int>): Boolean =
values[0] + values[1] > values[2] &&
values[0] + values[2] > values[1] &&
values[1] + values[2] > values[0]
inline fun <reified T> List<T>.grouped(by: Int): List<List<T>> {
require(by > 0) { "Groupings can't be less than 1" }
return if (isEmpty()) {
emptyList()
} else {
(0..lastIndex / by).map {
val fromIndex = it * by
val toIndex = Math.min(fromIndex + by, this.size)
subList(fromIndex, toIndex)
}
}
}
/**
* Not a very good transpose function. Works for squares though...
*/
inline fun <reified T> transpose(values: List<List<T>>): List<List<T>> {
return values.indices.map { i -> values[0].indices.map { values[it][i] } }
}
fun randomSequence(upper: Int = 10, lower: Int = 0): List<Int> {
return (lower..upper).distinct().toMutableList().apply { Collections.shuffle(this) }
}
fun <T> List<T>.pickRandom(num: Int = 4): List<T> {
return randomSequence(upper = this.size, lower = 0).take(num).map { this[it] }
}
| [
{
"class_path": "nishtahir__scratchpad__51115e3/ExtensionsKt.class",
"javap": "Compiled from \"Extensions.kt\"\npublic final class ExtensionsKt {\n public static final boolean isValidTriangle(java.util.List<java.lang.Integer>);\n Code:\n 0: aload_0\n 1: ldc #10 // S... |
rhavran__ProjectEuler__1115674/src/Utils.kt | import kotlin.math.sqrt
/**
* https://www.youtube.com/watch?v=V08g_lkKj6Q
*/
class EratosthenesSieve(n: Int) {
val numbers: List<Boolean>
init {
val numbersArray = BooleanArray(n + 1)
numbersArray.fill(true)
var potentialPrime = 2
while (potentialPrime * potentialPrime <= n) {
// If prime[p] is not changed, then it is a prime
if (numbersArray[potentialPrime]) { // Update all multiples of p
var nextPow = potentialPrime * potentialPrime
while (nextPow <= n) {
numbersArray[nextPow] = false
nextPow += potentialPrime
}
}
potentialPrime++
}
numbers = numbersArray.toList()
}
fun isPrime(n: Int): Boolean {
return numbers[n]
}
}
object PrimeFactorization {
private val incrementFunc: (t: Long, u: Long?) -> Long? = { _, old -> if (old == null) 1L else old + 1L }
fun primeFactors(n: Long): Map<Long, Long> {
val numberToPower = hashMapOf<Long, Long>()
// Add the number of 2s that divide n.
var number = n
while (number % 2L == 0L) {
numberToPower.compute(2L, incrementFunc)
number /= 2L
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2) as per sieve of Eratosthenes.
var i = 3L
while (i <= sqrt(number.toDouble())) {
// While i divides n, add i and divide n
while (number % i == 0L) {
numberToPower.compute(i, incrementFunc)
number /= i
}
i += 2L
}
// This condition is to handle the case when
// n is a prime number greater than 2
if (number > 2L) {
numberToPower.compute(number, incrementFunc)
}
return numberToPower
}
}
/**
* σ0(N)
* https://en.wikipedia.org/wiki/Divisor_function
*/
fun Long.dividers(): Long {
var dividers = 1L
val numberToPower = PrimeFactorization.primeFactors(this)
for (entry in numberToPower) {
dividers *= (entry.value + 1)
}
return dividers
}
fun Long.sequenceSumStartingFrom(a0: Long): Long {
return sumFromTo(a0, this)
}
fun sumFromTo(a0: Long, aN: Long): Long {
val n = aN - a0 + 1
return (n.toDouble() / 2.0 * (a0 + aN)).toLong()
} | [
{
"class_path": "rhavran__ProjectEuler__1115674/UtilsKt.class",
"javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final long dividers(long);\n Code:\n 0: lconst_1\n 1: lstore_2\n 2: getstatic #12 // Field PrimeFactorization.INSTANCE:... |
rhavran__ProjectEuler__1115674/src/P14LongestCollatzSequence.kt | fun main(args: Array<String>) {
println("Res: " + findSolution())
}
/**
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
*/
private fun findSolution(): Long {
val startingPoint = 999_999L
var maxChain = 0L
var startingPointWithMaxChain = 0L
for (x in startingPoint downTo 1L) {
val collatzSequence = collatzSequence(x)
if (collatzSequence > maxChain) {
maxChain = collatzSequence
startingPointWithMaxChain = x
}
}
return startingPointWithMaxChain
}
fun collatzSequence(startingPoint: Long): Long {
var result = 1L
var number = startingPoint
while (number != 1L) {
number = nextCollatzNumber(number)
result++
}
return result
}
fun nextCollatzNumber(n: Long): Long {
return if (n % 2 == 0L) n / 2 else (n * 3) + 1
}
| [
{
"class_path": "rhavran__ProjectEuler__1115674/P14LongestCollatzSequenceKt.class",
"javap": "Compiled from \"P14LongestCollatzSequence.kt\"\npublic final class P14LongestCollatzSequenceKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
rhavran__ProjectEuler__1115674/src/P12HighlyDivisibleTriangularNumber.kt | fun main(args: Array<String>) {
println("Res: " + findSolution())
}
/**
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
Res:76576500
Solution: σ0(N)
https://en.wikipedia.org/wiki/Prime_omega_function
*/
private fun findSolution(): Long {
val min = 10000 // 28 has 5
val nThTriangleNumber = Long.MAX_VALUE
for (nTh in min..nThTriangleNumber) {
val triangleNumber = nTh.sequenceSumStartingFrom(1)
if (triangleNumber % 2 != 0L && triangleNumber % 5 != 0L) {
println(triangleNumber)
continue
}
val numberOfDividers = triangleNumber.dividers()
if (numberOfDividers >= 500L) {
return triangleNumber
}
}
return -1
}
| [
{
"class_path": "rhavran__ProjectEuler__1115674/P12HighlyDivisibleTriangularNumberKt.class",
"javap": "Compiled from \"P12HighlyDivisibleTriangularNumber.kt\"\npublic final class P12HighlyDivisibleTriangularNumberKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n ... |
rhavran__ProjectEuler__1115674/src/P4LargersPalindromOf3Digits.kt | fun main(args: Array<String>) {
println("Res: " + largestLargestPalindromeProduct())
}
/**
* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
* Find the largest palindrome made from the product of two 3-digit numbers.
*/
private fun largestLargestPalindromeProduct(): Int {
val largest = 999
val smallest = 100
// largest number * largest number could be the first largest palindrome result
val palindrome = largest * largest
for (x in palindrome downTo 1) {
for (b in largest downTo smallest step 1) {
val a = x / b;
if (x % b == 0 && a <= largest && a >= smallest && isPalindrome(x.toString())) {
return x
}
}
}
return 0
}
fun isPalindrome(palindrome: String): Boolean {
var isPalindrome = true
for (ch in 0 until (palindrome.length / 2) step 1) {
isPalindrome = isPalindrome && palindrome[ch] == palindrome[palindrome.length - 1 - ch]
}
return isPalindrome;
}
| [
{
"class_path": "rhavran__ProjectEuler__1115674/P4LargersPalindromOf3DigitsKt.class",
"javap": "Compiled from \"P4LargersPalindromOf3Digits.kt\"\npublic final class P4LargersPalindromOf3DigitsKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9... |
Mestru__Advent_of_Code_2017__2cc4211/src/main/kotlin/Day7.kt | import java.io.File
import kotlin.math.abs
data class Program(var weight: Int, var parent: String?, var children: List<String>?)
val programs = HashMap<String, Program>()
fun main(args: Array<String>) {
// part 1
val lineRegex = "(\\w+) \\((\\d+)\\)( -> )?(.+)?".toRegex()
var name: String
var weight: Int
var children: List<String> = ArrayList()
File("input/day7.txt").forEachLine { line -> run {
name = lineRegex.matchEntire(line)?.groups?.get(1)!!.value
weight = lineRegex.matchEntire(line)?.groups?.get(2)!!.value.toInt()
if (lineRegex.matchEntire(line)?.groups?.get(3)?.value != null) {
children = lineRegex.matchEntire(line)?.groups?.get(4)?.value!!.split(", ")
}
children.forEach { child -> run {
programs.getOrPut(child, { Program(-1, name, null) }).parent = name
}}
programs.getOrPut(name, { Program(weight, null, children) }).weight = weight
programs.get(name)!!.children = children
children = ArrayList()
} }
var parent = Program(0, null, null)
programs.forEach { program -> run {
if (program.value.parent == null) {
println(program.key)
parent = program.value
}
} }
// part 2
balanceWeight(parent)
}
fun balanceWeight(program: Program): Int {
var weight = program.weight
var childWeight: Int
val childrenWeight = ArrayList<Int>()
if (program.children != null) {
for (child in program.children!!) {
childWeight = balanceWeight(programs.getOrDefault(child, Program(0, null, null)))
childrenWeight.add(childWeight)
weight += childWeight
}
}
if (childrenWeight.size > 0) {
val testedWeight = childrenWeight.get(0)
var badWeight = -1
childrenWeight.forEach { childsWeight -> run {
if (childsWeight != testedWeight) {
badWeight = childsWeight
}
} }
if (badWeight != -1 ) {
println(abs(testedWeight - badWeight))
}
}
return weight
} | [
{
"class_path": "Mestru__Advent_of_Code_2017__2cc4211/Day7Kt.class",
"javap": "Compiled from \"Day7.kt\"\npublic final class Day7Kt {\n private static final java.util.HashMap<java.lang.String, Program> programs;\n\n public static final java.util.HashMap<java.lang.String, Program> getPrograms();\n Code:... |
Mestru__Advent_of_Code_2017__2cc4211/src/main/kotlin/Day4.kt | import java.io.File
val letters = "abcdefghijklmnopqrstuvwxyz".toCharArray()
fun main(args: Array<String>) {
// part 1
var numberOfCorrectPassphrases = 0
File("input/day4.txt").forEachLine { line -> run {
if (passphraseIsValid(line)) numberOfCorrectPassphrases++
}
}
println(numberOfCorrectPassphrases)
// part 2
numberOfCorrectPassphrases = 0
File("input/day4.txt").forEachLine { line -> run {
val words = line.split(Regex("[ \t]"))
val o1 = HashMap<Char, Int>()
val o2 = HashMap<Char, Int>()
for (letter in letters) {
o1.put(letter, 0)
o2.put(letter, 0)
}
var isPassphraseCorrect = true
for (i in 0 until words.size) {
for (letter in letters) {
o1.put(letter, 0)
}
words[i].toCharArray().forEach { c -> o1.put(c, o1.getValue(c) + 1) }
for (j in 0 until words.size) {
for (letter in letters) {
o2.put(letter, 0)
}
words[j].toCharArray().forEach { c -> o2.put(c, o2.getValue(c) + 1) }
if (i != j && mapsEqual(o1, o2)) isPassphraseCorrect = false
}
}
if (isPassphraseCorrect) numberOfCorrectPassphrases++
}
}
println(numberOfCorrectPassphrases)
}
fun passphraseIsValid(line : String) : Boolean {
val words = line.split(Regex("[ \t]"))
for (i in 0 until words.size) {
for (j in 0 until words.size) {
if (i != j && words[i].equals(words[j])) return false
}
}
return true
}
fun mapsEqual(o1: HashMap<Char, Int>, o2: HashMap<Char, Int>): Boolean {
for (letter in letters) {
if (o1.get(letter) != o2.get(letter)) return false
}
return true
} | [
{
"class_path": "Mestru__Advent_of_Code_2017__2cc4211/Day4Kt.class",
"javap": "Compiled from \"Day4.kt\"\npublic final class Day4Kt {\n private static final char[] letters;\n\n public static final char[] getLetters();\n Code:\n 0: getstatic #11 // Field letters:[C\n 3: a... |
JoelEager__Kotlin-Collision-Detector__2c05f92/src/sat.kt | import kotlin.math.pow
class Vector(var x: Double, var y: Double)
/**
* @param poly1, poly2 The two polygons described as arrays of points as Vectors
* Note: The points list must go in sequence around the polygon
* @param maxDist The maximum distance between any two points of any two polygons that can be touching
* If this null then the optimization check that uses it will be skipped
*/
fun hasCollided(poly1: Array<Vector>, poly2: Array<Vector>, maxDist: Double?=null): Boolean {
// Do an optimization check using the maxDist
if (maxDist != null) {
if ((poly1[1].x - poly2[0].x).pow(2) + (poly1[1].y - poly2[0].y).pow(2) <= maxDist.pow(2)) {
// Collision is possible so run SAT on the polys
return runSAT(poly1, poly2)
} else {
return false
}
} else {
// No maxDist so run SAT on the polys
return runSAT(poly1, poly2)
}
}
fun runSAT(poly1: Array<Vector>, poly2: Array<Vector>): Boolean {
// Implements the actual SAT algorithm
val edges = polyToEdges(poly1) + polyToEdges(poly2)
val axes = Array(edges.size, { index -> orthogonal(edges[index])})
for (axis in axes) {
if (!overlap(project(poly1, axis), project(poly2, axis))) {
// The polys don't overlap on this axis so they can't be touching
return false
}
}
// The polys overlap on all axes so they must be touching
return true
}
/**
* Returns a vector going from point1 to point2
*/
fun edgeVector(point1: Vector, point2: Vector) = Vector(point2.x - point1.x, point2.y - point1.y)
/**
* Returns an array of the edges of the poly as vectors
*/
fun polyToEdges(poly: Array<Vector>) = Array(poly.size,
{ index -> edgeVector(poly[index], poly[(index + 1) % poly.size]) })
/**
* Returns a new vector which is orthogonal to the given vector
*/
fun orthogonal(vector: Vector) = Vector(vector.y, -vector.x)
/**
* Returns the dot (or scalar) product of the two vectors
*/
fun dotProduct(vector1: Vector, vector2: Vector) = vector1.x * vector2.x + vector1.y * vector2.y
/**
* Returns a vector showing how much of the poly lies along the axis
*/
fun project(poly: Array<Vector>, axis: Vector): Vector {
val dots = Array(poly.size, { index -> dotProduct(poly[index], axis) })
return Vector(dots.min()!!, dots.max()!!)
}
/**
* Returns a boolean indicating if the two projections overlap
*/
fun overlap(projection1: Vector, projection2: Vector) = projection1.x <= projection2.y &&
projection2.x <= projection1.y | [
{
"class_path": "JoelEager__Kotlin-Collision-Detector__2c05f92/SatKt.class",
"javap": "Compiled from \"sat.kt\"\npublic final class SatKt {\n public static final boolean hasCollided(Vector[], Vector[], java.lang.Double);\n Code:\n 0: aload_0\n 1: ldc #10 // String p... |
darwineee__adventOfCode2023__c301358/src/main/kotlin/Day1.kt | import kotlin.io.path.Path
import kotlin.io.path.forEachLine
fun day1_part1(path: String) {
var result = 0
Path(path).forEachLine { line ->
val numLine = line.filter { it.isDigit() }
val num = when (numLine.length) {
1 -> numLine + numLine
2 -> numLine
else -> numLine.removeRange(1, numLine.lastIndex)
}.toIntOrNull()
if (num != null) result += num
}
println(result)
}
fun day1_part2(path: String) {
var result = 0
val map = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9",
)
val substrings = map.flatMap { listOf(it.key, it.value) }
Path(path).forEachLine { line ->
val numLine = findAllOverlappingMatches(line, substrings).joinToString("") { map[it] ?: it }
val num = when (numLine.length) {
1 -> numLine + numLine
2 -> numLine
else -> numLine.removeRange(1, numLine.lastIndex)
}.toIntOrNull()
if (num != null) result += num
}
println(result)
}
fun findAllOverlappingMatches(input: String, substrings: List<String>): List<String> {
val matches = mutableListOf<String>()
for (i in input.indices) {
for (j in i + 1..input.length) {
val substring = input.substring(i, j)
if (substrings.contains(substring)) {
matches.add(substring)
}
}
}
return matches
} | [
{
"class_path": "darwineee__adventOfCode2023__c301358/Day1Kt.class",
"javap": "Compiled from \"Day1.kt\"\npublic final class Day1Kt {\n public static final void day1_part1(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #11 // String path\n 3: invokestatic #... |
leonhardbrenner__kitchensink__a7b9701/src/jvmMain/kotlin/Atom.kt | import java.util.*
val Pair<Int, Int>.a: Int get() = first
val Pair<Int, Int>.b: Int get() = second
fun <T, R> Sequence<T>.reductions(initial: R, operation: (acc: R, T) -> R) : Sequence<R> = sequence {
var last = initial
forEach {
last = operation(last, it)
yield(last)
}
}
class Atom(val data: IntArray) {
override fun toString() = Arrays.toString(this.data)
operator fun get(index: Atom) = Atom(data.sliceArray(index.data.toList()))
operator fun set(index: Atom, value: Atom) {
(index.data zip value.data).map { pair: Pair<Int, Int> ->
val (index, value) = pair
this.data[index] = value
}
}
operator fun plus(b: Int) = Atom(data.map { it + b }.toIntArray())
operator fun plus(other: Atom) = Atom((data zip other.data).map { it.a + it.b }.toIntArray())
operator fun minus(b: Int) = Atom(data.map { it - b }.toIntArray())
operator fun minus(other: Atom) = Atom((data zip other.data).map { it.a - it.b }.toIntArray())
operator fun times(b: Int) = Atom(data.map { it * b }.toIntArray())
operator fun times(other: Atom) = Atom((data zip other.data).map { it.a * it.b }.toIntArray())
operator fun div(b: Int) = Atom(data.map { it / b }.toIntArray())
operator fun div(other: Atom) = Atom((data zip other.data).map { it.a / it.b }.toIntArray())
operator fun rem(b: Int) = Atom(data.map { it % b }.toIntArray())
operator fun rem(other: Atom) = Atom((data zip other.data).map { it.a % it.b }.toIntArray())
//Todo - implement this like rl.range
operator fun rangeTo(b: Int): Atom = TODO("Not specified yet") //Atom(data.map { it % b }.toIntArray())
operator fun rangeTo(other: Atom): Atom = TODO("Not specified yet") //Atom((data zip other.data).map { it.a % it.b }.toIntArray())
fun cumsum(): Atom {
var last = 0
return Atom(data.map {
last += it
last
}.toIntArray())
}
fun repeat(count: Int): Atom {
return Atom(this.data.flatMap {
value ->
IntRange(1, count).map { value }
}.toIntArray())
}
fun repeat(counts: IntArray): Atom {
return Atom(this.data.zip(counts).flatMap {
pair ->
val (value, count) = pair
IntRange(1, count).map { value }
}.toIntArray())
}
fun repeat(counts: Atom): Atom {
return this.repeat(counts.data)
}
}
fun main(args: Array<String>) {
val x = Atom(arrayOf(1, 2, 3, 4).toIntArray())
val y = Atom(arrayOf(1, 3).toIntArray())
println("x = $x")
println("y = $y")
println("x[y] = ${x[y]}")
println("x + 1 = ${x + 1}")
println("x + x = ${x + x}")
println("x - 1 = ${x - 1}")
println("x - x = ${x - x}")
println("x * 1 = ${x * 1}")
println("x * x = ${x * x}")
println("x / 2 = ${x / 2}")
println("x / (x * 2) = ${x / (x * 2)}")
println("x % 2 = ${x % 2}")
println("x % (x * 2) = ${x % Atom(arrayOf(2, 2, 2, 2).toIntArray())}")
x[y] = y + 2; println("x[y] = y + 2; x = ${x}")
try {
x[y]..2
} catch (ex: NotImplementedError) {
println("TODO - Think of a useful way of using ..")
}
try {
x[y]..y
} catch (ex: NotImplementedError) {
println("TODO - Think of a useful way of using ..")
}
println(x)
println(x.cumsum())
//SequenceOf
println(sequenceOf(0, 1, 2, 3, 4).reductions(0) { last, it -> last + it }.toList()) //Cumsum
println(sequenceOf(0, 1, 2, 3, 4).reduce { last, it -> last + it }) //Sum
println(x.repeat(3))
println(x.repeat(x))
} | [
{
"class_path": "leonhardbrenner__kitchensink__a7b9701/AtomKt.class",
"javap": "Compiled from \"Atom.kt\"\npublic final class AtomKt {\n public static final int getA(kotlin.Pair<java.lang.Integer, java.lang.Integer>);\n Code:\n 0: aload_0\n 1: ldc #10 // String <thi... |
NicLeenknegt__kenze_exercise__11081ce/src/main/kotlin/Main.kt | import java.io.File
data class Matrix(
val matrix:Array<ArrayList<String>>,
var row:Int = 0,
var column:Int = 0
)
fun main(args: Array<String>) {
var words:Array<String> = splitStringByDelimiter(readFile("./input.txt"), "\n")
printStringArray(words)
var maxWordLength = words.map{ it:String -> it.length }.max() ?: 0
var maxWord = words.maxBy{ it:String -> it.length }
println(maxWordLength)
println(maxWord)
var wordMatrix: Array<ArrayList<String>> = Array<ArrayList<String>>(maxWordLength) { arrayListOf() }
//Counting sort
for (word in words) {
wordMatrix[word.length-1].add(word)
}
for (array in wordMatrix) {
println("ARRAY")
for (word in array) {
println(word)
}
}
var wordMatrixClass:Matrix = Matrix(wordMatrix)
}
fun readFile(filename:String):String = File(filename).inputStream().readBytes().toString(Charsets.UTF_8)
fun splitStringByDelimiter(input:String, delimiter:String):Array<String> = input.split(delimiter).map { it -> it.trim()}.dropLast(1).toTypedArray()
fun printStringArray(stringArray:Array<String>) {
for (string in stringArray) {
println(string)
}
}
fun isSolutionValid(wordLength:Int, solutionLength:Int, solutionWord:String, referenceWord:String):Boolean = ((wordLength + solutionLength) <= referenceWord.length ) && referenceWord.startsWith(solutionWord)
fun isSolutionComplete(referenceWord:String, solutionWord:String):Boolean = referenceWord == solutionWord
fun buildMatchingWordArrayRec(wordMatrix:Matrix, solutionArrayList:ArrayList<String>, solutionLength:Int, solutionCalculation:String, solutionWord:String, referenceWord:String) {
if (!isSolutionValid(wordMatrix.row, solutionLength, solutionWord, referenceWord)) {
return
}
if (isSolutionComplete(referenceWord, solutionWord)) {
println(solutionWord)
solutionArrayList.add(solutionWord)
}
while (wordMatrix.row < wordMatrix.matrix.size) {
while(wordMatrix.column < wordMatrix.matrix[wordMatrix.row].size) {
//Add current word to word solution
solutionWord.plus(wordMatrix.matrix[wordMatrix.row][wordMatrix.column])
//solutionLength is now equal to the original length + matrixRow
buildMatchingWordArrayRec(wordMatrix, solutionArrayList, solutionLength + wordMatrix.row, solutionCalculation, solutionWord, referenceWord)
wordMatrix.column + 1
}
wordMatrix.row + 1
wordMatrix.column = 0
}
}
| [
{
"class_path": "NicLeenknegt__kenze_exercise__11081ce/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic #15 ... |
gardnerdickson__advent-of-code-2015__4a23ab3/src/day_2.kt | import java.io.File
import kotlin.streams.toList
fun main(args: Array<String>) {
val input = "res/day_2_input.txt"
val answer1 = Day2.part1(input)
println("Part 1: $answer1")
val answer2 = Day2.part2(input)
println("Part 2: $answer2")
}
object Day2 {
fun part1(input: String): Int {
val reader = File(input).bufferedReader()
val amounts = reader.lines()
.map { parsePresent(it) }
.map { it.surfaceArea() + it.slack() }
.toList()
return amounts.sum()
}
fun part2(input: String): Int {
val reader = File(input).bufferedReader()
val amounts = reader.lines()
.map { parsePresent(it) }
.map { it.ribbon() + it.bow() }
.toList()
return amounts.sum()
}
private fun parsePresent(dimensions: String): Present {
val components = dimensions.split("x")
return Present(components[0].toInt(), components[1].toInt(), components[2].toInt())
}
}
data class Present(val width: Int, val height: Int, val length: Int) {
fun surfaceArea(): Int {
return 2 * length * width + 2 * width * height + 2 * height * length
}
fun slack(): Int {
val sorted = listOf(width, height, length).sorted()
return sorted[0] * sorted[1]
}
fun ribbon(): Int {
val sorted = listOf(width, height, length).sorted()
return sorted[0] * 2 + sorted[1] * 2
}
fun bow(): Int {
return width * height * length
}
}
| [
{
"class_path": "gardnerdickson__advent-of-code-2015__4a23ab3/Day_2Kt.class",
"javap": "Compiled from \"day_2.kt\"\npublic final class Day_2Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokest... |
gardnerdickson__advent-of-code-2015__4a23ab3/src/day_3.kt | import java.io.File
fun main(args: Array<String>) {
val input = "res/day_3_input.txt"
val answer1 = Day3.part1(input)
println("Part 1: $answer1")
val answer2 = Day3.part2(input)
println("Part 2: $answer2")
}
object Day3 {
private enum class Turn {
SANTA, ROBO_SANTA;
fun nextTurn(): Turn {
return when (this) {
Turn.SANTA -> Turn.ROBO_SANTA
else -> Turn.SANTA
}
}
}
fun part1(input: String): Int {
val directions = File(input).readText().toCharArray()
var currentPosition = Position(0, 0)
val positions = mutableSetOf<Position>()
positions.add(currentPosition)
for (direction in directions) {
val nextPosition = currentPosition.move(direction)
positions.add(nextPosition)
currentPosition = nextPosition
}
return positions.size
}
fun part2(input: String): Int {
val directions = File(input).readText().toCharArray()
var currentSantaPosition = Position(0, 0)
var currentRoboSantaPosition = Position(0, 0)
val positions = mutableSetOf<Position>()
positions.add(currentSantaPosition)
var turn = Turn.SANTA
for (direction in directions) {
when (turn) {
Turn.SANTA -> {
val nextPosition = currentSantaPosition.move(direction)
positions.add(nextPosition)
currentSantaPosition = nextPosition
}
Turn.ROBO_SANTA -> {
val nextPosition = currentRoboSantaPosition.move(direction)
positions.add(nextPosition)
currentRoboSantaPosition = nextPosition
}
}
turn = turn.nextTurn()
}
return positions.size
}
}
data class Position(val x: Int, val y: Int) {
fun move(direction: Char): Position {
return when (direction) {
'^' -> Position(this.x, this.y + 1)
'>' -> Position(this.x + 1, this.y)
'v' -> Position(this.x, this.y - 1)
'<' -> Position(this.x - 1, this.y)
else -> throw IllegalArgumentException("Input contained invalid character: $direction")
}
}
}
| [
{
"class_path": "gardnerdickson__advent-of-code-2015__4a23ab3/Day_3Kt.class",
"javap": "Compiled from \"day_3.kt\"\npublic final class Day_3Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokest... |
gardnerdickson__advent-of-code-2015__4a23ab3/src/day_10.kt | import java.lang.StringBuilder
fun main(args: Array<String>) {
val input = "1113222113"
val answer1 = Day10.part1(input)
println("Part 1: $answer1")
val answer2 = Day10.part2(input)
println("Part 2: $answer2")
}
object Day10 {
private fun lookAndSay(sequence: String): String {
val digits = sequence.toCharArray().map { Character.getNumericValue(it) }
val stringBuilder = StringBuilder()
var lastDigit = -1
var currentDigit: Int
var quantity = 0
for (i in 0 until digits.size) {
currentDigit = digits[i]
if (i == digits.size - 1) {
if (currentDigit != lastDigit) {
stringBuilder.append("$quantity$lastDigit")
stringBuilder.append("1$currentDigit")
} else {
stringBuilder.append("${(quantity + 1)}$lastDigit")
}
} else if (currentDigit != lastDigit && lastDigit != -1) {
stringBuilder.append("$quantity$lastDigit")
quantity = 1
} else {
quantity++
}
lastDigit = currentDigit
}
return stringBuilder.toString()
}
fun part1(sequence: String): Int {
var nextSequence = sequence
repeat(40) {
nextSequence = lookAndSay(nextSequence)
}
return nextSequence.length
}
fun part2(sequence: String): Int {
var nextSequence = sequence
repeat(50) {
nextSequence = lookAndSay(nextSequence)
}
return nextSequence.length
}
}
| [
{
"class_path": "gardnerdickson__advent-of-code-2015__4a23ab3/Day_10Kt.class",
"javap": "Compiled from \"day_10.kt\"\npublic final class Day_10Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invok... |
gardnerdickson__advent-of-code-2015__4a23ab3/src/day_7.kt | import java.io.File
import java.util.regex.Matcher
fun main(args: Array<String>) {
val filename = "res/day_7_input.txt"
val answer1 = Day7.part1(File(filename))
println("Part 1: $answer1")
val answer2 = Day7.part2(File(filename), answer1)
println("Part 2: $answer2")
}
object Day7 {
fun part1(file: File): Int {
val wires = mutableMapOf<String, Gate>()
file.useLines { lines ->
lines.map { Gate.parse(it) }.forEach { wires[it.target] = it }
}
return wires["a"]!!.evaluate(wires)
}
fun part2(file: File, a: Int): Int {
val wires = mutableMapOf<String, Gate>()
file.useLines { lines ->
lines.map { Gate.parse(it) }.forEach { wires[it.target] = it }
}
wires["b"]!!.wireValue = a
return wires["a"]!!.evaluate(wires)
}
}
sealed class Gate(val target: String) {
companion object {
private val andRegex = Regex("(?<left>[\\w\\d]+) AND (?<right>[\\w\\d]+) -> (?<target>\\w+)").toPattern()
private val orRegex = Regex("(?<left>[\\w\\d]+) OR (?<right>[\\w\\d]+) -> (?<target>\\w+)").toPattern()
private val lshiftRegex = Regex("(?<left>[\\w\\d]+) LSHIFT (?<right>[\\d]+) -> (?<target>\\w+)").toPattern()
private val rshiftRegex = Regex("(?<left>[\\w\\d]+) RSHIFT (?<right>[\\d]+) -> (?<target>\\w+)").toPattern()
private val notRegex = Regex("NOT (?<source>[\\w]+) -> (?<target>\\w+)").toPattern()
private val signalRegex = Regex("(?<source>[\\w\\d]+) -> (?<target>\\w+)").toPattern()
operator fun Matcher.get(name: String): String {
return this.group(name)
}
fun parse(instruction: String): Gate {
var matcher = andRegex.matcher(instruction)
if (matcher.matches()) {
return AndGate(matcher["left"], matcher["right"], matcher["target"])
}
matcher = orRegex.matcher(instruction)
if (matcher.matches()) {
return OrGate(matcher["left"], matcher["right"], matcher["target"])
}
matcher = lshiftRegex.matcher(instruction)
if (matcher.matches()) {
return LshiftGate(matcher["left"], matcher["right"].toInt(), matcher["target"])
}
matcher = rshiftRegex.matcher(instruction)
if (matcher.matches()) {
return RshiftGate(matcher["left"], matcher["right"].toInt(), matcher["target"])
}
matcher = notRegex.matcher(instruction)
if (matcher.matches()) {
return NotGate(matcher["source"], matcher["target"])
}
matcher = signalRegex.matcher(instruction)
if (matcher.matches()) {
return SignalGate(matcher["source"], matcher["target"])
}
throw IllegalArgumentException("Instruction '$instruction' could not be parsed")
}
}
var wireValue: Int? = null
abstract fun evaluate(wires: Map<String, Gate>): Int
}
class AndGate(private val left: String, private val right: String, target: String) : Gate(target) {
override fun evaluate(wires: Map<String, Gate>): Int {
if (wireValue == null) {
wireValue = (left.toIntOrNull() ?: wires[left]!!.evaluate(wires)) and (right.toIntOrNull() ?: wires[right]!!.evaluate(wires))
}
return wireValue!!.toInt()
}
}
class OrGate(private val left: String, private val right: String, target: String) : Gate(target) {
override fun evaluate(wires: Map<String, Gate>): Int {
if (wireValue == null) {
wireValue = (left.toIntOrNull() ?: wires[left]!!.evaluate(wires)) or (right.toIntOrNull() ?: wires[right]!!.evaluate(wires))
}
return wireValue!!.toInt()
}
}
class LshiftGate(private val left: String, private val right: Int, target: String) : Gate(target) {
override fun evaluate(wires: Map<String, Gate>): Int {
if (wireValue == null) {
wireValue = (left.toIntOrNull() ?: wires[left]!!.evaluate(wires)) shl right
}
return wireValue!!.toInt()
}
}
class RshiftGate(private val left: String, private val right: Int, target: String) : Gate(target) {
override fun evaluate(wires: Map<String, Gate>): Int {
if (wireValue == null) {
wireValue = (left.toIntOrNull() ?: wires[left]!!.evaluate(wires)) shr right
}
return wireValue!!.toInt();
}
}
class NotGate(private val source: String, target: String) : Gate(target) {
override fun evaluate(wires: Map<String, Gate>): Int {
if (wireValue == null) {
wireValue = (source.toIntOrNull() ?: wires[source]!!.evaluate(wires)).inv()
}
return wireValue!!.toInt()
}
}
class SignalGate(private val source: String, target: String) : Gate(target) {
override fun evaluate(wires: Map<String, Gate>): Int {
if (wireValue == null) {
wireValue = source.toIntOrNull() ?: wires[source]!!.evaluate(wires)
}
return wireValue!!.toInt()
}
}
| [
{
"class_path": "gardnerdickson__advent-of-code-2015__4a23ab3/Day_7Kt.class",
"javap": "Compiled from \"day_7.kt\"\npublic final class Day_7Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokest... |
darian-catalin-cucer__maximum-matching__db6b2b8/kt.kt | import java.util.*
fun maxMatching(n: Int, graph: Array<MutableList<Int>>): Int {
val matching = IntArray(n) { -1 }
val seen = BooleanArray(n)
fun dfs(i: Int): Boolean {
seen[i].also { seen[i] = true }
graph[i].forEach { j ->
if (matching[j] == -1 || (!seen[matching[j]] && dfs(matching[j]))) {
matching[j] = i
return true
}
}
return false
}
var matches = 0
(0 until n).forEach { i ->
if (dfs(i)) {
matches++
}
seen.fill(false)
}
return matches
}
// The code above implements the Hopcroft-Karp algorithm for finding the maximum matching in a bipartite graph. The algorithm starts by initializing the matching array to -1, which represents the fact that no node has been matched yet. The function dfs(i) attempts to find an augmenting path starting from node i, and updates the matching array if it succeeds. The maxMatching function loops over all nodes in one side of the bipartite graph, calling dfs on each node and incrementing the matches counter if a match is found. This process continues until no more augmenting paths can be found. The final value of matches is the size of the maximum matching in the bipartite graph.
| [
{
"class_path": "darian-catalin-cucer__maximum-matching__db6b2b8/KtKt.class",
"javap": "Compiled from \"kt.kt\"\npublic final class KtKt {\n public static final int maxMatching(int, java.util.List<java.lang.Integer>[]);\n Code:\n 0: aload_1\n 1: ldc #10 // String gr... |
luluvia__advent-of-code-22__29ddde3/src/main/kotlin/Day03.kt | class Day03 {
fun part1(input: List<String>): Int {
var priorityScore = 0
for (line in input) {
val matchingChar = getMatchingChar(line)
priorityScore += getPriorityScore(matchingChar)
}
return priorityScore
}
fun part2(input: List<String>): Int {
var priorityScore = 0
for (lines in input.chunked(3)) {
priorityScore += getPriorityScore(getMatchingCharThreeLines(lines))
}
return priorityScore
}
// Get char that matches across three lines
private fun getMatchingCharThreeLines(lines: List<String>): Char {
for (char in lines[0]) {
if (lines[1].contains(char) && lines[2].contains(char)) {
return char
}
}
throw IllegalArgumentException("Lines do not contain matching char")
}
private fun getMatchingChar(line: String): Char {
val firstRucksackRange = IntRange(0, line.length/2 - 1)
val secondRucksackRange = IntRange(line.length/2, line.length - 1)
for (char in line.substring(firstRucksackRange)) {
if (char in line.substring(secondRucksackRange)) {
return char
}
}
throw IllegalArgumentException("Line does not contain matching character")
}
private fun getPriorityScore(matchingChar: Char): Int {
return if (matchingChar.isLowerCase()) {
matchingChar.code - 96
} else {
matchingChar.code - 38
}
}
} | [
{
"class_path": "luluvia__advent-of-code-22__29ddde3/Day03.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class Day03 {\n public Day03();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final int ... |
luluvia__advent-of-code-22__29ddde3/src/main/kotlin/Day02.kt | class Day02 {
private val scores1 = mapOf(
'X' to mapOf('A' to 4, 'B' to 1, 'C' to 7),
'Y' to mapOf('A' to 8, 'B' to 5, 'C' to 2),
'Z' to mapOf('A' to 3, 'B' to 9, 'C' to 6)
)
private val scores2 = mapOf(
'X' to mapOf('A' to 3, 'B' to 1, 'C' to 2),
'Y' to mapOf('A' to 4, 'B' to 5, 'C' to 6),
'Z' to mapOf('A' to 8, 'B' to 9, 'C' to 7)
)
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val opChoice = line[0]
val myChoice = line[2]
score += scores1[myChoice]!![opChoice]!!
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (line in input) {
val opChoice = line[0]
val myOutcome = line[2]
score += scores2[myOutcome]!![opChoice]!!
}
return score
}
} | [
{
"class_path": "luluvia__advent-of-code-22__29ddde3/Day02.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class Day02 {\n private final java.util.Map<java.lang.Character, java.util.Map<java.lang.Character, java.lang.Integer>> scores1;\n\n private final java.util.Map<java.lang.Character, java.u... |
xfl03__DiscreteCourseWork__281042e/Matrix/Matrix.kt | /**
* 邻接矩阵
* 1 2 0 0
* 0 0 1 0
* 1 0 0 1
* 0 0 1 0
*/
val matrix = arrayOf(
"1200",
"0010",
"1001",
"0010"
)
/**
* 矩阵乘法
*/
fun multiply(a: Array<IntArray>, b: Array<IntArray>): Array<IntArray> {
val arr = Array(a.size) { IntArray(b[0].size) }
for (i in a.indices) {
for (j in 0 until b[0].size) {
for (k in 0 until a[0].size) {
arr[i][j] += a[i][k] * b[k][j]
}
}
}
return arr
}
/**
* 输出矩阵
*/
fun printMatrix(a: Array<IntArray>, mode: Int = 0) {
val n = a.size
for (i in 0 until n) {
for (j in 0 until n) {
print(if (mode == 0) "${a[i][j]} " else "${if (a[i][j] != 0) 1 else 0} ")
}
println()
}
}
/**
* 矩阵内元素和
*/
fun sumMatrix(a: Array<IntArray>): Int {
val n = a.size
var t = 0
for (i in 0 until n) {
for (j in 0 until n) {
t += a[i][j]
}
}
return t
}
/**
* 矩阵加法
*/
fun add(a: Array<IntArray>, b: Array<IntArray>): Array<IntArray> {
val n = a.size
val arr = Array(n) { IntArray(n) }
for (i in 0 until n) {
for (j in 0 until n) {
arr[i][j] = a[i][j] + b[i][j]
}
}
return arr
}
/**
* 主函数
*/
fun main(args: Array<String>) {
val n = matrix.size
//创建二维数组存储矩阵
val arr = Array(n) { IntArray(n) }
//初始化矩阵,将文本形式的矩阵转换成数组形式
(0 until n).forEach { i ->
var t = matrix[i].toInt()
(0 until n).forEach {
arr[i][n - 1 - it] = t % 10
t /= 10
}
}
//输出邻接矩阵
println("邻接矩阵")
printMatrix(arr)
println()
//计算并存储矩阵的n次方
val arr2 = multiply(arr, arr)
val arr3 = multiply(arr, arr2)
val arr4 = multiply(arr, arr3)
println("邻接矩阵4次方")
printMatrix(arr4)
println("长度为4的通路")
println(sumMatrix(arr4))
println()
//合并矩阵
val arrs = add(arr, add(arr2, arr3))
println("可达矩阵")
printMatrix(arrs, 1)
} | [
{
"class_path": "xfl03__DiscreteCourseWork__281042e/MatrixKt.class",
"javap": "Compiled from \"Matrix.kt\"\npublic final class MatrixKt {\n private static final java.lang.String[] matrix;\n\n public static final java.lang.String[] getMatrix();\n Code:\n 0: getstatic #11 // Fie... |
mehran-naghizadeh__radix-sort__8b8bb34/radix_sort.kt | fun main() = unitTest()
fun radixSort(list: List<Int>): List<Int> {
val count = maxDigits(list)
var sorted = stringify(list)
for(i in 1..count) {
sorted = bucketize(sorted, count - i).flatten()
}
return sorted.map { it.toInt() }
}
fun bucketize(list: List<String>, position: Int): List<List<String>> {
return (0..9).map {
list.filter { str -> str[position].toString() == it.toString() }
}
}
fun stringify(list: List<Int>): List<String> {
val length = maxDigits(list)
return list.map {
val prefix = "0".repeat(length - it.toString().length)
"$prefix$it"
}
}
fun maxDigits(list: List<Int>) = list.maxOrNull()?.toString()?.length ?: 0
fun unitTest() {
val testCases = listOf(
listOf(
listOf(170, 45, 75, 90, 2, 802, 2, 66),
listOf(2, 2, 45, 66, 75, 90, 170, 802)
),
listOf(
listOf(8902, 67832, 12, 1000, 4002),
listOf(12, 1000, 4002, 8902, 67832)
)
)
testCases.forEach {
val originalArray = it[0]
val expectedResult = it[1]
val result = radixSort(originalArray)
if (result == expectedResult) {
println("Worked well for")
} else {
println("Failed on")
}
println(originalArray)
println(result)
println("--------")
}
}
| [
{
"class_path": "mehran-naghizadeh__radix-sort__8b8bb34/Radix_sortKt.class",
"javap": "Compiled from \"radix_sort.kt\"\npublic final class Radix_sortKt {\n public static final void main();\n Code:\n 0: invokestatic #9 // Method unitTest:()V\n 3: return\n\n public static fi... |
fpeterek__Advent-Of-Code__d5bdf89/Day3/spiral_memory.kt | import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.sqrt
fun findNearestSquareRoot(num: Int): Int {
val nearestRoot = ceil(sqrt(num.toDouble())).toInt()
return if (nearestRoot % 2 == 0) {
nearestRoot + 1
} else {
nearestRoot
}
}
fun main(args: Array<String>) {
val input = 325489
val nearestRoot = findNearestSquareRoot(input)
val rightBottom = nearestRoot * nearestRoot
val leftBottom = rightBottom - nearestRoot + 1
val leftTop = leftBottom - nearestRoot + 1
val rightTop = leftTop - nearestRoot + 1
val rightLowest = rightTop - nearestRoot + 2
val horizontalPos = when (input) {
in leftTop..leftBottom -> leftTop
in rightLowest..rightTop -> rightBottom
else -> input
}
val horizontal = if (horizontalPos >= leftBottom) {
val midVal = leftBottom + (nearestRoot / 2.0).toInt()
abs(horizontalPos - midVal)
} else {
val midVal = rightTop + (nearestRoot / 2.0).toInt()
abs(horizontalPos - midVal)
}
val verticalPosition = when (input) {
in leftBottom..rightBottom -> leftBottom
in leftTop..rightTop -> leftTop
else -> input
}
val vertical = if (verticalPosition < leftTop) {
val midVal = rightTop - (nearestRoot / 2.0).toInt()
abs(verticalPosition - midVal)
} else {
val midVal = leftTop + (nearestRoot / 2.0).toInt()
abs(verticalPosition - midVal)
}
println(horizontal + vertical)
}
| [
{
"class_path": "fpeterek__Advent-Of-Code__d5bdf89/Spiral_memoryKt.class",
"javap": "Compiled from \"spiral_memory.kt\"\npublic final class Spiral_memoryKt {\n public static final int findNearestSquareRoot(int);\n Code:\n 0: iload_0\n 1: i2d\n 2: invokestatic #12 // Me... |
fpeterek__Advent-Of-Code__d5bdf89/Day6/memory_banks.kt | // Solves both first and second problem
fun redistribute(banks: MutableList<Int>) {
val max = banks.max()!!
var index = banks.indexOf(max)
var blocksToAlloc = max
banks[index] = 0
while (blocksToAlloc > 0) {
++index
if (index >= banks.size) {
index = 0
}
++banks[index]
--blocksToAlloc
}
}
fun main(args: Array<String>) {
val input = "5 1 10 0 1 7 13 14 3 12 8 10 7 12 0 6"
val banks = input.split(" ").map { it.toInt() }.toMutableList()
val occuredCombinations = mutableListOf<String>()
var combination: String
while (true) {
redistribute(banks)
combination = banks.fold("") { acc: String, i: Int -> "$acc$i " }
if (occuredCombinations.find {it == combination} != null) {
break
}
occuredCombinations.add(combination)
}
val loopSize = (occuredCombinations.size) - occuredCombinations.indexOf(combination)
println("Number of combinations: ${occuredCombinations.size + 1}")
println("Loop size: $loopSize")
}
| [
{
"class_path": "fpeterek__Advent-Of-Code__d5bdf89/Memory_banksKt.class",
"javap": "Compiled from \"memory_banks.kt\"\npublic final class Memory_banksKt {\n public static final void redistribute(java.util.List<java.lang.Integer>);\n Code:\n 0: aload_0\n 1: ldc #10 /... |
rfermontero__LalL-a-rLar__ca693f2/src/Parser.kt | fun parseGrammar(grammar: List<Pair<String, String>>) = getFirsts(grammar)
fun getFirsts(grammar: List<Pair<String, String>>): Map<String, List<String>> =
grammar.groupBy { it.first }
.mapValues { it.value.map { it.second } }
.mapValues {
it.value.map {
getFirsts(grammar.groupBy { it.first }.mapValues { it.value.map { it.second } }, it)
}.flatten()
}
fun getFollows(grammar: List<Pair<String, String>>, firsts: Map<String, List<String>>) {
}
private fun getFirsts(mapByRules: Map<String, List<String>>, it: String): Collection<String> {
return when {
!mapByRules.containsKey(it.substringBefore(" ")) -> setOf(it.substringBefore(" "))
else -> mapByRules
.filterKeys { key -> key == it }
.values
.flatten()
.map {
when {
!mapByRules.containsKey(it.substringBefore(" ")) -> listOf(it)
else -> getFirsts(mapByRules, it)
}
}.flatten()
}
}
| [
{
"class_path": "rfermontero__LalL-a-rLar__ca693f2/ParserKt.class",
"javap": "Compiled from \"Parser.kt\"\npublic final class ParserKt {\n public static final java.util.Map<java.lang.String, java.util.List<java.lang.String>> parseGrammar(java.util.List<kotlin.Pair<java.lang.String, java.lang.String>>);\n ... |
KonstantinLukaschenko__genetic-algorithm-kotlin__e282854/src/GeneticAlgorithm.kt | import java.lang.Math.random
/**
* Implementation of a basic genetic algorithm, that is capable to generate solutions for optimization and search
* problems relying on bio-inspired operations such as crossover, mutation and selection.
*
* @param T the type of an individual.
* @property population a collection of individuals to start optimization.
* @property score a function which scores the fitness of an individual. Higher fitness is better.
* @property cross a function which implements the crossover of two individuals resulting in a child.
* @property mutate a function which mutates a given individual.
* @property select a function which implements a selection strategy of an individual from the population.
*/
class GeneticAlgorithm<T>(
var population: Collection<T>,
val score: (individual: T) -> Double,
val cross: (parents: Pair<T, T>) -> T,
val mutate: (individual: T) -> T,
val select: (scoredPopulation: Collection<Pair<Double, T>>) -> T) {
/**
* Returns the best individual after the given number of optimization epochs.
*
* @param epochs number of optimization epochs.
* @property mutationProbability a value between 0 and 1, which defines the mutation probability of each child.
*/
fun run(epochs: Int = 1000, mutationProbability: Double = 0.1): T {
var scoredPopulation = population.map { Pair(score(it), it) }.sortedByDescending { it.first }
for (i in 0..epochs)
scoredPopulation = scoredPopulation
.map { Pair(select(scoredPopulation), select(scoredPopulation)) }
.map { cross(it) }
.map { if (random() <= mutationProbability) mutate(it) else it }
.map { Pair(score(it), it) }
.sortedByDescending { it.first }
return scoredPopulation.first().second
}
}
| [
{
"class_path": "KonstantinLukaschenko__genetic-algorithm-kotlin__e282854/GeneticAlgorithm$run$$inlined$sortedByDescending$2.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class GeneticAlgorithm$run$$inlined$sortedByDescending$2<T> implements java.util.Comparator {\n public GeneticAlgorit... |
thalees__kotlin-code-challenges__3b499d2/9_nine/FallingBlocks.kt | import java.util.*
private class Block(val l: Int, val r: Int) : Comparable<Block> {
fun cover(c: Block) = l <= c.l && r >= c.r
override fun compareTo(other: Block): Int = l.compareTo(other.l)
}
fun main() {
val (n, d) = readLine()!!.split(" ").map { it.toInt() }
val bh = arrayOfNulls<TreeSet<Block>>(n + 1) // blocks by height
// Segment tree
val tt = BooleanArray(4 * d) // terminal(leaf) node in segment tree
val th = IntArray(4 * d) // max height in this segment
tt[0] = true
// Segment tree functions
fun findMax(b: Block, i: Int, tl: Int, tr: Int): Int {
if (tt[i] || b.l <= tl && b.r >= tr) return th[i]
val tm = (tl + tr) / 2
return maxOf(
if (b.l <= tm) findMax(b, 2 * i + 1, tl, tm) else 0,
if (b.r > tm) findMax(b, 2 * i + 2, tm + 1, tr) else 0
)
}
fun setLeaf(i: Int, h: Int) {
tt[i] = true
th[i] = h
}
fun place(b: Block, h: Int, i: Int, tl: Int, tr: Int) {
if (b.l <= tl && b.r >= tr) return setLeaf(i, h)
val tm = (tl + tr) / 2
val j1 = 2 * i + 1
val j2 = 2 * i + 2
if (tt[i]) { // split node
tt[i] = false
setLeaf(j1, th[i])
setLeaf(j2, th[i])
}
if (b.l <= tm) place(b, h, j1, tl, tm)
if (b.r > tm) place(b, h, j2, tm + 1, tr)
th[i] = maxOf(th[j1], th[j2])
}
// Simulate each incoming block & print answer
var bc = 0
repeat(n) {
val b = readLine()!!.split(" ").map { it.toInt() }.let{ (l, r) -> Block(l, r) }
var maxH = findMax(b, 0, 1, d)
while (true) {
val bs = bh[maxH] ?: break
var floor = bs.floor(b)
if (floor != null && floor.r < b.l) floor = bs.higher(floor)
if (floor == null) floor = bs.first()
check(floor.l <= b.r)
val list = bs.tailSet(floor).takeWhile { it.l <= b.r }
if (!b.cover(list.first()) || !b.cover(list.last())) break
for (c in list) bs -= c // don't use bs.removeAll(list)
bc -= list.size
maxH--
}
val h = maxH + 1
place(b, h, 0, 1, d)
val bs = bh[h] ?: run { TreeSet<Block>().also { bh[h] = it } }
bs += b
println(++bc)
}
}
| [
{
"class_path": "thalees__kotlin-code-challenges__3b499d2/FallingBlocksKt.class",
"javap": "Compiled from \"FallingBlocks.kt\"\npublic final class FallingBlocksKt {\n public static final void main();\n Code:\n 0: invokestatic #12 // Method kotlin/io/ConsoleKt.readLine:()Ljava/lang... |
thalees__kotlin-code-challenges__3b499d2/8_eight/PaintString.kt | fun main() {
class Ans(val a: String, val m: String)
repeat(readLine()!!.toInt()) {
val s = readLine()!!
val n = s.length
val dp = Array(n) { i -> arrayOfNulls<Ans>(i + 1) }
dp[0][0] = Ans(s.substring(0, 1), "R")
var best = Ans(s, "")
fun updateBest(p: Ans) {
if (p.a <= best.a) best = p
}
fun updateDP(i: Int, j: Int, p: Ans) {
val cur = dp[i][j]
if (cur == null || p.a < cur.a) dp[i][j] = p
}
for (i in 1 until n) {
for (j in 0 until i) {
val p = dp[i - 1][j] ?: continue
updateDP(i, j, Ans(p.a + s[i], p.m + "R"))
if (j >= i - j) continue
if (s[i] == p.a[j]) updateDP(i, j + 1, Ans(p.a, p.m + "B"))
if (s[i] < p.a[j]) updateBest(Ans(p.a, p.m + "B".repeat(n - i)))
}
}
for (p in dp[n - 1]) if (p != null) updateBest(p)
println(best.m)
}
}
| [
{
"class_path": "thalees__kotlin-code-challenges__3b499d2/PaintStringKt$main$Ans.class",
"javap": "Compiled from \"PaintString.kt\"\npublic final class PaintStringKt$main$Ans {\n private final java.lang.String a;\n\n private final java.lang.String m;\n\n public PaintStringKt$main$Ans(java.lang.String, ja... |
thalees__kotlin-code-challenges__3b499d2/6_six/MovieFan.kt | import java.util.*
fun main() {
repeat(readLine()!!.toInt()) {
// readLine() // skip empty line
solveCase()
}
}
private data class Mv(val i: Int, val a: Int, val b: Int, var t: Int = 0) : Comparable<Mv> {
override fun compareTo(other: Mv): Int = if (b != other.b) b.compareTo(other.b) else i.compareTo(other.i)
}
private fun solveCase() {
val (n, m) = readLine()!!.split(" ").map { it.toInt() }
val d = Array(n) { i ->
readLine()!!.split(" ").map { it.toInt() }.let { (a, b) -> Mv(i, a, b) }
}
d.sortBy { it.a }
var t = 0
val w = TreeSet<Mv>()
fun advance(to: Int) {
while (t < to && !w.isEmpty()) {
repeat(minOf(w.size, m)) {
val v = w.first()
v.t = t
w -= v
}
t++
}
t = to
}
for (v in d) {
advance(v.a)
w += v
}
advance(Int.MAX_VALUE)
d.sortBy { it.i }
println(maxOf(0, d.map { it.t - it.b }.max()!!))
println(d.joinToString(" ") { it.t.toString() })
}
| [
{
"class_path": "thalees__kotlin-code-challenges__3b499d2/MovieFanKt$solveCase$$inlined$sortBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class MovieFanKt$solveCase$$inlined$sortBy$1<T> implements java.util.Comparator {\n public MovieFanKt$solveCase$$inlined$sortBy$1();\n Code:\n... |
thalees__kotlin-code-challenges__3b499d2/7_seven/MNumbers.kt | fun main() {
val (m, k) = readLine()!!.split(" ").map { it.toInt() }
val f = factor(m) ?: run {
println(-1)
return
}
val dp = HashMap<Long,Long>()
val dig = IntArray(100_000)
fun count(nd: Int, p: Long = -1): Long {
val e = f[0] + (f[1] shl 5) + (f[2] shl 10) + (f[3] shl 15) + (nd.toLong() shl 20)
if (nd == 0) return if (e == 0L) 1 else 0
if (p == -1L) dp[e]?.let { return it }
var cnt = 0L
for (d in 1..9) {
dig[nd - 1] = d
val df = factors[d]
for (i in 0..3) f[i] -= df[i]
if (f.all { it >= 0 }) {
val nc = count(nd - 1)
if (p >= 0 && cnt + nc > p) return count(nd - 1, p - cnt)
cnt += nc
}
for (i in 0..3) f[i] += df[i]
}
dp[e] = cnt
return cnt
}
var num = 1L
var nd = 1
while (count(nd) <= k - num) num += count(nd++)
check(count(nd, k - num) == 1L)
println(dig.take(nd).reversed().joinToString(""))
}
private val pr = listOf(2, 3, 5, 7)
private val factors = Array(10) { factor(it)!! }
private fun factor(m: Int): IntArray? {
val f = IntArray(4)
if (m <= 1) return f
var rem = m
for ((i, p) in pr.withIndex()) {
while (rem % p == 0) {
rem /= p
f[i]++
}
}
return f.takeIf { rem == 1 }
}
| [
{
"class_path": "thalees__kotlin-code-challenges__3b499d2/MNumbersKt.class",
"javap": "Compiled from \"MNumbers.kt\"\npublic final class MNumbersKt {\n private static final java.util.List<java.lang.Integer> pr;\n\n private static final int[][] factors;\n\n public static final void main();\n Code:\n ... |
philipphofmann__coding-problems__db0889c/src/LongestUniqueSubSequence.kt | /**
* Returns the longest subsequence with unique character.
*/
fun longestUniqueSubSequence(value: String): String {
var longestUniqueSubSequence = ""
value.forEachIndexed { index, _ ->
val uniqueSubsequence = uniqueSubSequence(value.subSequence(index, value.length))
if (longestUniqueSubSequence.length < uniqueSubsequence.length) {
longestUniqueSubSequence = uniqueSubsequence
}
}
return longestUniqueSubSequence
}
private fun uniqueSubSequence(sequence: CharSequence): String {
var uniqueSubSequence = ""
sequence.forEach { char ->
if (!uniqueSubSequence.contains(char)) {
uniqueSubSequence += char
} else {
return uniqueSubSequence
}
}
return uniqueSubSequence
}
| [
{
"class_path": "philipphofmann__coding-problems__db0889c/LongestUniqueSubSequenceKt.class",
"javap": "Compiled from \"LongestUniqueSubSequence.kt\"\npublic final class LongestUniqueSubSequenceKt {\n public static final java.lang.String longestUniqueSubSequence(java.lang.String);\n Code:\n 0: aloa... |
philipphofmann__coding-problems__db0889c/src/Atoi.kt | /**
* Parses the string as an [Int] number and returns the result.
* See https://leetcode.com/problems/string-to-integer-atoi/
*
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
fun atoi(string: String): Int {
val noWhitespaces = string.trim { it.isWhitespace() }
if (!isDigit(noWhitespaces[0])) {
return 0
}
val digitsAndNegativeSign = noWhitespaces.trim { char -> !isDigit(char) || char == '+' }
val isNegative = digitsAndNegativeSign[0] == '-'
val digits = if (isNegative) {
digitsAndNegativeSign.removeRange(0, 1)
} else {
digitsAndNegativeSign
}
var result = 0
var exponent = 1.0
var overflow = false
for (i in digits.length - 1 downTo 0) {
val digitValue = (charToInt(digits[i]) * exponent).toInt()
val r = result + digitValue
// HD 2-12 Overflow if both arguments have the opposite sign of r
if (result xor r and (digitValue xor r) < 0) {
overflow = true
break
}
result = r
exponent *= 10
}
result = if (isNegative) -result else result
return if (overflow) {
if (result < 0) {
Int.MIN_VALUE
} else {
Int.MAX_VALUE
}
} else {
result
}
}
private fun isDigit(char: Char) = charToInt(char) >= 0 || char == '-' || char == '+'
private fun charToInt(char: Char): Int {
return when (char) {
'0' -> 0
'1' -> 1
'2' -> 2
'3' -> 3
'4' -> 4
'5' -> 5
'6' -> 6
'7' -> 7
'8' -> 8
'9' -> 9
else -> Int.MIN_VALUE
}
}
| [
{
"class_path": "philipphofmann__coding-problems__db0889c/AtoiKt.class",
"javap": "Compiled from \"Atoi.kt\"\npublic final class AtoiKt {\n public static final int atoi(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 // String string\n 3: invokestatic #1... |
guilhermealbm__ManualFlashSettingsCalculator__74f049d/src/main/kotlin/CalculateAperture.kt | import java.lang.NumberFormatException
import kotlin.math.abs
val distances = listOf(1.2, 1.8, 2.5, 3.5, 5.0, 7.0)
val apertures = listOf(1.2, 1.4, 2, 2.8, 4, 5.6, 8, 11, 16, 22, 32, 45)
fun calculateAperture(iso_: String?, distance_: String?) : String {
val iso = convertIso(iso_)
val distance = convertDistance(distance_)
distance?.let {
val distanceIndex = distances.reversed().indexOf(it)
val isoIndex = iso.index
return "Set your aperture to ${apertures[distanceIndex + isoIndex]}"
} ?: run {
return "Unable to convert distance."
}
}
fun convertDistance(distance_: String?) : Double? =
try {
distance_?.toDouble()?.let {
distances.closestValue(it)
} ?: run {
null
}
} catch (exception: NumberFormatException) {
null
}
private fun List<Double>.closestValue(value: Double) = minByOrNull { abs(value - it) }
fun convertIso(iso: String?) : ISO =
when(iso?.trim()) {
"25" -> ISO.I25
"50" -> ISO.I50
"100" -> ISO.I100
"200" -> ISO.I200
"400" -> ISO.I400
"800" -> ISO.I800
"1000" -> ISO.I1000
else -> ISO.I100
}
enum class ISO(val index: Int) {
I25(0),
I50(1),
I100(2),
I200(3),
I400(4),
I800(5),
I1000(6)
}
| [
{
"class_path": "guilhermealbm__ManualFlashSettingsCalculator__74f049d/CalculateApertureKt.class",
"javap": "Compiled from \"CalculateAperture.kt\"\npublic final class CalculateApertureKt {\n private static final java.util.List<java.lang.Double> distances;\n\n private static final java.util.List<java.lang... |
charlottemach__adventofcode__dc83994/2021/five.kt | import java.io.File
import kotlin.math.abs
fun main() {
val input = File("five.txt").readText()
val coord = input.trim().split("\n").map{ it.split(" -> ")}
val mat = Array(1000) {Array(1000) {0} }
//val mat = Array(10) {Array(10) {0} }
for (c in coord) {
val start = c.first().split(","); val stop = c.last().split(",")
val x1 = start.first().toInt(); val y1 = start.last().toInt()
val x2 = stop.first().toInt(); val y2 = stop.last().toInt()
if (x1 == x2) {
val mnY = minOf(y1,y2); val mxY = maxOf(y1,y2)
for (y in mnY..mxY) {
mat[y][x1] += 1
}
} else if (y1 == y2) {
val mnX = minOf(x1,x2); val mxX = maxOf(x1,x2)
for (x in mnX..mxX) {
mat[y1][x] += 1
}
// Part B
} else {
for (i in 0..abs(x1-x2)) {
if (y1 < y2) {
if (x1 < x2) {
mat[y1 + i][x1 + i] += 1
} else {
mat[y1 + i][x1 - i] += 1
}
} else {
if (x1 < x2) {
mat[y1 - i][x1 + i] += 1
} else {
mat[y1 - i][x1 - i] += 1
}
}
}
}
}
//mPrint(mat)
print(mCount(mat))
}
fun mPrint(mat: Array<Array<Int>>) {
for (array in mat) {
for (value in array) {
print(value)
}
println()
}
}
fun mCount(mat: Array<Array<Int>>) : Int {
var count = 0
for (array in mat) {
for (value in array) {
if (value >= 2){
count += 1
}
}
}
return(count)
}
| [
{
"class_path": "charlottemach__adventofcode__dc83994/FiveKt.class",
"javap": "Compiled from \"five.kt\"\npublic final class FiveKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
charlottemach__adventofcode__dc83994/2023/11/eleven.kt | import java.io.File
import java.math.BigInteger
import java.util.Collections
fun main() {
val input = File("input.txt").readText()
println(cosmicExpansion(input,2))
println(cosmicExpansion(input,1000000))
}
fun cosmicExpansion(input: String, times: Int):BigInteger{
var lines = input.split("\n").dropLast(1)
var n = lines.size
var map = Array(n) {Array(n) {""} }
var galaxies = arrayOf<Pair<Int,Int>>()
for (y in 0..n-1) {
val line = lines[y].split("").drop(1).dropLast(1)
for (x in 0..n-1) {
var v = line[x]
map[y][x] = v
if (v == "#") {
galaxies += Pair(x,y)
}
}
}
//pprint(map)
var distSum = 0.toBigInteger()
var (xs,ys) = getExpandLines(map,n)
for (gi in 0..galaxies.size) {
for (gj in gi+1..galaxies.size-1) {
var p1 = galaxies[gi]
var p2 = galaxies[gj]
distSum += getDist(p1,p2,xs,ys,times)
}
}
return distSum
}
fun getDist(p1:Pair<Int,Int>, p2:Pair<Int,Int>, xs:Array<Int>, ys: Array<Int>, times:Int):BigInteger {
var (x1,y1) = p1
var (x2,y2) = p2
var dist = Math.abs(x2-x1) + Math.abs(y2-y1)
if (x1 < x2) {
x2 = x1.apply{x1 = x2}
}
if (y1 < y2) {
y2 = y1.apply{y1 = y2}
}
var cnt = 0
for (xx in x2..x1) {
if (xs.any({x -> x==xx})) {
cnt += 1
}
}
for (yy in y2..y1) {
if (ys.any({y -> y==yy})) {
cnt += 1
}
}
return dist.toBigInteger() + (cnt.toBigInteger() * (times-1).toBigInteger())
}
fun getExpandLines(map:Array<Array<String>>, n:Int):Pair<Array<Int>,Array<Int>> {
var ys = arrayOf<Int>()
for (x in 0..n-1) {
var col = arrayOf<String>()
for (y in 0..n-1) {
col += map[y][x]
}
if (col.all({y -> y=="."})) {
ys += x
}
}
var xs = arrayOf<Int>()
for (x in 0..n-1) {
if (map[x].all({x -> x!="#"})) {
xs += x
}
}
return Pair(ys,xs)
}
fun pprint(map: Array<Array<String>>) {
for (line in map) {
for (l in line) {
print(l)
}
print("\n")
}
}
| [
{
"class_path": "charlottemach__adventofcode__dc83994/ElevenKt.class",
"javap": "Compiled from \"eleven.kt\"\npublic final class ElevenKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ... |
skrim__AdventOfCode__0e7f425/2021/19/program.kt | data class Coordinate(val x: Int, val y: Int, val z: Int) {
fun add(other: Coordinate) : Coordinate = Coordinate(x + other.x, y + other.y, z + other.z)
fun subtract(other: Coordinate) : Coordinate = Coordinate(x - other.x, y - other.y, z - other.z)
fun manhattanDistance(other: Coordinate) : Int = Math.abs(x - other.x) + Math.abs(y - other.y) + Math.abs(z - other.z)
private fun getHeading(heading: Int) : Coordinate {
when (heading) { // heading
0 -> return Coordinate(x, y, z)
1 -> return Coordinate(-y, x, z)
2 -> return Coordinate(-x, -y, z)
3 -> return Coordinate(y, -x, z)
4 -> return Coordinate(-z, y, x)
5 -> return Coordinate(z, y, -x)
else -> throw Exception("Wut")
}
}
private fun getRotation(rotation: Int) : Coordinate {
when (rotation) { // rotation
0 -> return Coordinate(x, y, z);
1 -> return Coordinate(x, -z, y);
2 -> return Coordinate(x, -y, -z);
3 -> return Coordinate(x, z, -y);
else -> throw Exception("Wut")
}
}
fun transform(direction: Int) : Coordinate = getHeading(direction / 4).getRotation(direction % 4)
}
class Scanner() {
var coordinates: MutableList<Coordinate> = mutableListOf<Coordinate>()
var position: Coordinate = Coordinate(0, 0, 0)
fun getRotatedCoordinates(rotation: Int, delta: Coordinate) : MutableList<Coordinate> =
coordinates.map({ it.transform(rotation).subtract(delta) }).toMutableList()
fun normalize(rotation: Int, delta: Coordinate) {
coordinates = getRotatedCoordinates(rotation, delta)
position = Coordinate(0, 0, 0).subtract(delta)
}
}
class Program {
var pendingLocation : MutableList<Scanner> = mutableListOf<Scanner>()
var pendingCompare : MutableList<Scanner> = mutableListOf<Scanner>()
var completed : MutableList<Scanner> = mutableListOf<Scanner>()
fun load() {
var first = true
var current : Scanner = Scanner()
pendingCompare.add(current)
java.io.File("input.txt").forEachLine {
if (it.startsWith("---")) {
if (!first) {
current = Scanner()
pendingLocation.add(current)
}
first = false
} else if (!it.isNullOrEmpty()) {
val tokens = it.split(",")
current.coordinates.add(Coordinate(tokens[0].toInt(), tokens[1].toInt(), tokens[2].toInt()))
}
}
}
fun iterate() {
val first = pendingCompare[0]
var i = 0
while (i < pendingLocation.count()) {
val second = pendingLocation[i]
var found = false
var fi = 0
while (!found && fi < first.coordinates.count()) {
val c1 = first.coordinates[fi++]
var si = 0
while (!found && si < second.coordinates.count()) {
val c2 = second.coordinates[si++]
for (rotation in 0..23) {
val tc2 = c2.transform(rotation)
val delta = tc2.subtract(c1)
var matchAttempt = second.getRotatedCoordinates(rotation, delta)
var result = first.coordinates.intersect(matchAttempt)
if (result.count() == 12) {
second.normalize(rotation, delta)
found = true
}
}
}
}
if (found) {
pendingLocation.removeAt(i)
pendingCompare.add(second)
} else {
i++
}
}
pendingCompare.removeAt(0)
completed.add(first)
}
fun coordinateCount() : Int = completed.flatMap { it.coordinates }.distinct().count()
fun maxDistance() : Int {
var result = 0
completed.forEach { first ->
completed.forEach { second ->
result = Math.max(result, first.position.manhattanDistance(second.position))
}
}
return result
}
fun run() {
load()
while (pendingLocation.count() + pendingCompare.count() > 0) iterate()
println("Part 1: ${coordinateCount()}")
println("Part 2: ${maxDistance()}")
}
}
fun main() = Program().run() | [
{
"class_path": "skrim__AdventOfCode__0e7f425/ProgramKt.class",
"javap": "Compiled from \"program.kt\"\npublic final class ProgramKt {\n public static final void main();\n Code:\n 0: new #8 // class Program\n 3: dup\n 4: invokespecial #11 // M... |
A1rPun__nurture__295de6a/language/kotlin/fib.kt | import kotlin.math.pow
import kotlin.math.round
fun fib(n: Int): Int {
return if (n < 2) n else fib(n - 1) + fib(n - 2)
}
fun fibLinear(n: Int): Int {
var prevFib = 0
var fib = 1
repeat(n) {
val temp = prevFib + fib
prevFib = fib
fib = temp
}
return prevFib
}
fun fibFormula(n: Int): Int {
return round((((5.0.pow(0.5) + 1) / 2.0).pow(n)) / 5.0.pow(0.5)).toInt();
}
fun fibTailRecursive(n: Int, prevFib: Int = 0, fib: Int = 1): Int {
return if (n == 0) prevFib else fibTailRecursive(n - 1, fib, prevFib + fib)
}
fun fibonacciGenerate(n: Int): List<Int> {
var a = 0
var b = 1
fun next(): Int {
val result = a + b
a = b
b = result
return a
}
return generateSequence(::next).take(n).toList()
}
fun main(args: Array<String>) {
var input = if (args.size > 0) args[0].toInt() else 29
println(fibLinear(input))
}
| [
{
"class_path": "A1rPun__nurture__295de6a/FibKt.class",
"javap": "Compiled from \"fib.kt\"\npublic final class FibKt {\n public static final int fib(int);\n Code:\n 0: iload_0\n 1: iconst_2\n 2: if_icmpge 9\n 5: iload_0\n 6: goto 22\n 9: iload_0\n 10... |
a-red-christmas__aoc2017-kt__14e50f4/src/star05.kt | import java.lang.Math.abs
import java.lang.Math.pow
import kotlin.math.roundToInt
import kotlin.math.sqrt
fun main(args: Array<String>) {
println(findManhattanDistance(368078))
}
fun findManhattanDistance(start: Int) : Int {
val size = getSpiralArraySize(start)
val center = getSpiralArrayCenter(size) // q1, q2 == center, center
val last = (pow((size).toDouble(), 2.0)).toInt()
val bottomLeft = last - size + 1
val topLeft = bottomLeft - size + 1
val topRight = topLeft - size + 1
/*
1,1 ... size,1
.
.
.
1,size ... size,size
*/
val location = when {
start >= bottomLeft -> Pair(size - (last - start), size)
start >= topLeft -> Pair(1, size - (bottomLeft - start))
start >= topRight -> Pair(topLeft - start + 1, 1)
else -> Pair(size, topRight - start + 1)
}
return abs(location.first - center) + abs(location.second - center)
}
fun getSpiralArrayCenter(size: Int): Int {
val center = roundUp(size / 2.0) // q1, q2 == center, center
return center
}
fun getSpiralArraySize(start: Int): Int {
val sqrtStart = roundUp(sqrt(start.toDouble()))
val size = if (sqrtStart % 2 == 0) sqrtStart + 1 else sqrtStart
return size
}
fun roundUp(num : Double) : Int {
val rounded = num.roundToInt()
return if (num > rounded) rounded + 1 else rounded
}
| [
{
"class_path": "a-red-christmas__aoc2017-kt__14e50f4/Star05Kt.class",
"javap": "Compiled from \"star05.kt\"\npublic final class Star05Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic ... |
iproduct__course-kotlin__89884f8/03-problems-lab1/src/main/kotlin/Main.kt | import java.io.File
data class LongNumberProblem(
var n: Int,
var a: String,
var fm: List<Int>,
)
fun main(args: Array<String>) {
// read input
// val n = readLine()!!.toInt()
// val a = readLine()!!
// val fm = readLine()!!.split(" ").map { it.toInt() }
// read input from file
// Using BufferedReader
val bf = File("./long-number01.txt").bufferedReader()
val problems = mutableListOf<LongNumberProblem>()
var i = 0
var n: Int = 0
var a: String = ""
var fm: List<Int> = emptyList()
bf.forEachLine {
when (i++ % 3) {
0 -> n = it.toInt()
1 -> a = it
2 -> {
fm = it.split(" ").map { c -> c.toInt() }
problems.add(LongNumberProblem(n, a, fm))
}
}
}
// bf.useLines { lines ->
// lines.forEach {
// when (i++ % 3) {
// 0 -> n = it.toInt()
// 1 -> a = it
// 2 -> {
// fm = it.split(" ").map { c -> c.toInt() }
// problems.add(LongNumberProblem(n, a, fm))
// }
// }
// }
// }
for (p in problems) {
println(solveLongNumber(p))
}
}
private fun solveLongNumber(problem: LongNumberProblem): String {
fun f(c: Char) = '0' + problem.fm[c - '1']
// greedy maximum search
val s = problem.a.indexOfFirst { f(it) > it }
.takeIf { it >= 0 } ?: problem.a.length
val e = problem.a.withIndex().indexOfFirst { (i, c) -> i > s && f(c) < c }
.takeIf { it >= 0 } ?: problem.a.length
val result = problem.a.slice(0 until s) +
problem.a.slice(s until e).map { f(it) }.joinToString("") +
problem.a.slice(e until problem.a.length)
return result
}
| [
{
"class_path": "iproduct__course-kotlin__89884f8/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic #15 ... |
julianferres__Codeforces__14e8369/Kotlin Heroes 6 -Practice/G.kt | data class Edge(val from: Int, val to: Int, val cost: Long)
class DSU(val n: Int){
var par: MutableList<Int> = MutableList<Int>(n){ it }
var sz: MutableList<Int> = MutableList<Int>(n){ 1 }
fun find(x: Int): Int {
if(par[x] != x) par[x] = find(par[x])
return par[x]
}
fun join(ii: Int, jj: Int): Boolean{
var i=find(ii); var j=find(jj);
if(i == j) return false;
if(sz[i] < sz[j]){
run { val temp = i; i = j; j = temp }
}
sz[i] += sz[j];
par[j] = i;
return true
}
}
fun main() {
var (n, m) = readLine()!!.split(" ").map { it.toInt() }
var a = readLine()!!.split(" ").map { it.toLong() }
var mindex = a.indexOf(a.minBy{ it })
var edges = mutableListOf<Edge>()
repeat(m){
var line = readLine()!!.split(" ")
var from = line[0].toInt()
var to = line[1].toInt()
var cost = line[2].toLong()
edges.add(Edge(from-1, to-1, cost))
}
for (i in 0 until n){
edges.add(Edge(i, mindex, a[mindex] + a[i]))
}
edges.sortWith(compareBy {it.cost})
var dsu = DSU(n)
var ans = 0L
for(edge in edges){
if(dsu.find(edge.from) == dsu.find(edge.to)) continue
else{
ans += edge.cost
dsu.join(edge.from, edge.to)
}
}
println(ans)
}
| [
{
"class_path": "julianferres__Codeforces__14e8369/GKt$main$$inlined$compareBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class GKt$main$$inlined$compareBy$1<T> implements java.util.Comparator {\n public GKt$main$$inlined$compareBy$1();\n Code:\n 0: aload_0\n 1: invok... |
charlesfranciscodev__codingame__3ec8060/puzzles/kotlin/src/war/war.kt | import java.util.Scanner
import kotlin.system.exitProcess
fun main(args : Array<String>) {
val game = Game()
game.play()
}
/**
* Represents the result of one game turn:
* PLAYER1 if player 1 wins this round,
* PLAYER2 if player 2 wins this round,
* WAR if the two cards played are of equal value
* */
enum class Result {
PLAYER1,
PLAYER2,
WAR
}
class Card(val value: String, val suit: String) : Comparable<Card> {
companion object {
val intValues: HashMap<String, Int> = hashMapOf(
"2" to 2, "3" to 3, "4" to 4, "5" to 5, "6" to 6, "7" to 7, "8" to 8, "9" to 9, "10" to 10,
"J" to 11, "Q" to 12, "K" to 13, "A" to 14
)
}
override fun compareTo(other: Card): Int {
val value1 = intValues.getOrDefault(value, 0)
val value2 = intValues.getOrDefault(other.value, 0)
return value1 - value2
}
}
class Game {
val input = Scanner(System.`in`)
var deck1 = readGameInput()
var deck2 = readGameInput()
var nbRounds = 0
fun readGameInput(): List<Card> {
val n = input.nextInt() // the number of cards for the player
val cards = ArrayList<Card>(n)
for (i in 0 until n) {
val valueSuit = input.next()
val value = valueSuit.substring(0, valueSuit.length - 1)
val suit = valueSuit.substring(valueSuit.length - 1)
cards.add(Card(value, suit))
}
return cards
}
fun play() {
var index = 0
while (true) {
val result = playTurn(index)
val rotateIndex = index + 1
if (result == Result.PLAYER1) {
nbRounds++
deck1 = rotate(deck1, rotateIndex)
deck1 += deck2.take(rotateIndex) // take other player's cards
deck2 = deck2.drop(rotateIndex) // remove other player's cards
index = 0
} else if (result == Result.PLAYER2) {
nbRounds++
deck2 += deck1.take(rotateIndex) // take other player's cards
deck1 = deck1.drop(rotateIndex) // remove other player's cards
deck2 = rotate(deck2, rotateIndex)
index = 0
} else {
// WAR
index += 4
}
}
}
fun rotate(deck: List<Card>, index: Int): List<Card> {
return deck.drop(index) + deck.take(index)
}
/** Returns the result of one game turn */
fun playTurn(index: Int): Result {
if (index > deck1.size || index > deck2.size) {
println("PAT")
exitProcess(0)
}
checkGameOver()
val card1 = deck1[index]
val card2 = deck2[index]
return when {
card2 < card1 -> Result.PLAYER1
card1 < card2 -> Result.PLAYER2
else -> Result.WAR
}
}
fun checkGameOver() {
if (deck1.isEmpty()) {
println("2 $nbRounds")
exitProcess(0)
}
if (deck2.isEmpty()) {
println("1 $nbRounds")
exitProcess(0)
}
}
}
| [
{
"class_path": "charlesfranciscodev__codingame__3ec8060/WarKt.class",
"javap": "Compiled from \"war.kt\"\npublic final class WarKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic #15 ... |
charlesfranciscodev__codingame__3ec8060/puzzles/kotlin/src/surface/surface.kt | import java.util.Scanner
import java.util.ArrayDeque
const val LAND = '#'
const val WATER = 'O'
const val DEFAULT_INDEX = -1
fun main(args : Array<String>) {
val grid = Grid()
grid.readGameInput()
grid.test()
}
data class Square(val x: Int, val y: Int, val terrain: Char, var lakeIndex: Int = DEFAULT_INDEX)
class Grid {
val input = Scanner(System.`in`)
var width = 0
var height = 0
val nodes = ArrayList<List<Square>>()
val lakes = HashMap<Int, Int>() // lake_index -> surface area
fun readGameInput() {
width = input.nextInt()
height = input.nextInt()
if (input.hasNextLine()) {
input.nextLine()
}
for (y in 0 until height) {
val row = input.nextLine().withIndex().map { Square(it.index, y, it.value) }
nodes.add(row)
}
}
fun test() {
val n = input.nextInt()
for (i in 0 until n) {
val x = input.nextInt()
val y = input.nextInt()
println(area(x, y))
}
}
fun area(x: Int, y: Int): Int {
val node = nodes[y][x]
if (node.terrain == LAND) {
return 0
}
if (node.lakeIndex == DEFAULT_INDEX) {
floodFill(node)
}
return lakes.getOrDefault(node.lakeIndex, 0)
}
// Source https://en.wikipedia.org/wiki/Flood_fill
fun floodFill(start: Square) {
val queue = ArrayDeque<Square>()
var totalArea = 0
start.lakeIndex = start.y * width + start.x
queue.add(start)
while (!queue.isEmpty()) {
totalArea++
val current = queue.poll()
fillNeighbors(queue, current, start.lakeIndex)
}
lakes.put(start.lakeIndex, totalArea)
}
fun fillNeighbors(queue: ArrayDeque<Square>, square: Square, lakeIndex: Int) {
if (square.x + 1 < width) {
val rightNeighbor = nodes[square.y][square.x + 1]
fill(queue, rightNeighbor, lakeIndex)
}
if (square.x > 0) {
val leftNeighbor = nodes[square.y][square.x - 1]
fill(queue, leftNeighbor, lakeIndex)
}
if (square.y + 1 < height) {
val downNeighbor = nodes[square.y + 1][square.x]
fill(queue, downNeighbor, lakeIndex)
}
if (square.y > 0) {
val upNeighbor = nodes[square.y - 1][square.x]
fill(queue, upNeighbor, lakeIndex)
}
}
fun fill(queue: ArrayDeque<Square>, square: Square, lakeIndex: Int) {
if (square.terrain == WATER && square.lakeIndex == DEFAULT_INDEX) {
square.lakeIndex = lakeIndex
queue.add(square)
}
}
}
| [
{
"class_path": "charlesfranciscodev__codingame__3ec8060/SurfaceKt.class",
"javap": "Compiled from \"surface.kt\"\npublic final class SurfaceKt {\n public static final char LAND;\n\n public static final char WATER;\n\n public static final int DEFAULT_INDEX;\n\n public static final void main(java.lang.St... |
marc-bouvier-katas__Kotlin_EduTools_Advent_of_Code_2021__12cf74c/Day 5/Part 1/src/Task.kt | fun overlaps(ventsLines: Array<String>): Int {
val lines = Lines()
return if (ventsLines.size >= 2) {
repeat(ventsLines.size){
lines.mergeWith(Line.fromLineOfVent(LineOfVent.fromString(ventsLines[it])))
}
return lines.overlaps()
} else 0
}
data class Lines(private val data:MutableMap<Int,Line> = mutableMapOf()
){
fun mergeWith(line: Line){
data.merge(line.y,line,Line::mergeWith)
}
fun overlaps(): Int {
println(data)
return data.values.sumOf { it.overlaps() }
}
}
data class Line(val y: Int, private val xValues: Map<Int, Int> = mutableMapOf()) {
fun mergeWith(other:Line): Line {
val mergedXValues = xValues.toMutableMap()
other.xValues.forEach{
if(mergedXValues.containsKey(it.key)){
mergedXValues[it.key]=it.value+mergedXValues[it.key]!!
}else{
mergedXValues[it.key]=it.value
}
}
return Line(y, mergedXValues)
}
fun overlaps(): Int {
return xValues.values.count { it > 1 }
}
companion object{
fun fromLineOfVent(lineOfVent: LineOfVent):Line{
val xValues = mutableMapOf<Int, Int>()
(lineOfVent.x1 .. lineOfVent.x2).forEach{xValues[it]=1}
println("fromlineofvent: "+xValues)
return Line(lineOfVent.y1, xValues.toMap())
}
}
}
class LineOfVent(
val x1: Int,
val y1: Int,
val x2: Int,
val y2: Int
) {
fun numberOfOverlapsWith(other: LineOfVent): Int {
return if (!onTheSameYCoordinate(other))
0
else
arrayOf(this.x2, other.x2)
.minOrNull()!! - arrayOf(
this.x1,
other.x1
).maxOrNull()!! + 1
}
private fun onTheSameYCoordinate(other: LineOfVent) = this.y1 == other.y1
companion object {
fun fromString(string: String): LineOfVent {
val (left, right) = string.split(" -> ")
val (x1, y1) = left.split(",").map(String::toInt)
val (x2, y2) = right.split(",").map(String::toInt)
return LineOfVent(x1, y1, x2, y2)
}
}
}
| [
{
"class_path": "marc-bouvier-katas__Kotlin_EduTools_Advent_of_Code_2021__12cf74c/TaskKt.class",
"javap": "Compiled from \"Task.kt\"\npublic final class TaskKt {\n public static final int overlaps(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String vent... |
occmundial__Kotlin-Weekly-Challenge__f09ba0a/src/Challenge2.kt | /*
* Challenge #2
*
* Date: 15/08/2022
* Difficulty: Medium
* Create a function that translate from natural text to Morse code and vice versa.
* - Must be automatically detect what type it is and perform the conversion.
* - In Morse, dash "—", dot ".", a space " " between letters or symbols, and two spaces between words " " are supported.
* - The supported morse alphabet will be the one shown in https://es.wikipedia.org/wiki/Código_morse.
*/
lateinit var naturalDictionary: Map<String, String>
var morseDictionary = mutableMapOf<String, String>()
fun main() {
createDictionaries()
val naturalText = "<NAME>"
val morseText = ".... --- .-.. .- ---- . -.-. ---"
println(decoder(naturalText))
println(decoder(morseText))
}
private fun createDictionaries() {
naturalDictionary = mapOf(
"A" to ".-", "N" to "-.", "0" to "-----",
"B" to "-...", "Ñ" to "--.--", "1" to ".----",
"C" to "-.-.", "O" to "---", "2" to "..---",
"CH" to "----", "P" to ".--.", "3" to "...--",
"D" to "-..", "Q" to "--.-", "4" to "....-",
"E" to ".", "R" to ".-.", "5" to ".....",
"F" to "..-.", "S" to "...", "6" to "-....",
"G" to "--.", "T" to "-", "7" to "--...",
"H" to "....", "U" to "..-", "8" to "---..",
"I" to "..", "V" to "...-", "9" to "----.",
"J" to ".---", "W" to ".--", "." to ".-.-.-",
"K" to "-.-", "X" to "-..-", "," to "--..--",
"L" to ".-..", "Y" to "-.--", "?" to "..--..",
"M" to "--", "Z" to "--..", "\"" to ".-..-.", "/" to "-..-."
)
naturalDictionary.forEach {
morseDictionary[it.value] = it.key
}
}
private fun decoder(input: String): String {
var output = ""
if (input.contains(Regex("[a-zA-Z0-9]"))) {
// texto
output = getMorse(input)
} else if (input.contains(".") || input.contains("-")) {
// morse
output = getNatural(input)
}
return output
}
private fun getMorse(input: String): String {
var index = 0
var ch = false
var output = ""
input.uppercase().forEach { character ->
if (!ch && character.toString() != " ") {
val next = index + 1
if (character.toString() == "C" && next < input.length && input.uppercase()[next].toString() == "H") {
output += naturalDictionary["CH"]
ch = true
} else {
output += naturalDictionary[character.toString()]
}
output += " "
} else {
if (!ch) {
output += " "
}
ch = false
}
index++
}
return output
}
private fun getNatural(input: String): String {
var output = ""
input.split(" ").forEach { word ->
word.split(" ").forEach { symbol ->
if (symbol.isNotEmpty()) {
output += morseDictionary[symbol]
}
}
output += " "
}
return output
}
| [
{
"class_path": "occmundial__Kotlin-Weekly-Challenge__f09ba0a/Challenge2Kt.class",
"javap": "Compiled from \"Challenge2.kt\"\npublic final class Challenge2Kt {\n public static java.util.Map<java.lang.String, java.lang.String> naturalDictionary;\n\n private static java.util.Map<java.lang.String, java.lang.... |
sviams__aoc23__4914a54/src/main/kotlin/day2.kt | object day2 {
data class DrawSet(val red: Int, val green: Int, val blue: Int)
data class Game(val id: Int, val sets: List<DrawSet>) {
val power: Int by lazy { sets.maxOf { it.red } * sets.maxOf { it.blue } * sets.maxOf { it.green } }
fun withinLimit(r: Int, b: Int, g: Int): Boolean = sets.all { set ->
set.red <= r && set.blue <= b && set.green <= g
}
}
fun parseInput(input: List<String>): List<Game> = input.fold(emptyList()) { games, line ->
val (gameId) = Regex("""Game (\d+):""").find(line)!!.destructured
val drawSets = line.split(": ")[1].split(';').fold(emptyList<DrawSet>()) { drawSets, setString ->
val red = Regex("""(\d+) red""").find(setString)?.groupValues?.last()?.toInt() ?: 0
val blue = Regex("""(\d+) blue""").find(setString)?.groupValues?.last()?.toInt() ?: 0
val green = Regex("""(\d+) green""").find(setString)?.groupValues?.last()?.toInt() ?: 0
drawSets + DrawSet(red, green, blue)
}
games + Game(gameId.toInt(), drawSets)
}
fun pt1(input: List<String>): Int = parseInput(input).filter { it.withinLimit(12, 14, 13) }.sumOf { it.id }
fun pt2(input: List<String>): Int = parseInput(input).sumOf { it.power }
} | [
{
"class_path": "sviams__aoc23__4914a54/day2$DrawSet.class",
"javap": "Compiled from \"day2.kt\"\npublic final class day2$DrawSet {\n private final int red;\n\n private final int green;\n\n private final int blue;\n\n public day2$DrawSet(int, int, int);\n Code:\n 0: aload_0\n 1: invokespe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.