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/io/github/clechasseur/adventofcode/y2022/Day2.kt | clechasseur | 567,968,171 | false | {"Kotlin": 493887} | package io.github.clechasseur.adventofcode.y2022
import io.github.clechasseur.adventofcode.y2022.data.Day2Data
object Day2 {
private val input = Day2Data.input
fun part1(): Int = input.lines().sumOf { score(it) }
fun part2(): Int = input.lines().sumOf { score2(it) }
private enum class Choice(val opponent: Char, val you: Char, val score: Int) {
ROCK('A', 'X', 1),
PAPER('B', 'Y', 2),
SCISSORS('C', 'Z', 3);
companion object {
fun forOpponent(c: Char): Choice = values().first { it.opponent == c }
fun forYou(c: Char): Choice = values().first { it.you == c }
fun forOutcome(opponent: Choice, outcome: Char): Choice = if (outcome == 'Y') {
opponent
} else when (opponent) {
ROCK -> if (outcome == 'X') SCISSORS else PAPER
PAPER -> if (outcome == 'X') ROCK else SCISSORS
SCISSORS -> if (outcome == 'X') PAPER else ROCK
}
}
}
private fun Choice.beats(other: Choice): Boolean? = if (other == this) null else when (this) {
Choice.ROCK -> other == Choice.SCISSORS
Choice.PAPER -> other == Choice.ROCK
Choice.SCISSORS -> other == Choice.PAPER
}
private fun score(match: String): Int {
val opponent = Choice.forOpponent(match[0])
val you = Choice.forYou(match[2])
return you.score + when (you.beats(opponent)) {
false -> 0
null -> 3
true -> 6
}
}
private fun score2(match: String): Int {
val opponent = Choice.forOpponent(match[0])
val you = Choice.forOutcome(opponent, match[2])
return you.score + when (you.beats(opponent)) {
false -> 0
null -> 3
true -> 6
}
}
}
| 0 | Kotlin | 0 | 0 | 7ead7db6491d6fba2479cd604f684f0f8c1e450f | 1,835 | adventofcode2022 | MIT License |
src/main/kotlin/Day05.kt | joostbaas | 573,096,671 | false | {"Kotlin": 45397} | import kotlinx.collections.immutable.*
@JvmInline
value class Box(val content: Char)
typealias Stack = PersistentList<Box>
typealias Stacks = PersistentMap<Char, Stack>
data class Move(val count: Int, val from: Char, val to: Char)
interface CrateMover {
val stacks: Stacks
fun doMove(move: Move): CrateMover
}
data class CrateMover9000(override val stacks: Stacks) : CrateMover {
override fun doMove(move: Move): CrateMover9000 {
return if (move.count == 0) this
else {
val newFrom = stacks[move.from]!!.dropLast(1)
val newTo = stacks[move.to]!!.add(stacks[move.from]!!.last())
this.copy(stacks = stacks.put(move.from, newFrom).put(move.to, newTo))
.doMove(move.copy(count = move.count - 1))
}
}
}
data class CrateMover9001(override val stacks: Stacks) : CrateMover {
override fun doMove(move: Move): CrateMover9001 {
val newFrom = stacks[move.from]!!.dropLast(move.count)
val newTo = stacks[move.to]!!.addAll(stacks[move.from]!!.takeLast(move.count))
return this.copy(stacks = stacks.put(move.from, newFrom).put(move.to, newTo))
}
}
fun List<String>.parseStacks(): Stacks {
val chars = this.reversed().map { line -> line.chunked(4).map { it[1] } }
val stackIds = chars.first()
return List(stackIds.size) { i: Int ->
chars.map { it.getOrNull(i) ?: ' '}
}.map { it.parseStack() }
.let {
persistentMapOf<Char, Stack>().putAll(it)
}
}
fun List<Char>.parseStack(): Pair<Char, Stack> =
this.first() to this.drop(1).fold(persistentListOf()) { acc, c ->
if (c != ' ') acc.add(Box(c))
else acc
}
fun List<String>.parseMoves() =
"move (\\d+) from (.+) to (.+)".toRegex().let {regex ->
this.map { line ->
val (count, from, to) = regex.find(line)!!.destructured
Move(count.toInt(), from[0], to[0])
}
}
fun solution(input: List<String>, crateMoverFactory: (Stacks) -> CrateMover): String {
val stacksPart = input.takeWhile { it.isNotEmpty() }
val moves: List<Move> = input.drop(stacksPart.size + 1).parseMoves()
val stacksAfterMoves = moves.fold(crateMoverFactory(stacksPart.parseStacks())) { stacks, move ->
stacks.doMove(move)
}.stacks
return stacksAfterMoves.map { (_, stack) ->
stack.last().content
}.joinToString(separator = "")
}
fun day05Part1(input: List<String>): String =
solution(input) {
CrateMover9000(it)
}
fun day05Part2(input: List<String>): String =
solution(input) {
CrateMover9001(it)
}
| 0 | Kotlin | 0 | 0 | 8d4e3c87f6f2e34002b6dbc89c377f5a0860f571 | 2,634 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day005.kt | ruffCode | 398,923,968 | false | null | object Day005 {
private val sample = listOf("FBFBBFFRLR")
private val input = PuzzleInput("day005.txt")
@JvmStatic
fun main(args: Array<String>) {
val passes = input.readLines()
println(
"""
part1: ${partOne(passes)}
part2: ${partTwo(passes)}
""".trimIndent()
)
}
fun partOne(passes: List<String>): Int =
passes.toSeatIds().maxOf { it }
fun partTwo(passes: List<String>): Int {
val seatIds = passes.toSeatIds()
val max = seatIds.maxOf { it }
val min = seatIds.minOf { it }
return (min..max).toList().single { it !in seatIds }
}
internal fun getSeatId(boardingPass: String): Int {
var rows = (0..127).toList()
var columns = (0..7).toList()
boardingPass.forEach {
val rowsToDrop = rows.size / 2
val columnsToDrop = columns.size / 2
when (it) {
'F' -> rows = rows.dropLast(rowsToDrop)
'B' -> rows = rows.drop(rowsToDrop)
'R' -> columns = columns.drop(columnsToDrop)
'L' -> columns = columns.dropLast(columnsToDrop)
}
}
return rows.single() * 8 + columns.single()
}
private fun List<String>.toSeatIds(): List<Int> = this.map(::getSeatId)
// Solution from https://github.com/kotlin-hands-on/advent-of-code-2020/blob/master/src/day05/day5.kt
// by <NAME>
fun alternateSolution() {
val seatIDs = input.readLines()
.map(String::toSeatID)
val maxID = seatIDs.maxOrNull()!!
println("Max seat ID: $maxID")
val occupiedSeatsSet = seatIDs.toSet()
fun isOccupied(seat: Int) = seat in occupiedSeatsSet
val mySeat = (1..maxID).find { index ->
!isOccupied(index) && isOccupied(index - 1) && isOccupied(index + 1)
}
println("My seat ID: $mySeat")
}
}
internal fun String.toSeatID(): Int =
replace("B", "1").replace("F", "0")
.replace("R", "1").replace("L", "0")
.toInt(radix = 2)
| 0 | Kotlin | 0 | 0 | 477510cd67dac9653fc61d6b3cb294ac424d2244 | 2,117 | advent-of-code-2020-kt | MIT License |
src/day16/day16.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day16
import readInput
import java.util.UUID
import kotlin.math.max
fun parse(input: List<String>): Pair<Map<String, Map<String, Int>>, Map<String, Int>> {
val rates = HashMap<String, Int>()
val graph = HashMap<String, MutableMap<String, Int>>()
// create connections based on input
for (line in input) {
val parts = line.split("Valve ", " has flow rate=", "; tunnels lead to valves ", "; tunnel leads to valve ")
val key = parts[1]
val rate = parts[2].toInt()
val children = parts[3].split(", ").toMutableSet()
rates[key] = rate
graph[key] = children.associateWith { 1 }.toMutableMap()
graph[key]!![key] = 0
}
// check if can change
fun HashMap<String, MutableMap<String, Int>>.getHelper(start: String, end: String): Int {
val values = get(start).orEmpty()
return values[end] ?: Int.MAX_VALUE
}
fun HashMap<String, MutableMap<String, Int>>.checkCondition(i: String, j: String, k: String): Boolean {
if (getHelper(i, k) == Int.MAX_VALUE || getHelper(k, j) == Int.MAX_VALUE) {
return false
}
return getHelper(i, j) > getHelper(i, k) + getHelper(k, j)
}
// find all paths for all nodes
val keys = graph.keys
for (k in keys) {
for (i in keys) {
for (j in keys) {
if (graph.checkCondition(i, j, k)) {
graph[i]!![j] = graph.getHelper(i, k) + graph.getHelper(k, j)
}
}
}
}
// remove all insignificant paths
val result = graph.filter { it.key == "AA" || rates.getOrDefault(it.key, 0) > 0 }
.map { parent -> parent.key to parent.value.filter { it.key != parent.key && rates.getOrDefault(it.key, 0) > 0 } }
.filter { it.second.isNotEmpty() }
.toMap()
return Pair(result, rates)
}
private fun helper(
grid: Map<String, Map<String, Int>>,
rates: Map<String, Int>,
actors: Set<Actor>,
toVisit: Set<String>,
time: Int
): Int {
fun handleNewDestination(actor: Actor, node: String): Pair<Int, Actor> {
val moveTime = grid[actor.node]!![node]!!
val pressure = rates[node]!!
val newTime = max(0, time - moveTime - 1)
val value = newTime * pressure
val newActor = Actor(actor.id, node, newTime)
return Pair(value, newActor)
}
if (time <= 0) return 0
var max = 0
val actor = actors.first { it.time >= time }
val otherActors = actors - actor
for (node in toVisit) {
val destination = handleNewDestination(actor, node)
val newVisited = HashSet(toVisit).apply {
remove(destination.second.node)
}
val newActors = mutableSetOf<Actor>().apply {
addAll(otherActors)
add(destination.second)
}
val nextTime = newActors.maxBy { it.time }.time
val tempValue = destination.first + helper(
grid, rates, newActors, newVisited, nextTime
)
max = tempValue.coerceAtLeast(max)
}
return max
}
data class Actor(
val id: UUID = UUID.randomUUID(),
val node: String,
val time: Int,
)
private fun part1(input: List<String>): Int {
val parsesInput = parse(input)
val toVisit = parsesInput.second.filter { it.value > 0 }.keys
val actors = setOf(Actor(node = "AA", time = 30))
return helper(parsesInput.first, parsesInput.second, actors, toVisit, time = 30)
}
private fun part2(input: List<String>): Int {
val parsesInput = parse(input)
val toVisit = parsesInput.second.filter { it.value > 0 }.keys
val actors = setOf(Actor(node = "AA", time = 26), Actor(node = "AA", time = 26))
return helper(parsesInput.first, parsesInput.second, actors, toVisit, time = 26)
}
fun main() {
val input = readInput("day16/input")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 3,941 | aoc-2022 | Apache License 2.0 |
src/Day16_try.kt | TinusHeystek | 574,474,118 | false | {"Kotlin": 53071} | import extensions.grid.*
import kotlin.math.max
class Day16Try : Day(16) {
class Valve(val input: String) {
val name: String
val flowRate: Int
val connectedVales: List<String>
var isOpen: Boolean = false
var openedOnXMinutesLeft : Int = 0
init {
name = input.substring(6, 8)
val split = input.substringAfter("flow rate=").split(";")
flowRate = split[0].toInt()
connectedVales = split[1].split(" ").drop(5).map { it.replace(",", "") }
}
fun eventualPressure(withMinutes: Int): Int {
return flowRate * withMinutes
}
fun openValve(timer: Int): Int {
isOpen = true
openedOnXMinutesLeft = timer
return 1
}
override fun toString(): String {
return "$name - Flow: $flowRate - IsOpen: $isOpen - OpenedOnXMinutesLeft: $openedOnXMinutesLeft"
}
}
private fun parseInput(input: String) : List<Valve> {
return input.lines()
.map { Valve(it) }
}
private fun getBestFlowRateValve(valves: List<Valve>, graph: Graph, currentValve : Valve, timer: Int, ): Valve? {
val top2 = valves
.filter { !it.isOpen && it.flowRate > 0 }
.map {
val timeTo = graph.findPath(currentValve.name, it.name).count()
val count = it.eventualPressure(max(0, timer - timeTo)) / timeTo
Triple(it, count, timeTo)
}
.sortedByDescending {it.second }
.take(2)
if (top2.count() < 2)
return top2.firstOrNull()?.first
val t1 = graph.findPath(top2[0].first.name, top2[1].first.name).count()
val t1Total = top2[1].first.eventualPressure(max(0, timer - top2[0].third - t1)) / t1
val t2 = graph.findPath(top2[1].first.name, top2[0].first.name).count()
val t2Total = top2[0].first.eventualPressure(max(0, timer - top2[1].third - t2)) / t2
if (top2[0].second + t1Total > top2[1].second + t2Total)
return top2[0].first
else
return top2[1].first
// return top2.first()
//val v1 = top2[0].eventualPressure()
}
// --- Part 1 ---
override fun part1ToInt(input: String): Int {
val valves = parseInput(input)
val edges = valves.map { p -> p.connectedVales.map { Edge(p.name, it, 1) } }
.flatten();
val graph = Graph(edges);
var timer = 30
var currentValve = valves.first {it.name == "AA"}
var bestValve : Valve? = getBestFlowRateValve(valves, graph, currentValve, timer)
while (bestValve != null && timer > 0) {
val aa = graph.findPath(currentValve.name, bestValve.name)
timer -= aa.count()
currentValve = bestValve
//timer -=
bestValve.openValve(timer)
bestValve = getBestFlowRateValve(valves, graph, currentValve, timer)
}
val totalEventualPressure = valves
.sumOf { it.eventualPressure(it.openedOnXMinutesLeft) }
return totalEventualPressure
}
// --- Part 2 ---
override fun part2ToInt(input: String): Int {
return input.lines().size
}
}
fun main() {
Day16Try().printToIntResults(1651)
}
| 0 | Kotlin | 0 | 0 | 80b9ea6b25869a8267432c3a6f794fcaed2cf28b | 3,344 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day23.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | import Day23.Direction
fun main() {
val testInput = readInput("Day23_test")
.parseGround()
val input = readInput("Day23")
.parseGround()
part1(testInput).also {
println("Part 1, test input: $it")
check(it == 110)
}
part1(input).also {
println("Part 1, real input: $it")
check(it == 3862)
}
part2(testInput).also {
println("Part 2, test input: $it")
check(it == 20)
}
part2(input).also {
println("Part 2, real input: $it")
check(it == 913)
}
}
object Day23 {
enum class Direction(val dxdy: XY, val adjacent: List<XY>) {
N(
dxdy = XY(0, -1),
adjacent = listOf(
XY(-1, -1),
XY(0, -1),
XY(1, -1)
)
),
S(
dxdy = XY(0, 1),
adjacent = listOf(
XY(-1, 1),
XY(0, 1),
XY(1, 1),
)
),
W(
dxdy = XY(-1, 0),
adjacent = listOf(
XY(-1, -1),
XY(-1, 0),
XY(-1, 1),
),
),
E(
dxdy = XY(1, 0),
adjacent = listOf(
XY(1, -1),
XY(1, 0),
XY(1, 1),
),
);
private val all by lazy { enumValues<Direction>().toList() }
fun directionsFrom(): List<Direction> {
val p = all.indexOf(this)
return all.subList(p, all.size) +
(if (p != 0) all.subList(0, p) else emptyList())
}
}
data class XY(val x: Int, val y: Int) {
fun to(d: Direction): XY = XY(d.dxdy.x + this.x, d.dxdy.y + y)
}
class Field(tiles: List<List<Boolean>>) {
val elves: MutableSet<XY> = tiles.flatMapIndexed { y, booleans ->
booleans.mapIndexed { x, b ->
if (b == true) {
XY(x, y)
} else {
null
}
}.filterNotNull()
}.toMutableSet()
fun move(direction: Direction): Boolean {
val directions = direction.directionsFrom()
val newPositions: MutableMap<XY, Direction> = mutableMapOf()
var fieldChanged = false
elves.forEach { e ->
val hasElvesAround = directions
.any { d ->
d.adjacent.any { a ->
val p = XY(a.x + e.x, a.y + e.y)
p in elves
}
}
if (!hasElvesAround) {
return@forEach
}
fieldChanged = true
val newDirection = directions.firstOrNull { d ->
d.adjacent.all {
val p = XY(it.x + e.x, it.y + e.y)
p !in elves
}
}
if (newDirection != null) {
newPositions[e] = newDirection
}
}
val collisions: Map<XY, Int> = newPositions.map { (pos, direction) ->
pos.to(direction)
}.groupingBy { it }.eachCount()
newPositions.forEach { (pos, direction) ->
val newPosition = pos.to(direction)
if (collisions[newPosition] == 1) {
check(newPosition !in elves)
elves -= pos
elves += newPosition
}
}
return fieldChanged
}
fun getBoundingBoxWithElves(): Pair<XY, XY> {
val leftX = elves.minOf { it.x }
val rightX = elves.maxOf { it.x }
val topY = elves.minOf { it.y }
val bottomY = elves.maxOf { it.y }
return XY(leftX, topY) to XY(rightX, bottomY)
}
fun printField() {
val bbox = getBoundingBoxWithElves()
(bbox.first.y..bbox.second.y).forEach { y ->
val s = (bbox.first.x..bbox.second.x).map { x ->
if (XY(x, y) in elves) '#' else '.'
}.joinToString("")
println(s)
}
}
fun countEmptyPositions(): Int {
val bbox = getBoundingBoxWithElves()
return (bbox.second.y - bbox.first.y + 1) *
(bbox.second.x - bbox.first.x + 1) - elves.size
}
}
}
private fun part1(input: List<List<Boolean>>): Int {
val field = Day23.Field(tiles = input)
var direction = Direction.N
repeat(10) {
field.move(direction)
direction = direction.directionsFrom()[1]
}
return field.countEmptyPositions()
}
private fun part2(input: List<List<Boolean>>): Int {
val field = Day23.Field(tiles = input)
var direction = Direction.N
var fieldChanged: Boolean
var round = 0
do {
fieldChanged = field.move(direction)
round += 1
direction = direction.directionsFrom()[1]
} while (fieldChanged)
return round
}
private fun List<String>.parseGround(): List<List<Boolean>> {
return this.map { s ->
s.map { it == '#' }
}
} | 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 5,273 | aoc22-kotlin | Apache License 2.0 |
src/Day07.kt | phoenixli | 574,035,552 | false | {"Kotlin": 29419} | fun main() {
fun part1(input: List<String>): Int {
val root = parseInput(input)
return root.find { it.size <= 100000 }.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val root = parseInput(input)
val unused = 70000000 - root.size
val needToFree = 30000000 - unused
return root.find { it.size >= needToFree }.minOf { it.size }
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
class Directory(val name: String) {
private val children = mutableListOf<Directory>()
private var sizeOfFiles = 0
val size: Int
get() = sizeOfFiles + children.sumOf { it.size }
fun addFile(size: Int) {
sizeOfFiles += size
}
fun addDirectory(dir: Directory) {
children.add(dir)
}
fun find(predicae: (Directory) -> Boolean): List<Directory> {
return children.filter(predicae) + children.flatMap { it.find(predicae) }
}
}
fun parseInput(input: List<String>): Directory {
val directories = ArrayDeque<Directory>()
directories.add(Directory("/"))
input.forEach { cmd ->
when {
cmd == "$ cd /" -> directories.removeIf { it.name != "/" }
cmd == "$ cd .." -> directories.removeFirst()
cmd == "$ ls" -> {}
cmd.startsWith("dir") -> {}
cmd.startsWith("$ cd ") -> {
val name = cmd.substringAfterLast(' ')
val dir = Directory(name)
directories.first().addDirectory(dir)
directories.addFirst(dir)
}
else -> {
val size = cmd.substringBefore(' ').toInt()
directories.first().addFile(size)
}
}
}
return directories.last()
} | 0 | Kotlin | 0 | 0 | 5f993c7b3c3f518d4ea926a792767a1381349d75 | 1,801 | Advent-of-Code-2022 | Apache License 2.0 |
src/DayFour.kt | P-ter | 572,781,029 | false | {"Kotlin": 18422} | import kotlin.math.roundToInt
fun main() {
fun partOne(input: List<String>): Int {
var total = 0
input.forEach { line ->
val (firstElf, secondElf) = line.split(",")
val firstElfRange = firstElf.split("-").map { it.toInt() }
val secondElfRange = secondElf.split("-").map { it.toInt() }
if(firstElfRange[0] in secondElfRange[0]..secondElfRange[1] && firstElfRange[1] in secondElfRange[0]..secondElfRange[1]) {
total++
} else if(secondElfRange[0] in firstElfRange[0]..firstElfRange[1] && secondElfRange[1] in firstElfRange[0]..firstElfRange[1]) {
total++
}
}
return total
}
fun partTwo(input: List<String>): Int {
var total = 0
input.forEach { line ->
val (firstElf, secondElf) = line.split(",")
val firstElfRange = firstElf.split("-").map { it.toInt() }
val secondElfRange = secondElf.split("-").map { it.toInt() }
if(firstElfRange[0] in secondElfRange[0]..secondElfRange[1] || firstElfRange[1] in secondElfRange[0]..secondElfRange[1]) {
total++
} else if(secondElfRange[0] in firstElfRange[0]..firstElfRange[1] || secondElfRange[1] in firstElfRange[0]..firstElfRange[1]) {
total++
}
}
return total
}
val input = readInput("dayfour")
println(partOne(input))
println(partTwo(input))
}
| 0 | Kotlin | 0 | 1 | e28851ee38d6de5600b54fb884ad7199b44e8373 | 1,490 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/_2021/Day10.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2021
import REGEX_LINE_SEPARATOR
import aoc
import kotlin.math.ceil
private val CHUNK_MAP = mapOf(
')' to '(',
']' to '[',
'}' to '{',
'>' to '<'
)
private val CHUNK_MAP_REVERSED = CHUNK_MAP.entries.associateBy({ it.value }, { it.key })
fun main() {
aoc(2021, 10) {
aocRun { input ->
input.split(REGEX_LINE_SEPARATOR).sumOf { processLine(it).first }
}
aocRun { input ->
val scores = input.split(REGEX_LINE_SEPARATOR).asSequence()
.map { processLine(it) }
.filter { it.first == 0 }
.map { chunks -> chunks.second.reversed().map { CHUNK_MAP_REVERSED[it]!! } }
.map { chunks ->
chunks
.map {
when (it) {
')' -> 1L
']' -> 2L
'}' -> 3L
'>' -> 4L
else -> error("Pls why")
}
}
.reduce { acc, chunk -> (acc * 5L) + chunk }
// .also { println("${chunks.joinToString("")} -> $it") }
}
.sorted()
.toList()
return@aocRun scores[ceil(scores.size.toFloat() / 2F).toInt() - 1]
}
}
}
private fun processLine(line: String): Pair<Int, List<Char>> {
val chunks = mutableListOf<Char>()
for (char in line.toCharArray()) {
when (char) {
'(', '[', '{', '<' -> chunks += char
')', ']', '}', '>' -> {
val openChar = CHUNK_MAP[char]!!
val lastChunk = chunks.last()
if (lastChunk != openChar) {
// Illegal! Can't close a chunk with open chunks inside!
return when (char) {
')' -> 3
']' -> 57
'}' -> 1197
'>' -> 25137
else -> error("This shouldn't happen -> '$char'")
} to chunks
}
chunks.removeLast()
}
}
}
return 0 to chunks
}
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 1,629 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dp/BoxDepth.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
typealias Square = Tuple4<Int, Int, Int, Int>
// given n squares of size 10 as (X, Y) where X is the x-coordinate of its bottom
// left corner and Y is the y-coordinate of its bottom left corner
// find the largest subset of such squares : there is a common point in them
// and report the size of such set
fun OneArray<Tuple2<Int, Int>>.commonPoint(): Int {
val S = this
val n = size
// consider the input as a stack of squares piled from bottom to top (even
// though they don't overlap between each other, but just floating around)
// dp(i): largest such set that starts @ i-th square
val dp = OneArray(n) { 0 tu 0 tu 0 tu 0 tu 0 }
dp[n] = 1 tu S[n].toSquare()
for (i in n - 1 downTo 1) {
dp[i] = 1 tu S[i].toSquare()
for (j in i + 1..n) {
val area = dp[j].second tu dp[j].third tu dp[j].fourth tu dp[j].fifth
val overlap = S[i].overlap(area)
if (overlap.isValid() && dp[j].first + 1 > dp[i].first) {
dp[i] = dp[j].first + 1 tu overlap
}
}
}
return dp.maxBy { it.first }?.first ?: 0
}
private fun Tuple2<Int, Int>.toSquare() = this tu first + 10 tu second + 10
private fun Tuple2<Int, Int>.overlap(s: Square): Square {
// O(1) comparing
// r1 is the rectangle 1 that has smaller bottom right x coordinate
val (r1brx, r1bry, r1tlx, r1tly) = if (first < s.first) toSquare() else s
val (r2brx, r2bry, r2tlx, r2tly) = if (first < s.first) s else toSquare()
if (r1tlx < r2brx || r2tlx < r1brx || r1tly < r2bry || r2tly < r1bry) {
return 0 tu 0 tu 0 tu 0
}
return max(r1brx, r2brx) tu max(r1bry, r2bry) tu min(r1tlx, r2tlx) tu min(r1tly, r2tly)
}
private fun Square.isValid() = third > first && fourth > second
fun main(args: Array<String>) {
val s = oneArrayOf(
0 tu 0,
1 tu 1,
9 tu 9,
10 tu 10,
100 tu 200,
105 tu 190)
println(s.commonPoint())
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,843 | AlgoKt | MIT License |
aoc-2019/src/commonMain/kotlin/fr/outadoc/aoc/twentynineteen/Day03.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentynineteen
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.max
import fr.outadoc.aoc.scaffold.min
import fr.outadoc.aoc.scaffold.readDayInput
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Day03 : Day<Int> {
private val input: List<String> =
readDayInput().lines()
data class Point(val x: Int, val y: Int) {
operator fun plus(o: Point): Point {
return Point(x + o.x, y + o.y)
}
fun distance(o: Point): Int {
return abs(x - o.x) + abs(y - o.y)
}
}
data class Segment(val a: Point, val b: Point) {
private val isVertical = a.x == b.x
private val isHorizontal = a.y == b.y
private val rightMostPoint = if (a.x >= b.x) a else b
private val leftMostPoint = if (a.x >= b.x) b else a
private val topMostPoint = if (a.y >= b.y) b else a
private val bottomMostPoint = if (a.y >= b.y) a else b
private fun isPerpendicularTo(o: Segment): Boolean {
return when {
isVertical -> o.isHorizontal
isHorizontal -> o.isVertical
else -> throw IllegalStateException("Segment must be aligned on the grid")
}
}
fun intersectsAt(o: Segment): Point? {
if (!isPerpendicularTo(o)) {
return null
}
val vSeg = if (isVertical) this else o
val hSeg = if (isHorizontal) this else o
return when {
vSeg.topMostPoint.y >= hSeg.a.y ||
hSeg.leftMostPoint.x >= vSeg.a.x ||
vSeg.bottomMostPoint.y <= hSeg.a.y ||
hSeg.rightMostPoint.x <= vSeg.a.x -> {
null
}
else -> {
Point(hSeg.a.x, vSeg.a.y)
}
}
}
}
data class Wire(val segments: List<Segment>) {
fun crossesVerticallyAt(x: Int, y: Int): Boolean {
return segments.any { s ->
s.a.x == s.b.x // x is constant
&& s.a.x == x // x is the column that interests us
&& (y in (s.a.y..s.b.y) || y in (s.b.y..s.a.y)) // the segment exists at row y
}
}
fun crossesHorizontallyAt(x: Int, y: Int): Boolean {
return segments.any { s ->
s.a.y == s.b.y // y is constant
&& s.a.y == y // y is the row that interests us
&& (x in (s.a.x..s.b.x) || x in (s.b.x..s.a.x)) // the segment exists at column x
}
}
fun intersectsAt(o: Wire): List<Point> {
return segments.flatMap { s1 ->
o.segments.mapNotNull { s2 ->
s1.intersectsAt(s2)
}
}
}
}
data class Circuit(val wires: List<Wire>) {
val minX: Int by lazy {
wires.map { w ->
w.segments.map { s ->
min(s.a.x, s.b.x)
}.min()
}.min()
}
val maxX: Int by lazy {
wires.map { w ->
w.segments.map { s ->
max(s.a.x, s.b.x)
}.max()
}.max()
}
val minY: Int by lazy {
wires.map { w ->
w.segments.map { s ->
min(s.a.y, s.b.y)
}.min()
}.min()
}
val maxY: Int by lazy {
wires.map { w ->
w.segments.map { s ->
max(s.a.y, s.b.y)
}.max()
}.max()
}
private fun checkIntersectionAt(x: Int, y: Int): Boolean {
val hWiresAtPoint = wires.filter { it.crossesHorizontallyAt(x, y) }
val vWiresAtPoint = wires.filter { it.crossesVerticallyAt(x, y) }
if (hWiresAtPoint.isNotEmpty() && vWiresAtPoint.isNotEmpty()
&& hWiresAtPoint != vWiresAtPoint
) {
// wires cross this point both horizontally and vertically
// and they're not the same one
return true
}
return false
}
fun findIntersections(): List<Point> {
return (minX..maxX).flatMap { x ->
(minY..maxY).mapNotNull { y ->
if (checkIntersectionAt(x, y)) {
Point(x, y)
} else null
}
}.filterNot { it == Point(0, 0) }
}
fun findIntersectionsFast(): List<Point> {
return wires.flatMap { w1 ->
wires.flatMap { w2 ->
w1.intersectsAt(w2)
}
}
}
}
private fun parseSegment(str: String, a: Point): Segment {
val dir = str.first()
val len = str.drop(1).toInt()
val b = a + when (dir) {
'R' -> Point(len, 0)
'L' -> Point(-len, 0)
'U' -> Point(0, -len)
'D' -> Point(0, len)
else -> throw IllegalArgumentException()
}
return Segment(a, b)
}
private fun parseWire(wireStr: String): Wire {
val segments = wireStr.split(',')
.fold(emptyList<Segment>()) { acc, segmentStr ->
val lastPoint = acc.lastOrNull()?.b ?: Point(0, 0)
val wire = parseSegment(segmentStr, lastPoint)
acc + wire
}
return Wire(segments)
}
override fun step1(): Int {
val c = Circuit(input.map { parseWire(it) })
val intersect = c.findIntersectionsFast()
println(intersect.joinToString())
// Day3Debug().display(c)
return intersect.map { p -> p.distance(Point(0, 0)) }.min()
}
override fun step2(): Int = -1
override val expectedStep1: Int = -1
override val expectedStep2: Int = -1
} | 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 6,040 | adventofcode | Apache License 2.0 |
src/Day02.kt | manuel-martos | 574,260,226 | false | {"Kotlin": 7235} | fun main() {
println("part01 -> ${solveDay02Part01()}")
println("part02 -> ${solveDay02Part02()}")
}
private fun solveDay02Part01() =
readInput("day02")
.sumOf {
val other = it[0] - 'A' + 1
val mine = it[2] - 'X' + 1
val outcome = calcOutcome(mine, other)
mine + outcome
}
private fun solveDay02Part02() =
readInput("day02")
.sumOf {
val other = it[0] - 'A' + 1
val goal = it[2] - 'X' + 1
val mine = when {
other == 1 && goal == 1 -> 3
other == 2 && goal == 1 -> 1
other == 3 && goal == 1 -> 2
other == 1 && goal == 3 -> 2
other == 2 && goal == 3 -> 3
other == 3 && goal == 3 -> 1
else -> other
}
val outcome = calcOutcome(mine, other)
mine + outcome
}
private fun calcOutcome(mine: Int, other: Int) =
when {
other == 1 && mine == 2 -> 6
other == 2 && mine == 3 -> 6
other == 3 && mine == 1 -> 6
other == mine -> 3
else -> 0
} | 0 | Kotlin | 0 | 0 | 5836682fe0cd88b4feb9091d416af183f7f70317 | 1,157 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/mkuhn/aoc/Day09.kt | mtkuhn | 572,236,871 | false | {"Kotlin": 53161} | package mkuhn.aoc
import mkuhn.aoc.util.Point
import mkuhn.aoc.util.readInput
import mkuhn.aoc.util.splitToPair
fun main() {
val input = readInput("Day09")
println(day09part1(input))
println(day09part2(input))
}
fun day09part1(input: List<String>): Int {
val moves = input.map { it.lineToMovement() }
val rope = Rope(listOf(Point(0, 0), Point(0, 0)))
return applyMovementAndGetTailPositions(rope, moves).count()
}
fun day09part2(input: List<String>): Int {
val moves = input.map { it.lineToMovement() }
val rope = Rope(List(10) { Point(0, 0) })
return applyMovementAndGetTailPositions(rope, moves).count()
}
fun String.lineToMovement() = this.splitToPair(' ').let { it.first.first() to it.second.toInt() }
fun applyMovementAndGetTailPositions(rope: Rope, moves: List<Pair<Char, Int>>): Set<Point> =
moves.flatMap { m -> (0 until m.second).map { m.first } }
.fold(rope to setOf(rope.tail)) { acc, d ->
acc.first.moveRopeInDirection(d).let { it to acc.second.plus(it.tail) }
}.second
class Rope(val knots: List<Point>) {
val head = knots.first()
val tail = knots.last()
fun moveRopeInDirection(direction: Char): Rope =
mutableListOf(head.moveInDirection(direction))
.apply { knots.drop(1).forEach { k -> this += k.moveToward(this.last()) } }
.let { Rope(it) }
private fun Point.moveInDirection(direction: Char) =
when(direction) {
'U' -> Point(x, y-1)
'D' -> Point(x, y+1)
'R' -> Point(x+1, y)
'L' -> Point(x-1, y)
else -> error("invalid movement")
}
private fun Point.moveToward(target: Point): Point =
if(isTouching(target)) this
else Point(x - x.compareTo(target.x), y - y.compareTo(target.y))
private fun Point.isTouching(target: Point) =
target.x in (this.x-1 .. this.x+1) && target.y in (this.y-1 .. this.y+1)
} | 0 | Kotlin | 0 | 1 | 89138e33bb269f8e0ef99a4be2c029065b69bc5c | 1,955 | advent-of-code-2022 | Apache License 2.0 |
kotlin/graphs/shortestpaths/DijkstraCustomHeap.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs.shortestpaths
import java.util.stream.Stream
// https://en.wikipedia.org/wiki/Dijkstra's_algorithm
object DijkstraCustomHeap {
// calculate shortest paths in O(E*log(V)) time and O(V) memory
fun shortestPaths(edges: Array<List<Edge>>, s: Int, prio: LongArray, pred: IntArray) {
Arrays.fill(pred, -1)
Arrays.fill(prio, Long.MAX_VALUE)
prio[s] = 0
val h = BinaryHeap(edges.size)
h.add(s, 0)
while (h.size != 0) {
val u = h.remove()
for (e in edges[u]) {
val v = e.t
val nprio = prio[u] + e.cost
if (prio[v] > nprio) {
if (prio[v] == Long.MAX_VALUE) h.add(v, nprio) else h.increasePriority(v, nprio)
prio[v] = nprio
pred[v] = u
}
}
}
}
// Usage example
fun main(args: Array<String?>?) {
val cost = arrayOf(intArrayOf(0, 3, 2), intArrayOf(0, 0, -2), intArrayOf(0, 0, 0))
val n = cost.size
val edges: Array<List<Edge>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() }
for (i in 0 until n) {
for (j in 0 until n) {
if (cost[i][j] != 0) {
edges[i].add(Edge(j, cost[i][j]))
}
}
}
val dist = LongArray(n)
val pred = IntArray(n)
shortestPaths(edges, 0, dist, pred)
System.out.println(0 == dist[0])
System.out.println(3 == dist[1])
System.out.println(1 == dist[2])
System.out.println(-1 == pred[0])
System.out.println(0 == pred[1])
System.out.println(1 == pred[2])
}
class Edge(var t: Int, var cost: Int)
internal class BinaryHeap(n: Int) {
var heap: LongArray
var pos2Id: IntArray
var id2Pos: IntArray
var size = 0
fun remove(): Int {
val removedId = pos2Id[0]
heap[0] = heap[--size]
pos2Id[0] = pos2Id[size]
id2Pos[pos2Id[0]] = 0
down(0)
return removedId
}
fun add(id: Int, value: Long) {
heap[size] = value
pos2Id[size] = id
id2Pos[id] = size
up(size++)
}
fun increasePriority(id: Int, value: Long) {
heap[id2Pos[id]] = value
up(id2Pos[id])
}
fun up(pos: Int) {
var pos = pos
while (pos > 0) {
val parent = (pos - 1) / 2
if (heap[pos] >= heap[parent]) break
swap(pos, parent)
pos = parent
}
}
fun down(pos: Int) {
var pos = pos
while (true) {
var child = 2 * pos + 1
if (child >= size) break
if (child + 1 < size && heap[child + 1] < heap[child]) ++child
if (heap[pos] <= heap[child]) break
swap(pos, child)
pos = child
}
}
fun swap(i: Int, j: Int) {
val tt = heap[i]
heap[i] = heap[j]
heap[j] = tt
val t = pos2Id[i]
pos2Id[i] = pos2Id[j]
pos2Id[j] = t
id2Pos[pos2Id[i]] = i
id2Pos[pos2Id[j]] = j
}
init {
heap = LongArray(n)
pos2Id = IntArray(n)
id2Pos = IntArray(n)
}
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 3,509 | codelibrary | The Unlicense |
src/Day03.kt | cisimon7 | 573,872,773 | false | {"Kotlin": 41406} | fun main() {
fun Char.priority(): Int {
return if (this.isLowerCase()) this.code - 96 else this.code - 64 + 26
}
fun part1(stringList: List<String>): Int {
return stringList
.map { rucksack -> rucksack.chunked(rucksack.length / 2) }
.flatMap { (compartment1, compartment2) -> compartment1.toSet() intersect compartment2.toSet() }
.sumOf { item -> item.priority() }
}
fun part2(stringList: List<String>): Int {
return stringList.chunked(3)
.map { Triple(it[0], it[1], it[2]) }
.flatMap { (first, second, third) -> first.toSet() intersect second.toSet() intersect third.toSet() }
.sumOf { item -> item.priority() }
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 29f9cb46955c0f371908996cc729742dc0387017 | 948 | aoc-2022 | Apache License 2.0 |
src/Day25.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | import kotlin.math.pow
fun main() {
fun getStringLength(decimalSum: Long): Int {
var i = 0
while (true) {
val place = 5.toDouble().pow(i).toLong()
if (place <= decimalSum) {
i++
} else {
break
}
}
return i
}
fun part1(input: List<String>): String {
// Get the sum of the input in decimals.
val decimalInput = mutableListOf<Long>()
for (line in input) {
val decimalLine = mutableListOf<Long>()
for (i in line.indices) {
val decimalChar = when (line[i]) {
'=' -> -2 * 5.toDouble().pow((line.length - 1 - i)).toLong()
'-' -> -1 * 5.toDouble().pow((line.length - 1 - i)).toLong()
else -> line[i].digitToInt() * 5.toDouble().pow((line.length - 1 - i)).toLong()
}
decimalLine.add(decimalChar)
}
decimalInput.add(decimalLine.sum())
}
var decimalSum = decimalInput.sum()
println("DecimalSum: $decimalSum")
// Transform decimalSum to SNAFU.
val snafu = mutableListOf<String>()
val snafuLength = getStringLength(decimalSum)
for (i in snafuLength - 1 downTo 0) {
if (decimalSum - (5.toDouble().pow(i).toLong() * 1) < 0) {
snafu.add("0")
} else for (j in 4 downTo 0) {
if (decimalSum - (5.toDouble().pow(i).toLong() * j) >= 0) {
snafu.add(j.toString())
decimalSum -= (5.toDouble().pow(i).toLong() * j)
break
}
}
}
println("Incorrect SNAFU: ${snafu.joinToString("")}")
// Transform 3's, 4's and 5's to ='s, -'s and 0's respectively.
for (i in snafu.size - 1 downTo 0) {
when (snafu[i]) {
"3" -> {
snafu[i - 1] = (snafu[i - 1].toInt() + 1).toString()
snafu[i] = "="
}
"4" -> {
snafu[i - 1] = (snafu[i - 1].toInt() + 1).toString()
snafu[i] = "-"
}
"5" -> {
snafu[i - 1] = (snafu[i - 1].toInt() + 1).toString()
snafu[i] = "0"
}
}
}
print("SNAFU: ")
return snafu.joinToString("")
}
val input = readInputAsStrings("Day25")
println(part1(input))
}
| 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 2,547 | AoC2022 | Apache License 2.0 |
src/Day14.kt | akijowski | 574,262,746 | false | {"Kotlin": 56887, "Shell": 101} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
data class SandPoint(val x: Int = 0, val y: Int = 0) {
fun fromString(s: String, separator: String = ","): SandPoint {
val (a, b) = s.trim().split(separator)
return SandPoint(a.toInt(), b.toInt())
}
operator fun plus(other: SandPoint) = SandPoint(x + other.x, y + other.y)
operator fun minus(other: SandPoint) = SandPoint(x - other.x, y - other.y)
operator fun times(f: Int) = SandPoint(x * f, y * f)
fun diff(other: SandPoint): Int {
val mx = abs(x - other.x)
val my = abs(y - other.y)
return max(mx, my)
}
fun dir(other: SandPoint): SandPoint {
val sx = (x - other.x).sign
val sy = (y - other.y).sign
return SandPoint(sx, sy)
}
}
fun main() {
// find the next move, or null of it comes to rest.
fun getNextDirection(sand: SandPoint, rocksAndSand: Set<SandPoint>): SandPoint? {
return listOf(
SandPoint(0, 1),
SandPoint(-1, 1),
SandPoint(1, 1)
).firstOrNull { sand + it !in rocksAndSand }
}
fun buildRockWalls(start: SandPoint, end: SandPoint): List<SandPoint> {
val diff = start.diff(end)
val dir = end.dir(start)
return (0..diff).map { start + (dir * it) }
}
// convert a path list(x,y) to rock walls
fun pathToRocks(path: List<SandPoint>): List<SandPoint> =
path.zipWithNext().flatMap { (p1, p2) -> buildRockWalls(p1, p2) }
fun part1(input: List<String>, print: Boolean = false): Int {
val paths = input.map { it.split("->").map { c -> c.trim() }.map { p -> SandPoint().fromString(p) } }
val rocks = paths.flatMap { path -> pathToRocks(path).toSet() }.toSet()
val maxY = rocks.maxOf { it.y }
val rocksAndSand = rocks.toMutableSet()
var done = false
var count = 0
while (!done) {
var sand = SandPoint(500, 0)
while (true) {
// filled to the top
if (sand.y > maxY) {
done = true
break
}
val nextDir = getNextDirection(sand, rocksAndSand)
if (nextDir == null) {
rocksAndSand.add(sand)
count++
break
} else {
sand += nextDir
}
}
}
if (print) {
val minX = rocksAndSand.minOf { it.x }
val maxX = rocksAndSand.maxOf { it.x }
val map = List(maxY) { CharArray((maxX - minX)) { '.' } }
rocksAndSand.forEach { (x, y) -> map[y-1][x-minX] = 'o' }
rocks.forEach { (x, y) -> map[y-1][x-minX] = '#' }
map.forEach { println(it.joinToString(" ")) }
}
return count
}
fun part2(input: List<String>): Int {
val rocks = input
.map { it.split("->").map { c -> c.trim() }.map { p -> SandPoint().fromString(p) } }
.flatMap { path -> pathToRocks(path).toSet() }.toSet()
val l = rocks.minOf { it.x }
val r = rocks.maxOf { it.x }
val maxY = rocks.maxOf { it.y }
val start = SandPoint(500, 0)
val floor = ((l - 250)..(r + 250)).map { SandPoint(it, maxY + 2) }
val rocksAndSand = (rocks + floor).toMutableSet()
var done = false
var count = 0
while (!done) {
var sand = start
while (true) {
val nextDir = getNextDirection(sand, rocksAndSand)
if (nextDir == null) {
rocksAndSand.add(sand)
count++
if (sand == start) {
done = true
}
break
} else {
sand += nextDir
}
}
}
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput, true) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 84d86a4bbaee40de72243c25b57e8eaf1d88e6d1 | 4,243 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day15.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2022
import kotlin.math.abs
import kotlin.math.max
class Day15(private val input: List<String>) {
private val sensors = parseSensors()
fun solvePart1(targetY: Int): Int {
val range = coveredRange(targetY)
return range.last - range.first
}
fun solvePart2(maxRange: Int): Long {
for (y in 0..maxRange) {
try {
coveredRange(y)
} catch (e: RangeException) {
return e.x * 4_000_000L + y
}
}
error("No solution found")
}
private fun coveredRange(targetY: Int): IntRange {
return sensors
.mapNotNull { it.coveredRange(targetY) }
.sortedWith { a, b ->
if (a.first == b.first) {
a.last.compareTo(b.last)
} else {
a.first.compareTo(b.first)
}
}
.reduce { a, b ->
if (a.last + 1 < b.first) {
throw RangeException(a.last + 1)
}
// merge ranges
a.first..max(a.last, b.last)
}
}
private fun parseSensors(): List<Sensor> {
val numberRegex = Regex("-?\\d+")
return input.map { line ->
val (sensorX, sensorY, beaconX, beaconY) = numberRegex.findAll(line)
.map { it.groupValues.first().toInt() }
.toList()
Sensor(sensorX, sensorY, beaconX, beaconY)
}
}
private data class Sensor(val x: Int, val y: Int, val beaconX: Int, val beaconY: Int) {
val distanceBeacon = abs(x - beaconX) + abs(y - beaconY)
fun coveredRange(targetY: Int): IntRange? {
val distanceTarget = abs(y - targetY)
val deltaBeaconX = distanceBeacon - distanceTarget
if (deltaBeaconX < 0) {
return null
}
return (x - deltaBeaconX)..(x + deltaBeaconX)
}
}
private class RangeException(val x: Int) : Exception("Gap in range: $x")
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 2,096 | advent-of-code | Apache License 2.0 |
src/main/kotlin/net/rafaeltoledo/kotlin/advent/Day02.kt | rafaeltoledo | 726,542,427 | false | {"Kotlin": 11895} | package net.rafaeltoledo.kotlin.advent
class Day02 {
val validRound = Round(red = 12, green = 13, blue = 14)
fun invoke(input: List<String>): Int {
val games = input.map { it.toGame() }
return games.filter { it.isValid() }.sumOf { it.id }
}
fun invoke2(input: List<String>): Int {
val games = input.map { it.toGame() }
return games.map { it.rounds.optimal() }.sumOf { it.red * it.green * it.blue }
}
private fun Game.isValid(): Boolean {
return rounds.map { it.isValid() }.reduce { acc, value -> acc && value }
}
private fun Round.isValid(): Boolean {
return red <= validRound.red
&& blue <= validRound.blue
&& green <= validRound.green
}
private fun String.toGame(): Game {
val parts = split(":")
val id = parts.first().replace("Game ", "").toInt()
val rounds = parts.last().split(";").map { it.toRound() }
return Game(id = id, rounds = rounds)
}
private fun String.toRound(): Round {
val parts = split(",").map { it.trim() }
return Round(
red = parts.findAndParse("red"),
blue = parts.findAndParse("blue"),
green = parts.findAndParse("green"),
)
}
private fun List<String>.findAndParse(key: String): Int {
return find { it.endsWith(key) }?.replace(key, "")?.trim()?.toInt() ?: 0
}
}
private fun List<Round>.optimal(): Round {
return Round(
red = maxOf { it.red },
green = maxOf { it.green },
blue = maxOf { it.blue },
)
}
data class Round(
val red: Int,
val blue: Int,
val green: Int,
)
data class Game(
val id: Int,
val rounds: List<Round>,
)
| 0 | Kotlin | 0 | 0 | 7bee985147466cd796e0183d7c719ca6d01b5908 | 1,602 | aoc2023 | Apache License 2.0 |
src/Day03.kt | esteluk | 572,920,449 | false | {"Kotlin": 29185} | fun main() {
fun code(char: Char): Int {
return if (char.isLowerCase()) {
char.code - 96
} else {
char.code - 38
}
}
fun part1(input: List<String>): Int {
val chars = input.map {
val length = it.length
val co1 = it.substring(0, length/2).toCharArray().toSet()
val co2 = it.substring(length/2).toCharArray().asIterable().toSet()
co1.intersect(co2).first()
}.map { code(it) }
return chars.sum()
}
fun part2(input: List<String>): Int {
return input.chunked(3).map { chunk ->
chunk.map { it.toCharArray().toSet() }
.reduce { intersection, set -> intersection.intersect(set) }
.map { code(it) }
.first()
}
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73 | 1,124 | adventofcode-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/number_of_music_playlists/NumberOfPlaylistsTests.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.number_of_music_playlists
import datsok.shouldEqual
import org.junit.jupiter.api.Test
//
// https://leetcode.com/problems/number-of-music-playlists
//
// Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip.
// You create a playlist so that:
// - Every song is played at least once
// - A song can only be played again only if K other songs have been played
// Return the number of possible playlists. As the answer can be very large, return it modulo 10^9 + 7.
// Note: 0 <= K < N <= L <= 100
//
// Example 1:
// Input: N = 3, L = 3, K = 1
// Output: 6
// Explanation: There are 6 possible playlists. [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].
//
// Example 2:
// Input: N = 2, L = 3, K = 0
// Output: 6
// Explanation: There are 6 possible playlists. [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], [1, 2, 2]
//
// Example 3:
// Input: N = 2, L = 3, K = 1
// Output: 2
// Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2]
//
fun numMusicPlaylists(n: Int, l: Int, k: Int): Int {
return musicPlaylists(n, l, k).size
}
fun musicPlaylists(songCount: Int, playlistSize: Int, noRepeat: Int): List<Playlist> {
return musicPlaylists_(songCount, playlistSize, noRepeat)
.filter { it.isValid(songCount, playlistSize, noRepeat) }
.sortedBy { it.toString() }
}
private fun musicPlaylists_(songCount: Int, playlistSize: Int, noRepeat: Int): List<Playlist> {
if (songCount == 0 || playlistSize == 0) return listOf(emptyList())
return (musicPlaylists_(songCount - 1, playlistSize - 1, noRepeat) + musicPlaylists_(songCount, playlistSize - 1, noRepeat))
.flatMap { playlist -> playlist.insertAtAllPositions(songCount) }
.distinct()
}
private fun Playlist.isValid(songCount: Int, playlistSize: Int, noRepeat: Int): Boolean {
return size == playlistSize &&
containsAll((1..songCount).toSet()) &&
(noRepeat == 0 || windowed(size = noRepeat + 1).none { it.allItemsAreEqual() })
}
private fun Playlist.insertAtAllPositions(song: Int): List<Playlist> {
val playlist = ArrayList(this)
return (0..size).map { index ->
ArrayList(playlist).also { it.add(index, song) }
}
}
private fun Playlist.allItemsAreEqual(): Boolean =
size <= 1 || this.all { it == first() }
typealias Playlist = List<Int>
class NumberOfPlaylistsTests {
@Test fun `some examples`() {
musicPlaylists(songCount = 3, playlistSize = 3, noRepeat = 1).toString() shouldEqual
"[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]"
musicPlaylists(songCount = 2, playlistSize = 3, noRepeat = 0).toString() shouldEqual
"[[1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, 2, 1]]"
musicPlaylists(songCount = 2, playlistSize = 3, noRepeat = 1).toString() shouldEqual
"[[1, 2, 1], [2, 1, 2]]"
}
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,975 | katas | The Unlicense |
src/test/kotlin/icfp2019/TestUtils.kt | bspradling | 193,332,580 | true | {"JavaScript": 797310, "Kotlin": 85937, "CSS": 9434, "HTML": 5859} | package icfp2019
import com.google.common.base.CharMatcher
import com.google.common.base.Splitter
import icfp2019.model.*
import org.pcollections.TreePVector
import java.nio.file.Paths
fun loadProblem(problemNumber: Int): String {
val path = Paths.get("problems/prob-${problemNumber.toString().padStart(3, padChar = '0')}.desc").toAbsolutePath()
return path.toFile().readText()
}
fun boardString(p: Problem, path: Set<Node> = setOf()): String {
val lines = mutableListOf<String>()
for (y in (p.size.y - 1) downTo 0) {
val row = (0 until p.size.x).map { x ->
val node = p.map[x][y]
when {
p.startingPosition == Point(x, y) -> '@'
node.isObstacle -> 'X'
node in path -> '|'
node.isWrapped -> 'w'
node.booster != null -> 'o'
else -> '.'
}
}.joinToString(separator = " ")
lines.add(row)
}
return lines.joinToString(separator = "\n")
}
fun printBoard(p: Problem, path: Set<Node> = setOf()) {
println("${p.size}")
print(boardString(p, path))
println()
}
fun String.toProblem(): Problem {
return parseTestMap(this)
}
fun parseTestMap(map: String): Problem {
val mapLineSplitter = Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings()
val lines = mapLineSplitter.splitToList(map)
.map { CharMatcher.whitespace().removeFrom(it) }
.filter { it.isBlank().not() }
.reversed()
val height = lines.size
val width = lines[0].length
if (lines.any { it.length != width }) throw IllegalArgumentException("Inconsistent map line lengths")
val startPoint =
(0 until width).map { x ->
(0 until height).map { y ->
if (lines[y][x] == '@') Point(x, y)
else null
}
}.flatten().find { it != null } ?: Point.origin()
return Problem(MapSize(width, height), startPoint, TreePVector.from((0 until width).map { y ->
TreePVector.from((0 until height).map { x ->
val point = Point(x, y)
when (val char = lines[x][y]) {
'X' -> Node(point, isObstacle = true)
'w' -> Node(point, isObstacle = false, isWrapped = true)
'.' -> Node(point, isObstacle = false)
'@' -> Node(point, isObstacle = false)
in Booster.parseChars -> Node(point, isObstacle = false, booster = Booster.fromChar(char))
else -> throw IllegalArgumentException("Unknown Char '$char'")
}
})
}))
}
| 0 | JavaScript | 0 | 0 | 9f7e48cce858cd6a517d4fb69b9a0ec2d2a69dc5 | 2,605 | icfp-2019 | The Unlicense |
src/twentytwo/Day07.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentytwo
import java.util.*
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("Day07_test")
println(part1(testInput))
check(part1(testInput) == 95_437)
println(part2(testInput))
check(part2(testInput) == 24_933_642)
println("---")
val input = readInputLines("Day07_input")
println(part1(input))
println(part2(input))
testAlternativeSolutions()
}
private interface DirectoryElement {
val size: Int
}
private class Directory(val name: String) : DirectoryElement {
val directoryElements = mutableListOf<DirectoryElement>()
override val size: Int
get() = directoryElements.sumOf { it.size }
fun add(directoryElement: DirectoryElement) {
directoryElements.add(directoryElement)
}
}
private data class DirectoryFile(override val size: Int, val name: String) : DirectoryElement
private sealed interface Command {
object CDHome: Command
object LS: Command
data class Directory(val name: String): Command
data class File(val size: Int, val name: String): Command
data class CDInto(val directoryName: String): Command
object CDOut: Command
}
private fun String.toCommand(): Command {
if (this == "$ cd /") return Command.CDHome
if (this == "$ ls") return Command.LS
if (this == "$ cd ..") return Command.CDOut
if (this.startsWith("dir ")) return Command.Directory(this.removePrefix("dir "))
if (this.startsWith("$ cd ")) return Command.CDInto(this.removePrefix("$ cd "))
val (size, name) = this.split(" ")
return Command.File(size.toInt(), name)
}
private fun part1(input: List<String>): Int {
val homeDirectory = input.toFileStructure()
val dirsUnderSize = dirsUnderSize(homeDirectory, 100_000)
return dirsUnderSize.sumOf { it.size }
}
private fun part2(input: List<String>): Int {
val homeDirectory = input.toFileStructure()
val requiredExtraSpace = homeDirectory.size - (70_000_000 - 30_000_000)
val dirsOverSize = dirsOverSize(homeDirectory, requiredExtraSpace)
return dirsOverSize.minBy { it.size }.size
}
private fun List<String>.toFileStructure(): Directory {
val homeDirectory = Directory("/")
val directoryStack = Stack<Directory>()
directoryStack.push(homeDirectory)
fun currentDirectory() = directoryStack.peek()
this.forEach { inputLine ->
when (val command = inputLine.toCommand()) {
Command.CDHome -> {
directoryStack.empty()
directoryStack.add(homeDirectory)
}
is Command.CDInto -> {
val directoryName = command.directoryName
val dir = currentDirectory().directoryElements.filterIsInstance<Directory>().find { it.name == directoryName }
directoryStack.push(dir)
}
Command.CDOut -> directoryStack.pop()
is Command.Directory -> {
val newDir = Directory(command.name)
if (!currentDirectory().directoryElements.contains(newDir)) {
currentDirectory().add(newDir)
}
}
is Command.File -> {
val newFile = DirectoryFile(command.size, command.name)
if (!currentDirectory().directoryElements.contains(newFile)) {
currentDirectory().add(newFile)
}
}
Command.LS -> {}
}
}
return homeDirectory
}
private fun dirsUnderSize(parentDir: Directory, size: Int): List<Directory> {
val answer = mutableListOf<Directory>()
if (parentDir.size <= size) {
answer.add(parentDir)
}
parentDir.directoryElements.filterIsInstance<Directory>().forEach {
answer.addAll(dirsUnderSize(it, size))
}
return answer
}
private fun dirsOverSize(parentDir: Directory, size: Int): List<Directory> {
val answer = mutableListOf<Directory>()
if (parentDir.size >= size) {
answer.add(parentDir)
}
parentDir.directoryElements.filterIsInstance<Directory>().forEach {
answer.addAll(dirsOverSize(it, size))
}
return answer
}
// ------------------------------------------------------------------------------------------------
private fun testAlternativeSolutions() {
val testInput = readInputLines("Day07_test")
check(part1AlternativeSolution(testInput) == 95_437)
check(part2AlternativeSolution(testInput) == 24_933_642)
println("Alternative Solutions:")
val input = readInputLines("Day07_input")
println(part1AlternativeSolution(input))
println(part2AlternativeSolution(input))
}
private fun part1AlternativeSolution(input: List<String>): Int {
val directories = constructDirMap(input)
return directories.values.filter { it <= 100_000 }.sum()
}
private fun part2AlternativeSolution(input: List<String>): Int {
val directories = constructDirMap(input)
val totalSpace = 70_000_000
val requiredForUpdate = 30_000_000
val usedSpace: Int = directories["/"]!!
val currentFreeSpace = totalSpace - usedSpace
val extraFreeSpaceRequired = requiredForUpdate - currentFreeSpace
return directories.values.filter { it >= extraFreeSpaceRequired }.min()
}
/**
* Return map of directory path to directory size
*/
private fun constructDirMap(input: List<String>): Map<String, Int> {
var currentPath = "/"
val dirMap = mutableMapOf<String, Int>()
for (line in input) {
when {
line.startsWith("$ cd ") -> {
currentPath = when (val dirName = line.substringAfter("$ cd ")) {
"/" -> "/"
".." -> currentPath.substringBeforeLast("/")
else -> if (currentPath == "/") "/$dirName" else "$currentPath/$dirName"
}
}
line[0].isDigit() -> {
val (size, _) = line.split(" ")
var path = currentPath
while (true) {
dirMap[path] = (dirMap[path] ?: 0) + size.toInt()
if (path == "/") break
path = path.substringBeforeLast("/")
if (path == "") path = "/"
}
}
else -> { /* we don't care about this line */ }
}
}
return dirMap
}
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 6,359 | advent-of-code-solutions | Apache License 2.0 |
src/Day02.kt | mlidal | 572,869,919 | false | {"Kotlin": 20582} | import java.lang.IllegalArgumentException
enum class Result {
WIN, LOOSE, DRAW;
companion object {
fun parseResult(name: String) : Result {
return when(name) {
"X" -> LOOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException("Unrecognized name $name")
}
}
}
}
enum class Hand {
ROCK, PAPER, SCISSORS;
companion object {
fun getHand(name: String) : Hand {
return if (name == "A" || name == "X") ROCK else if (name == "B" || name == "Y") PAPER else if (name == "C" || name == "Z") SCISSORS else throw IllegalArgumentException("Unrecognized name $name")
}
fun getHand(other: Hand, result: Result) : Hand {
return when(other) {
ROCK -> when (result) {
Result.WIN -> PAPER
Result.LOOSE -> SCISSORS
Result.DRAW -> ROCK
}
PAPER -> when (result) {
Result.WIN -> SCISSORS
Result.LOOSE -> ROCK
Result.DRAW -> PAPER
}
SCISSORS -> when (result) {
Result.WIN -> ROCK
Result.LOOSE -> PAPER
Result.DRAW -> SCISSORS
}
}
}
}
private fun value() : Int {
return when(this) {
ROCK -> 1
PAPER -> 2
SCISSORS -> 3
}
}
private fun result(other: Hand) : Result {
when(this) {
ROCK -> return when(other) {
ROCK -> Result.DRAW
PAPER -> Result.LOOSE
SCISSORS -> Result.WIN
}
PAPER -> return when(other) {
ROCK -> Result.WIN
PAPER -> Result.DRAW
SCISSORS -> Result.LOOSE
}
SCISSORS -> return when(other) {
ROCK -> Result.LOOSE
PAPER -> Result.WIN
SCISSORS -> Result.DRAW
}
}
}
fun score(other: Hand) : Int {
val result = when(result(other)) {
Result.WIN -> 6
Result.LOOSE -> 0
Result.DRAW -> 3
}
return value() + result
}
}
fun main() {
fun parseLine(line: String) : Pair<Hand, Hand> {
val hands = line.split(" ").map { Hand.getHand(it) }.toList()
if (hands.size == 2) {
return Pair(hands[0], hands[1])
} else {
throw IllegalArgumentException("Unable to parse line $line")
}
}
fun part1(input: List<String>): Int {
val hands = input.map { parseLine(it) }.toList()
val scores = hands.map { it.second.score(it.first) }
return scores.sum()
}
fun parseLine2(line: String) : Pair<Hand, Hand> {
val hands = line.split(" ").take(2)
if (hands.size == 2) {
val other = Hand.getHand(hands[0])
val mine = Hand.getHand(other, Result.parseResult(hands[1]))
return Pair(other, mine)
} else {
throw IllegalArgumentException("Unable to parse line $line")
}
}
fun part2(input: List<String>): Int {
val hands = input.map { parseLine2(it) }.toList()
val scores = hands.map { it.second.score(it.first) }
return scores.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bea7801ed5398dcf86a82b633a011397a154a53d | 3,734 | AdventOfCode2022 | Apache License 2.0 |
src/Day07.kt | rmyhal | 573,210,876 | false | {"Kotlin": 17741} | fun main() {
fun part1(input: List<String>): Long {
return dirsSize(input)
}
fun part2(input: List<String>): Long {
return dirSizeToDelete(input)
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private fun dirsSize(input: List<String>): Long {
return getDirsTree(input).values
.sumOf { if (it <= 100_000) it else 0L }
}
private fun dirSizeToDelete(input: List<String>): Long {
val dirs = getDirsTree(input)
val usedSpace = dirs.getValue(Directory("/", null))
val unusedSpace = 70000000 - usedSpace
val toClean = 30000000 - unusedSpace
return dirs.values
.sorted()
.first { it > toClean }
}
private fun getDirsTree(input: List<String>): MutableMap<Directory, Long> {
var dir: Directory? = null
val dirs = mutableMapOf<Directory, Long>()
input
.forEach { line ->
if (line.startsWith("$")) {
val cmd = line.substringAfter("$ ")
// don't care about ls
if (cmd.startsWith("cd")) {
val dirName = cmd.substringAfter("cd ") // cd
dir = if (dirName != "..") {
Directory(name = dirName, parent = dir)
} else {
dir?.parent
}
}
} else {
// count file
if (line[0].isDigit()) {
val size = line.split(" ")[0].toLong()
dirs[dir!!] = dirs.getOrDefault(dir, 0L) + size
var parent = dir?.parent
while (parent != null) {
dirs[parent] = dirs.getOrDefault(parent, 0L) + size
parent = parent.parent
}
}
}
}
return dirs
}
private data class Directory(
val name: String = "/",
var parent: Directory?,
) | 0 | Kotlin | 0 | 0 | e08b65e632ace32b494716c7908ad4a0f5c6d7ef | 1,695 | AoC22 | Apache License 2.0 |
src/Day04.kt | MwBoesgaard | 572,857,083 | false | {"Kotlin": 40623} | fun main() {
fun doesOneRangeContainTheOther(rangeA: IntRange, rangeB: IntRange): Boolean {
return rangeA.all { it in rangeB } || rangeB.all { it in rangeA }
}
fun doRangesHaveAnyValueThatOverlap(rangeA: IntRange, rangeB: IntRange): Boolean {
return rangeA.any { it in rangeB }
}
fun part1(input: List<String>): Int {
return input
.map {
it.split(",")
.map { joinedStrRange -> joinedStrRange.split("-") }
.map { strRange -> IntRange(strRange[0].toInt(), strRange[1].toInt()) }
}
.count { doesOneRangeContainTheOther(it[0], it[1]) }
}
fun part2(input: List<String>): Int {
return input
.map {
it.split(",")
.map { joinedStrRange -> joinedStrRange.split("-") }
.map { strRange -> IntRange(strRange[0].toInt(), strRange[1].toInt()) }
}
.count { doRangesHaveAnyValueThatOverlap(it[0], it[1]) }
}
printSolutionFromInputLines("Day04", ::part1)
printSolutionFromInputLines("Day04", ::part2)
}
| 0 | Kotlin | 0 | 0 | 3bfa51af6e5e2095600bdea74b4b7eba68dc5f83 | 1,147 | advent_of_code_2022 | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2023/Day5.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2023
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.resultFrom
import kotlin.math.max
import kotlin.math.min
/**
* --- Day 5: If You Give A Seed A Fertilizer ---
* https://adventofcode.com/2023/day/5
*/
class Day5 : Solver {
override fun solve(lines: List<String>): Result {
val seeds = lines[0].split(": ", " ").drop(1).map { it.toLong() }
val seedsA = seeds.map { Range(it, it) }
val seedsB = seeds.windowed(2, 2).map { Range(it[0], it[0] + it[1] - 1) }
val maps = parseMaps(lines.drop(1))
return resultFrom(
solve(seedsA, maps.values),
solve(seedsB, maps.values)
)
}
private fun solve(
seedRanges: List<Range>,
sections: Collection<List<RangeMap>>
): Long {
var lowestLocation = Long.MAX_VALUE
for (seedRange in seedRanges) {
// We start out with only one range, but it might become multiple later as
// we split due to partially matching range mappings.
val values = mutableListOf(seedRange)
for (section in sections) {
// For each section we start with our current values as unmatched. We
// keep updating these as we go through the various range mappings.
val unmatched = values.toMutableList()
val matched = mutableListOf<Range>()
for (mapping in section) {
val unmatchedCopy = unmatched.toList()
unmatched.clear()
for (value in unmatchedCopy) {
val (newMatched, newUnmatched) = intersect(
value,
mapping.src,
mapping.dest
)
matched.addAll(newMatched)
unmatched.addAll(newUnmatched)
}
}
values.clear()
values.addAll(matched)
values.addAll(unmatched)
}
lowestLocation = minOf(lowestLocation, values.minOf { it.from })
}
return lowestLocation
}
}
private fun parseMaps(lines: List<String>): Map<String, List<RangeMap>> {
val result = mutableMapOf<String, MutableList<RangeMap>>()
var currentName = ""
for (line in lines) {
if (line.isNotBlank() && !line[0].isDigit()) {
currentName = line.split(" ")[0]
result[currentName] = mutableListOf()
} else if (line.isNotBlank()) {
val (dest, src, len) = line.split(" ")
result[currentName]!!.add(
RangeMap(
Range(dest.toLong(), dest.toLong() + len.toLong() - 1),
Range(src.toLong(), src.toLong() + len.toLong() - 1)
)
)
}
}
return result
}
private data class RangeMap(
val dest: Range,
val src: Range
)
private fun intersect(seed: Range, from: Range, to: Range): Pair<List<Range>, List<Range>> {
// We need to separate the matched ranges from the unmatched ones since the
// unmatched once will need to be further mapped on other mappings in the
// same section.
val matched = mutableListOf<Range>()
// Define the overlapping/matching range.
val resultFrom = max(seed.from, from.from)
val resultTo = min(seed.to, from.to)
// This will not be true if there is no overlap.
if (resultTo >= resultFrom) {
val rangeDiff = to.from - from.from
matched.add(Range(resultFrom + rangeDiff, resultTo + rangeDiff))
}
// The non-overlapping sections get passed on as-is, unmatched.
val unmatched = mutableListOf<Range>()
if (seed.from < from.from) {
unmatched.add(Range(seed.from, min(from.from - 1, seed.to)))
}
if (seed.to > from.to) {
unmatched.add(Range(max(from.to + 1, seed.from), seed.to))
}
return Pair(matched, unmatched)
}
private data class Range(val from: Long, val to: Long)
| 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 3,636 | euler | Apache License 2.0 |
src/day3/Day03.kt | dean95 | 571,923,107 | false | {"Kotlin": 21240} | package day3
import readInput
private fun main() {
fun part1(input: List<String>): Int {
var prioritiesSum = 0
input.forEach { item ->
val middle = item.length / 2
val firstRucksack = item.substring(0 until middle).toSet()
val secondRucksack = item.substring(middle until item.length).toSet()
firstRucksack.forEach charLoop@{
if (it in secondRucksack) {
prioritiesSum += if (it.isUpperCase()) (it - 'A' + 27) else (it - 'a').inc()
return@charLoop
}
}
}
return prioritiesSum
}
fun part2(input: List<String>): Int {
var prioritiesSum = 0
for (i in 0..input.lastIndex step 3) {
val map = mutableMapOf<Char, Int>()
repeat(3) { groupIndex ->
val s = input[i + groupIndex]
s.toSet().forEach {
map[it] = map.getOrDefault(it, 0).inc()
}
}
for ((char, count) in map) {
if (count == 3) {
prioritiesSum += if (char.isUpperCase()) (char - 'A' + 27) else (char - 'a').inc()
break
}
}
}
return prioritiesSum
}
val testInput = readInput("day3/Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("day3/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0ddf1bdaf9bcbb45116c70d7328b606c2a75e5a5 | 1,530 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2022/day08/TreetopTreeHouse.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day08
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toSlice
import com.barneyb.util.Vec2
import kotlin.math.max
fun main() {
Solver.execute(
::parse,
::visibleTreeCount,
::bestScenicScore,
)
}
private const val MAX_HEIGHT = 9
internal typealias Grid = List<List<Int>>
internal operator fun Grid.get(p: Vec2) =
get(p.y)[p.x]
internal val Grid.height
get() = size
internal val Grid.width
get() = get(0).size
internal fun Grid.contains(p: Vec2) =
p.y in 0 until height && p.x in 0 until width
internal fun parse(input: String) =
input.toSlice()
.trim()
.lines()
.map {
it.map<Int>(Char::digitToInt)
}
internal fun visibleTreeCount(grid: Grid): Int {
val visible = HashSet<Vec2>()
fun scan(start: Vec2, step: (Vec2) -> Vec2) {
visible.add(start)
var curr = start
var tallest = grid[curr]
while (true) {
curr = step(curr)
if (!grid.contains(curr)) break
val h = grid[curr]
if (h > tallest) {
visible.add(curr)
tallest = h
if (tallest == MAX_HEIGHT) break
}
}
}
for (x in 0 until grid.width) {
scan(Vec2(x, 0), Vec2::south)
scan(Vec2(x, grid.height - 1), Vec2::north)
}
for (y in 0 until grid.height) {
scan(Vec2(0, y), Vec2::east)
scan(Vec2(grid.width - 1, y), Vec2::west)
}
return visible.size
}
internal fun scenicScore(grid: Grid, pos: Vec2): Int {
fun scan(step: (Vec2) -> Vec2): Int {
var curr = pos
var count = 0
val max = grid[curr]
var tallest = Int.MIN_VALUE
while (true) {
curr = step(curr)
if (!grid.contains(curr)) break
count += 1
val h = grid[curr]
if (h > tallest) {
tallest = h
if (h >= max) break
}
}
return count
}
return scan(Vec2::north) *
scan(Vec2::south) *
scan(Vec2::east) *
scan(Vec2::west)
}
internal fun bestScenicScore(grid: Grid): Int {
var best = Int.MIN_VALUE
// no need to check the edges, since they're guaranteed zero
for (x in 1 until grid.width - 1) {
for (y in 1 until grid.height - 1) {
best = max(best, scenicScore(grid, Vec2(x, y)))
}
}
return best
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 2,511 | aoc-2022 | MIT License |
src/Day13.kt | floblaf | 572,892,347 | false | {"Kotlin": 28107} | fun main() {
fun parse(input: String): Packet.Data {
if (input.all { it in '0'..'9' }) {
return Packet.Data.Single(input.toInt())
}
if (input == "[]") {
return Packet.Data.Collection()
}
if (input.startsWith("[")) {
var depth = 0
var current = ""
return Packet.Data.Collection(
*buildList {
input.removePrefix("[").forEach { char ->
when {
char == ',' && depth == 0 -> {
add(parse(current))
current = ""
}
char == '[' -> {
depth++
current += char
}
char == ']' -> {
depth--
if (depth == -1) {
add(parse(current))
} else {
current += char
}
}
else -> current += char
}
}
}.toTypedArray()
)
}
throw IllegalStateException()
}
fun part1(input: List<Packet>): Int {
return input
.chunked(2)
.mapIndexed { index, (left, right) ->
if (left < right) {
index + 1
} else {
0
}
}
.sum()
}
fun part2(input: List<Packet>): Int {
val dividerA = Packet(parse("[[2]]"))
val dividerB = Packet(parse("[[6]]"))
val sorted = (input + listOf(dividerA, dividerB))
.sorted()
return (sorted.indexOf(dividerA) + 1) * (sorted.indexOf(dividerB) + 1)
}
val input = readInput("Day13")
.filter { it.isNotBlank() }
.map {
Packet(parse(it))
}
println(input.chunked(2))
println(part1(input))
println(part2(input))
}
data class Packet(
val data: Data
) : Comparable<Packet> {
override fun compareTo(other: Packet): Int {
return data.compareTo(other.data)
}
sealed class Data : Comparable<Data> {
class Collection(
vararg val items: Data
) : Data() {
override fun compareTo(other: Data): Int {
return when (other) {
is Single -> this.compareTo(Collection(other))
is Collection -> {
this.items
.zip(other.items) { l, r -> l.compareTo(r) }
.firstOrNull { it != 0 } ?: items.size.compareTo(other.items.size)
}
}
}
}
class Single(
val value: Int
) : Data() {
override fun compareTo(other: Data): Int {
return when (other) {
is Single -> value.compareTo(other.value)
is Collection -> Collection(this).compareTo(other)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | a541b14e8cb401390ebdf575a057e19c6caa7c2a | 3,331 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | akijowski | 574,262,746 | false | {"Kotlin": 56887, "Shell": 101} | import java.util.*
import kotlin.collections.ArrayDeque
fun main() {
fun List<String>.firstBlankIndex(): Int = this.indexOfFirst { it.isBlank() }
fun toStacks(input: List<String>, splitIdx: Int): List<Stack<Char>> {
//for i in row, if row[i] == num; for j in start-1 downTo 0, if input[j][i] == char; stack.push(char)
//for each number in the row, walk to the top and add each letter to the stack
val boxIdIdx = splitIdx - 1
val cols = boxIdIdx - 1
return buildList {
for (i in input[boxIdIdx].toCharArray().indices) {
if (input[boxIdIdx][i].isDigit()) {
val s = Stack<Char>().apply {
for (j in cols downTo 0) {
if (i in input[j].indices && input[j][i].isLetter()) {
push(input[j][i])
}
}
}
// add the stack
add(s)
}
}
}
}
fun toInstructions(input: String): List<Int> {
return input.split(" ").filter { it.first().isDigit() }.map { it.toInt() }
}
fun moveOneBoxAtATime(instruction: List<Int>, stacks: List<Stack<Char>>) {
val (move, from, to) = instruction
for (i in 1..move) {
stacks[from - 1].pop().let { stacks[to - 1].push(it) }
}
}
fun moveManyBoxesAtATime(instruction: List<Int>, stacks: List<Stack<Char>>) {
val (move, from, to) = instruction
val q = ArrayDeque<Char>()
for (i in 1..move) {
stacks[from - 1].pop().let { q.addFirst(it) }
}
while (q.isNotEmpty()) {
q.removeFirst().let { stacks[to - 1].push(it) }
}
}
fun part1(input: List<String>): String {
val splitIdx = input.firstBlankIndex()
val s = toStacks(input, splitIdx)
input.drop(splitIdx + 1)
.map {
toInstructions(it)
}
.forEach { moveOneBoxAtATime(it, s) }
return s.map { it.peek() }.joinToString("")
}
fun part2(input: List<String>): String {
val splitIdx = input.firstBlankIndex()
val s = toStacks(input, splitIdx)
input.drop(splitIdx + 1)
.map {
toInstructions(it)
}
.forEach { moveManyBoxesAtATime(it, s) }
return s.map { it.peek() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 84d86a4bbaee40de72243c25b57e8eaf1d88e6d1 | 2,762 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day21.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
typealias Operation = (Day21.LinearFunction, Day21.LinearFunction) -> Day21.LinearFunction
class Day21 : Day(21) {
override fun partOne(): Any {
val monkeys = parseMonkeys().associateBy { it.name }
return monkeys.getValue("root").eval(monkeys).b.toLong()
}
override fun partTwo(): Any {
val monkeys = parseMonkeys()
.map { if (it.name == "humn") it.copy(value = LinearFunction(1.0, 0.0)) else it }
.associateBy { it.name }
val (left, right) = monkeys.getValue("root").expr!!
.let { expr ->
monkeys.getValue(expr.left).eval(monkeys) to
monkeys.getValue(expr.right).eval(monkeys)
}
val x = (right.b - left.b) / left.a
return x.toLong()
}
private fun parseMonkeys() = inputList.map {
it.split(": ").let { (key, value) ->
if (value.all(Char::isDigit)) Monkey(key, value.toLong().toLinearFunction())
else {
value.split(" ").let { (left, op, right) ->
val operation: Operation = when (op.first()) {
'+' -> { a, b -> a + b }
'-' -> { a, b -> a - b }
'*' -> { a, b -> a * b }
'/' -> { a, b -> a / b }
else -> throw IllegalArgumentException("Unknown operation: ${op.first()}")
}
Monkey(key, null, Expression(left, right, operation))
}
}
}
}
data class Monkey(val name: String, var value: LinearFunction? = null, val expr: Expression? = null) {
fun eval(others: Map<String, Monkey>): LinearFunction {
if (value == null) {
with (expr!!) {
value = operation(others.getValue(left).eval(others),others.getValue(right).eval(others))
}
}
return value!!
}
}
data class Expression(val left: String, val right: String, val operation: Operation)
// Linear function: ax + b
data class LinearFunction(val a: Double, val b: Double) {
operator fun plus(other: LinearFunction) = LinearFunction(this.a + other.a, this.b + other.b)
operator fun minus(other: LinearFunction) = LinearFunction(this.a - other.a, this.b - other.b)
operator fun times(other: LinearFunction): LinearFunction {
assert(this.a.compareTo(0) == 0 || other.a.compareTo(0) == 0) { "$this * ${other}: function should stay linear, otherwise not supported" }
return LinearFunction(
this.a * other.b + this.b * other.a, this.b * other.b
)
}
operator fun div(other: LinearFunction): LinearFunction {
assert(other.a.compareTo(0) == 0) { "$this / ${other}: function should stay linear, otherwise not supported" }
return LinearFunction(this.a / other.b, this.b / other.b)
}
}
private fun Long.toLinearFunction() = LinearFunction(0.0, this.toDouble())
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 3,082 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/Day13.kt | mjossdev | 574,439,750 | false | {"Kotlin": 81859} | private sealed interface Packet
private data class ListPacket(val packets: List<Packet>) : Packet
private data class IntPacket(val value: Int) : Packet
private class PacketParser private constructor(data: String) {
private val iterator = data.iterator()
private var current: Char = 'd'
fun parse(): Packet {
next()
val packet = parsePacket()
check(!hasNext())
return packet
}
private fun parsePacket(): Packet {
return if (current == '[') {
parseListPacket()
} else {
parseIntPacket()
}
}
private fun parseIntPacket(): IntPacket {
check(current.isDigit())
var value = 0
while (hasNext() && current.isDigit()) {
value = value * 10 + current.digitToInt()
next()
}
return IntPacket(value)
}
private fun parseListPacket(): ListPacket {
check(current == '[')
next()
val list = if (current == ']') {
emptyList()
} else {
buildList {
add(parsePacket())
while (current == ',') {
next()
add(parsePacket())
}
}
}
check(current == ']')
if (hasNext()) {
next()
}
return ListPacket(list)
}
private fun next() {
current = iterator.nextChar()
}
private fun hasNext() = iterator.hasNext()
companion object {
fun parse(data: String) = PacketParser(data).parse()
}
}
fun main() {
fun compare(left: Packet, right: Packet): Int = when (left) {
is ListPacket -> {
val list = when (right) {
is ListPacket -> right.packets
is IntPacket -> listOf(right)
}
lexicographicalCompare(left.packets, list, ::compare)
}
is IntPacket -> {
when (right) {
is IntPacket -> left.value compareTo right.value
is ListPacket -> lexicographicalCompare(listOf(left), right.packets, ::compare)
}
}
}
operator fun Packet.compareTo(other: Packet) = compare(this, other)
fun part1(input: List<String>): Int = input.chunked(3).mapIndexed { index, (left, right) ->
if (PacketParser.parse(left) <= PacketParser.parse(right)) index + 1 else 0
}.sum()
fun part2(input: List<String>): Int {
val dividers = listOf(PacketParser.parse("[[2]]"), PacketParser.parse("[[6]]"))
val packets = (input.filter { it.isNotBlank() }.map(PacketParser::parse) + dividers).sortedWith(::compare)
return dividers.map { packets.indexOf(it) + 1 }.product()
}
// 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 | afbcec6a05b8df34ebd8543ac04394baa10216f0 | 3,022 | advent-of-code-22 | Apache License 2.0 |
src/leetcode_daily_chalange/WordSearch2.kt | faniabdullah | 382,893,751 | false | null | //Given an m x n board of characters and a list of strings words, return all
//words on the board.
//
// Each word must be constructed from letters of sequentially adjacent cells,
//where adjacent cells are horizontally or vertically neighboring. The same letter
//cell may not be used more than once in a word.
//
//
// Example 1:
//
//
//Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i",
//"f","l","v"]], words = ["oath","pea","eat","rain"]
//Output: ["eat","oath"]
//
//
// Example 2:
//
//
//Input: board = [["a","b"],["c","d"]], words = ["abcb"]
//Output: []
//
//
//
// Constraints:
//
//
// m == board.length
// n == board[i].length
// 1 <= m, n <= 12
// board[i][j] is a lowercase English letter.
// 1 <= words.length <= 3 * 10⁴
// 1 <= words[i].length <= 10
// words[i] consists of lowercase English letters.
// All the strings of words are unique.
//
// Related Topics Array String Backtracking Trie Matrix 👍 4722 👎 162
package leetcodeProblem.leetcode.editor.en
class WordSearchIi {
fun solution() {
}
//below code is used to auto submit to leetcode.com (using ide plugin)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
private val ans = mutableSetOf<String>()
private val root = Word('#')
lateinit var board: Array<CharArray>
fun findWords(board: Array<CharArray>, words: Array<String>): List<String> {
if (board.isEmpty() || board[0].isEmpty()) return ans.toList()
this.board = board
for (word in words) {
var parent = root
for (char in word) {
var node = parent.map[char]
if (node == null) {
node = Word(char)
parent.map[char] = node
}
parent = node
}
parent.isCompleted = true
}
val builder = StringBuilder()
for (x in board.indices) {
for (y in board[0].indices) {
val curChar = board[x][y]
builder.clear()
getWords(x, y, root.map[curChar], builder)
}
}
return ans.toList()
}
private fun getWords(x: Int, y: Int, node: Word?, builder: StringBuilder) {
if (node == null || board[x][y] == '$') return
val curChar = board[x][y]
board[x][y] = '$'
builder.append(curChar)
if (node.isCompleted) ans.add(builder.toString())
if (isValid(x + 1, y))
getWords(x + 1, y, node.map[board[x + 1][y]], builder)
if (isValid(x - 1, y))
getWords(x - 1, y, node.map[board[x - 1][y]], builder)
if (isValid(x, y + 1))
getWords(x, y + 1, node.map[board[x][y + 1]], builder)
if (isValid(x, y - 1))
getWords(x, y - 1, node.map[board[x][y - 1]], builder)
builder.deleteCharAt(builder.lastIndex)
board[x][y] = curChar
}
private fun isValid(x: Int, y: Int): Boolean {
return x >= 0 && y >= 0 && x < board.size && y < board[0].size
}
}
data class Word(val char: Char) {
val map = mutableMapOf<Char, Word>()
var isCompleted = false
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 3,520 | dsa-kotlin | MIT License |
year2019/src/main/kotlin/net/olegg/aoc/year2019/day22/Day22.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2019.day22
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2019.DayOf2019
import java.math.BigInteger
/**
* See [Year 2019, Day 22](https://adventofcode.com/2019/day/22)
*/
object Day22 : DayOf2019(22) {
override fun first(): Any? {
val deckSize = BigInteger.valueOf(10007L)
val input = lines
.map {
val split = it.split(" ")
when (split[1]) {
"into" -> Pair(BigInteger.valueOf(-1L), BigInteger.valueOf(-1L))
"with" -> Pair(split.last().toBigInteger(), BigInteger.ZERO)
else -> Pair(BigInteger.ONE, -split[1].toBigInteger())
}
}
val compressed = input.reduce { acc, vector -> combine(acc, vector, deckSize) }
return shuffle(BigInteger.valueOf(2019L), deckSize, BigInteger.ONE, compressed)
}
override fun second(): Any? {
val deckSize = BigInteger.valueOf(119315717514047L)
val input = lines
.map {
val split = it.split(" ")
when (split[1]) {
"into" -> Pair(BigInteger.valueOf(-1L), BigInteger.valueOf(-1L))
"with" -> Pair(split.last().toBigInteger() inv deckSize, BigInteger.ZERO)
else -> Pair(BigInteger.ONE, split[1].toBigInteger())
}
}
.asReversed()
val compressed = input.reduce { acc, vector -> combine(acc, vector, deckSize) }
return shuffle(BigInteger.valueOf(2020L), deckSize, BigInteger.valueOf(101741582076661L), compressed)
}
private fun shuffle(
position: BigInteger,
deckSize: BigInteger,
iterations: BigInteger,
operation: Pair<BigInteger, BigInteger>
): BigInteger {
return generateSequence(Triple(position, iterations, operation)) { (curr, iters, op) ->
val newOp = combine(op, op, deckSize)
val next = if (iters.testBit(0)) (curr * op.first + op.second) mod deckSize else curr
return@generateSequence Triple(next, iters shr 1, newOp)
}
.first { it.second == BigInteger.ZERO }
.first
}
private infix fun BigInteger.mod(modulo: BigInteger): BigInteger {
return (this % modulo + modulo) % modulo
}
private infix fun BigInteger.inv(modulo: BigInteger): BigInteger {
return generateSequence(Triple(BigInteger.ONE, modulo - BigInteger.valueOf(2), this)) { (curr, iters, power) ->
val next = if (iters.testBit(0)) (curr * power) mod modulo else curr
return@generateSequence Triple(next, iters shr 1, (power * power) mod modulo)
}
.first { it.second == BigInteger.ZERO }
.first
}
private fun combine(
first: Pair<BigInteger, BigInteger>,
second: Pair<BigInteger, BigInteger>,
modulo: BigInteger
) = Pair((first.first * second.first) mod modulo, (first.second * second.first + second.second) mod modulo)
}
fun main() = SomeDay.mainify(Day22)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,804 | adventofcode | MIT License |
src/main/kotlin/solutions/CHK/CheckoutSolution.kt | DPNT-Sourcecode | 690,804,775 | false | {"Kotlin": 16401, "Shell": 2184} | package solutions.CHK
data class Product(val price: Int, val offers: List<Offer> = listOf())
data class Offer(
val requiredCount: Int,
val price: Int,
val freeItem: Char? = null,
val freeItemCount: Int = 1,
val groupItems: List<Char>? = null
)
object CheckoutSolution {
private var productMap = mutableMapOf<Char, Product>(
'A' to Product(50, listOf(Offer(5,200), Offer(3, 130))),
'B' to Product(30, listOf(Offer(2, 45))),
'C' to Product(20),
'D' to Product(15),
'E' to Product(40, listOf(Offer(2, 80, 'B'))),
'F' to Product(10, listOf(Offer(3, 20))),
'G' to Product(20),
'H' to Product(10, listOf(Offer(10, 80), Offer(5, 45))),
'I' to Product(35),
'J' to Product(60),
'K' to Product(70, listOf(Offer(2, 120))),
'L' to Product(90),
'M' to Product(15),
'N' to Product(40, listOf(Offer(3, 120, 'M'))),
'O' to Product(10),
'P' to Product(50, listOf(Offer(5, 200))),
'Q' to Product(30, listOf(Offer(3, 80))),
'R' to Product(50, listOf(Offer(3, 150, 'Q'))),
'S' to Product(20, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))),
'T' to Product(20, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))),
'U' to Product(40, listOf(Offer(4,120))),
'V' to Product(50, listOf(Offer(3, 130), Offer(2, 90))),
'W' to Product(20),
'X' to Product(17, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))),
'Y' to Product(20, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))),
'Z' to Product(21, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))),
)
fun checkout(skus: String): Int {
val itemCounts = skus.groupingBy { it }.eachCount().toMutableMap()
if (itemCounts.keys.any { it !in productMap }) return -1
var total = 0
total += processFreeItems(itemCounts)
total += processGroupDiscounts(itemCounts)
total += processRegularDiscountsAndRemainingItems(itemCounts)
return total
}
private fun processRegularDiscountsAndRemainingItems(itemCounts: MutableMap<Char, Int>): Int {
var total = 0
itemCounts.forEach { p ->
val productChar = p.key
var count = p.value
val product = productMap[productChar]!!
product.offers
.filter { it.groupItems == null && it.freeItem == null }
.sortedByDescending { o -> o.requiredCount }
.forEach { offer ->
while(count >= offer.requiredCount) {
total += offer.price
count -= offer.requiredCount
}
}
total += count * product.price
}
return total
}
private fun processGroupDiscounts(itemCounts: MutableMap<Char, Int>): Int {
var total = 0
productMap.values.forEach { product ->
val groupOffers = product.offers.filter { it.groupItems != null }
groupOffers.forEach { offer ->
val eligibleGroupItems = offer.groupItems!!.associateWith {
itemCounts.getOrDefault(it, 0)
}.toMutableMap()
while (eligibleGroupItems.values.sum() >= offer.requiredCount) {
total += offer.price
var itemsNeededForDiscount = offer.requiredCount
for ((item, availabeCount) in eligibleGroupItems.entries.sortedByDescending {
productMap[it.key]!!.price
}) {
val itemsToUseForDiscount = minOf(availabeCount, itemsNeededForDiscount)
eligibleGroupItems[item] = availabeCount - itemsToUseForDiscount
itemCounts[item] = itemCounts.getOrDefault(item, 0) - itemsToUseForDiscount
itemsNeededForDiscount -= itemsToUseForDiscount
}
}
}
}
return total
}
private fun processFreeItems(itemCounts: MutableMap<Char, Int>): Int {
var total = 0
productMap.forEach { (productChar, product) ->
var count = itemCounts.getOrDefault(productChar, 0)
product.offers.filter { it.freeItem != null }.sortedByDescending { it.requiredCount }.forEach { offer ->
while (count >= offer.requiredCount && (itemCounts[offer.freeItem] ?: 0) >= offer.freeItemCount) {
total += offer.price
count -= offer.requiredCount
itemCounts[offer.freeItem!!] = maxOf(0, itemCounts[offer.freeItem]!! - offer.freeItemCount)
}
}
itemCounts[productChar] = count
}
return total
}
} | 0 | Kotlin | 0 | 0 | 035af07445aefe0270570419abf5b96e8c04b3a0 | 4,915 | CHK-ojzb01 | Apache License 2.0 |
src/Day04.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun IntRange.contains(other: IntRange) = other.first in this && other.last in this
fun IntRange.overlaps(other: IntRange) = max(first, other.first) <= min(last, other.last)
fun <T> List<T>.toPair(): Pair<T, T> =
if (this.size != 2) throw IllegalArgumentException("List is not of length 2!")
else Pair(this[0], this[1])
fun String.toPairOfRanges(): Pair<IntRange, IntRange> = this.split(',', '-')
.map { it.toInt() }
.chunked(2)
.map { IntRange(it[0], it[1]) }
.toPair()
fun part1(input: List<String>): Int =
input.count { line ->
line.toPairOfRanges().let { (a, b) -> a.contains(b) || b.contains(a) }
}
fun part2(input: List<String>): Int =
input.count { line ->
line.toPairOfRanges().let { (a, b) -> a.overlaps(b) }
}
// 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 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 1,187 | advent-of-code-kotlin-2022 | Apache License 2.0 |
app/src/y2021/day12/Day12PassagePathing.kt | henningBunk | 432,858,990 | false | {"Kotlin": 124495} | package y2021.day12
import common.Answers
import common.AocSolution
import common.annotations.AoCPuzzle
fun main(args: Array<String>) {
Day12PassagePathing().solveThem()
}
@AoCPuzzle(2021, 12)
class Day12PassagePathing : AocSolution {
override val answers = Answers(samplePart1 = 19, samplePart2 = 103, part1 = 3887, part2 = 104834)
lateinit var caves: Map<String, List<String>>
override fun solvePart1(input: List<String>): Any {
initCaveMap(input)
return findNumberOfPossibleRoutes("start", emptyList())
}
override fun solvePart2(input: List<String>): Any {
initCaveMap(input)
return findNumberOfPossibleRoutes("start", emptyList(), mayVisitOneSmallCaveTwice = true)
}
private fun initCaveMap(input: List<String>) {
val mapBuilder = mutableMapOf<String, MutableList<String>>()
input.forEach {
it.split("-").let { (a, b) ->
mapBuilder.getOrPut(a) { mutableListOf() }.add(b)
mapBuilder.getOrPut(b) { mutableListOf() }.add(a)
}
}
caves = mapBuilder
}
private fun findNumberOfPossibleRoutes(
visit: String,
visited: List<String>,
mayVisitOneSmallCaveTwice: Boolean = false,
): Int {
if (visit == "end") return 1
val nowVisited = visited.toMutableList().apply { add(visit) }.toList()
val neighboursICanVisit = caves[visit]?.filter { neighbour ->
when {
neighbour == "start" -> false
neighbour.first().isLowerCase() -> {
neighbour !in visited || (mayVisitOneSmallCaveTwice && !hasVisitedASmallCaveTwiceAlready(nowVisited))
}
else -> true
}
}
if (neighboursICanVisit?.isEmpty() == true) return 0
return neighboursICanVisit?.sumOf { neighbour ->
findNumberOfPossibleRoutes(
visit = neighbour,
visited = nowVisited,
mayVisitOneSmallCaveTwice = mayVisitOneSmallCaveTwice
)
} ?: 0
}
private fun hasVisitedASmallCaveTwiceAlready(visited: List<String>): Boolean {
val smallCavesVisited = visited.filter { it.first().isLowerCase() && it != "start" }
return smallCavesVisited.size != smallCavesVisited.distinct().size
}
}
| 0 | Kotlin | 0 | 0 | 94235f97c436f434561a09272642911c5588560d | 2,372 | advent-of-code-2021 | Apache License 2.0 |
src/Day04.kt | ajspadial | 573,864,089 | false | {"Kotlin": 15457} | fun main() {
fun getRange(rangeString: String): IntRange {
val values = rangeString.split("-")
val min = values[0].toInt()
val max = values[1].toInt()
return min..max
}
fun part1(input: List<String>): Int {
var score = 0
for (lines in input) {
val pair = lines.split(",")
val range1 = getRange(pair[0])
val range2 = getRange(pair[1])
if (range1.first in range2 && range1.last in range2 || range2.first in range1 && range2.last in range1) {
score++
}
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (lines in input) {
val pair = lines.split(",")
val range1 = getRange(pair[0])
val range2 = getRange(pair[1])
if (range1.first in range2 || range1.last in range2 || range2.first in range1 || range2.last in range1) {
score++
}
}
return score
}
// 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 | ed7a2010008be17fec1330b41adc7ee5861b956b | 1,317 | adventofcode2022 | Apache License 2.0 |
17/src/main/kotlin/EggNogContainers.kt | kopernic-pl | 109,750,709 | false | null | import com.google.common.collect.Sets.combinations
internal val CONTAINERS = """
33
14
18
20
45
35
16
35
1
13
18
13
50
44
48
6
24
41
30
42
""".trimIndent().lines().map { it.toInt() }
internal const val EXPECTED_VOLUME = 150
internal fun generateCombinationsOfIndices(numberOfElements: Int): List<Set<Int>> {
val indices = (0 until numberOfElements).toSet()
return (1..numberOfElements).flatMap { size -> combinations(indices, size) }
}
internal fun indexesToSumOfContainerVolumes(indices: Set<Int>): Int {
return indices.fold(0) { acc, idx -> acc + CONTAINERS[idx] }
}
fun main() {
generateCombinationsOfIndices(CONTAINERS.size)
.map(::indexesToSumOfContainerVolumes)
.filter { it == EXPECTED_VOLUME }
.also { println("Number of combinations that holds $EXPECTED_VOLUME liters: ${it.size}") }
val m = generateCombinationsOfIndices(CONTAINERS.size)
.map { c -> c to indexesToSumOfContainerVolumes(c) }
.filter { (_, size) -> size == EXPECTED_VOLUME }
.map { (set, _) -> set to set.size }
.toMap()
m.filterValues { it == m.values.minOrNull() }
.also { println("Number of combinations with smallest (${m.values.minOrNull()}) number of containers: ${it.size}") }
}
| 0 | Kotlin | 0 | 0 | 06367f7e16c0db340c7bda8bc2ff991756e80e5b | 1,336 | aoc-2015-kotlin | The Unlicense |
day1/src/main/kotlin/com/lillicoder/adventofcode2023/day1/Day1.kt | lillicoder | 731,776,788 | false | {"Kotlin": 98872} | package com.lillicoder.adventofcode2023.day1
fun main() {
val day1 = Day1()
val calibrationDocument = CalibrationDocumentParser().parse("input.txt")
println("[Part 1] The sum of calibration values is ${day1.part1(calibrationDocument)}.")
println("[Part 2] The sum of calibration values is ${day1.part2(calibrationDocument)}.")
}
class Day1 {
fun part1(document: List<String>) =
document.sumOf { line ->
"${line.find { it.isDigit() }}${line.findLast { it.isDigit() }}".toInt()
}.toLong()
fun part2(
document: List<String>,
finder: CalibrationValueFinder = CalibrationValueFinder(),
) = document.sumOf { line ->
finder.find(line)
}.toLong()
}
class CalibrationDocumentParser {
/**
* Parses the calibration document from the file with the given filename.
* @param filename Filename.
* @return Calibration document.
*/
fun parse(filename: String) = javaClass.classLoader.getResourceAsStream(filename)!!.reader().readLines()
}
/**
* Utility that can find calibration values from a calibration document.
*/
class CalibrationValueFinder {
/**
* Map of the digits 1 through 9 to their English-language word equivalent.
*/
private val wordToNumber: Map<String, Int> =
mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
)
/**
* Parses the given line to find the first and last digit and concatenate them to a single value.
* @param line Line to parse.
* @return Calibration value.
*/
fun find(line: String) = "${findFirstDigit(line)}${findLastDigit(line)}".toInt()
/**
* Finds the first digit in the given line. Both numeric characters and numeric words
* will be parsed.
* @param line Line to parse.
* @return First digit.
*/
private fun findFirstDigit(line: String): Int {
val digitsByPosition = mutableMapOf<Int, Int>()
// Pack first digit (if any) into a map of position -> digit
line.firstOrNull { it.isDigit() }?.let { digitsByPosition[line.indexOf(it)] = it.digitToInt() }
// Pack position for "one" through "nine" into map of position -> digit
wordToNumber.map {
(it.key.toRegex().findAll(line).firstOrNull()?.range?.first ?: Int.MAX_VALUE) to it.value
}.toMap(digitsByPosition)
// Smallest key is the first digit value in the line
return digitsByPosition[digitsByPosition.keys.min()]!!
}
/**
* Finds the last digit in the given line. Both numeric characters and numeric words
* will be parsed.
* @param line Line to parse.
* @return Last digit.
*/
private fun findLastDigit(line: String): Int {
val digitsByPosition = mutableMapOf<Int, Int>()
// Pack last digit (if any) into a map of position -> digit
line.lastOrNull { it.isDigit() }?.let { digitsByPosition[line.lastIndexOf(it)] = it.digitToInt() }
// Pack position for "one" through "nine" into map of position -> digit
wordToNumber.map {
(it.key.toRegex().findAll(line).lastOrNull()?.range?.last ?: Int.MIN_VALUE) to it.value
}.toMap(digitsByPosition)
// Largest key is the last digit value in the line
return digitsByPosition[digitsByPosition.keys.max()]!!
}
}
| 0 | Kotlin | 0 | 0 | 390f804a3da7e9d2e5747ef29299a6ad42c8d877 | 3,513 | advent-of-code-2023 | Apache License 2.0 |
src/day04/day04.kt | PS-MS | 572,890,533 | false | null | package day04
import readInput
fun main() {
fun String.toIntRange(): IntRange {
val (min, max) = this.split("-").map { it.toInt() }
return IntRange(min, max)
}
operator fun IntRange.contains(other: IntRange): Boolean {
return (this.min() >= other.min() && this.max() <= other.max() ||
other.min() >= this.min() && other.max() <= this.max())
}
fun IntRange.overlaps(other: IntRange): Boolean {
val otherList = other.toList()
return this.find { otherList.contains(it) } != null
}
fun part1(input: List<String>): Int {
return input.map { it.split(",") }.filter {
val (first, second) = it
val firstRange = first.toIntRange()
val secondRange = second.toIntRange()
firstRange in secondRange
}.size
}
fun part2(input: List<String>): Int {
return input.map { it.split(",") }.filter {
val (first, second) = it
val firstRange = first.toIntRange()
val secondRange = second.toIntRange()
firstRange.overlaps(secondRange)
}.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day04/test")
val p1Test = part1(testInput)
println("p1 test = $p1Test")
check(p1Test == 2)
val p2Test = part2(testInput)
println("p2 test = $p2Test")
check(part2(testInput) == 4)
val input = readInput("day04/real")
val p1Real = part1(input)
println("p1 real = $p1Real")
val p2Real = part2(input)
println("p2 real = $p2Real")
} | 0 | Kotlin | 0 | 0 | 24f280a1d8ad69e83755391121f6107f12ffebc0 | 1,625 | AOC2022 | Apache License 2.0 |
src/main/kotlin/Day03.kt | dliszewski | 573,836,961 | false | {"Kotlin": 57757} | class Day03 {
fun part1(input: List<String>): Int {
return input
.map { Rucksack(it) }
.flatMap { it.getCompartmentIntersection() }
.sumOf { it.toPriorityScore() }
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map { (elf1, elf2, elf3) -> Triple(Rucksack(elf1), Rucksack(elf2), Rucksack(elf3)) }
.map { it.first.getCompartmentIntersectionFrom(it.second, it.third).single() }
.sumOf { it.toPriorityScore() }
}
class Rucksack(private val content: String) {
fun getCompartmentIntersection(): Set<Char> {
val splitIndex = if (content.length % 2 == 0) content.length / 2 else content.length / 2 + 1
val first = content.take(splitIndex).toSet()
val second = content.substring(splitIndex).toSet()
return first.intersect(second)
}
fun getCompartmentIntersectionFrom(other: Rucksack, another: Rucksack): Set<Char> {
return content.toSet()
.intersect(other.content.toSet())
.intersect(another.content.toSet())
}
}
private fun Char.toPriorityScore(): Int {
return when {
// Lowercase item types a through z have priorities 1 through 26.
isLowerCase() -> this - 'a' + 1
// Uppercase item types A through Z have priorities 27 through 52.
isUpperCase() -> this - 'A' + 27
else -> error("Wrong input")
}
}
} | 0 | Kotlin | 0 | 0 | 76d5eea8ff0c96392f49f450660220c07a264671 | 1,550 | advent-of-code-2022 | Apache License 2.0 |
src/day_5/kotlin/Day5.kt | Nxllpointer | 573,051,992 | false | {"Kotlin": 41751} | // AOC Day 5
typealias Container = Char
typealias ContainerStack = ArrayDeque<Container>
typealias StackNumber = Int
data class MoveInstruction(val amount: Int, val from: Int, val to: Int)
fun Map<StackNumber, ContainerStack>.deepCopy(): Map<StackNumber, ContainerStack> {
return toMap().mapValues { ArrayDeque(it.value) }
}
fun part1(stacks: Map<StackNumber, ContainerStack>, instructions: Collection<MoveInstruction>) {
instructions.forEach { (amount, from, to) ->
repeat(amount) {
stacks[from]!!.removeFirst().also { stacks[to]!!.addFirst(it) }
}
}
val topContainersText = stacks.toSortedMap().values.map { it.first() }.joinToString("")
println("Part 1: The top most containers form the text $topContainersText")
}
fun part2(stacks: Map<StackNumber, ContainerStack>, instructions: Collection<MoveInstruction>) {
instructions.forEach { (amount, from, to) ->
val transferStack = ContainerStack()
repeat(amount) {
stacks[from]!!.removeFirst().also { transferStack.addFirst(it) }
}
repeat(amount) {
transferStack.removeFirst().also { stacks[to]!!.addFirst(it) }
}
}
val topContainersText = stacks.toSortedMap().values.map { it.first() }.joinToString("")
println("Part 2: The top most containers form the text $topContainersText")
}
val INSTRUCTION_REGEX = Regex("\\d+")
fun main() {
val (stacks, instructions) = getAOCInput { rawInput ->
val (sectionStacks, sectionInstructions) = rawInput.trim('\n').splitInTwo("\n\n").run {
first.split("\n") to second.split("\n")
}
val stacks = mutableMapOf<StackNumber, ContainerStack>()
sectionStacks.last().forEachIndexed { charIndex, char ->
if (char.isDigit()) {
val stack = ContainerStack().also { stacks[char.digitToInt()] = it }
for (layer in sectionStacks.dropLast(1).reversed()) {
val containerLabel = layer[charIndex]
if (containerLabel.isLetter()) stack.addFirst(layer[charIndex])
}
}
}
val instructions = sectionInstructions.map { rawInstruction ->
val instructionValues = INSTRUCTION_REGEX.findAll(rawInstruction).toList().map { it.value }.mapToInt()
MoveInstruction(instructionValues[0], instructionValues[1], instructionValues[2])
}
stacks to instructions
}
part1(stacks.deepCopy(), instructions)
part2(stacks.deepCopy(), instructions)
}
| 0 | Kotlin | 0 | 0 | b6d7ef06de41ad01a8d64ef19ca7ca2610754151 | 2,560 | AdventOfCode2022 | MIT License |
src/Day04.kt | kkaptur | 573,511,972 | false | {"Kotlin": 14524} | fun main() {
fun getRanges(input: List<String>): Pair<List<Int>, List<Int>> = Pair(
input[0].split("-").let { IntRange(it[0].toInt(), it[1].toInt()) }.toList(),
input[1].split("-").let { IntRange(it[0].toInt(), it[1].toInt()) }.toList()
)
fun part1(input: List<String>): Int = input.count { pair ->
with(pair.split(",")) {
val ranges = getRanges(this)
ranges.first.minus(ranges.second.toSet()).isEmpty()
|| ranges.second.minus(ranges.first.toSet()).isEmpty()
}
}
fun part2(input: List<String>): Int = input.count { pair ->
with(pair.split(",")) {
val ranges = getRanges(this)
ranges.first.any { ranges.second.contains(it) }
}
}
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 | 055073b7c073c8c1daabbfd293139fecf412632a | 971 | AdventOfCode2022Kotlin | Apache License 2.0 |
src/Day05.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | import kotlin.math.absoluteValue
import kotlin.reflect.KType
import kotlin.reflect.typeOf
import kotlin.streams.toList
class Line2D constructor(points: List<List<Int>>) {
val support: Pair<Int, Int>
val direction: Pair<Int, Int>
init {
support = Pair(points[0][0], points[0][1])
val tmp = Pair(points[1][0], points[1][1])
direction = tmp - support
}
fun getPoints(part: Int): List<Pair<Int, Int>> {
if (part == 1 && direction.first != 0 && direction.second != 0) {
return listOf()
}
val maxD = direction.toList().maxOf { i -> i.absoluteValue }
val ndir = direction.map { it / maxD }
return (0..maxD).map { support + ndir * it }
}
}
fun main() {
fun part1(input: List<Line2D>): Int {
val points = HashMap<Pair<Int, Int>, Int>()
for (l in input) {
for (ps in l.getPoints(1)) {
val v = if (points[ps] == null) 1 else points[ps]?.plus(1)!!
points[ps] = v
}
}
return points.count { it.value > 1 }
}
fun part2(input: List<Line2D>): Int {
val points = HashMap<Pair<Int, Int>, Int>()
for (l in input) {
for (ps in l.getPoints(2)) {
val v = if (points[ps] == null) 1 else points[ps]?.plus(1)!!
points[ps] = v
}
}
return points.count { it.value > 1 }
}
fun preprocessing(input: String): List<Line2D> {
return input.trim().split("\n").map {
val tmp = it.trim().split(" -> ").map { s -> s.split(",").map { s1 -> s1.toInt() } }
Line2D(tmp)
}.toList()
}
val realInp = read_testInput("real5")
val testInp = read_testInput("test5")
// 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,035 | advent_of_code21_kotlin | Apache License 2.0 |
src/main/java/challenges/coderbyte/BoggleSolver.kt | ShabanKamell | 342,007,920 | false | null | package challenges.coderbyte
/*
Have the function BoggleSolver(strArr) read the array of strings stored in strArr,
which will contain 2 elements: the first element will represent a 4x4 matrix of
letters, and the second element will be a long string of comma-separated words
each at least 3 letters long, in alphabetical order, that represents a dictionary
of some arbitrary length. For example: strArr can be: ["rbfg, ukop, fgub, mnry",
"bog,bop,gup,fur,ruk"]. Your goal is to determine if all the comma separated words
as the second parameter exist in the 4x4 matrix of letters. For this example,
the matrix looks like the following:
r b f g
u k o p
f g u b
m n r y
The rules to make a word are as follows:
1. A word can be constructed from sequentially adjacent spots in the matrix,
where adjacent means moving horizontally, vertically, or diagonally in any direction.
2. A word cannot use the same location twice to construct itself.
The rules are similar to the game of Boggle. So for the example above,
all the words exist in that matrix so your program should return the string true.
If all the words cannot be found, then return a comma separated string of the words
that cannot be found, in the order they appear in the dictionary.
Use the Parameter Testing feature in the box below to test your code with different arguments.
Solution: https://www.geeksforgeeks.org/boggle-set-2-using-trie/
*/
/*
Solution Steps:
1- Put all words in a Trie.
2- Iterate over each char in boggle.
3- Get the char node in Trie if found.
4- Depth-First Search each trie node to see if we can get a word
*/
object BoggleSolver {
private var dirX = intArrayOf(-1, -1, -1, 0, 1, 0, 1, 1)
private var dirY = intArrayOf(-1, 1, 0, -1, -1, 1, 0, 1)
private fun findWords(strArr: Array<String>): String {
val boggle = strArr[0]
.split(", ")
.map { it.toCharArray() }
.toTypedArray()
val words = strArr[1]
.split(", ")
.toTypedArray()
val trie = Trie()
trie.insert(words)
val result = findWords(boggle, trie)
if (result.size == words.size) {
return "true"
}
return words.filter { !result.contains(it) }
.joinToString(",")
}
// Prints all words present in dictionary.
private fun findWords(boggle: Array<CharArray>, trie: Trie): MutableSet<String> {
// Mark all characters as not visited
val visited = Array(boggle.size) { BooleanArray(boggle[0].size) }
val result: MutableSet<String> = HashSet()
// traverse all matrix elements
for (i in boggle.indices) {
for (j in boggle[0].indices) {
// we start searching for word in dictionary
// if we found a character which is child
// of Trie root
val ch = boggle[i][j]
val index = indexOf(ch)
val node = trie.root.child[index] ?: continue
searchWord(node, boggle, i, j, visited, ch.toString(), result)
}
}
return result
}
// A recursive function to print
// all words present on boggle
private fun searchWord(
root: TrieNode,
boggle: Array<CharArray>,
i: Int,
j: Int,
visited: Array<BooleanArray>,
word: String,
result: MutableSet<String>
) {
if (root.isWord) result.add(word)
// make it visited
visited[i][j] = true
for (k in 0..25) {
val child = root.child[k] ?: continue
val ch = toChar(k)
// skip if a cell is invalid, or it is already visited
for (n in 0..7) {
val x = i + dirX[n]
val y = j + dirY[n]
if (!(isSafe(x, y, boggle, visited))) continue
if (boggle[x][y] != ch) continue
searchWord(child, boggle, x, y, visited, word + ch, result)
}
}
// make current element unvisited
visited[i][j] = false
return
}
// function to check that current location
// (i and j) is in matrix range
private fun isSafe(
i: Int,
j: Int,
board: Array<CharArray>,
visited: Array<BooleanArray>
): Boolean {
return i in board.indices && j in board[0].indices && !visited[i][j]
}
class Trie {
var root: TrieNode = TrieNode()
// If not present, inserts a key into the trie
// If the key is a prefix of trie node, just
// marks leaf node
fun insert(words: Array<String>) {
for (element in words) insert(element)
}
fun insert(key: String) {
val n = key.length
var pChild = root
for (i in 0 until n) {
val index = indexOf(key[i])
if (pChild.child[index] == null) pChild.child[index] = TrieNode()
pChild = pChild.child[index]!!
}
// make last node as leaf node
pChild.isWord = true
}
}
// trie Node
class TrieNode {
var child = arrayOfNulls<TrieNode>(26)
// isWord is true if the node represents
// end of a word
var isWord = false
}
private fun toChar(c: Int): Char {
return (c + 'a'.toInt()).toChar()
}
private fun indexOf(c: Char): Int {
// subtract from a to convert unicode number to a number from 0 to 26.
return c - 'a'
}
@JvmStatic
fun main(args: Array<String>) {
val input = arrayOf(
"aaey, rrum, tgmn, ball",
"all, ball, mur, raeymnl, tall, true, trum"
)
val input2 = arrayOf(
"aaey, rrum, tgmn, ball",
"all, ball, mur, raeymnl, rumk, tall, true, trum, yes"
)
println(findWords(input))
println(findWords(input2))
}
}
| 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 5,959 | CodingChallenges | Apache License 2.0 |
src/Day05.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | import java.lang.Long.min
import kotlin.math.max
private const val EXPECTED_1 = 35L
private const val EXPECTED_2 = 46L
private class Day05(isTest: Boolean) : Solver(isTest) {
val transitions = listOf("seed-to-soil", "soil-to-fertilizer", "fertilizer-to-water", "water-to-light", "light-to-temperature", "temperature-to-humidity", "humidity-to-location")
val seeds = mutableListOf<Long>()
var mappings = mutableMapOf<String, MutableList<Triple<Long, Long, Long>>>()
fun parse() {
var mapName = ""
for (line in readAsLines()) {
if (line.startsWith("seeds:")) {
seeds.addAll(line.splitLongs())
} else {
if (line.contains("map:")) {
mapName = line.substringBefore(" ")
}
if (line.any { it.isDigit() }) {
val parts = line.split(" ")
val map = mappings.getOrPut(mapName) { mutableListOf() }
map.add(Triple(parts[0].toLong(), parts[1].toLong(), parts[2].toLong()))
}
}
}
}
fun part1(): Any {
parse()
var lowest = Long.MAX_VALUE
for (seed in seeds) {
var number = seed
for (transition in transitions) {
var newNumber = number
val map = mappings[transition] ?: error("No mapping for $transition")
for (t in map) {
if (number >= t.second && number < t.second + t.third) {
newNumber = t.first + (number - t.second)
}
}
number = newNumber
}
lowest = min(lowest, number)
}
return lowest
}
fun part2(): Any {
parse()
var lowest = Long.MAX_VALUE
for ((seedStart, seedLen) in seeds.chunked(2)) {
var seed = seedStart
while (seed < seedStart + seedLen) {
var maxProceed = Long.MAX_VALUE
var number = seed
for (transition in transitions) {
var newNumber = number
val map = mappings[transition] ?: error("No mapping for $transition")
for (t in map) {
if (number >= t.second && number < t.second + t.third) {
newNumber = t.first + (number - t.second)
maxProceed = min(maxProceed, t.second + t.third - number)
} else {
if (t.second > number) {
maxProceed = min(maxProceed, t.second - number)
}
}
}
number = newNumber
}
lowest = min(lowest, number)
//println("$seed $maxProceed")
seed += max(1, maxProceed)
}
}
return lowest
}
}
fun main() {
val testInstance = Day05(true)
val instance = Day05(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 3,386 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/Day08.kt | Maetthu24 | 572,844,320 | false | {"Kotlin": 41016} | package year2022
fun main() {
fun isVisible(x: Int, y: Int, list: List<List<Int>>): Boolean {
if (x == 0 || x == list[y].size - 1 || y == 0 || y == list.size - 1)
return true
val tree = list[y][x]
if ((0 until x).toList().all { list[y][it] < tree })
return true
if ((x + 1 until list[y].size).toList().all { list[y][it] < tree })
return true
if ((0 until y).toList().all { list[it][x] < tree })
return true
if ((y + 1 until list.size).toList().all { list[it][x] < tree })
return true
return false
}
fun part1(input: List<String>): Int {
val list = input.map { it.map { c -> c.digitToInt() } }
return list.indices.sumOf { y ->
list[y].indices.count { x ->
isVisible(x, y, list)
}
}
}
fun score(x: Int, y: Int, list: List<List<Int>>): Int {
var x1 = 0
val tree = list[y][x]
if (x > 0) {
for (i in x-1 downTo 0) {
x1++
if (list[y][i] >= tree) {
break
}
}
}
var x2 = 0
if (x < list[y].size - 1) {
for (i in x+1 until list[y].size) {
x2++
if (list[y][i] >= tree) {
break
}
}
}
var y1 = 0
if (y > 0) {
for (i in y-1 downTo 0) {
y1++
if (list[i][x] >= tree) {
break
}
}
}
var y2 = 0
if (y < list.size - 1) {
for (i in y+1 until list.size) {
y2++
if (list[i][x] >= tree) {
break
}
}
}
return x1 * x2 * y1 * y2
}
fun part2(input: List<String>): Int {
val list = input.map { it.map { c -> c.digitToInt() } }
return list.indices.maxOf { y ->
list[y].indices.maxOf { x ->
score(x, y, list)
}
}
}
val day = "08"
// Read inputs
val testInput = readInput("Day${day}_test")
val input = readInput("Day${day}")
// Test & run part 1
val testResult = part1(testInput)
val testExpected = 21
check(testResult == testExpected) { "testResult should be $testExpected, but is $testResult" }
println(part1(input))
// Test & run part 2
val testResult2 = part2(testInput)
val testExpected2 = 8
check(testResult2 == testExpected2) { "testResult2 should be $testExpected2, but is $testResult2" }
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 3b3b2984ab718899fbba591c14c991d76c34f28c | 2,709 | adventofcode-kotlin | Apache License 2.0 |
src/day04/Day04.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day04
import readInput
private fun String.toIntRange(): IntRange =
IntRange(this.substringBefore('-').toInt(), this.substringAfter('-').toInt())
private fun String.toIntRangePair(): Pair<IntRange, IntRange> =
Pair(this.substringBefore(',').toIntRange(), this.substringAfter(',').toIntRange())
private infix fun IntRange.fullyContain(other: IntRange): Boolean =
other.first >= this.first && other.last <= this.last
private infix fun IntRange.overlaps(other: IntRange): Boolean =
this.contains(other.first) || this.contains(other.last)
fun main() {
fun part1(input: List<String>): Int {
var fullyContainedRangesCount = 0
for (line in input) {
val (leftRange, rightRange) = line.toIntRangePair()
if (leftRange fullyContain rightRange || rightRange fullyContain leftRange)
++fullyContainedRangesCount
}
return fullyContainedRangesCount
}
fun part2(input: List<String>): Int {
var overlappingPairs = 0
for (line in input) {
val (leftRange, rightRange) = line.toIntRangePair()
if (leftRange overlaps rightRange || rightRange overlaps leftRange)
++overlappingPairs
}
return overlappingPairs
}
val testInput = readInput("sample_data", 4)
println(part1(testInput))
check(part1(testInput) == 2)
val mainInput = readInput("main_data", 4)
println(part1(mainInput))
check(part1(mainInput) == 538)
println(part2(testInput))
check(part2(testInput) == 4)
println(part2(mainInput))
check(part2(mainInput) == 792)
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 1,633 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day21.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
import java.util.concurrent.ConcurrentHashMap
sealed class Expression {
data class Add(val a:Long, val b: Long) {
override fun toString(): String = "$a+$b"
}
data class Sub(val a:Long, val b: Long) {
override fun toString(): String = "$a-$b"
}
data class Mul(val a:Long, val b: Long)
data class Div(val a:Long, val b: Long)
data class Constant(val v: Long)
}
private val parser = "(\\w+) ([-+*/]) (\\w+)".toRegex()
class Monkey20(val formula: String) {
fun result(resolver: (String) -> Long): Long {
val matcher = parser.matchEntire(formula)
if (matcher != null) {
val (left, op, right) = matcher.destructured
val operation: (Long, Long) -> Long = when(op) {
"+" -> { a,b -> a+b }
"-" -> { a,b -> a-b }
"*" -> { a,b -> a*b }
else -> { a,b -> a/b }
}
return operation(resolver(left), resolver(right))
}
try {
return formula.toLong()
}
catch (e: NumberFormatException) {
throw IllegalArgumentException("Unable to parse $formula")
}
}
}
class Monkeys(val monkeys: Map<String, Monkey20>) {
private val cache = ConcurrentHashMap<String, Long>()
fun calculate(s: String): Long {
if (cache.contains(s)) return cache[s]!!
val done = monkeys[s]!!.result(this::calculate)
cache[s] = done
return done
}
}
fun main() {
val testInput = """root: pppw + sjmn
dbpl: 5
cczh: sllz + lgvd
zczc: 2
ptdq: humn - dvpt
dvpt: 3
lfqf: 4
humn: 5
ljgn: 2
sjmn: drzm * dbpl
sllz: 4
pppw: cczh / lfqf
lgvd: ljgn * ptdq
drzm: hmdt - zczc
hmdt: 32""".split("\n")
fun parseMonkeys(input: List<String>) = input.associate {
val (label, formula) = it.split(": ")
label to Monkey20(formula)
}
fun part1(input: List<String>): Long {
val monkeys = parseMonkeys(input)
return Monkeys(monkeys).calculate("root")
}
fun part2(input: List<String>): Long {
val monkeys = parseMonkeys(input)
// TODO - solve algabraically
val root = Monkey20(monkeys["root"]!!.formula.replace("+","-"))
return Monkeys(monkeys + mapOf("root" to root)).calculate("root")
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 152L)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 21).toList()
println(part1(puzzleInput))
println(part2(testInput))
println(part2(puzzleInput))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 2,679 | aoc-2022-kotlin | Apache License 2.0 |
src/Day05.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | fun main() {
fun parseStacks(input: List<String>): List<ArrayList<Char>> {
val splitIndex = input.indexOf("")
val initialLines = input.take(splitIndex - 1).asReversed()
val stacksCount = (initialLines[0].length + 1) / 4
val stacks = (0 until stacksCount).map { arrayListOf<Char>() }
for (line in initialLines) {
for (index in stacks.indices) {
val char = line.getOrNull(index * 4 + 1)
if (char != null && char != ' ') {
stacks[index].add(char)
}
}
}
return stacks
}
fun parseCommands(line: String) = line
.split(" ")
.filter { it.all(Char::isDigit) }
.map(String::toInt)
fun part1(input: List<String>): String {
val stacks = parseStacks(input)
for (line in input.drop(input.indexOf("") + 1)) {
val (count, from, to) = parseCommands(line)
repeat(count) {
stacks[to - 1].add(stacks[from - 1].removeLast())
}
}
return stacks.joinToString("") { it.last().toString() }
}
fun part2(input: List<String>): String {
val stacks = parseStacks(input)
for (line in input.drop(input.indexOf("") + 1)) {
val (count, from, to) = parseCommands(line)
val buffer = mutableListOf<Char>()
repeat(count) {
buffer.add(stacks[from - 1].removeLast())
}
buffer.reverse()
stacks[to - 1].addAll(buffer)
}
return stacks.joinToString("") { it.last().toString() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 1,936 | AdventOfCode2022 | Apache License 2.0 |
src/Day04.kt | bogdanbeczkowski | 572,679,090 | false | {"Kotlin": 8398} | fun main() {
fun part1(input: List<String>): Int {
var count = 0
for (line in input) {
val (first, second) = line.split(",")
val (firstStart, firstEnd) = first.split("-")
val (secondStart, secondEnd) = second.split("-")
val firstRange = firstStart.toInt().rangeTo(firstEnd.toInt()).toSet()
val secondRange = secondStart.toInt().rangeTo(secondEnd.toInt()).toSet()
if (firstRange.containsAll(secondRange)) {
count += 1
} else if (secondRange.containsAll(firstRange)) {
count += 1
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
for (line in input) {
val (first, second) = line.split(",")
val (firstStart, firstEnd) = first.split("-")
val (secondStart, secondEnd) = second.split("-")
val firstRange = firstStart.toInt().rangeTo(firstEnd.toInt()).toSet()
val secondRange = secondStart.toInt().rangeTo(secondEnd.toInt()).toSet()
// if (firstRange.containsAll(secondRange)) {
// count += firstRange.intersect(secondRange)
// } else if (secondRange.containsAll(firstRange)) {
// count += 1
// }
val intersect = firstRange.intersect(secondRange)
if (intersect.isNotEmpty()) {
count += 1
}
}
return count
}
// 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 | 03c29c7571e0d98ab00ee5c4c625954c0a46ab00 | 1,781 | AoC-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/com/hjk/advent22/Day12.kt | h-j-k | 572,485,447 | false | {"Kotlin": 26661, "Racket": 3822} | package com.hjk.advent22
import java.util.PriorityQueue
object Day12 {
fun part1(input: List<String>): Int =
process(input) { map -> map.mapNotNull { (p, char) -> p.takeIf { char == 'S' } } }
fun part2(input: List<String>): Int =
process(input) { map -> map.mapNotNull { (p, char) -> p.takeIf { char in "Sa" } } }
private fun process(input: List<String>, start: (Map<Point2d, Char>) -> List<Point2d>): Int =
input.asAsciiMap().let { map -> start(map).minOf { process(map, it) } }
private fun process(map: Map<Point2d, Char>, start: Point2d): Int {
val end = map.toList().single { (_, char) -> char == 'E' }.first
val queue = PriorityQueue<Pair<Point2d, Int>>(compareBy { it.second }).also { it.add(start to 0) }
val seen = mutableMapOf<Point2d, Int>()
while (queue.isNotEmpty()) {
val (current, steps) = queue.remove()
if (current == end) return steps
for (next in current.sideNeighbors()) {
if (next in map && map.safeGet(next) - map.safeGet(current) <= 1
&& steps + 1 < seen.getOrDefault(next, Int.MAX_VALUE)) {
seen[next] = steps + 1
queue.add(next to seen.getValue(next))
}
}
}
return Int.MAX_VALUE
}
private fun Map<Point2d, Char>.safeGet(point: Point2d) =
when (val p = getValue(point)) {
'S' -> 'a'
'E' -> 'z'
else -> p
}
}
| 0 | Kotlin | 0 | 0 | 20d94964181b15faf56ff743b8646d02142c9961 | 1,526 | advent22 | Apache License 2.0 |
src/main/kotlin/Day09.kt | Vampire | 572,990,104 | false | {"Kotlin": 57326} | fun main() {
fun part1(input: List<String>, ropeLength: Int = 2): Int {
val rope = ropeLength.downTo(1).map { Pair(0, 0) }.toMutableList()
return input
.asSequence()
.map { it.split(" ") }
.flatMap { (direction, amount) ->
amount.toInt().downTo(1).asSequence().map { direction }
}
.map { direction ->
for ((i, knot) in rope.withIndex()) {
if (i == 0) {
rope[0] = when (direction) {
"R" -> knot.copy(first = knot.first + 1)
"U" -> knot.copy(second = knot.second + 1)
"L" -> knot.copy(first = knot.first - 1)
"D" -> knot.copy(second = knot.second - 1)
else -> error("Unexpected direction: $direction")
}
} else {
val head = rope[i - 1]
val tail = rope[i]
rope[i] = when {
head.first == tail.first ->
when (val distance = head.second - tail.second) {
-1, 0, 1 -> tail
-2 -> tail.copy(second = tail.second - 1)
2 -> tail.copy(second = tail.second + 1)
else -> error("Unexpected distance: $distance")
}
head.second == tail.second ->
when (val distance = head.first - tail.first) {
-1, 0, 1 -> tail
-2 -> tail.copy(first = tail.first - 1)
2 -> tail.copy(first = tail.first + 1)
else -> error("Unexpected distance: $distance")
}
else ->
when (val xDistance = head.first - tail.first) {
-1, 1 -> when (val yDistance = head.second - tail.second) {
-1, 1 -> tail
-2 -> tail.copy(tail.first + xDistance, tail.second - 1)
2 -> tail.copy(tail.first + xDistance, tail.second + 1)
else -> error("Unexpected distances: $xDistance / $yDistance")
}
-2 -> when (val yDistance = head.second - tail.second) {
-1 -> tail.copy(tail.first - 1, tail.second + yDistance)
1 -> tail.copy(tail.first - 1, tail.second + yDistance)
-2 -> tail.copy(tail.first - 1, tail.second - 1)
2 -> tail.copy(tail.first - 1, tail.second + 1)
else -> error("Unexpected distances: $xDistance / $yDistance")
}
2 -> when (val yDistance = head.second - tail.second) {
-1 -> tail.copy(tail.first + 1, tail.second + yDistance)
1 -> tail.copy(tail.first + 1, tail.second + yDistance)
-2 -> tail.copy(tail.first + 1, tail.second - 1)
2 -> tail.copy(tail.first + 1, tail.second + 1)
else -> error("Unexpected distances: $xDistance / $yDistance")
}
else -> error("Unexpected distance: $xDistance")
}
}
}
}
return@map rope.last()
}
.toSet()
.count()
}
fun part2(input: List<String>) = part1(input, ropeLength = 10)
val testInput1 = readStrings("Day09_test1")
check(part1(testInput1) == 13)
val input = readStrings("Day09")
println(part1(input))
check(part2(testInput1) == 1)
val testInput2 = readStrings("Day09_test2")
check(part2(testInput2) == 36)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f | 4,468 | aoc-2022 | Apache License 2.0 |
src/day6/Day06.kt | francoisadam | 573,453,961 | false | {"Kotlin": 20236} | package day6
import readInput
fun main() {
fun part1(input: List<String>): Int {
val signal = input.first().toCharArray()
return List(signal.size) { index ->
if (index in (3 until signal.size)) {
if (signal.checkDistinct(index, 4)) {
return@List index + 1
}
}
return@List -1
}.first { it >= 0 }
}
fun part2(input: List<String>): Int {
val signal = input.first().toCharArray()
return List(signal.size) { index ->
if (index in (13 until signal.size)) {
if (signal.checkDistinct(index, 14)) {
return@List index + 1
}
}
return@List -1
}.first { it >= 0 }
}
// test if implementation meets criteria from the description, like:
val test1Input = readInput("day6/Day06_test1")
val test1Part1 = part1(test1Input)
val test1Part2 = part2(test1Input)
val test2Input = readInput("day6/Day06_test2")
val test2Part1 = part1(test2Input)
val test2Part2 = part2(test2Input)
val test3Input = readInput("day6/Day06_test3")
val test3Part1 = part1(test3Input)
val test3Part2 = part2(test3Input)
val test4Input = readInput("day6/Day06_test4")
val test4Part1 = part1(test4Input)
val test4Part2 = part2(test4Input)
val test5Input = readInput("day6/Day06_test5")
val test5Part1 = part1(test5Input)
val test5Part2 = part2(test5Input)
println("test1Part1: $test1Part1")
check(test1Part1 == 7)
println("test2Part1: $test2Part1")
check(test2Part1 == 5)
println("test3Part1: $test3Part1")
check(test3Part1 == 6)
println("test4Part1: $test4Part1")
check(test4Part1 == 10)
println("test5Part1: $test5Part1")
check(test5Part1 == 11)
println("test1Part2: $test1Part2")
check(test1Part2 == 19)
println("test2Part2: $test2Part2")
check(test2Part2 == 23)
println("test3Part2: $test3Part2")
check(test3Part2 == 23)
println("test4Part2: $test4Part2")
check(test4Part2 == 29)
println("test5Part2: $test5Part2")
check(test5Part2 == 26)
val input = readInput("day6/Day06")
println("part1 : ${part1(input)}")
println("part2 : ${part2(input)}")
}
fun CharArray.checkDistinct(checkIndex: Int, numberOfChar: Int): Boolean = this.toList()
.subList(checkIndex - numberOfChar + 1, checkIndex + 1)
.distinct().size == numberOfChar | 0 | Kotlin | 0 | 0 | e400c2410db4a8343c056252e8c8a93ce19564e7 | 2,490 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/codes/jakob/aoc/solution/Day15.kt | The-Self-Taught-Software-Engineer | 433,875,929 | false | {"Kotlin": 56277} | @file:Suppress("SameParameterValue")
package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.Grid
import codes.jakob.aoc.shared.UndirectedGraph
import codes.jakob.aoc.shared.UndirectedGraph.Vertex
object Day15 : Solution() {
override fun solvePart1(input: String): Any {
val grid: Grid<Int> = Grid(parseInput(input))
val shortestPath: List<Vertex<Grid.Cell<Int>>> = findShortestPath(grid)
return shortestPath.map { it.value }.drop(1).sumOf { it.value }
}
override fun solvePart2(input: String): Any {
val grid: Grid<Int> = Grid(parseInput(input)).enlarge(5)
val shortestPath: List<Vertex<Grid.Cell<Int>>> = findShortestPath(grid)
return shortestPath.map { it.value }.drop(1).sumOf { it.value }
}
private fun findShortestPath(grid: Grid<Int>): List<Vertex<Grid.Cell<Int>>> {
val start: Grid.Cell<Int> = grid.matrix.first().first()
val end: Grid.Cell<Int> = grid.matrix.last().last()
val edges: List<Pair<Grid.Cell<Int>, Grid.Cell<Int>>> =
grid.cells.flatMap { cell: Grid.Cell<Int> -> cell.getAdjacent(false).map { cell to it } }
val graph: UndirectedGraph<Grid.Cell<Int>> = UndirectedGraph(edges)
return graph.findBestPath(
graph.vertices.first { it.value == start },
graph.vertices.first { it.value == end },
{ cell: Grid.Cell<Int> -> cell.distanceTo(end).toLong() },
{ _, adjacent: Grid.Cell<Int> -> adjacent.value.toLong() },
)
}
private fun Grid<Int>.enlarge(times: Int): Grid<Int> {
val height: Int = this.matrix.count()
val width: Int = this.matrix.first().count()
val input: List<List<(Grid.Cell<Int>) -> Int>> =
List(height * times) { y: Int ->
List(width * times) { x: Int ->
val down: Int = y / height
val right: Int = x / width
val originalY: Int = y % height
val originalX: Int = x % width
var value = this.matrix[originalY][originalX].value + down + right
if (value != 9) value %= 9
{ value }
}
}
return Grid(input)
}
private fun parseInput(input: String): List<List<(Grid.Cell<Int>) -> Int>> {
return input.splitMultiline().map { row: String ->
row.split("").filter { it.isNotBlank() }.map { value: String ->
{ value.toInt() }
}
}
}
}
fun main() {
Day15.solve()
}
| 0 | Kotlin | 0 | 6 | d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c | 2,578 | advent-of-code-2021 | MIT License |
src/Day10.kt | cypressious | 572,916,585 | false | {"Kotlin": 40281} | fun main() {
val braces = mapOf(
'(' to ')',
'[' to ']',
'{' to '}',
'<' to '>',
)
val wrongScores = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137,
)
val autocompleteScores = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
fun getWrongSymbol(line: String): Char? {
val stack = mutableListOf<Char>()
for (c in line.toCharArray()) {
when (c) {
in braces -> stack += braces[c]!!
stack.last() -> stack.removeLast()
else -> return c
}
}
return null
}
fun part1(input: List<String>): Int {
return input.mapNotNull(::getWrongSymbol).map(wrongScores::getValue).sum()
}
fun getIncompleteStack(line: String): List<Char>? {
val stack = mutableListOf<Char>()
for (c in line.toCharArray()) {
when (c) {
in braces -> stack += braces[c]!!
stack.last() -> stack.removeLast()
else -> return null
}
}
return stack
}
fun part2(input: List<String>): Long {
return input
.mapNotNull { getIncompleteStack(it) }
.map { it.reversed().fold(0L) { acc, c -> acc * 5 + autocompleteScores.getValue(c) } }
.sorted().let { it[it.size / 2] }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 26397)
check(part2(testInput) == 288957L)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 169fb9307a34b56c39578e3ee2cca038802bc046 | 1,727 | AdventOfCode2021 | Apache License 2.0 |
leetcode-75-kotlin/src/main/kotlin/KidsWithTheGreatestNumberOfCandies.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* There are n kids with candies.
* You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has,
* and an integer extraCandies, denoting the number of extra candies that you have.
*
* Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies,
* they will have the greatest number of candies among all the kids, or false otherwise.
*
* Note that multiple kids can have the greatest number of candies.
*
*
*
* Example 1:
*
* Input: candies = [2,3,5,1,3], extraCandies = 3
* Output: [true,true,true,false,true]
* Explanation: If you give all extraCandies to:
* - Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
* - Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
* - Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
* - Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
* - Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
* Example 2:
*
* Input: candies = [4,2,1,1,2], extraCandies = 1
* Output: [true,false,false,false,false]
* Explanation: There is only 1 extra candy.
* Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
* Example 3:
*
* Input: candies = [12,1,12], extraCandies = 10
* Output: [true,false,true]
*
*
* Constraints:
*
* n == candies.length
* 2 <= n <= 100
* 1 <= candies[i] <= 100
* 1 <= extraCandies <= 50
* @see <a href="https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/">LeetCode</a>
*/
fun kidsWithCandies(candies: IntArray, extraCandies: Int): List<Boolean> {
val maxCandies = candies.maxOrNull()!!
return candies.map { it + extraCandies >= maxCandies }
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,870 | leetcode-75 | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/Day2.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 2: Dive!
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.readFileAsStringList
fun main() {
println(" ** Day 2: Dive! ** \n")
val diveCommands = readFileAsStringList("/Day2DiveCommands.txt")
val finalPositionByDepth = processDiveCommandsByDepth(diveCommands)
println("Final position of part 1 is ${finalPositionByDepth.horizontalPosition} with a depth of ${finalPositionByDepth.depth}, " +
"the puzzle answer is ${finalPositionByDepth.horizontalPosition * finalPositionByDepth.depth}")
val finalPositionByAim = processDiveCommandsByAim(diveCommands)
println("Final position of part 2 is ${finalPositionByAim.horizontalPosition} with a depth of ${finalPositionByAim.depth}, " +
"the puzzle answer is ${finalPositionByAim.horizontalPosition * finalPositionByAim.depth}")
}
fun processDiveCommandsByDepth(commands: List<String>) =
commands.fold(DivePosition(0, 0)) { position, nextMove ->
val (action, unitsAsString) = nextMove.split(" ")
val units = unitsAsString.toInt()
when (action) {
"forward" -> position.moveForward(units)
"down" -> position.diveDown(units)
"up" -> position.riseUp(units)
else -> position
}
}
fun processDiveCommandsByAim(commands: List<String>) =
commands.fold(DiveAimPosition(0, 0, 0)) { position, nextMove ->
val (action, unitsAsString) = nextMove.split(" ")
val units = unitsAsString.toInt()
when (action) {
"forward" -> position.moveForward(units)
"down" -> position.aimDown(units)
"up" -> position.aimUp(units)
else -> position
}
}
data class DivePosition(val horizontalPosition: Int, val depth: Int) {
fun moveForward(units: Int) = DivePosition(horizontalPosition + units, depth)
fun diveDown(units: Int) = DivePosition(horizontalPosition, depth + units)
fun riseUp(units: Int) = DivePosition(horizontalPosition, depth - units)
}
data class DiveAimPosition(val horizontalPosition: Int, val depth: Int, private val aim: Int) {
fun moveForward(units: Int) = DiveAimPosition(horizontalPosition + units, depth + (units * aim), aim)
fun aimDown(units: Int) = DiveAimPosition(horizontalPosition, depth, aim + units)
fun aimUp(units: Int) = DiveAimPosition(horizontalPosition, depth, aim - units)
}
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 2,408 | AdventOfCode2021 | MIT License |
src/Day19.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import java.util.LinkedList
import java.util.Queue
import kotlin.math.max
import kotlin.math.min
import kotlin.system.measureTimeMillis
fun main() {
fun part1(input: List<String>): Int {
val blueprints = parseBlueprints(input)
return blueprints.sumOf { it.qualityLevel(24) }
}
fun part2(input: List<String>): Int {
val blueprints = parseBlueprints(input)
return blueprints.take(3).foldRight(1) { blueprint, acc -> blueprint.maxGeodeCount(32) * acc }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
println(
"took part1: " +
measureTimeMillis {
println(part1(testInput))
println(33)
})
// part2 takes about 1 min
println(
"took part2: " +
measureTimeMillis {
println(part2(testInput))
println(56 * 62)
})
val input = readInput("Day19")
println("took real part1: " + measureTimeMillis { println(part1(input)) })
// part2 takes about 20 seconds
println("took real part2: " + measureTimeMillis { println(part2(input)) })
}
private fun parseBlueprints(input: List<String>): List<Blueprint> {
return input.map { Blueprint.parse(it) }
}
private val linePatternDay19 =
Regex(
"Blueprint (\\d+):" +
" Each ore robot costs (\\d+) ore\\." +
" Each clay robot costs (\\d+) ore\\." +
" Each obsidian robot costs (\\d+) ore and (\\d+) clay\\." +
" Each geode robot costs (\\d+) ore and (\\d+) obsidian\\.")
private data class Blueprint(
val number: Int,
val oreRobotCostOre: Int,
val clayRobotCostOre: Int,
val obsidianRobotCostOre: Int,
val obsidianRobotCostClay: Int,
val geodeRobotCostOre: Int,
val geodeRobotCostObsidian: Int,
) {
val maxOreRobots =
listOf(
clayRobotCostOre,
obsidianRobotCostOre,
geodeRobotCostOre,
)
.max()
val maxClayRobots = obsidianRobotCostClay
val maxObsidianRobots = geodeRobotCostObsidian
fun qualityLevel(timeLeft: Int) = maxGeodeCount(timeLeft) * number
fun maxGeodeCount(timeLeft: Int) =
maxGeodeCount(SimulationState(timeLeft)).also {
println("Blueprint #$number, checked paths: $checkPathsCount")
}
var checkPathsCount = 0L
private fun maxGeodeCount(initialState: SimulationState): Int {
val discoveredStates: MutableSet<SimulationState> = mutableSetOf()
val queue: Queue<SimulationState> = LinkedList()
queue.add(initialState)
var maxGeode = 0
while (queue.isNotEmpty()) {
val state = queue.poll()
if (state.timeLeft == 0) {
maxGeode = max(maxGeode, state.geodeCount)
checkPathsCount++
continue
}
val nextStates = state.getPossibleNextStates(this)
for (nextState in nextStates) {
if (!discoveredStates.contains(nextState)) {
discoveredStates.add(nextState)
queue.add(nextState)
}
}
if (nextStates.isEmpty()) {
maxGeode = max(maxGeode, state.geodeCount + state.timeLeft * state.geodeRobotCount)
checkPathsCount++
}
}
return maxGeode
}
companion object {
fun parse(input: String): Blueprint {
val values = linePatternDay19.matchEntire(input)!!.groupValues.drop(1).map { it.toInt() }
return Blueprint(values[0], values[1], values[2], values[3], values[4], values[5], values[6])
}
}
}
private data class SimulationState(
val timeLeft: Int,
val oreCount: Int = 0,
val clayCount: Int = 0,
val obsidianCount: Int = 0,
val geodeCount: Int = 0,
val oreRobotCount: Int = 1,
val clayRobotCount: Int = 0,
val obsidianRobotCount: Int = 0,
val geodeRobotCount: Int = 0,
) {
fun buildNoRobot(): SimulationState =
copy(
oreCount = oreCount + oreRobotCount,
clayCount = clayCount + clayRobotCount,
obsidianCount = obsidianCount + obsidianRobotCount,
geodeCount = geodeCount + geodeRobotCount,
timeLeft = timeLeft - 1)
fun buildOreRobot(blueprint: Blueprint): SimulationState =
copy(
oreCount = oreCount + oreRobotCount - blueprint.oreRobotCostOre,
clayCount = clayCount + clayRobotCount,
obsidianCount = obsidianCount + obsidianRobotCount,
geodeCount = geodeCount + geodeRobotCount,
oreRobotCount = oreRobotCount + 1,
timeLeft = timeLeft - 1)
fun buildClayRobot(blueprint: Blueprint): SimulationState =
copy(
oreCount = oreCount + oreRobotCount - blueprint.clayRobotCostOre,
clayCount = clayCount + clayRobotCount,
obsidianCount = obsidianCount + obsidianRobotCount,
geodeCount = geodeCount + geodeRobotCount,
clayRobotCount = clayRobotCount + 1,
timeLeft = timeLeft - 1)
fun buildObsidianRobot(blueprint: Blueprint): SimulationState =
copy(
oreCount = oreCount + oreRobotCount - blueprint.obsidianRobotCostOre,
clayCount = clayCount + clayRobotCount - blueprint.obsidianRobotCostClay,
obsidianCount = obsidianCount + obsidianRobotCount,
geodeCount = geodeCount + geodeRobotCount,
obsidianRobotCount = obsidianRobotCount + 1,
timeLeft = timeLeft - 1)
fun buildGeodeRobot(blueprint: Blueprint): SimulationState =
copy(
oreCount = oreCount + oreRobotCount - blueprint.geodeRobotCostOre,
clayCount = clayCount + clayRobotCount,
obsidianCount = obsidianCount + obsidianRobotCount - blueprint.geodeRobotCostObsidian,
geodeCount = geodeCount + geodeRobotCount,
geodeRobotCount = geodeRobotCount + 1,
timeLeft = timeLeft - 1)
fun canBuildOreRobot(blueprint: Blueprint) = oreCount >= blueprint.oreRobotCostOre
fun canBuildClayRobot(blueprint: Blueprint) = oreCount >= blueprint.clayRobotCostOre
fun canBuildObsidianRobot(blueprint: Blueprint) =
clayCount >= blueprint.obsidianRobotCostClay && oreCount >= blueprint.obsidianRobotCostOre
fun canBuildGeodeRobot(blueprint: Blueprint) =
obsidianCount >= blueprint.geodeRobotCostObsidian && oreCount >= blueprint.geodeRobotCostOre
fun getPossibleNextStates(blueprint: Blueprint): List<SimulationState> {
return buildList {
// tried to filter out unnecessary paths to get down to a lower number of combinations
val canBuildOreRobot = canBuildOreRobot(blueprint)
val canBuildClayRobot = canBuildClayRobot(blueprint)
val canBuildObsidianRobot = canBuildObsidianRobot(blueprint)
val canBuildGeodeRobot = canBuildGeodeRobot(blueprint)
val requiredObsidianRobots = blueprint.maxObsidianRobots - obsidianRobotCount
val geodeRobotCountPossible =
min(
(oreCount + timeLeft * oreRobotCount - blueprint.obsidianRobotCostOre) /
blueprint.geodeRobotCostOre,
timeLeft - 1)
val obsidianRobotCountPossible =
min(
(oreCount + timeLeft * oreRobotCount - blueprint.clayRobotCostOre) /
blueprint.obsidianRobotCostOre,
requiredObsidianRobots)
val needsObsidian =
obsidianCount + timeLeft * obsidianRobotCount <
geodeRobotCountPossible * blueprint.geodeRobotCostObsidian
val needsClay =
needsObsidian &&
clayCount + obsidianRobotCountPossible * clayRobotCount <
obsidianRobotCountPossible * blueprint.obsidianRobotCostClay
val obsidianRobotsReached =
obsidianRobotCount == blueprint.maxObsidianRobots || !needsObsidian || timeLeft < 4
val clayRobotsReached =
clayRobotCount == blueprint.maxClayRobots ||
obsidianRobotsReached ||
!needsClay ||
timeLeft <
6 // makes no sense to build clay robot if timeLeft <= 5, because 1 min is spend
// for building, then minimum 1 min to generate clay (otherwise it makes no sense to build
// clay robot if higher rate is not used). then the same for obsidian and geode as clay makes
// only sense if i want to build obsidian robot and then geode robot -> minimum 6 minutes
// needed for clay robot to make sense
val notNeedsOre =
obsidianRobotsReached &&
oreCount + timeLeft * oreRobotCount - blueprint.oreRobotCostOre + (timeLeft - 1) >=
(timeLeft - 1) * blueprint.geodeRobotCostOre
val oreRobotsReached =
oreRobotCount == blueprint.maxOreRobots ||
obsidianRobotsReached && oreRobotCount == blueprint.geodeRobotCostOre ||
clayRobotsReached &&
oreRobotCount ==
max(blueprint.geodeRobotCostOre, blueprint.obsidianRobotCostOre) ||
notNeedsOre ||
timeLeft < 4 ||
timeLeft < 5 &&
oreCount >=
blueprint.geodeRobotCostOre // no need for ore robot as i already can build an
// geode
if (canBuildOreRobot && !oreRobotsReached) add(buildOreRobot(blueprint))
if (canBuildClayRobot && !clayRobotsReached) add(buildClayRobot(blueprint))
if (canBuildObsidianRobot && !obsidianRobotsReached) add(buildObsidianRobot(blueprint))
if (canBuildGeodeRobot && timeLeft > 1) // minimum 2 min needed to profit from higher rate
add(buildGeodeRobot(blueprint))
when {
(canBuildGeodeRobot || timeLeft < 2) &&
(oreRobotsReached || canBuildOreRobot) &&
(clayRobotsReached || canBuildClayRobot) &&
(obsidianRobotsReached || canBuildObsidianRobot) -> {}
obsidianRobotCount == 0 &&
canBuildObsidianRobot &&
(oreRobotsReached || canBuildOreRobot) &&
(clayRobotsReached || canBuildClayRobot) -> {}
clayRobotCount == 0 && canBuildClayRobot && (oreRobotsReached || canBuildOreRobot) -> {}
else -> add(buildNoRobot())
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 10,072 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/lucaszeta/adventofcode2020/day05/day05.kt | LucasZeta | 317,600,635 | false | null | package com.lucaszeta.adventofcode2020.day05
import com.lucaszeta.adventofcode2020.ext.getResourceAsText
fun main() {
val input = getResourceAsText("/day05/boarding-passes.txt")
.split("\n")
.filter { it.isNotEmpty() }
val seatIds = input
.map(::findSeat)
.map(::calculateSeatId)
println("Highest seat ID: %d".format(seatIds.maxOrNull() ?: 0))
println("Missing seat ID: %d".format(findMissingSeat(seatIds)))
}
fun findMissingSeat(seatIds: List<Int>): Int {
val existingSeats = seatIds.sorted()
return existingSeats
.filterIndexed { index, seatId ->
index != 0 && seatId - existingSeats[index - 1] > 1
}
.map { it - 1 }
.first()
}
fun calculateSeatId(seatCoordinates: Pair<Int, Int>) =
seatCoordinates.first * 8 + seatCoordinates.second
fun findSeat(coordinates: String): Pair<Int, Int> {
val allCoordinates = coordinates.chunked(1)
val rowCoordinates = allCoordinates
.filter { it == "F" || it == "B" }
.toBinaryString("B")
val columnCoordinates = allCoordinates
.filter { it == "L" || it == "R" }
.toBinaryString("R")
val row = Integer.parseInt(rowCoordinates, 2)
val column = Integer.parseInt(columnCoordinates, 2)
return row to column
}
fun List<String>.toBinaryString(characterOne: String): String {
return map { if (it == characterOne) 1 else 0 }.joinToString("")
}
| 0 | Kotlin | 0 | 1 | 9c19513814da34e623f2bec63024af8324388025 | 1,447 | advent-of-code-2020 | MIT License |
src/main/kotlin/days/Day18.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
import java.lang.Integer.max
import kotlin.math.abs
class Day18 : Day(18) {
override fun partOne(): Any {
val cubes = inputList.map {
it.split(",").map { it.toInt() }.let { Cube(it[0], it[1], it[2]) }
}
val touchingSurfaces = cubes.flatMap { left -> cubes.mapNotNull { right -> if (left != right) left to right else null } }
.count { (one, another) ->
(one.x == another.x && one.y == another.y && abs(one.z - another.z) == 1) ||
(one.y == another.y && one.z == another.z && abs(one.x - another.x) == 1) ||
(one.z == another.z && one.x == another.x && abs(one.y - another.y) == 1)
}
return 6 * cubes.size - touchingSurfaces
}
override fun partTwo(): Any {
val margin = 2
val cubes = inputList.map {
it.split(",").map { it.toInt() }.let { Cube(it[0] + margin, it[1] + margin, it[2] + margin) }
}.toSet()
val outerSurface = cubes.maxOf { max(max(it.x, it.y), it.z) } + margin
return cubes.flatMap { cube ->
cube.next().filter { it !in cubes }
}.count { reachSurface(it, cubes, outerSurface) }
}
private fun reachSurface(start: Cube, cubes: Set<Cube>, outerSurface: Int): Boolean {
val q = ArrayDeque<Cube>().apply { add(start) }
val visited = mutableSetOf(start)
while (q.isNotEmpty()) {
val cur = q.removeFirst()
if (cur.x == outerSurface || cur.y == outerSurface || cur.z == outerSurface) {
return true
} else {
val next = cur.next()
next.filter { it !in cubes && it !in visited }.let { visited.addAll(it); q.addAll(it) }
}
}
return false
}
data class Cube(val x: Int, val y:Int, val z:Int) {
fun next(): List<Cube> {
return listOf(
this.copy(x = this.x - 1),
this.copy(x = this.x + 1),
this.copy(y = this.y + 1),
this.copy(y = this.y - 1),
this.copy(z = this.z + 1),
this.copy(z = this.z - 1),
)
}
}
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 2,213 | aoc-2022 | Creative Commons Zero v1.0 Universal |
aoc-2021/src/main/kotlin/nerok/aoc/aoc2021/day10/Day10.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2021.day10
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun part1(input: List<String>): Long {
var score = 0
input.forEach{ line ->
val stack = ArrayDeque<String>()
var mismatchedBracket = ""
line.split("").forEach { char ->
if (mismatchedBracket != "") return@forEach
when (char) {
"(" -> stack.add(char)
"[" -> stack.add(char)
"{" -> stack.add(char)
"<" -> stack.add(char)
")" -> if (stack.last() == "(") stack.removeLast() else {
mismatchedBracket = char
}
"]" -> if (stack.last() == "[") stack.removeLast() else {
mismatchedBracket = char
}
"}" -> if (stack.last() == "{") stack.removeLast() else {
mismatchedBracket = char
}
">" -> if (stack.last() == "<") stack.removeLast() else {
mismatchedBracket = char
}
}
}
if (mismatchedBracket != "") {
when (mismatchedBracket) {
")" -> score += 3
"]" -> score += 57
"}" -> score += 1197
">" -> score += 25137
}
}
}
return score.toLong()
}
fun part2(input: List<String>): Long {
val scores = input.map { line ->
var score = 0L
val stack = ArrayDeque<String>()
line.split("").forEach { char ->
when (char) {
"(" -> stack.add(char)
"[" -> stack.add(char)
"{" -> stack.add(char)
"<" -> stack.add(char)
")" -> if (stack.last() == "(") stack.removeLast() else {
return@map null
}
"]" -> if (stack.last() == "[") stack.removeLast() else {
return@map null
}
"}" -> if (stack.last() == "{") stack.removeLast() else {
return@map null
}
">" -> if (stack.last() == "<") stack.removeLast() else {
return@map null
}
}
}
while (stack.isNotEmpty()) {
score *= 5
when (stack.removeLast()) {
"(" -> score += 1
"[" -> score += 2
"{" -> score += 3
"<" -> score += 4
}
}
score
}.filterNotNull().sorted()
return scores[scores.size/2]
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day10_test")
check(part1(testInput) == 26397L)
check(part2(testInput) == 288957L)
val input = Input.readInput("Day10")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 3,381 | AOC | Apache License 2.0 |
src/main/kotlin/com/hjk/advent22/Day09.kt | h-j-k | 572,485,447 | false | {"Kotlin": 26661, "Racket": 3822} | package com.hjk.advent22
import kotlin.math.abs
import kotlin.math.sign
object Day09 {
fun part1(input: List<String>): Int {
var head = Point2d(x = 0, y = 0)
val tailPositions = mutableListOf(head)
for (next in input) {
val (direction, distance) = next.split(" ").let { (a, b) -> a to b.toInt() }
head = when (direction) {
"U" -> head.copy(y = head.y - distance)
"D" -> head.copy(y = head.y + distance)
"L" -> head.copy(x = head.x - distance)
"R" -> head.copy(x = head.x + distance)
else -> throw RuntimeException()
}
tailPositions += if (!head.isNextTo(tailPositions.last()))
(tailPositions.last()..(head.stepBefore(direction))).distinct() else emptyList()
}
return tailPositions.toSet().size
}
fun part2(input: List<String>): Int {
val origin = Point2d(x = 0, y = 0)
val knots = MutableList(10) { origin }
val visited = mutableSetOf(origin)
for (next in input) {
val (direction, distance) = next.split(" ").let { (a, b) -> a to b.toInt() }
repeat(distance) {
knots[0] = knots.first().let {
when (direction) {
"U" -> it.copy(y = it.y - 1)
"D" -> it.copy(y = it.y + 1)
"L" -> it.copy(x = it.x - 1)
"R" -> it.copy(x = it.x + 1)
else -> throw RuntimeException()
}
}
(0 until knots.lastIndex).forEach {
val head = knots[it]
var tail = knots[it + 1]
if (tail !in head.allNeighbors()) {
tail = Point2d(x = tail.x + (head.x - tail.x).sign, y = tail.y + (head.y - tail.y).sign)
visited += knots.last()
}
knots[it + 1] = tail
}
}
}
return visited.size
}
private fun Point2d.isNextTo(other: Point2d): Boolean =
this == other || maxOf(abs(this.x - other.x), abs(this.y - other.y)) == 1
private fun Point2d.stepBefore(direction: String): Point2d =
when (direction) {
"U" -> copy(y = this.y + 1)
"D" -> copy(y = this.y - 1)
"L" -> copy(x = this.x + 1)
"R" -> copy(x = this.x - 1)
else -> throw RuntimeException()
}
private operator fun Point2d.rangeTo(target: Point2d): List<Point2d> = when {
this.x == target.x -> when {
this.y < target.y -> ((this.y + 1)..target.y).map { copy(y = it) }
else -> ((this.y - 1) downTo target.y).map { copy(y = it) }
}
this.y == target.y -> when {
this.x < target.x -> ((this.x + 1)..target.x).map { copy(x = it) }
else -> ((this.x - 1) downTo target.x).map { copy(x = it) }
}
else -> when {
abs(this.x - target.x) == 1 -> {
when {
this.y < target.y -> target.copy(y = this.y + 1).let { listOf(it) + (it..target) }
else -> target.copy(y = this.y - 1).let { listOf(it) + (it..target) }
}
}
abs(this.y - target.y) == 1 -> {
when {
this.x < target.x -> target.copy(x = this.x + 1).let { listOf(it) + (it..target) }
else -> target.copy(x = this.x - 1).let { listOf(it) + (it..target) }
}
}
else -> emptyList()
}
}
}
| 0 | Kotlin | 0 | 0 | 20d94964181b15faf56ff743b8646d02142c9961 | 3,699 | advent22 | Apache License 2.0 |
2022/src/day20/day20.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day20
import GREEN
import RESET
import printTimeMillis
import readInput
// List of Pair(idx, number)
fun mixString(
mapOfIdx: MutableList<Pair<Int, Long>>,
mixTimes: Int = 1,
decryptionKey: Long = 1
): Long {
for (i in 0 until mixTimes) {
for (idx in mapOfIdx.indices) {
val currentIdx = mapOfIdx.indexOfFirst { it.first == idx }
val number = mapOfIdx[currentIdx]
// .mod() The result is either zero or has the same sign as the divisor and has the absolute value less than the absolute value of the divisor
val newIdx = (currentIdx + number.second * decryptionKey).mod(mapOfIdx.lastIndex)
mapOfIdx.removeAt(currentIdx)
mapOfIdx.add(newIdx, number) // we preserve the initial number & initial index
}
}
val zeroIdx = mapOfIdx.indexOfFirst { it.second == 0L }
return listOf(1000, 2000, 3000).map { decryptionKey * mapOfIdx[(zeroIdx + it) % mapOfIdx.size].second }.sum()
}
fun part1(input: List<String>) = input.let {
val mapOfIdx = it.mapIndexed { index, s -> Pair(index, s.toLong()) }.toMutableList()
mixString(mapOfIdx)
}
fun part2(input: List<String>) = input.let {
val mapOfIdx = it.mapIndexed { index, s -> Pair(index, s.toLong()) }.toMutableList()
mixString(mapOfIdx,10, decryptionKey = 811589153)
}
fun main() {
val testInput = readInput("day20_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day20.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } // -6188367291625 wrong
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } // -9549157974198 wrong, 19079649397877 too high
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 1,850 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day19/Day19.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package day19
fun solveA(input: List<String>) = input
.map { Factory(it) }
.sumOf { it.id * it.run(minutes = 24, times = 100000) }
fun solveB(input: List<String>) = input
.take(3)
.map { Factory(it) }
.map { it.run(minutes = 32, times = 10000000) }
.reduce(Int::times)
data class OreRobotBlueprint(val oreCost: Int)
data class ClayRobotBlueprint(val oreCost: Int)
data class ObsidianRobotBlueprint(val oreCost: Int, val clayCost: Int)
data class GeodeRobotBlueprint(val oreCost: Int, val obsidianCost: Int)
data class Minerals(var ore: Int = 0, var clay: Int = 0, var obsidian: Int = 0, var geode: Int = 0)
data class Robots(var ore: Int = 1, var clay: Int = 0, var obsidian: Int = 0, var geode: Int = 0)
data class Blueprints(
var ore: OreRobotBlueprint? = null,
var clay: ClayRobotBlueprint? = null,
var obsidian: ObsidianRobotBlueprint? = null,
var geode: GeodeRobotBlueprint? = null
)
class Factory() {
var id = 0
private var minerals = Minerals()
private var robots = Robots()
private var blueprints = Blueprints()
constructor(blueprint: String) : this() {
val split = blueprint.split(": ")
id = split.first().split(" ").last().toInt()
val (oreCost, clayCost, obsidianCost, geodeCost) = split.last().split(". ")
.map { it.split(" ") }
blueprints = Blueprints(
OreRobotBlueprint(oreCost.reversed()[1].toInt()),
ClayRobotBlueprint(clayCost.reversed()[1].toInt()),
ObsidianRobotBlueprint(obsidianCost.reversed()[4].toInt(), obsidianCost.reversed()[1].toInt()),
GeodeRobotBlueprint(geodeCost.reversed()[4].toInt(), geodeCost.reversed()[1].toInt())
)
}
private fun reset() {
minerals = Minerals()
robots = Robots()
}
fun run(minutes: Int, times: Int): Int {
var max = 0
repeat(times) {
for (minute in 1..minutes) {
val toBuild = decide()
produce()
build(toBuild)
}
max = maxOf(max, minerals.geode)
reset()
}
return max
}
private fun produce() {
minerals.ore += robots.ore
minerals.clay += robots.clay
minerals.obsidian += robots.obsidian
minerals.geode += robots.geode
}
enum class Robot { GEODE, OBSIDIAN, CLAY, ORE }
private fun decide(): Robot? {
if (minerals.obsidian >= blueprints.geode!!.obsidianCost && minerals.ore >= blueprints.geode!!.oreCost) {
return Robot.GEODE
}
if (robots.obsidian <= blueprints.geode!!.obsidianCost &&
minerals.ore >= blueprints.obsidian!!.oreCost &&
minerals.clay >= blueprints.obsidian!!.clayCost && listOf(0, 1).random() == 1
) {
return Robot.OBSIDIAN
}
if (robots.clay <= blueprints.obsidian!!.clayCost &&
minerals.ore >= blueprints.clay!!.oreCost &&
listOf(0, 1).random() == 1
) {
return Robot.CLAY
}
if (robots.ore <= listOf(
blueprints.clay!!.oreCost,
blueprints.obsidian!!.oreCost,
blueprints.geode!!.oreCost
).max() &&
minerals.ore >= blueprints.ore!!.oreCost && listOf(0, 1).random() == 1
) {
return Robot.ORE
}
return null
}
private fun build(toBuild: Robot?) {
when (toBuild) {
Robot.GEODE -> {
minerals.ore -= blueprints.geode!!.oreCost
minerals.obsidian -= blueprints.geode!!.obsidianCost
robots.geode++
}
Robot.OBSIDIAN -> {
minerals.ore -= blueprints.obsidian!!.oreCost
minerals.clay -= blueprints.obsidian!!.clayCost
robots.obsidian++
}
Robot.CLAY -> {
minerals.ore -= blueprints.clay!!.oreCost
robots.clay++
}
Robot.ORE -> {
minerals.ore -= blueprints.ore!!.oreCost
robots.ore++
}
else -> null
}
}
}
| 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 4,221 | advent-of-code-2022 | Apache License 2.0 |
src/day10/Day10.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day10
import utils.*
import kotlin.math.absoluteValue
val THRESHOLDS = (20..220 step 40)
const val WIDTH = 40
fun getOperations(input: List<String>): List<Pair<Int, Int>> =
input.map { line ->
val args = line.split(" ")
when (args.first()) {
"noop" -> Pair(1, 0)
"addx" -> Pair(2, args[1].toInt())
else -> throw Error("invalid operation ${args.first()}")
}
}
fun getXValues(commands: List<Pair<Int, Int>>): List<Int> {
val values = mutableListOf<Int>()
var x = 1
commands.forEach { (duration, delta) ->
values.addAll(List(duration) { x })
x += delta
}
return values
}
fun part1(input: List<String>): Int {
val values = getXValues(getOperations(input))
return THRESHOLDS.sumOf { i -> values[i - 1] * i }
}
fun part2(input: List<String>): List<String> =
getXValues(getOperations(input))
.mapIndexed { i, x -> (i % WIDTH - x).absoluteValue < 2 }
.joinToString("") { if (it) "*" else " " }
.chunked(WIDTH)
fun main() {
val testInput = readInput("Day10_test")
expect(part1(testInput), 13140)
expect(part2(testInput), listOf(
"** ** ** ** ** ** ** ** ** ** ",
"*** *** *** *** *** *** *** ",
"**** **** **** **** **** ",
"***** ***** ***** ***** ",
"****** ****** ****** ****",
"******* ******* ******* "
))
val input = readInput("Day10")
println(part1(input))
println(part2(input).joinToString("\n"))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 1,620 | AOC-2022-Kotlin | Apache License 2.0 |
src/Day01.kt | ktrom | 573,216,321 | false | {"Kotlin": 19490, "Rich Text Format": 2301} | import java.util.stream.Collectors
import java.util.stream.Stream
fun main() {
fun part1(input: List<String>): Int {
val inputWithDelimiter = Stream.concat(input.stream(), Stream.of("")).collect(Collectors.toList())
var maxCalories = 0
var elfCalories = 0
inputWithDelimiter.forEach { foodCalorie ->
if (foodCalorie.isEmpty()) {
maxCalories = elfCalories.coerceAtLeast(maxCalories)
elfCalories = 0
} else {
elfCalories += foodCalorie.toInt()
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
val inputWithDelimiter = Stream.concat(input.stream(), Stream.of("")).collect(Collectors.toList())
// sorted list of top three elves' carried calories
val topThreeElvesCalories: MutableList<Int> = mutableListOf(0, 0, 0)
var elfCalories = 0
inputWithDelimiter.forEach { foodCalorie ->
if (foodCalorie.isEmpty()) {
// if this elf's calories are greater than the third-highest elf's
if (elfCalories > topThreeElvesCalories[0]) {
// remove minimum element
topThreeElvesCalories.removeFirstOrNull()
// binary search returns the index the given element would be at and negates it
val naturalIndex = -topThreeElvesCalories.binarySearch(elfCalories, naturalOrder()) - 1
topThreeElvesCalories.add(naturalIndex, elfCalories)
}
elfCalories = 0
} else {
elfCalories += foodCalorie.toInt()
}
}
return topThreeElvesCalories.sum()
}
// test if implementation meets criteria from the description
val testInput = readInput("Day01_test")
println(part1(testInput) == 24000)
println(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6940ff5a3a04a29cfa927d0bbc093cd5df15cbcd | 1,733 | kotlin-advent-of-code | Apache License 2.0 |
kotlinP/src/main/java/com/jadyn/kotlinp/leetcode/sort/sort_0.kt | JadynAi | 136,196,478 | false | null | package com.jadyn.kotlinp.leetcode.sort
import com.jadyn.kotlinp.leetcode.thought.merge
import java.util.*
import kotlin.math.log
/**
*JadynAi since 3/25/21
*/
fun main() {
// print("sort ${Arrays.toString(fastSort(arrayOf(3, 1, 9, 10, 7, 5, 4)))}")
val array = arrayOf(6, 10, 7, 9, 8, 11)
// print("sort ${Arrays.toString(mergeSort(array))}")
print("${log(16f, 2f)} ${Math.log(16.0)}")
}
fun fastSort1(array: Array<Int>, start: Int, end: Int) {
}
// 选择排序,每一轮选出最小的值
fun chooseSort(array: Array<Int>): Array<Int> {
for (i in 0 until array.lastIndex) {
var minPos = i
for (j in i + 1 until array.size) {
minPos = j.takeIf { array[j] < array[minPos] } ?: minPos
}
if (minPos != i) {
val s = array[minPos]
array[minPos] = array[i]
array[i] = s
}
}
return array
}
// 冒泡排序,让大的值浮上去,递减循环
fun bubbleSort(array: Array<Int>): Array<Int> {
for (i in 1 until array.size) {
for (j in 0..array.lastIndex - i) {
if (array[j] > array[j + 1]) {
val jv = array[j]
array[j] = array[j + 1]
array[j + 1] = jv
}
}
println("cur i $i arrays is ${Arrays.toString(array)}")
}
return array
}
// 插入排序,插入排序的核心思想就是把当前index之前的序列看作有序序列,从而和当前index
// 的值比较,小的就交换到前面去
fun insertSort(array: Array<Int>): Array<Int> {
for (i in 1..array.lastIndex) {
val i1 = array[i]
l@ for (j in i - 1 downTo 0) {
if (i1 > array[j]) {
break@l
} else {
val jv = array[j]
array[j + 1] = jv
array[j] = i1
}
}
println(Arrays.toString(array))
}
return array
}
// 快速排序
fun fastSort(array: Array<Int>, start: Int, end: Int) {
if (end <= start) {
return
}
val base = array[start]
// 为什么双指针的left不能从start+1开始,因为这样就是默认右侧比start小了,当
// 右侧的所有值比start大的话,left就不应该自增
var left = start
var right = end - 1
while (left < right) {
while (array[right] > base && left < right) {
right--
}
while (array[left] <= base && left < right) {
left++
}
if (left < right) {
val v = array[left]
array[left] = array[right]
array[right] = v
}
}
array[start] = array[left]
array[left] = base
println("${Arrays.toString(array)} left is $left right $right")
fastSort(array, start, left)
fastSort(array, left + 1, end)
}
// 归并排序,这个临时的数组newArray就是个工具数组,只是为了排好序后替换原来的数组
fun mergeSort(array: Array<Int>): Array<Int> {
val newArray = Array(array.size) { -1 }
println("input array ${Arrays.toString(array)}")
mergeSortInner(array, 0, array.lastIndex, newArray)
return array
}
fun mergeSortInner(array: Array<Int>, start: Int, end: Int, newArray: Array<Int>) {
if (start >= end) return
val mid = (start + end) / 2
println("cur start $start end $end mid $mid")
mergeSortInner(array, start, mid, newArray)
mergeSortInner(array, mid + 1, end, newArray)
var left = start
var right = mid + 1
var index = 0
while (left <= mid && right <= end) {
if (array[left] < array[right]) {
newArray[index++] = array[left++]
} else {
newArray[index++] = array[right++]
}
}
println("cur new array ${Arrays.toString(newArray)} left $left right $right index $index")
while (left <= mid) {
newArray[index++] = array[left++]
}
while (right <= end) {
newArray[index++] = array[right++]
}
println("after new array ${Arrays.toString(newArray)} left $left right $right index $index")
var j = start
for (i in 0 until index) {
array[j++] = newArray[i]
}
println("array cur ${Arrays.toString(array)}")
} | 0 | Kotlin | 6 | 17 | 9c5efa0da4346d9f3712333ca02356fa4616a904 | 4,227 | Kotlin-D | Apache License 2.0 |
src/Day15.kt | erikthered | 572,804,470 | false | {"Kotlin": 36722} | import kotlin.math.absoluteValue
fun main() {
data class Coordinate(var x: Int, var y: Int) {
fun manhattanDistance(other: Coordinate): Int {
return (this.x - other.x).absoluteValue + (this.y - other.y).absoluteValue
}
}
val regex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex()
fun parseInput(input: List<String>): Map<Coordinate, Coordinate> {
return input.associate {
val match = regex.find(it)
val (sx, sy, bx, by) = match!!.destructured
Coordinate(sx.toInt(), sy.toInt()) to Coordinate(bx.toInt(), by.toInt())
}
}
fun part1(input: List<String>, row: Int): Int {
val data = parseInput(input)
val emptyCoords = mutableSetOf<Coordinate>()
data.entries.forEach { (sensor, beacon) ->
val beaconDistance = sensor.manhattanDistance(beacon)
val distToTargetRow = (row - sensor.y).absoluteValue
if (distToTargetRow < beaconDistance) {
val remainder = beaconDistance - distToTargetRow
((sensor.x - remainder)..(sensor.x + remainder)).forEach {
emptyCoords.add(Coordinate(it, row))
}
}
}
emptyCoords.removeAll(data.values.toSet())
return emptyCoords.size
}
fun generatePointsImmediatelyOutsideRadius(sensor: Coordinate, range: Int): Set<Coordinate> {
val points = mutableSetOf<Coordinate>()
val top = Coordinate(sensor.x, sensor.y + (range + 1))
val bottom = Coordinate(sensor.x, sensor.y - (range + 1))
val left = Coordinate(sensor.x - (range + 1), sensor.y)
val right = Coordinate(sensor.x + (range + 1), sensor.y)
val point = top.copy()
while (point != right) {
point.x++
point.y--
points.add(point.copy())
}
while (point != bottom) {
point.x--
point.y--
points.add(point.copy())
}
while (point != left) {
point.x--
point.y++
points.add(point.copy())
}
while (point != top) {
point.x++
point.y++
points.add(point.copy())
}
return points
}
// TODO change to check the tiles just outside the range of each sensor
fun part2(input: List<String>, lowerBound: Int, upperBound: Int): Long {
val data = parseInput(input)
val sensors = data.entries.associate { (sensor, beacon) ->
sensor to ((sensor.x - beacon.x).absoluteValue + (sensor.y - beacon.y).absoluteValue)
}
sensors.forEach { (sensor, range) ->
generatePointsImmediatelyOutsideRadius(sensor, range)
.filter { it.x in lowerBound..upperBound && it.y in lowerBound..upperBound }
.forEach { c ->
if (sensors.all { (s, r) -> s.manhattanDistance(c) > r }) {
return c.x.toLong() * 4000000L + c.y.toLong()
}
}
}
return 0
}
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(
generatePointsImmediatelyOutsideRadius(Coordinate(5, 5), 2).containsAll(
setOf(
Coordinate(5, 2),
Coordinate(6, 3),
Coordinate(7, 4),
Coordinate(8, 5),
Coordinate(7, 6),
Coordinate(6, 7),
Coordinate(5, 8),
Coordinate(4, 7),
Coordinate(3, 6),
Coordinate(2, 5),
Coordinate(3, 4),
Coordinate(4, 3)
)
)
)
check(part2(testInput, 0, 20) == 56000011L)
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 0, 4000000))
}
| 0 | Kotlin | 0 | 0 | 3946827754a449cbe2a9e3e249a0db06fdc3995d | 3,960 | aoc-2022-kotlin | Apache License 2.0 |
src/problems/1807-evaluateBracketPairsString.kt | w1374720640 | 352,006,409 | false | null | package problems
/**
* 1807. 替换字符串中的括号内容 https://leetcode-cn.com/problems/evaluate-the-bracket-pairs-of-a-string/
*
* 解:先处理knowledge数组,将所有键值对转换成HashMap中的键值对,方便查找
* 因为括号成对出现且不会出现嵌套,分别使用两个整数记录左括号和右括号的索引
* 以括号中间的内容为键,在HashMap中查找对应的值或'?'符号,
* 所有的值用StringBuilder拼接成新的字符串
*/
fun evaluateBracketPairsString(s: String, knowledge: List<List<String>>): String {
val map = HashMap<String, String>()
knowledge.forEach { list ->
map[list[0]] = list[1]
}
val stringBuilder = StringBuilder()
var i = -1
for (j in s.indices) {
val char = s[j]
if (char == '(') {
if (j - i > 1) {
stringBuilder.append(s.substring(i + 1, j))
}
i = j
} else if (char == ')') {
val key = s.substring(i + 1, j)
val value = map[key]
if (value == null) {
stringBuilder.append('?')
} else {
stringBuilder.append(value)
}
i = j
}
}
if (s.length - i > 1) {
stringBuilder.append(s.substring(i + 1))
}
return stringBuilder.toString()
}
private fun arrayToList(array: Array<Array<String>>): List<List<String>> {
val list = ArrayList<List<String>>(array.size)
array.forEach {
val subList = ArrayList<String>()
subList.add(it[0])
subList.add(it[1])
list.add(subList)
}
return list
}
private fun test(origin: String, array: Array<Array<String>>, expect: String) {
check(evaluateBracketPairsString(origin, arrayToList(array)) == expect)
}
fun main() {
test(
"(name)is(age)yearsold",
arrayOf(arrayOf("name", "bob"), arrayOf("age", "two")),
"bobistwoyearsold"
)
test(
"hi(name)",
arrayOf(arrayOf("a", "b")),
"hi?"
)
test(
"(a)(a)(a)aaa",
arrayOf(arrayOf("a", "yes")),
"yesyesyesaaa"
)
test(
"(a)(b)",
arrayOf(arrayOf("a", "b"), arrayOf("b", "a")),
"ba"
)
test(
"",
arrayOf(arrayOf("a", "b")),
""
)
println("check succeed.")
} | 0 | Kotlin | 0 | 0 | 21c96a75d13030009943474e2495f1fc5a7716ad | 2,364 | LeetCode | MIT License |
src/main/kotlin/aoc2021/Day22.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
import java.util.*
import kotlin.math.max
import kotlin.math.min
private data class Instruction(
val newState: Boolean,
val xRange: IntRange,
val yRange: IntRange,
val zRange: IntRange
) {
companion object {
fun fromString(input: String): Instruction {
val split = input.split(" ")
val ranges = split[1].trim().split(",")
return Instruction(
split[0].trim() == "on",
rangeFromString(ranges[0]),
rangeFromString(ranges[1]),
rangeFromString(ranges[2])
)
}
}
}
private fun rangeFromString(input: String): IntRange {
// x=-20..26,
val split = input.drop(2).removeSuffix(",").split("..")
return IntRange(split[0].toInt(), split[1].toInt())
}
/**
* Applies the given instructions on a part of the reactor
* @param instructions the instructions to apply
* @param xRange the range in x dimension to consider
* @param yRange the range in y dimension to consider (default: same as [xRange])
* @param zRange the range in z dimension to consider (default: same as [xRange])
* @return the number of turned on cubes after applying all instructions on this subset
*/
private fun applyInstructions(
instructions: List<Instruction>, xRange: IntRange, yRange: IntRange = xRange, zRange: IntRange = xRange
): Int {
val size = xRange.count().toLong() * yRange.count() * zRange.count()
if (size < 0 || size > Int.MAX_VALUE) {
throw IllegalArgumentException("Range too big")
}
val xOffset = if (xRange.first < 0) xRange.first * -1 else 0
val yOffset = if (yRange.first < 0) yRange.first * -1 else 0
val zOffset = if (zRange.first < 0) zRange.first * -1 else 0
val reactor = BitSet(size.toInt())
val yMultiplier = xRange.count()
val zMultiplier = xRange.count() * yRange.count()
instructions.filter { it.xRange.intersect(xRange).isNotEmpty() }.filter { it.yRange.intersect(yRange).isNotEmpty() }
.filter { it.zRange.intersect(zRange).isNotEmpty() }.forEach {
for (x in it.xRange) {
for (y in it.yRange) {
for (z in it.zRange) {
val xIndex = x + xOffset
val yIndex = y + yOffset
val zIndex = z + zOffset
val index = xIndex + yIndex * yMultiplier + zIndex * zMultiplier
reactor[index] = it.newState
}
}
}
}
return reactor.cardinality()
}
private fun part1(input: List<String>) =
applyInstructions(input.map(Instruction.Companion::fromString), IntRange(-50, 50))
private data class Cuboid(val x: IntRange, val y: IntRange, val z: IntRange) {
private val isEmpty = x.isEmpty() || y.isEmpty() || z.isEmpty()
val cubesWithIn = x.count().toLong() * y.count() * z.count()
/**
* @return true, if the [other] cuboid overlaps with this one (e.g. has at least one cube in common)
*/
fun overlapsWith(other: Cuboid) =
(x.last > other.x.first && x.first < other.x.last) &&
(y.last > other.y.first && y.first < other.y.last) &&
(z.last > other.z.first && z.first < other.z.last)
/**
* @return true, if the [other] cuboid is contained within this cuboid
*/
fun contains(other: Cuboid) =
x.first <= other.x.first && x.last >= other.x.last &&
y.first <= other.y.first && y.last >= other.y.last &&
z.first <= other.z.first && z.last >= other.z.last
/**
* Removes the cubes which intersect in this cuboid and the [cut] cuboid
* @return a set of smaller [Cuboid]s, which are created by "cutting" the cubes of [cut] which intersect with this [Cuboid]
*/
fun cut(cut: Cuboid): Collection<Cuboid> {
val z1 = Cuboid(x, y, z.first until cut.z.first)
val z2 = Cuboid(x, y, cut.z.last + 1..z.last)
val y1 = Cuboid(x, y.first until cut.y.first, max(z.first, cut.z.first)..min(z.last, cut.z.last))
val y2 = Cuboid(x, cut.y.last + 1..y.last, max(z.first, cut.z.first)..min(z.last, cut.z.last))
val x1 = Cuboid(
x.first until cut.x.first,
max(y.first, cut.y.first)..min(y.last, cut.y.last),
max(z.first, cut.z.first)..min(z.last, cut.z.last)
)
val x2 = Cuboid(
cut.x.last + 1..x.last,
max(y.first, cut.y.first)..min(y.last, cut.y.last),
max(z.first, cut.z.first)..min(z.last, cut.z.last)
)
return setOf(x1, x2, y1, y2, z1, z2).filterNot { it.isEmpty }
}
}
/**
* Adds the new cubes contained within [newCuboid] to the set of distinct [Cuboid]s
*
* @param existing the existing cuboids
* @param newCuboid the new cuboid to add
* @return a set of cuboids, which do not have any intersecting cubes
*/
private fun addCuboid(existing: Set<Cuboid>, newCuboid: Cuboid): Set<Cuboid> {
val overlap = existing.find { it.overlapsWith(newCuboid) }
return if (overlap == null) {
existing.toMutableSet().also { it.add(newCuboid) }
} else {
val newCuboids = newCuboid.cut(overlap)
if (newCuboids.isEmpty()) {
existing
} else {
newCuboids.flatMap { addCuboid(existing, it) }.toSet()
}
}
}
/**
* @param instruction instruction to apply
* @param cuboids a set of cuboids which contain the cubes which are turned on
* @return a new set of cuboids with the cubes that are turned on after applying [instruction]
*/
private fun applyInstruction(instruction: Instruction, cuboids: Set<Cuboid>): Set<Cuboid> {
val newCuboid = Cuboid(instruction.xRange, instruction.yRange, instruction.zRange)
return if (instruction.newState) { // instruction will turn on some cubes
addCuboid(cuboids, newCuboid)
} else { // instruction will turn off some cubes
cuboids.flatMap {
if (it.overlapsWith(newCuboid)) {
it.cut(newCuboid)
} else {
setOf(it)
}
}.toSet()
}
}
private fun part2(input: List<String>): Long {
val instructions = input.map(Instruction.Companion::fromString)
var cuboids = emptySet<Cuboid>()
instructions.forEach { cuboids = applyInstruction(it, cuboids) }
return cuboids.sumOf { it.cubesWithIn }
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day22_test")
check(part1(testInput) == 474140)
check(part2(testInput) == 2758514936282235L)
val input = readInput("Day22")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 6,754 | adventOfCode | Apache License 2.0 |
gcj/y2020/round3/b_small.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2020.round3
private fun solve(): Int {
val (c, n) = readInts()
val xIn = readInts()
val x = (xIn.map { it - xIn[0] } + c).map { it * 2 }
readLn()
var maxMask = (1 shl (2 * c + 1)) - 1
for (v in x) maxMask = maxMask xor (1 shl v)
var ans = 2 * n
var mask = maxMask
while (mask > 0) {
if (mask.countOneBits() > ans) {
mask = (mask - 1) and maxMask
continue
}
val indices = (0 until 2 * c).filter { ((mask shr it) and 1) == 1 }
if (indices.toSet().intersect(x).isNotEmpty()) {
mask = (mask - 1) and maxMask
continue
}
var good = indices.first() == (2 * c - indices.last())
if (!good) {
mask = (mask - 1) and maxMask
continue
}
for (i in 1 until x.size) {
val inside = (x[i - 1] + 1) until x[i]
if (inside.toSet().intersect(indices).isEmpty()) good = false
}
if (!good) {
mask = (mask - 1) and maxMask
continue
}
for (i in 1..x.size - 2) {
val prev = indices.last { it < x[i] }
val next = indices.first { it > x[i] }
if (prev + next != 2 * x[i]) good = false
}
if (good) ans = minOf(ans, indices.size)
mask = (mask - 1) and maxMask
}
return ans
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun Int.countOneBits(): Int = Integer.bitCount(this)
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,459 | competitions | The Unlicense |
codeforces/round901/b.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round901
private fun precalc(mask: Int): IntArray {
val (a, b, m) = listOf(0x55, 0x33, 0x0F).map { it and mask }
val source = a with b
val queue = mutableListOf<Int>()
val dist = IntArray(1 shl 14) { -1 }
queue.add(source)
dist[source] = 0
var low = 0
while (low < queue.size) {
val v = queue[low++]
fun move(xx: Int, yy: Int) {
val u = xx with yy
if (dist[u] != -1) return
dist[u] = dist[v] + 1
queue.add(u)
}
val (x, y) = decode(v)
move(x and y, y)
move(x or y, y)
move(x, y xor x)
move(x, y xor m)
}
return dist
}
private val precalc = List(128) { precalc(it) }
private fun solve(): Int {
val (a, b, c, d, m) = readInts()
var mask = 128; var cWant = 0; var dWant = 0
for (i in 0 until Int.SIZE_BITS) {
val type = 7 - a[i] - (b[i] shl 1) - (m[i] shl 2)
if (mask[type] == 1) {
if (c[i] != cWant[type] || d[i] != dWant[type]) return -1
continue
}
mask = mask.setBit(type)
if (c[i] == 1) cWant = cWant.setBit(type)
if (d[i] == 1) dWant = dWant.setBit(type)
}
return precalc[mask - 128][cWant with dWant]
}
fun main() = repeat(readInt()) { println(solve()) }
private infix fun Int.with(that: Int) = shl(7) or that
fun decode(code: Int) = (code ushr 7) to (code and 0x7F)
private fun Int.bit(index: Int) = ushr(index) and 1
private fun Int.setBit(index: Int) = or(1 shl index)
private operator fun Int.get(index: Int) = bit(index)
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,561 | competitions | The Unlicense |
src/Day12.kt | bananer | 434,885,332 | false | {"Kotlin": 36979} | fun main() {
class Cave(
val name: String,
val connections: MutableSet<Cave> = mutableSetOf()
) {
val isStart
get() = name == "start"
val isEnd
get() = name == "end"
val isSmall
get() = !isStart && !isEnd && name.lowercase() == name
val isLarge
get() = !isStart && !isEnd && name.uppercase() == name
override fun equals(other: Any?): Boolean {
return (this === other)
|| (other as Cave).name == name
}
override fun hashCode(): Int {
return name.hashCode()
}
override fun toString(): String {
return "Cave($name)"
}
}
fun parseInput(input: List<String>): Map<String, Cave> {
val result = mutableMapOf<String, Cave>()
fun cave(name: String): Cave = result.computeIfAbsent(name) {
Cave(name)
}
input.forEach { line ->
val (nameFrom, nameTo) = line.split("-")
val from = cave(nameFrom)
val to = cave(nameTo)
from.connections.add(to)
to.connections.add(from)
}
return result
}
fun paths(head: List<Cave>, mayRevisitSingleSmallCave: Boolean): Set<List<Cave>> {
val currentCave = head.last()
if (currentCave.isEnd) {
return setOf(head)
}
return currentCave.connections
.filter {
if (it.isLarge || it.isEnd) {
// can always enter large cave and end cave
true
}
else if(it.isStart) {
// never return to start cave
false
}
else if (it.isSmall) {
if (head.contains(it)) {
// about to visit a small cave a second time
if (!mayRevisitSingleSmallCave) {
false
}
else {
// only proceed if we have not visited a small cave twice
head
.filter { c -> c.isSmall }
.let { caves ->
caves.toSet().size == caves.size
}
}
}
else {
// did not visit this small cave yet
true
}
}
else {
throw IllegalStateException()
}
}
.flatMap {
paths(head.plus(it), mayRevisitSingleSmallCave)
}
.toSet()
}
fun part1(input: List<String>): Int {
val caves = parseInput(input)
val paths = paths(listOf(caves["start"]!!), false)
return paths.size
}
fun part2(input: List<String>): Int {
val caves = parseInput(input)
val paths = paths(listOf(caves["start"]!!), true)
return paths.size
}
// test if implementation meets criteria from the description, like:
val testInput0 = readInput("Day12_test0")
val testInput1 = readInput("Day12_test1")
val testInput2 = readInput("Day12_test2")
check(part1(testInput0) == 10)
check(part1(testInput1) == 19)
check(part1(testInput2) == 226)
check(part2(testInput0) == 36)
check(part2(testInput1) == 103)
check(part2(testInput2) == 3509)
val input = readInput("Day12")
println("output part1: ${part1(input)}")
println("output part2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 98f7d6b3dd9eefebef5fa3179ca331fef5ed975b | 3,744 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/solutions/Day5SupplyStacks.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import utils.Collections
import utils.Input
import utils.Solution
// run only this day
fun main() {
Day5SupplyStacks()
}
class Day5SupplyStacks : Solution() {
init {
begin("Day 5 - Supply Stacks")
val input = Input.parseLines(filename = "/d5_crane_procedure.txt")
val stackRows = input.takeWhile { it.isNotEmpty() }.dropLast(1)
val stacks = getVerticalStacksV2(stackRows)
val instructions = getInstructions(input.drop(stackRows.size + 2))
// list mapped in argument to make a copy and reuse the original stack for part 2
val sol1 = moveAndListTopCrates(stacks.map { it.toMutableList() }, instructions)
output("Top Crates CrateMover9000", sol1)
val sol2 = moveAndListTopCrates(stacks, instructions, isCrateMover9001 = true)
output("Top Crates CrateMover9001", sol2)
}
// return lists of stacks with top crate at end of lists (checked - top first takes same amount of time :)
private fun getVerticalStacks(input: List<String>): List<MutableList<Char>> {
val stackRows = input.map { line ->
// replace blank spaces with 'x'
line.replace(("""\s{2,}""").toRegex()) { match ->
val xBlock = StringBuilder()
for (i in match.range.step(5)) {
xBlock.append('x')
}
xBlock
// remove brackets
}.replace(("""\[(.)\]""").toRegex()) { match ->
match.groupValues.last()
// map crates to list of single Chars
}.replace(" ", "")
.split("")
.filter { it.isNotBlank() }
.map { it.single() }
}
// transpose the list from rows to vertical stacks (was read in horizontally)
return Collections.transposeList(stackRows)
.map { col ->
col.filter { it != 'x' }
.reversed().toMutableList()
}
}
// 2nd parsing method! simpler, a bit faster, uses padding and expected positioning to get crates
private fun getVerticalStacksV2(input: List<String>): List<MutableList<Char>> {
val strLen = input.last().length
val stackRows = input.map { line ->
val padLine = line.padEnd(strLen,' ')
val row = mutableListOf<Char>()
for (i in 1 until strLen step 4) {
val c = padLine[i]
if (c != ' ') row.add(c)
else row.add('x')
}
return@map row
}
// transpose the list from rows to vertical stacks (was read in horizontally)
return Collections.transposeList(stackRows)
.map { col ->
col.filter { it != 'x' }
.reversed().toMutableList()
}
}
// convert instructions into index values
private fun getInstructions(input: List<String>): List<List<Int>> =
input.map { line ->
line.split("move ", " from ", " to ")
.filter { it.isNotBlank() }
.mapIndexed { i, n ->
// subtract index values to match 0-index lists, but amount to move stays same
n.toInt() - if (i == 0) 0 else 1
}
}
// perform movement operations and output string of top crates
private fun moveAndListTopCrates(
stacks: List<MutableList<Char>>,
instructions: List<List<Int>>,
isCrateMover9001: Boolean = false
): String {
instructions.forEach { ins ->
val numToMove = ins[0]
val fromStack = stacks[ins[1]]
val toStack = stacks[ins[2]]
val taken = fromStack.removeCrates(numToMove)
if (isCrateMover9001) toStack.addCratesMultiple(taken)
else toStack.addCratesSingle(taken)
}
return stacks.map { it.last() }.joinToString("")
}
private fun MutableList<Char>.removeCrates(num: Int): List<Char> {
// these must be added to other stack
val taken = takeLast(num)
var n = num
while (n > 0) {
removeLast()
n--
}
return taken
}
private fun MutableList<Char>.addCratesSingle(crates: List<Char>) = addAll(crates.reversed())
private fun MutableList<Char>.addCratesMultiple(crates: List<Char>) = addAll(crates)
} | 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 4,441 | advent-of-code-2022 | MIT License |
src/Day22.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | object Day22 {
private enum class MoveDirection {
RIGHT, DOWN, LEFT, UP;
val opposite: MoveDirection
get() = when (this) {
UP -> DOWN
RIGHT -> LEFT
DOWN -> UP
LEFT -> RIGHT
}
fun turn(where: Turn): MoveDirection = when (where) {
Turn.LEFT -> when (this) {
UP -> LEFT
RIGHT -> UP
DOWN -> RIGHT
LEFT -> DOWN
}
Turn.RIGHT -> when (this) {
UP -> RIGHT
RIGHT -> DOWN
DOWN -> LEFT
LEFT -> UP
}
}
}
private sealed interface Command
private data class Move(val distance: Int) : Command
private enum class Turn : Command {
LEFT, RIGHT
}
private enum class Tile {
EMPTY, WALL, FLOOR
}
private fun Char.toTile(): Tile = when (this) {
'#' -> Tile.WALL
'.' -> Tile.FLOOR
' ' -> Tile.EMPTY
else -> throw IllegalArgumentException("Unknown tile: $this")
}
private fun splitToDitigsAndLetters(input: String): List<String> {
val result = mutableListOf<String>()
var current = ""
for (c in input) {
if (c.isDigit()) {
current += c
} else {
if (current.isNotEmpty()) {
result.add(current)
current = ""
}
result.add(c.toString())
}
}
if (current.isNotEmpty()) {
result.add(current)
}
return result
}
// parses string like "10R23L5" to listOf(Move(10), Turn.RIGHT, Move(23), Turn.LEFT, Move(5))
private fun parsePath(input: String): List<Command> {
val lettersAndDigits = splitToDitigsAndLetters(input)
return lettersAndDigits.map {
if (it.first().isDigit()) {
Move(it.toInt())
} else {
when (it) {
"R" -> Turn.RIGHT
"L" -> Turn.LEFT
else -> throw IllegalArgumentException("Unknown command: $it")
}
}
}
}
private data class Pos(val x: Int, val y: Int) {
fun move(direction: MoveDirection): Pos = when (direction) {
MoveDirection.UP -> copy(x = x - 1)
MoveDirection.RIGHT -> copy(y = y + 1)
MoveDirection.DOWN -> copy(x = x + 1)
MoveDirection.LEFT -> copy(y = y - 1)
}
}
private fun computePassword(pos: Pos, direction: MoveDirection): Int {
return (pos.x + 1) * 1000 + (pos.y + 1) * 4 + direction.ordinal
}
private fun part1(input: List<String>): Int {
val path = parsePath(input.last())
val labirinth = input.dropLast(2).map { it.map { it.toTile() }.toMutableList() }.toList()
val height = labirinth.size
val width = labirinth.maxOf { it.size }
labirinth.forEach { row -> repeat(width - row.size) { row.add(Tile.EMPTY) } }
var pos = Pos(0, labirinth.first().indexOf(Tile.FLOOR))
var direction = MoveDirection.RIGHT
fun inLabyrinth(pos: Pos): Boolean = pos.x in 0 until height && pos.y in 0 until width
fun findFurthestTile(pos: Pos, direction: MoveDirection): Pos {
return generateSequence(pos) { it.move(direction) }
.takeWhile { inLabyrinth(it) }
.filter {
require(inLabyrinth(it))
labirinth[it.x][it.y] != Tile.EMPTY
}
.last()
}
fun findNextPos(pos: Pos, direction: MoveDirection): Pos {
val nextPos = pos.move(direction).takeIf { inLabyrinth(it) && labirinth[it.x][it.y] != Tile.EMPTY }
?: findFurthestTile(pos, direction.opposite)
require(inLabyrinth(nextPos))
return when (labirinth[nextPos.x][nextPos.y]) {
Tile.EMPTY -> error("Unexpected wrapped tile")
Tile.WALL -> pos
Tile.FLOOR -> nextPos
}
}
for (command in path) {
when (command) {
is Move -> {
repeat(command.distance) {
pos = findNextPos(pos, direction)
}
}
is Turn -> {
direction = direction.turn(command)
}
}
}
return computePassword(pos, direction)
}
@JvmStatic
fun main(args: Array<String>) {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day22_test")
check(part1(testInput) == 6032)
val input = readInput("Day22")
println(part1(input))
}
}
| 0 | Kotlin | 0 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 4,915 | aoc2022 | Apache License 2.0 |
src/main/kotlin/Day15.kt | andrewrlee | 434,584,657 | false | {"Kotlin": 29493, "Clojure": 14117, "Shell": 398} | import java.io.File
import java.nio.charset.Charset.defaultCharset
import kotlin.streams.toList
typealias ChitonGrid = Map<Pair<Int, Int>, Day15.Square>
object Day15 {
private fun toCoordinates(row: Int, line: String) = line.chars()
.map(Character::getNumericValue)
.toList()
.mapIndexed { col, value -> (col to row) to Square((col to row), value) }
private fun draw(coordinates: Collection<Square>) {
println("\n")
val maxCols = coordinates.maxOf { it.coord.first }
val maxRows = coordinates.maxOf { it.coord.second }
(0..maxRows).forEach { row ->
(0..maxCols).forEach { col ->
print(coordinates.find { it.coord == Pair(col, row) }?.let { it.risk } ?: ".")
}
println()
}
}
data class Square(
var coord: Pair<Int, Int>,
var risk: Int,
var distance: Int = Int.MAX_VALUE,
var parent: Square? = null
): Comparable<Square> {
fun getNeighbours(
validCells: ChitonGrid,
remaining: Collection<Square>,
deltas: List<Pair<Int, Int>> = listOf(
-1 to 0, 0 to -1,
1 to 0, 0 to 1,
)
) = deltas.asSequence()
.map { (x2, y2) -> coord.first + x2 to coord.second + y2 }
.mapNotNull { validCells[it] }
.filter { remaining.contains(it) }
override fun compareTo(other: Square): Int {
return this.distance.compareTo(other.distance)
}
}
object Part1 {
val chitonGrid = {
File("day15/input-real.txt")
.readLines(defaultCharset())
.mapIndexed(::toCoordinates)
.flatten()
.associate { it }
}
fun run() {
val grid = chitonGrid()
grid.values.first().distance = 0
val queue = grid.values.toMutableList()
while (queue.isNotEmpty()) {
val next = queue.minOrNull()!!
queue.remove(next)
val neighbours = next.getNeighbours(grid, queue)
neighbours.forEach {
if (next.distance + next.risk < it.distance) {
it.distance = next.distance + next.risk
it.parent = next
}
}
}
var end = grid.values.last()
val parents = mutableListOf(end)
while(end.parent != null) {
end = end.parent!!
parents.add(end)
}
draw(parents)
parents.reversed().forEach { println("${it.coord} ${it.risk} ${it.distance}") }
parents.sumOf { it.risk }.also { println(it - grid.values.first().risk) }
}
}
object Part2 {
private fun toCoordinates(row: Int, line: List<Int>) = line
.mapIndexed { col, value -> (col to row) to Square((col to row), value) }
fun run() {
val grid = File("day15/input-real.txt")
.readLines(defaultCharset())
.map { it.map (Character::getNumericValue) }
.map { vals -> (0..4).flatMap{ i -> vals.map { round(it, i) }}}.let{
grid -> (0..4).flatMap{ i -> grid.map { row -> row.map { round(it, i) } }}
}.mapIndexed { i, it -> toCoordinates(i, it) }
.flatten()
.associate { it }
grid.values.first().distance = 0
val queue = grid.values.toMutableList()
val total = queue.size
var count = 0
while (queue.isNotEmpty()) {
if (count++ % 500 == 0) {
println("$count/$total (${queue.size})")
}
val next = queue.minOrNull()!!
queue.remove(next)
val neighbours = next.getNeighbours(grid, queue)
neighbours.forEach {
if (next.distance + next.risk < it.distance) {
it.distance = next.distance + next.risk
it.parent = next
}
}
}
var end = grid.values.last()
val parents = mutableListOf(end)
while(end.parent != null) {
end = end.parent!!
parents.add(end)
}
draw(parents)
parents.reversed().forEach { println("${it.coord} ${it.risk} ${it.distance}") }
parents.sumOf { it.risk }.also { println(it - grid.values.first().risk) }
}
}
private fun round(it: Int, i: Int): Int {
val x = it + i
val y = x - 9
return if (y > 0) y else x
}
}
fun main() {
Day15.Part1.run()
Day15.Part2.run() // 21 mins!
} | 0 | Kotlin | 0 | 0 | aace0fccf9bb739d57f781b0b79f2f3a5d9d038e | 4,872 | adventOfCode2021 | MIT License |
year2019/src/main/kotlin/net/olegg/aoc/year2019/day24/Day24.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2019.day24
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.Companion.NEXT_4
import net.olegg.aoc.utils.Directions.D
import net.olegg.aoc.utils.Directions.L
import net.olegg.aoc.utils.Directions.R
import net.olegg.aoc.utils.Directions.U
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.get
import net.olegg.aoc.year2019.DayOf2019
/**
* See [Year 2019, Day 24](https://adventofcode.com/2019/day/24)
*/
object Day24 : DayOf2019(24) {
override fun first(): Any? {
val start = matrix
val visited = mutableSetOf<String>()
var curr = start
while (curr.footprint() !in visited) {
visited += curr.footprint()
curr = curr.mapIndexed { y, row ->
row.mapIndexed { x, c ->
val neighbors = NEXT_4.map { it.step + Vector2D(x, y) }
.mapNotNull { curr[it] }
.count { it == '#' }
when {
c == '.' && neighbors in 1..2 -> '#'
c == '#' && neighbors != 1 -> '.'
else -> c
}
}
}
}
return curr.footprint()
.reversed()
.replace('.', '0')
.replace('#', '1')
.toBigInteger(2)
}
override fun second(): Any? {
val start = matrix
val size = start.size
val center = Vector2D(size / 2, size / 2)
val empty = List(size * size) { '.' }.chunked(size)
val result = (1..200).fold(mapOf(0 to start).withDefault { empty }) { acc, count ->
(-count..count).associateWith { level ->
val prev = acc.getValue(level)
return@associateWith prev.mapIndexed { y, row ->
row.mapIndexed { x, c ->
val base = Vector2D(x, y)
val neighbors = NEXT_4.map { it to it.step + base }
.flatMap { (dir, point) ->
when {
point == center -> when (dir) {
L -> (0..<size).map { level - 1 to Vector2D(size - 1, it) }
R -> (0..<size).map { level - 1 to Vector2D(0, it) }
U -> (0..<size).map { level - 1 to Vector2D(it, size - 1) }
D -> (0..<size).map { level - 1 to Vector2D(it, 0) }
else -> emptyList()
}
point.x < 0 -> listOf(level + 1 to center + L.step)
point.x >= size -> listOf(level + 1 to center + R.step)
point.y < 0 -> listOf(level + 1 to center + U.step)
point.y >= size -> listOf(level + 1 to center + D.step)
else -> listOf(level to point)
}
}
.count { (level, point) ->
acc.getValue(level)[point] == '#'
}
when {
base == center -> '?'
c == '.' && neighbors in 1..2 -> '#'
c == '#' && neighbors != 1 -> '.'
else -> c
}
}
}
}.withDefault { empty }
}
return result.values
.sumOf { level ->
level.sumOf { row ->
row.count { it == '#' }
}
}
}
private fun List<List<Char>>.footprint() = joinToString("") { it.joinToString("") }
}
fun main() = SomeDay.mainify(Day24)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 3,225 | adventofcode | MIT License |
src/main/kotlin/day23/Day23.kt | Zordid | 160,908,640 | false | null | package day23
import shared.extractAllInts
import shared.measureRuntime
import shared.minToMaxRange
import shared.readPuzzle
import kotlin.math.abs
import kotlin.math.max
import kotlin.random.Random
data class Coordinate3d(val x: Int, val y: Int, val z: Int) {
infix fun manhattanDistanceTo(other: Coordinate3d) =
abs(x - other.x) + abs(y - other.y) + abs(z - other.z)
operator fun plus(other: Coordinate3d) = Coordinate3d(x + other.x, y + other.y, z + other.z)
operator fun minus(other: Coordinate3d) = Coordinate3d(x - other.x, y - other.y, z - other.z)
operator fun unaryMinus() = Coordinate3d(-x, -y, -z)
override fun toString() = "($x,$y,$z)"
}
data class NanoBot(val coordinate: Coordinate3d, val signalRadius: Int) {
infix fun inRangeOf(other: NanoBot) = coordinate manhattanDistanceTo other.coordinate <= other.signalRadius
}
fun coordinateInRange(coordinate: Coordinate3d, bot: NanoBot) =
coordinate manhattanDistanceTo bot.coordinate <= bot.signalRadius
fun part1(puzzle: List<List<Int>>): Any {
val bots = puzzle.map { (x, y, z, r) -> NanoBot(Coordinate3d(x, y, z), r) }
val strongest = bots.maxBy { it.signalRadius }
return bots.count { it inRangeOf strongest }
}
class Optimizer(private val bots: List<NanoBot>) {
val origin = Coordinate3d(0, 0, 0)
val boundedBy = bots.map { it.coordinate } + listOf(origin)
val boundsX = boundedBy.map { it.x }.minToMaxRange()!!
val boundsY = boundedBy.map { it.y }.minToMaxRange()!!
val boundsZ = boundedBy.map { it.z }.minToMaxRange()!!
var bestPoint = origin
var bestCount = 0
var bestDistance = 0
private fun testPoint(point: Coordinate3d) {
val c = bots.count { coordinateInRange(point, it) }
if (c >= bestCount) {
val d = point manhattanDistanceTo origin
if (c > bestCount || d < bestDistance) {
updateBest(point, d, c)
if (c > 800) {
improve(point, 20000, 2000)
}
println("Moving on")
}
}
}
tailrec fun improve(pStart: Coordinate3d, rangeToTry: Int, increment: Int) {
val range = -rangeToTry until rangeToTry step increment
var p = pStart
start@
for (xd in range) {
for (yd in range) {
for (zd in range) {
val delta = Coordinate3d(xd, yd, zd)
val p2 = p + delta
val c2 = bots.count { coordinateInRange(p2, it) }
if (c2 >= bestCount) {
val d2 = p2 manhattanDistanceTo origin
if (c2 > bestCount || d2 < bestDistance) {
updateBest(p2, d2, c2)
p = bestPoint
continue@start
}
}
}
}
}
if (increment == 1)
return
improve(p, increment + 1, max(1, increment / 5))
}
private fun updateBest(point: Coordinate3d, distance: Int, count: Int) {
bestDistance = distance
bestCount = count
bestPoint = point
println("$bestCount - $bestDistance - $bestPoint")
}
fun optimize() {
while (true) {
testPoint(randomPoint())
}
}
private fun randomPoint(): Coordinate3d = Coordinate3d(
Random.nextInt(boundsX.first, boundsX.last),
Random.nextInt(boundsY.first, boundsY.last),
Random.nextInt(boundsZ.first, boundsZ.last)
)
}
fun part2(puzzle: List<List<Int>>): Any {
val bots = puzzle.map { (x, y, z, r) -> NanoBot(Coordinate3d(x, y, z), r) }
//bots.sortedBy { it.signalRadius }.asReversed().forEach { println(it) }
val o = Optimizer(bots)
return o.optimize()
}
fun main() {
val puzzle = readPuzzle(23) { it.extractAllInts().toList() }
measureRuntime {
println(part1(puzzle))
println(part2(puzzle))
}
} | 0 | Kotlin | 0 | 0 | f246234df868eabecb25387d75e9df7040fab4f7 | 4,033 | adventofcode-kotlin-2018 | Apache License 2.0 |
src/Day09/Day09.kt | G-lalonde | 574,649,075 | false | {"Kotlin": 39626} | package Day09
import readInput
fun main() {
fun move(position: Pair<Int, Int>, to: String): Pair<Int, Int> {
return when (to) {
"R" -> position + Pair(1, 0)
"L" -> position + Pair(-1, 0)
"U" -> position + Pair(0, 1)
"D" -> position + Pair(0, -1)
else -> position
}
}
fun areTouching(first: Pair<Int, Int>, second: Pair<Int, Int>): Boolean {
return !(first.first > second.first + 1
|| first.first < second.first - 1
|| first.second > second.second + 1
|| first.second < second.second - 1)
}
fun part1(input: List<String>): Int {
var headPosition = Pair(0, 0)
var tailPosition = Pair(0, 0)
val positionsOfTail = mutableSetOf<Pair<Int, Int>>()
positionsOfTail.add(tailPosition)
for (line in input) {
val moves = line.split(" ")
val direction = moves[0]
val distance = moves[1].toInt()
for (i in 1..distance) {
headPosition = move(headPosition, direction)
if (!areTouching(headPosition, tailPosition)) {
// move tail
val difference = headPosition - tailPosition
tailPosition += difference
positionsOfTail.add(tailPosition)
}
}
}
return positionsOfTail.size
}
fun part2(input: List<String>): Int {
val positions = MutableList(10) { Pair(0, 0) }
val positionsOfTail = mutableSetOf<Pair<Int, Int>>()
positionsOfTail.add(positions.last())
for (line in input) {
val moves = line.split(" ")
val direction = moves[0]
val distance = moves[1].toInt()
for (i in 1..distance) {
positions[0] = move(positions.first(), direction)
for (j in 1 until positions.size) {
if (!areTouching(positions[j], positions[j - 1])) {
// move tail
val difference = positions[j - 1] - positions[j]
positions[j] += difference
}
positionsOfTail.add(positions.last())
}
}
}
return positionsOfTail.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09/Day09_test")
// check(part1(testInput) == 13) { "Got instead : ${part1(testInput)}" }
check(part2(testInput) == 36) { "Got instead : ${part2(testInput)}" }
val input = readInput("Day09/Day09")
// println("Answer for part 1 : ${part1(input)}")
println("Answer for part 2 : ${part2(input)}")
}
operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> {
// Define a function that adds two pairs together
return Pair(this.first + other.first, this.second + other.second)
}
operator fun Pair<Int, Int>.minus(other: Pair<Int, Int>): Pair<Int, Int> {
// Define a function that adds two pairs together
var x = this.first - other.first
if (x > 1) {
x = 1
}
if (x < -1) {
x = -1
}
var y = this.second - other.second
if (y > 1) {
y = 1
}
if (y < -1) {
y = -1
}
return Pair(x, y)
}
| 0 | Kotlin | 0 | 0 | 3463c3228471e7fc08dbe6f89af33199da1ceac9 | 3,383 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | alexdesi | 575,352,526 | false | {"Kotlin": 9824} | import java.io.File
fun main() {
fun priority(item: Char): Int {
return if (item.isUpperCase())
item.code - 38
else
item.code - 96
}
fun part1(input: List<String>): Int {
val splittedLines = input.map {
Pair(
it.substring(0, it.length / 2).toList(),
it.substring(it.length / 2, it.length).toList()
)
}
val errors = splittedLines.map {
it.first.intersect(it.second).first() // There is only one element (by design)
}
return errors.sumOf { priority(it) }
}
fun part2(input: List<String>): Int {
val groups = input.map {
it.toList()
}.chunked(3)
val badges = groups.map {
it[0].intersect(it[1]).intersect(it[2]).first()
}
return badges.sumOf { priority(it) }
}
// test if implementation meets criteria:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 56a6345e0e005da09cb5e2c7f67c49f1379c720d | 1,147 | advent-of-code-kotlin | Apache License 2.0 |
src/day03/day04.kt | zoricbruno | 573,440,038 | false | {"Kotlin": 13739} | package day03
import readInput
fun getWrongItem(rucksack: String): Char {
val firstPocket = rucksack.take(rucksack.length / 2).toSet()
val secondPocket = rucksack.takeLast(rucksack.length / 2).toSet()
return firstPocket.intersect(secondPocket).first()
}
fun getBadge(elf1: String, elf2: String, elf3: String): Char {
return elf1.toSet().intersect(elf2.toSet().intersect(elf3.toSet())).first()
}
fun getPoints(item: Char): Int {
return if (item in 'a'..'z') item.code - 'a'.code + 1 else item.code - 'A'.code + 27
}
fun part1(input: List<String>): Int {
var total = 0;
for (rucksack in input) {
total += getPoints(getWrongItem(rucksack))
}
return total
}
fun part2(input: List<String>): Int {
var total = 0;
input.chunked(3).forEach{
total += getPoints(getBadge(it[0], it[1], it[2]))
}
return total
}
fun main() {
val day = "Day03"
val test = "${day}_test"
val testInput = readInput(day, test)
val input = readInput(day, day)
val testFirst = part1(testInput)
println(testFirst)
check(testFirst == 157)
println(part1(input))
val testSecond = part2(testInput)
println(testSecond)
check(testSecond == 70)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16afa06aff0b6e988cbea8081885236e4b7e0555 | 1,251 | kotlin_aoc_2022 | Apache License 2.0 |
src/main/kotlin/com/adrielm/aoc2020/solutions/day13/Day13.kt | Adriel-M | 318,860,784 | false | null | package com.adrielm.aoc2020.solutions.day13
import com.adrielm.aoc2020.common.Solution
import org.koin.dsl.module
class Day13 : Solution<Day13.Input, Long>(13) {
override fun solveProblem1(input: Input): Long {
val mods = input.buses.map { input.startingTime % it.number }
if (mods.any { it == 0 }) return 0
val busNumberAndMod = (input.buses zip mods)
.map { it.first.number to it.first.number - it.second }
.minByOrNull { it.second }!!
return (busNumberAndMod.first * busNumberAndMod.second).toLong()
}
override fun solveProblem2(input: Input): Long {
val descendingBuses = input.buses.sortedByDescending { it.number }
var currentTime = (descendingBuses.first().number - descendingBuses.first().position).toLong()
var interval = descendingBuses.first().number.toLong()
// try to lock in interval at each slice by calculating the common multiples between the prior numbers and self
for (i in 1 until descendingBuses.size) {
val currentBus = descendingBuses[i]
while (!isInCorrectOffset(currentTime, currentBus)) {
currentTime += interval
}
interval *= currentBus.number
}
return currentTime
}
private fun isInCorrectOffset(time: Long, bus: Bus): Boolean {
return ((time + bus.position.toLong()) % bus.number.toLong()) == 0L
}
class Input(
val startingTime: Int,
val buses: List<Bus>
)
class Bus(
val number: Int,
val position: Int
)
companion object {
val module = module {
single { Day13() }
single { BusScheduleParser() }
}
}
}
| 0 | Kotlin | 0 | 0 | 8984378d0297f7bc75c5e41a80424d091ac08ad0 | 1,743 | advent-of-code-2020 | MIT License |
src/day07.kt | skuhtic | 572,645,300 | false | {"Kotlin": 36109} | fun main() {
day07.execute(forceBothParts = true)
}
val day07 = object : Day<Long>(7, 95437, 24933642) {
override val testInput: InputData = """
${'$'} cd /
${'$'} ls
dir a
14848514 b.txt
8504156 c.dat
dir d
${'$'} cd a
${'$'} ls
dir e
29116 f
2557 g
62596 h.lst
${'$'} cd e
${'$'} ls
584 i
${'$'} cd ..
${'$'} cd ..
${'$'} cd d
${'$'} ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
""".trimIndent().lines()
override fun part1(input: InputData): Long = getDirsFromInput(input)
.fold(0) { sum, dir -> if (dir.dirSize <= 100_000) sum + dir.dirSize else sum }
override fun part2(input: InputData): Long {
val dirs = getDirsFromInput(input)
val needToFree = 30_000_000 - ( 70_000_000 - dirs.first().dirSize)
return dirs.asSequence().sortedBy { it.dirSize }.first { it.dirSize >= needToFree }.dirSize
}
fun getDirsFromInput(input: InputData) = buildList {
var cd = Dir("", null).also { add(it) }
input.asSequence().drop(1).forEach { cp ->
when {
cp.first().isDigit() -> cd.add(cp.substringBefore(' ').toIntOrNull() ?: error("Input error: $cp"))
cp.startsWith("$ cd ..") -> cd = cd.parent ?: error("cd .. on root")
cp.startsWith("$ cd ") -> cd = Dir(cp.drop(5), cd).also {
cd.add(it)
add(it)
}
cp == "$ ls" -> Unit
cp.startsWith("dir") -> Unit
else -> error("Check input: $cp")
}
}
}
}
class Dir(private val name: String, val parent: Dir?) {
private val children = mutableListOf<Dir>()
private var sizeOfFiles = 0
val dirSize: Long by lazy {
sizeOfFiles + children.sumOf { it.dirSize }
}
private val fullPath: String by lazy {
(parent?.fullPath ?: "/").let {
if (it.endsWith("/")) it + name else "$it/$name"
}
}
override fun toString(): String = "Dir(${dirSize.toString().padStart(10)}, $name, $fullPath)"
fun add(fileSize: Int) {
sizeOfFiles += fileSize
}
fun add(dir: Dir) {
children.add(dir)
}
}
| 0 | Kotlin | 0 | 0 | 8de2933df90259cf53c9cb190624d1fb18566868 | 2,350 | aoc-2022 | Apache License 2.0 |
src/Day01.kt | TrevorSStone | 573,205,379 | false | {"Kotlin": 9656} | fun main() {
fun part1(input: List<String>): Int {
var maxCalories = 0
(input + "end").fold(0) { currentElfCalories, calLine ->
calLine.toIntOrNull()?.let { currentElfCalories + it }
?: run {
if (currentElfCalories > maxCalories) {
maxCalories = currentElfCalories
}
0
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
var topCalories = 0
var secondCalories = 0
var thirdCalories = 0
(input + "end").fold(0) { currentElfCalories, calLine ->
calLine.toIntOrNull()?.let { currentElfCalories + it }
?: run {
when {
currentElfCalories >= topCalories -> {
thirdCalories = secondCalories
secondCalories = topCalories
topCalories = currentElfCalories
}
currentElfCalories >= secondCalories -> {
thirdCalories = secondCalories
secondCalories = currentElfCalories
}
currentElfCalories >= thirdCalories -> {
thirdCalories = currentElfCalories
}
}
0
}
}
return topCalories + secondCalories + thirdCalories
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2a48776f8bc10fe1d7e2bbef171bf65be9939400 | 1,547 | advent-of-code-2022-kotlin | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day21/Day21.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day21
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputLines
object Day21 : Day {
override val input = readInputLines(21).map { Player.from(it) }
override fun part1(): Int {
var count = 0
val dice = DeterministicDice()
val players = input.map { it.copy() }
while (players.none { it.score >= 1000 }) {
players[count++ % 2].moves(dice)
}
return players.minOf { it.score } * dice.count
}
override fun part2(): Number {
val cache = mutableMapOf<Pair<Player, Player>, Pair<Long, Long>>()
fun play(players: Pair<Player, Player>): Pair<Long, Long> {
cache[players]?.let { return it }
var scores = 0L to 0L
for (d1 in 1..3) for (d2 in 1..3) for (d3 in 1..3) {
val next = players.first.copy().apply { moves(FixedDice(listOf(d1, d2, d3))) }
val (x, y) = if (next.score >= 21) 0L to 1L else play(players.second.copy() to next)
scores = scores.first + y to scores.second + x
}
return scores.also { cache[players] = it }
}
return play(input.first() to input.last()).let { maxOf(it.first, it.second) }
}
data class Player(var position: Int, var score: Int = 0) {
companion object {
fun from(line: String) = Player(line.substringAfter(": ").toInt())
}
fun moves(dice: Dice) {
position = (position + dice.roll() + dice.roll() + dice.roll() - 1) % 10 + 1
score += position
}
}
sealed interface Dice {
var count: Int
fun roll(): Int
}
class DeterministicDice : Dice {
private var state = 0
override var count = 0
override fun roll() = ((state++ % 100) + 1).also { count++ }
}
class FixedDice(private val outcomes: List<Int>) : Dice {
override var count = 0
override fun roll() = outcomes[count++]
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 2,063 | aoc2021 | MIT License |
src/main/kotlin/aoc2021/Day17.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import Point
import readInput
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.sign
/**
* A path is just a collection of points
* @property points the points along this path
*/
@JvmInline
private value class Path(val points: List<Point>)
/**
* @param vx the initial x velocity
* @param vy the initial y velocity
* @return a sequence of points when starting at (0,0) and the given initial accelerations
*/
private fun getPositions(vx: Int, vy: Int): Sequence<Point> {
var currentVelocityX = vx
var currentVelocityY = vy
return generateSequence(Point(0, 0)) {
val p = it.move(currentVelocityX, currentVelocityY)
currentVelocityX -= currentVelocityX.sign
currentVelocityY--
p
}
}
/**
* @param input the input describing the position of the target area in the form of "target area: x=20..30, y=-10..-5"
* @return all valid paths, which have at least one position within the given target area when starting at point (0,0)
*/
private fun getValidPaths(input: String): List<Path> {
val area = input.drop("target area: x=".length).split(", y=").map { it.split("..") }
val areaX = IntRange(area[0][0].toInt(), area[0][1].toInt())
val areaY = IntRange(area[1][0].toInt(), area[1][1].toInt())
// TODO: currently assumed that target area is on the bottom right somewhere
// calculate initial x velocities, which result in an x coordinate within areaX at some point
// example: x positions with velocity 5 after each step: 0, 5, 5+4, 5+4+3, 5+4+3+2, 5+4+3+2+1
val validXAccelerations = IntRange(1, areaX.last).filter { initialVelocity ->
var positionX = 0
for (velocityX in initialVelocity downTo 0) {
if (positionX in areaX) {
return@filter true
}
positionX += velocityX
}
false
}
// same for y, but here we can shoot up- and downwards (or not shoot in y direction at all and just let it fall)
val maxY = max(areaY.first.absoluteValue, areaY.last.absoluteValue)
val validYAccelerations = IntRange(-maxY, maxY).filter { initialVelocity ->
var positionY = 0
var velocityY = initialVelocity
while (positionY >= areaY.first) {
if (positionY in areaY) {
return@filter true
}
positionY += velocityY
velocityY--
}
false
}
// build list of all paths
return buildList {
for (vx in validXAccelerations) {
for (vy in validYAccelerations) {
// generate positions as long as there is a chance to end up within the target area
add(Path(getPositions(vx, vy).takeWhile { it.x <= areaX.last && it.y >= areaY.first }.toList()))
}
}
// filter only those paths, where at least one position is within the target area (aka 'valid paths')
}.filter { it.points.any { pos -> pos.x in areaX && pos.y in areaY } }
}
private fun part1(input: String) = getValidPaths(input).map { path -> path.points.maxOf { it.y } }.maxOf { it }
private fun part2(input: String) = getValidPaths(input).count()
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day17_test").first()
check(part1(testInput) == 45)
check(part2(testInput) == 112)
val input = readInput("Day17").first()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,497 | adventOfCode | Apache License 2.0 |
src/Day05.kt | mrwhoknows55 | 573,993,349 | false | {"Kotlin": 4863} | import java.io.File
import java.util.Stack
fun main() {
val inputPair = getInputPair("src/day05_input.txt")
part1(inputPair)
}
fun part1(inputPair: Pair<List<Stack<Char>>, List<Triple<Int, Int, Int>>>) {
val stacks = inputPair.first
val inputs = inputPair.second
inputs.forEach {
for (i in 0 until it.first) {
if (stacks.size >= it.second) {
val selected = stacks[it.second - 1]
if (stacks.size >= it.third && selected.isNotEmpty()) {
stacks[it.third - 1].push(selected.peek())
selected.pop()
}
}
}
}
val ans = stacks.joinToString(separator = "") {
it.peek().toString()
}
println(ans)
}
fun getInputPair(fileName: String): Pair<List<Stack<Char>>, List<Triple<Int, Int, Int>>> {
val fileInput = File(fileName).readText().split("\n\n")
val other = fileInput[1].split("\n")
val inputs = other.map {
val words = it.split(" ")
Triple(words[1].toInt(), words[3].toInt(), words[5].toInt())
}
val matrix = fileInput.first()
var str = ""
matrix.forEachIndexed { i, c ->
if (i % 4 == 0) {
str += "["
} else if (i % 2 == 0) {
str += "]"
} else {
str += c
}
}
val lets = str.replace("[ ]", "-").replace("[", "").replace("]", "").replace(" ", "").split("\n").map {
it.split("").filter { it.isNotBlank() }
}
val length = lets.last().size
val letters = lets.dropLast(1)
val stacks = mutableListOf<Stack<Char>>()
for (i in 0 until length) {
stacks.add(Stack())
for (j in 0 until length) {
if (letters.size > j && letters[j].size > i) letters[j][i].let {
if (it != "-") stacks[i].add(it.first())
}
}
stacks[i].reverse()
}
return Pair(stacks.toList(), inputs)
}
| 0 | Kotlin | 0 | 1 | f307e524412a3ed27acb93b7b9aa6aa7269a6d03 | 1,947 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | khongi | 572,983,386 | false | {"Kotlin": 24901} | sealed class HandGesture {
abstract val score: Int
abstract val defeats: HandGesture
abstract val losesTo: HandGesture
}
object Rock : HandGesture() {
override val score = 1
override val defeats = Scissors
override val losesTo = Paper
}
object Paper : HandGesture() {
override val score: Int = 2
override val defeats = Rock
override val losesTo = Scissors
}
object Scissors : HandGesture() {
override val score: Int = 3
override val defeats = Paper
override val losesTo = Rock
}
fun main() {
fun Char.getHandGesture(): HandGesture {
return when (this) {
'A', 'X' -> Rock
'B', 'Y' -> Paper
'C', 'Z' -> Scissors
else -> throw IllegalArgumentException("Input can't be $this")
}
}
fun Char.getStrategyHandGesture(enemy: HandGesture): HandGesture {
return when (this) {
'X' -> enemy.defeats
'Y' -> enemy
'Z' -> enemy.losesTo
else -> throw IllegalArgumentException("Input can't be $this")
}
}
fun HandGesture.calculateRound(enemy: HandGesture): Int {
val combatScore = if (this.defeats == enemy) {
6
} else if (this.losesTo == enemy) {
0
} else {
3
}
return combatScore + this.score
}
fun part1(input: List<String>): Int {
var sum = 0
input.forEach { line ->
val them = line[0].getHandGesture()
val us = line[2].getHandGesture()
sum += us.calculateRound(them)
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.forEach { line ->
val them = line[0].getHandGesture()
val us = line[2].getStrategyHandGesture(them)
sum += us.calculateRound(them)
}
return sum
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9cc11bac157959f7934b031a941566d0daccdfbf | 2,111 | adventofcode2022 | Apache License 2.0 |
src/Day08.kt | tristanrothman | 572,898,348 | false | null | import kotlin.math.abs
data class Tree(
val height: Int,
var visible: Boolean = false,
var scenicScore: Int = 0
)
typealias Grid = List<List<Tree>>
fun main() {
val input = readInput("Day08")
val testInput = readInput("Day08_test")
fun List<String>.toGrid() = this.map { row -> row.map { Tree(it.digitToInt()) } }
fun Grid.isBorder(i: Int, j: Int) = (i == 0 || i == this.size - 1) || (j == 0 || j == this[i].size - 1)
fun Grid.checkLeft(i: Int, j: Int) = (j - 1 downTo 0).map { k ->
this[i][k].height < this[i][j].height
}.all { it }
fun Grid.scoreLeft(i: Int, j: Int): Int {
var d = j
for (k in j - 1 downTo 0) {
if (this[i][k].height >= this[i][j].height) {
d = j - k
break
}
}
return d
}
fun Grid.checkRight(i: Int, j: Int) = (j + 1 until this.size).map { k ->
this[i][k].height < this[i][j].height
}.all { it }
fun Grid.scoreRight(i: Int, j: Int): Int {
var d = this[i].size - j - 1
for (k in j + 1 until this.size) {
if (this[i][k].height >= this[i][j].height) {
d = k - j
break
}
}
return d
}
fun Grid.checkUp(i: Int, j: Int) = (i - 1 downTo 0).map { k ->
this[k][j].height < this[i][j].height
}.all { it }
fun Grid.scoreUp(i: Int, j: Int): Int {
var d = i
for (k in i - 1 downTo 0) {
if (this[k][j].height >= this[i][j].height) {
d = i - k
break
}
}
return d
}
fun Grid.checkDown(i: Int, j: Int) = (i + 1 until this[i].size).map { k ->
this[k][j].height < this[i][j].height
}.all { it }
fun Grid.scoreDown(i: Int, j: Int): Int {
var d = this.size - i - 1
for(k in i + 1 until this[i].size) {
if(this[k][j].height >= this[i][j].height) {
d = k - i
break
}
}
return d
}
fun Grid.expedition() {
for (i in this.indices) {
for (j in this[i].indices) {
this[i][j].scenicScore = scoreLeft(i, j) * scoreRight(i, j) * scoreUp(i, j) * scoreDown(i, j)
if (this.isBorder(i, j)) {
this[i][j].visible = true
}
if (this.checkLeft(i, j) || this.checkRight(i, j) || this.checkUp(i, j) || this.checkDown(i, j)) {
this[i][j].visible = true
}
}
}
}
val grid = input.toGrid()
val testGrid = testInput.toGrid()
testGrid.expedition()
grid.expedition()
fun part1(test: Boolean = false): Int {
return (if (test) testGrid else grid).flatten().count { it.visible }
}
fun part2(test: Boolean = false): Int {
return (if (test) testGrid else grid).flatten().maxOf { it.scenicScore }
}
check(part1(true) == 21)
println(part1())
check(part2(true) == 8)
println(part2())
} | 0 | Kotlin | 0 | 0 | e794ab7e0d50f22d250c65b20e13d9b5aeba23e2 | 3,075 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | jdpaton | 578,869,545 | false | {"Kotlin": 10658} | fun main() {
fun part1() {
val testInput = readInput("Day04_test")
var fullOverlapCount = 0
val rangeIter = mapToRanges(testInput).iterator()
while(rangeIter.hasNext()) {
val rangePair = rangeIter.next()
val allInOne = rangePair.first.all { t-> rangePair.second.contains(t) }
val allInTwo = rangePair.second.all { t-> rangePair.first.contains(t) }
if(allInOne || allInTwo) {
fullOverlapCount += 1
}
}
println("Pt1 count: $fullOverlapCount")
}
fun part2() {
val testInput = readInput("Day04_test")
var partialOverlapCount = 0
val rangeIter = mapToRanges(testInput).iterator()
while(rangeIter.hasNext()) {
val rangePair = rangeIter.next()
val allInOne = rangePair.first.any { t-> rangePair.second.contains(t) }
val allInTwo = rangePair.first.any { t-> rangePair.second.contains(t) }
if(allInOne || allInTwo) {
partialOverlapCount += 1
}
}
println("Pt2 count: $partialOverlapCount")
}
part1()
part2()
}
fun mapToRanges(input: List<String>) = sequence {
input.forEach { line ->
val pair = line.split(",")
val ranges = pair.map { it.split("-") }
check(ranges.size == 2)
val rangeOne = (ranges[0][0].toInt()..ranges[0][1].toInt()).toList()
val rangeTwo = (ranges[1][0].toInt()..ranges[1][1].toInt()).toList()
yield(Pair(rangeOne,rangeTwo))
}
}
| 0 | Kotlin | 0 | 0 | f6738f72e2a6395815840a13dccf0f6516198d8e | 1,571 | aoc-2022-in-kotlin | Apache License 2.0 |
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day08/day08.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2023.day08
import eu.janvdb.aocutil.kotlin.lcm
import eu.janvdb.aocutil.kotlin.readGroupedLines
//const val FILENAME = "input08-test1.txt"
//const val FILENAME = "input08-test2.txt"
//const val FILENAME = "input08-test3.txt"
const val FILENAME = "input08.txt"
val LINE_REGEX = Regex("(\\S+) = \\((\\S+), (\\S+)\\)")
fun main() {
val lines = readGroupedLines(2023, FILENAME)
val instructions = lines[0][0].toCharArray().map { Instruction.valueOf(it.toString()) }
val nodeMap = NodeMap.parse(lines[1])
part1(instructions, nodeMap)
part2(instructions, nodeMap) // > 24253
}
private fun part1(instructions: List<Instruction>, nodeMap: NodeMap) {
println(findIterations(nodeMap, instructions, "AAA"))
}
private fun part2(instructions: List<Instruction>, nodeMap: NodeMap) {
// apparently the input is structured, so we can use the least common multiple for each start node
// see https://www.reddit.com/r/adventofcode/comments/18dfpub/2023_day_8_part_2_why_is_spoiler_correct/
val startNodes = nodeMap.nodes.keys.filter { it.endsWith('A') }
val steps = startNodes.map { findIterations(nodeMap, instructions, it) }
val result = steps.reduce { a, b -> lcm(a, b) }
println(result)
}
private fun findIterations(nodeMap: NodeMap, instructions: List<Instruction>, start: String): Long {
var iterations = 0L
var current = start
while (!current.endsWith('Z')) {
iterations++
current = nodeMap.apply(current, instructions)
}
val numberOfSteps = iterations * instructions.size
return numberOfSteps
}
data class Node(val from: String, val right: String, val left: String) {
companion object {
fun parse(line: String): Node {
val matchResult = LINE_REGEX.matchEntire(line) ?: throw IllegalArgumentException("Invalid line: $line")
val (from, right, left) = matchResult.destructured
return Node(from, left, right)
}
}
}
data class NodeMap(val nodes: Map<String, Node>) {
fun apply(nodeName: String, instructions: List<Instruction>): String {
return instructions.fold(nodeName) { current, instruction ->
val node = nodes[current] ?: throw IllegalArgumentException("Unknown node: $current")
when (instruction) {
Instruction.R -> node.right
Instruction.L -> node.left
}
}
}
companion object {
fun parse(lines: List<String>): NodeMap {
val instructions = lines
.map { Node.parse(it) }
.associateBy { it.from }
return NodeMap(instructions)
}
}
}
enum class Instruction { R, L } | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,466 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/siller/aoc2022/Day12.kt | chearius | 575,352,798 | false | {"Kotlin": 41999} | package dev.siller.aoc2022
private val example = """
Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi
""".trimIndent()
data class Coordinates(val x: Int, val y: Int)
data class Point(
val x: Int,
val y: Int,
val elevation: Int,
val startPoint: Boolean = false,
val endPoint: Boolean = false
)
private fun part1(input: List<String>): Int = getShortestPathLength(input) { points ->
setOf(points.first { p -> p.startPoint })
}
private fun part2(input: List<String>): Int = getShortestPathLength(input) { points ->
points.filter { p -> p.elevation == 1 }.toSet()
}
private fun getShortestPathLength(input: List<String>, startingPointsSelector: (Set<Point>) -> Set<Point>): Int {
val points = input.flatMapIndexed { rowIndex, line ->
line.toList().mapIndexed { columnIndex, e ->
val elevation = when (e) {
in 'a'..'z' -> e - 'a' + 1
'S' -> 1
'E' -> 'z' - 'a' + 1
else -> 0
}
Point(columnIndex, rowIndex, elevation, e == 'S', e == 'E')
}
}.toSet()
val endPoint = points.first { p -> p.endPoint }
val map = points.associateBy { p -> Coordinates(p.x, p.y) }
var steps = 0
var currentPoints = startingPointsSelector(points)
while (true) {
steps++
currentPoints = currentPoints.flatMap { currentPoint ->
setOfNotNull(
map[Coordinates(currentPoint.x + 1, currentPoint.y)],
map[Coordinates(currentPoint.x, currentPoint.y + 1)],
map[Coordinates(currentPoint.x - 1, currentPoint.y)],
map[Coordinates(currentPoint.x, currentPoint.y - 1)]
).filter { p -> p.elevation <= currentPoint.elevation + 1 }
}.toSet()
if (endPoint in currentPoints) {
break
}
}
return steps
}
fun aocDay12() = aocTaskWithExample(
day = 12,
part1 = ::part1,
part2 = ::part2,
exampleInput = example,
expectedOutputPart1 = 31,
expectedOutputPart2 = 29
)
fun main() {
aocDay12()
}
| 0 | Kotlin | 0 | 0 | e070c0254a658e36566cc9389831b60d9e811cc5 | 2,115 | advent-of-code-2022 | MIT License |
kotlin/src/com/s13g/aoc/aoc2021/Day15.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 15: Chiton ---
* https://adventofcode.com/2021/day/15
*/
class Day15 : Solver {
override fun solve(lines: List<String>): Result {
val width = lines[0].length
val height = lines.size
val data = IntArray(lines.size * lines[0].length)
for (y in lines.indices) {
for (x in lines[y].indices) {
data[width * y + x] = lines[y][x].toString().toInt()
}
}
val partA = Board(data, width, height).calc()
val partB = Board(expandForPartB(data, width, height), width * 5, height * 5).calc()
return Result("$partA", "$partB")
}
private fun expandForPartB(data: IntArray, width: Int, height: Int): IntArray {
val newData = IntArray(width * height * 5 * 5)
var idx = 0
for (y in 0 until height) {
for (i in 0..4) {
for (x in 0 until width) newData[idx++] = roundIt(data[y * width + x] + i)
}
}
val newWidth = width * 5
for (i in 1..4) {
for (y in 0 until height) {
for (x in 0 until newWidth) newData[idx++] = roundIt(newData[y * newWidth + x] + i)
}
}
return newData
}
private fun roundIt(num: Int) = if (num >= 10) num - 9 else num
private class Board(val data: IntArray, val width: Int, val height: Int) {
// Index (width/height) and cheapest cost.
val visited = mutableMapOf<Int, Int>()
var activeRoutes = mutableSetOf<Route>()
val goal = idxAt(width - 1, height - 1)
fun calc(): Int {
activeRoutes.add(Route(0, 0))
visited[0] = 0
while (activeRoutes.count { it.lastIdx != goal } > 0) {
for (route in activeRoutes.toList()) {
if (route.lastIdx == goal) continue
activeRoutes.remove(route)
if (costAt(route.lastIdx) < route.cost) continue
val end = route.lastIdx
val options = findNextOptions(end)
for (opt in options) {
val totalCost = data[opt] + route.cost
if (costAt(opt) > totalCost) {
activeRoutes.add(Route(opt, totalCost))
visited[opt] = totalCost
}
}
}
}
return activeRoutes.sortedBy { it.cost }.first().cost
}
fun costAt(pos: Int) = if (visited.containsKey(pos)) visited[pos]!! else Int.MAX_VALUE
fun idxAt(x: Int, y: Int) = y * width + x
fun findNextOptions(pos: Int): Set<Int> {
val x = pos % width
val y = pos / width
val result = mutableSetOf<Int>()
if (x > 0) result.add(idxAt(x - 1, y))
if (x < width - 1) result.add(idxAt(x + 1, y))
if (y > 0) result.add(idxAt(x, y - 1))
if (y < height - 1) result.add(idxAt(x, y + 1))
return result
}
}
private data class Route(val lastIdx: Int, val cost: Int);
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,827 | euler | Apache License 2.0 |
src/Day02.kt | bherbst | 572,621,759 | false | {"Kotlin": 8206} | import java.lang.IllegalArgumentException
import kotlin.math.round
fun main() {
fun parseChoice(char: Char): Choice {
return when (char) {
'A', 'X' -> Choice.Rock
'B', 'Y' -> Choice.Paper
'C', 'Z' -> Choice.Scissors
else -> throw IllegalArgumentException("Invalid char $char")
}
}
fun parseResult(char: Char): Result {
return when (char) {
'X' -> Result.Loss
'Y' -> Result.Tie
'Z' -> Result.Win
else -> throw IllegalArgumentException("Invalid char $char")
}
}
fun parseRound(line: String): Round {
return Round(
myChoice = parseChoice(line[2]),
theirChoice = parseChoice(line[0])
)
}
fun parseRound2(line: String): Round2 {
return Round2(
result = parseResult(line[2]),
theirChoice = parseChoice(line[0])
)
}
fun part1(input: List<String>): Int {
return input.map { parseRound(it) }
.sumOf { it.getScore() }
}
fun part2(input: List<String>): Int {
return input.map { parseRound2(it) }
.sumOf { it.getScore() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
private class Round(
private val theirChoice: Choice,
private val myChoice: Choice
) {
companion object {
private const val WIN = 6;
private const val LOSS = 0;
private const val TIE = 3;
}
fun getScore(): Int {
return getResultScore() + myChoice.value
}
private fun getResultScore(): Int {
return when (theirChoice) {
Choice.Rock -> {
when (myChoice) {
Choice.Rock -> TIE
Choice.Paper -> WIN
Choice.Scissors -> LOSS
}
}
Choice.Paper -> {
when (myChoice) {
Choice.Rock -> LOSS
Choice.Paper -> TIE
Choice.Scissors -> WIN
}
}
Choice.Scissors -> {
when (myChoice) {
Choice.Rock -> WIN
Choice.Paper -> LOSS
Choice.Scissors -> TIE
}
}
}
}
}
private class Round2(
private val theirChoice: Choice,
private val result: Result
) {
fun getScore(): Int {
return getMyChoice().value + result.value
}
private fun getMyChoice(): Choice {
return when (theirChoice) {
Choice.Rock -> {
when (result) {
Result.Win -> Choice.Paper
Result.Loss -> Choice.Scissors
Result.Tie -> Choice.Rock
}
}
Choice.Paper -> {
when (result) {
Result.Win -> Choice.Scissors
Result.Loss -> Choice.Rock
Result.Tie -> Choice.Paper
}
}
Choice.Scissors -> {
when (result) {
Result.Win -> Choice.Rock
Result.Loss -> Choice.Paper
Result.Tie -> Choice.Scissors
}
}
}
}
}
private enum class Choice(val value: Int) {
Rock(1),
Paper(2),
Scissors(3)
}
private enum class Result(val value: Int) {
Win(6),
Loss(0),
Tie(3)
}
| 0 | Kotlin | 0 | 0 | 64ce532d7a0c9904db8c8d09ff64ad3ab726ec7e | 3,726 | 2022-advent-of-code | Apache License 2.0 |
src/Day05.kt | sgc109 | 576,491,331 | false | {"Kotlin": 8641} | private const val COMMAND_TEMPLATE = "move (\\d+) from (\\d+) to (\\d+)"
fun main() {
data class Command(
val cnt: Int,
val from: Int,
val to: Int,
val retained: Boolean = false,
)
data class Game(
val stacks: List<ArrayDeque<Char>>,
val commands: List<Command>,
) {
fun execute(command: Command) {
require(stacks[command.from].size >= command.cnt)
val pops = (1..command.cnt).map {
stacks[command.from].removeLast()
}
if (command.retained) {
pops.reversed()
} else {
pops
}.forEach {
stacks[command.to].addLast(it)
}
}
}
fun initGame(input: String, retained: Boolean = false): Game {
val (part1, part2) = input.split("\n\n")
val upperLines = part1.split("\n")
val commandLines = part2.split("\n")
val size = upperLines.last().split(" ").filter { it.isNotBlank() }.maxOfOrNull { it.toInt() }!!
val stacks = List(size) { ArrayDeque<Char>() }
upperLines.dropLast(1).reversed().forEach { line ->
var idx = 0
line.windowed(size = 3, step = 4) { box ->
"\\[(\\w)]"
.toRegex()
.matchEntire(box)
?.groups
?.get(1)
?.value
?.let {
stacks[idx].addLast(it[0])
}
idx++
}
}
val commands = commandLines.map { line ->
val res = COMMAND_TEMPLATE.toRegex().matchEntire(line)!!
val (cnt, from, to) = res.groups.toList().drop(1).mapNotNull {
it?.value?.toInt()
}
Command(cnt, from - 1, to - 1, retained)
}
return Game(stacks, commands)
}
fun part1(input: String): String {
val game = initGame(input)
game.commands.forEach {
game.execute(it)
}
return game.stacks.map { it.last() }.joinToString("")
}
fun part2(input: String): String {
val game = initGame(input, retained = true)
game.commands.forEach {
game.execute(it)
}
return game.stacks.map { it.last() }.joinToString("")
}
val testInput = readText("Day05_test")
val ans = part2(testInput)
check(ans == "MCD")
val input = readText("Day05")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 03e4e85283d486430345c01d4c03419d95bd6daa | 2,577 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day03.kt | richardmartinsen | 572,910,850 | false | {"Kotlin": 14993} | fun main() {
fun findDuplicate(first: String, second: String): Char {
first.forEach {
if (second.contains(it)) {
return it
}
}
return 'X'
}
fun findTriplicate(first: String, second: String, third: String): Char {
first.forEach {
if (second.contains(it) && third.contains(it)) {
return it
}
}
return 'X'
}
fun part1(input: List<String>): Int {
val commonItems = mutableListOf<Char>()
var sum = 0
input.forEach { text ->
val first = text.substring(0, (text.length/2))
val second = text.substring((text.length/2))
commonItems.add(findDuplicate(first, second))
println("first : ${first}, second : $second, common : ${findDuplicate(first, second)}")
}
commonItems.forEach{
if (it.isLowerCase()) {
sum += it.code - 96
}
if (it.isUpperCase()) {
sum += it.code - 38
println("$it : ${it.code - 38}")
}
}
return sum
}
fun part2(input: List<String>): Int {
val list = input.chunked(3)
val commonItems = mutableListOf<Char>()
var sum = 0
list.forEach { threesome ->
val first = threesome.first()
val second = threesome[1]
val third = threesome[2]
println("first : ${first}, second : $second, third : $third, common : ${findTriplicate(first, second, third)}")
commonItems.add(findTriplicate(first, second, third))
}
commonItems.forEach{
if (it.isLowerCase()) {
sum += it.code - 96
}
if (it.isUpperCase()) {
sum += it.code - 38
}
}
return sum
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
check(part1(input) == 7848)
check(part2(input) == 2616)
}
| 0 | Kotlin | 0 | 0 | bd71e11a2fe668d67d7ee2af5e75982c78cbe193 | 2,056 | adventKotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/sorts/MergeSort.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <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.sorts
/**
* Invented in 1945 by <NAME>, merge sort is an efficient algorithm using the divide and conquer approach
* which is to divide a big problem into smaller problems and solve them. Conceptually, a merge sort works as follows:
* 1) Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
* 2) Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining.
*
* Worst-case performance O(n log n)
* Best-case performance O(n log n)
* Average performance O(n log n)
* Worst-case space complexity O(n)
*/
class MergeSort : AbstractSortStrategy {
override fun <T : Comparable<T>> perform(arr: Array<T>) {
val aux = arr.clone()
sort(arr, aux, 0, arr.size - 1)
}
private fun <T : Comparable<T>> sort(arr: Array<T>, aux: Array<T>, low: Int, high: Int) {
if (high <= low) return
val mid = (low + high) / 2
sort(arr, aux, low, mid)
sort(arr, aux, mid + 1, high)
merge(arr, aux, low, mid, high)
}
private fun <T : Comparable<T>> merge(arr: Array<T>, aux: Array<T>, low: Int, mid: Int, high: Int) {
System.arraycopy(arr, low, aux, low, high - low + 1)
var i = low
var j = mid + 1
for (k in low..high) {
when {
i > mid -> arr[k] = aux[j++]
j > high -> arr[k] = aux[i++]
aux[j] < aux[i] -> arr[k] = aux[j++]
else -> arr[k] = aux[i++]
}
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,212 | kotlab | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.