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/Day09/Day09.kt | martin3398 | 436,014,815 | false | {"Kotlin": 63436, "Python": 5921} | import java.lang.Integer.MAX_VALUE
import java.util.*
fun main() {
fun preprocess(input: List<String>): List<List<Int>> {
val parsed = input.map { x -> x.map { it.toString().toInt() } }.toMutableList()
val padding = MutableList(input[0].length) { MAX_VALUE }
parsed.add(0, padding)
parsed.add(padding)
fun pad(x: List<Int>): List<Int> {
val l = x.toMutableList()
l.add(0, Int.MAX_VALUE)
l.add(Int.MAX_VALUE)
return l
}
return parsed.map { pad(it) }
}
fun part1(input: List<List<Int>>): Int {
var res = 0
for (x in 1..input.size - 2) {
for (y in 1..input[x].size - 2) {
if (input[x][y] < input[x + 1][y]
&& input[x][y] < input[x - 1][y]
&& input[x][y] < input[x][y + 1]
&& input[x][y] < input[x][y - 1]
) {
res += 1 + input[x][y]
}
}
}
return res
}
fun part2(input: List<List<Int>>): Int {
val inputWc = input.toMutableList().map { it.toMutableList() }
val sizes = MutableList(0) { 0 }
for (x in 1..inputWc.size - 2) {
for (y in 1..inputWc[x].size - 2) {
if (inputWc[x][y] < 9) {
var size = 0
val queue = LinkedList(listOf(Pair(x, y)))
while (!queue.isEmpty()) {
val next = queue.pop()
if (inputWc[next.first][next.second] < 9) {
inputWc[next.first][next.second] = 9
size++
queue.add(Pair(next.first + 1, next.second))
queue.add(Pair(next.first - 1, next.second))
queue.add(Pair(next.first, next.second + 1))
queue.add(Pair(next.first, next.second - 1))
}
}
sizes.add(size)
}
}
}
sizes.sort()
sizes.reverse()
return sizes[0] * sizes[1] * sizes[2]
}
val testInput = preprocess(readInput(9, true))
val input = preprocess(readInput(9))
check(part1(testInput) == 15)
println(part1(input))
check(part2(testInput) == 1134)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 085b1f2995e13233ade9cbde9cd506cafe64e1b5 | 2,434 | advent-of-code-2021 | Apache License 2.0 |
advent2022/src/main/kotlin/year2022/Day14.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2022
import AdventDay
class Day14 : AdventDay(2022, 14) {
private val startPoint = 500 to 0
data class Area(
val blockedByRock: Set<Pair<Int, Int>>,
val blockedBySand: Set<Pair<Int, Int>> = emptySet()
) {
companion object {
private fun allBetween(a: Pair<Int, Int>, b: Pair<Int, Int>): Collection<Pair<Int, Int>> = when {
a.first <= b.first && a.second <= b.second -> (a.first..b.first).flatMap {
(a.second..b.second).map { d -> it to d }
}
a.first > b.first && a.second <= b.second -> (b.first..a.first).flatMap {
(a.second..b.second).map { d -> it to d }
}
a.first <= b.first && a.second > b.second -> (a.first..b.first).flatMap {
(b.second..a.second).map { d -> it to d }
}
else -> (b.first..a.first).flatMap {
(b.second..a.second).map { d -> it to d }
}
}
fun of(input: List<String>): Area {
val rocks = input.fold(mutableSetOf<Pair<Int, Int>>()) { acc, cur ->
cur.split(" -> ").map {
val (a, b) = it.split(",")
a.toInt() to b.toInt()
}.windowed(2).forEach { (a, b) ->
acc.addAll(allBetween(a, b))
}
acc
}
return Area(rocks)
}
}
val lowestRow: Int
get() = listOf(
blockedByRock.maxOfOrNull { (_, a) -> a },
blockedBySand.maxOfOrNull { (_, a) -> a },
).mapNotNull { it }.max()
private fun isEmpty(point: Pair<Int, Int>): Boolean =
point !in blockedByRock && point !in blockedBySand
private tailrec fun sandFallsFrom(point: Pair<Int, Int>): Pair<Int, Int>? {
if (point.second > lowestRow) {
return null
}
if (isEmpty(point.first to point.second + 1)) {
return sandFallsFrom(point.first to point.second + 1)
}
if (isEmpty(point.first - 1 to point.second + 1)) {
return sandFallsFrom(point.first - 1 to point.second + 1)
}
if (isEmpty(point.first + 1 to point.second + 1)) {
return sandFallsFrom(point.first + 1 to point.second + 1)
}
return point
}
fun simulateSandFall(point: Pair<Int, Int>): Area {
val newSand = sandFallsFrom(point) ?: return this
return copy(blockedBySand = blockedBySand + newSand)
}
}
override fun part1(input: List<String>): Int {
var area = Area.of(input)
while (true) {
val next = area.simulateSandFall(startPoint)
if (next == area) return area.blockedBySand.size
area = next
}
}
override fun part2(input: List<String>): Int {
var area = Area.of(input)
val leftX = area.blockedByRock.minOf { (a) -> a }
val rightX = area.blockedByRock.maxOf { (a) -> a }
val lowest = area.lowestRow
val additional = (leftX - lowest..rightX + lowest).map { x -> x to lowest + 2 }
area = area.copy(blockedByRock = area.blockedByRock + additional)
while (true) {
val next = area.simulateSandFall(startPoint)
if (next == area) return area.blockedBySand.size
area = next
}
}
}
fun main() = Day14().run()
| 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 3,622 | advent-of-code | Apache License 2.0 |
src/Day21.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} | sealed interface Expression {
data class Add(val left: Expression, val right: Expression) : Expression
data class Mul(val left: Expression, val right: Expression) : Expression
data class Divide(val left: Expression, val right: Expression) : Expression
data class Sub(val left: Expression, val right: Expression) : Expression
data class Value(val value: Long) : Expression
data class Monkey(val monkey: String) : Expression
}
fun main() {
fun part1(input: List<String>): Long {
val expressions = input.associate { line ->
val monkey = line.substringBefore(": ")
val expression = line.substringAfter(": ").split(' ')
monkey to when {
expression.size == 1 -> {
Expression.Value(expression[0].toLong())
}
expression[1] == "+" -> {
Expression.Add(Expression.Monkey(expression[0]), Expression.Monkey(expression[2]))
}
expression[1] == "-" -> {
Expression.Sub(Expression.Monkey(expression[0]), Expression.Monkey(expression[2]))
}
expression[1] == "*" -> {
Expression.Mul(Expression.Monkey(expression[0]), Expression.Monkey(expression[2]))
}
expression[1] == "/" -> {
Expression.Divide(Expression.Monkey(expression[0]), Expression.Monkey(expression[2]))
}
else -> {
throw IllegalStateException()
}
}
}
fun calculate(expression: Expression): Long = when (expression) {
is Expression.Add -> calculate(expression.left) + calculate(expression.right)
is Expression.Divide -> calculate(expression.left) / calculate(expression.right)
is Expression.Monkey -> calculate(expressions.getValue(expression.monkey))
is Expression.Mul -> calculate(expression.left) * calculate(expression.right)
is Expression.Sub -> calculate(expression.left) - calculate(expression.right)
is Expression.Value -> expression.value
}
val result = calculate(expressions.getValue("root"))
return result
}
fun part2(input: List<String>): Long {
return 0
}
// test if implementation meets criteria from the description, like:
val testInputExample = readInput("Day21_example")
check(part1(testInputExample) == 152L)
check(part2(testInputExample) == 0L)
val testInput = readInput("Day21_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 2,667 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2019/SetAndForget.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2019
import komu.adventofcode.utils.Direction
import komu.adventofcode.utils.Point
fun setAndForget1(input: String): Int {
val map = createAsciiMap(input)
fun get(x: Int, y: Int): Char? =
map.getOrNull(y)?.getOrNull(x)
var sum = 0
for ((y, line) in map.withIndex())
for ((x, c) in line.withIndex())
if (c == '#' && get(x - 1, y) == '#' && get(x + 1, y) == '#' && get(x, y - 1) == '#' && get(x, y + 1) == '#')
sum += x*y
return sum
}
fun verifySolution(input: String, program: String): Boolean {
val map = createAsciiMap(input)
val y = map.indexOfFirst { '^' in it }
val x = map[y].indexOf('^')
var direction = Direction.UP
var point = Point(x, y)
val visited = mutableSetOf(point)
for (cmd in program.split(',')) {
when (cmd) {
"L" -> direction = direction.left
"R" -> direction = direction.right
else -> {
repeat(cmd.toInt()) {
point = point.towards(direction, 1)
if (map[point.y][point.x] !in "^#")
error("invalid point: $point")
visited += point
}
}
}
}
val scaffoldBlocks = map.sumBy { line -> line.count { it in "^#" } }
return scaffoldBlocks == visited.size
}
private fun createAsciiMap(input: String): List<String> {
val machine = IntCodeMachine(input)
val buffer = StringBuilder()
machine.writeOutput = { c -> buffer.append(c.toChar()) }
machine.run()
return buffer.toString().lines()
}
fun setAndForget2(input: String): Int {
val machine = IntCodeMachine(input)
machine.memory[0] = 2
machine.writeLine("A,A,B,C,B,C,B,C,C,A")
machine.writeLine("R,8,L,4,R,4,R,10,R,8")
machine.writeLine("L,12,L,12,R,8,R,8")
machine.writeLine("R,10,R,4,R,4")
machine.writeLine("n")
machine.run()
return machine.outputToList().last().toInt()
}
fun isValidCompressedSolution(main: String, a: String, b: String, c: String, program: String): Boolean =
main.length <= 20 && a.length <= 20 && b.length <= 20 && c.length <= 20
&& decompress(main, a, b, c) == program
private fun decompress(main: String, a: String, b: String, c: String): String {
val commands = mutableListOf<String>()
for (call in main.split(',')) {
val subroutine = when (call) {
"A" -> a
"B" -> b
"C" -> c
else -> error("invalid call $call")
}
commands += subroutine.split(',')
}
return commands.joinToString(",")
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 2,658 | advent-of-code | MIT License |
src/Day01.kt | cornz | 572,867,092 | false | {"Kotlin": 35639} | fun main() {
fun getBiggestKcal(input: List<String>): ArrayList<Int> {
val summedUpValues = arrayListOf<Int>()
var summedUpValue = 0
for (it in input) {
when (it) {
"" -> {
summedUpValues.add(summedUpValue)
summedUpValue = 0
}
input[input.lastIndex] -> {
summedUpValue += it.toInt()
summedUpValues.add(summedUpValue)
}
else -> {
summedUpValue += it.toInt()
}
}
}
return summedUpValues
}
fun getBiggestKcalMax(input: ArrayList<Int>): Int {
return input.max()
}
fun getBiggestKcalSumUpTopThree(input: ArrayList<Int>): Int {
val sorted = input.sortedDescending()
return sorted[0]+sorted[1]+sorted[2]
}
fun part1(input: List<String>): Int {
return getBiggestKcalMax(getBiggestKcal(input))
}
fun part2(input: List<String>): Int {
return getBiggestKcalSumUpTopThree(getBiggestKcal(input))
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("input/Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("input/Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2800416ddccabc45ba8940fbff998ec777168551 | 1,430 | aoc2022 | Apache License 2.0 |
2023/src/main/kotlin/day24.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.SegmentD
import utils.Solution
import utils.Vec2d
import utils.Vec4d
import utils.Vec4l
import utils.cut
import utils.eq
import utils.map
import utils.minus
import utils.pairs
import utils.parseItems
import utils.plus
import utils.times
import utils.z3
fun main() {
Day24.run()
}
object Day24 : Solution<List<Day24.Ball>>() {
override val name = "day24"
override val parser = Parser.lines.parseItems { parseBall(it) }
private fun parseBall(line: String): Ball {
val (pos, vel) = line.cut(" @ ").map {
val (x, y, z) = it.split(", ").map { it.toLong() }
Vec4l(x, y, z, 0)
}
return Ball(pos, vel.copy(w = 1))
}
data class Ball(
val position: Vec4l,
val velocity: Vec4l,
)
fun intersect1(a: Ball, b: Ball, start: Vec2d, end: Vec2d): Boolean {
// check whether x-y intersects
val al = SegmentD(
Vec2d(a.position.x.toDouble(), a.position.y.toDouble()),
Vec2d((a.position + a.velocity).x.toDouble(), (a.position + a.velocity).y.toDouble())
)
val bl = SegmentD(
Vec2d(b.position.x.toDouble(), b.position.y.toDouble()),
Vec2d((b.position + b.velocity).x.toDouble(), (b.position + b.velocity).y.toDouble())
)
// intersection?
// ay = a[0] + ax * ad
// by = b[0] + bx * bd
// ay = by = x
// ax = bx = y
// y = a[0] + x * ad
// y = b[0] + x * bd
// b[0] + x * bd = a[0] + x * ad
// x * bd - x * ad = a[0] - b[0]
// x * (bd - ad) = a[0] - b[0]
// x = (a[0] - b[0]) / (bd - ad)
val x = (al[0.0].y - bl[0.0].y) / (bl.slope - al.slope)
val y = al[x].y
if (x !in start.x .. end.x || y !in start.y .. end.y) {
return false
}
// time?
// x = a.position.x + a.velocity.x * at
// at = (x - a.position.x) / a.velocity.x
val at = (x - a.position.x) / a.velocity.x
val bt = (x - b.position.x) / b.velocity.x
return (at > 0.0 && bt > 0.0)
}
override fun part1(): Int {
val isTest = input.size < 10
val (start, end) = if (isTest) {
Vec2d(7.0, 7.0) to Vec2d(27.0, 27.0)
} else {
Vec2d(200000000000000.0, 200000000000000.0) to Vec2d(400000000000000.0, 400000000000000.0)
}
return input.pairs.count { (a, b) -> intersect1(a, b, start, end) }
}
override fun part2(): Long {
// we need for our throw
// time?
// pos?
// velocity?
// x_t / xvel_t
// x = x_t + dt * xvel_t <-- solve for t_x / t_xvel
// x = x_1 + dt * xvel_1
// x = ...
// x = x_n + dt * xvel_n
// x_i, xvel_i = known
// x1 = x_t + dt1 * xvel_t
// x1 = x_1 + dt1 * xvel_1
// x2 = x_t + dt2 * xvel_t
// x2 = x_2 + dt2 * xvel_2
// x3 = x_t + dt3 * xvel_t
// x3 = x_3 + dt3 * xvel_3
// x_t + dt1 * xvel_t = x_1 + dt1 * xvel_1
// x_t - x_1 = dt1 * xvel_1 - dt1 * xvel_t
// x_t, y_t, z_t, xvel_t, yvel_t, zvel_t, dt1, dt2, dt3
// x_t - dt_i * xvel_i + dt_i * xvel_t = x_i
// y_t - dt_i * yvel_i + dt_i * yvel_t = y_i
// z_t - dt_i * zvel_i + dt_i * zvel_t = z_i
// x_t - x_i = dt_i * (xvel_i - xvel_t)
// dt_i * (xvel_i - xvel_t) = x_t - x_i
// dt_i = (x_t - x_i) / (xvel_i - xvel_t)
// dt1 = (x_t - x_1) / (xvel_1 - xvel_t)
// dt1 = (y_t - y_1) / (yvel_1 - yvel_t)
// dt1 = (z_t - z_1) / (zvel_1 - zvel_t)
// val dt = listOf("g", "h", "i", "j", "k", "l")
// x_t - x_1 = dt1 * (xvel_1 - xvel_t)
// y_t - y_1 = dt1 * (yvel_1 - yvel_t)
// z_t - z_1 = dt1 * (zvel_1 - zvel_t)
// x_t - x_2 = dt2 * (xvel_2 - xvel_t)
// y_t - y_2 = dt2 * (yvel_2 - yvel_t)
// z_t - z_2 = dt2 * (zvel_2 - zvel_t)
// x_t - x_3 = dt3 * (xvel_3 - xvel_t)
// y_t - y_3 = dt3 * (yvel_3 - yvel_t)
// z_t - z_3 = dt3 * (zvel_3 - zvel_t)
return z3 {
val x_t = int("x_t")
val y_t = int("y_t")
val z_t = int("z_t")
val xvel_t = int("xvel_t")
val yvel_t = int("yvel_t")
val zvel_t = int("zvel_t")
val dt1 = int("dt1")
val dt2 = int("dt2")
val dt3 = int("dt3")
val dt = listOf(dt1, dt2, dt3)
val eqs = input.take(3).flatMapIndexed { idx, ball ->
listOf(
(x_t - ball.position.x) eq (dt[idx] * (ball.velocity.x - xvel_t)),
(y_t - ball.position.y) eq (dt[idx] * (ball.velocity.y - yvel_t)),
(z_t - ball.position.z) eq (dt[idx] * (ball.velocity.z - zvel_t)),
)
}
solve(eqs)
eval(x_t + y_t + z_t).toLong()
}
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 4,479 | aoc_kotlin | MIT License |
src/Day02.kt | ostersc | 572,991,552 | false | {"Kotlin": 46059} | fun main() {
//A for Rock, B for Paper, and C for Scissors.
// 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 scoreRoundPart1(round: String): Int {
val s = round.split(" ")
when (s.first()) {
"A" -> when (s.last()) {
"X" -> return 3+1
"Y" -> return 6+2
"Z" -> return 0+3
}
"B" -> when (s.last()) {
"X" -> return 0+1
"Y" -> return 3+2
"Z" -> return 6+3
}
"C" -> when (s.last()) {
"X" -> return 6+1
"Y" -> return 0+2
"Z" -> return 3+3
}
}
return 0
}
//A for Rock, B for Paper, and C for Scissors.
//X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. Good luck!"
fun scoreRoundPart2(round: String): Int {
val s = round.split(" ")
when (s.first()) {
"A" -> when (s.last()) {
"X" -> return 0+3
"Y" -> return 3+1
"Z" -> return 6+2
}
"B" -> when (s.last()) {
"X" -> return 0+1
"Y" -> return 3+2
"Z" -> return 6+3
}
"C" -> when (s.last()) {
"X" -> return 0+2
"Y" -> return 3+3
"Z" -> return 6+1
}
}
return 0
}
fun part1(input: List<String>): Int {
return input.sumOf { scoreRoundPart1(it) }
}
fun part2(input: List<String>): Int {
return input.sumOf { scoreRoundPart2(it) }
}
// 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 | 1 | 3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9 | 2,202 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2022/Day13.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2022
import aoc2022.resources.data
import aoc2022.resources.data2
fun main() {
data class NCont(val nums: List<Int>, val subCon: NCont? = null)
fun look(first: Any, second: Any): Int = when {
first is Int && second is Int -> first - second
first is List<*> && second is List<*> -> first.zip(second)
.firstOrNull { pair -> look(pair.first!!, pair.second!!) != 0 }
?.let { look(it.first!!, it.second!!) } ?: (first.size - second.size)
first is List<*> -> look(first, listOf(second))
second is List<*> -> look(listOf(first), second)
else -> error("Not accepted input")
}
fun part1(input: List<String>): Int {
return (data + data2).chunked(2).mapIndexed { index, (a, b) -> if (look(a, b) < 0) index + 1 else 0 }.sum()
}
fun part2(input: List<String>): Int {
val packet2 = listOf(listOf(2))
val packet6 = listOf(listOf(6))
val addedPackets = (listOf(packet2, packet6) + data + data2)
val sorted = addedPackets.sortedWith(::look)
return (sorted.indexOfFirst { it === packet2 } + 1) * (sorted.indexOfFirst { it === packet6 } + 1)
}
// parts execution
val testInput = readInput("Day13_test").take(23)
val input = readInput("Day13")
// part1(testInput).checkEquals(13)
part1(input)
// .sendAnswer(part = 1, day = "13", year = 2022)
// part2(testInput).checkEquals(140)
part2(input)
// .sendAnswer(part = 2, day = "13", year = 2022)
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 1,533 | Kotlin-AOC-2023 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindCriticalEdges.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
* @see <a href="https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree">
* Source</a>
*/
fun interface FindCriticalEdges {
operator fun invoke(n: Int, edges: Array<IntArray>): List<List<Int>>
}
/**
* Approach 1: Kruskal's Algorithm
*/
class FindCriticalEdgesKruskal : FindCriticalEdges {
override operator fun invoke(n: Int, edges: Array<IntArray>): List<List<Int>> {
val critical: MutableList<Int> = ArrayList()
val pseudoCritical: MutableList<Int> = ArrayList()
for (i in edges.indices) {
var edge = edges[i]
edge = edge.copyOf(edge.size + 1)
edge[3] = i
edges[i] = edge
}
edges.sortWith { a: IntArray, b: IntArray -> a[2].compareTo(b[2]) }
val mstwt = findMST(n, edges, -1, -1)
for (i in edges.indices)
if (mstwt < findMST(n, edges, i, -1)) {
critical.add(edges[i][3])
} else if (mstwt == findMST(n, edges, -1, i)) {
pseudoCritical.add(edges[i][3])
}
val result: MutableList<List<Int>> = ArrayList()
result.add(critical)
result.add(pseudoCritical)
return result
}
private fun findParent(p: Int, parent: IntArray): Int =
if (parent[p] == p) p else findParent(parent[p], parent).also { parent[p] = it }
fun union(u: Int, v: Int, parent: IntArray) {
parent[findParent(u, parent)] = findParent(v, parent)
}
private fun findMST(n: Int, edges: Array<IntArray>, block: Int, e: Int): Int {
val parent = IntArray(n)
for (i in 0 until n) parent[i] = i
var weight = 0
if (e != -1) {
weight += edges[e][2]
union(edges[e][0], edges[e][1], parent)
}
for (i in edges.indices) {
if (i == block) continue
if (findParent(edges[i][0], parent) == findParent(edges[i][1], parent)) {
continue
}
union(edges[i][0], edges[i][1], parent)
weight += edges[i][2]
}
for (i in 0 until n) {
if (findParent(i, parent) != findParent(0, parent)) {
return Int.MAX_VALUE
}
}
return weight
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,006 | kotlab | Apache License 2.0 |
leetcode/src/offer/middle/Offer63.kt | zhangweizhe | 387,808,774 | false | null | package offer.middle
fun main() {
// 剑指 Offer 63. 股票的最大利润
// https://leetcode.cn/problems/gu-piao-de-zui-da-li-run-lcof/
println(maxProfit1(intArrayOf(7,1,5,3,6,4)))
}
fun maxProfit(prices: IntArray): Int {
if (prices.isEmpty()) {
return 0
}
// 1、状态定义:dp[i] 表示前 i 天的最大利润
// 2、转移方程:前 i 天的最大利润dp[i],取前 i-1 天的最大利润dp[i-1] 和 第 i 天卖出的最大利润,两者中的最大值
// dp[i] = max(dp[i-1], prices[i]-min[0:i]),min[0:i] 表示前 i 天的最小值
// 3、初始状态:dp[0] = 0,表示首日的利润为0
// 4、返回值:dp[dp.size-1]
val dp = IntArray(prices.size)
var min = prices[0]
dp[0] = 0
for (i in 1 until prices.size) {
if (prices[i] < min) {
min = prices[i]
}
dp[i] = Math.max(dp[i-1], prices[i] - min)
}
return dp[dp.size-1]
}
fun maxProfit1(prices: IntArray): Int {
// 动态规划,空间优化版本
// 因为 dp[i] 只和 dp[i-1] 有关,所以用 pre 代替 dp[i-1],
if (prices.isEmpty()) {
return 0
}
var pre = 0
var min = prices[0]
for (i in 1 until prices.size) {
if (prices[i] < min) {
min = prices[i]
}
pre = Math.max(pre, prices[i] - min)
}
return pre
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,380 | kotlin-study | MIT License |
src/main/day23/day23.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day23
import Point
import readInput
private typealias Grove = Set<Point>
var directionsToCheck = mutableListOf(
Point::northernNeighbours,
Point::southernNeighbours,
Point::westernNeighbours,
Point::easternNeighbours
)
fun main() {
val input = readInput("main/day23/Day23")
println(year_2017.day23.part1(input))
println(year_2017.day23.part2(input))
}
fun part1(input: List<String>): Int {
return generateSequence(input.toGrove()) { step(it).second }.drop(10).first().let { tenth ->
(1 + tenth.maxOf { it.x } - tenth.minOf { it.x }) *
(1 + tenth.maxOf { it.y } - tenth.minOf { it.y }) - tenth.size
}
}
fun part2(input: List<String>): Int {
directionsToCheck = mutableListOf(
Point::northernNeighbours,
Point::southernNeighbours,
Point::westernNeighbours,
Point::easternNeighbours
)
return generateSequence(emptySet<Point>() to input.toGrove()) { result ->
step(result.second)
}.takeWhile {
it.first != it.second
}.count()
}
private fun step(grove: Set<Point>): Pair<Grove, Grove> {
val proposedSteps = grove.proposedSteps()
directionsToCheck.add(directionsToCheck.removeFirst())
val stepsByElf = proposedSteps.associateBy { it.first }
val possiblePositions = proposedSteps.associateTo(mutableMapOf()) { (_, next) ->
next to proposedSteps.count { it.second == next }
}.filter {
it.value == 1
}.keys
return grove to grove.map { elf ->
if (possiblePositions.contains(stepsByElf[elf]?.second))
stepsByElf[elf]!!.second
else
elf
}.toSet()
}
fun Grove.proposedSteps(): List<Pair<Point, Point>> {
val proposedSteps = mutableListOf<Pair<Point, Point>>()
forEach { elf ->
if (elf.allNeighbours().any { this.contains(it) }) {
val direction = directionsToCheck.firstOrNull { findNeighbours ->
findNeighbours.invoke(elf).dropLast(1).none { this.contains(it) }
}
if (direction != null) {
proposedSteps.add(elf to (elf + direction.invoke(elf).last()))
}
}
}
return proposedSteps
}
fun List<String>.toGrove() =
flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, s ->
if (s == '#') Point(x, y) else null
}
}.toSet()
fun Point.northernNeighbours(): List<Point> {
return listOf(
Point(x - 1, y - 1),
Point(x, y - 1),
Point(x + 1, y - 1),
Point(0, -1),
)
}
fun Point.southernNeighbours(): List<Point> {
return listOf(
Point(x - 1, y + 1),
Point(x, y + 1),
Point(x + 1, y + 1),
Point(0, 1),
)
}
fun Point.easternNeighbours(): List<Point> {
return listOf(
Point(x + 1, y - 1),
Point(x + 1, y),
Point(x + 1, y + 1),
Point(1, 0),
)
}
fun Point.westernNeighbours(): List<Point> {
return listOf(
Point(x - 1, y - 1),
Point(x - 1, y),
Point(x - 1, y + 1),
Point(-1, 0),
)
}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 3,103 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | stcastle | 573,145,217 | false | {"Kotlin": 24899} | sealed interface Item {
val name: String
val size: Int
fun nameSuffix(): String {
val nameSuffix = name.split("/").last()
return if (nameSuffix == "") "/" else nameSuffix
}
}
/** Default size is -1 when unknown. */
class Directory(override val name: String, val parent: Directory?) : Item {
override var size: Int = -1
get() {
if (field == -1) {
field = items().fold(0) { acc: Int, item: Item -> acc + item.size }
}
return field
}
private val contents: MutableSet<Item> = mutableSetOf()
fun add(item: Item) = contents.add(item)
fun items(): Set<Item> = contents
fun subdirectories(): List<Directory> = contents.filterIsInstance<Directory>().map { it }
fun allsubdirectories(): List<Directory> =
subdirectories().fold(subdirectories()) { acc, directory ->
acc + directory.allsubdirectories()
}
// Just make the contents a set.
// fun contains(item: Item) = contents.contains(item)
// this is important for the sets.
override fun equals(other: Any?) = other is Directory && this.name == other.name
override fun hashCode(): Int {
return name.hashCode()
}
override fun toString(): String =
items().fold("- ${name} (dir, size=$size)") { acc: String, item: Item -> acc + "\n\t" + item }
}
data class File(override val name: String, override val size: Int) : Item {
override fun equals(other: Any?) = other is File && this.name == other.name
// override fun toString() = "- ${nameSuffix()} (file, size=$size)"
override fun toString() = "- ${name} (file, size=$size)"
}
/** Finds all sub-directories, including this one, with size at most [max]. */
fun Directory.getAll(maxSize: Int): List<Directory> =
this.allsubdirectories().fold(emptyList()) { acc: List<Directory>, directory: Directory ->
if (directory.size <= maxSize) {
acc + directory
} else acc
}
// fun addSizes(items: List<Item>) = items.sumOf { it.size }
/** Reads the input and returns the root [Directory]. */
fun buildFileSystem(input: List<String>): Directory {
val rootDirectory = Directory("/", null)
var currDir: Directory = rootDirectory
input.forEach { line ->
if (line == "$ cd /") {
// Should only be the first line, so doesn't matter, but whatever.
currDir = rootDirectory
} else if (line == "$ cd ..") {
currDir = currDir.parent!! // trouble if we cd .. from root.
} else if (line.startsWith("$ cd")) {
// Use the given name just as the suffix.
val nameSuffix = line.split(" ").last()
// root will look like "//".
val name = currDir.name + "/" + nameSuffix
// Any other cd is going down one directory.
currDir =
currDir.subdirectories().singleOrNull { it.name == name }
?: Directory(name = name, parent = currDir)
currDir.parent?.add(currDir)
} else if (line == "$ ls") {
// Nothing to do here.
} else if (line.startsWith("dir")) {
val nameSuffix = line.split(" ").last()
val name = currDir.name + "/" + nameSuffix
currDir.add(
currDir.subdirectories().find { it.name == name }
?: Directory(name = name, parent = currDir))
} else {
// Line is a file.
val nameSuffix = line.split(" ").last()
val name = currDir.name + "/" + nameSuffix
val size = line.split(" ").first().toInt()
currDir.add(File(name, size))
}
}
return rootDirectory
}
fun main() {
fun part1(input: List<String>): Int {
val rootDirectory = buildFileSystem(input)
// println(rootDirectory)
// println(rootDirectory.allsubdirectories().map { it.nameSuffix() })
return rootDirectory.getAll(maxSize = 100000).sumOf { it.size }
}
fun part2(input: List<String>): Int {
val rootDirectory = buildFileSystem(input)
val totalSpace = 70000000
val totalSpaceNeeded = 30000000
val openSpace = totalSpace - rootDirectory.size
val spaceNeededToFree = totalSpaceNeeded - openSpace
assert(spaceNeededToFree >= 0)
// Directories that are too small.
val directoriesTooSmall = rootDirectory.getAll(maxSize = spaceNeededToFree).toSet()
// add back in any directories with size exactly equal to spaceNeededToFree
val directoriesWeCanDelete =
setOf(rootDirectory) + rootDirectory.allsubdirectories().toSet() - directoriesTooSmall +
rootDirectory.allsubdirectories().filter { it.size == spaceNeededToFree }.toSet()
// print(directoriesWeCanDelete.map { it.nameSuffix() })
return directoriesWeCanDelete.minOf { it.size }
}
val day = "07"
val testInput = readInput("Day${day}_test")
println("Part 1 test = ${part1(testInput)}")
val input = readInput("Day${day}")
println("part1 = ${part1(input)}")
println("Part 2 test = ${part2(testInput)}")
println("part2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 746809a72ea9262c6347f7bc8942924f179438d5 | 4,853 | aoc2022 | Apache License 2.0 |
src/Day01.kt | SimoneStefani | 572,915,832 | false | {"Kotlin": 33918} | fun main() {
fun part1(input: List<String>): Int {
return (input + "").fold(Pair(0, 0)) { acc, curr -> // Pair(max so far, current elf)
if (curr.isBlank()) {
Pair(maxOf(acc.first, acc.second), 0) // is an empty line
} else {
Pair(acc.first, acc.second + curr.toInt()) // is a number
}
}.first
}
fun part2(input: List<String>): Int {
var partial = 0
return (input + "").mapNotNull { curr ->
if (curr.isBlank()) {
return@mapNotNull partial.also { partial = 0 } // is an empty line
} else {
partial += curr.toInt() // is a number
null
}
}.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b3244a6dfb8a1f0f4b47db2788cbb3d55426d018 | 1,063 | aoc-2022 | Apache License 2.0 |
leetcode2/src/leetcode/word-search.kt | hewking | 68,515,222 | false | null | package leetcode
/**
79. 单词搜索
https://leetcode-cn.com/problems/word-search/
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
object WordSearch {
class Solution {
var ans = false
/**
* 回溯法:
* res= []
* backTrack(路径,选择集) {
* if (结束条件){
* res.add(路径)
* }
* for (选择 in 选择集) {
* 选择
* backTrack(路径,选择集)
* 撤销选择
* }https://leetcode-cn.com/problems/word-search/solution/java-shen-du-sou-suo-hui-su-by-deep2018530/
* }
*/
fun exist(board: Array<CharArray>, word: String): Boolean {
for (i in 0 until board.size) {
for (j in 0 until board[i].size) {
if(backTrack(board,word,i,j,0)){
return true
}
}
}
return false
}
val rows = intArrayOf(0,1,0,-1)
val cols = intArrayOf(1,0,-1,0)
fun backTrack(board: Array<CharArray>,word:String,x: Int,y: Int,start: Int):Boolean {
// 判断越界
if(x >= board.size || x < 0 || y >= board[0].size || y < 0) return false
if (board[x][y] != word[start]) return false
if (word.length - 1 == start ) {
return true
}
board[x][y] = '.'
for (i in 0 until 4) {
if (backTrack(board,word,x + rows[i], y + cols[i],start + 1)){
return true
}
}
board[x][y] = word[start]
return false
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,351 | leetcode | MIT License |
src/year2022/02/Day02.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`02`
import readInput
fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.split(" ") }
.map { Round(it.first(), it[1]) }
.sumOf { it.outcome() }
}
fun part2(input: List<String>): Int {
return input
.map { it.split(" ") }
.map { Round(it.first(), it[1]) }
.sumOf { it.outcome2() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val part1Test = part2(testInput)
//println(part1Test)
check(part1Test == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
data class Round(
val opponent: String,
val outcome: String
) {
fun outcome(): Int {
val myRes = when (outcome) {
"X" -> 1 // rock
"Y" -> 2 //paper
"Z" -> 3 //scissors
else -> error("aaa")
}
// rock (A) - 1
// paper (B) - 2
// scissors (C) - 3
val youOutcome = when {
opponent == "A" && outcome == "X" -> 3
opponent == "A" && outcome == "Y" -> 6
opponent == "A" && outcome == "Z" -> 0
opponent == "B" && outcome == "X" -> 0
opponent == "B" && outcome == "Y" -> 3
opponent == "B" && outcome == "Z" -> 6
opponent == "C" && outcome == "X" -> 6
opponent == "C" && outcome == "Y" -> 0
opponent == "C" && outcome == "Z" -> 3
else -> error("illegal state")
}
return youOutcome + myRes
}
fun outcome2(): Int {
val myRes = when (outcome) {
"X" -> 0 //you lose
"Y" -> 3 //draw
"Z" -> 6 //you win
else -> error("Illegal State")
}
// rock (A) - 1
// paper (B) - 2
// scissors (C) - 3
val yourFigure = when {
opponent == "A" && outcome == "X" -> 3
opponent == "A" && outcome == "Y" -> 1
opponent == "A" && outcome == "Z" -> 2
opponent == "B" && outcome == "X" -> 1
opponent == "B" && outcome == "Y" -> 2
opponent == "B" && outcome == "Z" -> 3
opponent == "C" && outcome == "X" -> 2
opponent == "C" && outcome == "Y" -> 3
opponent == "C" && outcome == "Z" -> 1
else -> error("Illegal State")
}
return yourFigure + myRes
}
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 2,531 | KotlinAdventOfCode | Apache License 2.0 |
src/main/java/com/booknara/problem/math/ValidSquare.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.math
/**
* 593. Valid Square (Medium)
* https://leetcode.com/problems/valid-square/
*/
class ValidSquare {
// T:O(1), S:O(1)
fun validSquare(p1: IntArray, p2: IntArray, p3: IntArray, p4: IntArray): Boolean {
// input check, there are four points
val points = arrayOf(p1, p2, p3, p4)
points.sortWith(compareBy<IntArray> { it[0] }.thenBy { it[1] })
return (getDistance(points[0], points[1]) != 0) and
(getDistance(points[0], points[1]) == getDistance(points[1], points[3])) and
(getDistance(points[1], points[3]) == getDistance(points[3], points[2])) and
(getDistance(points[3], points[2]) == getDistance(points[2], points[0])) and
(getDistance(points[0], points[3]) == getDistance(points[1], points[2]))
}
private fun getDistance(p1: IntArray, p2: IntArray) = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1])
}
fun main() {
val valid = ValidSquare().validSquare(
intArrayOf(0, 0),
intArrayOf(5, 0),
intArrayOf(5, 4),
intArrayOf(0, 4)
)
println(valid)
}
/*
(0,4) (5,4)
(0,0) (5,0)
[1134,-2539]
[492,-1255]
[-792,-1897]
[-150,-3181]
*/ | 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 1,267 | playground | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2023/Day02.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2023
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.math.max
import kotlin.test.assertEquals
class Day02 : AbstractDay() {
@Test
fun part1() {
assertEquals(8, compute1(testInput))
assertEquals(2617, compute1(puzzleInput))
}
@Test
fun part1Dummy() {
assertEquals(6 to "blue", " 6 blue ".parseCube())
assertEquals(listOf(3 to "blue", 4 to "red"), " 3 blue, 4 red".parseSubset())
assertEquals(
listOf(
listOf(6 to "red", 1 to "blue", 3 to "green"),
listOf(2 to "blue", 1 to "red", 2 to "green"),
), " 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green".parseSubsets()
)
assertEquals(
5 to listOf(
listOf(6 to "red", 1 to "blue", 3 to "green"),
listOf(2 to "blue", 1 to "red", 2 to "green"),
), "Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green".parseGame()
)
}
@Test
fun part2() {
assertEquals(2286, compute2(testInput))
assertEquals(59795, compute2(puzzleInput))
}
@Test
fun part2Dummy() {
assertEquals(48, "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green".parseGame().second.determinePower())
}
private fun compute1(input: List<String>): Int {
return input
.map { it.parseGame() }
.filterNot { (_, subsets) ->
subsets.any { subset ->
subset.any { (count, cube) ->
availableColours.getValue(cube) < count
}
}
}
.sumOf { it.first }
}
private fun compute2(input: List<String>): Int {
return input
.map { it.parseGame() }
.sumOf { (_, subsets) ->
subsets.determinePower()
}
}
private fun List<List<Pair<Int, String>>>.determinePower(): Int {
val minPowerMap = mutableMapOf<String, Int>()
forEach { subset ->
subset.forEach { (count, cube) ->
val curVal = minPowerMap[cube] ?: 0
minPowerMap[cube] = max(curVal, count)
}
}
return minPowerMap.values.reduce { a, b -> a * b }
}
private fun String.parseGame(): Pair<Int, List<List<Pair<Int, String>>>> {
val (gameNum, cubes) = this
.replace("Game ", "")
.split(":")
return gameNum.toInt() to cubes.parseSubsets()
}
private fun String.parseSubsets(): List<List<Pair<Int, String>>> {
return this
.trim()
.split(";")
.map { it.parseSubset() }
}
private fun String.parseSubset(): List<Pair<Int, String>> {
return trim()
.split(",")
.map { cubeString ->
cubeString.parseCube()
}
}
private fun String.parseCube(): Pair<Int, String> {
val (countStr, cubeStr) = this.trim().split(" ")
return countStr.toInt() to cubeStr
}
private val availableColours = mapOf(
"red" to 12,
"green" to 13,
"blue" to 14,
)
} | 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 3,213 | aoc | Apache License 2.0 |
src/main/kotlin/aoc2023/Day14.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import utils.ArrayAsSurface
import utils.Coordinates
import utils.Direction
import utils.E
import utils.InputUtils
import utils.N
import utils.S
import utils.W
private fun getRocks(input: List<String>) = ArrayAsSurface(input)
.indexed()
.filter { (_, c) -> c == 'O' }
.map { it.first }.toSet()
private fun withoutRocks(input: List<String>) =
ArrayAsSurface(input.map { it.replace('O', '.') })
class Day14Rocks(val surface: ArrayAsSurface, val rolling: Set<Coordinates>) {
constructor(input: List<String>):
this(withoutRocks(input), getRocks(input)) {
}
val height = surface.points.size
fun weights() = rolling.map { height - it.y }.sum()
private fun comparatorFor(dir: Direction): (Coordinates) -> Int = when(dir) {
N -> { { it.y } }
S -> { { -it.y } }
W -> { { it.x } }
E -> { { -it.x } }
}
fun tip(dir: Direction): Day14Rocks {
val stopped = mutableSetOf<Coordinates>()
rolling.sortedBy(comparatorFor(dir)).forEach {old ->
stopped.add(old.heading(dir).takeWhile {
!stopped.contains(it) && surface.checkedAt(it, '#') == '.'
}.last())
}
return Day14Rocks(surface, stopped)
}
fun cycle() = tip(N).tip(W).tip(S).tip(E)
override fun toString(): String {
return surface.rows().map {row ->
row.map { if (rolling.contains(it)) 'O' else surface.at(it) }
.joinToString("")
}.joinToString("\n")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Day14Rocks
return rolling == other.rolling
}
override fun hashCode(): Int {
return rolling.hashCode()
}
}
fun main() {
val testInput = """O....#....
O.OO#....#
.....##...
OO.#O....O
.O.....O#.
O.#..O.#.#
..O..#O..O
.......O..
#....###..
#OO..#....""".trimIndent().split("\n")
fun part1(input: List<String>): Int {
return Day14Rocks(input).tip(N).weights()
}
fun part2(input: List<String>): Int {
val seen = mutableMapOf<Day14Rocks, Int>()
generateSequence(Day14Rocks(input)) { it.cycle() }
.mapIndexed { i, r -> r to i }
.forEach { (rocks, index) ->
val old = seen.put(rocks, index)
if (old != null) { // We have a loop
seen.put(rocks, old) // Put it back incase we need it
val loopSize = index - old
println("Loop: ${loopSize} elements from $old to $index")
val target = 1_000_000_000
val i = old + ((target - old) % loopSize)
return seen.entries.first { it.value == i }.key.weights()
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 136)
println(part2(testInput))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 14)
val input = puzzleInput.toList()
println(part1(input))
val start = System.currentTimeMillis()
println(part2(input))
println("Time: ${System.currentTimeMillis() - start}")
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 3,341 | aoc-2022-kotlin | Apache License 2.0 |
y2021/src/main/kotlin/adventofcode/y2021/Day13.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2021
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec2
import kotlin.math.abs
object Day13 : AdventSolution(2021, 13, "Transparent Origami") {
override fun solvePartOne(input: String): Int {
val (points, folds) = parse(input)
return foldPaper(points, folds.take(1)).size
}
override fun solvePartTwo(input: String): String {
val (points, folds) = parse(input)
val result = foldPaper(points, folds)
return prettyString(result)
}
private fun parse(input: String): Pair<List<Vec2>, List<Pair<String, Int>>> {
val (a, b) = input.split("\n\n")
val points = a.lineSequence().map {
val (x, y) = it.split(',').map(String::toInt)
Vec2(x, y)
}.toList()
val regex = """fold along ([xy])=(\d+)""".toRegex()
val folds = b.lineSequence()
.map { regex.matchEntire(it)!!.destructured }
.map { (axis, d) -> axis to d.toInt() }
.toList()
return points to folds
}
private fun foldPaper(points: List<Vec2>, folds: List<Pair<String, Int>>) =
folds.fold(points) { dots, (axis, d) ->
if (axis == "x")
dots.map { it.copy(x = d - abs(it.x - d)) }
else
dots.map { it.copy(y = d - abs(it.y - d)) }
}.toSet()
private fun prettyString(result: Set<Vec2>) =
(0..result.maxOf(Vec2::y)).joinToString("\n", "\n") { y ->
(0..result.maxOf(Vec2::x)).joinToString("") { x ->
if (Vec2(x, y) in result) "#" else " "
}
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,645 | advent-of-code | MIT License |
src/day12/Day12.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day12
import lib.Point2D
import lib.directionsClockwise
import readInput
import java.util.LinkedList
import kotlin.math.min
fun main() {
val input = readInput("day12/input")
val h = input.size
val w = input[0].length
var start = Point2D(0, 0)
var end = Point2D(0, 0)
val heights = List(h) { y ->
List(w) { x ->
val char = input[y][x]
val point = Point2D(x, y)
if (char == 'S') {
start = point
}
if (char == 'E') {
end = point
}
height(char)
}
}
fun shortestDistance(start: Point2D, end: Point2D): Int {
val distances: List<MutableList<Int>> = List(h) {
MutableList(w) { Int.MAX_VALUE }
}
distances[start.y][start.x] = 0
val queue = LinkedList<Point2D>()
queue.offer(start)
var res = Int.MAX_VALUE
while (queue.isNotEmpty()) {
val currentPoint = queue.poll()
if (currentPoint == end) {
res = distances[currentPoint.y][currentPoint.x]
break
}
for (d in directionsClockwise) {
val newPoint = currentPoint + d
if (newPoint.x in 0 until w && newPoint.y in 0 until h) {
if (heights[newPoint.y][newPoint.x] - heights[currentPoint.y][currentPoint.x] <= 1) {
val newDistance = distances[currentPoint.y][currentPoint.x] + 1
if (newDistance < distances[newPoint.y][newPoint.x]) {
distances[newPoint.y][newPoint.x] = newDistance
queue.offer(newPoint)
}
}
}
}
}
return res
}
println(shortestDistance(start, end))
var ans = Int.MAX_VALUE
for (y in 0 until h) {
for (x in 0 until w) {
if (input[y][x] == 'a') {
ans = min(ans, shortestDistance(Point2D(x, y), end))
}
}
}
println(ans)
}
fun height(c: Char): Int {
val char: Char = when (c) {
'S' -> {
'a'
}
'E' -> {
'z'
}
else -> {
c
}
}
return char - 'a'
} | 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 2,350 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | mborromeo | 571,999,097 | false | {"Kotlin": 10600} | fun main() {
fun parseCrates(input: List<String>): List<MutableList<Char>> {
val crates: List<MutableList<Char>> = List(input.last().last().digitToInt()) { mutableListOf() }
for (i in 1 until input.size){
input.reversed()[i].chunked(4).forEachIndexed { index, s ->
val crateLetter = s.replace("\\s|\\[|\\]".toRegex(), "")
if (crateLetter.isNotEmpty()) {
crates[index].add(crateLetter.first())
}
}
}
return crates
}
fun parseInput(input: List<String>): Pair<List<MutableList<Char>>, List<String>> {
var isState = true
val (state, commands) = input.partition {
if (it.isBlank()) { isState = false }
isState
}
return Pair(parseCrates(state), commands.filter { it.isNotEmpty() })
}
fun parseCommand(command: String): Triple<Int, Int, Int> {
val (amount, from, to) = command.split(" ").slice(setOf(1, 3, 5)).map { it.toInt() }
return Triple(amount, from, to)
}
fun part1(input: List<String>): String {
val (crates, commands) = parseInput(input)
for (command in commands) {
val (amount, from, to) = parseCommand(command)
repeat (amount) {
crates[to - 1].add(crates[from - 1].removeLast())
}
}
return crates.map {x -> x.lastOrNull() ?: " "}.joinToString("", "", "")
}
fun part2(input: List<String>): String {
val (crates, commands) = parseInput(input)
for (command in commands) {
val (amount, from, to) = parseCommand(command)
val tail = crates[from - 1].takeLast(amount)
repeat (amount) {
crates[from - 1].removeLast()
}
crates[to - 1].addAll(tail)
}
return crates.map {x -> x.lastOrNull() ?: " "}.joinToString("", "", "")
}
val input = readInput("Day05_input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d01860ecaff005aaf8e1e4ba3777a325a84c557c | 2,053 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | emanguy | 573,113,840 | false | {"Kotlin": 17921} | fun itemPriority(item: Char): Int = when(item) {
in 'a'..'z' -> item - 'a' + 1
in 'A'..'Z' -> item - 'A' + 27
else -> throw IllegalArgumentException("Not an item: $item")
}
fun main() {
fun part1(inputs: List<String>): Int {
var totalValue = 0
inputLoop@ for (input in inputs) {
val firstCompartment = input.take(input.length / 2)
val secondCompartment = input.takeLast(input.length / 2)
val firstCompartmentContents = firstCompartment.asSequence().toSet()
for (character in secondCompartment.asSequence()) {
if (character in firstCompartmentContents) {
totalValue += itemPriority(character)
continue@inputLoop
}
}
}
return totalValue
}
fun part2(inputs: List<String>): Int {
var totalValue = 0
for (inputChunk in inputs.chunked(3)) {
val (bag1, bag2, bag3) = inputChunk
val bag1Contents = bag1.asSequence().toSet()
val bag2Contents = bag2.asSequence().toSet()
val bag3Contents = bag3.asSequence().toSet()
val commonItemSet = bag1Contents intersect bag2Contents intersect bag3Contents
// Assuming there is exactly one item in common
totalValue += itemPriority(commonItemSet.first())
}
return totalValue
}
// Verify the sample input works
val inputs = readInput("Day03_test")
check(part1(inputs) == 157)
check(part2(inputs) == 70)
val finalInputs = readInput("Day03")
println(part1(finalInputs))
println(part2(finalInputs))
}
| 0 | Kotlin | 0 | 1 | 211e213ec306acc0978f5490524e8abafbd739f3 | 1,670 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | Kietyo | 573,293,671 | false | {"Kotlin": 147083} |
fun String.toClosedRange(): IntRange {
val (first, second) = this.split("-").map { it.toInt() }
return first..second
}
fun main() {
fun part1(input: List<String>): Unit {
var count = 0
input.forEach { line ->
val (first, second) = line.split(",").map { it.toClosedRange() }
if (first inRange second || second inRange first) {
count++
}
}
println(count)
}
fun part2(input: List<String>): Unit {
var count = 0
input.forEach { line ->
val (first, second) = line.split(",").map { it.toClosedRange() }
val overlaps = first.intersect(second).isNotEmpty()
println("first: $first, second: $second, overlaps: $overlaps")
// val inRange = first inRange second || second inRange first
if (overlaps) {
count++
}
}
println(count)
}
val dayString = "day4"
// test if implementation meets criteria from the description, like:
val testInput = readInput("${dayString}_test")
part1(testInput)
part2(testInput)
val input = readInput("${dayString}_input")
// part1(input)
part2(input)
}
private infix fun IntRange.inRange(second: IntRange): Boolean {
return this.first in second && this.last in second
}
| 0 | Kotlin | 0 | 0 | dd5deef8fa48011aeb3834efec9a0a1826328f2e | 1,352 | advent-of-code-2022-kietyo | Apache License 2.0 |
src/2021/Day23.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | import java.io.File
import java.util.*
import kotlin.math.abs
fun main() {
Day23().solve()
}
private enum class LocationType {CORRIDOR, ROOM}
// #############
// #01.2.3.4.56#
// ###0#1#2#3###
// #.#.#.#.#
private data class Location(val type: LocationType, val index: Int) {
companion object {
val allOrdered =
listOf(
Location(LocationType.CORRIDOR, 0),
Location(LocationType.CORRIDOR, 1),
Location(LocationType.ROOM, 0),
Location(LocationType.CORRIDOR, 2),
Location(LocationType.ROOM, 1),
Location(LocationType.CORRIDOR, 3),
Location(LocationType.ROOM, 2),
Location(LocationType.CORRIDOR, 4),
Location(LocationType.ROOM, 3),
Location(LocationType.CORRIDOR, 5),
Location(LocationType.CORRIDOR, 6))
val all: List<Location> get() = allOrdered
val rooms = all.filter { it.isRoom }
val corridor = all.filter { it.isCorridor }
val corridorIndices = corridor.map { toOrderIx(it) }
fun toOrderIx(l: Location): Int {
return allOrdered.indexOf(l)
}
fun fromOrderIx(ix: Int): Location {
return allOrdered[ix]
}
}
val orderIx: Int get() = toOrderIx(this)
val isRoom: Boolean get() = type == LocationType.ROOM
val isCorridor: Boolean get() = type == LocationType.CORRIDOR
override fun toString(): String {
return "( ${if (isRoom) "R" else "C"}$index/${orderIx})"
}
fun distance(other: Location): Int {
return abs(stepsTo(other))
}
fun stepsTo(other: Location): Int {
if (orderIx == other.orderIx) {
return 0
}
val extraSteps = listOf(this, other).count{it.isRoom}
val diff = other.orderIx - orderIx
if (diff>0) {
return diff + extraSteps
}
return diff - extraSteps
}
fun indicesUntil(other: Location): IntRange {
return if (orderIx < other.orderIx) {
orderIx+1..other.orderIx-1
} else {
other.orderIx+1..orderIx-1
}
}
fun locationsUntil(other: Location): List<Location> {
return indicesUntil(other).map { all[it] }
}
fun indicesTo(other: Location): IntRange {
return if (orderIx < other.orderIx) {
orderIx+1..other.orderIx
} else {
other.orderIx..orderIx-1
}
}
fun locationsTo(other: Location): List<Location> {
return indicesTo(other).map { all[it] }
}
}
private enum class Agent(val roomIndex: Int, val stepCost: Int) {
A(0, 1),
B(1, 10),
C(2, 100),
D(3, 1000);
fun isHomeRoom(l: Location): Boolean {
return l.isRoom && isHomeRoom(l.index)
}
fun isHomeRoom(index: Int): Boolean {
return index == roomIndex
}
fun homeRoom(): Location {
return Location(LocationType.ROOM, roomIndex)
}
fun minHomeDistance(location: Location): Int {
return location.distance(homeRoom())
}
fun minReturnCost(location: Location): Int {
return minHomeDistance(location) * stepCost
}
}
class Day23 {
val input1 =
"""#############
#...........#
###B#C#B#D###
#A#D#C#A#
#########"""
val input2 =
"""#############
#...........#
###C#D#D#A###
#B#A#B#C#
#########"""
val input3 =
"""#############
#...........#
###B#C#B#D###
#D#C#B#A#
#D#B#A#C#
#A#D#C#A#
#########"""
val input4 =
"""#############
#...........#
###C#D#D#A###
#D#C#B#A#
#D#B#A#C#
#B#A#B#C#
#########"""
// #############
// #01.2.3.4.56#
// ###0#1#2#3###
// #.#.#.#.#
private data class Move(val agent: Agent, val source: Location, val target: Location, val distance: Int, val fromState: State? = null) {
override fun toString(): String {
return "$agent: $source -> $target ($distance/${cost()})"
}
fun cost(): Int {
return agent.stepCost * distance
}
}
private class MinCostStateFinder(initialState: State) {
val states = PriorityQueue<State>(100, {a, b -> a.minFinishCost.compareTo(b.minFinishCost)})
var minState: State? = null
var maxSize = 0
var added = 0
val agentsStates = mutableMapOf<AgentsState, State>()
init {
if (initialState.isFinished()) {
minState = initialState
} else {
add(initialState)
}
}
fun isOptimal(s1: State): Boolean {
val s0 = agentsStates.get(AgentsState(s1))
if (s0 == null) {
return true
}
if (s0 === s1) {
return true
}
assert(s0.minReturnCost == s1.minReturnCost)
return s1.cost < s0.cost
}
fun add(s: State) {
states.add(s)
agentsStates[AgentsState(s)] = s
++added
if (states.size>maxSize) {
maxSize = states.size
}
// if (added % 10000 == 0) {
// println("${added} ${maxSize} ${s.steps.size} ${s.minFinishCost} ${minState!=null} ${agentsStates.size}")
// }
}
fun isLessCostThanMin(s: State): Boolean {
return s.minFinishCost < (minState?.cost ?: Int.MAX_VALUE)
}
tailrec fun find(): State? {
if (states.isEmpty()) {
return minState
}
val nextState = states.remove()
if (!isLessCostThanMin(nextState)) {
return find()
}
if (!isOptimal(nextState)) {
return find()
}
val nextStates = nextState.nextStates()
for (s in nextStates) {
if (isLessCostThanMin(s)) {
if (s.isFinished()) {
minState = s
} else if (isOptimal(s)) {
add(s)
}
}
}
return find()
}
}
private class AgentsState(val s: State) {
override fun equals(other: Any?): Boolean {
return (other is AgentsState) && s.corridor.equals(other.s.corridor) && s.rooms.equals(other.s.rooms)
}
override fun hashCode(): Int {
return (s.corridorToString() + s.roomsToString()).hashCode()
}
}
private class State(val rooms: List<List<Agent?>>,
val corridor: List<Agent?> = List(7){null},
val cost: Int = 0,
val minReturnCost: Int =
Location.rooms.map{r ->
val room = rooms[r.index]
room.map { it?.minReturnCost(r) ?: 0 }.sum()
}.sum(),
val steps: List<Move> = listOf()) {
val roomSize = rooms[0].size
val minFinishCost: Int get() = cost + minReturnCost
init {
assert(rooms.size == 4)
assert(rooms.all{it.size == roomSize})
assert(corridor.size == 7)
if (isFinished()) {
assert(minReturnCost == 0)
}
}
fun getAgent(location: Location): Agent? {
if (location.isCorridor) {
return corridor[location.index]
}
val room = rooms[location.index]
return room.firstNotNullOfOrNull { it }
}
fun getAgentAfterMove(location: Location, move: Move): Agent? {
if (location == move.source) {
return null
}
if (location == move.target) {
return getAgent(move.source)
}
return getAgent(location)
}
fun move(source: Location, target: Location): Move? {
if (source == target) {
return null
}
if (source.isCorridor && target.isCorridor) {
return null
}
val agent = getAgent(source)
if (agent == null) {
return null
}
if (target.isRoom && (!agent.isHomeRoom(target) || hasRoomAlien(target.index))) {
return null
}
if (target.isCorridor && source.isRoom && !hasRoomAlien(source.index)) {
return null
}
if (source.locationsTo(target).any {
it.isCorridor && getAgent(it) != null
}) {
return null
}
val distance = abs(target.orderIx - source.orderIx) +
(if (target.isRoom) getEmptySpace(target.index) else 0) +
(if (source.isRoom) getEmptySpace(source.index) + 1 else 0)
// val move = Move(agent, source, target, distance)
val move = Move(agent, source, target, distance, this)
if (causesDeadlock(move)) {
return null
}
return move
}
fun causesDeadlock(move: Move): Boolean {
return causesDeadlock(listOf(move.target), move)
}
fun causesDeadlock(blockChain: List<Location>, move: Move): Boolean {
val lastLocation = blockChain.last()
val lastAgent = getAgentAfterMove(lastLocation, move)!!
val nextBlockers = lastLocation.locationsUntil(lastAgent.homeRoom()).filter{getAgentAfterMove(it, move) != null}
for (l in nextBlockers) {
if (blockChain.indexOf(l) != -1) {
return true
} else {
return causesDeadlock(blockChain.toMutableList().apply{add(l)}, move)
}
}
return false
}
fun nextState(source: Location, target: Location): State? {
val move = move(source, target) ?: return null
val agent = getAgent(source)!!
val newCost = cost + move.cost()
val newRooms = rooms.map{it.toMutableList()}
val newCorridor = corridor.toMutableList()
val newMinReturnCost =
minReturnCost - agent.minReturnCost(source) + agent.minReturnCost(target)
val newSteps = steps.toMutableList().also{it.add(move)}
if (source.isRoom) {
val sourceRoom = newRooms[source.index]
sourceRoom[sourceRoom.indexOfFirst { it != null }] = null
} else {
newCorridor[source.index] = null
}
if (target.isRoom) {
val targetRoom = newRooms[target.index]
targetRoom[targetRoom.lastIndexOf(null)] = agent
} else {
newCorridor[target.index] = agent
}
return State(newRooms, newCorridor, newCost, newMinReturnCost, newSteps)
}
fun nextStates(): List<State> {
return Location.all.flatMap{it1 -> Location.all.map{it2 -> nextState(it1, it2)}.filter{it != null}.map{it!!}}.sortedBy { it.cost }
}
fun isFinished(): Boolean {
return rooms.indices.all { isRoomFinishished(it) }
}
fun hasRoomAlien(roomIndex: Int): Boolean {
return rooms[roomIndex].any{it != null && !it.isHomeRoom(roomIndex)}
}
fun getEmptySpace(roomIndex: Int): Int {
return rooms[roomIndex].count { it == null }
}
fun isRoomFinishished(roomIndex: Int): Boolean {
return rooms[roomIndex].all{it != null && it.isHomeRoom(roomIndex)}
}
fun corridorToString(): String {
return Location.all.map{ if (it.isRoom) {"${it.index}"} else {corridor[it.index]?.toString()?:"."} }.joinToString("")
}
fun roomToString(roomIndex: Int): String {
return rooms[roomIndex].map{it?.toString()?:"."}.joinToString("")
}
fun roomsToString(): String {
return rooms.indices.map{"R$it:${roomToString(it)}:${getEmptySpace(it)}"}.joinToString("|")
}
override fun toString(): String {
return "[C:${corridorToString()}|${roomsToString()}]($cost/$minFinishCost)"
}
}
fun solve() {
// val f = File("src/2021/inputs/day23.in")
// val s = Scanner(f)
val s = Scanner(input4)
s.useDelimiter("[^ABCD]+")
val initialRoom = listOf<Agent?>()
val initialRooms = List(4){initialRoom.toMutableList()}
var i = 0
while (s.hasNext()) {
initialRooms[i].add(Agent.valueOf(s.next("[ABCD]")))
i = (i+1) % 4
}
val state = State(initialRooms)
val finder = MinCostStateFinder(state)
val bestFinalState = finder.find()!!
println("${bestFinalState.cost} ${finder.maxSize} ${finder.added}")
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 12,986 | advent-of-code | Apache License 2.0 |
src/day02/Day02.kt | skokovic | 573,361,100 | false | {"Kotlin": 12166} | package day02
import readInput
fun calculateTuple(elf: String, me: String): Int {
var sum = 0
when (me) {
"X" -> sum += 1
"Y" -> sum += 2
"Z" -> sum += 3
}
when (elf) {
"A" -> when (me) {
"X" -> sum += 3
"Y" -> sum += 6
"Z" -> sum += 0
}
"B" -> when (me) {
"X" -> sum += 0
"Y" -> sum += 3
"Z" -> sum += 6
}
"C" -> when (me) {
"X" -> sum += 6
"Y" -> sum += 0
"Z" -> sum += 3
}
}
return sum
}
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEach {
val (elf, me) = it.split(' ')
sum += calculateTuple(elf, me)
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.forEach {
val (elf, me) = it.split(' ')
when (me) {
"X" -> when(elf) {
"A" -> sum+= calculateTuple("A", "Z")
"B" -> sum+= calculateTuple("B", "X")
"C" -> sum+= calculateTuple("C", "Y")
}
"Y" -> when(elf) {
"A" -> sum+= calculateTuple("A","X")
"B" -> sum+= calculateTuple("B","Y")
"C" -> sum+= calculateTuple("C","Z")
}
"Z" -> when(elf) {
"A" -> sum+= calculateTuple("A","Y")
"B" -> sum+= calculateTuple("B","Z")
"C" -> sum+= calculateTuple("C","X")
}
}
}
return sum
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fa9aee3b5dd09b06bfd5c232272682ede9263970 | 1,788 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/Day02.kt | Maetthu24 | 572,844,320 | false | {"Kotlin": 41016} | package year2022
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
var s = 0
when (it.last()) {
'X' -> s += 1
'Y' -> s += 2
'Z' -> s += 3
}
when (it) {
"A X", "B Y", "C Z" -> s += 3
"A Y", "B Z", "C X" -> s += 6
}
s
}
}
fun Char.draw(): Char {
return when(this) {
'A' -> 'X'
'B' -> 'Y'
else -> 'Z'
}
}
fun Char.win(): Char {
return when(this) {
'A' -> 'Y'
'B' -> 'Z'
else -> 'X'
}
}
fun Char.lose(): Char {
return when(this) {
'A' -> 'Z'
'B' -> 'X'
else -> 'Y'
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val p1 = it.first()
val p2 = when (it.last()) {
'X' -> p1.lose()
'Y' -> p1.draw()
else -> p1.win()
}
var s = 0
when (p2) {
'X' -> s += 1
'Y' -> s += 2
'Z' -> s += 3
}
when (p1.plus(" ").plus(p2)) {
"A X", "B Y", "C Z" -> s += 3
"A Y", "B Z", "C X" -> s += 6
}
s
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val testResult = part1(testInput)
val testExpected = 15
check(testResult == testExpected) { "testResult should be $testExpected, but is $testResult" }
val testResult2 = part2(testInput)
val testExpected2 = 12
check(testResult2 == testExpected2) { "testResult2 should be $testExpected2, but is $testResult2" }
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 3b3b2984ab718899fbba591c14c991d76c34f28c | 1,975 | adventofcode-kotlin | Apache License 2.0 |
leetcode/src/offer/middle/Offer38.kt | zhangweizhe | 387,808,774 | false | null | package offer.middle
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashSet
fun main() {
// 剑指 Offer 38. 字符串的排列
// https://leetcode.cn/problems/zi-fu-chuan-de-pai-lie-lcof/
println(permutation("1234567").contentToString())
}
fun permutation(s: String): Array<String> {
if (s == "") {
return arrayOf("")
}
val chars = s.toCharArray()
Arrays.sort(chars)
val resultList = ArrayList<String>()
dfs(chars.size, resultList, "", String(chars))
val result = Array<String>(resultList.size) {
resultList[it]
}
return result
}
private fun dfs(charsSize: Int, resultList: MutableList<String>, curr: String, remain: String) {
if (curr.length == charsSize) {
resultList.add(curr)
return
}
for (i in remain.indices) {
if (i > 0 && remain[i-1] == remain[i]){
continue
}
dfs(charsSize, resultList, curr + remain[i], remain.removeRange(i, i+1))
}
}
private class Solution {
private val resultList = ArrayList<String>()
lateinit var chars:CharArray
var charsSize = 0
fun permutation(s: String): Array<String> {
chars = s.toCharArray()
charsSize = chars.size
backtrack(0)
val array = Array<String>(resultList.size) {
resultList[it]
}
return array
}
/**
* 固定第 [x] 位上的字符
*/
private fun backtrack(x: Int) {
if (x == charsSize - 1) {
resultList.add(String(chars))
return
}
// 记录 x 位置上已经固定过的字符
val set = HashSet<Char>()
for (i in x until charsSize) {
if (set.contains(chars[i])) {
// x 位置上已经固定过这个字符了
continue
}
set.add(chars[i])
// 把 i 位置的值交换到 x 的位置上,也就是将 chars[i] 固定在 x 位置
// i==x 时,可以不执行交换
swap(i, x)
// 对交换后的 chars 数组继续执行递归,固定的位置是 x 的一下,也就是 x+1
backtrack(x+1)
// 恢复原数组,也就是恢复 x i 的位置,交换回来
swap(i, x)
}
}
private fun backtrack1(x: Int) {
if (x == charsSize - 1) {
resultList.add(String(chars))
return
}
val set = HashSet<Char>()
for (i in x until charsSize) {
if (set.contains(chars[i])) {
continue
}
set.add(chars[i])
swap(i, x)
backtrack1(x+1)
swap(i, x)
}
}
private fun swap(x:Int, y:Int) {
val tmp = chars[x]
chars[x] = chars[y]
chars[y] = tmp
}
}
| 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,862 | kotlin-study | MIT License |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-05.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.readInputLines
import kotlin.math.abs
import kotlin.math.max
fun main() {
val input = readInputLines(2021, "05-input")
val test1 = readInputLines(2021, "05-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val parsed = parse(input)
val filtered = parsed.filter { (start, end) -> start.x == end.x || start.y == end.y }
return countOverlaps(filtered)
}
private fun part2(input: List<String>): Int {
val parsed = parse(input)
return countOverlaps(parsed)
}
private fun countOverlaps(lines: List<Pair<Coord2D, Coord2D>>): Int {
val field = mutableMapOf<Coord2D, Int>()
lines.forEach { (start, end) ->
for (c in range(start, end)) {
val count = field.getOrDefault(c, 0)
field[c] = count + 1
}
}
return field.count { 2 <= it.value }
}
private fun parse(input: List<String>): List<Pair<Coord2D, Coord2D>> = input.map {
it.split(" -> ").let { (c1, c2) -> Coord2D.parse(c1) to Coord2D.parse(c2) }
}
private fun range(start: Coord2D, end: Coord2D): List<Coord2D> = buildList {
val dx = end.x - start.x
val dy = end.y - start.y
val max = max(abs(dx), abs(dy))
val stepX = dx / max
val stepY = dy / max
repeat(max + 1) {
this += Coord2D(start.x + stepX * it, start.y + stepY * it)
}
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,669 | advent-of-code | MIT License |
src/Day05.kt | jdappel | 575,879,747 | false | {"Kotlin": 10062} | fun makeStack(items: Collection<String>): ArrayDeque<String> {
val stack = ArrayDeque<String>()
items.forEach { stack.add(it) }
return stack
}
fun main() {
val st1 = makeStack(listOf("Q","F","M","R","L","W","C","V"))
val st2 = makeStack(listOf("D","Q","L"))
val st3 = makeStack(listOf("P","S","R","G","W","C","N","B"))
val st4 = makeStack(listOf("L","C","D","H","B","Q","G"))
val st5 = makeStack(listOf("V","G","L","F","Z","S"))
val st6 = makeStack(listOf("D","G","N","P"))
val st7 = makeStack(listOf("D","Z","P","V","F","C","W"))
val st8 = makeStack(listOf("C","P","D","M","S"))
val st9 = makeStack(listOf("Z","N","W","T","V","M","C","P"))
val inputToStack = mapOf(1 to st1, 2 to st2, 3 to st3, 4 to st4, 5 to st5, 6 to st6, 7 to st7, 8 to st8, 9 to st9)
fun part1(input: List<String>): String {
input.forEach { line ->
val (cnt, from, to) = line.split(" ")
for (i in 1..cnt.toInt()) {
val popStack = inputToStack[from.toInt()]
val pushStack = inputToStack[to.toInt()]
pushStack?.add(popStack?.removeLast() ?: "")
}
}
return listOf<String>(st1.last(),st2.last(),st3.last(),st4.last(),st5.last(),st6.last(),st7.last(),st8.last(),st9.last()).joinToString(separator = "") { it }
}
fun part2(input: List<String>): String {
input.forEach { line ->
val (cnt, from, to) = line.split(" ").map { it.toInt() }
val popStack = inputToStack[from]
val pushStack = inputToStack[to]
if (cnt == 1) {
pushStack?.add(popStack?.removeLast() ?: "")
}
else {
val tmpStack = ArrayDeque<String>()
for (i in 1..cnt) {
tmpStack.add(popStack?.removeLast() ?: "")
}
for (i in 1..cnt) {
pushStack?.add(tmpStack?.removeLast() ?: "")
}
}
}
return listOf<String>(st1.last(),st2.last(),st3.last(),st4.last(),st5.last(),st6.last(),st7.last(),st8.last(),st9.last()).joinToString(separator = "") { it }
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("Day05_test")
println(part2(input))
} | 0 | Kotlin | 0 | 0 | ddcf4f0be47ccbe4409605b37f43534125ee859d | 2,416 | AdventOfCodeKotlin | Apache License 2.0 |
src/Day13.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import kotlin.math.sign
import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day13.run {
solve1(13) // 6369
solve2(140) // 25800
}
}.let { println("Total: $it ms") }
}
object Day13 : Day.GroupInput<List<Day13.Data>, Int>("13") {
data class Data(val packet1: Packet, val packet2: Packet)
sealed class Packet: Comparable<Packet> {
data class DataList(val value: List<Packet>) : Packet()
data class DataNumber(val value: Int) : Packet()
override fun compareTo(other: Packet): Int = when {
this is DataNumber && other is DataNumber -> (value - other.value).sign
this is DataNumber -> DataList(listOf(this)).compareTo(other)
other is DataNumber -> compareTo(DataList(listOf(other)))
this is DataList && other is DataList -> run {
for (i in 0 .. minOf(value.lastIndex, other.value.lastIndex)) {
val cmp = value[i].compareTo(other.value[i])
if (cmp != 0) return cmp
}
(value.size - other.value.size).sign
}
else -> error("Should not reach here.")
}
companion object {
fun fromString(s: String): Packet {
var i = 0
fun parsePacket(): Packet = if (s[i] == '[') {
val list = mutableListOf<Packet>()
++i
while (i < s.length && s[i] != ']') {
if (s[i] == ',') ++i
list.add(parsePacket())
}
++i
DataList(list)
} else {
var num = 0
while (s[i] in '0'..'9') num = num * 10 + (s[i++] - '0')
DataNumber(num)
}
return parsePacket()
}
}
}
override fun parse(input: List<List<String>>) = input.map { (a, b) ->
Data(Packet.fromString(a), Packet.fromString(b))
}
override fun part1(data: List<Data>): Int = data.withIndex()
.filter { (_, pair) -> pair.run { packet1 < packet2 } }
.sumOf { it.index + 1 }
override fun part2(data: List<Data>): Int {
val flatList = data.flatMap { listOf(it.packet1, it.packet2) }.sorted()
val index1 = -flatList.binarySearch(Packet.fromString("[[2]]")) - 1
val index2 = -flatList.binarySearch(Packet.fromString("[[6]]")) - 1
return (index1 + 1) * (index2 + 2)
}
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 2,578 | AdventOfCode2022 | Apache License 2.0 |
src/Day9.kt | jrmacgill | 573,065,109 | false | {"Kotlin": 76362} | import java.lang.Integer.max
import kotlin.math.abs
class Day9 constructor(length: Int){
var head = Pair(0,0)
var tails = MutableList<Pair<Int,Int>>(length) { Pair(0,0)}
var width = 0
var height = 0
var visited : HashMap<Pair<Int,Int>, Int> = HashMap<Pair<Int,Int>, Int>()
fun Pair<Int, Int>.add(other: Pair<Int, Int>) : Pair<Int, Int> {
return Pair(this.first + other.first, this.second + other.second)
}
fun Pair<Int, Int>.touches(other: Pair<Int, Int>) : Boolean {
return abs(this.first - other.first) < 2 && abs(this.second - other.second) < 2
}
fun Pair<Int, Int>.twang(head: Pair<Int, Int>) : Pair<Int, Int> {
return when {
head.second == this.second -> Pair((head.first+this.first)/2, head.second)
head.first == this.first -> Pair(head.first, (head.second+this.second)/2)
head.first > this.first && head.second > this.second -> Pair(this.first + 1, this.second +1)
head.first > this.first && head.second < this.second -> Pair(this.first + 1, this.second -1)
head.first < this.first && head.second < this.second -> Pair(this.first - 1, this.second -1)
head.first < this.first && head.second > this.second -> Pair(this.first - 1, this.second +1)
else -> error("welp")
}
}
fun store(p : Pair<Int, Int>) {
visited.putIfAbsent(p, 0)
visited[p] = visited[p]!!+1
width = max(width, p.first)
height = max(height, p.first)
}
fun printMap(){
println()
for (y in height downTo 0) {
for (x in 0 .. width) {
print(visited[Pair(x,y)]?:".")
print("")
}
println()
}
}
fun moveTail(pos: Int) {
var top = when {
pos < tails.size-1 -> tails[pos+1]
else -> head
}
if (!tails[pos].touches(top)) {
tails[pos] = tails[pos].twang(top)
}
if (pos == 0) {
store(tails[pos])
} else {
moveTail(pos-1)
}
}
fun parseLine(line : String) {
var steps = line.split(" ")[1].toInt()
when (line.split(" ")[0]) {
"U" -> moveHead(Pair(0,1), steps)
"D" -> moveHead(Pair(0,-1), steps)
"R" -> moveHead(Pair(1,0), steps)
"L" -> moveHead(Pair(-1,0), steps)
else -> error("Invalid Move")
}
}
fun moveHead(change: Pair<Int, Int>, steps: Int) {
if (steps == 0) return
head = head.add(change)
moveTail(tails.size-1)
moveHead(change, steps-1)
}
fun go() {
val lines = readInput("dayNine")
lines.forEach{
parseLine(it)
}
println(visited.keys.size)
}
}
fun main() {
Day9(1).go()
Day9(9).go()
} | 0 | Kotlin | 0 | 1 | 3dcd590f971b6e9c064b444139d6442df034355b | 2,916 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/day05/solution.kt | bukajsytlos | 433,979,778 | false | {"Kotlin": 63913} | package day05
import java.io.File
import kotlin.math.abs
fun main() {
val segmentPattern = Regex("""(\d+),(\d+) -> (\d+),(\d+)""")
val inputLines = File("src/main/kotlin/day05/input.txt").readLines()
val segments = inputLines
.mapNotNull { segmentPattern.matchEntire(it) }
.map {
Segment(
Point(it.groupValues[1].toInt(), it.groupValues[2].toInt()),
Point(it.groupValues[3].toInt(), it.groupValues[4].toInt())
)
}
val dangerousVentCount = segments.asSequence()
.filter { it.isLateral() }
.dangerousVentCount()
println(dangerousVentCount)
val dangerousVentCount2 = segments.asSequence()
.dangerousVentCount()
println(dangerousVentCount2)
}
fun Sequence<Segment>.dangerousVentCount() = this
.map { it.getSegmentPoints() }
.flatten()
.groupBy { it }
.count { it.value.size > 1 }
data class Segment(val p1: Point, val p2: Point) {
fun isLateral(): Boolean = p1.x == p2.x || p1.y == p2.y
fun getSegmentPoints(): List<Point> {
val points = mutableListOf<Point>()
var lastPoint: Point = p1
for (i in 0..getLength()) {
points.add(lastPoint)
lastPoint += getDirectionVector()
}
return points
}
private fun getDirectionVector(): Vector {
val dx = p2.x - p1.x
val dy = p2.y - p1.y
return Vector(dx / getLength(), dy / getLength())
}
private fun getLength(): Int = maxOf(abs(p2.x - p1.x), abs(p2.y - p1.y))
}
data class Point(val x: Int, val y:Int) {
operator fun plus(vector: Vector): Point = Point(x + vector.dx, y + vector.dy)
}
data class Vector(val dx: Int, val dy: Int)
| 0 | Kotlin | 0 | 0 | f47d092399c3e395381406b7a0048c0795d332b9 | 1,739 | aoc-2021 | MIT License |
src/main/kotlin/aoc2023/day16/day16Solver.kt | Advent-of-Code-Netcompany-Unions | 726,531,711 | false | {"Kotlin": 94973} | package aoc2023.day16
import lib.*
suspend fun main() {
setupChallenge().solveChallenge()
}
fun setupChallenge(): Challenge<Array<Array<Char>>> {
return setup {
day(16)
year(2023)
//input("example.txt")
parser {
it.readLines().get2DArrayOfColumns()
}
partOne {
val res = it.traceBeam(Beam(0 to 0, CardinalDirection.East))
res.distinctBy { it.pos }.size.toString()
}
partTwo {
val dimensions = it.size - 1 to it.first().size - 1
val verticalRes = it.indices.flatMap {
listOf(
Beam(it to 0, CardinalDirection.South),
Beam(it to dimensions.second, CardinalDirection.North)
)
}
val horizontalRes = it.first().indices.flatMap {
listOf(
Beam(0 to it, CardinalDirection.East),
Beam(dimensions.first to it, CardinalDirection.West)
)
}
(verticalRes + horizontalRes).maxOf { beam -> it.traceBeam(beam).distinctBy { it.pos }.size }.toString()
}
}
}
data class Beam(var pos: Pair<Int, Int>, var direction: CardinalDirection)
fun Beam.move(): Beam {
return Beam(pos.adjacent(this.direction), this.direction)
}
fun Beam.withDirection(direction: CardinalDirection): Beam {
return Beam(this.pos, direction)
}
fun Beam.key(): String {
return "${this.pos.first}:${this.pos.second}-${this.direction}"
}
val solutions = mutableMapOf<String, Set<Beam>>()
fun Array<Array<Char>>.traceBeam(beam: Beam): Set<Beam> {
val toVisit = mutableSetOf(beam)
val res = mutableSetOf<Beam>()
while (toVisit.isNotEmpty()) {
val next = toVisit.first()
toVisit.remove(next)
/*if (solutions.containsKey(next.key())) {
res.addAll(solutions[next.key()]!!)
} else*/ if (isValidCoord(next.pos) && next !in res) {
res.add(next)
when (this[next.pos.first][next.pos.second]) {
'.' -> toVisit.add(next.move())
'\\' -> {
next.direction = when (next.direction) {
CardinalDirection.North -> CardinalDirection.West
CardinalDirection.East -> CardinalDirection.South
CardinalDirection.West -> CardinalDirection.North
CardinalDirection.South -> CardinalDirection.East
}
toVisit.add(next.move())
}
'/' -> {
next.direction = when (next.direction) {
CardinalDirection.North -> CardinalDirection.East
CardinalDirection.West -> CardinalDirection.South
CardinalDirection.East -> CardinalDirection.North
CardinalDirection.South -> CardinalDirection.West
}
toVisit.add(next.move())
}
'|' -> {
when (next.direction) {
CardinalDirection.West, CardinalDirection.East -> {
toVisit.add(next.withDirection(CardinalDirection.North))
toVisit.add(next.withDirection(CardinalDirection.South))
}
else -> toVisit.add(next.move())
}
}
'-' -> {
when (next.direction) {
CardinalDirection.South, CardinalDirection.North -> {
toVisit.add(next.withDirection(CardinalDirection.East))
toVisit.add(next.withDirection(CardinalDirection.West))
}
else -> toVisit.add(next.move())
}
}
}
}
}
//solutions[beam.key()] = res
return res
} | 0 | Kotlin | 0 | 0 | a77584ee012d5b1b0d28501ae42d7b10d28bf070 | 4,018 | AoC-2023-DDJ | MIT License |
src/main/kotlin/days/Day14.kt | julia-kim | 569,976,303 | false | null | package days
import Point
import readInput
fun main() {
fun getRockCoordinates(input: List<String>): List<Point> {
val pourPoint = Point(500, 0)
val rocks = mutableListOf(pourPoint)
input.forEach { line ->
// 498,4 -> 498,6 -> 496,6
val paths = line.split(" -> ")
.map { point -> point.split(",").let { Point(it.first().toInt(), it.last().toInt()) } }
rocks.addAll(paths)
paths.windowed(2).forEach {
val (firstPoint, secondPoint) = it.map { coords -> coords.copy() }
var dx = secondPoint.x - firstPoint.x
var dy = secondPoint.y - firstPoint.y
while (dx != 0) {
if (dx < 0) rocks.add(Point(firstPoint.x--, firstPoint.y))
else rocks.add(Point(firstPoint.x++, firstPoint.y))
dx = secondPoint.x - firstPoint.x
}
while (dy != 0) {
if (dy < 0) rocks.add(Point(firstPoint.x, firstPoint.y--))
else rocks.add(Point(firstPoint.x, firstPoint.y++))
dy = secondPoint.y - firstPoint.y
}
}
}
return rocks.distinctBy { it.x to it.y }
}
fun visualizeCave(rocks: List<Point>, sand: List<Point>) {
var rows = rocks.minOf { it.y }
while (rows <= rocks.maxOf { it.y } + 2) {
var cols = minOf(rocks.minOf { it.x }, sand.minOf { it.x })
while (cols <= maxOf(rocks.maxOf { it.x }, sand.maxOf { it.x })) {
when {
(rows == 500 && cols == 0) -> print("+")
(sand.contains(Point(cols, rows))) -> print("o")
(rocks.contains(Point(cols, rows))) -> print("#")
else -> print(".")
}
cols++
}
println()
rows++
}
}
fun dropSand(grain: Point, cave: MutableList<Point>, sand: MutableList<Point>, caveBottom: Int? = null): Boolean {
cave.addAll(sand)
val oneBelow = Point(grain.x, grain.y + 1)
val leftBelow = Point(grain.x - 1, grain.y + 1)
val rightBelow = Point(grain.x + 1, grain.y + 1)
when {
(oneBelow.y == caveBottom) -> {
sand.add(grain)
return true
}
!cave.contains(oneBelow) -> dropSand(oneBelow, cave, sand, caveBottom)
!cave.contains(leftBelow) -> dropSand(leftBelow, cave, sand, caveBottom)
!cave.contains(rightBelow) -> dropSand(rightBelow, cave, sand, caveBottom)
else -> {
sand.add(grain); return true
}
}
return true
}
fun part1(input: List<String>): Int {
val rocks = getRockCoordinates(input)
val restingSand = mutableListOf<Point>()
var sandCount = 0
try {
while (sandCount < Int.MAX_VALUE) {
if (dropSand(Point(500, 0), rocks.toMutableList(), restingSand)) sandCount++
}
} catch (e: StackOverflowError) {
visualizeCave(rocks, restingSand)
return sandCount
}
return sandCount
}
fun part2(input: List<String>): Int {
val rocks = getRockCoordinates(input)
val restingSand = mutableListOf<Point>()
val caveBottom = rocks.maxOf { it.y } + 2
val pourPoint = Point(500, 0)
while (!restingSand.contains(pourPoint)) {
dropSand(pourPoint, rocks.toMutableList(), restingSand, caveBottom)
}
visualizeCave(rocks, restingSand)
return restingSand.size
}
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 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 3,915 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2022/day13/Day13.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day13
import com.jacobhyphenated.advent2022.Day
/**
* Day 13: Distress Signal
*
* Packets are coming in out of order.
* Packets come in pairs (one on each line of the input).
*
* A packet consists of a number or list of packets, ex:
* [[1],[2,3,4]] turns into Packet[Packet[Packet[1]], Packet[Packet[2],Packet[3],Packet[4]]]
* [[1],4] turns into Packet[Packet[Packet[1]], Packet[4]]
*
*/
class Day13: Day<List<Pair<Packet, Packet>>> {
override fun getInput(): List<Pair<Packet, Packet>> {
return parseInput(readInputFile("day13"))
}
/**
* Observe each pair of packets. Find the index (1 based) in the list of
* all the packets that are in the correct order.
* Return the sum of those indexes
*/
override fun part1(input: List<Pair<Packet, Packet>>): Int {
return input.mapIndexed { index, (lhs, rhs) ->
if (lhs <= rhs) { index + 1 } else { 0 }
}.sum()
}
/**
* Take all packets and put them in a single list. Add two marker packets: [[2]] and [[6]]
* Put the packets in the correct order and find the (1 based) index of the marker packets.
* Return the product of both marker indexes
*/
override fun part2(input: List<Pair<Packet, Packet>>): Any {
val (marker1, _) = parsePacket("[[2]]")
val (marker2, _) = parsePacket("[[6]]")
val allPackets = input.flatMap { listOf(it.first, it.second) } + listOf(marker1, marker2)
val sortedPackets = allPackets.sorted()
return (sortedPackets.indexOf(marker1) + 1) * (sortedPackets.indexOf(marker2) + 1)
}
fun parseInput(input: String): List<Pair<Packet, Packet>> {
return input.split("\n\n").map { pairs ->
val (lhs, rhs) = pairs.lines().map { parsePacket(it).first }
Pair(lhs, rhs)
}
}
/**
* Recursive function to parse the packet out of the string.
* Nested [] get their own recursive call.
*
* @param packetString The entire packet string
* @param index the index to start the parsing at (defaults to 1 - all packets start with '[')
* @return A pair tuple consisting of the parsed packet
* and the index of the lasted visited location in the overall packetString
*/
private fun parsePacket(packetString: String, index: Int = 1): Pair<Packet, Int> {
var buffer = ""
var i = index
val packets = mutableListOf<Packet>()
// when we hit the close bracket, this parse function is done
while (packetString[i] != ']') {
if (packetString[i] == '[') {
// we are opening a new sub packet - recursively call this method
val (p, newIndex) = parsePacket(packetString, i+1)
packets.add(p)
i = newIndex
continue
}
if (packetString[i] == ',') {
// On a comma, move to the next item in the list (clear the buffer if necessary)
if (buffer.isNotEmpty()) {
packets.add(Packet(buffer.toInt(), null))
buffer = ""
}
i++
continue
}
// Numbers are stored in the buffer (as multi digit numbers are valid)
buffer += packetString[i]
i++
}
if (buffer.isNotEmpty()) {
packets.add(Packet(buffer.toInt(), null))
}
return Pair(Packet(null, packets), i + 1)
}
}
class Packet (
private val value: Int?,
private val packets: List<Packet>?
) : Comparable<Packet> {
/**
* To check order, look from left to right in each packet
* If the value is a number on both, the left should be less than the right
* If one of the two packets has a number, convert that number to a single value list
* If both are lists, go from left to right comparing each value in the list (left-hand side should be smaller)
* - if the left-hand side runs out of values first, they are in the correct order
* - if the right-hand side runs out of values first, they are out of order
*/
override fun compareTo(other: Packet): Int {
if (this.value != null && other.value != null) {
return this.value.compareTo(other.value)
}
val listA = this.packets ?: listOf(Packet(this.value!!, null))
val listB = other.packets ?: listOf(Packet(other.value!!, null))
for (i in listA.indices) {
if (i >= listB.size) { return 1 }
val cmp = listA[i].compareTo(listB[i])
if (cmp != 0) { return cmp }
}
if (listA.size < listB.size) {
return - 1
}
return 0
}
/**
* We could probably cheat and just do reference equivalence for this problem
* But here is a real equals method implementation
*/
override fun equals(other: Any?): Boolean {
if (this === other) { return true }
if (other !is Packet) { return false }
if (other.value != null && this.value != null && this.value == other.value) {
return true
}
if (other.packets != null && this.packets != null){
if (other.packets.size != this.packets.size) { return false }
return other.packets == this.packets
}
return false
}
// The IDE generated this one (It's always recommended to have hashCode if you have equals)
override fun hashCode(): Int {
val result = value ?: 0
return 31 * result + (packets?.hashCode() ?: 0)
}
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 5,666 | advent2022 | The Unlicense |
src/Day04v2.kt | vi-quang | 573,647,667 | false | {"Kotlin": 49703} |
fun main() {
class Elf(range: String) {
init {
val token = range.split("-")
val (rangeMin, rangeMax) = token[0].toInt() to token[1].toInt()
this.range = rangeMin .. rangeMax
}
val range : ClosedRange<Int>
}
fun ClosedRange<Int>.length() : Int {
return (endInclusive - start)
}
fun Elf.fullyContainsOrIsFullyContained(other : Elf) : Boolean {
val otherIsLarger = other.range.length() > range.length()
val (smallRange, largeRange) = if (otherIsLarger) range to other.range else other.range to range
return largeRange.contains(smallRange.start) && largeRange.contains(smallRange.endInclusive)
}
fun Elf.hasIntersection(other : Elf) : Boolean {
val otherIsLarger = other.range.length() > range.length()
val (smallRange, largeRange) = if (otherIsLarger) range to other.range else other.range to range
return largeRange.contains(smallRange.start) || largeRange.contains(smallRange.endInclusive)
}
fun createElfPairList(input: List<String>) : MutableList<Pair<Elf, Elf>> {
val elfPairList = mutableListOf<Pair<Elf, Elf>>()
for (line in input) {
val token = line.split(",")
val pair = (Elf(token[0]) to Elf(token[1]))
elfPairList.add(pair)
}
return elfPairList
}
fun part1(input: List<String>): Int {
val elfPairList = createElfPairList(input)
val resultList = mutableListOf<Pair<Elf, Elf>>()
for (pair in elfPairList) {
if (pair.first.fullyContainsOrIsFullyContained(pair.second)) {
resultList.add(pair)
}
}
return resultList.size
}
fun part2(input: List<String>): Int {
val elfPairList = createElfPairList(input)
val resultList = mutableListOf<Pair<Elf, Elf>>()
for (pair in elfPairList) {
if (pair.first.hasIntersection(pair.second)) {
resultList.add(pair)
}
}
return resultList.size
}
val input = readInput(4)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | ae153c99b58ba3749f16b3fe53f06a4b557105d3 | 2,181 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | import java.lang.RuntimeException
/**
* [Day03](https://adventofcode.com/2022/day/3)
*/
fun main() {
fun toCompartments(input: List<String>): List<Pair<String, String>> = input.map {
it.substring(0 until it.length / 2) to it.substring(it.length / 2 until it.length)
}
fun toIndex(c: Char): Int = if (c in 'a'..'z') c - 'a' else c - 'A' + 26
fun part1(input: List<String>): Int {
return toCompartments(input).map { (f, s) ->
val first = Array(52) { 0 }
val second = Array(52) { 0 }
for (i in f.indices) {
first[toIndex(f[i])]++
second[toIndex(s[i])]++
}
for (i in first.indices) {
if (first[i] > 0 && second[i] > 0) {
return@map i + 1
}
}
0
}.sum()
}
fun part2(input: List<String>): Int {
val conv = input.map {
it.toList().sorted().distinct()
}.map {
it.fold(0L) { acc, b -> acc or (1L shl toIndex(b)) }
}
var result = 0
for (i in conv.indices step 3) {
result += (conv[i] and conv[i + 1] and conv[i + 2]).countTrailingZeroBits() + 1
}
return result
}
// 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))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 1,546 | aoc-in-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/hopkins/aoc/day6/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day6
import java.io.File
const val debug = true
const val part = 2
/** Advent of Code 2023: Day 6 */
fun main() {
val inputFile = File("input/input6.txt")
val lines: List<String> = inputFile.readLines()
val times = readValues(lines[0])
val distances = readValues(lines[1])
if (debug) {
println("Times: $times")
println("Distances: $distances")
}
val ways: List<Int> =
times.zip(distances)
.map { (time, distance) -> findWays(time, distance) }
if (debug) {
println("Ways: $ways")
}
val result: Int =
ways.fold(1) { acc, item -> acc * item }
print("Result: $result") // 588588
}
/**
* Returns the number of ways in which the boat can travel the distance.
*
* Start with holding the button for 1 second, then 2 seconds, etc. then calculate
* the distance travelled in the time remaining.
*/
fun findWays(totalTime: Long, distance: Long): Int {
val range = LongRange(1, totalTime - 1)
val start = range.first { calculateDistanceTravelled(it, totalTime) > distance }
val end = range.last { calculateDistanceTravelled(it, totalTime) > distance }
return LongRange(start, end).count()
}
/** Calculate the distance traveled given the time held and total time. */
fun calculateDistanceTravelled(timeHeld: Long, totalTime: Long): Long {
// Speed = 1 mm/s for each second we hold the button
val speed = timeHeld
// Distance (mm) = Speed (mm/s) * Time remaining (s)
return speed * (totalTime - timeHeld)
}
/** Returns list of integers after the ":" separated by 1 or more spaces. */
fun readValues(line: String): List<Long> {
val (_, values) = line.split(":")
if (part == 1) {
return values.split(" ").filterNot { it.trim().isBlank() }.map { it.toLong() }
} else {
return listOf(values.split(" ").filterNot { it.trim().isBlank() }.joinToString(separator = "").toLong())
}
} | 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 1,960 | aoc2023 | MIT License |
src/Day08.kt | ahmadshabib | 573,197,533 | false | {"Kotlin": 13577} | fun main() {
val input = readInput("Day08")
val treesMap = Array(input.size) { Array(input[0].length) { 0 } }
input.forEachIndexed { index, s ->
s.toCharArray().forEachIndexed { columnIndex, c ->
treesMap[index][columnIndex] = c.toString().toInt()
}
}
var numberOfVisible = ((input.size - 1) * 2) + ((input[0].length - 1) * 2)
//First one
for (row in 1 until input.size - 1) {
for (column in 1 until input[0].length - 1) {
if ((treesMap[row][column] > 0) and (checkVisibleFromRight(column, treesMap[row]) ||
checkVisibleFromLeft(column, treesMap[row]) ||
checkVisibleFromTop(row, column, treesMap) ||
checkVisibleFromBottom(row, column, treesMap))
) {
numberOfVisible++
}
}
}
// Second One
var maxTree = 0
for (row in 1 until input.size - 1) {
for (column in 1 until input[0].length - 1) {
val value = maxVisibleFromRight(column, treesMap[row]) * maxVisibleFromBottom(
row,
column,
treesMap
) * maxVisibleFromTop(row, column, treesMap) * maxVisibleFromLeft(column, treesMap[row])
if (value > maxTree) {
maxTree = value
}
}
}
println(maxTree)
}
private fun checkVisibleFromRight(column: Int, treesMap: Array<Int>): Boolean {
val currentTree = treesMap[column]
val values = treesMap.drop(column + 1)
val currentMax = values.max()
if (currentTree > currentMax) {
return true
}
return false
}
private fun checkVisibleFromLeft(column: Int, treesMap: Array<Int>): Boolean {
val currentTree = treesMap[column]
val values = treesMap.dropLast(treesMap.size - column)
val currentMax = values.max()
if (currentTree > currentMax) {
return true
}
return false
}
private fun checkVisibleFromTop(raw: Int, column: Int, treesMap: Array<Array<Int>>): Boolean {
val currentTree = treesMap[raw][column]
val values = treesMap.map { it[column] }.dropLast(treesMap.size - raw)
val currentMax = values.max()
if (currentTree > currentMax) {
return true
}
return false
}
private fun checkVisibleFromBottom(raw: Int, column: Int, treesMap: Array<Array<Int>>): Boolean {
val currentTree = treesMap[raw][column]
val values = treesMap.map { it[column] }.drop(raw + 1)
val currentMax = values.max()
if (currentTree > currentMax) {
return true
}
return false
}
private fun maxVisibleFromRight(column: Int, treesMap: Array<Int>): Int {
val currentTree = treesMap[column]
val values = treesMap.drop(column + 1)
var distance = 0
for (i in values) {
if (currentTree > i) {
distance++
} else {
distance++
break
}
}
return distance
}
private fun maxVisibleFromLeft(column: Int, treesMap: Array<Int>): Int {
val currentTree = treesMap[column]
val values = treesMap.dropLast(treesMap.size - column)
var distance = 0
for (i in values.size - 1 downTo 0) {
if (currentTree > values[i]) {
distance++
} else {
distance++
break
}
}
return distance
}
private fun maxVisibleFromTop(raw: Int, column: Int, treesMap: Array<Array<Int>>): Int {
val currentTree = treesMap[raw][column]
val values = treesMap.map { it[column] }.dropLast(treesMap.size - raw)
var distance = 0
for (i in values.size - 1 downTo 0) {
if (currentTree > values[i]) {
distance++
} else {
distance++
break
}
}
return distance
}
private fun maxVisibleFromBottom(raw: Int, column: Int, treesMap: Array<Array<Int>>): Int {
val currentTree = treesMap[raw][column]
val values = treesMap.map { it[column] }.drop(raw + 1)
var distance = 0
for (i in values) {
if (currentTree > i) {
distance++
} else {
distance++
break
}
}
return distance
}
| 0 | Kotlin | 0 | 0 | 81db1b287ca3f6cae95dde41919bfa539ac3adb5 | 4,180 | advent-of-code-kotlin-22 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/single_element/SingleElement.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.single_element
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/discuss/interview-question/346626/google-phone-screen-single-element
*
* Given an array nums of length n. All elements appear in pairs except one of them. Find this single element that appears alone.
* Pairs of the same element cannot be adjacent:
* [2, 2, 1, 2, 2] // ok
* [2, 2, 2, 2, 1] // not allowed
*/
class SingleElementTests {
// private fun Array<Int>.findSingleElement() = this.slidingFind()
private fun Array<Int>.findSingleElement() = binaryFind(this)
@Test fun `find single element that appears alone in an array of pairs`() {
arrayOf(1, 2, 2).findSingleElement() shouldEqual 1
arrayOf(2, 2, 1, 2, 2).findSingleElement() shouldEqual 1
arrayOf(2, 2, 1).findSingleElement() shouldEqual 1
arrayOf(2, 2, 1, 1, 9, 9, 5, 2, 2).findSingleElement() shouldEqual 5
}
}
private fun binaryFind(a: Array<Int>): Int {
if (a[a.size - 1] != a[a.size - 2]) return a[a.size - 1]
val size = a.size / 2
var from = 0
var to = size - 1
while (true) {
val mid = (from + to) / 2
when {
a.isDiffAt(from) -> return a.firstAt(from)
a.isDiffAt(mid) -> to = mid
else -> from = mid + 1
}
}
}
private fun Array<Int>.firstAt(index: Int) = this[index * 2]
private fun Array<Int>.secondAt(index: Int) = this[index * 2 + 1]
private fun Array<Int>.isDiffAt(index: Int) = firstAt(index) != secondAt(index)
private fun Array<Int>.slidingFind(): Int {
slidingWindow { n1, n2 -> if (n1 != n2) return n1 }
error("")
}
private inline fun Array<Int>.slidingWindow(f: (Int, Int?) -> Unit) {
var i1 = 0
while (i1 < size) {
val i2 = i1 + 1
f(this[i1], if (i2 == size) null else this[i2])
i1 += 2
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,892 | katas | The Unlicense |
src/day09/Day09Answer2.kt | IThinkIGottaGo | 572,833,474 | false | {"Kotlin": 72162} | package day09
import day09.Directions.*
import readInput
import kotlin.math.abs
/**
* Answers from [Advent of Code 2022 Day 9 | Kotlin](https://youtu.be/ShU9dNUa_3g)
*/
enum class Directions {
UP,
DOWN,
LEFT,
RIGHT,
}
data class Movement(val direction: Directions) {
fun move(v: Vec2): Vec2 {
return when (direction) {
UP -> Vec2(v.x, v.y + 1)
DOWN -> Vec2(v.x, v.y - 1)
LEFT -> Vec2(v.x - 1, v.y)
RIGHT -> Vec2(v.x + 1, v.y)
}
}
}
fun String.toMovements(): List<Movement> {
val (dir, len) = split(" ")
val direction = when (dir) {
"U" -> UP
"D" -> DOWN
"L" -> LEFT
"R" -> RIGHT
else -> error("what")
}
return List(len.toInt()) { Movement(direction) }
}
val input = readInput("day09")
val instructions = input.flatMap { it.toMovements() }
fun main() {
part1()
part2()
}
fun part1() {
val visited = mutableSetOf<Vec2>()
var head = Vec2(0, 0)
var tail = Vec2(0, 0)
visited += tail
for (instruction in instructions) {
head = instruction.move(head)
if (head adjacentTo tail) continue // or even continue the outer loop!
val offset = head - tail
val normalizedOffset = Vec2(
offset.x.coerceIn(-1..1),
offset.y.coerceIn(-1..1)
)
tail += normalizedOffset
visited += tail
}
println(visited.size) // 5981
}
fun part2() {
val visited = hashSetOf<Vec2>()
val snake = MutableList(10) { Vec2(0, 0) }
visited += Vec2(0, 0)
for (instruction in instructions) {
val head = snake[0]
snake[0] = instruction.move(head)
for (headIdx in 0 until 9) {
val curTail = snake[headIdx + 1]
val curHead = snake[headIdx]
if (curTail adjacentTo curHead) continue // or even continue the outer loop!
val offset = curHead - curTail
val normalizedOffset = Vec2(
offset.x.coerceIn(-1..1),
offset.y.coerceIn(-1..1)
)
val newTail = curTail + normalizedOffset
snake[headIdx + 1] = newTail
}
visited += snake[snake.lastIndex]
}
println(visited.size) // 2352
}
data class Vec2(val x: Int, val y: Int) {
infix fun adjacentTo(other: Vec2): Boolean {
return abs(x - other.x) <= 1 && abs(y - other.y) <= 1
}
operator fun minus(other: Vec2): Vec2 {
return Vec2(this.x - other.x, this.y - other.y)
}
operator fun plus(other: Vec2): Vec2 {
return Vec2(x + other.x, y + other.y)
}
} | 0 | Kotlin | 0 | 0 | 967812138a7ee110a63e1950cae9a799166a6ba8 | 2,660 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/kotlin/com/resurtm/aoc2023/day23/Solution.kt | resurtm | 726,078,755 | false | {"Kotlin": 119665} | package com.resurtm.aoc2023.day23
import kotlin.math.abs
import kotlin.math.max
fun launchDay23(testCase: String) {
println("Day 23, part 1: ${Grid.readInput(testCase).solvePart1()}")
// println("Day 23, part 2 (slow): ${Grid.readInput(testCase).solvePart2Slow()}")
// println("Day 23, part 2 (fast): ${Grid.readInput(testCase).solvePart2Fast()}")
println("Day 23, part 2 (best): ${Grid.readInput(testCase).solvePart2Best()}")
}
internal data class Grid(
val grid: List<List<Node>>,
val start: Pos,
val end: Pos
) {
fun solvePart1(): Int = findLongestPath().first
fun solvePart2Slow(): Int = findLongestPath(ignoreDirs = true).first
fun solvePart2Fast(): Int = findLongestPath(useIntersections = true).first
fun solvePart2Best(): Int {
val emptyPositions = mutableSetOf<Pos>()
grid.forEachIndexed { row, items ->
items.forEachIndexed { col, item ->
if (item.ch in emptyChars)
emptyPositions.add(Pos(row, col))
}
}
val nonPacked = mutableMapOf<Pos, MutableList<Pos>>()
emptyPositions.forEach { pos ->
directions.forEach { dir ->
val lst = nonPacked[pos]
val add = Pos(pos.row + dir.first.row, pos.col + dir.first.col)
if (add.row >= 1 && add.col >= 1 && add.row <= grid.size - 2 && add.col <= grid[0].size - 2) {
if (lst == null) nonPacked[pos] = mutableListOf(add)
else lst.add(add)
}
}
}
val packed = mutableMapOf<Pos, List<Pair<Pos, Int>>>()
emptyPositions.forEach { pos0 ->
packed[pos0] = findNextPositionsV2(pos0).map { pos1 ->
Pair(pos1, pos1.dist(pos0))
}
}
// packed.forEach { println(it) }
return search(packed, start, end, 0, mutableSetOf())
}
private fun search(
packed: Map<Pos, List<Pair<Pos, Int>>>,
pos: Pos,
stop: Pos,
dist: Int,
history: MutableSet<Pos>,
): Int {
if (pos == stop) return dist
history.add(pos)
val best = (packed[pos] ?: emptyList()).map { v ->
if (v.first !in history) {
search(packed, v.first, stop, v.second + dist, history)
} else {
0
}
}.max()
val bestRes = max(0, best)
// println(bestRes)
history.remove(pos)
return bestRes
}
private fun findLongestPath(
ignoreDirs: Boolean = false,
useIntersections: Boolean = false,
): Pair<Int, Path> {
val paths = mutableListOf(
Path(mutableListOf(start.copy())),
)
var maxSize = 0
var maxPath = paths.first()
while (paths.size > 0) {
var pathIdx = 0
while (pathIdx < paths.size) {
val path = paths[pathIdx]
val nexts = if (useIntersections) findNextPositionsV2(path.points.last(), path.points)
else findNextPositionsV1(path.points.last(), path.points, ignoreDirs)
if (nexts.isEmpty()) {
if (path.points.last() == end && path.size() > maxSize) {
maxSize = path.size()
maxPath = path
// println(maxSize)
}
paths.removeAt(pathIdx)
continue
}
for (nextIdx in nexts.indices) {
val newPoints = path.points.map { it.copy() } + nexts[nextIdx]
paths.add(Path(newPoints.toMutableList()))
}
if (nexts.isNotEmpty()) {
paths.removeAt(pathIdx)
pathIdx--
}
pathIdx++
}
}
// printGrid(maxPath.points)
return Pair(maxSize, maxPath)
}
internal fun findNextPositionsV2(
p: Pos,
exclude: Collection<Pos> = emptyList(),
): List<Pos> {
val res = mutableListOf<Pos>()
// down dir
for (row in p.row + 1..<grid.size) {
if (
grid[row][p.col].ch in emptyChars &&
(grid[row][p.col - 1].ch in emptyChars || grid[row][p.col + 1].ch in emptyChars)
) {
res.add(Pos(row, p.col))
break
}
if (grid[row][p.col].ch !in emptyChars) {
if (Pos(row - 1, p.col) != p)
res.add(Pos(row - 1, p.col))
break
}
if (row == grid.size - 1) {
res.add(Pos(row, p.col))
}
}
// up dir
for (row in p.row - 1 downTo 0) {
if (
grid[row][p.col].ch in emptyChars &&
(grid[row][p.col - 1].ch in emptyChars || grid[row][p.col + 1].ch in emptyChars)
) {
res.add(Pos(row, p.col))
break
}
if (grid[row][p.col].ch !in emptyChars) {
if (Pos(row + 1, p.col) != p)
res.add(Pos(row + 1, p.col))
break
}
if (row == 0) {
res.add(Pos(row, p.col))
}
}
// right dir
for (col in p.col + 1..<grid[0].size) {
if (
grid[p.row][col].ch in emptyChars &&
(grid[p.row - 1][col].ch in emptyChars || grid[p.row + 1][col].ch in emptyChars)
) {
res.add(Pos(p.row, col))
break
}
if (grid[p.row][col].ch !in emptyChars) {
if (Pos(p.row, col - 1) != p)
res.add(Pos(p.row, col - 1))
break
}
if (col == grid[0].size - 1) {
res.add(Pos(p.row, col))
}
}
// left dir
for (col in p.col - 1 downTo 0) {
if (
grid[p.row][col].ch in emptyChars &&
(grid[p.row - 1][col].ch in emptyChars || grid[p.row + 1][col].ch in emptyChars)
) {
res.add(Pos(p.row, col))
break
}
if (grid[p.row][col].ch !in emptyChars) {
if (Pos(p.row, col + 1) != p)
res.add(Pos(p.row, col + 1))
break
}
if (col == 0) {
res.add(Pos(p.row, col))
}
}
return res.filter { !exclude.contains(it) }.toSet().toList()
}
private fun findNextPositionsV1(
pos: Pos,
exclude: Collection<Pos> = emptySet(),
ignoreDirs: Boolean = false,
): List<Pos> = directions
.asSequence()
.map {
val p = it.first
Pair(
it.first.copy(row = pos.row + p.row, col = pos.col + p.col),
it.second
)
}
.filter {
val p = it.first
p.row >= 0L && p.col >= 0L && p.row <= grid.size - 1L && p.col <= grid[0].size - 1L
}
.filter {
val ch = grid[it.first.row][it.first.col].ch
if (ignoreDirs) ch in emptyChars else ch != it.second && ch in emptyChars
}
.filter { it.first !in exclude }
.map { it.first }
.toList()
fun printGrid(maxPath: List<Pos> = listOf()) {
println("----------")
for (row in grid.indices) {
for (col in grid[row].indices) {
print(if (maxPath.contains(Pos(row, col))) 'O' else grid[row][col].ch)
}
println()
}
}
companion object {
private val emptyChars = arrayOf('.', '^', '>', 'v', '<')
private val directions = arrayOf(
Pair(Pos(-1, 0), 'v'),
Pair(Pos(1, 0), '^'),
Pair(Pos(0, -1), '>'),
Pair(Pos(0, 1), '<'),
)
internal fun readInput(testCase: String): Grid {
val reader =
object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader()
?: throw Exception("Cannot read an input, probably it is invalid")
val grid = mutableListOf<List<Node>>()
while (true) {
val rawLine = reader.readLine()
?: break
if (rawLine.trim().isEmpty())
continue
val row = rawLine.trim().toList().map { Node(it) }
grid.add(row)
}
val lastRow = grid.size - 1
val start = Pos(row = 0, col = grid[0].indexOfFirst { it.ch == '.' })
val end = Pos(row = lastRow, col = grid[lastRow].indexOfFirst { it.ch == '.' })
return Grid(grid, start, end)
}
}
}
internal data class Node(val ch: Char)
internal data class Pos(val row: Int, val col: Int) {
internal fun dist(some: Pos) = abs(some.row - this.row) + abs(some.col - this.col)
}
internal data class Path(val points: MutableList<Pos> = mutableListOf()) {
internal fun size(): Int {
var res = 0
for (idx in 0..points.size - 2) {
res += points[idx].dist(points[idx + 1])
}
return res
}
}
| 0 | Kotlin | 0 | 0 | fb8da6c246b0e2ffadb046401502f945a82cfed9 | 9,357 | advent-of-code-2023 | MIT License |
kotlin/src/com/leetcode/1314_MatrixBlockSum.kt | programmerr47 | 248,502,040 | false | null | package com.leetcode
import java.lang.Integer.min
import kotlin.math.max
//Partial sum matrix O(n * m)
private class Solution1314 {
fun matrixBlockSum(mat: Array<IntArray>, k: Int): Array<IntArray> {
val partCols = fillPartColumns(mat, k)
val result = Array(mat.size) { IntArray(mat[it].size) }
val prev = Prev()
mat.forEachIndexed { i, row ->
val indexes = if (i % 2 == 0) row.indices else row.indices.reversed()
indexes.forEach { j ->
prev.result = calculateWindow(mat, partCols, k, i, j, prev)
prev.i = i
prev.j = j
result[i][j] = prev.result
}
}
return result
}
private fun fillPartColumns(mat: Array<IntArray>, k: Int): Array<IntArray> {
val result = Array(mat.size) { IntArray(mat[it].size) }
val colCount = mat[0].size
var window = 0
for (j in 0 until colCount) {
mat.indices.forEach { i ->
if (i == 0) {
val kMax = min(k, mat.lastIndex)
for (ki in 0..kMax) {
window += mat[ki][j]
}
} else {
val removeI = i - k - 1
if (removeI >= 0) {
window -= mat[removeI][j]
}
val addI = i + k
if (addI < mat.size) {
window += mat[addI][j]
}
}
result[i][j] = window
}
window = 0
}
return result
}
private fun calculateWindow(mat: Array<IntArray>, partCols: Array<IntArray>, k: Int, i: Int, j: Int, prev: Prev): Int {
var result = 0
if (prev.result == 0) {
val jMin = max(j - k, 0)
val jMax = min(j + k, mat[i].lastIndex)
for (kj in jMin..jMax) {
result += partCols[i][kj]
}
} else {
result = prev.result
if (prev.i < i) {
if (prev.i - k >= 0) {
result -= rowSum(mat, k, prev.i - k, j)
}
if (i + k <= mat.lastIndex) {
result += rowSum(mat, k, i + k, j)
}
} else if (prev.j < j) {
if (prev.j - k >= 0) {
result -= partCols[i][prev.j - k]
}
if (j + k <= mat[i].lastIndex) {
result += partCols[i][j + k]
}
} else if (prev.j > j) {
if (prev.j + k <= mat[i].lastIndex) {
result -= partCols[i][prev.j + k]
}
if (j - k >= 0) {
result += partCols[i][j - k]
}
}
}
return result
}
private fun rowSum(mat: Array<IntArray>, k: Int, i: Int, j: Int): Int {
var result = 0
val jMin = max(j - k, 0)
val jMax = min(j + k, mat[i].lastIndex)
for (kj in jMin..jMax) {
result += mat[i][kj]
}
return result
}
private data class Prev(
var result: Int = 0,
var i: Int = -1,
var j: Int = -1
)
}
//Sliding window O(n * m * k)
private class Solution1314old2 {
fun matrixBlockSum(mat: Array<IntArray>, k: Int): Array<IntArray> {
val result = Array(mat.size) { IntArray(mat[it].size) }
var prevRes = 0
var prevI = -1
var prevJ = -1
mat.forEachIndexed { i, row ->
val indexes = if (i % 2 == 0) row.indices else row.indices.reversed()
indexes.forEach { j ->
prevRes = calculateWindow(mat, k, i, j, prevI, prevJ, prevRes)
prevI = i
prevJ = j
result[i][j] = prevRes
}
}
return result
}
private fun calculateWindow(mat: Array<IntArray>, k: Int, i: Int, j: Int, prevI: Int, prevJ: Int, prevRes: Int): Int {
var result = 0
if (prevRes == 0) {
val iMin = max(i - k, 0)
val iMax = min(i + k, mat.lastIndex)
for (ki in iMin..iMax) {
result += rowSum(mat, k, ki, j)
}
} else {
result = prevRes
if (prevI < i) {
if (prevI - k >= 0) {
result -= rowSum(mat, k, prevI - k, j)
}
if (i + k <= mat.lastIndex) {
result += rowSum(mat, k, i + k, j)
}
} else if (prevJ < j) {
if (prevJ - k >= 0) {
result -= colSum(mat, k, i, prevJ - k)
}
if (j + k <= mat[i].lastIndex) {
result += colSum(mat, k, i, j + k)
}
} else if (prevJ > j) {
if (prevJ + k <= mat[i].lastIndex) {
result -= colSum(mat, k, i, prevJ + k)
}
if (j - k >= 0) {
result += colSum(mat, k, i, j - k)
}
}
}
return result
}
private fun rowSum(mat: Array<IntArray>, k: Int, i: Int, j: Int): Int {
var result = 0
val jMin = max(j - k, 0)
val jMax = min(j + k, mat[i].lastIndex)
for (kj in jMin..jMax) {
result += mat[i][kj]
}
return result
}
private fun colSum(mat: Array<IntArray>, k: Int, i: Int, j: Int): Int {
var result = 0
val iMin = max(i - k, 0)
val iMax = min(i + k, mat.lastIndex)
for (ki in iMin..iMax) {
result += mat[ki][j]
}
return result
}
}
//Straight solution: O(n * m * (k^2))
private class Solution1314old1 {
fun matrixBlockSum(mat: Array<IntArray>, k: Int): Array<IntArray> {
val result = Array(mat.size) { IntArray(mat[it].size) }
mat.forEachIndexed { i, row ->
row.forEachIndexed { j, _ ->
result[i][j] = calculateWindow(mat, k, i, j)
}
}
return result
}
private fun calculateWindow(mat: Array<IntArray>, k: Int, i: Int, j: Int): Int {
val iMin = max(i - k, 0)
val iMax = min(i + k, mat.lastIndex)
var result = 0
for (ki in iMin..iMax) {
val jMin = max(j - k, 0)
val jMax = min(j + k, mat[ki].lastIndex)
for (kj in jMin..jMax) {
result += mat[ki][kj]
}
}
return result
}
}
fun main() {
println(Solution1314().matrixBlockSum(arrayOf(
intArrayOf(1,2,3),
intArrayOf(4,5,6),
intArrayOf(7,8,9)
), 1).joinToString(separator = "\n") { it.joinToString(prefix = "[", postfix = "]") })
} | 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 6,910 | problemsolving | Apache License 2.0 |
src/Day15.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import java.util.*
import kotlin.math.abs
import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day15.run {
solve1(26L) // 4907780L
solve2(56000011L) // 13639962836448L
}
}.let { println("Total: $it ms") }
}
object Day15 : Day.GroupInput<Day15.Data, Long>("15") {
class Data(private val positions: List<List<Int>>, val targetY: Int, val searchArea: Int) {
fun coveredIntervalsAt(y: Int): Stack<Pair<Int, Int>> = positions.mapNotNull { (sx, sy, bx, by) ->
val distance = abs(sx - bx) + abs(sy - by)
val distanceX = distance - abs(sy - y)
distanceX.takeIf { it >= 0 }?.let { sx - it to sx + it + 1 }
}.sortedBy { it.first }.fold(Stack<Pair<Int, Int>>()) { acc, (start, end) ->
acc.apply {
if (isEmpty() || peek().second < start) add(start to end)
else if (peek().second < end) push(pop().first to end)
}
}
fun beaconCountAt(y: Int): Int = positions.map { it[2] to it[3] }.toSet().count { it.second == y }
}
override fun parse(input: List<List<String>>): Data {
val positions = input[0].map {
Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""")
.matchEntire(it)!!.destructured.toList().map(String::toInt)
}
val (targetY, searchArea) = input[1].map(String::toInt)
return Data(positions, targetY, searchArea)
}
override fun part1(data: Data) = with(data) {
coveredIntervalsAt(targetY).sumOf { it.second - it.first } - beaconCountAt(targetY).toLong()
}
override fun part2(data: Data) = with(data) {
(0..searchArea).firstNotNullOf { y ->
coveredIntervalsAt(y).takeIf { it.size == 2 }?.let { (a, _) ->
a.second * 4000000L + y
}
}
}
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 1,914 | AdventOfCode2022 | Apache License 2.0 |
src/Day13.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | import java.util.Stack
import kotlin.math.sign
fun main() {
fun part1(input: List<String>): Int {
var result = 0
var pairIndex = 0
var firstLine = ""
input.forEachIndexed { index, s ->
when(index % 3) {
0 -> firstLine = s
1 -> {
pairIndex++
if (compareStrings(firstLine, s) == -1)
result += pairIndex
}
}
}
return result
}
fun part2(input: List<String>): Int {
val list: MutableList<Pair<ElemList, Boolean>> = input
.filter { it.isNotBlank() }
.map { Pair(createElemList(it), false) }
.toMutableList()
list.add(Pair(createElemList("[[2]]"), true))
list.add(Pair(createElemList("[[6]]"), true))
list.sortWith { p1, p2 -> compareElemList(p1.first, p2.first) }
var result = 1
list.forEachIndexed { index, pair -> if (pair.second) result *= (index + 1) }
return result
}
check(compareStrings("[1,1,3,1,1]", "[1,1,5,1,1]") == -1)
check(compareStrings("[[1],[2,3,4]]", "[[1],4]") == -1)
check(compareStrings("[9]", "[[8,7,6]]") == 1)
check(compareStrings("[]", "[3]") == -1)
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private abstract class Element
private class ElemNum(val int: Int): Element()
private class ElemList(val list: List<Element>): Element() {
val size get() = list.size
operator fun get(index: Int): Element = list[index]
}
private fun createElemList(input: String): ElemList {
val childList = mutableListOf<Element>()
if (input[0] != '[' || input[input.lastIndex] != ']')
throw IllegalArgumentException(input)
val stack = Stack<MutableList<Element>>()
var currentList = childList
var currentNum: Int? = null
for (i in 1 until input.lastIndex) {
when(input[i]) {
'[' -> {
stack.push(currentList)
currentList = mutableListOf()
}
']' -> {
if (currentNum != null) {
currentList.add(ElemNum(currentNum))
currentNum = null
}
val parentList = stack.pop()
parentList.add(ElemList(currentList))
currentList = parentList
}
',' -> {
if (currentNum != null) {
currentList.add(ElemNum(currentNum))
currentNum = null
}
}
in '0' .. '9' -> {
if (currentNum == null) {
currentNum = 0
}
currentNum = currentNum * 10 + input[i].digitToInt()
}
}
}
if (currentNum != null)
childList.add(ElemNum(currentNum))
return ElemList(childList)
}
private fun createElemListFromNum(elemNum: ElemNum): ElemList {
return ElemList(listOf(elemNum))
}
private fun compareElemList(list1: ElemList, list2: ElemList): Int {
for(i in 0 until list1.size.coerceAtMost(list2.size)) {
val compareResult: Int = if (list1[i] is ElemNum) {
if (list2[i] is ElemNum)
((list1[i] as ElemNum).int - (list2[i] as ElemNum).int).sign
else
compareElemList(createElemListFromNum(list1[i] as ElemNum), list2[i] as ElemList)
}
else {
if (list2[i] is ElemNum)
compareElemList(list1[i] as ElemList, createElemListFromNum(list2[i] as ElemNum))
else
compareElemList(list1[i] as ElemList, list2[i] as ElemList)
}
if (compareResult != 0)
return compareResult
}
return (list1.size - list2.size).sign
}
private fun compareStrings(s1: String, s2: String): Int {
return compareElemList(
createElemList(s1), createElemList(s2)
)
} | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 4,117 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/de/consuli/aoc/year2023/days/Day04.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2023.days
import de.consuli.aoc.common.Day
import kotlin.math.pow
class Day04 : Day(4, 2023) {
data class ScratchCard(val winningNumbers: Set<Int>, val numbers: Set<Int>)
override fun partOne(testInput: Boolean): Int = mapInputToScratchCards(getInput(testInput))
.sumOf { calculatePointsForCard(it) }
override fun partTwo(testInput: Boolean): Int {
val scratchCards = mapInputToScratchCards(getInput(testInput))
val cardCopies = IntArray(scratchCards.size) { initialCardCopies -> 1 }
scratchCards.forEachIndexed { currentIndex, currentCard ->
val winningNumberCounts = currentCard.numbers.count { number -> number in currentCard.winningNumbers }
val cardCyclingIndexRange = (currentIndex + 1..currentIndex + winningNumberCounts)
cardCyclingIndexRange.forEachIndexed { _, cyclingIndex ->
if (cyclingIndex < cardCopies.size) cardCopies[cyclingIndex] += cardCopies[currentIndex]
}
}
return cardCopies.sum()
}
private fun calculatePointsForCard(card: ScratchCard): Int = card.numbers
.count { it in card.winningNumbers }
.takeIf { it > 0 }?.let { 2.0.pow(it - 1).toInt() } ?: 0
private fun mapInputToScratchCards(input: List<String>): List<ScratchCard> =
input.map { inputLine ->
ScratchCard(
getNumbersFromLine(inputLine, isWinning = true),
getNumbersFromLine(inputLine, isWinning = false)
)
}
private fun getNumbersFromLine(line: String, isWinning: Boolean): Set<Int> =
line.substringAfter(':')
.split('|')
.run { if (isWinning) this[0] else this[1] }
.trim()
.split("\\s+".toRegex())
.map { it.toInt() }
.toSet()
}
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 1,859 | advent-of-code | Apache License 2.0 |
kotlin/src/x2022/day9/day9.kt | freeformz | 573,924,591 | false | {"Kotlin": 43093, "Go": 7781} | package day9
import readInput
import kotlin.math.absoluteValue
enum class Direction {
Right, Left, Up, Down
}
data class Position(val x: Int, val y: Int)
data class Move(val direction: Direction, val distance: Int)
class Grid(parts: Int) {
val ropeParts = MutableList(parts) { Position(0, 0) }
val visited = hashSetOf<Position>()
fun execute(move: Move) {
//println(move)
for (i in 1..move.distance) {
val head = ropeParts.first()
var x = head.x
var y = head.y
when (move.direction) {
Direction.Right -> x += 1
Direction.Left -> x -= 1
Direction.Up -> y += 1
Direction.Down -> y -= 1
}
ropeParts[0] = Position(x, y)
for (i in 0..ropeParts.count() - 2) {
val ntail = moveNext(move.direction, ropeParts[i], ropeParts[i + 1])
// println("i: $i, head: ${ropeParts[i]} tail: ${ropeParts[i + 1]} ntail: $ntail")
if ((i + 1) == (ropeParts.count() - 1)) {
//println("added")
visited.add(ntail)
}
ropeParts[i + 1] = ntail
}
//println(ropeParts)
}
}
private fun moveNext(direction: Direction, head: Position, tail: Position): Position {
val xd = head.x - tail.x
val yd = head.y - tail.y
if (xd.absoluteValue > 1 || yd.absoluteValue > 1) {
val xm = if (xd < -1) {
xd + 1
} else if (xd > 1) {
xd - 1
} else {
xd
}
val ym = if (yd < -1) {
yd + 1
} else if (yd > 1) {
yd - 1
} else {
yd
}
return Position(tail.x + xm, tail.y + ym)
}
return tail
}
}
fun main() {
fun parseInput(input: List<String>): List<Move> {
return input.map {
val parts = it.split(" ")
val dir = when (parts.first()) {
"U" -> Direction.Up
"D" -> Direction.Down
"R" -> Direction.Right
"L" -> Direction.Left
else -> throw Exception("invalid input: " + parts.first())
}
Move(dir, parts.last().toInt())
}
}
fun partOne(input: List<String>) {
val grid = Grid(2)
parseInput(input).forEach {
grid.execute(it)
}
println(grid.visited.count())
println(grid.ropeParts)
}
fun partTwo(input: List<String>) {
val grid = Grid(10)
parseInput(input).forEach {
grid.execute(it)
}
println(grid.visited.count())
println(grid.visited)
}
println("partOne test")
partOne(readInput("day9.test"))
println()
println("partOne")
partOne(readInput("day9"))
println()
println("partTwo with partTwo test input")
partTwo(readInput("day9-part2.test"))
println()
println("partTwo")
partTwo(readInput("day9"))
} | 0 | Kotlin | 0 | 0 | 5110fe86387d9323eeb40abd6798ae98e65ab240 | 3,154 | adventOfCode | Apache License 2.0 |
src/d20.main.kts | cjfuller | 317,725,797 | false | null | import java.io.File
fun Long.mirror(): Long = (0 until 10).map { i ->
if (this and (1L shl i) != 0L) {
1L shl (9 - i)
} else {
0
}
}.sum()
data class Tile(val number: Long, val borders: List<Long>) {
fun mirrorLR(): Tile =
this.copy(
borders = this.borders.take(2).map { it.mirror() } + this.borders.drop(2))
fun mirrorUD(): Tile =
this.copy(
borders = this.borders.take(2) + this.borders.drop(2).map { it.mirror() })
fun rot90(): Tile =
this.copy(
borders = listOf(
this.borders[3],
this.borders[0].mirror(),
this.borders[1],
this.borders[2].mirror()
)
)
fun allRotations() = listOf(
this,
this.rot90(),
this.rot90().rot90(),
this.rot90().rot90().rot90()
)
fun allOrientations() = allRotations().flatMap { r ->
listOf(
r,
r.mirrorLR(),
r.mirrorUD()
)
}
fun allBorders(): Set<Long> = allOrientations().flatMap { it.borders }.toSet()
fun hasTwoUnmatched(unmatchedBorders: Set<Long>): Boolean =
borders.count { it in unmatchedBorders } >= 2
}
fun numericValueForSeq(s: Iterable<Char>): Long =
s.withIndex().fold(0) { acc, (i, c) ->
if (c == '#') {
acc + (1 shl i)
} else {
acc
}
}
val tiles = File("./data/d20.txt")
.readLines()
.chunked(12) { chunk ->
val numLine = chunk.take(1)[0]
val grid = chunk.drop(1).take(10)
Tile(
Regex("""Tile (\d+):""").find(numLine)!!.groupValues[1].toLong(),
listOf(
numericValueForSeq(grid.first().asIterable()),
numericValueForSeq(grid.last().asIterable()),
numericValueForSeq(grid.map { it.first() }),
numericValueForSeq(grid.map { it.last() })
)
)
}
val tileLookup: MutableMap<Long, List<Tile>> = mutableMapOf()
tiles.forEach { tile ->
tile.allBorders().forEach { border ->
tileLookup[border] = (tileLookup[border] ?: listOf()) + tile
}
}
val unmatchedNumbers = tileLookup.filter { (_, v) -> v.size == 1 }.keys.toSet()
// Conceivable that this might not work if the corners actually do
// match another tile but there's no layout that satisfies all the
// other constraints.
// However, this works in practice.
val corners = tiles.filter { t ->
t.allOrientations().all { o -> o.hasTwoUnmatched(unmatchedNumbers) }
}
println("Part 1:")
println(corners.map { it.number }.reduce { a, b -> a * b })
| 0 | Kotlin | 0 | 0 | c3812868da97838653048e63b4d9cb076af58a3b | 2,665 | adventofcode2020 | MIT License |
src/Day03.kt | jmorozov | 573,077,620 | false | {"Kotlin": 31919} | fun main() {
val inputData = readInput("Day03")
part1(inputData)
part2(inputData)
}
private const val ASCII_DIFF_UPPER_CASE = 38
private const val ASCII_DIFF_LOWER_CASE = 96
fun Char.priority(): Int = when {
this.isLowerCase() -> this.code - ASCII_DIFF_LOWER_CASE
this.isUpperCase() -> this.code - ASCII_DIFF_UPPER_CASE
else -> 0
}
private fun part1(inputData: List<String>) {
var prioritiesSum = 0
for (line in inputData) {
val trimmedLine = line.trim()
val partSize = trimmedLine.length / 2
val part1: Set<Char> = trimmedLine.take(partSize).toSet()
val part2: Set<Char> = trimmedLine.takeLast(partSize).toSet()
val priority: Int = part1.intersect(part2).first().priority()
prioritiesSum += priority
}
println("The sum of the priorities: $prioritiesSum")
}
private fun part2(inputData: List<String>) {
var elf1Items: Set<Char> = setOf()
var elf2Items: Set<Char> = setOf()
var elf3Items: Set<Char> = setOf()
var groupPrioritiesSum = 0
for ((index, line) in inputData.withIndex()) {
val trimmedLine = line.trim()
val idx = index + 1
val isLastInGroup = idx % 3 == 0
val isSecondInGroup = idx % 2 == 0
when {
isLastInGroup -> elf3Items = trimmedLine.toSet()
isSecondInGroup -> elf2Items = trimmedLine.toSet()
else -> elf1Items = trimmedLine.toSet()
}
if (isLastInGroup) {
val priority: Int = elf1Items
.intersect(elf2Items)
.intersect(elf3Items)
.first()
.priority()
groupPrioritiesSum += priority
}
}
println("The sum of the groups priorities: $groupPrioritiesSum")
} | 0 | Kotlin | 0 | 0 | 480a98838949dbc7b5b7e84acf24f30db644f7b7 | 1,777 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day12/Day12.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day12
import readInput
import java.util.*
private const val DAY_ID = "12"
private data class Cell(
val row: Int,
val col: Int
) {
fun isInBounds(numRows: Int, numCols: Int): Boolean =
row in 0 until numRows && col in 0 until numCols
}
private data class Input(
val grid: List<List<Int>>,
val source: Cell,
val target: Cell,
val a: List<Cell>
)
fun main() {
fun parseInput(input: List<String>): Input {
var source: Cell? = null
var target: Cell? = null
val a = mutableListOf<Cell>()
val grid = input.mapIndexed{ row, line ->
line.mapIndexed{ col, c ->
var x = c
when (c) {
'S' -> {
source = Cell(row, col)
x = 'a'
}
'E' -> {
target = Cell(row, col)
x = 'z'
}
'a' -> {
a += Cell(row, col)
}
}
x - 'a'
}
}
return Input(
grid,
checkNotNull(source) { "S was not found in the grid" },
checkNotNull(target) { "E was not found in the grid" },
a
)
}
fun bfs(grid: List<List<Int>>, source: Cell, target: Cell): Int {
if (source == target) {
return 0
}
val m = grid.size
val n = grid[0].size
val directions = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1)
val q: Queue<Cell> = ArrayDeque()
val visited: MutableSet<Cell> = hashSetOf()
fun enqueue(cell: Cell) {
q.offer(cell)
visited += cell
}
var steps = 0
enqueue(source)
while (!q.isEmpty()) {
val size = q.size
repeat(size) {
val curr = q.poll()
for ((dx, dy) in directions) {
val next = Cell(curr.row + dx, curr.col + dy)
// out of boundaries or visited?
if (!next.isInBounds(m, n) || next in visited ) {
continue
}
// can go?
val h1 = grid[curr.row][curr.col]
val h2 = grid[next.row][next.col]
if (h2 < h1 || h2 - h1 <= 1) {
if (next == target) {
return steps + 1
}
enqueue(next)
}
}
}
steps++
}
// there is no path starting at `source` and ending at `target`
return -1
}
fun part1(input: List<String>): Int {
val (grid, source, target) = parseInput(input)
return bfs(grid, source, target)
}
fun part2(input: List<String>): Int {
val (grid, source, target, a) = parseInput(input)
var best = Int.MAX_VALUE
for (x in a + source) {
val steps = bfs(grid, x, target)
if (steps != -1) {
best = minOf(best, steps)
}
}
return best
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("day${DAY_ID}/Day$DAY_ID")
println(part1(input)) // answer = 380
println(part2(input)) // answer = 375
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 3,591 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-18.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2021
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import kotlin.math.max
fun main() {
val input = readInputLines(2021, "18-input")
val test1 = readInputLines(2021, "18-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>): Long {
val snailNumbers = input.map { parse(it).first }
val result = snailNumbers.reduce { acc, snailNumber -> acc + snailNumber }
return result.magnitude()
}
private fun part2(input: List<String>): Long {
var max = 0L
for (i in input.indices) {
for (j in input.indices) {
if (i == j) continue
val sum = (parse(input[i]).first + parse(input[j]).first).magnitude()
max = max(max, sum)
}
}
return max
}
private sealed class SnailNumber {
var parent: Pair? = null
abstract fun magnitude(): Long
data class Number(var value: Int) : SnailNumber() {
override fun magnitude(): Long {
return value.toLong()
}
override fun toString(): String {
return value.toString()
}
}
data class Pair(var left: SnailNumber, var right: SnailNumber) : SnailNumber() {
override fun toString() = "[$left,$right]"
fun reduce(): Pair {
while (true) {
if (explode() || split()) continue
return this
}
}
fun explode(): Boolean {
val toExplode = deeperThanFour() ?: return false
leftNeighbor(toExplode)?.let {
it.value += (toExplode.left as Number).value
}
rightNeighbor(toExplode)?.let {
it.value += (toExplode.right as Number).value
}
val parent = toExplode.parent!!
if (parent.left === toExplode) {
parent.left = Number(0).also { it.parent = parent }
} else {
parent.right = Number(0).also { it.parent = parent }
}
return true
}
fun split(): Boolean {
val toSplit = findChildToSplit() ?: return false
val leftValue = toSplit.value / 2
val rightValue = toSplit.value - leftValue
val newLeft = Number(leftValue)
val newRight = Number(rightValue)
val newPair = Pair(newLeft, newRight).also {
newLeft.parent = it
newRight.parent = it
}
val parent = toSplit.parent!!
if (parent.left === toSplit) {
parent.left = newPair.also { it.parent = parent }
} else {
parent.right = newPair.also { it.parent = parent }
}
return true
}
override fun magnitude() = 3 * left.magnitude() + 2* right.magnitude()
}
}
private fun SnailNumber.Pair.deeperThanFour(depth: Int = 0): SnailNumber.Pair? {
if (depth == 4) return this
val left = left
if (left is SnailNumber.Pair) {
val leftResult = left.deeperThanFour(depth + 1)
if (leftResult != null) return leftResult
}
val right = right
if (right is SnailNumber.Pair) {
val rightResult = right.deeperThanFour(depth + 1)
if (rightResult != null) return rightResult
}
return null
}
private fun SnailNumber.Pair.findChildToSplit(): SnailNumber.Number? {
val left = left
if (left is SnailNumber.Number) {
if (10 <= left.value) return left
} else {
val leftSub = (left as SnailNumber.Pair).findChildToSplit()
if (leftSub != null) return leftSub
}
val right = right
if (right is SnailNumber.Number) {
if (10 <= right.value) return right
} else {
val rightSub = (right as SnailNumber.Pair).findChildToSplit()
if (rightSub != null) return rightSub
}
return null
}
private fun leftNeighbor(current: SnailNumber): SnailNumber.Number? {
val parent = current.parent ?: return null
val isRight = parent.right === current
if (isRight) return rightMostNumber(parent.left)
return leftNeighbor(parent)
}
private fun rightMostNumber(current: SnailNumber): SnailNumber.Number {
if (current is SnailNumber.Number) return current
return rightMostNumber((current as SnailNumber.Pair).right)
}
private fun rightNeighbor(current: SnailNumber): SnailNumber.Number? {
val parent = current.parent ?: return null
val isleft = parent.left === current
if (isleft) return leftMostNumber(parent.right)
return rightNeighbor(parent)
}
private fun leftMostNumber(current: SnailNumber): SnailNumber.Number {
if (current is SnailNumber.Number) return current
return leftMostNumber((current as SnailNumber.Pair).left)
}
private operator fun SnailNumber.plus(other: SnailNumber): SnailNumber {
val pair = SnailNumber.Pair(this, other)
this.parent = pair
other.parent = pair
return pair.reduce()
}
private fun parse(input: String, start: Int = 0) : Pair<SnailNumber, Int> {
return if (input[start] == '[') {
val (left, middle) = parse(input, start + 1)
require(input[middle] == ',')
val (right, end) = parse(input, middle + 1)
require(input[end] == ']')
SnailNumber.Pair(left, right).also {
left.parent = it
right.parent = it
} to end + 1
} else {
SnailNumber.Number(input[start].digitToInt()) to start + 1
}
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 5,683 | advent-of-code | MIT License |
advent2/src/main/kotlin/Main.kt | thastreet | 574,294,123 | false | {"Kotlin": 29380} | import Outcome.DRAW
import Outcome.LOSS
import Outcome.WIN
import Shape.PAPER
import Shape.ROCK
import Shape.SCISSOR
import java.io.File
enum class Shape(val score: Int) {
ROCK(1),
PAPER(2),
SCISSOR(3)
}
enum class Outcome(val score: Int) {
WIN(6),
DRAW(3),
LOSS(0)
}
val Shape.beats: Shape
get() = when (this) {
ROCK -> SCISSOR
PAPER -> ROCK
SCISSOR -> PAPER
}
val Shape.beatenBy: Shape
get() = when (this) {
ROCK -> PAPER
PAPER -> SCISSOR
SCISSOR -> ROCK
}
fun Char.toShape(): Shape =
when (this) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSOR
else -> throw IllegalArgumentException("Invalid shape: $this")
}
fun Char.toOutcome(): Outcome =
when (this) {
'X' -> LOSS
'Y' -> DRAW
'Z' -> WIN
else -> throw IllegalArgumentException("Invalid outcome: $this")
}
fun main(args: Array<String>) {
val input = File("input.txt")
val lines = input.readLines()
println("Part 1 answer: ${part1(lines)}")
println("Part 2 answer: ${part2(lines)}")
}
private fun part1(lines: List<String>): Int =
parseRounds(lines).sumOf { (opponent, player) ->
player.score + getOutcomeScore(opponent, player)
}
private fun parseRounds(lines: List<String>): List<Pair<Shape, Shape>> =
lines.map {
it.split(" ").run {
get(0)[0].toShape() to get(1)[0].toShape()
}
}
private fun part2(lines: List<String>): Int =
parseOutcomes(lines).sumOf { (opponent, outcome) ->
val player = getPlayer(opponent, outcome)
player.score + getOutcomeScore(opponent, player)
}
private fun getPlayer(opponent: Shape, outcome: Outcome): Shape =
when (outcome) {
WIN -> opponent.beatenBy
DRAW -> opponent
LOSS -> opponent.beats
}
private fun parseOutcomes(lines: List<String>): List<Pair<Shape, Outcome>> =
lines.map {
it.split(" ").run {
get(0)[0].toShape() to get(1)[0].toOutcome()
}
}
private fun getOutcomeScore(opponent: Shape, player: Shape): Int =
when {
player.beats == opponent -> WIN.score
player.beatenBy == opponent -> LOSS.score
else -> DRAW.score
} | 0 | Kotlin | 0 | 0 | e296de7db91dba0b44453601fa2b1696af9dbb15 | 2,292 | advent-of-code-2022 | Apache License 2.0 |
src/_2015/Day02.kt | albertogarrido | 572,874,945 | false | {"Kotlin": 36434} | package _2015
import readInput
fun main() {
runTests()
val input = readInput("2015", "day02")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
var total = 0
input.forEach { dimen ->
total += part1Count(dimen)
}
return total
}
private fun part1Count(dimen: String): Int {
val (l, w, h) = dimen.split("x").map { it.toInt() }
val sidesAreas = listOf(
2 * l * w,
2 * w * h,
2 * h * l
)
return sidesAreas.sum() + (sidesAreas.min() / 2)
}
private fun part2(input: List<String>): Int {
var total = 0
input.forEach { dimen ->
total += part2Count(dimen)
}
return total
}
private fun part2Count(dimen: String): Int {
val (l, w, h) = dimen.split("x").map { it.toInt() }
val perimeters = listOf(
(2 * l) + (2 * w),
(2 * w) + (2 * h),
(2 * l) + (2 * h)
)
return perimeters.min() + l * w * h
}
// tests
private fun runTests() {
val testInput1a = readInput("2015", "day02_test1a")
val part1Test1a = part1(testInput1a)
check(part1Test1a == 58) {
"test 1a failed, expected (58) obtained ($part1Test1a)"
}
val testInput1b = readInput("2015", "day02_test1b")
val part1Test1b = part1(testInput1b)
check(part1Test1b == 43) {
"test 1b failed, expected (43) obtained ($part1Test1b)"
}
val testInput2a = readInput("2015", "day02_test1a")
val part1Test2a = part2(testInput2a)
check(part1Test2a == 34) {
"test 2a failed, expected (34) obtained ($part1Test2a)"
}
val testInput2b = readInput("2015", "day02_test1b")
val part1Test2b = part2(testInput2b)
check(part1Test2b == 14) {
"test 2b failed, expected (14) obtained ($part1Test2b)"
}
}
| 0 | Kotlin | 0 | 0 | ef310c5375f67d66f4709b5ac410d3a6a4889ca6 | 1,806 | AdventOfCode.kt | Apache License 2.0 |
src/Day05.kt | icoffiel | 572,651,851 | false | {"Kotlin": 29350} | fun main() {
operator fun <E> List<E>.component6(): E = get(5)
fun <E>ArrayDeque<E>.pop() = removeLast()
fun <E>ArrayDeque<E>.push(element: E) = addLast(element)
fun <E>ArrayDeque<E>.push(elements: List<E>) {
elements.forEach { element -> push(element) }
}
fun String.toMovement(): Movement {
val (_, amount, _, from, _, to) = split(" ")
return Movement(amount, from, to)
}
fun Array<ArrayDeque<CharSequence>>.convertToString() = map { it.removeLast() }
.map { it.toString() }
.joinToString("") { it.replace("[", "").replace("]", "") }
fun List<String>.applyForEachMove(
movement: (Movement) -> Unit
) {
filter { "move" in it }
.map { it.toMovement() }
.forEach(movement)
}
fun List<String>.toStackRows() = filter { "[" in it }
.map { it.chunked(4) { block -> block.trim() } }
.reversed()
fun part1(input: List<String>): String {
val stacksStrings = input.filter { "[" in it }
val stackRows: List<List<CharSequence>> = stacksStrings
.map { it.chunked(4) { block -> block.trim() } }
.reversed()
val stacks: Array<ArrayDeque<CharSequence>> = Array(stackRows.maxOf { it.size }) {
ArrayDeque()
}
stackRows.forEach { row ->
row.forEachIndexed { index, crate ->
if (crate.isNotBlank()) {
stacks[index].addLast(crate)
}
}
}
input.applyForEachMove {
val (amount, from, to) = it
repeat(amount.toInt()) {
val popped = stacks[from.toInt() - 1].pop()
stacks[to.toInt() - 1].push(popped)
}
}
return stacks.convertToString()
}
fun part2(input: List<String>): String {
val stackRows: List<List<CharSequence>> = input.toStackRows()
val stacks: Array<ArrayDeque<CharSequence>> = Array(stackRows.maxOf { it.size }) {
ArrayDeque()
}
stackRows.forEach { row ->
row.forEachIndexed { index, crate ->
if (crate.isNotBlank()) {
stacks[index].addLast(crate)
}
}
}
input.applyForEachMove {
val (amount, from, to) = it
val fromStack = stacks[from.toInt() - 1]
val toStack = stacks[to.toInt() - 1]
val popped = fromStack.subList(fromStack.size - amount.toInt(), fromStack.size)
toStack.push(popped)
repeat(amount.toInt()) {
fromStack.pop()
}
}
return stacks.convertToString()
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println("Part One: ${part1(input)}")
check(part1(input) == "QGTHFZBHV")
println("Part Two: ${part2(input)}")
check(part2(input) == "MGDMPSZTM")
}
data class Movement(val amount: String, val from: String, val to: String)
| 0 | Kotlin | 0 | 0 | 515f5681c385f22efab5c711dc983e24157fc84f | 3,147 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/week3/Volcano.kt | waikontse | 572,850,856 | false | {"Kotlin": 63258} | package week3
import shared.AdjacencyMatrix
import shared.Algorithms.Companion.floydWarshall
import shared.Puzzle
import shared.ReadUtils.Companion.debug
class Volcano : Puzzle(16) {
data class VolcanoConfig(
val adjacencyMatrix: AdjacencyMatrix,
val translationMap: Map<String, Int>,
val caveToFlowMap: Map<String, Int>,
val startingCave: String,
val runningTime: Int
)
override fun solveFirstPart(): Any {
val cleanedLines = puzzleInput
.map { it.replace("Valve ", "") }
.map { StringBuilder(it) }
.map { it.insert(2, ',') }
.map { it.toString() }
.sorted()
val translationMap = generateTranslationMap(cleanedLines)
val caveInfos = generateValveFlowList(cleanedLines).filter { it.value > 0 }
val adjacencyMatrix = floydWarshall(generateAdjacencyMatrix(cleanedLines, translationMap))
val runningTime = 30
val volcanoConfig = VolcanoConfig(adjacencyMatrix, translationMap, caveInfos, "AA", runningTime)
val maxDepth = 6
val avgDist = caveInfos.keys
.map { adjacencyMatrix[translationMap["AA"]!!][translationMap[it]!!] }
.average().toInt()
val bestRoute = calculateBestRouteForCave(volcanoConfig, maxDepth, avgDist * 2)
println("Best route: $bestRoute")
return bestRoute.second
}
override fun solveSecondPart(): Any {
val cleanedLines = puzzleInput
.map { it.replace("Valve ", "") }
.map { StringBuilder(it) }
.map { it.insert(2, ',') }
.map { it.toString() }
.sorted()
val translationMap = generateTranslationMap(cleanedLines)
val caveInfos = generateValveFlowList(cleanedLines).filter { it.value > 0 }
val maxRunningMinutes = 26
val maxDepth = 6
val adjacencyMatrix = floydWarshall(generateAdjacencyMatrix(cleanedLines, translationMap))
val volcanoConfig = VolcanoConfig(adjacencyMatrix, translationMap, caveInfos, "AA", maxRunningMinutes)
val avgDist = caveInfos.keys
.map { adjacencyMatrix[translationMap["AA"]!!][translationMap[it]!!] }
.average().toInt()
val comboSet = generateSet(caveInfos.map { it.key }.toSet(), maxDepth, volcanoConfig, avgDist * 2)
val prunedComboSet = getHighestUniqueRoutes(volcanoConfig, comboSet)
// Calculate the best complementing route for each generated starting route
val bestRoutes = prunedComboSet
.map {
it to calculatePointsForRoute(volcanoConfig, it)
}
.map {
val newCaveWithFlows = caveInfos - it.first.toSet()
val newVolcanoConfig = volcanoConfig.copy(caveToFlowMap = newCaveWithFlows)
val bestRoute = calculateBestRouteForCave(newVolcanoConfig, maxDepth - 1, avgDist * 2)
it to bestRoute
}
val bestestRoute = bestRoutes.maxBy { it.first.second + it.second.second }
println("Bestest route: $bestestRoute: ${bestestRoute.first.second + bestestRoute.second.second}")
return bestestRoute.first.second + bestestRoute.second.second
}
private fun getHighestUniqueRoutes(config: VolcanoConfig, routes: List<List<String>>): List<List<String>> {
// Prune the sets of routes based on
// 1) The route scored more than 0 points
// 2) The routes with the same set of caves, only select the highest scoring route.
val groupedRoutes = routes.map { it.toSet() to it }
.map { it to calculatePointsForRoute(config, it.second) }
.filter { it.second > 0 }
.groupBy { it.first.first }
return groupedRoutes
.map { it.value.maxBy { pair -> pair.second } }
.map { it.first.second }
}
private fun calculateBestRouteForCave(
config: VolcanoConfig,
maxSizeToGenerate: Int,
avgDistance: Int
): Pair<List<String>, Int> {
val comboSet = generateSet(config.caveToFlowMap.keys.toSet(), maxSizeToGenerate, config, avgDistance)
if (comboSet.isEmpty()) {
return listOf("") to 0
}
val bestRoute = comboSet
.map { it to calculatePointsForRoute(config, it) }
.maxByOrNull { it.second }!!
return bestRoute
}
private fun generateTranslationMap(lines: List<String>): Map<String, Int> {
val translationMap = mutableMapOf<String, Int>()
var currentCount = 0
for (line in lines) {
translationMap[line.substring(0..1)] = currentCount++
}
return translationMap
}
private fun generateValveFlowList(caves: List<String>): Map<String, Int> {
val caveInfo = mutableMapOf<String, Int>()
for (cave in caves) {
val caveName = cave.substring(0..1)
val flowRate = cave.split(";")[0]
.split("=")[1].toInt()
caveInfo.put(caveName, flowRate)
}
return caveInfo
}
private fun generateAdjacencyMatrix(
caves: List<String>,
caveToNumberMap: Map<String, Int>
): AdjacencyMatrix {
val adjacencyMatrix = Array(caves.size) { IntArray(caves.size) { 999991 } }
val edges = caves.map { it.replace(""" has flow rate=\d+; tunnels? leads? to valves? """.toRegex(), "") }
for (edge in edges) {
val connections = edge.split(",").map { it.trim() }
val from = caveToNumberMap[connections.first()]!!
for (connection in connections.drop(1)) {
debug("Checking connection: $connection")
val to = caveToNumberMap[connection]!!
adjacencyMatrix[from][to] = 1
}
}
return adjacencyMatrix
}
private fun generateSet(
initialSet: Set<String>,
maxDepth: Int,
config: VolcanoConfig,
avgDistance: Int
) = generateSet(initialSet, 0, maxDepth, mutableListOf(), listOf(), config, avgDistance)
private fun generateSet(
currentSet: Set<String>,
currentDepth: Int,
maxDepth: Int,
acc: MutableList<List<String>>,
currentCombo: List<String>,
config: VolcanoConfig,
avgDistance: Int
): List<List<String>> {
if (currentDepth == maxDepth) {
acc.add(currentCombo)
return acc
}
for (str in currentSet) {
// Skip if distance from <-> to cave is too big.
val currStartingCave = if (currentCombo.isEmpty()) "AA" else currentCombo.last()
val distanceToCave = config.adjacencyMatrix[config.translationMap[currStartingCave]!!][config.translationMap[str]!!]
if (distanceToCave > avgDistance) {
continue
}
generateSet(currentSet.minus(str), currentDepth.inc(), maxDepth, acc, currentCombo.plus(str), config, avgDistance)
}
return acc
}
private fun calculatePointsForRoute(config: VolcanoConfig, route: List<String>): Int {
var currentCave = config.startingCave
var accumulatedRoutePoints = 0
var currentMinute = 0
for (toCave in route) {
// find route cost from current cave to target cave
val from = config.translationMap[currentCave]!!
val to = config.translationMap[toCave]!!
val dist = config.adjacencyMatrix[from][to]
currentMinute += dist
// increment currentMinute to activate
currentMinute += 1
// calculate the points by multiplying remaining minutes with flow
val flowRate = config.caveToFlowMap[toCave]!!
accumulatedRoutePoints += (config.runningTime - currentMinute) * flowRate
// update current cave
currentCave = toCave
}
// safety check
if (currentMinute > config.runningTime) {
accumulatedRoutePoints = 0
}
return accumulatedRoutePoints
}
}
| 0 | Kotlin | 0 | 0 | 860792f79b59aedda19fb0360f9ce05a076b61fe | 8,130 | aoc-2022-in-kotllin | Creative Commons Zero v1.0 Universal |
advent-of-code-2021/src/main/kotlin/Day4.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 4: Giant Squid
//https://adventofcode.com/2021/day/4
import java.io.File
fun main() {
val lines = File("src/main/resources/Day4.txt").readLines()
val draws = lines.first().split(",").map { it.toInt() }
val boards = lines.asSequence().drop(1).chunked(6).map { board ->
board.drop(1).map { it.split(" ") }
}.map {
it.flatten().filter { number -> number.isNotBlank() }.map { number ->
BingoCell(number.toInt(), false)
}
}.map { BingoBoard(it.toMutableList()) }.toList()
println(bingoFirstWin(draws, boards.toList()))
println(bingoLastWin(draws, boards.toList()))
}
fun bingoFirstWin(draws: List<Int>, boards: List<BingoBoard>): Int {
draws.forEach { draw ->
boards.forEach { board ->
board.mark(draw)
if (board.isAWinner()) {
return draw * board.unMarkedCellsTotal()
}
}
}
return 0
}
fun bingoLastWin(draws: List<Int>, boards: List<BingoBoard>): Int {
var remainingBoards = boards.toMutableList()
draws.forEach { draw ->
remainingBoards.forEach { board ->
board.mark(draw)
if (board.isAWinner()) {
if (remainingBoards.size == 1) {
return draw * remainingBoards.first().unMarkedCellsTotal()
}
remainingBoards = (remainingBoards - board) as MutableList<BingoBoard>
}
}
}
return 0
}
data class BingoCell(var value: Int, var marked: Boolean = false)
data class BingoBoard(val cells: MutableList<BingoCell>) {
fun mark(number: Int) {
cells.replaceAll { if (it.value == number) it.copy(marked = true) else it }
}
fun unMarkedCellsTotal(): Int = cells.filter { it.marked.not() }.sumOf { it.value }
fun isAWinner(): Boolean = rowHasBingo() || columnHasBingo()
private fun columnHasBingo(): Boolean {
for (i in 0 until 5) {
if (cells.filterIndexed { index, _ -> index % 5 == i }.all { it.marked }) return true
}
return false
}
private fun rowHasBingo(): Boolean {
return cells.chunked(5).any { row -> row.all { it.marked } }
}
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,201 | advent-of-code | Apache License 2.0 |
src/Day03.kt | JohannesPtaszyk | 573,129,811 | false | {"Kotlin": 20483} | fun main() {
val possibleItems: List<Char> = ('a'..'z') + ('A'..'Z')
fun part1(input: List<String>): Int = input.sumOf {
val centerIndex = it.length / 2
val firstCompartment = it.substring(0, centerIndex).toSet()
val secondCompartment = it.substring(centerIndex, it.length).toSet()
val sharedItem = firstCompartment.intersect(secondCompartment).first()
possibleItems.indexOf(sharedItem) + 1
}
fun part2(input: List<String>): Int = input.windowed(3, 3).map { rucksacks ->
rucksacks.fold(mutableSetOf()) { param: MutableSet<Set<Char>>, s: String ->
val chars = s.toSet()
param.lastOrNull()?.intersect(chars)?.also {
param.add(it)
} ?: param.add(chars)
param
}.last()
}.sumOf {
possibleItems.indexOf(it.first()) + 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println("Part1 test: ${part1(testInput)}")
check(part1(testInput) == 157)
println("Part2 test: ${part2(testInput)}")
check(part2(testInput) == 70)
val input = readInput("Day03")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 1 | 6f6209cacaf93230bfb55df5d91cf92305e8cd26 | 1,268 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | import kotlin.math.abs
typealias Step = Pair<Direction, Int>
fun buildStep(dir: String, count: String): Step? {
return when (dir) {
"R" -> Step(Direction.RIGHT, count.toInt()-1)
"L" -> Step(Direction.LEFT, count.toInt()-1)
"U" -> Step(Direction.UP, count.toInt()-1)
"D" -> Step(Direction.DOWN, count.toInt()-1)
else -> null
}
}
class Rope(tailSize: Int) {
private var head: Vector2 = Pair(0, 0)
private var tail: MutableList<Vector2> = (0 until tailSize).map { Pair(0, 0) }.toMutableList()
private fun updateTail(): Vector2 {
fun inner(headX: Int, headY: Int, idx: Int): Vector2 {
if (idx == tail.size) {
return tail[tail.size-1]
}
var (tailX, tailY) = tail[idx]
val deltaX = abs(tailX - headX)
val deltaY = abs(tailY - headY)
if (deltaX < 2 && deltaY < 2) {
return tail[tail.size-1]
}
if (deltaX >= 1) {
if (headX > tailX) {
tailX++
} else {
tailX--
}
}
if (deltaY >= 1) {
if (headY > tailY) {
tailY++
} else {
tailY--
}
}
tail[idx] = Pair(tailX, tailY)
return inner(tail[idx].first, tail[idx].second, idx+1)
}
return inner(head.first, head.second, 0)
}
fun updateHead(step: Step): Set<Vector2> {
val (direction, count) = step
val tailPositions: MutableSet<Vector2> = mutableSetOf()
for (littleStep in (0..count)) {
val (headX, headY) = head
head = when (direction) {
Direction.LEFT -> {
Pair(headX-1, headY)
}
Direction.RIGHT -> {
Pair(headX+1, headY)
}
Direction.UP -> {
Pair(headX, headY-1)
}
Direction.DOWN -> {
Pair(headX, headY+1)
}
}
tailPositions.add(updateTail())
}
return tailPositions
}
}
fun main() {
fun part1(input: List<String>): Int {
val rope = Rope(1)
var tailPositions: Set<Vector2> = mutableSetOf()
for (line in input) {
val (direction, count) = line.split(' ')
tailPositions = tailPositions union rope.updateHead(buildStep(direction, count)!!)
}
return tailPositions.size
}
fun part2(input: List<String>): Int {
val rope = Rope(9)
var tailPositions: Set<Vector2> = mutableSetOf()
for (line in input) {
val (direction, count) = line.split(' ')
tailPositions = tailPositions union rope.updateHead(buildStep(direction, count)!!)
}
return tailPositions.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 3,275 | aoc2022 | Apache License 2.0 |
src/d09/Main.kt | cweckerl | 572,838,803 | false | {"Kotlin": 12921} | package d09
import java.io.File
import kotlin.math.pow
import kotlin.math.sqrt
fun main() {
fun dist(p1: Pair<Int, Int>, p2: Pair<Int, Int>) = sqrt(
(p1.first - p2.first).toDouble().pow(2) +
(p1.second - p2.second).toDouble().pow(2)
)
fun part1(input: List<String>) {
var h = Pair(0, 0)
var t = Pair(0, 0)
var prev = Pair(0, 0)
val visited = mutableSetOf<Pair<Int, Int>>()
visited.add(prev)
input.forEach {
val (d, m) = it.split(' ')
// dist, mag
repeat(m.toInt()) {
prev = h
h = when (d) {
"U" -> h.copy(second = h.second + 1)
"D" -> h.copy(second = h.second - 1)
"L" -> h.copy(first = h.first - 1)
else -> h.copy(first = h.first + 1)
}
if (dist(h, t) > sqrt(2.0)) {
t = prev.copy()
visited.add(t)
}
}
}
println(visited.size)
}
fun part2(input: List<String>) {
val p = MutableList(10) { Pair(0, 0) }
var prev = Pair(0, 0)
val visited = mutableSetOf<Pair<Int, Int>>()
visited.add(prev)
input.forEach { line ->
val (d, m) = line.split(' ')
repeat(m.toInt()) {
prev = p[0]
p[0] = when (d) {
"U" -> p[0].copy(second = p[0].second + 1)
"D" -> p[0].copy(second = p[0].second - 1)
"L" -> p[0].copy(first = p[0].first - 1)
else -> p[0].copy(first = p[0].first + 1)
}
for (i in 0 until p.size - 1) {
if (dist(p[i], p[i + 1]) > sqrt(2.0)) {
val dx = prev.first - p[1].first
val dy = prev.second - p[1].second
val indices = mutableSetOf(1)
for (j in i + 1 until p.size - 1) {
if (dist(p[j], p[j + 1]) != 1.0) {
break
}
indices.add(j + 1)
}
indices.forEach { p[it] = p[it].copy(p[it].first + dx, p[it].second + dy) }
visited.add(p.last())
}
}
}
}
println(visited.size)
}
val input = File("src/d09/input").readLines()
part1(input)
part2(input)
} | 0 | Kotlin | 0 | 0 | 612badffbc42c3b4524f5d539c5cbbfe5abc15d3 | 2,601 | aoc | Apache License 2.0 |
src/main/kotlin/me/mattco/days/day06.kt | mattco98 | 160,000,311 | false | null | package me.mattco.days
import me.mattco.utils.ResourceLoader.getTextResource
import java.lang.Math.abs
import kotlin.math.max
object Day6 {
private val input = getTextResource("/day06").split(System.lineSeparator())
private fun getGrid(): List<Pair<Int, Int>> = input.map {
val v = it.split(", ")
v[0].toInt() to v[1].toInt()
}
private fun dist(one: Pair<Int, Int>, two: Pair<Int, Int>): Int {
return abs(one.first - two.first) + abs(one.second - two.second)
}
fun part1(): Any? {
val g = getGrid()
val names = mutableMapOf<Pair<Int, Int>, Int>()
g.forEachIndexed { index, pair -> names[pair] = index }
val m = names.maxBy { max(it.key.first, it.key.second) }!!
val max = max(m.key.first, m.key.second)
var grid = mutableMapOf<Pair<Int, Int>, Int>()
for (i in 0..max) {
for (j in 0..max) {
val distances = names.map { it.value to dist(i to j, it.key) }
val min = distances.minBy { it.second }!!
if (distances.map { it.second }.count { it == min.second } > 1) {
grid[i to j] = -1
continue
}
grid[i to j] = min.first
}
}
for (i in 0..max) {
for (j in 0..max) {
if (!(i == 0 || i == max || j == 0 || j == max)) continue
val v = grid[i to j]
if (v != -1) {
grid = grid.filter { it.value != v }.toMutableMap()
}
}
}
return grid.values.filter { it != -1 }.groupingBy { it }.eachCount().values.max()
}
fun part2(): Any? {
val g = getGrid()
val max = max(g.maxBy { it.first }!!.first, g.maxBy { it.second }!!.second)
var grid = mutableMapOf<Pair<Int, Int>, Int>()
for (i in 0..max) {
for (j in 0..max) {
for (p in g) {
val pair = i to j
grid[pair] = grid.getOrDefault(pair, 0) + dist(pair, p)
}
}
}
return grid.filter { it.value < 10000 }.count()
}
}
fun main() {
println("=== Day 6 ===")
println("Part 1: ${Day6.part1()}")
println("Part 2: ${Day6.part2()}")
}
| 0 | Kotlin | 0 | 0 | 9ec878de1cd727bb56ba7cb17796c766d4894252 | 2,407 | AdventOfCode2018 | MIT License |
src/main/kotlin/g2901_3000/s2954_count_the_number_of_infection_sequences/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2954_count_the_number_of_infection_sequences
// #Hard #Array #Math #Combinatorics #2024_01_16_Time_1446_ms_(14.29%)_Space_69.1_MB_(14.29%)
import kotlin.math.max
class Solution {
private val fact = LongArray(M + 1)
private val invFact = LongArray(M + 1)
private var init: Long = 0
private fun modPow(x: Int, y: Int, mod: Int): Int {
if (y == 0) {
return 1
}
var p = (modPow(x, y / 2, mod) % mod).toLong()
p = (p * p) % mod
return if (y % 2 == 1) (p * x % mod).toInt() else p.toInt()
}
private fun binomCoeff(n: Int, k: Int): Long {
return max(
1.0,
(fact[n] * invFact[k] % MOD * invFact[n - k] % MOD).toDouble()
).toLong()
}
fun numberOfSequence(n: Int, sick: IntArray): Int {
if (init == 0L) {
init = 1
fact[0] = 1
for (i in 1..M) {
fact[i] = fact[i - 1] * i % MOD
}
invFact[M] = modPow(fact[M].toInt(), MOD - 2, MOD).toLong()
for (i in M - 1 downTo 1) {
invFact[i] = invFact[i + 1] * (i + 1) % MOD
}
}
var res: Long = 1
for (i in 1 until sick.size) {
val group = sick[i] - sick[i - 1] - 1
res = res * modPow(2, max(0.0, (group - 1).toDouble()).toInt(), MOD) % MOD
res = res * binomCoeff(sick[i] - i, group) % MOD
}
return (res * binomCoeff(n - sick.size, n - sick[sick.size - 1] - 1) % MOD).toInt()
}
companion object {
private const val M = 100000
private const val MOD = 1000000007
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,669 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/day11/Day11.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day11
import groupByBlanks
import runDay
fun main() {
fun part1(input: List<String>) = input.toMonkeys()
.let { monkeys ->
repeat(20) { processRound(monkeys) }
monkeys.map { it.inspectedItems }
.sortedDescending()
.take(2)
.reduce { a, b -> a * b }
}
fun part2(input: List<String>) = input.toMonkeys()
.let { monkeys ->
for (i in (0 until 10000)) {
processWorriedRound(monkeys)
}
monkeys.map { it.inspectedItems }
.sortedDescending()
.take(2)
.fold(1L) { a, b -> a * b }
}
(object {}).runDay(
part1 = ::part1,
part1Check = 10605,
part2 = ::part2,
part2Check = 2713310158L,
)
}
internal fun processRound(monkeys: List<Monkey>) {
monkeys.forEach {
it.inspectItems().forEach { (newWorryLevel, monkey) ->
monkeys[monkey].catchItem(newWorryLevel)
}
}
}
internal fun processWorriedRound(monkeys: List<Monkey>) {
val minimizer = monkeys.fold(1L) { product, monkey -> product * monkey.testDivisibleBy }.toLong()
monkeys.forEach {
val origItems = it.heldItems
it.inspectItems(false).forEach { (newWorryLevel, monkey) ->
if (newWorryLevel < 0) {
println(it)
println(origItems)
throw IllegalArgumentException()
}
monkeys[monkey].catchItem(newWorryLevel % minimizer)
}
}
}
internal fun List<String>.toMonkeys() =
groupByBlanks().map { it.toMonkey() }
internal fun List<String>.toMonkey() = Monkey(
startingItems = this[1].toStartingItems(),
operation = this[2].toOperation(),
testDivisibleBy = this[3].toTestDivisibleBy(),
ifTrueTarget = this[4].toIfTrueTarget(),
ifFalseTarget = this[5].toIfFalseTarget(),
)
private const val STARTING_ITEMS = "Starting items: "
private fun String.toStartingItems() =
this.substringAfter(STARTING_ITEMS).split(',')
.map { it.trim().toLong() }
.toMutableList()
private const val TEST_DIVISIBLE_BY = " Test: divisible by "
private fun String.toTestDivisibleBy() =
this.substringAfter(TEST_DIVISIBLE_BY).toInt()
private const val OPERATION = " Operation: new = old "
private fun String.toOperation() =
this.substringAfter(OPERATION)
.split(" ", limit = 2)
.let {
val value = it.last()
when (it.last()) {
"old" -> when (it.first()) {
"+" -> DoubleIt
"*" -> SquareIt
else -> throw IllegalArgumentException(it.first())
}
else -> when (it.first()) {
"+" -> Add(value.toLong())
"*" -> Multiply(value.toLong())
else -> throw IllegalArgumentException(it.first())
}
}
}
private const val IF_TRUE_TARGET = " If true: throw to monkey "
private fun String.toIfTrueTarget() =
this.substringAfter(IF_TRUE_TARGET).toInt()
private const val IF_FALSE_TARGET = " If false: throw to monkey "
private fun String.toIfFalseTarget() =
this.substringAfter(IF_FALSE_TARGET).toInt()
| 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 3,321 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dp/ConstructBST.kt | yx-z | 106,589,674 | false | null | package dp
import util.get
// given an array of look-up frequencies of some sorted array
// find the minimum cost for all look-ups if the sorted array is stored as a
// binary search tree (the sorted key values is actually irrelevant to this problem!
// cost = sum over all nodes (# of ancestors * freq) [one's ancestor includes itself]
fun main(args: Array<String>) {
val freq = intArrayOf(5, 8, 2, 1, 9, 5)
println(freq.bstCost())
}
fun IntArray.bstCost(): Int {
// dp[i][j] = optimal cost for this[i..j]
// dp[i][j] = 0, if i > j
// sum(this[i..j]) + min(dp[i][r - 1] + dp[r + 1][j]): i <= r <= j, o/w
val dp = Array(size) { IntArray(size) }
for (j in 0 until size) {
for (i in j downTo 0) {
dp[i][j] = this[i..j].sum() + ((i..j).map {
when {
it - 1 < 0 -> dp[it + 1][j]
it + 1 >= size -> dp[i][it - 1]
else -> dp[i][it - 1] + dp[it + 1][j]
}
}.min() ?: 0)
}
}
return dp[0][size - 1]
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 947 | AlgoKt | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/KthSmallest.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
import kotlin.math.max
import kotlin.math.min
/**
* Kth Smallest Element in a Sorted Matrix
* @see <a href="https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix">Source</a>
*/
fun interface KthSmallest {
operator fun invoke(matrix: Array<IntArray>, k: Int): Int
}
sealed class KthSmallestStrategy {
/**
* Time Complexity: let X=min(K,N);X+Klog(X)
* Space Complexity: O(X) which is occupied by the heap.
*/
object MinHeap : KthSmallest, KthSmallestStrategy() {
override operator fun invoke(matrix: Array<IntArray>, k: Int): Int {
val priorityQueue = PriorityQueue<Pair<Int, Int>>(compareBy { it.first })
val indices = MutableList(matrix.size) { 0 }
matrix.indices.forEach { priorityQueue.add(Pair(matrix[it][indices[it]++], it)) }
repeat(k - 1) {
val (_, index) = priorityQueue.poll()
if (indices[index] < matrix.size) {
priorityQueue.add(Pair(matrix[index][indices[index]++], index))
}
}
return priorityQueue.first().first
}
override fun toString(): String = "min heap"
}
/**
* Time Complexity: O(N×log(Max−Min))
* Space Complexity: O(1)
*/
object BinarySearch : KthSmallest, KthSmallestStrategy() {
override operator fun invoke(matrix: Array<IntArray>, k: Int): Int {
val n: Int = matrix.size
var start = matrix[0][0]
var end = matrix[n - 1][n - 1]
while (start < end) {
val mid = start + (end - start) / 2
// first number is the smallest and the second number is the largest
val smallLargePair = intArrayOf(matrix[0][0], matrix[n - 1][n - 1])
val count = countLessEqual(matrix, mid, smallLargePair)
if (count == k) {
return smallLargePair[0]
}
if (count < k) {
start = smallLargePair[1] // search higher
} else {
end = smallLargePair[0] // search lower
}
}
return start
}
private fun countLessEqual(matrix: Array<IntArray>, mid: Int, smallLargePair: IntArray): Int {
var count = 0
val n = matrix.size
var row = n - 1
var col = 0
while (row >= 0 && col < n) {
if (matrix[row][col] > mid) {
// as matrix[row][col] is bigger than the mid, let's keep track of the
// smallest number greater than the mid
smallLargePair[1] = min(smallLargePair[1], matrix[row][col])
row--
} else {
// as matrix[row][col] is less than or equal to the mid, let's keep track of the
// biggest number less than or equal to the mid
smallLargePair[0] = max(smallLargePair[0], matrix[row][col])
count += row + 1
col++
}
}
return count
}
override fun toString(): String = "binary search"
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,916 | kotlab | Apache License 2.0 |
src/main/kotlin/solutions/year2022/Day3.kt | neewrobert | 573,028,531 | false | {"Kotlin": 7605} | package solutions.year2022
import readInputLines
/**
* For each element you should split it on half = input.size() / 2
*
* compare both to see which element appears more than once
*
* check the priority and save it
*
* sum up all the priority
*/
fun main() {
fun Char.toPriority() = if (this in 'a'..'z') this.code - 'a'.code + 1 else this.code - 'A'.code + 27
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
val half = rucksack.length / 2
val (firstHalf, secondHalf) = rucksack.chunked(half)
firstHalf.find { it in secondHalf }?.toPriority() ?: 0
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { group ->
val (g1, g2, g3) = group
g1.find { it in g2 && it in g3 }?.toPriority() ?: 0
}
}
val testInput = readInputLines("2022", "Day3_test")
check(part1(testInput) != 0)
check(part1(testInput) == 97)
check(part2(testInput) != 0)
check(part2(testInput) == 38)
val input = readInputLines("2022", "Day3")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7ecf680845af9d22ef1b9038c05d72724e3914f1 | 1,154 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/sschr15/aocsolutions/Day19.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.*
import sschr15.aocsolutions.util.watched.sumOf
import sschr15.aocsolutions.util.watched.times
import java.util.ArrayDeque
import kotlin.collections.sumOf
/**
* AOC 2023 [Day 19](https://adventofcode.com/2023/day/19)
* Challenge: Help those poor Desert Island elves sort all of those new metal parts from Gear Island
*/
object Day19 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 19) {
// test()
data class State(val x: Int, val m: Int, val a: Int, val s: Int)
data class RawRule(val requiredOption: Char, val isGreater: Boolean, val requirement: Int, val workflow: String)
data class RawWorkflow(val name: String, val rules: List<RawRule>, val ifNoneMatch: String)
val accepted = RawWorkflow("A", listOf(), "R")
val rejected = RawWorkflow("R", listOf(), "R")
val forP2 = mutableMapOf(
"A" to accepted,
"R" to rejected,
)
part1 {
val workflows = inputLines.takeWhile { it.isNotBlank() }.map { line ->
val name = line.substringBefore('{')
val rawRules = mutableListOf<RawRule>()
val rules = line.substringAfter('{').substringBefore('}').split(",").map {
if (':' in it) {
val (condition, workflow) = it.split(":")
val operation = condition[1]
val requirement = condition.substring(2).toInt()
val check: (State) -> String? = when (condition.first()) {
'x' -> when (operation) {
'>' -> { state -> if (state.x > requirement) workflow else null }
'<' -> { state -> if (state.x < requirement) workflow else null }
else -> error("Unexpected operation $operation")
}
'm' -> when (operation) {
'>' -> { state -> if (state.m > requirement) workflow else null }
'<' -> { state -> if (state.m < requirement) workflow else null }
else -> error("Unexpected operation $operation")
}
'a' -> when (operation) {
'>' -> { state -> if (state.a > requirement) workflow else null }
'<' -> { state -> if (state.a < requirement) workflow else null }
else -> error("Unexpected operation $operation")
}
's' -> when (operation) {
'>' -> { state -> if (state.s > requirement) workflow else null }
'<' -> { state -> if (state.s < requirement) workflow else null }
else -> error("Unexpected operation $operation")
}
else -> throw IllegalArgumentException("Invalid condition: $condition")
}
val rule = RawRule(condition.first(), operation == '>', requirement, workflow)
rawRules.add(rule)
check
} else {
val result = it
val check: (State) -> String? = { _ -> result }
forP2[name] = RawWorkflow(name, rawRules, result)
check
}
}
name to { state: State ->
rules.firstNotNullOf { it(state) }
}
}.toMap()
val challenges = inputLines.takeLastWhile { it.isNotBlank() }.map { line ->
val (x, m, a, s) = line.substring(1, line.length - 1).split(",").map { it.substring(2).toInt() }
State(x, m, a, s)
}
challenges.mapNotNull {
var current = workflows["in"]!!(it)
while (current in workflows.keys) {
current = workflows[current]!!(it)
}
if (current == "A") it else null // "R" is rejected
}.sumOf { (x, m, a, s) -> x.toLong() + m + a + s }
}
part2 {
data class States(val x: IntRange = 1..4000, val m: IntRange = 1..4000, val a: IntRange = 1..4000, val s: IntRange = 1..4000)
val queue = ArrayDeque<Pair<States, RawWorkflow>>()
queue.add(States() to forP2["in"]!!)
val discoveredStates = mutableSetOf<States>()
val seenStates = mutableSetOf<States>()
while (queue.isNotEmpty()) {
val (state, workflow) = queue.removeFirst()
if (workflow == rejected) continue // don't bother with rejected states
if (workflow == accepted) {
discoveredStates.add(state)
continue
}
if (!seenStates.add(state)) continue
val newStates = mutableSetOf<Pair<States, RawWorkflow>>()
var eligibleForNext = state
for ((requiredOption, isGreater, requirement, resultingWorkflow) in workflow.rules) {
val range = when (requiredOption) {
'x' -> eligibleForNext.x
'm' -> eligibleForNext.m
'a' -> eligibleForNext.a
's' -> eligibleForNext.s
else -> throw IllegalArgumentException("Invalid required option: $requiredOption")
}
val newRange = if (isGreater) {
(requirement + 1)..range.last
} else {
range.first..<requirement
}
val nextEligibleRange = if (isGreater) {
range.first..requirement
} else {
requirement..range.last
}
if (!newRange.isEmpty()) {
newStates.add(when (requiredOption) {
'x' -> eligibleForNext.copy(x = newRange)
'm' -> eligibleForNext.copy(m = newRange)
'a' -> eligibleForNext.copy(a = newRange)
's' -> eligibleForNext.copy(s = newRange)
else -> throw IllegalArgumentException("Invalid required option: $requiredOption")
} to forP2[resultingWorkflow]!!)
eligibleForNext = when (requiredOption) {
'x' -> eligibleForNext.copy(x = nextEligibleRange)
'm' -> eligibleForNext.copy(m = nextEligibleRange)
'a' -> eligibleForNext.copy(a = nextEligibleRange)
's' -> eligibleForNext.copy(s = nextEligibleRange)
else -> throw IllegalArgumentException("Invalid required option: $requiredOption")
}
} // else, this rule is impossible to satisfy and we can skip it
}
if (!eligibleForNext.x.isEmpty() || !eligibleForNext.m.isEmpty() || !eligibleForNext.a.isEmpty() || !eligibleForNext.s.isEmpty()) {
newStates.add(eligibleForNext to forP2[workflow.ifNoneMatch]!!)
}
queue.addAll(newStates)
}
discoveredStates.sumOf { (x, m, a, s) -> x.range.toLong() * m.range * a.range * s.range }
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 7,875 | advent-of-code | MIT License |
src/Day04.kt | marosseleng | 573,498,695 | false | {"Kotlin": 32754} | fun main() {
fun part1(input: List<String>): Int {
return input.count {
val (first, second) = it.split(',')
val (firstStart, firstEnd) = first.split('-')
val (secondStart, secondEnd) = second.split('-')
val firstRange = firstStart.toInt()..firstEnd.toInt()
val secondRange = secondStart.toInt()..secondEnd.toInt()
(firstRange.first >= secondRange.first && firstRange.last <= secondRange.last) ||
(secondRange.first >= firstRange.first && secondRange.last <= firstRange.last)
}
}
fun part2(input: List<String>): Int {
return input.count {
val (first, second) = it.split(',')
val (firstStart, firstEnd) = first.split('-')
val (secondStart, secondEnd) = second.split('-')
val firstRange = firstStart.toInt()..firstEnd.toInt()
val secondRange = secondStart.toInt()..secondEnd.toInt()
firstRange.intersect(secondRange).isNotEmpty()
}
}
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 | f13773d349b65ae2305029017490405ed5111814 | 1,247 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/be/seppevolkaerts/day6/Day6.kt | Cybermaxke | 727,453,020 | false | {"Kotlin": 35118} | package be.seppevolkaerts.day6
import be.seppevolkaerts.splitLongs
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
data class Race(
val time: Long,
val recordDistance: Long,
)
fun Race.waysToWin(): Long {
// Loops, although fast enough, is it really?
/*
var count = 0L
for (holdTime in 1..<time) {
if (holdTime * (time - holdTime) > recordDistance)
count++
}
return count
*/
// Formulas, very fast
// holdTime * (time - holdTime) = recordDistance + 1
// -> derive holdTime1 and holdTime2 from it, which will be the start and end where we have at least one extra distance point
// https://www.symbolab.com/solver/solve-for-equation-calculator/x%5Cleft(t%20-%20x%5Cright)%20%3D%20r%20%2B1
val time = time.toDouble()
fun holdTime(operand: Int) = (-time + operand * sqrt(time * time + 4 * (-1 - recordDistance))) / -2
val start = ceil(holdTime(1)).toLong()
val end = floor(holdTime(-1)).toLong()
return end - start + 1L
}
fun List<Race>.waysToWinProduct() = asSequence().map { it.waysToWin() }.reduce { acc, i -> acc * i }
fun parsePart1Data(iterable: Iterable<String>): List<Race> {
fun numbers(prefix: String) = iterable.first { it.startsWith(prefix) }.substringAfter(':').splitLongs()
val times = numbers("Time")
val records = numbers("Distance")
return times.zip(records).map { (time, record) -> Race(time, record) }.toList()
}
fun parseData(iterable: Iterable<String>): Race {
fun number(prefix: String) = iterable.first { it.startsWith(prefix) }.substringAfter(':').replace(" ", "").toLong()
val time = number("Time")
val record = number("Distance")
return Race(time, record)
}
| 0 | Kotlin | 0 | 1 | 56ed086f8493b9f5ff1b688e2f128c69e3e1962c | 1,673 | advent-2023 | MIT License |
src/day4/Day4.kt | pocmo | 433,766,909 | false | {"Kotlin": 134886} | package day4
import java.io.File
data class Number(
val value: Int,
var marked: Boolean = false
)
data class Board(
val data: Array<Array<Number>> = Array(5) { Array(5) { Number(0) } }
) {
override fun equals(other: Any?): Boolean {
if (other !is Board) return false
return data.contentEquals(other.data)
}
override fun hashCode(): Int {
return data.contentHashCode()
}
override fun toString(): String {
return data.joinToString("\n") { row ->
row.joinToString(" ") { number ->
if (number.marked) "X" else number.value.toString()
}
}
}
fun mark(value: Int) {
data.forEach { row ->
row.forEach { number ->
if (number.value == value) number.marked = true
}
}
}
fun sumUnmarkedNumbers(): Int {
return data.flatten().filter { !it.marked }.sumBy { it.value }
}
fun isWinner(): Boolean {
return isRowWinner() || isColumnWinner()
}
private fun isRowWinner(): Boolean {
for (y in 0 until 5) {
var winner = true
for (x in 0 until 5) {
if (!data[y][x].marked) {
winner = false
}
}
if (winner) return true
}
return false
}
private fun isColumnWinner(): Boolean {
for (x in 0 until 5) {
var winner = true
for (y in 0 until 5) {
if (!data[y][x].marked) {
winner = false
}
}
if (winner) return true
}
return false
}
}
fun readBoard(data: List<String>, position: Int): Board {
val boardData = data.subList(position, position + 5)
val board = Board()
boardData.forEachIndexed { row, line ->
val rowData = line.split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
rowData.forEachIndexed { column, value ->
board.data[row][column] = Number(value)
}
}
return board
}
fun readData(): Pair<List<Int>, List<Board>> {
val values = File("day4.txt").readLines()
val numbers = values[0].split(",").map { it.toInt() }
val boards = mutableListOf<Board>()
for (i in 2 until values.size step 6) {
val board = readBoard(values, i)
boards.add(board)
}
return Pair(numbers, boards)
}
fun findWinningBoard(numbers: List<Int>, boards: List<Board>): Pair<Int, Board> {
for (number in numbers) {
for (board in boards) {
board.mark(number)
if (board.isWinner()) {
return Pair(number, board)
}
}
}
throw IllegalStateException("No winning board found")
}
fun part1() {
val (numbers, boards) = readData()
val (number, board) = findWinningBoard(numbers, boards)
println("Winning number: $number")
println("Winning board:")
println(board)
val sum = board.sumUnmarkedNumbers()
println("Unmarked numbers sum: $sum")
println()
println("Result: ${sum * number}")
}
fun part2() {
val (numbers, boards) = readData()
val boardCandidates = boards.toMutableList()
while (boardCandidates.size > 1) {
// Find the winning board and remove it from the list
val (number, winningBoard) = findWinningBoard(numbers, boardCandidates)
boardCandidates.remove(winningBoard)
}
val board = boardCandidates[0]
val (number, winningBoard) = findWinningBoard(numbers, listOf(board))
println("Last number: $number")
println("Winning board found:")
println(winningBoard)
val sum = winningBoard.sumUnmarkedNumbers()
println("Unmarked numbers sum: $sum")
println()
println("Result: ${sum * number}")
}
fun main() {
part2()
}
| 0 | Kotlin | 1 | 2 | 73bbb6a41229e5863e52388a19108041339a864e | 3,860 | AdventOfCode2021 | Apache License 2.0 |
year2016/src/main/kotlin/net/olegg/aoc/year2016/day11/Day11.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2016.day11
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2016.DayOf2016
import java.util.BitSet
/**
* See [Year 2016, Day 11](https://adventofcode.com/2016/day/11)
*/
object Day11 : DayOf2016(11) {
private val GEN_PATTERN = "(\\w+) generator".toRegex()
private val CHIP_PATTERN = "(\\w+)-compatible microchip".toRegex()
override fun first(): Any? {
val initial = lines
.map { floor ->
Pair(
GEN_PATTERN.findAll(floor).map { it.value[0] }.toSet(),
CHIP_PATTERN.findAll(floor).map { it.value[0] }.toSet(),
)
}
return countSteps(initial)
}
override fun second(): Any? {
val initial = lines
.map { floor ->
Pair(
GEN_PATTERN.findAll(floor).map { it.value[0] }.toSet(),
CHIP_PATTERN.findAll(floor).map { it.value[0] }.toSet(),
)
}
val fixed = initial.mapIndexed { i, floor ->
when (i) {
0 -> (floor.first + setOf('e', 'd') to floor.second + setOf('e', 'd'))
else -> floor
}
}
return countSteps(fixed)
}
private fun countSteps(input: List<Pair<Set<Char>, Set<Char>>>): Int {
val types = input.flatMap { it.first + it.second }.distinct().sorted()
val indexed = input.map { (gen, chip) ->
Pair(gen.map { types.indexOf(it) }.toSet(), chip.map { types.indexOf(it) }.toSet())
}
val bits = (types.size * 2 + 1) * 2
val initial = compress(indexed, 0, types.size)
val all = (1 shl bits) - 1
val queue = ArrayDeque(listOf(initial to 0))
val known = BitSet(1 shl bits)
known.set(initial)
val elevatorMoves = (0..3).map { curr -> listOf(curr - 1, curr + 1).filter { next -> next in 0..3 } }
do {
val (floors, elevator, steps) = decompress(queue.removeFirst(), types.size)
val (gens, chips) = floors[elevator]
val allMoves = gens.flatMap { a -> gens.map { b -> setOf(a, b) to emptySet<Int>() } } +
chips.flatMap { a -> chips.map { b -> emptySet<Int>() to setOf(a, b) } } +
gens.intersect(chips).map { setOf(it) to setOf(it) }
val moves = allMoves.distinct()
val nextFloors = elevatorMoves[elevator]
nextFloors.flatMap { next ->
moves.map { (genMove, chipMove) ->
floors.toMutableList().also { fl ->
fl[elevator] = fl[elevator].copy(fl[elevator].first - genMove, fl[elevator].second - chipMove)
fl[next] = fl[next].copy(fl[next].first + genMove, fl[next].second + chipMove)
} to next
}
}
.distinctBy { it.first }
.filterNot { (floors, _) ->
floors.any { (gens, chips) ->
gens.isNotEmpty() && (chips - gens).isNotEmpty()
}
}
.map { compress(it.first, it.second, types.size) }
.filterNot { state -> known.get(state) }
.forEach { state ->
known.set(state)
queue.add(state to steps + 1)
}
} while (!known.get(all))
return queue.first { it.first == all }.second
}
private fun compress(
state: List<Pair<Set<Int>, Set<Int>>>,
elevator: Int,
types: Int
): Day11State {
val data = IntArray(types * 2 + 1)
data[0] = elevator
state.forEachIndexed { floor, pair ->
pair.first.forEach { data[it * 2 + 1] = floor }
pair.second.forEach { data[it * 2 + 2] = floor }
}
return data.foldIndexed(0) { index, acc, value -> acc or (value shl (index * 2)) }
}
fun decompress(
compressed: Pair<Day11State, Int>,
types: Int
): Triple<List<Pair<Set<Int>, Set<Int>>>, Int, Int> {
val decompressed = List(4) { mutableSetOf<Int>() to mutableSetOf<Int>() }
val elevator = compressed.first and 3
(0..<types).forEach { index ->
decompressed[compressed.first[index * 2 + 1]].first += index
decompressed[compressed.first[index * 2 + 2]].second += index
}
return Triple(
decompressed,
elevator,
compressed.second,
)
}
}
typealias Day11State = Int
operator fun Day11State.get(index: Int) = (this shr (index * 2)) and 3
fun main() = SomeDay.mainify(Day11)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 4,130 | adventofcode | MIT License |
dynamic_programming/MinimumScoreTriangulationOfPolygon/kotlin/Solution.kt | YaroslavHavrylovych | 78,222,218 | false | {"Java": 284373, "Kotlin": 35978, "Shell": 2994} | /**
* Given N, consider a convex N-sided polygon with vertices
* labelled A[0], A[i], ..., A[N-1] in clockwise order.
*
* Suppose you triangulate the polygon into N-2 triangles.
* For each triangle, the value of that triangle is the product of the
* labels of the vertices, and the total score of the triangulation
* is the sum of these values over all N-2 triangles in the triangulation.
*
* Return the smallest possible total score that you can achieve
* with some triangulation of the polygon.
* <br>
* https://leetcode.com/problems/minimum-score-triangulation-of-polygon/
*/
class Solution {
lateinit var cache: Array<Array<Int>>
fun minScoreTriangulation(A: IntArray): Int {
cache = Array(A.size) { Array(A.size) { Int.MAX_VALUE } }
return findMin(A, 0, A.indices.last)
}
fun findMin(A:IntArray, l: Int, r: Int): Int {
if(r - l <= 1) return 0 //neighbours
if(cache[l][r] != Int.MAX_VALUE) return cache[l][r]
for(m in r-1 downTo l + 1) {
cache[l][r] = Math.min(cache[l][r],
A[l] * A[r] * A[m]
+ findMin(A, l, m)
+ findMin(A, m, r))
}
return cache[l][r]
}
}
fun main() {
println("Minimum Score Triangulation of Polygon: test is not implemented")
}
| 0 | Java | 0 | 2 | cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd | 1,390 | codility | MIT License |
src/year_2021/day_01/Day01.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2021.day_01
import readInput
object Day01 {
/**
* @return number of increases in depths
*/
fun solutionOne(sonarDepthsText: List<String>): Int {
val depths = parseDepths(sonarDepthsText)
var increases = 0
for (i in 0..depths.size - 2) {
if (depths[i] < depths[i + 1]) {
increases += 1
}
}
return increases
}
/**
* @return number of increases in depths with windows of 3 measurements
*/
fun solutionTwo(sonarDepthsText: List<String>): Int {
val depths = parseDepths(sonarDepthsText)
var increases = 0
for (i in 0..depths.size - 4) {
val currentWindow = depths[i] + depths[i + 1] + depths[i + 2]
val nextWindow = depths[i + 1] + depths[i + 2] + depths[i + 3]
if (currentWindow < nextWindow) {
increases += 1
}
}
return increases
}
private fun parseDepths(sonarDepthsText: List<String>): List<Int> {
return sonarDepthsText.map { it.toInt() }
}
}
fun main() {
val sonarDepthsText = readInput("year_2021/day_01/Day01.txt")
val solutionOne = Day01.solutionOne(sonarDepthsText)
println("Solution 1: $solutionOne")
val solutionTwo = Day01.solutionTwo(sonarDepthsText)
println("Solution 2: $solutionTwo")
}
| 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 1,386 | advent_of_code | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-09.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import kotlin.math.absoluteValue
fun main() {
val input = readInputLines(2022, "09-input")
val testInput1 = readInputLines(2022, "09-test1")
val testInput2 = readInputLines(2022, "09-test2")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput2).println()
part2(input).println()
}
private fun part1(input: List<String>) = solve(input, 2)
private fun part2(input: List<String>) = solve(input, 10)
private fun solve(input: List<String>, size: Int): Int {
val knots = MutableList(size) { Coord2D(0, 0) }
val visited = mutableSetOf(knots.last())
input.forEach { line ->
val (dir, s) = line.split(' ')
val steps = s.toInt()
repeat(steps) {
when (dir) {
"R" -> knots[0] = knots[0].copy(x = knots[0].x + 1)
"L" -> knots[0] = knots[0].copy(x = knots[0].x - 1)
"U" -> knots[0] = knots[0].copy(y = knots[0].y - 1)
"D" -> knots[0] = knots[0].copy(y = knots[0].y + 1)
}
for (i in 1 until size) {
knots[i] = knots[i].follow(knots[i - 1])
}
visited += knots.last()
}
}
return visited.size
}
private fun Coord2D.follow(other: Coord2D): Coord2D {
return if (2 <= (x - other.x).absoluteValue || 2 <= (y - other.y).absoluteValue) copy(
x = x + (other.x - x).coerceIn(-1, 1),
y = y + (other.y - y).coerceIn(-1, 1),
) else this
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,736 | advent-of-code | MIT License |
src/main/kotlin/com/colinodell/advent2022/Day02.kt | colinodell | 572,710,708 | false | {"Kotlin": 105421} | package com.colinodell.advent2022
class Day02(input: List<String>) {
private val strategyGuide = input.map { Pair(it[0], it[2]) }
fun solvePart1(): Int {
return strategyGuide
.map { Pair(Shape.from(it.first), Shape.from(it.second)) }
.sumOf { score(it.first.outcomeWhenIPlay(it.second), it.second) }
}
fun solvePart2(): Int {
return strategyGuide
.map { Pair(Shape.from(it.first), Outcome.from(it.second)) }
.map { Pair(it.first, it.first.respondWithShapeTo(it.second)) }
.sumOf { score(it.first.outcomeWhenIPlay(it.second), it.second) }
}
private fun score(outcome: Outcome, shape: Shape): Int {
return when (outcome) {
Outcome.WIN -> 6
Outcome.DRAW -> 3
Outcome.LOSE -> 0
} + when (shape) {
Shape.ROCK -> 1
Shape.PAPER -> 2
Shape.SCISSORS -> 3
}
}
enum class Outcome {
WIN, LOSE, DRAW;
companion object {
fun from(c: Char): Outcome {
return when (c) {
'X' -> LOSE
'Y' -> DRAW
'Z' -> WIN
else -> throw IllegalArgumentException("Invalid outcome: $c")
}
}
}
}
enum class Shape {
ROCK, PAPER, SCISSORS;
private fun beats(other: Shape): Boolean {
return when (this) {
ROCK -> other == SCISSORS
PAPER -> other == ROCK
SCISSORS -> other == PAPER
}
}
fun outcomeWhenIPlay(myShape: Shape): Outcome {
return when {
this == myShape -> Outcome.DRAW
this.beats(myShape) -> Outcome.LOSE
else -> Outcome.WIN
}
}
fun respondWithShapeTo(desiredOutcome: Outcome) = when (desiredOutcome) {
Outcome.WIN -> when (this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
Outcome.LOSE -> when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
Outcome.DRAW -> this
}
companion object {
fun from(c: Char): Shape {
return when (c) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> throw IllegalArgumentException("Invalid shape: $c")
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | 32da24a888ddb8e8da122fa3e3a08fc2d4829180 | 2,642 | advent-2022 | MIT License |
day15/src/main/kotlin/aoc2015/day15/Day15.kt | sihamark | 581,653,112 | false | {"Kotlin": 263428, "Shell": 467, "Batchfile": 383} | package aoc2015.day15
object Day15 {
fun highestCookieScore() = recipes()
.map { it.calculateScore() }
.max()!!
fun highestCookieScoreWith500Calories() = recipes()
.filter { it.calculateCalories() == 500 }
.map { it.calculateScore() }
.max()!!
private fun recipes(): Sequence<Recipe> {
val ingredients = input.map { Parser.parse(it) }
return CounterIterator((0..100).toList(), 4)
.asSequence()
.filter { it.sum() == 100 }
.map {
Recipe(it.mapIndexed { index, amount ->
CountedIngredient(amount, ingredients[index])
})
}
}
private data class Recipe(
val ingredients: List<CountedIngredient>
) {
fun calculateScore() = sumProperty { it.capacity } *
sumProperty { it.durability } *
sumProperty { it.flavor } *
sumProperty { it.texture }
fun calculateCalories() = sumProperty { it.calories }
private fun sumProperty(property: (Ingredient) -> Int): Int =
ingredients.map { it.amount * property(it.ingredient) }.sum().coerceAtLeast(0)
}
private data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
)
private data class CountedIngredient(
val amount: Int,
val ingredient: Ingredient
)
private class CounterIterator<T>(private val elements: List<T>, places: Int) : Iterator<List<T>> {
private var currentIndices = List(places) { 0 }
private var hasNext = true
override fun next(): List<T> {
val result = currentIndices.map { elements[it] }
currentIndices = currentIndices.next()
return result
}
override fun hasNext(): Boolean = hasNext
private fun List<Int>.next(): List<Int> {
val next = this.toMutableList()
for (index in (size - 1) downTo 0) {
val inc = next[index] + 1
if (inc >= elements.size) {
if (index == 0) {
hasNext = false
}
next[index] = 0
} else {
next[index] = inc
return next
}
}
return next
}
}
private object Parser {
private val validIngredient = Regex("""(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""")
fun parse(rawIngredient: String): Ingredient {
val parsedValues = validIngredient.find(rawIngredient)?.groupValues
?: error("no valid ingredient: $rawIngredient")
return Ingredient(
parsedValues[1],
parsedValues[2].toInt(),
parsedValues[3].toInt(),
parsedValues[4].toInt(),
parsedValues[5].toInt(),
parsedValues[6].toInt()
)
}
}
} | 0 | Kotlin | 0 | 0 | 6d10f4a52b8c7757c40af38d7d814509cf0b9bbb | 3,288 | aoc2015 | Apache License 2.0 |
aoc2022/day13.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2022
import utils.InputRetrieval
import kotlin.math.min
fun main() {
Day13.execute()
}
object Day13 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<String>): Int {
return input.windowed(2, 3).mapIndexed { index, it ->
val (left, right) = it
val result = parse(left).isSmaller(parse(right))
if (result == Result.LOWER) {
index + 1
} else 0
}.sum()
}
private val DELIMITERS = mutableListOf(parse("[[2]]", isDivider = true), parse("[[6]]", isDivider = true))
private fun part2(input: List<String>): Int {
val parsedInput = input.filter { it.isNotEmpty() }.map { parse(it) }
val inputWithDividers = DELIMITERS.apply { addAll(parsedInput) }
return inputWithDividers.sortedWith { a: DigitOrList, b: DigitOrList -> a.isSmaller(b).value }
.mapIndexed { index, value ->
if (value.isDivider) {
index + 1
} else {
0
}
}
.filter { it != 0 }
.reduce(Int::times)
}
private fun parse(input: String, isDivider: Boolean = false): DigitOrList {
val allParents = ArrayDeque<MutableList<DigitOrList>>()
var currentList: MutableList<DigitOrList>? = null
var i = 0
while (i < input.length) {
when (input[i]) {
in '0'..'9' -> {
// Get all numbers
var finalIndex = i + 1
while (input[finalIndex] != ',' && input[finalIndex] != ']') {
finalIndex++
}
val values = DigitOrList(input.substring(i, finalIndex).toInt())
currentList?.add(values)
i = finalIndex
}
'[' -> {
currentList?.also { allParents.add(it) }
currentList = mutableListOf()
i++
}
']' -> {
allParents.removeLastOrNull()?.also { parent ->
currentList?.also { parent.add(DigitOrList(it)) }
currentList = parent
}
i++
}
else -> i++
}
}
return DigitOrList(currentList!!, isDivider)
}
data class DigitOrList(var digit: Int?, var list: List<DigitOrList>?, val isDivider: Boolean) {
constructor(value: Int, isDivider: Boolean = false) : this(value, null, isDivider)
constructor(value: List<DigitOrList>, isDivider: Boolean = false) : this(null, value, isDivider)
private fun isDigit() = digit != null
fun isSmaller(other: DigitOrList): Result {
if (this.isDigit() && other.isDigit()) {
return if (this.digit!! < other.digit!!) {
Result.LOWER
} else if (this.digit!! > other.digit!!) {
Result.GREATER
} else {
Result.EQUAL
}
}
if (!this.isDigit() && !other.isDigit()) {
val size = min(this.list!!.size, other.list!!.size)
return (0 until size).map { this.list!![it].isSmaller(other.list!![it]) }.firstOrNull { it != Result.EQUAL }
?: if (this.list!!.size < other.list!!.size) {
Result.LOWER
} else if (this.list!!.size > other.list!!.size) {
Result.GREATER
} else {
Result.EQUAL
}
}
if (this.isDigit()) {
return DigitOrList(listOf(this)).isSmaller(other)
}
return this.isSmaller(DigitOrList(listOf(other)))
}
}
enum class Result(val value: Int) {
EQUAL(0),
LOWER(-1),
GREATER(1)
}
fun readInput(): List<String> = InputRetrieval.getFile(2022, 13).readLines()
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 4,225 | Advent-Of-Code | MIT License |
src/main/kotlin/leetcode/google/Problem792.kt | Magdi | 390,731,717 | false | null | package leetcode.google
/**
* https://leetcode.com/problems/number-of-matching-subsequences/
* Number of Matching Subsequences
*/
class Problem792 {
fun numMatchingSubseq(s: String, words: Array<String>): Int {
val histogram = Array(s.length) {
IntArray(26) { -1 }
}
for (i in s.lastIndex - 1 downTo 0) {
histogram[i] = histogram[i + 1].clone()
histogram[i][getIndex(s[i + 1])] = i + 1
}
return words.count {
val res = isSubSequance(s, it, histogram)
if (res) println(it)
res
}
}
private fun isSubSequance(s: String, it: String, histogram: Array<IntArray>): Boolean {
var index = 0
it.forEach { char ->
if (index >= s.length) {
return false
}
if (s[index] != char) {
if (histogram[index][getIndex(char)] == -1) {
return false
} else {
index = histogram[index][getIndex(char)] + 1
}
} else {
index++
}
}
return true
}
private fun getIndex(s: Char): Int = (s.toInt() - 'a'.toInt())
}
class Problem792_S2 {
fun numMatchingSubseq(s: String, words: Array<String>): Int {
val groups = words.map { Node(it, 0) }.groupBy { it.word[0] }.toMutableMap()
var ans = 0
s.forEach { c ->
val tmp = groups[c]
groups[c] = mutableListOf()
tmp?.forEach { node ->
node.index++
if (node.index == node.word.length) {
ans++
} else {
val list = groups.getOrDefault(node.word[node.index], mutableListOf()).toMutableList()
list.add(node)
groups[node.word[node.index]] = list
}
}
}
return ans
}
data class Node(val word: String, var index: Int)
} | 0 | Kotlin | 0 | 0 | 63bc711dc8756735f210a71454144dd033e8927d | 2,028 | ProblemSolving | Apache License 2.0 |
kotlin/src/main/kotlin/year2023/Day16.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
import year2023.Day16.Direction.*
fun main() {
val input = readInput("Day16")
Day16.part1(input).println()
Day16.part2(input).println()
}
object Day16 {
fun part1(input: List<String>): Int {
val contraption = input.map { line -> line.map { Box(it) } }
contraption.energize(Point(0, 0), RIGHT)
return contraption.countEnergized()
}
fun part2(input: List<String>): Int {
var maxEnergized = 0
for (i in input[0].indices) {
val contraption = input.map { line -> line.map { Box(it) } }
contraption.energize(Point(0, i), DOWN)
val energized = contraption.countEnergized()
if (energized > maxEnergized) {
maxEnergized = energized
}
}
for (i in input[0].indices) {
val contraption = input.map { line -> line.map { Box(it) } }
contraption.energize(Point(input.size - 1, i), UP)
val energized = contraption.countEnergized()
if (energized > maxEnergized) {
maxEnergized = energized
}
}
for (i in input.indices) {
val contraption = input.map { line -> line.map { Box(it) } }
contraption.energize(Point(i, 0), RIGHT)
val energized = contraption.countEnergized()
if (energized > maxEnergized) {
maxEnergized = energized
}
}
for (i in input.indices) {
val contraption = input.map { line -> line.map { Box(it) } }
contraption.energize(Point(i, input[0].length - 1), LEFT)
val energized = contraption.countEnergized()
if (energized > maxEnergized) {
maxEnergized = energized
}
}
return maxEnergized
}
private enum class Direction {
UP, DOWN, LEFT, RIGHT
}
private data class Box(val value: Char, val energized: MutableSet<Direction> = mutableSetOf()) {
fun reflect(beamDirection: Direction): List<Direction> {
return when (value) {
'.' -> listOf(beamDirection)
'-' -> when (beamDirection) {
UP, DOWN -> listOf(LEFT, RIGHT)
LEFT, RIGHT -> listOf(beamDirection)
}
'|' -> when (beamDirection) {
UP, DOWN -> listOf(beamDirection)
LEFT, RIGHT -> listOf(UP, DOWN)
}
'/' -> when (beamDirection) {
UP -> listOf(RIGHT)
DOWN -> listOf(LEFT)
LEFT -> listOf(DOWN)
RIGHT -> listOf(UP)
}
'\\' -> when (beamDirection) {
UP -> listOf(LEFT)
DOWN -> listOf(RIGHT)
LEFT -> listOf(UP)
RIGHT -> listOf(DOWN)
}
else -> error("Invalid value")
}
}
}
private data class Point(val row: Int, val column: Int) {
fun to(direction: Direction): Point {
return when (direction) {
UP -> Point(this.row - 1, this.column)
DOWN -> Point(this.row + 1, this.column)
LEFT -> Point(this.row, this.column - 1)
RIGHT -> Point(this.row, this.column + 1)
}
}
}
private fun List<List<Box>>.energize(point: Point, beamDirection: Direction) {
if (point.row < 0 || point.column < 0
|| point.row >= this.size || point.column >= this[point.row].size
) {
return
}
val box = this[point.row][point.column]
if (beamDirection in box.energized) {
return
}
box.energized.add(beamDirection)
val reflectedBeams = box.reflect(beamDirection)
reflectedBeams.forEach {
val reflectedBeam = it
val newPoint = point.to(reflectedBeam)
this.energize(newPoint, reflectedBeam)
}
}
private fun List<List<Box>>.countEnergized(): Int {
return this.sumOf { line -> line.count { it.energized.isNotEmpty() } }
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 4,258 | advent-of-code | MIT License |
src/main/kotlin/day12/Day12.kt | daniilsjb | 434,765,082 | false | {"Kotlin": 77544} | package day12
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day12/Day12.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 12 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private typealias Label = String
private typealias Graph = Map<Label, List<Label>>
private fun parse(path: String): Graph {
val graph = mutableMapOf<Label, List<Label>>()
for (line in File(path).readLines()) {
val (lhs, rhs) = line.split("-")
graph.merge(lhs, listOf(rhs)) { a, b -> a + b }
graph.merge(rhs, listOf(lhs)) { a, b -> a + b }
}
return graph
}
// Depth-first count of all possible paths from a node to the end of the graph.
// When bias is set to true, a single small cave is allowed to be visited twice.
private fun countPaths(
graph: Graph,
current: Label,
visited: List<Label> = listOf(current),
bias: Boolean = false
): Int =
graph.getValue(current).sumOf { neighbour ->
if (neighbour == "end") {
1
} else if (neighbour == "start") {
0
} else if (neighbour.all(Char::isLowerCase)) {
if (!visited.contains(neighbour)) {
countPaths(graph, neighbour, visited + neighbour, bias)
} else if (bias) {
countPaths(graph, neighbour, visited + neighbour)
} else {
0
}
} else {
countPaths(graph, neighbour, visited + neighbour, bias)
}
}
fun part1(graph: Graph) =
countPaths(graph, "start")
fun part2(graph: Graph) =
countPaths(graph, "start", bias = true)
| 0 | Kotlin | 0 | 1 | bcdd709899fd04ec09f5c96c4b9b197364758aea | 1,757 | advent-of-code-2021 | MIT License |
src/day09/Day09.kt | IThinkIGottaGo | 572,833,474 | false | {"Kotlin": 72162} | package day09
import readInput
import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val head = Node()
val tail = Node()
head.next = tail
doMove(head, input)
return tail.visited.size
}
fun part2(input: List<String>): Int {
val head = Node()
var tail = head
repeat(9) {
tail.next = Node()
tail = tail.next!!
}
doMove(head, input)
return tail.visited.size
}
val testInput = readInput("day09_test")
check(part1(testInput) == 88)
check(part2(testInput) == 36)
val input = readInput("day09")
println(part1(input)) // 5981
println(part2(input)) // 2352
}
fun doMove(head: Node, input: List<String>) {
input.forEach { line ->
val (action, steps) = line.split(" ").let { Pair(it[0], it[1].toInt()) }
repeat(steps) {
head.move(action) // each move 1 step, repeat steps times
}
}
}
data class Node(var x: Int = 0, var y: Int = 0) {
var next: Node? = null
val visited = hashSetOf(Pair(x, y))
fun move(action: String) {
when (action) {
"U" -> ++y
"D" -> --y
"L" -> --x
"R" -> ++x
else -> error("unknown direction!")
}
next?.sync(this)
}
private fun sync(prev: Node) {
val (ofx, ofy) = calcOffset(prev)
// Any state that requires Tail sync, it has an offset greater than 2 in at least one direction.
// Then shrink distance to that direction.
if (abs(ofx) >= 2 || abs(ofy) >= 2) {
if (ofx > 0) ++x else if (ofx < 0) --x
if (ofy > 0) ++y else if (ofy < 0) --y
visited += Pair(x, y)
}
next?.sync(this)
}
private fun calcOffset(prev: Node): Pair<Int, Int> = Pair(prev.x - x, prev.y - y)
} | 0 | Kotlin | 0 | 0 | 967812138a7ee110a63e1950cae9a799166a6ba8 | 1,900 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2018/Day18.kt | tginsberg | 155,878,142 | false | null | /*
* Copyright (c) 2018 by <NAME>
*/
/**
* Advent of Code 2018, Day 18 - Settlers of The North Pole
*
* Problem Description: http://adventofcode.com/2018/day/18
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day18/
*/
package com.ginsberg.advent2018
import java.util.Arrays
typealias Forest = Array<CharArray>
class Day18(rawInput: List<String>) {
private val forest: Forest = rawInput.map { it.toCharArray() }.toTypedArray()
fun solvePart1(): Int =
growTrees().drop(9).first().value()
fun solvePart2(find: Int = 1_000_000_000): Int {
val seen = mutableMapOf<Int, Int>()
var generation = 0
val firstRepeating = growTrees().dropWhile { tree ->
val treeHash = tree.hash()
generation++
if (treeHash in seen) {
false
} else {
seen[treeHash] = generation
true
}
}.first()
val cycleLength = generation - seen[firstRepeating.hash()]!!
val remainingSteps = (find - generation) % cycleLength
// Fast forward to the target
return growTrees(firstRepeating).drop(remainingSteps - 1).first().value()
}
private fun growTrees(initial: Forest = forest): Sequence<Forest> = sequence {
var current = initial
while (true) {
current = current.nextGeneration()
yield(current)
}
}
private fun Forest.nextGeneration(): Array<CharArray> =
this.mapIndexed { y, row ->
row.mapIndexed { x, _ -> this.nextGenerationSpot(Point(x, y)) }.toCharArray()
}.toTypedArray()
private fun Forest.nextGenerationSpot(at: Point): Char {
val neighborMap = this.countNeighbors(at)
return when (val space = this[at]) {
OPEN -> if (neighborMap.getOrDefault(TREE, 0) >= 3) TREE else OPEN
TREE -> if (neighborMap.getOrDefault(LUMBERYARD, 0) >= 3) LUMBERYARD else TREE
LUMBERYARD -> if (neighborMap.getOrDefault(LUMBERYARD, 0) >= 1 &&
neighborMap.getOrDefault(TREE, 0) >= 1) LUMBERYARD else OPEN
else -> space
}
}
private fun Forest.countNeighbors(at: Point): Map<Char, Int> =
at.neighbors(false)
.filterNot { it.x >= this[0].size }
.filterNot { it.y >= this.size }
.map { this[it] }
.groupingBy { it }
.eachCount()
private fun Forest.value(): Int =
this.flatMap { row ->
row.map { it }
}
.groupingBy { it }
.eachCount()
.run {
getOrDefault(TREE, 0) * getOrDefault(LUMBERYARD, 0)
}
private fun Forest.hash(): Int =
Arrays.deepHashCode(this)
companion object {
private const val OPEN = '.'
private const val LUMBERYARD = '#'
private const val TREE = '|'
}
}
| 0 | Kotlin | 1 | 18 | f33ff59cff3d5895ee8c4de8b9e2f470647af714 | 2,961 | advent-2018-kotlin | MIT License |
src/main/kotlin/g2901_3000/s2910_minimum_number_of_groups_to_create_a_valid_assignment/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2910_minimum_number_of_groups_to_create_a_valid_assignment
// #Medium #Array #Hash_Table #Greedy #2023_12_27_Time_745_ms_(75.00%)_Space_65.6_MB_(75.00%)
class Solution {
fun minGroupsForValidAssignment(nums: IntArray): Int {
val count = getCountMap(nums)
val countFreq = getCountFrequencyMap(count)
val minFrequency = getMinFrequency(countFreq)
for (size in minFrequency downTo 1) {
val group = calculateGroups(countFreq, size)
if (group > 0) {
return group
}
}
return -1
}
private fun getCountMap(nums: IntArray): Map<Int, Int> {
val count: MutableMap<Int, Int> = HashMap()
for (num in nums) {
count.merge(num, 1) { a: Int?, b: Int? ->
Integer.sum(
a!!, b!!
)
}
}
return count
}
private fun getCountFrequencyMap(count: Map<Int, Int>): Map<Int, Int> {
val countFreq: MutableMap<Int, Int> = HashMap()
for (c in count.values) {
countFreq.merge(c, 1) { a: Int?, b: Int? ->
Integer.sum(
a!!, b!!
)
}
}
return countFreq
}
private fun getMinFrequency(countFreq: Map<Int, Int>): Int {
return countFreq.keys.stream()
.min { obj: Int, anotherInteger: Int? -> obj.compareTo(anotherInteger!!) }
.orElseThrow { IllegalStateException("Count frequency map is empty") }
}
private fun calculateGroups(countFreq: Map<Int, Int>, size: Int): Int {
var group = 0
for ((len, value) in countFreq) {
val rem = len % (size + 1)
val g = len / (size + 1)
group += if (rem == 0) {
g * value
} else {
val need = size - rem
if (g >= need) {
(g + 1) * value
} else {
return -1
}
}
}
return group
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,096 | LeetCode-in-Kotlin | MIT License |
src/Day03.kt | AxelUser | 572,845,434 | false | {"Kotlin": 29744} | fun main() {
fun List<String>.solve1(): Int {
var res = 0
for (rucksack in this) {
val set = mutableSetOf<Char>()
for (i in 0 until rucksack.length / 2) {
set.add(rucksack[i])
}
for (i in rucksack.length / 2 until rucksack.length) {
if (set.contains(rucksack[i])) {
res += if (rucksack[i].isUpperCase()) rucksack[i] - 'A' + 27 else rucksack[i] - 'a' + 1
break
}
}
}
return res
}
fun List<String>.solve2(): Int {
var res = 0
for (group in windowed(3, 3)) {
val set = mutableMapOf<Char, Int>()
for (gi in group.indices) {
for (c in group[gi]) {
if (set.compute(c) { _, v -> if (v == null) 1 shl gi else v or (1 shl gi) } == 7) {
res += if (c.isUpperCase()) c - 'A' + 27 else c - 'a' + 1
break
}
}
}
}
return res
}
fun part1(input: List<String>): Int {
return input.solve1()
}
fun part2(input: List<String>): Int {
return input.solve2()
}
check(part1(readInput("Day03_test")) == 157)
check(part2(readInput("Day03_test")) == 70)
println(part1(readInput("Day03")))
println(part2(readInput("Day03")))
} | 0 | Kotlin | 0 | 1 | 042e559f80b33694afba08b8de320a7072e18c4e | 1,437 | aoc-2022 | Apache License 2.0 |
src/Day02_RockPaperScissors.kt | raipc | 574,467,742 | false | {"Kotlin": 9511} | fun main() {
checkAndSolve("Day02", 15) { calculateScore(it, Strategy.SUGGEST_EXACT_MOVE) }
checkAndSolve("Day02", 12) { calculateScore(it, Strategy.SUGGEST_OUTPUT) }
}
private fun calculateScore(lines: List<String>, strategy: Strategy): Int = lines
.sumOf { calculateScoreForSingleGame(it, strategy) }
private fun calculateScoreForSingleGame(game: String, strategy: Strategy) =
strategy.calculateScore(game[0], game[2])
private enum class Strategy {
SUGGEST_EXACT_MOVE {
override fun calculateScore(input: Char, suggestion: Char): Int {
val opponentCode = normalizeValue(input, 'A')
val playerCode = normalizeValue(suggestion, 'X')
return playerCode + when (playerCode - opponentCode) {
0 -> 3
1, -2 -> 6
else -> 0
}
}
},
SUGGEST_OUTPUT {
override fun calculateScore(input: Char, suggestion: Char): Int {
val pointsFromSuggestion = (suggestion - 'X') * 3
return pointsFromSuggestion + when (pointsFromSuggestion) {
3 -> normalizeValue(input, 'A')
6 -> if (input == 'C') 1 else normalizeValue(input, 'A') + 1
0 -> if (input == 'A') 3 else normalizeValue(input, 'A') - 1
else -> throw IllegalArgumentException()
}
}
};
fun normalizeValue(value: Char, base: Char) = value.code - base.code + 1
abstract fun calculateScore(input: Char, suggestion: Char): Int
} | 0 | Kotlin | 0 | 0 | 9068c21dc0acb5e1009652b4a074432000540d71 | 1,529 | adventofcode22 | Apache License 2.0 |
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day07.kt | loehnertz | 573,145,141 | false | {"Kotlin": 53239} | package codes.jakob.aoc
import codes.jakob.aoc.Day07.Directory
import codes.jakob.aoc.Day07.File
import codes.jakob.aoc.shared.splitMultiline
import codes.jakob.aoc.shared.toPair
class Day07 : Solution() {
override fun solvePart1(input: String): Any {
val root: Directory = buildDirectoryTree(input)
val directoryByRecursiveSize: Map<Directory, Long> = calculateDirectorySizes(root)
return directoryByRecursiveSize.values.filter { it <= SMALL_DIRECTORIES_MAX_SIZE }.sum()
}
override fun solvePart2(input: String): Any {
val root: Directory = buildDirectoryTree(input)
val directoryByRecursiveSize: Map<Directory, Long> = calculateDirectorySizes(root)
val missingSpace: Long = MIN_UNUSED_SPACE - (TOTAL_DISK_SIZE - root.recursiveFileSize())
return directoryByRecursiveSize.values.filter { it >= missingSpace }.minBy { it - missingSpace }
}
private fun calculateDirectorySizes(root: Directory): Map<Directory, Long> {
return root.allRecursiveChildren().associateWith { it.recursiveFileSize() }
}
private fun buildDirectoryTree(input: String): Directory {
val root = Directory(name = "/", parent = null)
var currentDirectory: Directory = root
for (command: Command in parse(input.splitMultiline())) {
when (command) {
is ChangeDirectory -> {
currentDirectory = if (command.path == root.name) {
root
} else {
if (command.path == ONE_LEVEL_BACK) {
currentDirectory.parent!!
} else {
currentDirectory.children.first { it.name == command.path }
}
}
}
is ListDirectory -> {
currentDirectory.children = command.directories().map { Directory(it, currentDirectory) }
currentDirectory.files = command.files()
}
}
}
return root
}
private fun parse(lines: List<String>): List<Command> {
val linesIndexed: List<Pair<String, Int>> = lines.withIndex().map { it.value to it.index }
val parsed: MutableList<Command> = mutableListOf()
var index = 0
while (index < linesIndexed.size) {
val (line, lineIndex) = linesIndexed[index]
if (line.startsWith("\$ cd")) {
parsed += ChangeDirectory(line.substringAfterLast(" "))
index++
} else if (line == "\$ ls") {
val takeWhile: List<Pair<String, Int>> =
linesIndexed.drop(index + 1).takeWhile { !it.first.startsWith("$") }
parsed += ListDirectory(takeWhile.map { it.first })
index = takeWhile.map { it.second }.last() + 1
}
}
return parsed
}
data class Directory(
val name: String, val parent: Directory?
) {
lateinit var children: List<Directory>
lateinit var files: List<File>
fun recursiveFileSize(): Long {
fun recurse(directory: Directory): Long {
val combinedFileSize: Long = directory.files.combinedFileSize()
return if (directory.children.isEmpty()) {
combinedFileSize
} else {
combinedFileSize + directory.children.sumOf { recurse(it) }
}
}
return recurse(this)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Directory) return false
if (name != other.name) return false
if (parent != other.parent) return false
return true
}
override fun hashCode(): Int {
var result: Int = name.hashCode()
result = 31 * result + (parent?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "Directory(name='$name', parent=${parent?.name})"
}
}
data class File(
val name: String, val size: Long
)
open class Command
data class ChangeDirectory(
val path: String
) : Command()
data class ListDirectory(
val output: List<String>
) : Command() {
fun directories(): List<String> {
return output.filter { it.startsWith("dir") }.map { it.split(" ").last() }
}
fun files(): List<File> {
return output.filterNot { it.startsWith("dir") }.map { it.split(" ").toPair() }
.map { (size, name) -> File(name, size.toLong()) }
}
}
companion object {
private const val ONE_LEVEL_BACK = ".."
private const val SMALL_DIRECTORIES_MAX_SIZE = 100_000L
private const val TOTAL_DISK_SIZE = 70_000_000L
private const val MIN_UNUSED_SPACE = 30_000_000L
}
}
private fun List<File>.combinedFileSize(): Long = sumOf { it.size }
private fun Directory.allRecursiveChildren(): Set<Directory> {
fun recurse(directory: Directory): List<Directory> {
return if (directory.children.isEmpty()) {
emptyList()
} else {
directory.children + directory.children.flatMap { recurse(it) }
}
}
return recurse(this).toSet()
}
fun main() = Day07().solve()
| 0 | Kotlin | 0 | 0 | ddad8456dc697c0ca67255a26c34c1a004ac5039 | 5,468 | advent-of-code-2022 | MIT License |
src/Day04.kt | 6234456 | 572,616,769 | false | {"Kotlin": 39979} | fun main() {
fun overlapping(l: List<List<Int>>):Boolean{
val a = l.first()
val b = l.last()
val a1 = a.first()
val a2 = a.last()
val b1 = b.first()
val b2 = b.last()
return (a1 <= b1 && b2 <= a2) || (b1 <= a1 && a2 <= b2)
}
fun overlapping0(l: List<List<Int>>):Boolean{
val a = l.first()
val b = l.last()
val a1 = a.first()
val a2 = a.last()
val b1 = b.first()
val b2 = b.last()
return !((a1 > b2) || (b1 > a2))
}
fun part1(input: List<String>): Int {
return input.map {
it.split(",").map {
x ->
x.split("-").map { y -> y.toInt() }
}
}.count {
overlapping(it)
}
}
fun part2(input: List<String>): Int {
return input.map {
it.split(",").map {
x ->
x.split("-").map { y -> y.toInt() }
}
}.count {
overlapping0(it)
}
}
var input = readInput("Test04")
println(part1(input))
println(part2(input))
input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b6d683e0900ab2136537089e2392b96905652c4e | 1,224 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/commonMain/kotlin/ai/hypergraph/kaliningraph/parsing/Levenshtein.kt | breandan | 245,074,037 | false | {"Kotlin": 1482924, "Haskell": 744, "OCaml": 200} | package ai.hypergraph.kaliningraph.parsing
import ai.hypergraph.kaliningraph.*
import ai.hypergraph.kaliningraph.automata.*
import ai.hypergraph.kaliningraph.repair.*
import ai.hypergraph.kaliningraph.types.*
import ai.hypergraph.kaliningraph.types.times
import kotlin.math.*
// Only accept states that are within radius dist of (strLen, 0)
fun acceptStates(strLen: Int, dist: Int) =
((strLen - dist..strLen) * (0..dist))
.filter { (i, j) -> ((strLen - i) + j).absoluteValue <= dist }
.map { (i, j) -> "d:$i:$j" }
fun backtrace(x: Int, y: Int, sym: Σᐩ) =
if (x == 0 && y == 0) sym else if (x < 0) "" else "d:$x:$y $sym"
// https://fulmicoton.com/posts/levenshtein#observations-lets-count-states
private fun levenshteinTransitions(symbols: List<Σᐩ>, i: Int) =
"d:0:$i -> ${if(i == 1) "" else "d:0:${i - 1} "}*\n" +
symbols.mapIndexed { j, s ->
"d:${j + 1}:$i -> " +
// Inbound transitions
backtrace(j, i, s) + " | " +
backtrace(j, i - 1, "*") + " | " +
backtrace(j + 1, i - 1, "*") +
if (0 < j) " | " + backtrace(j - 1, i - 1, symbols.getOrElse(j) { "" }) else ""
}.joinToString("\n")
fun constructLevenshteinCFG(symbols: List<Σᐩ>, dist: Int, alphabet: Set<Σᐩ> = symbols.toSet() + "ε"): Σᐩ =
"""
START -> ${acceptStates(symbols.size, dist).joinToString(" | ")}
* -> ${(alphabet + symbols).joinToString(" | ") { "%$it" }}
""".trimIndent() +
(alphabet + symbols).joinToString("\n", "\n", "\n") { "%$it -> $it" } + "d:1:0 -> ${symbols[0]}\n" +
symbols.drop(1).mapIndexed { i, symbol -> "d:${i+2}:0 -> d:${i+1}:0 $symbol" }.joinToString("\n", "\n") +
(1..dist).joinToString("\n\n", "\n") { levenshteinTransitions(symbols, it) }
/**
* Takes a [CFG], an [unparseable] string, and a [solver], and returns a sequence of
* parseable strings each within Levenshtein distance δ([unparseable], ·) <= [maxDist].
* @see [CJL.alignNonterminals]
*/
fun CFG.levenshteinRepair(maxDist: Int, unparseable: List<Σᐩ>, solver: CJL.(List<Σᐩ>) -> Sequence<Σᐩ>): Sequence<Σᐩ> {
val alphabet = terminals + unparseable + "ε"
val levCFG = constructLevenshteinCFG(unparseable, maxDist, alphabet).parseCFG().noNonterminalStubs
// println("Levenshtein CFG: ${levCFG.prettyPrint()}")
val template = List(unparseable.size + maxDist) { "_" }
return (this intersect levCFG).solver(template)
.map { it.replace("ε", "").tokenizeByWhitespace().joinToString(" ") }.distinct()
}
fun makeLevFSA(str: Σᐩ, dist: Int): FSA = makeLevFSA(str.tokenizeByWhitespace(), dist)
fun makeLevFSA(
str: List<Σᐩ>,
dist: Int,
digits: Int = (str.size * dist).toString().length,
): FSA =
(upArcs(str, dist, digits) +
diagArcs(str, dist, digits) +
str.mapIndexed { i, it -> rightArcs(i, dist, it, digits) }.flatten() +
str.mapIndexed { i, it -> knightArcs(i, dist, it, digits, str) }.flatten())
.let { Q ->
val initialStates = setOf("q_" + pd(0, digits).let { "$it/$it" })
fun Σᐩ.unpackCoordinates() =
substringAfter('_').split('/')
.let { (i, j) -> i.toInt() to j.toInt() }
val finalStates = mutableSetOf<String>()
Q.states.forEach {
val (i, j) = it.unpackCoordinates()
if ((str.size - i + j).absoluteValue <= dist) finalStates.add(it)
}
FSA(Q, initialStates, finalStates)
// .nominalize()
.also { println("Levenshtein-${str.size}x$dist automaton has ${Q.size} arcs!") }
}
private fun pd(i: Int, digits: Int) = i.toString().padStart(digits, '0')
/**
TODO: upArcs and diagArcs are the most expensive operations taking ~O(2n|Σ|) to construct.
Later, the Bar-Hillel construction creates a new production for every triple QxQxQ, so it
increases the size of generated grammar by (2n|Σ|)^3. To fix this, we must instead create
a nominal or parametric CFG with arcs which denote infinite alphabets.
See: [ai.hypergraph.kaliningraph.repair.CEAProb]
*//*
References
- https://arxiv.org/pdf/1402.0897.pdf#section.7
- https://arxiv.org/pdf/2311.03901.pdf#subsection.2.2
*/
/*
s∈Σ i∈[0,n] j∈[1,k]
-----------------------
(q_i,j−1 -s→ q_i,j)∈δ
*/
fun upArcs(str: List<Σᐩ>, dist: Int, digits: Int): TSA =
((0..<str.size + dist).toSet() * (1..dist).toSet())
// .filter { (i, _, s) -> str.size <= i || str[i] != s }
.filter { (i, j) -> i <= str.size || i - str.size < j }
.map { (i, j) -> i to j to if (i < str.size) str[i] else "###" }
.map { (i, j, s) -> i to j - 1 to "[!=]$s" to i to j }
.postProc(digits)
/*
s∈Σ i∈[1,n] j ∈[1,k]
-------------------------
(q_i−1,j−1 -s→ q_i,j)∈δ
*/
fun diagArcs(str: List<Σᐩ>, dist: Int, digits: Int): TSA =
((1..<str.size + dist).toSet() * (1..dist).toSet())
// .filter { (i, _, s) -> str.size <= i - 1 || str[i - 1] != s }
.filter { (i, j) -> i <= str.size || i - str.size <= j }
.map { (i, j) -> i to j to if (str.size <= i - 1) "###" else str[i - 1] }
.map { (i, j, s) -> i - 1 to j - 1 to "[!=]$s" to i to j }
.postProc(digits)
/*
s=σ_i i∈[1,n] j∈[0,k]
-----------------------
(q_i−1,j -s→ q_i,j)∈δ
*/
fun rightArcs(idx: Int, dist: Int, letter: Σᐩ, digits: Int): TSA =
(setOf(idx + 1) * (0..dist).toSet() * setOf(letter))
.map { (i, j, s) -> i - 1 to j to s to i to j }.postProc(digits)
/*
s=σ_i i∈[2,n] j∈[1,k]
-------------------------
(q_i−2,j−1 -s→ q_i,j)∈δ
*/
fun knightArcs(idx: Int, dist: Int, letter: Σᐩ, digits: Int): TSA =
if (idx < 1) setOf()
else (setOf(idx + 1) * (1..dist).toSet() * setOf(letter))
.map { (i, j, s) -> i - 2 to j - 1 to s to i to j }.postProc(digits)
fun knightArcs(idx: Int, dist: Int, letter: Σᐩ, digits: Int, str: List<Σᐩ>): TSA =
(1..dist).flatMap { d ->
(setOf(idx) * (0..dist).toSet())
.filter { (i, j) -> i + d + 1 <= str.size && j + d <= dist }
.map { (i, j) -> i to j to str[i + d] to (i + d + 1) to (j + d) }
}.postProc(digits)
fun List<Π5<Int, Int, Σᐩ, Int, Int>>.postProc(digits: Int) =
map { (a, b, s, d, e) ->
pd(a, digits) to pd(b, digits) to s to pd(d, digits) to pd(e, digits)
}.map { (a, b, s, d, e) ->
"q_$a/$b" to s to "q_$d/$e"
}.toSet()
fun allPairsLevenshtein(s1: Set<Σᐩ>, s2: Set<Σᐩ>) =
(s1 * s2).sumOf { (a, b) -> levenshtein(a, b) }
fun levenshtein(s1: Σᐩ, s2: Σᐩ): Int =
levenshtein(s1.tokenizeByWhitespace().toList(), s2.tokenizeByWhitespace().toList())
fun <T> levenshtein(o1: List<T>, o2: List<T>): Int {
var prev = IntArray(o2.size + 1)
for (j in 0 until o2.size + 1) prev[j] = j
for (i in 1 until o1.size + 1) {
val curr = IntArray(o2.size + 1)
curr[0] = i
for (j in 1 until o2.size + 1) {
val d1 = prev[j] + 1
val d2 = curr[j - 1] + 1
val d3 = prev[j - 1] + if (o1[i - 1] == o2[j - 1]) 0 else 1
curr[j] = min(min(d1, d2), d3)
}
prev = curr
}
return prev[o2.size]
}
fun levenshteinAlign(a: Σᐩ, b: Σᐩ): List<Pair<Σᐩ?, Σᐩ?>> =
levenshteinAlign(a.tokenizeByWhitespace(), b.tokenizeByWhitespace())
fun <T> levenshteinAlign(a: List<T>, b: List<T>): List<Pair<T?, T?>> {
val costs = Array(a.size + 1) { IntArray(b.size + 1) }
for (j in 0..b.size) costs[0][j] = j
for (i in 1..a.size) {
costs[i][0] = i
for (j in 1..b.size) {
val temp = costs[i - 1][j - 1] + (if (a[i - 1] == b[j - 1]) 0 else 1)
costs[i][j] = minOf(1 + minOf(costs[i - 1][j], costs[i][j - 1]), temp)
}
}
val aPathRev = mutableListOf<T?>()
val bPathRev = mutableListOf<T?>()
var i = a.size
var j = b.size
while (i > 0 && j > 0) {
val temp = costs[i - 1][j - 1] + (if (a[i - 1] == b[j - 1]) 0 else 1)
when (costs[i][j]) {
temp -> {
aPathRev.add(a[--i])
bPathRev.add(b[--j])
}
1 + costs[i-1][j] -> {
aPathRev.add(a[--i])
bPathRev.add(null)
}
1 + costs[i][j-1] -> {
aPathRev.add(null)
bPathRev.add(b[--j])
}
}
}
while (i > 0) {
aPathRev.add(a[--i])
bPathRev.add(null)
}
while (j > 0) {
aPathRev.add(null)
bPathRev.add(b[--j])
}
val revPathA = aPathRev.reversed()
val revPathB = bPathRev.reversed()
return revPathA.zip(revPathB)
}
fun <T> List<Pair<T?, T?>>.patchSize(): Int = count { (a, b) -> a != b }
fun <T> List<Pair<T?, T?>>.summarize(): Σᐩ =
mapIndexed { i, it -> it to i }.filter { (a, b) -> a != b }
.joinToString(", ") { (a, b, i) ->
when {
// Green (insertion)
a == null -> "I::$b::$i"
// Red (deletion)
b == null -> "D::$a::$i"
// Orange (substitution)
a != b -> "S::$a::$b::$i"
else -> b.toString()
}
}
fun <T> List<Pair<T?, T?>>.paintANSIColors(): Σᐩ =
joinToString(" ") { (a, b) ->
when {
// Green (insertion)
a == null -> "$ANSI_GREEN_BACKGROUND$b$ANSI_RESET"
// Red (deletion)
b == null -> "$ANSI_RED_BACKGROUND$a$ANSI_RESET"
// Orange (substitution)
a != b -> "$ANSI_ORANGE_BACKGROUND$b$ANSI_RESET"
else -> b.toString()
}
} | 0 | Kotlin | 8 | 100 | c755dc4858ed2c202c71e12b083ab0518d113714 | 9,122 | galoisenne | Apache License 2.0 |
src/main/Day21.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day21
import day21.Operation.*
import utils.readInput
import java.util.*
sealed interface Job
data class Number(val value: Long) : Job
data class Wait(val left: String, val right: String, val operation: Operation) : Job
enum class Operation(val operation: (Long, Long) -> Long) {
ADD(Long::plus),
SUB(Long::minus),
MUL(Long::times),
DIV(Long::div);
fun invert() =
when (this) {
ADD -> SUB
SUB -> ADD
MUL -> DIV
DIV -> MUL
}
operator fun invoke(left: Long, right: Long) = operation(left, right)
}
data class Monkeys(private val jobs: Map<String, Job>) {
fun yell(name: String): Long =
when (val job = jobs[name]) {
is Number -> job.value
is Wait -> with(job) { operation(yell(left), yell(right)) }
null -> error("No monkey named $name")
}
fun match(): Long {
val jobs = jobs + ("root" to (jobs["root"] as Wait).copy(operation = SUB))
val path = findPath("root", "humn") ?: error("No path from 'root' to 'humn'")
var balance = 0L
for ((parent, current) in path.windowed(2)) {
val (left, right, op) = jobs[parent] as Wait
val other = yell(if (current == left) right else left)
balance =
if (current == right && (op == DIV || op == SUB)) {
op(other, balance)
} else {
op.invert().invoke(balance, other)
}
}
return balance
}
private fun findPath(start: String, end: String): List<String>? {
val queue = ArrayDeque<List<String>>()
queue.add(listOf(start))
while (queue.isNotEmpty()) {
val path = queue.remove()
val current = path.last()
if (current == end) return path
val job = jobs[current]
if (job is Wait) {
queue.add(path + job.left)
queue.add(path + job.right)
}
}
return null
}
}
fun readJobs(filename: String): Monkeys =
readInput(filename)
.associate {
val (name, job) = it.split(": ".toRegex())
name to job.readJob()
}
.let(::Monkeys)
private fun String.readJob(): Job {
val parts = split(" ")
return if (parts.size == 1) {
Number(parts[0].toLong())
} else {
Wait(parts[0], parts[2], parts[1].toOperation())
}
}
private fun String.toOperation(): Operation =
when (this) {
"+" -> ADD
"-" -> SUB
"*" -> MUL
"/" -> DIV
else -> error("Unknown operation $this")
}
private const val filename = "Day21"
fun part1(filename: String) = readJobs(filename).yell("root")
fun part2(filename: String) = readJobs(filename).match()
fun main() {
println(part1(filename))
println(part2(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 2,925 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/briarshore/aoc2022/day01/Puzzle1.kt | steveswing | 579,243,154 | false | {"Kotlin": 47151} | package com.briarshore.aoc2022.day01
import println
import readInput
import kotlin.math.max
fun main() {
fun part1Simple(input: List<String>): Int {
var max = 0;
var total = 0;
for (s in input) {
if (s.isNotEmpty()) {
total += s.toInt()
} else {
max = max(max, total)
total = 0
}
}
return max
}
fun part1UsingGroupBy(input: List<String>): Int {
var elfNbr = 0
val calorieItemsByElf: Map<String, List<Int>> = input.groupBy({
if (it.isEmpty()) {
elfNbr++
}
return@groupBy "Elf$elfNbr"
},
{
return@groupBy if (it.isEmpty()) {
0
} else {
it.toInt()
}
})
val calorieTotalsByElf = calorieItemsByElf.mapValues { it.value.sum() }
return calorieTotalsByElf.values.max()
}
fun part1UsingMutatingFold(input: List<String>): Int {
return input.fold(mutableListOf(0)) { acc: MutableList<Int>, s: String ->
if (s.isEmpty()) {
acc.add(0)
} else {
val lastIndex = acc.lastIndex
acc[lastIndex] = acc[lastIndex].plus(s.toInt())
}
return@fold acc
}.max()
}
fun sharedFold(input: List<String>) =
input.fold(mutableListOf(mutableListOf())) { acc: MutableList<MutableList<Int>>, s: String ->
if (s.isEmpty()) {
acc.add(mutableListOf())
} else {
acc.last().add(s.toInt())
}
return@fold acc
}
fun part1UsingFold(input: List<String>): Int {
return sharedFold(input).maxOf { it.sum() }
}
fun part2UsingFold(input: List<String>): Int {
return sharedFold(input).map { it.sum() }
.sortedDescending()
.take(3)
.sum()
}
// fun part2(input: List<String>): Int {
// return input.size
// }
// test if implementation meets criteria from the description, like:
val testInput = readInput("d1p1-sample-data")
check(part1Simple(testInput) == 24000)
check(part1UsingGroupBy(testInput) == 24000)
check(part1UsingMutatingFold(testInput) == 24000)
check(part1UsingFold(testInput) == 24000)
val realInput = readInput("d1p1-input")
val part1Simple = part1Simple(realInput)
"part1Simple $part1Simple".println()
check(part1Simple == 71934)
val part1UsingGroupBy = part1UsingGroupBy(realInput)
"part1UsingGroupBy $part1UsingGroupBy".println()
check(part1UsingGroupBy == 71934)
val part1UsingMutatingFold = part1UsingMutatingFold(realInput)
"part1UsingMutatingFold $part1UsingMutatingFold".println()
check(part1UsingMutatingFold == 71934)
val part1UsingFold = part1UsingFold(realInput)
"part1UsingFold $part1UsingFold".println()
check(part1UsingFold == 71934)
check(part2UsingFold(testInput) == 45000)
val part2UsingFold = part2UsingFold(realInput)
check(part2UsingFold == 211447)
"part2UsingFold $part2UsingFold".println()
// val input = readInput("Day01")
// part1(input).println()
// part2(input).println()
}
| 0 | Kotlin | 0 | 0 | a0d19d38dae3e0a24bb163f5f98a6a31caae6c05 | 3,266 | 2022-AoC-Kotlin | Apache License 2.0 |
src/Day11.kt | robotfooder | 573,164,789 | false | {"Kotlin": 25811} | fun main() {
fun runRounds(monkeys: List<Monkey>, rounds: Int, reliefer: (Long) -> Long): Long {
for (round in 1..rounds) {
monkeys.forEach { monkey ->
monkey.inspectItems(reliefer).forEach {
val (toMonkey, worryLevel) = it
monkeys[toMonkey].items.add(worryLevel)
}
}
}
return monkeys
.map { it.inspectedItems }
.sortedDescending()
.take(2)
.reduce { acc, i ->
acc * i
}.toLong()
}
fun part1(input: List<String>): Long {
val rounds = 20
val monkeys = input
.chunkedBy { it.isBlank() }
.map { it.toMonkey() }
return runRounds(monkeys, rounds) {
it / 3
}
}
fun part2(input: List<String>): Long {
val rounds = 10000
val monkeys = input
.chunkedBy { it.isBlank() }
.map { it.toMonkey() }
val modValue = monkeys
.map { it.tester.testValue }
.reduce { acc, i ->
acc * i
}
return runRounds(monkeys, rounds) {
it % modValue
}
}
val day = "11"
// test if implementation meets criteria from the description, like:
runTestLong(10605, day, ::part1)
runTestLong(2713310158, day, ::part2)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
private fun List<String>.toMonkey(): Monkey {
val startingItems = this[1]
.substringAfter("Starting items: ")
.split(",")
.map { it.trim() }
.map(String::toLong)
val id = this[0].substringAfter("Monkey ").replace(":", "").toInt()
val ops = this[2].substringAfter("Operation: new = old ")
val testValue = this[3].substringAfter("Test: divisible by ").toLong()
val toTrue = this[4].substringAfter("If true: throw to monkey ").toInt()
val toFalse = this[5].substringAfter("If false: throw to monkey ").toInt()
return Monkey(
id,
startingItems.toMutableList(),
ops,
Tester(testValue, toTrue, toFalse)
)
}
data class Tester(val testValue: Long, val toTrue: Int, val toFalse: Int)
data class Monkey(
val id: Int,
var items: MutableList<Long>,
private val operation: String,
val tester: Tester,
) {
var inspectedItems: Long = 0
fun inspectItems(reliefer: (Long) -> Long): List<Pair<Int, Long>> {
val result = items.map { reliefer.inspectItem(it) }
items.clear()
return result
}
private fun performOperation(item: Long): Long {
val (operator, modifier) = operation.split(" ")
val modValue = if (modifier == "old") item else modifier.toLong()
return if (operator == "+") item + modValue else item * modValue
}
private fun ((Long) -> Long).inspectItem(item: Long): Pair<Int, Long> {
val worryLevel = performOperation(item)
if(worryLevel<0){
error(this@Monkey)
}
val worryLevelAfterRelief = this(worryLevel)
val toMonkey = runTests(worryLevelAfterRelief)
this@Monkey.inspectedItems++
return Pair(toMonkey, worryLevelAfterRelief)
}
private fun runTests(worryLevel: Long): Int {
return if (worryLevel % tester.testValue == 0L) tester.toTrue else tester.toFalse
}
}
| 0 | Kotlin | 0 | 0 | 9876a52ef9288353d64685f294a899a58b2de9b5 | 3,456 | aoc2022 | Apache License 2.0 |
src/Day04.kt | copperwall | 572,339,673 | false | {"Kotlin": 7027} | fun main() {
//main1();
main2()
}
fun main1() {
val inputLines = readInput("Day04-basic")
val pairs = inputLines.map { line ->
line.split(",").map { it.split("-").map { str -> str.toInt() } }
}
// Find
var duplicates = 0
for (pair in pairs) {
val (firstElf, secondElf) = pair
val firstRange = IntRange(firstElf[0], firstElf[1])
val secondRange = IntRange(secondElf[0], secondElf[1])
val smallerRange = if (firstRange.count() < secondRange.count()) {
firstRange
} else {
secondRange
}
val firstIntersection = firstRange.intersect(secondRange)
// If the intersection is the size of the smaller range, it exists totally within the larger one
if (firstIntersection.size == smallerRange.count()) {
duplicates += 1
}
}
println(duplicates)
}
fun main2() {
val inputLines = readInput("Day04")
val pairs = inputLines.map { line ->
line.split(",").map { it.split("-").map { str -> str.toInt() } }
}
// Find
var duplicates = 0
for (pair in pairs) {
val (firstElf, secondElf) = pair
val firstRange = IntRange(firstElf[0], firstElf[1])
val secondRange = IntRange(secondElf[0], secondElf[1])
val firstIntersection = firstRange.intersect(secondRange)
// If the intersection is the size of the smaller range, it exists totally within the larger one
if (!firstIntersection.isEmpty()) {
duplicates += 1
}
}
println(duplicates)
}
| 0 | Kotlin | 0 | 1 | f7b856952920ebd651bf78b0e15e9460524c39bb | 1,531 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/Day10.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 10: Syntax Scoring
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.readFileAsStringList
fun main() {
println(" ** Day 10: Syntax Scoring ** \n")
val navigationSubsystemCode = readFileAsStringList("/Day10NavigationSubsystemCode.txt")
val illegalCharacterSyntaxScore = calculateIllegalCharacterSyntaxScore(navigationSubsystemCode)
println("The illegal character syntax score for the navigation subsystem code is $illegalCharacterSyntaxScore")
val middleIncompleteSyntaxScore = calculateMiddleIncompleteSyntaxScore(navigationSubsystemCode)
println("The middle incomplete syntax score for the navigation subsystem code is $middleIncompleteSyntaxScore")
}
fun calculateIllegalCharacterSyntaxScore(code: List<String>) =
syntaxChecker(code)
.filterIsInstance<CorruptSyntaxError>().map {
when (it.illegalCharacter) {
')' -> 3
']' -> 57
'}' -> 1197
'>' -> 25137
else -> 0
}
}.sum()
fun calculateMiddleIncompleteSyntaxScore(code: List<String>): Long {
val scores = syntaxChecker(code)
.filterIsInstance<IncompleteSyntaxError>()
.map(::toIncompleteSyntaxScore)
.sorted()
return scores[scores.size / 2]
}
private fun toIncompleteSyntaxScore(error: IncompleteSyntaxError) =
error.missingClosingCharacters
.mapNotNull {
when (it) {
')' -> 1
']' -> 2
'}' -> 3
'>' -> 4
else -> null
}
}
.map { it.toLong() }
.fold(0L) { accumulator, characterScore -> (accumulator * 5) + characterScore }
private fun syntaxChecker(code: List<String>) =
code.mapIndexedNotNull { index, line -> findAnySyntaxErrorsInLine(line, index) }
private fun findAnySyntaxErrorsInLine(code: String, lineNumber: Int): SyntaxError? {
val expectedQueue = mutableListOf<Char>()
for (char in code.toCharArray()) {
when (char) {
'(' -> expectedQueue.add(')')
'[' -> expectedQueue.add(']')
'{' -> expectedQueue.add('}')
'<' -> expectedQueue.add('>')
expectedQueue.last() -> expectedQueue.removeLast()
else -> return CorruptSyntaxError(lineNumber, char)
}
}
return if (expectedQueue.isEmpty()) null else IncompleteSyntaxError(lineNumber, expectedQueue.reversed().toList())
}
open class SyntaxError(open val line: Int)
data class CorruptSyntaxError(override val line: Int, val illegalCharacter: Char) : SyntaxError(line)
data class IncompleteSyntaxError(override val line: Int, val missingClosingCharacters: List<Char>) : SyntaxError(line)
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 2,756 | AdventOfCode2021 | MIT License |
solutions/src/Day02.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | import java.lang.IllegalStateException
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val (opponentChoice, myChoice) = it.split(" ")
myRoundScore(opponentChoice, myChoice)
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val (opponentChoice, myChoice) = it.split(" ")
myRoundScore2(opponentChoice, myChoice)
}
}
// 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))
}
private fun myRoundScore(opponentChoice: String, myChoice: String): Int {
return when {
opponentChoice == "A" && myChoice == "X" -> 4
opponentChoice == "A" && myChoice == "Y" -> 8
opponentChoice == "A" && myChoice == "Z" -> 3
opponentChoice == "B" && myChoice == "X" -> 1
opponentChoice == "B" && myChoice == "Y" -> 5
opponentChoice == "B" && myChoice == "Z" -> 9
opponentChoice == "C" && myChoice == "X" -> 7
opponentChoice == "C" && myChoice == "Y" -> 2
opponentChoice == "C" && myChoice == "Z" -> 6
else -> throw IllegalStateException("Should not be possible. Opponent = $opponentChoice, Me = $myChoice")
}
}
private fun myRoundScore2(opponentChoice: String, myChoice: String): Int {
return when {
opponentChoice == "A" && myChoice == "X" -> 3
opponentChoice == "A" && myChoice == "Y" -> 4
opponentChoice == "A" && myChoice == "Z" -> 8
opponentChoice == "B" && myChoice == "X" -> 1
opponentChoice == "B" && myChoice == "Y" -> 5
opponentChoice == "B" && myChoice == "Z" -> 9
opponentChoice == "C" && myChoice == "X" -> 2
opponentChoice == "C" && myChoice == "Y" -> 6
opponentChoice == "C" && myChoice == "Z" -> 7
else -> throw IllegalStateException("Should not be possible. Opponent = $opponentChoice, Me = $myChoice")
}
}
| 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 2,129 | advent-of-code-22 | Apache License 2.0 |
aoc-2023/src/main/kotlin/nerok/aoc/aoc2023/day04/Day04.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2023.day04
import nerok.aoc.utils.Input
import kotlin.math.pow
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun part1(input: List<String>): Long {
return input.map { game ->
var inWinning = false
var inPlayers = false
val winningNumbers = emptySet<Long>().toMutableSet()
val yourNumbers = emptySet<Long>().toMutableSet()
var currentNumber = ""
game.toCharArray().map {
when {
it.isDigit() -> {
currentNumber = if (currentNumber.isNotEmpty()) {
"$currentNumber$it"
} else {
it.toString()
}
}
it.isWhitespace() -> {
if (currentNumber.isNotEmpty()) {
if (inWinning) {
winningNumbers.add(currentNumber.toLong())
}
if (inPlayers) {
yourNumbers.add(currentNumber.toLong())
}
currentNumber = ""
}
}
it == ':' -> {
inWinning = true
currentNumber = ""
}
it == '|' -> {inPlayers = true; inWinning=false}
}
}
if (currentNumber.isNotEmpty()) {
yourNumbers.add(currentNumber.toLong())
}
return@map 2.0.pow(winningNumbers.intersect(yourNumbers).size - 1 ).toLong()
}.sum()
}
fun part2(input: List<String>): Long {
val scores = input.map { game ->
var inWinning = false
var inPlayers = false
val winningNumbers = emptySet<Long>().toMutableSet()
val yourNumbers = emptySet<Long>().toMutableSet()
var currentNumber = ""
game.toCharArray().map {
when {
it.isDigit() -> {
currentNumber = if (currentNumber.isNotEmpty()) {
"$currentNumber$it"
} else {
it.toString()
}
}
it.isWhitespace() -> {
if (currentNumber.isNotEmpty()) {
if (inWinning) {
winningNumbers.add(currentNumber.toLong())
}
if (inPlayers) {
yourNumbers.add(currentNumber.toLong())
}
currentNumber = ""
}
}
it == ':' -> {
inWinning = true
currentNumber = ""
}
it == '|' -> {inPlayers = true; inWinning=false}
}
}
if (currentNumber.isNotEmpty()) {
yourNumbers.add(currentNumber.toLong())
}
return@map winningNumbers.intersect(yourNumbers).size
}
val numberOfCards = MutableList(scores.size) { 1L }
scores.forEachIndexed { index, score ->
for (i in (index+1)..(index+score)) {
numberOfCards[i] = numberOfCards[i] + numberOfCards[index]
}
}
println(numberOfCards)
return numberOfCards.sum().also { println(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day04_test")
check(part1(testInput) == 13L)
check(part2(testInput) == 30L)
val input = Input.readInput("Day04")
println("Part1:")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println("Part2:")
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 4,162 | AOC | Apache License 2.0 |
src/Day12.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | private val offsets = listOf(
Pair(0, 1),
Pair(0, -1),
Pair(1, 0),
Pair(-1, 0)
)
private fun part1(map: List<String>): Int {
val mapWidth = map[0].length
val mapHeight = map.size
var start = Pair(0, 0)
var end = Pair(0, 0)
for ((r, line) in map.withIndex()) {
val s = line.indexOf('S')
if (s != -1) {
start = Pair(r, s)
}
val e = line.indexOf('E')
if (e != -1) {
end = Pair(r, e)
}
}
val costs = List(mapHeight) {
MutableList(mapWidth) { Int.MAX_VALUE }
}
costs[start.first][start.second] = 0
val pendingInvestigationLocation = ArrayDeque(listOf(start))
while (pendingInvestigationLocation.isNotEmpty()) {
val location = pendingInvestigationLocation.removeFirst()
val cost = costs[location.first][location.second]
var height = map[location.first][location.second]
if (height == 'S') {
height = 'a'
}
for (offset in offsets) {
val nextR = location.first + offset.first
val nextC = location.second + offset.second
if (nextR in 0 until mapHeight && nextC in 0 until mapWidth) {
var nextHeight = map[nextR][nextC]
if (nextHeight == 'E') {
nextHeight = 'z'
}
if (nextHeight - height <= 1 && costs[nextR][nextC] > cost + 1) {
costs[nextR][nextC] = cost + 1
pendingInvestigationLocation.addLast(Pair(nextR, nextC))
}
}
}
}
return costs[end.first][end.second]
}
private fun part2(map: List<String>): Int {
// go from E until first a
val mapWidth = map[0].length
val mapHeight = map.size
var end = Pair(0, 0)
for ((r, line) in map.withIndex()) {
val e = line.indexOf('E')
if (e != -1) {
end = Pair(r, e)
}
}
val costs = List(mapHeight) {
MutableList(mapWidth) { Int.MAX_VALUE }
}
costs[end.first][end.second] = 0
val pendingInvestigationLocation = ArrayDeque(listOf(end))
while (pendingInvestigationLocation.isNotEmpty()) {
val location = pendingInvestigationLocation.removeFirst()
val cost = costs[location.first][location.second]
var height = map[location.first][location.second]
if (height == 'E') {
height = 'z'
}
for (offset in offsets) {
val nextR = location.first + offset.first
val nextC = location.second + offset.second
if (nextR in 0 until mapHeight && nextC in 0 until mapWidth) {
val nextHeight = map[nextR][nextC]
if (height - nextHeight <= 1 && costs[nextR][nextC] > cost + 1) {
if (nextHeight == 'a' || nextHeight == 'S') {
return cost + 1
}
costs[nextR][nextC] = cost + 1
pendingInvestigationLocation.addLast(Pair(nextR, nextC))
}
}
}
}
return costs[end.first][end.second]
}
fun main() {
val input = readInput("Day12")
// val input = readInput("Test")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 3,336 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | lonskiTomasz | 573,032,074 | false | {"Kotlin": 22055} | import kotlin.math.sign
private data class Position(val x: Int, val y: Int) {
operator fun plus(other: Position) = Position(x = x + other.x, y = y + other.y)
operator fun minus(other: Position) = Position(x = x - other.x, y = y - other.y)
fun isNeighbour(other: Position): Boolean {
val diff = this - other
return diff.x in -1..1 && diff.y in -1..1
}
fun move(other: Position) = this + Position((other.x - x).sign, (other.y - y).sign)
}
private fun String.toStep() = when (this) {
"R" -> Position(1, 0)
"L" -> Position(-1, 0)
"U" -> Position(0, 1)
"D" -> Position(0, -1)
else -> Position(0, 0)
}
fun main() {
fun part1(input: List<String>) {
val visitedPositions: MutableSet<Position> = mutableSetOf(Position(0, 0))
var currHead = Position(0, 0)
var currTail = Position(0, 0)
fun moveAndFollow(step: Position, times: Int) {
repeat(times) {
val prevHead = currHead
currHead += step
if (currHead.isNeighbour(currTail)) return@repeat
currTail += step
currTail += (prevHead - currTail) // jump if diagonal
visitedPositions += currTail
}
}
input.forEach { line ->
val cmd = line.split(' ')
moveAndFollow(step = cmd[0].toStep(), times = cmd[1].toInt())
}
println(visitedPositions.size)
}
fun part2(input: List<String>) {
val visitedPositions: MutableSet<Position> = mutableSetOf(Position(0, 0))
val knots = MutableList(10) { Position(0, 0) }
fun moveAndFollow(step: Position, times: Int) {
repeat(times) {
knots[0] += step // always move head
knots.indices.windowed(2) { (head, tail) ->
if (!knots[tail].isNeighbour(knots[head])) {
knots[tail] = knots[tail].move(knots[head])
}
}
visitedPositions += knots.last()
}
}
input.forEach { line ->
val cmd = line.split(' ')
moveAndFollow(step = cmd[0].toStep(), times = cmd[1].toInt())
}
println(visitedPositions.size)
}
val inputTest = readInput("day09/input_test")
val input = readInput("day09/input")
println(part1(inputTest))
println(part1(input)) // 5513
println(part2(inputTest))
println(part2(input)) // 2427
} | 0 | Kotlin | 0 | 0 | 9e758788759515049df48fb4b0bced424fb87a30 | 2,502 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/days/aoc2021/Day9.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2021
import days.Day
import kotlin.math.exp
class Day9 : Day(2021, 9) {
override fun partOne(): Any {
return calculateRiskLevelSum(inputList)
}
override fun partTwo(): Any {
return calculateThreeLargestBasins(inputList)
}
fun calculateThreeLargestBasins(inputList: List<String>): Int {
val seafloor = Seafloor(inputList)
val basinSizes = mutableListOf<Int>()
for (x in inputList.indices) {
for (y in inputList[x].indices) {
seafloor.exploreBasin(x, y).let {
if (it > 0) {
basinSizes.add(it)
}
}
}
}
return basinSizes.sortedDescending().take(3).reduce { acc, i -> acc * i }
}
class Seafloor(inputList: List<String>) {
private var floor: List<List<Point>> = inputList.map { line ->
line.trim().map { char -> char.toString().toInt() }.map { Point(it, false) }
}
// recursively explore this basin and return a running size
fun exploreBasin(x: Int, y: Int): Int {
floor.getOrElse(x) { listOf() }.getOrNull(y)?.let {
if (!(it.height == 9 || it.visited)) {
it.visited = true
return 1 + exploreBasin(x - 1, y) +
exploreBasin(x + 1, y) +
exploreBasin(x, y - 1) +
exploreBasin(x, y + 1)
}
}
return 0
}
class Point(val height: Int, var visited: Boolean)
}
fun calculateRiskLevelSum(inputLines: List<String>): Int {
var sum = 0
inputLines.map { line -> line.trim().map { char -> char.toString().toInt() } }.let { seafloor ->
for (x in seafloor.indices) {
val row = seafloor[x]
for (y in row.indices) {
sum += if (seafloor[x][y] < seafloor.getOrElse(x - 1) { listOf() }.getOrElse(y) {9} &&
seafloor[x][y] < seafloor.getOrElse(x + 1) { listOf() }.getOrElse(y) {9} &&
seafloor[x][y] < seafloor.getOrElse(x) { listOf() }.getOrElse(y - 1) {9} &&
seafloor[x][y] < seafloor.getOrElse(x) { listOf() }.getOrElse(y + 1) {9}) {
seafloor[x][y] + 1
} else {
0
}
}
}
}
return sum
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 2,539 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/algorithmdesignmanualbook/partialsum/PartialSumUsingFenwickTree.kt | realpacific | 234,499,820 | false | null | package algorithmdesignmanualbook.partialsum
import algorithmdesignmanualbook.print
import java.util.*
import kotlin.experimental.and
import kotlin.experimental.inv
/**
* Let A be an array of n real numbers. Design an algorithm to perform any sequence of the following operations:
* • Add(i,y) – Add the value y to the ith number.
* • Partial-sum(i) – Return the sum of the first i numbers
* Each operation must take O(logn).
*
* Fenwick Tree or Binary Indexed Tree is a tree containing n+1 nodes.
* Each node's parent is right most 1 flipped i.e
* * 8 -> 1000 so parent is 0000 (0)
* * 7 -> 0111 so parent is 0110 (6)
* * 10 -> 1010 so parent is 1000 (8)
* * 5 -> 0101 so parent is 0100 (4)
* Sum can be obtained by (0..5) -> tree[6] + tree[4] + tree[0] i.e index+1 and then go upwards to parents
*
* To get the parent:
* * 2's complement (Flip all bits and add 1)
* * AND it with original number
* * Subtract it from original number
*
* 7 (111) ---(step 1)---> 000+1=001 ---(AND 111)-->001 --(Subtract from 111)--->110
*
*/
class PartialSumUsingFenwickTree(private val values: Array<Int>) {
val tree = Array(values.size + 1) { 0 }
init {
construcFenwickTree()
}
fun removeLastSetBit(byte: Byte): Byte {
return (byte - byte.and(byte.inv().plus(0b1).toByte())).toByte()
}
private fun construcFenwickTree() {
values.forEachIndexed { index, value ->
update(index, value)
}
}
private fun update(index: Int, value: Int) {
var bTreeIndex = index + 1
while (bTreeIndex <= values.size) {
tree[bTreeIndex] += value
bTreeIndex += bTreeIndex.and(-bTreeIndex)
}
}
fun getSum(index: Int): Int {
var sum = 0
var bIndex = index + 1
while (bIndex > 0) {
sum += tree[bIndex]
bIndex -= bIndex.and(-bIndex)
}
return sum
}
}
fun main() {
val solution = PartialSumUsingFenwickTree(arrayOf(1, 2, 3, 4, 5, 6))
solution.removeLastSetBit(0b111).print { it.toString(2) }
solution.tree.print {
Arrays.toString(it)
}
solution.getSum(2).print()
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,186 | algorithms | MIT License |
src/Day04.kt | wgolyakov | 572,463,468 | false | null | fun main() {
fun part1(input: List<String>): Int {
return input.count {
val (r1, r2) = it.split(',')
.map { r -> r.split('-').map(String::toInt).let { (a, b) -> a..b } }
(r1.first in r2 && r1.last in r2) || (r2.first in r1 && r2.last in r1)
}
}
fun part2(input: List<String>): Int {
return input.count {
val (r1, r2) = it.split(',')
.map { r -> r.split('-').map(String::toInt).let { (a, b) -> a..b } }
r1.first in r2 || r1.last in r2 || r2.first in r1 || r2.last in r1
}
}
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 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 689 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | Krzychuk9 | 573,127,179 | false | null | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val midPoint = it.length / 2
val itemsInFirstCompartment = it.substring(0, midPoint).toSet()
val itemsInSecondCompartment = it.substring(midPoint).toSet()
val item = itemsInFirstCompartment.intersect(itemsInSecondCompartment).first()
getItemPriority(item)
}
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map {
it.reduce { l1, l2 -> l1.toSet().intersect(l2.toSet()).joinToString() }
}
.sumOf { getItemPriority(it.first()) }
}
// 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 getItemPriority(char: Char) = char.code - getCharOffset(char)
fun getCharOffset(char: Char) = if (char.isUpperCase()) 38 else 96
| 0 | Kotlin | 0 | 0 | ded55d03c9d4586166bf761c7d5f3f45ac968e81 | 1,097 | adventOfCode2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.