path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/de/jball/aoc2022/day02/Day02.kt | fibsifan | 573,189,295 | false | {"Kotlin": 43681} | package de.jball.aoc2022.day02
import de.jball.aoc2022.Day
class Day02(test: Boolean = false) : Day<Long>(test, 15, 12) {
private val games: List<Pair<Played, ToPlay>> = input.map { parseGame(it) }
private fun parseGame(it: String) =
Pair(Played.valueOf(it.substringBefore(" ")), ToPlay.valueOf(it.substringAfter(" ")))
override fun part1(): Long {
return games.sumOf { evaluateGame(it.first, it.second) }
}
private fun evaluateGame(played: Played, toPlay: ToPlay): Long {
return played.ordinal.toLong() + 1 + gameResult(played, toPlay)
}
private fun gameResult(played: Played, toPlay: ToPlay): Long {
return ((toPlay.ordinal.toLong() - played.ordinal.toLong() + 4) % 3) * 3
}
override fun part2(): Long {
return games.sumOf { anticipateGame(it.first, it.second) }
}
private fun anticipateGame(played: Played, toPlay: ToPlay): Long {
return toPlay.ordinal.toLong() * 3 + selectSign(played, toPlay)
}
private fun selectSign(played: Played, toPlay: ToPlay): Long {
return when (toPlay) {
ToPlay.X -> (played.ordinal.toLong() + 2) % 3 + 1
ToPlay.Y -> played.ordinal.toLong() + 1
ToPlay.Z -> (played.ordinal.toLong() + 1) % 3 + 1
}
}
enum class Played {
A, B, C
}
enum class ToPlay {
X, Y, Z
}
}
fun main() {
Day02().run()
}
| 0 | Kotlin | 0 | 3 | a6d01b73aca9b54add4546664831baf889e064fb | 1,425 | aoc-2022 | Apache License 2.0 |
src/Day01.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | fun main() {
fun insertMaxHeap(maxHeap: MutableList<Int>, heapSize: Int, entry: Int) {
var inserted = false;
for (i in maxHeap.indices) {
if (entry > maxHeap[i]) {
maxHeap.add(i, entry)
inserted = true
break
}
}
if (!inserted) {
maxHeap.add(entry)
}
if (maxHeap.size > heapSize) {
maxHeap.removeAt(heapSize)
}
}
fun part1(input: List<String>): Int {
var maxCalories = Int.MIN_VALUE
var totalCalories = 0
for (line in input) {
if (line.isEmpty()) {
if (totalCalories > maxCalories) {
maxCalories = totalCalories
}
totalCalories = 0
} else {
val calories = line.toInt()
totalCalories += calories
}
}
if (totalCalories > maxCalories) {
maxCalories = totalCalories
}
return maxCalories
}
fun part2(input: List<String>): Int {
val maxCaloriesHeap = mutableListOf<Int>()
var totalCalories = 0
for (line in input) {
if (line.isEmpty()) {
insertMaxHeap(maxCaloriesHeap, 3, totalCalories)
totalCalories = 0
} else {
val calories = line.toInt()
totalCalories += calories
}
}
insertMaxHeap(maxCaloriesHeap, 3, totalCalories)
return maxCaloriesHeap.sum()
}
val input = readInput("Day01")
// val input = readInput("Test")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 1,734 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/pl/klemba/aoc/day2/Main.kt | aklemba | 726,935,468 | false | {"Kotlin": 16373} | package pl.klemba.aoc.day2
import java.io.File
fun main() {
// ----- PART 1 -----
File(inputPath)
.readLines()
.foldIndexed(0) { index, acc, line -> if (line.meetsRequirements) acc + index + 1 else acc }
.let { println(it) }
// ----- PART 2 -----
File(inputPath)
.readLines()
.map { it.maxRgb }
.sumOf { it.red * it.green * it.blue }
.let { println(it) }
}
private val String.maxRgb: Rgb
get() = Rgb(
red = highestCubeNumber(this, redRegex),
green = highestCubeNumber(this, greenRegex),
blue = highestCubeNumber(this, blueRegex)
)
data class Rgb(var red: Int, var green: Int, var blue: Int)
private val String.meetsRequirements: Boolean
get() {
if (highestCubeNumber(this, redRegex) > MAX_RED) return false
if (highestCubeNumber(this, greenRegex) > MAX_GREEN) return false
if (highestCubeNumber(this, blueRegex) > MAX_BLUE) return false
return true
}
private fun highestCubeNumber(rawLine: String, regex: Regex): Int =
regex
.findAll(rawLine)
.map { it.destructured.component1().toInt() }
.sortedDescending()
.firstOrNull()
?: 0
private val redRegex = Regex(" (\\d*) red")
private val greenRegex = Regex(" (\\d*) green")
private val blueRegex = Regex(" (\\d*) blue")
private const val inputPath = "src/main/kotlin/pl/klemba/aoc/day2/input.txt"
private const val MAX_RED = 12
private const val MAX_GREEN = 13
private const val MAX_BLUE = 14
| 0 | Kotlin | 0 | 1 | 2432d300d2203ff91c41ffffe266e19a50cca944 | 1,497 | adventOfCode2023 | Apache License 2.0 |
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D24.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.Coordinate
import kotlin.math.absoluteValue
class Y2020D24 : BaseSolver() {
override val year = 2020
override val day = 24
override fun part1(): Int =
calculateStartingState(parseInput()).values.count { it }
override fun part2(): Int {
val tiles = parseInput()
val tileStates = calculateStartingState(tiles)
val finalState = (1..100).fold(tileStates) { acc, _ -> simulateDay(acc) }
return finalState.values.count { it }
}
private fun simulateDay(starting: Map<Coordinate, Boolean>): Map<Coordinate, Boolean> =
starting.keys.flatMap { it.adjacentCoords() }
.toSet()
.associateWith { c ->
val adjacentBlacks = c.adjacentCoords().count { starting[it] == true }
val currentTile = starting[c] ?: false
when {
currentTile && adjacentBlacks == 0 -> false
currentTile && adjacentBlacks > 2 -> false
!currentTile && adjacentBlacks == 2 -> true
else -> currentTile
}
}
private fun calculateStartingState(tiles: List<TilePath>): Map<Coordinate, Boolean> {
val tileStates = mutableMapOf<Coordinate, Boolean>()
tiles.forEach { t ->
val currentState = tileStates[t.coords] ?: false
tileStates[t.coords] = !currentState
}
return tileStates
}
private fun parseInput(): List<TilePath> = readInput {
readLines().map { line ->
val directions = mutableListOf<Direction>()
var l = line
while (l.isNotBlank()) {
val (d, lr) = parseLine(l)
directions.add(d)
l = lr
}
TilePath(directions)
}
}
private fun parseLine(line: String) =
Direction.values().first { line.startsWith(it.v) }.let { dir ->
Pair(dir, line.drop(dir.v.length))
}
data class TilePath(val directions: List<Direction>) {
val coords by lazy { toCoords() }
private fun toCoords(): Coordinate =
directions.fold(Coordinate(0, 0)) { acc, direction -> direction.applyToCoords(acc) }
}
private fun Coordinate.adjacentCoords() = Direction.values().map { it.applyToCoords(this) }
enum class Direction(val v: String) {
East("e"),
SouthEast("se"),
SouthWest("sw"),
West("w"),
NorthWest("nw"),
NorthEast("ne");
fun applyToCoords(coords: Coordinate): Coordinate {
val (x, y) = coords
return when (this) {
East -> coords.copy(x = x + 1)
SouthEast -> Coordinate(
if (y.absoluteValue % 2 == 1) x + 1 else x,
y - 1
)
SouthWest -> Coordinate(
if (y.absoluteValue % 2 == 0) x - 1 else x,
y - 1
)
West -> coords.copy(x = x - 1)
NorthWest -> Coordinate(
if (y.absoluteValue % 2 == 0) x - 1 else x,
y + 1
)
NorthEast -> Coordinate(
if (y.absoluteValue % 2 == 1) x + 1 else x,
y + 1
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 3,499 | advent-of-code | MIT License |
src/Day02.kt | ChenJiaJian96 | 576,533,624 | false | {"Kotlin": 11529} | /**
* https://adventofcode.com/2022/day/2
*/
fun main() {
fun String.calResult(): Int {
val (otherChar, _, myChar) = this
val otherChoice = otherChar.toChoice()
val myChoice = myChar.toChoice()
return myChoice.run {
this.toScore() + this.challengeTo(otherChoice).toScore()
}
}
fun part1(input: List<String>): Int = input.sumOf {
it.calResult()
}
fun String.calResult2(): Int {
val otherChoice = this[0].toChoice()
val result = Result.fromChar(this[2])
val myChoice = otherChoice.getTargetChoice(result)
return myChoice.run {
this.toScore() + this.challengeTo(otherChoice).toScore()
}
}
fun part2(input: List<String>): Int = input.sumOf {
it.calResult2()
}
val testInput = readInput("02", true)
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("02")
part1(input).println()
part2(input).println()
}
enum class Choice {
ROCK,
PAPER,
SCISSORS;
fun toScore(): Int = when (this) {
ROCK -> 1
PAPER -> 2
SCISSORS -> 3
}
}
enum class Result {
WIN,
DRAW,
LOSE;
fun toScore(): Int = when (this) {
WIN -> 6
DRAW -> 3
LOSE -> 0
}
companion object {
fun fromChar(input: Char): Result =
when (input) {
'X' -> LOSE
'Y' -> DRAW
'Z' -> WIN
else -> error("invalid input")
}
}
}
fun Choice.challengeTo(other: Choice): Result =
if (this == other) {
Result.DRAW
} else if (
(this == Choice.ROCK && other == Choice.SCISSORS) ||
(this == Choice.SCISSORS && other == Choice.PAPER) ||
(this == Choice.PAPER && other == Choice.ROCK)
) {
Result.WIN
} else {
Result.LOSE
}
fun Choice.getTargetChoice(result: Result): Choice =
when (result) {
Result.WIN -> {
when (this) {
Choice.ROCK -> Choice.PAPER
Choice.PAPER -> Choice.SCISSORS
Choice.SCISSORS -> Choice.ROCK
}
}
Result.DRAW -> this
Result.LOSE -> {
when (this) {
Choice.ROCK -> Choice.SCISSORS
Choice.PAPER -> Choice.ROCK
Choice.SCISSORS -> Choice.PAPER
}
}
}
fun Char.toChoice(): Choice {
return if (this == 'A' || this == 'X') {
Choice.ROCK
} else if (this == 'B' || this == 'Y') {
Choice.PAPER
} else if (this == 'C' || this == 'Z') {
Choice.SCISSORS
} else {
error("invalid input")
}
} | 0 | Kotlin | 0 | 0 | b1a88f437aee756548ac5ba422e2adf2a43dce9f | 2,746 | Advent-Code-2022 | Apache License 2.0 |
src/main/kotlin/me/giacomozama/adventofcode2022/days/Day21.kt | giacomozama | 572,965,253 | false | {"Kotlin": 75671} | package me.giacomozama.adventofcode2022.days
import java.io.File
class Day21 : Day() {
private lateinit var input: List<String>
override fun parseInput(inputFile: File) {
input = inputFile.readLines()
}
// n = number of monkeys
// time: O(n), space: O(n)
override fun solveFirstPuzzle(): Long {
abstract class MonkeyFunction {
abstract fun evaluate(): Long
}
val functions = hashMapOf<String, MonkeyFunction>()
class Immediate(val value: Long) : MonkeyFunction() {
override fun evaluate(): Long = value
}
class Operation(
val monkeyA: String, val monkeyB: String, val operation: (Long, Long) -> Long
) : MonkeyFunction() {
override fun evaluate(): Long {
return operation(functions[monkeyA]!!.evaluate(), functions[monkeyB]!!.evaluate())
}
}
for (line in input) {
val (key, value) = line.split(": ")
functions[key] = if (value[0] in 'a'..'z') {
val components = value.split(' ')
Operation(
monkeyA = components[0], monkeyB = components[2], operation = when (components[1]) {
"+" -> Long::plus
"-" -> Long::minus
"*" -> Long::times
else -> Long::div
}
)
} else {
Immediate(value.toLong())
}
}
return functions["root"]!!.evaluate()
}
override fun solveSecondPuzzle(): Long {
data class Fraction(val num: Long, val den: Long) {
private fun simplified(num: Long, den: Long): Fraction {
if (num == 0L) return Fraction(num, den)
var a = if (num > 0) num else -num
var b = if (den > 0) den else -den
while (b != 0L) {
val t = a
a = b
b = t % b
}
return Fraction(num / a, den / a)
}
operator fun plus(other: Fraction): Fraction {
val rDen = den * other.den
val rNum = rDen / den * num + rDen / other.den * other.num
return simplified(rNum, rDen)
}
operator fun minus(other: Fraction): Fraction {
val rDen = den * other.den
val rNum = rDen / den * num - rDen / other.den * other.num
return simplified(rNum, rDen)
}
operator fun times(other: Fraction) = simplified(num * other.num, den * other.den)
operator fun div(other: Fraction) = simplified(num * other.den, den * other.num)
}
class Binomial(val coeff: Fraction, val offset: Fraction) {
operator fun plus(other: Binomial) = Binomial(coeff + other.coeff, offset + other.offset)
operator fun minus(other: Binomial) = Binomial(coeff - other.coeff, offset - other.offset)
operator fun times(other: Binomial): Binomial = when {
coeff.num != 0L -> Binomial(other.offset * coeff, offset * other.offset)
other.coeff.num != 0L -> Binomial(offset * other.coeff, offset * other.offset)
else -> Binomial(Fraction(0, 1), offset * other.offset)
}
operator fun div(other: Binomial): Binomial = when {
coeff.num != 0L -> Binomial(coeff / other.offset, offset / other.offset)
other.coeff.num != 0L -> Binomial(offset / other.coeff, offset / other.offset)
else -> Binomial(Fraction(0, 1), offset / other.offset)
}
}
abstract class MonkeyFunction {
abstract fun evaluate(): Binomial
}
val functions = hashMapOf<String, MonkeyFunction>()
class Immediate(val value: Binomial) : MonkeyFunction() {
override fun evaluate() = value
}
class Operation(
val monkeyA: String,
val monkeyB: String,
val operation: (Binomial, Binomial) -> Binomial
) : MonkeyFunction() {
override fun evaluate() = operation(functions[monkeyA]!!.evaluate(), functions[monkeyB]!!.evaluate())
}
val entryPoints = Array(2) { "" }
for (line in input) {
val (key, value) = line.split(": ")
when {
key == "root" -> {
val components = value.split(' ')
entryPoints[0] = components[0]
entryPoints[1] = components[2]
}
key == "humn" -> {
functions[key] = Immediate(
Binomial(
Fraction(1, 1),
Fraction(0, 1)
)
)
}
value[0] in 'a'..'z' -> {
val components = value.split(' ')
functions[key] = Operation(
monkeyA = components[0],
monkeyB = components[2],
operation = when (components[1]) {
"+" -> Binomial::plus
"-" -> Binomial::minus
"*" -> Binomial::times
else -> Binomial::div
}
)
}
else -> {
functions[key] = Immediate(Binomial(Fraction(0, 1), Fraction(value.toLong(), 1)))
}
}
}
var a = functions[entryPoints[0]]!!.evaluate()
var b = functions[entryPoints[1]]!!.evaluate()
if (a.coeff.num == 0L) {
val t = a
a = b
b = t
}
val c = (b.offset - a.offset) / a.coeff
return c.num / c.den
}
}
| 0 | Kotlin | 0 | 0 | c30f4a37dc9911f3e42bbf5088fe246aabbee239 | 6,006 | aoc2022 | MIT License |
src/main/kotlin/io/matrix/MatrixDiagonalTraversal.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.matrix
import io.utils.runTests
import kotlin.math.absoluteValue
// https://leetcode.com/explore/learn/card/array-and-string/202/introduction-to-2d-array/1167/
class MatrixDiagonalTraversal {
fun execute(matrix: Array<IntArray>): IntArray = when {
matrix.isEmpty() -> intArrayOf()
matrix.size == 1 -> matrix.first()
matrix.first().size == 1 ->
matrix.map { it.first() }.toIntArray()
else -> {
val maxRow = matrix.size
val maxCol = matrix.firstOrNull()?.size ?: 0
val result = IntArray(maxRow * maxCol) { 0 }
val resultIndex = traverseColumns(maxRow, matrix, maxCol, result)
traverseInverseRows(maxRow, matrix, maxCol, result, resultIndex)
result
}
}
private fun traverseColumns(maxRow: Int, matrix: Array<IntArray>, maxCol: Int, result: IntArray): Int {
var traversalPositive = true
var resultIndex = 0
for (i in 0 until maxCol) {
resultIndex = matrix.traversal(
when {
traversalPositive -> minOf(i, maxRow - 1)
else -> 0
},
when {
traversalPositive && i < maxRow -> 0
traversalPositive && i >= maxRow -> i - (maxRow - 1)
else -> i
},
result, resultIndex, traversalPositive)
traversalPositive = !traversalPositive
}
return resultIndex
}
private fun traverseInverseRows(
maxRow: Int, matrix: Array<IntArray>, maxCol: Int, result: IntArray, resultIndexInput: Int): Int {
var traversalPositive = maxCol.rem(2) == 0
var resultIndex = resultIndexInput
for (i in 1 until maxRow - (maxCol - 1)) {
resultIndex = matrix.traversal(
when {
traversalPositive -> i + maxCol - 1
else -> i
},
when {
traversalPositive -> 0
else -> maxCol - 1
},
result, resultIndex, traversalPositive)
traversalPositive = !traversalPositive
}
for (i in maxOf(1, maxRow - (maxCol - 1)) until maxRow) {
resultIndex = matrix.traversal(
when {
traversalPositive -> maxRow - 1
else -> i
},
when {
traversalPositive && maxCol > maxRow -> maxCol - (maxRow - i)
traversalPositive -> i - (maxRow - maxCol).absoluteValue
else -> maxCol - 1
},
result, resultIndex, traversalPositive)
traversalPositive = !traversalPositive
}
return resultIndex
}
}
fun Array<IntArray>.traversal(
rowIndex: Int,
colIndex: Int,
output: IntArray,
startOutputIndex: Int,
positive: Boolean): Int {
var row = rowIndex
var col = colIndex
var outputIndex = startOutputIndex
while (row in indices && col in first().indices) {
output[outputIndex++] = this[row][col]
if (positive) row-- else row++
if (positive) col++ else col--
}
return outputIndex
}
fun main() {
runTests(listOf(
arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9)) to listOf(1, 2, 4, 7, 5, 3, 6, 8, 9),
arrayOf(intArrayOf(2, 3)) to listOf(2, 3),
arrayOf(intArrayOf(1, 2), intArrayOf(3, 4)) to listOf(1, 2, 3, 4),
arrayOf(intArrayOf(1), intArrayOf(2)) to listOf(1, 2),
arrayOf(intArrayOf(1), intArrayOf(2), intArrayOf(3), intArrayOf(4)) to listOf(1, 2, 3, 4),
arrayOf(intArrayOf(2, 5), intArrayOf(8, 4), intArrayOf(0, -1)) to listOf(2, 5, 8, 0, 4, -1),
arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9), intArrayOf(10, 11, 12)) to listOf(1, 2, 4, 7, 5, 3, 6, 8, 10, 11, 9, 12),
arrayOf(intArrayOf(2, 5), intArrayOf(8, 4), intArrayOf(0, -1), intArrayOf(3, 6)) to listOf(2, 5, 8, 0, 4, -1, 3, 6),
arrayOf(intArrayOf(1, 2, 3, 4, 5, 6, 7), intArrayOf(8, 9, 10, 11, 12, 13, 14), intArrayOf(15, 16, 17, 18, 19, 20, 21)) to listOf(1, 2, 8, 15, 9, 3, 4, 10, 16, 17, 11, 5, 6, 12, 18, 19, 13, 7, 14, 20, 21),
arrayOf(intArrayOf(2, 5, 8), intArrayOf(4, 0, -1)) to listOf(2, 5, 4, 0, 8, -1)
)) { (input, value) -> value to MatrixDiagonalTraversal().execute(input).toList() }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 4,111 | coding | MIT License |
src/main/kotlin/Sudoku/Heuristics.kt | aolkhov | 117,635,100 | false | null | package Sudoku
import kotlin.math.roundToInt
private fun sumOfAllPossibleValues(sm: SudokuMatrix) = sm.possibleValueCount * (sm.possibleValueCount + 1) / 2
/**
* When cell has a known value, no other cells in the same row, column, or quadrant, have that value
*/
class SingleValueInCellHeuristic: CellHeuristic() {
override fun apply(sm: SudokuMatrix, cell: Cell): Boolean {
if( !cell.isKnown )
return false
var modified = false
val cellVal = cell.value
for(zell in cell.allRelated()) {
val cellModified = zell.removeCandidateValue(cellVal)
if( cellModified )
Log.info("SingleValueInCellHeuristic: removed $cellVal from cell[${zell.row}][${zell.col}] because it is present in cell[${cell.row}][${cell.col}]. New value: ${zell.str()}")
modified = modified || cellModified
}
return modified
}
}
/**
* If all values but one are known for any row, column, or a quadrant,
* fill the remaining unknown with the only possible value
* Input: all cells of a row, column, or quadrant
*/
fun allButOneAreKnown(title: String, sm: SudokuMatrix, cells: List<Cell>): Boolean {
var allValsSum= sumOfAllPossibleValues(sm)
var targetCell: Cell? = null
for(cell in cells) {
if( cell.isKnown )
allValsSum -= cell.value
else if( targetCell == null )
targetCell = cell
else
return false // more than one not-known cell exists
}
if( targetCell == null )
return false // all values are known
Log.info("$title: setting cell[${targetCell.row}][${targetCell.col}] to the only remaining value $allValsSum")
targetCell.setValue(allValsSum)
return true
}
class AllButOneAreKnownInRow: LineHeuristic() {
override fun apply(sm: SudokuMatrix, line: Int): Boolean =
allButOneAreKnown("AllButOneAreKnownInARow", sm, (0 until sm.sideCellCount).map{ c -> sm.cells[line][c] })
}
class AllButOneAreKnownInCol: LineHeuristic() {
override fun apply(sm: SudokuMatrix, line: Int): Boolean =
allButOneAreKnown("AllButOneAreKnownInCol", sm, (0 until sm.sideCellCount).map{ r -> sm.cells[r][line] })
}
class AllButOneAreKnownInQuadrant: QuadrantHeuristic() {
override fun apply(sm: SudokuMatrix, qrow0: Int, qcol0: Int): Boolean =
allButOneAreKnown("AllButOneAreKnownInQuadrant", sm, sm.QuadrantCells(qrow0, qcol0).asSequence().toList())
}
/**
* If all values but one are known for any row, column, or a quadrant,
* fill the remaining unknown with the only possible value
* Input: groups of cells with unknown value, group being cells of a row, column, or quadrant
*/
fun uniqueValueLeft(title: String, sm: SudokuMatrix, cells: List<Cell>): Boolean {
var modified = false
outer@ for(cell in cells.filter { !it.isKnown }) {
var vs: Set<Int> = HashSet<Int>(cell.vals) //.toMutableSet()
for(otherCell in cells.filter { it !== cell }) {
vs -= otherCell.vals
if( vs.isEmpty() )
continue@outer
}
if( vs.size == 1 ) {
cell.vals = vs
sm.nextWorkSet.markModified(cell)
modified = true
Log.info("$title: set cell[${cell.row}][${cell.col}] to unique remaining value ${cell.value}")
}
}
return modified
}
class UniqueValueLeftInRow: LineHeuristic() {
override fun apply(sm: SudokuMatrix, line: Int): Boolean =
uniqueValueLeft("UniqueValueLeftInRow", sm, (0 until sm.sideCellCount).map{ c -> sm.cells[line][c] })
}
class UniqueValueLeftInCol: LineHeuristic() {
override fun apply(sm: SudokuMatrix, line: Int): Boolean =
uniqueValueLeft("UniqueValueLeftInCol", sm, (0 until sm.sideCellCount).map{ r -> sm.cells[r][line] })
}
class UniqueValueLeftInQuadrant: QuadrantHeuristic() {
override fun apply(sm: SudokuMatrix, qrow0: Int, qcol0: Int): Boolean =
uniqueValueLeft("UniqueValueLeftInQuadrant", sm, sm.QuadrantCells(qrow0, qcol0).asSequence().toList())
}
/**
* If group of cells contains K cells with the same K values, no other cells may contain these values.
* Input: groups of cells with unknown value, group being cells of a row, column, or quadrant
*/
fun combinationRemover(title: String, uqCells: List<Cell>): Boolean {
if( uqCells.size <= 1 )
return false
var modified = false
for(cell0 in uqCells.filter { it.vals.size < uqCells.size }) {
val sameValCells = uqCells.filter { it === cell0 || it.vals == cell0.vals }
if( sameValCells.count() == cell0.vals.size ) {
for(otherCell in uqCells.filter{ !sameValCells.contains(it) }) {
val oldVals = otherCell.vals
if( otherCell.removeCandidateValues(cell0.vals) ) {
modified = true
Log.info("$title: reduced cell[${otherCell.row}][${otherCell.col}] from $oldVals to ${otherCell.str()} because of ${sameValCells.size} cells like cell[${cell0.row}][${cell0.col}] ${cell0.str()}")
}
}
}
}
return modified
}
class CombinationInRow: LineHeuristic() {
override fun apply(sm: SudokuMatrix, line: Int): Boolean =
combinationRemover("CombinationInRow", (0 until sm.sideCellCount).map{ c -> sm.cells[line][c] }.filter{ !it.isKnown })
}
class CombinationInCol: LineHeuristic() {
override fun apply(sm: SudokuMatrix, line: Int): Boolean =
combinationRemover("CombinationInCol", (0 until sm.sideCellCount).map{ r -> sm.cells[r][line] }.filter{ !it.isKnown })
}
class CombinationInQuadrant: QuadrantHeuristic() {
override fun apply(sm: SudokuMatrix, qrow0: Int, qcol0: Int): Boolean =
combinationRemover("CombinationInQuadrant", sm.QuadrantCells(qrow0, qcol0).asSequence().filter{ !it.isKnown }.toList())
}
/**
* Redundant values in combination remover
* If a group of K cells (K < N) has the same values, then that group may not contain any other value
*/
fun closetSubset(title: String, sm: SudokuMatrix, allCells: List<Cell>): Boolean {
var modified = false
/**
* set1: candidate set
* set2: all other cells
*/
fun processSubset(set1: Set<Cell>, set2withKnowns: Set<Cell>) {
// common values of set1 elements are our candidates for closet set
// Could use set1.forEach { commonValues.retainAll(it.vals) } but we want to break ASAP
val commonValues: MutableSet<Int> = set1.iterator().next().vals.toMutableSet()
for(cell in set1) {
commonValues.retainAll(cell.vals)
if( commonValues.size < set1.size ) return // exit early if further search is pointless
}
// discard values found in cells outside of the candidate set (e.g. set2)
val uniqueVals = commonValues.toMutableSet()
for(v in commonValues) {
if( set2withKnowns.any { it.vals.contains(v) } ) {
if( uniqueVals.size-1 < set1.size ) return // exit early if further search is pointless
uniqueVals.remove(v)
}
}
// when set1 has K members and contains K unique values, we've found a closet set
if( uniqueVals.size == set1.size ) {
val closetSetStr = set1.joinToString(", ") { e -> "[${e.row}][${e.col}]" }
for (cell in set1.filter { it.vals != uniqueVals }) {
modified = true
val oldValsStr = cell.str()
cell.vals = uniqueVals.toMutableSet() // clone
sm.nextWorkSet.markModified(cell)
Log.info("$title: reduced cell[${cell.row}][${cell.col}] from $oldValsStr because of cells $closetSetStr: ${cell.str()}")
}
}
}
fun getCacheVal(set1: Set<Cell>, set2: Set<Cell>, set3: Set<Cell>) =
set1.sortedBy { it.row * sm.possibleValueCount + it.col }.joinToString(";") { e -> "${e.row},${e.col}" } + '|' +
set2.sortedBy { it.row * sm.possibleValueCount + it.col }.joinToString(";") { e -> "${e.row},${e.col}" } + '|' +
set3.sortedBy { it.row * sm.possibleValueCount + it.col }.joinToString(";") { e -> "${e.row},${e.col}" }
val processedCache: MutableSet<String> = mutableSetOf()
var cacheHits = 0
var procCalls = 0
fun processAllSubsets(set1: Set<Cell>, set2: Set<Cell>, setOfKnown: Set<Cell>) {
if( set1.size > 1 ) { // "last value in the set" is handled by other, less expensive heuristics
procCalls++
val cacheVal = getCacheVal(set1, set2, setOfKnown)
if( cacheVal in processedCache ) {
cacheHits++
} else {
if( Log.level >= Log.Level.Debug ) {
fun setAsString(set: Set<Cell>) =
set.sortedBy { it.row * sm.possibleValueCount + it.col }.joinToString(", ") { e -> "[${e.row}][${e.col}]" }
Log.print("++ processAllSubsets: set1 ${set1.size}: { ${setAsString(set1)} }, set2 ${set2.size}: { ${setAsString(set2)} }, known size: ${setOfKnown.size}\n")
}
processSubset(set1, set2 + setOfKnown)
processedCache.add(cacheVal)
}
}
if( set2.size > 1 )
set2.forEach { processAllSubsets(set1 + it, set2 - it, setOfKnown) }
}
val setOfKnown = allCells.filter { it.isKnown }.toSet()
val cellsSet = allCells.toSet() - setOfKnown
cellsSet.forEach { processAllSubsets(setOf(it), cellsSet - it, setOfKnown) }
val cacheHitRatio = if( procCalls == 0 ) 0f else (cacheHits * 1000f / procCalls).roundToInt() / 1000f
Log.info("$title: stats: total processing calls: ${procCalls}, skipped ${cacheHits}, cache hit ratio: ${cacheHitRatio}")
return modified
}
class ClosetSubsetInRow: LineHeuristic() {
override fun apply(sm: SudokuMatrix, line: Int): Boolean =
closetSubset("ClosetSubsetInRow", sm, (0 until sm.sideCellCount).map{ c -> sm.cells[line][c] })
}
class ClosetSubsetInCol: LineHeuristic() {
override fun apply(sm: SudokuMatrix, line: Int): Boolean =
closetSubset("ClosetSubsetInCol", sm, (0 until sm.sideCellCount).map{ r -> sm.cells[r][line] })
}
class ClosetSubsetInQuadrant: QuadrantHeuristic() {
override fun apply(sm: SudokuMatrix, qrow0: Int, qcol0: Int): Boolean =
closetSubset("ClosetSubsetInQuadrant", sm, sm.QuadrantCells(qrow0, qcol0).asSequence().toList())
}
/**
* If a value only appears in the same K lines of K quadrants (K < quadrant side length),
* then the value isn't present in these lines of the remaining quadrants
*/
class MatchingLineSubsets(sm: SudokuMatrix): MatrixHeuristic(sm) {
private fun getUncertainValuesInQuadrant(zell: Cell): Set<Int> {
val uncertainVals: MutableSet<Int> = mutableSetOf()
this.sm.QuadrantCells(zell).asSequence().toList().filter{ !it.isKnown }.forEach{ uncertainVals += it.vals }
return uncertainVals
}
private fun getLinesWithValue(zell: Cell, v: Int, rcMapper: (Cell) -> Int): List<Int> =
this.sm.QuadrantCells(zell).asSequence().toList().filter { it.vals.contains(v) }.map { cell -> rcMapper(cell) }.distinct()
private fun processQuadrantStripe(baseLine: Int, thisQuadrantLine: Int, isHorizontal: Boolean): Boolean {
val otherQuadrantLines = (0 until sm.sideCellCount step sm.quadrantSideLen).asSequence().toSet() - thisQuadrantLine
val zell = if( isHorizontal ) this.sm.cells[baseLine][thisQuadrantLine] else this.sm.cells[thisQuadrantLine][baseLine]
val distinctVals = this.getUncertainValuesInQuadrant(zell)
var modified = false
for(v in distinctVals) {
fun lineChooser(cell: Cell): Int = if( isHorizontal ) cell.row else cell.col
val thisLines = this.getLinesWithValue(zell, v, { cell -> lineChooser(cell) }).toSet()
if( thisLines.size >= sm.quadrantSideLen ) // the value is everywhere, nothing to remove
continue
// Build list of quadrants having the value in the same lines as we do
val sameLineSetQuadrants: MutableList<Int> = mutableListOf()
for(otherQuadrantLine in otherQuadrantLines) {
val qcell = sm.cells[if( isHorizontal) zell.row else otherQuadrantLine][if( isHorizontal) otherQuadrantLine else zell.col]
val otherLines = this.getLinesWithValue(qcell, v, { cell -> lineChooser(cell) }).toSet()
if( otherLines == thisLines )
sameLineSetQuadrants.add(otherQuadrantLine)
}
// see if we have sufficient quadrants with the same line set
if( 1 + sameLineSetQuadrants.size == thisLines.size ) {
for(qline in otherQuadrantLines.filter{ !sameLineSetQuadrants.contains(it) }) { // all other quadrants
for(lineToClear in thisLines) {
for(qline2 in qline until qline + sm.quadrantSideLen) { // all cells in its other dimension
val r = if( isHorizontal ) lineToClear else qline2
val c = if( isHorizontal ) qline2 else lineToClear
val cellModified = sm.cells[r][c].removeCandidateValue(v)
modified = modified || cellModified
if( cellModified ) {
val rcText = if( isHorizontal ) "rows" else "cols"
val lineLst = thisLines.sorted().joinToString(",")
Log.info("MatchingLineSubsets: removed $v from cell[$r][$c] because it is covered by $rcText $lineLst: ${sm.cells[r][c].str()}")
}
}
}
}
}
}
return modified
}
override fun apply(): Boolean {
var modified = false
val lineIndexes = (0 until sm.sideCellCount step sm.quadrantSideLen).asSequence().toList()
for(dim1 in lineIndexes)
for(dim2 in lineIndexes) {
modified = processQuadrantStripe(dim1, dim2, true ) || modified
modified = processQuadrantStripe(dim1, dim2, false) || modified
}
return modified
}
}
| 0 | Kotlin | 0 | 0 | d58ff1e30854b391c87b8efb73f1089d6512d20e | 14,320 | SudokuSolver | MIT License |
src/main/kotlin/mirecxp/aoc23/day09/Day09.kt | MirecXP | 726,044,224 | false | {"Kotlin": 42343} | package mirecxp.aoc23.day09
import mirecxp.aoc23.day04.toNumList
import mirecxp.aoc23.readInput
//https://adventofcode.com/2023/day/9
class Day09(private val inputPath: String) {
private var lines: List<List<Long>> = readInput(inputPath).map { it.toNumList() }
fun solve(part2: Boolean): String {
println("Solving day 9 for ${lines.size} lines [$inputPath]")
var result = 0L
lines.forEach { line: List<Long> ->
var isZero = false
var derivatives = mutableListOf<List<Long>>()
var lastDerivative = line
derivatives.add(line)
while (!isZero) {
isZero = true
val newDerivative = mutableListOf<Long>()
lastDerivative.forEachIndexed { index, l ->
if (index > 0) {
val newDif = l - lastDerivative[index - 1]
if (newDif != 0L) {
isZero = false
}
newDerivative.add(newDif)
}
}
derivatives.add(newDerivative)
lastDerivative = newDerivative
}
var newValue = 0L
derivatives.reversed().forEachIndexed { index, derivative: List<Long> ->
if (derivatives.size - index < derivatives.size) {
newValue = if (part2) {
derivative.first() - newValue
} else {
newValue + derivative.last()
}
}
}
result += newValue
}
println(result)
return "$result"
}
}
fun main(args: Array<String>) {
val testProblem = Day09("test/day09t")
check(testProblem.solve(part2 = false) == "114")
check(testProblem.solve(part2 = true) == "2")
val problem = Day09("real/day09a")
problem.solve(part2 = false)
problem.solve(part2 = true)
}
| 0 | Kotlin | 0 | 0 | 6518fad9de6fb07f28375e46b50e971d99fce912 | 2,005 | AoC-2023 | MIT License |
src/Day05.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} | fun main() {
fun part1(input: String): String {
val (header, instruction) = input.split("\n\n")
val crates = arrayOf(mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>())
for(line in header.lines()) {
line.windowed(3, 4).forEachIndexed { idx, data ->
val c = data[1]
if (c in 'A' .. 'Z') {
crates[idx].add(c)
}
}
}
for(instruction in instruction.lines()) {
val split = instruction.split(" ")
//val command = split[0]
val n = split[1].toInt()
//val from = split[2]
val source = split[3].toInt() - 1
//val to = split[4]
val destination = split[5].toInt() - 1
val cargo = crates[source].subList(0, n)
cargo.reverse()
crates[destination].addAll(0, cargo)
crates[source] = crates[source].subList(n, crates[source].size)
}
val result = crates.filter {!it.isEmpty() }.map { it.first() }.joinToString("")
return result
}
fun part2(input: String): String {
val (header, instruction) = input.split("\n\n")
val crates = arrayOf(mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>(), mutableListOf<Char>())
for(line in header.lines()) {
line.windowed(3, 4).forEachIndexed { idx, data ->
val c = data[1]
if (c in 'A' .. 'Z') {
crates[idx].add(c)
}
}
}
for(instruction in instruction.lines()) {
val split = instruction.split(" ")
//val command = split[0]
val n = split[1].toInt()
//val from = split[2]
val source = split[3].toInt() - 1
//val to = split[4]
val destination = split[5].toInt() - 1
val cargo = crates[source].subList(0, n)
crates[destination].addAll(0, cargo)
crates[source] = crates[source].subList(n, crates[source].size)
}
val result = crates.filter {!it.isEmpty() }.map { it.first() }.joinToString("")
return result
}
check(part1(readText("Day05_example")) == "CMZ")
check(part2(readText("Day05_example")) == "MCD")
// test if implementation meets criteria from the description, like:
val testInput = readText("Day05_test")
check(part1(testInput) == "NTWZZWHFV")
check(part2(testInput) == "BRZGFVBTJ")
}
| 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 2,810 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day07.kt | thelmstedt | 572,818,960 | false | {"Kotlin": 30245} | import java.io.File
sealed class Entry(open val name: String) {
data class File(override val name: String, val size: Long) : Entry(name)
data class Dir(
override val name: String,
val prev: Dir? = null,
var size: Long? = null,
val children: MutableList<Entry> = mutableListOf(),
) : Entry(name)
}
fun size(x: Entry): Long = when (x) {
is Entry.Dir -> {
val sumOf = x.children.sumOf { size(it) }
x.size = sumOf
sumOf
}
is Entry.File -> x.size
}
fun dirs(x: Entry, xs: MutableList<Entry.Dir>) {
when (x) {
is Entry.Dir -> {
xs.add(x)
x.children.forEach {
dirs(it, xs)
}
}
is Entry.File -> {
}
}
}
fun printDir(x: Entry, tab: String = "", minSize: Long = 0) {
when (x) {
is Entry.Dir -> {
println("${tab}- ${x.name} (dir, size=${x.size}")
x.children.forEach {
printDir(it, "$tab ", minSize)
}
}
is Entry.File -> {
println("$tab- ${x.name} (file, size=${x.size})")
}
}
}
fun sumAtMost(x: Entry, n: Long = 100000): Long {
val xs = mutableListOf<Entry.Dir>()
dirs(x, xs)
return xs.filter { size(it) <= n }.sumOf { size(it) }
}
fun main() {
fun getOutput(lines: List<String>, cursor: Int): List<String> {
val outlines = lines.subList(cursor, lines.size).takeWhile { !it.startsWith("$") }
return outlines
}
fun parseDirs(text: String): Entry.Dir {
var cursor = 0
var currentDir: Entry.Dir = Entry.Dir("/")
val root = currentDir
val lines = text.lines().filter { it.isNotBlank() }.drop(1)
while (cursor < lines.size) {
val line = lines[cursor]
cursor += 1
var cmd: String? = null
var args: String? = null
if (line.startsWith("$")) {
val split = line.drop(2).split(" ")
cmd = split[0]
args = split.getOrNull(1)
when (cmd) {
"cd" -> {
if (args == "..") {
currentDir = currentDir.prev!!
} else {
currentDir =
(currentDir.children.find { it.name == args }
?: error("Can't find $args in $currentDir")) as Entry.Dir
}
}
"ls" -> {
val output = getOutput(lines, cursor)
cursor += output.size
output.forEach { it ->
val split = it.split(" ")
if (it.matches("[0-9].*".toRegex())) {
currentDir.children.add(Entry.File(split[1], split[0].toLong()))
} else {
if (split[0] != "dir") error("What? $it")
val element = Entry.Dir(split[1], prev = currentDir)
currentDir.children.add(element)
}
}
}
}
}
}
return root
}
fun part1(text: String) {
val root = parseDirs(text)
println(printDir(root))
println(sumAtMost(root))
}
fun part2(text: String) {
val root = parseDirs(text)
size(root)
val total = 70000000L
val desired = 30000000L
val current = root.size!!
val unused = total - current
var required = desired - unused
println(current)
println(required)
printDir(root, "")
val allDirs = mutableListOf<Entry.Dir>()
dirs(root, allDirs)
// print(root)
val sortedBy = allDirs.sortedBy { it.size!! }
sortedBy.forEach {
val size = it.size!!
println("${it.name} $size ${size >= required} - from ${required - size}")
}
println(sortedBy.first { size(it) >= required }.name)
println(sortedBy.first { size(it) >= required }.size)
}
val testContent = File("src", "Day07_test.txt").readText()
val content = File("src", "Day07.txt").readText()
part2(testContent)
part2(content)
}
//10389918
//9290252 | 0 | Kotlin | 0 | 0 | e98cd2054c1fe5891494d8a042cf5504014078d3 | 4,456 | advent2022 | Apache License 2.0 |
src/test/kotlin/days/y2022/Day15Test.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2022
import days.Day
import org.hamcrest.CoreMatchers.nullValue
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.Is.`is`
import org.junit.jupiter.api.Test
import java.lang.Integer.max
import kotlin.math.absoluteValue
class Day15(val bound: Int = 20) : Day(2022, 15) {
override fun partOne(input: String): (rowToScan: Int) -> Int {
val sensors = parseInput(input.takeUnless { it.isBlank() } ?: inputString)
return { rowToScan ->
val beaconPositions =
sensors.mapNotNull { sensor -> sensor.closest.x.takeIf { sensor.closest.y == rowToScan } }.toSet()
val exclusionZonePoints = sensors.mapNotNull { sensor ->
sensor.exclusionZone(rowToScan)
}
(exclusionZonePoints.smallest()..exclusionZonePoints.largest()).count { x ->
!beaconPositions.contains(x) && exclusionZonePoints.any { it.contains(x) }
}
}
}
override fun partTwo(input: String): Any {
val sensors = parseInput(input)
for (y in (0..bound)) {
val zones = sensors.mapNotNull { sensor -> sensor.exclusionZone(y) }
val xBounds = (zones.smallest() + 1) until zones.largest()
val oneToTheLeft = zones.map { it.first }.map { it - 1 }
val oneToTheRight = zones.map { it.last }.map { it + 1 }
val searchXs = listOf(oneToTheLeft, oneToTheRight).flatten()
for (x in searchXs) {
if (xBounds.contains(x) && zones.none { it.contains(x) }) {
return (x * 4000000L) + y
}
}
}
error("no result found")
}
data class Point(val x: Int, val y: Int) {
fun distance(that: Point) = (x - that.x).absoluteValue + (y - that.y).absoluteValue
override fun toString() = "($x, $y)"
}
data class Sensor(val pos: Point, val closest: Point) {
val distance = pos.distance(closest)
}
fun parseInput(input: String): List<Sensor> {
if (input.isBlank() && inputString.isNotBlank()) return parseInput(inputString)
return input.trim().lines().mapNotNull { line ->
Regex(".*x=(-?\\d+), y=(-?\\d+).*x=(-?\\d+), y=(-?\\d+)").find(line)?.groupValues?.let { groupValues ->
val (x, y, closestX, closestY) = groupValues.drop(1).map { it.toInt() }
Sensor(Point(x, y), Point(closestX, closestY))
}
}
}
}
private fun List<IntRange>.smallest() = minOf { it.first }
private fun List<IntRange>.largest() = maxOf { it.last }
fun Day15.Sensor.exclusionZone(atY: Int): IntRange? {
val offset = (atY - pos.y).absoluteValue
val size = max(0, (distance - offset))
if (size == 0) return null
return (pos.x - size)..(pos.x + size)
}
class Day15Test {
val exampleInput = """
Sensor at x=2, y=18: closest beacon is at x=-2, y=15
Sensor at x=9, y=16: closest beacon is at x=10, y=16
Sensor at x=13, y=2: closest beacon is at x=15, y=3
Sensor at x=12, y=14: closest beacon is at x=10, y=16
Sensor at x=10, y=20: closest beacon is at x=10, y=16
Sensor at x=14, y=17: closest beacon is at x=10, y=16
Sensor at x=8, y=7: closest beacon is at x=2, y=10
Sensor at x=2, y=0: closest beacon is at x=2, y=10
Sensor at x=0, y=11: closest beacon is at x=2, y=10
Sensor at x=20, y=14: closest beacon is at x=25, y=17
Sensor at x=17, y=20: closest beacon is at x=21, y=22
Sensor at x=16, y=7: closest beacon is at x=15, y=3
Sensor at x=14, y=3: closest beacon is at x=15, y=3
Sensor at x=20, y=1: closest beacon is at x=15, y=3
""".trimIndent()
@Test
fun testExampleOne() {
assertThat(
Day15().partOne(exampleInput)(10), `is`(26)
)
}
@Test
fun testPartOne() {
assertThat(Day15().partOne("")(2000000), `is`(4724228))
}
@Test
fun testExclusionZone() {
val sensor = Day15.Sensor(Day15.Point(8, 7), Day15.Point(2, 10))
assertThat(sensor.exclusionZone(10000), `is`(nullValue()))
assertThat(sensor.exclusionZone(7), `is`(-1..17))
assertThat(sensor.exclusionZone(6), `is`(0..16))
assertThat(sensor.exclusionZone(5), `is`(1..15))
assertThat(sensor.exclusionZone(8), `is`(0..16))
assertThat(sensor.exclusionZone(9), `is`(1..15))
}
@Test
fun testExampleTwo() {
assertThat(
Day15(20).partTwo(exampleInput), `is`(56000011L)
)
}
@Test
fun testPartTwo() {
assertThat(
Day15(4000000).partTwo(""), `is`(13622251246513L)
)
}
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 4,743 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day14.kt | sbaumeister | 572,855,566 | false | {"Kotlin": 38905} | data class Scan(
var map: MutableList<MutableList<Char>>,
var startPos: Pair<Int, Int>,
val paths: List<List<Pair<Int, Int>>>,
val highestX: Int,
val lowestX: Int,
val highestY: Int,
)
fun createScanPart1(input: List<String>): Scan {
var (highestX, lowestX, highestY) = listOf(0, Int.MAX_VALUE, 0)
val paths = input.map { line ->
line.split(" -> ")
.map { it.split(",").map { n -> n.toInt() } }
.map { (x, y) ->
if (x > highestX) highestX = x
if (x < lowestX) lowestX = x
if (y > highestY) highestY = y
x to y
}
}.map { it.map { (x, y) -> y to (x - lowestX) } }
val startPos = 0 to (500 - lowestX)
return Scan(mutableListOf(), startPos, paths, highestX, lowestX, highestY)
}
fun createScanPart2(input: List<String>): Scan {
var (highestX, lowestX, highestY) = listOf(0, Int.MAX_VALUE, 0)
val paths = input.map { line ->
line.split(" -> ")
.map { it.split(",").map { n -> n.toInt() } }
.map { (x, y) ->
if (x > highestX) highestX = x
if (x < lowestX) lowestX = x
if (y > highestY) highestY = y
x to y
}
}
val newWidth = (highestY + 1 + 2) * 2 + 1
val xMiddlePos = (newWidth - 1) / 2
val xPosDiff = xMiddlePos - (500 - lowestX)
val startPos = 0 to xMiddlePos
return Scan(
mutableListOf(),
startPos,
paths.map { it.map { (x, y) -> y to (x - lowestX) + xPosDiff } },
lowestX + newWidth - 1,
lowestX,
highestY
)
}
fun countRestingSandUnits(scan: Scan): Int {
var countRestingUnits = 0
while (true) {
var pos = scan.startPos
while (true) {
val charDown = scan.map.getOrNull(pos.first + 1)?.getOrNull(pos.second) ?: return countRestingUnits
val newPos = when (charDown) {
'.' -> pos.first + 1 to pos.second
'#', 'o' -> {
val charDownLeft =
scan.map.getOrNull(pos.first + 1)?.getOrNull(pos.second - 1) ?: return countRestingUnits
if (charDownLeft == '.') {
pos.first + 1 to pos.second - 1
} else {
val charDownRight =
scan.map.getOrNull(pos.first + 1)?.getOrNull(pos.second + 1) ?: return countRestingUnits
if (charDownRight == '.') {
pos.first + 1 to pos.second + 1
} else {
pos
}
}
}
else -> pos
}
if (newPos == pos) {
newPos.let { (x, y) -> scan.map[x][y] = 'o' }
countRestingUnits++
if (newPos == scan.startPos) {
return countRestingUnits
}
break
}
pos = newPos
}
}
}
fun drawRocksOnMap(scan: Scan) {
scan.paths.forEach { path ->
path.windowed(2).forEach { (p1, p2) ->
if (p1.first < p2.first) {
(p1.first..p2.first).forEach { scan.map[it][p1.second] = '#' }
}
if (p1.first > p2.first) {
(p2.first..p1.first).forEach { scan.map[it][p1.second] = '#' }
}
if (p1.second < p2.second) {
(p1.second..p2.second).forEach { scan.map[p1.first][it] = '#' }
}
if (p1.second > p2.second) {
(p2.second..p1.second).forEach { scan.map[p1.first][it] = '#' }
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val scan = createScanPart1(input)
scan.map = MutableList(scan.highestY + 1) { x ->
MutableList(scan.highestX - scan.lowestX + 1) { y ->
if (x to y == scan.startPos) '+' else '.'
}
}
drawRocksOnMap(scan)
val countRestingSandUnits = countRestingSandUnits(scan)
//scan.map.forEach { println(it.joinToString()) }
return countRestingSandUnits
}
fun part2(input: List<String>): Int {
val scan = createScanPart2(input)
scan.map = MutableList(scan.highestY + 3) { x ->
MutableList(scan.highestX - scan.lowestX + 1) { y ->
if (x to y == scan.startPos) '+' else '.'
}
}
drawRocksOnMap(scan)
repeat(scan.map.last().size) { i ->
scan.map.last()[i] = '#'
}
val countRestingSandUnits = countRestingSandUnits(scan)
//scan.map.forEach { println(it.joinToString()) }
return countRestingSandUnits
}
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84 | 5,031 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/groupnet/algorithm/DescriptionMatcher.kt | AlmasB | 174,802,362 | false | {"Kotlin": 167480, "Java": 91450, "CSS": 110} | package groupnet.algorithm
import groupnet.euler.Description
import java.util.*
import java.util.stream.Stream
import kotlin.collections.ArrayList
/**
*
*
* @author <NAME> (<EMAIL>)
*/
object DescriptionMatcher {
/**
* Matches the actual string (description) with a given pattern.
* Given a pattern "a b ab" and actual "xy x y", the result
* is map containing a = x, b = y.
*
* @return empty map if no match, else mapping for how pattern terms needs to be replaced
*/
fun match(pattern: String, actual: String): Map<String, String> {
if (pattern.length != actual.length)
return emptyMap()
val actualTerms = actual.map { "$it" }.toSet().minus(" ")
val patternTerms = pattern.map { "$it" }.toSet().minus(" ")
if (actualTerms.size != patternTerms.size)
return emptyMap()
// do replacement pattern matching
val termsMap = HashMap<String, String>()
val result = permute(patternTerms)
val actualTermsList = actualTerms.toList()
return Stream.of(*result.toTypedArray())
//.parallel()
.map {
val tmpMap = hashMapOf<String, String>()
// "it" refers to a single permutation
for (i in 0 until it.length) {
tmpMap[actualTermsList[i]] = it[i].toString()
termsMap[it[i].toString()] = actualTermsList[i]
}
var replaced = ""
actual.forEach {
replaced += tmpMap[it.toString()] ?: " "
}
replaced = Description.from(replaced).getInformalDescription()
if (replaced == pattern) {
termsMap
} else {
emptyMap<String, String>()
}
}
.filter { it.isNotEmpty() }
.findAny()
.orElse(emptyMap())
}
}
/**
* Permute a set of 1-length strings without repetition.
* Given, setOf("a", "b", "c"), the result is "abc", "acb", "bac", "bca", "cab", "cba".
* The result size is given set size factorial.
*/
fun permute(set: Set<String>): Set<String> {
val result = arrayListOf<String>()
permute(0, ArrayList(set), result)
return result.toSet()
}
private fun permute(n: Int, list: MutableList<String>, result: MutableList<String>) {
if (n == list.size - 1) {
val s = list.fold("", { acc, x -> acc + x })
result.add(s)
} else {
for (i in n+1..list.size) {
permute(n + 1, ArrayList<String>(list), result)
if (i < list.size) {
Collections.swap(list, n, i)
}
}
}
} | 3 | Kotlin | 0 | 0 | 4aaa9de60ecdba5b9402b809e1e6e62489a1d790 | 2,852 | D2020 | Apache License 2.0 |
src/main/kotlin/day16/Day16.kt | dustinconrad | 572,737,903 | false | {"Kotlin": 100547} | package day16
import getCartesianProduct
import readResourceAsBufferedReader
import java.util.UUID
fun main() {
println("part 1: ${part1(readResourceAsBufferedReader("16_1.txt").readLines())}")
println("part 2: ${part2(readResourceAsBufferedReader("16_1.txt").readLines())}")
}
data class Node(val name: String, val rate: Int, val neighbors: Map<String, Int>) {
companion object {
private val valve: Regex = Regex("""Valve ([A-Z]{2}) has flow rate=(\d+); tunnels? leads? to valves? ([A-Z\s,]+)""")
fun parse(line: String): Node {
val m = valve.matchEntire(line) ?: throw IllegalArgumentException(line)
val (name, rate, neighbors) = m.destructured
return Node(
name,
rate.toInt(),
neighbors.split(",").map { it.trim() }.associateWith { 1 }
)
}
}
}
fun part1(input: List<String>): Int {
var nodes = input.map { Node.parse(it) }
val tunnels = Tunnels(nodes)
val result = tunnels.dfs("AA")
return result
}
fun part2(input: List<String>): Int {
val nodes = input.map { Node.parse(it) }
val tunnels = Tunnels(nodes)
val result = tunnels.dfs2(listOf("AA", "AA"))
return result
}
sealed interface Action {
fun apply(state: SearchState): Pair<SearchState, Int>
fun undo(state: SearchState): SearchState
fun cost(): Int
}
data class OpenValve(val node: Node): Action {
override fun apply(state: SearchState): Pair<SearchState, Int> {
return if (!state.opened.contains(node.name)) {
state.opened.add(node.name)
state to node.rate * state.minute
} else {
state to 0
}
}
override fun undo(state: SearchState): SearchState {
return if (state.opened.contains(node.name)) {
state.opened.remove(node.name)
state
} else {
state
}
}
override fun cost(): Int {
return 1
}
}
data class Move(val from: Node, val to: String, val dist: Int): Action {
override fun apply(state: SearchState): Pair<SearchState, Int> {
for (i in state.currNodes.indices) {
val node = state.currNodes[i]
if (node == from.name) {
state.currNodes[i] = to
break
}
}
state.currNodes.sort()
return state to 0
}
override fun undo(state: SearchState): SearchState {
for (i in state.currNodes.indices) {
val node = state.currNodes[i]
if (node == to) {
state.currNodes[i] = from.name
break
}
}
state.currNodes.sort()
return state
}
override fun cost(): Int {
return dist
}
}
data class SearchState(
val currNodes: MutableList<String>,
var minute: Int,
val opened: MutableSet<String>,
)
class Tunnels(nodes: Collection<Node>) {
private val graph = mutableMapOf<String, Node>()
private val cache = mutableMapOf<SearchState, Int>()
init {
nodes.forEach { addNode(it) }
}
private fun addNode(node: Node) {
graph[node.name] = node
}
fun dfs(currNodeName: String, minute: Int = 30): Int {
val initial = SearchState(
currNodes = mutableListOf(currNodeName),
minute = minute,
opened = mutableSetOf(),
)
return dfs(initial)
}
fun dfs2(currNodeName: List<String>, minute: Int = 26): Int {
val initial = SearchState(
currNodes = currNodeName.toMutableList(),
minute = minute,
opened = mutableSetOf(),
)
return dfs(initial)
}
private fun dfs(state: SearchState): Int {
if (cache.containsKey(state)) {
return cache[state]!!
}
if (state.minute <= 0) {
return 0
}
val actions = state.currNodes.map { actions(state, it) }
val actionCombinations = actions.getCartesianProduct()
state.minute--
var max = Integer.MIN_VALUE
actionCombinations.forEach { actions ->
val (nextState, score) = actions.foldRight(state to 0) { act, (st, sc) ->
val (newState, newScore) = act.apply(st)
newState to newScore + sc
}
val nextScore = dfs(nextState) + score
max = maxOf(max, nextScore)
actions.forEach {
it.undo(nextState)
}
}
state.minute++
//cache[state] = max
cache[state.copy(currNodes = state.currNodes.toMutableList())] = max
return max
}
private fun actions(currState: SearchState, currNodeName: String): List<Action> {
val possibleActions = mutableListOf<Action>()
val currNode = graph[currNodeName] ?: throw IllegalArgumentException("Unknown node name: $currNodeName")
if (!currState.opened.contains(currNodeName) && currNode.rate > 0) {
possibleActions.add(OpenValve(currNode))
}
currNode.neighbors.forEach {
possibleActions.add(Move(currNode, it.key, it.value))
}
return possibleActions
}
}
fun shortenAll(nodes: Collection<Node>): List<Node> {
val nodeLookup = nodes.associateBy { it.name }.toMutableMap()
val newNodes = mutableListOf<Node>()
for (node in nodes) {
if (node.name != "AA" && node.rate == 0) {
continue
}
val newNode = shorten(nodeLookup, node)
nodeLookup[newNode.name] = node
newNodes.add(newNode)
}
return newNodes
}
fun shorten(nodeLookup: Map<String, Node>, node: Node): Node {
val newNeighbors = mutableMapOf<String, Int>()
val visited = mutableSetOf<String>()
visited.add(node.name)
val q = ArrayDeque<Pair<String, Int>>()
q.addAll(node.neighbors.toList())
while(q.isNotEmpty()) {
val (candidate, dist) = q.removeFirst()
if (visited.contains(candidate)) {
continue
} else {
visited.add(candidate)
}
val candidateNode = nodeLookup[candidate]!!
if (candidateNode.rate > 0) {
newNeighbors[candidate] = dist
} else {
q.addAll(candidateNode.neighbors.map { (k, v) -> k to v + dist })
}
}
return node.copy(
neighbors = newNeighbors
)
}
| 0 | Kotlin | 0 | 0 | 1dae6d2790d7605ac3643356b207b36a34ad38be | 6,449 | aoc-2022 | Apache License 2.0 |
src/aoc2023/Day06.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2023
import readInput
import kotlin.text.Typography.times
fun main() {
fun part1(lines: List<String>): Long {
val times =
"(Time:\\s+)(.*)".toRegex().findAll(lines[0]).iterator().next().groupValues[2].split("\\s+".toRegex())
.map { it.toInt() }
val distances =
"(Distance:\\s+)(.*)".toRegex().findAll(lines[1]).iterator().next().groupValues[2].split("\\s+".toRegex())
.map { it.toInt() }
var result = 1L
for (i in times.indices) {
var ways = 0
for (j in 1 until times[i]) {
val distance = (j * (times[i] - j))
if (distance > distances[i]) {
ways += 1
}
}
result *= ways
}
return result
}
fun part2(lines: List<String>): Long {
val time =
"(Time:\\s+)(.*)".toRegex().findAll(lines[0]).iterator().next().groupValues[2].replace("\\s+".toRegex(), "")
.toLong()
val distance =
"(Distance:\\s+)(.*)".toRegex().findAll(lines[1]).iterator().next().groupValues[2].replace(
"\\s+".toRegex(),
""
).toLong()
// binary search index of the first element less than distance
var start = 0L
var end = time / 2L
var speed = (start + end) / 2L
while (end - start > 1) {
val curDistance = speed * (time - speed)
if (curDistance > distance) {
end = speed
} else {
start = speed
}
speed = (start + end) / 2L
}
return time - 2 * speed - 1
}
println(part1(readInput("aoc2023/Day06_test")))
println(part1(readInput("aoc2023/Day06")))
println(part2(readInput("aoc2023/Day06_test")))
println(part2(readInput("aoc2023/Day06")))
} | 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 1,922 | advent-of-code-kotlin | Apache License 2.0 |
leetcode-75-kotlin/src/main/kotlin/NumberOfRecentCalls.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* You have a RecentCounter class which counts the number of recent requests within a certain time frame.
*
* Implement the RecentCounter class:
*
* RecentCounter() Initializes the counter with zero recent requests.
* int ping(int t) Adds a new request at time t, where t represents some time in milliseconds,
* and returns the number of requests that has happened in the past 3000 milliseconds (including the new request).
* Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].
* It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.
*
*
*
* Example 1:
*
* Input
* ["RecentCounter", "ping", "ping", "ping", "ping"]
* [[], [1], [100], [3001], [3002]]
* Output
* [null, 1, 2, 3, 3]
*
* Explanation
* RecentCounter recentCounter = new RecentCounter();
* recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1
* recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2
* recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3
* recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3
*
*
* Constraints:
*
* 1 <= t <= 10^9
* Each test case will call ping with strictly increasing values of t.
* At most 10^4 calls will be made to ping.
* @see <a href="https://leetcode.com/problems/number-of-recent-calls/">LeetCode</a>
*/
class RecentCounter() {
val requests = mutableListOf<Int>()
fun ping(t: Int): Int {
requests.add(t)
while (requests.first() < t - 3000) {
requests.removeFirst()
}
return requests.size
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* var obj = RecentCounter()
* var param_1 = obj.ping(t)
*/
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,845 | leetcode-75 | Apache License 2.0 |
kotlin/strings/SuffixTree.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package strings
// https://stackoverflow.com/questions/9452701/ukkonens-suffix-tree-algorithm-in-plain-english/9513423#9513423
object SuffixTree {
const val ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789\u0001\u0002"
fun buildSuffixTree(s: CharSequence): Node {
val n: Int = s.length()
val a = ByteArray(n)
for (i in 0 until n) a[i] = ALPHABET.indexOf(s.charAt(i)) as Byte
val root = Node(0, 0, 0, null)
var node: Node? = root
var i = 0
var tail = 0
while (i < n) {
var last: Node? = null
while (tail >= 0) {
var ch = node!!.children[a[i - tail].toInt()]
while (ch != null && tail >= ch.end - ch.begin) {
tail -= ch.end - ch.begin
node = ch
ch = ch.children[a[i - tail].toInt()]
}
if (ch == null) {
node!!.children[a[i].toInt()] = Node(i, n, node.depth + node.end - node.begin, node)
if (last != null) last.suffixLink = node
last = null
} else {
val afterTail = a[ch.begin + tail]
if (afterTail == a[i]) {
if (last != null) last.suffixLink = node
break
} else {
val splitNode = Node(ch.begin, ch.begin + tail, node!!.depth + node.end - node.begin, node)
splitNode.children[a[i].toInt()] = Node(i, n, ch.depth + tail, splitNode)
splitNode.children[afterTail.toInt()] = ch
ch.begin += tail
ch.depth += tail
ch.parent = splitNode
node.children[a[i - tail].toInt()] = splitNode
if (last != null) last.suffixLink = splitNode
last = splitNode
}
}
if (node === root) {
--tail
} else {
node = node.suffixLink
}
}
i++
tail++
}
return root
}
// Usage example
fun main(args: Array<String?>?) {
val s1 = "aabcc"
val s2 = "abc"
// build generalized suffix tree
val s = s1 + '\u0001' + s2 + '\u0002'.toInt()
val tree = buildSuffixTree(s)
val lcs = lcs(tree, s1.length(), s1.length() + s2.length() + 1)
System.out.println(3 == lcs)
}
var lcsLength = 0
var lcsBeginIndex = 0
// traverse suffix tree to find longest common substring
fun lcs(node: Node, i1: Int, i2: Int): Int {
if (node.begin <= i1 && i1 < node.end) {
return 1
}
if (node.begin <= i2 && i2 < node.end) {
return 2
}
var mask = 0
for (f in 0 until ALPHABET.length()) {
if (node.children[f.toInt()] != null) {
mask = mask or lcs(node.children[f.toInt()], i1, i2)
}
}
if (mask == 3) {
val curLength = node.depth + node.end - node.begin
if (lcsLength < curLength) {
lcsLength = curLength
lcsBeginIndex = node.begin
}
}
return mask
}
class Node internal constructor(
var begin: Int, var end: Int, // distance in characters from root to this node
var depth: Int, var parent: Node?
) {
var children: Array<Node>
var suffixLink: Node? = null
init {
children = arrayOfNulls(ALPHABET.length())
}
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 3,719 | codelibrary | The Unlicense |
src/main/kotlin/dev/bogwalk/batch0/Problem10.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch0
/**
* Problem 10: Summation of Primes
*
* https://projecteuler.net/problem=10
*
* Goal: Find the sum of all prime numbers <= N.
*
* Constraints: 1 <= N <= 1e6
*
* e.g. N = 5
* primes = {2, 3, 5}
* sum = 10
*/
class SummationOfPrimes {
/**
* Stores the cumulative sum of prime numbers to allow quick access to the answers for
* multiple N <= [n].
*
* Solution mimics original Sieve of Eratosthenes algorithm that iterates over only odd
* numbers & their multiples, but uses boolean mask to alter a list of cumulative sums
* instead of returning a list of prime numbers.
*
* SPEED (WORSE) 51.48ms for N = 1e6
*
* @return array of the cumulative sums of prime numbers <= index.
*/
fun sumOfPrimesQuickDraw(n: Int): LongArray {
require(n % 2 == 0) { "Limit must be even otherwise loop check needed" }
val primesBool = BooleanArray(n + 1) {
it == 2 || it > 2 && it % 2 != 0
}
val sums = LongArray(n + 1) { 0L }.apply { this[2] = 2L }
for (i in 3..n step 2) {
if (primesBool[i]) {
// change current odd number
sums[i] = sums[i - 1] + i
// mark all multiples of this prime
if (1L * i * i < n.toLong()) {
for (j in (i * i)..n step 2 * i) {
primesBool[j] = false
}
}
} else {
// odd is not prime so keep most recent total
sums[i] = sums[i - 1]
}
// change next even number
sums[i + 1] = sums[i]
}
return sums
}
/**
* Similar to the above solution in that it stores the cumulative sum of prime numbers to
* allow future quick access; however, it replaces the typical boolean mask from the Sieve of
* Eratosthenes algorithm with this cumulative cache.
*
* An unaltered element == 0 indicates a prime, with future multiples of that prime
* marked with a -1, before the former, and its even successor, are replaced by the total so
* far.
*
* SPEED (BETTER) 31.90ms for N = 1e6
*
* @return array of the cumulative sums of prime numbers <= index.
*/
fun sumOfPrimesQuickDrawOptimised(n: Int): LongArray {
require(n % 2 == 0) { "Limit must be even otherwise loop check needed" }
val sums = LongArray(n + 1) { 0L }.apply { this[2] = 2L }
var total = 2L
for (i in 3..n step 2) {
if (sums[i] == 0L) {
total += i
// mark all multiples of this prime
if (1L * i * i < n.toLong()) {
for (j in (i * i)..n step 2 * i) {
sums[j] = -1L
}
}
}
// change current odd & next even number
sums[i] = total
sums[i + 1] = total
}
return sums
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,040 | project-euler-kotlin | MIT License |
src/Day06.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} | fun main() {
fun allDifferentChars(text: String): Boolean {
val chars = text.toCharArray().distinct()
return text.length == chars.size
}
fun part1(input: List<String>): List<Int> {
val returnList = mutableListOf<Int>()
input.forEach {
var bufferString = it[0].toString().repeat(4)
var messageStart = 0
it.forEachIndexed { i, c ->
bufferString = (bufferString + c).substring(1, 5)
if (allDifferentChars(bufferString) && (messageStart == 0))
messageStart = i + 1
}
returnList.add(messageStart)
}
println(returnList)
return returnList
}
fun part2(input: List<String>): MutableList<Int> {
val returnList = mutableListOf<Int>()
input.forEach {
var bufferString = it[0].toString().repeat(14)
var messageStart = 0
it.forEachIndexed { i, c ->
bufferString = (bufferString + c).substring(1, 15)
if (allDifferentChars(bufferString) && (messageStart == 0))
messageStart = i + 1
}
returnList.add(messageStart)
}
println(returnList)
return returnList
}
// test if implementation meets criteria from the description, like:
check (allDifferentChars("jpqm") == true)
val testInput = readInput("Day06-TestInput")
check(part1(testInput) == listOf(7, 5, 6, 10, 11))
check(part2(testInput) == listOf(19, 23, 23, 29, 26))
val input = readInput("Day06-Input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 1,664 | AoC-2022-12-01 | Apache License 2.0 |
src/day7/first/Solution.kt | verwoerd | 224,986,977 | false | null | package day7.first
import tools.executeProgram
import tools.readInput
import tools.timeSolution
import java.util.Collections.swap
fun main() = timeSolution {
val code = readInput()
val permutations = generatePermutations(mutableListOf(0,1,2,3,4))
val result = permutations.map {
// acctuator 1
var output = executeProgram(code, listOf(it[0],0))
// actuator 2
output = executeProgram(code, listOf(it[1],output.first()))
//actuator 3
output = executeProgram(code, listOf(it[2],output.first()))
// actuator 4
output = executeProgram(code, listOf(it[3],output.first()))
// actuator 5
output = executeProgram(code, listOf(it[4],output.first()))
Pair(it.joinToString(","), output.first())
}.maxBy (Pair<String, Int>::second)
println(result)
}
fun generatePermutations(list: MutableList<Int>) = generatePermutation(list, 0, list.size, mutableListOf())
fun generatePermutation(list: MutableList<Int>, start:Int, end: Int, result: MutableList<IntArray>): MutableList<IntArray> {
if (start == end) {
result.add(list.toIntArray())
return result
}
for (i in start until end) {
swap(list, start, i)
generatePermutation(list, start+1, end, result)
swap(list, start, i)
}
return result
}
| 0 | Kotlin | 0 | 0 | 554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7 | 1,290 | AoC2019 | MIT License |
src/main/kotlin/Day03.kt | joostbaas | 573,096,671 | false | {"Kotlin": 45397} | fun Char.priorityValue(): Int = when (this) {
in ('a'..'z') -> this - 'a' + 1
in ('A'..'Z') -> this - 'A' + 27
else -> throw IllegalArgumentException()
}
fun charsInCommon(s: List<String>): Set<Char> =
s.fold(s[0].toSet()) { acc, next ->
acc intersect next.toSet()
}
fun <T> Set<T>.onlyElement(): T = if (size != 1) throw IllegalArgumentException() else first()
fun day03Part1(input: List<String>): Int = input.sumOf { line ->
val halfStrings = line.chunked(line.length / 2)
charsInCommon(halfStrings).onlyElement().priorityValue()
}
fun day03Part2(input: List<String>): Int = input.chunked(3)
.sumOf { group: List<String> ->
charsInCommon(group).onlyElement().priorityValue()
}
| 0 | Kotlin | 0 | 0 | 8d4e3c87f6f2e34002b6dbc89c377f5a0860f571 | 735 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/pgebert/aoc/days/Day11.kt | pgebert | 724,032,034 | false | {"Kotlin": 65831} | package de.pgebert.aoc.days
import de.pgebert.aoc.Day
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
private typealias Point = Pair<Int, Int>
class Day11(input: String? = null) : Day(11, "Cosmic Expansion", input) {
private val rowsToDuplicate = inputList.indices.filter { i -> inputList[i].all { it == '.' } }
private val columnsToDuplicate = inputList.first().indices.filter { i -> inputList.all { it[i] == '.' } }
override fun partOne() = inputList.findGalaxies().computeDistances(2)
override fun partTwo() = inputList.findGalaxies().computeDistances(1000000)
private fun List<String>.findGalaxies(): List<Point> {
val galaxies = mutableListOf<Point>()
for (row in indices) {
for (col in this[row].indices) {
if (this[row][col] == '#') {
galaxies.add(Pair(row, col))
}
}
}
return galaxies
}
private fun List<Point>.computeDistances(factor: Int): Long {
val remaining = ArrayDeque<Point>()
remaining += this
var distances = 0L
while (remaining.isNotEmpty()) {
val a = remaining.removeFirst()
remaining.forEach { b ->
distances += a.distanceTo(b, factor)
}
}
return distances
}
private fun Point.distanceTo(other: Point, factor: Int): Int {
val rowsBetween = min(first, other.first)..max(first, other.first)
val columnsBetween = min(second, other.second)..max(second, other.second)
return (abs(first - other.first) + abs(second - other.second)
+ rowsToDuplicate.count { it in rowsBetween } * (factor - 1)
+ columnsToDuplicate.count { it in columnsBetween } * (factor - 1))
}
}
| 0 | Kotlin | 1 | 0 | a30d3987f1976889b8d143f0843bbf95ff51bad2 | 1,821 | advent-of-code-2023 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortedArrayToBST.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 108. Convert Sorted Array to Binary Search Tree
* @see <a href="https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/">Source</a>
*/
fun interface SortedArrayToBST {
operator fun invoke(nums: IntArray): TreeNode?
}
/**
* Approach 1: Preorder Traversal: Always Choose Left Middle Node as a Root
* Time complexity: O(N)
* Space complexity: O(N)
*/
class SortedArrayToBSTPreorder : SortedArrayToBST {
override operator fun invoke(nums: IntArray): TreeNode? {
return helper(nums = nums, right = nums.size - 1)
}
private fun helper(nums: IntArray, left: Int = 0, right: Int): TreeNode? {
if (left > right) return null
val leftMiddle = left.plus(right).div(2)
val root = TreeNode(nums[leftMiddle])
root.left = helper(nums, left, leftMiddle - 1)
root.right = helper(nums, leftMiddle + 1, right)
return root
}
}
/**
* Approach 2: Preorder Traversal: Always Choose Right Middle Node as a Root
* Time complexity: O(N).
* Space complexity: O(N).
*/
class RightMiddleSortedArrayToBST : SortedArrayToBST {
override operator fun invoke(nums: IntArray): TreeNode? {
return helper(nums = nums, right = nums.size - 1)
}
private fun helper(nums: IntArray, left: Int = 0, right: Int): TreeNode? {
if (left > right) return null
var middle = left.plus(right).div(2)
if ((left + right) % 2 == 1) {
++middle
}
val root = TreeNode(nums[middle])
root.left = helper(nums, left, middle - 1)
root.right = helper(nums, middle + 1, right)
return root
}
}
/**
* Approach 3: Preorder Traversal: Choose Random Middle Node as a Root
* Time complexity: O(N).
* Space complexity: O(N).
*/
class RandomMiddleSortedArrayToBST : SortedArrayToBST {
override operator fun invoke(nums: IntArray): TreeNode? {
return helper(nums = nums, right = nums.size - 1)
}
private fun helper(nums: IntArray, left: Int = 0, right: Int): TreeNode? {
if (left > right) return null
var middle = left.plus(right).div(2)
if ((left + right) % 2 == 1) {
middle += (0 until 2).random()
}
val root = TreeNode(nums[middle])
root.left = helper(nums, left, middle - 1)
root.right = helper(nums, middle + 1, right)
return root
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,028 | kotlab | Apache License 2.0 |
archive/k/kotlin/JobSequencing.kt | TheRenegadeCoder | 125,427,624 | false | {"BASIC": 97136, "Rust": 61107, "PHP": 58368, "Beef": 51651, "Mathematica": 43477, "C++": 37590, "Java": 33084, "Python": 30222, "JavaScript": 29447, "C": 29061, "Go": 22022, "C#": 18001, "Objective-C": 16797, "Haskell": 16781, "Kotlin": 13185, "Brainfuck": 12179, "Perl": 11260, "TypeScript": 10875, "MATLAB": 9411, "Makefile": 8577, "Assembly": 8277, "Fortran": 7187, "Scala": 7134, "Lua": 7054, "Dart": 6882, "Pascal": 6597, "Swift": 6304, "Elixir": 6151, "Shell": 6026, "Erlang": 5920, "Common Lisp": 5499, "Julia": 4624, "COBOL": 4343, "Groovy": 3998, "Ruby": 3725, "R": 3369, "Visual Basic .NET": 2790, "Clojure": 2313, "PowerShell": 2135, "CoffeeScript": 1071, "D": 1012, "Pyret": 988, "Racket": 967, "Nim": 901, "REXX": 735, "LOLCODE": 710, "Dockerfile": 705, "Ada": 632, "TeX": 607, "Boo": 576, "Vim Script": 545, "Berry": 544, "Prolog": 478, "F#": 427, "Crystal": 390, "Witcher Script": 390, "Agda": 343, "Scheme": 293, "Solidity": 191, "Zig": 145, "ColdFusion": 144, "PureScript": 140, "Eiffel": 135, "Modula-2": 130, "PicoLisp": 111, "Opa": 102, "Verilog": 102, "Ballerina": 95, "Haxe": 95, "Odin": 86, "Raku": 85, "Lex": 84, "F*": 76, "Golo": 74, "Frege": 73, "Pony": 72, "Hack": 69, "Idris": 58, "Red": 57, "V": 55, "Smalltalk": 34, "Csound": 33, "OCaml": 33, "Factor": 31, "Scilab": 31, "Wren": 30, "Batchfile": 29, "LiveScript": 28, "Shen": 27, "Chapel": 26, "Forth": 25, "Fennel": 24, "Io": 24, "Janet": 24, "GLSL": 23, "MoonScript": 22, "Nit": 22, "Elvish": 21, "Tcl": 21, "Ring": 20} | fun main(args: Array<String>) {
val jobs = buildJobs(args)
if (jobs.isNullOrEmpty()) {
println("Usage: please provide a list of profits and a list of deadlines")
} else {
println(maxProfit(jobs))
}
}
/**
* Calculates the maximum profit of a list of jobs
*/
private fun maxProfit(jobs: List<Job>): Int {
val scheduled = hashSetOf<Int>()
var profit = 0
jobs.sortedByDescending { it.profit }.forEach {
for (i in it.deadline downTo 1) {
if (scheduled.add(i)) {
profit += it.profit
break
}
}
}
return profit
}
/**
* Builds job list with input arguments
*/
private fun buildJobs(args: Array<String>): List<Job>? {
if (args.run { isNullOrEmpty() || size < 2 || any { it.isBlank() } }) return null
val profits = args[0].toIntArray()
val deadlines = args[1].toIntArray()
if (profits.size != deadlines.size) return null
return profits.mapIndexed { index, profit -> Job(profit, deadlines[index]) }
}
/**
* Represents the information of a job
*/
class Job(val profit: Int, val deadline: Int)
/**
* Extracts an array of integers from the string
*/
fun String.toIntArray() = split(",").mapNotNull { it.trim().toIntOrNull() }
| 83 | BASIC | 540 | 527 | bd5f385f6b3f7881c496a4c2884d1a63b8bb5448 | 1,269 | sample-programs | MIT License |
src/Day15.kt | uekemp | 575,483,293 | false | {"Kotlin": 69253} | import kotlin.math.absoluteValue
class SensorMap(val sensors: List<Sensor>) {
val map = mutableMapOf<Coordinate, Char>()
init {
sensors.forEach {sensor ->
this[sensor.position] = SENSOR
this[sensor.beacon] = BEACON
}
}
private val left: Int
get() = map.keys.map { c -> c.x }.min()
private val right: Int
get() = map.keys.map { c -> c.x }.max()
private val top: Int
get() = map.keys.map { c -> c.y }.min()
private val bottom: Int
get() = map.keys.map { c -> c.y }.max()
operator fun get(c: Coordinate) = map[c]
operator fun set(c: Coordinate, value: Char) {
map[c] = value
}
fun getRow(row: Int): CharArray {
return buildString {
for (x in left..right) {
append(this@SensorMap[Coordinate(x, row)] ?: UNDEFINED)
}
}.toCharArray()
}
fun computeCoverage(predicate: (Sensor) -> Boolean = { s -> true }): SensorMap {
sensors.filter(predicate).forEach { sensor ->
println("Checking coverage of $sensor")
val distance = sensor.distanceToBeacon
for (y in sensor.position.y - distance..sensor.position.y + distance) {
for (x in sensor.position.x - distance..sensor.position.x + distance) {
val c = Coordinate(x, y)
if ((this[c] == null) && (sensor.distanceTo(c) <= distance)) {
this[c] = COVERED
}
}
}
}
return this
}
fun computeRowCoverage(row: Int) {
sensors.forEach { sensor ->
println("Computing coverage for row $row for $sensor")
val x = sensor.position.x
val distance = sensor.distanceToBeacon
val left = distance - (sensor.position.y - row).absoluteValue
if (left > 0) {
for (i in x - left..x + left) {
val c = Coordinate(i, row)
if (this[c] == null) {
this[c] = COVERED
}
}
}
}
}
override fun toString(): String {
return buildString {
for (y in top..bottom) {
for (x in left..right) {
append(map[Coordinate(x, y)] ?: UNDEFINED)
}
append("\n")
}
}
}
companion object {
const val UNDEFINED = '.'
const val SENSOR = 'S'
const val BEACON = 'B'
const val COVERED = '#'
}
}
data class Sensor(val position: Coordinate, val beacon: Coordinate) {
val distanceToBeacon: Int
get() = (beacon.x - position.x).absoluteValue + (beacon.y - position.y).absoluteValue
fun distanceTo(other: Coordinate) = (position.x - other.x).absoluteValue + (position.y - other.y).absoluteValue
override fun toString(): String {
return "Sensor at $position, beacon: $beacon, distance=$distanceToBeacon"
}
}
fun parseSensorMap(input: List<String>): SensorMap {
val regexp = """x=(-?\b[0-9]+\b), y=(-?\b[0-9]+\b)""".toRegex()
val results = input.map { line ->
val result = regexp.findAll(line).toList()
val x = result[0].groups[1]!!.value.toInt()
val y = result[0].groups[2]!!.value.toInt()
val beaconX = result[1].groups[1]!!.value.toInt()
val beaconY = result[1].groups[2]!!.value.toInt()
Sensor(Coordinate(x, y), Coordinate(beaconX, beaconY))
}
return SensorMap(results)
}
fun main() {
fun part1(input: List<String>, row: Int): Int {
val map = parseSensorMap(input)
// map.computeCoverage { sensor -> sensor.c.x == 8 && sensor.c.y == 7 }
map.computeRowCoverage(row)
// println(map)
val result = map.getRow(row)
// println(row)
return result.count { c -> c == SensorMap.COVERED }
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
val input = readInput("Day15")
check(part1(input, 2000000) == 5832528)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bc32522d49516f561fb8484c8958107c50819f49 | 4,316 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day18.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | import java.util.*
fun parse(s: String): Triple<Int, Int, Int> {
val scanner = Scanner(s)
scanner.useDelimiter(",")
return Triple(scanner.nextInt(), scanner.nextInt(), scanner.nextInt())
}
fun main() {
fun part1(input: List<String>): Int {
val (maxX, maxY, maxZ) = listOf(19, 19, 19)
// val exist = Array(maxX + 1) { Array(maxY + 1) { BooleanArray(maxZ + 1) { false } } }
val surface = Array(maxX + 1) { Array(maxY + 1) { IntArray(maxZ + 1) { -1 } } }
input.forEach { line ->
val (x, y, z) = parse(line)
if (surface[x][y][z] != -1) error("duplicate coords")
var self = 6
if (x > 0 && surface[x-1][y][z] > 0) { self--; surface[x-1][y][z]-- }
if (x < maxX && surface[x+1][y][z] > 0) { self--; surface[x+1][y][z]-- }
if (y > 0 && surface[x][y-1][z] > 0) { self--; surface[x][y-1][z]-- }
if (y < maxY && surface[x][y+1][z] > 0) { self--; surface[x][y+1][z]-- }
if (z > 0 && surface[x][y][z-1] > 0) { self--; surface[x][y][z-1]-- }
if (z < maxZ && surface[x][y][z+1] > 0) { self--; surface[x][y][z+1]-- }
surface[x][y][z] = self
}
return surface.sumOf { it.sumOf { it.filter { it > 0 }.sum() } }
}
fun part2(input: List<String>): Int {
val (maxX, maxY, maxZ) = listOf(19, 19, 19)
val lavaSurface = Array(maxX + 1) { Array(maxY + 1) { IntArray(maxZ + 1) { -1 } } }
fun calcSurface(a: Array<Array<IntArray>>, x: Int, y: Int, z: Int) {
if (a[x][y][z] != -1) error("duplicate coords")
var self = 6
if (x > 0 && a[x-1][y][z] > 0) { self--; a[x-1][y][z]-- }
if (x < maxX && a[x+1][y][z] > 0) { self--; a[x+1][y][z]-- }
if (y > 0 && a[x][y-1][z] > 0) { self--; a[x][y-1][z]-- }
if (y < maxY && a[x][y+1][z] > 0) { self--; a[x][y+1][z]-- }
if (z > 0 && a[x][y][z-1] > 0) { self--; a[x][y][z-1]-- }
if (z < maxZ && a[x][y][z+1] > 0) { self--; a[x][y][z+1]-- }
a[x][y][z] = self
}
input.forEach { line ->
val (x, y, z) = parse(line)
calcSurface(lavaSurface, x, y, z)
}
val trap = Array(maxX + 1) { Array(maxY + 1) { IntArray(maxZ + 1) { -1 } } }
val reachable = Array(maxX + 1) { Array(maxY + 1) { BooleanArray(maxZ + 1) { false } } }
fun markReachable(x: Int, y: Int, z: Int) {
if (x == 0 || x == maxX) return
if (y == 0 || y == maxY) return
if (z == 0 || z == maxZ) return
if (reachable[x][y][z]) return
if (lavaSurface[x][y][z] > -1) return
reachable[x][y][z] = true
markReachable(x - 1, y, z)
markReachable(x + 1, y, z)
markReachable(x, y - 1, z)
markReachable(x, y + 1, z)
markReachable(x, y, z - 1)
markReachable(x, y, z + 1)
return
}
for (y in 1 until maxY)
for (z in 1 until maxZ) {
if (lavaSurface[0][y][z] == -1) markReachable(1, y, z)
if (lavaSurface[maxX][y][z] == -1) markReachable(maxX - 1, y, z)
}
for (x in 1 until maxX)
for (z in 1 until maxZ) {
if (lavaSurface[x][0][z] == -1) markReachable(x, 1, z)
if (lavaSurface[x][maxY][z] == -1) markReachable(x, maxY - 1, z)
}
for (x in 1 until maxX)
for (y in 1 until maxY) {
if (lavaSurface[x][y][0] == -1) markReachable(x, y, 1)
if (lavaSurface[x][y][maxZ] == -1) markReachable(x, y, maxZ - 1)
}
for (x in 1 until maxX)
for (y in 1 until maxY)
for (z in 1 until maxZ)
if (lavaSurface[x][y][z] == -1 && !reachable[x][y][z])
calcSurface(trap, x, y, z)
return lavaSurface.sumOf { it.sumOf { it.filter { it > 0 }.sum() } }.also { println("lava $it") } -
trap.sumOf { it.sumOf { it.filter { it > 0 }.sum() } }.also { println("trap $it") }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
// val testInput2 = readInput("Day18_test2")
// println(part1(testInput))
// check(part1(testInput2, 2022) == 10)
// check(part1(testInput) == 64)
println(part2(testInput))
check(part2(testInput) == 58)
@Suppress("UNUSED_VARIABLE")
val input = readInput("Day18")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 4,650 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/graph/variation/WrongEdgeWeight.kt | yx-z | 106,589,674 | false | null | package graph.variation
import graph.core.Vertex
import graph.core.WeightedGraph
import graph.core.dijkstra
import util.min
// suppose you have computed the all pairs shortest path (apsp) table
// but later you find out that your edge weight for u -> v is wrong during
// the computation... that is, w(u -> v) is used but w'(u -> v) is true weight
// 1. suppose w'(u -> v) < w(u -> v), restore the table in O(V^2) time
fun <V> HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>.restore(
u: Vertex<V>,
v: Vertex<V>,
newWeight: Int) {
// dist[x, y] = min{ dist[x, y], dist[x, u] + w'(u -> v) + dist[v, y] }
val dist = this
forEach { (x, map) ->
map.forEach { (y, _) ->
map[y] = min(map[y]!!, map[u]!! + newWeight + dist[v]!![y]!!)
}
}
}
// 2. use O(1) time to check whether your computed table is correct or not
// (yes it can still be correct), still assuming w'(u -> v) < w(u -> v)
fun <V> HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>.isCorrect(
u: Vertex<V>,
v: Vertex<V>,
newWeight: Int) = this[u]!![v]!! <= newWeight
// we actually just need to check if there exists a shortest path from u to v
// that doesn't use the edge u -> v!
// 3. ues O(VE) time to check whether your computed table is correct or not
// , but without restriction that w'(u -> v) < w(u -> v)
fun <V> HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>.isCorrect(
u: Vertex<V>,
v: Vertex<V>,
g: WeightedGraph<V, Int>,
newWeight: Int) = g.dijkstra(u).second[v] !== u && this[u]!![v]!! <= newWeight
// the idea is similar: check if the shortest path from u to v
// is actually using the edge u -> v, if it is then it must be wrong
// if it is NOT, it still can be wrong if the newWeight is smaller! we should use the new weight
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,727 | AlgoKt | MIT License |
src/main/kotlin/com/kishor/kotlin/ds/MinHeap.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.ds
import java.util.*
data class Item(val test: Int) : Comparable<Item> {
override fun compareTo(other: Item): Int {
return this.test.compareTo(other.test)
}
}
fun main() {
val minHeap = MinHeap()
minHeap.checkPriorityQueue()
println(minHeap.priorityQueue.peek().test)
}
class MinHeap {
var priorityQueue = PriorityQueue<Item>()
fun checkPriorityQueue() {
priorityQueue.add(Item(test = 89))
priorityQueue.add(Item(test = 9))
priorityQueue.add(Item(test = -1))
priorityQueue.add(Item(test = 890))
}
val compareByValue = kotlin.Comparator<Int> { o1, o2 ->
if (o1 > o2) 1
else if (o1 < o2) -1
else 0
}
var heap = PriorityQueue { n1: Int, n2: Int -> n1 - n2 }
val pqs = PriorityQueue<Int> { n1, n2 -> n1 - n2 }
val pq = PriorityQueue<Int>(2, compareByValue)
val array = arrayOf(2, 5, 7, 93, 14, 78, 3)
}
fun minMeetingRooms(intervals: Array<IntArray>): Int {
if (intervals.isEmpty()) return 0
val pq = PriorityQueue<Int> { n1, n2 -> n1 - n2 }
intervals.sortWith(kotlin.Comparator { a: IntArray, b: IntArray -> a[0] - b[0] })
pq.add(intervals[0][1])
for (i in intervals.indices) {
if (intervals[i][0] >= pq.peek()) {
pq.poll()
}
pq.add(intervals[i][1])
}
return pq.size
}
fun minMeetingRooms2(intervals: Array<IntArray>): Int {
// Check for the base case. If there are no intervals, return 0
if (intervals.size == 0) {
return 0
}
// Min heap
val allocator = PriorityQueue<Int>(
intervals.size
) { a, b -> a - b }
// Sort the intervals by start time
Arrays.sort(
intervals
) { a, b -> a[0] - b[0] }
// Add the first meeting
allocator.add(intervals[0][1])
// Iterate over remaining intervals
for (i in 1 until intervals.size) {
// If the room due to free up the earliest is free, assign that room to this meeting.
if (intervals[i][0] >= allocator.peek()) {
allocator.poll()
}
// If a new room is to be assigned, then also we add to the heap,
// If an old room is allocated, then also we have to add to the heap with updated end time.
allocator.add(intervals[i][1])
}
// The size of the heap tells us the minimum rooms required for all the meetings.
return allocator.size
} | 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 2,448 | DS_Algo_Kotlin | MIT License |
src/Day07.kt | frango9000 | 573,098,370 | false | {"Kotlin": 73317} | fun main() {
val input = readInput("Day07")
println(Day07.part1(input))
println(Day07.part2(input))
}
class Day07 {
companion object {
fun getFolderSizes(input: List<String>): MutableMap<String, Int> {
val folders: MutableMap<String, Int> = mutableMapOf()
val stack: ArrayDeque<String> = ArrayDeque()
input.filterNot { it == "$ ls" || it.startsWith("dir") }.forEach {
if (it.startsWith("$ cd")) {
val cdParam = it.subSequence(5, it.length).toString()
if (cdParam == "..") {
stack.removeLast()
} else {
val folderRoute = stack.joinToString("/") + "/$cdParam"
stack.addLast(folderRoute)
if (!folders.containsKey(folderRoute)) {
folders[folderRoute] = 0
}
}
} else {
val fileSize = it.split(" ").first().toInt()
for (parent in stack) {
folders[parent] = folders[parent]?.plus(fileSize) ?: fileSize
}
}
}
return folders
}
fun part1(input: List<String>): Int {
val folders: MutableMap<String, Int> = getFolderSizes(input)
return folders.values.filter { it <= 100000 }.sum()
}
fun part2(input: List<String>): Int {
val folders: MutableMap<String, Int> = getFolderSizes(input)
val totalSize = folders["//"]
val requiredCleanup = -40000000 + totalSize!!
return folders.values.sorted().first { it >= requiredCleanup }
}
}
}
| 0 | Kotlin | 0 | 0 | 62e91dd429554853564484d93575b607a2d137a3 | 1,784 | advent-of-code-22 | Apache License 2.0 |
2022/main/day_09/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_09_2022
import java.io.File
import kotlin.math.abs
fun day9(input: List<String>) {
var headPos = 0 to 0
var tailPos= 0 to 0
val visited = mutableMapOf((0 to 0) to 1)
val tailVisited = mutableMapOf((0 to 0) to 1)
val lastTen = ArrayDeque((0..9).map { 0 to 0 }.toList())
val inputs = input.map { it.split(' ')[0] to it.split(' ')[1].toInt() }
for ((direction, amount) in inputs) {
for (i in 1..amount) {
when (direction) {
"R" -> {
headPos = headPos.first + 1 to headPos.second
lastTen[0] = lastTen[0].first + 1 to lastTen[0].second
}
"L" -> {
headPos = headPos.first - 1 to headPos.second
lastTen[0] = lastTen[0].first - 1 to lastTen[0].second
}
"U" -> {
headPos = headPos.first to headPos.second + 1
lastTen[0] = lastTen[0].first to lastTen[0].second + 1
}
"D" -> {
headPos = headPos.first to headPos.second - 1
lastTen[0] = lastTen[0].first to lastTen[0].second - 1
}
}
if (abs(headPos.first - tailPos.first) == 2 && headPos.second == tailPos.second) {
tailPos = tailPos.first + (if (headPos.first > tailPos.first) 1 else -1) to tailPos.second
} else if (abs(headPos.second - tailPos.second) == 2 && headPos.first == tailPos.first) {
tailPos = tailPos.first to tailPos.second + (if (headPos.second > tailPos.second) 1 else -1)
} else if (headPos.first != tailPos.first && headPos.second != tailPos.second && abs(headPos.first - tailPos.first) + abs(headPos.second - tailPos.second) > 2) {
tailPos = (tailPos.first + (if (headPos.first > tailPos.first) 1 else -1)) to (tailPos.second + (if (headPos.second > tailPos.second) 1 else -1))
}
for (j in 1..9) {
val head = lastTen[j-1]
val tail = lastTen[j]
if (abs(head.first - tail.first) == 2 && head.second == tail.second) {
lastTen[j] = tail.first + (if (head.first > tail.first) 1 else -1) to tail.second
} else if (abs(head.second - tail.second) == 2 && head.first == tail.first) {
lastTen[j] = tail.first to tail.second + (if (head.second > tail.second) 1 else -1)
} else if (head.first != tail.first && head.second != tail.second && abs(head.first - tail.first) + abs(head.second - tail.second) > 2) {
lastTen[j] = (tail.first + (if (head.first > tail.first) 1 else -1)) to (tail.second + (if (head.second > tail.second) 1 else -1))
}
}
visited[tailPos] = visited.getOrDefault(tailPos, 0) + 1
tailVisited[lastTen[9]] = visited.getOrDefault(lastTen[9], 0) + 1
}
}
print("\n----- Part 1 -----\n")
print("The tail visits ${visited.size} positions at least once")
print("\n----- Part 2 -----\n")
print("The end of the tail visits ${tailVisited.size} positions at least once")
}
fun main(){
day9(File("src/inputs/Day_09.txt").readLines())
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 3,293 | AdventofCode | MIT License |
src/main/kotlin/com/dambra/adventofcode2018/day2/BoxChecksum.kt | pauldambra | 159,939,178 | false | null | package com.dambra.adventofcode2018.day2
fun List<LetterFrequency>.boxChecksum(): Int {
var twos = 0
var threes = 0
this.forEach {
if (it.exactlyTwoTimesLetter.isNotEmpty()) twos++
if (it.exactlyThreeTimesLetter.isNotEmpty()) threes++
}
return twos * threes
}
data class Comparison(val left: String, val right: String, val numberOfMatchingCharacters: Int) {
// doesn't matter what order left and right are when compared
override fun equals(other: Any?): Boolean {
if (other != null && other is Comparison) {
return other.numberOfMatchingCharacters == this.numberOfMatchingCharacters
&&
(other.left == this.left || other.left == this.right)
&&
(other.right == this.left || other.right == this.right)
}
return false
}
override fun hashCode(): Int {
val result = (left + right).toSortedSet().hashCode()
return 31 * result + numberOfMatchingCharacters
}
}
fun List<String>.similarIds(): List<String> {
val targetMatchingCharacters = this.first().length - 1
val comparisons = mutableSetOf<Comparison>()
this.forEachIndexed { leftIndex, left ->
this.forEachIndexed { rightIndex, right ->
if (leftIndex != rightIndex) {
val matches = left.zip(right)
.filter { it -> it.first == it.second }
.count()
if (matches == targetMatchingCharacters) {
comparisons.add(Comparison(left, right, matches))
}
}
}
}
return comparisons
.map {
it.left.zip(it.right)
.fold("") { acc, pair ->
if (pair.first == pair.second) {
acc + pair.first.toString()
} else {
acc
}
}
}
} | 0 | Kotlin | 0 | 1 | 7d11bb8a07fb156dc92322e06e76e4ecf8402d1d | 1,985 | adventofcode2018 | The Unlicense |
src/main/kotlin/g0801_0900/s0854_k_similar_strings/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0854_k_similar_strings
// #Hard #String #Breadth_First_Search #2023_03_31_Time_136_ms_(100.00%)_Space_33.6_MB_(100.00%)
class Solution {
fun kSimilarity(a: String, b: String): Int {
var ans = 0
val achars = a.toCharArray()
val bchars = b.toCharArray()
ans += getAllPerfectMatches(achars, bchars)
for (i in achars.indices) {
if (achars[i] == bchars[i]) {
continue
}
return ans + checkAllOptions(achars, bchars, i, b)
}
return ans
}
private fun checkAllOptions(achars: CharArray, bchars: CharArray, i: Int, b: String): Int {
var ans = Int.MAX_VALUE
for (j in i + 1 until achars.size) {
if (achars[j] == bchars[i] && achars[j] != bchars[j]) {
swap(achars, i, j)
ans = Math.min(ans, 1 + kSimilarity(String(achars), b))
swap(achars, i, j)
}
}
return ans
}
private fun getAllPerfectMatches(achars: CharArray, bchars: CharArray): Int {
var ans = 0
for (i in achars.indices) {
if (achars[i] == bchars[i]) {
continue
}
for (j in i + 1 until achars.size) {
if (achars[j] == bchars[i] && bchars[j] == achars[i]) {
swap(achars, i, j)
ans++
break
}
}
}
return ans
}
private fun swap(a: CharArray, i: Int, j: Int) {
val temp = a[i]
a[i] = a[j]
a[j] = temp
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,627 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/day24/Code.kt | fcolasuonno | 317,324,330 | false | null | package day24
import isDebug
import java.io.File
private val Pair<Int, Int>.hexNeighbours: Set<Pair<Int, Int>>
get() = Direction.values().map { Pair(first + it.x, second + it.y) }.toSet()
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val parsed = parse(input)
part1(parsed)
part2(parsed)
}
enum class Direction(val x: Int, val y: Int) {
e(2, 0),
se(1, -1),
sw(-1, -1),
w(-2, 0),
nw(-1, 1),
ne(1, 1)
}
fun parse(input: List<String>) = input.map {
mutableListOf<Direction>().apply {
var cursor = 0
while (cursor < it.length) {
add(try {
Direction.valueOf(it.substring(cursor, cursor + 1)).also { cursor++ }
} catch (_: Throwable) {
Direction.valueOf(it.substring(cursor, cursor + 2)).also { cursor += 2 }
})
}
}.toList()
}
fun part1(input: List<List<Direction>>) {
val map = mutableMapOf<Pair<Int, Int>, Boolean>().apply {
input.forEach {
val pos = it.fold(0 to 0) { acc, direction ->
acc.copy(acc.first + direction.x, acc.second + direction.y)
}
this[pos] = !getOrDefault(pos, false)
}
}.toMap()
println("Part 1 = ${map.count { it.value }}")
}
fun part2(input: List<List<Direction>>) {
val startingBlacks = mutableMapOf<Pair<Int, Int>, Boolean>().apply {
input.forEach {
val pos = it.fold(0 to 0) { acc, direction ->
acc.copy(acc.first + direction.x, acc.second + direction.y)
}
this[pos] = !getOrDefault(pos, false)
}
}.filterValues { it }.keys
val res = generateSequence(startingBlacks) { blacks ->
val neighbours = blacks.associateWith { it.hexNeighbours }
val toWhite = blacks.filter {
val nextBlacks = neighbours.getValue(it).count { it in blacks }
nextBlacks == 0 || nextBlacks > 2
}
val whiteNeighbours = (neighbours.flatMap { it.value } - blacks).groupingBy { it }.eachCount()
val newBlacks = whiteNeighbours.filter { it.value == 2 }.keys
blacks - toWhite + newBlacks
}.elementAt(100).count()
println("Part 2 = $res")
} | 0 | Kotlin | 0 | 0 | e7408e9d513315ea3b48dbcd31209d3dc068462d | 2,379 | AOC2020 | MIT License |
src/Day01.kt | polbins | 573,082,325 | false | {"Kotlin": 9981} | fun main() {
fun part1(input: List<String>): Long {
var current: Long = 0
var highest: Long = 0
for (s in input) {
current = s.toLongOrNull()?.let {
current + it
} ?: 0
if (current > highest) {
highest = current
}
}
return highest
}
fun part2(input: List<String>): Set<Int> {
var current = 0
val sums = sortedSetOf(0)
for (s in input) {
val num = s.toIntOrNull()
current = if (num != null) {
current + num
} else {
if (current > sums.first()) {
sums.add(current)
if (sums.size > 3) {
sums.pollFirst()
}
}
0
}
}
return sums
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000L)
val input1 = readInput("Day01")
println(part1(input1))
val input2 = readInput("Day01")
println(part2(input2).sum())
}
| 0 | Kotlin | 0 | 0 | fb9438d78fed7509a4a2cf6c9ea9e2eb9d059f14 | 996 | AoC-2022 | Apache License 2.0 |
src/Day07.kt | AxelUser | 572,845,434 | false | {"Kotlin": 29744} | import java.util.Stack
fun main() {
fun List<String>.buildTree(): Map<String, Int> {
val stack = Stack<String>()
val dirs = mutableMapOf<String, Int>()
dirs["/"] = 0
stack.push("/")
for (i in 1..lastIndex) {
val line = this[i].split(' ')
when (line[0]) {
"$" -> when (line[1]) {
"cd" -> when (line[2]) {
".." -> stack.pop()
else -> stack.push("${stack.peek()}${line[2]}/")
}
}
"ls" -> {}
"dir" -> {
dirs["${stack.peek()}${line[1]}/"] = 0
}
else -> {
val size = line[0].toInt()
stack.forEach {
dirs[it] = dirs[it]!! + size
}
}
}
}
return dirs
}
fun part1(input: List<String>): Int {
val dirs = input.buildTree()
return dirs.values.filter { v -> v <= 100000 }.sum()
}
fun part2(input: List<String>): Int {
val dirs = input.buildTree()
val target = 30000000 - (70000000 - dirs["/"]!!)
return dirs.values.filter { v -> v >= target }.min()
}
var input = readInput("Day07_test")
check(part1(input) == 95437)
check(part2(input) == 24933642)
input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 042e559f80b33694afba08b8de320a7072e18c4e | 1,499 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-04.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2021
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputText
fun main() {
val input = readInputText(2021, "04-input")
val test1 = readInputText(2021, "04-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: String): Int {
val bingo = Bingo(input)
return bingo.firstWin()
}
private fun part2(input: String): Int {
val bingo = Bingo(input)
return bingo.lastWin()
}
private class Bingo(input: String) {
private val numbers: List<Int>
private val boards: List<Board>
init {
val split = input.split("\n\n")
numbers = split.first().split(",").map { it.toInt() }
boards = split.drop(1).map { Board(it) }
}
fun firstWin(): Int {
var position = 0
do {
val n = numbers[position]
boards.forEach {
it.play(n)
}
position++
} while (!boards.any { it.isWinning() })
val sum = boards.first { it.isWinning() }.winningSum
val winningNum = numbers[position - 1]
return winningNum * sum
}
fun lastWin(): Int {
var position = 0
var lastBoardIndex = 0
do {
val n = numbers[position]
boards.forEachIndexed { index, board ->
if (board.isWinning()) return@forEachIndexed
board.play(n)
if (board.isWinning()) lastBoardIndex = index
}
position++
} while (boards.any { !it.isWinning() })
val sum = boards[lastBoardIndex].winningSum
val winningNum = numbers[position - 1]
return winningNum * sum
}
class Board(input: String) {
data class Field(val number: Int, var checked: Boolean = false)
val area: List<List<Field>>
private var won = false
val winningSum
get() = area.sumOf { line ->
line.filter { !it.checked }.sumOf { it.number }
}
fun isWinning(): Boolean {
if (won) return true
area.forEach {
if (it.all { it.checked }) {
won = true
return true
}
}
repeat(5) { column ->
if (area.all { it[column].checked }) {
won = true
return true
}
}
return false
}
fun play(n: Int) {
area.forEach { line ->
line.forEach {
if (it.number == n) it.checked = true
}
}
}
init {
area = input.lines().map {
it.windowed(3, 3, true).map { Field(it.trim().toInt()) }
}
}
}
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 3,001 | advent-of-code | MIT License |
src/Day02.kt | fouksf | 572,530,146 | false | {"Kotlin": 43124} | enum class PlayedChoice() {
A {
override fun getScore(): Int {
return 1
}
},
B {
override fun getScore(): Int {
return 2
}
},
C {
override fun getScore(): Int {
return 3
}
};
abstract fun getScore(): Int
}
enum class RockPaperScissors() {
X {
override fun getScore(played: PlayedChoice): Int {
return when (played) {
PlayedChoice.A -> 4
PlayedChoice.B -> 1
PlayedChoice.C -> 7
}
}
},
Y {
override fun getScore(played: PlayedChoice): Int {
return when (played) {
PlayedChoice.A -> 8
PlayedChoice.B -> 5
PlayedChoice.C -> 2
}
}
},
Z {
override fun getScore(played: PlayedChoice): Int {
return when (played) {
PlayedChoice.A -> 3
PlayedChoice.B -> 9
PlayedChoice.C -> 6
}
}
};
abstract fun getScore(played: PlayedChoice): Int
}
enum class Result() {
X {
override fun getScore(played: PlayedChoice): Int {
return 0
}
override fun getMyChoice(played: PlayedChoice): PlayedChoice {
return when (played) {
PlayedChoice.A -> PlayedChoice.C
PlayedChoice.B -> PlayedChoice.A
PlayedChoice.C -> PlayedChoice.B
}
}
},
Y {
override fun getScore(played: PlayedChoice): Int {
return 3
}
override fun getMyChoice(played: PlayedChoice): PlayedChoice {
return played
}
},
Z {
override fun getScore(played: PlayedChoice): Int {
return 6
}
override fun getMyChoice(played: PlayedChoice): PlayedChoice {
return when (played) {
PlayedChoice.A -> PlayedChoice.B
PlayedChoice.B -> PlayedChoice.C
PlayedChoice.C -> PlayedChoice.A
}
}
};
abstract fun getScore(played: PlayedChoice): Int
abstract fun getMyChoice(played: PlayedChoice): PlayedChoice
}
fun main() {
fun readGames(input: List<String>): List<Int> {
val scores = ArrayList<Int>()
for (game in input) {
val playedChoice = PlayedChoice.valueOf(game.substring(0, 1))
val myChoice = RockPaperScissors.valueOf(game.substring(2))
scores.add(myChoice.getScore(playedChoice))
}
return scores
}
fun part1(input: List<String>): Int {
val games = readGames(input)
return games.sum()
}
fun part2(input: List<String>): Int {
val scores = ArrayList<Int>()
for (game in input) {
val playedChoice = PlayedChoice.valueOf(game.substring(0, 1))
val desiredOutcome = Result.valueOf(game.substring(2))
scores.add(desiredOutcome.getScore(playedChoice) + desiredOutcome.getMyChoice(playedChoice).getScore())
}
return scores.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val input = readInput("Day02")
// println(part1(testInput))
println(part2(testInput))
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 701bae4d350353e2c49845adcd5087f8f5409307 | 3,427 | advent-of-code-2022 | Apache License 2.0 |
src/day7/Day7.kt | jorgensta | 573,824,365 | false | {"Kotlin": 31676} | import day7.Dir
import day7.File
fun String.isTerminalInstruction() = this.contains("$")
fun String.isChangeDirectory() = this.contains("cd") && this.isTerminalInstruction()
fun String.isListDir() = this.contains("ls") && this.isTerminalInstruction()
fun String.goesUpOneDirectory() = this.isChangeDirectory() && this.split(" ").last() == ".."
fun String.goesIntoDirectory() = this.isChangeDirectory() && this.contains("..").not()
fun String.dirName() = this.split(" ").last()
fun String.isFile() = this.split(" ").first().all { it.isDigit() }
fun String.fileSize() = this.split(" ").first().toInt()
fun String.fileName() = this.split(" ").last()
fun String.isDir() = this.split(" ").first() == "dir"
fun String.isRootNode() = this.isChangeDirectory() && this.split(" ").last() == "/"
fun main() {
val day = "day7"
val filename = "Day07"
val rootDir = Dir("/")
fun constructFilesystem(input: List<String>) {
var currentDir = rootDir
input.forEach { line ->
if (line.isListDir()) return@forEach
if (line.isRootNode()) {
currentDir = rootDir
return@forEach
}
if (line.goesIntoDirectory()) {
try {
currentDir = currentDir.children.find { it.name == line.dirName() }!!
} catch (ex: Exception) {
println("Could not find child")
}
return@forEach
}
if (line.goesUpOneDirectory()) {
if (currentDir.parent != null) {
currentDir = currentDir.parent!!
return@forEach
}
}
if (line.isDir()) {
val newDirectory = Dir(line.dirName())
currentDir.children.add(newDirectory)
newDirectory.parent = currentDir
return@forEach
}
if(line.isFile()) {
currentDir.files.add(File(line.fileSize(), line.fileName()))
return@forEach
}
}
}
fun browse(dir: Dir, collector: (Dir) -> Unit) {
if (dir.children.isEmpty()) return
dir.children.forEach {
collector(it)
browse(it, collector)
}
}
fun sumAllDirectoriesOfSizeAtMost(size: Int): Int {
var result = 0
val collector: (Dir) -> Unit = { dir: Dir ->
val dirSize = dir.getDirSize()
if(dirSize <= size) {
result += dirSize
}
}
browse(rootDir, collector)
return result
}
fun findAllDirs(): List<Dir> {
val dirs = mutableListOf<Dir>()
val collector: (Dir) -> Unit = { dir: Dir -> dirs.add(dir)}
browse(rootDir, collector)
return dirs.toList()
}
fun findSizeOfDirectoryToDelete(input: List<String>): Int? {
constructFilesystem(input)
val sizeAllDirs = rootDir.getDirSize()
val totalDiskSpace = 70000000
val atleastUnusedSpace = 30000000
val unusedSpace = totalDiskSpace - sizeAllDirs
val dirs = findAllDirs().map { it.getDirSize() }.sorted()
return dirs.find { dirSize -> (unusedSpace + dirSize) >= atleastUnusedSpace }
}
fun part1(input: List<String>): Int {
constructFilesystem(input)
return sumAllDirectoriesOfSizeAtMost(100000)
}
fun part2(input: List<String>): Int? {
return findSizeOfDirectoryToDelete(input)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/$day/${filename}_test")
val input = readInput("/$day/$filename")
// val partOneTest = part1(testInput)
// check(partOneTest == 95437)
// println("Part one: ${part1(input)}")
// val partTwoTest = part2(testInput)
// check(partTwoTest == 24933642)
println("Part two: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 7243e32351a926c3a269f1e37c1689dfaf9484de | 3,951 | AoC2022 | Apache License 2.0 |
src/main/kotlin/aoc/day1/Trebuchet.kt | hofiisek | 726,824,585 | false | {"Kotlin": 5136} | package aoc.day1
import aoc.dropFirst
import aoc.loadInput
import java.io.File
/**
* https://adventofcode.com/2023/day/1
*
* @author <NAME>
*/
fun File.part1() = readLines()
.map { line -> listOfNotNull(line.firstOrNull { it.isDigit() }, line.lastOrNull { it.isDigit() })
.joinToString(separator = "")
}
.filter { it.isNotBlank() }
.sumOf { it.toInt() }
.also(::println)
fun File.part2() = readLines()
.map { listOf(it.findFirstDigit(), it.findLastDigit()) }
.map { "${it.first()}${it.last()}".toInt() }
.sumOf { it }
.also(::println)
private val spelledDigits = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9
)
private fun String.findFirstDigit(): Int{
fun findFirstDigit(chars: List<Char>, acc: String): Int = chars.firstOrNull()
?.let {
if (it.isDigit()) {
it.digitToInt()
} else {
val substring = "$acc$it"
spelledDigits.entries
.firstOrNull { (spelledDigit, _) ->
substring.contains(spelledDigit)
}
?.let { (_, digit) ->
digit
}
?: findFirstDigit(chars.dropFirst(), substring)
}
}
?: throw IllegalStateException("String $this contains no digits")
return findFirstDigit(toCharArray().toList(), "")
}
private fun String.findLastDigit(): Int{
fun findLastDigit(chars: List<Char>, acc: String): Int = chars.firstOrNull()
?.let {
if (it.isDigit()) {
it.digitToInt()
} else {
val substring = "$acc$it"
spelledDigits.entries
.firstOrNull { (spelledDigit, _) ->
substring.contains(spelledDigit.reversed())
}
?.let { (_, digit) ->
digit
}
?: findLastDigit(chars.dropFirst(), substring)
}
}
?: throw IllegalStateException("String $this contains no digits")
return findLastDigit(toCharArray().reversed().toList(), "")
}
fun main() {
with(loadInput(day = 1)) {
part1()
part2()
}
} | 0 | Kotlin | 0 | 0 | 35a93ebd980202ab0d512310ed611a7d96dd330a | 2,392 | Advent-of-code-2023 | MIT License |
src/day04/Day04.kt | iliascholl | 572,982,464 | false | {"Kotlin": 8373} | package day04
import readInput
private fun String.toRangePair(): Pair<IntRange, IntRange> =
split(',', limit = 2)
.map(String::toRange)
.let { (first, second) -> first to second }
private fun String.toRange(): IntRange =
split('-', limit = 2)
.let { (start, end) -> start.toInt()..end.toInt() }
private infix fun IntRange.fullyContains(other: IntRange): Boolean =
contains(other.first) && contains(other.last)
private infix fun IntRange.overlaps(other: IntRange): Boolean =
this.contains(other.first) || other.contains(this.first)
fun main() {
fun part1(input: List<String>) = input
.map(String::toRangePair)
.count { (first, second) -> first fullyContains second || second fullyContains first }
fun part2(input: List<String>) = input
.map(String::toRangePair)
.count { (first, second) -> first overlaps second }
val testInput = readInput("day04/test")
check(part1(testInput) == 3)
val input = readInput("day04/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 26db12ddf4731e4ee84f45e1dc4385707f9e1d05 | 1,074 | advent-of-code-kotlin | Apache License 2.0 |
src/Day09.kt | seana-zr | 725,858,211 | false | {"Kotlin": 28265} | fun main() {
fun List<Int>.getDifferences(): MutableList<Int> {
val result = mutableListOf<Int>()
for (i in 1..this.lastIndex) {
result.add(this[i] - this[i - 1])
}
return result
}
fun List<Int>.isAllZeros(): Boolean = all { it == 0 }
fun part1(input: List<String>): Int {
var result = 0
input.forEach { line ->
val firstSequence = line
.split(" ")
.map { it.toInt() }
.toMutableList()
val sequences = mutableListOf(firstSequence)
while (!sequences.last().isAllZeros()) {
sequences.add(sequences.last().getDifferences())
}
// println(sequences)
sequences.last().add(0)
val reversed = sequences.reversed()
reversed.drop(1).forEachIndexed { index, sequence ->
sequence.add(reversed[index].last() + sequence.last())
}
println(sequences)
result += sequences.first().last()
println(result)
}
println("RESULT: $result")
return result
}
fun part2(input: List<String>): Int {
var result = 0
input.forEach { line ->
val firstSequence = line
.split(" ")
.map { it.toInt() }
.reversed()
.toMutableList()
val sequences = mutableListOf(firstSequence)
while (!sequences.last().isAllZeros()) {
sequences.add(sequences.last().getDifferences())
}
// println(sequences)
sequences.last().add(0)
val reversed = sequences.reversed()
reversed.drop(1).forEachIndexed { index, sequence ->
sequence.add(reversed[index].last() + sequence.last())
}
println(sequences)
result += sequences.first().last()
println(result)
}
println("RESULT: $result")
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
// check(part1(testInput) == 114)
check(part2(testInput) == 2)
val input = readInput("Day09")
// part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | da17a5de6e782e06accd3a3cbeeeeb4f1844e427 | 2,336 | advent-of-code-kotlin-template | Apache License 2.0 |
src/main/kotlin/year2021/day-10.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2021
import lib.aoc.Day
import lib.aoc.Part
fun main() {
Day(10, 2021, PartA10(), PartB10()).run()
}
open class PartA10 : Part() {
protected lateinit var lines: List<String>
override fun parse(text: String) {
lines = text.split("\n")
}
override fun compute(): String {
return lines.sumOf(::pointsForLine).toString()
}
protected fun pointsForLine(line: String): Int {
val pointTable = mapOf(')' to 3, ']' to 57, '}' to 1_197, '>' to 25_137)
val stack = mutableListOf<Char>()
for (char in line) {
val matching = checkCharacter(char, stack)
if (!matching) {
return pointTable.getValue(char)
}
}
return 0
}
protected fun checkCharacter(char: Char, stack: MutableList<Char>): Boolean {
val matchingCharacter = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>')
if (char in listOf('(', '[', '{', '<')) {
stack.add(char)
} else {
val lastChar = stack.removeLast()
if (char != matchingCharacter[lastChar]) {
return false
}
}
return true
}
override val exampleAnswer: String
get() = "26397"
override val customExampleData: String?
get() = """
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
""".trimIndent()
}
class PartB10 : PartA10() {
override fun compute(): String {
val notCorruptLines = lines.filter { pointsForLine(it) == 0 }
val points = notCorruptLines.map(::pointsToFinish)
return points.median().toString()
}
private fun pointsToFinish(line: String): Long {
val pointTable = mapOf('(' to 1, '[' to 2, '{' to 3, '<' to 4)
val stack = mutableListOf<Char>()
line.forEach { checkCharacter(it, stack) }
stack.reverse()
return stack.fold(0L) { acc, c -> acc * 5 + pointTable.getValue(c) }
}
private fun List<Long>.median() = sorted().let {
if (it.size % 2 == 0) {
(it[it.size / 2] + it[(it.size - 1) / 2]) / 2
} else {
it[it.size / 2]
}
}
override val exampleAnswer: String
get() = "288957"
}
| 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 2,649 | Advent-Of-Code-Kotlin | MIT License |
2022/src/main/kotlin/Day05.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day05 {
fun part1(input: String): String {
val inputs = parseInput(input)
val crates = inputs.crates.toMutableList()
inputs.moves.forEach { (number, from, to) ->
crates[to] = crates[to] + crates[from].takeLast(number).reversed()
crates[from] = crates[from].dropLast(number)
}
return crates.getTopCrates()
}
fun part2(input: String): String {
val inputs = parseInput(input)
val crates = inputs.crates.toMutableList()
inputs.moves.forEach { (number, from, to) ->
crates[to] = crates[to] + crates[from].takeLast(number)
crates[from] = crates[from].dropLast(number)
}
return crates.getTopCrates()
}
private fun List<List<Char>>.getTopCrates() = this.map { it.last() }.joinToString("")
private data class Input(val crates: List<List<Char>>, val moves: List<Move>)
private data class Move(val number: Int, val from: Int, val to: Int)
private fun parseInput(input: String): Input {
val (crateInput, moveInput) = input.split("\n\n")
return Input(parseCrateInput(crateInput), parseMoves(moveInput))
}
private fun parseCrateInput(input: String): List<List<Char>> {
val crates = mutableListOf<MutableList<Char>>()
input
.split("\n")
.reversed()
.drop(1)
.forEach { line ->
line.chunked(4).forEachIndexed { index, chunk ->
if (crates.size == index) {
crates.add(mutableListOf())
}
if (chunk[1] != ' ') {
crates[index].add(chunk[1])
}
}
}
return crates
}
private fun parseMoves(input: String): List<Move> {
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
return input
.splitNewlines()
.map { regex.matchEntire(it)!!.destructured }
.map { (number, from, to) -> Move(number.toInt(), from.toInt() - 1, to.toInt() - 1) }
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,881 | advent-of-code | MIT License |
src/Day04.kt | epishkin | 572,788,077 | false | {"Kotlin": 6572} | fun main() {
fun parseInput(input: List<String>) = input
.map {
it.split(",")
.map { txt ->
val (start, end) = txt
.split("-")
.map { num -> num.trim().toInt() }
IntRange(start, end).toSet()
}
}
fun part1(input: List<String>): Int {
return parseInput(input)
.count {
val maxSize = it.maxOf { r -> r.size }
val (one, two) = it
one.union(two).size == maxSize
}
}
fun part2(input: List<String>): Int {
return parseInput(input)
.count {
val (one, two) = it
one.intersect(two).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 | e5e5755c2d77f75750bde01ec5aad70652ef4dbf | 1,078 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | mhuerster | 572,728,068 | false | {"Kotlin": 24302} | fun main() {
// input: string of format 2-4,6-8
fun parseSectionStrings(pair: String): List<String> {
val (section1, section2) = pair.split(",")
return listOf(section1, section2)
}
// input: string of format 2-4
fun getSectionRange(section: String): Set<Int> {
val (start, end) = section.split("-").map{ it.toInt()!! }
return start.rangeTo(end)!!.toSet()
}
fun part1(pairs: List<String>): Int {
return pairs.map {
parseSectionStrings(it)
.map { getSectionRange((it))} }
.count {
val (a, b) = it
(a.containsAll(b)).or(b.containsAll(a))
}
}
fun part2(pairs: List<String>): Int {
return pairs.map {
parseSectionStrings(it)
.map { getSectionRange((it))} }
.count {
val (a, b) = it
!a.intersect(b).isEmpty()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_sample")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 5f333beaafb8fe17ff7b9d69bac87d368fe6c7b6 | 1,155 | 2022-advent-of-code | Apache License 2.0 |
src/main/kotlin/days/day24/Day24.kt | Stenz123 | 725,707,248 | false | {"Kotlin": 123279, "Shell": 862} | package days.day24
import Jama.Matrix
import days.Day
import kotlin.math.round
class Day24 : Day() {
override fun partOne(): Any {
val testArea = 200000000000000.0..400000000000000.0
val vectors = readInput().map {
val split = it.split(" @ ").map { it.split(", ").map(String::toDouble) }
val point = Point(split.first()[0], split.first()[1], 0.0)
val velocity = Velocity(split.last()[0], split.last()[1], 0.0)
Hail(point, velocity)
}
// return vectors.cartesianProduct().count { combination ->
// val collision = Hail.collision2D(combination.first, combination.second)
// collision != null && collision.x in testArea && collision.y in testArea
//}
return "aeds"
}
operator fun <T> List<T>.component6(): T = get(5)
override fun partTwo(): Any {
//math is very hard and my brain hurts
//i needed help with the math
//https://www.reddit.com/r/adventofcode/comments/18pnycy/comment/kesqnis/?utm_source=share&utm_medium=web2x&context=3
val hailstones = readInput().map {
val split = it.split(" @ ").map { it.split(", ").map(String::toDouble) }
val point = Point(split.first()[0], split.first()[1], split.first()[2])
val velocity = Velocity(split.last()[0], split.last()[1], split.last()[2])
Hail(point, velocity)
}
var coefficients = hailstones.combinations(2).take(6).drop(2).map { (h1, h2) ->
(doubleArrayOf(h2.velocity.y - h1.velocity.y,
h1.velocity.x - h2.velocity.x,
h1.point.y - h2.point.y,
h2.point.x - h1.point.x) to
doubleArrayOf((h1.velocity.x * h1.point.y - h2.velocity.x * h2.point.y + h2.point.x * h2.velocity.y - h1.point.x * h1.velocity.y)))
}
val A: Matrix = Matrix(coefficients.map { it.first }.toList().toTypedArray())
val x: Matrix = Matrix(coefficients.map { it.second }.toList().toTypedArray())
val (a, b, d, e) = A.inverse().times(x).array.map { round(it.first()) }
val h1 = hailstones.first()
val t1 = (a - h1.point.x) / (h1.velocity.x - d)
val h2 = hailstones[1]
val t2 = (a - h2.point.x) / (h2.velocity.x - d)
val f = ((h1.point.z - h2.point.z) + t1 * h1.velocity.z - t2 * h2.velocity.z) / (t1 - t2)
val c = h1.point.z + t1 * (h1.velocity.z - f)
val part2 = a + b + c
println("Part 2: $part2")
return part2.toLong()
}
}
operator fun <T> List<T>.component6(): T = get(5)
fun <T> List<T>.combinations(r: Int): Sequence<List<T>> = sequence {
if (r > size) return@sequence
val indices = IntArray(r)
while (true) {
yield(indices.map { get(it) })
var i = r - 1
while (i >= 0 && indices[i] == size - r + i) i--
if (i < 0) break
indices[i]++
for (j in i + 1 until r) indices[j] = indices[j - 1] + 1
}
}
// Extensions
//fun <T> List<T>.cartesianProduct(): List<Pair<T, T>> {
// val result = mutableListOf<Pair<T, T>>()
//
// for (i in indices) {
// for (j in i + 1 until size) {
// val pair = Pair(get(i), get(j))
// val reversePair = Pair(get(j), get(i))
//
// if (!result.contains(pair) && !result.contains(reversePair)) {
// result.add(pair)
// }
// }
// }
//
// return result
//}
class Hail(val point: Point, val velocity: Velocity) {
override fun toString() = "$point $velocity"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Hail
if (point != other.point) return false
if (velocity != other.velocity) return false
return true
}
override fun hashCode(): Int {
var result = point.hashCode()
result = 31 * result + velocity.hashCode()
return result
}
fun addVelocity() = Point(point.x + velocity.x, point.y + velocity.y, point.z + velocity.z)
companion object {
fun collision2D(vector1: Hail, vector2: Hail): Point? {
val secondPoint1 = vector1.addVelocity()
val k1 = calculateSlope(vector1.point, secondPoint1)
val d1 = calculateYIntercept(vector1.point, k1)
val secondPoint2 = vector2.addVelocity()
val k2 = calculateSlope(vector2.point, secondPoint2)
val d2 = calculateYIntercept(vector2.point, k2)
val intersect = findIntersectionPoint(k1, d1, k2, d2)
if (vector1.velocity.x > 0) {
if (intersect.x < vector1.point.x) return null
} else {
if (intersect.x > vector1.point.x) return null
}
if (vector2.velocity.x > 0) {
if (intersect.x < vector2.point.x) return null
} else {
if (intersect.x > vector2.point.x) return null
}
return intersect
}
fun findIntersectionPoint(k1: Double, d1: Double, k2: Double, d2: Double): Point {
// Solve for x: k1x + d1 = k2x + d2
val x = (d2 - d1) / (k1 - k2)
// Substitute x into either function to find y
val y = k1 * x + d1
return Point(x, y, 0.0)
}
fun calculateSlope(point1: Point, point2: Point): Double {
val deltaY = point2.y - point1.y
val deltaX = point2.x - point1.x
// Avoid division by zero
if (deltaX == 0.0) {
throw IllegalArgumentException("The slope is undefined for vertical lines.")
}
return deltaY / deltaX
}
fun calculateYIntercept(point: Point, slope: Double): Double {
return point.y - slope * point.x
}
}
}
class Point(val x: Double, val y: Double, val z: Double) {
override fun toString() = "P($x, $y, $z)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Point
if (x != other.x) return false
if (y != other.y) return false
if (z != other.z) return false
return true
}
override fun hashCode(): Int {
var result = x.hashCode()
result = 31 * result + y.hashCode()
result = 31 * result + z.hashCode()
return result
}
}
class Velocity(val x: Double, val y: Double, val z: Double) {
override fun toString() = "V($x, $y, $z)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Velocity
if (x != other.x) return false
if (y != other.y) return false
if (z != other.z) return false
return true
}
override fun hashCode(): Int {
var result = x.hashCode()
result = 31 * result + y.hashCode()
result = 31 * result + z.hashCode()
return result
}
}
| 0 | Kotlin | 1 | 0 | 3de47ec31c5241947d38400d0a4d40c681c197be | 7,142 | advent-of-code_2023 | The Unlicense |
src/Day12.kt | makohn | 571,699,522 | false | {"Kotlin": 35992} | fun main() {
val day = "12"
fun solve(input: List<String>, predicate: (Int) -> Boolean, startWith: Char, vararg endWith: Char): Int {
val inputMatrix = input.toCharMatrix()
val dataPoints = inputMatrix.dataPoints()
val startNode = dataPoints.single { it.data == startWith }
fun Char.height() = when(this) {
'S' -> 0
'E' -> 'z' - 'a'
else -> this - 'a'
}
val visited = bfs(startNode) { p ->
inputMatrix.adjacentPoints(p).filter { predicate(it.data.height() - p.data.height()) }
}
return visited.filter { it.key.data in endWith }.minBy { it.value }.value
}
fun part1(input: List<String>): Int {
return solve(input, { diff -> diff <= 1 }, 'S', 'E')
}
fun part2(input: List<String>): Int {
return solve(input, { diff -> diff >= -1 }, 'E', 'a', 'S')
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2734d9ea429b0099b32c8a4ce3343599b522b321 | 1,193 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | daniyarmukhanov | 572,847,967 | false | {"Kotlin": 9474} | //use this file as template
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEach {
val left = it.substring(0, it.length / 2).toSet()
val right = it.substring(it.length / 2, it.length).toSet()
left.forEach { leftChar ->
if (right.contains(leftChar)) {
var add = right.find { rightChar -> rightChar == leftChar }!!.toInt().minus(96)
if (add <= 0) {
add += 58
}
sum += add
}
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (i in input.indices step 3) {
val a = input[i].toSet()
val b = input[i + 1].toSet()
val c = input[i + 2].toSet()
a.forEach {
if (b.contains(it) && c.contains(it)) {
var add = a.find { q: Char -> q == it }!!.toInt().minus(96)
if (add <= 0) {
add += 58
}
sum += add
}
}
}
return sum
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebad16b2809ef0e3c7034d5eed75e6a8ea34c854 | 1,418 | aoc22 | Apache License 2.0 |
src/Day06.kt | thpz2210 | 575,577,457 | false | {"Kotlin": 50995} | private class Solution06(val input: String) {
fun part1() = findMarker(4)
fun part2() = findMarker(14)
private fun findMarker(length: Int) =
(length until input.length).first { input.subSequence(it - length, it).toSet().size == length }
}
fun main() {
val testSolution1 = Solution06("mjqjpqmgbljsphdztnvjfqwrcgsmlb")
check(testSolution1.part1() == 7)
check(testSolution1.part2() == 19)
val testSolution2 = Solution06("bvwbjplbgvbhsrlpgdmjqwftvncz")
check(testSolution2.part1() == 5)
check(testSolution2.part2() == 23)
val testSolution3 = Solution06("nppdvjthqldpwncqszvftbrmjlhg")
check(testSolution3.part1() == 6)
check(testSolution3.part2() == 23)
val testSolution4 = Solution06("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg")
check(testSolution4.part1() == 10)
check(testSolution4.part2() == 29)
val testSolution5 = Solution06("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw")
check(testSolution5.part1() == 11)
check(testSolution5.part2() == 26)
val solution = Solution06(readInput("Day06").first())
println(solution.part1())
println(solution.part2())
}
| 0 | Kotlin | 0 | 0 | 69ed62889ed90692de2f40b42634b74245398633 | 1,135 | aoc-2022 | Apache License 2.0 |
src/main/aoc2019/Day22.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2019
import kotlin.math.max
class Day22(val input: List<String>) {
sealed class Technique {
abstract fun nextPositionForCard(card: Long, deckSize: Long): Long
data class Cut(val n: Long) : Technique() {
override fun nextPositionForCard(card: Long, deckSize: Long) = Math.floorMod(card - n, deckSize)
}
data class Increment(val n: Long) : Technique() {
override fun nextPositionForCard(card: Long, deckSize: Long) = Math.floorMod(card * n, deckSize)
}
companion object {
fun fromString(input: String, deckSize: Long): List<Technique> {
fun String.getNumber() = this.split(" ").last().toLong()
return when {
input.startsWith("deal with") -> listOf(Increment(input.getNumber()))
input.startsWith("cut") -> listOf(Cut(input.getNumber()))
input.startsWith("deal into") -> listOf(
Increment(deckSize - 1),
Cut(1)
)
else -> throw IllegalStateException("Unknown shuffle technique: $input")
}
}
}
// Multiplying two very large longs will overflow, so use BigInteger to calculate
// "a * b % mod" to avoid overflows
private fun mulMod(a: Long, b: Long, mod: Long): Long {
return a.toBigInteger().multiply(b.toBigInteger()).mod(mod.toBigInteger()).longValueExact()
}
// Rules for combining techniques from:
// https://www.reddit.com/r/adventofcode/comments/ee56wh/2019_day_22_part_2_so_whats_the_purpose_of_this/fc0xvt5/
fun combine(other: Technique, deckSize: Long): List<Technique> {
return when {
this is Cut && other is Cut -> listOf(Cut(Math.floorMod(n + other.n, deckSize)))
this is Increment && other is Increment -> listOf(Increment(mulMod(n, other.n, deckSize)))
this is Cut && other is Increment -> listOf(Increment(other.n), Cut(mulMod(n, other.n, deckSize)))
else -> throw IllegalStateException("Invalid technique combination: $this and $other")
}
}
// Everything except Increment followed by Cut can be combined
fun canBeCombinedWith(other: Technique) = !(this is Increment && other is Cut)
}
fun parseInput(deckSize: Long) = input.map { Technique.fromString(it, deckSize) }.flatten()
// Find the position that the given card will have after the shuffle process has been finished
fun finalPositionForCard(card: Long,
deckSize: Long,
process: List<Technique> = reduceShuffleProcess(deckSize, parseInput(deckSize))): Long {
return process.fold(card) { pos, technique -> technique.nextPositionForCard(pos, deckSize) }
}
// Reduce the shuffle process to just two techniques by combining techniques that
// lies next to each other
private fun reduceShuffleProcess(deckSize: Long, initialProcess: List<Technique>): List<Technique> {
var process = initialProcess
while (process.size > 2) {
var offset = 0
while (offset < process.size - 1) {
if (process[offset].canBeCombinedWith(process[offset + 1])) {
// Combine current + next technique into one
val combined = process[offset].combine(process[offset + 1], deckSize)
process = process.subList(0, offset) + combined + process.subList(offset + 2, process.size)
// Next time try to combine previous technique (if there is any) with the new one
offset = max(0, offset - 1)
} else {
// Not possible to combine current + next, step ahead to check the next two
offset++
}
}
}
return process
}
fun solvePart1(): Int {
return finalPositionForCard(2019L, 10007L).toInt()
}
// Create a reduced shuffle process repeated the given number of times by doubling the amount
// of iterations until reaching the final count
@Suppress("SameParameterValue")
private fun repeatShuffleProcess(process: List<Technique>, times: Long, deckSize: Long): List<Technique> {
var current = process
val res = mutableListOf<Technique>()
// iterate trough the bits in the binary representation of the number of times to repeat
// from least significant to most significant
for (bit in times.toString(2).reversed()) {
if (bit == '1') {
// Obviously, a number is the sum of the value of all the ones in the binary representation
// Store the process for all bits that are set
res.addAll(current)
}
// double the amount of iterations in the shuffle process and reduce it to two operations
current = reduceShuffleProcess(deckSize, current + current)
}
// res now holds all the steps needed to repeat the shuffle process the given number of times,
// do a final reduction to get a reduced process with only two steps
return reduceShuffleProcess(deckSize, res)
}
// Draws a lot of inspiration from:
// https://www.reddit.com/r/adventofcode/comments/ee56wh/2019_day_22_part_2_so_whats_the_purpose_of_this/fbr0vjb/
fun solvePart2(): Long {
val deckSize = 119_315_717_514_047
val repeats = 101_741_582_076_661
val targetPosition = 2020L
// Deck becomes sorted again after every deckSize - 1 repeats of the shuffle
// according to Euler's Theorem as mentioned in:
// https://www.reddit.com/r/adventofcode/comments/ee56wh/2019_day_22_part_2_so_whats_the_purpose_of_this/fbs6s6z/
//
// We're interested in what cards ends up at position 2020 after 'repeats' number of repeats of the shuffle
// process. Calculate the number of times extra that the shuffle process has to be done to get to the
// original state.
val shufflesLeftUntilInitialState = deckSize - 1 - repeats
// If we run the shuffle process 'shufflesLeftUntilInitialState' times and see at what position
// the card that was at position 2020 ends up at we have the answer to the problem.
// So first create a reduced shuffle process of two steps with the desired amount of shuffles
val reduced = reduceShuffleProcess(deckSize, parseInput(deckSize))
val repeated = repeatShuffleProcess(reduced, shufflesLeftUntilInitialState, deckSize)
// Then check where the card at 2020 moves to with this shuffle process.
return finalPositionForCard(targetPosition, deckSize, repeated)
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 6,883 | aoc | MIT License |
src/main/kotlin/days/Day12.kt | hughjdavey | 572,954,098 | false | {"Kotlin": 61752} | package days
import xyz.hughjd.aocutils.Coords.Coord
import java.util.LinkedList
import java.util.Queue
class Day12 : Day(12) {
private val pointsInfo = PointsInfo.fromInput(inputList)
override fun partOne(): Any {
return dijkstra(pointsInfo)[pointsInfo.end] ?: 0
}
// todo improve performance - takes ~2 mins
override fun partTwo(): Any {
val possibleStarts = pointsInfo.points.filter { it.letter == 'a' }
return possibleStarts.parallelStream().map { start -> pointsInfo.copy(start = start.position) }
.map { dijkstra(it)[it.end] ?: 0 }.filter { it > 0 }.min(Int::compareTo).orElse(0)
}
// see https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode
private fun dijkstra(pointsInfo: PointsInfo): MutableMap<Coord, Int> {
val dist = mutableMapOf<Coord, Int>()
val Q = LinkedList<Point>()
pointsInfo.points.forEach { point ->
dist[point.position] = Int.MAX_VALUE
Q.add(point)
}
dist[pointsInfo.start] = 0
while (Q.isNotEmpty()) {
val u = Q.minBy { dist[it.position]!! }
Q.remove(u)
u.neighboursInQueue(Q).forEach { v ->
val alt = dist[u.position]!! + 1
if (alt < dist[v.position]!! && v.elevation - u.elevation <= 1) {
dist[v.position] = alt
}
}
}
return dist
}
data class PointsInfo(val start: Coord, val end: Coord, val points: List<Point>) {
companion object {
fun fromInput(input: List<String>): PointsInfo {
lateinit var start: Coord
lateinit var end: Coord
val points = input.mapIndexed { y, str ->
str.mapIndexed { x, char ->
if (char == 'S') {
start = Coord(x, y)
}
else if (char == 'E') {
end = Coord(x, y)
}
Point(Coord(x, y), char)
}
}.flatten()
return PointsInfo(start, end, points)
}
}
}
data class Point(val position: Coord, val letter: Char, val elevation: Int = getElevation(letter)) {
fun neighboursInQueue(queue: Queue<Point>): List<Point> {
return position.getAdjacent(false)
.mapNotNull { c -> queue.find { it.position == c } }
}
companion object {
fun getElevation(letter: Char) = when (letter) {
'S' -> 0
'E' -> 25
else -> letter.code - 97
}
}
}
}
| 0 | Kotlin | 0 | 2 | 65014f2872e5eb84a15df8e80284e43795e4c700 | 2,753 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/aoc2022/day04/Day04.kt | svilen-ivanov | 572,637,864 | false | {"Kotlin": 53827} | package aoc2022.day04
import readInput
fun String.toRange(): IntRange {
val startEnd = split('-').map { it.toInt() }
return startEnd[0]..startEnd[1]
}
fun IntRange.contains(other: IntRange): Boolean {
return contains(other.first) && contains(other.last)
}
fun IntRange.overlap(other: IntRange): Boolean {
return other.contains(this) || contains(other.first) || contains(other.last)
}
fun main() {
fun part1(input: List<String>) {
var sum = 0
for (line in input) {
val (pair1, pair2) = line.split(',')
val range1 = pair1.toRange()
val range2 = pair2.toRange()
if (range1.contains(range2) || range2.contains(range1)) {
sum++
}
}
println(sum)
check(sum == 560)
}
fun part2(input: List<String>) {
var sum = 0
for (line in input) {
val (pair1, pair2) = line.split(',')
val range1 = pair1.toRange()
val range2 = pair2.toRange()
if (range1.overlap(range2)) {
sum++
}
}
println(sum)
check(sum == 839)
}
val testInput = readInput("day04/day04")
part1(testInput)
part2(testInput)
}
| 0 | Kotlin | 0 | 0 | 456bedb4d1082890d78490d3b730b2bb45913fe9 | 1,257 | aoc-2022 | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day20/Day20.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day20
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.get
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 20](https://adventofcode.com/2021/day/20)
*/
object Day20 : DayOf2021(20) {
override fun first(): Any? {
return solve(2)
}
override fun second(): Any? {
return solve(50)
}
private fun solve(steps: Int): Int {
val (rawAlgo, rawSource) = data.trim().split("\n\n")
val algo = rawAlgo.toList()
val source = rawSource.trim()
.lines()
.map { it.toList() }
return (0..<steps)
.fold(source to '.') { acc, _ ->
enhance(acc.first, algo, acc.second)
}
.first
.sumOf { line -> line.count { it == '#' } }
}
private fun enhance(
source: List<List<Char>>,
algo: List<Char>,
blank: Char,
): Pair<List<List<Char>>, Char> {
val height = source.size
val width = source.first().size
return (-1..height).map { y ->
(-1..width).map { x ->
val chars = (-1..1).flatMap { dy ->
(-1..1).map { dx ->
source[Vector2D(x + dx, y + dy)] ?: blank
}
}.map { if (it == '#') 1 else 0 }
algo[chars.joinToString("").toInt(2)]
}
} to algo[if (blank == '#') 511 else 0]
}
}
fun main() = SomeDay.mainify(Day20)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,369 | adventofcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountPoints.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
import java.util.Arrays
/**
* 1828. Queries on Number of Points Inside a Circle
* @see <a href="https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/">Source</a>
*/
fun interface CountPoints {
operator fun invoke(points: Array<IntArray>, queries: Array<IntArray>): IntArray
}
class CountPointsSort : CountPoints {
override operator fun invoke(points: Array<IntArray>, queries: Array<IntArray>): IntArray {
Arrays.sort(points) { a, b -> a[0] - b[0] }
val n = queries.size
val ans = IntArray(n)
for (i in 0 until n) {
val xCenter = queries[i][0]
val yCenter = queries[i][1]
val r = queries[i][2]
val index = findLeftBoundaryIndex(points, xCenter, r)
var count = 0
var j = index
while (j < points.size && points[j][0] <= xCenter + r) {
val x = points[j][0]
val y = points[j][1]
// square of distance from center
val dist: Int = sqr(xCenter - x) + sqr(yCenter - y)
if (dist <= r * r) count++
j++
}
ans[i] = count
}
return ans
}
// find lower bound of left boundary
private fun findLeftBoundaryIndex(points: Array<IntArray>, xCenter: Int, r: Int): Int {
var lo = 0
var hi = points.size
while (lo < hi) {
val mi = lo + (hi - lo) / 2
if (xCenter - r <= points[mi][0]) hi = mi else lo = mi + 1
}
return hi
}
private fun sqr(a: Int): Int {
return a * a
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,274 | kotlab | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumANDSum.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 kotlin.math.max
import kotlin.math.pow
/**
* 2172. Maximum AND Sum of Array
* @see <a href="https://leetcode.com/problems/maximum-and-sum-of-array/">Source</a>
*/
fun interface MaximumANDSum {
operator fun invoke(nums: IntArray, numSlots: Int): Int
}
class MaximumANDSumDP : MaximumANDSum {
override operator fun invoke(nums: IntArray, numSlots: Int): Int {
val mask = 3.0.pow(numSlots.toDouble()).toInt() - 1
val memo = IntArray(mask + 1)
return dp(nums.size - 1, mask, numSlots, memo, nums)
}
private fun dp(i: Int, mask: Int, ns: Int, memo: IntArray, arr: IntArray): Int {
if (memo[mask] > 0) return memo[mask]
if (i < 0) return 0
var slot = 1
var bit = 1
while (slot <= ns) {
if (mask / bit % 3 > 0) {
memo[mask] = max(memo[mask], (arr[i] and slot) + dp(i - 1, mask - bit, ns, memo, arr))
}
++slot
bit *= 3
}
return memo[mask]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,654 | kotlab | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2022/day25/Day25.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day25
import com.jacobhyphenated.advent2022.Day
import kotlin.math.pow
/**
* Day 25: Full of Hot Air
*
* A SNAFU number is a special kind of base 5 number that uses the characters
* = (-2), - (-1), 0, 1, 2
* therefore 3 is 1=
* 9 is 2-
* 2022 is 1=11-2
*/
class Day25: Day<List<String>> {
override fun getInput(): List<String> {
return readInputFile("day25").lines()
}
/**
* The puzzle input is a list of SNAFU numbers.
* Add the numbers up. Return the answer as a SNAFU number.
*/
override fun part1(input: List<String>): String {
val total = input.sumOf { snafuToDecimal(it) }
return decimalToSnafu(total)
}
override fun part2(input: List<String>): String {
return ""
}
/**
* Decimal conversion is pretty straightforward
* Each digit i (starting at 0 and counting from the right) is the digit * 5 ^ i
* digits can be negative, sum all the digits.
*/
fun snafuToDecimal(snafu: String): Long {
return snafu.toList().map { when(it) {
'0' -> 0
'1' -> 1
'2' -> 2
'-' -> -1
'=' -> -2
else -> throw NotImplementedError("Invalid snafu digit $it")
} }.reversed()
.mapIndexed { i, digit -> digit * 5.toDouble().pow(i).toLong() }
.sum()
}
fun decimalToSnafu(decimal: Long): String {
var exp = 0
// first, find the largest power of 5 that is still less than the decimal number
while (5.0.pow(exp).toLong() < decimal) {
exp++
}
// pre-fill an array of digits (leave 1 extra space at the beginning for overflow)
val digits = MutableList(exp+1) { 0 }
exp -= 1
// Fill in each digit by dividing by the appropriate power of 5. digits can be 0 .. 4
var remainder = decimal
for (exponent in exp downTo 1) {
val power = 5.0.pow(exponent).toLong()
val rawDigit = remainder / power
remainder %= power
digits[exponent] = rawDigit.toInt()
}
digits[0] = remainder.toInt()
// Now we do a pass from the least significant digit to the greatest
// convert 3,4, or 5 to the appropriate snafu characters (which can carry over to the next digit)
for (i in 0 until digits.size) {
if (digits[i] == 3) {
digits[i] = -2
digits[i+1] += 1
}
else if (digits[i] == 4) {
digits[i] = -1
digits[i+1] += 1
}
else if (digits[i] == 5) {
digits[i] = 0
digits[i+1] += 1
}
}
// convert to string and replace negatives with special characters
return digits.map { when(it) {
-2 -> "="
-1 -> "-"
else -> it
} }.reversed().joinToString("").trimStart('0')
}
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 3,006 | advent2022 | The Unlicense |
src/day02/Day02.kt | Raibaz | 571,997,684 | false | {"Kotlin": 9423} | package day02
import readInput
fun main() {
fun processRound1(theirPlay: Char, myPlay: Char): Int {
return when (theirPlay) {
'A' -> when(myPlay) {
'X' -> 1 + 3
'Y' -> 2 + 6
'Z' -> 3 + 0
else -> -1
}
'B' -> when(myPlay) {
'X' -> 1 + 0
'Y' -> 2 + 3
'Z' -> 3 + 6
else -> -1
}
'C' -> when(myPlay) {
'X' -> 1 + 6
'Y' -> 2 + 0
'Z' -> 3 + 3
else -> -1
}
else -> -1
}
}
fun processRound2(theirPlay: Char, myPlay: Char): Int {
return when (theirPlay) {
'A' -> when(myPlay) {
'X' -> 3 + 0
'Y' -> 1 + 3
'Z' -> 2 + 6
else -> -1
}
'B' -> when(myPlay) {
'X' -> 1 + 0
'Y' -> 2 + 3
'Z' -> 3 + 6
else -> -1
}
'C' -> when(myPlay) {
'X' -> 2 + 0
'Y' -> 3 + 3
'Z' -> 1 + 6
else -> -1
}
else -> -1
}
}
fun part1(input: List<String>): Int {
return input.sumOf {
processRound1(it.first(), it.last())
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
processRound2(it.first(), it.last())
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day02/input_test")
println(part1(testInput))
val input = readInput("day02/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 99d912f661bd3545ca9ff222ac7d93c12682f42d | 1,810 | aoc-22 | Apache License 2.0 |
src/main/kotlin/io/array/LongestPalindromicSubstring.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.array
import io.utils.runTests
class LongestPalindromicSubstring {
fun executeManacher(rawInput: String): String {
if (rawInput.isEmpty()) return ""
val inputManacher = preprocessManacher(rawInput)
val weights = IntArray(inputManacher.length) { 0 }
var center = 0
var rightBoundary = 0
(1 until inputManacher.lastIndex).forEach { index ->
val mirror = 2 * center - index
if (index < rightBoundary)
weights[index] = minOf(rightBoundary - index, weights[mirror])
while (inputManacher[index + (1 + weights[index])] == inputManacher[index - (1 + weights[index])]) {
weights[index]++
}
if (index + weights[index] > rightBoundary) {
center = index
rightBoundary = index + weights[index]
}
}
return cleanSolution(inputManacher, weights)
}
private fun cleanSolution(input: String, weights: IntArray) = weights.foldIndexed(0 to 0) { index, (center, size), value ->
if (value > size) { index to value } else center to size
}.let { (center, size) -> input.substring(center - size..center + size).replace("#", "") }
private fun preprocessManacher(input: String) = "^$input$".toList().joinToString(separator = "#") { it.toString() }
fun execute1(input: String): String = when (input.length) {
0, 1 -> input
else -> {
val palindromes = (1 until input.length - 1).fold(mutableListOf<Pair<Int, Int>>()) { acc, value ->
acc.apply {
if (input.isPalindrome(value - 1, value + 1)) {
add(value - 1 to value + 1)
}
}
}
palindromes.addAll((1 until input.length).fold(mutableListOf()) { acc, value ->
acc.apply {
if (input.isPalindrome(value - 1, value)) {
add(value - 1 to value)
}
}
})
palindromes.fold(input.first().toString()) { acc, (f, l) ->
var first = f
var last = l
while (first > 0 && last < input.length - 1 && input[first - 1] == input[last + 1]) {
first--
last++
}
var word = input.substring(first..last)
if (word.isNotEmpty() && word.all { it == word.first() }) {
while (first > 0 && input[first - 1] == word.first()) {
first--
}
while (last < input.length - 1 && input[last + 1] == word.first()) {
last++
}
word = input.substring(first..last)
}
if (word.length > acc.length) word else acc
}
}
}
}
private fun String.isPalindrome(f: Int, l: Int): Boolean {
if (f !in indices || l !in indices) return false
var first = f
var last = l
while (first < length && last >= 0 && first < last && this[first] == this[last]) {
first++
last--
}
return first >= last
}
fun main() {
runTests(listOf(
"cbbd" to "bb",
"babad" to "bab",
"a" to "a",
"ac" to "a",
"aaaa" to "aaaa",
"tattarrattat" to "tattarrattat"
)) { (input, value) -> value to LongestPalindromicSubstring().executeManacher(input) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 3,079 | coding | MIT License |
src/Day01.kt | JaydenPease | 574,590,496 | false | {"Kotlin": 11645} | fun main() {
// fun part1(input: List<String>): Int {
// return input.size
// }
//
// fun part2(input: List<String>): Int {
// return input.size
// }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
//println(Day01(testInput))
//println(Day01_part2(testInput))
val input = readInput("Day01")
//println(Day01_part1(input))
println(Day01_part2(input))
}
fun Day01_part1(input : List<String>) : Int {
var greatest: Int = Integer.MIN_VALUE
var current: Int = 0
for(i in input.indices) {
if(input[i] != "") {
current += input[i].toInt()
}
else {
if(current > greatest) {greatest = current}
current = 0
}
}
return greatest
}
fun Day01_part2(input : List<String>) : Int {
var firstGreatest: Int = Integer.MIN_VALUE
var secondGreatest: Int = Integer.MIN_VALUE
var thirdGreatest: Int = Integer.MIN_VALUE
var current: Int = 0
for(i in input.indices) {
if(input[i] != "") {
current += input[i].toInt()
}
else {
val numbers2: List<Int> = Day01_part2_shufflePositionsHelper(listOf(firstGreatest, secondGreatest, thirdGreatest, current).toMutableList())
firstGreatest = numbers2[0]
secondGreatest = numbers2[1]
thirdGreatest = numbers2[2]
current = numbers2[3]
}
}
val numbers: List<Int> = Day01_part2_shufflePositionsHelper(listOf(firstGreatest, secondGreatest, thirdGreatest, current).toMutableList())
return numbers[0] + numbers[1] + numbers[2]
}
private fun Day01_part2_shufflePositionsHelper(input: MutableList<Int>): List<Int> {
if(input[3] > input[0]) {
input[2] = input[1]
input[1] = input[0]
input[0] = input[3]
}
else if(input[3] > input[1]) {
input[2] = input[1]
input[1] = input[3]
}
else if(input[3] > input[2]) {input[2] = input[3]}
input[3] = 0
return input
}
| 0 | Kotlin | 0 | 0 | 0a5fa22b3653c4b44a716927e2293fc4b2ed9eb7 | 2,096 | AdventOfCode-2022 | Apache License 2.0 |
src/Day16.kt | thomasreader | 573,047,664 | false | {"Kotlin": 59975} | import java.io.Reader
typealias ValveToValveDistance = Map<Valve, Map<Valve, Int>>
typealias MutableValveToValveDistance = MutableMap<Valve, Map<Valve, Int>>
fun main() {
val testInput = """
Valve AA has flow rate=0; tunnels lead to valves DD, II, BB
Valve BB has flow rate=13; tunnels lead to valves CC, AA
Valve CC has flow rate=2; tunnels lead to valves DD, BB
Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE
Valve EE has flow rate=3; tunnels lead to valves FF, DD
Valve FF has flow rate=0; tunnels lead to valves EE, GG
Valve GG has flow rate=0; tunnels lead to valves FF, HH
Valve HH has flow rate=22; tunnel leads to valve GG
Valve II has flow rate=0; tunnels lead to valves AA, JJ
Valve JJ has flow rate=21; tunnel leads to valve II
""".trimIndent()
val testTunnels = parseInput(testInput.reader()).associateBy { it.id }
val testDistances = djikstra(testTunnels)
val testBestFlow = getBestFlow(
currentValve = "AA",
valveMap = testTunnels,
distances = testDistances,
openedValves = emptySet(),
minutesLeft = 30
)
check(testBestFlow == 1651)
val input = reader("Day16.txt")
val tunnels = parseInput(input).associateBy { it.id }
val distances = djikstra(tunnels)
val bestFlow = getBestFlow(
currentValve = "AA",
valveMap = tunnels,
distances = distances,
openedValves = emptySet(),
minutesLeft = 30
)
println(bestFlow)
val testFlowElly = getBestFlowWithElly(
myPosition = "AA",
elephantPosition = "AA",
valveMap = testTunnels,
distances = testDistances,
openedValves = emptySet(),
myTimeLeft = 26,
elephantTimeLeft = 26
)
check(testFlowElly == 1707)
val flowElly = getBestFlowWithElly(
myPosition = "AA",
elephantPosition = "AA",
valveMap = tunnels,
distances = distances,
openedValves = emptySet(),
myTimeLeft = 26,
elephantTimeLeft = 26
)
println(flowElly)
}
fun getBestFlowWithElly(
myPosition: String,
elephantPosition: String,
valveMap: Map<String, Valve>,
distances: ValveToValveDistance,
openedValves: Set<Valve>,
myTimeLeft: Int,
elephantTimeLeft: Int
): Int {
val possiblePaths = distances[valveMap[myPosition]!!]!!.filterKeys { it !in openedValves }
val elephantPaths = distances[valveMap[elephantPosition]!!]!!.filterKeys { it !in openedValves }
return possiblePaths.maxOfOrNull { (to, travelTime) ->
val travelTimeAndOpeningTime = travelTime + 1
if (myTimeLeft > 2 && myTimeLeft > travelTimeAndOpeningTime) {
val myPressureGained = (myTimeLeft - travelTimeAndOpeningTime) * to.flowRate
myPressureGained + (elephantPaths.maxOfOrNull { (elephantTo, elephantTravelTime) ->
val eTravelTimeAndOpeningTime = elephantTravelTime + 1
if (elephantTimeLeft > 2 && elephantTimeLeft > eTravelTimeAndOpeningTime) {
val ePressureGained = if (to == elephantTo) 0 else (elephantTimeLeft - eTravelTimeAndOpeningTime) * elephantTo.flowRate
ePressureGained + getBestFlowWithElly(
myPosition = to.id,
elephantPosition = elephantTo.id,
valveMap = valveMap,
distances = distances,
openedValves = openedValves + arrayOf(to, elephantTo),
myTimeLeft = myTimeLeft - travelTimeAndOpeningTime,
elephantTimeLeft = elephantTimeLeft - eTravelTimeAndOpeningTime
)
} else { 0 }
} ?: 0)
} else { 0 }
} ?: 0
}
fun getBestFlow(
currentValve: String,
valveMap: Map<String, Valve>,
distances: ValveToValveDistance,
openedValves: Set<Valve>,
minutesLeft: Int
): Int {
return when (minutesLeft) {
0, 1, 2 -> 0
else -> {
val possiblePaths = distances[valveMap[currentValve]!!]!!.filterKeys { it !in openedValves }
possiblePaths.maxOfOrNull { (to, travelTime) ->
val travelTimeAndOpeningTime = travelTime + 1
if (travelTimeAndOpeningTime >= minutesLeft) {
return@maxOfOrNull 0
}
val valveOpenFor = minutesLeft - travelTimeAndOpeningTime
val pressureGained = (valveOpenFor) * to.flowRate
pressureGained + getBestFlow(
currentValve = to.id,
valveMap = valveMap,
distances = distances,
openedValves = openedValves + to,
minutesLeft = valveOpenFor
)
} ?: 0
}
}
}
private fun parseInput(src: Reader): List<Valve> {
val valves = mutableListOf<Valve>()
val digitRegex = Regex("""\d+""")
val idRegex = Regex("""[A-Z]{2}""")
src.forEachLine { line ->
val (a, b) = line.split("; ")
val aSplit = a.split(' ')
val id = aSplit[1]
val flowRate = digitRegex.find(aSplit[4])!!.value.toInt()
val toValves = b.split(' ').let {
it.subList(4, it.size)
.map { i -> idRegex.find(i)!!.value }
}
valves += Valve(id, flowRate, toValves)
}
return valves
}
fun ValveToValveDistance.prettyPrint() {
forEach { fromEntry ->
fromEntry.value.forEach { toEntry ->
println("${fromEntry.key.id} -> ${toEntry.key.id} (${toEntry.value})")
}
}
}
data class Valve(
val id: String,
val flowRate: Int,
val tunnelsTo: List<String>
)
private fun djikstra(graph: Map<String, Valve>): ValveToValveDistance {
val valveToValveDistances: MutableValveToValveDistance = mutableMapOf()
graph.forEach { entry ->
val distances: MutableMap<Valve, Int> = graph.values.associateWith { Int.MAX_VALUE }.toMutableMap()
val prev: MutableMap<Valve, Valve?> = graph.values.associateWith { null }.toMutableMap()
distances[entry.value] = 0
val queue = ArrayList(graph.values)
val seen = mutableListOf<Valve>()
while (queue.isNotEmpty()) {
val u = run {
var currentMin = queue[0]
queue.forEach {
if (distances[it]!! < distances[currentMin]!!) {
currentMin = it
}
}
currentMin
}
queue -= u
seen += u
u.tunnelsTo.forEach { vId ->
val v = graph[vId]
if (v!= null && distances[v]!! > distances[u]!! + 1) {
distances[v] = distances[u]!! + 1
prev[v] = u
}
}
}
valveToValveDistances[entry.value] = distances.filter { it.key.flowRate > 0 && it.key != entry.value }
}
return valveToValveDistances.filter { fromEntry ->
fromEntry.key.id == "AA" || fromEntry.key.flowRate > 0
}
} | 0 | Kotlin | 0 | 0 | eff121af4aa65f33e05eb5e65c97d2ee464d18a6 | 7,196 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2021/Day18.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 18 - Snailfish
* Problem Description: http://adventofcode.com/2021/day/18
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day18/
*/
package com.ginsberg.advent2021
import kotlin.math.ceil
import kotlin.math.floor
class Day18(private val input: List<String>) {
fun solvePart1(): Int =
input.map { SnailfishNumber.of(it) }.reduce { a, b -> a + b }.magnitude()
fun solvePart2(): Int =
input.mapIndexed { index, left ->
input.drop(index + 1).map { right ->
listOf(
SnailfishNumber.of(left) to SnailfishNumber.of(right),
SnailfishNumber.of(right) to SnailfishNumber.of(left)
)
}.flatten()
}.flatten()
.maxOf { (it.first + it.second).magnitude() }
data class PairNumberDepth(val depth: Int, val pair: PairNumber)
sealed class SnailfishNumber {
var parent: SnailfishNumber? = null
abstract fun magnitude(): Int
abstract fun split(): Boolean
abstract fun regularsInOrder(): List<RegularNumber>
abstract fun pairsInOrderWithDepth(depth: Int = 0): List<PairNumberDepth>
operator fun plus(other: SnailfishNumber): SnailfishNumber =
PairNumber(this, other).apply { reduce() }
fun reduce() {
do {
val didSomething = explode() || split()
} while(didSomething)
}
private fun root(): SnailfishNumber =
if (parent == null) this else parent!!.root()
private fun explode(): Boolean {
val pairs = root().pairsInOrderWithDepth()
val explodingPair = pairs.firstOrNull { it.depth == 4 }?.pair
if (explodingPair != null) {
val regulars = root().regularsInOrder()
regulars.elementAtOrNull(regulars.indexOfFirst { it === explodingPair.left } - 1)
?.addValue(explodingPair.left as RegularNumber)
regulars.elementAtOrNull(regulars.indexOfFirst { it === explodingPair.right } + 1)
?.addValue(explodingPair.right as RegularNumber)
(explodingPair.parent as PairNumber).childHasExploded(explodingPair)
return true
}
return false
}
companion object {
fun of(input: String): SnailfishNumber {
val stack = mutableListOf<SnailfishNumber>()
input.forEach { char ->
when {
char.isDigit() -> stack.add(RegularNumber(char.digitToInt()))
char == ']' -> {
val right = stack.removeLast()
val left = stack.removeLast()
stack.add(PairNumber(left, right))
}
}
}
return stack.removeFirst()
}
}
}
data class RegularNumber(var value: Int) : SnailfishNumber() {
override fun magnitude(): Int = value
override fun split(): Boolean = false
override fun regularsInOrder(): List<RegularNumber> = listOf(this)
override fun pairsInOrderWithDepth(depth: Int): List<PairNumberDepth> = emptyList()
fun addValue(amount: RegularNumber) {
this.value += amount.value
}
fun splitToPair(splitParent: SnailfishNumber): PairNumber =
PairNumber(
RegularNumber(floor(value.toDouble() / 2.0).toInt()),
RegularNumber(ceil(value.toDouble() / 2.0).toInt())
).apply { this.parent = splitParent }
override fun toString(): String =
value.toString()
}
data class PairNumber(var left: SnailfishNumber, var right: SnailfishNumber) : SnailfishNumber() {
init {
left.parent = this
right.parent = this
}
override fun magnitude(): Int = (left.magnitude() * 3) + (right.magnitude() * 2)
fun childHasExploded(child: PairNumber) {
val replacement = RegularNumber(0).apply { parent = this@PairNumber.parent }
when {
left === child -> left = replacement
else -> right = replacement
}
}
override fun regularsInOrder(): List<RegularNumber> =
this.left.regularsInOrder() + this.right.regularsInOrder()
override fun pairsInOrderWithDepth(depth: Int): List<PairNumberDepth> =
this.left.pairsInOrderWithDepth(depth + 1) +
listOf(PairNumberDepth(depth, this)) +
this.right.pairsInOrderWithDepth(depth + 1)
override fun split(): Boolean {
if (left is RegularNumber) {
val actualLeft = left as RegularNumber
if (actualLeft.value >= 10) {
left = actualLeft.splitToPair(this)
return true
}
}
val didSplit = left.split()
if (didSplit) return true
if (right is RegularNumber) {
val actualRight = right as RegularNumber
if (actualRight.value >= 10) {
right = actualRight.splitToPair(this)
return true
}
}
return right.split()
}
override fun toString(): String =
"[$left,$right]"
}
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 5,558 | advent-2021-kotlin | Apache License 2.0 |
app/src/main/kotlin/day04/Day04.kt | StylianosGakis | 434,004,245 | false | {"Kotlin": 56380} | package day04
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 4
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay04Part1, ::solveDay04Part2)
}
fun solveDay04Part1(input: List<String>): Int {
val winningNumbers = WinningNumbers.fromInput(input)
val boards = Board.listFromInput(input)
val (winningBoard, winningNumber) = findWinningBoardWithWinningNumber(winningNumbers, boards)
return winningBoard.calculateScore(winningNumber)
}
private tailrec fun findWinningBoardWithWinningNumber(
winningNumbers: WinningNumbers,
boards: List<Board>,
): Pair<Board, Int> {
val winningNumber = winningNumbers.numbers.first()
boards.forEach { board ->
board.setMarkedNumber(winningNumber)
}
val wonBoard = boards.firstOrNull { board -> board.hasWon() }
if (wonBoard != null) return wonBoard to winningNumber
return findWinningBoardWithWinningNumber(winningNumbers.dropFirst(), boards)
}
fun solveDay04Part2(input: List<String>): Int {
val winningNumbers = WinningNumbers.fromInput(input)
val boards = Board.listFromInput(input)
val (winningBoard, winningNumber) = findLastWinningBoardWithWinningNumber(winningNumbers, boards)
return winningBoard.calculateScore(winningNumber)
}
private tailrec fun findLastWinningBoardWithWinningNumber(
winningNumbers: WinningNumbers,
boards: List<Board>,
): Pair<Board, Int> {
val winningNumber = winningNumbers.numbers.first()
boards.forEach { board ->
board.setMarkedNumber(winningNumber)
}
if (boards.size == 1 && boards.first().hasWon()) return boards.first() to winningNumber
val boardsWithoutTheWinningOnes = boards.filterNot { board -> board.hasWon() }
return findLastWinningBoardWithWinningNumber(
winningNumbers.dropFirst(), boardsWithoutTheWinningOnes
)
}
| 0 | Kotlin | 0 | 0 | a2dad83d8c17a2e75dcd00651c5c6ae6691e881e | 1,944 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/twentytwentytwo/Graph.kt | JanGroot | 317,476,637 | false | {"Kotlin": 80906} | package twentytwentytwo
class Graph<T>(private val weightedPaths: Map<T, Map<T, Int>>) {
//dijkstra
fun findShortestPath(start: T, end: T): Int {
if (start == end) return 0
val paths = recurseFindShortestPath(NodePaths(start, end)).paths
return paths.getValue(end)
}
private tailrec fun recurseFindShortestPath(nodePaths: NodePaths<T>): NodePaths<T> {
return if (nodePaths.isFinished()) nodePaths
else {
val nextNode = nodePaths.nextNode(weightedPaths)
recurseFindShortestPath(nextNode)
}
}
//https://en.wikipedia.org/wiki/Floyd–Warshall_algorithm
fun findAllShortestPath() =
weightedPaths.keys.associateWith { k -> weightedPaths.keys.associateWith { findShortestPath(k, it) } }
}
data class NodePaths<T>(private val node: T, private val end: T, val paths: Map<T, Int> = emptyMap()) {
private fun updatePath(entry: Map.Entry<T, Int>): NodePaths<T> {
val currentDistance = paths.getOrDefault(entry.key, Integer.MAX_VALUE)
val newDistance = entry.value + paths.getOrDefault(node, 0)
return if (newDistance < currentDistance)
this + (entry.key to newDistance)
else
this
}
private fun updatePaths(weightedPaths: Map<T, Map<T, Int>>) = (weightedPaths[node]
?.map { updatePath(it) }
?.fold(copy()) { acc, item -> acc + item } ?: copy()) - node
fun nextNode(weightedPaths: Map<T, Map<T, Int>>): NodePaths<T> {
val updatedPaths = updatePaths(weightedPaths)
val nextNode = updatedPaths.paths.minBy { it.value }.key
return updatedPaths.copy(node = nextNode)
}
fun isFinished() = node == end
operator fun plus(other: NodePaths<T>) = copy(paths = paths + other.paths)
operator fun plus(pair: Pair<T, Int>) = copy(paths = paths + pair)
operator fun minus(node: T)= copy(paths = paths - node)
} | 0 | Kotlin | 0 | 0 | 04a9531285e22cc81e6478dc89708bcf6407910b | 1,936 | aoc202xkotlin | The Unlicense |
src/Day10.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | const val MAX_CYCLE = 220
const val FIRST_IMPORTANT_CYCLE = 20
const val ITERATION_IMPORTANT_CYCLES = 40
const val SCREEN_HEIGHT = 6
const val SCREEN_WIDTH = 40
fun main() {
fun nextCyclePart1(cycle: Int, x: Int, signalStrengthPerCycle: MutableMap<Int, Int>): Int {
val importantCycle = (cycle - FIRST_IMPORTANT_CYCLE) % ITERATION_IMPORTANT_CYCLES == 0
if (importantCycle) {
signalStrengthPerCycle[cycle] = cycle * x
}
return cycle + 1
}
fun nextCyclePart2(crtPosition: Int, x: Int, screen: Array<CharArray>): Int {
val col = crtPosition % SCREEN_WIDTH
val pixelIsActive = col == x - 1 || col == x || col == x + 1 // x is the col index of the middle of three horizontally aligned active pixels
if (pixelIsActive) {
screen[crtPosition / SCREEN_WIDTH][col] = '#'
}
return crtPosition + 1
}
fun getScreen(): Array<CharArray> {
val screen = Array(SCREEN_HEIGHT) { CharArray(SCREEN_WIDTH) }
for (i in 0 until SCREEN_HEIGHT) {
for (j in 0 until SCREEN_WIDTH) {
screen[i][j] = '.'
}
}
return screen
}
fun printScreen(screen: Array<CharArray>) {
for (row in screen) {
println(row.joinToString(""))
}
}
fun part1(input: List<String>): Int {
val signalStrengthPerCycle = mutableMapOf<Int, Int>()
var x = 1
var cycle = 1
while (cycle <= MAX_CYCLE) {
for (instruction in input) {
cycle = nextCyclePart1(cycle, x, signalStrengthPerCycle)
if (instruction.startsWith("addx")) {
cycle = nextCyclePart1(cycle, x, signalStrengthPerCycle)
x += instruction.split(" ").last().toInt()
}
}
}
return signalStrengthPerCycle.values.sum()
}
fun part2(input: List<String>) {
val screen = getScreen()
var x = 1 // x is the col index of the middle of three horizontally aligned active pixels
var crtPosition = 0
for (instruction in input) {
crtPosition = nextCyclePart2(crtPosition, x, screen)
if (instruction.startsWith("addx")) {
crtPosition = nextCyclePart2(crtPosition, x, screen)
x += instruction.split(" ").last().toInt()
}
}
printScreen(screen)
}
val input = readInputAsStrings("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 2,541 | AoC2022 | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2018/calendar/day15/Space.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2018.calendar.day15
import me.peckb.aoc._2018.calendar.day15.Day15.Companion.DEFAULT_POWER
sealed class Space(var x: Int, var y: Int) {
class Wall(_x: Int, _y: Int) : Space(_x, _y)
class Empty(_x: Int, _y: Int): Space(_x, _y)
sealed class Player(_x: Int, _y: Int, var attackPower: Int = DEFAULT_POWER, var hitPoints: Int = 200): Space(_x, _y) {
class Elf(_x: Int, _y: Int, _attackPower: Int = DEFAULT_POWER) : Player(_x, _y, _attackPower)
class Goblin(_x: Int, _y: Int) : Player(_x, _y)
fun takeTurn(gameMap: List<MutableList<Space>>, enemies: List<Player>, findEnemy: (List<Space>) -> Player?) : Boolean {
val remainingEnemies = enemies.filter { it.hitPoints > 0 }
if (remainingEnemies.isEmpty()) return true
var adjacentEnemy = maybeFindEnemy(gameMap, findEnemy)
if (adjacentEnemy == null) move(gameMap, remainingEnemies)
adjacentEnemy = maybeFindEnemy(gameMap, findEnemy)
adjacentEnemy?.let {
it.hitPoints -= attackPower
if (it.hitPoints <= 0) gameMap[it.y][it.x] = Empty(it.x, it.y)
}
return false
}
private fun maybeFindEnemy(gameMap: List<MutableList<Space>>, findEnemy: (List<Space>) -> Player?): Player? {
val u = gameMap[y - 1][x]
val l = gameMap[y][x - 1]
val r = gameMap[y][x + 1]
val d = gameMap[y + 1][x]
return findEnemy(listOf(u, l, r, d))
}
private fun move(gameMap: List<MutableList<Space>>, remainingEnemies: List<Player>) {
val paths = GameDijkstra(gameMap).solve(this)
val closestPaths = remainingEnemies.flatMap { enemy ->
val u = gameMap[enemy.y - 1][enemy.x]
val l = gameMap[enemy.y][enemy.x - 1]
val r = gameMap[enemy.y][enemy.x + 1]
val d = gameMap[enemy.y + 1][enemy.x]
listOf(u, l, r, d).filterIsInstance<Empty>().map { paths[it] }
}.filterNotNull().sortedBy { it.cost }
if (closestPaths.isNotEmpty()) {
val options = closestPaths.takeWhile { it.cost == closestPaths.first().cost }
val (newX, newY) = options.sortedWith(pathComparator).first().steps.first()
gameMap[y][x] = Empty(x, y)
gameMap[newY][newX] = this.also { x = newX; y = newY; }
}
}
companion object {
private val pathComparator = Comparator<Path> { p1, p2 ->
val p1Step = p1.steps.last()
val p2Step = p2.steps.last()
when (val yComparison = p1Step.y.compareTo(p2Step.y)) {
0 -> p1Step.x.compareTo(p2Step.x)
else -> yComparison
}
}
}
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 2,573 | advent-of-code | MIT License |
test/Main.kt | goodkillerchen | 452,747,451 | false | {"Kotlin": 21502} | val ans = ArrayList<Matrix>()
fun main(args: Array<String>){
while(true) {
val nextLine = readLine().takeUnless {
it.isNullOrEmpty()
} ?: break
val (V, E) = nextLine.split(' ').map(String::toInt)
val graphA = Graph(V, E)
val (V1, E1) = readLine()!!.split(' ').map(String::toInt)
val graphB = Graph(V1, E1)
val m = Matrix(V, V1)
init(m, graphA, graphB)
val visColumns = BooleanArray(V1){ false }
//val getAns = ArrayList<Matrix>()
dfs(graphA, graphB, visColumns, m, 0)
if(ans.size > 0){
for(item in ans){
print(item)
}
}
else{
print("no\n")
}
}
}
fun init(m: Matrix, graphA: Graph, graphB: Graph){
for(i in 1..graphA.V)
for(j in 1..graphB.V){
if(graphA.degree[i-1] <= graphB.degree[j-1])
m.matrix[i-1][j-1] = 1
}
}
fun dfs(graphA: Graph, graphB: Graph, visColumns: BooleanArray, m: Matrix, step: Int){
if(step == graphA.V){
for(i in 1..graphA.V){
//println(m.matrix[i-1].sum())
if (m.matrix[i-1].sum() != 1)
return
}
ans.add(m.clone())
return;
}
val m1 = refine(graphA, graphB, m.clone())
for(i in 0 until step){
if(m1.matrix[i].sum() == 0)
return
}
val curRow = m1.matrix[step].clone()
for(i in 1..visColumns.size){
if(m1.matrix[step][i-1] == 1 && !visColumns[i-1]){
visColumns[i-1] = true
val newRow = IntArray(visColumns.size){0}
newRow[i-1] = 1
m1.matrix[step] = newRow
dfs(graphA, graphB, visColumns, m1.clone(), step+1)
m1.matrix[step] = curRow
visColumns[i-1] = false
}
}
}
fun refine(graphA: Graph, graphB: Graph, m: Matrix): Matrix{
for(i in 1..m.matrix.size)
for(j in 1..m.matrix[0].size){
if(m.matrix[i-1][j-1] == 1){
for(k in 1..graphA.V){
var flag = false
if(graphA.adjMatrix.matrix[i-1][k-1] == 1){
for(l in 1..graphB.V){
if(graphB.adjMatrix.matrix[j-1][l-1] * m.matrix[k-1][l-1] == 1){
flag = true
break
}
}
if(!flag){
m.matrix[i-1][j-1] = 0
}
}
}
}
}
return m
} | 0 | Kotlin | 0 | 2 | f310137ed3adf7702c59a3d295f9824b9dc99398 | 2,630 | DS-for-Kotlin | MIT License |
src/Day15.kt | diego09310 | 576,378,549 | false | {"Kotlin": 28768} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
data class Point(var x: Int, var y: Int)
lateinit var occupied: HashSet<Int>
lateinit var beaconsInTarget: HashSet<Int>
var targetRow: Int
fun part1(input: List<String>): Int {
occupied = hashSetOf()
beaconsInTarget = hashSetOf()
targetRow = if (input.size > 15) 2000000 else 10
for (l in input) {
val parts = l.replace("""[:,]""".toRegex(), "").split(" ")
val sp = Point(parts[2].split("=")[1].toInt(), parts[3].split("=")[1].toInt())
val bp = Point(parts[8].split("=")[1].toInt(), parts[9].split("=")[1].toInt())
if (bp.y == targetRow) {
beaconsInTarget.add(bp.x)
}
val dist = abs(bp.x - sp.x) + abs(bp.y - sp.y)
if (abs(targetRow - sp.y) <= dist) {
val extra = dist - abs(targetRow - sp.y)
val xs = (sp.x - extra .. sp.x + extra).map { it }.toCollection(HashSet())
occupied.addAll(xs)
}
}
val result = occupied - beaconsInTarget
println(result.size)
return return result.size
}
data class Rang(var x0: Int, var x1: Int)
fun consolidate(rX: ArrayList<Rang>) {
var consolidated = false
var toRemove: HashSet<Rang> = hashSetOf()
while (!consolidated) {
consolidated = true
var prev = rX[0]
for (i in 1 until rX.size) {
if (prev.x1 in rX[i].x0..rX[i].x1) {
prev.x1 = rX[i].x1
consolidated = false
toRemove.add(rX[i])
continue
}
if (rX[i].x0 in prev.x0..prev.x1 && rX[i].x1 in prev.x0..prev.x1) {
toRemove.add(rX[i])
continue
}
prev = rX[i]
}
rX.removeAll(toRemove)
toRemove.clear()
}
}
fun addPoints(rX: ArrayList<Rang>, r0: Int, r1: Int) {
var check = false
var contained = false
for (s in rX) {
if (s.x0 in r0 .. r1) {
s.x0 = r0
check = true
}
if (s.x1 in r0 .. r1) {
s.x1 = r1
check = true
}
if (check) {
break
}
if (r0 in s.x0 .. s.x1 && r1 in s.x0..s.x1) {
contained = true
break
}
}
if (check) {
consolidate(rX)
} else if (!contained) {
rX.add(Rang(r0, r1))
rX.sortBy { it.x0 }
}
}
fun part2(input: List<String>): Long {
val sensorDist: HashMap<Point, Int> = hashMapOf()
val maxSize = if (input.size > 15) 4000000 else 20
for (l in input) {
val parts = l.replace("""[:,]""".toRegex(), "").split(" ")
val sp = Point(parts[2].split("=")[1].toInt(), parts[3].split("=")[1].toInt())
val bp = Point(parts[8].split("=")[1].toInt(), parts[9].split("=")[1].toInt())
val dist = abs(bp.x - sp.x) + abs(bp.y - sp.y)
sensorDist[sp] = dist
}
lateinit var b: Point
row@ for (r in 0 .. maxSize) {
val rX: ArrayList<Rang> = arrayListOf()
for (sd in sensorDist.entries) {
val extra = sd.value - abs(r - sd.key.y)
if (extra >= 0) {
val x0 = max(0, sd.key.x - extra)
val xN = min(maxSize, sd.key.x + extra)
addPoints(rX, x0, xN)
if (rX.size == 1 && rX[0].x0 == 0 && rX[0].x1 == maxSize) {
continue@row
}
}
}
b = Point(rX[0].x1 + 1, r)
break
}
val result = b.x * 4000000L + b.y
println("b: $b")
println(result)
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("../../15linput")
check(part1(testInput) == 26)
val input = readInput("../../15input")
println(part1(input))
check(part2(testInput) == 56000011L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 644fee9237c01754fc1a04fef949a76b057a03fc | 4,367 | aoc-2022-kotlin | Apache License 2.0 |
src/Day05.kt | touchman | 574,559,057 | false | {"Kotlin": 16512} | import java.util.LinkedList
fun main() {
val input = readInput("Day05")
val listOfIndexes = listOf(1, 5, 9, 13, 17, 21, 25, 29, 33)
fun fillQueues(input: List<String>): MutableList<LinkedList<Char>> {
val queues = mutableListOf<LinkedList<Char>>()
for (i in 0..8) {
queues.add(LinkedList<Char>())
}
input.subList(0, 8).forEach { string ->
listOfIndexes.forEachIndexed { index, indexToExtract ->
string[indexToExtract]
.takeIf { it.isLetterOrDigit() }
?.let {
queues[index].add(it)
}
}
}
return queues
}
fun getQueueTopResults(queues: MutableList<LinkedList<Char>>) =
queues.fold("") { acc, chars -> if (chars.isNotEmpty()) acc + chars.first else acc }
fun part1(input: List<String>): String {
val queues = fillQueues(input)
input.subList(10, input.size)
.forEach { action ->
val actions = action.split(" ")
val moveNumber = actions[1].toInt()
val fromNumber = actions[3].toInt() - 1
val toNumber = actions[5].toInt() - 1
queues[toNumber]
.apply {
repeat(moveNumber) {
addFirst(queues[fromNumber].first)
queues[fromNumber].removeFirst()
}
}
}
return getQueueTopResults(queues)
}
fun part2(input: List<String>): String {
val queues = fillQueues(input)
input.subList(10, input.size)
.forEach { action ->
val actions = action.split(" ")
val moveNumber = actions[1].toInt()
val fromNumber = actions[3].toInt() - 1
val toNumber = actions[5].toInt() - 1
queues[toNumber]
.apply {
val tempList = mutableListOf<Char>()
repeat(moveNumber) {
tempList.add(queues[fromNumber].first)
queues[fromNumber].removeFirst()
}
tempList.reversed().forEach(this::addFirst)
}
}
return getQueueTopResults(queues)
}
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 4f7402063a4a7651884be77bb9e97828a31459a7 | 2,475 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2023/Day02.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2023
import com.dvdmunckhof.aoc.multiply
import com.dvdmunckhof.aoc.splitOnce
import kotlin.math.max
class Day02(private val input: List<String>) {
fun solvePart1(): Int = solve { gameId, cubes ->
val valid = cubes.all { (count, color) ->
when (color) {
"red" -> count <= 12
"green" -> count <= 13
"blue" -> count <= 14
else -> false
}
}
if (valid) gameId else 0
}
fun solvePart2(): Int = solve { _, cubes ->
val cubeMap = mutableMapOf("red" to 0, "green" to 0, "blue" to 0)
for ((count, color) in cubes) {
cubeMap[color] = max(count, cubeMap.getValue(color))
}
cubeMap.values.multiply()
}
private fun solve(delegate: (gameId: Int, subsets: List<Pair<Int, String>>) -> Int): Int {
return input.sumOf { line ->
val colonIndex = line.indexOf(':', 6)
val gameId = line.substring(5, colonIndex).toInt()
val cubes = line.substring(colonIndex + 2)
.split("; ", ", ")
.map {
val (count, color) = it.splitOnce(" ")
count.toInt() to color
}
delegate(gameId, cubes)
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,337 | advent-of-code | Apache License 2.0 |
src/main/kotlin/me/mattco/days/day04.kt | mattco98 | 160,000,311 | false | null | package me.mattco.days
import me.mattco.utils.ResourceLoader.getTextResource
import java.util.*
object Day4 {
private val input = getTextResource("/day04").split(System.lineSeparator())
enum class Action {
BEGIN_SHIFT,
FALL_ASLEEP,
WAKE_UP
}
data class Instruction(val date: Calendar, val action: Action, val guardNumber: Int?)
data class Guard(val id: Int, val asleep: MutableMap<Int, Int> = mutableMapOf())
private fun getInstructions() = input.map { line ->
Regex("""^\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})] (.+)$""").matchEntire(line)!!.groupValues.let { matches ->
val action = when {
matches[6].startsWith("Guard") -> Action.BEGIN_SHIFT
matches[6] == "falls asleep" -> Action.FALL_ASLEEP
matches[6] == "wakes up" -> Action.WAKE_UP
else -> throw Exception(":(")
}
val guardNumber = if (action == Action.BEGIN_SHIFT) Regex("(\\d+)").find(matches[6])!!.groupValues[1].toInt() else null
Instruction(
Calendar.getInstance().apply {
set(matches[1].toInt(), matches[2].toInt(), matches[3].toInt(), matches[4].toInt(), matches[5].toInt())
},
action,
guardNumber
)
}
}.sortedBy {
it.date
}
private fun getGuards(): MutableList<Guard> {
val guards = mutableListOf<Guard>()
var guardId = -1
var begin = -1
getInstructions().forEach { inst ->
when (inst.action) {
Action.BEGIN_SHIFT -> guardId = inst.guardNumber!!
Action.FALL_ASLEEP -> begin = inst.date.get(Calendar.MINUTE)
Action.WAKE_UP -> {
var guard = guards.find { it.id == guardId }
if (guard == null) {
guard = Guard(guardId)
guards.add(guard)
}
for (i in begin until inst.date.get(Calendar.MINUTE))
guard.asleep[i] = guard.asleep.getOrDefault(i, 0) + 1
}
}
}
return guards
}
fun part1(): Any? {
val guards = getGuards()
val id = guards.maxBy { it.asleep.values.sum() }!!.id
val minute = guards.find { it.id == id }!!.asleep.maxBy { it.value }!!.key
return id * minute
}
fun part2(): Any? {
val guards = getGuards()
val guard = guards.maxBy { it.asleep.values.max()!! }!!
val minute = guard.asleep.maxBy { it.value }!!.key
return guard.id * minute
}
}
fun main() {
println("=== Day 4 ===")
println("Part 1: ${Day4.part1()}")
println("Part 2: ${Day4.part2()}")
}
| 0 | Kotlin | 0 | 0 | 9ec878de1cd727bb56ba7cb17796c766d4894252 | 2,903 | AdventOfCode2018 | MIT License |
src/Day08_part2.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
fun part2(input: List<String>): Int {
fun scenicScore(grid: List<List<Int>>, coord: Pair<Int, Int>): Int {
val tree = grid[coord.first][coord.second]
var west = 0
for (i in coord.first - 1 downTo 0) {
west++
if (grid[i][coord.second] >= tree) {
break
}
}
var east = 0
for (i in coord.first + 1 until grid.size) {
east++
if (grid[i][coord.second] >= tree) {
break
}
}
var north = 0
for (j in coord.second - 1 downTo 0) {
north++
if (grid[coord.first][j] >= tree) {
break
}
}
var south = 0
for (j in coord.second + 1 until grid[0].size) {
south++
if (grid[coord.first][j] >= tree) {
break
}
}
return north * south * east * west
}
val grid = mutableListOf<List<Int>>()
val score = mutableListOf<MutableList<Int>>()
for (it in input) {
val intArr = mutableListOf<Int>()
for (char in it.toList()) {
intArr.add(char.digitToInt())
}
grid.add(intArr)
score.add(MutableList(it.length) { 0 })
}
for (i in 1 until grid.size - 1) {
for (j in 1 until grid[i].size - 1) {
score[i][j] = scenicScore(grid, Pair(i, j))
}
}
return score.maxOf { it.max() }
}
val testInput = readInput("Day08_test")
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 1,832 | advent-of-code-2022 | Apache License 2.0 |
src/day3/day04.kt | kongminghan | 573,466,303 | false | {"Kotlin": 7118} | package day3
import readInput
fun main() {
fun Char.toPriority() = if (this.isUpperCase()) {
this.code - 38
} else {
this.code - 96
}
fun String.toCharSet(): Set<Char> = toCharArray().toSet()
fun List<String>.findIntersection(): Set<Char> {
return foldIndexed(setOf()) { index, acc, s ->
if (index == 0) {
acc + s.toCharSet()
} else {
acc.intersect(s.toCharSet())
}
}
}
fun List<String>.findPriority(): Int = findIntersection()
.first()
.toPriority()
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
rucksack
.chunked(rucksack.length.div(2))
.findPriority()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { rucksack ->
rucksack
.findPriority()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(day = 3, name = "Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput(day = 3, name = "Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f602900209712090778c161d407ded8c013ae581 | 1,276 | advent-of-code-kotlin | Apache License 2.0 |
src/Day04.kt | arksap2002 | 576,679,233 | false | {"Kotlin": 31030} | fun main() {
fun part1(input: List<String>): Int {
var result = 0
for (pairs in input) {
val firstLeft = pairs.split(",")[0].split("-")[0].toInt()
val firstRight = pairs.split(",")[0].split("-")[1].toInt()
val secondLeft = pairs.split(",")[1].split("-")[0].toInt()
val secondRight = pairs.split(",")[1].split("-")[1].toInt()
if (firstLeft <= secondLeft && secondLeft <= secondRight && secondRight <= firstRight) {
result++
} else if (secondLeft <= firstLeft && firstLeft <= firstRight && firstRight <= secondRight) {
result++
}
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
for (pairs in input) {
val firstLeft = pairs.split(",")[0].split("-")[0].toInt()
val firstRight = pairs.split(",")[0].split("-")[1].toInt()
val secondLeft = pairs.split(",")[1].split("-")[0].toInt()
val secondRight = pairs.split(",")[1].split("-")[1].toInt()
if (firstLeft <= secondLeft && secondLeft <= secondRight && secondRight <= firstRight) {
result++
} else if (secondLeft <= firstLeft && firstLeft <= firstRight && firstRight <= secondRight) {
result++
} else if (secondLeft <= firstLeft && firstLeft <= secondRight && secondRight <= firstRight) {
result++
} else if (firstLeft <= secondLeft && secondLeft <= firstRight && firstRight <= secondRight) {
result++
}
}
return result
}
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | a24a20be5bda37003ef52c84deb8246cdcdb3d07 | 1,748 | advent-of-code-kotlin | Apache License 2.0 |
src/Day02.kt | Advice-Dog | 436,116,275 | true | {"Kotlin": 25836} | fun main() {
fun part1(input: List<Command>): Int {
val horizontal = input
.filterIsInstance<Command.Forward>()
.sumOf { it.value }
val depth = input
.filterNot { it is Command.Forward }
.sumOf { it.value }
return horizontal * depth
}
fun part2(input: List<Command>): Int {
var horizontal = 0
var depth = 0
var aim = 0
input.forEach {
when (it) {
is Command.Forward -> {
horizontal += it.value
depth += aim * it.value
}
is Command.Up,
is Command.Down -> {
aim += it.value
}
}
}
return horizontal * depth
}
// test if implementation meets criteria from the description, like:
val testInput = getTestData("Day02")
.map { it.toCommand() }
check(part1(testInput) == 150)
check(part2(testInput) == 900)
val input = getData("Day02")
.map { it.toCommand() }
println(part1(input))
println(part2(input))
}
sealed class Command(val value: Int) {
class Forward(value: Int) : Command(value)
class Down(value: Int) : Command(value)
class Up(value: Int) : Command(-value)
}
fun String.toCommand(): Command {
val items = split(" ")
val command = items.first()
val value = items.last().toInt()
return when (command) {
"forward" -> Command.Forward(value)
"up" -> Command.Up(value)
"down" -> Command.Down(value)
else -> error("unknown command type: $command")
}
} | 0 | Kotlin | 0 | 0 | 2a2a4767e7f0976dba548d039be148074dce85ce | 1,665 | advent-of-code-kotlin-template | Apache License 2.0 |
src/Java/LeetcodeSolutions/src/main/java/leetcode/solutions/concrete/kotlin/Solution_32_Longest_Valid_Parentheses.kt | v43d3rm4k4r | 515,553,024 | false | {"Kotlin": 40113, "Java": 25728} | package leetcode.solutions.concrete.kotlin
import leetcode.solutions.*
import leetcode.solutions.ProblemDifficulty.*
import leetcode.solutions.validation.SolutionValidator.*
import leetcode.solutions.annotations.ProblemInputData
import leetcode.solutions.annotations.ProblemSolution
/**
* __Problem:__ Given a string containing just the characters '(' and ')', find the length of the longest valid
* (well-formed) parentheses substring.
*
* __Constraints:__
* - 0 <= s.length <= 3 * 10^4
* - s at _i_ is '(', or ')'
*
* __Solution:__ Iterating the array, counting the number of parentheses. If number of left and right ones matches, then
* we select the maximum value from the current sum of the passed parentheses and the currently maximum long valid part.
* If there are more right parentheses, then we reset the counters. This algorithm is valid only if it used on both
* sides, so we repeat the same from the other end of the string. The solution has O(1) space complexity.
*
* __Time:__ O(N)
*
* __Space:__ O(1)
*
* @see Solution_20_Valid_Parentheses
* @author <NAME>
*/
class Solution_32_Longest_Valid_Parentheses : LeetcodeSolution(HARD) {
@ProblemSolution(timeComplexity = "O(N)", spaceComplexity = "O(1)")
private fun longestValidParentheses(s: String): Int {
if (s.length < 2) return 0
var leftsCounter = 0; var rightsCounter = 0; var result = 0
for (i in s.indices) {
if (s[i] == '(') {
++leftsCounter;
} else if (s[i] == ')') {
++rightsCounter
}
if (rightsCounter == leftsCounter) {
result = result.coerceAtLeast(minimumValue = leftsCounter * 2);
} else if (rightsCounter > leftsCounter) {
leftsCounter = 0; rightsCounter = 0
}
}
leftsCounter = 0; rightsCounter = 0
for (i in s.indices.reversed()) {
if (s[i] == '(') {
++leftsCounter
} else if (s[i] == ')') {
++rightsCounter
}
if (rightsCounter == leftsCounter) {
result = result.coerceAtLeast(leftsCounter * 2)
} else if (leftsCounter > rightsCounter) {
leftsCounter = 0; rightsCounter = 0
}
}
return result;
}
@ProblemInputData
override fun run() {
ASSERT_EQ(2, longestValidParentheses("(()"))
ASSERT_EQ(4, longestValidParentheses(")()())"))
ASSERT_EQ(6, longestValidParentheses("()(())"))
ASSERT_EQ(6, longestValidParentheses(")((()))))"))
ASSERT_EQ(0, longestValidParentheses(""))
}
} | 0 | Kotlin | 0 | 1 | c5a7e389c943c85a90594315ff99e4aef87bff65 | 2,688 | LeetcodeSolutions | Apache License 2.0 |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day11/Day11.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day11
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.Companion.NEXT_8
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.get
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 11](https://adventofcode.com/2020/day/11)
*/
object Day11 : DayOf2020(11) {
override fun first(): Any? {
val map = matrix
val steps = generateSequence(map) { curr ->
curr.mapIndexed { y, row ->
row.mapIndexed { x, c ->
val place = Vector2D(x, y)
when {
c == 'L' && NEXT_8.map { it.step + place }.none { curr[it] == '#' } -> '#'
c == '#' && NEXT_8.map { it.step + place }.count { curr[it] == '#' } >= 4 -> 'L'
else -> c
}
}
}
}.zipWithNext()
return steps
.first { it.first == it.second }
.first
.sumOf { line -> line.count { it == '#' } }
}
override fun second(): Any? {
val map = matrix
val steps = generateSequence(map) { curr ->
curr.mapIndexed { y, row ->
row.mapIndexed { x, c ->
val place = Vector2D(x, y)
val occupied = NEXT_8
.map { it.step }
.map { step ->
generateSequence(1) { it + 1 }
.map { place + step * it }
.first { curr[it] != '.' }
.let { curr[it] }
}
.count { it == '#' }
when {
c == 'L' && occupied == 0 -> '#'
c == '#' && occupied >= 5 -> 'L'
else -> c
}
}
}
}.zipWithNext()
return steps
.first { it.first == it.second }
.first
.sumOf { line -> line.count { it == '#' } }
}
}
fun main() = SomeDay.mainify(Day11)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,789 | adventofcode | MIT License |
src/Day05.kt | karloti | 573,006,513 | false | {"Kotlin": 25606} | fun main() {
fun solution(lines: List<String>, part: Int): String {
val initLines = lines
.takeWhile { it.isNotEmpty() }
.dropLast(1)
.map { it.chunked(4).mapIndexedNotNull { i, s -> s.trim(' ', '[', ']').takeIf(String::isNotEmpty)?.let { i + 1 to it[0] } } }
val repo: MutableMap<Int, List<Char>> = initLines
.flatten()
.groupingBy { it.first }
.fold(emptyList<Char>()) { acc, (i, c) -> listOf(c) + acc }
.toMutableMap()
lines
.drop(initLines.size + 2)
.mapNotNull { Regex("""move\s(\d+)\sfrom\s(\d+)\sto\s(\d+)""").find(it)?.groupValues?.drop(1)?.map(String::toInt) }
.onEach { (count, fromRepo, toRepo) ->
val cargo = repo[fromRepo]!!.takeLast(count)
repo[fromRepo] = repo[fromRepo]!!.dropLast(count)
repo[toRepo] = repo[toRepo]!! + if (part == 1) cargo.reversed() else cargo
}
return repo.toSortedMap().map { it.value.last() }.joinToString("")
}
check(solution(readInput("Day05_test"), part = 1) == "CMZ")
check(solution(readInput("Day05_test"), part = 2) == "MCD")
println(solution(readInput("Day05"), part = 1))
println(solution(readInput("Day05"), part = 2))
} | 0 | Kotlin | 1 | 2 | 39ac1df5542d9cb07a2f2d3448066e6e8896fdc1 | 1,307 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/utils/AStarPath.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package utils
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sqrt
fun main() {
val rows = 5
val columns = 8
val grid = Array(rows) { row ->
Array(columns) { column ->
Node(row = row, column = column, value = 'S')
}
}
val origin = grid[0][0]
val destiny = grid[rows - 1][columns - 1]
val path = calculatePath(grid, origin, destiny)
println("path is [$path]")
}
fun calculatePath(grid: Array<Array<Node>>, origin: Node, destiny: Node): Pair<Int, String> {
val open = ArrayDeque<Node>()
val closed = mutableSetOf<Node>()
val cameFrom = mutableMapOf<String, Node>()
origin.gCost = 0
origin.fCost = heuristic(origin, destiny)
open.add(origin)
while (open.isNotEmpty()) {
val currentNode = getLowestCostOpenNode(open.toList()) ?: error("there is no node")
open.remove(currentNode)
closed.add(currentNode)
if (currentNode == destiny)
return reconstructPath(cameFrom, currentNode)
for (neighbor in currentNode.getNeighbors(grid)) {
if (closed.contains(neighbor)) {
continue
}
val calcDistance = distance(currentNode, neighbor)
if (calcDistance == Int.MIN_VALUE)
continue
val neighborTempG = currentNode.gCost + calcDistance
if (neighborTempG < neighbor.gCost) {
cameFrom[neighbor.name] = currentNode
neighbor.gCost = neighborTempG
neighbor.fCost = neighborTempG + heuristic(neighbor, destiny)
if (!open.contains(neighbor))
open.addLast(neighbor)
}
}
}
error("path not found from $origin to $destiny")
}
fun reconstructPath(cameFrom: MutableMap<String, Node>, currentNode: Node): Pair<Int, String> {
var totalPath = ""
var totalPathSize = 0
var current = currentNode
while (cameFrom.keys.contains(current.name)) {
current = cameFrom[current.name] ?: error("not found")
totalPath = "[${current.value}](${current.name}):${totalPath}"
totalPathSize++
}
return totalPathSize to totalPath
}
fun distance(currentNode: Node, neighbor: Node): Int {
val valid = currentNode.value == 'S'
if (valid) return 1
if (neighbor.value == 'E') {
return if (currentNode.value == 'z')
1
else
Int.MIN_VALUE
}
val diff = neighbor.value - currentNode.value
if (diff <= 1) {
return 1
}
return Int.MIN_VALUE
}
fun getLowestCostOpenNode(open: List<Node>): Node? {
return open.minByOrNull { it.fCost }
}
fun heuristic(origin: Node, destination: Node): Int {
val deltaX = abs(destination.row - origin.row).toDouble()
val deltaY = abs(destination.column - origin.column).toDouble()
return sqrt(deltaX.pow(2.0) + deltaY.pow(2.0)).roundToInt()
}
data class Node(
val row: Int,
val column: Int,
val value: Char,
var fCost: Int = Int.MAX_VALUE,
var gCost: Int = Int.MAX_VALUE,
var closed: Boolean = false,
) {
val name = "$row-$column"
fun getNeighbors(grid: Array<Array<Node>>): List<Node> {
val nodes = mutableListOf<Node>()
// top
if (row - 1 >= 0) {
nodes.add(grid[row - 1][column])
}
// bottom
if (row + 1 < grid.size) {
nodes.add(grid[row + 1][column])
}
// left
if (column - 1 >= 0) {
nodes.add(grid[row][column - 1])
}
// right
if (column + 1 < grid[0].size) {
nodes.add(grid[row][column + 1])
}
return nodes
}
override fun toString(): String {
return "$name v:${value} f:$fCost g:$gCost"
}
} | 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 3,854 | advent-of-code | Apache License 2.0 |
src/Day09.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import kotlin.math.abs
import kotlin.math.sign
import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day09.run {
solve1(listOf(13, 88)) // 6090
solve2(listOf(1, 36)) // 2566
}
}.let { println("Total: $it ms") }
}
object Day09 : Day.GroupInput<List<Day09.Data>, List<Int>>("09") {
data class Data(val steps: List<Step>) {
fun simulate(length: Int): Int {
val visited = mutableSetOf<List<Int>>()
val positions = Array(length) { IntArray(2) }
for ((dx, dy, move) in steps) {
repeat(move) {
positions[0][0] += dx
positions[0][1] += dy
for (i in 1..positions.lastIndex) {
val diffX = positions[i - 1][0] - positions[i][0]
val diffY = positions[i - 1][1] - positions[i][1]
if (abs(diffX) == 2 || abs(diffY) == 2) {
positions[i][0] += diffX.sign
positions[i][1] += diffY.sign
}
}
visited.add(positions.last().toList())
}
}
return visited.size
}
}
data class Step(val dx: Int, val dy: Int, val move: Int)
override fun parse(input: List<List<String>>) = input.map { rawSteps ->
rawSteps.map { step ->
val (dir, move) = step.split(" ")
val (dx, dy) = when (dir) {
"U" -> 0 to 1
"D" -> 0 to -1
"L" -> -1 to 0
"R" -> 1 to 0
else -> error("Invalid input.")
}
Step(dx, dy, move.toInt())
}.let(::Data)
}
override fun part1(data: List<Data>) = data.map { it.simulate(2) }
override fun part2(data: List<Data>) = data.map { it.simulate(10) }
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 1,930 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/dev/siller/aoc2022/Day03.kt | chearius | 575,352,798 | false | {"Kotlin": 41999} | package dev.siller.aoc2022
private val example = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
""".trimIndent()
private fun part1(input: List<String>): Int = input
.map { l -> l.toList() }
.map { l ->
val comp1 = l.take(l.size / 2).toSet()
val comp2 = l.drop(l.size / 2).toSet()
comp1.intersect(comp2)
}
.flatten()
.sumOf { c ->
if (c in 'a'..'z') {
c - 'a' + 1
} else {
c - 'A' + 27
}
}
private fun part2(input: List<String>): Int = input
.map { l -> l.toList() }
.chunked(3)
.map { g -> g.map { l -> l.toSet() } }
.map { g -> g[0].intersect(g[1]).intersect(g[2]) }
.flatten()
.sumOf { b ->
if (b in 'a'..'z') {
b - 'a' + 1
} else {
b - 'A' + 27
}
}
fun aocDay03() = aocTaskWithExample(
day = 3,
part1 = ::part1,
part2 = ::part2,
exampleInput = example,
expectedOutputPart1 = 157,
expectedOutputPart2 = 70
)
fun main() {
aocDay03()
}
| 0 | Kotlin | 0 | 0 | e070c0254a658e36566cc9389831b60d9e811cc5 | 1,173 | advent-of-code-2022 | MIT License |
src/Day06.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} | fun main() {
fun findMarker(input: String, numDistinct: Int): Int {
for(index in (numDistinct-1) until input.length) {
val set = (0 until numDistinct).map { i -> input[index - i] }.toSet()
if (set.size == numDistinct) {
return index+1
}
}
throw IllegalStateException("Reached end of string without finding marker")
}
fun part1(input: String) = findMarker(input, 4)
fun part2(input: String) = findMarker(input, 14)
val testInput = readInput("Day06_test")
val expectedResultsPart1 = listOf(7, 5, 6, 10, 11)
val testsPart1 = testInput.mapIndexed{ index, input -> Pair(input, expectedResultsPart1[index]) }
testsPart1.forEach {
check(part1(it.first) == it.second)
}
val expectedResultsPart2 = listOf(19, 23, 23, 29, 26)
val testsPart2 = testInput.mapIndexed{ index, input -> Pair(input, expectedResultsPart2[index]) }
testsPart2.forEach {
check(part2(it.first) == it.second)
}
val input = readInput("Day06")[0]
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 1,113 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2018/Day18.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2018
object Day18 {
fun part1(input: List<String>, minutes: Int = 10, print: Boolean = false): Int {
val area = parseInput(input)
if (print) {
println("Inital state")
print(area)
}
val endState = (1..minutes).fold(area) { previous, minute ->
val res = step(previous)
if (print) {
println("Minute $minute")
print(res)
}
res
}.flatten()
return resourceValueOfPoints(endState)
}
private fun resourceValueOfPoints(area: List<Point>): Int {
return resourceValueOfAreaTypes(area.map { it.areaType })
}
private fun resourceValueOfAreaTypes(area: List<AreaType>): Int {
return area.count { it == AreaType.Tree } * area.count { it == AreaType.Lumberyard }
}
fun part2(input: List<String>, target: Int = 1e9.toInt()): Int {
val area = parseInput(input)
var previous: List<List<Point>>
var next = area
val found = mutableMapOf(signature(area) to 0)
var minute = 0
while (true) {
minute++
previous = next
next = step(previous)
val signature = signature(next)
if (found.containsKey(signature)) {
return handleFoundLoop(minute, found, signature, target)
} else {
found[signature] = minute
}
}
}
private fun handleFoundLoop(minute: Int, found: MutableMap<String, Int>, signature: String, target: Int): Int {
val loopLength = minute - found.getValue(signature)
val remaining = target - minute
val extraEntries = remaining % loopLength
val targetEntry = found.getValue(signature) + extraEntries
val correctSignature = found.filter { it.value == targetEntry }.keys.first()
return resourceValueOfAreaTypes(parseLine(correctSignature))
}
fun signature(area: List<List<Point>>): String {
return area.joinToString(separator = "") { it.joinToString(separator = "") { it.toString() } }
}
fun print(area: List<List<Point>>) {
println(area.joinToString(separator = "\n") { line ->
line.joinToString(separator = "") { it.areaType.toString() }
})
println()
}
fun step(area: List<List<Point>>): List<List<Point>> {
return area.map { line ->
line.map { point -> transition(point, area) }
}
}
fun transition(point: Point, area: List<List<Point>>): Point {
val neighbours = point.neighbours(area)
val byType = neighbours.groupBy { it.areaType }
return when (point.areaType) {
AreaType.Open -> {
if ((byType[AreaType.Tree]?.size ?: 0) >= 3) {
point.copy(areaType = AreaType.Tree)
} else {
point
}
}
AreaType.Tree -> {
if ((byType[AreaType.Lumberyard]?.size ?: 0) >= 3) {
point.copy(areaType = AreaType.Lumberyard)
} else {
point
}
}
AreaType.Lumberyard -> {
if ((byType[AreaType.Lumberyard]?.size ?: 0) >= 1 && (byType[AreaType.Tree]?.size ?: 0) >= 1) {
point
} else {
point.copy(areaType = AreaType.Open)
}
}
}
}
fun parseInput(input: List<String>): List<List<Point>> {
return input.asSequence().mapIndexed { y, line ->
line.mapIndexed { x, c ->
val location = Location(x, y)
val areaType = parseAreaType(c)
Point(location, areaType)
}
}.toList()
}
fun parseLine(line: String): List<AreaType> {
return line.map { c ->
parseAreaType(c)
}
}
fun parseAreaType(c: Char): AreaType {
return when (c) {
'|' -> AreaType.Tree
'.' -> AreaType.Open
'#' -> AreaType.Lumberyard
else -> throw IllegalArgumentException("Don't know that kind of ground $c")
}
}
data class Location(val x: Int, val y: Int)
data class Point(val location: Location, val areaType: AreaType) {
private val neighbourCoords = listOf(
Location(location.x - 1, location.y - 1),
Location(location.x, location.y - 1),
Location(location.x + 1, location.y - 1),
Location(location.x - 1, location.y),
Location(location.x + 1, location.y),
Location(location.x - 1, location.y + 1),
Location(location.x, location.y + 1),
Location(location.x + 1, location.y + 1)
)
fun neighbours(area: List<List<Point>>) = neighbourCoords.filter {
it.x > -1 && it.x < area[0].size
}.filter {
it.y > -1 && it.y < area.size
}.map {
area[it.y][it.x]
}
override fun toString(): String {
return when (areaType) {
AreaType.Open -> "."
AreaType.Tree -> "|"
AreaType.Lumberyard -> "#"
}
}
}
enum class AreaType {
Open, Tree, Lumberyard
}
} | 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 5,414 | adventofcode | MIT License |
src/Day16/Day16.kt | martin3398 | 436,014,815 | false | {"Kotlin": 63436, "Python": 5921} | import java.lang.IllegalArgumentException
fun main() {
val hexToBin = mapOf(
"0" to "0000",
"1" to "0001",
"2" to "0010",
"3" to "0011",
"4" to "0100",
"5" to "0101",
"6" to "0110",
"7" to "0111",
"8" to "1000",
"9" to "1001",
"A" to "1010",
"B" to "1011",
"C" to "1100",
"D" to "1101",
"E" to "1110",
"F" to "1111"
)
// (version sum, length, value)
fun encode(packet: String): Triple<Int, Int, Long> {
val version = Integer.parseInt(packet.slice(0 until 3), 2)
val typeId = Integer.parseInt(packet.slice(3 until 6), 2)
if (typeId == 4) {
var value = ""
var nextStart = 6
do {
val nextFour = packet.slice(nextStart until nextStart + 5)
value += nextFour.slice(1 until 5)
nextStart += 5
} while (nextFour[0] == '1')
return Triple(version, nextStart, value.toLong(2))
}
val mode = packet[6].toString().toInt()
val subPackets = mutableListOf<Triple<Int, Int, Long>>()
var offset = 0
if (mode == 0) {
val length = Integer.parseInt(packet.slice(7 until 22), 2)
var nextStart = 22
var summedLength = 0
while (summedLength != length) {
val subPacket = packet.slice(nextStart until packet.length)
val packetRes = encode(subPacket)
subPackets.add(packetRes)
summedLength += packetRes.second
nextStart += packetRes.second
}
offset = 22
} else if (mode == 1) {
val num = Integer.parseInt(packet.slice(7 until 18), 2)
var nextStart = 18
for (i in 0 until num) {
val subPacket = packet.slice(nextStart until packet.length)
val packetRes = encode(subPacket)
subPackets.add(packetRes)
nextStart += packetRes.second
}
offset = 18
}
val res = when (typeId) {
0 -> subPackets.sumOf { it.third }
1 -> subPackets.fold(1L) { acc, i -> acc * i.third }
2 -> subPackets.minOf { it.third }
3 -> subPackets.maxOf { it.third }
5 -> if (subPackets[0].third > subPackets[1].third) 1 else 0
6 -> if (subPackets[0].third < subPackets[1].third) 1 else 0
7 -> if (subPackets[0].third == subPackets[1].third) 1 else 0
else -> throw IllegalArgumentException()
}
return Triple(subPackets.sumOf { it.first } + version, subPackets.sumOf { it.second } + offset, res)
}
fun part1(input: String): Int {
val bin = input.map { hexToBin.getOrDefault(it.toString(), "X") }.joinToString("") { it }
val packet = encode(bin)
return packet.first
}
fun part2(input: String): Long {
val bin = input.map { hexToBin.getOrDefault(it.toString(), "X") }.joinToString("") { it }
val packet = encode(bin)
return packet.third
}
val testInput = readInput(16, true)[0]
val input = readInput(16)[0]
check(part1(testInput) == 31)
println(part1(input))
check(part2(testInput) == 54L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 085b1f2995e13233ade9cbde9cd506cafe64e1b5 | 3,372 | advent-of-code-2021 | Apache License 2.0 |
Kotlin/LongestCommonSubSequence.kt | sukritishah15 | 299,329,204 | false | null | /**
* Algorithm: Longest Common Sub-Sequence using Dynamic Programming
* Language: Kotlin
* Input:
* String1 and String2 -> Two Strings
* Output:
* Integer -> The longest common sub-sequence of String1 and String2
* Time Complexity: O(nStr1*nStr2)
* Space Complexity: O(nStr1*nStr2)
*
* Sample Input:
* Enter the first String:
* AGGTAB
* Enter the second String:
* GXTXAYB
*
* Sample Output:
* The length of longest common sub-sequence is:
*/
import kotlin.math.max
class LongestCommonSubSequence {
fun longestCommonSubSequence(str1: String, str2: String): Int {
val nStr1 = str1.length
val nStr2 = str2.length
val dp = Array(nStr1 + 1) { IntArray(nStr2 + 1) }
(1 until nStr1 + 1).forEach { i ->
(1 until (nStr2 + 1)).forEach { j ->
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1]
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[nStr1][nStr2]
}
}
fun main() {
println("Enter the first string: ")
val string1 = readLine()!!
println("Enter the second string: ")
val string2 = readLine()!!
val lcs = LongestCommonSubSequence()
println("The length of longest common sub-sequence is: ${lcs.longestCommonSubSequence(string1, string2)}")
} | 164 | Java | 295 | 955 | 1b6040f7d9af5830882b53916e83d53a9c0d67d1 | 1,436 | DS-Algo-Point | MIT License |
kotlin/src/2022/Day02_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} | private fun part1(input: String): Int {
return input.lines().asSequence()
.map { (it[0] - 'A') to (it[2] - 'X') }
// pairs of (player's shape, difference)
.map { it.second to (it.second - it.first).mod(3) }
// score = player's shape + 1 + 3*(difference + 1) % 3
.map {
it.first + 1 + 3 * (it.second + 1).mod(3)
}
.sum()
}
private fun part2(input: String): Int {
return input.lines().asSequence()
.map { (it[0] - 'A') to (it[2] - 'X') }
// (player's symbol, player's base score)
.map {
(it.first + it.second - 1).mod(3) to it.second * 3
}
.map {it.first + 1 + it.second}
.sum()
}
fun main() {
val input = readInput(2).trim()
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 820 | adventofcode | Apache License 2.0 |
src/main/kotlin/Day14.kt | alex859 | 573,174,372 | false | {"Kotlin": 80552} | import kotlin.math.absoluteValue
fun main() {
val testInput = readInput("Day14_test.txt")
// check(testInput.day14Part1() == 24)
val day14Part1 = testInput.day14Part1()
// check(day14Part1 == 93)
val input = readInput("Day14.txt")
println(input.day14Part1())
// println(input.day13Part2())
}
internal fun String.day14Part1(): Int {
val rocks = lines().flatMap { it.readRocks() }
val result = WaterFall(rocks = rocks, sand = emptyList()).play()
return result.sand.size
}
internal fun String.readRocks(): List<Tile> {
val split = split(" -> ")
val chunked = split.flatMapIndexed { i, el ->
if (i == 0 || i == split.size - 1) {
listOf(el)
} else {
listOf(el, el)
}
}.chunked(2)
return chunked.flatMap { (startStr, endStr) ->
val p1 = startStr.toTile()
val p2 = endStr.toTile()
val others = if (p1.first == p2.first) {
if (p2.second > p1.second) verticalDown(p1, p2) else verticalUp(p1, p2)
} else if (p1.second == p2.second){
if (p1.first > p2.first) horizontalLeft(p1, p2) else horizontalRight(p1, p2)
} else TODO()
listOf(p1, p2) + others
}.toSet().toList()
}
private fun horizontalLeft(
p1: Pair<Int, Int>,
p2: Pair<Int, Int>
) = (1 until (p1.first - p2.first).absoluteValue).map { p1.first - it to p1.second }
private fun horizontalRight(
p1: Pair<Int, Int>,
p2: Pair<Int, Int>
) = (1 until (p1.first - p2.first).absoluteValue).map { p1.first + it to p1.second }
private fun verticalDown(
p1: Pair<Int, Int>,
p2: Pair<Int, Int>
) = (1 until (p1.second - p2.second).absoluteValue).map { p1.first to p1.second + it }
private fun verticalUp(
p1: Pair<Int, Int>,
p2: Pair<Int, Int>
) = (1 until (p1.second - p2.second).absoluteValue).map { p1.first to p1.second - it }
private fun String.toTile(): Pair<Int, Int> {
val (start, end) = split(",").map { it.toInt() }
return start to end
}
internal fun WaterFall.play(): WaterFall {
var start = this
var next = addSand().wait()
while(start != next) {
start = next
next = start.addSand().wait()
next.print()
println()
println()
println()
println()
println()
println()
}
return next
}
internal fun WaterFall.print() {
val minX = rocks.minOf { it.first }
val maxX = rocks.maxOf { it.first }
val minY = rocks.minOf { it.second }
val maxY = rocks.maxOf { it.second }
for (y in minY..maxY) {
print(y)
for (x in minX..maxX) {
when {
sand.contains(x to y) -> print("o")
rocks.contains(x to y) -> print("#")
else -> print(".")
}
}
println()
}
}
internal fun WaterFall.wait(): WaterFall {
val next = tick()
return if (next == this) {
next
} else {
next.wait()
}
}
internal fun WaterFall.tick(): WaterFall {
if (fallingSand == null || (500 to 1) in sand) {
return this
}
var next = fallingSand.down()
if (isBusy(next)) {
next = fallingSand.downLeft()
if (isBusy(next)) {
next = fallingSand.downRight()
}
}
return when {
isBusy(next) -> this.copy(sand = listOf(fallingSand) + sand, fallingSand = null)
next.second > max + 2 -> this.copy(fallingSand = null)
else -> this.copy(fallingSand = next)
}
}
private val WaterFall.max: Int get() = rocks.maxOf { it.second }
private fun Tile.downLeft() = copy(first = first - 1, second = second + 1)
private fun Tile.downRight() = copy(first = first + 1, second = second + 1)
private fun Tile.down() = copy(second = second + 1)
private fun WaterFall.isBusy(next: Tile) = sand.contains(next) || rocks.contains(next) || next.second == max + 2
typealias Tile = Pair<Int, Int>
data class WaterFall(
val rocks: List<Tile>,
val sand: List<Tile>,
val fallingSand: Tile? = null
)
internal fun WaterFall.addSand() = copy(fallingSand = 500 to 0)
| 0 | Kotlin | 0 | 0 | fbbd1543b5c5d57885e620ede296b9103477f61d | 4,115 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day21.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode.days
import org.mariuszgromada.math.mxparser.Expression
import kotlin.math.roundToLong
object Day21 {
val MONKEY_VALUE_PATTERN = """(\w+): (\d+)""".toRegex()
val MONKEY_EQ_PATTERN = """(\w+): (\w+) ([*/+\-]) (\w+)""".toRegex()
class RootCalculator() {
val allMonkeys: MutableMap<String, Monkey> = mutableMapOf()
fun calculateMonkeyWithId(id: String): Long {
val monkey = allMonkeys[id]!!
monkey.value?.let { return it }
val left = calculateMonkeyWithId(monkey.waitFor!!.first)
val right = calculateMonkeyWithId(monkey.waitFor.second)
monkey.value = when (monkey.operation) {
'+' -> left + right
'-' -> left - right
'*' -> left * right
'/' -> left / right
'=' -> if (left == right) 1L else 0L
else -> throw UnsupportedOperationException()
}
return monkey.value!!
}
fun buildEquationForMonkeyWithId(y: String, x: String): String {
val monkey = allMonkeys[y]!!
monkey.value?.let { return "${monkey.value}" }
val (left, right) = monkey.waitFor!!
var leftEquation = if (left == x) "x" else buildEquationForMonkeyWithId(left, x)
if (!leftEquation.contains("x")) {
leftEquation = calculateMonkeyWithId(left).toString()
}
var rightEquation = if (right == x) "x" else buildEquationForMonkeyWithId(right, x)
if (!rightEquation.contains("x")) {
rightEquation = calculateMonkeyWithId(right).toString()
}
return "($leftEquation ${monkey.operation!!} $rightEquation)"
}
companion object {
fun parse(input: List<String>): RootCalculator {
return RootCalculator().apply {
input.map { line ->
val monkey = Monkey.parse(line)
allMonkeys[monkey.id] = monkey
}
}
}
}
}
class Monkey(val id: String, var value: Long?, var operation: Char?, val waitFor: Pair<String, String>?) {
companion object {
fun parse(input: String): Monkey {
return if (MONKEY_VALUE_PATTERN.matches(input)) {
val (id, value) = MONKEY_VALUE_PATTERN.find(input)!!.destructured
Monkey(id, value.toLong(), null, null)
} else if (MONKEY_EQ_PATTERN.matches(input)) {
val (id, left, operation, right) = MONKEY_EQ_PATTERN.find(input)!!.destructured
Monkey(id, null, operation[0], Pair(left, right))
} else {
throw IllegalArgumentException("Invalid input: $input")
}
}
}
}
fun part1(input: List<String>): Long {
val calculator = RootCalculator.parse(input)
return calculator.calculateMonkeyWithId("root")
}
fun part2(input: List<String>): Long {
val calculator = RootCalculator.parse(input)
calculator.allMonkeys["root"]!!.operation = '='
val (left, right) = calculator.allMonkeys["root"]!!.waitFor!!
val leftEq = calculator.buildEquationForMonkeyWithId(left, "humn")
val rightEq = calculator.buildEquationForMonkeyWithId(right, "humn")
val e = Expression("solve ( ($leftEq - $rightEq), x, 0, ${Long.MAX_VALUE})")
return e.calculate().roundToLong()
}
}
| 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 3,596 | advent-of-code-2022 | Apache License 2.0 |
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p00/Leet42.kt | artemkaxboy | 513,636,701 | false | {"Kotlin": 547181, "Java": 13948} | package com.artemkaxboy.leetcode.p00
import com.artemkaxboy.leetcode.LeetUtils
import java.util.Collections
import java.util.TreeMap
/**
* Hard
* Runtime 653ms Beats 10.84%
* Memory 45.6MB Beats 15.27%
*/
class Leet42 {
fun trap(height: IntArray): Int {
val firstIndex = 0
val lastIndex = height.size - 1
val peakPairs = TreeMap<Int, IntArray>(Collections.reverseOrder())
height.withIndex()
.filter { it.value >= maxOf(it.index - 1, firstIndex).let { p -> height[p] } }
.filter { it.value >= minOf(it.index + 1, lastIndex).let { n -> height[n] } }
.map { (index, value) ->
peakPairs.computeIfAbsent(value) { intArrayOf(index, index) }[1] = index
}
var min = Int.MAX_VALUE
var max = 0
var water = 0
for (i in peakPairs.keys) {
val pair = peakPairs[i]!!
min = minOf(min, pair[0])
max = maxOf(max, pair[1])
val heightOfCurrentKey = i - (peakPairs.ceilingKey(i - 1) ?: 0)
var rowWater = 0
for (checkWaterIndex in min + 1 until max) {
rowWater += minOf(maxOf(i - height[checkWaterIndex], 0), heightOfCurrentKey)
}
// println("key: $i, next: ${peakPairs.ceilingKey(i - 1)}, height: $heightOfCurrentKey, rowWater: $rowWater")
water += rowWater
}
// println(peakPairs.map { "${it.key} = ${it.value.joinToString()}" })
return water
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
val testCase1 = "[0,1,0,2,1,0,1,3,2,1,2,1]" to 6
doWork(testCase1)
val testCase2 = "[4,2,0,3,2,5]" to 9
doWork(testCase2)
val myCase = "[2,0,3,0,4,2,0,3,2,5,4,5]" to 15
doWork(myCase)
val myCase2 = "[100,50,100,150,100,50,100]" to 100
doWork(myCase2)
}
private fun doWork(data: Pair<String, Int>) {
val solution = Leet42()
val result = solution.trap(LeetUtils.stringToIntArray(data.first))
println(" Data: $data")
println(" Result: $result")
println("Expected: ${data.second}\n")
}
}
}
| 0 | Kotlin | 0 | 0 | 516a8a05112e57eb922b9a272f8fd5209b7d0727 | 2,295 | playground | MIT License |
src/day02/Day02.kt | jacobprudhomme | 573,057,457 | false | {"Kotlin": 29699} | import java.io.File
import java.lang.IllegalArgumentException
enum class Result(val score: Int) {
LOSE(0),
DRAW(3),
WIN(6),
}
enum class Move(val value: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun against(other: Move): Result = when (other.value) {
((value + 1) % 3) + 1 -> Result.WIN
value -> Result.DRAW
else -> Result.LOSE
}
fun obtainsAgainst(result: Result): Move = when (result) {
Result.WIN -> fromValue((value % 3) + 1)
Result.LOSE -> fromValue(((value + 1) % 3) + 1)
else -> this
}
companion object {
fun fromValue(value: Int): Move = when (value) {
1 -> ROCK
2 -> PAPER
3 -> SCISSORS
else -> throw IllegalArgumentException("We should never get here")
}
}
}
fun main() {
fun readInput(name: String) = File("src/day02", name)
.readLines()
fun decryptMove(encryptedMove: String): Move = when (encryptedMove) {
"A", "X" -> Move.ROCK
"B", "Y" -> Move.PAPER
"C", "Z" -> Move.SCISSORS
else -> throw IllegalArgumentException("We should never get here")
}
fun decryptResult(encryptedResult: String): Result = when (encryptedResult) {
"X" -> Result.LOSE
"Y" -> Result.DRAW
"Z" -> Result.WIN
else -> throw IllegalArgumentException("We should never get here")
}
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val (theirMove, myMove, _) = line.split(" ").map { decryptMove(it) }
score += myMove.value + myMove.against(theirMove).score
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (line in input) {
val (theirMove, myResult) = line.split(" ").let { (theirMoveStr, myResultStr, _) ->
Pair(decryptMove(theirMoveStr), decryptResult(myResultStr))
}
score += theirMove.obtainsAgainst(myResult).value + myResult.score
}
return score
}
val input = readInput("input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 9c2b080aea8b069d2796d58bcfc90ce4651c215b | 2,246 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/sschr15/aocsolutions/Day22.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.*
private typealias Point3d = Triple<Int, Int, Int>
private typealias Cube = Set<Point3d>
/**
* AOC 2023 [Day 22](https://adventofcode.com/2023/day/22)
* Challenge: how can we have our sand bricks and disintegrate them too?
*/
object Day22 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 22) {
// test()
fun calculateFalling(bricks: List<Cube>): Pair<List<Cube>, Int> {
val newState = mutableListOf<Cube>()
val fallenEntries = mutableSetOf<Point3d>()
var fallen = 0
for (brick in bricks.sortedBy { it.minOf(Point3d::third) }) {
var currentBrickState = brick
while (true) {
val below: Cube = currentBrickState.map { (x, y, z) -> Triple(x, y, z - 1) }.toSet()
if (below.any { it in fallenEntries || it.third < 0 }) {
newState += currentBrickState
fallenEntries += currentBrickState
if (currentBrickState != brick) {
fallen++
}
break
}
currentBrickState = below
}
}
return newState to fallen
}
val fallenBricksByRemovedBrick: List<Int>
part1 {
val bricks: List<Cube> = inputLines.map { s ->
s.split("~")
.map { it.split(",") }
.map { (x, y, z) -> Triple(x.toInt(), y.toInt(), z.toInt()) }
.let { (start, end) ->
val minX = minOf(start.first, end.first)
val maxX = maxOf(start.first, end.first)
val minY = minOf(start.second, end.second)
val maxY = maxOf(start.second, end.second)
val minZ = minOf(start.third, end.third)
val maxZ = maxOf(start.third, end.third)
(minX..maxX).flatMap { x ->
(minY..maxY).flatMap { y ->
(minZ..maxZ).map { z ->
Triple(x, y, z)
}
}
}.toSet()
}
}
val initialState = calculateFalling(bricks).first
fallenBricksByRemovedBrick = initialState.map { calculateFalling(initialState.minusElement(it)).second }
fallenBricksByRemovedBrick.count { it == 0 } // number of bricks that don't cause any other bricks to fall if removed
}
part2 {
fallenBricksByRemovedBrick.sum()
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 2,915 | advent-of-code | MIT License |
src/Day04.kt | Cryosleeper | 572,977,188 | false | {"Kotlin": 43613} | fun main() {
fun List<String>.toRange(): IntRange {
return first().toInt()..last().toInt()
}
fun List<String>.prepareData(): List<List<IntRange>> =
map { line -> line.split(",").map { range -> range.split("-").toRange() } }
fun IntRange.hasFullOverlap(anotherRange: IntRange): Boolean {
if (this.first <= anotherRange.first && this.last >= anotherRange.last) {
return true
}
if (this.first >= anotherRange.first && this.last <= anotherRange.last) {
return true
}
return false
}
fun IntRange.hasPartialOverlap(anotherRange: IntRange): Boolean {
if (this.first in anotherRange) {
return true
}
if (this.last in anotherRange) {
return true
}
return false
}
fun IntRange.hasAnyOverlap(anotherRange: IntRange): Boolean {
return hasFullOverlap(anotherRange) || hasPartialOverlap(anotherRange)
}
fun part1(input: List<String>): Int {
return input
.prepareData()
.count {
it.first().hasFullOverlap(it.last())
}
}
fun part2(input: List<String>): Int {
return input
.prepareData()
.count {
it.first().hasAnyOverlap(it.last())
}
}
// 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 | a638356cda864b9e1799d72fa07d3482a5f2128e | 1,625 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ReplaceWords.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
/**
* 648. Replace Words
* @see <a href="https://leetcode.com/problems/replace-words/">Source</a>
*/
fun interface ReplaceWords {
operator fun invoke(dictionary: List<String>, sentence: String): String
}
class PrefixHash : ReplaceWords {
override operator fun invoke(dictionary: List<String>, sentence: String): String {
val rootSet: MutableSet<String> = HashSet(dictionary)
val ans = StringBuilder()
for (word in sentence.split("\\s+".toRegex())) {
var prefix = ""
for (i in 1..word.length) {
prefix = word.substring(0, i)
if (rootSet.contains(prefix)) break
}
if (ans.isNotEmpty()) ans.append(" ")
ans.append(prefix)
}
return ans.toString()
}
}
class ReplaceWordsTrie : ReplaceWords {
override operator fun invoke(dictionary: List<String>, sentence: String): String {
val trie = TrieNode()
for (root in dictionary) {
var cur = trie
for (letter in root.toCharArray()) {
if (cur.children[letter.code - 'a'.code] == null) {
cur.children[letter.code - 'a'.code] = TrieNode()
}
cur = cur.children[letter.code - 'a'.code] ?: TrieNode()
}
cur.word = root
}
val ans = StringBuilder()
for (word in sentence.split("\\s+".toRegex())) {
if (ans.isNotEmpty()) ans.append(" ")
var cur = trie
for (letter in word.toCharArray()) {
if (cur.children[letter.code - 'a'.code] == null || cur.word != null) break
cur = cur.children[letter.code - 'a'.code] ?: TrieNode()
}
ans.append(if (cur.word != null) cur.word else word)
}
return ans.toString()
}
private class TrieNode {
var children: Array<TrieNode?> = arrayOfNulls(ALPHABET_LETTERS_COUNT)
var word: String? = null
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,700 | kotlab | Apache License 2.0 |
src/Day20.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | import kotlin.math.abs
fun main() {
val testInput = readInput("Day20_test").map(String::toLong)
val input = readInput("Day20").map(String::toLong)
part1v2(testInput).also {
println("Part 1, test input: $it")
check(it == 3L)
}
part1v2(input).also {
println("Part 1 1, real input: $it")
check(it == 4914L)
}
part2v2(testInput).also {
println("Part 2 2, test input: $it")
check(it == 1623178306L)
}
part2v2(input).also {
println("Part 2 2, real input: $it")
check(it == 7973051839072)
}
}
private fun part1v2(input: List<Long>): Long {
val mixer = Mixer(input)
mixer.mix()
return listOf(1000, 2000, 3000).sumOf(mixer::getValueFromPositionOfZero)
}
private fun part2v2(input: List<Long>): Long {
val input2 = input.map { i -> i * 811589153L }
val mixer = Mixer(input2)
repeat(10) { mixer.mix() }
return listOf(1000, 2000, 3000).sumOf(mixer::getValueFromPositionOfZero)
}
private class NumberNode(
val value: Long
) {
var pred: NumberNode? = null /* by Delegates.notNull() */
var next: NumberNode? = null /* by Delegates.notNull() */
}
private class Mixer(input: List<Long>) {
val nodes = run {
val inputNodes: List<NumberNode> = input.map { i -> NumberNode(i) }
inputNodes.zipWithNext().forEach { (pred, next) ->
pred.next = next
next.pred = pred
}
inputNodes.last().next = inputNodes.first()
inputNodes.first().pred = inputNodes.last()
inputNodes
}
val zeroNode = nodes.first { n -> n.value == 0L }
private val size: Int = nodes.size
fun mix() {
nodes.forEach { currentNode ->
val nodesTraverse = (abs(currentNode.value) % (size - 1)).toInt()
if (nodesTraverse == 0 || currentNode.value == 0L) return@forEach
var newLeft: NumberNode = currentNode
var newRight: NumberNode = currentNode
if (currentNode.value > 0) {
repeat(nodesTraverse) {
newLeft = newLeft.next!!
}
newRight = newLeft.next!!
} else {
repeat(nodesTraverse) {
newRight = newRight.pred!!
}
newLeft = newRight.pred!!
}
val oldLeft = currentNode.pred
val oldRight = currentNode.next
newLeft.next = currentNode
currentNode.pred = newLeft
newRight.pred = currentNode
currentNode.next = newRight
oldLeft!!.next = oldRight
oldRight!!.pred = oldLeft
}
}
fun getValueFromPositionOfZero(position: Int): Long {
return nodesFromZero()
.drop(position % size)
.first()
}
fun nodesFromZero(): Sequence<Long> {
return sequence {
val root = zeroNode
var current = root
do {
yield(current.value)
current = current.next!!
} while (current != root)
}
}
} | 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 3,129 | aoc22-kotlin | Apache License 2.0 |
src/main/kotlin/70. Climbing Stairs.kts | ShreckYe | 206,086,675 | false | null | import kotlin.test.assertEquals
class Solution {
fun climbStairs(n: Int): Int =
(FIBONACCI_MATRIX pow n).a22
data class TwoTimesTwoSymmetricMatrix(val a11: Int, val a12AndA21: Int, val a22: Int) {
// The product of two symmetric matrices is a symmetric matrix if and only if they commute.
infix fun timesCommutatively(other: TwoTimesTwoSymmetricMatrix): TwoTimesTwoSymmetricMatrix =
TwoTimesTwoSymmetricMatrix(
a11 * other.a11 + a12AndA21 * other.a12AndA21,
a11 * other.a12AndA21 + a12AndA21 * other.a22,
a12AndA21 * other.a12AndA21 + a22 * other.a22
)
infix fun pow(exponent: Int): TwoTimesTwoSymmetricMatrix =
if (exponent == 1) this
else pow(exponent / 2).let { it timesCommutatively it }.let { if (exponent % 2 == 0) it else it timesCommutatively this }
}
companion object {
val FIBONACCI_MATRIX = TwoTimesTwoSymmetricMatrix(0, 1, 1)
}
}
// Tests
for (n in 1..10)
assertEquals(
generateSequence { Solution.FIBONACCI_MATRIX }.take(n).reduce(Solution.TwoTimesTwoSymmetricMatrix::timesCommutatively),
Solution.FIBONACCI_MATRIX pow n
)
val solution = Solution()
for (i in 1..10)
println(solution.climbStairs(i))
assertEquals(1, solution.climbStairs(1))
assertEquals(2, solution.climbStairs(2))
assertEquals(3, solution.climbStairs(3))
assertEquals(5, solution.climbStairs(4))
assertEquals(8, solution.climbStairs(5))
| 0 | Kotlin | 0 | 0 | 20e8b77049fde293b5b1b3576175eb5703c81ce2 | 1,509 | leetcode-solutions-kotlin | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day298/day298.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day298
// day298.kt
// By <NAME>, 2020.
import kotlin.math.max
typealias AppleType = Int
typealias ApplePath = List<AppleType>
/**
* Apple picking: this corresponds to the longest subarray that consists of just two values.
*/
fun applePicking(path: ApplePath): Int {
if (path.size <= 2)
path.size
require(path.all { it >= 0 })
/**
* We maintain:
* 1. The remaining path.
* 2. The apple we saw two tree types ago.
* 3. The apple we saw on the last tree type.
* 4. The number of apples we saw of the last tree type.
* This is because, say, we meet ABABBBC, when we start at C, we will start a new segment with type1 = B,
* type2 = C, and totalCount = 3B + 1C = 4.
* 5. The total segment length we are currently on.
* 6. The maximum segment length we have seen so far.
*/
tailrec
fun aux(remainingPath: ApplePath = path,
prevType1: AppleType = -1,
prevType2: AppleType = 0,
prevType2Count: Int = 0,
totalCount: Int = 0,
maxSoFar: Int = 0): Int {
if (remainingPath.isEmpty())
return max(totalCount, maxSoFar)
// Go down the path taking all of the apples of the same type.
val newType = remainingPath.first()
val newTypeCount = remainingPath.takeWhile { it == newType }.count()
// If we have switched types of apples, calculate the next max and reset.
if (newType != prevType1)
return aux(remainingPath.drop(newTypeCount), prevType2, newType, newTypeCount, prevType2Count + newTypeCount, max(totalCount, maxSoFar))
// If we don't switch types of apples, extend.
return aux(remainingPath.drop(newTypeCount), prevType2, newType, newTypeCount, totalCount + newTypeCount, maxSoFar)
}
return aux()
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 1,868 | daily-coding-problem | MIT License |
src/Day05.kt | adamgaafar | 572,629,287 | false | {"Kotlin": 12429} | import java.util.*
import kotlin.collections.ArrayDeque
fun main() {
var input = readInput("Day05")
fun part1(input: List<String>) = alterCrate(input,true)
fun part2(input: List<String>) = alterCrate(input,false)
println(part1(input))
println(part2(input))
}
fun alterCrate(input: List<String>, oneByOne: Boolean): String {
val stackLines = input.filter { '[' in it }
val moveLines = input.filter { it.startsWith('m') }
val pattern = """move (\d+) from (\d+) to (\d+)""".toRegex()
val commands = moveLines.map {
pattern.matchEntire(it)!!.destructured.toList()
}.map { it.map(String::toInt) }
val stacks = Array((stackLines.maxOf { it.length } + 1) / 4) {
ArrayDeque<Char>()
}
stackLines.forEach { line ->
val crates = "$line ".chunked(4).map { it.trim() }
crates.forEachIndexed { stack, crate ->
if (crate.isNotEmpty()) {
stacks[stack].addFirst(crate[1])
}
}
}
commands.forEach { (time ,from , to) ->
if (oneByOne) {
repeat(time) {
val crate = stacks[from - 1].removeLast()
stacks[to - 1].addLast(crate)
}
} else {
var order = ""
repeat(time) {
order += stacks[from - 1].removeLast()
}
order.reversed().forEach { crate ->
stacks[to - 1].addLast(crate)
}
}
}
return stacks.map { it.last() }.joinToString("")
}
| 0 | Kotlin | 0 | 0 | 5c7c9a2e819618b7f87c5d2c7bb6e6ce415ee41e | 1,538 | AOCK | Apache License 2.0 |
src/Day02.kt | esteluk | 572,920,449 | false | {"Kotlin": 29185} | fun main() {
val score = mapOf(
"A X" to 4,
"A Y" to 8,
"A Z" to 3,
"B X" to 1,
"B Y" to 5,
"B Z" to 9,
"C X" to 7,
"C Y" to 2,
"C Z" to 6,
)
fun part1(input: List<String>): Int {
return input.sumOf { score[it] ?: 0 }
}
// X - lose
// Y - draw
// Z - win
val newScore = mapOf(
"A X" to 3,
"A Y" to 4,
"A Z" to 8,
"B X" to 1,
"B Y" to 5,
"B Z" to 9,
"C X" to 2,
"C Y" to 6,
"C Z" to 7,
)
fun part2(input: List<String>): Int {
return input.sumOf { newScore[it] ?: 0 }
}
// Rock A X 1
// Paper B Y 2
// Scissors C Z 3
// 0 3 6
// 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 | 5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73 | 1,047 | adventofcode-2022 | Apache License 2.0 |
Kotlin/src/CombinationSum.kt | TonnyL | 106,459,115 | false | null | /**
* Given a set of candidate numbers (C) (without duplicates) and a target number (T),
* find all unique combinations in C where the candidate numbers sums to T.
*
* The same repeated number may be chosen from C unlimited number of times.
*
* Note:
* All numbers (including target) will be positive integers.
* The solution set must not contain duplicate combinations.
* For example, given candidate set [2, 3, 6, 7] and target 7,
* A solution set is:
* [
* [7],
* [2, 2, 3]
* ]
*
* Accepted.
*/
class CombinationSum {
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
if (candidates.isEmpty()) {
return emptyList()
}
val lists = mutableListOf<List<Int>>()
candidates.sort()
dfs(candidates, target, mutableListOf(), lists, 0)
return lists
}
private fun dfs(candidates: IntArray, target: Int, path: MutableList<Int>, ret: MutableList<List<Int>>, index: Int) {
if (target < 0) {
return
}
if (target == 0) {
ret.add(ArrayList(path))
return
}
for (i in index until candidates.size) {
path.add(candidates[i])
dfs(candidates, target - candidates[i], path, ret, i)
path.removeAt(path.size - 1)
}
}
}
| 1 | Swift | 22 | 189 | 39f85cdedaaf5b85f7ce842ecef975301fc974cf | 1,339 | Windary | MIT License |
src/Day01.kt | KarinaCher | 572,657,240 | false | {"Kotlin": 21749} | import java.util.Comparator
fun main() {
fun mapElvesCalories(input: List<String>): MutableMap<Int, Int> {
var elvesCalories = mutableMapOf<Int, Int>()
var index = 1
for (line in input) {
if (line.isEmpty()) {
index = index.plus(1)
elvesCalories.put(index.inc(), 0)
} else {
elvesCalories[index] = elvesCalories[index]?.plus(line.toInt()) ?: 0
}
}
return elvesCalories
}
fun part1(input: List<String>): Int {
var elvesCalories = mapElvesCalories(input)
return elvesCalories.maxOf {e -> e.value}
}
fun part2(input: List<String>): Int {
var elvesCalories = mapElvesCalories(input)
return elvesCalories.toList()
.sortedBy { it.second }
.reversed()
.stream()
.limit(3)
.mapToInt { it.second }
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 70613)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17d5fc87e1bcb2a65764067610778141110284b6 | 1,198 | KotlinAdvent | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.