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/dev/sirch/aoc/y2022/days/Day05.kt | kristofferchr | 573,549,785 | false | {"Kotlin": 28399, "Mustache": 1231} | package dev.sirch.aoc.y2022.days
import dev.sirch.aoc.Day
class Stack {
private val stack = mutableListOf<Char>()
fun peek(): Char {
return stack.last()
}
fun pop(amount: Int = 1): List<Char> {
return (0 until amount).map {
stack.removeLast()
}
}
fun push(crates: List<Char>) {
crates.forEach {
stack.add(it)
}
}
}
class CrateStacks(val cratesRaw: List<String>, val numberingWithIndexForCrates: List<Pair<Int, Int>>) {
private val stacks = initializeStacks()
fun initializeStacks(): Map<Int, Stack> {
return numberingWithIndexForCrates.associate { (numbering, crateIndexInRawString) ->
numbering to initializeStack(crateIndexInRawString)
}
}
fun initializeStack(indexForStack: Int): Stack {
val stack = Stack()
cratesRaw.map {
it.getOrElse(indexForStack) { ' ' }
}.filter {
it != ' '
}.reversed()
.forEach {
stack.push(listOf(it))
}
return stack
}
fun getAllCharOnTopOfStacks(): String {
return stacks.map {
it.value.peek()
}.joinToString("")
}
fun moveCratesBetweenStack(move: Move, multipleMoves: Boolean = false) {
val fromStack = stacks[move.from]!!
val toStack = stacks[move.to]!!
if (multipleMoves) {
val crates = fromStack.pop(move.amount).reversed()
toStack.push(crates)
} else {
repeat(move.amount) {
val removedCrate = fromStack.pop()
toStack.push(removedCrate)
}
}
}
}
data class Move(
val amount: Int,
val from: Int,
val to: Int
)
fun parseMoves(movesRaw: List<String>): List<Move> {
val commandKeywords = Regex("move|from|to")
return movesRaw.map { moveRaw ->
val (amount, from, to) = commandKeywords.split(moveRaw).map { it.trim() }.filter { it.isNotBlank() }
Move(amount.toInt(), from.toInt(), to.toInt())
}
}
fun getIndexesForCrates(numberingForCrates: String): List<Pair<Int, Int>> {
val numbers = numberingForCrates.trim().split(" ")
return numbers.map {
it.toInt() to numberingForCrates.indexOf(it)
}
}
fun performMovesAndGetTopCrates(input: List<String>, multipleMove: Boolean = false): String {
val indexofsplit = input.indexOf("")
val crates = input.subList(0, indexofsplit - 1)
val numberingforcrates = input[indexofsplit - 1]
val indexesForCrates = getIndexesForCrates(numberingforcrates)
val stacks = CrateStacks(crates, indexesForCrates)
val moves = input.subList(indexofsplit + 1, input.size)
val parsedmoves = parseMoves(moves)
parsedmoves.forEach {
stacks.moveCratesBetweenStack(it, multipleMove)
}
return stacks.getAllCharOnTopOfStacks()
}
class Day05(testing: Boolean = false): Day(2022, 5, testing) {
override fun part1(): String {
return performMovesAndGetTopCrates(inputLines)
}
override fun part2(): String {
return performMovesAndGetTopCrates(inputLines, multipleMove = true)
}
}
| 0 | Kotlin | 0 | 0 | 867e19b0876a901228803215bed8e146d67dba3f | 3,176 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2022/d14/Day14.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2022.d14
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
data class Point(val x: Int, val y: Int)
fun String.toPoint(): Point = split(",").let { (a, b) ->
Point(a.toInt(), b.toInt())
}
class Solver(input: Sequence<String>) {
private val blockedPoints: Set<Point>
private val maxDepth: Int
init {
val tmpBlockedPoints = mutableSetOf<Point>()
var tmpMaxDepth = 0
input.forEach { line ->
var prevPoint: Point? = null
line.split(" -> ")
.map { it.toPoint() }
.forEach { point ->
tmpMaxDepth = maxOf( tmpMaxDepth, point.y)
val prevPoint1 = prevPoint
if (prevPoint1 != null) {
val fromX = minOf(point.x, prevPoint1.x)
val toX = maxOf(point.x, prevPoint1.x)
val fromY = minOf(point.y, prevPoint1.y)
val toY = maxOf(point.y, prevPoint1.y)
(fromX..toX).forEach { x ->
(fromY..toY).forEach { y ->
tmpBlockedPoints.add(Point(x, y))
}
}
}
prevPoint = point
}
}
blockedPoints = tmpBlockedPoints
maxDepth = tmpMaxDepth
}
fun simulateFallingSand(sandSource: Point, partOne: Boolean): Int {
val bp = blockedPoints.toMutableSet()
fun isBlocked(point: Point): Boolean =
if (partOne) point in bp
else point in bp || point.y >= maxDepth + 2
fun simulateOne(): Boolean {
var sand = sandSource
while (true) {
if (partOne && sand.y > maxDepth) return false
if (!partOne && sandSource in bp) return false
when {
!isBlocked(sand.copy(y = sand.y + 1)) -> {
sand = sand.copy(y = sand.y + 1)
}
!isBlocked(Point(sand.x - 1, sand.y + 1)) -> {
sand = Point(sand.x - 1, sand.y + 1)
}
!isBlocked(Point(sand.x + 1, sand.y + 1)) -> {
sand = Point(sand.x + 1, sand.y + 1)
}
else -> {
bp.add(sand)
return true
}
}
}
}
var sandAtRest = 0
while (simulateOne()) sandAtRest++
return sandAtRest
}
}
fun main() = timed {
val solver = (DATAPATH / "2022/day14.txt").useLines { Solver(it) }
solver.simulateFallingSand(Point(500, 0), true)
.also { println("Part one: $it") }
solver.simulateFallingSand(Point(500, 0), false)
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,009 | advent-of-code | MIT License |
src/Day09.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} | import kotlin.math.abs
fun main() {
/**
* Calculate new position of tails after movement of head.
*/
fun newPosOfTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
val newtail: Pair<Int, Int>
// no tail movement, if there is no "big" difference in positions
if (abs(head.first - tail.first) < 2 && abs(head.second - tail.second) < 2)
return(tail)
// alright, we have to move the tail closer:
// only in a straight line?
if (head.first == tail.first) {
newtail = Pair(head.first, (head.second + tail.second) / 2)
return newtail
}
if (head.second == tail.second) {
newtail = Pair((head.first + tail.first) / 2, head.second)
return newtail
}
// or do we have to move diagonal?
// one coord is of difference 2, the other of difference 1
if (abs(head.first - tail.first) > abs(head.second - tail.second)) {
// first is of bigger difference, so ...
newtail = Pair((head.first + tail.first) / 2, head.second)
return newtail
} else if (abs(head.first - tail.first) < abs(head.second - tail.second)){
newtail = Pair(head.first, (head.second + tail.second) / 2)
return newtail
} else {
newtail = Pair((head.first + tail.first) / 2, (head.second + tail.second) / 2)
return newtail
}
}
fun part1(input: List<String>): Int {
// Moves:
// Tracking visited coords: Set of Pair (removes duplicates)
val visitedCoords = mutableSetOf<Pair<Int, Int>>()
// Calculate start (use 0,0)
// Head-Coord as Pair
var head = Pair(0, 0)
// Tail-Coord as Pair
var tail = Pair(0, 0)
// repeat for each line:
input.forEach {
val (cmd, times) = it.split(" ")
// repeat as often as line says:
for (i in 1..times.toInt()) {
// Move head one step udlr
when (cmd) {
"U" -> head = Pair(head.first - 1, head.second)
"D" -> head = Pair(head.first + 1, head.second)
"L" -> head = Pair(head.first, head.second - 1)
"R" -> head = Pair(head.first, head.second + 1)
}
// calc new pos of tail
tail = newPosOfTail(head, tail)
// add tail to set
visitedCoords.add(tail)
}
}
// return size of set
return visitedCoords.size
}
fun part2(input: List<String>): Int {
// What if we use an array of size (10)
// arr[0] is head, getting moved according to rules
// Then iterate over arr[1..9], each with
// arr[i] = calculateNewTail(arr[i-1], arr[i], i in 1..9
// then write down arr[9] as tail
val visitedCoords = mutableSetOf<Pair<Int, Int>>()
val rope = Array(10){ Pair(0, 0) }
// repeat for each line:
input.forEach {
val (cmd, times) = it.split(" ")
// repeat as often as line says:
for (i in 1..times.toInt()) {
// Move head one step udlr
when (cmd) {
"U" -> rope[0] = Pair(rope[0].first - 1, rope[0].second)
"D" -> rope[0] = Pair(rope[0].first + 1, rope[0].second)
"L" -> rope[0] = Pair(rope[0].first, rope[0].second - 1)
"R" -> rope[0] = Pair(rope[0].first, rope[0].second + 1)
}
// calc new pos of tail
for (j in 1..9) {
rope[j] = newPosOfTail(rope[j - 1], rope[j])
}
for (j in 0 until 9) {
check(abs(rope[j].first - rope[j + 1].first) < 2)
check(abs(rope[j].second - rope[j + 1].second) < 2)
}
// add tail to set
visitedCoords.add(rope[9])
}
}
//
// return size of set
return visitedCoords.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09-TestInput")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09-TestInput2")
check(part2(testInput2) == 36)
val input = readInput("Day09-Input")
check(part1(input) < 6128) // Answer was too high
println(part1(input))
check(part2(input) < 2561)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 4,636 | AoC-2022-12-01 | Apache License 2.0 |
src/Day07.kt | laricchia | 434,141,174 | false | {"Kotlin": 38143} | import kotlin.math.abs
import kotlin.math.roundToInt
fun firstPart07(list : List<Int>) {
getFuelConsumptionDescGrad(list) { average: Int ->
sumOf { abs(it - average) }
}
}
fun secondPart07(list : List<Int>) {
getFuelConsumptionDescGrad(list) { average ->
sumOf {
val steps = abs(it - average)
(1 .. steps).sum()
}
}
}
fun main() {
val input : List<String> = readInput("Day07")
val list = input.filter { it.isNotBlank() }.map { it.split(",").filter { it.isNotBlank() }.map { it.toInt() } }
firstPart07(list.first())
secondPart07(list.first())
}
inline fun getFuelConsumptionDescGrad(list: List<Int>, crossinline costFun : List<Int>.(Int) -> Int) {
val averagePosition = list.average().roundToInt()
var localMinReached = false
var currentPosition = averagePosition
var lastConsumedFuel : Int = list.costFun(averagePosition)
var minConsumedFuel = lastConsumedFuel
var minPosition = currentPosition
var lastIncrease = true
var increasingDirection = true
var iterations = 0
currentPosition ++
while (!localMinReached) {
iterations++
val currentConsumedFuel = list.costFun(currentPosition)
if (currentConsumedFuel < minConsumedFuel) {
minConsumedFuel = currentConsumedFuel
minPosition = currentPosition
increasingDirection = lastIncrease
}
if (currentConsumedFuel < lastConsumedFuel) {
if (lastIncrease) currentPosition++ else currentPosition--
} else if (currentConsumedFuel > lastConsumedFuel) {
if (lastIncrease) currentPosition -- else currentPosition ++
lastIncrease = !lastIncrease
}
if (currentPosition == minPosition && lastIncrease == increasingDirection) localMinReached = true
lastConsumedFuel = currentConsumedFuel
// println("consumption at $currentPosition: $currentConsumedFuel\n")
}
println("Solution after $iterations iteration: ------------------")
println("consumption at $minPosition: $minConsumedFuel")
}
| 0 | Kotlin | 0 | 0 | 7041d15fafa7256628df5c52fea2a137bdc60727 | 2,122 | Advent_of_Code_2021_Kotlin | Apache License 2.0 |
src/main/kotlin/ALU_24.kt | Flame239 | 433,046,232 | false | {"Kotlin": 64209} | val instructions: List<Instruction> by lazy {
readFile("ALU").split("\n").map { l ->
l.split(" ").let { if (it.size == 2) Instruction(it[0], it[1], "") else Instruction(it[0], it[1], it[2]) }
}
}
val mapVarToInd = mapOf(
"w" to 0,
"x" to 1,
"y" to 2,
"z" to 3
)
val variables = IntArray(4)
fun main() {
// https://github.com/dphilipson/advent-of-code-2021/blob/master/src/days/day24.rs
// max = 99999795919456
// min = 45311191516111
val input = "45311191516111".map { it.digitToInt() }
var inputIndex = 0
instructions.forEach { i ->
val varIndex = mapVarToInd[i.arg1]!!
when (i.op) {
"inp" -> {
variables[varIndex] = input[inputIndex]
inputIndex++
}
"add" -> {
variables[varIndex] = calculate(variables[varIndex], i.arg2) { a, b -> a + b }
}
"mul" -> {
variables[varIndex] = calculate(variables[varIndex], i.arg2) { a, b -> a * b }
}
"div" -> {
variables[varIndex] = calculate(variables[varIndex], i.arg2) { a, b -> a / b }
}
"mod" -> {
variables[varIndex] = calculate(variables[varIndex], i.arg2) { a, b -> a % b }
}
"eql" -> {
variables[varIndex] = calculate(variables[varIndex], i.arg2) { a, b -> if (a == b) 1 else 0 }
}
}
}
println(variables.contentToString())
}
fun calculate(arg1: Int, arg2: String, op: (Int, Int) -> Int): Int {
val arg2Value = mapVarToInd[arg2]?.let { variables[it] } ?: arg2.toInt()
return op(arg1, arg2Value)
}
data class Instruction(val op: String, val arg1: String, val arg2: String)
| 0 | Kotlin | 0 | 0 | ef4b05d39d70a204be2433d203e11c7ebed04cec | 1,778 | advent-of-code-2021 | Apache License 2.0 |
src/day14/Day14.kt | felldo | 572,762,654 | false | {"Kotlin": 104604} | package day14
import readInputString
import java.lang.Integer.max
fun main() {
fun buildCave(input: List<String>, addFloor: Boolean): Array<Array<Int>> {
val cave = Array(1_000) { Array(1_000) { 0 } }
var lowest = 0
for (line in input) {
val pts = line.split(" -> ").toMutableList()
val firstPt = pts.removeFirst().split(",")
var fx = firstPt[0].toInt()
var fy = firstPt[1].toInt()
for (pt in pts) {
val secondPt = pt.split(",").toMutableList()
val sx = secondPt[0].toInt()
val sy = secondPt[1].toInt()
while (fx < sx) {
cave[fx][fy] = 1
fx++
}
while (fx > sx) {
cave[fx][fy] = 1
fx--
}
while (fy < sy) {
cave[fx][fy] = 1
fy++
}
while (fy > sy) {
cave[fx][fy] = 1
fy--
}
cave[sx][sy] = 1
lowest = max(lowest, sy)
}
}
if (addFloor) {
for (x in 0..999) {
cave[x][lowest+2] = 1
}
}
return cave
}
fun pourSand(cave: Array<Array<Int>>): Int {
var totalSand = 0
var moreSand = true
while (moreSand) {
moreSand = false
var x = 500
var y = 0
while (x in 1..998 && y+1 in 0..999 && (cave[x][y+1] == 0 || cave[x-1][y+1] == 0 || cave[x+1][y+1] == 0)) {
y++
x = when {
cave[x][y] == 0 -> x
cave[x-1][y] == 0 -> x - 1
else -> x + 1
}
}
if (x in 1..998 && y in 1..998) {
cave[x][y] = 2
moreSand = true
totalSand++
}
}
return totalSand
}
fun part1(input: List<String>): Int {
val cave = buildCave(input, false)
return pourSand(cave)
}
fun part2(input: List<String>): Int {
val cave = buildCave(input, true)
return pourSand(cave) + 1
}
val testInput = readInputString("day14/test")
val input = readInputString("day14/input")
check(part1(testInput) == 24)
println(part1(input))
check(part2(testInput) == 93)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 2,534 | advent-of-code-kotlin-2022 | Apache License 2.0 |
y2023/src/main/kotlin/adventofcode/y2023/Day06.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
fun main() {
Day06.solve()
}
object Day06 : AdventSolution(2023, 6, "Wait For It") {
override fun solvePartOne(input: String): Long {
val (times, distances) = input.lines().map {
"\\d+".toRegex().findAll(it).map { it.value.toLong() }
}
return times.zip(distances)
.map { (time, record) -> waysToBeatTheRecord(time, record) }
.reduce(Long::times)
}
override fun solvePartTwo(input: String): Long {
val (time, distance) = input.lines().map {
"\\d+".toRegex().findAll(it).joinToString(separator = "", transform = MatchResult::value).toLong()
}
return waysToBeatTheRecord(time, distance)
}
}
private fun waysToBeatTheRecord(time: Long, distanceToBeat: Long): Long {
// Quadratic equation: tb - b² > d
// t: total race time, b: button press milli's, d: distance to beat
// So we use the quadratic formula to find the intercepts
val d = sqrt(time * time - 4.0 * distanceToBeat)
val t1 = (time - d) / 2
val t2 = (time + d) / 2
// A little bit of shenanigans to work around the case where x1 or x2 is an integer
// We have to strictly beat the record.
val firstFaster = floor(t1 + 1).toLong()
val lastFaster = ceil(t2 - 1).toLong()
return lastFaster - firstFaster + 1
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,474 | advent-of-code | MIT License |
src/main/kotlin/com/github/michaelbull/advent2023/day13/MirrorMap.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.day13
import com.github.michaelbull.advent2023.math.Vector2CharMap
import com.github.michaelbull.advent2023.math.toVector2CharMap
fun Sequence<String>.toMirrorMap(): MirrorMap {
val patterns = mutableListOf<Vector2CharMap>()
val pattern = mutableListOf<String>()
fun addPattern() {
if (pattern.isNotEmpty()) {
patterns += pattern.toVector2CharMap()
}
}
fun reset() {
pattern.clear()
}
for (line in this) {
if (line.isEmpty()) {
addPattern()
reset()
} else {
pattern += line
}
}
addPattern()
return MirrorMap(patterns.toList())
}
data class MirrorMap(
val patterns: List<Vector2CharMap>,
) {
fun summarize(distinctCount: Int): Int {
return patterns.sumOf { pattern ->
pattern.summarize(distinctCount)
}
}
private fun Vector2CharMap.summarize(distinctCount: Int): Int {
val columnsLeft = findReflectedX(distinctCount) ?: 0
val rowsAbove = findReflectedY(distinctCount) ?: 0
return (rowsAbove * 100) + columnsLeft
}
private fun Vector2CharMap.findReflectedX(distinctCount: Int): Int? {
return findReflected(distinctCount, HorizontalAxis(this))
}
private fun Vector2CharMap.findReflectedY(distinctCount: Int): Int? {
return findReflected(distinctCount, VerticalAxis(this))
}
private fun Vector2CharMap.findReflected(distinctCount: Int, axis: Axis): Int? {
return axis.range.drop(1).find { i ->
countDistinctReflections(axis, 0..<i) == distinctCount
}
}
private fun Vector2CharMap.countDistinctReflections(axis: Axis, range: IntRange): Int {
return range.sumOf { delta ->
zipReflectedChars(axis, range.last, delta).count(::isDistinct)
}
}
private fun Vector2CharMap.zipReflectedChars(axis: Axis, original: Int, delta: Int): List<Pair<Char, Char>> {
val originalChars = axis.opposite.map { this[axis(original - delta, it)] }
val reflectedChars = axis.opposite.mapNotNull { this.getOrNull(axis(original + delta + 1, it)) }
return originalChars.zip(reflectedChars)
}
private fun <A, B> isDistinct(pair: Pair<A, B>): Boolean {
return pair.first != pair.second
}
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 2,373 | advent-2023 | ISC License |
src/Day09.kt | bjornchaudron | 574,072,387 | false | {"Kotlin": 18699} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val sim = Simulation(2)
input.forEach { sim.move(it) }
return sim.tailHistory.size
}
fun part2(input: List<String>): Int {
val sim = Simulation(10)
input.forEach { sim.move(it) }
return sim.tailHistory.size
}
// test if implementation meets criteria from the description, like:
val day = "09"
val testInput = readLines("Day${day}_test")
check(part1(testInput) == 13)
// check(part2(testInput) == 36)
val input = readLines("Day$day")
println(part1(input))
println(part2(input))
}
data class Move(val direction: String, val times: Int)
class Simulation(private val length: Int) {
var rope = Array(length) { Point(0, 0) }
val tailHistory = mutableSetOf<Point>()
fun move(line: String) {
val move = parseMove(line)
repeat(move.times) {
moveHead(move.direction)
for (s in 1 until length) {
moveTail(s)
tailHistory.add(rope.last())
}
}
}
private fun parseMove(instruction: String): Move {
val (direction, times) = instruction.split(" ")
return Move(direction, times.toInt())
}
private fun moveHead(direction: String) {
val head = rope.first()
rope[0] = when (direction) {
"U" -> Point(head.x, head.y + 1)
"D" -> Point(head.x, head.y - 1)
"L" -> Point(head.x + 1, head.y)
"R" -> Point(head.x - 1, head.y)
else -> error("Invalid direction")
}
}
private fun isAdjacent(head: Point, tail: Point) = abs(head.x - tail.x) <= 1 && abs(head.y - tail.y) <= 1
private fun moveTail(segment: Int) {
val head = rope[segment - 1]
val tail = rope[segment]
if (isAdjacent(head, tail)) return
val dx = getDelta(tail.x, head.x)
val dy = getDelta(tail.y, head.y)
rope[segment] = Point(tail.x + dx, tail.y + dy)
}
private fun getDelta(a: Int, b: Int) = when {
a < b -> 1
a > b -> -1
else -> 0
}
} | 0 | Kotlin | 0 | 0 | f714364698966450eff7983fb3fda3a300cfdef8 | 2,170 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch5/Problem51.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch5
import dev.bogwalk.util.combinatorics.combinations
import dev.bogwalk.util.maths.isPrime
import dev.bogwalk.util.maths.primeNumbers
import dev.bogwalk.util.search.binarySearch
import kotlin.math.pow
/**
* Problem 51: Prime Digit Replacements
*
* https://projecteuler.net/problem=51
*
* Goal: Find the smallest N-digit prime which, by replacing K digits of the number with the same
* digit, is part of an L-prime value family at minimum. K digits are not necessarily adjacent &
* leading zeroes should not be considered.
*
* Constraints: 2 <= N <= 7, 1 <= K <= N, and 1 <= L <= 8
*
* Prime value family: A set of prime numbers generated by replacing the same digits with a new
* digit.
* e.g. Replacing the 3rd & 4th digits of 56**3 -> {56003, 56113, 56333, 56443, 56663, 56773, 56993}
*
* e.g.: N = 2, K = 1, L = 3
* replace 1 digit in 1* -> {11, 13, 17, 19}
* smallest 3-prime value family = {11, 13, 17}
*/
class PrimeDigitReplacements {
/**
* Solution optimised based on the following:
*
* - Generate all [n]-digit primes first.
*
* - Only replace digits that are of a value less than the maximum required to generate
* [length] primes.
*
* - Check for primality using a binary search through generated primes.
*
* - Break loop once a family of primes of desired [length] is found, ensuring the family is
* the smallest lexicographically, if multiple exist.
*/
fun smallestPrimeDigitRepl(n: Int, k: Int, length: Int): List<Int> {
var smallest = emptyList<Int>()
val maxDigit = (9 - length + 1).digitToChar()
val upperBounds = (10.0).pow(n).toInt() - 1
val lowerBounds = (10.0).pow(n - 1).toInt()
val primes = primeNumbers(upperBounds)
for (prime in primes) {
if (prime < lowerBounds) continue
val families = getReplacements(prime, maxDigit, k).map { newNums ->
newNums.filter { num -> binarySearch(num, primes) }
}.filter { family ->
family.size >= length - 1
}
if (families.isNotEmpty()) {
smallest = listOf(prime) + (
families.minByOrNull { it.first() }?.take(length - 1) ?: emptyList()
)
break
}
}
return smallest
}
/**
* e.g.:
* "769" with [k] = 1, [maxDigit] = "6" -> "7*9" -> [[779, 789, 799]]
*
* "797" with [k] = 2, [maxDigit] = "7" -> "*9*" -> [[898, 999]]
*
* "7677" with [k] = 2, [maxDigit] = "7" -> "*6*7", "*67*", "76**" ->
* [[8687, 9697], [8678, 9679], [7688, 7699]
*
* @param [p] prime to have its digits replaced.
* @param [maxDigit] max value a digit can be to allow L-primes to be generated.
* @param [k] number of equal digits to be replaced.
* @return list of all integer lists generated as a result of replacing k-digits of equal
* value. The original prime is not included, to avoid it being unnecessarily checked for
* primality in calling function.
*/
private fun getReplacements(
p: Int, maxDigit: Char, k: Int
): List<List<Int>> {
val replaced = mutableListOf<Char>()
val replacements = mutableListOf<List<Int>>()
val prime = p.toString()
for (digit in prime) {
if (digit <= maxDigit && prime.count { it == digit } >= k && digit !in replaced) {
replaced.add(digit)
for (perm in combinations(prime.indices.filter { prime[it] == digit }, k)) {
val matches = mutableListOf<Int>()
for (d in digit.digitToInt() + 1 until 10) {
matches.add(prime.mapIndexed { index, ch ->
if (index in perm) d.digitToChar() else ch
}.joinToString("").toInt())
}
replacements.add(matches)
}
}
}
return replacements
}
/**
* Project Euler specific implementation that requires the smallest prime that is part of an
* 8-prime value family to be returned. The amount of digits to be replaced is not specified,
* so all values of K should be attempted for numbers greater than 56009 (the next prime
* after 56003, which is the smallest prime to be in a 7-prime value family).
*
* It is optimised by only replacing digits in {0, 1, 2} as anything greater would not be
* able to generate 7 more primes of greater value.
*/
fun smallest8PrimeFamily(): Int {
var n = 56009
outer@while (true) {
if (n.isPrime()) {
// replace single digits only
val num = n.toString()
for ((i, digit) in num.withIndex()) {
if (digit <= '2') {
val family = (digit.digitToInt() + 1 until 10).map {
num.replaceRange(i..i, it.toString()).toInt()
}.filter { it.isPrime() }
if (family.size == 7) break@outer
}
}
// replace multiple digits only
val multiples = mutableListOf<Char>()
for (digit in num) {
if (digit <= '2' && num.count { it == digit } > 1 && digit !in multiples) {
multiples.add(digit)
val family = (digit.digitToInt() + 1 until 10).map {
num.replace(digit, it.digitToChar()).toInt()
}.filter { it.isPrime() }
if (family.size == 7) break@outer
}
}
}
n += 2
}
return n
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 5,900 | project-euler-kotlin | MIT License |
src/2022/Day14.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | package `2022`
import readInput
fun main() {
val startY = 0
val startX = 500
fun simulateSandFall(filledPoints: Set<Point>, maxY: Int): Point? {
var x = startX
var lastSandPoint = Point(0, 500)
(startY..maxY).forEach { y ->
listOf(x, x - 1, x + 1).find {
!filledPoints.contains(Point(it, y))
}?.let {
x = it
lastSandPoint = Point(x, y)
} ?: return lastSandPoint
}
return null
}
fun simulateSandFallWithFloor(filledPoints: Set<Point>, floorY: Int): Point {
var x = startX
var lastSandPoint = Point(startX, startY)
(startY until floorY).forEach { y ->
listOf(x, x - 1, x + 1).find {
!filledPoints.contains(Point(it, y))
}?.let {
x = it
lastSandPoint = Point(x, y)
} ?: return lastSandPoint
}
return lastSandPoint
}
fun readRocks(input: List<String>): Set<Point> {
val rocks = input.flatMap { path ->
path
.split("->")
.map {
val (x, y) = it.trim().split(",").map(String::toInt)
Point(x, y)
}
.windowed(2)
.flatMap { (first, second) -> first.straightLine(second) }
}.toSet()
return rocks
}
fun printMap(rocks: Set<Point>, filledPoints: Set<Point>) {
val maxY = filledPoints.map { it.y }.max()
val maxX = filledPoints.map { it.x }.max()
val minX = filledPoints.map { it.x }.min()
println((0..maxY).joinToString(separator = "\n") { y ->
(minX..maxX).joinToString(separator = "") { x ->
if (rocks.contains(Point(x, y))) {
"#"
} else if (filledPoints.contains(Point(x, y))) {
"O"
} else {
"."
}
}
})
}
fun part1(input: List<String>, debug: Boolean = false): Int {
val rocks = readRocks(input)
val maxY = rocks.map { it.y }.max()
val filledPoints = rocks.toMutableSet()
do {
val nextSandDrop = simulateSandFall(filledPoints, maxY)
nextSandDrop?.let { filledPoints.add(it) }
} while (nextSandDrop != null)
if (debug) {
printMap(rocks, filledPoints)
}
return filledPoints.size - rocks.size
}
fun part2(input: List<String>, debug: Boolean = false): Int {
val rocks = readRocks(input)
val floorY = rocks.map { it.y }.max() + 2
val filledPoints = rocks.toMutableSet()
do {
val nextSandDrop = simulateSandFallWithFloor(filledPoints, floorY)
filledPoints.add(nextSandDrop)
} while (nextSandDrop != Point(startX, startY))
if (debug) {
printMap(rocks, filledPoints)
}
return filledPoints.size - rocks.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
println(part1(testInput, true))
println(part2(testInput, true))
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
private fun Point.straightLine(to: Point): List<Point> {
if (x == to.x) {
return (Math.min(y, to.y)..Math.max(y, to.y)).map { Point(x, it) }
}
if (y == to.y) {
return (Math.min(x, to.x)..Math.max(x, to.x)).map { Point(it, y) }
}
error("Not a straight line")
}
| 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 3,701 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day11.kt | robinpokorny | 572,434,148 | false | {"Kotlin": 38009} | data class Monkey(
val items: ArrayDeque<Int>,
val operation: (Int, Int?) -> Int,
val test: Int,
val onPass: Int,
val onFail: Int,
var inspected: Long = 0
)
private fun parse(input: List<String>) = input
.joinToString("\n")
.split("\n\n")
.map { it.lines() }
.map {
Monkey(
it[1]
.substring(18)
.split(", ")
.map(String::toInt)
.let(::ArrayDeque),
it[2]
.substring(23)
.split(" ")
.let{(op, arg) -> parseOperation(op, arg)},
it[3].substring(21).toInt(),
it[4].substring(29).toInt(),
it[5].substring(30).toInt(),
)
}
private fun parseOperation(op: String, arg: String) = when {
arg == "old" -> { i: Int, mod: Int? ->
(i.toLong() * i.toLong()).mod(mod ?: Int.MAX_VALUE)
}
op == "*" -> { i, mod ->
(i * (arg.toInt())).mod(mod ?: Int.MAX_VALUE)
}
op == "+" -> { i, mod ->
(i + (arg.toInt())).mod(mod ?: Int.MAX_VALUE)
}
else -> error("Unknown operation")
}
private fun part1(monkeys: List<Monkey>): Long {
repeat(20) {
monkeys.forEach {
it.inspected += it.items.size
it.items.forEach { item ->
val nextItem = it.operation(item, null) / 3
val nextMonkey =
if (nextItem % it.test == 0) it.onPass else it.onFail
monkeys[nextMonkey].items.addLast(nextItem)
}
it.items.clear()
}
}
return monkeys
.map { it.inspected }
.sortedDescending()
.take(2)
.let { (a, b) -> a * b }
}
private fun part2(monkeys: List<Monkey>): Long {
val product = monkeys
.map { it.test }
.reduce(Int::times)
repeat(10_000) {
monkeys.forEach {
it.inspected += it.items.size
it.items.forEach { item ->
val nextItem = it.operation(item, product)
val nextMonkey =
if (nextItem % it.test == 0) it.onPass else it.onFail
monkeys[nextMonkey].items.addLast(nextItem)
}
it.items.clear()
}
}
monkeys.forEach {
println(it.inspected)
}
return monkeys
.map { it.inspected }
.sortedDescending()
.take(2)
.let { (a, b) -> a * b }
}
fun main() {
val input = parse(readDayInput(11))
val testInput = parse(rawTestInput)
// PART 1
assertEquals(part1(testInput), 10605)
println("Part1: ${part1(input)}")
// PART 2
// We mutate the Monkeys, so we need a new input
val input2 = parse(readDayInput(11))
val testInput2 = parse(rawTestInput)
assertEquals(part2(testInput2), 2713310158)
println("Part2: ${part2(input2)}")
}
private
val rawTestInput = """
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
""".trimIndent().lines() | 0 | Kotlin | 0 | 2 | 56a108aaf90b98030a7d7165d55d74d2aff22ecc | 3,563 | advent-of-code-2022 | MIT License |
src/Day14.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day14.run {
solve1(24) // 674
solve2(93) // 24958
}
}.let { println("Total: $it ms") }
}
object Day14 : Day.LineInput<Day14.Data, Int>("14") {
class Data(val map: Array<BooleanArray>, val startX: Int)
override fun parse(input: List<String>) = input.map { path ->
path.split(" -> ").map { it.split(",").let { (x, y) -> x.toInt() to y.toInt() } }
}.let { paths ->
val (minX, maxX, maxY) = paths.fold(intArrayOf(Int.MAX_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)) { acc, path ->
for ((x, y) in path) {
acc[0] = minOf(acc[0], x)
acc[1] = maxOf(acc[1], x)
acc[2] = maxOf(acc[2], y)
}
acc
}
val map = Array(maxY + 1) { BooleanArray(maxX - minX + 1) }
for (path in paths) {
for (i in 0 until path.lastIndex) {
val (x1, y1) = path[i]
val (x2, y2) = path[i + 1]
for (x in minOf(x1, x2) - minX..maxOf(x1, x2) - minX) {
for (y in minOf(y1, y2)..maxOf(y1,y2)) {
map[y][x] = true
}
}
}
}
Data(map, 500 - minX)
}
override fun part1(data: Data): Int {
var res = 0
val startX = data.startX
val blocked = Array(data.map.size) { data.map[it].copyOf() }
fun fall(): Boolean {
if (blocked[0][startX]) return false
var currX = startX
for (y in 0 until blocked.lastIndex) {
currX = when {
!blocked[y + 1][currX] -> currX
currX == 0 -> return false
!blocked[y + 1][currX - 1] -> currX - 1
currX == blocked[y + 1].lastIndex -> return false
!blocked[y + 1][currX + 1] -> currX + 1
else -> {
blocked[y][currX] = true
return true
}
}
}
return false
}
while (fall()) ++res
return res
}
override fun part2(data: Data): Int {
val map = data.map
val mid = data.startX
val noSand = BooleanArray(map.first().size)
fun updateNoSand() {
var left = 0
while (left < noSand.size) {
while (left < noSand.size && !noSand[left]) ++left
var right = left
while (right < noSand.size && noSand[right]) ++right
if (left < noSand.size) noSand[left] = false
noSand[right - 1] = false
left = right
}
}
var res = 0
for (y in map.indices) {
updateNoSand()
for (x in map[y].indices) {
if (map[y][x] && x in mid - y..mid + y) noSand[x] = true
}
res += y * 2 + 1 - noSand.count { it }
}
updateNoSand()
res += map.size * 2 + 1 - noSand.count { it }
return res.also(::println)
}
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 3,194 | AdventOfCode2022 | Apache License 2.0 |
src/Day10.kt | thorny-thorny | 573,065,588 | false | {"Kotlin": 57129} | import kotlin.math.absoluteValue
class CPU(instructions: Sequence<Instruction>) {
private val instructionsIterator = instructions.iterator()
private var runningInstruction: Instruction? = null
private var instructionCyclesLeft = 0
var regX = 1
private set
var cycles = 0
private set
fun cycle() {
if (runningInstruction == null) {
val nextInstruction = instructionsIterator.next()
runningInstruction = nextInstruction
instructionCyclesLeft = nextInstruction.cycles // idk why smart cast doesn't work for runningInstruction.cycles
}
instructionCyclesLeft -= 1
if (instructionCyclesLeft == 0) {
when (val instruction = runningInstruction) {
is Instruction.NoOp -> {}
is Instruction.AddX -> regX += instruction.value
null -> {}
}
runningInstruction = null
}
cycles += 1
}
fun cycleUntil(predicate: CPU.() -> Boolean) {
while (!predicate()) {
cycle()
}
}
}
class CRT() {
val width = 40
val height = 6
private val pixels = List(height) { MutableList (width) { false } }
fun drawPixel(index: Int, spriteX: Int) {
val x = index % width
pixels[index / width][x] = (x - spriteX).absoluteValue <= 1
}
override fun toString(): String {
return pixels.joinToString("\n") { line ->
line.joinToString("") {
when (it) {
true -> "#"
false -> "."
}
}
}
}
}
class Device(instructions: Sequence<Instruction>) {
private val cpu = CPU(instructions)
private val crt = CRT()
fun runProgram() {
val pixels = crt.width * crt.height
while (cpu.cycles < pixels) {
crt.drawPixel(cpu.cycles, cpu.regX)
cpu.cycle()
}
}
override fun toString(): String {
return crt.toString()
}
}
sealed class Instruction private constructor (val cycles: Int) {
class NoOp: Instruction(1)
class AddX(val value: Int): Instruction(2)
}
fun main() {
fun parseInstruction(line: String): Instruction {
val parts = line.split(' ')
return when (parts.first()) {
"noop" -> Instruction.NoOp()
"addx" -> Instruction.AddX(parts[1].toInt())
else -> throw Exception("Unknown instruction")
}
}
fun part1(input: List<String>): Int {
val cpu = CPU(input.asSequence().map(::parseInstruction))
val signalCycles = listOf(20, 60, 100, 140, 180, 220)
return signalCycles.sumOf { signalCycle ->
cpu.cycleUntil { cycles == signalCycle - 1 }
signalCycle * cpu.regX
}
}
fun part2(input: List<String>): String {
val device = Device(input.asSequence().map(::parseInstruction))
device.runProgram()
return device.toString()
}
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 843869d19d5457dc972c98a9a4d48b690fa094a6 | 3,191 | aoc-2022 | Apache License 2.0 |
src/Day13.kt | JanTie | 573,131,468 | false | {"Kotlin": 31854} | fun main() {
fun parseString(input: String): List<*> {
val mutableList = mutableListOf<Any>()
fun listAtDepth(depth: Int): MutableList<Any> {
var list = mutableList
repeat((0 until depth).count()) {
list = list.last() as MutableList<Any>
}
return list
}
var currentDepth = 0
var currentString: String? = null
input.forEach { char ->
when (char) {
'[' -> listAtDepth(currentDepth).add(mutableListOf<Any>()).also { currentDepth++ }
']' -> {
currentString?.toInt()?.let {
listAtDepth(currentDepth).add(it)
currentString = null
}
currentDepth--
}
',' -> currentString?.toInt()?.let {
listAtDepth(currentDepth).add(it)
currentString = null
}
else -> {
if (currentString == null) {
currentString = char.toString()
} else {
currentString += char
}
}
}
}
return mutableList[0] as List<*>
}
fun parseInput(input: List<String>): List<List<*>> = input
.filter { it.isNotEmpty() }
.chunked(2)
.map { it.map { parseString(it) } }
fun isValid(left: List<*>, right: List<*>, currentIndex: Int = 0): Boolean? {
val currentLeft = left.getOrNull(currentIndex)
val currentRight = right.getOrNull(currentIndex)
if (currentLeft == null && currentRight == null) {
return null
}
if (currentLeft == null) {
return true
}
if (currentRight == null) {
return false
}
println("$currentLeft | $currentRight")
println()
if (currentLeft is Int && currentRight is Int) {
if (currentLeft > currentRight) return false
if (currentLeft < currentRight) return true
} else if (currentLeft is List<*> && currentRight is List<*>) {
isValid(currentLeft, currentRight)?.let { return it }
} else {
if (currentLeft is List<*> && currentRight is Int) {
isValid(currentLeft, listOf(currentRight))?.let { return it }
} else if (currentLeft is Int && currentRight is List<*>) {
isValid(listOf(currentLeft), currentRight)?.let { return it }
}
}
return isValid(left.drop(1), right.drop(1))
}
fun part1(input: List<String>): Int {
return parseInput(input).mapIndexed { index, (l, r) ->
val left = l as List<*>
val right = r as List<*>
return@mapIndexed if (isValid(left, right) == true) index + 1 else 0
}
.sum()
}
fun part2(input: List<String>): Int {
return parseInput(input)
.flatMap { (l, r) -> listOf(l as List<*>, r as List<*>) }
.sortedWith(Comparator { thiz, other ->
val result = isValid(thiz, other)
if (result == true) return@Comparator -1
if (result == false) return@Comparator 1
return@Comparator 0
})
.let {
println(it)
val first = it.indexOfFirst { it == listOf(listOf(2)) } + 1
val second = it.indexOfFirst { it == listOf(listOf(6)) } + 1
println("first: $first")
println("second: $second")
first * second
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
val input = readInput("Day13")
println(part1(testInput))
//check(part1(testInput) == 13)
println(part1(input))
println(part2(testInput))
check(part2(testInput) == 140)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3452e167f7afe291960d41b6fe86d79fd821a545 | 4,061 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day04.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2021
class Day04(private val input: String) {
fun solvePart1(): Int = solve(true)
fun solvePart2(): Int = solve(false)
private fun solve(firstMatch: Boolean): Int {
val parts = input.split("\n\n")
val numbers = parts.first().split(",").map(String::toInt)
val spaceRegex = Regex("\\s+")
val cards = parts.drop(1).map {
val rows = it.split("\n").map { row ->
row.trim().split(spaceRegex).map(String::toInt)
}
Card(rows)
}.toMutableList()
for (n in numbers) {
val cardIterator = cards.listIterator()
for (card in cardIterator) {
if (card.checkBingo(n)) {
cardIterator.remove()
if (firstMatch || cards.isEmpty()) {
return n * card.remainingNumbers.sum()
}
}
}
}
error("No solution found")
}
private class Card(rows: List<List<Int>>) {
private val numbers = mutableMapOf<Int, Pair<Int, Int>>()
private val rows = rows.map(List<Int?>::toMutableList).toMutableList()
private val columns = MutableList<MutableList<Int?>>(rows.first().size) { i ->
rows.map { row -> row[i] }.toMutableList()
}
val remainingNumbers: Set<Int>
get() = numbers.keys
init {
rows.forEachIndexed { x, row ->
row.forEachIndexed { y, n ->
numbers[n] = x to y
}
}
}
fun checkBingo(n: Int): Boolean {
val (x, y) = numbers.remove(n) ?: return false
val row = rows[x]
row[y] = null
val col = columns[y]
col[x] = null
return row.all { it == null } || col.all { it == null }
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,923 | advent-of-code | Apache License 2.0 |
src/Day19.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | import java.util.PriorityQueue
import kotlin.math.ceil
fun main() {
data class Cost(val ore: Int, val clay: Int, val obsidian: Int)
data class Blueprint(
val id: Int,
val oreRobotCost: Cost,
val clayRobotCost: Cost,
val obsidianRobotCost: Cost,
val geodeRobotCost: Cost
) {
private val costs = listOf(oreRobotCost, clayRobotCost, obsidianRobotCost, geodeRobotCost)
val maxOre = costs.maxOf { it.ore }
val maxClay = costs.maxOf { it.clay }
val maxObsidian = costs.maxOf { it.obsidian }
}
data class FactoryState(
val time: Int = 1,
val ore: Int = 1,
val oreRobots: Int = 1,
val clay: Int = 0,
val clayRobots: Int = 0,
val obsidian: Int = 0,
val obsidianRobots: Int = 0,
val geodes: Int = 0,
val geodeRobots: Int = 0
) : Comparable<FactoryState> {
fun addCost(cost: Cost): FactoryState {
val timeToAdd = maxOf(
if (cost.ore <= ore) 0 else ceil((cost.ore - ore) / oreRobots.toFloat()).toInt(),
if (cost.clay <= clay) 0 else ceil((cost.clay - clay) / clayRobots.toFloat()).toInt(),
if (cost.obsidian <= obsidian) 0 else ceil((cost.obsidian - obsidian) / obsidianRobots.toFloat()).toInt()
) + 1
return copy(
time = time + timeToAdd,
ore = (ore - cost.ore) + (timeToAdd * oreRobots),
clay = (clay - cost.clay) + (timeToAdd * clayRobots),
obsidian = (obsidian - cost.obsidian) + (timeToAdd * obsidianRobots),
geodes = geodes + (timeToAdd * geodeRobots)
)
}
fun buildNextStates(blueprint: Blueprint, budget: Int) = buildList {
if (blueprint.maxOre > oreRobots && ore > 0) {
add(addCost(blueprint.oreRobotCost).copy(oreRobots = oreRobots + 1))
}
if (blueprint.maxClay > clayRobots && ore > 0) {
add(addCost(blueprint.clayRobotCost).copy(clayRobots = clayRobots + 1))
}
if (blueprint.maxObsidian > obsidianRobots && ore > 0 && clay > 0) {
add(addCost(blueprint.obsidianRobotCost).copy(obsidianRobots = obsidianRobots + 1))
}
if (ore > 0 && obsidian > 0) {
add(addCost(blueprint.geodeRobotCost).copy(geodeRobots = geodeRobots + 1))
}
}.filter { it.time <= budget }
fun maxGeodes(budget: Int): Int {
val remainder = budget - time
// n(n+1)/2 for summation
val capacity = (remainder) * (remainder + 1) / 2 + geodeRobots * remainder
return geodes + capacity
}
override fun compareTo(other: FactoryState) = other.geodes.compareTo(geodes)
}
fun List<String>.toBlueprints() = this.mapIndexed { i, it ->
val parts = it.split(" ")
Blueprint(
i + 1,
Cost(parts[6].toInt(), 0, 0),
Cost(parts[12].toInt(), 0, 0),
Cost(parts[18].toInt(), parts[21].toInt(), 0),
Cost(parts[27].toInt(), 0, parts[30].toInt()),
)
}
fun maxGeodes(blueprint: Blueprint, budget: Int): Int {
var geodes = 0
val queue = PriorityQueue<FactoryState>().apply { add(FactoryState()) }
while (queue.isNotEmpty()) {
val state = queue.poll()
if (state.time < budget && state.maxGeodes(budget) > geodes) {
queue.addAll(state.buildNextStates(blueprint, budget))
}
geodes = maxOf(geodes, state.geodes)
}
return geodes
}
fun part1(input: List<String>): Int {
return input
.toBlueprints()
.sumOf { it.id * maxGeodes(it, 24) }
}
fun part2(input: List<String>): Int {
return input
.toBlueprints()
.take(3)
.map { maxGeodes(it, 32) }
.reduce { acc, it -> acc * it }
}
val testInput = readInput("Day19_test")
println(part1(testInput)) // 33
println(part2(testInput)) // 3472
val input = readInput("Day19")
println(part1(input)) // 1681
println(part2(input)) // 1996
}
| 0 | Kotlin | 0 | 0 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 4,270 | advent-of-code-2022 | Apache License 2.0 |
day20/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | import java.io.File
import java.lang.IllegalStateException
import java.util.*
fun main() {
val regex = readInputFile()[0]
val result = solveProblem(regex)
println("Part I: the solution is ${result.largestNumberOfDoors}.")
println("Part II: the solution is ${result.numberOfRoomsRequiring1000Doors}.")
}
fun readInputFile(): List<String> {
return File(ClassLoader.getSystemResource("input.txt").file).readLines()
}
fun solveProblem(regex: String): Result {
var current = Coordinate(0, 0)
val numberOfDoors = mutableMapOf(current to 0)
val queuedLocations = ArrayDeque<Coordinate>()
for (char in regex) {
when (char) {
'(' -> queuedLocations.add(current)
')' -> current = queuedLocations.pollLast()
'|' -> current = queuedLocations.peekLast()
'N', 'E', 'S', 'W' -> {
val next = current.advance(char)
if (numberOfDoors[next] != null && (numberOfDoors[current]!! + 1) < numberOfDoors[next]!! ||
numberOfDoors[next] == null) {
numberOfDoors[next] = numberOfDoors[current]!! + 1
}
current = next
}
}
}
val largestNumberOfDoors = numberOfDoors
.map { it.value }!!
.max()!!
val numberOfRoomsRequiring1000Doors = numberOfDoors
.filter { it.value >= 1000 }
.count()
return Result(largestNumberOfDoors, numberOfRoomsRequiring1000Doors)
}
data class Coordinate(val x: Int, val y: Int) {
fun advance(direction: Char): Coordinate {
when (direction) {
'N' -> return Coordinate(this.x, this.y + 1)
'E' -> return Coordinate(this.x + 1, this.y)
'S' -> return Coordinate(this.x, this.y - 1)
'W' -> return Coordinate(this.x - 1, this.y)
}
throw IllegalStateException("This line should not be reached.")
}
}
data class Result(val largestNumberOfDoors: Int, val numberOfRoomsRequiring1000Doors: Int)
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 2,057 | AdventOfCode2018 | MIT License |
2023/src/main/kotlin/day12.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Memo
import utils.Parse
import utils.Parser
import utils.Solution
import utils.mapItems
fun main() {
Day12.run()
}
object Day12 : Solution<List<Day12.Input>>() {
override val name = "day12"
override val parser = Parser.lines.mapItems { parseInput(it) }
@Parse("{map} {r ',' dmgGroups}")
data class Input(
val map: String,
val dmgGroups: List<Int>
) {
fun place(index: Int): Input? {
val group = dmgGroups.firstOrNull() ?: return null
if (map.length < index + group) return null
if (map.substring(index, index + group).any { it == '.' }) return null
if (index + group < map.length && map[index + group] == '#') return null
return Input(map.substring(minOf(index + group + 1, map.length)), dmgGroups.drop(1))
}
}
private val countArrangements = Memo<Input, Long> { input ->
val firstNonDotChar = input.map.indexOfFirst { it != '.' }
if (input.dmgGroups.isEmpty()) {
return@Memo if (input.map.none { it == '#' }) 1L else 0L
} else if (input.map.isEmpty() || firstNonDotChar == -1) {
return@Memo if (input.dmgGroups.isEmpty()) 1L else 0L
}
// check whether we can place a group
val nextWithPlaced = input.place(firstNonDotChar)?.let { this(it) } ?: 0L
// if first char is not '#' then we can also not place a group
val nextWithoutPlaced = if (input.map[firstNonDotChar] != '#') {
this(Input(input.map.substring(firstNonDotChar + 1), input.dmgGroups))
} else 0L
return@Memo (nextWithPlaced + nextWithoutPlaced)
}
override fun part1(): Long {
return input.sumOf { countArrangements(it) }
}
override fun part2(): Long {
return input
.map { line -> Input(List(5) { line.map }.joinToString("?"), List(5) { line.dmgGroups }.flatten()) }
.sumOf { countArrangements(it) }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,838 | aoc_kotlin | MIT License |
advent-of-code-2021/src/main/kotlin/Day15.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 15: Chiton
//https://adventofcode.com/2021/day/15
import java.io.File
import java.util.PriorityQueue
data class Position(val xy: Pair<Int, Int>, val risk: Int)
val queue = PriorityQueue(compareBy(Position::risk))
fun main() {
val risks = File("src/main/resources/Day15.txt").readLines().map { positions ->
positions.toList().map { it.digitToInt() }
}
val length = risks.size
val width = risks.first().size
val array = Array(length) { x ->
IntArray(width) { y ->
risks[x][y]
}
}
findLowestRiskPath(array)
val lengthX5 = 5 * length
val widthX5 = 5 * width
val arrayX5 = Array(lengthX5) { x ->
IntArray(widthX5) { y ->
val z = x / length + y / width
((risks[x % length][y % width] + z - 1) % 9) + 1
}
}
findLowestRiskPath(arrayX5)
}
fun findLowestRiskPath(array: Array<IntArray>) {
val length = array.size
val width = array.first().size
val delta = Array(length) { IntArray(width) { Int.MAX_VALUE } }
val visited = Array(length) { BooleanArray(width) }
delta[0][0] = 0
queue.add(Position(0 to 0, 0))
while (!visited[length - 1][width - 1]) {
val (xy, risk) = queue.remove()
val (x, y) = xy
if (visited[x][y]) continue
visited[x][y] = true
edgeRelax(array, delta, visited, x - 1, y, risk)
edgeRelax(array, delta, visited, x + 1, y, risk)
edgeRelax(array, delta, visited, x, y - 1, risk)
edgeRelax(array, delta, visited, x, y + 1, risk)
}
println(delta[length - 1][width - 1])
}
fun edgeRelax(array: Array<IntArray>, delta: Array<IntArray>, visited: Array<BooleanArray>, x: Int, y: Int, risk: Int) {
val length = array.size
val width = array.first().size
if (x !in 0 until length || y !in 0 until width || visited[x][y]) return
val newRisk = risk + array[x][y]
if (newRisk < delta[x][y]) {
delta[x][y] = newRisk
queue += Position(x to y, newRisk)
}
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,030 | advent-of-code | Apache License 2.0 |
src/main/kotlin/aoc23/Day04.kt | tahlers | 725,424,936 | false | {"Kotlin": 65626} | package aoc23
import java.math.BigInteger
object Day04 {
data class Card(val id: Int, val winningNumbers: Set<Int>, val numbers: Set<Int>) {
val hits = numbers.filter { it in winningNumbers }.size
fun calculateScore(): BigInteger =
if (hits == 0) BigInteger.ZERO else BigInteger.valueOf(2L).pow(hits - 1)
}
private val cardRegex = """Card\s+(\d+):""".toRegex()
private val whitespaceRegex = """\s+""".toRegex()
fun calculateScore(input: String): BigInteger {
val cards = parseInputToCards(input)
return cards.sumOf { it.calculateScore() }
}
fun calculateNumberOfScratchcards(input: String): Int {
val cards = parseInputToCards(input)
val resultCountMap = calculateCardCountMap(cards)
return resultCountMap.values.sum()
}
private fun calculateCardCountMap(cards: List<Card>): Map<Int, Int> {
val initial = cards.associate { it.id to 1 }
val resultCountMap = cards.fold(initial) { countMap, card ->
val currentCardNumbers = countMap.getOrDefault(card.id, 0)
val toCopyIds = (card.id + 1)..(card.id + card.hits)
val updated = toCopyIds.fold(countMap) { acc, id ->
acc + (id to (acc.getOrDefault(id, 0) + currentCardNumbers))
}
updated
}
return resultCountMap
}
private fun parseInputToCards(input: String): List<Card> {
val lines = input.trim().lines()
return lines.map { line ->
val id = cardRegex.find(line)?.groupValues?.get(1)?.toInt()
val winningNumbers = line.substringAfter(':').substringBefore('|')
.split(whitespaceRegex)
.filter { it.trim().isNotEmpty() }
.map { it.toInt() }
val numbers = line.substringAfter('|').split(whitespaceRegex)
.filter { it.trim().isNotEmpty() }
.map { it.toInt() }
Card(id!!, winningNumbers.toSet(), numbers.toSet())
}
}
} | 0 | Kotlin | 0 | 0 | 0cd9676a7d1fec01858ede1ab0adf254d17380b0 | 2,041 | advent-of-code-23 | Apache License 2.0 |
src/Day01.kt | benwicks | 572,726,620 | false | {"Kotlin": 29712} | fun main() {
fun part1(input: List<String>): Int {
return getCalorieSumsPerElf(input).maxOrNull() ?: -1
}
fun part2(input: List<String>): Int {
val mutableCalorieSumsPerElf = getCalorieSumsPerElf(input).toMutableList()
var sumOfTop3Sums = 0
for (i in 1..3) {
val maxCalorieSum = mutableCalorieSumsPerElf.maxOrNull()
mutableCalorieSumsPerElf.remove(maxCalorieSum)
maxCalorieSum?.let {
sumOfTop3Sums += maxCalorieSum
}
}
return sumOfTop3Sums
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24_000)
check(part2(testInput) == 45_000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
fun getCalorieSumsPerElf(input: List<String>): List<Int> {
val caloriesPerElf = mutableListOf<Int>()
var caloriesForCurrentElf = 0
for (line in input) {
if (line.isNotEmpty()) {
val caloriesInSnack = line.toInt()
caloriesForCurrentElf += caloriesInSnack
} else {
caloriesPerElf.add(caloriesForCurrentElf)
caloriesForCurrentElf = 0
}
}
caloriesPerElf.add(caloriesForCurrentElf)
return caloriesPerElf
}
| 0 | Kotlin | 0 | 0 | fbec04e056bc0933a906fd1383c191051a17c17b | 1,357 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2023/Day06.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2023
import AoCDay
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
// https://adventofcode.com/2023/day/6
object Day06 : AoCDay<Long>(
title = "Wait For It",
part1ExampleAnswer = 288,
part1Answer = 1660968,
part2ExampleAnswer = 71503,
part2Answer = 26499773,
) {
private class Race(val time: Long, val distanceRecord: Long)
private fun parseRaces(input: String, ignoreSpaces: Boolean): List<Race> {
fun String.parse() =
if (ignoreSpaces) listOf(filterNot(' '::equals).toLong())
else split(' ').filter(String::isNotBlank).map(String::toLong)
val (times, distances) = input.split('\n', limit = 2)
return times.substringAfter("Time:").parse().zip(distances.substringAfter("Distance:").parse())
.map { (time, distance) -> Race(time, distance) }
}
private fun Race.calculateNumberOfWaysToBeatRecord(): Long {
// c: charge time, t: time, d: distanceRecord
// c(t - c) > d <=> c^2 - ct < -d <=> c^2 - ct + (t/2)^2 < (t/2)^2 - d <=> (c - t/2)^2 < (t/2)^2 - d
// => c e ]t/2 - sqrt((t/2)^2 - d), t/2 + sqrt((t/2)^2 - d)[
val t2 = time / 2.0
val sqrt = sqrt(t2 * t2 - distanceRecord)
val min = floor(t2 - sqrt).toLong() + 1
val max = ceil(t2 + sqrt).toLong() - 1
return max - min + 1 // e.g. 2..5: 5 - 2 + 1 = 4
}
override fun part1(input: String) = parseRaces(input, ignoreSpaces = false)
.map { it.calculateNumberOfWaysToBeatRecord() }
.reduce(Long::times)
override fun part2(input: String) = parseRaces(input, ignoreSpaces = true)
.single()
.calculateNumberOfWaysToBeatRecord()
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 1,726 | advent-of-code-kotlin | MIT License |
src/day14/day14.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day14
import readInput
private fun parse(input: List<String>): Pair<Array<CharArray>, IntRange> {
var left = Int.MAX_VALUE
var right = Int.MIN_VALUE
var top = Int.MIN_VALUE
for (line in input) {
val parts = line.split(" -> ")
for (item in parts) {
val coordinates = item.split(",")
left = left.coerceAtMost(coordinates[0].toInt())
right = right.coerceAtLeast(coordinates[0].toInt())
top = top.coerceAtLeast(coordinates[1].toInt())
}
}
val startPoint = Pair(0, 500)
val result = Array(top + 1) { CharArray(1000) { '.' } }
result[startPoint.first][startPoint.second] = '+'
for (line in input) {
val parts = line.split(" -> ")
for (index in 0 until parts.size - 1) {
val start = parts[index].split(",")
val end = parts[index + 1].split(",")
if (start[0] == end[0]) {
val startRow = start[1].coerceAtMost(end[1]).toInt()
val endRow = start[1].coerceAtLeast(end[1]).toInt()
for (index in startRow..endRow) {
result[index][start[0].toInt()] = '#'
}
} else if (start[1] == end[1]) {
val startCol = start[0].coerceAtMost(end[0]).toInt()
val endCol = start[0].coerceAtLeast(end[0]).toInt()
for (index in startCol..endCol) {
result[start[1].toInt()][index] = '#'
}
} else throw IllegalStateException()
}
}
return Pair(result, IntRange(left, right))
}
private fun play(grid: Array<CharArray>, startPoint: Pair<Int, Int>, range: IntRange): Int {
var condition = true
var counter = 0
while (condition) {
val temp = helper(startPoint.first, startPoint.second, grid, range)
if (temp.first) counter++
condition = temp.first && temp.second
}
return counter
}
private fun helper(row: Int, col: Int, grid: Array<CharArray>, range: IntRange): Pair<Boolean, Boolean> {
if (col < range.first || col > range.last) return Pair(false, false)
if (row >= grid.size) return Pair(false, true)
if (grid[row][col] != '.' && grid[row][col] != '+') return Pair(false, true)
val moves = listOf(
{ helper(row + 1, col, grid, range) },
{ helper(row + 1, col - 1, grid, range) },
{ helper(row + 1, col + 1, grid, range) }
)
moves.forEach {
val temp = it.invoke()
if (temp.second.not()) return Pair(false, false)
if (temp.first) return Pair(true, true)
}
grid[row][col] = 'O'
return Pair(true, true)
}
private fun part1(input: List<String>): Int {
val parsedInput = parse(input)
return play(parsedInput.first, Pair(0, 500), parsedInput.second)
}
private fun part2(input: List<String>): Int {
val parsedInput = parse(input)
val normalizedInput = normalizedInput(parsedInput.first)
return play(normalizedInput, Pair(0, 500), IntRange(0, 1000))
}
private fun normalizedInput(grid: Array<CharArray>): Array<CharArray> {
val newGrid = Array(grid.size + 2) { CharArray(grid[0].size) { '.' } }
for ((rowIndex, row) in grid.withIndex()) {
for ((index, col) in row.withIndex()) {
newGrid[rowIndex][index] = col
}
}
for (index in 0 until newGrid[0].size) {
newGrid.last()[index] = '#'
}
return newGrid
}
fun main() {
val input = readInput("day14/input")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 3,592 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/icfp2019/app.kt | jzogg | 193,197,477 | true | {"JavaScript": 797354, "Kotlin": 19302, "HTML": 9922, "CSS": 9434} | package icfp2019
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
fun main() {
val workingDir: Path = Paths.get("")
val solutions = mutableListOf<Solution>()
readZipFile(File("problems.zip"))
.filter { it.line.isNotEmpty() }
.forEach {
val problem = parseDesc(it)
val solution = solve(problem)
encodeSolution(solution, workingDir)
}
writeZip(workingDir, solutions)
}
fun writeZip(workingDir: Path, solutions: MutableList<Solution>) {
TODO(workingDir.toString() + solutions.toString() + "not implemented")
}
fun readZipFile(file: File): List<ProblemDescription> {
TODO(file.toString() + "not implemented")
}
enum class Boosters {
B, F, L, X
}
data class Point(val x: Int, val y: Int)
data class Node(val point: Point, val isObstacle: Boolean, val booster: Boosters? = null)
data class ProblemId(val id: Int)
data class ProblemDescription(val problemId: ProblemId, val line: String)
data class Size(val x: Int, val y: Int)
data class Problem(
val problemId: ProblemId,
val size: Size,
val startingPosition: Point,
val map: Array<Array<Node>>
)
/*
Task:
1. Open Zip file
2. parse a problem at a time: prob_NNN.desc
3. solve problem
4. encode solution
5. output to file prob_NNN.sol (use checker to validate?) https://icfpcontest2019.github.io/solution_checker/
6. add solution to another zip (script/program)
*/
enum class Actions {
W, S, A, D, Z, E, Q, B, F, L
}
data class RobotState(
val robotId: RobotId,
val currentPosition: Point,
val orientation: Orientation = Orientation.Up,
val remainingFastWheelTime: Int? = null,
val remainingDrillTime: Int? = null
)
data class RobotId(val id: Int)
enum class Orientation {
Up, Down, Left, Right
}
data class GameState(
val gameBoard: Array<Short>, // TODO: Martin will replace with GameBoard Builder
val robotStateList: List<RobotState>,
val teleportDestination: List<Point>,
val unusedBoosters: List<Boosters>
)
data class Solution(val problemId: ProblemId, val actions: List<Actions>)
fun solve(problem: Problem): Solution {
return Solution(problem.problemId, listOf())
}
fun constructObstacleMap(problem: Problem): Array<Array<Boolean>> {
val rowSize = problem.map.size
val colSize = problem.map.get(0).size
// Create a Array of Array map for the given problem with
val rowObstacle = Array(rowSize) { Array(colSize) { false } }
val row = problem.map
for (i in row.indices) {
val colObstacle = Array(colSize) { false }
val col = row[i]
for (j in col.indices) {
val node = col[j]
if (node.isObstacle) {
colObstacle[j] = true
}
}
rowObstacle[i] = colObstacle
}
return rowObstacle
}
fun encodeSolution(solution: Solution, directory: Path): File {
val file = Files.createFile(directory.resolve("prob-${solution.problemId.id}.sol"))
// TODO
return file.toFile()
}
| 0 | JavaScript | 0 | 0 | 8d637f7feee33d2c7a030f94732bb16c850e047c | 3,069 | icfp-2019 | The Unlicense |
src/main/kotlin/adventofcode/day11.kt | Kvest | 163,103,813 | false | null | package adventofcode
fun main(args: Array<String>) {
first11(7803)
second11(7803)
}
private const val SIZE = 300
fun first11(gsn: Int) {
val f = calcField(gsn)
maxSqr(f, 3).printXYK()
}
fun second11(gsn: Int) {
val f = calcField(gsn)
val max = (1..SIZE).map { maxSqr(f, it) }.maxBy { it.max }
max?.printXYK()
}
fun maxSqr(f: Array<IntArray>, k: Int): MaxInf {
var max = Int.MIN_VALUE
var maxI = -1
var maxJ = -1
(1..(f.size - k)).forEach { i ->
(1..(f[i].size - k)).forEach { j ->
val sum = f[i + k - 1][j + k - 1] + f[i - 1][j - 1] - f[i - 1][j + k - 1] - f[i + k - 1][j - 1]
if (sum > max) {
max = sum
maxI = i
maxJ = j
}
}
}
return MaxInf(maxI - 1, maxJ - 1, max, k)
}
private fun calcField(gsn: Int): Array<IntArray> {
val f = Array(SIZE + 1) { y ->
IntArray(SIZE + 1) { x ->
if (x == 0 || y == 0) {
0
} else {
calc(x, y, gsn)
}
}
}
(1 until f.size).forEach { i ->
(1 until f[i].size).forEach { j ->
f[i][j] = f[i][j] + f[i - 1][j] + f[i][j - 1] - f[i - 1][j - 1]
}
}
return f
}
private fun calc(x: Int, y: Int, gsn: Int): Int {
val rackID = x + 10
val tmp = (rackID * y + gsn) * rackID
return ((tmp % 1000) / 100) - 5
}
data class MaxInf(val i: Int, val j: Int, val max: Int, val k: Int) {
fun printXYK() {
println("${j + 1},${i+1},${k}")
}
}
| 0 | Kotlin | 0 | 0 | d94b725575a8a5784b53e0f7eee6b7519ac59deb | 1,576 | aoc2018 | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/LengthOfLongestSubstring.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
import java.util.*
/**
* 3. 无重复字符的最长子串
* 给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
*
* 示例1:
*
* 输入: "abcabcbb"
* 输出: 3
* 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
* 示例 2:
*
* 输入: "bbbbb"
* 输出: 1
* 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
* 示例 3:
*
* 输入: "pwwkew"
* 输出: 3
* 解释: 因为无重复字符的最长子串是"wke",所以其长度为 3。
* 请注意,你的答案必须是 子串 的长度,"pwke"是一个子序列,不是子串。
*/
class LengthOfLongestSubstring {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(LengthOfLongestSubstring().solution("abcabcbb"))
println(LengthOfLongestSubstring().solution("bbbbb"))
println(LengthOfLongestSubstring().solution("pwwkew"))
println()
println(LengthOfLongestSubstring().solutionV2("abcabcbb"))
println(LengthOfLongestSubstring().solutionV2("bbbbb"))
println(LengthOfLongestSubstring().solutionV2("pwwkew"))
}
}
fun solution(s: String): Int {
var max = 0
val deque = ArrayDeque<Char>()
s.forEach {
while (deque.contains(it)) {
deque.removeFirst()
}
deque.add(it)
max = deque.size.coerceAtLeast(max)
}
return max
}
/**
* O(n)
* 滑动窗口
*/
fun solutionV2(s: String): Int {
var max = 0
var left = 0
var right = 0
val map = hashMapOf<Char, Int>()
while (right < s.length) {
if (map.contains(s[right]) && map[s[right]] ?: 0 >= left) {
left = (map[s[right]] ?: 0) + 1
}
map[s[right]] = right
max = max.coerceAtLeast(++right - left)
}
return max
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,053 | daily_algorithm | Apache License 2.0 |
src/Day02.kt | rbraeunlich | 573,282,138 | false | {"Kotlin": 63724} | fun main() {
fun calculateRound(round: RoundPart1): Int =
when (round.opponentsTurn) {
"A" -> if (round.myTurn == "Y") 6 else if (round.myTurn == "X") 3 else 0
"B" -> if (round.myTurn == "Z") 6 else if (round.myTurn == "Y") 3 else 0
"C" -> if (round.myTurn == "X") 6 else if (round.myTurn == "Z") 3 else 0
else -> 0
}
fun calculateChoicePoints(round: RoundPart1): Int =
when (round.myTurn) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
fun part1(input: List<String>): Int {
var totalScore = 0
input.forEach {
val split = it.split(" ")
val round = RoundPart1(split[0], split[1])
val roundPoints = calculateRound(round)
val choicePoints = calculateChoicePoints(round)
totalScore += (roundPoints + choicePoints)
}
return totalScore
}
fun toEnum(s: String): RockPaperScissors =
when (s) {
"A" -> RockPaperScissors.ROCK
"B" -> RockPaperScissors.PAPER
"C" -> RockPaperScissors.SCISSORS
else -> throw RuntimeException()
}
fun calculateRound(round: RoundPart2): Int =
when (round.myTurn) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> 0
}
fun calculateChoicePoints(round: RoundPart2): Int {
val choice = when(round.myTurn) {
"X" -> round.opponentsTurn.winTo()
"Y" -> round.opponentsTurn.makeDraw()
"Z" -> round.opponentsTurn.loseTo()
else -> throw RuntimeException()
}
return choice.score
}
fun part2(input: List<String>): Int {
var totalScore = 0
input.forEach {
val split = it.split(" ")
val round = RoundPart2(toEnum(split[0]), split[1])
val roundPoints = calculateRound(round)
val choicePoints = calculateChoicePoints(round)
totalScore += (roundPoints + choicePoints)
}
return totalScore
}
// 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))
}
data class RoundPart1(
/**
* A - Rock
* B - Paper
* C - Scissors
*/
val opponentsTurn: String,
/**
* X - Rock 1
* Y - Paper 2
* Z - Scissors 3
*/
val myTurn: String
)
data class RoundPart2(
/**
* A - Rock
* B - Paper
* C - Scissors
*/
val opponentsTurn: RockPaperScissors,
/**
* X - Lose
* Y - Draw
* Z - Win
*/
val myTurn: String
)
enum class RockPaperScissors(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
fun makeDraw() =
when (this) {
ROCK -> ROCK
PAPER -> PAPER
SCISSORS -> SCISSORS
}
fun loseTo() =
when (this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
fun winTo() =
when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
} | 0 | Kotlin | 0 | 1 | 3c7e46ddfb933281be34e58933b84870c6607acd | 3,351 | advent-of-code-2022 | Apache License 2.0 |
src/day03/Day03.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day03
import readInput
fun main() {
fun priorityOf(itemType: Char): Int {
return when (itemType) {
in 'a'..'z' -> itemType - 'a' + 1
in 'A'..'Z' -> itemType - 'A' + 27
else -> throw IllegalArgumentException("Invalid item type: $itemType")
}
}
fun part1(input: List<String>): Int {
var totalPriority = 0
for (rucksack in input) {
check(rucksack.length % 2 == 0)
val left = rucksack.substring(0, rucksack.length / 2).toSet()
val right = rucksack.substring(rucksack.length / 2).toSet()
val commonItemSet = left intersect right
check(commonItemSet.size == 1)
val commonItem = commonItemSet.first()
totalPriority += priorityOf(commonItem)
}
return totalPriority
}
fun part2(input: List<String>): Int {
var totalPriority = 0
for (groupRucksacks in input.windowed(3, 3)) {
val (elf1, elf2, elf3) = groupRucksacks.map { it.toSet() }
val badgeItemSet = elf1 intersect elf2 intersect elf3
check(badgeItemSet.size == 1)
val badgeItem = badgeItemSet.first()
totalPriority += priorityOf(badgeItem)
}
return totalPriority
}
val testInput = readInput("sample_data", 3)
println(part1(testInput))
check(part1(testInput) == 157)
val mainInput = readInput("main_data", 3)
println(part1(mainInput))
check(part1(mainInput) == 8018)
println(part2(testInput))
check(part2(testInput) == 70)
println(part2(mainInput))
check(part2(mainInput) == 2518)
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 1,667 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.split(" ")[0] to it.split(" ")[1] }
.map {
val opponentShape =
when (it.first) {
"A" -> 0
"B" -> 1
"C" -> 2
else -> error("should not happen")
}
val myShape =
when (it.second) {
"X" -> 0
"Y" -> 1
"Z" -> 2
else -> error("should not happen")
}
val shapeScore = myShape + 1
val winningShape = (opponentShape + 1).mod(3)
val outcomeScore =
if (opponentShape == myShape) {
3
} else if (winningShape == myShape) {
6
} else {
0
}
shapeScore + outcomeScore
}
.sum()
}
fun part2(input: List<String>): Int {
return input
.map { it.split(" ")[0] to it.split(" ")[1] }
.map {
val opponentShape =
when (it.first) {
"A" -> 0
"B" -> 1
"C" -> 2
else -> error("should not happen")
}
val diffToTargetShape =
when (it.second) {
"X" -> -1
"Y" -> 0
"Z" -> +1
else -> error("should not happen")
}
val targetShape = (opponentShape + diffToTargetShape).mod(3)
val shapeScore = targetShape + 1
val outcomeScore =
when (it.second) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> error("should not happen")
}
shapeScore + outcomeScore
}
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
assertEquals(15, part1(testInput))
assertEquals(12, part2(testInput))
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 2,152 | aoc2022 | Apache License 2.0 |
src/year2023/day16/Day16.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2023.day16
import check
import parallelMap
import readInput
fun main() {
val testInput = readInput("2023", "Day16_test")
check(part1(testInput), 46)
check(part2(testInput), 51)
val input = readInput("2023", "Day16")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = input.parseCavern().beamQuanta().energizedTiles()
private fun part2(input: List<String>): Int {
val cavern = input.parseCavern()
val startingBeamQuanta = mutableSetOf<BeamQuanta>()
startingBeamQuanta += cavern.xRange.map { BeamQuanta(Pos(it, 0), Direction.Down) }
startingBeamQuanta += cavern.xRange.map { BeamQuanta(Pos(it, cavern.yRange.last), Direction.Up) }
startingBeamQuanta += cavern.yRange.map { BeamQuanta(Pos(0, it), Direction.Right) }
startingBeamQuanta += cavern.yRange.map { BeamQuanta(Pos(cavern.xRange.last, it), Direction.Left) }
return startingBeamQuanta.parallelMap { cavern.beamQuanta(it).energizedTiles() }.max()
}
private data class Cavern(val mirrors: Map<Pos, Mirror>, val xRange: IntRange, val yRange: IntRange)
private data class Pos(val x: Int, val y: Int) {
fun move(direction: Direction): Pos {
return when (direction) {
Direction.Up -> Pos(x, y - 1)
Direction.Down -> Pos(x, y + 1)
Direction.Left -> Pos(x - 1, y)
Direction.Right -> Pos(x+ 1, y )
}
}
}
private data class BeamQuanta(val pos: Pos, val direction: Direction)
private enum class Direction {
Up, Down, Left, Right;
}
private enum class Mirror(val symbol: Char) {
Vertical('|'),
Horizontal('-'),
Slash('/'),
BackSlash('\\');
fun reflect(direction: Direction): Set<Direction> {
return reflectionsByIncomingDirectionByMirror.getValue(this).getValue(direction)
}
companion object {
fun fromSymbol(symbol: Char) = entries.firstOrNull { it.symbol == symbol }
private val reflectionsByIncomingDirectionByMirror = mapOf(
Vertical to mapOf(
Direction.Up to setOf(Direction.Up),
Direction.Down to setOf(Direction.Down),
Direction.Left to setOf(Direction.Up, Direction.Down),
Direction.Right to setOf(Direction.Up, Direction.Down)
),
Horizontal to mapOf(
Direction.Up to setOf(Direction.Left, Direction.Right),
Direction.Down to setOf(Direction.Left, Direction.Right),
Direction.Left to setOf(Direction.Left),
Direction.Right to setOf(Direction.Right)
),
Slash to mapOf(
Direction.Up to setOf(Direction.Right),
Direction.Down to setOf(Direction.Left),
Direction.Left to setOf(Direction.Down),
Direction.Right to setOf(Direction.Up)
),
BackSlash to mapOf(
Direction.Up to setOf(Direction.Left),
Direction.Down to setOf(Direction.Right),
Direction.Left to setOf(Direction.Up),
Direction.Right to setOf(Direction.Down)
),
)
}
}
private fun List<String>.parseCavern(): Cavern {
val mirrors = mutableMapOf<Pos, Mirror>()
for ((y, line) in withIndex()) {
for ((x, c) in line.withIndex()) {
val mirror = Mirror.fromSymbol(c)
if (mirror != null) {
mirrors += Pos(x, y) to mirror
}
}
}
return Cavern(mirrors, first().indices, indices)
}
private fun Cavern.beamQuanta(startingBeamQuanta: BeamQuanta = BeamQuanta(Pos(0, 0), Direction.Right)): Set<BeamQuanta> {
val beamQuanta = mutableSetOf<BeamQuanta>()
val stack = ArrayDeque<BeamQuanta>()
stack += startingBeamQuanta
while (stack.isNotEmpty()) {
val current = stack.removeFirst()
beamQuanta += current
val mirror = mirrors[current.pos]
val nextBeamQuanta = mutableSetOf<BeamQuanta>()
if (mirror == null) {
nextBeamQuanta += BeamQuanta(current.pos.move(current.direction), current.direction)
} else {
nextBeamQuanta += mirror.reflect(current.direction).map { BeamQuanta(current.pos.move(it), it) }
}
stack += nextBeamQuanta.filter { it.pos.x in xRange && it.pos.y in yRange && it !in beamQuanta }
}
return beamQuanta
}
private fun Set<BeamQuanta>.energizedTiles() = map { it.pos }.toSet().size
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 4,486 | AdventOfCode | Apache License 2.0 |
src/Day05.kt | ranveeraggarwal | 573,754,764 | false | {"Kotlin": 12574} | fun main() {
fun part1(input: List<String>): String {
val numStacks = input[0].length / 4 + 1
val stacks = Array<ArrayDeque<Char>>(numStacks) { ArrayDeque() }
var cursor = 0
// process initial state
while (true) {
if (input[cursor][1] == '1') break
(input[cursor] + " ").chunked(4).forEachIndexed { index, entry ->
if (entry[1] != ' ') {
stacks[index].addLast(entry[1])
}
}
cursor++
}
cursor += 2
// process instructions
for (i in cursor until input.size) {
val parsedInstructions =
input[cursor].filter { it.isDigit() || it == ' ' }.split(' ').filter { it.isNotEmpty() }
.map { it.toInt() }
for (j in 0 until parsedInstructions[0]) {
stacks[parsedInstructions[2] - 1].addFirst(stacks[parsedInstructions[1] - 1].first())
stacks[parsedInstructions[1] - 1].removeFirst()
}
cursor++
}
return stacks.fold("") { sum, entry -> sum + entry.first() }
}
fun part2(input: List<String>): String {
val numStacks = input[0].length / 4 + 1
val stacks = Array<ArrayDeque<Char>>(numStacks) { ArrayDeque() }
var cursor = 0
// process initial state
while (true) {
if (input[cursor][1] == '1') break
(input[cursor] + " ").chunked(4).forEachIndexed { index, entry ->
if (entry[1] != ' ') {
stacks[index].addLast(entry[1])
}
}
cursor++
}
cursor += 2
// process instructions
for (i in cursor until input.size) {
val parsedInstructions =
input[cursor].filter { it.isDigit() || it == ' ' }.split(' ').filter { it.isNotEmpty() }
.map { it.toInt() }
val stack = ArrayDeque<Char>()
for (j in 0 until parsedInstructions[0]) {
stack.addFirst(stacks[parsedInstructions[1] - 1].first())
stacks[parsedInstructions[1] - 1].removeFirst()
}
for (j in 0 until parsedInstructions[0]) {
stacks[parsedInstructions[2] - 1].addFirst(stack.first())
stack.removeFirst()
}
cursor++
}
return stacks.fold("") { sum, entry -> sum + entry.first() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c8df23daf979404f3891cdc44f7899725b041863 | 2,770 | advent-of-code-2022-kotlin | Apache License 2.0 |
day16/src/main/kotlin/aoc2015/day16/Day16.kt | sihamark | 581,653,112 | false | {"Kotlin": 263428, "Shell": 467, "Batchfile": 383} | package aoc2015.day16
object Day16 {
private val targetSueProperties = listOf(
"children" to 3,
"cats" to 7,
"samoyeds" to 2,
"pomeranians" to 3,
"akitas" to 0,
"vizslas" to 0,
"goldfish" to 5,
"trees" to 3,
"cars" to 2,
"perfumes" to 1
).map { Property(it) }
fun findNumberOfSue(): Int {
val validSues = sues()
.filter { targetSueProperties.containsAll(it.properties) }
return validSues.first().number
}
fun findRealNumberOfSue(): Int {
val validSues = sues()
.filter { sue ->
sue.properties.all { property ->
val targetProperty = targetSueProperties.find { it.name == property.name }!!
when (property.name) {
"pomeranians" -> property.amount < targetProperty.amount
"goldfish" -> property.amount < targetProperty.amount
"cats" -> property.amount > targetProperty.amount
"trees" -> property.amount > targetProperty.amount
else -> property.amount == targetProperty.amount
}
}
}
return validSues.first().number
}
private fun sues() = input.asSequence()
.map { Parser.parse(it) }
private data class Sue(
val number: Int,
val properties: List<Property>
) {
constructor(number: Int, vararg properties: Pair<String, Int>) : this(number, properties.map { Property(it.first, it.second) })
}
private data class Property(
val name: String,
val amount: Int
) {
constructor(property: Pair<String, Int>) : this(property.first, property.second)
}
private object Parser {
private val validSue = Regex("""Sue (\d+): (\w+): (\d+), (\w+): (\d+), (\w+): (\d+)""")
fun parse(rawSue: String): Sue {
val parsedValues = validSue.find(rawSue)?.groupValues ?: error("supplied raw sue was invalid: $rawSue")
return Sue(
parsedValues[1].toInt(),
parsedValues[2] to parsedValues[3].toInt(),
parsedValues[4] to parsedValues[5].toInt(),
parsedValues[6] to parsedValues[7].toInt()
)
}
}
}
| 0 | Kotlin | 0 | 0 | 6d10f4a52b8c7757c40af38d7d814509cf0b9bbb | 2,499 | aoc2015 | Apache License 2.0 |
AOC2022/src/main/kotlin/AOC9.kt | bsautner | 575,496,785 | false | {"Kotlin": 16189, "Assembly": 496} | package com.yp.day9
import java.io.File
import kotlin.math.abs
class AOC9 {
fun process() {
val input = File("/home/ben/aoc/input-9.txt")
val instructions = input.useLines { it.toList() }
val p1 = (0..1).map { Pair(0, 0) }.toMutableList()
val p2 = (0..9).map { Pair(0, 0) }.toMutableList()
println("Part1: ${scan(p1, instructions)}")
println("Part2: ${scan(p2, instructions)}")
}
private fun scan(rope: MutableList<Pair<Int, Int>>, input: List<String>): Int {
val visitedPositions = mutableSetOf<Pair<Int, Int>>()
visitedPositions.add(rope.last())
input.forEach { instruction ->
val cmd = instruction.split(" ")
(1..cmd[1].toInt()).forEach { _ ->
rope[0] = processStep(cmd[0], rope[0])
(0 until rope.size - 1).forEachIndexed { index, _ ->
val newPositions =
tail(rope[index], rope[index + 1])
rope[index + 1] = newPositions
}
visitedPositions.add(rope.last())
}
}
return visitedPositions.size
}
private fun tail(
headPosition: Pair<Int, Int>,
tailPosition: Pair<Int, Int>
): Pair<Int, Int> {
return when {
abs((headPosition.first - tailPosition.first)) > 1 || abs((headPosition.second - tailPosition.second)) > 1 -> {
when {
headPosition.first == tailPosition.first -> {
Pair(
tailPosition.first,
if (headPosition.second > tailPosition.second) tailPosition.second + 1 else tailPosition.second - 1
)
}
headPosition.second == tailPosition.second -> {
Pair(
if (headPosition.first > tailPosition.first) tailPosition.first + 1 else tailPosition.first - 1,
tailPosition.second
)
}
else -> {
val xDiff = (headPosition.first - tailPosition.first)
val yDiff = (headPosition.second - tailPosition.second)
val changeX = abs(xDiff) > 1 || (abs(xDiff) > 0 && abs(yDiff) > 1)
val changeY = abs(yDiff) > 1 || (abs(yDiff) > 0 && abs(xDiff) > 1)
Pair(
if (changeX) tailPosition.first + (if (xDiff < 0) -1 else 1) else tailPosition.first,
if (changeY) tailPosition.second + (if (yDiff < 0) -1 else 1) else tailPosition.second,
)
}
}
}
else -> tailPosition
}
}
private fun processStep(step: String, headPosition: Pair<Int, Int>): Pair<Int, Int> {
val (x, y) = headPosition
return when (step) {
"U" -> headPosition.copy(second = y - 1)
"D" -> headPosition.copy(second = y + 1)
"L" -> headPosition.copy(first = x - 1)
"R" -> headPosition.copy(first = x + 1)
else -> { throw IllegalStateException() }
}
}
}
| 0 | Kotlin | 0 | 0 | 5f53cb1c4214c960f693c4f6a2b432b983b9cb53 | 3,302 | Advent-of-Code-2022 | The Unlicense |
src/aoc22/day15.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc22.day15
import kotlin.math.abs
import lib.Point
import lib.Ranges.size
import lib.Ranges.overlaps
import lib.Ranges.intersect
import lib.Ranges.union
import lib.Solution
import lib.Strings.extractInts
data class Sensor(
val position: Point,
val closestBeacon: Point,
) {
val closestBeaconDistance by lazy {
position.distance(closestBeacon)
}
companion object {
fun parse(line: String): Sensor {
val (sx, sy, bx, by) = line.extractInts()
return Sensor(Point(sx, sy), Point(bx, by))
}
}
}
typealias Input = List<Sensor>
typealias Output = Long
private val solution = object : Solution<Input, Output>(2022, "Day15") {
override fun parse(input: String): Input = input.lines().map { Sensor.parse(it) }
override fun format(output: Output): String = "$output"
override fun part1(input: Input): Output =
calculateNoBeaconColumns(input, 2000000, false).sumOf { it.size }.toLong()
override fun part2(input: Input): Output {
val queryRange = 0..4000000
val targetRow = queryRange.single { row ->
calculateNoBeaconColumns(input, row, true)
.map { it intersect queryRange }
.sumOf { it.size } < queryRange.size
}
val row = calculateNoBeaconColumns(input, targetRow, true)
val targetCol = queryRange.single { col -> row.all { col !in it } }
return targetCol * 4000000L + targetRow
}
private fun calculateNoBeaconColumns(
sensors: List<Sensor>,
targetRow: Int,
ignoreDetectedBeacons: Boolean,
): List<IntRange> =
sensors
.map { calculateNoBeaconColumns(it, targetRow, ignoreDetectedBeacons) }
.filter { it.size > 0 }
.sortedBy { it.first }
.fold(ArrayDeque()) { acc, range ->
when {
overlapsWithLastRange(acc, range) -> acc.apply { addLast(removeLast() union range) }
else -> acc.apply { addLast(range) }
}
}
private fun calculateNoBeaconColumns(
sensor: Sensor,
targetRow: Int,
ignoreDetectedBeacons: Boolean,
): IntRange {
val center = Point(sensor.position.x, targetRow)
val slack = sensor.closestBeaconDistance - sensor.position.distance(center)
return when {
slack < 0 -> IntRange.EMPTY
ignoreDetectedBeacons || sensor.closestBeacon.y != targetRow -> (center.x - slack)..(center.x + slack)
sensor.closestBeacon.x > center.x -> (center.x - slack) until center.x + slack
else -> (center.x - slack + 1)..(center.x + slack)
}
}
private fun overlapsWithLastRange(ranges: ArrayDeque<IntRange>, range: IntRange) =
ranges.lastOrNull()?.let { it overlaps range } ?: false
}
private fun Point.distance(other: Point) = abs(x - other.x) + abs(y - other.y)
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 2,778 | aoc-kotlin | Apache License 2.0 |
kotlin/2022/round-1a/equal-sum/src/main/kotlin/oldsolutionnottakingintoaccountnneq100/Solution.kt | ShreckYe | 345,946,821 | false | null | package oldsolutionnottakingintoaccountnneq100
import kotlin.system.exitProcess
fun main() {
val t = readLineOrExit()!!.toInt()
repeat(t) { testCase() }
}
fun readLineOrExit() =
readLine().also {
if (it == "-1")
exitProcess(0)
}
fun testCase() {
val nn = readLineOrExit()!!.toInt()
val aas = generateAas(nn)
println(aas.joinToString(" "))
val bbs = readLineOrExit()!!.splitToSequence(' ').map { it.toLong() }.toList()
val expectedSum = (bbs.sum() + aas.sum()) / 2
println(solve(nn, bbs, expectedSum).joinToString(" "))
}
fun solve(nn: Int, bbs: List<Long>, expectedSum: Long): List<Long> =
/*
println("fs: " + firstSubset)
println("fss: " + firstSubsetSum)
println("es: " + expectedSum)
*/
greedy(bbs, expectedSum, nn)
?: if (nn <= 28) bruteForce(bbs, expectedSum, nn)
else throw IllegalStateException("oldsolutionnottakingintoaccountnneq100.greedy doesn't work when nn=$nn")
fun generateAas(nn: Int) =
List(nn) { (1 shl it.coerceAtMost(29)).toLong() }
fun greedy(bbs: List<Long>, expectedSum: Long, nn: Int): List<Long>? {
val sbbs = bbs.sortedDescending()
val firstSubset = ArrayList<Long>(nn * 2)
var firstSubsetSum = 0L
var secondSubsetSum = 0L
for (b in sbbs)
if (firstSubsetSum <= secondSubsetSum) {
firstSubset += b
firstSubsetSum += b
} else
secondSubsetSum += b
val n = nn.coerceAtMost(29)
return if (canPick(firstSubsetSum, expectedSum, n))
firstSubset + pickAAs((expectedSum - firstSubsetSum).toInt(), n)
else null
}
fun maxSum(n: Int): Int {
require(n <= 29)
return 2 shl (n + 1) - 1
}
fun canPick(bbsFirstSubsetSum: Long, expectedSum: Long, n: Int): Boolean {
require(n <= 29)
return bbsFirstSubsetSum <= expectedSum && bbsFirstSubsetSum + maxSum(n) >= expectedSum
}
fun pickAAs(diff: Int, n: Int): List<Long> {
require(n <= 29)
val list = ArrayList<Long>(n + 1)
for (i in 0..n) {
val twoPowI = 1 shl i
if (diff and twoPowI != 0)
list.add(twoPowI.toLong())
}
return list
}
fun bruteForce(bbs: List<Long>, expectedSum: Long, n: Int) =
bbs.allSubsets().firstNotNullOf {
val bbsFirstSubsetSum = it.sum()
if (canPick(bbsFirstSubsetSum, expectedSum, n))
it + pickAAs((expectedSum - bbsFirstSubsetSum).toInt(), n)
else
null
}
fun bitSubsets(size: Int): Sequence<Int> {
require(size <= 30)
return (0 until (1 shl size)).asSequence()
}
fun <T> List<T>.allSubsets(): Sequence<List<T>> =
bitSubsets(size).map { s -> filterIndexed { i, _ -> (s and (1 shl i)) != 0 } }
| 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 2,714 | google-code-jam | MIT License |
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/leetcode/easy/1752_CheckIfArrayIsSorderAndRotated.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.easy
/** 1752. Check if Array Is Sorted and Rotated https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/
* Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number
* of positions (including zero). Otherwise, return false.
There may be duplicates in the original array.
Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length],
where % is the modulo operation. */
fun check(nums: IntArray): Boolean {
// There may be no more then 1 wrong-ordered elements.
// e.g. for 3, 4, 5, 1, 2 : 3->4 ok, 4->5 ok, 5 -> 1 first wrong, 1->2 ok, 2->3 ok. Rotation must exist
// e.g. for 2, 1 : 2 -> 1 first wrong. 1 -> 2 ok. Rotation must exist
// e.g. for 2, 1, 3, 4 : 2 -> 1 first wrong. 1 -> 3 ok. 3 -> 4 ok 4 -> 1. Second wrong. No rotation exist
var rotations = 0;
for (i in 1 until nums.size) {
if (nums[i] < nums[i - 1]) {
rotations++
if (rotations >= 2) {
return false
}
}
}
if (nums.first() < nums.last()) {
rotations++
}
return rotations < 2
}
fun main() {
println(check(intArrayOf(3, 4, 5, 1, 2))) // expected == true
println(check(intArrayOf(2, 1, 3, 4))) // expected == false
println(check(intArrayOf(1, 2, 3))) // expected == true
println(check(intArrayOf(1, 1, 1))) // expected == true
println(check(intArrayOf(2, 1))) // expected == true
println(check(intArrayOf(6, 10, 6))) // expected == true
}
| 1 | Java | 3 | 6 | eac3328ecd1c434b1e9aae2cdbec05a44fad4430 | 1,679 | code-samples | MIT License |
src/Day04.kt | ekgame | 573,100,811 | false | {"Kotlin": 20661} | fun main() {
fun Pair<Int,Int>.fullyOverlaps(with: Pair<Int, Int>) = this.first >= with.first && this.second <= with.second
fun Pair<Int,Int>.partiallyOverlaps(with: Pair<Int, Int>) = this.first <= with.second && with.first <= this.second
fun part1(input: List<String>): Int = input
.map { it.split(",").map { it.split("-").map { it.toInt() }.zipWithNext().first() } }
.count { it[0].fullyOverlaps(it[1]) || it[1].fullyOverlaps(it[0]) }
fun part2(input: List<String>): Int = input
.map { it.split(",").map { it.split("-").map { it.toInt() }.zipWithNext().first() } }
.count { it[0].partiallyOverlaps(it[1]) }
val testInput = readInput("04.test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 0c2a68cedfa5a0579292248aba8c73ad779430cd | 854 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxIceCream.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 1833. Maximum Ice Cream Bars
* @see <a href="https://leetcode.com/problems/maximum-ice-cream-bars/">Source</a>
*/
fun interface MaxIceCream {
operator fun invoke(costs: IntArray, coins: Int): Int
}
/**
* Approach 1 (Greedy)
*/
class MaxIceCreamGreedy : MaxIceCream {
override operator fun invoke(costs: IntArray, coins: Int): Int {
var c = coins
// Store ice cream costs in increasing order.
costs.sort()
val n: Int = costs.size
var answer = 0
// Pick ice creams till we can.
while (answer < n && costs[answer] <= c) {
// We can buy this icecream, reduce the cost from the coins.
c -= costs[answer]
answer += 1
}
return answer
}
}
/**
* Approach 2 (Bucket Sort)
*/
class MaxIceCreamBucketSort : MaxIceCream {
override operator fun invoke(costs: IntArray, coins: Int): Int {
var c = coins
// get the maximum cost available
var max = costs[0]
for (element in costs) {
max = max(element, max)
}
// create the bucket array of size of maximum_cost + 1
// and keep the frequencies of the cost
val buckets = IntArray(max + 1)
for (p in costs) {
buckets[p]++
}
// keep the track of maximum ice-creams can be bought
var ans = 0
for (i in buckets.indices) {
if (c < i) {
break
}
if (buckets[i] > 0) {
ans += min(buckets[i], c / i)
c -= min(c, i * buckets[i])
}
}
return ans
}
}
/**
* Approach 3 (DP)
*/
class MaxIceCreamDP : MaxIceCream {
override operator fun invoke(costs: IntArray, coins: Int): Int {
var cns = coins
var maxc = 0
for (i in costs.indices) {
if (costs[i] > maxc) {
maxc = costs[i]
}
}
val cc = IntArray(maxc + 1)
for (element in costs) {
cc[element]++
}
var c = 0
for (i in 1..maxc) {
if (cc[i] == 0) {
continue
}
if (cns < i) {
break
}
for (j in 0 until cc[i]) {
if (cns >= i) {
cns -= i
c++
}
}
}
return c
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,125 | kotlab | Apache License 2.0 |
journey-to-the-moon/src/main/kotlin/com/felipecsl/Main.kt | felipecsl | 94,643,403 | false | null | package com.felipecsl
import java.util.*
// https://www.hackerrank.com/challenges/journey-to-the-moon
// the entire graph
val NODES: MutableMap<Astronaut, MutableList<Edge>> = mutableMapOf()
// list of every disjoint graph (with astronauts grouped by nation)
val countries: MutableList<Country> = mutableListOf()
val debug = true
class Country(val nodes: MutableSet<Astronaut> = mutableSetOf()) {
override fun toString(): String {
return "Country(NODES=$nodes)"
}
}
class Astronaut(val value: Int, var country: Country? = null) {
override fun toString(): String {
return value.toString()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Astronaut
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
return value
}
fun assignCountry(country: Country) {
this.country = country
country.nodes.add(this)
}
}
data class Edge(val from: Astronaut, val to: Astronaut) {
fun assignCountry(country: Country) {
from.assignCountry(country)
to.assignCountry(country)
}
}
fun main(args: Array<String>) {
val tokens = readInputLine()
val n = tokens[0]
val p = tokens[1]
val pairs = (0 until p)
.map { readInputLine() }
.map { Pair(it[0], it[1]) }
print(solve(n, pairs))
}
fun solve(n: Int, pairs: List<Pair<Int, Int>>): Long {
populateNodes(n, pairs)
for ((node, edges) in NODES) {
if (node.country == null) {
val country = Country()
node.assignCountry(country)
edges.forEach { traverseGraph(it, country) }
countries.add(country)
}
}
val sums: MutableMap<Int, Int> = mutableMapOf()
var result = 0L
(1 until countries.size).forEach {
val prevSum = if (it > 1) sums[it - 1]!! else countries[0].nodes.size
sums.put(it, prevSum + countries[it].nodes.size)
result += (prevSum * countries[it].nodes.size).toLong()
}
return result
}
fun addNode(from: Astronaut, to: Astronaut) {
val lst = NODES[from]
val edge = Edge(from, to)
if (lst != null) {
lst.add(edge)
} else {
NODES.put(from, mutableListOf(edge))
}
}
// Finds all astronauts in the provided graph (edge list) - depth first
fun traverseGraph(currEdge: Edge, country: Country) {
val visited = mutableSetOf<Edge>()
val queue: Queue<Edge> = ArrayDeque()
visited.add(currEdge)
queue.offer(currEdge)
currEdge.assignCountry(country)
while (!queue.isEmpty()) {
val current = queue.poll()
NODES[current.to]!!.forEach {
if (!visited.contains(it)) {
it.assignCountry(country)
visited.add(it)
queue.offer(it)
}
}
}
}
private fun readInputLine() =
readLine()!!.split(' ').map(String::toInt)
fun populateNodes(n: Int, pairs: List<Pair<Int, Int>>) {
pairs.forEach {
val src = Astronaut(it.first)
val dst = Astronaut(it.second)
addNode(src, dst)
addNode(dst, src)
}
(0 until n).forEach {
val astronaut = Astronaut(it)
if (!NODES.containsKey(astronaut)) {
NODES.put(astronaut, mutableListOf())
}
}
} | 0 | Kotlin | 0 | 3 | a4c07dd1531aae23d67ff52284b6fcca17b6c37c | 3,135 | hackerrank | MIT License |
src/main/kotlin/aoc2022/Day23.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2022
import AoCDay
import aoc2022.Day23.Direction.*
import util.illegalInput
// https://adventofcode.com/2022/day/23
object Day23 : AoCDay<Int>(
title = "Unstable Diffusion",
part1ExampleAnswer = 110,
part1Answer = 4146,
part2ExampleAnswer = 20,
part2Answer = 957,
) {
private data class Position(val x: Int, val y: Int)
private fun parseElfPositions(input: String) = buildSet {
for ((y, line) in input.lineSequence().withIndex()) {
for ((x, char) in line.withIndex()) {
when (char) {
'.' -> {}
'#' -> add(Position(x, y))
else -> illegalInput(char)
}
}
}
}
private data class RoundResult(val round: Int, val before: Set<Position>, val after: Set<Position>)
private enum class Direction { NORTH, SOUTH, WEST, EAST }
private inline fun simulateRoundsUntil(input: String, stopPredicate: (RoundResult) -> Boolean): RoundResult {
var elves = parseElfPositions(input)
val directions = ArrayDeque(Direction.entries)
for (round in 1..Int.MAX_VALUE) {
val proposedPositions = elves.associateWith { elf ->
val (x, y) = elf
val hasAdjacentElf = (-1..1).any { dx ->
(-1..1).any { dy -> (dx != 0 || dy != 0) && Position(x + dx, y + dy) in elves }
}
if (hasAdjacentElf) {
directions
.firstOrNull { direction ->
when (direction) {
NORTH -> (-1..1).all { dx -> Position(x + dx, y - 1) !in elves }
SOUTH -> (-1..1).all { dx -> Position(x + dx, y + 1) !in elves }
WEST -> (-1..1).all { dy -> Position(x - 1, y + dy) !in elves }
EAST -> (-1..1).all { dy -> Position(x + 1, y + dy) !in elves }
}
}
?.let { direction ->
when (direction) {
NORTH -> Position(x, y - 1)
SOUTH -> Position(x, y + 1)
WEST -> Position(x - 1, y)
EAST -> Position(x + 1, y)
}
}
?: elf
} else elf
}
val proposedCounts = proposedPositions.values.groupingBy { it }.eachCount()
val movedElves = proposedPositions
.map { (elf, proposed) -> if (proposedCounts[proposed] == 1) proposed else elf }
.toSet()
val roundResult = RoundResult(round, before = elves, after = movedElves)
if (stopPredicate(roundResult)) return roundResult
elves = movedElves
directions.addLast(directions.removeFirst())
}
error("Round ran out of Int range")
}
override fun part1(input: String): Int {
val (_, _, after) = simulateRoundsUntil(input) { (round, _, _) -> round == 10 }
val rectangleArea = (after.maxOf { it.x } - after.minOf { it.x } + 1) *
(after.maxOf { it.y } - after.minOf { it.y } + 1)
return rectangleArea - after.size
}
override fun part2(input: String) = simulateRoundsUntil(input) { (_, before, after) -> before == after }.round
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 3,495 | advent-of-code-kotlin | MIT License |
src/main/aoc2022/Day14.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2022
import AMap
import Direction
import Pos
import kotlin.math.max
import kotlin.math.min
class Day14(input: List<String>) {
val map = AMap().apply {
input.forEach { line ->
line.split(" -> ").windowed(2).forEach { (a, b) ->
val (x1, y1) = a.split(",").map { it.toInt() }
val (x2, y2) = b.split(",").map { it.toInt() }
(min(x1, x2)..max(x1, x2)).forEach { x ->
(min(y1, y2)..max(y1, y2)).forEach { y ->
this[Pos(x, y)] = '#'
}
}
}
}
}
private tailrec fun findFirstBelow(pos: Pos): Pos? {
return when {
pos.x !in map.xRange() || pos.y !in 0..map.yRange().last -> null // will fall into the abyss
map[pos] != null -> pos
else -> findFirstBelow(pos.move(Direction.Down))
}
}
private fun sandLandsOn(start: Pos): Pos? {
val center = findFirstBelow(start) ?: return null
val left = findFirstBelow(center.move(Direction.Left))
val right = findFirstBelow(center.move(Direction.Right))
return when {
center.y == left?.y && center.y == right?.y -> center.move(Direction.Up)
center.y != left?.y -> left?.let { sandLandsOn(it) }
else -> right?.let { sandLandsOn(it) }
}
}
private fun simulate() {
val sandOrigin = Pos(500, 0)
var next = sandLandsOn(sandOrigin)
while (next != null) {
map[next] = 'o'
next = sandLandsOn(sandOrigin)
}
}
// If there would be no rock, this is the amount of sand that would fall until the whole space is filled
private fun sandPyramidSize(): Int {
return (0..map.yRange().last).sumOf { 1 + it * 2 }
}
// A space that have three rock spaces above it can't have sand on it, so mark it as rocks as well
private fun blockOutSpacesWhereSandCantLand() {
map.yRange().forEach { y ->
map.xRange().forEach { x ->
val curr = Pos(x, y)
val left = curr.move(Direction.Left)
val right = curr.move(Direction.Right)
val down = curr.move(Direction.Down)
if (map[curr] == '#' && map[left] == '#' && map[right] == '#' && down.y in map.yRange()) {
map[down] = '#'
}
}
}
}
fun solvePart1(): Int { // takes 10 seconds to finish, need to find a faster solution
simulate()
return map.values.count { it == 'o' }
}
fun solvePart2(): Int { // takes about 100 ms
map[Pos(500, map.yRange().last + 1)] = '.' // add one empty space at the bottom that can be filled by sand
blockOutSpacesWhereSandCantLand()
val pyramidSize = sandPyramidSize()
return pyramidSize - map.values.count { it == '#' }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,944 | aoc | MIT License |
src/main/kotlin/dk/lessor/Day9.kt | aoc-team-1 | 317,571,356 | false | {"Java": 70687, "Kotlin": 34171} | package dk.lessor
fun main() {
val xmas = readFile("day_9.txt").map { it.toLong() }
val invalid = analyzeXmas(xmas)
println(invalid)
println(findEncryptionWeakness(xmas, invalid))
}
fun analyzeXmas(xmas: List<Long>, preambleSize: Int = 25): Long {
for (i in preambleSize..xmas.lastIndex) {
val number = xmas[i]
val preamble = calculatePreambleValues(xmas.drop(i - preambleSize).take(preambleSize))
if (!preamble.contains(number)) return number
}
return 0
}
fun calculatePreambleValues(preamble: List<Long>): Set<Long> {
val result = mutableSetOf<Long>()
for (i in 0 until preamble.lastIndex) {
for (j in i + 1..preamble.lastIndex) {
result += preamble[i] + preamble[j]
}
}
return result
}
fun findEncryptionWeakness(xmas: List<Long>, invalid: Long): Long {
var longest = listOf<Long>()
for (i in 0..xmas.lastIndex) {
val temp = findLongestCain(xmas.drop(i), invalid)
if (temp.size > longest.size) longest = temp
}
longest = longest.sorted()
return longest.first() + longest.last()
}
fun findLongestCain(xmas: List<Long>, invalid: Long): List<Long> {
val result = mutableListOf<Long>()
var sum = 0L
for (number in xmas) {
result.add(number)
sum += number
if (sum > invalid) return emptyList()
if (sum == invalid) return result
}
return emptyList()
}
| 0 | Java | 0 | 0 | 48ea750b60a6a2a92f9048c04971b1dc340780d5 | 1,442 | lessor-aoc-comp-2020 | MIT License |
src/main/kotlin/com/github/brpeterman/advent2022/DirTree.kt | brpeterman | 573,059,778 | false | {"Kotlin": 53108} | package com.github.brpeterman.advent2022
class DirTree(input: String, val root: Folder = Folder("")) {
init {
constructTree(parseInput(input))
}
data class Folder(val name: String, val parent: Folder? = null, val children: MutableMap<String, Folder> = mutableMapOf(), val files: MutableMap<String, Int> = mutableMapOf())
fun sumSmallDirs(threshold: Int = 100000): Int {
val index = mutableMapOf<String, Int>()
dirSize(root, index)
return index.values
.filter { it <= threshold }
.sum()
}
fun findThresholdDir(totalSpace: Int = 70000000, requiredSpace: Int = 30000000): Int {
val index = mutableMapOf<String, Int>()
dirSize(root, index)
val usedSpace = index[""]!!
return index.values.sorted()
.first { totalSpace - usedSpace + it >= requiredSpace }
}
fun dirSize(dir: Folder, index: MutableMap<String, Int> = mutableMapOf()): Int {
val count = dir.files.values.sum() +
dir.children.values.map { dirSize(it, index) }.sum()
index[dir.name] = count
return count
}
fun constructTree(lines: List<String>) {
var workingDir = root
var index = 0
while (index < lines.size - 1) {
val line = lines[index]
val tokens = line.split(" ")
val cmd = tokens[1]
when (cmd) {
"cd" -> {
val dir = tokens[2]
workingDir = when (dir) {
"/" -> root
".." -> workingDir.parent!!
else -> workingDir.children[dir]!!
}
index++
}
"ls" -> {
var outputIndex = index + 1
while (lines[outputIndex].isNotBlank() && !lines[outputIndex].startsWith('$')) {
val outputLine = lines[outputIndex]
val outputTokens = outputLine.split(" ")
when (outputTokens[0]) {
"dir" -> workingDir.children.put(outputTokens[1], Folder("${workingDir.name}/${outputTokens[1]}", workingDir))
else -> workingDir.files.put(outputTokens[1], outputTokens[0].toInt())
}
outputIndex++
}
index = outputIndex
}
}
}
}
companion object {
fun parseInput(input: String): List<String> {
return input.split("\n")
}
}
}
| 0 | Kotlin | 0 | 0 | 1407ca85490366645ae3ec86cfeeab25cbb4c585 | 2,636 | advent2022 | MIT License |
src/Day05.kt | fouksf | 572,530,146 | false | {"Kotlin": 43124} | import java.io.File
import java.util.Deque
fun main() {
fun parseBox(index: Int, box: String, boxes: List<ArrayDeque<Char>>) {
if (box.isNotBlank()) {
boxes[index].add(box[1])
}
}
// [T] [R] [Z] [H] [H] [G] [C]
fun parseLine(line: String, boxes: List<ArrayDeque<Char>>): Unit {
line
.windowed(4, 4, true)
.toList()
.forEachIndexed { index, box -> parseBox(index, box, boxes) }
}
fun parseBoxes(input: String): List<ArrayDeque<Char>> {
val lines = input
.split("\n")
val boxes = lines
.last()
.split(" ")
.filter { it.isNotEmpty() }
.map { ArrayDeque<Char>() }
lines
.dropLast(1)
.reversed()
.forEach { parseLine(it, boxes) }
return boxes
}
fun executeCommand(command: String, boxes: List<ArrayDeque<Char>>) {
val numbers = command
.replace("[a-z]".toRegex(), "")
.replace(" ", " ")
.split(" ")
.filter { it.isNotBlank() }
.map { it.toInt() }
for (i in 1..numbers[0]) {
boxes[numbers[2] - 1].add(boxes[numbers[1] - 1].last())
boxes[numbers[1] - 1].removeLast()
}
}
fun executeCommand9001(command: String, boxes: List<ArrayDeque<Char>>) {
val numbers = command
.replace("[a-z]".toRegex(), "")
.replace(" ", " ")
.split(" ")
.filter { it.isNotBlank() }
.map { it.toInt() }
boxes[numbers[2] - 1].addAll(boxes[numbers[1] - 1].takeLast(numbers[0]))
for (i in 1..numbers[0]) {
boxes[numbers[1] - 1].removeLast()
}
}
fun part1(input: String): String {
val boxes = parseBoxes(input.split("\n\n")[0])
input.split("\n\n")[1].split("\n").filter { it.isNotBlank() }
.forEach { executeCommand(it, boxes) }
return boxes.map { it.last() }.joinToString("")
}
fun part2(input: String): String {
val boxes = parseBoxes(input.split("\n\n")[0])
input.split("\n\n")[1].split("\n").filter { it.isNotBlank() }
.forEach { executeCommand9001(it, boxes) }
return boxes.map { it.last() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = File("src", "Day05_test.txt").readText()
println(part1(testInput))
println(part2(testInput))
val input = File("src", "Day05.txt").readText()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 701bae4d350353e2c49845adcd5087f8f5409307 | 2,643 | advent-of-code-2022 | Apache License 2.0 |
src/Day17.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | import java.util.BitSet
private enum class WindDirection {
LEFT, RIGHT
}
private enum class TetrisBlock {
ROW, PLUS, REVERSE_L, COLUMN, SQUARE;
fun toPointCloud(x: Int, y: Long): List<Pair<Int, Long>> {
return when (this) {
ROW -> listOf(
x to y,
x + 1 to y,
x + 2 to y,
x + 3 to y,
)
PLUS -> listOf(
x + 1 to y,
x to y + 1,
x + 1 to y + 1,
x + 2 to y + 1,
x + 1 to y + 2,
)
REVERSE_L -> listOf(
x to y,
x + 1 to y,
x + 2 to y,
x + 2 to y + 1,
x + 2 to y + 2,
)
COLUMN -> listOf(
x to y,
x to y + 1,
x to y + 2,
x to y + 3,
)
SQUARE -> listOf(
x to y,
x + 1 to y,
x to y + 1,
x + 1 to y + 1,
)
}
}
}
fun main() {
fun parseInput(input: String) = input.map {
when (it) {
'<' -> WindDirection.LEFT
'>' -> WindDirection.RIGHT
else -> throw IllegalArgumentException("Unknown direction $it")
}
}.toList()
fun solution(input: String, rounds: Long): Long {
val windPattern = parseInput(input)
val blockPattern = listOf(
TetrisBlock.ROW,
TetrisBlock.PLUS,
TetrisBlock.REVERSE_L,
TetrisBlock.COLUMN,
TetrisBlock.SQUARE,
)
var highestBlock = -1L
var finalScoreOffset = 0L
val chambWidth = 7
val map = HashSet<Pair<Int, Long>>()
val repetitonMemo = HashMap<Triple<List<BitSet>, Int, Int>, Pair<Long, Long>>()
var foundCycle = false
var windIdx = 0
var blockIdx = 0
val floor = 0L
var round = 0L
while (round++ < rounds) {
val initialPosition = Pair(2, highestBlock + 4)
val block = blockPattern[blockIdx]
var blockPoints = block.toPointCloud(initialPosition.first, initialPosition.second)
if (round > 300 && !foundCycle) {
val image = (0L..100L).map { highestBlock - it }.map { y ->
(0..chambWidth).fold(BitSet()) { acc, x ->
if (map.contains(Pair(x, y))) {
acc.set(x + 1)
}
acc
}
}.toList()
val memoKey = Triple(image, windIdx, blockIdx)
if (repetitonMemo.containsKey(memoKey)) {
foundCycle = true
val (skipFrom, highestBlockAt) = repetitonMemo[memoKey]!!
repetitonMemo.clear()
val cycleSize = round - skipFrom
val cyclesToSkip = (rounds - skipFrom).floorDiv(cycleSize) - 1
round += cyclesToSkip * cycleSize
finalScoreOffset = cyclesToSkip * (highestBlock - highestBlockAt)
} else {
repetitonMemo[memoKey] = Pair(round, highestBlock)
}
}
while (true) {
val wind = windPattern[windIdx]
val blockPointsAfterWind = blockPoints.map { (x, y) ->
when (wind) {
WindDirection.LEFT -> x - 1 to y
WindDirection.RIGHT -> x + 1 to y
}
}
val isLegal = blockPointsAfterWind.all { (x, y) ->
x in 0 until chambWidth && y >= floor && (x to y) !in map
}
windIdx = (windIdx + 1) % windPattern.size
if (isLegal) {
blockPoints = blockPointsAfterWind
}
// Move block down
val blockPointsAfterGravity = blockPoints.map { (x, y) -> x to y - 1 }
val isLegalAfterGravity = blockPointsAfterGravity.all { (x, y) ->
y >= floor && (x to y) !in map
}
if (isLegalAfterGravity) {
blockPoints = blockPointsAfterGravity
} else {
val highestPointInBlock = blockPoints.maxByOrNull { (_, y) -> y }!!.second
highestBlock = maxOf(highestBlock, highestPointInBlock)
map.addAll(blockPoints)
break
}
}
blockIdx = (blockIdx + 1) % blockPattern.size
}
return highestBlock + 1 + finalScoreOffset
}
fun part1(input: String) = solution(input, 2022)
fun part2(input: String) = solution(input, 1000000000000)
val testInput = readInput("Day17_test")[0]
check(part1(testInput) == 3068L)
check(part2(testInput) == 1514285714288)
val input = readInput("Day17")[0]
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 5,141 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/Solution05.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import adventOfCode.util.TripleOf
import adventOfCode.util.longs
import kotlin.math.max
import kotlin.math.min
typealias PlantNumber = Long
typealias Almanac = List<List<TripleOf<PlantNumber>>>
object Solution05 : Solution<Pair<List<PlantNumber>, Almanac>>(AOC_YEAR, 5) {
override fun getInput(handler: InputHandler): Pair<List<PlantNumber>, Almanac> {
val data = handler.getInput("\n\n")
val seeds = data[0].longs()
val almanac = data.drop(1)
.map { it.split('\n') }
.map { lines ->
lines.drop(1)
.map { line ->
val (destStart, sourceStart, length) = line.longs()
Triple(sourceStart, sourceStart + length, destStart - sourceStart)
}
}
return seeds to almanac
}
private fun getBestLocation(almanac: Almanac, start: PlantNumber, length: PlantNumber = 1): PlantNumber? {
var bestLocation: PlantNumber? = null
val queue = ArrayDeque<Triple<PlantNumber, PlantNumber, Int>>()
queue.add(Triple(start, start + length, 0))
while (queue.isNotEmpty()) {
val (currStart, currStop, i) = queue.removeFirst()
if (i == almanac.size) {
bestLocation = listOfNotNull(bestLocation, currStart).min()
continue
}
var requeue = true
for ((sourceStart, sourceStop, offset) in almanac[i]) {
val sharedStart = max(currStart, sourceStart)
val sharedStop = min(currStop, sourceStop)
if (sharedStart >= sharedStop) continue
queue.add(Triple(sharedStart + offset, sharedStop + offset, i + 1))
if (sharedStart > currStart) queue.add(Triple(currStart, sharedStart, i))
if (sharedStop < currStop) queue.add(Triple(sharedStop, currStop, i))
requeue = false
}
if (requeue) {
queue.add(Triple(currStart, currStop, i + 1))
}
}
return bestLocation
}
override fun solve(input: Pair<List<PlantNumber>, Almanac>): PairOf<PlantNumber> {
val (seeds, almanac) = input
val ans1 = seeds.mapNotNull { getBestLocation(almanac, it) }.min()
val ans2 = seeds.withIndex()
.groupBy { it.index / 2 }
.values
.mapNotNull { getBestLocation(almanac, it[0].value, it[1].value) }
.min()
return ans1 to ans2
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 2,644 | Advent-of-Code-2023 | MIT License |
src/main/kotlin/y2016/day03/Day03.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2016.day03
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
typealias Triangle = List<Int>
fun input(): List<Triangle> =
AoCGenerics.getInputLines("/y2016/day03/input.txt")
.map {
val parts = it.trim().split(" ").filterNot { partString -> partString == "" }
Triple(parts[0].trim().toInt(), parts[1].trim().toInt(), parts[2].trim().toInt()).toList().sorted()
}
fun input2(): List<Triangle> =
AoCGenerics.getInputLines("/y2016/day03/input.txt").chunked(3)
.map { threeLines ->
val line1 = threeLines[0].trim().split(" ").filterNot { partString -> partString == "" }
val line2 = threeLines[1].trim().split(" ").filterNot { partString -> partString == "" }
val line3 = threeLines[2].trim().split(" ").filterNot { partString -> partString == "" }
listOf(
Triple(line1[0].trim().toInt(), line2[0].trim().toInt(), line3[0].trim().toInt()).toList().sorted(),
Triple(line1[1].trim().toInt(), line2[1].trim().toInt(), line3[1].trim().toInt()).toList().sorted(),
Triple(line1[2].trim().toInt(), line2[2].trim().toInt(), line3[2].trim().toInt()).toList().sorted(),
)
}.flatten()
fun List<Triangle>.valid() = this.count {
it[0] + it[1] > it[2]
}
fun part1() = input().valid()
fun part2() = input2().valid()
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 1,459 | AdventOfCode | MIT License |
year2018/src/main/kotlin/net/olegg/aoc/year2018/day3/Day3.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2018.day3
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2018.DayOf2018
/**
* See [Year 2018, Day 3](https://adventofcode.com/2018/day/3)
*/
object Day3 : DayOf2018(3) {
override fun first(): Any? {
val requests = lines.mapNotNull { Request.fromString(it) }
val width = requests.maxOf { it.left + it.width }
val height = requests.maxOf { it.top + it.height }
val field = Array(height) { Array(width) { 0 } }
requests.forEach { request ->
(request.top..<request.top + request.height).forEach { y ->
(request.left..<request.left + request.width).forEach { x ->
field[y][x] += 1
}
}
}
return field.sumOf { row -> row.count { it > 1 } }
}
override fun second(): Any? {
val requests = lines.mapNotNull { Request.fromString(it) }
return requests
.first { request -> requests.all { it.notIntersects(request) } }
.id
}
data class Request(
val id: Int,
val left: Int,
val top: Int,
val width: Int,
val height: Int
) {
companion object {
private val PATTERN = "#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)".toRegex()
fun fromString(data: String): Request? {
return PATTERN.matchEntire(data)?.let { match ->
val tokens = match.destructured.toList().map { it.toInt() }
Request(
id = tokens[0],
left = tokens[1],
top = tokens[2],
width = tokens[3],
height = tokens[4],
)
}
}
}
fun notIntersects(other: Request): Boolean {
return (id == other.id) ||
(left + width <= other.left) ||
(other.left + other.width <= left) ||
(top + height <= other.top) ||
(other.top + other.height <= top)
}
}
}
fun main() = SomeDay.mainify(Day3)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,858 | adventofcode | MIT License |
src/Day02.kt | TheGreatJakester | 573,222,328 | false | {"Kotlin": 47612} | import utils.readInputAsLines
val possibleHands = mapOf(
"A X" to 4,
"B X" to 1,
"C X" to 7,
"A Y" to 8,
"B Y" to 5,
"C Y" to 2,
"A Z" to 3,
"B Z" to 9,
"C Z" to 6
)
val possibleHandsStrat2 = mapOf(
"A X" to 3,
"B X" to 1,
"C X" to 2,
"A Y" to 4,
"B Y" to 5,
"C Y" to 6,
"A Z" to 6+2,
"B Z" to 6+3,
"C Z" to 6+1
)
fun main() {
fun part1(input: List<String>): Int {
val hands = input.mapNotNull { possibleHands[it] }
return hands.sum()
}
fun part2(input: List<String>): Int {
val hands = input.mapNotNull { possibleHandsStrat2[it] }
return hands.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsLines("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInputAsLines("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c76c213006eb8dfb44b26822a44324b66600f933 | 971 | 2022-AOC-Kotlin | Apache License 2.0 |
advent-of-code-2022/src/Day21.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | fun main() {
val testInput = readInput("Day21_test")
val input = readInput("Day21")
"Part 1" {
part1(testInput) shouldBe 152
measureAnswer { part1(input) }
}
"Part 2" {
part2(testInput) shouldBe 301
measureAnswer { part2(input) }
}
}
private fun part1(input: Map<String, YellingMonkey>): Long {
input.calculateMonkeyAnswer("root")
return input.requireAnswer("root").toLong()
}
private fun part2(input: Map<String, YellingMonkey>): Long {
val rootMonkey = input.getValue("root")
val me = input.getValue("humn")
// Calculate answers for left and right side
input.calculateMonkeyAnswer("root")
val (leftBefore, rightBefore) = rootMonkey.waitFor.map(input::requireAnswer)
input.resetAnswers()
// Increase my answer by 1 to see how thi will affect resulting answer
val originalAnswer = me.answer!!
me.answer = originalAnswer + 1
// Calculate answers for left and right side again to figure out
// what part has changed and how it is changed
input.calculateMonkeyAnswer("root")
val (leftAfter, rightAfter) = rootMonkey.waitFor.map(input::requireAnswer)
// Calculate value shift - divide original gap by te diff after we changed answer by one
val shift = if (rightAfter == rightBefore) {
(leftBefore - rightBefore) / (leftBefore - leftAfter)
} else {
(rightBefore - leftBefore) / (rightBefore - rightAfter)
}
return (originalAnswer + shift).toLong()
}
private fun Map<String, YellingMonkey>.requireAnswer(name: String) = checkNotNull(getValue(name).answer)
private fun Map<String, YellingMonkey>.resetAnswers() {
values.asSequence()
.filter { it.waitFor.isNotEmpty() }
.forEach { it.answer = null }
}
private fun Map<String, YellingMonkey>.calculateMonkeyAnswer(monkey: String) {
val stack = ArrayDeque<YellingMonkey>()
stack.addFirst(getValue(monkey))
while (stack.isNotEmpty()) {
val current = stack.first()
if (current.answer != null) {
stack.removeFirst()
} else {
val (a, b) = current.waitFor.map { getValue(it) }
val answerA = a.answer
val answerB = b.answer
if (answerA != null && answerB != null) {
current.answer = current.operation?.invoke(answerA, answerB)
} else {
if (answerA == null) stack.addFirst(a)
if (answerB == null) stack.addFirst(b)
}
}
}
}
private fun readInput(name: String) = readLines(name).map { line ->
val (monkeyName, rawOperation) = line.split(": ")
val operationParts = rawOperation.split(" ")
val operation: ((Double, Double) -> Double)? = if (operationParts.size == 3) {
when (operationParts[1]) {
"+" -> Double::plus
"*" -> Double::times
"/" -> Double::div
"-" -> Double::minus
else -> error("Unknown operation ${operationParts[1]}")
}
} else null
YellingMonkey(
name = monkeyName,
waitFor = if (operationParts.size == 3) listOf(operationParts[0], operationParts[2]) else emptyList(),
operation = operation,
).apply { answer = rawOperation.toDoubleOrNull() }
}.associateBy { it.name }
private data class YellingMonkey(
val name: String,
val waitFor: List<String>,
val operation: ((Double, Double) -> Double)?,
) {
var answer: Double? = null
}
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 3,481 | advent-of-code | Apache License 2.0 |
src/Day04.kt | buczebar | 572,864,830 | false | {"Kotlin": 39213} | typealias SectionRange = Pair<Int, Int>
fun main() {
infix fun SectionRange.contains(range: SectionRange): Boolean {
return first <= range.first && this.second >= range.second
}
infix fun SectionRange.overlap(range: SectionRange): Boolean {
return first <= range.second && range.first <= second
}
fun part1(input: List<Pair<SectionRange, SectionRange>>) =
input.count { it.first contains it.second || it.second contains it.first }
fun part2(input: List<Pair<SectionRange, SectionRange>>) =
input.count { it.first overlap it.second || it.second overlap it.first }
fun parseInput(name: String): List<Pair<SectionRange, SectionRange>> {
fun parseSectionRange(input: String) =
input.split("-").map { it.toInt() }.pair()
return readInput(name)
.map {
it.split(",").pair()
.let { ranges ->
Pair(parseSectionRange(ranges.first), parseSectionRange(ranges.second))
}
}
}
val testInput = parseInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = parseInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cdb6fe3996ab8216e7a005e766490a2181cd4101 | 1,268 | advent-of-code | Apache License 2.0 |
src/Day03.kt | TheOnlyTails | 573,028,916 | false | {"Kotlin": 9156} | fun Char.toPriority() = code - if (this > 'Z') {
96
} else {
38
}
fun main() {
fun part1(input: List<String>): Int {
return input
.map {
// split into each rucksack compartment
it.substring(0 until (it.length / 2)) to it.substring(it.length / 2)
}
.map { (comp1, comp2) ->
// find common item
comp1.find { it in comp2 }!!
}
.sumOf(Char::toPriority)
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map {
it.fold(it.first().toSet()) { acc, chars ->
acc intersect chars.toSet()
}.single()
}
.sumOf(Char::toPriority)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 685ce47586b6d5cea30dc92f4a8e55e688005d7c | 1,029 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | Daan-Gunnink | 572,614,830 | false | {"Kotlin": 8595} | class Day05 : AdventOfCode("CMZ", "MCD") {
internal data class Move(
val amount: Int,
val fromColumn: Int,
val toColumn: Int
)
private fun parseBoxes(input: List<String>): MutableList<MutableList<String>> {
return input.map { it.withIndex().filter { it.value.isLetter() } }.flatten().sortedBy { it.index }.groupBy { it.index }.map { it.value.map { it.value.toString() }.toMutableList() }.toMutableList()
}
private fun parseMove(input: String): Move {
val data = input.filter { !it.isLetter() }.split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
return Move(amount = data[0], fromColumn = data[1] - 1, toColumn = data[2] - 1)
}
private fun parseAnswer(input: List<List<String>>): String {
return input.joinToString("") { it.first().toString() }
}
override fun part1(input: List<String>): String {
val splitIndex = input.withIndex().single { it.value.isEmpty() }.index
val columns = parseBoxes(input.subList(0, splitIndex - 1))
val moves = input.subList(splitIndex + 1, input.size)
moves.forEach {
val move = parseMove(it)
val take = columns[move.fromColumn].take(move.amount)
columns[move.toColumn].addAll(0, take.reversed())
columns[move.fromColumn] = columns[move.fromColumn].drop(move.amount).toMutableList()
}
return parseAnswer(columns)
}
override fun part2(input: List<String>): String {
val splitIndex = input.withIndex().single { it.value.isEmpty() }.index
val columns = parseBoxes(input.subList(0, splitIndex - 1))
val moves = input.subList(splitIndex + 1, input.size)
moves.forEach {
val move = parseMove(it)
val take = columns[move.fromColumn].take(move.amount)
columns[move.fromColumn] = columns[move.fromColumn].drop(move.amount).toMutableList()
columns[move.toColumn].addAll(0, take)
}
return parseAnswer(columns)
}
}
| 0 | Kotlin | 0 | 0 | 15a89224f332faaed34fc2d000c00fbefe1a3c08 | 2,055 | advent-of-code-2022 | Apache License 2.0 |
2020/03.kt | Albert221 | 318,762,813 | false | null | import java.io.File
fun main() {
val map = File("2020/input/03.txt").run { Map.parse(readText()) }
val partOne = treesEncountered(map, Coords(3, 1))
var partTwo = 1L
for (step in listOf(
Coords(1, 1),
Coords(3, 1),
Coords(5, 1),
Coords(7, 1),
Coords(1, 2),
)) {
partTwo *= treesEncountered(map, step)
}
println("Part one: %d".format(partOne)) // 211
println("Part two: %d".format(partTwo)) // 3584591857
}
fun treesEncountered(map: Map, step: Coords): Int {
var trees = 0
var currentPos = Coords(0, 0)
while (true) {
if (currentPos.second >= map.height) break
if (map.isTree(currentPos)) trees++
currentPos += step
}
return trees
}
typealias Coords = Pair<Int, Int>
operator fun Coords.plus(other: Coords) = Coords(first + other.first, second + other.second)
class Map(val width: Int, val height: Int, private val trees: List<Coords>) {
companion object {
fun parse(map: String): Map {
val tree = '#'
val trees = mutableListOf<Coords>()
for ((y, row) in map.lines().withIndex()) {
for ((x, char) in row.toCharArray().withIndex()) {
if (char == tree) trees.add(Coords(x, y))
}
}
return Map(
width = map.lines().first().count(),
height = map.lines().count(),
trees = trees.toList(),
)
}
}
/**
* Map repeats itself in the x axis.
*/
private fun Coords.normalize() = Coords(first % width, second)
fun isTree(coords: Coords): Boolean = trees.contains(coords.normalize())
} | 0 | Kotlin | 0 | 0 | 8de13af4c68a46d2e509284af36130b214e22e4c | 1,756 | advent-of-code | Apache License 2.0 |
year2015/src/main/kotlin/net/olegg/aoc/year2015/day24/Day24.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2015.day24
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.parseLongs
import net.olegg.aoc.year2015.DayOf2015
/**
* See [Year 2015, Day 24](https://adventofcode.com/2015/day/24)
*/
object Day24 : DayOf2015(24) {
private val WEIGHTS = data.parseLongs("\n")
override fun first(): Any? {
val sum = WEIGHTS.sum() / 3
return subsets(sum, WEIGHTS)
.groupBy { it.size }
.minBy { it.key }
.value
.minOf { it.fold(1L, Long::times) }
}
override fun second(): Any? {
val sum = WEIGHTS.sum() / 4
return subsets(sum, WEIGHTS)
.groupBy { it.size }
.minBy { it.key }
.value
.minOf { it.fold(1L, Long::times) }
}
}
fun subsets(
sum: Long,
list: List<Long>
): List<List<Long>> = when {
(sum < 0L) -> emptyList()
(sum == 0L) -> listOf(emptyList())
(list.size == 1) -> if (sum == list[0]) listOf(list) else emptyList()
else -> subsets(sum, list.drop(1)) + subsets(sum - list[0], list.drop(1)).map { listOf(list[0]) + it }
}
fun main() = SomeDay.mainify(Day24)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,077 | adventofcode | MIT License |
src/Day22.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | fun main() {
val d = Day22(readInput("inputs/Day22"))
println(d.part1())
println(d.part2())
}
class Day22(input: List<String>) {
private val blockedPlaces: Set<Point> = parseBlockedPlaces(input)
private val instructions: List<Instruction> = Instruction.ofList(input)
fun part1(): Int =
followInstructions(CubeFacing(1)).score()
fun part2(): Int =
followInstructions(CubeFacing(11)).score()
private fun followInstructions(startingCube: CubeFacing): Orientation {
var cube = startingCube
var orientation = Orientation(cube.topLeft, Facing.East)
instructions.forEach { instruction ->
when (instruction) {
is Left -> orientation = orientation.copy(facing = orientation.facing.left)
is Right -> orientation = orientation.copy(facing = orientation.facing.right)
is Move -> {
var keepMoving = true
repeat(instruction.steps) {
if (keepMoving) {
var nextOrientation = orientation.move()
var nextCube = cube
if (nextOrientation.location !in cube) {
with(cube.transition(orientation.facing)) {
nextOrientation = Orientation(move(orientation.location), enter)
nextCube = destination
}
}
if (nextOrientation.location in blockedPlaces) {
keepMoving = false
} else {
orientation = nextOrientation
cube = nextCube
}
}
}
}
}
}
return orientation
}
private fun parseBlockedPlaces(input: List<String>): Set<Point> =
input
.takeWhile { it.isNotBlank() }
.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, c ->
if (c == '#') Point(x, y) else null
}
}.toSet()
private data class Orientation(val location: Point, val facing: Facing) {
fun score(): Int =
(1000 * (location.y + 1)) + (4 * (location.x + 1)) + facing.points
fun move(): Orientation =
copy(location = location + facing.offset)
}
private sealed class Instruction {
companion object {
fun ofList(input: List<String>): List<Instruction> =
input
.dropWhile { it.isNotBlank() }
.drop(1)
.first()
.trim()
.let { """\d+|[LR]""".toRegex().findAll(it) }
.map { it.value }
.filter { it.isNotBlank() }
.map { symbol ->
when (symbol) {
"L" -> Left
"R" -> Right
else -> Move(symbol.toInt())
}
}.toList()
}
}
private class Move(val steps: Int) : Instruction()
private object Left : Instruction()
private object Right : Instruction()
sealed class Facing(val points: Int, val offset: Point) {
abstract val left: Facing
abstract val right: Facing
object North : Facing(3, Point(0, -1)) {
override val left = West
override val right = East
}
object East : Facing(0, Point(1, 0)) {
override val left = North
override val right = South
}
object South : Facing(1, Point(0, 1)) {
override val left = East
override val right = West
}
object West : Facing(2, Point(-1, 0)) {
override val left = South
override val right = North
}
}
class CubeFacing(
val id: Int,
val size: Int,
val topLeft: Point,
val north: Transition,
val east: Transition,
val south: Transition,
val west: Transition
) {
val minX: Int = topLeft.x
val maxX: Int = topLeft.x + size - 1
val minY: Int = topLeft.y
val maxY: Int = topLeft.y + size - 1
operator fun contains(place: Point): Boolean =
place.x in (minX..maxX) && place.y in (minY..maxY)
fun scaleDown(point: Point): Point =
point - topLeft
fun scaleUp(point: Point): Point =
point + topLeft
fun transition(direction: Facing): Transition =
when (direction) {
Facing.North -> north
Facing.East -> east
Facing.South -> south
Facing.West -> west
}
companion object {
private val instances = mutableMapOf<Int, CubeFacing>()
operator fun invoke(id: Int): CubeFacing =
instances.getValue(id)
private operator fun plus(instance: CubeFacing) {
instances[instance.id] = instance
}
init {
CubeFacing + CubeFacing(
id = 1,
size = 50,
topLeft = Point(50, 0),
north = Transition(1, 5, Facing.North, Facing.North),
east = Transition(1, 2, Facing.East, Facing.East),
south = Transition(1, 3, Facing.South, Facing.South),
west = Transition(1, 2, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 2,
size = 50,
topLeft = Point(100, 0),
north = Transition(2, 2, Facing.North, Facing.North),
east = Transition(2, 1, Facing.East, Facing.East),
south = Transition(2, 2, Facing.South, Facing.South),
west = Transition(2, 1, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 3,
size = 50,
topLeft = Point(50, 50),
north = Transition(3, 1, Facing.North, Facing.North),
east = Transition(3, 3, Facing.East, Facing.East),
south = Transition(3, 5, Facing.South, Facing.South),
west = Transition(3, 3, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 4,
size = 50,
topLeft = Point(0, 100),
north = Transition(4, 6, Facing.North, Facing.North),
east = Transition(4, 5, Facing.East, Facing.East),
south = Transition(4, 6, Facing.South, Facing.South),
west = Transition(4, 5, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 5,
size = 50,
topLeft = Point(50, 100),
north = Transition(5, 3, Facing.North, Facing.North),
east = Transition(5, 4, Facing.East, Facing.East),
south = Transition(5, 1, Facing.South, Facing.South),
west = Transition(5, 4, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 6,
size = 50,
topLeft = Point(0, 150),
north = Transition(6, 4, Facing.North, Facing.North),
east = Transition(6, 6, Facing.East, Facing.East),
south = Transition(6, 4, Facing.South, Facing.South),
west = Transition(6, 6, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 11,
size = 50,
topLeft = Point(50, 0),
north = Transition(11, 16, Facing.North, Facing.East),
east = Transition(11, 12, Facing.East, Facing.East),
south = Transition(11, 13, Facing.South, Facing.South),
west = Transition(11, 14, Facing.West, Facing.East)
)
CubeFacing + CubeFacing(
id = 12,
size = 50,
topLeft = Point(100, 0),
north = Transition(12, 16, Facing.North, Facing.North),
east = Transition(12, 15, Facing.East, Facing.West),
south = Transition(12, 13, Facing.South, Facing.West),
west = Transition(12, 11, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 13,
size = 50,
topLeft = Point(50, 50),
north = Transition(13, 11, Facing.North, Facing.North),
east = Transition(13, 12, Facing.East, Facing.North),
south = Transition(13, 15, Facing.South, Facing.South),
west = Transition(13, 14, Facing.West, Facing.South)
)
CubeFacing + CubeFacing(
id = 14,
size = 50,
topLeft = Point(0, 100),
north = Transition(14, 13, Facing.North, Facing.East),
east = Transition(14, 15, Facing.East, Facing.East),
south = Transition(14, 16, Facing.South, Facing.South),
west = Transition(14, 11, Facing.West, Facing.East)
)
CubeFacing + CubeFacing(
id = 15,
size = 50,
topLeft = Point(50, 100),
north = Transition(15, 13, Facing.North, Facing.North),
east = Transition(15, 12, Facing.East, Facing.West),
south = Transition(15, 16, Facing.South, Facing.West),
west = Transition(15, 14, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 16,
size = 50,
topLeft = Point(0, 150),
north = Transition(16, 14, Facing.North, Facing.North),
east = Transition(16, 15, Facing.East, Facing.North),
south = Transition(16, 12, Facing.South, Facing.South),
west = Transition(16, 11, Facing.West, Facing.South)
)
}
}
}
data class Transition(val sourceId: Int, val destinationId: Int, val exit: Facing, val enter: Facing) {
private val byDirection = Pair(exit, enter)
private val source: CubeFacing by lazy { CubeFacing(sourceId) }
val destination: CubeFacing by lazy { CubeFacing(destinationId) }
private fun Point.rescale(): Point =
destination.scaleUp(source.scaleDown(this))
private fun Point.flipRescaled(): Point =
destination.scaleUp(source.scaleDown(this).flip())
private fun Point.flip(): Point =
Point(y, x)
fun move(start: Point): Point = when (byDirection) {
Pair(Facing.North, Facing.North) -> Point(start.rescale().x, destination.maxY)
Pair(Facing.East, Facing.East) -> Point(destination.minX, start.rescale().y)
Pair(Facing.West, Facing.West) -> Point(destination.maxX, start.rescale().y)
Pair(Facing.South, Facing.South) -> Point(start.rescale().x, destination.minY)
Pair(Facing.North, Facing.East) -> Point(destination.minX, start.flipRescaled().y)
Pair(Facing.East, Facing.North) -> Point(start.flipRescaled().x, destination.maxY)
Pair(Facing.East, Facing.West) -> Point(destination.maxX, destination.maxY - source.scaleDown(start).y)
Pair(Facing.West, Facing.East) -> Point(destination.minX, destination.maxY - source.scaleDown(start).y)
Pair(Facing.West, Facing.South) -> Point(start.flipRescaled().x, destination.minY)
Pair(Facing.South, Facing.West) -> Point(destination.maxX, start.flipRescaled().y)
else -> throw IllegalStateException("No transition from $exit to $enter")
}
}
}
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 12,574 | aoc-2022 | Apache License 2.0 |
2k23/aoc2k23/src/main/kotlin/10.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 d10
import input.read
import java.util.*
fun main() {
println("Part 1: ${part1(read("10.txt"))}")
println("Part 2: ~${part2(read("10.txt"))}, you need to debug a bit by yourself ¯\\_(ツ)_/¯")
}
fun part1(input: List<String>): Int {
val maze = Maze(input)
val start = maze.getStart()!!
maze.setDistance(start, 0)
val queue: Queue<List<Point>> = Direction.entries.filter { dir ->
val adj = maze.adjacents(start.to(dir))
adj.any { it == start }
}.map {
listOf(start.to(it), start)
}.let {
LinkedList(it)
}
while (true) {
val (point, prev) = queue.poll()
if (maze.getDistance(point) != -1) {
return maze.getDistance(point)
}
maze.setDistance(point, maze.getDistance(prev) + 1)
maze.adjacents(point).forEach {
if (it != prev) {
queue.add(listOf(it, point))
}
}
}
}
fun part2(input: List<String>): Int {
val maze = Maze(input)
val start = maze.getStart()!!
maze.setDistance(start, 0)
maze.setInside(start, 'S')
val stack: Stack<List<Point>> = Direction.entries.filter { dir ->
if (!maze.isValid(start.to(dir))) {
false
} else {
val adj = maze.adjacents(start.to(dir))
adj.any { it == start }
}
}.map {
listOf(start.to(it), start)
}.let {
val s: Stack<List<Point>> = Stack()
s.addAll(it)
s
}
while (true) {
val (point, prev) = stack.pop()
if (point == start) {
maze.enclosed()
maze.printInside()
return maze.countInside()
}
maze.discover(point)
maze.adjacents(point).forEach {
if (it != prev) {
stack.push(listOf(it, point))
}
}
}
}
class Point(val x: Int, val y: Int) {
fun to(dir: Direction): Point {
return when (dir) {
Direction.WEST -> Point(x - 1, y)
Direction.NORTH -> Point(x, y - 1)
Direction.SOUTH -> Point(x, y + 1)
Direction.EAST -> Point(x + 1, y)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Point) return false
return x == other.x && y == other.y
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
}
class Maze(input: List<String>) {
private val h: Int = input.size
private val w: Int = input.first().toCharArray().size
val map: List<CharArray> = input.map { it.toCharArray() }
private val distances: List<MutableList<Int>> = List(map.size) { MutableList(map[0].size) { -1 } }
private val inside: List<MutableList<Char>> = List(map.size) { MutableList(map[0].size) { ' ' } }
fun isValid(point: Point): Boolean = point.x in 0..<w && point.y in 0..<h
fun getStart(): Point? {
(0..<h).forEach { y ->
(0..<w).forEach { x ->
if (map[y][x] == 'S') {
return Point(x, y)
}
}
}
return null
}
fun printInside() {
(0..<h).forEach { y ->
(0..<w).forEach { x ->
print(getInside(Point(x, y)))
}
println()
}
}
fun getValue(point: Point): Char = map[point.y][point.x]
fun setDistance(point: Point, dist: Int) {
distances[point.y][point.x] = dist
}
fun getDistance(point: Point): Int = distances[point.y][point.x]
private fun getInside(point: Point): Char = inside[point.y][point.x]
fun setInside(point: Point, value: Char) {
inside[point.y][point.x] = value
}
fun adjacents(point: Point): List<Point> {
return SYMBOL_TO_DIRECTION[getValue(point)]!!.filter { dir -> isValid(point.to(dir)) }
.map { point.to(it) }
}
fun discover(point: Point) {
setInside(point, getValue(point))
}
fun enclosed() {
forEachPosition {
val boundaries = (it.x + 1..<w).count { x ->
val boundary = getInside(Point(x, it.y))
listOf('|', 'J', 'L').contains(boundary)
}
if (getInside(it) == ' ') {
setInside(
it, if (boundaries % 2 == 0) {
'O'
} else {
'I'
}
)
}
}
}
fun countInside(): Int {
var count = 0
forEachPosition {
if (getInside(it) == 'I') {
count++
}
}
return count
}
private fun forEachPosition(operation: (Point) -> Unit) {
(0..<h).forEach { y ->
(0..<w).forEach { x ->
operation(Point(x, y))
}
}
}
}
enum class Direction {
NORTH,
SOUTH,
EAST,
WEST;
}
private val SYMBOL_TO_DIRECTION: Map<Char, List<Direction>> =
hashMapOf(
'|' to listOf(Direction.NORTH, Direction.SOUTH),
'-' to listOf(Direction.WEST, Direction.EAST),
'L' to listOf(Direction.NORTH, Direction.EAST),
'J' to listOf(Direction.NORTH, Direction.WEST),
'7' to listOf(Direction.WEST, Direction.SOUTH),
'F' to listOf(Direction.EAST, Direction.SOUTH),
'.' to listOf()
)
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 5,479 | aoc | The Unlicense |
src/day2/main.kt | DonaldLika | 434,183,449 | false | {"Kotlin": 11805} | package day2
import assert
import readLines
fun main() {
fun readCommands(fileName: String): List<Pair<String, Int>> {
return readLines(fileName).map {
it.split(" ").zipWithNext().first()
}.map {
Pair(it.first, it.second.toInt())
}
}
fun part1(input: List<Pair<String, Int>>): Int {
val combinations = input.groupBy({ it.first }, { it.second }).mapValues {
it.value.sum()
}
val forward = combinations.getSum("forward")
val up = combinations.getSum("up")
val down = combinations.getSum("down")
return forward * (down - up)
}
fun part2(input: List<Pair<String, Int>>): Int {
var aim = 0
var horizontal = 0
var depth = 0
input.forEach {
if (it.first == "forward") {
horizontal += it.second
depth += aim * it.second
}
if (it.first == "up") {
aim -= it.second
}
if (it.first == "down") {
aim += it.second
}
}
return horizontal * depth
}
// example
val testInput = readCommands("day2/test")
assert(part1(testInput) == 150)
assert(part2(testInput) == 900)
val inputList = readCommands("day2/input")
val part1Result = part1(inputList)
val part2Result = part2(inputList)
println("Result of part 1= $part1Result")
println("Result of part 2= $part2Result")
}
fun Map<String, Int>.getSum(type: String) = this[type]!! | 0 | Kotlin | 0 | 0 | b288f16ee862c0a685a3f9e4db34d71b16c3e457 | 1,573 | advent-of-code-2021 | MIT License |
src/day03/Day03.kt | veronicamengyan | 573,063,888 | false | {"Kotlin": 14976} | package day03
import readInput
import splitToListOfList
/**
* Potential improvement:
* * use chunked instead of splitToListOfList
* * use extension class
*/
fun main() {
fun findItemsScore(input: String): Int {
val firstBag = input.substring(0, input.length/2).toSet()
val secondBag = input.substring(input.length/2).toSet()
return firstBag.intersect(secondBag).sumOf { item ->
when (item.isUpperCase()) {
true -> item - 'A' + 27
false -> item - 'a' + 1
}
}
}
fun findBadgeScore(input: List<String>): Int {
val firstElf = input[0].toSet()
val secondElf = input[1].toSet()
val thirdElf = input[2].toSet()
return firstElf.intersect(secondElf).intersect(thirdElf).sumOf { item ->
when (item.isUpperCase()) {
true -> item - 'A' + 27
false -> item - 'a' + 1
}
}
}
fun findBackpackItem1(input: List<String>): Int {
return input.sumOf { item ->
findItemsScore(item)
}
}
fun findBackpackItem2(input: List<String>): Int {
return splitToListOfList(input).sumOf { item ->
findBadgeScore(item)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day03/Day03_test")
println(findBackpackItem1(testInput))
check(findBackpackItem1(testInput) == 157)
println(findBackpackItem2(testInput))
check(findBackpackItem2(testInput) == 70)
val input = readInput("day03/Day03")
println(findBackpackItem1(input))
println(findBackpackItem2(input))
}
| 0 | Kotlin | 0 | 0 | d443cfa49e9d8c9f76fdb6303ecf104498effb88 | 1,686 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/io/matrix/SortMatrixDiagonally.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.matrix
import io.utils.runTests
import java.util.*
// https://leetcode.com/problems/sort-the-matrix-diagonally/
class SortMatrixDiagonally {
fun execute(input: Array<IntArray>?): Array<IntArray>? {
val queue = PriorityQueue<Int>()
if (input?.isEmpty() != false) return input
(input.size - 2 downTo 0).forEach { row ->
enqueue(input, row, 0, queue)
updateMatrix(input, row, 0, queue)
}
input.first().indices.forEach { col ->
enqueue(input, 0, col, queue)
updateMatrix(input, 0, col, queue)
}
return input
}
private fun enqueue(mat: Array<IntArray>, row: Int, col: Int, queue: PriorityQueue<Int>): Unit = when {
row >= mat.size || col >= mat.first().size || row < 0 || col < 0 -> {
}
else -> {
queue.add(mat[row][col])
enqueue(mat, row + 1, col + 1, queue)
}
}
private fun updateMatrix(mat: Array<IntArray>, row: Int, col: Int, queue: PriorityQueue<Int>): Unit = when {
row >= mat.size || col > mat.first().size || row < 0 || col < 0 || queue.isEmpty() -> {
}
else -> {
mat[row][col] = queue.poll()
updateMatrix(mat, row + 1, col + 1, queue)
}
}
}
fun main() {
runTests(listOf(
arrayOf(
intArrayOf(3, 3, 1, 1),
intArrayOf(2, 2, 1, 2),
intArrayOf(1, 1, 1, 2))
to
arrayOf(
intArrayOf(1, 1, 1, 1),
intArrayOf(1, 2, 2, 2),
intArrayOf(1, 2, 3, 3))
),
{ i, v -> i.map { it.toList() }.toList() == v?.map { it.toList() }?.toList() }
, { array -> array.map { it.toList() }.toList().toString() }
, { array -> array?.map { it.toList() }?.toList().toString() }
) { (input, value) ->
value to SortMatrixDiagonally().execute(input)
}
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,787 | coding | MIT License |
src/main/kotlin/Excercise05.kt | underwindfall | 433,989,850 | false | {"Kotlin": 55774} | import kotlin.math.abs
private fun part1() {
getInputAsTest("05") { split("\n") }
.map { preProcess(it) }
.let { input ->
buildMap<EntryPoint, Int> {
for ((start, end) in input) {
val (x0, y0) = start
val (x1, y1) = end
when {
x0 == x1 ->
for (y in minOf(y0, y1)..maxOf(y0, y1)) put(x0 to y, getOrElse(x0 to y) { 0 } + 1)
y0 == y1 ->
for (x in minOf(x0, x1)..maxOf(x0, x1)) put(x to y0, getOrElse(x to y0) { 0 } + 1)
}
}
}
.values
.count { it > 1 }
}
.apply { println("Part1 $this") }
}
private fun part2() {
getInputAsTest("05") { split("\n") }
.map { preProcess(it) }
.filter { (start, end) ->
val (x0, y0) = start
val (x1, y1) = end
x0 == x1 || y0 == y1 || abs(y0 - y1) == abs(x0 - x1)
}
.let { input ->
buildMap<EntryPoint, Int> {
for ((start, end) in input) {
val (x0, y0) = start
val (x1, y1) = end
when {
x0 == x1 ->
for (y in minOf(y0, y1)..maxOf(y0, y1)) {
put(x0 to y, getOrElse(x0 to y) { 0 } + 1)
}
y0 == y1 ->
for (x in minOf(x0, x1)..maxOf(x0, x1)) {
put(x to y0, getOrElse(x to y0) { 0 } + 1)
}
else -> {
val d = abs(x1 - x0)
val dx = (x1 - x0) / d
val dy = (y1 - y0) / d
repeat(d) { i ->
val xy = x0 + dx * i to y0 + i * dy
put(xy, getOrElse(xy) { 0 } + 1)
}
}
}
}
}
.values
.count { it > 1 }
}
.apply { println("Part2 $this") }
}
typealias EntryPoint = Pair<Int, Int>
private fun preProcess(s: String): Pair<EntryPoint, EntryPoint> {
val (from, to) = s.split("->").map { it.trim().split(",") }.map { it[0].toInt() to it[1].toInt() }
return Pair(from, to)
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 4fbee48352577f3356e9b9b57d215298cdfca1ed | 2,038 | advent-of-code-2021 | MIT License |
src/Day07.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | class TreeNode {
var size: Int = 0;
var idDir: Boolean = false;
var parent = -1;
var children = mutableMapOf<String, Int>();
}
var tree = mutableListOf<TreeNode>();
fun newNode(): Int {
tree.add(TreeNode());
return tree.size-1;
}
fun dfs(v: Int) {
if (tree[v].idDir) {
for (child in tree[v].children.values) {
dfs(child);
tree[v].size += tree[child].size;
}
}
}
fun main() {
fun part1(input: List<String>): Int {
var root = newNode();
tree[root].idDir = true;
var curNode = root;
for (line in input) {
var vs = line.split(" ");
if (vs[0] == "$") {
if (vs[1] == "cd") {
curNode = if (vs[2] == "/") {
root;
}
else if (vs[2] == "..") {
tree[curNode].parent;
}
else {
tree[curNode].children[vs[2]]!!;
}
}
}
else {
if (!tree[curNode].children.contains(vs[1])) {
tree[curNode].children[vs[1]] = newNode();
tree[tree[curNode].children[vs[1]]!!].parent = curNode;
}
if (vs[0] == "dir") {
tree[tree[curNode].children[vs[1]]!!].idDir = true;
}
else {
tree[tree[curNode].children[vs[1]]!!].size = vs[0].toInt();
}
}
}
dfs(root);
var ans = 0;
for (node in tree) {
if (node.idDir && node.size <= 100000) {
ans += node.size;
}
}
return ans;
}
fun part2(input: List<String>): Int {
var root = newNode();
tree[root].idDir = true;
var curNode = root;
for (line in input) {
var vs = line.split(" ");
if (vs[0] == "$") {
if (vs[1] == "cd") {
curNode = if (vs[2] == "/") {
root;
}
else if (vs[2] == "..") {
tree[curNode].parent;
}
else {
tree[curNode].children[vs[2]]!!;
}
}
}
else {
if (!tree[curNode].children.contains(vs[1])) {
tree[curNode].children[vs[1]] = newNode();
tree[tree[curNode].children[vs[1]]!!].parent = curNode;
}
if (vs[0] == "dir") {
tree[tree[curNode].children[vs[1]]!!].idDir = true;
}
else {
tree[tree[curNode].children[vs[1]]!!].size = vs[0].toInt();
}
}
}
dfs(root);
var totSize = 70000000;
var needed = 30000000;
var ans = totSize;
for (node in tree) {
if (node.idDir && totSize - (tree[root].size - node.size) >= needed) {
ans = ans.coerceAtMost(node.size);
}
}
return ans;
}
val input = readInput("Day07")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 3,344 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/aoc2021/Day03.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2021
import readInput
fun main() {
val (year, day) = "2021" to "Day03"
fun List<String>.countBits(index: Int): Pair<Int, Int> {
var zeros = 0
var ones = 0
this.forEach {
when (it[index]) {
'0' -> zeros++
'1' -> ones++
}
}
return zeros to ones
}
fun part1(input: List<String>): Int {
val length = input.first().length
val gamma = (0 until length).map {
input.countBits(it)
}.joinToString("") { (zeros, ones) ->
if (zeros > ones) "0" else "1"
}
val epsilon = gamma.map {
if (it == '0') "1" else "0"
}.joinToString("")
return gamma.toInt(2) * epsilon.toInt(2)
}
fun part2(input: List<String>): Int {
val length = input.first().length
var oxygen = input.map { it }
var i = 0
while (oxygen.size > 1) {
val (zeros, ones) = oxygen.countBits(i)
oxygen = oxygen.filter { it[i] == if (zeros > ones) '0' else '1' }
i = (i + 1) % length
}
var co2 = input.map { it }
i = 0
while (co2.size > 1) {
val (zeros, ones) = co2.countBits(i)
co2 = co2.filter { it[i] == if (zeros <= ones) '0' else '1' }
i = (i + 1) % length
}
return oxygen.first().toInt(2) * co2.first().toInt(2)
}
val testInput = readInput(name = "${day}_test", year = year)
val input = readInput(name = day, year = year)
check(part1(testInput) == 198)
println(part1(input))
check(part2(testInput) == 230)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,693 | aoc-kotlin | Apache License 2.0 |
src/Day09.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | import kotlin.math.abs
enum class Direction(val value: String) {
Up("U"),
Down("D"),
Left("L"),
Right("R")
}
data class Movement(
val direction: Direction,
val step: Int
)
data class Coordinates(
val x: Int,
val y: Int,
)
fun main() {
fun List<String>.toMovements(): List<Movement> =
map { line ->
val splitMovement = line.split(" ")
val direction = Direction.values().first { it.value == splitMovement.first() }
val steps = splitMovement.last().toInt()
Movement(direction, steps)
}
fun computeHeadCoordinates(movements: List<Movement>): List<Coordinates> {
var currentHeadCoordinates = Coordinates(0, 0)
val headCoordinates = mutableListOf(currentHeadCoordinates)
movements.forEach {
val direction = it.direction
repeat(it.step) {
currentHeadCoordinates = when (direction) {
Direction.Up -> currentHeadCoordinates.copy(y = currentHeadCoordinates.y + 1)
Direction.Down -> currentHeadCoordinates.copy(y = currentHeadCoordinates.y - 1)
Direction.Left -> currentHeadCoordinates.copy(x = currentHeadCoordinates.x - 1)
Direction.Right -> currentHeadCoordinates.copy(x = currentHeadCoordinates.x + 1)
}
headCoordinates.add(currentHeadCoordinates)
}
}
return headCoordinates
}
fun computeTailCoordinates(headCoordinates: List<Coordinates>): List<Coordinates> {
var currentTailCoordinates = Coordinates(0, 0)
val tailCoordinates = mutableListOf<Coordinates>()
headCoordinates.forEach { head ->
val offsetX = if (head.x > currentTailCoordinates.x) -1 else 1
val offsetY = if (head.y > currentTailCoordinates.y) -1 else 1
currentTailCoordinates = when {
abs(currentTailCoordinates.x - head.x) > 1 -> {
val x = head.x + offsetX
val y = if (abs(currentTailCoordinates.y - head.y) > 1) head.y + offsetY else head.y
currentTailCoordinates.copy(x = x, y = y)
}
abs(currentTailCoordinates.y - head.y) > 1 -> {
val x = if (abs(currentTailCoordinates.x - head.x) > 1) head.x + offsetX else head.x
val y = head.y + offsetY
currentTailCoordinates.copy(x = x, y = y)
}
else -> currentTailCoordinates
}
tailCoordinates.add(currentTailCoordinates)
}
return tailCoordinates
}
fun computeTailTrail(input: List<String>, knotSize: Int): Int {
var currentHeadCoordinates = computeHeadCoordinates(input.toMovements())
val tailCoordinatesList = mutableListOf<List<Coordinates>>()
repeat(knotSize) {
val tailCoordinates = computeTailCoordinates(currentHeadCoordinates)
currentHeadCoordinates = tailCoordinates
tailCoordinatesList.add(tailCoordinates)
}
return tailCoordinatesList.last().toSet().size
}
fun part1(input: List<String>): Int =
computeTailTrail(input, knotSize = 1)
fun part2(input: List<String>): Int =
computeTailTrail(input, knotSize = 9)
check(part1(readInput("Day09_test")) == 13)
check(part2(readInput("Day09_test")) == 1)
check(part2(readInput("Day09_test2")) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 3,599 | AdventOfCode2022 | Apache License 2.0 |
src/Day13.kt | hufman | 573,586,479 | false | {"Kotlin": 29792} | import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.*
fun main() {
fun parse(input: List<String>): List<JsonArray> {
return input
.filter { it.isNotEmpty() }
.map { Json.decodeFromString(it) }
}
fun comparePacket(left: JsonArray, right: JsonArray): Int {
// println(" - Comparing $left vs $right")
left.forEachIndexed { index, l ->
if (index >= right.size) {
// println(" - Left is too long, failing")
return 1
}
val r = right[index]
val result = if (l is JsonPrimitive && r is JsonPrimitive) {
l.int.compareTo(r.int)
} else {
if (l is JsonArray && r is JsonArray) {
comparePacket(l, r)
} else if (l is JsonPrimitive && r is JsonArray) {
comparePacket(JsonArray(listOf(l)), r)
} else if (l is JsonArray && r is JsonPrimitive) {
comparePacket(l, JsonArray(listOf(r)))
} else {
0
}
}
// println(" - $result $l vs $r")
if (result != 0) return result
}
return -1
}
fun part1(input: List<String>): Int {
val lines = parse(input)
return lines
.chunked(2) {
Pair(it[0], it[1])
}
.foldIndexed(0) { index, acc, pair: Pair<JsonArray, JsonArray> ->
val correct = comparePacket(pair.first, pair.second)
// println("$correct ${pair.first} ${pair.second}")
if (correct == -1) {
acc + index + 1
} else {
acc
}
}
}
fun part2(input: List<String>): Int {
val first = JsonArray(listOf(JsonArray(listOf(JsonPrimitive(2)))))
val second = JsonArray(listOf(JsonArray(listOf(JsonPrimitive(6)))))
val lines = parse(input) +
listOf(first, second)
val sorted = lines.sortedWith(object: Comparator<JsonArray> {
override fun compare(p0: JsonArray?, p1: JsonArray?): Int {
p0 ?: return 0
p1 ?: return 0
return comparePacket(p0, p1)
}
})
val firstIndex = sorted.indexOf(first)
val secondIndex = sorted.indexOf(second)
return (firstIndex + 1) * (secondIndex + 1)
}
// 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 | 0 | 1bc08085295bdc410a4a1611ff486773fda7fcce | 2,211 | aoc2022-kt | Apache License 2.0 |
2020/src/year2021/day12/code.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2021.day12
import util.readAllLines
enum class Size {
SMALL, LARGE;
}
data class Node(val name: String) {
val size = if (name[0].isUpperCase()) Size.LARGE else Size.SMALL
val paths = mutableMapOf<Node, MutableSet<MutableList<Node>>>()
val isVisitable: Boolean
get() = (size == Size.LARGE || numVisits == 0 || (isSpecial && numVisits < 2))
var isSpecial = false
var numVisits = 0
override fun toString() = "Node '${name}'"
override fun hashCode() = name.hashCode()
override fun equals(other: Any?) = (other is Node && other.name == name)
}
class CaveMap: MutableMap<Node, MutableSet<Node>> by mutableMapOf() {
fun add(node1Name: String, node2Name: String) {
val node1 = node(node1Name) ?: Node(node1Name)
val node2 = node(node2Name) ?: Node(node2Name)
put(node1, (get(node1) ?: mutableSetOf()).also { if (!it.contains(node2)) it.add(node2) })
put(node2, (get(node2) ?: mutableSetOf()).also { if (!it.contains(node1)) it.add(node1) })
}
val smallCaves: Set<Node>
get() = keys.filter { it.size == Size.SMALL && it.name != START && it.name != END }.toSet()
fun makeSpecial(node: Node) = keys.forEach { it.isSpecial = it == node }
fun reset() {
values.forEach {
it.forEach {
it.numVisits = 0
}
}
}
fun findPaths(start: String, end: String): Set<MutableList<Node>> =
findPaths(checkNotNull(node(start)), checkNotNull(node(end)))
private fun node(name: String) = keys.firstOrNull { it.name == name }
private fun findPaths(start: Node, end: Node, indent: String = ""): Set<MutableList<Node>> {
val nextIndent = "$indent "
val result = mutableSetOf<MutableList<Node>>()
if (!start.isVisitable) {
// println("${indent}--> $start is not visitable")
}
start.numVisits++
when {
start == end -> {
result.add(mutableListOf())
}
else -> {
val connections = get(start)
val alreadyVisited = mutableMapOf<Node, Int>()
caves.values.forEach { it.forEach { alreadyVisited[it] = it.numVisits } }
checkNotNull(connections)
.forEach { node ->
if (node.isVisitable) {
findPaths(node, end, nextIndent)
.onEach {
it.add(0, node)
result.add(it)
}
caves.reset()
alreadyVisited.forEach { (node, numVisits) -> node.numVisits = numVisits }
}
}
}
}
return result
}
}
private const val START = "start"
private const val END = "end"
val caves = CaveMap()
fun main() {
readAllLines("test1.txt").map { line ->
line.split('-').also { parts ->
caves.add(parts[0], parts[1])
}
}
part1()
part2()
}
private fun part1() {
val paths = caves.findPaths(START, END)
println(paths.size)
}
private fun part2() {
val paths = caves.smallCaves.flatMap {
caves.makeSpecial(it)
caves.reset()
caves.findPaths(START, END)
}
println(paths.size)
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 3,412 | adventofcode | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day20/Day20.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day20
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputSplitOnBlank
object Day20 : Day {
override val input = ScannerImage.from(readInputSplitOnBlank(20))
override fun part1() = enhance(2).image.filterValues { it == 1 }.size
override fun part2() = enhance(50).image.filterValues { it == 1 }.size
private fun enhance(times: Int): ScannerImage {
var current = input
repeat(times) {
current = current.enhance()
}
return current
}
data class ScannerImage(val algorithm: List<Int>, val image: Map<Position, Int>, val default: Int) {
companion object {
fun from(input: List<String>) = ScannerImage(
input.first().toList().map { if (it == '#') 1 else 0 },
input.last().lines()
.flatMapIndexed { y: Int, s: String -> s.toList().mapIndexed { x, c -> Position(x, y) to if (c == '#') 1 else 0 } }
.toMap(),
0
)
}
fun enhance(): ScannerImage {
val enhanced = buildMap {
for (y in image.keys.minOf { it.y } - 1..image.keys.maxOf { it.y } + 1) {
for (x in image.keys.minOf { it.x } - 1..image.keys.maxOf { it.x } + 1) {
val position = Position(x, y)
val bits = buildString { position.adjacent().forEach { append(image.getOrDefault(it, default).toString()) } }
put(position, algorithm[bits.toInt(2)])
}
}
}
return copy(image = enhanced, default = algorithm[default.toString().repeat(9).toInt(2)])
}
}
data class Position(val x: Int, val y: Int) {
fun adjacent(): List<Position> {
return (0..2).flatMap { y -> (0..2).map { it to y } }.map { (x, y) -> Position(this.x + x - 1, this.y + y - 1) }
}
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 2,013 | aoc2021 | MIT License |
src/aoc2016/kot/Day22.kt | Tandrial | 47,354,790 | false | null | package aoc2016.kot
import java.nio.file.Files
import java.nio.file.Paths
import java.util.regex.Pattern
object Day22 {
data class Node(val x: Int, val y: Int, val size: Int, val used: Int, val avail: Int)
fun parse(input: List<String>): List<Node> = input.mapNotNull {
val m = Pattern.compile("(\\d+)-y(\\d+)\\s+(\\d+)T\\s+(\\d+)T\\s+(\\d+)").matcher(it)
if (m.find()) Node(m.group(1).toInt(), m.group(2).toInt(), m.group(3).toInt(), m.group(4).toInt(), m.group(5).toInt())
else null
}
fun partOne(s: List<Node>): Int = s.filter { n -> n.used > 0 }.map { n -> s.filter { other -> n != other && other.avail >= n.used }.count() }.sum()
fun partTwo(s: List<Node>): Int {
val xSize: Int = s.maxBy { it.x }!!.x
val wallEdge: Node = s.find { it.x == s.find { it.size > 250 }!!.x - 1 }!!
val emptyDisk: Node = s.find { it.used == 0 }!!
val nodes = s.groupBy { it.x }
for ((_, value) in nodes) {
println(value.map {
when {
it.x == 0 && it.y == 0 -> 'S'
it.x == xSize && it.y == 0 -> 'G'
it.size > 100 -> '#'
else -> '.'
}
})
}
var result = Math.abs(emptyDisk.x - wallEdge.x) + Math.abs(emptyDisk.y - wallEdge.y)
result += Math.abs(wallEdge.x - xSize) + wallEdge.y + 5 * (xSize - 1)
return result
}
}
fun main(args: Array<String>) {
val s = Files.readAllLines(Paths.get("./input/2016/Day22_input.txt"))
val nodes = Day22.parse(s)
println("Part One = ${Day22.partOne(nodes)}")
println("Part One = ${Day22.partTwo(nodes)}")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 1,559 | Advent_of_Code | MIT License |
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p00/Leet4.kt | artemkaxboy | 513,636,701 | false | {"Kotlin": 547181, "Java": 13948} | package com.artemkaxboy.leetcode.p00
import com.artemkaxboy.leetcode.LeetUtils.stringToIntArray
private class Leet4 {
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val size1 = nums1.size
val size2 = nums2.size
val size = size1 + size2
val mergedList = ArrayList<Int>(size)
var i1 = 0
var i2 = 0
for (i in 0 until size) {
val num1 = if (i1 >= size1) Int.MAX_VALUE else nums1[i1]
val num2 = if (i2 >= size2) Int.MAX_VALUE else nums2[i2]
val next = if (num1 > num2) {
i2++
num2
} else {
i1++
num1
}
mergedList.add(next)
}
return if (size % 2 == 0) {
val first = (size / 2) - 1
val second = first + 1
return (mergedList[first] + mergedList[second]).toDouble() / 2
} else {
mergedList[size / 2].toDouble()
}
}
}
fun main() {
val case1 = "[1,3]" to "[2]" // 2
// doWork(case1)
val myCase = "[1,2,3,4,5,6,7]" to "[999,1000,1001]" // 5.5
doWork(myCase)
}
private fun doWork(data: Pair<String, String>) {
val solution = Leet4()
val nums1 = stringToIntArray(data.first)
val nums2 = stringToIntArray(data.second)
val result = solution.findMedianSortedArrays(nums1, nums2)
println("Data: $data")
println("Result: $result\n")
}
| 0 | Kotlin | 0 | 0 | 516a8a05112e57eb922b9a272f8fd5209b7d0727 | 1,469 | playground | MIT License |
src/main/kotlin/day05/Day05.kt | daniilsjb | 434,765,082 | false | {"Kotlin": 77544} | package day05
import java.io.File
import kotlin.math.min
import kotlin.math.max
fun main() {
val data = parse("src/main/kotlin/day05/Day05.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 05 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Point(
val x: Int,
val y: Int,
)
private data class Line(
val x1: Int,
val y1: Int,
val x2: Int,
val y2: Int,
)
private fun parse(path: String): List<Line> =
File(path)
.readLines()
.map(String::toLine)
private fun String.toLine(): Line {
val regex = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex()
val (x1, y1, x2, y2) = regex.find(this)!!
.destructured
.toList()
.map(String::toInt)
return Line(x1, y1, x2, y2)
}
private fun part1(lines: List<Line>) =
lines.asSequence()
.flatMap { (x1, y1, x2, y2) ->
if (y1 == y2) {
(min(x1, x2)..max(x1, x2)).asSequence().map { x -> Point(x, y1) }
} else if (x1 == x2) {
(min(y1, y2)..max(y1, y2)).asSequence().map { y -> Point(x1, y) }
} else {
sequenceOf()
}
}
.groupingBy { it }
.eachCount()
.count { (_, frequency) -> frequency >= 2 }
private fun part2(lines: List<Line>) =
lines.asSequence()
.flatMap { (x1, y1, x2, y2) ->
if (y1 == y2) {
(min(x1, x2)..max(x1, x2)).asSequence().map { x -> Point(x, y1) }
} else if (x1 == x2) {
(min(y1, y2)..max(y1, y2)).asSequence().map { y -> Point(x1, y) }
} else {
val xd = if (x2 > x1) 1 else -1
val yd = if (y2 > y1) 1 else -1
(0..(max(x1, x2) - min(x1, x2))).asSequence()
.map { delta -> Point(x1 + delta * xd, y1 + delta * yd) }
}
}
.groupingBy { it }
.eachCount()
.count { (_, frequency) -> frequency >= 2 } | 0 | Kotlin | 0 | 1 | bcdd709899fd04ec09f5c96c4b9b197364758aea | 2,118 | advent-of-code-2021 | MIT License |
src/Day04.kt | leeturner | 572,659,397 | false | {"Kotlin": 13839} | fun List<String>.parse(): List<List<Set<Int>>> {
return this.map {
it.split(',')
.map { pair -> pair.split('-').map { assignment -> assignment.toInt() } }
.map { (start, end) -> (start..end).toSet() }
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.parse().count { (firstAssignment, secondAssignment) ->
firstAssignment.containsAll(secondAssignment) || secondAssignment.containsAll(firstAssignment)
}
}
fun part2(input: List<String>): Int {
return input.parse().count { (firstAssignment, secondAssignment) ->
(firstAssignment intersect secondAssignment).isNotEmpty()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8da94b6a0de98c984b2302b2565e696257fbb464 | 914 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g0901_1000/s0934_shortest_bridge/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0901_1000.s0934_shortest_bridge
// #Medium #Array #Depth_First_Search #Breadth_First_Search #Matrix
// #Graph_Theory_I_Day_6_Matrix_Related_Problems
// #2023_04_27_Time_301_ms_(80.95%)_Space_77.9_MB_(9.52%)
class Solution {
private class Pair(var x: Int, var y: Int)
private val dirs = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1))
fun shortestBridge(grid: Array<IntArray>): Int {
val q: ArrayDeque<Pair> = ArrayDeque()
var flag = false
val visited = Array(grid.size) {
BooleanArray(
grid[0].size
)
}
var i = 0
while (i < grid.size && !flag) {
var j = 0
while (j < grid[i].size && !flag) {
if (grid[i][j] == 1) {
dfs(grid, i, j, visited, q)
flag = true
}
j++
}
i++
}
var level = -1
while (q.isNotEmpty()) {
var size: Int = q.size
level++
while (size-- > 0) {
val rem = q.removeFirst()
for (dir in dirs) {
val newrow = rem.x + dir[0]
val newcol = rem.y + dir[1]
if (newrow >= 0 && newcol >= 0 && newrow < grid.size && newcol < grid[0].size &&
!visited[newrow][newcol]
) {
if (grid[newrow][newcol] == 1) {
return level
}
q.add(Pair(newrow, newcol))
visited[newrow][newcol] = true
}
}
}
}
return -1
}
private fun dfs(grid: Array<IntArray>, row: Int, col: Int, visited: Array<BooleanArray>, q: ArrayDeque<Pair>) {
visited[row][col] = true
q.add(Pair(row, col))
for (dir in dirs) {
val newrow = row + dir[0]
val newcol = col + dir[1]
if (newrow >= 0 && newcol >= 0 && newrow < grid.size && newcol < grid[0].size &&
!visited[newrow][newcol] && grid[newrow][newcol] == 1
) {
dfs(grid, newrow, newcol, visited, q)
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,320 | LeetCode-in-Kotlin | MIT License |
src/Day04.kt | burtz | 573,411,717 | false | {"Kotlin": 10999} | fun main() {
fun returnSet(low : Int,high : Int) : Set<Int>
{
val set = mutableSetOf<Int>()
for (i in low..high) set += i
return set
}
fun part1(input: List<String>): Int {
var counter = 0
input.forEach {
var elfs = it.split(',')
var shift1 = returnSet(elfs[0].substringBefore('-').toInt(),elfs[0].substringAfter('-').toInt())
var shift2 = returnSet(elfs[1].substringBefore('-').toInt(),elfs[1].substringAfter('-').toInt())
if(shift1.intersect(shift2).size == shift1.size || shift1.intersect(shift2).size == shift2.size) counter ++
}
return counter
}
fun part2(input: List<String>): Int {
var counter = 0
input.forEach {
var elfs = it.split(',')
var shift1 = returnSet(elfs[0].substringBefore('-').toInt(),elfs[0].substringAfter('-').toInt())
var shift2 = returnSet(elfs[1].substringBefore('-').toInt(),elfs[1].substringAfter('-').toInt())
if(shift1.intersect(shift2).isNotEmpty()) counter ++
}
return counter
}
// 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 | daac7f91e1069d1490e905ffe7b7f11b5935af06 | 1,402 | adventOfCode2022 | Apache License 2.0 |
src/Day10.kt | treegem | 572,875,670 | false | {"Kotlin": 38876} | import common.readInput
fun main() {
fun part1(input: List<String>): Int {
val registerHistory = input.toRegisterHistory()
return (20..220 step 40).sumOf { registerHistory[it]!! * it }
}
fun part2(input: List<String>) =
input.toRegisterHistory()
.toSortedMap()
.values
.mapIndexed { pixel, spritePosition ->
if ((pixel % 40) in (spritePosition - 1..spritePosition + 1)) '█'
else ' '
}
.chunked(40)
.joinToString("\n") { it.joinToString("") }
val day = "10"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == 13140)
println(part2(testInput))
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
}
private fun List<String>.toRegisterHistory(): Map<Int, Int> {
val history = mutableMapOf(1 to 1)
var cycle = 1
this.forEach {
history[++cycle] = history[cycle - 1]!!
if (it.startsWith("addx")) {
history[++cycle] = history[cycle - 1]!! + it.substringAfterLast(" ").toInt()
}
}
return history
}
| 0 | Kotlin | 0 | 0 | 97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8 | 1,243 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/aoc2023/Day02.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2023
import AoCDay
import kotlin.math.max
// https://adventofcode.com/2023/day/2
object Day02 : AoCDay<Int>(
title = "Cube Conundrum",
part1ExampleAnswer = 8,
part1Answer = 2256,
part2ExampleAnswer = 2286,
part2Answer = 74229,
) {
private class CubeSet(val red: Int, val green: Int, val blue: Int)
private class Game(val id: Int, val rounds: List<CubeSet>)
private fun parseCubeSet(input: String): CubeSet {
val colors = input.split(", ", limit = 3).associate {
val (number, color) = it.split(' ', limit = 2)
color to number.toInt()
}
return CubeSet(colors["red"] ?: 0, colors["green"] ?: 0, colors["blue"] ?: 0)
}
private fun parseGame(input: String): Game {
val (game, rounds) = input.split(": ", limit = 2)
val id = game.substringAfter("Game ").toInt()
return Game(id, rounds.split("; ").map(::parseCubeSet))
}
private val Game.isPossibleWith12Red13Green14Blue
get() = rounds.all { it.red <= 12 && it.green <= 13 && it.blue <= 14 }
private val Game.minimumCubeSetToMakePossible
get() = rounds.fold(initial = CubeSet(0, 0, 0)) { acc, cur ->
CubeSet(max(acc.red, cur.red), max(acc.green, cur.green), max(acc.blue, cur.blue))
}
private val CubeSet.power get() = red * green * blue
override fun part1(input: String) = input
.lineSequence()
.map(::parseGame)
.filter { it.isPossibleWith12Red13Green14Blue }
.sumOf { it.id }
override fun part2(input: String) = input
.lineSequence()
.map(::parseGame)
.map { it.minimumCubeSetToMakePossible }
.sumOf { it.power }
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 1,717 | advent-of-code-kotlin | MIT License |
src/main/kotlin/com/jacobhyphenated/advent2023/day17/Day17.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day17
import com.jacobhyphenated.advent2023.Day
import java.util.*
/**
* Day 17: Clumsy Crucible
*
* The cart that carries the lava needs to travel from the top left corner
* to the bottom right of the puzzle input. Each space has a cost.
* Need to find path with the lowest overall cost.
*
* However, the cart has some limitations. It can only go a maximum of 3 consecutive spaces
* in the same direction before needing to make a 90 degree turn. It can turn 90 degrees
* at a time (so it cannot immediately go backwards).
*/
class Day17: Day<List<List<Int>>> {
override fun getInput(): List<List<Int>> {
return readInputFile("17").lines().map { it.toCharArray().map { c -> c.digitToInt() } }
}
/**
* Part 1: Find the minimum possible cost to get from the start ot the end
*/
override fun part1(input: List<List<Int>>): Int {
return findBestPathToEnd(input)
}
/**
* Part 2: Now use an "Ultra" cart. This cart must move at least 4 consecutive spaces before turning.
* It cannot go more than 10 spaces without turning. Also, it cannot stop unless it's gone 4 consecutive spaces
* and it must come to a stop at the bottom right corner
*/
override fun part2(input: List<List<Int>>): Any {
return findBestPathToEnd(input, true)
}
/**
* Use the same basic logic for part1 and 2 except for the boolean [useUltraPath] for part 2 that
* toggles on additional logic for the ultra cart.
*
* This is an implementation of Dijkstra's algorithm that specifically allows certain spaces to be
* traversed by a longer path, since depending on the cart state, some adjacent spaces are only valid
* options in certain circumstances.
*/
private fun findBestPathToEnd(input: List<List<Int>>, useUltraPath: Boolean = false): Int {
val distances: MutableMap<Pair<Int,Int>, Int> = mutableMapOf(Pair(0,0) to 0)
val endLocation = Pair(input.size - 1, input[0].size - 1)
// BFS where we always look next at the path with the least cost so far
val queue = PriorityQueue<PathCost> { a, b -> a.cost - b.cost }
// Use two separate start states (important for part2, negligible for part 1)
val start = CartPath(Pair(0,0), Direction.EAST, 0)
val start2 = CartPath(Pair(0,0), Direction.SOUTH, 0)
val visited = mutableSetOf(start, start2)
queue.add(PathCost(start, 0))
queue.add(PathCost(start2, 0))
var current: PathCost
do {
current = queue.remove()
// If we already found a less expensive way to reach this position (with the same cart path states)
if (current.cost > (distances[current.cartPath.location] ?: Int.MAX_VALUE) && current.cartPath in visited) {
continue
}
// Maintains a set of cart path states which include location, direction, and consecutive spaces traveled
visited.add(current.cartPath)
// this is the least expensive path to the end location
if (current.cartPath.location == endLocation){
// but for ultra mode - the path must be going for at least 4 consecutive spaces in order to stop
if (useUltraPath) {
if (current.cartPath.consecutive >= 4){
return current.cost
}
} else {
return current.cost
}
continue
}
// From the current position, find connecting pipes
val adjacent = if (useUltraPath) {
findAdjacentUltra(current.cartPath, input)
} else {
findAdjacent(current.cartPath, input)
}
adjacent.forEach {
val (r,c) = it.location
val cost = current.cost + input[r][c]
// If this is the least expensive way to reach this space, record that
if (cost < (distances[it.location] ?: Int.MAX_VALUE)) {
distances[it.location] = cost
}
queue.add(PathCost(it, cost))
}
} while (queue.size > 0)
return 0
}
/**
* For a standard cart, adjacent spaces are spaces at 90 degree angles,
* and forward one space if the cart has not already traveled 3 consecutive spaces-
*/
private fun findAdjacent(cartPath: CartPath, grid: List<List<Int>>): List<CartPath> {
val cartPaths = mutableListOf<CartPath>()
for (direction in cartPath.direction.turn()) {
val nextLocation = nextGridSpace(cartPath.location, direction, grid)
if (nextLocation != null){
cartPaths.add(CartPath(nextLocation, direction, 1))
}
}
if (cartPath.consecutive < 3) {
val nextLocation = nextGridSpace(cartPath.location, cartPath.direction, grid)
if (nextLocation != null){
cartPaths.add(CartPath(nextLocation, cartPath.direction, cartPath.consecutive + 1))
}
}
return cartPaths
}
/**
* For an ultra cart, adjacent spaces are:
* one forward if the cart has not already traveled 10 consecutive spaces
* one at each 90-degree angle if the cart has already traveled at least 4 consecutive spaces
*/
private fun findAdjacentUltra(cartPath: CartPath, grid: List<List<Int>>): List<CartPath> {
val cartPaths = mutableListOf<CartPath>()
if (cartPath.consecutive >= 4) {
for (direction in cartPath.direction.turn()) {
val nextLocation = nextGridSpace(cartPath.location, direction, grid)
if (nextLocation != null){
cartPaths.add(CartPath(nextLocation, direction, 1))
}
}
}
if (cartPath.consecutive < 10) {
val nextLocation = nextGridSpace(cartPath.location, cartPath.direction, grid)
if (nextLocation != null){
cartPaths.add(CartPath(nextLocation, cartPath.direction, cartPath.consecutive + 1))
}
}
return cartPaths
}
private fun nextGridSpace(location: Pair<Int,Int>, direction: Direction, grid: List<List<Int>>): Pair<Int,Int>? {
val (row,col) = location
val (nextRow, nextCol) = when(direction){
Direction.NORTH -> Pair(row - 1, col)
Direction.SOUTH -> Pair(row + 1, col)
Direction.EAST -> Pair(row, col + 1)
Direction.WEST -> Pair(row, col - 1)
}
return if (nextRow < 0 || nextRow >= grid.size || nextCol < 0 || nextCol >= grid[row].size) {
null
} else {
Pair(nextRow, nextCol)
}
}
override fun warmup(input: List<List<Int>>) {
part1(input)
}
}
data class CartPath(val location: Pair<Int,Int>, val direction: Direction, val consecutive: Int)
data class PathCost(val cartPath: CartPath, val cost: Int)
enum class Direction {
NORTH, SOUTH, EAST, WEST;
fun turn(): List<Direction> {
return when(this) {
NORTH, SOUTH -> listOf(EAST, WEST)
EAST, WEST -> listOf(NORTH, SOUTH)
}
}
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
Day17().run()
} | 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 6,746 | advent2023 | The Unlicense |
src/Day02.kt | Jaavv | 571,865,629 | false | {"Kotlin": 14896} | // https://adventofcode.com/2022/day/2
fun main() {
val input = readInput("Day02")
val testinput = readInput("Day02_test")
println(Day02Part1(input)) // 12276
println(Day02Part2(input)) // 9975
println(day02part1op(input))
println(day02part2op(input))
}
fun rock(vs: String): Int {
val result = when (vs) {
"A" -> 3
"B" -> 0
"C" -> 6
else -> 0
}
return result + 1
}
fun paper(vs: String): Int {
val result = when (vs) {
"A" -> 6
"B" -> 3
"C" -> 0
else -> 0
}
return result + 2
}
fun scissors(vs: String): Int {
val result = when (vs) {
"A" -> 0
"B" -> 6
"C" -> 3
else -> 0
}
return result + 3
}
fun RPS(opponent: String, player: String): Int {
return when (player) {
"X" -> rock(opponent)
"Y" -> paper(opponent)
"Z" -> scissors(opponent)
else -> 0
}
}
fun winPart2(vs: String): Int {
return when (vs) {
"A" -> paper(vs)
"B" -> scissors(vs)
"C" -> rock(vs)
else -> 0
}
}
fun losePart2(vs: String): Int {
return when (vs) {
"A" -> scissors(vs)
"B" -> rock(vs)
"C" -> paper(vs)
else -> 0
}
}
fun drawPart2(vs: String): Int {
return when (vs) {
"A" -> rock(vs)
"B" -> paper(vs)
"C" -> scissors(vs)
else -> 0
}
}
fun RPSpart2(opponent: String, player: String): Int {
return when (player) {
"X" -> losePart2(opponent)
"Y" -> drawPart2(opponent)
"Z" -> winPart2(opponent)
else -> 0
}
}
fun Day02Part1(input: List<String>): Int {
return input.sumOf { round ->
val hands = round.split(" ")
RPS(hands.first(), hands.last())
}
}
fun Day02Part2(input: List<String>): Int {
return input.sumOf { round ->
val hands = round.split(" ")
RPSpart2(hands.first(), hands.last())
}
}
// optimized attempt
fun rps(hands: Pair<String, String>): Int {
val score = when (hands) {
Pair("A", "Y"), Pair("B", "Z"), Pair("C", "X") -> 6
Pair("A", "X"), Pair("B", "Y"), Pair("C", "Z") -> 3
Pair("A", "Z"), Pair("B", "X"), Pair("C", "Y") -> 0
else -> 0
}
val shape = when (hands.second) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
return score + shape
}
fun wld(hands: Pair<String, String>): Int {
return when (hands.second) {
"X" -> when (hands.first) {
"A" -> rps(Pair("A", "Z"))
"B" -> rps(Pair("B", "X"))
"C" -> rps(Pair("C", "Y"))
else -> 0
}
"Y" -> when (hands.first) {
"A" -> rps(Pair("A", "X"))
"B" -> rps(Pair("B", "Y"))
"C" -> rps(Pair("C", "Z"))
else -> 0
}
"Z" -> when (hands.first) {
"A" -> rps(Pair("A", "Y"))
"B" -> rps(Pair("B", "Z"))
"C" -> rps(Pair("C", "X"))
else -> 0
}
else -> 0
}
}
fun day02part1op(input: List<String>): Int {
return input.sumOf { round ->
val hands = round.split(" ")
rps(Pair(hands.first(), hands.last()))
}
}
fun day02part2op(input: List<String>): Int {
return input.sumOf { round ->
val hands = round.split(" ")
wld(Pair(hands.first(), hands.last()))
}
}
| 0 | Kotlin | 0 | 0 | 5ef23a16d13218cb1169e969f1633f548fdf5b3b | 3,416 | advent-of-code-2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day25.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val connections = readInput(2023, 25, false).useLines { lines ->
buildMap<String, MutableSet<String>> {
for (line in lines) {
val (key, other) = line.split(": ")
val others = other.split(" ")
getOrPut(key, ::hashSetOf).addAll(others)
others.forEach { c -> getOrPut(c, ::hashSetOf).add(key) }
}
}
}
part1(connections)
}
private fun part1(connections: Map<String, Set<String>>) {
val arrangement = findArrangement(connections)
val groups = IntArray(2)
var found = 0
for ((_, group) in arrangement) {
if (group.size == 3) found++
groups[found] += group.size
}
println(groups[0] * groups[1])
}
private fun findArrangement(connections: Map<String, Set<String>>): Map<Int, Set<String>> {
for (start in connections.keys) {
val queue = ArrayDeque<Pair<String, Int>>()
val visited = hashSetOf<String>()
val groups = hashMapOf<Int, MutableSet<String>>()
queue.addLast(start to 0)
while (queue.isNotEmpty()) {
val (current, level) = queue.removeFirst()
if (visited.add(current)) {
groups.getOrPut(level) { hashSetOf() }.add(current)
for (other in connections.getValue(current)) if (other !in visited) queue.add(other to level + 1)
}
}
for ((level, group) in groups) {
// Condition to find the right arrangement (-_-)
if (group.size == 3 && level != groups.keys.last()) return groups
}
}
error("Arrangement not found")
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,746 | adventofcode | Apache License 2.0 |
src/Day03.kt | flexable777 | 571,712,576 | false | {"Kotlin": 38005} | fun main() {
fun Char.getPriority(): Int =
if (this.isLowerCase()) {
this - 'a' + 1
} else {
this - 'A' + 27
}
fun part1(input: List<String>): Int =
input.sumOf { line ->
//Better way to split these?
val middleIndex = line.length / 2
val compartment1 = line.substring(0, middleIndex).map { it.getPriority() }.toSet()
val compartment2 = line.substring(middleIndex).map { it.getPriority() }.toSet()
compartment1.intersect(compartment2).single()
}
fun part2(input: List<String>): Int {
//Alt. 1
// input.chunked(3).sumOf { chunk ->
// chunk.flatMap { it.toSet().map { char -> char.getPriority() } }
// .groupBy { it }
// .filter { it.value.size == 3 }
// .keys.first()
// }
//Alt. 2
return input.chunked(3).sumOf { chunk ->
chunk.reduce { acc, s ->
s.toSet().intersect(acc.toSet()).joinToString(separator = "")
}.map { it.getPriority() }.sum()
}
//Alt. 3 retainAll?
}
val testInput = readInputAsLines("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInputAsLines("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d9a739eb203c535a3d83bc5da1b6a6a90a0c7bd6 | 1,377 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | Cryosleeper | 572,977,188 | false | {"Kotlin": 43613} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val steps = input.toSteps()
val visitedPlaces = mutableSetOf<Position>()
val head = Position(0, 0)
val tail = Position(0, 0)
steps.forEach { step ->
when (step) {
Step.UP -> head.y--
Step.DOWN -> head.y++
Step.LEFT -> head.x--
Step.RIGHT -> head.x++
}
tail.moveTowards(head)
visitedPlaces.add(tail.copy())
}
return visitedPlaces.size
}
fun part2(input: List<String>): Int {
val steps = input.toSteps()
val visitedPlaces = mutableSetOf<Position>()
val knots = (0 until 10).map { Position(10000, 10000) }
steps.forEach { step ->
when (step) {
Step.UP -> knots.first().y--
Step.DOWN -> knots.first().y++
Step.LEFT -> knots.first().x--
Step.RIGHT -> knots.first().x++
}
knots.forEachIndexed { index, position ->
if (index > 0) {
position.moveTowards(knots[index-1])
}
}
visitedPlaces.add(knots.last().copy())
}
return visitedPlaces.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))
}
private fun List<String>.toSteps(): List<Step> {
val result = mutableListOf<Step>()
this.forEach { line ->
val (direction, distance) = line.split(" ")
repeat(distance.toInt()) { result.add(Step.fromLetter(direction)) }
}
return result
}
private enum class Step {
UP, DOWN, LEFT, RIGHT;
companion object {
fun fromLetter(letter: String): Step {
return when (letter) {
"R" -> RIGHT
"L" -> LEFT
"U" -> UP
"D" -> DOWN
else -> throw IllegalArgumentException("Unknown step: $letter")
}
}
}
}
private data class Position(var x: Int, var y: Int) {
fun rangeTo(position: Position): Int {
return abs(x - position.x) + abs(y - position.y)
}
fun moveTowards(position: Position) {
if (rangeTo(position) > 2) {
if (x > position.x)
x--
else if (x < position.x)
x++
if (y > position.y)
y--
else if (y < position.y)
y++
} else if (x - position.x == 2) {
x--
} else if (x - position.x == -2) {
x++
} else if (y - position.y == 2) {
y--
} else if (y - position.y == -2) {
y++
}
}
} | 0 | Kotlin | 0 | 0 | a638356cda864b9e1799d72fa07d3482a5f2128e | 2,957 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/lesson1/BinaryGap.kt | iafsilva | 633,017,063 | false | null | package lesson1
/**
* A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
*
* For example:
* - The number 9 has binary representation 1001 and contains a binary gap of length 2.
* - The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3.
* - The number 20 has binary representation 10100 and contains one binary gap of length 1.
* - The number 15 has binary representation 1111 and has no binary gaps.
* - The number 32 has binary representation 100000 and has no binary gaps.
*
* Write a function:
*
* class Solution { public int solution(int N); }
*
* that, given a positive integer N, returns the length of its longest binary gap.
* The function should return 0 if N doesn't contain a binary gap.
*
* For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
* Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [1..2,147,483,647].
*/
class BinaryGap {
fun solution(n: Int): Int {
var longestBinaryGap = 0
var currentBinaryGap = 0
var isCounting = false
// Get binary representation
val binaryString = Integer.toBinaryString(n)
for (char in binaryString) {
when {
// If we were already counting means binary gap ended
char == '1' && isCounting -> {
if (currentBinaryGap > longestBinaryGap) {
longestBinaryGap = currentBinaryGap
}
currentBinaryGap = 0
}
// When finding a 1 start counting
char == '1' -> isCounting = true
// When counting -> increment our binary gap
char == '0' && isCounting -> currentBinaryGap++
}
}
return longestBinaryGap
}
}
| 0 | Kotlin | 0 | 0 | 5d86aefe70e9401d160c3d87c09a9bf98f6d7ab9 | 2,206 | codility-lessons | Apache License 2.0 |
src/problems/day5/part2/part2.kt | klnusbaum | 733,782,662 | false | {"Kotlin": 43060} | package problems.day5.part2
import java.io.File
import java.util.*
//const val testFile = "input/day5/test.txt"
const val inputFile = "input/day5/input.txt"
fun main() {
val lowestLocationNum = File(inputFile).bufferedReader().useLines { lowestLocationNumber(it) }
println("Lowest Location Num: $lowestLocationNum")
}
private fun lowestLocationNumber(lines: Sequence<String>): Long? {
val almanac = lines.fold(AlmanacBuilder()) { builder, line -> builder.nextLine(line) }.build()
for (i in 0..<Long.MAX_VALUE) {
if (almanac.locationHasSeed(i)) {
return i
}
}
return null
}
private class Almanac(val seeds: TreeMap<Long,Long>, val reverseMaps: Map<String, OverrideMap>) {
fun locationHasSeed(location: Long): Boolean {
val humidity = reverseMaps["humidity-to-location"]?.get(location) ?: return false
val temperature = reverseMaps["temperature-to-humidity"]?.get(humidity) ?: return false
val light = reverseMaps["light-to-temperature"]?.get(temperature) ?: return false
val water = reverseMaps["water-to-light"]?.get(light) ?: return false
val fertilizer = reverseMaps["fertilizer-to-water"]?.get(water) ?: return false
val soil = reverseMaps["soil-to-fertilizer"]?.get(fertilizer) ?: return false
val seed = reverseMaps["seed-to-soil"]?.get(soil) ?: return false
val floorSeed = seeds.floorEntry(seed) ?: return false
return floorSeed.key <= seed && seed <= floorSeed.value
}
}
private class AlmanacBuilder {
private var state = State.SEEDS
private var currentMapName = ""
private var currentMap = TreeMap<Long, Override>()
private val maps = mutableMapOf<String, OverrideMap>()
private val seeds = TreeMap<Long, Long>()
fun nextLine(line: String): AlmanacBuilder {
when (state) {
State.SEEDS -> {
seeds.putAll(line.toSeeds())
state = State.SEEDS_BLANK
}
State.SEEDS_BLANK -> state = State.HEADER
State.HEADER -> {
currentMapName = line.substringBefore(" ")
currentMap = TreeMap<Long, Override>()
state = State.MAP
}
State.MAP -> {
if (line != "") {
addOverride(line)
} else {
recordMap()
state = State.HEADER
}
}
}
return this
}
fun addOverride(line: String) {
val overrides = line.split(" ").map { it.toLong() }
val dstStart = overrides[0]
val dstEnd = overrides[0] + overrides[2] - 1
val srcStart = overrides[1]
currentMap[dstStart] = Override(dstStart, dstEnd, srcStart)
}
fun recordMap() {
maps[currentMapName] = OverrideMap(currentMap)
}
fun build(): Almanac {
if (state == State.MAP) {
recordMap()
}
return Almanac(seeds, maps)
}
private enum class State {
SEEDS,
SEEDS_BLANK,
HEADER,
MAP,
}
}
private fun String.toSeeds(): TreeMap<Long, Long> {
val seedRanges = TreeMap<Long,Long>()
val pairs = this.substringAfter(":").trim().split(" ").iterator()
while (pairs.hasNext()) {
val start = pairs.next().toLong()
val length = pairs.next().toLong()
seedRanges[start] = start+length-1
}
return seedRanges
}
private class OverrideMap(val overrides: TreeMap<Long, Override>) {
operator fun get(key: Long): Long {
val possibleOverride = overrides.headMap(key, true).lastEntry()?.value ?: return key
if (key <= possibleOverride.dstEnd) {
return possibleOverride.srcStart + (key - possibleOverride.dstStart)
}
return key
}
}
private data class Override(val dstStart: Long, val dstEnd: Long, val srcStart: Long) | 0 | Kotlin | 0 | 0 | d30db2441acfc5b12b52b4d56f6dee9247a6f3ed | 3,925 | aoc2023 | MIT License |
src/day01/Day01.kt | benjaminknauer | 574,102,077 | false | {"Kotlin": 6414} | package day01
import java.io.File
data class Sweet(val calories: Int)
data class Elf(val sweets: List<Sweet>) {
fun getCaloriesSum(): Int {
return sweets.sumOf { it.calories }
}
}
fun parseInput(input: String): List<Elf> {
return input.split("\n\n")
.map { elf ->
val sweets = elf.split("\n")
.map { it.toInt() }
.map { Sweet(it) }
.toList()
Elf(sweets)
}
}
fun getCaloriesOfTopNElves(elves: List<Elf>, n: Int): Int {
val elvesSortedByCalories = elves
.sortedByDescending { it.getCaloriesSum() }
return elvesSortedByCalories
.take(n)
.sumOf { it.getCaloriesSum() }
}
fun part1(input: String): Int {
val elves = parseInput(input)
return getCaloriesOfTopNElves(elves, 1)
}
fun part2(input: String): Int {
val elves = parseInput(input)
return getCaloriesOfTopNElves(elves, 3)
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = File("src/day01/Day01_test.txt").readText()
check(part1(testInput) == 24000)
val input = File("src/day01/Day01.txt").readText()
println("Result Part 1: %s".format(part1(input)))
println("Result Part 2: %s".format(part2(input)))
}
| 0 | Kotlin | 0 | 0 | fcf41bed56884d777ff1f95eddbecc5d8ef731d1 | 1,295 | advent-of-code-22-kotlin | Apache License 2.0 |
src/Day09.kt | kipwoker | 572,884,607 | false | null | import kotlin.math.abs
class Command(val direction: Direction, val count: Int)
fun main() {
fun parse(input: List<String>): List<Command> {
return input.map { line ->
val parts = line.split(' ')
val direction = when (parts[0]) {
"U" -> Direction.Up
"D" -> Direction.Down
"L" -> Direction.Left
"R" -> Direction.Right
else -> throw RuntimeException()
}
Command(direction, parts[1].toInt())
}
}
fun move(point: Point, direction: Direction): Point {
return when (direction) {
Direction.Up -> Point(point.x, point.y + 1)
Direction.Down -> Point(point.x, point.y - 1)
Direction.Left -> Point(point.x - 1, point.y)
Direction.Right -> Point(point.x + 1, point.y)
}
}
fun isTouching(head: Point, tail: Point): Boolean {
return abs(head.x - tail.x) <= 1 && abs(head.y - tail.y) <= 1
}
fun getDelta(head: Int, tail: Int): Int {
if (head == tail) {
return 0
}
if (head > tail) {
return 1
}
return -1
}
fun tryMoveTail(head: Point, tail: Point): Point {
if (isTouching(head, tail)) {
return tail
}
val dx = getDelta(head.x, tail.x)
val dy = getDelta(head.y, tail.y)
return Point(tail.x + dx, tail.y + dy)
}
fun traverse(commands: List<Command>, totalSize: Int): Int {
val visited = mutableSetOf<Point>()
var head = Point(0, 0)
val size = totalSize - 2
val middle = (1..size).map { Point(0, 0) }.toMutableList()
var tail = Point(0, 0)
visited.add(tail)
for (command in commands) {
for (i in 1..command.count) {
head = move(head, command.direction)
var pointer = head
for (j in 0 until size) {
middle[j] = tryMoveTail(pointer, middle[j])
pointer = middle[j]
}
tail = tryMoveTail(pointer, tail)
visited.add(tail)
}
}
return visited.count()
}
fun part1(input: List<String>): Int {
val commands = parse(input)
return traverse(commands, 2)
}
fun part2(input: List<String>): Int {
val commands = parse(input)
return traverse(commands, 10)
}
val testInput = readInput("Day09_test")
assert(part1(testInput), 13)
assert(part2(testInput), 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 2,696 | aoc2022 | Apache License 2.0 |
src/day12/Day12.kt | GrzegorzBaczek93 | 572,128,118 | false | {"Kotlin": 44027} | package day12
import readInput
import utils.withStopwatch
import java.util.LinkedList
fun main() {
val testInput = readInput("input12_test")
withStopwatch { println(part1(testInput)) }
withStopwatch { println(part2(testInput)) }
val input = readInput("input12")
withStopwatch { println(part1(input)) }
withStopwatch { println(part2(input)) }
}
private fun part1(input: List<String>) = solve1(input)
private fun part2(input: List<String>) = solve2(input)
private fun solve1(input: List<String>): Int {
val graph = Graph(input)
val startNode = graph.getStartNode()
val endNode = graph.getEndNode()
return calculateBFS(startNode, endNode)?.size ?: -1
}
private fun solve2(input: List<String>): Int {
val graph = Graph(input)
val startNodes = graph.getNodes(1)
val endNode = graph.getEndNode()
return startNodes.mapNotNull {
calculateBFS(it, endNode).also { graph.clearNodes() }?.size
}.min()
}
private fun calculateBFS(startNode: Node, endNode: Node): List<Node>? {
val queue = LinkedList<Node>()
val visitedNodes = mutableSetOf<Node>()
visitedNodes.add(startNode)
queue.add(startNode)
while (queue.isNotEmpty()) {
val currentNode = queue.poll()
if (currentNode == endNode) {
val path = mutableListOf<Node>()
var current: Node? = currentNode
while (current != null) {
path.add(current)
current = current.parent
}
return path.reversed()
}
currentNode.edges.forEach { edge ->
if (!visitedNodes.contains(edge)) {
visitedNodes.add(edge)
queue.add(edge)
edge.parent = currentNode
}
}
}
return null
}
| 0 | Kotlin | 0 | 0 | 543e7cf0a2d706d23c3213d3737756b61ccbf94b | 1,806 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day9/day9.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day9
import lib.Point2D
import readInput
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.sign
fun main() {
val day = 9
val testInput = readInput("day$day/testInput")
check(part1(testInput) == 13)
val input = readInput("day$day/input")
println(part1(input))
println(part2(input))
}
fun getMoves(input: List<String>): List<Pair<Char, Int>> {
return input.map {
val (dir, moveSize) = it.split(" ")
Pair(dir.first(), moveSize.toInt())
}
}
fun part1(input: List<String>): Int {
return followHead(2, getMoves(input))
}
fun part2(input: List<String>): Int {
return followHead(10, getMoves(input))
}
fun Point2D.updateHead(dir: Char): Point2D {
return when (dir) {
'R' -> toRight()
'L' -> toLeft()
'U' -> higher()
'D' -> lower()
else -> error("Invalid direction")
}
}
fun Point2D.isAdjacent(p: Point2D): Boolean {
return this.distanceTo(p) < 1.5
}
fun Point2D.follow(f: Point2D): Point2D {
return Point2D(
x + sign(f.x - x.toDouble()).toInt() * min(abs(f.x - x), 1),
y + sign(f.y - y.toDouble()).toInt() * min(abs(f.y - y), 1)
)
}
fun followHead(ropeSize: Int, moves: List<Pair<Char, Int>>): Int {
val rope = MutableList(ropeSize) { Point2D(0, 0) }
val tailPoints = hashSetOf<Point2D>().apply {
add(rope.last())
}
for ((dir, steps) in moves) {
repeat(steps) {
rope[0] = rope[0].updateHead(dir)
for (i in 1 until ropeSize) {
if (!rope[i].isAdjacent(rope[i - 1])) {
rope[i] = rope[i].follow(rope[i - 1])
if (i == ropeSize - 1) {
tailPoints.add(rope.last())
}
} else {
break
}
}
}
}
return tailPoints.size
} | 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 1,904 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day19/day19.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day19
import biz.koziolek.adventofcode.findInput
fun main() {
val inputFile = findInput(object {})
val xmasSystem = parseXmasSystem(inputFile.bufferedReader().readLines())
val acceptedParts = xmasSystem.runWorkflows()
println("Sum of accepted parts: ${acceptedParts.sumOf { it.propsSum }}")
println("Sum of ALL accepted parts: ${xmasSystem.countAllAccepted()}")
}
data class XmasSystem(val workflows: List<XmasWorkflow>,
val parts: List<MachinePart>) {
private val startingWorkflow = findWorkflow("in")
private fun findWorkflow(name: String) = workflows.single { it.name == name }
fun runWorkflows(): List<MachinePart> =
parts.filter { isAccepted(it) }
private fun isAccepted(machinePart: MachinePart): Boolean {
var workflow = startingWorkflow
while (true) {
val rule = workflow.matches(machinePart)
when {
rule.isAccepted() -> return true
rule.isRejected() -> return false
else -> workflow = findWorkflow(rule.destination)
}
}
}
fun countAllAccepted(): Long {
var accepted = 0L
var rejected = 0L
var checked = 0L
val toCheck = mutableListOf<Pair<QuantumMachinePart, XmasWorkflow>>()
toCheck.add(
QuantumMachinePart(
x = 1..4000,
m = 1..4000,
a = 1..4000,
s = 1..4000,
) to startingWorkflow
)
while (toCheck.isNotEmpty()) {
checked++
val (part, workflow) = toCheck.removeFirst()
for (processedPart in workflow.process(part)) {
when {
processedPart.rule.isAccepted() -> accepted += processedPart.part.propsSum
processedPart.rule.isRejected() -> rejected += processedPart.part.propsSum
else -> toCheck.add(processedPart.part to findWorkflow(processedPart.rule.destination))
}
}
}
val total = accepted + rejected
println("Checked $checked for total of $total of which $accepted (${accepted * 100 / total}%) were accepted")
return accepted
}
}
data class XmasWorkflow(val name: String, val rules: List<XmasRule>) {
fun matches(machinePart: MachinePart): XmasRule =
rules.first { it.matches(machinePart) }
fun process(machinePart: QuantumMachinePart, debug: Boolean = false): List<MatchedQuantumPart> {
if (debug) println("Workflow $name:")
val processedParts = mutableListOf<MatchedQuantumPart>()
var pendingParts = listOf(machinePart)
for (rule in rules) {
val newPendingParts = mutableListOf<QuantumMachinePart>()
for (part in pendingParts) {
if (debug) println(" $part + $rule =")
for (processedPart in rule.process(part)) {
if (debug) println(" ${processedPart::class.simpleName} & ${processedPart.part}")
when (processedPart) {
is MatchedQuantumPart -> processedParts.add(processedPart)
is NotMatchedQuantumPart -> newPendingParts.add(processedPart.part)
}
}
}
pendingParts = newPendingParts
}
return processedParts
}
}
sealed interface XmasRule {
val destination: String
fun isAccepted() = destination == "A"
fun isRejected() = destination == "R"
fun matches(machinePart: MachinePart): Boolean
fun process(machinePart: QuantumMachinePart): List<ProcessedQuantumPart>
}
sealed interface ProcessedQuantumPart {
val part: QuantumMachinePart
}
data class MatchedQuantumPart(override val part: QuantumMachinePart, val rule: XmasRule) : ProcessedQuantumPart
data class NotMatchedQuantumPart(override val part: QuantumMachinePart) : ProcessedQuantumPart
data class ConditionalXmasRule(val property: Char,
val operator: Char,
val value: Int,
override val destination: String) : XmasRule {
override fun matches(machinePart: MachinePart): Boolean {
val partValue = machinePart.getProperty(property)
return when (operator) {
'>' -> partValue > value
'<' -> partValue < value
else -> throw IllegalArgumentException("Unexpected operator: $operator")
}
}
override fun process(machinePart: QuantumMachinePart): List<ProcessedQuantumPart> {
val valuesToCheck = machinePart.getProperty(property)
return when {
value in valuesToCheck ->
when (operator) {
'<' -> listOf(
MatchedQuantumPart(machinePart.copy(property, valuesToCheck.first..<value), this),
NotMatchedQuantumPart(machinePart.copy(property, value..valuesToCheck.last)),
)
'>' -> listOf(
NotMatchedQuantumPart(machinePart.copy(property, valuesToCheck.first..value)),
MatchedQuantumPart(machinePart.copy(property, value+1..valuesToCheck.last), this),
)
else -> throw IllegalArgumentException("Unexpected operator: $operator")
}
(operator == '<' && valuesToCheck.last < value) || (operator == '>' && valuesToCheck.first > value) ->
listOf(MatchedQuantumPart(machinePart, this))
else -> listOf(NotMatchedQuantumPart(machinePart))
}
}
override fun toString() = "Conditional{$property $operator $value -> $destination}"
}
data class DefaultXmasRule(override val destination: String) : XmasRule {
override fun matches(machinePart: MachinePart) = true
override fun process(machinePart: QuantumMachinePart): List<MatchedQuantumPart> =
listOf(MatchedQuantumPart(machinePart, this))
override fun toString() = "Always{-> $destination}"
}
data class MachinePart(val x: Int, val m: Int, val a: Int, val s: Int) {
val propsSum = x + m + a + s
fun getProperty(name: Char) =
when (name) {
'x' -> x
'm' -> m
'a' -> a
's' -> s
else -> throw IllegalArgumentException("Unexpected property: $name")
}
override fun toString() = "{x=$x,m=$m,a=$a,s=$s}"
}
data class QuantumMachinePart(val x: IntRange, val m: IntRange, val a: IntRange, val s: IntRange) {
val propsSum = x.count().toLong() * m.count().toLong() * a.count().toLong() * s.count().toLong()
fun getProperty(name: Char) =
when (name) {
'x' -> x
'm' -> m
'a' -> a
's' -> s
else -> throw IllegalArgumentException("Unexpected property: $name")
}
fun copy(property: Char, newValues: IntRange): QuantumMachinePart =
when (property) {
'x' -> copy(x = newValues)
'm' -> copy(m = newValues)
'a' -> copy(a = newValues)
's' -> copy(s = newValues)
else -> throw IllegalArgumentException("Unexpected property: $property")
}
override fun toString() = "{x=$x,m=$m,a=$a,s=$s}"
}
private fun IntRange.count(): Int {
return last - first + 1
}
fun parseXmasSystem(lines: Iterable<String>): XmasSystem {
val workflows = lines
.takeWhile { line -> line.isNotBlank() }
.map { line ->
val (name, rulesStr, _) = line.split('{', '}')
XmasWorkflow(
name = name,
rules = Regex("(([xmas])([<>])([0-9]+):)?([a-z]+|A|R)").findAll(rulesStr)
.map { match ->
if (match.groups[1]?.value != null) {
ConditionalXmasRule(
property = match.groups[2]!!.value.single(),
operator = match.groups[3]!!.value.single(),
value = match.groups[4]!!.value.toInt(),
destination = match.groups[5]!!.value,
)
} else {
DefaultXmasRule(
destination = match.groups[5]!!.value,
)
}
}
.toList()
)
}
val parts = lines
.dropWhile { line -> line.isNotBlank() }
.drop(1)
.mapNotNull { line ->
Regex("\\{x=([0-9]+),m=([0-9]+),a=([0-9]+),s=([0-9]+)}")
.find(line)
?.let { match ->
MachinePart(
x = match.groups[1]!!.value.toInt(),
m = match.groups[2]!!.value.toInt(),
a = match.groups[3]!!.value.toInt(),
s = match.groups[4]!!.value.toInt(),
)
}
}
return XmasSystem(workflows, parts)
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 9,195 | advent-of-code | MIT License |
src/Day13.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | fun main() {
data class Node(
var single: Int? = null,
var list: List<Node>? = null,
) : Comparable<Node> {
fun compare(a: List<Node>, b: List<Node>): Int {
for (i in 0 until minOf(a.size, b.size)) {
val c = a[i].compareTo(b[i])
if (c != 0) return c
}
return a.size.compareTo(b.size)
}
override fun compareTo(other: Node): Int {
if (single != null && other.single != null) return single!!.compareTo(other.single!!)
val a = list ?: listOf(Node(single = single))
val b = other.list ?: listOf(Node(single = other.single))
return compare(a, b)
}
override fun toString(): String {
return if (single != null) single.toString() else list!!.joinToString(",", "[", "]")
}
}
fun parse(a: String): Node {
var at = 0
fun parse(): Node {
val result = if (a[at] == '[') {
at++
val list = mutableListOf<Node>()
while (a[at] != ']') {
list += parse()
if (a[at] == ',') at++
}
Node(list = list).also { at++ }
} else {
var x = 0
while (a[at].isDigit()) {
x = x * 10 + a[at++].digitToInt()
}
Node(single = x)
}
return result
}
return parse().also { require(at == a.length) }
}
fun compare(a: String, b: String): Int {
val s = parse(a)
val t = parse(b)
return s.compareTo(t)
}
fun part1(input: List<String>): Int {
var cnt = 0
for (i in input.indices step 3) {
if (compare(input[i], input[i + 1]) <= 0) {
cnt += i / 3 + 1
}
}
return cnt
}
fun part2(input: List<String>): Int {
val a = mutableListOf<Node>()
for (i in input.indices step 3) {
a += parse(input[i])
a += parse(input[i + 1])
}
val n2 = parse("[[2]]")
val n6 = parse("[[6]]")
a += n2
a += n6
a.sort()
return (a.indexOf(n2) + 1) * (a.indexOf(n6) + 1)
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 13)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 2,729 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/leetcode/P980.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/467
class P980 {
fun uniquePathsIII(grid: Array<IntArray>): Int {
var y = 0
var x = 0
var total = 0 // 갈 수 있는 남은 칸 수
for (i in grid.indices) {
for (j in grid[i].indices) {
val v = grid[i][j]
if (v == 0) { // 이동 가능 칸
total++
} else if (v == 1) { // 출발 칸
y = i
x = j
// 시작 지점을 갈 수 있는 블럭으로 처리
grid[y][x] = 0
total++
}
}
}
return dfs(grid, y, x, total)
}
private fun dfs(grid: Array<IntArray>, y: Int, x: Int, remain: Int): Int {
if (y < 0 || y >= grid.size
|| x < 0 || x >= grid[y].size
|| grid[y][x] == -1 // 벽
) {
return 0
}
// 도착
if (grid[y][x] == 2) {
// 남아있는 칸이 없어야 함
return if (remain == 0) 1 else 0
}
grid[y][x] = -1 // visited
val r = remain - 1
val sum = dfs(grid, y - 1, x, r) + // 북
dfs(grid, y, x + 1, r) + // 동
dfs(grid, y + 1, x, r) + // 남
dfs(grid, y, x - 1, r) // 서
grid[y][x] = 0 // backtracking
return sum
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,462 | algorithm | MIT License |
src/Day05.kt | rbraeunlich | 573,282,138 | false | {"Kotlin": 63724} | import java.util.Stack
fun main() {
fun parseCrates(input: List<String>): List<MutableList<String>> {
val stacks = mutableListOf<MutableList<String>>()
for (line in input) {
if (line.isEmpty()) {
break;
} else {
line.chunked(4).forEachIndexed { index, s ->
if (stacks.getOrNull(index) == null) {
stacks.add(index, mutableListOf())
}
if (s.isEmpty() || !s.contains("[")) {
// do nothing
} else {
stacks[index].add(s.replace("[", "").replace("]", "").trim())
}
}
}
}
return stacks
}
fun parseMoves(input: List<String>): List<Move> {
val moves = mutableListOf<Move>()
var hasSeenEmptyLine = false
for (line in input) {
if (line.isEmpty()) {
hasSeenEmptyLine = true
continue
} else if (!hasSeenEmptyLine) {
continue
} else {
val split = line.split(" ")
val amount = split[1].toInt()
val from = split[3].toInt()
val to = split[5].toInt()
moves.add(Move(amount, from, to))
}
}
return moves
}
fun applyMoves(crates: List<MutableList<String>>, moves: List<Move>) {
moves.forEach { move ->
(1..move.amount).forEach {
val source = crates[move.from - 1]
val destination = crates[move.to - 1]
destination.add(0, source.removeFirst())
}
}
}
fun part1(input: List<String>): String {
val crates: List<MutableList<String>> = parseCrates(input)
println(crates)
val moves = parseMoves(input)
applyMoves(crates, moves)
return crates.map { it.first() }.joinToString(separator = "")
}
fun applyMoves2(crates: List<MutableList<String>>, moves: List<Move>) {
moves.forEach { move ->
val source = crates[move.from - 1]
val destination = crates[move.to - 1]
val toMove = source.take(move.amount)
(1..move.amount).forEach { source.removeFirst() }
destination.addAll(0, toMove)
}
}
fun part2(input: List<String>): String {
val crates: List<MutableList<String>> = parseCrates(input)
println(crates)
val moves = parseMoves(input)
applyMoves2(crates, moves)
return crates.map { it.first() }.joinToString(separator = "")
}
// 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))
}
data class Move(val amount: Int, val from: Int, val to: Int)
| 0 | Kotlin | 0 | 1 | 3c7e46ddfb933281be34e58933b84870c6607acd | 3,038 | advent-of-code-2022 | Apache License 2.0 |
src/day02/Day02.kt | TheRishka | 573,352,778 | false | {"Kotlin": 29720} | package day02
import readInput
fun main() {
val shapeScore = mapOf(
'X' to 1, // Rock
'Y' to 2, // Paper
'Z' to 3 // Scissors
)
val winMap = mapOf(
'A' to 'Y', // Rock <-- Paper WIN
'B' to 'Z', // Paper <-- Scissors WIN
'C' to 'X' // Scissors <-- Rock WIN
)
val drawMap = mapOf(
'A' to 'X', // Rock <-- Rock DRAW
'B' to 'Y', // Paper <-- Paper DRAW
'C' to 'Z' // Scissors <-- Scissors DRAW
)
/**
* X means you need to lose,
* Y means you need to end the round in a draw,
* Z means you need to win. Good luck!"
*/
val doIneedToWinMap = mapOf(
'X' to -1, // I need to loose
'Y' to 0, // I need to draw
'Z' to 1 // I need to win
)
val loseMap = mapOf(
'A' to 'Z', // Rock <-- Scissors LOOSE
'B' to 'X', // Paper <-- Rock LOOSE
'C' to 'Y' // Scissors <-- Paper LOOSE
)
fun calculateMatchScore(inputOpponent: Char, inputSelf: Char): Int {
// 0 lose, 6 win, 3 draw
val winChar = winMap[inputOpponent]!!
val drawChar = drawMap[inputOpponent]!!
val shape = shapeScore[inputSelf]!!
return when (inputSelf) {
winChar -> {
// win
6 + shape
}
drawChar -> {
// draw
3 + shape
}
else -> shape // lose
}
}
fun part1(input: List<String>): Int {
return input.fold(0) { total, strategyMapValues ->
total + calculateMatchScore(strategyMapValues.first(), strategyMapValues.last())
}
}
fun part2(input: List<String>): Int {
return input.fold(0) { total, strategyMapValues ->
val myInput = strategyMapValues.last()
val enemyInput = strategyMapValues.first()
val myInputAccordingToPlan = when (doIneedToWinMap[myInput]!!) {
1 -> {
// win
winMap[enemyInput]
}
-1 -> {
// lose
loseMap[enemyInput]
}
0 -> {
// draw
drawMap[enemyInput]
}
else -> 'X'
}
total + calculateMatchScore(strategyMapValues.first(), myInputAccordingToPlan!!)
}
}
val input = readInput("day02/Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 54c6abe68c4867207b37e9798e1fdcf264e38658 | 2,533 | AOC2022-Kotlin | Apache License 2.0 |
src/Day05.kt | aneroid | 572,802,061 | false | {"Kotlin": 27313} | private data class Move(val howMany: Int, val fromStack: Int, val toStack: Int)
class Day05(input: List<List<String>>) {
private val stacks = getStacks(input.first().dropLast(1).reversed())
private val moves = input.last().mapNotNull(::extractMove)
private fun getStacks(stacksText: List<String>): MutableList<MutableList<Char>> {
val stacks = MutableList(stacksText.first().length.plus(1) / 4) { mutableListOf<Char>() }
stacksText.flatMap(::extractStackLine)
.onEach { (idx, char) ->
stacks[idx].add(char)
}
println("stacks start: $stacks")
return stacks
}
private fun extractStackLine(line: String) =
line
.withIndex()
.filter { it.value in 'A'..'Z' }
.map { (it.index - 1) / 4 to it.value }
private fun extractMove(line: String) =
line.takeIf(String::isNotBlank)?.run {
Move(
line.substringAfter(" ").substringBefore(" ").toInt(),
line.substringAfter("from ").substringBefore(" ").toInt() - 1,
line.substringAfter("to ").toInt() - 1,
)
}
private fun List<List<Char>>.allTops(): List<Char> {
return map { it.last() }.also { println("final stacks: ${it.joinToString("")}") }
}
private fun MutableList<MutableList<Char>>.doMove(move: Move, withReversal: Boolean = false) {
this[move.toStack].addAll(this[move.fromStack].takeLast(move.howMany).withReversal(withReversal))
repeat(move.howMany) {
this[move.fromStack].removeLast()
}
}
private fun <T> Iterable<T>.withReversal(reverse: Boolean) =
if (reverse) reversed() else this.toList() // consistently a copy
fun partOne(): List<Char> {
moves.forEach { move -> stacks.doMove(move, true) }
return stacks.allTops()
}
fun partTwo(): List<Char> {
moves.forEach { move -> stacks.doMove(move) }
return stacks.allTops()
}
}
fun main() {
val testInput = readInputBlocks("Day05_test")
val input = readInputBlocks("Day05")
println("part One:")
assertThat(Day05(testInput).partOne()).isEqualTo("CMZ".toList())
println("actual: ${Day05(input).partOne()}\n")
println("part Two:")
assertThat(Day05(testInput).partTwo()).isEqualTo("MCD".toList()) // uncomment when ready
println("actual: ${Day05(input).partTwo()}\n") // uncomment when ready
}
| 0 | Kotlin | 0 | 0 | cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd | 2,524 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day10.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | import kotlin.streams.toList
fun main() {
fun part1(input: List<List<Char>>): Int {
val stk = ArrayDeque<Char>()
val open = listOf('(', '[', '{', '<')
val close = listOf(')', ']', '}', '>')
val scores = mapOf(
Pair(')', 3),
Pair(']', 57),
Pair('}', 1197),
Pair('>', 25137),
)
var out = 0
for (l in input) {
for (c in l) {
if (open.contains(c)){
stk.add(c)
} else {
if (open.indexOf(stk.removeLast()) == close.indexOf(c)) continue
out += scores[c]!!
break
}
}
stk.clear()
}
return out
}
fun part2(input: List<List<Char>>): Long {
val open = listOf('(', '[', '{', '<')
val close = listOf(')', ']', '}', '>')
val scores = mapOf(
Pair('(', 1),
Pair('[', 2),
Pair('{', 3),
Pair('<', 4),
)
val results = mutableListOf<Long>()
for (l in input) {
var out: Long = 0
val stk = ArrayDeque<Char>()
var broken = false
for (c in l) {
if (open.contains(c)){
stk.add(c)
} else {
if (open.indexOf(stk.removeLast()) == close.indexOf(c)) continue
broken = true
break
}
}
if (broken) continue
for (c in stk.reversed()){
out *= 5
out += scores[c]!!
}
results.add(out)
}
return results.sorted()[results.size/2]
}
fun preprocessing(input: String): List<List<Char>> {
return input.trim().split("\n").map { it.trim().toCharArray().toList() }.toList()
}
val realInp = read_testInput("real10")
val testInp = read_testInput("test10")
// val testInp = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
// println("Test 1: ${part1(preprocessing(testInp))}")
// println("Real 1: ${part1(preprocessing(realInp))}")
println("-----------")
println("Test 2: ${part2(preprocessing(testInp))}")
println("Real 2: ${part2(preprocessing(realInp))}")
}
| 0 | Kotlin | 0 | 0 | 3e33ab078f8f5413fa659ec6c169cd2f99d0b374 | 2,391 | advent_of_code21_kotlin | Apache License 2.0 |
Bootcamp_00/src/exercise5/src/main/kotlin/Main.kt | Hasuk1 | 740,111,124 | false | {"Kotlin": 120039} | import kotlin.math.*
fun main() {
val x1 = readCoordinate("Input x1:")
val y1 = readCoordinate("Input y1:")
val r1 = readRadius("Input r1:")
val x2 = readCoordinate("Input x2:")
val y2 = readCoordinate("Input y2:")
val r2 = readRadius("Input r2:")
val distance = sqrt((x2 - x1).pow(2) + (y2 - y1).pow(2))
when {
distance < r1 - r2 -> println("Result: circle 2 is inside circle 1")
distance < r2 - r1 -> println("Result: circle 1 is inside circle 2")
distance <= r1 + r2 -> {
if (distance < r1 + r2) {
try {
val intersectionPoints = calculateIntersectionPoints(x1, y1, r1, x2, y2, r2)
println("Result: the circles intersect")
intersectionPoints.forEach { point ->
println("Intersection point: (${"%.6f".format(point.first)}, ${"%.6f".format(point.second)})")
}
} catch (e: IllegalArgumentException) {
println("Circles do not touch or intersect.")
}
} else {
println("Result: the circles touch each other")
val touchPoint = calculateTouchPoint(x1, y1, r1, x2, y2)
println("Touch point: (${"%.6f".format(touchPoint.first)}, ${"%.6f".format(touchPoint.second)})")
}
}
distance > r1 + r2 -> println("Result: the circles do not intersect")
else -> println("Result: unexpected case")
}
}
fun calculateIntersectionPoints(
x1: Double, y1: Double, r1: Double,
x2: Double, y2: Double, r2: Double
): List<Pair<Double, Double>> {
val d = sqrt((x2 - x1).pow(2) + (y2 - y1).pow(2))
if (d == 0.0 && r1 == r2) throw IllegalArgumentException("Infinite touch points for coincident circles.")
val alpha = atan2(y2 - y1, x2 - x1)
val beta = acos((r1.pow(2) + d.pow(2) - r2.pow(2)) / (2 * r1 * d))
val xA = x1 + r1 * cos(alpha - beta)
val yA = y1 + r1 * sin(alpha - beta)
val xB = x1 + r1 * cos(alpha + beta)
val yB = y1 + r1 * sin(alpha + beta)
return listOf(xA to yA, xB to yB)
}
fun calculateTouchPoint(
x1: Double, y1: Double, r1: Double,
x2: Double, y2: Double
): Pair<Double, Double> {
val d = sqrt((x2 - x1).pow(2) + (y2 - y1).pow(2))
val touchX = x1 + (r1 * (x2 - x1)) / d
val touchY = y1 + (r1 * (y2 - y1)) / d
return touchX to touchY
}
| 0 | Kotlin | 0 | 1 | 1dc4de50dd3cd875e3fe76e3da4a58aa04bb87c7 | 2,237 | Kotlin_bootcamp | MIT License |
src/Day02.kt | henryjcee | 573,492,716 | false | {"Kotlin": 2217} | fun main() {
val mapping = mapOf(
"A" to 0,
"B" to 1,
"C" to 2,
"X" to 0,
"Y" to 1,
"Z" to 2,
)
fun score(theirs: Int, mine: Int) = mine + 1 + ((mine - theirs).mod(3) + 1) % 3 * 3
fun score2(theirs: Int, mine: Int) = (theirs - 1 + mine).mod(3) + 1 + (mine * 3)
fun part1(input: List<String>) = input.sumOf {
it
.split(" ")
.let { score(mapping[it[0]]!!, mapping[it[1]]!!) }
}
fun part2(input: List<String>) = input.sumOf {
it
.split(" ")
.let { score2(mapping[it[0]]!!, mapping[it[1]]!!) }
}
val testInput = readInput("Day02_test")
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2fde9f3db7454583ac9c47cfca524cfa6a16eb61 | 810 | aoc-2022 | Apache License 2.0 |
Coding Challenges/Advent of Code/2021/Day 5/part2.kt | Alphabeater | 435,048,407 | false | {"Kotlin": 69566, "Python": 5974} | import java.io.File
import java.util.*
import kotlin.math.abs
const val DIM = 1000
var m = Array(DIM) { IntArray(DIM) { 0 } }
fun rangeMinMax (x: Int, y: Int) = minOf(x, y)..maxOf(x, y)
fun fillMatrix(s: String) {
val n = s.split(" -> ")
val (x1, y1) = n[0].split(',').map { it.toInt() }
val (x2, y2) = n[1].split(',').map { it.toInt() }
if (x1 == x2) { //vertical
for (i in rangeMinMax(y1, y2)) {
m[x1][i]++
}
}
if (y1 == y2) { //horizontal
for (i in rangeMinMax(x1, x2)) {
m[i][y1]++
}
}
if (abs(y2 - y1) == abs(x2 - x1)) { //diagonal
val xPos = x1 < x2 //if x should increase or not
val yPos = y1 < y2 //same for y
for (i in 0 .. abs(y2 - y1)) {
if (xPos) { if (yPos) m[x1 + i][y1 + i]++ else m[x1 + i][y1 - i]++ }
else { if (yPos) m[x1 - i][y1 + i]++ else m[x1 - i][y1 - i]++ }
}
}
}
fun countMatrix(): Int {
var count = 0
for (i in 0 until DIM)
for (j in 0 until DIM)
if (m[i][j] > 1) count++
return count
}
/*fun printMatrix() { //test for lidl matrix
for (i in 0 until 10) {
for (j in 0 until 10) {
print(if (m[j][i] == 0) ". "
else "${m[j][i]} ")
}
println()
}
}*/
fun main() {
val file = File("src/input.txt")
val scanner = Scanner(file)
while(scanner.hasNext()) {
fillMatrix(scanner.nextLine())
}
println(countMatrix())
}
| 0 | Kotlin | 0 | 0 | 05c8d4614e025ed2f26fef2e5b1581630201adf0 | 1,509 | Archive | MIT License |
src/Day05.kt | zodiia | 573,067,225 | false | {"Kotlin": 11268} | typealias Stacks = ArrayList<ArrayDeque<Char>>
fun main() {
fun getStacks(input: List<String>): Stacks {
val lines = input.subList(0, input.indexOf("")).dropLast(1).map { it.filterIndexed { idx, _ -> idx % 4 == 1 } }
val stacks = Stacks()
lines.last().forEach { _ -> stacks.add(ArrayDeque()) }
lines.forEach { line -> line.forEachIndexed { idx, ch -> if (ch != ' ') stacks[idx].addLast(ch) } }
return stacks
}
fun applyMovesToStacks(stacks: Stacks, input: List<String>, retainOrder: Boolean): Stacks {
input.subList(input.indexOf("") + 1, input.size).forEach { line ->
val parts = line.split(' ')
val tempStack = ArrayDeque<Char>()
val (amount, from, to) = Triple(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1)
for (i in 1..amount) {
tempStack.addLast(stacks[from].removeFirst())
}
tempStack.apply { if (retainOrder) reverse() }.forEach { stacks[to].addFirst(it) }
}
return stacks
}
fun part1(input: List<String>) =
applyMovesToStacks(getStacks(input), input, false).map { it.first() }.joinToString("")
fun part2(input: List<String>) =
applyMovesToStacks(getStacks(input), input, true).map { it.first() }.joinToString("")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 4f978c50bb7603adb9ff8a2f0280f8fdbc652bf2 | 1,425 | aoc-2022 | Apache License 2.0 |
src/main/java/io/github/lunarwatcher/aoc/day3/Day3.kt | LunarWatcher | 160,042,659 | false | null | package io.github.lunarwatcher.aoc.day3
import io.github.lunarwatcher.aoc.commons.readFile
fun day3(part: Boolean = false){
val rawObjects = readFile("day3.txt")
val res = if(!part) day3part1processor(rawObjects) else day3part2processor(rawObjects)
println(res)
}
fun day3part1processor(rawObjects: List<String>) : Int {
val map: MutableMap<Int, MutableMap<Int, Int>> = mutableMapOf()
rawObjects.forEach {
val spaces = it.split(" ").map { it.replace("[@#:]".toRegex(), "")}.filter { !it.isEmpty() && !it.isBlank()}
val id = spaces[0].toInt()
val xy = spaces[1].split(",")
val x = xy[0].toInt()
val y = xy[1].toInt()
val wh = spaces[2].split("x")
val w = wh[0].toInt()
val h = wh[1].toInt()
for(i in x until (x + w)){
if(map[i] == null) map[i] = mutableMapOf()
for(j in y until (y + h)){
if(map[i]!![j] == null){
map[i]!![j] = id
}else {
map[i]!![j] = -1;
}
}
}
}
return map.map { (_, child) ->
child.map { (k, v) -> v}.filter { it == -1 }.count()
}.filter { it != 0}.sum()
}
fun day3part2processor(rawObjects: List<String>) : Int {
// <X, <Y, <ID>>>
val map: MutableMap<Int, MutableMap<Int, MutableList<Int>>> = mutableMapOf()
rawObjects.forEach {
val spaces = it.split(" ").map { it.replace("[@#:]".toRegex(), "")}.filter { !it.isEmpty() && !it.isBlank()}
val id = spaces[0].toInt()
val xy = spaces[1].split(",")
val x = xy[0].toInt()
val y = xy[1].toInt()
val wh = spaces[2].split("x")
val w = wh[0].toInt()
val h = wh[1].toInt()
for(i in x until (x + w)){
if(map[i] == null) map[i] = mutableMapOf()
for(j in y until (y + h)){
if(map[i]!![j] == null){
map[i]!![j] = mutableListOf()
}
map[i]!![j]!!.add(id)
}
}
}
val badIds = mutableListOf<Int>()
val r = map.map { (x, child) ->
x to child.map { (y, ids) ->
y to if (ids.size == 1 && ids[0] !in badIds) ids[0] else {
for (id in ids) if (id !in badIds) badIds.add(id)
-1
}
}.filter { (k, v) -> v != -1 && v !in badIds }
} .map { (k, v) -> v.map { it.second } }.flatMap { it }.distinct().filter { it !in badIds}
return r.first();
} | 0 | Kotlin | 0 | 1 | 99f9b05521b270366c2f5ace2e28aa4d263594e4 | 2,527 | AoC-2018 | MIT License |
src/day05/Day05.kt | Xlebo | 572,928,568 | false | {"Kotlin": 10125} | package day05
import getOrFetchInputData
import readInput
import java.util.*
fun main() {
val operation1: (Int, Stack<Char>, Stack<Char>) -> Unit = { amount: Int, base: Stack<Char>, target: Stack<Char> ->
repeat(amount) { target.add(base.pop()) }
}
val operation2: (Int, Stack<Char>, Stack<Char>) -> Unit = { amount: Int, base: Stack<Char>, target: Stack<Char> ->
if (amount == 1) {
target.push(base.pop())
} else {
val temp = Stack<Char>()
repeat(amount) {
temp.push(base.pop())
}
repeat(amount) {
target.push(temp.pop())
}
}
}
fun part1(input: List<String>, operation: (amount: Int, base: Stack<Char>, target: Stack<Char>) -> Unit = operation1): String {
val bottomRegex = Regex("[\\s|\\d]+")
val bottom = input.indexOfFirst { bottomRegex.matches(it) }
val cratesRegex = Regex("(\\s{3})\\s|(\\[.])")
val stacks = mutableListOf<Stack<Char>>()
(bottom - 1 downTo 0).forEach {
val matchesInRow = cratesRegex.findAll(input[it])
var matchCounter = 0
matchesInRow.forEach {
if (stacks.size == matchCounter) {
stacks += Stack<Char>()
}
val value = it.value[1]
if (value != ' ') {
stacks[matchCounter].push(value)
}
matchCounter++
}
}
var operationCounter = bottom + 2
val operationsRegex = Regex("move (\\d+)|from (\\d+)|to (\\d+)")
while (input.size > operationCounter) {
val matchesInRow = operationsRegex.findAll(input[operationCounter])
.map { match ->
match.groupValues.first { it.toIntOrNull() != null }
}
.map { it.toInt() }
.toList()
operation(matchesInRow[0], stacks[matchesInRow[1] - 1], stacks[matchesInRow[2] - 1])
operationCounter++
}
return stacks.map { it.pop() }.joinToString("")
}
fun part2(input: List<String>): String {
return part1(input, operation2)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test", "day05")
val result1 = part1(testInput)
val result2 = part2(testInput)
check(result1 == "CMZ") { "Got: $result1" }
check(result2 == "MCD") { "Got: $result2" }
val input = getOrFetchInputData(5)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cd718c2c7cb59528080d2aef599bd93e0919d2d9 | 2,632 | aoc2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.