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/Calculator.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | fun main() = Calculator.solve()
private object Calculator {
fun solve() {
val expressions = readInput()
println("Part 1: root value ${calcValue(expressions, "root")}")
println("Part 2, humn requires value ${matchValuesAt(expressions, "root")}")
}
private fun readInput(): Map<String, Expr> = buildMap {
generateSequence(::readLine).forEach { line ->
val parts = line.split(":")
val label = parts.get(0).trim()
val expr = parts.get(1).trim()
when {
expr.contains(" ") -> {
val parts = expr.split(" ")
val op = when (parts.get(1)) {
"+" -> Op.Plus
"-" -> Op.Minus
"*" -> Op.Mul
"/" -> Op.Div
else -> throw Error("Unexpected operation: ${parts.get(1)}")
}
put(label, Calc(parts[0], parts[2], op))
}
else -> {
put(label, Just(expr.toLong(10)))
}
}
}
}
private fun calcValue(expressions: Map<String, Expr>, label: String): Long {
val values = mutableMapOf<String, Long>()
fun getValue(label: String): Long {
var value = values[label]
if (value == null) {
val expr = expressions.getValue(label)
value = when (expr) {
is Just ->
expr.value
is Calc -> {
val a = getValue(expr.a)
val b = getValue(expr.b)
expr.operation.calc(a, b)
}
}
values[label] = value
}
return value
}
return getValue(label)
}
private fun matchValuesAt(expressions: Map<String, Expr>, rootLabel: String): Long {
val root = expressions.getValue(rootLabel) as Calc
fun findDeps(start: String, needle: String): List<String> {
val stack = mutableListOf(listOf(start))
while (stack.isNotEmpty()) {
val item = stack.removeFirst()
if (item.first() == needle) {
return item
}
val expr = expressions.getValue(item.first())
if (expr is Just) {
continue
}
if (expr is Calc) {
stack.add(listOf(expr.a).plus(item))
stack.add(listOf(expr.b).plus(item))
}
}
return listOf()
}
val aDeps = findDeps(root.a, "humn")
val bDeps = findDeps(root.b, "humn")
if (aDeps.isNotEmpty() && bDeps.isNotEmpty()) {
TODO("Dont know how to solve this yet")
} else if (aDeps.isEmpty() && bDeps.isEmpty()) {
throw Error("Failed to find dep list to humn")
}
val (targetValue, deps) = if (aDeps.isNotEmpty()) {
println("A: ${root.a}")
Pair(calcValue(expressions, root.b), aDeps)
} else {
println("B: ${root.b}")
Pair(calcValue(expressions, root.a), bDeps)
}
println("$root, targetValue: $targetValue, deps: $deps")
val targetValues = mutableMapOf(Pair(deps.last(), targetValue))
println("$targetValues")
for (pair in deps.reversed().windowed(2, 1)) {
val calc = expressions.getValue(pair.first()) as Calc
val next = pair.last()
val other = if (next == calc.a) calc.b else calc.a
val otherValue = calcValue(expressions, other)
val target = targetValues.getValue(pair.first())
val nextTarget = when (calc.operation) {
Op.Plus -> target - otherValue
Op.Mul -> target / otherValue
Op.Minus -> if (next == calc.a) target + otherValue else otherValue - target
Op.Div -> if (next == calc.a) target * otherValue else otherValue / target
}
targetValues[next] = nextTarget
}
return 0
}
sealed interface Expr
data class Just(val value: Long) : Expr
data class Calc(val a: String, val b: String, val operation: Op) : Expr
enum class Op {
Plus {
override fun calc(a: Long, b: Long): Long = a + b
},
Minus {
override fun calc(a: Long, b: Long): Long = a - b
},
Mul {
override fun calc(a: Long, b: Long): Long = a * b
},
Div {
override fun calc(a: Long, b: Long): Long = a / b
};
abstract fun calc(a: Long, b: Long): Long
}
} | 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 4,831 | aoc2022 | MIT License |
src/twentytwo/Day12.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentytwo
/**
* I used brute force (marking the route on the input) to solve this one initially :|
* Took just under an hour. I really didn't know how to solve it in code
*/
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("Day12_test")
val part1 = part1(testInput)
println(part1)
check(part1 == 31)
val part2 = part2(testInput)
println(part2)
// check(part2 == 45_000)
println("---")
val input = readInputLines("Day12_input")
println(part1(input))
println(part2(input))
}
private data class Map(
val terrain: List<List<Int>>,
val start: Pair<Int, Int>,
val end: Pair<Int, Int>,
)
private fun List<String>.toTerrainMap(): Map {
var start: Pair<Int, Int> = Pair(0,0)
var end: Pair<Int, Int> = Pair(0,0)
val terrain: List<List<Int>> = this.mapIndexed { index, inputLine ->
if (inputLine.contains('S')) {
start = Pair(inputLine.indexOf('S'), index)
}
if (inputLine.contains('E')) {
end = Pair(inputLine.indexOf('E'), index)
}
inputLine.map { it.toHeight() }
}
return Map(terrain, start, end)
}
private fun Char.toHeight(): Int {
val heights = "abcdefghijklmnopqrstuvwxyz"
if (this == 'S') return 0
if (this == 'E') return 25
return heights.indexOf(this)
}
private fun part1(input: List<String>): Int {
val tm = input.toTerrainMap()
println(tm)
return input.size
}
private fun part2(input: List<String>): Int {
return input.size
}
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 1,586 | advent-of-code-solutions | Apache License 2.0 |
2022/kotlin/app/src/main/kotlin/day05/Day05.kt | jghoman | 726,228,039 | false | {"Kotlin": 15309, "Rust": 14555, "Scala": 1804, "Shell": 737} | package day05
import java.util.ArrayDeque
import kotlin.math.ceil
typealias Stacks = Array<ArrayDeque<Char>>
data class MoveInstruction(val quantity: Int, val from: Int, val to: Int)
fun parseMove(s: String): MoveInstruction {
val parts = s.split(" ")
return MoveInstruction(parts[1].toInt(), parts[3].toInt(), parts[5].toInt())
}
fun initStacks(asStrings: List<String>): Stacks {
val numStacks = ceil(asStrings[0].length / 4.0).toInt()
val stacks: Stacks = Array(numStacks) { ArrayDeque<Char>() }
for(column in 0 until numStacks) {
for(line in asStrings.size - 2 downTo 0) {
val crate = asStrings[line][1 + (4 * column)]
if (crate.isWhitespace())
break
stacks[column].push(crate)
}
}
return stacks
}
fun move(stacks: Stacks, move: MoveInstruction) {
repeat(move.quantity) {
val crate = stacks[move.from - 1].pop()
stacks[move.to - 1].push(crate)
}
}
fun movePart2(stacks: Stacks, move: MoveInstruction) {
val holdingColumn = ArrayList<Char>()
repeat(move.quantity) {
val crate = stacks[move.from - 1].pop()
holdingColumn.add(crate)
}
repeat(move.quantity) {
stacks[move.to - 1].push(holdingColumn.removeAt(holdingColumn.size - 1))
}
}
fun part1(input: String):String {
val crates = input.split("\n\n")[0].split("\n")
val movesAsStrings = input.split("\n\n")[1]
val stacks = initStacks(crates)
movesAsStrings
.split("\n")
.map { parseMove(it) }
.forEach { move(stacks, it)}
//.forEach { println(it) }
val topCrates = stacks.map { it.peek() }
.map { it.toString() }
.reduce {acc, s -> s + acc}
.reversed()
return topCrates
}
fun part2(input: String):String {
val crates = input.split("\n\n")[0].split("\n")
val movesAsStrings = input.split("\n\n")[1]
val stacks = initStacks(crates)
movesAsStrings
.split("\n")
.map { parseMove(it) }
.forEach { movePart2(stacks, it) }
//.forEach { println(it) }
val topCrates = stacks.map { it.peek() }
.map { it.toString() }
.reduce {acc, s -> s + acc}
.reversed()
return topCrates
}
fun main() {
val realInput = util.readFileUsingGetResource("day-5-input.txt")
val testInput =
" [D] \n" +
"[N] [C] \n" +
"[Z] [M] [P]\n" +
" 1 2 3 \n" +
"\n" +
"move 1 from 2 to 1\n" +
"move 3 from 1 to 3\n" +
"move 2 from 2 to 1\n" +
"move 1 from 1 to 2"
val input = realInput
println("Part 1 Result = ${part1(input)}")
// FWNSHLDNZ
println("Part 2 Result = ${part2(input)}")
// RNRGDNFQG
} | 0 | Kotlin | 0 | 0 | 2eb856af5d696505742f7c77e6292bb83a6c126c | 2,923 | aoc | Apache License 2.0 |
src/year2021/12/Day12.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2021.`12`
import readInput
private sealed class Place {
data object Start : Place() {
override fun toString(): String = "start"
}
data class LargePlace(val key: String) : Place() {
override fun toString(): String = key
}
data class SmallPlace(val key: String) : Place() {
override fun toString(): String = key
}
data object End : Place() {
override fun toString(): String = "end"
}
fun isStart(): Boolean = this is Start
}
private data class Path(
val from: Place,
val to: Place,
) {
override fun toString(): String {
return "$from-$to"
}
}
private fun Place.neighbours(paths: Set<Path>): Set<Place> {
return paths
.filter { it.from == this }
.map { it.to }
.toSet()
}
fun main() {
fun from(string: String): Place {
return when {
string == "start" -> Place.Start
string == "end" -> Place.End
string.all { it.isUpperCase() } -> Place.LargePlace(string)
string.all { it.isLowerCase() } -> Place.SmallPlace(string)
else -> error("Illegal string: $string")
}
}
fun parse(input: List<String>): Set<Path> {
return input.map {
val (from, to) = it.split("-")
.map(::from)
listOf(Path(from, to), Path(to, from))
}
.flatten()
.toSet()
}
fun recursion(
cache: MutableSet<List<Place>>,
current: Place,
paths: Set<Path>,
currentPath: List<Place>,
placeThatCanBeVisitedTwice: Place?,
visitedPlaces: Map<Place, Int>,
) {
if (current is Place.End) {
cache.add(currentPath + current)
return
}
val amountOfVisited = visitedPlaces.getOrDefault(current, 0).inc()
val newVisitedPlace = visitedPlaces + (current to amountOfVisited)
current.neighbours(paths)
// Do not return to start
.filter { neighbour -> !neighbour.isStart() }
// Do not return to small cave if you were here previously.
.filter { neighbour ->
val threshold = if (neighbour == placeThatCanBeVisitedTwice) {
1
} else {
0
}
val smallPlaceVisitedTwice = (visitedPlaces.getOrDefault(neighbour, 0) > threshold)
val shouldStop = (neighbour is Place.SmallPlace) && smallPlaceVisitedTwice
!shouldStop
}
.forEach {
recursion(
cache = cache,
current = it,
paths = paths,
currentPath = currentPath + current,
placeThatCanBeVisitedTwice = placeThatCanBeVisitedTwice,
visitedPlaces = newVisitedPlace
)
}
}
fun part1(input: List<String>): Int {
val pathSet = parse(input)
val cache = mutableSetOf<List<Place>>()
recursion(
cache = cache,
current = Place.Start,
paths = pathSet,
currentPath = emptyList(),
placeThatCanBeVisitedTwice = null,
visitedPlaces = emptyMap()
)
return cache.size
}
fun part2(input: List<String>): Int {
val pathSet = parse(input)
val cache = mutableSetOf<List<Place>>()
pathSet.map { listOf(it.to, it.from) }
.flatten()
.filterIsInstance<Place.SmallPlace>()
.toSet()
.forEach {
recursion(
cache = cache,
current = Place.Start,
paths = pathSet,
currentPath = emptyList(),
placeThatCanBeVisitedTwice = it,
visitedPlaces = emptyMap()
)
}
return cache.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 10)
val input = readInput("Day12")
println(part1(input).also { check(it == 5254) })
println(part2(input).also { check(it == 149385) })
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 4,361 | KotlinAdventOfCode | Apache License 2.0 |
src/main/kotlin/aoc2022/Day11.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
sealed interface Operation {
fun apply(old: Long): Long
}
object Square : Operation {
override fun apply(old: Long): Long {
return old * old
}
}
class Add(private val add: Int) : Operation {
override fun apply(old: Long): Long {
return old + add
}
}
class Mul(private val mul: Int) : Operation {
override fun apply(old: Long): Long {
return old * mul
}
}
data class Test(val divisor: Long, val whenTrue: Int, val whenFalse: Int) {
fun apply(n: Long) = if (n.rem(divisor) == 0L) whenTrue else whenFalse
}
data class Monkey(
val id: Int,
val items: MutableList<Long>,
val operation: Operation,
val test: Test
)
fun main() {
val testInput = """Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1""".split("\n")
fun String.lastNumber(): Long = substringAfterLast(' ').toLong()
fun parseMonkey(lines: List<String>): Monkey {
val id = lines[0].substringAfter(' ')[0].digitToInt()
val items = listOfNumbers(lines[1].substringAfter(':')).map { it.toLong() }
val op = lines[2].substringAfter('=').trim()
val operation = when (op[4]) {
'*' -> {
when (val param = op.substring(6)) {
"old" -> Square
else -> Mul(param.toInt())
}
}
'+' -> Add(op.substringAfter('+').trim().toInt())
else -> throw IllegalArgumentException("Unsupported operation $op")
}
val test = Test(lines[3].lastNumber(), lines[4].lastNumber().toInt(), lines[5].lastNumber().toInt())
return Monkey(id, items.toMutableList(), operation, test)
}
fun runRound(monkeys: List<Monkey>, counts: MutableMap<Int, Int>, divisor: Long) {
val modulus = monkeys.map { it.test.divisor }.reduce(Long::times)
monkeys.forEach { monkey ->
counts.compute(monkey.id) { _, old -> (old ?: 0) + monkey.items.size }
for (worry in monkey.items) {
val exitWorry = (monkey.operation.apply(worry) / divisor).rem(modulus)
val targetMonkey = monkey.test.apply(exitWorry)
monkeys[targetMonkey].items.add(exitWorry)
}
monkey.items.clear()
}
}
fun part1(input: List<String>): Int {
val monkeys = blocksOfLines(input).map { parseMonkey(it) }.sortedBy { it.id }
val counts = mutableMapOf<Int, Int>()
repeat(20) {
runRound(monkeys, counts, 3)
}
println(counts)
return counts.values.sortedDescending().take(2).reduce(Int::times)
}
fun part2(input: List<String>): Long {
val monkeys = blocksOfLines(input).map { parseMonkey(it) }.sortedBy { it.id }
val counts = mutableMapOf<Int, Int>()
repeat(10_000) {
runRound(monkeys, counts, 1)
if ((it + 1) in listOf(1, 20, 1000)) {
println(counts)
}
}
println(counts)
return counts.values.sortedDescending().take(2).map { it.toLong() }.reduce(Long::times)
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 10605)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 11).toList()
println(part1(puzzleInput))
println(part2(testInput))
println(part2(puzzleInput))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 4,035 | aoc-2022-kotlin | Apache License 2.0 |
src/Day03.kt | tstellfe | 575,291,176 | false | {"Kotlin": 8536} | fun main() {
val alphabetLow = 'a'..'z'
val alphabetBig = 'A'..'Z'
val alphabet = alphabetLow.toMutableList().also { it.addAll(alphabetBig.toList()) }
fun part1(input: List<String>): Int {
return input.sumOf { backpack ->
val half = backpack.length / 2
val comp1 = backpack.substring(0 until half)
val comp2 = backpack.substring(half until backpack.length).toCharArray().joinToString(separator = "|")
val result = comp2.toRegex().find(comp1)?.value ?: throw Exception(backpack)
alphabet.indexOf(result[0]) + 1
}
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3) { group ->
val regex1 = group[0].toCharArray().joinToString(separator = "|").toRegex()
val regex2 = regex1.findAll(group[1]).map { it.value }.joinToString(separator = "|").toRegex()
val result2 = regex2.find(group[2])?.value ?: throw Exception(group.toString())
alphabet.indexOf(result2[0]) + 1
}.sum()
}
val testInput = readInput("Day03_test")
val input = readInput("Day03")
println(part2(testInput))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e100ba705c8e2b83646b172d6407475c27f02eff | 1,105 | adventofcode-2022 | Apache License 2.0 |
2023/day04-25/src/main/kotlin/Day07.kt | CakeOrRiot | 317,423,901 | false | {"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417} | import java.io.File
class Day07 {
fun solve1() {
var hands = File("inputs/7.txt").inputStream().bufferedReader().lineSequence().map { x ->
val split = x.split(' ')
val highCardsMapping = mapOf('A' to 14, 'K' to 13, 'Q' to 12, 'J' to 11, 'T' to 10)
val cards = split[0].map {
if (highCardsMapping.containsKey(it)) highCardsMapping.getOrDefault(it, 1) else it.toString().toInt()
}
Hand1(cards, split[1].toInt())
}.toList()
hands = hands.sorted()
var res = 0L
for (i in 1..hands.count()) {
res += i * hands[i - 1].bid
}
println(res)
}
fun solve2() {
var hands = File("inputs/7.txt").inputStream().bufferedReader().lineSequence().map { x ->
val split = x.split(' ')
val highCardsMapping = mapOf(
'A' to 14,
'K' to 13,
'Q' to 12,
'T' to 11,
'9' to 10,
'8' to 9,
'7' to 8,
'6' to 7,
'5' to 6,
'4' to 5,
'3' to 4,
'2' to 3,
'J' to 2,
)
val cards = split[0].map {
highCardsMapping.getOrDefault(it, 1)
}
Hand2(cards, split[1].toInt())
}.toList()
hands = hands.sorted()
var res = 0L
for (i in 1..hands.count()) {
res += i * hands[i - 1].bid
}
println(res)
}
}
data class Hand1(val cards: List<Int>, val bid: Int) : Comparable<Hand1> {
fun getType(): Int {
val counts = cards.groupingBy { it }.eachCount()
val maxCount = counts.values.max()
return when (maxCount) {
5 -> 7
4 -> 6
3 -> if (counts.values.min() == 2) 5 else 4
2 -> if (counts.filterValues { x -> x == 2 }.count() == 2) 3 else 2
1 -> 1
else -> throw Exception()
}
}
override fun compareTo(other: Hand1): Int {
val type = getType()
val otherType = other.getType()
if (type > otherType) return 1
else if (type < otherType) return -1
else {
for ((card, otherCard) in cards.zip(other.cards)) {
if (card > otherCard) return 1
else if (card < otherCard) return -1
}
return 0
}
}
}
data class Hand2(val cards: List<Int>, val bid: Int) : Comparable<Hand2> {
private fun getType(): Int {
return (2..14).maxOf { replacement ->
val changedCards = cards.map { x -> if (x == 2) replacement else x }
getTypeNoJacks(changedCards)
}
}
private fun getTypeNoJacks(cards: List<Int>): Int {
val counts = cards.groupingBy { it }.eachCount()
val maxCount = counts.values.max()
return when (maxCount) {
5 -> 7
4 -> 6
3 -> if (counts.values.min() == 2) 5 else 4
2 -> if (counts.filterValues { x -> x == 2 }.count() == 2) 3 else 2
1 -> 1
else -> throw Exception()
}
}
override fun compareTo(other: Hand2): Int {
val type = getType()
val otherType = other.getType()
if (type > otherType) return 1
else if (type < otherType) return -1
else {
for ((card, otherCard) in cards.zip(other.cards)) {
if (card > otherCard) return 1
else if (card < otherCard) return -1
}
return 0
}
}
}
| 0 | Kotlin | 0 | 0 | 8fda713192b6278b69816cd413de062bb2d0e400 | 3,662 | AdventOfCode | MIT License |
src/Day14.kt | vjgarciag96 | 572,719,091 | false | {"Kotlin": 44399} | import kotlin.math.abs
fun main() {
data class Point(val x: Int, val y: Int)
fun part1(input: List<String>): Int {
val rocks = input.flatMap { line ->
val rockPathPoints = line.split(" -> ").map { rawPoint ->
val (x, y) = rawPoint.split(",")
Point(x.toInt(), y.toInt())
}
rockPathPoints.windowed(size = 2) { (pointA, pointB) ->
val horizontalDistance = abs(pointA.x - pointB.x)
val verticalDistance = abs(pointA.y - pointB.y)
if (verticalDistance == 0) {
val maxX = maxOf(pointA.x, pointB.x)
val minX = minOf(pointA.x, pointB.x)
(minX..maxX).map { x -> Point(x, pointA.y) }
} else if (horizontalDistance == 0) {
val maxY = maxOf(pointA.y, pointB.y)
val minY = minOf(pointA.y, pointB.y)
(minY..maxY).map { y -> Point(pointA.x, y) }
} else {
error("Lines must be vertical or horizontal")
}
}.flatten()
}
val sandObstacles = ArrayList<Point>().apply { addAll(rocks) }
val downfallLimit = rocks.maxBy { it.y }.y
var currentSandUnit = Point(500, 0)
while (currentSandUnit.y <= downfallLimit) {
val downPoint = Point(currentSandUnit.x, currentSandUnit.y + 1)
val downLeftPoint = Point(currentSandUnit.x - 1, currentSandUnit.y + 1)
val downRightPoint = Point(currentSandUnit.x + 1, currentSandUnit.y + 1)
currentSandUnit = if (downPoint !in sandObstacles) {
downPoint
} else if (downLeftPoint !in sandObstacles) {
downLeftPoint
} else if (downRightPoint !in sandObstacles) {
downRightPoint
} else {
sandObstacles.add(currentSandUnit)
Point(500, 0)
}
}
return sandObstacles.minus(rocks).count()
}
fun part2(input: List<String>): Int {
val rocks = input.flatMap { line ->
val rockPathPoints = line.split(" -> ").map { rawPoint ->
val (x, y) = rawPoint.split(",")
Point(x.toInt(), y.toInt())
}
rockPathPoints.windowed(size = 2) { (pointA, pointB) ->
val horizontalDistance = abs(pointA.x - pointB.x)
val verticalDistance = abs(pointA.y - pointB.y)
if (verticalDistance == 0) {
val maxX = maxOf(pointA.x, pointB.x)
val minX = minOf(pointA.x, pointB.x)
(minX..maxX).map { x -> Point(x, pointA.y) }
} else if (horizontalDistance == 0) {
val maxY = maxOf(pointA.y, pointB.y)
val minY = minOf(pointA.y, pointB.y)
(minY..maxY).map { y -> Point(pointA.x, y) }
} else {
error("Lines must be vertical or horizontal")
}
}.flatten()
}
val sandObstacles = HashSet<Point>().apply { addAll(rocks) }
val floor = rocks.maxBy { it.y }.y + 2
var currentSandUnit = Point(500, 0)
while (true) {
val downPoint = Point(currentSandUnit.x, currentSandUnit.y + 1)
val downLeftPoint = Point(currentSandUnit.x - 1, currentSandUnit.y + 1)
val downRightPoint = Point(currentSandUnit.x + 1, currentSandUnit.y + 1)
currentSandUnit = if (downPoint !in sandObstacles && downPoint.y < floor) {
downPoint
} else if (downLeftPoint !in sandObstacles && downPoint.y < floor) {
downLeftPoint
} else if (downRightPoint !in sandObstacles && downPoint.y < floor) {
downRightPoint
} else {
sandObstacles.add(currentSandUnit)
if (currentSandUnit == Point(500, 0)) break
Point(500, 0)
}
}
return sandObstacles.minus(rocks).count()
}
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ee53877877b21166b8f7dc63c15cc929c8c20430 | 4,350 | advent-of-code-2022 | Apache License 2.0 |
src/Day24.kt | wgolyakov | 572,463,468 | false | null | fun main() {
class Cell {
val obstacles = mutableListOf<Char>()
var distance = -1
}
class Point(val x: Int, val y: Int, val t: Int)
fun parse(input: List<String>): List<List<Cell>> {
val map = List(input.size) { List(input[0].length) { Cell() } }
for (y in input.indices)
for (x in input[y].indices)
if (input[y][x] != '.') map[y][x].obstacles.add(input[y][x])
return map
}
val positionToMove = mapOf(
'#' to (0 to 0),
'^' to (0 to -1),
'v' to (0 to 1),
'<' to (-1 to 0),
'>' to (1 to 0),
)
fun addFrame(mapInTime: MutableList<List<List<Cell>>>) {
val curr = mapInTime.last()
val next = List(curr.size) { List(curr[0].size) { Cell() } }
for (y in curr.indices) {
for (x in curr[y].indices) {
for (c in curr[y][x].obstacles) {
val (dx, dy) = positionToMove[c]!!
var nx = x + dx
var ny = y + dy
if (c != '#') {
if (nx <= 0) nx = curr[y].size - 2
if (nx >= curr[y].size - 1) nx = 1
if (ny <= 0) ny = curr.size - 2
if (ny >= curr.size - 1) ny = 1
}
next[ny][nx].obstacles.add(c)
}
}
}
mapInTime.add(next)
}
fun trip(map: List<List<Cell>>, start: Point, stop: Point): List<List<Cell>>? {
val mapInTime = mutableListOf(map)
val queue = ArrayDeque<Point>()
queue.addLast(start)
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
if (curr.x == stop.x && curr.y == stop.y)
return mapInTime[curr.t]
if (mapInTime.size <= curr.t + 1)
addFrame(mapInTime)
val neighbors = listOf(
Point(curr.x + 1, curr.y, curr.t + 1),
Point(curr.x - 1, curr.y, curr.t + 1),
Point(curr.x, curr.y + 1, curr.t + 1),
Point(curr.x, curr.y - 1, curr.t + 1),
Point(curr.x, curr.y, curr.t + 1),
).filter { it.x in map[0].indices && it.y in map.indices }
.filter { mapInTime[it.t][it.y][it.x].obstacles.isEmpty() }
for (next in neighbors) {
if (mapInTime[next.t][next.y][next.x].distance == -1) {
mapInTime[next.t][next.y][next.x].distance = mapInTime[curr.t][curr.y][curr.x].distance + 1
queue.addLast(next)
}
}
}
return null
}
fun part1(input: List<String>): Int {
var map = parse(input)
val start = Point(1, 0, 0)
val stop = Point(map[0].size - 2, map.size - 1, 0)
map[start.y][start.x].distance = 0
map = trip(map, start, stop) ?: return -1
return map[stop.y][stop.x].distance
}
fun part2(input: List<String>): Int {
var map = parse(input)
val start = Point(1, 0, 0)
val stop = Point(map[0].size - 2, map.size - 1, 0)
map[start.y][start.x].distance = 0
map = trip(map, start, stop) ?: return -1
map = trip(map, stop, start) ?: return -1
map = trip(map, start, stop) ?: return -1
return map[stop.y][stop.x].distance
}
val testInput = readInput("Day24_test")
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInput("Day24")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 2,916 | advent-of-code-2022 | Apache License 2.0 |
src/adventofcode/blueschu/y2017/day20/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day20
import java.io.File
import kotlin.math.abs
import kotlin.test.assertEquals
val input: List<String> by lazy {
File("resources/y2017/day20.txt")
.bufferedReader()
.use { r -> r.readLines() }
}
fun main(args: Array<String>) {
println("Part 1: ${part1(input)}")
assertEquals(1, part2(listOf(
"p=<-6,0,0>, v=<3,0,0>, a=<0,0,0>",
"p=<-4,0,0>, v=<2,0,0>, a=<0,0,0>",
"p=<-2,0,0>, v=<1,0,0>, a=<0,0,0>",
"p=<3,0,0>, v=<-1,0,0>, a=<0,0,0>"))
)
println("Part 2: ${part2(input)}")
}
data class CartesianVector(var x: Int, var y: Int, var z: Int) {
val manhattan get() = abs(x) + abs(y) + abs(z)
fun offset(dx: Int, dy: Int, dz: Int) {
x += dx
y += dy
z += dz
}
fun offset(delta: CartesianVector) =
offset(delta.x, delta.y, delta.z)
}
data class Particle(
val pos: CartesianVector,
val vel: CartesianVector,
val acc: CartesianVector
)
fun parseParticle(token: String): Particle {
val pattern = ("p=<(-?\\d+),(-?\\d+),(-?\\d+)>, " +
"v=<(-?\\d+),(-?\\d+),(-?\\d+)>, " +
"a=<(-?\\d+),(-?\\d+),(-?\\d+)>").toRegex()
val match = pattern.matchEntire(token)
?: throw IllegalArgumentException("Particle could not be parsed: $token")
val result = match
.groupValues
.takeLast(9)
.map(String::toInt)
val (pos, vel, acc) = result.chunked(3)
return Particle(
pos = CartesianVector(pos[0], pos[1], pos[2]),
vel = CartesianVector(vel[0], vel[1], vel[2]),
acc = CartesianVector(acc[0], acc[1], acc[2])
)
}
fun part1(particlesDesc: List<String>): Int {
val particles = particlesDesc.map { parseParticle(it) }
// Find the particles with the lowest acceleration
val minAcc = particles.map { it.acc.manhattan }.min()!!
val lowestAccParticles = particles.filter { it.acc.manhattan == minAcc }
// Find the particle with the least initial velocity, assuming that
// each particles has a distinct velocity
val result = lowestAccParticles.minBy { it.vel.manhattan }!!
return particles.indexOf(result)
}
fun part2(particlesDesc: List<String>): Int {
var particles = particlesDesc.map { parseParticle(it) }
// 39 ticks produced all possible collisions for the provided input.
// The required tick count will vary for other puzzle inputs.
repeat(times = 39) {
particles.forEach {
it.vel.offset(it.acc)
it.pos.offset(it.vel)
}
// remove collocated particles
particles = particles
.groupBy { it.pos }
.filter { it.value.size == 1 }
.flatMap { it.value }
}
return particles.size
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 2,771 | Advent-Of-Code | MIT License |
src/main/kotlin/aoc2020/ex13.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | import kotlin.math.max
fun main() {
//part1()
part2()
}
private fun part2() {
val input = "7,13,x,x,59,x,31,19"
// require(findFirstTimeFor("17,x,13,19") == 3417L)
// require(findFirstTimeFor("7,13,x,x,59,x,31,19") == 1068781L)
// require(findFirstTimeFor("67,7,59,61") == 754018L)
// require(findFirstTimeFor("67,x,7,59,61") == 779210L)
// require(findFirstTimeFor("67,7,x,59,61") == 1261476L)
// require(findFirstTimeFor("1789,37,47,1889") == 1202161486L)
print(findFirstTimeFor("17,x,x,x,x,x,x,41,x,x,x,x,x,x,x,x,x,937,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,13,x,x,x,x,23,x,x,x,x,x,29,x,397,x,x,x,x,x,37,x,x,x,x,x,x,x,x,x,x,x,x,19"))
}
private fun findFirstTimeFor(input: String): Long {
val busses = input
.split(",")
//.filter { it != "x" }
.map {
if (it == "x") -1 else it.toLong()
}
val maxBus = busses.maxOrNull()!!
val nextMax = busses.maxOfOrNull {
if (it == maxBus) -1 else it
} ?: maxBus
val maxPlace = busses.indexOf(maxBus)
val nextMaxPlace = busses.indexOf(nextMax)
val (firstOption, distanceBetweenCanditades) =
if(busses.count { it != -1L } == 2 ) {
findFirstOption(maxBus, maxBus, maxPlace, maxPlace)
} else {
findFirstOption(maxBus, nextMax, maxPlace, nextMaxPlace)
}
println(maxBus)
println(firstOption)
var current = firstOption
var iter = 0L
val maxIter = 100_000_000_000L
val printIter = max(1L, maxIter / 10_000L)
while (iter < maxIter) {
iter++
if(iter % printIter == 0L
|| current / 100L == 10687L
) {
println("iteration $iter. candidate is $current")
}
if (checkNumber(current, busses)) {
print("found $current!")
return current
}
current += distanceBetweenCanditades
}
return -1
}
fun findFirstOption(max: Long, nextMax: Long, maxPlace: Int, nextMaxPlace: Int): Pair<Long, Long> {
if (max == nextMax) {
return max - maxPlace.toLong() to max
}
//println("next max $nextMax")
val lcm = lcm(nextMax, max)
val constructedBussed = List<String>(max(maxPlace, nextMaxPlace)+1) {
print(it)
when (it) {
maxPlace -> max.toInt().toString()
nextMaxPlace -> nextMax.toInt().toString()
else -> "x"
}.also { print(": $it\n") }
}.joinToString(",")
println(constructedBussed)
val fistTime = findFirstTimeFor(constructedBussed)
return fistTime to lcm(max, nextMax)
}
fun checkNumber(number: Long, busses: List<Long>): Boolean {
busses.forEachIndexed { index, bus: Long ->
if (bus == -1L) return@forEachIndexed
if ((number + index.toLong()) % bus != 0L) return false
}
return true
}
private fun part1() {
// from actual file
val input = """
1007268
17,x,x,x,x,x,x,41,x,x,x,x,x,x,x,x,x,937,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,13,x,x,x,x,23,x,x,x,x,x,29,x,397,x,x,x,x,x,37,x,x,x,x,x,x,x,x,x,x,x,x,19
""".trimIndent()
// val input = """
// 939
// 7,13,x,x,59,x,31,19
// """.trimIndent()
// val input = """
// 24
// 2,3,5,6,7,11,13
// """.trimIndent()
val lines = input.lines()
val timeGettingToBusStation = lines[0].toInt()
val busses = lines[1]
.split(",")
.filter { it != "x" }
.map {
it.toInt()
}
println(busses)
val busAndNextTimeForEachBus = busses.associateWith { busInterval ->
timeGettingToBusStation.ceilToProductOf(busInterval)
}
val nextBus = busAndNextTimeForEachBus.minByOrNull { it.value }!!
println("next bus $nextBus")
val waitTime = nextBus.value - timeGettingToBusStation
println(waitTime * nextBus.key)
}
fun Int.ceilToProductOf(interval: Int) = (this + interval - 1).floorToProductOf(interval)
fun Int.floorToProductOf(interval: Int) = this - Math.floorMod(this, interval)
fun lcm(n1: Long, n2: Long): Long {
var lcm: Long = if (n1 > n2) n1 else n2
while (true) {
if (lcm % n1 == 0L && lcm % n2 == 0L) {
return lcm
}
lcm++
}
} | 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 4,208 | AOC-2021 | MIT License |
src/main/kotlin/fp/algorithm/programmers_42785.kt | treetory | 238,101,549 | true | {"Kotlin": 312666} | package fp.algorithm
import fp.kotlin.example.head
import fp.kotlin.example.tail
fun main() {
val answer = make(arrayOf(1,5,2,6,3,7,4), arrayOf(arrayOf(2,5,3), arrayOf(4,4,1), arrayOf(1,7,3)), listOf())
answer.forEach { e -> println(e) }
}
// 자르고
private fun cut(start: Int, end: Int, arr: Array<Int>): List<Int> {
return arr.copyOfRange(start-1, end).asList()
}
// 정렬하고
private fun quicksort(list: List<Int>): List<Int> = when {
list.isEmpty() -> list
else -> {
val pivot = list.head()
val (small, bigger) = list.tail().partition { it < pivot }
quicksort(small) + listOf(pivot) + quicksort(bigger)
}
}
// 뽑아서 결과에 붙임 (acc 에 누적)
private fun make(arr: Array<Int>, commands: Array<Array<Int>>, acc: List<Int> = listOf()): Array<Int> = when {
commands.isEmpty() -> acc.toTypedArray()
else -> {
val temp = commands[0]
val sorted = quicksort(cut(temp[0], temp[1], arr))
val next = commands.drop(1)
if (next.isEmpty()) {
make(arr, arrayOf(), acc.plus(sorted[temp[2]-1]))
} else {
make(arr, next.toTypedArray(), acc.plus(sorted[temp[2]-1]))
}
}
}
| 0 | Kotlin | 0 | 0 | a4f323b1e6ca24644185e834eed17cf447baee78 | 1,212 | fp-kotlin-example | MIT License |
src/Day19.kt | wgolyakov | 572,463,468 | false | null | typealias Cost = MutableList<Int>
fun main() {
fun cost(ore: Int, clay: Int, obsidian: Int, geode: Int = 0) = mutableListOf(ore, clay, obsidian, geode)
class State(val t: Int = 0,
val resources: Cost = cost(0, 0, 0, 0),
val robots: Cost = cost(1, 0, 0, 0))
class Blueprint(val num: Int, val robotCosts: List<Cost>) {
var maxGeodes = 0
var maxT = 0
var maxState = State()
val allMaxStates = mutableListOf<State>()
}
fun parse(input: List<String>): List<Blueprint> {
val blueprints = mutableListOf<Blueprint>()
for (line in input) {
val b = Regex("Blueprint (\\d+): " +
"Each ore robot costs (\\d+) ore. " +
"Each clay robot costs (\\d+) ore. " +
"Each obsidian robot costs (\\d+) ore and (\\d+) clay. " +
"Each geode robot costs (\\d+) ore and (\\d+) obsidian.")
.matchEntire(line)!!.groupValues.takeLast(7).map { it.toInt() }
val blueprint = Blueprint(b[0], listOf(
cost(b[1], 0, 0),
cost(b[2], 0, 0),
cost(b[3], b[4], 0),
cost(b[5], 0, b[6])))
blueprints.add(blueprint)
}
return blueprints
}
fun canBuild(resources: Cost, robotCost: Cost): Boolean {
for (i in 0 until 4)
if (resources[i] < robotCost[i]) return false
return true
}
fun addResources(resources: Cost, r: Cost) { for (i in 0 until 4) resources[i] += r[i] }
fun removeResources(resources: Cost, r: Cost) { for (i in 0 until 4) resources[i] -= r[i] }
fun traverse(b: Blueprint, state: State, findAllMaximums: Boolean = false) {
if (state.t == b.maxT) {
if (state.resources[3] > b.maxGeodes) {
b.maxGeodes = state.resources[3]
b.maxState = state
} else if (findAllMaximums && state.resources[3] == b.maxGeodes) {
b.allMaxStates.add(state)
}
return
}
var canBuildCount = 0
for (r in 0 until 4) {
val robotCost = b.robotCosts[r]
if (canBuild(state.resources, robotCost)) {
canBuildCount++
// Start building robot
val resources = state.resources.toMutableList()
val robots = state.robots.toMutableList()
removeResources(resources, robotCost)
// Robots collects resources
addResources(resources, robots)
// Stop building robot
robots[r]++
traverse(b, State(state.t + 1, resources, robots), findAllMaximums)
}
}
if (canBuildCount <= 1) {
// Don't build robot
val resources = state.resources.toMutableList()
val robots = state.robots.toMutableList()
// Robots collects resources
addResources(resources, robots)
traverse(b, State(state.t + 1, resources, robots), findAllMaximums)
}
}
fun part1(input: List<String>): Int {
val blueprints = parse(input)
for (b in blueprints) {
b.maxT = 24
traverse(b, State())
println("${b.num} t: ${b.maxState.t} res:${b.maxState.resources} rob:${b.maxState.robots}")
}
println(blueprints.joinToString { it.maxGeodes.toString() })
return blueprints.sumOf { it.num * it.maxGeodes }
}
fun part2(input: List<String>, firstT: Int): Int {
val blueprints = parse(input.take(3))
for (b in blueprints) {
b.maxT = firstT
traverse(b, State())
println("${b.num} t: ${b.maxState.t} res:${b.maxState.resources} rob:${b.maxState.robots}")
traverse(b, State(), true)
b.maxT = 32
for (state in b.allMaxStates)
traverse(b, state)
}
println(blueprints.joinToString { it.maxGeodes.toString() })
return blueprints.map { it.maxGeodes }.reduce { a, b -> a * b }
}
val testInput = readInput("Day19_test")
check(part1(testInput) == 33)
check(part2(testInput, 25) == 56 * 62)
val input = readInput("Day19")
println(part1(input))
println(part2(input, 26))
}
| 0 | Kotlin | 0 | 0 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 3,594 | advent-of-code-2022 | Apache License 2.0 |
src/day24.kt | miiila | 725,271,087 | false | {"Kotlin": 77215} | import java.io.File
import kotlin.system.exitProcess
private const val DAY = 24
fun main() {
if (!File("./day${DAY}_input").exists()) {
downloadInput(DAY)
println("Input downloaded")
exitProcess(0)
}
val transformer = { x: String ->
x.split(" @ ").let {
Pair(
it[0].split(",").map(String::trim).map(String::toDouble),
it[1].split(", ").map(String::trim).map(String::toDouble)
)
}
}
val input = loadInput(DAY, false, transformer)
// println(input)
println(solvePart1(input))
solvePart2(input)
}
data class LineXY(val x: Double, val y: Double, val dx: Double, val dy: Double) {
val slope = dy / dx
val b = y - slope * x
fun getYforX(x: Double): Double {
return slope * x + b
}
}
// Part 1
private fun solvePart1(input: List<Pair<List<Double>, List<Double>>>): Int {
val lines = input.map { it -> LineXY(it.first[0], it.first[1], it.second[0], it.second[1]) }
val res = mutableListOf<Pair<Pair<Double, Double>?, Boolean>>()
for ((i, line) in lines.withIndex()) {
for (line2 in lines.drop(i + 1)) {
res.add(
Pair(
getIntersection(line, line2),
willIntersect(line, line2, 200000000000000.0, 400000000000000.0)
)
)
}
}
return res.count { it.second }
}
fun getIntersection(a: LineXY, b: LineXY): Pair<Double, Double>? {
val x = (b.b - a.b) / (a.slope - b.slope)
if (x == Double.POSITIVE_INFINITY) {
return null
}
val y = a.getYforX(x)
return Pair(x, y)
}
fun willIntersect(a: LineXY, b: LineXY, min: Double, max: Double): Boolean {
val intersection = getIntersection(a, b) ?: return false
if (intersection.first !in (min..max) || intersection.second !in (min..max)) {
return false
}
if ((a.dx < 0 && intersection.first > a.x) || (a.dx > 0 && intersection.first < a.x)) {
return false
}
if ((a.dy < 0 && intersection.second > a.y) || (a.dy > 0 && intersection.second < a.y)) {
return false
}
if ((b.dx < 0 && intersection.first > b.x) || (b.dx > 0 && intersection.first < b.x)) {
return false
}
if ((b.dy < 0 && intersection.second > b.y) || (b.dy > 0 && intersection.second < b.y)) {
return false
}
return true
}
// Part 2
private fun solvePart2(input: List<Pair<List<Double>, List<Double>>>) {
val velocities = mutableListOf<List<Long>>()
val startingPoints = mutableListOf<List<Long>>()
for (inp in input) {
velocities.add(inp.first.map(Double::toLong))
startingPoints.add(inp.second.map(Double::toLong))
}
println(velocities)
println(startingPoints)
}
| 0 | Kotlin | 0 | 1 | 1cd45c2ce0822e60982c2c71cb4d8c75e37364a1 | 2,797 | aoc2023 | MIT License |
src/Day03.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | fun main() {
fun calcPriority(c: Char) = when {
c.isUpperCase() -> c - 'A' + 27
c.isLowerCase() -> c - 'a' + 1
else -> 0
}
fun part1(input: List<String>): Int {
return input.sumOf {
val size = it.length / 2
it.take(size)
.toSet()
.let { leftDict -> it.substring(size).first { c -> c in leftDict } }
.let { c -> calcPriority(c) }
}
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3)
.sumOf{ lines ->
lines[0].filter { lines[1].toSet().contains(it) }
.first { lines[2].toSet().contains(it) }
.let { c -> calcPriority(c) }
}
}
val input = readInput("Day03")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 860 | advent-of-code-kotlin | Apache License 2.0 |
src/Day03.kt | dmdrummond | 573,289,191 | false | {"Kotlin": 9084} | fun main() {
fun priorityForCharacter(char: Char): Int {
val code = char.code
return if (code > 96 ) {
code - 96
} else {
code - 38
}
}
fun splitAndFindCommonCharacter(input: String): Char {
val first = input.substring(0 until input.length / 2)
val second = input.substring(input.length/2 until input.length)
for (char in first) {
if (second.contains(char)){
return char
}
}
throw Error("No duplicate found")
}
fun findCommonElement(input1: String, input2: String, input3: String): Char {
for (char in input1) {
if (input2.contains(char) && input3.contains(char)){
return char
}
}
throw Error("No badge found")
}
fun part1(input: List<String>) = input
.map { splitAndFindCommonCharacter(it) }
.sumOf { priorityForCharacter(it) }
fun part2(input: List<String>) = input
.chunked(3)
.map { findCommonElement(it[0], it[1], it[2]) }
.sumOf { priorityForCharacter(it) }
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 2493256124c341e9d4a5e3edfb688584e32f95ec | 1,370 | AoC2022 | Apache License 2.0 |
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p08/Leet886.kt | artemkaxboy | 513,636,701 | false | {"Kotlin": 547181, "Java": 13948} | package com.artemkaxboy.leetcode.p08
import com.artemkaxboy.leetcode.LeetUtils.toIntArray
import java.util.*
import kotlin.system.measureTimeMillis
class Leet886 {
class Solution {
fun possibleBipartition(n: Int, dislikes: Array<IntArray>): Boolean {
val dislikeMap = HashMap<Int, LinkedList<Int>>(n, 1.0f)
for (dislike in dislikes) {
dislikeMap.compute(dislike[0]) { k, v -> (v ?: LinkedList()).also { it.add(dislike[1]) } }
dislikeMap.compute(dislike[1]) { k, v -> (v ?: LinkedList()).also { it.add(dislike[0]) } }
}
var next = dislikeMap.entries.firstOrNull()
while (next != null) {
val discovered = HashSet<Int>().apply { add(next!!.key) }
val queue = LinkedList<Pair<Boolean, Int>>().apply { add(true to next!!.key) }
val clusters = mapOf(true to HashSet<Int>().apply { add(next!!.key) }, false to HashSet())
while (queue.isNotEmpty()) {
val (cluster, toDiscover) = queue.poll()
val opposites = dislikeMap.remove(toDiscover)!!
val selfCluster = clusters[cluster]!!
val oppositeCluster = clusters[!cluster]!!
for (opposite in opposites) {
if (selfCluster.contains(opposite)) return false
oppositeCluster.add(opposite)
if (discovered.add(opposite)) {
queue.add(!cluster to opposite)
}
}
}
next = dislikeMap.entries.firstOrNull()
}
return true
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
val testCase1 = Data("", "")
doWork(testCase1)
}
private fun doWork(data: Data) {
val solution = Solution()
val result: Any
val time = measureTimeMillis {
result = solution.possibleBipartition(
300,
"[[1,2],[2,3],[1,3]".split("],[").map { it.toIntArray() }.toTypedArray()
)
}
println("Data: ${data.input}")
println("Expected: ${data.expected}")
println("Result: $result")
println("Time: $time\n")
if (data.expected != result) {
throw AssertionError("\nExpected: ${data.expected}\nActual: $result")
}
}
}
data class Data(
val input: Any,
val expected: Any
)
}
| 0 | Kotlin | 0 | 0 | 516a8a05112e57eb922b9a272f8fd5209b7d0727 | 2,684 | playground | MIT License |
src/Day05.kt | befrvnk | 574,229,637 | false | {"Kotlin": 15788} | data class Movement(
val count: Int,
val from: Int,
val to: Int,
)
fun main() {
fun part1(input: List<String>): String {
val separatorLineIndex = input.indexOfFirst { it.isEmpty() }
val stackLines = input.subList(0, separatorLineIndex - 1)
val stackNames = input[separatorLineIndex - 1]
val stacks = (1..stackNames.length step 4).map { index ->
stackLines.reversed()
.mapNotNull { line ->
line.getOrNull(index)?.takeUnless { it.isWhitespace() }?.toString()
}
.toMutableList()
}
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
val movementLines = input.subList(separatorLineIndex + 1, input.size)
val movements = movementLines.mapNotNull {
regex.find(it)?.destructured?.let { (count, from, to) ->
Movement(count.toInt(), from.toInt(), to.toInt())
}
}
movements.forEach { movement ->
repeat(movement.count) {
val removed = stacks[movement.from - 1].removeLast()
stacks[movement.to - 1].add(removed)
}
}
return stacks.joinToString(separator = "") { it.last() }
}
fun part2(input: List<String>): String {
val separatorLineIndex = input.indexOfFirst { it.isEmpty() }
val stackLines = input.subList(0, separatorLineIndex - 1)
val stackNames = input[separatorLineIndex - 1]
val stacks = (1..stackNames.length step 4).map { index ->
stackLines.reversed()
.mapNotNull { line ->
line.getOrNull(index)?.takeUnless { it.isWhitespace() }?.toString()
}
.toMutableList()
}
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
val movementLines = input.subList(separatorLineIndex + 1, input.size)
val movements = movementLines.mapNotNull {
regex.find(it)?.destructured?.let { (count, from, to) ->
Movement(count.toInt(), from.toInt(), to.toInt())
}
}
movements.forEach { movement ->
val removed = (1..movement.count).map { stacks[movement.from - 1].removeLast() }.reversed()
stacks[movement.to - 1].addAll(removed)
}
return stacks.joinToString(separator = "") { it.last() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 68e5dd5656c052d8c8a2ea9e03c62f4cd2438dd7 | 2,698 | aoc-2022-kotlin | Apache License 2.0 |
src/day04/Day04.kt | molundb | 573,623,136 | false | {"Kotlin": 26868} | package day04
import readInput
fun main() {
val input = readInput(parent = "src/day04", name = "Day04_input")
println(solvePartOne(input))
println(solvePartTwo(input))
}
private fun solvePartOne(input: List<String>): Int = solve(input, partOneOverlapCheck())
private fun solvePartTwo(input: List<String>): Int = solve(input, partTwoOverlapCheck())
private fun partOneOverlapCheck(): (Int, Int, Int, Int) -> Boolean =
{ startPairOne: Int, startPairTwo: Int, endPairOne: Int, endPairTwo: Int ->
startPairOne >= startPairTwo && endPairOne <= endPairTwo || startPairOne <= startPairTwo && endPairOne >= endPairTwo
}
private fun partTwoOverlapCheck(): (Int, Int, Int, Int) -> Boolean =
{ startPairOne: Int, startPairTwo: Int, endPairOne: Int, endPairTwo: Int -> !(endPairOne < startPairTwo || startPairOne > endPairTwo) }
private fun solve(input: List<String>, overlapCheck: (Int, Int, Int, Int) -> Boolean): Int {
var sumOverlap = 0
input.forEach {
val pair = it.split(',')
val startAndEndPairOne = pair[0].split('-')
val startAndEndPairTwo = pair[1].split('-')
val startPairOne = startAndEndPairOne[0].toInt()
val startPairTwo = startAndEndPairTwo[0].toInt()
val endPairOne = startAndEndPairOne[1].toInt()
val endPairTwo = startAndEndPairTwo[1].toInt()
if (overlapCheck(startPairOne, startPairTwo, endPairOne, endPairTwo)) {
sumOverlap++
}
}
return sumOverlap
} | 0 | Kotlin | 0 | 0 | a4b279bf4190f028fe6bea395caadfbd571288d5 | 1,499 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/io/matrix/WallsAndGates.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.matrix
import io.utils.runTests
// https://leetcode.com/problems/walls-and-gates/
class WallsAndGates {
fun execute(input: Array<IntArray>) {
if (input.isEmpty() || input.first().isEmpty()) return
val gates = mutableListOf<Pair<Int, Int>>()
input.forEachIndexed { row, column ->
column.forEachIndexed { col, value ->
when (value) {
0 -> gates.add(row to col)
}
}
}
for (current in gates) {
val visited = mutableListOf<Pair<Int, Int>>()
var stack = generateChild(input, current, visited)
var distance = 1
while (stack.isNotEmpty()) {
stack = stack.flatMap { (row, col) ->
when {
visited.contains(row to col) -> emptyList()
distance < input[row][col] -> {
visited.add(row to col)
input[row][col] = distance
generateChild(input, row to col, visited)
}
else -> {
visited.add(row to col)
emptyList()
}
}
}
distance++
}
}
}
fun generateChild(input: Array<IntArray>, coordinates: Pair<Int, Int>, visited: Collection<Pair<Int, Int>>): List<Pair<Int, Int>> {
val result = mutableListOf<Pair<Int, Int>>()
val invalids = listOf(0, -1)
if (coordinates.first + 1 < input.size && input[coordinates.first + 1][coordinates.second] !in invalids && !visited.contains(coordinates.first + 1 to coordinates.second))
result.add(coordinates.first + 1 to coordinates.second)
if (coordinates.first - 1 >= 0 && input[coordinates.first - 1][coordinates.second] !in invalids && !visited.contains(coordinates.first - 1 to coordinates.second))
result.add(coordinates.first - 1 to coordinates.second)
if (coordinates.second + 1 < input.first().size && input[coordinates.first][coordinates.second + 1] !in invalids && !visited.contains(coordinates.first to coordinates.second + 1))
result.add(coordinates.first to coordinates.second + 1)
if (coordinates.second - 1 >= 0 && input[coordinates.first][coordinates.second - 1] !in invalids && !visited.contains(coordinates.first to coordinates.second - 1))
result.add(coordinates.first to coordinates.second - 1)
return result
}
}
fun main() {
runTests(listOf(
arrayOf(
intArrayOf(Int.MAX_VALUE, -1, 0, Int.MAX_VALUE),
intArrayOf(Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE, -1),
intArrayOf(Int.MAX_VALUE, -1, Int.MAX_VALUE, -1),
intArrayOf(0, -1, Int.MAX_VALUE, Int.MAX_VALUE)
) to listOf(
listOf(3, -1, 0, 1),
listOf(2, 2, 1, -1),
listOf(1, -1, 2, -1),
listOf(0, -1, 3, 4)
)
)) { (input, value) -> value to input.also { WallsAndGates().execute(input) }.map { it.toList() }.toList() }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 2,846 | coding | MIT License |
src/Day15.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.io.File
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.max
// Advent of Code 2022, Day 15, Beacon Exclusion Zone
typealias Pt = Pair<Int, Int>
fun main() {
// Manhattan distance
fun Pt.distance(other: Pt) = abs(this.first - other.first) + abs(this.second - other.second)
fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim()
fun part1(input: String, inputRow: Int): Int {
val readings = input.split("\n")
.map {
it.split("Sensor at x=", ", y=", ": closest beacon is at x=")
.drop(1) // initial empty
.map { it.toInt() }
}.map {
Pair(it[0] to it[1], it[2] to it[3])
}
val sensors = readings.filter {
// can reach inputRow
val range = it.first.distance(it.second)
range >= it.first.distance(Pair(it.first.first, inputRow))
}
val ptsInRange = mutableSetOf<Pt>()
val beaconLocations = sensors.map { it.second }.toSet()
sensors.forEach {
val range = it.first.distance(it.second)
for (x in (it.first.first - range)..(it.first.first + range)) {
val pt = x to inputRow
if (pt !in beaconLocations && it.first.distance(pt) <= range) {
ptsInRange.add(pt)
}
}
}
return ptsInRange.size
}
// Return a list of pairs. Each pair has a sensor position and a sensor range.
fun parse(input: String): List<Pair<Pair<Int, Int>, Int>> =
input.split("\n")
.map {
it.split("Sensor at x=", ", y=", ": closest beacon is at x=")
.drop(1) // initial empty
.map { it.toInt() }
}.map {
val sensor = it[0] to it[1]
val dist = sensor.distance(it[2] to it[3])
Pair(sensor, dist)
}
fun part2(input: String, maxCoord: Int): Long {
val readings = parse(input)
repeat(maxCoord+1) {inputRow ->
var xCoord = mutableListOf<Pair<Int, Int>>() // x ranges, inclusive
xCoord.add(0 to maxCoord)
run pointCheck@{
readings.forEachIndexed { _, it ->
val range = it.second
val distToRow = abs(it.first.second - inputRow)
if (range < distToRow) {
return@forEachIndexed // can't reach this row
}
val newxCoord = mutableListOf<Pair<Int, Int>>()
val rowRange = range - abs(inputRow - it.first.second)
val removeRange = max(0, (it.first.first - rowRange)) to min(maxCoord, (it.first.first + rowRange))
xCoord.forEach { xRange ->
if (removeRange.first > xRange.second || removeRange.second < xRange.first) {
newxCoord.add(xRange)
return@forEach // doesn't intersect this x coord range
}
// we know it intersects
if (removeRange.first <= xRange.first && xRange.second <= removeRange.second) {
return@forEach // completely intersects, don't add
} else if (xRange.first < removeRange.first && removeRange.second < xRange.second) {
// split
newxCoord.add(xRange.first to removeRange.first - 1)
newxCoord.add(removeRange.second + 1 to xRange.second)
} else {
val truncatedRange =
if (removeRange.second < xRange.second ) {
removeRange.second + 1 to xRange.second
} else {
xRange.first to removeRange.first - 1
}
check(truncatedRange.first <= truncatedRange.second)
newxCoord.add(truncatedRange)
}
}
xCoord = newxCoord
if (xCoord.isEmpty()) return@forEachIndexed
}
if (xCoord.isNotEmpty()) return@pointCheck
}
if (xCoord.isNotEmpty()) {
return xCoord.first().first * 4000000L + inputRow
}
}
return 0
}
val testInput = readInputAsOneLine("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
val input = readInputAsOneLine("Day15")
println(part1(input, 2_000_000))
println(part2(input, 4_000_000))
} | 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 4,863 | AdventOfCode2022 | Apache License 2.0 |
src/Day04.kt | gillyobeast | 574,413,213 | false | {"Kotlin": 27372} | import utils.appliedTo
import utils.readInput
fun main() {
fun toPair(it: String, delimiter: String): Pair<String, String> {
val halves = it.split(delimiter)
return halves[0] to halves[1]
}
fun Pair<String, String>.toRange(): IntRange = first.toInt()..second.toInt()
fun String.toRange(): IntRange = toPair(this, "-").toRange()
fun parsePairs(input: List<String>) = input
.map { toPair(it, ",") }
.map { it.first.toRange() to it.second.toRange() }
.toList()
infix fun IntRange.fullyContains(other: IntRange) =
this.all { it in other }
fun Pair<IntRange, IntRange>.overlapsFully(): Boolean {
val firstInSecond = second fullyContains first
val secondInFirst = first fullyContains second
return (firstInSecond or secondInFirst)
}
fun Pair<IntRange, IntRange>.overlaps(): Boolean =
first.any { it in second }
fun part1(input: List<String>): Int {
return parsePairs(input)
.count { it.overlapsFully() }
}
fun part2(input: List<String>): Int {
return parsePairs(input)
.count { it.overlaps() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("input_test")
val input = readInput("input")
// part 1
::part1.appliedTo(testInput, returns = 2)
println("Part 1: ${part1(input)}")
// part 2
::part2.appliedTo(testInput, returns = 4)
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 8cdbb20c1a544039b0e91101ec3ebd529c2b9062 | 1,534 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/hopkins/aoc/day13/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day13
import java.io.File
const val debug = false
const val part = 2
/** Advent of Code 2023: Day 13 */
fun main() {
// Read the file input
val lines: List<String> = File("input/input13.txt").readLines()
if (debug) {
println("Num lines: ${lines.size}")
}
// Parse lines into puzzles
val puzzles: List<Puzzle> =
lines.fold (mutableListOf(mutableListOf<String>())) { acc, line ->
if (line.isEmpty()) {
acc.add(mutableListOf())
} else {
acc.last().add(line)
}
acc
}.map { lines -> Puzzle(lines) }
if (debug) {
println("Num puzzles: ${puzzles.size}")
}
val puzzleSum = puzzles.sumOf { puzzle ->
if (debug) {
println("Puzzle width=${puzzle.width} height=${puzzle.height}")
println(" firstRow=${puzzle.rows[0]} firstColumn=${puzzle.columns[0]}")
}
val reflectionValue = puzzle.findReflectionValue()
println("Value: $reflectionValue")
reflectionValue
}
println("Sum: $puzzleSum")
}
class Puzzle(val rows: List<String>) {
val columns = rows[0].indices.map { index ->
rows.map { row -> row[index] }.joinToString(separator = "")
}
val width = rows[0].length
val height = rows.size
fun findReflectionValue(): Int {
if (debug) {
println("Vertical:")
}
val verticalReflection = findReflection(height, rows)
if (debug) {
println("Horizontal:")
}
val horizontalReflection = findReflection(width, columns)
println("VR: $verticalReflection HR: $horizontalReflection")
return verticalReflection * 100 + horizontalReflection
}
private fun findReflection(max: Int, lines: List<String>): Int {
val desiredDiff = if (part == 1) { 0 } else { 1 }
for (index in 1 until max) {
val num = index.coerceAtMost(max - index)
val left = lines.subList(index - num, index)
val right = lines.subList(index, index + num).reversed()
if (debug) {
println("left: $left, right: $right")
}
require(left.size == right.size)
if (calcDifference(left, right) == desiredDiff) {
return index
}
}
return 0
}
}
fun calcDifference(left: List<String>, right: List<String>): Int {
val leftChars = left.flatMap { line -> line.toList() }
val rightChars = right.flatMap { line -> line.toList() }
return leftChars.zip(rightChars).sumOf { (a, b) -> if (a == b) { 0.toInt() } else { 1 } }
} | 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 2,688 | aoc2023 | MIT License |
src/main/kotlin/com/colinodell/advent2021/Day04.kt | colinodell | 433,864,377 | true | {"Kotlin": 111114} | package com.colinodell.advent2021
class Day04 (val input: String) {
fun solvePart1(): Int {
val result = BingoGame(input).findWinner().first()
return result.number * result.board.sumOfUnusedSquares()
}
fun solvePart2(): Int {
val result = BingoGame(input).findWinner().last()
return result.number * result.board.sumOfUnusedSquares()
}
private inner class BingoGame(input: String) {
val numbersDrawn: List<Int>
var boards = emptySet<Board>()
init {
val sections = input.split("\n\n")
numbersDrawn = sections[0].split(",").map { it.toInt() }
for (i in 1 until sections.size) {
boards += Board(sections[i])
}
}
fun findWinner() = sequence {
// Start calling numbers
for (number in numbersDrawn) {
// Mark them on each board
for (board in boards) {
board.markIfExists(number)
if (board.isWinner()) {
yield(GameResult(board, number))
// Remove the board from future rounds
boards -= board
}
}
}
}
}
private inner class Board(input: String) {
val squares = mutableMapOf<Vector2, Square>()
init {
for (row in 0..4) {
// Split the row into individual numbers
val numbers = input.split("\n")[row].split(" ").filter { it !== "" }.map { it.toInt() }
for (col in 0..4) {
squares[Vector2(row, col)] = Square(numbers[col])
}
}
}
fun markIfExists(number: Int) = squares.values.filter { it.number == number }.forEach { it.used = true }
fun sumOfUnusedSquares(): Int = squares.values.filter { !it.used }.sumOf { it.number }
fun isWinner(): Boolean {
// Check rows and columns at the same time
for (i in 0..4) {
val foundInRow = (0..4).count { j -> squares[Vector2(i, j)]!!.used }
val foundInCol = (0..4).count { j -> squares[Vector2(j, i)]!!.used }
if (foundInRow == 5 || foundInCol == 5) {
return true
}
}
return false
}
}
private data class Square (val number: Int, var used: Boolean = false)
private data class GameResult(val board: Board, val number: Int)
} | 0 | Kotlin | 0 | 1 | a1e04207c53adfcc194c85894765195bf147be7a | 2,555 | advent-2021 | Apache License 2.0 |
src/Day15.kt | acrab | 573,191,416 | false | {"Kotlin": 52968} | import com.google.common.truth.Truth.assertThat
import java.lang.Integer.max
import java.lang.Integer.min
import kotlin.math.abs
data class Sensor(val sensorX: Int, val sensorY: Int, val beaconX: Int, val beaconY: Int)
fun String.toSensor(): Sensor {
val parts = split(" ")
return Sensor(
sensorX = parts[2].removePrefix("x=").removeSuffix(",").toInt(),
sensorY = parts[3].removePrefix("y=").removeSuffix(":").toInt(),
beaconX = parts[8].removePrefix("x=").removeSuffix(",").toInt(),
beaconY = parts[9].removePrefix("y=").toInt(),
)
}
fun main() {
fun calculateRangeOnRow(sensorX: Int, sensorY: Int, beaconX: Int, beaconY: Int, targetRow: Int): Pair<Int, Int>? {
//Calculate manhattan distance to beacon
val beaconDistance = abs(sensorX - beaconX) + abs(sensorY - beaconY)
//calculate distance to target row
val rowDistance = abs(sensorY - targetRow)
//calculate range on that row
return if (rowDistance > beaconDistance) {
//There's no overlap between this sensor's swept area and our target row
null
} else {
val d = beaconDistance - rowDistance
sensorX - d to sensorX + d
}
}
fun List<Pair<Int, Int>?>.consolidateRanges() = filterNotNull()
.fold(emptyList<Pair<Int, Int>>()) { acc, pair ->
if (acc.isEmpty()) {
listOf(pair)
} else {
var (start, end) = pair
acc.forEach { (s, e) ->
if (start in s..e) {
start = e
}
if (end in s..e) {
end = s
}
}
//we're covered by existing ranges
if (end <= start) {
acc
} else if (acc.any { it.first < start && it.second > end }) {
//we're completely covered by a single existing range
acc
} else {
//remove any ranges we completely cover, and add this range
acc.filterNot { it.first > start && it.second < end } + (start to end)
}
}
}
fun List<Pair<Int, Int>?>.consolidateRangesBetween(minStart: Int, maxEnd: Int) = filterNotNull()
.fold(emptyList<Pair<Int, Int>>()) { acc, pair ->
if (acc.isEmpty()) {
listOf(pair)
} else {
var (start, end) = pair
start = max(start, minStart)
end = min(end, maxEnd)
acc.forEach { (s, e) ->
if (start in s..e) {
start = e
}
if (end in s..e) {
end = s
}
}
//we're covered by existing ranges
if (end <= start) {
acc
} else if (acc.any { it.first <= start && it.second >= end }) {
//we're completely covered by a single existing range
acc
} else {
//remove any ranges we completely cover, and add this range
acc.filterNot { it.first >= start && it.second <= end } + (start to end)
}
}
}
fun part1(input: List<String>, targetRow: Int): Int {
val ranges = input.map {
val parts = it.split(" ")
val sensorX = parts[2].removePrefix("x=").removeSuffix(",").toInt()
val sensorY = parts[3].removePrefix("y=").removeSuffix(":").toInt()
val beaconX = parts[8].removePrefix("x=").removeSuffix(",").toInt()
val beaconY = parts[9].removePrefix("y=").toInt()
calculateRangeOnRow(sensorX, sensorY, beaconX, beaconY, targetRow)
}
println("Ranges: $ranges")
//consolidate overlapping ranges
val consolidatedRanges = ranges.consolidateRanges()
println("Ranges: $consolidatedRanges")
//sum separate ranges
return consolidatedRanges
.sumOf { it.second - it.first }
}
fun frequency(x: Int, y: Int): Long = (x * 4_000_000L) + y
fun part2(input: List<String>, maxSize: Int): Long {
val sensors = input.map(String::toSensor)
repeat(maxSize) { row ->
val ranges = sensors.map { calculateRangeOnRow(it.sensorX, it.sensorY, it.beaconX, it.beaconY, row) }
.consolidateRangesBetween(0, maxSize)
ranges.forEach { range ->
if (range.second < maxSize && ranges.none { it.first == range.second }) {
println("Calculating frequency for ${range.second + 1}, $row")
return frequency(range.second + 1, row)
}
}
}
return 0
}
val testInput = readInput("Day15_test")
assertThat(part1(testInput, 10)).isEqualTo(26)
val input = readInput("Day15")
println(part1(input, 2_000_000))
assertThat(part2(testInput, 20)).isEqualTo(56000011L)
println(part2(input, 4_000_000))
} | 0 | Kotlin | 0 | 0 | 0be1409ceea72963f596e702327c5a875aca305c | 5,210 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | SimoneStefani | 572,915,832 | false | {"Kotlin": 33918} | fun main() {
fun computeScoreFromGame(game: String) = when (game) {
"A X" -> 1 + 3 // rock x rock
"A Y" -> 2 + 6 // rock x paper
"A Z" -> 3 + 0 // rock x scissors
"B X" -> 1 + 0 // paper x rock
"B Y" -> 2 + 3 // paper x paper
"B Z" -> 3 + 6 // paper x scissors
"C X" -> 1 + 6 // scissors x rock
"C Y" -> 2 + 0 // scissors x paper
"C Z" -> 3 + 3 // scissors x scissors
else -> throw IllegalArgumentException("Invalid game $game!")
}
fun computeScoreFromOutcome(game: String) = when (game) {
"A X" -> 0 + 3 // lose -> rock x scissors
"A Y" -> 3 + 1 // draw -> rock x rock
"A Z" -> 6 + 2 // win -> rock x paper
"B X" -> 0 + 1 // lose -> paper x rock
"B Y" -> 3 + 2 // draw ->paper x paper
"B Z" -> 6 + 3 // win -> paper x scissors
"C X" -> 0 + 2 // lose -> scissors x paper
"C Y" -> 3 + 3 // draw -> scissors x scissors
"C Z" -> 6 + 1 // win -> scissors x rock
else -> throw IllegalArgumentException("Invalid game $game!")
}
fun part1(input: List<String>): Int = input.sumOf { computeScoreFromGame(it) }
fun part2(input: List<String>): Int = input.sumOf { computeScoreFromOutcome(it) }
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b3244a6dfb8a1f0f4b47db2788cbb3d55426d018 | 1,473 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/g1501_1600/s1594_maximum_non_negative_product_in_a_matrix/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1501_1600.s1594_maximum_non_negative_product_in_a_matrix
// #Medium #Array #Dynamic_Programming #Matrix
// #2023_06_14_Time_224_ms_(100.00%)_Space_35_MB_(100.00%)
class Solution {
private class Tuple(var max: Long, var min: Long)
fun maxProductPath(grid: Array<IntArray?>?): Int {
// DP
if (grid == null || grid.size == 0 || grid[0] == null || grid[0]!!.size == 0) {
return 0
}
val rows = grid.size
val cols = grid[0]!!.size
val dp = Array(rows) { arrayOfNulls<Tuple>(cols) }
for (i in 0 until rows) {
for (j in 0 until cols) {
dp[i][j] = Tuple(1, 1)
}
}
// Init first row and column
dp[0][0]!!.max = grid[0]!![0].toLong()
dp[0][0]!!.min = grid[0]!![0].toLong()
for (i in 1 until rows) {
dp[i][0]!!.max = grid[i]!![0] * dp[i - 1][0]!!.max
dp[i][0]!!.min = grid[i]!![0] * dp[i - 1][0]!!.min
}
for (i in 1 until cols) {
dp[0][i]!!.max = grid[0]!![i] * dp[0][i - 1]!!.max
dp[0][i]!!.min = grid[0]!![i] * dp[0][i - 1]!!.min
}
// DP
for (i in 1 until rows) {
for (j in 1 until cols) {
val up1 = dp[i - 1][j]!!.max * grid[i]!![j]
val up2 = dp[i - 1][j]!!.min * grid[i]!![j]
val left1 = dp[i][j - 1]!!.max * grid[i]!![j]
val left2 = dp[i][j - 1]!!.min * grid[i]!![j]
dp[i][j]!!.max = Math.max(up1, Math.max(up2, Math.max(left1, left2)))
dp[i][j]!!.min = Math.min(up1, Math.min(up2, Math.min(left1, left2)))
}
}
return if (dp[rows - 1][cols - 1]!!.max < 0) {
-1
} else (dp[rows - 1][cols - 1]!!.max % (1e9 + 7)).toInt()
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,832 | LeetCode-in-Kotlin | MIT License |
src/2022/Day21.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | package `2022`
import readInput
fun main() {
fun calculate(phrase: MonkeyPhrase, nameToResult: MutableMap<String, Long>, nameToPhrase: Map<String, MonkeyPhrase>): Long {
if (nameToResult.contains(phrase.name)) {
return nameToResult[phrase.name]!!
}
when (phrase) {
is MonkeyPhrase.Operation -> {
val firstOperand = calculate(nameToPhrase[phrase.firstOperand]!!, nameToResult, nameToPhrase)
val secondOperand = calculate(nameToPhrase[phrase.secondOperand]!!, nameToResult, nameToPhrase)
return when (phrase.operation) {
"*" -> firstOperand * secondOperand
"/" -> firstOperand / secondOperand
"+" -> firstOperand + secondOperand
"-" -> firstOperand - secondOperand
else -> error("illegal operand")
}
}
is MonkeyPhrase.Num -> {
return phrase.value
}
}
}
fun reverseCalculate(phrase: MonkeyPhrase, nameToResult: MutableMap<String, MonkeyOperationResult>, nameToPhrase: Map<String, MonkeyPhrase>): MonkeyOperationResult {
if (nameToResult.contains(phrase.name)) {
return nameToResult[phrase.name]!!
}
when (phrase) {
is MonkeyPhrase.Operation -> {
val firstOperand = reverseCalculate(nameToPhrase[phrase.firstOperand]!!, nameToResult, nameToPhrase)
val secondOperand = reverseCalculate(nameToPhrase[phrase.secondOperand]!!, nameToResult, nameToPhrase)
val result = when (phrase.operation) {
"*" -> firstOperand * secondOperand
"/" -> firstOperand / secondOperand
"+" -> firstOperand + secondOperand
"-" -> firstOperand - secondOperand
else -> error("illegal operand")
}
nameToResult[phrase.name] = result
return result
}
is MonkeyPhrase.Num -> {
error("illegal state")
}
}
}
fun part1(input: List<String>): Long {
val phrases = input.map { MonkeyPhrase.parse(it) }
val nameToPhrase = phrases.associateBy { it.name }
val rootMonkey = nameToPhrase["root"]!!
val nameToResult = phrases.filterIsInstance<MonkeyPhrase.Num>().associateBy { it.name }.mapValues { it.value.value }.toMutableMap()
return calculate(rootMonkey, nameToResult, nameToPhrase)
}
fun part2(input: List<String>): Long {
val phrases = input.map { MonkeyPhrase.parse(it) }
val nameToPhrase = phrases.associateBy { it.name }
val rootMonkey = nameToPhrase["root"]!! as MonkeyPhrase.Operation
val firstOperand = nameToPhrase[rootMonkey.firstOperand]!!
val secondOperand = nameToPhrase[rootMonkey.secondOperand]!!
val nameToResult: MutableMap<String, MonkeyOperationResult> = phrases.filterIsInstance<MonkeyPhrase.Num>().associateBy { it.name }.mapValues {
MonkeyOperationResult.Num(Rational(it.value.value))
}.toMutableMap()
nameToResult["humn"] = MonkeyOperationResult.X(Rational(0L), Rational(1L))
val firstResult = reverseCalculate(firstOperand, nameToResult, nameToPhrase).toX()
val secondResult = reverseCalculate(secondOperand, nameToResult, nameToPhrase).toX()
return ((firstResult.value - secondResult.value) / (secondResult.multi - firstResult.multi)).toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day21_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 152L)
check(part2(testInput) == 301L)
val input = readInput("Day21")
println(part1(input))
println(part2(input))
}
sealed interface MonkeyPhrase {
val name: String
data class Operation(
override val name: String,
val firstOperand: String,
val operation: String,
val secondOperand: String
): MonkeyPhrase
data class Num(override val name: String, val value: Long): MonkeyPhrase
companion object {
fun parse(input: String): MonkeyPhrase {
val name = input.substringBefore(":")
val rest = input.substringAfter(":").trim()
if ("^-?\\d+$".toRegex().matches(rest)) {
return Num(name, rest.toLong())
}
val (_, firstMonkey, operation, secondMonkey) = "(\\w+) (.) (\\w+)".toRegex().find(rest)!!.groups.map { it!!.value }
return Operation(name, firstMonkey, operation, secondMonkey)
}
}
}
sealed interface MonkeyOperationResult {
data class Num(val value: Rational): MonkeyOperationResult
data class X(val value: Rational, val multi: Rational): MonkeyOperationResult
fun toX(): X {
return when(this) {
is X -> this
is Num -> X(this.value, Rational(0L))
}
}
operator fun times(other: MonkeyOperationResult): MonkeyOperationResult {
return when(this) {
is Num -> {
when(other) {
is Num -> Num(this.value * other.value)
is X -> X(this.value * other.value, this.value * other.multi)
}
}
is X -> {
when(other) {
is Num -> X(this.value * other.value, this.multi * other.value)
is X -> error("too complex")
}
}
}
}
operator fun div(other: MonkeyOperationResult): MonkeyOperationResult {
return when(this) {
is Num -> {
when(other) {
is Num -> Num(this.value / other.value)
is X -> error("too complex")
}
}
is X -> {
when(other) {
is Num -> X(this.value / other.value, this.multi / other.value)
is X -> error("too complex")
}
}
}
}
operator fun plus(other: MonkeyOperationResult): MonkeyOperationResult {
return when(this) {
is Num -> {
when(other) {
is Num -> Num(this.value + other.value)
is X -> X(this.value + other.value, other.multi)
}
}
is X -> {
when(other) {
is Num -> X(this.value + other.value, this.multi)
is X -> X(this.value + other.value, this.multi + other.multi)
}
}
}
}
operator fun minus(other: MonkeyOperationResult): MonkeyOperationResult {
return when(this) {
is Num -> {
when(other) {
is Num -> Num(this.value - other.value)
is X -> X(this.value - other.value, -other.multi)
}
}
is X -> {
when(other) {
is Num -> X(this.value - other.value, this.multi)
is X -> X(this.value - other.value, this.multi - other.multi)
}
}
}
}
}
data class Rational(val nominator: Long, val denominator: Long = 1) {
operator fun times(other: Rational): Rational {
return Rational(nominator * other.nominator, denominator * other.denominator).compact()
}
operator fun div(other: Rational): Rational {
return Rational(nominator * other.denominator, denominator * other.nominator).compact()
}
operator fun plus(other: Rational): Rational {
return Rational(nominator * other.denominator + other.nominator * denominator, denominator * other.denominator).compact()
}
operator fun minus(other: Rational): Rational {
return Rational(nominator * other.denominator - other.nominator * denominator, denominator * other.denominator).compact()
}
operator fun unaryMinus(): Rational {
return copy(nominator = -nominator)
}
fun toLong(): Long {
return nominator / denominator
}
private fun compact(): Rational {
val gcd = gcd(nominator, denominator)
return Rational(nominator / gcd, denominator / gcd)
}
}
fun gcd(first: Long, second: Long): Long = if (second == 0L) first else gcd(second, first % second)
| 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 8,497 | aoc-2022-in-kotlin | Apache License 2.0 |
kotlin/src/Day02.kt | ekureina | 433,709,362 | false | {"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386} | import java.lang.IllegalArgumentException
import java.lang.Long.parseLong
data class PositionWithAim(val position: Long, val depth: Long, val aim: Long)
data class Position(val position: Long, val depth: Long)
sealed class Command(protected val magnitude: Long) {
abstract fun move(position: Position): Position
abstract fun moveAimed(positionWithAim: PositionWithAim): PositionWithAim
}
class Forward(magnitude: Long): Command(magnitude) {
override fun move(position: Position): Position {
return Position(position.position + magnitude, position.depth)
}
override fun moveAimed(positionWithAim: PositionWithAim): PositionWithAim {
return PositionWithAim(
positionWithAim.position + magnitude,
positionWithAim.depth + (positionWithAim.aim * magnitude),
positionWithAim.aim
)
}
}
class Down(magnitude: Long): Command(magnitude) {
override fun move(position: Position): Position {
return Position(position.position, position.depth + magnitude)
}
override fun moveAimed(positionWithAim: PositionWithAim): PositionWithAim {
return PositionWithAim(positionWithAim.position, positionWithAim.depth, positionWithAim.aim + magnitude)
}
}
class Up(magnitude: Long): Command(magnitude) {
override fun move(position: Position): Position {
return Position(position.position, position.depth - magnitude)
}
override fun moveAimed(positionWithAim: PositionWithAim): PositionWithAim {
return PositionWithAim(positionWithAim.position, positionWithAim.depth, positionWithAim.aim - magnitude)
}
}
fun main() {
fun part1(input: List<String>): Long {
val finalPosition = input.map { line ->
val command = line.split(" ")
when (command.first()) {
"forward" -> Forward(parseLong(command[1]))
"down" -> Down(parseLong(command[1]))
"up" -> Up(parseLong(command[1]))
else -> throw IllegalArgumentException("$command")
}
}.fold(Position(0L, 0L)) { position, command ->
command.move(position)
}
return finalPosition.position * finalPosition.depth
}
fun part2(input: List<String>): Long {
val finalPosition = input.map { line ->
val command = line.split(" ")
when (command.first()) {
"forward" -> Forward(parseLong(command[1]))
"down" -> Down(parseLong(command[1]))
"up" -> Up(parseLong(command[1]))
else -> throw IllegalArgumentException("$command")
}
}.fold(PositionWithAim(0L, 0L, 0L)) { position, command ->
command.moveAimed(position)
}
return finalPosition.position * finalPosition.depth
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 150L)
check(part2(testInput) == 900L)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 391d0017ba9c2494092d27d22d5fd9f73d0c8ded | 3,107 | aoc-2021 | MIT License |
src/Day07.kt | arhor | 572,349,244 | false | {"Kotlin": 36845} | fun main() {
val root = readInput {}.let(::buildFilesystemTree)
val size = root.size
println("Part 1: " + root.allDirs.map { it.size }.filter { it <= 100_000 }.sum())
println("Part 2: " + root.allDirs.map { it.size }.sorted().first { TOTAL - (size - it) >= NEEDS })
}
private fun buildFilesystemTree(input: List<String>): Node.Dir {
val root = Node.Dir("/", null)
var curr = root
for (line in input) {
when {
line.startsWith(COMMAND_LS) -> {
continue
}
line.startsWith(COMMAND_CD) -> {
curr = when (val dirName = line.substringAfter(COMMAND_CD).trim()) {
"/" -> root
".." -> curr.prev ?: root
else -> Node.Dir(dirName, curr).also(curr.next::add)
}
}
else -> {
val (attr, name) = line.split(" ")
if (attr != "dir") {
curr.next.add(
Node.File(
name = name,
size = attr.toLong(),
prev = curr
)
)
}
}
}
}
return root
}
private const val COMMAND_LS = "$ ls"
private const val COMMAND_CD = "$ cd"
private const val TOTAL = 70_000_000L
private const val NEEDS = 30_000_000L
private sealed interface Node {
val name: String
val size: Long
val prev: Dir?
data class File(override val name: String, override val size: Long, override val prev: Dir) : Node
data class Dir(override val name: String, override val prev: Dir? = null) : Node {
val next = ArrayList<Node>()
val allDirs: Sequence<Dir> get() = flattenTree(this) { next.asSequence().filterIsInstance<Dir>() }
override val size: Long get() = next.sumOf { it.size }
}
}
| 0 | Kotlin | 0 | 0 | 047d4bdac687fd6719796eb69eab2dd8ebb5ba2f | 1,926 | aoc-2022-in-kotlin | Apache License 2.0 |
src/questions/LongestAbsoluteFilePath.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* Suppose we have a file system that stores both files and directories.
*
* <img src="https://assets.leetcode.com/uploads/2020/08/28/mdir.jpg" height="150" width="150"/>
* Every file and directory has a unique absolute path in the file system,
* which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s.
*
* Given a string input representing the file system in the explained format,
* return the length of the longest absolute path to a file in the abstracted file system.
* If there is no file in the system, return 0.
*
* [Source](https://leetcode.com/problems/longest-absolute-file-path/)
*/
@UseCommentAsDocumentation
private fun lengthLongestPath(input: String): Int {
val split = input.split("\n")
val lines = split.toList()
val depthToPathMap = mutableMapOf<Int, MutableList<String>>() // maintain a mapping of depth -> paths
for (i in 0..lines.lastIndex) {
val row = lines[i]
val depth = row.numberOfTabs()
if (row.startsWithTabs()) {
val parent = depthToPathMap[depth - 1]!!.last() // get its parent, it is always at last
val absPath = "$parent/${row.replace("\t", "")}"
// add its path to its corresponding depth at the last of list
depthToPathMap[depth] = depthToPathMap.getOrElse(depth) { mutableListOf() }.apply {
add(absPath)
}
} else {
depthToPathMap[depth] = depthToPathMap.getOrElse(depth) { mutableListOf() }.apply {
add(row)
}
}
}
// find the longest path
var best = 0
for (paths in depthToPathMap.values) {
for (path in paths) {
if (path.isFilePath()) { // only consider file path
best = maxOf(best, path.length)
}
}
}
return best
}
private fun String.isFilePath(): Boolean {
val split = split("/")
return (split.last().contains("."))
}
private fun String.startsWithTabs(index: Int = 0): Boolean {
return substring(index, index + 1) == "\t"
}
/**
* Counts the number of '\t' characters at the beginning
*/
private fun String.numberOfTabs(): Int {
var depth = 0
var index = 0
while (this.startsWithTabs(index)) {
depth++
index += 1
}
return depth
}
fun main() {
lengthLongestPath(input = "file1.txt\nfile2.txt\nlongfile.txt") shouldBe 12
lengthLongestPath("dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext") shouldBe 20
lengthLongestPath("dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext") shouldBe 32
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,731 | algorithms | MIT License |
src/day03/Day03.kt | jacobprudhomme | 573,057,457 | false | {"Kotlin": 29699} | import java.io.File
fun main() {
fun readInput(name: String) = File("src/day03", name)
.readLines()
fun getItemPriority(item: Char): Int =
if (item.isLowerCase()) {
item.code - 96
} else {
item.code - 38
}
fun part1(input: List<String>): Int {
var sumOfPriorities = 0
for (line in input) {
val numItemsInFirstRucksack = line.length / 2
val itemsInFirstRucksack = line.take(numItemsInFirstRucksack).toSet()
val seenInSecondRucksack = mutableSetOf<Char>()
for (item in line.takeLast(numItemsInFirstRucksack)) {
if (itemsInFirstRucksack.contains(item) and !seenInSecondRucksack.contains(item)) {
sumOfPriorities += getItemPriority(item)
seenInSecondRucksack.add(item)
}
}
}
return sumOfPriorities
}
fun part2(input: List<String>): Int {
var sumOfPriorities = 0
var group = arrayListOf<Set<Char>>()
for (line in input) {
group.add(line.toSet())
if (group.size == 3) {
val itemsCommonToAllRucksacks = group.reduce { acc, currRucksack -> acc.intersect(currRucksack) }
val item = itemsCommonToAllRucksacks.first()
sumOfPriorities += getItemPriority(item)
group = arrayListOf()
}
}
return sumOfPriorities
}
val input = readInput("input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 9c2b080aea8b069d2796d58bcfc90ce4651c215b | 1,583 | advent-of-code-2022 | Apache License 2.0 |
src/adventOfCode/day13Problem.kt | cunrein | 159,861,371 | false | null | package adventOfCode
import kotlin.system.measureTimeMillis
data class Cart(var x: Int, var y: Int, var dir: Char, var isDead: Boolean = false) {
var turnCount = 0
fun move(trackSection: Char) {
when (trackSection) {
'+' -> makeTurn()
'\\' -> if (dir == '<' || dir == '>') right() else left()
'/' -> if (dir == '<' || dir == '>') left() else right()
}
when (dir) {
'^' -> y--
'>' -> x++
'v' -> y++
'<' -> x--
}
}
fun right() {
dir = turnRight[dir]!!
}
fun left() {
dir = turnLeft[dir]!!
}
fun makeTurn() {
turnCount = (turnCount + 1) % turns.length
when (turns[turnCount]) {
'r' -> right()
'l' -> left()
}
}
fun collidedWith(other: Cart) = (x == other.x) && (y == other.y)
fun position() = x to y
companion object {
val turns = "rls"
val turnRight = mapOf<Char, Char>('>' to 'v', 'v' to '<', '<' to '^', '^' to '>')
val turnLeft = mapOf<Char, Char>('>' to '^', 'v' to '>', '<' to 'v', '^' to '<')
}
}
fun findCollisions(tracks: Array<Array<Char>>, carts: List<Cart>) = sequence {
val movingCarts = carts.map { it.copy() }.toMutableList()
while (movingCarts.size > 1) {
movingCarts.sortWith(compareBy({ it.y }, { it.x }))
movingCarts.forEach { cart ->
if (!cart.isDead) {
cart.move(tracks[cart.y][cart.x])
if (movingCarts.collisonOccurred(cart)) {
movingCarts.forEach { if (it.collidedWith(cart)) it.isDead = true }
yield(cart.position())
}
}
}
movingCarts.removeIf { it.isDead }
}
// Output Position of Final Cart as a Collision
yield(movingCarts[0].position())
}
fun List<Cart>.collisonOccurred(cart: Cart): Boolean = this.count { !it.isDead && it.collidedWith(cart) } > 1
fun solve(tracks: Array<Array<Char>>, carts: List<Cart>): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val collisions = findCollisions(tracks, carts)
val firstCollision = collisions.first()
val lastCollision = collisions.last()
return firstCollision to lastCollision
}
fun main(args: Array<String>) {
val time = measureTimeMillis {
val (carts, tracks: Array<Array<Char>>) = parseLines(input)
val (part1, part2) = solve(tracks, carts.toList())
println("Part I: $part1")
println("Part II: $part2")
}
println("Elapsed Time: ${time}ms")
}
private fun parseLines(lines: List<String>): Pair<MutableList<Cart>, Array<Array<Char>>> {
val carts = mutableListOf<Cart>()
val tracks: Array<Array<Char>> = lines.mapIndexed { y, line ->
line.mapIndexed { x, c ->
if (c in listOf('>', 'v', '<', '^')) {
carts.add(Cart(x, y, c))
}
when (c) {
'v' -> '|'
'^' -> '|'
'<' -> '-'
'>' -> '-'
else -> c
}
}.toTypedArray()
}.toTypedArray()
return Pair(carts, tracks)
}
val input = listOf(
" /-----------\\ /--------\\ ",
" /-------------+-----------+----------------------------------------------------------------------\\ | | ",
" | | /--------+------------------------------\\ | | | ",
" | /-+--+--------+------------------------------+---------------------------------------+---------\\ | /-----+---------------------\\ ",
" /-+-----------+-+--+--\\/----+-----------\\ | /-------------+-\\ | | | | | ",
" | | /----+-+--+--++----+-----------+------------------+---------------------\\ | | | | | | | | ",
" | | | | | | || | |/-------------\\ | /-----+---+-------------+-+-------+----+--+-----+--------------------\\| ",
" /-+-+------+----+-+\\ | || | || /------<-+---+---------------+-----+---+-------------+-+-------+----+--+-->--+--------------------++\\",
" | | | |/---+-++-+--++----+-----------++--\\ | | | | | | | | | | | | |||",
" | | | || | ||/+--++----+-----------++--+-+--------+--\\| | | | /----------+-+-------+\\ | | | |||",
" | | | || | |||| || | || /+-+--------+--++---------------+-----+---+--+----------+-+\\ || | | | |||",
" | | | || | |||| || | /-++-++-+--------+--++---------------+-----+---+--+----------+-++-----\\|| | | | |||",
" | | | || | |||| || | | || || | /--+--++---------------+-----+---+--+----------+-++-----+++---+--+-----+-----\\ |||",
" | | | || | |||| || | | || || | | | || | | | | | || ||| | | /-+-----+\\ |||",
" | | | || /-+-++++--++----+---------+-++-++-+-----+--+--++---------------+----\\| | | | || ||| | | | | || |||",
" | | | /----++-+-+-++++--++----+---------+-++-++-+-----+--+--++--------------\\| || /+--+----\\ | ||/----+++---+--+---+-+-----++\\ |||",
" | | | | /-++-+-+-++++--++----+---------+-++-++-+-----+--+--++--------------++----++--++--+----+-----+-+++\\ ||| | | | | ||| |||",
" | | | | | || | | |||| || | | || || | | | || /-++----++--++--+----+----\\| |||| ||| | | | | ||| |||",
" | | | | | || | | |||| || | | || || | | | || | || || || |/---+----++-++++---+++---+--+--\\| | ||| |||",
" | | | | | || | | |||| || | |/++-++-+-----+--+--++------\\ | || || || || | /--++<++++---+++---+--+--++-+-----+++------\\ |||",
" | | | |/-+-++-+-+-++++--++----+---------++++-++-+-----+--+--++----\\ | | || || || || | | || |||| ||| | | || | /---+++------+--\\ |||",
" | | | || |/++-+-+-++++--++----+---------++++-++-+-----+--+--++----+-+-----+-++----++--++--++---+-+--++-++++---+++---+-\\| || | | ||| | | |||",
" | | | || |||| | | |||| || | |||| || | | | || | | | || || || || | | || |||| ||| \\-++--++-/ | ||| | | |||",
" | | | || |||| | | |||| || | |||| || \\-----+--+--++----+-+-----+-++----++--++--++---+-+--++-++++---+++-----++--++---+---+++------+--+--++/",
" | | | || |||| |/+-++++--++----+\\ |||| || | /+--++----+-+-----+-++\\ || || || | | || |||| ||| || || | ||| | | || ",
" | | | || |||| ||| |||| || || |||| || | || || | | | ||| || || || | | || |||| ||| || || | ||| | | || ",
" | | | \\+-++++-+++-++++--++----++--------++++-++-------+-++--++----+-+-----+-/|| || || || /-+-+--++-++++---+++-----++--++---+\\ ||| | | || ",
" | | | | |||| ||| |||| || || /----++++-++-------+-++--++--\\ | | | || || || || | | | || |||| ||| || || || ||| | | || ",
" | | \\--+-++++-+++-++++--++----++---+----++++-++-------+-++--++--+-+-+-----+--++---++--++--++-+-+-+--+/ |||| ||| || || || ||| | | || ",
" | | |/++++-+++-++++--++----++\\ |/---++++-++-------+-++--++--+-+-+-----+--++\\ || |\\--++-+-+-+--+--/||| ||| || || \\+--+++------+--/ || ",
" | | |||||| ||| |||| || ||| || |||| || | || || | | | \\--+++--++--+---++-+-+-+--/ |\\+---+++-----++--++----+--++/ | || ",
" | | ||||\\+-+++-++++--++----+++--++---++++-++-------+-++--++--+-+-+--------+++--+/ |/--++-+-+-+------+-+---+++-----++--++\\ | || | || ",
" | | |||| | ||| |||| || ||| || |||| || | || || | | | ||| | || || | | \\------+-+---+++-----++--+++---+--++-------/ || ",
" | | |||| | ||| |||| || ||| || |||| || /---+-++--++--+-+-+---\\ ||| | || \\+-+-+--------+-+---++/ || ||| /+--++------------\\|| ",
" | | |||| | ||| ||||/-++----+++--++---++++-++---+---+-++--++--+-+-+---+----+++--+---++---+-+-+--------+-+---++---\\ || ||| || || ||| ",
" | | |||| | ||| ||||| || ||| || |||| || | | || || | | | | ||| | || | | | | | || | || ||| || || ||| ",
" | | |||| | ||| ||||| || ||| || |||| || | | || || | | | | ||| | || | | | | | || | || ||| || || ||| ",
" | | |||| | ||| ||||| ||/---+++--++---++++-++---+---+-++--++--+-+-+---+----+++--+---++---+-+-+--------+-+-\\ || | || ||| || || ||| ",
" | | |||| | ||\\-+++++-+++---+++--++---++++-++---+---+-++--++--+-+-+---+----+++--+---++---+-+-+--------+-+-+-+//--+--++--+++--++-\\|| ||| ",
" | | |||| | || \\++++-+++---/|| || |||| || /-+---+-++--++--+-+-+---+----+++--+---++---+-+-+--------+-+-+-+-+\\ | || ||| || ||| ||| ",
" | | |\\++-+-++---++++-+++----+/ || /++++-++-+-+---+-++--++--+-+-+---+----+++--+---++---+-+-+--------+-+-+\\| || | || ||| || ||| ||| ",
" | | | || | || |||| ||| | || ||||| || | | | || || | | | | ||| | || | | |/-------+-+-+++-++-+--++--+++--++-+++---\\ ||| ",
" | | \\-++-+-++---++++-+++----+---++--+++++-++-+-+---+-++--++--+-/ | | ||| /+---++---+-+-++-------+-+-+++-++-+\\ || ||| || ||| | ||| ",
" | | || | || |||| |\\+----+---++--+++/| || | | | \\+--++--+---+---+----+/| || || | | || | | ||| || || || ||| || ||| | ||| ",
" | | || | || /-++++-+-+----+---++--+++-+-++-+-+---+--+--++--+---+---+----+\\| || |\\---+-+-++-------+-+-+++-++-++-++--++/ || ||| | ||| ",
" | | || | ||/+-++++-+-+----+---++--+++-+-++-+-+---+--+--++--+---+---+---\\||| || | | | || | | ||| || || || || || ||| | ||| ",
" | | || | |||| |\\++-+-+----+---++--+++-+-++-+-+---+--+--/| | | /-+---++++-++---+----+-+-++-------+-+-+++-++-++-++--++---++-+++---+--\\ ||| ",
" | |/-----++-+-++++-+-++-+-+----+---++--+++-+-++-+-+---+--+---+--+\\/-+-+-+---++++-++---+----+-+-++--\\ | | ||| || || || || || ||| | | ||| ",
" | || || | |||| | || | | | || ||| | || | | | | | ||| | | | |||| || | |/+-++--+----+-+-+++-++-++-++--++---++-+++---+--+-\\ ||| ",
" | || || v |||| | \\+-+-+----+---++--+++-+-++-+-+---+--+---/ ||| | | | |||| || | /--+++-++--+----+-+-+++-++-++-++--++---++-+++---+-\\| | ||| ",
" | || || | |||| | | | | | || ||| | || | | | | |||/+-+-+---++++-++---+-+--+++-++--+----+-+-+++-++-++-++-\\|| || ||| | || | ||| ",
" | || || | |||| | | | | | || ||| | || | | | /+------+++++-+-+---++++-++---+-+--+++-++--+-->-+-+-+++-++-++-++-+++---++-+++---+-++-+---+++\\",
" | || || | |||| | | | | | || ||| | || | | | || /+++++-+-+---++++-++---+-+--+++-++--+----+-+-+++-++-++-++-+++--\\|| ||| | || | ||||",
" | || || | |||| | | | | /--+---++--+++-+-++-+-+---+-++-----++++++-+\\| |||| || | | ||| || | | | ||| || || || ||| ||| ||| | || | ||||",
" | ||/----++-+-++++\\| |/+-+-+--+---++--+++-+-++-+-+---+-++-----++++++-+++---++++\\|| | | ||| || | | | ||| || || || ||| ||| ||| | || | ||||",
" | ||| ||/+-++++++--+++-+-+--+---++--+++-+-++-+-+---+-++-----++++++-+++---+++++++---+-+--+++-++--+-\\ | | ||| || || || ||| ||| ||| | || | ||||",
" | ||| /++++-++++++--+++-+-+--+---++--+++-+-++-+-+---+-++-----++++++-+++---+++++++---+-+--+++-++--+\\| | | ||| || || || ||| ||| ||| | || | ||||",
" | ||| ||||| |||||| ||| | | | || ||| \\-++-+-+---+-+/ |||||| ||| ||||||| \\-+--+++-/| ||| | | ||| || || || ||| ||| ||| | || | ||||",
" | ||| /+++++-++++++--+++-+\\| | || ||| || | | | | |||||| ||| ||||||| | ||| | ||| | | ||| || || || ||| ||| ||| | || | ||||",
" | ||| |||||| |||||| ||| ||| | || ||| || | | | | /---++++++-+++---+++++++-----+--+++--+--+++--+-+-+++-++-++-++-+++--+++-+++---+-++-+-\\ ||||",
" | ||| |||||| |||\\++--+++-+++--+---++--+++---++-+-+---+-+--+---++++++-+++---++/|||| | ||| | ||| | |/+++-++-++-++-+++--+++-+++---+-++-+\\| ||||",
" | \\++--++++++-+++-++--++/ ||| | || |||/--++-+-+---+-+-\\| |||\\++-+++---++-++++-----+--+++--+--/|| | ||||| || || || ||| ||| ||| | || ||| ||||",
" | || |||||| ||| || || |||/-+---++--++++--++-+-+---+-+-++---+++-++-+++---++-++++-----+--+++--+---++\\ | ||||| || || || |^| ||| ||| | || ||| ||||",
" | || |||||| ||| || || |||| | || |||| || | | | | || ||| || ||| || ||||/----+--+++--+---+++-+-+++++-++-++-++-+++--+++-+++--\\| || ||| ||||",
" | || |||||| ||| || || |||| | || |||| || | | |/+-++---+++-++-+++---++-+++++----+-\\||| | ||| | ||||| || || || ||| ||| ||| || || ||| ||||",
" | || |||||| ||| || || |||| | \\+--++++--++-+-+---+++-++---+/| || ||| /++-+++++----+-++++-\\| ||| | ||||| || || || ||| ||| ||| || || ||| ||||",
" | || |||||| ||| || || |||| | | |||| || | | ||| || | | || ||| ||| ||||| | |||| || ||| | ||||| \\+-++-++-+++--+++-/|| || || ||| ||||",
" | || |||||| ||| || || |||| | | |||| || | | ||| || | | || ||| ||| ||||| | |||| || ||| | ||||| | || || ||| ||| || || || ||| ||||",
" | || |||||| ||| || || |||| | /-+--++++--++-+-+---+++-++---+-+-++-+++--+++-+++++----+-++++-++---+++-+-+++++--+-++-++-+++--+++--++\\ || || ||| ||||",
" | || |||||| ||| || |\\--++++-+--+-+--++++--++-+-+---+++-++---+-+-++-+++--+++-+/||| | |||| || ||| | ||||| | || || ||| ||| ||| || || ||| ||||",
" | || |||||| ||| || | |||| | | | |||| || | | |||/++---+-+\\|| ||| ||| | ||| | |||| || ||| | ||||| | || || ||| ||| ||| || || ||| ||||",
" | || |||||| ||| || | |||| | | | |||| || | | ||\\+++---+-++++-+++--+++-+-+++----+-++++-++---+++-+-+++++--+-++-++-+++--+++--+++-++-++-+++-+++/",
" | || |||||| ||| || | |||| | | | |||| || | | || ||| | |||| ||| ||| | ||| | |||| || ||| | ||||| | || || ||| ||| ||| || || ||| ||| ",
" | || |||||| ||| || | |||| | | | |||| || | | || ||| | ||\\+-+++--+++-+-+++----+-++++-++---+++-+-+++++>-+-++-++-/|| ||| |^| || || ||| ||| ",
"/+--++--++++++-+++-++--+---++++-+--+-+--++++--++\\| | || ||| | || | ||| ||| | ||| | |||| || ||| | ||||| | || || || ||| ||| || || ||| ||| ",
"|| || ||||||/+++-++--+---++++-+--+-+--++++--++++-+-\\ || ||| | || | ||| ||| | ||| | |||| || ||| | ||||| | || || || ||| ||| || || ||| ||| ",
"|| || |||||||||| || | |||| | | | |||| |||| | | || ||| | || | ||| ||| | ||| | |||| |\\---+++-+-+++++--+-++-++--++--+++--+++-+/ || ||| ||| ",
"|| || /++++++++++-++--+---++++-+--+-+--++++\\ |||| | | || ||| | || | ||| ||| | ||| | |||| | ||| | ||||| | || || || ||| |||/+--++-+++\\||| ",
"|| || ||||||||||| || | |||| | | | ||||| |||| | | || ||| | ||/+-+++--+++-+-+++----+-++++-+----+++-+-+++++--+\\|| || || ||| ||||| || ||||||| ",
"|| /++-+++++++++++-++--+---++++-+--+\\| ||||| |||| | | || ||| | |||| ||| ||| | ||| | |||| | ||| | ||||| |||| || || /+++--+++++\\ || ||||||| ",
"|| ||| ||||||||||| || | |||| | ||| ||||| |||| | | || ||| | |||| \\++--+++-+-+++----+-++++-+----+++-+-+++++--++++-++--++-++++--++++++-+/ ||||||| ",
"|| ||| ||||||||||| || | |||| | ||| ||||| |||| | | || ||| | |||| ||/-+++-+-+++----+-++++-+----+++-+-+++++--++++-++--++-++++-\\|||||| | ||||||| ",
"|| ||| ||||||||||| || | ||\\+-+--+++--+++++-++++-+-+-++-+++---+-++++--/|| ||| | ||| | |||| | ||| | ||||| |||| || || |||| ||||||| | ||||||| ",
"|| ||| ||||||||\\++-++--+---++-+-+--+++--+++++-++++-+-+-++-+++---+-++++---++-+++-+-+/| | |||| | ||| | ||||| |||| || || |||| ||||||| | ||||||| ",
"|| ||| |||||||| || || | || | | ||| ||||| |||| | | || ||| | |||| || ||| | | | | |||| | ||| | ||||| |||| || || |||| ||||||| | ||||||| ",
"|| ||| |||||||| || || | || | | ||| ||||| |||| | | || |||/--+-++++---++-+++-+-+-+----+-++++-+----+++-+-+++++-\\|||| || || |||| ||||||| | ||||||| ",
"|| ||| |||||||| || || | /++-+-+--+++--+++++-++++-+-+-++-++++--+-++++---++-+++-+-+-+----+-++++-+----+++-+-+++++-+++++-++\\ || |||| ||||||| | ||||||| ",
"|| ||| |||||||\\-++-++--+--+++-+-+--+++--+++++-++++-+-/ || |||| | |||| || ||| | | | | |||| | ||| | ||||| ||||| ||| || |||| ||||||| | ||||||| ",
"|| \\++-+++++++--++-++--+--+++-+-+--+/| ||||| \\+++-+---++-++++--+-++++---++-+++-+-+-+----+-++++-+----+++-/ ||||| ||||| ||| || |||| ||||||| | ||||||| ",
"|| || |||\\+++--++-++--+--+++-+-+--+-+--+++++--+++-+---++-++++--+-++++---++-+++-+-+-+----+-++++-+----+++---/|||| ||||| ||| || ||\\+-+++++++-+--++++/|| ",
"|| || ||| \\++--++-++--+--+++-+-+--+-+--+++++--+++-+---++-++++--+-++++---++-+++-+-+-+----+-++++-+----+++----++++-+++++-/|| || || | ||||||| | |||| || ",
"|| || ||| || || ||/-+--+++-+-+--+-+--+++++--+++-+---++-++++--+-++++---++-+++-+-+-+----+-++++-+----+++----++++\\||||| || || || | ||||||| | |||| || ",
"\\+--++-+++--++--++-+++-+--+++-+-+--+-+--+++++--+/| | || |||| | |||| || ||| | | | | |||| | ||| |||||||||| || || || | ||||||| | |||| || ",
" | || ||| || || ||| | ||| | | | | ||||| | | | /++-++++--+-++++---++-+++-+-+-+----+-++++-+--\\ ||| |||||||||| || || || | ||||||| | |||| || ",
" | || ||| || || ||| | ||| | | | | ||||| | | | ||| ||\\+--+-++++---++-+++-+-+-+----+-++++-+--+-+++----++++++++++--++-++-++-+-+++++++-+--++/| || ",
" | || ||| || || ||| | |||/+-+--+-+--+++++--+-+-+--+++-++-+--+-++++---++-+++-+-+-+----+-++++-+--+-+++----++++++++++-\\|| || || | ||||||| | || | || ",
" | || ||| |\\--++-+++-+--+++++-+--+-+--+++++--/ | | ||| || | | |||| |\\-+++-+-+-+----+-++++-+--+-+++----++++++++++-+++-++-++-+-/|||||| | || | || ",
" | || ||| | || ||| | \\++++-+--+-+--+++++----+-+--+++-++-+--+-++++---+--+++-+-+-+----+-++++-+--+-+++----++++++++++-++/ || || | |||||| | || | || ",
" | || ||| | || ||| | |||| | | | ||||| | | ||| || | | |||| | ||\\-+-+-+----+-++++-+--+-+++----++++++++++-++--++-++-+--++++++-+--++-+-/| ",
" | || ||| | || ||| | |||\\-+--+-+--+++++----+-+--+++-++-+--+-++++---+--++--+-+-+----+-++++-+--+-++/ |||||||||| || || || | |||||| | || | | ",
" | || ||| | || ||| | ||| | | | ||||| | | ||| || | | |||| | || | | | | |||| | | || |||||||||| || || || | |||||| | || | | ",
" | || ||| | || ||| | ||| | |/+--+++++----+-+--+++-++-+--+-++++\\ | || | | | | |||| | | || |||||||||| || || || | |||||| | || | | ",
" | || ||| | || ||| | ||| | ||| |\\+++----+-+--+++-++-+--+-+++++--+--++--+-+-+----+-++++-+--+-++-----+++/|||||| || || || | |||||| | || | | ",
" | || ||| | || ||| | ||| | ||\\--+-+++----+-+--+++-++-+--+-+++++--+--++--/ | | | |||| | | || \\++-++++++-++--++-++-+--++++++-+--+/ | | ",
" | || ||| | || ||| | ||| | || | ||| | | ||| || | | ||||| | || | | | |||| | | || || |||||| || || || | |||\\++-+--+--/ | ",
" | || ||| | || ||| | ||\\--+--++---+-+++----+-+--+++-++-+--+-+++++--+--++----+-+----+-++++-+--+-++------++-++++++-/| || || | ||| || | | | ",
" | || ||| | || ||| | || | || | ||| /--+-+--+++-++-+--+-+++++--+--++----+-+----+-++++-+--+-++------++-++++++--+--++-++\\| ||| || | | | ",
" | || ||| | || ||| | || | || v ||| | | | |||/++-+--+-+++++--+--++---\\| | | |||| | | || || |||||| \\--++-++++--+++-++-+--+-----/ ",
" | || ||\\--+---++-+++-+---++---+--++---+-+++-+--+-+--++++++-+--+-+++++--+--++>--++-+----+-++++-+--+-/| || |||||| || \\+++--+++-+/ | | ",
" | || || | || ||| | \\+---+--++---+-+++-+--+-+--++++++-+--+-+++++--+--++---++-+----+-++++-+--+--+-->---/| |||||| || ||| ||| | | | ",
" | /++-++---+---++-+++-+----+---+--++-\\ \\-+++-+--+-+--++++++-+--+-+++++--+--++---++-+----+-++++-+--+--+-------/ |||||| || ||| ||| | | | ",
" \\-+++-++---+---++-+/| | | | || | \\++-+--+-+--++++++-+--+-+++/| | || || \\----+-++++-+--+--+---------++++++-----++--+++--+++-/ | | ",
" ||| || | || | | | | | || | || | | | |||||| | | ||| | | || || /--+-++++-+--+--+-------\\ |||||| || ||| ||| | | ",
" ||| || | || | | | | | || | || | \\-+--++++++-+--+-+++-+--+--++---++---+--+-++++-+--+--+-------+-++/||| || ||| ||| | | ",
" ||| || | || | | | | | || | /--++-+----+--++++++-+--+-+++-+--+--++--\\|| | | |||\\-+--+--+-------+-++-+++-----++--++/ ||| | | ",
" ||| || | || | | | | | || | | || | \\--++++++-+--+-+++-+--/ || ||| | | ||| | | | | || ||| |\\--++---+/| | | ",
" /-+++-++-\\ | || | | | | | || | | || | |\\++++-+--+-+++-+-----++--+++---+--+-+++--+--+--+-------+-++-+++-----+---++---/ | | | ",
" | ||| || | | || | | | | | || | | \\+-+-------+-+++/ | | ||| | || ||| | | ||| | | | | || ||| | || | | | ",
" | ||| || | | || | | | /--+---+--++-+-+--\\| | |/+++--+--+-+++-+-----++--+++---+--+-+++--+--+--+-------+-++-+++-----+---++-----+---\\| | ",
" | ||| || | | ^| | | | | | | || | | || | ||||| | | ||| | || ||| | | |\\+--+--+--+-------+-++-+++-----/ || | || | ",
" | ||| || | | || | \\-+-+--+---+--++-+-+--++-+-------+++++--+--+-+++-+-----++--+++---+--+-+-+--+--+--+-------+-/| ||| || | || | ",
" | ||^ || | | || | | | | | || | | || | ||||| | | ||| | || ||| | \\-+-+--+--+--+-------+--+-+++---------++-----+---+/ | ",
" | ||| || | | \\+-+---+-+--+---/ || | | || | ||||\\--+--+-+/| | \\+--+++---+----+-+--/ | | | | ||| || |/--+---+-----\\ ",
" | ||| || | | | | | | | || | | || | |||| | | | | | | ||| | | | | | | | ||| || || | | | ",
" | ||| \\+-+-+----+-+---+-+--+------++-+-+--+/ | |||| \\--+-+-+-+------+--+++---+----+-+-----+--+-------+--/ ||| || || | | | ",
" | ||| | | | | | | | | || | | | | /-++++------+-+-+-+------+--+++---+----+-+-----+--+-------+----+++------\\ || || | | | ",
" | ||| | | | | | | | | || | |/-+--+-----+-++++------+-+-+-+-\\ | ||| | | | | | | ||| | || || | | | ",
" | ||| | | | \\-+---+-+--+------++-+-++-+--+-----+-++++------+-+-+-+-+----/ ||| | | | | | | ||| | || || | | | ",
" | \\++--+-+-+------+---+-+--+------++-/ || | | | |||| | | \\-+-+-------+++---+----+-+-----+--+-------+----/|| | || || | | | ",
" | || | | | | | | | || || | | | |||| | | | | ||| | | | | | | || | || || | | | ",
" | || | | \\------+---+-+--+------++---++-+--+-----+-++++------+-+---+-+-------+++---+----+-+-----+--/ | || | || || | | | ",
" | || | | | | | | || || | | | ||\\+------+-+---+-+-------+++---+----/ \\-----+----------+-----++------+--++-----++--+---/ | ",
" | || | | | \\-+--+------++---++-+--+-----+-++-+------+-+---+-+--->---+++---+------------+----------+-----/| | || || | | ",
" | || | | | | | || || | | | |\\-+------+-+---+-+-------+++---+------------+----------+------+------+--++-----++--/ | ",
" | || | | | | | || || | | | | \\------+-+---+-+-------+/|/--+------------+----------+------+----\\ | || || | ",
" | |\\--+-+--------/ | | || || | | | | | | | | | || | | | | | | || || | ",
" | | | | | | /----++---++-+--+-----+-+---------+-+---+-+->-----+-++--+------------+----------+------+----+-+--++--\\ || | ",
" | \\---+-+--------------+--+-+----++---++-+--+-----+-+---------+-/ | | | || | | | | | | || | || | ",
" | | | | | | || || | | | \\---------+-----+-+-------+-++--+------------/ | | | | || | || | ",
" | | | | | | || \\+-+--+-----+-----------+-----+-+-------/ \\+--+-------->--------------+------/ | | || | || | ",
" \\------+-/ | | | || | | | ^ \\-----+-+----------+--+-----------------------+-----------+-+--/| | || | ",
" | | | | || | | | | | | | \\-----------------------/ | | | | || | ",
" | | | | |\\----+-+--+-----+-----------------/ | | | | | | || | ",
" \\----------------+--/ | | | | | | | | | | | | || | ",
" \\----+----+-----+-/ | \\-------------------+----------+--------------------------------------+-/ | | |\\------------/ ",
" | | \\----+-------------------------/ \\--------------------------------------/ | | | ",
" | | \\---------------------------------------------------------------------------------/ | | ",
" \\----+-----------------------------------------------------------------------------------------------/ | ",
" \\--------------------------------------------------------------------------------------------------/ ",
" "
) | 0 | Kotlin | 0 | 0 | 3488ccb200f993a84f1e9302eca3fe3977dbfcd9 | 27,109 | ProblemOfTheDay | Apache License 2.0 |
src/main/kotlin/day17.kt | Gitvert | 725,292,325 | false | {"Kotlin": 97000} | fun day17 (lines: List<String>) {
val map = parseFactoryMap(lines)
val maxX = map[0].indices.last
val maxY = map.indices.last
val leastHeatPart1 = dijkstra(map, maxX, maxY, false)
println("Day 17 part 1: $leastHeatPart1")
val leastHeatPart2 = dijkstra(map, maxX, maxY, true)
println("Day 17 part 2: $leastHeatPart2")
println()
}
fun dijkstra(map: List<List<Int>>, maxX: Int, maxY: Int, part2: Boolean): Int {
val lowestCost = mutableMapOf<NodeKey, Int>()
val queue = mutableSetOf<Node>()
lowestCost[NodeKey(Pos(0, 0), Pos(0, 0))] = 0
queue.add(Node(NodeKey(Pos(0, 0), Pos(0, 0)), 0))
while(queue.isNotEmpty()) {
val currentNode = queue.minBy { lowestCost[it.key]!! }
queue.remove(currentNode)
val newNodes = mutableSetOf<Node>()
if (currentNode.key.direction.x == 0) {
evaluateNewNode(map, currentNode, Pos(1, 0), newNodes, maxX, maxY, part2)
evaluateNewNode(map, currentNode, Pos(-1, 0), newNodes, maxX, maxY, part2)
}
if (currentNode.key.direction.y == 0) {
evaluateNewNode(map, currentNode, Pos(0, 1), newNodes, maxX, maxY, part2)
evaluateNewNode(map, currentNode, Pos(0, -1), newNodes, maxX, maxY, part2)
}
newNodes.forEach { newNode ->
if (lowestCost[newNode.key] != null && lowestCost[newNode.key]!! > newNode.heatLoss) {
lowestCost[newNode.key] = newNode.heatLoss
queue.removeIf { it.key == newNode.key }
queue.add(newNode)
} else if (lowestCost[newNode.key] == null) {
lowestCost[newNode.key] = newNode.heatLoss
queue.add(newNode)
}
}
}
return lowestCost.entries.filter { it.key.pos == Pos(maxX, maxY) }.minOf { it.value }
}
fun evaluateNewNode(map: List<List<Int>>, start: Node, direction: Pos, newNodes: MutableSet<Node>, maxX: Int, maxY: Int, part2: Boolean) {
var addedHeatLoss = 0
val endStep = if (part2) { 10 } else { 3 }
for (i in 1..endStep) {
val newNode = Node(NodeKey(Pos(start.key.pos.x + direction.x * i, start.key.pos.y + direction.y * i), direction), start.heatLoss)
if (newNode.key.pos.x in 0..maxX && newNode.key.pos.y in 0..maxY) {
addedHeatLoss += map[newNode.key.pos.y][newNode.key.pos.x]
newNode.heatLoss += addedHeatLoss
if (!part2 || i > 3) {
newNodes.add(newNode)
}
}
}
}
fun parseFactoryMap(lines: List<String>): List<List<Int>> {
val map = mutableListOf<MutableList<Int>>()
for (y in lines.indices) {
val row = mutableListOf<Int>()
for (x in lines[0].indices) {
row.add(Integer.parseInt(lines[y][x].toString()))
}
map.add(row)
}
return map
}
data class NodeKey(val pos: Pos, val direction: Pos) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is NodeKey) return false
if (pos != other.pos) return false
if (direction != other.direction) return false
return true
}
override fun hashCode(): Int {
var result = pos.hashCode()
result = 31 * result + direction.hashCode()
return result
}
}
data class Node(val key: NodeKey, var heatLoss: Int) | 0 | Kotlin | 0 | 0 | f204f09c94528f5cd83ce0149a254c4b0ca3bc91 | 3,441 | advent_of_code_2023 | MIT License |
src/main/kotlin/com/anahoret/aoc2022/day22/BoardSolver.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day22
import com.anahoret.aoc2022.calculateEndIndex
import java.lang.RuntimeException
class BoardSolver(private val input: String) {
fun solve(): List<Int> {
val (board, path) = parseInputToBoard(input)
val startRow = 1
val startCol = board.rows.getValue(startRow).minIndex
val startDirection = Direction.RIGHT
val currentPos = Position(startRow, startCol, startDirection)
path.actions.forEach {
currentPos.move(board, it)
}
return listOf(currentPos.row, currentPos.col, currentPos.direction.facing)
}
private fun parseInputToBoard(str: String): Pair<Board, Path> {
val (boardStr, pathStr) = str.split("\n\n")
return Board.parse(boardStr) to parsePath(pathStr)
}
}
private data class Position(var row: Int, var col: Int, var direction: Direction)
private class TileList(val minIndex: Int, val maxIndex: Int, val rockPositions: List<Int>) {
fun stoneAfter(col: Int): Int? {
return rockPositions.firstOrNull { it > col } ?: rockPositions.firstOrNull()
}
fun stoneBefore(col: Int): Int? {
return rockPositions.lastOrNull { it < col } ?: rockPositions.lastOrNull()
}
}
private class Board(tiles: List<Tile>) {
companion object {
fun parse(str: String): Board {
val tiles = parseTiles(str).flatten()
return Board(tiles)
}
}
val rows = groupToList(tiles, Tile::row, Tile::col)
val cols = groupToList(tiles, Tile::col, Tile::row)
private fun groupToList(
tiles: List<Tile>,
listSelector: (Tile) -> Int,
elementSelector: (Tile) -> Int
): Map<Int, TileList> {
return tiles.groupBy(listSelector)
.mapValues { (_, tiles) ->
val minIndex = tiles.minOf(elementSelector)
val maxIndex = tiles.maxOf(elementSelector)
val rockPositions = tiles.filterIsInstance<SolidWall>().map(elementSelector)
TileList(minIndex, maxIndex, rockPositions)
}
}
override fun toString(): String {
val minRow = 1
val maxRow = cols.maxOf { it.value.maxIndex }
val minCol = 1
val maxCol = rows.maxOf { it.value.maxIndex }
return (minRow..maxRow).joinToString(separator = "\n") { row ->
(minCol..maxCol).joinToString(separator = "") { col ->
val r = rows.getValue(row)
if (col in r.minIndex..r.maxIndex && col !in r.rockPositions) "."
else if (col in r.minIndex..r.maxIndex && col in r.rockPositions) "#"
else if (col < r.minIndex) " "
else ""
}
}
}
}
private fun Position.move(board: Board, action: Action) {
fun loop(tileList: TileList, pos: Int, steps: Int): Int {
val endIndex = calculateEndIndex(pos - tileList.minIndex, steps, tileList.maxIndex - tileList.minIndex + 1)
return endIndex + tileList.minIndex
}
fun move(steps: Int, tileList: TileList, pos: Int): Int {
val last = tileList.maxIndex
val first = tileList.minIndex
fun movePositive(stone: Int): Int {
return when {
stone > pos && stone > pos + steps -> pos + steps
stone > pos && stone <= pos + steps -> stone - 1
stone < pos && pos + steps <= last -> pos + steps
stone < pos && pos + steps > last && first + steps - (last - pos) < stone -> loop(tileList, pos, steps)
stone < pos && pos + steps > last && first + steps - (last - pos) >= stone && stone == first -> last
stone < pos && pos + steps > last && first + steps - (last - pos) >= stone && stone > first -> stone - 1
else -> throw RuntimeException("Unhandled case.")
}
}
fun moveNegative(stone: Int): Int {
return when {
stone < pos && stone < pos + steps -> pos + steps
stone < pos && stone >= pos + steps -> stone + 1
stone > pos && pos + steps >= first -> pos + steps
stone > pos && pos + steps < first && last + steps + (pos - first) > stone -> loop(tileList, pos, steps)
stone > pos && pos + steps < first && last + steps + (pos - first) <= stone && stone == last -> first
stone > pos && pos + steps < first && last + steps + (pos - first) <= stone && stone < last -> stone + 1
else -> throw RuntimeException("Unhandled case.")
}
}
val stone = if (steps > 0) tileList.stoneAfter(pos) else tileList.stoneBefore(pos)
return when {
stone == null -> loop(tileList, pos, steps)
steps > 0 -> movePositive(stone)
else -> moveNegative(stone)
}
}
fun moveHorizontally(steps: Int) {
val currentRow = board.rows.getValue(row)
col = move(steps, currentRow, col)
}
fun moveVertically(steps: Int) {
val currentCol = board.cols.getValue(col)
row = move(steps, currentCol, row)
}
when (action) {
is Movement -> when (direction) {
Direction.LEFT -> moveHorizontally(-action.steps)
Direction.RIGHT -> moveHorizontally(action.steps)
Direction.UP -> moveVertically(-action.steps)
Direction.DOWN -> moveVertically(action.steps)
}
is Rotation -> direction = direction.rotate(action.direction)
}
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 5,550 | advent-of-code-2022 | Apache License 2.0 |
src/Day02/Day02.kt | NST-d | 573,224,214 | false | null | package Day02
import utils.*
enum class RPS(val score: Int){
ROCK(1),
PAPER(2),
SCISSOR (3),
}
fun winScore(opponent: RPS, player: RPS): Int {
if(opponent == player) return 3
if((opponent.ordinal+1)%3 == player.ordinal ) return 6
return 0
}
fun getRPS(input:Char, base:Char) =
when( input-base){
0 -> RPS.ROCK
1 -> RPS.PAPER
2 -> RPS.SCISSOR
else -> error("Unssuporter input $input for base $base")
}
fun main() {
fun part1(input : List<String>)=
input.sumOf {
val opponent = getRPS(it[0], 'A')
val recommended = getRPS(it[2], 'X')
val score =recommended.score + winScore(opponent, recommended)
//println("$opponent vs $recommended -> $score")
score
}
fun part2(input: List<String>) =
input.sumOf {
val opponent = getRPS(it[0], 'A')
val recommended = when(it[2]){
'X' -> RPS.values()[(opponent.ordinal +2) % 3]
'Y' -> opponent
'Z' -> RPS.values()[(opponent.ordinal+1) % 3]
else -> error("")
}
val score = recommended.score + winScore(opponent, recommended)
//println("$opponent vs $recommended -> $score")
score
}
val test = readTestLines("Day02")
val input = readInputLines("Day02")
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c4913b488b8a42c4d7dad94733d35711a9c98992 | 1,436 | aoc22 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day24.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.*
fun main() = Day24.run()
object Day24 : Day(2022, 24) {
val map = toMap(input).entries.associate { it.key to it.value.toString() }
private val yMax = map.entries.maxOf { it.key.y }
private val xMax = map.entries.maxOf { it.key.x }
private val startPos = map.entries.first { it.key.y == 0 && it.value == "." }.key
private val goal = map.entries.first { it.key.y == yMax && it.value == "." }.key
private var memo = mutableMapOf(0 to map)
override fun part1(): Any {
data class State(val pos: Point, val time: Int)
val next: (State) -> List<State> = { (pos, t) ->
val next = mutableListOf<State>()
val nextTime = t + 1
memo.computeIfAbsent(nextTime) { step(memo[t]!!) }
val newWorld = memo[nextTime]!!
val candidates = pos.neighborsSimple().filter { newWorld[it] != null && newWorld[it]!! == "." }
candidates.forEach { next.add(State(it, nextTime)) }
if (newWorld[pos]!! == ".") {
next.add(State(pos, nextTime))
}
next
}
return bfs(State(startPos, 0), { it.pos == goal }, next).second
}
private fun step(map: Map<Point, String>): Map<Point, String> {
val blizzards = map.filter { it.value != "." && it.value != "#" }
.flatMap { p -> p.value.e().map { p.key to it } }
.map { (p, v) ->
val nextP = when (v) {
'<' -> P(if (p.x == 1) xMax - 1 else p.x - 1, p.y)
'>' -> P(if (p.x == xMax - 1) 1 else p.x + 1, p.y)
'v' -> P(p.x, if (p.y == yMax - 1) 1 else p.y + 1)
'^' -> P(p.x, if (p.y == 1) yMax - 1 else p.y - 1)
else -> throw RuntimeException("Unsupported dir")
}
nextP to v.toString()
}.groupBy { it.first }
.entries.associate { it.key to it.value.joinToString("") { b -> b.second } }
return map.entries.associate {
var newVal = "."
if (it.value == "#")
newVal = "#"
else if (it.key in blizzards) {
newVal = blizzards[it.key]!!
}
it.key to newVal
}
}
override fun part2(): Any {
// State = 0 not found goal yet
// State = 1 has found goal
// State = 2 has gotten candy
data class State(val pos: Point, val time: Int, val state: Int)
// start: State, isEnd: (State) -> Boolean, next: (State) -> Iterable<State>
fun nextS(s: Int, p: Point): Int {
return if (s == 0 && p == goal) {
1
} else if (s == 1 && p == startPos) {
2
} else {
s
}
}
val next: (State) -> List<State> = { (pos, t, s) ->
val next = mutableListOf<State>()
val nextTime = t + 1
memo.computeIfAbsent(nextTime) { step(memo[t]!!) }
val newWorld = memo[nextTime]!!
val candidates = pos.neighborsSimple().filter { newWorld[it] != null && newWorld[it]!! == "." }
candidates.forEach { next.add(State(it, nextTime, nextS(s, it))) }
if (newWorld[pos]!! == ".") {
next.add(State(pos, nextTime, nextS(s, pos)))
}
next
}
return bfs(State(startPos, 0, 0), { it.pos == goal && it.state == 2 }, next).second
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 3,549 | adventofkotlin | MIT License |
app/src/y2021/day09/Day09SmokeBasin.kt | henningBunk | 432,858,990 | false | {"Kotlin": 124495} | package y2021.day09
import common.*
import common.annotations.AoCPuzzle
typealias CaveMap = List<MutableList<Int>>
typealias CaveQueue = MutableList<Pair<Int, Int>>
fun main(args: Array<String>) {
Day09SmokeBasin().solveThem()
}
@AoCPuzzle(2021, 9)
class Day09SmokeBasin : AocSolution {
override val answers = Answers(samplePart1 = 15, samplePart2 = 1134, part1 = 516, part2 = 1023660)
override fun solvePart1(input: List<String>): Any = input
.toCaveMap()
.let { caveMap ->
caveMap
.getLowPoints()
.sumOf { (x, y) -> caveMap[y][x] + 1 }
}
override fun solvePart2(input: List<String>): Any {
val caveMap = input.toCaveMap()
val lowPoints = caveMap.getLowPoints()
val basinSizes = mutableListOf<Int>()
for ((x, y) in lowPoints) {
val queue: CaveQueue = mutableListOf()
queue.add(x to y)
caveMap[y][x] = 9
var basinSize = 0
while (queue.isNotEmpty()) {
val (vX, vY) = queue.removeFirst()
basinSize++
queue.processNeighbour(x = vX - 1, y = vY, map = caveMap)
queue.processNeighbour(x = vX + 1, y = vY, map = caveMap)
queue.processNeighbour(x = vX, y = vY - 1, map = caveMap)
queue.processNeighbour(x = vX, y = vY + 1, map = caveMap)
}
basinSizes.add(basinSize)
}
return basinSizes.sorted().takeLast(3).fold(1) { acc, next -> acc * next }
}
private fun List<String>.toCaveMap(): CaveMap =
map { it.toList().map(Character::getNumericValue).toMutableList() }
private fun CaveMap.getLowPoints(): MutableList<Pair<Int, Int>> {
val lowPoints = mutableListOf<Pair<Int, Int>>()
for (y in (0..lastIndex)) {
for (x in (0..this[y].lastIndex)) {
if (
(x - 1 < 0 || this[y][x] < this[y][x - 1]) &&
(x + 1 > this[y].lastIndex || this[y][x] < this[y][x + 1]) &&
(y - 1 < 0 || this[y][x] < this[y - 1][x]) &&
(y + 1 > lastIndex || this[y][x] < this[y + 1][x])
) {
lowPoints.add(x to y)
}
}
}
return lowPoints
}
private fun CaveQueue.processNeighbour(x: Int, y: Int, map: CaveMap) {
if (!map.isOnMap(x, y)) return
if (map[y][x] == 9) return
add(x to y)
map[y][x] = 9
}
private fun CaveMap.isOnMap(x: Int, y: Int): Boolean =
x >= 0 &&
y >= 0 &&
y <= this.lastIndex &&
x <= this[y].lastIndex
} | 0 | Kotlin | 0 | 0 | 94235f97c436f434561a09272642911c5588560d | 2,712 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1498/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1498
/**
* LeetCode page: [1498. Number of Subsequences That Satisfy the Given Sum Condition](https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/);
*/
class Solution {
/* Complexity:
* Time O(NLogN) and Space O(N) where N is the size of nums;
*/
fun numSubseq(nums: IntArray, target: Int): Int {
/* Instead of finding the result of nums, we can find the result of the sorted nums
* since their subsequences are one to one mapping.
*/
val sortedNums = nums.sorted()
var result = 0
val mod = 1_000_000_007
/* For each suffix array of sorted nums, find the result of it with a constraint that
* its first element must be included, and add to the final result.
*
* Two pointers technique is used to determine the maximum index that the subsequence
* can extend to.
*/
var suffixStart = 0
var maxEndIndex = nums.lastIndex
while (suffixStart <= maxEndIndex) {
// Find the max index that the subsequence can extend to
while (
suffixStart <= maxEndIndex &&
sortedNums[suffixStart] + sortedNums[maxEndIndex] > target
) {
maxEndIndex--
}
// Compute the sub result and add it to the final result
val maxTailLength = maxEndIndex - suffixStart
val subResult = when {
maxTailLength < 0 -> 0
maxTailLength == 0 -> 1
else -> normalizedNumSubsequences(maxTailLength, mod)
}
result = (result + subResult) % mod
suffixStart++
}
// Return the final result.
return result
}
private fun normalizedNumSubsequences(length: Int, mod: Int): Int {
if (length <= 0) {
return 0
}
if (length == 1) {
return 2 % mod
}
val halfLength = length / 2
val halfLengthResult = normalizedNumSubsequences(halfLength, mod).toLong()
val oddFactor = if (length.isOdd()) 2 else 1
return halfLengthResult.let {
(((it * it) % mod) * oddFactor) % mod
}.toInt()
}
private fun Int.isOdd() = this and 1 == 1
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,357 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-13.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2021
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputText
fun main() {
val input = readInputText(2021, "13-input")
val test1 = readInputText(2021, "13-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: String): Int {
val (dots, folds) = parse(input)
val result = dots.fold(folds.first())
return result.size
}
private fun part2(input: String): String {
val (dots, folds) = parse(input)
val result = folds.fold(dots) { acc, f -> acc.fold(f) }
val maxX = result.maxOf { it.x }
val maxY = result.maxOf { it.y }
return buildString {
for (col in 0..maxY) {
for (row in 0..maxX) {
if (Coord2D(row, col) in result) append('#') else append('.')
}
append('\n')
}
}
}
private fun parse(input: String): Pair<Set<Coord2D>, List<Fold>> {
val (dotsString, foldsString) = input.split("\n\n")
val dots = dotsString.lines().map { it.split(',').let { (x, y) -> Coord2D(x.toInt(), y.toInt()) } }.toSet()
val folds = foldsString.lines().map {
val (axis, value) = regex.matchEntire(it)!!.destructured
Fold(axis.single(), value.toInt())
}
return Pair(dots, folds)
}
private fun Set<Coord2D>.fold(fold: Fold): Set<Coord2D> {
val result = mutableSetOf<Coord2D>()
if (fold.axis == 'x') {
forEach {
result += if (fold.value < it.x) {
it.copy(x = fold.value - (it.x - fold.value))
} else {
it
}
}
} else {
forEach {
result += if (fold.value < it.y) {
it.copy(y = fold.value - (it.y - fold.value))
} else {
it
}
}
}
return result
}
private val regex = """fold along ([xy])=(\d+)""".toRegex()
private data class Fold(val axis: Char, val value: Int)
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,161 | advent-of-code | MIT License |
src/main/kotlin/day23.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.Point
import shared.getText
fun main() {
val input = getText("day23.txt")
println(day23A(input))
println(day23B(input))
}
fun day23A(input: String): Int {
val elves = toElves(input)
val proposeOrder = mutableListOf('N', 'S', 'W', 'E')
repeat(10) {
moveElves(elves, proposeOrder)
proposeOrder.add(proposeOrder.removeAt(0))
}
val xWidth = elves.maxOf { it.point.x } - elves.minOf { it.point.x } + 1
val yWidth = elves.maxOf { it.point.y } - elves.minOf { it.point.y } + 1
return (xWidth * yWidth) - elves.size
}
fun day23B(input: String): Int {
val elves = toElves(input)
val proposeOrder = mutableListOf('N', 'S', 'W', 'E')
var round = 0
while (true) {
round++
val moved = moveElves(elves, proposeOrder)
if(!moved) return round
proposeOrder.add(proposeOrder.removeAt(0))
}
}
private fun toElves(input: String): List<Elf> {
return input.lines().flatMapIndexed { y, line ->
line.toCharArray().mapIndexed { x, c ->
if(c == '#') {
Elf(Point(x, y))
} else {
null
}
}
}.filterNotNull()
}
private fun moveElves(elves: List<Elf>, proposeOrder: List<Char>): Boolean {
for(elf in elves) {
val alone = elf.adjacent().none { p -> elves.any { it.point == p } }
if(!alone) {
for(propose in proposeOrder) {
elf.suggest = when {
propose == 'N' && elf.northAdjacent().none { elves.hasElfOn(it) } -> {
Point(elf.point.x, elf.point.y-1)
}
propose == 'S' && elf.southAdjacent().none { elves.hasElfOn(it) } -> {
Point(elf.point.x, elf.point.y+1)
}
propose == 'W' && elf.westAdjacent().none { elves.hasElfOn(it) } -> {
Point(elf.point.x-1, elf.point.y)
}
propose == 'E' && elf.eastAdjacent().none { elves.hasElfOn(it) } -> {
Point(elf.point.x+1, elf.point.y)
}
else -> null
}
if(elf.suggest != null) break
}
}
}
val suggestions = elves.mapNotNull { it.suggest }
if(suggestions.isEmpty()) return false
for(elf in elves) {
if(suggestions.count { it == elf.suggest } == 1) {
elf.point = elf.suggest!!
}
elf.suggest = null
}
return true
}
private fun List<Elf>.hasElfOn(point: Point) = any { it.point == point }
private class Elf(var point: Point, var suggest: Point? = null) {
fun adjacent() = (northAdjacent() + southAdjacent() + westAdjacent() + eastAdjacent()).toSet()
fun northAdjacent(): List<Point> {
return listOf(
Point(point.x-1, point.y-1),
Point(point.x, point.y-1),
Point(point.x+1, point.y-1),
)
}
fun southAdjacent(): List<Point> {
return listOf(
Point(point.x-1, point.y+1),
Point(point.x, point.y+1),
Point(point.x+1, point.y+1),
)
}
fun westAdjacent(): List<Point> {
return listOf(
Point(point.x-1, point.y-1),
Point(point.x-1, point.y),
Point(point.x-1, point.y+1),
)
}
fun eastAdjacent(): List<Point> {
return listOf(
Point(point.x+1, point.y-1),
Point(point.x+1, point.y),
Point(point.x+1, point.y+1),
)
}
} | 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 3,606 | AdventOfCode2022 | MIT License |
src/main/kotlin/pl/klemba/aoc/day5/Main.kt | aklemba | 726,935,468 | false | {"Kotlin": 16373} | package pl.klemba.aoc.day5
import java.io.File
fun main() {
// ----- PART 1 -----
val almanac = File(inputPath)
.readLines()
val seeds: List<Long> = getSeeds(almanac)
println("Seeds: $seeds")
val mappings = getMappings(almanac)
mappings
.forEach { println(it) }
seeds
.map { seed -> seed.mapToLocation(mappings) }
.let {
println("Resultlist: $it")
println(it.min())
}
// ----- PART 2 -----
val almanac2 = File(inputPath)
.readLines()
val seedRanges: List<LongRange> = getSeedRangesPart2(almanac2)
val mappings2 = getMappings(almanac2)
seedRanges
.fold(Long.MAX_VALUE) { acc, longRange -> findMinLocationOf(longRange, mappings2).let { location -> if (location < acc) location else acc } }
.let { println(it) }
}
fun getMappings(almanac: List<String>): ArrayList<ArrayList<MappingPattern>> {
val mappings = ArrayList<ArrayList<MappingPattern>>()
return almanac
.fold(mappings) { acc, line -> addToMappingsList(line, acc) }
}
private fun String.hasThreeNumbers() = getMappingLine() != null
private fun String.getMappingLine() = mappingLineRegex.matchEntire(this)
fun addToMappingsList(line: String, acc: ArrayList<ArrayList<MappingPattern>>): java.util.ArrayList<java.util.ArrayList<MappingPattern>> {
when {
line.endsWith("map:") -> {
acc.add(ArrayList())
}
line.hasThreeNumbers() -> {
acc.last().add(getMappingPattern(line))
}
}
return acc
}
fun getMappingPattern(line: String) =
line.getMappingLine()
?.destructured
?.let { (destinationValue, sourceValue, rangeValue ) -> mapToMappingPattern(destinationValue.toLong(), sourceValue.toLong(), rangeValue.toLong()) }
?: throw IllegalStateException("Mapping pattern not found! Wierd since it has been checked before!")
fun mapToMappingPattern(destinationValue: Long, sourceValue: Long, rangeValue: Long) =
MappingPattern(LongRange(sourceValue, sourceValue + rangeValue), destinationValue - sourceValue)
fun getSeeds(almanac: List<String>): List<Long> =
numberRegex.findAll(almanac[0])
.map { it.destructured.component1().toLong() }
.toList()
fun getSeedRangesPart2(almanac: List<String>): List<LongRange> =
getSeeds(almanac)
.chunked(2)
.map { LongRange(it[0], it[0] + it[1]) }
private fun Long.mapToLocation(mappings: java.util.ArrayList<java.util.ArrayList<MappingPattern>>) =
mappings
.fold(this) { acc, mappingPatterns ->
mappingPatterns.find { it.sourceRange.contains(acc) }
?.let { pattern -> pattern.valueShift + acc }
?: acc
}
fun findMinLocationOf(longRange: LongRange, almanac2: ArrayList<ArrayList<MappingPattern>>) =
longRange
.fold(Long.MAX_VALUE) { acc, seed -> seed.mapToLocation(almanac2).let { location -> if (location < acc) location else acc } }
/**
* @param sourceRange range of IDs which can be mapped by this pattern
* @param valueShift parameter indicating needed value shift (addition of the value to source ID) to achieve the mapping result
*/
data class MappingPattern(val sourceRange: LongRange, val valueShift: Long)
private val numberRegex = Regex(""" (\d+)""")
private val mappingLineRegex = Regex("""(\d+) (\d+) (\d+)""")
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day5/input.txt" | 0 | Kotlin | 0 | 1 | 2432d300d2203ff91c41ffffe266e19a50cca944 | 3,382 | adventOfCode2023 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/max_distance/MaxDistance.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.max_distance
import nonstdlib.tail
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/discuss/interview-question/350363/Google-or-OA-2018-or-Max-Distance
*/
class MaxDistanceTests {
@Test fun examples() {
maxDistance("1011000", "1011110") shouldEqual Pair("1011000", "1011110")
maxDistance("1011000", "1011110", "1011----") shouldEqual Pair("1011110", "1011----")
maxDistance("1011000--", "1011110", "1011----") shouldEqual Pair("1011----", "1011000--")
}
}
data class TrieNode(val value: Char, val children: HashMap<Char, TrieNode> = HashMap()) {
fun add(s: String) {
if (s.isEmpty()) return
val child = children.getOrPut(s.first()) { TrieNode(s.first()) }
child.add(s.tail())
}
fun maxDepthChildren(): Pair<String, String> {
val (child1, child2) = children.values.map { it.maxDepthChild() }.sortedBy { it.first }.takeLast(2)
return Pair(child1.second, child2.second)
}
private fun maxDepthChild(): Pair<Int, String> {
val max = children.values.map { it.maxDepthChild() }.maxByOrNull { it.first } ?: Pair(-1, "")
return Pair(max.first + 1, value.toString() + max.second)
}
}
private fun maxDistance(vararg strings: String): Pair<String, String> {
var trie = TrieNode(0.toChar())
strings.forEach { trie.add(it) }
var prefix = ""
while (trie.children.size == 1) {
trie = trie.children.values.first()
prefix += trie.value
}
val (child1, child2) = trie.maxDepthChildren()
return Pair(prefix + child1, prefix + child2)
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,637 | katas | The Unlicense |
src/exercises/Day09.kt | Njko | 572,917,534 | false | {"Kotlin": 53729} | // ktlint-disable filename
package exercises
import readInput
import kotlin.math.pow
import kotlin.math.sqrt
data class Vec2(val x: Int, val y: Int)
operator fun Vec2.plus(minusVec2: Vec2): Vec2 = Vec2(this.x + minusVec2.x, this.y + minusVec2.y)
operator fun Vec2.minus(minusVec2: Vec2): Vec2 = Vec2(this.x - minusVec2.x, this.y - minusVec2.y)
fun Vec2.isNotCloseTo(position: Vec2): Boolean {
return sqrt(
(position.x - this.x).toDouble().pow(2) + (position.y - this.y).toDouble().pow(2)
) > 1.5
}
fun main() {
fun moveTailToHead(tailPositon: Vec2, headPosition: Vec2): Vec2 {
val direction = headPosition - tailPositon
val normalizedDirection = Vec2(
direction.x.coerceIn(-1..1),
direction.y.coerceIn(-1..1)
)
return tailPositon + normalizedDirection
}
fun part1(input: List<String>): Int {
var headPosition = Vec2(0, 0)
var tailPositon = Vec2(0, 0)
val positionVisited = mutableSetOf(tailPositon)
input.forEach { instruction ->
val (direction, steps) = instruction.split(" ")
repeat(steps.toInt()) {
when (direction) {
"U" -> headPosition = headPosition.copy(y = headPosition.y + 1)
"D" -> headPosition = headPosition.copy(y = headPosition.y - 1)
"L" -> headPosition = headPosition.copy(x = headPosition.x - 1)
"R" -> headPosition = headPosition.copy(x = headPosition.x + 1)
}
if (tailPositon.isNotCloseTo(headPosition)) {
tailPositon = moveTailToHead(tailPositon, headPosition)
}
positionVisited.add(tailPositon)
}
}
return positionVisited.size
}
fun part2(input: List<String>): Int {
val positionVisited = mutableSetOf(Vec2(0, 0))
val longTail = generateSequence { Vec2(0, 0) }.take(10).toMutableList()
input.forEach { instruction ->
val (direction, steps) = instruction.split(" ")
repeat(steps.toInt()) {
when (direction) {
"U" -> longTail[0] = longTail[0].copy(y = longTail[0].y + 1)
"D" -> longTail[0] = longTail[0].copy(y = longTail[0].y - 1)
"L" -> longTail[0] = longTail[0].copy(x = longTail[0].x - 1)
"R" -> longTail[0] = longTail[0].copy(x = longTail[0].x + 1)
}
longTail.dropLast(1).forEachIndexed { tailElementIndex, _ ->
val currentHead = longTail[tailElementIndex]
val currentTail = longTail[tailElementIndex + 1]
if (currentHead.isNotCloseTo(currentTail)) {
longTail[tailElementIndex + 1] = moveTailToHead(
headPosition = currentHead,
tailPositon = currentTail
)
}
}
positionVisited.add(longTail.last())
}
}
return positionVisited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
val testInput2 = readInput("Day09_test2")
println("Test results:")
println(part1(testInput))
check(part1(testInput) == 13)
println(part2(testInput))
check(part2(testInput) == 1)
println(part2(testInput2))
check(part2(testInput2) == 36)
val input = readInput("Day09")
println("Final results:")
println(part1(input))
check(part1(input) == 6087)
println(part2(input))
check(part2(input) == 2493)
}
| 0 | Kotlin | 0 | 2 | 68d0c8d0bcfb81c183786dfd7e02e6745024e396 | 3,718 | advent-of-code-2022 | Apache License 2.0 |
src/day08/Day08.kt | lpleo | 572,702,403 | false | {"Kotlin": 30960} | package day08
import readInput
import kotlin.math.max
private const val FILES_DAY_08_TEST = "files/Day08_test"
private const val FILES_DAY_08 = "files/Day08"
fun main() {
fun part1(input: List<String>): Int {
val wood = createWood(input)
var counter = 0;
for (i in wood.indices) {
for (j in wood[i].indices) {
if (!existHigherTreeBefore(i, j, wood[i][j], wood) ||
!existHigherTreeAfter(i, j, wood[i][j], wood) ||
!existHigherTreeUp(i, j, wood[i][j], wood) ||
!existHigherTreeDown(i, j, wood[i][j], wood)) {
counter++;
}
}
}
return counter;
}
fun part2(input: List<String>): Int {
val wood = createWood(input)
var maxScenicIndex = 0;
for (i in wood.indices) {
for (j in wood[i].indices) {
val scenicIndex = scenicIndexBefore(i, j, wood) * scenicIndexAfter(i, j, wood) * scenicIndexUp(i, j, wood) * scenicIndexDown(i, j, wood)
if (scenicIndex > maxScenicIndex) {
maxScenicIndex = scenicIndex
}
}
}
return maxScenicIndex
}
println(part1(readInput(FILES_DAY_08_TEST)))
check(part1(readInput(FILES_DAY_08_TEST)) == 21)
println(part2(readInput(FILES_DAY_08_TEST)))
check(part2(readInput(FILES_DAY_08_TEST)) == 8)
val input = readInput(FILES_DAY_08)
println(part1(input))
println(part2(input))
}
fun createWood(input: List<String>): Array<IntArray> {
val wood = Array(input.size) { IntArray(input[0].length) }
var rowPos = 0;
var columnPos = 0
input.forEach { row ->
row.forEach { tree ->
wood[columnPos][rowPos] = (tree + "").toInt()
rowPos++;
}
rowPos = 0;
columnPos += 1;
}
return wood
}
fun existHigherTreeBefore(col: Int, row: Int, treeHeight: Int, wood: Array<IntArray>): Boolean {
for (rowPos in 0 until row) {
if (wood[col][rowPos] >= treeHeight) {
return true;
}
}
return false;
}
fun existHigherTreeAfter(col: Int, row: Int, treeHeight: Int, wood: Array<IntArray>): Boolean {
for (rowPos in row until wood[0].size) {
if (rowPos != row && wood[col][rowPos] >= treeHeight) {
return true;
}
}
return false
}
fun existHigherTreeUp(col: Int, row: Int, treeHeight: Int, wood: Array<IntArray>): Boolean {
for (columnPos in 0 until col) {
if (wood[columnPos][row] >= treeHeight) {
return true;
}
}
return false;
}
fun existHigherTreeDown(col: Int, row: Int, treeHeight: Int, wood: Array<IntArray>): Boolean {
for (columnPos in col until wood.size) {
if (columnPos != col && wood[columnPos][row] >= treeHeight) {
return true;
}
}
return false;
}
fun scenicIndexBefore(col: Int, row: Int, wood: Array<IntArray>): Int {
var counter = 0
for (rowPos in (row - 1) downTo 0) {
if (wood[col][rowPos] < wood[col][row]) {
counter++
} else {
counter++
break
}
}
return counter
}
fun scenicIndexAfter(col: Int, row: Int, wood: Array<IntArray>): Int {
var counter = 0
for (rowPos in row + 1 until wood[0].size) {
if (wood[col][rowPos] < wood[col][row]) {
counter++
} else {
counter++
break
}
}
return counter
}
fun scenicIndexUp(col: Int, row: Int, wood: Array<IntArray>): Int {
var counter = 0
for (columnPos in (col - 1) downTo 0) {
if (wood[columnPos][row] < wood[col][row]) {
counter++
} else {
counter++
break
}
}
return counter
}
fun scenicIndexDown(col: Int, row: Int, wood: Array<IntArray>): Int {
var counter = 0
for (columnPos in col + 1 until wood.size) {
if (wood[columnPos][row] < wood[col][row]) {
counter++
} else {
counter++
break
}
}
return counter
}
| 0 | Kotlin | 0 | 0 | 115aba36c004bf1a759b695445451d8569178269 | 4,176 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | akunowski | 573,109,101 | false | {"Kotlin": 5413} | fun main() {
fun roundResult(pair: Pair<Char, Char>) =
when (pair) {
'A' to 'B', 'B' to 'C', 'C' to 'A' -> 6
'A' to 'A', 'B' to 'B', 'C' to 'C' -> 3
else -> 0
}
fun shapeValue(shape: Char): Int =
when (shape) {
'A' -> 1
'B' -> 2
'C' -> 3
else -> throw Error()
}
fun calculateScore(pair: Pair<Char, Char>): Int = roundResult(pair) + shapeValue(pair.second)
fun normalizeShapesPart1(myShape: Char): Char =
when (myShape) {
'X' -> 'A'
'Y' -> 'B'
'Z' -> 'C'
else -> throw Error()
}
fun normalizeShapesPart2(pair: Pair<Char, Char>): Char =
when (pair.second) {
'X' -> {
when (pair.first) {
'A' -> 'C'
'B' -> 'A'
else -> 'B'
}
}
'Z' -> {
when (pair.first) {
'A' -> 'B'
'B' -> 'C'
else -> 'A'
}
}
else -> pair.first
}
fun part1(input: List<String>): Int =
input
.map { it[0] to normalizeShapesPart1(it[2]) }
.sumOf { calculateScore(it) }
fun part2(input: List<String>): Int =
input
.map { it[0] to normalizeShapesPart2(it[0] to it[2]) }
.sumOf { calculateScore(it) }
val input = readInput("inputs/day2")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b306b779386c793f5bf9d8a86a59a7d0755c6159 | 1,600 | aoc-2022 | Apache License 2.0 |
2022/src/day24/day24.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day24
import GREEN
import RESET
import printTimeMillis
import readInput
import java.util.*
import kotlin.math.abs
typealias Iter = (Point, Int) -> Point
data class Point(val x: Int, val y: Int) {
fun neighbors() = listOf(
Point(x + 1, y), Point(x, y + 1), Point(x - 1, y), Point(x, y - 1),
)
}
data class Blizzard(val pos: Point, val wind: Iter) {
override fun toString() = pos.toString()
}
data class Basin(
val start: Point,
val end: Point,
val maxX: Int,
val maxY: Int,
val blizzards: Set<Blizzard>
) {
fun getBlizzards(minute: Int) = blizzards.map { it.wind(it.pos, minute) }.toSet()
}
fun toBasin(input: List<String>) = input.drop(1).dropLast(1).map {
it.substring(1, it.lastIndex)
}.let {
val maxX = it.first().length - 1
val maxY = it.size - 1
val start = Point(0, -1)
val end = Point(maxX, it.size)
val blizzards = mutableSetOf<Blizzard>()
for (y in it.indices) {
for (x in it[y].indices) {
when (it[y][x]) {
'v' -> blizzards.add(Blizzard(Point(x, y)) { p, mn -> Point(p.x, (p.y + mn).mod(maxY + 1)) })
'^' -> blizzards.add(Blizzard(Point(x, y)) { p, mn -> Point(p.x, (p.y - mn).mod(maxY + 1)) })
'>' -> blizzards.add(Blizzard(Point(x, y)) { p, mn -> Point((p.x + mn).mod(maxX + 1), p.y) })
'<' -> blizzards.add(Blizzard(Point(x, y)) { p, mn -> Point((p.x - mn).mod(maxX + 1), p.y) })
}
}
}
Basin(start, end, maxX, maxY, blizzards)
}
data class Visit(val p: Point, val minute: Int)
fun runBfs(
start: Point,
end: Point,
blizCache: MutableMap<Int, Set<Point>>,
basin: Basin,
initialMinute: Int = 0
): Int {
val queue = mutableListOf<Visit>().also { it.add(Visit(start, initialMinute)) }
val visited = mutableSetOf<Visit>()
while (queue.isNotEmpty()) {
val next = queue.removeFirst()
if (visited.contains(next)) continue
visited.add(next)
if (Point(next.p.x, next.p.y + 1) == end ||
Point(next.p.x, next.p.y - 1) == end) { // reached the end
return (next.minute + 1) - initialMinute
}
for (i in next.minute..next.minute + 1) {
if (!blizCache.contains(i)) { // generate and cache the blizzard positions
blizCache[i] = basin.getBlizzards(i)
}
}
// We waited here but stuck in the blizzard, discard this option
if (blizCache[next.minute]!!.contains(next.p)) continue
val possible = next.p.neighbors().filterNot {
blizCache[next.minute + 1]!!.contains(it)
}.filterNot {
it.x < 0 || it.x > basin.maxX || it.y < 0 || it.y > basin.maxY
}
queue.add(Visit(next.p, next.minute + 1)) // wait here
queue.addAll(possible.map { Visit(it, next.minute + 1) })
}
return -1
}
fun part1(input: List<String>): Int {
val basin = toBasin(input)
val blizCache = mutableMapOf<Int, Set<Point>>()
return runBfs(basin.start, basin.end, blizCache, basin)
}
fun part2(input: List<String>): Int {
val basin = toBasin(input)
val blizCache = mutableMapOf<Int, Set<Point>>()
val there = runBfs(basin.start, basin.end, blizCache, basin)
val back = runBfs(basin.end, basin.start, blizCache, basin, there)
val thereAgain = runBfs(basin.start, basin.end, blizCache, basin, there + back)
return there + back + thereAgain
}
fun main() {
val testInput = readInput("day24_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day24.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } // 322
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 3,910 | advent-of-code | Apache License 2.0 |
y2022/src/main/kotlin/adventofcode/y2022/Day24.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
import adventofcode.util.vector.neighbors
object Day24 : AdventSolution(2022, 24, "<NAME>") {
override fun solvePartOne(input: String): Int {
val initialBlizzards: List<Blizzard> = parse(input)
val xs = initialBlizzards.minOf { it.p.x }..initialBlizzards.maxOf { it.p.x }
val ys = initialBlizzards.minOf { it.p.y }..initialBlizzards.maxOf { it.p.y }
fun Vec2.wrap(xs: IntRange, ys: IntRange) = Vec2(
when {
x < xs.first -> xs.last
x > xs.last -> xs.first
else -> x
},
when {
y < ys.first -> ys.last
y > ys.last -> ys.first
else -> y
}
)
val blizzards = generateSequence(initialBlizzards) {
it.map {
it.step().let { it.copy(p = it.p.wrap(xs, ys)) }
}
}.map { it.map { it.p }.toSet() }.drop(1)
val start = Vec2(1, 0)
val target = Vec2(xs.last, ys.last + 1)
val wallXs = xs.first - 1..xs.last + 1
val wallYs = ys.first - 1..ys.last + 1
val walls = buildSet {
addAll(wallXs.map { Vec2(it, wallYs.first) })
addAll(wallXs.map { Vec2(it, wallYs.last) })
addAll(wallYs.map { Vec2(wallXs.first, it) })
addAll(wallYs.map { Vec2(wallXs.last, it) })
add(Vec2(wallXs.first + 1, wallYs.first - 1))
add(Vec2(wallXs.last - 1, wallYs.last + 1))
remove(start)
remove(target)
}
return blizzards.scan(setOf(start)) { frontier, currentBlizzards ->
val unexploredNeighbors = frontier.flatMap { it.neighbors() + it }.toSet()
unexploredNeighbors - walls - currentBlizzards
}
.indexOfFirst { target in it }
}
override fun solvePartTwo(input: String): Int {
val initialBlizzards: List<Blizzard> = parse(input)
val xs = initialBlizzards.minOf { it.p.x }..initialBlizzards.maxOf { it.p.x }
val ys = initialBlizzards.minOf { it.p.y }..initialBlizzards.maxOf { it.p.y }
fun Vec2.wrap(xs: IntRange, ys: IntRange) = Vec2(
when {
x < xs.first -> xs.last
x > xs.last -> xs.first
else -> x
},
when {
y < ys.first -> ys.last
y > ys.last -> ys.first
else -> y
}
)
val blizzards = generateSequence(initialBlizzards) {
it.map {
it.step().let { it.copy(p = it.p.wrap(xs, ys)) }
}
}.map { it.map { it.p }.toSet() }.drop(1)
val start = Vec2(1, 0) to 0
val target = Vec2(xs.last, ys.last + 1) to 2
val wallXs = xs.first - 1..xs.last + 1
val wallYs = ys.first - 1..ys.last + 1
val walls = buildSet {
addAll(wallXs.map { Vec2(it, wallYs.first) })
addAll(wallXs.map { Vec2(it, wallYs.last) })
addAll(wallYs.map { Vec2(wallXs.first, it) })
addAll(wallYs.map { Vec2(wallXs.last, it) })
add(Vec2(wallXs.first + 1, wallYs.first - 1))
add(Vec2(wallXs.last - 1, wallYs.last + 1))
remove(start.first)
remove(target.first)
}
return blizzards.scan(setOf(start)) { frontier, currentBlizzards ->
frontier
.asSequence()
.flatMap { (p, leg) ->
(p.neighbors() + p).map { new ->
new to when {
leg == 0 && new == target.first -> 1
leg == 1 && new == start.first -> 2
else -> leg
}
}
}
.filterNot { it.first in walls }
.filterNot { it.first in currentBlizzards }
.toSet()
}
.indexOfFirst { target in it }
}
private fun parse(input: String) = buildList {
input.lineSequence().forEachIndexed { y, row ->
row.forEachIndexed { x, ch ->
when (ch) {
'<' -> add(Blizzard(Vec2(x, y), Direction.LEFT))
'>' -> add(Blizzard(Vec2(x, y), Direction.RIGHT))
'^' -> add(Blizzard(Vec2(x, y), Direction.UP))
'v' -> add(Blizzard(Vec2(x, y), Direction.DOWN))
}
}
}
}
private data class Blizzard(val p: Vec2, val d: Direction) {
fun step() = copy(p = p + d.vector)
}
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 4,792 | advent-of-code | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year19/Day24.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year19
import com.grappenmaker.aoc.*
fun PuzzleSet.day24() = puzzle(day = 24) {
val initial = inputLines.asGrid { it == '#' }
val emptyGrid = initial.mapElements { false }
val center = Point(initial.width / 2, initial.height / 2)
fun rule(curr: Boolean, adj: Int) = when {
curr && adj != 1 -> false
!curr && (adj == 1 || adj == 2) -> true
else -> curr
}
val config = initial.automaton { p, c -> rule(c, p.adjacentSideElements().countTrue()) }.firstNotDistinct()
partOne = config.points.zip(generateSequence(1) { it * 2 }.asIterable())
.sumOf { (p, a) -> if (config[p]) a else 0 }.s()
partTwo = generateSequence(mapOf(0 to initial)) { layers ->
val new = layers.toMutableMap()
val bottomLayer = layers.keys.min()
val topLayer = layers.keys.max()
if (layers.getValue(bottomLayer).any { it }) new[bottomLayer - 1] = emptyGrid
if (layers.getValue(topLayer).any { it }) new[topLayer + 1] = emptyGrid
for ((layer, grid) in new) {
new[layer] = grid.mapIndexedElements { point, v ->
if (point == center) return@mapIndexedElements false
val directNeighbours = point.adjacentSidesInf().count { it in grid && it != center && grid[it] }
val lowerNeighbours = layers[layer + 1]?.let { lowerLayer ->
when (point) {
center + Direction.LEFT -> lowerLayer.columnValues(0).countTrue()
center + Direction.RIGHT -> lowerLayer.columnValues(grid.width - 1).countTrue()
center + Direction.DOWN -> lowerLayer.rowValues(grid.height - 1).countTrue()
center + Direction.UP -> lowerLayer.rowValues(0).countTrue()
else -> 0
}
}
val upperNeighbours = layers[layer - 1]?.let { upperLayer ->
var sum = 0
if (point.x == 0 && upperLayer[center + Direction.LEFT]) sum++
if (point.x == grid.width - 1 && upperLayer[center + Direction.RIGHT]) sum++
if (point.y == grid.height - 1 && upperLayer[center + Direction.DOWN]) sum++
if (point.y == 0 && upperLayer[center + Direction.UP]) sum++
sum
}
rule(v, directNeighbours + (upperNeighbours ?: 0) + (lowerNeighbours ?: 0))
}
}
new
}.nth(200).values.sumOf { it.countTrue() }.s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,576 | advent-of-code | The Unlicense |
src/Day01.kt | euphonie | 571,665,044 | false | {"Kotlin": 23344} | fun main() {
fun buildSumArray(input: List<String>) : List<Int> {
val sums = ArrayList<Int>()
var currSum = 0;
for (food in input) {
if (food == "") {
sums.add(currSum);
currSum = 0;
} else {
currSum += food.toInt()
}
}
return sums
}
/**
* Return max sum from array
*/
fun part1(input: List<String>): Int {
var max = 0;
val sums = buildSumArray(input)
for (sum in sums){
if (sum > max){
max = sum
}
}
return max
}
/**
* Get 3 greatest values from array
*/
fun part2(input: List<String>): Int {
val sums = ArrayList<Int>(buildSumArray(input))
sums.sort()
return sums[sums.size-1] + sums[sums.size-2] + sums[sums.size-3]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 41000)
val input = readInput("Day01")
check(part1(input) == 67658)
check(part2(input) == 200158)
}
| 0 | Kotlin | 0 | 0 | 82e167e5a7e9f4b17f0fbdfd01854c071d3fd105 | 1,202 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/kr/co/programmers/P150368.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/488
class P150368 {
fun solution(users: Array<IntArray>, emoticons: IntArray): IntArray {
val answer = intArrayOf(0, 0)
// 모든 조합으로 구매를 계산한다.
val combinations = combinations(emoticons.size)
for (comb in combinations) {
var subscribe = 0 // 총 이모티콘 플러스 서비스 가입자수
var total = 0 // 총 판매 금액
for (user in users) {
var amount = 0 // 유저의 총 구매 금액
for (i in emoticons.indices) {
// 할인율이 사용자의 기준 이상이면 구매
if (comb[i] >= user[0]) {
amount += emoticons[i] * (100 - comb[i]) / 100
}
// 사용자의 총 구매 금액이 기준 금액을 넘으면 서비스 가입으로 전환
if (amount >= user[1]) {
subscribe++
amount = 0
break
}
}
total += amount // 총 만패 금액에 합산
}
// 교체 기준
if (subscribe > answer[0]) {
answer[0] = subscribe
answer[1] = total
} else if (subscribe == answer[0] && total > answer[1]) {
answer[1] = total
}
}
return answer
}
private fun combinations(n: Int): List<List<Int>> {
val combinations = mutableListOf<List<Int>>()
backtrack(combinations, mutableListOf(), n)
return combinations
}
private fun backtrack(combinations: MutableList<List<Int>>, current: MutableList<Int>, N: Int) {
if (current.size == N) {
combinations.add(current.toList())
return
}
val numbers = listOf(10, 20, 30, 40)
for (number in numbers) {
current.add(number)
backtrack(combinations, current, N)
current.removeAt(current.size - 1)
}
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 2,153 | algorithm | MIT License |
src/main/kotlin/adventofcode/year2022/Day12HillClimbingAlgorithm.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2022
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.common.neighbors
class Day12HillClimbingAlgorithm(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val grid by lazy { input.lines().map(String::toList) }
override fun partOne() = grid.bfs('S', 'E') { from, to -> to.level - from.level <= 1 }
override fun partTwo() = grid.bfs('E', 'a') { from, to -> to.level - from.level >= -1 }
companion object {
private fun List<List<Char>>.find(char: Char): Pair<Int, Int> {
val y = indexOfFirst { row -> row.contains(char) }
val x = this[y].indexOfFirst { column -> column == char }
return x to y
}
private val Char.level
get() = when (this) {
'S' -> 0
'E' -> 'z' - 'a'
else -> this - 'a'
}
private fun List<List<Char>>.bfs(start: Char, end: Char, validNeighborTest: (from: Char, to: Char) -> Boolean): Int {
val startNode = find(start)
val queue: MutableList<Pair<Int, Int>> = mutableListOf(startNode)
val visited: MutableMap<Pair<Int, Int>, Int> = mutableMapOf(startNode to 0)
while (queue.isNotEmpty() && this[queue.first().second][queue.first().first] != end) {
val (x, y) = queue.removeFirst()
neighbors(x, y, false)
.filter { (nx, ny) -> validNeighborTest(this[y][x], this[ny][nx]) }
.filterNot { neighbor -> visited.contains(neighbor) }
.forEach { neighbor ->
queue += neighbor
visited[neighbor] = visited[x to y]!! + 1
}
}
return visited.keys.filter { (x, y) -> this[y][x] == end }.minOf { key -> visited[key]!! }
}
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 1,904 | AdventOfCode | MIT License |
src/Day08.kt | euphonie | 571,665,044 | false | {"Kotlin": 23344} | fun main() {
fun buildMatrix(input: List<String>) : Array<IntArray> {
return input.map {
it.map { v -> v.digitToInt() }.toIntArray()
}.toTypedArray()
}
fun printMatrix(matrix: Array<IntArray>) {
println(
matrix.map {
it.contentToString() + "\n"
}
)
}
fun isVisible(i:Int, j:Int, matrix: Array<IntArray>) : Boolean {
val height = matrix.size
val width = matrix[0].size
// find first blocking tree at each direction for given coordinate
val maxNorth =
if (matrix[i-1][j] < matrix[i][j]) (i-1 downTo 0).maxOf { matrix[it][j] }
else matrix[i-1][j]
val maxSouth =
if (matrix[i+1][j] < matrix[i][j]) (i+1 until height).maxOf { matrix[it][j] }
else matrix[i+1][j]
val maxEast =
if (matrix[i][j+1] < matrix[i][j]) (j+1 until width).maxOf { matrix[i][it] }
else matrix[i][j+1]
val maxWest =
if (matrix[i][j-1] < matrix[i][j]) (j-1 downTo 0).maxOf { matrix[i][it] }
else matrix[i][j-1]
return arrayOf(maxNorth, maxSouth, maxEast, maxWest).any { matrix[i][j] > it }
}
fun part1(input: List<String>) : Int {
val matrix = buildMatrix(input)
val height = matrix.size
val width = matrix[0].size
var counter = 0
for (i in 1 until height -1) {
for (j in 1 until width -1) {
counter += if (isVisible(i, j, matrix)) 1 else 0
}
}
return counter + (2*height) + (2*width) - 4
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
val input = readInput("Day08")
check(part1(input) == 1823)
} | 0 | Kotlin | 0 | 0 | 82e167e5a7e9f4b17f0fbdfd01854c071d3fd105 | 1,835 | advent-of-code-kotlin | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day17/Day17.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day17
import nl.sanderp.aoc.common.*
private val targetX = 29..73
private val targetY = -248..-194
fun main() {
val (answer1, duration1) = measureDuration<Int> { partOne() }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
val (answer2, duration2) = measureDuration<Int> { partTwo() }
println("Part two: $answer2 (took ${duration2.prettyPrint()})")
}
private fun trajectory(initialVelocity: Point2D) = velocity(initialVelocity).runningFold(0 to 0) { p, v -> p + v }
private fun velocity(initial: Point2D) = generateSequence(initial) {
val nextX = when {
it.x > 0 -> it.x - 1
it.x < 0 -> it.x + 1
else -> 0
}
Point2D(nextX, it.y - 1)
}
private fun partOne(): Int {
val valid = buildList {
for (x in 0..targetX.last) {
for (y in 0..1000) {
val t = trajectory(x to y).takeWhile { it.x <= targetX.last && it.y >= targetY.first }
if (t.any { it.x >= targetX.first && it.y <= targetY.last }) {
add(t)
}
}
}
}
return valid.maxOf { t -> t.maxOf { it.y } }
}
private fun partTwo(): Int {
val valid = buildList {
for (x in 0..targetX.last) {
for (y in targetY.first..1000) {
val t = trajectory(x to y).takeWhile { it.x <= targetX.last && it.y >= targetY.first }
if (t.any { it.x >= targetX.first && it.y <= targetY.last }) {
add(x to y)
}
}
}
}
return valid.distinct().size
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,617 | advent-of-code | MIT License |
src/Day03.kt | hubikz | 573,170,763 | false | {"Kotlin": 8506} | fun main() {
// a..z -> 1..25
// A..Z -> 26..52
fun charToPriority(char: Char): Int {
return Character.getNumericValue(char) - 9 + if (Character.isUpperCase(char)) 26 else 0
}
fun part1(input: List<String>): Int {
return input.sumOf { items ->
val halfIndex = items.length / 2
val compartment1 = items.toCharArray(0, halfIndex)
val compartment2 = items.toCharArray(halfIndex)
val element = compartment1.first { compartment2.contains(it) }
charToPriority(element)
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf {
val (first, second, third) = it
val element = first.first { char -> second.contains(char) && third.contains(char) }
charToPriority(element)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println("Part 1: ${part1(input)}")
check(part2(testInput) == 70)
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 902c6c3e664ad947c38c8edcb7ffd612b10e58fe | 1,158 | AoC2022 | Apache License 2.0 |
src/Day07.kt | chrisjwirth | 573,098,264 | false | {"Kotlin": 28380} | fun main() {
class Dir(
val name: String,
val parentDir: Dir? = null,
val childrenDirs: MutableMap<String, Dir> = mutableMapOf(),
var sizeOfDirectFiles: Int = 0,
var totalSize: Int? = null
)
fun linePurpose(line: String): String {
return if (line.substring(0, 4) == "$ cd") {
"cd"
} else if (line.substring(0, 4) == "$ ls") {
"ls"
} else if (line.substring(0, 3) == "dir") {
"dir"
} else {
"fileSize"
}
}
fun buildDirTree(input: List<String>): MutableMap<String, Dir> {
val dirs = mutableMapOf(
"/" to Dir("/")
)
var currentDir = Dir("")
input.forEach inputLoop@ {
when (linePurpose(it)) {
"cd" -> {
val dirName = it.substring(5)
currentDir = if (dirName == "..") {
currentDir.parentDir!!
} else {
dirs[currentDir.name + dirName]!!
}
}
"dir" -> {
val childDirName = currentDir.name + it.substring(4)
val childDir = Dir(childDirName, currentDir)
currentDir.childrenDirs[childDirName] = childDir
dirs[childDirName] = childDir
}
"fileSize" -> {
val fileSize = it.split(" ")[0].toInt()
currentDir.sizeOfDirectFiles += fileSize
}
else -> return@inputLoop
}
}
return dirs
}
fun dirSize(dir: Dir): Int {
var size = dir.sizeOfDirectFiles
val stack = mutableListOf<Dir>()
stack.addAll(dir.childrenDirs.values)
while (stack.isNotEmpty()) {
val childDir = stack.removeLast()
if (childDir.totalSize != null) {
size += childDir.totalSize!!
} else {
size += childDir.sizeOfDirectFiles
stack.addAll(childDir.childrenDirs.values)
}
}
return size
}
fun listOfDirSizes(dirs: MutableMap<String, Dir>): MutableList<Int> {
val listOfSizes = mutableListOf<Int>()
dirs.values.forEach {
listOfSizes.add(dirSize(it))
}
return listOfSizes
}
fun part1(input: List<String>): Int {
val dirs = buildDirTree(input)
val listOfDirSizes = listOfDirSizes(dirs)
return listOfDirSizes.filter { it <= 100_000 }.sum()
}
fun part2(input: List<String>): Int {
val dirs = buildDirTree(input)
val listOfDirSizes = listOfDirSizes(dirs)
val totalSpace = 70_000_000
val remainingSpace = totalSpace - listOfDirSizes.maxOf { it }
val spaceToFree = 30_000_000 - remainingSpace
return listOfDirSizes.filter { it >= spaceToFree }.min()
}
// Test
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
// Final
val input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d8b1f2a0d0f579dd23fa1dc1f7b156f728152c2d | 3,226 | AdventOfCode2022 | Apache License 2.0 |
archive/2022/Day05.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = "CMZ"
private const val EXPECTED_2 = "MCD"
private class Day05(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
val data = readAsString()
val parts = data.split("\n\n")
val stacks = readInitialState(parts[0])
applyCommands(stacks, parts[1], true)
return stacks.map { it.last() }.joinToString("")
}
fun part2(): Any {
val data = readAsString()
val parts = data.split("\n\n")
val stacks = readInitialState(parts[0])
applyCommands(stacks, parts[1], false)
return stacks.map { it.last() }.joinToString("")
}
private fun readInitialState(initialState: String): MutableList<MutableList<Char>> {
val stacks = mutableListOf<MutableList<Char>>()
val lines = initialState.split("\n")
val N = (lines[0].length + 3) / 4
for (i in 0 until N) {
stacks.add(mutableListOf<Char>())
}
for (line in lines.subList(0, lines.size - 1)) {
for (i in 0 until N) {
if (line[i * 4 + 1] != ' ') {
stacks[i].add(line[i * 4 + 1])
}
}
}
stacks.forEach { it.reverse() }
return stacks
}
private fun applyCommands(stacks: MutableList<MutableList<Char>>, commands: String, shouldReverse: Boolean) {
for (line in commands.split('\n')) {
if (line.trim().isEmpty()) {
continue
}
val parts = line.split(" ")
val count = parts[1].toInt()
val from = stacks[parts[3].toInt() - 1]
val to = stacks[parts[5].toInt() - 1]
to.addAll(from.subList(from.size - count, from.size).let { if(shouldReverse) it.reversed() else it })
from.subList(from.size - count, from.size).clear()
}
}
}
fun main() {
val testInstance = Day05(true)
val instance = Day05(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println(instance.part1())
testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } }
println(instance.part2())
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 2,203 | advent-of-code-2022 | Apache License 2.0 |
2022/src/main/kotlin/day20_attempt3.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.badInput
import utils.mapItems
import kotlin.math.absoluteValue
fun main() {
Day20_3.run()
}
object Day20_3 : Solution<List<Long>>() {
override val name = "day20"
override val parser = Parser.lines.mapItems { it.toLong() }
data class Item(
val origIndex: Int,
val value: Long,
)
override fun part1(input: List<Long>): Any? {
return solve(input, 1, 1)
}
override fun part2(input: List<Long>): Any? {
return solve(input, 811589153, 10)
}
fun solve(input: List<Long>, key: Long, mixTimes: Int): Long {
val items = MutableList(input.size) { Item(it, input[it] * key) }
fun wrap(idx: Int): Int {
return (input.size + idx) % input.size
}
fun wrapRepeats(r: Long): Int {
return (r % (input.size - 1)).toInt() // why?
}
repeat(mixTimes) {
for (i in input.indices) {
val curIndex = items.indexOfFirst { it.origIndex == i }
val item = items[curIndex]
// swap forward N times
if (item.value > 0) {
var idx = curIndex
repeat(wrapRepeats(item.value)) {
val swap = items[wrap(idx)]
items[wrap(idx)] = items[wrap(idx + 1)]
items[wrap(idx + 1)] = swap
idx = wrap(idx + 1)
}
} else {
var idx = curIndex
repeat(wrapRepeats(item.value.absoluteValue)) {
val swap = items[wrap(idx - 1)]
items[wrap(idx - 1)] = items[wrap(idx)]
items[wrap(idx)] = swap
idx = wrap(idx - 1)
}
}
}
}
val zi = items.indexOfFirst { it.value == 0L }
return items[(zi + 1000) % input.size].value + items[(zi + 2000) % input.size].value + items[(zi + 3000) % input.size].value
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,804 | aoc_kotlin | MIT License |
src/year2023/day10/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2023.day10
import arrow.core.nonEmptyListOf
import io.kotest.matchers.collections.shouldHaveSize
import utils.Point
import utils.ProblemPart
import utils.get
import utils.neighbors
import utils.print
import utils.readInputs
import utils.runAlgorithm
import utils.x
import utils.y
fun main() {
val (realInput, testInputs) = readInputs(
2023,
10,
"test_input_2",
"test_input_3",
"test_input_4",
)
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(8, 22, 70, 80),
algorithm = ::part1,
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(1, 4, 8, 10),
algorithm = ::part2,
),
)
}
private fun part1(input: List<String>): Int = computeLoop(input).size / 2
private fun computeLoop(input: List<String>): List<Point> {
val start = input.asSequence()
.mapIndexedNotNull { y, row ->
row.asSequence()
.mapIndexedNotNull { x, char -> if (char == 'S') x else null }
.firstOrNull()
?.let { Point(it, y) }
}
.first()
val (firstPoint, secondPoint) = start.neighbors()
.filter { it.x in input.first().indices && it.y in input.indices }
.filter { neighbor -> start in neighbor.pipeNeighbors(input[neighbor]) }
.toList()
.also { it shouldHaveSize 2 }
return computeNextStepFunction(input)
.let {
generateSequence(mutableListOf(start, firstPoint), it)
.zip(generateSequence(mutableListOf(start, secondPoint), it))
}
.takeWhile { (path1, path2) ->
path1.last() != path2.last() && path1[path1.lastIndex - 1] != path2[path2.lastIndex]
}
.last()
.let { (path1, path2) ->
path1 + path2.asReversed().asSequence().drop(if (path1.last() == path2.last()) 1 else 2)
}
}
private fun Point.pipeNeighbors(pipeShape: Char): List<Point> = when (pipeShape) {
'|' -> listOf(moveUp(this), moveDown(this))
'-' -> listOf(moveLeft(this), moveRight(this))
'F' -> listOf(moveRight(this), moveDown(this))
'J' -> listOf(moveUp(this), moveLeft(this))
'7' -> listOf(moveLeft(this), moveDown(this))
'L' -> listOf(moveUp(this), moveRight(this))
else -> emptyList()
}
private val moveLeft = Point.x.lift(Int::dec)
private val moveRight = Point.x.lift(Int::inc)
private val moveUp = Point.y.lift(Int::dec)
private val moveDown = Point.y.lift(Int::inc)
private fun computeNextStepFunction(input: List<String>): (MutableList<Point>) -> MutableList<Point>? = { path ->
val newElement = path.last().pipeNeighbors(input[path.last()])
.single { it != path[path.lastIndex - 1] }
path.apply { add(newElement) }
}
private fun part2(input: List<String>): Int {
val loop = computeLoop(input).toSet()
val standardMap = input.mapIndexed { y, line ->
line.asSequence()
.mapIndexed { x, char ->
when {
Point(x, y) !in loop -> '.'
char == 'S' -> when {
Point(x, y + 1) in loop && Point(x, y - 1) in loop -> '|'
Point(x, y + 1) in loop && Point(x + 1, y) in loop -> 'F'
Point(x, y + 1) in loop && Point(x - 1, y) in loop -> '7'
Point(x, y - 1) in loop && Point(x + 1, y) in loop -> 'L'
Point(x, y - 1) in loop && Point(x - 1, y) in loop -> 'J'
else -> '-'
}
else -> char
}
}
.joinToString(separator = "")
}
val horizontalInterior = standardMap.asSequence()
.findInnerPoints(wrappedHorizontalZones)
.toSet()
val verticalInterior = standardMap.first().indices.asSequence()
.map { column -> standardMap.asSequence().map { it[column] }.joinToString(separator = "") }
.findInnerPoints(wrappedVerticalZones)
.map { Point(it.y, it.x) }
.toSet()
return horizontalInterior.intersect(verticalInterior).size
}
private fun Sequence<String>.findInnerPoints(insideRegex: Regex): Sequence<Point> = flatMapIndexed { y, line ->
insideRegex.findAll(line)
.filterIndexed { index, _ -> index % 2 == 0 }
.flatMap { match ->
val space = match.groups[1]!!
space.range.asSequence().mapNotNull { x -> if (line[x] == '.') x else null }
}
.map { x -> Point(x, y) }
}
private val wrappedHorizontalZones = "(?:\\||F-*J|L-*7)(.*?)(?=\\||F-*J|L-*7)".toRegex()
private val wrappedVerticalZones = "(?:-|7\\|*L|F\\|*J)(.*?)(?=-|7\\|*L|F\\|*J)".toRegex()
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 4,831 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/day12.kt | kevinrobayna | 436,414,545 | false | {"Ruby": 195446, "Kotlin": 42719, "Shell": 1288} | import kotlin.math.abs
fun day12ProblemReader(text: String): List<Pair<String, Int>> {
return text
.split('\n')
.map { line ->
Pair(line.trim().filter { !it.isDigit() }, line.trim().filter { it.isDigit() }.toInt())
}
}
// https://adventofcode.com/2020/day/12
class Day12(
private val actions: List<Pair<String, Int>>,
) {
companion object {
const val NORTH = "N"
const val SOUTH = "S"
const val EAST = "E"
const val WEST = "W"
const val FORWARD = "F"
val MOVEMENTS = listOf(NORTH, SOUTH, EAST, WEST, FORWARD)
const val LEFT = "L"
const val RIGHT = "R"
}
fun solvePart1(): Int {
return solve(Pair(1, 0), false)
}
fun solvePart2(): Int {
return solve(Pair(10, 1), true)
}
private fun solve(direction: Pair<Int, Int> = Pair(1, 0), waypoint: Boolean = false): Int {
var (dx, dy) = direction
var (x, y) = Pair(0, 0)
for ((change, amount) in actions) {
when (change in MOVEMENTS) {
true -> {
when (change) {
NORTH -> {
if (waypoint) dy += amount
else y += amount
}
SOUTH -> {
if (waypoint) dy -= amount
else y -= amount
}
EAST -> {
if (waypoint) dx += amount
else x += amount
}
WEST -> {
if (waypoint) dx -= amount
else x -= amount
}
FORWARD -> {
x += dx * amount
y += dy * amount
}
}
}
else -> {
when (amount) {
90 -> when (change) {
LEFT -> dx = -dy.also { dy = dx }
RIGHT -> dy = -dx.also { dx = dy }
}
180 -> dx = -dx.also { dy = -dy }
270 -> when (change) {
LEFT -> dy = -dx.also { dx = dy }
RIGHT -> dx = -dy.also { dy = dx }
}
}
}
}
}
return abs(x) + abs(y)
}
}
fun main() {
val problem = day12ProblemReader(Day10::class.java.getResource("day12.txt").readText())
println("solution = ${Day12(problem).solvePart1()}")
println("solution part2 = ${Day12(problem).solvePart2()}")
} | 0 | Kotlin | 0 | 0 | 9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577 | 2,812 | adventofcode_2020 | MIT License |
src/Day03.kt | GreyWolf2020 | 573,580,087 | false | {"Kotlin": 32400} | fun main() {
fun itemPriority(c: Char): Int = when {
c.isLowerCase() -> c.code - 96
c.isUpperCase() -> c.code - 64 + 26
else -> 0
}
fun part1(input: List<String>): Int = input.foldRight(0) { rucksack, prioritySum ->
rucksack
.chunked(rucksack.length / 2)
.map {
it.toSet()
}
.intersection()
.map(::itemPriority)
.sum() + prioritySum
}
fun part2(input: List<String>): Int = input
.windowed(3, 3)
.foldRight(0) { threeRucksacks, prioritySum ->
threeRucksacks
.map { it.toSet() }
.intersection()
.map(::itemPriority)
.sum() + prioritySum
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day03_test")
// check(part1(testInput) == 157)
// check(part2(testInput) == 70)
//
// val input = readInput("Day03")
// println(part1(input))
// println(part2(input))
}
//
//fun List<Set<Char>>.intersection() = reduce { element, acc ->
// element.intersect(acc)
//}
private fun <A> List<Set<A>>.intersection(): Set<A> = reduce { element, acc ->
element.intersect(acc)
} | 0 | Kotlin | 0 | 0 | 498da8861d88f588bfef0831c26c458467564c59 | 1,312 | aoc-2022-in-kotlin | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2022/Day18.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2022
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.resultFrom
/**
* --- Day 18: Boiling Boulders ---
* https://adventofcode.com/2022/day/18
*/
class Day18 : Solver {
private val deltas = setOf(
XYZ(-1, 0, 0),
XYZ(1, 0, 0),
XYZ(0, -1, 0),
XYZ(0, 1, 0),
XYZ(0, 0, -1),
XYZ(0, 0, 1)
)
override fun solve(lines: List<String>): Result {
val cubes = lines.map { it.split(",") }
.map { XYZ(it[0].toInt(), it[1].toInt(), it[2].toInt()) }.toSet()
val (minX, maxX) = listOf(cubes.minOf { it.x }, cubes.maxOf { it.x })
val (minY, maxY) = listOf(cubes.minOf { it.y }, cubes.maxOf { it.y })
val (minZ, maxZ) = listOf(cubes.minOf { it.z }, cubes.maxOf { it.z })
val allAir = mutableSetOf<XYZ>()
for (x in minX..maxX) {
for (y in minY..maxY) {
for (z in minZ..maxZ) {
XYZ(x, y, z).let { if (it !in cubes) allAir.add(it) }
}
}
}
val trappedAir = mutableSetOf<XYZ>()
val alreadyLookedAt = mutableSetOf<XYZ>()
for (air in allAir) {
if (air in alreadyLookedAt) continue
val group = mutableSetOf(air)
floodFill(air, group, cubes)
alreadyLookedAt.addAll(group)
val trapped =
!group.any { a -> a.x !in minX..maxX || a.y !in minY..maxY || a.z !in minZ..maxZ }
if (trapped) trappedAir.addAll(group)
}
val sidesA = cubes.sumOf { numSidesFree(it, cubes, emptySet()) }
val sidesB = cubes.sumOf { numSidesFree(it, cubes, trappedAir) }
return resultFrom(sidesA, sidesB)
}
private fun floodFill(c: XYZ, group: MutableSet<XYZ>, cubes: Set<XYZ>) {
if (c.x < cubes.minOf { it.x } || c.x > cubes.maxOf { it.x } ||
c.y < cubes.minOf { it.y } || c.y > cubes.maxOf { it.y } ||
c.z < cubes.minOf { it.z } || c.z > cubes.maxOf { it.z })
return
val sideCubes = deltas.map { XYZ(it.x + c.x, it.y + c.y, it.z + c.z) }
val sideAirNew = sideCubes.subtract(cubes).subtract(group)
group.addAll(sideAirNew)
sideAirNew.forEach { floodFill(it, group, cubes) }
}
private fun numSidesFree(c: XYZ, all: Set<XYZ>, trappedAir: Set<XYZ>) =
deltas.map { XYZ(it.x + c.x, it.y + c.y, it.z + c.z) }
.minus(trappedAir)
.minus(all).count()
data class XYZ(val x: Int, val y: Int, val z: Int)
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,335 | euler | Apache License 2.0 |
src/day01/Day01.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day01
import readInput
data class CalorieEntry(val elfId: Int, val calories: Int)
fun parseInput(inputLines: List<String>): Iterable<CalorieEntry> {
val caloriesPerItem = mutableListOf<CalorieEntry>()
var elfId = 0
for (line in inputLines) {
if (line.isEmpty()) {
++elfId
continue
}
caloriesPerItem.add(CalorieEntry(elfId, line.toInt()))
}
val totalCaloriesPerElf = caloriesPerItem.groupBy { entry ->
entry.elfId
}.map {
CalorieEntry(it.key, it.value.sumOf { calorieEntry -> calorieEntry.calories })
}
return totalCaloriesPerElf
}
fun main() {
fun part1(input: List<String>): Int {
val totalCaloriesPerElf = parseInput(input)
val maxCalorieElf = totalCaloriesPerElf.maxBy { it.calories }
return maxCalorieElf.calories
}
fun part2(input: List<String>): Int {
val totalCaloriesPerElf = parseInput(input)
return totalCaloriesPerElf.sortedByDescending { it.calories }.take(3).sumOf { it.calories }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("sample_data", 1)
check(part1(testInput) == 24000)
val input = readInput("main_data", 1)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 1,321 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day13.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.P
fun main() = Day13.run()
object Day13 : Day(2022, 13) {
class Packet(private val fixed: Int? = null, val values: MutableList<Packet> = mutableListOf()) : Comparable<Packet> {
override fun toString() = fixed?.toString() ?: ("[" + values.joinToString(",") + "]")
override operator fun compareTo(other: Packet): Int {
if (this.fixed != null && other.fixed != null) return this.fixed.compareTo(other.fixed)
val left = if (this.fixed != null) Packet(null, mutableListOf(Packet(this.fixed))) else this
val right = if (other.fixed != null) Packet(null, mutableListOf(Packet(other.fixed))) else other
for (i in left.values.indices) {
if (i >= right.values.size) return 1
val compareI = left.values[i].compareTo(right.values[i])
if (compareI != 0) return compareI
}
return left.values.size.compareTo(right.values.size)
}
companion object {
fun parse(inp: String): Packet {
val p = Packet()
val part = inp.dropLast(1).drop(1)
var i = 0
var num = ""
while (i < part.length) {
val c = part[i]
if (c.isDigit()) {
num += c
} else if (c == '[') {
var j = i + 1
var cnt = 1
while (cnt > 0) {
if (part[j] == ']') cnt -= 1
else if (part[j] == '[') cnt += 1
j += 1
}
p.values.add(parse(part.substring(i, j)))
i = j - 1
} else if (c == ',' && num != "") {
p.values.add(Packet(num.toInt()))
num = ""
}
i += 1
}
if (num != "") p.values.add(Packet(num.toInt()))
return p
}
}
}
override fun part1(): Any {
val packetPairs = input.split("\n\n").map { P(Packet.parse(it.lines()[0]), Packet.parse(it.lines()[1])) }
return packetPairs.withIndex().filter { it.value.first < it.value.second }.sumOf { it.index + 1 }
}
override fun part2(): Any {
val packets = input.lines().filter { it != "" }.map(Packet.Companion::parse).toMutableList()
val divider1 = Packet.parse("[[2]]")
val divider2 = Packet.parse("[[6]]")
packets.add(divider1)
packets.add(divider2)
packets.sort()
return (packets.indexOf(divider1) + 1) * (packets.indexOf(divider2) + 1)
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,853 | adventofkotlin | MIT License |
src/Day13.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} |
fun main() {
fun CharSequence.toList(): List<Any> {
fun listHelper(s: CharSequence, startIx: Int): Pair<List<Any>, Int> {
var ix = startIx
if (s[ix++] != '[') throw IllegalArgumentException("Not a list: $s")
val ret = mutableListOf<Any>()
while (ix < this.length) {
val nextVal: Any = when(s[ix]) {
'[' -> {
val(list, newIx) = listHelper(s,ix)
ix = newIx
list
}
']' -> return Pair(ret, ix + 1)
',' -> {
++ix
continue
}
else -> {
// assume it's a number
val end = s.indexOfAny(",]".toCharArray(), ix)
if (end < ix) throw IllegalArgumentException("Bad syntax in: ${s.subSequence(ix,s.length)}")
val int = s.subSequence(ix,end).trim().toString().toInt()
ix = end
int
}
}
ret.add(nextVal)
}
throw IllegalArgumentException("No closing bracket: $s")
}
return listHelper(this, 0).first
}
fun compare(left: List<Any>, right: List<Any>): Int {
if (left.isEmpty()) return if (right.isEmpty()) 0 else -1
for ((ix, itemL) in left.withIndex()) {
val itemR = right.getOrNull(ix) ?: return 1
val listL = itemL as? List<Any>
val listR = itemR as? List<Any>
val result = when {
listL != null && listR != null -> compare(listL, listR)
listL != null -> compare(listL, listOf(itemR))
listR != null -> compare(listOf(itemL), listR)
itemL is Int && itemR is Int -> itemL - itemR
else -> throw IllegalArgumentException("Blargh")
}
if (result != 0) {
return result
}
}
return if (right.size > left.size) -1 else 0
}
fun compare(left: String, right: String): Int {
return compare(left.toList(), right.toList())
}
fun part1(input: List<String>): Int {
var left: String? = null
var right: String? = null
var pairCount = 1
val listOfCorrectPairs = mutableListOf<Int>()
for (line in input) {
if (line.isBlank()) {
left = null
right = null
} else if (left == null) {
left = line
} else if (right == null) {
right = line
if (compare(left, right) < 0) {
listOfCorrectPairs.add(pairCount)
}
++pairCount
}
}
println(listOfCorrectPairs)
return listOfCorrectPairs.sum()
}
fun part2(input: List<String>): Int {
val twoList = "[[2]]".toList()
val sixList = "[[6]]".toList()
val allLists = input.mapNotNull { if (it.isBlank()) null else it.toList() }.toMutableList()
allLists.addAll(listOf(twoList, sixList))
allLists.sortWith { first, second -> compare(first, second) }
val twoIx = allLists.indexOfFirst { compare(it,twoList) == 0 } + 1
val sixIx = allLists.indexOfFirst { compare(it,sixList) == 0 } + 1
println("Two at $twoIx, six at $sixIx")
return twoIx * sixIx
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"[1,1,3,1,1]\n",
"[1,1,5,1,1]\n",
"\n",
"[[1],[2,3,4]]\n",
"[[1],4]\n",
"\n",
"[9]\n",
"[[8,7,6]]\n",
"\n",
"[[4,4],4,4]\n",
"[[4,4],4,4,4]\n",
"\n",
"[7,7,7,7]\n",
"[7,7,7]\n",
"\n",
"[]\n",
"[3]\n",
"\n",
"[[[]]]\n",
"[[]]\n",
"\n",
"[1,[2,[3,[4,[5,6,7]]]],8,9]\n",
"[1,[2,[3,[4,[5,6,0]]]],8,9]\n\n",
)
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 4,314 | 2022-aoc-kotlin | Apache License 2.0 |
src/Day05.kt | jamesrobert | 573,249,440 | false | {"Kotlin": 13069} | fun main() {
fun loadCrates(crateInput: List<String>): MutableMap<Int, String> {
val crates = mutableMapOf<Int, String>()
for (line in crateInput) {
for ((index, chunk) in line.chunked(4).withIndex()) {
val stackNumber = index + 1
if (crates[stackNumber] == null) crates[stackNumber] = ""
if (chunk.isBlank() || chunk[1].isDigit()) continue
crates[stackNumber] = "${chunk[1]}${crates[stackNumber]}"
}
}
return crates
}
fun getMoves(moveInput: List<String>) = moveInput.map {
Triple(
it.substring(5, it.indexOf(" from ")).toInt(),
it.substring(it.indexOf(" from ") + 6, it.indexOf(" to ")).toInt(),
it.substring(it.indexOf(" to ") + 4).toInt()
)
}
fun move(crates: MutableMap<Int, String>, moveInput: List<String>): Map<Int, String> {
for ((q, f, t) in getMoves(moveInput)) {
var qq = q
while (qq > 0) {
crates[t] = crates[t] + crates[f]!!.last()
crates[f] = crates[f]!!.dropLast(1)
qq--
}
}
return crates
}
fun moveMultiple(crates: MutableMap<Int, String>, moveInput: List<String>): Map<Int, String> {
for ((q, f, t) in getMoves(moveInput)) {
crates[t] = crates[t] + crates[f]!!.substring(crates[f]!!.length - q)
crates[f] = crates[f]!!.dropLast(q)
}
return crates
}
fun moveCrates(input: List<String>, move: (MutableMap<Int, String>, List<String>) -> Map<Int, String>): String {
val crateInput = input.takeWhile { it != "" }
val moveInput = input.takeLastWhile { it != "" }
val crates = loadCrates(crateInput)
return move(crates, moveInput).map { it.value.last() }.joinToString(separator = "")
}
fun part1(input: List<String>): String = moveCrates(input, ::move)
fun part2(input: List<String>): String = moveCrates(input, ::moveMultiple)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input)) // BSDMQFLSP
println(part2(input)) // PGSQBFLDP
} | 0 | Kotlin | 0 | 0 | d0b49770fc313ae42d802489ec757717033a8fda | 2,361 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | Jintin | 573,640,224 | false | {"Kotlin": 30591} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val a = line.substring(0, line.length / 2).toSet().toMutableSet()
val b = line.substring(line.length / 2).toSet()
a.retainAll(b)
a.sumOf {
if (it in 'A'..'Z') {
it - 'A' + 1 + 26
} else {
it - 'a' + 1
}
}
}
}
fun part2(input: List<String>): Int {
var score = 0
for (index in 0 until input.size / 3) {
val a = input[index * 3].toSet().toMutableSet()
val b = input[index * 3 + 1].toSet()
val c = input[index * 3 + 2].toSet()
a.retainAll(b)
a.retainAll(c)
score += a.sumOf {
if (it in 'A'..'Z') {
it - 'A' + 1 + 26
} else {
it - 'a' + 1
}
}
}
return score
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 4aa00f0d258d55600a623f0118979a25d76b3ecb | 1,110 | AdventCode2022 | Apache License 2.0 |
src/Day02.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | fun main() {
fun part1(input: List<String>): Int {
return input.filter { return@filter it.isNotEmpty() }.sumOf {
var myChoice = it[2].code - 'X'.code
var win = when (it[0].code - 'A'.code) {
(myChoice + 1) % 3 -> 0
myChoice -> 3
else -> 6
}
return@sumOf win + myChoice + 1
}
}
fun part2(input: List<String>): Int {
return input.filter { return@filter it.isNotEmpty() }.sumOf {
var outcome = it[2].code - 'X'.code
var opChoice = it[0].code - 'A'.code
return@sumOf outcome * 3 + (opChoice + outcome + 2) % 3 + 1
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 973 | aoc-2022 | Apache License 2.0 |
src/Day01.kt | qmchenry | 572,682,663 | false | {"Kotlin": 22260} | fun main() {
fun sums(input: List<String>): List<Int> {
return input
.flatMapIndexed { index, x ->
when {
index == 0 || index == input.lastIndex -> listOf(index)
x.isEmpty() -> listOf(index - 1, index + 1)
else -> emptyList()
}
}
.windowed(size = 2, step = 2) { (from, to) ->
input.slice(from..to)
.map { it.toInt() }
}
.map { it.sum() }
}
fun part1(input: List<String>): Int {
return sums(input).maxOf { it }
}
fun part2(input: List<String>): Int {
return sums(input)
.sorted()
.takeLast(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_sample")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val realInput = readInput("Day01_test")
println("Part 1: ${part1(realInput)}")
println("Part 2: ${part2(realInput)}")
}
| 0 | Kotlin | 0 | 0 | 2813db929801bcb117445d8c72398e4424706241 | 1,103 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day23.kt | clechasseur | 567,968,171 | false | {"Kotlin": 493887} | package io.github.clechasseur.adventofcode.y2022
import io.github.clechasseur.adventofcode.util.Pt
import io.github.clechasseur.adventofcode.y2022.data.Day23Data
object Day23 {
private val input = Day23Data.input
fun part1(): Int = groveSequence(input.toGrove()).elementAt(10).groundCount
fun part2(): Int = groveSequence(input.toGrove()).count()
private enum class Direction(val displacement: Pt) {
NW(Pt(-1, -1)),
N(Pt(0, -1)),
NE(Pt(1, -1)),
E(Pt(1, 0)),
SE(Pt(1, 1)),
S(Pt(0, 1)),
SW(Pt(-1, 1)),
W(Pt(-1, 0));
companion object {
val allDirections = setOf(*values())
}
}
private fun Pt.move(direction: Direction): Pt = this + direction.displacement
private data class Proposal(val checks: Set<Direction>, val result: Direction)
private val initialProposals = listOf(
Proposal(setOf(Direction.NW, Direction.N, Direction.NE), Direction.N),
Proposal(setOf(Direction.SW, Direction.S, Direction.SE), Direction.S),
Proposal(setOf(Direction.NW, Direction.W, Direction.SW), Direction.W),
Proposal(setOf(Direction.NE, Direction.E, Direction.SE), Direction.E),
)
private data class Grove(val elves: Set<Pt>) {
val minX: Int
get() = elves.minOf { it.x }
val maxX: Int
get() = elves.maxOf { it.x }
val minY: Int
get() = elves.minOf { it.y }
val maxY: Int
get() = elves.maxOf { it.y }
val groundCount: Int
get() = (minX..maxX).flatMap { x ->
(minY..maxY).map { y -> if (elves.contains(Pt(x, y))) 0 else 1 }
}.sum()
fun advance(proposals: List<Proposal>): Grove {
val moves = elves.mapNotNull { elf ->
if (neighbourCount(elf, Direction.allDirections) > 0) {
proposals.firstNotNullOfOrNull { proposal ->
if (neighbourCount(elf, proposal.checks) == 0) {
PossibleMove(elf, elf.move(proposal.result))
} else null
}
} else null
}.fold(mutableMapOf<Pt, MutableList<PossibleMove>>()) { m, move ->
m.getOrPut(move.destination) { mutableListOf() }.add(move)
m
}.filterValues { moves ->
moves.size == 1
}.values.associate { moves ->
moves.first().elf to moves.first().destination
}
return Grove(elves.map { elf -> moves[elf] ?: elf }.toSet())
}
private fun neighbourCount(pt: Pt, directions: Set<Direction>): Int = directions.count { direction ->
elves.contains(pt.move(direction))
}
private data class PossibleMove(val elf: Pt, val destination: Pt)
}
private fun proposalSequence(): Sequence<List<Proposal>> = generateSequence(initialProposals) { proposals ->
proposals.drop(1) + proposals.first()
}
private fun groveSequence(initialGrove: Grove): Sequence<Grove> = sequence {
var grove = initialGrove
for (proposals in proposalSequence()) {
yield(grove)
val nextGrove = grove.advance(proposals)
if (nextGrove == grove) {
break
}
grove = nextGrove
}
}
private fun String.toGrove(): Grove = Grove(lineSequence().withIndex().flatMap { (y, row) ->
row.withIndex().mapNotNull { (x, c) -> if (c == '#') Pt(x, y) else null }
}.toSet())
}
| 0 | Kotlin | 0 | 0 | 7ead7db6491d6fba2479cd604f684f0f8c1e450f | 3,602 | adventofcode2022 | MIT License |
2023/11/solve-2.kts | gugod | 48,180,404 | false | {"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595} | import java.io.File
import kotlin.math.abs
class Cosmos (
val observation: List<String>,
val expansionFactor: Long,
) {
private fun String.allIndicesOf(c: Char) = indices.filter { this[it] == c }
val observedEmptyRows : List<Int> = observation.indices
.filter { j -> observation[j].all { it == '.' } }
val observedEmptyCols : List<Int> = observation[0].indices
.filter { i -> observation.indices.all { j -> observation[j][i] == '.' } }
val observedGalaxies : List<Pair<Int,Int>> =
observation.flatMapIndexed { j, line ->
line.allIndicesOf('#').map { Pair(j,it) }
}
val galaxies : List<Pair<Long,Long>> = observedGalaxies.map { (y,x) ->
val dy = (expansionFactor - 1) * observedEmptyRows.filter { it < y }.count()
val dx = (expansionFactor - 1) * observedEmptyCols.filter { it < x }.count()
Pair(y + dy, x + dx)
}
fun sumOfPairwiseGalaticManhattonDistances() : Long {
return galaxies.indices.map { i ->
(i..galaxies.lastIndex).map { j ->
abs(galaxies[i].first - galaxies[j].first) + abs(galaxies[i].second - galaxies[j].second)
}.sum()
}.sum()
}
}
println(
Cosmos( observation = File("input").readLines().toList(), expansionFactor = 1000000 )
.sumOfPairwiseGalaticManhattonDistances()
.toString()
)
| 0 | Raku | 1 | 5 | ca0555efc60176938a857990b4d95a298e32f48a | 1,389 | advent-of-code | Creative Commons Zero v1.0 Universal |
2022/Day17.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | import java.util.*
fun main() {
val rocks = arrayOf(
arrayOf(
"####"
),
arrayOf(
".#.",
"###",
".#.",
),
arrayOf(
"..#",
"..#",
"###",
).reversed().toTypedArray(),
arrayOf(
"#",
"#",
"#",
"#",
),
arrayOf(
"##",
"##",
)
)
val wind = readInput("Day17").single()
fun solve(): Sequence<Int> {
var time = 0
var maxy = 0
val m = 7
val map = Array(10_000_000) { BooleanArray(m+2) }
for (y in map.indices) {
map[y][0] = true
map[y][m+1] = true
if (y == 0) Arrays.fill(map[y], true)
}
fun fits(x: Int, y: Int, rock: Array<String>): Boolean {
for (y1 in rock.indices) {
for (x1 in rock[y1].indices) {
val x2 = x + x1
val y2 = y + y1
if (rock[y1][x1] == '#' && map[y2][x2]) return false
}
}
return true
}
fun place(x: Int, y: Int, rock: Array<String>) {
for (y1 in rock.indices) {
for (x1 in rock[y1].indices) {
val x2 = x + x1
val y2 = y + y1
if (rock[y1][x1] == '#') {
maxy = maxOf(maxy, y2)
map[y2][x2] = true
}
}
}
}
fun printMap(ySize: Int): String {
val sb = StringBuilder()
for (y in maxy downTo maxOf(0, maxy - ySize)) {
sb.append(map[y].joinToString("") { if (it) "#" else "." }).append('\n')
}
return sb.toString()
}
fun dropRock(r: Int) {
val rock = rocks[r % rocks.size]
var x = 3
var y = maxy + 4
while (true) {
val xw = when (wind[time % wind.length]) {
'>' -> x + 1
'<' -> x - 1
else -> error("")
}
time++
if (fits(xw, y, rock)) {
x = xw
}
if (!fits(x, y-1, rock)) {
place(x, y, rock)
break
} else {
y--
}
}
}
return sequence {
var r = 0
while (true) {
dropRock(r++)
yield(maxy)
}
}
}
println(solve().drop(2021).first())
val heights = solve().take(1_000_000).toList()
val startCycle = 100_000
val cycLen = (10*rocks.size until heights.size).find { cycLen ->
(0 until cycLen).all {
(1..100).all { k ->
heights[startCycle + it+1] - heights[startCycle + it] == heights[startCycle + k*cycLen + it+1] - heights[startCycle + k*cycLen + it]
}
}
}!!
println(cycLen)
val cycHeight = heights[startCycle + cycLen] - heights[startCycle]
var rounds = 1000000000000L - startCycle
val t = rounds / cycLen
var res2 = heights[startCycle] + t * cycHeight
rounds -= t*cycLen
res2 += heights[startCycle + rounds.toInt()] - heights[startCycle]
println(res2-1)
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 3,447 | advent-of-code-kotlin | Apache License 2.0 |
kata/src/main/kotlin/kata/ColorChoice.kt | gualtierotesta | 129,613,223 | false | null | package kata
import java.math.BigInteger
/*
You know combinations: for example, if you take 5 cards from a 52 cards deck you have 2,598,960
different combinations.
In mathematics the number of x combinations you can take from a set of n elements is called the
binomial coefficient of n and x, or more often n choose x.
The formula to compute m = n choose x is: m = n! / (x! * (n - x)!) where ! is the factorial operator.
You are a renowned poster designer and painter.
You are asked to provide 6 posters all having the same design each in 2 colors.
Posters must all have a different color combination and you have the choice of 4 colors:
red, blue, yellow, green.
How many colors can you choose for each poster?
The answer is two since 4 choose 2 = 6.
The combinations will be: {red, blue}, {red, yellow}, {red, green}, {blue, yellow}, {blue, green}, {yellow, green}.
Now same question but you have 35 posters to provide and 7 colors available.
How many colors for each poster?
If you take combinations 7 choose 2 you will get 21 with the above formula.
But 21 schemes aren't enough for 35 posters.
If you take 7 choose 5 combinations you will get 21 too.
Fortunately if you take 7 choose 3 or 7 choose 4 combinations you get 35 and so each poster
will have a different combination of 3 colors or 5 colors.
You will take 3 colors because it's less expensive.
Hence the problem is:
knowing m (number of posters to design),
knowing n (total number of available colors),
let us search x (number of colors for each poster so that each poster has a unique combination of
colors and the number of combinations is exactly the same as the number of posters).
In other words we must find x such as n choose x = m (1) for a given m and a given n; m >= 0 and n > 0.
If many x are solutions give as result the smallest x.
It can happen that when m is given at random there are no x satisfying equation (1) then return -1.
Examples:
checkchoose(6, 4) --> 2
checkchoose(4, 4) --> 1
checkchoose(4, 2) --> -1
checkchoose(35, 7) --> 3
checkchoose(36, 7) --> -1
a = 47129212243960
checkchoose(a, 50) --> 20
checkchoose(a + 1, 50) --> -1
clojure: Use big integers in the calculation of n choose k!
*/
fun fact(num: Int): BigInteger {
var factorial: BigInteger = BigInteger.ONE
for (i in 1..num) {
factorial = factorial.multiply(BigInteger.valueOf(i.toLong()))
}
return factorial
}
fun nChooseX(n: Int, x: Int): BigInteger {
// m = n! / (x! * (n - x)!)
return fact(n).div(fact(x).multiply(fact(n - x)))
}
fun checkchoose(m: Long, n: Int): Long {
for (x in 1..n) {
val mCurrent = nChooseX(n, x)
if (mCurrent.longValueExact() == m) {
return x.toLong()
}
}
return -1
} | 0 | Kotlin | 0 | 0 | 8366bb3aed765fff7fb5203abce9a20177529a8e | 2,741 | PlayWithKotlin | Apache License 2.0 |
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day07/Day07.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2022.day07
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun treeWriter(tree: MutableMap<String, Any>, key: String, values: MutableMap<String, Any>, separator: Char = '/'): MutableMap<String, Any> {
if (key == "/") return values
val keyList = key.split(separator).filter { it.isNotEmpty() }
var currentSubTree = tree
keyList.dropLast(1).forEach { keyFragment ->
currentSubTree = currentSubTree[keyFragment] as MutableMap<String, Any>
}
currentSubTree[keyList.last()] = values
return tree
}
fun part1(input: String): Long {
var pwd = ""
var dirTree = emptyMap<String, Any>().toMutableMap()
input
.split("$")
.filter { it.isNotEmpty() }
.map { line ->
line
.lines()
.filter { it.isNotEmpty() }
.map { it.trim() }
}.forEach { command ->
if (command.first().startsWith("cd ")) {
val path = command.first().removePrefix("cd ")
pwd = when (path) {
".." -> {
pwd
.split("/")
.filter { it.isNotEmpty() }
.dropLast(1)
.joinToString("/", "/", "/")
.replace("//", "/")
}
"/" -> {
"/"
}
else -> {
"$pwd$path/"
}
}
} else {
val output = command.drop(1)
val values = emptyMap<String, Any>().toMutableMap()
output.forEach { item ->
val (first, last) = item.split(" ")
if (first == "dir") {
values[last] = emptyMap<String, Any>().toMutableMap()
} else {
values[last] = first
}
}
dirTree = treeWriter(dirTree, pwd, values)
}
}
val sizedTree = calculateSize(dirTree)
val sizeLimit = 100000L
return filterSubtreesBySize(sizedTree, sizeLimit).sumOf { it["_sum"] as Long }
}
fun part2(input: String): Long {
val totalSpace = 70000000L
val requiredFree = 30000000L
var pwd = ""
var dirTree = emptyMap<String, Any>().toMutableMap()
input
.split("$")
.filter { it.isNotEmpty() }
.map { line ->
line
.lines()
.filter { it.isNotEmpty() }
.map { it.trim() }
}.forEach { command ->
if (command.first().startsWith("cd ")) {
val path = command.first().removePrefix("cd ")
pwd = when (path) {
".." -> {
pwd
.split("/")
.filter { it.isNotEmpty() }
.dropLast(1)
.joinToString("/", "/", "/")
.replace("//", "/")
}
"/" -> {
"/"
}
else -> {
"$pwd$path/"
}
}
} else {
val output = command.drop(1)
val values = emptyMap<String, Any>().toMutableMap()
output.forEach { item ->
val (first, last) = item.split(" ")
if (first == "dir") {
values[last] = emptyMap<String, Any>().toMutableMap()
} else {
values[last] = first
}
}
dirTree = treeWriter(dirTree, pwd, values)
}
}
val sizedTree = calculateSize(dirTree)
val freeSpace = totalSpace.minus(sizedTree["_sum"] as Long)
val minimumSpaceToDelete = requiredFree.minus(freeSpace)
return filterSubtreesBySize(sizedTree, minimumSpaceToDelete, false).minOf { it["_sum"] as Long }
}
// test if implementation meets criteria from the description, like:
val testInput = Input.getInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = Input.getInput("Day07")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
private fun filterSubtreesBySize(tree: MutableMap<String, Any>, sizeLimit: Long, filterSmaller: Boolean = true): List<MutableMap<String, Any>> {
var subtrees = emptyList<MutableMap<String, Any>>().toMutableList()
tree.forEach { (_, value) ->
if (value is MutableMap<*, *>) {
subtrees = subtrees.plus(filterSubtreesBySize(value as MutableMap<String, Any>, sizeLimit, filterSmaller)).toMutableList()
}
}
if (filterSmaller && tree["_sum"] as Long <= sizeLimit) subtrees.add(tree)
if (!filterSmaller && tree["_sum"] as Long >= sizeLimit) subtrees.add(tree)
return subtrees
}
private fun calculateSize(tree: MutableMap<String, Any>): MutableMap<String, Any> {
var sum = 0L
tree.forEach { (_, value) ->
sum = if (value is MutableMap<*, *>) {
val subtree = calculateSize(value as MutableMap<String, Any>)
sum.plus(subtree["_sum"].toString().toLong())
} else {
value.toString().toLong().plus(sum)
}
}
tree["_sum"] = sum
return tree
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 6,127 | AOC | Apache License 2.0 |
src/main/kotlin/day20/day20.kt | corneil | 572,437,852 | false | {"Kotlin": 93311, "Shell": 595} | package day20
import main.utils.measureAndPrint
import main.utils.scanInt
import utils.checkNumber
import utils.readFile
import utils.readLines
import utils.separator
import java.util.*
fun main() {
val test = readLines(
"""1
2
-3
3
-2
0
4"""
)
val lines = readFile("day20")
class EncryptedFile(val input: List<Int>) {
private fun mix(number: Pair<Long, Int>, mixed: MutableList<Pair<Long, Int>>) {
if (number.first != 0L) {
val index = mixed.indexOf(number)
check(index >= 0)
mixed.remove(number)
Collections.rotate(mixed, ((-1L * number.first) % mixed.size.toLong()).toInt())
mixed.add(index, number)
}
}
fun numbersAfterZeroMixed(rounds: List<Int>, mixCount: Int, encryptionKey: Long): List<Long> {
val zeroInputIndex = input.indexOf(0)
val indexedList = input.mapIndexed { index, value -> encryptionKey * value.toLong() to index }.toList()
val mixedFile = indexedList.toMutableList()
check(indexedList.size == input.size)
check(mixedFile.size == input.size)
repeat(mixCount) { count ->
indexedList.forEach { number ->
mix(number, mixedFile)
}
check(mixedFile.size == input.size) { "Sizes differ for mixed ${mixedFile.size} and input ${input.size} after $count" }
}
return rounds.map { round ->
val zeroIndex = mixedFile.indexOf(0L to zeroInputIndex)
check(zeroIndex >= 0) { "Expected zeroIndex >=0 not $zeroIndex" }
val end = (zeroIndex + (round % input.size)) % input.size
mixedFile[end].first
}
}
}
fun calcSolution(input: List<String>, mixCount: Int = 1, encryptionKey: Long = 1, print: Boolean = true): Long {
val file = input.map { it.scanInt() }
val encrypted = EncryptedFile(file)
val values = encrypted.numbersAfterZeroMixed(listOf(1000, 2000, 3000), mixCount, encryptionKey)
if (print) {
println("Values=${values.joinToString(", ")}")
}
return values.sum()
}
fun part1() {
println("Warmup.")
repeat(1000) { calcSolution(test, 1, 1, false) }
println("Start.")
val testResult = measureAndPrint("Part 1 Test Time: ") {
calcSolution(test)
}
println("Part 1 Test Answer = $testResult")
checkNumber(testResult, 3L)
val result = measureAndPrint("Part 1 Time: ") {
calcSolution(lines)
}
println("Part 1 Answer = $result")
checkNumber(result, 4426L)
}
fun part2() {
val encryptionKey = 811589153L
val testResult = measureAndPrint("Part 2 Test Time: ") {
calcSolution(test, 10, encryptionKey)
}
println("Part 2 Test Answer = $testResult")
checkNumber(testResult, 1623178306L)
val result = measureAndPrint("Part 2 Time: ") {
calcSolution(lines, 10, encryptionKey)
}
println("Part 2 Answer = $result")
}
println("Day - 20")
part1()
separator()
part2()
}
| 0 | Kotlin | 0 | 0 | dd79aed1ecc65654cdaa9bc419d44043aee244b2 | 2,918 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2021/Day20.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 20 - Trench Map
* Problem Description: http://adventofcode.com/2021/day/20
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day20/
*/
package com.ginsberg.advent2021
class Day20(input: List<String>) {
private val algorithmString: String = input.first().map { if (it == '#') '1' else '0' }.joinToString("")
private val startingImage: List<String> = parseInput(input)
fun solvePart1(): Int =
solve(2)
fun solvePart2(): Int =
solve(50)
private fun solve(rounds: Int): Int =
(1 .. rounds).fold(startingImage to '0') { (image, defaultValue), _ ->
image.nextRound(defaultValue) to if (defaultValue == '0') algorithmString.first() else algorithmString.last()
}.first.sumOf { it.count { char -> char == '1' } }
private fun List<String>.nextRound(defaultValue: Char): List<String> =
(-1..this.size).map { y ->
(-1..this.first().length).map { x ->
algorithmString[
Point2d(x, y)
.surrounding()
.map { this.valueAt(it, defaultValue) }
.joinToString("")
.toInt(2)
]
}.joinToString("")
}
private fun List<String>.valueAt(pixel: Point2d, defaultValue: Char): Char =
if (pixel in this) this[pixel.y][pixel.x] else defaultValue
private operator fun List<String>.contains(pixel: Point2d): Boolean =
pixel.y in this.indices && pixel.x in this.first().indices
private fun Point2d.surrounding(): List<Point2d> =
listOf(
Point2d(x - 1, y - 1), Point2d(x, y - 1), Point2d(x + 1, y - 1),
Point2d(x - 1, y), this, Point2d(x + 1, y),
Point2d(x - 1, y + 1), Point2d(x, y + 1), Point2d(x + 1, y + 1),
)
private fun parseInput(input: List<String>): List<String> =
input.drop(2).map { row ->
row.map { char ->
if (char == '#') 1 else 0
}.joinToString("")
}
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 2,145 | advent-2021-kotlin | Apache License 2.0 |
src/Day23.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | data class Elf(var currentCoord: Coord2D, var nextCoord: Coord2D? = null)
operator fun Coord2D.plus(other: Coord2D) = Coord2D(x + other.x, y + other.y)
fun makeStrat(dirs: List<Int>, outDir: Int) = fun(cur: Coord2D, existing: Set<Coord2D>) =
if (dirs.all { it.toDirection() + cur !in existing }) cur + outDir.toDirection() else null
fun Int.toDirection() = when (this) {
in (0..8) -> Coord2D(
x = this % 3 - 1, y = this / 3 - 1
)
else -> throw IllegalArgumentException("invalid number for converting to direction")
}
val zeroStrats = listOf(
makeStrat(
(0 until 9).toList(
) - 4, 4
)
)
val strats = listOf(
makeStrat(listOf(0, 1, 2), 1),
makeStrat(listOf(6, 7, 8), 7),
makeStrat(listOf(0, 3, 6), 3),
makeStrat(listOf(2, 5, 8), 5),
)
val fallbackStrats = listOf(
makeStrat(listOf(), 4)
)
fun <T> List<T>.shifted(offset: Int) = (0 until size).map { this[(offset + it).mod(size)] }.toList()
fun Elf.proposeMove(strats: List<(Coord2D, Set<Coord2D>) -> Coord2D?>, existing: Set<Coord2D>) {
nextCoord = strats.asSequence().map { strat -> strat(currentCoord, existing) }.first { it != null }
}
fun stratForRound(roundNo: Int) = zeroStrats + strats.shifted(roundNo) + fallbackStrats
fun <T> List<T>.counts() = buildMap<T, Int> {
this@counts.forEach {
this[it] = this.getOrPut(it) { 0 } + 1
}
}
fun move(elfs: List<Elf>, roundNo: Int): Boolean {
val coords = elfs.map { it.currentCoord }.toSet()
val strats = stratForRound(roundNo)
elfs.forEach { it.proposeMove(strats, coords) }
val permittedMoves = elfs.map { it.nextCoord!! }.counts().filter { (_, v) -> v == 1 }.keys
var hasMoved = false
elfs.forEach {
if (it.nextCoord!! in permittedMoves) {
if (it.nextCoord != it.currentCoord) hasMoved = true
it.currentCoord = it.nextCoord!!
it.nextCoord = null
}
}
return hasMoved
}
fun main() {
fun part1(input: List<String>): Int {
val elves = buildList {
input.forEachIndexed { i, row ->
row.forEachIndexed { j, ch ->
if (ch == '#') add(Elf(Coord2D(y = i, x = j)))
}
}
}
repeat(10) {
move(elves, it.toInt())
}
val w = elves.maxOf { it.currentCoord.x } - elves.minOf { it.currentCoord.x } + 1
val h = elves.maxOf { it.currentCoord.y } - elves.minOf { it.currentCoord.y } + 1
return w * h - elves.size
}
fun part2(input: List<String>): Int {
val elves = buildList {
input.forEachIndexed { i, row ->
row.forEachIndexed { j, ch ->
if (ch == '#') add(Elf(Coord2D(y = i, x = j)))
}
}
}
var moved = false
var i = 0
do {
moved = move(elves, i)
i++
} while (moved)
return i
}
val testInput = readInput("Day23_test")
println(part1(testInput))
check(part1(testInput) == 110)
println(part2(testInput))
check(part2(testInput) == 20)
val input = readInput("Day23")
println("Part 1")
println(part1(input))
println("Part 2")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 3,269 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day08.kt | thelmstedt | 572,818,960 | false | {"Kotlin": 30245} | import java.io.File
fun main() {
fun rays(
grid: List<List<Int>>,
x: Int,
y: Int,
excludeSelf: Boolean = true,
): List<List<Pair<Int, Int>>> {
val height = grid.size
val width = grid.first().size
val d = if (excludeSelf) 1 else 0
val up = (y - d downTo 0).map { x to it }
val down = (y + d until height).map { x to it }
val right = (x + d until width).map { it to y }
val left = (x - d downTo 0).map { it to y }
return listOf(up, left, down, right)
}
fun intGrid(text: String): List<List<Int>> = text.lineSequence()
.map { row -> row.map { it.digitToInt() } }
.toList()
fun part1(file: File) {
val grid = intGrid(file.readText())
var visible = 0
grid.forEachIndexed { y, row ->
row.forEachIndexed { x, tree ->
if (rays(grid, x, y).any { it.all { (x, y) -> grid[y][x] < tree } }) {
visible += 1
}
}
}
println(visible)
}
fun rayScore(
grid: List<List<Int>>,
tree: Int,
ray: List<Pair<Int, Int>>,
): Int {
var score = 0
ray.forEach { (x, y) ->
score += 1
if (grid[y][x] >= tree) return score
}
return score
}
fun part2(file: File) {
val grid = intGrid(file.readText())
val score = grid.flatMapIndexed { y, row ->
row.mapIndexed { x, tree ->
rays(grid, x, y)
.map { rayScore(grid, tree, it) }
.reduce { acc, i -> acc * i }
}
}.max()
println(score)
}
part1(File("src", "Day08_test.txt"))
part1(File("src", "Day08.txt"))
part2(File("src", "Day08_test.txt"))
part2(File("src", "Day08.txt"))
}
| 0 | Kotlin | 0 | 0 | e98cd2054c1fe5891494d8a042cf5504014078d3 | 1,878 | advent2022 | Apache License 2.0 |
src/day5/Day05.kt | dean95 | 571,923,107 | false | {"Kotlin": 21240} | package day5
import readInput
private fun main() {
fun part1(input: List<String>): String {
val crates = input.takeWhile { it.contains(']') }
val cratesToStack = mutableListOf<Pair<Char, Int>>()
crates.forEach {
for (i in 1..it.lastIndex step 4) {
if (it[i].isLetter()) cratesToStack.add(it[i] to (i / 4))
}
}
val numberOfStacks = cratesToStack.maxOf(Pair<Char, Int>::second).inc()
val stacks = List(numberOfStacks) { ArrayDeque<Char>() }
cratesToStack.forEach { (crate, stackIndex) ->
stacks[stackIndex].addFirst(crate)
}
val commands = input
.dropWhile { it.firstOrNull()?.isLetter()?.not() ?: true }
.map { command ->
val (numOfCrates, originStackIndex, destinationStackIndex) = command
.split(' ')
.filter { it.toIntOrNull() != null }
.map(String::toInt)
Command(numOfCrates, originStackIndex.dec(), destinationStackIndex.dec())
}
commands.forEach { command ->
val (numOfCrates, originStackIndex, destinationStackIndex) = command
repeat(numOfCrates) {
val crate = stacks[originStackIndex].removeLast()
stacks[destinationStackIndex].add(crate)
}
}
val topCrates = StringBuilder()
stacks.forEach {
topCrates.append(it.last())
}
return topCrates.toString()
}
fun part2(input: List<String>): String {
val crates = input.takeWhile { it.contains(']') }
val cratesToStack = mutableListOf<Pair<Char, Int>>()
crates.forEach {
for (i in 1..it.lastIndex step 4) {
if (it[i].isLetter()) cratesToStack.add(it[i] to (i / 4))
}
}
val numberOfStacks = cratesToStack.maxOf(Pair<Char, Int>::second).inc()
val stacks = List(numberOfStacks) { ArrayDeque<Char>() }
cratesToStack.forEach { (crate, stackIndex) ->
stacks[stackIndex].addFirst(crate)
}
val commands = input
.dropWhile { it.firstOrNull()?.isLetter()?.not() ?: true }
.map { command ->
val (numOfCrates, originStackIndex, destinationStackIndex) = command
.split(' ')
.filter { it.toIntOrNull() != null }
.map(String::toInt)
Command(numOfCrates, originStackIndex.dec(), destinationStackIndex.dec())
}
commands.forEach { command ->
val (numOfCrates, originStackIndex, destinationStackIndex) = command
val stacksToRemove = stacks[originStackIndex].takeLast(numOfCrates)
repeat(numOfCrates) { stacks[originStackIndex].removeLast() }
stacks[destinationStackIndex].addAll(stacksToRemove)
}
val topCrates = StringBuilder()
stacks.forEach {
topCrates.append(it.last())
}
return topCrates.toString()
}
val testInput = readInput("day5/Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("day5/Day05")
println(part1(input))
println(part2(input))
}
private data class Command(
val numOfCrates: Int,
val originStackIndex: Int,
val destinationStackIndex: Int
) | 0 | Kotlin | 0 | 0 | 0ddf1bdaf9bcbb45116c70d7328b606c2a75e5a5 | 3,450 | advent-of-code-2022 | Apache License 2.0 |
day14/src/main/kotlin/App.kt | ascheja | 317,918,055 | false | null | package net.sinceat.aoc2020.day14
import kotlin.properties.Delegates
fun main() {
println(part1InstructionProcessor(readInstructions("testinput.txt")))
println(part1InstructionProcessor(readInstructions("input.txt")))
println(part2InstructionProcessor(readInstructions("testinput2.txt")))
println(part2InstructionProcessor(readInstructions("input.txt")))
}
fun part1InstructionProcessor(instructions: List<Instruction>): Long {
var currentMask: Mask by Delegates.notNull()
val memory = mutableMapOf<Long, Long>()
for (instruction in instructions) {
when (instruction) {
is SetMask -> currentMask = instruction.mask
is WriteMemory -> memory[instruction.address] = currentMask.apply(instruction.value)
}
}
return memory.values.sum()
}
fun part2InstructionProcessor(instructions: List<Instruction>): Long {
var currentMask: Mask by Delegates.notNull()
val memory = mutableMapOf<Long, Long>()
for (instruction in instructions) {
when (instruction) {
is SetMask -> currentMask = instruction.mask
is WriteMemory -> {
val addresses = currentMask.addressMasks(instruction.address)
addresses.forEach { address ->
memory[address] = instruction.value
}
}
}
}
return memory.values.sum()
}
class Mask(private val value: String) {
private val orMask: Long = value.replace('X', '0').toLong(2)
private val andMask: Long = value.replace('X', '1').toLong(2)
fun apply(value: Long): Long {
return value and andMask or orMask
}
fun addressMasks(address: Long): List<Long> {
return maskAddress(address.toString(2).padStart(36, '0'), value).map { it.toLong(2) }.toList()
}
companion object {
private fun maskAddress(address: String, mask: String): Sequence<String> {
if (mask.isEmpty() || address.length != mask.length) {
return emptySequence()
}
val maskHead = mask.first()
val addressHead = address.first()
val maskTail = mask.substring(1 until mask.length)
val addressTail = address.substring(1 until address.length)
if (maskTail.isEmpty()) {
return sequence {
when (maskHead) {
'0' -> yield("$addressHead")
'1' -> yield("1")
'X' -> {
yield("0")
yield("1")
}
}
}
}
return sequence {
when (maskHead) {
'0' -> yieldAll(maskAddress(addressTail, maskTail).map { "$addressHead$it" })
'1' -> yieldAll(maskAddress(addressTail, maskTail).map { "1$it" })
'X' -> {
val tails = maskAddress(addressTail, maskTail).toList()
yieldAll(tails.map { "0$it" })
yieldAll(tails.map { "1$it" })
}
}
}
}
}
}
sealed class Instruction
data class SetMask(val mask: Mask) : Instruction()
data class WriteMemory(val address: Long, val value: Long) : Instruction()
fun readInstructions(fileName: String): List<Instruction> {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
lines.filter(String::isNotBlank).map { line -> line.split("=").map(String::trim) }.map { (left, right) ->
if (left == "mask") {
return@map SetMask(Mask(right))
}
WriteMemory(left.removePrefix("mem[").removeSuffix("]").toLong(), right.toLong())
}.toList()
}
}
| 0 | Kotlin | 0 | 0 | f115063875d4d79da32cbdd44ff688f9b418d25e | 3,844 | aoc2020 | MIT License |
src/test/kotlin/be/brammeerten/y2022/Day13Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2022
import be.brammeerten.readFile
import be.brammeerten.readFileSplitted
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import kotlin.math.min
class Day13Test {
@Test
fun `part 1a`() {
val pairs = readPairs("2022/day13/exampleInput.txt")
Assertions.assertEquals(13, solve(pairs))
}
@Test
fun `part 1b`() {
val packets = readFile("2022/day13/input.txt")
.filter { it.isNotEmpty() }
.map { parseList(it) }
.toMutableList()
packets.add(parseList("[[2]]"))
packets.add(parseList("[[6]]"))
val sorted = sortPackets(packets)
val result = sorted.mapIndexed{i, v ->
if (v.isList && v.list.size == 1 && v.list[0].isList && v.list[0].list.size == 1 && v.list[0].list[0].isNumber && v.list[0].list[0].getVal() == 6)
i+1
else if (v.isList && v.list.size == 1 && v.list[0].isList && v.list[0].list.size == 1 && v.list[0].list[0].isNumber && v.list[0].list[0].getVal() == 2)
i+1
else
0
}.filter { it != 0 }
Assertions.assertEquals(140, result[0] * result[1])
}
private fun sortPackets(packets: MutableList<ValueOrList>): List<ValueOrList> {
return packets.sortedWith(object : Comparator<ValueOrList> {
override fun compare(o1: ValueOrList?, o2: ValueOrList?): Int {
val r = isCorrect(o1!!, o2!!)
if (r == true) return -1
else if (r == false) return 1
else return 0
}
})
}
fun readPairs(file: String): List<Pair<ValueOrList, ValueOrList>> {
return readFileSplitted(file, "\n\n")
.map { (p1, p2) -> parseList(p1) to parseList(p2) }
}
fun solve(pairs: List<Pair<ValueOrList, ValueOrList>>): Int {
val results: List<Int> = pairs.mapIndexed { i, p ->
if (isCorrect(p.first, p.second) == true) i + 1 else 0
}
return results.sum()
}
fun isCorrect(left: ValueOrList, right: ValueOrList): Boolean? {
if (left.isNumber && right.isNumber) {
if (left.getVal() < right.getVal()) return true
else if (left.getVal() > right.getVal()) return false
else return null
} else if (left.isList && right.isList) {
for (i in 0 until Math.max(left.list.size, right.list.size)) {
if (i == left.list.size && i != right.list.size) return true
if (i != left.list.size && i == right.list.size) return false
if (i == left.list.size && i == right.list.size) continue
val res = isCorrect(left.list[i], right.list[i])
if (res == false) return false
if (res == true) return true
}
return null
} else if (left.isList) {
val rightList = ValueOrList(true, right.parent)
rightList.addItem(right.getVal())
return isCorrect(left, rightList)
} else {
val leftList = ValueOrList(true, left.parent)
leftList.addItem(left.getVal())
return isCorrect(leftList, right)
}
}
fun parseList(list: String): ValueOrList {
var toParse = list.drop(1)
var curr = ValueOrList(true)
while (toParse.length > 1) {
// read next token
var token: String
if (toParse[0] == '[') token = "["
else if (toParse[0] == ']') token = "]"
else if (toParse[0] == ',') token = ","
else {
val end = min(if (toParse.indexOf(",") < 0) Int.MAX_VALUE else toParse.indexOf(","), if (toParse.indexOf("]") < 0) Int.MAX_VALUE else toParse.indexOf("]"))
if (end == Int.MAX_VALUE) throw IllegalStateException("No end character found: $toParse")
token = toParse.substring(0, end)
}
toParse = toParse.drop(token.length)
// parse token
if (token == "[") {
val new = ValueOrList(true, curr)
curr.addItem(new)
curr = new
} else if (token == "]") {
curr = curr.parent!!
} else if (token != ",") {
curr.addItem(token.toInt())
}
}
return curr
}
}
class ValueOrList(val isList: Boolean, val parent: ValueOrList? = null, val value: Int? = null) {
val list = mutableListOf<ValueOrList>()
val isNumber = !isList
fun addItem(v: ValueOrList) {
if (!isList) throw IllegalStateException("Not a list")
list.add(v)
}
fun addItem(v: Int) {
if (!isList) throw IllegalStateException("Not a list")
list.add(ValueOrList(false, this, v))
}
fun getVal(): Int {
if (isList) throw IllegalStateException("is a list")
return value!!
}
}
| 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 4,982 | Advent-of-Code | MIT License |
src/Day04.kt | nguyendanv | 573,066,311 | false | {"Kotlin": 18026} | fun main() {
fun part1(input: List<String>): Int {
return input
.filter { pair ->
val numbers = pair.split(",", "-").map { it.toInt() }
val first = (numbers[0]..numbers[1]).toSet()
val second = (numbers[2]..numbers[3]).toSet()
first.containsAll(second) || second.containsAll(first)
}
.size
}
fun part2(input: List<String>): Int {
return input
.filter { pair ->
val numbers = pair.split(",", "-").map { it.toInt() }
val first = (numbers[0]..numbers[1]).toSet()
val second = (numbers[2]..numbers[3]).toSet()
first.intersect(second).isNotEmpty()
}
.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput)==2)
check(part2(testInput)==4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 376512583af723b4035b170db1fa890eb32f2f0f | 1,056 | advent2022 | Apache License 2.0 |
2020/src/main/kotlin/Day1.kt | osipxd | 388,214,845 | false | null | /**
* # Day 1: Report Repair
*
* The Elves in accounting just need you to fix your **expense report** (your puzzle input); apparently,
* something isn't quite adding up. Specifically, they need you to find the two entries that sum to 2020
* and then multiply those two numbers together.
*
* For example, suppose your expense report contained the following:
* ```
* 1721
* 979
* 366
* 299
* 675
* 1456
* ```
*
* In this list, the two entries that sum to `2020` are `1721` and `299`. Multiplying them together produces
* `1721 * 299 = 514579`, so the correct answer is `514579`.
*
* Of course, your expense report is much larger. **Find the two entries that sum to 2020; what do you get
* if you multiply them together?**
*
* --- Part Two ---
*
* The Elves in accounting are thankful for your help; one of them even offers you a starfish coin they had
* left over from a past vacation. They offer you a second one if you can find **three** numbers in your
* expense report that meet the same criteria.
*
* Using the above example again, the three entries that sum to `2020` are `979`, `366`, and `675`. Multiplying
* them together produces the answer, `241861950`.
*
* In your expense report, **what is the product of the three entries that sum to `2020`?**
*
* *[Open in browser](https://adventofcode.com/2020/day/1)*
*/
object Day1 {
// Complexity: O(n^2)
fun part1Naive(expenseReport: List<Int>): Int {
for (a in expenseReport) {
for (b in expenseReport) {
if (a + b == 2020) {
return (a * b).also { println("$a * $b = $it") }
}
}
}
error("What? There no answer?")
}
// Complexity: O(n)
fun part1Optimized(expenseReport: List<Int>): Int {
val (a, b) = expenseReport.findPairForSum(2020) ?: error("Impossible.")
return (a * b).also { println("$a * $b = $it") }
}
// Complexity: O(n^3)
fun part2Naive(expenseReport: List<Int>): Int {
for (a in expenseReport) {
for (b in expenseReport) {
for (c in expenseReport) {
if (a + b + c == 2020) {
return (a * b * c).also { println("$a * $b * $c = $it") }
}
}
}
}
error("What? There no answer?")
}
// Complexity: O(n^2)
fun part2Optimized(expenseReport: List<Int>): Int {
for (a in expenseReport) {
val (b, c) = expenseReport.findPairForSum(2020 - a) ?: continue
return (a * b * c).also { println("$a * $b * $c = $it") }
}
error("What? There no answer?")
}
private fun List<Int>.findPairForSum(sum: Int): Pair<Int, Int>? {
val pairs = associateBy { sum - it }
val first = find { it in pairs } ?: return null
return first to pairs.getValue(first)
}
}
| 0 | Kotlin | 0 | 0 | 66553923d8d221bcd1bd108f701fceb41f4d1cbf | 2,922 | advent-of-code | MIT License |
advanced-algorithms/kotlin/src/bO2CMax.kt | nothingelsematters | 135,926,684 | false | {"Jupyter Notebook": 7400788, "Java": 512017, "C++": 378834, "Haskell": 261217, "Kotlin": 251383, "CSS": 45551, "Vue": 37772, "Rust": 34636, "HTML": 22859, "Yacc": 14912, "PLpgSQL": 10573, "JavaScript": 9741, "Makefile": 8222, "TeX": 7166, "FreeMarker": 6855, "Python": 6708, "OCaml": 5977, "Nix": 5059, "ANTLR": 4802, "Logos": 3516, "Perl": 2330, "Mustache": 1527, "Shell": 1105, "MATLAB": 763, "M": 406, "Batchfile": 399} | import java.io.File
import java.util.Scanner
fun scheduleO2CMax(p1: List<Long>, p2: List<Long>): Pair<Long, List<List<Long>>> {
fun fill(schedule: MutableList<Long>, times: List<Long>, indices: Sequence<Int>, init: Long = 0) =
indices.fold(init) { sum, index ->
schedule[index] = sum
sum + times[index]
}
fun i() = p1.asSequence().withIndex().filter { (index, i) -> i <= p2[index] }.map { it.index }
fun j() = p1.asSequence().withIndex().filter { (index, i) -> i > p2[index] }.map { it.index }
val x = i().maxByOrNull { p1[it] }
val y = j().maxByOrNull { p2[it] }
return if (x == null || y != null && p1[x] < p2[y]) {
val (cMax, schedule) = scheduleO2CMax(p2, p1)
cMax to listOf(schedule[1], schedule[0])
} else {
val cMax = maxOf(p1.sum(), p2.sum(), p1.asSequence().zip(p2.asSequence()).maxOf { (a, b) -> a + b })
val first = MutableList(p1.size) { 0L }
fill(first, p1, i() - x)
fill(first, p1, sequenceOf(x), cMax - p1[x])
fill(first, p1, j(), cMax - p1[x] - j().sumOf { p1[it] })
val second = MutableList(p2.size) { 0L }
fill(second, p2, sequenceOf(x))
fill(second, p2, i() - x, p2[x])
fill(second, p2, j(), cMax - j().sumOf { p2[it] })
cMax to listOf(first, second)
}
}
fun main() {
val input = Scanner(File("o2cmax.in").bufferedReader())
val n = input.nextInt()
val p1 = List(n) { input.nextLong() }
val p2 = List(n) { input.nextLong() }
val (c, schedule) = scheduleO2CMax(p1, p2)
File("o2cmax.out").printWriter().use { output ->
output.println(c)
schedule.forEach { line ->
line.forEach { output.print("$it ") }
output.println()
}
}
}
| 0 | Jupyter Notebook | 3 | 5 | d442a3d25b579b96c6abda13ed3f7e60d1747b53 | 1,796 | university | Do What The F*ck You Want To Public License |
src/y2023/Day18.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2023
import util.Cardinal
import util.minus
import util.neighborsManhattan
import util.readInput
import util.times
import util.timingStatistics
import util.toLong
object Day18 {
data class DigInstruction(
val direction: Cardinal,
val distance: Long
)
val dirMap = mapOf(
'R' to Cardinal.EAST,
'L' to Cardinal.WEST,
'U' to Cardinal.NORTH,
'D' to Cardinal.SOUTH
)
private fun parse(input: List<String>): List<DigInstruction> {
return input.map { line ->
val (dir, dist, _) = line.split(' ')
DigInstruction(
direction = dirMap[dir.first()]!!,
distance = dist.toLong()
)
}
}
fun part1(input: List<String>): Int {
val parsed = parse(input)
val start = 0 to 0
val edges = mutableListOf(start)
parsed.forEach { digInstruction ->
repeat(digInstruction.distance.toInt()) {
edges.add(
digInstruction.direction.of(edges.last())
)
}
}
val startRow = edges.minOf { it.first } - 1
val endRow = edges.maxOf { it.first } + 1
val startCol = edges.minOf { it.second } - 1
val endCol = edges.maxOf { it.second } + 1
val outsides = mutableSetOf(startRow to startCol)
var frontier = setOf(start)
while (frontier.isNotEmpty()) {
frontier = frontier.flatMap { pos ->
pos.neighborsManhattan()
}.filter {
it.first in startRow..endRow && it.second in startCol..endCol
}.filter {
it !in outsides && it !in edges
}.toSet()
outsides.addAll(frontier)
}
val totalSize = (endRow - startRow + 1) * (endCol - startCol + 1)
return totalSize - outsides.size
}
val dirMap2 = mapOf(
'0' to Cardinal.EAST,
'1' to Cardinal.SOUTH,
'2' to Cardinal.WEST,
'3' to Cardinal.NORTH
)
private fun parse2(input: List<String>): List<DigInstruction> {
return input.map { line ->
val (_, _, color) = line.split(' ')
val dist = color.drop(2).take(5)
DigInstruction(
direction = dirMap2[color[7]]!!,
distance = dist.toLong(16)
)
}
}
fun part2(input: List<String>): Long {
val parsed = parse2(input)
val start = 0L to 0L
val corners = mutableListOf(start)
parsed.forEach { digInstruction ->
corners.add(
// the minus is actually a plus, because of platform declaration clash
(digInstruction.direction.relativePos.toLong() * digInstruction.distance) - corners.last()
)
}
val correctedCorners = (listOf(parsed.last()) + parsed).zipWithNext().zip(corners).map { (digs, pos) ->
if (digs.second.direction == Cardinal.NORTH ||
digs.first.direction == Cardinal.NORTH
) {
pos - (0L to -1L)
} else {
pos
}
}
check(correctedCorners.size == parsed.size)
val cornerColLookup = correctedCorners.groupBy { it.second }
val startCol = correctedCorners.minOf { it.second }
var activeRanges = listOf<LongRange>()
var totalArea = 0L
var lastCol = startCol
cornerColLookup.keys.sorted().forEach { colIdx ->
totalArea += columnArea(activeRanges) * (colIdx - lastCol)
lastCol = colIdx
val cornersInColumn = cornerColLookup[colIdx]?.map { it.first }
if (cornersInColumn != null) {
val activeCorners = activeRanges.flatMap { range ->
listOf(range.first, range.last)
}
val allCorners = (cornersInColumn + activeCorners).sorted()
val duplicates = allCorners.zipWithNext().filter { (first, second) ->
first == second
}.map { it.first }.toSet()
val noDuplicates = allCorners.filter { it !in duplicates }
check(noDuplicates.size % 2 == 0) {
"no duplicates should be even: \n$allCorners\n$duplicates\n$noDuplicates"
}
activeRanges = noDuplicates.chunked(2).map { it.first()..it.last() }
} else {
error("no corners in column by key: $colIdx")
}
}
check(activeRanges.isEmpty()) { "active ranges should be empty: $activeRanges, $totalArea" }
return totalArea
}
private fun columnArea(activeRanges: List<LongRange>) = activeRanges.sumOf { it.last - it.first + 1 }
}
fun main() {
val testInput = """
R 6 (#70c710)
D 5 (#0dc571)
L 2 (#5713f0)
D 2 (#d2c081)
R 2 (#59c680)
D 2 (#411b91)
L 5 (#8ceee2)
U 2 (#caa173)
L 1 (#1b58a2)
U 2 (#caa171)
R 2 (#7807d2)
U 3 (#a77fa3)
L 2 (#015232)
U 2 (#7a21e3)
""".trimIndent().split("\n")
println("------Tests------")
println(Day18.part1(testInput))
println(Day18.part2(testInput))
println("------Real------")
val input = readInput(2023, 18)
println("Part 1 result: ${Day18.part1(input)}")
println("Part 2 result: ${Day18.part2(input)}")
timingStatistics { Day18.part1(input) }
timingStatistics { Day18.part2(input) }
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 5,548 | advent-of-code | Apache License 2.0 |
leetcode/src/offer/middle/Offer14_1.kt | zhangweizhe | 387,808,774 | false | null | package offer.middle
fun main() {
// 剑指 Offer 14- I. 剪绳子
// https://leetcode.cn/problems/jian-sheng-zi-lcof/
for (i in 2..10) {
println("$i -> ${cuttingRope1(i)}")
}
}
private fun cuttingRope(n: Int): Int {
/**
* 如果是剪 1 刀,那么可以剪出的长度是 1、2、3...n-1
* 则剩下的长度是 n-1、n-2、n-3...1
* 一共有 n-1 种剪法
* 即剪下的长度为j,剩下的长度为 n-j
* 剩下的长度 n-j 可以剪,也可以不剪
* 剪:n-j 的最优解是 f(n-j)
* 不剪:n-j 的最优解就是 n-j
* 那么 f(n) = j * max(f(n-j), n-j) j属于[2,n]
* */
val dp = IntArray(n+1)
dp[1] = 1
dp[2] = 1
// 绳子长度从 2 到 n
for (i in 2..n) {
// 剪下一段的长度1 到 i-1
for (j in 1 until i) {
// 剪掉的长度是j,剩下的长度是 i-j
// 那么剩下的 i-j 的最优解就是 1)不剪:i-j;2)剪:dp[i-j];所以取两者的最大值
// 然后乘以 j,就是绳子长度为i,剪下长度为 j 的最优解
val tmp = j * Math.max(dp[i-j], i-j)
// 比较每个 j 的最优解,取最大的那个
dp[i] = Math.max(tmp, dp[i])
}
}
println(dp.contentToString())
return dp[n]
}
fun cuttingRope1(n: Int): Int {
val dp = IntArray(n+1)
dp[2] = 1
for (i in 2..n) {
for (j in 1 until i) {
val tmp = j * Math.max(dp[i-j], i-j)
dp[i] = Math.max(tmp, dp[i])
}
}
return dp[n]
}
fun cuttingRope2(n: Int): Int {
/**
* 绳子长度是 n
* 假设剪一刀,那么剪掉的长度可以是 1、2、3、4...n-1,
* 剩下的长度,就是 n-1, n-2, n-3 ... 1
* 即剪下的长度是j,剩下的长度是 n-j
* 共有 n-1 种剪法
* 定义 f(n) 表示长度为 n 的长度的最优解
* 对于剩下的 n-j,我们可以选择剪,或者不剪,
* 剪:那么剩下的长度 n-j 的最优解是 f(n-j)
* 不剪:那么 n-j 就是最优解
* 则 f(n) = j * Max(f(n-j), n-j)
*/
val dp = IntArray(n+1);
// 绳子长度为2时,最优解是1
dp[2] = 1
// 绳子长度 [2,n]
for (i in 2..n) {
// 剪掉的长度
for (j in 1 until i) {
val tmp = j * Math.max(dp[i-j], i-j);
dp[i] = Math.max(tmp, dp[i]);
}
}
return dp[n];
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,471 | kotlin-study | MIT License |
src/Day03.kt | wgolyakov | 572,463,468 | false | null | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val a = it.substring(0, it.length / 2).toSet()
val b = it.substring(it.length / 2, it.length).toSet()
val c = a.intersect(b).first()
c.code + if (c.isLowerCase()) 1 - 'a'.code else 27 - 'A'.code
}
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3).sumOf { (s1, s2, s3) ->
val c = s1.toSet().intersect(s2.toSet()).intersect(s3.toSet()).first()
c.code + if (c.isLowerCase()) 1 - 'a'.code else 27 - 'A'.code
}
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 715 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day09.kt | joostbaas | 573,096,671 | false | {"Kotlin": 45397} | import Direction.*
import kotlin.math.abs
enum class Direction {
UP, DOWN, RIGHT, LEFT
}
fun String.toDirection() =
when (this) {
"R" -> RIGHT
"U" -> UP
"L" -> LEFT
"D" -> DOWN
else -> throw IllegalArgumentException()
}
fun List<String>.parseRopeMoves() =
flatMap { line ->
val (direction, count) = line.split(' ')
List(count.toInt()) { direction.toDirection() }
}
data class Point(val x: Int, val y: Int) {
fun move(direction: Direction) =
when (direction) {
UP -> this.copy(y = y + 1)
DOWN -> this.copy(y = y - 1)
RIGHT -> this.copy(x = x + 1)
LEFT -> this.copy(x = x - 1)
}
private fun avg(n1: Int, n2: Int) = (n1 + n2) / 2
private fun x(x: Int) = copy(x = x)
private fun y(y: Int) = copy(y = y)
fun moveTowards(other: Point) =
when (Pair(abs(other.x - this.x), abs(other.y - this.y))) {
Pair(2, 1) -> other.x(avg(x, other.x))
Pair(1, 2) -> other.y(avg(y, other.y))
Pair(0, 2) -> other.y(avg(y, other.y))
Pair(2, 0) -> other.x(avg(x, other.x))
Pair(2, 2) -> other.x(avg(x, other.x)).y(avg(y, other.y))
else -> this
}
}
data class Situation(val points: List<Point>, val tailVisited: Set<Point> = emptySet()) {
fun move(direction: Direction): Situation =
points.fold(emptyList<Point>()) { acc, oldPoint ->
if (acc.isEmpty()) listOf(oldPoint.move(direction))
else acc + oldPoint.moveTowards(acc.last())
}.let { newPoints ->
Situation(
newPoints,
tailVisited = tailVisited + newPoints.last(),
)
}
}
fun List<Direction>.countTailPositions(tailCount: Int): Int =
fold(
initial = Situation(List(tailCount) { Point(0, 0) })
) { situation, direction ->
situation.move(direction)
}.tailVisited.size
fun day09Part1(input: List<String>): Int = input.parseRopeMoves().countTailPositions(2)
fun day09Part2(input: List<String>): Int = input.parseRopeMoves().countTailPositions(10) | 0 | Kotlin | 0 | 0 | 8d4e3c87f6f2e34002b6dbc89c377f5a0860f571 | 2,164 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/13.kts | reitzig | 318,492,753 | false | null | import java.io.File
data class BusLine(val frequency: Long, val contestOffset: Long) {
val id: Long = frequency
fun nextDepartureAfter(timestamp: Long): Long =
((timestamp / frequency) * frequency).let {
if (it < timestamp) {
it + frequency
} else {
it
}
}
fun normalized(): BusLine =
copy(contestOffset = contestOffset % frequency)
}
val input = File(args[0]).readLines()
val earliestDeparture = input[0].toLong()
val busLines = input[1]
.split(",")
.mapIndexed { index, it ->
BusLine(it.toLongOrNull() ?: -1, index.toLong())
}
.filterNot { it.frequency == -1L }
// Part 1:
println(
busLines
.map { Pair(it, it.nextDepartureAfter(earliestDeparture)) }
.minByOrNull { it.second }
?.let { it.first.id * (it.second - earliestDeparture) }
)
// Part 2:
// Attempt 1: too slow
// val candidates = generateSequence(0L) { it + busLines[0].frequency }
// Attempt 2:
//val candidates = busLines
// .maxByOrNull { it.frequency }
// ?.let { leastFrequentLine ->
// generateSequence(leastFrequentLine.frequency - leastFrequentLine.contestOffset) {
// it + leastFrequentLine.frequency
// }
// }!!
//println(
// candidates
// .first { timestamp ->
// if (timestamp < 0) throw IllegalStateException("overflow")
// busLines.all { busLine ->
// (timestamp + busLine.contestOffset) % busLine.frequency == 0L
// }
// }
//)
//
// Nope, not gonna work.
//
// We note that
// - we're looking for time t s.t. t == frequency - offset (modulo frequency)
// for all bus lines, and
// - the frequencies are co-prime (since they are prime)
// Thus, we can apply the Chinese remainder theorem and use sieving as
// described here:
// https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Search_by_sieving
val maxFrequencyLine = busLines.maxByOrNull { it.frequency }!!
busLines
.map { it.normalized() }
.sortedByDescending { it.frequency }
.drop(1) // smallest solution for only the first bus line becomes seed of fold
.fold(
Pair(
maxFrequencyLine.frequency - maxFrequencyLine.contestOffset,
maxFrequencyLine.frequency
)
) { baseAndProduct, line -> // (xi, n1*...*ni
generateSequence(baseAndProduct.first) { it + baseAndProduct.second } // xi + k * n1 * ... * ni
.first { candidate -> (candidate + line.contestOffset) % line.frequency == 0L }
.let { Pair(it, baseAndProduct.second * line.frequency) }
// --> first component is smallest solution for first i bus lines
}
.let { println(it.first) }
| 0 | Kotlin | 0 | 0 | f17184fe55dfe06ac8897c2ecfe329a1efbf6a09 | 2,749 | advent-of-code-2020 | The Unlicense |
src/main/kotlin/day18/solution.kt | bukajsytlos | 433,979,778 | false | {"Kotlin": 63913} | package day18
import java.io.File
fun main() {
val lines = File("src/main/kotlin/day18/input.txt").readLines()
val snailFishNumbers = lines.map { parseSnailFish(it) }
println(snailFishNumbers.reduce { acc, snailFishNumber -> acc.copy() + snailFishNumber.copy() }.magnitude())
var highestMagnitude = 0
for (number1 in snailFishNumbers) {
for (number2 in snailFishNumbers) {
val magnitude1 = (number1.copy() + number2.copy()).magnitude()
if (magnitude1 > highestMagnitude) highestMagnitude = magnitude1
val magnitude2 = (number2.copy() + number1.copy()).magnitude()
if (magnitude2 > highestMagnitude) highestMagnitude = magnitude2
}
}
println(highestMagnitude)
}
fun parseSnailFish(value: String): SnailFishNumber {
if (!value.startsWith('[')) return Regular(value.toInt())
val inside = value.removeSurrounding("[", "]")
var nestLevel = 0
val index = inside.indexOfFirst {
if (it == '[') nestLevel++
else if (it == ']') nestLevel--
else if (it == ',' && nestLevel == 0) return@indexOfFirst true
false
}
return Pair(parseSnailFish(inside.substring(0, index)), parseSnailFish(inside.substring(index + 1)))
.also {
it.childsParent(it)
}
}
sealed class SnailFishNumber(var parent: Pair? = null) {
operator fun plus(other: SnailFishNumber): SnailFishNumber = Pair(this, other).also { it.childsParent(it) }.reduce()
abstract fun print()
abstract fun magnitude(): Int
fun copy(): SnailFishNumber {
return when(this) {
is Pair -> Pair(this.left.copy(), this.right.copy()).also { it.childsParent(it) }
is Regular -> Regular(this.value)
}
}
protected fun reduce(): SnailFishNumber {
while (true) {
// this.print()
// println()
val exploding = findExploding()
if (exploding != null) {
exploding.explode()
continue
}
val splitting = findSplitting()
if (splitting != null) {
splitting.split()
continue
}
break
}
return this
}
private fun findExploding(nestLevel: Int = 0): Pair? {
if (this is Pair) {
if (nestLevel == 4) return this
return this.left.findExploding( nestLevel + 1) ?: this.right.findExploding(nestLevel + 1)
}
return null
}
private fun findSplitting(): Regular? {
return when (this) {
is Regular -> if (this.value >= 10) this else null
is Pair -> this.left.findSplitting() ?: this.right.findSplitting()
}
}
}
class Regular(var value: Int, parent: Pair? = null) : SnailFishNumber(parent) {
override fun magnitude(): Int = value
override fun print() {
print(value)
}
fun add(addition: Int) {
value += addition
}
fun split() {
val newValue = Pair(Regular(value / 2), Regular(value / 2 + value % 2), parent)
.also {
it.childsParent(it)
}
if (parent != null) {
if (parent!!.left == this) {
parent!!.left = newValue
} else {
parent!!.right = newValue
}
}
}
}
class Pair(var left: SnailFishNumber, var right: SnailFishNumber, parent: Pair? = null) : SnailFishNumber(parent) {
override fun magnitude(): Int = 3 * left.magnitude() + 2 * right.magnitude()
override fun print() {
print("[");left.print();print(",");right.print();print("]")
}
fun explode() {
findClosestLeftRegular()?.add((left as Regular).value)
findClosestRightRegular()?.add((right as Regular).value)
if (parent != null) {
val newValue = Regular(0, parent)
if (parent!!.left == this) {
parent!!.left = newValue
} else {
parent!!.right = newValue
}
}
}
private fun findClosestLeftRegular(): Regular? {
return if (parent != null) {
if (parent!!.left == this) {
parent!!.findClosestLeftRegular()
} else {
when (parent!!.left) {
is Regular -> parent!!.left as Regular
is Pair -> {
return (parent!!.left as Pair).findRightMostChild()
}
}
}
} else {
null
}
}
private fun findRightMostChild(): Regular = when (this.right) {
is Regular -> this.right as Regular
else -> (this.right as Pair).findRightMostChild()
}
private fun findClosestRightRegular(): Regular? {
return if (parent != null) {
if (parent!!.right == this) {
parent!!.findClosestRightRegular()
} else {
when (parent!!.right) {
is Regular -> parent!!.right as Regular
is Pair -> {
return (parent!!.right as Pair).findLeftMostChild()
}
}
}
} else {
null
}
}
private fun findLeftMostChild(): Regular = when (this.left) {
is Regular -> this.left as Regular
else -> (this.left as Pair).findLeftMostChild()
}
fun childsParent(parent: Pair?) {
left.parent = parent
right.parent = parent
}
}
| 0 | Kotlin | 0 | 0 | f47d092399c3e395381406b7a0048c0795d332b9 | 5,577 | aoc-2021 | MIT License |
gcj/y2019/round3/a.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2019.round3
import java.util.TreeSet
private const val M = 1_000_000_000_000L
private const val S = 10_000_000_000L
private fun play() {
val ranges = mutableSetOf(1..M)
fun makeMove(p: Long) {
val removed = ranges.first { p in it }
ranges.remove(removed)
val added = listOf(removed.first until p, p + S..removed.last)
ranges.addAll(added.filter { it.size() >= S })
}
while (true) {
val p = readLong()
if (p < 0) { return }
makeMove(p)
val xor = ranges.map(::getGrundy).fold(0, Int::xor)
val q = if (xor == 0) ranges.first().first else {
val range = ranges.first { getGrundy(it) xor xor < getGrundy(it) }
val wantedValue = getGrundy(range) xor xor
range.first + possibleMoves.first {
getGrundy(it) xor getGrundy(range.size() - S - it) == wantedValue
}
}
println(q)
makeMove(q)
}
}
private val grundy = grundy()
private val possibleMoves = grundy.keys.flatMap { listOf(it.first, it.last).distinct() }
private fun getGrundy(x: Long) : Int = grundy.entries.first { x in it.key }.value
private fun getGrundy(range: LongRange) : Int = getGrundy(range.size())
private fun grundy(): Map<LongRange, Int> {
data class Event(val x: Long, val value: Int, val delta: Int) : Comparable<Event> {
override fun compareTo(other: Event): Int =
compareValuesBy(this, other, { it.x }, { System.identityHashCode(it) })
}
val events = TreeSet<Event>()
val ranges = mutableMapOf((0 until S) to 0)
val reachable = mutableMapOf<Int, Int>().withDefault { 0 }
while (true) {
val (rangeA, valueA) = ranges.entries.maxByOrNull { it.key.first }!!
for ((rangeB, valueB) in ranges) {
val valueC = valueA xor valueB
events.add(Event(rangeA.first + rangeB.first + S, valueC, +1))
events.add(Event(rangeA.last + rangeB.last + 1 + S, valueC, -1))
}
val low = rangeA.last + 1
if (low > M) { break }
while (events.first().x <= low) {
val event = events.pollFirst()
@Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
reachable[event.value] = reachable.getValue(event.value) + event.delta
}
val high = minOf(events.first().x, low + S)
val value = (0..reachable.size).first { reachable.getValue(it) == 0 }
if (valueA == value) {
ranges.remove(rangeA)
ranges[rangeA.first until high] = value
} else {
ranges[low until high] = value
}
}
return ranges
}
fun main() {
repeat(readInts()[0]) { play() }
}
private fun LongRange.size(): Long = this.last - this.first + 1
private fun readLn() = readLine()!!
private fun readLong() = readLn().toLong()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,657 | competitions | The Unlicense |
Problems/Algorithms/1091. Shortest Path in Binary Matrix/ShortestPathBinaryMatrix.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun shortestPathBinaryMatrix(grid: Array<IntArray>): Int {
val n = grid.size
val m = grid[0].size
if (n == 1 && m == 1) {
if (grid[0][0] == 0) return 1
return -1
}
if (grid[0][0] == 1 || grid[n-1][m-1] == 1) return -1
val neighbors: Array<IntArray> = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(1, 1), intArrayOf(1, -1), intArrayOf(-1, 1), intArrayOf(-1, -1))
val visited = Array(n) { BooleanArray(m) { false } }
val queue = ArrayDeque<Pair<Int, Int>>()
queue.add(Pair(0, 0))
visited[0][0] = true
var ans = 1
while (!queue.isEmpty()) {
for (i in 1..queue.size) {
val curr = queue.removeFirst()
val r = curr.first
val c = curr.second
for (neighbor in neighbors) {
val x = r + neighbor[0]
val y = c + neighbor[1]
if (isValid(n, m, x, y) && !visited[x][y] && grid[x][y] == 0) {
if (x == n-1 && y == m-1) return ans + 1
queue.add(Pair(x, y))
visited[x][y] = true
}
}
}
ans++
}
return -1
}
private fun isValid(n: Int, m: Int, r: Int, c: Int): Boolean {
return r >= 0 && r < n && c >= 0 && c < m
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,582 | leet-code | MIT License |
src/Day03.kt | alfr1903 | 573,468,312 | false | {"Kotlin": 9628} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { commonCompartmentLetter(it).toPriority() }
}
fun part2(input: List<String>): Any {
return input.chunked(3).sumOf { commonBadgeLetter(it).toPriority() }
}
val input = readInputAsList("Day03Input")
println(part1(input))
println(part2(input))
}
private fun commonCompartmentLetter(listEntry: String): Char {
val firstHalf: String = listEntry.take(listEntry.length / 2)
val secondHalf: String = listEntry.takeLast(listEntry.length / 2)
return firstHalf.find { secondHalf.contains(it) }!!
}
private fun commonBadgeLetter(group: List<String>): Char =
group[0].filter { group[1].contains(it) }.find { group[2].contains(it) }!!
private fun Char.toPriority(): Int = if (this.isLowerCase()) this.code - 96 else this.code - 38
| 0 | Kotlin | 0 | 0 | c1d1fbf030ac82c643fa5aea4d9f7c302051c38c | 854 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | tsschmidt | 572,649,729 | false | {"Kotlin": 24089} |
fun main() {
fun parseDequed(input: List<String>): List<ArrayDeque<Char>> {
val numStacks = input[0].length / 3
val stacks = mutableListOf<ArrayDeque<Char>>()
repeat(numStacks) { stacks.add(ArrayDeque()) }
input.takeWhile { it.contains('[') }.forEach {
it.chunked(4).forEachIndexed { index, s ->
if (s.isNotBlank()) {
stacks[index].addFirst(s[1])
}
}
}
return stacks
}
fun part1(input: List<String>): String {
val (s, m) = input.chunkBy { it.isEmpty() }
val stacks = parseDequed(s)
m.forEach {
val moves = it.split(" ")
val amt = moves[1].toInt()
val from = moves[3].toInt() - 1
val to = moves[5].toInt() - 1
repeat(amt) { stacks[to].addLast(stacks[from].removeLast()) }
}
return stacks.map { if (it.isNotEmpty()) it.removeLast() else "" }.joinToString("")
}
fun part2(input: List<String>): String {
val (s, m) = input.chunkBy { it.isEmpty() }
val stacks = parseDequed(s)
m.forEach {
val moves = it.split(" ")
val amt = moves[1].toInt()
val from = moves[3].toInt() - 1
val to = moves[5].toInt() - 1
val temp = ArrayDeque<Char>()
repeat(amt) { temp.addLast(stacks[from].removeLast())}
repeat(amt) { stacks[to].addLast(temp.removeLast())}
}
return stacks.map { if (it.isNotEmpty()) it.removeLast() else "" }.joinToString("")
}
//val input = readInput("Day05_test")
//check(part1(input) == "CMZ")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7bb637364667d075509c1759858a4611c6fbb0c2 | 1,782 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | stephenkao | 572,205,897 | false | {"Kotlin": 14623} | fun main() {
// indices and scores
val shapeIndices = mapOf(
// rock
"A" to 0,
"X" to 0,
// paper
"B" to 1,
"Y" to 1,
// scissors
"C" to 2,
"Z" to 2
)
fun part1(input: List<String>): Int {
fun getOutcomeScore(opponentChoice: String, myChoice: String): Int {
val opponentIdx = shapeIndices[opponentChoice]!!
val myIdx = shapeIndices[myChoice]!!
// tie: 3 points
if (opponentIdx == myIdx) {
return 3
}
// win: 6 points
if ((opponentIdx + 1) % 3 == (myIdx % 3)) {
return 6
}
// loss: 0 points
return 0
}
var sum = 0
for (line in input) {
val (opponentChoice: String, myChoice: String)= line.split(' ')
val outcomeScore = getOutcomeScore(opponentChoice, myChoice)
val shapeScore = shapeIndices[myChoice]!! + 1
sum += outcomeScore + shapeScore
}
return sum
}
// you dumb elf
// X = should lose
// Y = should draw
// Z = should win
fun part2(input: List<String>): Int {
val outcomeScores = mapOf(
"X" to 0,
"Y" to 3,
"Z" to 6
)
var sum = 0
for (line in input) {
val (opponentChoice: String, intendedOutcome: String) = line.split(' ')
val opponentIdx = shapeIndices[opponentChoice]!!
// need to determine my shape
val shapeScore = when (intendedOutcome) {
// loss
"X" -> (((opponentIdx - 1) + 3) % 3) + 1
// tie
"Y" -> opponentIdx + 1
// win
"Z" -> ((opponentIdx + 1) % 3) + 1
else -> 0 // hmmm should probably enum these instead
}
sum += outcomeScores[intendedOutcome]!! + shapeScore
}
return sum
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | 7a1156f10c1fef475320ca985badb4167f4116f1 | 2,264 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day13.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | import org.json.JSONArray
import org.json.JSONTokener
fun main() {
fun log(message: Any?) {
println(message)
}
fun String.toJSONArray() = JSONTokener(this).nextValue() as JSONArray
fun String.toListViaJSONArray() = this.toJSONArray().toList()
val marker2 = "[[2]]".toListViaJSONArray()
val marker6 = "[[6]]".toListViaJSONArray()
// TODO: read up on Any vs *
// wow this was hard to reason out...
fun List<*>.wtfCompareTo(that: List<*>): Int {
val compare = when {
// check edge cases
this.isNotEmpty() && that.isEmpty() -> return 1
this.isEmpty() && that.isNotEmpty() -> return -1
this.isEmpty() /*&& that.isEmpty()*/ -> return 0
// then check heads
this[0] is Int && that[0] is Int -> (this[0] as Int).compareTo((that[0] as Int)) // int <> int
this[0] is List<*> && that[0] is Int -> (this[0] as List<*>).wtfCompareTo(listOf(that[0])) // list <> int
this[0] is Int && that[0] is List<*> -> listOf(this[0]).wtfCompareTo(that[0] as List<*>) // int <> list
else -> (this[0] as List<*>).wtfCompareTo(that[0] as List<*>) // list <> list
}
if (compare != 0) return compare // we're done, someone won
return this.drop(1).wtfCompareTo(that.drop(1)) // drop heads, keep going
}
fun parse1(input: List<String>): List<Pair<List<Any>, List<Any>>> {
val list = input.windowed(3, 3, partialWindows = true).map {// partial for the last pair
val (left, right, _) = it
// log("parse $left <> $right")
Pair(left.toListViaJSONArray(), right.toListViaJSONArray())
}.toList()
// log(">>>\n$list")
return list
}
fun parse2(input: List<String>): List<List<Any>> {
val list = input.filter { it.isNotEmpty() }.mapIndexed { i, it ->
// log("parse2 ${i + 1} -> $it")
it.toListViaJSONArray()
}.toMutableList().also {
it.add(marker2)
it.add(marker6)
}.toList()
// log(">>>\n$list")
return list
}
fun part1(input: List<String>): Int {
val pairs = parse1(input)
val result: List<Int> = pairs.mapIndexed() { i, p ->
val (left, right) = Pair(p.first, p.second)
val isOrdered = left.wtfCompareTo(right) <= 0
// log("$i -> $left <> $right -> $isOrdered")
when {
isOrdered -> i + 1
else -> 0
}
}.toList()
// log(">>> $result -> ${result.sum()}")
return result.sum()
}
fun part2(input: List<String>): Int {
val lists = parse2(input)
val sorted = lists.sortedWith(List<Any>::wtfCompareTo)
// log(" lists:\n${lists}\nsorted:\n${sorted}")
val position2 = sorted.indexOfFirst { it.wtfCompareTo(marker2) == 0 } + 1
val position6 = sorted.indexOfFirst { it.wtfCompareTo(marker6) == 0 } + 1
return position2 * position6
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test.txt")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13.txt")
println(part1(input))
check(part1(input) == 5659)
println(part2(input))
check(part2(input) == 22110)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 3,387 | aoc2022 | Apache License 2.0 |
src/day4/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day4
import java.io.File
data class Board(val numbers: Map<Int, Pair<Int, Int>>) {
private val rows = numbers.values.maxOf { it.first } + 1
private val cols = numbers.values.maxOf { it.second } + 1
private val matches = mutableListOf<Int>()
private val rowCounts = MutableList(rows) { 0 }
private val colCounts = MutableList(cols) { 0 }
fun play(number: Int): Boolean {
val coords = numbers[number]
if (coords != null) {
matches.add(number)
rowCounts[coords.first] += 1
colCounts[coords.second] += 1
return rowCounts[coords.first] == rows || colCounts[coords.second] == cols
}
return false
}
fun score() = (numbers.keys.sum() - matches.sum()) * matches.last()
}
fun main() {
val parts = File("src/day4/input.txt").readText().split("\n\n")
val numbers = parts[0].split(",").map { it.toInt() }
var boards = parts.subList(1, parts.size).map { it.readBoard() }
val scores = mutableListOf<Int>()
for (number in numbers) {
val newBoards = mutableListOf<Board>()
for (board in boards) {
if (board.play(number)) {
scores += board.score()
} else {
newBoards += board
}
}
boards = newBoards
}
println(scores.first())
println(scores.last())
}
fun String.readBoard() : Board {
val numbers = mutableMapOf<Int, Pair<Int, Int>>()
for ((row, line) in this.lines().withIndex()) {
numbers.putAll(line.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
.mapIndexed { col, number -> number to Pair(row, col) })
}
return Board(numbers)
} | 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 1,744 | advent-of-code-2021 | MIT License |
src/Day02.kt | mikemac42 | 573,071,179 | false | {"Kotlin": 45264} | fun String.sumCharScores(charScores: Map<Char, Int>): Int =
sumOf { charScores[it] ?: 0 }
fun String.sumLineScores(lineScores: Map<String, Int>): Int =
lines().sumOf { lineScores[it] ?: 0 }
/**
* The first column is what your opponent is going to play:
* A for Rock, B for Paper, and C for Scissors
* The second column, you reason, must be what you should play in response:
* X for Rock, Y for Paper, and Z for Scissors
* The score for a single round is the score for the shape you selected:
* 1 for Rock, 2 for Paper, and 3 for Scissors
* plus the score for the outcome of the round:
* 0 if you lost, 3 if the round was a draw, and 6 if you won
*/
fun part1Score(strategyGuide: String): Int {
val shapeScore = strategyGuide.sumCharScores(
mapOf(
'X' to 1,
'Y' to 2,
'Z' to 3
)
)
val outcomeScore = strategyGuide.sumLineScores(
mapOf(
"A X" to 3,
"A Y" to 6,
"B Y" to 3,
"B Z" to 6,
"C Z" to 3,
"C X" to 6
)
)
return shapeScore + outcomeScore
}
/**
* X means lose, Y means draw, and Z means win
*/
fun part2Score(strategyGuide: String): Int {
val shapeScore = strategyGuide.sumLineScores(
mapOf(
"A X" to 3,
"A Y" to 1,
"A Z" to 2,
"B X" to 1,
"B Y" to 2,
"B Z" to 3,
"C X" to 2,
"C Y" to 3,
"C Z" to 1
)
)
val outcomeScore = strategyGuide.sumCharScores(
mapOf(
'Y' to 3,
'Z' to 6
)
)
return shapeScore + outcomeScore
}
| 0 | Kotlin | 1 | 0 | 909b245e4a0a440e1e45b4ecdc719c15f77719ab | 1,519 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | diesieben07 | 572,879,498 | false | {"Kotlin": 44432} | import java.util.BitSet
import kotlin.math.max
private val file = "Day08"
//private val file = "Day08Example"
private fun readInput(): Pair<Int, List<IntArray>> {
val lines = readInput(file)
val gridSize = lines.size
check(lines.all { it.length == gridSize })
val grid = lines.map { it.map { c -> c.digitToInt() }.toIntArray() }
return Pair(gridSize, grid)
}
private fun part1() {
val (gridSize, grid) = readInput()
var visible = BitSet(gridSize * gridSize)
// check each row first left to right then right to left
for (row in 0 until gridSize) {
val rowD = grid[row]
for (colRange in listOf(0 until gridSize, (gridSize - 1 downTo 0))) {
var highestThisRow = -1
for (col in colRange) {
val bitIdx = row * gridSize + col
val value = rowD[col]
if (value > highestThisRow) {
visible.set(bitIdx)
highestThisRow = value
}
}
}
}
// check each col, first top to bottom then bottom to top
cols@for (col in 0 until gridSize) {
rowRanges@for (rowRange in listOf(0 until gridSize, (gridSize - 1 downTo 0))) {
var highestThisCol = -1
for (row in rowRange) {
val bitIdx = row * gridSize + col
val value = grid[row][col]
if (value > highestThisCol) {
visible.set(bitIdx)
highestThisCol = value
}
}
}
}
println(visible.cardinality())
}
private fun part2() {
val (gridSize, grid) = readInput()
var maxScore = 0
for (row in 0 until gridSize) {
for (col in 0 until gridSize) {
var score = 1
for ((rowDir, colDir) in listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))) {
var dirScore = 0
val checkHeight = grid[row][col]
for (i in 1 until Int.MAX_VALUE) {
val checkRow = row + rowDir * i
val checkCol = col + colDir * i
if (checkRow !in 0 until gridSize || checkCol !in 0 until gridSize) break
dirScore++
val checkVal = grid[checkRow][checkCol]
if (checkVal >= checkHeight) {
break
}
}
score *= dirScore
}
maxScore = max(score, maxScore)
}
}
println(maxScore)
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6 | 2,602 | aoc-2022 | Apache License 2.0 |
kotlin/0072-edit-distance.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | /*
* DP Time O(m*n) and space O(m*n)
*/
class Solution {
fun minDistance(word1: String, word2: String): Int {
val cache = Array(word1.length + 1) {
IntArray(word2.length + 1){ Integer.MAX_VALUE }
}
for(j in 0..word2.length)
cache[word1.length][j] = word2.length - j
for(i in 0..word1.length)
cache[i][word2.length] = word1.length - i
for(i in word1.lastIndex downTo 0) {
for(j in word2.lastIndex downTo 0) {
if(word1[i] == word2[j]) {
cache[i][j] = cache[i + 1][j + 1]
}else {
cache[i][j] = 1 + minOf(
cache[i + 1][j],
cache[i][j + 1],
cache[i + 1][j + 1]
)
}
}
}
return cache[0][0]
}
}
/*
* DP Time O(m*n) and optimized space O(n)
*/
class Solution {
fun minDistance(word1: String, word2: String): Int {
val m = word1.length
val n = word2.length
var prev = IntArray(n + 1) { it }
for (i in 1..m) {
val new = IntArray(n + 1)
new[0] = i
for (j in 1..n) {
if (word1[i - 1] == word2[j - 1]) {
new[j] = prev[j - 1]
} else {
new[j] = 1 + minOf(
prev[j],
prev[j - 1],
new[j - 1]
)
}
}
prev = new
}
return prev[n]
}
}
/*
* DFS/Recursion + memoization Time O(m*n) and space O(n*m)
*/
class Solution {
fun minDistance(word1: String, word2: String): Int {
val cache = Array(word1.length + 1) { IntArray(word2.length + 1){ Integer.MAX_VALUE } }
fun dfs(i: Int, j: Int): Int {
if (i == word1.length && j == word2.length) return 0
else if (i == word1.length) return word2.length - j
else if (j == word2.length) return word1.length - i
if (cache[i][j] != Integer.MAX_VALUE) return cache[i][j]
if (word1[i] == word2[j]) {
cache[i][j] = dfs(i + 1, j + 1)
} else {
cache[i][j] = 1 + minOf(
dfs(i + 1, j),
dfs(i, j + 1),
dfs(i + 1, j + 1)
)
}
return cache[i][j]
}
return dfs(0, 0)
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 2,559 | leetcode | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.