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/nl/tiemenschut/aoc/y2023/day17.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.util.Direction
import nl.tiemenschut.aoc.lib.util.Direction.DOWN
import nl.tiemenschut.aoc.lib.util.Direction.RIGHT
import nl.tiemenschut.aoc.lib.util.grid.CharGridParser
import nl.tiemenschut.aoc.lib.util.grid.Grid
import nl.tiemenschut.aoc.lib.util.points.Point
import nl.tiemenschut.aoc.lib.util.points.by
import java.util.PriorityQueue
fun main() {
aoc(CharGridParser) {
puzzle { 2023 day 17 }
fun List<Direction>.nextValidDirections(): Set<Direction> {
if (isEmpty()) return mutableSetOf(DOWN, RIGHT)
val last = last()
val result = mutableSetOf(last.rotateLeft(), last.rotateRight())
if (size < 3 || takeLast(3).any { it != last }) result.add(last)
return result
}
data class Day17Key(val p: Point<Int>, val lastD: Direction, val c: Int)
fun key(p: Point<Int>, d: List<Direction>): Day17Key =
Day17Key(p, d.last(), d.takeLastWhile { it == d.last() }.count())
fun Grid<Char>.bestimate(): Int {
var p: Point<Int> = 0 by 0
var cost = 0
while (p != width() - 1 by height() - 1) {
p = p.moved(RIGHT)
cost += get(p).digitToInt()
p = p.moved(DOWN)
cost += get(p).digitToInt()
}
return cost
}
part1 { input ->
val bestPerLocation: MutableMap<Day17Key, Int> =
mutableMapOf(Day17Key(0 by 0, RIGHT, 0) to 0)
data class PathFindingPoint(val pos: Point<Int>, val directions: List<Direction>, val cost: Int)
fun Grid<Char>.findCheapest(points: PriorityQueue<PathFindingPoint>): Int {
var totalIter = 0
var best = input.bestimate()
while (points.isNotEmpty()) {
val p = points.poll()
if (p.cost >= best) continue
totalIter++
p.directions.nextValidDirections()
.map { d -> p.pos.moved(d) to d }
.filter { (n, _) -> n in this@findCheapest }
.map { (n, d) ->
PathFindingPoint(
n,
(p.directions + d).takeLast(3),
p.cost + this[n].digitToInt()
)
}
.filter { pfp ->
bestPerLocation.getOrDefault(key(pfp.pos, pfp.directions), Int.MAX_VALUE) > pfp.cost
}
.forEach { pfp ->
bestPerLocation[key(pfp.pos, pfp.directions)] = pfp.cost
if (pfp.pos == input.width() - 1 by input.height() - 1) {
best = best.coerceAtMost(pfp.cost)
} else if (pfp.cost < best) {
points.add(pfp)
}
}
}
println("iterations: $totalIter")
return best
}
val start = PriorityQueue<PathFindingPoint>(1) { o1, o2 -> o1.cost.compareTo(o2.cost) }
start.add(PathFindingPoint(0 by 0, emptyList(), 0))
input.findCheapest(start)
}
fun Grid<Char>.bestimatePart2(): Int {
var p: Point<Int> = 0 by 0
var cost = 0
while (p != width() - 1 by height() - 1) {
repeat(4) {
p = p.moved(RIGHT)
if (p in this) cost += get(p).digitToInt()
}
repeat(4) {
p = p.moved(DOWN)
if (p in this) cost += get(p).digitToInt()
}
}
return cost
}
fun Point<Int>.moved(d: Direction, count: Int): Point<Int> = when (d) {
Direction.UP -> x by y - count
Direction.DOWN -> x by y + count
Direction.LEFT -> x - count by y
Direction.RIGHT -> x + count by y
}
part2 { input ->
val bestPerLocation: MutableMap<Day17Key, Int> = mutableMapOf(Day17Key(0 by 0, RIGHT, 0) to 0)
data class PathFindingPoint(val pos: Point<Int>, val directions: List<Direction>, val cost: Int)
fun Grid<Char>.findCheapest(points: PriorityQueue<PathFindingPoint>): Int {
var totalIter = 0
var best = input.bestimatePart2()
while (points.isNotEmpty()) {
val p = points.poll()
if (p.cost >= best) continue
totalIter++
val nextDirections = if (p.directions.isEmpty()) setOf(RIGHT, DOWN)
else setOf(p.directions.last().rotateLeft(), p.directions.last().rotateRight())
nextDirections.flatMap { d ->
var runningCost = p.cost + (1 .. 3).sumOf {
val next = p.pos.moved(d, it)
if (next in this) this[next].digitToInt() else 0
}
val runningDirections = p.directions.toMutableList()
(4..10).mapNotNull {
val next = p.pos.moved(d, it)
if (next in this) {
runningCost += this[next].digitToInt()
runningDirections.add(d)
PathFindingPoint(next, runningDirections.takeLast(3), runningCost)
} else null
}
}
.filter { pfp ->
bestPerLocation.getOrDefault(key(pfp.pos, pfp.directions), Int.MAX_VALUE) > pfp.cost
}
.forEach { pfp ->
bestPerLocation[key(pfp.pos, pfp.directions)] = pfp.cost
if (pfp.pos == input.width() - 1 by input.height() - 1) {
best = best.coerceAtMost(pfp.cost)
} else if (pfp.cost < best) {
points.add(pfp)
}
}
}
println("iterations: $totalIter")
return best
}
val start = PriorityQueue<PathFindingPoint>(1) { o1, o2 -> o1.cost.compareTo(o2.cost) }
start.add(PathFindingPoint(0 by 0, emptyList(), 0))
input.findCheapest(start)
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 6,851 | aoc-2023 | The Unlicense |
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/DepthFirstSearch.kt | betulnecanli | 568,477,911 | false | {"Kotlin": 167849} | // The Depth-First Search (DFS) coding pattern is used for exploring or
//traversing a data structure by going as deep as possible before backtracking.
/*
Usage: This technique is used to solve problems involving traversing trees or graphs in a depth-first search manner.
*/
//1. Path With Given Sequence
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun hasPathWithSequence(root: TreeNode?, sequence: List<Int>): Boolean {
if (root == null) {
return sequence.isEmpty()
}
return dfsPathWithSequence(root, sequence, 0)
}
fun dfsPathWithSequence(node: TreeNode?, sequence: List<Int>, index: Int): Boolean {
if (node == null) {
return false
}
if (index >= sequence.size || node.`val` != sequence[index]) {
return false
}
if (node.left == null && node.right == null && index == sequence.size - 1) {
return true
}
return (
dfsPathWithSequence(node.left, sequence, index + 1) ||
dfsPathWithSequence(node.right, sequence, index + 1)
)
}
fun main() {
val root = TreeNode(1)
root.left = TreeNode(7)
root.right = TreeNode(9)
root.left?.left = TreeNode(4)
root.left?.right = TreeNode(5)
root.right?.left = TreeNode(2)
root.right?.right = TreeNode(7)
val sequence = listOf(1, 9, 7)
val result = hasPathWithSequence(root, sequence)
println("Has Path with Sequence $sequence: $result")
}
//2. Count Paths for a Sum
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun countPathsForSum(root: TreeNode?, targetSum: Int): Int {
return if (root == null) 0 else dfsCountPaths(root, targetSum) +
countPathsForSum(root.left, targetSum) +
countPathsForSum(root.right, targetSum)
}
fun dfsCountPaths(node: TreeNode?, remainingSum: Int): Int {
if (node == null) {
return 0
}
var pathCount = 0
if (node.`val` == remainingSum) {
pathCount++
}
pathCount += dfsCountPaths(node.left, remainingSum - node.`val`)
pathCount += dfsCountPaths(node.right, remainingSum - node.`val`)
return pathCount
}
fun main() {
val root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(-3)
root.left?.left = TreeNode(3)
root.left?.right = TreeNode(1)
root.right?.right = TreeNode(11)
root.left?.left?.left = TreeNode(3)
root.left?.left?.right = TreeNode(-2)
root.left?.right?.right = TreeNode(2)
val targetSum = 8
val result = countPathsForSum(root, targetSum)
println("Number of Paths for Sum $targetSum: $result")
}
/*
Path With Given Sequence:
The hasPathWithSequence function checks whether there exists a root-to-leaf path in the binary tree that matches
the given sequence using the DFS pattern.
Count Paths for a Sum:
The countPathsForSum function counts the number of paths in the binary tree where the sum of node values equals
the target sum using the DFS pattern.
*/
| 2 | Kotlin | 2 | 40 | 70a4a311f0c57928a32d7b4d795f98db3bdbeb02 | 3,021 | Kotlin-Data-Structures-Algorithms | Apache License 2.0 |
src/Day13.kt | karloti | 573,006,513 | false | {"Kotlin": 25606} | /**
* https://github.com/dfings/advent-of-code/blob/main/src/2022/problem_13.main.kts
* @author <NAME>
*/
sealed interface PacketData : Comparable<PacketData>
data class ListValue(val values: List<PacketData>) : PacketData {
override fun toString() = values.toString()
override operator fun compareTo(other: PacketData): Int = when (other) {
is IntValue -> compareTo(ListValue(listOf(other)))
is ListValue -> values
.zip(other.values)
.asSequence()
.map { (a, b) -> a.compareTo(b) }
.firstOrNull { it != 0 } ?: values.size.compareTo(other.values.size)
}
}
data class IntValue(val value: Int) : PacketData {
override fun toString() = value.toString()
override operator fun compareTo(other: PacketData): Int = when (other) {
is IntValue -> value.compareTo(other.value)
is ListValue -> ListValue(listOf(this)).compareTo(other)
}
}
fun String.parsePacketData() = ArrayDeque(toList()).parsePacketData()
fun ArrayDeque<Char>.parsePacketData(): PacketData {
if (first() != '[') return IntValue(joinToString("").toInt())
removeFirst()
val values = mutableListOf<PacketData>()
while (size > 1) {
val text = ArrayDeque<Char>()
var braceCounter = 0
while (true) {
val character = removeFirst()
when (character) {
'[' -> braceCounter++
']' -> if (--braceCounter < 0) break
',' -> if (braceCounter == 0) break
}
text.add(character)
}
values.add(text.parsePacketData())
}
return ListValue(values)
}
fun main() {
val input = readInput("Day13")
input
.filter(String::isNotBlank)
.map(String::parsePacketData)
.chunked(2)
.mapIndexed { i, it -> if (it[0] < it[1]) i + 1 else 0 }
.sum()
.let { check(it.also(::println) == 6086) }
val two = "[[2]]".parsePacketData()
val six = "[[6]]".parsePacketData()
input
.filter(String::isNotBlank)
.map(String::parsePacketData)
.plus(listOf(two, six))
.sorted()
.run { (indexOf(two) + 1) * indexOf(six) + 1 }
.let { check(it.also(::println) == 27798) }
} | 0 | Kotlin | 1 | 2 | 39ac1df5542d9cb07a2f2d3448066e6e8896fdc1 | 2,274 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/tonnoz/adventofcode23/day15/Day15Part2.kt | tonnoz | 725,970,505 | false | {"Kotlin": 78395} | package com.tonnoz.adventofcode23.day15
import com.tonnoz.adventofcode23.utils.readInput
import kotlin.system.measureTimeMillis
typealias BoxNr = Int
object Day15Part2 {
data class Box(val lensesBox: MutableList<Lens>){
data class Lens(val label: String, val value: String)
}
@JvmStatic
fun main(args: Array<String>) {
val input = "input15.txt".readInput().first().split(",")
val time = measureTimeMillis {
val boxes: MutableMap<BoxNr, Box> = mutableMapOf()
input.forEach { key ->
val label = getLabel(key)
val (hashedLabel, operator, lens) = getOtherVariables(label, key)
when (operator) {
"-" -> boxes.minusOp(hashedLabel, label)
"=" -> boxes.equalOp(hashedLabel, label, lens)
}
}
println("Part2: ${boxes.sumLenses()}")
}
println("P2 time: $time ms")
}
private fun MutableMap<BoxNr, Box>.sumLenses() = this.entries.fold(0L){ acc, curr -> acc + curr }
private fun getOtherVariables(label: String, key: String): Triple<Int, String, String> {
val hashedLabel = hash(label)
val operator = key.first { it == '-' || it == '=' }.toString()
val lens = key.substring(key.indexOfFirst { it == '-' || it == '=' } + 1)
return Triple(hashedLabel, operator, lens)
}
private fun MutableMap<BoxNr, Box>.equalOp(hashedLabel: Int, label: String, lens: String) {
val box = this.getOrPut(hashedLabel) { Box(mutableListOf(Box.Lens(label, lens))) }
box.replaceOrAddLensWithLabel(label, lens)
}
private fun MutableMap<BoxNr, Box>.minusOp(hashedLabel: Int, label: String) =
this[hashedLabel]?.let { box ->
box.removeFirstLensWithLabel(label)
if (box.lensesBox.isEmpty()) this.remove(hashedLabel)
}
infix operator fun Long.plus(other: MutableMap.MutableEntry<BoxNr, Box>): Long =
other.value.lensesBox.foldIndexed(0L) { i, acc, lens ->
acc + lens.value.toLong() * (i + 1) * (other.key + 1)
} + this
private fun hash(key: String) =
getLabel(key).fold(0) { acc, curr -> ((acc + curr.code) * 17) % 256 }
private fun getLabel(key: String) = key.takeWhile { it != '-' && it != '=' }
private fun Box.removeFirstLensWithLabel(label: String) =
this.lensesBox.remove(this.lensesBox.firstOrNull { it.label == label })
private fun Box.replaceOrAddLensWithLabel(lensLabel: String, lensValue: String) {
this.lensesBox.find { it.label == lensLabel }?.let { found ->
val aIndex = this.lensesBox.indexOf(found)
this.lensesBox[aIndex] = Box.Lens(label = found.label, value = lensValue)
} ?: this.lensesBox.add(Box.Lens(label = lensLabel, value = lensValue))
}
}
| 0 | Kotlin | 0 | 0 | d573dfd010e2ffefcdcecc07d94c8225ad3bb38f | 2,653 | adventofcode23 | MIT License |
kotlin/src/katas/kotlin/hackerrank/minimum_swaps2/MinimumSwaps2.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.hackerrank.minimum_swaps2
import katas.kotlin.hackerrank.OutputRecorder
import katas.kotlin.hackerrank.trimToLineSequence
import nonstdlib.permutations
import nonstdlib.printed
import datsok.shouldEqual
import org.junit.Test
import java.io.File
import java.util.*
/**
* https://www.hackerrank.com/challenges/minimum-swaps-2
*/
fun main() {
val scanner = Scanner(System.`in`)
main(generateSequence { scanner.nextLine() })
}
private fun main(input: Sequence<String>, output: (Any?) -> Unit = { println(it) }) {
val i = input.iterator()
i.next().trim().toInt() // skip number of items because it can be inferred from the line itself
val array = i.next().split(" ").map { it.toInt() }.toTypedArray()
output(minimumSwaps(array))
}
fun minimumSwaps_(array: Array<Int>): Int {
var result = 0
var i = 0
while (i < array.lastIndex) {
if (array[i] != i + 1) {
var j = i
while (array[j] != i + 1) j++
array.apply(Swap(i, j))
result++
}
i++
}
return result
}
fun minimumSwaps(array: Array<Int>): Int = findSwapsToSort(array).count()
private data class Swap(val i1: Int, val i2: Int) {
override fun toString() = "Swap($i1, $i2)"
}
private fun findSwapsToSort(array: Array<Int>): Sequence<Swap> =
if (array.size <= 1) emptySequence()
else {
var n = 0
generateSequence {
val i = IntRange(n, array.lastIndex).find { array[it] != it + 1 } ?: return@generateSequence null
var j = i
while (array[j] != i + 1) j++
// This 👇 really slows down testcase 9
// val j = IntRange(i, array.lastIndex).find { array[it] == i + 1 } ?: error(i)
val swap = Swap(i, j)
array.apply(swap)
n = i
swap
}
}
private fun <T> Array<T>.apply(swap: Swap) {
val tmp = this[swap.i1]
this[swap.i1] = this[swap.i2]
this[swap.i2] = tmp
}
class MinimumSwaps2 {
@Test fun `swaps for single element`() {
arrayOf(1) isSortedWithSwaps listOf()
}
@Test fun `swaps for two elements`() {
arrayOf(1, 2) isSortedWithSwaps listOf()
arrayOf(2, 1) isSortedWithSwaps listOf(Swap(0, 1))
}
@Test fun `swaps for three elements`() {
arrayOf(1, 2, 3) isSortedWithSwaps listOf()
arrayOf(1, 3, 2) isSortedWithSwaps listOf(Swap(1, 2))
arrayOf(2, 1, 3) isSortedWithSwaps listOf(Swap(0, 1))
arrayOf(2, 3, 1) isSortedWithSwaps listOf(Swap(0, 2), Swap(1, 2))
arrayOf(3, 1, 2) isSortedWithSwaps listOf(Swap(0, 1), Swap(1, 2))
arrayOf(3, 2, 1) isSortedWithSwaps listOf(Swap(0, 2))
}
@Test fun `swaps for four elements`() {
arrayOf(2, 1, 4, 3) isSortedWithSwaps listOf(Swap(0, 1), Swap(2, 3))
val permutations = arrayOf(1, 2, 3, 4).toList().permutations().map { it.toTypedArray() }
permutations.forEach {
findSwapsToSort(it).toList().printed()
}
}
@Test fun `testcase from the task`() {
arrayOf(7, 1, 3, 2, 4, 5, 6) isSortedWithSwaps listOf(
Swap(0, 1), Swap(1, 3), Swap(3, 4), Swap(4, 5), Swap(5, 6)
)
"""|7
|7 1 3 2 4 5 6
""" shouldOutput """
|5
"""
}
@Test fun `testcase 0`() {
arrayOf(4, 3, 1, 2) isSortedWithSteps listOf(
listOf(1, 3, 4, 2) to Swap(0, 2),
listOf(1, 2, 4, 3) to Swap(1, 3),
listOf(1, 2, 3, 4) to Swap(2, 3)
)
"""|4
|4 3 1 2
""" shouldOutput """
|3
"""
}
@Test fun `testcase 1`() {
arrayOf(2, 3, 4, 1, 5) isSortedWithSteps listOf(
listOf(1, 3, 4, 2, 5) to Swap(0, 3),
listOf(1, 2, 4, 3, 5) to Swap(1, 3),
listOf(1, 2, 3, 4, 5) to Swap(2, 3)
)
"""|5
|2 3 4 1 5
""" shouldOutput """
|3
"""
}
@Test fun `testcase 2`() {
arrayOf(1, 3, 5, 2, 4, 6, 7) isSortedWithSwaps listOf(
Swap(1, 3), Swap(2, 3), Swap(3, 4)
)
"""|7
|1 3 5 2 4 6 7
""" shouldOutput """
|3
"""
}
@Test fun `testcase 4`() {
"""|50
|2 31 1 38 29 5 44 6 12 18 39 9 48 49 13 11 7 27 14 33 50 21 46 23 15 26 8 47 40 3 32 22 34 42 16 41 24 10 4 28 36 30 37 35 20 17 45 43 25 19
""" shouldOutput """
|46
"""
}
@Test fun `testcase 9`() {
val input = File("src/katas/kotlin/hackerrank/minimum_swaps2/MinimumSwaps2-input09.txt").readText()
input shouldOutput """
|49990
"""
}
@Test fun `swaps on large array`() {
val array = Array(100_000) { it + 1 }
val i2 = array.size - 1
val tmp = array[0]
array[0] = array[i2]
array[i2] = tmp
minimumSwaps(array) shouldEqual 1
}
private infix fun Array<Int>.isSortedWithSwaps(expected: List<Swap>) {
findSwapsToSort(this).toList() shouldEqual expected
}
private infix fun Array<Int>.isSortedWithSteps(expected: List<Pair<List<Int>, Swap>>) {
findSwapsToSort(this).map { this.toList() to it }.toList() shouldEqual expected
}
private infix fun String.shouldOutput(expectedOutput: String) {
val outputRecorder = OutputRecorder()
main(trimToLineSequence(), outputRecorder)
outputRecorder.text shouldEqual expectedOutput.trimMargin() + "\n"
}
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 5,546 | katas | The Unlicense |
src/main/kotlin/com/quakbo/euler/Euler9.kt | quincy | 120,237,243 | false | null | package com.quakbo.euler
/*
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
According to Wikipedia, every Pythagorean triplet is expressed by
a = m^2 - n^2, b = 2mn, c = m^2 + n^2
where m > n > 0
and m and n are coprime
and m and n are both not odd
So an intelligent brute force approach is to increment m and n one at a time and find a, b, and c.
*/
fun main(args: Array<String>) {
val sum = 1000L
for (m in 2L..99L) {
for (n in 1L until m) {
val (a, b, c) = createPythagoreanTriplet(m, n) ?: continue
if ((a + b + c) == sum) {
println("Found ($a, $b, $c) with sum=${a + b + c} and product = ${a * b * c})")
return
}
}
}
println("No pythagorean triplets found which sum to 1000.")
}
internal fun createPythagoreanTriplet(m: Long, n: Long): Triple<Long, Long, Long>? {
if (m <= n || m < 1) {
return null
}
if (isOdd(m) && isOdd(n)) {
return null
}
if (coprime(m, n)) {
return null
}
val a: Long = (m * m) - (n * n)
val b: Long = 2 * m * n
val c: Long = (m * m) + (n * n)
return Triple(a, b, c)
}
private fun isOdd(i: Long): Boolean {
return i % 2L != 0L
}
/** Return true if the greatest common divisor of m and n is 1. */
private fun coprime(m: Long, n: Long): Boolean {
var gcd = 1
var i = 1
while (i <= m && i <= n) {
if (m % i == 0L && n % i == 0L) {
gcd = i
}
i++
}
return gcd == 1
}
| 0 | Kotlin | 0 | 0 | 01d96f61bda6e87f1f58ddf7415d9bca8a4913de | 1,737 | euler-kotlin | The Unlicense |
calendar/day09/Day9.kt | rocketraman | 573,845,375 | false | {"Kotlin": 45660} | package day09
import Day
import Lines
class Day9 : Day() {
data class Position(val x: Int, val y: Int) {
val adjacentPositions get() = setOf(
Position(x, y),
Position(x - 1, y - 1),
Position(x - 1, y),
Position(x - 1, y + 1),
Position(x, y - 1),
Position(x, y + 1),
Position(x + 1, y - 1),
Position(x + 1, y),
Position(x + 1, y + 1),
)
val right get() = copy(x = x + 1, y = y)
val up get() = copy(x = x, y = y + 1)
val left get() = copy(x = x - 1, y = y)
val down get() = copy(x = x, y = y - 1)
}
override fun part1(input: Lines): Any = simulate(input, 2)
override fun part2(input: Lines): Any = simulate(input, 10)
private fun simulate(input: Lines, knotCount: Int): Int {
val knots = MutableList(knotCount) { Position(0, 0) }
return buildSet {
add(knots.last())
inputToMoves(input).forEach { direction ->
knots[0] = knots.first().move(direction)
for (k in 1 until knotCount) knots[k] = knots[k].follow(knots[k - 1])
add(knots.last())
}
}.size
}
private fun inputToMoves(input: Lines) = input
.map { it.split(" ") }
// flatten multi-moves into individual moves
.flatMap { (direction, count) ->
List(count.toInt()) { direction }
}
private fun Position.move(direction: String) = when (direction) {
"R" -> right
"U" -> up
"L" -> left
"D" -> down
else -> error("Invalid direction $direction")
}
private fun Position.follow(leader: Position): Position = if (this in leader.adjacentPositions) this else when {
y == leader.y -> if (x < leader.x) right else left
x == leader.x -> if (y < leader.y) up else down
x < leader.x -> if (y < leader.y) up.right else down.right
else -> if (y < leader.y) up.left else down.left
}
}
| 0 | Kotlin | 0 | 0 | 6bcce7614776a081179dcded7c7a1dcb17b8d212 | 1,836 | adventofcode-2022 | Apache License 2.0 |
src/day04/Day04.kt | sophiepoole | 573,708,897 | false | null | package day04
import readInput
fun main() {
fun getRange(a: String): IntRange {
val split = a.split("-")
return split[0].toInt()..split[1].toInt()
}
fun checkPair(pair: String): Int {
val split = pair.split(",")
val a = getRange(split[0])
val b = getRange(split[1])
val intersect = a.intersect(b)
return if (intersect.size == a.count() || intersect.size == b.count()) { 1 }
else { 0 }
}
fun part1(input: List<String>): Int {
return input.sumOf { checkPair(it) }
}
fun checkPair2(pair: String): Int {
val split = pair.split(",")
val a = getRange(split[0])
val b = getRange(split[1])
val intersect = a.intersect(b)
return if (intersect.isNotEmpty()) { 1 }
else { 0 }
}
fun part2(input: List<String>): Int {
return input.sumOf { checkPair2(it) }
}
val testInput = readInput("day04/input_test")
println("----------Test----------")
println("Part 1: ${part1(testInput)}")
println("Part 2: ${part2(testInput)}")
val input = readInput("day04/input")
println("----------Input----------")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 00ad7d82cfcac2cb8a902b310f01a6eedba985eb | 1,267 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CheckWays.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
/**
* 1719. Number Of Ways To Reconstruct A Tree
* @see <a href="https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/">Source</a>
*/
fun interface CheckWays {
operator fun invoke(pairs: Array<IntArray>): Int
}
class CheckWaysDFS : CheckWays {
var result = 1
override operator fun invoke(pairs: Array<IntArray>): Int {
result = 1
val graph: HashMap<Int, HashSet<Int>> = HashMap()
for (pair in pairs) {
graph.computeIfAbsent(pair[0]) { HashSet() }.add(pair[1])
graph.computeIfAbsent(pair[1]) { HashSet() }.add(pair[0])
}
val nodes: ArrayList<Int> = ArrayList(graph.keys)
nodes.sortWith { a, b ->
graph.getOrDefault(a, HashSet()).size - graph.getOrDefault(b, HashSet()).size
}
val tree: HashMap<Int, ArrayList<Int>> = HashMap()
var root = -1
for (l in nodes.indices) {
var p = l + 1
val leaf = nodes[l]
while (p < nodes.size && !graph.getOrDefault(nodes[p], HashSet()).contains(leaf)) p++
if (p < nodes.size) {
tree.computeIfAbsent(nodes[p]) { ArrayList() }.add(leaf)
if (graph[nodes[p]]?.size == graph[leaf]?.size) {
result = 2
}
} else {
root = if (root == -1) {
leaf
} else {
return 0
}
}
}
dfs(root, 0, tree, graph, HashSet())
return result
}
private fun dfs(
root: Int,
depth: Int,
tree: HashMap<Int, ArrayList<Int>>,
graph: HashMap<Int, HashSet<Int>>,
visited: HashSet<Int?>,
): Int {
if (result == 0) return -1
if (visited.contains(root)) {
result = 0
return -1
}
visited.add(root)
var descendantsNum = 0
for (node in tree.getOrDefault(root, ArrayList())) {
descendantsNum += dfs(
node,
depth + 1,
tree,
graph,
visited,
)
}
if (descendantsNum + depth != graph[root]?.size) {
result = 0
return -1
}
return descendantsNum + 1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,970 | kotlab | Apache License 2.0 |
src/cn/leetcode/codes/simple22/Simple22.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple22
import cn.leetcode.codes.out
/**
* 刷题情况
*
* 题目地址:https://leetcode-cn.com/problems/generate-parentheses/
*
* 1 刷是否通过:没有
*
*
* 2 刷是否完成:
*
*
* 3 刷是否完成:
*
*
* 4 刷是否完成:
*
*
* 5 刷是否完成:
*
* 最优解析:https://leetcode-cn.com/problems/generate-parentheses/solution/gua-hao-sheng-cheng-by-leetcode-solution/
*
* 官方下方 第一条评论
*
*/
fun main() {
val n = 1
val re = generateParenthesis(n)
out(re)
}
/*
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
1 <= n <= 8
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
fun generateParenthesis(n: Int): List<String> {
val list = ArrayList<String>()
if (n <= 0) {
return list
}
generate(list,"", n, n)
return list
}
private fun generate(list: ArrayList<String>, str: String, left: Int, right: Int) {
//左右两边都使用完
if (left == 0 && right == 0) {
list.add(str)
return
}
//左右两边相同 先添加左括号
if (left == right){
generate(list, "$str(",left - 1,right)
}else{
//左边还有括号 先添加左括号
if (left > 0){
generate(list,"$str(",left - 1,right)
}
//添加右括号
generate(list,"$str)",left,right - 1)
}
}
| 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 1,769 | LeetCodeSimple | Apache License 2.0 |
src/extensions/grid/PathfindingDijkstraGraph.kt | TinusHeystek | 574,474,118 | false | {"Kotlin": 53071} | package extensions.grid
import java.util.TreeSet
class Edge(val nodeFrom: String, val nodeTo: String, val distance: Int)
/** One vertex of the graph, complete with mappings to neighbouring vertices */
class Vertex(val nodeName: String) : Comparable<Vertex> {
var distance = Int.MAX_VALUE // MAX_VALUE assumed to be infinity
var cameFromVertex: Vertex? = null
val neighbours = HashMap<Vertex, Int>()
override fun compareTo(other: Vertex): Int {
if (distance == other.distance) return nodeName.compareTo(other.nodeName)
return distance.compareTo(other.distance)
}
override fun toString() = "($nodeName, $distance)"
}
class Graph(
val edges: List<Edge>,
val directed: Boolean = true,
) {
// mapping of vertex names to Vertex objects, built from a set of Edges
private val graph = HashMap<String, Vertex>(edges.size)
init {
// one pass to find all vertices
for (edge in edges) {
if (!graph.containsKey(edge.nodeFrom)) graph[edge.nodeFrom] = Vertex(edge.nodeFrom)
if (!graph.containsKey(edge.nodeTo)) graph[edge.nodeTo] = Vertex(edge.nodeTo)
}
// another pass to set neighbouring vertices
for (edge in edges) {
graph[edge.nodeFrom]!!.neighbours[graph[edge.nodeTo]!!] = edge.distance
// also do this for an undirected graph if applicable
if (!directed) graph[edge.nodeTo]!!.neighbours[graph[edge.nodeFrom]!!] = edge.distance
}
}
/** Runs dijkstra using a specified source vertex */
fun dijkstra(startNodeName: String) {
if (!graph.containsKey(startNodeName)) {
println("Graph doesn't contain start vertex '$startNodeName'")
return
}
val source = graph[startNodeName]
val queue = TreeSet<Vertex>()
// set-up vertices
for (vertex in graph.values) {
vertex.cameFromVertex = if (vertex == source) source else null
vertex.distance = if (vertex == source) 0 else Int.MAX_VALUE
queue.add(vertex)
}
dijkstra(queue)
}
/** Implementation of dijkstra's algorithm using a binary heap */
private fun dijkstra(queue: TreeSet<Vertex>) {
while (!queue.isEmpty()) {
// vertex with the shortest distance (first iteration will return source)
val shortestDistanceVertex = queue.pollFirst()
// if distance is infinite we can ignore 'u' (and any other remaining vertices)
// since they are unreachable
if (shortestDistanceVertex.distance == Int.MAX_VALUE) break
//look at distances to each neighbour
for (neighbour in shortestDistanceVertex.neighbours) {
val vertex = neighbour.key // the neighbour in this iteration
val alternateDist = shortestDistanceVertex.distance + neighbour.value
if (alternateDist < vertex.distance) { // shorter path to neighbour found
queue.remove(vertex)
vertex.distance = alternateDist
vertex.cameFromVertex = shortestDistanceVertex
queue.add(vertex)
}
}
}
}
fun findPath(startNodeName: String, endNodeName: String): List<String> {
if (startNodeName == endNodeName)
return listOf(startNodeName)
dijkstra(startNodeName)
if (!graph.containsKey(endNodeName)) {
println("Graph doesn't contain end vertex '$endNodeName'")
return listOf()
}
val pathEdges = mutableListOf<String>()
pathEdges.add(graph[endNodeName]!!.nodeName)
var cameFromVertex = graph[endNodeName]!!.cameFromVertex
while (cameFromVertex != null) {
pathEdges.add(cameFromVertex.nodeName)
if (cameFromVertex.nodeName == startNodeName)
break
cameFromVertex = cameFromVertex.cameFromVertex
}
pathEdges.reverse()
return pathEdges
}
} | 0 | Kotlin | 0 | 0 | 80b9ea6b25869a8267432c3a6f794fcaed2cf28b | 4,072 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day4/Day04.kt | omarshaarawi | 573,867,009 | false | {"Kotlin": 9725} | package day4
import readInput
fun main() {
fun IntRange.overlaps(other: IntRange): Boolean {
return (this.first >= other.first && this.last <= other.last) ||
(other.first >= this.first && other.last <= this.last)
}
fun String.toRange(): IntRange {
return this.split("-")
.let { (a, b) -> a.toInt()..b.toInt() }
}
fun part1(): Int {
val input = readInput("day4/Day04")
.map { it.split(" ") }
.flatten()
.map { range -> range.split(",").map { it.toRange() } }
val countOfOverlaps = input.map {
val (a, b) = it
a.overlaps(b)
}.count { it }
return countOfOverlaps
}
fun part2(): Int {
val input = readInput("day4/Day04")
.map { it.split(" ") }
.flatten()
.map { range -> range.split(",").map { it.toRange() } }
val countOfIntersections = input.map {
val (a, b) = it
a.intersect(b)
}.count { it.isNotEmpty() }
return countOfIntersections
}
println(part1())
println(part2())
}
| 0 | Kotlin | 0 | 0 | 4347548045f12793a8693c4d31fe3d3dade5100a | 1,144 | advent-of-code-kotlin-2022 | Apache License 2.0 |
y2019/src/main/kotlin/adventofcode/y2019/Day02.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2019
import adventofcode.io.AdventSolution
import adventofcode.util.collections.cartesian
fun main() = Day02.solve()
object Day02 : AdventSolution(2019, 2, "1202 Program Alarm") {
override fun solvePartOne(input: String) = parse(input).runProgram(12, 2)
override fun solvePartTwo(input: String): Int? {
val data = parse(input)
return (0..99).cartesian()
.find { (n, v) -> data.runProgram(n, v) == 19690720 }
?.let { (n, v) -> 100 * n + v }
}
private fun parse(input: String): List<Int> = input.split(',').map(String::toInt)
private fun List<Int>.runProgram(n: Int, v: Int): Int {
val programData = this.toIntArray()
programData[1] = n
programData[2] = v
val p = IntProgram(programData)
p.run()
return p.mem[0]
}
}
private class IntProgram(val mem: IntArray, private var pc: Int = 0) {
fun run() {
while (true) {
when (mem[pc]) {
1 -> store(3, load(2) + load(1))
2 -> store(3, load(2) * load(1))
99 -> return
else -> throw IllegalStateException()
}
pc += 4
}
}
private fun load(offset: Int) = mem[mem[pc + offset]]
private fun store(offset: Int, v: Int) {
mem[mem[pc + offset]] = v
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,392 | advent-of-code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumFuelCost.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
/**
* 2477. Minimum Fuel Cost to Report to the Capital
* @see <a href="https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/">Source</a>
*/
fun interface MinimumFuelCost {
operator fun invoke(roads: Array<IntArray>, seats: Int): Long
}
class MinimumFuelCostDFS : MinimumFuelCost {
private var ans: Long = 0
private var s: Int = 0
override operator fun invoke(roads: Array<IntArray>, seats: Int): Long {
val graph: MutableList<MutableList<Int>> = ArrayList()
s = seats
for (i in 0 until roads.size + 1) {
graph.add(ArrayList())
}
for (r in roads) {
graph[r[0]].add(r[1])
graph[r[1]].add(r[0])
}
dfs(0, 0, graph)
return ans
}
private fun dfs(i: Int, prev: Int, graph: List<List<Int>>): Int {
var people = 1
for (x in graph[i]) {
if (x == prev) continue
people += dfs(x, i, graph)
}
if (i != 0) ans += (people + s - 1) / s
return people
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,699 | kotlab | Apache License 2.0 |
src/main/kotlin/aoc2019/OxygenSystem.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2019
import komu.adventofcode.aoc2019.MoveResult.FOUND
import komu.adventofcode.aoc2019.MoveResult.WALL
import komu.adventofcode.utils.Direction
import komu.adventofcode.utils.Direction.*
import komu.adventofcode.utils.Point
import utils.shortestPathBetween
fun oxygenSystem1(input: String): Int {
val (floor, tank) = createMap(input)
return floor.shortestPathOnFloor(Point.ORIGIN, tank).size
}
fun oxygenSystem2(input: String): Int {
val (floor, tank) = createMap(input)
val filled = mutableSetOf(tank)
var frontier = listOf(tank)
var minutes = 0
while (true) {
val nextFrontier = mutableListOf<Point>()
for (node in frontier)
for (neighbor in node.neighbors)
if (neighbor in floor && filled.add(neighbor))
nextFrontier += neighbor
if (nextFrontier.isEmpty())
return minutes
frontier = nextFrontier
minutes++
}
}
private fun createMap(input: String): Pair<Set<Point>, Point> {
val machine = IntCodeMachine(input)
var position = Point.ORIGIN
val floor = mutableSetOf(position)
val walls = mutableSetOf<Point>()
var tank: Point? = null
val queue = position.neighbors.toMutableSet()
while (queue.isNotEmpty()) {
val target = queue.removeClosest(position)
val path = floor.shortestPathOnFloor(position, target)
for (node in path) {
val direction = position.directionOfNeighbor(node)
val result = machine.executeMove(direction)
if (result == WALL) {
walls += node
} else {
floor += node
position = node
if (result == FOUND)
tank = node
for (neighbor in node.neighbors)
if (neighbor !in floor && neighbor !in walls)
queue += neighbor
}
}
}
return Pair(floor, tank!!)
}
private fun IntCodeMachine.executeMove(dir: Direction) =
MoveResult.values()[sendInputAndWaitForOutput(dir.toMove()).toInt()]
private enum class MoveResult {
WALL, MOVE, FOUND
}
private fun Set<Point>.shortestPathOnFloor(from: Point, to: Point): List<Point> =
shortestPathBetween(from, to) { p ->
p.neighbors.filter { it in this || it == to }
}!!
private fun MutableSet<Point>.removeClosest(p: Point): Point {
val closest = minByOrNull { it.manhattanDistance(p) } ?: error("no points")
remove(closest)
return closest
}
private fun Direction.toMove(): Long = when (this) {
UP -> 1
DOWN -> 2
LEFT -> 3
RIGHT -> 4
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 2,680 | advent-of-code | MIT License |
src/main/kotlin/dev/paulshields/aoc/Day20.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 20: Trench Map
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.readFileAsStringList
fun main() {
println(" ** Day 20: Trench Map ** \n")
val trenchMapImage = readFileAsStringList("/Day20TrenchMapImage.txt")
val imageEnhancementAlgorithm = trenchMapImage[0]
val image = trenchMapImage.drop(1)
val enhancedImage = enhanceImage(image, imageEnhancementAlgorithm, 2)
println("There are ${sumOfLitPixels(enhancedImage)} in the enhanced image")
val furtherEnhancedImage = enhanceImage(image, imageEnhancementAlgorithm, 50)
println("There are ${sumOfLitPixels(furtherEnhancedImage)} in the further enhanced image")
}
fun sumOfLitPixels(image: List<String>) = image.sumOf { it.sumOf { if (it == '#') 1L else 0L } }
fun enhanceImage(image: List<String>, imageEnhancementAlgorithm: String, numberOfIterations: Int = 1): List<String> {
var processedImage = image
var outOfBoundsPixel = '.'
for (i in 0 until numberOfIterations) {
processedImage = processImageEnhancementIteration(processedImage, imageEnhancementAlgorithm, outOfBoundsPixel)
outOfBoundsPixel = if (outOfBoundsPixel == '#') imageEnhancementAlgorithm.last() else imageEnhancementAlgorithm.first()
}
return processedImage
}
private fun processImageEnhancementIteration(image: List<String>, imageEnhancementAlgorithm: String, outOfBoundsPixel: Char) =
(-1 until image.height + 1).map { y ->
(-1 until image.width + 1).map { x ->
enhancePixelFromImage(x, y, image, imageEnhancementAlgorithm, outOfBoundsPixel)
}.joinToString("")
}
private fun enhancePixelFromImage(x: Int, y: Int, image: List<String>, imageEnhancementAlgorithm: String, unprocessedPixel: Char): Char {
val enhancementPositionAsBinaryString = (y - 1..y + 1).joinToString("") { consideredY ->
(x - 1..x + 1).joinToString("") { consideredX ->
when (getPixelFromImageOrElse(consideredX, consideredY, image, unprocessedPixel)) {
'#' -> "1"
else -> "0"
}
}
}
return imageEnhancementAlgorithm[enhancementPositionAsBinaryString.toInt(2)]
}
private fun getPixelFromImageOrElse(x: Int, y: Int, image: List<String>, orElse: Char) = image.getOrNull(y)?.getOrNull(x) ?: orElse
private val List<String>.width: Int
get() = this.first().length
private val List<String>.height: Int
get() = this.size
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 2,440 | AdventOfCode2021 | MIT License |
calendar/day12/Day12.kt | maartenh | 572,433,648 | false | {"Kotlin": 50914} | package day12
import Day
import Lines
import kotlin.math.max
class Day12 : Day() {
override fun part1(input: Lines): Any {
val map = parseMap(input)
map.calculateStepsToGoal()
println(map)
return map.stepsToGoal(map.start)
}
override fun part2(input: Lines): Any {
val map = parseMap(input)
map.calculateStepsToGoal()
val shortestPathStart = map.shortestPathStart()
return map.stepsToGoal(shortestPathStart)
}
private fun parseMap(input: Lines): Map {
val joinedLines = input.joinToString(separator = "")
val startIndex = joinedLines.indexOf("S")
val goalIndex = joinedLines.indexOf("E")
val width = input[0].length
val elevations = joinedLines.map {
when (it) {
'S' -> 0
'E' -> 25
else -> it.code - 'a'.code
}
}.toIntArray()
return Map(
elevations,
width,
input.size,
startIndex.toPosition(width),
goalIndex.toPosition(width)
)
}
}
private const val NotCalculated = -1
class Map(
private val elevations: IntArray,
private val width: Int,
private val height: Int,
val start: Position,
val goal: Position
) {
private val steps = IntArray(elevations.size) { NotCalculated }
private val indexRange = elevations.indices
private val xRange = 0 until width
private val yRange = 0 until height
fun calculateStepsToGoal() {
steps[goal.toIndex()] = 0
var step = 1
var lastPositions = setOf(goal)
while (steps[start.toIndex()] == NotCalculated) {
val candidates = findNotCalculatedNeighbours(lastPositions)
val nextSteps = candidates.filter { candidate ->
lastPositions.any { it.isAccessibleFrom(candidate)}
}
nextSteps.forEach { steps[it.toIndex()] = step }
lastPositions = nextSteps.toSet()
step += 1
}
}
fun stepsToGoal(position: Position) = steps[position.toIndex()]
fun shortestPathStart(): Position {
val potentialStartIndices = elevations.withIndex().filter { it.value == 0 }.map { it.index }
val calculatedStartIndices = potentialStartIndices.filter { steps[it] >= 0 }
return calculatedStartIndices.minBy { steps[it] }.toPosition(width)
}
private fun pathTo(target: Position): List<Position> {
val path = mutableListOf(target)
var position: Position? = start
var stepValue = steps[start.toIndex()]
while (stepValue > 0 && position != null) {
stepValue -= 1
val nextPosition = position.neighbours().firstOrNull {
steps[it.toIndex()] == stepValue && it.isAccessibleFrom(position!!)
}
if (nextPosition != null) {
path.add(position)
}
position = nextPosition
}
return path
}
private fun findNotCalculatedNeighbours(positions: Set<Position>) =
positions.flatMap { it.neighbours() }
.toSet()
.filter { it.toIndex() in indexRange && it.steps() == NotCalculated }
.toSet()
private fun Position.isAccessibleFrom(from: Position): Boolean =
this.elevation() <= from.elevation() + 1 && this in from.neighbours()
private fun Position.neighbours() =
listOf(
Position(x, y - 1),
Position(x + 1, y),
Position(x, y + 1),
Position(x - 1, y)
).filter {
it.x in xRange && it.y in yRange
}
private inline fun Position.toIndex() =
y * width + x
private inline fun Position.elevation() =
elevations[this.toIndex()]
private inline fun Position.steps() =
steps[this.toIndex()]
override fun toString(): String {
val aCode = 'a'.code
val cellWidth = max(steps.max().toString().length + 1, 3)
val startIndex = start.toIndex()
val goalIndex = goal.toIndex()
val pathIndices = pathTo(goal).map { it.toIndex() }.toSet()
val elevationLines = elevations.withIndex().joinToString(separator = "") { (index, elevation) ->
val elevationChar = (elevation + aCode).toChar()
val specialChar = when (index) {
startIndex -> 'S'
goalIndex -> 'E'
in pathIndices -> '*'
else -> ' '
}
"$elevationChar$specialChar".padEnd(cellWidth, ' ')
}.chunked(width * cellWidth)
val stepsLines = steps.joinToString(separator = "") {
"$it".padEnd(cellWidth, ' ')
}.chunked(width * cellWidth)
return elevationLines.zip(stepsLines)
.flatMap { (e, s) -> listOf(e, s, "") }
.joinToString(separator = "\n")
.plus("\n\n${pathTo(goal)}")
}
}
data class Position(val x: Int, val y: Int)
fun Int.toPosition(width: Int) = Position(this % width, this / width)
| 0 | Kotlin | 0 | 0 | 4297aa0d7addcdc9077f86ad572f72d8e1f90fe8 | 5,112 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/y2021/Day05.kt | jforatier | 432,712,749 | false | {"Kotlin": 44692} | package y2021
import kotlin.math.absoluteValue
import kotlin.math.sign
class Day05(private val data: List<String>) {
private val table: MutableMap<Coordinate, Int> = mutableMapOf()
data class Coordinate(val x: Int, val y: Int) {
fun lineTo(that: Coordinate): List<Coordinate> {
val xDelta = (that.x - x).sign
val yDelta = (that.y - y).sign
val steps = maxOf((x - that.x).absoluteValue, (y - that.y).absoluteValue)
return (1..steps).scan(this) { last, _ -> Coordinate(last.x + xDelta, last.y + yDelta) }
}
}
data class Line(val from: Coordinate, val to: Coordinate)
private fun Line.onTheSameLine(): Boolean {
return this.from.x == this.to.x
}
private fun Line.onTheSameColumn(): Boolean {
return this.from.y == this.to.y
}
private fun getSegments(input: List<String>): List<Line> {
return input
.map { line ->
line.split(" -> ") // <= Split values with " -> " separator
.map {
Coordinate(
it.split(",")[0].toInt(),
it.split(",")[1].toInt()
)
}
}.map { Line(it[0], it[1]) }
}
fun part1(): Int {
getSegments(data)
.filter { segment -> segment.onTheSameLine() || segment.onTheSameColumn() }
.forEach {
// 0,9 -> 5,9
// 8,0 -> 0,8
// ...
val line = it.from.lineTo(it.to)
line.forEach { point ->
if (table.get(Coordinate(point.x, point.y)) != null) {
table.put(Coordinate(point.x, point.y), table.get(Coordinate(point.x, point.y))!! + 1)
} else {
table.put(Coordinate(point.x, point.y), 1)
}
}
}
return table.count { it.value > 1 }
}
fun part2(): Int {
getSegments(data)
.forEach {
// 0,9 -> 5,9
// 8,0 -> 0,8
// ...
val line = it.from.lineTo(it.to)
line.forEach { point ->
if (table.get(Coordinate(point.x, point.y)) != null) {
table.put(Coordinate(point.x, point.y), table.get(Coordinate(point.x, point.y))!! + 1)
} else {
table.put(Coordinate(point.x, point.y), 1)
}
}
}
return table.count { it.value > 1 }
}
}
| 0 | Kotlin | 0 | 0 | 2a8c0b4ccb38c40034c6aefae2b0f7d4c486ffae | 2,663 | advent-of-code-kotlin | MIT License |
src/main/kotlin/de/tek/adventofcode/y2022/day09/RopeBridge.kt | Thumas | 576,671,911 | false | {"Kotlin": 192328} | package de.tek.adventofcode.y2022.day09
import de.tek.adventofcode.y2022.util.math.*
import de.tek.adventofcode.y2022.util.readInputLines
class Rope(vararg initialKnotPositions: Point) {
private val knotPositions = arrayOf(*initialKnotPositions)
private val tailHistory = mutableSetOf(knotPositions.last())
constructor(initialPosition: Point, numberOfKnots: Int) : this(*Array(numberOfKnots) { initialPosition })
companion object {
fun atOrigin(numberOfKnots: Int) = Rope(ORIGIN, numberOfKnots)
}
fun move(direction: Direction) {
moveHead(direction)
letTailFollowHead()
}
private fun moveHead(direction: Direction) {
knotPositions[0] = knotPositions[0] + direction.toVector()
}
private fun letTailFollowHead() {
for (i in 1 until knotPositions.size) {
val difference = knotPositions[i - 1] - knotPositions[i]
if (InfinityNorm.sizeOf(difference) > 1) {
knotPositions[i] = knotPositions[i] + Vector(difference.x.signum(), difference.y.signum())
}
}
updateTailHistory()
}
private fun Int.signum() = if (this > 0) 1 else if (this < 0) -1 else 0
private fun updateTailHistory() {
tailHistory.add(knotPositions.last())
}
fun getNumberOfVisitedTailPositions() = tailHistory.size
override fun toString(): String {
return "Rope(knotPositions=${knotPositions.contentToString()}, tailHistory=$tailHistory)"
}
fun visualize(): String {
if (knotPositions.size > 10) return "Too many knots to visualize."
val pointsToVisualize = tailHistory + knotPositions
val lowerLeftCorner = pointsToVisualize.lowerLeftCorner()!!
val upperRightCorner = pointsToVisualize.upperRightCorner()!!
val diagonal = upperRightCorner - lowerLeftCorner
val grid = Array(diagonal.y + 1) { Array(diagonal.x + 1) { '.' } }
val correctToOrigin = ORIGIN - lowerLeftCorner
tailHistory.map { it + correctToOrigin }.forEach { (x, y) -> grid[y][x] = '#' }
knotPositions.mapIndexed { index, position -> index to position + correctToOrigin }
.forEach { (index, point) -> grid[point.y][point.x] = index.toString()[0] }
return grid.reversed().joinToString("\n") { it.joinToString("") }
}
}
fun main() {
val input = readInputLines(Rope::class)
fun part1(input: List<String>): Int {
val rope = createAndMoveRope(2, input)
return rope.getNumberOfVisitedTailPositions()
}
fun part2(input: List<String>): Int {
val rope = createAndMoveRope(10, input)
return rope.getNumberOfVisitedTailPositions()
}
println("2 knots: ${part1(input)} positions were visited by the tail at least once.")
println("10 knots: ${part2(input)} positions were visited by the tail at least once.")
}
private fun createAndMoveRope(numberOfKnots: Int, input: List<String>): Rope {
val rope = Rope.atOrigin(numberOfKnots)
val moves = input.flatMap(::parseMove)
for (move in moves) {
rope.move(move)
}
return rope
}
fun parseMove(s: String): List<Direction> {
val (directionChar, numberOfMoves) = s.split(' ')
val direction = when (directionChar) {
"U" -> Direction.UP
"L" -> Direction.LEFT
"D" -> Direction.DOWN
"R" -> Direction.RIGHT
else -> throw IllegalArgumentException("Invalid move code, cannot parse direction: $s.")
}
return List(numberOfMoves.toInt()) { direction }
}
| 0 | Kotlin | 0 | 0 | 551069a21a45690c80c8d96bce3bb095b5982bf0 | 3,556 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/problems/Day20.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
class Day20(override val input: String) : Problem {
override val number: Int = 20
private val algorithm = input.lines().first()
private val LIT = '#'
private val pixelToBinary = mapOf('.' to '0', LIT to '1')
override fun runPartOne(): String {
return runAlgorithm(2)
}
override fun runPartTwo(): String {
return runAlgorithm(50)
}
private fun runAlgorithm(runs: Int): String {
val inputImage = input
.split("\n\n")[1]
.lines()
.map { it.toCharArray().toList() }
return (1..runs).fold(inputImage) { acc, run ->
val empty = when {
algorithm[0] == '.' -> '.'
run % 2 == 1 -> '.'
else -> '#'
}
acc.applyImageEnhancementAlgorithm(empty)
}
.sumOf { line -> line.count { it == LIT } }
.toString()
}
private fun List<List<Char>>.applyImageEnhancementAlgorithm(empty: Char = '.'): List<MutableList<Char>> {
val newList = List(this.size + 2) { MutableList(this.first().size + 2) { empty } }
for (m in newList.indices) {
for (n in newList.first().indices) {
val algorithmIdx = Pair(m, n)
.neighbours()
.map { (nm, nn) ->
val inBounds = ((nm - 1) in (0 until this.size)) && ((nn - 1) in (0 until this.first().size))
when (inBounds) {
false -> empty
else -> this[nm - 1][nn - 1]
}
}
.map { pixelToBinary[it]!! }
.joinToString(separator = "")
.toInt(2)
newList[m][n] = algorithm[algorithmIdx]
}
}
return newList
}
private fun Pair<Int, Int>.neighbours(): List<Pair<Int, Int>> {
return listOf(
Pair(-1, -1),
Pair(-1, 0),
Pair(-1, 1),
Pair(0, -1),
Pair(0, 0),
Pair(0, 1),
Pair(1, -1),
Pair(1, 0),
Pair(1, 1),
)
.map { Pair(it.first + this.first, it.second + this.second) }
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 2,298 | AdventOfCode2021 | MIT License |
src/day2/puzzle02.kt | brendencapps | 572,821,792 | false | {"Kotlin": 70597} | package day2
import Puzzle
import PuzzleInput
import java.io.File
sealed class Gesture(val value: Int) {
object Rock : Gesture(1)
object Paper : Gesture(2)
object Scissors : Gesture(3)
private fun win(opponent: Gesture): Boolean {
return when(this) {
Rock -> opponent == Scissors
Paper -> opponent == Rock
Scissors -> opponent == Paper
}
}
fun getResult(opponent: Gesture): Result {
return if(opponent == this) {
Result.Draw
} else if(win(opponent)) {
Result.Win
} else {
Result.Lose
}
}
}
sealed class Result(val value: Int) {
object Win : Result(6)
object Draw : Result(3)
object Lose : Result(0)
fun getPlayForResult(opponent: Gesture) : Gesture {
return when(this) {
Win ->
when(opponent) {
Gesture.Rock -> Gesture.Paper
Gesture.Scissors -> Gesture.Rock
Gesture.Paper -> Gesture.Scissors
}
Draw -> opponent
Lose ->
when(opponent) {
Gesture.Rock -> Gesture.Scissors
Gesture.Scissors -> Gesture.Paper
Gesture.Paper -> Gesture.Rock
}
}
}
}
data class GamePlay (
val opponent: String,
val me: String = "",
val result: String = "") {
private val _opponent: Gesture
private val _me: Gesture
private val _result: Result
init {
if(me.isBlank() && result.isBlank()) {
error("Invalid input. Expecting my gesture or result to be set.")
}
_opponent = getGesture(opponent)
if(me.isBlank()) {
_result = getResult(result)
_me = _result.getPlayForResult(_opponent)
}
else if(result.isBlank()) {
_me = getGesture(me)
_result = _me.getResult(_opponent)
}
else {
error("Expecting my gesture or result to be blank.")
}
}
private fun getResult(strategy: String) : Result {
return when(strategy) {
"X" -> Result.Lose
"Y" -> Result.Draw
"Z" -> Result.Win
else -> error("day2.Result input expected to be X, Y, or Z")
}
}
private fun getGesture(play: String) : Gesture {
return when(play) {
"A" -> Gesture.Rock
"B" -> Gesture.Paper
"C" -> Gesture.Scissors
"X" -> Gesture.Rock
"Y" -> Gesture.Paper
"Z" -> Gesture.Scissors
else -> error("day2.Gesture expected to be A, B, C, X, Y, or Z")
}
}
fun getScore(): Int {
return _me.value + _result.value
}
}
fun day2Puzzle() {
Day2Puzzle1Solution().solve(Day2PuzzleInput(10624))
Day2Puzzle2Solution().solve(Day2PuzzleInput(14060))
Day2Puzzle1Solution2().solve(Day2PuzzleInput(10624))
Day2Puzzle2Solution2().solve(Day2PuzzleInput(14060))
}
class Day2PuzzleInput(expectedResult: Int? = null) : PuzzleInput<Int>(expectedResult) {
fun getResult(result: (String, String) -> Int): Int {
return File("inputs/day2/strategy.txt").readLines().sumOf { game ->
val gamePlay = game.split(" ")
check(gamePlay.size == 2)
result(gamePlay[0], gamePlay[1])
}
}
fun getResult2(result: (String) -> Int): Int {
return File("inputs/day2/strategy.txt").readLines().sumOf { game ->
result(game)
}
}
}
class Day2Puzzle1Solution : Puzzle<Int, Day2PuzzleInput>() {
override fun solution(input: Day2PuzzleInput): Int {
return input.getResult { opponent, me ->
GamePlay(opponent = opponent, me = me).getScore()
}
}
}
class Day2Puzzle2Solution : Puzzle<Int, Day2PuzzleInput>() {
override fun solution(input: Day2PuzzleInput): Int {
return input.getResult { opponent, resultStrategy ->
GamePlay(opponent = opponent, result = resultStrategy).getScore()
}
}
}
class Day2Puzzle1Solution2 : Puzzle<Int, Day2PuzzleInput>() {
override fun solution(input: Day2PuzzleInput): Int {
return input.getResult2 { game ->
when(game) {
"A X" -> 1 + 3
"A Y" -> 2 + 6
"A Z" -> 3 + 0
"B X" -> 1 + 0
"B Y" -> 2 + 3
"B Z" -> 3 + 6
"C X" -> 1 + 6
"C Y" -> 2 + 0
"C Z" -> 3 + 3
else -> 0
}
}
}
}
class Day2Puzzle2Solution2 : Puzzle<Int, Day2PuzzleInput>() {
override fun solution(input: Day2PuzzleInput): Int {
return input.getResult2 { game ->
when (game) {
"A X" -> 3 + 0
"A Y" -> 1 + 3
"A Z" -> 2 + 6
"B X" -> 1 + 0
"B Y" -> 2 + 3
"B Z" -> 3 + 6
"C X" -> 2 + 0
"C Y" -> 3 + 3
"C Z" -> 1 + 6
else -> 0
}
}
}
}
| 0 | Kotlin | 0 | 0 | 00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3 | 5,369 | aoc_2022 | Apache License 2.0 |
src/Day04.kt | RogozhinRoman | 572,915,906 | false | {"Kotlin": 28985} | fun main() {
infix fun Pair<Int, Int>.isFullyContain(tested: Pair<Int, Int>) =
this.first <= tested.first && this.second >= tested.second
infix fun Pair<Int, Int>.includesStart(tested: Pair<Int, Int>) =
this.first <= tested.first && this.second >= tested.first
infix fun Pair<Int, Int>.hasOverlap(tested: Pair<Int, Int>) =
this includesStart tested || tested includesStart this
fun getInputPairs(input: List<String>) = input
.map { it.split(',') }
.map { it ->
it.map { it.split('-') }
.map { Pair(it.first().toInt(), it.last().toInt()) }
}
fun part1(input: List<String>) = getInputPairs(input).count {
it.first() isFullyContain it.last() ||
it.last() isFullyContain it.first()
}
fun part2(input: List<String>) = getInputPairs(input).count { it.first() hasOverlap it.last() }
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 | 6375cf6275f6d78661e9d4baed84d1db8c1025de | 1,106 | AoC2022 | Apache License 2.0 |
src/day3/day3.kt | allout58 | 159,955,103 | false | null | package day3
import java.io.File
data class Claim(val id: Int, val atX: Int, val atY: Int, val width: Int, val height: Int) {
fun toRectangel() = Rectangle(Point(atX, atY), Point(atX + width, atY + height))
}
fun main(args: Array<String>) {
val input = File("test.txt").useLines { it.toList() }
val regex = Regex("^#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)$")
val claims = input.map {
val res = regex.matchEntire(it)?.groupValues
if (res == null) {
null
} else {
val inted = res.subList(1, res.size).map { x -> x.toInt() }
Claim(inted[0], inted[1], inted[2], inted[3], inted[4])
}
}
val sparseTable = HashMap<Int, HashMap<Int, Int>>()
for (claim in claims.filterNotNull()) {
for (x in claim.atX until (claim.atX + claim.width)) {
val row = sparseTable.getOrDefault(x, HashMap())
for (y in claim.atY until (claim.atY + claim.height)) {
val oldValue = row.getOrDefault(y, 0)
row[y] = oldValue + 1
}
sparseTable[x] = row
}
}
var count = 0
for (row in sparseTable) {
for (column in row.value) {
if (column.value > 1) {
count++
}
}
}
print("Day 1: ")
println(count)
print("Day 2: ")
val rects = claims.filterNotNull().map { it.toRectangel() }.toMutableList()
val intersected = mutableListOf<Rectangle>();
for (rect in rects) {
if (rect in intersected) {
continue
}
for (rect2 in rects) {
if (rect == rect2) {
continue
}
if (rect2 in intersected) {
continue
}
if (rect.intersection(rect2) == null) {
intersected.add(rect)
intersected.add(rect2)
}
}
}
val notIntersected = rects.find { it !in intersected }
if (notIntersected != null) {
println(claims.filterNotNull().find {
it.atX == notIntersected.topLeft.x
&& it.atY == notIntersected.topLeft.y
&& it.atX + it.width == notIntersected.bottomRight.x
&& it.atY + it.height == notIntersected.bottomRight.y
})
}
}
| 0 | Kotlin | 0 | 0 | 20a634569ddc0cbcb22a47a2c79e2a4fd1470645 | 2,335 | AdventOfCode2018 | Apache License 2.0 |
src/day2/Day02.kt | helbaroudy | 573,339,882 | false | null | package day2
import readInput
fun main() {
fun parse(value: String): Move {
return when (value) {
"A", "X" -> Move.ROCK____
"B", "Y" -> Move.PAPER___
"C", "Z" -> Move.SCISSORS
else -> error("Err: $value")
}
}
fun parseDesiredResult(value: String) = when (value) {
"X" -> Result.LOSS
"Y" -> Result.DRAW
"Z" -> Result.WIN_
else -> error("Err: $value")
}
fun part1(input: List<String>) = input.fold(0) { total, entry ->
val entries = entry.split(" ")
val opponent = parse(entries[0])
val mine = parse(entries[1])
total + mine.play(opponent).score + mine.score
}
fun part2(input: List<String>) = input.fold(0) { total, entry ->
val entries = entry.split(" ")
val opponent = parse(entries[0])
val mine = opponent.moveForResult(parseDesiredResult(entries[1]))
total + mine.play(opponent).score + mine.score
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class Result(val score: Int) {
LOSS(0),
DRAW(3),
WIN_(6),
}
enum class Move(val score: Int) {
ROCK____(1),
PAPER___(2),
SCISSORS(3);
fun play(opponent: Move): Result {
return if (opponent == this) return Result.DRAW
else when (this) {
ROCK____ -> if (opponent == SCISSORS) Result.WIN_ else Result.LOSS
SCISSORS -> if (opponent == PAPER___) Result.WIN_ else Result.LOSS
PAPER___ -> if (opponent == ROCK____) Result.WIN_ else Result.LOSS
}
}
fun moveForResult(result: Result) = when (result) {
Result.LOSS -> when (this) {
ROCK____ -> SCISSORS
PAPER___ -> ROCK____
SCISSORS -> PAPER___
}
Result.DRAW -> this
Result.WIN_ -> when (this) {
ROCK____ -> PAPER___
PAPER___ -> SCISSORS
SCISSORS -> ROCK____
}
}
} | 0 | Kotlin | 0 | 0 | e9b98fc0eda739048e68f4e5472068d76ee50e89 | 2,013 | aoc22 | Apache License 2.0 |
src/Day07.kt | mr-cell | 575,589,839 | false | {"Kotlin": 17585} | fun main() {
fun part1(input: List<String>): Int {
val rootDir = parseInput(input)
return rootDir.find { it.size <= 100_000 }.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val rootDir = parseInput(input)
val unusedSpace = 70_000_000 - rootDir.size
val deficit = 30_000_000 - unusedSpace
return rootDir.find { it.size >= deficit }.minBy { it.size }.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private fun parseInput(input: List<String>): Directory {
val callStack = ArrayDeque<Directory>().apply { add(Directory("/")) }
input.forEach { item ->
when {
item == "$ ls" -> {} // no-op
item.startsWith("dir") -> {} // no-op
item == "$ cd /" -> callStack.removeIf { it.name != "/" }
item == "$ cd .." -> callStack.removeFirst()
item.startsWith("$ cd") -> {
val name = item.substringAfterLast(" ")
callStack.addFirst(callStack.first().traverse(name))
}
else -> {
val size = item.substringBefore(" ").toInt()
callStack.first().addFile(size)
}
}
}
return callStack.last()
}
private class Directory(val name: String) {
private val children: MutableMap<String, Directory> = mutableMapOf()
private var sizeOfFiles: Int = 0
val size: Int
get() = sizeOfFiles + children.values.sumOf { it.size }
fun addFile(size: Int) {
sizeOfFiles += size
}
fun traverse(dir: String): Directory = children.getOrPut(dir) { Directory(dir) }
fun find(predicate: (Directory) -> Boolean): List<Directory> =
children.values.filter(predicate) + children.values.flatMap { it.find(predicate) }
} | 0 | Kotlin | 0 | 0 | 2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9 | 2,031 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | topr | 572,937,822 | false | {"Kotlin": 9662} | import java.util.Stack
data class Stacks(private val stacks: List<Stack<Char>>) {
constructor(numberOfStacks: Int) : this((0 until numberOfStacks).map { Stack() })
fun topCrates() = stacks
.map(Stack<Char>::peek)
.joinToString("")
fun moveOneByOne(move: Move) = repeat(move.amount) {
stack(move.to).add(stack(move.from).pop())
}
fun moveAllAtOnce(move: Move) {
stack(move.to).addAll(stack(move.from).popAll(move.amount))
}
fun add(inputLine: String) {
stacks.forEachIndexed { index, stack ->
inputLine[index * 4 + 1]
.takeIf(Char::isLetter)
?.let(stack::add)
}
}
private fun stack(position: Int) = stacks[position - 1]
private fun <E> Stack<E>.popAll(amount: Int) = amount
.downTo(1)
.map { pop() }
.reversed()
}
data class Move(
val amount: Int,
val from: Int,
val to: Int
)
fun main() {
fun stacksOf(stacksInput: String): Stacks {
val startingStacks = stacksInput.lines().toMutableList().asReversed()
val numberOfStacks = startingStacks.removeFirst().trim().last().digitToInt()
return Stacks(numberOfStacks).also {
startingStacks.forEach(it::add)
}
}
fun movesOf(rearrangementInput: String) = rearrangementInput.lines()
.filterNot(String::isBlank)
.map { it.split(' ') }
.map {
Move(
it[1].toInt(),
it[3].toInt(),
it[5].toInt()
)
}
fun rearrange(stacks: Stacks, moves: List<Move>, action: (Stacks, Move) -> Unit) =
stacks.apply {
moves.forEach { action(this, it) }
}
fun part1(stacksInput: String, rearrangementInput: String) =
rearrange(
stacksOf(stacksInput),
movesOf(rearrangementInput),
Stacks::moveOneByOne
).topCrates()
fun part2(stacksInput: String, rearrangementInput: String) =
rearrange(
stacksOf(stacksInput),
movesOf(rearrangementInput),
Stacks::moveAllAtOnce
).topCrates()
fun splitInput(input: String) = input.split("\n\n")
val (testStacksInput, testRearrangementInput) = readInputText("Day05_test").let(::splitInput)
check(part1(testStacksInput, testRearrangementInput) == "CMZ")
check(part2(testStacksInput, testRearrangementInput) == "MCD")
val (stacksInput, rearrangementInput) = readInputText("Day05").let(::splitInput)
println(part1(stacksInput, rearrangementInput))
println(part2(stacksInput, rearrangementInput))
} | 0 | Kotlin | 0 | 0 | 8c653385c9a325f5efa2895e94830c83427e5d87 | 2,657 | advent-of-code-kotlin-2022 | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year18/Day22.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year18
import com.grappenmaker.aoc.*
import java.math.BigInteger
// I don't like this code
private val mod = 20183.toBigInteger()
private val xTimes = 16807L.toBigInteger()
private val yTimes = 48271L.toBigInteger()
fun PuzzleSet.day22() = puzzle {
val (depth, targetX, targetY) = rawInput.splitInts()
val depthBig = depth.toBigInteger()
val target = Point(targetX, targetY)
val cache = mutableMapOf<Point, BigInteger>(
Point(0, 0) to BigInteger.ZERO,
target to BigInteger.ZERO,
)
val grid = grid(targetX + 1, targetY + 1) { it.caveType(cache, depthBig) }
partOne = grid.elements.sum().s()
data class State(val equipped: Tool = Tool.TORCH, val pos: Point = Point(0, 0), val justEquipped: Boolean = false)
partTwo = dijkstra(
initial = State(),
isEnd = { it.pos == target && it.equipped == Tool.TORCH },
neighbors = { curr ->
curr.pos.adjacentSidesInf()
.filter { it.x >= 0 && it.y >= 0 && curr.equipped.isAllowed(it.caveType(cache, depthBig)) }
.map { curr.copy(pos = it, justEquipped = false) } + curr.copy(
equipped = curr.equipped.other(curr.pos.caveType(cache, depthBig)),
justEquipped = true
)
},
findCost = { if (it.justEquipped) 7 else 1 }
)?.cost.s()
}
private fun Point.geoIndex(cache: MutableMap<Point, BigInteger>, depth: BigInteger): BigInteger = cache.getOrPut(this) {
when {
y == 0 -> (x.toBigInteger() * xTimes) % mod
x == 0 -> (y.toBigInteger() * yTimes) % mod
else -> (Point(x - 1, y).erosion(cache, depth) * Point(x, y - 1).erosion(cache, depth)) % mod
}
}
private fun Point.erosion(cache: MutableMap<Point, BigInteger>, depth: BigInteger) =
(geoIndex(cache, depth) + depth) % mod
private fun Point.caveType(cache: MutableMap<Point, BigInteger>, depth: BigInteger) =
erosion(cache, depth).intValueExact() % 3
enum class Tool {
TORCH, CLIMB, NEITHER;
fun other(type: Int) = when (type) {
0 -> if (this == CLIMB) TORCH else CLIMB
1 -> if (this == CLIMB) NEITHER else CLIMB
2 -> if (this == TORCH) NEITHER else TORCH
else -> error("Impossible")
}
fun isAllowed(type: Int) = when (type) {
0 -> this == TORCH || this == CLIMB
1 -> this == NEITHER || this == CLIMB
2 -> this == TORCH || this == NEITHER
else -> error("Impossible")
}
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,496 | advent-of-code | The Unlicense |
aoc-2021/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentyone/Day05.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwentyone
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.readDayInput
import kotlin.math.abs
class Day05 : Day<Int> {
private data class Point(val x: Int, val y: Int) {
override fun toString() = "($x,$y)"
}
private data class Segment(val a: Point, val b: Point) {
override fun toString() = "[$a $b]"
}
private val input = readDayInput()
.lineSequence()
.map { line ->
val (a, b) = line.split(" -> ").map { point ->
val (x, y) = point.split(',')
Point(x.toInt(), y.toInt())
}
Segment(a, b)
}
private data class State(
val map: Array<IntArray> = Array(0) { IntArray(0) }
) {
val height: Int = map.size
val width: Int = map.firstOrNull()?.size ?: 0
fun copyWithSize(height: Int, width: Int) = copy(
map = Array(height) { index ->
map.getOrNull(index)?.copyOf(width) ?: IntArray(width)
}
)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as State
if (!map.contentDeepEquals(other.map)) return false
return true
}
override fun hashCode(): Int {
return map.contentDeepHashCode()
}
}
private fun State.reduce(segment: Segment, withDiagonals: Boolean) = with(segment) {
// Increase map size if necessary
val height = maxOf(height, a.y + 1, b.y + 1)
val width = maxOf(width, a.x + 1, b.x + 1)
copyWithSize(height, width).apply {
a.rangeTo(b, withDiagonals = withDiagonals).forEach { p ->
map[p.y][p.x] = map[p.y][p.x] + 1
}
}
}
private fun Point.rangeTo(other: Point, withDiagonals: Boolean): List<Point> {
if (x > other.x) return other.rangeTo(this, withDiagonals)
val coeff = (other.y - y).toFloat() / (other.x - x).toFloat()
return when {
// Vertical
x == other.x -> (minOf(y, other.y)..maxOf(y, other.y)).map { y -> Point(x, y) }
// Horizontal
y == other.y -> (minOf(x, other.x)..maxOf(x, other.x)).map { x -> Point(x, y) }
!withDiagonals -> emptyList()
coeff == 1f -> (0..abs(other.x - x)).map { i -> Point(x + i, y + i) }
coeff == -1f -> (0..abs(other.x - x)).map { i -> Point(x + i, y - i) }
else -> error("unknown range")
}
}
private fun State.countOverlaps(): Int =
map.sumOf { line ->
line.sumOf { count ->
if (count > 1) 1L else 0L
}
}.toInt()
private fun State.print() {
map.forEach { line ->
println(
line.joinToString(" ") {
if (it == 0) "." else it.toString()
}
)
}
println()
println()
}
override fun step1(): Int = input
.fold(State()) { acc, segment ->
acc.reduce(segment, withDiagonals = false)
}
.countOverlaps()
override fun step2(): Int = input
.fold(State()) { acc, segment ->
acc.reduce(segment, withDiagonals = true)
}
.countOverlaps()
override val expectedStep1 = 8060
override val expectedStep2 = 21577
}
| 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 3,502 | adventofcode | Apache License 2.0 |
src/main/kotlin/com/tonnoz/adventofcode23/day1/One.kt | tonnoz | 725,970,505 | false | {"Kotlin": 78395} | package com.tonnoz.adventofcode23.day1
import com.tonnoz.adventofcode23.utils.readInput
object One{
@JvmStatic
fun main(args: Array<String>) {
val inputLines = "inputOne.txt".readInput()
inputLines
.sumOf { "${it.firstDigit()}${it.lastDigit()}".toInt() }
.let { println("solution 1st q: $it") } //solution first problem: 55108
inputLines
.sumOf { "${it.firstDigitOrDigitWord()}${it.lastDigitOrDigitWord()}".toInt() }
.let { println("solution 2nd q: $it") } //solution second problem: 56324
}
private val digitWords = 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
)
private val digitWordsR = mapOf(
"eno" to 1,
"owt" to 2,
"eerht" to 3,
"ruof" to 4,
"evif" to 5,
"xis" to 6,
"neves" to 7,
"thgie" to 8,
"enin" to 9
)
private fun String.firstDigit(): Char = this.first{ aChar -> aChar.isDigit() }
private fun String.lastDigit(): Char = this.last{ aChar -> aChar.isDigit() }
private fun String.firstDigitOrDigitWord(): Int {
for (i in indices) {
if (this[i].isDigit()) return this[i].digitToInt()
for ((word, value) in digitWords) {
if (i + word.length <= length && substring(i, i + word.length) == word) {
return value
}
}
}
return -9999999
}
private fun String.lastDigitOrDigitWord(): Int {
for (i in this.indices.reversed()) {
if (this[i].isDigit()) return this[i].digitToInt()
for ((word, value) in digitWordsR) {
if (i - word.length >= 0 && substring(i - word.length, i) == word) {
return value
}
}
}
return -9999999
}
}
| 0 | Kotlin | 0 | 0 | d573dfd010e2ffefcdcecc07d94c8225ad3bb38f | 1,754 | adventofcode23 | MIT License |
src/main/kotlin/com/marcdenning/adventofcode/day07/Day07a.kt | marcdenning | 317,730,735 | false | {"Kotlin": 87536} | package com.marcdenning.adventofcode.day07
import java.io.File
import java.util.*
import java.util.regex.Pattern
import java.util.stream.Collectors
fun main(args: Array<String>) {
var numberOfColors = 0
Scanner(File(args[0])).use { scanner ->
numberOfColors += getAncestorsOfTargetColor(parseRules(scanner), args[1]).size
}
println("Number of colors: $numberOfColors")
}
/**
* Extract map of color to rule pairings from a Scanner. Rules are a map of color to number of bags.
*/
fun parseRules(scanner: Scanner): Map<String, Map<String, Int>> = mapOf(
*
scanner.findAll("([\\w\\s]+)\\sbags\\scontain\\s([\\d\\s\\w\\,]+)\\.\\n?").map {
Pair(it.group(1), parseRulesForColor(it.group(2)))
}.collect(Collectors.toList()).toTypedArray()
)
fun parseRulesForColor(rulesString: String): Map<String, Int> {
if ("no other bags" == rulesString) {
return emptyMap()
}
return mapOf(
*rulesString.split(',')
.map {
val matcher = Pattern.compile("(\\d+)\\s([\\w\\s]+)\\sbags?").matcher(it.trim())
matcher.matches()
Pair(matcher.group(2), matcher.group(1).toInt())
}.toTypedArray()
)
}
fun getAncestorsOfTargetColor(rules: Map<String, Map<String, Int>>, targetColor: String): Set<String> {
// find colors that immediately contain the target color
val immediateParentRules = rules.filter { entry -> entry.value.containsKey(targetColor) }
// recurse through map for immediate parent colors to find their parents
if (immediateParentRules.isEmpty()) {
return emptySet()
}
return immediateParentRules.keys union immediateParentRules.map { getAncestorsOfTargetColor(rules, it.key) }
.reduce { s1, s2 -> s1 union s2}
}
| 0 | Kotlin | 0 | 0 | b227acb3876726e5eed3dcdbf6c73475cc86cbc1 | 1,792 | advent-of-code-2020 | MIT License |
src/Day04.kt | SimoneStefani | 572,915,832 | false | {"Kotlin": 33918} | fun main() {
fun extractRanges(line: String): Pair<IntRange, IntRange> {
val (first, second) = line.split(",")
val (fStart, fEnd) = first.split("-").map { it.toInt() }
val (sStart, sEnd) = second.split("-").map { it.toInt() }
return Pair(IntRange(fStart, fEnd), IntRange(sStart, sEnd))
}
fun part1(input: List<String>): Int {
return input.count { line ->
val (firstRange, secondRange) = extractRanges(line)
firstRange.fullyOverlapsWith(secondRange) || secondRange.fullyOverlapsWith(firstRange)
}
}
fun part2(input: List<String>): Int {
return input.count { line ->
val (firstRange, secondRange) = extractRanges(line)
firstRange.overlapsWith(secondRange)
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun IntRange.fullyOverlapsWith(other: IntRange) = this.first <= other.first && this.last >= other.last
fun IntRange.overlapsWith(other: IntRange) = this.intersect(other).isNotEmpty() | 0 | Kotlin | 0 | 0 | b3244a6dfb8a1f0f4b47db2788cbb3d55426d018 | 1,183 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | colund | 573,040,201 | false | {"Kotlin": 10244} | fun main() {
val lines = readInput("Day07")
day7(lines)
}
fun day7(lines: List<String>) {
val cdCommand = "\\$ cd (.*)".toRegex()
val sizeFile = "(\\d+) (.*)".toRegex()
val pathSizes = mutableMapOf<String, Int>()
var cwd = ""
for (line in lines) {
if (line == "\$ ls") continue
cdCommand.captures(line)?.let { list ->
val cdDir = list.first()
if (cdDir == "..") { // Go up
cwd = cwd.substringBeforeLast("/")
return@let
}
cwd = cwd + (if (cwd.endsWith("/") || cdDir == "/") "" else "/") + cdDir
pathSizes[cwd] = 0
} ?: sizeFile.captures(line)?.let {
val size: Int = it[0].toInt()
var currDir = cwd
while (true) {
pathSizes[currDir] = pathSizes.getOrDefault(currDir, 0) + size
if (currDir == "/") break
currDir = if (currDir.lastIndexOf("/") > 0) currDir.substringBeforeLast("/") else "/"
}
}
}
println("Day7 part 1: " + pathSizes.filter { it.value < 100_000 }.values.sum())
val freeSpace = 70000000 - pathSizes.getOrDefault("/", 0)
val missing = 30000000 - freeSpace
println("Day7 part 2: " + pathSizes.filter { it.value > missing }.values.minOf { it })
}
private fun Regex.captures(line: String): List<String>? {
return find(line)?.groupValues?.drop(1)
}
| 0 | Kotlin | 0 | 0 | 49dcd2fccad0e54ee7b1a9cb99df2acdec146759 | 1,434 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/days/Day8.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package days
import util.DAY_FILE
import util.DayInput
import java.math.BigInteger
class Day8 : Day("8") {
override fun partOne(dayInput: DayInput): Any {
val instructions = dayInput.inputList()[0].toCharArray()
val map = dayInput.inputList().subList(2, dayInput.inputList().size).map {
val split = it.split(" = ")
val node = split[0]
val path = split[1].replace(")", "").replace("(", "").split(", ")
node to Pair(path[0], path[1])
}.toMap()
var current = "AAA"
var instructionsCount = -1
var steps = 0
while (current != "ZZZ") {
instructionsCount++
val instruction = instructions[instructionsCount % instructions.size]
val pair = map[current]!!
current = if (instruction == 'L') pair.first else pair.second
}
return instructionsCount + 1
}
// Function to calculate the Greatest Common Divisor (GCD) using Euclidean algorithm
fun calculateGCD(a: Long, b: Long): Long {
return if (b == 0L) {
a
} else {
calculateGCD(b, a % b)
}
}
// Function to calculate the Least Common Multiple (LCM) given two numbers
fun calculateLCM(a: Long, b: Long): Long {
return a * b / calculateGCD(a, b)
}
// Function to calculate the LCD for an array of numbers
fun findLCD(numbers: LongArray): BigInteger {
var commomnLCD = BigInteger.valueOf(numbers[0])
numbers.slice(1 until numbers.size).forEach {
val current = BigInteger.valueOf(it)
val mult = commomnLCD.multiply(current)
val gcd: BigInteger = commomnLCD.gcd(current)
commomnLCD = mult.divide(gcd)
}
return commomnLCD
}
override fun partTwo(dayInput: DayInput): Any {
val instructions = dayInput.inputList()[0].toCharArray()
val map = dayInput.inputList().subList(2, dayInput.inputList().size).map {
val split = it.split(" = ")
val node = split[0]
val path = split[1].replace(")", "").replace("(", "").split(", ")
node to Pair(path[0], path[1])
}.toMap()
/*var current = map.map { it.key }.filter { it.last() == 'A' }*/
var current = map.map { it.key }.filter { it.last() == 'A' }
val interations = mutableListOf<Long>()
for (strart in current) {
var instructionsCount = -1
var currentStart = strart
while (currentStart.last() != 'Z') {
instructionsCount++
val instruction = instructions[instructionsCount % instructions.size]
val pair = map[currentStart]!!
currentStart = if (instruction == 'L') pair.first else pair.second
}
interations.add(instructionsCount + 1L)
}
return findLCD(interations.toLongArray())
}
fun partTwoM(dayInput: DayInput): Any {
val instructions = dayInput.inputList()[0].toCharArray()
val map = dayInput.inputList().subList(2, dayInput.inputList().size).map {
val split = it.split(" = ")
val node = split[0]
val path = split[1].replace(")", "").replace("(", "").split(", ")
node to Pair(path[0], path[1])
}.toMap()
/*var current = map.map { it.key }.filter { it.last() == 'A' }*/
var current = map.map { it.key }.filter { it.last() == 'A' }
val occurance: MutableMap<String, MutableMap<String, MutableList<Pair<Int, Int>>>> = mutableMapOf()
for (strart in current) {
occurance.put(strart, mutableMapOf())
var currentStarrt = strart
var instructionsCount = 0
while (true) {
currentStarrt = map[currentStarrt]!!.let {
val instruction = instructions[instructionsCount % instructions.size]
if (instruction == 'L') it.first else it.second
}
instructionsCount++
if (currentStarrt.last() == 'Z') {
occurance[strart]!!.putIfAbsent(currentStarrt, mutableListOf())
val firstIndex = occurance.get(strart)!!.get(currentStarrt)!!.lastOrNull()?.first ?: 0
occurance.get(strart)!!.get(currentStarrt)!!
.add(Pair(instructionsCount, instructionsCount - firstIndex + 1))
println("$currentStarrt ${occurance.get(strart)!!.get(currentStarrt)!!}")
if (occurance.get(strart)!!.get(currentStarrt)!!.size > 4) {
break
}
}
}
}
return ""
}
}
fun main() {
val day = Day8().run()
}
| 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 4,813 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
src/Day05.kt | 6234456 | 572,616,769 | false | {"Kotlin": 39979} | fun main() {
fun part1(input: List<String>): String {
var sep = -1
input.forEachIndexed { index, s ->
if (s.isBlank()){
sep = index
return@forEachIndexed
}
}
val indexList = input[sep-1]
.toCharArray().mapIndexed { index, c -> index to c }
.filter { it.second.toString().isNotBlank() }.map { it.first }
val stacks = Array(indexList.size){java.util.Stack<Char>()}
((sep - 2) downTo 0).forEach {
indexList.map { idx ->
if (input[it].length <= idx)
' '
else
input[it][idx]
}.forEachIndexed { index, c ->
if (c.toString().isNotBlank())
stacks[index].push(c)
}
}
// orders
((sep + 1) until input.size).forEach {
val orders = """\s+\d+(?:\s+|\b)""".toRegex().findAll(input[it]).map { it.value.trim().toInt()}.toList()
val cnt = orders.first()
val src = orders[1]
val targ = orders.last()
repeat(cnt){
stacks[targ-1].push(stacks[src-1].pop())
}
}
return stacks.map { it.peek() }.joinToString("")
}
fun part2(input: List<String>): String {
var sep = -1
input.forEachIndexed { index, s ->
if (s.isBlank()){
sep = index
return@forEachIndexed
}
}
val indexList = input[sep-1]
.toCharArray().mapIndexed { index, c -> index to c }
.filter { it.second.toString().isNotBlank() }.map { it.first }
val stacks = Array(indexList.size){java.util.Stack<Char>()}
((sep - 2) downTo 0).forEach {
indexList.map { idx ->
if (input[it].length <= idx)
' '
else
input[it][idx]
}.forEachIndexed { index, c ->
if (c.toString().isNotBlank())
stacks[index].push(c)
}
}
// orders
val tmp = java.util.Stack<Char>()
((sep + 1) until input.size).forEach {
val orders = """\s+\d+(?:\s+|\b)""".toRegex().findAll(input[it]).map { it.value.trim().toInt()}.toList()
val cnt = orders.first()
val src = orders[1]
val targ = orders.last()
repeat(cnt){
tmp.push(stacks[src-1].pop())
}
while (!tmp.isEmpty()){
stacks[targ-1].push(tmp.pop())
}
}
return stacks.map { it.peek() }.joinToString("")
}
var input = readInput("Test05")
println(part1(input))
println(part2(input))
input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b6d683e0900ab2136537089e2392b96905652c4e | 2,912 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | mihansweatpants | 573,733,975 | false | {"Kotlin": 31704} | fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.getCommonItem() }
.sumOf { it.getPriority() }
}
fun part2(input: List<String>): Int {
return input.withIndex()
.groupBy(keySelector = { it.index / 3 }, valueTransform = { it.value })
.values
.map { it.getCommonItem() }
.sumOf { it.getPriority() }
}
val input = readInput("Day03").lines()
println(part1(input))
println(part2(input))
}
private fun String.getCommonItem(): Char {
val firstHalf = this.take(this.length / 2).toSet()
val secondHalf = this.takeLast(this.length / 2).toSet()
return firstHalf.intersect(secondHalf).first()
}
private fun Iterable<String>.getCommonItem(): Char =
this.map { it.toSet() }.reduce { acc, curr -> acc.intersect(curr) }.first()
private fun Char.getPriority(): Int {
val basePriority = 1 + ('z' - 'a') - ('z' - this.lowercaseChar())
if (this.isUpperCase()) {
return 26 + basePriority
}
return basePriority
} | 0 | Kotlin | 0 | 0 | 0de332053f6c8f44e94f857ba7fe2d7c5d0aae91 | 1,077 | aoc-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/movies_on_flight/MoviesOnFlight.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.leetcode.movies_on_flight
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/discuss/interview-question/313719/Amazon-or-Online-Assessment-2019-or-Movies-on-Flight
*/
class MoviesOnFlightTests {
@Test fun examples() {
findMovies(movieDurations = emptyArray(), flightDuration = 100) shouldEqual null
findMovies(movieDurations = arrayOf(1), flightDuration = 100) shouldEqual null
findMovies(movieDurations = arrayOf(1, 2), flightDuration = 20) shouldEqual null
findMovies(movieDurations = arrayOf(1, 2), flightDuration = 100) shouldEqual Pair(1, 2)
findMovies(movieDurations = arrayOf(1, 2, 3), flightDuration = 100) shouldEqual Pair(2, 3)
findMovies(
movieDurations = arrayOf(90, 85, 75, 60, 120, 150, 125),
flightDuration = 250
) shouldEqual Pair(90, 125)
}
@Test fun `if two pairs are equal, prefer the one with the longest movie`() {
findMovies(movieDurations = arrayOf(40, 50, 30, 60), flightDuration = 120) shouldEqual Pair(30, 60)
}
}
private fun findMovies(movieDurations: Array<Int>, flightDuration: Int): Pair<Int, Int>? {
var max = 0
var maxPair: Pair<Int, Int>? = null
fun updateMax(target: Int, firstIndex: Int, secondIndex: Int) {
if (firstIndex == secondIndex) return
if (secondIndex < 0 || secondIndex >= movieDurations.size) return
val first = movieDurations[firstIndex]
val second = movieDurations[secondIndex]
if (second > target) return
val sum = first + second
if (sum > max) {
max = sum
maxPair = Pair(first, second)
}
}
movieDurations.sort()
for ((index, first) in movieDurations.withIndex()) {
val target = flightDuration - 30 - first
if (target > 0) {
val i = movieDurations.binarySearch(target, fromIndex = index + 1)
if (i >= 0) updateMax(target, index, i)
else {
updateMax(target, index, -i - 2)
updateMax(target, index, -i - 1)
}
}
}
return maxPair
}
private fun findMovies_loops(movieDurations: Array<Int>, flightDuration: Int): Pair<Int, Int>? {
movieDurations.sort()
val target = flightDuration - 30
var max = 0
var maxPair: Pair<Int, Int>? = null
for ((index, first) in movieDurations.withIndex()) {
for (second in movieDurations.drop(index + 1)) {
val sum = first + second
if (sum > target) continue
if (sum > max) {
max = sum
maxPair = Pair(first, second)
}
}
}
return maxPair
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,719 | katas | The Unlicense |
src/main/kotlin/aoc/Day4.kt | dtsaryov | 573,392,550 | false | {"Kotlin": 28947} | package aoc
import kotlin.math.max
import kotlin.math.min
/**
* [AoC 2022: Day 4](https://adventofcode.com/2022/day/4)
*/
fun getNestedRangesCount(): Int {
val input = readInput("day4.txt") ?: return -1
return getRanges(input).fold(0) { acc, (left, right) ->
if (left.contains(right) || right.contains(left)) acc + 1
else acc
}
}
fun getOverlapsCount(): Int {
val input = readInput("day4.txt") ?: return -1
return getRanges(input).fold(0) { acc, (left, right) ->
if (left.overlaps(right)) acc + 1
else acc
}
}
private fun getRanges(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map { s ->
val (l, r) = s.split(",")
val (lf, ls) = l.split("-")
val (rf, rs) = r.split("-")
IntRange(lf.toInt(), ls.toInt()) to IntRange(rf.toInt(), rs.toInt())
}
}
private fun IntRange.contains(range: IntRange): Boolean {
return this.first <= range.first && this.last >= range.last
}
fun IntRange.overlaps(range: IntRange): Boolean {
val lb = max(this.first, range.first)
val rb = min(this.last, range.last)
if (rb < lb) return false
val overlap = IntRange(lb, rb)
return this.contains(overlap) && range.contains(overlap)
} | 0 | Kotlin | 0 | 0 | 549f255f18b35e5f52ebcd030476993e31185ad3 | 1,256 | aoc-2022 | Apache License 2.0 |
src/Day01.kt | lukewalker128 | 573,611,809 | false | {"Kotlin": 14077} | fun main() {
/**
* Returns the maximum number of calories held by a single elf.
*/
fun part1(calories: List<Int>): Int {
return calories.max()
}
/**
* Returns the total number of calories held by the three elves carrying the most calories.
*/
fun part2(calories: List<Int>): Int {
// Instead of sorting the entire list it would be more efficient to scan the list and store the largest elements
// in a heap of size 3, but the input size isn't large enough to warrant this.
return calories.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
val testCalories = testInput.toCalories()
check(part1(testCalories) == 24_000)
check(part2(testCalories) == 45_000)
val input = readInput("Day01")
val calories = input.toCalories()
println("Part 1: ${part1(calories)}")
println("Part 2: ${part2(calories)}")
}
private fun List<String>.toCalories(): List<Int> {
val calories = mutableListOf<Int>()
var i = 0
while (i < this.size) {
// consume input up to the next blank line or until we reach the end of the file
var count = 0
while (i < this.size && this[i].isNotBlank()) {
count += this[i].toInt()
i++
}
calories.add(count)
// skip over any blank lines in the input
while (i < this.size && this[i].isBlank()) {
i++
}
}
return calories
}
| 0 | Kotlin | 0 | 0 | c1aa17de335bd5c2f5f555ecbdf39874c1fb2854 | 1,584 | advent-of-code-2022 | Apache License 2.0 |
src/test/java/quam/features/SimonsProblemFeature.kt | johnhearn | 149,781,062 | false | null | package quam.features
import org.junit.jupiter.api.Test
import quam.*
import java.util.*
import kotlin.test.assertEquals
/**
* The problem is that given a mapping
*
* f : (List<Boolean>) -> List<Boolean>
*
* (as a black box) with the added property that there is a special value, s, such
* that f(x) = f(x xor s) for all x, then find what s is.
*
* Take, for example, the 3-bit case where s = 011. So
* f(000) = f(011) = 010
* f(100) = f(111) = 110
* f(001) = f(010) = 101
* f(101) = f(110) = 001
* (https://www.cs.vu.nl/~tcs/ac/ac-11_simon_algorithm.pdf)
*/
class SimonsProblemFeature {
private val random = Random(35L)
@Test
fun `identity function evaluates to 0^n`() {
assertEquals(0b000, simonsProblem(3) { it })
}
@Test
fun `3-bit case in comment s=011`() {
// Worked example (s=011) from here - https://www.cs.vu.nl/~tcs/ac/ac-11_simon_algorithm.pdf
val fppt = mapping(
0b000 to 0b010, 0b011 to 0b010,
0b100 to 0b110, 0b111 to 0b110,
0b001 to 0b101, 0b010 to 0b101,
0b101 to 0b001, 0b110 to 0b001)
assertEquals(0b011, simonsProblem(3, fppt))
}
@Test
fun `3-bit case in wikipedia s=110`() {
// Wikipedia example (s=110) from here - https://en.wikipedia.org/wiki/Simon%27s_problem#Example
val fWiki = mapping(
0b000 to 0b101,
0b001 to 0b010,
0b010 to 0b000,
0b011 to 0b110,
0b100 to 0b000,
0b101 to 0b110,
0b110 to 0b101,
0b111 to 0b010)
assertEquals(0b110, simonsProblem(3, fWiki))
}
private fun simonsProblem(n: Int, f: (Int) -> Int): Int {
val oracle = oracle(n, n) { x, y -> f(x) xor y }
val ys = (0..n*2).map { y(n, oracle) }
.filter { it != listOf(false, false, false) }
.distinct()
println(ys.map { format(it.toInt(), n)})
// "Solve" by going through possibilities for s and checking xor_sum of y*s is 0 for all y
for(s in (1 until pow2(n))) {
if(ys.map { it.toInt() }
.map { it and s }
.map {
// xor over i of (y_i * s_i)
(0..n).fold(0) { acc, i ->
acc xor ((it ushr i and 1) * (s ushr i and 1))
}
}
.all { it == 0 })
return s
}
return 0
}
fun y(n: Int, oracle: ComplexMatrix): List<Boolean> {
return Qubits(n, random)
.hadamard(0 until n)
.ancillary(n)
.apply(0, oracle)
//.measureLast(width)
.hadamard(0 until n)
.measureFirst(n)
}
private fun format(x: Int, width: Int) = x.toByte().toString(2).padStart(width, '0')
}
| 1 | Kotlin | 0 | 1 | 4215d86e7afad97b803ce850745920b63f75a0f9 | 2,975 | quko | MIT License |
codeforces/round614/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round614
fun main() {
readLn()
val a = readInts()
val aCount = a.groupBy { it }.mapValues { it.value.size }
var b = aCount.keys.toList()
val (primes, factPrimes) = List(2) { MutableList(2) { listOf<Int>() } }
for (i in 2..b.maxOrNull()!!) {
val j = (2..i).first { i % it == 0 }
primes.add(primes[i / j].plus(j))
factPrimes.add(factPrimes[i - 1].plus(primes[i]).sortedDescending())
}
var ans = aCount.map { factPrimes[it.key].size * 1L * it.value }.sum()
for (x in factPrimes.last().indices) {
val groups = b.groupBy { factPrimes[it].getOrNull(x) }
val win = groups.mapValues { entry -> 2 * entry.value.sumOf { aCount.getValue(it) } - a.size }
val p = win.entries.firstOrNull { it.value > 0 }?.key ?: break
ans -= win.getValue(p)
b = groups.getValue(p)
}
println(ans)
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 959 | competitions | The Unlicense |
src/main/kotlin/com/danielmichalski/algorithms/data_structures/_12_dijkstra_algorithm/WeightedGraph.kt | DanielMichalski | 288,453,885 | false | {"Kotlin": 101963, "Groovy": 19141} | package com.danielmichalski.algorithms.data_structures._12_dijkstra_algorithm
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class WeightedGraph {
private val adjacencyList: MutableList<Node> = ArrayList()
fun addVertex(vertex: String) {
val node = findNode(vertex)
if (node == null) {
val newNode = Node(vertex, mutableListOf())
this.adjacencyList.add(newNode)
}
}
fun addEdge(vertex1: String, vertex2: String, weight: Int) {
val node1 = findNode(vertex1)
val node2 = findNode(vertex2)
val connection1 = Connection(vertex1, weight)
val connection2 = Connection(vertex2, weight)
node1!!.getConnections().add(connection2)
node2!!.getConnections().add(connection1)
}
fun dijkstra(start: String, finish: String): List<String> {
val compareByWeight: Comparator<QueueNode> = compareBy { it.getPriority() }
val nodesQueue = PriorityQueue(compareByWeight)
val path: MutableList<String> = ArrayList()
val distances = HashMap<String, Int>(adjacencyList.size)
val previous = HashMap<String, String?>(adjacencyList.size)
var smallest: String
for (vertexNode in adjacencyList) {
val vertex = vertexNode.getVertex()
if (vertex == start) {
distances[vertex] = 0
val queueNode = QueueNode(vertex, 0)
nodesQueue.add(queueNode)
} else {
distances[vertex] = Int.MAX_VALUE
val queueNode = QueueNode(vertex, Int.MAX_VALUE)
nodesQueue.add(queueNode)
}
previous[vertex] = null
}
while (nodesQueue.size > 0) {
smallest = nodesQueue.poll().getValue()
if (smallest === finish) {
while (previous[smallest] != null) {
path.add(smallest)
smallest = previous[smallest]!!
}
break
}
if (distances[smallest] != Int.MAX_VALUE) {
val node = adjacencyList.first { vertexNode -> vertexNode.getVertex() === smallest }
for (neighbor in node.getConnections()) {
val candidate = distances[smallest]?.plus(neighbor.getWeight())
val nextNeighbor = neighbor.getVertex()
if (candidate!! < distances[nextNeighbor]!!) {
distances[nextNeighbor] = candidate
previous[nextNeighbor] = smallest
val queueNode = QueueNode(nextNeighbor, candidate)
nodesQueue.add(queueNode)
}
}
}
}
return path
}
override fun toString(): String {
return "UndirectedGraph(adjacencyList='$adjacencyList')\n"
}
private fun findNode(vertex: String): Node? {
return adjacencyList.stream()
.filter { node -> node.getVertex() == vertex }
.findFirst()
.orElse(null)
}
}
| 0 | Kotlin | 1 | 7 | c8eb4ddefbbe3fea69a172db1beb66df8fb66850 | 3,170 | algorithms-and-data-structures-in-kotlin | MIT License |
src/Day07.kt | timmiller17 | 577,546,596 | false | {"Kotlin": 44667} | fun main() {
fun part1(input: List<String>): Int {
val root = DirectoryNode(value = "/")
var currentDirectory = root
outerLoop@ for ((index, line) in input.withIndex()) {
// println("index:$index $line")
if (line.startsWith("$ cd ..")) {
currentDirectory = currentDirectory.parent!!
} else if (line.startsWith("$ cd")) {
val destinationDirectory = line.substring(5)
if (destinationDirectory == currentDirectory.value) {
continue
} else {
for (subdirectory in currentDirectory.directories) {
if (subdirectory.value == destinationDirectory) {
currentDirectory = subdirectory
continue@outerLoop
}
}
throw IllegalStateException("Directory $destinationDirectory does not exist in location ${currentDirectory.value}")
}
} else if (line.startsWith("$ ls")) {
continue
} else if (line.startsWith("dir")) {
currentDirectory.directories.add(
DirectoryNode(
parent = currentDirectory,
value = line.substring(4)
)
)
} else {
val spaceIndex = line.indexOf(" ")
currentDirectory.files.add(
MyFile(
size = line.substring(0, spaceIndex).toInt(),
name = line.substring(spaceIndex + 1)
)
)
}
}
val fileSystemSize = root.totalSize()
val limitedFileSystemSize = root.sumOfDirectoriesUnderLimit(100000)
return limitedFileSystemSize
}
fun part2(input: List<String>): Int {
val root = DirectoryNode(value = "/")
var currentDirectory = root
outerLoop@ for ((index, line) in input.withIndex()) {
// println("index:$index $line")
if (line.startsWith("$ cd ..")) {
currentDirectory = currentDirectory.parent!!
} else if (line.startsWith("$ cd")) {
val destinationDirectory = line.substring(5)
if (destinationDirectory == currentDirectory.value) {
continue
} else {
for (subdirectory in currentDirectory.directories) {
if (subdirectory.value == destinationDirectory) {
currentDirectory = subdirectory
continue@outerLoop
}
}
throw IllegalStateException("Directory $destinationDirectory does not exist in location ${currentDirectory.value}")
}
} else if (line.startsWith("$ ls")) {
continue
} else if (line.startsWith("dir")) {
currentDirectory.directories.add(
DirectoryNode(
parent = currentDirectory,
value = line.substring(4)
)
)
} else {
val spaceIndex = line.indexOf(" ")
currentDirectory.files.add(
MyFile(
size = line.substring(0, spaceIndex).toInt(),
name = line.substring(spaceIndex + 1)
)
)
}
}
val availableSpace = 70000000 - root.totalSize()
val spaceToFree = 30000000 - availableSpace
val listOfDirectorySizes = mutableListOf<Int>()
root.listDirectorySizes(listOfDirectorySizes)
return listOfDirectorySizes.sorted().first { it > spaceToFree }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
part1(input).println()
part2(input).println()
}
data class DirectoryNode(
val value: String,
val parent: DirectoryNode? = null,
var files: MutableList<MyFile> = mutableListOf(),
) {
var directories: MutableList<DirectoryNode> = mutableListOf()
}
data class MyFile(
val size: Int,
val name: String,
)
fun DirectoryNode.totalSize(): Int {
return this.files.sumOf { it.size } + this.directories.sumOf { it.totalSize() }
}
fun DirectoryNode.sumOfDirectoriesUnderLimit(limit: Int): Int {
val size = this.totalSize()
return (if (size <= limit) size else 0) + this.directories.sumOf { it.sumOfDirectoriesUnderLimit(limit) }
}
fun DirectoryNode.listDirectorySizes(list: MutableList<Int>, includeThis: Boolean = true) {
if (includeThis) {
list.add(this.totalSize())
}
this.directories.forEach {
list.add(it.totalSize())
it.listDirectorySizes(list, false)
}
} | 0 | Kotlin | 0 | 0 | b6d6b647c7bb0e6d9e5697c28d20e15bfa14406c | 5,087 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | jalex19100 | 574,686,993 | false | {"Kotlin": 19795} | import kotlin.math.abs
fun main() {
class Coordinate(val x: Int, val y: Int) {
fun moveRight(): Coordinate = Coordinate(x+1, y)
fun moveLeft(): Coordinate = Coordinate(x-1, y)
fun moveUp(): Coordinate = Coordinate(x, y+1)
fun moveDown(): Coordinate = Coordinate(x, y-1)
}
class Rope(var headPosition: Coordinate, var tailPosition: Coordinate) {
fun move(direction: Char, numberOfSteps: Int): Coordinate {
var newHeadPosition = headPosition
repeat(numberOfSteps) {
when (direction) {
'R' -> newHeadPosition = newHeadPosition.moveRight()
'L' -> newHeadPosition = newHeadPosition.moveLeft()
'U' -> newHeadPosition = newHeadPosition.moveUp()
'D' -> newHeadPosition = newHeadPosition.moveDown()
}
tailPosition = moveTail(newHeadPosition, tailPosition)
}
}
fun moveTail(headPosition: Coordinate, tailPosition: Coordinate):Coordinate {
val xDiff = headPosition.x - tailPosition.y
val yDiff = headPosition.y - tailPosition.y
if (abs(xDiff) > 1 || abs(yDiff) > 1) {
when(tailPosition.compareTo(headPosition)) {
-1 ->
}
}
}
}
fun part1(input: List<String>): Int {
val rope = Rope
input.forEach { line ->
val (direction, count) = line.split(' ')
rope.mo
}
return input.size
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
// check(part1(testInput) == 1)
println(part1(testInput))
val input = readInput("Day09")
// println(part1(input))
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a50639447a2ef3f6fc9548f0d89cc643266c1b74 | 1,938 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/hjk/advent22/Day08.kt | h-j-k | 572,485,447 | false | {"Kotlin": 26661, "Racket": 3822} | package com.hjk.advent22
object Day08 {
fun part1(input: List<String>): Int =
input.pointIndices().count { point ->
point.x in setOf(0, input[0].lastIndex) || point.y in setOf(0, input.lastIndex) || setOf(
input leftOf point,
input rightOf point,
input topOf point,
input bottomOf point
).any { points -> points.all { it < input[point] } }
}
fun part2(input: List<String>): Int =
input.pointIndices().maxOf { point ->
val heights = (input[point]..'9').toSet().toCharArray()
mapOf(
(input leftOf point).reversed() to point.x,
(input rightOf point) to (input[0].length - point.x - 1),
(input topOf point).reversed() to point.y,
(input bottomOf point) to (input.size - point.y - 1)
).map { (side, default) -> (side.indexOfAny(heights) + 1).takeIf { it >= 1 } ?: default }.reduce(Int::times)
}
private infix fun List<String>.leftOf(p: Point2d) = this[p.y].substring(0, p.x)
private infix fun List<String>.rightOf(p: Point2d) = this[p.y].substring(p.x + 1)
private infix fun List<String>.topOf(p: Point2d) = (0 until p.y).column(this, p)
private infix fun List<String>.bottomOf(p: Point2d) = ((p.y + 1) until this.size).column(this, p)
private fun IntRange.column(input: List<String>, p: Point2d) = joinToString("") { input[it][p.x].toString() }
}
| 0 | Kotlin | 0 | 0 | 20d94964181b15faf56ff743b8646d02142c9961 | 1,495 | advent22 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1254/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1254
/**
* LeetCode page: [1254. Number of Closed Islands](https://leetcode.com/problems/number-of-closed-islands/);
*/
class Solution {
/* Complexity:
* Time O(MN) and Space O(MN) where M and N are the number of rows and columns of grid;
*/
fun closedIsland(grid: Array<IntArray>): Int {
var numClosedIslands = 0
visitAllIslands(grid) { isClosed ->
if (isClosed) numClosedIslands++
}
return numClosedIslands
}
private fun visitAllIslands(
grid: Array<IntArray>,
onEachIsland: (isClosed: Boolean) -> Unit
) {
val numRows = grid.size
val numColumns = grid[0].size
val visited = Array(numRows) { BooleanArray(numColumns) }
for (row in grid.indices) {
for (column in grid[row].indices) {
val cell = Cell(row, column)
if (cell.isUnvisitedLand(grid, visited)) {
var isClosedIsland = true
visitAllConnectedUnvisitedLands(cell, grid, visited) { isOnBoundary ->
if (isOnBoundary) isClosedIsland = false
}
onEachIsland(isClosedIsland)
}
}
}
}
private data class Cell(val row: Int, val column: Int)
private fun Cell.isUnvisitedLand(grid: Array<IntArray>, visited: Array<BooleanArray>): Boolean {
return isWithinBounds(grid) && isLand(grid[row][column]) && !visited[row][column]
}
private fun Cell.isWithinBounds(grid: Array<IntArray>): Boolean {
return row in grid.indices && column in grid[row].indices
}
private fun isLand(gridValue: Int): Boolean = gridValue == 0
private fun visitAllConnectedUnvisitedLands(
source: Cell,
grid: Array<IntArray>,
visited: Array<BooleanArray>,
onEachLand: (isOnBoundary: Boolean) -> Unit
) {
if (source.isUnvisitedLand(grid, visited)) {
onEachLand(source.isOnBoundary(grid))
val (row, column) = source
visited[row][column] = true
visitAllConnectedUnvisitedLands(Cell(row + 1, column), grid, visited, onEachLand)
visitAllConnectedUnvisitedLands(Cell(row - 1, column), grid, visited, onEachLand)
visitAllConnectedUnvisitedLands(Cell(row, column + 1), grid, visited, onEachLand)
visitAllConnectedUnvisitedLands(Cell(row, column - 1), grid, visited, onEachLand)
}
}
private fun Cell.isOnBoundary(grid: Array<IntArray>): Boolean {
return row == 0 || row == grid.lastIndex || column == 0 || column == grid[row].lastIndex
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,703 | hj-leetcode-kotlin | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day08.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year21
import com.grappenmaker.aoc.PuzzleSet
import kotlin.math.pow
// Maps segments count to the number (we do be lazy)
val knownLengths = mapOf(1 to 2, 7 to 3, 4 to 4, 8 to 7)
fun PuzzleSet.day8() = puzzle(day = 8) {
// Part one
val data = inputLines.map { it.split(" | ") }
// All lengths we know
partOne = data.sumOf { it[1].split(" ").count { e -> e.length in knownLengths.values } }.s()
// Part two
partTwo = data.map { line ->
// 97 isn't magic: it's equivalent to 'a'.code
val remap: (String) -> Set<Int> = { seg -> seg.map { it.code - 97 }.toSet() }
line.first().split(" ").map(remap) to line[1].split(" ").map(remap)
}.sumOf {
val mapping = getMapping(it.first)
it.second.foldIndexed(0) { idx, acc, value ->
acc + mapping.getValue(value) * 10.0.pow((it.second.size - idx - 1).toDouble()).toInt()
}.toInt()
}.s()
}
// Lot of magic going on here
private fun getMapping(segments: List<Set<Int>>): Map<Set<Int>, Int> {
// Initialize mapping
val mapping = mutableMapOf<Int, Set<Int>>()
// Get the ones we "know"
// Again, lazy... or smart??
knownLengths.forEach { (k, v) -> mapping[k] = segments.first { it.size == v } }
// Util for convenience
val mapDigit = { digit: Int, size: Int, condition: (Set<Int>) -> Boolean ->
mapping[digit] = segments.first { it.size == size && condition(it) }
}
// Map digit 3 (has size of 5 and should overlap with 1)
mapDigit(3, 5) { it overlays mapping.getValue(1) }
// Map digit 9 (has size of 6 and should overlap with 3)
mapDigit(9, 6) { it overlays mapping.getValue(3) }
// Map digit 0 (has size of 6 and should overlap with 1 and 7, and is not nine)
mapDigit(0, 6) { it overlays mapping.getValue(1) && it overlays mapping.getValue(7) && it != mapping[9] }
// Map digit 6 (has size of 6 and should NOT overlay with 0 or 9 at all)
mapDigit(6, 6) { it != mapping[0] && it != mapping[9] }
// Map digit 5 (has size of 5 and 6 should overlap with it)
mapDigit(5, 5) { mapping.getValue(6) overlays it }
// Map digit 2 (has size of 5 and should NOT overlay with 3 or 5 at all)
mapDigit(2, 5) { it != mapping[3] && it != mapping[5] }
// Invert the mapping, again because im a lazy f*ck and ive spent way
// too much time on this puzzle.
return mapping.map { it.value to it.key }.toMap()
}
// Probably a little bit cleaner
private infix fun <T> Set<T>.overlays(other: Set<T>) = this.containsAll(other) | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,566 | advent-of-code | The Unlicense |
gcj/y2023/farewell_d/d_small.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2023.farewell_d
private fun solve(): Modular {
val s = readLn()
val dp = ModularArray(s.length) { 0.toModularUnsafe() }
var ans = 0.toModularUnsafe()
for (i in s.indices) {
if (s[i] !in ".o") continue
if (s.take(i).all { it in ".>" }) dp[i] = 1.toModularUnsafe()
for (j in 0 until i) {
var good = true
if (s[j] !in ".o") continue
for (k in j+1 until i) {
val desired = if (2 * k == i + j) '=' else if (2 * k < i + j) '<' else '>'
if (s[k] != desired && s[k] != '.') good = false
}
if (good) dp[i] += dp[j]
}
if (s.drop(i + 1).all { it in ".<" }) ans += dp[i]
}
return ans
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
//typealias Modular = Double; fun Number.toModular() = toDouble(); fun Number.toModularUnsafe() = toDouble()
//typealias ModularArray = DoubleArray; val ModularArray.data; get() = this
@JvmInline
@Suppress("NOTHING_TO_INLINE")
private value class Modular(val x: Int) {
companion object {
const val M = 1000000007; val MOD_BIG_INTEGER = M.toBigInteger()
}
inline operator fun plus(that: Modular) = Modular((x + that.x).let { if (it >= M) it - M else it })
inline operator fun minus(that: Modular) = Modular((x - that.x).let { if (it < 0) it + M else it })
inline operator fun times(that: Modular) = Modular((x.toLong() * that.x % M).toInt())
inline operator fun div(that: Modular) = times(that.inverse())
inline fun inverse() = Modular(x.toBigInteger().modInverse(MOD_BIG_INTEGER).toInt())
override fun toString() = x.toString()
}
private fun Int.toModularUnsafe() = Modular(this)
private fun Int.toModular() = Modular(if (this >= 0) { if (this < Modular.M) this else this % Modular.M } else { Modular.M - 1 - inv() % Modular.M })
private fun Long.toModular() = Modular((if (this >= 0) { if (this < Modular.M) this else this % Modular.M } else { Modular.M - 1 - inv() % Modular.M }).toInt())
private fun java.math.BigInteger.toModular() = Modular(mod(Modular.MOD_BIG_INTEGER).toInt())
private fun String.toModular() = Modular(fold(0L) { acc, c -> (c - '0' + 10 * acc) % Modular.M }.toInt())
@JvmInline
private value class ModularArray(val data: IntArray) {
operator fun get(index: Int) = data[index].toModularUnsafe()
operator fun set(index: Int, value: Modular) { data[index] = value.x }
}
private inline fun ModularArray(n: Int, init: (Int) -> Modular) = ModularArray(IntArray(n) { init(it).x })
private val factorials = mutableListOf(1.toModularUnsafe())
private fun factorial(n: Int): Modular {
while (n >= factorials.size) factorials.add(factorials.last() * factorials.size.toModularUnsafe())
return factorials[n]
}
private fun cnk(n: Int, k: Int) = factorial(n) / factorial(k) / factorial(n - k)
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,905 | competitions | The Unlicense |
src/Day13.kt | ZiomaleQ | 573,349,910 | false | {"Kotlin": 49609} | fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (i in 0..(input.size / 3)) {
val leftPacket = Packet.parse(input[(i * 3)])
val rightPacket = Packet.parse(input[(i * 3) + 1])
val inOrder = leftPacket.rightOrder(rightPacket)
if (inOrder) sum += (i + 1)
}
return sum
}
fun part2(input: List<String>): Int {
val packets = mutableListOf<Packet>()
for (i in 0..(input.size / 3)) {
Packet.parse(input[(i * 3)]).also { packets.add(it) }
Packet.parse(input[(i * 3) + 1]).also { packets.add(it) }
}
val first = Packet.parse("[[2]]").also { packets.add(it) }
val second = Packet.parse("[[6]]").also { packets.add(it) }
packets.sort()
return packets.indexOf(first).inc() * packets.indexOf(second).inc()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
part1(testInput).also { println(it); check(it == 13) }
part2(testInput).also { println(it); check(it == 140) }
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private data class Packet(val elements: List<CodeNode>) : Comparable<Packet> {
fun rightOrder(right: Packet): Boolean {
for ((index, elt) in elements.withIndex()) {
val rightElt = right.elements.getOrNull(index) ?: return false
if (elt is NumberNode && rightElt is NumberNode) {
if (elt == rightElt) continue
return elt < rightElt
} else {
return if (elt is ArrayNode && rightElt is ArrayNode) {
val comp = elt.compare(rightElt)
if (comp == 0) continue
else comp == -1
} else {
val enclosedLeft = if (elt is NumberNode) ArrayNode(mutableListOf(elt)) else elt
val enclosedRight = if (rightElt is NumberNode) ArrayNode(mutableListOf(rightElt)) else rightElt
val comp = (enclosedLeft as ArrayNode).compare(enclosedRight as ArrayNode)
if (comp == 0) continue
else comp == -1
}
}
}
return true
}
override fun compareTo(other: Packet): Int {
for ((index, elt) in elements.withIndex()) {
val rightElt = other.elements.getOrNull(index) ?: return 1
if (elt is NumberNode && rightElt is NumberNode) {
if (elt == rightElt) continue
return if (elt < rightElt) -1 else 1
} else {
return if (elt is ArrayNode && rightElt is ArrayNode) {
val comp = elt.compare(rightElt)
if (comp == 0) continue
else comp
} else {
val enclosedLeft = if (elt is NumberNode) ArrayNode(mutableListOf(elt)) else elt
val enclosedRight = if (rightElt is NumberNode) ArrayNode(mutableListOf(rightElt)) else rightElt
val comp = (enclosedLeft as ArrayNode).compare(enclosedRight as ArrayNode)
if (comp == 0) continue
else comp
}
}
}
return when (elements.size) {
other.elements.size -> 0
else -> elements.size - other.elements.size
}
}
companion object {
fun parse(string: String): Packet {
val tokens = Tokenizer(string).tokenizeCode()
return Packet(
Parser(tokens).parse().let { if (it[0] is ArrayNode) (it[0] as ArrayNode).nodes else listOf(it[0]) })
}
}
override fun toString() = "[${elements.joinToString()}]"
}
//Taken from parts heh
private class Tokenizer(private val code: String) {
private var rules: MutableList<Rule> = mutableListOf(
Rule(true, "OPERATOR", "[],"),
Rule(false, "NUMBER", "[0-9]"),
)
private var current = 0
fun tokenizeCode(): MutableList<Token> {
val code = this.code.toCharArray()
val tokens = mutableListOf<Token>()
val rulesLocal = rules.groupBy { it.isSingle }
while (current < code.size) {
var found = false
var expr: String
for (rule in rulesLocal[true] ?: listOf()) {
if (found) break
if (rule.rule.toCharArray().find { it == peek() } != null) {
found = tokens.add(Token(rule.name, "${peekNext()}", 1))
break
}
}
for (rule in rulesLocal[false] ?: listOf()) {
if (found) break
if (rule.test(code[current])) {
expr = code[current++].toString().also { found = true }
while (current < code.size && rule.test(peek())) expr = "$expr${peekNext()}"
tokens.add(Token(rule.name, expr, expr.length))
}
}
if (!found) current++
}
return tokens.map { it.parse() }.toMutableList()
}
private fun peek(): Char = code[current]
private fun peekNext(): Char = code[current++]
private data class Rule(var isSingle: Boolean, var name: String, var rule: String) {
override fun toString(): String = "[ $isSingle, '$name', /$rule/ ]"
fun test(check: Any): Boolean = rule.toRegex(RegexOption.IGNORE_CASE).matches("$check")
}
}
private data class Token(var type: String, var value: String, val length: Int) {
private var parsed: Boolean = false
override fun toString(): String = "Token of type $type with value $value"
fun parse(): Token {
if (parsed) return this
val operators = mapOf(
',' to "COMMA",
'[' to "LEFT_BRACKET",
']' to "RIGHT_BRACKET"
)
when (type) {
"OPERATOR" -> type = operators[value[0]] ?: "ERROR-XD"
}
return this.also { parsed = true }
}
}
private class Parser(private val code: MutableList<Token>) {
private var lastToken: Token = Token("x", "x", 0)
private var tokens: MutableList<CodeNode> = mutableListOf()
fun parse(): MutableList<CodeNode> {
lastToken = getEOT()
try {
while (code.size != 0) {
tokens.add(primary())
}
} catch (err: Error) {
println(code.take(2))
println(err.message)
}
return tokens
}
private fun primary(): CodeNode = when {
match("LEFT_BRACKET") -> {
val list = mutableListOf<CodeNode>()
if (peek().type != "RIGHT_BRACKET") {
do {
list.add(primary())
} while (match("COMMA"))
}
advance()
ArrayNode(list)
}
match("NUMBER", "STRING") -> NumberNode(lastToken.value.toInt())
else -> error("Expected expression. Got ${peek().value}")
}
private fun match(vararg types: String): Boolean = if (peek().type in types) true.also { advance() } else false
private fun advance(): Token = code.removeFirst().also { lastToken = it }
private fun error(message: String): Nothing = throw Error(message)
private fun peek(): Token = if (code.size > 0) code[0] else getEOT()
private fun getEOT(): Token = Token("EOT", "EOT", 3)
}
private sealed interface CodeNode
private data class ArrayNode(val nodes: MutableList<CodeNode>) : CodeNode {
//- 1 left side, 0, middle, 1 right side
fun compare(other: ArrayNode): Int {
for ((index, leftElt) in nodes.withIndex()) {
val rightElt = other.nodes.getOrNull(index) ?: return 1
if (leftElt is NumberNode && rightElt is NumberNode) {
if (leftElt == rightElt) continue
else return if (leftElt < rightElt) -1 else 1
}
if (leftElt is ArrayNode && rightElt is ArrayNode) {
val comp = leftElt.compare(rightElt)
if (comp == 0) continue
else return comp
}
val enclosedLeft = if (leftElt is NumberNode) ArrayNode(mutableListOf(leftElt)) else leftElt
val enclosedRight = if (rightElt is NumberNode) ArrayNode(mutableListOf(rightElt)) else rightElt
val comp = (enclosedLeft as ArrayNode).compare(enclosedRight as ArrayNode)
if (comp == 0) continue
else return comp
}
return when (nodes.size) {
other.nodes.size -> 0
else -> nodes.size - other.nodes.size
}
}
override fun toString() = "[${nodes.joinToString()}]"
}
private data class NumberNode(val int: Int) : CodeNode, Comparable<NumberNode> {
override fun compareTo(other: NumberNode): Int =
this.int.compareTo(other.int)
override fun toString() = int.toString()
} | 0 | Kotlin | 0 | 0 | b8811a6a9c03e80224e4655013879ac8a90e69b5 | 9,035 | aoc-2022 | Apache License 2.0 |
src/Day11/day11.kt | NST-d | 573,224,214 | false | null | package Day11
import utils.*
operator fun <T> List<T>.component6() = this[5]
class Monkey(
var worryLevels: MutableList<Long>,
val operation: (Long) -> Long,
val testCondition: Long,
val passTo: Pair<Int, Int>,
val updateMonkey: (Int, Long) -> Unit
) {
var limiter = 1L
var inspectingCounter = 0L
fun Update() {
worryLevels
.map { operation(it) }
.map { it%limiter }
.forEach {
inspectingCounter++
if (it % testCondition == 0L) {
updateMonkey(passTo.first, it)
} else {
updateMonkey(passTo.second, it)
}
}
worryLevels = emptyList<Long>().toMutableList()
}
}
fun parseMonkeys(input: String): List<Monkey>{
val monkeyText = input.split("\n\n")
lateinit var monkeys: List<Monkey>
fun updateMonkey(index: Int, element: Long) {
monkeys[index].worryLevels.add(element)
}
monkeys = List(monkeyText.size) {
val (monkey, start, operationString, testString, passTrue, passFalse) = monkeyText[it].split("\n")
val itemWorryLevels = start.substring(18)
.split(", ")
.map { it.toLong() }.toMutableList()
val operationArgument = operationString.substring(25)
val operation = when (operationString[23]) {
'+' -> { x: Long ->
x + if (operationArgument == "old") {
x
} else {
operationArgument.toLong()
}
}
'-' -> { x: Long ->
x - if (operationArgument == "old") {
x
} else {
operationArgument.toLong()
}
}
'*' -> { x: Long ->
x * if (operationArgument == "old") {
x
} else {
operationArgument.toLong()
}
}
'/' -> { x: Long ->
x / if (operationArgument == "old") {
x
} else {
operationArgument.toLong()
}
}
else -> error("Unkown operation: $operationString")
}
val testCompare = testString.substring(21).toLong()
val passTo = Pair(
passTrue.split(" ").last().toInt(),
passFalse.split(" ").last().toInt()
)
Monkey(itemWorryLevels, operation, testCompare, passTo) { i, e -> updateMonkey(i, e) }
}
return monkeys
}
fun main() {
fun part1(input: String): Long {
val monkeys = parseMonkeys(input)
monkeys.forEach { it.limiter = 3 }
val print =
// listOf(1,20,1000,2000,3000,4000,5000,6000,7000,8000,9000,10_000)
emptyList<Int>()
println(monkeys.map { it.worryLevels })
for( i in 1..20){
monkeys.forEach { it.Update() }
if (print.contains(i)) {
println(monkeys.map { it.inspectingCounter })
println(monkeys.map { it.worryLevels })
println()
}
}
return monkeys.map { it.inspectingCounter }
//max 2
.sortedDescending().take(2)
.fold(1L) { acc, t -> acc * t }
}
fun part2(input: String): Long {
val monkeys = parseMonkeys(input)
val limiter = monkeys.map { it.testCondition }.fold(1L) {acc, t -> acc* t}
monkeys.forEach { it.limiter = limiter }
val print =
// listOf(1,20,1000,2000,3000,4000,5000,6000,7000,8000,9000,10_000)
emptyList<Int>()
println(monkeys.map { it.worryLevels })
for( i in 1..10_000){
monkeys.forEach { it.Update() }
if (print.contains(i)) {
println(monkeys.map { it.inspectingCounter })
println(monkeys.map { it.worryLevels })
println()
}
}
return monkeys.map { it.inspectingCounter }
//max 2
.sortedDescending().take(2)
.fold(1L) { acc, t -> acc * t }
}
val test = readTestString("Day11").trimIndent()
val input = readInputString("Day11").trimIndent()
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c4913b488b8a42c4d7dad94733d35711a9c98992 | 4,348 | aoc22 | Apache License 2.0 |
src/test/kotlin/Day10.kt | christof-vollrath | 317,635,262 | false | null | import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.lang.IllegalStateException
/*
--- Day 10: Adapter Array ---
See https://adventofcode.com/2020/day/10
*/
fun Set<Int>.findAdapterChain(start: Int): List<Pair<Int, Int>> {
val currentSet = this.toMutableSet()
var currentJolts = start
return sequence {
while(currentSet.isNotEmpty()) {
val nextJolts = findJoltageCandidates(currentJolts).intersect(currentSet).minOrNull() ?: throw IllegalStateException("No adapter for $currentJolts")
yield(nextJolts - currentJolts to nextJolts)
currentSet -= nextJolts
currentJolts = nextJolts
}
yield(3 to currentJolts + 3)
}.toList()
}
fun parseAdapters(numbersString: String) =
numbersString.split("\n").map{ it.toInt() }
fun findJoltageCandidates(jolts: Int): Set<Int> = (1..3).map { jolts + it }.toSet()
fun Set<Int>.findAlternatives(): List<Pair<Int, Set<Int>>> {
val adapters = this + setOf(0)
val sortedAdapters = adapters.sorted()
return sequence {
for(currentAdapter in sortedAdapters) {
val nextAdapters = findJoltageCandidates(currentAdapter).intersect(this@findAlternatives)
yield(currentAdapter to nextAdapters)
}
}.toList()
}
fun findJoltageCandidatesBackwards(jolts: Int): Set<Int> = (1..3).map { jolts - it }.toSet()
fun Set<Int>.findAlternativesBackwards(): Map<Int, Set<Int>> {
val adapters = this + setOf(0)
val sortedAdapters = this.sorted()
return sequence {
for(currentAdapter in sortedAdapters) {
val nextAdapters = findJoltageCandidatesBackwards(currentAdapter).intersect(adapters)
yield(currentAdapter to nextAdapters)
}
}.toMap()
}
fun Set<Int>.findCombinations(): List<Pair<Long, Int>> {
val reachableFrom = findAlternativesBackwards().toMap()
val numberOfCombinationsPerAdapter = linkedMapOf<Int, Long>(0 to 1)
for(adapter in this.sorted()) {
if (adapter == 0) continue
val adapterReachableFrom = reachableFrom[adapter] ?: throw IllegalStateException("Adapter $adapter can't be reached")
val numberOfCombinations = adapterReachableFrom.map { from ->
numberOfCombinationsPerAdapter[from] ?: throw IllegalStateException("Unknown combinations for $from")
}.sum()
numberOfCombinationsPerAdapter[adapter] = numberOfCombinations
}
return numberOfCombinationsPerAdapter.entries.map { it.value to it.key }
}
fun Set<Int>.findCombinationsDeprecated(): List<Pair<Long, Int>> {
val alternatives = findAlternatives()
val reachableFrom = alternatives.invertConnections()
val numberOfCombinationsPerAdapter = linkedMapOf(0 to 1L)
for(adapter in this.sorted()) {
if (adapter == 0) continue
val adapterReachableFrom = reachableFrom[adapter] ?: throw IllegalStateException("Adapter $adapter can't be reached")
val numberOfCombinations = adapterReachableFrom.map { from ->
numberOfCombinationsPerAdapter[from] ?: throw IllegalStateException("Unknown combinations for $from")
}.sum()
numberOfCombinationsPerAdapter[adapter] = numberOfCombinations
}
return numberOfCombinationsPerAdapter.entries.map { it.value to it.key }
}
fun List<Pair<Int, Set<Int>>>.invertConnections() =
flatMap { (adapter, connectedTos) ->
connectedTos.map { connectedTo ->
connectedTo to adapter
}.toSet()
}.groupBy { it.first }
.map { (adapter, connections) ->
adapter to connections.map { it.second }.toSet()
}.toMap()
val adaptersString = """
16
10
15
5
1
11
7
19
6
12
4
""".trimIndent()
val largerExample = """
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
""".trimIndent()
class Day10_Part1 : FunSpec({
val numbers = parseAdapters(adaptersString)
context("find next joltage candidates for 0") {
val candidates = findJoltageCandidates(0)
candidates shouldBe setOf(1, 2, 3)
}
context("find next joltage candidates for 2") {
val candidates = findJoltageCandidates(2)
candidates shouldBe setOf(3, 4, 5)
}
context("find adapter chain") {
val chain = numbers.toSet().findAdapterChain(0)
chain shouldBe listOf(
1 to 1,
3 to 4,
1 to 5,
1 to 6,
1 to 7,
3 to 10,
1 to 11,
1 to 12,
3 to 15,
1 to 16,
3 to 19,
3 to 22
)
chain.filter { it.first == 1 }.count() shouldBe 7
chain.filter { it.first == 3 }.count() shouldBe 5
}
context("find adapter chain for larger example") {
val largerExampleNumbers = parseAdapters(largerExample)
val chain = largerExampleNumbers.toSet().findAdapterChain(0)
chain.filter { it.first == 1 }.count() shouldBe 22
chain.filter { it.first == 3 }.count() shouldBe 10
}
})
class Day10_Part1_Exercise: FunSpec({
val input = readResource("day10Input.txt")!!
val numbers = parseAdapters(input)
val chain = numbers.toSet().findAdapterChain(0)
val count1 = chain.filter { it.first == 1 }.count()
val count3 = chain.filter { it.first == 3 }.count()
val result = count1 * count3
test("solution") {
result shouldBe 1984
}
})
class Day10_Part2 : FunSpec({
val numbers = parseAdapters(adaptersString)
context("find alternatives for next adapter") {
val alternatives = numbers.toSet().findAlternatives()
alternatives shouldBe listOf(
0 to setOf(1),
1 to setOf(4),
4 to setOf(5, 6, 7),
5 to setOf(6, 7),
6 to setOf(7),
7 to setOf(10),
10 to setOf(11, 12),
11 to setOf(12),
12 to setOf(15),
15 to setOf(16),
16 to setOf(19),
19 to setOf()
)
test("connections backwards") {
val alternativesBackwards = numbers.toSet().findAlternativesBackwards()
alternativesBackwards shouldBe mapOf(
1 to setOf(0),
4 to setOf(1),
5 to setOf(4),
6 to setOf(4, 5),
7 to setOf(4, 5, 6),
10 to setOf(7),
11 to setOf(10),
12 to setOf(10, 11),
15 to setOf(12),
16 to setOf(15),
19 to setOf(16)
)
}
context("invert connections") {
val inverted = alternatives.invertConnections()
test("inverted connections") {
inverted shouldBe mapOf(
1 to setOf(0),
4 to setOf(1),
5 to setOf(4),
6 to setOf(4, 5),
7 to setOf(4, 5, 6),
10 to setOf(7),
11 to setOf(10),
12 to setOf(10, 11),
15 to setOf(12),
16 to setOf(15),
19 to setOf(16)
)
}
}
context("invert connections and connections should be equal") {
val largerExampleNumbers = parseAdapters(largerExample)
val alternativesBackwards = largerExampleNumbers.toSet().findAlternativesBackwards()
val inverted = largerExampleNumbers.toSet().findAlternatives().invertConnections()
alternativesBackwards shouldBe inverted
}
}
context("find combinations for adapters") {
val combinations = numbers.toSet().findCombinationsDeprecated()
combinations shouldBe listOf(
1L to 0,
1L to 1,
1L to 4,
1L to 5,
2L to 6,
4L to 7,
4L to 10,
4L to 11,
8L to 12,
8L to 15,
8L to 16,
8L to 19,
)
numbers.toSet().findCombinations() shouldBe combinations
}
context("find combinations for adapters in larger example") {
val largerExampleNumbers = parseAdapters(largerExample)
val combinations = largerExampleNumbers.toSet().findCombinations()
combinations.last().first shouldBe 19208L
}
context("find combinations for adapters in larger example (deprecated)") {
val largerExampleNumbers = parseAdapters(largerExample)
val combinations = largerExampleNumbers.toSet().findCombinationsDeprecated()
combinations.last().first shouldBe 19208L
}
})
class Day10_Part2_Exercise: FunSpec({
val input = readResource("day10Input.txt")!!
val numbers = parseAdapters(input)
val combinations = numbers.toSet().findCombinations()
val result = combinations.last().first
test("solution") {
result shouldBe 3543369523456L
}
})
| 1 | Kotlin | 0 | 0 | 8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8 | 9,308 | advent_of_code_2020 | Apache License 2.0 |
solutions/qualifications/median-sort/src/main/kotlin/solutions.median.sort/MedianSortSolution.kt | Lysoun | 351,224,145 | false | null | interface Judge {
fun askJudge(numbers: List<Int>): Int
}
class RealJudge: Judge {
override fun askJudge(numbers: List<Int>): Int {
println(numbers.joinToString(" "))
return readLine()!!.toInt()
}
}
fun main(args: Array<String>) {
val input = readLine()!!.split(" ").map { it.toInt() }
val casesNumber = input[0]
val listSize = input[1]
for (i in 1..casesNumber) {
sortList(listSize, RealJudge())
}
}
fun sortList(listSize: Int, judge: Judge): List<Int> {
var numbersToSort = MutableList(listSize) { it + 1 }
var triplet = numbersToSort.subList(0, 3)
var median = judge.askJudge(triplet)
val tripletWithoutMedian = triplet.filter { it != median }
var sortedNumbers = listOf(tripletWithoutMedian[0], median, tripletWithoutMedian[1])
numbersToSort = numbersToSort.filter { !triplet.contains(it) }.toMutableList()
var numberToSort: Int? = null
var left = 0
var right = sortedNumbers.size - 1
while(sortedNumbers.size < listSize) {
if(numberToSort == null) {
numberToSort = numbersToSort.removeFirst()
left = 0
right = sortedNumbers.size - 1
}
val middle = (left + right) / 2
triplet = (sortedNumbers.subList(middle, middle + 2) + listOf(numberToSort)).toMutableList()
median = judge.askJudge(triplet)
if(middle == 0 && median == sortedNumbers[0]) {
sortedNumbers = listOf(numberToSort) + sortedNumbers
numberToSort = null
} else {
if(middle == (sortedNumbers.size - 2) && median == sortedNumbers[sortedNumbers.size - 1]) {
sortedNumbers = sortedNumbers + listOf(numberToSort)
numberToSort = null
} else {
if(median == numberToSort) {
sortedNumbers = (sortedNumbers.subList(0, middle + 1) +
listOf(numberToSort) +
sortedNumbers.subList(middle + 1, sortedNumbers.size)).toMutableList()
numberToSort = null
}
}
}
if(median == triplet[1]) {
left = middle + 1
} else {
right = middle - 1
}
}
judge.askJudge(sortedNumbers)
return sortedNumbers
} | 0 | Kotlin | 0 | 0 | 98d39fcab3c8898bfdc2c6875006edcf759feddd | 2,323 | google-code-jam-2021 | MIT License |
src/main/kotlin/day14/CountProjection.kt | Ostkontentitan | 434,500,914 | false | {"Kotlin": 73563} | package day14
class CountProjection {
fun perform(steps: Int, inputs: List<String>): Long {
val instructions = extractInstructionMap(inputs)
val polyCount = initialPolyPairCount(inputs.first())
val polyTail = inputs.first().last().toString()
val countForChars = growPolyCountBySteps(steps, polyCount, instructions, polyTail)
val counts = countForChars.values.sorted()
return counts.maxOf { it } - counts.minOf { it }
}
private tailrec fun growPolyCountBySteps(
steps: Int,
polyCount: Map<String, Long>,
instructions: Map<String, String>,
tail: String
): Map<String, Long> = if (steps == 0) {
polyCount.keys.fold(mapOf(tail to 1)) { acc, item ->
val first = item.first().toString()
val count = polyCount[item]!!
acc + (first to (acc[first] ?: 0L) + count)
}
} else {
val new = growPolyCountByStep(polyCount, instructions)
growPolyCountBySteps(steps - 1, new, instructions, tail)
}
private fun growPolyCountByStep(
polyCount: Map<String, Long>,
instructions: Map<String, String>
): Map<String, Long> {
val updated = mutableMapOf<String, Long>()
polyCount.forEach { item ->
val insertion = instructions[item.key]
if (insertion != null) {
val keyOne = "${item.key[0]}${insertion}"
val keyTwo = "${insertion}${item.key[1]}"
val itemCount = item.value
updated.addToValue(keyOne, itemCount)
updated.addToValue(keyTwo, itemCount)
}
}
return updated.filterValues { it > 0L }
}
private fun MutableMap<String, Long>.addToValue(key: String, itemCount: Long) {
this += (key to ((this[key] ?: 0) + itemCount))
}
private fun initialPolyPairCount(input: String): Map<String, Long> =
input.windowed(size = 2, partialWindows = true).fold(emptyMap()) { acc, item ->
acc + (item to (acc[item] ?: 0L) + 1L)
}
private fun extractInstructionMap(inputs: List<String>): Map<String, String> =
inputs.subList(2, inputs.size).associate {
val (target, replace) = it.split(" -> ")
target to replace
}
}
| 0 | Kotlin | 0 | 0 | e0e5022238747e4b934cac0f6235b92831ca8ac7 | 2,319 | advent-of-kotlin-2021 | Apache License 2.0 |
src/Day02.kt | Jessenw | 575,278,448 | false | {"Kotlin": 13488} | fun main() {
fun part1(input: List<String>) =
input
.sumOf {
val split = it.split(" ")
val opponentPlay = scoreForPlay(split[0])
val myPlay = scoreForPlay(split[1])
val roundPoints =
if (opponentPlay == myPlay) 3
else if (myPlay == 1 && opponentPlay == 3
|| myPlay == 3 && opponentPlay == 2
|| myPlay == 2 && opponentPlay == 1) 6
else 0
roundPoints + myPlay
}
fun part2(input: List<String>) =
input
.sumOf {
val split = it.split(" ")
val opponentPlay = scoreForPlay(split[0])
val outcome = scoreForPlay(split[1])
if (outcome == 1)
if (opponentPlay - 1 < 1) 3 else opponentPlay - 1
else if (outcome == 2)
opponentPlay + 3
else
(if (opponentPlay + 1 > 3) 1 else opponentPlay + 1) + 6
}
val testInput = readInputLines("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInputLines("Day02")
println(part1(input))
println(part2(input))
}
fun scoreForPlay(play: String) =
when (play) {
"A", "X" -> 1 // Rock, lose
"B", "Y" -> 2 // Paper, draw
"C", "Z" -> 3 // Scissors, win
else -> 0
} | 0 | Kotlin | 0 | 0 | 05c1e9331b38cfdfb32beaf6a9daa3b9ed8220a3 | 1,503 | aoc-22-kotlin | Apache License 2.0 |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day5/Day5.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day5
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.parseLongs
import net.olegg.aoc.utils.toTriple
import net.olegg.aoc.year2023.DayOf2023
/**
* See [Year 2023, Day 5](https://adventofcode.com/2023/day/5)
*/
object Day5 : DayOf2023(5) {
override fun first(): Any? {
val sections = data.split("\n\n")
val seeds = sections.first().parseLongs(" ")
val maps = sections.drop(1)
.map { section ->
val lines = section.lines()
val (from, to) = lines.first().substringBefore(" ").split("-to-")
val ranges = lines.drop(1)
.map { it.parseLongs(" ").toTriple() }
.map { (to, from, length) ->
Range(
from = from..<from + length,
to = to..<to + length,
delta = to - from,
)
}
Mapping(
from = from,
to = to,
ranges = ranges,
excludes = emptyList(),
)
}
return maps
.fold(seeds) { curr, mapping ->
curr.map { seed ->
seed + (mapping.ranges.firstOrNull { seed in it.from }?.delta ?: 0)
}
}
.min()
}
override fun second(): Any? {
val sections = data.split("\n\n")
val seeds = sections.first()
.parseLongs(" ")
.chunked(2)
.map { it.first()..<it.first() + it.last() }
val startSeeds = seeds.normalize()
val maps = sections.drop(1)
.map { section ->
val lines = section.lines()
val (from, to) = lines.first().substringBefore(" ").split("-to-")
val ranges = lines.drop(1)
.map { it.parseLongs(" ").toTriple() }
.map { (to, from, length) ->
Range(
from = from..<from + length,
to = to..<to + length,
delta = to - from,
)
}
Mapping(
from = from,
to = to,
ranges = ranges,
excludes = emptyList(),
)
}
val max = maxOf(
startSeeds.maxOf { it.last },
maps.maxOf { map -> map.ranges.maxOf { maxOf(it.from.last, it.to.last) } },
)
val full = 0..max
val fullMaps = maps.map { sourceMap ->
sourceMap.copy(
excludes = xored(full, sourceMap.ranges.map { it.from }).map { longRange ->
Range(
from = longRange,
to = longRange,
delta = 0,
)
},
)
}
return fullMaps
.fold(startSeeds) { curr, mapping ->
curr.flatMap { seedRange ->
mapping.ranges
.filter { it.from touch seedRange }
.map { it to (it.from overlap seedRange) }
.map { (range, seedRange) -> seedRange.first + range.delta..seedRange.last + range.delta } +
mapping.excludes
.filter { it.from touch seedRange }
.map { it.from overlap seedRange }
}.normalize()
}
.minOf { it.first }
}
private fun List<LongRange>.normalize(): List<LongRange> {
val events = this.flatMap {
listOf(it.first to 1, it.last + 1 to -1)
}.sortedWith(compareBy({ it.first }, { -it.second }))
return buildList {
var depth = 0
var from = Long.MIN_VALUE
events.forEach { (place, delta) ->
if (depth == 0 && delta == 1) {
from = place
}
depth += delta
if (depth == 0) {
add(from..place)
}
}
}
}
private fun xored(
fullRange: LongRange,
exclude: List<LongRange>
): List<LongRange> {
val excludeNorm = exclude.normalize()
return buildList {
add(fullRange.first)
excludeNorm.forEach {
add(it.first - 1)
add(it.last + 1)
}
add(fullRange.last)
}
.chunked(2)
.mapNotNull {
if (it.first() <= it.last()) {
it.first()..it.last()
} else {
null
}
}
}
private data class Mapping(
val from: String,
val to: String,
val ranges: List<Range>,
val excludes: List<Range>,
)
private data class Range(
val from: LongRange,
val to: LongRange,
val delta: Long,
)
private infix fun LongRange.touch(other: LongRange) =
first in other || last in other || other.first in this || other.last in this
private infix fun LongRange.overlap(other: LongRange) = LongRange(maxOf(first, other.first), minOf(last, other.last))
}
fun main() = SomeDay.mainify(Day5)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 4,491 | adventofcode | MIT License |
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day12/Record.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2023.day12
import kotlin.streams.asStream
data class Record(val text: String, val groups: List<Int>) {
private val ICON_BROKEN_SPRING = '#'
private val ICON_OPERATIONAL_SPRING = '.'
private val ICON_UNKNOWN_SPRING = '?'
private val possibilities = replaceQuestionmark(sequenceOf(text), text.count { it == '?' })
val possibleGroups = possibilities
.asStream()
.parallel()
.map {
it
.split(ICON_OPERATIONAL_SPRING)
.filter { it.isNotBlank() }
.map { it.length }
}
.filter { it == groups }
val possibilitiesCount = findSolutions(mutableMapOf(), "$text.".toList(), groups, 0)
private tailrec fun replaceQuestionmark(lines: Sequence<String>, count: Int): Sequence<String> {
if (count > 0) {
return replaceQuestionmark(
lines.flatMap {
listOf(
it.replaceFirst(ICON_UNKNOWN_SPRING, ICON_OPERATIONAL_SPRING),
it.replaceFirst(ICON_UNKNOWN_SPRING, ICON_BROKEN_SPRING)
)
},
count - 1
)
}
return lines
}
@SuppressWarnings("kotlin:S6510", "kotlin:S3776")
private fun findSolutions(
cache: MutableMap<Triple<List<Char>, List<Int>, Int>, Long>,
line: List<Char>,
sizes: List<Int>,
doneInGroup: Int
): Long {
val cv = cache[Triple(line, sizes, doneInGroup)]
when {
cv != null -> {
return cv
}
else -> when {
line.isEmpty() -> {
return when {
sizes.isEmpty() && (doneInGroup == 0) -> 1
else -> 0
}
}
else -> {
var solutions = 0L
val possible = when {
line[0] == ICON_UNKNOWN_SPRING -> listOf(ICON_OPERATIONAL_SPRING, ICON_BROKEN_SPRING)
else -> line.subList(0, 1)
}
for (c in possible) {
when (c) {
'#' -> {
solutions += findSolutions(cache, line.subList(1, line.size), sizes, doneInGroup + 1)
}
else -> {
when {
doneInGroup > 0 -> {
when {
sizes.isNotEmpty() && sizes[0] == doneInGroup -> solutions += findSolutions(
cache,
line.subList(1, line.size),
sizes.subList(1, sizes.size),
0
)
}
}
else -> {
solutions += findSolutions(cache, line.subList(1, line.size), sizes, 0)
}
}
}
}
}
cache[Triple(line, sizes, doneInGroup)] = solutions
return solutions
}
}
}
}
}
| 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 3,576 | advent-of-code | Apache License 2.0 |
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/greedy/luck/LuckBalance.kt | slobanov | 200,526,003 | false | null | package ru.amai.study.hackerrank.practice.interviewPreparationKit.greedy.luck
import java.lang.IllegalArgumentException
import java.util.*
fun luckBalance(k: Int, contests: List<Contest>): Int {
val (importantContests, unimportanceContests) =
contests.partition { it.importance == Importance.IMPORTANT }
val sortedImportantContests =
importantContests.sortedBy { it.luck }
val lostContestLuck =
(unimportanceContests + sortedImportantContests.takeLast(k)).totalLuck
val importantContestsCnt = importantContests.size
return if (importantContestsCnt > k) {
val winContestsLuck =
sortedImportantContests.take(importantContestsCnt - k).totalLuck
lostContestLuck - winContestsLuck
} else lostContestLuck
}
private val List<Contest>.totalLuck: Int
get() = sumBy { it.luck }
data class Contest(val luck: Int, val importance: Importance)
enum class Importance {
IMPORTANT,
UNIMPORTANT
}
private fun from(importanceValue: Int): Importance = when (importanceValue) {
0 -> Importance.UNIMPORTANT
1 -> Importance.IMPORTANT
else -> throw IllegalArgumentException(
"got illegal importanceValue = $importanceValue; 0 or 1 expected"
)
}
fun main() {
val scan = Scanner(System.`in`)
val (n, k) = scan.nextLine().split(" ").map { it.toInt() }
val contests = (1..n).map {
val (luck, importanceValue) = scan.nextLine().split(" ").map { it.trim().toInt() }
Contest(luck, from(importanceValue))
}
val result = luckBalance(k, contests)
println(result)
}
| 0 | Kotlin | 0 | 0 | 2cfdf851e1a635b811af82d599681b316b5bde7c | 1,602 | kotlin-hackerrank | MIT License |
src/main/kotlin/Chiton_15.kt | Flame239 | 433,046,232 | false | {"Kotlin": 64209} | val risks: Array<IntArray> by lazy {
readFile("Chiton").split("\n").map { it.map { it.digitToInt() }.toIntArray() }.toTypedArray()
}
fun findLeastRiskyPath(field: Array<IntArray>): Int {
val h = field.size
val w = field[0].size
val edges = mutableListOf<Edge>()
for (i in 0 until h) {
for (j in 0 until w) {
if (i < h - 1) {
edges.add(Edge(coordsToString(i, j), coordsToString(i + 1, j), field[i][j] + field[i + 1][j]))
}
if (i > 0) {
edges.add(Edge(coordsToString(i, j), coordsToString(i - 1, j), field[i][j] + field[i - 1][j]))
}
if (j < w - 1) {
edges.add(Edge(coordsToString(i, j), coordsToString(i, j + 1), field[i][j] + field[i][j + 1]))
}
if (j > 0) {
edges.add(Edge(coordsToString(i, j), coordsToString(i, j - 1), field[i][j] + field[i][j - 1]))
}
}
}
val graph = Graph(edges, true)
graph.dijkstra(coordsToString(0, 0))
val dist = graph.getDistanceTo(coordsToString(h - 1, w - 1))
return (dist - field[0][0] + field[h - 1][w - 1]) / 2
}
fun getBigField(field: Array<IntArray>): Array<IntArray> {
val h = field.size
val w = field[0].size
val bigH = field.size * 5
val bigW = field[0].size * 5
val bigField = Array(bigH) { IntArray(bigW) }
for (i in 0 until bigH) {
for (j in 0 until bigW) {
val delta = i / h + j / w
var newVal = field[i % h][j % w] + delta
if (newVal > 9) newVal -= 9
bigField[i][j] = newVal
}
}
return bigField
}
fun main() {
println(findLeastRiskyPath(risks))
println(findLeastRiskyPath(getBigField(risks)))
}
fun coordsToString(i: Int, j: Int) = "$i,$j"
| 0 | Kotlin | 0 | 0 | ef4b05d39d70a204be2433d203e11c7ebed04cec | 1,814 | advent-of-code-2021 | Apache License 2.0 |
WarmUp/CompleteTheProject/src/main/kotlin/jetbrains/kotlin/course/warmup/Main.kt | jetbrains-academy | 504,249,857 | false | {"Kotlin": 1108971} | package jetbrains.kotlin.course.mastermind.advanced
fun getGameRules(wordLength: Int, maxAttemptsCount: Int, secretExample: String) =
"Welcome to the game! $newLineSymbol" +
newLineSymbol +
"Two people play this game: one chooses a word (a sequence of letters), " +
"the other guesses it. In this version, the computer chooses the word: " +
"a sequence of $wordLength letters (for example, $secretExample). " +
"The user has several attempts to guess it (the max number is $maxAttemptsCount). " +
"For each attempt, the number of complete matches (letter and position) " +
"and partial matches (letter only) is reported. $newLineSymbol" +
newLineSymbol +
"For example, with $secretExample as the hidden word, the BCDF guess will " +
"give 1 full match (C) and 1 partial match (B)."
fun countPartialMatches(secret: String, guess: String): Int {
val matches = minOf(
secret.filter { it in guess }.length,
guess.filter { it in secret }.length,
)
return matches - countExactMatches(guess, secret)
}
fun countExactMatches(secret: String, guess: String): Int =
guess.filterIndexed { index, letter -> letter == secret[index] }.length
fun generateSecret(wordLength: Int, alphabet: String) =
List(wordLength) { alphabet.random() }.joinToString("")
fun isComplete(secret: String, guess: String) = secret == guess
fun printRoundResults(secret: String, guess: String) {
val fullMatches = countExactMatches(secret, guess)
val partialMatches = countPartialMatches(secret, guess)
println("Your guess has $fullMatches full matches and $partialMatches partial matches.")
}
fun isWon(complete: Boolean, attempts: Int, maxAttemptsCount: Int) = complete && attempts <= maxAttemptsCount
fun isLost(complete: Boolean, attempts: Int, maxAttemptsCount: Int) = !complete && attempts > maxAttemptsCount
fun isCorrectInput(userInput: String, wordLength: Int, alphabet: String): Boolean {
if (userInput.length != wordLength) {
println("The length of your guess should be $wordLength! Try again!")
return false
}
val notAlphabetSymbols = userInput.filter { it !in alphabet }
if (notAlphabetSymbols.isNotEmpty()) {
println("All symbols in your guess should be from the alphabet: $alphabet! Try again!")
return false
}
return true
}
fun safeUserInput(wordLength: Int, alphabet: String): String {
var guess: String
var isCorrect: Boolean
do {
println("Please input your guess. It should be of length $wordLength, and each symbol should be from the alphabet: $alphabet.")
guess = safeReadLine()
isCorrect = isCorrectInput(guess, wordLength, alphabet)
} while(!isCorrect)
return guess
}
fun playGame(secret: String, wordLength: Int, maxAttemptsCount: Int, alphabet: String) {
var complete: Boolean
var attempts = 0
do {
println("Please input your guess. It should be of length $wordLength.")
val guess = safeUserInput(wordLength, alphabet)
printRoundResults(secret, guess)
complete = isComplete(secret, guess)
attempts++
if (isLost(complete, attempts, maxAttemptsCount)) {
println("Sorry, you lost! :( My word is $secret")
break
} else if (isWon(complete, attempts, maxAttemptsCount)) {
println("Congratulations! You guessed it!")
}
} while (!complete)
}
fun main() {
val wordLength = 4
val maxAttemptsCount = 3
val secretExample = "ACEB"
val alphabet = "ABCDEFGH"
println(getGameRules(wordLength, maxAttemptsCount, secretExample))
playGame(generateSecret(wordLength, alphabet), wordLength, maxAttemptsCount, alphabet)
}
| 14 | Kotlin | 1 | 6 | bc82aaa180fbd589b98779009ca7d4439a72d5e5 | 3,811 | kotlin-onboarding-introduction | MIT License |
src/main/kotlin/twentytwentytwo/Day21.kt | JanGroot | 317,476,637 | false | {"Kotlin": 80906} | package twentytwentytwo
import twentytwentytwo.Day21.Monkey.Operation
import twentytwentytwo.Day21.Monkey.Value
fun main() {
val input = {}.javaClass.getResource("input-21.txt")!!.readText().linesFiltered { it.isNotEmpty() };
val tinput = {}.javaClass.getResource("input-21-1.txt")!!.readText().linesFiltered { it.isNotEmpty() };
val test = Day21(tinput)
val day = Day21(input)
println(test.part1())
println(test.part2())
println(day.part1())
println(day.part2())
}
private const val HUMAN = "humn"
class Day21(input: List<String>) {
private val monkeys =
input.map { it.split(": ") }.associate { (key, value) -> key to parseMonkey(key, value) }.toMutableMap()
fun part1(): Long {
val root = monkeys["root"]!!
return recurse(root);
}
fun part2(): Long {
val root = (monkeys["root"] as Operation?)!!
// approx
var under = 0L
var over = 5000000000000L
monkeys[HUMAN] = Value(HUMAN, 1)
val runLeft = recurse(monkeys[root.left]!!)
monkeys[HUMAN] = Value(HUMAN, 1000)
val leftConstant = (runLeft == recurse(monkeys[root.left]!!))
val leftGrowing = (runLeft < recurse(monkeys[root.left]!!))
val growing = leftConstant xor leftGrowing
val target = if (leftConstant) recurse(monkeys[root.left]!!) else recurse(monkeys[root.right]!!)
val variable = if (leftConstant) monkeys[root.right]!! else monkeys[root.left]!!
while (true) {
val guess = (under + over) / 2
monkeys[HUMAN] = Value(HUMAN, guess)
val result = recurse(variable)
if (growing) {
when {
(result < target) -> under = guess + 1
(result > target) -> over = guess - 1
else -> return guess
}
}
else {
when {
(result > target) -> under = guess + 1
(result < target) -> over = guess - 1
else -> return guess
}
}
}
}
private fun recurse(monkey: Monkey): Long {
return when (monkey) {
is Value -> monkey.value
is Operation -> {
when (monkey.operand) {
"*" -> recurse(monkeys[monkey.left]!!) * recurse(monkeys[monkey.right]!!)
"+" -> recurse(monkeys[monkey.left]!!) + recurse(monkeys[monkey.right]!!)
"-" -> recurse(monkeys[monkey.left]!!) - recurse(monkeys[monkey.right]!!)
"/" -> recurse(monkeys[monkey.left]!!) / recurse(monkeys[monkey.right]!!)
else -> {
error("operation not found")
}
}
}
}
}
sealed class Monkey(val name: String) {
class Value(name: String, val value: Long) : Monkey(name)
class Operation(name: String, val left: String, val operand: String, val right: String) : Monkey(name)
}
private fun parseMonkey(key: String, value: String): Monkey {
return if (value.all { it.isDigit() }) Value(key, value.toLong())
else {
val split = value.split(" ")
Operation(key, split[0], split[1], split[2])
}
}
}
| 0 | Kotlin | 0 | 0 | 04a9531285e22cc81e6478dc89708bcf6407910b | 3,346 | aoc202xkotlin | The Unlicense |
src/main/kotlin/com/hjk/advent22/Day07.kt | h-j-k | 572,485,447 | false | {"Kotlin": 26661, "Racket": 3822} | package com.hjk.advent22
object Day07 {
fun part1(input: List<String>): Int =
process(input).getDirs().sumOf { dir -> dir.size.takeIf { it <= 100000 } ?: 0 }
fun part2(input: List<String>): Int {
val root = process(input)
val spaceRequired = 30000000 - (70000000 - root.size)
return root.getDirs().filter { it.size >= spaceRequired }.minOf { it.size }
}
private fun process(input: List<String>): Dir {
var current: Dir? = null
for (line in input) {
when {
line.startsWith("$ cd") -> {
when (val name = line.split(" ").last()) {
".." -> current = current!!.parent!!
else -> {
val dir = Dir(name, current)
if (current != null) current += dir
current = dir
}
}
}
line.startsWith("$ ls") || line.startsWith("dir ") -> continue
else -> line.split(" ").let { (size, name) ->
require(current != null)
current += File(name, size.toInt())
}
}
}
return generateSequence(current) { it.parent }.last()
}
private sealed interface Node {
val name: String
val size: Int
}
private data class Dir(override val name: String, val parent: Dir? = null) : Node {
private val entries = mutableListOf<Node>()
fun getDirs(): List<Dir> = listOf(this) + entries.filterIsInstance<Dir>().flatMap { it.getDirs() }
operator fun plusAssign(entry: Node) {
entries += entry
}
override val size: Int get() = entries.sumOf { it.size }
}
private data class File(override val name: String, override val size: Int) : Node
}
| 0 | Kotlin | 0 | 0 | 20d94964181b15faf56ff743b8646d02142c9961 | 1,908 | advent22 | Apache License 2.0 |
src/day01/Day01.kt | Barros9 | 572,616,965 | false | {"Kotlin": 2313} | package day01
import Day
import readInput
class Day01 : Day {
private fun part1(input: List<String>): Int {
return input
.asSequence()
.flatMapIndexed { index, value ->
when {
index == 0 || index == input.lastIndex -> listOf(index)
value.isEmpty() -> listOf(index - 1, index + 1)
else -> emptyList()
}
}
.windowed(size = 2, step = 2) { (from, to) -> input.slice(from..to) }
.maxOfOrNull { elf -> elf.sumOf { it.toInt() } } ?: 0
}
private fun part2(input: List<String>): Int {
return input
.asSequence()
.flatMapIndexed { index, value ->
when {
index == 0 || index == input.lastIndex -> listOf(index)
value.isEmpty() -> listOf(index - 1, index + 1)
else -> emptyList()
}
}
.windowed(size = 2, step = 2) { (from, to) -> input.slice(from..to) }
.map { elf -> elf.sumOf { it.toInt() } }
.sortedDescending()
.take(3)
.sum()
}
override fun play() {
val testInput = readInput("day01/Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("day01/Day01")
println("Day 01")
println("- Part 1 result: ${part1(input)}")
println("- Part 2 result: ${part2(input)}")
}
}
| 0 | Kotlin | 0 | 0 | 03e03fa69033ee8c5c7bf61fec45a663abbfad28 | 1,543 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day18/Code.kt | fcolasuonno | 225,219,560 | false | null | package day18
import isDebug
import java.io.File
import kotlin.math.abs
fun main() {
val name = if (isDebug() && false) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val (parsed, walls) = parse(input)
println(parsed to walls)
// println("Part 1 = ${part1(parsed, walls)}")
// println("Part 2 = ${part2(parsed, walls)}")
}
fun parse(input: List<String>) = input.withIndex().flatMap { (j, s) ->
s.withIndex().mapNotNull { (i, c) ->
when {
c == '@' -> Tile.Pos
c.isLowerCase() -> Tile.Key(c)
c.isUpperCase() -> Tile.Door(c.toLowerCase())
c == '#' -> Tile.Wall
else -> null
}?.let { Triple(i, j, it) }
}
}.let {
Step1(
it.single { it.third == Tile.Pos }.let { it.first to it.second },
it.filter { it.third is Tile.Key }.map { (it.first to it.second) to (it.third as Tile.Key) }.toMap(),
it.filter { it.third is Tile.Door }.map { (it.first to it.second) to (it.third as Tile.Door) }.toMap()
) to it.filter { it.third == Tile.Wall }.map { (it.first to it.second) }.toSet()
}
fun part1(input: Step1, initialWalls: Set<Pair<Int, Int>>): Any? {
val walls = initialWalls.toMutableSet()
var size: Int
do {
size = walls.size
val newWalls = walls.flatMap { it.neighbours() }.toSet()
.filter { it !in walls && it !in input.doorMap && it !in input.keyMap && it.neighbours().count { it in walls } == 3 }
walls.addAll(newWalls)
} while (size != walls.size)
val seen = mutableSetOf<String>().apply { add(input.hash()) }
val frontier = input.neighbours(walls).toSortedSet(compareBy<Step1> {
it.step
}.thenBy {
it.keyMap.size
}.thenBy {
it.pos.first
}.thenBy {
it.pos.second
}.thenBy {
it.keyMap.values.map { it.c }.sorted().joinToString("")
})
while (frontier.isNotEmpty()) {
val first = frontier.first()
if (first.keyMap.isEmpty()) {
return first.step
} else {
frontier.remove(first)
seen.add(first.hash())
frontier.addAll(first.neighbours(walls).filter { it.hash() !in seen })
}
}
return 0
}
fun part2(input: Step1, initialWalls: Set<Pair<Int, Int>>): Any? {
val pos = input.pos
val walls = (initialWalls + pos.neighbours() + pos).toMutableSet()
var size: Int
do {
size = walls.size
val newWalls = walls.flatMap { it.neighbours() }.toSet()
.filter { (abs(it.first - pos.first) + abs(it.second - pos.second)) > 2 && it !in walls && it !in input.doorMap && it !in input.keyMap && it.neighbours().count { it in walls } == 3 }
walls.addAll(newWalls)
} while (size != walls.size)
val others = input.keyMap.map { keyEntry ->
val seen = mutableSetOf<Pair<Int, Int>>()
val doors = input.doorMap.toMutableMap()
val keys = input.keyMap.toMutableMap()
val cost: MutableMap<Char, Pair<Int, String>> = mutableMapOf()
val frontier = setOf(
Step2(
keyEntry.key,
doors,
keys,
cost
)
).toSortedSet(compareBy<Step2> { it.pos.first }.thenBy { it.pos.second })
while (frontier.isNotEmpty()) {
val first = frontier.first()
frontier.remove(first)
seen.add(first.pos)
frontier.addAll(first.neighbours(walls).filter { it.pos !in seen && it.pos != keyEntry.key })
}
keyEntry.value.c to cost
}.toMap()
val seen = mutableSetOf<Pair<Int, Int>>()
val doors = input.doorMap.toMutableMap()
val keys = input.keyMap.toMutableMap()
val cost: List<MutableMap<Char, Pair<Int, String>>> =
listOf(mutableMapOf(), mutableMapOf(), mutableMapOf(), mutableMapOf())
val frontier = mutableListOf(
input.pos.copy(input.pos.first - 1, input.pos.second - 1),
input.pos.copy(input.pos.first - 1, input.pos.second + 1),
input.pos.copy(input.pos.first + 1, input.pos.second - 1),
input.pos.copy(input.pos.first + 1, input.pos.second + 1)
).mapIndexed { index, pair ->
Step2(pair, doors, keys, cost[index])
}.toSortedSet(compareBy<Step2> { it.pos.first }.thenBy { it.pos.second })
while (frontier.isNotEmpty()) {
val first = frontier.first()
frontier.remove(first)
seen.add(first.pos)
frontier.addAll(first.neighbours(walls).filter { it.pos !in seen })
}
val newFrontier = cost.mapIndexed { index, mutableMap ->
mutableMap.filterValues { it.second.isEmpty() }.map { c ->
Pair(List(4) { if (it == index) "${c.key}" else "" }, c.value.first)
}
}.flatten()
.toSortedSet(compareBy<Pair<List<String>, Int>> { it.second }
.thenBy { it.first.flatMap { it.toList() }.sorted().joinToString("") })
while (newFrontier.isNotEmpty()) {
val first = newFrontier.first()
newFrontier.remove(first)
if (first.first.sumBy { it.length } == (input.keyMap.toMutableMap().size)) {
return first.second
}
val collectedKeys = first.first.joinToString("").toSet()
val otherKeys = first.first.withIndex().filter { it.value.isNotEmpty() }.flatMap { (index, c) ->
others.getValue(c.last()).filterValues { it.second.all { it in collectedKeys } }
.filterKeys { it !in first.first.toString() }
.map {
Pair(
first.first.mapIndexed { i, l -> if (i == index) (l + it.key) else l },
first.second + it.value.first
)
}
}
val otherStarts = cost.withIndex().mapNotNull { (index, c) ->
if (first.first[index].isNotEmpty()) null else
c.filterKeys { it !in collectedKeys }
.filterValues { it.second.all { it in collectedKeys } }
.map {
Pair(
first.first.mapIndexed { i, l -> if (i == index) (l + it.key) else l },
first.second + it.value.first
)
}
}.flatten()
newFrontier.addAll(otherKeys + otherStarts)
}
return 0
}
sealed class Tile {
object Wall : Tile()
data class Key(val c: Char) : Tile()
data class Door(val c: Char) : Tile()
object Pos : Tile()
}
data class Step1(
val pos: Pair<Int, Int>,
val keyMap: Map<Pair<Int, Int>, Tile.Key>,
val doorMap: Map<Pair<Int, Int>, Tile.Door>,
val step: Int = 0
) {
fun neighbours(walls: Set<Pair<Int, Int>>): List<Step1> =
pos.neighbours().filter { it !in walls && it !in doorMap }.map {
val key = keyMap[it]
if (key == null) {
copy(pos = it, step = step + 1)
} else {
copy(pos = it, keyMap = keyMap.filterValues { it != key }, doorMap = doorMap.filterValues {
it.c != key.c
}, step = step + 1)
}
}
fun hash() = "${pos.first},${pos.second},${keyMap.values.map { it.c }.sorted().joinToString("")}"
}
data class Step2(
val pos: Pair<Int, Int>,
val doors: MutableMap<Pair<Int, Int>, Tile.Door>,
val keys: MutableMap<Pair<Int, Int>, Tile.Key>,
val cost: MutableMap<Char, Pair<Int, String>>,
var required: String = "",
val step: Int = 0
) {
fun neighbours(walls: Set<Pair<Int, Int>>): List<Step2> =
pos.neighbours().filter { it !in walls }.map {
var newRequired = required
if (it in doors) {
newRequired += doors.getValue(it).c
doors.remove(it)
}
if (it in keys) {
val key = keys.getValue(it)
keys.remove(it)
cost[key.c] = (step + 1) to newRequired
}
copy(pos = it, step = step + 1, required = newRequired)
}
override fun toString() = pos.toString()
}
private fun Pair<Int, Int>.neighbours() = listOf(
copy(first = first - 1),
copy(first = first + 1),
copy(second = second - 1),
copy(second = second + 1)
)
| 0 | Kotlin | 0 | 0 | d1a5bfbbc85716d0a331792b59cdd75389cf379f | 8,378 | AOC2019 | MIT License |
codeforces/round901/a.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round901
private fun solve(): Long {
val (_, _, k) = readInts()
val (a, b) = List(2) { readInts().toMutableList() }
val moves = mutableListOf<Long>()
var i = 0
while (i < k) {
val move = if (i % 2 == 0) makeMove(a, b) else makeMove(b, a)
moves.add(move)
if (i >= 4 && moves[moves.size - 1] == moves[moves.size - 3] && moves[moves.size - 2] == moves[moves.size - 4]) {
i += maxOf((k - 1 - i) / 2 * 2, 0)
}
i++
}
return a.sumOf { it.toLong() }
}
private fun makeMove(a: MutableList<Int>, b: MutableList<Int>): Long {
val aMin = a.min()
val bMax = b.max()
if (aMin >= bMax) return 0
a.remove(aMin); a.add(bMax)
b.add(aMin); b.remove(bMax)
return aMin with bMax
}
private infix fun Int.with(that: Int) = (toLong() shl 32) or that.toLong()
fun main() = repeat(readInt()) { println(solve()) }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 984 | competitions | The Unlicense |
src/main/kotlin/year2022/Day03.kt | simpor | 572,200,851 | false | {"Kotlin": 80923} | import AoCUtils
import AoCUtils.test
fun main() {
fun part1(input: String, debug: Boolean = false): Long {
return input.lines().map { line ->
val firstItem = line.substring(0, line.length / 2)
val secondItem = line.substring(line.length / 2)
firstItem.map { c -> if (secondItem.contains(c)) c else null }
.filterNotNull()
.distinct()
.map {
if (it.isLowerCase()) it.code - 'a'.code + 1
else it.code - 'A'.code + 27
}
}.flatten().sum().toLong()
}
fun part2(input: String, debug: Boolean = false): Long {
return input.lines().chunked(3).map {
it[0].map { c ->
if (it[1].contains(c) && it[2].contains(c)) c else null
}.filterNotNull().distinct()
}.flatten().sumOf {
if (it.isLowerCase()) it.code - 'a'.code + 1
else it.code - 'A'.code + 27
}.toLong()
}
val testInput =
"vJrwpWtwJgWrhcsFMMfFFhFp\n" +
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL\n" +
"PmmdzqPrVvPwwTWBwg\n" +
"wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn\n" +
"ttgJtRGJQctTZtZT\n" +
"CrZsJsPPZsGzwwsLwLmpwMDw"
val input = AoCUtils.readText("year2022/day03.txt")
part1(testInput, false) test Pair(157L, "test 1 part 1")
part1(input, false) test Pair(7850L, "part 1")
part2(testInput, false) test Pair(70L, "test 2 part 2")
part2(input) test Pair(2581L, "part 2")
}
| 0 | Kotlin | 0 | 0 | 631cbd22ca7bdfc8a5218c306402c19efd65330b | 1,582 | aoc-2022-kotlin | Apache License 2.0 |
src/2021/Day09.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2021`
import java.io.File
import java.lang.Integer.max
import java.lang.Integer.min
import java.util.*
fun main() {
Day09().solve()
}
class Day09 {
val input = """
2199943210
3987894921
9856789892
8767896789
9899965678
""".trimIndent()
class CaveBuilder(s: Scanner) {
val h = mutableListOf<Int>()
var sizeX = 0
var sizeY = 0
init {
while (s.hasNextLine()) {
val line = s.nextLine().trim()
this.add(line)
}
}
fun add(s: String) {
sizeX = s.length
++sizeY
h.addAll(s.toCharArray().map{it.toString().toInt()})
}
fun build(): Cave {
return Cave(h, sizeX, sizeY)
}
}
class Cave(val h: List<Int>, val sizeX: Int, val sizeY: Int) {
val basins = MutableList(h.size){-1}
init {
for (i in basins.indices) {
if (basins[i] == -1 && h[i] != 9) {
slide(i)
}
}
}
fun neighbours4(i: Int): List<Int> {
val r = mutableListOf<Int>()
val x = toX(i)
val y = toY(i)
if (x>0) {
r.add(i-1)
}
if (x<sizeX-1) {
r.add(i+1)
}
if (y>0) {
r.add(i-sizeX)
}
if (y<sizeY-1) {
r.add(i+sizeX)
}
return r
}
fun neighbours8(i: Int): List<Int> {
val r = mutableListOf<Int>()
val x = toX(i)
val y = toY(i)
for (ix in max(0, x-1)..min(sizeX-1, x+1)) {
for (jy in max(0, y-1)..min(sizeY-1, y+1)) {
if (ix!=x || jy!=y) {
r.add(jy * sizeX + ix)
}
}
}
return r
}
fun toX(i: Int): Int {
return i%sizeX
}
fun toY(i: Int): Int {
return i/sizeX
}
fun riskMap(): List<Int> {
return h.mapIndexed{ix, it -> if (neighbours4(ix).map{jt -> h[jt]}.all{hit -> hit>it}) {it+1} else {0} }
}
fun riskSum(): Int {
return riskMap().sum()
}
fun slide(start: Int) {
val s = mutableListOf<Int>()
var nextIx = start
var basinIx = basins[nextIx]
while (basinIx == -1) {
s.add(nextIx)
nextIx = gradNext(nextIx)
if (nextIx == -1) {
break
}
basinIx = basins[nextIx]
}
if (basinIx == -1) {
basinIx = s.last()
}
s.forEach{basins[it] = basinIx}
}
fun gradNext(i: Int): Int {
val minNextIx = neighbours4(i).map{Pair(it, h[it])}.minWithOrNull(compareBy({it.second}))!!.first
if (h[minNextIx]<h[i]) {
return minNextIx
}
return -1
}
fun toString(list: List<Int>): String {
return list.windowed(size = sizeX, step = sizeX){it.joinToString("|")}.joinToString("\n")
}
}
fun solve() {
val f = File("src/2021/inputs/day09.in")
val s = Scanner(f)
// val s = Scanner(input)
val cave = CaveBuilder(s).build()
val basinSizes = cave.basins.fold(mutableMapOf<Int, Int>()){acc, it -> acc[it]=(acc[it]?:0)+1; acc}.filter{it.key != -1}.values.sorted().reversed()
println("${cave.riskSum()} ${basinSizes[0] * basinSizes[1] * basinSizes[2]}")
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 3,681 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2021/Day12.kt | colinodell | 433,864,377 | true | {"Kotlin": 111114} | package com.colinodell.advent2021
class Day12 (input: List<String>) {
private val caves: Map<String, Set<String>> = parseInput(input)
fun solvePart1() = countDistinctPaths("start", "end", VisitSmallCavesExactlyOnce())
fun solvePart2() = countDistinctPaths("start", "end", VisitOneSmallCaveTwice())
private fun countDistinctPaths(current: String, end: String, strategy: Strategy): Int {
if (current == end) {
return 1
}
return strategy.nextSteps(current).sumOf { countDistinctPaths(it, end, strategy.copy()) }
}
interface Strategy {
fun nextSteps(current: String): Collection<String>
fun copy(): Strategy
}
inner class VisitSmallCavesExactlyOnce : Strategy {
private val visited = mutableSetOf<String>()
override fun nextSteps(current: String): Collection<String> {
if (isSmallCave(current)) {
visited.add(current)
}
return caves[current]!!.filter { !visited.contains(it) }
}
override fun copy(): Strategy = VisitSmallCavesExactlyOnce().also { it.visited.addAll(visited) }
}
inner class VisitOneSmallCaveTwice : Strategy {
private val visited = mutableSetOf<String>()
private var caveVisitedTwice: Boolean = false
override fun nextSteps(current: String): Collection<String> {
if (isSmallCave(current)) {
if (visited.contains(current)) {
caveVisitedTwice = true
} else {
visited.add(current)
}
}
return caves[current]!!.filter { canVisit(it) }
}
private fun canVisit(cave: String) = when {
!visited.contains(cave) -> true // Any cave can be visited once
!caveVisitedTwice && !setOf("start", "end").contains(cave) -> true // Any cave except "start" and "end" can be visited twice
else -> false // Otherwise, we can't visit this cave
}
override fun copy(): Strategy = VisitOneSmallCaveTwice().also { it.visited.addAll(visited); it.caveVisitedTwice = caveVisitedTwice }
}
private fun isSmallCave(s: String) = s.all { it.isLowerCase() }
private fun parseInput(input: List<String>) = buildMap<String, MutableSet<String>> {
input.forEach {
val (a, b) = it.split("-")
this.computeIfAbsent(a) { mutableSetOf() }.add(b)
this.computeIfAbsent(b) { mutableSetOf() }.add(a)
}
}
} | 0 | Kotlin | 0 | 1 | a1e04207c53adfcc194c85894765195bf147be7a | 2,541 | advent-2021 | Apache License 2.0 |
year2018/src/main/kotlin/net/olegg/aoc/year2018/day11/Day11.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2018.day11
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2018.DayOf2018
/**
* See [Year 2018, Day 11](https://adventofcode.com/2018/day/11)
*/
object Day11 : DayOf2018(11) {
override fun first(): Any? {
val serial = data.toInt()
val grid = (1..300).map { y ->
(1..300).map { x ->
val rack = x + 10
val start = rack * y
val withSerial = start + serial
val byId = withSerial * rack
val digit = (byId / 100) % 10
digit - 5
}
}
return (1..298).flatMap { y ->
(1..298).map { x ->
val sum = (-1..1).sumOf { dy -> (-1..1).sumOf { dx -> grid[y + dy][x + dx] } }
(x to y) to sum
}
}
.maxBy { it.second }
.let { "${it.first.first},${it.first.second}" }
}
override fun second(): Any? {
val serial = data.toInt()
val grid = (1..300).map { y ->
(1..300).map { x ->
val rack = x + 10
val start = rack * y
val withSerial = start + serial
val byId = withSerial * rack
val digit = (byId / 100) % 10
digit - 5
}
}
return (0..299).flatMap { y ->
(0..299).flatMap { x ->
(0..299).mapNotNull { size ->
return@mapNotNull if (x + size < 300 && y + size < 300) {
val sum = (0..size).sumOf { dy -> (0..size).sumOf { dx -> grid[y + dy][x + dx] } }
Triple(x + 1, y + 1, size + 1) to sum
} else {
null
}
}
}
}
.maxBy { it.second }
.let { "${it.first.first},${it.first.second},${it.first.third}" }
}
}
fun main() = SomeDay.mainify(Day11)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,675 | adventofcode | MIT License |
2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day04.kt | codelicia | 627,407,402 | false | {"Kotlin": 49578, "PHP": 554, "Makefile": 293} | package com.codelicia.advent2021
class Day04(input: String) {
private val newline = "\n"
private val section = "\n\n"
private val sections = input.split(section)
private val draws = sections[0].trim().split(",").map(String::toInt)
private val cards : List<BingoBoard> = buildList {
for (i in 1 until sections.size) {
val numbers = sections[i].split(newline).map { it.split(" ").filter(String::isNotBlank).map(String::toInt) }
add(BingoBoard(numbers.map { row -> row.map { it to false } }))
}
}
class BingoBoard(private var numbers: List<List<Pair<Int, Boolean>>>) {
fun mark(number: Int) {
numbers = numbers.map {
it.map { pair ->
if (pair.first == number) pair.first to true else pair
}
}
}
fun unmarkedSum(): Int = numbers.flatten().filter { !it.second }.sumOf { it.first }
fun hasBingo(): Boolean {
val diagonal = List(numbers[0].size) { column -> List(numbers[0].size) { numbers[it][column] } }
val merge = numbers + diagonal
merge.forEach { row ->
row.forEach { _ ->
if (row.count { it.second } == row.size) return true
}
}
return false
}
}
private fun cardsScore(): MutableSet<Pair<Int, Int>> {
val cardsInBingoOrder = mutableSetOf<Pair<Int, Int>>()
draws.forEach { numberCalled ->
cards.forEach { it.mark(numberCalled) }
val isBingo = cards.filter { it.hasBingo() }
isBingo.forEach { card ->
if (false == cardsInBingoOrder.map { it.first }.contains(card.hashCode())) {
cardsInBingoOrder.add(card.hashCode() to numberCalled * card.unmarkedSum())
}
}
}
return cardsInBingoOrder
}
fun part1(): Int = cardsScore().first().second
fun part2(): Int = cardsScore().last().second
} | 2 | Kotlin | 0 | 0 | df0cfd5c559d9726663412c0dec52dbfd5fa54b0 | 2,043 | adventofcode | MIT License |
src/day09/Day09.kt | lpleo | 572,702,403 | false | {"Kotlin": 30960} | package day09
import readInput
private const val FILES_DAY_TEST = "files/Day09_test"
private const val FILES_DAY = "files/Day09"
class Point(var x: Int, var y: Int) {
fun go(direction: Char) = run {
if (direction == 'R') x += 1;
if (direction == 'L') x -= 1;
if (direction == 'U') y += 1
if (direction == 'D') y -= 1;
}
fun follow(head: Point) = run {
if (kotlin.math.abs(this.x - head.x) <= 1 && kotlin.math.abs(this.y - head.y) <= 1) {
return@run Point(this.x, this.y)
//do nothing
}
if (head.x == this.x) {
if (head.y > this.y) this.y += 1
else this.y -= 1
return@run Point(this.x, this.y)
}
if (head.y == this.y) {
if (head.x > this.x) this.x += 1
else this.x -= 1
return@run Point(this.x, this.y)
}
if (head.x - this.x > 0 && head.y - this.y > 0) {
this.x += 1
this.y += 1
}
if (head.x - this.x < 0 && head.y - this.y > 0) {
this.x -= 1
this.y += 1
}
if (head.x - this.x > 0 && head.y - this.y < 0) {
this.x += 1
this.y -= 1
}
if (head.x - this.x < 0 && head.y - this.y < 0) {
this.x -= 1
this.y -= 1
}
return@run Point(this.x, this.y);
}
override fun equals(other: Any?): Boolean {
return if (other is Point) other.x == this.x && other.y == this.y else false;
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
}
fun main() {
fun part1(input: List<String>): Int {
val head = Point(0, 0)
val tail = Point(0, 0)
val visitedTailPlaces = ArrayList<Point>()
input.map { row -> row.split(" ") }.forEach { command ->
val direction = command[0].toCharArray()[0]
val amount = command[1].toInt()
for (i in 0 until amount) {
head.go(direction)
val visitedPoint = tail.follow(head)
if (!visitedTailPlaces.contains(visitedPoint)) visitedTailPlaces.add(visitedPoint)
}
}
return visitedTailPlaces.count()
}
fun part2(input: List<String>): Int {
val head = Point(0, 0);
val points = ArrayList<Point>()
points.add(head)
val visitedTailPlaces = ArrayList<Point>()
var nodeCounter = 0;
input.map { row -> row.split(" ") }.forEach { command ->
val direction = command[0].toCharArray()[0]
val amount = command[1].toInt()
for (i in 0 until amount) {
head.go(direction)
if (nodeCounter < 9) {
points.add(Point(0, 0))
nodeCounter++
}
for (pointNumber in 1 until points.size) {
val visitedPoint = points[pointNumber].follow(points[pointNumber - 1])
if (pointNumber == points.size - 1 && !visitedTailPlaces.contains(visitedPoint)) {
visitedTailPlaces.add(visitedPoint)
}
}
}
}
return visitedTailPlaces.count()
}
println(part1(readInput(FILES_DAY_TEST)))
check(part1(readInput(FILES_DAY_TEST)) == 13)
println(part2(readInput(FILES_DAY_TEST)))
check(part2(readInput(FILES_DAY_TEST)) == 1)
println(part2(listOf("R 5", "U 8", "L 8", "D 3", "R 17", "D 10", "L 25", "U 20")))
check(part2(listOf("R 5", "U 8", "L 8", "D 3", "R 17", "D 10", "L 25", "U 20")) == 36)
val input = readInput(FILES_DAY)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 115aba36c004bf1a759b695445451d8569178269 | 3,803 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/year2022/day-24.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2022
import lib.Grid2d
import lib.Position
import lib.TraversalAStar
import lib.aoc.Day
import lib.aoc.Part
import lib.math.Vector
import lib.memoize
fun main() {
Day(24, 2022, PartA24(), PartB24()).run()
}
open class PartA24 : Part() {
private lateinit var blizzards: (Int) -> Set<Position>
private lateinit var valley: Grid2d<Char>
private lateinit var moves: List<Vector>
private lateinit var limits: List<Iterable<Int>>
protected lateinit var target: Position
override fun parse(text: String) {
valley = Grid2d.ofLines(text.split("\n"))
moves = Position.moves(zeroMove = true)
limits = valley.limits
target = Position.at(valley.size[0] - 2, valley.size[1] - 1)
val blizzardIterator = blizzardIteratorOf(valley)
blizzards = { _: Int -> blizzardIterator.next() }.memoize()
}
private fun blizzardIteratorOf(valley: Grid2d<Char>) = sequence {
val limits = valley.size.map { 1..<it - 1 }
val moves = mapOf(
">" to Vector.at(1, 0),
"^" to Vector.at(0, -1),
"<" to Vector.at(-1, 0),
"v" to Vector.at(0, 1),
)
val posAndDir = moves.keys.flatMap { move ->
valley.findAll(move.asIterable()).map { it to moves.getValue(move) }
}
var positions = posAndDir.map { it.first }
val directions = posAndDir.map { it.second }
while (true) {
yield(positions.toSet())
positions = (positions zip directions).map { (pos, dir) ->
(pos + dir).wrapToLimits(limits)
}
}
}.iterator()
override fun compute(): String {
val start = Position.at(1, 0)
val traversal = TraversalAStar({ s, _ -> nextState(s) }, ::heuristic)
.startFrom(Pair(start, 0))
for ((position, _) in traversal) {
if (position == target) {
return (traversal.depth - 1).toString()
}
}
error("should not be reached")
}
protected fun nextState(state: Pair<Position, Int>) = sequence {
val (position, minute) = state
val blizzardPositions = blizzards(minute)
for (nextPosition in position.neighbours(moves, limits)) {
if (valley[nextPosition] != '#' && nextPosition !in blizzardPositions) {
yield(Pair(nextPosition, minute + 1) to 1f)
}
}
}.asIterable()
protected fun heuristic(state: Pair<Position, Int>): Float {
return state.first.manhattanDistance(target).toFloat()
}
override val exampleAnswer: String
get() = "18"
override val customExampleData: String?
get() = """
#.######
#>>.<^<#
#.<..<<#
#>v.><>#
#<^v^^>#
######.#
""".trimIndent()
}
class PartB24 : PartA24() {
override fun compute(): String {
val start = Position.at(1, 0)
val traversal = TraversalAStar({ s, _ -> nextState(s) }, ::heuristic)
var minute = 0
var result = 0
listOf(start to target, target to start, start to target).forEach { (start, partTarget) ->
target = partTarget
for ((position, partMinute) in traversal.startFrom(Pair(start, minute))) {
if (position == target) {
minute = partMinute
result += traversal.depth
break
}
}
}
return (result - 1).toString()
}
override val exampleAnswer: String
get() = "54"
}
| 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 3,746 | Advent-Of-Code-Kotlin | MIT License |
src/main/kotlin/day03.kt | tobiasae | 434,034,540 | false | {"Kotlin": 72901} | class Day03 : Solvable("03") {
override fun solveA(input: List<String>): String {
val gammaList = getMostCommon(input)
val epsilonList = gammaList.map { if (it == 0) 1 else 0 }
return (binaryToInt(gammaList) * binaryToInt(epsilonList)).toString()
}
override fun solveB(input: List<String>): String {
val intInput = input.map { it.map { it.toInt() - 48 } }
var pos = 0
var oxygen = intInput
while (oxygen.size > 1) {
oxygen = oxygen.filter { l -> l[pos] == getMostCommonInt(oxygen)[pos] }
pos++
}
pos = 0
var co2 = intInput
while (co2.size > 1) {
co2 = co2.filter { it[pos] != getMostCommonInt(co2)[pos] }
pos++
}
return (binaryToInt(oxygen[0]) * binaryToInt(co2[0])).toString()
}
private fun getMostCommon(input: List<String>): List<Int> {
return getMostCommonInt(input.map { it.map { it.toInt() - 48 } })
}
private fun getMostCommonInt(input: List<List<Int>>): List<Int> {
return input.reduce { l, r -> l.zip(r) { a, b -> a + b } }.map {
if (it >= input.size - it) 1 else 0
}
}
private fun binaryToInt(list: List<Int>): Int {
return list.reversed().reduceIndexed { i, l, r -> l + (r shl i) }
}
}
| 0 | Kotlin | 0 | 0 | 16233aa7c4820db072f35e7b08213d0bd3a5be69 | 1,343 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/eu/qiou/aaf4k/finance/Leistungsmatrix.kt | 6234456 | 191,817,083 | false | null | package eu.qiou.aaf4k.finance
import eu.qiou.aaf4k.util.sortedWithOrderList
/**
* the matrix of the contribution(Leistungsaustausch) between the auxiliary cost centers (Hilfskostenstellen) and from
* auxiliary cost centers to the primary cost centers
*
* each row of the matrix contains the contributions to all the cost centers (incl. itself)
*
*/
data class Leistungsmatrix(
private val matrix: Array<Array<Double>>,
val costCenters: Array<Kostenstelle>,
val indirectCosts: Array<Double>
) {
init {
// "The matrix is not square!"
val size = matrix.size
assert(matrix.isEmpty() || matrix.all { it.size == size })
assert(costCenters.size == size)
assert(size == indirectCosts.size)
assert(size == costCenters.map { it.id }.toSet().size)
}
private val n = matrix.size
private val mapPos2CostCenter = costCenters.mapIndexed { index, kostenstelle -> index to kostenstelle }.toMap()
private val mapCostCenter2Pos = costCenters.mapIndexed { index, kostenstelle -> kostenstelle to index }.toMap()
fun anbauVerfahren(): Array<Pair<Kostenstelle, Array<Double>>> {
val orderList: List<Int> = costCenters.map { if (it.isAuxiliary) 0 else 1 }
val costTotal = matrix.mapIndexed { index, doubles ->
if (orderList[index] == 1)
indirectCosts[index]
else
indirectCosts[index] / doubles.foldIndexed(0.0) { i, acc, d -> acc + d * orderList[i] }
}
return matrix.mapIndexed { i, data ->
val total = costTotal[i]
mapPos2CostCenter[i]!! to (if (orderList[i] == 1)
data.mapIndexed { index, d ->
if (index == i) total else 0.0
}
else
data.mapIndexed { index, d ->
total * orderList[index] * d
}).toTypedArray()
}.toTypedArray()
}
fun stufenleiterVerfahren(): Array<Pair<Kostenstelle, Array<Double>>> {
// recording the cascading of the indirectCosts
var costTemp = indirectCosts
var orderList: List<Int> = listOf()
var matrixTemp = matrix
// sort based on innerbetrieblicher Leistungsverrechnung, desc
return (costCenters.zip(matrix).filter { it.first.isAuxiliary }.map {
it.first to
it.second.reduceIndexed { index, acc, d ->
acc + if ((mapPos2CostCenter[index] ?: error("")).isAuxiliary) d else 0.0
} / it.second.reduce { acc, d -> acc + d } * indirectCosts[mapCostCenter2Pos[it.first]!!]
}.sortedByDescending { it.second }.map { it.first } + costCenters.filter { !it.isAuxiliary }).apply {
orderList =
this.mapIndexed { index, kostenstelle -> (mapCostCenter2Pos[kostenstelle] ?: error("")) to index }
.sortedBy { it.first }.map { it.second }
costTemp = costTemp.toList().sortedWithOrderList(orderList).toTypedArray()
matrixTemp = matrix.toList().sortedWithOrderList(orderList).map {
it.toList().sortedWithOrderList(orderList).toTypedArray()
}.toTypedArray()
}.mapIndexed {
// idx the index in the sorted array with hilfkostenstelle at the beginning
idx, x ->
val index = idx
val contribution = matrixTemp[index]
val cost = costTemp[idx]
// excluding the contribution to itself
val total =
if (x.isAuxiliary) cost / contribution.mapIndexed { i, d -> if (i > idx) d else 0.0 }.reduce { acc, d -> acc + d } else cost
val distributed = if (x.isAuxiliary) contribution.mapIndexed { i, d -> if (i > idx) d * total else 0.0 }
else contribution.mapIndexed { i, d -> if (i == idx) cost else 0.0 }
// cascading to the next level
costTemp = costTemp.zip(distributed)
.foldIndexed(listOf<Double>()) { i, acc, pair -> acc + listOf(if (i > idx) pair.first + pair.second else 0.0) }
.toTypedArray()
x to distributed.toTypedArray()
}.toTypedArray()
}
fun gleichungsVerfahren(): Array<Pair<Kostenstelle, Array<Double>>> {
// two type of situation
// 1. the Haupt-Kostenstellen has explicit output Amount to certain Kostentraeger
// 2. or by default with the output amount to be 1 and matrix reflects only innerbetriebliche Verrechnung
val isDefaultSituation = matrix.any {
it.reduce { acc, d -> acc + d } == 0.0
}
val contributions = matrix.mapIndexed { index, v ->
val kostenstelle = mapPos2CostCenter[index]!!
(1..n).map {
val value = v.reduce { acc, d -> acc + d }
if (it - 1 == index) {
if (isDefaultSituation) {
-1.0 * if (kostenstelle.isAuxiliary)
value
else
1.0
} else {
-1.0 * value
}
} else
0.0
}.toDoubleArray()
}.toTypedArray()
return Matrix(matrix.mapIndexed { index, doubles ->
val kostenstelle = mapPos2CostCenter[index]!!
doubles.apply {
// if situation 1 , set the contribution of Hauptkostenstellen to itself to 0
if (!isDefaultSituation && !kostenstelle.isAuxiliary) {
this[index] = 0.0
}
}.toDoubleArray()
}.toTypedArray()).transpose().plus(
Matrix(contributions)
).solve(
Matrix(
indirectCosts.map {
doubleArrayOf(it * -1.0)
}.toTypedArray()
)
).data.mapIndexed { index, doubles ->
mapPos2CostCenter[index]!! to doubles.toTypedArray()
}.toTypedArray()
}
} | 2 | Kotlin | 0 | 0 | dcd0ef0bad007e37a08ce5a05af52990c9d904e0 | 6,051 | aaf4k-base | MIT License |
src/Day15.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | import kotlin.streams.toList
fun main() {
class Node(val cost: Int, val pos: Pair<Int, Int>) {
var parent: Node? = null
var gScore = Int.MAX_VALUE
fun addParent(n: Node) {
parent = n
this.gScore = this.cost + n.gScore
}
fun getFScore(end: Node) = gScore + h(end)
fun h(end: Node): Int {
return end.pos.first - pos.first + end.pos.second - pos.second
}
fun potNeighbors(): List<Pair<Int, Int>> {
// return (-1..1).flatMap {
// (-1..1).filter { jt -> it != 0 && jt != 0 }.map { jt -> Pair(pos.first + it, pos.second + jt) }
// }
return listOf(
Pair(pos.first - 1, pos.second),
Pair(pos.first + 1, pos.second),
Pair(pos.first, pos.second - 1),
Pair(pos.first, pos.second + 1)
)
}
override fun hashCode(): Int {
return pos.hashCode()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Node
if (pos != other.pos) return false
return true
}
override fun toString(): String {
return cost.toString()
}
}
fun printNodes(field: Array<Array<Node>>) {
for (r in field) {
for (n in r) {
print(n)
}
println()
}
}
fun part1(input: Array<Array<Node>>): Int {
val openSet = HashSet<Node>()
val closedSet = HashSet<Node>()
input[0][0].gScore = 0
openSet.add(input[0][0])
val goal = input.last().last()
while (openSet.isNotEmpty()) {
val current = openSet.minByOrNull { it.getFScore(goal) }!!
if (current == goal) return goal.gScore
openSet.remove(current)
closedSet.add(current)
for (neiPos in current.potNeighbors()) {
if (!input.isIndex(neiPos.first) || !input[neiPos.first].isIndex(neiPos.second)) continue
val nei = input[neiPos.first][neiPos.second]
if (closedSet.contains(nei)) continue
if (current.gScore + nei.cost < nei.gScore) nei.addParent(current)
if (!openSet.contains(nei)) openSet.add(nei)
}
// printNodes(openSet, input)
// println("----------------------")
}
return -99
}
fun expandInput(input: Array<Array<Node>>): Array<Array<Node>> {
val height = input.size
val width = input[0].size
return Array(height * 5) {
Array(width * 5) { jt ->
if (input.isIndex(it) && input[it].isIndex(jt)) input[it][jt]
else Node(
(input[it % height][jt % width].cost + it / height + jt / width).let { if (it > 9) it % 10 + 1 else it },
Pair(it, jt)
)
}
}
}
fun part2(input: Array<Array<Node>>): Int {
// println(tmp.joinToString { it.reversed().toString() + "\n" })
return part1(expandInput(input))
}
fun preprocessing(input: String): Array<Array<Node>> {
val tmp =
input.trim().split("\n").map { it.trim().chars().map { c -> c.toChar().digitToInt() }.toList() }.toList()
return Array(tmp.size) {
Array(tmp[it].size) { jt ->
Node(tmp[it][jt], Pair(it, jt))
}
}
}
val realInp = read_testInput("real15")
val testInp = read_testInput("test15")
// val testInp = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
// printNodes(expandInput(arrayOf(arrayOf(Node(8, Pair(0, 0))))))
// println("Test 1: ${part1(preprocessing(testInp))}")
// println("Real 1: ${part1(preprocessing(realInp))}")
// println("-----------")
// println("Test 2: ${part2(preprocessing(testInp))}")
println("Real 2: ${part2(preprocessing(realInp))}")
}
| 0 | Kotlin | 0 | 0 | 3e33ab078f8f5413fa659ec6c169cd2f99d0b374 | 4,131 | advent_of_code21_kotlin | Apache License 2.0 |
src/main/java/dev/haenara/mailprogramming/solution/y2020/m01/d06/Solution200106.kt | HaenaraShin | 226,032,186 | false | null | import dev.haenara.mailprogramming.solution.Solution
import kotlin.math.max
import kotlin.math.min
/**
* 매일프로그래밍 2020. 01. 06
* 간격(interval)로 이루어진 배열이 주어지면, 겹치는 간격 원소들을 합친 새로운 배열을 만드시오.
* 간격은 시작과 끝으로 이루어져 있으며 시작은 끝보다 작거나 같습니다.
* Given a list of intervals, merge intersecting intervals.
*
* Input: {{2,4}, {1,5}, {7,9}}
* Output: {{1,5}, {7,9}}
* Input: {{3,6}, {1,3}, {2,4}}
* Output: {{1,6}}
*
* 풀이 :
*
*/
class Solution200106 : Solution<Array<Pair<Int, Int>>, Array<Pair<Int, Int>>> {
override fun solution(input: Array<Pair<Int, Int>>): Array<Pair<Int, Int>> {
val sum = arrayListOf<Pair<Int, Int>>()
for ((index, toMerge) in input.withIndex()) {
sum.merge(toMerge)
}
return sum.toTypedArray()
}
private fun ArrayList<Pair<Int, Int>>.merge(input: Pair<Int, Int>) {
var toMerge = input
if (isEmpty()) {
add(toMerge)
return
}
// TO REFACTORING
// 처음부터 하나하나 비교하는 대신 binary search 하여 성능 개선할 여지가 있다.
for ((index, summed) in this.withIndex()) {
if (summed == toMerge) {
return
}
val left = left(summed, toMerge)
val right = right(summed, toMerge)
if (left == right) {
remove(summed)
// TO REFACTORING
// 재귀적 호출로 성능이 너무 떨어질 수 있다.
merge(left)
return
}
if (isOverlapped(left, right)) {
remove(toMerge)
remove(summed)
// TO REFACTORING
// 재귀적 호출로 성능이 너무 떨어질 수 있다.
merge(Pair(min(left.first, right.first), max(left.second, right.second)))
return
}
}
add(toMerge)
}
private fun left(first : Pair<Int, Int>, second : Pair<Int, Int>) : Pair<Int, Int>{
return if (first.first < second.first) {
first
} else {
second
}
}
private fun right(first : Pair<Int, Int>, second : Pair<Int, Int>) : Pair<Int, Int>{
return if (first.second >= second.second) {
first
} else {
second
}
}
private fun isOverlapped(left : Pair<Int, Int>, right : Pair<Int, Int>) : Boolean {
return left.second >= right.first || left.first == right.first || left.second == right.second
}
} | 0 | Kotlin | 0 | 7 | b5e50907b8a7af5db2055a99461bff9cc0268293 | 2,696 | MailProgramming | MIT License |
src/main/kotlin/adventofcode/day3.kt | Kvest | 163,103,813 | false | null | package adventofcode
import java.io.File
import kotlin.math.max
fun main(args: Array<String>) {
first3(File("./data/day3_1.txt").readLines())
second3(File("./data/day3_2.txt").readLines())
}
fun first3(data: List<String>) {
val regex = Regex("#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)")
var w = 0
var h = 0
val items = data.mapNotNull {
regex.find(it)?.let {
val (id, left, top, width, height) = it.destructured
val item = Item(id.toInt(), left.toInt(), top.toInt(), width.toInt(), height.toInt())
w = max(w, item.left + item.width)
h = max(h, item.top + item.height)
return@mapNotNull item
}
null
}
val field = IntArray(w * h) { 0 }
items.forEach {
(it.top until (it.top + it.height)).forEach { i ->
(it.left until (it.left + it.width)).forEach { j ->
++field[i * w + j]
}
}
}
val count = field.count { it > 1 }
println(count)
}
fun second3(data: List<String>) {
var regex = Regex("#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)")
val items = data.mapNotNull {
regex.find(it)?.let {
val (id, left, top, width, height) = it.destructured
return@mapNotNull ItemRange(
id.toInt(),
left.toInt() until left.toInt() + width.toInt(),
top.toInt() until top.toInt() + height.toInt())
}
null as? ItemRange
}
items.forEach { i ->
var intersects = false
items.forEach { j ->
if (i.id != j.id && i.intersect(j)) {
intersects = true
}
}
if (!intersects) {
println(i.id)
}
}
}
data class Item(val id: Int, val left: Int, val top: Int, val width: Int, val height: Int)
data class ItemRange(val id: Int, val width: IntRange, val height: IntRange) {
fun intersect(other: ItemRange): Boolean {
return width.intersect(other.width).isNotEmpty() && height.intersect(other.height).isNotEmpty()
}
}
| 0 | Kotlin | 0 | 0 | d94b725575a8a5784b53e0f7eee6b7519ac59deb | 2,105 | aoc2018 | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2022/Day15.kt | colinodell | 572,710,708 | false | {"Kotlin": 105421} | package com.colinodell.advent2022
import kotlin.math.abs
class Day15(input: List<String>) {
private val regex = Regex("x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
private val sensors = input.map { line ->
regex.find(line)!!.destructured.let { (sx, sy, bx, by) ->
val sensor = Vector2(sx.toInt(), sy.toInt())
val beacon = Vector2(bx.toInt(), by.toInt())
Sensor(sensor, beacon)
}
}
fun solvePart1(row: Int) = findDisallowedPositions(row).sumOf { it.count() } - 1
fun solvePart2(maxY: Int): Long {
for (y in 0..maxY) {
val disallowedRanges = findDisallowedPositions(y).clamp(0, 4000000)
// Assume the distress beacon is not coming from the very edges of our search area
// With this assumption, we can simply check if the range has a gap somewhere in the middle
if (disallowedRanges.size == 1) {
continue
}
// Gap found! Assume there's only one gap, so the x coordinate is just 1 higher than the first range
val x = disallowedRanges[0].last + 1
return x.toLong() * 4000000L + y.toLong()
}
error("No solution found")
}
private fun findDisallowedPositions(y: Int): List<IntRange> {
val disallowedRanges = mutableSetOf<IntRange>()
for (sensor in sensors) {
val dy = abs(y - sensor.position.y)
if (dy > sensor.radius) {
continue
}
val dx = sensor.radius - dy
disallowedRanges.add(-dx + sensor.position.x..dx + sensor.position.x)
}
return disallowedRanges.simplify()
}
private class Sensor(val position: Vector2, val nearestBeacon: Vector2) {
val radius: Int by lazy {
position.manhattanDistanceTo(nearestBeacon)
}
}
}
| 0 | Kotlin | 0 | 1 | 32da24a888ddb8e8da122fa3e3a08fc2d4829180 | 1,913 | advent-2022 | MIT License |
src/main/kotlin/com/github/dangerground/aoc2020/Day10.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
fun main() {
val process = Day10(DayInput.asIntList(10))
println("result part 1: ${process.part1()}")
println("result part 2: ${process.part2()}")
}
class Day10(adapters: List<Int>) {
private val sortedAdapters = mutableListOf<List<Int>>()
init {
val input = adapters.toMutableList()
input.add(0)
var newList1 = mutableListOf<Int>()
input.sorted().forEach {
if (newList1.isNotEmpty() && newList1.last() + 3 == it) {
sortedAdapters.add(newList1)
newList1 = mutableListOf()
}
newList1.add(it)
}
if (!newList1.isEmpty()) {
sortedAdapters.add(newList1)
}
}
fun part1(): Int {
val oneJoltDiff = sortedAdapters.map { it.size-1 }.sum()
val threeJoltDiff = sortedAdapters.size
return oneJoltDiff * threeJoltDiff;
}
fun part2(): Long {
return sortedAdapters
.map { permutations(it) }
.reduce { i1, i2 -> i1 * i2 }
}
private fun permutations(i: List<Int>): Long {
// copied values from recursive function for all possible ways
// TODO find a reprentative mathematical way of computation
return when (i.size) {
5 -> 7
4 -> 4
3 -> 2
2 -> 1
1 -> 1
else -> 0
}
}
}
| 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 1,500 | adventofcode-2020 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MakeArrayStrictlyIncreasing.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Arrays
import kotlin.math.min
/**
* 1187. Make Array Strictly Increasing
* @see <a href="https://leetcode.com/problems/make-array-strictly-increasing/">Source</a>
*/
fun interface MakeArrayStrictlyIncreasing {
operator fun invoke(arr1: IntArray, arr2: IntArray): Int
fun bisectRight(arr: IntArray, value: Int): Int {
var left = 0
var right = arr.size
while (left < right) {
val mid = (left + right) / 2
if (arr[mid] <= value) {
left = mid + 1
} else {
right = mid
}
}
return left
}
}
class MakeArrayStrictlyIncreasingTopDown : MakeArrayStrictlyIncreasing {
private val dp: MutableMap<Pair<Int, Int>, Int> = HashMap()
companion object {
private const val COST_LIMIT = 2001
}
override operator fun invoke(arr1: IntArray, arr2: IntArray): Int {
arr2.sort()
val answer = dfs(0, -1, arr1, arr2)
return if (answer < COST_LIMIT) answer else -1
}
private fun dfs(i: Int, prev: Int, arr1: IntArray, arr2: IntArray): Int {
if (i == arr1.size) {
return 0
}
if (dp.containsKey(Pair(i, prev))) {
return dp[Pair(i, prev)]!!
}
var cost = COST_LIMIT
// If arr1[i] is already greater than prev, we can leave it be.
if (arr1[i] > prev) {
cost = dfs(i + 1, arr1[i], arr1, arr2)
}
// Find a replacement with the smallest value in arr2.
val idx = bisectRight(arr2, prev)
// Replace arr1[i], with a cost of 1 operation.
if (idx < arr2.size) {
cost = min(cost, 1 + dfs(i + 1, arr2[idx], arr1, arr2))
}
dp[Pair(i, prev)] = cost
return cost
}
}
class MakeArrayStrictlyIncreasingBottomUp : MakeArrayStrictlyIncreasing {
override operator fun invoke(arr1: IntArray, arr2: IntArray): Int {
var dp: MutableMap<Int, Int> = HashMap()
Arrays.sort(arr2)
val n: Int = arr2.size
dp[-1] = 0
for (i in arr1.indices) {
val newDp: MutableMap<Int, Int> = HashMap()
for (prev in dp.keys) {
if (arr1[i] > prev) {
newDp[arr1[i]] = min(
newDp.getOrDefault(arr1[i], Int.MAX_VALUE),
dp[prev]!!,
)
}
val idx = bisectRight(arr2, prev)
if (idx < n) {
newDp[arr2[idx]] =
min(newDp.getOrDefault(arr2[idx], Int.MAX_VALUE), 1 + dp[prev]!!)
}
}
dp = newDp
}
var answer = Int.MAX_VALUE
for (value in dp.values) {
answer = min(answer, value)
}
return if (answer == Int.MAX_VALUE) -1 else answer
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,539 | kotlab | Apache License 2.0 |
src/main/kotlin/de/dikodam/day17/Day17.kt | dikodam | 317,290,436 | false | null | package de.dikodam.day17
import de.dikodam.AbstractDay
fun main() {
Day17()()
}
data class Coordinates3D(val x: Int, val y: Int, val z: Int)
data class Coordinates4D(val w: Int, val x: Int, val y: Int, val z: Int)
private typealias GameState3D = Set<Coordinates3D>
private typealias GameState4D = Set<Coordinates4D>
class Day17 : AbstractDay() {
override fun task1(): String {
var gameState = parseInitialState3D(Day17Input().input.lines())
println("initial count: ${gameState.count()}")
repeat(6) { i ->
gameState = computeNextState3D(gameState)
println("count after round ${i + 1}: ${gameState.count()}")
}
return "${gameState.count()}"
}
fun parseInitialState3D(lines: List<String>): GameState3D {
val interpretLine: (Int, String) -> List<Triple<Int, Int, Char>> =
{ xIndex, line -> line.mapIndexed { yIndex, char: Char -> Triple(xIndex, yIndex, char) } }
return lines.flatMapIndexed(interpretLine)
.filter { (_, _, c) -> c == '#' }
.map { (x, y) -> Coordinates3D(x, y, 0) }
.toSet()
}
fun computeNextState3D(state: GameState3D): GameState3D {
return state.determinePotential3DCandidates()
.filter { candidate -> determineNextLiveness(candidate, state) }
.toSet()
}
fun GameState3D.determinePotential3DCandidates(): Set<Coordinates3D> =
this.flatMap { determine3DNeighbors(it, includeSelf = true) }
.toSet()
fun determineNextLiveness(cube: Coordinates3D, state: GameState3D): Boolean {
val livingNeighborsCount = determine3DNeighbors(cube, includeSelf = false)
.filter { neighbor -> state.contains(neighbor) }
.count()
val isActive = state.contains(cube)
return if (isActive) {
livingNeighborsCount == 2 || livingNeighborsCount == 3
} else {
livingNeighborsCount == 3
}
// equivalent expression, but I find it harder to read:
// return livingNeighborsCount == 3 || (livingNeighborsCount == 2 && state.contains(cube))
}
fun determine3DNeighbors(cube: Coordinates3D, includeSelf: Boolean = false): Set<Coordinates3D> {
val accumulator = mutableListOf<Coordinates3D>()
for (a in (cube.x - 1)..(cube.x + 1)) {
for (b in (cube.y - 1)..(cube.y + 1)) {
for (c in (cube.z - 1)..(cube.z + 1)) {
accumulator.add(Coordinates3D(a, b, c))
}
}
}
if (!includeSelf) {
accumulator.remove(cube)
}
return accumulator.toSet()
}
override fun task2(): String {
var gameState = parseInitialState4D(Day17Input().input.lines())
println("initial count: ${gameState.count()}")
repeat(6) { i ->
gameState = computeNextState4D(gameState)
println("count after round ${i + 1}: ${gameState.count()}")
}
return "${gameState.count()}"
}
fun parseInitialState4D(lines: List<String>): GameState4D {
val interpretLine: (Int, String) -> List<Triple<Int, Int, Char>> =
{ xIndex, line -> line.mapIndexed { yIndex, char: Char -> Triple(xIndex, yIndex, char) } }
return lines.flatMapIndexed(interpretLine)
.filter { (_, _, c) -> c == '#' }
.map { (x, y) -> Coordinates4D(x, y, 0, 0) }
.toSet()
}
fun computeNextState4D(state: GameState4D): GameState4D {
return state.determinePotential4DCandidates()
.filter { candidate -> determineNextLiveness(candidate, state) }
.toSet()
}
fun GameState4D.determinePotential4DCandidates(): Set<Coordinates4D> =
this.flatMap { determine4DNeighbors(it, includeSelf = true) }
.toSet()
fun determine4DNeighbors(cube: Coordinates4D, includeSelf: Boolean = false): Set<Coordinates4D> {
val accumulator = mutableListOf<Coordinates4D>()
for (a in (cube.w - 1)..(cube.w + 1)) {
for (b in (cube.x - 1)..(cube.x + 1)) {
for (c in (cube.y - 1)..(cube.y + 1)) {
for (d in (cube.z - 1)..(cube.z + 1)) {
accumulator.add(Coordinates4D(a, b, c, d))
}
}
}
}
if (!includeSelf) {
accumulator.remove(cube)
}
return accumulator.toSet()
}
fun determineNextLiveness(cube: Coordinates4D, state: GameState4D): Boolean {
val livingNeighborsCount = determine4DNeighbors(cube, includeSelf = false)
.filter { neighbor -> state.contains(neighbor) }
.count()
val isActive = state.contains(cube)
return if (isActive) {
livingNeighborsCount == 2 || livingNeighborsCount == 3
} else {
livingNeighborsCount == 3
}
}
}
| 0 | Kotlin | 0 | 0 | dc70d185cb9f6fd7d69bd1fe74c6dfc8f4aac097 | 4,978 | adventofcode2020 | MIT License |
src/day02/Day02.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | @file:Suppress("MagicNumber")
package day02
import day02.Type.*
import readInput
enum class Type(val value: Int) {
ROCK(1), PAPER(2), SCISSOR(3)
}
fun main() {
fun translate(s: String): Type = when (s) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSOR
else -> error("")
}
fun winedPrice(game: Pair<Type, Type>): Int = when (game) {
ROCK to PAPER -> 6
PAPER to SCISSOR -> 6
SCISSOR to ROCK -> 6
ROCK to SCISSOR -> 0
PAPER to ROCK -> 0
SCISSOR to PAPER -> 0
else -> 3
}
fun calculateScore(it: Pair<Type, Type>) = it.second.value + winedPrice(it)
fun cleanUpInput(input: List<String>) = input.map { it.split(" ") }
.map { translate(it[0]) to translate(it[1]) }
fun part1(input: List<String>): Int = cleanUpInput(input).sumOf {
calculateScore(it)
}
fun calculateGame(game: Pair<Type, Type>): Type =
when (game.second) {
ROCK -> {
when (game.first) {
ROCK -> SCISSOR
PAPER -> ROCK
SCISSOR -> PAPER
}
}
PAPER -> game.first
SCISSOR -> {
when (game.first) {
ROCK -> PAPER
PAPER -> SCISSOR
SCISSOR -> ROCK
}
}
}
fun part2(input: List<String>): Int = cleanUpInput(input).map {
it.first to calculateGame(it)
}.sumOf {
calculateScore(it)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day02/Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
val input = readInput("day02/Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 1,865 | advent-of-code-kotlin-2022 | Apache License 2.0 |
Kotlin/src/CombinationSumII.kt | TonnyL | 106,459,115 | false | null | /**
* Given a collection of candidate numbers (C) and a target number (T),
* find all unique combinations in C where the candidate numbers sums to T.
*
* Each number in C may only be used once in the combination.
*
* Note:
* All numbers (including target) will be positive integers.
* The solution set must not contain duplicate combinations.
* For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
* A solution set is:
* [
* [1, 7],
* [1, 2, 5],
* [2, 6],
* [1, 1, 6]
* ]
*
* Accepted.
*/
class CombinationSumII {
fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> {
if (candidates.isEmpty()) {
return emptyList()
}
val lists = mutableListOf<List<Int>>()
candidates.sort()
dfs(candidates, target, ArrayList(), lists, 0)
return lists
}
private fun dfs(candidates: IntArray, target: Int, path: MutableList<Int>, ret: MutableList<List<Int>>, index: Int) {
if (target < 0) {
return
}
if (target == 0) {
ret.add(ArrayList(path))
return
}
for (i in index until candidates.size) {
if (i != index && candidates[i] == candidates[i - 1]) {
continue
}
path.add(candidates[i])
dfs(candidates, target - candidates[i], path, ret, i + 1)
path.removeAt(path.size - 1)
}
}
}
| 1 | Swift | 22 | 189 | 39f85cdedaaf5b85f7ce842ecef975301fc974cf | 1,461 | Windary | MIT License |
src/ca/josue/rational/Rational.kt | josue-lubaki | 432,939,460 | false | {"Kotlin": 4542} | package ca.josue.rational
import java.math.BigInteger
class Rational (private val numerator: BigInteger, private val denominator: BigInteger) : Comparable<Rational>{
init {
if (denominator == BigInteger.ZERO)
throw IllegalArgumentException("Denominator cannot be 0")
}
// Redefinition des opérateurs
operator fun plus(other: Rational): Rational {
val num = (numerator * other.denominator) + (denominator * other.numerator)
val den = denominator * other.denominator
return num.divBy(den)
}
operator fun minus(other: Rational) : Rational{
val num = (numerator * other.denominator) - (denominator * other.numerator)
val den = denominator * other.denominator
return num.divBy(den)
}
operator fun times(other: Rational): Rational{
return (numerator * other.numerator).divBy(denominator * other.denominator)
}
operator fun div(other: Rational):Rational{
return (numerator * other.denominator).divBy(denominator * other.numerator)
}
operator fun unaryMinus(): Rational = Rational(numerator.negate(),denominator)
override fun compareTo(other: Rational): Int {
return (numerator * other.denominator).compareTo(denominator * other.numerator)
}
private fun simplify(rational: Rational): Rational{
val greatCommonDivisor = rational.numerator.gcd(rational.denominator)
val num = rational.numerator / greatCommonDivisor
val den = rational.denominator / greatCommonDivisor
return Rational(num, den)
}
private fun formatRational(): String = "$numerator/$denominator"
override fun equals(other: Any?): Boolean {
if (this === other) return true
other as Rational
val thisSimplified = simplify(this)
val otherSimplified = simplify(other)
val thisAsDouble = thisSimplified.numerator.toDouble() / thisSimplified.denominator.toDouble()
val otherAsDouble = otherSimplified.numerator.toDouble() / otherSimplified.denominator.toDouble()
return thisAsDouble == otherAsDouble
}
override fun toString(): String {
val shouldBeOneNumber = denominator == BigInteger.ONE || numerator % denominator == BigInteger.ZERO
return when {
shouldBeOneNumber -> (numerator / denominator).toString()
else -> {
val thisSimplified = simplify(this)
if (thisSimplified.denominator < BigInteger.ZERO || (thisSimplified.numerator < BigInteger.ZERO && thisSimplified.denominator < BigInteger.ZERO)){
Rational(thisSimplified.numerator.negate(), thisSimplified.denominator.negate()).formatRational()
}
else{
Rational(thisSimplified.numerator, thisSimplified.denominator).formatRational()
}
}
}
}
override fun hashCode(): Int {
var result = numerator.hashCode()
result = 31 * result + denominator.hashCode()
return result
}
}
fun String.toRational():Rational{
val ratio = split('/')
return when (ratio.size) {
1 -> Rational(ratio[0].toBigInteger(), BigInteger.ONE)
2 -> Rational(ratio[0].toBigInteger(), ratio[1].toBigInteger())
else -> throw IllegalArgumentException("Invalid format")
}
}
// Infix
infix fun Int.divBy(other: Int):Rational = Rational(toBigInteger(), other.toBigInteger())
infix fun Long.divBy(other: Long): Rational = Rational(toBigInteger(), other.toBigInteger())
infix fun BigInteger.divBy(other: BigInteger) = Rational(this, other)
fun main() {
val half = 1 divBy 2
val third = 1 divBy 3
val sum: Rational = half + third
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 | 1 | cbeb74d26fb742ecaee0c4f3bb0ab77d0ea9c822 | 4,542 | Rational | MIT License |
src/day19/Day19.kt | spyroid | 433,555,350 | false | null | package day19
import readRawInput
import kotlin.math.abs
import kotlin.system.measureTimeMillis
class Scanners(input: String) {
private val scanners = input
.split("\n\n")
.filter { it.isNotEmpty() }
.map { s ->
Scanner(
s.trim().lines().drop(1)
.map { it.split(",") }
.map { (x, y, z) -> Point3D(x.toInt(), y.toInt(), z.toInt()) }
.toSet()
)
}
fun assembleMap(): AssembledMap {
val foundBeacons = scanners.first().beacons.toMutableSet()
val foundScannersPositions = mutableSetOf(Point3D(0, 0, 0))
val remaining = ArrayDeque<Scanner>().apply { addAll(scanners.drop(1)) }
while (remaining.isNotEmpty()) {
val candidate = remaining.removeFirst()
when (val transformedCandidate = Scanner(foundBeacons).getTransformedIfOverlap(candidate)) {
null -> remaining.add(candidate)
else -> {
foundBeacons.addAll(transformedCandidate.beacons)
foundScannersPositions.add(transformedCandidate.position)
}
}
}
return AssembledMap(foundBeacons, foundScannersPositions)
}
private data class Scanner(val beacons: Set<Point3D>) {
fun allRotations() = beacons.map { it.allRotations() }.transpose().map { Scanner(it) }
fun getTransformedIfOverlap(otherScanner: Scanner): TransformedScanner? {
return otherScanner.allRotations().firstNotNullOfOrNull { otherReoriented ->
beacons.firstNotNullOfOrNull { first ->
otherReoriented.beacons.firstNotNullOfOrNull { second ->
val otherPosition = first - second
val otherTransformed = otherReoriented.beacons.map { otherPosition + it }.toSet()
when ((otherTransformed intersect beacons).size >= 12) {
true -> TransformedScanner(otherTransformed, otherPosition)
false -> null
}
}
}
}
}
private fun List<Set<Point3D>>.transpose(): List<Set<Point3D>> {
return when (all { it.isNotEmpty() }) {
true -> listOf(map { it.first() }.toSet()) + map { it.drop(1).toSet() }.transpose()
false -> emptyList()
}
}
}
private data class TransformedScanner(val beacons: Set<Point3D>, val position: Point3D)
data class AssembledMap(val beacons: Set<Point3D>, val scannersPositions: Set<Point3D>)
data class Point3D(val x: Int, val y: Int, val z: Int) {
operator fun plus(other: Point3D) = Point3D(x + other.x, y + other.y, z + other.z)
operator fun minus(other: Point3D) = Point3D(x - other.x, y - other.y, z - other.z)
infix fun distanceTo(other: Point3D) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z)
fun allRotations(): Set<Point3D> {
return setOf(
Point3D(x, y, z), Point3D(x, -z, y), Point3D(x, -y, -z), Point3D(x, z, -y), Point3D(-x, -y, z),
Point3D(-x, -z, -y), Point3D(-x, y, -z), Point3D(-x, z, y), Point3D(-z, x, -y), Point3D(y, x, -z),
Point3D(z, x, y), Point3D(-y, x, z), Point3D(z, -x, -y), Point3D(y, -x, z), Point3D(-z, -x, y),
Point3D(-y, -x, -z), Point3D(-y, -z, x), Point3D(z, -y, x), Point3D(y, z, x), Point3D(-z, y, x),
Point3D(z, y, -x), Point3D(-y, z, -x), Point3D(-z, -y, -x), Point3D(y, -z, -x),
)
}
}
}
fun main() {
fun part1(input: String) = Scanners(input).assembleMap().beacons.size
fun part2(input: String) = Scanners(input).assembleMap().scannersPositions.let { positions ->
positions.flatMapIndexed { index, first -> positions.drop(index + 1).map { second -> first to second } }
.maxOf { (first, second) -> first distanceTo second }
}
val testData = readRawInput("day19/test")
val inputData = readRawInput("day19/input")
var res1 = part1(testData)
check(res1 == 79) { "Expected 79 but got $res1" }
measureTimeMillis { res1 = part1(inputData) }
.also { time ->
println("⭐️ Part1: $res1 in $time ms")
}
measureTimeMillis { res1 = part2(inputData) }
.also { time ->
println("⭐️ Part2: $res1 in $time ms")
}
}
| 0 | Kotlin | 0 | 0 | 939c77c47e6337138a277b5e6e883a7a3a92f5c7 | 4,518 | Advent-of-Code-2021 | Apache License 2.0 |
src/main/aoc2019/Day16.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2019
import kotlin.math.abs
class Day16(input: String) {
val parsedInput = input.chunked(1).map { it.toInt() }
private fun patternLookup(currentDigit: Int, index: Int): Int {
// digit 0: length 4, digit 1: length 8, ...
val patternLength = 4 * (currentDigit + 1)
// First time the pattern is applied it's shifted by one step
val positionInPattern = (index + 1) % patternLength
// The pattern have four different sections, divide by current digit to
// get a 0-3 indicating in which section the index is
// Sections: 0, 1, 0, -1
return when(positionInPattern / (currentDigit + 1)) {
1 -> 1
3 -> -1
else -> 0
}
}
private fun runPhases(list: List<Int>): String {
val ret = list.toIntArray()
repeat(100) {
for (currentElement in ret.indices) {
var theSum = 0
// As learned in part two (see below) all digits before currentElement is 0, so those can be skipped.
for (i in currentElement until ret.size) {
theSum += ret[i] * patternLookup(currentElement, i)
}
ret[currentElement] = abs(theSum) % 10
}
}
return ret.take(8).joinToString("")
}
fun solvePart1(): String {
return runPhases(parsedInput)
}
private fun valueStartingAt(offset: Int, list: List<Int>): String {
/*
for line 0, you have 0 zeros at the start of phase
for line 1, you have 1 zero at the start
for line offset, you have offset zeros at the start
==> values of digits only depends on digits after the current digit
offset > input.size / 2 ==> first offset zeros, then rest is ones
==> for any digit, add it's current value with the new value of the digit to the right
all together means, start from last digit work backwards to the offset digit
*/
val digits = list.subList(offset, list.size).toIntArray()
repeat(100) {
var prev = 0
for (i in digits.size - 1 downTo 0) {
digits[i] = (digits[i] + prev) % 10
prev = digits[i]
}
}
return digits.take(8).joinToString("")
}
fun solvePart2(): String {
val realInput = mutableListOf<Int>()
repeat(10_000) {
realInput.addAll(parsedInput)
}
val messageOffset = parsedInput.subList(0, 7).joinToString(("")).toInt()
return valueStartingAt(messageOffset, realInput)
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,634 | aoc | MIT License |
src/main/kotlin/g0501_0600/s0539_minimum_time_difference/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0501_0600.s0539_minimum_time_difference
// #Medium #Array #String #Math #Sorting #2023_01_16_Time_183_ms_(100.00%)_Space_36_MB_(96.23%)
class Solution {
fun findMinDifference(timePoints: List<String>): Int {
return if (timePoints.size < 300) {
smallInputSize(timePoints)
} else largeInputSize(timePoints)
}
private fun largeInputSize(timePoints: List<String>): Int {
val times = BooleanArray(60 * 24)
for (time in timePoints) {
val hours = time.substring(0, 2).toInt()
val minutes = time.substring(3, 5).toInt()
if (times[hours * 60 + minutes]) {
return 0
}
times[hours * 60 + minutes] = true
}
var prev = -1
var min = 60 * 24
for (i in 0 until times.size + times.size / 2) {
if (i < times.size) {
if (times[i] && prev == -1) {
prev = i
} else if (times[i]) {
min = Math.min(min, i - prev)
prev = i
}
} else {
if (times[i - times.size] && prev == -1) {
prev = i
} else if (times[i - times.size]) {
min = Math.min(min, i - prev)
prev = i
}
}
}
return min
}
private fun smallInputSize(timePoints: List<String>): Int {
val times = IntArray(timePoints.size)
var j = 0
for (time in timePoints) {
val hours = time.substring(0, 2).toInt()
val minutes = time.substring(3, 5).toInt()
times[j++] = hours * 60 + minutes
}
times.sort()
var min = 60 * 24
for (i in 1..times.size) {
min = if (i == times.size) {
Math.min(min, times[0] + 60 * 24 - times[times.size - 1])
} else {
Math.min(min, times[i] - times[i - 1])
}
if (min == 0) {
return 0
}
}
return min
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,123 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/zer0rez/euler/util/Util.kt | cgnik | 199,092,974 | false | {"Python": 110405, "Kotlin": 15347} | package com.zer0rez.euler.util
import kotlin.math.sqrt
fun Int.isDivisibleBy(i: Int): Boolean = this % i == 0
fun Int.isDivisibleByAll(i: IntArray): Boolean = i.all { this.isDivisibleBy(it) }
fun Long.isDivisibleBy(i: Long): Boolean = this % i == 0L
fun Long.isDivisibleByAny(i: Collection<Long>): Boolean = i.any { this.isDivisibleBy(it) }
fun Int.isPalindrome(): Boolean {
if (this < 10) return false;
val ns = this.toString()
val end = ns.length - 1
for (i in 0..(ns.length / 2)) {
if (i >= end) break
if (ns[i] != ns[end - i]) return false
}
return true
}
fun IntArray.swapin(arrow: Int): Int {
this[0] = this[1]
this[1] = arrow
return this[1]
}
fun fibonacci(quit: (Int) -> Boolean): IntArray {
var values = ArrayList<Int>()
values.add(1)
values.add(1)
while (!quit(values.last())) {
values.add(values[values.count() - 1] + values[values.count() - 2])
}
values.remove(values.last())
return values.toIntArray()
}
fun Long.factorize(): Sequence<Long> {
var target = this
var current = sqrt(target.toDouble()).toLong()
return sequence {
while (current % 2 == 0L) current /= 2
while (current > 0 && current < target) {
if (target % current == 0L) {
yield(current)
target /= current
}
current -= 2
}
}
}
fun LongArray.productSeries(size: Int) = IntRange(0, this.count() - size).map { i ->
Pair(this.slice(i until i + size).reduce { t: Long, x: Long -> x * t }, this.slice(i until i + size))
}
| 0 | Python | 0 | 0 | fe70459a0e0d0272980300a4782872f2e545fea5 | 1,601 | euler | MIT License |
src/main/kotlin/days/Solution03.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import adventOfCode.util.Point2D
object Solution03 : Solution<List<String>>(AOC_YEAR, 3) {
override fun getInput(handler: InputHandler) = handler.getInput("\n")
private fun Char.isSymbol() = !this.isDigit() && this != '.'
private fun Char.isGear() = this == '*'
private fun MutableSet<Point2D>.pop(): Point2D {
val ret = this.first()
this.remove(ret)
return ret
}
override fun solve(input: List<String>): PairOf<Int> {
val rowIndices = input.indices
val colIndices = input[0].indices
fun getNumbers(row: Int, col: Int): Map<Point2D, Int> {
val numbers = mutableMapOf<Point2D, Int>()
val candidates = (row - 1..row + 1)
.flatMap { i -> (col - 1..col + 1).map { j -> i to j } }
.filter { (i, j) -> i in rowIndices && j in colIndices }
.filter { (i, j) -> input[i][j].isDigit() }
.toMutableSet()
while (candidates.isNotEmpty()) {
val (i, j) = candidates.pop()
val line = input[i]
val jMin = (j - 1 downTo colIndices.first).find { !line[it].isDigit() } ?: (colIndices.first - 1)
val jMax = (j + 1..colIndices.last).find { !line[it].isDigit() } ?: (colIndices.last + 1)
candidates.removeIf { it.first == i && it.second in jMin..jMax }
numbers[i to jMin] = line.substring(jMin + 1, jMax).toInt()
}
return numbers
}
val numbers = mutableMapOf<Point2D, Int>()
var gearRatioSum = 0
for ((row, line) in input.withIndex()) {
for ((col, c) in line.withIndex()) {
if (!c.isSymbol()) continue
val newNumbers = getNumbers(row, col)
numbers += newNumbers
if (c.isGear() && newNumbers.size == 2) {
gearRatioSum += newNumbers.values.reduce(Int::times)
}
}
}
return numbers.values.sum() to gearRatioSum
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 2,172 | Advent-of-Code-2023 | MIT License |
src/main/kotlin/Day05.kt | robert-iits | 573,124,643 | false | {"Kotlin": 21047} | import java.util.Stack
import kotlin.system.measureTimeMillis
typealias StackList = List<Stack<Char>>
typealias CommandList = List<Command>
class Day05 {
fun part1(input: List<String>): String {
val (stacks, commands) = splitInputIntoStackAndCommand(input)
val movedStacks = craneAction(stacks, commands)
return getTopItems(movedStacks)
}
fun part2(input: List<String>): String {
val (stacks, commands) = splitInputIntoStackAndCommand(input)
val movedStacks = craneAction9001(stacks, commands)
return getTopItems(movedStacks)
}
private fun getTopItems(movedStacks: List<Stack<Char>>): String {
var topStack = ""
movedStacks.forEach { stack ->
topStack += stack.pop()
}
return topStack
}
private fun splitInputIntoStackAndCommand(input: List<String>): Pair<StackList, CommandList> {
val stackData = input.take(8)
val commandData = input.drop(10)
val stacks = stackParser(stackData)
val commands = commandParser(commandData)
return Pair(stacks, commands)
}
private fun craneAction(stacks: List<Stack<Char>>, commands: List<Command>): List<Stack<Char>> {
commands.forEach { command ->
repeat(command.quantity) {
stacks[command.toStack].push(stacks[command.fromStack].pop())
}
}
return stacks
}
private fun craneAction9001(stacks: List<Stack<Char>>, commands: List<Command>): List<Stack<Char>> {
commands.forEach { command ->
val craneContainer = Stack<Char>()
repeat(command.quantity) {
craneContainer.push(stacks[command.fromStack].pop())
}
repeat(command.quantity) {
stacks[command.toStack].push(craneContainer.pop())
}
}
return stacks
}
private fun stackParser(stackData: List<String>): List<Stack<Char>> {
val charPosition = mutableListOf<Int>()
stackData.last().forEachIndexed { index, c -> if (c in 'A'..'Z') charPosition.add(index) }
val stackList = mutableListOf<Stack<Char>>()
charPosition.toList().forEach { charpos ->
val newStack = Stack<Char>()
stackData.forEach { stringLine ->
stringLine[charpos].let { if (it != ' ') newStack.push(it) }
}
newStack.reverse()
stackList.add(newStack)
}
return stackList
}
private fun commandParser(commandData: List<String>): MutableList<Command> {
val commandList = mutableListOf<Command>()
commandData.forEach { commandline ->
commandline.filter { it.isDigit() }
.let {
if (it.length == 4) {
commandList.add(Command(it.take(2).toInt(), it[2].digitToInt() - 1, it[3].digitToInt() - 1))
} else {
commandList.add(Command(it[0].digitToInt(), it[1].digitToInt() - 1, it[2].digitToInt() - 1))
}
}
}
return commandList
}
}
data class Command(val quantity: Int, val fromStack: Int, val toStack: Int)
fun main() {
val input = readInput("Day05")
println("duration (ms): " + measureTimeMillis { println("part 1: " + Day05().part1(input)) })
println("duration (ms): " + measureTimeMillis { println("part 2: " + Day05().part2(input)) })
} | 0 | Kotlin | 0 | 0 | 223017895e483a762d8aa2cdde6d597ab9256b2d | 3,483 | aoc2022 | Apache License 2.0 |
src/2023/2023Day03.kt | bartee | 575,357,037 | false | {"Kotlin": 26727} | package `2023`
import readInput
data class IntIndex(val index: Int, val pos: Pair<Int, Int>)
fun createSymbolIndex(input: String): List<Int> {
val symbol_pattern = """[^\d\w\.]+""".toRegex()
return symbol_pattern.findAll(input).map { it.range.start }.toList<Int>()
}
fun createNumberIndex(input: String): List<IntIndex> {
val int_pattern = """(\d)+""".toRegex()
return int_pattern.findAll(input).map{ IntIndex(it.groupValues[1].toInt(), Pair(it.range.start.toInt(), it.range.endInclusive.toInt())) }.toList()
}
fun partOne(input: List<String>): Int {
// var numberIndex = mutableMapOf<Int, List<IntIndex>>()
val symbolIndex = input.mapIndexed { index, s -> createSymbolIndex(s) }
val numberIndex = input.mapIndexed{ index, s -> createNumberIndex(s) }
symbolIndex.withIndex().forEach{
val ind = it.index
// find the min and the max
val minNumberRow = (if ind -1 < 0) ? 0 : (ind -1)
val maxNumberrow = (if ind +1 > numberIndex.size) ? numberIndex.size : (ind + 1)
}
return 0
}
fun partTwo(input: List<String>): Int {
return 0
}
fun main() {
val test_input = readInput("2023/resources/input/day03_testinput")
val game_input = readInput("2023/resources/input/day03_gameinput")
val testOne = partOne(test_input)
val testTwo = partTwo(test_input)
println("Testing ... ")
assert(testOne == 4361)
// assert(testTwo == 2286)
println("Tested! ")
var res = partOne(game_input)
println("Part one result: $res")
} | 0 | Kotlin | 0 | 0 | c7141d10deffe35675a8ca43297460a4cc16abba | 1,467 | adventofcode2022 | Apache License 2.0 |
src/commonMain/kotlin/ai/hypergraph/kaliningraph/StringUtils.kt | breandan | 245,074,037 | false | {"Kotlin": 1482924, "Haskell": 744, "OCaml": 200} | package ai.hypergraph.kaliningraph
import ai.hypergraph.kaliningraph.automata.*
import ai.hypergraph.kaliningraph.image.escapeHTML
import ai.hypergraph.kaliningraph.parsing.*
import ai.hypergraph.kaliningraph.tensor.FreeMatrix
import ai.hypergraph.kaliningraph.tensor.transpose
import ai.hypergraph.kaliningraph.types.*
import kotlin.math.*
fun Σᐩ.tokenizeByWhitespace(): List<Σᐩ> = split(Regex("\\s+")).filter { it.isNotBlank() }
fun Σᐩ.tokenizeByWhitespaceAndKeepDelimiters(): List<Σᐩ> =
split(Regex("(?<=\\s)|(?=\\s)"))
infix fun Char.closes(that: Char) =
if (this == ')' && that == '(') true
else if (this == ']' && that == '[') true
else if (this == '}' && that == '{') true
else this == '>' && that == '<'
val BRACKETS = "()[]{}<>".toCharArray().toSet()
val JUST_PARENS = "()[]{}".toCharArray().toSet()
fun Σᐩ.hasBalancedBrackets(brackets: Set<Char> = BRACKETS): Boolean =
filter { it in brackets }.fold(Stack<Char>()) { stack, c ->
stack.apply { if (isNotEmpty() && c.closes(peek())) pop() else push(c) }
}.isEmpty() && brackets.any { it in this }
fun Σᐩ.splitProd() = replaceFirst("->", "→").split('→').map { it.trim() }
fun List<Σᐩ>.formatAsGrid(cols: Int = -1): FreeMatrix<Σᐩ> {
fun Σᐩ.tok() = splitProd()
fun Σᐩ.LHS() = tok()[0]
fun Σᐩ.RHS() = tok()[1]
val groups = groupBy { it.LHS() }
fun List<Σᐩ>.rec() = if (cols == -1) // Minimize whitespace over all grids with a predefined number of columns
(3..5).map { formatAsGrid(it) }.minBy { it.toString().length }
else sortedWith(compareBy(
{ groups[it.LHS()]!!.maxOf { it.length } }, // Shortest longest pretty-printed production comes first
{ -groups[it.LHS()]!!.size }, // Take small groups first
{ it.LHS() }, // Must never split up two LHS productions
{ it.length }
)).let { productions ->
val (cols, rows) = cols to ceil(productions.size.toDouble() / cols).toInt()
val padded = productions + List(cols * rows - productions.size) { "" }
FreeMatrix(cols, rows, padded).transpose
}.let { up ->
FreeMatrix(up.numRows, up.numCols) { r, c ->
if (up[r, c].isEmpty()) return@FreeMatrix ""
val (lhs, rhs) = up[r, c].splitProd().let { it[0] to it[1] }
val lp = lhs.padStart(up.transpose[c].maxOf { it.substringBefore(" -> ").length })
val rp = rhs.padEnd(up.transpose[c].maxOf { it.substringAfter(" -> ").length })
"$lp → $rp"
}
}
return rec()
}
private fun <T> List<List<T>>.col(i: Int) = map { it[i] }
// https://en.wikipedia.org/wiki/Seam_carving
fun Σᐩ.carveSeams(toRemove: Regex = Regex("\\s{2,}")): Σᐩ =
replace(" | ", " ")
.lines().filter { it.isNotBlank() }.map { it.split('→') }.let { toMerge ->
val minCols = toMerge.minOf { it.size }
val takeAway = (0 until minCols).map { toMerge.col(it).minOf { toRemove.find(it)!!.value.length } }
val subs = takeAway.map { List(it) { " " }.joinToString("") }
toMerge.joinToString("\n", "\n") {
it.mapIndexed { i, it -> if (i < minCols) it.replaceFirst(subs[i], " ") else it }
.joinToString("→").drop(4).dropLast(3)
}
}
fun <T> List<Pair<T?, T?>>.paintDiffs(): String =
joinToString(" ") { (a, b) ->
when {
a == null -> "<span style=\"color: green\">${b.toString().escapeHTML()}</span>"
b == null -> "<span style=\"background-color: gray\"><span class=\"noselect\">${List(a.toString().length){" "}.joinToString("")}</span></span>"
a == "_" -> "<span style=\"color: green\">${b.toString().escapeHTML()}</span>"
a != b -> "<span style=\"color: orange\">${b.toString().escapeHTML()}</span>"
else -> b.toString().escapeHTML()
}
}
fun multisetManhattanDistance(s1: Σᐩ, s2: Σᐩ): Int =
multisetManhattanDistance(s1.tokenizeByWhitespace().toList(), s2.tokenizeByWhitespace().toList())
fun <T> multisetManhattanDistance(q1: List<T>, q2: List<T>): Int {
val (s1, s2) = listOf(q1, q2).map { it.groupingBy { it }.eachCount() }
val totalDiff = s1.keys.union(s2.keys)
.sumOf { t -> (s1.getOrElse(t) { 0 } - s2.getOrElse(t) { 0 }).absoluteValue }
return totalDiff
}
fun String.removeEpsilon() = tokenizeByWhitespace().filter { it != "ε" }.joinToString(" ")
// Intersperses "" in between every token in a list of tokens
fun List<Σᐩ>.intersperse(i: Int = 1, tok: Σᐩ = "", spacer: List<Σᐩ> = List(i) { tok }): List<Σᐩ> =
fold(spacer) { acc, s -> acc + spacer + s } + spacer
fun String.cfgType() = when {
isNonterminalStub() -> "NT/$this"
// Is a Java or Kotlin identifier character in Kotlin common library (no isJavaIdentifierPart)
Regex("[a-zA-Z0-9_]+").matches(this) -> "ID/$this"
any { it in BRACKETS } -> "BK/$this"
else -> "OT"
}
const val ANSI_RESET = "\u001B[0m"
const val ANSI_BLACK = "\u001B[30m"
const val ANSI_RED = "\u001B[31m"
const val ANSI_GREEN = "\u001B[32m"
const val ANSI_YELLOW = "\u001B[33m"
const val ANSI_BLUE = "\u001B[34m"
const val ANSI_PURPLE = "\u001B[35m"
const val ANSI_CYAN = "\u001B[36m"
const val ANSI_WHITE = "\u001B[37m"
const val ANSI_BLACK_BACKGROUND = "\u001B[40m"
const val ANSI_RED_BACKGROUND = "\u001B[41m"
const val ANSI_GREEN_BACKGROUND = "\u001B[42m"
const val ANSI_ORANGE_BACKGROUND = "\u001B[43m"
const val ANSI_YELLOW_BACKGROUND = "\u001B[43m"
const val ANSI_BLUE_BACKGROUND = "\u001B[44m"
const val ANSI_PURPLE_BACKGROUND = "\u001B[45m"
const val ANSI_CYAN_BACKGROUND = "\u001B[46m"
const val ANSI_WHITE_BACKGROUND = "\u001B[47m" | 0 | Kotlin | 8 | 100 | c755dc4858ed2c202c71e12b083ab0518d113714 | 5,476 | galoisenne | Apache License 2.0 |
src/Day04.kt | adrianforsius | 573,044,406 | false | {"Kotlin": 68131} | import org.assertj.core.api.Assertions.assertThat
fun main() {
fun part1(input: List<String>): Int {
return input.map {
it.split("\n")
}.map {
val parts = it.first().split(",")
val part1 = parts[0].split("-")
val part2 = parts[1].split("-")
val range1 = part1[0].toInt().rangeTo(part1[1].toInt())
val range2 = part2[0].toInt().rangeTo(part2[1].toInt())
val match1 = range1.all{
it in range2
}
val match2 = range2.all{
it in range1
}
if (match1 || match2) 1 else 0
}.sum()
}
fun part2(input: List<String>): Int {
return input.map {
val lines = it.split("\n")
lines.map {
val parts = it.split(",")
val part1 = parts[0].split("-")
val part2 = parts[1].split("-")
val range1 = part1[0].toInt().rangeTo(part1[1].toInt())
val range2 = part2[0].toInt().rangeTo(part2[1].toInt())
val match1 = range1.any{
it in range2
}
val match2 = range2.any{
it in range1
}
if (match1 || match2) 1 else 0
}.sum()
}.sum()
}
// test if implementation meets criteria from the description, like:
// Test
val testInput = readInput("Day04_test")
val output1 = part1(testInput)
assertThat(output1).isEqualTo(2)
// Answer
val input = readInput("Day04")
val outputAnswer1 = part1(input)
assertThat(outputAnswer1).isEqualTo(657)
// Test
val output2 = part2(testInput)
assertThat(output2).isEqualTo(4)
// Answer
val outputAnswer2 = part2(input)
assertThat(outputAnswer2).isEqualTo(938)
}
| 0 | Kotlin | 0 | 0 | f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb | 1,879 | kotlin-2022 | Apache License 2.0 |
src/main/aoc2018/Day10.kt | Clausr | 575,584,811 | false | {"Kotlin": 65961} | package aoc2018
class Day10(input: List<String>) {
private val lights = input.map(Light::from)
fun solvePart1(): String {
val message = Sky(lights).getMessageWithLeastArea()
println(message.second)
return message.first
}
fun solvePart2(): Int {
val message = Sky(lights).getMessageWithLeastArea()
return message.second
}
data class Light(var x: Int, var y: Int, val velocityX: Int, val velocityY: Int) {
fun move(direction: Direction) = when (direction) {
Direction.Forward -> {
x += velocityX
y += velocityY
}
Direction.Backward -> {
x -= velocityX
y -= velocityY
}
}
companion object {
fun from(line: String): Light {
val (x, y) = line.substringAfter("<").substringBefore(">").trimAndSplitBy(",")
val (velocityX, velocityY) = line.substringAfterLast("<").substringBeforeLast(">").trimAndSplitBy(",")
return Light(x.toInt(), y.toInt(), velocityX.toInt(), velocityY.toInt())
}
}
}
enum class Direction {
Forward, Backward
}
data class Sky(val lights: List<Light>) {
/**
* For this to make sense, we assume that the message shows itself when the area of all the lights are the smallest
* This might be naïve, but it seems to work with this task.
* It would've failed if the stars all started from the center of the sky
*/
fun getMessageWithLeastArea(): Pair<String, Int> {
var lastArea = Long.MAX_VALUE
var currentArea = calculateCurrentArea()
var seconds = 0
while (lastArea > currentArea) {
moveLights()
seconds += 1
lastArea = currentArea
currentArea = calculateCurrentArea()
}
// We're out of the loop since the lastArea is smaller than the current area,
// so that means we're 1 second too far ahead... Luckily we can just go back in time.
moveLights(direction = Direction.Backward)
return this.toString() to seconds - 1
}
private fun moveLights(direction: Direction = Direction.Forward) = lights.forEach { it.move(direction) }
private val rangeY
get() = IntRange(lights.minOf { it.y }, lights.maxOf { it.y })
private val rangeX
get() = IntRange(lights.minOf { it.x }, lights.maxOf { it.x })
private fun calculateCurrentArea(): Long =
(rangeX.last - rangeX.first).toLong() * (rangeY.last - rangeY.first).toLong()
override fun toString(): String {
val lightSet = lights.map { it.x to it.y }.toSet()
return rangeY.joinToString(separator = "\n") { y ->
rangeX.map { x ->
if (x to y in lightSet) '#' else '.'
}.joinToString("")
}
}
}
}
private fun String.trimAndSplitBy(delimiter: String) = replace("\\s".toRegex(), "").split(delimiter)
| 1 | Kotlin | 0 | 0 | dd33c886c4a9b93a00b5724f7ce126901c5fb3ea | 3,174 | advent_of_code | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2019/Day14.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2019
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import java.lang.Long.min
import kotlin.math.ceil
/** https://adventofcode.com/2019/day/14 */
class Day14 : Solver {
override fun solve(lines: List<String>): Result {
val reactions = parseInput(lines)
val resultA = produce("FUEL", 1, reactions)
val resultB = howMuchFuelProduces(1000000000000L, reactions)
return Result("$resultA", "$resultB")
}
private fun howMuchFuelProduces(maxOre: Long, reactions: Map<Amount, List<Amount>>): Long {
// Binary search to find the answer.
var minFuel = 0L
var maxFuel = 10000000L
while (maxFuel - minFuel > 1) {
val fuel = ((maxFuel - minFuel) / 2L) + minFuel
val ore = produce("FUEL", fuel, reactions)
if (ore > maxOre) {
maxFuel = fuel
} else {
minFuel = fuel
}
}
return minFuel
}
/**
* Produces the given number of the given element.
*
* @param name the name of the element to produce
* @param amount the number of elements to produce
* @param extra will add extra elements produced in here and will use them if
* applicable
* @return The number of ore required to produce the elements.
*/
private fun produce(name: String, amount: Long,
reactions: Map<Amount, List<Amount>>,
extra: MutableMap<String, Long> = mutableMapOf()): Long {
// Base material
if (name == "ORE") {
return amount
}
// Check if we got extra from what we are asked to produce and take it.
val takeFromExtra = min(extra[name] ?: 0, amount)
val num = amount - takeFromExtra
extra[name] = (extra[name] ?: 0) - takeFromExtra
var actuallyProduced = 0L
var lowestOreCost = Long.MAX_VALUE
// There might be multiple ways to produce what we need. Find the cheapest.
for ((output, inputs) in reactions.entries) {
if (output.name == name) {
val numRequired = ceil(num.toFloat() / output.num.toFloat()).toLong()
var cost = 0L
for (input in inputs) {
val price =
produce(input.name, input.num * numRequired, reactions, extra)
cost += price
}
if (cost < lowestOreCost) {
actuallyProduced = numRequired * output.num
lowestOreCost = cost
}
}
}
extra[name] = (extra[name] ?: 0) + (actuallyProduced - num)
return lowestOreCost
}
private fun parseInput(lines: List<String>): Map<Amount, List<Amount>> {
val result = hashMapOf<Amount, List<Amount>>()
lines.map { parseLine(it) }.forEach { result[it.first] = it.second }
return result
}
private fun parseLine(line: String): Pair<Amount, List<Amount>> {
val split = line.split(" => ")
val product = parseAmount(split[1])
val ingredients = split[0].split(", ").map { parseAmount(it) }
return Pair(product, ingredients)
}
private fun parseAmount(str: String): Amount {
val split = str.split(" ")
return Amount(split[0].toLong(), split[1])
}
private data class Amount(val num: Long, val name: String)
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 3,138 | euler | Apache License 2.0 |
src/net/sheltem/aoc/y2023/Day23.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2023
import net.sheltem.common.*
suspend fun main() {
Day23().run()
}
class Day23 : Day<Long>(94, 154) {
override suspend fun part1(input: List<String>) = input
.adjacencies(true)
.dfs(input[0].indexOf('.') to 0, input.last().indexOf('.') to (input.size - 1))!!.toLong()
override suspend fun part2(input: List<String>) = input
.adjacencies()
.dfs(input[0].indexOf('.') to 0, input.last().indexOf('.') to (input.size - 1))!!.toLong()
}
private fun List<String>.adjacencies(icy: Boolean = false): Map<PositionInt, Map<PositionInt, Int>> {
val adjacencies = indices.flatMap { y ->
this[y].indices.mapNotNull { x ->
if (this[y][x] != '#') {
(x to y) to Direction.cardinals.mapNotNull { dir ->
val current = x to y
val next = current.move(dir)
if (next.within(this)
&& this.charAt(next) != '#'
&& (!icy || (this.charAt(current) == '.' || Direction.from(this.charAt(current).toString()) == dir))
) {
next to 1
} else {
null
}
}.toMap(mutableMapOf())
} else null
}
}.toMap(mutableMapOf())
adjacencies.keys.toList().forEach { key ->
adjacencies[key]?.takeIf { it.size == 2 }?.let { neighbors ->
val left = neighbors.keys.first()
val right = neighbors.keys.last()
val totalSteps = neighbors[left]!! + neighbors[right]!!
adjacencies.getOrPut(left) { mutableMapOf() }.merge(right, totalSteps, ::maxOf)
adjacencies.getOrPut(right) { mutableMapOf() }.merge(left, totalSteps, ::maxOf)
listOf(left, right).forEach { adjacencies[it]?.remove(key) }
adjacencies.remove(key)
}
}
return adjacencies
}
private fun Map<PositionInt, Map<PositionInt, Int>>.dfs(current: PositionInt, goal: PositionInt, visited: MutableMap<PositionInt, Int> = mutableMapOf()): Int? {
if (current == goal) {
return visited.values.sum()
}
var max: Int? = null
(this[current] ?: emptyMap()).forEach { (neighbour, steps) ->
if (neighbour !in visited) {
visited[neighbour] = steps
val next = this.dfs(neighbour, goal, visited)
max = next nullsafeMax max
visited.remove(neighbour)
}
}
return max
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 2,535 | aoc | Apache License 2.0 |
src/main/kotlin/aoc2020/ex9.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} |
fun main() {
val input = readInputFile("aoc2020/input9")
val data = input.lines().map { it.toLong() }
val invalid = findFirstInvalid(data, 25)
val (low, high) = findSummingRangeOf(invalid, data)
val summands = data.subList(low, high+1)
println(summands)
println("${summands.minOrNull()}, ${summands.maxOrNull()}")
println(summands.minOrNull()!! + summands.maxOrNull()!!)
}
fun findSummingRangeOf(invalid: Long, data: List<Long>): Pair<Int, Int> {
// TODO: 23/11/2021 seems like first time that performance matters!!
var start = 0
var end = 0
var sum = 0L
while (start <= data.lastIndex) {
sum += data[end]
if (sum == invalid) return start to end
if (sum > invalid) {
start++
end = start
sum = 0L
} else { // sum < invalid
end++
}
}
return -1 to -1
}
private fun findFirstInvalid(numbers: List<Long>, preSize: Int): Long {
require(numbers.take(preSize).toSet().size == preSize)
numbers.drop(preSize).forEachIndexed { index, number ->
val options = numbers.subList(index, index + preSize)
require(options.size == preSize) {"${options.size}"}
//println("$options")
if(!isSumOf(number, options)) return number
}
return -1L
}
private fun isSumOf(number: Long, options: List<Long>): Boolean {
options.forEach { option ->
if (number - option in options && number - option != option) {
//println("$number=$option+${number-option}")
return true
}
}
println("$number invalid")
return false
} | 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 1,638 | AOC-2021 | MIT License |
src/main/kotlin/Day19.kt | cbrentharris | 712,962,396 | false | {"Kotlin": 171464} | import kotlin.String
import kotlin.collections.List
object Day19 {
private const val MIN_STATES = 1L
private const val MAX_STATES = 4000L
private const val ACCEPTED_STATE = "A"
private const val REJECTED_STATE = "R"
private const val START_STATE = "in"
data class Part(val ratings: Map<String, Int>) {
companion object {
fun parse(input: String): Part {
val ratings = input.drop(1).dropLast(1).split(",").map {
val (id, rating) = it.split("=")
id to rating.toInt()
}.toMap()
return Part(ratings)
}
}
fun score(): Int = ratings.values.sum()
}
data class Rule(val key: String, val op: String, val value: Int, val nextState: String) {
fun inverse(): Rule {
val inverseOp = when (op) {
"<" -> ">="
">" -> "<="
else -> throw IllegalArgumentException("Cannot inverse op $op")
}
return Rule(key, inverseOp, value, nextState)
}
}
data class Condition(val key: String, val op: String, val value: Int) {
fun toMinAndMax(): MinAndMax {
return when (op) {
"<" -> MinAndMax(MIN_STATES, value.toLong() - 1, key)
"<=" -> MinAndMax(MIN_STATES, value.toLong(), key)
">" -> MinAndMax(value.toLong() + 1, MAX_STATES, key)
">=" -> MinAndMax(value.toLong(), MAX_STATES, key)
else -> throw IllegalArgumentException("Cannot inverse op $op")
}
}
}
data class CompositeCondition(val conditions: List<Condition>, val nextState: String)
data class PathFinder(val jobs: Map<String, Job>) {
fun findPathsToRejectedState(): List<Path> {
val startJob = jobs[START_STATE]!!
val paths = mutableListOf<Path>()
paths.addAll(startJob.conditionsLeadingToRejectedState().map { Path(listOf(it)) })
val nextStates = ArrayDeque(
startJob.nonTerminalConditions()
.map { it to Path(listOf(it)) })
while (nextStates.isNotEmpty()) {
val (nextRule, runningPath) = nextStates.removeFirst()
val nextJob = jobs[nextRule.nextState]!!
val failureStates = nextJob.conditionsLeadingToRejectedState()
val failedPaths = failureStates.map { runningPath.with(it) }
paths.addAll(failedPaths)
val nonTerminalStates = nextJob.nonTerminalConditions()
nextStates.addAll(nonTerminalStates.map { it to runningPath.with(it) })
}
return paths
}
}
data class Path(val compositeConditions: List<CompositeCondition>) {
fun with(compositeCondition: CompositeCondition): Path {
return Path(compositeConditions + compositeCondition)
}
}
data class Job(
val id: String,
val rules: List<Pair<(Part) -> Boolean, String>>,
val endState: String,
val rawRules: List<Rule>
) {
fun evaluate(part: Part): String {
return rules.find { (rule, _) -> rule(part) }?.second ?: endState
}
fun conditionsLeadingToRejectedState(): List<CompositeCondition> {
val rejectedRules = mutableListOf<CompositeCondition>()
if (endState == REJECTED_STATE) {
val endStateCompositeCondition =
CompositeCondition(
rawRules.map { it.inverse() }.map { Condition(it.key, it.op, it.value) },
REJECTED_STATE
)
rejectedRules.add(endStateCompositeCondition)
}
rejectedRules.addAll(rawRules.withIndex().filter { (_, rule) -> rule.nextState == REJECTED_STATE }
.map { (idx, rule) ->
val inversedPreceedingRules =
rawRules.subList(0, idx).map { it.inverse() }.map { Condition(it.key, it.op, it.value) }
val thisRule = listOf(Condition(rule.key, rule.op, rule.value))
CompositeCondition(inversedPreceedingRules + thisRule, rule.nextState)
})
return rejectedRules
}
fun nonTerminalConditions(): List<CompositeCondition> {
val nonAcceptedNorRejectedConditions = mutableListOf<CompositeCondition>()
if (endState != ACCEPTED_STATE && endState != REJECTED_STATE) {
val endStateCompositeCondition =
CompositeCondition(
rawRules.map { it.inverse() }.map { Condition(it.key, it.op, it.value) },
endState
)
nonAcceptedNorRejectedConditions.add(endStateCompositeCondition)
}
nonAcceptedNorRejectedConditions.addAll(
rawRules.withIndex()
.filter { (_, rule) -> rule.nextState != REJECTED_STATE && rule.nextState != ACCEPTED_STATE }
.map { (idx, rule) ->
val inversedPreceedingRules =
rawRules.subList(0, idx).map { it.inverse() }.map { Condition(it.key, it.op, it.value) }
val thisRule = listOf(Condition(rule.key, rule.op, rule.value))
CompositeCondition(inversedPreceedingRules + thisRule, rule.nextState)
})
return nonAcceptedNorRejectedConditions
}
companion object {
fun parse(input: String): Job {
val curlyIndex = input.indexOf("{")
val id = input.substring(0, curlyIndex).trim()
val rawRules = input.substring(curlyIndex).drop(1).dropLast(1)
val lastComma = rawRules.lastIndexOf(",")
val endState = rawRules.substring(lastComma + 1).trim()
val ops = mapOf("<" to { part: Part, value: Int, key: String -> part.ratings[key]!! < value },
">" to { part: Part, value: Int, key: String -> part.ratings[key]!! > value })
val rules = rawRules.substring(0, lastComma).split(",").map {
val pattern = """(\w+)([<>])(\d+):(\w+)""".toRegex()
val matchResult = pattern.matchEntire(it.trim())!!
val (key, op, value, nextState) = matchResult.destructured
Rule(key, op, value.toInt(), nextState)
}
val rulesAsFunctions =
rules.map { { part: Part -> ops[it.op]!!(part, it.value, it.key) } to it.nextState }
return Job(id, rulesAsFunctions, endState, rules)
}
}
}
data class Workflow(val jobs: Map<String, Job>) {
fun isAccepted(part: Part): Boolean {
val startJob = jobs[START_STATE]!!
var state = startJob.evaluate(part)
while (state != ACCEPTED_STATE && state != REJECTED_STATE) {
val job = jobs[state]!!
state = job.evaluate(part)
}
return state == ACCEPTED_STATE
}
}
fun part1(input: List<String>): String {
val partitionIndex = input.withIndex().find { it.value.isEmpty() }!!.index
val jobs = input.subList(0, partitionIndex).map { Job.parse(it) }
val parts = input.subList(partitionIndex + 1, input.size).map { Part.parse(it) }
val workflow = Workflow(jobs.associateBy { it.id })
return parts.filter { workflow.isAccepted(it) }.sumOf { it.score() }.toString()
}
data class MinAndMax(val min: Long, val max: Long, val key: String) {
fun coerce(other: MinAndMax): MinAndMax {
return MinAndMax(min.coerceAtLeast(other.min), max.coerceAtMost(other.max), key)
}
fun length(): Long = max - min + 1
}
fun part2(input: List<String>): String {
val partitionIndex = input.withIndex().find { it.value.isEmpty() }!!.index
val jobs = input.subList(0, partitionIndex).map { Job.parse(it) }
val rejectedPaths = PathFinder(jobs.associateBy { it.id }).findPathsToRejectedState()
val minAndMaxes: List<Map<String, MinAndMax>> = rejectedPaths
.filter { it.compositeConditions.isNotEmpty() }
.map { path ->
path.compositeConditions.flatMap { it.conditions }
.map { it.toMinAndMax() }.groupBy { it.key }
.mapValues { (_, minAndMaxes) -> minAndMaxes.reduce { a, b -> a.coerce(b) } }
}
val possibleRejectedStates = minAndMaxes.map { minAndMax ->
listOf("x", "m", "a", "s").map { minAndMax[it] ?: MinAndMax(1, 4000, it) }
.map { it.length() }
.reduce { acc, num -> acc * num }
}.sum()
val possibleStates = 4000L * 4000L * 4000L * 4000L
val delta = possibleStates - possibleRejectedStates
return delta.toString()
}
}
| 0 | Kotlin | 0 | 1 | f689f8bbbf1a63fecf66e5e03b382becac5d0025 | 9,079 | kotlin-kringle | Apache License 2.0 |
src/year2022/day16/Day16.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day16
import readInputFileByYearAndDay
import readTestFileByYearAndDay
import java.lang.Integer.max
import java.lang.Integer.min
data class Valve(val name: String, val flowRate: Int, val connections: MutableList<Valve> = mutableListOf()) {
private val cost = mutableMapOf(this to 0)
fun findWayTo(other: Valve, seen: List<Valve> = listOf()): Int {
if (connections.contains(other)) {
cost[other] = 1
return 1
}
val nextHops = connections.filterNot { seen.contains(it) }
if (nextHops.isEmpty()) return Int.MAX_VALUE
val min = 1 + nextHops.minOf { it.findWayTo(other, seen + listOf(this)) }
cost[other] = min(cost.getOrDefault(other, Int.MAX_VALUE), min)
return cost[other]!!
}
override fun toString(): String =
"Valve (name=$name, flowRate=$flowRate, connections=${connections.map { it.name }}, cost=${cost.map { it.key.name to it.value }})"
override fun hashCode(): Int = name.hashCode() + flowRate.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Valve
if (name != other.name) return false
if (flowRate != other.flowRate) return false
return true
}
}
// I don't trust myself to specify a correct hash code by hand
data class State(val current: String, val timeLeft: Int, val numPlayers: Int, val opened: List<Valve>)
fun main() {
fun initializeValves(input: List<String>): List<Valve> {
val regex = Regex("""Valve ([A-Z]{2})(.*)rate=(\d*)(.*)valves? (.*)""")
val valves = input.map { regex.find(it) }
.map { Valve(name = it!!.groups[1]!!.value, flowRate = it.groups[3]!!.value.toInt()) }
.toList()
input.map { regex.find(it) }
.map { it!!.groups[1]!!.value to it.groups[5]!!.value }
.map { valves.first { valve -> valve.name == it.first } to it.second.split(",") }
.map { it.first to it.second.map { name -> valves.first { valve -> valve.name == name.trim() } } }
.forEach { it.first.connections.addAll(it.second) }
valves.forEach { valve -> valves.forEach(valve::findWayTo) }
return valves
}
fun maximizeSteam(valves: List<Valve>, maxTime: Int, numPlayers: Int): Int {
val memory = mutableMapOf<State, Int>()
fun aux(
current: Valve,
opened: List<Valve>,
totalFlow: Int,
maxTime: Int,
timeLeft: Int,
numPlayers: Int
): Int {
// core idea: elephant moves after we have moved, not in parallel
// this works because the elephant starts with the same time and
// remembers what we opened
if (timeLeft == 0) return if (numPlayers == 1) 0 else aux(
valves.first(),
opened,
totalFlow,
maxTime,
maxTime,
numPlayers - 1
)
val key = State(current.name, timeLeft, numPlayers, opened.sortedBy { it.name })
if (memory.contains(key)) return memory[key]!!
// if current valve has flow greater 0 and is not opened, might open it
var res = 0
if (current.flowRate > 0 && !(opened.contains(current))) {
res = max(
res,
(timeLeft - 1) * current.flowRate + aux(
current,
opened + listOf(current),
totalFlow + current.flowRate,
maxTime,
timeLeft - 1,
numPlayers
)
)
}
// for all connections, check what happens if we go there without opening the current one
current.connections.forEach {
res = max(res, aux(it, opened, totalFlow, maxTime, timeLeft - 1, numPlayers))
}
memory[key] = res
return res
}
val res = aux(valves.first(), listOf(), 0, maxTime, maxTime, numPlayers)
return res
}
fun part1(input: List<String>): Int = maximizeSteam(initializeValves(input), 30, 1)
fun part2(input: List<String>): Int = maximizeSteam(initializeValves(input), 26, 2)
val testInput = readTestFileByYearAndDay(2022, 16)
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInputFileByYearAndDay(2022, 16)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 4,667 | advent-of-code-kotlin | Apache License 2.0 |
src/day/_4/Day04.kt | Tchorzyksen37 | 572,924,533 | false | {"Kotlin": 42709} | package day._4
import readInput
fun main() {
fun part1(input: List<String>): Int {
var overlappingSectionsCount = 0
for (str in input) {
println(str)
val elvesPair = str.split(",")
val sectionOneRange = elvesPair[0].split("-")
val sectionTwoRange = elvesPair[1].split("-")
if ((Integer.parseInt(sectionOneRange[0]) >= Integer.parseInt(sectionTwoRange[0])
&& Integer.parseInt(sectionOneRange[1]) <= Integer.parseInt(sectionTwoRange[1]))
|| (Integer.parseInt(sectionTwoRange[0]) >= Integer.parseInt(sectionOneRange[0])
&& Integer.parseInt(sectionTwoRange[1]) <= Integer.parseInt(sectionOneRange[1]))) {
overlappingSectionsCount++
}
}
return overlappingSectionsCount
}
fun part2(input: List<String>): Int {
var overlappingSectionsCount = 0
for (str in input) {
println(str)
val elvesPair = str.split(",")
val sectionOneRange = elvesPair[0].split("-")
val sectionTwoRange = elvesPair[1].split("-")
if ((Integer.parseInt(sectionOneRange[0]) >= Integer.parseInt(sectionTwoRange[0])
&& Integer.parseInt(sectionOneRange[0]) <= Integer.parseInt(sectionTwoRange[1]))
|| (Integer.parseInt(sectionOneRange[1]) <= Integer.parseInt(sectionTwoRange[1])
&& Integer.parseInt(sectionOneRange[1]) >= Integer.parseInt(sectionTwoRange[0]))
|| (Integer.parseInt(sectionTwoRange[0]) >= Integer.parseInt(sectionOneRange[0])
&& Integer.parseInt(sectionTwoRange[0]) <= Integer.parseInt(sectionOneRange[1]))
|| (Integer.parseInt(sectionTwoRange[1]) <= Integer.parseInt(sectionOneRange[1])
&& Integer.parseInt(sectionTwoRange[1]) >= Integer.parseInt(sectionOneRange[0]))) {
overlappingSectionsCount++
println("Sections are overlapping. Count $overlappingSectionsCount")
}
}
return overlappingSectionsCount
}
val testInput = readInput("day/_4/Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("day/_4/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 27d4f1a6efee1c79d8ae601872cd3fa91145a3bd | 2,016 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | matheusfinatti | 572,935,471 | false | {"Kotlin": 12612} | data class File(
val name: String,
val size: Long = 0,
val parent: File? = null,
val children: MutableList<File> = mutableListOf()
)
val root = File("/")
fun main() {
val input = readInput("Day07").split("\n")
val lsAcc = mutableListOf<String>()
var node = root
for (output in input) {
if (output.startsWith("$")) {
val c = output.split(" ")
if (c.count() == 3) { // cd
node.ls(lsAcc)
lsAcc.clear()
node = node.cd(c[2])!!
}
} else {
lsAcc += output
}
}
if (lsAcc.isNotEmpty()) {
node.ls(lsAcc)
}
//root.lsTree()
val nr = root.fillDirSizes()
println(nr.size(limit = 100_000))
val unused = 70_000_000 - nr.size
val req = 30_000_000 - unused
val files = nr.findFiles(req)
// println(files)
files.minOfOrNull { it.size }.also(::println)
}
fun File.cd(dst: String) =
when (dst) {
".." -> parent
"/" -> root
else -> children.firstOrNull { file ->
file.name == dst
} ?: error("Dir doesn't exist")
}
fun File.ls(files: List<String>) {
for (file in files) {
if (file.startsWith("dir")) {
val (_, name) = file.split(" ")
children.add(File(name, parent = this))
} else {
val (size, name) = file.split(" ")
children.add(File(name, size.toLong(), parent = this))
}
}
}
fun File.lsTree(depth: Int = 0) {
repeat(depth) { print("\t") }
print(" - $name ")
if (children.isEmpty()) {
print("(file, size=$size)")
println()
} else {
print("(dir, size=$size)")
println()
children.forEach { file ->
file.lsTree(depth + 1)
}
}
}
fun File.size(limit: Long = Long.MAX_VALUE): Long =
if (children.isEmpty()) {
0L
} else {
children.fold(
size.takeIf { it <= limit } ?: 0L
) { acc, f ->
acc + f.size(limit)
}
}
fun File.fillDirSizes(): File {
if (children.isEmpty()) return this
val children = children.map(File::fillDirSizes).toMutableList()
return copy(
size = children.sumOf { it.size },
children = children,
)
}
fun File.findFiles(req: Long): List<File> =
if (children.isEmpty()) {
emptyList()
} else {
if (size >= req) {
listOf(this) + children.flatMap { it.findFiles(req) }
} else {
emptyList()
}
} | 0 | Kotlin | 0 | 0 | a914994a19261d1d81c80e0ef8e196422e3cd508 | 2,569 | adventofcode2022 | Apache License 2.0 |
03/part_two.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
fun readInput() : List<String> {
return File("input.txt")
.readLines()
}
fun getRates(report : List<String>) : Pair<Int, Int> {
val oxygenGenRating = calcOxygenRating(report)
val carbonDioxideScrubRating = calcCarbonDioxideScrubRating(report)
return Pair(oxygenGenRating, carbonDioxideScrubRating)
}
fun calcOxygenRating(report : List<String>) : Int {
val columns = report[0].length
var reportCopy = report.toList()
var column = 0
while (column < columns && reportCopy.size > 1) {
val mostFrequentBit = calcMostFrequentBit(reportCopy, column)
reportCopy = getUpdatedReport(reportCopy, column, mostFrequentBit)
column++
}
return reportCopy[0].toInt(2)
}
fun calcCarbonDioxideScrubRating(report : List<String>) : Int {
val columns = report[0].length
var reportCopy = report.toList()
var column = 0
while (column < columns && reportCopy.size > 1) {
val leastFrequentBit = calcLeastFrequentBit(reportCopy, column)
reportCopy = getUpdatedReport(reportCopy, column, leastFrequentBit)
column++
}
return reportCopy[0].toInt(2)
}
fun calcMostFrequentBit(report : List<String>, column : Int) : Char {
val freq = IntArray(2)
for (line in report) {
freq[line[column] - '0']++
}
return if (freq[1] >= freq[0]) '1' else '0'
}
fun calcLeastFrequentBit(report : List<String>, column : Int) : Char {
val freq = IntArray(2)
for (line in report) {
freq[line[column] - '0']++
}
return if (freq[1] < freq[0]) '1' else '0'
}
fun getUpdatedReport(report : List<String>, column : Int, matchingBit : Char) : List<String> {
val updatedReport = mutableListOf<String>()
for (line in report) {
if (line[column] == matchingBit) {
updatedReport.add(line)
}
}
return updatedReport
}
fun solve(oxygenGenRating : Int, carbonDioxideScrubRating : Int) : Int {
return oxygenGenRating * carbonDioxideScrubRating;
}
fun main() {
val report = readInput()
val (oxygenGenRating, carbonDioxideScrubRating) = getRates(report)
val ans = solve(oxygenGenRating, carbonDioxideScrubRating)
println(ans)
} | 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 2,233 | advent-of-code-2021 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.