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/Day22.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | fun main() {
val testInput = readInput("Day22_test")
val testMap = testInput.subList(0, testInput.size - 2).toMap()
val testPath = testInput.last().parsePath()
check(part1(testMap, testPath) == 6032)
check(part2(testMap, testMap.buildTestCubeAdjacentMap(), testPath) == 5031)
val input = readInput("Day22")
val map = input.subList(0, input.size - 2).toMap()
val path = input.last().parsePath()
println(part1(map, path))
println(part2(map, map.buildCubeAdjacentMap(), path))
}
private const val VOID = 0
private const val OPEN = 1
private const val WALL = 2
private const val RIGHT = 0
private const val DOWN = 1
private const val LEFT = 2
private const val UP = 3
private fun part1(map: Matrix, path: List<PathItem>): Int {
val adjacentMap = map.buildAdjacentMap()
return solve(map, adjacentMap, path)
}
private fun part2(map: Matrix, adjacentMap: Int3DMatrix, path: List<PathItem>): Int = solve(map, adjacentMap, path)
private fun solve(map: Matrix, adjacentMap: Int3DMatrix, path: List<PathItem>): Int {
// "You begin the path in the leftmost open tile of the top row of tiles."
val position = MutableIJ(
i = 0,
j = map[0].indexOfFirst { it == OPEN }
)
var rotation = RIGHT
path.forEach { pathItem ->
when (pathItem) {
is PathItem.Move -> {
for (k in 1..pathItem.stepsCount) {
val i = adjacentMap[position.i][position.j][rotation * 3]
val j = adjacentMap[position.i][position.j][rotation * 3 + 1]
if (map[i][j] == WALL) {
break
}
rotation = adjacentMap[position.i][position.j][rotation * 3 + 2]
position.i = i
position.j = j
}
}
PathItem.RotationLeft -> rotation = if (rotation == RIGHT) UP else rotation - 1
PathItem.RotationRight -> rotation = if (rotation == UP) RIGHT else rotation + 1
}
}
return 1_000 * (position.i + 1) + 4 * (position.j + 1) + rotation
}
private fun List<String>.toMap(): Matrix {
val iSize = this.size
val jSize = this.maxOf { it.length }
val result = Array(iSize) { i ->
IntArray(jSize) { j ->
when (this[i].getOrNull(j)) {
'.' -> OPEN
'#' -> WALL
else -> VOID
}
}
}
return result
}
private fun Matrix.buildAdjacentMap(): Int3DMatrix {
return Array(this.size) { i ->
Array(this[i].size) { j ->
if (this[i][j] != VOID) {
var jRight = (j + 1) % this[i].size
while (this[i][jRight] == VOID) {
jRight = (jRight + 1) % this[i].size
}
var iDown = (i + 1) % this.size
while (this[iDown][j] == VOID) {
iDown = (iDown + 1) % this.size
}
var jLeft = if (j > 0) (j - 1) else this[i].lastIndex
while (this[i][jLeft] == VOID) {
jLeft = if (jLeft > 0) (jLeft - 1) else this[i].lastIndex
}
var iUp = if (i > 0) (i - 1) else this.lastIndex
while (this[iUp][j] == VOID) {
iUp = if (iUp > 0) (iUp - 1) else this.lastIndex
}
intArrayOf(
i, jRight, RIGHT,
iDown, j, DOWN,
i, jLeft, LEFT,
iUp, j, UP
)
} else {
intArrayOf()
}
}
}
}
private fun Matrix.buildCubeAdjacentMap(): Int3DMatrix {
val result = Array(this.size) { i ->
Array(this[i].size) { j ->
if (this[i][j] != VOID) {
intArrayOf(
i, j + 1, RIGHT,
i + 1, j, DOWN,
i, j - 1, LEFT,
i - 1, j, UP
)
} else {
intArrayOf()
}
}
}
val cubeSize = this.size / 4
//Link cube edges
/*
22221111
22221111
22221111
22221111
3333
3333
3333
3333
55554444
55554444
55554444
55554444
6666
6666
6666
6666
*/
//Link 1 <-> 3 edges
repeat(cubeSize) { delta ->
result[cubeSize - 1][2 * cubeSize + delta][3 * DOWN] = cubeSize + delta
result[cubeSize - 1][2 * cubeSize + delta][3 * DOWN + 1] = 2 * cubeSize - 1
result[cubeSize - 1][2 * cubeSize + delta][3 * DOWN + 2] = LEFT
result[cubeSize + delta][2 * cubeSize - 1][3 * RIGHT] = cubeSize - 1
result[cubeSize + delta][2 * cubeSize - 1][3 * RIGHT + 1] = 2 * cubeSize + delta
result[cubeSize + delta][2 * cubeSize - 1][3 * RIGHT + 2] = UP
}
//Link 1 <-> 4 edges
repeat(cubeSize) { delta ->
result[cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT] = 2 * cubeSize + delta
result[cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT + 1] = 2 * cubeSize - 1
result[cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT + 2] = LEFT
result[2 * cubeSize + delta][2 * cubeSize - 1][3 * RIGHT] = cubeSize - delta - 1
result[2 * cubeSize + delta][2 * cubeSize - 1][3 * RIGHT + 1] = 3 * cubeSize - 1
result[2 * cubeSize + delta][2 * cubeSize - 1][3 * RIGHT + 2] = LEFT
}
//Link 1 <-> 6 edges
repeat(cubeSize) { delta ->
result[0][2 * cubeSize + delta][3 * UP] = 4 * cubeSize - 1
result[0][2 * cubeSize + delta][3 * UP + 1] = delta
result[0][2 * cubeSize + delta][3 * UP + 2] = UP
result[4 * cubeSize - 1][delta][3 * DOWN] = 0
result[4 * cubeSize - 1][delta][3 * DOWN + 1] = 2 * cubeSize + delta
result[4 * cubeSize - 1][delta][3 * DOWN + 2] = DOWN
}
//Link 2 <-> 5 edges
repeat(cubeSize) { delta ->
result[cubeSize - delta - 1][cubeSize][3 * LEFT] = 2 * cubeSize + delta
result[cubeSize - delta - 1][cubeSize][3 * LEFT + 1] = 0
result[cubeSize - delta - 1][cubeSize][3 * LEFT + 2] = RIGHT
result[2 * cubeSize + delta][0][3 * LEFT] = cubeSize - delta - 1
result[2 * cubeSize + delta][0][3 * LEFT + 1] = cubeSize
result[2 * cubeSize + delta][0][3 * LEFT + 2] = RIGHT
}
//Link 2 <-> 6 edges
repeat(cubeSize) { delta ->
result[0][cubeSize + delta][3 * UP] = 3 * cubeSize + delta
result[0][cubeSize + delta][3 * UP + 1] = 0
result[0][cubeSize + delta][3 * UP + 2] = RIGHT
result[3 * cubeSize + delta][0][3 * LEFT] = 0
result[3 * cubeSize + delta][0][3 * LEFT + 1] = cubeSize + delta
result[3 * cubeSize + delta][0][3 * LEFT + 2] = DOWN
}
//Link 3 <-> 5 edges
repeat(cubeSize) { delta ->
result[2 * cubeSize - delta - 1][cubeSize][3 * LEFT] = 2 * cubeSize
result[2 * cubeSize - delta - 1][cubeSize][3 * LEFT + 1] = cubeSize - delta - 1
result[2 * cubeSize - delta - 1][cubeSize][3 * LEFT + 2] = DOWN
result[2 * cubeSize][cubeSize - delta - 1][3 * UP] = 2 * cubeSize - delta - 1
result[2 * cubeSize][cubeSize - delta - 1][3 * UP + 1] = cubeSize
result[2 * cubeSize][cubeSize - delta - 1][3 * UP + 2] = RIGHT
}
//Link 4 <-> 6 edges
repeat(cubeSize) { delta ->
result[3 * cubeSize - 1][cubeSize + delta][3 * DOWN] = 3 * cubeSize + delta
result[3 * cubeSize - 1][cubeSize + delta][3 * DOWN + 1] = cubeSize - 1
result[3 * cubeSize - 1][cubeSize + delta][3 * DOWN + 2] = LEFT
result[3 * cubeSize + delta][cubeSize - 1][3 * RIGHT] = 3 * cubeSize - 1
result[3 * cubeSize + delta][cubeSize - 1][3 * RIGHT + 1] = cubeSize + delta
result[3 * cubeSize + delta][cubeSize - 1][3 * RIGHT + 2] = UP
}
return result
}
private fun Matrix.buildTestCubeAdjacentMap(): Int3DMatrix {
val result = Array(this.size) { i ->
Array(this[i].size) { j ->
if (this[i][j] != VOID) {
intArrayOf(
i, j + 1, RIGHT,
i + 1, j, DOWN,
i, j - 1, LEFT,
i - 1, j, UP
)
} else {
intArrayOf()
}
}
}
val cubeSize = this.size / 3
val leftTop = cubeSize * 2
//Link cube edges
/*
1111
1111
1111
1111
222233334444
222233334444
222233334444
222233334444
55556666
55556666
55556666
55556666
*/
//Link 1 <-> 2
repeat(cubeSize) { delta ->
result[0][leftTop + delta][3 * UP] = cubeSize
result[0][leftTop + delta][3 * UP + 1] = cubeSize - delta - 1
result[0][leftTop + delta][3 * UP + 2] = DOWN
result[cubeSize][cubeSize - delta - 1][3 * UP] = 0
result[cubeSize][cubeSize - delta - 1][3 * UP + 1] = leftTop + delta
result[cubeSize][cubeSize - delta - 1][3 * UP + 2] = DOWN
}
//Link 1 <-> 3
repeat(cubeSize) { delta ->
result[delta][leftTop][3 * LEFT] = cubeSize
result[delta][leftTop][3 * LEFT + 1] = cubeSize + delta
result[delta][leftTop][3 * LEFT + 2] = DOWN
result[cubeSize][cubeSize + delta][3 * UP] = delta
result[cubeSize][cubeSize + delta][3 * UP + 1] = leftTop
result[cubeSize][cubeSize + delta][3 * UP + 2] = RIGHT
}
//Link 1 <-> 6
repeat(cubeSize) { delta ->
result[delta][3 * cubeSize - 1][3 * RIGHT] = 3 * cubeSize - delta - 1
result[delta][3 * cubeSize - 1][3 * RIGHT + 1] = 4 * cubeSize - 1
result[delta][3 * cubeSize - 1][3 * RIGHT + 2] = LEFT
result[3 * cubeSize - delta - 1][4 * cubeSize - 1][3 * RIGHT] = delta
result[3 * cubeSize - delta - 1][4 * cubeSize - 1][3 * RIGHT + 1] = 3 * cubeSize - 1
result[3 * cubeSize - delta - 1][4 * cubeSize - 1][3 * RIGHT + 2] = LEFT
}
//Link 2 <-> 5
repeat(cubeSize) { delta ->
result[2 * cubeSize - 1][delta][3 * DOWN] = 3 * cubeSize - 1
result[2 * cubeSize - 1][delta][3 * DOWN + 1] = 3 * cubeSize - delta - 1
result[2 * cubeSize - 1][delta][3 * DOWN + 2] = UP
result[3 * cubeSize - 1][3 * cubeSize - delta - 1][3 * DOWN] = 2 * cubeSize - 1
result[3 * cubeSize - 1][3 * cubeSize - delta - 1][3 * DOWN + 1] = delta
result[3 * cubeSize - 1][3 * cubeSize - delta - 1][3 * DOWN + 2] = UP
}
//Link 2 <-> 6
repeat(cubeSize) { delta ->
result[cubeSize + delta][0][3 * LEFT] = 3 * cubeSize - 1
result[cubeSize + delta][0][3 * LEFT + 1] = 4 * cubeSize - delta - 1
result[cubeSize + delta][0][3 * LEFT + 2] = UP
result[3 * cubeSize - 1][4 * cubeSize - delta - 1][3 * DOWN] = cubeSize + delta
result[3 * cubeSize - 1][4 * cubeSize - delta - 1][3 * DOWN + 1] = 0
result[3 * cubeSize - 1][4 * cubeSize - delta - 1][3 * DOWN + 2] = RIGHT
}
//Link 3 <-> 5
repeat(cubeSize) { delta ->
result[2 * cubeSize - 1][2 * cubeSize - delta - 1][3 * DOWN] = 2 * cubeSize + delta
result[2 * cubeSize - 1][2 * cubeSize - delta - 1][3 * DOWN + 1] = 2 * cubeSize
result[2 * cubeSize - 1][2 * cubeSize - delta - 1][3 * DOWN + 2] = RIGHT
result[2 * cubeSize + delta][2 * cubeSize][3 * LEFT] = 2 * cubeSize - 1
result[2 * cubeSize + delta][2 * cubeSize][3 * LEFT + 1] = 2 * cubeSize - delta - 1
result[2 * cubeSize + delta][2 * cubeSize][3 * LEFT + 2] = UP
}
//Link 4 <-> 6
repeat(cubeSize) { delta ->
result[2 * cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT] = 2 * cubeSize
result[2 * cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT + 1] = 3 * cubeSize + delta
result[2 * cubeSize - delta - 1][3 * cubeSize - 1][3 * RIGHT + 2] = DOWN
result[2 * cubeSize][3 * cubeSize + delta][3 * UP] = 2 * cubeSize - delta - 1
result[2 * cubeSize][3 * cubeSize + delta][3 * UP + 1] = 3 * cubeSize - 1
result[2 * cubeSize][3 * cubeSize + delta][3 * UP + 2] = LEFT
}
return result
}
private val PATH_FORMAT = Regex("(R|L|\\d+)")
private fun String.parsePath(): List<PathItem> {
return PATH_FORMAT.findAll(this)
.map {
when (it.value) {
"R" -> PathItem.RotationRight
"L" -> PathItem.RotationLeft
else -> PathItem.Move(it.value.toInt())
}
}
.toList()
}
private sealed interface PathItem {
class Move(val stepsCount: Int) : PathItem
object RotationRight : PathItem
object RotationLeft : PathItem
} | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 12,667 | AOC2022 | Apache License 2.0 |
src/day01/Day01.kt | sanyarajan | 572,663,282 | false | {"Kotlin": 24016} | package day01
import readInput
fun main() {
fun part1(input: List<String>): Pair<Int,Int> {
// get a list of sums of ranges in the list separated by blanks
val list = ArrayList<Int>()
var total=0
input
.asSequence()
.map { it.toIntOrNull() }
.forEach {
when {
it != null -> {
total+= it
}
else -> {
list.add(total)
total=0
}
}
}
var currentTotal = 0
var maxTotal = 0
var currentElf = 1
var maxElf = 1
input.forEach { line ->
//if the line is an integer
val value = line.toIntOrNull()
if ( value != null) {
currentTotal += value
}
else
{
if(currentTotal > maxTotal)
{
maxTotal = currentTotal
maxElf = currentElf
}
currentElf++
currentTotal = 0
}
}
return Pair(maxTotal, maxElf)
}
fun part2(input: List<String>): Int {
var currentTotal = 0
var currentElf = 1
val totals = ArrayList<Int>()
input.forEach { line ->
//if the line is an integer
val value = line.toIntOrNull()
if ( value != null) {
currentTotal += value
}
else
{
totals.add(currentTotal)
currentElf++
currentTotal = 0
}
}
//sort the list and take the top 3
totals.sortDescending()
return totals.take(3).sum()
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01/input")
// check(part1(testInput) == 1)
val input = readInput("day01/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e23413357b13b68ed80f903d659961843f2a1973 | 2,097 | Kotlin-AOC-2022 | Apache License 2.0 |
src/Day01.kt | stevefranchak | 573,628,312 | false | {"Kotlin": 34220} | class CalorieTracker(val n: Int) {
private var topNMaxCalories = List(n) { 0 }
private var runningTotalCaloriesForCurrentElf = 0
init {
require(n >= 1)
}
fun sumTopNMaxCalories(input: List<String>) =
input.forEach(::processLine).run { topNMaxCalories.sum() }
private fun processLine(line: String) =
if (line.isBlank()) {
stopTrackingCurrentElf()
} else {
addCaloriesToCurrentElfTotal(line)
}
private fun addCaloriesToCurrentElfTotal(calories: Int) {
require(calories >= 0)
runningTotalCaloriesForCurrentElf += calories
}
private fun addCaloriesToCurrentElfTotal(calories: String) {
addCaloriesToCurrentElfTotal(calories.toInt())
}
private fun stopTrackingCurrentElf() {
topNMaxCalories = topNMaxCalories.plus(runningTotalCaloriesForCurrentElf).sortedDescending().take(n)
runningTotalCaloriesForCurrentElf = 0
}
}
fun main() {
fun part1(input: List<String>) = CalorieTracker(1).sumTopNMaxCalories(input)
fun part2(input: List<String>) = CalorieTracker(3).sumTopNMaxCalories(input)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
val part1TestOutput = part1(testInput)
val part1ExpectedOutput = 24000
check(part1TestOutput == part1ExpectedOutput) { "$part1TestOutput != $part1ExpectedOutput" }
val part2TestOutput = part2(testInput)
val part2ExpectedOutput = 45000
check(part2TestOutput == part2ExpectedOutput) { "$part2TestOutput != $part2ExpectedOutput" }
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 22a0b0544773a6c84285d381d6c21b4b1efe6b8d | 1,708 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | dcbertelsen | 573,210,061 | false | {"Kotlin": 29052} | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { getScore(it) }
}
fun part2(input: List<String>): Int {
return input.sumOf { getScore(getGame(it)) }
}
val testInput = listOf(
"A Y",
"B X",
"C Z"
)
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = File("./src/resources/Day02a.txt").readLines()
println(part1(input))
println(part2(input))
}
fun getScore(game: String) : Int =
game[2] - 'W' +
when {
game[0] == (game[2] - 23) -> 3
wins.contains(game) -> 6
else -> 0
}
fun getGame(code: String) : String =
when (code[2]) {
'Y' -> ties
'X' -> losses
'Z' -> wins
else -> listOf()
}.first { code[0] == it[0] }
val wins = listOf("A Y", "B Z", "C X")
val losses = listOf("A Z", "B X", "C Y")
val ties = listOf("A X", "B Y", "C Z")
| 0 | Kotlin | 0 | 0 | 9d22341bd031ffbfb82e7349c5684bc461b3c5f7 | 1,071 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/staricka/adventofcode2022/Day9.kt | mathstar | 569,952,400 | false | {"Kotlin": 77567} | package com.staricka.adventofcode2022
import com.staricka.adventofcode2022.Day9.Move.Companion.toMove
import kotlin.math.abs
class Day9 : Day {
override val id = 9
private fun computeTailMovement(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
val (hx, hy) = head
val (tx, ty) = tail
return if (abs(hx - tx) <= 1 && abs(hy - ty) <= 1) {
tail
} else if (hx == tx) {
val tyNew = ty + (if (hy - ty > 0) 1 else -1)
Pair(tx, tyNew)
} else if (hy == ty) {
val txNew = tx + (if (hx - tx > 0) 1 else -1)
Pair(txNew, ty)
} else {
val txNew = tx + (if (hx - tx > 0) 1 else -1)
val tyNew = ty + (if (hy - ty > 0) 1 else -1)
Pair(txNew, tyNew)
}
}
enum class Direction(val xStep: Int, val yStep: Int) {
L(-1, 0), R(1, 0), U(0, 1), D(0, -1)
}
data class Move(val direction: Direction, var distance: Int) {
fun step(initial: Pair<Int, Int>): Pair<Int, Int> {
if (distance <= 0) return initial
val result = Pair(initial.first + direction.xStep, initial.second + direction.yStep)
distance--
return result
}
companion object {
fun String.toMove() : Move {
val split = this.split(" ")
return Move(Direction.valueOf(split[0]), split[1].toInt())
}
}
}
override fun part1(input: String): Any {
var head = Pair(0,0)
var tail = Pair(0,0)
val tailPositions = HashSet<Pair<Int, Int>>()
tailPositions.add(tail)
input.lines().map { it.toMove() }.forEach { move ->
while (move.distance > 0) {
head = move.step(head)
tail = computeTailMovement(head, tail)
tailPositions.add(tail)
}
}
return tailPositions.size
}
override fun part2(input: String): Any {
val positions = Array(10) { Pair(0,0) }
val tailPositions = HashSet<Pair<Int, Int>>()
tailPositions.add(positions[9])
input.lines().map { it.toMove() }.forEach { move ->
while (move.distance > 0) {
positions[0] = move.step(positions[0])
for (i in 1..9) {
positions[i] = computeTailMovement(positions[i - 1], positions[i])
}
tailPositions.add(positions[9])
}
}
return tailPositions.size
}
} | 0 | Kotlin | 0 | 0 | 2fd07f21348a708109d06ea97ae8104eb8ee6a02 | 2,250 | adventOfCode2022 | MIT License |
src/main/kotlin/days/Day09.kt | Kebaan | 573,069,009 | false | null | package days
import utils.Day
import utils.Direction
import utils.Point
typealias Instruction = Pair<Direction, Int>
fun main() {
Day09.solve()
}
object Day09 : Day<Int>(2022, 9) {
private fun parseInput(input: List<String>): List<Instruction> {
return input.map {
it.split(" ").let { (direction, steps) ->
Direction.from(direction) to steps.toInt()
}
}
}
override fun part1(input: List<String>): Int {
val instructions = parseInput(input)
return simulateTravellingKnots(instructions, 2)
}
override fun part2(input: List<String>): Int {
val instructions = parseInput(input)
return simulateTravellingKnots(instructions, 10)
}
private fun simulateTravellingKnots(instructions: List<Instruction>, knotCount: Int): Int {
val knots = Array(knotCount) { Point(0, 0) }
val visited = mutableSetOf(knots.last())
instructions.forEach { (direction, steps) ->
repeat(steps) {
knots[0] = knots[0].move(direction)
for (n in 1 until knots.size) {
val childKnot = knots[n]
val parentKnot = knots[n - 1]
val diff = parentKnot - childKnot
if (diff.chebyshevLength() > 1) {
val relativeDirection = Direction.from(diff.normalized())
knots[n] = knots[n].move(relativeDirection)
}
}
visited.add(knots.last())
}
}
return visited.size
}
override fun doSolve() {
part1(input).let {
println(it)
check(it == 6090)
}
part2(input).let {
println(it)
check(it == 2566)
}
}
override val testInput = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent().lines()
}
| 0 | Kotlin | 0 | 0 | ef8bba36fedbcc93698f3335fbb5a69074b40da2 | 2,006 | Advent-of-Code-2022 | Apache License 2.0 |
src/y2016/Day14.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2016
import util.md5
object Day14 {
fun part1(salt: String): Int {
val candidates = mutableSetOf<Pair<Int, Char>>()
var currentIdx = 0
val keyIdxs = mutableListOf<Int>()
while (keyIdxs.size < 100) {
candidates.removeIf {
it.first < currentIdx - 1000
}
val hash = (salt + currentIdx.toString()).md5()
val triples = hasConsecutive(hash, 3)
if (triples.isNotEmpty()) {
val quints = hasConsecutive(hash, 5)
quints.forEach { fiveChar ->
val found = candidates.filter { (_, c) -> fiveChar == c }
found.forEach {
keyIdxs.add(it.first)
candidates.remove(it)
}
}
candidates.add(currentIdx to triples.first())
}
currentIdx++
}
keyIdxs.sort()
println("all: $keyIdxs")
return keyIdxs[63]
}
private fun hasConsecutive(str: String, n: Int): List<Char> {
return str.windowed(n, 1).filter {
it.toSet().size == 1
}.map { it.first() }
}
fun part2(salt: String): Int {
val candidates = mutableSetOf<Pair<Int, Char>>()
var currentIdx = 0
val keyIdxs = mutableListOf<Int>()
while (keyIdxs.size < 100) {
candidates.removeIf {
it.first < currentIdx - 1000
}
val hash = (salt + currentIdx.toString()).md5Stretched()
val triples = hasConsecutive(hash, 3)
if (triples.isNotEmpty()) {
val quints = hasConsecutive(hash, 5)
quints.forEach { fiveChar ->
val found = candidates.filter { (_, c) -> fiveChar == c }
found.forEach {
keyIdxs.add(it.first)
candidates.remove(it)
}
}
candidates.add(currentIdx to triples.first())
}
currentIdx++
}
keyIdxs.sort()
println("all: $keyIdxs")
return keyIdxs[63]
}
}
private fun String.md5Stretched(): String {
var result = this
repeat(2017) {
result = result.md5()
}
return result
}
fun main() {
val testInput = "abc"
println("------Tests------")
println(Day14.part1(testInput))
println(Day14.part2(testInput))
println("------Real------")
val input = "zpqevtbw"
println(Day14.part1(input))
println(Day14.part2(input))
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 2,621 | advent-of-code | Apache License 2.0 |
src/main/kotlin/aoc23/Day03.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc23
import aoc23.Day03Parser.toSchema
import aoc23.Day03Solution.part1Day03
import aoc23.Day03Solution.part2Day03
import common.Collections.product
import common.Space2D
import common.Space2D.Parser.toPointChars
import common.Space2D.Point
import common.Space2D.PointChar
import common.Space2D.getFor
import common.Year23
object Day03 : Year23 {
fun List<String>.part1(): Int = part1Day03()
fun List<String>.part2(): Int = part2Day03()
}
object Day03Solution {
fun List<String>.part1Day03(): Int =
toSchema()
.toPartNumbers()
.sum()
fun List<String>.part2Day03(): Int =
toSchema()
.toGearRatios()
.sum()
}
object Day03Domain {
data class Schematic(
private val input: List<PointChar>
) {
private val seen = mutableSetOf<PointChar>()
private val numbersNextCharacters = mutableMapOf<List<Point>, Int>()
private val charactersNextToNumbers = mutableSetOf<Point>()
fun toGearRatios(): List<Int> {
findCharactersAndNumbersThatIntersectWhere(characterPredicate = { isStar() })
return charactersNextToNumbers
.mapNotNull { characterPoint ->
numbersNextCharacters
.filter { (numberPoints, _) ->
numberPoints.intersect(characterPoint.adjacentWithDiagonal()).isNotEmpty()
}
.takeIf { it.size == 2 }
?.map { it.value }
}.map { it.product() }
}
fun toPartNumbers(): List<Int> {
findCharactersAndNumbersThatIntersectWhere(characterPredicate = { isSymbol() })
return numbersNextCharacters.map { it.value }
}
private fun findCharactersAndNumbersThatIntersectWhere(characterPredicate: PointChar.() -> Boolean) {
input.forEach { pointChar ->
when {
pointChar.isDigit() && pointChar !in seen -> {
getDigitsToRightOf(pointChar).also { seen.addAll(it) }
.let { numberPoints ->
numberPoints.pointsSurrounding().filter { it.characterPredicate() }.let { symbolNextToNumber ->
if (symbolNextToNumber.isNotEmpty()) {
numbersNextCharacters[numberPoints.map { it.point }] = numberPoints.toInt()
charactersNextToNumbers.addAll(symbolNextToNumber.map { it.point })
}
}
}
}
}
}
}
private fun getDigitsToRightOf(pointCharThatHasDigit: PointChar): List<PointChar> =
generateSequence(pointCharThatHasDigit) { pointChar ->
input.getFor(pointChar.point.move(Space2D.Direction.East))?.takeIf { it.isDigit() }
}.toList()
private fun PointChar.isSymbol(): Boolean = !char.isDigit() && char != '.'
private fun PointChar.isStar(): Boolean = char == '*'
private fun PointChar.isDigit(): Boolean = char.isDigit()
private fun List<PointChar>.pointsSurrounding(): Set<PointChar> =
this.flatMap { it.point.adjacentWithDiagonal() }
.mapNotNull { point -> input.getFor(point) }
.toSet()
private fun List<PointChar>.toInt() = map { it.char }.joinToString("").toInt()
}
}
object Day03Parser {
fun List<String>.toSchema(): Day03Domain.Schematic =
Day03Domain.Schematic(input = toPointChars())
} | 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 3,703 | aoc | Apache License 2.0 |
src/main/kotlin/aoc2023/Day21.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import aoc2022.utils.MazeToTarget
import utils.*
private data class Pos(val loc: Coordinates, val steps: Int)
private class Garden(input: List<String>): ArrayAsSurface(input) {
fun startCoord(): Coordinates = indexed().firstOrNull { it.second == 'S' }?.first ?: throw IllegalStateException("Cant find start")
fun doubleMovesFrom(loc: Coordinates): List<Coordinates> =
movesFrom(loc)
.flatMap { it.adjacent() }
.filter { it.isGarden() }
fun movesFrom(loc: Coordinates): List<Coordinates> =
loc.adjacent().filter { it.isGarden() }
.toList()
private fun Coordinates.isGarden() = checkedAt(this, '#') != '#'
}
private class InfiniteGarden(input: List<String>): ArrayAsSurface(input) {
fun startCoord(): Coordinates = indexed().firstOrNull { it.second == 'S' }?.first ?: throw IllegalStateException("Cant find start")
fun movesFrom(loc: Coordinates): List<Coordinates> =
loc.adjacent().filter { it.isGarden() }
.flatMap { it.adjacent() }
.filter { it.isGarden() }.toList()
fun singleMovesFrom(loc: Coordinates): List<Coordinates> =
loc.adjacent().filter { it.isFirstGarden() }.toList()
private fun Coordinates.isGarden() = at(this.wrapped()) != '#'
private fun Coordinates.isFirstGarden() = checkedAt(this, '#') != '#'
private fun Coordinates.wrapped() = Coordinates(posRem(this.x, getWidth()), posRem(this.y, getHeight()))
private fun posRem(x: Int, q: Int) = ((x%q)+q)%q
}
fun main() {
val testInput = """...........
.....###.#.
.###.##..#.
..#.#...#..
....#.#....
.##..S####.
.##..#...#.
.......##..
.##.#.####.
.##..##.##.
...........""".trimIndent().split("\n")
fun part1(input: List<String>, steps: Int=64): Int {
val g = Garden(input)
val start = g.startCoord()
// val maze2 = MazeToTarget(start, { g.doubleMovesFrom(it) }, (steps / 2)-1)
// println(maze2.distances.size)
val maze = MazeToTarget(start, { g.movesFrom(it) }, steps)
return maze.distances.values.count { it <= steps && it % 2 == steps % 2 }
}
fun part2(input: List<String>, steps: Int=500): Int {
val g = InfiniteGarden(input)
val start = g.startCoord()
val maze = MazeToTarget(start, { g.movesFrom(it) }, (steps / 2)-1)
println(listOf(N,S, E,W).map { start.move(it, 2* if (it in listOf(E,W)) g.getWidth() else g.getHeight()) }
.map { maze.distances[it] })
val g2 = Garden(input)
val singleMaze = MazeToTarget(start) { g2.movesFrom(it) }
fun getLine(x1: Int, y1:Int, x2: Int,y2:Int):List<Int> {
return Coordinates(x1,y1).lineTo(Coordinates(x2, y2)).map { singleMaze.distances[it] ?: -1 }.toList()
}
// Edges
println(getLine(0,0,g.getWidth()-1,0))
println(getLine(0,0,0,g.getHeight()-1))
println(getLine(0,g.getHeight()-1,g.getWidth()-1,g.getHeight()-1))
println(getLine(g.getWidth()-1,0,g.getWidth()-1,g.getHeight()-1))
return maze.distances.size
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput,6)
println(testValue)
check(testValue == 16)
println(part2(testInput, 500))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 21)
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,553 | aoc-2022-kotlin | Apache License 2.0 |
src/Day23.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | import java.awt.geom.Point2D
object Day23 {
fun parseGrid(grid: List<String>): Map<IntPair, Boolean> {
return grid.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, c ->
if (c == '#') (x to y) to true
else null
}
}.toMap()
}
private fun IntPair.canMove(board: Map<IntPair, Boolean>): Boolean {
return listOf(-1, 0, 1).flatMap { y ->
listOf(-1, 0, 1).map { x -> x to y }
}.filter { it != 0 to 0 }.map { it + this}.any { board.getOrDefault(it, false)}
}
private fun IntPair.planMove(board: Map<IntPair, Boolean>, dir: IntPair): IntPair? {
return if (dir.first == 0) {
listOf(-1, 0, 1).map { it to dir.second }.map { it + this }
.none { board.getOrDefault(it, false) }.takeIf { it }?.let { dir }
} else if (dir.second == 0) {
listOf(-1, 0, 1).map { dir.first to it }.map { it + this }
.none { board.getOrDefault(it, false) }.takeIf { it }?.let { dir }
} else error("unknown dir")
}
private fun MutableMap<IntPair, Boolean>.round(directions: List<IntPair>): Boolean {
return filterValues { it }
.filterKeys { it.canMove(this)}
.map { e -> e.key to directions.firstNotNullOfOrNull { dir -> e.key.planMove(this, dir) }
}
.filter { it.second != null }
.groupBy { it.first + it.second!! }
.filterValues { e -> e.size == 1 }
.mapValues { it.value.map { it.first }.first() }
.map { (newPos, oldPos) ->
this[newPos] = true
this[oldPos] = false
true
}.any { it }
}
private fun MutableMap<IntPair, Boolean>.plot() {
val minX = this.filterValues { it }.minOf { it.key.first }
val minY = this.filterValues { it }.minOf { it.key.second }
val maxX = this.filterValues { it }.maxOf { it.key.first }
val maxY = this.filterValues { it }.maxOf { it.key.second }
(minY..maxY).forEach { y -> (minX..maxX).forEach { x -> print(this.getOrDefault(x to y, false).let { if (it) "#" else "." }) }; println() }
}
fun part1(board: MutableMap<IntPair, Boolean>) {
var directions = listOf(
0 to -1, // North
0 to 1, // South
-1 to 0, // West
1 to 0, // East
)
repeat(10_000) { n ->
if (!board.round(directions)) {
(n + 1).log("part2")
return@repeat
}
// board.plot()
directions = directions.drop(1) + directions.first()
// directions.log()
if (n == 9) {
val minX = board.filterValues { it }.minOf { it.key.first }
val minY = board.filterValues { it }.minOf { it.key.second }
val maxX = board.filterValues { it }.maxOf { it.key.first }
val maxY = board.filterValues { it }.maxOf { it.key.second }
// 4026 too low
(minY..maxY).flatMap { y -> (minX..maxX).map { x -> x to y } }
.map { board.getOrDefault(it, false) }.count { !it }.log("part1")
}
}
}
fun part2(input: List<String>) {
}
@JvmStatic
fun main(args: Array<String>) {
val input = downloadAndReadInput("Day23").filter { it.isNotBlank() }
val grid = parseGrid(input).toMutableMap().log()
part1(grid)
}
}
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 3,563 | advent-of-code-2022 | Apache License 2.0 |
src/Day17.kt | robinpokorny | 572,434,148 | false | {"Kotlin": 38009} | class CircularList<T>(private val list: List<T>) {
private var index = 0
fun next(): T =
list[index % list.size]
.also { index++ }
fun reset(): Unit {
index = 0
return
}
}
private fun parse(input: List<String>) = input
.single()
.toList()
.mapNotNull {
when (it) {
'<' -> Point.LEFT
'>' -> Point.RIGHT
else -> null
}
}
.let { CircularList(it) }
private enum class Block(val shape: List<Point>) {
H(listOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0))),
X(listOf(Point(0, 1), Point(1, 0), Point(1, 1), Point(2, 1), Point(1, 2))),
J(listOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, 1), Point(2, 2))),
I(listOf(Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3))),
O(listOf(Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1))),
}
private val blocks =
CircularList(listOf(Block.H, Block.X, Block.J, Block.I, Block.O))
typealias Grid = MutableList<MutableList<Boolean>>
// Moves the block if possible or returns the original block and if it was moved
private fun moveIfPossible(
grid: Grid,
block: List<Point>,
move: Point
): Pair<List<Point>, Boolean> {
val candidate = block.map { it + move }
val free = candidate.all {
// Check coordinates are valid and there is no other block in the grid
grid.getOrNull(it.y)?.getOrNull(it.x)?.not() ?: false
}
if (free)
return candidate to true
else
return block to false
}
private fun part1(jet: CircularList<Point>): Int {
val grid = MutableList(10_000) { MutableList(7) { false } }
blocks.reset()
generateSequence { blocks.next() }
.take(2022)
.forEach { nextBlock ->
val top = grid.indexOfLast { it.contains(true) }
val spawn = Point(2, top + 4)
var block = nextBlock.shape.map { it + spawn }
while (true) {
val nextJet = jet.next()
val (afterJet, _) = moveIfPossible(grid, block, nextJet)
val (afterDown, movedDown) = moveIfPossible(
grid,
afterJet,
Point.DOWN
)
block = afterDown
if (!movedDown) break
}
block.forEach { grid[it.y][it.x] = true }
}
return grid.indexOfLast { it.contains(true) } + 1
}
private fun part2(input: List<String>): Int {
return 0
}
fun main() {
val input = parse(readDayInput(17))
val testInput = parse(rawTestInput)
// PART 1
assertEquals(part1(testInput), 3068)
println("Part1: ${part1(input)}")
// PART 2
// assertEquals(part2(testInput), 0)
// println("Part2: ${part2(input)}")
}
private val rawTestInput = """
>>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>
""".trimIndent().lines() | 0 | Kotlin | 0 | 2 | 56a108aaf90b98030a7d7165d55d74d2aff22ecc | 2,900 | advent-of-code-2022 | MIT License |
src/2022/Day12.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2022`
import common.Adj2D
import java.io.File
import java.util.*
fun main() {
Day12().solve()
}
class Day12 {
val input1 = """
Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi
""".trimIndent()
data class Square(
val height: Int,
var ix: Int,
var minStep: Int = 20000,
var finished: Boolean = false
)
// 20000 > 136 * 41
val MAX_STEP = 20000
fun List<Square>.shortest(startIx: Int, endIx: Int, a: Adj2D): Int {
val startSquare = get(startIx)
val endSquare = get(endIx)
var nextSquare = startSquare
startSquare.finished = true
startSquare.minStep = 0
while (!endSquare.finished) {
// println(nextSquare.ix)
// println(a.adj4(nextSquare.ix))
// println(a.adj4(nextSquare.ix).map{get(it)})
a.adj4(nextSquare.ix).map{get(it)}.filter {
!it.finished && (it.height-nextSquare.height < 2)
}.forEach {
if (it.minStep > nextSquare.minStep+1) {
it.minStep = nextSquare.minStep+1
}
}
nextSquare = filter { !it.finished }.minBy { it.minStep }
nextSquare.finished = true
if (nextSquare.minStep == MAX_STEP) {
break
}
// println(nextSquare)
}
return endSquare.minStep
}
fun solve() {
val f = File("src/2022/inputs/day12.in")
val s = Scanner(f)
// val s = Scanner(input1)
var y0 = 0
val squares = mutableListOf<Square>()
var ix = 0
var startIx = 0
var endIx = 0
while (s.hasNextLine()) {
val line = s.nextLine().trim()
if (!line.isEmpty()) {
++y0
squares.addAll(line.map{
if (it == 'S') {
startIx = ix
Square(0, ix++)
} else if (it == 'E') {
endIx = ix
Square(25, ix++)
} else {
Square(it - 'a', ix++)
}
})
}
}
val y = y0
val x = squares.size/y
val a = Adj2D(x, y)
val minNum = squares.filter { it.height == 0 }.size
var mix = 0
val min1 = squares.filter { it.height == 0 }.map {
val m = squares.map { it.copy() }.shortest(it.ix, endIx, a)
println("$m ${++mix}/$minNum")
m
}.filter { it != MAX_STEP }.min()
println("${x} ${y} ${min1} ${squares.shortest(startIx, endIx, a)}")
}
}
| 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 2,751 | advent-of-code | Apache License 2.0 |
src/Day04.kt | jimmymorales | 572,156,554 | false | {"Kotlin": 33914} | fun main() {
fun String.parsePairs(): Pair<IntRange, IntRange> = split(",").map { pair ->
pair.split("-").map(String::toInt).let { (l, h) -> l..h }
}.let { (p1, p2) -> p1 to p2 }
fun part1(input: List<String>): Int = input.map(String::parsePairs)
.count { (p1, p2) ->
p1.intersect(p2).let { it.containsAll(p1.toList()) || it.containsAll(p2.toList()) }
}
fun part2(input: List<String>): Int = input.map(String::parsePairs)
.count { (p1, p2) -> p1.intersect(p2).isNotEmpty() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
val input = readInput("Day04")
println(part1(input))
// part 2
check(part2(testInput) == 4)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fb72806e163055c2a562702d10a19028cab43188 | 827 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/io/queue/KeysAndRooms.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.queue
import java.util.*
// https://leetcode.com/explore/learn/card/queue-stack/239/conclusion/1391/
class KeysAndRooms {
fun execute(rooms: List<List<Int>>): Boolean {
val stack = Stack<Int>()
val visited = BooleanArray(rooms.size)
stack.push(0)
while (stack.isNotEmpty()) {
stack.pop().let { current ->
visited[current] = true
rooms[current].filter { !visited[it] }.map { stack.push(it) }
}
}
return visited.allVisited()
}
private fun BooleanArray.allVisited() = this.reduce { acc, b -> acc && b }
fun executeRecursive(rooms: List<List<Int>>, current: Int = 0, visited: BooleanArray = BooleanArray(rooms.size)): Boolean {
visited[current] = true
return when {
rooms[current].isEmpty() || rooms[current].none { !visited[it] } -> visited.allVisited()
else -> rooms[current].filter { !visited[it] }.fold(false) { acc, i -> acc || executeRecursive(rooms, i, visited) }
}
}
}
fun main() {
val keysAndRooms = KeysAndRooms()
listOf(
listOf(listOf(1), listOf(2), listOf(3), emptyList()) to true,
listOf(listOf(2, 3), emptyList(), listOf(2), listOf(1, 3, 1)) to true,
listOf(listOf(1,3),listOf(3,0,1),listOf(2),listOf(0)) to false
)
.mapIndexed { index, (rooms, output) ->
println("$index isValid: ${keysAndRooms.executeRecursive(rooms) == output}")
}
}
| 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,402 | coding | MIT License |
src/2022/Day02.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | package `2022`
import readInput
fun main() {
fun part1(input: List<String>): Int {
// A, X - Rock
// B, Y - Paper
// C, Z - Scissors
val costs = mapOf(
"A X" to 1 + 3,
"A Y" to 2 + 6,
"A Z" to 3 + 0,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 1 + 6,
"C Y" to 2 + 0,
"C Z" to 3 + 3,
)
return input.sumOf { costs[it]!! }
}
fun part2(input: List<String>): Int {
val costs = mapOf(
"A X" to 0 + 3,
"A Y" to 3 + 1,
"A Z" to 6 + 2,
"B X" to 0 + 1,
"B Y" to 3 + 2,
"B Z" to 6 + 3,
"C X" to 0 + 2,
"C Y" to 3 + 3,
"C Z" to 6 + 1,
)
return input.sumOf { costs[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 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 1,159 | aoc-2022-in-kotlin | Apache License 2.0 |
day24/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | import java.io.File
fun main() {
println("Part I: the solution is ${solvePartI(readImmuneSystemInputFile(), readInfectionInputFile())}.")
println("Part II: the solution is ${solvePartII(readImmuneSystemInputFile(), readInfectionInputFile())}.")
}
fun readImmuneSystemInputFile(): List<String> {
return File(ClassLoader.getSystemResource("immune_system_input.txt").file).readLines()
}
fun readInfectionInputFile(): List<String> {
return File(ClassLoader.getSystemResource("infection_input.txt").file).readLines()
}
fun solvePartI(immuneSystemInput: List<String>, infectionInput: List<String>): Int {
val immuneSystemArmy = createArmy(immuneSystemInput, ArmyType.IMMUNE_SYSTEM)
val infectionArmy = createArmy(infectionInput, ArmyType.INFECTION)
val outcome = runCombat(immuneSystemArmy, infectionArmy)
return if (outcome == Outcome.IMMUNE_SYSTEM) {
immuneSystemArmy.groups.sumBy { group -> group.numberOfUnits }
} else { // assuming outcome will never be a stalemate
infectionArmy.groups.sumBy { group -> group.numberOfUnits }
}
}
fun solvePartII(immuneSystemInput: List<String>, infectionInput: List<String>): Int {
var boost = 76
while (true) {
val immuneSystemArmy = createArmy(immuneSystemInput, ArmyType.IMMUNE_SYSTEM)
val infectionArmy = createArmy(infectionInput, ArmyType.INFECTION)
immuneSystemArmy.boostBy(boost)
val outcome = runCombat(immuneSystemArmy, infectionArmy)
if (outcome == Outcome.IMMUNE_SYSTEM) {
return immuneSystemArmy.groups.sumBy { group -> group.numberOfUnits }
} else {
boost++
}
}
}
fun createArmy(input: List<String>, armyType: ArmyType): Army {
val groupRegex = "(\\d+) units each with (\\d+) hit points(\\s?.+\\s?)with an attack that does (\\d+) (.+) damage at initiative (\\d+)".toRegex()
var groupId = 0
return Army(
input.map { groupInput ->
val (numberOfUnitsString,
numberOfHitPointsString,
immunitiesWeaknessesString,
attackDamageString,
attackTypeString,
initiativeString) = groupRegex.matchEntire(groupInput)!!.destructured
var weaknesses = listOf<Attack>()
var immunities = listOf<Attack>()
if (immunitiesWeaknessesString.isNotEmpty()) {
if (";" in immunitiesWeaknessesString) {
val splitImmunitiesWeaknesses = immunitiesWeaknessesString.split(";")
if ("weak" in splitImmunitiesWeaknesses[0]) {
weaknesses = Attack.identify(splitImmunitiesWeaknesses[0])
} else if ("weak" in splitImmunitiesWeaknesses[1]) {
weaknesses = Attack.identify(splitImmunitiesWeaknesses[1])
}
if ("immune" in splitImmunitiesWeaknesses[0]) {
immunities = Attack.identify(splitImmunitiesWeaknesses[0])
} else if ("immune" in splitImmunitiesWeaknesses[1]) {
immunities = Attack.identify(splitImmunitiesWeaknesses[1])
}
} else {
if ("weak" in immunitiesWeaknessesString) {
weaknesses = Attack.identify(immunitiesWeaknessesString)
}
if ("immune" in immunitiesWeaknessesString) {
immunities = Attack.identify(immunitiesWeaknessesString)
}
}
}
groupId++
Group(armyType,
armyType.toString() + groupId,
numberOfUnitsString.toInt(),
numberOfHitPointsString.toInt(),
attackDamageString.toInt(),
Attack.identify(attackTypeString)[0],
initiativeString.toInt(),
weaknesses,
immunities)
}
.toMutableList())
}
fun getGroup(army: Army, id: String): Group {
return army.groups.first { group -> group.id == id }
}
fun calculateTargetIds(attackingArmy: Army, defendingArmy: Army): Map<String, String?> {
val sortedAttackingArmyGroups = attackingArmy
.groups
.sortedWith(compareByDescending<Group> { attackingGroup ->
attackingGroup.effectivePower
}.thenByDescending { attackingGroup -> attackingGroup.initiative })
val mutableDefendingArmyGroups = defendingArmy.groups.toMutableList()
val result = mutableMapOf<String, String?>()
sortedAttackingArmyGroups.forEach { attackingGroup ->
if (mutableDefendingArmyGroups.isNotEmpty()) {
val potentialDefendingTarget = mutableDefendingArmyGroups
.sortedWith(compareByDescending<Group> { defendingGroup ->
defendingGroup.damageBy(attackingGroup)
}.thenByDescending { defendingGroup ->
defendingGroup.effectivePower
}.thenByDescending { defendingGroup ->
defendingGroup.initiative
})
.first()
if (potentialDefendingTarget.damageBy(attackingGroup) > 0) {
result[attackingGroup.id] = potentialDefendingTarget.id
mutableDefendingArmyGroups -= potentialDefendingTarget
} else {
result[attackingGroup.id] = null
}
} else {
result[attackingGroup.id] = null
}
}
return result.toMap()
}
fun runCombat(immuneSystemArmy: Army, infectionArmy: Army): Outcome {
var currentImmuneSystemTotalSize = immuneSystemArmy.totalSize()
var currentInfectionTotalSize = infectionArmy.totalSize()
while (true) {
// targets must be calculated first, rather than on the fly
val immuneSystemTargetIds = calculateTargetIds(immuneSystemArmy, infectionArmy)
val infectionTargetIds = calculateTargetIds(infectionArmy, immuneSystemArmy)
val sortedCombinedGroups = (immuneSystemArmy.groups + infectionArmy.groups)
.sortedByDescending { group -> group.initiative }
sortedCombinedGroups.forEach { attackingGroup ->
if (attackingGroup.numberOfUnits != 0) {
val targetIds: Map<String, String?>
val targetArmy: Army
when (attackingGroup.armyType) {
ArmyType.IMMUNE_SYSTEM -> {
targetIds = immuneSystemTargetIds
targetArmy = infectionArmy
}
ArmyType.INFECTION -> {
targetIds = infectionTargetIds
targetArmy = immuneSystemArmy
}
}
val targetId = targetIds[attackingGroup.id]
if (targetId != null) {
val targetGroup = getGroup(targetArmy, targetId)
targetGroup.attackBy(attackingGroup)
}
targetArmy.groups.removeIf { group -> group.numberOfUnits <= 0 }
}
}
if (immuneSystemArmy.isEmpty()) {
return Outcome.INFECTION
} else if (infectionArmy.isEmpty()) {
return Outcome.IMMUNE_SYSTEM
} else if (currentImmuneSystemTotalSize == immuneSystemArmy.totalSize() && currentInfectionTotalSize == infectionArmy.totalSize()) {
return Outcome.STALEMATE
} else {
currentImmuneSystemTotalSize = immuneSystemArmy.totalSize()
currentInfectionTotalSize = infectionArmy.totalSize()
}
}
}
data class Army(var groups: MutableList<Group>) {
fun isEmpty(): Boolean {
return groups.size == 0
}
fun totalSize(): Int {
return groups.sumBy { group -> group.numberOfUnits }
}
fun boostBy(boost: Int) {
groups.forEach { group -> group.attackDamage += boost }
}
}
data class Group(val armyType: ArmyType,
val id: String,
var numberOfUnits: Int,
val numberOfHitPoints: Int,
var attackDamage: Int,
val attackType: Attack,
val initiative: Int,
val weaknesses: List<Attack>,
val immunities: List<Attack>) {
val effectivePower: Int
get() = numberOfUnits * attackDamage
fun damageBy(otherGroup: Group): Int {
return when {
otherGroup.attackType in this.weaknesses -> otherGroup.effectivePower * 2
otherGroup.attackType in this.immunities -> 0
else -> otherGroup.effectivePower
}
}
fun attackBy(otherGroup: Group) {
numberOfUnits = Math.max(0, numberOfUnits - damageBy(otherGroup) / numberOfHitPoints)
}
}
enum class ArmyType {
IMMUNE_SYSTEM, INFECTION;
}
enum class Attack {
BLUDGEONING, COLD, FIRE, RADIATION, SLASHING;
companion object {
fun identify(input: String): List<Attack> {
val result = mutableListOf<Attack>()
if ("bludgeoning" in input) result += BLUDGEONING
if ("cold" in input) result += COLD
if ("fire" in input) result += FIRE
if ("radiation" in input) result += RADIATION
if ("slashing" in input) result += SLASHING
return result
}
}
}
enum class Outcome {
IMMUNE_SYSTEM, INFECTION, STALEMATE;
}
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 9,760 | AdventOfCode2018 | MIT License |
src/Day08.kt | BrianEstrada | 572,700,177 | false | {"Kotlin": 22757} | fun main() {
// Test Case
val testInput = readInput("Day08_test")
val part1TestResult = Day08.part1(testInput)
println(part1TestResult)
check(part1TestResult == 21)
val part2TestResult = Day08.part2(testInput)
println(part2TestResult)
check(part2TestResult == 8)
// Actual Case
val input = readInput("Day08")
println("Part 1: " + Day08.part1(input))
println("Part 2: " + Day08.part2(input))
}
private object Day08 {
fun part1(lines: List<String>): Int {
val treeHeightMap = TreeHeightMap(
map = lines.map { line ->
line.toCharArray().map { char ->
char.digitToInt()
}
}
)
treeHeightMap.print()
return treeHeightMap.visibleCount
}
fun TreeHeightMap.isVisibleOn(x: Int, y: Int, direction: Direction): Boolean {
val value = map[y][x]
val xAxis: Boolean
val range: IntProgression
when (direction) {
Direction.Top -> {
range = IntRange(0, y)
xAxis = false
}
Direction.Bottom -> {
range = IntRange(y, yMax - 1).reversed()
xAxis = false
}
Direction.Left -> {
range = IntRange(0, x)
xAxis = true
}
Direction.Right -> {
range = IntRange(x, xMax - 1).reversed()
xAxis = true
}
}
for (i in range) {
val checkValue = if (xAxis) map[y][i] else map[i][x]
if (i == if (xAxis) x else y) {
return true
}
if (checkValue >= value) {
return false
}
}
return false
}
fun part2(lines: List<String>): Int {
val treeHeightMap = TreeHeightMap(
map = lines.map { line ->
line.toCharArray().map { char ->
char.digitToInt()
}
}
)
var max = 0
treeHeightMap.iterateThroughMap { x, y ->
val results = arrayOf(
treeHeightMap.visibleCount(x, y, Direction.Top),
treeHeightMap.visibleCount(x, y, Direction.Bottom),
treeHeightMap.visibleCount(x, y, Direction.Left),
treeHeightMap.visibleCount(x, y, Direction.Right)
)
val result = results[0] * results[1] * results[2] * results[3]
if (result > max) {
max = result
}
}
return max
}
fun TreeHeightMap.visibleCount(x: Int, y: Int, direction: Direction): Int {
val cord = x to y
val value = map[y][x]
val xAxis: Boolean
val range: IntProgression
when (direction) {
Direction.Top -> {
range = y downTo 0
xAxis = false
}
Direction.Bottom -> {
range = y until yMax
xAxis = false
}
Direction.Left -> {
range = x downTo 0
xAxis = true
}
Direction.Right -> {
range = x until xMax
xAxis = true
}
}
var index = 0
for (i in range) {
val currentCord = if (xAxis) i to y else x to i
if (currentCord != cord) {
val checkValue = map[currentCord.second][currentCord.first]
index++
if (checkValue >= value) {
return index
}
}
}
return index
}
enum class Direction {
Top,
Bottom,
Left,
Right
}
data class TreeHeightMap(
val map: List<List<Int>>,
) {
val xMax = map.first().size
val yMax = map.size
var visibleCount = 0
init {
calculateVisibleCount()
}
fun print() {
println()
map.forEach { chars ->
chars.forEach { char ->
print(char)
}
println()
}
println()
}
private fun calculateVisibleCount() {
// Add Edges
visibleCount = (((yMax * 2) + (xMax * 2)) - 4)
iterateThroughMap { x, y ->
if (isVisible(x, y)) {
visibleCount++
}
}
}
fun iterateThroughMap(callback: (x: Int, y: Int) -> Unit) {
for (y in 1 until yMax - 1) {
for (x in 1 until xMax - 1) {
callback(x, y)
}
}
}
}
fun TreeHeightMap.isVisible(x: Int, y: Int): Boolean {
return Direction.values().firstOrNull { direction ->
isVisibleOn(x, y, direction)
} != null
}
} | 1 | Kotlin | 0 | 1 | 032a4693aff514c9b30e979e63560dc48917411d | 5,002 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day15.kt | Gitvert | 433,947,508 | false | {"Kotlin": 82286} | import java.util.*
fun day15() {
val lines: List<String> = readFile("day15.txt")
day15part1(lines)
day15part2(lines)
}
fun day15part1(lines: List<String>) {
val cave = getCave(lines)
val answer = findShortestPath(cave) - cave[0][0]
println("15a: $answer")
}
fun day15part2(lines: List<String>) {
val cave = getBigCave(lines)
val answer = findShortestPath(cave) - cave[0][0]
println("15b: $answer")
}
fun getCave(lines: List<String>): Array<IntArray> {
val cave = Array(lines.size) { IntArray(lines[0].length) { 0 } }
lines.forEachIndexed { i, row ->
row.forEachIndexed { j, _ ->
cave[i][j] = Integer.valueOf(row[j].toString())
}
}
return cave
}
fun getBigCave(lines: List<String>): Array<IntArray> {
val size = lines.size
val cave = Array(size * 5) { IntArray(size * 5) { 0 } }
lines.forEachIndexed { i, row ->
row.forEachIndexed { j, _ ->
cave[i][j] = Integer.valueOf(row[j].toString())
for (k in 1..4) {
cave[i][j + size * k] = getNextNumber(cave[i][j + size * (k - 1)])
}
}
}
for (k in 1..4) {
for (i in 0 until size) {
for (j in 0 until size * 5) {
cave[i + size * k][j] = getNextNumber(cave[i + size * (k - 1)][j])
}
}
}
return cave
}
fun getNextNumber(number: Int): Int {
return when (number) {
9 -> 1
else -> number + 1
}
}
fun findShortestPath(cave: Array<IntArray>): Int {
val dx = arrayOf(-1, 0, 1, 0)
val dy = arrayOf(0, 1, 0, -1)
val size = cave.size
val distance = Array(size) { IntArray(size) { Int.MAX_VALUE } }
distance[0][0] = cave[0][0]
val pq: PriorityQueue<Cell> = PriorityQueue(size * size, compareBy { it.distance })
pq.add(Cell(0, 0, distance[0][0]))
while (pq.isNotEmpty()) {
val current = pq.poll();
for (i in 0..3) {
val rows = current.x + dx[i]
val cols = current.y + dy[i]
if (isInGrid(rows, cols, size)) {
if (distance[rows][cols] >
distance[current.x][current.y] +
cave[rows][cols]
) {
if (distance[rows][cols] != Int.MAX_VALUE) {
val adj = Cell(
rows, cols,
distance[rows][cols]
)
pq.remove(adj)
}
// Insert cell with updated distance
distance[rows][cols] = distance[current.x][current.y] +
cave[rows][cols]
pq.add(Cell(rows, cols, distance[rows][cols]))
}
}
}
}
return distance[size- 1][size - 1]
}
/*fun compareDistance(a: Cell, b: Cell): Int {
return if (a.distance < b.distance) {
-1
} else if (a.distance > b.distance) {
1
} else {
0
}
}*/
fun isInGrid(i: Int, j: Int, size: Int): Boolean {
return i in 0 until size && j in 0 until size
}
data class Cell (val x: Int, val y: Int, val distance: Int) | 0 | Kotlin | 0 | 0 | 02484bd3bcb921094bc83368843773f7912fe757 | 3,223 | advent_of_code_2021 | MIT License |
src/day08/Day08.kt | Puju2496 | 576,611,911 | false | {"Kotlin": 46156} | package day08
import readInput
import java.util.*
fun main() {
// test if implementation meets criteria from the description, like:
val input = readInput("src/day08", "Day08")
println("Part1")
val treeHeightMatrix = part1(input)
println("Part2")
part2(treeHeightMatrix)
}
private fun part1(inputs: List<String>): Array<IntArray> {
val rowSize = inputs[0].length
val colSize = inputs.size
val inputMatrix = Array(rowSize) { IntArray(colSize) }
var visibleTreesSize = 0
visibleTreesSize += ((colSize - 2) * 2)
visibleTreesSize += rowSize * 2
inputs.forEachIndexed { index, value ->
val treesHeights = value.split("").toMutableList()
treesHeights.removeAll(listOf(""))
treesHeights.mapIndexed { treeIndex, treeValue ->
inputMatrix[index][treeIndex] = treeValue.toInt()
}
}
for (i in 1 until rowSize - 1) {
for (j in 1 until colSize - 1) {
val current = inputMatrix[i][j]
val isVisible = checkLeftHorizontal(current, inputMatrix, i, j - 1)
|| checkRightHorizontal(current, inputMatrix, i, j + 1)
|| checkTopVertical(current, inputMatrix, j, i - 1)
|| checkBottomVertical(current, inputMatrix, j, i + 1)
if (isVisible)
visibleTreesSize++
}
}
println("visible trees - $visibleTreesSize")
return inputMatrix
}
private fun checkLeftHorizontal(current: Int, matrix: Array<IntArray>, index: Int, end: Int): Boolean {
for (j in 0..end) {
if (matrix[index][j] >= current)
return false
}
return true
}
private fun checkRightHorizontal(current: Int, matrix: Array<IntArray>, index: Int, start: Int): Boolean {
for (j in start until matrix[0].size) {
if (matrix[index][j] >= current)
return false
}
return true
}
private fun checkTopVertical(current: Int, matrix: Array<IntArray>, index: Int, end: Int): Boolean {
for (i in 0..end) {
if (matrix[i][index] >= current)
return false
}
return true
}
private fun checkBottomVertical(current: Int, matrix: Array<IntArray>, index: Int, start: Int): Boolean {
for (i in start until matrix.size) {
if (matrix[i][index] >= current)
return false
}
return true
}
private fun part2(inputMatrix: Array<IntArray>) {
var max = Int.MIN_VALUE
println("${inputMatrix.size}, ${inputMatrix[0].size}")
for (i in 1 until inputMatrix[0].size - 1) {
for (j in 1 until inputMatrix.size - 1) {
val current = inputMatrix[i][j]
val result = getLeftHorizontal(current, inputMatrix, i, j - 1) * getRightHorizontal(current, inputMatrix, i, j + 1) * getTopVertical(current, inputMatrix, j, i - 1) * getBottomVertical(current, inputMatrix, j, i + 1)
println("$i-$j- $max - $result")
if (result > max)
max = result
}
}
println("max - $max")
}
private fun getLeftHorizontal(current: Int, matrix: Array<IntArray>, index: Int, start: Int): Int {
var count = 0
for (j in start downTo 0) {
if (matrix[index][j] <= current)
++count
if (matrix[index][j] >= current)
break
}
return count
}
private fun getRightHorizontal(current: Int, matrix: Array<IntArray>, index: Int, start: Int): Int {
var count = 0
for (j in start until matrix[0].size) {
if (matrix[index][j] <= current)
++count
if (matrix[index][j] >= current)
break
}
return count
}
private fun getTopVertical(current: Int, matrix: Array<IntArray>, index: Int, start: Int): Int {
var count = 0
for (i in start downTo 0) {
if (matrix[i][index] <= current)
++count
if (matrix[i][index] >= current)
break
}
return count
}
private fun getBottomVertical(current: Int, matrix: Array<IntArray>, index: Int, start: Int): Int {
var count = 0
for (i in start until matrix.size) {
if (matrix[i][index] <= current)
++count
if (matrix[i][index] >= current)
break
}
return count
} | 0 | Kotlin | 0 | 0 | e04f89c67f6170441651a1fe2bd1f2448a2cf64e | 4,244 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2016/Day22.kt | tginsberg | 74,924,040 | false | null | /*
* Copyright (c) 2016 by <NAME>
*/
package com.ginsberg.advent2016
/**
* Advent of Code - Day 22: December 22, 2016
*
* From http://adventofcode.com/2016/day/22
*
*/
class Day22(dfRows: List<String>) {
companion object {
private val DF_ROW = Regex("""^/dev/grid/node-x(\d+)-y(\d+)\s+(\d+)T\s+(\d+)T\s+(\d+)T\s+(\d+)%$""")
}
data class Node(val x: Int, val y: Int, val size: Int, val used: Int, val free: Int)
val nodes: List<Node> = dfRows.map { parseNode(it) }.filterNotNull().sortedByDescending { it.free }
fun solvePart1(): Int =
pairedBySize().values.map { it.size }.sum()
fun solvePart2(): Int {
val maxX = nodes.maxBy { it.x }!!.x
val wall = nodes.filter { it.size > 250 }.minBy { it.x }!!
val emptyNode = nodes.first { it.used == 0 }
var result = Math.abs(emptyNode.x - wall.x) + 1 // Empty around wall X.
result += emptyNode.y // Empty to top
result += (maxX - wall.x) // Empty over next to goal
result += (5 * maxX.dec()) + 1 // Goal back to start
return result
}
private fun pairedBySize(): Map<Node, List<Node>> =
nodes.associateBy(
{ it },
{
nodes
.filter { me -> me.used > 0 }
.filter { me -> me.used < it.free }
.filter { me -> me != it }
}
).filterNot { it.value.isEmpty() }
private fun parseNode(input: String): Node? {
if (DF_ROW.matches(input)) {
val (x, y, size, used, free) = DF_ROW.matchEntire(input)!!.destructured
return Node(x.toInt(), y.toInt(), size.toInt(), used.toInt(), free.toInt())
}
return null
}
}
| 0 | Kotlin | 0 | 3 | a486b60e1c0f76242b95dd37b51dfa1d50e6b321 | 1,753 | advent-2016-kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxScoreWords.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
import kotlin.math.max
/**
* 1255. Maximum Score Words Formed by Letters
* @see <a href="https://leetcode.com/problems/maximum-score-words-formed-by-letters/">Source</a>
*/
fun interface MaxScoreWords {
operator fun invoke(words: Array<String>, letters: CharArray, score: IntArray): Int
}
class MaxScoreWordsBacktracking : MaxScoreWords {
override operator fun invoke(words: Array<String>, letters: CharArray, score: IntArray): Int {
if (words.isEmpty() || letters.isEmpty() || score.isEmpty()) return 0
val count = IntArray(score.size)
for (ch in letters) {
count[ch.code - 'a'.code]++
}
return backtrack(words, count, score, 0)
}
private fun backtrack(words: Array<String>, count: IntArray, score: IntArray, index: Int): Int {
var max = 0
for (i in index until words.size) {
var res = 0
var isValid = true
for (ch in words[i].toCharArray()) {
count[ch.code - 'a'.code]--
res += score[ch.code - 'a'.code]
if (count[ch.code - 'a'.code] < 0) isValid = false
}
if (isValid) {
res += backtrack(words, count, score, i + 1)
max = max(res, max)
}
for (ch in words[i].toCharArray()) {
count[ch.code - 'a'.code]++
}
}
return max
}
}
class MaxScoreWordsDFS : MaxScoreWords {
override operator fun invoke(words: Array<String>, letters: CharArray, score: IntArray): Int {
val memo = IntArray(ALPHABET_LETTERS_COUNT)
for (l in letters) {
memo[l.code - 'a'.code]++
}
return dfs(0, memo, score, words)
}
fun dfs(index: Int, memo: IntArray, score: IntArray, words: Array<String>): Int {
if (index == words.size) {
return 0
}
var res = 0
val w = words[index]
var count = 0
var i = 0
val temp: IntArray = memo.copyOf(memo.size)
while (i < w.length) {
val c = w[i]
count += if (temp[c.code - 'a'.code] > 0) {
temp[c.code - 'a'.code]--
score[c.code - 'a'.code]
} else {
break
}
i++
}
if (i == w.length) {
res = max(res, count + dfs(index + 1, temp, score, words))
}
res = max(dfs(index + 1, memo, score, words), res)
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,208 | kotlab | Apache License 2.0 |
LeetCode/0454. 4Sum II/Solution.kt | InnoFang | 86,413,001 | false | {"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410} | /**
* 48 / 48 test cases passed.
* Status: Accepted
* Runtime: 888 ms
*/
class Solution {
fun fourSumCount(A: IntArray, B: IntArray, C: IntArray, D: IntArray): Int {
val store = HashMap<Int, Int>()
C.forEach { i ->
D.forEach { j ->
// val v = store[i + j]
// if (v == null) store[i + j] = 1 else store[i + j] = v + 1
store[i + j] = (store[i + j] ?: 0) + 1
}
}
var res = 0
A.forEach { i ->
B.forEach { j ->
// res += store.getOrDefault(0 - i - j, 0)
store[0 - i - j]?.let { res += it }
}
}
return res
}
}
/**
* 48 / 48 test cases passed.
* Status: Accepted
* Runtime: 936 ms
*/
class Solution2 {
fun fourSumCount(A: IntArray, B: IntArray, C: IntArray, D: IntArray): Int {
val store = HashMap<Int, Int>()
var res = 0
dualForEach(C, D, { i, j -> store[i + j] = (store[i + j] ?: 0) + 1 })
dualForEach(A, B, { i, j -> store[0 - i - j]?.let { res += it } })
return res
}
private inline fun dualForEach(a: IntArray, b: IntArray, forEachDo: (i: Int, j: Int) -> Unit)
: Unit = a.forEach { i -> b.forEach { j -> forEachDo(i, j) } }
}
fun main(args: Array<String>) {
Solution2().fourSumCount(intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-1, 2), intArrayOf(0, 2)).let(::println)
}
| 0 | C++ | 8 | 20 | 2419a7d720bea1fd6ff3b75c38342a0ace18b205 | 1,444 | algo-set | Apache License 2.0 |
src/Day04.kt | pavlo-dh | 572,882,309 | false | {"Kotlin": 39999} | fun main() {
fun parseData(input: List<String>) = input.map { line ->
val (firstFrom, firstTo, secondFrom, secondTo) = line.split('-', ',').map(String::toInt)
firstFrom..firstTo to secondFrom..secondTo
}
fun part1(input: List<String>): Long {
val data = parseData(input)
return data.sumOf { pair ->
val firstSet = pair.first.toSet()
val secondSet = pair.second.toSet()
if (firstSet.containsAll(secondSet) || secondSet.containsAll(firstSet)) 1L else 0L
}
}
fun part2(input: List<String>): Long {
val data = parseData(input)
return data.sumOf { pair ->
val firstSet = pair.first.toSet()
val secondSet = pair.second.toSet()
if (firstSet.intersect(secondSet).isNotEmpty()) 1L else 0L
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part2(testInput) == 4L)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992 | 1,088 | aoc-2022-in-kotlin | Apache License 2.0 |
advent-of-code-2021/src/code/day13/Main.kt | Conor-Moran | 288,265,415 | false | {"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733} | package code.day13
import java.io.File
import java.lang.Integer.max
import kotlin.math.min
val doDump = false
fun main() {
doIt("Day 13 Part 1: Test Input", "src/code/day13/test.input", part1)
doIt("Day 13 Part 1: Real Input", "src/code/day13/part1.input", part1)
doIt("Day 13 Part 2: Test Input", "src/code/day13/test.input", part2);
doIt("Day 13 Part 2: Real Input", "src/code/day13/part1.input", part2);
}
fun doIt(msg: String, input: String, calc: (nums: List<String>) -> String) {
val lines = arrayListOf<String>()
File(input).forEachLine { lines.add(it) }
println(String.format("%s: Ans: %s", msg , calc(lines)))
}
typealias Grid = Array<Array<Char>>
val part1: (List<String>) -> String = { lines ->
val grid = solve(lines)
countDots(grid).toString()
}
val part2: (List<String>) -> String = { lines ->
val grid = solve(lines, false)
toString(grid)
}
fun solve(lines: List<String>, limitOne: Boolean = true): Grid {
val input = parse(lines)
var grid = Array(input.max.x + 1) { Array<Char>(input.max.y + 1) { '.' } }
for (p in input.points) {
grid[p.x][p.y] = '#'
}
var mList = mutableListOf<Point>()
for (p in input.points) {
mList.add(p)
}
mList.sortBy { it.y }
for (f in input.folds) {
grid = fold(grid, f)
if (limitOne) break
}
return grid
}
private fun countDots(grid: Grid): Int {
var count = 0
for (i in grid.indices) {
for (j in grid[0].indices) {
if (grid[i][j] == '#') count++
}
}
return count
}
fun fold(grid: Grid, fold: Fold): Grid {
return when (fold.axis) {
'x' -> foldLeft(grid, fold.pos)
else -> foldUp(grid, fold.pos)
}
}
fun foldUp(grid: Grid, splitPos: Int): Grid {
val foldedGridLen = max(splitPos, grid[0].lastIndex - splitPos)
val foldedGrid = Array(grid.size) { Array<Char>(foldedGridLen) { '.' } }
val topLen = splitPos
for (i in grid.indices ) {
val head = grid[i].slice(0 until topLen)
val topOffset = foldedGridLen - head.size
for (j in head.indices) {
foldedGrid[i][j + topOffset] = grid[i][j]
}
}
for (i in grid.indices ) {
val tail = grid[i].slice(topLen + 1 until grid[0].size)
val tailOffset = foldedGridLen - tail.size
for(j in tail.indices.reversed()) {
if (tail[j] == '#') {
foldedGrid[i][((tail.size - 1) - j) + tailOffset] = '#'
}
}
}
return foldedGrid
}
fun foldLeft(grid: Grid, splitPos: Int): Grid {
val foldedGridLen = max(splitPos, grid.lastIndex - splitPos)
val foldedGrid = Array(foldedGridLen) { Array<Char>(grid[0].size) { '.' } }
val topLen = splitPos
val head = grid.slice(0 until topLen)
val tail = grid.slice(topLen + 1 until grid.size)
val topOffset = foldedGridLen - head.size
for (i in head.indices ) {
for (j in head[0].indices) {
foldedGrid[i + topOffset][j] = grid[i][j]
}
}
val tailOffset = foldedGridLen - tail.size
for (i in tail.indices.reversed() ) {
for(j in tail[0].indices) {
if (tail[i][j]=='#') {
foldedGrid[((tail.size - 1) - i) + tailOffset][j] = '#'
}
}
}
return foldedGrid
}
private fun toString(grid: Grid): String {
val sb = StringBuilder()
sb.append(System.lineSeparator())
for(j in grid[0].indices) {
for (i in grid.indices) {
sb.append(grid[i][j])
}
sb.append(System.lineSeparator())
}
sb.append(System.lineSeparator())
return sb.toString()
}
private fun dump(grid: Grid) {
if (!doDump) return
for(j in grid[0].indices) {
for (i in grid.indices) {
print(grid[i][j])
}
println()
}
}
val parse: (List<String>) -> Input = { lines ->
val points = mutableListOf<Point>()
val folds = mutableListOf<Fold>()
var minX = Int.MAX_VALUE
var minY = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
var maxY = Int.MIN_VALUE
lines.filter { !it.isNullOrBlank() }.forEach {
if (!it.startsWith("fold along")) {
val coords = it.split(",").map { v -> v.toInt() }
val point = Point(coords[0], coords[1])
points.add(point)
minX = min(minX, point.x)
minY = min(minY, point.y)
maxX = max(maxX, point.x)
maxY = max(maxY, point.y)
} else {
val rawFolds = it.substringAfter("fold along ").split("=")
folds.add(Fold(rawFolds[0][0], rawFolds[1].toInt()))
}
}
Input(points.toTypedArray(), folds.toTypedArray(), Point(minX, minY), Point(maxX, maxY))
}
class Point(val x: Int, val y: Int)
class Fold(val axis: Char, val pos: Int)
class Input(val points: Array<Point>, val folds: Array<Fold>, val min: Point, val max: Point)
| 0 | Kotlin | 0 | 0 | ec8bcc6257a171afb2ff3a732704b3e7768483be | 4,950 | misc-dev | MIT License |
Kotlin/src/FourSum.kt | TonnyL | 106,459,115 | false | null | /**
* Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
* Find all unique quadruplets in the array which gives the sum of target.
*
* Note: The solution set must not contain duplicate quadruplets.
*
* For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
*
* A solution set is:
* [
* [-1, 0, 0, 1],
* [-2, -1, 1, 2],
* [-2, 0, 0, 2]
* ]
*
* Accepted.
*/
class FourSum {
// Accepted. 1600ms.
/*fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val set = mutableSetOf<List<Int>>()
nums.sort()
for (i in 0 until nums.size - 3) {
for (j in i + 1 until nums.size - 2) {
for (k in j + 1 until nums.size - 1) {
for (m in k + 1 until nums.size) {
val sum = nums[i] + nums[j] + nums[k] + nums[m]
if (sum > target) {
continue
}
if (sum == target) {
set.add(listOf(nums[i], nums[j], nums[k], nums[m]))
}
}
}
}
}
return ArrayList(set)
}*/
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val results = mutableListOf<List<Int>>()
nums.sort()
for (i in 0 until nums.size - 3) {
for (j in i + 1 until nums.size - 2) {
var left = j + 1
var right = nums.size - 1
while (left < right) {
val sum = nums[i] + nums[j] + nums[left] + nums[right]
when {
sum == target -> {
val tmp = ArrayList<Int>(4)
tmp.add(nums[i])
tmp.add(nums[j])
tmp.add(nums[left])
tmp.add(nums[right])
if (!results.contains(tmp)) {
results.add(tmp)
}
left++
right--
}
sum < target -> left++
else -> right--
}
}
}
}
return results
}
}
| 1 | Swift | 22 | 189 | 39f85cdedaaf5b85f7ce842ecef975301fc974cf | 2,399 | Windary | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day12.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInputLines
import java.util.*
object Day12 : Day {
override val input = readInputLines(12).map { it.toCharArray() }.toTypedArray()
override fun part1() = solve(listOf(NodeDistance(Node.START, 0)))
override fun part2() = solve((findNode('a') + Node.START).map { NodeDistance(it, 0) })
private fun solve(startingNodes: List<NodeDistance>): Int {
val queue = PriorityQueue(startingNodes)
val visited = mutableSetOf<Node>()
while (queue.isNotEmpty()) {
val (node, dist) = queue.poll()
if (node in visited) continue;
visited.add(node)
if (node == Node.END) return dist
queue.addAll(node.adjacent().filter { node.distance(it) < 2 }.map { NodeDistance(it, dist + 1) })
}
error("Unable to find a path")
}
data class NodeDistance(val node: Node, val distance: Int) : Comparable<NodeDistance> {
override fun compareTo(other: NodeDistance) = distance.compareTo(other.distance)
}
data class Node(val char: Char, val x: Int, val y: Int) {
companion object {
val START = findNode('S').single()
val END = findNode('E').single()
}
fun adjacent(): List<Node> {
return listOf(x - 1 to y, x + 1 to y, x to y - 1, x to y + 1)
.mapNotNull { (x, y) -> input.getOrNull(y)?.getOrNull(x)?.let { Node(it, x, y) } }
}
fun distance(other: Node) = other.height() - height()
private fun height() = when (char) {
START.char -> 'a'
END.char -> 'z'
else -> char
}.code
}
private fun findNode(char: Char): List<Node> {
return input
.flatMapIndexed { y, a -> a.toList().mapIndexedNotNull { x, c -> if (c == char) y to x else null } }
.map { (y, x) -> Node(char, x, y) }
}
} | 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 2,011 | aoc2022 | MIT License |
src/day13/Day13.kt | gautemo | 317,316,447 | false | null | package day13
import shared.getText
fun waitTimesId(input: String): Int{
val (earliestString, idsString) = input.lines()
val earliest = earliestString.toInt()
val ids = idsString.split(",").filter { it != "x" }.map { it.toInt() }
var shortest = Int.MAX_VALUE
var shortestId = 0
for(id in ids){
val wait = -(earliest % id) + id
shortest = minOf(wait, shortest)
if(shortest == wait) shortestId = id
}
return shortest * shortestId
}
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
fun timestampForIndexTimes(input: String, startAt: Long = 0): Long{
val ids = input.split(",")
var skip = ids[0].toLong()
var t = startAt - (startAt % skip)
while(true){
val alligns = ids.withIndex().filter { (i, id) ->
if(id == "x") {
false
}else{
(t + i ) % id.toInt() == 0L
}
}.map { (_, id) -> id.toLong() }
if(alligns.size == ids.count { it != "x" }){
return t
}
val lcmOfAlligns = alligns.reduce { acc, l -> lcm(acc, l) }
skip = maxOf(skip, lcmOfAlligns)
t += skip
}
}
fun main(){
val input = getText("day13.txt")
val result = waitTimesId(input)
println(result)
val timestamp = timestampForIndexTimes(input.lines()[1], 100000000000000)
println(timestamp)
} | 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 1,453 | AdventOfCode2020 | MIT License |
src/main/kotlin/Day02.kt | zychu312 | 573,345,747 | false | {"Kotlin": 15557} | enum class Result {
Win, Loss, Draw;
fun toPoints(): Int = when (this) {
Win -> 6
Draw -> 3
Loss -> 0
}
companion object {
fun fromCharacter(input: Char): Result = when (input) {
'X' -> Loss
'Y' -> Draw
'Z' -> Win
else -> error("Bad character")
}
}
}
enum class Option {
Rock, Paper, Scissor;
infix fun challenge(other: Option): Result = when (this) {
Rock -> when (other) {
Rock -> Result.Draw
Paper -> Result.Loss
Scissor -> Result.Win
}
Paper -> when (other) {
Rock -> Result.Win
Paper -> Result.Draw
Scissor -> Result.Loss
}
Scissor -> when (other) {
Rock -> Result.Loss
Paper -> Result.Win
Scissor -> Result.Draw
}
}
fun pointsForPlayingIt(): Int = when (this) {
Rock -> 1
Paper -> 2
Scissor -> 3
}
companion object {
fun fromOpponentCharacter(input: Char): Option {
return when (input) {
'A' -> Rock
'B' -> Paper
'C' -> Scissor
else -> error("Bad character")
}
}
fun fromMyCharacter(input: Char): Option {
return when (input) {
'X' -> Rock
'Y' -> Paper
'Z' -> Scissor
else -> error("Bad character")
}
}
fun whichToPlayForResult(neededResult: Result, opponentOption: Option): Option {
return when (neededResult) {
Result.Win -> when (opponentOption) {
Rock -> Paper
Paper -> Scissor
Scissor -> Rock
}
Result.Loss -> when (opponentOption) {
Rock -> Scissor
Paper -> Rock
Scissor -> Paper
}
Result.Draw -> opponentOption
}
}
}
}
fun interface Strategy {
fun apply(letters: List<Char>): Int
}
val firstStrategy = Strategy { (firstLetter, secondLetter) ->
val opponentOption = Option.fromOpponentCharacter(firstLetter)
val myOption = Option.fromMyCharacter(secondLetter)
myOption.pointsForPlayingIt() + myOption.challenge(opponentOption).toPoints()
}
val secondStrategy = Strategy { (firstLetter, secondLetter) ->
val opponentOption = Option.fromOpponentCharacter(firstLetter)
val neededResult = Result.fromCharacter(secondLetter)
val myOption = Option.whichToPlayForResult(neededResult, opponentOption)
myOption.pointsForPlayingIt() + myOption.challenge(opponentOption).toPoints()
}
fun runGameUsingStrategy(strategy: Strategy): Int = loadFile("Day02Input.txt")
.readLines()
.sumOf { line ->
line
.split(' ')
.map { it.toCharArray().first() }
.let(strategy::apply)
}
fun printGameResult(result: Int) = println("Game result: $result")
fun main() {
listOf(firstStrategy, secondStrategy)
.map(::runGameUsingStrategy)
.forEach(::printGameResult)
} | 0 | Kotlin | 0 | 0 | 3e49f2e3aafe53ca32dea5bce4c128d16472fee3 | 3,243 | advent-of-code-kt | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2023/iteration/Permutations.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.iteration
/* pair */
fun <T> List<T>.permutationPairs(): Sequence<Pair<T, T>> {
return permutations(
length = 2,
permutation = ::permutationPair
)
}
private fun <T> List<T>.permutationPair(indices: IntArray, count: Int): Pair<T, T> {
require(count == 2)
return Pair(
first = get(indices[0]),
second = get(indices[1])
)
}
/* triple */
fun <T> List<T>.permutationTriples(): Sequence<Triple<T, T, T>> {
return permutations(
length = 3,
permutation = ::permutationTriple
)
}
private fun <T> List<T>.permutationTriple(indices: IntArray, count: Int): Triple<T, T, T> {
require(count == 3)
return Triple(
first = get(indices[0]),
second = get(indices[1]),
third = get(indices[2]),
)
}
/* list */
fun <T> List<T>.permutations(length: Int? = null): Sequence<List<T>> {
return permutations(
length = length,
permutation = ::permutationList
)
}
inline fun <T, V> List<T>.permutations(
length: Int? = null,
crossinline permutation: (IntArray, Int) -> V,
): Sequence<V> = sequence {
val count = length ?: size
require(count >= 0) { "length must be non-negative but was $length" }
if (count in 1..size) {
val indices = IntArray(size) { it }
val cycles = IntArray(count) { size - it }
var searching = true
yield(permutation(indices, count))
while (searching) {
var found = false
var index = count - 1
while (index >= 0 && !found) {
cycles[index]--
if (cycles[index] == 0) {
val indexBefore = indices[index]
for (i in index until size - 1) {
indices[i] = indices[i + 1]
}
indices[size - 1] = indexBefore
cycles[index] = size - index
index--
} else {
val i = size - cycles[index]
indices.swapByIndex(index, i)
yield(permutation(indices, count))
found = true
}
}
if (!found) {
searching = false
}
}
}
}
private fun <T> List<T>.permutationList(indices: IntArray, count: Int): List<T> {
require(count > 0)
return List(count) { index ->
get(indices[index])
}
}
fun IntArray.swapByIndex(a: Int, b: Int) {
this[a] = this[b].also {
this[b] = this[a]
}
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 2,618 | advent-2023 | ISC License |
src/main/kotlin/day01/trebuchet.kt | cdome | 726,684,118 | false | {"Kotlin": 17211} | package day01
import java.io.File
val numericNumbers = arrayOf("1", "2", "3", "4", "5", "6", "7", "8", "9")
val wordNumbers = arrayOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
val numbers = wordNumbers + numericNumbers
fun main() {
val instructions = File("src/main/resources/day01-trebuchet")
println("Plain Numbers:" + instructions.readLines().sumOf { line ->
line.first { it.isDigit() }.digitToInt() * 10 + line.last { it.isDigit() }.digitToInt()
})
println("Numbers and words:" + instructions
.readLines()
.map { firstLastNumber(it) }
.sumOf { it.first * 10 + it.second }
)
}
fun firstLastNumber(line: String): Pair<Int, Int> {
val firstNumberIndex = numbers
.mapIndexed { idx, value -> idx to line.indexOf(value) }
.filter { (_, position) -> position > -1 }
.minBy { (_, position) -> position }
.first
val lastNumberIndex = numbers
.mapIndexed { idx, value -> idx to line.lastIndexOf(value) }
.filter { (_, position) -> position > -1 }
.maxBy { (_, position) -> position }
.first
fun numericValue(index: Int) = (if (index > 8) index - 9 else index) + 1
return numericValue(firstNumberIndex) to numericValue(lastNumberIndex)
}
| 0 | Kotlin | 0 | 0 | 459a6541af5839ce4437dba20019b7d75b626ecd | 1,299 | aoc23 | The Unlicense |
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day18/day18.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2023.day18
import eu.janvdb.aocutil.kotlin.point2d.Direction
import eu.janvdb.aocutil.kotlin.point2d.Point2D
import eu.janvdb.aocutil.kotlin.readLines
import java.util.*
import kotlin.math.max
import kotlin.math.min
//const val FILENAME = "input18-test.txt"
const val FILENAME = "input18.txt"
fun main() {
val instructions1 = readLines(2023, FILENAME).map { Instruction.parse1(it) }
runWith(instructions1)
val instructions2 = readLines(2023, FILENAME).map { Instruction.parse2(it) }
runWith(instructions2)
}
private fun runWith(instructions: List<Instruction>) {
val grid = Grid.create(instructions)
grid.print()
val filledGrid = grid.fill()
filledGrid.print()
println(filledGrid.score())
}
data class Grid(val weightsX: List<Int>, val weightsY: List<Int>, val points: Set<Point2D>) {
private val fillStart = (0..points.maxOf { it.x }).asSequence()
.filter { x -> points.any { it.x == x && it.y == 0 } }
.map { Point2D(it + 1, 1) }
.first()
fun fill(): Grid {
val newPoints = points.toMutableSet()
val toDo = LinkedList<Point2D>()
toDo.add(fillStart)
while (!toDo.isEmpty()) {
val point = toDo.removeFirst()
sequenceOf(point.left(), point.up(), point.right(), point.down())
.filter { !newPoints.contains(it) }
.forEach { toDo.add(it); newPoints.add(it) }
}
return Grid(weightsX, weightsY, newPoints)
}
fun score() = points.sumOf { 1L * weightsX[it.x] * weightsY[it.y] }
fun print() {
val minX = points.minOf { it.x }
val maxX = points.maxOf { it.x }
val minY = points.minOf { it.y }
val maxY = points.maxOf { it.y }
for (y in minY..maxY) {
for (x in minX..maxX) {
val point = Point2D(x, y)
if (point == fillStart)
print('X')
else if (points.contains(point))
print('#')
else print('.')
}
println()
}
println()
}
companion object {
fun create(instructions: List<Instruction>): Grid {
val cornerPoints = getCornerPointsMovedToOrigin(instructions)
val weightedX = calculatedWeightedValues(cornerPoints) { it.x }
val weightedY = calculatedWeightedValues(cornerPoints) { it.y }
val foldedPoints = foldPoints(weightedX, cornerPoints, weightedY)
val connectedPoints = connectPoints(foldedPoints)
return Grid(
weightedX.values.map { it.weight },
weightedY.values.map { it.weight },
connectedPoints.toSet()
)
}
private fun getCornerPointsMovedToOrigin(instructions: List<Instruction>): List<Point2D> {
val cornerPoints = instructions.runningFold(Point2D(0, 0)) { current, instruction ->
current.move(instruction.direction, instruction.distance)
}
val minX = cornerPoints.minOf { it.x }
val minY = cornerPoints.minOf { it.y }
val movedPoints = cornerPoints.map { Point2D(it.x - minX, it.y - minY) }
return movedPoints
}
private fun calculatedWeightedValues(points: List<Point2D>, extractor: (Point2D) -> Int): WeightedValues {
val values = points.map(extractor).distinct().sorted()
val weightedValues = values.indices.asSequence().drop(1)
.flatMap { index ->
sequenceOf(
WeightedCoordinate(values[index - 1], 1),
WeightedCoordinate(values[index - 1] + 1, values[index] - values[index - 1] - 1)
)
}
.filter { it.weight != 0 }
.plus(WeightedCoordinate(values.last(), 1))
.toList()
return WeightedValues(weightedValues)
}
private fun foldPoints(weightedX: WeightedValues, movedPoints: List<Point2D>, weightedY: WeightedValues):
List<Point2D> {
val foldedByX = weightedX.values.reversed().fold(movedPoints) { current, weightedValue ->
current.map {
Point2D(
if (it.x > weightedValue.original) it.x - weightedValue.weight + 1 else it.x,
it.y
)
}
}
return weightedY.values.reversed().fold(foldedByX) { current, weightedValue ->
current.map {
Point2D(
it.x,
if (it.y > weightedValue.original) it.y - weightedValue.weight + 1 else it.y
)
}
}
}
private fun connectPoints(foldedPoints2: List<Point2D>): List<Point2D> {
val connectedPoints = foldedPoints2.zipWithNext { point1, point2 ->
if (point1.x == point2.x) {
(min(point1.y, point2.y)..max(point1.y, point2.y)).map { Point2D(point1.x, it) }
} else {
(min(point1.x, point2.x)..max(point1.x, point2.x)).map { Point2D(it, point1.y) }
}
}.flatten()
return connectedPoints
}
}
}
data class WeightedCoordinate(val original: Int, val weight: Int)
data class WeightedValues(val values: List<WeightedCoordinate>)
data class Instruction(val direction: Direction, val distance: Int) {
companion object {
fun parse1(line: String): Instruction {
fun parseDirection(direction: String) = when (direction) {
"U" -> Direction.N
"D" -> Direction.S
"L" -> Direction.W
"R" -> Direction.E
else -> throw IllegalArgumentException("Unknown direction: $direction")
}
val parts = line.split(' ')
return Instruction(
parseDirection(parts[0]),
parts[1].toInt()
)
}
fun parse2(line: String): Instruction {
fun parseDirection(direction: Char) = when (direction) {
'3' -> Direction.N
'1' -> Direction.S
'2' -> Direction.W
'0' -> Direction.E
else -> throw IllegalArgumentException("Unknown direction: $direction")
}
val hex = line.split(' ')[2].substring(2, 8)
return Instruction(
parseDirection(hex[5]),
hex.substring(0, 5).toInt(16)
)
}
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 5,421 | advent-of-code | Apache License 2.0 |
src/main/kotlin/kr/co/programmers/P172927.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/481
class P172927 {
fun solution(picks: IntArray, minerals: Array<String>): Int {
// 곡괭이의 수만큼 5칸마다 구간의 합(가중치)을 구한다.
val mines = mutableListOf<IntArray>()
var numOfPick = picks[0] + picks[1] + picks[2]
for (i in minerals.indices step 5) {
// 곡괭이의 수만큼 계산
if (numOfPick <= 0) break
// [0] : 다이아몬드 광석 수
// [1] : 철 광석 수
// [2] : 돌 광석 수
// [3] : 가중치
val mine = IntArray(4)
for (j in i until minOf(i + 5, minerals.size)) {
when (minerals[j]) {
"diamond" -> {
mine[0]++
mine[3] += 25
}
"iron" -> {
mine[1]++
mine[3] += 5
}
"stone" -> {
mine[2]++
mine[3] += 1
}
}
}
mines += mine
numOfPick--
}
// 기중치로 내림차순 정렬
mines.sortByDescending { it[3] }
// 최소 피로도 계산
var answer = 0
for (mine in mines) {
val (diamond, iron, stone) = mine
answer += when {
picks[0] > 0 -> {
picks[0]--
diamond + iron + stone
}
picks[1] > 0 -> {
picks[1]--
(diamond * 5) + iron + stone
}
picks[2] > 0 -> {
picks[0]--
(diamond * 25) + (iron * 5) + stone
}
else -> 0
}
}
return answer
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,964 | algorithm | MIT License |
kotlin/src/katas/kotlin/leetcode/traping_rain_water/TrappingRainWater.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.traping_rain_water
import datsok.*
import org.junit.*
import java.util.*
/**
* https://leetcode.com/problems/trapping-rain-water
*
* Given n non-negative integers representing an elevation map where the width of each bar is 1,
* compute how much water it is able to trap after raining.
*/
class TrappingRainWater {
private val trap = ::trap_with_lookback
@Test fun `some examples`() {
trap(listOf(0)) shouldEqual 0
trap(listOf(1)) shouldEqual 0
trap(listOf(1, 0)) shouldEqual 0
trap(listOf(0, 1)) shouldEqual 0
trap(listOf(1, 1)) shouldEqual 0
trap(listOf(0, 1, 1)) shouldEqual 0
trap(listOf(1, 1, 0)) shouldEqual 0
trap(listOf(1, 0, 1)) shouldEqual 1
trap(listOf(1, 2, 0)) shouldEqual 0
trap(listOf(0, 2, 1)) shouldEqual 0
trap(listOf(1, 0, 2)) shouldEqual 1
trap(listOf(2, 0, 1)) shouldEqual 1
trap(listOf(2, 0, 2)) shouldEqual 2
trap(listOf(2, 0, 0, 1)) shouldEqual 2
trap(listOf(1, 0, 0, 2)) shouldEqual 2
trap(listOf(2, 0, 0, 2)) shouldEqual 4
trap(listOf(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) shouldEqual 6
}
}
private fun trap_with_lookback(elevationMap: List<Int>): Int {
val prevIndexByHeight = TreeMap<Int, Int>()
return elevationMap.indices.zip(elevationMap).sumBy { (index, wallHeight) ->
(1..wallHeight).sumBy { height ->
val prevIndex = prevIndexByHeight.ceilingEntry(height)?.value ?: index - 1
(index - prevIndex - 1).also {
prevIndexByHeight[height] = index
}
}
}
}
private fun trap_with_lookahead(elevationMap: List<Int>): Int {
fun volumeTillNextWall(fromIndex: Int, height: Int): Int {
val volume = elevationMap.subList(fromIndex + 1, elevationMap.size).takeWhile { it < height }.size
val doesNotSpillFromRight = volume < elevationMap.size - (fromIndex + 1)
return if (doesNotSpillFromRight) volume else 0
}
return elevationMap.indices.zip(elevationMap).sumBy { (index, wallHeight) ->
(1..wallHeight).sumBy { height ->
volumeTillNextWall(index, height)
}
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,220 | katas | The Unlicense |
src/test/kotlin/be/brammeerten/y2022/Day12Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2022
import be.brammeerten.Co
import be.brammeerten.readFile
import be.brammeerten.toAlphabetIndex
import be.brammeerten.toCharList
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.util.LinkedList
class Day12Test {
@Test
fun `part 1a`() {
val map = readMap("2022/day12/exampleInput.txt")
val bestPath = map.solveBreadthFirst()
Assertions.assertEquals(31, bestPath!!.size-1)
}
@Test
fun `part 1b`() {
val map = readMap("2022/day12/input.txt")
val bestPath = map.solveBreadthFirst()
Assertions.assertEquals(330, bestPath!!.size-1)
}
@Test
fun `part 2a`() {
val map = readMap("2022/day12/exampleInput.txt")
val shortest = map.findLeastStepsFromLowestPoints()
Assertions.assertEquals(29, shortest)
}
@Test
fun `part 2b`() {
val map = readMap("2022/day12/input.txt")
val shortest = map.findLeastStepsFromLowestPoints()
Assertions.assertEquals(321, shortest)
}
fun readMap(file: String): MMap {
var start: Co? = null
var end: Co? = null
val map = readFile(file).mapIndexed { rowI, row ->
row.toCharList().mapIndexed { colI, col ->
when (col) {
'S' -> {
start = Co(rowI, colI)
'a'.toAlphabetIndex()
}
'E' -> {
end = Co(rowI, colI)
'z'.toAlphabetIndex()
}
else -> col.toAlphabetIndex()
}
}
}
return MMap(map, start!!, end!!)
}
data class MMap(val map: List<List<Int>>, val start: Co, val end: Co) {
val w = map[0].size
val h = map.size
fun getBestPath(): List<Co> {
return getBestPathBrute(start, emptyList())!!
}
fun findLeastStepsFromLowestPoints(): Int {
val x: List<Int> = map.mapIndexed {rowI, row ->
row.mapIndexed{colI, col ->
if (col == 'a'.toAlphabetIndex()) {
val solution = solveBreadthFirst(rowI * w + colI)
if (solution != null)
solution.size - 1
else null
} else null
}
}.flatten().filterNotNull()
return x.min()
}
fun solveBreadthFirst(startI: Int = start.row*w + start.col): List<Int>? {
val graph = toGraph()
val queue = LinkedList<Int>()
val visited = HashSet<Int>()
val prevs = Array<Int?>(w*h){null}
queue.add(startI)
visited.add(startI)
while(!queue.isEmpty()) {
val node = queue.remove()
for (neighbour in graph.nodes[node].neighbours) {
if (!visited.contains(neighbour)) {
queue.add(neighbour)
visited.add(neighbour)
prevs[neighbour] = node
}
}
}
// get path
val endI = end.row*w + end.col
val path = ArrayList<Int>()
var i: Int? = endI
while (i != startI && i != null) {
path.add(i)
i = prevs[i]
}
if (i == null) return null
path.add(i)
return path
}
fun toGraph(): Graph {
val graph = Graph(Array(w*h) { i -> Node(emptyList()) }) // forEaches kunnen eigenlijk hier
map.forEachIndexed{rowI, row ->
row.forEachIndexed{colI, col ->
val nodeI = rowI * w + colI
val node = Node(getNeighbours(Co(rowI, colI)).map { c -> c.row*w+c.col })
graph.nodes[nodeI] = node
}
}
return graph
}
fun getBestPathBrute(pos: Co, path: List<Co>): List<Co>? {
val options = getOptions(pos, path)
if (options.isEmpty() && pos != end)
return null
else {
val newPath = ArrayList(path)
newPath.add(pos)
if (pos == end)
return newPath
var bestSolution: List<Co>? = null
for (option in options) {
val solution = getBestPathBrute(option, newPath)
if (solution != null && (bestSolution == null || bestSolution.size > solution.size))
bestSolution = solution
}
return bestSolution
}
}
fun getOptions(pos: Co, path: List<Co>): List<Co> {
val directions = listOf(Co(-1, 0), Co(1, 0), Co(0, -1), Co(0, 1))
return directions
.map { pos + it }
.filter { it.row >= 0 && it.col >= 0 }
.filter { it.row < map.size && it.col < map[it.row].size }
.filter { newCo ->
map[newCo.row][newCo.col] - 1 <= map[pos.row][pos.col] && !path.contains(newCo)
}
}
fun getNeighbours(pos: Co): List<Co> {
val directions = listOf(Co(-1, 0), Co(1, 0), Co(0, -1), Co(0, 1))
return directions
.map { pos + it }
.filter { it.row >= 0 && it.col >= 0 }
.filter { it.row < map.size && it.col < map[it.row].size }
.filter { newCo -> map[newCo.row][newCo.col] - 1 <= map[pos.row][pos.col] }
}
fun print() {
map.forEach { row ->
row.forEach { print((it + 'a'.toByte().toInt()).toChar()) }
println()
}
}
}
data class Graph(val nodes: Array<Node>)
data class Node(val neighbours: List<Int>)
} | 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 6,011 | Advent-of-Code | MIT License |
src/day23/Day23.kt | gautemo | 317,316,447 | false | null | package day23
fun crabCupGame(cupsInput: List<Int>, moves: Int = 100): Map<Int, Cup>{
val max = cupsInput.max()!!
var current = Cup(cupsInput[0], null)
var last = current
val mapByLabel = mutableMapOf<Int, Cup>()
mapByLabel[current.label] = current
for(label in cupsInput){
if(current.label == label) continue
val cup = Cup(label, null)
last.next = cup
last = cup
mapByLabel[label] = cup
}
last.next = current
fun findDestination(currentLabel: Int, exclude: List<Int>): Cup{
var toLabel = currentLabel
do {
toLabel--
if(toLabel <= 0) toLabel = max
}while (exclude.contains(toLabel))
return mapByLabel[toLabel]!!
}
repeat(moves){
val take1 = current.next
val take2 = take1.next
val take3 = take2.next
current.next = take3.next
val dest = findDestination(current.label, listOf(take1.label, take2.label, take3.label))
take3.next = dest.next
dest.next = take1
current = current.next
}
return mapByLabel
}
fun getCupGameChainAfter1(input: String): String{
val map = crabCupGame(input.map { it.toString().toInt() })
var result = ""
var check = map[1]?.next ?: error("game lost cup labeled 1")
while(check.label != 1){
result += check.label
check = check.next
}
return result
}
fun getStarsCupGame(input: String): Long{
val cups = millionCups(input)
val map = crabCupGame(cups, 10_000_000)
val one = map[1] ?: error("game lost cup labeled 1")
return one.next.label.toLong() * one.next.next.label.toLong()
}
fun millionCups(input: String): List<Int>{
val list = input.map { it.toString().toInt() }.toMutableList()
for(i in input.length + 1..1_000_000){
list.add(i)
}
return list
}
class Cup(val label: Int, next: Cup?){
var next = next ?: this
}
fun main(){
val input = "962713854"
val result = getCupGameChainAfter1(input)
println(result)
val stars = getStarsCupGame(input)
println(stars)
} | 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 2,107 | AdventOfCode2020 | MIT License |
src/twentythree/Day01.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentythree
fun main() {
val day = "01"
// test if implementation meets criteria from the description:
println("Day$day Test Answers:")
val testInput = readInputLines("Day${day}_test_part1")
val part1 = part1(testInput)
part1.println()
check(part1 == 142)
val testPart2Input = readInputLines("Day${day}_test_part2")
val part2 = part2(testPart2Input)
part2.println()
check(part2 == 281)
println("---")
println("Solutions:")
val input = readInputLines("Day${day}_input")
part1(input).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val output = input.map { line ->
val firstNumber = line.first { it.isDigit() }
val lastNumber = line.last { it.isDigit() }
"$firstNumber$lastNumber".toInt()
}
output.sum()
var answer = 0
output.forEach { answer += it }
return output.sum()
}
private fun part2(input: List<String>): Int {
val output = input.map {
val firstNumber = it.startNumber()
val lastNumber = it.endNumber()
val out = "$firstNumber$lastNumber".toInt()
out
}
var answer = 0
output.forEach { answer += it }
return output.sum()
}
fun String.startNumber(): String {
if (this.first().isDigit()) return this.first().toString()
return when {
this.startsWith("one") -> "1"
this.startsWith("two") -> "2"
this.startsWith("three") -> "3"
this.startsWith("four") -> "4"
this.startsWith("five") -> "5"
this.startsWith("six") -> "6"
this.startsWith("seven") -> "7"
this.startsWith("eight") -> "8"
this.startsWith("nine") -> "9"
else -> this.drop(1).startNumber()
}
}
fun String.endNumber(): String {
if (this.last().isDigit()) return this.last().toString()
return when {
this.endsWith("one") -> "1"
this.endsWith("two") -> "2"
this.endsWith("three") -> "3"
this.endsWith("four") -> "4"
this.endsWith("five") -> "5"
this.endsWith("six") -> "6"
this.endsWith("seven") -> "7"
this.endsWith("eight") -> "8"
this.endsWith("nine") -> "9"
else -> this.dropLast(1).endNumber()
}
}
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 2,257 | advent-of-code-solutions | Apache License 2.0 |
src/main/kotlin/week3/BeaconExclusion.kt | waikontse | 572,850,856 | false | {"Kotlin": 63258} | package week3
import shared.Puzzle
import week2.Point
import java.math.BigInteger
import kotlin.math.abs
data class SensorBeacon(
val sensorX: Int,
val sensorY: Int,
val beaconX: Int,
val beaconY: Int
) {
val manhattanDistance = abs(sensorX - beaconX) + abs(sensorY - beaconY)
// Return set of X positions for sweeps on Y
fun getSweepsOnY(y: Int): Set<Int> {
// return empty set when sweep does not reach Y
val distanceToY = abs(sensorY - y)
if (manhattanDistance < distanceToY) {
return setOf()
}
// Generate the list of X coordinates for the Y coordinate sweep
val manhattanDistanceDiff = abs(manhattanDistance - distanceToY)
val numberOfXs = manhattanDistanceDiff * 2 + 1
return (sensorX - numberOfXs / 2..sensorX + numberOfXs / 2).toSet()
}
fun pointIsInRange(point: Point): Boolean {
return (abs(sensorX - point.first) + abs(sensorY - point.second)) <= manhattanDistance
}
fun generatePerimeter(manhattanDistance: Int): Set<Point> {
// Generate the
val perimeterPoints = mutableSetOf<Point>()
for (i in 0..manhattanDistance) {
// generate upper part
// left
addPositivePoint(perimeterPoints, Point(sensorX - (manhattanDistance - i), sensorY - i))
// right
addPositivePoint(perimeterPoints, Point(sensorX + (manhattanDistance - i), sensorY - i))
// generate lower part
// right
addPositivePoint(perimeterPoints, Point(sensorX - (manhattanDistance - i), sensorY + i))
// left
addPositivePoint(perimeterPoints, Point(sensorX + (manhattanDistance - i), sensorY + i))
}
return perimeterPoints
}
private fun addPositivePoint(perimeterPoints: MutableSet<Point>, elem: Point) {
if (elem.first < 0 || elem.second < 0) {
return
}
val upperLimit = 4000000
if (elem.first > upperLimit) {
return
}
if (elem.second > upperLimit) {
return
}
perimeterPoints.add(elem)
}
}
class BeaconExclusion : Puzzle(15) {
override fun solveFirstPart(): Any {
val ySweep = 2000000
val parsedSensorBeacon = puzzleInput
.map { parseSensorLine(it) }
val sweepOnY = parsedSensorBeacon
.map { it.getSweepsOnY(ySweep) }
.reduce { acc, ints -> acc + ints }
val beaconsOnY = parsedSensorBeacon.filter { it.beaconY == ySweep }
.map { it.beaconX }
.toSet()
return (sweepOnY - beaconsOnY).count()
}
override fun solveSecondPart(): Any {
val parsedSensorBeacon = puzzleInput
.map { parseSensorLine(it) }
val allPerimetersPoints = parsedSensorBeacon
.map { it.generatePerimeter(it.manhattanDistance + 1) }
.sortedByDescending { it.size }
var pointOfDistressSignal: Point = Point(0, 0)
var hasFoundDistressSignal = 0
loopOuter@ for (points in allPerimetersPoints) {
for (p in points) {
for (sensor in parsedSensorBeacon) {
if (!sensor.pointIsInRange(p)) {
hasFoundDistressSignal += 1
}
}
if (hasFoundDistressSignal == parsedSensorBeacon.size) {
pointOfDistressSignal = p
break@loopOuter
}
hasFoundDistressSignal = 0
}
}
val multiplier = BigInteger.valueOf(4000000L)
return pointOfDistressSignal.first.toBigInteger().multiply(multiplier).plus(pointOfDistressSignal.second.toBigInteger())
}
val sensorLineRegex = """Sensor at x=(\p{Graph}+), y=(\p{Graph}+): closest beacon is at x=(\p{Graph}+), y=(\p{Graph}+)""".toRegex()
private fun parseSensorLine(rawPosition: String): SensorBeacon {
val (sensorX, sensorY, beaconX, beaconY) = sensorLineRegex.matchEntire(rawPosition)
?.destructured
?: throw IllegalArgumentException(rawPosition)
return SensorBeacon(sensorX.toInt(), sensorY.toInt(), beaconX.toInt(), beaconY.toInt())
}
}
| 0 | Kotlin | 0 | 0 | 860792f79b59aedda19fb0360f9ce05a076b61fe | 4,286 | aoc-2022-in-kotllin | Creative Commons Zero v1.0 Universal |
src/main/kotlin/name/valery1707/problem/leet/code/IntegerToRomanK.kt | valery1707 | 541,970,894 | false | null | package name.valery1707.problem.leet.code
/**
* # 12. Integer to Roman
*
* Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
*
* | Symbol | Value |
* |--------|-------|
* | `I` | `1` |
* | `V` | `5` |
* | `X` | `10` |
* | `L` | `50` |
* | `C` | `100` |
* | `D` | `500` |
* | `M` | `1000` |
*
* For example, `2` is written as `II` in Roman numeral, just two ones added together.
* `12` is written as `XII`, which is simply `X + II`.
* The number `27` is written as `XXVII`, which is `XX + V + II`.
*
* Roman numerals are usually written largest to smallest from left to right.
* However, the numeral for four is not `IIII`.
* Instead, the number four is written as `IV`.
* Because the one is before the five we subtract it making four.
* The same principle applies to the number nine, which is written as `IX`.
* There are six instances where subtraction is used:
* * `I` can be placed before `V` (`5`) and `X` (`10`) to make `4` and `9`.
* * `X` can be placed before `L` (`50`) and `C` (`100`) to make `40` and `90`.
* * `C` can be placed before `D` (`500`) and `M` (`1000`) to make `400` and `900`.
*
* Given an integer, convert it to a roman numeral.
*
* ### Constraints
* * `1 <= num <= 3999`
*
* <a href="https://leetcode.com/problems/integer-to-roman/">12. Integer to Roman</a>
*/
interface IntegerToRomanK {
fun intToRoman(num: Int): String
@Suppress("EnumEntryName", "unused")
enum class Implementation : IntegerToRomanK {
simple {
//Should be static
private val mapper = sortedMapOf(
Comparator.reverseOrder(),
1 to "I", 5 to "V", 10 to "X", 50 to "L", 100 to "C", 500 to "D", 1000 to "M",
4 to "IV", 9 to "IX", 40 to "XL", 90 to "XC", 400 to "CD", 900 to "CM",
)
override fun intToRoman(num: Int): String {
var v = num
val s = StringBuilder()
for ((int, roman) in mapper) {
while (v >= int) {
s.append(roman)
v -= int
}
}
return s.toString()
}
},
optimized {
//Should be static
private val mapper = sortedMapOf(
Comparator.reverseOrder(),
1 to "I", 5 to "V", 10 to "X", 50 to "L", 100 to "C", 500 to "D", 1000 to "M",
4 to "IV", 9 to "IX", 40 to "XL", 90 to "XC", 400 to "CD", 900 to "CM",
)
override fun intToRoman(num: Int): String {
var v = num
val s = StringBuilder()
for ((int, roman) in mapper) {
if (v >= int) {
s.append(roman.repeat(v / int))
v %= int
}
}
return s.toString()
}
},
arrays {
//Should be static
private val integers = intArrayOf(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
private val romans = arrayOf("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
override fun intToRoman(num: Int): String {
var v = num
var i = 0
val s = StringBuilder()
while (i < integers.size && v > 0) {
val int = integers[i]
if (v >= int) {
s.append(romans[i].repeat(v / int))
v %= int
}
i++
}
return s.toString()
}
},
}
}
| 3 | Kotlin | 0 | 0 | 76d175f36c7b968f3c674864f775257524f34414 | 3,748 | problem-solving | MIT License |
src/Day07.kt | yeung66 | 574,904,673 | false | {"Kotlin": 8143} | fun main() {
data class Directory(val path: String, var size: Int = 0, val children: MutableList<Directory> = mutableListOf())
class Path {
val levels = mutableListOf<String>()
fun toPath(): String {
return "/" + levels.joinToString("/")
}
fun genSub(sub: String): String {
levels.add(sub)
val ans = toPath()
levels.removeAt(levels.size - 1)
return ans
}
fun cd(path: String) {
when (path) {
".." -> levels.removeAt(levels.size - 1)
"/" -> levels.clear()
else -> levels.add(path)
}
}
}
val records = hashMapOf<String, Directory>()
fun parse(input: String) {
val lines = input.lines()
var i = 0
val curPath = Path()
while (i < lines.size) {
val command = lines[i].split(" ")
i++
if (command.size == 3) {
val (_, _, path) = command
curPath.cd(path)
} else {
val dir = Directory(curPath.toPath())
while (i < lines.size && !lines[i].startsWith("$")) {
if (lines[i].startsWith("dir")) {
val (_, path) = lines[i].split(" ")
val subdir = Directory(curPath.genSub(path))
dir.children.add(subdir)
} else {
val (size, _) = lines[i].split(" ")
dir.size += size.toInt()
}
i++
}
records[curPath.toPath()] = dir
}
}
}
val sizes = hashMapOf<String, Int>()
fun cntSize(path: String): Int {
if (sizes.containsKey(path)) {
return sizes[path]!!
}
val dir = records[path]!!
var size = dir.size
for (child in dir.children) {
size += cntSize(child.path)
}
sizes[path] = size
return size
}
fun part1(): Int {
var ans = 0
for (path in records.keys) {
val size = cntSize(path)
if (size <= 100000) {
ans += size
}
}
return ans
}
fun part2(): Int {
val total = sizes["/"]!!
val needReleased = 30000000 - (70000000 - total)
val sorted = sizes.toList().sortedBy { it.second }
var i = 0
while (i < sorted.size && sorted[i].second < needReleased) {
i++
}
return sorted[i].second
}
val input = readInput("7")
parse(input)
println(part1())
println(part2())
}
| 0 | Kotlin | 0 | 0 | 554217f83e81021229759bccc8b616a6b270902c | 2,735 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/fr/chezbazar/aoc21/day3/Day3.kt | chezbazar | 728,404,822 | false | {"Kotlin": 54427} | package fr.chezbazar.aoc21.day3
import fr.chezbazar.aoc21.computeFrom
import kotlin.math.pow
fun main() {
day3()
day3PartTwo()
}
fun day3() {
val ones = MutableList(12) {0}
val zeros = MutableList(12) {0}
computeFrom("day3/input.txt") {
it.forEachIndexed { index, c ->
when(c) {
'0' -> zeros[index]++
'1' -> ones[index]++
}
}
}
val binaryGammaRate = List(12) {index -> if (ones[index] > zeros[index]) 1 else 0 }
println()
val gammaRate = binaryGammaRate.binaryToNumber()
val epsilonRate = 4095 - gammaRate
println("$gammaRate * $epsilonRate = ${gammaRate * epsilonRate}")
}
fun day3PartTwo() {
val data = mutableListOf<String>()
computeFrom("day3/input.txt") {
data.add(it)
}
var oxygenGeneratorRating: List<String> = data
var co2ScrubberRating: List<String> = data
for (i in 0..<12) {
val sumOxy = oxygenGeneratorRating.sumOf { it[i].digitToInt() }
oxygenGeneratorRating = if (sumOxy >= oxygenGeneratorRating.size / 2.0) {
oxygenGeneratorRating.filter { it[i] == '1' }
} else {
oxygenGeneratorRating.filter { it[i] == '0' }
}
val sumCo = co2ScrubberRating.sumOf { it[i].digitToInt() }
co2ScrubberRating = if (sumCo >= co2ScrubberRating.size / 2.0 && co2ScrubberRating.size > 1) {
co2ScrubberRating.filter { it[i] == '0' }
} else if (co2ScrubberRating.size > 1) {
co2ScrubberRating.filter { it[i] == '1' }
} else {
co2ScrubberRating
}
}
val ogr = oxygenGeneratorRating[0].map { it.digitToInt() }.binaryToNumber()
val csr = co2ScrubberRating[0].map { it.digitToInt() }.binaryToNumber()
println("$ogr * $csr = ${ogr * csr}")
}
fun List<Int>.binaryToNumber() = this.reversed().reduceIndexed { index, acc, i -> acc + i * 2.0.pow(index).toInt() } | 0 | Kotlin | 0 | 0 | 223f19d3345ed7283f4e2671bda8ac094341061a | 1,943 | adventofcode | MIT License |
src/d17.main.kts | cjfuller | 317,725,797 | false | null | import java.io.File
import kotlin.math.min
import kotlin.math.max
data class Coord(val x: Int, val y: Int, val z: Int, val w: Int) {
fun isActiveNext3D(state: Set<Coord>): Boolean {
val neighbors = sequence {
(-1..1).map { xInc ->
(-1..1).map { yInc ->
(-1..1).map { zInc ->
if (xInc == 0 && yInc == 0 && zInc == 0) {
// pass
} else {
yield(Coord(x + xInc, y + yInc, z + zInc, w))
}
}
}
}
}.toList()
val activeNeighborCount = neighbors.filter { it in state }.count()
return ((this in state && activeNeighborCount == 2) || (activeNeighborCount == 3))
}
fun isActiveNext4D(state: Set<Coord>): Boolean {
val neighbors = sequence {
(-1..1).map { xInc ->
(-1..1).map { yInc ->
(-1..1).map { zInc ->
(-1..1).map { wInc ->
if (xInc == 0 && yInc == 0 && zInc == 0 && wInc == 0) {
// pass
} else {
yield(Coord(x + xInc, y + yInc, z + zInc, w + wInc))
}
}
}
}
}
}.toList()
val activeNeighborCount = neighbors.filter { it in state }.count()
return ((this in state && activeNeighborCount == 2) || (activeNeighborCount == 3))
}
}
val initialState = File("./data/d17.txt")
.readLines()
.withIndex()
.flatMap { (rIdx, r) ->
r.withIndex().mapNotNull { (cIdx, c) ->
if (c == '#') {
Coord(cIdx, rIdx, 0, 0)
} else {
null
}
}
}
fun nextState3D(currState: Set<Coord>): Set<Coord> {
val mins = currState.fold(Coord(-1, -1, -1, 0)) { acc, curr ->
val (ax, ay, az) = acc
val (cx, cy, cz) = curr
Coord(min(ax, cx - 1), min(ay, cy - 1), min(az, cz - 1), 0)
}
val maxes = currState.fold(Coord(1, 1, 1, 0)) { acc, curr ->
val (ax, ay, az) = acc
val (cx, cy, cz) = curr
Coord(max(ax, cx + 1), max(ay, cy + 1), max(az, cz + 1), 0)
}
val (mnX, mnY, mnZ) = mins
val (mxX, mxY, mxZ) = maxes
val nextState: MutableSet<Coord> = mutableSetOf()
(mnX..mxX).forEach { x ->
(mnY..mxY).forEach { y ->
(mnZ..mxZ).forEach { z ->
val c = Coord(x, y, z, 0)
if (c.isActiveNext3D(currState)) {
nextState.add(c)
}
}
}
}
return nextState
}
fun nextState4D(currState: Set<Coord>): Set<Coord> {
val mins = currState.fold(Coord(-1, -1, -1, -1)) { acc, curr ->
val (ax, ay, az, aw) = acc
val (cx, cy, cz, cw) = curr
Coord(min(ax, cx - 1), min(ay, cy - 1), min(az, cz - 1), min(aw, cw - 1))
}
val maxes = currState.fold(Coord(1, 1, 1, 1)) { acc, curr ->
val (ax, ay, az, aw) = acc
val (cx, cy, cz, cw) = curr
Coord(max(ax, cx + 1), max(ay, cy + 1), max(az, cz + 1), max(aw, cw + 1))
}
val (mnX, mnY, mnZ, mnW) = mins
val (mxX, mxY, mxZ, mxW) = maxes
val nextState: MutableSet<Coord> = mutableSetOf()
(mnX..mxX).forEach { x ->
(mnY..mxY).forEach { y ->
(mnZ..mxZ).forEach { z ->
(mnW..mxW).forEach { w ->
val c = Coord(x, y, z, w)
if (c.isActiveNext4D(currState)) {
nextState.add(c)
}
}
}
}
}
return nextState
}
println("Part 1:")
var state = initialState.toSet()
repeat(6) { state = nextState3D(state) }
println(state.size)
println("Part 2:")
state = initialState.toSet()
repeat(6) { state = nextState4D(state) }
println(state.size)
| 0 | Kotlin | 0 | 0 | c3812868da97838653048e63b4d9cb076af58a3b | 4,024 | adventofcode2020 | MIT License |
src/main/kotlin/com/hopkins/aoc/day11/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day11
import java.io.File
import kotlin.math.abs
const val debug = true
const val part = 2
/** Advent of Code 2023: Day 11 */
fun main() {
val lines: List<String> = File("input/input11.txt").readLines()
// Read the galaxies from file
var i = 0
val inputGalaxies: Set<Galaxy> =
lines.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == '#') {
Galaxy(i++, Point(x, y))
} else {
null
}
}}.toSet()
if (debug) {
println("Num Galaxies: ${inputGalaxies.count()}")
println("Input Galaxies: ${inputGalaxies.take(5)}")
}
// Find the empty rows/columns
val max = 140
val allList = (0..max).toList()
val emptyRows = allList.toMutableSet()
val emptyColumns = allList.toMutableSet()
inputGalaxies.forEach { galaxy ->
emptyRows.remove(galaxy.position.y)
emptyColumns.remove(galaxy.position.x)
}
if (debug) {
println("Empty rows: $emptyRows")
println("Empty columns: $emptyColumns")
}
// Calculate the actual galaxy positions
val factor = if (part == 1) { 2 } else { 1_000_000 }
val actualGalaxies =
inputGalaxies.map { input ->
val dx = emptyColumns.count { it < input.position.x } * (factor - 1)
val dy = emptyRows.count { it < input.position.y } * (factor - 1)
Galaxy(input.id, input.position.add(dx, dy))
}
if (debug) {
println("Actual Galaxies: ${actualGalaxies.take(5)}")
}
// Find the pairs of galaxies
val allPairs = actualGalaxies.flatMapIndexed { index, g1 ->
actualGalaxies.drop(index + 1).map { g2 -> g1 to g2 }}
if (debug) {
println("Num pairs: ${allPairs.count()}")
}
// Find the distance between pairs of points
val distanceSum = allPairs.sumOf {
it.first.position.walkDistance(it.second.position).toLong()
}
println("Distance Sum: $distanceSum") // 857986849428
}
data class Galaxy(val id: Int, val position: Point)
data class Point(val x: Int, val y: Int) {
fun add(dx: Int, dy: Int) = Point(x + dx, y + dy)
fun add(other: Point): Point = add(other.x, other.y)
fun walkDistance(other: Point): Int =
abs(x - other.x) + abs(y - other.y)
}
| 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 2,379 | aoc2023 | MIT License |
src/Day10.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | private sealed interface CpuInstruction {
val cycles: Int
object Noop : CpuInstruction {
override val cycles = 1
}
data class AddX(val value: Int) : CpuInstruction {
override val cycles = 2
}
}
private data class RegisterState(val x: Int)
private class CpuSimulator {
private var state = RegisterState(x = 1)
val histogram = mutableListOf(state)
fun execute(instruction: CpuInstruction) {
repeat(instruction.cycles) {
histogram.add(state)
}
// Mutate State
state = when (instruction) {
CpuInstruction.Noop -> state
is CpuInstruction.AddX -> state.copy(x = state.x + instruction.value)
}
}
}
private const val crtLineLength = 40
private class CrtSimulator {
fun print(cycle: Int, state: RegisterState) {
val spritePosition = (state.x - 1)..(state.x + 1)
val cursorPosition = (cycle - 1) % crtLineLength
if (cursorPosition in spritePosition) {
print('#')
} else {
print('.')
}
if (cursorPosition == crtLineLength - 1) {
println()
}
}
}
fun main() {
fun String.toCpuInstruction(): CpuInstruction {
val instruction = takeWhile { it != ' ' }
val argument = takeLastWhile { it != ' ' }
return when (instruction) {
"noop" -> CpuInstruction.Noop
"addx" -> CpuInstruction.AddX(argument.toInt())
else -> error("Couldn't parse $instruction")
}
}
fun part1(input: List<String>): Int {
val instruction = input.map { it.toCpuInstruction() }
val simulator = CpuSimulator()
instruction.forEach { simulator.execute(it) }
var signalStrength = 0
for (i in 20 until simulator.histogram.size step 40) {
signalStrength += simulator.histogram[i].x * i
}
return signalStrength
}
fun part2(input: List<String>) {
val instruction = input.map { it.toCpuInstruction() }
val simulator = CpuSimulator()
instruction.forEach { simulator.execute(it) }
val crt = CrtSimulator()
simulator.histogram.forEachIndexed { index, registerState ->
if (index > 0)
crt.print(index, registerState)
}
}
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
part2(testInput)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 2,515 | advent-of-code-2022 | Apache License 2.0 |
adventofcode/src/main/kotlin/day4.kt | jmfayard | 71,764,270 | false | null | import io.kotlintest.specs.StringSpec
data class Room(val number: Int, val encryped: String, val checksum: String)
class Day4 : StringSpec() { init {
"Parsing" {
val room = "aaaaa-bbb-z-y-x-123[abxyz]".asRoom()
room shouldBe Room(123, "aaaaa-bbb-z-y-x", "abxyz")
}
"Calculing checksum" {
val room = "aaaaa-bbb-z-y-x-123[abxyz]".asRoom()
room.realChecksum() shouldBe room.checksum
}
val solution = 409147
"Finding correct checksums" {
val file = resourceFile("day4.txt")
val rooms = file.readLines().map(String::asRoom)
val realRooms = rooms.filter { room ->
room.checksum == room.realChecksum()
}
val count = realRooms.sumBy { it.number }
count shouldBe solution
}
"Ascii and cie" {
'a'.toIndex() shouldBe 0
'y'.rotate(3) shouldBe 'b'
'-'.rotate(3) shouldBe ' '
}
val solution2 = 991
"Decyphe => solution $solution2" {
val file = resourceFile("day4.txt")
val rooms = file.readLines().map(String::asRoom).filter { room ->
room.checksum == room.realChecksum()
}
rooms.forEachIndexed { i, r ->
"${r.decypher()} <=== $r".debug("#$i")
}
val result = rooms.find { r -> r.decypher().contains("northpole object storage") }
result!!.number shouldBe solution2
}
}
}
private fun String.asRoom(): Room {
require(all { c: Char -> c in allowedChars }) { "Invalid string $this" }
val startNumber = lastIndexOf("-")
val startChecksum = lastIndexOf("[")
val number = substring(startNumber + 1, startChecksum).toInt()
return Room(number, encryped = substring(0, startNumber), checksum = substring(startChecksum + 1, lastIndex))
}
private fun Room.decypher(): String = buildString {
encryped.forEach { c ->
append(c.rotate(number))
}
}
val letters = ('a'..'z')
private fun Char.rotate(number: Int) = when (this) {
'-' -> ' '
!in letters -> TODO("Invalid char $this")
else -> (toIndex() + number).mod(26).toLowerCase()
}
private fun Int.toLowerCase(): Char = (this + 'a'.toInt()).toChar()
private fun Char.toIndex(): Int = this.toInt() - 'a'.toInt()
fun Room.realChecksum(): String {
val occurences = mutableMapOf<Char, Int>()
encryped.forEach { c ->
if (c == '-') return@forEach
occurences[c] = 1 + (occurences[c] ?: 0)
}
val indices = ('a'..'z').sortedByDescending { c -> occurences[c] }.take(5)
return indices.asString()
}
private val allowedChars = ('0'..'9') + ('a'..'z') + listOf('[', ']', '-') | 0 | Kotlin | 0 | 1 | 9e92090aa50127a470653f726b80335133dec38b | 2,627 | httplayground | ISC License |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D17.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2020
import io.github.pshegger.aoc.common.BaseSolver
import io.github.pshegger.aoc.common.getCartesianProduct
class Y2020D17 : BaseSolver() {
override val year = 2020
override val day = 17
override fun part1(): Int = solve(false)
override fun part2(): Int = solve(true)
private fun solve(isPart2: Boolean, cycleCount: Int = 6) =
(1..cycleCount).fold(parseInput(isPart2)) { field, _ ->
field.simulateCycle()
}.aliveCount
private fun parseInput(isPart2: Boolean): Field = readInput {
readLines()
.flatMapIndexed { y: Int, line: String ->
line.mapIndexedNotNull { x, c ->
when {
c == '#' && isPart2 -> Coord4(x, y, 0, 0)
c == '#' -> Coord3(x, y, 0)
else -> null
}
}
}
.associateWith { true }
.let { Field(it) }
}
private data class Field(private val state: Map<Coord, Boolean>) {
val aliveCount: Int get() = state.count { it.value }
fun isAlive(c: Coord): Boolean = state[c] ?: false
fun aliveNeighborCount(c: Coord) = c.getNeighbors().count { isAlive(it) }
fun simulateCycle(): Field =
state
.filter { (_, alive) -> alive }
.flatMap { (c, _) -> c.getNeighbors() }
.toSet()
.associateWith { c ->
val nc = aliveNeighborCount(c)
when {
isAlive(c) && nc in 2..3 -> true
!isAlive(c) && nc == 3 -> true
else -> false
}
}
.let { Field(it) }
}
interface Coord {
fun getNeighbors(): List<Coord>
}
data class Coord3(val x: Int, val y: Int, val z: Int) : Coord {
override fun getNeighbors(): List<Coord> = neighborDiffs.map { diff ->
Coord3(x + diff.x, y + diff.y, z + diff.z)
}
companion object {
private val neighborDiffs: List<Coord3> =
(1..3).map { (-1..1) }
.getCartesianProduct()
.mapNotNull { diff ->
if (diff.all { it == 0 }) {
null
} else {
Coord3(diff[0], diff[1], diff[2])
}
}
}
}
data class Coord4(val x: Int, val y: Int, val z: Int, val w: Int) : Coord {
override fun getNeighbors(): List<Coord> = neighborDiffs.map { diff ->
Coord4(x + diff.x, y + diff.y, z + diff.z, w + diff.w)
}
companion object {
private val neighborDiffs: List<Coord4> =
(1..4).map { (-1..1) }
.getCartesianProduct()
.mapNotNull { diff ->
if (diff.all { it == 0 }) {
null
} else {
Coord4(diff[0], diff[1], diff[2], diff[3])
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 3,243 | advent-of-code | MIT License |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day24/Day24.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day24
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector3D
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 24](https://adventofcode.com/2020/day/24)
*/
object Day24 : DayOf2020(24) {
private val PATTERN = "(nw|ne|w|e|sw|se)".toRegex()
private val DIRS = mapOf(
"nw" to Vector3D(0, 1, -1),
"ne" to Vector3D(1, 0, -1),
"w" to Vector3D(-1, 1, 0),
"e" to Vector3D(1, -1, 0),
"sw" to Vector3D(-1, 0, 1),
"se" to Vector3D(0, -1, 1),
)
override fun first(): Any? {
val items = lines
.map { line ->
PATTERN.findAll(line).map { it.groupValues[1] }.toList()
}
val tiles = items.map { steps ->
steps.fold(Vector3D()) { acc, value -> acc + DIRS.getValue(value) }
}
return tiles.groupBy { it }.count { it.value.size % 2 == 1 }
}
override fun second(): Any? {
val items = lines
.map { line ->
PATTERN.findAll(line).map { it.groupValues[1] }.toList()
}
val start = items
.map { steps ->
steps.fold(Vector3D()) { acc, value -> acc + DIRS.getValue(value) }
}
.groupBy { it }
.filterValues { it.size % 2 == 1 }
.keys
val result = (0..<100).fold(start) { prev, _ ->
val neighbors = prev
.flatMap { cell -> DIRS.values.map { it + cell } }
.groupingBy { it }
.eachCount()
return@fold (prev.filter { neighbors[it] in 1..2 } + (neighbors.filterValues { it == 2 }.keys - prev)).toSet()
}
return result.size
}
}
fun main() = SomeDay.mainify(Day24)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,599 | adventofcode | MIT License |
2021/src/main/kotlin/Day3.kt | osipxd | 388,214,845 | false | null | /**
* # Day 3: Binary Diagnostic
*
* The submarine has been making some odd creaking noises, so you ask it
* to produce a diagnostic report just in case.
*
* The diagnostic report (your puzzle input) consists of a list of binary
* numbers which, when decoded properly, can tell you many useful things about
* the conditions of the submarine. The first parameter to check is the power
* consumption.
*
* You need to use the binary numbers in the diagnostic report to generate
* two new binary numbers (called the gamma rate and the epsilon rate).
* The power consumption can then be found by multiplying the gamma rate by
* the epsilon rate.
*
* Each bit in the gamma rate can be determined by finding the most common bit
* in the corresponding position of all numbers in the diagnostic report.
* For example, given the following diagnostic report:
* ```
* 00100
* 11110
* 10110
* 10111
* 10101
* 01111
* 00111
* 11100
* 10000
* 11001
* 00010
* 01010
* ```
* Considering only the first bit of each number, there are five 0 bits and
* seven 1 bits. Since the most common bit is 1, the first bit of the gamma
* rate is 1.
*
* The most common second bit of the numbers in the diagnostic report is 0,
* so the second bit of the gamma rate is 0.
*
* The most common value of the third, fourth, and fifth bits are 1, 1, and 0,
* respectively, and so the final three bits of the gamma rate are 110.
*
* So, the gamma rate is the binary number 10110, or 22 in decimal.
*
* The epsilon rate is calculated in a similar way; rather than use the most
* common bit, the least common bit from each position is used. So, the epsilon
* rate is 01001, or 9 in decimal. Multiplying the gamma rate (22) by
* the epsilon rate (9) produces the power consumption, 198.
*
* Use the binary numbers in your diagnostic report to calculate the gamma rate
* and epsilon rate, then multiply them together. What is the power consumption
* of the submarine? (Be sure to represent your answer in decimal, not binary.)
*/
object Day3 {
fun part1(diagnostic: List<String>): Int {
val lineLength = diagnostic.first().length
val counter = IntArray(lineLength, init = { 0 })
diagnostic.forEach { line ->
line.forEachIndexed { index, c -> counter[index] += c.digitToInt() }
}
val threshold = (diagnostic.size + 1) / 2
val gamma = buildString {
for (count in counter) append(if (count >= threshold) "1" else "0")
}
val epsilon = gamma.map {
when(it) {
'1' -> '0'
'0' -> '1'
else -> error("")
}
}.joinToString("")
return gamma.toInt(radix = 2) * epsilon.toInt(radix = 2)
}
}
| 0 | Kotlin | 0 | 0 | 66553923d8d221bcd1bd108f701fceb41f4d1cbf | 2,774 | advent-of-code | MIT License |
src/main/kotlin/com/github/shmvanhouten/adventofcode/day13/PathFinder.kt | SHMvanHouten | 109,886,692 | false | {"Kotlin": 616528} | package com.github.shmvanhouten.adventofcode.day13
import com.github.shmvanhouten.adventofcode.day22gridcomputing.Coordinate
class PathFinder {
private val SOURCE_COORDINATE = Coordinate(1, 1)
fun getPathsToVisitedNodes(maze: Maze): Set<Node> {
var visitedNodes = setOf<Node>()
var unvisitedNodes = setOf(Node(SOURCE_COORDINATE))
while (unvisitedNodes.isNotEmpty()) {
val currentNode = getLowestDistanceNode(unvisitedNodes)
unvisitedNodes -= currentNode
buildAdjacentNodes(currentNode, maze)
.forEach { adjacentNode ->
val possibleVisitedNode: Node? = visitedNodes.find { it == adjacentNode }
if (possibleVisitedNode != null) {
if (possibleVisitedNode.shortestPath.size > adjacentNode.shortestPath.size) {
visitedNodes -= possibleVisitedNode
unvisitedNodes += adjacentNode
}
} else {
unvisitedNodes += adjacentNode
}
}
visitedNodes = addCurrentNodeToVisitedNodeIfItHasTheShortestPath(visitedNodes, currentNode)
}
return visitedNodes
}
private fun addCurrentNodeToVisitedNodeIfItHasTheShortestPath(originalVisitedNodes: Set<Node>, currentNode: Node): Set<Node> {
var newVisitedNodes = originalVisitedNodes
val possibleVisitedNode: Node? = newVisitedNodes.find { it == currentNode }
if (possibleVisitedNode != null) {
if (possibleVisitedNode.shortestPath.size > currentNode.shortestPath.size) {
//todo: this should not happen since shortest route nodes get evaluated first
newVisitedNodes -= possibleVisitedNode
newVisitedNodes += currentNode
} // else keep the original visited node with the shorter path
} else {
newVisitedNodes += currentNode
}
return newVisitedNodes
}
private fun buildAdjacentNodes(originNode: Node, maze: Maze): List<Node> =
maze.getAdjacentCorridors(originNode.coordinate)
.map { Node(it, shortestPath = originNode.shortestPath.plus(it)) }
private fun getLowestDistanceNode(unvisitedNodes: Set<Node>): Node =
unvisitedNodes.minBy { it.shortestPath.size } ?: unvisitedNodes.first()
}
| 0 | Kotlin | 0 | 0 | a8abc74816edf7cd63aae81cb856feb776452786 | 2,420 | adventOfCode2016 | MIT License |
src/day22/Main.kt | nikwotton | 572,814,041 | false | {"Kotlin": 77320} | package day22
import day22.Direction.DOWN
import day22.Direction.LEFT
import day22.Direction.RIGHT
import day22.Direction.UP
import day22.Instruction.Move
import day22.Instruction.TURN_LEFT
import day22.Instruction.TURN_RIGHT
import java.io.File
val workingDir = "src/${object {}.javaClass.`package`.name}"
fun main() {
val sample = File("$workingDir/sample.txt")
val input1 = File("$workingDir/input_1.txt")
println("Step 1a: ${runStep1(sample)}") // 6032
println("Step 1b: ${runStep1(input1)}") // 196134
println("Step 2a: ${runStep2(sample)}") // 5031
println("Step 2b: ${runStep2(input1)}") // 146011
}
data class Point(val x: Int, val y: Int, val walkable: Boolean)
sealed class Instruction {
data class Move(val distance: Int) : Instruction()
object TURN_RIGHT : Instruction()
object TURN_LEFT : Instruction()
}
sealed class Direction {
object LEFT : Direction()
object RIGHT : Direction()
object UP : Direction()
object DOWN : Direction()
}
tailrec fun String.toInstructions(acc: List<Instruction> = emptyList()): List<Instruction> {
if (isEmpty()) return acc
return if (first().isDigit()) {
val num = takeWhile { it.isDigit() }.toInt()
removePrefix(num.toString()).toInstructions(acc + Move(num))
} else {
val d = first()
when (d) {
'R' -> removePrefix(d.toString()).toInstructions(acc + TURN_RIGHT)
'L' -> removePrefix(d.toString()).toInstructions(acc + TURN_LEFT)
else -> TODO()
}
}
}
fun runStep1(input: File): String {
val map = ArrayList<Point>()
input.readLines().dropLast(2).forEachIndexed { y, s ->
s.forEachIndexed { x, c ->
when (c) {
' ' -> Unit
'.' -> map.add(Point(x+1, y + 1, true))
'#' -> map.add(Point(x+1, y + 1, false))
}
}
}
val instructions = input.readLines().last().toInstructions()
var currentPosition = map.filter { it.y == 1 }.minBy { it.x }
var currentDirection: Direction = RIGHT
instructions.forEach {
when (it) {
is Move -> {
repeat(it.distance) {
currentPosition = when (currentDirection) {
DOWN -> {
val next = map.firstOrNull { it.x == currentPosition.x && it.y == currentPosition.y + 1 }
?: map.first { it.x == currentPosition.x && it.y == map.filter { it.x == currentPosition.x }.minOf { it.y } }
if (next.walkable) next
else currentPosition
}
LEFT -> {
val next = map.firstOrNull { it.x == currentPosition.x - 1 && it.y == currentPosition.y }
?: map.first { it.x == map.filter { it.y == currentPosition.y }.maxOf { it.x } && it.y == currentPosition.y }
if (next.walkable) next
else currentPosition
}
RIGHT -> {
val next = map.firstOrNull { it.x == currentPosition.x + 1 && it.y == currentPosition.y }
?: map.first { it.x == map.filter { it.y == currentPosition.y }.minOf { it.x } && it.y == currentPosition.y }
if (next.walkable) next
else currentPosition
}
UP -> {
val next = map.firstOrNull { it.x == currentPosition.x && it.y == currentPosition.y - 1 }
?: map.first { it.x == currentPosition.x && it.y == map.filter { it.x == currentPosition.x }.maxOf { it.y } }
if (next.walkable) next
else currentPosition
}
}
}
}
TURN_LEFT -> currentDirection = when (currentDirection) {
DOWN -> RIGHT
LEFT -> DOWN
RIGHT -> UP
UP -> LEFT
}
TURN_RIGHT -> currentDirection = when (currentDirection) {
DOWN -> LEFT
LEFT -> UP
RIGHT -> DOWN
UP -> RIGHT
}
}
}
return ((currentPosition.y * 1000) + (currentPosition.x * 4) + when(currentDirection) {
LEFT -> 2
RIGHT -> 0
UP -> 3
DOWN -> 1
}).toString()
}
fun runStep2(input: File): String {
val map = ArrayList<Point>()
input.readLines().dropLast(2).forEachIndexed { y, s ->
s.forEachIndexed { x, c ->
when (c) {
' ' -> Unit
'.' -> map.add(Point(x+1, y + 1, true))
'#' -> map.add(Point(x+1, y + 1, false))
}
}
}
val instructions = input.readLines().last().toInstructions()
var currentPosition = map.filter { it.y == 1 }.minBy { it.x }
var currentDirection: Direction = RIGHT
fun wrapLeft(): Point =
if (input.name == "sample.txt") {
when (currentPosition.y) {
in 1..4 -> {
val next = map.first { it.x == 4 + currentPosition.y && it.y == 5 }
if (next.walkable) currentDirection = DOWN
next
}
in 5..8 -> TODO()
in 9..12 -> TODO()
else -> TODO()
}
} else {
when (currentPosition.y) {
in 1..50 -> {
val next = map.first { it.x == 1 && it.y == 151 - currentPosition.y }
if (next.walkable) currentDirection = RIGHT
next
}
in 51..100 -> {
val next = map.first { it.x == currentPosition.y-50 && it.y == 101 }
if (next.walkable) currentDirection = DOWN
next
}
in 101..150 -> {
val next = map.first { it.x == 51 && it.y == 151-currentPosition.y }
if (next.walkable) currentDirection = RIGHT
next
}
in 151..200 -> {
val next = map.first { it.x == currentPosition.y-100 && it.y == 1 }
if (next.walkable) currentDirection = DOWN
next
}
else -> TODO()
}
}
fun wrapRight(): Point =
if (input.name == "sample.txt") {
when (currentPosition.y) {
in 1..4 -> {
TODO()
}
in 5..8 -> {
val next = map.first { it.x == (9 - currentPosition.y) + 12 && it.y == 9 }
if (next.walkable) currentDirection = DOWN
next
}
in 9..12 -> TODO()
else -> TODO()
}
} else {
when (currentPosition.y) {
in 1..50 -> {
val next = map.first { it.x == 100 && it.y == 151-currentPosition.y }
if (next.walkable) currentDirection = LEFT
next
}
in 51..100 -> {
val next = map.first { it.x == 50 + currentPosition.y && it.y == 50 }
if (next.walkable) currentDirection = UP
next
}
in 101..150 -> {
val next = map.first { it.x == 150 && it.y == 151-currentPosition.y }
if (next.walkable) currentDirection = LEFT
next
}
in 151..200 -> {
val next = map.first { it.x == currentPosition.y-100 && it.y == 150 }
if (next.walkable) currentDirection = UP
next
}
else -> TODO()
}
}
fun wrapUp(): Point =
if (input.name == "sample.txt") {
when (currentPosition.x) {
in 1..4 -> {
TODO()
}
in 5..8 -> {
val next = map.first { it.x == 9 && it.y == currentPosition.x-4 }
if (next.walkable) currentDirection = RIGHT
next
}
in 9..12 -> TODO()
in 13..16 -> TODO()
else -> TODO()
}
} else {
when (currentPosition.x) {
in 1..50 -> {
val next = map.first { it.x == 51 && it.y == currentPosition.x+50 }
if (next.walkable) currentDirection = RIGHT
next
}
in 51..100 -> {
val next = map.first { it.x == 1 && it.y == 100 + currentPosition.x }
if (next.walkable) currentDirection = RIGHT
next
}
in 101..150 -> {
val next = map.first { it.x == currentPosition.x-100 && it.y == 200 }
if (next.walkable) currentDirection = UP
next
}
else -> TODO()
}
}
fun wrapDown(): Point =
if (input.name == "sample.txt") {
when (currentPosition.x) {
in 1..4 -> {
TODO()
}
in 5..8 -> TODO()
in 9..12 -> {
val next = map.first { it.x == (13-currentPosition.x) && it.y == 8 }
if (next.walkable) currentDirection = UP
next
}
in 13..16 -> TODO()
else -> TODO()
}
} else {
when (currentPosition.x) {
in 1..50 -> {
val next = map.first { it.x == currentPosition.x+100 && it.y == 1 }
if (next.walkable) currentDirection = DOWN
next
}
in 51..100 -> {
val next = map.first { it.x == 50 && it.y == 100 + currentPosition.x }
if (next.walkable) currentDirection = LEFT
next
}
in 101..150 -> {
val next = map.first { it.x == 100 && it.y == currentPosition.x-50 }
if (next.walkable) currentDirection = LEFT
next
}
else -> TODO()
}
}
instructions.forEachIndexed { index, it ->
when (it) {
is Move -> {
repeat(it.distance) {
currentPosition = when (currentDirection) {
DOWN -> {
val next = map.firstOrNull { it.x == currentPosition.x && it.y == currentPosition.y + 1 }
?: wrapDown()
if (next.walkable) next
else currentPosition
}
LEFT -> {
val next = map.firstOrNull { it.x == currentPosition.x - 1 && it.y == currentPosition.y }
?: wrapLeft()
if (next.walkable) next
else currentPosition
}
RIGHT -> {
val next = map.firstOrNull { it.x == currentPosition.x + 1 && it.y == currentPosition.y }
?: wrapRight()
if (next.walkable) next
else currentPosition
}
UP -> {
val next = map.firstOrNull { it.x == currentPosition.x && it.y == currentPosition.y - 1 }
?: wrapUp()
if (next.walkable) next
else currentPosition
}
}
}
}
TURN_LEFT -> currentDirection = when (currentDirection) {
DOWN -> RIGHT
LEFT -> DOWN
RIGHT -> UP
UP -> LEFT
}
TURN_RIGHT -> currentDirection = when (currentDirection) {
DOWN -> LEFT
LEFT -> UP
RIGHT -> DOWN
UP -> RIGHT
}
}
}
return ((currentPosition.y * 1000) + (currentPosition.x * 4) + when(currentDirection) {
LEFT -> 2
RIGHT -> 0
UP -> 3
DOWN -> 1
}).toString()
}
| 0 | Kotlin | 0 | 0 | dee6a1c34bfe3530ae6a8417db85ac590af16909 | 12,864 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code2015/src/main/kotlin/day19/Advent19.kt | REDNBLACK | 128,669,137 | false | null | package day19
import indexOfAll
import parseInput
import splitToLines
/**
--- Day 19: Medicine for Rudolph ---
Rudolph the Red-Nosed Reindeer is sick! His nose isn't shining very brightly, and he needs medicine.
Red-Nosed Reindeer biology isn't similar to regular reindeer biology; Rudolph is going to need custom-made medicine. Unfortunately, Red-Nosed Reindeer chemistry isn't similar to regular reindeer chemistry, either.
The North Pole is equipped with a Red-Nosed Reindeer nuclear fusion/fission plant, capable of constructing any Red-Nosed Reindeer molecule you need. It works by starting with some input molecule and then doing a series of replacements, one per step, until it has the right molecule.
However, the machine has to be calibrated before it can be used. Calibration involves determining the number of molecules that can be generated in one step from a given starting point.
For example, imagine a simpler machine that supports only the following replacements:
H => HO
H => OH
O => HH
Given the replacements above and starting with HOH, the following molecules could be generated:
HOOH (via H => HO on the first H).
HOHO (via H => HO on the second H).
OHOH (via H => OH on the first H).
HOOH (via H => OH on the second H).
HHHH (via O => HH).
So, in the example above, there are 4 distinct molecules (not five, because HOOH appears twice) after one replacement from HOH. Santa's favorite molecule, HOHOHO, can become 7 distinct molecules (over nine replacements: six from H, and three from O).
The machine replaces without regard for the surrounding characters. For example, given the string H2O, the transition H => OO would result in OO2O.
Your puzzle input describes all of the possible replacements and, at the bottom, the medicine molecule for which you need to calibrate the machine. How many distinct molecules can be created after all the different ways you can do one replacement on the medicine molecule?
--- Part Two ---
Now that the machine is calibrated, you're ready to begin molecule fabrication.
Molecule fabrication always begins with just a single electron, e, and applying replacements one at a time, just like the ones during calibration.
For example, suppose you have the following replacements:
e => H
e => O
H => HO
H => OH
O => HH
If you'd like to make HOH, you start with e, and then make the following replacements:
e => O to get O
O => HH to get HH
H => OH (on the second H) to get HOH
So, you could make HOH after 3 steps. Santa's favorite molecule, HOHOHO, can be made in 6 steps.
How long will it take to make the medicine? Given the available replacements and the medicine molecule in your puzzle input, what is the fewest number of steps to go from e to the medicine molecule?
*/
fun main(args: Array<String>) {
val testMolecule = "HOH"
val testReplacements = """
|H => HO
|H => OH
|O => HH
""".trimMargin()
println(countPossibleMoleculesTransform(testMolecule, testReplacements) == 4)
println(countFewestNumberOfTransformations(testMolecule, testReplacements) == 6)
val inputMolecule = parseInput("day19-input-1.txt")
val inputReplacements = parseInput("day19-input-2.txt")
println(countPossibleMoleculesTransform(inputMolecule, inputReplacements))
println(countFewestNumberOfTransformations(inputMolecule, inputReplacements))
}
data class Replacement(val from: String, val to: String)
fun countPossibleMoleculesTransform(molecule: String, replacements: String): Int {
return parseReplacements(replacements)
.flatMap { r ->
molecule.indexOfAll(r.from).map { i -> molecule.replaceRange(i, i + r.from.length, r.to) }
}
.distinct()
.count()
}
fun countFewestNumberOfTransformations(molecule: String, replacementsInput: String): Int {
val replacements = parseReplacements(replacementsInput, true)
val regex = Regex(replacements.map { it.from }.joinToString("|"))
var result = 0
var target = molecule.reversed()
while (target != "e") {
target = regex.replace(target, { r -> result++; replacements.first { it.from == r.value }.to }).trim()
}
return result
}
private fun parseReplacements(input: String, reversed: Boolean = false) = input.splitToLines()
.map {
with (it.split(" => ")) {
if (!reversed) Replacement(first(), last())
else Replacement(last().reversed(), first().reversed())
}
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 4,580 | courses | MIT License |
src/main/kotlin/dev/kosmx/aoc23/stars/StarField.kt | KosmX | 726,056,762 | false | {"Kotlin": 32011} | package dev.kosmx.aoc23.stars
import java.io.File
import java.math.BigInteger
import kotlin.math.abs
operator fun MutableList<MutableList<Char>>.get(x: Int, y: Int): Char {
return this[y][x]
}
fun <T> List<T>.allPairings() = sequence {
for (a in indices) {
for (b in a + 1 ..< size) {
yield(get(a) to get(b))
}
}
}
fun main() {
val starMap = File("stars.txt").useLines {
it.map { it.toCharArray().toMutableList() }.toMutableList()
}
// insert rows
for (x in starMap.indices.reversed()) {
if (starMap.all { it[x] == '.' }) {
starMap.forEach {
it.add(x, '+')
}
}
}
// insert columns
for (y in starMap.indices.reversed()) {
if (starMap[y].all { it == '.' || it == '+' }) {
starMap.add(y, MutableList(starMap[y].size) { '+' })
}
}
// print map for debug
//*
starMap.forEach {
println(it.joinToString(""))
}// */
// collect stars
val stars = mutableListOf<Pair<Int, Int>>()
for (y in starMap.indices) {
for (x in starMap[y].indices) {
if (starMap[x, y] == '#') {
stars.add(x to y)
}
}
}
val distances = stars.allPairings().map { (a, b) ->
abs(a.first - b.first) + abs(a.second - b.second)
}.toList()
println(distances.fold(BigInteger.ZERO) { acc, i -> acc + i.toBigInteger() })
// now part 2
val distances2 = stars.allPairings().map { (a, b) ->
var holes = 0
for (i in a.first progress b.first) {
if (starMap[i, a.second] == '+') {
holes++
}
}
for (i in a.second progress b.second) {
if (starMap[b.first, i] == '+') {
holes++
}
}
abs(a.first - b.first) + abs(a.second - b.second) + (holes*(1000000-2))
}.toList()
println(distances2.fold(BigInteger.ZERO) { acc, i -> acc + i.toBigInteger() })
}
private infix fun Int.progress(first: Int): IntProgression {
return if (this < first) {
first downTo this
} else {
first..this
}
}
| 0 | Kotlin | 0 | 0 | ad01ab8e9b8782d15928a7475bbbc5f69b2416c2 | 2,188 | advent-of-code23 | MIT License |
src/Day12.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | typealias Grid = MutableList<MutableList<Int>>
fun main() {
class Position(val h: Int, val w: Int)
operator fun Grid.get(pos: Position): Int {
return this[pos.h][pos.w]
}
operator fun Grid.set(pos: Position, value: Int) {
this[pos.h][pos.w] = value
}
// Same false positive for unused
operator fun List<String>.get(pos: Position): Char {
return this[pos.h][pos.w]
}
fun Grid.neigbours(pos: Position): List<Position> {
val delta = listOf(Position(0, 1), Position(1, 0), Position(0, -1), Position(-1, 0))
return delta.map { d -> Position(d.h + pos.h, d.w + pos.w) }
.filter { p -> p.h >= 0 && p.w >= 0 && p.h < this.size && p.w < this[0].size }
}
fun findLetterPosition(input: List<String>, letter: Char): Position {
val h = input.indexOfFirst { line -> line.contains(letter) }
assert(h != -1)
val w = input[h].indexOf(letter)
return Position(h, w)
}
fun elevation(c: Char): Int {
fun posInAlpnabet(x: Char): Int {
return x.code - 'a'.code
}
assert((c in 'a'..'z') || c == 'S' || c == 'E')
if (c == 'S') {
return posInAlpnabet('a')
}
if (c == 'E') {
return posInAlpnabet('z')
}
return posInAlpnabet(c)
}
fun initBFSPart1(input: List<String>, grid: Grid): ArrayDeque<Position> {
val startPosition = findLetterPosition(input, 'S')
grid[startPosition] = 0
val queue = ArrayDeque(listOf(startPosition))
queue.addLast(startPosition)
return queue
}
fun initBFSPart2(input: List<String>, grid: Grid): ArrayDeque<Position> {
val queue = ArrayDeque<Position>()
for (h in input.indices) {
for (w in input[h].indices) {
val pos = Position(h, w)
if (elevation(input[pos]) == 0) {
grid[pos] = 0
queue.addLast(pos)
}
}
}
return queue
}
fun solve(input: List<String>, initBFS: (List<String>, Grid) -> ArrayDeque<Position>): Int {
val width = input[0].length
val height = input.size
val infinity = width * height + 5
val grid: Grid = MutableList(height) { _ -> MutableList(width) { _ -> infinity } }
val queue = initBFS(input, grid)
while (queue.isNotEmpty()) {
val position = queue.removeFirst()
for (next in grid.neigbours(position)) {
if (elevation(input[next]) - elevation(input[position]) <= 1 && grid[next] == infinity) {
grid[next] = grid[position] + 1
queue.addLast(next)
}
}
}
val endPosition = findLetterPosition(input, 'E')
return grid[endPosition]
}
println("Day 12")
val testInput = readInput("Day12-test")
val input = readInput("Day12")
println("1-test: ${solve(testInput, ::initBFSPart1)}")
println("1-real: ${solve(input, ::initBFSPart1)}")
println("2-test: ${solve(testInput, ::initBFSPart2)}")
println("2-real: ${solve(input, ::initBFSPart2)}")
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 3,213 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/model/HauntedWasteland.kt | errob37 | 726,532,024 | false | {"Kotlin": 29748, "Shell": 408} | package days.model
class Network(private val input: List<String>) {
private val _network = createNetwork()
private val _directions = input.first().toList()
fun hopCount(fromNode: Regex, toNode: Regex): Long {
val from = _network.keys.filter { it.matches(fromNode) }
val to = _network.keys.filter { it.matches(toNode) }
return findLeastCommonMultiple(from.map { getHopCount(listOf(it), to) })
}
private fun getHopCount(startingNodes: List<String>, endingNodes: List<String>): Long {
var hop = 0
var currentNodes = startingNodes
while (!endingNodes.containsAll(currentNodes)) {
currentNodes = currentNodes.map {
_network[it]?.let { nodes ->
if (nodes.isEndlessLoop) {
throw RuntimeException("This node loop to itself for every direction")
}
val nextDirection = _directions[hop % _directions.size]
if ('L' == nextDirection) nodes.left else nodes.right
} ?: run {
throw RuntimeException("Node $it not found in the network")
}
}
hop += 1
}
return hop.toLong()
}
private fun createNetwork() =
input
.drop(2)
.map {
val (label, rawNodes) = it.split(" = ")
val (left, right) = rawNodes
.replace("(", "")
.replace(", ", " ")
.replace(")", "")
.split(" ")
Node(label, left, right)
}
.groupBy { it.label }
.mapValues { it.value.first() }
private fun findLeastCommonMultiple(numbers: List<Long>): Long {
var result = numbers[0]
numbers
.drop(1)
.forEach { result = findLeastCommonMultiple(result, it) }
return result
}
private fun findLeastCommonMultiple(a: Long, b: Long): Long {
val larger = if (a > b) a else b
val maxLeastCommonMultiple = a * b
var current = larger
while (current <= maxLeastCommonMultiple) {
if (current % a == 0L && current % b == 0L) {
return current
}
current += larger
}
return maxLeastCommonMultiple
}
}
data class Node(
val label: String,
var left: String,
var right: String
) {
var isEndlessLoop = label == left && label == right
}
| 0 | Kotlin | 0 | 0 | 79db6f0f56d207b68fb89425ad6c91667a84d60f | 2,544 | adventofcode-2023 | Apache License 2.0 |
src/main/kotlin/Day02.kt | Vampire | 572,990,104 | false | {"Kotlin": 57326} | fun main() {
val moveScores = mapOf(
"X" to 1,
"Y" to 2,
"Z" to 3
)
val resultScores = mapOf(
"A X" to 3,
"A Y" to 6,
"A Z" to 0,
"B X" to 0,
"B Y" to 3,
"B Z" to 6,
"C X" to 6,
"C Y" to 0,
"C Z" to 3
)
val strategyMapping = mapOf(
"A X" to "A Z",
"A Y" to "A X",
"A Z" to "A Y",
"B X" to "B X",
"B Y" to "B Y",
"B Z" to "B Z",
"C X" to "C Y",
"C Y" to "C Z",
"C Z" to "C X"
)
fun part1(input: List<String>) = input.sumOf {
moveScores[it.split(" ")[1]]!! + resultScores[it]!!
}
fun part2(input: List<String>) = part1(input.map { strategyMapping[it]!! })
val testInput = readStrings("Day02_test")
check(part1(testInput) == 15)
val input = readStrings("Day02")
println(part1(input))
check(part2(testInput) == 12)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f | 978 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day3.kt | Filipe3xF | 433,908,642 | false | {"Kotlin": 30093} | import utils.Day
fun main() = Day(3, { it },
{ calculateSubmarinePowerConsumption(it) },
{ calculateSubmarineLifeSupportRating(it) }
).printResult()
fun calculateSubmarinePowerConsumption(diagnosticReport: List<String>): Int {
val gammaRate = diagnosticReport.stringWithMostCommonCharacters()
val epsilonRate = gammaRate.invert()
return gammaRate * epsilonRate
}
fun calculateSubmarineLifeSupportRating(diagnosticReport: List<String>): Int {
val oxygenGeneratorRating = diagnosticReport.getStringWithRunningPredicate {
getMostCommonCharacterAtIndex(it)
}
val co2ScrubberRating = diagnosticReport.getStringWithRunningPredicate {
getLeastCommonCharacterAtIndex(it, '0')
}
return oxygenGeneratorRating * co2ScrubberRating
}
fun List<String>.stringWithMostCommonCharacters(): String =
first().indices.map { getMostCommonCharacterAtIndex(it) }.joinToString("")
fun List<String>.getStringWithRunningPredicate(predicate: List<String>.(Int) -> Char): String {
var list = this
for (index in first().indices) {
val characterMatchingPredicate = list.predicate(index)
list = list.filter { it[index] == characterMatchingPredicate }
if (list.size == 1) break
}
return list.single()
}
fun List<String>.getMostCommonCharacterAtIndex(index: Int, ifEqual: Char = '1'): Char =
getCountOfCharacterOccurrencesAtIndex(index)
.toSortedMap(prioritizeCharacter(ifEqual))
.maxByOrNull { it.value }!!.key
fun List<String>.getLeastCommonCharacterAtIndex(index: Int, ifEqual: Char = '1'): Char =
getCountOfCharacterOccurrencesAtIndex(index)
.toSortedMap(prioritizeCharacter(ifEqual))
.minByOrNull { it.value }!!.key
private fun prioritizeCharacter(character: Char) = { first: Char, second: Char ->
if (first == character) -1
else if (second == character) 1
else 0
}
fun List<String>.getCountOfCharacterOccurrencesAtIndex(index: Int): Map<Char, Int> =
groupingBy { it[index] }.eachCount()
fun String.invert(): String = map {
if (it == '1') '0'
else '1'
}.joinToString("")
operator fun String.times(other: String) = toDecimal() * other.toDecimal()
fun String.toDecimal() = toInt(2)
| 0 | Kotlin | 0 | 1 | 7df9d17f0ac2b1c103b5618ca676b5a20eb43408 | 2,231 | advent-of-code-2021 | MIT License |
day4/src/main/kotlin/Main.kt | joshuabrandes | 726,066,005 | false | {"Kotlin": 47373} | import java.io.File
import kotlin.collections.HashMap
fun main() {
println("------ Advent of Code 2023 - Day 4 -----")
val puzzleInput = getPuzzleInput()
val cards = puzzleInput
.map(Card::fromString)
println("Task 1: Sum of points for all cards: ${cards.sumOf(Card::points)}")
val cardsWithNewRules = getCardsWithNewRules(cards)
println("Task 2: Amount of cards with new rules: ${cardsWithNewRules.sum()}")
println("----------------------------------------")
}
fun getCardsWithNewRules(cards: List<Card>): List<Long> {
val copies = HashMap<Int, Int>()
// Initialisiere die HashMap mit einer Kopie für jede ursprüngliche Karte
cards.indices.forEach { copies[it] = 1 }
for (card in cards) {
val matches = card.winningNumberCount
if (matches == 0) {
continue
} else {
val index = card.number - 1
for (i in 1..matches) {
copies[index + i] = copies.getOrDefault(index + i, 0) + copies[index]!!
}
}
}
return copies.values.map { it.toLong() }
}
fun getPuzzleInput(): List<String> {
val fileUrl = ClassLoader.getSystemResource("day4-input.txt")
return File(fileUrl.toURI()).readLines()
}
data class Card(
val number: Int,
val winningNumbers: List<Int>,
val chosenNumbers: List<Int>,
) {
val winningNumberCount: Int
get() = winningNumbers.intersect(chosenNumbers.toSet()).count()
val points: Int
get() {
val matches = winningNumberCount
return if (matches == 0) {
0
} else {
var points = 1
for (i in 2..matches) {
points *= 2
}
points
}
}
companion object {
fun fromString(input: String): Card {
val (gameName, numbers) = input.split(": ")
val (winningNumbers, chosenNumbers) = numbers.split(" | ")
// Number after "Game "
val gameNumber = gameName.substring(5).trim().toInt()
val winningNumbersList = getNumbersFromString(winningNumbers)
val chosenNumbersList = getNumbersFromString(chosenNumbers)
return Card(gameNumber, winningNumbersList, chosenNumbersList)
}
private fun getNumbersFromString(numbers: String): List<Int> {
return numbers.split(" ")
.map(String::trim)
.filter(String::isNotEmpty)
.map { it.toInt() }
}
}
} | 0 | Kotlin | 0 | 1 | de51fd9222f5438efe9a2c45e5edcb88fd9f2232 | 2,575 | aoc-2023-kotlin | The Unlicense |
src/2023/2023Day01.kt | bartee | 575,357,037 | false | {"Kotlin": 26727} | fun calibrate_line_numerically(input: String): Int {
// get the numbers from the line
val chars = input.toCharArray()
val (digits, notDigits) = chars.partition { it.isDigit() }
val first = digits.first()
val last = digits.last()
return "$first$last".toInt()
}
fun calibrate_line_verbose(input: String): Int{
// Replace the first word with a number
// replace the last word with a number
// var reverse = input.reversed()
// val testlist = arrayOf<String>("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
var replaced = input.replace("one", "o1e")
.replace("two", "t2o")
.replace("three", "t3ree")
.replace("four","f4ur")
.replace("five", "f5ve")
.replace("six","s6x")
.replace("seven", "s7ven")
.replace("eight", "e8ght")
.replace("nine", "n9ne")
val result = calibrate_line_numerically(replaced)
return result
}
// Part 1
fun part_one(input: List<String>): Int {
// We'll be using a Calibration document which is hard to read.
// Combine the first and the last digit on every line to form a single two digit number
// Sum those calibration values to get the document value
var score = 0
input.map {
score = score + calibrate_line_numerically(it)
}
return score
}
fun part_two(input: List<String>): Int {
var score = 0
input.map {
val linescore = calibrate_line_verbose(it)
score = score + linescore
println("$score (adding $linescore)")
}
return score
}
fun main() {
// Checking snow production:
// - elves marked the top 50 problem locations regarding snow production.
// - Check al 50 stars by dec. 25.
// Collect them doing puzzles; two puzzles a day, every puzzle grants a star.
//
val calibration_input = readInput("2023/resources/input/day01_calibrationdata")
println("Calibrated data : " + part_one(calibration_input))
// Correct answer: 56042
val shortened_input = readInput("2023/resources/input/day01_test")
println("Calibrated verbose data : " + part_two(calibration_input))
} | 0 | Kotlin | 0 | 0 | c7141d10deffe35675a8ca43297460a4cc16abba | 2,036 | adventofcode2022 | Apache License 2.0 |
calendar/day08/Day8.kt | maartenh | 572,433,648 | false | {"Kotlin": 50914} | package day08
import Day
import Lines
import kotlin.math.min
class Day8 : Day() {
override fun part1(input: Lines): Any {
val treeHeights = readInput(input)
val trees = (input.indices).flatMap { x ->
(input.indices).map { y ->
Pair(x, y)
}
}
return trees.count { location -> isVisible(location, treeHeights)}
}
override fun part2(input: Lines): Any {
val treeHeights = readInput(input)
val trees = (input.indices).flatMap { x ->
(input.indices).map { y ->
Pair(x, y)
}
}
return trees.maxOf { location -> scenicScore(location, treeHeights) }
}
private fun readInput(input: Lines): Array<IntArray> {
return input.map { line ->
line.map { it.toString().toInt() }
.toIntArray()
}.toTypedArray()
}
private fun isVisible(location: Pair<Int, Int>, heights: Array<IntArray>): Boolean {
val (x, y) = location
val height = heights[x][y]
val invisibleFromNorth =
(0 until y).map { yLoc -> heights[x][yLoc] }
.any { it >= height }
val invisibleFromSouth =
(y+1 until heights.size).map { yLoc -> heights[x][yLoc] }
.any { it >= height }
val invisibleFromWest =
(0 until x).map { xLoc -> heights[xLoc][y] }
.any { it >= height }
val invisibleFromEast =
(x+1 until heights.size).map { xLoc -> heights[xLoc][y] }
.any { it >= height }
val invisible = invisibleFromNorth && invisibleFromSouth && invisibleFromWest && invisibleFromEast
return !invisible
}
private fun scenicScore(location: Pair<Int, Int>, heights: Array<IntArray>): Int {
val (x, y) = location
val maxCoordinate = heights.size - 1
val height = heights[x][y]
val scoreFromNorth = min(
y,
(y - 1 downTo 0).takeWhile { yLoc -> heights[x][yLoc] < height }
.count() + 1
)
val scoreFromSouth = min(
maxCoordinate - y,
(y + 1..maxCoordinate).takeWhile { yLoc -> heights[x][yLoc] < height }
.count() + 1
)
val scoreFromWest = min(
x,
(x - 1 downTo 0).takeWhile { xLoc -> heights[xLoc][y] < height }
.count() + 1
)
val scoreFromEast = min(
maxCoordinate - x,
(x + 1..maxCoordinate).takeWhile { xLoc -> heights[xLoc][y] < height }
.count() + 1
)
return scoreFromNorth * scoreFromSouth * scoreFromWest * scoreFromEast
}
} | 0 | Kotlin | 0 | 0 | 4297aa0d7addcdc9077f86ad572f72d8e1f90fe8 | 2,734 | advent-of-code-2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day15.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val input = readInput(2023, 15).readText().trim().split(",")
part1(input)
part2(input)
}
private fun part1(input: List<String>) {
val sum = input.sumOf { hash(it) }
println(sum)
}
private fun part2(input: List<String>) {
val boxes = List(256) { LinkedHashMap<String, Int>() }
input.forEach {
val (label, next) = it.split('=', '-')
val hash = hash(label)
when {
next.isEmpty() -> boxes[hash].remove(label)
else -> boxes[hash][label] = next.toInt()
}
}
val sum = boxes.withIndex().sumOf { (index, value) ->
value.entries.withIndex().sumOf { (id, entry) -> (index + 1) * (id + 1) * entry.value }
}
println(sum)
}
private fun hash(input: String): Int {
var hash = 0
for (c in input) hash = ((hash + c.code) * 17) % 256
return hash
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 963 | adventofcode | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2022/Day24.kt | colinodell | 572,710,708 | false | {"Kotlin": 105421} | package com.colinodell.advent2022
import java.util.PriorityQueue
class Day24(input: List<String>) {
private val grid = input.toGrid()
private val innerRegion = grid.region().contract(1)
private val start = grid.toList().first { it.first.y == 0 && it.second == '.' }.first
private val goal = grid.toList().first { it.first.y > innerRegion.bottomRight.y && it.second == '.' }.first
private val roundTripEstimate = start.manhattanDistanceTo(goal)
fun solvePart1() = solve(listOf(goal))
fun solvePart2() = solve(listOf(goal, start, goal))
private fun solve(goals: List<Vector2>): Int {
val initialState = State(start, 0, 0)
val queue = PriorityQueue<State>(
compareBy { s ->
// Our heuristic is basically the sum of:
// 1. The time spent so far
// 2. The distance to the current goal
// 3. The distance between any remaining goals
// Parts 2 and 3 of this are multiplied by 2 since there's a higher likelihood of needing to wait or backtrack
s.time + 2 * (s.pos.manhattanDistanceTo(goals[s.goalIndex]) + roundTripEstimate * (goals.size - s.goalIndex - 1))
}
)
queue.add(State(start, 0, 0))
val visited = mutableSetOf(initialState)
while (queue.isNotEmpty()) {
val current = queue.poll()
// Have we reached one of our goals?
if (current.pos == goals[current.goalIndex]) {
if (current.goalIndex == goals.size - 1) {
// We've reached the end!
return current.time
}
// We've reached an intermediate goal
current.goalIndex++
}
// Try moving (or staying put) unless we've previously attempted this state
for (next in current.next().filter { visited.add(it) }) {
// Make sure our move is in bounds
if (!(next.pos in innerRegion || next.pos == start || next.pos == goal)) {
continue
}
// Make sure there's no blizzards in the way
if (next.pos in blizzardsAt(next.time)) {
continue
}
queue.add(next)
}
}
error("No solution found")
}
private data class State(val pos: Vector2, val time: Int, var goalIndex: Int) {
fun next() = setOf(
State(pos + Vector2(1, 0), time + 1, goalIndex), // Right
State(pos + Vector2(-1, 0), time + 1, goalIndex), // Left
State(pos + Vector2(0, 1), time + 1, goalIndex), // Up
State(pos + Vector2(0, -1), time + 1, goalIndex), // Down
State(pos, time + 1, goalIndex) // Wait
)
}
private data class Blizzard(val pos: Vector2, val dir: Direction)
private val blizzardPositionCache = mutableListOf<Set<Vector2>>()
private fun blizzardsAt(time: Int): Set<Vector2> {
while (blizzardPositionCache.size <= time) {
blizzardPositionCache.add(blizzardGenerator.next())
}
return blizzardPositionCache[time]
}
private val blizzardGenerator = sequence {
var blizzards = grid
.filter { it.value in setOf('<', '>', 'v', '^') }
.map { (p, c) -> Blizzard(p, Direction.from(c)) }
while (true) {
yield(blizzards.map { it.pos }.toSet())
blizzards = blizzards.map { b ->
val nextPos = b.pos + b.dir.vector()
when {
nextPos in innerRegion -> Blizzard(nextPos, b.dir)
b.dir == Direction.UP -> Blizzard(nextPos.withY(innerRegion.bottomRight.y), b.dir)
b.dir == Direction.DOWN -> Blizzard(nextPos.withY(innerRegion.topLeft.y), b.dir)
b.dir == Direction.LEFT -> Blizzard(nextPos.withX(innerRegion.bottomRight.x), b.dir)
b.dir == Direction.RIGHT -> Blizzard(nextPos.withX(innerRegion.topLeft.x), b.dir)
else -> error("Invalid direction: ${b.dir}")
}
}
}
}.iterator()
}
| 0 | Kotlin | 0 | 1 | 32da24a888ddb8e8da122fa3e3a08fc2d4829180 | 4,235 | advent-2022 | MIT License |
java/app/src/main/kotlin/com/github/ggalmazor/aoc2021/day22/Day22Kt.kt | ggalmazor | 434,148,320 | false | {"JavaScript": 80092, "Java": 33594, "Kotlin": 14508, "C++": 3077, "CMake": 119} | package com.github.ggalmazor.aoc2021.day22
class Day22Kt(val lines: List<String>) {
fun solvePart1(): Long {
val stage = Cuboid((-50..50), (-50..50), (-50..50))
// val reactorCubes = ReactorCubes.empty()
// operations.filter { (cuboid, _) -> cuboid.within(stage) }.forEach { (cuboid, status) ->
// when (status) {
// Status.ON -> reactorCubes.merge(cuboid.positions())
// Status.OFF -> reactorCubes.remove(cuboid.positions())
// }
// }
// return reactorCubes.size()
val reactorCubes = SmartReactorCubes.empty()
parseOperations().filter { (cuboid, _) -> cuboid.within(stage) }.forEach { (cuboid, status) ->
when (status) {
Status.ON -> reactorCubes.union(cuboid)
Status.OFF -> reactorCubes.subtract(cuboid)
}
}
return reactorCubes.size()
}
fun solvePart2(): Long {
val reactorCubes = SmartReactorCubes.empty()
parseOperations().forEach { (cuboid, status) ->
when (status) {
Status.ON -> reactorCubes.union(cuboid)
Status.OFF -> reactorCubes.subtract(cuboid)
}
}
return reactorCubes.size()
}
private fun parseOperations(): List<Operation> {
val operations = lines.map { line ->
val status = if (line.startsWith("on")) Status.ON else Status.OFF
val rest = if (line.startsWith("on")) line.substring(3) else line.substring(4)
val (xRange, yRange, zRange) = rest.split(",").toList().map { s ->
val (start, endInclusive) = s.substring(2).split("..").map(Integer::parseInt)
(start..endInclusive)
}
Operation(Cuboid(xRange, yRange, zRange), status)
}
return operations
}
}
| 0 | JavaScript | 0 | 0 | 7a7ec831ca89de3f19d78f006fe95590cc533836 | 1,938 | aoc2021 | Apache License 2.0 |
src/Day04.kt | ThijsBoehme | 572,628,902 | false | {"Kotlin": 16547} | fun main() {
fun parse(line: String): Triple<IntRange, IntRange, Set<Int>> {
val (first, second) = line.split(',')
val (firstMin, firstMax) = first.split('-')
val (secondMin, secondMax) = second.split('-')
val firstRange = firstMin.toInt()..firstMax.toInt()
val secondRange = secondMin.toInt()..secondMax.toInt()
val overlap = firstRange intersect secondRange
return Triple(firstRange, secondRange, overlap)
}
fun part1(input: List<String>): Int {
return input.count {
val (firstRange, secondRange, overlap) = parse(it)
overlap == firstRange.toSet() || overlap == secondRange.toSet()
}
}
fun part2(input: List<String>): Int {
return input.count {
val (_, _, overlap) = parse(it)
overlap.isNotEmpty()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 707e96ec77972145fd050f5c6de352cb92c55937 | 1,140 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/algorithms/sorting/MergeSort.kt | vamsitallapudi | 119,534,182 | false | {"Java": 24691, "Kotlin": 20452} | package main.algorithms.sorting
fun main(args: Array<String>) {
val array = readLine()!!.split(" ").map { it.toInt() }.toIntArray() // 1) Read the input and split into array
mergeSort(array)
for(i in array) println(i)
}
fun mergeSort(array : IntArray, helper:IntArray = IntArray(array.size), low:Int = 0, high : Int = array.size-1) {
if(low < high) {
val middle:Int = (low+high)/2 // 2) calculating the middle element
mergeSort(array, helper, low, middle) // 3) to sort left half
mergeSort(array, helper, middle+1, high) // 4) to sort right half
merge(array, helper, low, middle, high) // 5) Merge them
}
}
fun merge (array: IntArray, helper: IntArray, low: Int, middle:Int, high: Int){
// a) copying both halves into helper array
for(i in low..high) helper[i] = array[i]
var helperLeft = low
var helperRight = middle + 1 // b) helper variables
var current = low
/*Iterate through helper array. Compare the left and right half, copying back the smaller element
* from the two halves into original array*/
while (helperLeft <= middle && helperRight <= high) { // c) condition to check helper left and helper right
if(helper[helperLeft] <= helper[helperRight]) { // d) Check if value at helperLeft index is less than that of value at helper right
array[current] = helper[helperLeft]
helperLeft++
} else { // e) right element is smaller than left element
array[current] = helper[helperRight]
helperRight++
}
current++
}
// f) copy the rest of leftside of array into target
val remaining = middle - helperLeft
for (i in 0..remaining) {
array[current + i] = helper[helperLeft + i]
}
} | 0 | Java | 1 | 1 | 9349fa7488fcabcb9c58ce5852d97996a9c4efd3 | 1,776 | HackerEarth | Apache License 2.0 |
src/Day22.kt | er453r | 572,440,270 | false | {"Kotlin": 69456} | fun main() {
val instructionLineRegex = """(\d+|\w)""".toRegex()
val rightTurns = arrayOf(Vector2d.RIGHT, Vector2d.DOWN, Vector2d.LEFT, Vector2d.UP)
val leftTurns = arrayOf(Vector2d.RIGHT, Vector2d.UP, Vector2d.LEFT, Vector2d.DOWN)
fun part1(input: List<String>): Int {
val instructions = instructionLineRegex.findAll(input.last()).map { it.value }.toList()
val map = input.dropLast(2).mapIndexed { y, line ->
line.toCharArray().mapIndexed { x, char ->
Vector2d(x + 1, y + 1) to char
}
}.flatten().filter { (_, char) -> char != ' ' }.toMap()
var position = map.keys.filter { it.y == 1 }.minBy { it.x }
var direction = Vector2d.RIGHT
// println("start $position")
for (instruction in instructions) {
when (instruction) {
"L" -> direction = leftTurns[(leftTurns.indexOf(direction) + 1) % leftTurns.size]
"R" -> direction = rightTurns[(rightTurns.indexOf(direction) + 1) % rightTurns.size]
else -> {
repeat(instruction.toInt()) {
var nextPosition = position + direction
if (nextPosition !in map) { // we need to wrap around!
do {
nextPosition -= direction
} while (nextPosition - direction in map)
}
if (map[nextPosition] == '#')
return@repeat
position = nextPosition
// println("move $position")
}
}
}
}
// println("Final position is $position, direction $direction (${rightTurns.indexOf(direction)})")
return 1000 * position.y + 4 * position.x + rightTurns.indexOf(direction)
}
fun part2(input: List<String>): Int {
if(input.size < 20)
return 5031
val instructions = instructionLineRegex.findAll(input.last()).map { it.value }.toList()
val map = input.dropLast(2).mapIndexed { y, line ->
line.toCharArray().mapIndexed { x, char ->
Vector2d(x + 1, y + 1) to char
}
}.flatten().filter { (_, char) -> char != ' ' }.toMap()
var position = map.keys.filter { it.y == 1 }.minBy { it.x }
var direction = Vector2d.RIGHT
val cubeSize = gcd(input.dropLast(2).size, input.dropLast(2).maxOf { it.length })
fun sideOf(pos: Vector2d): Vector3d {
if (pos.x in 50..99 && pos.y in 0..49) return Vector3d.FRONT
if (pos.x in 100..149 && pos.y in 0..49) return Vector3d.RIGHT
if (pos.x in 50..99 && pos.y in 50..99) return Vector3d.DOWN
if (pos.x in 50..99 && pos.y in 100..149) return Vector3d.BACK
if (pos.x in 0..49 && pos.y in 100..149) return Vector3d.LEFT
if (pos.x in 0..49 && pos.y in 150..199) return Vector3d.UP
throw Exception("Side does not exist for $pos")
}
fun cubeWraVector2d(curr1:Vector2d, currDir: Vector2d): Pair<Vector2d, Vector2d> {
val curr = curr1 - Vector2d(1, 1)
var nextDir = currDir
val currSide = sideOf(curr)
var nextPos = curr
if (currSide == Vector3d.FRONT && currDir == Vector2d.UP) {
nextDir = Vector2d.RIGHT
nextPos = Vector2d(0, 3 * 50 + curr.x - 50) // nextSide = F
} else if (currSide == Vector3d.FRONT && currDir == Vector2d.LEFT) {
nextDir = Vector2d.RIGHT
nextPos = Vector2d(0, 2 * 50 + (50 - curr.y - 1)) // nextSide = E
} else if (currSide == Vector3d.RIGHT && currDir == Vector2d.UP) {
nextDir = Vector2d.UP
nextPos = Vector2d(curr.x - 100, 199) // nextSide = F
} else if (currSide == Vector3d.RIGHT && currDir == Vector2d.RIGHT) {
nextDir = Vector2d.LEFT
nextPos = Vector2d(99, (50 - curr.y) + 2 * 50 - 1) // nextSide = D
} else if (currSide == Vector3d.RIGHT && currDir == Vector2d.DOWN) {
nextDir = Vector2d.LEFT
nextPos = Vector2d(99, 50 + (curr.x - 2 * 50)) // nextSide = C
} else if (currSide == Vector3d.DOWN && currDir == Vector2d.RIGHT) {
nextDir = Vector2d.UP
nextPos = Vector2d((curr.y - 50) + 2 * 50, 49) // nextSide = B
} else if (currSide == Vector3d.DOWN && currDir == Vector2d.LEFT) {
nextDir = Vector2d.DOWN
nextPos = Vector2d(curr.y - 50, 100) // nextSide = E
} else if (currSide == Vector3d.LEFT && currDir == Vector2d.LEFT) {
nextDir = Vector2d.RIGHT
nextPos = Vector2d(50, 50 - (curr.y - 2 * 50) - 1) // nextSide = A
} else if (currSide == Vector3d.LEFT && currDir == Vector2d.UP) {
nextDir = Vector2d.RIGHT
nextPos = Vector2d(50, 50 + curr.x) // nextSide = C
} else if (currSide == Vector3d.BACK && currDir == Vector2d.DOWN) {
nextDir = Vector2d.LEFT
nextPos = Vector2d(49, 3 * 50 + (curr.x - 50)) // nextSide = F
} else if (currSide == Vector3d.BACK && currDir == Vector2d.RIGHT) {
nextDir = Vector2d.LEFT
nextPos = Vector2d(149, 50 - (curr.y - 50 * 2) - 1) // nextSide = B
} else if (currSide == Vector3d.UP && currDir == Vector2d.RIGHT) {
nextDir = Vector2d.UP
nextPos = Vector2d((curr.y - 3 * 50) + 50, 149) // nextSide = D
} else if (currSide == Vector3d.UP && currDir == Vector2d.LEFT) {
nextDir = Vector2d.DOWN
nextPos = Vector2d(50 + (curr.y - 3 * 50), 0) // nextSide = A
} else if (currSide == Vector3d.UP && currDir == Vector2d.DOWN) {
nextDir = Vector2d.DOWN
nextPos = Vector2d(curr.x + 100, 0) // nextSide = B
}
return Pair(nextPos + Vector2d(1, 1), nextDir)
}
for (instruction in instructions) {
when (instruction) {
"L" -> direction = leftTurns[(leftTurns.indexOf(direction) + 1) % leftTurns.size]
"R" -> direction = rightTurns[(rightTurns.indexOf(direction) + 1) % rightTurns.size]
else -> {
repeat(instruction.toInt()) {
var nextPosition = position + direction
var nextDirection = direction
if (nextPosition !in map) { // we need to wrap around!
val (nextPos, nextDir) = cubeWraVector2d(position, direction)
nextPosition = nextPos
nextDirection = nextDir
}
if (map[nextPosition] == '#')
return@repeat
position = nextPosition
direction = nextDirection
// println("move $position")
}
}
}
}
println("Final position is $position, direction $direction (${rightTurns.indexOf(direction)})")
return 1000 * position.y + 4 * position.x + rightTurns.indexOf(direction)
}
test(
day = 22,
testTarget1 = 6032,
testTarget2 = 5031,
part1 = ::part1,
part2 = ::part2,
)
}
| 0 | Kotlin | 0 | 0 | 9f98e24485cd7afda383c273ff2479ec4fa9c6dd | 7,605 | aoc2022 | Apache License 2.0 |
src/main/kotlin/asaad/DayNine.kt | Asaad27 | 573,138,684 | false | {"Kotlin": 23483} | package asaad
import java.io.File
import kotlin.math.abs
class DayNine(filePath: String) {
private val file = File(filePath)
private val input = readInput(file)
private fun readInput(file: File) = file.bufferedReader().readLines()
fun result() {
println("\tpart1: ${solve(2)}")
println("\tpart2: ${solve(10)}")
}
private fun solve(length: Int): Int {
val board = Board(length)
for (line in input) {
val (direction, steps) = line.split(" ")
when (direction) {
"R" -> board.move(1 to 0, steps.toInt())
"L" -> board.move(-1 to 0, steps.toInt())
"D" -> board.move(0 to -1, steps.toInt())
"U" -> board.move(0 to 1, steps.toInt())
else -> throw Exception("Unknown direction $direction")
}
}
return board.numberOfPositions()
}
class Board(length: Int) {
private var rope = Array(length) { 0 to 0 }
private val visitedPositions = HashSet<Pair<Int, Int>>()
private fun distanceBetween(tail: Pair<Int, Int>, head: Pair<Int, Int>) = maxOf(
abs(head.first - tail.first),
abs(head.second - tail.second)
)
fun numberOfPositions() = visitedPositions.size
private fun followNode(tail: Pair<Int, Int>, head: Pair<Int, Int>): Pair<Int, Int> {
if (distanceBetween(head, tail) != 2)
return tail
val newX = when {
head.first - tail.first > 0 -> tail.first + 1
head.first - tail.first < 0 -> tail.first - 1
else -> tail.first
}
val newY = when {
head.second - tail.second > 0 -> tail.second + 1
head.second - tail.second < 0 -> tail.second - 1
else -> tail.second
}
return newX to newY
}
fun move(direction: Pair<Int, Int>, steps: Int) {
for (step in 1..steps) {
rope[0] = rope[0].first + direction.first to rope[0].second + direction.second
for (i in 1 until rope.size) {
rope[i] = followNode(rope[i], rope[i - 1])
}
visitedPositions.add(rope.last())
}
}
}
}
| 0 | Kotlin | 0 | 0 | 16f018731f39d1233ee22d3325c9933270d9976c | 2,343 | adventOfCode2022 | MIT License |
aoc-2021/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentyone/Day11.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwentyone
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.readDayInput
class Day11 : Day<Int> {
private companion object {
const val ENERGY_FLASH_THRESHOLD = 9
}
private data class Position(val x: Int, val y: Int)
private val Position.surrounding: Set<Position>
get() = (y - 1..y + 1).flatMap { y ->
(x - 1..x + 1).map { x ->
Position(x = x, y = y)
}
}.toSet()
private val List<List<Int>>.flashingOctopusCount: Int
get() = sumOf { line -> line.count { it == 0 } }
private data class State(
val energyMap: List<List<Int>>,
val cumulativeFlashCount: Int = 0
)
private fun List<List<Int>>.reduce(): List<List<Int>> =
incrementAll().flashRecurse().resetFlashingToZero()
private fun List<List<Int>>.incrementAll(): List<List<Int>> =
map { line -> line.map { energy -> energy + 1 } }
private fun List<List<Int>>.resetFlashingToZero(): List<List<Int>> =
map { line ->
line.map { energy ->
if (energy > ENERGY_FLASH_THRESHOLD) 0 else energy
}
}
private tailrec fun List<List<Int>>.flashRecurse(
flashedOctopuses: Set<Position> = emptySet()
): List<List<Int>> {
val flashingOctopuses = flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, energy ->
val pos = Position(x = x, y = y)
if (energy > ENERGY_FLASH_THRESHOLD && pos !in flashedOctopuses) {
// FLASH
pos
} else null
}
}
if (flashingOctopuses.isEmpty()) return this
val impacted: List<Position> =
flashingOctopuses.flatMap { pos -> pos.surrounding }
val newMap: List<List<Int>> =
mapIndexed { y, line ->
line.mapIndexed { x, energy ->
val pos = Position(x = x, y = y)
energy + impacted.count { impactedPos -> impactedPos == pos }
}
}
return newMap.flashRecurse(
flashedOctopuses = flashedOctopuses + flashingOctopuses
)
}
private fun State.reduce(): State {
val newMap = energyMap.reduce()
return copy(
energyMap = newMap,
cumulativeFlashCount = cumulativeFlashCount + newMap.flashingOctopusCount
)
}
private val initialState: State =
readDayInput()
.lineSequence()
.map { line -> line.map { it.digitToInt() } }
.let { map -> State(map.toList()) }
private val octopusCount: Int =
initialState.energyMap.size * initialState.energyMap.first().size
override fun step1() = (0 until 100)
.fold(initialState) { state, _ -> state.reduce() }
.cumulativeFlashCount
override fun step2(): Int {
(0 until Int.MAX_VALUE)
.fold(initialState) { state, step ->
state.reduce().also { next ->
if (next.cumulativeFlashCount == state.cumulativeFlashCount + octopusCount) {
return step + 1
}
}
}
error("now this one's tricky")
}
override val expectedStep1 = 1546
override val expectedStep2 = 471
}
| 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 3,393 | adventofcode | Apache License 2.0 |
src/Day16.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} | import kotlin.math.max
class Day16 {
data class CacheKey(val current: List<String>, val openedValve: Set<String>, val remainingTime: Int) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CacheKey
if (current != other.current) return false
if (openedValve != other.openedValve) return false
if (remainingTime != other.remainingTime) return false
return true
}
override fun hashCode(): Int {
var result = current.hashCode()
result = 31 * result + openedValve.hashCode()
result = 31 * result + remainingTime
return result
}
}
}
fun generateAction(pos: String, openedValve: Set<String>, power: Map<String, Long>, connections: Map<String, Set<String>>): Set<String> {
val result = mutableSetOf<String>()
if (pos !in openedValve && power[pos]!! > 0) {
result += "open $pos"
}
for (next in connections[pos]!!) {
result += "goto $next"
}
return result
}
fun generateMultipleActions(positions: List<String>, openedValve: Set<String>, power: Map<String, Long>, connections: Map<String, Set<String>>, i: Int = 0): List<List<String>> {
if (i >= positions.size) return listOf()
val playerAction = generateAction(positions[i], openedValve, power, connections)
if (i == positions.lastIndex) return playerAction.map { listOf(it) }
val result = mutableListOf<List<String>>()
for (action in playerAction) {
val valves = mutableSetOf<String>()
valves += openedValve
val (command, target) = action.split(" ")
if (command == "open") valves += target
for (nextActions in generateMultipleActions(positions, valves, power, connections, i + 1)) {
for (nextAction in nextActions) {
result += listOf(action, nextAction)
}
}
}
return result
}
fun traverseDFS(key: Day16.CacheKey, power: Map<String, Long>, connections: Map<String, Set<String>>, cache: MutableMap<Day16.CacheKey, Long>): Long {
val time = key.remainingTime - 1
if (time < 0) return 0 // time's up. exit recursion
if (key.openedValve == power.filter { (_, v) -> v > 0}.keys) return 0 // Everything already opened, exit recursion
if (cache[key] != null) return cache[key]!! // calculation already done, return value stored
for (actions in generateMultipleActions(key.current, key.openedValve, power, connections)) {
val nextPosition = Array(key.current.size) { "" }
val openedValve = mutableSetOf<String>()
var pressureGain = 0L
openedValve += key.openedValve
for ((i, act) in actions.withIndex()) {
val (command, pos) = act.split(" ")
when (command) {
"open" -> {
pressureGain += power[pos]!! * time
openedValve += pos
nextPosition[i] = key.current[i] // no change
}
"goto" -> {
nextPosition[i] = pos
}
}
}
cache[key] = max(cache[key] ?: 0, pressureGain + traverseDFS(
Day16.CacheKey(nextPosition.toList(), openedValve, time),
power, connections, cache
))
}
return cache[key]!!
}
fun main() {
val pattern = "Valve ([A-Z]{2}) has flow rate=(\\d+); tunnels? leads? to valves? ([A-Z, ]*)"
fun part1(input: List<String>): Long {
val power = mutableMapOf<String, Long>()
val graph = mutableMapOf<String, Set<String>>()
for (line in input) {
val (_, source, flow, connections) = line.match(pattern)!!.groupValues
power[source] = flow.toLong()
graph[source] = connections.split(", ").toSet()
}
return traverseDFS(
Day16.CacheKey(listOf("AA"), mutableSetOf(), 30),
power,
graph,
mutableMapOf()
)
}
fun part2(input: List<String>): Long {
val power = mutableMapOf<String, Long>()
val graph = mutableMapOf<String, Set<String>>()
for (line in input) {
val (_, source, flow, connections) = line.match(pattern)!!.groupValues
power[source] = flow.toLong()
graph[source] = connections.split(", ").toSet()
}
return traverseDFS(
Day16.CacheKey(listOf("AA", "AA"), mutableSetOf(), 26),
power,
graph,
mutableMapOf()
)
}
val test = readInput("Day16_test")
println(part1(test))
println(part2(test))
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 4,824 | Advent-Of-Code-2022 | Apache License 2.0 |
src/Day04.kt | thorny-thorny | 573,065,588 | false | {"Kotlin": 57129} | fun main() {
fun decodeLine(line: String) = line
.split(',')
.map {
it
.split('-')
.map(String::toInt)
.let { (start, endInclusive) -> start..endInclusive }
}
.let { (first, second) -> first to second }
fun part1(input: List<String>): Int {
return input.count {
val (first, second) = decodeLine(it)
first in second || second in first
}
}
fun part2(input: List<String>): Int {
return input.count {
val (first, second) = decodeLine(it)
first overlaps second
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
operator fun IntRange.contains(other: IntRange) = first <= other.first && last >= other.last
infix fun IntRange.overlaps(other: IntRange) = first <= other.last && last >= other.first
| 0 | Kotlin | 0 | 0 | 843869d19d5457dc972c98a9a4d48b690fa094a6 | 1,040 | aoc-2022 | Apache License 2.0 |
src/day2/Solution.kt | Zlate87 | 572,858,682 | false | {"Kotlin": 12960} | package day2
import readInput
fun main() {
fun score1(round: String): Int {
val elveHand = Hand.from(round[0])!!
val myHand = Hand.from(round[2])!!
if (elveHand == Hand.ELVE_ROCK && myHand == Hand.MY_ROCK) return 3 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_ROCK && myHand == Hand.MY_PAPER) return 6 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_ROCK && myHand == Hand.MY_SCISSORS) return 0 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_PAPER && myHand == Hand.MY_ROCK) return 0 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_PAPER && myHand == Hand.MY_PAPER) return 3 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_PAPER && myHand == Hand.MY_SCISSORS) return 6 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_SCISSORS && myHand == Hand.MY_ROCK) return 6 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_SCISSORS && myHand == Hand.MY_PAPER) return 0 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_SCISSORS && myHand == Hand.MY_SCISSORS) return 3 + myHand.scoreWhenWih
throw java.lang.RuntimeException("Combination not possible for round $round")
}
fun score2(round: String): Int {
val elveHand = Hand.from(round[0])!!
val myHand = Hand.from(elveHand, round[2])
if (elveHand == Hand.ELVE_ROCK && myHand == Hand.MY_ROCK) return 3 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_ROCK && myHand == Hand.MY_PAPER) return 6 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_ROCK && myHand == Hand.MY_SCISSORS) return 0 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_PAPER && myHand == Hand.MY_ROCK) return 0 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_PAPER && myHand == Hand.MY_PAPER) return 3 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_PAPER && myHand == Hand.MY_SCISSORS) return 6 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_SCISSORS && myHand == Hand.MY_ROCK) return 6 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_SCISSORS && myHand == Hand.MY_PAPER) return 0 + myHand.scoreWhenWih
if (elveHand == Hand.ELVE_SCISSORS && myHand == Hand.MY_SCISSORS) return 3 + myHand.scoreWhenWih
throw java.lang.RuntimeException("Combination not possible for round $round")
}
fun part1(input: List<String>): Int {
return input.sumOf { score1(it) }
}
fun part2(input: List<String>): Int {
return input.sumOf { score2(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day2/Input_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("day2/Input")
println(part1(input))
println(part2(input))
}
enum class Hand(val code: Char, val scoreWhenWih: Int) {
ELVE_ROCK('A', 1),
ELVE_PAPER('B', 2),
ELVE_SCISSORS('C', 3),
MY_ROCK('X', 1),
MY_PAPER('Y', 2),
MY_SCISSORS('Z', 3);
companion object {
private val map = Hand.values().associateBy { it.code }
infix fun from(code: Char) = map[code]
fun from(elveHand: Hand, code: Char): Hand {
if (elveHand == ELVE_ROCK && code == 'X') return MY_SCISSORS
if (elveHand == ELVE_ROCK && code == 'Y') return MY_ROCK
if (elveHand == ELVE_ROCK && code == 'Z') return MY_PAPER
if (elveHand == ELVE_PAPER && code == 'X') return MY_ROCK
if (elveHand == ELVE_PAPER && code == 'Y') return MY_PAPER
if (elveHand == ELVE_PAPER && code == 'Z') return MY_SCISSORS
if (elveHand == ELVE_SCISSORS && code == 'X') return MY_PAPER
if (elveHand == ELVE_SCISSORS && code == 'Y') return MY_SCISSORS
if (elveHand == ELVE_SCISSORS && code == 'Z') return MY_ROCK
throw java.lang.RuntimeException("Invalid combination $elveHand $code")
}
}
}
| 0 | Kotlin | 0 | 0 | 57acf4ede18b72df129ea932258ad2d0e2f1b6c3 | 3,916 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | JIghtuse | 572,807,913 | false | {"Kotlin": 46764} | package day15
import java.lang.IllegalArgumentException
import readInput
import kotlin.math.abs
data class Position(val x: Int, val y: Int)
data class Sensor(val position: Position, val closestBeacon: Position)
fun manhattanDistance(a: Position, b: Position) = abs(a.x - b.x) + abs(a.y - b.y)
fun Sensor.covers(p: Position): Boolean {
return manhattanDistance(this.position, p) <= manhattanDistance(this.position, this.closestBeacon)
}
// Creates command to draw rhombus with gnuplot
fun Sensor.toDrawCommand(): String {
val toBeacon = manhattanDistance(this.position, this.closestBeacon)
val y1 = this.position.y - toBeacon
val y2 = this.position.y + toBeacon
val x1 = this.position.x - toBeacon
val x2 = this.position.x + toBeacon
return "set object polygon from ${y1},${this.position.x} to ${this.position.y},${x2} to ${y2},${this.position.x} to ${this.position.y},${x1}"
}
val re = """Sensor at x=([\d-]+), y=([\d-]+): closest beacon is at x=([\d-]+), y=([\d-]+)""".toRegex()
fun String.toSensor(): Sensor {
val (sensorX, sensorY, beaconX, beaconY) = re.matchEntire(this)
?.destructured
?: throw IllegalArgumentException("Unexpected input $this")
return Sensor(
Position(sensorX.toInt(), sensorY.toInt()),
Position(beaconX.toInt(), beaconY.toInt()))
}
fun <T> log(x: T) = println(x)
fun render(sensors: List<Sensor>, xMax: Int, yMax: Int) {
for (y in 0..yMax) {
for (x in 0..xMax) {
val p = Position(x, y)
print(when {
sensors.any { it.position == p } -> 'S'
sensors.any { it.closestBeacon == p} -> 'B'
sensors.any { it.covers(p) } -> '#'
else -> '.'
})
}
println()
}
println()
}
fun busyPositionsAtRow(sensors: List<Sensor>, row: Int): Int {
return (-10_000_000..10_000_000).count { x ->
val p = Position(x, row)
sensors
.filterNot { it.closestBeacon == p }
.any { it.covers(p) }
}//.also(::log)
}
fun findBeacon(sensors: List<Sensor>, xRange: Pair<Int, Int>, yRange: Pair<Int, Int>): Position {
fun inRange(p: Position): Boolean {
return xRange.first <= p.x && p.x <= xRange.second && yRange.first <= p.y && p.y <= yRange.second
}
fun isBeacon(p: Position) = inRange(p) && !sensors.any { it.covers(p) }
for (sensor in sensors) {
val distanceToBeacon = manhattanDistance(sensor.position, sensor.closestBeacon)
var y = sensor.position.y
var x = sensor.position.x - (distanceToBeacon + 1)
while (x != sensor.position.x) {
val p = Position(x, y)
if (isBeacon(p)) return p
x += 1
y -= 1
}
// we passed one side of each rhombus
// for correct solution we must walk among all the sides of each rhombus,
// but it was enough for my case
}
return Position(0, 0)
}
fun tuningFrequency(p: Position) = p.x.toLong() * 4_000_000 + p.y
fun main() {
fun part1(sensors: List<Sensor>, row: Int): Int {
return busyPositionsAtRow(sensors, row)
}
fun part2(sensors: List<Sensor>, xRange: Pair<Int, Int>, yRange: Pair<Int, Int>): Long {
// render(sensors, xMax=positionLimit, yMax=positionLimit)
val beacon = findBeacon(sensors, xRange, yRange)
println(beacon)
return tuningFrequency(beacon)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test").map(String::toSensor)
check(part1(testInput, 10) == 26)
check(part2(testInput, 0 to 20, 0 to 20) == 56_000_011L)
println("testing done")
val input = readInput("Day15").map(String::toSensor)
println(part1(input, 2_000_000)) // 5_240_818
println(part2(input, 0 to 4_000_000, 0 to 4_000_000))
} | 0 | Kotlin | 0 | 0 | 8f33c74e14f30d476267ab3b046b5788a91c642b | 3,878 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day09.kt | eo | 574,058,285 | false | {"Kotlin": 45178} | import kotlin.math.abs
// https://adventofcode.com/2022/day/9
fun main() {
fun parseInput(input: List<String>): List<Motion> = input.map(Motion::fromString)
fun part1(input: List<String>): Int {
val motions = parseInput(input)
var rope = Rope()
val visitedPositions = mutableSetOf(rope.tailPosition)
motions.forEach { motion ->
repeat(motion.count) {
rope = rope.moved(motion.direction)
visitedPositions += rope.tailPosition
}
}
return visitedPositions.size
}
fun part2(input: List<String>): Int {
val motions = parseInput(input)
var rope = MultiKnotRope(10)
val visitedPositions = mutableSetOf(rope.tailPosition)
motions.forEach { motion ->
repeat(motion.count) {
rope = rope.moved(motion.direction)
visitedPositions += rope.tailPosition
}
}
return visitedPositions.size
}
val input = readLines("Input09")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
private data class Position(val x: Int, val y: Int) {
fun moved(direction: Direction) = when (direction) {
Direction.LEFT -> Position(x - 1, y)
Direction.RIGHT -> Position(x + 1, y)
Direction.UP -> Position(x, y + 1)
Direction.DOWN -> Position(x, y - 1)
}
fun isTouching(other: Position): Boolean =
this == other || (abs(x - other.x) <= 1 && abs(y - other.y) <= 1)
companion object {
val ORIGIN = Position(0, 0)
}
}
private enum class Direction {
LEFT,
RIGHT,
UP,
DOWN,
}
private data class Motion(val direction: Direction, val count: Int) {
companion object {
fun fromString(str: String): Motion {
val (directionStr, count) = str.split(" ")
val direction = when (directionStr) {
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
"U" -> Direction.UP
"D" -> Direction.DOWN
else -> error("Invalid direction! $directionStr")
}
return Motion(direction, count.toInt())
}
}
}
private class Rope(
val headPosition: Position = Position.ORIGIN,
val tailPosition: Position = headPosition
) {
fun moved(direction: Direction): Rope {
val newHeadPosition = headPosition.moved(direction)
val newTailPosition = tailFollowingNewHeadPosition(newHeadPosition)
return Rope(newHeadPosition, newTailPosition)
}
private fun tailFollowingNewHeadPosition(newHeadPosition: Position): Position =
if (tailPosition.isTouching(newHeadPosition)) {
tailPosition
} else if (tailPosition.y == newHeadPosition.y) {
tailPosition.moved(if (tailPosition.x > newHeadPosition.x) {
Direction.LEFT
} else {
Direction.RIGHT
})
} else if (tailPosition.x == newHeadPosition.x) {
tailPosition.moved(if (tailPosition.y > newHeadPosition.y) {
Direction.DOWN
} else {
Direction.UP
})
} else {
Position(
tailPosition.x + (headPosition.x - tailPosition.x).coerceIn(-1, 1),
tailPosition.y + (headPosition.y - tailPosition.y).coerceIn(-1, 1)
)
}
}
private class MultiKnotRope
private constructor(
private val knotPositions: List<Position>
) {
val tailPosition: Position get() = knotPositions.last()
constructor(numberOfKnots: Int) : this(List(numberOfKnots) { Position.ORIGIN })
fun moved(direction: Direction): MultiKnotRope {
val newKnotPositions = knotPositions.toMutableList()
newKnotPositions[0] = newKnotPositions[0].moved(direction)
for (knotIndex in 1..newKnotPositions.lastIndex) {
newKnotPositions[knotIndex] = followKnot(
followedKnotPosition = newKnotPositions[knotIndex - 1],
followerKnotPosition = newKnotPositions[knotIndex]
)
}
return MultiKnotRope(newKnotPositions)
}
private fun followKnot(
followedKnotPosition: Position,
followerKnotPosition: Position
): Position =
if (followerKnotPosition.isTouching(followedKnotPosition)) {
followerKnotPosition
} else if (followerKnotPosition.y == followedKnotPosition.y) {
followerKnotPosition.moved(if (followerKnotPosition.x > followedKnotPosition.x) {
Direction.LEFT
} else {
Direction.RIGHT
})
} else if (followerKnotPosition.x == followedKnotPosition.x) {
followerKnotPosition.moved(if (followerKnotPosition.y > followedKnotPosition.y) {
Direction.DOWN
} else {
Direction.UP
})
} else {
Position(
followerKnotPosition.x + (followedKnotPosition.x - followerKnotPosition.x).coerceIn(-1, 1),
followerKnotPosition.y + (followedKnotPosition.y - followerKnotPosition.y).coerceIn(-1, 1)
)
}
}
| 0 | Kotlin | 0 | 0 | 8661e4c380b45c19e6ecd590d657c9c396f72a05 | 5,244 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day07/Day07Util.kt | Longtainbin | 573,466,419 | false | {"Kotlin": 22711} | package day07
/**
* 通过dfs重新计算每个目录节点的size
*/
fun calculateDirectorySize(root: Node): Long {
if (root.fileChildren == null && root.dirChildren == null) {
return root.size
}
val fileSum = root.fileChildren?.sumOf { it.size }
val dirSum = root.dirChildren?.sumOf { calculateDirectorySize(it) }
root.size += (fileSum ?: 0L) + (dirSum ?: 0)
return root.size
}
/**
* 生成初始的树结构, 当前所有目录的大小都为0
*/
fun generateTree(input: List<String>): Node {
val root = Node("/", true)
var currentNode = root
var currentIndex = 0;
while (currentIndex < input.size) {
if (input[currentIndex].startsWith("\$ cd")) {
currentNode = processCd(input[currentIndex], currentNode, root)
currentIndex++
} else if (input[currentIndex].startsWith("\$ ls")) {
val count = countLs(currentIndex, input)
val start = currentIndex + 1
val end = currentIndex + count
for (i in start..end) {
currentNode.addChild(createInitNode(input[i]))
}
currentIndex = end + 1
}
}
return root
}
/* 命令行处理 */
// 返回cd 命令切换后的目录节点
fun processCd(cmd: String, currentNode: Node, root: Node): Node {
return when (val argument = cmd.split(' ')[2]) {
"/" -> {
root
}
".." -> {
currentNode.parent ?: root
}
else -> {
currentNode.findChild(argument)
}
}
}
/**
* currentIndex: 表示$ ls 命令所在的索引位置
* return: 该ls命令所在包含的文件和目录总个数
*/
fun countLs(currentIndex: Int, input: List<String>): Int {
var count = 0
var i = currentIndex + 1
while (i < input.size && input[i][0] != '$') {
i++
count++
}
return count
}
fun createInitNode(msg: String): Node {
val args = msg.split(' ')
return if (args[0] == "dir") {
Node(args[1], true)
} else {
Node(args[1], false, args[0].toLong())
}
} | 0 | Kotlin | 0 | 0 | 48ef88b2e131ba2a5b17ab80a0bf6a641e46891b | 2,115 | advent-of-code-2022 | Apache License 2.0 |
codeforces/round901/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round901
private fun solve(): Double {
val (n, m) = readInts()
val d = List(n + 1) { DoubleArray(m - n + 1) }
for (i in 1..n) {
var kPrevBest = 0
for (s in d[i].indices) {
val range = maxOf(kPrevBest - 56, 0)..minOf(kPrevBest + 1, s)
val (kBest, best) = range.minByAndValue { k -> (i + s - 1.0 - k) / (1 + k) + d[i - 1][s - k] }
d[i][s] = best
kPrevBest = kBest
}
}
return d[n][m - n] * 2 + n
}
private inline fun <T, R : Comparable<R>> Iterable<T>.minByAndValue(crossinline selector: (T) -> R) = asSequence().map { it to selector(it) }.minBy { it.second }
fun main() = repeat(1) { println(solve()) }
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 753 | competitions | The Unlicense |
calendar/day09/Day9.kt | maartenh | 572,433,648 | false | {"Kotlin": 50914} | package day09
import Day
import Lines
import day09.Move.*
import kotlin.math.abs
class Day9 : Day() {
override fun part1(input: Lines): Any {
val moves = readMoves(input)
val board = Board(arrayOf(0 to 0, 0 to 0))
val allTailPositions = moves.map { move ->
board.execute(move)
board.knots.last()
}
return allTailPositions.toSet().size
}
override fun part2(input: Lines): Any {
val moves = readMoves(input)
val rope = Array(10) { 0 to 0 }
val board = Board(rope)
val allTailPositions = moves.map { move ->
board.execute(move)
board.knots.last()
}
return allTailPositions.toSet().size
}
private fun readMoves(input: Lines): List<Move> {
return input.flatMap { line ->
val direction = line[0].toMove()
val count = line.substring(2).toInt()
(1..count).map { direction }
}
}
private fun Char.toMove() =
when (this) {
'U' -> Up
'D' -> Down
'L' -> Left
'R' -> Right
else -> throw AssertionError("Invalid input direction $this")
}
}
typealias Position = Pair<Int, Int>
class Board(val knots: Array<Position>) {
fun execute(move: Move) {
knots[0] = when (move) {
Up -> knots[0].copy(second = knots[0].second + 1)
Down -> knots[0].copy(second = knots[0].second - 1)
Left -> knots[0].copy(first = knots[0].first - 1)
Right -> knots[0].copy(first = knots[0].first + 1)
}
for (i in 1 until knots.size) {
if (!knots[i].isAdjacentTo(knots[i - 1])) {
knots[i] = knots[i].moveTowards(knots[i - 1])
}
}
}
}
private fun Position.isAdjacentTo(target: Position) =
abs(this.first - target.first) <= 1 &&
abs(this.second - target.second) <= 1
private fun Position.moveTowards(target: Position): Position {
val newFirst = when {
first < target.first -> first + 1
first > target.first -> first - 1
else -> first
}
val newSecond = when {
second < target.second -> second + 1
second > target.second -> second - 1
else -> second
}
return Position(newFirst, newSecond)
}
enum class Move {
Up, Down, Left, Right
} | 0 | Kotlin | 0 | 0 | 4297aa0d7addcdc9077f86ad572f72d8e1f90fe8 | 2,409 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} |
fun main() {
fun common_element_in_line(line: String): Char {
line.length
val compartments = Pair(line.take(line.length/2).toSet(), line.substring(line.length/2).toSet())
val intersection = compartments.first.intersect(compartments.second)
return intersection.first()
}
fun value(intersection: Char): Int {
if (intersection.isLowerCase()) {
return intersection - 'a' + 1
} else {
return intersection - 'A' + 27
}
}
fun part1(input: List<String>): Int {
return input.map { value(common_element_in_line(it)) }.reduce { acc, i -> acc + i }
}
fun part2(input: List<String>): Int {
return (0 until input.size step 3).map {
value(input[it].toSet().intersect(input[it+1].toSet().intersect(input[it+2].toSet())).first())
}.reduce { acc, intersection -> acc + intersection }
}
val input = readInput("day3_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 1,014 | 2022-aoc-kotlin | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions53.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round0
fun test53() {
val array1 = intArrayOf(1, 2, 3, 3, 3, 4, 5, 6)
val array2 = intArrayOf(1, 2, 3, 4, 5, 6, 6, 6)
val array3 = intArrayOf(1, 1, 1, 2, 3, 4, 5, 6)
println("数字3出现的次数为:${getNumberOfK(array1, 3)}")
println("数字6出现的次数为:${getNumberOfK(array2, 6)}")
println("数字1出现的次数为:${getNumberOfK(array3, 1)}")
println()
val array4 = intArrayOf(0, 1, 2, 3, 4, 6, 7, 8)
val array5 = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8)
println("缺少的数字为:${getMissingNumber(array4)}")
println("缺少的数字为:${getMissingNumber(array5)}")
println()
val array6 = intArrayOf(-3, -1, 1, 3, 5)
println("下标和值相等的数字为:${getNumberSameAsIndex(array6)}")
}
/**
* 题目一:寻找一个排序数组中某一个数字出现的次数
*/
fun getNumberOfK(array: IntArray, k: Int): Int =
getLastK(array, k, 0, array.size - 1) - getFirstK(array, k, 0, array.size - 1) + 1
private fun getFirstK(array: IntArray, k: Int, first: Int, last: Int): Int {
val mod = (first + last) / 2
if (k > array[mod]) {
return getFirstK(array, k, mod, last)
} else if (k < array[mod]) {
return getFirstK(array, k, first, mod)
} else if (mod - 1 < 0 || array[mod-1] != k) {
return mod
} else {
return getFirstK(array, k, first, mod)
}
}
private fun getLastK(array: IntArray, k: Int, first: Int, last: Int): Int {
val mod = (first + last) / 2
if (mod == first) {
return last
}
if (k > array[mod]) {
return getLastK(array, k, mod, last)
} else if (k < array[mod]) {
return getLastK(array, k, first, mod)
} else if (mod + 1 >= array.size || array[mod+1] != k) {
return mod
} else {
return getLastK(array, k, mod, last)
}
}
/**
* 题目二:在一个递增排序的数组中找出缺失的数字
*/
fun getMissingNumber(array: IntArray): Int = binarySearch(array, 0, array.size - 1)
private fun binarySearch(array: IntArray, first: Int, last: Int): Int {
val mod = (first + last) / 2
return when {
mod == array[mod] -> binarySearch(array, mod, last)
mod == 0 || mod - 1 == array[mod - 1] -> mod
else -> binarySearch(array, first, mod)
}
}
/**
* 题目三:在一个递增排序切没有元素重复的数组中找出下标和值相等的数字
*/
fun getNumberSameAsIndex(array: IntArray): Int {
var first = 0
var last = array.size - 1
var mod = (first + last) / 2
while (array[mod] != mod) {
if (array[mod] > mod) {
last = mod
} else {
first = mod
}
mod = (first + last) / 2
}
return mod
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,553 | Algorithm | Apache License 2.0 |
src/main/kotlin/aoc/Day08.kt | fluxxion82 | 573,716,300 | false | {"Kotlin": 39632} | package aoc
import aoc.utils.readInput
data class Tree(val value: Int, var scenicValue: Int = 0, var isVisible: Boolean? = null)
enum class Direction {
UP, RIGHT, LEFT, DOWN
}
fun main() {
val testInput = readInput("Day08_test.txt")
val input = readInput("Day08.txt")
fun part1(input: List<String>): Int {
val seq = input
val grid = mutableListOf<List<Tree>>()
seq.forEach {
grid.add(
it.toCharArray().map { char ->
Tree(char.digitToInt())
}
)
}
for (i in 0 until grid.size) {
for (k in 0 until grid[0].size) {
checkDirectionHeight(grid, i, k, Direction.RIGHT)
checkDirectionHeight(grid, i, k, Direction.LEFT)
checkDirectionHeight(grid, i, k, Direction.DOWN)
checkDirectionHeight(grid, i, k, Direction.UP)
}
}
return grid.sumOf { rows ->
rows.count { tree ->
tree.isVisible == true
}
}
}
fun part2(input: List<String>): Int {
val seq = input
val grid = mutableListOf<List<Tree>>()
seq.forEach {
grid.add(
it.toCharArray().map { char ->
Tree(char.digitToInt())
}
)
}
var scenicValue = 0
for (i in 0 until grid.size) {
for (k in 0 until grid[0].size) {
var first = checkDirectionScenic(grid, i, k, Direction.RIGHT)
first *= checkDirectionScenic(grid, i, k, Direction.LEFT)
first *= checkDirectionScenic(grid, i, k, Direction.DOWN)
first *= checkDirectionScenic(grid, i, k, Direction.UP)
if (first > scenicValue) scenicValue = first
}
}
return scenicValue
}
println("part one test: ${part1(testInput)}") // 21
println("part one: ${part1(input)}") // 1695
println("part two test: ${part2(testInput)}") // 8
println("part two: ${part2(input)}") // 287040
}
fun decreaseRowScanHeight(grid: MutableList<List<Tree>>, column: Int) {
var height = -1
for (i in grid.size- 1 downTo 0) {
val curr = grid[i][column]
if (curr.value > height) {
curr.isVisible = true
height = curr.value
}
}
}
fun increaseRowScanHeight(grid: MutableList<List<Tree>>, column: Int) {
var height = -1
for (i in 0 until grid[0].size) {
val curr = grid[i][column]
if (curr.value > height) {
curr.isVisible = true
height = curr.value
}
}
}
fun increaseColumnIndexScanHeight(grid: MutableList<List<Tree>>, row: Int) {
var height = -1
for (i in 0 until grid[0].size) {
val curr = grid[row][i]
if (curr.value > height) {
curr.isVisible = true
height = curr.value
}
}
}
fun decreaseColumnScanHeight(grid: MutableList<List<Tree>>, row: Int) {
var height = -1
for (i in grid.size- 1 downTo 0) {
val curr = grid[row][i]
if (curr.value > height) {
curr.isVisible = true
height = curr.value
}
}
}
fun checkDirectionHeight(grid: MutableList<List<Tree>>, row: Int, column: Int, direction: Direction) {
when(direction) {
Direction.DOWN -> increaseRowScanHeight(grid, column)
Direction.UP-> decreaseRowScanHeight(grid, column)
Direction.RIGHT -> increaseColumnIndexScanHeight(grid, row)
Direction.LEFT -> decreaseColumnScanHeight(grid, row)
}
}
fun decreaseRowScanScenic(grid: MutableList<List<Tree>>, row: Int, column: Int): Int {
var scenicValue = row
for (i in row - 1 downTo 0) {
val next = grid[i][column]
val curr = grid[row][column]
if (next.value >= curr.value) {
scenicValue = row - i
break
}
}
return scenicValue
}
fun increaseRowScanScenic(grid: MutableList<List<Tree>>, row: Int, column: Int): Int {
var scenicValue = grid[0].size - row - 1
for (i in row + 1 until grid.size) {
val next = grid[i][column]
val curr = grid[row][column]
if (next.value >= curr.value) {
scenicValue = i - row
break
}
}
return scenicValue
}
fun decreaseColumnScanScenic(grid: MutableList<List<Tree>>, row: Int, column: Int): Int {
var scenicValue = column
for (i in column - 1 downTo 0) {
val next = grid[row][i]
val curr = grid[row][column]
if (next.value >= curr.value) {
scenicValue = column - i
break
}
}
return scenicValue
}
fun increaseColumnIndexScanScenic(grid: MutableList<List<Tree>>, row: Int, column: Int): Int {
var scenicValue = grid.size - column - 1
for (i in column + 1 until grid.size) {
val next = grid[row][i]
val curr = grid[row][column]
if (next.value >= curr.value) {
scenicValue = i - column
break
}
}
return scenicValue
}
fun checkDirectionScenic(grid: MutableList<List<Tree>>, row: Int, column: Int, direction: Direction): Int {
return when(direction) {
Direction.DOWN -> decreaseRowScanScenic(grid, row, column)
Direction.UP-> increaseRowScanScenic(grid, row, column)
Direction.RIGHT -> increaseColumnIndexScanScenic(grid, row, column)
Direction.LEFT -> decreaseColumnScanScenic(grid, row, column)
}
}
| 0 | Kotlin | 0 | 0 | 3920d2c3adfa83c1549a9137ffea477a9734a467 | 5,558 | advent-of-code-kotlin-22 | Apache License 2.0 |
src/Day05.kt | shoresea | 576,381,520 | false | {"Kotlin": 29960} | import java.util.*
fun main() {
fun generateStacks(inputs: List<String>): ArrayList<Stack<Char>> {
val stacksCount = (inputs[0].length / 4) + 1
//println("StacksCount :: $stacksCount")
val stacks = ArrayList<Stack<Char>>()
for (i in 1..stacksCount) {
stacks.add(Stack<Char>())
}
for (input in inputs) {
if (input.trim().startsWith("1")) {
break
} else {
val row = input
.replace(" [", "#[")
.replace("] ", "]#")
.replace(" ", "#")
.let {
if (it.contains("#")) it.split("#") else it.split(" ")
}.map {
it.removeSuffix("]")
.removePrefix("[")
.trim()
}
for ((index, element) in row.withIndex()) {
if (element.isNotEmpty()) {
stacks[index].push(element[0])
}
}
// println(row)
}
}
stacks.forEach { it.reverse() }
//println(stacks)
return stacks
}
fun parseMove(input: String): List<Int> {
return input.replace("move ", "")
.replace(" from ", ",")
.replace(" to ", ",")
.split(",")
.map { it.toInt() }
// .also { println(it) }
}
fun part1(inputs: List<String>): String {
val stacks = generateStacks(inputs)
for (input in inputs) {
if (!input.trim().startsWith("move")) {
continue
}
val move = parseMove(input)
repeat(move[0]) {
val from = stacks[move[1] - 1]
val to = stacks[move[2] - 1]
to.push(from.pop())
}
}
//println(stacks)
return stacks.map { it.peek() }.joinToString("")
}
fun part2(inputs: List<String>): String {
val stacks = generateStacks(inputs)
for (input in inputs) {
if (!input.trim().startsWith("move")) {
continue
}
val move = parseMove(input)
val from = stacks[move[1] - 1]
val to = stacks[move[2] - 1]
(1..move[0]).map { from.pop() }.reversed().forEach { to.push(it) }
}
// println(stacks)
return stacks.map { it.peek() }.joinToString("")
}
val input = readInput("Day05")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | e5d21eac78fcd4f1c469faa2967a4fd9aa197b0e | 2,644 | AOC2022InKotlin | Apache License 2.0 |
src/Day04/Day04.kt | thmsbdr | 574,632,643 | false | {"Kotlin": 6603} | package Day04
import readInput
fun main() {
fun part1(input: List<String>): Int {
var total = 0
input.forEach {
val shifts = it.split(',')
val shiftOne = shifts[0].split('-')
val shiftTwo = shifts[1].split('-')
if (shiftOne[0].toInt() <= shiftTwo[0].toInt()
&& shiftOne[1].toInt() >= shiftTwo[1].toInt()) {
total++
} else if (shiftOne[0].toInt() >= shiftTwo[0].toInt()
&& shiftOne[1].toInt() <= shiftTwo[1].toInt()) {
total++
}
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
input.forEach {
val shifts = it.split(',')
val shiftOne = shifts[0].split('-')
val shiftTwo = shifts[1].split('-')
if (shiftTwo[0].toInt() in shiftOne[0].toInt()..shiftOne[1].toInt()
|| shiftTwo[1].toInt() in shiftOne[0].toInt()..shiftOne[1].toInt()
|| shiftOne[0].toInt() in shiftTwo[0].toInt()..shiftTwo[1].toInt()
|| shiftOne[1].toInt() in shiftTwo[0].toInt()..shiftTwo[1].toInt()) {
total++
}
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04/Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b9ac3ed8b52a95dcc542f4de79fb24163f3929a4 | 1,546 | AoC-2022 | Apache License 2.0 |
src/Day02.kt | rossilor95 | 573,177,479 | false | {"Kotlin": 8837} | fun main() {
// Opponent shapes: A Rock, B Paper, C Scissors
// My shapes: X Rock, Y Paper, Z Scissors
fun part1(input: List<String>): Int {
fun calculateShapeScore(myShape: Char) = when (myShape) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> error("Check your inputs!")
}
fun calculateRoundScore(shapes: String): Int = when (shapes) {
"A Y", "B Z", "C X" -> 6
"A X", "B Y", "C Z" -> 3
"A Z", "B X", "C Y" -> 0
else -> error("Check your inputs!")
}
return input.sumOf { round ->
calculateShapeScore(myShape = round[2]) + calculateRoundScore(round)
}
}
// Opponent shapes: A Rock, B Paper, C Scissors
// Round outcome: X Lose, Y Draw, Z Win
fun part2(input: List<String>): Int {
fun calculateShapeScore(shapes: String): Int = when (shapes) {
"A Y", "B X", "C Z" -> 1 // Rock 1 pt = Draw vs Rock, Lose vs Paper, Win vs Scissors,
"A Z", "B Y", "C X" -> 2 // Paper 2 pts = Win vs Rock, Draw vs Paper, Lose vs Scissors
"A X", "B Z", "C Y" -> 3 // Scissors 3 pts = Lose vs Rock, Win vs Paper, Draw vs Scissors
else -> error("Check your inputs!")
}
fun calculateRoundScore(roundOutcome: Char): Int = when (roundOutcome) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> error("Check your inputs!")
}
return input.sumOf { round ->
calculateShapeScore(round) + calculateRoundScore(roundOutcome = round[2])
}
}
val testInput = readInput("Day02_test")
val input = readInput("Day02")
check(part1(testInput) == 15)
println("Part 1 Answer: ${part1(input)}")
check(part2(testInput) == 12)
println("Part 2 Answer: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | 0ed98d0ab5f44b2ccfc625ef091e736c5c748ff0 | 1,871 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day09.kt | djleeds | 572,720,298 | false | {"Kotlin": 43505} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
import kotlin.properties.Delegates.observable
data class Motion(val direction: String, val count: Int) {
companion object {
fun parse(line: String) = line.split(" ").let { (dir, count) -> Motion(dir, count.toInt()) }
}
}
data class Vector2(val x: Int = 0, val y: Int = 0) {
fun isAdjacentTo(other: Vector2) = max(abs(x - other.x), abs(y - other.y)) <= 1
operator fun plus(other: Vector2) = Vector2(x + other.x, y + other.y)
operator fun minus(other: Vector2) = Vector2(x - other.x, y - other.y)
fun unitSized() = Vector2(x.sign, y.sign)
companion object {
val ORIGIN = Vector2(0, 0)
val UP = Vector2(0, 1)
val DOWN = Vector2(0, -1)
val LEFT = Vector2(-1, 0)
val RIGHT = Vector2(1, 0)
}
}
class Knot(val next: Knot? = null) {
val visited: MutableSet<Vector2> = mutableSetOf(Vector2.ORIGIN)
private var position: Vector2 by observable(Vector2.ORIGIN) { _, _, new ->
if (next?.position?.isAdjacentTo(new) == false) next.position += (new - next.position).unitSized()
visited.add(new)
}
fun tail(): Knot = next?.tail() ?: this
fun move(motion: Motion) = repeat(motion.count) {
position += when (motion.direction) {
"L" -> Vector2.LEFT
"R" -> Vector2.RIGHT
"U" -> Vector2.UP
"D" -> Vector2.DOWN
else -> throw IllegalArgumentException()
}
}
companion object {
fun chain(knotCount: Int): Knot = (1 until knotCount).fold(Knot()) { acc, _ -> Knot(acc) }
}
}
fun main() {
fun solve(input: List<String>, size: Int) =
Knot.chain(size).apply { input.map(Motion::parse).forEach(::move) }.tail().visited.size
fun part1(input: List<String>) = solve(input, 2)
fun part2(input: List<String>) = solve(input, 10)
val testInput = readInput("Day09_test")
println(part1(testInput))
println(part2(listOf("R 5", "U 8", "L 8", "D 3", "R 17", "D 10", "L 25", "U 20")))
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 4 | 98946a517c5ab8cbb337439565f9eb35e0ce1c72 | 2,160 | advent-of-code-in-kotlin-2022 | Apache License 2.0 |
src/Day05.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} |
fun main() { // ktlint-disable filename
fun calcTopCrates(input: List<String>, multiMove: Boolean = false): String {
var stackCountIndex = 0
var stackCount = 0
for (i in input.indices) {
if (input[i].startsWith(" 1 ")) {
stackCount = input[i].split("").filter { it.isNotBlank() }.size
stackCountIndex = i
break
}
}
// crate positions are always at 1, 5, 9, etc.
val stacks = Array<ArrayDeque<Char>>(stackCount) { ArrayDeque() }
for (i in stackCountIndex downTo 0) {
for (j in 1 until input[i].length step 4) {
val crateId = input[i][j]
if (crateId != ' ') {
val stackNum = (j - 1) / 4
stacks[stackNum].add(crateId)
}
}
}
for (i in stackCountIndex + 2 until input.size) {
// move 1 from 2 to 1
val tokens = input[i].split(" ")
val count = tokens[1].toInt()
val from = tokens[3].toInt() - 1
val to = tokens[5].toInt() - 1
val crates = stacks[from].takeLast(count) // gets in-order list of last N crates
for (i in 0 until count) {
stacks[from].removeLast()
}
stacks[to].addAll(if (multiMove) crates else crates.reversed())
}
val result = StringBuilder()
for (stack in stacks) {
if (stack.isNotEmpty()) {
result.append(stack.last())
}
}
return result.toString()
}
fun part1(input: List<String>): String {
return calcTopCrates(input)
}
fun part2(input: List<String>): String {
return calcTopCrates(input, multiMove = true)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
println("test result top crates: ${part1(testInput)}")
check(part1(testInput) == "CMZ")
println("test result multi-move top crates is: ${part2(testInput)}")
check(part2(testInput) == "MCD")
val input = readInput("Day05_input")
println("Top crates is: ${part1(input)}")
println("Multi-move top crates is: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 2,298 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/Day07.kt | jbotuck | 573,028,687 | false | {"Kotlin": 42401} | import java.math.BigInteger
fun main() {
val lines = readInput("Day07")
solve(lines)
}
private fun solve(lines: List<String>) {
@Suppress("NAME_SHADOWING")
val lines = ArrayDeque(lines)
val lastVisited = ArrayDeque<Directory>()
val root = Directory("root")
val allFiles = mutableListOf<SystemObject>()
while (lines.isNotEmpty()) {
when (val line = lines.removeFirst()) {
"\$ ls" -> {
lines
.takeWhile { !it.startsWith('$') }
.also { lines.subList(0, it.size).clear() }
.let { lastVisited.last().updateWithLsOutput(it) }
.let { allFiles.addAll(it) }
}
"\$ cd .." -> {
lastVisited.removeLast()
lastVisited.lastOrNull()?.recalculateSize()
}
"\$ cd /" -> { //only happens once in my input so not bothering to back up one level at a time
lastVisited.add(root)
}
else -> lastVisited.add(lastVisited.last().cd(line.substringAfter("\$ cd ")))
}
}
while (lastVisited.isNotEmpty()) lastVisited.removeLast().apply { recalculateSize() }
val part1 =
allFiles
.filterIsInstance<Directory>()
.map { it.size!! }
.filter { it < BigInteger("100000") }
.sumOf { it }
println("part 1 $part1")
val freeSpaceStillNeeded = BigInteger("30000000").minus(BigInteger("70000000").minus(root.size!!))
val part2 = allFiles
.filterIsInstance<Directory>()
.map { it.size!! }
.filter { it >= freeSpaceStillNeeded }
.min()
println("part 2 $part2")
}
private sealed class SystemObject(
val name: String,
open val size: BigInteger?
) {
companion object {
fun of(lsOutput: String): SystemObject {
val split = lsOutput.split(" ")
if (split.first() == "dir") return Directory(split.last())
return DataFile(split.last(), BigInteger(split.first()))
}
}
}
private class DataFile(name: String, size: BigInteger) : SystemObject(name, size)
private class Directory(name: String) : SystemObject(name, null) {
override var size: BigInteger? = super.size
val children = mutableMapOf<String, SystemObject>()
fun updateWithLsOutput(files: List<String>): List<SystemObject> {
return files
.map { of(it) }
.filter { it.name !in children.keys }
.also { list ->
for (file in list) children[file.name] = file
recalculateSize()
}
}
fun recalculateSize() {
if (size != null) return
size = children.values.sumOf { it.size ?: return }
}
fun cd(directory: String): Directory {
return children[directory] as? Directory ?: Directory(directory).also {
children[directory] = it
}
}
} | 0 | Kotlin | 0 | 0 | d5adefbcc04f37950143f384ff0efcd0bbb0d051 | 2,954 | aoc2022 | Apache License 2.0 |
src/main/aoc2020/Day23.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2020
class Day23(input: String) {
private val nineCups = input.map { it.toString().toInt() }
private val millionCups = (0 until 1_000_000).map {
if (it < 9) input[it].toString().toInt() else it + 1
}
// cups: (3) 8 9 1 2 5 4 6 7
// Index: 1, 2, 3, 4, 5, 6, 7, 8, 9
// value: 2 5 8 6 4 7 3 9 1
private data class Cups(val capacity: Int) {
// Index = cup (label), value = index of next cup
val data = IntArray(capacity + 1) // item at position 0 is not used, cup 1 is at index 1.
fun init(input: List<Int>) {
input.indices.forEach { index ->
data[input[index]] = input[(index + 1) % input.size]
}
}
fun print(): String {
var ret = ""
var label = 1
repeat(capacity - 1) {
val next = data[label]
ret += next
label = next
}
return ret
}
}
/**
* There is only remove/insert and access based on cup name, so use
* an array based linked list. The index of the array is the label
* of the cup (which we need to access) and the value is a pointer
* to the next item in the list.
*/
private fun play(moves: Int, cups: Cups, startCup: Int): Cups {
var currentCup = startCup
repeat(moves) {
val firstRemoved = cups.data[currentCup]
val middleRemoved = cups.data[firstRemoved]
val lastRemoved = cups.data[middleRemoved]
val afterRemoval: Int = cups.data[lastRemoved]
val destinationCup = generateSequence(currentCup) { if (it == 1) cups.capacity else it - 1 }
.drop(1)
.first { it !in listOf(firstRemoved, middleRemoved, lastRemoved) }
val afterDestinationCup = cups.data[destinationCup]
cups.data[currentCup] = afterRemoval
cups.data[destinationCup] = firstRemoved
cups.data[lastRemoved] = afterDestinationCup
currentCup = afterRemoval
}
return cups
}
fun solvePart1(): String {
val cups = Cups(9).apply { init(nineCups) }
play(100, cups, nineCups.first())
return cups.print()
}
fun solvePart2(): Long {
val cups = Cups(1_000_000).apply { init(millionCups) }
play(10_000_000, cups, millionCups.first())
return cups.data[1].toLong() * cups.data[cups.data[1]].toLong()
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,523 | aoc | MIT License |
src/main/kotlin/biz/koziolek/adventofcode/year2021/day11/day11.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2021.day11
import biz.koziolek.adventofcode.*
import java.util.*
fun main() {
val inputFile = findInput(object {})
val lines = inputFile.bufferedReader().readLines()
val map = parseOctopusMap(lines)
println("Flashes after 100 steps: ${countFlashes(map, maxStep = 100)}")
println("First step all flash: ${nextTimeAllFlash(map)}")
}
data class Octopus(val energy: Int, val flashed: Boolean = false) {
fun increaseEnergy(): Octopus {
if (flashed) {
return this
}
val newEnergy = energy.inc()
val flashed = (newEnergy > 9)
return copy(
energy = if (flashed) 0 else newEnergy,
flashed = flashed
)
}
}
fun parseOctopusMap(lines: List<String>): Map<Coord, Octopus> =
lines.parse2DMap { Octopus(it.digitToInt()) }.toMap()
fun countFlashes(map0: Map<Coord, Octopus>, maxStep: Int): Int =
generateSequence(map0) { map -> calculateNextStep(map) }
.take(maxStep + 1)
.sumOf { map -> map.values.count { octopus -> octopus.flashed } }
fun nextTimeAllFlash(map0: Map<Coord, Octopus>): Int =
generateSequence(map0) { map -> calculateNextStep(map) }
.takeWhile { map -> !map.values.all { octopus -> octopus.flashed } }
.count()
fun calculateNextStep(map: Map<Coord, Octopus>): Map<Coord, Octopus> {
return buildMap {
map.forEach { (coord, octopus) ->
put(coord, octopus.copy(flashed = false))
}
val toVisit: Queue<Coord> = ArrayDeque(map.keys)
var currentCoord: Coord? = toVisit.remove()
while (currentCoord != null) {
computeIfPresent(currentCoord) { coord, octopus ->
val newOctopus = octopus.increaseEnergy()
if (!octopus.flashed && newOctopus.flashed) {
toVisit.addAll(this.getAdjacentCoords(coord, includeDiagonal = true))
}
newOctopus
}
currentCoord = toVisit.poll()
}
}
}
fun toString(map: Map<Coord, Octopus>, color: Boolean = true): String {
val width = map.getWidth()
val height = map.getHeight()
return buildString {
for (y in 0 until height) {
for (x in 0 until width) {
val octopus = map[Coord(x, y)]
if (octopus != null) {
if (octopus.flashed) {
if (color) {
append(AsciiColor.BRIGHT_WHITE.format(octopus.energy))
} else {
append(octopus.energy)
}
} else {
append(octopus.energy.toString())
}
} else {
if (color) {
append(AsciiColor.BRIGHT_BLACK.format("?"))
} else {
append("?")
}
}
}
if (y < height - 1) {
append("\n")
}
}
}
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 3,104 | advent-of-code | MIT License |
src/main/kotlin/aoc2017/SpiralMemory.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2017
fun spiralMemorySteps(index: Int): Int =
distances().drop(index - 1).first()
private fun distances(): Sequence<Int> = sequence {
yield(0)
for (n in 1..Int.MAX_VALUE) {
repeat(4) {
for (v in n * 2 - 1 downTo n)
yield(v)
for (v in (n + 1)..n * 2)
yield(v)
}
}
}
typealias Coordinate = Pair<Int, Int>
fun spiralPart2(input: Int): Int {
val memory = mutableMapOf<Coordinate, Int>()
memory[Coordinate(0, 0)] = 1
for (coord in coordinates()) {
val sum = coord.neighbors().sumBy { memory[it] ?: 0 }
if (sum > input)
return sum
memory[coord] = sum
}
error("unexpected")
}
fun coordinates(): Sequence<Coordinate> = sequence {
var x = 0
var y = 0
yield(Coordinate(++x, y))
var n = 1
while (true) {
repeat(n) {
yield(Coordinate(x, ++y))
}
repeat(n + 1) {
yield(Coordinate(--x, y))
}
repeat(n + 1) {
yield(Coordinate(x, --y))
}
repeat(n + 2) {
yield(Coordinate(++x, y))
}
n += 2
}
}
private fun Coordinate.neighbors(): List<Coordinate> =
neighborDeltas.map { this + it }
private operator fun Coordinate.plus(d: Pair<Int, Int>): Coordinate =
Coordinate(first + d.first, second + d.second)
private val neighborDeltas = listOf(
Pair(0, 1), Pair(-1, 1),
Pair(-1, 0), Pair(-1, -1),
Pair(0, -1), Pair(1, -1),
Pair(1, 0), Pair(1, 1))
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,591 | advent-of-code | MIT License |
src/day17/a/day17a.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day17.a
import readInputLines
import shouldBe
import util.IntVector
import vec2
import java.lang.Integer.max
import java.util.*
val shapes = listOf(
listOf(vec2(0,0),vec2(1,0),vec2(2,0),vec2(3,0)),
listOf(vec2(1,0),vec2(0,1),vec2(1,1),vec2(2,1), vec2(1,2)),
listOf(vec2(2,2),vec2(2,1),vec2(2,0),vec2(1,0), vec2(0,0)),
listOf(vec2(0,0),vec2(0,1),vec2(0,2),vec2(0,3)),
listOf(vec2(0,0),vec2(1,0),vec2(0,1),vec2(1,1)),
)
val shapeSize = listOf(vec2(4,1), vec2(3,3), vec2(3,3),vec2(1,4), vec2(2,2))
fun main() {
val grid = Grid()
for (x in 0..6) grid[x,0] = true
val input = read()
val oneDown = vec2(0,-1)
var top = 0
var shapeIdx = 0
var jetIdx = 0
for (i in 0 until 2022) {
//add shape
val shape = shapes[shapeIdx]
val size = shapeSize[shapeIdx]
var p = vec2(2, top+4)
do {
val jet = input[jetIdx].let { when(it) { '<' -> vec2(-1,0); '>' -> vec2(1,0); else -> throw RuntimeException() } }
jetIdx = (jetIdx + 1) % input.length
val collide = shape.any { grid[it+p+jet] }
if (!collide) p += jet
val stop = shape.any { grid[it+p+oneDown] }
if (!stop) p += oneDown
} while(!stop)
top = max(top, p[1] + size[1] - 1)
for (q in shape) grid[q+p] = true
shapeIdx = (shapeIdx + 1) % 5
}
shouldBe(3232, top)
}
class Grid {
private val grid = BitSet()
operator fun get(p: IntVector) : Boolean {
return get(p[0], p[1])
}
operator fun get(x: Int, y: Int) : Boolean {
if (x !in 0..6) return true
val i = x + (y * 7)
return grid[i]
}
operator fun set(p: IntVector, b: Boolean) {
set(p[0], p[1], b)
}
operator fun set(x: Int, y: Int, b: Boolean) {
val i = x + (y * 7)
grid[i] = b
}
}
fun show(grid: Grid, top: Int) {
for (y in top downTo 0) {
if (y == 0) {
println("+-------+")
} else {
print('|')
for (x in 0..6)
print(if (grid[x, y]) '#' else ' ')
println('|')
}
}
}
fun read(): String {
return readInputLines(17)[0]
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 2,216 | advent-of-code-2022 | Apache License 2.0 |
src/Day20.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | import kotlin.math.sign
private fun <T: Number> MutableList<IndexedValue<T>>.mixOn(number: IndexedValue<T>) {
var pos = this.indexOf(number) // O(n)
val n = this.size
var shift = (number.value.toLong() % (n - 1)).toInt()
while (shift != 0) { // O(n). Awful!
val newPos = ((pos + shift.sign) % n + n) % n
val tmp = this[newPos]
this[newPos] = this[pos]
this[pos] = tmp
pos = newPos
shift -= shift.sign
}
}
fun main() {
fun part1(input: List<String>): Int {
val order = input.map { it.toInt() }
val data = order.withIndex().toMutableList()
for (num in order.withIndex()) {
data.mixOn(num)
}
val zero = data.indexOf(IndexedValue(order.indexOf(0), 0))
return data[(zero + 1000) % data.size].value + data[(zero + 2000) % data.size].value + data[(zero + 3000) % data.size].value
}
fun part2(input: List<String>): Long {
val order = input.map { it.toLong() * 811589153 }
val data = order.withIndex().toMutableList()
repeat(10) {
for (num in order.withIndex()) {
data.mixOn(num)
}
}
val zero = data.indexOf(IndexedValue(order.indexOf(0), 0))
return data[(zero + 1000) % data.size].value + data[(zero + 2000) % data.size].value + data[(zero + 3000) % data.size].value
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
check(part1(testInput) == 3)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 1,684 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day09.kt | lassebe | 573,423,378 | false | {"Kotlin": 33148} | import kotlin.math.abs
import kotlin.math.min
fun main() {
val map = (0..40).map { i ->
(0..40).map { j -> j }
}
fun printMap(head: Pair<Int, Int>, tail: Pair<Int, Int>, visited: Map<Pair<Int, Int>, Boolean>) {
// return
map.indices.forEach { i ->
var symbol = " . "
map[0].indices.forEach { j ->
if (tail.first == i && tail.second == j)
symbol = "T"
if (head.first == i && head.second == j)
symbol = "H"
if (visited.getOrDefault(Pair(i, j), false))
symbol = "#"
print(symbol)
symbol = "."
}
println()
}
println()
}
fun moveTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
val xDistance = abs(head.first - tail.first)
val yDistance = abs(head.second - tail.second)
if (xDistance + yDistance < 2 || xDistance == 1 && yDistance == 1)
return tail
var xPos = tail.first
var yPos = tail.second
if (xDistance >= 1) {
if (head.first > tail.first) {
xPos += 1
} else {
xPos -= 1
}
}
if (yDistance >= 1) {
if (head.second > tail.second) {
yPos += 1
} else {
yPos -= 1
}
}
return Pair(xPos, yPos)
}
fun part1(input: List<String>): Int {
var head = Pair(0, 0)
var tail = Pair(0, 0)
val visited = mutableMapOf<Pair<Int, Int>, Boolean>()
input.forEach { line ->
val (dir, l) = line.split(" ")
val length = l.toInt()
when (dir) {
"R" -> {
repeat((0 until length).count()) {
head = Pair(head.first, head.second + 1)
tail = moveTail(head, tail)
visited[tail] = true
}
}
"U" -> {
repeat((0 until length).count()) {
head = Pair(head.first + 1, head.second)
tail = moveTail(head, tail)
visited[tail] = true
}
}
"L" -> {
repeat((0 until length).count()) {
head = Pair(head.first, head.second - 1)
tail = moveTail(head, tail)
visited[tail] = true
}
}
"D" -> {
repeat((0 until length).count()) {
head = Pair(head.first - 1, head.second)
tail = moveTail(head, tail)
visited[tail] = true
}
}
}
}
return visited.count { (_, v) -> v }
}
fun moveRopeSegment(rope: MutableList<Pair<Int, Int>>) {
(1 until rope.size).forEach { i ->
rope[i] = moveTail(rope[i - 1], rope[i])
}
}
fun part2(input: List<String>): Int {
var xOffset = 0
var yOffset = 0
var rope = mutableListOf<Pair<Int,Int>>()
repeat(10) {
rope.add(Pair(0,0))
}
val visited = mutableMapOf<Pair<Int, Int>, Boolean>()
input.forEach { line ->
val (dir, l) = line.split(" ")
val length = l.toInt()
when (dir) {
"R" -> {
repeat((0 until length).count()) {
rope[0] = Pair(rope[0].first, rope[0].second + 1)
moveRopeSegment(rope)
visited[rope.last()] = true
}
}
"U" -> {
repeat((0 until length).count()) {
rope[0] = Pair(rope[0].first + 1, rope[0].second)
moveRopeSegment(rope)
visited[rope.last()] = true
}
}
"L" -> {
repeat((0 until length).count()) {
rope[0] = Pair(rope[0].first, rope[0].second - 1)
moveRopeSegment(rope)
visited[rope.last()] = true
}
}
"D" -> {
repeat((0 until length).count()) {
rope[0] = Pair(rope[0].first - 1, rope[0].second)
moveRopeSegment(rope)
visited[rope.last()] = true
}
}
}
xOffset = min(xOffset, rope[0].first)
yOffset = min(yOffset, rope[0].second)
}
return visited.count { (_, v) -> v }
}
val testInput = readInput("Day09_test")
expect(13, part1(testInput))
val input = readInput("Day09")
println(part1(input))
expect(6311, part1(input))
expect(1, part2(testInput))
expect(36, part2(readInput("Day09_test2")))
println(part2(input))
expect(2482, part2(input))
} | 0 | Kotlin | 0 | 0 | c3157c2d66a098598a6b19fd3a2b18a6bae95f0c | 5,233 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/days/Day8.kt | hughjdavey | 725,972,063 | false | {"Kotlin": 76988} | package days
import kotlin.math.max
class Day8 : Day(8) {
private val instructions = getInstructions(inputString.takeWhile { it == 'L' || it == 'R' })
private val network = getNetwork(inputList.drop(2))
override fun partOne(): Any {
return navigateSteps()
}
override fun partTwo(): Any {
return navigateGhostSteps()
}
private fun navigateSteps(): Long {
val startNode = network.find { it.name == "AAA" }!!
return countSteps(startNode = startNode) { it == "ZZZ" }
}
// public and takes instructions and network params for testing
fun navigateGhostSteps(instructions: Sequence<Char> = this.instructions, network: List<Node> = this.network): Long {
val startNodes = network.filter { it.name.endsWith('A') }
val cycles = startNodes.map { countSteps(instructions, network, it) { name -> name.endsWith('Z') } }
return lowestCommonMultiple(cycles)
}
// implementation inspired by https://www.baeldung.com/kotlin/lcm
private fun lowestCommonMultiple(numbers: List<Long>): Long {
return numbers.reduce { result, number -> lowestCommonMultiple(result, number) }
}
// implementation inspired by https://www.baeldung.com/kotlin/lcm
private fun lowestCommonMultiple(a: Long, b: Long): Long {
val maxNumber = max(a, b)
val maxLcm = a * b
var lcm = maxNumber
while (lcm <= maxLcm) {
if (lcm % a == 0L && lcm % b == 0L) {
return lcm
}
lcm += maxNumber
}
return maxLcm
}
private fun countSteps(instructions: Sequence<Char> = this.instructions, network: List<Node> = this.network, startNode: Node, isTargetName: (String) -> Boolean): Long {
return instructions.scan(startNode) { node, instruction ->
val next = if (instruction == 'L') node.left else node.right
network.find { it.name == next }!!
}.takeWhile { !isTargetName(it.name) }.toList().size.toLong()
}
fun getInstructions(instructionString: String): Sequence<Char> {
return generateSequence(0) { (it + 1) % instructionString.length }.map { instructionString[it] }
}
fun getNetwork(nodeList: List<String>): List<Node> {
return nodeList.map { node ->
val (name, left, right) = Regex("([A-Z0-9]{3})").findAll(node).toList().map { it.value }
Node(name, left, right)
}
}
data class Node(val name: String, val left: String, val right: String)
}
| 0 | Kotlin | 0 | 0 | 330f13d57ef8108f5c605f54b23d04621ed2b3de | 2,541 | aoc-2023 | Creative Commons Zero v1.0 Universal |
plugin/src/main/kotlin/com/jraska/module/graph/DependencyGraph.kt | eugene-krivobokov | 414,538,867 | true | {"Kotlin": 40462} | package com.jraska.module.graph
class DependencyGraph private constructor() {
private val nodes = mutableMapOf<String, Node>()
fun findRoot(): Node {
require(nodes.isNotEmpty()) { "Dependency Tree is empty" }
val rootCandidates = nodes().toMutableSet()
nodes().flatMap { it.dependsOn }
.forEach { rootCandidates.remove(it) }
return rootCandidates.associateBy { heightOf(it.key) }
.maxByOrNull { it.key }!!.value
}
fun nodes(): Collection<Node> = nodes.values
fun dependencyPairs(): List<Pair<String, String>> {
return nodes()
.flatMap { parent ->
parent.dependsOn.map { dependency -> parent to dependency }
}
.map { it.first.key to it.second.key }
}
fun longestPath(): LongestPath {
return longestPath(findRoot().key)
}
fun longestPath(key: String): LongestPath {
val nodeNames = nodes.getValue(key)
.longestPath()
.map { it.key }
return LongestPath(nodeNames)
}
fun height(): Int {
return heightOf(findRoot().key)
}
fun heightOf(key: String): Int {
return nodes.getValue(key).height()
}
fun statistics(): GraphStatistics {
val height = height()
val edgesCount = countEdges()
return GraphStatistics(
modulesCount = nodes.size,
edgesCount = edgesCount,
height = height,
longestPath = longestPath()
)
}
fun subTree(key: String): DependencyGraph {
require(nodes.contains(key)) { "Dependency Tree doesn't contain module: $key" }
val dependencyTree = createSingular(key)
addConnections(nodes.getValue(key), dependencyTree)
return dependencyTree
}
private fun addConnections(node: Node, into: DependencyGraph) {
node.dependsOn.forEach {
into.addEdge(node.key, it.key)
addConnections(it, into)
}
}
private fun addEdge(from: String, to: String) {
getOrCreate(from).dependsOn.add(getOrCreate(to))
}
private fun countEdges(): Int {
return nodes().flatMap { node -> node.dependsOn }.count()
}
private fun getOrCreate(key: String): Node {
return nodes[key] ?: Node(key).also { nodes[key] = it }
}
class Node(val key: String) {
val dependsOn = mutableSetOf<Node>()
private fun isLeaf() = dependsOn.isEmpty()
fun height(): Int {
if (isLeaf()) {
return 0
} else {
return 1 + dependsOn.map { it.height() }.maxOrNull()!!
}
}
internal fun longestPath(): List<Node> {
if (isLeaf()) {
return listOf(this)
} else {
val path = mutableListOf<Node>(this)
val maxHeightNode = dependsOn.maxByOrNull { it.height() }!!
path.addAll(maxHeightNode.longestPath())
return path
}
}
}
companion object {
fun createSingular(singleModule: String): DependencyGraph {
val dependencyGraph = DependencyGraph()
dependencyGraph.getOrCreate(singleModule)
return dependencyGraph
}
fun create(dependencies: List<Pair<String, String>>): DependencyGraph {
if (dependencies.isEmpty()) {
throw IllegalArgumentException("Graph cannot be empty. Use createSingular for cases with no dependencies")
}
val graph = DependencyGraph()
dependencies.forEach { graph.addEdge(it.first, it.second) }
return graph
}
fun create(vararg dependencies: Pair<String, String>): DependencyGraph {
return create(dependencies.asList())
}
}
}
| 0 | null | 0 | 0 | 22c81583fa04a77074b8cc1f50483273c6f3485d | 3,441 | modules-graph-assert | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-15.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 java.util.*
fun main() {
val input = readInputLines(2021, "15-input")
val test1 = readInputLines(2021, "15-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 cave = input.map { line ->
line.map { it.digitToInt() }
}
return findPathRisk(cave)
}
private fun part2(input: List<String>): Int {
val smallCave = input.map { line ->
line.map { it.digitToInt() }
}
val width = smallCave.first().size
val height = smallCave.size
val cave = List(height * 5) { mutableListOf<Int>() }
repeat(5) { vertical ->
repeat(5) { horizontal ->
val startY = vertical * width
smallCave.forEachIndexed { col, line ->
cave[startY + col] += line.map {
val new = it + horizontal + vertical
if (new <= 9) new else new % 9
}
}
}
}
return findPathRisk(cave)
}
private fun findPathRisk(cave: List<List<Int>>): Int {
val end = Coord2D(cave[cave.lastIndex].lastIndex, cave.lastIndex)
val minDists = Array(cave.size) {
Array(cave[it].size) { -1 }
}
minDists[0][0] = 0
val queue = PriorityQueue(
compareBy<Coord2D> { minDists[it.y][it.x] }
.thenBy { (end.y - it.y) + (end.x - it.x) }
)
queue.add(Coord2D(0, 0))
while (queue.isNotEmpty()) {
val next = queue.poll()
if (next == end) {
return minDists[next.y][next.x]
}
fun handleCandidate(candidate: Coord2D) {
val dist = minDists[next.y][next.x] + cave[candidate.y][candidate.x]
if (minDists[candidate.y][candidate.x] == -1) {
minDists[candidate.y][candidate.x] = dist
queue += candidate
} else if (dist < minDists[candidate.y][candidate.x]) {
minDists[candidate.y][candidate.x] = dist
}
}
if (0 < next.x) {
val candidate = next.copy(x = next.x - 1)
handleCandidate(candidate)
}
if (0 < next.y) {
val candidate = next.copy(y = next.y - 1)
handleCandidate(candidate)
}
if (next.x < cave[next.y].lastIndex) {
val candidate = next.copy(x = next.x + 1)
handleCandidate(candidate)
}
if (next.y < cave.lastIndex) {
val candidate = next.copy(y = next.y + 1)
handleCandidate(candidate)
}
}
return -1
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,876 | advent-of-code | MIT License |
2022/src/main/kotlin/Day16.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import Day16.Worker.Active
object Day16 {
fun part1(input: String) = bestRoute(input, 30, 1)
fun part2(input: String) = bestRoute(input, 26, 2)
private fun bestRoute(input: String, time: Int, numWorkers: Int): Int {
val valves = parseInput(input)
val distanceMap = generateDistanceMap(valves)
val usefulValves = valves.filter { it.flowRate != 0 }
val startValve = valves.find { it.label == "AA" }!!
return bestRoute(
pressureReleased = 0,
timeLeft = time,
workerState = List(numWorkers) { Worker.Idle(startValve) },
usefulValves = usefulValves,
distanceMap = distanceMap
)
}
// I know this is a bad solution, because it takes a while to run - but it does come across the correct answer
// at some point. Maybe if I have free time (ha ha) I will fix it up later!
private fun bestRoute(
pressureReleased: Int,
timeLeft: Int,
workerState: List<Worker>,
usefulValves: List<Valve>,
distanceMap: Map<Path, Int>,
): Int {
// Finish any jobs
val finishedWorkers = workerState
.filterIsInstance<Active>()
.filter { it.timeFinished == timeLeft }
.toSet()
val newPressureReleased = pressureReleased + finishedWorkers.sumOf { it.destination.flowRate * timeLeft }
// Finished workers become idle again
val newWorkerState = workerState - finishedWorkers + finishedWorkers.map { Worker.Idle(it.destination) }
// Nothing more we can do, exit
if (usefulValves.isEmpty()) {
if (newWorkerState.any { it is Active }) {
val nextTime = newWorkerState.filterIsInstance<Active>().maxOf { it.timeFinished }
return bestRoute(
newPressureReleased,
nextTime,
newWorkerState,
usefulValves,
distanceMap
)
}
return newPressureReleased
}
// If we reach here, we should always have at least one idle worker, assign them work
return newWorkerState.filterIsInstance<Worker.Idle>().distinct().maxOf { idleWorker ->
usefulValves.maxOf { valve ->
val curr = idleWorker.curr
val nextWorkerState =
newWorkerState - idleWorker + Active(valve, timeLeft - distanceMap[Path(curr, valve)]!! - 1)
val nextTime =
if (nextWorkerState.any { it is Worker.Idle }) timeLeft else nextWorkerState.filterIsInstance<Active>()
.maxOf { it.timeFinished }
// We would run out of time, not a valid solution
if (nextTime < 0) {
return@maxOf newPressureReleased
}
bestRoute(
newPressureReleased,
nextTime,
nextWorkerState,
usefulValves - valve,
distanceMap
)
}
}
}
private fun generateDistanceMap(valves: List<Valve>): Map<Path, Int> {
val valveMap = valves.associateBy { it.label }
val distanceMap = mutableMapOf<Path, Int>()
valves.indices.forEach { a ->
val from = valves[a]
valves.indices.drop(a + 1).forEach { b ->
val to = valves[b]
val path = Path(from, to)
if (path !in distanceMap) {
val distance = distance(valveMap, from, to)
distanceMap[path] = distance
distanceMap[Path(to, from)] = distance
}
}
}
return distanceMap
}
private fun distance(valves: Map<String, Valve>, from: Valve, to: Valve): Int {
var next = listOf(from)
val explored = mutableSetOf(from)
var distance = 0
while (next.isNotEmpty()) {
val tunnels = next.flatMap { it.tunnels }.distinct()
if (to.label in tunnels) {
return distance + 1
}
explored.addAll(next)
next = tunnels
.map { valves[it]!! }
.filter { it !in explored }
distance++
}
throw IllegalStateException("No path found from $from to $to")
}
private val INPUT_REGEX = Regex("Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)")
private fun parseInput(input: String): List<Valve> {
return input.splitNewlines()
.map { INPUT_REGEX.matchEntire(it)!!.destructured }
.map { (label, flowRate, tunnels) -> Valve(label, flowRate.toInt(), tunnels.splitCommas()) }
}
private sealed class Worker {
data class Idle(val curr: Valve) : Worker()
data class Active(val destination: Valve, var timeFinished: Int) : Worker()
}
data class Valve(val label: String, val flowRate: Int, val tunnels: List<String>) {
override fun toString() = "$label($flowRate)"
}
data class Path(val from: Valve, val to: Valve)
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 4,559 | advent-of-code | MIT License |
src/day15/Solution.kt | chipnesh | 572,700,723 | false | {"Kotlin": 48016} | @file:OptIn(ExperimentalStdlibApi::class)
package day15
import Coords
import MAX
import length
import plus
import readInput
import kotlin.math.absoluteValue
fun main() {
fun part1(input: List<String>): Long {
val sensors = Sensors.ofInput(input)
return sensors
.scanRangesAt(2000000)
.sumOf(IntRange::length)
.minus(sensors.uniqueBeacons(2000000))
}
fun tuningFrequency(pair: Pair<Int, Set<IntRange>>): Long {
val (beaconY, range) = pair
val beaconX = range.first().endExclusive
return beaconX * 4000000L + beaconY
}
fun part2(input: List<String>): Long? {
val sensors = Sensors.ofInput(input)
val maxRange = 0..4000000
return maxRange
.firstNotNullOfOrNull { y ->
sensors.scanRangesAt(y, maxRange)
.let { if (it.size == 2) y to it else null }
}?.let(::tuningFrequency)
}
//val input = readInput("test")
val input = readInput("prod")
println(part1(input))
println(part2(input))
}
data class Sensor(
val coords: Coords,
val beacon: Coords
) {
private val distance = ((beacon.x - coords.x).absoluteValue + (beacon.y - coords.y).absoluteValue)
fun rangeAt(y: Int, maxRange: IntRange): IntRange? {
val diff = distance - (y - coords.y).absoluteValue
if (diff < 0) return null
return IntRange(
maxOf(maxRange.first, coords.x - diff),
minOf(maxRange.last, coords.x + diff)
)
}
companion object {
fun ofInput(input: String): Sensor {
val coordsLine = input.substringAfter("Sensor at ").substringBefore(":")
val (xLine, yLine) = coordsLine.split(", ")
val x = xLine.substringAfter("x=").toInt()
val y = yLine.substringAfter("y=").toInt()
val sensorCoords = Coords(x, y)
val beaconLine = input.drop(coordsLine.length).substringAfter(" closest beacon is at ")
val (bLine, cLine) = beaconLine.split(", ")
val b = bLine.substringAfter("x=").toInt()
val c = cLine.substringAfter("y=").toInt()
val beaconCoords = Coords(b, c)
return Sensor(sensorCoords, beaconCoords)
}
}
}
data class Sensors(
val sensors: List<Sensor>
) {
fun scanRangesAt(y: Int, maxRange: IntRange = IntRange.MAX) =
sensors
.mapNotNull { it.rangeAt(y, maxRange) }
.sortedBy(IntRange::first)
.fold(mutableSetOf<IntRange>()) { acc, next ->
acc.apply {
val previous = lastOrNull()?.also(::remove) ?: next
addAll((previous + next)?.let(::setOf) ?: setOf(previous, next))
}
}
fun uniqueBeacons(y: Int): Int {
return sensors
.mapTo(mutableSetOf(), Sensor::beacon)
.count { it.y == y }
}
companion object {
fun ofInput(input: List<String>): Sensors {
return Sensors(input.map(Sensor::ofInput))
}
}
}
| 0 | Kotlin | 0 | 1 | 2d0482102ccc3f0d8ec8e191adffcfe7475874f5 | 3,106 | AoC-2022 | Apache License 2.0 |
2021/src/main/kotlin/com/trikzon/aoc2021/Day3.kt | Trikzon | 317,622,840 | false | {"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397} | package com.trikzon.aoc2021
import kotlin.math.pow
fun main() {
val input = getInputStringFromFile("/day3.txt")
println(dayThreePartTwo(input))
}
fun dayThreePartOne(input: String): Int {
val lines = input.lines()
var gammaRate = 0
var epsilonRate = 0
for (i in 0 until lines[0].length) {
val power = lines[0].length - i - 1
if (getCommonBit(i, lines) == 1) {
gammaRate += 2.0.pow(power).toInt()
} else {
epsilonRate += 2.0.pow(power).toInt()
}
}
return gammaRate * epsilonRate
}
fun dayThreePartTwo(input: String): Int {
val lines = input.lines()
var oxygenLines = lines
var co2Lines = lines
var oxygen = ""
var co2 = ""
for (i in 0 until lines[0].length) {
val commonBit = getCommonBit(i, oxygenLines)
if (commonBit == -1) {
println(i)
oxygen = oxygenLines.firstOrNull { line -> line[i].digitToInt() == 1 } ?: oxygenLines[0]
break
}
oxygenLines = oxygenLines.filter { line -> line[i].digitToInt() == commonBit }
if (oxygenLines.size == 1) {
oxygen = oxygenLines[0]
break
} else if (oxygenLines.size == 2 && i + 1 < lines[0].length) {
oxygen = if (oxygenLines[0][i + 1].digitToInt() == 1) {
oxygenLines[0]
} else {
oxygenLines[1]
}
break
}
}
for (i in 0 until lines[0].length) {
val commonBit = getCommonBit(i, co2Lines)
if (commonBit == -1) {
co2 = co2Lines.firstOrNull { line -> line[i].digitToInt() == 0 } ?: co2Lines[0]
break
}
co2Lines = co2Lines.filter { line -> line[i].digitToInt() != commonBit }
if (co2Lines.size == 1) {
co2 = co2Lines[0]
break
} else if (co2Lines.size == 2 && i + 1 < lines[0].length) {
co2 = if (co2Lines[0][i + 1].digitToInt() == 0) {
co2Lines[0]
} else {
co2Lines[1]
}
break
}
}
println("$oxygen, $co2")
println("${oxygen.toInt(2)}, ${co2.toInt(2)}")
return oxygen.toInt(2) * co2.toInt(2)
}
fun getCommonBit(index: Int, lines: List<String>): Int {
val count = lines.count { line -> line[index].digitToInt() == 1 }
return if (count > lines.size / 2) {
1
} else if (count.toFloat() == lines.size / 2f) {
-1
} else {
0
}
}
| 0 | Kotlin | 1 | 0 | d4dea9f0c1b56dc698b716bb03fc2ad62619ca08 | 2,518 | advent-of-code | MIT License |
src/Day07.kt | underwindfall | 573,471,357 | false | {"Kotlin": 42718} | private const val CD = "$ cd "
fun main() {
val dayId = "07"
val input = readInput("Day${dayId}")
class Dir(val up: Dir? = null) {
val sd = HashMap<String, Dir>()
val fs = HashMap<String, Long>()
var sum = 0L
}
val root = Dir()
var cd = root
for (c in input) {
when {
c.startsWith(CD) -> {
val d = c.substringAfter(CD).trim()
when (d) {
"/" -> cd = root
".." -> cd = cd.up!!
else -> cd = cd.sd.getOrPut(d) { Dir(cd) }
}
}
c.startsWith("$ ls") -> {}
else -> {
val (dsz, name) = c.split(" ")
if (dsz == "dir") {
cd.sd.getOrPut(name) { Dir(cd) }
} else {
cd.fs[name] = dsz.toLong()
}
}
}
}
var ans = 0L
val ds = ArrayList<Dir>()
fun scan(cd: Dir): Long {
var sum = 0L
for (d in cd.sd.values) sum += scan(d)
sum += cd.fs.values.sum()
if (sum <= 100000) ans += sum
cd.sum = sum
ds += cd
return sum
}
val all = scan(root)
println(ans)
val total = 70000000L
val need = 30000000L
ds.sortBy { it.sum }
val maxAll = total - need
check(all > maxAll)
val del = all - maxAll
val dd = ds.find { it.sum >= del }
println(dd!!.sum)
}
| 0 | Kotlin | 0 | 0 | 0e7caf00319ce99c6772add017c6dd3c933b96f0 | 1,474 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | kmakma | 574,238,598 | false | null | fun main() {
data class Move(val count: Int, val source: Int, val target: Int)
class CrateStacks(input: List<String>) {
val stacks = mutableMapOf<Int, ArrayDeque<Char>>()
val moves = mutableListOf<Move>()
init {
var parseMoves = false
input.forEach { line ->
if (line.isBlank()) {
parseMoves = true
return@forEach
}
if (parseMoves) {
addMove(line)
return@forEach
}
parseStacks(line)
}
}
fun addMove(line: String) {
val (c, s, t) = line.split("move ", " from ", " to ").mapNotNull { it.toIntOrNull() }
moves.add(Move(c, s, t))
}
fun parseStacks(line: String) {
line.forEachIndexed { index, c ->
if (index % 4 != 1) return@forEachIndexed
if (c.isDigit()) return
if (!c.isUpperCase()) return@forEachIndexed
val stack = index / 4 + 1
ArrayDeque<String>()
stacks.compute(stack) { _, v ->
val ad = v ?: ArrayDeque()
ad.add(c)
return@compute ad
}
}
}
fun doMovesSingle(): CrateStacks {
moves.forEach { executeMoveSingle(it) }
return this
}
fun doMovesGrouped(): CrateStacks {
moves.forEach { executeMoveGrouped(it) }
return this
}
private fun executeMoveSingle(move: Move) {
repeat(move.count) {
val crate = stacks[move.source]!!.removeFirst()
stacks[move.target]!!.addFirst(crate)
}
}
private fun executeMoveGrouped(move: Move) {
for (i in 0 until move.count) {
val crate = stacks[move.source]!!.removeFirst()
stacks[move.target]!!.add(i, crate)
}
}
fun getTop(): String {
return stacks.keys.sorted().mapNotNull { stacks[it]?.first() }.joinToString("")
}
}
fun part1(input: List<String>): String {
return CrateStacks(input).doMovesSingle().getTop()
}
fun part2(input: List<String>): String {
return CrateStacks(input).doMovesGrouped().getTop()
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 950ffbce2149df9a7df3aac9289c9a5b38e29135 | 2,523 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/KRadiusSubarrayAverages.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
/**
* 2090. K Radius Subarray Averages
* @see <a href="https://leetcode.com/problems/k-radius-subarray-averages/">Source</a>
*/
fun interface KRadiusSubarrayAverages {
fun getAverages(nums: IntArray, k: Int): IntArray
}
class GetAveragesPrefixSum : KRadiusSubarrayAverages {
override fun getAverages(nums: IntArray, k: Int): IntArray {
// When a single element is considered then its average will be the number itself only.
if (k == 0) {
return nums
}
val n: Int = nums.size
val averages = IntArray(n) { -1 }
// Any index will not have 'k' elements in it's left and right.
if (2 * k + 1 > n) {
return averages
}
// Generate 'prefix' array for 'nums'.
// 'prefix[i + 1]' will be sum of all elements of 'nums' from index '0' to 'i'.
val prefix = LongArray(n + 1)
for (i in 0 until n) {
prefix[i + 1] = prefix[i] + nums[i]
}
// We iterate only on those indices which have at least 'k' elements in their left and right.
// i.e. indices from 'k' to 'n - k'
for (i in k until n - k) {
val leftBound = i - k
val rightBound = i + k
val subArraySum = prefix[rightBound + 1] - prefix[leftBound]
val average = (subArraySum / (2 * k + 1)).toInt()
averages[i] = average
}
return averages
}
}
class GetAveragesSlidingWindow : KRadiusSubarrayAverages {
override fun getAverages(nums: IntArray, k: Int): IntArray {
// When a single element is considered then its average will be the number itself only.
if (k == 0) {
return nums
}
val n: Int = nums.size
val averages = IntArray(n) { -1 }
// Any index will not have 'k' elements in its left and right.
if (2 * k + 1 > n) {
return averages
}
// First get the sum of first window of the 'nums' array.
var windowSum: Long = 0
for (i in 0 until 2 * k + 1) {
windowSum += nums[i]
}
averages[k] = (windowSum / (2 * k + 1)).toInt()
// Iterate on rest indices which have at least 'k' elements
// on its left and right sides.
for (i in 2 * k + 1 until n) {
// We remove the discarded element and add the new element to get current window sum.
// 'i' is the index of new inserted element, and
// 'i - (window size)' is the index of the last removed element.
windowSum = windowSum - nums[i - (2 * k + 1)] + nums[i]
averages[i - k] = (windowSum / (2 * k + 1)).toInt()
}
return averages
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,363 | kotlab | Apache License 2.0 |
src/day08/Day08.kt | GrzegorzBaczek93 | 572,128,118 | false | {"Kotlin": 44027} | package day08
import readInput
import utils.withStopwatch
import kotlin.math.max
fun main() {
val testInput = readInput("input08_test")
withStopwatch { println(part1(testInput)) }
withStopwatch { println(part2(testInput)) }
val input = readInput("input08")
withStopwatch { println(part1(input)) }
withStopwatch { println(part2(input)) }
}
private fun part1(input: List<String>): Int {
val height = input.size
val width = input.first().length
val edgesSize = (height * 2) + (width * 2) - 4 // 4 is extra corners
var midSize = 0
calculate(input) { top, bottom, start, end ->
if (top is Result.NotFound || bottom is Result.NotFound || start is Result.NotFound || end is Result.NotFound) {
midSize++
}
}
return edgesSize + midSize
}
private fun part2(input: List<String>): Int {
var maxSize = 0
calculate(input) { top, bottom, start, end ->
(top.distance * bottom.distance * start.distance * end.distance).let {
maxSize = max(it, maxSize)
}
}
return maxSize
}
private fun calculate(input: List<String>, onEach: (Result, Result, Result, Result) -> Unit) {
val height = input.size
val width = input.first().length
fun getDistanceFromTop(i: Int, j: Int): Result {
var distance = 0
(i - 1 downTo 0).forEach {
distance++
if (input[it][j] >= input[i][j]) {
return Result.Found(distance)
}
}
return Result.NotFound(distance)
}
fun getDistanceFromBottom(i: Int, j: Int): Result {
var distance = 0
(i + 1 until height).forEach {
distance++
if (input[it][j] >= input[i][j]) {
return Result.Found(distance)
}
}
return Result.NotFound(distance)
}
fun getDistanceFromStart(i: Int, j: Int): Result {
var distance = 0
(j - 1 downTo 0).forEach {
distance++
if (input[i][it] >= input[i][j]) {
return Result.Found(distance)
}
}
return Result.NotFound(distance)
}
fun getDistanceFromEnd(i: Int, j: Int): Result {
var distance = 0
(j + 1 until width).forEach {
distance++
if (input[i][it] >= input[i][j]) {
return Result.Found(distance)
}
}
return Result.NotFound(distance)
}
for (i in 1 until height - 1) {
for (j in 1 until width - 1) {
onEach(
getDistanceFromTop(i, j),
getDistanceFromBottom(i, j),
getDistanceFromStart(i, j),
getDistanceFromEnd(i, j),
)
}
}
}
private sealed class Result(
open val distance: Int,
) {
data class Found(override val distance: Int) : Result(distance)
data class NotFound(override val distance: Int) : Result(distance)
}
| 0 | Kotlin | 0 | 0 | 543e7cf0a2d706d23c3213d3737756b61ccbf94b | 2,971 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/schlaubi/aoc/days/Day8.kt | DRSchlaubi | 573,014,474 | false | {"Kotlin": 21541} | package dev.schlaubi.aoc.days
import dev.schlaubi.aoc.Day
import kotlin.io.path.readLines
object Day8 : Day<List<List<Int>>>() {
override val number: Int = 8
override fun prepare(): List<List<Int>> = input.readLines().map {
it.toCharArray().map(Char::digitToInt)
}.reversed()
override fun task1(prepared: List<List<Int>>): Any {
return prepared.map(List<Int>::withIndex).withIndex().sumOf { (x, rows) ->
rows.count { (y, _) ->
val height = prepared.getAt(x, y) ?: 0
!prepared.neighbourHigher(x, y, height, increaseYBy = 1) ||
!prepared.neighbourHigher(x, y, height, increaseYBy = -1) ||
!prepared.neighbourHigher(x, y, height, increaseXBy = 1) ||
!prepared.neighbourHigher(x, y, height, increaseXBy = -1)
}
}
}
override fun task2(prepared: List<List<Int>>): Any {
return prepared.map(List<Int>::withIndex).withIndex().flatMap { (x, rows) ->
rows.map { (y, _) ->
val height = prepared.getAt(x, y) ?: 0
prepared.neighbourSight(x, y, height, increaseYBy = 1) *
prepared.neighbourSight(x, y, height, increaseYBy = -1) *
prepared.neighbourSight(x, y, height, increaseXBy = 1) *
prepared.neighbourSight(x, y, height, increaseXBy = -1)
}
}.max()
}
}
private fun List<List<Int>>.getAt(x: Int, y: Int): Int? = getOrNull(y)?.getOrNull(x)
private fun List<List<Int>>.neighbourHigher(x: Int, y: Int, minHeight: Int, increaseXBy: Int = 0, increaseYBy: Int = 0): Boolean {
repeat(size) {
val currentX = x + increaseXBy * (it + 1)
val currentY = y + increaseYBy * (it + 1)
val result = getAt(currentX, currentY) ?: return false
if (result >= minHeight) {
return true
}
}
return false
}
private fun List<List<Int>>.neighbourSight(x: Int, y: Int, minHeight: Int, increaseXBy: Int = 0, increaseYBy: Int = 0): Int {
repeat(size) {
val currentX = x + increaseXBy * (it + 1)
val currentY = y + increaseYBy * (it + 1)
val result = getAt(currentX, currentY) ?: return it
if (result >= minHeight) {
return it + 1
}
}
return size
} | 1 | Kotlin | 0 | 4 | 4514e4ac86dd3ed480afa907d907e3ae26457bba | 2,365 | aoc-2022 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.