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/ExtendedPolymerization_14.kt | Flame239 | 433,046,232 | false | {"Kotlin": 64209} | val polymerInput: PolymerInput by lazy {
val lines = readFile("ExtendedPolymerization").split("\n")
val initialPolymer = lines[0]
val rulesMap = mutableMapOf<String, String>()
lines.drop(2).map { line ->
line.split(" -> ").also { rulesMap[it[0]] = it[1] }
}
PolymerInput(initialPolymer, rulesMap)
}
fun polymerGrowSimulation(): String {
val (poly, rulesMap) = polymerInput
var curPolymer = StringBuilder(poly)
repeat(10) {
val curLen = curPolymer.length
val nextPoly = StringBuilder(curLen)
for (i in 0 until curLen - 1) {
nextPoly.append(curPolymer[i])
val replacement = rulesMap[curPolymer.substring(i, i + 2)] ?: ""
nextPoly.append(replacement)
}
nextPoly.append(curPolymer.last())
curPolymer = nextPoly
}
return curPolymer.toString()
}
fun countFrequencies(): Int {
val result = polymerGrowSimulation()
val frequencies = IntArray(26)
result.forEach { frequencies[it - 'A']++ }
return frequencies.filter { it != 0 }.sorted().let { it.last() - it.first() }
}
fun polymerGrowOptimized(): Long {
val (poly, rulesMap) = polymerInput
val frequencies = LongArray(26)
poly.forEach {
frequencies[it - 'A']++
}
var pairFrequencies = mutableMapOf<String, Long>()
poly.zipWithNext { a, b -> a.toString().plus(b) }.forEach {
pairFrequencies.merge(it, 1, Long::plus)
}
repeat(40) {
val newPairFrequencies = mutableMapOf<String, Long>()
pairFrequencies.forEach { (pair, count) ->
val insertion = rulesMap[pair]
if (insertion == null) {
newPairFrequencies[pair] = count
} else {
frequencies[insertion[0] - 'A'] += count
newPairFrequencies.merge(pair[0] + insertion, count, Long::plus)
newPairFrequencies.merge(insertion + pair[1], count, Long::plus)
}
}
pairFrequencies = newPairFrequencies
}
return frequencies.filter { it != 0L }.sorted().let { it.last() - it.first() }
}
fun main() {
println(countFrequencies())
println(polymerGrowOptimized())
}
data class PolymerInput(val initialPolymer: String, val rules: Map<String, String>) | 0 | Kotlin | 0 | 0 | ef4b05d39d70a204be2433d203e11c7ebed04cec | 2,291 | advent-of-code-2021 | Apache License 2.0 |
src/Day05.kt | MisterTeatime | 560,956,854 | false | {"Kotlin": 37980} | fun main() {
fun part1(input: List<String>): String {
val stacks = getStackSetup(input.takeWhile { it.isNotEmpty() }.dropLast(1))
val instructions = getInstructions(input.takeLastWhile { it.isNotEmpty() })
instructions.forEach {
var sourceStack = stacks[it.source - 1]
var destinationStack = stacks[it.destination - 1]
destinationStack += sourceStack.takeLast(it.amount).reversed() //Die Kisten aus dem Ausgangsstapel in umgekehrter Reihenfolge auf den Zielstapel legen
sourceStack = sourceStack.dropLast(it.amount) //Die Kisten vom Ausgangsstapel entfernen
stacks[it.source - 1] = sourceStack
stacks[it.destination - 1] = destinationStack
}
return stacks.fold("") { acc, stack -> acc + stack.takeLast(1)}
}
fun part2(input: List<String>): String {
val stacks = getStackSetup(input.takeWhile { it.isNotEmpty() }.dropLast(1))
val instructions = getInstructions(input.takeLastWhile { it.isNotEmpty() })
instructions.forEach {
var sourceStack = stacks[it.source - 1]
var destinationStack = stacks[it.destination - 1]
destinationStack += sourceStack.takeLast(it.amount) //Die Kisten aus dem Ausgangsstapel in gleicher Reihenfolge auf den Zielstapel legen
sourceStack = sourceStack.dropLast(it.amount) //Die Kisten vom Ausgangsstapel entfernen
stacks[it.source - 1] = sourceStack
stacks[it.destination - 1] = destinationStack
}
return stacks.fold("") { acc, stack -> acc + stack.takeLast(1)}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
fun getStackSetup(input: List<String>): MutableList<String> {
val levels = input
.map { level -> level.chunked(4).map { it[1] } }
.reversed()
val stacks = mutableListOf<String>()
for (i in 0 until levels.maxOf { it.size }) {
stacks.add(levels.map { it.elementAtOrNull(i) ?: "" }.fold("") { acc, item -> acc+item}.trimEnd())
}
return stacks
}
fun getInstructions(input: List<String>): List<ShiftInstruction> {
val regex = """move (\d+) from (\d+) to (\d+)""".toRegex()
return input
.map { regex.find(it)!!.groupValues.drop(1) }
.map { (amount, source, destination) -> ShiftInstruction(amount.toInt(), source.toInt(), destination.toInt())}
}
data class ShiftInstruction(val amount: Int, val source: Int, val destination: Int) | 0 | Kotlin | 0 | 0 | 8ba0c36992921e1623d9b2ed3585c8eb8d88718e | 2,717 | AoC2022 | Apache License 2.0 |
src/day22/Day22.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day22
import readInputAsString
private const val DAY_ID = "22"
private enum class Turn {
// turn 90 degrees clockwise
R,
// turn 90 degrees counterclockwise
L
}
private enum class Facing(val score: Int, val dx: Int, val dy: Int) {
RIGHT(0, 0, 1) {
override fun change(turn: Turn): Facing = when (turn) {
Turn.R -> DOWN
Turn.L -> UP
}
},
DOWN(1, 1, 0) {
override fun change(turn: Turn): Facing = when (turn) {
Turn.R -> LEFT
Turn.L -> RIGHT
}
},
LEFT(2, 0, -1) {
override fun change(turn: Turn): Facing = when (turn) {
Turn.R -> UP
Turn.L -> DOWN
}
},
UP(3, -1, 0) {
override fun change(turn: Turn): Facing = when (turn) {
Turn.R -> RIGHT
Turn.L -> LEFT
}
};
abstract fun change(turn: Turn): Facing
}
private data class Board(val rows: List<RowInfo>, val cols: List<ColInfo>) {
// row = x + offsetX
data class RowInfo(private val items: List<Boolean>, val offsetY: Int) {
val size: Int = items.size
operator fun get(col: Int): Boolean = items[col]
}
// col = y + offsetY
data class ColInfo(val size: Int, val offsetX: Int)
companion object {
fun fromString(s: String): Board {
// since key is an int, the natural order of columns will be preserved;
// cols[y][0] - size of column y
// cols[y][1] - X offset
val cols = hashMapOf<Int, IntArray>()
val rows = s.lines().mapIndexed { x, line ->
var offsetY = 0
val items = mutableListOf<Boolean>()
line.forEachIndexed { y, c ->
if (!c.isWhitespace()) {
if (items.isEmpty()) {
offsetY = y
}
items += c == '.'
cols.getOrPut(y) { intArrayOf(0, x) }[0]++
}
}
RowInfo(items, offsetY)
}
return Board(rows, cols.values.map { (size, offsetX) -> ColInfo(size, offsetX) })
}
}
}
private sealed class Move {
data class Number(val steps: Int) : Move()
data class Letter(val turn: Turn) : Move()
}
private data class Path(val moves: List<Move>) {
companion object {
fun fromString(s: String): Path {
var i = 0
var x = 0
val moves = mutableListOf<Move>()
while (i < s.length) {
if (s[i].isDigit()) {
x *= 10
x += s[i].digitToInt()
} else {
// "10R..." vs possible? "R10..."
if (s.first().isDigit()) {
moves += Move.Number(x)
}
moves += Move.Letter(enumValueOf("${s[i]}"))
x = 0
}
i++
}
// "...L5" vs possible? "...5L"
if (s.last().isDigit()) {
moves += Move.Number(x)
}
return Path(moves)
}
}
}
private data class Note(val board: Board, val path: Path)
fun main() {
fun parseInput(input: String): Note {
val (board, path) = input.split("\n\n")
return Note(Board.fromString(board), Path.fromString(path))
}
fun mod(x: Int, m: Int): Int = if (x < 0) (m - (-x) % m) % m else x % m
fun part1(input: String): Int {
val (board, path) = parseInput(input)
var row = 0
var y = -1
var facing = Facing.RIGHT
for (move in path.moves) {
when (move) {
is Move.Letter -> facing = facing.change(move.turn)
is Move.Number -> {
for (step in 0 until move.steps) {
val oldRow = row
val oldY = y
// move to the next tile and wrap around if needed
when (facing) {
Facing.LEFT, Facing.RIGHT -> {
// x doesn't change
y += facing.dy
y = mod(y, board.rows[row].size)
}
Facing.UP, Facing.DOWN -> {
// y doesn't change
val col = y + board.rows[row].offsetY
row -= board.cols[col].offsetX
row += facing.dx
row = mod(row, board.cols[col].size)
row += board.cols[col].offsetX
// recompute y in a new row
y = col - board.rows[row].offsetY
}
}
// hit the wall?
if (!board.rows[row][y]) {
row = oldRow
y = oldY
break
}
}
}
}
}
val col = y + board.rows[row].offsetY
return 1000 * (row + 1) + 4 * (col + 1) + facing.score
}
fun part2(input: String): Int {
TODO()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsString("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == 6032)
//check(part2(testInput) == 42)
val input = readInputAsString("day${DAY_ID}/Day${DAY_ID}")
println(part1(input)) // answer = 76332
//println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 5,797 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day07/day07.kt | PS-MS | 572,890,533 | false | null | package day07
import readInput
fun main() {
open class DeviceObj {
}
data class DeviceFile(val fileSize: Long, val name: String) : DeviceObj()
data class DeviceDir(val name: String, val content: List<DeviceObj>) : DeviceObj()
fun buildDirectoryTree(input: List<String>): HashMap<String, MutableList<DeviceFile>> {
val deviceContent: HashMap<String, MutableList<DeviceFile>> =
hashMapOf(Pair("/", mutableListOf()))
var currentPath = ""
input.forEach {
val parts = it.split(" ")
when (parts[0]) {
"$" -> {
when (parts[1]) {
"cd" -> {
when (parts[2]) {
".." -> currentPath = currentPath.substringBeforeLast("/")
"/" -> currentPath = "/"
else -> currentPath += "/${parts[2]}"
}
}
}
}
"dir" -> {
val dirPath = "$currentPath/${parts[1]}"
if (!deviceContent.contains(dirPath)) {
deviceContent[dirPath] = mutableListOf()
}
}
"ls" -> {} // the next parts will be for this directory
else -> {
val file = DeviceFile(parts[0].toLong(), parts[1])
var recursivePath = currentPath
while (recursivePath.isNotBlank()) {
deviceContent[recursivePath]?.add(file)
recursivePath = recursivePath.substringBeforeLast("/")
}
}
}
}
return deviceContent
}
fun part1(input: List<String>): Long {
val deviceContent = buildDirectoryTree(input)
val filtered =
deviceContent.asIterable().filter { it.value.sumOf { it.fileSize } <= 100000 }
return filtered.sumOf { it.value.sumOf { it.fileSize } }
}
fun part2(input: List<String>): Long {
val dirMap = buildDirectoryTree(input)
val totalSpace = 70000000
val updateSpace = 30000000
val usedSpace = dirMap["/"]?.sumOf { it.fileSize } ?: 0
val unusedSpace = totalSpace - usedSpace
val requiredSpace = updateSpace - unusedSpace
val dirCandidates =
dirMap.asIterable().filter { it.value.sumOf { it.fileSize } >= requiredSpace }
return dirCandidates.minOf { it.value.sumOf { it.fileSize } }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day07/test")
// val p1Test = part1(testInput)
// println("p1 test = $p1Test")
// check(p1Test == 95437L)
val p2Test = part2(testInput)
println("p2 test = $p2Test")
check(part2(testInput) == 24933642L)
val input = readInput("day07/real")
val p1Real = part1(input)
println("p1 real = $p1Real")
val p2Real = part2(input)
println("p2 real = $p2Real")
} | 0 | Kotlin | 0 | 0 | 24f280a1d8ad69e83755391121f6107f12ffebc0 | 3,112 | AOC2022 | Apache License 2.0 |
src/day11/Day11.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day11
import readInput
fun main() {
val testInput = readInput("day11/test")
part1(testInput)
part2(testInput)
}
private fun part1(testInput: List<String>) {
val solution = Solution.from(testInput)
solution.calculate1()
}
private fun part2(testInput: List<String>) {
val solution = Solution.from(testInput)
solution.calculate2()
}
private class Solution {
val monkeys = mutableListOf<Monkey>()
fun addNewMonkey(initialItems: List<Long>, operation: (Long) -> Long, test: Int, monkey1: Int, monkey2: Int) {
val monkey = Monkey(operation, test, monkey1 to monkey2).apply {
addItems(initialItems)
}
monkeys.add(monkey)
}
fun Iterable<Long>.lcm(): Long = reduce { a, b -> a * b }
fun calculate1() {
repeat(20) {
monkeys.forEach {
it.inspect1()
}
}
val (first, second) = monkeys.map { it.inspectCount }.sortedDescending().take(2)
println(first.toLong() * second.toLong())
}
fun calculate2() {
val modulus = monkeys.map { it.divisible.toLong() }.lcm()
repeat(10000) {
monkeys.forEach {
it.inspect2(modulus)
}
}
val (first, second) = monkeys.map { it.inspectCount }.sortedDescending().take(2)
println(first.toLong() * second.toLong())
}
inner class Monkey(
val operation: (Long) -> Long,
val divisible: Int,
val nextMonkey: Pair<Int, Int>
) {
val items: MutableList<Long> = mutableListOf()
var inspectCount = 0
fun addItems(newItems: List<Long>) {
items.addAll(newItems)
}
fun inspect1() {
while (items.isNotEmpty()) {
val item = items.removeFirst()
val newLevel = operation(item) / 3
if (newLevel % divisible == 0L) {
monkeys[nextMonkey.first].items.add(newLevel)
} else {
monkeys[nextMonkey.second].items.add(newLevel)
}
inspectCount++
}
}
fun inspect2(modulus: Long) {
while (items.isNotEmpty()) {
val item = items.removeFirst()
val newLevel = operation(item) % modulus
if (newLevel % divisible == 0L) {
monkeys[nextMonkey.first].items.add(newLevel)
} else {
monkeys[nextMonkey.second].items.add(newLevel)
}
inspectCount++
}
}
}
companion object {
private fun createOperation(operation: String): (Long) -> Long {
val (_, operator, value) = operation.split(" ")
return when (operator) {
"+" -> { old -> old + value.toInt() }
"*" -> { old ->
if (value == "old") {
old * old
} else {
old * value.toInt()
}
}
else -> { old -> old }
}
}
fun from(testInput: List<String>): Solution {
val solution = Solution()
var index = 0
while (index < testInput.size) {
val itemsLine = testInput[index + 1]
val operationLine = testInput[index + 2]
val test = testInput[index + 3].filter { it.isDigit() }.toInt()
val trueMonkey = testInput[index + 4].filter { it.isDigit() }.toInt()
val falseMonkey = testInput[index + 5].filter { it.isDigit() }.toInt()
val items = itemsLine.replace(" Starting items: ", "").split(", ")
val operation = createOperation(operationLine.replace(" Operation: new = ", ""))
solution.addNewMonkey(items.map { it.toLong() }, operation, test, trueMonkey, falseMonkey)
index += 7
}
return solution
}
}
} | 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 4,062 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | syncd010 | 324,790,559 | false | null | import kotlin.math.abs
import kotlin.math.asin
import kotlin.math.hypot
import kotlin.math.PI
class Day10: Day {
private fun Position.direction(): Position? {
val g = abs(gcd(x, y))
return if (g == 0) null else Position(x / g, y / g)
}
fun Position.angleFromVertical(): Double {
val h = hypot(x.toDouble(), y.toDouble())
return when {
(x >= 0) && (y < 0) -> asin(x / h)
(x > 0) && (y >= 0) -> PI / 2 + asin(y / h)
(x <= 0) && (y > 0) -> PI + asin(-x / h)
(x < 0) && (y <= 0) -> 3 * PI / 2 + asin(-y / h)
else -> -1.0
}
}
fun Position.hypot(): Double = hypot(x.toDouble(), y.toDouble())
private fun convert(input: List<String>) : List<Position> {
return input.mapIndexed { idxRow, row ->
row.mapIndexedNotNull { idxCol, col ->
if (col == '#') Position(idxCol, idxRow) else null
}
}.flatten()
}
override fun solvePartOne(input: List<String>): Int {
val asteroids = convert(input)
return asteroids
.map { orig ->
asteroids
.filter { it != orig }
.map { dest -> dest - orig }
.groupBy { it.direction() }
.size
}.max() ?: -1
}
override fun solvePartTwo(input: List<String>): Int {
val asteroids = convert(input)
val grouped = asteroids
.map { orig ->
asteroids
.filter { it != orig }
.map { dest -> dest - orig }
.groupBy { it.direction() }
}
val idxMax = grouped.withIndex()
.maxBy { it.value.size }!!
.index
val sortedAsts = grouped[idxMax].values
.sortedBy { it[0].angleFromVertical() }
.map { it.sortedBy { it.hypot() } }
val res = sortedAsts[199][0] + asteroids[idxMax]
return res.x * 100 + res.y
}
} | 0 | Kotlin | 0 | 0 | 11c7c7d6ccd2488186dfc7841078d9db66beb01a | 2,110 | AoC2019 | Apache License 2.0 |
src/day02/Day02.kt | tiginamaria | 573,173,440 | false | {"Kotlin": 7901} | package day02
import readInput
enum class Shape(val score: Int) {
Rock(1), Paper(2), Scissors(3);
fun compare(opponent: Shape): Result {
if (this.score == opponent.score) return Result.Draw
if ((this.score + 1) % 3 == opponent.score % 3) return Result.Lose
return Result.Win
}
fun pair(result: Result): Shape {
if (result == Result.Draw) return this
if (result == Result.Lose) return Shape.values()[(this.ordinal - 1 + 3) % 3]
return Shape.values()[(this.ordinal + 1) % 3]
}
}
enum class Result(val score: Int) {
Win(6), Draw(3), Lose(0);
}
fun main() {
val opponentToShape = mapOf(
'A' to Shape.Rock,
'B' to Shape.Paper,
'C' to Shape.Scissors,
)
val myToShape = mapOf(
'X' to Shape.Rock,
'Y' to Shape.Paper,
'Z' to Shape.Scissors,
)
val myToResult = mapOf(
'X' to Result.Lose,
'Y' to Result.Draw,
'Z' to Result.Win,
)
fun part1(input: List<String>): Int {
var totalScore = 0
input.forEach {
val opponentShape = opponentToShape[it[0]]!!
val myShape = myToShape[it[2]]!!
val myResult = myShape.compare(opponentShape)
totalScore += myResult.score + myShape.score
}
return totalScore
}
fun part2(input: List<String>): Int {
var totalScore = 0
input.forEach {
val opponentShape = opponentToShape[it[0]]!!
val myResult = myToResult[it[2]]!!
val myShape = opponentShape.pair(myResult)
totalScore += myResult.score + myShape.score
}
return totalScore
}
val input = readInput("Day02", 2)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bf81cc9fbe11dce4cefcb80284e3b19c4be9640e | 1,808 | advent-of-code-kotlin | Apache License 2.0 |
src/Day04.kt | Aldas25 | 572,846,570 | false | {"Kotlin": 106964} | fun main() {
fun contains(firstElf: List<Int>, secondElf: List<Int>): Boolean {
return firstElf[0] <= secondElf[0] && secondElf[1] <= firstElf[1]
}
fun overlaps(firstElf: List<Int>, secondElf: List<Int>): Boolean {
return !(firstElf[0] > secondElf[1] || secondElf[0] > firstElf[1])
}
fun part1(input: List<String>): Int {
var ans = 0
for (s in input) {
val ranges = s.split(",")
val firstElf = ranges[0].split("-").map { x -> x.toInt() }
val secondElf = ranges[1].split("-").map { x -> x.toInt() }
if (contains(firstElf, secondElf) || contains(secondElf, firstElf)) {
ans++
}
}
return ans
}
fun part2(input: List<String>): Int {
var ans = 0
for (s in input) {
val ranges = s.split(",")
val firstElf = ranges[0].split("-").map { x -> x.toInt() }
val secondElf = ranges[1].split("-").map { x -> x.toInt() }
if (overlaps(firstElf, secondElf)) {
ans++
}
}
return ans
}
val filename =
// "inputs\\day04_sample"
"inputs\\day04"
val input = readInput(filename)
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 80785e323369b204c1057f49f5162b8017adb55a | 1,333 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/day23/Day23.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day23
import readInput
data class Position(val col: Int, val row: Int)
enum class Direction(val dx: Int, val dy: Int, val horizontal: Boolean) {
LEFT(-1, 0, false),
UP(0, -1, true),
RIGHT(1, 0, false),
DOWN(0, 1, true);
}
data class Limits(val minX: Int, val minY: Int, val maxX: Int, val maxY: Int)
data class State(val elves: Set<Position>) {
fun result(): Int {
return limits.let {
(it.maxY - it.minY + 1) * (it.maxX - it.minX + 1) - elves.size
}
}
private val limits = elves.fold(Limits(Int.MAX_VALUE, Int.MAX_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)) { acc, elf ->
Limits(
minOf(acc.minX, elf.col),
minOf(acc.minY, elf.row),
maxOf(acc.maxX, elf.col),
maxOf(acc.maxY, elf.row)
)
}
private val directions = listOf(Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT)
fun round(round: Int): State {
val moves = mutableMapOf<Position, Position>()
val seen = mutableSetOf<Position>()
val invalid = mutableSetOf<Position>()
for (elf in elves) {
if (!shouldMove(elf)) {
continue
}
for (i in 0..3) {
val direction = directions[(round + i) % 4]
val nx = elf.col + direction.dx
val ny = elf.row + direction.dy
val horizontal = direction.horizontal
val position = Position(nx, ny)
if (isValid(position, horizontal)) {
if (!seen.add(position)) {
invalid.add(position)
}
moves[elf] = position
break
}
}
}
return State(
elves.map {
moves[it]?.let { pos -> if (!invalid.contains(pos)) pos else it } ?: it
}.toSet()
)
}
fun shouldMove(position: Position): Boolean {
return listOf(
Position(position.col - 1, position.row),
Position(position.col - 1, position.row - 1),
Position(position.col, position.row - 1),
Position(position.col + 1, position.row - 1),
Position(position.col + 1, position.row),
Position(position.col + 1, position.row + 1),
Position(position.col, position.row + 1),
Position(position.col - 1, position.row + 1)
).any { isOccupied(it) }
}
fun isValid(position: Position, horizontal: Boolean): Boolean {
val positionsToCheck = if (horizontal) {
listOf(position, Position(position.col - 1, position.row), Position(position.col + 1, position.row))
} else {
listOf(position, Position(position.col, position.row - 1), Position(position.col, position.row + 1))
}
return positionsToCheck.none { isOccupied(it) }
}
private fun isOccupied(position: Position): Boolean {
return elves.contains(position)
}
fun print() {
println("${limits.minX} ${limits.minY} ")
println((limits.minY..limits.maxY).joinToString(separator = "\n") { y ->
(limits.minX..limits.maxX).joinToString(separator = "") { x ->
if (isOccupied(Position(x, y))) {
"#"
} else {
"."
}
}
})
}
}
fun parse(input: List<String>): State {
val map = input.takeWhile { it.isNotEmpty() }
val elves = map.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c -> if (c == '#') Position(x, y) else null }
}.map { it }
return State(elves.toSet())
}
fun main() {
fun part1(input: List<String>): Int {
var state = parse(input)
state.print()
repeat(10) {
state = state.round(it)
state.print()
}
return state.result()
}
fun part2(input: List<String>): Int {
var state = parse(input)
var round = 0
while (true) {
val newState = state.round(round)
round += 1
if (newState == state) {
break
}
state = newState
}
return round
}
val testInput = readInput("day23", "test")
val input = readInput("day23", "input")
val part1 = part1(testInput)
println(part1)
check(part1 == 110)
println(part1(input))
val part2 = part2(testInput)
println(part2)
check(part2 == 20)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 4,583 | aoc2022 | Apache License 2.0 |
string-similarity/src/commonMain/kotlin/com/aallam/similarity/LongestCommonSubsequence.kt | aallam | 597,692,521 | false | null | package com.aallam.similarity
import kotlin.math.max
/**
* The longest common subsequence (LCS) problem consists in finding the longest subsequence common to two (or more)
* sequences. It differs from problems of finding common substrings: unlike substrings, subsequences are not required
* to occupy consecutive positions within the original sequences.
*
* LCS distance is equivalent to Levenshtein distance, when only insertion and deletion is allowed (no substitution),
* or when the cost of the substitution is the double of the cost of an insertion or deletion.
*/
public class LongestCommonSubsequence {
/**
* Return the LCS distance between strings [first] (length n) and [second] (length m),
* computed as `|n| + |m| - 2 * |LCS(first, second)|`, with min = 0 max = n + m
*
* @param first the first string to compare.
* @param second the second string to compare.
*/
public fun distance(first: String, second: String): Int {
if (first == second) return 0
return first.length + second.length - 2 * length(first, second)
}
/**
* Return the length of the longest common subsequence (LCS) between strings [first]
* and [second].
*
* @param first the first string to compare.
* @param second the second string to compare.
*/
public fun length(first: String, second: String): Int {
val n = first.length
val m = second.length
val x = first.toCharArray()
val y = second.toCharArray()
val c = Array(n + 1) { IntArray(m + 1) }
for (i in 1..n) {
for (j in 1..m) {
if (x[i - 1] == y[j - 1]) {
c[i][j] = c[i - 1][j - 1] + 1
} else {
c[i][j] = max(c[i][j - 1], c[i - 1][j])
}
}
}
return c[n][m]
}
}
| 0 | Kotlin | 0 | 1 | 40cd4eb7543b776c283147e05d12bb840202b6f7 | 1,879 | string-similarity-kotlin | MIT License |
solutions/aockt/y2015/Y2015D14.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2015
import io.github.jadarma.aockt.core.Solution
object Y2015D14 : Solution {
private data class Reindeer(val name: String, val speed: Int, val sprint: Int, val rest: Int)
private val inputRegex =
Regex("""(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds\.""")
/** Parses a single line of input and returns a [Reindeer] and its statistics. */
private fun parseInput(input: String): Reindeer {
val (name, speed, sprint, rest) = inputRegex.matchEntire(input)!!.destructured
return Reindeer(name, speed.toInt(), sprint.toInt(), rest.toInt())
}
/** Calculates the total distance this [Reindeer] travelled after exactly this many [seconds]. */
private fun Reindeer.distanceAfter(seconds: Int): Int {
val cycle = sprint + rest
val completeCycles = seconds / cycle
val moduloSprint = minOf(sprint, seconds % cycle)
return (completeCycles * sprint + moduloSprint) * speed
}
/** Races the [contestants], returning their associated scores after each increment (in seconds). */
private fun reindeerRace(contestants: List<Reindeer>) = sequence<Map<Reindeer, Int>> {
val currentScore = contestants.associateWithTo(mutableMapOf()) { 0 }
var seconds = 0
yield(currentScore)
while (true) {
seconds += 1
val reindeerDistances = contestants.associateWith { it.distanceAfter(seconds) }
val maxDistance = reindeerDistances.maxOf { it.value }
reindeerDistances
.filter { it.value == maxDistance }
.forEach { (reindeer, _) -> currentScore[reindeer] = currentScore[reindeer]!! + 1 }
yield(currentScore)
}
}
override fun partOne(input: String) =
input
.lineSequence()
.map(this::parseInput)
.map { it.distanceAfter(seconds = 2503) }
.maxOrNull()!!
override fun partTwo(input: String): Int {
val contestants = input.lines().map(this::parseInput)
return reindeerRace(contestants).elementAt(2503).maxOf { it.value }
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 2,169 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day05.kt | simonbirt | 574,137,905 | false | {"Kotlin": 45762} | fun main() {
Day5.printSolutionIfTest("CMZ", "MCD")
}
typealias Stacks = MutableMap<Int, List<String>>
object Day5 : Day<String, String>(5) {
override fun part1(lines: List<String>) = solve(lines, true)
override fun part2(lines: List<String>) = solve(lines, false)
private fun solve(lines: List<String>, rev:Boolean) =
readStacks(lines)
.also {applyInstructions(lines, it, rev)}
.values.joinToString("") { it.first() }
private fun readStacks(lines: List<String>) =
lines.takeWhile { it.contains("[") }
.flatMap { l -> l.chunked(4).withIndex().filter { it.value.isNotBlank() }}
.groupBy({ it.index + 1 }, { it.value[1].toString() })
.toSortedMap()
private fun applyInstructions(lines: List<String>, stacks: Stacks, rev:Boolean) {
lines.filter { it.contains("move") }
.map { l -> l.split("move ", " from ", " to ").filter { it.isNotBlank() }.map { it.toInt() } }
.forEach { (m, f, t) -> move(stacks, m, f, t, rev)}
}
private fun move(stacks: Stacks, quantity: Int, source: Int, destination: Int, rev: Boolean) {
stacks[destination] = stacks[source]?.take(quantity)?.let{ if (rev) it.reversed() else it }!! + stacks[destination]!!
stacks[source] = stacks[source]?.drop(quantity)!!
}
}
| 0 | Kotlin | 0 | 0 | 962eccac0ab5fc11c86396fc5427e9a30c7cd5fd | 1,350 | advent-of-code-2022 | Apache License 2.0 |
2018/kotlin/day18p2/src/main.kt | sgravrock | 47,810,570 | false | {"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488} | import java.util.*
fun main(args: Array<String>) {
val start = Date()
val input = puzzleInput()
val result = scoreAfter(1000000000, input)
val end = Date()
println(result)
println("in ${end.time - start.time} ms")
}
fun puzzleInput(): World {
val classLoader = World::class.java.classLoader
val input = classLoader.getResource("input.txt").readText()
return World.parse(input)
}
enum class Acre { Open, Wooded, LumberYard }
fun unoptimizedScoreAfter(minutes: Int, world: World): Int {
val endState = (1..minutes).fold(world, { prev, _ -> prev.next() })
val wooded = endState.cells().count { it == Acre.Wooded }
val lumberYards = endState.cells().count { it == Acre.LumberYard }
return wooded * lumberYards
}
fun scoreAfter(minutes: Int, world: World): Int {
val cycle = findCycle(minutes, world)
val minutesAfterCycle = (minutes - cycle.start) % cycle.length
val endState = (1..minutesAfterCycle)
.fold(cycle.endState, { prev, _ -> prev.next() })
val wooded = endState.cells().count { it == Acre.Wooded }
val lumberYards = endState.cells().count { it == Acre.LumberYard }
return wooded * lumberYards
}
fun findCycle(minutes: Int, world: World): Cycle {
val seen = mutableMapOf(world to 0)
(1..minutes).asSequence().fold(world, { prev, minute ->
val next = prev.next()
if (seen.containsKey(next)) {
return Cycle(seen[next]!!, minute - 1, next)
}
seen[next] = minute
next
})
throw Error("Didn't find a cycle")
}
data class Coord(val x: Int, val y: Int)
data class Cycle(val start: Int, val end: Int, val endState: World) {
val length = end - start + 1
}
data class World(val data: List<List<Acre>>) {
fun next(): World {
val result = data.mapIndexed { y, row ->
row.mapIndexed { x, acre ->
when (acre) {
Acre.Open -> {
if (numNeighbors(x, y, Acre.Wooded) >= 3) {
Acre.Wooded
} else {
Acre.Open
}
}
Acre.Wooded -> {
if (numNeighbors(x, y, Acre.LumberYard) >= 3) {
Acre.LumberYard
} else {
Acre.Wooded
}
}
Acre.LumberYard -> {
if (
numNeighbors(x, y, Acre.LumberYard) >= 1 &&
numNeighbors(x, y, Acre.Wooded) >= 1
) {
Acre.LumberYard
} else {
Acre.Open
}
}
}
}
}
return World(result)
}
fun cells(): Sequence<Acre> {
return data.asSequence().flatMap { it.asSequence() }
}
private fun numNeighbors(x: Int, y: Int, type: Acre): Int {
val candidates = listOf(
Coord(x - 1, y - 1),
Coord(x, y - 1),
Coord(x + 1, y - 1),
Coord(x - 1, y),
Coord(x + 1, y),
Coord(x - 1, y + 1),
Coord(x, y + 1),
Coord(x + 1, y + 1)
)
return candidates.count { c -> at(c) == type }
}
private fun at(c: Coord): Acre? {
val row = data.getOrNull(c.y)
?: return null
return row.getOrNull(c.x)
}
override fun toString(): String {
return data
.map { row ->
row.map {
when (it) {
Acre.Open -> '.'
Acre.Wooded -> '|'
Acre.LumberYard -> '#'
}
}.joinToString("")
}.joinToString("\n")
}
companion object {
fun parse(input: String): World {
val result = input.lines()
.map { line ->
line.toCharArray()
.map { c ->
when (c) {
'.' -> Acre.Open
'|' -> Acre.Wooded
'#' -> Acre.LumberYard
else -> throw Error("Unrecognized character: $c")
}
}
}
return World(result)
}
}
} | 0 | Rust | 0 | 0 | ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3 | 4,569 | adventofcode | MIT License |
src/Day04.kt | hubikz | 573,170,763 | false | {"Kotlin": 8506} | fun main() {
fun pairElves(it: String): Pair<List<Int>, List<Int>> {
val (left, right) = it.split(",")
val (leftStart, leftStop) = left.split("-")
val (rightStart, rightStop) = right.split("-")
val leftRange = (leftStart.toInt()..leftStop.toInt()).toList()
val rightRange = (rightStart.toInt()..rightStop.toInt()).toList()
return Pair(leftRange, rightRange)
}
fun part1(input: List<String>): Int {
val result = input.map {
val (leftRange, rightRange) = pairElves(it)
if (leftRange.containsAll(rightRange) || rightRange.containsAll(leftRange)) 1 else 0
}
return result.sum()
}
fun part2(input: List<String>): Int {
val result = input.map {
val (leftRange, rightRange) = pairElves(it)
if (leftRange.firstOrNull { section -> rightRange.contains(section) } != null) 1 else 0
}
return result.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
val input = readInput("Day04")
println("Part 1: ${part1(input)}")
check(part2(testInput) == 4)
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 902c6c3e664ad947c38c8edcb7ffd612b10e58fe | 1,272 | AoC2022 | Apache License 2.0 |
src/Day07.kt | vlsolodilov | 573,277,339 | false | {"Kotlin": 19518} | fun main() {
fun getDirectoryList(input: List<String>): List<Directory> {
val dirs = mutableListOf<Directory>()
var currentDirectory: Directory? = Directory()
input.forEach { line ->
if (line.startsWith("$ cd")) {
if (line.split(" ").last() == "..") {
currentDirectory = currentDirectory?.parent
} else {
currentDirectory = Directory(
parent = currentDirectory,
name = line.split(" ").last()
)
dirs.add(currentDirectory!!)
}
} else if (line[0].isDigit()) {
val fileSize = line.split(" ")[0].toInt()
var directory: Directory? = currentDirectory
while (directory != null) {
directory.increaseSize(fileSize)
directory = directory.parent
}
}
}
return dirs
}
fun part1(input: List<String>): Int =
getDirectoryList(input)
.filter { directory -> directory.totalSize <= 100_000 }
.sumOf { it.totalSize }
fun part2(input: List<String>): Int {
val dirSizeList = getDirectoryList(input).map { it.totalSize }
val unusedSpace = 70_000_000 - dirSizeList.max()
return dirSizeList.sorted().first { (unusedSpace + it) >= 30_000_000 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95_437)
check(part2(testInput) == 24_933_642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
data class Directory(
val parent: Directory? = null,
val name: String = "",
var totalSize: Int = 0
) {
fun increaseSize(size: Int) {
totalSize +=size
}
}
| 0 | Kotlin | 0 | 0 | b75427b90b64b21fcb72c16452c3683486b48d76 | 1,925 | aoc22 | Apache License 2.0 |
2023/src/main/kotlin/Day13.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import java.util.regex.Pattern
object Day13 {
fun part1(input: String) = solve(input, ::findHorizontalReflection)
fun part2(input: String) = solve(input, ::findSmudgedHorizontalReflection)
private fun solve(input: String, finder: (List<String>) -> Int?): Int {
return parseInput(input)
.sumOf { pattern ->
val horizontal = finder(pattern)
if (horizontal != null) 100 * horizontal else finder(rotateClockwise(pattern))!!
}
}
private fun findHorizontalReflection(pattern: List<String>): Int? {
val height = pattern.size
return (1..<height)
.find { y ->
val size = minOf(y, height - y)
val above = pattern.subList(y - size, y)
val below = pattern.subList(y, y + size).reversed()
return@find above == below
}
}
private fun findSmudgedHorizontalReflection(pattern: List<String>): Int? {
val height = pattern.size
return (1..<height)
.find { y ->
val size = minOf(y, height - y)
val above = pattern.subList(y - size, y)
val below = pattern.subList(y, y + size).reversed()
// Require one row to differ
val differentRows = (0..<size).filter { above[it] != below[it] }
if (differentRows.size != 1) {
return@find false
}
// Require one smudge in the one row that differs
val smudgeRow = differentRows[0]
return@find canSmudge(above[smudgeRow], below[smudgeRow])
}
}
private fun rotateClockwise(pattern: List<String>): List<String> {
return pattern[0].indices.map { col ->
pattern.map { it[col] }.joinToString("")
}
}
private fun canSmudge(a: String, b: String) = a.indices.count { a[it] != b[it] } == 1
private fun parseInput(input: String): List<List<String>> {
return input.split(Pattern.compile("\\r?\\n\\r?\\n")).map { it.splitNewlines() }
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,886 | advent-of-code | MIT License |
src/main/kotlin/aoc2023/Day15.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import utils.InputUtils
import java.lang.IllegalArgumentException
val parseInstruction = "([a-z]+)(-)?(=(\\d))?".toRegex()
private fun String.day15Hash() = fold(0) { acc, c ->
((acc + c.code) * 17) % 256
}
private class HashTable {
val buckets = Array(256) { mutableListOf<Pair<String, Int>>() }
fun score() = buckets.flatMapIndexed { index, pairs ->
pairs.mapIndexed { i, pair -> (index + 1) * (i + 1) * pair.second }
}.sum()
fun add(key: String, lense: Int) {
val bucket = bucket(key)
val index = bucket.indexOfFirst { it.first == key }
if (index == -1) bucket.add(key to lense)
else bucket[index] = key to lense
}
fun remove(key: String) {
bucket(key).removeIf { it.first == key }
}
private fun bucket(key: String) = buckets[key.day15Hash()]
}
fun main() {
val testInput = """rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7""".trimIndent().split("\n")
fun part1(input: List<String>): Int {
return input.joinToString("").split(",")
.sumOf { it.day15Hash() }
}
fun part2(input: List<String>): Int {
val h = HashTable()
input.joinToString("").split(",")
.map { instruction ->
parseMatchOrThrow(instruction, parseInstruction) {
val (key, remove, _, lense) = it.destructured
//println("$key, $remove, $lense")
if (remove.isNotEmpty()) {
h.remove(key)
} else if (lense.isNotEmpty()) {
h.add(key, lense.toInt())
} else throw IllegalArgumentException("Invalid instruction $instruction")
} }
return h.score()
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 1320)
println(part2(testInput))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 15)
val input = puzzleInput.toList()
println(part1(input))
val start = System.currentTimeMillis()
println(part2(input))
println("Time: ${System.currentTimeMillis() - start}")
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 2,203 | aoc-2022-kotlin | Apache License 2.0 |
advent-of-code-2023/src/Day16.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | import lib.countDistinctBy
import lib.matrix.*
import lib.matrix.Direction.*
import lib.matrix.Direction.Companion.nextInDirection
private const val DAY = "Day16"
fun main() {
fun testInput() = readInput("${DAY}_test")
fun input() = readInput(DAY)
"Part 1" {
part1(testInput()) shouldBe 46
measureAnswer { part1(input()) }
}
"Part 2" {
part2(testInput()) shouldBe 51
measureAnswer { part2(input()) }
}
}
private fun part1(field: Matrix<Char>): Int = energizeField(field, startBeam = Beam(RIGHT, field.topLeftPosition))
private fun part2(field: Matrix<Char>): Int = field.startBeams().maxOf { startBeam -> energizeField(field, startBeam) }
private fun Matrix<Char>.startBeams(): Sequence<Beam> = sequence {
for (row in rowIndices) {
yield(Beam(RIGHT, Position(row, 0)))
yield(Beam(LEFT, Position(row, lastColumnIndex)))
}
for (col in columnIndices) {
yield(Beam(DOWN, Position(0, col)))
yield(Beam(UP, Position(lastRowIndex, col)))
}
}
private fun energizeField(field: Matrix<Char>, startBeam: Beam): Int {
val beams = ArrayDeque<Beam>()
val seenBeams = mutableSetOf<Beam>()
fun addBeam(beam: Beam) {
if (beam.position in field && beam !in seenBeams) {
seenBeams += beam
beams.addLast(beam)
}
}
addBeam(startBeam)
while (beams.isNotEmpty()) {
val beam = beams.removeFirst()
val (nextBeam, forkedBeam) = beam.move(field[beam.position])
addBeam(nextBeam)
forkedBeam?.let(::addBeam)
}
return seenBeams.countDistinctBy { it.position }
}
private data class Beam(
val direction: Direction,
val position: Position,
) {
/** Returns the beam with updated position and direction, and forked beam if it was split. */
fun move(currentTile: Char): Pair<Beam, Beam?> {
val (direction, forkedBeam) = processTile(currentTile)
val position = position.nextInDirection(direction)
return Beam(direction, position) to forkedBeam
}
private fun processTile(tile: Char): Pair<Direction, Beam?> {
var forkedBeam: Beam? = null
var direction = this.direction
when (tile) {
in "\\/" -> direction = direction.turn(tile)
'|' -> if (direction.horizontal) {
direction = UP
forkedBeam = copy(direction = DOWN)
}
'-' -> if (direction.vertical) {
direction = LEFT
forkedBeam = copy(direction = RIGHT)
}
}
return direction to forkedBeam
}
}
private fun readInput(name: String) = readMatrix(name)
private fun Direction.turn(mirror: Char) = turn(clockwise = if (vertical) mirror == '/' else mirror == '\\')
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 2,811 | advent-of-code | Apache License 2.0 |
2019/src/main/kotlin/adventofcode/day03/main.kt | analogrelay | 47,284,386 | false | {"Go": 93140, "F#": 42601, "Common Lisp": 36618, "Rust": 35214, "Kotlin": 15705, "Erlang": 15613, "TypeScript": 9933, "Swift": 4317, "HTML": 1721, "Shell": 1388, "PowerShell": 1180, "CSS": 990, "Makefile": 293, "JavaScript": 165} | package adventofcode.day03
import java.io.File
data class Point(val x: Int, val y: Int) {
public fun moveLeft(distance: Int)= Point(x - distance, y)
public fun moveRight(distance: Int)= Point(x + distance, y)
public fun moveUp(distance: Int)= Point(x, y + distance)
public fun moveDown(distance: Int)= Point(x, y - distance)
public fun iterateLeft(distance: Int) = (1..distance).map { Point(x - it, y) }
public fun iterateRight(distance: Int) = (1..distance).map { Point(x + it, y) }
public fun iterateUp(distance: Int) = (1..distance).map { Point(x, y + it) }
public fun iterateDown(distance: Int) = (1..distance).map { Point(x, y - it) }
public fun manhattenDistance(p2: Point): Int =
Math.abs(x - p2.x) + Math.abs(y - p2.y)
}
data class Line(val start: Point, val end: Point) {
public fun hasPoint(p: Point): Boolean {
val minX = Math.min(start.x, end.x)
val maxX = Math.max(start.x, end.x)
val minY = Math.min(start.y, end.y)
val maxY = Math.max(start.y, end.y)
return p.x >= minX && p.x <= maxX && p.y >= minY && p.y <= maxY
}
public fun intersects(other: Line): Point? {
// Generate the intersection
val intersection = if (end.y == start.y) {
Point(other.start.x, start.y)
} else {
Point(start.x, other.start.y)
}
// Check if the intersection is on both lines
if (other.hasPoint(intersection) && hasPoint(intersection)) {
return intersection
} else {
return null
}
}
}
fun main(args: Array<String>) {
val inputFile = if (args.size < 1) {
System.err.println("Usage: adventofcode day03 <INPUT FILE>")
System.exit(1)
throw Exception("Whoop")
} else {
args[0]
}
val wires = File(inputFile).readLines().map(::parseItem)
// println("[Part 1] Wire #1 ${wires[0]}")
// println("[Part 1] Wire #2 ${wires[1]}")
val intersections = (wires[0] intersect wires[1]).filterNot { it.x == 0 && it.y == 0 }
val best = intersections.minBy {
println("[Part 1] Intersection at $it")
it.manhattenDistance(Point(0, 0))
}
if (best == null) {
println("[Part 1] No intersection found.")
} else {
val distance = best.manhattenDistance(Point(0, 0))
println("[Part 1] Closest intersection is $best (distance: $distance)")
}
// Now compute the best intersection by distance along the line
val bestBySteps = intersections.map {
// Add two to include the end points
Pair(it, wires[0].indexOf(it) + wires[1].indexOf(it) + 2)
}.minBy { it.second }
if (bestBySteps == null) {
println("[Part 2] No intersection found.")
} else {
println("[Part 2] Closest intersection is ${bestBySteps.first} (distance: ${bestBySteps.second})")
}
}
fun parseItem(line: String): List<Point> {
var prev = Point(0, 0)
return line.split(",").flatMap {
val start = prev
val distance = it.substring(1).toInt()
when (it[0]) {
'L' -> {
prev = start.moveLeft(distance)
start.iterateLeft(distance)
}
'R' -> {
prev = start.moveRight(distance)
start.iterateRight(distance)
}
'D' -> {
prev = start.moveDown(distance)
start.iterateDown(distance)
}
'U' -> {
prev = start.moveUp(distance)
start.iterateUp(distance)
}
else -> throw Exception("Invalid direction: ${it[0]}")
}
}
}
| 0 | Go | 0 | 2 | 006343d0c05d12556605cc4d2c2d47938ce09045 | 3,808 | advent-of-code | Apache License 2.0 |
src/year2022/day21/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2022.day21
import arrow.core.Either
import arrow.core.flatMap
import arrow.core.identity
import arrow.core.left
import arrow.core.right
import io.kotest.matchers.shouldBe
import utils.Identifier
import utils.Tree
import utils.asIdentifier
import utils.fold
import utils.readInput
fun main() {
val testInput = readInput("21", "test_input").parse().toTree()
val realInput = readInput("21", "input").parse().toTree()
testInput.fold { node, childrenValues: List<Long> ->
node.value.fold(
ifRight = ::identity,
ifLeft = childrenValues::reduce
)
}
.also(::println) shouldBe 152
realInput.fold { node, childrenValues: List<Long> ->
node.value.fold(
ifRight = ::identity,
ifLeft = childrenValues::reduce
)
}
.let(::println)
testInput.reduce()
.computeHumanValue()
.also(::println) shouldBe 301
realInput.reduce()
.computeHumanValue()
.let(::println)
}
private fun List<String>.parse(): Map<Identifier, Either<OperationDetails, Long>> {
return asSequence()
.map(parsingRegex::matchEntire)
.map { it!!.destructured }
.associate { (identifier, value, firstOperand, operation, secondOperand) ->
identifier.asIdentifier() to if (value.isEmpty()) OperationDetails(
firstOperand.asIdentifier(),
value = when (operation) {
"+" -> Operation.Addition
"-" -> Operation.Subtraction
"*" -> Operation.Multiplication
else -> Operation.Division
},
secondOperand.asIdentifier(),
).left() else value.toLong().right()
}
}
private data class OperationDetails(
val firstOperandIdentifier: Identifier,
val value: Operation,
val secondOperandIdentifier: Identifier,
)
private val parsingRegex = "([a-z]+): (?:(\\d+)|([a-z]+) ([-+*/]) ([a-z]+))".toRegex()
private fun Map<Identifier, Either<OperationDetails, Long>>.toTree(nodeIdentifier: Identifier = Identifier("root")): Tree<Node> {
return getValue(nodeIdentifier).fold(
ifRight = {
Tree(
nodeValue = Node(nodeIdentifier, it.right()),
children = emptyList()
)
},
ifLeft = {
Tree(
nodeValue = Node(nodeIdentifier, it.value.left()),
children = listOf(
toTree(it.firstOperandIdentifier),
toTree(it.secondOperandIdentifier),
)
)
}
)
}
private data class Node(
val identifier: Identifier,
val value: Either<Operation, Long>,
)
private fun Tree<Node>.reduce() = fold { node, childrenValues: List<Tree<Node>> ->
node.value.fold(
ifRight = { Tree(node, childrenValues) },
ifLeft = { operation ->
childrenValues.takeIf { children -> children.none { it.nodeValue.identifier == Identifier("humn") } }
?.asSequence()
?.map { it.nodeValue.value }
?.reduce { first, second ->
first.flatMap { firstOperand ->
second.map { secondOperand -> operation(firstOperand, secondOperand) }
}
}
?.fold(
ifRight = { Tree(Node(node.identifier, it.right()), emptyList()) },
ifLeft = { Tree(node, childrenValues) }
)
?: Tree(node, childrenValues)
}
)
}
private fun Tree<Node>.computeHumanValue(): Long {
return generateSequence(
seedFunction = {
val result = children.firstNotNullOf { it.nodeValue.value as? Either.Right }.value
val formula = children.first { it.nodeValue.value is Either.Left }
result to formula
},
nextFunction = { (result, formula) ->
if (formula.nodeValue.identifier == Identifier("humn")) null
else {
val (firstOperand, secondOperand) = formula.children
val operation = formula.nodeValue.value.let { it as Either.Left<Operation> }.value
if (firstOperand.nodeValue.identifier == Identifier("humn")
|| firstOperand.nodeValue.value is Either.Left<Operation>
) with(operation) {
check(secondOperand.nodeValue.value is Either.Right<Long>)
result.resultsOfOperatingWith(secondOperand.nodeValue.value.value) to firstOperand
} else with(operation) {
check(firstOperand.nodeValue.value is Either.Right<Long>)
result.resultsOfOperatingOn(firstOperand.nodeValue.value.value) to secondOperand
}
}
}
)
.last()
.first
}
private sealed interface Operation : (Long, Long) -> Long {
fun Long.resultsOfOperatingOn(a: Long): Long // R = a + x
fun Long.resultsOfOperatingWith(b: Long): Long // R = x + b
object Addition : Operation {
override fun invoke(a: Long, b: Long) = a + b
override fun Long.resultsOfOperatingOn(a: Long) = minus(a)
override fun Long.resultsOfOperatingWith(b: Long) = minus(b)
}
object Subtraction : Operation {
override fun invoke(a: Long, b: Long) = a - b
override fun Long.resultsOfOperatingOn(a: Long) = a - this
override fun Long.resultsOfOperatingWith(b: Long) = plus(b)
}
object Multiplication : Operation {
override fun invoke(a: Long, b: Long) = a * b
override fun Long.resultsOfOperatingOn(a: Long) = div(a)
override fun Long.resultsOfOperatingWith(b: Long) = div(b)
}
object Division : Operation {
override fun invoke(a: Long, b: Long) = a / b
override fun Long.resultsOfOperatingOn(a: Long) = a / this
override fun Long.resultsOfOperatingWith(b: Long) = times(b)
}
}
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 6,038 | Advent-of-Code | Apache License 2.0 |
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/leetcode/medium/939_MinimumAreaRectangle.kt | aquatir | 76,377,920 | false | {"Java": 674809, "Python": 143889, "Kotlin": 112192, "Haskell": 57852, "Elixir": 33284, "TeX": 20611, "Scala": 17065, "Dockerfile": 6314, "HTML": 4714, "Shell": 387, "Batchfile": 316, "Erlang": 269, "CSS": 97} | package com.codesample.leetcode.medium
/**
* 939. Minimum Area Rectangle https://leetcode.com/problems/minimum-area-rectangle/
*
* Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides
* parallel to the x and y axes. If there isn't any rectangle, return 0.
*
* Example 1:
* Input: [[1,1],[1,3],[3,1],[3,3],[2,2]]
* Output: 4
* Example 2:
*
* Input: [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
* Output: 2
*
* Note:
* 1 <= points.length <= 500
* 0 <= points[i][0] <= 40000
* 0 <= points[i][1] <= 40000
* All points are distinct.
*/
fun minAreaRect(points: Array<IntArray>): Int {
val lookupSet = mutableSetOf<Pair<Int, Int>>() // save all points we seen in set
var curMin = Integer.MAX_VALUE
for ( (x1, y1) in points) { // for each point let's try other point for rectangle in lookupSet
for ( (x2, y2) in lookupSet) { // iterate over lookup set
if (x1 == x2 && y1 == y2) { // do nothing if we found the same point in lookup set on this iteration
continue
}
if (Pair(x1, y2) in lookupSet) { // for all other points -> try to see if we have a rectangle
if (Pair(x2, y1) in lookupSet) {
// it only works if all points are DISTINCT which is true for this task
curMin = Math.min(curMin, Math.abs(x2-x1) * Math.abs(y2-y1))
}
}
}
lookupSet.add(Pair(x1, y1)) // !!! don't forget to add element into lookup set
}
return if (curMin == Integer.MAX_VALUE) 0 else curMin
}
fun main() {
println(minAreaRect(arrayOf(
intArrayOf(1,1),
intArrayOf(1,3),
intArrayOf(3,1),
intArrayOf(3,3),
intArrayOf(4,1),
intArrayOf(4,3),
)))
// (0,0), (0,1), (0,1), (1,0), (1,1)
println(minAreaRect(arrayOf(
intArrayOf(0,0),
intArrayOf(0,1),
intArrayOf(0,1),
intArrayOf(1,0),
intArrayOf(1,1),
)))
}
| 1 | Java | 3 | 6 | eac3328ecd1c434b1e9aae2cdbec05a44fad4430 | 2,035 | code-samples | MIT License |
src/Day05.kt | jaldhar | 573,188,501 | false | {"Kotlin": 14191} |
import kotlin.collections.first
import kotlin.collections.removeFirst
class Stacks {
val stacks = mutableMapOf<Int, MutableList<Char>>()
fun readDiagram(line: String) {
val matches = """\[(\p{Upper})\]""".toRegex().findAll(line)
for (match in matches) {
val index = (match.range.first / 4) + 1
if (stacks[index] == null) {
stacks[index] = mutableListOf<Char>()
}
stacks[index]!!.add(match.value.get(1))
}
}
fun move(line: String) {
val matches = """move (\d+) from (\d+) to (\d+)""".toRegex().find(line)
val (quantity, from, to) = matches!!.destructured
for (i in 0 until quantity.toInt()) {
stacks[to.toInt()]!!.add(0, stacks[from.toInt()]!!.removeFirst())
}
}
fun moveAll(line: String) {
val matches = """move (\d+) from (\d+) to (\d+)""".toRegex().find(line)
val (quantity, from, to) = matches!!.destructured
val moving: List<Char> = stacks[from.toInt()]!!.take(quantity.toInt())
stacks[to.toInt()]!!.addAll(0, moving)
stacks[from.toInt()]!!.subList(0, quantity.toInt()).clear()
}
fun dump() {
for (key in stacks.keys.toList().sorted()) {
println("${key} ${stacks.get(key)!!.joinToString()}")
}
}
fun top(): String {
return stacks.keys.toList().sorted().map({ stacks[it]!!.first() }).joinToString("")
}
}
fun main() {
fun part1(input: List<String>): String {
val stacks = Stacks()
var task = stacks::readDiagram
for (line in input) {
if (line.isEmpty()) {
task = stacks::move
continue
}
task(line);
}
return stacks.top()
}
fun part2(input: List<String>): String {
val stacks = Stacks()
var task = stacks::readDiagram
for (line in input) {
if (line.isEmpty()) {
task = stacks::moveAll
continue
}
task(line);
}
return stacks.top()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b193df75071022cfb5e7172cc044dd6cff0f6fdf | 2,446 | aoc2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2023/Day07.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 7 - Camel Cards
* Problem Description: http://adventofcode.com/2023/day/7
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day7/
*/
package com.ginsberg.advent2023
class Day07(private val input: List<String>) {
fun solvePart1(): Int =
playCamelCards()
fun solvePart2(): Int =
playCamelCards(true)
private fun playCamelCards(jokersWild: Boolean = false): Int =
input
.asSequence()
.map { row -> row.split(" ") }
.map { parts -> Hand(parts.first(), parts.last().toInt(), jokersWild) }
.sorted()
.mapIndexed { index, hand -> hand.bid * (index + 1) }
.sum()
private class Hand(cards: String, val bid: Int, jokersWild: Boolean) : Comparable<Hand> {
private val identity: Int = calculateIdentity(
cards,
if (jokersWild) STRENGTH_WITH_JOKERS else STRENGTH_WITHOUT_JOKERS,
if (jokersWild) this::calculateCategoryWithJokers else this::calculateCategoryWithoutJokers
)
private fun calculateIdentity(
cards: String,
strength: String,
categoryCalculation: (String) -> List<Int>
): Int {
val category = categoryCalculation(cards)
return cards.fold(CATEGORIES.indexOf(category)) { acc, card ->
(acc shl 4) or strength.indexOf(card)
}
}
private fun calculateCategoryWithoutJokers(cards: String): List<Int> =
cards.groupingBy { it }.eachCount().values.sortedDescending()
private fun calculateCategoryWithJokers(cards: String): List<Int> {
val cardsWithoutJokers = cards.filterNot { it == 'J' }
val numberOfJokers = cards.length - cardsWithoutJokers.length
return if (numberOfJokers == 5) listOf(5)
else calculateCategoryWithoutJokers(cardsWithoutJokers).toMutableList().apply {
this[0] += numberOfJokers
}
}
override fun compareTo(other: Hand): Int =
this.identity - other.identity
companion object {
private val CATEGORIES = listOf(
listOf(1, 1, 1, 1, 1),
listOf(2, 1, 1, 1),
listOf(2, 2, 1),
listOf(3, 1, 1),
listOf(3, 2),
listOf(4, 1),
listOf(5)
)
private const val STRENGTH_WITHOUT_JOKERS = "23456789TJQKA"
private const val STRENGTH_WITH_JOKERS = "J23456789TQKA"
}
}
}
| 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 2,666 | advent-2023-kotlin | Apache License 2.0 |
kotlin/src/x2022/day7/Day7.kt | freeformz | 573,924,591 | false | {"Kotlin": 43093, "Go": 7781} | package day7
import readInput
data class File(val name: String, val size: Int)
data class Dir(
val name: String,
val parent: Dir? = null,
val children: MutableMap<String, Dir>,
val files: MutableList<File>
) {
fun size(): Int {
return files.sumOf { it.size } + children.values.sumOf { it.size() }
}
fun childrenAtMost(size: Int): List<Dir> {
return children.values.filter { c ->
c.size() <= size
} + children.values.flatMap { c ->
c.childrenAtMost(size)
}
}
fun childrenAtLeast(size: Int): List<Dir> {
return children.values.filter { c ->
c.size() >= size
} + children.values.flatMap { c ->
c.childrenAtLeast(size)
}
}
}
fun main() {
fun parseInput(input: List<String>): Dir {
val root = Dir("/", null, mutableMapOf(), mutableListOf())
var cwd = root
input.forEach { line ->
val parts = line.split(" ")
when (parts[0]) {
"$" -> when (parts[1]) {
"cd" -> {
when (parts[2]) {
"/" -> cwd = root
".." -> cwd = cwd.parent!!
else -> {
cwd = cwd.children.getOrElse(parts[2]) {
throw Exception("cd dir (" + parts[2] + ") before dir")
}
}
}
}
"ls" -> {
}
else -> throw Exception("invalid input")
}
"dir" -> {
if (!cwd.children.containsKey(parts[1])) {
cwd.children[parts[1]] = Dir(parts[1], cwd, mutableMapOf(), mutableListOf())
}
}
else -> { // file case
check(parts.count() == 2)
cwd.files.add(File(parts[1], parts[0].toInt()))
}
}
}
return root
}
fun partOne(input: List<String>) {
println(parseInput(input).childrenAtMost(100000).sumOf { it.size() })
}
val max = 70000000 - 30000000
fun partTwo(input: List<String>) {
val dirs = parseInput(input)
val totalSize = dirs.size()
val diff = totalSize - max
println(dirs.childrenAtLeast(diff).sortedBy { it.size() }.first().size())
}
println("partOne test")
partOne(readInput("day7.test"))
println()
println("partOne")
partOne(readInput("day7"))
println()
println("partTwo test")
partTwo(readInput("day7.test"))
println()
println("partTwo")
partTwo(readInput("day7"))
} | 0 | Kotlin | 0 | 0 | 5110fe86387d9323eeb40abd6798ae98e65ab240 | 2,816 | adventOfCode | Apache License 2.0 |
kotlin/src/main/kotlin/year2023/Day13.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
fun main() {
val input = readInput2("Day13")
Day13.part1(input).println()
Day13.part2(input).println()
}
object Day13 {
fun part1(input: String): Int {
val inputChunks = input.split(DOUBLE_NEW_LINE_REGEX)
return inputChunks
.map { it.split(NEW_LINE_REGEX) }
.sumOf {
val horizontal = it.horizontalReflection()
val vertical = it.verticalReflection()
if (horizontal != -1) (horizontal + 1) * 100 else (vertical + 1)
}
}
fun part2(input: String): Int {
val inputChunks = input.split(DOUBLE_NEW_LINE_REGEX)
return inputChunks
.map { it.split(NEW_LINE_REGEX) }
.sumOf {
val horizontal = it.horizontalReflection(smudgesDesired = 1)
val vertical = it.verticalReflection(smudgesDesired = 1)
if (horizontal != -1) (horizontal + 1) * 100 else (vertical + 1)
}
}
private fun List<String>.horizontalReflection(smudgesDesired: Int = 0): Int {
for (row in 0 until this.size - 1) {
if (hasHorizontalReflectionIn(row, smudgesDesired)) {
return row
}
}
return -1
}
private fun List<String>.hasHorizontalReflectionIn(row: Int, smudgesDesired: Int): Boolean {
var left = row
var right = row + 1
var smudges = 0
while (left >= 0 && right < this.size) {
smudges += this[left].countDifferentChars(this[right])
left--
right++
}
return smudges == smudgesDesired
}
private fun String.countDifferentChars(other: String): Int {
assert(this.length == other.length) { "It should have the same size" }
var count = 0
for (i in this.indices) {
if (this[i] != other[i]) {
count++
}
}
return count
}
private fun List<String>.verticalReflection(smudgesDesired: Int = 0): Int {
for (column in 0 until this[0].length - 1) {
if (hasVerticalReflectionIn(column, smudgesDesired)) {
return column
}
}
return -1
}
private fun List<String>.hasVerticalReflectionIn(column: Int, smudgesDesired: Int): Boolean {
var top = column
var down = column + 1
var smudges = 0
while (top >= 0 && down < this[0].length) {
val topBuilder = StringBuilder()
val downBuilder = StringBuilder()
for (row in this.indices) {
topBuilder.append(this[row][top])
downBuilder.append(this[row][down])
}
smudges += topBuilder.toString().countDifferentChars(downBuilder.toString())
top--
down++
}
return smudges == smudgesDesired
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 2,926 | advent-of-code | MIT License |
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day12Test.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
import java.io.File
import java.util.*
private fun solution1(input: String) = Grid(input).let { it.shortest(sequenceOf(it.start)) }
private fun solution2(input: String) = Grid(input).let { it.shortest(it.vertices { c -> c == 'a' }) }
private class Grid(input: String) {
private val infinity = 100000000
private val cells = input.filter { it != '\n' }.toCharArray()
private val height = input.lineSequence().count()
private val width = cells.size / height
val start = cells.indexOf('S')
private val end = cells.indexOf('E')
init {
cells[start] = 'a'
cells[end] = 'z'
}
fun vertices(predicate: (Char) -> Boolean) = cells.indices.asSequence().filter { predicate(cells[it]) }
fun shortest(starts: Sequence<Int>): Int {
val dist = mutableMapOf<Int, Int>()
val prev = mutableMapOf<Int, Int>()
val q = PriorityQueue<Int> { o1, o2 -> dist.getValue(o1).compareTo(dist.getValue(o2)) }
cells.indices.forEach { dist[it] = infinity }
starts.forEach { v -> dist[v] = 0 }
q.addAll(starts)
while (q.isNotEmpty()) {
val u = q.poll()
if (u == end || dist[u] == infinity) break
neighbors(u).forEach { v ->
val alt = dist.getValue(u) + 1
if (alt < dist.getValue(v)) {
dist[v] = alt
prev[v] = u
q.add(v)
}
}
}
return dist.getValue(end)
}
private fun neighbors(index: Int) = sequence {
if (index % width > 0) yield(index - 1)
if (index % width < width - 1) yield(index + 1)
if (index + width < cells.size) yield(index + width)
if (index >= width) yield(index - width)
}.filter { cells[it] - cells[index] <= 1 }
}
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 12
class Day12Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 31 }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 380 }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 29 }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 375 }
})
private val exampleInput =
"""
Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi
""".trimIndent()
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 2,690 | adventofcode-kotlin | MIT License |
src/questions/LargestDivisibleSubset.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBeOneOf
/**
* Given a set of distinct positive integers nums, return the largest subset answer
* such that every pair (`answer[i]`, `answer[j]`) of elements in this subset satisfies:
*
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
* If there are multiple solutions, return any of them.
*
* [Source](https://leetcode.com/problems/largest-divisible-subset/)
*
* @see LongestIncreasingSubSeq
*
* @see LengthOfLongestIncreasingSubSeq
*/
@UseCommentAsDocumentation
private fun largestDivisibleSubset(nums: IntArray): List<Int> {
if (nums.size == 1) return nums.toList()
nums.sort()
var indexOfLargestSubsequence = 0
val sizes = IntArray(nums.size) { 1 }
for (i in 1..nums.lastIndex) {
for (j in 0 until i) {
if (nums[i] % nums[j] == 0 && sizes[i] <= sizes[j]) {
sizes[i] = 1 + sizes[j]
}
}
if (sizes[indexOfLargestSubsequence] < sizes[i]) {
indexOfLargestSubsequence = i
}
}
val totalSize = sizes[indexOfLargestSubsequence]
val result = IntArray(totalSize) { -1 }
var current = totalSize
for (i in result.lastIndex downTo 0) {
for (j in sizes.lastIndex downTo 0) {
val rightElementInSubset = result.getOrNull(i + 1)
// [2,3,4,8] ---- LIS ---> [1,1,2,3] so need to check once again
val shouldBeInSubset = if (rightElementInSubset == null) true else rightElementInSubset % nums[j] == 0
if (sizes[j] == current && shouldBeInSubset) {
result[i] = nums[j]
current--
break
}
}
}
return result.toList()
}
fun main() {
largestDivisibleSubset(intArrayOf(2, 3, 4, 8)) shouldBeOneOf listOf(listOf(2, 4, 8))
largestDivisibleSubset(intArrayOf(1, 2, 4, 8, 9, 72)) shouldBeOneOf listOf(listOf(1, 2, 4, 8, 72))
largestDivisibleSubset(intArrayOf(3, 4, 16, 8)) shouldBeOneOf listOf(listOf(4, 8, 16))
largestDivisibleSubset(intArrayOf(4, 8, 10, 240)) shouldBeOneOf listOf(listOf(4, 8, 240))
largestDivisibleSubset(intArrayOf(1, 2, 3)) shouldBeOneOf listOf(listOf(1, 2), listOf(1, 3))
largestDivisibleSubset(intArrayOf(1, 2, 3, 6, 9, 12)) shouldBeOneOf
listOf(listOf(1, 3, 6, 12), listOf(1, 2, 6, 12))
largestDivisibleSubset(intArrayOf(9, 75, 12, 18, 90, 4, 36, 8, 28, 2)) shouldBeOneOf
listOf(listOf(2, 4, 12, 36))
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,516 | algorithms | MIT License |
src/main/kotlin/adventofcode2022/solution/day_7.kt | dangerground | 579,293,233 | false | {"Kotlin": 51472} | package adventofcode2022.solution
import adventofcode2022.util.readDay
import java.util.Objects
fun main() {
Day7("7").solve()
}
class Day7(private val num: String) {
private val inputText = readDay(num)
private val startNumeric = Regex("^\\d+.*$")
fun solve() {
println("Day $num Solution")
println("* Part 1: ${solution1()}")
println("* Part 2: ${solution2()}")
}
fun solution1(): Long {
val (root, dirs) = checkDirectorySizes()
return dirs.filter { it.size() <= 100000 }.sumOf { it.size() }
}
private fun checkDirectorySizes(): Pair<Element, MutableList<Element>> {
val dirs = mutableListOf<Element>()
val root = Element(
name = "",
path = "/",
parent = null,
children = mutableSetOf()
)
var currentDir = root
inputText.lines().drop(1).forEach {
when {
it.startsWith("\$ cd") -> {
val name = it.substring(5)
if (name == "..") {
currentDir = currentDir.parent!!
} else {
currentDir =
currentDir.children.find { it.name == name || (name == "/" && it.parent == null) }!!
}
//println("change to: $currentPath")
}
it.startsWith("\$ ls") -> {
//println("list")
}
it.startsWith("dir ") -> {
val name = it.substring(4)
//println("detect dir: $name")
val el = Element(
name = name,
path = elementInPath(currentDir.path, name),
parent = currentDir,
)
currentDir.add(el)
dirs.add(el)
}
it.matches(startNumeric) -> {
val name = it.substringAfter(' ')
val size = it.substringBefore(' ').toLong()
//println("detect dir: ${dirs[currentPath]!!}")
currentDir.add(
Element(
name = name,
path = elementInPath(currentDir.path, name),
parent = currentDir,
size = size,
)
)
}
else -> println("unknwon $it (${it.matches(startNumeric)})")
}
}
return Pair(root, dirs)
}
private fun elementInPath(currentPath: String, name: String): String {
return currentPath.trimEnd('/') + '/' + name.trim('/')
}
fun solution2(): Long {
val totalSpace = 70000000
val requiredSpace = 30000000
val (root, dirs) = checkDirectorySizes()
val usedSpace = (totalSpace - root.size())
val toDeleteSpace = requiredSpace - usedSpace
println("used $usedSpace :: missing $toDeleteSpace")
return dirs.filter { it.size() > toDeleteSpace }
.minByOrNull { it.size() }!!
.size()
}
}
data class Element(
val name: String,
val path: String,
val parent: Element?,
val children: MutableSet<Element> = mutableSetOf(),
val size: Long = 0,
) {
fun size(): Long {
return (children.sumOf { it.size() } ?: 0L) + size
}
fun add(el: Element) {
children.add(el)
}
override fun equals(other: Any?): Boolean {
return Objects.equals(this, other)
}
override fun hashCode(): Int {
return Objects.hash(path, name)
}
override fun toString() = if (size == 0L) {
"dir $name:\n'$children'\n"
} else {
"file (name=$name; size=$size)\n"
}
}
| 0 | Kotlin | 0 | 0 | f1094ba3ead165adaadce6cffd5f3e78d6505724 | 3,899 | adventofcode-2022 | MIT License |
src/main/kotlin/Day12.kt | dliszewski | 573,836,961 | false | {"Kotlin": 57757} | import java.util.*
class Day12 {
fun part1(input: List<String>): Int {
val area = mapToArea(input)
return area.traverseFromStart()
}
fun part2(input: List<String>): Int {
return mapToArea(input).traverseFromEnd()
}
private fun mapToArea(input: List<String>): Area {
var finishPoint: Point? = null
var startingPoint: Point? = null
val field: Map<Point, Int> = input.flatMapIndexed { y, row ->
row.mapIndexed { x, heightCode ->
val point = Point(x, y)
val height = heightCode.decodeHeight()
when (heightCode) {
'E' -> point to height.also { finishPoint = point }
'S' -> point to height.also { startingPoint = point }
else -> point to height
}
}
}.toMap()
return Area(startingPoint!!, finishPoint!!, field)
}
private fun Char.decodeHeight(): Int {
return when (this) {
'S' -> 'a' - 'a'
'E' -> 'z' - 'a'
in 'a'..'z' -> this - 'a'
else -> error("Wrong level value $this")
}
}
data class Area(
val startingPoint: Point,
val destination: Point,
val field: Map<Point, Int>
) {
fun traverseFromStart(): Int {
val canMove: (Int, Int) -> Boolean = { nextPlace, currentPlace -> nextPlace - currentPlace <= 1 }
val isDestination: (Path) -> Boolean = { it.point == destination }
return traverse(canMove, isDestination, startingPoint)
}
fun traverseFromEnd(): Int {
val canMove: (Int, Int) -> Boolean = { nextPlace, currentPlace -> currentPlace - nextPlace <= 1 }
val isDestination: (Path) -> Boolean = { field[it.point] == 0 }
return traverse(canMove, isDestination, destination)
}
private fun traverse(
canMove: (Int, Int) -> Boolean,
isDestination: (Path) -> Boolean,
startingPoint: Point
): Int {
val toBeEvaluated = PriorityQueue<Path>().apply { add(Path(startingPoint, 0)) }
val visited = mutableSetOf<Point>()
while (toBeEvaluated.isNotEmpty()) {
val currentPlace = toBeEvaluated.poll()
if (isDestination(currentPlace)) {
return currentPlace.distanceSoFar
}
if (currentPlace.point !in visited) {
visited.add(currentPlace.point)
currentPlace.point
.neighbors()
.filter { nextPlace -> nextPlace in field }
.filter { nextPlace -> canMove(field.getValue(nextPlace), field.getValue(currentPlace.point)) }
.map { nextPlace -> Path(nextPlace, currentPlace.distanceSoFar + 1) }
.forEach { path -> toBeEvaluated.offer(path) }
}
}
error("No path found to destination")
}
}
data class Path(val point: Point, val distanceSoFar: Int) : Comparable<Path> {
override fun compareTo(other: Path): Int {
return distanceSoFar - other.distanceSoFar
}
}
data class Point(val x: Int, val y: Int) {
fun neighbors(): List<Point> {
return listOf(
Point(x, y + 1),
Point(x, y - 1),
Point(x + 1, y),
Point(x - 1, y)
)
}
}
}
| 0 | Kotlin | 0 | 0 | 76d5eea8ff0c96392f49f450660220c07a264671 | 3,584 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/d7/d7.kt | LaurentJeanpierre1 | 573,454,829 | false | {"Kotlin": 118105} | package d7
import readInput
data class File(val name: String, val content: MutableMap<String, File>, var size: Int) {
var parent: File? = null
constructor(name: String, content: MutableMap<String, File>, size: Int, parent: File?) : this(name, content, size) {
this.parent = parent
}
fun print(prefix: String) {
if (content.isEmpty()) println( "${prefix}${size} $name")
else {
println("${prefix}${name}:")
content.forEach{ (_, v) ->v.print("$prefix ")}
}
}
}
fun part1(input: List<String>): Int {
val root = parseFileSystem(input)
root.print("")
globalSum = 0
sizeLess100000(root)
return globalSum
}
private fun parseFileSystem(input: List<String>): File {
val root = File("/", mutableMapOf(), 0, null)
var curDir = root
var curDirTemp = curDir
for (line in input) if (line.isNotEmpty()) {
val words = line.split(" ")
if (words[0] == "$") {
val newDir = if (words.size > 2) words[2] else ""
when (words[1]) {
"cd" -> when (newDir) {
"/" -> curDir = root
".." -> curDir = curDir.parent ?: root
"." -> {}//curDir = curDir
else -> {
if (newDir !in curDir.content)
curDir.content[newDir] = File(newDir, mutableMapOf(), 0, curDir)
curDir = curDir.content[newDir]!!
}
}
"ls" -> if (words.size > 2) {
if (newDir !in curDir.content)
curDir.content[newDir] = File(newDir, mutableMapOf(), 0, curDir)
curDirTemp = curDir.content[newDir]!!
} else
curDirTemp = curDir
}
} else {
// this is a file
val name = words[1]
if (words[0] == "dir") {
if (name !in curDir.content)
curDirTemp.content[name] = File(name, mutableMapOf(), 0, curDirTemp)
} else {
curDirTemp.content[name] = File(name, mutableMapOf(), words[0].toInt(), curDirTemp)
}
}
}
return root
}
var globalSum = 0
fun sizeLess100000(root: File): Int {
val sum = root.size + root.content.map { (_,v)-> sizeLess100000(v) }.sum()
if ((sum < 100000) && root.content.isNotEmpty()) {
globalSum += sum
//print("+")
}
//println("debug: ${root.name} -> ${sum}")
return sum
}
fun part2(input: List<String>): Int {
val root = parseFileSystem(input)
globalSum = 0
val totalSize = sizeLess100000(root)
val requireSize = 30000000 - (70000000 - totalSize)
return smallestMoreThan(requireSize, 30000001, root)
}
fun smallestMoreThan(requireSize: Int, curMin: Int, root: File): Int {
var min = curMin
root.content.forEach{(_,v)->
val size = smallestMoreThan(requireSize, min, v)
if (size in (requireSize + 1) until min)
min = size
}
if (root.content.isNotEmpty()) {
val size = sizeLess100000(root)
if (size in (requireSize + 1) until min)
min = size
}
return min
}
fun main() {
//val input = readInput("d7/test")
val input = readInput("d7/input1")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5cf6b2142df6082ddd7d94f2dbde037f1fe0508f | 3,409 | aoc2022 | Creative Commons Zero v1.0 Universal |
src/Day02.kt | tomoki1207 | 572,815,543 | false | {"Kotlin": 28654} | import Result.*
import Sign.*
sealed class Result(val score: Int) {
object Win : Result(6)
object Draw : Result(3)
object Lose : Result(0)
}
sealed class Sign(val score: Int) {
abstract fun vs(sign: Sign): Result
abstract fun simulate(result: Result): Sign
object Rock : Sign(1) {
override fun vs(sign: Sign) = when (sign) {
is Rock -> Draw
is Paper -> Lose
is Scissors -> Win
}
override fun simulate(result: Result) = when (result) {
is Draw -> Rock
is Lose -> Scissors
is Win -> Paper
}
}
object Paper : Sign(2) {
override fun vs(sign: Sign) = when (sign) {
is Rock -> Win
is Paper -> Draw
is Scissors -> Lose
}
override fun simulate(result: Result) = when (result) {
is Draw -> Paper
is Lose -> Rock
is Win -> Scissors
}
}
object Scissors : Sign(3) {
override fun vs(sign: Sign) = when (sign) {
is Rock -> Lose
is Paper -> Win
is Scissors -> Draw
}
override fun simulate(result: Result) = when (result) {
is Draw -> Scissors
is Lose -> Paper
is Win -> Rock
}
}
}
fun main() {
fun part1(input: List<String>): Int {
fun toSign(sign: String): Sign = when (sign) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> throw Error("Not supported sign [$sign]")
}
return input.map { line ->
val pair = line.split(" ")
toSign(pair.first()) to toSign(pair.last())
}.sumOf { pair ->
val opponent = pair.first
val yours = pair.second
yours.score + yours.vs(opponent).score
}
}
fun part2(input: List<String>): Int {
fun toSign(sign: String): Sign = when (sign) {
"A" -> Rock
"B" -> Paper
"C" -> Scissors
else -> throw Error("Not supported sign [$sign]")
}
fun toResult(sign: String): Result = when (sign) {
"X" -> Lose
"Y" -> Draw
"Z" -> Win
else -> throw Error("Not supported sign [$sign]")
}
return input.map { line ->
val pair = line.split(" ")
toSign(pair.first()) to toResult(pair.last())
}.sumOf { pair ->
val opponent = pair.first
val result = pair.second
val yours = opponent.simulate(result)
yours.score + result.score
}
}
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 | 2ecd45f48d9d2504874f7ff40d7c21975bc074ec | 2,896 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day10.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
import kotlin.math.absoluteValue
fun main() {
val grid = readInput(2023, 10, false).readLines()
val sIndex = findS(grid)
val next = findNext(sIndex.x, sIndex.y, grid)
val path = buildPath(sIndex, next, grid)
part1(path)
part2(grid, path)
}
private fun part1(path: List<Index>) {
println(path.size / 2)
}
private fun part2(grid: List<String>, path: List<Index>) {
val pathSet = path.toSet()
var count = 0
for (j in grid.indices) {
val row = grid[j]
for (i in row.indices) {
val cell = Index(i, j)
if (cell !in pathSet && cell.isInPath(pathSet, grid)) count++
}
}
println(count)
}
private fun part2alternative(path: List<Index>) {
val perimeter = path.size
// Shoelace method: https://en.wikipedia.org/wiki/Shoelace_formula
val area = path.zip(path.drop(1) + path.take(1)) { a, b -> a.x * b.y - a.y * b.x }.sum().absoluteValue / 2
// Picks theorem: https://en.wikipedia.org/wiki/Pick's_theorem
val points = area - perimeter / 2 + 1
println(points)
}
private fun buildPath(start: Index, next: Index, grid: List<String>): List<Index> {
return buildList {
add(start)
var prev = start
var cur = next
while (cur != start) {
add(cur)
val forward = when (grid[cur.y][cur.x]) {
'7' -> if (prev.y == cur.y) Index(cur.x, cur.y + 1) else Index(cur.x - 1, cur.y)
'|' -> if (prev.y == cur.y-1) Index(cur.x, cur.y + 1) else Index(cur.x, cur.y-1)
'J' -> if (prev.y == cur.y-1) Index(cur.x - 1, cur.y) else Index(cur.x, cur.y-1)
'-' -> if (prev.x == cur.x-1) Index(cur.x + 1, cur.y) else Index(cur.x-1, cur.y)
'L' -> if (prev.y == cur.y-1) Index(cur.x+1, cur.y) else Index(cur.x, cur.y-1)
'F' -> if (prev.y == cur.y+1) Index(cur.x + 1, cur.y) else Index(cur.x, cur.y+1)
else -> error("Invalid path. Should never happen")
}
prev = cur
cur = forward
}
}
}
private fun findS(grid: List<String>): Index {
for (y in grid.indices) {
val line = grid[y]
for (x in line.indices) if (line[x] == 'S') return Index(x, y)
}
error("S not found")
}
private fun findNext(x: Int, y: Int, grid: List<String>): Index {
val dx = intArrayOf(0, 1, 0, -1)
val dy = intArrayOf(-1, 0, 1, 0)
val dc = arrayOf(
charArrayOf('7', '|', 'F'),
charArrayOf('J', '-', '7'),
charArrayOf('J', '|', 'L'),
charArrayOf('L', '-', 'F')
)
for (i in dx.indices) {
val index = Index(x + dx[i], y + dy[i])
val cell = grid.getOrNull(index.y)?.getOrNull(index.x) ?: continue
if (cell in dc[i]) return index
}
error("Next not found")
}
private fun Index.isInPath(path: Set<Index>, grid: List<String>): Boolean {
// Ray casting: https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm
val hits = (0..<x).count { Index(it, y) in path && grid[y][it] !in setOf('J', 'L', '-') }
return hits % 2 != 0
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 3,214 | adventofcode | Apache License 2.0 |
src/main/day4/Day04.kt | Derek52 | 572,850,008 | false | {"Kotlin": 22102} | package main.day4
import main.readInput
fun main() {
val input = readInput("day4/day4")
val firstHalf = true
testAlg(firstHalf)
if (firstHalf) {
println(part1(input))
} else {
println(part2(input))
}
}
data class Range(val x:Int, val y:Int)
fun rangeInRange(left: Range, right: Range) : Boolean {
return (left.x <= right.x && left.y >= right.y) || (right.x <= left.x && right.y >= left.y)
}
fun rangeOverlapsRange(left: Range, right: Range) : Boolean{
return (right.x >= left.x && right.x <= left.y) || (right.y >= left.x && right.y <= left.y) ||
(left.x >= right.x && left.x <= right.y) || (left.y >= right.x && left.y <= right.y)
}
fun part1(input: List<String>) : Int{
var overlapCount = 0
for (line in input) {
val assignments = line.split(',')
val elf1 = Assignment(assignments[0])
val elf2 = Assignment(assignments[1])
var overlap = if (elf1.range.x <= elf2.range.x) {
rangeInRange(elf1.range, elf2.range)
} else {
rangeInRange(elf2.range, elf1.range)
}
if (overlap) {
overlapCount++
}
}
return overlapCount
}
fun part2(input: List<String>) : Int {
var overlapCount = 0
for (line in input) {
val assignments = line.split(',')
val elf1 = Assignment(assignments[0])
val elf2 = Assignment(assignments[1])
if (rangeOverlapsRange(elf1.range, elf2.range)) {
overlapCount++
}
}
return overlapCount
}
data class Assignment(val assignment: String) {
var a: Int = 0
var b: Int = 0
var range = Range(0, 0)
init {
val boundaries = assignment.split("-")
a = boundaries[0].toInt()
b = boundaries[1].toInt()
range = Range(a, b)
}
}
fun testAlg(firstHalf : Boolean) {
val input = readInput("day4/day4_test")
if (firstHalf) {
println(part1(input))
} else {
println(part2(input))
}
} | 0 | Kotlin | 0 | 0 | c11d16f34589117f290e2b9e85f307665952ea76 | 2,016 | 2022AdventOfCodeKotlin | Apache License 2.0 |
src/main/kotlin/Day03.kt | akowal | 434,506,777 | false | {"Kotlin": 30540} | fun main() {
println(Day03.solvePart1())
println(Day03.solvePart2())
}
object Day03 {
private val input = readInput("day03")
private val nbits = input.first().length
fun solvePart1(): Int {
val gamma = (0 until nbits)
.map { pos -> input.count { bits -> bits[pos] == '1' } }
.fold(0) { acc, ones ->
var x = acc.shl(1)
if (ones > input.size / 2) {
x++
}
x
}
val epsilon = gamma.inv().and(1.shl(nbits) - 1)
return gamma * epsilon
}
fun solvePart2(): Int {
val o2GeneratorRating = calculateRating { zeros, ones -> zeros > ones }
val co2ScrubberRating = calculateRating { zeros, ones -> zeros <= ones }
return o2GeneratorRating * co2ScrubberRating
}
private fun calculateRating(selectZeros: (Int, Int) -> Boolean): Int {
var candidates = input
for (pos in 0 until nbits) {
val zeros = candidates.filter { it[pos] == '0' }
val ones = candidates.filter { it[pos] == '1' }
if (selectZeros(zeros.size, ones.size)) {
candidates = zeros
} else {
candidates = ones
}
if (candidates.size == 1) {
break
}
}
return candidates.single().toInt(2)
}
}
| 0 | Kotlin | 0 | 0 | 08d4a07db82d2b6bac90affb52c639d0857dacd7 | 1,416 | advent-of-kode-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/sk/topicWise/dp/5. Longest Palindromic Substring.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.topicWise.dp
class Solution5 {
private var start = 0
private var maxLen = 0
fun longestPalindrome(s: String): String {
val len = s.length
if (len < 2) return s
for (i in 0 until len - 1) {
extendPalindrome(s, i, i) //assume odd length, try to extend Palindrome as possible
extendPalindrome(s, i, i + 1) //assume even length.
}
return s.substring(start, start + maxLen)
}
private fun extendPalindrome(s: String, l: Int, r: Int) {
var l = l
var r = r
while (l >= 0 && r < s.length && s[l] == s[r]) {
l--
r++
}
if (maxLen < r - l - 1) {
start = l + 1
maxLen = r - l - 1
}
}
/**
* go to every index
* make current index as palindrome center and expand both side, mark max found
* make pre and current both as center, expand palindrome, mark max found
*/
fun longestPalindrome2(s: String): String {
var left = 0
var right = 0
for (i in s.indices) {
var l = i
var r = i
while (l >= 0 && r <= s.lastIndex && s[l] == s[r]) {
l--
r++
}
if (--r - ++l > right - left) {
left = l
right = r
}
if (i == 0) continue
l = i - 1
r = i
while (l >= 0 && r <= s.lastIndex && s[l] == s[r]) {
l--
r++
}
if (--r - ++l > right - left) {
left = l
right = r
}
}
return s.substring(left, right + 1)
}
// dp, bottom-up
// Time:O(n^2)
fun longestPalindrome3(str: String): String {
val table = Array(str.length) { BooleanArray(str.length) }
var max = 0
var start = 0 // beginning index of max palindrome
for (k in 1..str.length) { // size of palindrome
for (i in 0..str.length - k) { // start index
val j = i + k - 1
if (k == 1) { // single length palindrome
table[i][j] = true
} else if (k == 2) {
if (str[i] == str[j]) table[i][j] = true
} else { // for more than 3 length, we'll have middle elements
if (table[i + 1][j - 1] && str[i] == str[j]) table[i][j] = true
}
// we found new bigger palindrome
if (table[i][j] && k > max) {
max = k
start = i
}
// println("i$i, j=$j, k=$k table=${table[i][j]}, max=$max, start=$start")
}
}
return str.substring(start, start + max)
}
}
// Taken from comments of
// https://leetcode.com/problems/longest-palindromic-substring/solutions/151144/bottom-up-dp-two-pointers
class Solution5_2 {
/**
* If you do the brute force way you would generate a lot more strings than this method looks at.
* which is set of all subsets ( rather substrings) -
* E(sigma) (n-i) as i runs from 1 to n-1 = n-squared + n(n+1)/2 - O(n-squared) complexity.
* This problem can be done using DP with n-squared complexity as shown above by [@GraceMeng](https://leetcode.com/GraceMeng)
* with a few comments below by me based on that
*/
fun longestPalindrome(s: String?): String? {
if (s == null || s.length <= 1) return s
val len = s.length
// dp[i][j] stands for status of a substring starting at i and ending at j incl j
val dp = Array(len) { BooleanArray(len) }
// initialize all the 1 character palins
for (i in 0 until len) {
dp[i][i] = true
}
// to compute dp[i][j] we need dp[i+1][j-1]
// so the i - outer loop needs to go from higher to lower
// and the j - inner loop needs to go from lower to higher
var maxLen = 0
var maxSta = 0
var maxEnd = 0
for (i in len downTo 0) {
// dist of 0 - already covered by initialization
for (dist in 1 until len - i) {
val j = i + dist
// we are ready to compute dp [i] [j]
if (dist == 1 && s[i] == s[j]) {
dp[i][j] = true
} else if (s[i] == s[j]) {
dp[i][j] = dp[i + 1][j - 1]
}
// if true
if (dp[i][j] && maxLen < j - i + 1) {
maxLen = j - i + 1
maxSta = i
maxEnd = j
}
}
}
return s.substring(maxSta, maxEnd + 1)
}
} | 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 4,781 | leetcode-kotlin | Apache License 2.0 |
src/day7/Day07.kt | francoisadam | 573,453,961 | false | {"Kotlin": 20236} | package day7
import readInput
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.div
fun main() {
fun part1(input: List<String>): Long {
val dirMap = getDirAndFiles(input)
val dirSizes = getDirSizes(dirMap)
return dirSizes.filter { it.value <= 100000 }.map { it.value }.sum()
}
fun part2(input: List<String>): Long {
val dirMap = getDirAndFiles(input)
val dirSizes = getDirSizes(dirMap)
val unusedSpace = 70000000 - (dirSizes[Paths.get("/")] ?: 0L)
val neededSpace = 30000000 - unusedSpace
return dirSizes.values.filter { it > neededSpace }.minOf { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day7/Day07_test")
val testPart1 = part1(testInput)
println("testPart1: $testPart1")
val testPart2 = part2(testInput)
println("testPart2: $testPart2")
check(testPart1 == 95437L)
check(testPart2 == 24933642L)
val input = readInput("day7/Day07")
println("part1 : ${part1(input)}")
println("part2 : ${part2(input)}")
}
private data class File(
val name: String,
val size: Long,
)
private sealed class Command {
object CdUp: Command()
data class CdDown(val destinationDirName: String): Command()
object CdRoot: Command()
object Ls: Command()
data class Result(val isDir: Boolean, val size: Long, val name: String): Command()
}
private fun String.detectCommand(): Command {
if (this.first().toString() != "$") {
return Command.Result(
isDir = this.substring(0, 3) == "dir",
size = this.split(" ").first().toLongOrNull() ?: 0L,
name = this.split(" ").last(),
)
}
return when {
this.substring(2,4) == "ls" -> Command.Ls
this.substring(5) == "/" -> Command.CdRoot
this.substring(5) == ".." -> Command.CdUp
else -> Command.CdDown(this.substring(5))
}
}
private fun MutableList<File>.totalSize(): Long = this.sumOf { it.size }
private fun Path.isParent(potentialChild: Path): Boolean = potentialChild.startsWith(this)
private fun getDirAndFiles(input: List<String>): MutableMap<Path, MutableList<File>> {
val dirMap = mutableMapOf<Path, MutableList<File>>()
val rootPath = Paths.get("/")
var currentDirPath = rootPath
var remainingLines = input
while (remainingLines.isNotEmpty()) {
when (val command = remainingLines.first().detectCommand()) {
is Command.CdUp -> currentDirPath = currentDirPath.parent
is Command.CdRoot -> currentDirPath = rootPath
is Command.CdDown -> currentDirPath /= command.destinationDirName
is Command.Ls -> dirMap[currentDirPath] = dirMap.getOrDefault(currentDirPath, mutableListOf())
is Command.Result -> {
if (!command.isDir) {
val fileList = dirMap.getOrDefault(currentDirPath, mutableListOf())
fileList.add(File(name = command.name, size = command.size))
dirMap[currentDirPath] = fileList
}
}
}
remainingLines = remainingLines.drop(1)
}
return dirMap
}
private fun getDirSizes(dirMap: MutableMap<Path, MutableList<File>>): MutableMap<Path, Long> {
val dirSizes = mutableMapOf<Path, Long>()
dirMap.forEach { (currentPath, currentFiles) ->
val childrenSize = dirMap.filter { (path, _) ->
currentPath.isParent(path) && path != currentPath
}.map {
it.value.totalSize()
}.sum()
val size = currentFiles.totalSize() + childrenSize
dirSizes[currentPath] = size
}
return dirSizes
}
| 0 | Kotlin | 0 | 0 | e400c2410db4a8343c056252e8c8a93ce19564e7 | 3,728 | AdventOfCode2022 | Apache License 2.0 |
src/Day05.kt | imavroukakis | 572,438,536 | false | {"Kotlin": 12355} | fun main() {
val regex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
operator fun MatchResult?.component1() = this?.destructured?.let { (moveN, _, _) ->
moveN.toInt()
} ?: throw IllegalArgumentException()
operator fun MatchResult?.component2() = this?.destructured?.let { (_, from, _) ->
from.toInt()
} ?: throw IllegalArgumentException()
operator fun MatchResult?.component3() = this?.destructured?.let { (_, _, to) ->
to.toInt()
} ?: throw IllegalArgumentException()
fun parseStacks(input: List<String>): Map<Int, Stack> {
val stacks = sortedMapOf<Int, Stack>()
input.takeWhile { !it.startsWith(" 1") }.forEach { line ->
line.chunked(4).forEachIndexed { index, c ->
if (c.isNotBlank()) {
stacks.computeIfAbsent(index + 1) {
Stack()
}.add(c.trim().removeSurrounding("[", "]"))
}
}
}
return stacks
}
fun moveContainers(
input: List<String>,
stacks: Map<Int, Stack>,
grouped: Boolean = false,
) {
input.dropWhile { !it.startsWith("move") }.forEach {
val (moveN, from, to) = regex.matchEntire(it)
stacks[from]?.moveTo(moveN, stacks.getValue(to), grouped)
}
}
fun part1(input: List<String>): String {
val stacks = parseStacks(input)
moveContainers(input, stacks)
return stacks.values
.filter { it.containers.isNotEmpty() }
.joinToString(separator = "") { it.containers.first() }
}
fun part2(input: List<String>): String {
val stacks = parseStacks(input)
moveContainers(input, stacks, grouped = true)
return stacks.values
.filter { it.containers.isNotEmpty() }
.joinToString(separator = "") { it.containers.first() }
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
println(part1(readInput("Day05")))
check(part2(testInput) == "MCD")
println(part2(readInput("Day05")))
}
class Stack {
var containers = mutableListOf<String>()
fun add(container: String) {
containers.add(container)
}
private fun stack(container: String) {
containers.add(0, container)
}
fun moveTo(count: Int, stack: Stack, grouped: Boolean = false) {
val take = containers.take(count)
for (i in 0 until count) containers.removeFirst()
if (grouped) {
stack.containers.addAll(0, take)
} else {
take.forEach { stack.stack(it) }
}
}
}
| 0 | Kotlin | 0 | 0 | bb823d49058aa175d1e0e136187b24ef0032edcb | 2,668 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/Problem10.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | import kotlin.math.floor
import kotlin.math.sqrt
import kotlin.system.measureNanoTime
/**
* Summation of primes
*
* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
* Find the sum of all the primes below two million.
*
* https://projecteuler.net/problem=10
*/
fun main() {
println(sumOfPrimes(10))
println(sumOfPrimesSieve(10))
val time1 = measureNanoTime { println(sumOfPrimes(2_000_000)) }
val time2 = measureNanoTime { println(sumOfPrimesSieve(2_000_000)) }
println(time1)
println(time2)
}
private fun sumOfPrimes(n: Long): Long {
if (n < 2) return 0
return (3..n step 2).asSequence()
.filter(::isPrime)
.sum() + 2
}
private fun sumOfPrimesSieve(n: Long): Long {
return primes(n).sumOf(Int::toLong)
}
// The sieve of Eratosthenes optimized
fun primes(n: Long): List<Int> {
val sieveBound = ((n - 1) / 2).toInt()
val sieve = Array(sieveBound) { true }
val crosslimit = (floor(sqrt(n.toDouble())).toInt() - 1) / 2
for (i in 1..crosslimit) {
if (!sieve[i-1]) continue
for (j in (2 * i * (i + 1)) .. sieveBound step 2 * i + 1) {
sieve[j-1] = false
}
}
return listOf(2) + sieve.mapIndexedNotNull { i, isPrime -> if (isPrime) 2 * (i + 1) + 1 else null }
}
| 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 1,285 | project-euler | MIT License |
src/day16/Day16.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day16
import logEnabled
import logln
import readInput
private const val DAY_NUMBER = 16
val valveRegex = """Valve ([A-Z]{2}) has flow rate=(\d+); tunnels? leads? to valves? ([A-Z, ]+)""".toRegex()
typealias NodeId = String
fun parseFile(rawInput: List<String>): Map<NodeId, ValveNode> {
val flowMap = mutableMapOf<NodeId, Int>()
val neighbourMap = mutableMapOf<NodeId, List<NodeId>>()
for (line in rawInput) {
val (valveId, flowRate, rawNeighbours) = valveRegex.matchEntire(line)?.destructured
?: throw IllegalArgumentException("Invalid input line: $line")
flowMap[valveId] = flowRate.toInt()
val neighbours = rawNeighbours.split(", ")
neighbourMap[valveId] = neighbours
}
val nodeMap = flowMap.map { (nodeId, flowRate) -> ValveNode(nodeId, flowRate) }.associateBy { it.id }
neighbourMap.forEach { (nodeId, neighbours) ->
nodeMap[nodeId]?.neighbours = neighbours.map { nodeMap[it]!! }
}
return nodeMap
}
data class ValveNode(val id: NodeId, val flowRate: Int) {
var neighbours: List<ValveNode> = listOf()
fun shortestPathTo(target: ValveNode): List<ValveNode>? {
if (target == this)
throw IllegalArgumentException("Target node is current node")
val queue = ArrayDeque(listOf(listOf<ValveNode>() to this))
val visitedNodes = mutableSetOf<ValveNode>()
while (queue.isNotEmpty()) {
val (path, node) = queue.removeFirst()
if (node == target)
return (path + node).drop(1) // Skip source node
visitedNodes.add(node)
queue.addAll(node.neighbours.filter { it !in visitedNodes }.map { path + node to it })
}
return null
}
override fun toString(): String {
return "$id(flow=$flowRate)"
}
}
data class CandidateMove(val path: List<ValveNode>, val cost: Int, val resultingFlow: Int, val benefit: Float)
fun calculateMove(source: ValveNode, destination: ValveNode, timeLeft: Int): CandidateMove? {
val shortestPath = source.shortestPathTo(destination)!!
val cost = shortestPath.size + 1 // Cost of getting to candidate valve + opening time
val benefit = destination.flowRate.toFloat() / cost + destination.neighbours.size
if (benefit > 0) {
logln(" Benefit of moving $source -> ${shortestPath.joinToString(" -> ")}: $benefit with cost $cost")
return CandidateMove(shortestPath, cost, destination.flowRate * (timeLeft - cost), benefit)
}
return null
}
fun visitValve(node: ValveNode, timeLeft: Int, openValves: Set<ValveNode>): Int {
if (timeLeft == 0) {
logln("Time out @ ${node.id}")
return 0
}
logln("$timeLeft minutes left")
// Find best valve to open
val availableMoves = openValves
.filter { it != node }
.mapNotNull { candidate ->
calculateMove(node, candidate, timeLeft)
}
.filter { it.cost < timeLeft }
if (availableMoves.isEmpty()) {
logln("No moves left with $timeLeft time left")
return 0
}
val bestMove = availableMoves.maxBy { it.benefit }
// Perform move
logln("Moving to ${bestMove.path.joinToString(" -> ")}} for ${bestMove.benefit} of benefit and ${bestMove.cost} time cost")
return bestMove.resultingFlow + visitValve(bestMove.path.last(), timeLeft - bestMove.cost, openValves - node)
}
fun main() {
fun part1(rawInput: List<String>): Int {
val valveMap = parseFile(rawInput)
// valveMap.values.forEach { node ->
// if (node.flowRate > 0)
// println(" ${node.id} [label=\"${node.id} ${node.flowRate}\"];")
// else
// println(" ${node.id} [label=\"${node.id}\"];")
// node.neighbours.forEach { neighbour ->
// println(" ${node.id} -- ${neighbour.id};")
// }
// }
val startValve = valveMap["AA"]!!
val openValves = valveMap.values.filter { it.flowRate != 0 }.toSet()
return visitValve(startValve, 30, openValves)
}
fun part2(rawInput: List<String>): Int {
return 0
}
val sampleInput = readInput("sample_data", DAY_NUMBER)
val mainInput = readInput("main_data", DAY_NUMBER)
logEnabled = true
val part1SampleResult = part1(sampleInput)
println(part1SampleResult)
check(part1SampleResult == 1651)
val part1MainResult = part1(mainInput)
println(part1MainResult)
// check(part1MainResult == 0) // Greater than 1444
// val part2SampleResult = part2(sampleInput)
// println(part2SampleResult)
// check(part2SampleResult == 0)
// val part2MainResult = part2(mainInput)
// println(part2MainResult)
// check(part2MainResult == 0)
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 4,776 | advent-of-code-2022 | Apache License 2.0 |
src/day08/Day08.kt | Frank112 | 572,910,492 | false | null | package day08
import assertThat
import readInput
fun main() {
fun parseInput(input: List<String>): List<List<Int>> {
return input.map { l -> l.chunked(1).map { it.toInt() } }
}
fun isTreeVisibleFromLeft(input: List<List<Int>>, x: Int, y: Int): Boolean {
val treeHeight = input[x][y]
for (left in 0 until x) {
if (input[left][y] >= treeHeight) return false
}
return true
}
fun isTreeVisibleFromRight(input: List<List<Int>>, x: Int, y: Int): Boolean {
val treeHeight = input[x][y]
for (right in x + 1 until input[x].size) {
if (input[right][y] >= treeHeight) return false
}
return true
}
fun isTreeVisibleFromTop(input: List<List<Int>>, x: Int, y: Int): Boolean {
val treeHeight = input[x][y]
for (top in 0 until y) {
if (input[x][top] >= treeHeight) return false
}
return true
}
fun isTreeVisibleFromBottom(input: List<List<Int>>, x: Int, y: Int): Boolean {
val treeHeight = input[x][y]
for (bottom in y + 1 until input.size) {
if (input[x][bottom] >= treeHeight) return false
}
return true
}
fun isTreeVisible(input: List<List<Int>>, x: Int, y: Int): Boolean {
return isTreeVisibleFromLeft(input, x, y) || isTreeVisibleFromRight(input, x, y)
|| isTreeVisibleFromTop(input, x, y) || isTreeVisibleFromBottom(input, x, y)
}
fun countTreesInView(trees: List<Int>, treeHeight: Int): Int {
var count = 0
for(tree in trees) {
count++
if (tree >= treeHeight) return count
}
return count
}
fun viewDistance(rowOrColumn: List<Int>, treeIndex: Int): Pair<Int, Int> {
val treeHeight = rowOrColumn[treeIndex]
val treesLeft = rowOrColumn.subList(0, treeIndex).reversed()
val treesRight = rowOrColumn.subList(treeIndex + 1, rowOrColumn.size)
return Pair(countTreesInView(treesLeft, treeHeight), countTreesInView(treesRight, treeHeight))
}
fun computeScenicScore(input: List<List<Int>>, x: Int, y: Int): Int {
val leftRightView = viewDistance(input[y], x)
val topDownView = viewDistance(input.map { it[x] }, y)
return leftRightView.first * leftRightView.second * topDownView.first * topDownView.second
}
fun part1(input: List<List<Int>>): Int {
val length = input.size
val height = input[0].size
var countVisibleTrees = 0
for (x in 1..length - 2) {
for (y in 1..height - 2) {
if (isTreeVisible(input, x, y)) countVisibleTrees++
}
}
return length * 2 + (height - 2) * 2 + countVisibleTrees
}
fun part2(input: List<List<Int>>): Int {
val length = input.size
val height = input[0].size
var maxScenicScore = Int.MIN_VALUE
for (x in 1..length - 2) {
for (y in 1..height - 2) {
val currentScenicScore = computeScenicScore(input, x, y)
if (currentScenicScore > maxScenicScore) maxScenicScore = currentScenicScore
}
}
return maxScenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = parseInput(readInput("day08/Day08_test"))
println("Parsed test input: $testInput")
assertThat(part1(testInput), 21)
assertThat(part2(testInput), 8)
val input = parseInput(readInput("day08/Day08"))
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1e927c95191a154efc0fe91a7b89d8ff526125eb | 3,593 | advent-of-code-2022 | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day21/Day21.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day21
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2021.DayOf2021
import java.util.PriorityQueue
/**
* See [Year 2021, Day 21](https://adventofcode.com/2021/day/21)
*/
object Day21 : DayOf2021(21) {
override fun first(): Any? {
val start = lines.map { it.split(" ").last().toInt() }
val dice = generateSequence(1) { if (it == 100) 1 else it + 1 }
val counter = generateSequence(0) { it + 3 }
val startUniverse = Universe(
listOf(
State(start.first(), 0),
State(start.last(), 0),
),
move = 0,
)
return dice
.chunked(3)
.map { it.sum() }
.scan(startUniverse) { universe, increase ->
Universe(
states = universe.states.mapIndexed { index, value ->
if (index == universe.move) {
val newPos = (value.pos - 1 + increase) % 10 + 1
State(newPos, value.score + newPos)
} else {
value
}
},
move = 1 - universe.move,
)
}
.map { un -> un.states.map { it.score } }
.zip(counter)
.first { (scores, _) -> scores.any { it >= 1000 } }
.let { (scores, dices) -> scores.minOf { it } * dices }
}
override fun second(): Any? {
val start = lines.map { it.split(" ").last().toInt() }
val increases = (1..3).flatMap { a ->
(1..3).flatMap { b ->
(1..3).map { c ->
a + b + c
}
}
}
.groupingBy { it }
.eachCount()
.mapValues { it.value.toLong() }
val startUniverse = Universe(
listOf(
State(start.first(), 0),
State(start.last(), 0),
),
move = 0,
)
val knownUniverses = mutableMapOf(startUniverse to 1L)
val queue = PriorityQueue<Universe>(compareBy { un -> un.states.sumOf { it.score } })
queue += startUniverse
while (queue.isNotEmpty()) {
val curr = queue.remove()
val currCount = knownUniverses.getOrDefault(curr, 0L)
val active = curr.states[curr.move]
val newUniverses = increases
.map { (increase, count) ->
val newPos = (active.pos - 1 + increase) % 10 + 1
State(newPos, active.score + newPos) to count
}
.map { (state, count) ->
Universe(
states = curr.states.mapIndexed { index, value ->
if (index == curr.move) state else value
},
move = 1 - curr.move,
) to count
}
newUniverses.forEach { (universe, count) ->
if (universe !in knownUniverses && universe.states.none { it.score >= 21 }) {
queue += universe
}
knownUniverses[universe] = knownUniverses.getOrDefault(universe, 0) + count * currCount
}
}
return knownUniverses.filter { un -> un.key.states.any { it.score >= 21 } }
.toList()
.groupBy { 1 - it.first.move }
.mapValues { un -> un.value.sumOf { it.second } }
.maxOf { it.value }
}
data class Universe(
val states: List<State>,
val move: Int,
)
data class State(
val pos: Int,
val score: Int,
)
}
fun main() = SomeDay.mainify(Day21)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 3,200 | adventofcode | MIT License |
src/year2023/day08/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2023.day08
import year2023.getLCM
import year2023.solveIt
fun main() {
val day = "08"
val expectedTest1 = 6L
val expectedTest2 = 6L
fun navigateToNext(
instructions: String, currIdx: Int, paths: Map<String, Pair<String, String>>, current: String
) = if (instructions[currIdx] == 'L') paths[current]!!.first else paths[current]!!.second
fun solveIt(
current: String, instructions: String, paths: Map<String, Pair<String, String>>
): Long {
var actual = current
var i = 0L
while (actual[2] != 'Z') {
val currIdx = (i % instructions.length).toInt()
actual = navigateToNext(instructions, currIdx, paths, actual)
i++
}
return i
}
fun part1(input: List<String>): Long {
val instructions = input[0]
val paths = input.drop(2).associate { it.substring(0, 3) to (it.substring(7, 10) to it.substring(12, 15)) }
return solveIt("AAA", instructions, paths)
}
fun part2(input: List<String>): Long {
val instructions = input[0]
val paths = input.drop(2).map { it.substring(0, 3) to (it.substring(7, 10) to it.substring(12, 15)) }.toMap()
val solutions = paths.filter { it.key.endsWith('A') }.map { it.key }.map { solveIt(it, instructions, paths) }
return solutions.chunked(2).map { getLCM(it[0], it[1]) }.fold(1L) { acc, l -> getLCM(acc, l) }
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test2")
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 1,530 | adventOfCode | Apache License 2.0 |
src/Day11.kt | arnoutvw | 572,860,930 | false | {"Kotlin": 33036} | import com.notkamui.keval.Keval
fun main() {
data class Monkey(val numbers: MutableList<Long>, val operation: String, val divisibleBy: Int, val monkyIfTrue: Int, val monkeyIfFalse: Int, var inspections: Long = 0)
fun part1(input: List<String>, monkeys: MutableMap<Int, Monkey>): Int {
for(i in 1..20) {
for (m in 0 until monkeys.size) {
val monkey = monkeys[m]
if(monkey != null) {
monkey.numbers.forEach {
val res = Keval.eval(monkey.operation.replace("old", it.toString())).toInt() / 3
if (res % monkey.divisibleBy == 0) {
monkeys[monkey.monkyIfTrue]?.numbers?.add(res.toLong())
} else {
monkeys[monkey.monkeyIfFalse]?.numbers?.add(res.toLong())
}
}
monkey.inspections += monkey.numbers.size
monkey.numbers.clear()
}
}
}
return monkeys.values.map { it.inspections }.sortedDescending().take(2).reduce { i, j -> i*j }.toInt()
}
fun part2(input: List<String>, monkeys: MutableMap<Int, Monkey>): Long {
val mod = monkeys.values.map { it.divisibleBy }.reduce { a, b -> a * b }
for(i in 0 until 10000) {
for (m in 0 until monkeys.size) {
val monkey = monkeys[m]
if(monkey != null) {
monkey.numbers.forEach {
val res = Keval.eval(monkey.operation.replace("old", it.toString())).toLong() % mod
if (res % monkey.divisibleBy.toLong() == 0L) {
monkeys[monkey.monkyIfTrue]?.numbers?.add(res)
} else {
monkeys[monkey.monkeyIfFalse]?.numbers?.add(res)
}
}
monkey.inspections += monkey.numbers.size
monkey.numbers.clear()
}
}
}
return monkeys.values.map { it.inspections }.sortedDescending().take(2).reduce { i, j -> i*j }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
val testMonkeys = mutableMapOf(0 to Monkey(mutableListOf(79, 98), "old * 19", 23, 2, 3),
1 to Monkey(mutableListOf(54, 65, 75, 74), "old + 6", 19, 2, 0),
2 to Monkey(mutableListOf(79, 60, 97), "old * old", 13, 1, 3),
3 to Monkey(mutableListOf(74), "old + 3", 17, 0, 1))
println("Test")
//val part1 = part1(testInput, testMonkeys)
//println(part1)
val part2 = part2(testInput, testMonkeys)
println(part2)
//check(part1 == 10605)
check(part2 == 2713310158)
println("Waarde")
val input = readInput("Day11")
val realMonkeys = mutableMapOf(0 to Monkey(mutableListOf(56, 52, 58, 96, 70, 75, 72), "old * 17", 11, 2, 3),
1 to Monkey(mutableListOf(75, 58, 86, 80, 55, 81), "old + 7", 3, 6, 5),
2 to Monkey(mutableListOf(73, 68, 73, 90), "old * old", 5, 1, 7),
3 to Monkey(mutableListOf(72, 89, 55, 51, 59), "old + 1", 7, 2, 7),
4 to Monkey(mutableListOf(76, 76, 91), "old * 3", 19, 0, 3),
5 to Monkey(mutableListOf(88), "old + 4", 2, 6, 4),
6 to Monkey(mutableListOf(64, 63, 56, 50, 77, 55, 55, 86), "old + 8", 13, 4, 0),
7 to Monkey(mutableListOf(79, 58), "old + 6", 17, 1, 5),
)
//println(part1(input, realMonkeys))
println(part2(input, realMonkeys))
}
| 0 | Kotlin | 0 | 0 | 0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4 | 3,603 | aoc-2022-in-kotlin | Apache License 2.0 |
day-10/src/main/kotlin/SyntaxScoring.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | import java.util.LinkedList
import java.util.Stack
fun main() {
println("Part One Solution: ${partOne()}")
println("Part Two Solution: ${partTwo()}")
}
val closingMatch = mapOf(
')' to '(',
']' to '[',
'}' to '{',
'>' to '<',
)
val openingMatch = mapOf(
'(' to ')',
'[' to ']',
'{' to '}',
'<' to '>',
)
val openingDelimiters = openingMatch.keys
val illegalCharScore = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137,
)
val completingCharScore = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
private fun partOne(): Int {
return readInputLines()
.map {
val stack = Stack<Char>()
for (curChar in it.toCharArray()) {
if (curChar in openingDelimiters) {
stack.push(curChar)
} else {
if (stack.pop() != closingMatch[curChar]!!) {
return@map curChar
}
}
}
}
.sumOf {
illegalCharScore[it] ?: 0
}
}
private fun partTwo(): Long {
val sortedScore = readInputLines()
.asSequence()
.map {
val stack = Stack<Char>()
for (c in it.toCharArray()) {
if (c in openingDelimiters) {
stack.push(c)
} else {
if (stack.pop() != closingMatch[c]!!) {
return@map Stack<Char>()
}
}
}
stack
}
.map {
val toComplete = LinkedList<Char>()
while (!it.empty()) {
toComplete.add(openingMatch[it.pop()]!!)
}
toComplete
}.map {
var score = 0L
while (!it.isEmpty()) {
score = (score * 5) + completingCharScore[it.pop()!!]!!
}
score
}
.filter { it != 0L }
.sorted()
.toList()
return sortedScore[sortedScore.size / 2]
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 2,266 | aoc-2021 | MIT License |
src/Day02.kt | Hwajun1323 | 574,962,608 | false | {"Kotlin": 6799} | import kotlin.math.min
enum class RPS(val value: Int){
ROCK(1),
PAPER(2),
SCISSORS(3),
}
object WinScore{
const val WIN = 6
const val LOOSE = 0
const val DRAW = 3
}
fun main() {
fun Char.toGameChoice():RPS =
when(this) {
'A', 'X' -> RPS.ROCK
'B', 'Y' -> RPS.PAPER
'C', 'Z' -> RPS.SCISSORS
else -> throw IllegalArgumentException("Not available choice")
}
fun toGameChoice(input: String) : Pair<RPS, RPS> {
return input[0].toGameChoice() to input[2].toGameChoice()
}
fun Char.toEndResult() =
when(this){
'X' -> WinScore.LOOSE
'Y' -> WinScore.DRAW
else -> WinScore.WIN
}
fun toFigureShape(input: String) : Pair<RPS, Int> {
return input[0].toGameChoice() to input[2].toEndResult()
}
fun Int.decideChoice(opponent: RPS) : Int{
return when (this) {
// loose
0 -> when (opponent)
{ RPS.ROCK -> 3
RPS.PAPER -> 1
else -> 2
}
// draw
3 -> when (opponent)
{ RPS.ROCK -> 1
RPS.PAPER -> 2
else -> 3
}
// win
else -> when (opponent)
{
RPS.ROCK -> 2
RPS.PAPER -> 3
else -> 1
}
}
}
// win case of RPS
fun RPS.win(opponent: RPS): Boolean =
when {
this == RPS.ROCK && opponent == RPS.SCISSORS || this == RPS.PAPER && opponent == RPS.ROCK || this == RPS.SCISSORS && opponent == RPS.PAPER -> true
else -> false
}
fun RPS.getScore(opponent: RPS) =
when {
this.win(opponent) -> WinScore.WIN
this == opponent -> WinScore.DRAW
else -> WinScore.LOOSE
}
fun part1(input: List<String>): Int {
return input.sumOf {
if (it.isBlank()) 0
else {
val (opponent, mine) = toGameChoice(it)
mine.getScore(opponent) + mine.value
}
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
if(it.isBlank()) 0
else {
val (opponent, mine) = toFigureShape(it)
mine.decideChoice(opponent) + mine
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 667a8c7a0220bc10ddfc86b74e3e6de44b73d5dd | 2,636 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | seana-zr | 725,858,211 | false | {"Kotlin": 28265} | import java.lang.IllegalStateException
import java.util.regex.Pattern
import kotlin.math.max
fun main() {
data class GameRound(
var red: Int = 0,
var green: Int = 0,
var blue: Int = 0,
)
/**
* which games would have been possible if the bag contained only
* 12 red cubes, 13 green cubes, and 14 blue cubes
*/
fun isRoundValid(red: Int, green: Int, blue: Int): Boolean {
return red <= 12 && green <= 13 && blue <= 14
}
/**
* for inputs like 14blue, 5green, 20red
*/
fun extractNumberAndColor(input: String): Pair<Int, String> {
val pattern = Pattern.compile("(\\d+)([a-zA-Z]+)")
val matcher = pattern.matcher(input)
if (matcher.find()) {
val number = matcher.group(1).toInt()
val color = matcher.group(2)
return Pair(number, color)
} else {
throw IllegalArgumentException("Invalid input format: $input")
}
}
fun parseGameToRounds(game: String): List<GameRound> {
val roundInputs = game
.dropWhile { it != ':' }
.drop(2)
.filterNot { it.isWhitespace() }
.split(";")
val rounds = roundInputs.map { input ->
var round = GameRound()
input.split(",").forEach { cubes ->
val (number, color) = extractNumberAndColor(cubes)
round = when (color) {
"red" -> round.copy(red = number)
"blue" -> round.copy(blue = number)
"green" -> round.copy(green = number)
else -> throw IllegalStateException("$color is not a valid color")
}
}
round
}
return rounds
}
fun part1(input: List<String>): Int {
var result = 0
input.forEachIndexed { index, game ->
val gameId = index + 1
val rounds = parseGameToRounds(game)
val gameIsValid = rounds.all { isRoundValid(it.red, it.green, it.blue) }
result += if (gameIsValid) gameId else 0
}
return result
}
fun getMinimumCubeSet(rounds: List<GameRound>): GameRound {
var result = GameRound()
rounds.forEach { round ->
result = result.copy(
red = max(result.red, round.red),
blue = max(result.blue, round.blue),
green = max(result.green, round.green)
)
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
input.forEach { game ->
val rounds = parseGameToRounds(game)
val minCubeSet = getMinimumCubeSet(rounds)
result += minCubeSet.blue * minCubeSet.green * minCubeSet.red
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part2(testInput) == 2286)
val input = readInput("Day02")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | da17a5de6e782e06accd3a3cbeeeeb4f1844e427 | 3,095 | advent-of-code-kotlin-template | Apache License 2.0 |
aoc-2021/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentyone/Day04.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwentyone
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.readDayInput
class Day04 : Day<Int> {
private val input = readDayInput()
.split("\n\n")
.map { chunk -> chunk.lines() }
private val draw = input
.first()
.first()
.split(',')
.map { num -> num.toInt() }
private val boards = input
.drop(1)
.map { board ->
Board(
board.map { line ->
line.split(' ')
.filter { it.isNotBlank() }
.map { num -> num.toInt() }
}
)
}
private class Board(private val lines: List<List<Int>>) {
private val size: Int = lines.size
operator fun get(x: Int, y: Int): Int {
check(x in 0 until size)
check(y in 0 until size)
return lines[y][x]
}
fun hasWon(drawnNumbers: Set<Int>): Boolean =
(0 until size).any { i ->
isHorizontalWin(drawnNumbers, i) || isVerticalWin(drawnNumbers, i)
}
private fun isHorizontalWin(drawnNumbers: Set<Int>, y: Int): Boolean {
return lines[y].all { num -> num in drawnNumbers }
}
private fun isVerticalWin(drawnNumbers: Set<Int>, x: Int): Boolean {
return (0 until size).all { y ->
this[x, y] in drawnNumbers
}
}
fun getScore(drawnNumbers: Set<Int>): Int {
val sum = lines.sumOf { line ->
line.sumOf { num ->
if (num in drawnNumbers) 0 else num
}
}
return sum * drawnNumbers.last()
}
fun println(drawnNumbers: Set<Int>) {
lines.forEach { line ->
println(
line.joinToString("") { num ->
val marked = num in drawnNumbers
((if (marked) "[" else " ") + num + (if (marked) "]" else " ")).padStart(4)
}
)
}
}
}
private data class BoardState(val boards: List<Board>, val drawnNumbers: Set<Int>) {
val winningBoards: Set<Board> = boards.filter { board -> board.hasWon(drawnNumbers) }.toSet()
fun printState() {
boards.forEachIndexed { index, board ->
println()
println("board $index; hasWon=${board.hasWon(drawnNumbers)}")
board.println(drawnNumbers)
}
}
}
override fun step1(): Int {
draw.fold(BoardState(boards, emptySet())) { state, drawnNumber ->
state.winningBoards.firstOrNull()?.let { winner ->
return winner.getScore(state.drawnNumbers)
}
state.copy(drawnNumbers = state.drawnNumbers + drawnNumber)
}
throw IllegalStateException("No winners")
}
override fun step2(): Int {
draw.fold(BoardState(boards, emptySet())) { state, drawnNumber ->
val nextState = state.copy(drawnNumbers = state.drawnNumbers + drawnNumber)
// If everybody won
if (nextState.winningBoards.size == nextState.boards.size) {
// Get the latest winner and return their score
val newWinners = nextState.winningBoards - state.winningBoards
return newWinners.first().getScore(nextState.drawnNumbers)
}
nextState
}
throw IllegalStateException("Not everybody won")
}
override val expectedStep1: Int = 2745
override val expectedStep2: Int = 6594
}
| 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 3,697 | adventofcode | Apache License 2.0 |
src/Day14.kt | oleksandrbalan | 572,863,834 | false | {"Kotlin": 27338} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
val input = readInput("Day14")
.filterNot { it.isEmpty() }
.map { row -> row.split(" -> ").map { Point.from(it) } }
val part1 = input.sandSimulation()
println("Part1: $part1")
val bounds = input.flatten().getBounds()
val height = bounds.to.y + 2
val bottomPath = listOf(listOf(Point(500 - height, height), Point(500 + height, height)))
val part2 = (input + bottomPath).sandSimulation()
println("Part2: $part2")
}
private fun List<List<Point>>.sandSimulation(): Int {
val bounds = flatten().getBounds()
val rows = bounds.to.y + 1
val columns = bounds.to.x - bounds.from.x + 1
val start = Point(500 - bounds.from.x, 0)
val matrix = IntMatrix(rows, columns)
forEach { path ->
val points = path.map { Point(it.x - bounds.from.x, it.y) }
matrix.fill(points)
}
var sand = start
while (true) {
sand = try {
matrix.move(sand)
} catch (e: NoSuchElementException) {
matrix.set(sand.y, sand.x, FLAG_SAND)
if (sand == start) {
break
}
start
} catch (e: IndexOutOfBoundsException) {
break
}
}
return matrix.asSequence().count { it == FLAG_SAND }
}
private fun IntMatrix.fill(path: List<Point>) {
path.windowed(2).forEach { (p1, p2) ->
val minX = min(p1.x, p2.x)
repeat(abs(p2.x - p1.x) + 1) {
set(p1.y, minX + it, FLAG_ROCK)
}
val minY = min(p1.y, p2.y)
repeat(abs(p2.y - p1.y) + 1) {
set(minY + it, p1.x, FLAG_ROCK)
}
}
}
private fun IntMatrix.move(point: Point): Point =
sequenceOf(
Point(point.x, point.y + 1),
Point(point.x - 1, point.y + 1),
Point(point.x + 1, point.y + 1),
).first { (x, y) -> get(y, x) == 0 }
private fun List<Point>.getBounds(): Bounds {
var minX = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
var minY = Int.MAX_VALUE
var maxY = Int.MIN_VALUE
forEach {
minX = min(minX, it.x)
maxX = max(maxX, it.x)
minY = min(minY, it.y)
maxY = max(maxY, it.y)
}
return Bounds(Point(minX, minY), Point(maxX, maxY))
}
private data class Bounds(val from: Point, val to: Point)
private data class Point(val x: Int, val y: Int) {
companion object {
fun from(value: String): Point {
val data = value.split(",").map { it.toInt() }
return Point(data[0], data[1])
}
}
}
private const val FLAG_ROCK = 1
private const val FLAG_SAND = 2
| 0 | Kotlin | 0 | 2 | 1493b9752ea4e3db8164edc2dc899f73146eeb50 | 2,662 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | TinusHeystek | 574,474,118 | false | {"Kotlin": 53071} | import extensions.grid.*
import kotlin.math.abs
class Day15 : Day(15) {
data class SensorInfo(val sensor: Point, val beacon: Point)
private fun parseInput(input: String): List<SensorInfo> {
return input.lines()
.map { line -> line.filter { it.isDigit() || it == '-' || it == '='} }
.map { line ->
val split = line.substring(1).split("=").map { it.toInt() }
SensorInfo(split[0] to split[1], split[2] to split[3])
}
}
private fun manhattanDistance(point1: Point, point2: Point): Int {
val distance = point2 - point1
return abs(distance.x) + abs(distance.y)
}
// --- Part 1 ---
override fun part1ToString(input: String): String {
val sensorInfo = parseInput(input)
val level = (if (sensorInfo.count() < 15) 10 else 2000000)
val covered = mutableSetOf<Pair<Int, Int>>()
sensorInfo.forEach { info ->
val distance = manhattanDistance(info.sensor, info.beacon)
for (x in (info.sensor.x - distance)..(info.sensor.x + distance)) {
val point = Pair(x, level)
if (point != info.beacon && manhattanDistance(info.sensor, point) <= distance) {
covered.add(point)
}
}
}
return covered.size.toString()
}
// --- Part 2 ---
override fun part2ToString(input: String): String {
val sensorInfo = parseInput(input)
val maxLevel = (if (sensorInfo.count() < 15) 20 else 4_000_000)
val sensors = sensorInfo.map { info ->
info.sensor to manhattanDistance(info.sensor, info.beacon)
}.sortedBy { (sensor, _) -> sensor.x }
for (y in 0..maxLevel) {
var x = 0
sensors.forEach { (sensor, distance) ->
if (manhattanDistance(sensor, Pair(x, y)) <= distance) {
x = sensor.x + distance - abs(sensor.y - y) + 1
}
}
if (x <= maxLevel) {
return (x * 4_000_000L + y).toString()
}
}
error("Point not found")
}
}
fun main() {
Day15().printToStringResults("26", "56000011")
}
| 0 | Kotlin | 0 | 0 | 80b9ea6b25869a8267432c3a6f794fcaed2cf28b | 2,233 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day19/day.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day19
import util.extractIntGroups
import util.readInput
import util.shouldBe
fun main() {
val testInput = readInput(Input::class, testInput = true).parseInput()
testInput.part1() shouldBe 33
testInput.part2() shouldBe 56 * 62
val input = readInput(Input::class).parseInput()
println("output for part1: ${input.part1()}")
println("output for part2: ${input.part2()}")
}
private operator fun IntArray.contains(other: IntArray): Boolean {
for (i in 0..3) if (this[i] < other[i]) return false
return true
}
private inline fun combineResourceArray(f: (Int) -> Int) = IntArray(4) { f(it) }
private class Blueprint(
val id: Int,
val robotCosts: Array<IntArray>,
) {
val maxIncomes: IntArray = combineResourceArray { resource ->
if (resource == 3) 999999 else (0..3).maxOf { botType -> robotCosts[botType][resource] }
}
}
private val lineRegex =
Regex("""Blueprint (\d+): Each ore robot costs (\d+) ore\. Each clay robot costs (\d+) ore\. Each obsidian robot costs (\d+) ore and (\d+) clay\. Each geode robot costs (\d+) ore and (\d+) obsidian\.""")
private class Input(
val blueprints: List<Blueprint>,
)
private fun List<String>.parseInput(): Input {
val blueprints = map { line ->
val values = line.extractIntGroups(lineRegex).iterator()
Blueprint(
id = values.next(),
robotCosts = arrayOf(
intArrayOf(values.next(), 0, 0, 0),
intArrayOf(values.next(), 0, 0, 0),
intArrayOf(values.next(), values.next(), 0, 0),
intArrayOf(values.next(), 0, values.next(), 0),
),
)
}
return Input(blueprints)
}
private data class State(
val maxTime: Int,
val blueprint: Blueprint,
var minute: Int,
val inventory: IntArray,
val income: IntArray,
var maxGeodes: Int = 0,
) {
constructor(maxTime: Int, blueprint: Blueprint) : this(
maxTime = maxTime,
blueprint = blueprint,
minute = 1,
inventory = intArrayOf(0, 0, 0, 0),
income = intArrayOf(1, 0, 0, 0),
)
}
private inline fun IntArray.mutate(f: (Int) -> Int) {
for (i in 0..3) this[i] = f(i)
}
// thats weird:
// when i split this function into two (one for nextRobot==null and one for nextRobot!= null)
// i would expect to get either a very minor performance boost, or none at all.
// but instead i get a performance LOSS of a factor of 2... jvm optimizations are weird sometimes ^^
private fun State.search(nextRobot: Int?): Int {
if (minute > maxTime) return inventory.last()
if (nextRobot == null) {
// i would have liked to use some form of maxOf {...} here, but this makes it up to 6 times slower...
var best = 0
for (nextRobot in 0..3) {
if (income[nextRobot] < blueprint.maxIncomes[nextRobot]) {
val score = search(nextRobot)
if (score > best) best = score
}
}
return best
}
val cost = blueprint.robotCosts[nextRobot]
return if (cost in inventory) {
inventory.mutate { inventory[it] + (income[it] - cost[it]) }
income[nextRobot]++
minute++
val result = search(null)
minute--
income[nextRobot]--
inventory.mutate { inventory[it] - (income[it] - cost[it]) }
result
} else {
inventory.mutate { inventory[it] + income[it] }
minute++
val result = search(nextRobot)
minute--
inventory.mutate { inventory[it] - income[it] }
result
}
}
private fun findBestScore(blueprint: Blueprint, maxTime: Int): Int {
val t1 = System.currentTimeMillis()
val score = State(maxTime, blueprint).search(null)
println("blueprint ${blueprint.id} has best score $score ($maxTime step sim took ${System.currentTimeMillis() - t1}ms)")
return score
}
private fun Input.part1(): Int {
return blueprints.sumOf { it.id * findBestScore(it, 24) }
}
private fun Input.part2(): Int {
// i am probably missing some way to reduce branching in the search,
// since the test run took 5.5 minutes and the real run took 1 minute.
// but i am too lazy to look for more optimizations :D
return blueprints
.take(3)
.map { findBestScore(it, 32) }
.reduce { a, b -> a * b }
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 4,360 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Valves.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | fun main() = Valves.solve()
private object Valves {
fun solve() {
val nodes = readInput()
val maxPressure = findMaxPressureRelease(nodes, "AA", 26)
println("Max releasable pressure: ${maxPressure}")
}
private fun readInput(): Map<String, Node> = buildMap<String, Node> {
generateSequence(::readLine).forEach {
val groupValues =
"Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? ([\\w ,]+)".toRegex()
.matchEntire(it)!!.groupValues
val node = Node(
groupValues[1],
groupValues[2].toInt(10),
groupValues[3].split(", ").toList()
)
put(node.label, node)
}
}
private fun findMaxPressureRelease(nodes: Map<String, Node>, startPos: String, remainingTime: Int): Int {
val distances = mutableMapOf<String, Int>()
fun distanceKey(a: String, b: String) = listOf(a, b).sorted().joinToString("")
fun distanceBetween(a: String, b: String): Int {
if (a == b) {
return 0
}
if (distanceKey(a, b) in distances) {
return distances[distanceKey(a, b)]!!
}
val queue = mutableListOf(a)
while (queue.isNotEmpty()) {
val item = queue.removeFirst()
if (item == b) {
return distances[distanceKey(a, item)]!!
}
val dist = distanceBetween(a, item)
for (edge in nodes[item]!!.edges) {
if (distanceKey(a, edge) !in distances) {
distances[distanceKey(a, edge)] = dist + 1
}
if (edge !in queue) {
queue.add(edge)
}
}
}
throw Error("Path not found $a->$b")
}
fun pathTime(path: List<String>): Int {
var result = 0
var prev = startPos
for (item in path) {
result += distanceBetween(prev, item) + 1
prev = item
}
return result
}
fun pathFlowPair(first: List<String>, second: List<String>): Int {
var result = 0
var flow = 0
val openValves = mutableSetOf<String>()
fun openValve(valve: String) {
if (valve in openValves) return
openValves.add(valve)
flow += nodes[valve]!!.pressure
}
val pathA = first.toMutableList()
val pathB = second.toMutableList()
var a = startPos
var b = startPos
var timeA = 0
var timeB = 0
var nextA: String? = null
var nextB: String? = null
for (i in 0..remainingTime) {
result += flow
if (i == timeA) {
if (i > 0 && nextA != null) {
a = nextA
openValve(a)
}
nextA = pathA.removeFirstOrNull()
if (nextA != null) {
timeA += distanceBetween(a, nextA) + 1
}
}
if (i == timeB) {
if (i > 0 && nextB != null) {
b = nextB
openValve(b)
}
nextB = pathB.removeFirstOrNull()
if (nextB != null) {
timeB += distanceBetween(b, nextB) + 1
}
}
}
return result
}
val paths = mutableSetOf<List<String>>(listOf())
val valves = nodes.keys.filter { nodes[it]!!.pressure > 0 }
for (level in 0..valves.size) {
println("$level")
val newItems = mutableSetOf<List<String>>()
for (valve in valves) {
for (prefix in paths) {
if (valve in prefix) {
continue
}
val path = prefix.plus(valve)
if (path in paths) {
continue
}
// println("$valve $prefix")
if (pathTime(path) < remainingTime) {
newItems.add(path)
}
}
}
if (!paths.addAll(newItems)) {
break
} else {
//println("NI ${newItems.size}")
}
}
println("Number of paths ${paths.size}")
var max = 0
var i = 0
for (a in paths) {
for (b in paths) {
if (a != b) {
max = maxOf(max, pathFlowPair(a, b))
}
}
i += 1
println("$i")
}
// println("Distance ${distanceBetween("BB", "JJ")}")
// val bestPath = paths.sortedBy { pathFlow(it) }.last()
// println("Best path $bestPath")
return max
}
data class Node(val label: String, val pressure: Int, val edges: List<String>)
} | 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 5,273 | aoc2022 | MIT License |
src/Day13.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | import java.lang.Integer.min
sealed interface Value {
fun lessThan(value: Value): Boolean?
}
class IntValue(val v: Int) : Value {
override fun lessThan(value: Value): Boolean? {
return if (value is IntValue) {
if (this.v < value.v) true else if (this.v > value.v) false else null
} else {
ListValue(mutableListOf(this)).lessThan(value)
}
}
override fun toString(): String {
return v.toString()
}
}
class ListValue(val values: MutableList<Value>) : Value {
override fun lessThan(value: Value): Boolean? {
if (value is IntValue) {
return lessThan(ListValue(mutableListOf(value)))
}
require(value is ListValue)
for (i in 0 until min(values.size, value.values.size)) {
val res = values[i].lessThan(value.values[i])
if (res != null) {
return res
}
}
if (values.size < value.values.size) {
return true
}
else if (values.size > value.values.size) {
return false
}
return null
}
override fun toString(): String {
return values.joinToString(",")
}
}
fun main() {
fun parseValue(it: String): Value {
val res = ListValue(mutableListOf())
val a: ArrayDeque<ListValue> = ArrayDeque(listOf(res))
var i = 1
while (i < it.length - 1) {
if (it[i] == '[') {
a.addFirst(ListValue(mutableListOf()))
} else if (it[i] == ']') {
val element = a.removeFirst()
a.first().values.add(element)
}
else if (it[i] == ',') {
i++
continue
}
else {
var s = ""
while (Character.isDigit(it[i])) s += it[i++]
a.first().values.add(ListValue(mutableListOf(IntValue(s.toInt()))))
continue
}
i++
}
return res
}
fun part1(input: List<String>): Int {
return input.asSequence().filter { it.isNotEmpty() }.chunked(2)
.map { it.map(::parseValue) }
.withIndex()
.filter { it.value[0].lessThan(it.value[1]) == true }
.sumOf { it.index + 1 }
}
fun part2(input: List<String>): Int {
val a = parseValue("[[2]]")
val b = parseValue("[[6]]")
val map = (input.filter { it.isNotEmpty() }.map { parseValue(it) } + listOf(a, b))
.sortedWith { f, s -> if (f.lessThan(s) == true) -1 else if (s.lessThan(f) == true) 1 else 0 }
return (map.indexOf(a) + 1) * (map.indexOf(b) + 1)
}
part1(readInput("input")).println()
part2(readInput("input")).println()
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 2,797 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc22/Day11.kt | asmundh | 573,096,020 | false | {"Kotlin": 56155} | package aoc22
import lcm
import readInput
data class Monkey(
val name: String,
val items: MutableList<Long> = mutableListOf(),
val operation: String,
val divisor: Long,
val ifTrueTarget: Int,
val ifFalseTarget: Int,
var inspections: Long = 0
) {
fun doRound(worryDivisor: Long, leastCommonMultiplier: Long): Map<Int, List<Long>> {
val itemsToThrow = mutableMapOf<Int, MutableList<Long>>(
ifTrueTarget to mutableListOf(),
ifFalseTarget to mutableListOf(),
)
items.forEach {
val newWorryLevel = doOperation(it) % leastCommonMultiplier
val boredLevel = Math.floorDiv(newWorryLevel, worryDivisor)
itemsToThrow[getMonkeyTarget(boredLevel)]?.add(boredLevel)
inspections ++
}
items.clear()
return itemsToThrow
}
private fun doOperation(old: Long): Long {
val op = operation.split(" ")
val second = op[2].let {
if (it == "old") old
else it.toLong()
}
return when (op[1]) {
"*" -> old * second
"+" -> old + second
else -> throw Exception("Ulovlig mattestykke: $operation ga meg $op")
}
}
private fun getMonkeyTarget(testOutput: Long) = if ((testOutput % divisor) == 0L) ifTrueTarget else ifFalseTarget
}
data class MonkeyGang(
val monkeys: List<Monkey>,
val rounds: Int = 20,
val worryDivisor: Long = 1,
) {
private var roundCount = 0
private val leastCommonMultiplier = monkeys.map { it.divisor }.reduce { acc, i -> lcm(acc, i) }
fun trigger() {
while (roundCount < rounds) {
doRound()
roundCount++
}
}
private fun doRound() {
monkeys.forEach { monkey ->
val toDistribute = monkey.doRound(worryDivisor, leastCommonMultiplier)
toDistribute.forEach {
monkeys[it.key].items.addAll(it.value)
}
}
}
fun measureMonkeyBusinessLevel() = monkeys
.map { it.inspections }
.sortedDescending()
.let { it[0] * it[1] }
}
fun List<String>.parseToMonkey(): Monkey =
Monkey(
name = this[0].split(" ")[1],
items = this[1].split(":")[1].split(",").mapTo(mutableListOf()) { it.trim().toLong() },
operation = this[2].split("= ")[1],
divisor = this[3].split("by ")[1].toLong(),
ifTrueTarget = this[4].split("monkey ")[1].toInt(),
ifFalseTarget = this[5].split("monkey ")[1].toInt(),
)
fun day11part1(input: List<String>): Long {
val monkeys = input.chunked(7).map { it.parseToMonkey() }
val monkeyGang = MonkeyGang(monkeys = monkeys, worryDivisor = 3)
monkeyGang.trigger()
println(monkeyGang.monkeys.map { it.inspections })
return monkeyGang.measureMonkeyBusinessLevel()
}
fun day11part2(input: List<String>): Long {
val monkeys = input.chunked(7).map { it.parseToMonkey() }
val monkeyGang = MonkeyGang(monkeys = monkeys, rounds = 10000)
monkeyGang.trigger()
println(monkeyGang.monkeys.map { it.inspections })
return monkeyGang.measureMonkeyBusinessLevel()
}
fun main() {
val input = readInput("Day11")
println(day11part1(input))
println(day11part2(input))
}
| 0 | Kotlin | 0 | 0 | 7d0803d9b1d6b92212ee4cecb7b824514f597d09 | 3,290 | advent-of-code | Apache License 2.0 |
2022/src/main/kotlin/de/skyrising/aoc2022/day24/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2022.day24
import de.skyrising.aoc.*
private class Day24Setup(val start: Vec2i, val end: Vec2i, val grid: CharGrid, val blizzardsX: Array<Set<Vec2i>>, val blizzardsY: Array<Set<Vec2i>>) {
fun validPos(pos: Vec2i) = pos in grid || pos == start || pos == end
fun blizzardAt(pos: Vec2i, t: Int) = pos in blizzardsX[t % grid.width] || pos in blizzardsY[t % grid.height]
fun dist(start: Vec2i, end: Vec2i, tStart: Int) = (bfsPath(start to tStart, { it.first == end }) { (pos, t) ->
pos.fiveNeighbors().filter { validPos(it) && !blizzardAt(it, t + 1) }.map { it to t + 1 }
} ?: error("No path found")).size - 1
}
private fun parseInput(input: PuzzleInput): Day24Setup {
val grid = input.charGrid.translatedView(Vec2i(-1, -1))
val innerGrid = grid.subGrid(Vec2i(0, 0), Vec2i(grid.width - 2, grid.height - 2))
val empty = grid.where { it == '.' }
val start = empty.first()
val end = empty.last()
val blizzardN = innerGrid.where { it == '^' }
val blizzardE = innerGrid.where { it == '>' }
val blizzardS = innerGrid.where { it == 'v' }
val blizzardW = innerGrid.where { it == '<' }
val blizzardsX = Array<Set<Vec2i>>(innerGrid.width) {
val set = mutableSetOf<Vec2i>()
for (b in blizzardE) set.add(Vec2i((b.x + it).mod(innerGrid.width), b.y))
for (b in blizzardW) set.add(Vec2i((b.x - it).mod(innerGrid.width), b.y))
set
}
val blizzardsY = Array<Set<Vec2i>>(innerGrid.height) {
val set = mutableSetOf<Vec2i>()
for (b in blizzardN) set.add(Vec2i(b.x, (b.y - it).mod(innerGrid.height)))
for (b in blizzardS) set.add(Vec2i(b.x, (b.y + it).mod(innerGrid.height)))
set
}
return Day24Setup(start, end, innerGrid, blizzardsX, blizzardsY)
}
val test = TestInput("""
#.######
#>>.<^<#
#.<..<<#
#>v.><>#
#<^v^^>#
######.#
""")
@PuzzleName("<NAME>")
fun PuzzleInput.part1(): Any {
return parseInput(this).run {
dist(start, end, 0)
}
}
fun PuzzleInput.part2(): Any {
return parseInput(this).run {
val a = dist(start, end, 0)
val b = dist(end, start, a)
val c = dist(start, end, a + b)
log("$a+$b+$c")
a + b + c
}
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,262 | aoc | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem15/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem15
/**
* LeetCode page: [15. 3Sum](https://leetcode.com/problems/3sum/);
*/
class Solution {
/* Complexity:
* Time O(N^2) and Space O(N) where N is the size of nums;
*/
fun threeSum(nums: IntArray): List<List<Int>> {
val sortedNumbers = getSortedNumbers(nums)
return getValidTriplets(sortedNumbers)
}
private fun getSortedNumbers(numbers: IntArray): IntArray {
return numbers.clone().apply { sort() }
}
private fun getValidTriplets(sortedNumbers: IntArray): List<List<Int>> {
if (sortedNumbers.first() > 0 || sortedNumbers.last() < 0) return emptyList()
val leftBound = getLeftBoundIndex(sortedNumbers)
val rightBound = getRightBoundIndex(sortedNumbers)
val validTriplets = hashSetOf<List<Int>>()
val availableThirdNumbers = hashSetOf<Int>().also { it.add(sortedNumbers[leftBound]) }
for (firstIndex in leftBound + 1 until rightBound) {
val firstNumber = sortedNumbers[firstIndex]
for (secondIndex in firstIndex + 1..rightBound) {
val secondNumber = sortedNumbers[secondIndex]
val target = -(firstNumber + secondNumber)
if (target in availableThirdNumbers) validTriplets.add(listOf(firstNumber, secondNumber, target))
}
availableThirdNumbers.add(sortedNumbers[firstIndex])
}
return validTriplets.toList()
}
private fun getLeftBoundIndex(sortedNumbers: IntArray): Int {
val maxTwoSum = sortedNumbers
.lastIndex
.let { sortedNumbers[it] + sortedNumbers[it - 1] }
return sortedNumbers
.binarySearch(-maxTwoSum, 0, sortedNumbers.lastIndex - 1)
.let { biIndex -> if (biIndex < 0) -(biIndex + 1) else biIndex }
}
private fun getRightBoundIndex(sortedNumbers: IntArray): Int {
val minTwoSum = sortedNumbers[0] + sortedNumbers[1]
return sortedNumbers
.binarySearch(-minTwoSum, 2, sortedNumbers.size)
.let { biIndex -> if (biIndex < 0) -(biIndex + 1) else biIndex }
.coerceAtMost(sortedNumbers.lastIndex)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,200 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day09.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | import kotlin.math.abs
data class Coord(var x: Int, var y: Int)
const val dim = 1000
val field = Array(dim) { ByteArray(dim) }
val rope = Array(10) { Coord(dim / 2, dim / 2) }
var hx = dim / 2
var hy = dim / 2
var tx = dim / 2
var ty = dim / 2
fun moveHead(dir: Char) {
when (dir) {
'U' -> hy++
'D' -> hy--
'R' -> hx++
'L' -> hx--
else -> error("wrong dir $dir")
}
}
fun pullTail() {
val dx = hx - tx
val dy = hy - ty
if (dy == 0) tx += dx / 2
else if (dx == 0) ty += dy / 2
else {
tx += if (abs(dy) > 1) dx else dx / 2
ty += if (abs(dx) > 1) dy else dy / 2
}
}
fun moveRopeHead(h: Coord, dir: Char) {
when (dir) {
'U' -> h.y++
'D' -> h.y--
'R' -> h.x++
'L' -> h.x--
else -> error("wrong dir $dir")
}
}
fun pullRope(h: Coord, t: Coord) {
val dx = h.x - t.x
val dy = h.y - t.y
if (dy == 0) t.x = t.x + (dx / 2)
else if (dx == 0) t.y = t.y + (dy / 2)
else if (abs(dy) > 1 && abs(dx) > 1) {
t.x += dx / 2
t.y = t.y + dy / 2
} else {
t.x = t.x + if (abs(dy) > 1) dx else dx / 2
t.y = t.y + if (abs(dx) > 1) dy else dy / 2
}
}
fun main() {
fun part1(input: List<String>): Int {
val field = Array(dim) { ByteArray(dim) }
input.forEach { line ->
val dir = line.first()
val steps = line.substring(2).toInt()
repeat(steps) {
moveHead(dir)
pullTail()
field[tx][ty] = 1
}
}
return field.sumOf { it.sum() }
}
fun part2(input: List<String>): Int {
// val field = Array(dim) { ByteArray(dim) }
// val rope = Array(10) { Coord(dim / 2, dim / 2) }
input.forEach { line ->
val dir = line.first()
val steps = line.substring(2).toInt()
repeat(steps) {
moveRopeHead(rope[0], dir)
for (i in 1..9) {
pullRope(rope[i - 1], rope[i])
}
field[rope[9].x][rope[9].y] = 1
}
}
return field.sumOf { it.sum() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
// println(part1(testInput))
// check(part1(testInput) == 13)
// println(part2(testInput))
// check(part2(testInput) == 36)
val input = readInput("Day09")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 2,552 | AoC-2022 | Apache License 2.0 |
src/day16/day16.kt | diesieben07 | 572,879,498 | false | {"Kotlin": 44432} | package day16
import streamInput
import java.util.*
import kotlin.math.max
data class Valve(val name: String, val rate: Int, val tunnels: Set<String>)
private val regex = Regex("""Valve (\w+) has flow rate=([\d]+); tunnels? leads? to valves? ((?:\w+(?:, )?)+)""")
fun Sequence<String>.parseInput(): Sequence<Valve> {
return map { line ->
val (name, rateR, tunnelsR) = checkNotNull(regex.find(line)).destructured
val rate = rateR.toInt()
val tunnels = tunnelsR.splitToSequence(", ").toSet()
Valve(name, rate, tunnels)
}
}
private data class FNode<T : Any>(val node: T, val f: Int, val predecessor: FNode<T>?)
fun <T : Any> aStar(
start: T,
successors: T.() -> Sequence<T>,
cost: (T, T) -> Int,
estimateToTarget: (T) -> Int,
isTarget: T.() -> Boolean
): List<T>? {
val openList = PriorityQueue<FNode<T>>(compareBy { it.f })
val closedList = HashSet<T>()
val gScore = HashMap<T, Int>()
fun T.withF(f: Int, predecessor: FNode<T>?) = FNode(this, f, predecessor)
fun buildPath(end: FNode<T>): List<T> {
val path = generateSequence(end) { it.predecessor }.map { it.node }.toMutableList()
path.reverse()
return path
}
openList.add(start.withF(0, null))
gScore[start] = 0
do {
val currentNode = openList.poll()
if (currentNode.node.isTarget()) {
return buildPath(currentNode)
}
closedList.add(currentNode.node)
// expand node
for (successor in currentNode.node.successors()) {
if (successor in closedList) continue
val tentativeG = gScore[currentNode.node]!! + cost(currentNode.node, successor)
val existingFNode = openList.find { it.node == successor }
if (existingFNode != null && tentativeG >= gScore[successor]!!) continue
gScore[successor] = tentativeG
val successorF = successor.withF(tentativeG + estimateToTarget(successor), currentNode)
if (existingFNode != null) {
openList.remove(existingFNode)
}
openList.add(successorF)
}
} while (openList.isNotEmpty())
return null
}
private fun <T> Collection<T>.allCombinations(): Sequence<Pair<T, T>> {
return sequence {
for (a in this@allCombinations) {
for (b in this@allCombinations) {
if (a != b) {
yield(Pair(a, b))
}
}
}
}
}
private fun <T> MutableList<T>.swap(a: Int, b: Int) {
if (a != b) {
val t = this[a]
this[a] = this[b]
this[b] = t
}
}
private fun part1() {
// val file = "Day16Example"
val file = "Day16"
streamInput(file) { input ->
val valves = input.parseInput().associateBy { it.name }
fun Valve.successors(): Sequence<Valve> {
return tunnels.asSequence().map { valves[it]!! }
}
val startValve = checkNotNull(valves["AA"])
val relevantValves = valves.values.filter { it.rate != 0 }
check(startValve !in relevantValves)
val paths = valves.values.allCombinations()
.associateWith { (from, to) ->
aStar(
start = from,
successors = Valve::successors,
cost = { a, b -> 1 },
estimateToTarget = { 1 },
isTarget = { this == to }
)!!
}
val workingList = relevantValves.toMutableList()
var maxScore = 0
fun permute(start: Int, minutesPassed: Int, scoreSoFar: Int) {
maxScore = max(maxScore, scoreSoFar)
if (start != workingList.size) {
for (i in start until workingList.size) {
workingList.swap(i, start)
val position = workingList[start]
val path = paths[Pair(if (start == 0) startValve else workingList[start - 1], position)]!!
val addedDistance = path.size - 1
val newMinutesPassed = minutesPassed + addedDistance + 1 // add one minute to open it
if (newMinutesPassed <= 30) { // only keep going down the list if we have time left
val addedScore = position.rate * (30 - newMinutesPassed)
val newScore = scoreSoFar + addedScore
permute(start + 1, newMinutesPassed, newScore)
}
workingList.swap(start, i)
}
}
}
permute(0, 0, 0)
println("max score $maxScore")
}
}
fun main() {
part1()
}
| 0 | Kotlin | 0 | 0 | 0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6 | 4,788 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc22/Day08.kt | asmundh | 573,096,020 | false | {"Kotlin": 56155} | package aoc22
import datastructures.Direction
import readInput
fun List<List<Int>>.heightOfTreeInDirection(direction: Direction, y: Int, x: Int): Int {
if ((y == 0) || (x == 0) || (y == lastIndex) || x == lastIndex) return -1
return when (direction) {
Direction.NORTH -> this[y - 1][x]
Direction.WEST -> this[y][x - 1]
Direction.EAST -> this[y][x + 1]
Direction.SOUTH -> this[y + 1][x]
}
}
fun List<List<Int>>.isVisibleInDirection(direction: Direction, y: Int, x: Int, currentTree: Int): Boolean {
val treeToCheck = heightOfTreeInDirection(direction, y, x)
return ((treeToCheck == -1) || currentTree > treeToCheck)
}
fun List<List<Int>>.isVisibleFromAbove(y: Int, x: Int): Boolean {
for (idx in y downTo 1 step 1) {
val isVisible = isVisibleInDirection(Direction.NORTH, idx, x, this[y][x])
if (!isVisible) return false
}
return true
}
fun List<List<Int>>.isVisibleFromBelow(y: Int, x: Int): Boolean {
for (idx in y until this.size) {
val isVisible = isVisibleInDirection(Direction.SOUTH, idx, x, this[y][x])
if (!isVisible) return false
}
return true
}
fun List<List<Int>>.isVisibleFromRight(y: Int, x: Int): Boolean {
for (idx in x until this[y].size) {
val isVisible = isVisibleInDirection(Direction.EAST, y, idx, this[y][x])
if (!isVisible) return false
}
return true
}
fun List<List<Int>>.isVisibleFromLeft(y: Int, x: Int): Boolean {
for (idx in x downTo 0 step 1) {
val isVisible = isVisibleInDirection(Direction.WEST, y, idx, this[y][x])
if (!isVisible) return false
}
return true
}
fun String.splitToIntList(): List<Int> =
this.map { it.toString().toInt() }
fun day8part1(input: List<String>): Int {
val treeLines = input.map { it.splitToIntList() }
var count = 0
treeLines.forEachIndexed { y, trees ->
trees.forEachIndexed { x, _ ->
val bools = listOf(
treeLines.isVisibleFromAbove(y, x) ||
treeLines.isVisibleFromBelow(y, x) ||
treeLines.isVisibleFromLeft(y, x) ||
treeLines.isVisibleFromRight(y, x)
)
if (bools.any { it }) count += 1
}
}
return count
}
fun day8part2(input: List<String>): Int {
val sum = input.sumOf { it.length }
return sum
}
fun main() {
val input = readInput("Day08")
println(day8part1(input))
println(day8part2(input))
}
| 0 | Kotlin | 0 | 0 | 7d0803d9b1d6b92212ee4cecb7b824514f597d09 | 2,500 | advent-of-code | Apache License 2.0 |
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day16.kt | Guruth | 328,467,380 | false | {"Kotlin": 188298, "Rust": 13289, "Elixir": 1833} | package sh.weller.adventofcode.twentytwenty
import sh.weller.adventofcode.util.product
fun List<String>.day16Part2(): Long {
val splitInput = mutableListOf<List<String>>()
var lastIndex = 0
this.forEachIndexed { index, s ->
if (s == "") {
splitInput.add(this.subList(lastIndex, index))
lastIndex = index + 1
}
if (index == this.size - 1) {
splitInput.add(this.subList(lastIndex, this.size))
}
}
val rules = splitInput[0].createRules()
val myTicket = splitInput[1].drop(1).first().split(",").map { it.toInt() }
val otherTickets = splitInput[2].drop(1)
val validTickets = otherTickets.filter { ticket ->
val parsedTicket = ticket.split(",").map { it.toInt() }
return@filter parsedTicket.map { rules.validNumber(it) }.contains(false).not()
}
val rulesMap = mutableMapOf<Int, MutableList<Int>>()
validTickets
.forEach { ticket ->
val parsedTicket = ticket.split(",").map { it.toInt() }
rules.forEachIndexed { ruleIndex, rule ->
parsedTicket.forEachIndexed { index, i ->
if (rule.validNumber(i)) {
val ruleLIst: MutableList<Int> = rulesMap.getOrDefault(ruleIndex, mutableListOf())
ruleLIst.add(index)
rulesMap[ruleIndex] = ruleLIst
}
}
}
}
val possibleColumnsPerRule = rulesMap.map { ruleMap ->
val ruleColumns = ruleMap.value
val groupedColumns = ruleColumns.groupBy { it }
val sortedColumns = groupedColumns.values.sortedBy { it.size }
val possibleColumns = sortedColumns.filter { it.size == sortedColumns.last().size }.map { it.first() }
val ruleName = rules[ruleMap.key].name
return@map Pair(ruleName, possibleColumns)
}
val determinedRules = mutableListOf<Pair<String, Int>>()
while (determinedRules.size != rules.size) {
possibleColumnsPerRule
.forEach { rule ->
val filteredColumns = rule.second
.filter { possibleColumn ->
if (determinedRules.map { it.second }.contains(possibleColumn)) {
return@filter false
}
return@filter true
}
if (filteredColumns.size == 1) {
determinedRules.add(Pair(rule.first, filteredColumns.single()))
}
}
}
return determinedRules.filter { it.first.startsWith("departure") }
.map { myTicket[it.second] }
.product()
}
fun List<String>.day16Part1(): Int {
val splitInput = mutableListOf<List<String>>()
var lastIndex = 0
this.forEachIndexed { index, s ->
if (s == "") {
splitInput.add(this.subList(lastIndex, index))
lastIndex = index + 1
}
if (index == this.size - 1) {
splitInput.add(this.subList(lastIndex, this.size))
}
}
val rules = splitInput[0].createRules()
val otherTickets = splitInput[2].drop(1)
val invalidFields = otherTickets.flatMap { line -> line.split(",").map { it.toInt() } }
.mapNotNull {
if (!rules.validNumber(it)) {
return@mapNotNull it
}
return@mapNotNull null
}
return invalidFields.sum()
}
private fun Rule.validNumber(number: Int): Boolean {
if (number in (this.rule1.first..this.rule1.second) || number in (this.rule2.first..this.rule2.second)) {
return true
}
return false
}
private fun List<Rule>.validNumber(number: Int): Boolean =
this.map {
if (number in (it.rule1.first..it.rule1.second) || number in (it.rule2.first..it.rule2.second)) {
return@map true
}
return@map false
}.contains(true)
private fun List<String>.createRules(): List<Rule> =
this.map {
val splitLine = it.split(":")
val className = splitLine[0].trim()
val rule1 = splitLine[1].split("or")[0].trim().createRule()
val rule2 = splitLine[1].split("or")[1].trim().createRule()
return@map Rule(className, rule1, rule2)
}
private fun String.createRule(): Pair<Int, Int> =
Pair(this.split("-")[0].toInt(), this.split("-")[1].toInt())
private data class Rule(
val name: String,
val rule1: Pair<Int, Int>,
val rule2: Pair<Int, Int>
) | 0 | Kotlin | 0 | 0 | 69ac07025ce520cdf285b0faa5131ee5962bd69b | 4,526 | AdventOfCode | MIT License |
src/day06/Day06.kt | pnavais | 727,416,570 | false | {"Kotlin": 17859} | package day06
import readInput
enum class Direction { UP, DOWN }
fun traverse(time: Long, refTime: Long, distance: Long, direction: Direction): Long {
var isValid = true
var numWays = 0L
var startTime = time
while (isValid) {
if (startTime.times(refTime.minus(startTime)) > distance) {
numWays++
if (direction == Direction.DOWN) { startTime-- } else { startTime++ }
} else {
isValid = false
}
}
return numWays
}
fun computeWaysForRace(time : Long, distance: Long): Long {
val startTime = time.div(2)
var numWays = traverse(startTime, time, distance, Direction.DOWN)
numWays += traverse(startTime + 1, time, distance, Direction.UP)
return numWays
}
private fun computeAllWays(
times: List<Long>,
distances: List<Long>
): Long {
var ways = 1L
repeat(times.size) {
ways *= computeWaysForRace(times[it], distances[it])
}
return ways
}
fun part1(input: List<String>): Long {
val times = input.first().split(":")[1].trim().split("\\s+".toRegex()).map(String::toLong)
val distances = input.last().split(":")[1].trim().split("\\s+".toRegex()).map(String::toLong)
return computeAllWays(times, distances)
}
fun part2(input: List<String>): Long {
val times = listOf(input.first().split(":")[1].trim().replace("\\s+".toRegex(), "").toLong())
val distances = listOf(input.last().split(":")[1].trim().replace("\\s+".toRegex(), "").toLong())
return computeAllWays(times, distances)
}
fun main() {
val testInput = readInput("input/day06")
println(part1(testInput))
println(part2(testInput))
} | 0 | Kotlin | 0 | 0 | f5b1f7ac50d5c0c896d00af83e94a423e984a6b1 | 1,657 | advent-of-code-2k3 | Apache License 2.0 |
src/Day09.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | import kotlin.math.abs
private val moves = mapOf("R" to Pair(1, 0), "L" to Pair(-1, 0), "U" to Pair(0, 1), "D" to Pair(0, -1))
private data class Point(var x: Int, var y: Int) {
fun move(direction: String, steps: Int) {
x += steps * moves[direction]!!.first
y += steps * moves[direction]!!.second
}
fun isFar(other: Point): Boolean {
return abs(x-other.x) > 1 || abs(y-other.y) > 1
}
operator fun minus(other: Point): Point {
return Point(x-other.x, y-other.y)
}
}
fun main() {
val knotsSize = 2
val knots = buildList { for (i in 1..knotsSize) add(Point(0,0)) }
// Having a set with data class of var types is a bad idea.
// This illustrates the problem: https://pl.kotl.in/q-ixDhSD6.
val visited: MutableSet<Point> = mutableSetOf()
visited.add(Point(0, 0).copy())
val input = readInput("Day09_input")
input.map { it.split(" ").let { l -> Pair(l[0], l[1].toInt()) } }.forEach {
val direction = it.first
val steps = it.second
for (i in 1..steps) {
knots.first().move(direction, 1)
knots.zipWithNext().forEach { pairOfKnots ->
val head = pairOfKnots.first
val tail = pairOfKnots.second
if (tail.isFar(head)) {
val d = head - tail;
when {
tail.x == head.x -> tail.y += ((d.y) / abs(d.y))
tail.y == head.y -> tail.x += ((d.x) / abs(d.x))
else -> {
tail.x += ((d.x) / abs(d.x))
tail.y += ((d.y) / abs(d.y))
}
}
}
}
visited.add(knots.last().copy())
}
}
println(visited.size)
}
| 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 1,830 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | defvs | 572,381,346 | false | {"Kotlin": 16089} | fun main() {
fun part1(input: List<String>) = input.sumOf { rucksack ->
// Create a set of the items in the first compartment
val first = rucksack.substring(0, rucksack.length / 2).toSet()
// Create a set of the items in the second compartment
val second = rucksack.substring(rucksack.length / 2).toSet()
// Find the common item in this rucksack
val common = first.intersect(second).single()
// Return its priority to be added to the sum
if (common.isLowerCase()) {
// Lowercase item types a through z have priorities 1 through 26
common.code - 96
} else {
// Uppercase item types A through Z have priorities 27 through 52
common.code - 38
}
}
fun part2(input: List<String>) = input.indices.step(3).sumOf { i ->
val group = input.subList(i, i + 3)
val badge = group.map { s -> s.toSet() }.reduce { set1, set2 -> set1.intersect(set2) }.single()
if (badge.isLowerCase()) badge.code - 'a'.code + 1 else badge.code - 'A'.code + 27
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput).also { println("Test 1 result was: $it") } == 157)
check(part2(testInput).also { println("Test 2 result was: $it") } == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | caa75c608d88baf9eb2861eccfd398287a520a8a | 1,330 | aoc-2022-in-kotlin | Apache License 2.0 |
2k23/aoc2k23/src/main/kotlin/15.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d15
fun main() {
println("Part 1: ${part1(input.read("15.txt"))}")
println("Part 2: ${part2(input.read("15.txt"))}")
}
fun part1(input: List<String>): Int =
input[0].split(",").sumOf { hash(it) }
fun part2(input: List<String>): Int {
val boxes: MutableMap<Int, MutableMap<String, Int>> = mutableMapOf()
input[0].split(",").forEach { elem ->
if (elem.endsWith("-")) {
val label = elem.replace("-", "")
val hashed = hash(label)
boxes.compute(hashed) { _, lenses -> lenses?.apply { remove(label) } ?: mutableMapOf() }
} else {
val (label, focalLength) = elem.split('=').let { Pair(it[0], it[1].toInt()) }
val hashed = hash(label)
boxes.compute(hashed) { _, lenses ->
lenses?.apply { this[label] = focalLength } ?: mutableMapOf(label to focalLength)
}
}
}
return boxes.entries.sumOf { (box, slots) ->
slots.entries.mapIndexed { slot, (_, focalLength) ->
(box + 1) * (slot + 1) * focalLength
}.sum()
}
}
fun hash(input: String): Int =
input.toCharArray().fold(0) { acc, c ->
var next = acc
next += c.code
next *= 17
next %= 256
next
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 1,276 | aoc | The Unlicense |
src/Day03.kt | riFaulkner | 576,298,647 | false | {"Kotlin": 9466} | fun main() {
fun part1(input: List<String>): Int {
val rucksackPriorities = input.map {rucksack ->
val (comp1, comp2) = getRucksackCompartments(rucksack)
calculatePriority(comp1, comp2)
}
return rucksackPriorities.sum()
}
fun part2(input: List<String>): Int {
val groupCharacters = getGroupBadgeCharacters(input).map {
characterToPriorityValue(it)
}
return groupCharacters.sum()
}
val testInput = readInput("inputs/Day03-example")
part1(testInput).println()
part2(testInput).println()
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("inputs/Day03")
part1(input).println()
part2(input).println()
}
fun getRucksackCompartments(rucksack: String): Pair<String, String> {
val midPoint = rucksack.length/2
return rucksack.subSequence(0, midPoint).toString() to rucksack.subSequence(midPoint,rucksack.length).toString()
}
fun calculatePriority(comp1: String, comp2: String): Int {
val comp1Map = comp1.map {
it to true
}.toMap()
comp2.forEach {
if (comp1Map.contains(it)) {
return characterToPriorityValue(it)
}
}
return 0
}
fun characterToPriorityValue(char: Char): Int {
// 'A' ascii value is 65, offset for that, then because we want lowercase to be a lower priority value
// subtract 26 to shift the whole set
var offset = 64 - 26
if (char.isLowerCase()) {
offset = 96
}
return char.toString().first().code - offset
}
fun getGroupBadgeCharacters(input: List<String>): List<Char> {
val groups = mutableListOf<List<String>>()
val currentGroup = mutableListOf<String>()
input.forEach {
currentGroup.add(it)
if (currentGroup.size == 3) {
groups.add(ArrayList(currentGroup))
currentGroup.clear()
}
}
return groups.map {
findGroupBadgeCharacter(it)
}
}
fun findGroupBadgeCharacter(group: List<String>): Char {
if (group.size != 3) throw IllegalArgumentException("Incorrect Group Size")
val comp1Map = group[0].map {
it to false
}.toMap().toMutableMap()
group[1].forEach {
if (comp1Map.contains(it)) {
comp1Map[it] = true
}
}
group[2].forEach {
if (comp1Map.get(it) == true) {
return it
}
}
throw Exception("Group does not have a badge")
} | 0 | Kotlin | 0 | 0 | 33ca7468e17c47079fe2e922a3b74fd0887e1b62 | 2,481 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Main.kt | Jeff-Gillot | 521,245,168 | false | {"Kotlin": 8976} | import java.io.File
import kotlin.system.measureTimeMillis
fun main() {
val time = measureTimeMillis {
// Read the words and keep only 5 letters words
val textWords = File(Signature::class.java.getResource("words_alpha.txt")!!.toURI())
.readLines()
.filter { it.length == 5 }
// Let's group the words by their signature and only keep the words that have 5 distinct letters
// Also the signature is the same for anagrams since we don't keep track of the order of letters in the signature
val wordsBySignature: Map<Signature, List<String>> = textWords
.groupBy { it.toSignature() }
.filterKeys { it.distinctLetters() == 5 }
// We get the letters and the number of time those letters appears in each signature
// We'll use that to start with the least common letters first
val letterCount = letters.values
.associateWith { letter -> wordsBySignature.keys.fold(0) { acc, signature -> if (letter in signature) acc + 1 else acc } }.toList()
.sortedBy { it.second }
.toMap()
println("--- Letters and occurrences")
letterCount.forEach { (letterSignature, count) -> println("${letterSignature.letter()} -> $count") }
// Fortunately all of those methods keep the order so it's very useful
val orderedLetters = letterCount.keys
// We group the word signatures by the first of the letter from the ordered letters
// This works because we will try to fill in the letters using the same order
val wordsByLetter = wordsBySignature
.keys
.groupBy { word -> orderedLetters.first { letter -> letter in word } }
println("--- Letters and words count associated to it")
wordsByLetter.forEach { (letterSignature, words) -> println("${letterSignature.letter()} -> ${words.size}") }
println("--- Starting the solver loop")
var solution = listOf(WordGroup(emptyList(), Signature.empty))
orderedLetters.forEachIndexed { index, letter ->
val newSolution = mutableListOf<WordGroup>()
//This is all the letters that we tried to add so far + the current one
val expectedLetters = letterCount.keys.take(index + 1).merge()
//We add the previous groups that have all the letters - 1 (we want solution that have 25 of the 26 letters so we can have 1 gap)
solution
.filter { it.signature.commonLetters(expectedLetters).distinctLetters() >= index }
.let { newSolution.addAll(it) }
val wordsToCheck = wordsByLetter[letter] ?: emptyList()
println("${lettersInverted[letter]} -> Words to check ${wordsToCheck.size}")
// Do a cartesian product of the current solutions and words for this letter
// Ignore any word that creates has duplicate letters or that do not have enough distinct letters (1 gap max)
wordsToCheck
.flatMap { word ->
solution
.filter { word !in it }
.map { it + word }
.filter { it.signature.commonLetters(expectedLetters).distinctLetters() >= index }
}
.let { newSolution.addAll(it) }
// Update the solution with the new result
solution = newSolution
println("${lettersInverted[letter]} -> Current solution ${solution.size}")
}
// Now that we the solutions but we probably want to output it
// The solution removed the anagrams and only contains the signatures we need to transform that back into words
val words = solution
.flatMap { it.toWords(wordsBySignature) }
.onEach { println(it.joinToString(" ")) }
println()
println("Total possibilities including anagrams: ${words.size}")
println()
println("Total possibilities excluding anagrams: ${solution.size}")
}
println("${time / 1000.0} seconds")
}
// The signature is a bitset representation of the word each bit represent whether a letter is present or not
@JvmInline
value class Signature(private val value: Int) {
operator fun plus(other: Signature): Signature = Signature(value or other.value)
operator fun contains(other: Signature): Boolean = value and other.value != 0
fun distinctLetters(): Int = value.countOneBits()
fun commonLetters(other: Signature) = Signature(value and other.value)
fun letter(): Char {
if (distinctLetters() == 1) {
return lettersInverted[this]!!
} else {
throw IllegalStateException("There is more than one letter in this signature")
}
}
companion object {
val empty = Signature(0)
}
}
fun Iterable<Signature>.merge(): Signature = fold(Signature.empty) { acc, signature -> acc + signature }
data class WordGroup(
val words: List<Signature>,
val signature: Signature,
) {
operator fun contains(word: Signature): Boolean = word in signature
operator fun plus(word: Signature): WordGroup = WordGroup(words + word, signature + word)
fun toWords(wordsBySignature: Map<Signature, List<String>>): List<List<String>> {
return words
.map { wordSignature -> wordsBySignature[wordSignature]!! }
.fold(emptyList()) { acc, words ->
if (acc.isEmpty()) {
words.map { listOf(it) }
} else {
words.flatMap { word -> acc.map { it + word } }
}
}
}
}
// Each letter has its own signature
val letters = mapOf(
'a' to Signature(0b00000000000000000000000001),
'b' to Signature(0b00000000000000000000000010),
'c' to Signature(0b00000000000000000000000100),
'd' to Signature(0b00000000000000000000001000),
'e' to Signature(0b00000000000000000000010000),
'f' to Signature(0b00000000000000000000100000),
'g' to Signature(0b00000000000000000001000000),
'h' to Signature(0b00000000000000000010000000),
'i' to Signature(0b00000000000000000100000000),
'j' to Signature(0b00000000000000001000000000),
'k' to Signature(0b00000000000000010000000000),
'l' to Signature(0b00000000000000100000000000),
'm' to Signature(0b00000000000001000000000000),
'n' to Signature(0b00000000000010000000000000),
'o' to Signature(0b00000000000100000000000000),
'p' to Signature(0b00000000001000000000000000),
'q' to Signature(0b00000000010000000000000000),
'r' to Signature(0b00000000100000000000000000),
's' to Signature(0b00000001000000000000000000),
't' to Signature(0b00000010000000000000000000),
'u' to Signature(0b00000100000000000000000000),
'v' to Signature(0b00001000000000000000000000),
'w' to Signature(0b00010000000000000000000000),
'x' to Signature(0b00100000000000000000000000),
'y' to Signature(0b01000000000000000000000000),
'z' to Signature(0b10000000000000000000000000),
)
val lettersInverted = mapOf(
Signature(0b00000000000000000000000001) to 'a',
Signature(0b00000000000000000000000010) to 'b',
Signature(0b00000000000000000000000100) to 'c',
Signature(0b00000000000000000000001000) to 'd',
Signature(0b00000000000000000000010000) to 'e',
Signature(0b00000000000000000000100000) to 'f',
Signature(0b00000000000000000001000000) to 'g',
Signature(0b00000000000000000010000000) to 'h',
Signature(0b00000000000000000100000000) to 'i',
Signature(0b00000000000000001000000000) to 'j',
Signature(0b00000000000000010000000000) to 'k',
Signature(0b00000000000000100000000000) to 'l',
Signature(0b00000000000001000000000000) to 'm',
Signature(0b00000000000010000000000000) to 'n',
Signature(0b00000000000100000000000000) to 'o',
Signature(0b00000000001000000000000000) to 'p',
Signature(0b00000000010000000000000000) to 'q',
Signature(0b00000000100000000000000000) to 'r',
Signature(0b00000001000000000000000000) to 's',
Signature(0b00000010000000000000000000) to 't',
Signature(0b00000100000000000000000000) to 'u',
Signature(0b00001000000000000000000000) to 'v',
Signature(0b00010000000000000000000000) to 'w',
Signature(0b00100000000000000000000000) to 'x',
Signature(0b01000000000000000000000000) to 'y',
Signature(0b10000000000000000000000000) to 'z',
)
fun String.toSignature(): Signature = map { letters[it]!! }.merge() | 0 | Kotlin | 1 | 2 | 4b110074945cf161680a6e804038f7fb54e54ca9 | 8,526 | word-clique | MIT License |
src/Day15/Day15.kt | AllePilli | 572,859,920 | false | {"Kotlin": 47397} | package Day15
import checkAndPrint
import discreteDistanceTo
import measureAndPrintTimeMillis
import readInput
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
val lineRgx = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex()
fun List<String>.prepareInput() = map { line ->
val coordinates = lineRgx.matchEntire(line)?.groupValues
?.drop(1)
?.map(String::toInt)
?: throw IllegalArgumentException("line: $line")
Pair(
Sensor(coordinates[0] to coordinates[1]),
Beacon(coordinates[2] to coordinates[3])
)
}
fun Pair<Int, Int>.noPossibleBeacon(beacons: List<Beacon>, sensorRadi: List<Pair<Sensor, Int>>): Boolean {
return if (beacons.contains(Beacon(this))) false
else sensorRadi.any { (sensor, radiusToBeacon) ->
val distance = this.discreteDistanceTo(sensor.coordinate)
distance <= radiusToBeacon
}
}
fun part1(row: Int, input: List<Pair<Sensor, Beacon>>): Int {
val sensors = input.map { it.first }
val beacons = input.map { it.second }.distinct()
val minX = min(sensors.minOf { it.coordinate.first }, beacons.minOf { it.coordinate.first })
val maxX = max(sensors.maxOf { it.coordinate.first }, beacons.maxOf { it.coordinate.first })
val sensorsRadi = input.map { (sensor, beacon) ->
sensor to sensor.coordinate.discreteDistanceTo(beacon.coordinate)
}
val maxRadius = sensorsRadi.maxOf { it.second }
return ((minX - maxRadius)..(maxX + maxRadius)).map { x -> x to row }
.count { currentPos -> currentPos.noPossibleBeacon(beacons, sensorsRadi) }
}
fun part2(maxRange: Int, input: List<Pair<Sensor, Beacon>>): Long {
val freqMultiplier = 4000000L
val sensorsRadi = input.map { (sensor, beacon) ->
sensor to sensor.coordinate.discreteDistanceTo(beacon.coordinate)
}
var x: Int
var y = 0
while (y <= maxRange) {
x = 0
while (x <= maxRange) {
val pos = x to y
val (sensor, radius) = sensorsRadi
.find { (sensor, radius) -> sensor.coordinate.discreteDistanceTo(pos) <= radius }
?: return freqMultiplier * x.toLong() + y.toLong()
x += if (pos.first <= sensor.coordinate.first) {
val dx = sensor.coordinate.first - pos.first
dx + (radius - abs(pos.second - sensor.coordinate.second)) + 1
} else {
val dist = pos.first - sensor.coordinate.first
radius - dist + 1
}
}
y++
}
throw IllegalStateException("No position found")
}
val testInput = readInput("Day15_test").prepareInput()
check(part1(10, testInput) == 26)
check(part2(20, testInput) == 56000011L)
val input = readInput("Day15").prepareInput()
measureAndPrintTimeMillis {
checkAndPrint(part1(2000000, input), 5100463)
}
measureAndPrintTimeMillis {
checkAndPrint(part2(4000000, input), 11557863040754L)
}
}
@JvmInline
private value class Sensor(val coordinate: Pair<Int, Int>)
@JvmInline
private value class Beacon(val coordinate: Pair<Int, Int>) | 0 | Kotlin | 0 | 0 | 614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643 | 3,410 | AdventOfCode2022 | Apache License 2.0 |
src/day13/Day13.kt | Regiva | 573,089,637 | false | {"Kotlin": 29453} | package day13
import readLines
fun main() {
val id = "13"
val testOutput = 13
val testInput = readInput("day$id/Day${id}_test")
println(part1(testInput))
check(part1(testInput) == testOutput)
val input = readInput("day$id/Day$id")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<Packet>): Int {
var index = 0
var count = 0
for ((left, right) in input.chunked(2)) {
index++
if (left <= right) count += index
}
return count
}
private fun part2(input: List<Packet>): Int {
fun divider(value: Int) = Packet.Complex(Packet.Complex(Packet.Simple(value)))
val dividerTwo = divider(2)
val dividerSix = divider(6)
val sortedListWithDividers = (input + listOf(dividerTwo, dividerSix)).sorted()
val indexTwo = sortedListWithDividers.binarySearch(dividerTwo)
val indexSix = sortedListWithDividers.binarySearch(dividerSix)
return (indexTwo + 1) * (indexSix + 1)
}
private fun readInput(fileName: String): List<Packet> {
return readLines(fileName)
.filter(String::isNotEmpty)
.map(::eval)
}
private fun eval(line: String): Packet {
val number = StringBuilder()
val stack = ArrayDeque<Packet?>()
fun pushSimple() {
if (number.isNotEmpty()) {
stack.addFirst(Packet.Simple(number.toString().toInt()))
number.clear()
}
}
fun pushComplex() {
val nested = ArrayDeque<Packet>()
var current = stack.removeFirst()
while (current != null) {
nested.addFirst(current)
current = stack.removeFirst()
}
stack.addFirst(Packet.Complex(nested))
}
for (char in line) {
when (char) {
'[' -> stack.addFirst(null)
',' -> pushSimple()
']' -> {
pushSimple()
pushComplex()
}
else -> number.append(char)
}
}
return checkNotNull(stack.single())
}
private sealed interface Packet : Comparable<Packet> {
data class Simple(val value: Int) : Packet {
override fun compareTo(other: Packet): Int {
return when (other) {
is Simple -> value compareTo other.value
is Complex -> Complex(this) compareTo other
}
}
override fun toString() = value.toString()
}
data class Complex(val list: List<Packet>) : Packet {
constructor(value: Packet) : this(listOf(value))
override fun compareTo(other: Packet): Int {
val left = this
val right = if (other is Complex) other else Complex(other)
for (i in 0..minOf(left.list.lastIndex, right.list.lastIndex)) {
val compare = left.list[i] compareTo right.list[i]
if (compare != 0) return compare
}
return left.list.lastIndex compareTo right.list.lastIndex
}
override fun toString() = list.toString()
}
}
| 0 | Kotlin | 0 | 0 | 2d9de95ee18916327f28a3565e68999c061ba810 | 3,030 | advent-of-code-2022 | Apache License 2.0 |
src/Day16.kt | l8nite | 573,298,097 | false | {"Kotlin": 105683} | import kotlin.system.measureTimeMillis
data class Valve(val id: String, val flowRate: Int = 0, val neighbors: List<String>) {
companion object {
private val valveRegex = "^Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? ((?:\\w+(?:, )?)+)$".toRegex()
fun from(line: String): Valve {
val result = valveRegex.matchEntire(line)
val id = result!!.groups[1]!!.value
val rate = result.groups[2]!!.value.toInt()
val neighbors = result.groups[3]!!.value.split(", ")
return Valve(id, rate, neighbors)
}
}
override fun toString(): String {
return "$id ($flowRate) -> $neighbors"
}
}
data class Path(val valves: List<Valve>, val opened: Map<Valve, Int>, val maxTime: Int = 30) {
fun currentValve(): Valve = valves.last()
fun flowTotal(): Int = opened.map { (valve, time) -> (maxTime - time) * valve.flowRate }.sum()
fun shouldOpenValve(): Boolean {
return currentValve().flowRate > 0 && !opened.containsKey(currentValve())
}
}
data class TrainedElephantPath(val elfValves: List<Valve>, val elephantValves: List<Valve>, val opened: Map<Valve, Int>, val maxTime: Int = 26) {
fun elfCurrentValve(): Valve = elfValves.last()
fun elephantCurrentValve(): Valve = elephantValves.last()
fun flowTotal(): Int = opened.map { (valve, time) -> (maxTime - time) * valve.flowRate }.sum()
fun shouldElfOpenValve(): Boolean {
return elfCurrentValve().flowRate > 0 && !opened.containsKey(elfCurrentValve())
}
fun shouldElephantOpenValve(): Boolean {
return elephantCurrentValve().flowRate > 0 && !opened.containsKey(elephantCurrentValve())
}
}
fun main() {
fun part1(input: List<String>): Int {
val valves = input.map { Valve.from(it) }.associateBy { it.id }
// we start with a single path to explore, with a single valve in the path, and nothing opened
var paths = listOf(
Path(mutableListOf(valves["AA"]!!), HashMap())
)
var bestPath = paths.first()
// start walking...
var time = 1
while (time < 30) {
val exploratoryPaths = mutableListOf<Path>()
// evaluate each path we've started walking on and create a new path to explore for each case:
// 1. we open the current valve (advance time by 1, stay in same position)
// 2. we move to any of the next valves instead
for (path in paths) {
if (path.shouldOpenValve()) {
// create a new exploratory path where we advanced time by 1 tick and opened this valve
exploratoryPaths.add(
Path(path.valves + path.currentValve(), path.opened.toMutableMap().also { it[path.currentValve()] = time })
)
}
exploratoryPaths.addAll(path.currentValve().neighbors.map { neighbor ->
Path(path.valves + valves[neighbor]!!, path.opened.toMap())
})
}
paths = exploratoryPaths.sortedByDescending { it.flowTotal() }.take(10000) // arbitrary
if (paths.first().flowTotal() > bestPath.flowTotal()) {
bestPath = paths.first()
}
time++
}
return bestPath.flowTotal()
}
fun part2(input: List<String>): Int {
val valves = input.map { Valve.from(it) }.associateBy { it.id }
// we start with a single path to explore, with a single valve in the path, and nothing opened
val start = listOf(valves["AA"]!!)
var paths = listOf(
TrainedElephantPath(start, start, HashMap())
)
var bestPath = paths.first()
// start walking...
var time = 1
while (time < 26) {
val exploratoryPaths = mutableListOf<TrainedElephantPath>()
for (path in paths) {
val opened = path.opened.toMutableMap()
// if one (or both) of them is stopping to open the valve, then there is no need to map
// every elf position to every elephant position or vice-versa
if (path.shouldElfOpenValve() || path.shouldElephantOpenValve()) {
val possibleElfValves = if (path.shouldElfOpenValve()) {
opened[path.elfCurrentValve()] = time
listOf(path.elfValves + path.elfCurrentValve())
} else {
path.elfCurrentValve().neighbors.map { neighbor -> path.elfValves + valves[neighbor]!! }
}
val possibleElephantValves = if (path.shouldElephantOpenValve()) {
opened[path.elephantCurrentValve()] = time
listOf(path.elfValves + path.elephantCurrentValve())
} else {
path.elephantCurrentValve().neighbors.map { neighbor -> path.elephantValves + valves[neighbor]!! }
}
for (elfValves in possibleElfValves) {
for (elephantValves in possibleElephantValves) {
exploratoryPaths.add(TrainedElephantPath(elfValves, elephantValves, opened))
}
}
}
// we also need to explore the paths where neither elf nor elephant open a valve
val combinedPaths = path.elfCurrentValve().neighbors.flatMap { elf ->
path.elephantCurrentValve().neighbors.map { elephant ->
elf to elephant
}
}.filter { (a, b) -> a != b } // filter out paths from/to the same valve
.map { (elf, elephant) ->
TrainedElephantPath(path.elfValves + valves[elf]!!, path.elephantValves + valves[elephant]!!, path.opened.toMap() )
}
exploratoryPaths.addAll(combinedPaths)
}
paths = exploratoryPaths.sortedByDescending { it.flowTotal() }.take(10000) // arbitrary
if (paths.first().flowTotal() > bestPath.flowTotal()) {
bestPath = paths.first()
}
time++
}
return bestPath.flowTotal()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
var result: Any
val elapsed1 = measureTimeMillis {
result = part1(input)
}
println("Part 1 Result: $result")
println("Part 1 Time: ${elapsed1}ms")
val elapsed2 = measureTimeMillis {
result = part2(input)
}
println("Part 2 Result: $result")
println("Part 2 Time: ${elapsed2}ms")
} | 0 | Kotlin | 0 | 0 | f74331778fdd5a563ee43cf7fff042e69de72272 | 6,911 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2017/Day24.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2017
import se.saidaspen.aoc.util.Day
fun main() = Day24.run()
data class Port(val inPins: Int, val outPins: Int)
object Day24 : Day(2017, 24) {
private val ports: List<Port> = input.lines().map { it.split("/") }.map { Port(it[0].toInt(), it[1].toInt()) }
override fun part1(): Int {
return findStrongest(ports, 0)
}
private fun findStrongest(ports: List<Port>, numPorts: Int): Int {
val candidates = ports.filter { it.inPins == numPorts || it.outPins == numPorts }.toList()
var strongest = 0
for (candidate in candidates) {
val thisPort = if (candidate.inPins == numPorts) candidate.inPins else candidate.outPins
val nextPorts = if (candidate.inPins == numPorts) candidate.outPins else candidate.inPins
val cand = thisPort + nextPorts + findStrongest(ports.minus(candidate), nextPorts)
strongest = if (strongest < cand) cand else strongest
}
return strongest
}
override fun part2(): Int {
return findLongest(ports, 0, 0).second
}
private fun findLongest(ports: List<Port>, numPorts: Int, level: Int): Pair<Int, Int> {
val candidates = ports.filter { it.inPins == numPorts || it.outPins == numPorts }.toList()
var best = Pair(0, 0)
for (candidate in candidates) {
val thisPort = if (candidate.inPins == numPorts) candidate.inPins else candidate.outPins
val nextPorts = if (candidate.inPins == numPorts) candidate.outPins else candidate.inPins
val longestSub = findLongest(ports.minus(candidate), nextPorts, level + 1)
val cand = Pair(longestSub.first + level, longestSub.second + thisPort + nextPorts)
best = if (cand.first > best.first || (cand.first == best.first && cand.second > best.second)) cand else best
}
return best
}
} | 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,906 | adventofkotlin | MIT License |
src/Day05.kt | nielsz | 573,185,386 | false | {"Kotlin": 12807} | typealias StackLot = Array<ArrayDeque<Char>>
fun main() {
fun part1(stackLot: StackLot, operations: List<List<Int>>): String {
operations.onEach { operation ->
repeat(operation[0]) {
val crate = stackLot[operation[1] - 1].removeLast()
stackLot[operation[2] - 1].addLast(crate)
}
}
return stackLot
.map { it.last() }
.joinToString("")
}
fun part2(stackLot: StackLot, operations: List<List<Int>>): String {
operations.onEach { operation ->
val movableStack = ArrayDeque<Char>()
repeat(operation[0]) {
movableStack.add(stackLot[operation[1] - 1].removeLast())
}
repeat(operation[0]) {
stackLot[operation[2] - 1].addLast(movableStack.removeLast())
}
}
return stackLot
.map { it.last() }
.joinToString("")
}
val input = readInput("Day05")
val (stack, stackCount, operations) = separateStackAndOperations(input)
val op = setupOperations(operations)
println(part1(setupStackLot(stack, stackCount), op)) // GFTNRBZPF
println(part2(setupStackLot(stack, stackCount), op)) // VRQWPDSGP
}
fun setupStackLot(stack: List<String>, stackCount: Int): StackLot {
val stack = stack.map { line ->
line
.chunked(4)
.map { it[1] }
}.reversed()
val stackLot = StackLot(size = stackCount, init = { ArrayDeque() })
for (chars in stack) {
chars.forEachIndexed { index, c ->
if (c != ' ') stackLot[index].add(c)
}
}
return stackLot
}
fun setupOperations(operations: List<String>): List<List<Int>> {
return operations.map {
it
.replace("move ", "")
.replace(" from ", ",")
.replace(" to ", ",")
.split(",").map { int -> int.toInt() }
}
}
fun separateStackAndOperations(input: List<String>): Triple<List<String>, Int, List<String>> {
val stack = mutableListOf<String>()
val operations = mutableListOf<String>()
var stillAddingStack = true
input.forEach { line ->
if (line == "") {
stillAddingStack = false
} else {
if (stillAddingStack) {
stack.add(line)
} else {
operations.add(line)
}
}
}
return Triple(stack.dropLast(1), stack.last().trim().last().digitToInt(), operations)
}
| 0 | Kotlin | 0 | 0 | 05aa7540a950191a8ee32482d1848674a82a0c71 | 2,521 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | dannyrm | 573,100,803 | false | null | import DesiredOutcome.*
import Move.*
import kotlin.reflect.KFunction2
fun main() {
fun part1(input: List<String>): Int {
return input.map { convertToMovePair(it, ::calculatePart1Move) }.sumOf { calculateMoveResult(it) }
}
fun part2(input: List<String>): Int {
return input.map { convertToMovePair(it, ::calculatePart2Move) }.sumOf { calculateMoveResult(it) }
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
fun calculatePart1Move(opponentMove: Move, move: Char): Move {
return when (move) {
'X' -> ROCK
'Y' -> PAPER
'Z' -> SCISSORS
else -> { throw Exception("Unexpected character") }
}
}
fun calculatePart2Move(opponentMove: Move, move: Char): Move {
return when (move) {
'X' -> calculateAppropriateMove(opponentMove, LOSE)
'Y' -> calculateAppropriateMove(opponentMove, DRAW)
'Z' -> calculateAppropriateMove(opponentMove, WIN)
else -> { throw Exception("Unexpected character") }
}
}
fun convertToMovePair(input: String, moveFunc: KFunction2<Move, Char, Move>): Pair<Move, Move> {
val move1 = when (input[0]) {
'A' -> ROCK
'B' -> PAPER
'C' -> SCISSORS
else -> { throw Exception("Unexpected character") }
}
return Pair(move1, moveFunc(move1, input[2]))
}
fun calculateMoveResult(move: Pair<Move, Move>): Int {
val win = 6
val draw = 3
val lose = 0
if (move.first == move.second) {
return draw + move.second.ordinal + 1
}
val result = when (move) {
ROCK to PAPER -> win
PAPER to SCISSORS -> win
SCISSORS to ROCK -> win
else -> lose
}
return result + move.second.ordinal + 1
}
fun calculateAppropriateMove(move: Move, desiredOutcome: DesiredOutcome): Move {
return when (move to desiredOutcome) {
ROCK to WIN -> PAPER
ROCK to LOSE -> SCISSORS
PAPER to WIN -> SCISSORS
PAPER to LOSE -> ROCK
SCISSORS to WIN -> ROCK
SCISSORS to LOSE -> PAPER
else -> move // We want a draw so choose the same move
}
}
enum class Move {
ROCK,
PAPER,
SCISSORS
}
enum class DesiredOutcome {
WIN,
DRAW,
LOSE
}
| 0 | Kotlin | 0 | 0 | 9c89b27614acd268d0d620ac62245858b85ba92e | 2,257 | advent-of-code-2022 | Apache License 2.0 |
2022/src/main/kotlin/day22.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import Day22.Direction.DOWN
import Day22.Direction.LEFT
import Day22.Direction.RIGHT
import Day22.Direction.UP
import utils.Grid
import utils.IntGrid
import utils.Parser
import utils.Solution
import utils.Vec2i
import utils.badInput
fun main() {
Day22.run()
}
object Day22 : Solution<Pair<Grid<Char>, List<Day22.Insn>>>() {
override val name = "day22"
override val parser = Parser.compound(Parser.charGrid) {
buildList {
var acc = 0
for (char in it.trim()) {
if (char.isDigit()) {
acc = acc * 10 + char.digitToInt()
continue
}
if (acc != 0) {
add(Insn.Forward(acc))
acc = 0
}
if (char == 'L') {
add(Insn.RotateL)
} else if (char == 'R') {
add(Insn.RotateR)
} else {
badInput()
}
}
if (acc != 0) {
add(Insn.Forward(acc))
}
}
}
sealed class Insn {
data class Forward(val amount: Int) : Insn()
object RotateL : Insn()
object RotateR : Insn()
}
enum class Direction(val v: Vec2i, val score: Int) {
RIGHT(Vec2i(1, 0), 0),
DOWN(Vec2i(0, 1), 1),
LEFT(Vec2i(-1, 0), 2),
UP(Vec2i(0, -1), 3),
}
data class State(
val facing: Direction,
val location: Vec2i,
)
private fun apply(grid: Grid<Char>, edgeMap: IntGrid, edgeRules: Map<Pair<Int, Direction>, Pair<Direction, (Vec2i) -> Vec2i>>, state: State, insn: Insn, part2: Boolean): State {
return when (insn) {
Insn.RotateR -> state.copy(facing = Direction.values().first { it.score == (state.facing.score + 1) % 4 })
Insn.RotateL -> state.copy(facing = Direction.values().first { it.score == (state.facing.score + 3) % 4 })
is Insn.Forward -> {
var pos = state.location
var direction = state.facing
repeat(insn.amount) {
var newPos = pos + direction.v
var newDirection = direction
// if ' ' or out of bounds then wrap according to direction
if (newPos !in grid || grid[newPos] == ' ') {
if (part2) {
val rule = edgeRules[edgeMap[pos] to direction]!!
newDirection = rule.first
newPos = rule.second(pos)
// println("Ported from ${edgeMap[pos]} $pos / $direction to ${edgeMap[newPos]} $newPos / $newDirection")
} else {
newPos = when (direction) {
RIGHT -> grid.getRow(newPos.y).cells.first { it.second != ' ' }.first
DOWN -> grid[newPos.x].cells.first { it.second != ' ' }.first
LEFT -> grid.getRow(newPos.y).cells.last { it.second != ' ' }.first
UP -> grid[newPos.x].cells.last { it.second != ' ' }.first
}
}
}
if (grid[newPos] == '#') {
// if hitting a wall, don't move any more
return@repeat
}
pos = newPos
direction = newDirection
}
state.copy(location = pos, facing = direction)
}
}
}
override fun part1(input: Pair<Grid<Char>, List<Insn>>): Int {
return solve(input, false)
}
override fun part2(input: Pair<Grid<Char>, List<Insn>>): Int {
return solve(input, true)
}
private fun solve(input: Pair<Grid<Char>, List<Insn>>, part2: Boolean): Int {
val (grid, insns) = input
val initialPos = Vec2i(grid.getRow(0).values.indexOfFirst { it == '.' }, 0)
var state = State(RIGHT, initialPos)
val isTest = grid.width < 20
val edgeMap = if (isTest) {
IntGrid(grid.width, grid.height) { c ->
// 1
// 234
// 56
when (c / 4) {
Vec2i(2, 0) -> 1
Vec2i(0, 1) -> 2
Vec2i(1, 1) -> 3
Vec2i(2, 1) -> 4
Vec2i(2, 2) -> 5
Vec2i(3, 2) -> 6
else -> 0
}
}
} else {
// 12
// 3
// 45
// 6
IntGrid(grid.width, grid.height) { c ->
when (c / 50) {
Vec2i(1, 0) -> 1
Vec2i(2, 0) -> 2
Vec2i(1, 1) -> 3
Vec2i(0, 2) -> 4
Vec2i(1, 2) -> 5
Vec2i(0, 3) -> 6
else -> 0
}
}
}
val edgeRules: Map<Pair<Int, Direction>, Pair<Direction, (Vec2i) -> Vec2i>> = if (isTest) buildMap {
// 1
// 234
// 56
put(1 to RIGHT, LEFT to { v -> Vec2i(15, 8 + (v.y - 3)) }) // to 6
put(1 to LEFT, DOWN to { v -> Vec2i(4 + v.y, 4) }) // to 3
put(1 to UP, DOWN to { v -> Vec2i(3 - (v.x - 8), 4) }) // to 2
put(2 to LEFT, UP to { v -> Vec2i(12 + (7 - v.y), 11) }) // to 6
put(2 to UP, DOWN to { v -> Vec2i(8 + (v.x - 3), 0) }) // to 1
put(2 to DOWN, UP to { v -> Vec2i(8 + (v.x - 3), 11) }) // to 5
put(3 to UP, RIGHT to { v -> Vec2i(8, (v.x - 4)) }) // to 1
put(3 to DOWN, RIGHT to { v -> Vec2i(8, 4 + v.x) }) // to 5
put(4 to RIGHT, DOWN to { v -> Vec2i(15 - (v.y - 4), 8) }) // to 6
put(5 to LEFT, UP to { v -> Vec2i(4 + (3 - (v.y - 8)), 7) }) // to 3
put(5 to DOWN, UP to { v -> Vec2i(3 - (v.x - 8), 7) }) // to 2
put(6 to UP, LEFT to { v -> Vec2i(11, 4 + (3 - (v.x - 12))) }) // to 4
put(6 to RIGHT, LEFT to { v -> Vec2i(11, (3 - (v.y - 8))) }) // to 1
put(6 to DOWN, RIGHT to { v -> Vec2i(0, 4 + (3 - (v.x - 12))) }) // to 2
} else buildMap {
// 12
// 3
// 45
// 6
put(1 to LEFT, RIGHT to { v -> Vec2i(0, 100 + (49 - v.y)) }) // to 4
put(1 to UP, RIGHT to { v -> Vec2i(0, 150 + (v.x - 50)) }) // to 6
put(2 to UP, UP to { v -> Vec2i(v.x - 100, 199) }) // to 6
put(2 to RIGHT, LEFT to { v -> Vec2i(99, 149 - v.y) }) // to 5
put(2 to DOWN, LEFT to { v -> Vec2i(99, 50 + (v.x - 100)) }) // to 3
put(3 to LEFT, DOWN to { v -> Vec2i(v.y - 50, 100) }) // to 4
put(3 to RIGHT, UP to { v -> Vec2i(v.y - 50 + 100, 49) }) // to 2
put(4 to LEFT, RIGHT to { v -> Vec2i(50, 49 - (v.y - 100)) }) // to 1
put(4 to UP, RIGHT to { v -> Vec2i(50, 50 + v.x) }) // to 3
put(5 to RIGHT, LEFT to { v -> Vec2i(149, 49 - (v.y - 100)) }) // to 2
put(5 to DOWN, LEFT to { v -> Vec2i(49, 150 + (v.x - 50)) }) // to 6
put(6 to RIGHT, UP to { v -> Vec2i(50 + (v.y - 150), 149) }) // to 5
put(6 to DOWN, DOWN to { v -> Vec2i(100 + v.x, 0) }) // to 2
put(6 to LEFT, DOWN to { v -> Vec2i(50 + (v.y - 150), 0) }) // to 1
}
insns.forEach {
state = apply(grid, edgeMap, edgeRules, state, it, part2)
}
return state.facing.score + (state.location.y + 1) * 1000 + (state.location.x + 1) * 4
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 6,624 | aoc_kotlin | MIT License |
src/Day14.kt | ricardorlg-yml | 573,098,872 | false | {"Kotlin": 38331} | import java.lang.Integer.max
import java.lang.Integer.min
class Day14Solver(private val input: List<String>) {
private var maxCol: Int = -1
private var maxRow: Int = -1
data class Path(val point1: Point, val point2: Point) {
fun range(): List<Point> {
return if (point1.row == point2.row) {
(min(point1.col, point2.col)..max(point1.col, point2.col)).map { col ->
Point(point1.row, col)
}
} else if (point1.col == point2.col) {
(min(point1.row, point2.row)..max(point1.row, point2.row)).map { row ->
Point(row, point1.col)
}
} else {
throw IllegalArgumentException("Invalid path")
}
}
}
data class Point(val row: Int, val col: Int) {
fun neighbors(part2: Boolean = false, maxRow: Int = -1): List<Point> {
return if (part2 && row == maxRow) {
listOf(Point(row, col), Point(row, col - 1), Point(row, col + 1))
} else {
listOf(Point(row + 1, col), Point(row + 1, col - 1), Point(row + 1, col + 1))
}
}
}
private fun parseInput(infinityFloor: Boolean = false, rowMapper: (Int) -> Int): Array<CharArray> {
val points = input.map { line ->
line.split("->")
.map { p ->
val (x, y) = p.trim().split(",")
Point(y.toInt(), x.toInt())
}
}
val mc = points.flatten().minBy { it.col }.col
maxCol = points.flatten().maxBy { it.col }.col + mc
maxRow = rowMapper(points.flatten().maxBy { it.row }.row)
val grid =
Array(maxRow) { i ->
CharArray(maxCol + 1) {
if (infinityFloor) {
'.'.takeIf { i < maxRow - 1 } ?: '#'
} else
'.'
}
}
points
.flatMap {
it.zipWithNext().map { (p1, p2) -> Path(p1, p2) }
}.forEach { path ->
path.range().forEach { p ->
grid[p.row][p.col] = '#'
}
}
return grid
}
private tailrec fun nextPoint(grid: Array<CharArray>, point: Point, part2: Boolean): Point {
val neighbors = point.neighbors(part2, grid.lastIndex)
if (neighbors.all { kotlin.runCatching { grid[it.row][it.col] }.getOrDefault('#') != '.' }) {
return point
}
val nextPoint = neighbors.first { grid[it.row][it.col] == '.' }
return nextPoint(grid, nextPoint, part2)
}
fun solvePart1(): Int {
val grid = parseInput { it + 1 }
var counter = 0
val start = Point(0, 500)
while (true) {
val next = nextPoint(grid, start, false)
if (next.row >= grid.lastIndex) {
break
}
grid[next.row][next.col] = 'o'
counter++
}
return counter
}
fun solvePart2(): Int {
val grid = parseInput(true) { it + 3 }
var counter = 0
val start = Point(0, 500)
while (true) {
val next = nextPoint(grid, start, true)
grid[next.row][next.col] = 'o'
counter++
if (next == start)
break
}
return counter
}
}
fun main() {
// val data = readInput("Day14_test")
val data = readInput("Day14")
val solver = Day14Solver(data)
// check(solver.solvePart1() == 24)
// check(solver.solvePart2() == 93)
println(solver.solvePart1())
println(solver.solvePart2())
} | 0 | Kotlin | 0 | 0 | d7cd903485f41fe8c7023c015e4e606af9e10315 | 3,726 | advent_code_2022 | Apache License 2.0 |
src/Day04.kt | cvb941 | 572,639,732 | false | {"Kotlin": 24794} | fun main() {
fun processInput(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map {
val (first, second) = it.split(",")
val (firstFirst, firstSecond) = first.split("-")
val (secondFirst, secondSecond) = second.split("-")
(firstFirst.toInt()..firstSecond.toInt()) to (secondFirst.toInt()..secondSecond.toInt())
}
}
fun part1(input: List<String>): Int {
return processInput(input).map { (first, second) ->
first.all { it in second } || second.all { it in first }
}.map { if (it) 1 else 0 }.sum()
}
fun part2(input: List<String>): Int {
return processInput(input).map { (first, second) ->
first.any { it in second } || second.any { it in first }
}.map { if (it) 1 else 0 }.sum()
}
// 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 | fe145b3104535e8ce05d08f044cb2c54c8b17136 | 1,121 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day05.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | fun main() {
data class Common(val input: List<String>) {
lateinit var moves: List<String>
lateinit var stacks: List<ArrayDeque<Char>>
init {
parse()
}
fun parse() {
val map = input.groupBy {
when {
it.contains("move") -> "moves"
it.contains("[") -> "crates"
else -> "garbage"
}
}
val maxStringLength = map["crates"]!!.maxOf { it.length }
val crates = map["crates"]!!
.map {
it.padEnd(maxStringLength)
.toList()
.chunked(4)
.map { list -> list[1] }
}
val rowLength = crates.first().size
stacks = List(rowLength) { ArrayDeque() }
crates.forEach {
it.forEachIndexed {
i, c -> stacks[i].addLast(c)
}
}
moves = map["moves"]!!.map {
it.replace("move", "")
.replace("from", "")
.replace("to", "")
.trim()
}
}
}
fun part1(input: List<String>): String {
val common = Common(input)
common.moves.forEach {
val (count, from, to) = it.split(" ").filterNot { s -> s.isBlank() }.map { n -> n.toInt() }
repeat (count) {
var element: Char
do {
element = common.stacks[from - 1].removeFirst()
} while(element == ' ')
common.stacks[to-1].addFirst(element)
}
}
return List(common.stacks.size) { i ->
common.stacks[i].removeFirst()
}.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val main = Common(input)
main.moves.forEach {
val (count, from, to) = it.split(" ").filterNot { s -> s.isBlank() }.map { n -> n.toInt() }
val cratesToMove = mutableListOf<Char>()
repeat (count) {
if (main.stacks[from -1].isNotEmpty()) {
var element: Char
do {
element = main.stacks[from - 1].removeFirst()
if (element != ' ') {
cratesToMove.add(element)
}
} while (element == ' ')
}
}
cratesToMove.reversed().forEach { c ->
main.stacks[to - 1].addFirst(c)
}
}
return List(main.stacks.size) { i ->
main.stacks[i].removeFirst()
}.joinToString(separator = "")
}
val input = readInput("inputs/Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 2,905 | aoc-2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day04.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
part1()
part2()
}
private fun part1() {
val points = readInput(2023, 4).useLines { lines ->
lines.sumOf { line ->
val (winner, own) = line.split(" | ")
val numbers = winner.substringAfter(": ").trim().split(" +".toRegex()).mapTo(hashSetOf()) { it.toInt() }
val ownNumbers = own.trim().split(" +".toRegex()).mapTo(hashSetOf()) { it.toInt() }
val winCount = numbers.intersect(ownNumbers).size
if (winCount == 0) 0 else 1 shl winCount - 1
}
}
println(points)
}
private fun part2() {
val game = readInput(2023, 4).readLines()
val wins = IntArray(game.size) { 1 }
for (i in game.indices) {
val (winner, own) = game[i].split(" | ")
val numbers = winner.substringAfter(": ").trim().split(" +".toRegex()).mapTo(hashSetOf()) { it.toInt() }
val ownNumbers = own.trim().split(" +".toRegex()).mapTo(hashSetOf()) { it.toInt() }
val winCount = numbers.intersect(ownNumbers).size
val max = minOf(i + winCount, game.lastIndex)
for (j in i+1..max) wins[j] += wins[i]
}
val total = wins.fold(0) { acc, n -> acc + n }
println(total)
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,297 | adventofcode | Apache License 2.0 |
src/Day04.kt | sebastian-heeschen | 572,932,813 | false | {"Kotlin": 17461} | fun main() {
fun part1(input: List<String>): Int = intRanges(input)
.count { (firstSections, secondSections) ->
firstSections.all { secondSections.contains(it) } || secondSections.all { firstSections.contains(it) }
}
fun part2(input: List<String>): Int {
return intRanges(input)
.count { (firstSections, secondSections) ->
firstSections.any { secondSections.contains(it) }
}
}
// 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))
}
fun intRanges(input: List<String>) = input
.map { it.ranges() }
.map { (first, second) -> first.intRange() to second.intRange() }
fun String.intRange(): IntRange {
val delimiter = '-'
return (substringBefore(delimiter).toInt()..substringAfter(delimiter).toInt())
}
fun String.ranges(): Pair<String, String> {
val delimiter = ','
return substringBefore(delimiter) to substringAfter(delimiter)
}
| 0 | Kotlin | 0 | 0 | 4432581c8d9c27852ac217921896d19781f98947 | 1,163 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | class Node(val name: String, val parent: Node? = null, val children: MutableMap<String, Node> = mutableMapOf(), val size: Long = 0) {
override fun toString(): String {
return name + " " + (if (children.isEmpty()) size else "dir")
}
}
fun main() {
fun putNode(cur: Node, dir: String, size: Long = 0) = cur.children.computeIfAbsent(dir) { Node(dir, cur, size = size) }
fun buildTree(input: List<String>): Node {
val root = Node("/")
var cur = root
var i = 0
while (i < input.size) {
val line = input[i++]
val cd = "$ cd "
if (line.startsWith(cd)) {
val dir = line.substring(cd.length)
cur = when (dir) {
".." -> cur.parent!!
"/" -> root
else -> putNode(cur, dir)
}
} else if (line == "$ ls") {
while (i < input.size && !input[i].startsWith("$")) {
val lsLine = input[i++]
val part = lsLine.split(" ")
putNode(cur, part[1], if (part[0] == "dir") 0 else part[0].toLong())
}
}
}
return root
}
fun dfs(root: Node, directorySizeCallback: (Long) -> Unit): Long {
if (root.children.isEmpty()) {
return root.size
}
val sum = root.children.values.sumOf { dfs(it, directorySizeCallback) }
directorySizeCallback(sum)
return sum
}
fun part1(input: List<String>): Long {
val root = buildTree(input)
var res = 0L
dfs(root) {
if (it <= 100000) {
res += it
}
}
return res
}
fun part2(input: List<String>): Long {
val root = buildTree(input)
val sizes: MutableList<Long> = mutableListOf()
var rootSize = 0L
dfs(root) {
sizes.add(it)
rootSize = it
}
sizes.sort()
return sizes.find { 70000000 - rootSize + it >= 30000000 }!!
}
part1(readInput("input")).println()
part2(readInput("input")).println()
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 2,168 | advent-of-code-2022 | Apache License 2.0 |
src/day4/Day04.kt | francoisadam | 573,453,961 | false | {"Kotlin": 20236} | package day4
import readInput
fun main() {
fun part1(input: List<String>): Int {
return input.map { row ->
row.split(",").map { it.toAssignment() }.isDuplicate()
}.map { overlapping -> if (overlapping) 1 else 0 }.sum()
}
fun part2(input: List<String>): Int {
return input.map { row ->
row.split(",").map { it.toAssignment() }.isOverlapping()
}.map { overlapping -> if (overlapping) 1 else 0 }.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day4/Day04_test")
val testPart1 = part1(testInput)
println("testPart1: $testPart1")
val testPart2 = part2(testInput)
println("testPart2: $testPart2")
check(testPart1 == 2)
check(testPart2 == 4)
val input = readInput("day4/Day04")
println("part1 : ${part1(input)}")
println("part2 : ${part2(input)}")
}
private data class Assignment(
val fromID: Int,
val toID: Int,
)
private fun String.toAssignment(): Assignment = this.split("-").let {
Assignment(
fromID = it.first().toInt(),
toID = it.last().toInt(),
)
}
private fun List<Assignment>.isDuplicate(): Boolean =
(first().fromID >= last().fromID && first().toID <= last().toID) ||
(last().fromID >= first().fromID && last().toID <= first().toID)
private fun List<Assignment>.isOverlapping(): Boolean =
(first().fromID in (last().fromID..last().toID)) ||
(first().toID in (last().fromID..last().toID)) ||
(last().fromID in (first().fromID..first().toID)) ||
(last().toID in (first().fromID..first().toID)) | 0 | Kotlin | 0 | 0 | e400c2410db4a8343c056252e8c8a93ce19564e7 | 1,663 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/dp/LOS.kt | yx-z | 106,589,674 | false | null | package dp
import util.OneArray
import util.max
import util.oneArrayOf
// longest oscillating subsequence
// X[1..n] is oscillating if X[i] < X[i + 1] for even i, and X[i] > X[i + 1] for odd i
// find the length of los of A[1..n]
fun main(args: Array<String>) {
val A = intArrayOf(-1 /* ignored value to be one-indexed */, 1, 25, 9, 20, 5)
// println(los(A))
val B = oneArrayOf(1, 25, 9, 20, 5)
println(B.los())
}
fun los(A: IntArray): Int {
val n = A.size - 1
// los(i): len of los for A[i..n] starting at A[i]
// we want max{ los(i) : i in 1..n }
// define lo's(i): len of lo's for A[i..n] starting at A[i], lo's is the longest oscillating'
// subsequence where X[i] < X[i +1] for odd i, and X[i] > X[i + 1] for even i
// los(i), los'(i) = 0 i > n
// assume max {} = 0
// los(i) = max { lo's(k) : i < k <= n && A[k] > A[i] } + 1
// lo's(i) = max { los(k) : i < k <= n && A[k] < A[i] } + 1
val los = IntArray(n + 1)
val loos = IntArray(n + 1)
for (i in n downTo 1) {
los[i] = (loos.filterIndexed { idx, _ -> idx in i + 1 until n && A[idx] > A[i] }.max()
?: 0) + 1
loos[i] = (los.filterIndexed { idx, _ -> idx in i + 1 until n && A[idx] < A[i] }.max()
?: 0) + 1
}
// println(Arrays.toString(los))
// println(Arrays.toString(loos))
return los[1]
}
fun OneArray<Int>.los(): Int {
val A = this
val n = size
// los(i): len of los of A[i..n] that MUST include A[i]
// loos(i): len of loos of A[i..n] that MUST include A[i]
// where loos of X[1..n] satisfies the reversed condition of los of X
// memoization structure: two 1d arrs, los[1..n], loos[1..n]
val los = OneArray(n) { 1 }
val loos = OneArray(n) { 1 }
// assuming max { } = 0
// los(i) = 1 + max_k { loos(k) } where k > i and A[k] < A[i]
// loos(i) = 1 + max_k { los(k) } where k > i and A[k] > A[i]
// dependency: los(i), loos(i) depends on loos(k), los(k), where k > i
// that is, entries to the right
// eval order: outer loop for i decreasing from n - 1 down to 1
for (i in n - 1 downTo 1) {
// inner loop k with no specific order, say increasing from i + 1 to n
los[i] = 1 + ((i + 1..n)
.filter { k -> A[k] < A[i] }
.map { k -> loos[k] }
.max() ?: 0)
loos[i] = 1 + ((i + 1..n)
.filter { k -> A[k] > A[i] }
.map { k -> los[k] }
.max() ?: 0)
}
// time: O(n^2)
// los.prettyPrintln()
// loos.prettyPrintln()
// we want max_i { los(i) }
return los.max() ?: 0
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,426 | AlgoKt | MIT License |
src/com/ncorti/aoc2023/Day01.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
import kotlin.math.max
fun main() {
fun part1() = getInputAsText("01") {
split("\n")
}
.filterNot(String::isBlank)
.map(String::toCharArray)
.sumOf { array ->
val firstDigit = array.first { it.isDigit() }.digitToInt()
val lastDigit = array.last { it.isDigit() }.digitToInt()
(firstDigit * 10) + lastDigit
}
fun part2() = getInputAsText("01") {
split("\n")
}
.filterNot(String::isBlank)
.sumOf { input ->
val firstDigitIndex = if (input.indexOfFirst { it.isDigit() } == -1) input.length else input.indexOfFirst { it.isDigit() }
val firstSubstring = input.substring(0, firstDigitIndex)
val firstDigit = if (firstSubstring.containsSpelledNumber()) {
firstSubstring.firstSpelledNumber()
} else {
input.first { it.isDigit() }.digitToInt()
}
val lastDigitIndex = max(input.indexOfLast { it.isDigit() } + 1, 0)
val lastSubstring = input.substring(lastDigitIndex)
val lastDigit = if (lastSubstring.containsSpelledNumber()) {
lastSubstring.lastSpelledNumber()
} else {
input.last { it.isDigit() }.digitToInt()
}
(firstDigit * 10L) + lastDigit
}
println(part1())
println(part2())
}
private fun String.firstSpelledNumber(): Int =
mapOf(
1 to this.indexOf("one"),
2 to this.indexOf("two"),
3 to this.indexOf("three"),
4 to this.indexOf("four"),
5 to this.indexOf("five"),
6 to this.indexOf("six"),
7 to this.indexOf("seven"),
8 to this.indexOf("eight"),
9 to this.indexOf("nine"),
).filter { (_, value) -> value != -1 }
.minBy { (_, value) -> value }
.let {(key, _) -> key}
private fun String.lastSpelledNumber(): Int =
mapOf(
1 to this.lastIndexOf("one"),
2 to this.lastIndexOf("two"),
3 to this.lastIndexOf("three"),
4 to this.lastIndexOf("four"),
5 to this.lastIndexOf("five"),
6 to this.lastIndexOf("six"),
7 to this.lastIndexOf("seven"),
8 to this.lastIndexOf("eight"),
9 to this.lastIndexOf("nine"),
).filter { (_, value) -> value != -1 }
.maxBy { (_, value) -> value }
.let {(key, _) -> key}
private fun String.containsSpelledNumber(): Boolean =
"one" in this || "two" in this || "three" in this || "four" in this || "five" in this || "six" in this || "seven" in this || "eight" in this || "nine" in this
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 2,658 | adventofcode-2023 | MIT License |
src/Day05.kt | razvn | 573,166,955 | false | {"Kotlin": 27208} | fun main() {
val day = "Day05"
fun part1(input: List<String>): String {
val (creates, cmds) = load(input)
cmds.forEach { c ->
val take = creates[c.from]!!.take(c.number)
creates[c.from] = creates[c.from]!!.drop(c.number)
take.forEach {
creates[c.to] = "$it${creates[c.to]}"
}
}
return creates.values.map { it.firstOrNull() ?: "" }.joinToString("")
}
fun part2(input: List<String>): String {
val (creates, cmds) = load(input)
cmds.forEach { c ->
val take = creates[c.from]!!.take(c.number)
creates[c.from] = creates[c.from]!!.drop(c.number)
creates[c.to] = "$take${creates[c.to]}"
}
return creates.values.map { it.firstOrNull() ?: "" }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
// println(part1(testInput))
// println(part2(testInput))
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput(day)
println(part1(input))
println(part2(input))
}
private fun load(input: List<String>): Pair<MutableMap<Int, String>, List<Command>> {
val buffer = mutableMapOf<Int, String>()
val commands = mutableListOf<Command>()
val start = 1
val nbCrates = (input.first().length + 1) / 4
(1..nbCrates).forEach { buffer[it] = "" }
input.forEach { line ->
if (line.trim().startsWith("[")) {
(1..nbCrates).forEach { nb ->
val index = start + (nb - 1) * 4
val char = line[index]
buffer[nb] = "${buffer[nb]}$char".trim()
}
}
if (line.startsWith("move")) {
commands.add(parseCommand(line))
}
}
return buffer to commands
}
private data class Command(val number: Int, val from: Int, val to: Int)
private val regEx = """move (\d*) from (\d*) to (\d*)""".toRegex()
private fun parseCommand(line: String): Command {
val result = regEx.find(line.trim())
val (nb, from, to) = result!!.destructured
return Command(nb.toInt(), from.toInt(), to.toInt())
}
| 0 | Kotlin | 0 | 0 | 73d1117b49111e5044273767a120142b5797a67b | 2,228 | aoc-2022-kotlin | Apache License 2.0 |
src/Day13.kt | pavlo-dh | 572,882,309 | false | {"Kotlin": 39999} | sealed class E : Comparable<E>
class L(vararg elements: E) : E() {
val elements = mutableListOf(*elements)
override fun compareTo(other: E): Int = when (other) {
is L -> {
elements.forEachIndexed { index, element ->
val otherElement = other.elements.getOrNull(index) ?: return 1
val comparisonResult = element.compareTo(otherElement)
if (comparisonResult != 0) return comparisonResult
}
if (other.elements.size > elements.size) -1 else 0
}
is I -> this.compareTo(L(other))
}
override fun toString() = elements.joinToString(separator = ",", prefix = "[", postfix = "]")
}
class I(val value: Int) : E() {
override fun compareTo(other: E) = when (other) {
is I -> value.compareTo(other.value)
is L -> L(this).compareTo(other)
}
override fun toString() = value.toString()
}
fun main() {
fun findSubListEnd(elementsString: String, subListStart: Int): Int {
var bracketsCounter = 1
for (i in subListStart + 1..elementsString.lastIndex) {
if (elementsString[i] == ']') {
bracketsCounter--
if (bracketsCounter == 0) {
return i
}
} else if (elementsString[i] == '[') {
bracketsCounter++
}
}
error("Sublist end not found.")
}
fun parseElementsString(elementsString: String): L {
var index = 0
val l = L()
while (index < elementsString.length) {
if (elementsString[index] == '[') {
val subListEnd = findSubListEnd(elementsString, index)
val subListString = elementsString.substring(index + 1, subListEnd)
val subList = parseElementsString(subListString)
l.elements.add(subList)
index = subListEnd + 2
} else {
var delimiterIndex = elementsString.indexOf(',', startIndex = index + 1)
if (delimiterIndex == -1) delimiterIndex = elementsString.length
val integerString = elementsString.substring(index, delimiterIndex)
val integer = I(integerString.toInt())
l.elements.add(integer)
index = delimiterIndex + 1
}
}
return l
}
fun parseInput(input: List<String>): List<L> = input.chunked(3).flatMap { (firstString, secondString) ->
val firstPacket = parseElementsString(firstString.substring(1, firstString.lastIndex))
val secondPacket = parseElementsString(secondString.substring(1, secondString.lastIndex))
listOf(firstPacket, secondPacket)
}
fun part1(input: List<String>): Int {
val packets = parseInput(input)
val comparisons = packets.chunked(2).map { (firstPacket, secondPacket) ->
firstPacket.compareTo(secondPacket)
}
return comparisons.withIndex().sumOf { (index, value) ->
if (value == -1) index + 1 else 0
}
}
fun part2(input: List<String>): Int {
val firstDividerPacketString = "[[2]]"
val secondDividerPacketString = "[[6]]"
val packets = parseInput(input + listOf("\n", firstDividerPacketString, secondDividerPacketString))
val packetsAsStringsSorted = packets.sorted().map(L::toString)
val firstDividerPacketIndex = packetsAsStringsSorted.indexOf(firstDividerPacketString) + 1
val secondDividerPacketIndex = packetsAsStringsSorted.indexOf(secondDividerPacketString) + 1
return firstDividerPacketIndex * secondDividerPacketIndex
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992 | 3,957 | aoc-2022-in-kotlin | Apache License 2.0 |
src/year2023/day19/Day19.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2023.day19
import check
import readInput
import splitByEmptyLines
fun main() {
val testInput = readInput("2023", "Day19_test")
check(part1(testInput), 19114)
check(part2(testInput), 167409079868000)
val input = readInput("2023", "Day19")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val (workflows, parts) = input.parseWorkflowsAndParts()
val workflowsByName = workflows.associateBy { it.name }
val acceptedParts = mutableListOf<Part>()
for (part in parts) {
var workflow = workflowsByName.getValue("in")
var result = workflow.process(part)
while (result !is Accept && result !is Reject) {
if (result is SendToWorkflow) {
workflow = workflowsByName.getValue(result.name)
result = workflow.process(part)
} else error("Unexpected result $result")
}
if (result is Accept) {
acceptedParts += part
}
}
return acceptedParts.sumOf { it.total() }
}
private fun part2(input: List<String>): Long {
val workflowsByName = input.parseWorkflowsAndParts().first.associateBy { it.name }
val partRanges = findPartRanges(PartRange(), workflowsByName.getValue("in"), workflowsByName)
return partRanges.toList().combinations()
}
private data class Part(
val x: Int,
val m: Int,
val a: Int,
val s: Int,
) {
fun total() = x + m + a + s
}
private data class Workflow(
val name: String,
val operations: List<Operation>,
)
private sealed interface Operation {
fun check(part: Part): Result
}
private sealed interface Result
private data object Continue : Result
private data object Reject : Result
private data object Accept : Result
private class SendToWorkflow(val name: String) : Result
private data object RejectOperation : Operation {
override fun check(part: Part) = Reject
}
private data object AcceptOperation : Operation {
override fun check(part: Part) = Accept
}
private class SendToWorkflowOperation(val name: String) : Operation {
override fun check(part: Part) = SendToWorkflow(name)
}
private enum class Attribute {
X, M, A, S
}
private sealed interface ComparisonOperation : Operation {
val limit: Int
val attribute: Attribute
val getAttribute: Part.() -> Int
val result: Result
}
private data class LessThanOperation(
override val limit: Int,
override val attribute: Attribute,
override val getAttribute: Part.() -> Int,
override val result: Result,
) : ComparisonOperation {
override fun check(part: Part) = if (part.getAttribute() < limit) result else Continue
}
private data class GreaterThanOperation(
override val limit: Int,
override val attribute: Attribute,
override val getAttribute: Part.() -> Int,
override val result: Result,
) : ComparisonOperation {
override fun check(part: Part) = if (part.getAttribute() > limit) result else Continue
}
private fun List<String>.parseWorkflowsAndParts(): Pair<List<Workflow>, List<Part>> {
val (workflowLines, partLines) = splitByEmptyLines()
val workflows: List<Workflow> = workflowLines.map { line ->
val name = line.substringBefore("{")
val operationTexts = line.substringAfter("{").removeSuffix("}").split(',')
val operations = operationTexts.map { operationText ->
if (operationText == "R") RejectOperation
else if (operationText == "A") AcceptOperation
else if ("<" in operationText || ">" in operationText) operationText.toComparisonOperation()
else SendToWorkflowOperation(operationText)
}
Workflow(name, operations)
}
val parts = partLines.map { line ->
val (x, m, a, s) = line.removePrefix("{").removeSuffix("}").split(',').map { it.split("=").last().toInt() }
Part(x = x, m = m, a = a, s = s)
}
return workflows to parts
}
private fun String.toComparisonOperation(): Operation {
val (attributeName, limitText, resultText) = split('<', '>', ':')
val result = when (resultText) {
"A" -> Accept
"R" -> Reject
else -> SendToWorkflow(resultText)
}
val attribute = Attribute.valueOf(attributeName.uppercase())
val attributeGetter: Part.() -> Int = when (attribute) {
Attribute.X -> Part::x
Attribute.M -> Part::m
Attribute.A -> Part::a
Attribute.S -> Part::s
}
val limit = limitText.toInt()
return if ("<" in this) LessThanOperation(limit, attribute, attributeGetter, result)
else GreaterThanOperation(limit, attribute, attributeGetter, result)
}
private fun Workflow.process(part: Part): Result {
for (operation in operations) {
val result = operation.check(part)
if (result is Continue) continue
else return result
}
error("Workflow $this had no outcome for $part")
}
private data class PartRange(
val xMin: Int = 1,
val xMax: Int = 4000,
val mMin: Int = 1,
val mMax: Int = 4000,
val aMin: Int = 1,
val aMax: Int = 4000,
val sMin: Int = 1,
val sMax: Int = 4000,
) {
fun copyWithMin(attribute: Attribute, min: Int) = when (attribute) {
Attribute.X -> copy(xMin = min)
Attribute.M -> copy(mMin = min)
Attribute.A -> copy(aMin = min)
Attribute.S -> copy(sMin = min)
}
fun copyWithMax(attribute: Attribute, max: Int) = when (attribute) {
Attribute.X -> copy(xMax = max)
Attribute.M -> copy(mMax = max)
Attribute.A -> copy(aMax = max)
Attribute.S -> copy(sMax = max)
}
fun isEmpty() = combinations() == 0L
}
private fun findPartRanges(
partRange: PartRange,
workflow: Workflow,
workflowsByName: Map<String, Workflow>,
): List<PartRange> {
return findPartRangesInOperations(partRange, workflow, 0, workflowsByName)
}
private fun findPartRangesInOperations(
partRange: PartRange,
workflow: Workflow,
operationIndex: Int,
workflowsByName: Map<String, Workflow>,
): List<PartRange> {
if (partRange.isEmpty() || operationIndex > workflow.operations.lastIndex) {
return emptyList()
}
return when (val operation = workflow.operations[operationIndex]) {
AcceptOperation -> listOf(partRange)
RejectOperation -> emptyList()
is ComparisonOperation -> {
val (matchingPartRange, nonMatchingPartRange) = operation.splitPartRanges(partRange)
val partRangesFromContinuing =
findPartRangesInOperations(nonMatchingPartRange, workflow, operationIndex + 1, workflowsByName)
when (val result = operation.result) {
Accept -> listOf(matchingPartRange) + partRangesFromContinuing
Reject -> partRangesFromContinuing
is SendToWorkflow -> findPartRanges(
matchingPartRange,
workflowsByName.getValue(result.name),
workflowsByName
) + partRangesFromContinuing
Continue -> error("Unexpected Continue")
}
}
is SendToWorkflowOperation -> findPartRanges(
partRange,
workflowsByName.getValue(operation.name),
workflowsByName
)
}
}
private fun ComparisonOperation.splitPartRanges(partRange: PartRange) = when (this) {
is GreaterThanOperation -> splitPartRanges(partRange)
is LessThanOperation -> splitPartRanges(partRange)
}
private fun GreaterThanOperation.splitPartRanges(partRange: PartRange): Pair<PartRange, PartRange> {
return partRange.copyWithMin(attribute, limit + 1) to partRange.copyWithMax(attribute, limit)
}
private fun LessThanOperation.splitPartRanges(partRange: PartRange): Pair<PartRange, PartRange> {
return partRange.copyWithMax(attribute, limit - 1) to partRange.copyWithMin(attribute, limit)
}
private fun PartRange.combinations() =
1L * (xMax - xMin + 1) * (mMax - mMin + 1) * (aMax - aMin + 1) * (sMax - sMin + 1)
private fun List<PartRange>.combinations() = sumOf { it.combinations() }
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 8,126 | AdventOfCode | Apache License 2.0 |
src/Day03/Day03.kt | martin3398 | 436,014,815 | false | {"Kotlin": 63436, "Python": 5921} | import kotlin.math.pow
fun main() {
fun bitListToInt(input: List<Int>) =
input.foldIndexed(0) { index, sum, elem -> sum + elem * (2.0).pow(input.size - index - 1).toInt() }
fun part1(input: List<String>): Int {
val zeros = MutableList(input[0].length) { 0 }
for (e in input) {
for ((i, c) in e.withIndex()) {
if (c == '0') {
zeros[i]++
}
}
}
val gamma = bitListToInt(zeros.map { x -> if (x <= input.size / 2) 1 else 0 })
val eps = bitListToInt(zeros.map { x -> if (x <= input.size / 2) 0 else 1 })
return gamma * eps
}
fun filterBinary(input: List<String>, needle: Char): Int {
var inputWc = input
var res = 0
val inputLen = inputWc[0].length
for (i in 0 until inputLen) {
val zeros = inputWc.count { it[i] == '0' } > inputWc.size / 2
inputWc = inputWc.filter { (zeros && it[i] == needle) || (!zeros && it[i] != needle) }
if (inputWc.size == 1) {
res = bitListToInt(inputWc[0].map { it.toString().toInt() })
}
}
return res
}
fun part2(input: List<String>): Int {
val oxygen = filterBinary(input, '0')
val co2 = filterBinary(input, '1')
return oxygen * co2
}
val testInput = readInput(3, true)
check(part1(testInput) == 198)
check(part2(testInput) == 230)
val input = readInput(3)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 085b1f2995e13233ade9cbde9cd506cafe64e1b5 | 1,555 | advent-of-code-2021 | Apache License 2.0 |
src/Day09.kt | stevennoto | 573,247,572 | false | {"Kotlin": 18058} | import java.util.Deque
import kotlin.math.absoluteValue
fun main() {
// Adjust rope head position based on direction
fun moveHead(head: Pair<Int, Int>, direction: String): Pair<Int, Int> {
return when (direction) {
"U" -> Pair(head.first, head.second + 1)
"D" -> Pair(head.first, head.second - 1)
"R" -> Pair(head.first + 1, head.second)
"L" -> Pair(head.first - 1, head.second)
else -> head
}
}
// Adjust tail position based on head position
fun moveTail(tail: Pair<Int, Int>, head: Pair<Int, Int>): Pair<Int, Int> {
// If in same X or Y coord, and other coord is >= 2 off, adjust other coord (move orthogonally)
return if (head.first == tail.first && (head.second - tail.second).absoluteValue >= 2) {
Pair(tail.first, tail.second + if (head.second < tail.second) -1 else 1)
} else if (head.second == tail.second && (head.first - tail.first).absoluteValue >= 2) {
Pair(tail.first + if (head.first < tail.first) -1 else 1, tail.second)
}
// Else, if either coord is >= 2 off, adjust both coords (move diagonally)
else if ((head.first - tail.first).absoluteValue >= 2 || (head.second - tail.second).absoluteValue >= 2) {
Pair(tail.first + if (head.first < tail.first) -1 else 1, tail.second + if (head.second < tail.second) -1 else 1)
} else {
tail
}
}
fun part1(input: List<String>): Int {
// Parse instructions, moving head per instructions and tail per head movement. Track unique tail locations in Set.
var head = Pair(0, 0)
var tail = Pair(0, 0)
val tailLocations = mutableSetOf<Pair<Int, Int>>()
input.forEach {
val (direction, numTimes) = Regex("(\\w) (\\d+)").find(it)!!.destructured.toList()
repeat(numTimes.toInt()) {
head = moveHead(head, direction)
tail = moveTail(tail, head)
tailLocations.add(tail)
}
}
return tailLocations.size
}
fun part2(input: List<String>): Int {
// Same as above, but instead of head and tail, rope has 10 nodes
val ropeNodes = MutableList(10) { Pair(0, 0) }
val tailLocations = mutableSetOf<Pair<Int, Int>>()
input.forEach {
val (direction, numTimes) = Regex("(\\w) (\\d+)").find(it)!!.destructured.toList()
repeat(numTimes.toInt()) {
ropeNodes[0] = moveHead(ropeNodes[0], direction)
repeat(9) { index ->
ropeNodes[index + 1] = moveTail(ropeNodes[index + 1], ropeNodes[index])
}
tailLocations.add(ropeNodes[9])
}
}
return tailLocations.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 42941fc84d50b75f9e3952bb40d17d4145a3036b | 3,095 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/day12.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.getText
import shared.placeInAlphabet
import shared.Point
fun main() {
val input = getText("day12.txt")
println(day12A(input))
println(day12B(input))
}
fun day12A(input: String): Int {
val startY = input.lines().indexOfFirst { it.contains("S") }
val startX = input.lines()[startY].indexOfFirst { it == 'S' }
val goalY = input.lines().indexOfFirst { it.contains("E") }
val goalX = input.lines()[goalY].indexOfFirst { it == 'E' }
return bfs(input, Point(startX, startY), listOf(Point(goalX, goalY)), canGoUp)
}
fun day12B(input: String): Int {
val startY = input.lines().indexOfFirst { it.contains("E") }
val startX = input.lines()[startY].indexOfFirst { it == 'E' }
val goals = mutableListOf<Point>()
for(y in input.lines().indices) {
for(x in 0 until input.lines()[y].length) {
if(input.lines()[y][x] == 'a' || input.lines()[y][x] == 'S') {
goals.add(Point(x, y))
}
}
}
return bfs(input, Point(startX, startY), goals, canGoDown)
}
private fun bfs(map: String, start: Point, goal: List<Point>, canGo: (from: Char, to: Char?) -> Boolean): Int {
val explored = mutableListOf(start)
val queue = mutableListOf(Pair(start, 0))
while (queue.isNotEmpty()) {
val check = queue.removeAt(0)
if(goal.contains(check.first)) return check.second
for(moveTo in possibleMoves(map, check.first, canGo).filter { !explored.contains(it) }) {
queue.add(Pair(moveTo, check.second + 1))
explored.add(moveTo)
}
}
throw Exception("should have found goal by now")
}
private fun String.at(point: Point) = lines().getOrNull(point.y)?.toCharArray()?.getOrNull(point.x)
private val canGoUp = fun(from: Char, to: Char?) = to != null && from.elevation() + 1 >= to.elevation()
private val canGoDown = fun(from: Char, to: Char?) = to != null && to.elevation() + 1 >= from.elevation()
private val possibleMoves = fun(map: String, point: Point, canGo: (from: Char, to: Char?) -> Boolean): List<Point>{
val x = point.x
val y = point.y
return listOfNotNull(
Point(x-1, y).let {
if(canGo(map.at(point)!!, map.at(it))) it else null
},
Point(x, y-1).let {
if(canGo(map.at(point)!!, map.at(it))) it else null
},
Point(x, y+1).let {
if(canGo(map.at(point)!!, map.at(it))) it else null
},
Point(x+1, y).let {
if(canGo(map.at(point)!!, map.at(it))) it else null
},
)
}
private fun Char.elevation() = if(this == 'S') 1 else if(this == 'E') 26 else this.placeInAlphabet()
| 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 2,662 | AdventOfCode2022 | MIT License |
src/main/kotlin/y2023/Day2.kt | juschmitt | 725,529,913 | false | {"Kotlin": 18866} | package y2023
import utils.Day
import kotlin.math.max
class Day2 : Day(2, 2023, false) {
override fun partOne(): Any {
return inputList
.mapToGame()
.filter { game ->
game.grabs.fold(true) { acc1, cubes ->
acc1 && cubes.fold(true) { acc2, cube ->
acc2 && when (cube) {
is Cube.Blue -> cube.amount <= winningBlues
is Cube.Green -> cube.amount <= winningGreens
is Cube.Red -> cube.amount <= winningReds
}
}
}
}.sumOf { it.id }
}
override fun partTwo(): Any {
return inputList.mapToGame()
.map { it.grabs }
.fold(0) { power, game ->
val (red, green, blue) = game.fold(Triple(0, 0, 0)) { (aRed, aGreen, aBlue), cubes ->
val (gRed, gGreen, gBlue) = cubes.fold(Triple(0, 0, 0)) { (red, green, blue), cube ->
when (cube) {
is Cube.Blue -> Triple(red, green, cube.amount)
is Cube.Green -> Triple(red, cube.amount, blue)
is Cube.Red -> Triple(cube.amount, green, blue)
}
}
Triple(max(aRed, gRed), max(aGreen, gGreen), max(aBlue, gBlue))
}
power + (red * green * blue)
}
}
}
private fun List<String>.mapToGame() = map { line ->
val game = line.split(":")
val id = game[0].drop(5).toInt()
val grabs = game[1].split(";").map { grab ->
grab.split(",").map { cubes ->
val c = cubes.trim().split(" ")
val amount = c[0].toInt()
when (c[1]) {
"red" -> Cube.Red(amount)
"blue" -> Cube.Blue(amount)
"green" -> Cube.Green(amount)
else -> error("Something wrong here: $line, $grab, $cubes, $c")
}
}
}
Game(id, grabs)
}
private data class Game(
val id: Int,
val grabs: List<List<Cube>>
)
private sealed interface Cube {
val amount: Int
data class Red(override val amount: Int) : Cube
data class Blue(override val amount: Int) : Cube
data class Green(override val amount: Int) : Cube
}
private const val winningReds = 12
private const val winningGreens = 13
private const val winningBlues = 14 | 0 | Kotlin | 0 | 0 | b1db7b8e9f1037d4c16e6b733145da7ad807b40a | 2,499 | adventofcode | MIT License |
src/Day05.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | data class Move(val from: Int, val to: Int, val count: Int)
data class Input(
val dequeues: List<ArrayDeque<Char>>,
val moves: List<Move>
)
fun main() {
fun part1(input: Input): List<Char> {
val dequeues = List(input.dequeues.size) { i -> ArrayDeque(input.dequeues[i]) }
input.moves.forEach { move ->
repeat(move.count) {
dequeues[move.to].push(dequeues[move.from].pop())
}
}
return dequeues.map { it.peek() }
}
fun part2(input: Input): List<Char> {
val dequeues = List(input.dequeues.size) { i -> ArrayDeque(input.dequeues[i]) }
input.moves.forEach { move ->
val deque: ArrayDeque<Char> = ArrayDeque()
repeat(move.count) {
deque.push(dequeues[move.from].pop())
}
while (!deque.isEmpty()) {
dequeues[move.to].push(deque.pop())
}
}
return dequeues.map { it.peek() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test").parseInput()
val result = part1(testInput).joinToString("")
check(result == "CMZ")
val input = readInput("Day05").parseInput()
val part1Result = part1(input).joinToString("")
println(part1Result)
// check(part1Result == "CWMTGHBDW")
val parse2Result = part2(input).joinToString("")
println(parse2Result)
// check(parse2Result == "SSCGWJCRB")
}
fun List<String>.parseInput(): Input {
val splitPosition = this.indexOf("")
val deq = this.take(splitPosition)
val moves = this.drop(splitPosition + 1)
return Input(
dequeues = parseDequeues(deq),
moves = parseMoves(moves)
)
}
val movePattern = Regex("""move (\d+) from (\d+) to (\d+)""")
fun parseMoves(input: List<String>): List<Move> {
return input.map { s ->
val groups = movePattern.matchEntire(s)?.groups ?: error("Can not parse move `$s`")
check(groups.size == 4)
Move(
count = groups[1]!!.value.toInt(),
from = groups[2]!!.value.toInt() - 1,
to = groups[3]!!.value.toInt() - 1
)
}
}
fun parseDequeues(input: List<String>): List<ArrayDeque<Char>> {
val dequeues = mutableListOf<ArrayDeque<Char>>()
input.asReversed().asSequence().drop(1).forEach { s ->
val dequeCount = (s.length + 1) / 4
if (dequeues.size < dequeCount) {
repeat(dequeCount - dequeues.size) {
dequeues.add(ArrayDeque())
}
}
repeat(dequeCount) { index ->
val item = s.substring(index * 4, index * 4 + 3)
if (item != " ") {
dequeues[index].push(item[1])
}
}
}
return dequeues
}
private inline fun <reified E> ArrayDeque<in E>.push(item: E) = addLast(item)
private inline fun <reified E> ArrayDeque<out E>.peek(): E = this.last()
private inline fun <reified E> ArrayDeque<out E>.pop(): E = removeLast()
| 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 3,028 | aoc22-kotlin | Apache License 2.0 |
src/main/kotlin/advent/day5/HydrothermalVenture.kt | hofiisek | 434,171,205 | false | {"Kotlin": 51627} | package advent.day5
import advent.loadInput
import java.io.File
import kotlin.math.abs
/**
* @author <NAME> */
data class Coordinate(val x: Int, val y: Int)
data class LineSegment(val start: Coordinate, val end: Coordinate)
fun LineSegment.isHorizontalOrVertical() = start.x == end.x || start.y == end.y
fun LineSegment.isDiagonal() =
abs(start.x - end.x) == abs(start.y - end.y) || abs(start.x - start.y) == abs(end.x - end.y)
fun LineSegment.coveredPoints(): List<Coordinate> {
val (x1, y1) = start
val (x2, y2) = end
val xRange = if (x1 <= x2) x1 .. x2 else x1 downTo x2
val yRange = if (y1 <= y2) y1 .. y2 else y1 downTo y2
return when {
isHorizontalOrVertical() -> xRange.flatMap { x -> yRange.map { y -> Coordinate(x, y) } }
isDiagonal() -> xRange.zip(yRange).map { (x, y) -> Coordinate(x, y) }
else -> throw IllegalArgumentException("Invalid segment: $this")
}
}
fun part1(input: File) = buildSegments(input)
.filter(LineSegment::isHorizontalOrVertical)
.also { it.printSegments() }
.flatMap(LineSegment::coveredPoints)
.groupingBy { it }
.eachCount()
.count { it.value >= 2 }
fun part2(input: File) = buildSegments(input)
.filter { it.isHorizontalOrVertical() || it.isDiagonal() }
.also { it.printSegments() }
.flatMap(LineSegment::coveredPoints)
.groupingBy { it }
.eachCount()
.count { it.value >= 2 }
fun buildSegments(input: File): List<LineSegment> = input.readLines()
.map { it.split("( -> )|,".toRegex()).map { it.toInt() } }
.map { (x1, y1, x2, y2) ->
// columns go first in the input (which is weird) so we have to swap it
LineSegment(Coordinate(y1, x1), Coordinate(y2, x2))
}
fun List<LineSegment>.printSegments() {
val allCoordinates: List<Coordinate> = flatMap { listOf(it.start, it.end) }.distinct()
val maxX = allCoordinates.maxOf { it.x }
val maxY = allCoordinates.maxOf { it.y }
val coveredPointsWithCount: Map<Coordinate, Int> = flatMap { it.coveredPoints() }
.groupingBy { it }
.eachCount()
for (x in 0 .. maxX) {
for (y in 0 .. maxY) {
coveredPointsWithCount.getOrDefault(Coordinate(x, y), 0)
.let { if (it > 0) "$it" else "." }
.also(::print)
}
println()
}
}
fun main() {
// with(loadInput(day = 5, filename = "input_example.txt")) {
with(loadInput(day = 5)) {
println(part1(this))
println(part2(this))
}
} | 0 | Kotlin | 0 | 2 | 3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb | 2,520 | Advent-of-code-2021 | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day13/Day13.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day13
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputSplitOnBlank
import kotlin.math.abs
object Day13 : Day {
override val input = Grid.from(readInputSplitOnBlank(13).map { it.lines() })
override fun part1() = input.foldOnce().count()
override fun part2() = 0.apply { input.display() }
data class Grid(val positions: Set<Position>, val folds: List<Fold>) {
companion object {
fun from(lines: List<List<String>>) = Grid(lines.first().positions(), lines.last().folds())
private fun List<String>.positions() = map { it.split(',') }.map { Position(it.first().toInt(), it.last().toInt()) }.toSet()
private fun List<String>.folds(): List<Fold> {
return map { it.substringAfterLast(' ') }
.map { it.split('=') }
.map { Fold(Axis.valueOf(it.first().uppercase()), it.last().toInt()) }
}
}
fun foldOnce() = positions.fold(folds.first())
fun display() {
with(foldAll()) {
val (maxX, maxY) = (positions.maxOf { it.x } to positions.maxOf { it.y })
(0..maxY).forEach { y ->
println((0..maxX).map { x -> if (positions.contains(Position(x, y))) '#' else '.' }.joinToString(""))
}
}
}
private fun foldAll() = copy(positions = folds.fold(positions) { acc, fold -> acc.fold(fold) })
}
data class Position(val x: Int, val y: Int) {
fun fold(fold: Fold) = when (fold.axis) {
Axis.X -> Position(abs(x - fold.value * 2), y)
Axis.Y -> Position(x, abs(y - fold.value * 2))
}
}
data class Fold(val axis: Axis, val value: Int)
enum class Axis {
X,
Y
}
private fun Set<Position>.fold(fold: Fold) = when (fold.axis) {
Axis.X -> fold(fold) { x }
Axis.Y -> fold(fold) { y }
}
private fun Set<Position>.fold(fold: Fold, axis: Position.() -> Int): Set<Position> {
return (filter { it.axis() < fold.value } + filter { it.axis() > fold.value }.map { it.fold(fold) }).toSet()
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 2,230 | aoc2021 | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day17.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2016
import se.saidaspen.aoc.util.*
fun main() = Day17.run()
typealias State = P<P<Int, Int>, String>
object Day17 : Day(2016, 17) {
val next : (State) -> Iterable<State> = { (pos, inp) ->
val doorState = doorState(inp, pos)
val next = mutableListOf<State>()
if (doorState[0]){ next.add(P(pos.x, pos.y-1) to inp + "U") }
if (doorState[1]){ next.add(P(pos.x, pos.y+1) to inp + "D") }
if (doorState[2]){ next.add(P(pos.x-1, pos.y) to inp + "L")}
if (doorState[3]){ next.add(P(pos.x+1, pos.y) to inp + "R")}
next
}
override fun part1(): Any {
return bfs(P(0,0) to input, { (a, _) -> a.x == 3 && a.y == 3 }, next).first!!.second.replace(input, "")
}
override fun part2(): Any {
return bfsLong(P(0,0) to input, { (a, _) -> a.x == 3 && a.y == 3 }, next)!!.first.second.replace(input, "").length
}
private fun doorState(input: String, pos : P<Int, Int>) : MutableList<Boolean> {
val doors = md5(input).take(4).map { "bcdef".contains(it) }.toMutableList()
if (pos.x == 0) doors[2] = false
if (pos.x == 3) doors[3] = false
if (pos.y == 0) doors[0] = false
if (pos.y == 3) doors[1] = false
return doors
}
inline fun <State> bfsLong(start: State, isEnd: (State) -> Boolean, next: (State) -> Iterable<State>): Pair<State, Int>? {
var queue = mutableListOf(start)
var nextQueue = mutableListOf<State>()
var dist = -1
var longest: Pair<State, Int>? = null
while (queue.isNotEmpty()) {
dist++
for (current in queue) {
if (isEnd(current)) longest = current to dist
else
for (i in next(current)) {
nextQueue.add(i)
}
}
val p = nextQueue
nextQueue = queue
queue = p
nextQueue.clear()
}
return longest
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,020 | adventofkotlin | MIT License |
src/DayTwo.kt | P-ter | 573,301,805 | false | {"Kotlin": 9464} | data class Dimension(val length: Int, val width: Int, val height: Int)
fun main() {
fun part1(input: List<String>): Int {
val dimensions = input.map {
val dimension = it.split("x")
Dimension(dimension[0].toInt(), dimension[1].toInt(), dimension[2].toInt())
}
val totalSqFt = dimensions.fold(0) { acc, dimension ->
val (length, width, height) = dimension
val areaList = listOf<Int>(
length*width,
width*height,
height*length
)
acc + (2*areaList[0] + 2*areaList[1] + 2*areaList[2] + areaList.min())
}
return totalSqFt
}
fun part2(input: List<String>): Int {
val dimensions = input.map {
val dimension = it.split("x")
Dimension(dimension[0].toInt(), dimension[1].toInt(), dimension[2].toInt())
}
val totalFt = dimensions.fold(0) { acc, dimension ->
val (length, width, height) = dimension
val sortedSideBasedOnLength = listOf(length, width, height).sorted()
val lengthOfRibbon = sortedSideBasedOnLength[0]*2 + sortedSideBasedOnLength[1]*2
val presentVolume = length*width*height
acc + lengthOfRibbon + presentVolume
}
return totalFt
}
val input = readInput("daytwo")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fc46b19451145e0c41b1a50f62c77693865f9894 | 1,426 | aoc-2015 | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day06/day6.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day06
import biz.koziolek.adventofcode.findInput
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.pow
import kotlin.math.sqrt
fun main() {
val inputFile = findInput(object {})
val lines = inputFile.bufferedReader().readLines()
val races = parseBoatRaces(lines)
println("Margin of error for ${races.size} races is: ${findMarginOfError(races)}")
val theRace = parseTheBoatRace(lines)
println("Ways to win the race is: ${findWaysToWinRace(theRace).count()}")
}
data class BoatRace(val time: Long, val distance: Long)
fun parseBoatRaces(lines: Iterable<String>): List<BoatRace> {
val (firstLine, secondLine) = lines.toList()
val times = readNumbers(firstLine)
val distances = readNumbers(secondLine)
return times.zip(distances).map { BoatRace(it.first, it.second) }
}
fun parseTheBoatRace(lines: Iterable<String>): BoatRace =
lines
.map { it.replace(Regex(" +"), "").replace(":", ": ") }
.let { parseBoatRaces(it) }
.single()
private fun readNumbers(line: String) =
line
.replace(Regex(" +"), " ")
.split(" ")
.drop(1)
.map { it.toLong() }
fun findWaysToWinRace(race: BoatRace): IntRange {
val delta = race.time.toDouble().pow(2) - 4 * (race.distance + 0.00000001)
val maxTime = (-race.time - sqrt(delta)) / -2
val minTime = (-race.time + sqrt(delta)) / -2
return ceil(minTime).toInt() .. floor(maxTime).toInt()
}
fun findMarginOfError(races: List<BoatRace>): Int =
races
.map { findWaysToWinRace(it).count() }
.reduce(Int::times)
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 1,640 | advent-of-code | MIT License |
src/day14/first/Solution.kt | verwoerd | 224,986,977 | false | null | package day14.first
import tools.ceilDivision
import tools.timeSolution
import java.util.LinkedList
import kotlin.math.max
fun main() = timeSolution {
val reactionList = readReactionInput()
println(solver(reactionList, 1L))
}
fun readReactionInput() = System.`in`.bufferedReader().readLines()
.map { it.split("=>") }
.map { (input, output) ->
val (factor, result) = parseReaction(output)
val inputs = input.split(",").map(::parseReaction).map { (amount, result) -> result to amount }
result to Reaction(result, factor, inputs)
}.toMap()
val reactionRegex = Regex("(\\d+) (\\w+)")
fun parseReaction(reaction: String) = reactionRegex.matchEntire(reaction.trim())
.let { it!!.groupValues[1].toInt() to it.groupValues[2] }
data class Reaction(val result: String, val produces: Int, val ingredients: List<Pair<String, Int>>) {
fun isBaseElement() =
ingredients.size == 1 && ingredients.first().first == "ORE"
fun oreCost() =
ingredients.first().second
}
fun solver(reactionList: Map<String, Reaction>, fuel: Long): Long {
val currentNeeds = mutableMapOf("FUEL" to fuel).withDefault { 0 }
val currentRemains = mutableMapOf<String, Long>().withDefault { 0 }
val queue = LinkedList<Pair<String, Long>>()
queue.add("FUEL" to fuel)
while (queue.isNotEmpty()) {
val (current, need) = queue.poll()
val reaction = reactionList.getValue(current)
val numReactions = need ceilDivision reaction.produces
when {
reaction.isBaseElement() -> {
currentNeeds["ORE"] = currentNeeds.getValue("ORE") + numReactions * reaction.oreCost()
}
else -> {
reaction.ingredients.forEach { (input, amount) ->
val currentReaction = reactionList.getValue(input)
val needToProduce = max(numReactions * amount - currentRemains.getValue(input), 0L)
val numResult = needToProduce ceilDivision currentReaction.produces
currentNeeds[input] = currentNeeds.getValue(input) + need * amount
currentRemains[input] =
(numResult * currentReaction.produces) + currentRemains.getValue(input) - numReactions * amount
if (needToProduce > 0) {
queue.add(input to (needToProduce))
}
}
}
}
}
return currentNeeds.getValue("ORE")
}
| 0 | Kotlin | 0 | 0 | 554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7 | 2,292 | AoC2019 | MIT License |
src/main/kotlin/org/hydev/lcci/lcci_01.kt | VergeDX | 334,298,924 | false | null | import kotlin.collections.set
import kotlin.math.abs
// https://leetcode-cn.com/problems/is-unique-lcci/
fun isUnique(astr: String): Boolean {
// All character, maybe not in English...?
// if (astr.length > 24) return false
astr.forEachIndexed { index, c -> if (astr.indexOf(c) != index) return false }
return true
}
// https://leetcode-cn.com/problems/check-permutation-lcci/
fun CheckPermutation(s1: String, s2: String): Boolean {
if (s1.length != s2.length) return false
if (s1.toCharArray().sorted() == s2.toCharArray().sorted()) return true
return false
}
// https://leetcode-cn.com/problems/string-to-url-lcci/
fun replaceSpaces(S: String, length: Int): String {
// substring: [start, end)
val tempString = S.substring(0, length)
return tempString.replace(" ", "%20")
}
// https://leetcode-cn.com/problems/palindrome-permutation-lcci/
fun canPermutePalindrome(s: String): Boolean {
val tempMap = HashMap<Char, Int>()
s.forEach { tempMap[it] = (tempMap[it] ?: 0) + 1 }
val groupCount = tempMap.values.count { it % 2 != 0 }
return groupCount == s.length % 2
}
// https://leetcode-cn.com/problems/one-away-lcci/
fun oneEditAway(first: String, second: String): Boolean {
if (first == second) return true
if (first.length == second.length) {
var diffCount = 0
for (pair in first zip second)
if (pair.first != pair.second)
diffCount++
// Exclude cases 0.
return diffCount == 1
}
if (abs(first.length - second.length) == 1) {
val longest = if (first.length > second.length) first else second
val another = if (longest == first) second else first
if (another.isEmpty()) return true
var indexLongest = 0
var indexAnother = 0
while (indexAnother != another.length) {
if (longest[indexLongest] == another[indexAnother]) {
indexLongest++
indexAnother++
continue
} else {
// Error more than one times.
if (indexLongest != indexAnother) return false
indexLongest++
continue
}
}
return true
}
return false
}
// https://leetcode-cn.com/problems/compress-string-lcci/
fun compressString(S: String): String {
if (S.isEmpty()) return ""
var currentChar = S[0]
var currentCount = 0
var result = ""
S.forEach {
if (it != currentChar) {
result += "${currentChar}${currentCount}"
currentChar = it
currentCount = 1
} else currentCount++
}
result += "${currentChar}${currentCount}"
return if (result.length >= S.length) S else result
}
// https://leetcode-cn.com/problems/rotate-matrix-lcci/
fun rotate(matrix: Array<IntArray>): Unit {
if (matrix.isEmpty()) return
// size x size matrix.
val sizeIndex = matrix.size - 1
val tempMatrix = matrix.map { it.clone() }
tempMatrix.forEachIndexed { index, ints ->
val insertIndex = sizeIndex - index
for (i in 0..sizeIndex) {
matrix[i][insertIndex] = ints[i]
}
}
}
// https://leetcode-cn.com/problems/zero-matrix-lcci/
fun setZeroes(matrix: Array<IntArray>): Unit {
if (matrix.isEmpty()) return
// Matrix: m x n.
val m = matrix.size
val n = matrix[0].size
val zeroRowIndex = LinkedHashSet<Int>()
val zeroColumnIndex = LinkedHashSet<Int>()
matrix.forEachIndexed { rowIndex, ints ->
ints.forEachIndexed { columnIndex, i ->
if (i == 0) {
zeroRowIndex.add(rowIndex)
zeroColumnIndex.add(columnIndex)
}
}
}
zeroRowIndex.forEach { matrix[it] = IntArray(n) { 0 } }
zeroColumnIndex.forEach { matrix.forEach { ints -> ints[it] = 0 } }
}
// https://leetcode-cn.com/problems/string-rotation-lcci/
fun isFlipedString(s1: String, s2: String): Boolean {
if (s1.length != s2.length) return false
if (s1.isEmpty()) return true
// Rotate string to right given times, times should < string length.
fun rotate(rawString: String, times: Int): String {
val targetIndex = rawString.length - times
return rawString.substring(targetIndex) + rawString.substring(0, targetIndex)
}
for (i in 1 until s1.length)
if (rotate(s1, i) == s2)
return true
// s1.length == 1 && s1 == s2.
if (s1 == s2) return true
return false
}
fun main() {
println(canPermutePalindrome("code"))
println(oneEditAway("pale", "ple"))
println(oneEditAway("pales", "pal"))
println(oneEditAway("a", "ab"))
rotate(arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9)))
setZeroes(arrayOf(intArrayOf(1, 1, 1), intArrayOf(1, 0, 1), intArrayOf(1, 1, 1)))
setZeroes(arrayOf(intArrayOf(0, 1, 2, 0), intArrayOf(3, 4, 5, 2), intArrayOf(1, 3, 1, 5)))
}
| 0 | Kotlin | 0 | 0 | 9a26ac2e24b0a0bdf4ec5c491523fe9721c6c406 | 4,963 | LeetCode_Practice | MIT License |
src/main/kotlin/pl/bizarre/day7_1.kt | gosak | 572,644,357 | false | {"Kotlin": 26456} | package pl.bizarre
import pl.bizarre.common.loadInput
fun main() {
val input = loadInput(7)
println("result ${day7_1(input)}")
}
fun day7_1(input: List<String>): Int {
val fileSystem = input.getFileSystem()
val allDirectories = fileSystem.allDirectories()
val allDirectoriesWithSizeAtMost100000 = allDirectories.filter { it.size() <= 100000 }
return allDirectoriesWithSizeAtMost100000.sumOf { it.size() }
}
fun List<String>.getFileSystem(): Directory {
val cdRegex = "\\$ cd (.*)".toRegex()
val fileRegex = "([0-9]+) (.*)".toRegex()
val dirRegex = "dir (.*)".toRegex()
val fileSystem = Directory("/")
var currentDirectory = fileSystem
forEach { line ->
when {
line == "$ cd /" -> {
currentDirectory = fileSystem
}
line == "$ cd .." -> {
if (currentDirectory.parent != null) {
currentDirectory = currentDirectory.parent!!
}
}
cdRegex.matches(line) -> {
val name = cdRegex.find(line)!!.groups[1]!!.value
currentDirectory = currentDirectory.files.find { it.name == name } as Directory
}
line == "$ ls" -> {}
fileRegex.matches(line) -> {
val groups = fileRegex.find(line)!!.groups
val newFile = SimpleFile(
size = groups[1]!!.value.toInt(),
name = groups[2]!!.value
)
currentDirectory.files.add(newFile)
}
dirRegex.matches(line) -> {
val newFile = Directory(
name = dirRegex.find(line)!!.groups[1]!!.value,
parent = currentDirectory,
)
currentDirectory.files.add(newFile)
}
}
}
return fileSystem
}
fun File.allDirectories(): List<Directory> =
when (this) {
is SimpleFile -> emptyList()
is Directory -> listOf(this) + files.flatMap { it.allDirectories() }
}
sealed class File(
open val name: String,
) {
abstract fun size(): Int
}
data class SimpleFile(
override val name: String,
private val size: Int,
) : File(name) {
override fun size() = size
}
class Directory(
override val name: String,
val files: MutableList<File> = mutableListOf(),
val parent: Directory? = null,
) : File(name) {
override fun size() = files.sumOf(File::size)
}
| 0 | Kotlin | 0 | 0 | aaabc56532c4a5b12a9ce23d54c76a2316b933a6 | 2,497 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/Day07.kt | SimonMarquis | 724,825,757 | false | {"Kotlin": 30983} | import Day07.Card.J
class Day07(private val input: List<String>) {
private fun String.toHand() = split(" ").let { (cards, bid) ->
Hand(
cards = cards.map(Char::toString).map(Card::valueOf),
bid = bid.toLong(),
)
}
private data class Hand(val cards: List<Card>, val bid: Long) : Comparable<Hand> {
val type = cards.groupingBy { it }.eachCount().values.let {
when {
5 in it -> Type.`Five of a kind`
4 in it -> Type.`Four of a kind`
3 in it && 2 in it -> Type.`Full house`
3 in it -> Type.`Three of a kind`
it.count { it == 2 } == 2 -> Type.`Two pair`
2 in it -> Type.`One pair`
else -> Type.`High card`
}
}
override fun compareTo(other: Hand): Int = type.compareTo(other.type).takeUnless { it == 0 }?.unaryMinus()
?: cards.zip(other.cards).firstNotNullOfOrNull { (l, r) -> l.compareTo(r).unaryMinus().takeUnless { it == 0 } }
?: 0
}
private data class JokerHand(val hand: Hand) : Comparable<JokerHand> {
val joker: Hand = hand.asJoker()
private fun List<Card>.asJoker() = map { it.takeUnless { it == J } ?: Card.`0` }
private fun Hand.asJoker(): Hand =
if (J !in this.cards) this
else Card.entries.minOf { r -> copy(cards = cards.map { if (it == J) r else it }) }
override fun compareTo(other: JokerHand): Int = joker.type.compareTo(other.joker.type).takeUnless { it == 0 }?.unaryMinus()
?: hand.cards.asJoker().zip(other.hand.cards.asJoker()).firstNotNullOfOrNull { (l, r) -> r.compareTo(l).takeUnless { it == 0 } }
?: 0
}
@Suppress("EnumEntryName")
enum class Card { `0`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, T, J, Q, K, A }
@Suppress("EnumEntryName")
enum class Type { `High card`, `One pair`, `Two pair`, `Three of a kind`, `Full house`, `Four of a kind`, `Five of a kind` }
fun part1(): Long = input
.map { it.toHand() }
.sorted()
.asReversed()
.foldIndexed(0L) { index, acc, hand -> acc + (index + 1) * hand.bid }
fun part2(): Long = input
.map { it.toHand() }
.map(::JokerHand)
.sorted()
.asReversed()
.foldIndexed(0L) { index, acc, hand -> acc + (index + 1) * hand.joker.bid }
}
| 0 | Kotlin | 0 | 1 | 043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e | 2,423 | advent-of-code-2023 | MIT License |
src/main/kotlin/dev/bogwalk/batch8/Problem83.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch8
import java.util.PriorityQueue
/**
* Problem 83: Path Sum 4 Ways
*
* https://projecteuler.net/problem=83
*
* Goal: Find the minimum path sum for an NxN grid, starting at (0,0) and ending at (n,n), by
* moving left, right, up, or down with each step.
*
* Constraints: 1 <= N <= 1000, numbers in [1, 1e9]
*
* e.g.: N = 3
* grid = 2 0 3 5
* 8 0 9 9
* 0 3 9 9
* 0 1 1 1
* minimum = 8: {2 -> R -> D -> D -> L -> D -> R -> R -> 1}
*/
class PathSum4Ways {
/**
* Solution is identical to the Dijkstra solution used in Problems 81 and 82, except extra
* steps (left & up) are added to the PriorityQueue, instead of using an adjacency matrix.
*
* SPEED (WORSE) 109.45ms for N = 80
*/
fun minPathSumDijkstra(rows: Int, grid: Array<IntArray>): Long {
val visited = Array(rows) { BooleanArray(rows) }
val compareByWeight = compareBy<Triple<Int, Int, Long>> { it.third }
val queue = PriorityQueue(compareByWeight).apply {
add(Triple(0, 0, grid[0][0].toLong()))
}
var minSum = 0L
while (queue.isNotEmpty()) {
val (row, col, weight) = queue.poll()
if (visited[row][col]) continue
if (row == rows - 1 && col == rows - 1) {
minSum = weight
break
}
visited[row][col] = true
if (col - 1 >= 0) {
queue.add(Triple(row, col - 1, weight + grid[row][col-1]))
}
if (row - 1 >= 0) {
queue.add(Triple(row - 1, col, weight + grid[row - 1][col]))
}
if (col + 1 < rows) {
queue.add(Triple(row, col + 1, weight + grid[row][col+1]))
}
if (row + 1 < rows) {
queue.add(Triple(row + 1, col, weight + grid[row + 1][col]))
}
}
return minSum
}
/**
* Dijkstra's algorithm for finding the shortest paths between nodes in a graph involves
* using 2 arrays to store the distance from the source (sum in this case) for each vertex &
* whether each vertex has been processed. Using a PriorityQueue is faster than storing the sums
* & writing a function that finds the matrix element with the smallest sum so far.
*
* Since only the smallest sum path between the source and the target is required, regardless
* of the length of the path (how many steps it takes), the loop can be broken once the
* target element is reached.
*
* An adjacency matrix is initially created to link all neighbour vertices, instead of
* relying on conditional branches to generate the PriorityQueue.
*
* SPEED (BETTER) 97.71ms for N = 80
*/
fun minPathSumDijkstraImproved(rows: Int, grid: Array<IntArray>): Long {
val adjacents = makeAdjacencyMatrix(rows, grid)
val visited = Array(rows) { BooleanArray(rows) }
val compareByWeight = compareBy<Triple<Int, Int, Long>> { it.third }
val queue = PriorityQueue(compareByWeight).apply {
add(Triple(0, 0, grid[0][0].toLong()))
}
var minSum = 0L
while (queue.isNotEmpty()) {
val (row, col, weight) = queue.poll()
if (visited[row][col]) continue
if (row == rows - 1 && col == rows - 1) {
minSum = weight
break
}
visited[row][col] = true
for ((adjR, adjC, adjW) in adjacents[row][col]) {
if (!visited[adjR][adjC]) {
queue.add(Triple(adjR, adjC, weight + adjW))
}
}
}
return minSum
}
private fun makeAdjacencyMatrix(
rows: Int,
grid: Array<IntArray>
): Array<Array<List<Triple<Int, Int, Long>>>> {
// step up, left, down, right
val directions = listOf(-1 to 0, 0 to -1, 1 to 0, 0 to 1)
return Array(rows) { row ->
Array(rows) { col ->
directions.mapNotNull { (x, y) ->
val (adjR, adjC) = row + x to col + y
if (adjR in 0 until rows && adjC in 0 until rows) {
Triple(adjR, adjC, grid[adjR][adjC].toLong())
} else null
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 4,395 | project-euler-kotlin | MIT License |
src/Day02.kt | AndreiShilov | 572,661,317 | false | {"Kotlin": 25181} | fun main() {
fun pair(inputLine: String): Pair<Char, Char> {
val split = inputLine.split(" ")
val opponent = split[0].toCharArray()[0]
val we = split[1].toCharArray()[0]
return Pair(opponent, we)
}
fun solve1(inputLine: String): Int {
val (opponent, we) = pair(inputLine)
val game = we.code - opponent.code
println("Opponent - [${opponent}], we [${we}] game [$game]")
val result = when (game) {
22, 25 -> 0
23 -> 3
24, 21 -> 6
else -> throw IllegalStateException("Noooooo")
}
return (we.code - 87) + result
}
fun solve2(inputLine: String): Int {
val (opponent, we) = pair(inputLine)
val result = when (we) {
'X' -> 0 + ((opponent.code + 22) % 3)
'Y' -> 3 + ((opponent.code + 23) % 3)
'Z' -> 6 + ((opponent.code + 24) % 3)
else -> throw IllegalStateException("Noooooo")
}
println("Opponent - [${opponent}], we [${result}]")
return (we.code - 87) + result
}
fun part1(input: List<String>): Int {
return input.sumOf { solve1(it) }
}
fun part2(input: List<String>): Int {
return input.sumOf { solve2(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 852b38ab236ddf0b40a531f7e0cdb402450ffb9a | 1,564 | aoc-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.