path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/day3.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getLines
fun getPowerConsumption(diagnosticReport: List<String>): Int{
val length = diagnosticReport.first().length
var gamma = ""
var epsilon = ""
for(i in 0 until length){
val ones = diagnosticReport.count { it[i] == '1' }
val zeros = diagnosticReport.count { it[i] == '0' }
if(ones > zeros){
gamma += "1"
epsilon += "0"
}else{
gamma += "0"
epsilon += "1"
}
}
return gamma.toInt(2) * epsilon.toInt(2)
}
fun getLifeSupport(diagnosticReport: List<String>): Int{
return getMetric(diagnosticReport) { ones, zeros -> ones >= zeros } * getMetric(diagnosticReport) { ones, zeros -> ones < zeros }
}
private fun getMetric(input: List<String>, criteria: (ones: Int, zeros: Int) -> Boolean): Int{
var diagnosticReport = input
val length = diagnosticReport.first().length
for(i in 0 until length){
val ones = diagnosticReport.count { it[i] == '1' }
val zeros = diagnosticReport.count { it[i] == '0' }
val keep = if(criteria(ones, zeros)) '1' else '0'
diagnosticReport = diagnosticReport.filter { it[i] == keep }
if(diagnosticReport.size == 1){
return diagnosticReport[0].toInt(2)
}
}
throw Exception("Should stop with one diagnostic line")
}
fun main(){
val input = getLines("day3.txt")
val power = getPowerConsumption(input)
println(power)
val lifeSupport = getLifeSupport(input)
println(lifeSupport)
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 1,528 | AdventOfCode2021 | MIT License |
src/challenges.kt | BenjaminEarley | 151,190,621 | false | null | import java.math.BigInteger
fun String.isPalindrome(): Boolean =
when {
count() < 2 -> true
first() != last() -> false
else -> slice(1..count() - 2).isPalindrome()
}
fun Int.isEven(): Boolean = this % 2 == 0
fun Int.isOdd(): Boolean = this.isEven().not()
fun power(x: Int, n: Int): Double =
when {
n == 0 -> 1.0
n < 0 -> 1.0 / power(x, -n)
n.isOdd() -> x * power(x, n - 1)
else -> power(x, n / 2) * power(x, n / 2)
}
enum class Tower(val title: String) {
LEFT("left"),
MIDDLE("middle"),
RIGHT("right")
}
fun moveDisk(source: Tower, destination: Tower) =
println("Move ${source.title}'s top disk to ${destination.title}")
fun solveHanoi(size: Int, source: Tower, destination: Tower) {
if (size > 0) {
val tmp = (Tower.values().toList() - source - destination).first()
solveHanoi(size - 1, source, tmp)
moveDisk(source, destination)
solveHanoi(size - 1, tmp, destination)
}
}
// Linear Fib
fun linFib(n: Int): BigInteger {
val memo = mutableMapOf<Int, BigInteger>()
fun loop(n: Int): BigInteger =
if (n < 2) n.toBigInteger() else memo.getOrPut(n - 2) { loop(n - 2) } + memo.getOrPut(n - 1) { loop(n - 1) }
return loop(n)
}
fun tailRecFactorial(n: Int): Int {
tailrec fun helper(nn: Int, result: Int): Int =
if (nn == 0) result
else helper(nn - 1, result * nn)
return helper(n, 1)
}
| 0 | Kotlin | 0 | 0 | 1a4278273f3d79d4e5bb7054d0e5fb91274e871c | 1,461 | Functional_Kotlin | MIT License |
src/Day01.kt | rk012 | 574,169,156 | false | {"Kotlin": 9389} | fun main() {
fun List<String>.readWithNulls() = scan<_, Int?>(null) { acc, s ->
if (s.isBlank()) null
else (acc ?: 0) + s.toInt()
}.let { it + null }
fun part1(input: List<String>) = input.readWithNulls().filterNotNull().max()
fun part2(input: List<String>) = input.readWithNulls().let { l ->
l.indices.filter { l[it] == null }.map { it - 1 } to l
}.let { (i, l) ->
l.filterIndexed { index, _ -> i.contains(index) }.filterNotNull()
}.sortedDescending().subList(0, 3).sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bfb4c56c4d4c8153241fa6aa6ae0e829012e6679 | 813 | advent-of-code-2022 | Apache License 2.0 |
codeforces/codeton6/e_tl.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.codeton6
private fun solve(): Int {
readln()
val a = readInts()
val mark = IntArray(a.size + 1) { -1 }
val dp0 = mutableSetOf(0)
val dp = MutableList(a.size + 1) { dp0 }
val dpMax = IntArray(a.size + 1) { 0 }
val dpHashCode = IntArray(a.size + 1) { 0 }
val used = mutableSetOf<Long>()
var leastAbsent = 1
for (i in a.indices) {
var mex = 0
val dpCurrent = dp[i].toMutableSet()
dp[i + 1] = dpCurrent
for (j in i downTo 0) {
val aj = a[j]
mark[aj] = i
if (aj == mex) {
while (mark[mex] == i) mex++
//println("${dp[j]} xor $mex}")
val t = dpMax[j] or mex
.let { (1 shl it.countSignificantBits()) - 1 }
if (leastAbsent > t) continue
val code = (dpHashCode[j].toLong() shl 32) or mex.toLong()
if (!used.add(code)) continue
for (v in dp[j]) dpCurrent.add(v xor mex)
while (leastAbsent in dpCurrent) leastAbsent++
}
}
dpMax[i + 1] = dpCurrent.max()
dpHashCode[i + 1] = dpCurrent.hashCode()
}
return dpMax.last()
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private fun Int.countSignificantBits() = Int.SIZE_BITS - Integer.numberOfLeadingZeros(this)
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,295 | competitions | The Unlicense |
y2022/src/main/kotlin/adventofcode/y2022/Day20.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
object Day20 : AdventSolution(2022, 20, "Grove Positioning System") {
override fun solvePartOne(input: String): Long {
val lines = parse(input).withIndex().toList()
return solve(1, lines)
}
override fun solvePartTwo(input: String): Any? {
val lines = parse(input).map { it * 811589153L }.withIndex().toList()
return solve(10, lines)
}
private fun parse(input: String) = input.lines().map { it.toLong() }
private fun solve(rounds: Int, lines: List<IndexedValue<Long>>): Long {
val circle = ArrayDeque(lines)
fun clamp(i: Long): Int = when {
i < 0 -> i + circle.size
i > circle.lastIndex -> i - circle.size
else -> i
}.toInt()
repeat(rounds) {
for (v in lines) {
val pos = circle.indexOf(v)
circle.remove(v)
circle.add(clamp(pos + v.value % circle.size), v)
}
}
val zero = circle.indexOfFirst { it.value == 0L }
return listOf(1000L, 2000L, 3000L)
.map { it % circle.size }
.map(zero::plus)
.map(::clamp)
.map(circle::get)
.sumOf { it.value }
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,304 | advent-of-code | MIT License |
codeforces/codeton6/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.codeton6
private fun solve() {
val (_, k) = readInts()
fun rightmost(a: List<Int>): IntArray {
val res = IntArray(k) { -1 }
for (i in a.indices) res[a[i]] = i
for (i in k - 2 downTo 0) res[i] = maxOf(res[i], res[i + 1])
return res
}
val a = readInts().map { it - 1 }
val present = BooleanArray(k)
for (x in a) present[x] = true
val right = rightmost(a)
val left = rightmost(a.asReversed()).map { a.size - 1 - it }
val ans = IntArray(k) {
if (right[it] == -1 || !present[it]) 0 else (right[it] - left[it] + 1) * 2
}
println(ans.joinToString(" "))
}
fun main() = repeat(readInt()) { solve() }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 781 | competitions | The Unlicense |
src/main/kotlin/Day1.kt | darwineee | 726,871,065 | false | {"Kotlin": 1770} | import kotlin.io.path.Path
import kotlin.io.path.forEachLine
fun day1_part1(path: String) {
var result = 0
Path(path).forEachLine { line ->
val numLine = line.filter { it.isDigit() }
val num = when (numLine.length) {
1 -> numLine + numLine
2 -> numLine
else -> numLine.removeRange(1, numLine.lastIndex)
}.toIntOrNull()
if (num != null) result += num
}
println(result)
}
fun day1_part2(path: String) {
var result = 0
val map = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9",
)
val substrings = map.flatMap { listOf(it.key, it.value) }
Path(path).forEachLine { line ->
val numLine = findAllOverlappingMatches(line, substrings).joinToString("") { map[it] ?: it }
val num = when (numLine.length) {
1 -> numLine + numLine
2 -> numLine
else -> numLine.removeRange(1, numLine.lastIndex)
}.toIntOrNull()
if (num != null) result += num
}
println(result)
}
fun findAllOverlappingMatches(input: String, substrings: List<String>): List<String> {
val matches = mutableListOf<String>()
for (i in input.indices) {
for (j in i + 1..input.length) {
val substring = input.substring(i, j)
if (substrings.contains(substring)) {
matches.add(substring)
}
}
}
return matches
} | 0 | Kotlin | 0 | 0 | c301358dd55b456337857a8a63a300974f6b8acb | 1,588 | adventOfCode2023 | MIT License |
src/main/kotlin/com/dvdmunckhof/aoc/event2023/Day06.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2023
import com.dvdmunckhof.aoc.multiply
import kotlin.math.pow
import kotlin.math.sqrt
class Day06(private val input: List<String>) {
fun solvePart1(): Int {
val (times, distances) = input.map { line -> line.split(' ').mapNotNull(String::toIntOrNull) }
val wins = times.zip(distances).map { (time, distance) ->
(1..<time).count { t -> t * (time - t) > distance }
}
return wins.filter { it > 0 }.multiply()
}
fun solvePart2(): Long {
val (time, distance) = input.map { line -> line.filter(Char::isDigit).toLong() }
val (a, b) = solveQuadraticEquation(-1.0, time.toDouble(), -distance.toDouble())
return b.toLong() - a.toLong()
}
private fun solveQuadraticEquation(a: Double, b: Double, c: Double): Pair<Double, Double> {
val discriminant = b.pow(2) - (4 * a * c)
val root1 = (-b + sqrt(discriminant)) / (2 * a)
val root2 = (-b - sqrt(discriminant)) / (2 * a)
return root1 to root2
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,047 | advent-of-code | Apache License 2.0 |
code/GeneticAlgorithm/GeneticAlgorithm/src/main/kotlin/GA.kt | Artificial-Intelligence-Games | 690,504,479 | false | {"Kotlin": 21550, "Prolog": 19264} | import java.lang.Math.random
/**
* Implementação do Algoritmo Genético, inspirado em mutações genéticas a nivel bioloógico.
* O agoritmo admite 3 fases por cada ciclo (epoch):
* Seleção --------> Reprodução ---------> Mutação
*
* @param T é o tipo do invididuo.
* @property population a collection of individuals to start optimization.
* @property score a function which scores the fitness of an individual. Higher fitness is better. É o numero total de conflitos, menor numero = maior fitness
* @property cross a function which implements the crossover of two individuals resulting in a child.
* @property mutate a function which mutates a given individual.
* @property select a function which implements a selection strategy of an individual from the population.
*/
class GA<T>(
var population: Collection<T>,
val score: (individual: T) -> Double,
val cross: (parents: Pair<T, T>) -> T,
val mutate: (individual: T) -> T,
val select: (scoredPopulation: Collection<Pair<Double, T>>) -> T) {
/**
* @return O melhor individuo, após o número de epochs ter executado sob a população dada.
*
* @param epochs - numero de epochs (ciclos de mutação)
* @param mutationProbability - valor entre 0 e 1 que define a probabilidade do Filho ser mutado
*/
fun run(epochs: Int = 1000, mutationProbability: Double = 0.1): T {
var scoredPopulation = population.map { Pair(score(it), it) }.sortedByDescending { it.first }
for (i in 0..epochs)
scoredPopulation = scoredPopulation
.map { Pair(select(scoredPopulation), select(scoredPopulation)) }
.map { cross(it) }
.map { if (random() <= mutationProbability) mutate(it) else it }
.map { Pair(score(it), it) }
.sortedByDescending { it.first }
return scoredPopulation.first().second
}
}
/**
* Exemplo do Array Binário, obter o máximo numero de 1's possivel num individuo.
*/
fun binaryArrayExample() : List<Int>{
val population = (1..100).map { (1..10).map { if (random() < 0.5) 0 else 1 } }
val algorithm = GA(
population,
score = { it.count{it==1}.toDouble()},
cross = ::crossover,
mutate = ::mutation,
select = ::fitnessProportionateSelection
)
return algorithm.run()
}
fun sudokuSolver(template : String) : List<List<Cell>> {
val boardTemplate = getBoardFromTemplate(template)
println("Initial Board: ")
boardTemplate.print()
println()
println()
val population = (1 .. 100).map {boardTemplate.fillWithRandValues().board}
val algorithm = GA<List<List<Cell>>>(
population,
score = {81 - Board(it).getTotalCost().toDouble()},
cross = ::sudokuCrossover,
mutate = ::sudokuMutation,
select = ::sudokuSelectionTournament
)
return algorithm.run()
}
fun main(){
//val result = binaryArrayExample()
val result = sudokuSolver(".5..83.17...1..4..3.4..56.8....3...9.9.8245....6....7...9....5...729..861.36.72.4") //result vai ser uma board com Score é 0
print("Best individual: ")
result.forEach { print(it) }
} | 0 | Kotlin | 0 | 1 | 03419d7db9cbdec371abf8be565e79b181ad8d19 | 3,202 | Sudoku-Solver | MIT License |
2021/src/main/kotlin/de/skyrising/aoc2021/day24/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day24
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import java.util.function.IntFunction
@PuzzleName("Arithmetic Logic Unit")
fun PuzzleInput.part1() = solve(this, intArrayOf(9, 8, 7, 6, 5, 4, 3, 2, 1))
fun PuzzleInput.part2() = solve(this, intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9))
data class Box<T>(val value: T)
private const val CACHE_SIZE = 192
class IntIntCache<T> {
private val cache = Int2ObjectOpenHashMap<Int2ObjectLinkedOpenHashMap<Box<T>>>()
inline fun eval(a: Int, b: Int, fn: (Int, Int) -> T): T {
val v = this[a, b]
if (v != null) return v.value
val value = fn(a, b)
this[a, b] = value
return value
}
operator fun set(a: Int, b: Int, value: T) {
val level1 = cache.computeIfAbsent(a, IntFunction { Int2ObjectLinkedOpenHashMap(CACHE_SIZE + 1) })
level1.putAndMoveToFirst(b, Box(value))
if (level1.size > CACHE_SIZE) level1.removeLast()
}
operator fun get(a: Int, b: Int): Box<T>? = cache[a]?.getAndMoveToFirst(b)
}
fun solve(input: PuzzleInput, order: IntArray): String? {
val cache = IntIntCache<String?>()
return solveRecursive(input.lines.map {
val parts = it.split(' ')
AluInstr(parts[0], *parts.subList(1, parts.size).map(::AluSymbol).toTypedArray())
}, cache, order, 0, 0)
}
data class AluSymbol(val value: String) {
val intValue = value.toIntOrNull()
}
class AluInstr(op: String, private vararg val args: AluSymbol) {
val op = op[1]
operator fun get(arg: Int) = args[arg]
}
fun solveRecursive(instr: List<AluInstr>, cache: IntIntCache<String?>, order: IntArray, step: Int, z: Int): String? {
for (input in order) {
val state = State(0, 0, z, 0)
state[instr[step][0].value] = input
var i = step + 1
while (true) {
if (i == instr.size) {
if (state.z == 0) return input.toString()
break
}
val ins = instr[i]
when (ins.op) {
// iNp
'n' -> {
val r = cache.eval(i, state.z) { a, b -> solveRecursive(instr, cache, order, a, b) }
if (r != null) return "$input$r"
break
}
// aDd
'd' -> state[ins[0].value] = state[ins[0]] + state[ins[1]]
// mUl
'u' -> state[ins[0].value] = state[ins[0]] * state[ins[1]]
// dIv
'i' -> state[ins[0].value] = state[ins[0]] / state[ins[1]]
// mOd
'o' -> state[ins[0].value] = state[ins[0]] % state[ins[1]]
// eQl
'q' -> state[ins[0].value] = if (state[ins[0]] == state[ins[1]]) 1 else 0
}
i++
}
}
return null
}
data class State(var x: Int = 0, var y: Int = 0, var z: Int = 0, var w: Int = 0) {
operator fun get(index: AluSymbol): Int {
val intValue = index.intValue
if (intValue != null) return intValue
return when (index.value[0]) {
'x' -> x
'y' -> y
'z' -> z
'w' -> w
else -> throw IllegalArgumentException(index.value)
}
}
operator fun set(index: String, value: Int) {
when (index[0]) {
'x' -> x = value
'y' -> y = value
'z' -> z = value
'w' -> w = value
}
}
} | 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 3,566 | aoc | MIT License |
capitulo5/src/main/kotlin/5.27(Maior Divisor Comum).kt | Cursos-Livros | 667,537,024 | false | {"Kotlin": 104564} | //5.27 (Maior Divisor Comum) O máximo divisor comum (MDC) de dois números inteiros é o maior
//inteiro que divide igualmente cada um dos dois números. Escreva um método gcd que retorne o maior
//divisor comum de dois números inteiros. [Dica: você pode querer usar o algoritmo de Euclides. Você pode encontrar
//informações sobre isso em en.wikipedia.org/wiki/Euclidean_algorithm.] Incorpore o método
//em um aplicativo que lê dois valores do usuário e exibe o resultado.
fun main() {
println("Digite o 1 numero")
var inteiro1 = leInput11()
println("Digite o 2 numero")
var inteiro2 = leInput11()
val resultado = calculaMdc(inteiro1, inteiro2)
println("MDC entre os valores: $resultado ")
}
fun leInput11(): Int {
val input = readLine() ?: "0"
return input.toInt()
}
fun calculaMdc(inteiro1: Int, inteiro2: Int): Int {
var numeroA = inteiro1
var numeroB = inteiro2
while (numeroB!= 0) {
val resto = numeroA % numeroB
numeroA = numeroB
numeroB = resto
}
return numeroA
}
| 0 | Kotlin | 0 | 0 | f2e005135a62b15360c2a26fb6bc2cbad18812dd | 1,066 | Kotlin-Como-Programar | MIT License |
src/commonMain/kotlin/ru/spbstu/wheels/Comparables.kt | vorpal-research | 185,828,983 | false | null | package ru.spbstu.wheels
inline class ComparatorScope<T>(val comparator: Comparator<T>) {
operator fun T.compareTo(that: T) = comparator.compare(this, that)
fun Iterable<T>.maxOrNull() = maxWithOrNull(comparator)
fun Iterable<T>.minOrNull() = minWithOrNull(comparator)
fun Collection<T>.sorted() = sortedWith(comparator)
fun MutableList<T>.sort() = sortWith(comparator)
}
inline fun <T, R> Comparator<T>.use(body: ComparatorScope<T>.() -> R) = ComparatorScope(this).body()
fun combineCompares(cmp0: Int, cmp1: Int): Int = when {
cmp0 != 0 -> cmp0
else -> cmp1
}
fun combineCompares(cmp0: Int, cmp1: Int, cmp2: Int): Int = when {
cmp0 != 0 -> cmp0
cmp1 != 0 -> cmp1
else -> cmp2
}
fun combineCompares(vararg cmps: Int): Int = cmps.find { it != 0 } ?: 0
fun <A: Comparable<A>> Pair<A, A>.sorted() = when {
first <= second -> this
else -> second to first
}
fun <A> Pair<A, A>.sortedWith(cmp: Comparator<A>) = cmp.use {
when {
first <= second -> this@sortedWith
else -> second to first
}
}
fun <A> Triple<A, A, A>.sortedWith(cmp: Comparator<A>) = cmp.use {
when {
first <= second -> when {
// first <= second && second <= third
second <= third -> this@sortedWith // Triple(first, second, third)
// first <= second && third < second && first <= third
// => first <= third < second
first <= third -> Triple(first, third, second)
// first <= second && third < second && third < first
// => third < first <= second
else -> Triple(third, first, second)
}
// second < first
else -> when {
// second < first && third <= second
// => third <= second < first
third <= second -> Triple(third, second, first)
// second < first && second < third && third <= first
// => second < third <= first
third <= first -> Triple(second, third, first)
// second < first && second < third && first < third
// => second < first < third
else -> Triple(second, first, third)
}
}
}
fun <A: Comparable<A>> Triple<A, A, A>.sorted() = sortedWith(naturalOrder())
| 0 | Kotlin | 1 | 0 | 389f9c290d496aae3d4f5eaa2a0d4f4863f281c2 | 2,261 | kotlin-wheels | MIT License |
src/main/kotlin/Puzzle7.kt | namyxc | 317,466,668 | false | null | object Puzzle7 {
@JvmStatic
fun main(args: Array<String>) {
val rules = Rules(Puzzle7::class.java.getResource("puzzle7.txt").readText().split("\n"))
val sumOfAvailableOuterColors = rules.countContainingBags("shiny gold")
println(sumOfAvailableOuterColors)
val sumOfAvailableInnreColors = rules.countAllInnerBags("shiny gold")
println(sumOfAvailableInnreColors)
}
class Rules {
val bagRules = HashMap<String, HashMap<String, Int>?>()
constructor(input: List<String>){
input.forEach { line ->
val bagColorRegexp = "^([^ ]+ [^ ]+) bags contain (.+)\\.$".toRegex()
val bagListRegexp = "^(\\d+) ([^ ]+ [^ ]+) bags?$".toRegex()
val matchResult = bagColorRegexp.find(line)
val bagColor = matchResult?.groups?.get(1)?.value!!
val containingString = matchResult.groups[2]?.value!!
if (containingString == "no other bags"){
bagRules[bagColor] = null
}else{
val bagStringList = containingString.split(", ")
bagRules[bagColor] = HashMap()
bagStringList.forEach { bagCountString ->
val bagMatchResult = bagListRegexp.find(bagCountString)
val bagCount = bagMatchResult?.groups?.get(1)?.value?.toInt()!!
val innerBagColor = bagMatchResult.groups[2]?.value!!
bagRules[bagColor]!![innerBagColor] = bagCount
}
}
}
}
fun countContainingBags(color: String): Int {
val foundParents = HashSet<String>()
var count: Int
var addedCount: Int
var lookFor: HashSet<String> = hashSetOf(color)
do {
count = foundParents.count()
val parents = bagRules.filter { rule ->
if (rule.value != null)
lookFor.any { rule.value!!.containsKey(it) }
else
false
}
lookFor = parents.keys.toHashSet()
foundParents.addAll(lookFor)
addedCount = foundParents.count() - count
}while (addedCount > 0)
return foundParents.count()
}
fun countAllInnerBags(color: String) = countInnerBags(color) - 1
private fun countInnerBags(color: String): Int {
return if (bagRules[color] == null){
1
}else{
var retVal = 1
bagRules[color]!!.forEach { c, cnt ->
retVal += cnt * countInnerBags(c)
}
retVal
}
}
}
} | 0 | Kotlin | 0 | 0 | 60fa6991ac204de6a756456406e1f87c3784f0af | 2,834 | adventOfCode2020 | MIT License |
src/main/kotlin/Day03.kt | rogierbom1 | 573,165,407 | false | {"Kotlin": 5253} | package main.kotlin
import readInput
private fun Char.toPriority(): Int {
val priorityMap = ('a'..'z').associateWith { it - 'a' + 1 } + ('A'..'Z').associateWith { it - 'A' + 27 }
return priorityMap[this] ?: throw Exception("Unmapped character")
}
fun main() {
fun part1(input: List<String>): Int = input.map{ rucksack ->
rucksack.take(rucksack.length / 2).toSet() to rucksack.substring(rucksack.length / 2).toSet()
}.mapNotNull { compartments ->
compartments.first.intersect(compartments.second).firstOrNull()
}.sumOf { item ->
item.toPriority()
}
fun part2(input: List<String>): Int = input.chunked(3).mapNotNull { rucksacks ->
rucksacks[0].toSet()
.intersect(rucksacks[1].toSet())
.intersect(rucksacks[2].toSet())
.firstOrNull()
}.sumOf { badge ->
badge.toPriority()
}
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 | b7a03e95785cb4a2ec0bfa170f4f667fc574c1d2 | 1,142 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/g0401_0500/s0472_concatenated_words/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0401_0500.s0472_concatenated_words
// #Hard #Array #String #Dynamic_Programming #Depth_First_Search #Trie
// #2022_12_29_Time_484_ms_(100.00%)_Space_48_MB_(100.00%)
class Solution {
private val ans: MutableList<String> = ArrayList()
private var root: Trie? = null
fun findAllConcatenatedWordsInADict(words: Array<String>): List<String> {
root = Trie()
words.sortWith { a: String, b: String ->
a.length.compareTo(b.length)
}
for (word in words) {
var ptr = root
if (search(word, 0, 0)) {
ans.add(word)
} else {
for (j in 0 until word.length) {
if (ptr!!.nxt[word[j].code - 'a'.code] == null) {
ptr.nxt[word[j].code - 'a'.code] = Trie()
}
ptr = ptr.nxt[word[j].code - 'a'.code]
}
ptr!!.endHere = true
}
}
return ans
}
private fun search(cur: String, idx: Int, wordCnt: Int): Boolean {
if (idx == cur.length) {
return wordCnt >= 2
}
var ptr = root
for (i in idx until cur.length) {
if (ptr!!.nxt[cur[i].code - 'a'.code] == null) {
return false
}
if (ptr.nxt[cur[i].code - 'a'.code]!!.endHere) {
val ret = search(cur, i + 1, wordCnt + 1)
if (ret) {
return true
}
}
ptr = ptr.nxt[cur[i].code - 'a'.code]
}
return ptr!!.endHere && wordCnt >= 2
}
private class Trie internal constructor() {
var nxt: Array<Trie?>
var endHere: Boolean
init {
nxt = arrayOfNulls(26)
endHere = false
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,841 | LeetCode-in-Kotlin | MIT License |
src/Day01.kt | phoenixli | 574,035,552 | false | {"Kotlin": 29419} | fun main() {
fun part1(input: List<String>): Int {
var maxCalories = 0
var currCalories = 0
input.forEach {
val foodCal = it.toIntOrNull()
if (foodCal != null) {
currCalories += foodCal
} else {
maxCalories = maxOf(currCalories, maxCalories)
currCalories = 0
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
val allCalories = mutableListOf<Int>()
var currCalories = 0
input.forEach {
val foodCal = it.toIntOrNull()
if (foodCal != null) {
currCalories += foodCal
} else {
allCalories.add(currCalories)
currCalories = 0
}
}
return allCalories.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5f993c7b3c3f518d4ea926a792767a1381349d75 | 1,129 | Advent-of-Code-2022 | Apache License 2.0 |
src/day01/Task.kt | dniHze | 433,447,720 | false | {"Kotlin": 35403} | package day01
import readInput
fun main() {
val input = readInput("day01")
println(solvePartOne(input))
println(solvePartTwo(input))
}
fun solvePartOne(input: List<String>): Int =
input.map { value -> value.toInt() }
.solveIncreasingTimes()
fun solvePartTwo(input: List<String>): Int = input.map { value -> value.toInt() }
.windowed(size = 3, step = 1, partialWindows = false) { list ->
list.sum()
}
.solveIncreasingTimes()
internal fun Iterable<Int>.solveIncreasingTimes(): Int = fold(Result()) { acc, value ->
val newCounter = when {
acc.previousHighest != null && value > acc.previousHighest -> acc.counter + 1
else -> acc.counter
}
acc.copy(previousHighest = value, counter = newCounter)
}.counter
data class Result(
val previousHighest: Int? = null,
val counter: Int = 0,
)
| 0 | Kotlin | 0 | 1 | f81794bd57abf513d129e63787bdf2a7a21fa0d3 | 866 | aoc-2021 | Apache License 2.0 |
src/main/kotlin/dev/siller/aoc2023/Day07.kt | chearius | 725,594,554 | false | {"Kotlin": 50795, "Shell": 299} | package dev.siller.aoc2023
data object Day07 : AocDayTask<UInt, UInt>(
day = 7,
exampleInput =
"""
|32T3K 765
|T55J5 684
|KK677 28
|KTJJT 220
|QQQJA 483
""".trimMargin(),
expectedExampleOutputPart1 = 6440u,
expectedExampleOutputPart2 = 5905u
) {
private enum class Card(val id: Char) {
JOKER('*'),
TWO('2'),
THREE('3'),
FOUR('4'),
FIVE('5'),
SIX('6'),
SEVEN('7'),
EIGHT('8'),
NINE('9'),
TEN('T'),
JACK('J'),
QUEEN('Q'),
KING('K'),
ACE('A')
}
private enum class HandType {
FIVE_OF_A_KIND,
FOUR_OF_A_KIND,
FULL_HOUSE,
THREE_OF_A_KIND,
TWO_PAIR,
ONE_PAIR,
HIGH_CARD
}
private class Hand(
val cards: List<Card>
) {
init {
check(cards.size == 5) { "A hand must contain exactly 5 cards!" }
}
val type: HandType = getHandType()
@Suppress("detekt:CyclomaticComplexMethod")
private fun getHandType(): HandType {
// occurrences without jokers
val cardOccurrencesHigherThanOne =
cards
.filterNot { card -> card == Card.JOKER }
.groupBy(Card::id)
.values
.map(List<Card>::size)
.filter { size -> size > 1 }
.sortedDescending()
val jokersCount = cards.count { card -> card == Card.JOKER }
return when (cardOccurrencesHigherThanOne.size) {
2 -> { // Possible combinations - 3,2 ; 2,2
val (firstOccurrencesCount, secondOccurrencesCount) = cardOccurrencesHigherThanOne
if (firstOccurrencesCount + jokersCount == 3 && secondOccurrencesCount == 2) {
HandType.FULL_HOUSE
} else {
HandType.TWO_PAIR
}
}
1 -> {
when (cardOccurrencesHigherThanOne.single() + jokersCount) {
5 -> HandType.FIVE_OF_A_KIND
4 -> HandType.FOUR_OF_A_KIND
3 -> HandType.THREE_OF_A_KIND
else -> HandType.ONE_PAIR
}
}
else ->
when (jokersCount) {
5, 4 -> HandType.FIVE_OF_A_KIND
3 -> HandType.FOUR_OF_A_KIND
2 -> HandType.THREE_OF_A_KIND
1 -> HandType.ONE_PAIR
else -> HandType.HIGH_CARD
}
}
}
override fun toString(): String {
return "Hand(cards=$cards, type=$type)"
}
}
private data class HandAndBid(
val hand: Hand,
val bid: UInt
)
override fun runPart1(input: List<String>): UInt =
input
.map(::parseHandWithBid)
.sortedWith(compareHands)
.mapIndexed { index, (_, bid) ->
bid * (index.toUInt() + 1u)
}
.sum()
override fun runPart2(input: List<String>): UInt =
input
.asSequence()
.map { line -> line.replace(Card.JACK.id, Card.JOKER.id) } // replace Jack with Joker
.map(::parseHandWithBid)
.sortedWith(compareHands)
.mapIndexed { index, (_, bid) ->
bid * (index.toUInt() + 1u)
}
.sum()
private fun parseHandWithBid(line: String): HandAndBid {
val (cardIds, bid) = line.split(' ', limit = 2)
val cards = cardIds.map { cardId -> Card.entries.first { card -> card.id == cardId } }
return HandAndBid(
hand = Hand(cards),
bid = bid.toUInt()
)
}
private val compareHands: (hand1: HandAndBid, hand2: HandAndBid) -> Int = { (hand1, _), (hand2, _) ->
val compareTypes = hand2.type.compareTo(hand1.type)
if (compareTypes == 0) {
hand2.cards
.zip(hand1.cards)
.map { (card1, card2) ->
card2.compareTo(card1)
}
.firstOrNull { result -> result != 0 } ?: 0
} else {
compareTypes
}
}
}
| 0 | Kotlin | 0 | 0 | fab1dd509607eab3c66576e3459df0c4f0f2fd94 | 4,444 | advent-of-code-2023 | MIT License |
src/day14/Day14.kt | tobihein | 569,448,315 | false | {"Kotlin": 58721} | package day14
import readInput
class Day14 {
fun part1(): Int {
val readInput = readInput("day14/input")
return part1(readInput)
}
fun part2(): Int {
val readInput = readInput("day14/input")
return part2(readInput)
}
fun part1(input: List<String>): Int {
val maxColumn = getMaxColumn(input)
val maxRow = getMaxRow(input)
val board = Array(maxRow + 2) { Array(maxColumn * maxRow) { '.' } }
initializeBoard(input, board)
var sandCounter = 0
while (pourSand(board, maxRow)) {
sandCounter++
}
return sandCounter
}
fun part2(input: List<String>): Int {
val maxColumn = getMaxColumn(input)
val maxRow = getMaxRow(input) + 2
val board = Array(maxRow + 2) { Array(maxColumn * maxRow) { '.' } }
initializeBoard(input, board)
for (i in 0 until board[0].size) {
board[maxRow][i] = '#'
}
var sandCounter = 0
while (pourSand(board)) {
sandCounter++
}
return sandCounter
}
private fun pourSand(board: Array<Array<Char>>, maxRow: Int): Boolean {
var previousPos = Pair(500, 0)
var nextPos: Pair<Int, Int>? = previousPos
var finish = false
while (nextPos != null && !finish) {
nextPos = getNextPos(board, previousPos)
if (nextPos != null) {
finish = (nextPos.second == maxRow)
previousPos = nextPos
}
}
if (!finish) {
board[previousPos.second][previousPos.first] = 'o'
}
return !finish
}
private fun pourSand(board: Array<Array<Char>>): Boolean {
if (board[0][500] == '.') {
var previousPos = Pair(500, 0)
var nextPos: Pair<Int, Int>? = previousPos
while (nextPos != null) {
nextPos = getNextPos(board, previousPos)
if (nextPos != null) {
previousPos = nextPos
}
}
board[previousPos.second][previousPos.first] = 'o'
return true
}
return false
}
private fun getNextPos(board: Array<Array<Char>>, sandPos: Pair<Int, Int>): Pair<Int, Int>? {
val nextRow = sandPos.second + 1
if (board.size > nextRow) {
val below = board[nextRow][sandPos.first]
if (below == '.') {
return Pair(sandPos.first, nextRow)
}
val leftPos = sandPos.first - 1
if (leftPos >= 0) {
val left = board[nextRow][leftPos]
if (left == '.')
return Pair(leftPos, nextRow)
}
val rightpos = sandPos.first + 1
if (board[0].size > rightpos) {
val right = board[nextRow][rightpos]
if (right == '.') {
return Pair(rightpos, nextRow)
}
}
}
return null
}
private fun initializeBoard(input: List<String>, board: Array<Array<Char>>) {
input.forEach {
val paths = it.split("->").map { it.trim().split(",") }.map { Pair(it[0].toInt(), it[1].toInt()) }
for (i in 0 until paths.size - 1) {
drawLine(paths[i], paths[i + 1], board)
}
}
}
private fun drawLine(from: Pair<Int, Int>, to: Pair<Int, Int>, board: Array<Array<Char>>) {
if (from.first == to.first) {
for (i in Math.min(from.second, to.second)..Math.max(from.second, to.second)) {
board[i][from.first] = '#'
}
} else if (from.second == to.second) {
for (i in Math.min(from.first, to.first)..Math.max(from.first, to.first)) {
board[from.second][i] = '#'
}
}
}
private fun getMaxColumn(input: List<String>) = input.map { it.split("->") }.map { maxColumnValue(it) }.max()
private fun getMaxRow(input: List<String>) = input.map { it.split("->") }.map { maxRowValue(it) }.max()
private fun maxColumnValue(line: List<String>) = line.map { it.trim() }.map { it.split(",")[0].toInt() }.max()
private fun maxRowValue(line: List<String>) = line.map { it.trim() }.map { it.split(",")[1].toInt() }.max()
}
| 0 | Kotlin | 0 | 0 | af8d851702e633eb8ff4020011f762156bfc136b | 4,354 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxPathSum.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 124. Binary Tree Maximum Path Sum
* @see <a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/">Source</a>
*/
fun interface MaxPathSum {
operator fun invoke(root: TreeNode?): Int
}
class MaxPathSumRecursion : MaxPathSum {
private var maxSum = Int.MIN_VALUE
override operator fun invoke(root: TreeNode?): Int {
maxGain(root)
return maxSum
}
private fun maxGain(node: TreeNode?): Int {
if (node == null) return 0
// max sum on the left and right sub-trees of node
val leftGain = max(maxGain(node.left), 0)
val rightGain = max(maxGain(node.right), 0)
// the price to start a new path where `node` is a highest node
val priceNewPath: Int = node.value + leftGain + rightGain
// update max_sum if it's better to start a new path
maxSum = max(maxSum, priceNewPath)
// for recursion :
// return the max gain if continue the same path
return node.value + max(leftGain, rightGain)
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,700 | kotlab | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2023/iteration/Product.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.iteration
/* pair */
fun <A, B> Iterable<A>.product(other: Iterable<B>): Sequence<Pair<A, B>> = sequence {
for (a in this@product) {
for (b in other) {
yield(Pair(a, b))
}
}
}
fun <A, B> Pair<Iterable<A>, Iterable<B>>.product(): Sequence<Pair<A, B>> = sequence {
for (a in first) {
for (b in second) {
yield(Pair(a, b))
}
}
}
/* triple */
fun <A, B, C> Iterable<A>.product(first: Iterable<B>, second: Iterable<C>): Sequence<Triple<A, B, C>> = sequence {
for (a in this@product) {
for (b in first) {
for (c in second) {
yield(Triple(a, b, c))
}
}
}
}
fun <A, B, C> Triple<Iterable<A>, Iterable<B>, Iterable<C>>.product(): Sequence<Triple<A, B, C>> = sequence {
for (a in first) {
for (b in second) {
for (c in third) {
yield(Triple(a, b, c))
}
}
}
}
/* list */
fun <T> List<List<T>>.product(): Sequence<List<T>> = sequence {
if (isNotEmpty()) {
val indices = IntArray(size) { 0 }
var searching = true
yield(product(indices))
while (searching) {
var found = false
var index = indices.size - 1
while (index >= 0 && !found) {
indices[index]++
if (indices[index] >= get(index).size) {
indices[index] = 0
index--
} else {
yield(product(indices))
found = true
}
}
if (!found) {
searching = false
}
}
}
}
private fun <T> List<List<T>>.product(indices: IntArray): List<T> {
return indices.zip(this).map { (index, list) ->
list[index]
}
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 1,881 | advent-2023 | ISC License |
src/Day10/Day10.kt | brhliluk | 572,914,305 | false | {"Kotlin": 16006} | fun main() {
fun part1(input: List<String>): Int {
var register = 1
var cycle = 0
val signalStrengths = mutableListOf<Int>()
val importantCycles = listOf(20, 60, 100, 140, 180, 220)
input.forEach { instruction ->
when {
instruction.startsWith("noop") -> {
cycle += 1
if (cycle in importantCycles) signalStrengths.add(cycle * register)
}
instruction.startsWith("addx") -> {
cycle += 2
if (cycle - 1 in importantCycles) signalStrengths.add((cycle - 1) * register)
if (cycle in importantCycles) signalStrengths.add(cycle * register)
register += instruction.trimStart('a', 'd', 'x').trim().toInt()
}
else -> error("Unknown instruction")
}
}
return signalStrengths.sum()
}
fun part2(input: List<String>): Int {
var register = 1
var cycle = 0
val signalStrengths = mutableListOf<Int>()
val importantCycles = listOf(20, 60, 100, 140, 180, 220)
input.forEach { instruction ->
when {
instruction.startsWith("noop") -> {
cycle += 1
if (cycle in importantCycles) signalStrengths.add(cycle * register)
}
instruction.startsWith("addx") -> {
cycle += 2
if (cycle - 1 in importantCycles) signalStrengths.add((cycle - 1) * register)
if (cycle in importantCycles) signalStrengths.add(cycle * register)
register += instruction.trimStart('a', 'd', 'x').trim().toInt()
}
else -> error("Unknown instruction")
}
}
return signalStrengths.sum()
}
val input = readInput("Day10")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 96ac4fe0c021edaead8595336aad73ef2f1e0d06 | 1,989 | kotlin-aoc | Apache License 2.0 |
src/main/kotlin/days/y2023/day16/Day16.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2023.day16
import util.InputReader
typealias PuzzleLine = String
typealias PuzzleInput = List<PuzzleLine>
class Day16(val input: PuzzleInput) {
val maze = Maze(Grid2d.from(input))
fun partOne(): Int {
val start = Beam(Position(-1, 0), Direction.RIGHT)
return energyFor(mutableListOf(start))
}
fun partTwo(): Int {
val starts = listOf(
input[0].indices.map { x -> Beam(Position(x, -1), Direction.DOWN) },
input[0].indices.map { x -> Beam(Position(x, input.size), Direction.UP) },
input.indices.map { y -> Beam(Position(-1, y), Direction.RIGHT) },
input.indices.map { y -> Beam(Position(input[0].length, y), Direction.LEFT) }
).flatten()
return starts.maxOf { energyFor(mutableListOf(it)) }
}
private fun energyFor(startQueue: List<Beam>): Int {
val energised = mutableSetOf<Position>()
val queue = startQueue.toMutableList()
val alreadyTravelled = mutableSetOf<Pair<Position, Direction>>()
while (queue.isNotEmpty()) {
val beam = queue.removeFirst()
val next = maze.advance(alreadyTravelled, energised, beam)
queue.addAll(next)
}
return energised.size
}
}
data class Grid2d(val chars: List<List<Char>>) {
fun contains(position: Position): Boolean {
return position.y in chars.indices && position.x in chars[position.y].indices
}
companion object {
fun from(lines: List<String>): Grid2d {
return Grid2d(lines.map { it.toList() })
}
}
}
data class Position(val x: Int, val y: Int)
enum class Direction {
UP, DOWN, LEFT, RIGHT
}
data class Beam(val position: Position, val direction: Direction)
data class Maze(val grid: Grid2d)
fun Maze.advance(
alreadyTravelled: MutableSet<Pair<Position, Direction>>,
energized: MutableSet<Position>,
beam: Beam
): List<Beam> {
if (alreadyTravelled.contains(beam.position to beam.direction)) return emptyList()
alreadyTravelled.add(beam.position to beam.direction)
val nextBeam = beam.advance()
if (!grid.contains(nextBeam.position)) return emptyList()
energized.add(nextBeam.position)
val nextPosition = grid[nextBeam.position]
val deflected = getDeflected(nextPosition, nextBeam)
return deflected
}
private fun getDeflected(square: Char, beam: Beam) =
when (square) {
'.' -> listOf(beam)
'|' -> when (beam.direction) {
Direction.UP, Direction.DOWN -> listOf(beam)
Direction.LEFT, Direction.RIGHT -> listOf(
beam.copy(direction = Direction.UP),
beam.copy(direction = Direction.DOWN)
)
}
'-' -> when (beam.direction) {
Direction.UP, Direction.DOWN -> listOf(
beam.copy(direction = Direction.LEFT),
beam.copy(direction = Direction.RIGHT)
)
Direction.LEFT, Direction.RIGHT -> listOf(beam)
}
'/' -> when (beam.direction) {
Direction.UP -> listOf(beam.copy(direction = Direction.RIGHT))
Direction.DOWN -> listOf(beam.copy(direction = Direction.LEFT))
Direction.LEFT -> listOf(beam.copy(direction = Direction.DOWN))
Direction.RIGHT -> listOf(beam.copy(direction = Direction.UP))
}
'\\' -> when (beam.direction) {
Direction.UP -> listOf(beam.copy(direction = Direction.LEFT))
Direction.DOWN -> listOf(beam.copy(direction = Direction.RIGHT))
Direction.LEFT -> listOf(beam.copy(direction = Direction.UP))
Direction.RIGHT -> listOf(beam.copy(direction = Direction.DOWN))
}
else -> TODO("$square")
}
fun Beam.advance() = when (direction) {
Direction.UP -> Beam(Position(position.x, position.y - 1), direction)
Direction.DOWN -> Beam(Position(position.x, position.y + 1), direction)
Direction.LEFT -> Beam(Position(position.x - 1, position.y), direction)
Direction.RIGHT -> Beam(Position(position.x + 1, position.y), direction)
}
private operator fun Grid2d.get(position: Position): Char {
return chars[position.y][position.x]
}
fun main() {
val year = 2023
val day = 16
val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day)
val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day)
fun partOne(input: PuzzleInput) = Day16(input).partOne()
println("Example 1: ${partOne(exampleInput)}")
println("Puzzle 1: ${partOne(puzzleInput)}")
println("Example 2: ${Day16(exampleInput).partTwo()}")
println("Puzzle 2: ${Day16(puzzleInput).partTwo()}")
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 4,713 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/aoc2022/Day08.kt | nguyen-anthony | 572,781,123 | false | null | package aoc2022
import utils.readInputAsList
import kotlin.math.max
fun main() {
fun isVisibleOutside(map: List<List<Int>>, row: List<Int>, rowIndex: Int, colIndex: Int) : Boolean {
return rowIndex == 0 || colIndex == 0 || rowIndex == map.lastIndex || colIndex == row.lastIndex
}
fun isLeftVisible(row: List<Int>, colIndex: Int, value: Int) : Boolean {
return row.subList(0, colIndex).all { it < value }
}
fun isRightVisible(row: List<Int>, colIndex: Int, value: Int) : Boolean {
return row.subList(colIndex + 1, row.size).all { it < value }
}
fun isUpVisible(map: List<List<Int>>, rowIndex: Int, colIndex: Int, value: Int) : Boolean {
return map.subList(0, rowIndex).all { it[colIndex] < value }
}
fun isDownVisible(map: List<List<Int>>, rowIndex: Int, colIndex: Int, value: Int) : Boolean {
return map.subList(rowIndex + 1, map.size).all { it[colIndex] < value }
}
fun score(map: List<List<Int>>, row: List<Int>, rowIndex: Int, colIndex: Int) : Int {
return if(rowIndex == 0 || colIndex == 0 || rowIndex == map.lastIndex || colIndex == row.lastIndex) 0 else 1
}
fun leftScore(row: List<Int>, colIndex: Int, value: Int) : Int {
return row.subList(0, colIndex).reversed().fold(Pair(0, false)) { (count, found), newValue ->
if (found) Pair(count, true)
else if (newValue >= value) Pair(count + 1, true)
else Pair(count + 1, false)
}.first
}
fun rightScore(row: List<Int>, colIndex: Int, value: Int) : Int {
return row.subList(colIndex+1, row.size).fold(Pair(0, false)) { (count, found), newValue ->
if (found) Pair(count, true)
else if (newValue >= value) Pair(count + 1, true)
else Pair(count + 1, false)
}.first
}
fun upScore(map: List<List<Int>>, rowIndex: Int, colIndex: Int, value: Int) : Int {
return map.subList(0, rowIndex).reversed().fold(Pair(0, false)) { (count, found), list ->
if(found) Pair(count, true)
else if (list[colIndex] >= value) Pair(count + 1, true)
else Pair(count + 1, false)
}.first
}
fun downScore(map: List<List<Int>>, rowIndex: Int, colIndex: Int, value: Int) : Int {
return map.subList(rowIndex + 1, map.size).fold(Pair(0,false)) { (count, found), list ->
if(found) Pair(count,true)
else if (list[colIndex] >= value) Pair(count + 1, true)
else Pair(count + 1, false)
}.first
}
fun part1(input: List<List<Int>>) : Any {
return input.withIndex().fold(0) { count, (rowIndex, row) ->
row.withIndex().fold(count) { rCount, (colIndex, value) ->
if(isVisibleOutside(input, row, rowIndex, colIndex) ||
isLeftVisible(row, colIndex, value) ||
isRightVisible(row, colIndex, value) ||
isUpVisible(input, rowIndex, colIndex, value) ||
isDownVisible(input, rowIndex, colIndex, value)
) rCount + 1 else rCount
}
}
}
fun part2(input: List<List<Int>>) : Any {
return input.withIndex().fold(0) { max, (rowIndex, row) ->
row.withIndex().fold(max) { rMax, (colIndex, value) ->
max(
rMax,
score(input, row, rowIndex, colIndex) *
leftScore(row, colIndex, value) *
rightScore(row, colIndex, value) *
upScore(input, rowIndex, colIndex, value) *
downScore(input, rowIndex, colIndex, value)
)
}
}
}
val input = readInputAsList("Day08", "2022").map { line -> line.toList().map { it.digitToInt() } }
println(part1(input))
println(part2(input))
val testInput = readInputAsList("Day08_test", "2022").map { line -> line.toList().map { it.digitToInt() } }
check(part1(testInput) == 21)
check(part2(testInput) == 8)
} | 0 | Kotlin | 0 | 0 | 9336088f904e92d801d95abeb53396a2ff01166f | 4,081 | AOC-2022-Kotlin | Apache License 2.0 |
2023/src/main/kotlin/sh/weller/aoc/Day08.kt | Guruth | 328,467,380 | false | {"Kotlin": 188298, "Rust": 13289, "Elixir": 1833} | package sh.weller.aoc
object Day08 : SomeDay<String, Long> {
override fun partOne(input: List<String>): Long {
val directions = input.first().toCharArray()
val nodes = input.drop(2)
.associate { line ->
val splitLine = line.split("=").map { it.trim() }
val key = splitLine.first()
val nextNodes = splitLine.last().drop(1).dropLast(1)
.split(",").map { it.trim() }
val left = nextNodes.first()
val right = nextNodes.last()
return@associate key to (left to right)
}
var currentNode = "AAA"
var currentDirectionPointer = 0
var stepCounter = 0L
do {
val (left, right) = nodes[currentNode]!!
val direction = directions[currentDirectionPointer]
currentNode = when (direction) {
'L' -> left
'R' -> right
else -> throw IllegalArgumentException("Unknown Direction")
}
currentDirectionPointer += 1
if (currentDirectionPointer == directions.size) {
currentDirectionPointer = 0
}
stepCounter += 1
} while (currentNode != "ZZZ")
return stepCounter
}
override fun partTwo(input: List<String>): Long {
val directions = input.first().toCharArray()
val nodes = input.drop(2)
.associate { line ->
val splitLine = line.split("=").map { it.trim() }
val key = splitLine.first()
val nextNodes = splitLine.last().drop(1).dropLast(1)
.split(",").map { it.trim() }
val left = nextNodes.first()
val right = nextNodes.last()
return@associate key to (left to right)
}
return nodes.keys
.filter { it.endsWith("A") }
.map {
var currentNode = it
var currentDirectionPointer = 0
var stepCounter = 0L
do {
val (left, right) = nodes[currentNode]!!
val direction = directions[currentDirectionPointer]
currentNode = when (direction) {
'L' -> left
'R' -> right
else -> throw IllegalArgumentException("Unknown Direction")
}
currentDirectionPointer += 1
if (currentDirectionPointer == directions.size) {
currentDirectionPointer = 0
}
stepCounter += 1
} while (currentNode.endsWith("Z").not())
return@map stepCounter
}.reduce { acc, i -> findLCM(acc, i) }
}
// https://www.baeldung.com/kotlin/lcm
private fun findLCM(a: Long, b: Long): Long {
val larger = if (a > b) a else b
val maxLcm = a * b
var lcm = larger
while (lcm <= maxLcm) {
if (lcm % a == 0L && lcm % b == 0L) {
return lcm
}
lcm += larger
}
return maxLcm
}
} | 0 | Kotlin | 0 | 0 | 69ac07025ce520cdf285b0faa5131ee5962bd69b | 3,246 | AdventOfCode | MIT License |
src/Day04.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | fun main() {
@Suppress("unused")
fun log(message: Any?) {
println(message)
}
fun part1(input: List<String>): Int {
return input.sumOf { record ->
// BUG NOTE dammit, forgot to convert these to ints!
val (a, b, x, y) = record.split(",", "-").map { it.toInt() }
// hit https://youtrack.jetbrains.com/issue/KT-46360 here with sumOf() resolution for Int vs Long
(if ((a in x..y && b in x..y) || (x in a..b && y in a..b)) 1 else 0).toInt()
}
}
fun part2(input: List<String>): Int {
return input.sumOf { record ->
val (a, b, x, y) = record.split(",", "-").map { it.toInt() }
(if (a in x..y || b in x..y || x in a..b || y in a..b) 1 else 0).toInt()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test.txt")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04.txt")
println(part1(input))
check(part1(input) == 595)
println(part2(input))
check(part2(input) == 952)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 1,133 | aoc2022 | Apache License 2.0 |
src/main/kotlin/de/pgebert/aoc/days/Day13.kt | pgebert | 724,032,034 | false | {"Kotlin": 65831} | package de.pgebert.aoc.days
import de.pgebert.aoc.Day
import kotlin.math.min
class Day13(input: String? = null) : Day(13, "Point of Incidence", input) {
override fun partOne() = inputString.sumReflectionsBlockwise()
override fun partTwo() = inputString.sumReflectionsBlockwise(tolerance = 1)
private fun String.sumReflectionsBlockwise(tolerance: Int = 0): Int {
val block = mutableListOf<String>()
var result = 0
split("\n").map { it.trimIndent() }.forEach { line ->
if (line.isEmpty()) {
if (block.isNotEmpty()) {
val horizontal = block.findReflection(tolerance)
val vertical = block.transpose().findReflection(tolerance)
result += horizontal * 100 + vertical
block.removeAll { true }
}
} else {
block.add(line)
}
}
return result
}
private fun List<String>.findReflection(tolerance: Int = 0): Int {
for (i in indices) {
if (isReflection(i, tolerance)) {
return i
}
}
return 0
}
private fun List<String>.transpose(): List<String> {
var transposed = mutableListOf<String>()
for (i in first().indices) {
var col = ""
forEach { row ->
col += row[i]
}
transposed.add(col)
}
return transposed
}
private fun List<String>.isReflection(index: Int, tolerance: Int): Boolean {
// reflection before index
val range = min(index, size - index)
if (range <= 0) return false
var diff = (1..range).sumOf { i ->
this[index - i].zip(this[index + i - 1]).count { it.first != it.second }
}
return diff == tolerance
}
}
| 0 | Kotlin | 1 | 0 | a30d3987f1976889b8d143f0843bbf95ff51bad2 | 1,886 | advent-of-code-2023 | MIT License |
implementation/src/main/kotlin/io/github/tomplum/aoc/map/volcano/VolcanoCaveMap.kt | TomPlum | 572,260,182 | false | {"Kotlin": 224955} | package io.github.tomplum.aoc.map.volcano
class VolcanoCaveMap(scan: List<String>) {
private val valveRelationships: Map<Valve, List<Valve>> = scan.associate { line ->
val label = line.removePrefix("Valve ").split(" ")[0].trim()
val flowRate = line.split(" has flow rate=")[1].split(";")[0].toInt()
val tunnels = if (line.contains("tunnels")) {
line.split("tunnels lead to valves ")[1].trim().split(", ").map { label -> Valve(label) }
} else {
listOf(line.split("tunnel leads to valve ")[1].trim()).map { label -> Valve(label) }
}
val valve = Valve(label)
valve.flowRate = flowRate
valve to tunnels
}
fun findMaximumReleasablePressure(): Int {
val valves = valveRelationships.keys.toList()
val distances = valves.fold(mutableMapOf<Valve, MutableMap<Valve, Int>>()) { sources, start ->
valves.forEach { end ->
val targets = sources.getOrPut(start) { mutableMapOf() }
targets[end] = findShortestPath(start, end).size - 1
sources[start] = targets
}
sources
}
val flowingValves = valves.filter { valve -> valve.flowRate > 0 }
val times = calculateValveOpenTime(distances, Valve("AA"), 30, flowingValves)
val pressuresReleased = times.map { rates ->
rates.entries.fold(0) { pressure, (valve, time) -> pressure + valve.flowRate * time }
}
return pressuresReleased.max()
}
fun findMaximumReleasablePressureWithElephant(): Int {
val valves = valveRelationships.keys.toList()
val distances = valves.fold(mutableMapOf<Valve, MutableMap<Valve, Int>>()) { sources, start ->
valves.forEach { end ->
val targets = sources.getOrPut(start) { mutableMapOf() }
targets[end] = findShortestPath(start, end).size - 1
sources[start] = targets
}
sources
}
val flowingValves = valves.filter { valve -> valve.flowRate > 0 }
val times = calculateValveOpenTime(distances, Valve("AA"), 26, flowingValves)
val maxScores = mutableMapOf<List<String>, Int>()
times.forEach { time ->
val key = time.keys.sortedBy { it.flowRate }.map { valve -> valve.label }
val score = time.entries.fold(0) { acc, entry -> acc + valves.find { it == entry.key }!!.flowRate * entry.value }
val maxScore = maxScores.getOrPut(key) { Int.MIN_VALUE }
maxScores[key] = maxOf(score, maxScore)
}
var highest = Int.MIN_VALUE
maxScores.keys.forEach { us ->
maxScores.keys.forEach { elephant ->
val distinctValves = (us + elephant).distinct().size
if (distinctValves == (us.size + elephant.size)) {
highest = maxOf(maxScores[us]!! + maxScores[elephant]!!, highest)
}
}
}
return highest
}
private fun calculateValveOpenTime(
distances: Map<Valve, Map<Valve, Int>>,
source: Valve,
time: Int,
remaining: List<Valve>,
opened: Map<Valve, Int> = mutableMapOf()
): List<Map<Valve, Int>> {
val cumulativeTime = mutableListOf(opened)
remaining.forEachIndexed { i, target ->
val distance = distances[source]?.get(target)!!
val newTime = time - distance - 1
if (newTime < 1) {
return@forEachIndexed
}
val newlyOpened = opened.toMutableMap()
newlyOpened[target] = newTime
val newRemaining = remaining.toMutableList()
newRemaining.removeAt(i)
cumulativeTime.addAll(calculateValveOpenTime(distances, target, newTime, newRemaining, newlyOpened))
}
return cumulativeTime
}
private fun findShortestPath(start: Valve, end: Valve): List<Valve> {
if (start == end) {
return listOf(start)
}
val visited = mutableSetOf(start)
val next = mutableListOf<List<Valve>>()
next.add(listOf(start))
while(next.isNotEmpty()) {
val path = next.removeFirst()
val valve = path.last()
valveRelationships[valve]?.forEach { adjacent ->
if (adjacent in visited) {
return@forEach
}
val updatedPath = path + adjacent
if (adjacent == end) {
return updatedPath
}
visited.add(adjacent)
next.add(updatedPath)
}
}
throw IllegalArgumentException("Could not find path from $start -> $end")
}
} | 0 | Kotlin | 0 | 0 | 703db17fe02a24d809cc50f23a542d9a74f855fb | 4,795 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem2050/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2050
/**
* LeetCode page: [2050. Parallel Courses III](https://leetcode.com/problems/parallel-courses-iii/);
*/
class Solution {
/* Complexity:
* Time O(n+E) and Space O(n+E);
*/
fun minimumTime(n: Int, relations: Array<IntArray>, time: IntArray): Int {
// prerequisites[i]::= the prerequisites of course i
val prerequisites = coursePrerequisites(n, relations)
// memoization[i]::= the earliest finish time of course i
val memoization = hashMapOf<Int, Int>()
return (1..n).maxOf { course ->
earliestFinishTime(course, time, prerequisites, memoization)
}
}
private fun coursePrerequisites(n: Int, relations: Array<IntArray>): List<List<Int>> {
val result = List(n + 1) { mutableListOf<Int>() }
for ((prerequisite, course) in relations) {
result[course].add(prerequisite)
}
return result
}
private fun earliestFinishTime(
course: Int,
time: IntArray,
prerequisites: List<List<Int>>,
memoization: MutableMap<Int, Int>,
): Int {
if (course in memoization) {
return checkNotNull(memoization[course])
}
val earliestStartTime = prerequisites[course].maxOfOrNull {
earliestFinishTime(it, time, prerequisites, memoization)
} ?: 0
val result = earliestStartTime + time[course - 1]
memoization[course] = result
return result
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,521 | hj-leetcode-kotlin | Apache License 2.0 |
Algorithms/src/main/kotlin/NextClosestTime.kt | ILIYANGERMANOV | 557,496,216 | false | {"Kotlin": 74485} | fun main() {
val sut = NextClosestTime()
for (h in 0..23) {
val hour = if (h < 10) "0$h" else h.toString()
for (m in 0..59) {
val minute = if (m < 10) "0$m" else m.toString()
val time = "$hour:$minute"
println("\"$time\" -> \"${sut.nextClosestTime(time)}\"")
}
}
}
class NextClosestTime {
fun nextClosestTime(time: String): String {
val digits = mutableSetOf<Int>()
digits.add(time[0].digitToInt())
digits.add(time[1].digitToInt())
digits.add(time[3].digitToInt())
digits.add(time[4].digitToInt())
val sortedDigits = digits.sorted()
val hour = String(charArrayOf(time[0], time[1]))
val minute = String(charArrayOf(time[3], time[4]))
val minuteInt = minute.toInt()
val hasZero: Boolean = sortedDigits.first() == 0
return tryNextMinute(
sortedDigits = sortedDigits,
hour = hour,
minute = minute,
minuteInt = minuteInt,
hasZero = hasZero
) ?: tryNextHorWithMinimizedMin(
sortedDigits = sortedDigits,
hour = hour,
hasZero = hasZero
) ?: minimizeTime(sortedDigits)
}
private fun tryNextMinute(
sortedDigits: List<Int>,
hour: String,
minute: String,
minuteInt: Int,
hasZero: Boolean
): String? {
if (minute == "59") return null
for (i in sortedDigits.indices) {
val digit1 = sortedDigits[i]
if (hasZero) {
// try single digit
if (digit1 > minuteInt) return "$hour:0$digit1"
}
for (j in sortedDigits.indices) {
val digit2 = sortedDigits[j]
val newMinute = validMinute(digit1, digit2)
if (newMinute != null && newMinute > minuteInt) return "$hour:${format(newMinute)}"
}
}
return null
}
private fun tryNextHorWithMinimizedMin(
sortedDigits: List<Int>,
hour: String,
hasZero: Boolean
): String? {
fun minimizedMin(): String = sortedDigits.first().run {
if (hasZero) "0$this" else "$this$this"
}
if (hour == "23") return null
val hourInt = hour.toInt()
for (i in sortedDigits.indices) {
val digit1 = sortedDigits[i]
if (hasZero) {
// try single digit
if (digit1 > hourInt) return "0$digit1:${minimizedMin()}"
}
for (j in sortedDigits.indices) {
val digit2 = sortedDigits[j]
val newHour = validHour(digit1, digit2)
if (newHour != null && newHour > hourInt) return "${format(newHour)}:${minimizedMin()}"
}
}
return null
}
private fun minimizeTime(
sortedDigits: List<Int>
): String {
val first = sortedDigits.first()
return "$first$first:$first$first"
}
private fun format(newNumber: Int): String = if (newNumber < 10)
"0$newNumber" else newNumber.toString()
private fun validHour(digit1: Int, digit2: Int): Int? {
val newHour = digit1 * 10 + digit2
return newHour.takeIf { it in 0..23 }
}
private fun validMinute(digit1: Int, digit2: Int): Int? {
val newMinute = digit1 * 10 + digit2
return newMinute.takeIf { it in 0..59 }
}
/**
* LeetCode compatibility
*/
private fun Char.digitToInt(): Int = this.toInt() - '0'.toInt()
} | 0 | Kotlin | 0 | 1 | 4abe4b50b61c9d5fed252c40d361238de74e6f48 | 3,592 | algorithms | MIT License |
Day12/src/JupiterMoons.kt | gautemo | 225,219,298 | false | null | import java.io.File
import kotlin.math.abs
import kotlinx.coroutines.*
fun main(){
val input = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText().trim()
val energy = energyAfterStep(getMoons(input), 1000)
println(energy)
val loop = repeatsAfter(getMoons(input))
println(loop)
}
fun getMoons(input: String): List<Moon> {
val moons = mutableListOf<Moon>()
val reg = Regex("""-?\d+""")
input.lines().forEach {
val xyz = reg.findAll(it)
val x = xyz.elementAt(0).value.toInt()
val y = xyz.elementAt(1).value.toInt()
val z = xyz.elementAt(2).value.toInt()
moons.add(Moon(x, y, z))
}
return moons
}
fun energyAfterStep(moons: List<Moon>, steps: Int): Int {
for(i in 0 until steps){
doStep(moons)
}
return moons.sumBy { it.energy() }
}
fun repeatsAfter(moons: List<Moon>): Long{
val x = moons.map { Axis(it.x) }
val y = moons.map { Axis(it.y) }
val z = moons.map { Axis(it.z) }
var repeat = -1L
runBlocking {
val xRepeat = async { repeats(x) }
val yRepeat = async { repeats(y) }
val zRepeat = async { repeats(z) }
repeat = lcm(lcm(xRepeat.await(), yRepeat.await()), zRepeat.await())
}
return repeat
}
fun repeats(a: List<Axis>): Long{
val start = a.map { it.copy() }
var counter = 1L
do{
doStep(a)
counter++
}while(start != a)
return counter
}
fun doStep(moveables: List<Moveable>){
moveables.forEach { m -> moveables.forEach { m.changeVel(it) } }
moveables.forEach { it.move() }
}
abstract class Moveable{
abstract fun changeVel(c: Any)
abstract fun move()
}
data class Moon(var x: Int, var y: Int, var z: Int) : Moveable(){
var velX = 0
var velY = 0
var velZ = 0
override fun changeVel(c: Any){
c as Moon
velX += compareValues(c.x, x)
velY += compareValues(c.y, y)
velZ += compareValues(c.z, z)
}
override fun move(){
x += velX
y += velY
z += velZ
}
fun energy() = (abs(x) + abs(y) + abs(z)) * (abs(velX) + abs(velY) + abs(velZ))
}
data class Axis(var pos: Int) : Moveable(){
var vel = 0
override fun changeVel(c: Any){
c as Axis
vel += compareValues(c.pos, pos)
}
override fun move(){
pos += vel
}
}
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b | 0 | Kotlin | 0 | 0 | f8ac96e7b8af13202f9233bb5a736d72261c3a3b | 2,520 | AdventOfCode2019 | MIT License |
src/main/kotlin/day7/part2/Part2.kt | bagguley | 329,976,670 | false | null | package day7.part2
import day7.data
fun main() {
val bagMap = data.map{it.split(" bags contain ")}.map{ process2(it) }.toMap()
val stack = mutableListOf(bagMap["shiny gold"])
var count = 0
do {
val c = stack.removeAt(0)
stack.addAll(c!!.map{f -> bagMap[f.second]!!.map{g -> f.first * g.first to g.second}})
count += c.map { f -> f.first }.sum()
} while (stack.isNotEmpty())
println(count)
}
fun process2(input: List<String>) : Pair<String, List<Pair<Int,String>>> {
val v = input[1].split(Regex(" bags?[,.]? ?")).filter { it != "no other" && it.isNotEmpty()}
return input[0] to v.map{ process3(it) }
}
fun process3(input: String) : Pair<Int,String> {
val x = Regex("(\\d+) (.+)").matchEntire(input)
return x!!.groupValues[1].toInt() to x.groupValues[2]
}
| 0 | Kotlin | 0 | 0 | 6afa1b890924e9459f37c604b4b67a8f2e95c6f2 | 824 | adventofcode2020 | MIT License |
src/main/kotlin/io/github/pshegger/aoc/y2022/Y2022D5.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2022
import io.github.pshegger.aoc.common.BaseSolver
import io.github.pshegger.aoc.common.extractAll
import io.github.pshegger.aoc.common.splitByBlank
import io.github.pshegger.aoc.common.toExtractor
class Y2022D5 : BaseSolver() {
override val year = 2022
override val day = 5
private val extractor = "move %d from %d to %d".toExtractor()
override fun part1(): String = parseInput()
.convertForPart1()
.solve()
override fun part2(): String = parseInput().solve()
private fun Input.convertForPart1() = copy(
steps = steps.flatMap { step -> List(step.count) { step.copy(count = 1) } }
)
private fun Input.solve() =
steps.fold(starting) { stacks, step ->
val moving = stacks[step.from].takeLast(step.count)
stacks.mapIndexed { i, stack ->
when (i) {
step.from -> stack.dropLast(step.count)
step.to -> stack + moving
else -> stack
}
}
}
.mapNotNull { it.lastOrNull() }
.joinToString(separator = "")
private fun parseInput() = readInput {
val (starting, steps) = readLines().splitByBlank()
val stackCount = starting.last()
.split(" ")
.map { it.trim() }
.filter { it.isNotBlank() }
.maxOf { it.toInt() }
val stacks = List(stackCount) { mutableListOf<Char>() }
starting.dropLast(1)
.forEach { line ->
line.chunked(4)
.map { it.trim() }
.forEachIndexed { i, item ->
if (item.length > 1 && !item[1].isWhitespace()) {
stacks[i].add(item[1])
}
}
}
Input(
starting = stacks.map { it.reversed() },
steps = steps.extractAll(extractor) { (count, from, to) ->
Step(from.toInt() - 1, to.toInt() - 1, count.toInt())
}
)
}
private data class Step(val from: Int, val to: Int, val count: Int)
private data class Input(val starting: List<List<Char>>, val steps: List<Step>)
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 2,260 | advent-of-code | MIT License |
src/aoc2023/Day09.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2023
import readInput
fun main() {
fun resolveSequence(start: List<Int>): Long {
var totalLastValues = 0L
var current = start
var next = mutableListOf<Int>()
while (current.any { it != 0 }) {
for (i in 0 until current.size - 1) {
next.add(current[i + 1] - current[i])
}
totalLastValues += current.last()
current = next
next = mutableListOf()
}
return totalLastValues
}
fun resolveSequenceBackwards(start: List<Int>): Int {
var firstValues = mutableListOf<Int>()
var current = start
var next = mutableListOf<Int>()
while (current.any { it != 0 }) {
for (i in 0 until current.size - 1) {
next.add(current[i + 1] - current[i])
}
firstValues.add(current.first())
current = next
next = mutableListOf()
}
firstValues.add(0)
// new + cur = prev; new = prev - cur
var cur = 0
for (i in firstValues.size - 1 downTo 0) {
cur = (firstValues[i] - cur)
}
return cur
}
fun part1(lines: List<String>): Long {
var sum = 0L
for (line in lines) {
sum += resolveSequence(line.trim().split(" ").map { it.toInt() })
}
return sum
}
fun part2(lines: List<String>): Long {
var sum = 0L
for (line in lines) {
sum += resolveSequenceBackwards(line.trim().split(" ").map { it.toInt() })
}
return sum
}
println(part1(readInput("aoc2023/Day09_test")))
println(part1(readInput("aoc2023/Day09")))
println(part2(readInput("aoc2023/Day09_test")))
println(part2(readInput("aoc2023/Day09")))
} | 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 1,814 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/freekdb/kotlin/workshop/step05/MastermindVersion2.kt | FreekDB | 230,429,337 | false | null | package com.github.freekdb.kotlin.workshop.step05
// Code-breaking game: https://en.wikipedia.org/wiki/Mastermind_(board_game)
// Additional information: http://mathworld.wolfram.com/Mastermind.html
// Implementation inspired by: http://www.rosettacode.org/wiki/Mastermind#Python
// https://www.coursera.org/learn/kotlin-for-java-developers/programming/vmwVT/mastermind-game
private const val MINIMUM_LETTER_COUNT = 2
private const val MAXIMUM_LETTER_COUNT = 20
private const val MINIMUM_CODE_LENGTH = 4
private const val MAXIMUM_CODE_LENGTH = 10
fun main() {
val (letters, code) = initializeGame()
runGame(letters, code)
}
private fun initializeGame(): Pair<String, String> {
println("""
|Welcome to Mastermind. You are challenged to guess a random code!
|In response to each guess, you will receive a hint.
|In this hint, an X means you guessed that letter correctly.
|An O means that letter is in the code, but in a different position.
""".trimMargin())
val letterCount = readNumber("Select a number of possible letters for the code",
MINIMUM_LETTER_COUNT, MAXIMUM_LETTER_COUNT)
val codeLength = readNumber("Select a length for the code",
MINIMUM_CODE_LENGTH, MAXIMUM_CODE_LENGTH)
val letters = "ABCDEFGHIJKLMNOPQRST".take(letterCount)
val code = (1..codeLength).map { letters.random() }.joinToString("")
return Pair(letters, code)
}
private fun readNumber(prompt: String, minimum: Int, maximum: Int): Int {
var number: Int? = null
val promptWithRange = "$prompt ($minimum-$maximum): "
while (number == null || number !in minimum..maximum) {
print(promptWithRange)
number = readLine()?.toIntOrNull()
}
return number
}
private fun runGame(letters: String, code: String) {
val guesses = mutableListOf<String>()
var finished = false
while (!finished) {
println()
print("Enter a guess of length ${code.length} ($letters): ")
val guess = readLine()?.toUpperCase()?.trim() ?: ""
println()
if (guess == code) {
println("Your guess $guess was correct!")
finished = true
} else if (guess.length != code.length || guess.any { it !in letters }) {
println("Your guess $guess was invalid. Please try again...")
} else {
guesses += "${guesses.size + 1}: ${guess.toCharArray().joinToString(" ")} =>" +
" ${encode(code, guess)}"
guesses.forEach {
println("------------------------------------")
println(it)
println("------------------------------------")
}
}
}
}
// A black key peg ("X") is placed for each code peg from the guess which is correct in both color and position ("cc-cp").
// A white key peg ("O") indicates the existence of a correct color code peg placed in the wrong position ("cc-wp").
private fun encode(code: String, guess: String): String =
code
.zip(guess)
.map { if (it.first == it.second) "cc-cp" else if (it.second in code) "cc-wp" else "wc-wp" }
.sorted()
.map { when(it) {
"cc-cp" -> "X"
"cc-wp" -> "O"
else -> "-"
} }
.joinToString(" ")
| 0 | Kotlin | 0 | 2 | 5a9bb08a8d0bd3d68dd2274becf4758ab10caf5d | 3,355 | kotlin-for-kurious-koders | Apache License 2.0 |
src/main/kotlin/space/d_lowl/kglsm/problem/TSP.kt | d-lowl | 300,622,439 | false | null | package space.d_lowl.kglsm.problem
import space.d_lowl.kglsm.general.space.isRepeating
import java.io.File
import kotlin.math.pow
import kotlin.math.sqrt
import kotlin.random.Random
typealias DistanceFunction = (NDPoint, NDPoint) -> Double
class NDPoint(vararg val coords: Double) {
fun getDimensions(): Int = coords.size
override fun toString(): String = "{${coords.joinToString(",")}}"
companion object {
fun euclideanDistance(a: NDPoint, b: NDPoint): Double =
sqrt(a.coords.zip(b.coords).map { (it.first - it.second).pow(2) }.sum())
}
}
class TSP(
private val points: List<NDPoint>,
private val cycle: Boolean = false,
private val dist: DistanceFunction = (NDPoint)::euclideanDistance
): Problem<Int> {
val size: Int
get() = points.size
init {
val dimensions = points.first().getDimensions()
require(points.all { it.getDimensions() == dimensions })
}
override fun getSolutionCost(solution: Array<Int>): Double {
// Solution must be a (partial) permutation
require(solution.isNotEmpty())
require(!solution.isRepeating())
require(solution.min()!! >= 0)
require(solution.max()!! < points.size)
var pathCost = solution.asIterable().zipWithNext().map { dist(points[it.first], points[it.second]) }.sum()
// If permutation is complete and cycle is expected
if (cycle && solution.size == points.size) {
pathCost += dist(points[solution.first()], points[solution.last()])
}
return pathCost
}
override fun toString(): String = "[${points.joinToString(";")}]"
companion object {
fun getRandomInstance(
dimensions: Int,
noPoints: Int,
cycle: Boolean = false,
dist: DistanceFunction = (NDPoint)::euclideanDistance
) = TSP(
List(noPoints) { NDPoint(*(DoubleArray(dimensions) { Random.nextDouble() })) },
cycle,
dist
)
fun fromFile(filepath: String): TSP {
var isNodeReadingMode = false
val iterator = File(filepath).readLines().iterator()
while (!isNodeReadingMode && iterator.hasNext()) {
val value = iterator.next().split(":").map { it.trim() }
when (value.first()) {
"EDGE_WEIGHT_TYPE" -> {
if (value.last() != "EUC_2D") {
throw Exception("Only problem instances with euclidean distance are supported")
}
}
"NODE_COORD_SECTION" -> { isNodeReadingMode = true }
}
}
val points = iterator.asSequence().map { line ->
val values = Regex("\\d+").findAll(line).map { it.value.toDouble() }.drop(1).toList()
NDPoint(*values.toDoubleArray())
}.filter { it.getDimensions() == 2 }.toList()
return TSP(points, true)
}
}
} | 17 | Kotlin | 0 | 1 | 0886e814be75a77fa8f33faa867329aef19085a5 | 3,077 | kGLSM | MIT License |
kotlin/src/katas/kotlin/sort/heapsort/HeapSort0.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.sort.heapsort
import nonstdlib.listOfInts
import nonstdlib.permutations
import nonstdlib.printed
import nonstdlib.swap
import datsok.shouldEqual
import org.junit.Test
import kotlin.random.Random
class HeapSort0Tests {
@Test fun `sort a list`() {
emptyList<Int>().heapSort() shouldEqual emptyList()
listOf(1).heapSort() shouldEqual listOf(1)
listOf(1, 2, 3).permutations().forEach {
it.heapSort() shouldEqual listOf(1, 2, 3)
}
listOf(1, 2, 3, 4).permutations().forEach {
it.heapSort() shouldEqual listOf(1, 2, 3, 4)
}
fun List<Int>.isSorted() =
windowed(size = 2).all { it[0] <= it[1] }
val list = Random(seed = Random.nextInt().printed()).listOfInts(
sizeRange = 0..100,
valuesRange = 0..100
).printed().heapSort()
list.printed().isSorted() shouldEqual true
}
@Test fun `array-based binary heap`() {
val heap = BinaryHeap()
heap.add(2)
heap.add(1)
heap.add(3)
heap.add(-1)
heap.removeTop() shouldEqual -1
heap.removeTop() shouldEqual 1
heap.removeTop() shouldEqual 2
heap.removeTop() shouldEqual 3
}
}
class BinaryHeap(list: List<Int> = emptyList()) {
private val array = Array(size = 256, init = { 0 })
private var size = 0
init {
list.forEach { add(it) }
}
fun add(element: Int) {
array[size] = element
siftUp(size)
size++
}
fun removeTop(): Int {
val result = array[0]
array[0] = array[size - 1]
size--
siftDown(0)
return result
}
private fun siftUp(index: Int) {
val parentIndex = if (index == 0) -1 else (index - 1) / 2
if (parentIndex != -1 && array[parentIndex] > array[index]) {
array.swap(parentIndex, index)
siftUp(parentIndex)
}
}
private fun siftDown(index: Int) {
var minIndex = index
val childIndex1 = index * 2 + 1
val childIndex2 = index * 2 + 2
if (childIndex1 < size && array[childIndex1] < array[minIndex]) minIndex = childIndex1
if (childIndex2 < size && array[childIndex2] < array[minIndex]) minIndex = childIndex2
if (minIndex == index) return
array.swap(index, minIndex)
siftDown(minIndex)
}
fun isEmpty(): Boolean = size == 0
}
private fun List<Int>.heapSort(): List<Int> {
val result = ArrayList<Int>()
val heap = BinaryHeap(this)
while (!heap.isEmpty()) {
result.add(heap.removeTop())
}
return result
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,660 | katas | The Unlicense |
src/main/kotlin/de/dikodam/adventofcode2019/days/Day04.kt | dikodam | 225,222,616 | false | null | package de.dikodam.adventofcode2019.days
import de.dikodam.adventofcode2019.utils.TimingData
import de.dikodam.adventofcode2019.utils.withTimer
fun main() {
val (passwordRange, setupDuration) = withTimer {
val (start, end) = day04input.split("-").map { it.toInt() }
(start..end)
}
val (t1ValidPasswordCount, t1duration) = withTimer {
passwordRange
.filter { it.hasOnlyRisingDigits() }
.filter { it.hasAdjacentDuplicateDigits() }
.count()
}
val (t2ValidPasswordCount, t2duration) = withTimer {
passwordRange
.filter { it.hasOnlyRisingDigits() }
.filter { it.hasExactly2DuplicateDigits() }
.count()
}
println("Task 1: There are $t1ValidPasswordCount valid passwords in the range $passwordRange.")
println("Task 2: There are $t2ValidPasswordCount valid passwords in the range $passwordRange.")
TimingData(setupDuration, t1duration, t2duration).print()
}
private fun Int.hasAdjacentDuplicateDigits(): Boolean {
val digits = this.toString()
return digits
.dropLast(1)
.zip(digits.drop(1))
.any { (char, nextChar) -> char == nextChar }
}
private fun Int.hasOnlyRisingDigits(): Boolean {
val digits = this.toString()
return digits
.dropLast(1)
.zip(digits.drop(1))
.all { (char, nextChar) -> char <= nextChar }
}
private fun Int.hasExactly2DuplicateDigits(): Boolean {
val digits = this.toString()
// case 1: 1123456 - exactly 2 matching at start
if (digits[0] == digits[1] && digits[0] != digits[2]) {
return true
}
// case 2. 123455 - exactly 2 matching at end
if (digits[digits.lastIndex] == digits[digits.lastIndex - 1] && digits[digits.lastIndex] != digits[digits.lastIndex - 2]) {
return true
}
// case 3. 123345 - exactly 2 matching somewhere in between
for (index in 2 until digits.length) {
if (digits[index - 2] != digits[index] && digits[index - 1] == digits[index] && digits[index + 1] != digits[index]) {
return true
}
}
return false
}
private const val day04input = "372304-847060"
| 0 | Kotlin | 0 | 0 | 6db72123172615f4ba5eb047cc2e1fc39243adc7 | 2,191 | adventofcode2019 | MIT License |
src/main/kotlin/before/test/problem1/test.kt | K-Diger | 642,489,846 | false | {"Kotlin": 105578, "Java": 57609} | package before.test.problem1
class Solution {
fun solution(histogram: Array<IntArray>): Int {
var result = 1
val height = histogram.size
val width = histogram[0].size
var histogramConversionAxis = Array(width) { IntArray(height) }
histogramConversionAxis = setHistogramConversionAxis(histogram, histogramConversionAxis, width, height)
for (row in histogramConversionAxis.indices) {
var possibleGraphHeight: Int
var firstZero = histogramConversionAxis[row].indexOf(0)
if (firstZero == -1) firstZero = height
possibleGraphHeight = find(firstZero, histogramConversionAxis, row)
result *= possibleGraphHeight
}
return result
}
private fun setHistogramConversionAxis(
histogram: Array<IntArray>,
histogramConversionAxis: Array<IntArray>,
width: Int,
height: Int
): Array<IntArray> {
for (row in histogram.indices) {
for (column in histogram[row].indices) {
histogramConversionAxis[width - column - 1][height - row - 1] = histogram[row][column]
}
}
return histogramConversionAxis
}
private fun find(
firstZero: Int,
histogramConversionAxis: Array<IntArray>,
row: Int
): Int {
var possibleGraphHeight = 1
for (column in firstZero - 1 downTo 0) {
if (histogramConversionAxis[row][column] == 1) break
if (histogramConversionAxis[row][column] == 2) possibleGraphHeight += 1
}
return possibleGraphHeight
}
}
| 0 | Kotlin | 0 | 0 | 2789df5993923f7aab6e8774a7387ab65c29060a | 1,638 | algorithm-rehab | MIT License |
src/main/kotlin/aoc2020/ex11.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | fun main() {
assert1()
assert2()
val input = readInputFile("aoc2020/input11")
occupiedOnStabilization(matFromInput(input)) { it.update() }
occupiedOnStabilization(matFromInput(input)) { it.update3() }
}
fun Mat.update2() {
val r = Mat(array.mapIndexed { rIndex, row ->
row.mapIndexed { cIndex, _ ->
hasNeighborAt(this, rIndex, cIndex, 0, -1, mutableMapOf()).let {
if (it) PlaceState.OCCUPIED else PlaceState.SEAT
}
}
})
println("\n")
println(r.repr())
require(
r == matFromInput(
"""
L#####L###
L#L###LLLL
LLL#######
L#L######L
L#####LLLL
L#####L###
LLL#######
L#L######L
L##LL###LL
L###L#####
""".trimIndent()
)
)
}
data class PosAndDir(val x: Int, val y: Int, val dx: Int, val dy: Int)
private fun hasNeighborAt(
mat: Mat,
row: Int,
col: Int,
dr: Int,
dc: Int,
cache: MutableMap<PosAndDir, Boolean>
): Boolean {
val entry = PosAndDir(col, row, dc, dr)
val neighborY = entry.y + entry.dy
val neighborX = entry.x + entry.dx
if (neighborX < 0 || neighborX >= mat.columns) return false
if (neighborY < 0 || neighborY >= mat.rows) return false
if (cache.contains(entry)) return cache.getValue(entry)
val immediateNeighbor = mat.array[neighborY][neighborX]
return when (immediateNeighbor) {
PlaceState.SEAT -> false
PlaceState.FLOOR -> hasNeighborAt(mat, neighborY, neighborX, entry.dy, entry.dx, cache)
PlaceState.OCCUPIED -> true
}.also {
cache.put(entry, it)
}
}
fun matFromInput(input: String) = Mat(input.lines().map { row -> row.map { PlaceState.fromChar(it) } })
data class Mat(val array: List<List<PlaceState>>) {
fun repr() = array.map { row -> row.map { it.repr() }.joinToString("") }.joinToString("\n")
val columns = array.first().size
val rows = array.size
}
enum class PlaceState {
SEAT, FLOOR, OCCUPIED;
companion object {
fun fromChar(char: Char) = when (char) {
SEAT_CODE -> SEAT
FLOOR_CODE -> FLOOR
OCCUPIED_CODE -> OCCUPIED
else -> error("")
}
}
}
fun PlaceState.repr() = when (this) {
PlaceState.SEAT -> SEAT_CODE
PlaceState.FLOOR -> FLOOR_CODE
PlaceState.OCCUPIED -> OCCUPIED_CODE
}
private const val SEAT_CODE = 'L'
private const val FLOOR_CODE = '.'
private const val OCCUPIED_CODE = '#'
fun updateSeat(state: PlaceState, occupiedNeighbort: Int): PlaceState {
return when (state) {
PlaceState.SEAT -> if (occupiedNeighbort == 0) PlaceState.OCCUPIED else PlaceState.SEAT
PlaceState.FLOOR -> PlaceState.FLOOR
PlaceState.OCCUPIED -> if (occupiedNeighbort >= 4) PlaceState.SEAT else PlaceState.OCCUPIED
}
}
fun updateSeat2(state: PlaceState, occupiedNeighbort: Int): PlaceState {
return when (state) {
PlaceState.SEAT -> if (occupiedNeighbort == 0) PlaceState.OCCUPIED else PlaceState.SEAT
PlaceState.FLOOR -> PlaceState.FLOOR
PlaceState.OCCUPIED -> if (occupiedNeighbort >= 5) PlaceState.SEAT else PlaceState.OCCUPIED
}
}
fun Mat.update3(): Mat {
val neighborsCache = mutableMapOf<PosAndDir, Boolean>()
return Mat(
array.mapIndexed { rIndex, row ->
row.mapIndexed { cIndex, cell ->
val occupiedNeighbors = neighborDirections.count {
hasNeighborAt(this, rIndex, cIndex, it.first, it.second, neighborsCache)
}
updateSeat2(cell, occupiedNeighbors)
}
})
}
fun Mat.update(): Mat {
val rows = array.size
val columns = array.first().size
return Mat(
array.mapIndexed { rIndex, row ->
row.mapIndexed { cIndex, cell ->
val occupiedNeighbors = neighborDirections
.map { it.first + rIndex to it.second + cIndex }
.filter {
it.first in 0 until rows &&
it.second in 0 until columns
}.map {
array[it.first][it.second]
}.count { it == PlaceState.OCCUPIED }
updateSeat(cell, occupiedNeighbors)
}
})
}
fun Mat.countOccupied() = array.sumOf { row -> row.count { it == PlaceState.OCCUPIED } }
private val neighborDirections = listOf(
-1 to -1,
-1 to 0,
-1 to 1,
0 to -1,
0 to 1,
1 to -1,
1 to 0,
1 to 1
)
fun occupiedOnStabilization(input: Mat, change: (Mat) -> Mat) {
var prevMat = input
var mat = prevMat.update()
var iter = 0
while (mat != prevMat && iter < 100) {
iter++
println("iter $iter")
prevMat = mat
mat = change(mat)
}
println("stabilized after $iter")
println("occupied ${mat.countOccupied()}")
}
private fun assert1() {
val input = """
L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL
""".trimIndent()
val t1 = """
#.##.##.##
#######.##
#.#.#..#..
####.##.##
#.##.##.##
#.#####.##
..#.#.....
##########
#.######.#
#.#####.##
""".trimIndent()
val t2 = """
#.LL.L#.##
#LLLLLL.L#
L.L.L..L..
#LLL.LL.L#
#.LL.LL.LL
#.LLLL#.##
..L.L.....
#LLLLLLLL#
#.LLLLLL.L
#.#LLLL.##
""".trimIndent()
val t3 = """
#.##.L#.##
#L###LL.L#
L.#.#..#..
#L##.##.L#
#.##.LL.LL
#.###L#.##
..#.#.....
#L######L#
#.LL###L.L
#.#L###.##
""".trimIndent()
val t4 = """
#.#L.L#.##
#LLL#LL.L#
L.L.L..#..
#LLL.##.L#
#.LL.LL.LL
#.LL#L#.##
..L.L.....
#L#LLLL#L#
#.LLLLLL.L
#.#L#L#.##
""".trimIndent()
val t5 = """
#.#L.L#.##
#LLL#LL.L#
L.#.L..#..
#L##.##.L#
#.#L.LL.LL
#.#L#L#.##
..L.L.....
#L#L##L#L#
#.LLLLLL.L
#.#L#L#.##
""".trimIndent()
val ts = listOf(t1, t2, t3, t4, t5).map { matFromInput(it) }
val mat = matFromInput(input)
ts.forEachIndexed { index, _ ->
println("test ${index + 1}")
require(ts[index] == mat.update(index + 1)) {
"${ts[index].repr()}\n\n${mat.update(index + 1).repr()}"
}
}
}
private fun assert2() {
val input = """
L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL
""".trimIndent()
val t1 = """
#.##.##.##
#######.##
#.#.#..#..
####.##.##
#.##.##.##
#.#####.##
..#.#.....
##########
#.######.#
#.#####.##
""".trimIndent()
val t2 = """
#.LL.LL.L#
#LLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLL#
#.LLLLLL.L
#.LLLLL.L#
""".trimIndent()
val t3 = """
#.L#.##.L#
#L#####.LL
L.#.#..#..
##L#.##.##
#.##.#L.##
#.#####.#L
..#.#.....
LLL####LL#
#.L#####.L
#.L####.L#
""".trimIndent()
val t4 = """
#.L#.L#.L#
#LLLLLL.LL
L.L.L..#..
##LL.LL.L#
L.LL.LL.L#
#.LLLLL.LL
..L.L.....
LLLLLLLLL#
#.LLLLL#.L
#.L#LL#.L#
""".trimIndent()
val t5 = """
#.L#.L#.L#
#LLLLLL.LL
L.L.L..#..
##L#.#L.L#
L.L#.#L.L#
#.L####.LL
..#.#.....
LLL###LLL#
#.LLLLL#.L
#.L#LL#.L#
""".trimIndent()
val ts = listOf(t1, t2, t3, t4, t5).map { matFromInput(it) }
val mat = matFromInput(input)
ts.forEachIndexed { index, _ ->
println("test ${index + 1}")
require(ts[index] == mat.update3(index + 1)) {
"\n${ts[index].repr()}\n\n${mat.update3(index + 1).repr()}"
}
}
}
fun Mat.update(i: Int) = transform(i) { update() }
fun Mat.update3(i: Int) = transform(i) { update3() } | 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 8,483 | AOC-2021 | MIT License |
src/lib/Combinatorics.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | package lib
object Combinatorics {
fun <T> permutationsWithReplacement(input: Set<T>, n: Int): List<List<T>> =
if (n <= 0) listOf(emptyList())
else input.flatMap { first ->
permutationsWithReplacement(input, n - 1).map { rest ->
listOf(first) + rest
}
}
fun <T> permutations(input: Set<T>): List<List<T>> {
if (input.isEmpty()) return listOf(emptyList())
val first = input.first()
val tail = input.drop(1).toSet()
return permutations(tail).flatMap { rest ->
(0..rest.size).map {
buildList {
addAll(rest.take(it))
add(first)
addAll(rest.drop(it))
}
}
}
}
fun <T> combinations(input: Set<T>, n: Int): Set<Set<T>> {
if (n <= 0) return setOf(emptySet())
if (input.isEmpty()) return emptySet()
val first = input.take(1).toSet()
val tail = input.drop(1).toSet()
return combinations(tail, n - 1).map { rest -> first + rest }.toSet() + combinations(tail, n)
}
}
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 1,001 | aoc-kotlin | Apache License 2.0 |
src/Day04.kt | avarun42 | 573,407,145 | false | {"Kotlin": 8697} | import day04.SectionAssignment
fun main() {
fun List<String>.toSectionAssignmentPairs(): List<Pair<SectionAssignment, SectionAssignment>> {
return this.splitEach(",").map { elfPair ->
elfPair.splitEach("-").map { SectionAssignment(it) }.toPair()
}
}
fun part1(input: List<String>): Int {
return input.toSectionAssignmentPairs().count { (elf1, elf2) ->
elf1.contains(elf2) || elf2.contains(elf1)
}
}
fun part2(input: List<String>): Int {
return input.toSectionAssignmentPairs().count { (elf1, elf2) -> elf1.overlaps(elf2) }
}
// 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 | 1 | 622d022b7556dd0b2b3e3fb2abdda1c854bfe3a3 | 890 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/kosmx/aoc23/graphs/BFS.kt | KosmX | 726,056,762 | false | {"Kotlin": 32011} | package dev.kosmx.aoc23.graphs
import java.io.File
import java.util.PriorityQueue
operator fun List<String>.get(x: Int, y: Int): Char = this.getOrNull(y)?.getOrNull(x) ?: '.'
operator fun List<String>.get(xy: Pair<Int, Int>): Char = this[xy.first, xy.second]
operator fun List<String>.contains(xy: Pair<Int, Int>): Boolean = xy.second in indices && xy.first in this[0].indices
val deltas = listOf(-1 to 0, 0 to -1, 1 to 0, 0 to 1)
val neighbours: Map<Char, Collection<Pair<Int, Int>>> = mapOf(
'.' to listOf(),
'S' to deltas,
'L' to listOf(0 to -1, 1 to 0),
'F' to listOf(1 to 0, 0 to 1),
'J' to listOf(0 to -1, -1 to 0),
'7' to listOf(-1 to 0, 0 to 1),
'-' to listOf(-1 to 0, 1 to 0),
'|' to listOf(0 to -1, 0 to 1)
)
fun main() {
val map = File("pipes.txt").readLines()
val start = map.indexOfFirst { 'S' in it }.let { y -> map[y].indexOf('S') to y }
println("Start at $start")
val lengths = mutableMapOf(start to 0)
val seen = PriorityQueue<Pair<Int, Int>> { a, b -> lengths[a]!!.compareTo(lengths[b]!!) }.apply {
this += start
}
// coordinate to vector
val directions: MutableMap<Pair<Int, Int>, Pair<Int, Int>> = mutableMapOf(start to (0 to 0))
// Let's BFS
piece@while (seen.any()) {
val head: Pair<Int, Int> = seen.remove()
for (delta in neighbours[map[head]]!!) {
val newPos = head + delta
if (newPos !in lengths && neighbours[map[newPos]]!!.contains(-delta)) {
lengths[newPos] = lengths[head]!! + 1
// update direction vectors for part2
directions[head] = directions.getOrDefault(head, 0 to 0) + delta
directions[newPos] = directions.getOrDefault(newPos, 0 to 0) + delta
seen += newPos
continue@piece
}
}
}
println("Part1: ${lengths.maxBy { (it.value+1)/2 }}")
// part 2, false for negative true for positive area
val areas = mutableMapOf<Pair<Int, Int>, Boolean>()
// last created list
var lastUpdate = listOf<Pair<Pair<Int, Int>, Boolean>>()
run { // Round 0
val new = mutableListOf<Pair<Pair<Int, Int>, Boolean>>()
for (y in map.indices) {
for (x in map[y].indices) {
if ((x to y) !in directions) {
deltas.asSequence().map { d -> d to (x to y) + d }
.mapNotNull { directions[it.second]?.let { (dx, dy) -> it.first * (dy to -dx) } }
.firstOrNull()?.let { side ->
if (side != 0) {
new += (x to y) to (side > 0)
}
}
}
}
}
lastUpdate = new
areas += lastUpdate
}
//*
while (lastUpdate.isNotEmpty()) {
val new = mutableListOf<Pair<Pair<Int, Int>, Boolean>>()
lastUpdate.forEach { (pos, side) ->
deltas.forEach { delta ->
val p = pos + delta
if (p !in directions && p !in areas && p in map) {
areas += p to side
new += p to side
}
}
}
lastUpdate = new
}// */
//*
for (y in map.indices) {
for (x in map[y].indices) {
val area = areas[x to y]
val areaCode = if (area != null) if(area) "I" else "O" else "X"
val direction = directions[x to y]?.let {
when(it) {
(1 to 0), (2 to 0) -> '→'
-1 to 0, -2 to 0 -> '←'
0 to 1, 0 to 2 -> '↓'
0 to -1, 0 to -2 -> '↑'
1 to 1, -> '↘'
1 to -1 -> '↗'
-1 to -1 -> '↖'
-1 to 1 -> '↙'
else -> '↻'
}
}
print((direction ?: areaCode).toString().padEnd(1, ' '))
}
println()
}// */
val groups = areas.asSequence().groupingBy { it.value }.eachCount()
println(groups)
}
// Math!
operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> = first + other.first to second + other.second
operator fun Pair<Int, Int>.minus(other: Pair<Int, Int>): Pair<Int, Int> = first - other.first to second - other.second
operator fun Pair<Int, Int>.unaryMinus(): Pair<Int, Int> = -first to -second
// Mathematical dot product
operator fun Pair<Int, Int>.times(other: Pair<Int, Int>): Int = this.first * other.first + this.second * other.second
| 0 | Kotlin | 0 | 0 | ad01ab8e9b8782d15928a7475bbbc5f69b2416c2 | 4,633 | advent-of-code23 | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day15.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInputLines
import kotlin.math.abs
object Day15 : Day {
override val input = readInputLines(15).map { SensorBeacon.from(it) }
override fun part1(): Int {
val y = 10L
val possible = mutableSetOf<Long>()
input.forEach {
val x = it.distance - abs(it.sensor.y - y)
possible += it.sensor.x - x..it.sensor.x + x
}
val beacons = input.map { it.beacon }
return possible.count { Position(it, y) !in beacons }
}
override fun part2(): Long {
val max = if (isTest()) 20 else 4000000
input.forEach { (sensor, _, distance) ->
for (distanceX in 0..(distance + 1)) {
val distanceY = distance + 1 - distanceX
for ((dirX, dirY) in listOf(-1 to -1, -1 to 1, 1 to -1, 1 to 1)) {
val (bX, bY) = sensor.x + distanceX * dirX to sensor.y + distanceY * dirY
if (bX !in 0..max || bY !in 0..max)
continue
if (input.none { abs(it.sensor.y - bY) + abs(it.sensor.x - bX) <= it.distance })
return bX * 4000000 + bY
}
}
}
return -1
}
private fun isTest() = input.maxOf { it.sensor.x } <= 100
data class Position(val x: Long, val y: Long)
data class SensorBeacon(val sensor: Position, val beacon: Position, val distance: Long) {
companion object {
fun from(line: String): SensorBeacon {
val sensorX = line.substringAfter("x=").substringBefore(",").toLong()
val beaconX = line.substringAfterLast("x=").substringBeforeLast(",").toLong()
val sensorY = line.substringAfter("y=").substringBefore(":").toLong()
val beaconY = line.substringAfterLast("y=").trim().toLong()
return SensorBeacon(
Position(sensorX, sensorY),
Position(beaconX, beaconY),
abs(sensorX - beaconX) + abs(sensorY - beaconY)
)
}
}
}
} | 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 2,220 | aoc2022 | MIT License |
day19/kotlin/corneil/src/main/kotlin/solution.kt | jensnerche | 317,661,818 | true | {"HTML": 2739009, "Java": 348790, "Kotlin": 271053, "TypeScript": 262310, "Python": 198318, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day19
import com.github.corneil.aoc2019.intcode.Program
import com.github.corneil.aoc2019.intcode.readProgram
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
data class Coord(val x: Int, val y: Int)
class Grid(val cells: MutableMap<Coord, Char> = mutableMapOf()) {
fun printToString(): String {
val sw = StringWriter()
sw.use {
PrintWriter(sw).use { pw ->
val maxY = cells.keys.maxBy { it.y }?.y ?: 0
val maxX = cells.keys.maxBy { it.x }?.x ?: 0
for (y in 0..maxY) {
pw.print(String.format("%02d ", y))
for (x in 0..maxX) {
val cell = cells[Coord(x, y)] ?: ' '
pw.print(cell)
}
pw.println()
}
}
}
return sw.toString()
}
fun tractorActiveLine(y: Int): Pair<Coord, Coord> {
val line = cells.entries.filter { it.key.y == y }.filter { it.value == '#' }.map { it.key }
if (line.isEmpty()) {
return Pair(Coord(0, 0), Coord(0, 0))
}
val start = line.minBy { it.x } ?: error("Expected values for $y")
val end = line.maxBy { it.x } ?: error("Expected values for $y")
return Pair(start, end)
}
}
fun readGrid(input: String): Grid {
val grid = Grid()
var x = 0
var y = 0
input.forEach { c ->
when (c) {
'\n' -> {
if (grid.cells.isNotEmpty()) {
y += 1
}
x = 0
}
'.', '#' -> {
grid.cells[Coord(x, y)] = c
x += 1
}
}
}
return grid
}
fun scanGrid(code: List<Long>, width: Int, height: Int): Grid {
val grid = Grid()
scanGrid(code, grid, 0, width - 1, 0, height - 1)
return grid
}
fun scanGrid(code: List<Long>, grid: Grid, left: Int, right: Int, top: Int, bottom: Int) {
for (x in left..right) {
for (y in top..bottom) {
scanCoord(code, x, y, grid)
}
}
}
fun scanCoord(code: List<Long>, x: Int, y: Int, grid: Grid): Char {
val program = Program(code).createProgram()
val output = program.executeUntilOutput(listOf(x.toLong(), y.toLong()))
require(output.size == 1)
val out = output.first()
val cell = when (out) {
0L -> '.'
1L -> '#'
else -> ('0' + out.toInt())
}
grid.cells[Coord(x, y)] = cell
return cell
}
fun scanStanta(code: List<Long>, size: Int): Long {
val grid = scanGrid(code, size + 2, size + 2)
var top = size + 1
do {
print("Scan=${top}\r")
scanLine(2, code, top, grid)
val result = checkSolution(grid, size, top)
if (result != 0L) {
return result
}
top += 1
} while (true)
}
fun checkSolution(grid: Grid, size: Int, start: Int = size + 1): Long {
val exit = Pair(Coord(0, 0), Coord(0, 0))
var maxY = grid.cells.keys.maxBy { it.y }?.y ?: error("Expected values")
for (top in (start)..maxY) {
val last = grid.tractorActiveLine(top)
if (last == exit) {
error("No solution")
}
val first = grid.tractorActiveLine(top - size + 1)
if (last.first.x == (first.second.x - size) + 1) {
println("\nFirst = $first, Last = $last")
return (last.first.x.toLong() * 10000L) + first.first.y.toLong()
}
}
return 0
}
fun scanLine(left: Int, code: List<Long>, top: Int, grid: Grid) {
var x = left - 2
do {
val c = scanCoord(code, x, top, grid)
x += 1
} while (c == '.')
do {
val c = scanCoord(code, x, top, grid)
x += 1
} while (c == '#')
}
fun main() {
val code = readProgram(File("input.txt"))
val grid = scanGrid(code, 50, 50)
println(grid.printToString())
val affected = grid.cells.values.count { it == '#' }
println("Affected = $affected")
require(affected == 126)
val loc = scanStanta(code, 100)
println("Answer = $loc")
require(loc == 11351625L)
}
| 0 | HTML | 0 | 0 | a84c00ddbeb7f9114291125e93871d54699da887 | 4,201 | aoc-2019 | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day11.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2021
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.P
import se.saidaspen.aoc.util.neighbors
fun main() = Day11.run()
object Day11 : Day(2021, 11) {
override fun part1(): Any {
val lines = input.lines()
val octs = mutableMapOf<P<Int, Int>, Int>()
for (line in lines.indices) {
val lineChars = lines[line].toCharArray()
for (col in lineChars.indices) {
octs[P(col, line)] = lineChars[col].toString().toInt()
}
}
var flashes = 0
var step = 1
while (step <= 100) {
octs.keys.forEach { octs.merge(it, 1, Int::plus) }
// flashes
val hasFlashed = mutableListOf<Pair<Int, Int>>()
var toFlash: List<Pair<Int, Int>>
flashes@ do {
toFlash = octs.entries
.filter { it.value > 9 }
.map { it.key }
.filter { octs.containsKey(it) }
.filter { !hasFlashed.contains(it) }
.distinct()
hasFlashed.addAll(toFlash)
flashes += toFlash.size
toFlash.flatMap { neighbors(it) }.filter { octs.containsKey(it) }
.forEach { octs.merge(it, 1, Int::plus) }
} while (toFlash.isNotEmpty())
// reset
hasFlashed.forEach { octs[it] = 0 }
step++
}
return flashes
}
override fun part2(): Any {
val lines = input.lines()
val octs = mutableMapOf<P<Int, Int>, Int>()
for (line in lines.indices) {
val lineChars = lines[line].toCharArray()
for (col in lineChars.indices) {
octs[P(col, line)] = lineChars[col].toString().toInt()
}
}
var flashes = 0
var step = 1
while (true) {
octs.keys.forEach { octs.merge(it, 1, Int::plus) }
// flashes
val hasFlashed = mutableListOf<Pair<Int, Int>>()
var toFlash: List<Pair<Int, Int>>
flashes@ do {
toFlash = octs.entries
.filter { it.value > 9 }
.map { it.key }
.filter { octs.containsKey(it) }
.filter { !hasFlashed.contains(it) }
.distinct()
hasFlashed.addAll(toFlash)
flashes += toFlash.size
toFlash.flatMap { neighbors(it) }.filter { octs.containsKey(it) }
.forEach { octs.merge(it, 1, Int::plus) }
} while (toFlash.isNotEmpty())
// reset
hasFlashed.forEach { octs[it] = 0 }
if (hasFlashed.size == octs.size) {
return step
}
step++
}
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,877 | adventofkotlin | MIT License |
src/Day21.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | import java.util.*
enum class Operation(val c: Char) {
PLUS('+'),
MINUS('-'),
MUL('*'),
DIV('/');
companion object {
fun parse(c: Char): Operation {
return when(c) {
'+' -> PLUS
'-' -> MINUS
'*' -> MUL
'/' -> DIV
else -> error("bad op $c")
}
}
}
}
data class Expression(val name: String, val firstName: String, val op: Operation, val secondName: String) {
var first: Long? = null
var second: Long? = null
}
fun main() {
fun part1(input: List<String>): Long {
val numbers = mutableMapOf<String, Long>()
val ops = mutableListOf<Expression>()
fun parse(s: String) {
// lgvd: ljgn * ptdq
// hmdt: 32
val regex = """(\w+): (\d+)?(?:(\w+) ([+\-*/]) (\w+))?""".toRegex()
val (name, number, firstName, op, secondName) = regex.matchEntire(s)//?.groupValues
//?.map { it.toInt() }
?.destructured
?: error("Bad input '$s'")
if (number.isNotEmpty())
numbers[name] = number.toLong()
else
ops.add(Expression(name, firstName, Operation.parse(op.first()), secondName))
}
fun solve(first: Long, op: Operation, second: Long): Long {
return when(op) {
Operation.PLUS -> first + second
Operation.MINUS -> first - second
Operation.MUL -> first * second
Operation.DIV -> first / second
}
}
input.forEach { line ->
parse(line)
}
while (true) {
val itr = ops.iterator()
while (itr.hasNext()) {
with(itr.next()) {
if (first == null) {
first = numbers[firstName]
}
if (second == null) {
second = numbers[secondName]
}
if (first != null && second != null) {
val solvedNumber = solve(first!!, op, second!!)
numbers[name] = solvedNumber
if (name == "root") return numbers[name]!!
else itr.remove()
}
}
}
}
return 0
}
fun part2(input: List<String>): Long {
val numbers = mutableMapOf<String, Long>()
val ops = mutableMapOf<String, Expression>()
fun parse(s: String) {
// lgvd: ljgn * ptdq
// hmdt: 32
val regex = """(\w+): (\d+)?(?:(\w+) ([+\-*/]) (\w+))?""".toRegex()
val (name, number, first, op, second) = regex.matchEntire(s)//?.groupValues
//?.map { it.toInt() }
?.destructured
?: error("Bad input '$s'")
if (number.isNotEmpty())
numbers[name] = number.toLong()
else
ops[name] = Expression(name, first, Operation.parse(op.first()), second)
}
input.forEach { line ->
parse(line)
}
fun solve(first: Long, op: Operation, second: Long): Long {
return when(op) {
Operation.PLUS -> first + second
Operation.MINUS -> first - second
Operation.MUL -> first * second
Operation.DIV -> first / second
}
}
fun calc(expr: Expression): Long? {
with(expr) {
first = numbers[firstName] ?: if (firstName == "humn") null else calc( ops[firstName]!!)
second = numbers[secondName] ?: if (secondName == "humn") null else calc( ops[secondName]!!)
if (first != null && second != null)
return solve(first!!, op, second!!).also { numbers[name] = it }
else
return null
}
}
fun printExpr(expr: Expression) {
with(expr) {
if (first != null) print(first)
else {
if (firstName == "humn") print("X")
// val firstExpr = ops[firstName]
// if (firstExpr == null) print("X")
else {
print("(")
printExpr(ops[firstName]!!)
print(")")
}
}
print(op.c)
if (second != null) print(second)
else {
if (secondName == "humn") print("X")
// val secondExpr = ops[secondName]
// if (secondExpr == null) print("X")
else {
print("(")
printExpr(ops[secondName]!!)
print(")")
}
}
}
}
val left = ops[ops["root"]?.firstName]!!
val right = ops[ops["root"]?.secondName]!!
//// for (i in 0 .. (Int.MAX_VALUE / 10).toLong()) {
// for (i in 0 downTo (-Int.MAX_VALUE / 10).toLong()) {
// numbers["humn"] = i
// if (calc(left) == calc(right)) return i
// }
numbers.remove("humn")
println(calc(left))
println(calc(right))
printExpr(left)
println()
// with help of cite
// https://math.semestr.ru/math/expand.php
// and WolframAlpha
// https://www.wolframalpha.com/input?i=%5Cfrac%7B7511588713779448%7D%7B135%7D-%5Cfrac%7B76636%5Ccdot+x%7D%7B6075%7D%3D6745394553620
numbers["humn"] = 3876027196185
println(calc(left)) // check equality
return TODO("Provide the return value")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day21_test")
// val testInput2 = readInput("Day21_test2")
// println(part1(testInput))
// check(part1(testInput2) == 33)
// check(part1(testInput) == 152L)
// println(part2(testInput))
// check(part2(testInput) == 301)
@Suppress("UNUSED_VARIABLE")
val input = readInput("Day21")
// check(part1(input)) == 62386792426088
// check(part2(input)) ==
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 6,398 | AoC-2022 | Apache License 2.0 |
day04/Kotlin/day04.kt | Ad0lphus | 353,610,043 | false | {"C++": 195638, "Python": 139359, "Kotlin": 80248} | import java.io.*
fun print_day_4() {
val yellow = "\u001B[33m"
val reset = "\u001b[0m"
val green = "\u001B[32m"
println(yellow + "-".repeat(25) + "Advent of Code - Day 4" + "-".repeat(25) + reset)
println(green)
val process = Runtime.getRuntime().exec("figlet Giant Squid -c -f small")
val reader = BufferedReader(InputStreamReader(process.inputStream))
reader.forEachLine { println(it) }
println(reset)
println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n")
}
fun main() {
print_day_4()
print("Puzzle 1: ")
Day4().part_1()
print("Puzzle 2: ")
Day4().part_2()
println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n")
}
class Day4 {
private val lines = File("../Input/day4.txt").readLines()
private val drawOrder = lines[0].split(",").map { it.toInt() }
private val boards =
lines.drop(1).windowed(6, 6) {
it.drop(1).map { line ->
line.trim().split(" ", " ").map { numStr -> numStr.toInt() }
}
}
fun checkLine(line: List<Int>, drawn: List<Int>) = drawn.containsAll(line)
fun checkBoard(board: List<List<Int>>, drawn: List<Int>): Boolean {
val hasHorizontalLine = board.any { checkLine(it, drawn) }
val flippedBoard =
(board[0].indices).map { outer ->
(board.indices).map { inner -> board[inner][outer] }
}
val hasVerticalLine = flippedBoard.any { checkLine(it, drawn) }
return hasHorizontalLine || hasVerticalLine
}
fun part_1() {
for (i in 5..drawOrder.size) {
val currentDraw = drawOrder.take(i)
boards.forEach() {
if (checkBoard(it, currentDraw)) {
return calculateWinner(it, currentDraw)
}
}
}
}
private fun calculateWinner(board: List<List<Int>>, currentDraw: List<Int>) {
println(board.flatten().filter { !currentDraw.contains(it) }.sum() * currentDraw.last())
}
fun part_2() {
val winners = mutableListOf<Int>()
for (i in 5..drawOrder.size) {
val currentDraw = drawOrder.take(i)
boards.forEachIndexed() { index, board ->
if (!winners.contains(index) && checkBoard(board, currentDraw)) {
winners.add(index)
if (winners.size == boards.size) {
return calculateWinner(board, currentDraw)
}
}
}
}
}
}
| 0 | C++ | 0 | 0 | 02f219ea278d85c7799d739294c664aa5a47719a | 2,612 | AOC2021 | Apache License 2.0 |
src/questions/SortCharByFrequency.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBeOneOf
import java.util.*
/**
*
* Given a string s, sort it in decreasing order based on the frequency of the characters.
* The frequency of a character is the number of times it appears in the string.
* Return the sorted string. If there are multiple answers, return any of them.
* [Source](https://leetcode.com/problems/sort-characters-by-frequency/)
*/
@UseCommentAsDocumentation
fun frequencySort(s: String): String {
if (s.length <= 2) return s
// Maintains map of char to its count
val charToCountMap = HashMap<Char, Int>(s.length)
for (i in 0..s.lastIndex) {
charToCountMap[s[i]] = charToCountMap.getOrDefault(s[i], 0) + 1
}
// maintains SORTED map of count to the character with that frequency
// sorted w.r.t frequency of occurrence in reverse order
// eg: in "cccaaabb" -> 3: "cccaaa", 2: "bb"
val countToCharMap = TreeMap<Int, String>(object : Comparator<Int> {
override fun compare(o1: Int?, o2: Int?): Int {
return o2!! - o1!! // This will be sorted in reverse order of frequency
}
})
charToCountMap.forEach { (k, count) ->
countToCharMap[count] = countToCharMap.getOrDefault(count, "") + k.toString().repeat(count)
}
// [countToCharMap] is already sorted so just join the values
return countToCharMap.values.joinToString("")
}
fun main() {
frequencySort(s = "tree") shouldBeOneOf listOf("eert", "eetr")
frequencySort(s = "cccaaa") shouldBeOneOf listOf("cccaaa", "aaaccc")
frequencySort(s = "Aabb") shouldBeOneOf listOf("bbAa", "bbaA")
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 1,653 | algorithms | MIT License |
kotlin/src/com/s13g/aoc/aoc2020/Day18.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 18: Operation Order ---
* https://adventofcode.com/2020/day/18
*/
class Day18 : Solver {
/** Either 'v' value or sub-group 'g' are allowed, but not both. */
private data class Expr(val op: Char, val v: Long, val g: List<Expr> = emptyList())
private fun Expr.doOp(other: Expr, prio: Char) =
if (op == '+') solve(prio) + other.solve(prio) else solve(prio) * other.solve(prio)
override fun solve(lines: List<String>): Result {
val input = lines.map { Expr(' ', 0, parse(it.replace("\\s".toRegex(), ""))) }
return Result("${input.map { it.solve(' ') }.sum()}", "${input.map { it.solve('+') }.sum()}")
}
/** Recursively parses the expression. */
private fun parse(line: String): List<Expr> {
val chain = mutableListOf<Expr>()
var op = ' '
var n = -1
while (++n < line.length) {
val s = line[n]
when (s) {
in listOf('+', '*') -> op = s
'(' -> {
val closeIdx = findMatchingClose(line.substring(n + 1))
chain.add(Expr(op, 0, parse(line.substring(n + 1, n + 1 + closeIdx))))
n += 1 + closeIdx
}
// Note: Input only contains single digit numbers.
else -> chain.add(Expr(op, s.toString().toLong()))
}
}
return chain
}
private fun Expr.solve(prio: Char) = if (this.g.isEmpty()) this.v else this.g.reduce(prio).v
private fun List<Expr>.reduce(prio: Char): Expr {
assert(this[0].op == ' ')
var reduced = mutableListOf(this[0])
if (prio != ' ') {
for (n in 1 until this.size)
if (this[n].op == prio) {
reduced[reduced.lastIndex] = Expr(reduced.last().op, this[n].doOp(reduced.last(), prio))
} else {
reduced.add(this[n])
}
} else {
reduced = this.toMutableList()
}
return reduced.reduce { acc, expr -> Expr(' ', expr.doOp(acc, prio)) }
}
private fun findMatchingClose(str: String): Int {
var opened = 0
for (n in str.indices) {
if (str[n] == '(') opened++
else if (str[n] == ')') if (--opened == -1) return n
}
error("Parsing error: Missing closing parenthesis.")
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,220 | euler | Apache License 2.0 |
code/day_07/src/jvm8Main/kotlin/task1.kt | dhakehurst | 725,945,024 | false | {"Kotlin": 105846} | package day_07
val map1 = mapOf(
"A" to 14,
"K" to 13,
"Q" to 12,
"J" to 11,
"T" to 10
)
data class Hand1(
val cards: String,
val bid: Int
) : Comparable<Hand1> {
val cardValues = cards.map { map1[it.toString()] ?: it.toString().toInt() }
val grouped = cardValues.groupBy { it }
val isFiveOfAKind = grouped.size==1
val isFourOfAKind = grouped.size==2 && grouped.maxOf { it.value.size }==4
val isFullHouse = grouped.size==2 && grouped.maxOf { it.value.size }==3 && grouped.minOf { it.value.size }==2
val isThreeOdAKind = grouped.size==3 && grouped.maxOf { it.value.size }==3
val isTwoPair = grouped.size==3 && grouped.maxOf { it.value.size }==2
val isOnePair = grouped.size==4 && grouped.maxOf { it.value.size }==2
val handValue = when {
isFiveOfAKind -> 6
isFourOfAKind -> 5
isFullHouse -> 4
isThreeOdAKind -> 3
isTwoPair -> 2
isOnePair -> 1
else -> 0
}
override fun compareTo(other: Hand1): Int = when {
this.handValue > other.handValue -> 1
this.handValue < other.handValue -> -1
this.handValue == other.handValue -> {
var r = 0
for(i in 0 .. 4) {
r = when {
cardValues[i] > other.cardValues[i] -> +1
cardValues[i] < other.cardValues[i] -> -1
else -> 0
}
if (0!=r) break
}
r
}
else -> 0
}
}
fun task1(lines: List<String>): Long {
var total = 0L
val hands = lines.map {
val cards = it.substringBefore(" ")
val bid = it.substringAfter(" ").toInt()
Hand1(cards, bid)
}
val sorted = hands.sortedBy { it }
sorted.forEachIndexed { idx, it ->
println("${it.cards} ${it.bid} ${idx+1} ${it.bid * (idx+1)}")
total += it.bid * (idx+1)
}
println("Day 07 task 1: $total")
return total
} | 0 | Kotlin | 0 | 0 | be416bd89ac375d49649e7fce68c074f8c4e912e | 1,990 | advent-of-code | Apache License 2.0 |
src/net/sheltem/pe/Task11.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.pe
import net.sheltem.common.*
import net.sheltem.common.Direction8.*
fun main() {
input
.lines()
.map {
it.split(" ")
.filter { string -> string.isNotBlank() }
.map { number ->
number.toLong()
}
}
.maxMultiple()
.let(::println)
}
private fun List<List<Long>>.maxMultiple(): Long {
val visited = mutableListOf<List<Long>>()
val directions = listOf(EAST, SOUTH_EAST, SOUTH, SOUTH_WEST)
return this.flatMapIndexed { y, line ->
line.indices.mapNotNull { x ->
val current = x to y
directions.maxOfOrNull { dir ->
current
.lineTo(dir, 3)
.takeIf { list -> list.all { it.withinMap(this) } }
?.map { this[it.second][it.first] }
?.also { visited.add(it) }
?.multiply() ?: 0
}
}
}.max()
}
val input = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48""".trimIndent()
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 2,320 | aoc | Apache License 2.0 |
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day13.kt | clechasseur | 568,233,589 | false | {"Kotlin": 242914} | package io.github.clechasseur.adventofcode.y2015
import io.github.clechasseur.adventofcode.util.permutations
import io.github.clechasseur.adventofcode.y2015.data.Day13Data
object Day13 {
private val input = Day13Data.input
private val happyRegex = """^(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+).$""".toRegex()
fun part1(): Int {
val instructions = input.toInstructions()
val persons = instructions.keys.toList()
val arrangements = permutations(persons)
return arrangements.maxOf { it.happiness(instructions) }
}
fun part2(): Int {
val instructions = input.toInstructions()
instructions.keys.toList().forEach {
instructions[it]!!["Me"] = 0
instructions.computeIfAbsent("Me") { mutableMapOf() }[it] = 0
}
val persons = instructions.keys.toList()
val arrangements = permutations(persons)
return arrangements.maxOf { it.happiness(instructions) }
}
private fun List<String>.happiness(instructions: Map<String, Map<String, Int>>): Int =
(zipWithNext() + (last() to first())).sumOf { it.happiness(instructions) }
private fun Pair<String, String>.happiness(instructions: Map<String, Map<String, Int>>): Int =
instructions[first]!![second]!! + instructions[second]!![first]!!
private fun MutableMap<String, MutableMap<String, Int>>.addInstruction(instruction: String) {
val match = happyRegex.matchEntire(instruction) ?: error("Wrong instruction: $instruction")
val (a, swing, i, b) = match.destructured
computeIfAbsent(a) { mutableMapOf() }[b] = if (swing == "gain") i.toInt() else -i.toInt()
}
private fun String.toInstructions(): MutableMap<String, MutableMap<String, Int>> {
val instructions = mutableMapOf<String, MutableMap<String, Int>>()
lines().forEach { instructions.addInstruction(it) }
return instructions
}
}
| 0 | Kotlin | 0 | 0 | e5a83093156cd7cd4afa41c93967a5181fd6ab80 | 1,966 | adventofcode2015 | MIT License |
2021/01/24/huisam/129_SumRootToLeafNumbers.kt | Road-of-CODEr | 323,110,862 | false | null | package com.huisam.kotlin.leetcode
/**
* LeetCode Problem
* @see <a href="https://leetcode.com/problems/sum-root-to-leaf-numbers/submissions/">문제링크</a>
*/
data class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
class Solution3 {
fun sumNumbers(root: TreeNode?): Int {
return if (root?.left == null && root?.right == null) {
root?.`val` ?: 0
} else sumHelper(root, 0)
}
private fun sumHelper(node: TreeNode?, value: Int): Int {
if (node?.left == null && node?.right == null) {
return value + (node?.`val` ?: 0)
}
val nextValue = value + node.`val`
var res = 0
if (node.left != null) {
res += sumHelper(node.left, nextValue * 10)
}
if (node.right != null) {
res += sumHelper(node.right, nextValue * 10)
}
return res
}
}
fun main() {
val left = TreeNode(9)
val right = TreeNode(0)
val root = TreeNode(4)
root.left = left
root.right = right
val leftLeft = TreeNode(5)
val leftRight = TreeNode(1)
left.left = leftLeft
left.right = leftRight
println(Solution3().sumNumbers(root))
}
| 1 | Java | 25 | 22 | cae1df83ac110519a5f5d6b940fa3e90cebb48c1 | 1,232 | stupid-week-2021 | MIT License |
src/main/kotlin/com/sk/set3/399. Evaluate Division.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set3
class Solution399 {
fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray {
val map = HashMap<String, Node>()
for (i in equations.indices) {
val eq = equations[i]
val first = eq[0]
val second = eq[1]
if (map.containsKey(first).not()) {
val node = Node()
node.values = ArrayList()
node.neighbours = ArrayList()
map[first] = node
}
if (map.containsKey(second).not()) {
val node = Node()
node.values = ArrayList()
node.neighbours = ArrayList()
map[second] = node
}
val node1 = map[first]
val node2 = map[second]
node1?.neighbours?.add(node2)
node1?.values?.add(values[i])
node2?.neighbours?.add(node1)
node2?.values?.add(1/values[i])
}
val res = DoubleArray(queries.size) { -1.0 }
for (i in queries.indices) {
val query = queries[i]
val first = query[0]
val second = query[1]
val node1 = map[first] ?: continue
val node2 = map[second] ?: continue
var ans = 1
val seen = HashSet<Node>()
res[i] = dfs(node1, 1.0, node2, seen)
}
return res
}
private fun dfs(node: Node?, value: Double, target: Node, seen: HashSet<Node>): Double {
if (node == null || seen.contains(node)) return -1.0
if (node == target) {
return value
}
seen.add(node)
for (i in node.neighbours?.indices!!) {
val neighbour = node.neighbours!![i]
val v = node.values?.get(i)
dfs(neighbour, value * v!!, target, seen).let {
if (it != -1.0) return it
}
}
return -1.0
}
class Node {
var values: ArrayList<Double>? = null
var neighbours: ArrayList<Node?>? = null
}
} | 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,114 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day7.kt | hughjdavey | 159,955,618 | false | null | package days
import util.addAndGet
class Day7 : Day(7) {
override fun partOne(): String {
val steps = parseSteps(inputList)
val execution = (0 until steps.size).map { i ->
val eligibleSteps = steps.filterNot { it.done }
.filter { it.dependencies.isEmpty() }
.sortedBy { it.name }
val mostEligible = eligibleSteps.first()
mostEligible.complete()
steps.forEach { step -> step.dependencies.removeIf { it == mostEligible.name } }
mostEligible.name
}
return execution.joinToString("")
}
// todo improve this (remove while loop ideally)
override fun partTwo(): Any {
val steps = parseSteps(inputList)
val workerPool = Array(5) { Worker() }
var seconds = -1
while (true) {
workerPool.forEach { it.update() }
seconds++
val completedSteps = steps.filter { it.done }.map { it.name }
if (completedSteps.size == steps.size) {
break
}
steps.forEach { step -> step.dependencies.removeIf { completedSteps.contains(it) } }
val eligibleSteps = steps.filterNot { it.doing }
.filter { it.dependencies.isEmpty() }
.sortedBy { it.name }
if (workerPool.none { it.isFree() }) {
continue
}
else if (eligibleSteps.isEmpty()) {
continue
}
eligibleSteps.zip(workerPool.filter { it.isFree() }).forEach { (step, worker) ->
worker.startWork(step)
}
//println("Second: $seconds; Steps: ${steps.filter { it.doing }}; Done: ${steps.filter { it.done }}")
}
return seconds
}
data class Step(val name: Char) {
val dependencies = mutableSetOf<Char>()
var secondsNeeded = 60 + ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(this.name) + 1)
var done = false
var doing = false
fun complete() {
done = true
doing = false
}
fun doWork() {
if (--secondsNeeded == 0) {
this.complete()
}
}
}
class Worker {
private var step: Step? = null
fun isFree() = step == null
fun startWork(step: Step) {
this.step = step
step.doing = true
}
fun update() {
if (this.step != null) {
this.step!!.doWork()
if (this.step!!.done) {
this.step = null
}
}
}
}
companion object {
fun parseSteps(input: List<String>): Collection<Step> {
return input.map { str -> str[36] to str[5] }.fold(mutableSetOf()) { steps, dependency ->
(steps.find { it.name == dependency.first } ?: steps.addAndGet(Step(dependency.first))).dependencies.add(dependency.second)
(steps.find { it.name == dependency.second } ?: steps.addAndGet(Step(dependency.second)))
steps
}
}
}
}
| 0 | Kotlin | 0 | 0 | 4f163752c67333aa6c42cdc27abe07be094961a7 | 3,162 | aoc-2018 | Creative Commons Zero v1.0 Universal |
leetcode-75-kotlin/src/main/kotlin/CanPlaceFlowers.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* You have a long flowerbed in which some of the plots are planted, and some are not.
* However, flowers cannot be planted in adjacent plots.
*
* Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n,
* return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
*
*
*
* Example 1:
*
* Input: flowerbed = [1,0,0,0,1], n = 1
* Output: true
* Example 2:
*
* Input: flowerbed = [1,0,0,0,1], n = 2
* Output: false
*
*
* Constraints:
*
* 1 <= flowerbed.length <= 2 * 10^4
* flowerbed[i] is 0 or 1.
* There are no two adjacent flowers in flowerbed.
* 0 <= n <= flowerbed.length
* @see <a href="https://leetcode.com/problems/can-place-flowers/">LeetCode</a>
*/
fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean {
var remainingFlowers = n
for (index in 0 until flowerbed.size) {
if (remainingFlowers == 0) return true
if (flowerbed[index] == 0
&& (index == 0 || flowerbed[index - 1] == 0)
&& (index == flowerbed.lastIndex || flowerbed[index + 1] == 0)
) {
flowerbed[index] = 1
remainingFlowers--
}
}
return remainingFlowers == 0
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,291 | leetcode-75 | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2023/calendar/day23/Day23.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2023.calendar.day23
import arrow.core.fold
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import kotlin.math.max
class Day23 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(filename: String) = generatorFactory.forFile(filename).read { input ->
val grid = input.map { row -> row.toList() }.toList()
val start = Location(0, grid[0].indexOf('.'))
val goal = Location(grid.lastIndex, grid[grid.lastIndex].indexOf('.'))
dfs(grid, start, goal)
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input ->
val grid = input.map { row -> row.toList() }.toList()
val adjacencyGraph = makeAdjacencies(grid)
val start = Location(0, grid[0].indexOf('.'))
val goal = Location(grid.lastIndex, grid[grid.lastIndex].indexOf('.'))
dfsWithAdjacencies(adjacencyGraph, start, goal)
}
private fun dfs(
grid: List<List<Char>>,
location: Location,
goal: Location,
visited: MutableSet<Location> = mutableSetOf(),
steps: Int = 0
): Int {
if (location == goal) {
return steps
}
visited.add(location)
val distanceToEnd = getNeighbors(grid, location)
.filter { it !in visited }
.map { dfs(grid, it, goal, visited, steps + 1) }
.maxOfOrNull { it }
?: steps
visited.remove(location)
return distanceToEnd
}
private fun makeAdjacencies(grid: List<List<Char>>): Map<Location, Map<Location, Int>> {
// create a list of every location, and their direct neighbors
val adjacencies = grid.indices.flatMap { rowIndex ->
grid[rowIndex].indices.filter { grid[rowIndex][it] != '#' }.map { colIndex ->
val neighbors = DIRECTIONS_WITH_SLOPE
.map { (dr, dc, _) -> rowIndex + dr to colIndex + dc }
.filter { (row, col) -> row in grid.indices && col in grid[0].indices && grid[row][col] != '#' }
.associateTo(mutableMapOf()) { (row, col) -> Location(row, col) to 1 }
Location(rowIndex, colIndex) to neighbors
}
}.toMap(mutableMapOf())
// collapse all the nodes that have "two neighbors" (not a branching location)
adjacencies.keys.toList().forEach { location ->
adjacencies[location]?.takeIf { it.size == 2 }?.let { neighbors ->
val first = neighbors.keys.first()
val last = neighbors.keys.last()
val totalSteps = neighbors[first]!! + neighbors[last]!!
adjacencies.getOrPut(first) { mutableMapOf() }.merge(last, totalSteps, ::maxOf)
adjacencies.getOrPut(last) { mutableMapOf() }.merge(first, totalSteps, ::maxOf)
listOf(first, last).forEach { adjacencies[it]?.remove(location) }
adjacencies.remove(location)
}
}
return adjacencies
}
private fun dfsWithAdjacencies(
adjacencyGraph: Map<Location, Map<Location, Int>>,
location: Location,
goal: Location,
visited: MutableMap<Location, Int> = mutableMapOf()
): Int {
if (location == goal) { return visited.values.sum() }
return (adjacencyGraph[location] ?: emptyMap()).fold(0) { best, adjacency ->
val (neighbor, steps) = adjacency
if (neighbor in visited) { best } else {
visited.whileVisiting(neighbor, steps) {
max(best, dfsWithAdjacencies(adjacencyGraph, neighbor, goal, visited))
}
}
}
}
private inline fun <K, V, R> MutableMap<K, V>.whileVisiting(key: K, value: V, action: () -> R): R {
put(key, value)
return action().also { remove(key) }
}
private fun getNeighbors(grid: List<List<Char>>, location: Location): List<Location> {
val spot = grid[location.row][location.col]
return DIRECTIONS_WITH_SLOPE
.map { (dr, dc, slope) -> location.move(dr, dc) to slope }
.filter { (l, _) -> l.inGrid(grid) }
.filter { (l, slope) -> grid[l.row][l.col] != '#' && (spot == '.' || spot == slope) }
.map { (l, _) -> l }
}
data class Location(val row: Int, val col: Int) {
fun move(dr: Int, dc: Int) = Location(row + dr, col + dc)
fun inGrid(grid: List<List<Char>>) = row in grid.indices && col in grid[0].indices
}
data class MovementWithSlope(val rowDelta: Int, val colDelta: Int, val slope: Char)
companion object {
val NORTH = MovementWithSlope(-1, 0, '^')
val SOUTH = MovementWithSlope( 1, 0, 'v')
val EAST = MovementWithSlope( 0, 1, '>')
val WEST = MovementWithSlope( 0, -1, '<')
val DIRECTIONS_WITH_SLOPE = listOf(NORTH, SOUTH, EAST, WEST)
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 4,559 | advent-of-code | MIT License |
src/main/kotlin/g2401_2500/s2428_maximum_sum_of_an_hourglass/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2401_2500.s2428_maximum_sum_of_an_hourglass
// #Medium #Array #Matrix #Prefix_Sum #2023_07_05_Time_274_ms_(50.00%)_Space_40.5_MB_(100.00%)
class Solution {
fun maxSum(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
var res = 0
for (i in 0 until m) {
for (j in 0 until n) {
res = if (isHourGlass(i, j, m, n)) {
res.coerceAtLeast(calculate(i, j, grid))
} else {
// If we cannot form an hour glass from the current row anymore, just move to
// the next one
break
}
}
}
return res
}
// Check if an hour glass can be formed from the current position
private fun isHourGlass(r: Int, c: Int, m: Int, n: Int): Boolean {
return r + 2 < m && c + 2 < n
}
// Once we know an hourglass can be formed, just traverse the value
private fun calculate(r: Int, c: Int, grid: Array<IntArray>): Int {
var sum = 0
// Traverse the bottom and the top row of the hour glass at the same time
for (i in c..c + 2) {
sum += grid[r][i]
sum += grid[r + 2][i]
}
// Add the middle vlaue
sum += grid[r + 1][c + 1]
return sum
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,349 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/PossibleBipartition.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 886. Possible Bipartition
* @see <a href="https://leetcode.com/problems/possible-bipartition">Source</a>
*/
fun interface PossibleBipartition {
operator fun invoke(n: Int, dislikes: Array<IntArray>): Boolean
}
class PossibleBipartitionDFS : PossibleBipartition {
override operator fun invoke(n: Int, dislikes: Array<IntArray>): Boolean {
val graph: Array<MutableList<Int>> = Array(n + 1) { mutableListOf() }
for (dislike in dislikes) {
graph[dislike[0]].add(dislike[1])
graph[dislike[1]].add(dislike[0])
}
val colors = arrayOfNulls<Int>(n + 1)
for (i in 1..n) {
// If the connected component that node i belongs to hasn't been colored yet then try coloring it.
if (colors[i] == null && !dfs(graph, colors, i, 1)) {
return false
}
}
return true
}
private fun dfs(graph: Array<MutableList<Int>>, colors: Array<Int?>, currNode: Int, currColor: Int): Boolean {
colors[currNode] = currColor
// Color all uncolored adjacent nodes.
for (adjacentNode in graph[currNode]) {
if (colors[adjacentNode] == null) {
if (!dfs(graph, colors, adjacentNode, currColor * -1)) {
return false
}
} else if (colors[adjacentNode] == currColor) {
return false
}
}
return true
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,107 | kotlab | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2021/Day3.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2021
import net.voldrich.BaseDay
// https://adventofcode.com/2021/day/2
/* correct results:
gamma 1114, epsilon 2981, multiplied 3320834
oxygen: 101011101111, decimal: 2799
co2: 011001000001, decimal: 1601
multiply: 4481199
*/
fun main() {
Day3().run()
}
class Day3 : BaseDay() {
override fun task1() : Int {
val bitCount = input.lines()[0].length
val oneCounts = IntArray(bitCount)
input.lines().forEach {
for (i in 0 until bitCount) {
if (it[i] == '1') {
oneCounts[i] += 1
}
}
}
val gamma = StringBuilder()
val epsilon = StringBuilder()
for (i in 0 until bitCount) {
if (oneCounts[i] > input.lines().size / 2) {
gamma.append("0")
epsilon.append("1")
} else {
gamma.append("1")
epsilon.append("0")
}
}
val gammaDecimal = gamma.toString().toInt(2)
val epsilonDecimal = epsilon.toString().toInt(2)
return gammaDecimal * epsilonDecimal
}
override fun task2() : Int {
val oxygen = calculate(input.lines(), fun(oneCount, size): Char {
if (size == 2) return '1'
return if (oneCount >= size - oneCount) '1' else '0'
})
val co2 = calculate(input.lines(), fun(oneCount, size): Char {
if (size == 2) return '0'
return if (oneCount >= size - oneCount) '0' else '1'
})
println ("oxygen: $oxygen, decimal: ${oxygen.toInt(2)}")
println ("co2: $co2, decimal: ${co2.toInt(2)}")
return oxygen.toInt(2) * co2.toInt(2)
}
private fun calculate(lines: List<String>, logic: (Int, Int) -> Char): String {
val bitCount = lines[0].length
var filteredLines = lines
for (i in 0 until bitCount) {
val oneCount = calculateOneCount(i, filteredLines)
val filteredNum = logic(oneCount, filteredLines.size)
filteredLines = filteredLines.filter { it[i] == filteredNum }.toList()
if (filteredLines.size == 1) {
return filteredLines[0]
}
}
throw Exception("More then one lines remained " + filteredLines.size)
}
private fun calculateOneCount(index: Int, lines: List<String>) : Int {
return lines.map { it[index] }.count { it == '1' }
}
} | 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 2,465 | advent-of-code | Apache License 2.0 |
src/aoc2022/day05/AoC05.kt | Saxintosh | 576,065,000 | false | {"Kotlin": 30013} | package aoc2022.day05
import readAll
class Cmd(txt: String) {
val qty: Int
val c1: Int
val c2: Int
init {
val s = txt.split(" ")
qty = s[1].toInt()
c1 = s[3].toInt() - 1
c2 = s[5].toInt() - 1
}
companion object {
fun fromTxt(txt: String) = txt.lines().map { Cmd(it) }
}
}
class Stacks(txt: String) {
private val stacks: Array<MutableList<Char>>
init {
val l = txt.lines()
val last = l.last()
val count = last.trim().split(" ").last().toInt()
stacks = Array(count) { mutableListOf() }
l.dropLast(1).reversed().forEach { line ->
(0 until count).forEach { index ->
val ch = line[index * 4 + 1]
if (ch != ' ')
stacks[index].add(ch)
}
}
}
fun execute1(cmd: Cmd) {
repeat(cmd.qty) {
val last = stacks[cmd.c1].removeLast()
stacks[cmd.c2].add(last)
}
}
fun execute2(cmd: Cmd) {
val x = stacks[cmd.c1].takeLast(cmd.qty)
repeat(cmd.qty) { stacks[cmd.c1].removeLast() }
stacks[cmd.c2].addAll(x)
}
fun getTop() = String(stacks.map { it.last() }.toCharArray())
}
fun main() {
fun decode(txt: String): Pair<Stacks, List<Cmd>> {
val (a, b) = txt.split("\n\n")
return Stacks(a) to Cmd.fromTxt(b)
}
fun part1(txt: String): String {
val (stacks, cmdList) = decode(txt)
cmdList.forEach { stacks.execute1(it) }
return stacks.getTop()
}
fun part2(txt: String): String {
val (stacks, cmdList) = decode(txt)
cmdList.forEach { stacks.execute2(it) }
return stacks.getTop()
}
readAll("CMZ", "MCD", ::part1, ::part2)
}
| 0 | Kotlin | 0 | 0 | 877d58367018372502f03dcc97a26a6f831fc8d8 | 1,503 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day8/Day8.kt | cyril265 | 433,772,262 | false | {"Kotlin": 39445, "Java": 4273} | package day8
import readToList
private val input = readToList("day8.txt")
fun main() {
val validDigits = input.map { line ->
val (signalStr, digitStr) = line.split(" | ")
val signals = signalStr.split(" ").map { Digit(it) }.filter { validLengths.contains(it.sorted.size) }.toSet()
val digits = digitStr.split(" ").map { Digit(it) }
digits.filter { signals.contains(it) }
}
println(validDigits.sumOf { it.size })
}
private class Digit(val signal: String) {
val sorted = signal.toCharArray().sortedArray()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Digit
if (!sorted.contentEquals(other.sorted)) return false
return true
}
override fun hashCode(): Int {
return sorted.contentHashCode()
}
override fun toString(): String {
return "Digit(signal='$signal')"
}
}
private val validLengths = arrayOf(2, 3, 4, 7)
| 0 | Kotlin | 0 | 0 | 1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b | 1,037 | aoc2021 | Apache License 2.0 |
kotlin/src/katas/kotlin/eightQueen/EightQueen10.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.eightQueen
import org.hamcrest.CoreMatchers.equalTo
import org.junit.Assert.assertThat
import org.junit.Test
import java.lang.Math.abs
class EightQueen10 {
@Test fun `find all solutions for eight queen puzzle`() {
assertThat(findAllSolutions(boardSize = 0), equalTo(listOf(
Board()
)))
assertThat(findAllSolutions(boardSize = 1), equalTo(listOf(
Board(Queen(0, 0))
)))
assertThat(findAllSolutions(boardSize = 2), equalTo(listOf()))
assertThat(findAllSolutions(boardSize = 3), equalTo(listOf()))
assertThat(findAllSolutions(boardSize = 4), equalTo(listOf(
Board(Queen(1, 0), Queen(3, 1), Queen(0, 2), Queen(2, 3)),
Board(Queen(2, 0), Queen(0, 1), Queen(3, 2), Queen(1, 3))
)))
assertThat(findAllSolutions(boardSize = 8).size, equalTo(92))
assertThat(findAllSolutions(boardSize = 10).size, equalTo(724))
}
@Test fun `converts board to string`() {
assertThat(Board(Queen(0, 0), Queen(2, 1), Queen(1, 2)).toPrintableString(), equalTo(
"*--\n" +
"--*\n" +
"-*-"
))
}
private fun findAllSolutions(boardSize: Int): List<Board> {
return findAllSolutions(Board(boardSize, listOf()))
}
private fun findAllSolutions(board: Board): List<Board> {
if (board.isComplete()) return listOf(board)
return board.nextMoves().flatMap { boardWithNewMove ->
findAllSolutions(boardWithNewMove)
}
}
private data class Queen(val row: Int, val column: Int)
private data class Board(val size: Int, val queens: List<Queen>) {
constructor(vararg queens: Queen): this(maxPosition(queens), queens.toList())
fun nextMoves(): List<Board> {
val nextColumn = (queens.map { it.column }.maxOrNull() ?: -1) + 1
return 0.until(size)
.map { Queen(it, nextColumn) }
.filter { isValidMove(it) }
.map { Board(size, queens + it) }
}
fun isComplete(): Boolean {
return queens.size == size
}
private fun isValidMove(queen: Queen): Boolean {
val notOnTheSameLine = queens.none { it.row == queen.row || it.column == queen.column }
val notOnTheSameDiagonal = queens.none {
abs(it.row - queen.row) == abs(it.column - queen.column)
}
return notOnTheSameLine && notOnTheSameDiagonal
}
fun toPrintableString(): String {
return 0.until(size).map { row ->
0.until(size).map { column ->
if (queens.contains(Queen(row, column))) "*" else "-"
}.joinToString("")
}.joinToString("\n")
}
companion object {
private fun maxPosition(queens: Array<out Queen>): Int {
if (queens.isEmpty()) return 0
return Math.max(queens.map { it.row }.maxOrNull()!!, queens.map { it.column }.maxOrNull()!!) + 1
}
}
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 3,106 | katas | The Unlicense |
src/Lesson4CountingElements/MaxCounters.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} | /**
* 100/100
* @param N
* @param A
* @return
*/
fun solution(N: Int, A: IntArray): IntArray? {
var maxCounter = 0
var lastMaxCounter = 0
val resultCounters = IntArray(N)
for (i in A.indices) {
if (A[i] <= N) {
resultCounters[A[i] - 1] = java.lang.Math.max(resultCounters[A[i] - 1], lastMaxCounter)
resultCounters[A[i] - 1]++
maxCounter = java.lang.Math.max(resultCounters[A[i] - 1], maxCounter)
} else if (A[i] == N + 1) {
lastMaxCounter = maxCounter
}
}
for (i in resultCounters.indices) {
resultCounters[i] = java.lang.Math.max(resultCounters[i], lastMaxCounter)
}
return resultCounters
}
/**
* You are given N counters, initially set to 0, and you have two possible operations on them:
*
* increase(X) − counter X is increased by 1,
* max counter − all counters are set to the maximum value of any counter.
* A non-empty array A of M integers is given. This array represents consecutive operations:
*
* if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
* if A[K] = N + 1 then operation K is max counter.
* For example, given integer N = 5 and array A such that:
*
* A[0] = 3
* A[1] = 4
* A[2] = 4
* A[3] = 6
* A[4] = 1
* A[5] = 4
* A[6] = 4
* the values of the counters after each consecutive operation will be:
*
* (0, 0, 1, 0, 0)
* (0, 0, 1, 1, 0)
* (0, 0, 1, 2, 0)
* (2, 2, 2, 2, 2)
* (3, 2, 2, 2, 2)
* (3, 2, 2, 3, 2)
* (3, 2, 2, 4, 2)
* The goal is to calculate the value of every counter after all operations.
*
* Write a function:
*
* class Solution { public int[] solution(int N, int[] A); }
*
* that, given an integer N and a non-empty array A consisting of M integers, returns a sequence of integers representing the values of the counters.
*
* Result array should be returned as an array of integers.
*
* For example, given:
*
* A[0] = 3
* A[1] = 4
* A[2] = 4
* A[3] = 6
* A[4] = 1
* A[5] = 4
* A[6] = 4
* the function should return [3, 2, 2, 4, 2], as explained above.
*
* Write an efficient algorithm for the following assumptions:
*
* N and M are integers within the range [1..100,000];
* each element of array A is an integer within the range [1..N + 1].
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 2,355 | Codility-Kotlin | Apache License 2.0 |
src/Day03.kt | arksap2002 | 576,679,233 | false | {"Kotlin": 31030} | fun main() {
fun part1(input: List<String>): Int {
var result = 0
for (bag in input) {
val hashSet = mutableSetOf<Char>()
for (i in bag.indices) {
if (i < bag.length / 2) {
hashSet.add(bag[i])
} else {
if (hashSet.contains(bag[i])) {
hashSet.remove(bag[i])
result += if (bag[i] in 'A'..'Z') {
27 + (bag[i] - 'A')
} else {
1 + (bag[i] - 'a')
}
}
}
}
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
var index = 0
while (index < input.size) {
val hashSet1 = mutableSetOf<Char>()
for (i in input[index].indices) {
hashSet1.add(input[index][i])
}
index++
val hashSet2 = mutableSetOf<Char>()
for (i in input[index].indices) {
hashSet2.add(input[index][i])
}
index++
for (i in input[index].indices) {
if (hashSet1.contains(input[index][i]) && hashSet2.contains(input[index][i])) {
result += if (input[index][i] in 'A'..'Z') {
27 + (input[index][i] - 'A')
} else {
1 + (input[index][i] - 'a')
}
break
}
}
index++
}
return result
}
val input = readInput("Day03")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | a24a20be5bda37003ef52c84deb8246cdcdb3d07 | 1,747 | advent-of-code-kotlin | Apache License 2.0 |
src/Day04.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | fun main() {
fun getRangeSets(input: List<Pair<String, String>>) = input.map { (first, second) ->
first.toRangeSet() to second.toRangeSet()
}
fun part1(input: List<Pair<String, String>>) = getRangeSets(input).count { (f, s) ->
(f union s).size in listOf(f.size, s.size)
}
fun part2(input: List<Pair<String, String>>): Int = getRangeSets(input).count { (f, s) ->
(f union s).size < f.size + s.size
}
val input = readInputAndSplitInPairs("Day04", ",")
println(part1(input))
println(part2(input))
}
fun String.toRangeSet() = split("-").let {
it[0].toInt()..it[1].toInt()
}.toSet()
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 648 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | Sagolbah | 573,032,320 | false | {"Kotlin": 14528} | import kotlin.math.max
import kotlin.streams.toList
fun main() {
fun processInput(input: List<String>): List<List<Int>> {
val res = mutableListOf<List<Int>>()
for (line in input) {
res.add(line.codePoints().map { x -> x - '0'.code }.toList())
}
return res
}
fun part1(input: List<List<Int>>): Int {
val ans = mutableSetOf<Pair<Int, Int>>()
var mx = -1
// left traversal
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] > mx) {
ans.add(Pair(i, j))
mx = input[i][j]
}
}
mx = -1
}
// right traversal
for (i in input.indices) {
for (j in input[i].indices.reversed()) {
if (input[i][j] > mx) {
ans.add(Pair(i, j))
mx = input[i][j]
}
}
mx = -1
}
// upper traversal
for (j in input.indices) {
for (i in input.indices) {
if (input[i][j] > mx) {
ans.add(Pair(i, j))
mx = input[i][j]
}
}
mx = -1
}
// lower traversal
for (j in input.indices) {
for (i in input.indices.reversed()) {
if (input[i][j] > mx) {
ans.add(Pair(i, j))
mx = input[i][j]
}
}
mx = -1
}
return ans.size
}
fun part2(input: List<List<Int>>): Int {
// I'll use here naive O(n^3) solution, but it can be solved with O(n^2) preprocessing
var ans = -1
for (i in 1..input.size - 2) {
for (j in 1..input.size - 2) {
var up = 0
var down = 0
var left = 0
var right = 0
val my = input[i][j]
// up
for (k in (0 until i).reversed()) {
up++
if (input[k][j] >= my) break
}
// down
for (k in i + 1 until input.size) {
down++
if (input[k][j] >= my) break
}
// left
for (k in (0 until j).reversed()) {
left++
if (input[i][k] >= my) break
}
// right
for (k in j + 1 until input.size) {
right++
if (input[i][k] >= my) break
}
ans = max(ans, up * down * left * right)
}
}
return ans
}
val input = processInput(readInput("Day08"))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 893c1797f3995c14e094b3baca66e23014e37d92 | 2,888 | advent-of-code-kt | Apache License 2.0 |
src/main/kotlin/day10/part2/main.kt | TheMrMilchmann | 225,375,010 | false | null | /*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package day10.part2
import utils.*
import kotlin.math.*
fun main() {
val input = readInputText("/day10/input.txt")
val data = input.lineSequence().mapIndexed { y, line ->
line.mapIndexed { x, c ->
if (c == '#') Vec(x, y) else null
}
}.flatten().filterNotNull().toList()
println(run(data))
}
private fun run(data: List<Vec>): Int {
fun gcd(a: Int, b: Int): Int {
var r = abs(b)
var oldR = abs(a)
while (r != 0) {
val quotient = oldR / r
val tmpR = r
r = oldR - quotient * r
oldR = tmpR
}
return oldR
}
return data.map { station ->
station to data.asSequence()
.filter { it != station }
.map { Vec(it.x - station.x, -(it.y - station.y)) }
.groupBy {
when {
it.x == 0 -> Vec(0, it.y.sign)
it.y == 0 -> Vec(it.x.sign, 0)
else -> {
val gcd = gcd(it.x, it.y)
if (gcd >= 0) Vec(it.x / gcd, it.y / gcd) else it
}
}
}
.toList()
}.maxBy { (_, rays) -> rays.size }!!.let { (station, vecs) ->
fun Vec.angle(): Double {
val rawInRad = atan2(y.toDouble(), x.toDouble())
val invInRad = -rawInRad
val expInRad = (invInRad + 2 * PI) % (2 * PI)
val offInRad = (expInRad + PI / 2) % (2 * PI)
return offInRad
}
var j = 0
vecs.sortedBy { (rep, _) -> rep.angle() }
.let {
fun Vec.length() = sqrt(x.toDouble().pow(2) + y.toDouble().pow(2))
val rays = it.map { (_, ray) -> ray.toMutableList().sortedBy(Vec::length).toMutableList() }.toMutableList()
sequence {
var i = 0
while (rays.isNotEmpty()) {
val ray = rays[i]
val vec = ray.first()
yield(vec)
ray.removeAt(0)
if (ray.isEmpty()) {
rays.removeAt(i)
} else {
i++
}
if (i >= rays.size) i = 0
}
}
}
.toList()[199]
.let { 100 * (station.x + it.x) + (station.y + -it.y) }
}
}
private data class Vec(val x: Int, val y: Int) | 0 | Kotlin | 0 | 1 | 9d6e2adbb25a057bffc993dfaedabefcdd52e168 | 3,674 | AdventOfCode2019 | MIT License |
src/com/ssynhtn/medium/MaximumSubarray.kt | ssynhtn | 295,075,844 | false | {"Java": 639777, "Kotlin": 34064} | package com.ssynhtn.medium
class MaximumSubarray {
fun maxSubArrayDivConquer(nums: IntArray): Int {
return maxSubArrayDivConquer(nums, 0, nums.size)[0] // max, left max, right max, total, each requiring at least length one
}
// end > start
fun maxSubArrayDivConquer(nums: IntArray, start: Int, end: Int): IntArray {
if (end - start == 1) {
val ans = nums[start]
return intArrayOf(ans, ans, ans, ans)
}
val mid = (start + end) / 2
val max1 = maxSubArrayDivConquer(nums, start, mid)
val max2 = maxSubArrayDivConquer(nums, mid, end)
// val total = max1[3] + max2[3]
// val leftMax = Math.max(max1[1], max1[3] + max2[1])
// val rightMax = Math.max(max2[2], max2[3] + max1[2])
// val max = Math.max(max1[0], Math.max(max2[0], max1[2] + max2[1]))
max1[0] = Math.max(max1[0], Math.max(max2[0], max1[2] + max2[1]))
max1[1] = Math.max(max1[1], max1[3] + max2[1])
max1[2] = Math.max(max2[2], max2[3] + max1[2])
max1[3] = max1[3] + max2[3]
return max1
}
fun maxSubArray(nums: IntArray): Int {
var max = Int.MIN_VALUE
var sum = 0
for (num in nums) {
if (num > max) {
max = num
}
sum += num
if (sum > max) {
max = sum
}
if (sum < 0) {
sum = 0
}
}
return max
}
}
fun main(args: Array<String>) {
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(-2,1,-3,4,-1,2,1,-5,4)))
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(1)))
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(0)))
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(-1)))
println(MaximumSubarray().maxSubArrayDivConquer(intArrayOf(-2147483647)))
} | 0 | Java | 0 | 0 | 511f65845097782127bae825b07a51fe9921c561 | 1,907 | leetcode | Apache License 2.0 |
src/Day09.kt | SergeiMikhailovskii | 573,781,461 | false | {"Kotlin": 32574} | val uniqueItems = mutableSetOf<String>()
fun main() {
val input = readInput("Day09_test")
val snake = Array(10) {
arrayOf(0, 0)
}
input.forEach {
val direction = it.split(" ").first()
val amount = it.split(" ").last().toInt()
for (i in 0 until amount) {
when (direction) {
"D" -> snake.first()[1] += 1
"L" -> snake.first()[0] -= 1
"U" -> snake.first()[1] -= 1
"R" -> snake.first()[0] += 1
}
for (j in 0 until snake.size - 1) {
move(snake[j], snake[j + 1], j + 1 == snake.size - 1)
}
}
}
println(uniqueItems.size)
}
fun move(head: Array<Int>, tail: Array<Int>, isLast: Boolean) {
if (head[0] == tail[0]) {
if (head[1] - tail[1] > 1) {
tail[1] += 1
} else if (head[1] - tail[1] < -1) {
tail[1] -= 1
}
} else if (head[1] == tail[1]) {
if (head[0] - tail[0] > 1) {
tail[0] += 1
} else if (head[0] - tail[0] < -1) {
tail[0] -= 1
}
} else if ((head[0] - tail[0] > 1 && head[1] > tail[1]) || (head[1] - tail[1] > 1 && head[0] > tail[0])) {
tail[0] += 1
tail[1] += 1
} else if ((head[0] - tail[0] < -1 && head[1] > tail[1]) || (head[1] - tail[1] > 1 && head[0] < tail[0])) {
tail[0] -= 1
tail[1] += 1
} else if ((head[0] - tail[0] < -1 && head[1] < tail[1]) || (head[1] - tail[1] < -1 && head[0] < tail[0])) {
tail[0] -= 1
tail[1] -= 1
} else if ((head[0] - tail[0] > 1 && head[1] < tail[1]) || (head[1] - tail[1] < -1 && head[0] > tail[0])) {
tail[0] += 1
tail[1] -= 1
}
if (isLast) uniqueItems.add("${tail[0]} ${tail[1]}")
} | 0 | Kotlin | 0 | 0 | c7e16d65242d3be6d7e2c7eaf84f90f3f87c3f2d | 1,806 | advent-of-code-kotlin | Apache License 2.0 |
src/day07/Day07.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day07
import readLines
import java.lang.Math.random
import java.util.*
fun main() {
fun getDirectorySizes(input: List<String>): HashMap<String, Int> {
val directories = Stack<String>()
val directorySizes = HashMap<String, Int>()
for (line in input) {
val splitLine = line.split(" ")
if (splitLine[1] == "cd") {
if (splitLine[2] == "..") {
directories.pop()
} else {
directories.push(splitLine[2] + "_" + random())
}
}
else if (splitLine[0].toIntOrNull() != null) { // if file size
val size = splitLine[0].toInt()
for (directory in directories) {
if (directorySizes.containsKey(directory)) {
directorySizes[directory] = directorySizes.getValue(directory) + size
} else {
directorySizes[directory] = size
}
}
}
}
return directorySizes
}
fun part1(input: List<String>): Int {
val directorySizes = getDirectorySizes(input)
return directorySizes.values.filter { it <= 100000 }.sum()
}
fun part2(input: List<String>): Int {
val directorySizes = getDirectorySizes(input)
val rootDirectorySize = directorySizes.values.max()
val unusedSpace = 70000000 - rootDirectorySize
val neededSpace = 30000000 - unusedSpace
return directorySizes.values.filter { it - neededSpace > 0 }.min()
}
println(part1(readLines("day07/test")))
println(part1(readLines("day07/input")))
println(part2(readLines("day07/test")))
println(part2(readLines("day07/input")))
} | 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 1,794 | aoc2022 | Apache License 2.0 |
src/main/kotlin/g0301_0400/s0321_create_maximum_number/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0301_0400.s0321_create_maximum_number
// #Hard #Greedy #Stack #Monotonic_Stack #2022_11_12_Time_209_ms_(100.00%)_Space_36.2_MB_(100.00%)
class Solution {
fun maxNumber(nums1: IntArray, nums2: IntArray, k: Int): IntArray {
if (k == 0) {
return IntArray(0)
}
val maxSubNums1 = IntArray(k)
val maxSubNums2 = IntArray(k)
var res = IntArray(k)
// select l elements from nums1
for (l in 0..Math.min(k, nums1.size)) {
if (l + nums2.size < k) {
continue
}
// create maximum number for each array
// nums1: l elements; nums2: k - l elements
maxSubArray(nums1, maxSubNums1, l)
maxSubArray(nums2, maxSubNums2, k - l)
// merge the two maximum numbers
// if get a larger number than res, update res
res = merge(maxSubNums1, maxSubNums2, l, k - l, res)
}
return res
}
private fun maxSubArray(nums: IntArray, maxSub: IntArray, size: Int) {
if (size == 0) {
return
}
var j = 0
for (i in nums.indices) {
while (j > 0 && nums.size - i + j > size && nums[i] > maxSub[j - 1]) {
j--
}
if (j < size) {
maxSub[j++] = nums[i]
}
}
}
private fun merge(maxSub1: IntArray, maxSub2: IntArray, size1: Int, size2: Int, res: IntArray): IntArray {
val merge = IntArray(res.size)
var i = 0
var j = 0
var idx = 0
var equal = true
while (i < size1 || j < size2) {
if (j >= size2) {
merge[idx] = maxSub1[i++]
} else if (i >= size1) {
merge[idx] = maxSub2[j++]
} else {
var ii = i
var jj = j
while (ii < size1 && jj < size2 && maxSub1[ii] == maxSub2[jj]) {
ii++
jj++
}
if (ii < size1 && jj < size2) {
if (maxSub1[ii] > maxSub2[jj]) {
merge[idx] = maxSub1[i++]
} else {
merge[idx] = maxSub2[j++]
}
} else if (jj == size2) {
merge[idx] = maxSub1[i++]
} else {
// ii == size1
merge[idx] = maxSub2[j++]
}
}
// break if we already know merge must be < res
if (merge[idx] > res[idx]) {
equal = false
} else if (equal && merge[idx] < res[idx]) {
break
}
idx++
}
// if get a larger number than res, update res
val k = res.size
if (i == size1 && j == size2 && !equal) {
return merge
}
return if (equal && merge[k - 1] > res[k - 1]) {
merge
} else res
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,021 | LeetCode-in-Kotlin | MIT License |
src/main/aoc2018/Day10.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
class Day10(input: List<String>) {
private data class Pos(val x: Int, val y: Int) {
fun hasNeighbour(allPoints: Set<Pos>): Boolean {
return List(3) { nx -> List(3) { ny -> Pos(x - 1 + nx, y - 1 + ny) } }
.flatten()
.filterNot { it == this }
.any { allPoints.contains(it) }
}
}
private data class Point(val x: Int, val y: Int, val dx: Int, val dy: Int) {
fun posAt(time: Int) = Pos(x + dx * time, y + dy * time)
}
private val initialState = parseInput(input)
private fun List<Point>.at(time: Int) = map { it.posAt(time) }.toSet()
private fun parseInput(input: List<String>): List<Point> {
return input.map {
// To parse: position=< 3, 6> velocity=<-1, -1>
Point(
it.substringAfter("position=<").substringBefore(",").trim().toInt(),
it.substringAfter(",").substringBefore(">").trim().toInt(),
it.substringAfter("velocity=<").substringBefore(",").trim().toInt(),
it.substringAfterLast(",").dropLast(1).trim().toInt()
)
}
}
private fun findMessage(): Int {
for (time in 1..100000) {
val currentArrangement = initialState.at(time)
if (currentArrangement.all { it.hasNeighbour(currentArrangement) }) {
return time
}
}
return -1
}
private fun printMessage(points: Set<Pos>) {
for (y in points.minByOrNull { it.y }!!.y..points.maxByOrNull { it.y }!!.y) {
for (x in points.minByOrNull { it.x }!!.x..points.maxByOrNull { it.x }!!.x) {
print(if (points.contains(Pos(x, y))) '#' else ' ')
}
println()
}
}
fun solvePart1(): Int {
val messageTime = findMessage()
printMessage(initialState.at(messageTime))
return messageTime
}
fun solvePart2(): Int {
return findMessage()
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,054 | aoc | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LetterCombinations.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
/**
* 17. Letter Combinations of a Phone Number
* @see <a href="https://leetcode.com/problems/letter-combinations-of-a-phone-number">Source</a>
*/
fun interface LetterCombinations {
operator fun invoke(digits: String): List<String>
}
class LetterCombinationsRecursion : LetterCombinations {
companion object {
private const val DIGIT_OFFSET = 50
}
override operator fun invoke(digits: String): List<String> {
val arr = arrayOf("abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz")
return digits.mapNotNull { arr[it.code - DIGIT_OFFSET].toList() }.getCartesianProduct()
.map { String(it.toCharArray()) }
}
private fun <T> Collection<Iterable<T>>.getCartesianProduct(): List<List<T>> =
if (isEmpty()) {
emptyList()
} else {
drop(1)
.fold(first().map(::listOf)) { acc, iterable ->
acc.flatMap { list -> iterable.map(list::plus) }
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,645 | kotlab | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day05.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2021
class Day05(private val input: List<String>) {
fun solvePart1(): Int = solve(false)
fun solvePart2(): Int = solve(true)
private fun solve(diagonal: Boolean): Int {
val lineRegex = Regex("""(\d+),(\d+) -> (\d+),(\d+)""")
val map = mutableMapOf<Coordinate, Int>()
for (line in input) {
val values = lineRegex.find(line)!!.groupValues.drop(1).map(String::toInt)
val from = Coordinate(values[0], values[1])
val to = Coordinate(values[2], values[3])
if (diagonal || from.x == to.x || from.y == to.y) {
for (coordinate in CoordinateIterator(from, to)) {
map[coordinate] = map.getOrDefault(coordinate, 0) + 1
}
}
}
return map.count { it.value > 1 }
}
private data class Coordinate(val x: Int, val y: Int) {
operator fun plus(other: Coordinate) = Coordinate(x + other.x, y + other.y)
}
private class CoordinateIterator(from: Coordinate, to: Coordinate) : Iterator<Coordinate> {
private val step = Coordinate(to.x.compareTo(from.x), to.y.compareTo(from.y))
private val end = to + step
private var current = from
override fun hasNext(): Boolean = current != end
override fun next(): Coordinate {
val value = current
current = value + step
return value
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,473 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day14DockingData.kt | Scavi | 68,294,098 | false | {"Java": 1449516, "Kotlin": 59149} | package com.scavi.brainsqueeze.adventofcode
import kotlin.math.pow
class Day14DockingData(val isFluid: Boolean) {
private val memRegex by lazy { """(mem\[)(\d+)(\]\s+\=\s+)(\d+)""".toRegex() }
private data class Masks(val defaultMask: List<Pair<Char, Int>>, val fluidMask: List<List<Pair<Char, Int>>>)
private fun createMask(line: String): Masks {
val mask = mutableListOf<Pair<Char, Int>>()
val fluidMask = mutableListOf<List<Pair<Char, Int>>>()
val tmpFluid = mutableListOf<Int>()
for (i in line.indices) {
if (isFluid) {
if (line[i] == '1') {
mask.add(Pair(line[i], i))
} else if (line[i] == 'X') {
tmpFluid.add(i)
}
} else {
if (line[i] != 'X') {
mask.add(Pair(line[i], i))
}
}
}
if (isFluid) {
for (x in 0..(2.0.pow(tmpFluid.size.toDouble()).toInt())) {
fluidMask.add("%0${tmpFluid.size}d".format(Integer.toBinaryString(x).toInt()).toCharArray() zip tmpFluid)
}
}
return Masks(mask, fluidMask)
}
fun solve(instructions: List<String>): Long {
var masks = Masks(mutableListOf(), mutableListOf())
var memory = mutableMapOf<Long, Long>()
for (line in instructions) {
if (line.startsWith("mask")) {
masks = createMask(line.substring(7))
} else {
val (_, mem, _, v) = memRegex.find(line)!!.destructured
val value = if (isFluid) {
StringBuilder("0".repeat(36 - Integer.toBinaryString(mem.toInt()).length)
+ Integer.toBinaryString(mem.toInt()))
} else {
StringBuilder("0".repeat(36 - Integer.toBinaryString(v.toInt()).length)
+ Integer.toBinaryString(v.toInt()))
}
for (mask in masks.defaultMask) {
value[mask.second] = mask.first
}
if (isFluid) {
for (fluid in masks.fluidMask) {
for ((i, j) in fluid) {
value[j] = i
}
memory[value.toString().toLong(2)] = v.toLong()
}
} else {
memory[mem.toLong()] = value.toString().toLong(2)
}
}
}
return memory.map { it.value }.sum()
}
}
| 0 | Java | 0 | 1 | 79550cb8ce504295f762e9439e806b1acfa057c9 | 2,594 | BrainSqueeze | Apache License 2.0 |
src/day-7/part-1/solution-day-7-part-1.kts | d3ns0n | 572,960,768 | false | {"Kotlin": 31665} | import `day-7`.Directory
import `day-7`.File
import `day-7`.FileSystemItem
val root = Directory("/")
var currentDirectory = root
fun addFileSystemItem(string: String) {
if (string.startsWith("dir")) {
currentDirectory.content.add(Directory(string.substring(4), parent = currentDirectory))
} else {
val split = string.split(" ")
currentDirectory.content.add(File(split[1], split[0].toInt()))
}
}
fun processCommand(string: String) {
val command = string.removePrefix("$").trim()
if (command.startsWith("cd")) {
val target = command.removePrefix("cd").trim()
currentDirectory = when (target) {
"/" -> root
".." -> currentDirectory.parent
else -> currentDirectory.content.first { it is Directory && it.name == target } as Directory
}
}
}
fun process(string: String) {
if (string.startsWith("$")) {
processCommand(string)
} else {
addFileSystemItem(string)
}
}
fun findDirectoriesWithSizeUpTo(
itemsToProcess: List<FileSystemItem>,
foundItems: MutableList<FileSystemItem>,
limit: Int
): List<FileSystemItem> {
val directories = itemsToProcess.filterIsInstance<Directory>()
if (directories.isEmpty()) {
return foundItems
}
val firstDirectory = directories.first()
val remainingDirectories =
mutableListOf<FileSystemItem>(*directories.drop(1).toTypedArray()).apply {
this.addAll(firstDirectory.content)
}
if (firstDirectory.size <= limit) {
foundItems.add(firstDirectory)
}
return findDirectoriesWithSizeUpTo(remainingDirectories, foundItems, limit)
}
java.io.File("../input.txt").readLines()
.forEach { process(it) }
val wantedFileSystemItems = findDirectoriesWithSizeUpTo(root.content, mutableListOf(), 100000)
val totalSize = wantedFileSystemItems.sumOf { it.size }
println(totalSize)
assert(totalSize == 1077191)
| 0 | Kotlin | 0 | 0 | 8e8851403a44af233d00a53b03cf45c72f252045 | 1,948 | advent-of-code-22 | MIT License |
src/main/kotlin/com/sbg/vindinium/kindinium/model/board/BoardNavigator.kt | SoulBeaver | 23,961,494 | false | null | package com.sbg.vindinium.kindinium.model.board
import java.util.HashMap
import com.sbg.vindinium.kindinium.model.Position
import java.util.ArrayList
/**
* The BoardNavigator knows how to navigate a MetaBoard and create the shortest
* path to and from any Position.
*/
private class BoardNavigator(val metaboard: MetaBoard) {
/**
* Given a set of Positions, finds a path to the nearest one, if any.
*
* @return a Path to the nearest position in targets, or null if no Path could be found.
*/
public fun pathToNearest(targets: List<Position>, start: Position): Path? {
val pathsFromTargets = targets.map { target -> constructPathsFrom(start, target) }
var paths = HashMap<Position, Position?>()
var nearest = Position(0, 0)
var stepsToNearest = 9000
for ((i, pathsFromTarget) in pathsFromTargets.withIndices()) {
val stepsToTarget = countSteps(targets.get(i), pathsFromTarget)
if (stepsToTarget < stepsToNearest && stepsToTarget != 0) {
paths = pathsFromTarget
nearest = targets.get(i)
stepsToNearest = stepsToTarget
}
}
return Path(paths, nearest, start)
}
/**
* Constructs the shortest path to a given position.
*
* @return a Path to the given Position, or null if no Path could be found.
*/
public fun pathTo(to: Position, start: Position): Path {
val pathsToStart = constructPathsFrom(start, to)
return Path(pathsToStart, to, start)
}
private fun constructPathsFrom(start: Position, to: Position): HashMap<Position, Position?> {
val frontier = arrayListOf(start)
val cameFrom = hashMapOf<Position, Position?>(start to null)
while (frontier.isNotEmpty()) {
val current = frontier.first!!
frontier.remove(0)
for (next in neighbors(current, to)) {
if (!cameFrom.contains(next)) {
frontier.add(next)
cameFrom[next] = current
}
}
}
return cameFrom
}
private fun neighbors(position: Position, to: Position): List<Position> {
val neighbors = arrayListOf<Position>()
addIfViableNeighbor(neighbors, Position(position.x - 1, position.y), to)
addIfViableNeighbor(neighbors, Position(position.x + 1, position.y), to)
addIfViableNeighbor(neighbors, Position(position.x, position.y - 1), to)
addIfViableNeighbor(neighbors, Position(position.x, position.y + 1), to)
return neighbors
}
private fun addIfViableNeighbor(neighbors: ArrayList<Position>, candidate: Position, include: Position) {
if (candidate.x >= 0 && candidate.x < metaboard.board.size &&
candidate.y >= 0 && candidate.y < metaboard.board.size &&
(metaboard[candidate] == BoardTile.ROAD || candidate == include)) {
neighbors.add(candidate)
}
}
private fun countSteps(target: Position, paths: HashMap<Position, Position?>): Int {
var count = 0
var current: Position? = target
while (current != null) {
count++
current = paths[current]
}
return count - 1
}
} | 0 | Kotlin | 1 | 4 | 9150d6619229db4932494e95c92f6911a7dd3443 | 3,314 | kindinium | Apache License 2.0 |
src/Day03.kt | jimmymorales | 572,156,554 | false | {"Kotlin": 33914} | fun main() {
fun Char.priority() = (if (this <= 'Z') this - 'A' + 26 else this - 'a') + 1
fun part1(input: List<String>): Int = input.map { rubsack ->
rubsack.chunked(rubsack.length / 2, CharSequence::toSet)
.reduce(Set<Char>::intersect)
.single()
}.sumOf(Char::priority)
fun part2(input: List<String>): Int = input.windowed(step = 3, size = 3)
.map { groups ->
groups.map(String::toSet)
.reduce(Set<Char>::intersect)
.single()
}.sumOf(Char::priority)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
// part 2
check(part2(testInput) == 70)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fb72806e163055c2a562702d10a19028cab43188 | 855 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode2023/day16/day16.kt | dzkoirn | 725,682,258 | false | {"Kotlin": 133478} | package adventofcode2023.day16
import adventofcode2023.Point
import adventofcode2023.line
import adventofcode2023.readInput
import adventofcode2023.col
import kotlin.time.measureTime
fun main() {
println("day 16")
val input = readInput("day16")
val time1 = measureTime {
val output = findEnergizedPoints(input.map { it.toCharArray() })
println("Puzzle 1 ${output.size}")
}
println("Puzzle took $time1")
println("Puzzle 2")
val time2 = measureTime {
val output = findBestStartPoint(input)
println("Puzzle 2 $output")
}
println("Puzzle 2 took $time2")
}
data class RayHeader(
val point: Point,
val direction: Direction
) {
enum class Direction {
UP, LEFT, DOWN, RIGHT
}
}
fun handlePoint(rayHeader: RayHeader, char: Char): List<RayHeader> {
return when (char) {
'\\' -> listOf(
with(rayHeader.point) {
when(rayHeader.direction) {
RayHeader.Direction.UP -> RayHeader(copy(second = col - 1), RayHeader.Direction.LEFT)
RayHeader.Direction.LEFT -> RayHeader(copy(first = line - 1), RayHeader.Direction.UP)
RayHeader.Direction.DOWN -> RayHeader(copy(second = col + 1), RayHeader.Direction.RIGHT)
RayHeader.Direction.RIGHT -> RayHeader(copy(first = line + 1), RayHeader.Direction.DOWN)
}
}
)
'/' -> listOf(
with(rayHeader.point) {
when(rayHeader.direction) {
RayHeader.Direction.UP -> RayHeader(copy(second = col + 1), RayHeader.Direction.RIGHT)
RayHeader.Direction.LEFT -> RayHeader(copy(first = line + 1), RayHeader.Direction.DOWN)
RayHeader.Direction.DOWN -> RayHeader(copy(second = col - 1), RayHeader.Direction.LEFT)
RayHeader.Direction.RIGHT -> RayHeader(copy(first = line - 1), RayHeader.Direction.UP)
}
}
)
'-' -> with(rayHeader.point) {
buildList {
when(rayHeader.direction) {
RayHeader.Direction.LEFT -> add(RayHeader(copy(second = col - 1), RayHeader.Direction.LEFT))
RayHeader.Direction.RIGHT -> add(RayHeader(copy(second = col + 1), RayHeader.Direction.RIGHT))
RayHeader.Direction.DOWN, RayHeader.Direction.UP -> {
add(RayHeader(copy(second = col - 1), RayHeader.Direction.LEFT))
add(RayHeader(copy(second = col + 1), RayHeader.Direction.RIGHT))
}
}
}
}
'|' -> with(rayHeader.point) {
buildList {
when(rayHeader.direction) {
RayHeader.Direction.UP -> add(RayHeader(copy(first = line - 1), RayHeader.Direction.UP))
RayHeader.Direction.DOWN -> add(RayHeader(copy(first = line + 1), RayHeader.Direction.DOWN))
RayHeader.Direction.LEFT,
RayHeader.Direction.RIGHT -> {
add(RayHeader(copy(first = line - 1), RayHeader.Direction.UP))
add(RayHeader(copy(first = line + 1), RayHeader.Direction.DOWN))
}
}
}
}
else -> listOf(
RayHeader(
with(rayHeader.point) {
when(rayHeader.direction) {
RayHeader.Direction.UP -> copy(first = line - 1)
RayHeader.Direction.LEFT -> copy(second = col - 1)
RayHeader.Direction.DOWN -> copy(first = line + 1)
RayHeader.Direction.RIGHT -> copy(second = col + 1)
}
},
rayHeader.direction
)
)
}
}
tailrec fun findEnergizedPoints(
input: List<CharArray>,
rayHeaders: List<RayHeader> = listOf(RayHeader(Point(0,0), RayHeader.Direction.RIGHT)),
visitedPoints: MutableSet<RayHeader> = mutableSetOf()
): Set<Point> {
if (rayHeaders.isEmpty()) return visitedPoints.map { (p,_) -> p }.toSet()
visitedPoints.addAll(rayHeaders)
val newRayHeaders = rayHeaders.flatMap { rh ->
val ch = input[rh.point.line][rh.point.col]
handlePoint(rh, ch)
}.filter { (p, _) -> p.line in (0..input.lastIndex) && p.col in (0..input.first.lastIndex) }
.filter { it !in visitedPoints }
return findEnergizedPoints(input, newRayHeaders, visitedPoints)
}
fun visualize(input: List<CharArray>, points: Set<Point>): List<CharArray> {
points.forEach { (line, row) ->
input[line][row] = '#'
}
return input
}
fun findBestStartPoint(input: List<String>): Int {
val preparedInput = input.map { it.toCharArray() }
return listOf(
Array(input.size) { index -> RayHeader(Point(index, 0), RayHeader.Direction.RIGHT) },
Array(input.size) { index -> RayHeader(Point(index, input.first.lastIndex), RayHeader.Direction.LEFT) },
Array(input.first.length) { index -> RayHeader(Point(0, index), RayHeader.Direction.DOWN) },
Array(input.first.length) { index -> RayHeader(Point(input.lastIndex, index), RayHeader.Direction.UP) },
).flatMap { it.toList() }
.stream().parallel().map { start ->
findEnergizedPoints(preparedInput, listOf(start)).size
}.max(Comparator.naturalOrder()).get()
} | 0 | Kotlin | 0 | 0 | 8f248fcdcd84176ab0875969822b3f2b02d8dea6 | 5,446 | adventofcode2023 | MIT License |
src/net/sheltem/aoc/y2023/Day05.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2023
import kotlinx.coroutines.coroutineScope
suspend fun main() {
Day05().run()
}
class Day05 : Day<Long>(35, 46) {
override suspend fun part1(input: List<String>): Long = input.toAlmanac().minLocationNumber(input[0].toSeedList())
override suspend fun part2(input: List<String>): Long {
val almanac = input.toAlmanac()
val ranges = input[0].toSeedList().chunked(2).map { it.first()..(it.first() + it.last()) }
return coroutineScope {
generateSequence(0L) { it + 1 }
.first { result ->
almanac.resultToSeed(result)
.let { seed ->
ranges.any { it.contains(seed) }
}
}
}
}
}
private fun String.toSeedList() = split(": ").last().split(" ").mapNotNull { it.toLongOrNull() }
private fun List<String>.toAlmanac(): Almanac {
val almanac = this.drop(2).joinToString("\n").split("\n\n").map { xToYMap ->
xToYMap.split("\n").drop(1).map(AlmanacMapping::from)
}
return Almanac(almanac.map(::AlmanacSection))
}
private fun List<AlmanacSection>.findMapping(mappingNumber: Long) =
fold(mappingNumber) { acc, almanacMapping -> almanacMapping.map(acc) }
private fun List<AlmanacSection>.findReverseMapping(result: Long) =
reversed().fold(result) { acc, almanacMapping -> almanacMapping.reverseMap(acc) }
private data class Almanac(val mappings: List<AlmanacSection>) {
fun minLocationNumber(seeds: List<Long>) =
seeds.minOf { seed ->
mappings.findMapping(seed)
}
fun resultToSeed(result: Long): Long =
mappings.findReverseMapping(result)
}
private data class AlmanacSection(
val mappings: List<AlmanacMapping>
) {
fun map(number: Long): Long = mappings.find { it.canMap(number) }?.map(number) ?: number
fun reverseMap(number: Long): Long = mappings.find { it.canReverseMap(number) }?.reverseMap(number) ?: number
}
private data class AlmanacMapping(val target: Long, val start: Long, val size: Long) {
fun canMap(mappingNumber: Long) = (mappingNumber >= start && mappingNumber < (start + size))
fun canReverseMap(mappingNumber: Long) = (mappingNumber >= target && mappingNumber < (target + size))
fun map(mappingNumber: Long) = mappingNumber + (target - start)
fun reverseMap(mappingNumber: Long) = mappingNumber - (target - start)
companion object {
fun from(input: String) = input.split(" ").mapNotNull { it.toLongOrNull() }.let { (target, start, size) -> AlmanacMapping(target, start, size) }
}
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 2,631 | aoc | Apache License 2.0 |
src/main/kotlin/g2201_2300/s2246_longest_path_with_different_adjacent_characters/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2201_2300.s2246_longest_path_with_different_adjacent_characters
// #Hard #Array #String #Depth_First_Search #Tree #Graph #Topological_Sort
// #2023_06_27_Time_828_ms_(100.00%)_Space_53.3_MB_(100.00%)
import java.util.LinkedList
class Solution {
fun longestPath(parent: IntArray, s: String): Int {
// for first max length
val first = IntArray(s.length)
first.fill(0)
// for second max length
val second = IntArray(s.length)
second.fill(0)
// for number of children for this node
val children = IntArray(s.length)
children.fill(0)
for (i in 1 until s.length) {
// calculate all children for each node
children[parent[i]]++
}
// for traversal from leafs to root
val st = LinkedList<Int>()
// put all leafs
for (i in 1 until s.length) {
if (children[i] == 0) {
st.add(i)
}
}
// traversal from leafs to root
while (st.isNotEmpty()) {
// fetch current node
val i = st.pollLast()
// if we in root - ignore it
if (i == 0) {
continue
}
if (--children[parent[i]] == 0) {
// decrease number of children by parent node and if number of children
st.add(parent[i])
}
// is equal 0 - our parent became a leaf
// if letters isn't equal
if (s[parent[i]] != s[i]) {
// fetch maximal path from node
val maxi = 1 + Math.max(first[i], second[i])
// and update maximal first and second path from parent
if (maxi >= first[parent[i]]) {
second[parent[i]] = first[parent[i]]
first[parent[i]] = maxi
} else if (second[parent[i]] < maxi) {
second[parent[i]] = maxi
}
}
}
// fetch answer
var ans = 0
for (i in 0 until s.length) {
ans = Math.max(ans, first[i] + second[i])
}
return ans + 1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,189 | LeetCode-in-Kotlin | MIT License |
src/Day13Alt.kt | GarrettShorr | 571,769,671 | false | {"Kotlin": 82669} | import com.beust.klaxon.Klaxon
import kotlin.reflect.typeOf
fun main() {
fun isCorrect(leftList: MutableList<Any>?, rightList: MutableList<Any>?): Boolean? {
println("$leftList vs. $rightList")
if(leftList == null && rightList == null) {
return null
}
if(leftList?.isEmpty() == true && !rightList?.isEmpty()!!) {
return true
}
if(rightList?.isEmpty() == true && !leftList?.isEmpty()!!) {
return false
}
var left = leftList?.get(0)
var right = rightList?.get(0)
//both list
if(left is List<*> && right is List<*>) {
if(left.isEmpty() && !right.isEmpty()) {
return true
} else if(!left.isEmpty() && right.isEmpty()) {
return false
} else {
return isCorrect(left as MutableList<Any>?, right as MutableList<Any>?)
}
}
// both string
if(left is Int && right is Int) {
if(left == right) {
leftList?.removeAt(0)
rightList?.removeAt(0)
return isCorrect(leftList, rightList)
} else {
return left < right
}
}
// 1 of each
if(left is String && right is List<*>) {
left = listOf(left)
leftList?.set(0, left)
return isCorrect(leftList, rightList)
}
// 1 empty
return false
}
fun part1(input: List<String>): Int {
val parser = Klaxon()
var instructions = mutableListOf<List<Any>>()
for(line in input) {
if(line != "") {
instructions.add(parser.parseArray<List<Any>>(line)!!)
}
}
instructions = instructions.windowed(2).toMutableList()
// println(instructions.joinToString("\n"))
var count = 0
var indexTotal = 0
for(i in instructions.indices step 2) {
println("original pair: ${instructions[i]} ")
if(isCorrect(instructions[i][0] as MutableList<Any>, instructions[i][1] as MutableList<Any>) == true) {
count++
indexTotal += i
println("pair: ${instructions[i]} is correct. count: $count i: $i")
}
}
return indexTotal
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
println(part1(testInput))
// println(part2(testInput))
val input = readInput("Day13")
// output(part1(input))
// output(part2(input))
}
| 0 | Kotlin | 0 | 0 | 391336623968f210a19797b44d027b05f31484b5 | 2,715 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/practicecode/coursera/rational/Rational.kt | mnhmasum | 556,253,855 | false | null | package practicecode.coursera.rational
import java.math.BigInteger
import java.math.BigInteger.*
class Rational(numerator: BigInteger, denominator: BigInteger) : Comparable<Rational> {
val numer: BigInteger
val denom: BigInteger
init {
val divisor = numerator.gcd(denominator)
val sign = denominator.signum().toBigInteger()
numer = numerator / divisor * sign
denom = denominator / divisor * sign
}
override fun compareTo(other: Rational): Int {
return ((numer * other.denom) - (denom * other.numer)).signum()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Rational
if (numer != other.numer) return false
if (denom != other.denom) return false
return true
}
override fun hashCode(): Int {
var result = numer.hashCode()
result = 31 * result + denom.hashCode()
return result
}
operator fun unaryMinus(): Rational = Rational(-numer, denom)
operator fun plus(other: Rational): Rational = Rational(
(numer * other.denom) + (other.numer * denom),
denom * other.denom
)
operator fun minus(other: Rational): Rational = Rational(
(numer * other.denom) - (other.numer * denom),
denom * other.denom
)
operator fun times(other: Rational): Rational = Rational((numer * other.numer), (denom * other.denom))
operator fun div(other: Rational): Rational {
val r2 = Rational(other.denom, other.numer)
return times(r2)
}
override fun toString(): String {
if (numer < ZERO && numer > denom) return "-$numer/$denom"
if (denom < ZERO && numer > denom) return "-$numer/${denom.abs()}"
if (numer > denom && numer.rem(denom) == ZERO) return numer.toString()
return "$numer/$denom"
}
}
infix fun Int.divBy(r2: Int): Rational = Rational(toBigInteger(), r2.toBigInteger())
infix fun Long.divBy(r2: Long): Rational = Rational(toBigInteger(), r2.toBigInteger())
infix fun BigInteger.divBy(r2: BigInteger): Rational = Rational(this, r2)
fun String.toRational(): Rational {
if (!contains("/")) {
return Rational(toBigInteger(), ONE)
}
val (numerator, denominator) = split("/")
return Rational(numerator.toBigInteger(), denominator.toBigInteger())
}
fun main() {
val half = 1 divBy 2
val third = 1 divBy 3
val sum: Rational = half + third
println(sum)
println(5 divBy 6 == sum)
val difference: Rational = half - third
println(1 divBy 6 == difference)
val product: Rational = half * third
println(1 divBy 6 == product)
val quotient: Rational = half / third
println(3 divBy 2 == quotient)
val negation: Rational = -half
println(-1 divBy 2 == negation)
println((2 divBy 1).toString() == "2")
println((-2 divBy 4).toString() == "-1/2")
println("117/1098".toRational().toString() == "13/122")
val twoThirds = 2 divBy 3
println(half < twoThirds)
println(half in third..twoThirds)
println(2000000000L divBy 4000000000L == 1 divBy 2)
println(
"912016490186296920119201192141970416029".toBigInteger() divBy
"1824032980372593840238402384283940832058".toBigInteger() == 1 divBy 2
)
} | 0 | Kotlin | 0 | 0 | 260b8d1e41c3924bc9ac710bb343107bff748aa0 | 3,367 | ProblemSolvingDaily | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem427/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem427
/**
* LeetCode page: [427. Construct Quad Tree](https://leetcode.com/problems/construct-quad-tree/);
*/
class Solution {
/* Complexity:
* Time O(N^2) and Space O(LogN) where N is the size of grid;
*/
fun construct(grid: Array<IntArray>): Node? {
return if (grid.isEmpty()) null else constructSubGrid(grid)
}
private fun constructSubGrid(
grid: Array<IntArray>,
rowStart: Int = 0,
columnStart: Int = 0,
size: Int = grid.size
): Node {
require(size > 0)
require(size == 1 || size and 1 == 0)
val isSingleElement = size == 1
if (isSingleElement) {
val value = grid[rowStart][columnStart] == 1
return Node(value, true)
}
val halfSize = size shr 1
val secondHalfRowStart = rowStart + halfSize
val secondHalfColumnStart = columnStart + halfSize
val topLeft = constructSubGrid(grid, rowStart, columnStart, halfSize)
val topRight = constructSubGrid(grid, rowStart, secondHalfColumnStart, halfSize)
val bottomLeft = constructSubGrid(grid, secondHalfRowStart, columnStart, halfSize)
val bottomRight = constructSubGrid(grid, secondHalfRowStart, secondHalfColumnStart, halfSize)
return if (shouldMergeAsLeaf(topLeft, topRight, bottomLeft, bottomRight)) {
Node(topLeft.`val`, true)
} else {
Node(topLeft.`val`, false).apply {
this.topLeft = topLeft
this.topRight = topRight
this.bottomLeft = bottomLeft
this.bottomRight = bottomRight
}
}
}
private fun shouldMergeAsLeaf(topLeft: Node, topRight: Node, bottomLeft: Node, bottomRight: Node): Boolean {
val isChildNodesAllLeaf =
topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf
if (!isChildNodesAllLeaf) return false
return topLeft.`val` == topRight.`val` &&
topLeft.`val` == bottomLeft.`val` &&
topLeft.`val` == bottomRight.`val`
}
}
class Node(var `val`: Boolean, var isLeaf: Boolean) {
var topLeft: Node? = null
var topRight: Node? = null
var bottomLeft: Node? = null
var bottomRight: Node? = null
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,327 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/io/github/raphaeltarita/days/Day9.kt | RaphaelTarita | 433,468,222 | false | {"Kotlin": 89687} | package io.github.raphaeltarita.days
import io.github.raphaeltarita.structure.AoCDay
import io.github.raphaeltarita.util.day
import io.github.raphaeltarita.util.inputPath
import io.github.raphaeltarita.util.minOfBy
import kotlinx.datetime.LocalDate
import kotlin.io.path.readLines
object Day9 : AoCDay {
override val day: LocalDate = day(9)
private fun heightMap(): List<List<Int>> {
return inputPath.readLines()
.map { row -> row.map { it.digitToInt() } }
}
private fun height(x: Int, y: Int, heightMap: List<List<Int>>): Int {
if (y < 0 || y > heightMap.lastIndex || x < 0 || x > heightMap.first().lastIndex) return 9
return heightMap[y][x]
}
private fun isLowPoint(x: Int, y: Int, heightMap: List<List<Int>>): Boolean {
val current = heightMap[y][x]
if (height(x, y - 1, heightMap) <= current) return false // top
if (height(x + 1, y, heightMap) <= current) return false // right
if (height(x, y + 1, heightMap) <= current) return false // bottom
if (height(x - 1, y, heightMap) <= current) return false // left
return true
}
override fun executePart1(): Int {
val heightMap = heightMap()
var risk = 0
for (y in heightMap.indices) {
for (x in heightMap.first().indices) {
if (isLowPoint(x, y, heightMap)) {
risk += 1 + heightMap[y][x]
}
}
}
return risk
}
private fun <K, V> MutableMap<K, V>.addAllFrom(keys: Iterable<K>, value: V) {
for (k in keys) {
this[k] = value
}
}
private fun findBasin(x: Int, y: Int, heightMap: List<List<Int>>, basinMap: MutableMap<Pair<Int, Int>, Pair<Int, Int>>): Pair<Int, Int> {
var xCurr = x
var yCurr = y
val foundBasinFor = mutableListOf<Pair<Int, Int>>()
while (true) {
val cached = basinMap[xCurr to yCurr]
if (cached != null) {
basinMap.addAllFrom(foundBasinFor, cached)
return cached
}
val (xNew, yNew) = minOfBy(
xCurr to yCurr,
xCurr to yCurr - 1,
xCurr + 1 to yCurr,
xCurr to yCurr + 1,
xCurr - 1 to yCurr
) { (x, y) -> height(x, y, heightMap) }
if (xNew == xCurr && yNew == yCurr) {
basinMap.addAllFrom(foundBasinFor, xCurr to yCurr)
return xCurr to yCurr
} else {
xCurr = xNew
yCurr = yNew
foundBasinFor += xCurr to yCurr
}
}
}
override fun executePart2(): Int {
val heightMap = heightMap()
val basinMap = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
for (y in heightMap.indices) {
for (x in heightMap.first().indices) {
if (x to y !in basinMap && heightMap[y][x] < 9) {
basinMap[x to y] = findBasin(x, y, heightMap, basinMap)
}
}
}
return basinMap.values
.groupingBy { it }
.eachCount()
.values
.sortedDescending()
.take(3)
.fold(1) { acc, i -> acc * i }
}
} | 0 | Kotlin | 0 | 3 | 94ebe1428d8882d61b0463d1f2690348a047e9a1 | 3,321 | AoC-2021 | Apache License 2.0 |
src/Day09B.kt | zsmb13 | 572,719,881 | false | {"Kotlin": 32865} | @file:Suppress("DuplicatedCode")
import kotlin.math.abs
import kotlin.math.sign
fun main() {
data class Position(val x: Int, val y: Int)
fun adjacent(p: Position, q: Position) =
abs(p.x - q.x) <= 1 && abs(p.y - q.y) <= 1
fun parse(input: List<String>) = input.map { line ->
line[0] to line.substring(2).toInt()
}
fun Char.toDeltaValues() = when (this) {
'R' -> 1 to 0
'L' -> -1 to 0
'U' -> 0 to 1
'D' -> 0 to -1
else -> error("Invalid dir $this")
}
fun Position.follow(other: Position): Position {
if (adjacent(this, other)) return this
val dx = (other.x - x).sign
val dy = (other.y - y).sign
return Position(x + dx, y + dy)
}
fun part1(testInput: List<String>): Int {
var head = Position(0, 0)
var tail = Position(0, 0)
val tailPositions = mutableSetOf(tail)
parse(testInput).forEach { (dir, dist) ->
repeat(dist) {
val (dx, dy) = dir.toDeltaValues()
head = Position(x = head.x + dx, y = head.y + dy)
tail = tail.follow(head)
tailPositions += tail
}
}
return tailPositions.size
}
fun part2(testInput: List<String>): Int {
val snake = Array(10) { Position(0, 0) }
val tailPositions = mutableSetOf(snake.last())
parse(testInput).forEach { (dir, dist) ->
repeat(dist) {
val (dx, dy) = dir.toDeltaValues()
snake[0] = Position(x = snake[0].x + dx, y = snake[0].y + dy)
for (i in 1..9) {
snake[i] = snake[i].follow(snake[i - 1])
}
tailPositions += snake.last()
}
}
return tailPositions.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 | 6 | 32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35 | 2,122 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/java/com/example/calculator/domain/useCase/fractionNumber/FractionNumber.kt | vfadin | 611,611,259 | false | null | package com.example.calculator.domain.useCase.fractionNumber
import com.example.calculator.domain.useCase.INumber
import kotlin.math.pow
import kotlin.math.sqrt
class FractionNumber(numerator: Long, denominator: Long = 1L) : INumber {
var numerator = 0L
private set
var denominator = 1L
private set
init {
this.numerator = numerator
this.denominator = denominator
}
override fun plus(a: INumber): INumber {
if ((a as FractionNumber).denominator == 0L) return this
if (denominator == 0L) return a
val cDenominator: Long = lcm(a.denominator, denominator)
val cNumerator: Long =
a.numerator * (cDenominator / a.denominator) + numerator * (cDenominator / denominator)
return simplify(FractionNumber(cNumerator, cDenominator))
}
override fun minus(a: INumber): INumber {
if (denominator == 0L) {
(a as FractionNumber).numerator *= -1
return a
}
if ((a as FractionNumber).denominator == 0L) return this
// if (denominator == 0L) return a
val cDenominator: Long = lcm(a.denominator, denominator)
val cNumerator: Long = numerator * (cDenominator / denominator) -
a.numerator * (cDenominator / a.denominator)
return simplify(FractionNumber(cNumerator, cDenominator))
}
override fun div(a: INumber): INumber {
return simplify(
FractionNumber(
numerator * (a as FractionNumber).denominator,
denominator * a.numerator
)
)
}
override fun times(a: INumber): INumber {
return simplify(
FractionNumber(
numerator * (a as FractionNumber).numerator,
denominator * a.denominator
)
)
}
private fun simplify(c: FractionNumber): FractionNumber {
if (c.numerator == 0L) {
c.denominator = 0
return c
}
val d: Long = gcd(c.denominator, c.numerator)
c.numerator /= d
c.denominator /= d
return c
}
override fun toString(): String {
if (denominator < 0 && numerator > 0) {
return "-$numerator/${denominator * -1}"
}
if (denominator == 0L || numerator == 0L) {
return "0"
}
if (denominator == 1L) {
return "$numerator"
}
return "$numerator/$denominator"
}
private fun gcd(a: Long, b: Long): Long {
return if (b == 0L) a else gcd(b, a % b)
}
private fun abs(a: Long): Long {
return if (a < 0) a * -1 else a
}
private fun lcm(a: Long, b: Long): Long {
return a * b / gcd(a, b)
}
override fun squared(): INumber {
var numerator = numerator.toDouble().pow(0.5).toLong()
var denominator = denominator.toDouble().pow(0.5).toLong()
if (numerator * numerator != this.numerator) {
numerator = this.numerator
}
if (denominator * denominator != this.denominator) {
denominator = this.denominator
}
return simplify(FractionNumber(numerator, denominator))
}
} | 0 | Kotlin | 0 | 0 | 2b7b275fdf7bfdf6fcd74375332be855aac22034 | 3,217 | Calculator | MIT License |
src/2022/Day19alt.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2022`
import common.BackTracker
import java.io.File
import java.util.*
import kotlin.math.min
fun main() {
Day19alt().solve()
}
class Day19alt {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
val input1 = """
Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian.
""".trimIndent()
enum class ResourceType {
ORE, CLAY, OBS, GEO, NO
}
object ResourceIterator {
val resourceRange = ResourceType.ORE.ordinal .. ResourceType.GEO.ordinal
}
// fun solve(bp: o: Int)
data class Blueprint(
val id: Int,
val ore2ore: Int,
val ore2clay: Int,
val ore2obs: Int,
val clay2obs: Int,
val ore2geo: Int,
val obs2geo: Int,
)
data class Max(var max: Int)
fun Blueprint.solve(minutesLeft: Int): Int {
val max = Max(0)
// solve(minutesLeft, 1, 0, 0, 0, 0, 0, 0, 0, max)
solve1(minutesLeft, 1, 0, 0, 0, 0, 0, 0, max)
return max.max
}
fun Blueprint.solve1(
minLeft: Int,
orr: Int,
clr: Int,
obr: Int,
or: Int,
cl: Int,
ob: Int,
ge: Int,
max: Max
) {
if (max.max < ge) {
max.max = ge
}
if (minLeft == 0) {
return
}
val maxGe = ge + (minLeft - 1) * minLeft / 2
if (maxGe <= max.max) {
return
}
if (minLeft == 26) {
println("$id $max $ge")
}
val nor0 = or+orr
val ncl0 = cl+clr
val nob0 = ob+obr
if (ore2geo <= or && obs2geo <= ob) {
solve1(minLeft-1, orr, clr, obr, nor0-ore2geo, ncl0, nob0-obs2geo, ge+minLeft-1, max)
}
if (ore2obs <= or && clay2obs <= cl) {
solve1(minLeft-1, orr, clr, obr+1, nor0-ore2obs, ncl0-clay2obs, nob0, ge, max)
}
if (ore2clay <= or) {
solve1(minLeft-1, orr, clr+1, obr, nor0-ore2clay, ncl0, nob0, ge, max)
}
if (ore2ore <= or) {
solve1(minLeft-1, orr+1, clr, obr, nor0-ore2ore, ncl0, nob0, ge, max)
}
solve1(minLeft-1, orr, clr, obr, nor0, ncl0, nob0, ge, max)
}
fun Blueprint.solve(
minLeft: Int,
orr: Int,
clr: Int,
obr: Int,
ger: Int,
or: Int,
cl: Int,
ob: Int,
ge: Int,
max: Max
) {
if (minLeft == 0) {
if (max.max < ge) {
max.max = ge
}
return
}
val maxGe = ge + (2 * ger + minLeft - 1) * minLeft / 2
if (maxGe <= max.max) {
return
}
if (minLeft == 20) {
println("$id $max $ge")
}
val nor0 = or+orr
val ncl0 = cl+clr
val nob0 = ob+obr
val nge0 = ge+ger
if (ore2ore <= or) {
solve(minLeft-1, orr+1, clr, obr, ger, nor0-ore2ore, ncl0, nob0, nge0, max)
}
if (ore2clay <= or) {
solve(minLeft-1, orr, clr+1, obr, ger, nor0-ore2clay, ncl0, nob0, nge0, max)
}
if (ore2obs <= or && clay2obs <= cl) {
solve(minLeft-1, orr, clr, obr+1, ger, nor0-ore2obs, ncl0-clay2obs, nob0, nge0, max)
}
if (ore2geo <= or && obs2geo <= ob) {
solve(minLeft-1, orr, clr, obr, ger+1, nor0-ore2geo, ncl0, nob0-obs2geo, nge0, max)
}
solve(minLeft-1, orr, clr, obr, ger, nor0, ncl0, nob0, nge0, max)
}
fun solve() {
val f = File("src/2022/inputs/day19.in")
val s = Scanner(f)
// val s = Scanner(input1)
var sumQ = 0L
var prodQ = 1L
while (s.hasNextLine()) {
val line = s.nextLine().trim()
val words = line.split(" ")
if (!words.isEmpty()) {
val id = words[1].split(":")[0].toInt()
val b =
Blueprint(
id,
words[6].toInt(),
words[12].toInt(),
words[18].toInt(),
words[21].toInt(),
words[27].toInt(),
words[30].toInt())
// val q = b.solve(24)
// sumQ += b.id.toLong() * q.toLong()
// println("*** ${b.id.toLong() * q.toLong()} ${b.id} $q $sumQ")
if (id < 4) {
val q1 = b.solve(32)
prodQ *= q1
println("!!! ${b.id} $q1 $prodQ")
if (id == 3) break
}
}
}
println("${sumQ} ${prodQ}")
}
}
| 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 5,053 | advent-of-code | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec10.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2020
import org.elwaxoro.advent.PuzzleDayTester
class Dec10 : PuzzleDayTester(10, 2020) {
override fun part1() = parse().fold(AdapterWad(), AdapterWad::addAnyAdapter).let {
it.threeJolt * it.oneJolt
}
override fun part2() = parse().fold(mutableListOf(AdapterWad(oneJolt = 1L))) { wads, adapter ->
wads.also {
wads.last().addSequentialAdapter(adapter) ?: wads.add(AdapterWad(oneJolt = 1L, lastAdapter = adapter))
}
}.map(AdapterWad::possibleCombinations).reduce { acc, wad ->
acc * wad
}
private fun parse() = load().map { it.toLong() }.sorted()
private data class AdapterWad(
var oneJolt: Long = 0,
var threeJolt: Long = 1L, // always include the final 3 joltage hop
var lastAdapter: Long = 0,
) {
// puzzle 1: one giant adapter wad
fun addAnyAdapter(adapter: Long): AdapterWad = this.also {
when (adapter - lastAdapter) {
1L -> oneJolt++
3L -> threeJolt++
}
lastAdapter = adapter
}
// puzzle 2: only add +1 adapters (new wad after every +3 adapter)
fun addSequentialAdapter(adapter: Long): AdapterWad? = this.takeIf { adapter - lastAdapter == 1L }?.also {
oneJolt++
lastAdapter = adapter
}
// puzzle 2
// turns out you can be pretty lazy with the data: no sequences have gaps, max sequence length is 5
fun possibleCombinations(): Long =
when (oneJolt) {
in 0L..2L -> 1L // no adapter branching
3L -> 2L // 2 branches
4L -> 4L // 4 branches
5L -> 7L // 7 branches
else -> 0L // EVERYTHING IS A LIE WHY DID I DO IT LIKE THIS AAAHHHHHHHH
}
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 1,851 | advent-of-code | MIT License |
src/leecode/215.kt | DavidZhong003 | 157,566,685 | false | null | package leecode
import algorithm.print
/**
*
* @author doive
* on 2019/6/20 17:17
*/
fun main() {
fun findKthLargest(nums: IntArray, k: Int): Int {
fun sortKth(nums: IntArray, left: Int, right: Int, position: Int) {
if (left > right) {
return
}
val temp = nums[left]
var l = left
var r = right
while (l < r) {
while (l < r && nums[r] <= temp) {
r--
}
while (l < r && nums[l] >= temp) {
l++
}
if (l < r) {
val t = nums[l]
nums[l] = nums[r]
nums[r] = t
}
}
nums[left] = nums[l]
nums[l] = temp
when {
l > position -> {
sortKth(nums, left, l - 1, position)
}
l < position -> {
sortKth(nums, l + 1, right, position)
}
else -> return
}
}
sortKth(nums, 0, nums.lastIndex, k-1)
nums.print()
return nums[k-1]
}
/**
* 桶排序
*/
fun bucketSort(nums: IntArray): IntArray {
if (nums.size <= 1) {
return nums
}
var min = nums[0]
var max = nums[0]
nums.forEach {
min = Math.min(min, it)
max = Math.max(max, it)
}
//桶
val buckets = IntArray(max - min + 1)
nums.forEach {
buckets[it - min]++
}
buckets.print()
var i = 0
buckets.forEachIndexed { index, value ->
if (value != 0) {
var j = value
while (j > 0) {
nums[i++] = index + min
j--
}
}
}
return nums
}
/**
* 快排序
*/
fun quickSort(nums: IntArray): IntArray {
fun quickSort(nums: IntArray, low: Int, high: Int) {
if (low > high) {
return
}
var l = low
var r = high
// 基准值
val temp = nums[l]
while (l < r) {
while (l < r && nums[r] >= temp) {
r--
}
while (l < r && nums[l] <= temp) {
l++
}
//交换数据
if (l < r) {
val t = nums[l]
nums[l] = nums[r]
nums[r] = t
}
}
//交换基准值
nums[low] = nums[l]
nums[l] = temp
quickSort(nums, low, l - 1)
quickSort(nums, l + 1, high)
}
quickSort(nums, 0, nums.lastIndex)
return nums
}
// bucketSort(intArrayOf(4, 2, 5, 1, 7, 3, 2, 7, 10)).print()
findKthLargest(intArrayOf(5, 2, 4, 1, 3, 6, 0), 4).println()
findKthLargest(intArrayOf(3,2,1,5,6,4),2).println()
findKthLargest(intArrayOf(3,2,3,1,2,4,5,5,6),4).println()
} | 0 | Kotlin | 0 | 1 | 7eabe9d651013bf06fa813734d6556d5c05791dc | 3,193 | LeetCode-kt | Apache License 2.0 |
kotlin/problems/src/solution/StringProblems.kt | lunabox | 86,097,633 | false | {"Kotlin": 146671, "Python": 38767, "JavaScript": 19188, "Java": 13966} | package solution
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.HashSet
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class StringProblems {
/**
* https://leetcode-cn.com/problems/is-subsequence/
* 给定字符串 s 和 t ,判断 s 是否为 t 的子序列
*/
fun isSubsequence(s: String, t: String): Boolean {
if (s.isBlank()) {
return true
}
var index = 0
t.forEach {
if (it == s[index]) {
index++
}
if (index == s.length) {
return true
}
}
return false
}
/**
* https://leetcode-cn.com/problems/number-of-matching-subsequences/
* 给定字符串 S 和单词字典 words, 求 words[i] 中是 S 的子序列的单词个数
*/
fun numMatchingSubseq(S: String, words: Array<String>): Int {
var result = 0
val charIndex = HashMap<Char, List<Int>>()
repeat(S.length) {
val char = S[it]
val list = if (charIndex[char] == null) ArrayList() else charIndex[char] as ArrayList<Int>
list.add(it)
charIndex[char] = list
}
words.forEach {
kotlin.run word_search@{
var currentIndex = -1
it.forEach char_search@{
val list = charIndex[it] ?: return@word_search
// exist char
list.forEach { index ->
if (index > currentIndex) {
currentIndex = index
return@char_search
}
}
if (list.last() <= currentIndex) {
return@word_search
}
}
result++
}
}
return result
}
/**
* https://leetcode-cn.com/problems/validate-ip-address/
*/
fun validIPAddress(IP: String): String {
if (IP.contains(".")) {
val ips = IP.split(".")
run ip4@{
if (ips.size == 4) {
repeat(4) {
try {
val p = ips[it]
if (p.isBlank() || (p.toInt() > 0 && p.startsWith("0")) ||
(p.toInt() == 0 && p.length > 1) || (p.toInt() !in 0..255)
) {
return@ip4
}
} catch (e: Exception) {
return@ip4
}
}
return "IPv4"
}
}
} else if (IP.contains(":")) {
val ips = IP.split(":")
run ipv6@{
if (ips.size == 8) {
repeat(8) {
try {
if (ips[it].isBlank() || ips[it].length > 4 || ips[it][0] == '-' || ips[it].toInt(16) !in 0..0xffff) {
return@ipv6
}
} catch (e: Exception) {
return@ipv6
}
}
return "IPv6"
}
}
}
return "Neither"
}
/**
* https://leetcode-cn.com/problems/reverse-words-in-a-string/
*/
fun reverseWords(s: String): String {
val words = s.split(" ").filter { it.isNotBlank() }
val result = StringBuffer()
words.asReversed().forEach { result.append(it).append(" ") }
return if (result.isBlank()) "" else result.deleteCharAt(result.lastIndex).toString()
}
/**
* https://leetcode-cn.com/problems/positions-of-large-groups/
*/
fun largeGroupPositions(S: String): List<List<Int>> {
val result = ArrayList<List<Int>>()
var begin = S[0]
var beginIndex = 0
for (i in 1 until S.length) {
if (S[i] != begin) {
if (i - beginIndex >= 3) {
result.add(intArrayOf(beginIndex, i - 1).toList())
}
begin = S[i]
beginIndex = i
}
}
if (S.length - beginIndex >= 3) {
result.add(intArrayOf(beginIndex, S.length - 1).toList())
}
return result
}
/**
* https://leetcode-cn.com/problems/valid-palindrome-ii/comments/
*/
fun validPalindrome(s: String): Boolean {
var i = 0
var j = s.length - 1
while (i < j) {
if (s[i] != s[j]) {
return isSubStringValid(s, i + 1, j) || isSubStringValid(s, i, j - 1)
}
i++
j--
}
return true
}
private fun isSubStringValid(s: String, i: Int, j: Int): Boolean {
var start = i
var end = j
while (start < end) {
if (s[start] != s[end]) {
return false
}
start++
end--
}
return true
}
fun toLowerCase(str: String): String {
val ch = CharArray(str.length)
str.forEachIndexed { index, c ->
if (c in 'A'..'Z') {
ch[index] = (c.toInt() - 'A'.toInt() + 'a'.toInt()).toChar()
} else {
ch[index] = c
}
}
return String(ch)
}
/**
* https://leetcode-cn.com/problems/is-unique-lcci/
*/
fun isUnique(astr: String): Boolean {
var cur: Char? = null
astr.toCharArray().sorted().forEach {
if (it == cur) {
return false
}
cur = it
}
return true
}
/**
* https://leetcode-cn.com/problems/count-binary-substrings/
*/
fun countBinarySubstrings(s: String): Int {
var countItem = 1
var cur = s[0]
val step = mutableListOf<Int>()
s.drop(1).forEach {
if (it == cur) {
countItem++
} else {
if (countItem > 0) {
step.add(countItem)
}
countItem = 1
cur = it
}
}
if (countItem > 0) {
step.add(countItem)
}
var result = 0
for (i in 0 until step.lastIndex) {
result += if (step[i] <= step[i + 1]) step[i] else step[i + 1]
}
return result
}
/**
* https://leetcode-cn.com/problems/letter-case-permutation/
*/
fun letterCasePermutation(S: String): List<String> {
val letterCount = S.count { it.isLetter() }
val result = ArrayList<String>((1 shl letterCount) + 1)
letterDfs(S.toCharArray(), 0, result)
return result
}
private fun letterDfs(s: CharArray, index: Int, result: MutableList<String>) {
if (index > s.lastIndex) {
result.add(String(s))
return
}
val curLetter = s[index]
if (curLetter.isLetter()) {
letterDfs(s, index + 1, result)
s[index] = if (curLetter.isLowerCase()) curLetter.toUpperCase() else curLetter.toLowerCase()
}
letterDfs(s, index + 1, result)
}
/**
* https://leetcode-cn.com/problems/generate-parentheses/
*/
fun generateParenthesis(n: Int): List<String> {
val ans = mutableListOf<String>()
backTrace(ans, "", 0, 0, n)
return ans
}
/**
* 回溯法
* @param ans 结果
* @param cur 当前结构
* @param left 左括号
* @param right 右括号
* @param n 最大括号对数
*/
private fun backTrace(ans: MutableList<String>, cur: String, left: Int, right: Int, n: Int) {
if (cur.length == 2 * n) {
ans.add(cur)
return
}
if (left < n) {
backTrace(ans, "$cur(", left + 1, right, n)
}
if (right < left) {
backTrace(ans, "$cur)", left, right + 1, n)
}
}
/**
* https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
*/
fun letterCombinations(digits: String): List<String> {
val ans = mutableListOf<String>()
val map = mapOf(
'2' to "abc",
'3' to "def",
'4' to "ghi",
'5' to "jkl",
'6' to "mno",
'7' to "pqrs",
'8' to "tuv",
'9' to "wxyz"
)
dfsLetter(ans, map, "", digits, 0)
return ans
}
private fun dfsLetter(ans: MutableList<String>, map: Map<Char, String>, cur: String, digits: String, index: Int) {
if (index == digits.length) {
if (cur.isNotBlank()) {
ans.add(cur)
}
return
}
map[digits[index]]?.forEach {
dfsLetter(ans, map, "$cur$it", digits, index + 1)
}
}
/**
* https://leetcode-cn.com/problems/longest-palindrome/
*/
fun longestPalindrome(s: String): Int {
val charCount = IntArray(128)
var ans = 0
s.forEach { charCount[it.toInt()]++ }
charCount.forEach {
ans += it / 2 * 2
if (it % 2 == 1 && ans % 2 == 0) {
ans++
}
}
return ans
}
/**
* https://leetcode-cn.com/problems/rotate-string/
*/
fun rotateString(A: String, B: String): Boolean {
if (A == B) {
return true
}
for (index in 0..A.lastIndex) {
val rotate = A.slice(IntRange(index + 1, A.lastIndex)) + A.slice(IntRange(0, index))
if (B == rotate) {
return true
}
}
return false
}
/**
* https://leetcode-cn.com/problems/group-anagrams/
*/
fun groupAnagrams(strs: Array<String>): List<List<String>> {
val result = mutableListOf<List<String>>()
val map = HashMap<String, MutableList<String>>()
strs.forEach {
val sorted = String(it.toCharArray().sortedArray())
if (sorted !in map) {
map[sorted] = mutableListOf()
}
map[sorted]?.add(it)
}
result.addAll(map.values)
return result
}
/**
* https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target/
*/
fun nextGreatestLetter(letters: CharArray, target: Char): Char {
letters.forEach {
if (it.toInt() > target.toInt()) {
return it
}
}
return letters[0]
}
/**
* https://leetcode-cn.com/problems/reverse-only-letters/
*/
fun reverseOnlyLetters(S: String): String {
val chars = S.toCharArray()
val indexes = mutableListOf<Int>()
chars.forEachIndexed { index, c ->
if (c.isLetter()) {
indexes.add(index)
}
}
repeat(indexes.size / 2) {
val temp = chars[indexes[it]]
chars[indexes[it]] = chars[indexes[indexes.size - it - 1]]
chars[indexes[indexes.size - it - 1]] = temp
}
return String(chars)
}
/**
* https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/
*/
fun countCharacters(words: Array<String>, chars: String): Int {
val letter = IntArray(26) { 0 }
var sum = 0
chars.forEach {
letter[it - 'a']++
}
words.forEach words@{ word ->
val map = HashMap<Char, Int>()
word.forEach {
map[it] = map[it]?.plus(1) ?: 1
}
map.keys.forEach {
if (map[it]!! > letter[it - 'a']) {
return@words
}
}
sum += word.length
}
return sum
}
/**
* 周赛
*/
fun canConstruct(s: String, k: Int): Boolean {
val letters = IntArray(26) { 0 }
s.forEach {
letters[it - 'a']++
}
var jishu = 0
var oushu = 0
letters.filter { it > 0 }.forEach {
oushu += it / 2
if (it % 2 == 1) {
jishu++
}
}
if (jishu > k) {
return false
}
if (jishu + oushu > k || (jishu + oushu <= k && k <= jishu + 2 * oushu)) {
return true
}
return false
}
/**
* https://leetcode-cn.com/problems/longest-happy-string/
*/
fun longestDiverseString(a: Int, b: Int, c: Int): String {
val result = StringBuffer(a + b + c)
val chars = arrayOf('a', 'b', 'c')
val n = arrayOf(a, b, c)
var lastIndex = -1
while (true) {
val temp = mutableListOf<Pair<Int, Int>>()
for (index in n.indices) {
if (index != lastIndex) {
temp.add(Pair(n[index], index))
}
}
temp.sortBy { it.first }
val last = temp.last()
if (last.first == 0) {
break
}
var take = min(last.first, 2)
if (lastIndex != -1 && n[lastIndex] > last.first) {
take = 1
}
repeat(take) {
result.append(chars[last.second])
}
n[last.second] -= take
lastIndex = last.second
}
return result.toString()
}
/**
* https://leetcode-cn.com/problems/zigzag-conversion/
*/
fun convert(s: String, numRows: Int): String {
if (numRows == 0) {
return s
}
val chars = Array<MutableList<Char>>(numRows) { mutableListOf() }
var mode = 0
var index = 0
s.forEach { c ->
chars[index].add(c)
if (mode == 0) {
index++
if (index == numRows) {
mode = 1
index = max(index - 2, 0)
}
} else {
index--
if (index == -1) {
mode = 0
index = min(index + 2, numRows - 1)
}
}
}
val result = StringBuffer(s.length)
chars.forEach {
it.forEach { c ->
result.append(c)
}
}
return result.toString()
}
/**
* https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
*/
fun lengthOfLongestSubstring(s: String): Int {
val letters = HashSet<Char>()
var ans = 0
var i = 0
var j = 0
while (i < s.length && j < s.length) {
if (s[j] !in letters) {
letters.add(s[j++])
ans = kotlin.math.max(ans, j - i)
} else {
letters.remove(s[i++])
}
}
return ans
}
/**
* https://leetcode-cn.com/problems/restore-ip-addresses/
*/
fun restoreIpAddresses(s: String): List<String> {
val result = mutableListOf<String>()
dfsIp(s, "", 0, 1, result)
return result
}
private fun dfsIp(s: String, current: String, index: Int, level: Int, result: MutableList<String>) {
if (index > s.lastIndex) {
return
}
if (level == 4) {
val last = s.slice(IntRange(index, s.lastIndex))
try {
if ((last.length == 1 || last[0] != '0') && last.toInt() in 0..255) {
result.add("$current$last")
return
}
} catch (e: NumberFormatException) {
return
}
}
for (i in index..min(index + 2, s.lastIndex)) {
val item = s.slice(IntRange(index, i))
try {
if ((item.length == 1 || item[0] != '0') && item.toInt() in 0..255) {
dfsIp(s, "$current$item.", i + 1, level + 1, result)
}
} catch (e: NumberFormatException) {
}
}
}
fun stringMatching(words: Array<String>): List<String> {
val ans = HashSet<String>()
for (i in words.indices) {
for (j in i + 1 until words.size) {
if (words[i].length >= words[j].length && words[i].indexOf(words[j]) >= 0) {
ans.add(words[j])
} else if (words[i].length < words[j].length && words[j].indexOf(words[i]) >= 0) {
ans.add(words[i])
}
}
}
return ans.toList()
}
fun entityParser(text: String): String {
var ans = text.replace(""", "\"")
ans = ans.replace("'", "'")
ans = ans.replace("&", "&")
ans = ans.replace(">", ">")
ans = ans.replace("<", "<")
ans = ans.replace("⁄", "/")
return ans
}
/**
* https://leetcode-cn.com/contest/biweekly-contest-24/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/
*/
fun getHappyString(n: Int, k: Int): String {
val happy = mutableListOf<String>()
happyDFS("", n, happy)
if (happy.size < k) {
return ""
}
happy.sort()
return happy[k - 1]
}
private val chars = arrayOf('a', 'b', 'c')
private fun happyDFS(current: String, n: Int, happy: MutableList<String>) {
if (current.length == n) {
happy.add(current)
return
}
if (current.isEmpty()) {
happyDFS("a", n, happy)
happyDFS("b", n, happy)
happyDFS("c", n, happy)
} else {
val usefulChar = mutableListOf<Char>()
chars.forEach {
if (it != current.last()) {
usefulChar.add(it)
}
}
usefulChar.forEach {
happyDFS("$current$it", n, happy)
}
}
}
/**
* https://leetcode-cn.com/contest/weekly-contest-185/problems/reformat-the-string/
*/
fun reformat(s: String): String {
val letters = mutableListOf<Char>()
val nums = mutableListOf<Char>()
s.forEach {
if (it.isLetter()) {
letters.add(it)
} else {
nums.add(it)
}
}
if (abs(letters.size - nums.size) > 1) {
return ""
}
val ans = StringBuffer()
var letterIndex = 0
var numsIndex = 0
if (letters.size > nums.size) {
ans.append(letters[letterIndex++])
} else if (letters.size < nums.size) {
ans.append(nums[numsIndex++])
}
while (letterIndex < letters.size && numsIndex < nums.size) {
if (letterIndex >= numsIndex) {
ans.append(nums[numsIndex++])
ans.append(letters[letterIndex++])
} else {
ans.append(letters[letterIndex++])
ans.append(nums[numsIndex++])
}
}
return ans.toString()
}
/**
* https://leetcode-cn.com/problems/partition-labels/
*/
fun partitionLabels(S: String): List<Int> {
val lastPos = HashMap<Char, Int>()
S.forEachIndexed { index, c ->
lastPos[c] = index
}
var endPos = 0
var startPos = 0
val ans = mutableListOf<Int>()
S.forEachIndexed { index, c ->
endPos = max(endPos, lastPos[c]!!)
if (endPos == index) {
ans.add(endPos - startPos + 1)
startPos = index + 1
}
}
return ans
}
/**
* https://leetcode-cn.com/problems/buddy-strings/
*/
fun buddyStrings(A: String, B: String): Boolean {
if (A.length != B.length) {
return false
}
if (A == B) {
val chars = IntArray(26)
A.forEach {
chars[it - 'a']++
}
chars.forEach {
if (it >= 2) {
return true
}
}
return false
} else {
var first = -1
var second = -1
for (i in A.indices) {
if (A[i] != B[i]) {
when {
first == -1 -> first = i
second == -1 -> second = i
else -> return false
}
}
}
return first != -1 && second != -1 && A[first] == B[second] && A[second] == B[first]
}
}
/**
* https://leetcode-cn.com/contest/weekly-contest-186/problems/maximum-score-after-splitting-a-string/
*/
fun maxScore(s: String): Int {
val left = IntArray(s.length)
val right = IntArray(s.length)
var ans = 0
for (i in s.indices) {
if (i == 0) {
left[0] = if (s[i] == '0') 1 else 0
} else {
left[i] = left[i - 1] + if (s[i] == '0') 1 else 0
}
}
for (i in s.lastIndex downTo 0) {
if (i == s.lastIndex) {
right[i] = if (s[i] == '1') 1 else 0
} else {
right[i] = right[i + 1] + if (s[i] == '1') 1 else 0
}
}
for (i in 0 until s.lastIndex) {
ans = max(ans, left[i] + right[i + 1])
}
return ans
}
/**
* https://leetcode-cn.com/problems/unique-email-addresses/
*/
fun numUniqueEmails(emails: Array<String>): Int {
val ans = HashSet<String>()
emails.forEach {
val index = it.indexOf("@")
var name = it.substring(0, index)
name = name.replace(".", "")
val plusIndex = name.indexOf("+")
if (plusIndex > -1) {
name = name.substring(0, plusIndex)
}
ans.add(name + it.substring(index))
}
return ans.size
}
/**
* https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/
*/
fun removeDuplicates(S: String): String {
val list = mutableListOf<Char>()
S.forEach { list.add(it) }
var hasRemove = true
while (hasRemove) {
hasRemove = false
var i = 0
while (i < list.size - 1) {
if (list[i] == list[i + 1]) {
hasRemove = true
list.removeAt(i)
list.removeAt(i)
} else {
i++
}
}
}
return String(list.toCharArray())
}
} | 0 | Kotlin | 0 | 0 | cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9 | 23,007 | leetcode | Apache License 2.0 |
src/main/kotlin/g1201_1300/s1284_minimum_number_of_flips_to_convert_binary_matrix_to_zero_matrix/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1201_1300.s1284_minimum_number_of_flips_to_convert_binary_matrix_to_zero_matrix
// #Hard #Array #Breadth_First_Search #Matrix #Bit_Manipulation
// #2023_06_08_Time_131_ms_(100.00%)_Space_34.3_MB_(100.00%)
import java.util.ArrayDeque
import java.util.Queue
class Solution {
private lateinit var visited: MutableSet<Int>
private fun isValid(x: Int, y: Int, r: Int, c: Int): Boolean {
return x >= 0 && y >= 0 && x < r && y < c
}
private fun next(n: Int, r: Int, c: Int): List<Int> {
val ans: MutableList<Int> = ArrayList()
val dx = intArrayOf(0, 0, 0, 1, -1)
val dy = intArrayOf(0, 1, -1, 0, 0)
for (i in 0 until r) {
for (j in 0 until c) {
var newMask = n
for (k in dx.indices) {
val nx = i + dx[k]
val ny = j + dy[k]
if (isValid(nx, ny, r, c)) {
newMask = newMask xor (1 shl nx * 3 + ny)
}
}
if (visited.add(newMask)) {
ans.add(newMask)
}
}
}
return ans
}
fun minFlips(mat: Array<IntArray>): Int {
var mask = 0
val r = mat.size
val c = mat[0].size
if (r == 1 && c == 1) {
return if (mat[0][0] == 0) 0 else 1
}
for (i in 0 until r) {
for (j in 0 until c) {
mask = mask or (mat[i][j] shl i * 3 + j)
}
}
if (mask == 0) {
return 0
}
visited = HashSet()
val q: Queue<Int> = ArrayDeque()
var count = 1
q.add(mask)
visited.add(mask)
while (q.isNotEmpty()) {
val qSize = q.size
for (i in 0 until qSize) {
val currMask = q.poll()
val nextStates = next(currMask, r, c)
for (nextState in nextStates) {
if (nextState == 0) {
return count
}
q.add(nextState)
}
}
count++
}
return -1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,195 | LeetCode-in-Kotlin | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day14.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInputLines
object Day14 : Day {
override val input = Terrain.of(readInputLines(14))
override fun part1() = input.next { y > input.end }.tiles
override fun part2() = input.next { this == Position.INITIAL }.tiles + 1
data class Terrain(val rocks: Set<Position>, val end: Int, val tiles: Int = 0) {
companion object {
fun of(input: List<String>) = parseRocks(input).let { r -> Terrain(r, r.maxOf { it.y }) }
private fun parseRocks(input: List<String>): Set<Position> {
return input
.flatMap { it.split(" -> ").windowed(2).flatMap { (a, b) -> Position.of(a).rocks(Position.of(b)) } }
.toSet()
}
}
fun next(endReached: Position.() -> Boolean): Terrain {
return Position.INITIAL.landingPosition(rocks, end)
?.takeIf { !it.endReached() }
?.let { copy(rocks = rocks + it, tiles = tiles + 1).next(endReached) }
?: this
}
}
data class Position(val x: Int, val y: Int) {
companion object {
val INITIAL = Position(500, 0)
fun of(input: String): Position {
val (x, y) = input.split(",").map { it.toInt() }
return Position(x, y)
}
}
fun landingPosition(blocked: Set<Position>, end: Int): Position? {
val next = next(blocked)
return when {
next == null -> this
next.y > end -> next
else -> next.landingPosition(blocked, end)
}
}
private fun next(blocked: Set<Position>) = attempts().firstOrNull { it !in blocked }
private fun attempts() = listOf(copy(y = y + 1), copy(x = x - 1, y = y + 1), copy(x = x + 1, y = y + 1))
fun rocks(other: Position): Set<Position> = when {
x > other.x || y > other.y -> other.rocks(this)
x == other.x -> (y..other.y).map { Position(x, it) }.toSet()
y == other.y -> (x..other.x).map { Position(it, y) }.toSet()
else -> error("Invalid input")
}
}
} | 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 2,284 | aoc2022 | MIT License |
src/Day09.kt | mcdimus | 572,064,601 | false | {"Kotlin": 32343} | import util.cartesian.point.DataPoint
import util.cartesian.point.Direction
import util.cartesian.point.Point
import util.readInput
import kotlin.math.*
@OptIn(ExperimentalStdlibApi::class)
fun main() {
fun part1(input: List<String>): Int {
var currentHeadPoint = Point.of(0, 0)
var currentTailPoint = Point.of(0, 0)
val visitedPoints = mutableSetOf(currentTailPoint)
var currentDirection: Direction
for (command in input) {
currentDirection = Direction.of(command[0])
val length = command.substring(2).toInt()
for (i in 0..<length) {
val prev = currentHeadPoint
currentHeadPoint = currentHeadPoint.move(currentDirection)
if (currentTailPoint distanceTo currentHeadPoint >= 2) {
currentTailPoint = prev
visitedPoints.add(currentTailPoint)
}
}
}
return visitedPoints.size
}
fun part2(input: List<String>): Int {
val currentRopePoints = Array(10) { index -> DataPoint.of(0, 0, index)}
var currentHeadPoint = DataPoint.of(0, 0, 0)
val visitedPoints = mutableSetOf(currentRopePoints.last())
var currentDirection: Direction
for (command in input) {
currentDirection = Direction.of(command[0])
val length = command.substring(2).toInt()
for (i in 0..<length) {
currentHeadPoint = currentHeadPoint.move(currentDirection)
currentRopePoints[0] = currentHeadPoint
for (y in currentRopePoints.indices.drop(1)) {
if (currentRopePoints[y] distanceTo currentRopePoints[y-1] >= 2) {
val xDiff = (currentRopePoints[y - 1].x - currentRopePoints[y].x) / 2.0
val xSign = sign(xDiff).toInt()
val newXDelta = xSign*ceil(abs(xDiff)).toInt()
val yDiff = (currentRopePoints[y - 1].y - currentRopePoints[y].y) / 2.0
val ySign = sign(yDiff).toInt()
val newYDelta = ySign*ceil(abs(yDiff)).toInt()
currentRopePoints[y] = currentRopePoints[y].move(newXDelta, newYDelta)
}
}
visitedPoints.add(currentRopePoints.last())
}
}
return visitedPoints.size
}
// test if implementation meets criteria from the description, like:
val testInput1 = readInput("Day09_test")
check(part1(testInput1) == 13)
check(part2(testInput1) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dfa9cfda6626b0ee65014db73a388748b2319ed1 | 2,803 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/g2401_2500/s2467_most_profitable_path_in_a_tree/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2401_2500.s2467_most_profitable_path_in_a_tree
// #Medium #Array #Depth_First_Search #Breadth_First_Search #Tree #Graph
// #2023_07_05_Time_850_ms_(100.00%)_Space_103.8_MB_(100.00%)
class Solution {
fun mostProfitablePath(edges: Array<IntArray>, bob: Int, amount: IntArray): Int {
// Time: O(E); Space: O(N + E)
// build graph
val graph: Array<MutableList<Int>> = Array(amount.size) { ArrayList<Int>() }
for (edge in edges) {
graph[edge[0]].add(edge[1])
graph[edge[1]].add(edge[0])
}
return helperDfs(graph, 0, bob, amount, BooleanArray(amount.size), 1)[0]
}
// Time: O(N); Space: O(N)
private fun helperDfs(
graph: Array<MutableList<Int>>,
node: Int,
bob: Int,
amount: IntArray,
seen: BooleanArray,
height: Int
): IntArray {
var res = Int.MIN_VALUE
seen[node] = true
var bobPathLen = if (node == bob) 1 else 0
for (nextNode in graph[node]) {
if (seen[nextNode]) continue
val tmp = helperDfs(graph, nextNode, bob, amount, seen, height + 1)
if (tmp[1] > 0) bobPathLen = tmp[1] + 1
res = Math.max(res, tmp[0])
}
if (bobPathLen in 1..height) {
if (bobPathLen == height) amount[node] = amount[node] / 2 else amount[node] = 0
}
return intArrayOf(if (res == Int.MIN_VALUE) amount[node] else amount[node] + res, bobPathLen)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,501 | LeetCode-in-Kotlin | MIT License |
2022/Day20.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
fun mix(input: Array<Pair<Long, Int>>) {
val n = input.size
for (idx in 0 until n) {
val oldI = input.indices.find { input[it].second == idx }!!
var newI = (oldI + input[oldI].first) % (n-1)
newI = (newI + n-1) % (n-1)
if (newI == 0L) newI = n-1L
if (oldI < newI) {
val o = input[oldI]
for (i in oldI until newI.toInt()) {
input[i] = input[i+1]
}
input[newI.toInt()] = o
} else {
val o = input[oldI]
for (i in oldI downTo newI.toInt()+1) {
input[i] = input[i-1]
}
input[newI.toInt()] = o
}
//println(input.joinToString(",") { it.first.toString() })
}
}
val file = "Day20"
run {
val input = readInput(file).mapIndexed() { idx, v -> v.toLong() to idx }.toTypedArray()
val n = input.size
mix(input)
val idx0 = input.indices.find { input[it].first == 0L }!!
val res1 = input[(idx0 + 1000) % n].first + input[(idx0 + 2000) % n].first + input[(idx0 + 3000) % n].first
println(res1)
}
run {
val input = readInput(file).mapIndexed() { idx, v -> 811589153L * v.toLong() to idx }.toTypedArray()
val n = input.size
repeat(10) {
println("Round${it+1}")
mix(input)
}
val idx0 = input.indices.find { input[it].first == 0L }!!
val res2 = input[(idx0 + 1000) % n].first + input[(idx0 + 2000) % n].first + input[(idx0 + 3000) % n].first
println(res2)
}
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,696 | advent-of-code-kotlin | Apache License 2.0 |
advent-of-code-2021/src/code/day5/Main.kt | Conor-Moran | 288,265,415 | false | {"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733} | package code.day5
import java.io.File
import java.lang.Integer.max
import kotlin.math.abs
fun main() {
doIt("Day 5 Part 1: Test Input", "src/code/day5/test.input", part1);
doIt("Day 5 Part 1: Real Input", "src/code/day5/part1.input", part1);
doIt("Day 5 Part 2: Test Input", "src/code/day5/test.input", part2);
doIt("Day 5 Part 2: Real Input", "src/code/day5/part1.input", part2);
}
fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Int) {
val lines = arrayListOf<String>()
File(input).forEachLine { lines.add(it) };
println(String.format("%s: Ans: %d", msg , calc(lines)));
}
val part1: (List<String>) -> Int = { lines ->
val input = parse(lines)
val grid = Grid(input.maxX + 1, input.maxY + 1)
grid.draw(input.lines)
grid.show()
grid.count()
}
val part2: (List<String>) -> Int = { lines ->
val input = parse(lines)
val grid = Grid(input.maxX + 1, input.maxY + 1, false)
grid.draw(input.lines)
grid.count()
}
val parse: (List<String>) -> Input = { lines ->
val endpoints = mutableListOf<Line>();
var maxX: Int = Int.MIN_VALUE
var maxY: Int = Int.MIN_VALUE
lines.forEach() { line ->
val points = line.split(Regex(" -> ")).map {
val coords = it.split(",")
Point(Integer.parseInt(coords[0]), Integer.parseInt(coords[1]))
}
endpoints.add(Line(points[0], points[1]))
maxX = max(maxX, max(points[0].x, points[1].x))
maxY = max(maxY, max(points[0].y, points[1].y))
}
Input(endpoints, maxX, maxY)
}
class Input(val lines: List<Line>, val maxX: Int, val maxY: Int) {}
class Point(val x: Int, val y: Int) {
override fun toString(): String {
return "Point($x, $y)"
}
}
class Line(val p1: Point, val p2: Point) {
override fun toString(): String {
return "Line($p1, $p2)"
}
}
class Grid(val xLen: Int, val yLen: Int, var simple: Boolean = true): ArrayList<MutableList<Int>>(xLen) {
init {
fill()
}
private fun fill() {
for (i in 0 until xLen) {
this.add(MutableList(yLen) { 0 })
}
}
fun inc(p: Point) {
inc(p.x, p.y)
}
fun inc(i: Int, j: Int) {
this[i][j]++
}
fun draw(line: Line) {
val dxi = line.p2.x - line.p1.x
val dyi = line.p2.y - line.p1.y
var dx = decDelta(dxi)
var dy = decDelta(dyi)
if (simple && isAngled(dx, dy)) return
inc(line.p2)
inc(line.p1)
while (abs(dx) > 0 || abs(dy) > 0) {
inc(line.p1.x + dx, line.p1.y + dy)
dx = decDelta(dx)
dy = decDelta(dy)
}
}
fun isAngled(dx: Int, dy: Int): Boolean {
return dx != 0 && dy != 0
}
private fun decDelta(delta: Int): Int {
return when {
delta > 0 -> delta - 1
delta < 0 -> delta + 1
else -> 0
}
}
fun draw(lines: List<Line>) {
lines.forEach() { draw(it) }
//draw(lines[0])
}
fun count(): Int {
var cnt = 0;
for (x in 0 until xLen) {
for (y in 0 until yLen) {
if(this[x][y] >= 2) cnt++
}
}
return cnt
}
fun show() {
if (xLen > 50) return
for (x in 0 until xLen) {
for (y in 0 until yLen) {
print(this[x][y])
}
println()
}
}
}
| 0 | Kotlin | 0 | 0 | ec8bcc6257a171afb2ff3a732704b3e7768483be | 3,466 | misc-dev | MIT License |
app/src/main/kotlin/com/resurtm/aoc2023/day16/Solution.kt | resurtm | 726,078,755 | false | {"Kotlin": 119665} | package com.resurtm.aoc2023.day16
fun launchDay16(testCase: String) {
val grid = readInputGrid(testCase)
val part1 = runBeam(grid, Pos(), Dir.RIGHT).size
println("Day 16, part 1: $part1")
val part2 = runBeams(grid)
println("Day 16, part 2: $part2")
}
private fun runBeams(gr: Grid): Int {
var max = 0
for (col in gr[0].indices) {
val v1 = runBeam(gr, Pos(0, col), Dir.DOWN).size
if (max < v1) max = v1
val v2 = runBeam(gr, Pos(gr.size - 1, col), Dir.UP).size
if (max < v2) max = v2
}
for (row in gr.indices) {
val v1 = runBeam(gr, Pos(row, 0), Dir.RIGHT).size
if (max < v1) max = v1
val v2 = runBeam(gr, Pos(row, gr[0].size - 1), Dir.LEFT).size
if (max < v2) max = v2
}
return max
}
private fun runBeam(gr: Grid, startPos: Pos, startDir: Dir): Set<Pos> {
val bms = mutableListOf(Beam(startPos, startDir))
val vis = mutableSetOf(bms.first())
val vh = mutableListOf<Int>()
val vhs = 10
var genNum = 0
while (!(vh.size >= vhs && vh.subList(vh.size - vhs, vh.size).all { it == vh.last() })) {
/*printGrid(genNum, gr, bms)
printVis(genNum, gr, vis)*/
var bmNum = 0
while (bmNum < bms.size) {
val bm = bms[bmNum]
var p = bm.p
var d = bm.d
// if (p.row >= 0 && p.col >= 0 && p.row < gr.size && p.col < gr[0].size) when (gr[p.row][p.col]) {
when (gr[p.row][p.col]) {
'.' -> p = moveBeam(p, d)
'|', '-' -> {
val r = branchBeam(p, d, gr)
p = r.first.p
d = r.first.d
val second = r.second
if (second != null) {
bmNum++
bms.addFirst(second)
vis.add(second)
}
}
'/', '\\' -> {
val r = diagonalBeam(p, d, gr[p.row][p.col])
p = r.p
d = r.d
}
}
val bmn = Beam(p, d)
if (bmn in vis || p.row < 0 || p.col < 0 || p.row >= gr.size || p.col >= gr[0].size) {
bms.removeAt(bmNum)
continue
}
bms[bmNum] = bmn
vis.add(bmn)
bmNum++
}
// println("${vis.size} - ${bms.size} - $genNum")
vh.add(vis.size)
genNum++
}
return vis.map { it.p }.toSet()
}
private fun diagonalBeam(p: Pos, d: Dir, t: Char): Beam {
if (t == '/') return when (d) {
Dir.UP -> Beam(p.copy(col = p.col + 1), Dir.RIGHT)
Dir.DOWN -> Beam(p.copy(col = p.col - 1), Dir.LEFT)
Dir.LEFT -> Beam(p.copy(row = p.row + 1), Dir.DOWN)
Dir.RIGHT -> Beam(p.copy(row = p.row - 1), Dir.UP)
}
if (t == '\\') return when (d) {
Dir.UP -> Beam(p.copy(col = p.col - 1), Dir.LEFT)
Dir.DOWN -> Beam(p.copy(col = p.col + 1), Dir.RIGHT)
Dir.LEFT -> Beam(p.copy(row = p.row - 1), Dir.UP)
Dir.RIGHT -> Beam(p.copy(row = p.row + 1), Dir.DOWN)
}
throw Exception("Invalid state, cannot process a diagonal move")
}
private fun branchBeam(p: Pos, d: Dir, gr: Grid): Pair<Beam, Beam?> {
if (gr[p.row][p.col] == '|' && (d == Dir.LEFT || d == Dir.RIGHT)) {
if (p.row == 0)
return Pair(Beam(p.copy(row = p.row + 1), Dir.DOWN), null)
if (p.row == gr.size - 1)
return Pair(Beam(p.copy(row = p.row - 1), Dir.UP), null)
return Pair(
Beam(p.copy(row = p.row - 1), Dir.UP),
Beam(p.copy(row = p.row + 1), Dir.DOWN)
)
}
if (gr[p.row][p.col] == '-' && (d == Dir.UP || d == Dir.DOWN)) {
if (p.col == 0)
return Pair(Beam(p.copy(col = p.col + 1), Dir.RIGHT), null)
if (p.col == gr[0].size - 1)
return Pair(Beam(p.copy(col = p.col - 1), Dir.LEFT), null)
return Pair(
Beam(p.copy(col = p.col - 1), Dir.LEFT),
Beam(p.copy(col = p.col + 1), Dir.RIGHT)
)
}
return Pair(Beam(moveBeam(p, d), d), null)
}
private fun moveBeam(p: Pos, d: Dir): Pos = when (d) {
Dir.UP -> p.copy(row = p.row - 1)
Dir.DOWN -> p.copy(row = p.row + 1)
Dir.LEFT -> p.copy(col = p.col - 1)
Dir.RIGHT -> p.copy(col = p.col + 1)
}
private fun printGrid(gen: Int, gr: Grid, beams: List<Beam>) {
println("Generation $gen")
val pos = beams.map { it.p }
gr.forEachIndexed { row, rowItems ->
rowItems.forEachIndexed { col, colItem ->
val p = Pos(row, col)
print(if (pos.indexOf(p) == -1) colItem else 'X')
}
println()
}
}
private fun printVis(gen: Int, gr: Grid, vis: Set<Beam>) {
println("Generation $gen")
val pos = vis.map { it.p }
gr.forEachIndexed { row, rowItems ->
rowItems.forEachIndexed { col, _ ->
val p = Pos(row, col)
print(if (p in pos) '#' else '.')
}
println()
}
}
private fun readInputGrid(testCase: String): Grid {
val reader =
object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader()
?: throw Exception("Invalid state, cannot read an input")
val input = mutableListOf<MutableList<Char>>()
while (true) {
val rawLine = reader.readLine() ?: break
input.add(rawLine.trim().toMutableList())
}
return input
}
private data class Pos(val row: Int = 0, val col: Int = 0)
private enum class Dir {
UP,
DOWN,
LEFT,
RIGHT
}
private data class Beam(val p: Pos, val d: Dir)
private typealias Grid = List<List<Char>>
| 0 | Kotlin | 0 | 0 | fb8da6c246b0e2ffadb046401502f945a82cfed9 | 5,703 | advent-of-code-2023 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.