path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/10.kts | reitzig | 318,492,753 | false | null | import java.io.File
data class Joltage(val value: Int) : Comparable<Joltage> {
fun canTake(other: Joltage): Boolean =
value <= other.value + 3
override fun compareTo(other: Joltage): Int =
value.compareTo(other.value)
operator fun plus(difference: Int): Joltage =
Joltage(value + difference)
operator fun minus(other: Joltage): Int =
value - other.value
}
fun countWorkingArrangements(sortedJoltages: List<Joltage>): Long {
val countToEnd = Array<Long?>(sortedJoltages.size) { null }
countToEnd[sortedJoltages.lastIndex] = 1
for (i in (sortedJoltages.lastIndex - 1) downTo 0) {
var count = 0L
// Add together the counts for all possible next adapters
var next = i + 1
while (next <= sortedJoltages.lastIndex &&
sortedJoltages[next].canTake(sortedJoltages[i])
) {
count += countToEnd[next]!!
next += 1
}
countToEnd[i] = count
}
return countToEnd[0]!!
}
val joltages = File(args[0])
.readLines()
.map { Joltage(it.toInt()) }
.let { adapterJoltages ->
adapterJoltages +
listOf(Joltage(0),
adapterJoltages.maxOrNull()?.let { it + 3 })
.requireNoNulls()
}
.sorted()
// Part 1:
println(
joltages
.zipWithNext()
.map { it.second - it.first }
.groupBy({ it }, { 1 })
.mapValues { it.value.sum() }
.values
.reduce(Int::times)
)
// Part 2:
println(countWorkingArrangements(joltages))
| 0 | Kotlin | 0 | 0 | f17184fe55dfe06ac8897c2ecfe329a1efbf6a09 | 1,582 | advent-of-code-2020 | The Unlicense |
src/Day05.kt | mythicaleinhorn | 572,689,424 | false | {"Kotlin": 11494} | import java.util.*
fun main() {
fun parseInput(input: List<String>): List<Deque<Char>> {
val stacks = mutableListOf<Deque<Char>>()
val drawing = input.take(input.indexOf(""))
val n = drawing.last().trim()[drawing.last().trim().lastIndex].digitToInt()
repeat(n) {
stacks.add(ArrayDeque())
}
for (line in drawing.dropLast(1)) {
for ((x, i) in (1..line.length step 4).withIndex()) {
if (line[i] != ' ') {
stacks[x].addLast(line[i])
}
}
}
return stacks
}
fun part1(input: List<String>): String {
val stacks = parseInput(input)
val instructions = input.drop(input.indexOf("") + 1)
for (line in instructions) {
val quantity = line.split(' ')[1].toInt()
val from = line.split(' ')[3].toInt()
val to = line.split(' ')[5].toInt()
repeat(quantity) {
stacks[to - 1].push(stacks[from - 1].pop())
}
}
var result = ""
for (stack in stacks) {
result += stack.pop()
}
return result
}
fun part2(input: List<String>): String {
val stacks = parseInput(input)
val instructions = input.drop(input.indexOf("") + 1)
for (line in instructions) {
val quantity = line.split(' ')[1].toInt()
val from = line.split(' ')[3].toInt()
val to = line.split(' ')[5].toInt()
val elements = stacks[from - 1].take(quantity)
repeat(quantity) {
stacks[from - 1].removeFirst()
}
for (char in elements.asReversed()) {
stacks[to - 1].push(char)
}
}
var result = ""
for (stack in stacks) {
result += stack.pop()
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 959dc9f82c14f59d8e3f182043c59aa35e059381 | 2,220 | advent-of-code-2022 | Apache License 2.0 |
cz.wrent.advent/Day5.kt | Wrent | 572,992,605 | false | {"Kotlin": 206165} | package cz.wrent.advent
import java.util.*
fun main() {
val result = partOne(input)
println("5a: $result")
val resultTwo = partTwo(input)
println("5b: $resultTwo")
}
private fun partOne(input: String): String {
return moveCrates(input) { x, y, z -> moveCrates9000(x, y, z) }
}
private fun partTwo(input: String): String {
return moveCrates(input) { x, y, z -> moveCrates9001(x, y, z) }
}
private fun moveCrates(input: String, fn: (from: Deque<String>, to: Deque<String>, num: Int) -> Unit): String {
val (stacksInput, movesInput) = input.split("\n\n")
val stacks = stacksInput.toStacks()
val moves = movesInput.toMoves()
moves.forEach {
val from = stacks.get(it.from)
val to = stacks.get(it.to)
fn(from, to, it.num)
}
return stacks.map { it.peek() }.joinToString(separator = "")
}
private fun moveCrates9000(from: Deque<String>, to: Deque<String>, num: Int) {
repeat(num) {
val crate = from.pop()
to.push(crate)
}
}
private fun moveCrates9001(from: Deque<String>, to: Deque<String>, num: Int) {
val crates = mutableListOf<String>()
repeat(num) {
crates.add(from.pop())
}
crates.reversed().forEach { to.push(it) }
}
private fun String.toStacks(): List<Deque<String>> {
val split = this.split("\n").dropLast(1)
val cnt = (split.first().length + 1) / 4
val lists = (0 until cnt).map { mutableListOf<String>() }
for (row in split) {
var i = 1
var j = 0
while (i < row.length) {
val char = row[i]
if (char != ' ') {
lists.get(j).add(char.toString())
}
j++
i += 4
}
}
return lists.map {
it.toDeque()
}
}
private fun List<String>.toDeque(): Deque<String> {
return LinkedList(this)
}
private data class Move(val num: Int, val from: Int, val to: Int)
private fun String.toMoves(): List<Move> {
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
return this.split("\n")
.map { regex.matchEntire(it) }
.map { Move(it!!.groupValues.get(1).toInt(), it.groupValues.get(2).toInt() - 1, it.groupValues.get(3).toInt() - 1) }
}
private const val input = """[Q] [J] [H]
[G] [S] [Q] [Z] [P]
[P] [F] [M] [F] [F] [S]
[R] [R] [P] [F] [V] [D] [L]
[L] [W] [W] [D] [W] [S] [V] [G]
[C] [H] [H] [T] [D] [L] [M] [B] [B]
[T] [Q] [B] [S] [L] [C] [B] [J] [N]
[F] [N] [F] [V] [Q] [Z] [Z] [T] [Q]
1 2 3 4 5 6 7 8 9
move 1 from 8 to 1
move 1 from 6 to 1
move 3 from 7 to 4
move 3 from 2 to 9
move 11 from 9 to 3
move 1 from 6 to 9
move 15 from 3 to 9
move 5 from 2 to 3
move 3 from 7 to 5
move 6 from 9 to 3
move 6 from 1 to 6
move 2 from 3 to 7
move 5 from 4 to 5
move 7 from 9 to 4
move 2 from 9 to 5
move 10 from 4 to 2
move 6 from 5 to 4
move 2 from 7 to 6
move 10 from 2 to 3
move 21 from 3 to 5
move 1 from 3 to 6
move 3 from 6 to 9
move 1 from 8 to 9
move 5 from 4 to 5
move 4 from 9 to 3
move 17 from 5 to 1
move 1 from 6 to 2
move 16 from 5 to 1
move 3 from 3 to 6
move 6 from 6 to 4
move 1 from 2 to 4
move 4 from 1 to 2
move 2 from 6 to 2
move 28 from 1 to 3
move 1 from 9 to 7
move 1 from 8 to 7
move 1 from 5 to 4
move 1 from 2 to 6
move 1 from 3 to 1
move 3 from 2 to 5
move 1 from 6 to 3
move 4 from 4 to 7
move 5 from 5 to 2
move 1 from 5 to 6
move 6 from 1 to 3
move 1 from 6 to 2
move 26 from 3 to 6
move 2 from 7 to 9
move 4 from 7 to 3
move 19 from 6 to 3
move 6 from 2 to 4
move 5 from 3 to 2
move 1 from 9 to 7
move 26 from 3 to 8
move 6 from 4 to 3
move 1 from 3 to 8
move 1 from 6 to 7
move 6 from 3 to 6
move 6 from 6 to 4
move 1 from 9 to 2
move 2 from 4 to 9
move 22 from 8 to 2
move 2 from 6 to 5
move 1 from 9 to 1
move 1 from 6 to 5
move 1 from 7 to 5
move 3 from 6 to 7
move 2 from 6 to 1
move 1 from 1 to 5
move 3 from 5 to 9
move 4 from 8 to 4
move 2 from 1 to 4
move 18 from 2 to 1
move 2 from 7 to 8
move 3 from 9 to 5
move 8 from 1 to 9
move 5 from 9 to 3
move 1 from 9 to 8
move 2 from 9 to 4
move 2 from 7 to 8
move 5 from 5 to 7
move 1 from 9 to 3
move 4 from 8 to 4
move 1 from 7 to 8
move 4 from 4 to 3
move 2 from 8 to 3
move 1 from 8 to 9
move 2 from 1 to 8
move 3 from 4 to 5
move 1 from 8 to 4
move 1 from 9 to 3
move 1 from 8 to 5
move 8 from 1 to 8
move 11 from 2 to 9
move 12 from 3 to 5
move 1 from 3 to 9
move 1 from 8 to 5
move 11 from 9 to 3
move 4 from 5 to 9
move 3 from 8 to 7
move 3 from 7 to 8
move 1 from 5 to 8
move 7 from 4 to 3
move 1 from 4 to 5
move 1 from 2 to 8
move 3 from 7 to 6
move 3 from 4 to 8
move 1 from 7 to 9
move 2 from 4 to 7
move 5 from 8 to 1
move 3 from 6 to 5
move 2 from 4 to 2
move 1 from 9 to 4
move 1 from 8 to 6
move 1 from 2 to 9
move 1 from 8 to 5
move 3 from 8 to 4
move 3 from 4 to 2
move 4 from 3 to 9
move 17 from 5 to 9
move 9 from 9 to 6
move 1 from 9 to 3
move 5 from 6 to 3
move 3 from 6 to 3
move 8 from 9 to 5
move 2 from 8 to 5
move 1 from 4 to 8
move 1 from 5 to 3
move 1 from 8 to 5
move 3 from 2 to 6
move 3 from 1 to 4
move 7 from 5 to 1
move 1 from 2 to 6
move 13 from 3 to 6
move 2 from 7 to 8
move 13 from 6 to 5
move 3 from 5 to 7
move 6 from 5 to 6
move 1 from 7 to 6
move 2 from 7 to 3
move 1 from 6 to 8
move 13 from 3 to 5
move 9 from 5 to 9
move 7 from 5 to 7
move 17 from 9 to 2
move 3 from 4 to 7
move 9 from 2 to 9
move 10 from 9 to 3
move 8 from 7 to 8
move 2 from 5 to 3
move 4 from 2 to 6
move 11 from 3 to 9
move 9 from 6 to 5
move 5 from 9 to 8
move 1 from 3 to 1
move 3 from 9 to 1
move 2 from 5 to 2
move 1 from 7 to 9
move 2 from 9 to 4
move 2 from 9 to 8
move 13 from 1 to 8
move 3 from 8 to 5
move 27 from 8 to 1
move 10 from 5 to 9
move 1 from 7 to 2
move 2 from 4 to 3
move 10 from 9 to 6
move 1 from 8 to 7
move 15 from 1 to 9
move 13 from 9 to 5
move 15 from 5 to 7
move 5 from 1 to 3
move 8 from 7 to 1
move 7 from 7 to 1
move 16 from 1 to 8
move 4 from 3 to 9
move 4 from 1 to 7
move 4 from 9 to 6
move 5 from 2 to 7
move 15 from 8 to 6
move 1 from 9 to 1
move 3 from 3 to 4
move 1 from 9 to 7
move 1 from 2 to 7
move 1 from 2 to 7
move 1 from 8 to 1
move 3 from 4 to 8
move 3 from 8 to 1
move 8 from 6 to 8
move 7 from 1 to 4
move 11 from 6 to 8
move 14 from 6 to 5
move 13 from 8 to 7
move 4 from 7 to 5
move 15 from 7 to 4
move 6 from 5 to 4
move 2 from 5 to 9
move 1 from 5 to 2
move 3 from 8 to 5
move 19 from 4 to 7
move 10 from 5 to 8
move 2 from 6 to 8
move 1 from 4 to 8
move 2 from 7 to 9
move 9 from 7 to 4
move 6 from 4 to 6
move 11 from 4 to 8
move 2 from 5 to 4
move 5 from 6 to 4
move 1 from 6 to 7
move 3 from 9 to 5
move 3 from 8 to 5
move 3 from 7 to 6
move 11 from 8 to 7
move 1 from 9 to 5
move 1 from 6 to 8
move 1 from 2 to 1
move 5 from 4 to 9
move 2 from 4 to 1
move 2 from 1 to 4
move 1 from 1 to 9
move 4 from 5 to 1
move 1 from 4 to 6
move 17 from 7 to 5
move 9 from 8 to 7
move 6 from 9 to 7
move 3 from 1 to 9
move 12 from 7 to 9
move 12 from 9 to 5
move 5 from 7 to 9
move 17 from 5 to 3
move 7 from 3 to 1
move 5 from 1 to 5
move 5 from 9 to 2
move 4 from 3 to 5
move 1 from 4 to 8
move 5 from 2 to 1
move 22 from 5 to 9
move 3 from 7 to 6
move 6 from 6 to 9
move 2 from 5 to 4
move 1 from 6 to 3
move 2 from 4 to 1
move 3 from 8 to 2
move 1 from 3 to 4
move 24 from 9 to 1
move 4 from 3 to 9
move 2 from 2 to 9
move 2 from 3 to 1
move 1 from 8 to 6
move 1 from 6 to 9
move 1 from 8 to 9
move 2 from 7 to 4
move 1 from 8 to 3
move 1 from 4 to 7
move 3 from 9 to 8
move 1 from 2 to 1
move 9 from 9 to 3
move 1 from 8 to 7
move 1 from 4 to 3
move 2 from 9 to 7
move 1 from 9 to 3
move 2 from 8 to 4
move 12 from 3 to 8
move 2 from 1 to 7
move 1 from 4 to 3
move 30 from 1 to 5
move 6 from 5 to 7
move 12 from 7 to 2
move 1 from 3 to 4
move 2 from 1 to 3
move 1 from 4 to 9
move 10 from 5 to 7
move 10 from 2 to 6
move 8 from 8 to 3
move 3 from 1 to 3
move 5 from 6 to 3
move 2 from 8 to 5
move 1 from 9 to 2
move 2 from 8 to 6
move 4 from 7 to 2
move 3 from 2 to 7
move 2 from 7 to 5
move 1 from 4 to 9
move 11 from 3 to 1
move 7 from 6 to 9
move 3 from 2 to 3
move 10 from 1 to 7
move 14 from 7 to 5
move 3 from 7 to 6
move 5 from 9 to 7
move 29 from 5 to 7
move 6 from 3 to 9
move 2 from 9 to 7
move 15 from 7 to 5
move 11 from 5 to 6
move 5 from 9 to 5
move 10 from 5 to 8
move 1 from 2 to 4
move 1 from 8 to 2
move 2 from 4 to 3
move 2 from 5 to 9
move 8 from 8 to 9
move 11 from 9 to 3
move 1 from 1 to 8
move 18 from 7 to 3
move 1 from 9 to 3
move 28 from 3 to 5
move 12 from 6 to 7
move 1 from 2 to 9
move 15 from 7 to 2
move 1 from 8 to 1
move 10 from 2 to 9
move 10 from 5 to 3
move 2 from 2 to 3
move 18 from 3 to 4
move 6 from 9 to 4
move 1 from 1 to 7
move 1 from 6 to 4
move 1 from 8 to 2
move 1 from 9 to 4
move 2 from 9 to 4
move 19 from 4 to 3
move 1 from 7 to 9
move 1 from 9 to 7
move 1 from 6 to 8
move 3 from 2 to 8
move 2 from 9 to 5
move 15 from 3 to 1
move 7 from 5 to 1
move 3 from 4 to 9
move 1 from 7 to 2
move 3 from 3 to 1
move 6 from 5 to 2
move 3 from 3 to 9
move 4 from 9 to 2
move 5 from 5 to 3
move 1 from 3 to 5
move 3 from 5 to 7
move 3 from 8 to 5
move 1 from 7 to 5
move 4 from 5 to 1
move 4 from 4 to 2
move 2 from 7 to 8
move 12 from 1 to 6
move 1 from 8 to 6
move 6 from 2 to 3
move 9 from 3 to 8
move 1 from 3 to 4
move 3 from 6 to 1
move 2 from 9 to 2
move 1 from 4 to 5
move 2 from 8 to 3
move 10 from 2 to 1
move 2 from 4 to 7
move 12 from 1 to 4
move 1 from 5 to 1
move 7 from 4 to 9
move 2 from 3 to 2
move 6 from 9 to 2
move 1 from 9 to 1
move 1 from 7 to 8
move 5 from 6 to 7
move 3 from 6 to 1
move 6 from 2 to 3
move 2 from 4 to 3
move 1 from 6 to 8
move 1 from 6 to 7
move 8 from 3 to 9
move 2 from 4 to 5
move 3 from 2 to 4
move 10 from 8 to 2
move 22 from 1 to 9
move 9 from 2 to 4
move 1 from 1 to 3
move 1 from 3 to 2
move 3 from 2 to 4
move 2 from 7 to 1
move 14 from 4 to 2
move 2 from 1 to 8
move 2 from 4 to 5
move 4 from 7 to 8
move 24 from 9 to 6
move 3 from 5 to 9
move 1 from 9 to 8
move 1 from 5 to 2
move 1 from 6 to 7
move 6 from 9 to 1
move 1 from 7 to 3
move 5 from 8 to 6
move 9 from 6 to 3
move 4 from 1 to 4
move 2 from 1 to 2
move 11 from 6 to 3
move 13 from 3 to 2
move 2 from 9 to 8
move 8 from 3 to 8
move 2 from 8 to 5
move 1 from 7 to 5
move 3 from 6 to 3
move 11 from 8 to 5
move 13 from 2 to 4
move 10 from 5 to 2
move 2 from 3 to 4
move 2 from 5 to 7
move 15 from 4 to 9
move 2 from 7 to 4
move 2 from 4 to 2
move 2 from 4 to 9
move 2 from 4 to 2
move 1 from 3 to 8
move 1 from 8 to 1
move 1 from 1 to 2
move 1 from 6 to 3
move 7 from 2 to 4
move 1 from 5 to 3
move 7 from 9 to 1
move 7 from 1 to 2
move 4 from 6 to 9
move 12 from 9 to 7
move 6 from 7 to 5
move 1 from 3 to 5
move 7 from 4 to 7
move 3 from 7 to 8
move 3 from 8 to 6
move 18 from 2 to 9
move 7 from 2 to 3
move 15 from 9 to 4
move 3 from 3 to 9
move 1 from 3 to 1
move 3 from 5 to 4
move 1 from 1 to 2
move 1 from 9 to 2
move 2 from 6 to 2
move 5 from 7 to 6
move 5 from 2 to 7
move 3 from 3 to 4
move 5 from 5 to 3
move 6 from 7 to 4
move 9 from 4 to 2
move 18 from 4 to 9
move 6 from 2 to 1
move 1 from 1 to 9
move 4 from 7 to 4
move 7 from 2 to 4
move 1 from 2 to 8
move 1 from 4 to 2
move 4 from 3 to 4
move 16 from 9 to 5
move 9 from 9 to 8
move 1 from 9 to 7
move 4 from 1 to 2
move 2 from 5 to 4
move 10 from 5 to 4
move 4 from 2 to 1
move 5 from 1 to 2
move 1 from 8 to 5
move 1 from 6 to 5
move 4 from 8 to 5
move 2 from 6 to 9
move 3 from 6 to 2
move 2 from 9 to 1
move 1 from 7 to 6
move 1 from 3 to 8
move 9 from 5 to 9
move 4 from 8 to 1
move 2 from 8 to 2
move 1 from 5 to 7
move 9 from 9 to 8
move 1 from 7 to 5
move 9 from 8 to 2
move 6 from 1 to 6
move 6 from 2 to 6
move 10 from 2 to 5
move 5 from 2 to 1
move 1 from 3 to 5
move 8 from 5 to 4
move 5 from 1 to 3
move 10 from 6 to 8
move 3 from 6 to 9
move 4 from 3 to 1
move 5 from 8 to 2
move 4 from 5 to 9
move 1 from 3 to 7
move 1 from 7 to 3
move 1 from 8 to 6
move 1 from 6 to 1
move 15 from 4 to 8
move 5 from 9 to 2
move 1 from 9 to 1
move 1 from 1 to 3
move 6 from 4 to 8
move 12 from 8 to 7
move 1 from 3 to 5
move 3 from 1 to 9
move 13 from 4 to 9
move 5 from 7 to 2
move 1 from 5 to 4
move 8 from 9 to 5
move 6 from 2 to 5
move 2 from 5 to 6"""
| 0 | Kotlin | 0 | 0 | 8230fce9a907343f11a2c042ebe0bf204775be3f | 11,968 | advent-of-code-2022 | MIT License |
src/d01/Day01.kt | Ezike | 573,181,935 | false | {"Kotlin": 7967} | package d01
import readInput
fun main() {
fun part1(day: String): Int? {
var calories = mutableListOf<Int>()
var sum = 0
val (input, lastIndex) = readInput(day).let { it to it.lastIndex }
for ((i, s) in input.withIndex()) {
if (s.isEmpty()) {
sum = maxOf(sum, calories.sum())
calories = mutableListOf()
continue
}
if (i == lastIndex) {
calories.add(s.toInt())
sum = maxOf(sum, calories.sum())
break
}
calories.add(s.toInt())
}
return sum.takeIf { it > 0 }
}
fun part2(day: String): Int {
var calories = mutableListOf<Int>()
val (input, lastIndex) = readInput(day).let { it to it.lastIndex }
val top3 = mutableListOf<Int>()
for ((i, s) in input.withIndex()) {
if (s.isEmpty()) {
top3.add(calories.sum())
calories = mutableListOf()
continue
}
if (i == lastIndex) {
calories.add(s.toInt())
top3.add(calories.sum())
break
}
calories.add(s.toInt())
}
return top3.sortedDescending().take(3).sum()
}
check(part1("d01/Day01_test") == 24000)
check(part2("d01/Day01_test") == 45000)
println(part1("d01/Day01"))
println(part2("d01/Day01"))
}
| 0 | Kotlin | 0 | 0 | 07ed8acc2dcee09cc4f5868299a8eb5efefeef6d | 1,476 | advent-of-code | Apache License 2.0 |
src/Day19.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | object Day19 {
const val EXPECTED_PART1_CHECK_ANSWER = 33
const val EXPECTED_PART2_CHECK_ANSWER = 3472
val BLUEPRINT_REGEX =
Regex("Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.")
const val PART1_MINUTES = 24
}
enum class RobotCurrency {
ORE, CLAY, OBSIDIAN
}
enum class RobotType {
ORE_COLLECTOR, CLAY_COLLECTOR, OBSIDIAN_COLLECTOR, GEODE_CRACKING
}
data class RobotBuildCost(val amount: Int, val currency: RobotCurrency)
data class Blueprint(
val id: Int,
val buildCosts: Map<RobotType, Set<RobotBuildCost>>,
)
data class CollectingState(
val minutesDone: Int = 0,
val orePerMinute: Int = 1,
val clayPerMinute: Int = 0,
val obsidianPerMinute: Int = 0,
val geoCrackedPerMinute: Int = 0,
val ore: Int = 0,
val clay: Int = 0,
val obs: Int = 0,
val geoCracked: Int = 0,
)
fun main() {
fun List<String>.parseBlueprints() =
map {
val (id, oreRobotOre, clayRobotOre, obsRobotOre, obsRobotClay, geoRobotOre, geoRobotObs) = Day19.BLUEPRINT_REGEX.matchEntire(
it
)?.destructured ?: error("Oops")
Blueprint(
id.toInt(),
mapOf(
RobotType.ORE_COLLECTOR to setOf(RobotBuildCost(oreRobotOre.toInt(), RobotCurrency.ORE)),
RobotType.CLAY_COLLECTOR to setOf(RobotBuildCost(clayRobotOre.toInt(), RobotCurrency.ORE)),
RobotType.OBSIDIAN_COLLECTOR to setOf(RobotBuildCost(obsRobotOre.toInt(), RobotCurrency.ORE), RobotBuildCost(obsRobotClay.toInt(), RobotCurrency.CLAY)),
RobotType.GEODE_CRACKING to setOf(RobotBuildCost(geoRobotOre.toInt(), RobotCurrency.ORE), RobotBuildCost(geoRobotObs.toInt(), RobotCurrency.OBSIDIAN)),
)
)
}
fun findBest(
blueprint: Blueprint,
minutesToRun: Int,
state: CollectingState,
): Int {
val minutesLeft = minutesToRun - state.minutesDone
return blueprint.buildCosts
.maxOf { (robotType, buildCosts) ->
if (
(robotType == RobotType.ORE_COLLECTOR && state.orePerMinute > 5) ||
(robotType == RobotType.CLAY_COLLECTOR && state.clayPerMinute > 5) ||
(robotType == RobotType.OBSIDIAN_COLLECTOR && state.obsidianPerMinute > 5)
){
-1
} else {
val minutesPerCurrency = buildCosts.map {
when (it.currency) {
RobotCurrency.ORE -> if (state.ore >= it.amount) 0 else if (state.orePerMinute > 0) it.amount - state.ore / state.orePerMinute else -1
RobotCurrency.CLAY -> if (state.clay >= it.amount) 0 else if (state.clayPerMinute > 0) it.amount - state.clay / state.clayPerMinute else -1
RobotCurrency.OBSIDIAN -> if (state.obs >= it.amount) 0 else if (state.obsidianPerMinute > 0) it.amount - state.obs / state.obsidianPerMinute else -1
}
}
val canNotMake = minutesPerCurrency.any { it == -1 }
val minutesUntilWeCanMakeRobot = minutesPerCurrency.max() + 1
if (canNotMake || minutesUntilWeCanMakeRobot >= minutesLeft) {
state.copy(
minutesDone = minutesToRun,
ore = state.ore + state.orePerMinute * minutesLeft,
clay = state.clay + state.clayPerMinute * minutesLeft,
obs = state.obs + state.obsidianPerMinute * minutesLeft,
geoCracked = state.geoCracked + state.geoCrackedPerMinute * minutesLeft,
).geoCracked
} else {
findBest(
blueprint,
minutesToRun,
state.copy(
minutesDone = state.minutesDone + minutesUntilWeCanMakeRobot,
ore = state.ore + (minutesUntilWeCanMakeRobot * state.orePerMinute) - (buildCosts.firstOrNull { it.currency == RobotCurrency.ORE }?.amount
?: 0),
clay = state.clay + (minutesUntilWeCanMakeRobot * state.clayPerMinute) - (buildCosts.firstOrNull { it.currency == RobotCurrency.CLAY }?.amount
?: 0),
obs = state.obs + (minutesUntilWeCanMakeRobot * state.obsidianPerMinute) - (buildCosts.firstOrNull { it.currency == RobotCurrency.OBSIDIAN }?.amount
?: 0),
geoCracked = state.geoCracked + (minutesUntilWeCanMakeRobot * state.geoCrackedPerMinute),
orePerMinute = state.orePerMinute + if (robotType == RobotType.ORE_COLLECTOR) 1 else 0,
clayPerMinute = state.clayPerMinute + if (robotType == RobotType.CLAY_COLLECTOR) 1 else 0,
obsidianPerMinute = state.obsidianPerMinute + if (robotType == RobotType.OBSIDIAN_COLLECTOR) 1 else 0,
geoCrackedPerMinute = state.geoCrackedPerMinute + if (robotType == RobotType.GEODE_CRACKING) 1 else 0,
)
)
}
}
}
}
fun part1(input: List<String>): Int {
val bluePrints = input.parseBlueprints()
println(bluePrints)
bluePrints.forEach { bluePrint -> println("${bluePrint.id}: ${findBest(bluePrint, 24 /*Day19.PART1_MINUTES*/, CollectingState())}") }
return 1
}
fun part2(input: List<String>): Int {
return 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
check(part1(testInput) == Day19.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day19.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 6,375 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/day17/Day17.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day17
import readInput
fun main() {
val rocks = listOf(
listOf("####"),
listOf(
" # ",
"###",
" # "
),
listOf(
" #",
" #",
"###"
),
listOf(
"#",
"#",
"#",
"#"
),
listOf(
"##",
"##"
)
)
fun isValid(chamber: List<CharArray>, rock: Int, x: Int, y: Int): Boolean {
val width = rocks[rock][0].length
val height = rocks[rock].size
if (y < 0 || x < 0 || x + width > 7) {
return false
}
for (i in 0 until height) {
for (j in 0 until width) {
if (rocks[rock][i][j] != ' ' && chamber[y + height - 1 - i][x + j] != ' ') {
return false
}
}
}
return true
}
fun apply(chamber: List<CharArray>, rock: Int, x: Int, y: Int): Boolean {
val width = rocks[rock][0].length
val height = rocks[rock].size
for (i in 0 until height) {
for (j in 0 until width) {
if (rocks[rock][i][j] != ' ') {
chamber[y + height - 1 - i][x + j] = rocks[rock][i][j]
}
}
}
return true
}
fun printChamber(chamber: MutableList<CharArray>) {
println(
chamber.withIndex().reversed()
.joinToString(separator = "\n") {
it.value.joinToString(separator = "", prefix = "${it.index.toString().padStart(3)} #", postfix = "#")
}
)
println(" #########")
}
fun isEqual(chamber: List<CharArray>, from1: Int, from2: Int, len: Int): Boolean {
for (i in 0 until len) {
if (!chamber[from1 + i].contentEquals(chamber[from2 + i])) {
return false
}
}
return true
}
data class Result(val top: Int, val rount: Int, val rock: Int, val jet: Int, val cycle: Int, val cycleTop: Int)
data class RoundKey(val rock: Int, val jet: Int)
data class RoundResult(val n: Int, val top: Int)
fun simulate(input: List<String>, rounds: Int, initRock: Int = 0, initJet: Int = 0): Result {
var top = -1
var jet = initJet
var rock = initRock
val chamber = mutableListOf<CharArray>()
var cycle = -1
var cycleTop = -1
val seen = mutableMapOf<RoundKey, RoundResult>()
var round = 0
while(round < rounds) {
val stateKey = RoundKey(rock, jet)
if (seen.contains(stateKey)) {
val roundResult = seen[stateKey]!!
val len = top - roundResult.top
if (roundResult.top >= len) {
if (isEqual(chamber, roundResult.top - len + 1, top - len + 1, len)) {
cycle = round - roundResult.n
cycleTop = len
break
}
}
}
seen[stateKey] = RoundResult(round, top)
var x = 2
var y = top + 4
val height = rocks[rock].size
repeat(y + height + 1 - chamber.size) {
chamber.add(CharArray(7) { ' ' })
}
var stop = false
while (!stop) {
val shift = if (input[0][jet] == '>') {
1
} else {
-1
}
jet = (jet + 1) % input[0].length
if (isValid(chamber, rock, x + shift, y)) {
x += shift
}
if (isValid(chamber, rock, x, y - 1)) {
y -= 1
} else {
stop = true
}
}
apply(chamber, rock, x, y)
top = maxOf(top, y + height - 1)
rock = (rock + 1) % 5
round += 1
}
printChamber(chamber)
return Result(top + 1, round, rock, jet, cycle, cycleTop)
}
fun solve(input: List<String>, count: Long): Long {
val (top, round, rock, jet, cycleSize, cycleTop) = simulate(input, 10000)
val initHeight = top - cycleTop * (round / cycleSize)
val initRounds = round % cycleSize
val cycles = (count - initRounds) / cycleSize
val restRounds = (count - initRounds) % cycleSize
val restHeight = simulate(input, restRounds.toInt(), rock, jet).top
return initHeight + cycleTop * cycles + restHeight
}
fun part1(input: List<String>): Long {
return solve(input, 2022L)
}
fun part2(input: List<String>): Long {
return solve(input, 1000000000000L)
}
val testInput = readInput("day17", "test")
val input = readInput("day17", "input")
val part1 = part1(testInput)
println(part1)
check(part1 == 3068L)
val part1_2 = part1(input)
println(part1_2)
check(part1_2 == 3191L)
val part2 = part2(testInput)
println(part2)
check(part2 == 1514285714288L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 5,193 | aoc2022 | Apache License 2.0 |
src/main/kotlin/se/brainleech/adventofcode/aoc2022/Aoc2022Day01.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2022
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
import kotlin.math.max
class Aoc2022Day01 {
fun part1(input: List<String>): Long {
var maxCalories = 0L
var currentCalories = 0L
input.forEach {
if (it.isBlank()) maxCalories = max(maxCalories, currentCalories).also { currentCalories = 0L }
else currentCalories += it.toLong()
}
return max(maxCalories, currentCalories)
}
fun part2(input: List<String>): Long {
val maxCalories = MutableList(4) { 0L }
input.forEach {
if (it.isBlank()) maxCalories.sortDescending().also { maxCalories[3] = 0L }
else maxCalories[3] += it.toLong()
}
return maxCalories.sortedDescending().take(3).sum()
}
}
fun main() {
val solver = Aoc2022Day01()
val prefix = "aoc2022/aoc2022day01"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(24000L, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(45000L, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
}
| 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 1,291 | adventofcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/GraphValidTree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 261. Graph Valid Tree
* @see <a href="https://leetcode.com/problems/graph-valid-tree/">Source</a>
*/
fun interface GraphValidTree {
fun validTree(n: Int, edges: Array<IntArray>): Boolean
}
private class GraphValidTreeUnionFind(n: Int) {
private val parent: IntArray = IntArray(n)
private val size: IntArray = IntArray(n)
init {
for (node in 0 until n) {
parent[node] = node
size[node] = 1
}
}
fun Int.find(): Int {
// Step 1: Find the root.
var a = this
var root = a
while (parent[root] != root) {
root = parent[root]
}
// Step 2: Do a second traversal, this time setting each node to point
// directly at A as we go.
while (a != root) {
val oldRoot = parent[a]
parent[a] = root
a = oldRoot
}
return root
}
fun union(a: Int, b: Int): Boolean {
// Find the roots for A and B.
val rootA = a.find()
val rootB = b.find()
// Check if A and B are already in the same set.
if (rootA == rootB) {
return false
}
// We want to ensure the larger set remains the root.
if (size[rootA] < size[rootB]) {
// Make rootB the overall root.
parent[rootA] = rootB
// The size of the set rooted at B is the sum of the 2.
size[rootB] += size[rootA]
} else {
// Make rootA the overall root.
parent[rootB] = rootA
// The size of the set rooted at A is the sum of the 2.
size[rootA] += size[rootB]
}
return true
}
}
/**
* Approach 1: Graph Theory + Iterative Depth-First Search
*/
class GVTSimpleIterativeDFS : GraphValidTree {
override fun validTree(n: Int, edges: Array<IntArray>): Boolean {
val adjacencyList: MutableList<MutableList<Int>> = ArrayList()
for (i in 0 until n) {
adjacencyList.add(ArrayList())
}
for (edge in edges) {
adjacencyList[edge[0]].add(edge[1])
adjacencyList[edge[1]].add(edge[0])
}
val parent: MutableMap<Int, Int> = HashMap()
parent[0] = -1
val queue: Queue<Int> = LinkedList()
queue.offer(0)
while (queue.isNotEmpty()) {
val node: Int = queue.poll()
for (neighbour in adjacencyList[node]) {
if (parent[node] == neighbour) {
continue
}
if (parent.containsKey(neighbour)) {
return false
}
queue.offer(neighbour)
parent[neighbour] = node
}
}
return parent.size == n
}
}
/**
* Approach 2: Advanced Graph Theory + Iterative Depth-First Search
*/
class GVTAdvancedIterativeDFS : GraphValidTree {
override fun validTree(n: Int, edges: Array<IntArray>): Boolean {
if (edges.size != n - 1) return false
// Make the adjacency list.
// Make the adjacency list.
val adjacencyList: MutableList<MutableList<Int>> = ArrayList()
for (i in 0 until n) {
adjacencyList.add(ArrayList())
}
for (edge in edges) {
adjacencyList[edge[0]].add(edge[1])
adjacencyList[edge[1]].add(edge[0])
}
val queue: Queue<Int> = LinkedList()
val seen: MutableSet<Int> = HashSet()
queue.offer(0)
seen.add(0)
while (queue.isNotEmpty()) {
val node = queue.poll()
for (neighbour in adjacencyList[node]) {
if (seen.contains(neighbour)) continue
seen.add(neighbour)
queue.offer(neighbour)
}
}
return seen.size == n
}
}
/**
* Approach 3: Advanced Graph Theory + Union Find
*/
class GVTAdvancedUnionFind : GraphValidTree {
override fun validTree(n: Int, edges: Array<IntArray>): Boolean {
// Condition 1: The graph must contain n - 1 edges.
if (edges.size != n - 1) return false
// Condition 2: The graph must contain a single connected component.
// Create a new UnionFind object with n nodes.
val unionFind = GraphValidTreeUnionFind(n)
// Add each edge. Check if a merge happened, because if it
// didn't, there must be a cycle.
for (edge in edges) {
val a = edge[0]
val b = edge[1]
if (!unionFind.union(a, b)) {
return false
}
}
// If we got this far, there's no cycles!
return true
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,390 | kotlab | Apache License 2.0 |
src/Day03.kt | dyomin-ea | 572,996,238 | false | {"Kotlin": 21309} | fun main() {
fun intersection(input: List<String>): Iterable<Char> =
input.fold(
input.first()
.toSet()
) { acc, s ->
acc.intersect(s.toSet())
}
fun pointsOf(c: Char): Int =
when (c) {
in 'a'..'z' -> c - 'a' + 1
in 'A'..'Z' -> c - 'A' + 27
else -> error("unsupported")
}
fun String.splitByHalf(): List<String> =
listOf(
substring(0..lastIndex / 2),
substring(length / 2..lastIndex),
)
fun part1(input: List<String>): Int =
input
.flatMap { intersection(it.splitByHalf()) }
.sumOf(::pointsOf)
fun part2(input: List<String>): Int =
input.chunked(3)
.flatMap(::intersection)
.sumOf(::pointsOf)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 8aaf3f063ce432207dee5f4ad4e597030cfded6d | 918 | advent-of-code-2022 | Apache License 2.0 |
src/Day01/Day01.kt | brhliluk | 572,914,305 | false | {"Kotlin": 16006} | fun main() {
fun part1(input: List<String>) = input.chunkBy { it.isEmpty() }.map {
calloryList -> calloryList.map { it.toInt() }.reduce { acc, meal -> acc + meal }
}.maxOrNull()
fun part2(input: List<String>) = input.chunkBy { it.isEmpty() }.map {
calloryList -> calloryList.map { it.toInt() }.reduce { acc, meal -> acc + meal }
}.sortedDescending().take(3).reduce { acc, meal -> acc + meal }
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
fun <T> List<T>.chunkBy(predicate: (T) -> Boolean): Sequence<List<T>> = sequence {
val currentGroup = mutableListOf<T>()
for (element in this@chunkBy) {
if (predicate(element)) {
yield(currentGroup.toList())
currentGroup.clear()
} else currentGroup += element
}
yield(currentGroup)
}
| 0 | Kotlin | 0 | 0 | 96ac4fe0c021edaead8595336aad73ef2f1e0d06 | 869 | kotlin-aoc | Apache License 2.0 |
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day12RainRisk.kt | Scavi | 68,294,098 | false | {"Java": 1449516, "Kotlin": 59149} | package com.scavi.brainsqueeze.adventofcode
import kotlin.math.abs
class Day12RainRisk(private val wayPoint: WayPoint? = null) {
private enum class CardDirection(val value: Int) {
N(0), E(90), S(180), W(270);
companion object {
fun fromInt(value: Int) = values().first { it.value == value }
}
}
private val split = """(\w)(\d+)""".toRegex()
fun solve(instructions: List<String>): Int {
val boat = Boat()
for (current in instructions) {
val (instruction, distance) = split.find(current)!!.destructured
if (instruction == "F") {
boat.control(instruction, distance.toInt(), wayPoint)
} else {
if (wayPoint != null) {
wayPoint.control(instruction, distance.toInt())
} else {
boat.control(instruction, distance.toInt(), wayPoint)
}
}
}
return boat.manhattanDistance()
}
abstract class Control(var x: Int, var y: Int) {
fun control(instruction: String, distance: Int) {
turn(instruction, distance)
move(instruction, distance)
}
protected open fun move(instruction: String, distance: Int) {
when (instruction) {
CardDirection.N.toString() -> this.y += distance
CardDirection.E.toString() -> this.x += distance
CardDirection.S.toString() -> this.y -= distance
CardDirection.W.toString() -> this.x -= distance
}
}
protected abstract fun turn(instruction: String, distance: Int)
}
open class WayPoint : Control(10, 1) {
override fun turn(instruction: String, distance: Int) {
val amount = distance / 90
for (i in 1..amount) {
if (instruction == "R") {
val prevX = this.x
this.x = this.y
this.y = prevX * -1
} else {
val prevY = this.y
this.y = this.x
this.x = prevY * -1
}
}
}
}
private class Boat(var direction: CardDirection = CardDirection.E) : Control(0, 0) {
fun control(instruction: String, distance: Int, wayPoint: WayPoint? = null) {
if (wayPoint != null) {
this.x += wayPoint.x * distance
this.y += wayPoint.y * distance
} else {
super.control(instruction, distance)
}
}
fun manhattanDistance(): Int {
return abs(this.x) + abs(this.y)
}
override fun move(instruction: String, distance: Int) {
when (instruction) {
"F" -> move(this.direction.toString(), distance)
else -> super.move(instruction, distance)
}
}
override fun turn(instruction: String, distance: Int) {
if (instruction == "R") {
this.direction = CardDirection.fromInt((this.direction.value + distance) % 360)
} else if (instruction == "L") {
val tmp = (this.direction.value - distance) % 360
this.direction = CardDirection.fromInt(if (tmp >= 0) tmp else 360 - abs(tmp))
}
}
}
}
| 0 | Java | 0 | 1 | 79550cb8ce504295f762e9439e806b1acfa057c9 | 3,387 | BrainSqueeze | Apache License 2.0 |
src/Day03.kt | ditn | 572,953,437 | false | {"Kotlin": 5079} | fun main() {
fun part1(input: List<String>): Int = input
.map {
val left = it.subSequence(0, it.length / 2)
val right = it.subSequence(it.length / 2, it.length)
left.toSet() intersect right.toSet()
}
.map(Set<Char>::first)
.map(Char::toPriority)
.sum()
fun part2(input: List<String>): Int = input
.asSequence()
.chunked(3)
.map { it.map(String::toSet) }
.map { it[0] intersect it[1] intersect it[2] }
.map(Set<Char>::first)
.map(Char::toPriority)
.sum()
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun Char.toPriority() = if (!isUpperCase()) {
this - 'a' + 1
} else {
code - 38
} | 0 | Kotlin | 0 | 0 | 4c9a286a911cd79d433075cda5ed01249ecb5994 | 899 | aoc2022 | Apache License 2.0 |
src/main/kotlin/co/csadev/advent2021/Day05.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2021 by <NAME>
* Advent of Code 2021, Day 5
* Problem Description: http://adventofcode.com/2021/day/5
*/
package co.csadev.advent2021
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Resources.resourceAsText
class Day05(override val input: List<String> = resourceAsText("21day05.txt").lines()) :
BaseDay<List<String>, Int, Int> {
private fun countVents(input: List<String>, diagonals: Boolean): Int {
return input.flatMap {
val (x1, y1, x2, y2) = """\d+""".toRegex().findAll(it).map { found -> found.value.toInt() }.toList()
when {
x1 == x2 -> {
val (start, end) = listOf(y1, y2).sorted()
(start..end).map { y -> x1 to y }
}
y1 == y2 -> {
val (start, end) = listOf(x1, x2).sorted()
(start..end).map { x -> x to y1 }
}
diagonals -> {
val dx = if (x1 < x2) 1 else -1
val dy = if (y1 < y2) 1 else -1
(0..dx * (x2 - x1)).map { t ->
(x1 + dx * t) to (y1 + dy * t)
}
}
else -> emptyList()
}
}.groupingBy { it }.eachCount().count { it.value > 1 }
}
override fun solvePart1() = countVents(input, false)
override fun solvePart2() = countVents(input, true)
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 1,473 | advent-of-kotlin | Apache License 2.0 |
src/main/kotlin/leetcode/advanceds/DisjointSetDataStructure1.kt | sandeep549 | 251,593,168 | false | null | package leetcode.advanceds
// https://en.wikipedia.org/wiki/Disjoint-set_data_structure
// https://www.techiedelight.com/disjoint-set-data-structure-union-find-algorithm/
/**
* Problem Statement: We have some number of items. We are allowed to merge any two items to consider them equal.
* At any point we should be able to answer whether two items are equal or not ?
*/
private class DisjointSet {
private var parent = mutableMapOf<Int, Int>()
private var rank = mutableMapOf<Int, Int>()
// perform MakeSet operation
fun makeSet(x: Int) {
parent.put(x, x) // create new disjoint set point to itself
rank.put(x, 0)
}
// find root/representative of disjoint set to which x belongs
fun find(x: Int): Int {
if (parent.get(x) != x) {
parent.put(x, find(parent.get(x)!!)) // path compression
}
return parent.get(x)!!
}
// perform union of two disjoint sets
fun union(x: Int, y: Int) {
var a = find(x)
var b = find(y)
if (a == b) return // if already in same set
// perform union by rank
// attach smaller depth tree under the root of deeper tree
if (rank.get(x)!! < rank.get(y)!!)
parent.put(y, x)
else if (rank.get(x)!! > rank.get(y)!!)
parent.put(x, y)
else {
parent.put(x, y)
rank.put(y, rank.get(y)!! + 1)
}
}
// helper function to print all disjoints sets, i.e. print all representatives
fun printDisjointSets() {
parent.forEach {
if (it.key == it.value) print(it.key)
}
println()
}
}
fun main() {
var dj = DisjointSet()
dj.makeSet(1)
dj.makeSet(2)
dj.makeSet(3)
dj.makeSet(4)
dj.makeSet(5)
dj.printDisjointSets()
dj.union(1, 2)
dj.printDisjointSets()
dj.union(2, 3)
dj.printDisjointSets()
dj.union(4, 5)
dj.printDisjointSets()
// is 1 and 3 are equal(or friends), yes as belong to same disjoint set
println(dj.find(1) == dj.find(3))
}
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 2,073 | kotlinmaster | Apache License 2.0 |
string-similarity/src/commonMain/kotlin/com/aallam/similarity/JaroWinkler.kt | aallam | 597,692,521 | false | null | package com.aallam.similarity
import kotlin.math.max
import kotlin.math.min
/**
* The Jaro–Winkler distance metric is designed and best suited for short strings such as person names, and to detect
* typos; it is (roughly) a variation of Damerau-Levenshtein, where the substitution of 2 close characters is considered
* less important than the substitution of 2 characters that a far from each other.
*
* Jaro-Winkler was developed in the area of record linkage (duplicate detection) (Winkler, 1990).
* It returns a value in the interval [0.0, 1.0].
*
* @param threshold The current value of the threshold used for adding the Winkler bonus. The default value is 0.7.
*
* [Jaro–Winkler distance](https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance)
*/
public class JaroWinkler(
private val threshold: Double = 0.7
) {
/**
* Compute Jaro-Winkler similarity.
*
*
* @param first the first string to compare.
* @param second the second string to compare.
* @return The Jaro-Winkler similarity in the range [0, 1]
*/
public fun similarity(first: String, second: String): Double {
if (first == second) return 1.0
val (m, t, l, p) = matchStrings(first, second)
if (m == 0f) return 0.0
// Jaro similarity = 1/3 * (m/|s1| + m/|s2| + (m-t)/m)
val sj = ((m / first.length) + (m / second.length) + ((m - t) / m)) / 3.0
// Winkler similarity = Sj + P * L * (1 – Sj)
return if (sj > threshold) sj + p * l * (1 - sj) else sj
}
/**
* Return 1 - similarity.
* @param first the first string to compare.
* @param second the second string to compare.
* @return 1 - similarity.
*/
public fun distance(first: String, second: String): Double {
return 1.0 - similarity(first, second)
}
/**
* Matches two given strings and returns the count of matching characters, transpositions, the length of the
* common prefix, and the scaling factor.
*
* @param first The first string to compare.
* @param second The second string to compare.
*/
private fun matchStrings(first: String, second: String): Match {
val min = minOf(first, second)
val max = maxOf(first, second)
val (matchIndexes, matchFlags, matches) = computeStringMatch(max, min)
val ms1 = CharArray(matches).apply { fill(min, matchIndexes) }
val ms2 = CharArray(matches).apply { fill(max, matchFlags) }
val transpositions = transpositions(ms1, ms2)
val prefix = commonPrefix(min, max)
val scaling = min(JW_SCALING_FACTOR, 1.0 / max.length)
return Match(matches.toFloat(), transpositions, prefix, scaling)
}
/**
* Computes the matching indexes and flags between two strings.
*
* @param max the longer string
* @param min the shorter string
*/
private fun computeStringMatch(max: String, min: String): StringMatchInfo {
val range = max(max.length / 2 - 1, 0)
val matchIndexes = IntArray(min.length) { -1 }
val matchFlags = BooleanArray(max.length)
var matches = 0
for (i in min.indices) {
val char = min[i]
var xi = max(i - range, 0)
val xn = min(i + range + 1, max.length)
while (xi < xn) {
if (!matchFlags[xi] && char == max[xi]) {
matchIndexes[i] = xi
matchFlags[xi] = true
matches++
break
}
xi++
}
}
return StringMatchInfo(matchIndexes, matchFlags, matches)
}
/**
* Fills this character array with the characters from [max] at the positions indicated by the corresponding value
* in [flags].
*
* @param max the string from which to take the characters.
* @param flags the boolean array indicating which characters in the max string should be included.
*/
private fun CharArray.fill(max: String, flags: BooleanArray) {
var si = 0
for (i in max.indices) {
if (flags[i]) {
this[si] = max[i]
si++
}
}
}
/**
* Fills the character array with characters from the given string [min], based on the specified match [indexes].
*
* @param min the string containing the characters to be copied into the character array.
* @param indexes the indexes indicating which characters to copy from `min`. Any index value of -1 will be ignored.
*/
private fun CharArray.fill(min: String, indexes: IntArray) {
var si = 0
for (i in min.indices) {
if (indexes[i] != -1) {
this[si] = min[i]
si++
}
}
}
/**
* Calculates the length of the common prefix between two strings.
*
* @param min the shorter of the two strings being compared
* @param max the longer of the two strings being compared
*/
private fun commonPrefix(min: String, max: String): Int {
var prefix = 0
for (mi in min.indices) {
if (min[mi] != max[mi]) break
prefix++
}
return prefix
}
/**
* Calculates the number of transpositions between two matched strings.
*
* @param ms1 the first matched string.
* @param ms2 the second matched string.
*/
private fun transpositions(ms1: CharArray, ms2: CharArray): Int {
var transpositions = 0
for (mi in ms1.indices) {
if (ms1[mi] != ms2[mi]) {
transpositions++
}
}
return transpositions / 2
}
public companion object {
/** The standard value for the scaling factor */
private const val JW_SCALING_FACTOR = 0.1
}
}
/**
* Represents information about the matching indexes and flags between two strings,
* along with the total number of matches found.
*
* @param matchIndexes matching indexes
* @param matchFlags matching flags
* @param matches total number of matches found
*/
internal data class StringMatchInfo(
val matchIndexes: IntArray,
val matchFlags: BooleanArray,
val matches: Int
)
/**
* Represents a set of parameters that describe the similarity between two strings.
*
* @param matches number of matching characters
* @param transpositions number of transpositions
* @param prefix length of common prefix
* @param scaling scaling factor
*/
internal data class Match(
val matches: Float,
val transpositions: Int,
val prefix: Int,
val scaling: Double,
)
| 0 | Kotlin | 0 | 1 | 40cd4eb7543b776c283147e05d12bb840202b6f7 | 6,664 | string-similarity-kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CherryPickup.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 741. Cherry Pickup
* @see <a href="https://leetcode.com/problems/cherry-pickup/">Source</a>
*/
fun interface CherryPickup {
operator fun invoke(grid: Array<IntArray>): Int
}
/**
* Approach #2: Dynamic Programming (Top Down)
*/
class CherryPickupTopDown : CherryPickup {
private lateinit var memo: Array<Array<IntArray>>
private lateinit var grid: Array<IntArray>
var n = 0
override operator fun invoke(grid: Array<IntArray>): Int {
this.grid = grid
n = grid.size
memo = Array(n) { Array(n) { IntArray(n) { Int.MIN_VALUE } } }
return max(0, dp(0, 0, 0))
}
private fun dp(r1: Int, c1: Int, c2: Int): Int {
val r2 = r1 + c1 - c2
val helper = n == r1 || n == r2 || n == c1 || n == c2
if (grid.isNotEmpty() && grid.first().isEmpty()) {
return 0
}
return when {
helper || grid[r1][c1] == -1 || grid[r2][c2] == -1 -> {
LIMIT
}
r1 == n - 1 && c1 == n - 1 -> {
grid[r1][c1]
}
memo[r1][c1][c2] != Int.MIN_VALUE -> {
memo[r1][c1][c2]
}
else -> {
var ans = grid[r1][c1]
if (c1 != c2) ans += grid[r2][c2]
ans += max(
max(dp(r1, c1 + 1, c2 + 1), dp(r1 + 1, c1, c2 + 1)),
max(dp(r1, c1 + 1, c2), dp(r1 + 1, c1, c2)),
)
memo[r1][c1][c2] = ans
ans
}
}
}
companion object {
private const val LIMIT = -999999
}
}
/**
* Approach #3: Dynamic Programming (Bottom Up)
*/
class CherryPickupBottomUp : CherryPickup {
override operator fun invoke(grid: Array<IntArray>): Int {
if (grid.isEmpty()) return 0
val n: Int = grid.size
var dp = Array(n) { IntArray(n) { Int.MIN_VALUE } }
if (grid.isNotEmpty() && grid.first().isEmpty()) {
return 0
}
dp.first()[0] = grid.first().first()
for (t in 1..2 * n - 2) {
val dp2 = Array(n) { IntArray(n) { Int.MIN_VALUE } }
for (i in max(0, t - (n - 1))..min(n - 1, t)) {
for (j in max(0, t - (n - 1))..min(n - 1, t)) {
if (grid[i][t - i] == -1 || grid[j][t - j] == -1) continue
var value = grid[i][t - i]
if (i != j) value += grid[j][t - j]
for (pi in i - 1..i) {
for (pj in j - 1..j) {
if (pi >= 0 && pj >= 0) {
dp2[i][j] = max(dp2[i][j], dp[pi][pj] + value)
}
}
}
}
}
dp = dp2
}
return max(0, dp[n - 1][n - 1])
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,566 | kotlab | Apache License 2.0 |
src/Day24.kt | flex3r | 572,653,526 | false | {"Kotlin": 63192} | suspend fun main() {
val testInput = readInput("Day24_test")
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInput("Day24")
measureAndPrintResult {
part1(input)
}
measureAndPrintResult {
part2(input)
}
}
private fun part1(input: List<String>): Int {
val (grid, start, end) = parseGrid(input)
return moveTime(grid, start, end)
}
private fun part2(input: List<String>): Int {
val (grid, start, end) = parseGrid(input)
return moveTime(grid, start, end, moveTime(grid, end, start, moveTime(grid, start, end)))
}
private fun parseGrid(input: List<String>): Triple<Grid<Char>, Vec2, Vec2> {
val width = input.maxOf { it.length }
val height = input.size
val grid = Grid.fromInput(width, height) { (x, y) -> input[y][x] }
val start = grid.getRowCells(0).first { (_, c) -> c == '.' }.first
val end = grid.getRowCells(input.lastIndex).first { (_, c) -> c == '.' }.first
return Triple(grid, start, end)
}
private fun moveTime(grid: Grid<Char>, start: Vec2, end: Vec2, startTime: Int = 0): Int {
return bfs(start.withIndex(startTime)) {
moves(grid, it)
}.first { (_, pos) -> pos.value == end }.value.index
}
private fun moves(grid: Grid<Char>, position: IndexedValue<Vec2>): List<IndexedValue<Vec2>> {
val time = position.index + 1
return (position.value.neighbors + position.value)
.filter { it in grid && grid[it] != '#' && checkBlizzards(grid, it, time) }
.map { it.withIndex(time) }
}
private fun checkBlizzards(grid: Grid<Char>, pos: Vec2, time: Int): Boolean {
val widthWithoutBroder = grid.width - 2
val heightWithoutBorder = grid.height - 2
return grid.get(x = (pos.x - 1 + time).mod(widthWithoutBroder) + 1, pos.y) != '<' &&
grid.get(x = (pos.x - 1 - time).mod(widthWithoutBroder) + 1, pos.y) != '>' &&
grid.get(pos.x, y = (pos.y - 1 + time).mod(heightWithoutBorder) + 1) != '^' &&
grid.get(pos.x, y = (pos.y - 1 - time).mod(heightWithoutBorder) + 1) != 'v'
} | 0 | Kotlin | 0 | 0 | 8604ce3c0c3b56e2e49df641d5bf1e498f445ff9 | 2,067 | aoc-22 | Apache License 2.0 |
src/main/aoc2021/Day10.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2021
class Day10(val input: List<String>) {
companion object {
private val opposite = mapOf('{' to '}', '[' to ']', '(' to ')', '<' to '>')
private val part1Scores = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137)
// We have a list of leftover opening characters without any missing characters
// so scores need to be assigned to the corresponding opening character
private val part2Values = mapOf('(' to 1, '[' to 2, '{' to 3, '<' to 4)
}
private sealed interface Result {
class Corrupt(val invalid: Char) : Result {
fun score() = part1Scores.getValue(invalid)
}
class Incomplete(val missing: List<Char>) : Result {
fun score() = missing.fold(0L) { acc, c -> acc * 5 + part2Values.getValue(c) }
}
}
private fun parse(line: String): Result {
val stack = ArrayDeque<Char>()
line.forEach { ch ->
when {
ch in opposite -> stack.add(ch)
ch != opposite[stack.removeLast()] -> return Result.Corrupt(ch)
}
}
return Result.Incomplete(stack.reversed())
}
fun solvePart1(): Int {
return input
.map { parse(it) }
.filterIsInstance<Result.Corrupt>()
.sumOf { it.score() }
}
fun solvePart2(): Long {
return input
.map { parse(it) }
.filterIsInstance<Result.Incomplete>()
.map { it.score() }
.sorted()
.let { it[it.size / 2] }
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,578 | aoc | MIT License |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-16.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.CharGrid
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.get
import com.github.ferinagy.adventOfCode.isIn
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import com.github.ferinagy.adventOfCode.rotateCcw
import com.github.ferinagy.adventOfCode.rotateCw
import com.github.ferinagy.adventOfCode.searchGraph
import com.github.ferinagy.adventOfCode.singleStep
import com.github.ferinagy.adventOfCode.toCharGrid
fun main() {
val input = readInputLines(2023, "16-input")
val test1 = readInputLines(2023, "16-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val grid = input.toCharGrid()
return energize(grid, Coord2D(0, 0) to Coord2D(1, 0))
}
private fun part2(input: List<String>): Int {
val grid = input.toCharGrid()
val initials = grid.xRange.map { Coord2D(it, 0) to Coord2D(0, 1) } +
grid.xRange.map { Coord2D(it, grid.yRange.last) to Coord2D(0, -1) } +
grid.yRange.map { Coord2D(0, it) to Coord2D(1, 0) } +
grid.yRange.map { Coord2D(grid.xRange.last, it) to Coord2D(-1, 0) }
return initials.maxOf { energize(grid, it) }
}
private fun energize(grid: CharGrid, start: State): Int {
val visited = mutableSetOf<Coord2D>()
searchGraph(
start = start,
isDone = {
visited += it.first
false
},
nextSteps = {
next(it, grid[it.first]).filter { it.first.isIn(grid.xRange, grid.yRange) }.toSet().singleStep()
}
)
return visited.size
}
private fun next(current: State, tile: Char): List<State> = when (tile) {
'.' -> listOf(current.second)
'/' -> {
val newDir = if (current.second.x == 0) current.second.rotateCcw() else current.second.rotateCw()
listOf(newDir)
}
'\\' -> {
val newDir = if (current.second.x == 0) current.second.rotateCw() else current.second.rotateCcw()
listOf(newDir)
}
'|' -> if (current.second.x == 0) {
listOf(current.second)
} else {
listOf(Coord2D(0, -1), Coord2D(0, 1))
}
'-' -> if (current.second.y == 0) {
listOf(current.second)
} else {
listOf(Coord2D(-1, 0), Coord2D(1, 0))
}
else -> error("bad tile")
}.map { current.first + it to it}
private typealias State = Pair<Coord2D, Coord2D>
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,638 | advent-of-code | MIT License |
src/main/kotlin/day09/DayNine.kt | Neonader | 572,678,494 | false | {"Kotlin": 19255} | package day09
import java.io.File
data class Knot(var x: Int, var y: Int)
val fileList = File("puzzle_input/day09.txt").readLines()
fun moveHead(head: Knot, direction: Char) = when (direction) {
'U' -> Knot(head.x, head.y + 1)
'L' -> Knot(head.x - 1, head.y)
'R' -> Knot(head.x + 1, head.y)
'D' -> Knot(head.x, head.y - 1)
else -> Knot(0, 0)
}
fun moveTail(head: Knot, tail: Knot) = when {
head.x > tail.x + 1 && head.y > tail.y + 1 -> Knot(head.x - 1, head.y - 1)
head.x < tail.x - 1 && head.y > tail.y + 1 -> Knot(head.x + 1, head.y - 1)
head.x > tail.x + 1 && head.y < tail.y - 1 -> Knot(head.x - 1, head.y + 1)
head.x < tail.x - 1 && head.y < tail.y - 1 -> Knot(head.x + 1, head.y + 1)
head.x > tail.x + 1 -> Knot(head.x - 1, head.y)
head.x < tail.x - 1 -> Knot(head.x + 1, head.y)
head.y > tail.y + 1 -> Knot(head.x, head.y - 1)
head.y < tail.y - 1 -> Knot(head.x, head.y + 1)
else -> tail
}
fun a(): Int {
val visited = mutableSetOf(Knot(0, 0))
var head = Knot(0, 0)
var tail = Knot(0, 0)
for (line in fileList) {
val direction = line[0]
val steps = line.slice(2 until line.length).toInt()
repeat(steps) {
head = moveHead(head, direction)
tail = moveTail(head, tail)
visited += tail
}
}
return visited.size
}
fun b(): Int {
val visited = mutableSetOf(Knot(0, 0))
val rope = Array(10) { Knot(0,0) }
for (line in fileList) {
val direction = line[0]
val steps = line.slice(2 until line.length).toInt()
repeat(steps) {
rope[0] = moveHead(rope[0], direction)
for (i in rope.indices.filter { it > 0 }) rope[i] = moveTail(rope[i - 1], rope[i])
visited += rope[9]
}
}
return visited.size
} | 0 | Kotlin | 0 | 3 | 4d0cb6fd285c8f5f439cb86cb881b4cd80e248bc | 1,751 | Advent-of-Code-2022 | MIT License |
src/main/kotlin/com/ginsberg/advent2021/Day15.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 15 - Chiton
* Problem Description: http://adventofcode.com/2021/day/15
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day15/
*/
package com.ginsberg.advent2021
import java.util.PriorityQueue
typealias ChitonCave = Array<IntArray>
class Day15(input: List<String>) {
private val cave: ChitonCave = parseInput(input)
fun solvePart1(): Int =
cave.traverse()
fun solvePart2(): Int =
cave.traverse(
Point2d((cave.first().size * 5) - 1, (cave.size * 5) - 1)
)
private fun ChitonCave.traverse(
destination: Point2d = Point2d(first().lastIndex, lastIndex)
): Int {
val toBeEvaluated = PriorityQueue<Traversal>().apply { add(Traversal(Point2d(0, 0), 0)) }
val visited = mutableSetOf<Point2d>()
while (toBeEvaluated.isNotEmpty()) {
val thisPlace = toBeEvaluated.poll()
if (thisPlace.point == destination) {
return thisPlace.totalRisk
}
if (thisPlace.point !in visited) {
visited.add(thisPlace.point)
thisPlace.point
.neighbors()
.filter { it.x in (0..destination.x) && it.y in (0..destination.y) }
.forEach { toBeEvaluated.offer(Traversal(it, thisPlace.totalRisk + this[it])) }
}
}
error("No path to destination (which is really weird, right?)")
}
private operator fun ChitonCave.get(point: Point2d): Int {
val dx = point.x / this.first().size
val dy = point.y / this.size
val originalRisk = this[point.y % this.size][point.x % this.first().size]
val newRisk = (originalRisk + dx + dy)
return newRisk.takeIf { it < 10 } ?: (newRisk - 9)
}
private fun parseInput(input: List<String>): ChitonCave =
input.map { row ->
row.map { risk ->
risk.digitToInt()
}.toIntArray()
}.toTypedArray()
private class Traversal(val point: Point2d, val totalRisk: Int) : Comparable<Traversal> {
override fun compareTo(other: Traversal): Int =
this.totalRisk - other.totalRisk
}
} | 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 2,281 | advent-2021-kotlin | Apache License 2.0 |
src/Day03.kt | robotfooder | 573,164,789 | false | {"Kotlin": 25811} | fun main() {
fun part1(input: List<String>): Int = input
.map { it.splitToPair(it.length / 2) }
.flatMap { (c1, c2) -> c1.toSet() intersect c2.toSet() }
.sumOf { it.score() }
fun part2(input: List<String>): Int {
return input
.chunked(3)
.flatMap { it[0].toSet() intersect it[1].toSet() intersect it[2].toSet() }
.sumOf { it.score() }
}
fun runTest(expected: Int, day: String, testFunction: (List<String>) -> Int) {
val actual = testFunction(readInput("Day${day}_test"))
check(expected == actual)
{
"Failing for day $day, ${testFunction}. " +
"Expected $expected but got $actual"
}
}
val day = "03"
// test if implementation meets criteria from the description, like:
runTest(157, day, ::part1)
runTest(70, day, ::part2)
val input = readInput("Day$day")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9876a52ef9288353d64685f294a899a58b2de9b5 | 993 | aoc2022 | Apache License 2.0 |
src/main/kotlin/solutions/day05/Day5.kt | Dr-Horv | 570,666,285 | false | {"Kotlin": 115643} | package solutions.day05
import solutions.Solver
class Day5 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val inputList = input.toMutableList()
val stacks = parseStacks(inputList)
performMoves(stacks, inputList, partTwo)
return (1..stacks.keys.max())
.map { stacks[it]!!.first() }
.joinToString("")
}
private fun performMoves(
stacks: MutableMap<Int, MutableList<Char>>,
inputList: MutableList<String>,
partTwo: Boolean
) {
inputList.forEach {
if (it.isBlank()) {
return@forEach
}
val parts = it.split("from").map(String::trim)
val count = parts[0].removePrefix("move ").toInt()
val fromToParts = parts[1].split("to").map(String::trim).map(String::toInt)
val from = fromToParts[0]
val to = fromToParts[1]
val fromStack = stacks[from]
val toStack = stacks[to]
for (i in 0 until count) {
val c = if (!partTwo) {
fromStack!!.removeFirst()
} else {
fromStack!!.removeAt(count - 1 - i)
}
toStack!!.add(0, c)
}
}
}
private fun parseStacks(inputList: MutableList<String>): MutableMap<Int, MutableList<Char>> {
val stacks = mutableMapOf<Int, MutableList<Char>>()
while (inputList.isNotEmpty()) {
val line = inputList.removeFirst().toList()
if (line[1] == '1') {
break
}
for (i in 1..line.size step 4) {
val c = line[i]
if (c != ' ') {
val index = (i / 4) + 1
val l = stacks.getOrElse(index) { mutableListOf() }
l.add(c)
stacks[index] = l
}
}
}
return stacks
}
}
| 0 | Kotlin | 0 | 2 | 6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e | 2,011 | Advent-of-Code-2022 | MIT License |
2022/src/main/kotlin/day20_attempt2.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.badInput
import utils.mapItems
fun main() {
Day20_2.run()
}
object Day20_2 : Solution<List<Int>>() {
override val name = "day20"
override val parser = Parser.lines.mapItems { it.toInt() }
data class Item(
val origIndex: Int,
val value: Int,
)
override fun part1(input: List<Int>): Int {
val items = MutableList(input.size) { Item(it, input[it]) }
for (i in input.indices) {
val curIndex = items.indexOfFirst { it.origIndex == i }
val item = items[curIndex]
var move = item.value
while (move <= 0) {
move += input.size
}
if (item.value < 0) {
move -= 1 // backwards off-by-1
}
move %= input.size
// swap forward N times
var idx = curIndex
repeat(move) {
val swap = items[idx % input.size]
items[idx % input.size] = items[(idx + 1) % input.size]
items[(idx + 1) % input.size] = swap
idx++
}
}
val zi = items.indexOfFirst { it.value == 0 }
return items[(zi + 1000) % input.size].value + items[(zi + 2000) % input.size].value + items[(zi + 3000) % input.size].value
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,192 | aoc_kotlin | MIT License |
src/Day05.kt | ezeferex | 575,216,631 | false | {"Kotlin": 6838} | import java.util.*
fun processCrate(crates: List<String>): Pair<List<Stack<Char>>, List<Triple<Int, Int, Int>>> {
val stacks = mutableListOf<Stack<Char>>()
val lines = crates[0].split("\n")
lines.last().split(" ")
.filter(String::isNotBlank)
.forEach { _ ->
stacks.add(Stack<Char>())
}
for (i in lines.size - 2 downTo 0) {
val line = lines[i]
val chars = line.toCharArray()
for (j in chars.indices step 4) {
if (chars[j] == '[') {
stacks[j / 4].push(chars[j + 1])
}
}
}
val moves = crates[1].split("\n")
.map {
val move = it.split(" ")
Triple(move[1].toInt(), move[3].toInt(), move[5].toInt())
}
return stacks.toList() to moves
}
fun main() {
fun part1() = processCrate(readInput("05").split("\n\n"))
.let { (stacks, moves) ->
moves.forEach { (amount, prev, pos) ->
repeat(amount) {
stacks[pos - 1].push(stacks[prev - 1].pop())
}
}
stacks
}.let {
var message = ""
repeat(it.size) { index ->
message += it[index].peek()
}
message
}
fun part2() = processCrate(readInput("05").split("\n\n"))
.let {(stacks, moves) ->
moves.forEach { (amount, prev, pos) ->
val stackAux = Stack<Char>()
repeat(amount) {
stackAux.push(stacks[prev - 1].pop())
}
repeat(amount) {
stacks[pos - 1].push(stackAux.pop())
}
}
stacks
}.let {
var message = ""
repeat(it.size) { index ->
message += it[index].peek()
}
message
}
println( "Part 1: " + part1())
println( "Part 2: " + part2())
} | 0 | Kotlin | 0 | 0 | f06f8441ad0d7d4efb9ae449c9f7848a50f3f57c | 1,973 | advent-of-code-2022 | Apache License 2.0 |
src/day09/Day09.kt | robin-schoch | 572,718,550 | false | {"Kotlin": 26220} | package day09
import AdventOfCodeSolution
import kotlin.math.abs
fun main() {
Day09.run()
}
sealed class MoveDirection {
companion object {
fun of(direction: Char) = when (direction) {
'R' -> Right
'U' -> Up
'L' -> Left
'D' -> Down
else -> error("Unsupported move direction")
}
}
}
object Right : MoveDirection()
object Left : MoveDirection()
object Up : MoveDirection()
object Down : MoveDirection()
data class Coord(var y: Int, var x: Int) {
infix fun isNotOnSameRow(c: Coord) = abs(x - c.x) > 1
infix fun isNotOnSameColumn(c: Coord) = abs(y - c.y) > 1
infix fun isHigher(c: Coord) = y > c.y
infix fun isRigther(c: Coord) = x > c.x
}
data class Position(val tail: List<Coord>) {
private val head = tail[0]
infix fun moveHead(direction: MoveDirection) = when (direction) {
Down -> Coord(head.y - 1, head.x)
Left -> Coord(head.y, head.x - 1)
Right -> Coord(head.y, head.x + 1)
Up -> Coord(head.y + 1, head.x)
}.let { Position(listOf(it) + tail.drop(1)) }
@OptIn(ExperimentalStdlibApi::class)
fun adjustTailPosition(): Position {
for (i in 1..<tail.size) {
val prev = tail[i - 1]
val curr = tail[i]
if (prev isNotOnSameRow curr && prev isRigther curr) {
curr.x = prev.x - 1
if (prev isHigher curr) {
curr.y += 1
} else if (curr isHigher prev) {
curr.y -= 1
}
} else if (prev isNotOnSameRow curr && curr isRigther prev) {
curr.x = prev.x + 1
if (prev isHigher curr) {
curr.y += 1
} else if (curr isHigher prev) {
curr.y -= 1
}
} else if (prev isNotOnSameColumn curr && prev isHigher curr) {
curr.y = prev.y - 1
if (prev isRigther curr) {
curr.x += 1
} else if (curr isRigther prev) {
curr.x -= 1
}
} else if (prev isNotOnSameColumn curr && curr isHigher prev) {
curr.y = prev.y + 1
if (prev isRigther curr) {
curr.x += 1
} else if (curr isRigther prev) {
curr.x -= 1
}
}
}
return Position(tail)
}
}
object Day09 : AdventOfCodeSolution<Int, Int> {
override val testSolution1 = 88
override val testSolution2 = 36
private fun buildInstructionSequenz(input: List<String>) = sequence {
input.map {
val direction = MoveDirection.of(it[0])
val count = it.split(" ")[1].toInt()
repeat(count) { yield(direction) }
}
}
private fun calculateRopeEndPos(ropeLength: Int, input: List<String>): Int {
var position = Position(sequence { repeat(ropeLength) { yield(Coord(0, 0)) } }.toList())
val tailVisited = mutableSetOf<String>()
for (move in buildInstructionSequenz(input)) {
position = position moveHead move
position = position.adjustTailPosition()
tailVisited.add(position.tail.last().toString())
}
return tailVisited.size
}
override fun part1(input: List<String>): Int {
return calculateRopeEndPos(2, input)
}
override fun part2(input: List<String>): Int {
return calculateRopeEndPos(10, input)
}
} | 0 | Kotlin | 0 | 0 | fa993787cbeee21ab103d2ce7a02033561e3fac3 | 3,577 | aoc-2022 | Apache License 2.0 |
server/src/main/kotlin/com/heerkirov/hedge/server/library/compiler/grammar/definintion/SyntaxTable.kt | HeerKirov | 298,201,781 | false | null | package com.heerkirov.hedge.server.library.compiler.grammar.definintion
import kotlin.math.max
//语法分析表的定义,作用是和syntax-table.txt中的定义对应。
class SyntaxTable(internal val actionTable: Array<Array<Action?>>,
internal val gotoTable: Array<Array<Int?>>,
private val actionMap: Map<String, Int>,
private val gotoMap: Map<String, Int>) {
private val reflectActionMap by lazy { actionMap.asSequence().map { (k, v) -> v to k }.toMap() }
val statusCount: Int get() = actionTable.size
val actionNotations: Set<String> get() = actionMap.keys
val gotoNotations: Set<String> get() = gotoMap.keys
fun getAction(status: Int, terminalNotation: String): Action? {
val i = actionMap[terminalNotation] ?: throw RuntimeException("Action $terminalNotation is not exist.")
return actionTable[status][i]
}
fun getGoto(status: Int, nonTerminalNotation: String): Int? {
val i = gotoMap[nonTerminalNotation] ?: throw RuntimeException("Goto $nonTerminalNotation is not exist.")
return gotoTable[status][i]
}
fun getExpected(status: Int): List<String> {
return actionTable[status].asSequence()
.mapIndexed { i, action -> i to action }
.filter { (_, action) -> action != null }
.map { (i, _) -> reflectActionMap[i]!! }
.toList()
}
}
/**
* ACTION的指令。
*/
sealed class Action
data class Shift(val status: Int) : Action() {
override fun toString() = "Shift($status)"
}
data class Reduce(val syntaxExpressionIndex: Int) : Action() {
override fun toString() = "Reduce($syntaxExpressionIndex)"
}
object Accept : Action() {
override fun toString() = "Accept"
}
/**
* 读取并生成语法分析表的定义。
*/
fun readSyntaxTable(text: String): SyntaxTable {
val lines = text.split("\n")
.filter { it.isNotBlank() }
.apply { if(isEmpty()) throw RuntimeException("Text of syntax table is empty.") }
.map { it.split(Regex("\\s+")).filter { i -> i.isNotBlank() } }
val head = lines.first().apply { if(isEmpty()) throw RuntimeException("Table head is empty.") }
val terminalNum = head.first().toInt()
val actionMap = head.subList(1, terminalNum + 1).asSequence().mapIndexed { i, s -> s to i }.toMap()
val gotoMap = head.subList(terminalNum + 1, head.size).asSequence().mapIndexed { i, s -> s to i }.toMap()
val (action, goto) = lines.subList(1, lines.size).asSequence().map { row ->
val action = row.subList(1, terminalNum + 1).map {
when {
it == "_" -> null
it == "acc" -> Accept
it.startsWith("s") -> Shift(it.substring(1).toInt())
it.startsWith("r") -> Reduce(it.substring(1).toInt())
else -> throw RuntimeException("Unknown action '$it'.")
}
}.toTypedArray()
val goto = row.subList(terminalNum + 1, row.size).map { if(it == "_") null else it.toInt() }.toTypedArray()
Pair(action, goto)
}.unzip()
val actionTable = action.toTypedArray()
val gotoTable = goto.toTypedArray()
return SyntaxTable(actionTable, gotoTable, actionMap, gotoMap)
}
/**
* 将语法分析表打印为文本定义。
*/
fun printSyntaxTable(table: SyntaxTable): String {
//将action和goto表to string
val actionTable = table.actionTable.map { row ->
row.map { action ->
if(action == null) "_" else when (action) {
is Shift -> "s${action.status}"
is Reduce -> "r${action.syntaxExpressionIndex}"
is Accept -> "acc"
}
}
}
val gotoTable = table.gotoTable.map { row -> row.map { goto -> goto?.toString() ?: "_" } }
//取得首列、action列、goto列的宽度
val statusColWidth = max(table.statusCount.toString().length, table.actionNotations.size.toString().length)
val actionColWidth = max(table.actionNotations.maxOf { it.length }, actionTable.flatten().maxOf { it.length })
val gotoColWidth = max(table.gotoNotations.maxOf { it.length }, gotoTable.flatten().maxOf { it.length })
val head = String.format("%-${statusColWidth}s %s %s",
table.actionNotations.size,
table.actionNotations.joinToString(" ") { String.format("%-${actionColWidth}s", it) },
table.gotoNotations.joinToString(" ") { String.format("%-${gotoColWidth}s", it) }
)
val body = actionTable.zip(gotoTable).mapIndexed { i, (actionRow, gotoRow) ->
String.format("%-${statusColWidth}s %s %s", i,
actionRow.joinToString(" ") { String.format("%-${actionColWidth}s", it) },
gotoRow.joinToString(" ") { String.format("%-${gotoColWidth}s", it) }
)
}.joinToString("\n")
return "$head\n$body"
} | 0 | TypeScript | 0 | 1 | 8140cd693759a371dc5387c4a3c7ffcef6fb14b2 | 4,854 | Hedge-v2 | MIT License |
usvm-util/src/main/kotlin/org/usvm/algorithms/GraphUtils.kt | UnitTestBot | 586,907,774 | false | {"Kotlin": 2547205, "Java": 471958} | package org.usvm.algorithms
import java.util.LinkedList
import java.util.Queue
/**
* Finds minimal distances from one vertex to all other vertices in unweighted graph.
* A map with already calculated minimal distances can be specified to reduce the amount of calculations.
*
* @param startVertex vertex to find distances from.
* @param adjacentVertices function which maps a vertex to the sequence of vertices adjacent to
* it.
* @param distanceCache already calculated minimal distances map. Maps a start vertex to another map
* from end vertex to distance.
* @return Map from end vertex to minimal distance from startVertex to it.
*/
inline fun <V> findMinDistancesInUnweightedGraph(
startVertex: V,
adjacentVertices: (V) -> Sequence<V>,
distanceCache: Map<V, Map<V, UInt>> = emptyMap(),
): Map<V, UInt> {
val currentDistances = hashMapOf(startVertex to 0u)
val queue: Queue<V> = LinkedList()
queue.add(startVertex)
while (queue.isNotEmpty()) {
val currentVertex = queue.remove()
val distanceToCurrentVertex = currentDistances.getValue(currentVertex)
val cachedDistances = distanceCache[currentVertex]
if (cachedDistances != null) {
for ((theVertex, distanceFromCurrentToTheVertex) in cachedDistances) {
val currentDistanceToTheVertex = currentDistances[theVertex]
val newDistanceToTheVertex = distanceToCurrentVertex + distanceFromCurrentToTheVertex
if (currentDistanceToTheVertex == null || newDistanceToTheVertex < currentDistanceToTheVertex) {
/*
1.
Why won't we break anything with such update?
Because even if newDistanceToTheVertex < currentDistanceToTheVertex holds, we haven't visited theVertex yet:
Suppose we have, then
currentDistanceToTheVertex <= distanceToCurrentVertex (because we're doing BFS)
newDistanceToTheVertex < currentDistanceToTheVertex ~
distanceToCurrentVertex + distanceFromCurrentToTheVertex < currentDistanceToTheVertex
distanceToCurrentVertex + distanceFromCurrentToTheVertex < distanceToCurrentVertex ?!
*/
currentDistances[theVertex] = newDistanceToTheVertex
}
}
continue
}
for (adjacentVertex in adjacentVertices(currentVertex)) {
val currentDistanceToAdjacentVertex = currentDistances[adjacentVertex]
val newDistanceToAdjacentVertex = distanceToCurrentVertex + 1u
if (currentDistanceToAdjacentVertex == null || newDistanceToAdjacentVertex < currentDistanceToAdjacentVertex) {
currentDistances[adjacentVertex] = newDistanceToAdjacentVertex
/*
2.
If the vertex was added to queue, then it will never be added again:
If we write newDistanceToAdjacentVertex to dictionary here, newDistanceToAdjacentVertex >= currentDistanceToAdjacentVertex
will always hold because of BFS. It won't be broken by cache because currentDistanceToAdjacentVertex won't be rewritten from cache (see 1.)
*/
queue.add(adjacentVertex)
}
}
}
return currentDistances
}
/**
* Returns the sequence of vertices in breadth-first order.
*
* @param startVertices vertices to start traversal from.
* @param adjacentVertices function which maps a vertex to the sequence of vertices adjacent to.
* it.
*/
inline fun <V> bfsTraversal(
startVertices: Collection<V>,
crossinline adjacentVertices: (V) -> Sequence<V>,
): Sequence<V> {
val queue = ArrayDeque(startVertices)
val visited = HashSet<V>(startVertices)
return sequence {
while (queue.isNotEmpty()) {
val currentVertex = queue.removeFirst()
yield(currentVertex)
adjacentVertices(currentVertex)
.forEach { vertex ->
if (visited.add(vertex)) {
queue.add(vertex)
}
}
}
}
}
/**
* Returns the set of vertices with depth <= [depthLimit] in breadth-first order.
*
* @param depthLimit vertices which are reachable via paths longer than this value are
* not considered (i.e. 1 means only the vertices adjacent to start).
* @param startVertices vertices to start traversal from.
* @param adjacentVertices function which maps a vertex to the set of vertices adjacent to.
*/
inline fun <V> limitedBfsTraversal(
startVertices: Collection<V>,
depthLimit: UInt = UInt.MAX_VALUE,
crossinline adjacentVertices: (V) -> Sequence<V>,
): Sequence<V> {
var currentDepth = 0u
var numberOfVerticesOfCurrentLevel = startVertices.size
var numberOfVerticesOfNextLevel = 0
val queue = ArrayDeque(startVertices)
val verticesInQueue = HashSet<V>(startVertices)
return sequence {
while (currentDepth <= depthLimit && queue.isNotEmpty()) {
val currentVertex = queue.removeFirst()
yield(currentVertex)
adjacentVertices(currentVertex)
.forEach { vertex ->
if (verticesInQueue.add(vertex)) {
queue.add(vertex)
numberOfVerticesOfNextLevel++
}
}
if (--numberOfVerticesOfCurrentLevel == 0) {
currentDepth++
numberOfVerticesOfCurrentLevel = numberOfVerticesOfNextLevel
numberOfVerticesOfNextLevel = 0
}
}
}
}
| 39 | Kotlin | 0 | 7 | 94c5a49a0812737024dee5be9d642f22baf991a2 | 5,753 | usvm | Apache License 2.0 |
src/main/kotlin/Problem4.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | /**
* Largest palindrome product
*
* 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.
*
* https://projecteuler.net/problem=4
*/
fun main() {
println(largestPalindrome())
}
fun largestPalindrome(): Int {
var largestPalindrome = 0
for (a in 999 downTo 100) {
var b = 999
while (b >= a) {
val p = a * b
if (p <= largestPalindrome) {
break // since p is always going to be small
}
if (p.isPalindrome) {
largestPalindrome = p
}
b--
}
}
return largestPalindrome
}
val Int.isPalindrome: Boolean get() = this == reverse()
fun Int.reverse(): Int {
var num = this
var reversed = 0
while (num > 0) {
reversed = (10 * reversed) + (num % 10)
num /= 10
}
return reversed
}
| 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 1,023 | project-euler | MIT License |
tmp/arrays/youTrackTests/1541.kt | vitekkor | 600,111,569 | true | {"Kotlin": 11752665, "JavaScript": 2761845, "ANTLR": 28803, "Java": 12579} | // Original bug: KT-37416
fun main() = println(solve().joinToString("\n"))
private fun solve() = Array(readLine()!!.toInt()) { tn ->
if (tn > 0) readLine()
val (n, m) = readLine()!!.split(" ").map { it.toInt() }
val c = readLine()!!.split(" ").map { it.toLong() }
val g = Array(n) { ArrayList<Int>(2) }
repeat(m) {
val (u, v) = readLine()!!.split(" ").map { it.toInt() - 1 }
g[v].add(u)
}
val sum = HashMap<Long, Long>()
for ((i, l) in g.withIndex()) {
if (l.isEmpty()) continue
l.sort()
val h = l.fold(1L) { a, x -> a * 1299827 + x }
sum[h] = (sum[h] ?: 0) + c[i]
}
sum.values.fold(0L) { a, x -> gcd(a, x) }
}
private tailrec fun gcd(x: Long, y: Long): Long = if (y == 0L) x else gcd(y, x % y)
| 1 | Kotlin | 12 | 0 | f47406356a160ac61ab788f985b37121cc2e2a2a | 788 | bbfgradle | Apache License 2.0 |
HackerRank/BiggerIsGreater/Iteration1.kt | MahdiDavoodi | 434,677,181 | false | {"Kotlin": 57766, "JavaScript": 17002, "Java": 10647, "HTML": 696, "Python": 683} | fun biggerIsGreater(w: String): String {
var str = w.toCharArray().toMutableList()
if (w.length < 2) return "no answer"
for (i in str.size - 2 downTo 0) {
if (str[i] < str[i + 1]) {
val ch = str[i]
val cutFrom = i + 1
val rest = str.subList(cutFrom, str.size)
val minBigger = rest.minByIndex(ch)
if (minBigger != null) {
str[i] = minBigger.first
str[minBigger.second + cutFrom] = ch
val temp = str.subList(cutFrom, str.size).sorted()
str = str.dropLast(temp.size).toMutableList()
str.addAll(cutFrom, temp)
return str.joinToString("")
}
}
}
return "no answer"
}
fun List<Char>.minByIndex(element: Char): Pair<Char, Int>? {
var min = Pair('z', 0)
var flag = false
for (i in this.indices) if (this[i] > element && this[i] < min.first) {
min = Pair(this[i], i)
flag = true
}
return if (flag) min else null
}
fun main() {
val n = readLine()!!.toInt()
for (TItr in 1..n) {
val w = readLine()!!.trim()
println(biggerIsGreater(w))
}
}
/*
* For each word, start from the end.
* Find the first character that is bigger than the previous one. If you can't, return no answer.
* After that, find the smallest biggest character after the character you found.
* Swap them. Sort the rest of the string.
* */ | 0 | Kotlin | 0 | 0 | 62a23187efc6299bf921a95c8787d02d5be51742 | 1,462 | ProblemSolving | MIT License |
src/main/kotlin/day07/Day07.kt | dustinconrad | 572,737,903 | false | {"Kotlin": 100547} | package day07
import readResourceAsBufferedReader
import java.util.function.Predicate
fun main() {
println("part 1: ${part1(readResourceAsBufferedReader("7_1.txt").readLines())}")
println("part 2: ${part2(readResourceAsBufferedReader("7_1.txt").readLines())}")
}
fun part1(input: List<String>): Int {
val device = Device()
val instructions = parseCommands(input)
instructions.forEach { device.execute(it) }
val found = device.dfs { it is Directory && it.size() <= 100000 }
return found.sumOf { it.size() }
}
fun part2(input: List<String>): Int {
val device = Device()
val instructions = parseCommands(input)
instructions.forEach { device.execute(it) }
val usedSpace = device.usedSpace()
val freeSpace = 70000000 - usedSpace
val target = 30000000 - freeSpace
val found = device.dfs { it is Directory && it.size() >= target }
return found.sortedBy { it.size() }[0].size()
}
fun parseCommands(lines: List<String>): List<Command> {
val commands = mutableListOf<Command>()
var input = lines[0]
var output = mutableListOf<String>()
for (i in 1 until lines.size) {
val curr = lines[i]
if (curr.startsWith("$")) {
var arg = ""
val parts = input.split(" ")
if (parts.size == 3) {
arg = parts[2]
}
commands.add(Command(parts[1], arg, output))
input = curr
output = mutableListOf()
} else {
output.add(curr)
}
}
if (output.isNotEmpty()) {
var arg = ""
val parts = input.split(" ")
if (parts.size == 3) {
arg = parts[2]
}
commands.add(Command(parts[1], arg, output))
}
return commands
}
class Device {
private val root = Directory(null, "/")
private var currContext: FileOrDirectory = root
fun execute(command: Command) {
when(command.cmd) {
"cd" -> {
currContext = currContext.cd(command.arg)
}
"ls" -> currContext.ls(command.output)
}
}
fun dfs(pred: Predicate<FileOrDirectory>): List<FileOrDirectory> {
return root.dfs(pred)
}
fun usedSpace(): Int = root.size()
}
data class Command(val cmd: String, val arg: String, val output: List<String>)
sealed class FileOrDirectory(val parent: FileOrDirectory?, val name: String) {
abstract fun size(): Int
abstract fun cd(input: String): FileOrDirectory
abstract fun ls(output: List<String>)
abstract fun dfs(pred: Predicate<FileOrDirectory>): List<FileOrDirectory>
}
class File(parent: FileOrDirectory?, name: String, val size: Int): FileOrDirectory(parent, name) {
override fun size(): Int {
return size
}
override fun cd(input: String): FileOrDirectory {
throw IllegalArgumentException("Not a directory")
}
override fun ls(output: List<String>) {
throw IllegalArgumentException("Not a directory")
}
override fun dfs(pred: Predicate<FileOrDirectory>): List<FileOrDirectory> {
return if (pred.test(this)) {
listOf(this)
} else {
emptyList()
}
}
override fun toString(): String {
return "File(name=$name,size=$size)"
}
}
class Directory(parent: FileOrDirectory?, name: String): FileOrDirectory(parent, name) {
private val files = mutableMapOf<String, FileOrDirectory>()
private val _size: Int by lazy {
files.values.sumOf { it.size() }
}
override fun size(): Int {
return _size
}
override fun cd(input: String): FileOrDirectory {
return when(input) {
".." -> parent ?: throw IllegalStateException("No parent")
"/" -> {
var p: FileOrDirectory = this
while(p.parent != null) {
p = p.parent!!
}
p
}
else -> files[input]!!
}
}
override fun ls(output: List<String>) {
output.forEach {
val (l, r) = it.split(" ")
if (l == "dir") {
files[r] = Directory(this, r)
} else {
files[r] = File(this, r, l.toInt())
}
}
}
override fun dfs(pred: Predicate<FileOrDirectory>): List<FileOrDirectory> {
var result = mutableListOf<FileOrDirectory>()
if (pred.test(this)) {
result.add(this)
}
files.values.forEach { result.addAll(it.dfs(pred)) }
return result
}
override fun toString(): String {
return "Directory(name=$name,size=${size()})"
}
}
| 0 | Kotlin | 0 | 0 | 1dae6d2790d7605ac3643356b207b36a34ad38be | 4,696 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2022/Day07.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2022
import net.voldrich.BaseDay
import java.lang.RuntimeException
// https://adventofcode.com/2022/day/7
fun main() {
Day07().run()
}
class Day07 : BaseDay() {
override fun task1() : Int {
val rootDir = parseDirectoryTree()
return rootDir.filterDirectories { it.dirSize <= 100000 }.sumOf { it.dirSize }
}
override fun task2() : Int {
val hddSize = 70000000
val freeSpaceNeeded = 30000000
val rootDir = parseDirectoryTree()
val unusedSpace = hddSize - rootDir.dirSize
val minimumDirSizeToDelete = freeSpaceNeeded - unusedSpace
return rootDir.filterDirectories { it.dirSize > minimumDirSizeToDelete }.minOf { it.dirSize }
}
private fun parseDirectoryTree(): ElfDir {
val rootDir = ElfDir("/")
var currentDir = rootDir
val cmds = input.lines()
var num = 0
while (num < cmds.size) {
val cmd = cmds[num]
if (cmd.startsWith("$ cd")) {
val dirName = cmd.substring(5)
if (dirName == "/") {
currentDir = rootDir
} else if (dirName == "..") {
currentDir = currentDir.parent ?: throw RuntimeException("Cannot go up from root")
} else {
currentDir = currentDir.createSubDir(dirName)
}
num++
} else if (cmd == "$ ls") {
num++
while (num < cmds.size && !cmds[num].startsWith("$")) {
val line = cmds[num]
if (line.startsWith("dir")) {
val dirName = line.substring(3).trim()
currentDir.createSubDir(dirName)
} else {
val split = line.split(" ")
currentDir.createFile(split[1], split[0].toInt())
}
num++
}
}
}
rootDir.calculateDirectorySize()
return rootDir
}
}
class ElfDir(val name: String, val parent: ElfDir? = null) {
val subDirs: MutableMap<String, ElfDir> = mutableMapOf()
val files: MutableMap<String, ElfFile> = mutableMapOf()
var dirSize = 0
fun createSubDir(dirName: String): ElfDir {
return subDirs.computeIfAbsent(dirName) { ElfDir(dirName, this) }
}
fun createFile(name: String, size: Int) {
files.computeIfAbsent(name) { ElfFile(name, size) }
}
fun calculateDirectorySize(): Int {
dirSize = files.values.sumOf { it.size } + subDirs.values.sumOf { it.calculateDirectorySize() }
return dirSize
}
fun filterDirectories(predicate: (ElfDir) -> Boolean): List<ElfDir> {
if (predicate.invoke(this)) {
return listOf(this) + subDirs.values.flatMap { it.filterDirectories(predicate) }
} else {
return subDirs.values.flatMap { it.filterDirectories(predicate) }
}
}
}
data class ElfFile(val name: String, val size: Int)
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 3,073 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day12.kt | tianyu | 574,561,581 | false | {"Kotlin": 49942} | import assertk.assertThat
import assertk.assertions.containsExactly
import assertk.assertions.isEqualTo
private fun main() {
tests {
val example = HeightMap(
"""
Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi
""".trimIndent().encodeToByteArray()
)
"Reading a HeightMap" {
assertThat(example.start).isEqualTo(0)
assertThat(example.end).isEqualTo(23)
}
"Getting options from a position" {
assertThat(example.options(0).toList())
.containsExactly(1, 9)
assertThat(example.options(8).toList())
.containsExactly(8 - 1, 9 + 8)
assertThat(example.options(4 * 9).toList())
.containsExactly(4 * 9 + 1, 3 * 9)
assertThat(example.options(4 * 9 + 8).toList())
.containsExactly(4 * 9 + 7, 3 * 9 + 8)
assertThat(example.options(2 * 9 + 3).toList())
.containsExactly(2 * 9 + 4, 2 * 9 + 2, 3 * 9 + 3, 9 + 3)
}
"Part 1 Example" {
val distanceMap = example.mapTrails()
assertThat(distanceMap[example.start]).isEqualTo(31)
}
}
val heightMap = HeightMap()
val trailsMap = heightMap.mapTrails()
part1("The shortest path to the target location is:") {
trailsMap[heightMap.start]
}
part2("The fewest steps required to move from a square with elevation 'a' to the target location is:") {
heightMap.locationsWithElevation('a'.code.toByte())
.minOf { trailsMap[it] }
}
}
private class HeightMap(val bytes: ByteArray = inputStream("day12.txt").readBytes()) {
val width = bytes.indexOf('\n'.code.toByte())
private val lineWidth = width + 1
val height = bytes.size / lineWidth
val start = bytes.indexOf('S'.code.toByte())
val end = bytes.indexOf('E'.code.toByte())
operator fun get(index: Int): Byte = when (val byte = bytes[index]) {
'S'.code.toByte() -> 'a'.code.toByte()
'E'.code.toByte() -> 'z'.code.toByte()
else -> byte
}
fun options(index: Int) = sequence {
val row = index / lineWidth
val col = index % lineWidth
if (col < width - 1) yield(index + 1)
if (col > 0) yield(index - 1)
if (row < height - 1) yield(index + lineWidth)
if (row > 0) yield(index - lineWidth)
}
fun mapTrails(): IntArray {
val distanceMap = IntArray(bytes.size) { Int.MAX_VALUE }
val positions = ArrayDeque<Int>()
distanceMap[end] = 0
positions.add(end)
while (positions.isNotEmpty()) {
val position = positions.removeFirst()
val distance = distanceMap[position]
val height = this[position]
positions.addAll(
options(position)
.filter { distanceMap[it] == Int.MAX_VALUE && height - this[it] <= 1 }
.onEach { distanceMap[it] = distance + 1 }
)
}
return distanceMap
}
fun locationsWithElevation(elevation: Byte) = bytes.indices.asSequence()
.filter { this[it] == elevation }
}
| 0 | Kotlin | 0 | 0 | 6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea | 2,894 | AdventOfCode2022 | MIT License |
2021/src/main/kotlin/de/skyrising/aoc2021/day21/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day21
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap
val test = TestInput("""
Player 1 starting position: 4
Player 2 starting position: 8
""")
@PuzzleName("<NAME>")
fun PuzzleInput.part1(): Any {
var (p1, p2) = parseInput(this)
val dice = Dice()
var score1 = 0
var score2 = 0
var rolls = 0
while (score2 < 1000) {
p1 = move(p1, dice.next() + dice.next() + dice.next())
rolls += 3
score1 += p1
if (score1 >= 1000) break
p2 = move(p2, dice.next() + dice.next() + dice.next())
rolls += 3
score2 += p2
}
return minOf(score1, score2) * rolls
}
fun PuzzleInput.part2(): Any {
val (i1, i2) = parseInput(this)
var wins1 = 0L
var wins2 = 0L
val universes = Object2LongLinkedOpenHashMap<Universe>()
universes[Universe(i1, i2, 0, 0)] = 1L
while (universes.isNotEmpty()) {
val (universe, count) = universes.object2LongEntrySet().first()
universes.removeLong(universe)
val (p1, p2, score1, score2) = universe
for (d11 in 1..3) for (d12 in 1..3) for (d13 in 1..3) {
val p12 = move(p1, d11 + d12 + d13)
val score12 = score1 + p12
if (score12 >= 21) {
wins1 += count
continue
}
for (d21 in 1..3) for (d22 in 1..3) for (d23 in 1..3) {
val p22 = move(p2, d21 + d22 + d23)
val score22 = score2 + p22
if (score22 >= 21) {
wins2 += count
continue
}
val newUniverse = Universe(p12, p22, score12, score22)
universes[newUniverse] = universes.getLong(newUniverse) + count
}
}
}
return maxOf(wins1, wins2)
}
private fun move(p: Int, amount: Int) = (p + amount - 1) % 10 + 1
data class Universe(val p1: Int, val p2: Int, val score1: Int, val score2: Int)
data class Dice(var next: Int = 1) {
fun next(): Int {
val r = next
next++
if (next > 1000) next = 1
return r
}
}
private fun parseInput(input: PuzzleInput) = Pair(input.lines[0].ints().getInt(1), input.lines[1].ints().getInt(1)) | 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,291 | aoc | MIT License |
08/kotlin/src/main/kotlin/se/nyquist/Functions.kt | erinyq712 | 437,223,266 | false | {"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098} | package se.nyquist
import java.math.BigInteger
fun <T> getPermutationsWithDistinctValues(original: List<T>): Set<List<T>> {
if (original.isEmpty())
return emptySet()
val permutationInstructions = original.toSet()
.map { it to original.count { x -> x == it } }
.fold(listOf(setOf<Pair<T, Int>>())) { acc, (value, valueCount) ->
mutableListOf<Set<Pair<T, Int>>>().apply {
for (set in acc) for (retainIndex in 0 until valueCount) add(set + (value to retainIndex))
}
}
return mutableSetOf<List<T>>().also { outSet ->
for (instructionSet in permutationInstructions) {
outSet += original.toMutableList().apply {
for ((value, retainIndex) in instructionSet) {
repeat(retainIndex) { removeAt(indexOfFirst { it == value }) }
repeat(count { it == value } - 1) { removeAt(indexOfLast { it == value }) }
}
}
}
}
}
fun <T> allPermutations(digits : List<T>) : List<List<T>> {
val size = digits.size
var current = 0
val values = mutableListOf<List<T>>()
while (current < size) {
val head = digits[current]
if (size> 1) {
val subList = digits.filter { it != head }.toList()
val tails = allPermutations(subList)
for (tail in tails) {
val newList = mutableListOf<T>(head)
newList.addAll(tail)
values.add(newList)
}
} else {
values.add(mutableListOf<T>(head))
}
current++
}
return values
}
fun allNumberPermutations(digits : IntArray) : IntArray {
val size = digits.size
var current = 0
val base = BigInteger.valueOf(10L)
val values = mutableListOf<Int>()
while (current < digits.size) {
val head = base.pow(size-1).multiply(digits[current].toBigInteger())
if (size> 1) {
val tails = allNumberPermutations(digits.filter { it != digits[current] }.toIntArray())
for (tail in tails) {
values.add(head.add(tail.toBigInteger()).toInt())
}
} else {
values.add(head.toInt())
}
current++
}
return values.toIntArray()
} | 0 | Kotlin | 0 | 0 | b463e53f5cd503fe291df692618ef5a30673ac6f | 2,299 | adventofcode2021 | Apache License 2.0 |
src/main/kotlin/days/y22/Day02.kt | kezz | 572,635,766 | false | {"Kotlin": 20772} | package days.y22
import util.Day
public fun main() {
Day2().run()
}
public class Day2 : Day(22, 2) {
override fun part1(input: List<String>): Any = input
.map { string -> string.filterNot(Char::isWhitespace).toCharArray() }
.map { (opponentCode, playerCode) -> Pair(opponentCode.code - 64, playerCode.code - 87) }
.sumOf { (opponentsMove, playersMove) ->
playersMove + when {
opponentsMove == playersMove -> 3
playersMove == 1 && opponentsMove == 3 -> 6
opponentsMove == 1 && playersMove == 3 -> 0
playersMove > opponentsMove -> 6
else -> 0
}
}
override fun part2(input: List<String>): Any = input
.map { string -> string.filterNot(Char::isWhitespace).toCharArray() }
.map { (opponentCode, targetCode) -> Pair(opponentCode.code - 64, (targetCode.code - 88) * 3) }
.map { (opponentsMove, targetScore) ->
targetScore to when (targetScore) {
6 -> opponentsMove + 1
3 -> opponentsMove
else -> opponentsMove - 1
}
}
.sumOf { (targetScore, uncorrectedPlayerMove) ->
targetScore + when (uncorrectedPlayerMove) {
4 -> 1
0 -> 3
else -> uncorrectedPlayerMove
}
}
}
| 0 | Kotlin | 0 | 0 | 1cef7fe0f72f77a3a409915baac3c674cc058228 | 1,399 | aoc | Apache License 2.0 |
src/Day13.kt | mcrispim | 573,449,109 | false | {"Kotlin": 46488} | fun isInt(s: String): Boolean {
return try {
s.toInt()
true
} catch (e: NumberFormatException) {
false
}
}
fun isList(s: String) = s.startsWith('[') && s.endsWith(']')
fun unlist(list: String): MutableList<String> {
val elements = mutableListOf<String>()
var level = 0
var start = 0
var index = 1
while (index <= list.lastIndex) {
when (list[index]) {
'[' -> {
if (level == 0)
start = index
level++
}
']' -> {
level--
if (level == 0)
elements.add(list.slice(start..index))
}
in '0'..'9' -> {
if (level == 0) {
start = index++
while (list[index] in '0'..'9')
index++
index--
elements.add(list.slice((start..index)))
}
}
}
index++
}
return elements
}
fun intsInOrder(left: String, right: String): Boolean? {
val l = left.toInt()
val r = right.toInt()
if (l < r) return true
if (l > r) return false
return null
}
fun listsInOrder(left: String, right: String, level: Int): Boolean? {
val rawLeft = unlist(left)
val rawRight = unlist(right)
while (rawLeft.isNotEmpty() && rawRight.isNotEmpty()) {
val leftElement = rawLeft.removeAt(0)
val rightElement = rawRight.removeAt(0)
return areInOrder(leftElement, rightElement, level + 1) ?: continue
}
if (rawLeft.isEmpty() && rawRight.isEmpty())
return null
if (rawLeft.isEmpty())
return true
return false
}
fun areInOrder(left: String, right: String, level: Int): Boolean? {
if (isList(left) && isList(right)) {
val inOrder = listsInOrder(left, right, level)
if (level == 0 && inOrder == null)
return true
return inOrder
}
if (isInt(left) && isInt(right)) {
val inOrder = intsInOrder(left, right)
if (level == 0 && inOrder == null)
return true
return inOrder
}
return if (isInt(left))
areInOrder("[$left]", right, level + 1)
else
areInOrder(left, "[$right]", level + 1)
}
class Packet(val text: String) : Comparable<Packet> {
override fun compareTo(other: Packet): Int {
return when (areInOrder(left = this.text, right = other.text, level = 0)) {
true -> -1
false -> 1
null -> 0
}
}
override fun toString(): String {
return text
}
}
fun main() {
fun part1(input: List<String>): Int {
var line = 0
var index = 0
var indexSum = 0
while (line < input.size) {
val left = input[line++]
val right = input[line++]
line++
index++
val inOrder = areInOrder(left, right, level = 0)
if (inOrder!!)
indexSum += index
}
return indexSum
}
fun part2(input: List<String>): Int {
val packets = input.filter { it.isNotEmpty() }.map { Packet(it) }.toMutableList()
packets.add(Packet("[[2]]"))
packets.add(Packet("[[6]]"))
val sortedPackets = packets.sorted()
val mark1 = sortedPackets.indexOfFirst { it.text == "[[2]]" } + 1
val mark2 = sortedPackets.indexOfFirst { it.text == "[[6]]" } + 1
return mark1 * mark2
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test2")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5fcacc6316e1576a172a46ba5fc9f70bcb41f532 | 3,806 | AoC2022 | Apache License 2.0 |
src/main/kotlin/g0601_0700/s0691_stickers_to_spell_word/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0601_0700.s0691_stickers_to_spell_word
// #Hard #Array #String #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask
// #2023_02_20_Time_249_ms_(100.00%)_Space_42.6_MB_(100.00%)
class Solution {
// count the characters of every sticker
private lateinit var counts: Array<IntArray>
// For each character, save the sticker index which has this character
private val map: HashMap<Char, HashSet<Int>> = HashMap()
private val cache: HashMap<Int, Int> = HashMap()
fun minStickers(stickers: Array<String>, target: String): Int {
counts = Array(stickers.size) { IntArray(26) }
for (i in 0..25) {
map[('a'.code + i).toChar()] = HashSet()
}
for (i in stickers.indices) {
for (c in stickers[i].toCharArray()) {
counts[i][c.code - 'a'.code]++
map[c]!!.add(i)
}
}
val res = dp(0, target)
return if (res > target.length) {
-1
} else res
}
private fun dp(bits: Int, target: String): Int {
val len = target.length
if (bits == (1 shl len) - 1) {
// all bits are 1
return 0
}
if (cache.containsKey(bits)) {
return cache[bits]!!
}
var index = 0
// find the first bit which is 0
for (i in 0 until len) {
if (bits and (1 shl i) == 0) {
index = i
break
}
}
// In worst case, each character use 1 sticker. So, len + 1 means impossible
var res = len + 1
for (key in map[target[index]]!!) {
val count = counts[key].clone()
var mask = bits
for (i in index until len) {
if (mask and (1 shl i) != 0) {
// this bit has already been 1
continue
}
val c = target[i]
if (count[c.code - 'a'.code] > 0) {
count[c.code - 'a'.code]--
mask = mask or (1 shl i)
}
}
val `val` = dp(mask, target) + 1
res = res.coerceAtMost(`val`)
}
cache[bits] = res
return res
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,269 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/g0001_0100/s0016_3sum_closest/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0016_3sum_closest
// #Medium #Array #Sorting #Two_Pointers #Level_2_Day_14_Sliding_Window/Two_Pointer
// #2023_07_03_Time_163_ms_(100.00%)_Space_37.5_MB_(92.24%)
class Solution {
fun threeSumClosest(nums: IntArray, target: Int): Int {
if (nums.size < 3) {
return 0
}
if (nums.size == 3) {
return nums[0] + nums[1] + nums[2]
}
nums.sort()
val n = nums.size
var sum = nums[0] + nums[1] + nums[2]
for (i in 0 until n - 2) {
if (nums[i] + nums[n - 1] + nums[n - 2] < target) {
sum = nums[i] + nums[n - 1] + nums[n - 2]
continue
}
if (nums[i] + nums[i + 1] + nums[i + 2] > target) {
val temp = nums[i] + nums[i + 1] + nums[i + 2]
return lessGap(sum, temp, target)
}
var j = i + 1
var k = n - 1
while (j < k) {
val temp = nums[i] + nums[j] + nums[k]
if (temp == target) {
return target
}
if (temp < target) {
j++
} else {
k--
}
sum = lessGap(sum, temp, target)
}
}
return sum
}
private fun lessGap(sum: Int, temp: Int, target: Int): Int {
return if (Math.abs(sum - target) < Math.abs(temp - target)) sum else temp
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,495 | LeetCode-in-Kotlin | MIT License |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day19/Day19.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day19
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.toPair
import net.olegg.aoc.year2023.DayOf2023
/**
* See [Year 2023, Day 19](https://adventofcode.com/2023/day/19)
*/
object Day19 : DayOf2023(19) {
override fun first(): Any? {
val (rulesBlock, partsBlock) = data.split("\n\n")
val rules = rulesBlock.lines()
.associate { line ->
val name = line.substringBefore('{')
val rulesRaw = line.substringAfter('{').substringBefore('}').split(",")
val rulesList = rulesRaw.map { ruleRaw ->
when {
'<' in ruleRaw -> Rule.Less(
stat = ruleRaw.substringBefore('<'),
value = ruleRaw.substringAfter('<').substringBefore(':').toInt(),
) to ruleRaw.substringAfter(':')
'>' in ruleRaw -> Rule.More(
stat = ruleRaw.substringBefore('>'),
value = ruleRaw.substringAfter('>').substringBefore(':').toInt(),
) to ruleRaw.substringAfter(':')
else -> Rule.Always to ruleRaw
}
}
name to rulesList
}
val parts = partsBlock.lines()
.map { line ->
val stats = line.drop(1).dropLast(1).split(",")
Part(stats.associate { stat -> stat.split("=").toPair().let { it.first to it.second.toInt() } })
}
return parts
.filter { part ->
var curr = "in"
do {
val rule = rules.getValue(curr)
curr = rule.first { it.first.accept(part) }.second
} while (curr != "A" && curr != "R")
curr == "A"
}
.sumOf { it.x + it.m + it.a + it.s }
}
override fun second(): Any? {
val rulesBlock = data.substringBefore("\n\n")
val rules = rulesBlock.lines()
.associate { line ->
val name = line.substringBefore('{')
val rulesRaw = line.substringAfter('{').substringBefore('}').split(",")
val rulesList = rulesRaw.map { ruleRaw ->
when {
'<' in ruleRaw -> Rule.Less(
stat = ruleRaw.substringBefore('<'),
value = ruleRaw.substringAfter('<').substringBefore(':').toInt(),
) to ruleRaw.substringAfter(':')
'>' in ruleRaw -> Rule.More(
stat = ruleRaw.substringBefore('>'),
value = ruleRaw.substringAfter('>').substringBefore(':').toInt(),
) to ruleRaw.substringAfter(':')
else -> Rule.Always to ruleRaw
}
}
name to rulesList
}
val queue = ArrayDeque(
listOf(
"in" to PartRanges(
map = mapOf(
"x" to listOf(1..4000),
"m" to listOf(1..4000),
"a" to listOf(1..4000),
"s" to listOf(1..4000),
),
),
),
)
val result = mutableListOf<PartRanges>()
while (queue.isNotEmpty()) {
val (node, curr) = queue.removeFirst()
if (node == "R") {
continue
}
if (curr == PartRanges.EMPTY) {
continue
}
if (node == "A") {
result += curr
continue
}
rules.getValue(node).fold(curr) { acc, (rule, target) ->
val (accept, reject) = rule.partition(acc)
if (accept != PartRanges.EMPTY) {
queue.add(target to accept)
}
reject
}
}
return result.sumOf { partRanges ->
partRanges.map.values
.map { ranges -> ranges.sumOf { it.count().toLong() } }
.reduce(Long::times)
}
}
sealed interface Rule {
fun accept(part: Part): Boolean
fun partition(partRanges: PartRanges): Pair<PartRanges, PartRanges>
data class Less(
val stat: String,
val value: Int,
) : Rule {
override fun accept(part: Part): Boolean {
return part.map.getOrDefault(stat, 0) < value
}
override fun partition(partRanges: PartRanges): Pair<PartRanges, PartRanges> {
val accept = mutableListOf<IntRange>()
val reject = mutableListOf<IntRange>()
partRanges.map.getOrDefault(stat, emptyList()).forEach { range ->
when {
range.first > value -> reject.add(range)
range.last < value -> accept.add(range)
else -> {
accept.add(range.first..<value)
reject.add(value..range.last)
}
}
}
val acceptParts = if (accept.isNotEmpty()) {
partRanges.copy(map = partRanges.map + (stat to accept))
} else {
PartRanges.EMPTY
}
val rejectParts = if (accept.isNotEmpty()) {
partRanges.copy(map = partRanges.map + (stat to reject))
} else {
PartRanges.EMPTY
}
return acceptParts to rejectParts
}
}
data class More(
val stat: String,
val value: Int,
) : Rule {
override fun accept(part: Part): Boolean {
return part.map.getOrDefault(stat, 0) > value
}
override fun partition(partRanges: PartRanges): Pair<PartRanges, PartRanges> {
val accept = mutableListOf<IntRange>()
val reject = mutableListOf<IntRange>()
partRanges.map.getOrDefault(stat, emptyList()).forEach { range ->
when {
range.first > value -> accept.add(range)
range.last < value -> reject.add(range)
else -> {
reject.add(range.first..value)
accept.add(value + 1..range.last)
}
}
}
val acceptParts = if (accept.isNotEmpty()) {
partRanges.copy(map = partRanges.map + (stat to accept))
} else {
PartRanges.EMPTY
}
val rejectParts = if (accept.isNotEmpty()) {
partRanges.copy(map = partRanges.map + (stat to reject))
} else {
PartRanges.EMPTY
}
return acceptParts to rejectParts
}
}
data object Always : Rule {
override fun accept(part: Part): Boolean = true
override fun partition(partRanges: PartRanges): Pair<PartRanges, PartRanges> {
return partRanges to PartRanges.EMPTY
}
}
}
data class Part(
val map: Map<String, Int>,
) {
val x: Int by map
val m: Int by map
val a: Int by map
val s: Int by map
}
data class PartRanges(
val map: Map<String, List<IntRange>>,
) {
val x: List<IntRange> by map
val m: List<IntRange> by map
val a: List<IntRange> by map
val s: List<IntRange> by map
companion object {
val EMPTY = PartRanges(
map = emptyMap(),
)
}
}
}
fun main() = SomeDay.mainify(Day19)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 6,643 | adventofcode | MIT License |
src/Day02.kt | iownthegame | 573,926,504 | false | {"Kotlin": 68002} | enum class Shape {
PAPER, SCISSORS, STONE, INVALID
}
enum class Outcome {
WIN, DRAW, LOSE, INVALID
}
class Round(private val shapeOfOpponent: Shape, private var suggestedShape: Shape?, private var outcome: Outcome?) {
private val scoreOfShape = mapOf(
Shape.PAPER to 2,
Shape.SCISSORS to 3,
Shape.STONE to 1
)
private val scoreOfOutcome = mapOf(
Outcome.WIN to 6,
Outcome.DRAW to 3,
Outcome.LOSE to 0
)
val score: Int
init {
outcome = calculateOutCome()
suggestedShape = calculateSuggestedShape()
score = calculateScore()
}
private fun calculateOutCome(): Outcome {
if (outcome != null) return outcome as Outcome
return when(shapeOfOpponent) {
Shape.PAPER -> {
when(suggestedShape) {
Shape.PAPER -> Outcome.DRAW
Shape.SCISSORS -> Outcome.WIN
Shape.STONE -> Outcome.LOSE
else -> Outcome.INVALID
}
}
Shape.SCISSORS -> {
when(suggestedShape) {
Shape.SCISSORS -> Outcome.DRAW
Shape.STONE -> Outcome.WIN
Shape.PAPER -> Outcome.LOSE
else -> Outcome.INVALID
}
}
Shape.STONE -> {
when(suggestedShape) {
Shape.STONE -> Outcome.DRAW
Shape.PAPER -> Outcome.WIN
Shape.SCISSORS -> Outcome.LOSE
else -> Outcome.INVALID
}
}
else -> Outcome.INVALID
}
}
private fun calculateSuggestedShape(): Shape {
if (suggestedShape != null) return suggestedShape as Shape
return when(shapeOfOpponent) {
Shape.PAPER -> {
when(outcome) {
Outcome.DRAW -> Shape.PAPER
Outcome.WIN -> Shape.SCISSORS
Outcome.LOSE -> Shape.STONE
else -> Shape.INVALID
}
}
Shape.SCISSORS -> {
when(outcome) {
Outcome.DRAW -> Shape.SCISSORS
Outcome.WIN -> Shape.STONE
Outcome.LOSE -> Shape.PAPER
else -> Shape.INVALID
}
}
Shape.STONE -> {
when(outcome) {
Outcome.DRAW -> Shape.STONE
Outcome.WIN -> Shape.PAPER
Outcome.LOSE -> Shape.SCISSORS
else -> Shape.INVALID
}
}
else -> Shape.INVALID
}
}
private fun calculateScore(): Int {
return scoreOfShape[suggestedShape]!! + scoreOfOutcome[outcome]!!
}
}
fun main() {
val shapeOfStrategyInput = mapOf(
"A" to Shape.STONE ,
"B" to Shape.PAPER ,
"C" to Shape.SCISSORS
)
fun calculateRoundsBySuggestedInput(input: List<String>): Array<Round> {
val shapeOfStrategyOutput = mapOf(
"X" to Shape.STONE ,
"Y" to Shape.PAPER ,
"Z" to Shape.SCISSORS
)
var rounds = arrayOf<Round>()
for (line in input) {
val splits = line.split(" ")
val shapeOfOpponent = shapeOfStrategyInput[splits.first()]!!
val suggestedShape = shapeOfStrategyOutput[splits.last()]!!
val round = Round(shapeOfOpponent, suggestedShape, null)
rounds += round
}
return rounds
}
fun calculateRoundsBySuggestedOutcome(input: List<String>): Array<Round> {
val outcomeOfStrategyOutput = mapOf(
"X" to Outcome.LOSE ,
"Y" to Outcome.DRAW ,
"Z" to Outcome.WIN
)
var rounds = arrayOf<Round>()
for (line in input) {
val splits = line.split(" ")
val shapeOfOpponent = shapeOfStrategyInput[splits.first()]!!
val suggestedOutCome = outcomeOfStrategyOutput[splits.last()]!!
val round = Round(shapeOfOpponent, null, suggestedOutCome)
rounds += round
}
return rounds
}
fun part1(input: List<String>): Int {
val rounds = calculateRoundsBySuggestedInput(input)
return rounds.sumOf { it.score }
}
fun part2(input: List<String>): Int {
val rounds = calculateRoundsBySuggestedOutcome(input)
return rounds.sumOf { it.score }
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day02_sample")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readTestInput("Day02")
println("part 1 result: ${part1(input)}")
println("part 2 result: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 4e3d0d698669b598c639ca504d43cf8a62e30b5c | 4,906 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/year2021/Day01.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2021
private fun part1(input: List<String>): Int {
val numbers = input.map { it.toInt() }
var count = 0
var previous = numbers[0]
for (number in numbers) {
if (number > previous) {
count++
}
previous = number
}
return count
}
private fun part2(input: List<String>): Int {
val numbers = input.map { it.toInt() }
val window = mutableListOf(numbers[0], numbers[1], numbers[3])
var previous = window.reduce { acc, i -> i + acc }
var count = 0
for (i in 3 until numbers.size) {
window.removeAt(0)
window.add(numbers[i])
val value = window.reduce { acc, n -> n + acc }
if (value > previous) {
count++
}
previous = value
}
return count
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 7)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 1,049 | advent-of-code | MIT License |
src/net/sheltem/aoc/y2023/Day04.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2023
import kotlin.math.pow
suspend fun main() {
Day04().run()
}
class Day04 : Day<Long>(13, 30) {
override suspend fun part1(input: List<String>): Long = input.indexWinners()
.sumOf { it.second.score() }
override suspend fun part2(input: List<String>): Long = input.indexWinners()
.map { it.first to it.second.count() }
.countCards()
}
private fun List<String>.indexWinners(): List<Pair<Int, List<Long>>> = toLotteryNumbers()
.mapIndexed { index, outerList ->
index to outerList.component2()
.filter { outerList.component1().contains(it) }
}
private fun List<String>.toLotteryNumbers(): List<List<List<Long>>> = this.map { line ->
line.substringAfter(":")
.split("|")
.map { it.trim() }
.map { it.split(" ").filter { it.isNotBlank() }.map { it.toLong() } }
.let { listOf(it.component1(), it.component2()) }
}
private fun List<Long>.score(): Long = if (isNotEmpty()) 2.toDouble().pow(size - 1).toLong() else 0
private fun List<Pair<Int, Int>>.countCards(): Long {
val cardCounts = this.associate { it.first to 1 }.toMutableMap()
for (index in 0..this.last().first) {
if (this[index].second > 0) cardCounts.addCards(index, this[index].second, cardCounts[index]!!)
}
return cardCounts.values.sum().toLong()
}
private fun MutableMap<Int, Int>.addCards(index: Int, rangeLength: Int, amountToAdd: Int): MutableMap<Int, Int> {
for (i in index + 1..(index + rangeLength)) {
this[i] = this[i]!! + amountToAdd
}
return this
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 1,598 | aoc | Apache License 2.0 |
src/day18/Parser.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day18
import readInput
import kotlin.math.absoluteValue
data class Dimensions (val min: Point, val max: Point) {
val cells: Int
get () {
val point = max.add (min.negate ()).add (Point (1, 1, 1))
val (x, y, z) = point
return x * y * z
}
fun contains (point: Point): Boolean {
val (x, y, z) = point
return x >= min.x && x <= max.x && y >= min.y && y <= max.y && z >= min.z && z <= max.z
}
override fun toString (): String = "$min x $max"
}
data class Point (val x: Int, val y: Int, val z: Int) {
fun min (other: Point) = Point (Math.min (x, other.x), Math.min (y, other.y), Math.min (z, other.z))
fun max (other: Point) = Point (Math.max (x, other.x), Math.max (y, other.y), Math.max (z, other.z))
override fun toString (): String = "($x, $y, $z)"
fun touches (points: List<Point>): Boolean {
for (point in points) {
if (touches (point)) {
return true
}
}
return false
}
fun touches (other: Point): Boolean {
val delta = add (other.negate ())
val (x, y, z) = delta
return (x.absoluteValue + y.absoluteValue + z.absoluteValue) == 1
}
fun negate () = Point (-x, -y, -z)
fun add (other: Point) = Point (x + other.x, y + other.y, z + other.z)
companion object {
val DIRECTIONS = mutableListOf<Point> ().apply {
for (i in listOf (-1, 1)) {
add (Point (i, 0, 0))
add (Point (0, i, 0))
add (Point (0, 0, i))
}
}
fun adjacencies (points: List<Point>): Int {
var total = 0
for (i in points) {
for (j in points) {
if (i != j && i.touches (j)) {
total ++
}
}
}
return total / 2
}
fun touches (list1: List<Point>, list2: List<Point>): Boolean {
for (p0 in list1) {
for (p1 in list2) {
if (p0.touches (p1)) {
return true
}
}
}
return false
}
}
}
data class Grid (val points: List<Point>) {
var min: Point = points[0]
var max: Point = points[0]
val bounds: Dimensions
get () = Dimensions (min, max)
val data = mutableMapOf<Point, Boolean> ()
init {
points.forEach {
set (it)
}
}
fun set (point: Point) {
data[point] = true
min = min.min (point)
max = max.max (point)
return
}
fun get (point: Point): Boolean {
return data[point] != null
}
fun visit (func: (Point) -> Unit) {
data.keys.forEach { func (it) }
return
}
fun dump () { println (toString ()) }
override fun toString (): String {
val buf = StringBuffer ()
buf.append ("${data.size} points, ${min} x ${max}\n")
data.keys.forEach {
buf.append (" - $it\n")
}
return buf.toString ()
}
}
fun loadGrid (example: Boolean): Grid {
val input = readInput (18, example)
val points = input.trim ().split ("\n").map {
val strs = it.split (",")
Point (strs[0].toInt(), strs[1].toInt (), strs[2].toInt ())
}
return Grid (points)
}
fun main (args: Array<String>) {
val example = true
val grid = loadGrid (example)
grid.dump ()
return
}
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 3,557 | advent_of_code_2022 | Apache License 2.0 |
src/Day01.kt | niltsiar | 572,887,970 | false | {"Kotlin": 16548} | fun main() {
fun part1(input: List<String>): Int {
return calculateCaloriesCarriedByElf(input)
.max()
}
fun part2(input: List<String>): Int {
return calculateCaloriesCarriedByElf(input)
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
fun calculateCaloriesCarriedByElf(input: List<String>): List<Int> {
return input.fold(listOf(0)) { acc, s ->
if (s.isBlank()) {
acc + 0
} else {
val newValueForAcc = acc.last() + s.toInt()
acc.dropLast(1) + newValueForAcc
}
}
}
| 0 | Kotlin | 0 | 0 | 766b3e168fc481e4039fc41a90de4283133d3dd5 | 884 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/filter.kt | knewjade | 382,342,162 | false | null | import common.tetfu.Tetfu
import common.tetfu.TetfuElement
import common.tetfu.TetfuPage
import common.tetfu.common.ColorConverter
import core.mino.MinoFactory
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.PrintWriter
import java.util.*
import kotlin.math.pow
data class Line(val index: Int, val pieces: String, val fumens: Set<String>)
data class Line2(val index: Int, val fumens: BitSet)
data class Solution(val fumen: String, val pieceBit: BitSet)
data class BitSize(val fumen: Int, val sequences: Int) {
}
fun toItem(index: Int, elements: List<String>): Line {
// [ツモ, 対応地形数, 使用ミノ, 未使用ミノ, テト譜]
val pieces = elements[0]
val fumens = elements[4].split(";").filter { it.isNotEmpty() }
assert(fumens.size == Integer.parseInt(elements[1]))
return Line(index, pieces, fumens.toSet())
}
fun BitSet.copy(): BitSet {
val copied = BitSet(this.size())
copied.or(this)
return copied
}
fun BitSet.invert(size: Int) {
this.flip(0, size)
}
fun candidatesToUncoveredPieceBit(solutions: List<Solution>, candidates: BitSet, sequencesSize: Int): BitSet {
val pieceBit = BitSet(sequencesSize)
candidates.stream().forEach {
pieceBit.or(solutions[it].pieceBit)
}
pieceBit.invert(sequencesSize)
return pieceBit
}
fun main(args: Array<String>) {
filterMain(args)
}
fun filterMain(args: Array<String>) {
val lines = File("path.csv").readLines().asSequence()
.drop(1)
.map { it.split(",") }
.filter { it.isNotEmpty() }
.mapIndexed { index, elements -> toItem(index, elements) }
.toList()
if (args.isEmpty()) {
val populationScale = 5.0
val childrenScale = 1.0
val mutationScale = 6.0 // < dimension
val maxGeneration = 300000
run(lines, Settings(populationScale, childrenScale, mutationScale, maxGeneration))
} else if (args[0] == "verify") {
val output = File("output.txt").readLines().asSequence()
.map { it.trim() }
.filter { it.isNotEmpty() }
.toList()
verify(lines, output)
} else if (args.size == 4) {
val populationScale = args[0].toDouble()
val childrenScale = args[1].toDouble()
val mutationScale = args[2].toDouble()
val maxGeneration = args[3].toInt()
run(lines, Settings(populationScale, childrenScale, mutationScale, maxGeneration))
}
}
fun verify(lines: List<Line>, answer: List<String>) {
val selected = answer.toSet()
val covered = lines.asSequence()
.filter { it.fumens.any { fumen -> selected.contains(fumen) } }
.count()
println("${answer.size} solutions")
val succeedSequences = lines.filter { it.fumens.isNotEmpty() }.count()
if (covered == succeedSequences) {
println("OK, all sequences are covered [covered sequences = $covered]")
} else {
println("### all sequences are NOT covered [covered sequences = $covered] ###")
}
val tetfu = Tetfu(MinoFactory(), ColorConverter())
val elements = selected.map { tetfu.decode(it.substring(5)) }
.fold(mutableListOf<TetfuPage>()) { acc, pages ->
val element = pages.first()
acc.add(element)
acc
}
.map {
TetfuElement(it.field, it.colorType, it.rotate, it.x, it.y, it.comment)
}
val data = tetfu.encode(elements)
println("http://fumen.zui.jp/?v115@$data")
}
fun run(lines_: List<Line>, settings: Settings) {
val lines = lines_.asSequence()
.filter { it.fumens.isNotEmpty() }
.mapIndexed { index, line -> Line(index, line.pieces, line.fumens) }
.toList()
val solutionsPre = lines.asSequence()
.map { it.fumens }
.flatMap { it.asSequence() }
.toSet()
.map { fumen ->
val bitSet = BitSet(lines.size)
lines.forEach {
if (it.fumens.contains(fumen)) {
bitSet.set(it.index)
}
}
Solution(fumen, bitSet)
}
.shuffled()
.toList()
val solutions = solutionsPre.asSequence()
.filter { solution ->
solutionsPre
.filter { solution.fumen != it.fumen }
.all {
val copied = solution.pieceBit.copy()
val same = it.pieceBit == copied
copied.and(it.pieceBit)
val isNotSubset = solution.pieceBit != copied
same || isNotSubset
}
}
.toList()
println("selected solutions = ${solutions.size}")
val fumenToSolutionIndex = solutions.asSequence()
.mapIndexed { index, bits -> bits.fumen to index }
.toMap()
assert(fumenToSolutionIndex.size == solutions.size)
val sequenceToLine2 = lines.asSequence()
.map { line ->
val fumens = BitSet(solutions.size)
line.fumens.forEach { fumen ->
fumenToSolutionIndex[fumen]?.let { fumens.set(it) }
}
Line2(line.index, fumens)
}
.toList()
val ga = GA(sequenceToLine2, solutions, BitSize(solutions.size, lines.size))
ga.run(settings)
}
data class Fitness(val gene: BitSet, val fitness: Double)
data class Settings(
val populationScale: Double, val childrenScale: Double,
val mutationScale: Double, val maxGeneration: Int
)
class GA(private val sequenceToLine2: List<Line2>, private val solutions: List<Solution>, private val size: BitSize) {
private val random = Random()
fun fix(copied1: BitSet) {
val uncovered = candidatesToUncoveredPieceBit(solutions, copied1, size.sequences)
if (uncovered.isEmpty) {
return
}
val requiredSolutions = BitSet(size.fumen)
uncovered.stream().forEach {
requiredSolutions.or(sequenceToLine2[it].fumens)
}
requiredSolutions.xor(copied1)
val requiredIndexList = Sequence { requiredSolutions.stream().iterator() }.toList().shuffled()
for (selected in requiredIndexList) {
copied1.set(selected)
val covered = solutions[selected].pieceBit.copy()
covered.invert(size.sequences)
uncovered.and(covered)
if (uncovered.isEmpty) {
return
}
}
assert(false)
}
fun run(settings: Settings) {
val dimension = size.fumen
val population = (1..(dimension * settings.populationScale).toInt()).map {
val gene = BitSet(dimension)
(0 until dimension).forEach { index ->
if (random.nextBoolean()) {
gene.set(index)
}
}
fix(gene)
to(gene)
}.toMutableList()
val mutate = 1.0 / dimension * settings.mutationScale
(1..settings.maxGeneration).forEach { generation ->
population.shuffle()
val children = (1..(dimension * settings.childrenScale).toInt()).map {
val mask1 = BitSet(dimension)
(0 until dimension).forEach { index ->
if (random.nextBoolean()) {
mask1.set(index)
}
}
val mask2 = mask1.copy()
mask2.invert(dimension)
val parent1 = random.nextInt(dimension + 1)
val copied1 = population[parent1].gene.copy()
copied1.and(mask1)
val parent2 = random.nextInt(dimension + 1)
val copied2 = population[parent2].gene.copy()
copied2.and(mask2)
copied1.or(copied2)
(0 until dimension).forEach { index ->
if (random.nextDouble() < mutate) {
copied1.flip(index)
}
}
fix(copied1)
copied1
}.toMutableList()
children.add(population[0].gene)
children.add(population[1].gene)
val results = children
.map { to(it) }
.sortedByDescending { it.fitness }
.toList()
val a = results
.mapIndexed { index, fitness -> index to fitness.fitness.pow(2) }
val sum = a.map { it.second }.sum()
val v = random.nextDouble() * sum
var roulette: Int? = null
run loop@{
var t = 0.0
a.forEach {
t += it.second
if (v < t) {
roulette = it.first
return@loop
}
}
}
assert(roulette != null)
population[0] = results[0]
population[1] = results[roulette!!]
if (generation % 100 == 0) {
println("---")
val sorted = population
.sortedByDescending { it.fitness }
.toList()
println(generation)
val average = sorted.map { it.fitness }.average()
println("average = $average")
val best = sorted.first()
best.let {
if (it.fitness < 1.0) {
println("best = ${it.fitness * 100} % covered")
} else {
println("best = ${it.gene.cardinality()} solutions")
}
}
val worst = sorted.last()
worst.let {
if (it.fitness < 1.0) {
println("worst = ${it.fitness * 100} % covered")
} else {
println("worst = ${it.gene.cardinality()} solutions")
}
}
val fumens = Sequence { best.gene.stream().iterator() }
.map { solutions[it] }
.map { it.fumen }
.sorted()
.toList()
val printWriter = PrintWriter(BufferedWriter(FileWriter("output.txt")))
printWriter.use { writer ->
fumens.forEach { writer.println(it) }
}
}
}
}
private fun to(gene: BitSet): Fitness {
return Fitness(gene, evaluate(gene))
}
private fun evaluate(bitSet: BitSet): Double {
val uncovered = candidatesToUncoveredPieceBit(solutions, bitSet, size.sequences).cardinality()
return if (0 < uncovered) {
1.0 - (uncovered.toDouble() / size.sequences)
} else {
size.fumen - bitSet.cardinality() + 1.0
}
}
} | 0 | Kotlin | 0 | 0 | ec7aeb05696abc2c59c4aa27033ea2bc35a5d6fe | 11,186 | path-filter | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2023/Day01.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2023
import se.saidaspen.aoc.util.*
fun main() = Day01.run()
object Day01 : Day(2023, 1) {
fun digits(input: String) = input.filter { it.isDigit() }.map { it.toString().toInt() }.toList()
override fun part1() = input.lines().sumOf { digits(it)[0] * 10 + digits(it)[digits(it).size - 1] }
override fun part2() = input.lines().sumOf { firstAndLastDigit(it) }
private fun firstAndLastDigit(s: String): Int {
val toInt = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "1", "2", "3", "4", "5", "6", "7", "8", "9")
val firstDigit = toInt.map { P(it, s.indexOf(it)) }.filter { it.second >= 0 }.minBy { it.second }.first
val lastDigit = toInt.map { P(it, s.lastIndexOf(it)) }.maxBy { it.second }.first
return (toInt.indexOf(firstDigit) % 9 + 1) * 10 + (toInt.indexOf(lastDigit) % 9 + 1)
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 904 | adventofkotlin | MIT License |
src/main/kotlin/g1301_1400/s1314_matrix_block_sum/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1301_1400.s1314_matrix_block_sum
// #Medium #Array #Matrix #Prefix_Sum #Dynamic_Programming_I_Day_14
// #2023_06_05_Time_235_ms_(100.00%)_Space_39_MB_(50.00%)
class Solution {
fun matrixBlockSum(mat: Array<IntArray>, k: Int): Array<IntArray> {
val rows = mat.size
val cols = mat[0].size
val prefixSum = Array(rows + 1) { IntArray(cols + 1) }
for (i in 1..rows) {
for (j in 1..cols) {
prefixSum[i][j] = (
(
mat[i - 1][j - 1] -
prefixSum[i - 1][j - 1]
) + prefixSum[i - 1][j] +
prefixSum[i][j - 1]
)
}
}
val result = Array(rows) { IntArray(cols) }
for (i in 0 until rows) {
for (j in 0 until cols) {
val iMin = Math.max(i - k, 0)
val iMax = Math.min(i + k, rows - 1)
val jMin = Math.max(j - k, 0)
val jMax = Math.min(j + k, cols - 1)
result[i][j] = (
(
prefixSum[iMin][jMin] +
prefixSum[iMax + 1][jMax + 1]
) - prefixSum[iMax + 1][jMin] -
prefixSum[iMin][jMax + 1]
)
}
}
return result
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,402 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/mantono/lingress/Spread.kt | mantono | 100,183,137 | false | null | package com.mantono.lingress
fun median(c: Collection<Number>): Double = c.asSequence().median()
fun mean(c: Collection<Number>): Double = c.map { it.toDouble() }.average()
fun range(c: Collection<Number>): Double = c.asSequence().range()
fun variance(c: Collection<Number>): Double = c.asSequence().variance()
fun standardDeviation(c: Collection<Number>): Double = Math.sqrt(variance(c))
fun Sequence<Number>.median(): Double
{
val size = this.asSequence().count()
val evenSize = size % 2 == 0
val elementsToDrop: Int = when(evenSize)
{
true -> ((size/2.0) - 1).toInt()
false -> size/2
}
return this.map { it.toDouble() }
.sorted()
.drop(elementsToDrop)
.take(if(evenSize) 2 else 1)
.average()
}
fun Sequence<Number>.range(): Double
{
val min: Double = map { it.toDouble() }.min() ?: 0.0
val max: Double = map { it.toDouble() }.max() ?: 0.0
return max - min
}
fun Sequence<Number>.variance(): Double
{
val doubleSequence: Sequence<Double> = map { it.toDouble() }
val mean = doubleSequence.average()
val sum = doubleSequence
.map { it - mean }
.map { Math.pow(it, 2.0) }
.sum()
return sum/count()
}
fun Sequence<Number>.standardDeviation(): Double = Math.sqrt(variance()) | 0 | Kotlin | 0 | 0 | 0c7cb0ff9b8feb946aea0d57538da8bd0423aada | 1,219 | linear-regression | MIT License |
LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/LetterCombinationsOfAPhoneNumber.kt | ani03sha | 297,402,125 | false | null | package org.redquark.tutorials.leetcode
fun letterCombinations(digits: String): List<String> {
// Resultant list
val combinations: MutableList<String> = mutableListOf()
// Base condition
if (digits.isEmpty()) {
return combinations
}
// Mappings of letters and numbers
val lettersAndNumbersMappings = arrayOf(
"Anirudh",
"is awesome",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
)
findCombinations(combinations, digits, StringBuilder(), 0, lettersAndNumbersMappings)
return combinations
}
fun findCombinations(combinations: MutableList<String>, digits: String, previous: StringBuilder, index: Int, lettersAndNumbersMappings: Array<String>) {
// Base condition for recursion to stop
if (index == digits.length) {
combinations.add(previous.toString())
return
}
// Get the letters corresponding to the current index of digits string
val letters = lettersAndNumbersMappings[digits[index] - '0']
// Loop through all the characters in the current combination of letters
for (c in letters.toCharArray()) {
findCombinations(combinations, digits, previous.append(c), index + 1, lettersAndNumbersMappings)
previous.deleteCharAt(previous.length - 1)
}
}
fun main() {
println(letterCombinations("23"))
println(letterCombinations(""))
println(letterCombinations("2"))
}
| 2 | Java | 40 | 64 | 67b6ebaf56ec1878289f22a0324c28b077bcd59c | 1,516 | RedQuarkTutorials | MIT License |
src/Day17.kt | fasfsfgs | 573,562,215 | false | {"Kotlin": 52546} | const val CHAMBER_WIDTH = 7
fun main() {
fun part1(input: String): Int {
return simulateChamber(input, 2022)
}
fun part2(input: String): Int {
return input.length
}
val testInput = readInputAsString("Day17_test")
check(part1(testInput) == 3068)
// check(part2(testInput) == 0)
val input = readInputAsString("Day17")
println(part1(input))
// println(part2(input))
}
fun simulateChamber(input: String, numberOfRocks: Int): Int {
val restedRocks = List(CHAMBER_WIDTH) { Pos(it, 0) }.toMutableSet()
val jetProducer = JetProducer.build(input)
val rockProducer = RockProducer.build()
repeat(numberOfRocks) {
dropRock(restedRocks, rockProducer.getNext(), jetProducer)
}
return restedRocks.highest()
}
fun dropRock(restedRocks: MutableSet<Pos>, rock: Rock, jetProducer: JetProducer) {
var rockFalling = rock.movedX(2).movedY(restedRocks.highest() + 4)
var rockRested = false
while (!rockRested) {
val jet = jetProducer.getNext()
rockFalling = rockFalling.movedX(restedRocks, jet)
if (rockFalling.canFall(restedRocks))
rockFalling = rockFalling.movedY(-1)
else
rockRested = true
}
restedRocks.addAll(rockFalling.pieces)
}
fun Set<Pos>.highest() = maxOf { it.y }
enum class Jet { LEFT, RIGHT }
class JetProducer(private val jets: List<Jet>) {
private var nextIndex = 0
companion object {
fun build(input: String): JetProducer {
val jets = input.map { if (it == '>') Jet.RIGHT else Jet.LEFT }
return JetProducer(jets)
}
}
fun getNext(): Jet {
if (nextIndex > jets.lastIndex) nextIndex = 0
return jets[nextIndex++]
}
}
data class Pos(val x: Int, val y: Int)
data class Rock(val pieces: Set<Pos>) {
constructor(vararg pieces: Pos) : this(pieces.toSet())
fun movedX(restedRocks: Set<Pos>, jet: Jet): Rock {
val imaginaryRock = if (jet == Jet.LEFT) movedX(-1) else movedX(1)
val isRockOutOfChamber = imaginaryRock.pieces
.map { it.x }
.any { it !in (0 until CHAMBER_WIDTH) }
if (isRockOutOfChamber)
return this
if (imaginaryRock.pieces.intersect(restedRocks).isNotEmpty())
return this
return imaginaryRock
}
fun movedX(delta: Int): Rock {
val newPieces = pieces.map { it.copy(x = it.x + delta) }.toSet()
return Rock(newPieces)
}
fun movedY(delta: Int): Rock {
val newPieces = pieces.map { it.copy(y = it.y + delta) }.toSet()
return Rock(newPieces)
}
fun canFall(levelHeight: Set<Pos>): Boolean {
val imaginaryRock = this.movedY(-1)
return imaginaryRock.pieces.intersect(levelHeight).isEmpty()
}
}
class RockProducer(private val rocks: List<Rock>) {
private var nextIndex = 0
constructor(vararg rocks: Rock) : this(rocks.toList())
companion object {
fun build(): RockProducer {
val rock0 = Rock(
Pos(0, 0), // ####
Pos(1, 0),
Pos(2, 0),
Pos(3, 0)
)
val rock1 = Rock(
Pos(1, 0), // .#.
Pos(1, 0), // ###
Pos(0, 1), // .#.
Pos(1, 1),
Pos(2, 1),
Pos(1, 2)
)
val rock2 = Rock(
Pos(0, 0), // ..#
Pos(1, 0), // ..#
Pos(2, 0), // ###
Pos(2, 1),
Pos(2, 2)
)
val rock3 = Rock(
Pos(0, 0), // #
Pos(0, 1), // #
Pos(0, 2), // #
Pos(0, 3) // #
)
val rock4 = Rock(
Pos(0, 0), // ##
Pos(1, 0), // ##
Pos(0, 1),
Pos(1, 1)
)
return RockProducer(rock0, rock1, rock2, rock3, rock4)
}
}
fun getNext(): Rock {
if (nextIndex > rocks.lastIndex) nextIndex = 0
return rocks[nextIndex++]
}
}
| 0 | Kotlin | 0 | 0 | 17cfd7ff4c1c48295021213e5a53cf09607b7144 | 4,155 | advent-of-code-2022 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions33.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
fun test33() {
printlnResult(5, 7, 6, 9, 11, 10, 8) // true
printlnResult(5, 7, 6, 11, 10, 8) // true
printlnResult(7, 4, 6, 5) // false
printlnResult(5, 6, 11, 10, 8) // true
printlnResult(5, 7, 6, 10, 8) // false
printlnResult(5, 6, 10, 8, 7) // true
}
/**
* Questions33-1: Input an array, judge whether the array is the post order of a binary search tree
*/
private fun <T : Comparable<T>> Array<T>.isPostOrder(): Boolean {
if (isEmpty()) return false
val mid = getMidIndex(0, lastIndex)
return mid >= 0 && isPostOrder(0, lastIndex, mid)
}
private fun <T : Comparable<T>> Array<T>.isPostOrder(startIndex: Int, endIndex: Int, mid: Int): Boolean {
if ((startIndex until mid).any { this[it] > this[endIndex] })
return false
if ((mid until endIndex).any { this[it] < this[endIndex] })
return false
return isSubArrayPostOrder(startIndex, mid - 1) && isSubArrayPostOrder(mid, endIndex - 1)
}
private fun <T : Comparable<T>> Array<T>.isSubArrayPostOrder(startIndex: Int, endIndex: Int): Boolean {
if (startIndex == endIndex || endIndex - startIndex == 1)
return true
val mid = getMidIndex(startIndex, endIndex)
return mid >= 0 && isPostOrder(startIndex, endIndex, mid)
}
private fun <T : Comparable<T>> Array<T>.getMidIndex(startIndex: Int, endIndex: Int): Int {
val thisSize = endIndex - startIndex + 1
val half = thisSize shr 1
if (thisSize % 2 == 1)
return half + startIndex
val root = this[endIndex]
return if (this[half] > root) {
(if (this[half - 1] < root) half else half - 1) + startIndex
} else -1
}
private fun printlnResult(vararg elements: Int) =
println("Is the array: ${elements.toList()} post order of a binary search tree: ${elements.toTypedArray().isPostOrder()}") | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,852 | Algorithm | Apache License 2.0 |
src/main/kotlin/io/github/ajoz/puzzles/Day03.kt | ajoz | 574,043,593 | false | {"Kotlin": 21275} | package io.github.ajoz.puzzles
import io.github.ajoz.utils.firstRepeatingCharFrom
import io.github.ajoz.utils.halfs
import io.github.ajoz.utils.readInput
/**
--- Day 3: Rucksack Reorganization ---
One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that
Elf didn't quite follow the packing instructions, and so a few items now need to be rearranged.
Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two
compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.
The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help
finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to
different types of items).
The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same
number of items in each of its two compartments, so the first half of the characters represent items in the first
compartment, while the second half of the characters represent items in the second compartment.
*/
fun main() {
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
/**
* --- Part One ---
*
* For example, suppose you have the following list of contents from six rucksacks:
*
* vJrwpWtwJgWrhcsFMMfFFhFp
* jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
* PmmdzqPrVvPwwTWBwg
* wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
* ttgJtRGJQctTZtZT
* CrZsJsPPZsGzwwsLwLmpwMDw
*
* The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the
* items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears
* in both compartments is lowercase p.
* The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears
* in both compartments is uppercase L.
* The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P.
* The fourth rucksack's compartments only share item type v.
* The fifth rucksack's compartments only share item type t.
* The sixth rucksack's compartments only share item type s.
*
* To help prioritize item rearrangement, every item type can be converted to a priority:
*
* Lowercase item types a through z have priorities 1 through 26.
* Uppercase item types A through Z have priorities 27 through 52.
*
* In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p),
* 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.
*
* Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those
* item types?
*/
private fun part1(input: List<String>): Int {
return input.fold(0) { prioritySum, inputLine ->
val (firstCompartment, secondCompartment) = inputLine.halfs()
val priority = getPriority(firstCompartment.firstRepeatingCharFrom(secondCompartment))
prioritySum + priority
}
}
/**
* --- Part Two ---
*
* As you finish identifying the misplaced items, the Elves come to you with another issue.
*
* For safety, the Elves are divided into groups of three. Every Elf carries a badge that identifies their group.
* For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves.
* That is, if a group's badge is item type B, then all three Elves will have item type B somewhere in their rucksack,
* and at most two of the Elves will be carrying any other item type.
*
* The problem is that someone forgot to put this year's updated authenticity sticker on the badges. All of the badges
* need to be pulled out of the rucksacks so the new authenticity stickers can be attached.
*
* Additionally, nobody wrote down which item type corresponds to each group's badges. The only way to tell which item
* type is the right one is by finding the one item type that is common between all three Elves in each group.
*
* Every set of three lines in your list corresponds to a single group, but each group can have a different badge item
* type. So, in the above example, the first group's rucksacks are the first three lines:
*
* vJrwpWtwJgWrhcsFMMfFFhFp
* jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
* PmmdzqPrVvPwwTWBwg
*
* And the second group's rucksacks are the next three lines:
*
* wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
* ttgJtRGJQctTZtZT
* CrZsJsPPZsGzwwsLwLmpwMDw
*
* In the first group, the only item type that appears in all three rucksacks is lowercase r; this must be their badges.
* In the second group, their badge item type must be Z.
*
* Priorities for these items must still be found to organize the sticker attachment efforts: here, they are 18 (r) for
* the first group and 52 (Z) for the second group. The sum of these is 70.
*
* Find the item type that corresponds to the badges of each three-Elf group. What is the sum of the priorities of
* those item types?
*/
private fun part2(input: List<String>): Int {
return input.windowed(size = 3, step = 3).fold(0) { prioritySum, racksacks ->
val (first, second, third) = racksacks
val priority = getPriority(first.firstRepeatingCharFrom(second, third))
prioritySum + priority
}
}
val alphabet = listOf(
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z"
)
fun getPriority(itemType: String): Int =
when {
itemType.first().isLowerCase() -> alphabet.indexOf(itemType) + 1
else -> alphabet.indexOf(itemType.first().lowercase()) + 27
}
| 0 | Kotlin | 0 | 0 | 6ccc37a4078325edbc4ac1faed81fab4427845b8 | 6,051 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/problems/day6/part2/part2.kt | klnusbaum | 733,782,662 | false | {"Kotlin": 43060} | package problems.day6.part2
import java.io.File
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
private const val inputFile = "input/day6/input.txt"
//const val testFile = "input/day6/test.txt"
fun main() {
val numberOfBeats = File(inputFile).bufferedReader().useLines { multiplyNumBeats(it) }
println("The number of ways to be the current max is: $numberOfBeats")
}
private fun multiplyNumBeats(lines: Sequence<String>): Long {
val iterator = lines.iterator()
val time = iterator.next().toTime()
val maxes = iterator.next().toMax()
return Race(time, maxes).numBeats()
}
private fun String.toTime(): Long {
return this.substringAfter("Time: ")
.replace(" ","")
.toLong()
}
private fun String.toMax(): Long {
return this.substringAfter("Distance: ")
.replace(" ","")
.toLong()
}
private data class Race(val time: Long, val currentMax: Long) {
fun numBeats(): Long {
val a = -1
val b = time
val c = -currentMax
val discriminant = sqrt(((b * b) - (4.0 * a * c)))
val low = (-b + discriminant) / (2 * a)
val high = (-b - discriminant) / (2 * a)
val flooredHigh = floor(high)
val ceiledLow = ceil(low)
var numBeats = (flooredHigh - ceiledLow).toLong() + 1
if (flooredHigh == high) {
numBeats--
}
if (ceiledLow == low) {
numBeats--
}
return numBeats
}
}
| 0 | Kotlin | 0 | 0 | d30db2441acfc5b12b52b4d56f6dee9247a6f3ed | 1,490 | aoc2023 | MIT License |
src/Day11.kt | vladislav-og | 573,326,483 | false | {"Kotlin": 27072} | fun main() {
fun extractNumbers(input: String): MutableList<String> {
val regex = Regex("\\d+")
return regex.findAll(input).map { c -> c.value }.toMutableList()
}
fun extractMonkeysInitialData(input: List<String>): Pair<HashMap<Int, HashMap<String, MutableList<String>>>, MutableList<Int>> {
val monkeysItemCount = mutableListOf<Int>()
val monkeys = hashMapOf<Int, HashMap<String, MutableList<String>>>()
var curMonkey = -1
for (row in input) {
if (row.isBlank()) {
continue
}
if (row.startsWith("Monkey")) {
curMonkey++
monkeysItemCount.add(0)
monkeys[curMonkey] = hashMapOf()
} else {
val trimmedInput = row.trim()
if (trimmedInput.startsWith("S")) {
monkeys[curMonkey]!!["items"] = extractNumbers(row)
} else if (trimmedInput.startsWith("O")) {
val number = trimmedInput.substring(23)
val operation = trimmedInput.substring(21, 22)
monkeys[curMonkey]!!["operation"] = mutableListOf(operation, number)
} else if (trimmedInput.startsWith("T")) {
monkeys[curMonkey]!!["divisible"] = mutableListOf(trimmedInput.substring(19))
} else if (trimmedInput.startsWith("If t")) {
monkeys[curMonkey]!!["true"] = mutableListOf(trimmedInput.substring(25))
} else if (trimmedInput.startsWith("If f")) {
monkeys[curMonkey]!!["false"] = mutableListOf(trimmedInput.substring(26))
}
}
}
return Pair(monkeys, monkeysItemCount)
}
fun getWorryLevel(operation: MutableList<String>, item: String, divider: Int): Long {
val worryLevel = when (operation[0]) {
"*" -> {
if (operation[1] == "old") {
item.toLong() * item.toLong()
} else {
item.toLong() * operation[1].toLong()
}
}
"+" -> {
item.toLong() + operation[1].toLong()
}
else -> 0L
}
return if (divider == 3) worryLevel / 3 else worryLevel % divider
}
fun runGame(monkeys: HashMap<Int, HashMap<String, MutableList<String>>>, monkeysItemCount: MutableList<Int>, commonModulus: Int, rounds: Int) {
for (i in 1..rounds) {
for (j in 0 until monkeys.size) {
for (item in monkeys[j]!!["items"]!!) {
monkeysItemCount[j] = monkeysItemCount[j] + 1
val operation = monkeys[j]!!["operation"]!!
val worryLevel = getWorryLevel(operation, item, commonModulus)
if (worryLevel % monkeys[j]!!["divisible"]!![0].toInt() == 0L) {
val monkeyToPassItem = monkeys[j]!!["true"]!![0]
monkeys[monkeyToPassItem.toInt()]!!["items"]!!.add(worryLevel.toString())
} else {
val monkeyToPassItem = monkeys[j]!!["false"]!![0]
monkeys[monkeyToPassItem.toInt()]!!["items"]!!.add(worryLevel.toString())
}
}
monkeys[j]!!["items"] = mutableListOf()
}
}
}
fun part1(input: List<String>): Long {
val (monkeys, monkeysItemCount) = extractMonkeysInitialData(input)
runGame(monkeys, monkeysItemCount, 3, 20)
monkeysItemCount.sort()
return monkeysItemCount[monkeysItemCount.size - 1].toLong() * monkeysItemCount[monkeysItemCount.size - 2].toLong()
}
fun part2(input: List<String>): Long {
val (monkeys, monkeysItemCount) = extractMonkeysInitialData(input)
val commonModulus = monkeys.values.map { it["divisible"]!![0].toInt() }
.reduce { acc, it -> if (acc % it == 0) acc else acc * it }
runGame(monkeys, monkeysItemCount, commonModulus, 10000)
monkeysItemCount.sort()
return monkeysItemCount[monkeysItemCount.size - 1].toLong() * monkeysItemCount[monkeysItemCount.size - 2].toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
// println(part1(testInput))
check(part1(testInput) == 10605L)
// println(part2(testInput))
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
// println(part1(input))
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b230ebcb5705786af4c7867ef5f09ab2262297b6 | 4,064 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/Exercise18.kt | cortinico | 317,667,457 | false | null | fun main() {
object {}
.javaClass
.getResource("input-18.txt")
.readText()
.split("\n")
.map { it.replace(" ", "") }
.sumOf { evaluate(it, 0) }
.also(::println)
}
fun evaluate(input: String, partial: Long): Long =
when {
input.isEmpty() -> partial
input[0] in '0'..'9' ->
evaluate(input.drop(1), Character.getNumericValue(input[0]).toLong())
input[0] == '(' -> {
val end = findClosingParenthesis(input, 0)
val parenthesis = evaluate(input.substring(1, end), 0)
evaluate(input.substring(end + 1), parenthesis)
}
input[0] == '+' || input[0] == '*' -> {
val op: Long.(Long) -> Long = if (input[0] == '+') Long::plus else Long::times
if (input[1].isDigit()) {
evaluate(input.drop(2), partial.op(Character.getNumericValue(input[1]).toLong()))
} else {
val end = findClosingParenthesis(input, 1)
val parenthesis = evaluate(input.substring(2, end), 0)
evaluate(input.substring(end + 1), partial.op(parenthesis))
}
}
else -> partial
}
fun findClosingParenthesis(input: String, start: Int): Int {
var count = 1
var i = start + 1
while (i < input.length) {
when (input[i]) {
'(' -> count++
')' -> count--
}
if (count == 0) break
i++
}
return i
}
| 1 | Kotlin | 0 | 4 | a0d980a6253ec210433e2688cfc6df35104aa9df | 1,499 | adventofcode-2020 | MIT License |
src/main/kotlin/com/dkanen/graphmapnav/collections/graphs/Dijkstra.kt | prufrock | 662,847,778 | false | {"Kotlin": 284337} | package com.dkanen.graphmapnav.collections.graphs
import com.dkanen.graphmapnav.collections.queues.ComparatorPriorityQueueImpl
/**
* Finds the shortest paths from a given node.
*/
class Dijkstra<T: Any>(private val graph: AdjacencyList<T>) {
/**
* Follows route from the destination to the start.
*/
private fun route(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): ArrayList<Edge<T>> {
var vertex = destination // The vertex expected to be reached.
val path = arrayListOf<Edge<T>>() // The edges followed to get to the vertex.
loop@ while (true) {
val visit = paths[vertex] ?: break
when(visit.type) {
// As long as there is a path with valid edges
VisitType.EDGE -> visit.edge?.let {
// Add the edge to the path.
path.add(it)
// Use the `source` of the edge as the path to the next vertex to follow.
vertex = it.source
}
// End the loop once it reaches the START
VisitType.START -> break@loop
}
}
return path
}
/**
* Calculate the cost of getting to the destination by working backwards from the destination
* to the start. Then add up all the weights.
*/
private fun distance(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): Double {
val path = route(destination, paths)
return path.sumOf { it.weight ?: 0.0 }
}
/**
* Finds the shortest path from the start to all the vertices in the graph.
* Time complexity: O(E log V) because all edges need to be traversed and managing the priority is O(log V)
*/
fun shortestPath(start: Vertex<T>): HashMap<Vertex<T>, Visit<T>> {
// Create `paths` with the start vertex
val paths: HashMap<Vertex<T>, Visit<T>> = HashMap()
paths[start] = Visit(VisitType.START)
// Whichever path is smaller goes to the front of the priority queue.
// min-priority queue
val distanceComparator = Comparator<Vertex<T>> { first, second ->
(distance(second, paths) - distance(first, paths)).toInt()
}
val priorityQueue = ComparatorPriorityQueueImpl(distanceComparator)
priorityQueue.enqueue(start)
while (true) {
// always take the shortest path because Dijkstra is greedy
val vertex = priorityQueue.dequeue() ?: break
val edges = graph.edges(vertex)
// examine all the edges before examining the child's edges (bfs)
edges.forEach {
// if an edge doesn't have a weight don't consider it.
val weight = it.weight ?: return@forEach
// Add the path if it hasn't been visited before.
// OR
// Add the path destination if the path is less than an existing path to that destination.
// Is there a way to not check the distance every time? Cache the calculated distances?
if (paths[it.destination] == null
|| distance(vertex, paths) + weight < distance(it.destination, paths)) {
paths[it.destination] = Visit(VisitType.EDGE, it)
// enqueue this shortest path so it can keep being greedy
priorityQueue.enqueue(it.destination)
// then go back around again!
}
}
}
return paths
}
/**
* Returns the shortest path to the given vertex.
*/
fun shortestPath(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): ArrayList<Edge<T>> {
return route(destination, paths)
}
fun getAllShortestPath(source: Vertex<T>): HashMap<Vertex<T>, ArrayList<Edge<T>>> {
val paths = HashMap<Vertex<T>, ArrayList<Edge<T>>>()
// Find all the paths from the source.
val pathsFromSource = shortestPath(source)
// Look through each of the edges to find the path, if it exists, to the source.
graph.allVertices.forEach {
if (it != source) {
val path = shortestPath(it, pathsFromSource)
if (path.isNotEmpty()) {
paths[it] = path
}
}
}
return paths
}
}
class Visit<T: Any>(val type: VisitType, val edge: Edge<T>? = null)
enum class VisitType {
START, // The vertex is the starting edge
EDGE // The vertex has an edge that leads back to START
} | 0 | Kotlin | 0 | 1 | 55ebc6120b97a9c2c3d86b9d67c4cb97186a30f7 | 4,607 | graphmapnav | MIT License |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day14/Day14.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day14
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2023.DayOf2023
/**
* See [Year 2023, Day 14](https://adventofcode.com/2023/day/14)
*/
object Day14 : DayOf2023(14) {
override fun first(): Any? {
val shifted = matrix.transpose().shiftLeft()
return shifted.transpose().northLoad()
}
override fun second(): Any? {
val seen = mutableMapOf<List<List<Char>>, Int>()
val rev = mutableMapOf<Int, List<List<Char>>>()
var curr = matrix
var step = 0
while (curr !in seen) {
rev[step] = curr
seen[curr] = step
step++
val north = curr.transpose().shiftLeft().transpose()
val west = north.shiftLeft()
val south = west.transpose().flip().shiftLeft().flip().transpose()
curr = south.flip().shiftLeft().flip()
}
val head = seen.getValue(curr)
val loop = step - head
val tail = (1000000000 - head) % loop
val final = rev.getValue(head + tail)
return final.northLoad()
}
private fun List<List<Char>>.transpose(): List<List<Char>> {
return List(first().size) { row ->
List(size) { column -> this[column][row] }
}
}
private fun List<List<Char>>.northLoad(): Int {
return mapIndexed { y, row ->
(size - y) * row.count { it == 'O' }
}.sum()
}
private fun List<List<Char>>.shiftLeft() = map { row ->
val total = StringBuilder()
val round = StringBuilder()
"#$row".reversed().forEach { char ->
when (char) {
'.' -> total.append(char)
'O' -> round.append(char)
'#' -> {
total.append(round).append(char)
round.setLength(0)
}
}
}
total.setLength(total.length - 1)
total.reverse().toList()
}
private fun List<List<Char>>.flip() = map { it.asReversed() }
}
fun main() = SomeDay.mainify(Day14)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,862 | adventofcode | MIT License |
src/Day03.kt | buczebar | 572,864,830 | false | {"Kotlin": 39213} | fun main() {
fun Char.getPriority() =
(('a'..'z') + ('A'..'Z')).indexOf(this) + 1
fun part1(input: List<String>) =
input.map { sack -> sack.chunked(sack.length / 2).map { comp -> comp.toList() } }
.map { (comp1, comp2) -> (comp1 intersect comp2.toSet()).single() }
.sumOf { it.getPriority() }
fun part2(input: List<String>) =
input.chunked(3)
.map { (a, b, c) -> (a.toSet() intersect b.toSet() intersect c.toSet()).single() }
.sumOf { it.getPriority() }
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cdb6fe3996ab8216e7a005e766490a2181cd4101 | 744 | advent-of-code | Apache License 2.0 |
src/main/kotlin/aoc19/Day12.kt | tahlers | 225,198,917 | false | null | package aoc19
import io.vavr.collection.HashSet
import io.vavr.collection.Stream
import io.vavr.collection.Vector
import java.util.Arrays
import kotlin.math.abs
object Day12 {
data class Vec(val x: Int, val y: Int, val z: Int) {
operator fun plus(other: Vec): Vec = Vec(x + other.x, y + other.y, z + other.z)
fun abs(): Int = abs(x) + abs(y) + abs(z)
}
data class Moon(val pos: Vec, val velocity: Vec = Vec(0, 0, 0)) {
fun energy(): Int = pos.abs() * velocity.abs()
fun updateWithGravity(others: Vector<Moon>): Moon {
val deltaVelocities = others.remove(this).map { moon ->
Vec(
deltaV(pos.x, moon.pos.x),
deltaV(pos.y, moon.pos.y),
deltaV(pos.z, moon.pos.z)
)
}
val newVelocity = deltaVelocities.fold(velocity, Vec::plus)
val newPos = pos + newVelocity
return Moon(newPos, newVelocity)
}
}
private fun deltaV(a: Int, b: Int): Int {
return when {
a < b -> 1
a > b -> -1
else -> 0
}
}
fun updateMoons(moons: Vector<Moon>): Stream<Vector<Moon>> {
val stepStream = Stream.iterate(moons) { it.map { moon -> moon.updateWithGravity(it) } }
return stepStream
}
fun Vector<Moon>.energy() = this.map { it.energy() }.sum().toInt()
enum class Axis { X, Y, Z }
private fun repeatAxisAfter(moons: Vector<Moon>, axis: Axis): Long {
Stream.from(0L).fold(moons to HashSet.empty<Vector<Pair<Int, Int>>>()) { (currentMoons, set), count ->
val updated = currentMoons.map { it.updateWithGravity(currentMoons) }
val updatedAxis = when (axis) {
Axis.X -> updated.map { it.pos.x to it.velocity.x }
Axis.Y -> updated.map { it.pos.y to it.velocity.y }
Axis.Z -> updated.map { it.pos.z to it.velocity.z }
}
if (set.contains(updatedAxis)) return count
updated to set.add(updatedAxis)
}
return -1
}
fun repeatAfter(moons: Vector<Moon>): Long {
val repeatXCount = repeatAxisAfter(moons, Axis.X)
val repeatYCount = repeatAxisAfter(moons, Axis.Y)
val repeatZCount = repeatAxisAfter(moons, Axis.Z)
return lcm(repeatXCount, repeatYCount, repeatZCount)
}
private fun gcd(x: Long, y: Long): Long {
return if (y == 0L) x else gcd(y, x % y)
}
private fun lcm(vararg numbers: Long): Long {
return Arrays.stream(numbers).reduce(1L) { x, y -> x * (y / gcd(x, y)) }
}
} | 0 | Kotlin | 0 | 0 | dae62345fca42dd9d62faadf78784d230b080c6f | 2,654 | advent-of-code-19 | MIT License |
src/main/kotlin/g1001_1100/s1092_shortest_common_supersequence/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1001_1100.s1092_shortest_common_supersequence
// #Hard #String #Dynamic_Programming #2023_06_02_Time_174_ms_(100.00%)_Space_37.9_MB_(100.00%)
class Solution {
fun shortestCommonSupersequence(str1: String, str2: String): String {
val m = str1.length
val n = str2.length
val dp = Array(m + 1) { IntArray(n + 1) }
for (i in 0..m) {
for (j in 0..n) {
if (i == 0) {
dp[i][j] = j
} else if (j == 0) {
dp[i][j] = i
} else if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1]
} else {
dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1])
}
}
}
// Length of the ShortestSuperSequence
var l = dp[m][n]
val arr = CharArray(l)
var i = m
var j = n
while (i > 0 && j > 0) {
/* If current character in str1 and str2 are same, then
current character is part of shortest supersequence */
if (str1[i - 1] == str2[j - 1]) {
arr[--l] = str1[i - 1]
i--
j--
} else if (dp[i - 1][j] < dp[i][j - 1]) {
arr[--l] = str1[i - 1]
i--
} else {
arr[--l] = str2[j - 1]
j--
}
}
while (i > 0) {
arr[--l] = str1[i - 1]
i--
}
while (j > 0) {
arr[--l] = str2[j - 1]
j--
}
return String(arr)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,641 | LeetCode-in-Kotlin | MIT License |
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/search/BinarySearch.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1728251} | package dev.funkymuse.datastructuresandalgorithms.search
/**
* Binary stringSearch, assumes that the list is sorted.
* Splits the list in half with every single iteration, bringing the worst case running time to O(log n)
*
* Time complexity per case:
* Best - O(1), constant. In case the element is in the very middle.
* Average, Worst - O(log n), logarithmic.
*/
fun <T : Comparable<T>> binarySearch(list: List<T>, value: T, startIndex: Int = 0, endIndex: Int = list.size - 1): Int {
if (endIndex >= startIndex) {
val mid = (startIndex + endIndex) / 2
when {
list[mid] == value -> return mid
list[mid] < value -> return binarySearch(list, value, mid + 1, endIndex)
list[mid] > value -> return binarySearch(list, value, startIndex, mid - 1)
}
}
return -1
}
fun <T : Comparable<T>> ArrayList<T>.binarySearch(value: T, range: IntRange = indices): Int? {
if (range.first > range.last) {
return null
}
val size = range.last - range.first + 1
val middle = range.first + size / 2
return when {
this[middle] == value -> middle
this[middle] > value -> binarySearch(value, range.first until middle)
else -> binarySearch(value, (middle + 1)..range.last)
}
} | 0 | Kotlin | 92 | 771 | e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1 | 1,296 | KAHelpers | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[78]子集.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.util.*
import kotlin.collections.ArrayList
//给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
//
// 解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
//
//
//
// 示例 1:
//
//
//输入:nums = [1,2,3]
//输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
//
//
// 示例 2:
//
//
//输入:nums = [0]
//输出:[[],[0]]
//
//
//
//
// 提示:
//
//
// 1 <= nums.length <= 10
// -10 <= nums[i] <= 10
// nums 中的所有元素 互不相同
//
// Related Topics 位运算 数组 回溯
// 👍 1275 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun subsets(nums: IntArray): List<List<Int>> {
//递归 回溯
//使用栈来最为中间保存数组
val res = ArrayList<ArrayList<Int>>()
dfs(0,nums.size,nums, LinkedList<Int>(),res)
return res
}
private fun dfs(index: Int, numLen: Int, nums: IntArray, tempStack: LinkedList<Int>, res: java.util.ArrayList<java.util.ArrayList<Int>>) {
//递归结束条件
if(index == numLen){
//从零开始 空数组也算
res.add(ArrayList(tempStack))
return
}
//逻辑处理
dfs(index+1,numLen,nums,tempStack, res)
//取数字
tempStack.addLast(nums[index])
dfs(index+1,numLen,nums,tempStack, res)
//不符合回溯
tempStack.removeLast()
//数据reverse
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,630 | MyLeetCode | Apache License 2.0 |
08/kotlin/src/main/kotlin/se/nyquist/Decoder.kt | erinyq712 | 437,223,266 | false | {"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098} | package se.nyquist
class Decoder {
private val validCombinations = Digit.values().map { it.representation }
private val value = "abcdefg"
private val valueArray : List<String> = IntRange(0, value.length-1).map{value.substring(it,it+1)}.toList()
private val permutations : List<List<String>> = allPermutations(valueArray)
fun hasDecoded(): Boolean {
return true
}
fun decode(input: List<String>, output: List<String>): Int {
for(permutation in permutations) {
if (validate(permutation, input)) {
println(permutation.joinToString(""))
return encode(output, permutation).map { it.toInt() }.joinToString("").toInt()
}
}
return Int.MIN_VALUE
}
fun encode(input: List<String>, permutation: List<String>): List<Digit> {
val translation = getTranslationMap(permutation)
return input.map { getDigits(it, translation) }.toList()
}
private fun getDigits(
input: String,
translation: Map<String, String>
) : Digit {
val digits = getDigit(IntRange(0, input.length - 1).map { translation[input.substring(it, it + 1)] }.sortedBy { it }.joinToString(""))
println(digits)
return digits
}
private fun getTranslationMap(permutation: List<String>) : Map<String, String> {
val translation = mutableMapOf<String, String>()
IntRange(0, value.length - 1).map { translation.put(permutation[it], valueArray[it]) }
return translation
}
private fun validate(permutation: List<String>, samples: List<String>) : Boolean {
val translation = getTranslationMap(permutation)
val valid = samples.all { input ->
val translated : String = IntRange(0, input.length-1).map{ translation[ input.substring(it,it+1) ] }.sortedBy { it }.joinToString("")
validCombinations.contains(translated)
}
return valid
}
} | 0 | Kotlin | 0 | 0 | b463e53f5cd503fe291df692618ef5a30673ac6f | 1,967 | adventofcode2021 | Apache License 2.0 |
src/main/kotlin/days/Day12.kt | jgrgt | 433,952,606 | false | {"Kotlin": 113705} | package days
import util.MutableTree
import util.MutableTree.MutableNode
class Day12 : Day(12) {
companion object {
/**
* Avoid 'lower case' nodes being used twice!
*/
fun paths(current: List<MutableNode<String>>, end: MutableNode<String>): List<List<MutableNode<String>>> {
val candidates = current.last().next
// remove invalid candidates
val lowerCaseCurrent = current.filter { it.value[0].isLowerCase() }
val filteredCandidates = candidates.filter { c ->
!lowerCaseCurrent.contains(c)
}
val x = filteredCandidates.map { next ->
val newCurrent = current + listOf(next)
if (next == end) {
listOf(newCurrent)
} else {
paths(newCurrent, end)
}
}
return x.flatten()
}
/**
* Avoid 'lower case' nodes being used twice!
*/
fun paths2(current: List<MutableNode<String>>, end: MutableNode<String>): List<List<MutableNode<String>>> {
val candidates = current.last().next
// remove invalid candidates: start, end, and lower case nodes if any lower case node was used twice
val lowerCaseCurrent = current.map { it.value }.filter { it[0].isLowerCase() }
val hasDuplicateLowerCaseCurrent = lowerCaseCurrent.toSet().size < lowerCaseCurrent.size
val filteredCandidates = candidates.filter { c ->
val value = c.value
value != "start" && if (hasDuplicateLowerCaseCurrent) {
!lowerCaseCurrent.contains(value)
} else {
true
}
}
val x = filteredCandidates.map { next ->
val newCurrent = current + listOf(next)
if (next == end) {
listOf(newCurrent)
} else {
paths2(newCurrent, end)
}
}
return x.flatten()
}
fun buildTree(lines: List<String>): MutableTree<String> {
val sep = "-"
val grouped = lines.map {
val (start, end) = it.split(sep)
start to end
}.groupBy({ it.first }, { it.second })
val nodes = (grouped.keys + grouped.values.flatten()).toSet().map {
MutableNode(it, mutableListOf())
}.associateBy { n ->
n.value
}.toMutableMap()
grouped.forEach { (start, ends) ->
val node = nodes[start]!!
val nextNodes = ends.map { end ->
nodes[end]!!
}
nextNodes.forEach {
it.addNext(listOf(node))
}
node.addNext(nextNodes)
}
val start = nodes["start"]!!
return MutableTree(start, nodes.values.toList())
}
}
override fun runPartOne(lines: List<String>): Any {
val tree = buildTree(lines)
val start = tree.root
val end = tree.getNode("end")
val endPaths = paths(listOf(start), end)
return endPaths.size
}
override fun runPartTwo(lines: List<String>): Any {
val tree = buildTree(lines)
val start = tree.root
val end = tree.getNode("end")
val endPaths = paths2(listOf(start), end)
return endPaths.size
}
}
| 0 | Kotlin | 0 | 0 | 6231e2092314ece3f993d5acf862965ba67db44f | 3,540 | aoc2021 | Creative Commons Zero v1.0 Universal |
src/Day14.kt | kipwoker | 572,884,607 | false | null | import kotlin.math.max
import kotlin.math.min
enum class CaveCell {
Air,
Rock,
Sand
}
enum class SandFallResult {
Stuck,
Fall
}
val caveSize = 1000
fun main() {
class Cave(val map: Array<Array<CaveCell>>) {
fun getBounds(): Pair<Point, Point> {
var minX = caveSize
var minY = caveSize
var maxX = 0
var maxY = 0
for (y in 0 until caveSize) {
for (x in 0 until caveSize) {
if (map[x][y] != CaveCell.Air) {
minX = min(minX, x)
minY = min(minY, y)
maxX = max(maxX, x)
maxY = max(maxY, y)
}
}
}
return Point(minX, minY) to Point(maxX, maxY)
}
}
fun parse(input: List<String>): Cave {
val cave = Cave(Array(caveSize) { _ -> Array(caveSize) { _ -> CaveCell.Air } })
val pointBlocks = input.map { line ->
line
.split('-')
.map { pair ->
val parts = pair.split(',')
Point(parts[0].toInt(), parts[1].toInt())
}
}
for (pointBlock in pointBlocks) {
for (i in 0..pointBlock.size - 2) {
val left = pointBlock[i]
val right = pointBlock[i + 1]
if (left.x != right.x && left.y != right.y) {
println("Unexpected $left -> $right")
throw RuntimeException()
}
if (left.x == right.x) {
val x = left.x
for (dy in min(left.y, right.y)..max(left.y, right.y)) {
cave.map[x][dy] = CaveCell.Rock
}
}
if (left.y == right.y) {
val y = left.y
for (dx in min(left.x, right.x)..max(left.x, right.x)) {
cave.map[dx][y] = CaveCell.Rock
}
}
}
}
return cave
}
fun print(cave: Cave) {
val window = 0
val (minPoint, maxPoint) = cave.getBounds()
for (y in (minPoint.y - window)..(maxPoint.y + window)) {
for (x in (minPoint.x - window)..(maxPoint.x + window)) {
val sign = when (cave.map[x][y]) {
CaveCell.Air -> '.'
CaveCell.Rock -> '#'
CaveCell.Sand -> 'o'
}
print(sign)
}
println()
}
}
fun playSand(cave: Cave): SandFallResult {
val (_, maxPoint) = cave.getBounds()
var sx = 500
var sy = 0
while (sy < maxPoint.y) {
if (cave.map[sx][sy + 1] == CaveCell.Air) {
++sy
} else if (cave.map[sx - 1][sy + 1] == CaveCell.Air) {
--sx
++sy
} else if (cave.map[sx + 1][sy + 1] == CaveCell.Air) {
++sx
++sy
} else {
cave.map[sx][sy] = CaveCell.Sand
return SandFallResult.Stuck
}
}
return SandFallResult.Fall
}
fun play1(cave: Cave): Int {
var counter = 0
while (playSand(cave) != SandFallResult.Fall) {
// print(cave)
++counter
}
return counter
}
fun play2(cave: Cave): Int {
val (_, maxPoint) = cave.getBounds()
for (x in 0 until caveSize) {
cave.map[x][maxPoint.y + 2] = CaveCell.Rock
}
var counter = 0
while (playSand(cave) != SandFallResult.Fall && cave.map[500][0] != CaveCell.Sand) {
++counter
}
return counter + 1
}
fun part1(input: List<String>): Int {
val cave = parse(input)
return play1(cave)
}
fun part2(input: List<String>): Int {
val cave = parse(input)
return play2(cave)
}
val testInput = readInput("Day14_test")
assert(part1(testInput), 24)
assert(part2(testInput), 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 4,287 | aoc2022 | Apache License 2.0 |
src/main/kotlin/base/data/datas.kt | chlesaec | 544,431,960 | false | {"Kotlin": 68026} | package base.data
import base.vectors.RealVector
import base.vectors.Vector
import kotlin.math.exp
fun softMax(values : RealVector): Pair<Double, DoubleArray> {
val exponential = DoubleArray(values.size) {
exp(values[it])
}
val sum: Double = exponential.sum()
return Pair(sum, exponential)
}
fun calculateScore(referencedIndex : Int, values : Vector<Byte>) : Double {
var min = Byte.MAX_VALUE
values.iterator().forEach {
if (it < min) {
min = it
}
}
var suml = values.length()
if (suml == 0.0) {
suml = 1.0
}
var score = 0.0
values.iterator().withIndex().forEach {
if (it.index == referencedIndex) {
score += (it.value.toDouble() - min.toDouble())/suml
}
else {
score += -(it.value.toDouble() - min.toDouble())/suml
}
}
/*println("score : $score")
val unitPredictions: RealVector = values.normalize()
val perfect = RealVector(values.size) {
if (it == referencedIndex)
1.0
else
-1.0
}
return perfect * unitPredictions*/
return score
}
data class TrainingItem<T>(val input : Vector<T>, val indexResult: Int)
where T:Number, T:Comparable<T> {
fun scorePrevisionOK(predictor: (Vector<T>) -> Vector<Byte>) : Pair<Double, Double> {
val predictions: Vector<Byte> = predictor(this.input)
return score(predictions)
}
fun score(predictions: Vector<Byte>): Pair<Double, Double> {
//val score = calculateScore(indexResult, predictions)
var maxIndex = 0
repeat(predictions.size) {
if (predictions[it] > predictions[maxIndex]) {
maxIndex = it
}
}
var nbeMax = 0
var nbeOK = 0.0
repeat(predictions.size) {
if (predictions[it] == predictions[maxIndex]) {
nbeMax++
if (maxIndex == it) {
nbeOK = 1.0
}
}
}
//println("nbe max ${nbeMax}; prediction : ${predictions[maxIndex]}, prev:${maxIndex}, vs:${indexResult}")
val rate = nbeOK / nbeMax.toDouble()
return Pair(rate, rate)
}
fun extractOne(): Number? {
if (this.input.size == 0) {
return null
}
return input[0]
}
}
class TrainingData<T>(val items : List<TrainingItem<T>>)
where T:Number, T:Comparable<T>{
fun scoreAndRate(predictor: (Vector<T>) -> Vector<Byte>): Pair<Double, Double> {
val result = this.items
.map { item -> item.scorePrevisionOK(predictor) }
.fold(Pair(0.0, 0.0)) {
buffer: Pair<Double, Double>,
scoreAndPrev: Pair<Double, Double> ->
Pair(buffer.first + scoreAndPrev.first,
buffer.second + scoreAndPrev.second)
}
return Pair(result.first / this.items.size, result.second / this.items.size)
}
fun scoreAndRateMass(predictor: (List<Vector<T>>) -> List<Vector<Byte>>): Pair<Double, Double> {
val predictions: List<Vector<Byte>> = predictor(this.items.map {
it.input
})
val (score, rate) = predictions.mapIndexed { index: Int, pred: Vector<Byte> ->
this.items[index].score(pred)
}
.fold(Pair(0.0, 0.0)) { buffer: Pair<Double, Double>,
scoreAndPrev: Pair<Double, Double> ->
Pair(
buffer.first + scoreAndPrev.first,
buffer.second + scoreAndPrev.second
)
}
return Pair(score / this.items.size, rate / this.items.size)
}
fun extractOne(): Number? {
if (items.isEmpty()) {
return null
}
val firstData = items[0]
return firstData.extractOne()
}
}
| 0 | Kotlin | 0 | 0 | 0169f05a15164a56fc61d4e2d25314fdcc64f869 | 3,909 | Neurons | Apache License 2.0 |
src/main/kotlin/nov_challenge2021/UniquePathsIII.kt | yvelianyk | 405,919,452 | false | {"Kotlin": 147854, "Java": 610} | package nov_challenge2021
fun main() {
val grid1 = arrayOf(
intArrayOf(1, 0, 0, 0),
intArrayOf(0, 0, 0, 0),
intArrayOf(0, 0, 2, -1),
)
val res1 = UniquePathsIII().uniquePathsIII(grid1)
assert(res1 == 2)
val grid2 = arrayOf(
intArrayOf(0, 1),
intArrayOf(2, 0),
)
val res2 = UniquePathsIII().uniquePathsIII(grid2)
assert(res2 == 0)
}
class UniquePathsIII {
private var result = 0
private lateinit var visited: Array<IntArray>
private lateinit var grid: Array<IntArray>
private var obstaclesCount = 0
private val dirs = arrayOf(Pair(0, 1), Pair(1, 0), Pair(0, -1), Pair(-1, 0))
fun uniquePathsIII(grid: Array<IntArray>): Int {
var startI = 0
var startJ = 0
this.grid = grid
visited = Array(grid.size) {
IntArray(grid[0].size)
}
for (i in grid.indices) {
for (j in grid[i].indices) {
if (grid[i][j] == 1) {
startI = i
startJ = j
}
if (grid[i][j] == -1) {
obstaclesCount++
}
}
}
count(startI, startJ, 0)
return result
}
private fun count(i: Int, j: Int, counter: Int) {
if (grid[i][j] == 2 && counter == grid.size * grid[0].size - 1 - obstaclesCount) {
result++
return
}
visited[i][j] = 1
for (dir in dirs) {
val newI = i + dir.first
val newJ = j + dir.second
if (
newI >= 0 &&
newI < grid.size &&
newJ >= 0 &&
newJ < grid[0].size &&
visited[newI][newJ] == 0 &&
grid[newI][newJ] != -1
) {
count(newI, newJ, counter + 1)
}
}
visited[i][j] = 0
}
}
| 0 | Kotlin | 0 | 0 | 780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd | 1,931 | leetcode-kotlin | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem808/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem808
/**
* LeetCode page: [808. Soup Servings](https://leetcode.com/problems/soup-servings/);
*/
class Solution {
/* Complexity:
* Time O(1) and Space O(1) because the number of recursions is bounded by O(n0^2),
* where n0 is a constant much smaller than the upper bound of n, and for n is not
* less than n0, the probability is not less than 1-tolerance;
*/
fun soupServings(n: Int): Double {
val memoization = hashMapOf<RemainingSoupMl, Double>()
val resultTolerance = 1e-5
val mlPrecision = 25 // 1 to 25 is equivalent to 25, 26 to 50 is equivalent to 50, and so on
for (amount in 0..n step mlPrecision) {
if (probabilityAsked(RemainingSoupMl(amount, amount), memoization) > 1 - resultTolerance) {
return 1.0
}
}
return probabilityAsked(RemainingSoupMl(n, n), memoization)
}
private fun probabilityAsked(
remainingSoupMl: RemainingSoupMl,
memoization: MutableMap<RemainingSoupMl, Double> = hashMapOf()
): Double = with(remainingSoupMl) {
if (this in memoization) {
return checkNotNull(memoization[this])
}
if (typeA > 0 && typeB <= 0) {
return 0.0
}
if (typeA <= 0) {
return if (typeB <= 0) 0.5 else 1.0
}
val result = 0.25 * (probabilityAsked(remainingSoupMl.afterOperation1(), memoization)
+ probabilityAsked(remainingSoupMl.afterOperation2(), memoization)
+ probabilityAsked(remainingSoupMl.afterOperation3(), memoization)
+ probabilityAsked(remainingSoupMl.afterOperation4(), memoization))
memoization[remainingSoupMl] = result
return result
}
private data class RemainingSoupMl(val typeA: Int, val typeB: Int) {
fun afterOperation1(): RemainingSoupMl = RemainingSoupMl(typeA - 100, typeB)
fun afterOperation2(): RemainingSoupMl = RemainingSoupMl(typeA - 75, typeB - 25)
fun afterOperation3(): RemainingSoupMl = RemainingSoupMl(typeA - 50, typeB - 50)
fun afterOperation4(): RemainingSoupMl = RemainingSoupMl(typeA - 25, typeB - 75)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,231 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day11.kt | icoffiel | 572,651,851 | false | {"Kotlin": 29350} | private const val DAY = "Day11"
fun main() {
data class Test(val divisibleBy: Int, val throwToTrue: Int, val throwToFalse: Int)
data class Operation(val operand: String, val value: String) {
fun perform(itemValue: Long): Long {
val parsedValue: Long = when (value) {
"old" -> itemValue
else -> value.toLong()
}
return when (operand) {
"*" -> itemValue * parsedValue
"+" -> itemValue + parsedValue
else -> error("Unknown operand: $operand")
}
}
}
data class Monkey(
val name: String,
val items: MutableList<Long>,
val operation: Operation,
val test: Test,
var timesCounted: Long = 0L
) {
fun thrownTo(item: Long) {
items.add(item)
}
}
/**
* Takes a string and converts it to the monkey name:
*
* Example input:
* `Monkey 0:`
*
* Output:
* `0`
*/
fun String.toMonkeyName(): String = "[0-9]+"
.toRegex()
.find(this)
?.value ?: error("$this cannot be converted to name")
/**
* Takes a string in the following format and converts it to a list of Strings:
*
* Example input:
* ` Starting items: 79, 98`
*
* Output:
* `[79, 98]`
*/
fun String.toStartingItems(): MutableList<Long> = this
.replace("Starting items: ", "")
.trim()
.split(",")
.map { it.trim() }
.map { it.toLong() }
.toMutableList()
fun String.toDivisibleBy(): Int {
return this
.replace("Test: divisible by ", "")
.trim()
.toInt()
}
fun String.toThrowToTrue(): Int {
return this
.replace("If true: throw to monkey ", "")
.trim()
.toInt()
}
fun String.toThrowToFalse(): Int {
return this
.replace("If false: throw to monkey ", "")
.trim()
.toInt()
}
fun String.toOperation(): Operation {
val (operand, value) = this
.replace("Operation: new = old ", "")
.trim()
.split(" ")
return Operation(operand, value)
}
fun toTest(testLine: String, trueLine: String, falseLine: String): Test {
return Test(
testLine.toDivisibleBy(),
trueLine.toThrowToTrue(),
falseLine.toThrowToFalse(),
)
}
fun parse(input: String) = input
.split("${System.lineSeparator()}${System.lineSeparator()}")
.map { monkey ->
val monkeyLines = monkey.lines()
Monkey(
monkeyLines[0].toMonkeyName(),
monkeyLines[1].toStartingItems(),
monkeyLines[2].toOperation(),
toTest(monkeyLines[3], monkeyLines[4], monkeyLines[5])
)
}
fun worryScore(monkeys: List<Monkey>): Long = monkeys
.sortedByDescending { it.timesCounted }
.take(2)
.map { it.timesCounted }
.reduce { acc, i -> acc * i }
fun part1(input: String): Long {
val monkeys: List<Monkey> = parse(input)
repeat((0..19).count()) {
monkeys.forEach { monkey ->
val itemsIter = monkey.items.listIterator()
while (itemsIter.hasNext()) {
val item = itemsIter.next()
val worryLevelIncrease = monkey.operation.perform(item)
val afterBored = worryLevelIncrease / 3
val thrownToMonkeyIndex = when (afterBored % monkey.test.divisibleBy) {
0L -> monkey.test.throwToTrue
else -> monkey.test.throwToFalse
}
monkeys[thrownToMonkeyIndex].thrownTo(afterBored)
itemsIter.remove()
monkey.timesCounted += 1L
}
}
}
return worryScore(monkeys)
}
fun part2(input: String): Long {
val monkeys: List<Monkey> = parse(input)
val commonModulus = monkeys.map { it.test.divisibleBy }.reduce(Int::times)
repeat((0..9999).count()) {
monkeys.forEach { monkey ->
val itemsIter = monkey.items.listIterator()
while (itemsIter.hasNext()) {
val item = itemsIter.next()
val worryLevelIncrease = monkey.operation.perform(item)
val afterBored = worryLevelIncrease % commonModulus
val thrownToMonkeyIndex = when (afterBored % monkey.test.divisibleBy) {
0L -> monkey.test.throwToTrue
else -> monkey.test.throwToFalse
}
monkeys[thrownToMonkeyIndex].thrownTo(afterBored)
itemsIter.remove()
monkey.timesCounted += 1
}
}
}
return worryScore(monkeys)
}
val testInput = readInputAsText("${DAY}_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInputAsText(DAY)
println("Part One: ${part1(input)}")
check(part1(input) == 120056L)
println("Part Two: ${part2(input)}")
check(part2(input) == 21816744824)
}
| 0 | Kotlin | 0 | 0 | 515f5681c385f22efab5c711dc983e24157fc84f | 5,419 | advent-of-code-2022 | Apache License 2.0 |
src/Day01.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | fun main() {
fun MutableList<Int>.insert_ordered(value: Int, max_position: Int) {
var ix = kotlin.math.min(this.size, max_position)
while (ix > 0 && value > this[ix-1]) {
ix--
}
if (ix < max_position) {
this.add(ix, value)
}
}
fun part2(input: List<String>): List<Int> {
val largest_so_far = mutableListOf<Int>()
var num_elves = 0
var current_elf_total = 0
for (line in input) {
if (line.isBlank() && current_elf_total > 0) {
num_elves += 1
largest_so_far.insert_ordered(current_elf_total, 3)
current_elf_total = 0
} else {
try {
current_elf_total += line.toInt()
} catch (e: NumberFormatException) {
// Do Nothing
}
}
}
// Handle the case where the file doesn't end in an empty line
if (current_elf_total > 0) {
num_elves += 1
largest_so_far.insert_ordered(current_elf_total, 3)
}
println("${num_elves} elves, list_len:${largest_so_far.size}")
return largest_so_far.take(3)
}
fun part1(input: List<String>): Int {
return part2(input).first()
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("1-input")
// check(part1(testInput) == 1)
val input = readInput("1-input")
val ans1 = part1(input)
println(ans1)
val ans2 = part2(input)
println("${ans2}, ${ans2.sum()}")
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 1,625 | 2022-aoc-kotlin | Apache License 2.0 |
src/Day22.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | import java.util.PriorityQueue
import java.util.Stack
import kotlin.math.min
data class Brick(
val name: String,
val xRange: IntRange,
val yRange: IntRange,
var zRange: IntRange,
val supports: MutableList<Brick> = mutableListOf(),
val supportedBy: MutableList<Brick> = mutableListOf(),
var isCrumbled: Boolean = false
) {
val z1 get() = zRange.first
val z2 get() = zRange.last
companion object {
fun init(line: String, name: String = ""): Brick {
val (c1, c2) = line.split("~", limit = 2)
val (x1, y1, z1) = c1.split(",", limit = 3).map { it.toInt() }
val (x2, y2, z2) = c2.split(",", limit = 3).map { it.toInt() }
return Brick(name, x1..x2, y1..y2, z1..z2)
}
}
fun intersects(b: Brick): Boolean {
val x = this.xRange.intersects(b.xRange)
val y = this.yRange.intersects(b.yRange)
return x && y
}
fun supports(b: Brick): Boolean {
return this.intersects(b) && z2 + 1 == b.z1
}
fun settle(h: Int) {
zRange = h..(h + (z2 - z1))
}
fun canDisintegrate(): Boolean {
return !(supports.isNotEmpty() && supports.count { it.supportedBy.size == 1 } > 0)
}
fun countFall(): Int {
isCrumbled = true
if (supports.isEmpty())
return 0
// Count the supporting bricks where its supports are all crumbled
val bricks = supports.filter { b ->
b.supportedBy.count { !it.isCrumbled } == 0
}
return bricks.size + bricks.sumOf { it.countFall() }
}
}
fun Input.settleBricks(): List<Brick> {
val bricks = this.mapIndexed { i, it -> Brick.init(it, (i + 1).toString()) }
// Bricks fall in the order of its lower z
val pq = PriorityQueue(compareBy<Brick> { it.z1 })
pq.addAll(bricks)
// Bricks by its upper z after settling
val settledBricks = PriorityQueue(compareBy<Brick> { it.z2 * -1 })
while (pq.isNotEmpty()) {
val b1 = pq.poll()
// Start popping the settle bricks until we find one that can be a support
val tempStack = Stack<Brick>()
while (settledBricks.isNotEmpty()) {
if (settledBricks.peek().intersects(b1)) break
tempStack.push(settledBricks.poll())
}
// If no more bricks left, this one will settle on the ground level
// Otherwise, put this one on top of the highest settled brick
val settleLevel =
if (settledBricks.isEmpty()) 1
else settledBricks.peek().z2 + 1
settledBricks.add(b1.apply { settle(settleLevel) })
// Move the popped bricks back in
while (tempStack.isNotEmpty()) {
settledBricks.add(tempStack.pop())
}
}
// Build the bricks dependency
val bricksByLevel = settledBricks.groupBy { it.z1 }
bricksByLevel.forEach { (_, bricks) ->
for (b1 in bricks) {
bricksByLevel[b1.z2 + 1]?.forEach { b2 ->
if (b1.supports(b2)) {
b1.supports.add(b2)
b2.supportedBy.add(b1)
}
}
}
}
return bricks
}
fun main() {
fun part1(input: List<String>): Int {
return input.settleBricks().count { it.canDisintegrate() }
}
fun part2(input: List<String>): Int {
val bricks = input.settleBricks()
val keyBricks = bricks.filter { !it.canDisintegrate() }
return keyBricks.sumOf {
// Reset crumbed state
bricks.forEach { it.isCrumbled = false }
it.countFall()
}
}
val input = readInput("Day22")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 3,722 | aoc-2023 | Apache License 2.0 |
src/main/kotlin/days/Day15.kt | vovarova | 572,952,098 | false | {"Kotlin": 103799} | package days
import days.Util.manhattanDistance
import util.Cell
import kotlin.math.abs
class Day15 : Day(15) {
class Sensor(val coordinates: Cell, val beacon: Cell) {
val beaconDistance: Int = manhattanDistance(coordinates, beacon)
fun distanceTo(cell: Cell): Int = manhattanDistance(coordinates, cell)
fun covers(cell: Cell): Boolean {
return beaconDistance >= distanceTo(cell)
}
fun maxColumnCovered(row: Int): Cell {
return Cell(row, coordinates.column + abs(beaconDistance - abs(row - coordinates.row)))
}
fun minColumnCovered(row: Int): Cell {
return Cell(row, coordinates.column - abs(beaconDistance - abs(row - coordinates.row)))
}
}
class Sensors(input: List<String>) {
val beacons: Set<Cell>
val sensorMap: Map<Cell, Sensor>
fun sensorsOnRow(row: Int, minColumn: Int, maxColumn: Int): List<Sensor> {
return sensorMap.values.filter { it.coordinates.row == row && it.coordinates.column >= minColumn && it.coordinates.column <= maxColumn }
}
fun beaconsOnRow(row: Int, minColumn: Int, maxColumn: Int): List<Cell> {
return beacons.filter { it.row == row && it.column >= minColumn && it.column <= maxColumn }
}
init {
val regex = Regex("-?\\d+")
sensorMap = input.map {
regex.findAll(it).map { it.value.toInt() }.toList()
}
.map {
Sensor(Cell(it[1], it[0]), Cell(it[3], it[2]))
}.map { it.coordinates to it }.toMap()
beacons = sensorMap.values.map { it.beacon }.toSet()
}
fun coveredBySensor(cell: Cell): Sensor? {
return sensorMap.values.asSequence().find { it.covers(cell) }
}
}
fun partOne(row: Int): Int {
val sensors = Sensors(inputList)
val minColumn = sensors.sensorMap.values.map { it.minColumnCovered(row) }.map { it.column }.min()
val maxColumn = sensors.sensorMap.values.map { it.maxColumnCovered(row) }.map { it.column }.max()
var currentCell = Cell(row, minColumn)
var count: Int = 0
while (currentCell.column <= maxColumn) {
val coveredBySensor = sensors.coveredBySensor(currentCell)
if (coveredBySensor != null) {
val maxColumnCovered = coveredBySensor.maxColumnCovered(currentCell.row)
count += maxColumnCovered.column - currentCell.column + 1
count -= sensors.sensorsOnRow(currentCell.row, currentCell.column, maxColumnCovered.column).size
count -= sensors.beaconsOnRow(currentCell.row, currentCell.column, maxColumnCovered.column).size
currentCell = maxColumnCovered
}
currentCell = currentCell.right()
}
return count
}
override fun partOne(): Int {
return partOne(row = 2000000)
}
fun notCoveredCell(maxCoordinate: Int): Cell? {
val sensors = Sensors(inputList)
for (row in 0..maxCoordinate) {
var currentCell = Cell(row, 0)
while (currentCell.column <= maxCoordinate) {
val coveredBySensor = sensors.coveredBySensor(currentCell)
if (coveredBySensor != null) {
currentCell = coveredBySensor.maxColumnCovered(currentCell.row).right()
} else {
return currentCell
}
}
}
return null
}
fun partTwo(maxCoordinate: Int): Any {
val notCoveredCell = notCoveredCell(maxCoordinate)!!
return notCoveredCell.column.toLong() * 4000000 + notCoveredCell.row.toLong()
}
override fun partTwo(): Any {
return partTwo(4000000)
}
}
object Util {
fun manhattanDistance(c1: Cell, c2: Cell): Int =
abs(c1.row - c2.row) + abs(c1.column - c2.column)
}
fun main() {
Day15().partTwo()
}
| 0 | Kotlin | 0 | 0 | e34e353c7733549146653341e4b1a5e9195fece6 | 4,008 | adventofcode_2022 | Creative Commons Zero v1.0 Universal |
day14/Kotlin/day14.kt | Ad0lphus | 353,610,043 | false | {"C++": 195638, "Python": 139359, "Kotlin": 80248} | import java.io.*
fun print_day_14() {
val yellow = "\u001B[33m"
val reset = "\u001b[0m"
val green = "\u001B[32m"
println(yellow + "-".repeat(25) + "Advent of Code - Day 14" + "-".repeat(25) + reset)
println(green)
val process = Runtime.getRuntime().exec("figlet Extended Polymerization -c -f small")
val reader = BufferedReader(InputStreamReader(process.inputStream))
reader.forEachLine { println(it) }
println(reset)
println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n")
}
fun main() {
print_day_14()
Day14().part_1()
Day14().part_2()
println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n")
}
class Day14 {
val lines = File("../Input/day14.txt").readLines()
val polyTemplate = lines.first()
fun part_1() {
val pairInsertions = lines.drop(2).map {
val (pair, insertion) = it.split(" -> ")
pair to insertion
}
var polyIteration = polyTemplate
for (step in 1..10) {
polyIteration = polyIteration.fold("") { str, curr ->
val pairCheck = "" + (str.lastOrNull() ?: "") + curr
val insert = pairInsertions.find { it.first == pairCheck } ?.second ?: ""
str + insert + curr
}
}
val elementCounts = polyIteration.groupBy { it }.map { it.key to it.value.size }.sortedBy { it.second }
val ans = elementCounts.last().second - elementCounts.first().second
println("Puzzle 1: $ans")
}
fun part_2() {
val insertPattern = lines.drop(2).map { it.split(" -> ") }.associate { it[0] to it[1] }
var pairFrequency = mutableMapOf<String, Long>()
polyTemplate.windowed(2).forEach{ pairFrequency.put(it, pairFrequency.getOrDefault(it, 0) + 1) }
for (step in 1..40) {
val updatedFrequencies = mutableMapOf<String, Long>()
pairFrequency.forEach {
val key1 = it.key[0] + insertPattern[it.key]!!
val key2 = insertPattern[it.key]!! + it.key[1]
updatedFrequencies.put(key1, updatedFrequencies.getOrDefault(key1, 0) + it.value)
updatedFrequencies.put(key2, updatedFrequencies.getOrDefault(key2, 0) + it.value)
}
pairFrequency = updatedFrequencies
}
val charFrequency = pairFrequency.toList().fold(mutableMapOf<Char, Long>()) { acc, pair ->
acc.put(pair.first[0], acc.getOrDefault(pair.first[0], 0) + pair.second)
acc
}
charFrequency.put(polyTemplate.last(), charFrequency.getOrDefault(polyTemplate.last(), 0) + 1)
val sorted = charFrequency.values.sorted()
val ans = sorted.last() - sorted.first()
println("Puzzle 2: $ans")
}
} | 0 | C++ | 0 | 0 | 02f219ea278d85c7799d739294c664aa5a47719a | 2,797 | AOC2021 | Apache License 2.0 |
kts/aoc2016/aoc2016_15.kts | miknatr | 576,275,740 | false | {"Kotlin": 413403} | val input15 = """Disc #1 has 13 positions; at time=0, it is at position 1.
Disc #2 has 19 positions; at time=0, it is at position 10.
Disc #3 has 3 positions; at time=0, it is at position 2.
Disc #4 has 7 positions; at time=0, it is at position 1.
Disc #5 has 5 positions; at time=0, it is at position 3.
Disc #6 has 17 positions; at time=0, it is at position 5."""
val input15_2 = """$input15
Disc #7 has 11 positions; at time=0, it is at position 0."""
data class Disc(val level: Int, val positions: Int, val startPosition: Int)
fun parseInput(input: String): List<Disc> =
input
.split("\n")
.map { Regex("Disc #(\\d+) has (\\d+) positions; at time=0, it is at position (\\d+).").matchEntire(it)!! }
.filterNotNull()
.map { it.groups }
.map { Disc(it[1]!!.value.toInt(), it[2]!!.value.toInt(), it[3]!!.value.toInt()) }
fun canFallThroughDisk(disk: Disc, second: Int): Boolean =
(second + disk.level + disk.startPosition) % disk.positions == 0
fun getSecondToFall(disks: List<Disc>): Int =
generateSequence(0, Int::inc)
.filter { second -> disks.all { disk -> canFallThroughDisk(disk, second) } }
.first()
println("Part One")
println(getSecondToFall(parseInput(input15)))
println("Part Two")
println(getSecondToFall(parseInput(input15_2)))
| 0 | Kotlin | 0 | 0 | 400038ce53ff46dc1ff72c92765ed4afdf860e52 | 1,315 | aoc-in-kotlin | Apache License 2.0 |
src/Day03.kt | zt64 | 572,594,597 | false | null | val priorities = (('a'..'z') + ('A'..'Z'))
.mapIndexed { index, char -> char to index + 1 }
.toMap()
fun main() {
val input = readInput("Day03")
fun part1(input: String): Int {
val rucksacks = input.lines()
val total = rucksacks.sumOf { rucksack ->
val middle = rucksack.length / 2
val compartment1 = rucksack.take(middle).toList()
val compartment2 = rucksack.takeLast(middle).toList()
priorities[compartment1.intersect(compartment2.toSet()).single()]!!
}
return total
}
fun part2(input: String): Int {
val groups = input.lines().chunked(3)
return groups.sumOf { group ->
val elf1 = group[0].toSet()
val elf2 = group[1].toSet()
val elf3 = group[2].toSet()
priorities[elf1.intersect(elf2).intersect(elf3).single()]!!
}
}
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 4e4e7ed23d665b33eb10be59670b38d6a5af485d | 963 | aoc-2022 | Apache License 2.0 |
src/Day21.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day21.run {
solve1(152L) // 309248622142100L
solve2(301L) // 3757272361782L
}
}.let { println("Total: $it ms") }
}
object Day21 : Day.LineInput<Day21.Monkeys, Long>("21") {
override fun parse(input: List<String>) = input.associate {
it.split(": ").let { (name, job) ->
name to job.split(" ")
}
}.let(::Monkeys)
class Monkeys(private val data: Map<String, List<String>>) {
private val cache = mutableMapOf<String, Long>()
private val humanMonkeys = mutableSetOf("humn")
fun getMonkeyValue(name: String): Long = cache[name] ?: data[name]!!.let { job ->
if (job.size == 1) {
job.first().toLong()
} else {
val (monkey1, monkey2) = job[0] to job[2]
when (job[1]) {
"+" -> getMonkeyValue(monkey1) + getMonkeyValue(monkey2)
"-" -> getMonkeyValue(monkey1) - getMonkeyValue(monkey2)
"*" -> getMonkeyValue(monkey1) * getMonkeyValue(monkey2)
"/" -> getMonkeyValue(monkey1) / getMonkeyValue(monkey2)
else -> error("Should not reach here.")
}.also { if (monkey1 in humanMonkeys || monkey2 in humanMonkeys) humanMonkeys.add(name) }
}.also { cache[name] = it }
}
fun getHumanMonkeyValue(): Long {
fun getHumanValue(name: String, expectValue: Long): Long = if (name == "humn") {
expectValue
} else {
val job = data[name]!!
val (monkey1, monkey2) = job[0] to job[2]
when {
job[1] == "+" && monkey1 in humanMonkeys -> getHumanValue(monkey1, expectValue - getMonkeyValue(monkey2))
job[1] == "-" && monkey1 in humanMonkeys -> getHumanValue(monkey1, expectValue + getMonkeyValue(monkey2))
job[1] == "*" && monkey1 in humanMonkeys -> getHumanValue(monkey1, expectValue / getMonkeyValue(monkey2))
job[1] == "/" && monkey1 in humanMonkeys -> getHumanValue(monkey1, expectValue * getMonkeyValue(monkey2))
job[1] == "+" -> getHumanValue(monkey2, expectValue - getMonkeyValue(monkey1))
job[1] == "-" -> getHumanValue(monkey2, getMonkeyValue(monkey1) - expectValue)
job[1] == "*" -> getHumanValue(monkey2, expectValue / getMonkeyValue(monkey1))
job[1] == "/" -> getHumanValue(monkey2, getMonkeyValue(monkey1) / expectValue)
else -> error("Should not reach here.")
}
}
val job = data["root"]!!
val (monkey1, monkey2) = job[0] to job[2]
return if (monkey1 in humanMonkeys) getHumanValue(monkey1, getMonkeyValue(monkey2))
else getHumanValue(monkey2, getMonkeyValue(monkey1))
}
}
override fun part1(data: Monkeys) = data.getMonkeyValue("root")
override fun part2(data: Monkeys) = data.getHumanMonkeyValue()
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 3,149 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LargestDivisibleSubset.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 368. Largest Divisible Subset
* @see <a href="https://leetcode.com/problems/largest-divisible-subset/">Source</a>
*/
fun interface LargestDivisibleSubset {
operator fun invoke(nums: IntArray): List<Int>
}
class LargestDivisibleSubsetDFS : LargestDivisibleSubset {
private val mem: MutableMap<Int, List<Int>> = HashMap()
override operator fun invoke(nums: IntArray): List<Int> {
nums.sort()
return helper(nums, 0)
}
private fun helper(nums: IntArray, i: Int): List<Int> {
if (mem.containsKey(i)) {
return mem[i] ?: emptyList()
}
var maxLenLst: List<Int> = ArrayList()
val div = if (i == 0) 1 else nums[i - 1]
for (k in i until nums.size) {
if (nums[k] % div == 0) {
// make a copy is crucial here, so that we won't modify the returned List reference
val lst: MutableList<Int> = ArrayList(helper(nums, k + 1))
lst.add(nums[k])
if (lst.size > maxLenLst.size) maxLenLst = lst
}
}
mem[i] = maxLenLst
return maxLenLst
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,775 | kotlab | Apache License 2.0 |
src/Day01.kt | b0n541 | 571,797,079 | false | {"Kotlin": 17810} | fun main() {
fun sumCaloriesPerElf(input: List<String>): List<Int> {
var result = mutableListOf<Int>()
var currentElfCalories = 0
input.forEach { line ->
if (line.isNotEmpty()) {
currentElfCalories += line.toInt()
} else {
result.add(currentElfCalories)
currentElfCalories = 0
}
}
result.add(currentElfCalories)
return result
}
fun part1(input: List<String>): Int {
return sumCaloriesPerElf(input).max()
}
fun part2(input: List<String>): Int {
return sumCaloriesPerElf(input).sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println("Part 1: " + part1(input))
check(part1(input) == 71502)
println("Part 2: " + part2(input))
check(part2(input) == 208191)
}
| 0 | Kotlin | 0 | 0 | d451f1aee157fd4d47958dab8a0928a45beb10cf | 1,063 | advent-of-code-2022 | Apache License 2.0 |
src/day10/Day10.kt | armanaaquib | 572,849,507 | false | {"Kotlin": 34114} | package day10
import readInput
fun main() {
data class Instruction(val command: String, val value: Int? = null)
fun parseInput(input: List<String>) = input.map { line ->
val c = line.split(" ").filter { it.isNotEmpty() }
if(c[0] == "noop") {
Instruction(c[0])
} else {
Instruction(c[0], c[1].toInt())
}
}
fun part1(input: List<String>): Int {
val instructions = parseInput(input)
val cycles = setOf(20, 60, 100, 140, 180, 220)
var noOfCycles = 0
var x = 1
var signalsStrength = 0
instructions.forEach {
noOfCycles++
if (cycles.contains(noOfCycles)) {
signalsStrength += noOfCycles * x
}
if (it.command == "addx") {
noOfCycles++
if (cycles.contains(noOfCycles)) {
signalsStrength += noOfCycles * x
}
x += it.value!!
}
}
return signalsStrength
}
fun part2(input: List<String>) {
val instructions = parseInput(input)
var noOfCycles = 0
var x = 1
instructions.forEach {
// println("$noOfCycles, $x")
noOfCycles++
if (noOfCycles >= x && noOfCycles < x + 3) {
print("#")
} else {
print(".")
}
if (noOfCycles % 40 == 0) {
noOfCycles = 0
println()
}
if (it.command == "addx") {
noOfCycles++
if (noOfCycles >= x && noOfCycles < x + 3) {
print("#")
} else {
print(".")
}
if (noOfCycles % 40 == 0) {
noOfCycles = 0
println()
}
x += it.value!!
}
}
}
// test if implementation meets criteria from the description, like:
check(part1(readInput("Day10_test")) == 13140)
println(part1(readInput("Day10")))
// part2(readInput("Day10_test"))
part2(readInput("Day10"))
}
| 0 | Kotlin | 0 | 0 | 47c41ceddacb17e28bdbb9449bfde5881fa851b7 | 2,200 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/se/brainleech/adventofcode/aoc2020/Aoc2020Day03.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2020
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
class Aoc2020Day03 {
companion object {
private const val TREE = '#'
private const val HIT = 'X'
private const val MISS = 'O'
}
data class Forest(val slices: List<String>) {
private fun String.markedAt(column: Int): String {
val output = this.toCharArray()
val index = (column - 1).mod(this.length)
output[index] = if (output[index] == TREE) HIT else MISS
return String(output)
}
fun treeCount(dx: Int, dy: Int): Long {
var column = 1
return slices.asSequence()
.drop(dy)
.filterIndexed { row, _ -> row.mod(dy) == 0 }
.onEach { column += dx }
.map { it.markedAt(column) }
.count { it.contains(HIT) }
.toLong()
}
}
fun part1(input: List<String>): Long {
return Forest(input).treeCount(3, 1)
}
fun part2(input: List<String>): Long {
val forest = Forest(input)
return forest.treeCount(1, 1)
.times(forest.treeCount(3, 1))
.times(forest.treeCount(5, 1))
.times(forest.treeCount(7, 1))
.times(forest.treeCount(1, 2))
}
}
fun main() {
val solver = Aoc2020Day03()
val prefix = "aoc2020/aoc2020day03"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(7L, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(336L, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
} | 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 1,809 | adventofcode | MIT License |
y2017/src/main/kotlin/adventofcode/y2017/Day03.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2017
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec2
import adventofcode.util.vector.mooreNeighbors
import kotlin.math.roundToInt
import kotlin.math.sqrt
object Day03 : AdventSolution(2017, 3, "Spiral Memory") {
override fun solvePartOne(input: String) = toSpiralCoordinates(input.toInt() - 1).distance(Vec2.origin)
override fun solvePartTwo(input: String): Int {
val spiralCoordinatesSequence = generateSequence(1, Int::inc).map(this::toSpiralCoordinates)
val spiral = mutableMapOf(Vec2.origin to 1)
fun Vec2.sumNeighborhood() = mooreNeighbors().mapNotNull(spiral::get).sum()
return spiralCoordinatesSequence
.map { spiral.computeIfAbsent(it) { v -> v.sumNeighborhood() } }
.first { it > input.toInt() }
}
private fun toSpiralCoordinates(index: Int): Vec2 {
if (index <= 0) return Vec2.origin
//The width of the edge at the current edge of the spiral
//each half-turn the width increases by one
val width = sqrt(index.toDouble()).roundToInt()
//the index of the end of the preceding completed half-turn
//i.e. the size of the completed inner 'block'
val spiralBaseIndex = width * (width - 1)
// 1 or -1, depending on if we've done a complete turn or a half-turn
val sign = if (width % 2 == 0) 1 else -1
//distance from origin: the position of spiralBaseIndex is [offset,offset]
val offset = sign * (width / 2)
//corner in the middle of the current half-turn
val cornerIndex = spiralBaseIndex + width
val x = offset - sign * (index - spiralBaseIndex).coerceAtMost(width)
val y = offset - sign * (index - cornerIndex).coerceAtLeast(0)
return Vec2(x, y)
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,824 | advent-of-code | MIT License |
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12934_square.kt | boris920308 | 618,428,844 | false | {"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407} | package main.kotlin.programmers.lv01
import kotlin.math.pow
import kotlin.math.sqrt
/**
*
* https://school.programmers.co.kr/learn/courses/30/lessons/12934
*
* 문제 설명
* 임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
* n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.
*
* 제한 사항
* n은 1이상, 50000000000000 이하인 양의 정수입니다.
* 입출력 예
* n return
* 121 144
* 3 -1
* 입출력 예 설명
* 입출력 예#1
* 121은 양의 정수 11의 제곱이므로, (11+1)를 제곱한 144를 리턴합니다.
*
* 입출력 예#2
* 3은 양의 정수의 제곱이 아니므로, -1을 리턴합니다.
*
*/
fun main() {
println("result = ${solution(12)}")
println("result = ${solution(13)}")
println("result = ${solution(121)}")
println("result = ${solution(3)}")
}
private fun solution(n: Long): Long{
var answer:Long = 0
val sqrt = sqrt(n.toDouble()).toLong()
println("n = $n , sqrt = $sqrt")
answer = if (sqrt * sqrt == n) {
(sqrt + 1).toDouble().pow(2.0).toLong()
} else {
-1
}
return answer
} | 1 | Kotlin | 1 | 2 | 88814681f7ded76e8aa0fa7b85fe472769e760b4 | 1,291 | HoOne | Apache License 2.0 |
src/Day05.kt | Sagolbah | 573,032,320 | false | {"Kotlin": 14528} | import java.lang.StringBuilder
fun main() {
val cols = 9
data class Movement(val items: Int, val from: Int, val to: Int)
fun parse(line: String): List<Char?> {
val res = mutableListOf<Char?>()
for (i in line.indices step 4) {
res.add(if (line[i + 1].isWhitespace()) null else line[i + 1])
}
return res
}
fun parseMovement(line: String): Movement {
val sb = StringBuilder()
val res = mutableListOf<Int>()
var skip = true
for (c in line) {
if (c.isDigit()) {
skip = false
sb.append(c)
} else if (!skip) {
res.add(sb.toString().toInt())
sb.setLength(0)
skip = true
}
}
res.add(sb.toString().toInt())
return Movement(res[0], res[1], res[2])
}
fun solve(input: List<String>, multitake: Boolean) : String {
val stacks = MutableList(cols) { mutableListOf<Char>() }
var idx = 0
while (true) {
val line = input[idx++]
if (line.startsWith(" 1")) break
val parsed = parse(line)
for (i in parsed.indices) {
if (parsed[i] != null) {
stacks[i].add(parsed[i]!!)
}
}
}
idx++
for (stack in stacks) stack.reverse()
while (idx < input.size) {
val move = parseMovement(input[idx])
val items = stacks[move.from - 1].takeLast(move.items)
stacks[move.from - 1] = stacks[move.from - 1].dropLast(move.items).toMutableList()
val toAdd = if (multitake) items else items.reversed()
stacks[move.to - 1].addAll(toAdd)
idx++
}
val sb = StringBuilder()
for (stack in stacks) sb.append(stack.last())
return sb.toString()
}
fun part1(input: List<String>): String {
return solve(input, false)
}
fun part2(input: List<String>): String {
return solve(input, true)
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 893c1797f3995c14e094b3baca66e23014e37d92 | 2,180 | advent-of-code-kt | Apache License 2.0 |
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day09Test.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
import kotlin.math.sign
private fun solution1(input: String) = doMotions(input, 2)
private fun solution2(input: String) = doMotions(input, 10)
private fun doMotions(input: String, knotCount: Int): Int {
val knots = List(knotCount) { Knot(0, 0) }
val last = knots.last()
val tailVisited = mutableSetOf<Pair<Int, Int>>()
input.lineSequence().map { it.split(" ") }
.flatMap { (dir, count) -> generateSequence { dir }.take(count.toInt()) }
.forEach { dir ->
knots[0].move(dir)
knots.windowed(2, 1).forEach { (k1, k2) -> k2.follow(k1) }
tailVisited.add(last.x to last.y)
}
return tailVisited.size
}
private class Knot(var x: Int, var y: Int) {
private val deltas = mapOf("R" to (1 to 0), "U" to (0 to 1), "L" to (-1 to 0), "D" to (0 to -1))
fun move(direction: String) {
val (dx, dy) = deltas.getValue(direction)
x += dx
y += dy
}
fun follow(other: Knot) {
val dx = other.x - x
val dy = other.y - y
if (dx in -1..1 && dy in -1..1) return
x += dx.sign
y += dy.sign
}
}
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 9
class Day09Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 13 }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 5513 }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 1 }
"larger example part 2" { ::solution2 invokedWith largerExampleInput shouldBe 36 }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 2427 }
})
private val exampleInput =
"""
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent()
private val largerExampleInput =
"""
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent()
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 2,259 | adventofcode-kotlin | MIT License |
src/main/kotlin/days/Day14.kt | andilau | 429,557,457 | false | {"Kotlin": 103829} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2015/day/14",
date = Date(day = 14, year = 2015)
)
class Day14(input: List<String>) : Puzzle {
private val reindeer = input.map(Reindeer::from)
internal var duration = 2503
override fun partOne(): Int = reindeer.winningDistanceBy(duration)
override fun partTwo(): Int = reindeer.winningPointsBy(duration)
private fun List<Reindeer>.winningDistanceBy(seconds: Int): Int = maxOf { it.distanceMovedOn(seconds) }
private fun List<Reindeer>.winningPointsBy(seconds: Int): Int =
(1..seconds)
.fold(this.associate { it.distances.iterator() to 0 }) { distancesPoints, _ ->
val associateWithDistance: Map<Iterator<Int>, Int> = distancesPoints.keys.associateWith { it.next() }
val maxDistance = associateWithDistance.values.maxOf { it }
val winners = associateWithDistance.filterValues { it == maxDistance }.keys
distancesPoints.mapValues { if (it.key in winners) it.value + 1 else it.value }
}
.values.maxOf { it }
data class Reindeer(val name: String, val speed: Int, val endure: Int, val rest: Int) {
fun distanceMovedOn(seconds: Int) = distances.drop(seconds - 1).first()
val distances
get() = sequence {
var distance = 0
while (true) {
var endureFor = endure
while (--endureFor >= 0) {
distance += speed
yield(distance)
}
var restFor = rest
while (--restFor >= 0) yield(distance)
}
}
companion object {
private val PATTERN =
Regex("""^(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.${'$'}""")
fun from(line: String): Reindeer {
return PATTERN.matchEntire(line)?.destructured?.let { (name, speed, endure, rest) ->
Reindeer(name, speed.toInt(), endure.toInt(), rest.toInt())
}
?: error("Invalid format: $line")
}
}
}
} | 0 | Kotlin | 0 | 0 | 55932fb63d6a13a1aa8c8df127593d38b760a34c | 2,276 | advent-of-code-2015 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dev/shtanko/algorithms/learn/Dijkstra.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.learn
import java.util.TreeSet
internal class Edge(val v1: String, val v2: String, val dist: Int)
/** One vertex of the graph, complete with mappings to neighbouring vertices */
internal class Vertex(val name: String) : Comparable<Vertex> {
var dist = Int.MAX_VALUE // MAX_VALUE assumed to be infinity
var previous: Vertex? = null
val neighbours = HashMap<Vertex, Int>()
fun printPath() {
when (previous) {
this -> {
print(name)
}
null -> {
print("$name(unreached)")
}
else -> {
previous?.printPath()
print(" -> $name($dist)")
}
}
}
override fun compareTo(other: Vertex): Int {
if (dist == other.dist) return name.compareTo(other.name)
return dist.compareTo(other.dist)
}
override fun toString() = "($name, $dist)"
}
internal class Graph(
edges: List<Edge>,
private val directed: Boolean,
private val showAllPaths: Boolean = false,
) {
// mapping of vertex names to Vertex objects, built from a set of Edges
private val mainGraph = HashMap<String, Vertex>(edges.size)
init {
// one pass to find all vertices
for (e in edges) {
if (!mainGraph.containsKey(e.v1)) mainGraph[e.v1] = Vertex(e.v1)
if (!mainGraph.containsKey(e.v2)) mainGraph[e.v2] = Vertex(e.v2)
}
// another pass to set neighbouring vertices
for (e in edges) {
mainGraph[e.v2]?.let { vrx ->
val n = mainGraph[e.v1]?.neighbours
n?.let {
it[vrx] = e.dist
}
// also do this for an undirected graph if applicable
if (!directed) {
mainGraph[e.v1]?.let { v1 ->
vrx.neighbours[v1] = e.dist
}
}
}
}
}
/** Runs dijkstra using a specified source vertex */
fun dijkstra(startName: String) {
if (!mainGraph.containsKey(startName)) {
println("Graph doesn't contain start vertex '$startName'")
return
}
val source = mainGraph[startName]
val q = TreeSet<Vertex>()
// set-up vertices
for (v in mainGraph.values) {
v.previous = if (v == source) source else null
v.dist = if (v == source) 0 else Int.MAX_VALUE
q.add(v)
}
dijkstra(q)
}
/** Implementation of dijkstra's algorithm using a binary heap */
private fun dijkstra(q: TreeSet<Vertex>) {
while (q.isNotEmpty()) {
// vertex with the shortest distance (first iteration will return source)
val u = q.pollFirst() ?: return
// if distance is infinite we can ignore 'u' (and any other remaining vertices)
// since they are unreachable
if (u.dist == Int.MAX_VALUE) break
// look at distances to each neighbour
for (a in u.neighbours) {
val v = a.key // the neighbour in this iteration
val alternateDist = u.dist + a.value
if (alternateDist < v.dist) { // shorter path to neighbour found
q.remove(v)
v.dist = alternateDist
v.previous = u
q.add(v)
}
}
}
}
/** Prints a path from the source to the specified vertex */
fun printPath(endName: String) {
if (!mainGraph.containsKey(endName)) {
println("Graph doesn't contain end vertex '$endName'")
return
}
print(if (directed) "Directed : " else "Undirected : ")
val v = mainGraph[endName]
v?.printPath()
println()
if (showAllPaths) printAllPaths() else println()
}
/** Prints the path from the source to every vertex (output order is not guaranteed) */
private fun printAllPaths() {
for (v in mainGraph.values) {
v.printPath()
println()
}
println()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,806 | kotlab | Apache License 2.0 |
src/Day14.kt | thomasreader | 573,047,664 | false | {"Kotlin": 59975} | import java.io.Reader
import java.util.SortedMap
import java.util.SortedSet
fun main() {
val testInput = """
498,4 -> 498,6 -> 496,6
503,4 -> 502,4 -> 502,9 -> 494,9
""".trimIndent()
val testRocks = parseInput(testInput.reader())
check(partOne(testRocks) == 24)
val input = reader("Day14.txt")
val rocks = parseInput(input)
println(partOne(rocks))
check(partTwo(testRocks) == 93)
println(partTwo(rocks))
}
private fun partTwo(rocks: Set<Coordinate>): Int {
val bottomY = rocks.maxBy { it.y }
val floor = bottomY.y + 2
val rocksAndSand = rocks.toMutableSet()
while (Coordinate(500, 0) !in rocksAndSand) {
var sandUnit = Coordinate(500, 0)
var atRest = false
while (!atRest) {
val nextDrop = sandUnit.y + 1
if (nextDrop == floor) {
atRest = true
rocksAndSand += sandUnit
continue
}
val down = sandUnit.down()
when (down !in rocksAndSand) {
true -> sandUnit = down
false -> {
val downLeft = sandUnit.downLeft()
when (downLeft !in rocksAndSand) {
true -> sandUnit = downLeft
false -> {
val downRight = sandUnit.downRight()
when (downRight !in rocksAndSand) {
true -> sandUnit = downRight
false -> {
atRest = true
rocksAndSand += sandUnit
}
}
}
}
}
}
}
}
return rocksAndSand.size - rocks.size
}
private fun partOne(rocks: Set<Coordinate>): Int {
val floor = rocks.maxBy { it.y }
val rocksAndSand = rocks.toMutableSet()
var intoEndlessVoid = false
while (!intoEndlessVoid) {
var sandUnit = Coordinate(500, 0)
var atRest = false
while (!atRest && !intoEndlessVoid) {
val down = sandUnit.down()
when (down !in rocksAndSand) {
true -> sandUnit = down
false -> {
val downLeft = sandUnit.downLeft()
when (downLeft !in rocksAndSand) {
true -> sandUnit = downLeft
false -> {
val downRight = sandUnit.downRight()
when (downRight !in rocksAndSand) {
true -> sandUnit = downRight
false -> {
atRest = true
rocksAndSand += sandUnit
}
}
}
}
}
}
if (sandUnit lowerThan floor) {
intoEndlessVoid = true
}
}
}
return rocksAndSand.size - rocks.size
}
private fun parseInput(src: Reader): Set<Coordinate> {
val rocks = mutableSetOf<Coordinate>()
src.forEachLine { line ->
val coords = line
.split(" -> ")
.map { c ->
val (x, y) = c.split(",").map(String::toInt)
Coordinate(x, y)
}
// should be added anyway
rocks.addAll(coords)
for (i in 0 until coords.lastIndex) {
val first = coords[i]
val second = coords[i + 1]
rocks += first.linesBetween(second)
}
}
return rocks
}
data class Coordinate(
val x: Int,
val y: Int
): Comparable<Coordinate> {
override fun compareTo(other: Coordinate): Int {
return if (this.x == other.x) {
this.y.compareTo(other.y)
} else this.x.compareTo(other.x)
}
infix fun lowerThan(other: Coordinate) = this.y > other.y
//infix fun xlt(other: Coordinate) = this.x < other.x
fun down() = Coordinate(x, y + 1)
fun downLeft() = Coordinate(x - 1, y + 1)
fun downRight() = Coordinate(x + 1, y + 1)
}
fun Coordinate.linesBetween(other: Coordinate): Set<Coordinate> {
val line = mutableSetOf<Coordinate>()
var x = this.x
var y = this.y
line += this
line += other
while (x != other.x) {
line.add(Coordinate(x, y))
x -= x.compareTo(other.x)
}
while (y != other.y) {
line.add(Coordinate(x, y))
y -= y.compareTo(other.y)
}
return line
}
class Cave(
val rocks: SortedMap<Int, SortedSet<Int>>
) {
val sand: SortedMap<Int, SortedSet<Int>> = sortedMapOf()
} | 0 | Kotlin | 0 | 0 | eff121af4aa65f33e05eb5e65c97d2ee464d18a6 | 4,804 | advent-of-code-2022-kotlin | Apache License 2.0 |
2020/src/year2021/day13/code.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2021.day13
import util.readAllLines
import kotlin.math.max
data class Dot(val x: Int, val y: Int)
data class Fold(val x: Int, val y: Int)
fun main() {
val dots = mutableSetOf<Dot>()
val folds = mutableListOf<Fold>()
readAllLines("input.txt").forEach { line ->
if (line.startsWith("fold")) {
line.removePrefix("fold along ").split("=").also { (axis, value) ->
val v = value.toInt()
val fold = when (axis) {
"x" -> Fold(v, 0)
"y" -> Fold(0, v)
else -> error("Illegal axis $axis")
}
folds.add(fold)
}
} else if (line.isNotEmpty()) {
line.split(",").let { (x, y) -> dots.add(Dot(x.toInt(), y.toInt())) }
}
}
folds.forEach { fold ->
val removed = mutableSetOf<Dot>()
val added = mutableSetOf<Dot>()
if (fold.x > 0) {
dots.filter { it.x > fold.x }.forEach {
removed.add(it)
added.add(Dot(fold.x + fold.x - it.x, it.y))
}
} else if (fold.y > 0) {
dots.filter { it.y > fold.y }.forEach {
removed.add(it)
added.add(Dot(it.x, fold.y + fold.y - it.y))
}
}
dots.apply {
removeAll(removed)
addAll(added)
}
println(dots.size)
}
var maxX = Int.MIN_VALUE
var maxY = Int.MIN_VALUE
dots.forEach {
maxX = max(maxX, it.x)
maxY = max(maxY, it.y)
}
(0..maxY).forEach { y ->
(0..maxX).forEach { x ->
print(if(dots.contains(Dot(x, y))) "#" else ".")
}
println()
}
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 1,744 | adventofcode | MIT License |
src/main/kotlin/de/tek/adventofcode/y2022/util/algorithms/SetAlgorithms.kt | Thumas | 576,671,911 | false | {"Kotlin": 192328} | package de.tek.adventofcode.y2022.util.algorithms
import de.tek.adventofcode.y2022.util.math.until
import java.math.BigInteger
/**
* Returns a list of all subsets of this set.
*/
fun <T> Set<T>.subsets(): List<Set<T>> {
val elements = this.toList()
val numberOfElements = elements.size
val result = mutableListOf<Set<T>>()
val numberOfElementsInPowerSet = BigInteger.valueOf(2).pow(numberOfElements)
for (bitSet in BigInteger.ZERO until numberOfElementsInPowerSet) {
val combination = mutableSetOf<T>()
for (bit in 0 until numberOfElements) {
if (bitSet.testBit(bit)) {
combination.add(elements[bit])
}
}
result.add(combination)
}
return result
}
/**
* Returns a Sequence of pairs:
* - the first component is the beginning of a permutation of this set for which the given pruneBy function
* returns true; if it returns false for some combination, no combination starting with that combination is included
* in the result; if no pruneBy parameter is given, all permutations are returned
* - the second component is as set of remaining elements of this set that are not part of the permutation.
*/
fun <T> Set<T>.permutations(pruneBy: (List<T>) -> Boolean = { _ -> false }): Sequence<Pair<List<T>, Set<T>>> =
sequence {
val set = this@permutations
val remainingElements = set.toMutableSet()
val stack = mutableListOf(remainingElements.toMutableList())
val permutation = mutableListOf<T>()
val alreadyYielded = Array(set.size) { false }
while (stack.isNotEmpty()) {
val elementsForCurrentPosition = stack.last()
if (elementsForCurrentPosition.isNotEmpty()) {
val element = elementsForCurrentPosition.removeLast()
permutation.add(element)
if (pruneBy(permutation)) {
permutation.removeLast()
if (permutation.size > 0 && !alreadyYielded[permutation.size - 1]) {
yield(Pair(permutation.toList(), remainingElements.toSet()))
alreadyYielded[permutation.size - 1] = true
}
continue
}
alreadyYielded[permutation.size - 1] = false
remainingElements.remove(element)
stack.add(remainingElements.toMutableList())
} else {
stack.removeLast()
if (permutation.size > 0) {
if (!alreadyYielded[permutation.size - 1]) {
yield(Pair(permutation.toList(), remainingElements.toSet()))
}
alreadyYielded[permutation.size - 1] = false
val freeElement = permutation.removeLast()
remainingElements.add(freeElement)
}
}
}
if (permutation.size > 0) {
yield(Pair(permutation.toList(), remainingElements.toSet()))
}
} | 0 | Kotlin | 0 | 0 | 551069a21a45690c80c8d96bce3bb095b5982bf0 | 3,065 | advent-of-code-2022 | Apache License 2.0 |
src/day04/Day04.kt | palpfiction | 572,688,778 | false | {"Kotlin": 38770} | package day04
import readInput
fun main() {
fun expand(assignment: String) =
with(assignment.split("-")) {
(this.component1().toInt()..this.component2().toInt()).toSet()
}
fun part1(input: List<String>): Int =
input.map { it.split(",") }
.map { (first, second) -> expand(first) to expand(second) }
.count { (first, second) -> first.subtract(second).isEmpty() || second.subtract(first).isEmpty() }
fun part2(input: List<String>): Int =
input.map { it.split(",") }
.map { (first, second) -> expand(first) to expand(second) }
.count { (first, second) -> first.intersect(second).isNotEmpty() || second.intersect(first).isNotEmpty() }
val testInput = readInput("/day04/Day04_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("/day04/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7 | 1,020 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/marcdenning/adventofcode/day16/Day16a.kt | marcdenning | 317,730,735 | false | {"Kotlin": 87536} | package com.marcdenning.adventofcode.day16
import java.io.File
import java.util.regex.Pattern
fun main(args: Array<String>) {
val inputLines = File(args[0]).readLines()
val separatorLineIndex = inputLines.indexOf("")
val rules = inputLines.subList(0, separatorLineIndex).map { line ->
parseRule(line)
}
println("Ticket scanning error rate: ${getTicketScanningErrorRate(rules, inputLines)}")
}
fun getTicketScanningErrorRate(rules: List<Rule>, inputLines: List<String>): Int {
val nearbyTicketsLineIndex = inputLines.indexOf("nearby tickets:") + 1
return inputLines.subList(nearbyTicketsLineIndex, inputLines.size).flatMap { ticket ->
ticket.split(',').map { value -> value.toInt() }
}.filter { value ->
rules.all { rule -> !(rule as Rule).isNumberValid(value) }
}.sum()
}
fun parseRule(ruleString: String): Rule {
val matcher = Pattern.compile("([\\w\\s]+):\\s(\\d+)\\-(\\d+)\\sor\\s(\\d+)\\-(\\d+)").matcher(ruleString)
if (!matcher.matches()) {
throw Exception()
}
return Rule(
matcher.group(1),
matcher.group(2).toInt()..matcher.group(3).toInt(),
matcher.group(4).toInt()..matcher.group(5).toInt()
)
}
data class Rule(
val fieldName: String,
val range1: IntRange,
val range2: IntRange
) {
fun isNumberValid(int: Int): Boolean {
return range1.contains(int) || range2.contains(int)
}
}
| 0 | Kotlin | 0 | 0 | b227acb3876726e5eed3dcdbf6c73475cc86cbc1 | 1,435 | advent-of-code-2020 | MIT License |
src/main/kotlin/endredeak/aoc2022/Day17.kt | edeak | 571,891,076 | false | {"Kotlin": 44975} | package endredeak.aoc2022
import kotlin.math.absoluteValue
fun main() {
/**
* Ported Todd's solution: https://todd.ginsberg.com/post/advent-of-code/2022/day17/
*/
solve("Pyroclastic Flow") {
fun Char.asMove() =
when (this) {
'>' -> 1 to 0
'<' -> -1 to 0
else -> error("waat")
}
infix fun Set<Pair<Int, Int>>.move(m: Pair<Int, Int>) =
m.let { (mx, my) -> this.map { (x, y) -> x + mx to y + my } }.toSet()
fun <T> List<T>.nth(n: Int) = this[n % this.size]
val p = listOf(
setOf(0 to 0, 1 to 0, 2 to 0, 3 to 0),
setOf(1 to 0, 0 to -1, 1 to -1, 2 to -1, 1 to -2),
setOf(0 to 0, 1 to 0, 2 to 0, 2 to -1, 2 to -2),
setOf(0 to 0, 0 to -1, 0 to -2, 0 to -3),
setOf(0 to 0, 1 to 0, 0 to -1, 1 to -1)
)
val input = lines.first().map { it.asMove() }
val grid = (0..6).map { it to 0 }.toMutableSet()
val jets = input
var shapeIndex = 0
var jetIndex = 0
fun simulate() {
var thisShape = p.nth(shapeIndex++) move (2 to (grid.minOf { it.second } - 4))
do {
val jettedShape = thisShape move jets.nth(jetIndex++)
if (jettedShape.all { it.first in (0..6) } && jettedShape.intersect(grid).isEmpty()) {
thisShape = jettedShape
}
thisShape = thisShape move (0 to 1)
} while (thisShape.intersect(grid).isEmpty())
grid += thisShape move (0 to -1)
}
part1(3130) {
repeat(2022) { simulate() }
grid.minOf { it.second }.absoluteValue
}
fun Set<Pair<Int ,Int>>.norm() =
groupBy { it.first }
.entries
.sortedBy { it.key }
.map { pointList -> pointList.value.minBy { it.second } }
.let { points ->
val normalTo = this.minOf { it.second }
points.map { normalTo - it.second }
}
shapeIndex = 0
jetIndex = 0
fun calculateHeight(n: Long): Long {
val seen: MutableMap<Triple<List<Int>, Int, Int>, Pair<Int, Int>> = mutableMapOf()
while (true) {
simulate()
val state = Triple(grid.norm(), shapeIndex % p.size, jetIndex % jets.size)
if (state in seen) {
val (startShapeIndex, startHeight) = seen.getValue(state)
val shapesPerLoop: Long = shapeIndex - 1L - startShapeIndex
val totalLoops: Long = (n - startShapeIndex) / shapesPerLoop
val remainingBlocksFromClosestLoopToGoal: Long =
(n - startShapeIndex) - (totalLoops * shapesPerLoop)
val heightGainedSinceLoop = grid.minOf { it.second }.absoluteValue - startHeight
repeat(remainingBlocksFromClosestLoopToGoal.toInt()) {
simulate()
}
return grid.minOf { it.second }.absoluteValue + (heightGainedSinceLoop * (totalLoops - 1))
}
seen[state] = shapeIndex - 1 to grid.minOf { it.second }.absoluteValue
}
}
part2(1556521739139) {
calculateHeight(1000000000000L - 1)
}
}
} | 0 | Kotlin | 0 | 0 | e0b95e35c98b15d2b479b28f8548d8c8ac457e3a | 3,451 | AdventOfCode2022 | Do What The F*ck You Want To Public License |
src/Day05.kt | dyomin-ea | 572,996,238 | false | {"Kotlin": 21309} | fun main() {
fun stacksFrom(input: List<String>): List<MutableList<Char>> =
(1..input.first().length step 4)
.map { c ->
input.map { it[c] }
.filterNot(Char::isWhitespace)
.reversed()
.toMutableList()
}
fun moves9000From(input: List<String>): List<Move9000> {
fun movesFrom(input: String): List<Move9000> {
val (count, f, t) = """move (\d+) from (\d+) to (\d+)"""
.toRegex()
.find(input)!!
.destructured
return (1..count.toInt()).map { Move9000(f.toInt() - 1, t.toInt() - 1) }
}
return input.flatMap(::movesFrom)
}
fun moves9001From(input: List<String>): List<Move9001> {
fun movesFrom(input: String): List<Move9001> {
val (count, f, t) = """move (\d+) from (\d+) to (\d+)"""
.toRegex()
.find(input)!!
.destructured
return listOf(Move9001(f.toInt() - 1, t.toInt() - 1, count.toInt()))
}
return input.flatMap(::movesFrom)
}
fun makeMoves(moves: List<(List<MutableList<Char>>) -> Unit>, stacks: List<MutableList<Char>>) {
moves.forEach { it(stacks) }
}
fun part1(input: List<String>): String {
val stacks = stacksFrom(
input.takeWhile { !it.contains('1') }
)
val moves = moves9000From(
input.filter { it.startsWith("move ") }
)
makeMoves(moves, stacks)
return stacks.joinToString(separator = "") {
it.last()
.toString()
}
}
fun part2(input: List<String>): String {
val stacks = stacksFrom(
input.takeWhile { !it.contains('1') }
)
val moves = moves9001From(
input.filter { it.startsWith("move ") }
)
makeMoves(moves, stacks)
return stacks.joinToString(separator = "") {
it.last()
.toString()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
data class Move9000(
val from: Int,
val to: Int,
) : (List<MutableList<Char>>) -> Unit {
override operator fun invoke(input: List<MutableList<Char>>) {
val last = input[from].last()
input[from].removeLast()
input[to].add(last)
}
}
data class Move9001(
val from: Int,
val to: Int,
val count: Int,
) : (List<MutableList<Char>>) -> Unit {
override operator fun invoke(input: List<MutableList<Char>>) {
val load = input[from].takeLast(count)
input[from].removeLast(count)
input[to].addAll(load)
}
private fun <T> MutableList<T>.removeLast(count: Int) {
var c = count
while (c > 0) {
c--
removeLast()
}
}
} | 0 | Kotlin | 0 | 0 | 8aaf3f063ce432207dee5f4ad4e597030cfded6d | 2,552 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/Triangle.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* Triangle
* @see <a href="https://leetcode.com/problems/triangle/">Source</a>
*/
fun interface Triangle {
operator fun invoke(triangle: List<List<Int>>): Int
}
/**
* Approach 1: Dynamic Programming (Bottom-up: In-place)
* Time Complexity: O(n^2).
* Space Complexity: O(1).
*/
class TriangleBottomUp : Triangle {
override operator fun invoke(triangle: List<List<Int>>): Int {
val result = triangle.toMutableList().map { it.toMutableList() }
for (row in 1 until result.size) {
for (col in 0..row) {
var smallestAbove = Int.MAX_VALUE
if (col > 0) {
smallestAbove = result[row - 1][col - 1]
}
if (col < row) {
smallestAbove = min(smallestAbove, result[row - 1][col])
}
val path = smallestAbove + result[row][col]
result[row][col] = path
}
}
return result[result.size - 1].minOrNull() ?: -1
}
}
/**
* Approach 2: Dynamic Programming (Bottom-up: Auxiliary Space)
* Time Complexity: O(n^2).
* Space Complexity: O(n).
*/
class TriangleAuxiliarySpace : Triangle {
override operator fun invoke(triangle: List<List<Int>>): Int {
var prevRow = triangle[0]
for (row in 1 until triangle.size) {
val currRow: MutableList<Int> = ArrayList()
for (col in 0..row) {
var smallestAbove = Int.MAX_VALUE
if (col > 0) {
smallestAbove = prevRow[col - 1]
}
if (col < row) {
smallestAbove = min(smallestAbove, prevRow[col])
}
currRow.add(smallestAbove + triangle[row][col])
}
prevRow = currRow
}
return prevRow.minOrNull() ?: -1
}
}
/**
* Approach 3: Dynamic Programming (Bottom-up: Flip Triangle Upside Down)
*/
class TriangleUpsideDown : Triangle {
override operator fun invoke(triangle: List<List<Int>>): Int {
var belowRow = triangle[triangle.size - 1]
for (row in triangle.size - 2 downTo 0) {
val currRow: MutableList<Int> = ArrayList()
for (col in 0..row) {
val bestBelow = min(belowRow[col], belowRow[col + 1])
currRow.add(bestBelow + triangle[row][col])
}
belowRow = currRow
}
return belowRow[0]
}
}
/**
* Approach 4: Memoization (Top-Down)
* Time Complexity: O(n^2).
* Space Complexity: O(n^2).
*/
class TriangleMemoization : Triangle {
private var memoTable: MutableMap<String, Int> = HashMap()
private lateinit var triangle: List<List<Int>>
override operator fun invoke(triangle: List<List<Int>>): Int {
this.triangle = triangle
return minPath(0, 0)
}
private fun minPath(row: Int, col: Int): Int {
val params = "$row:$col"
if (memoTable.containsKey(params)) {
return memoTable[params] ?: -1
}
var path = triangle[row][col]
if (row < triangle.size - 1) {
path += min(minPath(row + 1, col), minPath(row + 1, col + 1))
}
memoTable[params] = path
return path
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,931 | kotlab | Apache License 2.0 |
src/day14/Day14.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day14
import readInput
import java.awt.Point
import java.util.Stack
fun main() {
val rocksPositionSet = hashSetOf<Point>()
val sandPositionSet = hashSetOf<Point>()
var minX = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
var maxY = Int.MIN_VALUE
fun resetGlobalStuff() {
rocksPositionSet.clear()
sandPositionSet.clear()
minX = Int.MAX_VALUE
maxX = Int.MIN_VALUE
maxY = Int.MIN_VALUE
}
fun parseInput(input: List<String>) {
resetGlobalStuff()
input.forEach {
it.split("->").map { it.trim() }.windowed(2)
.forEach {
val from = it[0].split(",").map { it.trim().toInt() }.let { Point(it[0], it[1]) }
val to = it[1].split(",").map { it.trim().toInt() }.let { Point(it[0], it[1]) }
maxX = maxOf(maxX, maxOf(from.x, to.x))
minX = minOf(minX, minOf(from.x, to.x))
maxY = maxOf(maxY, maxOf(from.y, to.y))
if (from.x == to.x) { // horizontal
var colRange = from.y..to.y
if (to.y < from.y) colRange = to.y..from.y
for (col in colRange) rocksPositionSet.add(Point(from.x, col))
} else { // vertical
var rowRange = from.x..to.x
if (to.x < from.x) rowRange = to.x..from.x
for (row in rowRange) rocksPositionSet.add(Point(row, to.y))
}
}
}
}
fun part1(input: List<String>): Int {
parseInput(input)
fun produceSand(currentPosition: Point): Int {
if (currentPosition.y > maxY || currentPosition.x < minX || currentPosition.x > maxX) return -1
val down = Point(currentPosition.x, currentPosition.y + 1)
if (!rocksPositionSet.contains(down) && !sandPositionSet.contains(down)) return produceSand(down)
val downleft = Point(currentPosition.x - 1, currentPosition.y + 1)
if (!rocksPositionSet.contains(downleft) && !sandPositionSet.contains(downleft)) return produceSand(downleft)
val downRight = Point(currentPosition.x + 1, currentPosition.y + 1)
if (!rocksPositionSet.contains(downRight) && !sandPositionSet.contains(downRight)) return produceSand(downRight)
sandPositionSet.add(currentPosition)
return 0
}
while (true) {
val value = produceSand(Point(500, 0))
if (value == -1) break
}
return sandPositionSet.size
}
fun part2(input: List<String>): Int {
parseInput(input)
maxY += 2
fun dfs(posn: Point): Point {
val stack = Stack<Point>()
stack.push(posn)
while (stack.isNotEmpty()) {
val curr = stack.pop()
val down = Point(curr.x, curr.y + 1)
val downleft = Point(curr.x - 1, curr.y + 1)
val downRight = Point(curr.x + 1, curr.y + 1)
when {
!rocksPositionSet.contains(down) && !sandPositionSet.contains(down) && down.y < maxY -> stack.push(down)
!rocksPositionSet.contains(downleft) && !sandPositionSet.contains(downleft) && downleft.y < maxY -> stack.push(downleft)
!rocksPositionSet.contains(downRight) && !sandPositionSet.contains(downRight) && downRight.y < maxY -> stack.push(downRight)
else -> sandPositionSet.add(curr)
}
if (down == Point(500, 0) || downleft == Point(500, 0) || downRight == Point(500, 0)) return Point(500, 0)
}
return posn
}
while (true){
dfs(Point(500,0))
val downBlocker = Point(500,1)
val leftBlocker = Point(499,1)
val rightBlocker = Point(501,1)
if (
(rocksPositionSet.contains(downBlocker) || sandPositionSet.contains(downBlocker))
&&
(rocksPositionSet.contains(leftBlocker) || sandPositionSet.contains(leftBlocker))
&&
(rocksPositionSet.contains(rightBlocker) || sandPositionSet.contains(rightBlocker))
) break
}
return sandPositionSet.size + 1
}
val testInput = readInput("/day14/Day14_test")
println(part1(testInput))
println(part2(testInput))
println("----------------------")
val input = readInput("/day14/Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 4,641 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/day10/Day10.kt | mortenberg80 | 574,042,993 | false | {"Kotlin": 50107} | package day10
class Day10(private val input: List<String>) {
private val commands = parseCommands(input)
private fun parseCommands(input: List<String>): List<Command> {
return input.flatMap { parseCommand(it) }
}
private fun parseCommand(input: String): List<Command> {
if (input == "noop") return listOf(Command.Noop)
val split = input.split(" ")
if (split[0] == "addx") return listOf(Command.AddFirstCycle(split[1].toInt()), Command.AddSecondCycle(split[1].toInt()))
return listOf()
}
fun part1(): Int {
val _20 = commands.take(19).fold(1) { initial, command -> initial + command.compute() } * 20
val _60 = commands.take(59).fold(1) { initial, command -> initial + command.compute() } * 60
val _100 = commands.take(99).fold(1) { initial, command -> initial + command.compute() } * 100
val _140 = commands.take(139).fold(1) { initial, command -> initial + command.compute() } * 140
val _180 = commands.take(179).fold(1) { initial, command -> initial + command.compute() } * 180
val _220 = commands.take(219).foldIndexed(1) { i, initial, command -> initial + command.compute() } * 220
return _20 + _60 + _100 + _140 + _180 + _220
}
fun part2(): String {
val emptyRow = (0 until 40).joinToString("") { "." }
val firstRow = Row(cyclePosition = 0, currentRow = emptyRow, 1)
val row1 = commands.take(40).fold(firstRow) { row, command -> row.handleCommand(command)}
val secondRow = Row(cyclePosition = 0, currentRow = emptyRow, registerX = row1.registerX)
val row2 = commands.drop(40).take(40).fold(secondRow) { row, command -> row.handleCommand(command)}
val third = Row(cyclePosition = 0, currentRow = emptyRow, registerX = row2.registerX)
val row3 = commands.drop(80).take(40).fold(third) { row, command -> row.handleCommand(command)}
val fourth = Row(cyclePosition = 0, currentRow = emptyRow, row3.registerX)
val row4 = commands.drop(120).take(40).fold(fourth) { row, command -> row.handleCommand(command)}
val fifth = Row(cyclePosition = 0, currentRow = emptyRow, registerX = row4.registerX)
val row5 = commands.drop(160).take(40).fold(fifth) { row, command -> row.handleCommand(command)}
val sixth = Row(cyclePosition = 0, currentRow = emptyRow, registerX = row5.registerX)
val row6 = commands.drop(200).take(40).fold(sixth) { row, command -> row.handleCommand(command)}
return "\n${row1.currentRow}\n" +
"${row2.currentRow}\n" +
"${row3.currentRow}\n" +
"${row4.currentRow}\n" +
"${row5.currentRow}\n" +
"${row6.currentRow}\n"
}
}
sealed class Command {
abstract fun compute(): Int
object Noop : Command() {
override fun compute(): Int = 0
}
data class AddFirstCycle(val value: Int) : Command() {
override fun compute(): Int = 0
}
data class AddSecondCycle(val value: Int) : Command() {
override fun compute(): Int = value
}
}
data class Row(val cyclePosition: Int, val currentRow: String, val registerX: Int) {
fun handleCommand(command: Command): Row {
val nextRow = drawPixel()
val nextCyclePosition = cyclePosition + 1
val nextRegisterX = registerX + command.compute()
return Row(nextCyclePosition, nextRow, nextRegisterX)
}
fun drawPixel(): String {
return if ((registerX - 1..registerX + 1).contains(cyclePosition)) currentRow.replaceRange(cyclePosition, cyclePosition+1, "#")
else currentRow
}
}
data class Row2(val cyclePosition: Int, val currentRow: String, val registerX: Int) {
fun handleCommand(command: Command): Row {
val nextRow = drawPixel()
val nextCyclePosition = cyclePosition + 1
val nextRegisterX = registerX + command.compute()
return Row(nextCyclePosition, nextRow, nextRegisterX)
}
fun drawPixel(): String {
return if ((registerX - 1..registerX + 1).contains(cyclePosition)) currentRow.replaceRange(cyclePosition, cyclePosition+1, "#")
else currentRow
}
}
fun main() {
val testInput = Day10::class.java.getResourceAsStream("/day10_test.txt").bufferedReader().readLines()
val input = Day10::class.java.getResourceAsStream("/day10_input.txt").bufferedReader().readLines()
val day10test = Day10(testInput)
val day10input = Day10(input)
println("Day10 part 1 test result: ${day10test.part1()}")
println("Day10 part 1 result: ${day10input.part1()}")
println("Day10 part 2 test result: ${day10test.part2()}")
println("Day10 part 2 result: ${day10input.part2()}")
}
| 0 | Kotlin | 0 | 0 | b21978e145dae120621e54403b14b81663f93cd8 | 4,752 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/VerifyPreorderInBinarySearchTree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Stack
// Verify Preorder Sequence in Binary Search Tree
fun interface VerifyPreorderInBinarySearchTreeStrategy {
operator fun invoke(preorder: IntArray): Boolean
}
class VerifyPreorderInBinarySearchTreeBF : VerifyPreorderInBinarySearchTreeStrategy {
override operator fun invoke(preorder: IntArray): Boolean {
var low = Int.MIN_VALUE
var i = -1
for (p in preorder) {
if (p < low) return false
while (i >= 0 && p > preorder[i]) low = preorder[i--]
preorder[++i] = p
}
return true
}
}
class VerifyPreorderInBinarySearchTreeStack : VerifyPreorderInBinarySearchTreeStrategy {
override operator fun invoke(preorder: IntArray): Boolean {
var low = Int.MIN_VALUE
val path: Stack<Int> = Stack()
for (p in preorder) {
if (p < low) return false
while (!path.empty() && p > path.peek()) low = path.pop()
path.push(p)
}
return true
}
}
class VerifyPreorderInBinarySearchTreeRecursion : VerifyPreorderInBinarySearchTreeStrategy {
private var i = 1
override operator fun invoke(preorder: IntArray): Boolean {
return preorder.isEmpty() || check(preorder, Integer.MIN_VALUE, preorder.first()) && check(
preorder,
preorder.first(),
Integer.MAX_VALUE,
)
}
private fun check(a: IntArray, left: Int, right: Int): Boolean {
if (i == a.size || a[i] > right) return true
val mid = a[i++]
return mid > left && check(a, left, mid) && check(a, mid, right)
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,268 | kotlab | Apache License 2.0 |
src/main/kotlin/cloud/dqn/leetcode/TrappingRainWaterKt.kt | aviuswen | 112,305,062 | false | null | package cloud.dqn.leetcode
/**
* https://leetcode.com/problems/trapping-rain-water/description/
Given n non-negative integers representing an elevation map where
the width of each bar is 1, compute how much water it is able to
trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
*/
class TrappingRainWaterKt {
class Solution {
/**
Algo0:
time: O(n^2)
space: O(1)
For each bucket {
Compute the max height of left
compute the max height of right
min(maxLeft, maxRight)
summation(max(min - height, 0)
}
*/
private fun max(left: Int, right: Int): Int {
return if (left < right) right else left
}
private fun min(left: Int, right: Int): Int {
return if (left < right) left else right
}
private fun maxLeft(index: Int, arr: IntArray): Int {
var height = 0
var leftIndex = index - 1
while (leftIndex >= 0) {
height = max(arr[leftIndex], height)
leftIndex--
}
return height
}
private fun maxRight(index: Int, arr: IntArray): Int {
var height = 0
var rightIndex = index + 1
while (rightIndex < arr.size) {
height = max(height, arr[rightIndex])
rightIndex++
}
return height
}
private fun heightAt(index: Int, arr: IntArray): Int {
return arr[index]
}
fun trap(height: IntArray): Int {
/**
For each bucket {
Compute the max height of left
compute the max height of right
min(maxLeft, maxRight)
summation(max(min - height, 0)
}
*/
var total = 0
var left = 0
var right = 0
var minLeftRight = 0
height.forEachIndexed { index, indexHeight ->
left = maxLeft(index, height)
right = maxRight(index, height)
minLeftRight = min(left, right)
if (minLeftRight > indexHeight) {
total += (minLeftRight - indexHeight)
}
}
return total
}
fun trapFaster(height: IntArray): Int {
/**
time: O(n)
size: O(n)
maxRight: IntArray = Compute max right for all by walking from right to left
maxLeft: IntArray = compute max left for all by walking from left to right
for each index {
maxAtIndex = min(maxRight[index], maxLeft[index])
if (maxAtIndex > indexHeight) {
summation(maxAtIndex - indexHeight)
}
}
*/
if (height.size <= 2) {
return 0
}
var maxRightArray = IntArray(height.size)
// maxRightArray[maxRightArray.size - 1] = 0 // defaults at this
var maxOfTwoOver = height[maxRightArray.size - 1]
maxRightArray[maxRightArray.size - 2] = maxOfTwoOver
var i = height.size - 3
while (i >= 0) {
maxOfTwoOver = max(height[i + 1], maxOfTwoOver)
maxRightArray[i] = maxOfTwoOver
i--
}
var maxLeftArray = IntArray(height.size)
maxLeftArray[1] = height[0]
maxOfTwoOver = height[0]
i = 2
while (i < height.size) {
maxOfTwoOver = max(height[i - 1], maxOfTwoOver)
maxLeftArray[i] = maxOfTwoOver
i++
}
var total = 0
height.forEachIndexed { index, indexHeight ->
i = min(maxLeftArray[index], maxRightArray[index])
if (i > indexHeight) {
total += (i - indexHeight)
}
}
return total
}
}
} | 0 | Kotlin | 0 | 0 | 23458b98104fa5d32efe811c3d2d4c1578b67f4b | 4,187 | cloud-dqn-leetcode | No Limit Public License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.