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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aoc-2022/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentytwo/Day02.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwentytwo
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.readDayInput
class Day02 : Day<Int> {
private val input: Sequence<Pair<String, String>> =
readDayInput()
.lineSequence()
.map { line ->
val (a, b) = line.split(' ')
a to b
}
private fun String.parseShape(): Shape {
return when (this) {
"A", "X" -> Shape.Rock
"B", "Y" -> Shape.Paper
"C", "Z" -> Shape.Scissors
else -> error("Invalid input $input")
}
}
enum class Shape(val score: Int) {
Rock(score = 1),
Paper(score = 2),
Scissors(score = 3)
}
private data class Round(
val input: Shape,
val output: Shape
)
private enum class Outcome(val score: Int) {
Loss(score = 0),
Draw(score = 3),
Win(score = 6)
}
private fun outcomeFor(opponent: Shape, us: Shape): Outcome =
when (opponent) {
Shape.Rock -> when (us) {
Shape.Rock -> Outcome.Draw
Shape.Paper -> Outcome.Win
Shape.Scissors -> Outcome.Loss
}
Shape.Paper -> when (us) {
Shape.Rock -> Outcome.Loss
Shape.Paper -> Outcome.Draw
Shape.Scissors -> Outcome.Win
}
Shape.Scissors -> when (us) {
Shape.Rock -> Outcome.Win
Shape.Paper -> Outcome.Loss
Shape.Scissors -> Outcome.Draw
}
}
private val Round.score: Int
get() = output.score + outcomeFor(input, output).score
override fun step1(): Int = input
.map { (input, respondWith) ->
Round(
input = input.parseShape(),
output = respondWith.parseShape()
)
}
.sumOf { round -> round.score }
override val expectedStep1 = 12_772
private data class Strategy(
val input: Shape,
val suggestedOutcome: Outcome
)
private fun String.parseOutcome(): Outcome =
when (this) {
"X" -> Outcome.Loss
"Y" -> Outcome.Draw
"Z" -> Outcome.Win
else -> error("Invalid input $input")
}
private val Strategy.suggestedOutput: Shape
get() = Shape.values().first { possibleShape ->
outcomeFor(input, possibleShape) == suggestedOutcome
}
override fun step2(): Int = input
.map { (input, suggestedOutcome) ->
Strategy(
input = input.parseShape(),
suggestedOutcome = suggestedOutcome.parseOutcome()
)
}
.map { strategy ->
Round(
input = strategy.input,
output = strategy.suggestedOutput
)
}
.sumOf { round -> round.score }
override val expectedStep2: Int = 11_618
}
| 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 3,013 | adventofcode | Apache License 2.0 |
src/main/kotlin/aoc/year2020/Day04.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2020
import aoc.Puzzle
/**
* [Day 4 - Advent of Code 2020](https://adventofcode.com/2020/day/4)
*/
object Day04 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int {
val reqFields = setOf(
"byr",
"iyr",
"eyr",
"hgt",
"hcl",
"ecl",
"pid",
//"cid",
)
val deque = ArrayDeque<HashSet<String>>().apply { addLast(hashSetOf()) }
input.lineSequence().flatMap { it.splitToSequence(' ') }
.map { it.split(':', limit = 2).first() }
.forEach {
if (it.isEmpty()) deque.addLast(HashSet())
else deque.last().add(it)
}
return deque.count { it.containsAll(reqFields) }
}
override fun solvePartTwo(input: String): Int {
val deque = ArrayDeque<MutableList<String>>().apply { addLast(mutableListOf()) }
input.lineSequence().flatMap { it.splitToSequence(' ') }
.forEach {
if (it.isEmpty()) deque.addLast(mutableListOf())
else deque.last().add(it)
}
return deque.count(::isValid)
}
private fun isValid(fields: List<String>): Boolean {
val map = fields.associate { it.split(':', limit = 2).let { (k, v) -> k to v } }
val byr = map["byr"]
?.let { """^([0-9]{4})$""".toRegex().find(it)?.groupValues?.firstOrNull() }
?.toIntOrNull()
?.let { it in 1920..2002 }
?: false
val iyr = map["iyr"]
?.let { """^([0-9]{4})$""".toRegex().find(it)?.groupValues?.firstOrNull() }
?.toIntOrNull()
?.let { it in 2010..2020 }
?: false
val eyr = map["eyr"]
?.let { """^([0-9]{4})$""".toRegex().find(it)?.groupValues?.firstOrNull() }
?.toIntOrNull()
?.let { it in 2020..2030 }
?: false
val hgt = map["hgt"]
?.let { """^(\d+)(cm|in)$""".toRegex().find(it)?.destructured }
?.let { (i, unit) ->
when (unit) {
"cm" -> i.toInt() in 150..193
"in" -> i.toInt() in 59..76
else -> error("Unexpected unit: $unit")
}
}
?: false
val hcl = map["hcl"]
?.let { """^#([0-9a-f]{6})$""".toRegex().find(it)?.groupValues?.firstOrNull() } != null
val ecl = map["ecl"]
?.let { it in setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") }
?: false
val pid = map["pid"]
?.let { """^([0-9]{9})$""".toRegex().find(it)?.groupValues?.firstOrNull() } != null
return byr && iyr && eyr && hgt && hcl && ecl && pid
}
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 2,806 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem2466/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2466
/**
* LeetCode page: [2466. Count Ways To Build Good Strings](https://leetcode.com/problems/count-ways-to-build-good-strings/);
*/
class Solution {
private val mod = 1_000_000_007 // modulo required by the problem
/* Complexity:
* Time O(high) and Space O(high-low);
*/
fun countGoodStrings(low: Int, high: Int, zero: Int, one: Int): Int {
/* The idea is to apply dynamic programming. Let subResults[i] be the number of ways
* to build a good string of length i.
*/
val subResults = hashMapOf<Int, Int>().apply {
updateBaseCases(this)
updateRemainingCases(low, high, zero, one, this)
}
return originalProblem(low, high, subResults)
}
private fun updateBaseCases(subResults: HashMap<Int, Int>) {
// There is only one way to build an empty string
subResults[0] = 1
}
private fun updateRemainingCases(
low: Int, high: Int,
zero: Int, one: Int,
subResults: HashMap<Int, Int>
) {
/* Solve the sub results in increasing order of length using the relation that
* subResults[i-zero] + subResults[i-one] = subResults[i].
*/
for (length in 0..high) {
val subResult = subResults[length] ?: continue
// Contribute the sub result of length to the cases that are related to it
subResults[length + zero] = subResults[length + zero]
?.let { (it + subResult) % mod }
?: subResult
subResults[length + one] = subResults[length + one]
?.let { (it + subResult) % mod }
?: subResult
// The sub result of length is no longer needed if it is less than low
if (length < low) {
subResults.remove(length)
}
}
}
private fun originalProblem(low: Int, high: Int, subResults: HashMap<Int, Int>): Int {
// The original problem is the sum of sub results from low to high
var originalProblem = 0
for (length in low..high) {
val subResult = subResults[length] ?: continue
originalProblem = (originalProblem + subResult) % mod
}
return originalProblem
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,311 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/java/challenges/cracking_coding_interview/bit_manipulation/flip_bit_to_win/QuestionB.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.bit_manipulation.flip_bit_to_win
import kotlin.math.max
/**
* You have an integer, and you can flip exactly one bit from a 0 to a 1.
* Write code to find the length of the longest sequence of ls you could create.
* EXAMPLE
* Input: 1775 (or: 11011101111) Output: 8
*/
object QuestionB {
fun longestSequence(n: Int): Int {
if (n == -1) return Integer.BYTES * 8
val sequences = getAlternatingSequences(n)
return findLongestSequence(sequences)
}
/* Return a list of the sizes of the sequences. The sequence starts
* off with the number of 0s (which might be 0) and then alternates
* with the counts of each value.*/
private fun getAlternatingSequences(n: Int): ArrayList<Int> {
var n = n
val sequences = ArrayList<Int>()
var searchingFor = 0
var counter = 0
for (i in 0 until Integer.BYTES * 8) {
if (n and 1 != searchingFor) {
sequences.add(counter)
searchingFor = n and 1 // Flip 1 to 0 or 0 to 1
counter = 0
}
counter++
n = n ushr 1
}
sequences.add(counter)
return sequences
}
private fun findLongestSequence(seq: ArrayList<Int>): Int {
var maxSeq = 1
var i = 0
while (i < seq.size) {
val zerosSeq = seq[i]
val onesSeqPrev = if (i - 1 >= 0) seq[i - 1] else 0
val onesSeqNext = if (i + 1 < seq.size) seq[i + 1] else 0
var thisSeq = 0
if (zerosSeq == 1) { // Can merge
thisSeq = onesSeqNext + 1 + onesSeqPrev
} else if (zerosSeq > 1) { // Just add a one to either side
thisSeq = 1 + max(onesSeqPrev, onesSeqNext)
} else if (zerosSeq == 0) { // No zero, but take either side
thisSeq = max(onesSeqPrev, onesSeqNext)
}
maxSeq = max(thisSeq, maxSeq)
i += 2
}
return maxSeq
}
@JvmStatic
fun main(args: Array<String>) {
val originalNumber = 1775
val newNumber = longestSequence(originalNumber)
println(Integer.toBinaryString(originalNumber))
println(newNumber)
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,281 | CodingChallenges | Apache License 2.0 |
src/Day08.kt | brunojensen | 572,665,994 | false | {"Kotlin": 13161} | fun main() {
fun part1(input: List<String>): Int {
val matrix = input.map { it.map { v -> v.digitToInt() } }
val visible = Array(matrix.size) { BooleanArray(matrix[0].size) }
val edgesCount = (matrix.size * 2 + matrix[0].size * 2) - 4
for (x in 1..matrix.size - 2) {
for (y in 1..matrix[0].size - 2) {
val curr = matrix[x][y]
print(curr)
}
println()
}
return edgesCount + visible.sumOf { it.count { v -> v } }
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08.test")
check(part1(testInput) == 21)
check(part2(testInput) == 0)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2707e76f5abd96c9d59c782e7122427fc6fdaad1 | 798 | advent-of-code-kotlin-1 | Apache License 2.0 |
y2022/src/main/kotlin/adventofcode/y2022/Day25.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
object Day25 : AdventSolution(2022, 25, "Full of Hot Air") {
override fun solvePartOne(input: String) =
input.lineSequence().map { fromBalancedQuinary(it) }.sum().toBalancedQuinary()
private fun fromBalancedQuinary(it: String): Long = it.asSequence().fold(0L) { acc, digit ->
val i = when (digit) {
'=' -> -2
'-' -> -1
'0' -> 0
'1' -> 1
'2' -> 2
else -> throw NumberFormatException(it)
}
acc * 5 + i
}
private fun Long.toBalancedQuinary(): String {
val quinary = this.toString(5)
val x = quinary.reversed().map { Character.getNumericValue(it) }.scan((0 to 0)) { (_, carry), digit ->
val n = digit + carry
if (n > 2) n - 5 to 1 else n to 0
}
val withcarry = if (x.last().second == 1) x + (1 to 0) else x
return withcarry.drop(1).reversed().map { it.first }.joinToString("") {
when (it) {
-2 -> "="
-1 -> "-"
else -> it.toString()
}
}
}
override fun solvePartTwo(input: String) = "Free Star!"
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,244 | advent-of-code | MIT License |
src/main/kotlin/day3/solver.kt | derekaspaulding | 317,756,568 | false | null | package day3
import java.io.File
fun solveProblemOne(rawGrid: List<String>, slope: Pair<Int, Int> = Pair(1, 3)): Int {
val grid = Grid(rawGrid)
var x = 0
var y = 0
var trees = 0
while (y < grid.height) {
if (grid.isTree(x, y)) {
trees += 1
}
x += slope.second
y += slope.first
}
return trees
}
fun solveProblemTwo(rawGrid: List<String>): List<Int> {
val slopes = listOf<Pair<Int, Int>>(
Pair(1, 1),
Pair(1, 3),
Pair(1, 5),
Pair(1, 7),
Pair(2, 1)
)
return slopes
.map { solveProblemOne(rawGrid, it) }
}
fun main() {
val grid = File("src/main/resources/day3/input.txt")
.useLines { it.toList() }
println("Trees: ${solveProblemOne(grid)}")
val solution = solveProblemTwo(grid)
val product = solution.reduce{acc, treeCount -> acc * treeCount}
val productString = solution.joinToString(separator = " x ") { it.toString() }
println("$productString = $product")
}
| 0 | Kotlin | 0 | 0 | 0e26fdbb3415fac413ea833bc7579c09561b49e5 | 1,030 | advent-of-code-2020 | MIT License |
src/main/kotlin/_2022/Day21.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readInput
fun main() {
fun dfs(
monkeyName: String,
monkeyMap: Map<String, MathMonkey>
): Long {
val currentMonkey = monkeyMap[monkeyName]!!
if (currentMonkey.simpleNumber > -1L) {
return currentMonkey.simpleNumber
}
val firstMonkeyValue = dfs(currentMonkey.firstMonkey!!, monkeyMap)
val secondMonkeyValue = dfs(currentMonkey.secondMonkey!!, monkeyMap)
return currentMonkey.operation!!.invoke(firstMonkeyValue, secondMonkeyValue)
}
fun isInFirstChain(
monkeyName: String,
endMonkeyName: String,
monkeyMap: Map<String, MathMonkey>
): Boolean {
val currentMonkey = monkeyMap[monkeyName]!!
val parentMonkey = monkeyMap.values.find { it.firstMonkey == monkeyName || it.secondMonkey == monkeyName }!!
if (parentMonkey.name == endMonkeyName) {
return parentMonkey.firstMonkey == currentMonkey.name
}
return isInFirstChain(parentMonkey.name, endMonkeyName, monkeyMap)
}
fun parseInput(input: List<String>): Map<String, MathMonkey> {
return input.associate {
val (name, operation) = it.split(":")
if (operation.trim().toLongOrNull() != null) {
name to MathMonkey(name, operation.trim().toLong(), null, null, null)
} else {
val (firstMonkey, operator, secondMonkey) = operation.trim()
.split(" ")
var mathOperation: ((Long, Long) -> Long)? = null
when (operator) {
"+" -> mathOperation = Long::plus
"-" -> mathOperation = Long::minus
"*" -> mathOperation = Long::times
"/" -> mathOperation = Long::div
}
name to MathMonkey(name, -1, mathOperation, firstMonkey, secondMonkey)
}
}
}
fun part1(input: List<String>): Long {
val monkeyMap = parseInput(input)
return dfs("root", monkeyMap)
}
fun solveEquation(
endMonkey: String,
startMonkey: String,
endValue: Long,
monkeyMap: Map<String, MathMonkey>
): Long {
println("$endValue")
if (startMonkey == endMonkey) {
return endValue
}
val currentMonkey = monkeyMap[startMonkey]!!
val inFirstChain = isInFirstChain(endMonkey, startMonkey, monkeyMap)
var value = if (inFirstChain) {
dfs(currentMonkey.secondMonkey!!, monkeyMap)
} else {
dfs(currentMonkey.firstMonkey!!, monkeyMap)
}
val operation = currentMonkey.operation!!
val plusOperation: (Long, Long) -> Long = Long::plus
val minusOperation: (Long, Long) -> Long = Long::minus
val timesOperation: (Long, Long) -> Long = Long::times
val divOperation: (Long, Long) -> Long = Long::div
var result = 0L
when (operation) {
plusOperation -> result = endValue - value
minusOperation -> result = if (inFirstChain) {endValue + value} else { value - endValue }
timesOperation -> result = endValue / value
divOperation -> result = if (inFirstChain) {endValue * value} else {value / endValue}
}
return if (inFirstChain) {
solveEquation(endMonkey, currentMonkey.firstMonkey!!, result, monkeyMap)
} else {
solveEquation(endMonkey, currentMonkey.secondMonkey!!, result, monkeyMap)
}
}
fun part2(input: List<String>): Long {
val monkeyMap = parseInput(input)
val rootMonkey = monkeyMap["root"]!!
val inFirstChain = isInFirstChain("humn", "root", monkeyMap)
val endValue: Long = if (inFirstChain) {
dfs(rootMonkey.secondMonkey!!, monkeyMap)
} else {
dfs(rootMonkey.firstMonkey!!, monkeyMap)
}
return if (inFirstChain) {
solveEquation("humn", rootMonkey.firstMonkey!!, endValue, monkeyMap)
} else {
solveEquation("humn", rootMonkey.secondMonkey!!, endValue, monkeyMap)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day21_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day21")
println(part1(input))
println(part2(input))
}
data class MathMonkey(
val name: String,
var simpleNumber: Long,
val operation: ((firstMonkey: Long, secondMonkey: Long) -> Long)?,
val firstMonkey: String?,
val secondMonkey: String?
)
| 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 4,658 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2020/Day09.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2020
import com.nibado.projects.advent.*
object Day09 : Day {
private val numbers = resourceLines(2020, 9).map { it.toLong() }
private const val preAmbleSize = 25
private val part1Number : Long by lazy { numbers.asSequence().drop(preAmbleSize).mapIndexedNotNull { index, i ->
if(pairs(numbers.subList(index, index + preAmbleSize)).map { (a, b) -> a + b }.toSet().contains(i)) {
null
} else i
}.first() }
override fun part1() = part1Number
override fun part2() : Long {
val ranges = mutableListOf<Pair<Int, Int>>()
for(i in numbers.indices) {
var sum = 0L
for(j in i .. numbers.indices.last) {
sum += numbers[j]
if(sum == part1Number) {
ranges += i to j
break
}
}
}
return ranges.maxByOrNull { (a,b) -> b - a }!!.let { (a, b) -> numbers.subList(a, b).minOrNull()!! + numbers.subList(a,b).maxOrNull()!! }
}
private fun pairs(list: List<Long>): List<Pair<Long, Long>> = list.indices
.flatMap { a -> list.indices.map { b -> a to b } }
.filterNot { (a, b) -> a == b }
.map { (a, b) -> list[a] to list[b] }
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,298 | adventofcode | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions5.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
fun test5() {
printlnResult(arrayOf("abcw", "foo", "bar", "fxyz", "abcdef"))
}
/**
* Questions 5: We have a String array, find the maximum product
* of the two strings that don't have any same alphabet, the all
* stings are composed by lowercase alphabets
*/
private fun Array<String>.findMaxProduct(): Int {
val alphabets = IntArray(size)
forEachIndexed { i, str ->
str.forEach {
alphabets[i] = 1 shl (it.code - 'a'.code) or alphabets[i]
}
}
var result = 0
for (i in 0 ..< lastIndex)
for (j in i + 1..lastIndex)
if (alphabets[i] and alphabets[j] == 0) {
val product = this[i].length * this[j].length
if (product > result)
result = product
}
return result
}
private fun printlnResult(array: Array<String>) {
println("The string array is: ${array.toList()}")
println("The maximum product of two strings that don't have same alphabets is: (${array.findMaxProduct()})")
}
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,064 | Algorithm | Apache License 2.0 |
src/Day21.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | class Monkeys(val input: List<String>) {
val monkeys = mutableMapOf<String, Monkey>()
var ownId: String = ""
init {
input.forEach { line ->
val (id, info) = line.split(": ")
val monkey = when {
" " in info -> {
val (m1, op, m2) = info.split(" ")
CompoundMonkey(id, m1, op, m2)
}
else -> SimpleMonkey(id, info.toLong())
}
monkeys[id] = monkey
}
}
abstract class Monkey {
abstract val id: String
abstract fun yell(): Long
abstract fun match(targetValue: Long?)
abstract fun dependsOnOwn(): Boolean
}
inner class SimpleMonkey(override val id: String, val initialValue: Long) : Monkey() {
var matchedValue: Long = -1
override fun yell() = initialValue
override fun dependsOnOwn() = id == ownId
override fun match(targetValue: Long?) {
if (id == ownId) {
matchedValue = targetValue!!
} else {
throw IllegalStateException("Not own monkey")
}
}
}
inner class CompoundMonkey(override val id: String, val m1: String, val op: String, val m2: String) : Monkey() {
private val monkey1: Monkey by lazy { monkeys[m1]!! }
private val monkey2: Monkey by lazy { monkeys[m2]!! }
val opFunction: (Long, Long) -> Long = when (op) {
"+" -> Long::plus
"-" -> Long::minus
"*" -> Long::times
"/" -> Long::div
else -> throw IllegalStateException("Unsupported operation $op")
}
override fun yell() = opFunction(monkey1.yell(), monkey2.yell())
override fun dependsOnOwn() = monkey1.dependsOnOwn() || monkey2.dependsOnOwn()
override fun match(targetValue: Long?) {
val depends1 = monkey1.dependsOnOwn()
val depends2 = monkey2.dependsOnOwn()
if (depends2) {
val value1 = monkey1.yell()
if (targetValue == null) {
monkey2.match(value1)
} else {
val value2 = when(op) {
"+" -> targetValue - value1
"-" -> value1 - targetValue
"*" -> targetValue / value1
"/" -> value1 / targetValue
else -> throw IllegalStateException("Unsupported operation $op")
}
monkey2.match(value2)
}
} else if (depends1) {
val value2 = monkey2.yell()
if (targetValue == null) {
monkey1.match(value2)
} else {
val value1 = when(op) {
"+" -> targetValue - value2
"-" -> targetValue + value2
"*" -> targetValue / value2
"/" -> targetValue * value2
else -> throw IllegalStateException("Unsupported operation $op")
}
monkey1.match(value1)
}
}
}
}
fun yellRoot() = monkeys["root"]!!.yell()
fun matchRootWithOwn(): Long {
monkeys["root"]!!.match(null)
return (monkeys[ownId]!! as SimpleMonkey).matchedValue
}
}
fun main() {
fun part1(input: List<String>) = Monkeys(input).yellRoot()
fun part2(input: List<String>) = Monkeys(input).apply { ownId = "humn" }.matchRootWithOwn()
val testInput = readInputLines("Day21_test")
check(part1(testInput), 152L)
check(part2(testInput), 301L)
val input = readInputLines("Day21")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 3,822 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/com/leetcode/P311.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package com.leetcode
import java.util.*
// https://github.com/antop-dev/algorithm/issues/311
class P311 {
private val dy = intArrayOf(-1, +0, +1, +0)
private val dx = intArrayOf(+0, +1, +0, -1)
fun shortestPath(grid: Array<IntArray>, k: Int): Int {
val m = grid.size
val n = grid[0].size
val memo = Array(m) { Array(n) { intArrayOf(m * n, m * n) } }
// [y좌표, x좌표, 장애물제거수]
val queue = LinkedList<IntArray>()
queue += intArrayOf(0, 0, 0)
var move = 0 // 이동 수
loop@ while (queue.isNotEmpty()) {
val size = queue.size
repeat(size) {
val (y, x, eliminate) = queue.poll()
// 목적지 도착
if (y == m - 1 && x == n - 1) { // 도착
return move
}
// 네방향 체크
dy.zip(dx) { a, b ->
val ny = y + a
val nx = x + b
if (ny in 0 until m && nx in 0 until n) {
val next = intArrayOf(ny, nx, eliminate)
if (grid[ny][nx] == 1) { // 벽
if (eliminate < k) { // 장애물 제거 가능
next[2]++
} else { // 장애물 제거 불가능
return@zip
}
}
memo[ny][nx][0] = move
memo[ny][nx][1] = next[2]
queue += next
}
}
}
move++
}
return -1
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,712 | algorithm | MIT License |
src/Day03.kt | ChenJiaJian96 | 576,533,624 | false | {"Kotlin": 11529} | fun main() {
fun findSameChar(first: String, second: String): Set<Char> {
return first.toCharArray().toSet() intersect second.toCharArray().toSet()
}
fun findSameChar(first: String, second: String, third: String): Set<Char> {
return first.toCharArray().toSet() intersect second.toCharArray().toSet() intersect third.toCharArray().toSet()
}
fun part1(input: List<String>): Int {
return input.map {
it.substring(0, it.length / 2) to it.substring(it.length / 2)
}.flatMap {
findSameChar(it.first, it.second)
}.sumOf {
it.toVal()
}
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3) {
val (first, second, third) = it
findSameChar(first, second, third)
}.sumOf { chars ->
chars.sumOf { it.toVal() }
}
}
val testInput = readInput("03", true)
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("03")
check(part1(input) == 7597)
check(part2(input) == 2607)
}
fun Char.toVal() =
if (this.isLowerCase()) {
this - 'a' + 1
} else {
this - 'A' + 27
} | 0 | Kotlin | 0 | 0 | b1a88f437aee756548ac5ba422e2adf2a43dce9f | 1,220 | Advent-Code-2022 | Apache License 2.0 |
src/main/kotlin/com/ab/advent/day04/Puzzle.kt | battagliandrea | 574,137,910 | false | {"Kotlin": 27923} | package com.ab.advent.day04
import com.ab.advent.utils.readLines
/*
PART 01
Space needs to be cleared before the last supplies can be unloaded from the ships,
and so several Elves have been assigned the job of cleaning up sections of the camp.
Every section has a unique ID number, and each Elf is assigned a range of section IDs.
However, as some of the Elves compare their section assignments with each other,
they've noticed that many of the assignments overlap. To try to quickly find overlaps and reduce duplicated effort,
the Elves pair up and make a big list of the section assignments for each pair (your puzzle input).
For example, consider the following list of section assignment pairs:
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
For the first few pairs, this list means:
Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4),
while the second Elf was assigned sections 6-8 (sections 6, 7, 8).
The Elves in the second pair were each assigned two sections.
The Elves in the third pair were each assigned three sections:
one got sections 5, 6, and 7, while the other also got 7, plus 8 and 9.
This example list uses single-digit section IDs to make it easier to draw;
your actual list might contain larger numbers. Visually, these pairs of section assignments look like this:
.234..... 2-4
.....678. 6-8
.23...... 2-3
...45.... 4-5
....567.. 5-7
......789 7-9
.2345678. 2-8
..34567.. 3-7
.....6... 6-6
...456... 4-6
.23456... 2-6
...45678. 4-8
Some of the pairs have noticed that one of their assignments fully contains the other.
For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6.
In pairs where one assignment fully contains the other, one Elf in the pair would
be exclusively cleaning sections their partner will already be cleaning,
so these seem like the most in need of reconsideration. In this example, there are 2 such pairs.
In how many assignment pairs does one range fully contain the other?
It seems like there is still quite a bit of duplicate work planned.
Instead, the Elves would like to know the number of pairs that overlap at all.
In the above example, the first two pairs (2-4,6-8 and 2-3,4-5) don't overlap,
while the remaining four pairs (5-7,7-9, 2-8,3-7, 6-6,4-6, and 2-6,4-8) do overlap:
5-7,7-9 overlaps in a single section, 7.
2-8,3-7 overlaps all of the sections 3 through 7.
6-6,4-6 overlaps in a single section, 6.
2-6,4-8 overlaps in sections 4, 5, and 6.
So, in this example, the number of overlapping assignment pairs is 4.
In how many assignment pairs do the ranges overlap?
*/
fun main() {
println("Day 4: Camp Cleanup")
println("In how many assignment pairs does one range fully contain the other?")
println(answer1("puzzle_04_input.txt".readLines()))
println("In how many assignment pairs do the ranges overlap?")
println(answer2("puzzle_04_input.txt".readLines()))
}
fun answer1(input: List<String>) = input.map(AssignmentSheet::parse).filter { it.hasOverlap() }.size
fun answer2(input: List<String>) = input.map(AssignmentSheet::parse).filter { it.anyOverlap() }.size
| 0 | Kotlin | 0 | 0 | cb66735eea19a5f37dcd4a31ae64f5b450975005 | 3,144 | Advent-of-Kotlin | Apache License 2.0 |
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day18.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwenty
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.readDayInput
class Day18 : Day<Long> {
private sealed class Expression {
data class Addition(val a: Expression, val b: Expression) : Expression() {
override fun toString() = "($a + $b)"
}
data class Product(val a: Expression, val b: Expression) : Expression() {
override fun toString() = "($a * $b)"
}
data class Parentheses(val a: Expression) : Expression() {
override fun toString() = "($a)"
}
data class Constant(val n: Long) : Expression() {
override fun toString() = n.toString()
}
}
private val input: Sequence<String> = readDayInput().lineSequence()
private fun parse(rest: List<Char>, previousExpr: Expression? = null): Expression {
if (rest.isEmpty()) return previousExpr!!
val head = rest.first()
val tail = rest.drop(1)
return when (head) {
in '0'..'9' -> parse(tail, Expression.Constant(head.toString().toLong()))
'+' -> Expression.Addition(parse(tail), previousExpr!!)
'*' -> Expression.Product(parse(tail), previousExpr!!)
')' -> {
val (contentInside, contentOutside) = parseParentheses(tail)
parse(contentOutside, Expression.Parentheses(parse(contentInside)))
}
else -> throw IllegalStateException()
}
}
private fun parseParentheses(content: List<Char>): Pair<List<Char>, List<Char>> {
var openParens = 0
content.forEachIndexed { index, c ->
when (c) {
')' -> openParens++
'(' -> when (openParens) {
0 -> return content.subList(0, index) to content.subList(index + 1, content.size)
else -> openParens--
}
}
}
throw IllegalArgumentException("no matching parens")
}
private fun String.parse(): Expression =
parse(replace(" ", "").toCharArray().toList().reversed())
private fun Expression.solve(): Long = when (this) {
is Expression.Constant -> n
is Expression.Addition -> a.solve() + b.solve()
is Expression.Product -> a.solve() * b.solve()
is Expression.Parentheses -> a.solve()
}
private fun prioritizeAdditionOnce(expr: Expression): Expression = when (expr) {
is Expression.Addition -> when {
expr.a is Expression.Product -> Expression.Product(
a = prioritizeAdditionOnce(expr.a.a),
b = prioritizeAdditionOnce(Expression.Addition(expr.a.b, expr.b))
)
expr.b is Expression.Product -> Expression.Product(
a = prioritizeAdditionOnce(Expression.Addition(expr.a, expr.b.a)),
b = prioritizeAdditionOnce(expr.b.b)
)
else -> expr.copy(
a = prioritizeAdditionOnce(expr.a),
b = prioritizeAdditionOnce(expr.b),
)
}
is Expression.Product -> expr.copy(
a = prioritizeAdditionOnce(expr.a),
b = prioritizeAdditionOnce(expr.b)
)
is Expression.Parentheses -> expr.copy(
a = prioritizeAdditionOnce(expr.a)
)
is Expression.Constant -> expr
}
private fun Expression.prioritizeAddition(): Expression {
var lastIter: Expression = this
while (true) {
val next = prioritizeAdditionOnce(lastIter)
if (next == lastIter) return next
lastIter = next
}
}
override fun step1(): Long {
return input.sumOf { expression ->
expression.parse().solve()
}
}
override fun step2(): Long {
return input.sumOf { expression ->
expression.parse()
.prioritizeAddition()
.solve()
}
}
override val expectedStep1: Long = 209335026987
override val expectedStep2: Long = 33331817392479
} | 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 4,108 | adventofcode | Apache License 2.0 |
src/commonMain/kotlin/io/github/kkarnauk/parsek/token/tokenizer/Tokenizer.kt | kkarnauk | 440,554,625 | false | {"Kotlin": 111337} | package io.github.kkarnauk.parsek.token.tokenizer
import io.github.kkarnauk.parsek.exception.TokenizeException
import io.github.kkarnauk.parsek.info.Location
import io.github.kkarnauk.parsek.token.Token
import io.github.kkarnauk.parsek.token.TokenProducer
import io.github.kkarnauk.parsek.token.type.TokenType
/**
* Required to transform a text into [TokenProducer].
*/
public interface Tokenizer {
/**
* Transforms [input] into [TokenProducer].
*/
public fun tokenize(input: CharSequence): TokenProducer
}
/**
* * On each step looks for the token from [tokenTypes] with the best match (see [findBestMatch]).
* * Doesn't return tokens with [TokenType.ignored] `= true`.
*/
public abstract class BestMatchTokenizer(protected val tokenTypes: List<TokenType>) : Tokenizer {
init {
require(tokenTypes.isNotEmpty()) { "Tokens types must be non-empty." }
}
override fun tokenize(input: CharSequence): TokenProducer = object : TokenProducer {
val state = State()
override fun nextToken(): Token? = nextNotIgnoredToken(input, state)
}
/**
* @return the best matched token from [tokenTypes] and the length of the matched segment.
* For example, 'the best match' can be the longest or the first match.
* Matching starts from [offset] in [input].
*
* If nothing is matched, then `null` should be returned.
*/
protected abstract fun findBestMatch(input: CharSequence, offset: Int): Pair<TokenType, Int>?
private fun nextToken(input: CharSequence, state: State): Token? {
while (true) {
if (state.offset >= input.length) {
return null
}
val bestMatch = findBestMatch(input, state.offset)
if (bestMatch == null) {
throw TokenizeException(
"Cannot tokenize the whole input. Unknown token: row=${state.row}, column=${state.column}."
)
}
val (type, length) = bestMatch
val (offset, row, column) = state
repeat(length) {
state.advance(input[offset + it])
}
if (!type.ignored) {
return Token(type, input, length, Location(offset, row, column))
}
}
}
private fun nextNotIgnoredToken(input: CharSequence, state: State): Token? {
while (true) {
val next = nextToken(input, state)
if (next == null) {
// TODO make clear errors
require(input.length == state.offset) {
"Cannot tokenize the whole input. Unknown token: row=${state.row}, column=${state.column}"
}
return null
} else if (!next.type.ignored) {
return next
}
}
}
private data class State(
var offset: Int = 0,
var row: Int = 1,
var column: Int = 1,
) {
fun advance(symbol: Char) {
if (symbol == '\n') {
row++
column = 0
}
column++
offset++
}
}
}
| 0 | Kotlin | 0 | 17 | 7479f94b28d4fdb611f4fabf83acece597a0203c | 3,155 | parsek | Apache License 2.0 |
src/day17/Day17.kt | davidcurrie | 579,636,994 | false | {"Kotlin": 52697} | package day17
import java.io.File
fun main() {
val jetPattern = File("src/day17/input.txt").readLines().first()
val rockShapes = listOf(
listOf(Pair(0,0), Pair(1,0), Pair(2,0), Pair(3,0)),
listOf(Pair(0,1), Pair(1,0), Pair(1,1), Pair(1,2), Pair(2,1)),
listOf(Pair(0,0), Pair(1,0), Pair(2,0), Pair(2,1), Pair(2,2)),
listOf(Pair(0,0), Pair(0,1), Pair(0,2), Pair(0,3)),
listOf(Pair(0,0), Pair(0,1), Pair(1,0), Pair(1,1))
)
var jetPatternIndex = 0
val stoppedRocks = mutableSetOf<Pair<Long, Long>>()
val heights = mutableListOf<Long>()
val cycleHeights = mutableListOf<Long>()
val cycleRocks = mutableListOf<Long>()
for (rock in 0 .. 1_000_000_000_000) {
val rockShapeIndex = (rock % rockShapes.size).toInt()
val rockShape = rockShapes[rockShapeIndex]
var coord = Pair(2L, 3 + (stoppedRocks.maxOfOrNull { it.second + 1 } ?: 0))
while (true) {
val jet = jetPattern[jetPatternIndex]
jetPatternIndex = (jetPatternIndex + 1) % jetPattern.length
val acrossCoord = if (jet == '>') {
Pair(coord.first + 1L, coord.second)
} else {
Pair(coord.first - 1L, coord.second)
}
if (allowed(rockCoords(acrossCoord, rockShape), stoppedRocks)) {
coord = acrossCoord
}
val downCoord = Pair(coord.first, coord.second - 1)
if (allowed(rockCoords(downCoord, rockShape), stoppedRocks)) {
coord = downCoord
} else {
stoppedRocks.addAll(rockCoords(coord, rockShape))
break
}
}
val height = stoppedRocks.maxOf { it.second } + 1
heights.add(height)
if (rock == 2022L - 1) println(height)
if (jetPatternIndex == 0) {
cycleHeights.add(height)
cycleRocks.add(rock)
}
if (cycleHeights.size > 3 && (cycleHeights[cycleHeights.size - 1] - cycleHeights[cycleHeights.size - 2]) ==
(cycleHeights[cycleHeights.size - 2] - cycleHeights[cycleHeights.size - 3])) break
}
val cycleHeightDiff = cycleHeights[cycleHeights.size - 1] - cycleHeights[cycleHeights.size - 2]
val cycleRockDiff = cycleRocks[cycleRocks.size - 1] - cycleRocks[cycleRocks.size - 2]
val cycleStarts = cycleRocks[0] + 1
val remainder = (1_000_000_000_000 - cycleStarts) % cycleRockDiff
val remainderHeight = heights[(cycleStarts + remainder - 1).toInt()]
println(remainderHeight + (((1_000_000_000_000 - cycleStarts) / cycleRockDiff) * cycleHeightDiff))
}
fun allowed(rockCoords: List<Pair<Long, Long>>, stoppedRocks: Set<Pair<Long, Long>>): Boolean {
rockCoords.forEach {
if (it.second < 0) return false
if (it.first < 0) return false
if (it.first > 6) return false
if (it in stoppedRocks) return false
}
return true
}
fun rockCoords(coord: Pair<Long, Long>, rockShape: List<Pair<Int, Int>>): List<Pair<Long, Long>> =
rockShape.map { Pair(coord.first + it.first, coord.second + it.second) } | 0 | Kotlin | 0 | 0 | 0e0cae3b9a97c6019c219563621b43b0eb0fc9db | 3,129 | advent-of-code-2022 | MIT License |
src/Day05.kt | RickShaa | 572,623,247 | false | {"Kotlin": 34294} | import java.util.*
import kotlin.collections.ArrayDeque
import kotlin.math.sign
fun main() {
val fileName = "day05.txt"
val testFileName = "day05_test.txt"
val input = FileUtil.getText(fileName);
val cratesAndInstructions = input.split("\n\n")
fun String.patchLastValue(): List<Char> {
var crates = this
if(this.length == 8){
crates+="#"
}
return crates.toList()
}
val lines = cratesAndInstructions[0].split("\n")
.map {
it
.replace(" ", "#")
.replace(" ", "")
.replace("[", "")
.replace("]", "")
}.map { it -> it.patchLastValue()}.take(8)
lines.forEach { println(it) }
fun createStacks(lines:List<List<Char>>):MutableMap<Int,ArrayDeque<Char>> {
var filledStack:MutableMap<Int,ArrayDeque<Char>> = mutableMapOf()
lines.forEach { line -> line.forEachIndexed { index, c ->
val idx = index+1;
if(c.toString() != "#"){
if(filledStack.contains(idx)){
filledStack[idx]?.addFirst(c)
}else{
filledStack[idx] = ArrayDeque(listOf(c))
}
}
}}
return filledStack
}
fun createInstructions(text:List<String>, regex: Regex): List<Instruction> {
return text
.map{ instruction -> regex.findAll(instruction).map { it.groupValues[0] }.joinToString()}
.map { it.split(",").map{ it.trim().toInt()} }
.map { item -> Instruction(item[0], item[1], item[2]) }
}
val instText = cratesAndInstructions[1].split("\n")
val instRegex = "\\d{1,2}".toRegex()
val instructions = createInstructions(instText,instRegex)
val stacks = createStacks(lines)
fun getTopCrates(sortedStacks: MutableMap<Int, ArrayDeque<Char>>): String {
var result = ""
for(i in 1..9){
result+= sortedStacks.get(i)?.removeLast()
}
return result
}
fun moveFromOriginToDestination(instruction: Instruction) {
val originStack = stacks[instruction.originStack]
val destinationStack = stacks[instruction.destinationStack]
val removedElement = originStack?.removeLast()
if (removedElement != null) {
destinationStack?.addLast(removedElement)
}
}
instructions.map { instruction -> instruction.moveOrdered(stacks) }
println(getTopCrates(stacks))
}
data class Instruction(val numberOfCrates:Int,val originStack:Int, val destinationStack:Int){
fun moveOrdered(stacks: MutableMap<Int, ArrayDeque<Char>>){
val originStack = stacks[originStack]
val destinationStack = stacks[destinationStack]
val tempList = mutableListOf<Char>()
for (i in 1..numberOfCrates){
tempList.add(originStack?.removeLast()!!)
}
tempList.reversed().forEach { it-> destinationStack?.addLast(it) }
}
}
| 0 | Kotlin | 0 | 1 | 76257b971649e656c1be6436f8cb70b80d5c992b | 2,989 | aoc | Apache License 2.0 |
src/Day02.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | class Day02 {
private val scoreMap1 = mapOf<String, Int>(
"A X" to 1 + 3,
"A Y" to 2 + 6,
"A Z" to 3 + 0,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 1 + 6,
"C Y" to 2 + 0,
"C Z" to 3 + 3,
)
private val scoreMap2 = mapOf(
"A X" to 3 + 0,
"A Y" to 1 + 3,
"A Z" to 2 + 6,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 2 + 0,
"C Y" to 3 + 3,
"C Z" to 1 + 6,
)
fun part1(input: List<String>): Int = input.fold(0) { acc, round ->
acc + scoreMap1[round]!!
}
fun part2(input: List<String>): Int = input.fold(0) { acc, round ->
acc + scoreMap2[round]!!
}
}
fun main() {
val day02 = Day02()
val input = readInput("input02_1")
println(day02.part1(input))
println(day02.part2(input))
}
| 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 912 | advent-of-code | Apache License 2.0 |
advent2022/src/main/kotlin/year2022/Day24.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2022
import AdventDay
import Point2D
import lcm
class Day24 : AdventDay(2022, 24) {
private data class Blizzard(val location: Point2D, val movement: Point2D) {
fun next(boundary: Point2D): Blizzard {
val nextLocation = location + movement
val correctedNextLocation = when {
nextLocation.x == 0L -> Point2D(boundary.x, location.y)
nextLocation.x > boundary.x -> Point2D(1, location.y)
nextLocation.y == 0L -> Point2D(location.x, boundary.y)
nextLocation.y > boundary.y -> Point2D(location.x, 1)
else -> nextLocation
}
return copy(location = correctedNextLocation)
}
}
private data class MapState(val boundary: Point2D, val blizzards: Set<Blizzard>) {
private val unsafeSpots by lazy {
blizzards.map { it.location }.toSet()
}
fun isSafe(place: Point2D): Boolean =
place !in unsafeSpots
fun inBounds(place: Point2D): Boolean =
place.x > 0 && place.y > 0 && place.x <= boundary.x && place.y <= boundary.y
fun nextState(): MapState =
copy(blizzards = blizzards.map { it.next(boundary) }.toSet())
companion object {
fun of(input: List<String>): MapState =
MapState(
Point2D(input.first().lastIndex - 1L, input.lastIndex - 1L),
input.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
when (char) {
'>' -> Blizzard(Point2D(x, y), Point2D(1, 0))
'<' -> Blizzard(Point2D(x, y), Point2D(-1, 0))
'v' -> Blizzard(Point2D(x, y), Point2D(0, 1))
'^' -> Blizzard(Point2D(x, y), Point2D(0, -1))
else -> null
}
}
}.toSet()
)
}
}
private data class PathAttempt(val steps: Int, val location: Point2D) {
fun next(place: Point2D = location): PathAttempt =
PathAttempt(steps + 1, place)
}
private fun MapState.computeLookup(startsAtRound: Int = 0): (Int) -> MapState {
val cycleLength = lcm(boundary.x, boundary.y).toInt()
val lookupTable = (1 .. cycleLength)
.runningFold(startsAtRound % cycleLength to this) { (_, lastState), cur ->
(cur + startsAtRound) % cycleLength to lastState.nextState()
}.toMap()
return { lookupTable.getValue(it % cycleLength) }
}
private fun solve(
startPlace: Point2D,
stopPlace: Point2D,
startState: MapState,
stepsSoFar: Int = 0,
lookupMapState: (Int) -> MapState = startState.computeLookup(stepsSoFar),
): Pair<Int, MapState> {
val queue = mutableListOf(PathAttempt(stepsSoFar, startPlace))
val seen = mutableSetOf<PathAttempt>()
while (queue.isNotEmpty()) {
val current = queue.removeFirst()
if (current !in seen) {
seen += current
val nextMapState = lookupMapState(current.steps + 1)
if (nextMapState.isSafe(current.location)) {
queue += current.next()
}
val neighbors = current.location.cardinalNeighbors
// Found the goal?
if (stopPlace in neighbors) return Pair(current.steps + 1, nextMapState)
queue += neighbors
.filter {
it == startPlace || (nextMapState.inBounds(it) && nextMapState.isSafe(it))
}
.map { current.next(it) }
}
}
error("no path found")
}
override fun part1(input: List<String>): Int {
val initialMapState: MapState = MapState.of(input)
val start = Point2D(input.first().indexOfFirst { it == '.' }, 0)
val goal = Point2D(input.last().indexOfFirst { it == '.' }, input.lastIndex)
return solve(start, goal, initialMapState).first
}
override fun part2(input: List<String>): Int {
val initialMapState: MapState = MapState.of(input)
val start = Point2D(input.first().indexOfFirst { it == '.' }, 0)
val goal = Point2D(input.last().indexOfFirst { it == '.' }, input.lastIndex)
val stuff = listOf(start, goal, start, goal).zipWithNext()
return stuff.fold(0 to initialMapState) { (rounds, state), (start, goal) ->
solve(start, goal, state, rounds)
}.first
}
}
fun main() = Day24().run() | 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 4,748 | advent-of-code | Apache License 2.0 |
aoc2022/day11.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2022
import utils.InputRetrieval
fun main() {
Day11.execute()
}
object Day11 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
input.forEach { it.reset() }
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<Monkey>): Long = monkeyBusiness(input, 20) { it / 3L }
private fun part2(input: List<Monkey>): Long {
val modulus = input.map { it.test.value }.reduce(Long::times)
return monkeyBusiness(input, 10000) { it % modulus }
}
private fun monkeyBusiness(input: List<Monkey>, rounds: Int, worryLevelManagement: (Long) -> Long): Long {
val inspectedItemsPerMonkey = MutableList(input.size) { 0L }
repeat(rounds) {
// Process Monkeys
input.forEachIndexed { index, monkey ->
monkey.items.forEach { item ->
val newItemValue = worryLevelManagement.invoke(monkey.operation.apply(item))
val targetMonkey = monkey.test.apply(newItemValue)
input[targetMonkey].items.add(newItemValue)
inspectedItemsPerMonkey[index]++
}
monkey.items.clear()
}
}
return inspectedItemsPerMonkey.sorted().takeLast(2).reduce { acc, value -> acc * value }
}
private fun readInput(): List<Monkey> = InputRetrieval.getFile(2022, 11).readText().split("\n\n").map {
Monkey.parse(it)
}
class Monkey(var items: MutableList<Long>, var operation: Operation, var test: Test, private val originalList: List<Long> = items.toList()) {
fun reset() {
items = originalList.toMutableList()
}
companion object {
fun parse(input: String): Monkey {
val lines = input.lines()
val startingItems = lines[1].trim().removePrefix("Starting items: ").split(", ").map { it.toLong() }.toMutableList()
val operation = Operation.parse(lines[2])
val test = Test.parse(lines[3], lines[4], lines[5])
return Monkey(startingItems, operation, test)
}
}
}
class Operation(private val operator: Char, private val value: String) {
fun apply(itemValue: Long): Long {
val parsedValue = when (value) {
"old" -> itemValue
else -> value.toLong()
}
return when (operator) {
'+' -> itemValue + parsedValue
'*' -> itemValue * parsedValue
else -> throw RuntimeException("Impossible!") // Based on the input, this is impossible
}
}
companion object {
fun parse(input: String): Operation {
val tmp = input.substringAfter("old ")
val (operator, value) = tmp.split(' ')
return Operation(operator.first(), value)
}
}
}
class Test(val value: Long, private val ifTrueMonkey: Int, private val ifFalseMonkey: Int) {
fun apply(itemValue: Long): Int = when (itemValue % value == 0L) {
true -> ifTrueMonkey
false -> ifFalseMonkey
}
companion object {
fun parse(operation: String, ifTrueAction: String, ifFalseAction: String): Test {
val value = operation.substringAfter("divisible by ").toLong()
val ifTrueMonkey = ifTrueAction.substringAfter("throw to monkey ").toInt()
val ifFalseMonkey = ifFalseAction.substringAfter("throw to monkey ").toInt()
return Test(value, ifTrueMonkey, ifFalseMonkey)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 3,720 | Advent-Of-Code | MIT License |
src/main/kotlin/day03.kt | mgellert | 572,594,052 | false | {"Kotlin": 19842} | object RucksackReorganization : Solution {
fun findSumOfMatching(rucksacks: List<Rucksack>, priorities: Map<Char, Int> = priorities()): Int = rucksacks.map {
val first = it.substring(0, it.length / 2).toSet()
val second = it.substring(it.length / 2).toSet()
first.intersect(second)
}
.flatten()
.sumOf { priorities[it] ?: 0 }
fun findSumOfBadges(rucksacks: List<Rucksack>, priorities: Map<Char, Int> = priorities()): Int =
rucksacks.chunked(3).map {
val (a, b, c) = it.map { rucksack -> rucksack.toSet() }
val asd = a.intersect(b).intersect(c)
asd
}
.flatten()
.sumOf { priorities[it] ?: 0 }
private fun priorities(): Map<Char, Int> = mutableMapOf<Char, Int>().also {
('a'..'z').mapIndexed { index, char -> it[char] = index + 1 }
('A'..'Z').mapIndexed { index, char -> it[char] = index + 27 }
}.toMap()
fun readRucksackContents() = readInput("day03").readLines()
}
typealias Rucksack = String | 0 | Kotlin | 0 | 0 | 4224c762ad4961b28e47cd3db35e5bc73587a118 | 1,052 | advent-of-code-2022-kotlin | The Unlicense |
src/main/kotlin/g2801_2900/s2867_count_valid_paths_in_a_tree/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2801_2900.s2867_count_valid_paths_in_a_tree
// #Hard #Dynamic_Programming #Math #Depth_First_Search #Tree #Number_Theory
// #2023_12_21_Time_793_ms_(100.00%)_Space_111.6_MB_(100.00%)
class Solution {
private lateinit var isPrime: BooleanArray
private lateinit var treeEdges: Array<MutableList<Int>?>
private var r: Long = 0
private fun preparePrime(n: Int): BooleanArray {
// Sieve of Eratosthenes < 3
val isPrimeLocal = BooleanArray(n + 1)
for (i in 2 until n + 1) {
isPrimeLocal[i] = true
}
for (i in 2..n / 2) {
var j = 2 * i
while (j < n + 1) {
isPrimeLocal[j] = false
j += i
}
}
return isPrimeLocal
}
private fun prepareTree(n: Int, edges: Array<IntArray>): Array<MutableList<Int>?> {
val treeEdgesLocal: Array<MutableList<Int>?> = arrayOfNulls(n + 1)
for (edge in edges) {
if (treeEdgesLocal[edge[0]] == null) {
treeEdgesLocal[edge[0]] = ArrayList()
}
treeEdgesLocal[edge[0]]!!.add(edge[1])
if (treeEdgesLocal[edge[1]] == null) {
treeEdgesLocal[edge[1]] = ArrayList()
}
treeEdgesLocal[edge[1]]!!.add(edge[0])
}
return treeEdgesLocal
}
private fun countPathDfs(node: Int, parent: Int): LongArray {
val v = longArrayOf((if (isPrime[node]) 0 else 1).toLong(), (if (isPrime[node]) 1 else 0).toLong())
val edges = treeEdges[node] ?: return v
for (neigh in edges) {
if (neigh == parent) {
continue
}
val ce = countPathDfs(neigh, node)
r += v[0] * ce[1] + v[1] * ce[0]
if (isPrime[node]) {
v[1] += ce[0]
} else {
v[0] += ce[0]
v[1] += ce[1]
}
}
return v
}
fun countPaths(n: Int, edges: Array<IntArray>): Long {
isPrime = preparePrime(n)
treeEdges = prepareTree(n, edges)
r = 0
countPathDfs(1, 0)
return r
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,167 | LeetCode-in-Kotlin | MIT License |
leetcode-75-kotlin/src/main/kotlin/ReverseWordsInAString.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* Given an input string s, reverse the order of the words.
*
* A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
*
* Return a string of the words in reverse order concatenated by a single space.
*
* Note that s may contain leading or trailing spaces or multiple spaces between two words.
* The returned string should only have a single space separating the words. Do not include any extra spaces.
*
*
*
* Example 1:
*
* Input: s = "the sky is blue"
* Output: "blue is sky the"
* Example 2:
*
* Input: s = " hello world "
* Output: "world hello"
* Explanation: Your reversed string should not contain leading or trailing spaces.
* Example 3:
*
* Input: s = "a good example"
* Output: "example good a"
* Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
*
*
* Constraints:
*
* 1 <= s.length <= 10^4
* s contains English letters (upper-case and lower-case), digits, and spaces ' '.
* There is at least one word in s.
*
*
* Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?
* @see <a href="https://leetcode.com/problems/reverse-words-in-a-string/">LeetCode</a>
*/
fun reverseWords(s: String): String {
val reversedChars = cleanAndReverseString(s)
reverseAllWords(reversedChars)
return reversedChars.joinToString("")
}
private fun cleanAndReverseString(s: String): MutableList<Char> {
val reversedChars = mutableListOf<Char>()
for (index in s.lastIndex downTo 0) {
if (!s[index].isWhitespace()) {
reversedChars.add(s[index])
} else if (reversedChars.lastOrNull()?.isWhitespace() == false) {
reversedChars.add(s[index])
}
}
if (reversedChars.last().isWhitespace()) reversedChars.removeLast()
return reversedChars
}
private fun reverseAllWords(charList: MutableList<Char>) {
var wordStart = 0
var wordEnd = 0
while (wordEnd < charList.size) {
while (wordEnd < charList.size && !charList[wordEnd].isWhitespace()) wordEnd++
reverseWord(wordStart, wordEnd - 1, charList)
wordEnd++
wordStart = wordEnd
}
}
private fun reverseWord(start: Int, end: Int, chars: MutableList<Char>) {
var left = start
var right = end
while (left < right) {
val temp = chars[left]
chars[left] = chars[right]
chars[right] = temp
left++
right--
}
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 2,530 | leetcode-75 | Apache License 2.0 |
src/Day01.kt | vi-quang | 573,647,667 | false | {"Kotlin": 49703} | import java.util.PriorityQueue
fun main() {
data class Elf(val calorieList: MutableList<Int> = mutableListOf()) {
fun totalCalories() : Int {
return calorieList.sumOf { it }
}
}
fun createElfList(input : List<String>) : MutableList<Elf> {
val elves = mutableListOf<Elf>()
var currentElf = Elf()
for (line in input) {
if (line.isEmpty()) {
elves.add(currentElf)
currentElf = Elf()
} else {
currentElf.calorieList.add(line.toInt())
}
}
return elves
}
fun findElvesWithTheMostCalories(elves: List<Elf>, numberOfElves:Int) : PriorityQueue<Elf> {
val priorityQueue = PriorityQueue<Elf> {
e1, e2 -> e1.totalCalories() - e2.totalCalories()
}
for (elf in elves) {
priorityQueue.add(elf)
if (priorityQueue.size > numberOfElves) {
priorityQueue.poll()
}
}
return priorityQueue
}
fun part1(input: List<String>): Int {
val elves = createElfList(input)
val priorityQueue = findElvesWithTheMostCalories(elves, 1)
return priorityQueue.sumOf { it.totalCalories() }
}
fun part2(input: List<String>): Int {
val elves = createElfList(input)
val priorityQueue = findElvesWithTheMostCalories(elves, 3)
return priorityQueue.sumOf { it.totalCalories() }
}
val input = readInput(1)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | ae153c99b58ba3749f16b3fe53f06a4b557105d3 | 1,574 | aoc-2022 | Apache License 2.0 |
src/Day14.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | import java.lang.Integer.max
import java.lang.Integer.min
fun main() {
fun part1(input: List<String>): Int {
val a: Array<CharArray> = Array(1000) { CharArray(1000) { '.' } }
input.asSequence().filter { it.isNotEmpty() }
.map { it.split(" -> ") }
.map {
it.map { p ->
val pp = p.split(",")
Pair(pp[0].toInt(), pp[1].toInt())
}
}
.forEach {
var cur = it[0]
a[cur.second][cur.first] = '#'
for (i in 1 until it.size) {
for (ii in min(cur.second, it[i].second)..max(cur.second, it[i].second)) {
a[ii][cur.first] = '#'
}
for (jj in min(cur.first, it[i].first)..max(cur.first, it[i].first)) {
a[cur.second][jj] = '#'
}
cur = it[i]
}
}
a[0][500] = '+'
val deepest = a.indices.filter { a[it].contains('#') }.max()
var res = 0
// println(a.joinToString("\n", transform = {it.joinToString("")}))
while (true) {
var i = 0
var j = 500
while (i <= deepest) {
if (a[i + 1][j] == '.') {
i++
}
else if (a[i + 1][j - 1] == '.') {
i++
j--
}
else if (a[i + 1][j + 1] == '.') {
i++
j++
} else {
a[i][j] = 'o'
res++
break
}
}
if (i > deepest) {
// println(a.joinToString("\n", transform = {it.joinToString("")}))
return res
}
}
}
fun part2(input: List<String>): Int {
val a: Array<CharArray> = Array(1000) { CharArray(1000) { '.' } }
input.asSequence().filter { it.isNotEmpty() }
.map { it.split(" -> ") }
.map {
it.map { p ->
val pp = p.split(",")
Pair(pp[0].toInt(), pp[1].toInt())
}
}
.forEach {
var cur = it[0]
a[cur.second][cur.first] = '#'
for (i in 1 until it.size) {
for (ii in min(cur.second, it[i].second)..max(cur.second, it[i].second)) {
a[ii][cur.first] = '#'
}
for (jj in min(cur.first, it[i].first)..max(cur.first, it[i].first)) {
a[cur.second][jj] = '#'
}
cur = it[i]
}
}
a[0][500] = '+'
val deepest = a.indices.filter { a[it].contains('#') }.max()
for (j in 0 until a[deepest + 2].size) {
a[deepest + 2][j] = '#'
}
var res = 0
println(a.joinToString("\n", transform = {it.joinToString("")}))
while (true) {
var i = 0
var j = 500
if (a[i][j] == 'o') {
println(a.joinToString("\n", transform = {it.joinToString("")}))
return res
}
while (true) {
if (a[i + 1][j] == '.') {
i++
}
else if (a[i + 1][j - 1] == '.') {
i++
j--
}
else if (a[i + 1][j + 1] == '.') {
i++
j++
} else {
a[i][j] = 'o'
res++
break
}
}
}
}
part1(readInput("input")).println()
part2(readInput("input")).println()
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 3,902 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/TwoPointers.kt | betulnecanli | 568,477,911 | false | {"Kotlin": 167849} | /*
The two-pointer technique is often used for problems that involve searching for a pair of elements, sorting,
or finding a subarray with a specific property. Let's tackle three problems:
"Squaring a Sorted Array," "Dutch National Flag Problem," and "Minimum Window Sort in a Matrix."
I'll provide Kotlin implementations for each.
*/
//1. Squaring a Sorted Array
fun sortedSquares(nums: IntArray): IntArray {
val n = nums.size
val result = IntArray(n)
var left = 0
var right = n - 1
var index = n - 1
while (left <= right) {
val leftSquare = nums[left] * nums[left]
val rightSquare = nums[right] * nums[right]
if (leftSquare > rightSquare) {
result[index] = leftSquare
left++
} else {
result[index] = rightSquare
right--
}
index--
}
return result
}
fun main() {
val nums = intArrayOf(-4, -1, 0, 3, 10)
val result = sortedSquares(nums)
println("Squared Sorted Array: ${result.joinToString(", ")}")
}
//2. Dutch National Flag Problem
fun sortColors(nums: IntArray) {
var low = 0
var high = nums.size - 1
var i = 0
while (i <= high) {
when {
nums[i] == 0 -> {
swap(nums, i, low)
i++
low++
}
nums[i] == 2 -> {
swap(nums, i, high)
high--
}
else -> {
i++
}
}
}
}
fun swap(nums: IntArray, i: Int, j: Int) {
val temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
fun main() {
val colors = intArrayOf(2, 0, 2, 1, 1, 0)
sortColors(colors)
println("Sorted Colors: ${colors.joinToString(", ")}")
}
//3. Minimum Window Sort
fun minWindowSort(nums: IntArray): Int {
var left = 0
var right = nums.size - 1
// Find the left bound of the unsorted subarray
while (left < nums.size - 1 && nums[left] <= nums[left + 1]) {
left++
}
if (left == nums.size - 1) {
return 0 // The array is already sorted
}
// Find the right bound of the unsorted subarray
while (right > 0 && nums[right] >= nums[right - 1]) {
right--
}
// Find the minimum and maximum values in the unsorted subarray
var minVal = Int.MAX_VALUE
var maxVal = Int.MIN_VALUE
for (i in left..right) {
minVal = minOf(minVal, nums[i])
maxVal = maxOf(maxVal, nums[i])
}
// Expand the left bound to include elements smaller than minVal
while (left > 0 && nums[left - 1] > minVal) {
left--
}
// Expand the right bound to include elements greater than maxVal
while (right < nums.size - 1 && nums[right + 1] < maxVal) {
right++
}
return right - left + 1
}
fun main() {
val nums = intArrayOf(1, 3, 5, 2, 6, 4, 8)
val result = minWindowSort(nums)
println("Minimum Window to Sort: $result")
}
| 2 | Kotlin | 2 | 40 | 70a4a311f0c57928a32d7b4d795f98db3bdbeb02 | 2,965 | Kotlin-Data-Structures-Algorithms | Apache License 2.0 |
plugins/evaluation-plugin/core/src/com/intellij/cce/metric/SimilarityMetrics.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.cce.metric
import com.intellij.cce.core.Lookup
import com.intellij.cce.core.Session
import com.intellij.cce.metric.util.Bootstrap
import org.apache.commons.lang3.StringUtils
import org.apache.commons.text.similarity.LevenshteinDistance
import kotlin.math.max
import kotlin.math.min
abstract class SimilarityMetric(override val showByDefault: Boolean) : Metric {
private var totalMatched: Double = 0.0
private var totalExpected: Double = 0.0
private var sample: MutableList<Pair<Double, Double>> = mutableListOf()
override val valueType = MetricValueType.DOUBLE
override val value: Double
get() = totalMatched / totalExpected
override fun confidenceInterval(): Pair<Double, Double> = Bootstrap.computeInterval(sample) { values ->
values.sumOf { it.first } / values.sumOf { it.second }
}
override fun evaluate(sessions: List<Session>): Double {
var matched = 0.0
var expected = 0.0
for (session in sessions) {
for (lookup in session.lookups) {
val expectedText = session.expectedText.substring(lookup.offset)
val currentExpected = computeExpected(lookup, expectedText)
expected += currentExpected
val similarity = computeSimilarity(lookup, expectedText) ?: 0.0
matched += similarity
sample.add(Pair(similarity, currentExpected))
}
}
totalMatched += matched
totalExpected += expected
return matched / expected
}
abstract fun computeSimilarity(lookup: Lookup, expectedText: String): Double?
open fun computeExpected(lookup: Lookup, expectedText: String): Double = expectedText.length.toDouble()
}
class MatchedRatio(showByDefault: Boolean = false) : SimilarityMetric(showByDefault) {
override val name = "Matched Ratio"
override val description: String = "Length of selected proposal normalized by expected text (avg by invocations)"
override fun computeSimilarity(lookup: Lookup, expectedText: String): Double? {
if (lookup.selectedPosition == -1)
return null
val selected = lookup.suggestions[lookup.selectedPosition]
return selected.text.length.toDouble() - lookup.prefix.length
}
}
class MatchedRatioAt(showByDefault: Boolean = false, val n: Int) : SimilarityMetric(showByDefault) {
override val name = "Matched Ratio At $n"
override val description: String = "Length of the longest matching proposal among top-$n normalized by expected text (avg by invocations)"
override fun computeSimilarity(lookup: Lookup, expectedText: String): Double {
val numConsideredSuggestions = min(n, lookup.suggestions.size)
var maxMatchedLen = 0
for (i in 0 until numConsideredSuggestions) {
if (lookup.suggestions[i].isRelevant) {
val selected = lookup.suggestions[i]
maxMatchedLen = max(maxMatchedLen, selected.text.length - lookup.prefix.length)
}
}
return maxMatchedLen.toDouble()
}
}
class PrefixSimilarity(showByDefault: Boolean = false) : SimilarityMetric(showByDefault) {
override val name = "Prefix Similarity"
override val description: String = "The most matching prefix among proposals normalized by expected text (avg by invocations)"
override fun computeSimilarity(lookup: Lookup, expectedText: String): Double? =
lookup.suggestions.maxOfOrNull {
StringUtils.getCommonPrefix(it.text.drop(lookup.prefix.length), expectedText).length
}?.toDouble()
}
class EditSimilarity(showByDefault: Boolean = false) : SimilarityMetric(showByDefault) {
override val name = "Edit Similarity"
override val description: String = "The minimum edit similarity among proposals normalized by expected text (avg by invocations)"
override fun computeSimilarity(lookup: Lookup, expectedText: String): Double? {
return lookup.suggestions.maxOfOrNull {
expectedText.length - LevenshteinDistance.getDefaultInstance().apply(it.text.drop(lookup.prefix.length), expectedText)
}?.toDouble()?.coerceAtLeast(0.0)
}
}
| 251 | null | 5,079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 4,076 | intellij-community | Apache License 2.0 |
src/main/kotlin/solutions/CHK/CheckoutSolution.kt | DPNT-Sourcecode | 683,058,972 | false | null | package solutions.CHK
/**
* +------+-------+------------------------+
* | Item | Price | Special offers |
* +------+-------+------------------------+
* | A | 50 | 3A for 130, 5A for 200 |
* | B | 30 | 2B for 45 |
* | C | 20 | |
* | D | 15 | |
* | E | 40 | 2E get one B free |
* +------+-------+------------------------+
*/
object CheckoutSolution {
private val pricesPerSKU = mapOf(
'A' to 50,
'B' to 30,
'C' to 20,
'D' to 15,
'E' to 40
)
private val specialDiscounts = mapOf(
'A' to listOf(
SpecialDiscount(3, 130),
SpecialDiscount(5, 200)
),
'B' to listOf(
SpecialDiscount(2, 45)
)
)
private val freeItems = mapOf(
'E' to FreeItem(2, 'B', 1)
)
fun checkout(skus: String): Int {
val skusList = skus.toCharArray()
return calculatePrices(skusList)
}
private fun calculatePrices(skusList: CharArray): Int {
val skusCount = mutableMapOf<Char, Int>()
var totalPrice = 0
skusList.forEach { sku ->
if (pricesPerSKU[sku] == null) {
return -1
}
if (skusCount[sku] == null) {
skusCount[sku] = 1
} else {
skusCount[sku] = skusCount[sku]!! + 1
}
}
skusCount.forEach { (sku, amount) ->
val freeItem = freeItems[sku]
if (freeItem != null && amount >= freeItem.amountNecessary && skusCount[freeItem.freeItem] != null) {
val amountToRemove = amount / freeItem.amountNecessary
skusCount[freeItem.freeItem] = skusCount[freeItem.freeItem]!! - (freeItem.freeItemAmount * amountToRemove)
}
}
skusCount.forEach { (sku, amount) ->
val specialDiscounts = specialDiscounts[sku]
val specialDiscount = findSuitableSpecialDiscount(amount, specialDiscounts)
if (specialDiscount != null) {
totalPrice += specialDiscount.calculateTotal(
amount,
pricesPerSKU[sku]!!
)
} else {
totalPrice += pricesPerSKU[sku]!! * amount
}
}
return totalPrice
}
private fun findSuitableSpecialDiscount(amount: Int, specialDiscounts: List<SpecialDiscount>?): SpecialDiscount? {
return specialDiscounts?.lastOrNull{
it.numberOfItems <= amount
}
}
}
| 0 | Kotlin | 0 | 0 | 08a55cb40cb8bed10ab5a0397b70cedc80ad3d5f | 2,629 | CHK-fncv01 | Apache License 2.0 |
src/main/kotlin/com/github/davio/aoc/y2016/Day1.kt | Davio | 317,510,947 | false | {"Kotlin": 405939} | package com.github.davio.aoc.y2016
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.getInputAsList
import com.github.davio.aoc.y2016.Day1.Orientation.*
import kotlin.math.abs
fun main() {
Day1.getResultPart1()
}
object Day1 : Day() {
/*
* --- Day 1: No Time for a Taxicab ---
Santa's sleigh uses a very high-precision clock to guide its movements, and the clock's oscillator is regulated by stars.
* Unfortunately, the stars have been stolen... by the Easter Bunny.
* To save Christmas, Santa needs you to retrieve all fifty stars by December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar;
* the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You're airdropped near Easter Bunny Headquarters in a city somewhere. "Near", unfortunately,
* is as close as you can get - the instructions on the Easter Bunny Recruiting Document the Elves intercepted start here,
* and nobody had time to work them out further.
The Document indicates that you should start at the given coordinates (where you just landed) and face North.
* Then, follow the provided sequence: either turn left (L) or right (R) 90 degrees, then walk forward the given number of blocks,
* ending at a new intersection.
There's no time to follow such ridiculous instructions on foot, though, so you take a moment and work out the destination.
* Given that you can only walk on the street grid of the city, how far is the shortest path to the destination?
For example:
Following R2, L3 leaves you 2 blocks East and 3 blocks North, or 5 blocks away.
R2, R2, R2 leaves you 2 blocks due South of your starting position, which is 2 blocks away.
R5, L5, R5, R3 leaves you 12 blocks away.
How many blocks away is Easter Bunny HQ?
*
* --- Part Two ---
Then, you notice the instructions continue on the back of the Recruiting Document.
* Easter Bunny HQ is actually at the first location you visit twice.
For example, if your instructions are R8, R4, R4, R8, the first location you visit twice is 4 blocks away, due East.
How many blocks away is the first location you visit twice?
*/
private var orientation = NORTH
private var coordinates = Pair(0, 0)
fun getResultPart1() {
val directions = getInputAsList()[0].split(", ")
directions.forEach {
val direction = it[0]
val steps = it.substring(1).toInt()
coordinates = processMovement(direction, steps)
}
println(abs(coordinates.first) + abs(coordinates.second))
}
private fun processMovement(direction: Char, steps: Int): Pair<Int, Int> {
var orientationIndex: Int
when (direction) {
'R' -> {
orientationIndex = orientation.ordinal + 1
if (orientationIndex == 4) {
orientationIndex = 0
}
}
else -> {
orientationIndex = orientation.ordinal - 1
if (orientationIndex == -1) {
orientationIndex = 3
}
}
}
orientation = Orientation.values()[orientationIndex]
return when (orientation) {
NORTH -> Pair(coordinates.first, coordinates.second + steps)
EAST -> Pair(coordinates.first + steps, coordinates.second)
SOUTH -> Pair(coordinates.first, coordinates.second - steps)
WEST -> Pair(coordinates.first - steps, coordinates.second)
}
}
private enum class Orientation {
NORTH,
EAST,
SOUTH,
WEST
}
}
| 1 | Kotlin | 0 | 0 | 4fafd2b0a88f2f54aa478570301ed55f9649d8f3 | 3,676 | advent-of-code | MIT License |
src/main/kotlin/Day05.kt | dliszewski | 573,836,961 | false | {"Kotlin": 57757} | import kotlin.collections.HashMap
class Day05 {
fun part1(input: String): String {
return getTopCrates(input, CrateMoverModel.CrateMover9000)
}
fun part2(input: String): String {
return getTopCrates(input, CrateMoverModel.CrateMover9001)
}
private fun getTopCrates(input: String, modelType: CrateMoverModel): String {
val (cranes, instructions) = input.split("\n\n")
val cranesNumber = cranes.parseCranesNumber()
val boxes = cranes.lines().dropLast(1).flatMap { line -> line.mapToBoxes(cranesNumber) }
val craneOperator = CraneOperator(cranesNumber, modelType, boxes)
val craneInstructions = instructions.parseToCommands()
craneOperator.executeCommands(craneInstructions)
return craneOperator.getTopCrates()
}
private fun String.parseCranesNumber() = lines()
.last()
.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.count()
private fun String.parseToCommands() = lines().map {
val (p1, p2) = it.split(" from ")
val moveQuantity = p1.replace("move ", "").toInt()
val (from, to) = p2.split(" to ")
CraneCommand(moveQuantity, from.toInt(), to.toInt())
}
data class Box(val index: Int, val content: String)
data class CraneCommand(val quantity: Int, val from: Int, val to: Int)
enum class CrateMoverModel { CrateMover9000, CrateMover9001 }
private fun String.mapToBoxes(size: Int): List<Box> {
return (1..size)
.map { craneNumber -> Box(craneNumber, this.parseBoxFromCraneNumber(craneNumber)) }
.filter { it.content.isNotBlank() }
}
private fun String.parseBoxFromCraneNumber(n: Int): String {
val craneRow = n - 1
return substring(4 * craneRow + 1, 4 * craneRow + 2)
}
private class CraneOperator(numberOfCranes: Int, private val modelType: CrateMoverModel, boxes: List<Box>) {
private val boxStacks: HashMap<Int, ArrayDeque<String>> = HashMap()
init {
(1..numberOfCranes).forEach { boxStacks[it] = ArrayDeque() }
boxes.forEach { putBoxInCrane(it) }
}
private fun putBoxInCrane(box: Box) {
boxStacks[box.index]?.addFirst(box.content)
}
fun executeCommands(commands: List<CraneCommand>) {
commands.forEach { command ->
val toMove = (1..command.quantity).map { boxStacks[command.from]?.removeLast()!! }
when (modelType) {
CrateMoverModel.CrateMover9000 -> {
boxStacks[command.to]?.addAll(toMove)
}
CrateMoverModel.CrateMover9001 -> {
boxStacks[command.to]?.addAll(toMove.reversed())
}
}
}
}
fun getTopCrates(): String {
return boxStacks.values.joinToString(separator = "") { it.last() }
}
}
} | 0 | Kotlin | 0 | 0 | 76d5eea8ff0c96392f49f450660220c07a264671 | 3,004 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/wtf/log/xmas2021/day/day03/Day03.kt | damianw | 434,043,459 | false | {"Kotlin": 62890} | package wtf.log.xmas2021.day.day03
import wtf.log.xmas2021.Day
import wtf.log.xmas2021.util.math.toInt
import java.io.BufferedReader
object Day03 : Day<BitTable, Int, Int> {
override fun parseInput(reader: BufferedReader): BitTable = BitTable.parse(reader)
override fun part1(input: BitTable): Int {
val mostCommonBits = input.foldMostCommon()
val width = mostCommonBits.size
val gammaRate = mostCommonBits.toInt()
val epsilonRate = gammaRate.inv() and ((1 shl width) - 1)
return gammaRate * epsilonRate
}
override fun part2(input: BitTable): Int {
return computeRating(input, false) * computeRating(input, true)
}
private fun computeRating(input: BitTable, invert: Boolean): Int {
val candidateRows = input.rows.toCollection(mutableSetOf())
for (columnIndex in 0 until input.width) {
val subTable = BitTable(candidateRows.toList())
val column = subTable.columns[columnIndex]
val mostCommon = column.findMostCommon()
val target = mostCommon xor invert
val rowIterator = candidateRows.iterator()
while (rowIterator.hasNext()) {
val candidateRow = rowIterator.next()
if (candidateRow[columnIndex] != target) {
rowIterator.remove()
}
}
if (candidateRows.size == 1) {
break
}
}
return candidateRows.single().toInt()
}
}
data class BitTable(
val rows: List<List<Boolean>>,
) {
init {
require(rows.isNotEmpty())
}
val height: Int = rows.size
val width: Int = rows.first().size
val columns: List<List<Boolean>> = (0 until width).map { ColumnView(it) }
init {
require(rows.all { it.size == width })
}
override fun toString(): String = buildString {
for (row in rows) {
for (value in row) {
append(
when (value) {
true -> '1'
false -> '0'
}
)
}
append('\n')
}
}
private inner class ColumnView(private val columnIndex: Int) : AbstractList<Boolean>() {
override val size: Int
get() = height
override fun get(index: Int): Boolean = rows[index][columnIndex]
}
companion object {
fun parse(reader: BufferedReader): BitTable {
val rows = mutableListOf<List<Boolean>>()
for (line in reader.lineSequence()) {
val row = line.map { char ->
when (char) {
'0' -> false
'1' -> true
else -> error("Invalid bit character: $char")
}
}
rows += row
}
return BitTable(rows)
}
}
}
private fun BitTable.foldMostCommon(): List<Boolean> {
return columns.map { it.findMostCommon() }
}
private fun List<Boolean>.findMostCommon(): Boolean {
val count = count { it }
val half = size / 2
return size % 2 == 0 && count == half || count > half
}
| 0 | Kotlin | 0 | 0 | 1c4c12546ea3de0e7298c2771dc93e578f11a9c6 | 3,238 | AdventOfKotlin2021 | BSD Source Code Attribution |
src/main/kotlin/endredeak/aoc2023/Day14.kt | edeak | 725,919,562 | false | {"Kotlin": 26575} | package endredeak.aoc2023
fun main() {
solve("Parabolic Reflector Dish") {
val input = lines.map { it.toCharArray() }
fun List<CharArray>.copy() = this.map { it.toMutableList().toCharArray() }
fun List<CharArray>.tilt(dir: String): List<CharArray> {
val c = this.copy()
var prev = c.copy()
while (true) {
when (dir) {
"N" -> (c.lastIndex downTo 1).forEach { y ->
c.first().indices.forEach { x ->
if (c[y][x] == 'O') {
if (c[y - 1][x] == '.') {
c[y - 1][x] = 'O'
c[y][x] = '.'
}
}
}
}
"W" -> {
c.indices.forEach { y ->
(c.first().lastIndex downTo 1).forEach { x ->
if (c[y][x] == 'O') {
if (c[y][x - 1] == '.') {
c[y][x - 1] = 'O'
c[y][x] = '.'
}
}
}
}
}
"S" -> {
(0..<c.lastIndex).forEach { y ->
c.first().indices.forEach { x ->
if (c[y][x] == 'O') {
if (c[y + 1][x] == '.') {
c[y + 1][x] = 'O'
c[y][x] = '.'
}
}
}
}
}
"E" -> {
c.indices.forEach { y ->
(0..<c.first().lastIndex).forEach { x ->
if (c[y][x] == 'O') {
if (c[y][x + 1] == '.') {
c[y][x + 1] = 'O'
c[y][x] = '.'
}
}
}
}
}
}
if (indices.all { prev[it].contentEquals(c[it]) }) {
break
}
prev = c.copy()
}
return c.copy()
}
fun List<CharArray>.calc() = first().indices.sumOf { x ->
this.joinToString("") { "${it[x]}" }
.let { col ->
col.indices.fold(0L) { acc, i ->
if (col[i] == 'O') acc + lastIndex - i + 1 else acc
}
}
}
fun List<CharArray>.repeatedTilt(limit: Int): List<CharArray> {
val seen = mutableMapOf<List<String>, Int>()
var current = this
var i = 0
var length = 0
while (i < limit) {
val key = current.map { it.concatToString() }
if (key in seen) {
length = i - seen[key]!!
break
}
seen[key] = i
current = current.tilt("N").tilt("W").tilt("S").tilt("E")
i++
}
if (length > 0) {
val remainingCycles = (limit - i) % length
for (c in 0 until remainingCycles) {
current = current.tilt("N").tilt("W").tilt("S").tilt("E")
}
}
return current
}
part1(107142) {
input.tilt("N").calc()
}
part2(104815) {
input.repeatedTilt(1_000_000_000).calc()
}
}
}
| 0 | Kotlin | 0 | 0 | 92c684c42c8934e83ded7881da340222ff11e338 | 3,998 | AdventOfCode2023 | Do What The F*ck You Want To Public License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SumOfUnique.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
/**
* Sum of Unique Elements
* @see <a href="https://leetcode.com/problems/sum-of-unique-elements">Source</a>
*/
fun interface SumOfUnique {
operator fun invoke(nums: IntArray): Int
}
/**
* Brute Force
*/
class SumOfUniqueBruteForce : SumOfUnique {
override operator fun invoke(nums: IntArray): Int {
val unique = IntArray(LIMIT) { 0 }
var ans = 0
for (num in nums) {
val idx = num - 1
unique[idx]++
if (unique[idx] == 1) {
ans += num
} else if (unique[idx] == 2) {
ans -= num
}
}
return ans
}
companion object {
private const val LIMIT = 101
}
}
/**
* Hashmap, single loop
*/
class SumOfUniqueHashMap : SumOfUnique {
override operator fun invoke(nums: IntArray): Int {
var sum = 0
val map: MutableMap<Int, Int> = HashMap()
for (num in nums) {
if (map.containsKey(num)) {
var repeated = map[num]!!
map[num] = ++repeated
if (repeated == 1) {
sum -= num
}
continue
}
map[num] = 0
sum += num
}
return sum
}
}
/**
* Filter
*/
class SumOfUniqueFilter : SumOfUnique {
override operator fun invoke(nums: IntArray): Int = nums.filter { n -> nums.count { it == n } < 2 }.sum()
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,085 | kotlab | Apache License 2.0 |
src/main/kotlin/year2022/Day07.kt | simpor | 572,200,851 | false | {"Kotlin": 80923} | import AoCUtils
import AoCUtils.test
fun main() {
data class File(val name: String, val size: Long)
data class Folder(
val name: String,
val parent: Folder?,
val files: MutableList<File> = mutableListOf(),
val folders: MutableList<Folder> = mutableListOf(),
var totalSize: Long = 0
) {
val level: Int
init {
level = if (parent != null) parent.level + 1 else 0
}
}
fun isCommand(line: String) = line.startsWith("$")
fun isCd(line: String) = line.contains("cd")
fun isLs(line: String) = line.contains("ls")
fun printFileSystem(folder: Folder) {
println(" ".repeat(folder.level) + folder.name + " (dir, totalSize: ${folder.totalSize})")
folder.files.forEach { println(" ".repeat(folder.level + 1) + it.name + " (file, size: ${it.size})") }
folder.folders.forEach { printFileSystem(it) }
}
fun isFolder(line: String) = line.contains("dir")
fun countTotalSize(folder: Folder): Long {
val fileSize = folder.files.sumOf { it.size }
folder.totalSize = folder.folders.sumOf { countTotalSize(it) } + fileSize
return folder.totalSize
}
fun sumOfFoldersWithSizeLessThen(folder: Folder, totalSize: Long): Long {
if (folder.totalSize < totalSize) {
return folder.totalSize + folder.folders.sumOf { sumOfFoldersWithSizeLessThen(it, totalSize) }
} else {
return folder.folders.sumOf { sumOfFoldersWithSizeLessThen(it, totalSize) }
}
}
fun getFileSystem(input: String): Folder {
val root = Folder("/", null)
var currentDir = root
var listingMode = false
input.lines().forEach { line ->
if (isCommand(line)) {
if (isCd(line)) {
listingMode = false
val dir = line.split(" ").last()
currentDir = if (dir == "/") {
root
} else if (dir == "..") {
currentDir.parent!!
} else {
currentDir.folders.first { it.name == dir }
}
} else if (isLs(line)) {
listingMode = true
} else {
throw Exception("Unknown command: $line")
}
} else if (listingMode) {
if (isFolder(line)) {
val dir = line.split(" ").last().trim()
if (!currentDir.folders.any { it.name == dir }) {
currentDir.folders.add(Folder(dir, currentDir))
}
} else {
val split = line.split(" ")
val size = split[0].trim().toLong()
val name = split[1].trim()
currentDir.files.add(File(name, size))
}
}
}
countTotalSize(root)
return root
}
fun part1(input: String, debug: Boolean = false): Long {
val root = getFileSystem(input)
printFileSystem(root)
return sumOfFoldersWithSizeLessThen(root, 100000L)
}
fun listOfDirs(folder: Folder): List<Folder> {
val folders = folder.folders
return folders + folder.folders.map { listOfDirs(it) }.flatten()
}
fun part2(input: String, debug: Boolean = false): Long {
val root = getFileSystem(input)
val neededSize = 30000000L - (70000000L - root.totalSize)
val listOfDirs = listOfDirs(root)
val size = listOfDirs.map { it.totalSize - neededSize }.filter { it > 0 }.minOf { it }
return size + neededSize
}
val testInput =
"\$ cd /\n" +
"\$ ls\n" +
"dir a\n" +
"14848514 b.txt\n" +
"8504156 c.dat\n" +
"dir d\n" +
"\$ cd a\n" +
"\$ ls\n" +
"dir e\n" +
"29116 f\n" +
"2557 g\n" +
"62596 h.lst\n" +
"\$ cd e\n" +
"\$ ls\n" +
"584 i\n" +
"\$ cd ..\n" +
"\$ cd ..\n" +
"\$ cd d\n" +
"\$ ls\n" +
"4060174 j\n" +
"8033020 d.log\n" +
"5626152 d.ext\n" +
"7214296 k"
val input = AoCUtils.readText("year2022/day07.txt")
part1(testInput, false) test Pair(95437L, "test 1 part 1")
part1(input, false) test Pair(1443806L, "part 1")
part2(testInput, false) test Pair(24933642L, "test 2 part 2")
part2(input) test Pair(921L, "part 2")
}
| 0 | Kotlin | 0 | 0 | 631cbd22ca7bdfc8a5218c306402c19efd65330b | 4,722 | aoc-2022-kotlin | Apache License 2.0 |
src/Day09.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.io.File
import kotlin.math.abs
import kotlin.math.sign
// Advent of Code 2022, Day 09, Rope Bridge
fun main() {
fun readInput(name: String) = File("src", "$name.txt").readLines()
data class Pos(val x: Int, val y: Int)
fun getHeadMoves(input: List<String>): List<Pos> {
val headMoves = mutableListOf<Pos>()
var head = Pos(0, 0)
headMoves.add(head)
input.forEach {
val move = it.split(" ")
val newDir =
when (move[0]) {
"R" -> Pos(1, 0)
"L" -> Pos(-1, 0)
"U" -> Pos(0, 1)
else -> Pos(0, -1)
}
repeat(move[1].toInt()) {
head = Pos(head.x + newDir.x, head.y + newDir.y)
headMoves.add(head)
}
}
return headMoves
}
fun part1(input: List<String>): Int {
val headMoves = getHeadMoves(input)
val tailMoves = mutableSetOf <Pos>()
var tail = Pos(0, 0)
tailMoves.add(tail)
headMoves.forEach {
val movedALot = abs(it.x - tail.x) > 1 || abs(it.y - tail.y) > 1
if (movedALot) {
val moveX = (it.x - tail.x).sign
val moveY = (it.y - tail.y).sign
tail = Pos(tail.x + moveX, tail.y + moveY)
tailMoves.add(tail)
}
}
return tailMoves.size
}
fun printGrid(ropePos: Array<Pos>) {
for (j in 30 downTo -15) {
for (i in -15..15) {
when (val idx = ropePos.indexOfFirst { it == Pos(i, j) }) {
-1 -> if (i==0 && j== 0) print('s') else print('.')
else -> print(idx)
}
}
print('\n')
}
print('\n')
}
fun part2(input: List<String>): Int {
val headMoves = getHeadMoves(input)
val tailMoves = mutableSetOf <Pos>()
tailMoves.add(Pos(0, 0))
val ropePos = Array(10) {Pos(0, 0)}
headMoves.forEach {
ropePos[0] = it
repeat(9) {i ->
val lead = ropePos[i]
val next = ropePos[i + 1]
val movedALot = abs(lead.x - next.x) > 1 || abs(lead.y - next.y) > 1
if (movedALot) {
val moveX = (lead.x - next.x).sign
val moveY = (lead.y - next.y).sign
ropePos[i + 1] = Pos(next.x + moveX, next.y + moveY)
} // else break out of repeat loop?
}
tailMoves.add(ropePos.last())
}
return tailMoves.size
}
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 2,958 | AdventOfCode2022 | Apache License 2.0 |
codeforces/src/main/kotlin/contest1911/G.kt | austin226 | 729,634,548 | false | {"Kotlin": 23837} | import java.math.BigInteger
private fun String.splitWhitespace() = split("\\s+".toRegex())
// s1 and s2 both have the same length
fun averageString(s1: String, s2: String, len: Int): String {
// // Work backwards from the end
// val avgStrChars = MutableList<Char>(len) { '?' }
// var remainder = 0
// for (i in len - 1 downTo 0) {
// // Add the chars together, then divide by two
// val c1Val = s1[i] - 'a'
// val c2Val = s2[i] - 'a'
// val (avgC, nextRemainder) = if (c1Val == c2Val) {
// Pair(c1Val, 0)
// } else if (c1Val < c2Val) {
// Pair((c1Val + c2Val) / 2, 0)
// } else {
// // c1Val > c2Val
// Pair((c1Val + c2Val + 26) / 2, -1)
// }
//
// avgStrChars[i] = (remainder + avgC % 26 + ('a'.code)).toChar()
// remainder = if (c1Val + c2Val > 25) 1 else 0
// }
//
// return avgStrChars.joinToString("")
var s1Num = BigInteger.ZERO
var s2Num = BigInteger.ZERO
for (i in 0 until len) {
val c1Val = (s1[i] - 'a').toLong()
val c2Val = (s2[i] - 'a').toLong()
val placeFactor = BigInteger.valueOf(26).pow(len - i - 1)
s1Num = s1Num.plus(BigInteger.valueOf(c1Val).times(placeFactor))
s2Num = s2Num.plus(BigInteger.valueOf(c2Val).times(placeFactor))
}
val sAvg = s1Num.plus(s2Num).divide(BigInteger.valueOf(2))
val resChars = mutableListOf<Char>()
var rem = sAvg
var exp = len - 1
while (exp >= 0) {
val divisor = BigInteger.valueOf(26).pow(exp)
val n = rem.divide(divisor).toInt()
rem = rem.mod(divisor)
exp--
val c = (n + 'a'.code).toChar()
resChars.add(c)
}
return resChars.joinToString("")
}
fun main() {
// len(s) = len(t) = k
// k in 1..=2e5
val k = readln().toInt()
val s = readln()
val t = readln()
// Find the median string that is (> s) and (< t)
// We know there are an odd number of such strings
// Median will be the same as the mean
// Treat strings like k-digit numbers in base 26.
println(averageString(s, t, k))
} | 0 | Kotlin | 0 | 0 | 4377021827ffcf8e920343adf61a93c88c56d8aa | 2,134 | codeforces-kt | MIT License |
src/main/aoc2019/Day14.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2019
import kotlin.math.ceil
import kotlin.math.min
class Day14(input: List<String>) {
data class Reaction(val req: List<Pair<Int, String>>, val res: Pair<Int, String>)
// Material name to reaction to create the material
private val reactions = input.map { parseLine(it) }.associateBy { it.res.second }
// 165 ORE => 6 DCFZ
// 44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL
private fun parseLine(line: String): Reaction {
val req = mutableListOf<Pair<Int, String>>()
val (before, after) = line.split(" => ")
before.split(", ").forEach { req.add(getAmountMaterialPair(it)) }
return Reaction(req, getAmountMaterialPair(after))
}
private fun getAmountMaterialPair(s: String): Pair<Int, String> {
val (amount, material) = s.split(" ")
return Pair(amount.toInt(), material)
}
// Returns the amount of ore needed to create the given material
private fun create(amount: Long, material: String, available: MutableMap<String, Long>): Long {
if (material == "ORE") {
return amount
}
// If there is already some of the desired material created since an earlier reaction use that.
val alreadyAvailable = min(amount, available.getOrDefault(material, 0))
available[material] = available.getOrDefault(material, 0) - alreadyAvailable
val toCreate = amount - alreadyAvailable
// Create more materials to fill the need.
val reaction = reactions[material] ?: error("Unknown material: $material")
val numReactions = ceil(toCreate.toDouble() / reaction.res.first).toLong()
val oreNeeded = reaction.req.sumByLong { create(numReactions * it.first, it.second, available) }
val created = numReactions * reaction.res.first
// Store any left over materials for future reactions.
val leftOver = created - toCreate
available[material] = available.getOrDefault(material, 0) + leftOver
return oreNeeded
}
fun solvePart1(): Long {
return create(1L, "FUEL", mutableMapOf())
}
fun solvePart2(): Long {
val capacity = 1_000_000_000_000
val oreForOne = create(1L, "FUEL", mutableMapOf())
val lowerBound = capacity / oreForOne
var start = lowerBound
var end = lowerBound * 2
var candidate = 0L
while (start <= end) {
val mid = start + (end - start) / 2
val currentValue = create(mid, "FUEL", mutableMapOf())
if (currentValue > capacity) {
end = mid - 1
} else {
start = mid + 1
candidate = mid
}
}
return candidate
}
private inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
var sum = 0L
for (element in this) {
sum += selector(element)
}
return sum
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,962 | aoc | MIT License |
src/Day05.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | import kotlin.collections.ArrayDeque
const val FIRST_STACK_NUMBER = '1'
fun main() {
data class Procedure(val unit: Int, val startStack: Int, val destinationStack: Int)
fun getCrates(input: List<String>): Map<Int, ArrayDeque<Char>> {
val crates = mutableMapOf<Int, ArrayDeque<Char>>()
// Get rowIndex of all stackNumbers.
val rowIndex = input.indexOfFirst{it.contains(FIRST_STACK_NUMBER)}
var stackNumber = '1'
var endReached = false
while (!endReached) {
// Get columnIndex of the given stackNumber.
val columnIndex = input[rowIndex].indexOfFirst{it == stackNumber}
// Fill the stack of the specified stackNumber with all crates on the same columnIndex.
crates[stackNumber.digitToInt()] = ArrayDeque()
for (line in input) {
if (line.length - 1 >= columnIndex &&
line[columnIndex] != ' ' &&
line[columnIndex] != stackNumber) {
crates[stackNumber.digitToInt()]?.add(line[columnIndex])
}
}
// Up the stackNumber and check if this stackNumber still exists. If not, end the loop.
stackNumber++
if (input.all{!it.contains(stackNumber)}) {
endReached = true
}
}
return crates
}
fun getProcedures(input: List<String>): List<Procedure> {
val splitInput = input.map{line -> line.split("move ", " from ", " to ").filter{ it.isNotEmpty() }}
val procedures = mutableListOf<Procedure>()
for (line in splitInput) {
val unit = line[0].toInt()
val startStack = line[1].toInt()
val destinationStack = line[2].toInt()
procedures.add(Procedure(unit, startStack, destinationStack))
}
return procedures
}
fun part1(input: List<List<String>>): String {
val crates = getCrates(input.first())
val procedures = getProcedures(input.last())
for (procedure in procedures) {
for (i in 0 until procedure.unit) {
val tempCrate = crates[procedure.startStack]?.removeFirst() ?: ' '
crates[procedure.destinationStack]?.addFirst(tempCrate)
}
}
return crates.values.map{it.first()}.joinToString("")
}
fun part2(input: List<List<String>>): String {
val crates = getCrates(input.first())
val procedures = getProcedures(input.last())
for (procedure in procedures) {
val tempCrates = mutableListOf<Char>()
for (i in 0 until procedure.unit) {
tempCrates.add(crates[procedure.startStack]?.removeFirst() ?: ' ')
}
for (i in tempCrates.size - 1 downTo 0) {
crates[procedure.destinationStack]?.addFirst(tempCrates[i])
}
}
return crates.values.map{it.first()}.joinToString("")
}
val input = readInputSplitByDelimiter("Day05", "${System.lineSeparator()}${System.lineSeparator()}")
.map{it.split(System.lineSeparator())}
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 3,196 | AoC2022 | Apache License 2.0 |
plugins/evaluation-plugin/core/src/com/intellij/cce/metric/CompletionGolfMetrics.kt | trinhanhngoc | 205,765,945 | true | null | package com.intellij.cce.metric
import com.intellij.cce.core.Session
import com.intellij.cce.metric.util.Sample
abstract class CompletionGolfMetric<T : Number> : Metric {
protected var sample = Sample()
private fun T.alsoAddToSample(): T = also { sample.add(it.toDouble()) }
protected fun computeMoves(session: Session): Int = session.lookups.sumOf { if (it.selectedPosition >= 0) it.selectedPosition else 0 }
protected fun computeCompletionCalls(sessions: List<Session>): Int = sessions.sumOf { it.lookups.count { lookup -> lookup.isNew } }
override fun evaluate(sessions: List<Session>, comparator: SuggestionsComparator): T = compute(sessions, comparator).alsoAddToSample()
abstract fun compute(sessions: List<Session>, comparator: SuggestionsComparator): T
}
class CompletionGolfMovesSumMetric : CompletionGolfMetric<Int>() {
override val name: String = "Code Golf Moves Count"
override val valueType = MetricValueType.INT
override val value: Double
get() = sample.sum()
override fun compute(sessions: List<Session>, comparator: SuggestionsComparator): Int {
// Add x2 amount of lookups, assuming that before each action we call code completion
// We summarize 3 types of actions:
// call code completion (1 point)
// choice suggestion from completion or symbol (if there is no offer in completion) (1 point)
// navigation to the suggestion (if it fits) (N points, based on suggestion index, assuming first index is 0)
return sessions.map { computeMoves(it) + it.lookups.count() }
.sum()
.plus(computeCompletionCalls(sessions))
}
}
class CompletionGolfMovesCountNormalised : CompletionGolfMetric<Double>() {
override val name: String = "Code Golf Moves Count Normalised"
override val valueType = MetricValueType.DOUBLE
override val value: Double
get() = sample.mean()
override fun compute(sessions: List<Session>, comparator: SuggestionsComparator): Double {
val linesLength = sessions.sumOf { it.expectedText.length } * 2.0
val amountOfMoves = sessions.sumOf { computeMoves(it) + it.lookups.count() } + computeCompletionCalls(sessions)
val subtrahend = sessions.count() * 2.0
// Since code completion's call and the choice of option (symbol) contains in each lookup,
// It is enough to calculate the difference for the number of lookups and extra moves (for completion case)
// To reach 0%, you also need to subtract the minimum number of lookups (eq. number of sessions plus minimum amount of completion calls)
// 0% - best scenario, every line was completed from start to end with first suggestion in list
// >100% is possible, when navigation in completion takes too many moves
return ((amountOfMoves - subtrahend) / (linesLength - subtrahend))
}
}
class CompletionGolfPerfectLine : CompletionGolfMetric<Int>() {
override val name: String = "Code Golf Perfect Line"
override val valueType = MetricValueType.INT
override val value: Double
get() = sample.sum()
override fun compute(sessions: List<Session>, comparator: SuggestionsComparator): Int {
return sessions.count { it.success }
}
}
| 0 | null | 0 | 0 | 1d4a962cfda308a73e0a7ef75186aaa4b15d1e17 | 3,147 | intellij-community | Apache License 2.0 |
src/aoc2022/Day08.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import println
import readInput
fun main() {
data class Tree(val x: Int, val y: Int, val h: Int)
fun part1(input: List<String>): Int {
// i top to bottom, j left to right == LEFT
val unique = mutableSetOf<Tree>()
for (i in input.indices) {
var tallest = 0
for (j in input[i].indices) {
if (j == 0) {
tallest = input[i][j].digitToInt()
unique.add(Tree(i, j, input[i][j].digitToInt()))
}
if (input[i][j].digitToInt() > tallest) {
tallest = input[i][j].digitToInt()
unique.add(Tree(i, j, input[i][j].digitToInt()))
}
}
}
// i top to bottom, j right to left == RIGHT
for (i in input.indices) {
var tallest = 0
for (j in input[i].indices.reversed()) {
if (j == input[i].length - 1) {
tallest = input[i][j].digitToInt()
unique.add(Tree(i, j, input[i][j].digitToInt()))
}
if (input[i][j].digitToInt() > tallest) {
tallest = input[i][j].digitToInt()
unique.add(Tree(i, j, input[i][j].digitToInt()))
}
}
}
// j left to right, i top to bottom == TOP
for (j in input[0].indices) {
var tallest = 0
for (i in input.indices) {
if (i == 0) {
tallest = input[i][j].digitToInt()
unique.add(Tree(i, j, input[i][j].digitToInt()))
}
if (input[i][j].digitToInt() > tallest) {
tallest = input[i][j].digitToInt()
unique.add(Tree(i, j, input[i][j].digitToInt()))
}
}
}
// j left to right, i bottom to top == BOTTOM
for (j in input[0].indices) {
var tallest = 0
for (i in input.indices.reversed()) {
if (i == input.size - 1) {
tallest = input[i][j].digitToInt()
unique.add(Tree(i, j, input[i][j].digitToInt()))
}
if (input[i][j].digitToInt() > tallest) {
tallest = input[i][j].digitToInt()
unique.add(Tree(i, j, input[i][j].digitToInt()))
}
}
}
return unique.size
}
fun part2(input: List<String>): Int {
var maxScenicScore = 0
for (i in 1 until input.size - 1) {
for (j in 1 until input[i].length - 1) {
var topView = 0
for (k in 1 .. i ) {
topView += 1
if (input[i - k][j].digitToInt() >= input[i][j].digitToInt())
break
}
var downView = 0
for (k in 1 .. input.size - 1 - i ) {
downView += 1
if (input[i + k][j].digitToInt() >= input[i][j].digitToInt())
break
}
var leftView = 0
for (k in 1 .. j ) {
leftView += 1
if (input[i][j - k].digitToInt() >= input[i][j].digitToInt())
break
}
var rightView = 0
for (k in 1 .. input[0].length - 1 - j ) {
rightView += 1
if (input[i][j + k].digitToInt() >= input[i][j].digitToInt())
break
}
val score = topView * downView * leftView * rightView
if (score > maxScenicScore) maxScenicScore = score
}
}
return maxScenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 4,134 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/KruskalsMST.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.algo.algorithms.graph
import java.util.*
fun main() {
val unionFind = KruskalsMST(9)
val sc = Scanner(System.`in`)
unionFind.accept(sc)
unionFind.display()
// println(unionFind.containsCycle())
var sum = 0
val mst: Array<Edge?> = unionFind.kruskal()
for (e in mst) {
println("Edge $e")
sum += e!!.weight
}
println("\nTotal weight of MST = $sum")
sc.close()
}
class KruskalsMST(val vertCount: Int) {
var edgeCount: Int = 0
private val mat = Array(vertCount) { Array(vertCount) { Int.MAX_VALUE } }
private lateinit var edgeList : Array<Edge?>
/* private data class Edge(val src: Int, val dst: Int, val weight: Int) {
override fun toString(): String {
return "src: $src to dest: $dst weight: $weight"
}
}*/
fun accept(sc: Scanner) {
println("Enter number of edges: ")
edgeCount = sc.nextInt()
println("Enter $edgeCount edges, src - dst - weight")
edgeList = arrayOfNulls(edgeCount)
for (i in 0 until edgeCount) {
val src = sc.nextInt()
val dst = sc.nextInt()
val wt = sc.nextInt()
mat[src][dst] = wt
mat[dst][src] = wt
edgeList[i] = Edge(src, dst, wt)
// edgeArray[i] = (Edge(src, dst, wt))
}
}
fun display() {
for (oArray in mat) {
println()
for (iVal in oArray) {
if (iVal == Int.MAX_VALUE) {
print("\t#")
} else {
print("\t$iVal")
}
}
println()
}
}
fun find(v: Int, parent: IntArray): Int {
// var t = v
// for (i in parent) {
// if (parent[i] != -1) {
// t = parent[i]
// }
// }
// return t
var v = v
while (parent[v] != -1) v = parent[v]
return v
}
fun union(src: Int, dst: Int, parent: IntArray) {
parent[src] = dst
}
private fun cotainsCycle(mst: Array<Edge?>, mstCount: Int): Boolean {
val parent = IntArray(vertCount) {-1}
for (i in 0 until mstCount) {
val e = mst[i]
val sr = find(e!!.src, parent)
val dr = find(e.dst, parent)
if (sr == dr) return true
union(sr, dr, parent)
}
return false
}
internal fun kruskal() : Array<Edge?> {
edgeList.sortWith(Comparator {e1, e2 -> e1!!.weight - e2!!.weight})
// edgeArray.sort(Comparator { o1: Edge, o2: Edge -> o1.weight - o2.weight})
// val mst = MutableList(vertCount-1) {Edge(0, 0, 0)}
val mst = arrayOfNulls<Edge>(vertCount - 1)// {Edge(0, 0, 0)}
var i = 0
var mstEdgeCount = 0
while (mstEdgeCount < vertCount - 1) {
val e = edgeList[i]
i += 1
mst[mstEdgeCount] = e
mstEdgeCount++
if (cotainsCycle(mst, mstEdgeCount)) {
mstEdgeCount -= 1
mst[mstEdgeCount] = null
}
}
return mst
}
} | 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 3,215 | DS_Algo_Kotlin | MIT License |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-25.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2022, "25-input")
val testInput1 = readInputLines(2022, "25-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
}
private fun part1(input: List<String>): String {
val sum = input.sumOf { snafuToDecimal(it) }
return decimalToSnafu(sum)
}
private fun snafuToDecimal(snafu: String): Long {
var result = 0L
var value = 1L
val digits = digitsMap.associate { it.second to it.first }
for (c in snafu.reversed()) {
val digit = digits[c]!!
result += digit * value
value *= 5
}
return result
}
private fun decimalToSnafu(number: Long): String {
var result = ""
var rest = number
val digits = digitsMap.toMap()
while (rest != 0L) {
var mod = rest % 5
if (2 < mod) mod -= 5
result += digits[mod]!!
rest = (rest - mod) / 5
}
return result.reversed()
}
val digitsMap = listOf(-2L to '=', -1L to '-', 0L to '0', 1L to '1', 2L to '2')
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,179 | advent-of-code | MIT License |
src/Day10.kt | GreyWolf2020 | 573,580,087 | false | {"Kotlin": 32400} | fun main() {
fun part1(input: List<String>): Int {
val cycleForSignalStrength = mutableListOf<Int>(20, 60, 100, 140, 180, 220)
val register = Register()
val clock = Clock().apply { addProcessors(register) }
val signalStrength = buildList {
input
.forEach { instruction ->
register
.parseInstruction(instruction)
while (!register.isInstructionDone) {
clock.incrementCycle()
if (cycleForSignalStrength.isNotEmpty() && clock.cycle == cycleForSignalStrength.first()) {
add(Pair(cycleForSignalStrength.removeFirst(), register.value))
}
}
register.executeInstruction()
}
}
clock.removeProcessor(register)
return signalStrength
.sumOf { it.first * it.second }
}
fun part2(input: List<String>): Int {
val register = Register()
val clock = Clock().apply { addProcessors(register) }
val crtAllPixels = buildList {
input
.forEach { instruction ->
register
.parseInstruction(instruction)
while (!register.isInstructionDone) {
val crtCurrentPosition = (clock.cycle) % 40
val sprite = register.value - 1 .. register.value + 1
if (crtCurrentPosition in sprite)
add("#")
else add(".")
clock.incrementCycle()
}
register.executeInstruction()
}
}
clock.removeProcessor(register)
return crtAllPixels
.also { drawCrtAllPixels(it) }
.also { println() }
.filter { it == "#" }
.size
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day10_test")
// check(part1(testInput) == 13140)
// check(part2(testInput) == 124)
//
// val input = readInput("Day10")
// println(part1(input))
// println(part2(input))
}
interface Processor {
fun process()
}
data class Clock(var cycle: Int = 0) {
val processors = mutableListOf<Processor>()
fun incrementCycle() {
cycle++
processors.forEach { processor -> processor.process() }
}
fun addProcessors(processor: Processor) {
if (!processors.contains(processor))
processors.add(processor)
}
fun removeProcessor(processor: Processor) {
if (!processors.contains(processor))
processors.remove(processor)
}
}
class Register(var value: Int = 1) : Processor {
sealed class Instruction(var cyclesLeft: Int, val valueToAdd: Int) {
data class Noop(val value: Int = 0): Instruction(1, value)
data class AddX(val value: Int): Instruction(2, value)
}
val isInstructionDone: Boolean
get() = currentInstruction.cyclesLeft == 0
lateinit var currentInstruction: Instruction
override fun process() {
currentInstruction.cyclesLeft--
}
fun executeInstruction() {
value += currentInstruction.valueToAdd
}
}
fun Register.parseInstruction(instruction: String) {
val noopOrAddX = instruction.split(" ")
when (noopOrAddX.first()) {
"noop" -> currentInstruction = Register.Instruction.Noop()
"addx" -> currentInstruction = Register.Instruction.AddX(noopOrAddX.last().toInt())
}
}
fun drawCrtAllPixels(crtAllPixels: List<String>) {
crtAllPixels.forEachIndexed { index, pixel ->
if ((index) % 40 == 0)
println()
print(pixel)
}
} | 0 | Kotlin | 0 | 0 | 498da8861d88f588bfef0831c26c458467564c59 | 3,852 | aoc-2022-in-kotlin | Apache License 2.0 |
src/kotlin/_2023/Task01.kt | MuhammadSaadSiddique | 567,431,330 | false | {"Kotlin": 20410} | package _2022
import Task
import readInput
object Task01: Task {
override fun partA() = part1(parseInput())
override fun partB() = part2(parseInput())
private fun parseInput() = readInput("_2022/01")
.split("\n\n")
.map { it.split("\n").sumOf { it.toInt() } }
fun part1(input: List<String>): Int {
return input.sumOf {
(it.find { it.isDigit() }.toString() + it.findLast { it.isDigit() }).toInt()
}
}
fun part2(input: List<String>): Int {
val map = mapOf(
"one" to 1, "two" to 2, "three" to 3, "four" to 4,
"five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9,
"1" to 1, "2" to 2, "3" to 3, "4" to 4, "5" to 5, "6" to 6,
"7" to 7, "8" to 8, "9" to 9
)
return input.sumOf {
val first = map[it.findAnyOf(map.keys)!!.second].toString()
val second = map[it.findLastAnyOf(map.keys)!!.second].toString()
(first + second).toInt()
}
}
}
| 0 | Kotlin | 0 | 0 | 3893ae1ac096c56e224e798d08d7fee60e299a84 | 1,041 | AdventCode-Kotlin | Apache License 2.0 |
src/Day13.kt | cornz | 572,867,092 | false | {"Kotlin": 35639} | import kotlin.math.min
fun main() {
data class Index(var index: Int = 0)
fun processList(input: String, index: Index): List<Any> {
val list = mutableListOf<Any>()
while (index.index < input.count()) {
val char = input[index.index]
index.index++
when (char) {
'[' -> list.add(processList(input, index))
',' -> continue
']' -> return list
else -> {
val startIndex = index.index - 1
while (input[index.index].isDigit()) {
index.index++
}
list.add(input.subSequence(startIndex, index.index).toString().toInt())
}
}
}
return list
}
fun processPair(input: List<String>): Pair<List<Any>, List<Any>> {
return Pair(processList(input[0], Index()), processList(input[1], Index()))
}
fun processPairs(left: List<Any>, right: List<Any>): Boolean? {
for (i in 0 until min(left.size, right.size)) {
if (left[i] is Int && right[i] is Int) {
val leftInt = left[i] as Int
val rightInt = right[i] as Int
if (leftInt == rightInt) continue
if (leftInt < rightInt) return true
if (leftInt > rightInt) return false
} else if (left[i] is List<*> && right[i] is List<*>) {
val arrayResult = processPairs(left[i] as List<Any>, right[i] as List<Any>)
if (arrayResult != null) return arrayResult
} else if (left[i] is Int) {
val arrayResult = processPairs(listOf(left[i]), right[i] as List<Any>)
if (arrayResult != null) return arrayResult
} else if (right[i] is Int) {
val arrayResult = processPairs(left[i] as List<Any>, listOf(right[i]))
if (arrayResult != null) return arrayResult
}
}
if (left.size < right.size) {
return true
} else if (left.size > right.size) {
return false
}
return null
}
fun isPairInRightOrder(pair: Pair<List<Any>, List<Any>>): Boolean {
return processPairs(pair.first, pair.second)!!
}
fun part1(input: List<String>): Int {
val res = mutableListOf<Boolean>()
val inputs = input.filter { x -> x.isNotEmpty() }.chunked(2)
val pairs = inputs.map { processPair(it) }
for (pair in pairs) {
res.add(isPairInRightOrder(pair))
}
var count = 0
for ((index, result) in res.withIndex()) {
if (result) {
count += index + 1
}
}
return count
}
val isALlInRightOrder = Comparator<List<Any>> { a, b ->
val result = processPairs(a, b)
if (result == null) {
0
} else if (result) {
-1
} else {
1
}
}
fun part2(input: List<String>): Int {
val holder = mutableListOf<List<Any>>()
val signals = input.filter { x -> x.isNotEmpty() }
for (signal in signals) {
val processSignal = processList(signal, Index())
holder.add(processSignal)
}
holder.add(listOf(listOf(2)))
holder.add(listOf(listOf(6)))
val sortedSignals = holder.sortedWith(isALlInRightOrder)
val res = sortedSignals.withIndex().filter { x -> x.value !is ArrayList<*> }
return res.map { x -> x.index + 1 }.reduce { acc, i -> acc * i }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("input/Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("input/Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2800416ddccabc45ba8940fbff998ec777168551 | 3,927 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day18/Day18.kt | alxgarcia | 435,549,527 | false | {"Kotlin": 91398} | package day18
import java.io.File
sealed interface SnailFishNumber {
val magnitude: Int
}
class SnailNumber(override var magnitude: Int) : SnailFishNumber {
val isSplittable: Boolean
get() = magnitude > 9
override fun toString(): String = magnitude.toString()
fun split(parent: SnailPair): SnailPair =
SnailPair(parent, SnailNumber(magnitude / 2), SnailNumber(magnitude - (magnitude / 2)))
}
class SnailPair(var parent: SnailPair?) : SnailFishNumber {
constructor(parent: SnailPair?, left: SnailPair, right: SnailPair) : this(parent) {
left.parent = this
this.left = left
right.parent = this
this.right = right
}
constructor(parent: SnailPair?, left: SnailFishNumber, right: SnailFishNumber) : this(parent) {
this.left = left
this.right = right
}
lateinit var left: SnailFishNumber
lateinit var right: SnailFishNumber
private val isExploitable
get() = left is SnailNumber && right is SnailNumber
override val magnitude: Int
get() = 3 * left.magnitude + 2 * right.magnitude
override fun toString(): String = "[$left,$right]"
fun reduceOnce(): Boolean = exploit(0) || split()
fun reduce() {
do { val hasReduced = reduceOnce() } while (hasReduced)
}
private fun split(): Boolean =
when { // Returning true breaks the recursion
(left as? SnailNumber)?.isSplittable ?: false -> {
left = (left as SnailNumber).split(this)
true
}
(left as? SnailPair)?.split() ?: false -> true
(right as? SnailNumber)?.isSplittable ?: false -> {
right = (right as SnailNumber).split(this)
true
}
else -> (right as? SnailPair)?.split() ?: false
}
private fun exploit(level: Int): Boolean {
fun sumToLeft(amount: Int, current: SnailPair, parent: SnailPair?) {
if (parent == null) return
else if (parent.left == current) sumToLeft(amount, parent, parent.parent)
else {
var leftNumber = parent.left
while (leftNumber is SnailPair) leftNumber = leftNumber.right
(leftNumber as SnailNumber).magnitude += amount
}
}
fun sumToRight(amount: Int, current: SnailPair, parent: SnailPair?) {
if (parent == null) return
else if (parent.right == current) sumToRight(amount, parent, parent.parent)
else {
var rightNumber = parent.right
while (rightNumber is SnailPair) rightNumber = rightNumber.left
(rightNumber as SnailNumber).magnitude += amount
}
}
fun exploit(pair: SnailPair) {
sumToLeft((pair.left as SnailNumber).magnitude, pair, this)
sumToRight((pair.right as SnailNumber).magnitude, pair, this)
}
return when {
level >= 3 && (left as? SnailPair)?.isExploitable ?: false -> {
exploit(left as SnailPair)
left = SnailNumber(0)
true
}
level >= 3 && (right as? SnailPair)?.isExploitable ?: false -> {
exploit(right as SnailPair)
right = SnailNumber(0)
true
}
else -> (((left as? SnailPair)?.exploit(level + 1)) ?: false) || (((right as? SnailPair)?.exploit(level + 1)) ?: false)
}
}
}
fun parseSnailFishNumber(line: String): SnailPair {
fun parseSnailFishNumber(input: Iterator<Char>, parent: SnailPair?): SnailFishNumber =
when (val c = input.next()) {
'[' -> {
val pair = SnailPair(parent)
pair.left = parseSnailFishNumber(input, pair)
input.next() // ignoring comma
pair.right = parseSnailFishNumber(input, pair)
input.next() // consuming the closing ']'
pair
}
// gotta be a digit since numbers greater than 9 are not allowed (must be split)
else -> SnailNumber(c.digitToInt())
}
return parseSnailFishNumber(line.iterator(), null) as SnailPair // The root is always a Pair
}
fun sum(n1: SnailPair, n2: SnailPair): SnailPair {
val result = SnailPair(null, n1, n2)
result.reduce()
return result
}
fun main() {
File("./input/day18.txt").useLines { lines ->
val input = lines.toList()
println(input.map { parseSnailFishNumber(it) }.reduce(::sum).magnitude)
println(input
.flatMap { x -> input.filterNot { it == x }.map { y -> x to y } }
.maxOf { (x, y) -> sum(parseSnailFishNumber(x), parseSnailFishNumber(y)).magnitude })
}
}
| 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 4,309 | advent-of-code-2021 | MIT License |
src/Day04.kt | l8nite | 573,298,097 | false | {"Kotlin": 105683} | fun main() {
fun part1(input: List<String>): Int {
var overlapped = 0
input.forEach { line ->
val (a1, a2, b1, b2) = line.split("-",",").map { it.toInt() }
if ((a1 <= b1 && a2 >= b2) || (a1 >= b1 && a2 <= b2) ) {
overlapped += 1
}
}
return overlapped
}
fun part2(input: List<String>): Int {
var overlapped = 0
input.forEach { line ->
val (a1, a2, b1, b2) = line.split("-",",").map { it.toInt() }
if ((a1 in b1..b2) || (b1 in a1..a2)) {
overlapped += 1
}
}
return overlapped }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f74331778fdd5a563ee43cf7fff042e69de72272 | 938 | advent-of-code-2022 | Apache License 2.0 |
app/src/y2021/day15/Day15Chiton.kt | henningBunk | 432,858,990 | false | {"Kotlin": 124495} | package y2021.day15
import common.*
import common.annotations.AoCPuzzle
import kotlin.math.min
fun main(args: Array<String>) {
Day15Chiton().solveThem(ignorePart1 = true)
}
@AoCPuzzle(2021, 15)
class Day15Chiton : AocSolution {
override val answers = Answers(samplePart1 = 40, samplePart2 = 315, part1 = 398)
override fun solvePart1(input: List<String>): Any {
val map = ChitonMap(input)
return map.findMinimalWayCost()
}
// ⏱ Calculating it took 386988,18ms
override fun solvePart2(input: List<String>): Any {
val map = ChitonMap(input, mapExpandsBy = 5)
return map.findMinimalWayCost()
}
}
class ChitonMap(input: List<String>, mapExpandsBy: Int = 1) {
private val labels: MutableMap<Coordinate, Int> = hashMapOf()
private val nodes: MutableList<Node> = mutableListOf()
private val lastX = (input[0].length * mapExpandsBy) - 1
private val lastY = (input.size * mapExpandsBy) - 1
init {
val riskLevels = input.map { it.map(Character::getNumericValue) }
val tileWidth = riskLevels[0].size
val tileHeight = riskLevels.size
for (y in (0..(lastY))) {
for (x in (0..lastX)) {
addNode(Coordinate(x, y))
}
}
for (y in (0..lastY)) {
// println()
for (x in (0..lastX)) {
// print((riskLevels[y % tileHeight][(x)% tileWidth] + x / tileWidth + y / tileHeight).let {
// if (it > 9) it % 10 + 1 else it
// })
if (x - 1 >= 0) {
val cost = (riskLevels[y % tileHeight][(x - 1) % tileWidth] + (x-1) / tileWidth + y / tileHeight).let {
if (it > 9) it % 10 + 1 else it
}
addEdge(Coordinate(x, y), Coordinate(x - 1, y), cost)
}
if (x + 1 <= lastX) {
val cost = (riskLevels[y % tileHeight][(x + 1) % tileWidth] + (x+1) / tileWidth + y / tileHeight).let {
if (it > 9) it % 10 + 1 else it
}
addEdge(Coordinate(x, y), Coordinate(x + 1, y), cost)
}
if (y - 1 >= 0) {
val cost = (riskLevels[(y - 1) % tileHeight][x % tileWidth] + x / tileWidth + (y-1) / tileHeight).let {
if (it > 9) it % 10 + 1 else it
}
addEdge(Coordinate(x, y), Coordinate(x, y - 1), cost)
}
if (y + 1 <= lastY) {
val cost = (riskLevels[(y + 1) % tileHeight][x % tileWidth] + x / tileWidth + (y+1) / tileHeight).let {
if (it > 9) it % 10 + 1 else it
}
addEdge(Coordinate(x, y), Coordinate(x, y + 1), cost)
}
}
}
}
private fun addNode(label: Coordinate) {
nodes.add(Node())
labels[label] = nodes.lastIndex
}
private fun addEdge(source: Coordinate, destination: Coordinate, cost: Int) {
nodes[labels[source]!!].addEdge(Edge(destination, cost))
}
data class Coordinate(val x: Int, val y: Int)
data class Edge(val destination: Coordinate, val cost: Int)
class Node {
private val _edges: MutableList<Edge> = mutableListOf()
val edges: List<Edge>
get() = _edges
fun addEdge(edge: Edge) {
_edges.add(edge)
}
}
fun findMinimalWayCost(): Int {
var percentFinished = 0
val idStart = labels[Coordinate(0, 0)]!!
val idEnd = labels[Coordinate(lastX, lastY)]!!
val nodesToVisit = labels.values.associateWith { Int.MAX_VALUE }.toMutableMap()
nodesToVisit[idStart] = 0
var costToEnd = Int.MAX_VALUE
while (nodesToVisit.isNotEmpty()) {
val nodeCost = nodesToVisit.values.minOf { it }
val nodeId = nodesToVisit.filter { (k, v) -> v == nodeCost }.keys.first()
nodesToVisit.remove(nodeId)
nodes[nodeId].edges.forEach { (destination, cost) ->
val targetId = labels[destination]
val previousTargetCost = nodesToVisit[targetId]
if (targetId != null && previousTargetCost != null) {
nodesToVisit[targetId] = min(previousTargetCost, nodeCost + cost)
}
}
if (nodeId == idEnd) {
costToEnd = nodeCost
}
(nodesToVisit.size * 100 / nodes.size).let { percent ->
if (percentFinished != percent) {
percentFinished = percent
println("$percent%")
}
}
}
return costToEnd
}
} | 0 | Kotlin | 0 | 0 | 94235f97c436f434561a09272642911c5588560d | 4,806 | advent-of-code-2021 | Apache License 2.0 |
src/day07/Day07.kt | jimsaidov | 572,881,855 | false | {"Kotlin": 10629} | package day07
class Day07(private val input: List<String>) {
private data class File(val name: String, val size: Double)
private data class Directory(
val name: String,
val parent: Directory?,
val dirs: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf()
) {
private fun calculateSize() : Double =
dirs.sumOf { it.calculateSize() } + files.sumOf{ it.size }
val size : Double by lazy {
calculateSize()
}
}
private fun getDirectorySizeList(input: List<String>): List<Double> {
var currentDir = Directory("/", null)
val dirSizes = mutableListOf<Double>()
input.drop(1).forEach { line ->
when {
line.startsWith("$ cd") -> {
val dirName = line.split(" ")[2]
currentDir = if (dirName == "..") {
dirSizes.add(currentDir.size)
currentDir.parent!!
} else {
currentDir.dirs.first { it.name == dirName }
}
}
line.startsWith("dir") -> currentDir.dirs.add(line.createDirectory(currentDir))
line[0].isDigit() -> currentDir.files.add(line.createFile())
else -> {}
}
}
while (true) {
dirSizes.add(currentDir.size)
if (currentDir.name == "/") {
break
}
currentDir = currentDir.parent!!
}
return dirSizes
}
private fun String.createDirectory(parent: Directory) = Directory(split(" ")[1], parent)
private fun String.createFile() = with(split(" ")) {
File(this.last(), this.first().toDouble())
}
private fun List<Double>.getTotalLessThan(other: Double) = filter { it < other }.sum()
fun part1(): Int = getDirectorySizeList(input).getTotalLessThan(100000.00).toInt()
fun part2(): Int = with (getDirectorySizeList(input)) {
this.sorted().first{it >= (30000000.00 - (70000000.00 - this.max()))}.toInt()
}
}
fun main() {
val day = "07"
check(Day07(InputReader.testFileAsList(day)).part1() == 95437)
println(Day07(InputReader.asList(day)).part1())
check(Day07(InputReader.testFileAsList(day)).part2() == 24933642)
println(Day07(InputReader.asList(day)).part2())
} | 0 | Kotlin | 0 | 0 | d4eb926b57460d4ba4acced14658f211e1ccc12c | 2,439 | aoc2022 | Apache License 2.0 |
src/Day03.kt | MisterTeatime | 561,848,263 | false | {"Kotlin": 20300} | fun main() {
val movements = mapOf(
'>' to Point2D(1,0),
'<' to Point2D(-1,0),
'^' to Point2D(0,1),
'v' to Point2D(0,-1)
)
fun part1(input: List<String>): Int {
var position = Point2D(0,0)
val visitedHouses = mutableSetOf<Point2D>(position)
input[0].forEach {
position += movements[it]!!
visitedHouses.add(position)
}
return visitedHouses.size
}
fun part2(input: List<String>): Int {
var positionSanta = Point2D(0,0)
var positionRobotSanta = Point2D(0,0)
val visitedHouses = mutableSetOf<Point2D>(positionSanta)
input[0].forEachIndexed { index, c ->
when (index % 2) {
0 -> {
positionSanta += movements[c]!!
visitedHouses.add(positionSanta)
}
1 -> {
positionRobotSanta += movements[c]!!
visitedHouses.add(positionRobotSanta)
}
}
}
return visitedHouses.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 4)
check(part2(testInput) == 3)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d684bd252a9c6e93106bdd8b6f95a45c9924aed6 | 1,376 | AoC2015 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions57.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
fun test57() {
printlnResult(intArrayOf(1, 2, 3, 1), 3, 0)
printlnResult(intArrayOf(1, 5, 9, 1, 5, 9), 2, 3)
}
/**
* Questions 57: Given an IntArray nums, and two positive integer t and k,
* find the two indexes i and j that abs(i - j) <= k, and abs(nums[i] - nums[j]) <= t.
*/
private fun findIndexes(nums: IntArray, k: Int, t: Int): Boolean {
val bucketSize = t + 1
val buckets = HashMap<Int, Int>(bucketSize)
nums.forEachIndexed { i, num ->
val id = getBucketID(num, bucketSize)
if (buckets.contains(id)
|| (buckets.contains(id - 1) && buckets[id - 1]!! + t >= num)
|| (buckets.contains(id + 1) && buckets[id + 1]!! - t <= num))
return true
buckets[id] = num
if (i >= k)
buckets.remove(getBucketID(nums[i - k], bucketSize))
}
return false
}
private fun getBucketID(num: Int, bucketSize: Int): Int =
if (num >= 0) num / bucketSize else (num + 1) / (bucketSize - 1)
private fun printlnResult(nums: IntArray, k: Int, t: Int) =
println("In IntArray ${nums.toList()}, k = $k, t = $t, is the two indexes exit: ${findIndexes(nums, k, t)}") | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,200 | Algorithm | Apache License 2.0 |
src/main/kotlin/cc/stevenyin/leetcode/_0941_ValidMountainArray.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.leetcode
/**
* https://leetcode.com/problems/valid-mountain-array
* Given an array of integers arr, return true if and only if it is a valid mountain array.
*
* Recall that arr is a mountain array if and only if:
*
* arr.length >= 3
* There exists some i with 0 < i < arr.length - 1 such that:
* arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
* arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
*
* Example 1:
* Input: arr = [2,1]
* Output: false
*
* Example 2:
* Input: arr = [3,5,5]
* Output: false
*
* Example 3:
* Input: arr = [0,3,2,1]
* Output: true
*
*
* Constraints:
*
* 1 <= arr.length <= 104
* 0 <= arr[i] <= 104
*/
class _0941_ValidMountainArray {
fun validMountainArray(arr: IntArray): Boolean {
if (arr.size < 3) return false
var peak = -1
for (idx in 0 until arr.size - 1) {
if (arr[idx] == arr[idx + 1]) {
return false
} else if (arr[idx] > arr[idx + 1]) {
peak = idx
break
}
}
if (peak == arr.size - 1 || peak == -1) return false
for (idx in peak until arr.size - 1) {
if (arr[idx] == arr[idx + 1] || arr[idx] < arr[idx + 1]) {
return false
}
}
return true
}
}
fun main() {
val solution = _0941_ValidMountainArray()
solution.validMountainArray(intArrayOf(0,1,2,3,4,5,6,7,8,9))
solution.validMountainArray(intArrayOf(9,8,7,6,5,4,3,2,1,0))
}
| 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 1,512 | kotlin-demo-code | MIT License |
2021/Day2.kt | vypxl | 159,938,890 | false | {"Python": 216454, "Haskell": 97987, "Scala": 79708, "Go": 17521, "C++": 15658, "Kotlin": 6914, "Shell": 6661, "Elixir": 6363, "F#": 5977, "C#": 5571, "D": 5098, "C": 4467, "JavaScript": 3386, "Pascal": 3004, "OCaml": 2736, "Idris": 2434, "Perl": 1627, "Assembly": 1614, "Just": 1549, "Ruby": 1457, "Lua": 1117, "Groovy": 884, "Julia": 823, "Dart": 774, "Rust": 392, "Vim Script": 151} | import java.io.File
data class Command(val kind: String, val x: Int)
typealias TInput2 = List<Command>
typealias TOutput2 = Int
private fun part1(input: TInput2): TOutput2 =
input.fold(Pair(0, 0)) { (d, p), (kind, x) -> when(kind) {
"forward" -> Pair(d, p + x)
"up" -> Pair(d - x, p)
"down" -> Pair(d + x, p)
else -> Pair(d, p)
} }.let { (d, p) -> d*p }
private fun part2(input: TInput2): TOutput2 =
input.fold(Triple(0, 0, 0)) { (d, p, a), (kind, x) -> when(kind) {
"forward" -> Triple(d + a * x, p + x, a)
"up" -> Triple(d, p, a - x)
"down" -> Triple(d, p, a + x)
else -> Triple(d, p, a)
} }.let { (d, p, _) -> d*p }
private fun parse(raw_input: String): TInput2 =
lines(raw_input).map { val xs = it.split(" "); Command(xs[0], xs[1].toInt()) }
fun main() {
val rawInput = File("2.in").readText()
val input = parse(rawInput)
println("Solution for Part 1: ${part1(input)}")
println("Solution for Part 2: ${part2(input)}")
}
// Solution part 1: 1804520
// Solution part 2: 1971095320
| 0 | Python | 0 | 2 | d15e2052e6cff0f817080e815eb05543a7781982 | 1,091 | aoc | Do What The F*ck You Want To Public License |
src/Day14.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | private const val SAND_START_X = 500
fun main() {
fun part1(input: List<String>): Int {
val pathList: List<List<Coords>> = readPathList(input)
val fieldData = getFieldDataForPart1(pathList)
val field = Field(fieldData)
return field.getSandUnitCount()
}
fun part2(input: List<String>): Int {
val pathList: List<List<Coords>> = readPathList(input)
val fieldData = getFieldDataForPart2(pathList)
val field = Field(fieldData)
return field.getSandUnitCount()
}
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
private fun readPathList(input: List<String>): List<List<Coords>> {
return input
.map {
it.split(" -> ")
.map { stringPair ->
val list = stringPair.split(",")
.map { s -> s.toInt() }
Coords(list[0], list[1])
}
}
}
private data class FieldData(
val minX: Int,
val matrix: Array<Array<Boolean>>
)
private fun getFieldDataForPart1(pathList: List<List<Coords>>): FieldData {
var maxY = 0
var minX = SAND_START_X
var maxX = SAND_START_X
pathList.flatten()
.forEach {
if (it.x < minX)
minX = it.x
else if (it.x > maxX)
maxX = it.x
if (it.y > maxY)
maxY = it.y
}
val matrix = Array(maxX - minX + 1) { Array(maxY + 1) { false } }
addPathsToMatrix(pathList, matrix, minX)
return FieldData(minX, matrix)
}
private fun getFieldDataForPart2(pathList: List<List<Coords>>): FieldData {
var maxY = 0
var minX = SAND_START_X
var maxX = SAND_START_X
pathList.flatten()
.forEach {
if (it.x < minX)
minX = it.x
else if (it.x > maxX)
maxX = it.x
if (it.y > maxY)
maxY = it.y
}
maxY += 2
minX = Math.min(minX, SAND_START_X - maxY)
maxX = Math.max(maxX, SAND_START_X + maxY)
val matrix = Array(maxX - minX + 1) { Array(maxY + 1) { false } }
addPathsToMatrix(pathList, matrix, minX)
matrix.forEach {
it[it.lastIndex] = true
}
return FieldData(minX, matrix)
}
private fun addPathsToMatrix(
pathList: List<List<Coords>>,
matrix: Array<Array<Boolean>>,
minX: Int
) {
pathList.forEach {
for (i in 1 .. it.lastIndex) {
val startCoords = it[i - 1]
val endCoords = it[i]
if (startCoords.x == endCoords.x) {
val x = startCoords.x - minX
for (j in Math.min(startCoords.y, endCoords.y) .. Math.max(startCoords.y, endCoords.y))
matrix[x][j] = true
}
else {
val x1 = startCoords.x - minX
val x2 = endCoords.x - minX
for (j in Math.min(x1, x2) .. Math.max(x1, x2))
matrix[j][startCoords.y] = true
}
}
}
}
private class Field(fieldData: FieldData) {
private var maxY = fieldData.matrix[0].lastIndex
private var minX = fieldData.minX
private val matrix: Array<Array<Boolean>> = fieldData.matrix
private val lastColumn = fieldData.matrix.lastIndex
fun getSandUnitCount(): Int {
var result = 0
val startCoords = Coords(SAND_START_X - minX, 0)
while (true) {
val coords = getSandFinishCoords(startCoords)
if (coords == startCoords) {
result++
break
}
if (coords.y > maxY)
break
if (coords.x < 0 || coords.x > lastColumn)
break
matrix[coords.x][coords.y] = true
result++
}
return result
}
val moveXArray = arrayOf(0, -1, 1)
private fun getSandFinishCoords(startCoords: Coords): Coords {
var current = startCoords
while (true) {
var next: Coords? = null
for (move in moveXArray) {
val nextX = current.x + move
val nextY = current.y + 1
if (nextX in 0 .. lastColumn && nextY <= maxY) {
if (!matrix[nextX][nextY]) {
next = Coords(nextX, nextY)
break
}
}
else {
return Coords(nextX, nextY)
}
}
if (next == null)
return current
else {
current = next
}
}
}
}
| 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 4,776 | AdventOfCode2022 | Apache License 2.0 |
src/Day07NoSpaceLeftOnDevice.kt | zizoh | 573,932,084 | false | {"Kotlin": 13370} | fun main() {
val input: List<String> = readInput("input/day07")
val totalSizeOnDisk = calculateSumOfDirectories(getRootNode(input))
val totalDiskSpace = 70_000_000
val minimumSpaceRequired = 30_000_000
println(
sizesOfDirectories.filter { size ->
size >= minimumSpaceRequired + totalSizeOnDisk - totalDiskSpace
}.min()
)
}
private var sizesOfDirectories = mutableListOf<Int>()
private var totalSizeOnDisk = 0
fun calculateSumOfDirectories(node: Node): Int {
val sumOf = node.children.values.map {
if (it.name.isDirectoryOutput()) {
calculateSumOfDirectories(it)
} else it.size.toInt()
}
val sumOfDirectory = sumOf.sum()
totalSizeOnDisk += sumOfDirectory
sizesOfDirectories += sumOfDirectory
return sumOfDirectory
}
fun getRootNode(input: List<String>): Node {
val root = Node("root", "0")
val directories = mutableListOf(root)
for (index in 1..input.lastIndex) {
val commandOrOutput = input[index]
val currentDirectory = directories.last()
if (commandOrOutput.isMoveInCommand()) {
val directoryName = commandOrOutput.getDirectoryName()
val tempCurrentDirectory = currentDirectory.children["$DIR $directoryName"]!!
directories.add(tempCurrentDirectory)
} else if (commandOrOutput.isMoveOutCommand()) {
directories.removeLast()
} else if (commandOrOutput.isDirectoryOutput()) {
val directory = Node(commandOrOutput, size = "0")
currentDirectory.children[commandOrOutput] = directory
} else if (commandOrOutput.isFileOutput()) {
val fileName = commandOrOutput.getFileName()
val file = Node(fileName, commandOrOutput.getFileSize())
currentDirectory.children[fileName] = file
}
}
return root
}
private const val DIR = "dir"
private fun String.isDirectoryOutput() = this.split(" ").first() == DIR
private fun String.isFileOutput() = this.first().isDigit()
private fun String.isMoveOutCommand() = this == "\$ cd .."
private fun String.isMoveInCommand() = this.contains("\$ cd") && !this.contains("..")
private fun String.getDirectoryName(): String = this.split(" ").last()
fun String.getFileSize() = this.split(" ")[0]
fun String.getFileName() = this.split(" ")[1]
data class Node(
val name: String,
val size: String,
var children: MutableMap<String, Node> = mutableMapOf()
) | 0 | Kotlin | 0 | 0 | 817017369d257cca648974234f1e4137cdcd3138 | 2,474 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/mkuhn/aoc/Day14.kt | mtkuhn | 572,236,871 | false | {"Kotlin": 53161} | package mkuhn.aoc
import mkuhn.aoc.util.Point
import mkuhn.aoc.util.progressBetween
import mkuhn.aoc.util.readInput
fun main() {
val input = readInput("Day14")
println(day14part1(input))
println(day14part2(input))
}
fun day14part1(input: List<String>): Int {
val sandOrigin = Point(500, 0)
val rockPoints = input.parseInputToRockPoints()
return rockPoints.fillSandUntil(sandOrigin) { it == null }.size
}
fun day14part2(input: List<String>): Int {
val sandOrigin = Point(500, 0)
val rockPoints = input.parseInputToRockPoints()
val floorY = rockPoints.maxOf { it.y }+2
rockPoints += (Point(-5000, floorY) to Point(5000, floorY)).segmentToPoints()
return rockPoints.fillSandUntil(sandOrigin) { it == sandOrigin }.size+1
}
fun Set<Point>.fillSandUntil(sandOrigin: Point, goal: (Point?) -> Boolean): List<Point> {
val obstructionHeightMap = mutableMapOf<Int, MutableList<Int>>()
this.forEach { r -> obstructionHeightMap.addPoint(r) }
return generateSequence { sandOrigin }
.map { obstructionHeightMap.dropSandOrNull(it) }
.takeWhile { !goal(it) }
.filterNotNull()
.toList()
}
fun List<String>.parseInputToRockPoints() =
flatMap { line -> line.parseLineToPoints()
.zipWithNext()
.flatMap { it.segmentToPoints() }
}.toMutableSet()
fun String.parseLineToPoints() = split("""\D+""".toRegex()).chunked(2).map { Point(it[0].toInt(), it[1].toInt()) }
fun Pair<Point, Point>.segmentToPoints(): Set<Point> =
(first.x.progressBetween(second.x)).flatMap { xx ->
(first.y.progressBetween(second.y)).map { yy ->
Point(xx, yy)
}
}.toSet()
fun MutableMap<Int, MutableList<Int>>.addPoint(p: Point) {
if(this[p.x] == null) { this[p.x] = mutableListOf(p.y) }
else { this[p.x]?.add(p.y) }
}
fun MutableMap<Int, MutableList<Int>>.dropSandOrNull(sandOrigin: Point): Point? {
val newSand = findSandRestingPoint(sandOrigin)
if(newSand != null) addPoint(newSand)
return newSand
}
fun MutableMap<Int, MutableList<Int>>.findSandRestingPoint(sandOrigin: Point): Point? {
val yIntersect = this[sandOrigin.x]?.filter { it > sandOrigin.y }?.minOrNull()
return when {
yIntersect == null -> null
isOpen(Point(sandOrigin.x-1, yIntersect)) -> findSandRestingPoint(Point(sandOrigin.x-1, yIntersect))
isOpen(Point(sandOrigin.x+1, yIntersect)) -> findSandRestingPoint(Point(sandOrigin.x+1, yIntersect))
else -> Point(sandOrigin.x, yIntersect-1)
}
}
fun MutableMap<Int, MutableList<Int>>.isOpen(p: Point) = this[p.x]?.none { it == p.y }?:true | 0 | Kotlin | 0 | 1 | 89138e33bb269f8e0ef99a4be2c029065b69bc5c | 2,624 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/solutions/Day22MonkeyMap.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import models.Coord2d
import utils.Input
import utils.Solution
// run only this day
fun main() {
Day22MonkeyMap()
}
class Day22MonkeyMap : Solution() {
init {
begin("Day 22 - Monkey Map")
val input = Input.parseLines("/d22_monkey_notes.txt")
// map coord -> isOpenSpace
val map = mutableMapOf<Coord2d, Boolean>()
input.dropLast(2).forEachIndexed { l, line ->
line.forEachIndexed { c, char ->
when (char) {
'.' -> map[Coord2d(l, c)] = true
'#' -> map[Coord2d(l, c)] = false
}
}
}
val steps = """(\d+)|(\S)""".toRegex()
.findAll(input.takeLast(1).first(), 0)
val sol1 = walkPath(map, steps)
output("Password", sol1.toPassword())
val sol2 = "2222"
output("string 2", sol2)
}
private fun walkPath(
map: MutableMap<Coord2d, Boolean>,
steps: Sequence<MatchResult>
): Pair<Coord2d, Direction> {
val curPos = map.entries
.filter { it.key.x == 0 }
.sortedBy { it.key.y }
.first { it.value }.key
var curDir = Direction.RIGHT
val dirVals = Direction.values()
val iter = steps.iterator()
while (iter.hasNext()) {
val next = iter.next().value
// try treating 'next' as a number, fallback to rotation if it fails
try {
curPos.tryStep(curDir, next.toInt(), map)
} catch (_: Exception) {
curDir = when (next) {
"R" -> dirVals[(curDir.ordinal + 1) % dirVals.size]
else -> dirVals[(curDir.ordinal - 1 + dirVals.size) % dirVals.size]
}
}
}
return (curPos + Coord2d(1, 1)) to curDir
}
private fun Coord2d.tryStep(
cDir: Direction,
dist: Int,
map: MutableMap<Coord2d, Boolean>
) {
for (i in 0 until dist) {
when (cDir) {
Direction.RIGHT -> {
map[this.copy(y = y + 1)]?.let {
if (it) y++
else return
} ?: run {
val cWrap = map.entries.filter { it.key.x == x }.minBy { it.key.y }
if (cWrap.value) y = cWrap.key.y
else return
}
}
Direction.LEFT -> {
map[this.copy(y = y - 1)]?.let {
if (it) y--
else return
} ?: run {
val cWrap = map.entries.filter { it.key.x == x }.maxBy { it.key.y }
if (cWrap.value) y = cWrap.key.y
else return
}
}
Direction.UP -> {
map[this.copy(x = x - 1)]?.let {
if (it) x--
else return
} ?: run {
val cWrap = map.entries.filter { it.key.y == y }.maxBy { it.key.x }
if (cWrap.value) x = cWrap.key.x
else return
}
}
Direction.DOWN -> {
map[this.copy(x = x + 1)]?.let {
if (it) x++
else return
} ?: run {
val cWrap = map.entries.filter { it.key.y == y }.minBy { it.key.x }
if (cWrap.value) x = cWrap.key.x
else return
}
}
}
}
}
private fun Pair<Coord2d, Direction>.toPassword(): Int =
(first.x * 1000) + (first.y * 4) + second.ordinal
private enum class Direction {
RIGHT, DOWN, LEFT, UP
}
}
| 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 3,954 | advent-of-code-2022 | MIT License |
src/Day14.kt | MerickBao | 572,842,983 | false | {"Kotlin": 28200} | import kotlin.math.max
import kotlin.math.min
fun main() {
var MAX = 0
fun build(input: List<String>): HashSet<Int> {
val res = HashSet<Int>()
for (s in input) {
val coords = s.split(" -> ")
for (i in coords.indices) {
if (i == 0) continue
val prev = coords[i - 1].split(",")
val now = coords[i].split(",")
val px = prev[0].toInt()
val py = prev[1].toInt()
val nx = now[0].toInt()
val ny = now[1].toInt()
MAX = max(MAX, max(py, ny))
if (px == nx) {
for (y in min(py, ny) until max(py, ny) + 1) {
res.add(px * 100000000 + y)
}
} else {
for (x in min(px, nx) until max(px, nx) + 1) {
res.add(x * 100000000 + py)
}
}
}
}
return res
}
fun check(all: HashSet<Int>, isP2: Boolean, maxY: Int): Boolean {
var x = 500
var y = 0
while (y <= maxY && !all.contains(x * 100000000 + y)) {
if (isP2 && y + 1 >= maxY) {
all.add(x * 100000000 + y)
return true
}
if (!all.contains(x * 100000000 + y + 1)) {
y++
} else if (!all.contains((x - 1) * 100000000 + y + 1)) {
x--
y++
} else if (!all.contains((x + 1) * 100000000 + y + 1)) {
x++
y++
} else {
all.add(x * 100000000 + y)
return true
}
}
return false
}
fun part1(input: List<String>): Int {
val all = build(input)
var ans = 0
while (check(all, false, MAX)) ans++
return ans
}
fun part2(input: List<String>): Int {
val all = build(input)
var ans = 0
while (check(all, true, MAX + 2)) ans++
return ans
}
val input = readInput("Day14")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 70a4a52aa5164f541a8dd544c2e3231436410f4b | 2,174 | aoc-2022-in-kotlin | Apache License 2.0 |
src/aoc_2022/Day04.kt | jakob-lj | 573,335,157 | false | {"Kotlin": 38689} | package aoc_2022
import readInput
fun main() {
val input = readInput("day4_test")
part1(input)
part2(input)
}
fun part1(input: List<String>) {
val data = input.map {
val compartments = it.split(",")
val first = compartments[0].split("-")
val second = compartments[1].split("-")
Pair(Pair(first[0].toInt(), first[1].toInt()), Pair(second[0].toInt(), second[1].toInt()))
}.count {
val first = it.first
val second = it.second
(first.first <= second.first && first.second >= second.second) || (first.first >= second.first && first.second <= second.second)
}
println(data)
}
fun part2(input: List<String>) {
val data = input.map {
val compartments = it.split(",")
val first = compartments[0].split("-")
val second = compartments[1].split("-")
Pair(Pair(first[0].toInt(), first[1].toInt()), Pair(second[0].toInt(), second[1].toInt()))
}.count {
val first = it.first
val second = it.second
first.second <= second.first && first.first >= second.first || second.first <= first.second && second.second >= first.first
}
println(data)
}
| 0 | Kotlin | 0 | 0 | 3a7212dff9ef0644d9dce178e7cc9c3b4992c1ab | 1,195 | advent_of_code | Apache License 2.0 |
src/main/kotlin/year2021/day-21.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2021
import lib.aoc.Day
import lib.aoc.Part
import lib.memoize
import lib.splitLines
import kotlin.math.max
fun main() {
Day(21, 2021, PartA21(), PartB21()).run()
}
open class PartA21 : Part() {
protected class DeterministicDice {
var counter = 0
fun roll(): Int {
val number = 1 + counter % 100
counter++
return number
}
}
protected class Player(var position: Int, var points: Int) {
fun move(dice: DeterministicDice) {
val movement = (0..<3).sumOf { dice.roll() }
position = (position + movement - 1) % 10 + 1
points += position
}
}
protected lateinit var playerA: Player
protected lateinit var playerB: Player
override fun parse(text: String) {
val lines = text.splitLines()
val positionA = lines[0].split(": ")[1].toInt()
val positionB = lines[1].split(": ")[1].toInt()
playerA = Player(positionA, 0)
playerB = Player(positionB, 0)
}
override fun compute(): String {
val dice = DeterministicDice()
val winningPoints = 1000
while (true) {
playerA.move(dice)
if (playerA.points >= winningPoints) {
return (playerB.points * dice.counter).toString()
}
playerB.move(dice)
if (playerB.points >= winningPoints) {
return (playerA.points * dice.counter).toString()
}
}
}
override val exampleAnswer: String
get() = "739785"
}
class PartB21 : PartA21() {
private var doQuantumTurnMemoized = ::doQuantumTurn.memoize()
override fun compute(): String {
val wins = doQuantumTurnMemoized(playerA.position, playerB.position, 0, 0)
return max(wins.first, wins.second).toString()
}
private fun doQuantumTurn(pos1: Int, pos2: Int, points1: Int, points2: Int): Pair<Long, Long> {
val possibilities = mapOf(3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1)
var winsA = 0L
var winsB = 0L
for ((movement, splits) in possibilities) {
val pos = (pos1 + movement - 1) % 10 + 1
val points = points1 + pos
if (points >= 21) {
winsA += splits
continue
}
val (nextWinsB, nextWinsA) = doQuantumTurnMemoized(pos2, pos, points2, points)
winsA += nextWinsA * splits
winsB += nextWinsB * splits
}
return Pair(winsA, winsB)
}
override val exampleAnswer: String
get() = "444356092776315"
}
| 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 2,739 | Advent-Of-Code-Kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximizeScoreAfterNOperations.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <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 dev.shtanko.algorithms.math.gcd
import kotlin.math.max
/**
* 1799. Maximize Score After N Operations
* @see <a href="https://leetcode.com/problems/maximize-score-after-n-operations/">Source</a>
*/
fun interface MaximizeScoreAfterNOperations {
fun maxScore(nums: IntArray): Int
}
/**
* Approach 1: DP with Bitmasking (Recursive)
*/
class MaxScoreDpRecursive : MaximizeScoreAfterNOperations {
override fun maxScore(nums: IntArray): Int {
val memoSize = 1 shl nums.size // 2^(nums array size)
val memo = IntArray(memoSize) { -1 }
return backtrack(nums, 0, 0, memo)
}
private fun backtrack(nums: IntArray, mask: Int, pairsPicked: Int, memo: IntArray): Int {
// If we have picked all the numbers from 'nums' array, we can't get more score.
if (2 * pairsPicked == nums.size) {
return 0
}
// If we already solved this sub-problem then return the stored result.
if (memo[mask] != -1) {
return memo[mask]
}
var maxScore = 0
// Iterate on 'nums' array to pick the first and second number of the pair.
for (firstIndex in nums.indices) {
for (secondIndex in firstIndex + 1 until nums.size) {
// If the numbers are same, or already picked, then we move to next number.
if (mask shr firstIndex and 1 == 1 || mask shr secondIndex and 1 == 1) {
continue
}
// Both numbers are marked as picked in this new mask.
val newMask = mask or (1 shl firstIndex) or (1 shl secondIndex)
// Calculate score of current pair of numbers, and the remaining array.
val currScore: Int = (pairsPicked + 1) * gcd(nums[firstIndex], nums[secondIndex])
val remainingScore = backtrack(nums, newMask, pairsPicked + 1, memo)
// Store the maximum score.
maxScore = max(maxScore, currScore + remainingScore)
// We will use old mask in loop's next iteration,
// means we discarded the picked number and backtracked.
}
}
// Store the result of the current sub-problem.
memo[mask] = maxScore
return maxScore
}
}
/**
* Approach 2: DP with Bitmasking (Iterative)
*/
class MaxScoreDpIterative : MaximizeScoreAfterNOperations {
override fun maxScore(nums: IntArray): Int {
val maxStates = 1 shl nums.size // 2^(nums array size)
val finalMask = maxStates - 1
// 'dp[i]' stores max score we can get after picking remaining numbers represented by 'i'.
val dp = IntArray(maxStates)
// Iterate on all possible states one-by-one.
for (state in finalMask downTo 0) {
// If we have picked all numbers, we know we can't get more score as no number is remaining.
if (state == finalMask) {
dp[state] = 0
continue
}
val numbersTaken = Integer.bitCount(state)
val pairsFormed = numbersTaken / 2
// States representing even numbers are taken are only valid.
if (numbersTaken % 2 != 0) {
continue
}
// We have picked 'pairsFormed' pairs, we try all combinations of one more pair now.
// We iterate on two numbers using two nested for loops.
for (firstIndex in nums.indices) {
for (secondIndex in firstIndex + 1 until nums.size) {
// We only choose those numbers which were not already picked.
if (state shr firstIndex and 1 == 1 || state shr secondIndex and 1 == 1) {
continue
}
val currentScore = (pairsFormed + 1) * gcd(nums[firstIndex], nums[secondIndex])
val stateAfterPickingCurrPair = state or (1 shl firstIndex) or (1 shl secondIndex)
val remainingScore = dp[stateAfterPickingCurrPair]
dp[state] = Math.max(dp[state], currentScore + remainingScore)
}
}
}
// Returning score we get from 'n' remaining numbers of array.
return dp[0]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,922 | kotlab | Apache License 2.0 |
src/Day04.kt | roxanapirlea | 572,665,040 | false | {"Kotlin": 27613} | fun main() {
fun String.getAssignment(): Pair<Int, Int> =
substringBefore("-").toInt() to substringAfter("-").toInt()
fun isAssignmentContainingOther(assignment1: Pair<Int, Int>, assignment2: Pair<Int, Int>): Boolean {
if (assignment1.first <= assignment2.first && assignment1.second >= assignment2.second) return true
if (assignment2.first <= assignment1.first && assignment2.second >= assignment1.second) return true
return false
}
fun areSeparated(assignment1: Pair<Int, Int>, assignment2: Pair<Int, Int>): Boolean {
if (assignment1.first > assignment2.second || assignment1.second < assignment2.first) return true
return false
}
fun part1(input: List<String>): Int {
return input.map {
isAssignmentContainingOther(
it.substringBefore(",").getAssignment(),
it.substringAfter(",").getAssignment()
)
}.count { it }
}
fun part2(input: List<String>): Int {
return input.map {
areSeparated(
it.substringBefore(",").getAssignment(),
it.substringAfter(",").getAssignment()
)
}.count { !it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 6c4ae6a70678ca361404edabd1e7d1ed11accf32 | 1,494 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | bin-wang | 572,801,360 | false | {"Kotlin": 19395} | fun main() {
infix fun IntRange.fullyContains(other: IntRange) = first <= other.first && last >= other.last
infix fun IntRange.overlaps(other: IntRange) = !(last < other.first || first > other.last)
fun parseLine(line: String): List<IntRange> {
return line.split(",").map {
val (first, last) = it.split("-")
first.toInt()..last.toInt()
}
}
fun part1(input: List<String>): Int {
return input.map(::parseLine).count { (r1, r2) ->
r1 fullyContains r2 || r2 fullyContains r1
}
}
fun part2(input: List<String>): Int {
return input.map(::parseLine).count { (r1, r2) ->
r1 overlaps r2
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dca2c4915594a4b4ca2791843b53b71fd068fe28 | 915 | aoc22-kt | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year18/Day24.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year18
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.doubleLines
import com.grappenmaker.aoc.splitInts
import com.grappenmaker.aoc.takeUntil
fun PuzzleSet.day24() = puzzle {
data class Group(
val units: Int,
val hp: Int,
val immunities: Set<String>,
val weaknesses: Set<String>,
val damage: Int,
val damageType: String,
val initiative: Int
)
fun Group.effectivePower() = units * damage
fun Group.damageTo(other: Group) = when (damageType) {
in other.immunities -> 0
in other.weaknesses -> effectivePower() * 2
else -> effectivePower()
}
fun String.parseGroup(): Group {
val words = split(' ')
val (units, hp, damage, initiative) = splitInts()
val detailParts = if ('(' !in this) emptyMap() else {
val details = substringAfter('(').substringBefore(')')
details.split("; ").associate {
val (property, types) = it.split(" to ")
property to types.split(", ").toSet()
}
}
return Group(
units = units,
hp = hp,
immunities = detailParts["immune"] ?: emptySet(),
weaknesses = detailParts["weak"] ?: emptySet(),
damage = damage,
damageType = words[words.indexOf("damage") - 1],
initiative = initiative
)
}
val ordering = compareByDescending<Group> { it.effectivePower() }.thenByDescending { it.initiative }
data class GameState(val immuneSystem: List<Group>, val infection: List<Group>)
fun GameState.isOver() = immuneSystem.isEmpty() || infection.isEmpty()
fun GameState.remainingUnits() = (immuneSystem + infection).sumOf { it.units }
fun GameState.advance(): GameState {
fun List<Group>.selectTargets(enemy: List<Group>): Map<Group, Group?> {
val enemiesLeft = enemy.sortedWith(ordering).toMutableList()
return sortedWith(ordering).associateWith { ourGroup ->
enemiesLeft
.maxByOrNull { ourGroup.damageTo(it) }
?.takeIf { ourGroup.damageTo(it) > 0 }
?.also { enemiesLeft -= it }
}
}
val newImmuneSystem = immuneSystem.toMutableList()
val newInfection = infection.toMutableList()
fun IntRange.asIDs(hostile: Boolean) = map { it to hostile }
fun Pair<Int, Boolean>.army() = if (second) newInfection else newImmuneSystem
fun Pair<Int, Boolean>.currentGroup() = army()[first]
fun Pair<Int, Boolean>.replace(new: Group) {
val army = army()
army.removeAt(first)
army.add(first, new)
}
fun Group.asID(hostile: Boolean) = (if (hostile) newInfection else newImmuneSystem).indexOf(this) to hostile
fun Map<Group, Group?>.asIDTargets(hostile: Boolean) = toList().associate { (attacker, target) ->
attacker.asID(hostile) to target?.asID(!hostile)
}
val immuneTargets = immuneSystem.selectTargets(infection).asIDTargets(false)
val infectionTargets = infection.selectTargets(immuneSystem).asIDTargets(true)
val ids = (newImmuneSystem.indices.asIDs(false) + newInfection.indices.asIDs(true))
.sortedByDescending { it.currentGroup().initiative }
for (id in ids) {
val group = id.currentGroup()
if (group.units <= 0) continue
val target = (if (id.second) infectionTargets else immuneTargets)[id] ?: continue
val targetGroup = target.currentGroup()
val unitsLost = group.damageTo(targetGroup) / targetGroup.hp
target.replace(targetGroup.copy(units = targetGroup.units - unitsLost))
}
fun List<Group>.filterAlive() = filter { it.units > 0 }
return GameState(newImmuneSystem.filterAlive(), newInfection.filterAlive())
}
fun GameState.evaluate() = generateSequence(this) { it.advance() }
.takeUntil { !it.isOver() }.windowed(2)
.takeWhile { (a, b) -> a != b }
.map { (_, a) -> a }.last()
fun GameState.won() = immuneSystem.isNotEmpty() && infection.isEmpty()
val (initialImmune, initialInfection) = input.doubleLines().map { it.lines().drop(1).map(String::parseGroup) }
partOne = GameState(initialImmune, initialInfection).evaluate().remainingUnits().s()
fun List<Group>.boost(amount: Int) = map { it.copy(damage = it.damage + amount) }
fun evaluateWithBoost(amount: Int) = GameState(initialImmune.boost(amount), initialInfection).evaluate()
var min = 0
var max = 50
while (min + 1 < max) {
val pivot = (min + max) / 2
if (evaluateWithBoost(pivot).won()) max = pivot else min = pivot
}
partTwo = evaluateWithBoost(max).remainingUnits().s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 4,899 | advent-of-code | The Unlicense |
2015/18/kotlin/b.kt | shrivatsas | 583,681,989 | false | {"Kotlin": 17998, "Python": 9402, "Racket": 4669, "Clojure": 2953} | import java.io.File
fun updateStuckLights(d: List<CharArray>): List<CharArray> {
d[0][0] = '#'
d[0][d[0].size - 1] = '#'
d[d.size - 1][0] = '#'
d[d.size - 1][d[0].size - 1] = '#'
return d
}
fun isOn(d: List<CharArray>, i: Int, j: Int): Boolean {
if (i < 0 || i > d.size - 1) {
return false
}
if (j < 0 || j > d[0].size - 1) {
return false
}
return d[i][j] == '#'
}
fun neighbourCount(d: List<CharArray>, i: Int, j: Int): Pair<Int, Int> {
var neighbours = MutableList<Boolean>(8) { false }
neighbours[0] = isOn(d, i-1, j-1)
neighbours[1] = isOn(d, i, j-1)
neighbours[2] = isOn(d, i+1, j-1)
neighbours[3] = isOn(d, i+1, j)
neighbours[4] = isOn(d, i+1, j+1)
neighbours[5] = isOn(d, i, j+1)
neighbours[6] = isOn(d, i-1, j+1)
neighbours[7] = isOn(d, i-1, j)
return Pair<Int, Int>(neighbours.count({ it }), neighbours.count({ !it }))
}
fun nextState(disp: List<CharArray>): List<CharArray> {
val d = MutableList<CharArray>(disp.size) { CharArray(disp.size) }
for (i in disp.indices) {
for (j in disp[0].indices) {
// A # means "on", and a . means "off".
// A light which is on stays on when 2 or 3 neighbors are on, and turns off otherwise.
// A light which is off turns on if exactly 3 neighbors are on, and stays off otherwise.
val (on, off) = neighbourCount(disp, i, j)
val c = disp[i][j]
if (c == '#') {
if (on == 2 || on == 3) {
d[i][j] = '#'
} else {
d[i][j] = '.'
}
} else {
if (on == 3) {
d[i][j] = '#'
} else {
d[i][j] = '.'
}
}
}
}
return d
}
fun main() {
var d: List<CharArray> = File("../18.input").readLines().map({ it.toCharArray() })
val count = 100
for (i in 1..count) {
d = nextState(updateStuckLights(d))
if (i == count) {
println("----")
d = updateStuckLights(d)
d.forEach { println(it) }
println(d.map({ it.count({ it == '#' }) }).sum())
}
}
} | 0 | Kotlin | 0 | 1 | 529a72ff55f1d90af97f8e83b6c93a05afccb44c | 2,002 | AoC | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/KClosestPoints.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.PriorityQueue
fun interface KClosestPointsStrategy {
operator fun invoke(points: Array<IntArray>, k: Int): Array<IntArray>
fun IntArray.getDistance(): Int {
return this[0] * this[0] + this[1] * this[1]
}
}
class KClosestPointsQueue : KClosestPointsStrategy {
override operator fun invoke(points: Array<IntArray>, k: Int): Array<IntArray> {
var n = k
val heap = PriorityQueue(Comparator<IntArray> { left, right -> right.getDistance() - left.getDistance() })
for (point in points) {
heap.add(point)
if (heap.size > n) heap.poll()
}
val result = Array(n) { IntArray(2) }
while (n > 0) result[--n] = heap.poll()
return result
}
}
class KClosestPointsSort : KClosestPointsStrategy {
override operator fun invoke(points: Array<IntArray>, k: Int): Array<IntArray> {
val n = points.size
val dists = IntArray(n)
for (i in 0 until n) dists[i] = points[i].getDistance()
dists.sort()
val distK = dists[k - 1]
val ans = Array(k) { IntArray(2) }
var t = 0
for (i in 0 until n) if (points[i].getDistance() <= distK) ans[t++] = points[i]
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,888 | kotlab | Apache License 2.0 |
2022/src/main/kotlin/day16.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parse
import utils.Parser
import utils.Solution
import utils.mapItems
fun main() {
Day16.run()
}
object Day16 : Solution<List<Day16.Valve>>() {
override val name = "day16"
override val parser = Parser.lines
.mapItems { it.replace("tunnel leads to valve", "tunnels lead to valves") }
.mapItems(::parseValve)
@Parse("Valve {name} has flow rate={flowRate}; tunnels lead to valves {r ', ' out}")
data class Valve(val name: String, val flowRate: Int, val out: List<String>)
data class CacheKeyP1(val releasedPressure: Int, val curTime: Int, val curNode: String, val openValves: String)
private val cachep1 = mutableMapOf<CacheKeyP1, Int>()
fun getBestFlowRateP1(releasedPressure: Int, curTime: Int, curNode: String, openValves: Set<String>, valves: Map<String, Valve>): Int {
val flowRate = openValves.map { valves[it]!! }.sumOf { it.flowRate }
val newReleasedPressure = releasedPressure + flowRate
if (curTime == 30) {
return newReleasedPressure
}
// if all valves are open, just advance time
if (openValves.size == valves.size) {
return newReleasedPressure + (30 - curTime) * flowRate
}
val cacheKey = CacheKeyP1(releasedPressure, curTime, curNode, openValves.sorted().joinToString(","))
val cachedAnsw = cachep1[cacheKey]
if (cachedAnsw != null) {
return cachedAnsw
}
val curValve = valves[curNode]!!
// try opening current valve if it gives any flowrate
val bestAfterOpen = if (curValve.flowRate > 0 && curValve.name !in openValves) {
getBestFlowRateP1(newReleasedPressure, curTime + 1, curNode, openValves + curValve.name, valves)
} else {
Integer.MIN_VALUE // don't consider opening
}
val bestAfterVisit = curValve.out.map { valves[it]!! }.maxOf {
getBestFlowRateP1(newReleasedPressure, curTime + 1, it.name, openValves, valves)
}
val best = maxOf(bestAfterOpen, bestAfterVisit)
cachep1[cacheKey] = best
return best
}
data class CacheKeyP2(val releasedPressure: Int, val curTime: Int, val myNode: String, val elephantNode: String, val openValves: String)
// private val cachep2 = mutableMapOf<CacheKeyP2, Int>()
sealed class Next {
object Open : Next()
data class Move(val to: String) : Next()
}
var bestOpenTime = Integer.MAX_VALUE
var bestReleasedPressure = IntArray(40) { Integer.MIN_VALUE }
fun getBestFlowRateP2(releasedPressure: Int, curTime: Int, myNode: String, ellyNode: String, openValves: Set<String>, valves: Map<String, Valve>, root: Boolean = false): Int {
val flowRate = openValves.map { valves[it]!! }.sumOf { it.flowRate }
val newReleasedPressure = releasedPressure + flowRate
if (curTime == 26) {
return newReleasedPressure
}
// if all valves are open, just advance time
// if (openValves.size == valves.values.filter { it.flowRate > 0 }.size) {
// if (curTime < bestOpenTime) {
// println("Found best open time at $curTime")
// }
// bestOpenTime = minOf(curTime, bestOpenTime)
// bestReleasedPressure[curTime] = maxOf(bestReleasedPressure[curTime], newReleasedPressure)
// return newReleasedPressure + (26 - curTime) * flowRate
// } else if (curTime > bestOpenTime) {
// if (bestReleasedPressure[bestOpenTime] > newReleasedPressure) {
// // no point
// return Integer.MIN_VALUE
// }
// }
// val cacheKey = CacheKeyP2(releasedPressure, curTime, myNode, ellyNode, openValves.sorted().joinToString(","))
// val cachedAnsw = cachep2[cacheKey]
// if (cachedAnsw != null) {
// return cachedAnsw
// }
val curMyValve = valves[myNode]!!
val curEllyValve = valves[ellyNode]!!
// val myOpts = if (curMyValve.flowRate > 0 && curMyValve.name !in openValves) { listOf(Next.Open) } else curMyValve.out.map { Next.Move(it) }
// val ellyOpts = if (curEllyValve.flowRate > 0 && curEllyValve.name !in openValves) { listOf(Next.Open) } else curEllyValve.out.map { Next.Move(it) }
val myOpts = listOf(Next.Open.takeIf { curMyValve.flowRate > 0 && curMyValve.name !in openValves }) + curMyValve.out.map { Next.Move(it) }
val ellyOpts = listOf(Next.Open.takeIf { curEllyValve.flowRate > 0 && curEllyValve.name !in openValves }) + curEllyValve.out.map { Next.Move(it) }
val opts = myOpts.filterNotNull().flatMap { myOpt ->
ellyOpts.filterNotNull().map { myOpt to it }
}
val best = opts.mapIndexed { i, (myNext, ellyNext) ->
val myNextNode = if (myNext is Next.Move) myNext.to else null
val ellyNextNode = if (ellyNext is Next.Move) ellyNext.to else null
val newOpenValves = openValves + listOfNotNull(
curMyValve.name.takeIf { myNextNode == null },
curEllyValve.name.takeIf { ellyNextNode == null },
)
if (root) {
println("$i / ${opts.size}")
}
getBestFlowRateP2(newReleasedPressure, curTime + 1, myNextNode ?: myNode, ellyNextNode ?: ellyNode, newOpenValves, valves)
}.max()
// cachep2[cacheKey] = best
return best
}
override fun part1(input: List<Valve>): Int {
return 0
// cachep1.clear()
// val valves = input.associateBy { it.name }
// return getBestFlowRateP1(0, 1, "AA", emptySet(), valves)
}
override fun part2(input: List<Valve>): Any? {
// cachep2.clear()
bestOpenTime = Integer.MAX_VALUE
val valves = input.associateBy { it.name }
return getBestFlowRateP2(0, 1, "AA", "AA", emptySet(), valves, root = true)
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 5,488 | aoc_kotlin | MIT License |
src/main/kotlin/g0701_0800/s0764_largest_plus_sign/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0701_0800.s0764_largest_plus_sign
// #Medium #Array #Dynamic_Programming #2023_03_08_Time_415_ms_(100.00%)_Space_49.9_MB_(100.00%)
class Solution {
fun orderOfLargestPlusSign(n: Int, mines: Array<IntArray>): Int {
val mat = Array(n) { BooleanArray(n) }
for (pos in mines) {
mat[pos[0]][pos[1]] = true
}
val left = Array(n) { IntArray(n) }
val right = Array(n) { IntArray(n) }
val up = Array(n) { IntArray(n) }
val down = Array(n) { IntArray(n) }
var ans = 0
// For Left and Up only
for (i in 0 until n) {
for (j in 0 until n) {
val i1 = if (j == 0) 0 else left[i][j - 1]
left[i][j] = if (mat[i][j]) 0 else 1 + i1
val i2 = if (i == 0) 0 else up[i - 1][j]
up[i][j] = if (mat[i][j]) 0 else 1 + i2
}
}
// For Right and Down and simoultaneously get answer
for (i in n - 1 downTo 0) {
for (j in n - 1 downTo 0) {
val i1 = if (j == n - 1) 0 else right[i][j + 1]
right[i][j] = if (mat[i][j]) 0 else 1 + i1
val i2 = if (i == n - 1) 0 else down[i + 1][j]
down[i][j] = if (mat[i][j]) 0 else 1 + i2
val x = left[i][j].coerceAtMost(up[i][j]).coerceAtMost(
right[i][j].coerceAtMost(down[i][j])
)
ans = ans.coerceAtLeast(x)
}
}
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,523 | LeetCode-in-Kotlin | MIT License |
aoc/src/ColorGame.kt | aragos | 726,211,893 | false | {"Kotlin": 16232} | import java.io.File
fun main() {
// problem1()
problem2()
}
private fun problem2() {
var powerSum = 0
val colors = listOf("red", "green", "blue")
File("inputs/colorGame.txt").forEachLine { line ->
val split = line.split(":")
val maxes = colors.associateWith { 0 }.toMutableMap()
split[1].split(";").forEach {
it.split(",").forEach { color ->
for ((name, max) in maxes) {
if (color.contains(name)) {
val count = Regex("\\d+").find(color)?.value?.toInt() ?: 0
if (count > max) {
maxes[name] = count
}
}
}
}
}
powerSum += maxes.values.reduce { acc, value -> acc * value }
}
println(powerSum)
}
private fun problem1() {
val colors = mapOf("red" to 12, "green" to 13, "blue" to 14)
var validGamesSum = 0
File("inputs/colorGame.txt").forEachLine { line ->
val split = line.split(":")
val gameId = split[0].substring(5).toInt()
split[1].split(";").forEach {
it.split(",").forEach { color ->
for ((name, max) in colors) {
if (color.contains(name)) {
if ((Regex("\\d+").find(color)?.value?.toInt() ?: 0) > max) {
return@forEachLine
}
}
}
}
}
validGamesSum += gameId
}
println(validGamesSum)
}
| 0 | Kotlin | 0 | 0 | 7bca0a857ea42d89435adc658c0ff55207ca374a | 1,334 | aoc2023 | Apache License 2.0 |
src/main/kotlin/dp/EditDist.kt | yx-z | 106,589,674 | false | null | import util.get
import util.min
import util.set
import util.toCharOneArray
// Edit Distance between 2 Strings
// min # of add/remove/replace modifications to match 2 Strings
fun main(args: Array<String>) {
// test strings
val s1 = "algorithm"
val s2 = "altruistic"
// println(editDistRecursion(s1, s2))
println(editDistDP(s1, s2))
println(s1 editDistRedo s2)
}
// Recursive Implementation
fun editDistRecursion(s1: String, s2: String): Int {
if (s1.isEmpty()) {
return s2.length
}
if (s2.isEmpty()) {
return s1.length
}
return if (s1[0] == s2[0]) {
editDistRecursion(s1.substring(1), s2.substring(1))
} else {
1 + min(editDistRecursion(s1.substring(1), s2),
editDistRecursion(s1, s2.substring(1)),
editDistRecursion(s1.substring(1), s2.substring(1)))
}
}
// DP Implementation
fun editDistDP(s1: String, s2: String): Int {
if (s1.isEmpty()) {
return s2.length
}
if (s2.isEmpty()) {
return s1.length
}
val l1 = s1.length
val l2 = s2.length
// dp[i][j] = edit distance between s1[1..i] and s2[1..j]
// *here strings are one-indexed
// dp[i][j] = i, if j == 0, i.e. insert i characters
// = j, if i == 0
// = min(dp[i - 1][j], dp[j - 1][i]) + 1, if s1[i] != s2[j]
// = min(dp[i - 1][j] + 1, dp[j - 1][i] + 1, dp[i - 1][j - 1]), if s1[i] == s2[j]
// *this case can be optimized to just dp[i - 1][j - 1] in that if two characters are
// the same, we can leave them unchanged
val dp = Array(l1 + 1) { Array(l2 + 1) { 0 } }
// base case for empty strings
for (i in 0..l1) {
dp[i][0] = i
}
for (i in 0..l2) {
dp[0][i] = i
}
for (i1 in 1..l1) {
for (i2 in 1..l2) {
dp[i1][i2] = if (s1[i1 - 1] == s2[i2 - 1]) {
dp[i1 - 1][i2 - 1]
} else {
1 + min(dp[i1 - 1][i2], dp[i1][i2 - 1], dp[i1 - 1][i2 - 1])
}
}
}
return dp[l1][l2]
}
infix fun String.editDistRedo(that: String): Int {
val A = this.toCharOneArray()
val m = A.size
val B = that.toCharOneArray()
val n = B.size
// dp[i, j]: edit dist between A[0..i], B[0..j]
// memoization structure: 2d arr dp[0..m, 0..n]
val dp = Array(m + 1) { Array(n + 1) { 0 } }
// space: O(mn)
// base case:
// dp[0, j] = j
for (j in 0..n) {
dp[0, j] = j
}
// dp[i, 0] = i
for (i in 0..m) {
dp[i, 0] = i
}
// recursive case:
// dp[i, j] = min { dp[i - 1, j] + 1,
// dp[i, j - 1] + 1,
// dp[i - 1, j - 1] + A[i] != B[j] }
// dependency: dp[i, j] depends on dp[i - 1, j], dp[i, j - 1], and dp[i - 1,j - 1]
// that is entries above, to the left, and to the upper-left
// eval order: outer loop for i increasing from 1 to m
for (i in 1..m) {
// inner loop for j increasing from 1 to n
for (j in 1..n) {
dp[i, j] = min(
dp[i - 1, j] + 1,
dp[i, j - 1] + 1,
dp[i - 1, j - 1] + if (A[i] == B[j]) 0 else 1)
}
}
// time: O(mn)
// we want the edit dist between A[1..m] and B[1..n]
return dp[m, n]
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,961 | AlgoKt | MIT License |
src/main/kotlin/day18/Code.kt | fcolasuonno | 317,324,330 | false | null | package day18
import isDebug
import java.io.File
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val parsed = parse(input)
part1(parsed)
part2(parsed)
}
fun parse(input: List<String>) = input.map { it.replace(" ", "") }
fun part1(input: List<String>) {
val res = input.sumOf { it.solve1(0).first }
println("Part 1 = $res")
}
fun String.solve1(start: Int): Pair<Long, Int> {
var (acc, current) = if (this[start] == '(') solve1(start + 1) else this[start].asLong() to (start + 1)
do {
val op: ((Long, Long) -> Long) = if (this[current++] == '+') Long::plus else Long::times
val next = if (this[current] == '(') solve1(current + 1) else this[current].asLong() to current + 1
acc = op(acc, next.first)
current = next.second
} while (current < length && get(current) != ')')
return acc to (current + 1)
}
private fun Char.asLong() = (this - '0').toLong()
fun part2(input: List<String>) {
val res = input.sumOf { it.solve2(0).first }
println("Part 2 = $res")
}
fun String.solve2(start: Int): Pair<Long, Int> {
var (acc, current) = if (this[start] == '(') solve2(start + 1) else this[start].asLong() to (start + 1)
val mult = mutableListOf<Long>()
do {
val op: ((Long, Long) -> Long) = if (this[current++] == '+') Long::plus else { a, b -> b.also { mult.add(a) } }
val next = if (this[current] == '(') solve2(current + 1) else this[current].asLong() to current + 1
acc = op(acc, next.first)
current = next.second
} while (current < length && get(current) != ')')
acc = mult.fold(acc) { a, l -> a * l }
return acc to (current + 1)
} | 0 | Kotlin | 0 | 0 | e7408e9d513315ea3b48dbcd31209d3dc068462d | 1,827 | AOC2020 | MIT License |
src/main/kotlin/days/Day4Data.kt | yigitozgumus | 572,855,908 | false | {"Kotlin": 26037} | package days
import utils.SolutionData
fun main() = with(Day4Data()) {
solvePart1()
solvePart2()
}
class Day4Data : SolutionData(inputFile = "inputs/day4.txt") {
val part1Data = rawData.map { it.split(",").map { it.split("-").map { it.toInt() } } }
fun doesListsContainEachOther(first: List<Int>, second: List<Int>): Boolean {
return first.first() <= second.first() && first.last() >= second.last() ||
second.first() <= first.first() && second.last() >= first.last()
}
fun doesListBoundariesOverlap(first: List<Int>, second: List<Int>): Boolean {
return doesListsContainEachOther(first, second) ||
(first.last() >= second.first() && first.first() <= second.first() && second.last() >= first.last() ||
first.first() >= second.first() && first.last() >= second.last() && second.last() >= first.first())
}
}
fun Day4Data.solvePart1() {
part1Data.count { doesListsContainEachOther(it.first(), it.last()) }.also { println(it) }
}
fun Day4Data.solvePart2() {
part1Data.count { doesListBoundariesOverlap(it.first(), it.last()) }.also { println(it) }
}
| 0 | Kotlin | 0 | 0 | 9a3654b6d1d455aed49d018d9aa02d37c57c8946 | 1,077 | AdventOfCode2022 | MIT License |
src/main/kotlin/Day001.kt | ruffCode | 398,923,968 | false | null | object Day001 {
private val input = PuzzleInput("day001.txt").readLines().map { it.toInt() }
internal fun partOne(input: List<Int>): Int {
var result = 0
outer@ for (i in input) {
for (ii in input) {
if (i + ii == 2020) {
result = i * ii
break@outer
}
}
}
return result
}
internal fun partTwo(input: List<Int>): Int {
var result = 0
outer@ for (i in input) {
for (ii in input) {
for (iii in input) {
if (i + ii + iii == 2020) {
result = i * ii * iii
break@outer
}
}
}
}
return result
}
internal fun partOneBetter(numbers: List<Int>): Int? {
val pair = numbers.findPairOfSum(2020)
return pair?.let { (x, y) -> x * y }
}
internal fun partTwoBetter(numbers: List<Int>): Int? {
val triple = numbers.findTripleOfSum(2020)
return triple?.let { (x, y, z) -> x * y * z }
}
private fun List<Int>.findTripleOfSum(sum: Int): Triple<Int, Int, Int>? =
firstNotNullOfOrNull { x ->
findPairOfSum(sum - x)?.let {
Triple(x, it.first, it.second)
}
}
private fun List<Int>.findPairOfSum(
sum: Int,
): Pair<Int, Int>? {
val complements = associateBy { sum - it }
return firstNotNullOfOrNull { number ->
complements[number]?.let {
Pair(number, it)
}
}
}
@JvmStatic
fun main(args: Array<String>) {
println(partOne(input))
println(partOneBetter(input))
println(partTwo(input))
println(partTwoBetter(input))
}
}
| 0 | Kotlin | 0 | 0 | 477510cd67dac9653fc61d6b3cb294ac424d2244 | 1,857 | advent-of-code-2020-kt | MIT License |
src/Day07.kt | undermark5 | 574,819,802 | false | {"Kotlin": 67472} | import java.math.BigInteger
sealed interface TerminalLine {
sealed class Command : TerminalLine {
class CdCommand(val arg: String) : Command()
object LsCommand : Command()
}
sealed class Listing(val name: String) : TerminalLine {
abstract val size: BigInteger
class FileListing(override val size: BigInteger, name: String) : Listing(name)
class DirListing(name: String) : Listing(name) {
var parent: DirListing? = null
val contents: MutableList<Listing> = mutableListOf()
override val size get() = contents.sumOf { it.size }
}
}
}
fun main() {
fun part1(input: List<String>): BigInteger {
val mapped: List<TerminalLine> = input.map {
if (it.startsWith("$ cd")) {
TerminalLine.Command.CdCommand(it.split(" ").last())
} else if (it.startsWith("$ ls")) {
TerminalLine.Command.LsCommand
} else {
if (it.startsWith("dir")) {
TerminalLine.Listing.DirListing(it.split(" ")[1])
} else {
val data = it.split(" ")
TerminalLine.Listing.FileListing(data[0].toBigInteger(), data[1])
}
}
}
val dirs = mutableMapOf<String, TerminalLine.Listing.DirListing>("/" to TerminalLine.Listing.DirListing("/"))
var currentDir = dirs["/"]
mapped.forEach {
when (it) {
is TerminalLine.Command.CdCommand -> {
if (it.arg != "..") {
if (it.arg == "/") {
currentDir = dirs["/"]
} else {
val dirName = it.arg
currentDir =
currentDir?.contents?.filterIsInstance(TerminalLine.Listing.DirListing::class.java)
?.firstOrNull { it.name == dirName }
}
} else {
currentDir = currentDir?.parent
}
}
TerminalLine.Command.LsCommand -> {
// dirs[currentDir] = TerminalLine.Listing.DirListing(currentDir)
}
is TerminalLine.Listing.DirListing -> {
currentDir?.contents?.add(it)
it.parent = currentDir
}
is TerminalLine.Listing.FileListing -> {
currentDir?.contents?.add(it)
}
}
}
val root = dirs["/"]
val dirListings = root?.dirs()
return dirListings?.map { it.size }?.filter { it <= 100000.toBigInteger() }?.sumOf { it } ?: BigInteger.ZERO
}
fun part2(input: List<String>): BigInteger {
val mapped: List<TerminalLine> = input.map {
if (it.startsWith("$ cd")) {
TerminalLine.Command.CdCommand(it.split(" ").last())
} else if (it.startsWith("$ ls")) {
TerminalLine.Command.LsCommand
} else {
if (it.startsWith("dir")) {
TerminalLine.Listing.DirListing(it.split(" ")[1])
} else {
val data = it.split(" ")
TerminalLine.Listing.FileListing(data[0].toBigInteger(), data[1])
}
}
}
val dirs = mutableMapOf<String, TerminalLine.Listing.DirListing>("/" to TerminalLine.Listing.DirListing("/"))
var currentDir = dirs["/"]
mapped.forEach {
when (it) {
is TerminalLine.Command.CdCommand -> {
if (it.arg != "..") {
if (it.arg == "/") {
currentDir = dirs["/"]
} else {
val dirName = it.arg
currentDir =
currentDir?.contents?.filterIsInstance(TerminalLine.Listing.DirListing::class.java)
?.firstOrNull { it.name == dirName }
}
} else {
currentDir = currentDir?.parent
}
}
TerminalLine.Command.LsCommand -> {
// dirs[currentDir] = TerminalLine.Listing.DirListing(currentDir)
}
is TerminalLine.Listing.DirListing -> {
currentDir?.contents?.add(it)
it.parent = currentDir
}
is TerminalLine.Listing.FileListing -> {
currentDir?.contents?.add(it)
}
}
}
val root = dirs["/"]
val dirListings: List<TerminalLine.Listing.DirListing>? = root?.dirs()
val usedSpace = root!!.size
val freeSpace = (70000000).toBigInteger() - usedSpace
val spaceRequired: BigInteger = 30000000.toBigInteger() - freeSpace
return dirListings?.map { it.size }?.filter { it >= spaceRequired }?.min() ?: BigInteger.ZERO
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
// println(part1(testInput))
check(part1(testInput) == 95437L.toBigInteger())
// println(part2(testInput))
// check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private fun TerminalLine.Listing.DirListing.dirs(): List<TerminalLine.Listing.DirListing> {
return listOf(this) + this.contents.filterIsInstance<TerminalLine.Listing.DirListing>().flatMap { it.dirs() }
}
| 0 | Kotlin | 0 | 0 | e9cf715b922db05e1929f781dc29cf0c7fb62170 | 5,755 | AoC_2022_Kotlin | Apache License 2.0 |
src/Day02.kt | HenryCadogan | 574,509,648 | false | {"Kotlin": 12228} | fun main() {
val input = readInput("Day02")
/*
A | X -> Rock
B | Y -> Paper
C | Z -> Scissors
*/
fun part1(input: List<String>): Int {
return input.sumOf {
val myMove = it.takeLast(1)[0]
val theirMove = it.take(1)[0]
val shapePoints = shapePoint(myMove)
val rpsPoints = calculateRPSWin(myMove, theirMove)
//println("Evaluating $myMove VS $theirMove = ${shapePoints + rpsPoints} ($shapePoints + $rpsPoints)")
shapePoints + rpsPoints
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val theirMove = it.take(1)[0]
val outcome = it.takeLast(1)[0]
val myMove = calculateMove(theirMove, outcome)
val shapePoint = shapePoint(myMove)
val rpsPoints = calculateRPSWin(myMove, theirMove)
shapePoint + rpsPoints
}
}
val testInput = """
A Y
B X
C Z
""".trimIndent()
check(part2(testInput.lines()) == 12)
println(part1(input))
println(part2(input))
}
private fun shapePoint(move: Char): Int = when (move) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> error("Unknown Move $move")
}
/*
X -> Lose
Y -> Draw
Z -> Win
A | X -> Rock
B | Y -> Paper
C | Z -> Scissors
*/
private fun calculateMove(theirMove: Char, outcomeNeeded: Char): Char{
return when (theirMove) {
'A' -> when (outcomeNeeded) {
'X' -> 'Z'
'Y' -> 'X'
'Z' -> 'Y'
else -> error("Unknown move $outcomeNeeded")
}
'B' -> when (outcomeNeeded) {
'X' -> 'X'
'Y' -> 'Y'
'Z' -> 'Z'
else -> error("Unknown move $outcomeNeeded")
}
'C' -> when (outcomeNeeded) {
'X' -> 'Y'
'Y' -> 'Z'
'Z' -> 'X'
else -> error("Unknown move $outcomeNeeded")
}
else -> error("Unknown move $outcomeNeeded")
}
}
private fun calculateRPSWin(myMove: Char, theirMove: Char): Int {
return when (theirMove) {
'A' -> when (myMove) {
'X' -> 3
'Y' -> 6
'Z' -> 0
else -> error("Unknown move $myMove")
}
'B' -> when (myMove) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> error("Unknown move $myMove")
}
'C' -> when (myMove) {
'X' -> 6
'Y' -> 0
'Z' -> 3
else -> error("Unknown move $myMove")
}
else -> error("Unknown move $myMove")
}
} | 0 | Kotlin | 0 | 0 | 0a0999007cf16c11355fcf32fc8bc1c66828bbd8 | 2,658 | AOC2022 | Apache License 2.0 |
src/Day23.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | import java.util.*
fun main() {
val dirs = HashMap<Char, Pair<Int, Int>>().apply {
this['N'] = -1 to 0
this['S'] = 1 to 0
this['W'] = 0 to -1
this['E'] = 0 to 1
}
val neighbors = mapOf(
'N' to "EW",
'S' to "EW",
'W' to "NS",
'E' to "NS"
)
fun get(b: Char): List<Pair<Int, Int>> {
val neighbors = neighbors[b]!!
val base = dirs[b]!!
return neighbors.map { base + dirs[it]!! } + base
}
val inOrder = "NSWE".map { get(it) }
fun List<String>.toUsed() = indices.flatMap { i ->
this[i].indices.map { j ->
i to j
}
}.filter { (i, j) -> this[i][j] == '#' }.toMutableSet()
fun iter(used: MutableSet<Pair<Int, Int>>, time: Int): Boolean {
val moves = HashMap<Pair<Int, Int>, Pair<Int, Int>>()
val countForEach = HashMap<Pair<Int, Int>, Int>()
for (from in used) {
var cntAround = 0
for (i in -1..1) for (j in -1..1) if ((from + (i to j)) in used) cntAround++
if (cntAround == 1) continue
var check = 0
while (check < inOrder.size) {
val turn = inOrder[(time + check) % inOrder.size]
if (turn.all { delta -> (from + delta) !in used }) break
check++
}
if (check == inOrder.size) continue
val dest = inOrder[(time + check) % inOrder.size].last() + from
moves[from] = dest
countForEach.merge(dest, 1, Int::plus)
}
for ((from, to) in moves) {
if (countForEach[to]!! == 1) {
used -= from
used += to
}
}
return moves.isNotEmpty()
}
fun part1(input: List<String>): Any {
val used = input.toUsed()
repeat(10) { time ->
iter(used, time)
}
val minX = used.fold(Int.MAX_VALUE) { acc, p -> minOf(acc, p.first) }
val maxX = used.fold(Int.MIN_VALUE) { acc, p -> maxOf(acc, p.first) }
val minY = used.fold(Int.MAX_VALUE) { acc, p -> minOf(acc, p.second) }
val maxY = used.fold(Int.MIN_VALUE) { acc, p -> maxOf(acc, p.second) }
fun print() {
for (i in minX..maxX) {
for (j in minY..maxY) {
print(if ((i to j) in used) '#' else '.')
}
println()
}
}
// print()
return (maxX - minX + 1) * (maxY - minY + 1) - used.size
}
fun part2(input: List<String>): Any {
val used = input.toUsed()
var time = 0
while (true) {
val anyMove = iter(used, time++)
if (!anyMove) break
}
return time
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 23)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 3,192 | advent-of-code-2022 | Apache License 2.0 |
cz.wrent.advent/Day13.kt | Wrent | 572,992,605 | false | {"Kotlin": 206165} | package cz.wrent.advent
import java.util.Deque
import java.util.LinkedList
fun main() {
println(partOne(test))
val result = partOne(input)
println("13a: $result")
println(partTwo(test))
println("13b: ${partTwo(input)}")
}
private fun partOne(input: String): Int {
val pairs = input.split("\n\n")
val packetPairs = pairs.map { it.split("\n").filter { it.isNotEmpty() }.map { it.parsePacketData() } }
.map { it.first() to it.get(1) }
return packetPairs.mapIndexed { index, pair -> index to pair.first.compareTo(pair.second) }.filter { it.second < 0 }
.sumOf { it.first + 1 }
}
private fun partTwo(input: String): Int {
val parsed = input.split("\n").map { it.trim() }.filter { it.isNotEmpty() }.map { it.parsePacketData() } + "[[2]]".parsePacketData() + "[[6]]".parsePacketData()
val sorted = parsed.sorted()
val a = sorted.indexOfFirst { it == PacketList(listOf(PacketList(listOf(PacketInt(2))))) }
val b = sorted.indexOfFirst { it == PacketList(listOf(PacketList(listOf(PacketInt(6))))) }
return (a + 1) * (b + 1)
}
private fun String.parsePacketData(): PacketList {
val root = mutableListOf<PacketData>()
val input = this.substring(1, this.length - 1)
val stack: Deque<MutableList<PacketData>> =
LinkedList<MutableList<PacketData>?>().apply { add(root) } as Deque<MutableList<PacketData>>
val sb = StringBuilder()
for (char in input) {
when (char) {
'[' -> stack.push(mutableListOf())
']' -> {
if (sb.isNotEmpty()) {
stack.peek().add(PacketInt(sb.toString().toInt()))
sb.clear()
}
val closed = stack.pop()
stack.peek().add(PacketList(closed))
}
',' -> {
if (sb.isNotEmpty()) {
stack.peek().add(PacketInt(sb.toString().toInt()))
sb.clear()
}
}
else -> sb.append(char)
}
}
if (sb.isNotEmpty()) {
stack.peek().add(PacketInt(sb.toString().toInt()))
sb.clear()
}
return PacketList(root)
}
private interface PacketData : Comparable<PacketData>
private data class PacketInt(val value: Int) : PacketData {
override fun compareTo(other: PacketData): Int {
return if (other is PacketInt) {
this.value.compareTo(other.value)
} else {
PacketList(listOf(this)).compareTo(other)
}
}
}
private data class PacketList(val value: List<PacketData>) : PacketData {
override fun compareTo(other: PacketData): Int {
return if (other is PacketList) {
val zipped = value.zip(other.value)
var result = 0
for (pair in zipped) {
val compare = pair.first.compareTo(pair.second)
if (compare != 0) {
result = compare
break
}
}
if (result != 0) {
result
} else {
this.value.size.compareTo(other.value.size)
}
} else {
this.compareTo(PacketList(listOf(other)))
}
}
}
private const val test = """[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
"""
private const val input =
"""[]
[[6,[4,[4,10,7]],[[0,8,6],2],[[],8,[7,10,6,4,2],[10,10],6],4]]
[[[9,6,2,5,[4,6,6,8,2]],1,4,10],[[[2,10,9,8],6,1,[0]],[[],[8]]],[[9,[0,7,8],6],[[],9,[5,5],[3]]],[6,3,[7,[1],[0,10,10,2,1],[7]],6,[4,2,3,[]]],[[0,4,[5,4,2,9,5],[2,10],4],5,6,[5,8,4],[[4],5]]]
[[4,0,7,[1,[2,7,2],5,[6]],5],[3,[1,10,[10,4,5,9],8]],[7],[[0],[],6,8],[[[1,2],10,3,8,[]],0,7]]
[[[4,6,9,3,1],4,[3],[2,4,[6,10]],6],[]]
[[4,8],[[],6],[3,4]]
[[10,[[8],7,[4,10,3],1,7]],[[[],2,[6]],10,[[10,0,6,1],1,0],8],[]]
[[2,[3]],[[[],0,[2,6]]]]
[[3,[[8,1,10,7],[10,8,1,5],5,[8]],10]]
[[[4],5,[[],[],10]],[[[],[],[10],[3,7,1],[5,5,6]]],[[4,3],7],[[[5,9,8,9]]]]
[[5,[1],9,[[7,10,5],8,[8,7,2],[6,1]]]]
[[[[1,6],6,7],[],1,[],[[8,4,4,0,4],9]]]
[[[2,7,[10,6,0],[10]],[[1,6,9],9],[[2],[],1,[8]]],[[]]]
[[],[5,9,3,[9,[10,8,10,1],6],[3]],[[10,3,[6,5,1,5]]],[5,[]]]
[[4],[[0,[1],1,4],[3,0,8,[10,3,7,8]],3],[4,9],[[8],[[9,1,4,6],[0,3,7,9,3],[2,9,9,9,0],[]],10,8]]
[[],[3,[0,[4,7],2],10,3,[2,3]]]
[[[[2,2],2,[9],[1,6,7,6,2]],[],6]]
[[3,3,10],[[3,[10,2,6,8,9],[10,10,4,6,1],[7,1,0]],1,[[1,1,9],[10,4,7,4]]],[[],[8,5],[1,[4,4,4,8],[6,7,4],[1,4]],5,8],[4]]
[[9,8,8],[],[],[7,[0,1,1],8]]
[[9,[[2,5]],[10,[1,5,10,5]],4,5],[0]]
[[],[],[4,[9],[[3,7]],4],[5,10,[4],[[9,4,7],[2,0,6,8,5],3,5,7],10],[]]
[[4,[2,10,[],[9,5,9]],[[2,8,8],[4,6,10],1,[9],[1,9]],[8,[5,3,10,10],[7,0],0],[]],[],[],[[10,[1,8,3,3],7,7,[4]],4],[[],1,3]]
[[9,[[1,2,6],1,6,2],5,[4,[0,5,9],[2],3]]]
[[[],[1,8,[3,7,0],7],1,[5,4],[[10,0,0],6,0,[1,2,6],[0,4]]],[1,1,0,[[3],[6,8,6],[10,7,8],[2,10,8,7],6],[]],[[],[[9,5,1,1,8],8,[5]],[[6,10,2,10,2],7,0,8,[10]]],[[[1,4,1,10],[],7],[[6],9,8,[4,1,9,3,3],[2,10,0]],2,[9,8]],[[],4,[]]]
[[5],[9,[[10,3],[0,5,10,6],9,8,5],10,[6,3,6,6]],[4,8],[1,[[2],7,5]]]
[[[4],[[3,0,7],[],7]],[[[],10,[],[10,3,6,1],8],8,0,[[9,8,3],5,[],1],2],[[],[[6,9,10,8,8]],0],[7,[8,0,8,5,[8,3,5]],[8,[6,3,1]],3],[[],[2]]]
[[5,[10],5,10],[],[],[7,3],[4,4]]
[[6,[[10,3,2,7,2],[7,3]]]]
[[],[[10],9,5,9,1],[7,4,[]],[6,[10,6,[2],[5,10,4,9]]]]
[[0,5,9],[[[3],[7,7,4,2],[],1,[]],3,[5,[3,1,9],0,[9,8],4],[6,5],10],[[8,3,[5,9,7,5,7],4],10,[[5,5,4],[2,1,4],1,[7,5,9]]]]
[[[[0],[5]],7,[5,5,2,2]],[10,[[10,1,7,6,6],[5,1,10,3,7],[9,5,7]]]]
[[],[1,[[0,7,0,5,10],10,[4]]],[2,[3,[3,9,1]],[[10,9,0,4],8]],[2],[6,10,2,[[2,1,4]],6]]
[[6,[[3,8],5,0,7],[5,3,4]],[[10,5,[],[10,8,6,3,9]],2,[2,2],1],[1,[2,[8,4],2,7,[]]],[[[1],[3]],[[2],[10,10,5,6],9],[[5,6,7],[0,9],1,2],2]]
[[[8,4],[9,[],8,8,10],3,4,2],[[5,[4,8,5],[2,0,1,4]],[0,[5,5,6]]],[5,[]],[]]
[[[[],[0,7,5],5],9,[3,7,[]],[]],[[[4],7,10,[4,6,10,10,8]],[0,[9,8,4,0],10,3,9],10,[[1,9],10,[3,5,6,2]],0],[6],[[[0]],2,1]]
[[6],[1,[[5],[1,8,0,8,3],5,6,7],[6],[[3,0,1,6,2],[9,7,8],10,[0,1,5,0,0],[4,10]]],[[9,8],9,[[8],0,[8,10,4,0],[]]]]
[[[],[0,[10,7,2],[9,3,4,9],[10,0,10]],[],[[2,6,3,0],9],6]]
[[5,[7,1,6,[9,1,5]]],[[7,[10,4,1,7],8,[2,10,0]],10,2,10,[[10,8,2,7,0],[3,6,0,8,4],7]],[[0,10,[9,4,10],3,[0,1,7,10,9]],1,1],[7,8,[6,[9],[3,5,0,3,5],[4,10,7,0,7],[4]],3,7],[3,[1],0,[[6,7,9],[7,9,0],[9,7,9,7,7]],[[5,10]]]]
[[5,9,0],[[7,[]],[9,6,[6,8],2],1,[]],[],[[[6,4,3,2],[6,3,5],[6,9,0,9,2],0,1],[1,[2,4,7,1],0]]]
[[3,[],[7,[3,5,9,10],[2,4]],0,1],[7]]
[[[[5,4],10],10,[[1,4,1,10]]],[2,[]],[4,[1]],[[1],6,[[4,0,9,10,2],5],8]]
[[],[[],3],[1],[[9],[[],[0],3,5]],[2]]
[[10,6,5,10,[]],[[10,9,4,6],7,10]]
[[1,10,[[9,10,0,6,5],4],10,10],[[[3,2,10,3],7,[],[3,9,2,5]],2,4]]
[[],[[],6,[[9,8,6,7,9],[9,3],1,8,[6,1,7]],2],[[0],[1,4,10,[],10]],[7,1,1,6],[]]
[[8,6,[1,9,9]],[0,[5,7]]]
[[],[],[[5,[2,2,8,5,7],3,9,[4,6,0,2,0]],1,7,0],[],[[[7,6,5],9,[2,2,10,5,6]],4,[0,[],[9,4,1,8]],8,7]]
[[7,0,0]]
[[[[4,9,6,5,4],[0]],[]],[[[7],3,[10,7,4,8,4],[8,9],4],[5,4,[1]]]]
[[[[4,9,0,2],[2,5,6],[3,10,4]],0,8,1,1],[[10,[2],1,[9,0,0,1,9],[8,9,6]],[[9,6,6],4,[5,7],8,[5,9,8,7,10]],10,2],[],[[],[2,0,9,10],1],[4,[[6],[]],5,[7,8,[9,9,3],0],1]]
[[2,10,[[],0,9,8,7],6,0],[7,5,2,[],7],[3]]
[[],[8,[1],5]]
[[[[10,2,4],3,[],0],1,[[5,3,9,0],1],[7,[0,1],[1],9,5],[[1,10],[4,1,9,5,9]]],[8],[1,[9],5,[4,4,6],[8]]]
[[1,10,[[2,3,4,8],8,8],2],[[[],[8,2],9,[0,5,7,0,5],4],4,[[],9,[]],[9,[2,9]],[[],[5],6,7,[]]]]
[[9],[[[4,9],2,[6],[1],[]],[],[]],[[1]],[],[[],[0,[7,4,1],10],[[1]],[[1],[],[6,2,2,1,4],0,[5,4,2,2,5]],[]]]
[[[4,2,1,3],[[9,2,3,3,4],10,8,8,10]],[7,[2,[3,3,6,3],0,[10,2,3,3]]],[[[],6,[5,6],3,[5,6,5,6,9]]]]
[[[5,7,[9,7,10],[]],[[3,10,9,5],5],[],[[],8],[[1,10],10,9]],[[],[1,[4,8,5],[],[2,7,6,7,5]],1],[],[9,4]]
[[],[6,7,3,3],[[3,[]],[]]]
[[[[3,4],8,0,5],4,[[2,10]],7],[[[8,3,4],10,[6,9,8],[2,6,7,7,4]],10,5,[[1],[0,9],[1,1,3,5]]],[]]
[[[[8,4],[0,6,5],0,[0,6]],[2],[[5]]]]
[[8],[[2,7,2,[0,3,8]],[[6,3,8],3,[0],[3,6,1,4,3],6],10,6,[0]],[7],[[],[[],2,[0]]],[4,9,[[6,7,6]],7]]
[[[[8]]],[[2,[3,4,0,1,6],10,[8],[]],[[7,9],4,10],[[6,8],[],6,[],[5,7,6]],[[6,7,10,5,2]],3],[2,3,2,[[10]]],[8,2,[9,8,[1,0,2]]]]
[[7,[[0,5,6,0],[4,1,7,0],8,[1,3,7]],3,[]],[[10,8,[4,3],6,10],7],[],[[],6],[[1,2,4],[[1,3],[9,10],2,[10,6,5,6,0]],[[0],[],3,1],3,[[8],0,9]]]
[[3,8,[5,9,5],4],[3],[],[[],[10,7,[7,0,7],7]],[7]]
[[7,[[],8,[1],[9,1,6,7]],[[],0,[5,2,7,9]]],[[[10],8,[7,1],9],10],[[]]]
[[[6,6,[0,0]],6,5,4,4]]
[[[0,[2,10,1],[4,8,7,4],2,[9]],[5],8],[],[[2,7,[7,10],8,2],8,9,[1,4]],[[[1,4,2],3,[3],[4,1,9]],8,[],[9,[]],[]]]
[[],[[0,1],3,[[4,2,7],10,6,[6,8,6],[3,8,3,5,8]],8,6],[1,1],[9,[[]],7],[[[6],[7,9],[0,6],[4,5,9,4]],[5,9,[10,5,7],[]],[3,[],1,10],5]]
[[[[]],[],0,[[],[2,0,9],[3,3,1],7,[]],8],[[[2],[5,10],5,[10,0,5]],[[6],[0,0,4,6],[0,10]],5,[[]],6],[[2,[4,8,4,3,8],9],2,5,[[],2]],[[[5]]]]
[[],[7,8,[[9,6],[7]]],[[[],1],1],[[[8,5,8,5],[]],[],9,1],[5,[[],10,[10,1,4,6,8],[10,9,9],[2,10,5]],0,[4,[4,2,0,1],2],5]]
[[6,10,3]]
[[],[[],3,[1],6],[],[[3],8,[1,1,[0,5,6,6,5],[]]]]
[[9,8,9,5,[[3,9,6]]]]
[[],[9,[[1,3],1,[8,6,4],[7,0,5,3,10],6],[[5],[1,5,3,8,4],10],[7,[0,0],[7,2,3,9],[6,5],[]]],[4,[],6,[[7,2]]],[8,8,3]]
[[[[],7]],[5,[5,0,[6]]],[5,[0]],[9,2,[[]],[10,[4,9,9,5,10],6,7],10],[]]
[[[[7,2],[1,2],10,[],[2,8]]]]
[[0,[0,5,[4],4,4]]]
[[[[10,0,2,2],1,[]],[10,[3]]],[6,10,[],6]]
[[[],9,5],[[],8,[3]],[[],[[8],[6,8,5,4],[],[0,5,4,4,10]],8,[[],[10,0,1],[2,1,8,0]]],[[0],3,[4,0,[8],[4]],[]],[[[2,10,10,7,10],8,3,0,[7,0,3,1]],[[],[4,9,10,10],[5,8,6,9]],[2,[8,7,10],[7,9],[],[10]]]]
[[6,9],[[8,9],1],[6,[0,[9,2,5,10],5],[9,[10,2,2],8,[9,3],[7,5,2,8]],8]]
[[[3,1,[3,9]],1,[[]],6],[],[6,[[4,10,10,2,4],[],[6,7],0,6],[[7],[],[10,9],[5]]],[[5,[0,10,5],[6,9,4],4,9],5,8,[6,7]]]
[[0]]
[[[],1,[[8,6,8],[5,9],10],[[10,9,1,10,10],9,[8,3,3,0,5],[2,6,1,3,5],[0,7,8,7]],[[8,6,9,1],4]],[10,[1]],[],[4,[[5,4,0],[1],5]]]
[[[]],[10,5,4]]
[[10,10],[7]]
[[],[[],10,6,8]]
[[7,8],[1,[]],[]]
[[2,2,3,8,7],[],[4,7,[0,4,4,[]],4],[[[3,0,9,10],[],[2,0]],[[1,10,3,5,9],3,[],[]]]]
[[[[8],7,[2,7,5,9],[7,5,9,9]],[[],[7],7],6,0],[[[9,6],[1,3,9,4,4]],[[4,4],10],5,9],[1,4,7,7,3],[]]
[[],[]]
[[2,[1],[],[[8,10,4,0]]],[[],[1,[5,6,5,9],6]],[]]
[[[4,6,1,5],[],2,[6,[]]],[[[7,7,2,3]]]]
[[1,[[],9],1,[9,3,[1,9,4,5],10],4],[3,[[],[5,0,1,9,0]]],[[1,[2],1]]]
[[],[[5,6,10,6],[[3,7,0,0,8],2,0,[9]],[5,10,6,7,4],1,[[6,9],6,[7,6],1]],[],[[2,8,[5,7],4],9,0]]
[[[5,[6,5]],[1,2,4,[6,9,2],2],3,[[],[10,7,0,9],[10]]],[3,[[9,3,3],1,[4],[0,3,5],10],[[8,5,5],[],[10,3,10,1]],2],[[[10,9,2,0,9],0,[8,7,7,7]]]]
[[],[[]],[[[5,10],[0,7,4,0],[3,3,10,8,0],[8,5,3,4,7],[3,6]],3,4],[1]]
[[6,2],[],[9],[]]
[[],[[[],6,2,[6,5,0,4],[1,7,6,1,5]],[[],6,[6,7,8,4,6],[4,10,5,10]],[],6],[0,[],[5]],[6]]
[[10],[[[2,10],0],[1,[2,8,8],[]],[[8,1,0]],2,7],[0]]
[[7,[8,[]]]]
[[1,6,9,10,4]]
[[[]],[[10,[0,1,1,9,8],[2,3,4,0]],[[5,2],[5,5,3,5],4,5]]]
[[6,10,[10,4,3,10,[9,9,8,0]]],[[[8,6,5]],8,7,6,[]],[[[1,1,5,10,9],10],[[4,6,8,10,1],10,[0,0,5]],[[9,7]]]]
[[],[[7,[8],7]],[],[1],[]]
[[1,[[1,2,6,9,9],[],[],9],5],[8],[[7],[0,[7,3,9],[4,3,8,7],2,[]],10,[[],10,0,7],[2]],[4,[[],[9],[],8,7],[[9,6,2],2,[8],[4,1,0]],[],8],[]]
[[],[[[7,8,10,3,1],0,4,[3,6,8,8,4]],6,9,[10,8,5,10]],[[[3,10,3],6],[2,[3,10,4,2,8],[7,3,3]]],[]]
[[5,10,[],[10,[1,1,6,3],[8,5,5,1],10]],[2]]
[[[],[],[[2,1,2,3,8],[9,4],[10,9,7,6],0],10,[[5,4,6],2,[4,8],3]]]
[[[[6,0]],[[],6,0],3,[],7]]
[[[[10,5],[]],[],7,5,6],[[[5],[9,8,5,10,4],[10,9,2,3,10],[2,6,2,0]]],[[1,2,10,[6,4,8,5,5],1],1,10,[[5],[4,0,10,5,6],[3,2,5,7],5,1],7]]
[[],[[[5],[9,5,1,7,1],[2,2,10,5]],[5,3,[8,1],[]],[6,3,[2,8,2,6,1]],[[7,0,0,7],[]]],[9,[],[10]],[[5,10],[[6,1,2,7],[0,8,0,4]],[],1,2]]
[[1,8,[],1,[]],[5],[3,6]]
[[7,6],[6,[6,[]],[],10,10],[[1,[4],[1],[10,10,9,0]],[7,2,[],7,[8,5,6]]],[],[[],5,2,[]]]
[[[[4,9],[4],2,[8,0,8,2]],[4,[7,0],[3,1,7,0],[0,1,3],[0,7,1,10]],2,[]]]
[[[[6],[6],[0,6,9,9,0]]],[6,[[],[9,9,5,1],[0,1,6]],[[6,6,5],[5,2],[8,1,3],[4,2,5,2],7]]]
[[[[9,1],[9,3,3,6,8],[],[7,5],3],4,[6,5,9],[[2,1,4,9,8],0,[5,10,1,7,6],[9,7,7]],[[5,5],2]]]
[[[[7,5,3,3,4],[4,6,1,5]],10,[8,1],3],[5,[9,[10,8],[10,5,4,8]],[5,2,0,[0,0,6]],[[2,10,6],[10,2,6],0,1],3]]
[[10,[6],[9,[1,1,0,5],6,10,4],8,0],[[]]]
[[[[4,6],[6,7,5,7,9],1,5],5,7,8,[[8,5,1,9,2],3,[],[1,2,8],[5,3,6]]],[9],[8]]
[[[[6,10,7,1,5],[3,1,4,9,0]]],[[[9,7],1,2],4,[[2,4],10,10,5]],[5,[1,0,6,[10,6]]]]
[[[[8,5],8,1],1,1],[[5,[5,10,8],1,6,1],5,3],[0,3,6,[]],[7,3,4],[[[2,2],8,2],[[4,1,10,8],[2],3],4,8]]
[[[9,1]]]
[[[8,3,[0,10,4,10]],2]]
[[3]]
[[[[],[3,6],[5,7,1,9],[9,5,6,2,7]],8,0,7,2],[],[5,0,[4,[7,8,4],[7,1,2],[4,7,1]],[]],[4,9,[[5,6,9,6]],1]]
[[[2],4,5,[[10,2,7,9,10],5]],[8,[5,5,[9,5,4,8,9],7,[3,10,0,1,7]],[6],[],[1]],[8,[[2,1,10],[]],[[8,3,7,8,4]],[[10,1,8],[10,0,10],3,7,5],[[0,5,1]]],[8],[[10,[],[6],[],6],3,[3,[],2,2,[3,1,10]],2]]
[[],[[3,0,[]],[1,[10,2,3,5,5],[0,8,3,7,2],[5,0]],[2],[[0,4,2,3,7],[8,6,7,5],1]],[[0,[6]],[[4],2,[6,6,3],[8,3,4,2]],[5,1,[4,2,9]]]]
[[[7,[],[10,8,4,3,8],[1,0]],2,8],[3,1,2],[[3,6,[7,6,0,9,7]],8],[8,6,[[4,10,1,1]],[[1,1,1],10],[6]],[[]]]
[[[],[[5],4],[],9,3],[[7,[2,0,5,9,8],6,6,0]],[[5,4,[],[9]],7],[4,[[1,1],3,4,2],[[6,5,7],6,[2,0,5,3]]],[]]
[[2],[[[10]],2,3],[[[1,6,2,9],10,[3,6,7,2,10],4,[6,3,10,6,7]],[[9,2]]]]
[[[[]],[2],[1,2,[0],0],10,[[],3,9,[]]],[3,1]]
[[[],7]]
[[],[[[2,9,9],[]],8,[],[],[[6,1]]],[[10,0,[9,4,6,6],7,[]],9,[8,5,9]]]
[[7,[]],[10,[8],[[9,8,7,6,8],[],10,2,2]],[[],3,[8,10],8,[2,6,[4,8,3]]],[[1,[5,1],4,0],[2,0],9,[]]]
[[],[9,[[7,10,8],2,4],2],[3,5,3,10]]
[[],[1,6],[1,8]]
[[1,[[5,10,6,10,4],[10,8,9],[9,2,2,10,3],8],[1,5,1],[[8]]]]
[[[6,10,6,[5,0,4]],9,8,5,[[4,9],10,[1,4],[]]],[8,[[1,7,8]],[10],[],1],[5,8,[[1,2,9],[3,1,6,4,2],10],3]]
[[[10],[[10,4,7,4]],[[1],7,3,[5]]]]
[[[],[]],[9,4,[],[],5],[[[8,3],[10],[],[2,8]],4,[[1,6,3],[6,8,0]],0],[[[2]],[3,4,[0,3,0],[2]]]]
[[1],[1],[]]
[[],[[5,[]],2],[[[4,7]]],[8,5,[[8]],3]]
[[[3,2,[10]],5,[[9,8,2,10],4,[0,5,4],1],0,[]],[9,[[9],[7,3,6,9],7,[6],4],1],[9,[[4,3,4,10]],[[6,9,6,4,6]],[[0,5,2,5,0],[4,8,3,4],[2,0,9],[],[3,9]]],[[[1,0,7,2,8],[8],6,9]]]
[[[[],1,[7,6,9,8],[2,1,1],8],1,0],[[9,[],[10,0,4,0,5],[]],[[5,1],[2,1,6],0,0,[2,8,0]],1,8]]
[[[[9,10],[10,3,10,8],[],[],[7,5]],[[0,9,4,10,0]],[8,1,4,4,[2]],[7,[10,1,0],[],10],[]],[[0,8,3,6,9],9,[[],[6,2,3,3],[6,4,7],[2]],6],[],[]]
[[[],6,2,9,5],[],[5,7]]
[[6,4,[[7]]]]
[[0],[3,6,7],[[7,[8,8,10]]]]
[[7,[[],5],7,[[2,10],4,[4,0,3]],[]],[7,[2,[9,1],[0],5,7],0,5,[8,[7,8],0]],[[[2],[8]],[]],[6,[9,10,0,4],5,[[3,3,3,3,7],[3],[7,3],0]],[]]
[[[[4],3,5,6],[],[3,7,[2,0,4,9,8]]]]
[[2,[[1,1,8]]]]
[[[1,10,3,5,2],[5],9],[[9,[10],[10,3,0,9]]],[[[4,2,8,10]],[8,[3,0,10],[8,7],2,[9,7,7]],[]]]
[4,5,9,7]
[4,5,9,7,3]
[[[4,0,5,[3,6,9],[7,1]],[9,6],1,5]]
[[3,[1,[5,8,10,3,5],[8,7,8],[8,2]],4,[[7,4,7],[6],[3,2],4]],[],[0,0,3,[[4,2]]],[8,[[1,1,2,8,7],1,[5,4,0,10,6]],[0,0,9],9,[2,[0,9,8,3],10,5]],[7,[3,[4],[1,2]],[[9,4,0,5],5,[1,3,9,5],[6,2,10,6,1],[1,5,1,2,1]]]]
[[5,[4,[5,0,2],[6],[7]]],[8,9],[6,[8,1,7,[6]]]]
[[[6,[4,3,5,10,2],3,[2,7,6],9],7,[1,[5,6,1,4,10],3,[],5]],[[7,[8,4,8],[5,3],[0,4,8],[4,9,1,3]],0,[],6],[[7,[4,9,3,4,7]],[2,3,0,[],6],[[4,5,3],[8,3,10,3,5],[3,8],3,9]],[[9,1,0,1],[3,[8,10],7]]]
[[7,[[9,4,0,1,9],[7],[9,3],[2,9,3],[2,9,3,10]],[[8,1],[4],9],[8],[]],[[1,9,[]],0,6]]
[[[[]],5]]
[[9]]
[[3,[[9]]],[[[1]],4,5],[0,3],[3,0,[4,0,6],[[3,6],[9,7,3],5,3,8]],[2,[0,2,[10]],3,7,[]]]
[[],[[6,[7,2,7,9,6],[9,4,5],3,[]]],[5,4,9,0]]
[[2,3,[],5,8],[[3,5,[9,3]]]]
[[5,[],[]]]
[[],[[]],[[[6],2,2,8],[[]]],[[],[[8],0],2,[[1]],[5,8]]]
[[[2],[[3,0,0,3,2],[1,1],[2,7,2,10],[3]],2],[5,[7,9,6,[7,2,4,8,2]],[10]]]
[[10,8,3],[9],[],[6,[],[[2,6],[8],8],[1,[1,3],4]]]
[[9],[5,[[2,2,1,9,4],[2,2,0,3],3,1],[2,8,3,5]],[],[10],[]]
[[[5]],[9],[9,[[8],[1,6]],7]]
[[0],[],[1,[[],[8]],8,[[7,6,6,2,0],[7,6,3],[7,5,9],9]]]
[[[9,1,4,[8,6]],2,8]]
[[[[7,10,3],6,4],[[5,8,7,4,7],[2,4,3,7]],[4,7,[4,7,1,8],[]],2]]
[[[[4,9]],[7,[2]],[],[[1,9,7],4,4,6,7]],[]]
[[[2,0],[0,10,[1]],9,[[5],[1,9],4,[3,0,3,7,3],8]],[2],[],[[[1,1],[8,8,6]],[4,[7,9,9],[10,10,6,6,5]],[[10,3,9],[10,5,5,9],1,3,9],4],[4,3]]
[[[[],[8,8,7,2]],[[5,3],[2,3],8,[7,8,9,4,4]]],[[5,0,6,8,[1,1,4,3,1]],[[9,5,4,5],2],[],[8,7,[9,2,0,6],[]]],[4,[[],[1],6]]]
[[4,[2,8,[3,7,4,6,5],[9]]],[[[],7],2,3,[3],[]],[]]
[[6,2,0],[],[[[],6]]]
[[[4,6],7],[[4,[6,5],9],7,0],[6,2,5],[8,[[10,2],0,6,[],[0,4]],[[8],10,7,[0,6]],[[7,1,9,3]]],[[[],10,1,[7,6,0]],8,8]]
[[2,[7],5],[],[0,[[0,5],0,[2,5,3,5,7],[10,3,3]],3,[],[10,10,[]]],[[[8,0,8,7],10,6,[9,4,6,1]],9],[[]]]
[[[]],[[8],[7,5,10],0],[1,[[3,10,2],[9,4,3,6],0,[3,0,7,7,2],[7,3,4,2,10]],[7,[3,1,8,9,4],0,7,2],[6,6,[10,7,2,7,9]],7],[[4,1,[10],[8,2,9,6,1]],0,[[8],[0,6,5,3,10],[1,8,0,0],5,7],8],[8]]
[[[[3,1,2,10,0],7],[[9,9,5,10],[4,2,3],8],6,[]],[10],[[[10]]],[[[9,5,0],[7]],10,[]],[[[8,9],1,1]]]
[[10,1,[0]]]
[[3,4,4],[5,[6]],[[1]],[3,[[9,1]],[[]]],[7,1]]
[[],[8,5,[[2,8,7],[3]],9,[1,[4,7,2,6,0],0]],[6],[[10,0,8,1]],[3,9,[7,[]],[[9,3],[0,0,8,7,1],10]]]
[[0],[5,10,10,[4,9,9,2,[4,7]]]]
[[9,3]]
[[[5,10,[5,1,10,6,5],10]],[],[[9,7,[2,5,7,9,5],[8,4,3,4,5],[3]],8,[[0,5],4,[9,6]],[]]]
[[[[5,6],[6,2],0]],[4,[[3,3,0],[]]],[[[]],9,2,6,4],[[[9],3,8,1],6,[6,3,10,6]],[[10,[1]],[9,9],2,4,[[3,3],6,[],[5,9,2,0,9]]]]
[[[[4,9],3,[9,4,10,7]],[[9,6,7],6,[2,4,3],5],6,1,[]],[3,8],[1]]
[9,3,1,1,2]
[9,3,1,1]
[[[],4,[4],[[9,2,4,1],[0],[4,7],[1,5,10]]],[8,[[2,3,4,4,1]],[]]]
[[8],[],[],[2,2,3,9],[9,3,[]]]
[[2],[10,8],[[[7,3,3,5,7],[]],10,1,[[0,3,0],[],[2,2],2,[3,7,1]],8],[]]
[[[10],[1,1,3,[9]],[1,4],[[],9],[8,3,[3]]],[[[9,4,8,7],9,4,[7,6,6,6]],7,4,[8,[1],4,4,8],2],[[[3,10,10],8,[5,9],[2,1,0,7,4]],[1,5,6,[10,7,10,7]],[],3,[[7],[6,7,5,2],0]]]
[[],[[6,8,4,8,[4,7,4,2]],8,[[3,5,2],[]],[0,9,[0,6,2,6,6]],8]]
[[8],[7,8,4],[5,2,[[5,2],0,[5,9]],[[10,2,4,7,4],7,0,[10,6],[3,6]],[5,4,8,8]]]
[[10,[[6]],[2],5,3]]
[[3,6,[0,7,[]]],[9,[]],[0,[[7,8,8,10,5],9,[]],[[7,7,10],3],[[5,4,4,0],8,1]],[[],[4]]]
[[],[[[]],[6,[],10],[],2,[[1],[10,10],[7,10]]]]
[[9,4,[[4,0,0,8,8],[6,10,3,10,0],8]]]
[[2,[3,[8,9,5]],[[],9,[]],9],[8,[],[[],8,3]],[[3,[8,2,4]],[[8,5,5,8,7],9,4],[[5,2,0],7,[],[7,5],3],10]]
[[[],[3,7],[[9,5,1],[3,9,3],5],[5],[3,9,[],[4,3,2],[8,8,8,8,7]]],[[],[6,4,[0,3,1]],[3,[1,4,4,5]]],[[9,[5,9,1,3,0],6,[]],9,1,[[5,2,7,3,9],4,4,7,[10,2,5,6]],8],[7,[],[[0,6],[8,6,8],5]]]
[[6,2,[[],0,[1]]],[[[2],[6,2,8,5,0],[6,6,5,3],[8,10,8,5,1],[]],[[],[10,2,7],[7,3,4],3],[[3],1],8],[8,[7],[],7],[[[0,4,5,3,0],[0,10]],7]]
[[[[6,9]],0,[1,[6,6,4,6,5],8],[2,6,0,[3]],[]],[[2,1],[8,2,8,3,6],5,10],[1,8],[1,8,1],[[10,[5,5,4,8,2],1,[]]]]
[[3,4],[[],4,[6,[9,10,10,9,0],[0,10,0],[2,2]],[9,[8,4,2,3,4],6,[9,10,1,2],[3,2,2,3,4]]],[[8]]]
[[9,[[]]],[],[2,[[0,4,8,7,7],[0,5]]],[]]
[[7,5,4],[[[],1,[]]],[7],[4],[[],2,[[],[9,1,2],10,[6,5,1],[8,9,8]]]]
[[[1,[10,2,3,0,3],9,0,5],4,[5,0,1,3,[5,2,1,9,10]],8],[[10],[[3,9,9,3,3]],9,10],[],[8,[],6,[8,9,10,8],[[4]]],[2,[9],2,[[10,5,8,2,9],[4,1,1,10],[3,3],[2,1,3],[6]]]]
[[5,[]],[],[[0,4,1],4,[],[]],[[[1,7,3]],4,3],[8,[[9],[0,4,4,2],[10,6,4],[3],4],[4,[],[]]]]
[[5,4,1,[10,2]]]
[[4,[]],[6,[[1,2,3,10,9],[5,0,2,2,2],1,5,[8,8,8,9,3]]],[[[4,1,0,5],3,[2,10,8,5],[1],[4,9,6,5]],7,8,[2,4],6],[6],[]]
[[[[1,9],[],[3,4,0]],[[6,1,6],0,4,8,5],6],[2,8],[[8,[7,10,5,0],9,[2,0,9,7,3]]]]
[[0,[5,[],0,[],4]],[[3,5,[0],[10,10,2,5]],[[1,5],[6],4,0]]]
[[[[3],[4,9,8,4,8],[]],6,[[3,5,6,9],5]],[[10,[3,7],[],[1,7,7,4,4],[3,9,4,1]],[0,1,5],4,7,[0,3]],[],[[],[[3,1,8,7]],[[9,9,10],[9,8,7,10],[9,2,0,5]]],[0,[[1,1,6],9,9,4]]]
[[[0,10],[],[],2,[]],[[],5,[10],10],[5],[4,[[2,2,0,3],[0,10,9,4,9],[8],[7,8,9,6,3]],[[0,4],[3],[0,8,10,3,8]]]]
[[1,[7],[6],7],[[],[1,[10],[3,1]],8],[[[9,1,8],2],0,10,3,3],[4,[[10,7,9],4],[6,10,10,2,9],4,[5]]]
[[5,[],[[8,7,6,4],3,[5,2]],7,[[7,3,1,5],[7,8,2,1]]],[4,1,8],[[10,5],10,[5],3],[[3,[1,9,10,9,0],9,[5],7],10,10,[[7,10,0,10]],[8,[3,9],5,[],10]],[[7,[9,6,6,9],7,7,[3,1,1]],10,4,[[]],6]]
[[7,[[6,4,5],10],6,[3,6,[8],[6,4,5],0],[[9,0,7,8,10],10,[4]]],[8,1,8,7],[[[],[0,1,0,2],0,[10,6,1,9],4],[[10,2,5,6,8]]],[]]
[[]]
[[[6,5,10,1,2],[6],3,5,1],[],[[9],7,[[],[5,3,8,3,6],0],5]]
[[[[1],[3],[7,3,2,9]],[[5,1,0,7],[],1],[]]]
[[],[[1],7,[8,[3,0],[0]],[1,[10,3,9],[],0]],[[]],[5,10],[[8,[5,10]],4,8]]
[[[2,3,[6],5],[[6,9],[9,2,2],[9,3,2,0],[6,5,9,3],[5]],0,[[8,8,7,5],[9],9],[]],[[9,8,10],[4],4,9,[8,[],10,2,5]],[5,[],0,2],[[]]]
[[8,[1],[6],0,10],[[8,[3],3],7,[[8,1],7,[10,2,0,1],[10,2],2]],[4]]
[[8,10,9],[[],4,[10,[7,7,7],[],6],[]],[4,8,5,7]]
[[[[9,1,1,8],5]],[[1,6,4,0,5],8],[],[[],5,[9,[]]]]
[[[3,3,6,0],2,9,[[3,6,10],[],7,[3],[8,1]]],[[[0,1,10,2,0],3,4,8],[],[[4],[10,10],[9],9],[0],5],[[],[0,1,1,[5,2,1]]],[1]]
[[[5,[2]],[1],3,3,6],[[[3,9],[8,10,4,3,4],10,[10]],6,[[6,9,2]],6,8],[[[],4,5,[10,6,0,2],[8,0,7,6,9]],[[6,8],8,5,6,[]]],[[[9],2],[9,[],[0,0,7,3,3],6],6,6,3]]
[[[1],10],[[],7],[[[]],7,[[1,3],[4,2,9,10,5]],[[4,1],1]],[[[10,3,5,6,4],10,3,[6,4],0],[2],8,[0,[8],6,[],[6,4,9]]]]
[[[3,2,9],[[3,0],10]],[[6,3],[[6,9,0],[6,9,10,6],[3,9],[7,4,8,5,9],[4,1,4,3,1]],[8],[6,8,[10],8]]]
[[7],[[],[],6],[[[7,8,5,6,5],8,[2,8],9,[4]],0]]
[[[],3,[[3,1],[1,5,4],[8,6,8,5],[5,7,4],[]],3,9],[6,1,[],[]],[[],5],[1,[5,6,[9],[0,2,6,3,7],[7,5,1,1]],[3,4],[[7,3],5,2]]]
[[10,[]]]
[[[[]],[4,[],[1,0,2,2]],[6,[],5,[1],[6,2,7]],[4,9]],[[4,[2,6,2,5,3],[1,8,10],10,[]],1,10,5],[[1,3,7],0]]
[[],[],[5,4,0,10,7],[2,[[],2,0,[7,4,7,7,10],[]],[]]]
[[[0,1],[],6,[10,4,[1,10,5],[8,5,7],7]],[2],[]]
[[],[8,[[],8,[3]],7,3],[1,0],[[],3,2,[]],[]]
[[[2,[8,9,10],[],[4,5,10,0,3]],6,[[]],8],[[10,[5,10,10],[0,3,2,0],8],[7,[8,9]],3,7,[[4,3,6,4,0],2,6]],[3,[5]]]
[[[[0,1,3,3],7,[9,9,1,5,0],2,9],[5,[5,9,1,2,3],1],6,[[10,0],[8,10,8,4],3],1]]
[[[0,7,[8,5,5,6,0],[],8],[]],[0,2,0,[9,1,[6,10,1,9,2],[0,7,10,1,7],9],10]]
[[[8],[[3,0,9],[10,0],1],[[6,3,7,5],[]]]]
[[[],1,[[8,2],[4],9],3,1],[]]
[[],[],[[2],[3],[[10],10,0,[4,1,7,2,10],9],2,[4,9,[4,6,6,1,2],9]]]
[[10]]
[[],[10,[5],[],[6,[2,4,4,8,9],[0,0,8,9],[8],4]],[5,[],7,3,[[5],[8,9,1],7,[9]]],[6,5]]
[[[3,[],[],[3],[6,1,4,4]],5,[],6],[[[6,6,2]],5,[5,5],7],[[[9,8,1,10,0],1,[2,10,0,9,6]],1,4,9]]
[[0],[[7]]]
[[[[0,4],[0]],[],[0,4,0,[5,4]],5],[[],[7,8,4,[7],[10,5]]],[1,1,[[],[],[3,0,1,3]],6],[[],[],7,7,8]]
[[[[1,10,0,1],[7],[2,0,6,3],[],[4,8,5,8,6]],7,[6,9]]]
[[2,0,[[8],1],6,[1,5]],[4],[],[1,9,9]]
[[2,[10,[9,3,6,2],[7],4,5]],[[],9,10],[[],2,[4,[0],[7,5,3,2]],8,10],[9,[1,4,2],[[3,5,6,4,0]]]]
[[3,[9],0,8],[[[7,3],[4,6,6],2,[],[2,5,10,3]]]]
[[[[6,10],4],[3,[6,10,8],[2],[0,2],[8,5,9,6]],7,3],[[[8,3,5]],[2,[10,7,1,4],5]],[[[7,1,7,8]],[2,[1,6,7,7,3]],10],[[10,4,[6],[],7]]]
[[1,[[10,5,2],[5]],0,[1,[7,1,4,9]],6],[],[[[4],[9,6,4]],[[5]]],[[[5,2],10,[10,5,10,9],[5,7]]]]
[[1,[4],4,2]]
[[],[8,[6],1,3],[[]],[[9,8],[[]]]]
[[[7,[],6,9,2],[5,[9],1,8]],[6],[10,1,4]]
[[[8],9,[6],[],0],[[0,4,[8,9],[],8],4,[7,3,[],[6]],[[]],[[],[1,2,7],[]]]]
[[4]]
[[1,[[6],7,5]],[7],[1,10,5],[7,8,[[3],[1,1,5,1],2],[],[7,2,[1,10,5,4],0]],[]]
[[[[]]],[0],[3,[5],9,8,[6,[8,5,2,4,10],[3,4,0],[7,2,4,5,5],[4,8,7,1,4]]],[10,[],[5,[3,6,6,7,3],5,6],7,[10,7,[]]]]
[[2,5,2,2,[[4,2,0,8],[8,7],[1],3]],[[],[[7,5,5,2],[10,2],5,0],[[],3,7,6,9]],[2,[7,[5,6],[5,0,1,8]],3],[[[0,1,4,8,1],[0,0,7,2,1],5,[7,8,0],[]]],[2]]
[[],[1,7,[[0,6]],[[6],[],8]],[2,9,8,8,2],[[[5,1],[8,10,6,4,1]],[],5,5],[1,7,0]]
[[],[8,[1,[2,4,4]]],[[[6,10,4,4,10],7,[3,10,8,3,2],6]],[[1,[10,7],6,1],10,[9,[2],[5,1,4]],[3]],[1,6,7,9,[[9,9,9,2],3]]]
[[[[2,1],[5,9,2],[0,8,5,2],4,[7]]],[3,[1,2,[],6],[7],[[],10],0],[9,8,7,2,7],[[[6,1,8,9]],[[9,6],[0,8,3],4]]]
[[0],[],[],[5,7]]
[[5,8],[[6,7,[2,0,1,4],[3,0,8,5,8],[]],8]]
[[5,8],[2,5,[],5,[[9,9,0],[8,0,3,5,5],[5],[4,9,0,0]]],[9,[],7,7,2],[5,[[],1,8,[10,6,0,10],5],[8,2],2],[6,4,[[9,5,2,0,9],10,7,[0,4,0,2,2],[4,5,0]],[1]]]
[[9],[2],[7,8,[8],7,[]],[[6,8,[7,8,5,3],[9,1,5]],5,8,2],[9,5,[[9,9,2],2]]]
[[],[[9,[6,6,6,0,5],8,5,10],7,[1,[],9,5],[[4,8]]],[[],3],[[[],1],8,[[3],[10,7,9],3,[],9],9,[6,[5,3,8,1,1],10,[]]],[3,5,4,[8,10,[0,4,5,1]]]]
[[],[],[7,[0,[0,6,6,9,4],[],[8,3]],3,7,10]]
[[[]],[10,3,10]]
[[4,[5]],[6,1,[[3],[7],[9,1],[0,4,4,10]]],[[[9],[],[3]]],[[[9,8,0],0,[]],2,5,[6,5,[4,7,4,6,2]]]]
[[1,9],[[[1,9,9,0,8],[8],[5,8,6]],5,4,[3,2,0],5],[2]]
[[5,[10],3]]
[[10,5,[3,6,4,5],7,0],[9,2,[7,[]],[7]],[4]]
[[[],[],[[],4,[5,4,7,9,9],5,3]]]
[[[[5],[],[5,9,6]],[[10,0],[3],2,6,1],6,[10,[5,8,5,3,1],6,[0],3]],[[9,2,9,3],[[7,7],9,[9,3,3,2,1]],[7,1,[2,6,2]],0,8]]
[[10],[3,6],[],[1,8,3,6,1],[0,[[],10,3,[10,8]],4]]
[[[[5,10,5,6],[4]],4,7,[[],[],5,4]],[[2,6,4,8],[]],[[[10,6],[4],[4,7,3]]]]
[[[3,[7,6]],[[8,8,0]],1],[1],[[],5,4,4],[[2,[4,10,2],[3,3,8,7,9],[6,2,5,8],1],[[10,4,1,4],1,[5,5,2,1],[9,9,3]],[2,[7,8,4],[5,1,1,2],[],3]]]
[[1,6,2,4],[1,[],8,[7,6,[5,4],10]],[0],[0,[8]],[[],4]]
[[[1],[0,9,[10,2,2],[6,9,9]]],[[1,[3,3,5,8,10],[],1],[],4],[[[0,2],5,[1],[],7]],[3,7,[]]]
[[8],[0,[7,6,2,[6,5,0]],[10,3,[],[1,6,4,4]],[6,[1,7,7],10,0],10],[9,[[5],[10,6,9,2],1,9],3],[[9,10,1,[10,9,3]],6,[0,[4,5,10],7],6]]
[[4,[3,[9,8,10,2,6],[7,7,2,5,0],[6,9,8,6]]],[4,7,[]],[[4,0,[0,10],7],[4,[6,7,8,7],[7,0,1,0,9]],4],[9,[[6],5,6,4]]]
[[9,7,[9]],[],[[[10,7,10],[1,9,5],[],[]],9],[[[3,9,2,1],8,[],[7,7,6,3],1],[[0,7],10,0],10,[10]],[[],[[8,4],0,[],[8,7,0]],[[9,3,6,0,4],9,[1,7,0,7,10],[]]]]
[[[8],8,4,9]]
[[],[9,8],[7,3,[],3]]
[[[[5],1,4,3],5,[[0,9],4,[5,10,6,2,3],8],[6,3]],[9,2,1,[3,[1],[],4]],[5,[[0,7,9,5],[1,4,0,5],3],[1]],[6,7],[1,10]]
[[[2],1,5,[9,[9,0,9],[],10]],[0,0],[0,[1,8]],[]]
[[3,[]],[1,[4,6,10,6],[8,[3,1],8,6]],[10,3]]
[[[2,4,8],7,[],[]],[4,[],2,[[3,5,4,7,9],[4,4,1]],[4,[0,9,6,5,8]]]]
[[0,[7],[2,[5,7]],6,[3]],[0,[],[3]]]
[[[8,[],[10,3,8],[3,1,2,10]],1,[9]],[[2,10,3,8,[3,1,5]]],[8]]
[[5]]
[[9,8,[[1,9,3,5],[9]],4,2],[7,5],[2,[1,[]]],[4,[[7,8],3,7,[3,2,6],[9,0,4]],9],[[[2,2,7],7],[[7],[2,2,9,10]]]]
[[6],[10,[[2,7,3,8],[5],8,9],[0],10],[[[1,5],[1,4,0,2],[10,8,9]]],[2]]
[[10,[],[5,[1,4,1],6],[[8,3,0,8],[2]]],[1,[[],[8],[]],10,9,10],[]]"""
| 0 | Kotlin | 0 | 0 | 8230fce9a907343f11a2c042ebe0bf204775be3f | 25,069 | advent-of-code-2022 | MIT License |
src/Day12.kt | iownthegame | 573,926,504 | false | {"Kotlin": 68002} | import java.util.Queue
import kotlin.Pair
class Point(val x: Int, val y: Int, val value: Char) {
fun sameAs(anotherPoint: Point): Boolean {
return anotherPoint.x == x && anotherPoint.y == y
}
// fun inRange(rows: Int, cols: Int): Boolean {
// return (x in 0 until rows) && (y in 0 until cols)
// }
override fun toString(): String {
return "(x: $x, y: $y)"
}
}
fun main() {
// fun dfs(grid: Array<Array<Char>>, rows: Int, cols: Int, currentPoint: Point, currentPointValue: Char, endPoint: Point, currentSteps: Int, totalSteps: MutableList<Int>) {
// if (currentPoint.sameAs(endPoint)) {
// totalSteps.add(currentSteps)
// return
// }
//
// if (totalSteps.isNotEmpty() && currentSteps >= totalSteps.min()) {
// return
// }
//
// val directions = arrayOf(arrayOf(0, -1), arrayOf(0, 1), arrayOf(-1, 0), arrayOf(1, 0))
// for (direction in directions) {
// val newPoint = Point(currentPoint.x + direction[0], currentPoint.y + direction[1])
// if (!newPoint.inRange(rows, cols)) {
// continue
// }
// if (grid[newPoint.x][newPoint.y] == "X".toCharArray().first()) { // visited
// continue
// }
//
// val newPointValue = grid[newPoint.x][newPoint.y]
// if (newPointValue.code - currentPointValue.code > 1) {
// continue
// }
// grid[newPoint.x][newPoint.y] = "X".toCharArray().first()
// dfs(grid, rows, cols, newPoint, newPointValue, endPoint, currentSteps + 1, totalSteps)
// grid[newPoint.x][newPoint.y] = newPointValue
// }
// }
fun bfs(grid: Array<Array<Point>>, rows: Int, cols: Int, startPoints: Array<Point>, endPoint: Point): Int {
val visitedPoints = ArrayDeque<Point>()
startPoints.forEach { visitedPoints.add(it) }
val directions = arrayOf(arrayOf(0, -1), arrayOf(0, 1), arrayOf(-1, 0), arrayOf(1, 0))
var steps = 0
while (true) {
for (i in 1..visitedPoints.size) {
val currentPoint = visitedPoints.removeFirst()
for (direction in directions) {
val newX = currentPoint.x + direction[0]
val newY = currentPoint.y + direction[1]
if (!((newX in 0 until rows) && (newY in 0 until cols))) {
continue
}
val newPoint = grid[newX][newY]
if (visitedPoints.contains(newPoint)) {
continue
}
if (newPoint.value.code - currentPoint.value.code > 1) {
continue
}
visitedPoints.add(newPoint)
}
}
steps += 1
if (visitedPoints.contains(endPoint)) {
return steps
}
}
}
fun part1(input: List<String>): Int {
val rows = input.size
val cols = input[0].length
val grid = Array(rows) { Array(cols) { Point(-1, -1, '1') } }
var startPoint = Point(-1, -1, '1')
var endPoint = Point(-1, -1, '1')
for ((i, line) in input.withIndex()) {
for((j, c) in line.withIndex()) {
if (c.toString() == "S") {
startPoint = Point(i, j, 'a')
grid[i][j] = startPoint
} else if (c.toString() == "E") {
endPoint = Point(i, j, 'z')
grid[i][j] = endPoint
} else {
grid[i][j] = Point(i, j, c)
}
}
}
// dfs works for sample data, not work for actual data
// val totalSteps = mutableListOf<Int>()
// val startPointValue = grid[startPoint.x][startPoint.y]
// grid[startPoint.x][startPoint.y] = "X".toCharArray().first()
// dfs(grid, rows, cols, startPoint, startPointValue, endPoint, 0, totalSteps)
return bfs(grid, rows, cols, arrayOf(startPoint), endPoint)
}
fun part2(input: List<String>): Int {
val rows = input.size
val cols = input[0].length
val grid = Array(rows) { Array(cols) { Point(-1, -1, '1') } }
var startPoints = arrayOf<Point>()
var endPoint = Point(-1, -1, '1')
for ((i, line) in input.withIndex()) {
for((j, c) in line.withIndex()) {
if (c.toString() == "S" || c.toString() == "a") {
val startPoint = Point(i, j, 'a')
grid[i][j] = startPoint
startPoints += startPoint
} else if (c.toString() == "E") {
endPoint = Point(i, j, 'z')
grid[i][j] = endPoint
} else {
grid[i][j] = Point(i, j, c)
}
}
}
return bfs(grid, rows, cols, startPoints, endPoint)
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day12_sample")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readTestInput("Day12")
println("part 1 result: ${part1(input)}")
println("part 2 result: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 4e3d0d698669b598c639ca504d43cf8a62e30b5c | 5,389 | advent-of-code-2022 | Apache License 2.0 |
kotlin-practice/src/main/kotlin/algorithms/new/SumOfCalibrationValues.kt | nicolegeorgieva | 590,020,790 | false | {"Kotlin": 120359} | package algorithms.new
import java.io.File
fun main() {
val input = File("day1.txt").readText()
val input2 = File("new.txt").readText()
println(finalSum("www3two"))
println(finalSum(input))
println(finalSum(input2))
}
val numbers = mapOf(
Pair("one", 1),
Pair("two", 2),
Pair("three", 3),
Pair("four", 4),
Pair("five", 5),
Pair("six", 6),
Pair("seven", 7),
Pair("eight", 8),
Pair("nine", 9)
)
val finalNums = numbers + numbers.map {
val newKey = it.key.reversed()
Pair(newKey, it.value)
}
private fun finalSum(input: String): Int {
val words = getWords(input)
val res = words.map {
wordToTwoDigitNumber(it)
}.sum()
return res
}
private fun wordToTwoDigitNumber(word: String): Int {
val first = extractFirstDigit(word) ?: throw Exception("Error!")
val second = extractFirstDigit(word.reversed()) ?: first
return "$first$second".toInt()
}
private fun getWords(input: String): List<String> {
return input.split("\n")
}
private fun extractFirstDigit(word: String): Int? {
var accumulated = ""
var digit: Int? = null
for (char in word) {
if (char.isDigit()) {
digit = char.digitToInt()
break
}
accumulated += char
val number = containsTextDigit(accumulated)
if (number != null) {
digit = number
break
}
}
return digit
}
// "wwwone" -> "one"
// "www" -> null
private fun containsTextDigit(accumulated: String): Int? {
for (key in finalNums.keys) {
if (key in accumulated) {
return finalNums[key]
}
}
return null
} | 0 | Kotlin | 0 | 1 | c96a0234cc467dfaee258bdea8ddc743627e2e20 | 1,685 | kotlin-practice | MIT License |
src/main/kotlin/com/advent/of/code/hjk/Day22.kt | h-j-k | 427,964,167 | false | {"Java": 46088, "Kotlin": 26804} | package com.advent.of.code.hjk
import kotlin.math.abs
object Day22 {
private fun parse(line: String): Node? =
"/dev/grid/node-x(?<x>\\d+)-y(?<y>\\d+)\\s+(?<size>\\d+)T\\s+(?<used>\\d+)T.+".toRegex()
.matchEntire(line)?.destructured
?.let { (x, y, size, used) -> Node(x.toInt(), y.toInt(), size.toInt(), used.toInt()) }
fun part1(input: List<String>): Int {
val nodes = input.drop(2).mapNotNull { parse(it) }
return nodes.flatMap { node ->
nodes.mapNotNull { other ->
setOf(node, other).takeIf { node != other && node.used > 0 && node.used <= other.avail }
}
}.toSet().size
}
fun part2(input: List<String>): Int {
val nodes = input.drop(2).mapNotNull { parse(it) }.sortedByDescending { it.avail }
val maxX = nodes.maxOf { it.x }
val wall = nodes.filter { it.size > 250 }.minByOrNull { it.x }!!
val emptyNode = nodes.first { it.used == 0 }
var result = abs(emptyNode.x - wall.x) + 1
result += emptyNode.y
result += maxX - wall.x
return result + (5 * (maxX - 1)) + 1
}
internal data class Node(val x: Int, val y: Int, val size: Int, val used: Int) {
val avail = size - used
}
}
| 0 | Java | 0 | 0 | 5ffa381e97cbcfe234c49b5a5f8373641166db6c | 1,277 | advent16 | Apache License 2.0 |
src/Day03.kt | MisterTeatime | 560,956,854 | false | {"Kotlin": 37980} | fun main() {
val priorities = ('a'..'z') + ('A'..'Z')
fun part1(input: List<String>): Int {
return input.map {
it.chunked(it.length / 2)
}
.flatMap { (front, back) ->
front.toSet().intersect(back.toSet())
}
.sumOf { priorities.indexOf(it) + 1 }
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.flatMap { group ->
group.fold(group[0].toSet()) { acc, line ->
acc.intersect(line.toSet())
}
}
.sumOf { priorities.indexOf(it) + 1 }
}
// 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 | 8ba0c36992921e1623d9b2ed3585c8eb8d88718e | 934 | AoC2022 | Apache License 2.0 |
src/main/kotlin/io/nozemi/aoc/solutions/year2021/day09/SmokeBasin.kt | Nozemi | 433,882,587 | false | {"Kotlin": 92614, "Shell": 421} | package io.nozemi.aoc.solutions.year2021.day09
import io.nozemi.aoc.puzzle.Puzzle
import io.nozemi.aoc.utils.addIfNotExists
import kotlin.reflect.KFunction0
class SmokeBasin(input: String) : Puzzle<Array<IntArray>>(input) {
override fun Sequence<String>.parse(): Array<IntArray> = this.map { line ->
line.toCharArray().map { digit -> digit.digitToInt() }.toIntArray()
}.toList().toTypedArray()
override fun solutions(): List<KFunction0<Any>> = listOf(
::part1,
::part2
)
private fun part1(): Int {
return getLowPoints().sumOf { it + 1 }
}
private fun part2(): Int {
val basins = findBasins().toMutableList()
if (basins.size <= 3) {
throw RuntimeException("You fucked up! You need at least 3 basins.")
}
val basinSizes = basins.map { it.size }.toMutableList()
val threeLargestBasins = IntArray(3) { -1 }
repeat(3) { iteration ->
val max = basinSizes.maxOrNull() ?: throw RuntimeException("You fucked up... Should never really come to this!?")
threeLargestBasins[iteration] = max; basinSizes.remove(max)
}
return threeLargestBasins[0] * threeLargestBasins[1] * threeLargestBasins[2]
}
fun findBasins(): List<Basin> {
val basins = mutableListOf<Basin>()
iterateLowPoints { input, row, column, number ->
val positions = traverseBasin(input, mutableListOf(), number, row, column)
basins.add(Basin(size = positions.count(), positions = positions))
}
return basins
}
private fun aboveConditionBasin(input: Array<IntArray>, row: Int, column: Int, number: Int): Boolean =
(row != 0 && input[row - 1][column] < 9 && input[row - 1][column] > number)
private fun belowConditionBasin(input: Array<IntArray>, row: Int, column: Int, number: Int): Boolean =
(row < (input.size - 1) && input[row + 1][column] < 9 && input[row + 1][column] > number)
private fun leftConditionBasin(input: Array<IntArray>, row: Int, column: Int, number: Int): Boolean =
(column != 0 && input[row][column - 1] < 9 && input[row][column - 1] > number)
private fun rightConditionBasin(input: Array<IntArray>, row: Int, column: Int, number: Int): Boolean =
(column < (input[row].size - 1) && input[row][column + 1] < 9 && input[row][column + 1] > number)
private fun traverseBasin(
input: Array<IntArray>, visitedNodes: MutableList<Position>, currentNumber: Int, row: Int, column: Int
): MutableList<Position> {
visitedNodes.addIfNotExists(Position(row, column, currentNumber))
if (aboveConditionBasin(input, row, column, currentNumber)) {
visitedNodes.addIfNotExists(Position(row, column, input[row - 1][column]))
traverseBasin(input, visitedNodes, input[row - 1][column], row - 1, column)
}
if (belowConditionBasin(input, row, column, currentNumber)) {
visitedNodes.addIfNotExists(Position(row, column, input[row + 1][column]))
traverseBasin(input, visitedNodes, input[row + 1][column], row + 1, column)
}
if (leftConditionBasin(input, row, column, currentNumber)) {
visitedNodes.addIfNotExists(Position(row, column, input[row][column - 1]))
traverseBasin(input, visitedNodes, input[row][column - 1], row, column - 1)
}
if (rightConditionBasin(input, row, column, currentNumber)) {
visitedNodes.addIfNotExists(Position(row, column, input[row][column + 1]))
traverseBasin(input, visitedNodes, input[row][column + 1], row, column + 1)
}
return visitedNodes
}
private inline fun iterateLowPoints(
input: Array<IntArray> = parsedInput,
doWithPosition: (input: Array<IntArray>, row: Int, column: Int, number: Int) -> Unit
) {
input.forEachIndexed { row, columns ->
columns.forEachIndexed { column, number ->
// Get number above if row isn't 0
val above = if (row == 0) 10 else input[row - 1][column]
val below = if (row == input.size - 1) 10 else input[row + 1][column]
val left = if (column == 0) 10 else input[row][column - 1]
val right = if (column == columns.size - 1) 10 else input[row][column + 1]
if ((number < above) && (number < below) && (number < left) && (number < right)) {
doWithPosition(input, row, column, number)
}
}
}
}
fun getLowPoints(input: Array<IntArray> = parsedInput): List<Int> {
val lowPoints = mutableListOf<Int>()
iterateLowPoints(input) { _, _, _, number ->
lowPoints.add(number)
}
return lowPoints
}
data class Basin(
val size: Int,
val positions: List<Position>
)
data class Position(
val row: Int,
val column: Int,
val value: Int
) {
override fun equals(other: Any?): Boolean {
if (other == null || other !is Position) return false
return this.row == other.row && this.column == other.column
}
override fun hashCode(): Int {
var result = row
result = 31 * result + column
result = 31 * result + value
return result
}
}
} | 0 | Kotlin | 0 | 0 | fc7994829e4329e9a726154ffc19e5c0135f5442 | 5,428 | advent-of-code | MIT License |
src/main/kotlin/dev/bogwalk/batch9/Problem97.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch9
import java.math.BigInteger
/**
* Problem 97: Large Non-Mersenne Prime
*
* https://projecteuler.net/problem=97
*
* Goal: Return the last 12 digits of a very large number of the form A * (B^C) + D. If this
* amount is less than 1e12, return the output padded with leading zeroes.
*
* Constraints: 1 <= A, B, C, D <= 1e9
*
* Mersenne Prime: A prime number that is 1 less than a power of 2, of the form M_n = (2^n) - 1.
* For this number to be prime, n must also be prime. The 1st few Mersenne primes are 3, 7, 31,
* 127, 8191 corresponding to n = 2, 3, 5, 7, 13. The 1st known prime to exceed 1e6 digits is a
* Mersenne prime of the form (2^6_972_593) - 1, which contains exactly 2_098_960 digits.
*
* e.g.: A = 2, B = 3, C = 4, D = 5
* 2 * (3^4) + 5 = 167
* output = "000000000167"
*/
class LargeNonMersennePrime {
private val modulo: Long = 1_000_000_000_000
/**
* Solution using BigInteger's built-in modPow().
*
* SPEED (WORSE) 3.73s for PE problem.
*/
fun tailOfVeryLargeNumBI(a: Int, b: Int, c: Int, d: Int): String {
val bigMod = BigInteger.valueOf(modulo)
val (aBI, bBI, cBI, dBI) = listOf(a, b, c, d).map(Int::toBigInteger)
val power = bBI.modPow(cBI, bigMod)
val result = aBI * power + dBI
return result.mod(bigMod).toString().padStart(12, '0')
}
/**
* Solution is similar to Problem 13's RTL manual addition, except that there is no need to
* either use RollingQueue or iterate more than 12 times since only the last 12 digits are
* required.
*
* SPEED (BETTER) 8.72ms for PE problem.
*/
fun tailOfVeryLargeNum(a: Int, b: Int, c: Int, d: Int): String {
val power = b.toBigInteger().pow(c).toString().takeLast(12).padStart(12, '0')
val tail = IntArray(12)
var carryOver = 0
val extra = d.toString().padStart(12, '0')
for (i in 11 downTo 0) {
val sum = a * power[i].digitToInt() + extra[i].digitToInt() + carryOver
tail[i] = sum % 10
carryOver = sum / 10
}
return tail.joinToString("")
}
/**
* HackerRank specific implementation that requires the last 12 digits of the sum of multiple
* very large numbers resulting from expressions of the form a * b^c + d.
*/
fun tailSumOfVerlyLargeNums(inputs: List<List<String>>): String {
val bigMod = BigInteger.valueOf(modulo)
var sum = BigInteger.ZERO
for ((a, b, c, d) in inputs) {
val power = b.toBigInteger().modPow(c.toBigInteger(), bigMod)
sum += (a.toBigInteger() * power + d.toBigInteger()).mod(bigMod)
// could perform a third modulo here but this significantly reduces performance
}
return sum.mod(bigMod).toString().padStart(12, '0')
}
/**
* Project Euler specific implementation that requires the last 10 digits of the massive
* non-Mersenne prime of the form 28433 * (2^7_830_457) + 1, which contains 2_357_207 digits.
*/
fun tailOfNonMersennePrime(useManual: Boolean = false): String {
val (a, b, c, d) = listOf(28433, 2, 7_830_457, 1)
return if (useManual) {
tailOfVeryLargeNum(a, b, c, d).takeLast(10)
} else {
tailOfVeryLargeNumBI(a, b, c, d).takeLast(10)
}
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,387 | project-euler-kotlin | MIT License |
src/Day08/Day08.kt | emillourens | 572,599,575 | false | {"Kotlin": 32933} | fun main() {
fun part1(input: List<String>): Int {
var forest: MutableList<MutableList<Int>> = ArrayList()//Array(input.size) { IntArray(input.size) }
var counter = 0
for (line in input)
{
var tempList: MutableList<Int> = ArrayList()
for ( j in line.indices)
tempList.add(line[j].digitToInt())
forest.add(tempList)
}
var forestTranspose: MutableList<MutableList<Int>> = ArrayList()
for (i in forest.indices) {
var tempList: MutableList<Int> = ArrayList()
for (j in forest[i].indices) {
tempList.add(forest[j][i])
}
forestTranspose.add(tempList)
}
for (row in forest.indices)
{
for (column in forest[row].indices)
{
var tree = forest[row][column]
var left = forest[row].subList(0, column)
var right = forest[row].subList(column + 1, forest.size)
var up = forestTranspose[column].subList(0, row)
var down = forestTranspose[column].subList(row + 1, forest.size)
if( right.all { x -> x < tree }
|| left.all { x -> x < tree }
|| up.all { x -> x < tree }
|| down.all { x -> x < tree })
counter++
}
//println("Visible tree $largest")
}
println(counter)
return counter
}
fun ViewDistance(tree: Int, view: MutableList<Int>): Int
{
var view_length = 0
for (v in view) {
view_length += 1
if (v >= tree)
break
}
return view_length
}
fun part2(input: List<String>): Int {
var forest: MutableList<MutableList<Int>> = ArrayList()//Array(input.size) { IntArray(input.size) }
var BigScore = 0
for (line in input)
{
var tempList: MutableList<Int> = ArrayList()
for ( j in line.indices)
tempList.add(line[j].digitToInt())
forest.add(tempList)
}
var forestTranspose: MutableList<MutableList<Int>> = ArrayList()
for (i in forest.indices) {
var tempList: MutableList<Int> = ArrayList()
for (j in forest[i].indices) {
tempList.add(forest[j][i])
}
forestTranspose.add(tempList)
}
for (row in forest.indices)
{
for (column in forest[row].indices)
{
var score = 0
var tree = forest[row][column]
var left = forest[row].subList(0, column).reversed().toMutableList()
var right = forest[row].subList(column + 1, forest.size)
var up = forestTranspose[column].subList(0, row).reversed().toMutableList()
var down = forestTranspose[column].subList(row + 1, forest.size)
var s1 = ViewDistance(tree, left)
var s2 = ViewDistance(tree, right)
var s3 = ViewDistance(tree, up)
var s4 = ViewDistance(tree, down)
score = s1 * s2 * s3 * s4
if (score > BigScore)
BigScore = score
}
//println("Visible tree $largest")
}
println(BigScore)
return BigScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08/Day08_test")
check(part1(testInput) == 21)
val testInput2 = readInput("Day08/Day08_test2")
check(part1(testInput2) == 22)
check(part2(testInput) == 8)
val input = readInput("Day08/Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1f9739b73ef080b012e505e0a4dfe88f928e893d | 3,846 | AoC2022 | Apache License 2.0 |
src/aoc22/Day13.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc2022.day13
import lib.Collections.headTail
import lib.Solution
sealed interface Value : Comparable<Value> {
override operator fun compareTo(other: Value): Int =
when (this) {
is IntegerValue -> when (other) {
is IntegerValue -> value.compareTo(other.value)
is ListValue -> ListValue(listOf(this)).compareTo(other)
}
is ListValue -> when (other) {
is IntegerValue -> compareTo(ListValue(listOf(other)))
is ListValue -> {
val (h1, t1) = list.headTail()
val (h2, t2) = other.list.headTail()
when {
h1 == null || h2 == null -> list.size.compareTo(other.list.size)
h1.compareTo(h2) == 0 -> ListValue(t1).compareTo(ListValue(t2))
else -> h1.compareTo(h2)
}
}
}
}
data class IntegerValue(val value: Int) : Value {
companion object {
fun parse(input: ArrayDeque<Char>): IntegerValue {
assert(input.isNotEmpty() && input.first().isDigit())
var v = 0
while (input.first().isDigit()) {
val d = input.removeFirst().digitToInt()
v = v * 10 + d
}
return IntegerValue(v)
}
}
}
data class ListValue(val list: List<Value>) : Value {
companion object {
fun parse(input: ArrayDeque<Char>): ListValue {
assert(input.size >= 2 && input.first() == '[')
// Special case for handling empty list.
if (input[1] == ']') {
repeat(2) {
input.removeFirst()
}
return ListValue(emptyList())
}
val l = buildList {
while (input.removeFirst() != ']') {
add(Value.parse(input))
}
}
return ListValue(l)
}
}
}
companion object {
fun parse(input: String): Value = parse(ArrayDeque(input.toList()))
fun parse(input: ArrayDeque<Char>): Value =
if (input.first() == '[') {
ListValue.parse(input)
} else {
IntegerValue.parse(input)
}
}
}
typealias Input = List<Pair<Value, Value>>
typealias Output = Int
private val solution = object : Solution<Input, Output>(2022, "Day13") {
val DIVIDER_PACKETS = listOf(Value.parse("[[2]]"), Value.parse("[[6]]"))
override fun parse(input: String): Input =
input
.split("\n\n")
.map { block ->
val (l1, l2) = block.lines()
Value.parse(l1) to Value.parse(l2)
}
override fun format(output: Output): String = "$output"
override fun part1(input: Input): Output =
input
.mapIndexedNotNull { idx, pair ->
(idx + 1).takeIf {
pair.first < pair.second
}
}.sum()
override fun part2(input: Input): Output =
(input.flatMap { it.toList() } + DIVIDER_PACKETS).sorted()
.mapIndexedNotNull { idx, packet ->
(idx + 1).takeIf {
packet in DIVIDER_PACKETS
}
}.reduce(Int::times)
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 3,022 | aoc-kotlin | Apache License 2.0 |
src/Day03.kt | derivz | 575,340,267 | false | {"Kotlin": 6141} | // create map of all lowercase letters and uppercase letters to numbers from 1 to 52
val letterValues = ('a'..'z').zip(1..26).toMap() + ('A'..'Z').zip(27..52).toMap()
fun main() {
fun part1(lines: List<String>): Int {
return lines.map { line ->
val left = line.substring(0, line.length / 2).toSet()
val right = line.substring(line.length / 2).toSet()
val commonLetters = left.intersect(right)
letterValues[commonLetters.first()]!!
}.sum()
}
fun part2(lines: List<String>): Int {
// group line by chunks of 3
return lines.chunked(3).map {
val commonLetters = it[0].toSet().intersect(it[1].toSet()).intersect(it[2].toSet())
letterValues[commonLetters.first()]!!
}.sum()
}
val lines = readLines("Day03")
println(part1(lines))
println(part2(lines))
}
| 0 | Kotlin | 0 | 0 | 24da2ff43dc3878c4e025f5b737dca31913f40a5 | 890 | AoC2022.kt | Apache License 2.0 |
src/main/kotlin/adventofcode2022/solution/day_10.kt | dangerground | 579,293,233 | false | {"Kotlin": 51472} | package adventofcode2022.solution
import adventofcode2022.util.readDay
import java.lang.Long.min
fun main() {
Day10("10").solve()
}
class Day10(private val num: String) {
private val inputText = readDay(num)
fun solve() {
println("Day $num Solution")
println("* Part 1: ${solution1()}")
println("* Part 2: ${solution2()}")
}
fun solution1(): Long {
val cycleValues = mutableMapOf<Int, Long>()
var cycle = 1
var regX = 1L
inputText.lines().forEach {
when {
it == "noop" -> {
cycleValues[cycle] = regX
cycle++
}
it.startsWith("addx ") -> {
cycleValues[cycle] = regX
cycle++
println("cycle $cycle: x=$regX")
regX += it.substring("addx ".length).toLong()
cycleValues[cycle] = regX
cycle++
}
}
println("cycle $cycle: x=$regX")
}
return cycleValues.filter {
listOf(
20,
60,
100,
140,
180,
220
).contains(it.key)
}.map { it.key * it.value }
.sum()
}
fun solution2(): Long {
val cycleValues = mutableMapOf<Int, Int>()
var cycle = 0
var regX = 1
val screen = IntRange(0, 239).associateWith { '.' }.toMap().toMutableMap()
inputText.lines().forEach {
when {
it == "noop" -> {
screen.draw(regX, cycle)
cycleValues[cycle] = regX
cycle++
}
it.startsWith("addx ") -> {
screen.draw(regX, cycle)
cycleValues[cycle] = regX
cycle++
screen.draw(regX, cycle)
regX += it.substring("addx ".length).toInt()
cycleValues[cycle] = regX
cycle++
}
}
}
screen.values.map { it.toString() }.joinToString("") { it }
.chunked(40)
.forEach {
println(it)
}
return 0
}
private fun MutableMap<Int, Char>.draw(pixel: Int, cycle: Int) {
print("cycle $cycle: x=$pixel (sprite=(${pixel - 1}-${pixel + 1})")
val cycle2 = cycle % 40
if (pixel - 1 <= cycle2 && cycle2 <= pixel + 1) {
this[cycle] = '#'
print(" DRAW")
}
println()
}
} | 0 | Kotlin | 0 | 0 | f1094ba3ead165adaadce6cffd5f3e78d6505724 | 2,686 | adventofcode-2022 | MIT License |
src/Day11.kt | ChAoSUnItY | 572,814,842 | false | {"Kotlin": 19036} | import java.util.*
fun main() {
val perMonkeyPattern =
Regex("""Monkey \d*:\n {2}Starting items: ([\w, ]+)\n {2}Operation: (new = [ (old)+*\d]+)\n {2}Test: divisible by (\d+)\n {4}If true: throw to monkey (\d+)\n {4}If false: throw to monkey (\d+)""")
val operationPattern =
Regex("""new = old ([*|+]) (\d+|old)""")
data class Monkey(
val items: LinkedList<Long>,
val operation: (Long) -> Long,
val divisibleValue: Long,
val trueBranch: Int,
val falseBranch: Int,
var inspectedItems: Long = 0
)
fun processOperation(data: String): (Long) -> Long {
val (operator, rhs) = operationPattern.matchEntire(data)!!.destructured
return when (operator) {
"*" -> {
when (rhs) {
"old" -> { a -> a * a }
else -> { a -> a * rhs.toLong() }
}
}
"+" -> {
when (rhs) {
"old" -> { a -> a + a }
else -> { a -> a + rhs.toLong() }
}
}
else -> { a -> a }
}
}
fun processData(data: List<String>): List<Monkey> =
data.joinToString("\n")
.split("\n\n")
.map {
val (items, operation, divisibleValue, trueThrowTo, falseThrowTo) = perMonkeyPattern.matchEntire(it)!!.destructured
val processedItems = items.split(",")
.map(String::trim)
.mapTo(LinkedList(), String::toLong)
Monkey(
processedItems,
processOperation(operation),
divisibleValue.toLong(),
trueThrowTo.toInt(),
falseThrowTo.toInt()
)
}
fun startRound(monkeys: List<Monkey>, worryUpdater: (Long) -> Long) {
for (monkey in monkeys) {
while (monkey.items.isNotEmpty()) {
monkey.inspectedItems++
val item = monkey.items
.pollFirst()
.let(monkey.operation::invoke)
.let(worryUpdater)
val branch =
if (item % monkey.divisibleValue == 0L) monkey.trueBranch
else monkey.falseBranch
monkeys[branch].items += item
}
}
}
fun runRounds(round: Int, monkeys: List<Monkey>, worryUpdater: (Long) -> Long): Long {
for (_i in 0 until round) {
startRound(monkeys, worryUpdater)
}
return monkeys.map(Monkey::inspectedItems)
.sortedDescending()
.take(2)
.reduce(Long::times)
}
fun part1(monkeys: List<Monkey>): Long =
runRounds(20, monkeys) { it / 3 }
fun part2(monkeys: List<Monkey>): Long =
runRounds(10_000, monkeys) { it % monkeys.map(Monkey::divisibleValue).fold(1, Long::times) }
val input = readInput("Day11")
println(part1(processData(input)))
println(part2(processData(input)))
}
| 0 | Kotlin | 0 | 3 | 4fae89104aba1428820821dbf050822750a736bb | 3,113 | advent-of-code-2022-kt | Apache License 2.0 |
leetcode2/src/leetcode/sqrtx.kt | hewking | 68,515,222 | false | null | package leetcode
/**
* 69. x 的平方根
* https://leetcode-cn.com/problems/sqrtx/
* Created by test
* Date 2019/7/18 0:50
* Description
* 实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
输入: 4
输出: 2
示例 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sqrtx
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object Sqrt {
@JvmStatic
fun main(args: Array<String>) {
println(Solution().mySqrt(2147483647))
}
class Solution {
/**
* 思路:
* 理论上可行这种方式,可是相乘会导致结果超出Int上限,导致错误
*/
fun mySqrt(x: Int): Int {
for (i in 1 until (x + 1)) {
if (i * i == x) {
return i
} else if (i * i > x) {
return i - 1
}
}
return 0
}
/**
* 思路:
* 1. 通过二分查找思想,找出中间数,然后平方
* 2.根据平方结果与x值进行比较
*/
fun mySqrt2(x: Int): Int {
if ( x < 2) {
return x
}
return sqrt(x,0,x)
}
fun sqrt(x: Int,low: Int,high: Int): Int{
if (low > high) {
return high
}
var m = (low + high) / 2
if (m > x / m) {
return sqrt(x,low , m - 1)
} else if (m < x / m) {
return sqrt(x,m + 1 , high)
} else {
return m
}
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,951 | leetcode | MIT License |
src/main/kotlin/recursion/WordSearchII.kt | e-freiman | 471,473,372 | false | {"Kotlin": 78010} | package recursion
class WordSearchII {
class TrieNode {
val children = HashMap<Char, TrieNode>()
var isLeaf = false
}
private val ret = mutableSetOf<String>()
private var board: Array<CharArray> = arrayOf<CharArray>()
private var m: Int = -1
private var n: Int = -1
private var visited: BooleanArray = booleanArrayOf()
private fun find(i: Int, j: Int, cur: TrieNode, sb: StringBuilder) {
if (board[i][j] in cur.children) {
visited[i * n + j] = true
sb.append(board[i][j])
val next = cur.children[board[i][j]]!!
if (next.isLeaf) {
ret.add(sb.toString())
}
if (i > 0 && !visited[(i - 1) * n + j]) find(i - 1, j, next, sb)
if (i < m - 1 && !visited[(i + 1) * n + j]) find(i + 1, j, next, sb)
if (j > 0 && !visited[i * n + j - 1]) find(i, j - 1, next, sb)
if (j < n - 1 && !visited[i * n + j + 1]) find(i, j + 1, next, sb)
sb.deleteCharAt(sb.lastIndex)
visited[i * n + j] = false
}
}
// O(m * n * max(word length))
fun findWords(board: Array<CharArray>, words: Array<String>): List<String> {
this.board = board
val trieRoot = TrieNode()
for (word in words) {
var cur = trieRoot
for (ch in word) {
if (ch !in cur.children) {
cur.children[ch] = TrieNode()
}
cur = cur.children[ch]!!
}
cur.isLeaf = true
}
m = board.size
n = board[0].size
for (i in 0 until m) {
for (j in 0 until n) {
visited = BooleanArray(m * n) {false}
val sb = StringBuilder()
find(i, j, trieRoot, sb)
}
}
return ret.toList()
}
}
fun main() {
println(WordSearchII().findWords(arrayOf(
charArrayOf('a','b','c','e'),
charArrayOf('x','x','c','d'),
charArrayOf('x','x','b','a')),
arrayOf("abc","abcd")))
}
| 0 | Kotlin | 0 | 0 | fab7f275fbbafeeb79c520622995216f6c7d8642 | 2,105 | LeetcodeGoogleInterview | Apache License 2.0 |
solutions/aockt/y2016/Y2016D03.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2016
import io.github.jadarma.aockt.core.Solution
object Y2016D03 : Solution {
/** Parses the input, returning the number rows as triples of integers. */
private fun parseInput(input: String): Sequence<Triple<Int, Int, Int>> =
input
.lineSequence()
.map {
val (a, b, c) = it
.trim()
.replace(Regex("""\s+"""), ",")
.split(',')
.map(String::toInt)
Triple(a, b, c)
}
/** Given a sequence of rows of three integers, maps it to a sequence of vertically transposed numbers. */
private fun Sequence<Triple<Int, Int, Int>>.readVertically(): Sequence<Triple<Int, Int, Int>> =
chunked(3) { row ->
sequenceOf(
Triple(row[0].first, row[1].first, row[2].first),
Triple(row[0].second, row[1].second, row[2].second),
Triple(row[0].third, row[1].third, row[2].third),
)
}.flatten()
/** Checks whether three integers could be the values of the length of a triangle. */
private fun Triple<Int, Int, Int>.couldBeTriangle(): Boolean = toList().sorted().let { (a, b, c) -> a + b > c }
override fun partOne(input: String) = parseInput(input).count { it.couldBeTriangle() }
override fun partTwo(input: String) = parseInput(input).readVertically().count { it.couldBeTriangle() }
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 1,455 | advent-of-code-kotlin-solutions | The Unlicense |
src/com/ncorti/aoc2023/Day16.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
import com.ncorti.aoc2023.Direction.*
enum class Direction {
UP, DOWN, LEFT, RIGHT;
fun opposite(): Direction = when (this) {
UP -> DOWN
DOWN -> UP
LEFT -> RIGHT
RIGHT -> LEFT
}
}
fun main() {
fun parseInput() = getInputAsText("16") {
split("\n").filter(String::isNotBlank).map { it.toCharArray() }
}.toTypedArray()
fun computeEnergized(
start: Triple<Int, Int, Direction>,
map: Array<CharArray>,
): Array<IntArray> {
val seen = Array(map.size) {
IntArray(map[0].size) { 0 }
}
val toProcess = mutableListOf(start)
val processSeen = mutableSetOf<Triple<Int, Int, Direction>>()
while (toProcess.isNotEmpty()) {
val nextToProcess = toProcess.removeAt(0)
if (nextToProcess in processSeen) {
continue
}
processSeen.add(nextToProcess)
var (i, j, direction) = nextToProcess
when (direction) {
UP -> i--
DOWN -> i++
LEFT -> j--
RIGHT -> j++
}
if (i < 0 || j < 0 || i >= map.size || j >= map[0].size) {
continue
}
seen[i][j] = 1
when (map[i][j]) {
'.' -> {
toProcess.add(Triple(i, j, direction))
}
'-' -> {
if (direction == LEFT || direction == RIGHT) {
toProcess.add(Triple(i, j, direction))
} else {
toProcess.add(Triple(i, j, LEFT))
toProcess.add(Triple(i, j, RIGHT))
}
}
'|' -> {
if (direction == UP || direction == DOWN) {
toProcess.add(Triple(i, j, direction))
} else {
toProcess.add(Triple(i, j, UP))
toProcess.add(Triple(i, j, DOWN))
}
}
'/' -> {
when (direction) {
UP -> toProcess.add(Triple(i, j, RIGHT))
DOWN -> toProcess.add(Triple(i, j, LEFT))
LEFT -> toProcess.add(Triple(i, j, DOWN))
RIGHT -> toProcess.add(Triple(i, j, UP))
}
}
'\\' -> {
when (direction) {
UP -> toProcess.add(Triple(i, j, LEFT))
DOWN -> toProcess.add(Triple(i, j, RIGHT))
LEFT -> toProcess.add(Triple(i, j, UP))
RIGHT -> toProcess.add(Triple(i, j, DOWN))
}
}
}
}
return seen
}
fun part1(): Int = computeEnergized(Triple(0, -1, RIGHT), parseInput()).sumOf { it.sum() }
fun part2(): Int {
val map = parseInput()
var max = 0
val entryPoints = mutableListOf<Triple<Int, Int, Direction>>()
for (i in map.indices) {
entryPoints.add(Triple(i, -1, RIGHT))
entryPoints.add(Triple(i, map[i].size, LEFT))
}
for (i in map[0].indices) {
entryPoints.add(Triple(-1, i, DOWN))
entryPoints.add(Triple(map.size, i, UP))
}
for (key in entryPoints) {
val seen = computeEnergized(key, map)
val totalSeen = seen.sumOf { it.sum() }
if (totalSeen > max) {
max = totalSeen
}
}
return max
}
println(part1())
println(part2())
}
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 3,740 | adventofcode-2023 | MIT License |
src/main/kotlin/com/github/michaelbull/advent2023/day21/GardenMap.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.day21
import com.github.michaelbull.advent2023.math.Vector2
import com.github.michaelbull.advent2023.math.Vector2.Companion.CARDINAL_DIRECTIONS
import com.github.michaelbull.advent2023.math.Vector2CharMap
import com.github.michaelbull.advent2023.math.Vector3
import com.github.michaelbull.advent2023.math.mod
import com.github.michaelbull.advent2023.math.toVector2CharMap
fun Sequence<String>.toGardenMap(): GardenMap {
val map = this.toVector2CharMap()
val (start) = map.first { (_, char) -> char == 'S' }
map[start] = '.'
return GardenMap(map, start)
}
data class GardenMap(
val map: Vector2CharMap,
val start: Vector2,
) {
fun reachablePlots(steps: Int): Int {
return paths(steps).count { path ->
(path.steps and 1) == (steps and 1)
}
}
fun infiniteReachablePlots(steps: Int): Long {
val x0 = steps % map.width
val x1 = x0 + map.width
val x2 = x1 + map.width
val paths = paths(x2)
val y0 = paths.count { (_, steps) -> (steps and 1) == (x0 and 1) && steps <= x0 }
val y1 = paths.count { (_, steps) -> (steps and 1) == (x1 and 1) && steps <= x1 }
val y2 = paths.count { (_, steps) -> (steps and 1) == (x2 and 1) && steps <= x2 }
val polynomial = Vector3(y0, y1, y2).lagrange()
val x = (steps - start.x) / map.width
return x.toLong().quadratic(polynomial)
}
private fun paths(steps: Int): Sequence<Path> = sequence {
val queue = ArrayDeque<Path>()
val visited = mutableSetOf<Vector2>()
queue += Path(start, 0)
visited += start
while (queue.isNotEmpty()) {
val path = queue.removeFirst()
yield(path)
val nextStep = path.steps + 1
if (nextStep <= steps) {
val adjacentPlots = adjacentPlots(path.destination)
val unvisitedPlots = adjacentPlots.filter { it !in visited }
val paths = unvisitedPlots.map { destination -> Path(destination, nextStep) }
queue += paths
visited += unvisitedPlots
}
}
}
private fun adjacentPlots(position: Vector2): List<Vector2> {
return CARDINAL_DIRECTIONS
.map(position::plus)
.filter(::isPlotAt)
}
private fun isPlotAt(position: Vector2): Boolean {
return map.getInfinitely(position) == '.'
}
private fun Vector2CharMap.getInfinitely(position: Vector2): Char {
val x = position.x.mod(map.xRange)
val y = position.y.mod(map.yRange)
return get(Vector2(x, y))
}
private data class Path(
val destination: Vector2,
val steps: Int,
)
/**
* Lagrange's Interpolation formula for ax^2 + bx + c with x=[0,1,2] and y=[y0,y1,y2] we have
* f(x) = (x^2-3x+2) * y0/2 - (x^2-2x)*y1 + (x^2-x) * y2/2
* so the coefficients are:
* a = y0/2 - y1 + y2/2
* b = -3*y0/2 + 2*y1 - y2/2
* c = y0
*
* [Reddit](https://www.reddit.com/r/adventofcode/comments/18nevo3/2023_day_21_solutions/keb8ud3/)
*/
private fun Vector3.lagrange(): Vector3 {
return Vector3(
x = (x / 2.0 - y + z / 2.0).toInt(),
y = (-3 * (x / 2.0) + 2 * y - z / 2.0).toInt(),
z = x,
)
}
private fun Long.quadratic(polynomial: Vector3): Long {
val (a, b, c) = polynomial
return (a * this * this) + (b * this) + c
}
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 3,539 | advent-2023 | ISC License |
Day24/src/Bugs.kt | gautemo | 225,219,298 | false | null | import java.io.File
import kotlin.math.pow
fun main(){
val input = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText()
val result = findRepeatedBiodiversity(input)
println(result)
val spaceResult = findBugsSpaceFold(input, 200)
println(spaceResult)
}
fun findBugsSpaceFold(map: String, minutes: Int): Int {
val spaceFold = List(minutes + 10){ emptyTiles() }.toMutableList()
val init = mapToTiles(map).toMutableList()
init.removeAll { it.x == 2 && it.y == 2 }
spaceFold[minutes/2 + 5] = init
for(m in 0 until minutes){
println(m)
val copy = spaceFold.map { it.map { t -> t.copy() } }
for((i, tiles) in spaceFold.withIndex()){
tick(tiles, copy[i], copy.getOrNull(i-1), copy.getOrNull(i+1))
//print(tiles)
}
}
return spaceFold.map { it.count { t -> t.bug } }.sum()
}
fun mapToTiles(map: String): List<Tile>{
val width = map.lines().first().length
return map.filter { it != '\n' }.mapIndexed { index, c ->
val x = index % width
val y = index / width
Tile(x, y, c == '#', index)
}
}
fun emptyTiles(): List<Tile>{
val tiles = mutableListOf<Tile>()
for(y in 0 until 5){
for(x in 0 until 5){
if(x == 2 && y == 2){
continue
}
tiles.add(Tile(x, y, false, 0))
}
}
return tiles
}
fun findRepeatedBiodiversity(map: String): Int {
val tiles = mapToTiles(map)
val prevStates = mutableListOf(listOf<Tile>())
while(true){
val copy = tiles.map { it.copy() }
tick(tiles, copy, null, null)
//print(tiles)
if(prevStates.contains(tiles)){
return tiles.filter { it.bug }.sumBy { it.biodiversity.toInt() }
}
prevStates.add(tiles.map { it.copy() })
}
}
fun tick(tiles: List<Tile>, copy: List<Tile>, around: List<Tile>?, inside: List<Tile>?){
for(tile in tiles){
//Same tiles
var bugsAround = copy.filter { it.bug && tilesAreNeighbour(tile, it) }.count()
//Around layer
if(tile.x == 0){
bugsAround += if(around?.first { it.x == 1 && it.y == 2 }?.bug == true) 1 else 0
}
if(tile.x == 4){
bugsAround += if(around?.first { it.x == 3 && it.y == 2 }?.bug == true) 1 else 0
}
if(tile.y == 0){
bugsAround += if(around?.first { it.x == 2 && it.y == 1 }?.bug == true) 1 else 0
}
if(tile.y == 4){
bugsAround += if(around?.first { it.x == 2 && it.y == 3 }?.bug == true) 1 else 0
}
//Inside layer
if(tile.x == 3 && tile.y == 2){
bugsAround += inside?.filter { it.bug && it.x == 4 }?.count() ?: 0
}
if(tile.x == 1 && tile.y == 2){
bugsAround += inside?.filter { it.bug && it.x == 0 }?.count() ?: 0
}
if(tile.x == 2 && tile.y == 3){
bugsAround += inside?.filter { it.bug && it.y == 4 }?.count() ?: 0
}
if(tile.x == 2 && tile.y == 1){
bugsAround += inside?.filter { it.bug && it.y == 0 }?.count() ?: 0
}
when{
tile.bug && bugsAround != 1 -> tile.bug = false
!tile.bug && bugsAround in (1..2) -> tile.bug = true
}
}
}
data class Tile(val x: Int, val y: Int, var bug: Boolean, val tileNr: Int){
val biodiversity = 2.0.pow(tileNr)
}
fun tilesAreNeighbour(p1: Tile, p2: Tile): Boolean{
if(p1.y == p2.y){
return p1.x - 1 == p2.x || p1.x + 1 == p2.x
}
if(p1.x == p2.x){
return p1.y - 1 == p2.y || p1.y + 1 == p2.y
}
return false
}
fun print(tiles: List<Tile>){
var map = ""
var y = 0
for(t in tiles){
if(t.y != y){
y++
map += '\n'
}
map += if(t.bug) '#' else '.'
}
println(map)
println()
} | 0 | Kotlin | 0 | 0 | f8ac96e7b8af13202f9233bb5a736d72261c3a3b | 3,919 | AdventOfCode2019 | MIT License |
src/Day03.kt | lmoustak | 573,003,221 | false | {"Kotlin": 25890} | fun main() {
val items = mutableSetOf<Char>()
for (c in 'a'..'z') items.add(c)
for (c in 'A'..'Z') items.add(c)
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val partition = line.length / 2
val firstHalf = line.substring(0, partition)
val firstHalfItems = firstHalf.toCharArray()
val secondHalf = line.substring(partition)
val commonsFound = mutableSetOf<Char>()
for (c in secondHalf) {
if (firstHalfItems.contains(c) && commonsFound.add(c)) score += items.indexOf(c) + 1
}
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
val size = input.size
for (i in 0 until size step 3) {
var commons = input[i].toCharSet()
commons = commons.intersect(input[i + 1].toCharSet())
commons = commons.intersect(input[i + 2].toCharSet())
score += items.indexOf(commons.first()) + 1
}
return score
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd259af405b557ab7e6c27e55d3c419c54d9d867 | 1,175 | aoc-2022-kotlin | Apache License 2.0 |
aoc/src/main/kotlin/com/bloidonia/aoc2023/day10/Main.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.day10
import com.bloidonia.aoc2023.text
private const val example = """-L|F7
7S-7|
L|7||
-L-J|
L|-JF"""
private const val example2 = """7-F7-
.FJ|7
SJLL7
|F--J
LJ.LJ"""
private const val example3 = """...........
.S-------7.
.|F-----7|.
.||.....||.
.||.....||.
.|L-7.F-J|.
.|..|.|..|.
.L--J.L--J.
..........."""
private const val example4 = """.F----7F7F7F7F-7....
.|F--7||||||||FJ....
.||.FJ||||||||L7....
FJL7L7LJLJ||LJ.L-7..
L--J.L7...LJS7F-7L7.
....F-J..F7FJ|L7L7L7
....L7.F7||L7|.L7L7|
.....|FJLJ|FJ|F7|.LJ
....FJL-7.||.||||...
....L---J.LJ.LJLJ..."""
private data class Position(val x: Int, val y: Int) {
}
private data class Tile(val position: Position, val exits: List<Position>, var distance: Long = 0) {
}
private fun parse(input: String) = input.lines().flatMapIndexed { y, line ->
line.mapIndexed { x, c ->
Position(x, y) to when (c) {
'-' -> Tile(Position(x, y), listOf(Position(x - 1, y), Position(x + 1, y)))
'|' -> Tile(Position(x, y), listOf(Position(x, y - 1), Position(x, y + 1)))
'L' -> Tile(Position(x, y), listOf(Position(x, y - 1), Position(x + 1, y)))
'J' -> Tile(Position(x, y), listOf(Position(x, y - 1), Position(x - 1, y)))
'F' -> Tile(Position(x, y), listOf(Position(x, y + 1), Position(x + 1, y)))
'7' -> Tile(Position(x, y), listOf(Position(x, y + 1), Position(x - 1, y)))
'S' -> Tile(Position(x, y), listOf())
else -> Tile(Position(x, y), listOf(Position(x, y)))
}
}
}.toMap().toMutableMap()
private fun process(input: String) = parse(input).let { map ->
// Find the start and fix the exits
val startPosition = map.firstNotNullOf { (pos, tile) -> if (tile.exits.isEmpty()) pos else null }
map[startPosition] = Tile(startPosition, map.filter { (_, tile) -> tile.exits.contains(startPosition) }.keys.toList())
val seen = mutableSetOf(startPosition)
var tiles = map[startPosition]?.exits!!
var distance = 1L
while (tiles.isNotEmpty()) {
tiles = tiles.flatMap {
val tile = map[it]!!
seen.add(it)
tile.distance = distance
tile.exits.filter { exit -> !seen.contains(exit) }
}
distance++
}
println("Max distance along loop: ${map.values.maxByOrNull { it.distance }!!.distance}")
}
fun main() {
process(example)
process(example2)
process(example3)
process(example4)
process(text("/day10.input"))
} | 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 2,510 | aoc-2023 | MIT License |
src/Day03.kt | pejema | 576,456,995 | false | {"Kotlin": 7994} | import kotlin.streams.toList
fun main() {
val items = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun getPriorities(compartment1: String, compartment2: String) : Int {
return compartment1.toList().stream()
.filter { item -> compartment2.contains(item) }
.findFirst()
.map { item -> items.indexOf(item) + 1 }
.orElse(0)
}
fun getPrioritiesPart2(group: List<String>) : Int {
return group[0].toList().stream()
.filter { item -> group[1].contains(item) && group[2].contains(item) }
.findFirst()
.map { item -> items.indexOf(item) + 1 }
.orElse(0)
}
fun part1(input: List<String>): Int {
return input.stream()
.map { line ->
val half = line.length / 2
getPriorities(line.substring(0, half), line.substring(half))
}
.toList().sum()
}
fun part2(input: List<String>): Int {
return input.chunked(3)
{ group -> getPrioritiesPart2(group) }.sum()
}
// 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")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | b2a06318f0fcf5c6067058755a44e5567e345e0c | 1,432 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2016/Day22.kt | colinodell | 495,627,767 | false | {"Kotlin": 80872} | package com.colinodell.advent2016
class Day22(input: List<String>) {
private val nodes = input.drop(2).map { Node.parse(it) }
fun solvePart1() = nodes.permutationPairs().includingReversePairs().filter { it.first.used > 0 && it.first.used < it.second.avail }.count()
fun solvePart2(): Int {
val xMax = nodes.maxOf { it.pos.x }
val hole = nodes.first { it.used == 0 }
val wallStart = nodes.filter { it.size > 250 }.minByOrNull { it.pos.x }!!
return listOf(
hole.pos.manhattanDistance(wallStart.pos), // empty node to wall
hole.pos.y, // up to the top
(xMax - wallStart.pos.x), // over to the goal
(5 * (xMax - 1)) // from the goal back to the start
).sum()
}
private data class Node(val pos: Vector2, val size: Int, val used: Int, val avail: Int) {
companion object {
private val re = Regex("""/dev/grid/node-x(\d+)-y(\d+)\s+(\d+)T\s+(\d+)T\s+(\d+)T""")
fun parse(line: String): Node {
val (x, y, size, used, avail) = re.find(line)!!.groupValues.drop(1).map { it.toInt() }
return Node(Vector2(x, y), size, used, avail)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8a387ddc60025a74ace8d4bc874310f4fbee1b65 | 1,225 | advent-2016 | Apache License 2.0 |
src/Day01.kt | phamobic | 572,925,492 | false | {"Kotlin": 12697} | fun main() {
fun insertCaloriesToSortedMax(topMaxCalories: MutableList<Long>, calories: Long) {
val index = topMaxCalories.indexOfFirst { calories > it }
if (index < 0) return
topMaxCalories.add(index, calories)
topMaxCalories.removeLast()
}
fun getMaxCaloriesSum(numberOfElves: Int, caloriesInput: List<String>): Long {
val topMaxCalories = MutableList(numberOfElves) { 0L }
var currentElfCalories = 0L
caloriesInput.forEach { line ->
if (line.isBlank()) {
insertCaloriesToSortedMax(topMaxCalories, currentElfCalories)
currentElfCalories = 0L
} else {
currentElfCalories += line.toLong()
}
}
insertCaloriesToSortedMax(topMaxCalories, currentElfCalories)
return topMaxCalories.sum()
}
fun part1(input: List<String>): Long = getMaxCaloriesSum(1, input)
fun part2(input: List<String>): Long = getMaxCaloriesSum(3, input)
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000L)
check(part2(testInput) == 45000L)
}
| 1 | Kotlin | 0 | 0 | 34b2603470c8325d7cdf80cd5182378a4e822616 | 1,137 | aoc-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.