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/Day13.kt | asm0dey | 572,860,747 | false | {"Kotlin": 61384} | import Node13.Leaf
import Node13.NodeList
fun main() {
fun parse(tokens: ArrayDeque<String>): Node13 {
val mutable = arrayListOf<Node13>()
while (tokens.isNotEmpty()) {
when (val token = tokens.removeFirst()) {
"]" -> return NodeList(mutable)
"[" -> mutable.add(parse(tokens))
else -> mutable.add(Leaf(token.toInt()))
}
}
return mutable[0]
}
fun part1(input: List<String>): Int {
return input
.asSequence()
.filterNot(String::isBlank)
.map { Regex("\\[|]|\\d+").findAll(it).map(MatchResult::value).toList() }
.map(::ArrayDeque)
.chunked(2)
.map { it.take(2) }
.map { (fst, snd) -> parse(fst) to parse(snd) }
.mapIndexed { index, pair ->
val (a, b) = pair
if (a < b) index + 1 else 0
}
.sum()
}
fun part2(input: List<String>): Int {
return (input + listOf("[[2]]", "[[6]]"))
.asSequence()
.filterNot(String::isBlank)
.map { Regex("\\[|]|\\d+").findAll(it).map(MatchResult::value).toList() }
.map(::ArrayDeque)
.map(::parse)
.sorted()
.mapIndexed { index, packet ->
if (packet.toString() == "[[2]]" || packet.toString() == "[[6]]") index + 1
else 1
}
.reduce(Int::times)
}
val testInput = readInput("Day13_test")
val testPart1 = part1(testInput)
check(testPart1 == 13) { "Actual result: $testPart1" }
val input = readInput("Day13")
println(part1(input))
val testPart2 = part2(testInput)
check(testPart2 == 140) { "Actual result: $testPart2" }
println(part2(input))
}
sealed interface Node13 : Comparable<Node13> {
override operator fun compareTo(other: Node13): Int
@JvmInline
value class Leaf(val input: Int) : Node13 {
override fun compareTo(other: Node13): Int = when (other) {
is Leaf -> input.compareTo(other.input)
is NodeList -> NodeList(listOf(this)).compareTo(other)
}
override fun toString(): String = input.toString()
}
@JvmInline
value class NodeList(val input: List<Node13> = emptyList()) : Node13 {
override fun compareTo(other: Node13): Int {
return when (other) {
is Leaf -> this.compareTo(NodeList(listOf(other)))
is NodeList -> {
var pointer = 0
while (true) {
when {
input.size == other.input.size && input.size == pointer -> return 0
input.size > pointer && other.input.size > pointer -> {
val comparison = input[pointer].compareTo(other.input[pointer])
if (comparison != 0) return comparison
else {
pointer++
continue
}
}
input.size == pointer -> return -1
other.input.size == pointer -> break
}
}
1
}
}
}
override fun toString(): String = "[${input.joinToString(", ")}]"
}
}
| 1 | Kotlin | 0 | 1 | f49aea1755c8b2d479d730d9653603421c355b60 | 3,520 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day21.kt | tobiasae | 434,034,540 | false | {"Kotlin": 72901} | class Day21 : Solvable("21") {
override fun solveA(input: List<String>): String {
val (player1, player2) = getPlayers(input)
val dice = DeterministicDie()
var count = 0
while (true) {
player1.play(dice.roll() + dice.roll() + dice.roll())
if (player1.score >= 1000) {
return ((count * 6 + 3) * player2.score).toString()
}
player2.play(dice.roll() + dice.roll() + dice.roll())
if (player2.score >= 1000) {
return ((count * 6 + 6) * player1.score).toString()
}
count++
}
}
override fun solveB(input: List<String>): String {
val (player1, player2) = getPlayers(input)
val p = recursive(Universe(player1, player2, true), null)
return Math.max(p.first, p.second).toString()
}
private fun getPlayers(input: List<String>): Pair<Player, Player> {
return Player(input.first().split(":")[1].trim().toInt() - 1) to
Player(input.last().split(":")[1].trim().toInt() - 1)
}
val dice =
listOf(3, 4, 5, 4, 5, 6, 5, 6, 7, 4, 5, 6, 5, 6, 7, 6, 7, 8, 5, 6, 7, 6, 7, 8, 7, 8, 9)
private val memo = HashMap<Universe, Pair<Long, Long>>()
private fun recursive(universe: Universe, next: Int?): Pair<Long, Long> {
val u = if (next != null) universe.next(next) else universe
memo[u]?.let {
return it
}
if (u.p1.score >= 21) {
return 1L to 0L
} else if (u.p2.score >= 21) {
return 0L to 1L
}
return dice
.map { recursive(u, it) }
.reduce { (p0, p1), (p2, p3) -> p0 + p2 to p1 + p3 }
.also { memo[u] = it }
}
}
data class Universe(val p1: Player, val p2: Player, val p1sTurn: Boolean) {
fun next(diceRoll: Int): Universe {
return if (p1sTurn) Universe(p1.copy().apply { play(diceRoll) }, p2, false)
else Universe(p1, p2.copy().apply { play(diceRoll) }, true)
}
}
data class Player(var position: Int = 1, var score: Int = 0) {
fun play(diceRoll: Int) {
position += diceRoll
position %= 10
score += position + 1
}
}
class DeterministicDie() {
var last = 0
fun roll(): Int {
return (++last).also { if (it > 1000) last = 1 }
}
}
| 0 | Kotlin | 0 | 0 | 16233aa7c4820db072f35e7b08213d0bd3a5be69 | 2,385 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day02.kt | ty-garside | 573,030,387 | false | {"Kotlin": 75779} | // Rock Paper Scissors
// https://adventofcode.com/2022/day/2
// * Enhanced to support Lizard and Spock
object Rock : Shape({
it("breaks", Scissors)
it("crushes", Lizard)
})
object Paper : Shape({
it("covers", Rock)
it("disproves", Spock)
})
object Scissors : Shape({
it("cuts", Paper)
it("decapitates", Lizard)
})
object Lizard : Shape({
it("eats", Paper)
it("poisons", Spock)
})
object Spock : Shape({
it("vaporizes", Rock)
it("smashes", Scissors)
})
fun score(theirs: Shape, mine: Shape) =
when (mine) { // shape score
Rock -> 1
Paper -> 2
Scissors -> 3
Lizard -> 4
Spock -> 5
} + when { // outcome score
mine > theirs -> 6 // win
mine < theirs -> 0 // lose
else -> 3 // draw
}
fun List<String>.sumOfScores(
withStrategy: Shape.(Char) -> Shape
) = sumOf { line ->
val theirs = when (line[0]) {
'A' -> Rock
'B' -> Paper
'C' -> Scissors
'D' -> Lizard
'E' -> Spock
else -> error("Invalid: $line")
}
val ours = theirs.withStrategy(line[2])
score(theirs, ours)
.also {
if (DEBUG) when {
ours > theirs -> println("WIN: $ours ${ours.beats[theirs]} $theirs ($it points)")
ours < theirs -> println("LOSE: $theirs ${ours.loses[theirs]} $ours ($it points)")
else -> println("DRAW: $ours ($it points)")
}
}
}
const val DEBUG = false
fun main() {
fun part1(input: List<String>): Int {
return input.sumOfScores {
when (it) {
'X' -> Rock
'Y' -> Paper
'Z' -> Scissors
'W' -> Lizard
'V' -> Spock
else -> error("Invalid $it")
}
}
}
fun part2(input: List<String>): Int {
return input.sumOfScores {
when (it) {
'X' -> beats.keys.first() // always lose
'Y' -> this // always draw
'Z' -> loses.keys.first() // always win
'W' -> beats.keys.last() // maximize loss score
'V' -> loses.keys.last() // maximize win score
else -> error("Invalid $it")
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
typealias Rules = (verb: String, loser: Shape) -> Unit
sealed class Shape(defineRules: (Rules) -> Unit) : Comparable<Shape> {
val beats by lazy {
mutableMapOf<Shape, String>().apply {
defineRules { verb, loser ->
put(loser, verb)
}
}.toMap()
}
val loses by lazy {
Shapes.filter {
it.beats.contains(this)
}.associateWith {
it.beats[this]!!
}
}
override fun compareTo(other: Shape) = when {
beats.contains(other) -> 1
loses.contains(other) -> -1
else -> 0
}
override fun toString() = this::class.simpleName!!
}
val Shapes by lazy {
// used to avoid sealed class reflection
// lazy avoids circular reference weirdness
setOf(
Rock,
Paper,
Scissors,
Lizard,
Spock
)
}
/*
--- Day 2: Rock Paper Scissors ---
The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage, a giant Rock Paper Scissors tournament is already in progress.
Rock Paper Scissors is a game between two players. Each game contains many rounds; in each round, the players each simultaneously choose one of Rock, Paper, or Scissors using a hand shape. Then, a winner for that round is selected: Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, the round instead ends in a draw.
Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win. "The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column--" Suddenly, the Elf is called away to help with someone's tent.
The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. Winning every time would be suspicious, so the responses must have been carefully chosen.
The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores for each round. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won).
Since you can't be sure if the Elf is trying to help you or trick you, you should calculate the score you would get if you were to follow the strategy guide.
For example, suppose you were given the following strategy guide:
A Y
B X
C Z
This strategy guide predicts and recommends the following:
In the first round, your opponent will choose Rock (A), and you should choose Paper (Y). This ends in a win for you with a score of 8 (2 because you chose Paper + 6 because you won).
In the second round, your opponent will choose Paper (B), and you should choose Rock (X). This ends in a loss for you with a score of 1 (1 + 0).
The third round is a draw with both players choosing Scissors, giving you a score of 3 + 3 = 6.
In this example, if you were to follow the strategy guide, you would get a total score of 15 (8 + 1 + 6).
What would your total score be if everything goes exactly according to your strategy guide?
Your puzzle answer was 14163.
--- Part Two ---
The Elf finishes helping with the tent and sneaks back over to you. "Anyway, the second column says how the round needs to end: X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. Good luck!"
The total score is still calculated in the same way, but now you need to figure out what shape to choose so the round ends as indicated. The example above now goes like this:
In the first round, your opponent will choose Rock (A), and you need the round to end in a draw (Y), so you also choose Rock. This gives you a score of 1 + 3 = 4.
In the second round, your opponent will choose Paper (B), and you choose Rock so you lose (X) with a score of 1 + 0 = 1.
In the third round, you will defeat your opponent's Scissors with Rock for a score of 1 + 6 = 7.
Now that you're correctly decrypting the ultra top secret strategy guide, you would get a total score of 12.
Following the Elf's instructions for the second column, what would your total score be if everything goes exactly according to your strategy guide?
Your puzzle answer was 12091.
Both parts of this puzzle are complete! They provide two gold stars: **
*/
| 0 | Kotlin | 0 | 0 | 49ea6e3ad385b592867676766dafc48625568867 | 7,078 | aoc-2022-in-kotlin | Apache License 2.0 |
advent-of-code/src/main/kotlin/DayNine.kt | pauliancu97 | 518,083,754 | false | {"Kotlin": 36950} | import kotlin.math.max
import kotlin.math.min
private typealias Graph = Map<String, DayNine.Node>
private fun getPermutationsHelper(
currentPermutation: List<String>,
availableElements: List<String>,
permutations: MutableList<List<String>>
) {
if (availableElements.isEmpty()) {
permutations.add(currentPermutation)
} else {
for (element in availableElements) {
val updatedPermutation = currentPermutation + element
val updatedAvailableElements = availableElements - element
getPermutationsHelper(
updatedPermutation,
updatedAvailableElements,
permutations
)
}
}
}
fun getPermutations(elements: List<String>): List<List<String>> {
val permutations: MutableList<List<String>> = mutableListOf()
getPermutationsHelper(emptyList(), elements, permutations)
return permutations
}
class DayNine {
data class InputEdge(
val sourceNodeName: String,
val destinationNodeName: String,
val cost: Int
) {
companion object {
val REGEX = """([a-zA-Z]+) to ([a-zA-Z]+) = (\d+)""".toRegex()
}
}
data class Edge(
val nodeName: String,
val cost: Int
)
data class Node(
val name: String,
val edges: List<Edge>
) {
fun getCost(destinationName: String): Int? =
edges.firstOrNull { it.nodeName == destinationName }?.cost
}
private fun String.toInputEdge(): InputEdge? {
val matchResult = InputEdge.REGEX.matchEntire(this) ?: return null
val sourceNodeName = matchResult.groupValues.getOrNull(1) ?: return null
val destinationNodeName = matchResult.groupValues.getOrNull(2) ?: return null
val cost = matchResult.groupValues.getOrNull(3)?.toIntOrNull() ?: return null
return InputEdge(sourceNodeName, destinationNodeName, cost)
}
private fun getGraph(inputEdges: List<InputEdge>): Graph {
val nodesNames = inputEdges.flatMap { listOf(it.sourceNodeName, it.destinationNodeName) }.distinct()
val nodes = nodesNames
.map { nodeName ->
val edges = inputEdges
.mapNotNull { inputEdge ->
when {
inputEdge.sourceNodeName == nodeName -> Edge(inputEdge.destinationNodeName, inputEdge.cost)
inputEdge.destinationNodeName == nodeName -> Edge(inputEdge.sourceNodeName, inputEdge.cost)
else -> null
}
}
Node(name = nodeName, edges = edges)
}
return nodes.associateBy { it.name }
}
private fun readInputEdges(path: String) =
readLines(path).mapNotNull { it.toInputEdge() }
private fun getPathCost(path: List<String>, graph: Graph): Int? {
val pairedNodes = path.dropLast(1).zip(path.drop(1))
var cost = 0
for ((source, destination) in pairedNodes) {
val edgeCost = graph[source]?.getCost(destination) ?: return null
cost += edgeCost
}
return cost
}
private fun Graph.getNodesNames() = this.keys.toList()
private fun getTravellingSalesmanSolution(graph: Graph): Int? {
val nodes = graph.getNodesNames()
var minCost: Int? = null
for (path in getPermutations(nodes)) {
val pathCost = getPathCost(path, graph)
if (pathCost != null) {
val currentMinCost = minCost
minCost = if (currentMinCost != null) {
min(currentMinCost, pathCost)
} else {
pathCost
}
}
}
return minCost
}
private fun getReversedTravellingSalesmanSolution(graph: Graph): Int? {
val nodes = graph.getNodesNames()
var maxCost: Int? = null
for (path in getPermutations(nodes)) {
val pathCost = getPathCost(path, graph)
if (pathCost != null) {
val currentMaxCost = maxCost
maxCost = if (currentMaxCost != null) {
max(currentMaxCost, pathCost)
} else {
pathCost
}
}
}
return maxCost
}
fun solvePartOne() {
val inputEdges = readInputEdges("day_nine.txt")
val graph = getGraph(inputEdges)
val solution = getTravellingSalesmanSolution(graph)
println(solution)
}
fun solvePartTwo() {
val inputEdges = readInputEdges("day_nine.txt")
val graph = getGraph(inputEdges)
val solution = getReversedTravellingSalesmanSolution(graph)
println(solution)
}
}
fun main() {
DayNine().solvePartTwo()
} | 0 | Kotlin | 0 | 0 | 3ba05bc0d3e27d9cbfd99ca37ca0db0775bb72d6 | 4,865 | advent-of-code-2015 | MIT License |
dsalgo/src/commonMain/kotlin/com/nalin/datastructurealgorithm/problems/AE_List.kt | nalinchhajer2 | 481,901,695 | false | {"Kotlin": 25247, "Ruby": 1605} | package com.nalin.datastructurealgorithm.problems
import com.nalin.datastructurealgorithm.ds.LinkedListNode
import kotlin.math.max
import kotlin.math.min
/**
* Merge overlapping intervals. They are not likely to be in order
*/
fun mergeOverlappingIntervals(intervals: List<List<Int>>): List<List<Int>> {
val sortedInterval = intervals.sortedBy {
it[0]
}
val result = mutableListOf<MutableList<Int>>()
for (item in sortedInterval) {
if (result.size != 0 && checkIntervalOveralps(result.last(), item)) {
result.last()[0] = min(item[0], result.last()[0])
result.last()[1] = max(item[1], result.last()[1])
} else {
result.add(mutableListOf(item[0], item[1]))
}
}
return result
}
fun checkIntervalOveralps(item1: List<Int>, item2: List<Int>): Boolean {
// item1 left is not in item2 right
// item1 right is not in item2 left
return !((item1[0] < item2[0] && item1[1] < item2[0])
|| (item1[0] > item2[0] && item1[0] > item2[1]))
}
fun firstDuplicateValue(array: MutableList<Int>): Int {
val map = hashMapOf<Int, Int>()
for (item in array) {
map.put(item, (map.get(item) ?: 0) + 1)
if (map.get(item)!! > 1) {
return item
}
}
return -1
}
/**
* Check if a given linked list is palindrome or not
*/
fun linkedListPalindrome(linkedList: LinkedListNode<Int>?): Boolean {
fun _traverse(
head: LinkedListNode<Int>,
tail: LinkedListNode<Int>
): Pair<LinkedListNode<Int>?, Boolean> {
var result = true
var newHead: LinkedListNode<Int>? = head
if (tail.nextNode !== null) {
val (resHead, newResult) = _traverse(head, tail.nextNode!!)
newHead = resHead
result = newResult
}
return Pair(newHead?.nextNode, result && newHead?.value == tail.value)
}
return _traverse(linkedList!!, linkedList!!).second
}
/**
* Find min area rectangle in 2D-plane
*/
fun minimumAreaRectangle(points: List<List<Int>>): Int {
// Write your code here.
return 0
}
fun findRectangleFromPoints(points: List<List<Int>>) {
val mutablePoints = points.toMutableList()
// Need in x, y plane only
// square can also be consider as rect
// 4 points in x, y plane will form triangle if
// 2 points in x, 2 points in y are same
// x1,y1 x1,y2 x2,y1 x2,y2 -> x1,x2,y1,y2
// 1,5 2,5 1,3 2,3 -> 1,2,5,3
// nlogn + n ^ 2 + n
val mapX = mergePointsFromGivenDimension(mutablePoints, 0, 1) // 1,5 1,3
val mapY = mergePointsFromGivenDimension(mutablePoints, 1, 0)
for ((xIndex, yPoints) in mapX) {
// 5, 3, 8, 9
}
// 5 -> 1 or 3 -> 1 and 3 in x contains 3
// check if a point can be part of a rect
}
fun mergePointsFromGivenDimension(
points: MutableList<List<Int>>,
dimensionFrom: Int,
dimensionTo: Int
): MutableMap<Int, MutableSet<Int>> {
val dict: MutableMap<Int, MutableSet<Int>> = mutableMapOf()
for (point in points) {
var list: MutableSet<Int>? = dict[point[dimensionFrom]]
if (list == null) {
list = mutableSetOf()
}
list.add(point[dimensionTo])
dict[point[dimensionFrom]] = list
}
val dictIterator = dict.entries.iterator()
while (dictIterator.hasNext()) {
val (_, value) = dictIterator.next()
if (value.size < 2) {
dictIterator.remove()
}
}
return dict
}
| 0 | Kotlin | 0 | 0 | 84a071cd15f8eab1ec8425060570691315c103f9 | 3,505 | kotlin-ds-algo | MIT License |
Advent-of-Code-2023/src/Day09.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day09"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
/**
* Gets the next backwards or forwards value in the sequence. First is calculated the difference between each number in
* the sequence, then the next value is calculated recursively.
*/
private fun getNextValue(diffs: List<Int>, backwards: Boolean = false): Int {
if (diffs.all { it == 0 }) return 0
val nextDiffs = diffs.zipWithNext().map { it.second - it.first }
val diff = getNextValue(nextDiffs, backwards)
return if (backwards) (diffs.first() - diff) else (diffs.last() + diff)
}
/**
* Calculates the next value in the sequence by calculating the difference between each number, until all numbers are 0.
* Afterward, the next value of each line of the differences is calculated by summing the last value of the previous
* line with the resulting difference of the current line.
*/
private fun part1(input: List<String>): Int {
val oasis = input.map { it.split(" ").map { num -> num.toInt() } }
return oasis.sumOf { history -> getNextValue(history) }
}
/**
* Instead calculates the previous value in the sequence.
*/
private fun part2(input: List<String>): Int {
val oasis = input.map { it.split(" ").map { num -> num.toInt() } }
return oasis.sumOf { history -> getNextValue(history, backwards = true) }
}
fun main() {
createTestFiles(AOC_DAY)
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 114
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 2
println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 2101499000" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 1089" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 1,983 | Advent-of-Code-2023 | Apache License 2.0 |
src/Day04.kt | jgodort | 573,181,128 | false | null | fun main() {
val inputData = readInput("Day4_input")
println(day4Part1(inputData))
println(day4Part2(inputData))
}
private fun convertToRange(value: String): IntRange {
val elements = value.split("-")
.map { it.toInt() }
.sorted()
return IntRange(elements.component1(), elements.component2())
}
private fun IntRange.isFullyContained(other: IntRange): Boolean =
this.contains(other.first) && this.contains(other.last)
private fun getRanges(it: String): List<IntRange> = it
.split(",")
.map { elfAssigment -> convertToRange(elfAssigment) }
fun day4Part1(input: String): Int = input.lines()
.sumOf { line ->
val ranges = getRanges(line)
val firstRange = ranges.component1()
val secondRange = ranges.component2()
val result = if (firstRange.isFullyContained(secondRange) || secondRange.isFullyContained(firstRange)) 1 else 0
result
}
fun day4Part2(input: String): Int = input.lines()
.sumOf { line ->
val ranges = getRanges(line)
val firstRange = ranges.component1()
val secondRange = ranges.component2()
val result = if (firstRange.intersect(secondRange).isNotEmpty()) 1 else 0
result
}
| 0 | Kotlin | 0 | 0 | 355f476765948c79bfc61367c1afe446fe9f6083 | 1,235 | aoc2022Kotlin | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day23/day23.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day23
import biz.koziolek.adventofcode.*
fun main() {
val inputFile = findInput(object {})
val lines = inputFile.bufferedReader().readLines()
val hikingTrails = parseHikingTrails(lines)
println("Longest path has ${findLongestPathLen(hikingTrails)} steps")
val graph = parseHikingTrailsAsGraph(lines)
println("Longest path ignoring slopes has ${findLongestPathLen(graph)} steps")
}
const val PATH = '.'
const val FOREST = '#'
const val SLOPE_N = '^'
const val SLOPE_E = '>'
const val SLOPE_S = 'v'
const val SLOPE_W = '<'
private val slopeToDirection = mapOf(
SLOPE_N to Direction.NORTH,
SLOPE_E to Direction.EAST,
SLOPE_S to Direction.SOUTH,
SLOPE_W to Direction.WEST,
)
fun parseHikingTrails(lines: Iterable<String>): Map<Coord, Char> =
lines.parse2DMap().filter { (_, char) -> char != FOREST }.toMap()
fun parseHikingTrailsAsGraph(lines: Iterable<String>): Graph<CoordNode, BiDirectionalGraphEdge<CoordNode>> =
lines.parse2DMap()
.filter { (_, char) -> char != FOREST }
.toMap()
.mapValues { 1 }
.toBiDirectionalGraph(includeDiagonal = false)
fun findLongestPathLen(hikingTrails: Map<Coord, Char>): Int {
val start = hikingTrails.entries.single { it.key.y == 0 && it.value == PATH }.key
val distance = hikingTrails.keys.associateWith { Int.MIN_VALUE }.toMutableMap()
distance[start] = 0
val sorted = topologicalSort(hikingTrails, start)
val visited = mutableSetOf<Coord>()
while (sorted.isNotEmpty()) {
val coord = sorted.removeFirst()
visited.add(coord)
val newDist = distance[coord]!! + 1
for (adjCoord in getAdjacentTiles(hikingTrails, coord).filter { it !in visited }) {
if (distance[adjCoord]!! < newDist) {
distance[adjCoord] = newDist
}
}
}
val end = hikingTrails.entries.single { it.key.y == hikingTrails.getHeight() - 1 }.key
return distance[end]!!
}
fun findLongestPathLen(hikingTrails: Graph<CoordNode, BiDirectionalGraphEdge<CoordNode>>): Int {
val simplified = hikingTrails.simplify()
val path = simplified.findLongestPath(
start = simplified.nodes.minBy { it.coord.y },
end = simplified.nodes.maxBy { it.coord.y },
)
return path.sumOf { it.weight }
}
fun topologicalSort(
hikingTrails: Map<Coord, Char>,
coord: Coord,
visited: MutableSet<Coord> = mutableSetOf(),
sorted: MutableList<Coord> = mutableListOf(coord)
): List<Coord> {
if (coord in visited) {
return emptyList()
}
visited.add(coord)
for (adjCoord in getAdjacentTiles(hikingTrails, coord)) {
if (adjCoord !in visited) {
topologicalSort(hikingTrails, adjCoord, visited, sorted)
}
}
sorted.addFirst(coord)
return sorted
}
private fun getAdjacentTiles(hikingTrails: Map<Coord, Char>, coord: Coord): List<Coord> =
Direction.entries
.mapNotNull { direction ->
val newCoord = coord.move(direction)
val char = hikingTrails[newCoord]
if (char == PATH || slopeToDirection[char] == direction) {
newCoord
} else {
null
}
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 3,272 | advent-of-code | MIT License |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day21/Day21.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day21
import nl.sanderp.aoc.common.increaseBy
import nl.sanderp.aoc.common.measureDuration
import nl.sanderp.aoc.common.prettyPrint
import kotlin.math.min
fun main() {
val initialGame = Game(8, 0, 7, 0)
val (answer1, duration1) = measureDuration<Int> { partOne(initialGame) }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
val (answer2, duration2) = measureDuration<Long> { partTwo(initialGame) }
println("Part two: $answer2 (took ${duration2.prettyPrint()})")
}
enum class Player {
Player1, Player2;
fun next() = when (this) {
Player1 -> Player2
Player2 -> Player1
}
}
private data class Game(val position1: Int, val score1: Int, val position2: Int, val score2: Int) {
fun next(player: Player, moves: Int) = when (player) {
Player.Player1 -> {
val nextPosition = (position1 + moves - 1) % 10 + 1
this.copy(position1 = nextPosition, score1 = score1 + nextPosition)
}
Player.Player2 -> {
val nextPosition = (position2 + moves - 1) % 10 + 1
this.copy(position2 = nextPosition, score2 = score2 + nextPosition)
}
}
fun winner(score: Int) = when {
score1 >= score -> Player.Player1
score2 >= score -> Player.Player2
else -> null
}
}
private fun partOne(initial: Game): Int {
data class State(val game: Game, val rolls: List<Int>)
val dice = generateSequence(1) { it % 100 + 1 }
val turns = generateSequence(Player.Player1) { it.next() }
val initialState = State(initial, emptyList())
val states = dice.chunked(3).zip(turns).runningFold(initialState) { state, (rolls, turn) ->
State(state.game.next(turn, rolls.sum()), state.rolls + rolls)
}
val (game, rolls) = states.first { it.game.winner(1000) != null }
return min(game.score1, game.score2) * rolls.size
}
private fun partTwo(initial: Game): Long {
val moves = buildList {
for (a in 1..3) {
for (b in 1..3) {
for (c in 1..3) {
add(a + b + c)
}
}
}
}.groupingBy { it }.eachCount()
val winningScore = 21
val wins = mutableMapOf(Player.Player1 to 0L, Player.Player2 to 0L)
var openGames = mapOf(initial to 1L)
var turn = Player.Player1
while (openGames.isNotEmpty()) {
val games = buildMap<Game, Long> {
for ((game, gameCount) in openGames) {
for ((move, moveCount) in moves) {
val newGame = game.next(turn, move)
val newGameCount = gameCount * moveCount
increaseBy(newGame, newGameCount)
}
}
}
games.entries.mapNotNull { it.key.winner(winningScore)?.to(it.value) }.forEach { (winner, count) ->
wins.increaseBy(winner, count)
}
openGames = games.filterKeys { it.winner(winningScore) == null }.toMap()
turn = turn.next()
}
return wins.values.maxOf { it }
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 3,081 | advent-of-code | MIT License |
src/Day02.kt | D000L | 575,350,411 | false | {"Kotlin": 23716} | enum class RPS(val point: Int) {
Rock(1), Paper(2), Scissors(3);
companion object {
fun from(word: String): RPS {
return when (word) {
"A", "X" -> Rock
"B", "Y" -> Paper
else -> Scissors
}
}
}
}
enum class Result(val point: Int) {
Lost(0), Draw(3), Win(6);
companion object {
fun from(word: String): Result {
return when (word) {
"X" -> Lost
"Y" -> Draw
else -> Win
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val (player1, player2) = it.split(" ").map { RPS.from(it) }
val result = if (player1 == player2) Result.Draw
else if (
player1 == RPS.Rock && player2 == RPS.Scissors ||
player1 == RPS.Scissors && player2 == RPS.Paper ||
player1 == RPS.Paper && player2 == RPS.Rock
) Result.Lost
else Result.Win
result.point + player2.point
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val (player1Word, resultWord) = it.split(" ")
val player1 = RPS.from(player1Word)
val result = Result.from(resultWord)
val player2 = when (result) {
Result.Draw -> player1
Result.Win -> {
when (player1) {
RPS.Paper -> RPS.Scissors
RPS.Scissors -> RPS.Rock
else -> RPS.Paper
}
}
else -> {
when (player1) {
RPS.Paper -> RPS.Rock
RPS.Scissors -> RPS.Paper
else -> RPS.Scissors
}
}
}
result.point + player2.point
}
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b733a4f16ebc7b71af5b08b947ae46afb62df05e | 2,089 | adventOfCode | Apache License 2.0 |
src/main/kotlin/aoc2023/day17/day17Solver.kt | Advent-of-Code-Netcompany-Unions | 726,531,711 | false | {"Kotlin": 94973} | package aoc2023.day17
import lib.*
import lib.graph.Graph
suspend fun main() {
setupChallenge().solveChallenge()
}
fun setupChallenge(): Challenge<Array<Array<Int>>> {
return setup {
day(17)
year(2023)
//input("example.txt")
parser {
it.readLines().get2DArrayOfColumns().map { it.map { it.digitToInt() }.toTypedArray() }.toTypedArray()
}
partOne {
val costs = it
val nodes =
it.indices.flatMap { i -> it[i].indices.flatMap { j -> CardinalDirection.entries.map { (i to j) to it } } }
val connections =
nodes.associateWith { costs.getConnectionsFrom(it).map { (it.destination to it.direction) to it.cost } }
.toMutableMap()
val start = (-1 to -1) to CardinalDirection.East
val startConnections = costs.getMoves(
(0 to 0) to CardinalDirection.East,
setOf(CardinalDirection.East, CardinalDirection.South),
1..3
)
connections[start] = startConnections.map { (it.destination to it.direction) to it.cost }
val dest = (costs.size - 1) to (costs.first().size - 1)
val graph = Graph({nodes.toSet() + start}, {node -> (if(node.first.first == -1) startConnections else costs.getConnectionsFrom(node)).map { (it.destination to it.direction) to it.cost }.toSet()})
val bound = costs.getUpperBound(1..3)
graph.limit = bound
graph.shortestDistanceFromTo(start) { it.first == dest }.toString()
}
partTwo {
val costs = it
val nodes =
it.indices.flatMap { i -> it[i].indices.flatMap { j -> CardinalDirection.entries.map { (i to j) to it } } }
val connections = nodes.associateWith {
costs.getConnectionsFrom(it, 4..10).map { (it.destination to it.direction) to it.cost }
}.mapKeys { "${it.key.first}-${it.key.second}" }.mapValues { it.value.map { "${it.first.first}-${it.first.second}" to it.second } }.toMutableMap()
val startConnections = costs.getMoves(
(0 to 0) to CardinalDirection.East,
setOf(CardinalDirection.East, CardinalDirection.South),
4..10
)
connections["start"] = startConnections.map { "${it.destination}-${it.direction}" to it.cost }
val graph = Graph(connections)
graph.shortestDistanceFromTo("start") {
it.startsWith("${costs.size - 1 to costs.first().size - 1}")
}.toString()
}
}
}
data class Move(val destination: Pair<Int, Int>, val direction: CardinalDirection, val cost: Long)
fun Array<Array<Int>>.getConnectionsFrom(
source: Pair<Pair<Int, Int>, CardinalDirection>,
allowedDistance: IntRange = 1..3
): List<Move> {
val directions = setOf(source.second.turn(RelativeDirection.Left), source.second.turn(RelativeDirection.Right))
return this.getMoves(source, directions, allowedDistance)
}
fun Array<Array<Int>>.getMoves(
source: Pair<Pair<Int, Int>, CardinalDirection>,
directions: Set<CardinalDirection>,
allowedDistance: IntRange
): List<Move> {
val moves = mutableListOf<Move>()
directions.forEach {
var i = 1
var current = source.first.adjacent(it)
var cost = 0L
while (i <= allowedDistance.last && isValidCoord(current)) {
cost += this[current.first][current.second]
if (i in allowedDistance) {
moves.add(Move(current, it, cost))
}
current = current.adjacent(it)
i++
}
}
return moves
}
fun Array<Array<Int>>.getUpperBound(validMoves: IntRange): Long {
val dest = this.size - 1 to this.first().size - 1
var current = 0 to 0
var res = 0L
while(current != dest) {
val toMoveX = minOf(dest.first - current.first, validMoves.last)
val toMoveY = minOf(dest.second - current.second, validMoves.last)
repeat(toMoveX) {
current = current.adjacent(CardinalDirection.East)
res += this[current.first][current.second]
}
repeat(toMoveY) {
current = current.adjacent(CardinalDirection.South)
res += this[current.first][current.second]
}
if(toMoveX + toMoveY == 0 || !isValidCoord(current)) {
throw Exception("Error navigating to dest")
}
}
return res
} | 0 | Kotlin | 0 | 0 | a77584ee012d5b1b0d28501ae42d7b10d28bf070 | 4,524 | AoC-2023-DDJ | MIT License |
src/day11/Day11.kt | spyroid | 433,555,350 | false | null | package day11
import readInput
import kotlin.system.measureTimeMillis
fun main() {
data class Point(val x: Int, val y: Int, var v: Int) {
fun inc(): Int {
if (v == 9) v = 0 else v++
return v
}
}
class Area(input: List<String>) {
val points = readPoints(input)
val areaWidth = input.first().length
val areaHeight = input.size
var totalFlashes = 0
fun readPoints(seq: List<String>) = mutableListOf<Point>().apply {
seq.forEachIndexed { y, line -> line.forEachIndexed { x, v -> this += Point(x, y, v.digitToInt()) } }
}
fun at(x: Int, y: Int): Point? {
if (x < 0 || x >= areaWidth || y < 0) return null
return points.getOrNull(x + areaWidth * y)
}
fun neighbors(x: Int, y: Int) = listOfNotNull(
at(x - 1, y - 1), at(x, y - 1), at(x + 1, y - 1),
at(x - 1, y), at(x + 1, y),
at(x - 1, y + 1), at(x, y + 1), at(x + 1, y + 1),
)
override fun toString(): String {
return buildString {
for (y in 0 until areaHeight) {
for (x in 0 until areaHeight) append(at(x, y)?.v).append(" ")
append("\n")
}
}
}
fun oneStep() {
var zeroes = mutableSetOf<Point>()
val excludes = mutableSetOf<Point>()
points.filter { it.inc() == 0 }.forEach {
excludes.add(it)
zeroes.add(it)
totalFlashes++
}
while (zeroes.isNotEmpty()) {
zeroes = mutableSetOf<Point>().apply {
zeroes.forEach { z ->
neighbors(z.x, z.y)
.filterNot { it.v == 0 && it in excludes }
.filter { it.inc() == 0 }
.forEach {
excludes.add(it)
add(it)
totalFlashes++
}
}
}
}
}
fun allFlashing() = points.sumOf { it.v } == 0
}
fun part1(input: List<String>): Int {
val area = Area(input)
return repeat(100) { area.oneStep() }
.let { area.totalFlashes }
}
fun part2(input: List<String>): Int {
val area = Area(input)
return generateSequence(1) { it + 1 }
.onEach { area.oneStep() }
.first { area.allFlashing() }
}
val testData = readInput("day11/test")
val inputData = readInput("day11/input")
var res1 = part1(testData)
check(res1 == 1656) { "Expected 1656 but got $res1" }
var time = measureTimeMillis { res1 = part1(inputData) }
println("Part1: $res1 in $time ms") // 1637
time = measureTimeMillis { res1 = part2(inputData) }
println("Part2: $res1 in $time ms") // 242
}
| 0 | Kotlin | 0 | 0 | 939c77c47e6337138a277b5e6e883a7a3a92f5c7 | 3,010 | Advent-of-Code-2021 | Apache License 2.0 |
src/Day02.kt | Totwart123 | 573,119,178 | false | null | fun main() {
val duells = mutableListOf(
0 to listOf(Pair('A', 'Z'), Pair('B', 'X'), Pair('C', 'Y')),
3 to listOf(Pair('A', 'X'), Pair('B', 'Y'), Pair('C', 'Z')),
6 to listOf(Pair('A', 'Y'), Pair('B', 'Z'), Pair('C', 'X')),
)
fun part1(input: List<String>): Int {
return input.sumOf {
val move = it.trim()
val enemyMove = move.first()
val myMove = move.last()
val movePoints = when (myMove) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> -1
}
check(movePoints != -1)
val duellPoints = duells.first { duell -> duell.second.contains(Pair(enemyMove, myMove)) }.first
movePoints + duellPoints
}
}
val predictedDuells = mutableListOf(
1 to listOf(Pair('A', 'Y'), Pair('B', 'X'), Pair('C', 'Z')),
2 to listOf(Pair('B', 'Y'), Pair('C', 'X'), Pair('A', 'Z')),
3 to listOf(Pair('C', 'Y'), Pair('A', 'X'), Pair('B', 'Z')),
)
fun part2(input: List<String>): Int {
return input.sumOf {
val move = it.trim()
val enemyMove = move.first()
val result = move.last()
val movePoints = predictedDuells.first { duell -> duell.second.contains(Pair(enemyMove, result)) }.first
val duellPoints = when (result) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> -1
}
check(movePoints != -1)
movePoints + duellPoints
}
}
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 | 33e912156d3dd4244c0a3dc9c328c26f1455b6fb | 1,816 | AoC | Apache License 2.0 |
src/day11/day11.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day11
import readInput
import java.util.*
private fun parse(input: List<String>): List<Monkey> {
fun parseItems(line: String): MutableList<Long> {
val result = mutableListOf<Long>()
val parts = line.split(":")
val items = parts[1].split(",")
for (part in items) {
result.add(part.substring(1).toLong())
}
return result
}
fun operation(line: String): (item: Long) -> Long {
val parts = line.split(": ")
val items = parts[1].split("= ")[1].split(" ")
return { value ->
val secondItem = when (items[2]) {
"old" -> value
else -> items[2].toLong()
}
when (items[1]) {
"*" -> value * secondItem
"+" -> value + secondItem
else -> throw NullPointerException()
}
}
}
fun divideBy(line: String): Int {
val parts = line.split("by ")
return parts[1].toInt()
}
fun action(line: String): Int {
val parts = line.split("to monkey ")
return parts[1].toInt()
}
val result = mutableListOf<Monkey>()
var index = 0
while (index < input.size) {
if (input[index] == "") index++
val id = result.size
val items = parseItems(input[++index])
val operation = operation(input[++index])
val division = divideBy(input[++index])
val ifTrue = action(input[++index])
val ifFalse = action(input[++index])
result.add(
Monkey(
id = id,
items = items,
operation = operation,
divideBy = division,
policy = Pair(ifTrue, ifFalse)
)
)
index++
}
return result
}
private fun solution(input: List<String>, iterationCount: Int, isSecondPart: Boolean): Long {
val monkeys = parse(input)
val common = monkeys.map { it.divideBy }.reduce { a, b -> a * b }
for (round in 0 until iterationCount) {
for (monkey in monkeys) {
for (item in monkey.items) {
monkey.counter++
val temp = monkey.operation(item)
val newWorryLevel = if (isSecondPart) temp % common else temp / 3
if (newWorryLevel % monkey.divideBy == 0L) {
monkeys[monkey.policy.first].items.add(newWorryLevel)
} else {
monkeys[monkey.policy.second].items.add(newWorryLevel)
}
}
monkey.items = mutableListOf()
}
}
val queue = PriorityQueue<Monkey>(monkeys.size, compareByDescending { it.counter })
for (item in monkeys) {
queue.add(item)
}
val first = queue.poll().counter
val second = queue.poll().counter
return first.toLong() * second.toLong()
}
private fun part1(input: List<String>): Long {
return solution(input, 20, false)
}
private fun part2(input: List<String>): Long {
return solution(input, 10_000, true)
}
data class Monkey(
var counter: Int = 0,
val id: Int,
var items: MutableList<Long>,
val operation: (item: Long) -> Long,
val divideBy: Int,
val policy: Pair<Int, Int>
)
fun main() {
val input = readInput("day11/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 3,385 | aoc-2022 | Apache License 2.0 |
src/y2023/Day07.kt | a3nv | 574,208,224 | false | {"Kotlin": 34115, "Java": 1914} | package y2023
import utils.readInput
val WEIGHTS = "23456789TJQKA".mapIndexed { index, it -> it to index + 2 }.toMap()
class Hand(private val hand: String, val bid: Long) {
fun handStrength(): Int {
val cardWeights = hand.map { WEIGHTS[it] }
val combos = cardWeights.groupingBy { it }.eachCount()
val sortedCombos = combos.entries.sortedWith(
compareByDescending<Map.Entry<Int?, Int>> { it.value }.thenByDescending { it.key }
)
val maxCombo = sortedCombos.maxByOrNull { it.value }!!
val maxComboValue = maxCombo.key!!
val secondComboValue = sortedCombos.drop(1).maxByOrNull { it.value }?.key ?: 0
val baseScore = when (maxCombo.value) {
4 -> 70000
3 -> if (sortedCombos.size == 2) 60000 else 50000
2 -> if (sortedCombos.size == 3) 40000 else 30000
else -> 10000
}
return baseScore + maxComboValue * 100 + secondComboValue
}
}
fun main() {
val comparator: Comparator<Hand> = compareBy { it.handStrength() }
fun part1(input: List<String>): Long {
val hands = input.map {
val split = it.split(" ")
Hand(split[0], split[1].toLong())
}
val sortedWith = hands.sortedWith(comparator)
return sortedWith.mapIndexed { index, hand ->
(index + 1) * hand.bid
}.sum()
}
fun part2(input: List<String>): Long {
return 0
}
// test if implementation meets criteria from the description, like:
var testInput = readInput("y2023", "Day07_test_part1")
println(part1(testInput))
check(part1(testInput) == 6440L)
// println(part2(testInput))
// check(part2(testInput) == 251927063)
val input = readInput("y2023", "Day07")
println(part1(input))
check(part1(input) == 251927063L)
// println(part2(input))
// check(part2(input) == 255632664)
} | 0 | Kotlin | 0 | 0 | ab2206ab5030ace967e08c7051becb4ae44aea39 | 1,922 | advent-of-code-kotlin | Apache License 2.0 |
Advent-of-Code-2023/src/Day07.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day07"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
private data class Hand(val cards: String, val bid: Int, val typeStrength: Int)
private fun relativeStrengthMap(withJokers: Boolean = false) = mapOf(
'A' to 13,
'K' to 12,
'Q' to 11,
if (withJokers) 'J' to 0 else 'J' to 10,
'T' to 9,
'9' to 8,
'8' to 7,
'7' to 6,
'6' to 5,
'5' to 4,
'4' to 3,
'3' to 2,
'2' to 1
)
/**
* Counts the existent jokers and evaluates the type of the hand.
* @return the type strength of the hand.
*/
private fun getTypeStrength(hand: String, withJokers: Boolean): Int {
// Occurrences of each card in the hand
val handMap = mutableMapOf<Char, Int>()
var jokers = 0
hand.forEach { c ->
if (c == 'J') jokers++
if (handMap.containsKey(c)) handMap[c] = handMap[c]!! + 1
else handMap[c] = 1
}
jokers = if (withJokers) jokers else 0
val typeStrength = when (handMap.size) {
5 -> if (jokers == 1) 2 else 1 // one-pair: 2 | high-card: 1
4 -> if (jokers == 1 || jokers == 2) 4 else 2 // three of a kind: 4 | one-pair: 2
3 -> if (handMap.none { it.value == 3 }) // two-pair: 3 | three of a kind: 4
(if (jokers == 2) 6 else if (jokers == 1) 5 else 3) // four of a kind: 6 | full-house: 5 | two-pair: 3
else
(if (jokers == 1 || jokers == 3) 6 else 4) // four of a kind: 6 | three of a kind: 4
2 -> if (handMap.any { it.value == 3 }) // full-house: 5 | four of a kind: 6
(if (jokers > 0) 7 else 5) // five of a kind: 7 | full-house: 5
else
(if (jokers == 1 || jokers == 4) 7 else 6) // five of a kind: 7 | four of a kind: 6
else -> 7 // five of a kind: 7
}
return typeStrength
}
/**
* Parses the input into a list of hands.
* @return a list of hands.
*/
private fun parseHands(input: List<String>, withJokers: Boolean = false): List<Hand> {
return input.joinToString("\n").split("\n").map {
val (hand, bid) = it.split(" ")
Hand(hand, bid.toInt(), getTypeStrength(hand, withJokers))
}
}
/**
* Compares two hands by their type strength and then by their relative strength.
*/
private fun strengthComparator(relativeStrengthMap: Map<Char, Int>) = Comparator<Hand> { hand1, hand2 ->
if (hand1.typeStrength != hand2.typeStrength) return@Comparator hand1.typeStrength - hand2.typeStrength
for ((i, card1) in hand1.cards.withIndex()) {
if (card1 == hand2.cards[i]) continue
return@Comparator relativeStrengthMap[card1]!! - relativeStrengthMap[hand2.cards[i]]!!
}
0
}
/**
* Calculates the total winnings of the hands by multiplying the bid with the rank of each hand. The rank is determined
* by the strength of the hand, it is first evaluated by the type strength and then by the relative strength.
* @return the total winnings of the hands.
*/
private fun part1(input: List<String>): Int {
val hands = parseHands(input)
val rankedHands = hands.sortedWith(strengthComparator(relativeStrengthMap()))
return rankedHands.foldIndexed(0) { i, totalWinnings, hand -> totalWinnings + hand.bid * (i + 1) }
}
/**
* The objective is the same of part 1, but now the jokers are considered as the lowest card, and act like whatever
* card would make the hand the strongest type possible.
* @return the total winnings of the hands.
*/
private fun part2(input: List<String>): Int {
val hands = parseHands(input, withJokers = true)
val rankedHands = hands.sortedWith(strengthComparator(relativeStrengthMap(withJokers = true)))
return rankedHands.foldIndexed(0) { i, totalWinnings, hand -> totalWinnings + hand.bid * (i + 1) }
}
fun main() {
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 6440
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 5905
println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 248113761" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 246285222" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 4,546 | Advent-of-Code-2023 | Apache License 2.0 |
src/y2021/Day03.kt | Yg0R2 | 433,731,745 | false | null | package y2021
fun main() {
fun part1(input: List<String>): Int {
val gammaRate = input[0]
.mapIndexed { index, _ -> input.getMostCommonBit(index) }
.joinToString("")
.toInt(2)
val epsilonRate = input[0]
.mapIndexed { index, _ -> input.getLeastCommonBit(index) }
.joinToString("")
.toInt(2)
return gammaRate * epsilonRate
}
fun part2(input: List<String>): Int {
val oxygenGeneratorRating = filterBy(input, 0) { _input, _stringIndex ->
_input.getMostCommonBit(_stringIndex)
}
.first()
.toInt(2)
val co2ScrubberRating = filterBy(input, 0) { _input, _stringIndex ->
_input.getLeastCommonBit(_stringIndex)
}
.first()
.toInt(2)
return oxygenGeneratorRating * co2ScrubberRating
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 198)
check(part2(testInput) == 230)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private val commonComparator: (o1: Map.Entry<Char, Int>, o2: Map.Entry<Char, Int>) -> Int = { o1, o2 ->
if (o1.value == o2.value) -1 else compareValues(o1.value, o2.value)
}
private fun filterBy(input: List<String>, stringIndex: Int, expectedBitBlock: (input: List<String>, stringIndex: Int) -> Char): List<String> {
val expected = expectedBitBlock.invoke(input, stringIndex)
return input.filter { it[stringIndex] == expected }
.let {
if (it.size != 1) {
filterBy(it, stringIndex + 1, expectedBitBlock)
}
else {
it
}
}
}
private fun List<String>.getCommonBit(stringIndex: Int, filter: (Map<Char, Int>) -> Map.Entry<Char, Int>?): Char {
return this
.map { it[stringIndex] }
.groupingBy { it }
.eachCount()
.toSortedMap(compareBy { it.inc() })
.let { filter(it) }
?.key
?: throw IllegalArgumentException("Invalid input String.")
}
// filter less common, keep 1 if both has the same amount
private fun List<String>.getLeastCommonBit(stringIndex: Int): Char {
return getCommonBit(stringIndex) {
it.minWithOrNull(commonComparator)
}
}
// filter most common, keep 1 if both has the same amount
private fun List<String>.getMostCommonBit(stringIndex: Int): Char {
return getCommonBit(stringIndex) {
it.maxWithOrNull(commonComparator)
}
}
| 0 | Kotlin | 0 | 0 | d88df7529665b65617334d84b87762bd3ead1323 | 2,617 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day9/Day9.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day9
import execute
import readAllText
import wtf
import kotlin.math.sign
enum class Direction { U, D, L, R }
data class Pos(val r: Int, val c: Int) {
fun isAdjacent(other: Pos) = (r - other.r) in (-1..1) && (c - other.c) in (-1..1)
fun moveTowards(other: Pos) = Pos(r + (other.r - r).sign, c + (other.c - c).sign)
fun move(d: Direction) = when (d) {
Direction.U -> copy(r = r - 1)
Direction.D -> copy(r = r + 1)
Direction.L -> copy(c = c - 1)
Direction.R -> copy(c = c + 1)
}
}
class State(length: Int) {
var rope: List<Pos> = (1..length).map { Pos(0, 0) }
val visited: MutableSet<Pos> = mutableSetOf(Pos(0, 0))
fun updateWith(newRope: List<Pos>) {
rope = newRope
visited += newRope.last()
}
}
fun State.solve(input: String) = moveSequence(input)
.flatMap { (direction, l) -> (1..l).map { direction } }
.forEach { direction ->
buildList {
rope.forEachIndexed { index, pos ->
add(
when {
index == 0 -> pos.move(direction)
pos.isAdjacent(last()) -> pos
else -> pos.moveTowards(last())
}
)
}
}.let { updateWith(it) }
}
fun part1(input: String) = State(2).apply { solve(input) }.visited.size
fun part2(input: String) = State(10).apply { solve(input) }.visited.size
private val regex = "(.) (\\d+)".toRegex()
private fun moveSequence(input: String) = input.lineSequence()
.filterNot(String::isBlank)
.map { regex.matchEntire(it) ?: wtf(it) }
.map { it.destructured.let { (a, b) -> Direction.valueOf(a) to b.toInt() } }
fun main() {
val input = readAllText("local/day9_input.txt")
val test = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent()
val test2 = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent()
execute(::part1, test, 13)
execute(::part1, input)
execute(::part2, test, 1)
execute(::part2, test2, 36)
execute(::part2, input)
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 2,213 | advent-of-code-2022 | MIT License |
src/Day02.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} |
const val SCORE_ROCK = 1
const val SCORE_PAPER = 2
const val SCORE_SCISSORS = 3
const val DRAW = 'Y'
const val LOSE = 'X'
const val WIN = 'Z'
const val EXPECTED_PART1_CHECK_ANSWER = 15
const val EXPECTED_PART2_CHECK_ANSWER = 12
const val POS_THEIR_CHOICE = 0
const val POS_OUR_CHOICE = 2
const val SCORE_WIN = 6
const val SCORE_DRAW = 3
const val SCORE_LOSE = 0
enum class Shape(val shapeScore: Int) {
Rock(SCORE_ROCK),
Paper(SCORE_PAPER),
Scissors(SCORE_SCISSORS);
companion object {
fun from(char: Char): Shape =
when (char) {
'A', 'X' -> Rock
'B', 'Y' -> Paper
'C', 'Z' -> Scissors
else -> error("Unknown value $char")
}
}
}
val BEATS = mapOf(
Shape.Rock to Shape.Scissors,
Shape.Paper to Shape.Rock,
Shape.Scissors to Shape.Paper,
)
val BEATEN_BY = mapOf(
Shape.Scissors to Shape.Rock,
Shape.Rock to Shape.Paper,
Shape.Paper to Shape.Scissors,
)
fun main() {
fun getScore(theirs: Shape, ours: Shape) = when {
ours == theirs -> ours.shapeScore + SCORE_DRAW
BEATS[ours] == theirs -> ours.shapeScore + SCORE_WIN
else -> ours.shapeScore + SCORE_LOSE
}
fun part1(input: List<String>): Int {
return input.sumOf {
val theirs = Shape.from(it[POS_THEIR_CHOICE])
val ours = Shape.from(it[POS_OUR_CHOICE])
getScore(theirs, ours)
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val theirs = Shape.from(it[POS_THEIR_CHOICE])
val ours = when (it[POS_OUR_CHOICE]) {
DRAW -> theirs
LOSE -> BEATS[theirs]!!
WIN -> BEATEN_BY[theirs]!!
else -> error("Wrong input")
}
getScore(theirs, ours)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == EXPECTED_PART1_CHECK_ANSWER)
check(part2(testInput) == EXPECTED_PART2_CHECK_ANSWER)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 2,201 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | hanmet | 573,490,488 | false | {"Kotlin": 9896} | fun main() {
fun calcPoints2(opponentsShape: String, game: String): Int {
return when {
opponentsShape == "A" && game == "X" -> 3 + 0
opponentsShape == "A" && game == "Y" -> 1 + 3
opponentsShape == "A" && game == "Z" -> 2 + 6
opponentsShape == "B" && game == "X" -> 1 + 0
opponentsShape == "B" && game == "Y" -> 2 + 3
opponentsShape == "B" && game == "Z" -> 3 + 6
opponentsShape == "C" && game == "X" -> 2 + 0
opponentsShape == "C" && game == "Y" -> 3 + 3
opponentsShape == "C" && game == "Z" -> 1 + 6
else -> -1
}
}
fun calcPoints1(opponentsShape: String, game: String): Int {
return when {
opponentsShape == "A" && game == "X" -> 1 + 3
opponentsShape == "A" && game == "Y" -> 2 + 6
opponentsShape == "A" && game == "Z" -> 3 + 0
opponentsShape == "B" && game == "X" -> 1 + 0
opponentsShape == "B" && game == "Y" -> 2 + 3
opponentsShape == "B" && game == "Z" -> 3 + 6
opponentsShape == "C" && game == "X" -> 1 + 6
opponentsShape == "C" && game == "Y" -> 2 + 0
opponentsShape == "C" && game == "Z" -> 3 + 3
else -> -1
}
}
fun part1(input: List<String>): Int {
return input.sumOf {
val (opponentsShape, game) = it.split(" ")
calcPoints1(opponentsShape, game)
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val (opponentsShape, game) = it.split(" ")
calcPoints2(opponentsShape, game)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e4e1722726587639776df86de8d4e325d1defa02 | 1,932 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/day18/Day18.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day18
import check
import readInput
import kotlin.math.abs
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day18_test")
check(part1(testInput), 64)
check(part2(testInput), 58)
val input = readInput("2022", "Day18")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val lavaDroplet = parsePositions(input)
return calculateSurface(lavaDroplet)
}
private fun part2(input: List<String>): Int {
val lavaDroplet = parsePositions(input)
val minX = lavaDroplet.minOf { it.x } - 1
val maxX = lavaDroplet.maxOf { it.x } + 1
val minY = lavaDroplet.minOf { it.y } - 1
val maxY = lavaDroplet.maxOf { it.y } + 1
val minZ = lavaDroplet.minOf { it.z } - 1
val maxZ = lavaDroplet.maxOf { it.z } + 1
val enclosingVolume = getVolume(minX, maxX, minY, maxY, minZ, maxZ)
// enclosing air volume with bubbles of air on the inside
val airVolume = enclosingVolume - lavaDroplet
val startingPos = airVolume.first {
it.x == minX || it.x == maxX || it.y == minY || it.y == maxY || it.z == minZ || it.z == maxZ
}
val outsideAirVolume = getAllReachablePositions(startingPos, airVolume)
val gasPockets = airVolume - outsideAirVolume
return calculateSurface(lavaDroplet) - calculateSurface(gasPockets)
}
private fun getAllReachablePositions(
startingPos: Pos,
airVolume: Set<Pos>
): Set<Pos> {
val queue = ArrayDeque<Pos>().apply { add(startingPos) }
val visited = hashSetOf(startingPos)
while (queue.isNotEmpty()) {
val pos = queue.removeFirst()
for (next in pos.adjecants) {
if (next !in visited && next in airVolume) {
visited += next
queue.addLast(next)
}
}
}
return visited
}
private fun calculateSurface(positions: Set<Pos>) =
positions.size * 6 - positions.sumOf { pos ->
positions.count {
it touches pos
}
}
private fun getVolume(
minX: Int,
maxX: Int,
minY: Int,
maxY: Int,
minZ: Int,
maxZ: Int
): MutableSet<Pos> {
val volume = mutableSetOf<Pos>()
for (x in minX..maxX) {
for (y in minY..maxY) {
for (z in minZ..maxZ) {
volume += Pos(x, y, z)
}
}
}
return volume
}
private fun parsePositions(input: List<String>) = input.mapTo(mutableSetOf()) { line ->
val (x, y, z) = line.split(',').map { it.toInt() }
Pos(x, y, z)
}
private data class Pos(val x: Int, val y: Int, val z: Int) {
infix fun touches(other: Pos): Boolean = (x == other.x && y == other.y && abs(z - other.z) == 1) ||
(x == other.x && z == other.z && abs(y - other.y) == 1) ||
(y == other.y && z == other.z && abs(x - other.x) == 1)
val adjecants: Set<Pos>
get() = setOf(
Pos(x + 1, y, z),
Pos(x, y + 1, z),
Pos(x, y, z + 1),
Pos(x - 1, y, z),
Pos(x, y - 1, z),
Pos(x, y, z - 1),
)
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 3,140 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/aoc2023/Day06.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
class Day06 {
fun part1(input: List<String>): Long = parseRaces(input)
.map { race -> (1L..race.time).map { t -> (race.time - t) * t }.count { it > race.distance } }
.fold(1L) { acc, r -> acc * r }
fun part2(input: List<String>): Long {
val (time, distance) = parseRace(input)
var first = 1L
while ((time - first) * first <= distance) {
first += 1L
}
var last = time - 1L
while ((time - last) * last <= distance) {
last -= 1L
}
return last - first + 1L
}
private fun parseRaces(input: List<String>): List<Race> {
val parser: (String) -> List<Long> =
{ s -> s.split(' ').drop(1).filter { it.isNotEmpty() }.map { it.toLong() } }
val times = parser(input[0])
val distances = parser(input[1])
return times.zip(distances).map { (t, d) -> Race(time = t, distance = d) }
}
private fun parseRace(input: List<String>): Race {
val (time) = "^Time: (.+)$".toRegex().find(input[0])!!.destructured
val (distance) = "^Distance: (.+)$".toRegex().find(input[1])!!.destructured
return Race(
time = time.replace(" ", "").toLong(),
distance = distance.replace(" ", "").toLong(),
)
}
data class Race(val time: Long, val distance: Long)
}
fun main() {
val day06 = Day06()
val input = readInputAsStringList("day06.txt")
println("06, part 1: ${day06.part1(input)}")
println("06, part 2: ${day06.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 1,568 | advent-of-code-2023 | MIT License |
src/Day12.kt | wujingwe | 574,096,169 | false | null | typealias Point = Pair<Int, Int>
object Day12 {
private val DIRS = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1)
private fun bfs(map: List<List<Char>>, start: Point, end: Point): Int {
val m = map.size
val n = map[0].size
val visited = MutableList(m) { MutableList(n) { false } }
val queue = ArrayDeque<Point>()
queue.addLast(start)
var count = 0
while (queue.isNotEmpty()) {
val size = queue.size
for (i in 0 until size) {
val point = queue.removeFirst()
if (visited[point.first][point.second]) { // important!
continue
}
visited[point.first][point.second] = true
if (point == end) {
return count
}
DIRS.forEach { (dx, dy) ->
val nx = point.first + dx
val ny = point.second + dy
if (nx in 0 until m && ny in 0 until n && !visited[nx][ny]) {
if (map[nx][ny] - map[point.first][point.second] <= 1) {
queue.addLast(nx to ny)
}
}
}
}
count++
}
return Int.MAX_VALUE
}
fun part1(inputs: List<String>): Int {
val m = inputs.size
val n = inputs[0].length
var start = 0 to 0
var end = 0 to 0
val map = inputs.map { s -> s.toCharArray().toMutableList() }
for (i in 0 until m) {
for (j in 0 until n) {
if (map[i][j] == 'S') {
map[i][j] = 'a'
start = i to j
} else if (map[i][j] == 'E') {
map[i][j] = 'z'
end = i to j
}
}
}
return bfs(map, start, end)
}
fun part2(inputs: List<String>): Int {
val m = inputs.size
val n = inputs[0].length
val starts = mutableListOf<Point>()
var end = 0 to 0
val map = inputs.map { s -> s.toCharArray().toMutableList() }
for (i in 0 until m) {
for (j in 0 until n) {
if (map[i][j] == 'a') {
starts.add(i to j)
} else if (map[i][j] == 'S') {
map[i][j] = 'a'
starts.add(i to j)
} else if (map[i][j] == 'E') {
map[i][j] = 'z'
end = i to j
}
}
}
return starts.minOf { bfs(map, it, end) }
}
}
fun main() {
fun part1(inputs: List<String>): Int {
return Day12.part1(inputs)
}
fun part2(inputs: List<String>): Int {
return Day12.part2(inputs)
}
val testInput = readInput("../data/Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("../data/Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a5777a67d234e33dde43589602dc248bc6411aee | 3,060 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day14.kt | bananer | 434,885,332 | false | {"Kotlin": 36979} | typealias Rules = Map<Pair<Char, Char>, Char>
fun Rules.get(c1: Char, c2: Char): Char? = get(Pair(c1, c2))
fun main() {
fun parseInput(input: List<String>): Pair<String, Rules> {
check(input[1].isEmpty())
val rules = mutableMapOf<Pair<Char, Char>, Char>()
input.subList(2, input.size).forEach {
check(it.substring(2, 6) == " -> ")
rules[Pair(it[0], it[1])] = it[6]
}
return Pair(input[0], rules)
}
fun apply(template: String, rules: Rules): String {
val chars = mutableListOf<Char>()
var i = 0
while (i < template.length - 1) {
chars.add(template[i])
val insert = rules.get(template[i], template[i+1])
if (insert != null) {
chars.add(insert)
}
i++
}
chars.add(template.last())
return String(chars.toCharArray())
}
fun countChars(str: String): Map<Char, Int> {
val res = mutableMapOf<Char, Int>()
for (c in str) {
res[c] = (res[c] ?: 0) + 1
}
return res
}
fun part1(input: List<String>): Int {
val (templ, rules) = parseInput(input)
var str = templ
(0 until 10).forEach {
str = apply(str, rules)
}
val charCounts = countChars(str)
return charCounts.maxOf { it.value } - charCounts.minOf { it.value }
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
val testOutput1 = part1(testInput)
println("test output1: $testOutput1")
check(testOutput1 == 1588)
val testOutput2 = part2(testInput)
println("test output2: $testOutput2")
//check(testOutput2 == -1)
val input = readInput("Day14")
println("output part1: ${part1(input)}")
println("output part2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 98f7d6b3dd9eefebef5fa3179ca331fef5ed975b | 1,983 | advent-of-code-2021 | Apache License 2.0 |
src/Day06.kt | Miguel1235 | 726,260,839 | false | {"Kotlin": 21105} | private class Race(val time: Long, val record: Long)
private fun parseInput(input: List<String>): List<Race> {
val dRegex = Regex("""\d+""")
val times = dRegex.findAll(input[0]).map { it.value.toLong() }.toList()
val records = dRegex.findAll(input[1]).map { it.value.toLong() }.toList()
val races: MutableList<Race> = mutableListOf()
for (i in times.indices) {
val time = times[i]
val record = records[i]
races.add(Race(time, record))
}
return races
}
private fun countWays2Win(race: Race): Int {
var ways2Win = 0
for (timeHold in 0..race.time) {
val distance = timeHold * (race.time - timeHold)
if (distance > race.record) {
ways2Win++
}
}
return ways2Win
}
private val joinAndObtain = {line: String -> line.replace("\\s".toRegex(), "").split(":")[1].toLong() }
private val removeKerning = {input:List<String> -> Race( joinAndObtain(input[0]), joinAndObtain(input[1]) ) }
private val part1 = {input: List<String> -> parseInput(input).fold(1) { acc, race -> acc * countWays2Win(race) } }
private val part2 = {input: List<String> -> countWays2Win(removeKerning(input)) }
fun main() {
val testInput = readInput("Day06_test")
check(part1(testInput) == 288)
check(part2(testInput) == 71503)
val input = readInput("Day06")
check(part1(input) == 293046)
check(part2(input) == 35150181)
}
| 0 | Kotlin | 0 | 0 | 69a80acdc8d7ba072e4789044ec2d84f84500e00 | 1,420 | advent-of-code-2023 | MIT License |
src/Day16.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | import kotlin.math.max
import kotlin.math.pow
data class Day16State(val myPos: Int, val elephantPos: Int, val valveStates: Int) {
fun nextPossibleStates(adj: List<List<Int>>, nonEmptyCount: Int) = sequence<Day16State> {
if (myPos < nonEmptyCount) {
yield(copy(valveStates = valveStates or (1 shl myPos)))
}
adj[myPos].forEach {
yield(copy(myPos = it))
}
}.flatMap {
sequence {
it.apply {
if (elephantPos < nonEmptyCount) {
yield(copy(valveStates = valveStates or (1 shl elephantPos)))
}
adj[elephantPos].forEach {
yield(copy(elephantPos = it))
}
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val valves = input.map(::parseValveRaw).sortedDescending()
val valveNameMap = valves.withIndex().map { it.value.name to it.index }.toMap()
val adj = buildMap<Int, MutableList<Int>> {
valves.forEachIndexed { thisIdx, it ->
it.adjacentValves.map { adjName -> valveNameMap[adjName]!! }.forEach { adjIdx ->
this.getOrPut(thisIdx, { mutableListOf<Int>() }).add(adjIdx)
}
}
}
val flows = valves.map { it.flow }.takeWhile { it != 0 }
val nonEmptyCount = valves.count { it.flow > 0 }
val startIndex = valves.indexOfFirst { it.name == "AA" }
val possibleStates = (2.0).pow(nonEmptyCount).toInt()
val flowMemo = mutableMapOf<Int, Int>()
fun calcFlow(mask: Int) = flowMemo.getOrPut(mask, {
(0 until nonEmptyCount).sumOf { if (1 shl it and mask != 0) flows[it] else 0 }
})
var cur = List(valves.size) { MutableList(possibleStates) { Int.MIN_VALUE } }
var next = List(valves.size) { MutableList(possibleStates) { Int.MIN_VALUE } }
cur[startIndex][0] = 0 // first position
repeat(30) {
cur.forEachIndexed { position, states ->
states.forEachIndexed { state, value ->
if (value != Int.MIN_VALUE) {
// do nothing
next[position][state] = max(next[position][state], value + calcFlow(state))
// open valve
if (position < nonEmptyCount) {
next[position][state or (1 shl position)] =
max(next[position][state or (1 shl position)], value + calcFlow(state))
}
// move next
adj[position]!!.forEach { nextPos ->
next[nextPos][state] = max(next[nextPos][state], value + calcFlow(state))
}
}
}
}
val tmp = next to cur
cur = tmp.first
next = tmp.second
}
return cur.maxOf { it.max() }
}
fun part2(input: List<String>): Int {
val valves = input.map(::parseValveRaw).sortedDescending()
val valveNameMap = valves.withIndex().map { it.value.name to it.index }.toMap()
val adj = List(valves.size) { mutableListOf<Int>() }
valves.forEachIndexed { thisIdx, it ->
it.adjacentValves.map { adjName -> valveNameMap[adjName]!! }.forEach { adjIdx ->
adj[thisIdx].add(adjIdx)
adj[adjIdx].add(thisIdx)
}
}
val flows = valves.map { it.flow }.takeWhile { it != 0 }
val nonEmptyCount = valves.count { it.flow > 0 }
val startIndex = valves.indexOfFirst { it.name == "AA" }
val possibleStates = (2.0).pow(nonEmptyCount).toInt()
val flowMemo = mutableMapOf<Int, Int>()
fun calcFlow(mask: Int) = flowMemo.getOrPut(mask, {
(0 until nonEmptyCount).sumOf { if (1 shl it and mask != 0) flows[it] else 0 }
})
val x = valves.size
fun encode(a: Int, b: Int): Int {
return a * x + b
}
fun decode(s: Int): Pair<Int, Int> {
return s / x to s % x
}
var cur = List(valves.size * valves.size) { MutableList(possibleStates) { Int.MIN_VALUE } }
var next = List(valves.size * valves.size) { MutableList(possibleStates) { Int.MIN_VALUE } }
cur[encode(startIndex, startIndex)][0] = 0 // first position
repeat(26) { time ->
cur.forEachIndexed { enc, states ->
states.forEachIndexed { state, value ->
if (value != Int.MIN_VALUE) {
val v = value + calcFlow(state)
val (myPosition, elephantPosition) = decode(enc)
Day16State(myPosition, elephantPosition, state).nextPossibleStates(adj, nonEmptyCount)
.forEach { (myNextPos, elephantNextPos, nextState) ->
val s = encode(myNextPos, elephantNextPos)
next[s][nextState] = max(next[s][nextState], v)
}
cur[enc][state] = Int.MIN_VALUE
}
}
}
val tmp = next to cur
cur = tmp.first
next = tmp.second
}
return cur.maxOf { it.max() }
}
val testInput = readInput("Day16_test")
println(part1(testInput))
check(part1(testInput) == 1651)
println(part2(testInput))
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
// WARNING: VERY LONG RUN TIME
// println(part2(input))
}
data class ValveRaw(val name: String, val flow: Int, val adjacentValves: List<String>) : Comparable<ValveRaw> {
override fun compareTo(other: ValveRaw): Int {
return flow.compareTo(other.flow).let {
if (it != 0) it
else name.compareTo(other.name)
}
}
}
private fun parseValveRaw(input: String): ValveRaw {
val names = Regex("[A-Z]{2}").findAll(input).map { it.value }.toList()
val flow = Regex("\\d+").find(input)!!.value.toInt()
return ValveRaw(names[0], flow, names.subList(1, names.size))
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 6,280 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day07_alt1.kt | zodiia | 573,067,225 | false | {"Kotlin": 11268} | package day07alt1
import readInput
enum class FsNodeType { FILE, DIR }
data class FsNode(
var size: Long,
val type: FsNodeType,
val childNodes: HashMap<String, FsNode> = HashMap(),
) {
private val childDirs: Collection<FsNode> get() = childNodes.filter { it.value.type == FsNodeType.DIR }.map { it.value }
val flatDirs: Collection<FsNode> get() = buildList {
add(this@FsNode)
addAll(childDirs.flatMap { it.flatDirs })
}
fun getNode(path: ArrayDeque<String>): FsNode {
if (path.size == 0) {
return this
}
return childNodes[path.first()]?.getNode(ArrayDeque(path).also { it.removeFirst() }) ?: throw IllegalStateException()
}
fun calculateSize(): Long {
if (!(size == 0L && childNodes.size > 0)) {
return size
}
size = childNodes.map { it.value.calculateSize() }.sum()
return size
}
}
fun main() {
fun parseFiles(input: List<String>): FsNode {
val rootNode = FsNode(0L, FsNodeType.DIR)
var cwd = ArrayDeque<String>()
input.forEach { line ->
if (line.startsWith("$ cd ")) {
when (line.substring(5)) {
"/" -> cwd = ArrayDeque()
".." -> cwd.removeLast()
else -> cwd.addLast(line.substring(5))
}
} else if (!line.startsWith("$")) {
val parts = line.split(' ')
val type = if (parts[0] == "dir") FsNodeType.DIR else FsNodeType.FILE
rootNode.getNode(cwd).childNodes[parts[1]] = FsNode(parts[0].toLongOrNull() ?: 0L, type)
}
}
rootNode.calculateSize()
return rootNode
}
fun part1(input: List<String>) = parseFiles(input).flatDirs.filter { it.size <= 100000 }.sumOf { it.size }
fun part2(input: List<String>): Long {
val root = parseFiles(input)
return root.flatDirs.fold(Long.MAX_VALUE) { cur, it -> if (it.size >= root.size - 40000000 && it.size < cur) it.size else cur }
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 4f978c50bb7603adb9ff8a2f0280f8fdbc652bf2 | 2,178 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | mvmlisb | 572,859,923 | false | {"Kotlin": 14994} | private data class Directory(val parent: Directory?, val name: String) {
private var directories = mutableListOf<Directory>()
private var sizeOnCurrentLevel = 0L
companion object {
fun createFromCdCommand(string: String, rootDirectory: Directory, currentDirectory: Directory): Directory {
return when (val name = string.substringAfter("cd ")) {
"/" -> rootDirectory
".." -> currentDirectory.parent ?: throw Error()
else -> currentDirectory.getDirectories().first { it.name == name }
}
}
}
fun getSize(): Long = sizeOnCurrentLevel + directories.sumOf(Directory::getSize)
fun getDirectories(): List<Directory> = directories
fun collect(): Sequence<Directory> = sequence {
yield(this@Directory)
yieldAll(directories.flatMap { it.collect() }.asSequence())
}
fun fillFromLsResult(string: String) {
val (first, second) = string.split(" ")
if (first == "dir")
directories += Directory(this, second)
else
sizeOnCurrentLevel += first.toLong()
}
}
fun main() {
val rootDirectory = createRootDirectory()
val part1 = rootDirectory
.collect()
.filter { it.getSize() < 100000 }
.sumOf { it.getSize() }
val part2 = rootDirectory
.collect()
.filter { it.getSize() > 30000000 - (70000000 - rootDirectory.getSize()) }
.sortedBy { it.getSize() }
.first()
.getSize()
println(part1)
println(part2)
}
private fun createRootDirectory(): Directory {
val input = readInput("Day07_test")
val rootDirectory = Directory(null, "/")
var currentDirectory = rootDirectory
input.forEach {
when {
it.startsWith("\$ cd") -> currentDirectory =
Directory.createFromCdCommand(it, rootDirectory, currentDirectory)
!it.startsWith("\$") -> currentDirectory.fillFromLsResult(it)
}
}
return rootDirectory
}
| 0 | Kotlin | 0 | 0 | 648d594ec0d3b2e41a435b4473b6e6eb26e81833 | 2,036 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day07.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
sealed class Day07 {
abstract fun size(): Int
data class Directory(val name: String, val parent: Directory?, val contents: MutableList<Day07> = mutableListOf()) :
Day07() {
override fun size(): Int = contents.sumOf { it.size() }
fun dirs() = contents.filterIsInstance<Day07.Directory>()
}
data class File(val size: Int, val name: String) : Day07() {
override fun size(): Int = size
}
}
class FileSystem() {
val root: Day07.Directory = Day07.Directory("/", null)
var cwd = root
fun dfs(): Sequence<Day07.Directory> = dfs(root)
fun dfs(dir: Day07.Directory): Sequence<Day07.Directory> = sequence {
dir.dirs().forEach { yieldAll(dfs(it)) }
yield(dir)
}
}
private val cd = Regex("\\$ cd (\\S+)")
private val ls = Regex("\\$ ls")
private val dir = Regex("dir (\\S+)")
private val file = Regex("(\\d+) (\\S+)")
fun FileSystem.create(commands: Iterator<String>) {
while (commands.hasNext()) {
val cmd = commands.next()
cd.matchEntire(cmd)?.let { match ->
val (dir) = match.destructured
cwd = when (dir) {
"/" -> root
".." -> cwd.parent!!
else -> cwd.dirs().first { it.name == dir }
}
}
if (cmd == "${'$'} ls") {
// Nothing
}
dir.matchEntire(cmd)?.let { match ->
val (name) = match.destructured
cwd.contents.add(Day07.Directory(name, cwd))
}
file.matchEntire(cmd)?.let { match ->
val (size, name) = match.destructured
cwd.contents.add(Day07.File(size.toInt(), name))
}
}
}
fun main() {
val testInput = """${'$'} 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""".split("\n")
fun part1(input: List<String>): Int {
val fs = FileSystem()
fs.create(input.iterator())
return fs.dfs().map { it.size() }.filter { it < 100_000 }.sum()
}
fun part2(input: List<String>): Int {
val fs = FileSystem()
fs.create(input.iterator())
val free = 70_000_000 - fs.root.size()
val target = 30_000_000 - free
return fs.dfs().map { it.size() }.sorted().filter { it >= target }.first()
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 95437)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 7).toList()
println(part1(puzzleInput))
println(part2(puzzleInput))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 2,797 | aoc-2022-kotlin | Apache License 2.0 |
lib/src/main/kotlin/com/bloidonia/advent/day15/Day15.kt | timyates | 433,372,884 | false | {"Kotlin": 48604, "Groovy": 33934} | package com.bloidonia.advent.day15
import com.bloidonia.advent.readList
import java.util.PriorityQueue
import kotlin.math.abs
typealias Position = Pair<Int, Int>
operator fun Position.plus(pos: Position) = Position(this.first + pos.first, this.second + pos.second)
class Cave(private val width: Int, private val costs: IntArray) {
private val height by lazy { costs.size / width }
private fun inCave(pos: Position, scale: Int = 1) =
pos.first in 0 until width * scale && pos.second in 0 until height * scale
private fun offset(pos: Position, scale: Int = 1) =
if (inCave(pos, scale)) pos.second.mod(height) * width + pos.first.mod(width) else -1
// Costs increment for every repetition of the grid in both x and 9
fun cost(pos: Position, scale: Int = 1): Int =
(costs[offset(pos, scale)] + (pos.first / width) + (pos.second / height)).let {
if (it > 9) it.mod(10) + 1 else it
}
private fun guessDistance(start: Position, finish: Position) =
abs(start.first - finish.first) + abs(start.second - finish.second)
// A* search
fun search(scale: Int = 1): Int {
val start = Position(0, 0)
val end = Position(width * scale - 1, height * scale - 1)
val done = mutableSetOf<Position>()
val totalCost = mutableMapOf(start to 0)
val costGuess = mutableMapOf(start to guessDistance(start, end))
val todo = PriorityQueue<Position>(Comparator.comparingInt { costGuess.getValue(it) }).apply {
add(start)
}
while (todo.isNotEmpty()) {
val currentPos = todo.poll()
if (currentPos == end) return costGuess.getValue(end)
done.add(currentPos)
neighbours(currentPos, scale).filterNot { done.contains(it) }.forEach { neighbour ->
val score = totalCost.getValue(currentPos) + cost(neighbour, scale)
if (score < totalCost.getOrDefault(neighbour, Int.MAX_VALUE)) {
totalCost[neighbour] = score
costGuess[neighbour] = score + guessDistance(neighbour, end)
todo.offer(neighbour)
}
}
}
return -1
}
// Right, left, down and up neighbors that are still in the cave
private fun neighbours(position: Position, scale: Int = 1): List<Position> =
listOf(Position(1, 0), Position(-1, 0), Position(0, 1), Position(0, -1)).map { position + it }
.filter { inCave(it, scale) }
}
fun List<String>.toCave() = Cave(first().length, joinToString("").map { "$it".toInt() }.toIntArray())
fun main() {
println(readList("/day15input.txt").toCave().search())
println(readList("/day15input.txt").toCave().search(5))
} | 0 | Kotlin | 0 | 1 | 9714e5b2c6a57db1b06e5ee6526eb30d587b94b4 | 2,767 | advent-of-kotlin-2021 | MIT License |
src/Day15.kt | frango9000 | 573,098,370 | false | {"Kotlin": 73317} | import kotlin.math.absoluteValue
fun main() {
val input = readInput("Day15")
printTime { print(Day15.part1(input, 2_000_000)) }
printTime { print(Day15.part2(input, 4_000_000)) }
}
class Day15 {
companion object {
fun part1(input: List<String>, targetY: Int): Int {
val sensorsAndBeacons = input.map {
it.substring(10).split(": closest beacon is at ").map { it.split(", ").map { it.substring(2).toInt() } }
.map { (x, y) -> Point(x, y) }
}
val blockedRanges: List<IntRange> = sensorsAndBeacons.mapNotNull {
scannerRangeOnRow(it, targetY)
}.merge()
val blockedXsInYTarget = sensorsAndBeacons.flatten().filter { it.y == targetY }.map { it.x }.toSet()
return blockedRanges.sumOf { it.size } - blockedXsInYTarget.size
}
fun part2(input: List<String>, side: Int): Long {
val sensorsAndBeacons = input.map {
it.substring(10).split(": closest beacon is at ").map { it.split(", ").map { it.substring(2).toInt() } }
.map { (x, y) -> Point(x, y) }
}
val validRange = 0..side
for (y in validRange) {
val blockedRanges: List<IntRange> = sensorsAndBeacons.mapNotNull {
scannerRangeOnRow(it, y)
}
val unblocked = validRange.subtract(blockedRanges)
if (unblocked.isNotEmpty()) {
return unblocked.first().first * 4_000_000L + y
}
}
error("Not Found")
}
private fun scannerRangeOnRow(points: List<Point>, targetY: Int): IntRange? {
val (sensor, beacon) = points
val sensorCoverage = sensor.rectilinearDistanceTo(beacon)
val yDistanceToYTarget = (targetY - sensor.y).absoluteValue
val yOverlapBy = sensorCoverage - yDistanceToYTarget
return if (yOverlapBy <= 0) null
else (sensor.x - yOverlapBy..sensor.x + yOverlapBy)
}
// fun part1withArray(input: List<String>, targetY: Int): Int {
// val sensorsAndBeacons = input.map {
// it.substring(10).split(": closest beacon is at ").map { it.split(", ").map { it.substring(2).toInt() } }
// .map { (x, y) -> Point(x, y) }
// }
//
// val offset = sensorsAndBeacons.maxOf { it[0].rectilinearDistanceTo(it[1]) } * 2
// val beaconMaxX = sensorsAndBeacons.maxOf { it[1].x }
// val blockedXsInTargetY = BooleanArray(beaconMaxX + offset)
//
// for ((sensor, beacon) in sensorsAndBeacons) {
// val sensorCoverage = sensor.rectilinearDistanceTo(beacon)
// val yDistanceToYTarget = (targetY - sensor.y).absoluteValue
// val yOverlapBy = sensorCoverage - yDistanceToYTarget
// if (yOverlapBy > 0) {
// for (x in (sensor.x - (yOverlapBy)) towards (sensor.x + (yOverlapBy))) {
// blockedXsInTargetY[x + offset] = true
// }
// }
// }
//
// val beaconXsInYTarget = sensorsAndBeacons.map { it[1] }.filter { it.y == targetY }.map { it.x }
// for (beaconX in beaconXsInYTarget) {
// blockedXsInTargetY[beaconX + offset] = false
// }
//
// return blockedXsInTargetY.count { it }
// }
//
// fun part2WithArray(input: List<String>, side: Int): Int {
// val sensorsAndBeacons = input.map {
// it.substring(10).split(": closest beacon is at ").map { it.split(", ").map { it.substring(2).toInt() } }
// .map { (x, y) -> Point(x, y) }
// }
// val validRange = 0..side
//
// for (y in validRange) {
// val blockedXsInTargetY = BooleanArray(side + 1)
// for ((sensor, beacon) in sensorsAndBeacons) {
// val sensorCoverage = sensor.rectilinearDistanceTo(beacon)
// val yDistanceToYTarget = (y - sensor.y).absoluteValue
// val yOverlapBy = sensorCoverage - yDistanceToYTarget
// if (yOverlapBy > 0) {
// for (x in (sensor.x - (yOverlapBy)) towards (sensor.x + (yOverlapBy))) {
// if (x in validRange && y in validRange) blockedXsInTargetY[x] = true
// }
// }
// }
// if (blockedXsInTargetY.any { !it }) return blockedXsInTargetY.indexOfFirst { !it } * 4_000_000 + y
// }
// error("Not Found")
// }
}
class Point(var x: Int = 0, var y: Int = 0) {
fun rectilinearDistanceTo(point: Point): Int {
return (this.x - point.x).absoluteValue + (this.y - point.y).absoluteValue
}
override fun toString(): String {
return "Point(x=$x, y=$y)"
}
operator fun component1() = x
operator fun component2() = y
}
}
| 0 | Kotlin | 0 | 0 | 62e91dd429554853564484d93575b607a2d137a3 | 5,142 | advent-of-code-22 | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2020/Day11.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2020
import com.s13g.aoc.*
/**
* --- Day 11: Seating System ---
* https://adventofcode.com/2020/day/11
*/
class Day11 : Solver {
override fun solve(lines: List<String>): Result {
val dim = XY(lines[0].length, lines.size)
val map = mutableMapOf<XY, Char>()
lines.indices.forEach { y -> lines[y].indices.forEach { x -> map[XY(x, y)] = lines[y][x] } }
return Result("${dance(map, dim, 4, true).countOccupied()}", "${dance(map, dim, 5, false).countOccupied()}")
}
}
// Iterate over the whole seating config and produce a new one as we go.
private fun dance(input: Map<XY, Char>, dim: XY, minAdj: Int, isA: Boolean): Map<XY, Char> {
var current = input.toMutableMap()
while (true) {
val newOne = current.toMutableMap()
for (pos in input.keys) {
val num = if (isA) current.numAdj(pos, 1) else current.numAdj(pos, dim.max())
newOne[pos] = if (current[pos] == 'L' && num == 0) '#'
else if (current[pos] == '#' && num >= minAdj) 'L'
else current[pos]!!
}
if (current == newOne) return current
current = newOne
}
}
// Iterate over the eight directions for 'max' maximum steps. For part A that's '1'.
private val dirs = listOf(XY(-1, -1), XY(0, -1), XY(1, -1), XY(-1, 0), XY(1, 0), XY(-1, 1), XY(0, 1), XY(1, 1))
private fun Map<XY, Char>.numAdj(xy: XY, max: Int): Int {
var count = 0
for (dir in dirs) {
val pos = xy.copy()
for (i in 1..max) {
pos.addTo(dir)
if (this[pos] == '#') count++
if (pos !in this || this[pos] != '.') break
}
}
return count
}
private fun Map<XY, Char>.countOccupied() = this.values.count { it == '#' }
| 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,658 | euler | Apache License 2.0 |
src/Day12.kt | jimmymorales | 572,156,554 | false | {"Kotlin": 33914} | import kotlin.collections.ArrayDeque
fun main() {
fun Pair<Int, Int>.neighbors(): List<Pair<Int, Int>> = buildList {
add(first + 1 to second)
add(first to second + 1)
add(first - 1 to second)
add(first to second - 1)
}
fun Array<IntArray>.search(start: Pair<Int, Int>, end: Pair<Int, Int>): Int {
val queue = ArrayDeque<Pair<Pair<Int, Int>, Int>>().apply { addLast(start to 0) }
val visited = mutableSetOf<Pair<Int, Int>>().apply { add(start) }
while (queue.isNotEmpty()) {
val (pos, level) = queue.removeFirst()
if (pos == end) {
return level
}
pos.neighbors()
.filter { it.first in indices && it.second in this[0].indices }
.forEach { node ->
if (node !in visited && this[node.first][node.second] - this[pos.first][pos.second] <= 1) {
visited.add(node)
queue.addLast(node to level + 1)
}
}
}
return -1
}
fun part1(input: List<String>): Int {
var start = 0 to 0
var end = 0 to 0
val grid = Array(input.size) { x ->
IntArray(input[0].length) { y ->
val value = when (val cell = input[x][y]) {
'S' -> {
start = x to y
'a'
}
'E' -> {
end = x to y
'z'
}
else -> cell
}
value - 'a'
}
}
return grid.search(start, end)
}
fun part2(input: List<String>): Int {
val startingPoints = mutableListOf<Pair<Int, Int>>()
var end = 0 to 0
val grid = Array(input.size) { x ->
IntArray(input[0].length) { y ->
val value = when (val cell = input[x][y]) {
'S', 'a' -> {
startingPoints.add(x to y)
'a'
}
'E' -> {
end = x to y
'z'
}
else -> cell
}
value - 'a'
}
}
return startingPoints.map { grid.search(it, end) }
.filter { it != -1 }
.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
val input = readInput("Day12")
println(part1(input))
// part 2
check(part2(testInput) == 29)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fb72806e163055c2a562702d10a19028cab43188 | 2,766 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | a2xchip | 573,197,744 | false | {"Kotlin": 37206} | private fun String.toRange(): IntRange {
val (from, to) = this.split("-").map { it.toInt() }
return from..to
}
fun toRangePairs(line: String): Pair<IntRange, IntRange> {
val (a, b) = line.split(",")
return a.toRange() to b.toRange()
}
fun fullyOverlaps(pair: Pair<IntRange, IntRange>): Boolean {
val (first, second) = pair
return first.all(second::contains) || second.all(first::contains)
}
fun partiallyOverlaps(pair: Pair<IntRange, IntRange>): Boolean {
val (first, second) = pair
return first.any(second::contains) || second.any(first::contains)
}
fun main() {
fun part1(input: List<String>): Int {
return input.map(::toRangePairs).filter(::fullyOverlaps).size
}
fun part2(input: List<String>): Int {
return input.map(::toRangePairs).filter(::partiallyOverlaps).size
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
println("Test 1 - ${part1(testInput)}")
println("Test 2 - ${part2(testInput)}")
val input = readInput("Day04")
println("Part 1 - ${part1(input)}")
println("Part 2 - ${part2(input)}")
check(part1(input) == 471)
check(part2(input) == 888)
}
| 0 | Kotlin | 0 | 2 | 19a97260db00f9e0c87cd06af515cb872d92f50b | 1,221 | kotlin-advent-of-code-22 | Apache License 2.0 |
src/year2021/14/Day14.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2021.`14`
import readInput
// region Parsing
private fun parseInput(input: List<String>): String = input.first()
private fun parseMapper(input: List<String>): Transformations {
val transformations = input.drop(2)
return transformations.associate { transformationString ->
val (left, right) = transformationString.split("->")
.map { it.trim() }
left to right
}
}
// endregion
typealias MapPairCount = MutableMap<String, Long>
typealias MapCharCount = Map<Char, Long>
typealias Transformations = Map<String, String>
private fun cycle(input: MapPairCount, transformations: Transformations): MapPairCount {
val resultMap: MapPairCount = mutableMapOf()
input.keys
.forEach { initialPair ->
if (initialPair.length != 2) error("Illegal pair : $initialPair")
val chatToSet = transformations[initialPair]
val left = initialPair.first()
val right = initialPair.last()
val leftPair = "$left$chatToSet"
val rightPair = "$chatToSet$right"
resultMap[leftPair] = resultMap.getOrDefault(leftPair, 0) + input[initialPair]!!
resultMap[rightPair] = resultMap.getOrDefault(rightPair, 0) + input[initialPair]!!
}
return resultMap
}
private fun MapPairCount.countCharCount(firstChar: Char, lastChar: Char): MapCharCount {
val map = mutableMapOf<Char, Long>()
forEach { (key, value) ->
val left = key.first()
val right = key.last()
map[left] = map.getOrDefault(left, 0) + value
map[right] = map.getOrDefault(right, 0) + value
}
map[firstChar] = map[firstChar]!! + 1
map[lastChar] = map[lastChar]!! + 1
return map
}
private fun stringToMapCount(string: String): MapPairCount {
return string.windowed(2)
.groupBy { it }
.mapValues { it.value.size.toLong() } as MapPairCount
}
private fun fastAnswer(input: List<String>, n: Int): Long {
val initLine = parseInput(input)
val transformations = parseMapper(input)
var bufRes = stringToMapCount(initLine)
repeat(n) {
bufRes = cycle(bufRes, transformations)
}
val res = bufRes.countCharCount(initLine.first(), initLine.last())
val answer = res.values.max() - res.values.min()
return answer / 2
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
val part1Test = fastAnswer(testInput, 10)
val part2Test = fastAnswer(testInput, 40)
println(part1Test.also { check(it == 1588L) })
println(part2Test.also { assert(it == 2188189693529) })
val input = readInput("Day14")
println(fastAnswer(input, 10).also { assert(it == 2188189693529) })
println(fastAnswer(input, 40).also { assert(it == 4110568157153) })
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 2,848 | KotlinAdventOfCode | Apache License 2.0 |
src/day05/day06.kt | barbulescu | 572,834,428 | false | {"Kotlin": 17042} | package day05
import readInput
import java.lang.IllegalArgumentException
fun main() {
val lines = readInput("day05/Day05")
val (stackLines, operationLines) = splitLines(lines)
val stacks = buildStacks(stackLines)
buildOperations(operationLines, stacks.size())
.forEach(stacks::operate)
println(stacks.top())
}
private data class Operation(val quantity: Int, val from: Int, val to: Int)
private fun buildOperations(operationLines: List<String>, stackSize: Int): List<Operation> = operationLines
.map { buildOperation(it) }
.onEach { require(it.from in 0 until stackSize) { "invalid operation 'from' value on $it" } }
.onEach { require(it.to in 0 until stackSize) { "invalid operation 'to' value on $it" } }
private fun buildOperation(line: String): Operation {
val matches = "move (\\d+) from (\\d+) to (\\d+)".toRegex().matchEntire(line)?.groupValues
?: throw IllegalArgumentException("Unable to parse '$line'")
return Operation(matches[1].toInt(), matches[2].toInt() - 1, matches[3].toInt() - 1)
}
private data class Stacks(private val stacks: List<ArrayDeque<String>>) {
fun size(): Int = stacks.size
fun operate(operation: Operation): Stacks {
val buffer = mutableListOf<String>()
repeat(operation.quantity) {
val value = stacks[operation.from].removeFirst()
buffer.add(value)
}
stacks[operation.to].addAll(0, buffer)
return this
}
fun top(): String = stacks.joinToString(separator = "") { it.first() }
}
private fun buildStacks(stackLines: List<String>): Stacks {
val size = stackLines.last().split(" ").size
val parsedStackLines = stackLines
.map { line -> parseStackLine(line, size) }
.dropLast(1)
val stacks = (0 until size)
.map { column ->
parsedStackLines
.map { it[column] }
.map(Char::toString)
.filter(String::isNotBlank)
}
.map(::ArrayDeque)
return Stacks(stacks)
}
private fun parseStackLine(line: String, size: Int): List<Char> {
val chars = line.toCharArray()
var index = 1
return buildList {
repeat(size) {
add(chars[index])
index += 4
}
}
}
private fun splitLines(lines: List<String>): Pair<List<String>, List<String>> {
val separatorIndex = lines.indexOf("")
val stackLines = lines.take(separatorIndex)
val operationLines = lines.drop(separatorIndex + 1)
return stackLines to operationLines
}
| 0 | Kotlin | 0 | 0 | 89bccafb91b4494bfe4d6563f190d1b789cde7a4 | 2,555 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day07/Day07.kt | skokovic | 573,361,100 | false | {"Kotlin": 12166} | package day07
import readInput
data class FileNode(val name: String, val parent: FileNode? = null, val children: MutableList<FileNode> = mutableListOf(), var size: Int = 0)
fun createFileTree(lines: List<String>): List<FileNode> {
val root = FileNode("/")
val nodes = mutableListOf(root)
var current = root
lines.drop(1).forEach {
when {
it.startsWith("$ cd") -> {
val name = it.drop(5) // "$ cd name"
current = if (name == "..") current.parent!! else current.children.find{ it.name == name}!!
}
it.startsWith("dir") -> {
val name = it.drop(4) // "dir name"
val child = FileNode(name, current)
nodes.add(child)
current.children.add(child)
}
it.first().isDigit() -> {
val size = it.split(" ").first().toInt() // "100 file.txt"
current.size += size
var parent = current.parent
while (parent != null) {
parent.size += size
parent = parent.parent
}
}
}
}
return nodes
}
fun calcSize(node: FileNode): Int {
if (node.children.isEmpty()) {
return node.size
}
node.size = node.size + node.children.map { calcSize(it) }.sum()
return node.size
}
fun main() {
fun part1(nodes: List<FileNode>): Int {
return nodes.filter { it.size <= 100000 }.sumOf { it.size }
}
fun part2(nodes: List<FileNode>): Int {
val free = 70000000 - nodes.find { it.name == "/" }!!.size // root
return nodes.filter { it.size >= 30000000 - free }.minOf { it.size }
}
val input = readInput("Day07")
val nodes = createFileTree(input)
println(part1(nodes))
println(part2(nodes))
}
| 0 | Kotlin | 0 | 0 | fa9aee3b5dd09b06bfd5c232272682ede9263970 | 1,862 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2023/Day05.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
import kotlin.math.max
import kotlin.math.min
class Day05(input: List<String>) {
private data class Map(val ranges: List<Range>) {
fun apply(input: List<LongRange>): List<LongRange> {
val rangesToMap = input.toMutableList()
// Map each source range to its destination
val mappedRanges = mutableListOf<LongRange>()
while (rangesToMap.isNotEmpty()) {
val inputRange = rangesToMap.removeFirst()
val mapping = ranges.find {
inputRange.first <= it.sourceRange.last && inputRange.last >= it.sourceRange.first
}
// No mapping? Use the original range as-is
if (mapping == null) {
mappedRanges += inputRange
continue
}
val (mapRange, offset) = mapping
// Map the overlapping part of the range
mappedRanges += (max(inputRange.first, mapRange.first) + offset)..(min(inputRange.last, mapRange.last) + offset)
// If the mapping didn't cover the entire range we'll need to map the remaining parts
if (inputRange.first < mapRange.first) {
// Mapping only covered the end of the range, so map the beginning (in a future iteration)
rangesToMap += inputRange.first until mapRange.first
}
if (inputRange.last > mapRange.last) {
// Mapping only covered the beginning of the range, so map the end (in a future iteration)
rangesToMap += (mapRange.last + 1)..inputRange.last
}
}
return mappedRanges
}
}
private data class Range(val sourceRange: LongRange, val offset: Long)
private class Chain(private val maps: List<Map>) {
fun apply(seeds: List<LongRange>) = maps.fold(seeds) { ranges, map -> map.apply(ranges) }
}
private val startingSeeds = input.first().split(": ").last().split(" ").map { it.toLong() }
private val chain = input
// Ignore the first two lines; those contain the starting seeds
.drop(2)
// Split the remaining lines into sections, each of which contains a single mapping
.chunkedBy { it.isBlank() }
// Parse each section into a Map
.map { section ->
Map(
section.drop(1).map { line ->
val (destinationStart, sourceStart, length) = line.split(" ").map { it.toLong() }
Range(LongRange(sourceStart, sourceStart + length - 1), destinationStart - sourceStart)
}
)
}
.let { maps -> Chain(maps) }
fun solvePart1() = startingSeeds
// Each seed is a single number
.map { it..it }
.let { chain.apply(it) }
.minOf { it.first }
fun solvePart2() = startingSeeds
.let {
// Every two "seeds" is actually a range
it.chunked(2).map { (start, length) -> start until start + length }
}
.let { chain.apply(it) }
.minOf { it.first }
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 3,205 | advent-2023 | MIT License |
src/main/kotlin/solutions/Day8TreetopTreeHouse.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import models.Coord2d
import utils.Collections
import utils.Input
import utils.Solution
// run only this day
fun main() {
Day8TreetopTreeHouse()
}
class Day8TreetopTreeHouse : Solution() {
init {
begin("Day 8 - Treetop Tree House")
val rows = Input.parseTo2dList<Int>(filename = "/d8_tree_topo.txt")
val cols = Collections.transposeList(rows)
val sol1 = determineVisibleTrees(rows, cols)
output("Visible Trees", sol1.size)
val sol2 = determineBestScenicScore(rows, cols, sol1)
output("Highest Scenic Score", sol2)
}
// create 'lanes' from each edge to each tree to check what's visible, return list of visible coords
private fun determineVisibleTrees(
rows: List<List<Int>>,
cols: List<List<Int>>
): Set<Coord2d> {
// start with edges, subtract corners
val width = rows[0].size
val height = rows.size
val vTrees = mutableSetOf<Coord2d>().apply {
addAll(List(rows[0].size) { i -> Coord2d(0, i) })
addAll(List(rows[height - 1].size) { i -> Coord2d(height - 1, i) })
addAll(List(cols[0].size) { i -> Coord2d(i, 0) })
addAll(List(cols[width - 1].size) { i -> Coord2d(i, width - 1) })
}
for (r in 1 until width - 1) {
for (c in 1 until height - 1)
if (isVisible(rows[r].take(c + 1)) || // from left
isVisible(rows[r].drop(c).reversed()) || // from right
isVisible(cols[c].take(r + 1)) || // from top
isVisible(cols[c].drop(r).reversed()) // from bottom
) vTrees.add(Coord2d(r, c))
}
return vTrees
}
// each 'lane' passed is from one edge until the tree being checked (tree is always last)
private fun isVisible(lane: List<Int>): Boolean =
if (lane.first() == 9) false // quickest out
else lane.last() > lane.dropLast(1).max()
// take all visible trees from part 1, do basically the same checks with different visibility logic
private fun determineBestScenicScore(
rows: List<List<Int>>,
cols: List<List<Int>>,
vTrees: Set<Coord2d>
): Int =
vTrees.mapNotNull { t ->
if (t.x == 0 || t.y == 0 || t.x == rows.size - 1 || t.y == rows[0].size - 1) null
else treesVisible(rows[t.x].take(t.y + 1).reversed()) * treesVisible(rows[t.x].drop(t.y)) *
treesVisible(cols[t.y].take(t.x + 1).reversed()) * treesVisible(cols[t.y].drop(t.x))
}.max()
// each 'lane' passed is from the tree until an edge (tree is always first),
// end conditional accounts for if a blocker was found or if the edge was hit
private fun treesVisible(lane: List<Int>): Int {
val t = lane.drop(1).takeWhile { it < lane.first() }.size
return if (t == lane.size - 1) t else t + 1
}
} | 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 2,961 | advent-of-code-2022 | MIT License |
src/Day02.kt | jordan-thirus | 573,476,470 | false | {"Kotlin": 41711} | fun main() {
fun part1(input: List<String>): Int {
val scores = buildMap {
put(OpponentPlay.ROCK,
mapOf(
Play.ROCK to Play.ROCK.score + Outcome.DRAW.score,
Play.PAPER to Play.PAPER.score + Outcome.WIN.score,
Play.SCISSORS to Play.SCISSORS.score + Outcome.LOSE.score))
put(OpponentPlay.PAPER,
mapOf(
Play.ROCK to Play.ROCK.score + Outcome.LOSE.score,
Play.PAPER to Play.PAPER.score + Outcome.DRAW.score,
Play.SCISSORS to Play.SCISSORS.score + Outcome.WIN.score))
put(OpponentPlay.SCISSORS,
mapOf(
Play.ROCK to Play.ROCK.score + Outcome.WIN.score,
Play.PAPER to Play.PAPER.score + Outcome.LOSE.score,
Play.SCISSORS to Play.SCISSORS.score + Outcome.DRAW.score))
}
fun scoreGame2(game: String): Int{
val opponentPlay = OpponentPlay.get(game[0])
val selfPlay = Play.get(game[2])
return scores.getOrDefault(opponentPlay, emptyMap()).getOrDefault(selfPlay, 0)
}
return input.sumOf { game -> scoreGame2(game) }
}
fun part2(input: List<String>): Int {
fun scoreGame(game: String): Int {
val opponentPlay = OpponentPlay.get(game[0])
val outcome = Outcome.get(game[2])
val score = when(opponentPlay) {
OpponentPlay.ROCK -> {
when(outcome) {
Outcome.WIN -> Play.PAPER.score + Outcome.WIN.score
Outcome.DRAW -> Play.ROCK.score + Outcome.DRAW.score
Outcome.LOSE -> Play.SCISSORS.score + Outcome.LOSE.score
}
}
OpponentPlay.PAPER -> {
when(outcome) {
Outcome.WIN -> Play.SCISSORS.score + Outcome.WIN.score
Outcome.DRAW -> Play.PAPER.score + Outcome.DRAW.score
Outcome.LOSE -> Play.ROCK.score + Outcome.LOSE.score
}
}
OpponentPlay.SCISSORS -> {
when(outcome) {
Outcome.WIN -> Play.ROCK.score + Outcome.WIN.score
Outcome.DRAW -> Play.SCISSORS.score + Outcome.DRAW.score
Outcome.LOSE -> Play.PAPER.score + Outcome.LOSE.score
}
}
}
//println("Game '$game' had score $score")
return score
}
return input.sumOf { game -> scoreGame(game) }
}
// 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))
}
enum class Outcome(val score:Int) {
LOSE(0),
DRAW(3),
WIN(6);
companion object {
fun get(outcome: Char) = when(outcome){
'X' -> LOSE
'Y' -> DRAW
'Z' -> WIN
else -> throw UnsupportedOperationException("Invalid outcome")
}
}
}
enum class OpponentPlay{
ROCK,
PAPER,
SCISSORS;
companion object {
fun get(play: Char) = when(play){
'A' -> ROCK
'B' -> PAPER
'C' -> SCISSORS
else -> throw UnsupportedOperationException("Invalid play")
}
}
}
enum class Play(val score: Int){
ROCK(1),
PAPER(2),
SCISSORS(3);
companion object {
fun get(play: Char) = when(play){
'X' -> ROCK
'Y' -> PAPER
'Z' -> SCISSORS
else -> throw UnsupportedOperationException("Invalid play")
}
}
} | 0 | Kotlin | 0 | 0 | 59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e | 3,899 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | fun main() {
fun part1(input: List<String>): Int {
return HeightsGrid.parse(input).countMinStepsFromS()
}
fun part2(input: List<String>): Int {
return HeightsGrid.parse(input).countMinStepsFromA()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput).also { println("part1 test: $it") } == 31)
check(part2(testInput).also { println("part2 test: $it") } == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
private class HeightsGrid(
val heights: Array<Array<Int>>,
val startPoint: Pair<Int, Int>,
val finishPoint: Pair<Int, Int>,
) {
private val rows: Int by lazy { heights.size }
private val columns: Int by lazy { heights[0].size }
private operator fun Array<Array<Int>>.get(point: Pair<Int, Int>) = heights[point.first][point.second]
fun countMinStepsFromS(): Int {
val visited = countSteps()
return visited.getValue(startPoint)
}
fun countMinStepsFromA(): Int {
val visited = countSteps()
return visited.filter { heights[it.key] == 0 }.minOf { it.value }
}
private fun countSteps(): Map<Pair<Int, Int>, Int> {
val visited = mutableMapOf<Pair<Int, Int>, Int>()
val toVisit = ArrayDeque<Pair<Int, Int>>()
fun addToVisit(point: Pair<Int, Int>, steps: Int) {
if (!visited.containsKey(point)) {
visited[point] = steps
toVisit.add(point)
}
}
fun visit(i: Int, j: Int, height: Int, steps: Int) {
val point = Pair(i, j)
if (i < 0 || i == rows || j < 0 || j == columns || visited.contains(point)) return
if (height <= heights[point] + 1) {
addToVisit(point, steps)
}
}
addToVisit(finishPoint, 0)
while (toVisit.isNotEmpty()) {
val point = toVisit.removeFirst()
val steps = requireNotNull(visited[point]) + 1
val height = heights[point]
visit(point.first, point.second + 1, height, steps)
visit(point.first, point.second - 1, height, steps)
visit(point.first - 1, point.second, height, steps)
visit(point.first + 1, point.second, height, steps)
}
return visited
}
companion object {
fun parse(input: List<String>): HeightsGrid {
lateinit var finishPoint: Pair<Int, Int>
lateinit var startPoint: Pair<Int, Int>
val points = Array(input.size) { i ->
Array(input[i].length) { j ->
when (val c = input[i][j]) {
'S' -> {
startPoint = Pair(i, j)
'a' - 'a'
}
'E' -> {
finishPoint = Pair(i, j)
'z' - 'a'
}
else -> c - 'a'
}
}
}
return HeightsGrid(points, startPoint, finishPoint)
}
}
}
| 0 | Kotlin | 0 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 3,207 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | lonskiTomasz | 573,032,074 | false | {"Kotlin": 22055} | fun main() {
/**
* The ASCII value of lowercase alphabets are from 97 to 122. 'a' (97) to 'z' (122)
* And, the ASCII value of uppercase alphabets are from 65 to 90. 'A' (65) to 'Z' (90)
*
* Lowercase item types a through z have priorities 1 through 26.
* Uppercase item types A through Z have priorities 27 through 52.
*
* Formula: ASCII - x = priority
* For lowercase: ASCII - 96 = priority, e.g.: 'a' = 1, 97 - 96 = 1
* For uppercase: ASCII - 38 = priority, e.g.: 'A' = 27, 65 - 38 = 27
*/
fun Char.toPriority(): Int {
return when {
isLowerCase() -> code - 96
isUpperCase() -> code - 38
else -> 0
}
}
fun sumOfPrioritiesOfEachRucksack(input: List<String>): Int = input.sumOf { rucksack ->
val mid: Int = rucksack.length / 2
rucksack.substring(0, mid).toSet()
.intersect(rucksack.substring(mid).toSet())
.sumOf { it.toPriority() }
}
fun sumOfPrioritiesOfBadges(input: List<String>): Int {
val groups = input.map { it.toSet() }.chunked(3)
return groups.sumOf { group ->
val commonPart = group[0].intersect(group[1]).intersect(group[2])
commonPart.sumOf { it.toPriority() }
}
}
val inputTest = readInput("day03/input_test")
val input = readInput("day03/input")
println(sumOfPrioritiesOfEachRucksack(inputTest))
println(sumOfPrioritiesOfEachRucksack(input))
println(sumOfPrioritiesOfBadges(inputTest))
println(sumOfPrioritiesOfBadges(input))
}
/**
* 157
* 8139
* 70
* 2668
*/ | 0 | Kotlin | 0 | 0 | 9e758788759515049df48fb4b0bced424fb87a30 | 1,627 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/Day15.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day15
import geometry.Position
import geometry.manhattenDistance
import geometry.x
import geometry.y
import utils.readInput
import kotlin.math.absoluteValue
data class Sensor(val position: Position, val beacon: Position) {
private val radius = beacon.manhattenDistance(position)
fun slice(y: Int): IntRange? {
val halfWidth = radius - (y - position.y).absoluteValue
return if (halfWidth >= 0) position.x - halfWidth..position.x + halfWidth else null
}
}
fun String.toSensor(): Sensor {
val (xS, yS, xB, yB) =
"Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)"
.toRegex()
.matchEntire(this)
?.groupValues
?.drop(1)
?.map(String::toInt)
?: error("Invalid sensor: $this")
return Sensor(xS to yS, xB to yB)
}
fun List<Sensor>.covered(y: Int): Int = (detected(y) - beacons(y)).size
private fun List<Sensor>.detected(y: Int) =
mapNotNull { it.slice(y)?.toSet() }.reduce(Set<Int>::union)
private fun List<Sensor>.beacons(y: Int) =
map { it.beacon }.filter { it.y == y }.map { it.x }.toSet()
fun part1(filename: String): Int = covered(filename, 2000000)
fun covered(filename: String, y: Int) = readInput(filename).map(String::toSensor).covered(y)
private fun List<Sensor>.findMissingBeacon(range: IntRange): Position? {
for (y in range) {
val slices =
mapNotNull { it.slice(y) }.sortedWith(compareBy(IntRange::first, IntRange::last))
var candidate = range.first
for (slice in slices) {
if (candidate in slice) {
candidate = slice.last + 1
}
if (candidate > range.last) break
}
if (candidate in range) return candidate to y
}
return null
}
private fun Position.tuningFrequency(): Long = x.toLong() * 4000000L + y.toLong()
fun part2(filename: String): Long = findMissingBeaconFrequency(filename, 0..4000000)
fun findMissingBeaconFrequency(filename: String, range: IntRange) =
readInput(filename).map(String::toSensor).findMissingBeacon(range)?.tuningFrequency()
?: error("No missing beacon found")
private const val filename = "Day15"
fun main() {
println(part1(filename))
println(part2(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 2,304 | aoc-2022 | Apache License 2.0 |
src/main/Day22.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day22
import geometry.Direction
import geometry.Position
import geometry.x
import geometry.y
import utils.readInput
enum class Tile {
OPEN,
WALL
}
typealias Board = Map<Position, Tile>
fun Iterable<String>.readBoard(): Board =
withIndex()
.flatMap { (i, row) ->
row.withIndex().map { (j, column) ->
when (column) {
'.' -> j to i to Tile.OPEN
'#' -> j to i to Tile.WALL
else -> null
}
}
}
.filterNotNull()
.toMap()
sealed interface Instruction {
object TurnLeft : Instruction
object TurnRight : Instruction
data class Move(val steps: Int) : Instruction
}
fun String.readInstructions(): Sequence<Instruction> =
"""\d+|R|L""".toRegex().findAll(this).map {
when (it.value) {
"R" -> Instruction.TurnRight
"L" -> Instruction.TurnLeft
else -> Instruction.Move(it.value.toInt())
}
}
data class State(val position: Position, val facing: Direction) {
fun turnRight(): State =
copy(
facing =
when (facing) {
Direction.Right -> Direction.Down
Direction.Down -> Direction.Left
Direction.Left -> Direction.Up
Direction.Up -> Direction.Right
}
)
fun turnLeft(): State =
copy(
facing =
when (facing) {
Direction.Right -> Direction.Up
Direction.Down -> Direction.Right
Direction.Left -> Direction.Down
Direction.Up -> Direction.Left
}
)
fun Board.move(steps: Int): State {
var position = position
for (i in 1..steps) {
val next = position.next()
position =
when (this[next]) {
Tile.WALL -> break
Tile.OPEN -> next
null -> wrap(position)
}
}
return copy(position = position)
}
val password = (position.y + 1) * 1000 + (position.x + 1) * 4 + facing.ordinal
private fun Board.wrap(position: Position): Position =
with(position) {
when (facing) {
Direction.Right -> row(y).minOf { it.x } to y
Direction.Down -> x to column(x).minOf { it.y }
Direction.Left -> row(y).maxOf { it.x } to y
Direction.Up -> x to column(x).maxOf { it.y }
}.takeIf { this@wrap[it] == Tile.OPEN }
?: position
}
private fun Position.next(): Position =
when (facing) {
Direction.Right -> x + 1 to y
Direction.Down -> x to y + 1
Direction.Left -> x - 1 to y
Direction.Up -> x to y - 1
}
}
fun Board.trace(instructions: Sequence<Instruction>): Sequence<State> =
instructions.scan(start()) { state, instruction ->
with(state) {
when (instruction) {
Instruction.TurnLeft -> turnLeft()
Instruction.TurnRight -> turnRight()
is Instruction.Move -> move(instruction.steps)
}
}
}
private fun Board.start() = State(row(0).minOf { it.x } to 0, Direction.Right)
private fun Board.row(y: Int) = keys.filter { it.y == y }
private fun Board.column(x: Int) = keys.filter { it.x == x }
private const val filename = "Day22"
fun part1(filename: String): Int {
val input = readInput(filename)
val board = input.takeWhile { it.isNotBlank() }.readBoard()
return board.trace(input.last().readInstructions()).last().password
}
fun main() {
println(part1(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 3,807 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | mcdimus | 572,064,601 | false | {"Kotlin": 32343} | import util.readInput
fun main() {
fun part1(input: List<String>): Long {
val root = parse(input)
return root.findRecursiveFoldersNotLargerThan(100000).sumOf(Node.Folder::getSize)
}
fun part2(input: List<String>): Long {
val root = parse(input)
val needToFree = root.getSize() - 40000000
return root.getRecursiveFolders()
.map(Node.Folder::getSize)
.filter { it > needToFree }
.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private fun parse(input: List<String>): Node.Folder {
val root = Node.Folder(name = "/", parent = null, children = mutableListOf())
var currentDir: Node.Folder = root
for (command in input.drop(1)) {
when {
command == "$ cd /" -> {
currentDir = root
continue
}
command == "$ cd .." -> {
currentDir = currentDir.parent ?: throw IllegalStateException("no parent")
continue
}
command.startsWith("$ cd ") -> {
val folderName = command.replace("$ cd ", "")
currentDir = currentDir.findDirectFolderByName(folderName)
continue
}
command.startsWith("$ ls") -> continue
command.startsWith("dir") -> {
val folderName = command.replace("dir ", "")
if (currentDir.children.none { it.name == folderName }) {
currentDir.children.add(
Node.Folder(name = folderName, parent = currentDir)
)
}
continue
}
!command.startsWith("$") && !command.startsWith("dir") -> {
val split = command.split(' ')
val fileSize = split[0]
val fileName = split[1]
if (currentDir.children.none { it.name == fileName }) {
currentDir.children.add(
Node.File(name = fileName, parent = currentDir, size = fileSize.toLong())
)
}
}
}
}
return root
}
sealed class Node(
open val name: String,
open val parent: Folder?
) {
data class File(
override val name: String,
override val parent: Folder?,
val size: Long
) : Node(name, parent) {
override fun toString() = "$size $name"
}
data class Folder(
override val name: String,
override val parent: Folder? = null,
val children: MutableList<Node> = mutableListOf()
) : Node(name, parent) {
private val _size: Long by lazy {
children.filterIsInstance<File>().sumOf { it.size } +
children.filterIsInstance<Folder>().sumOf { it.getSize() }
}
fun getSize() = _size
fun findRecursiveFoldersNotLargerThan(limit: Long): List<Folder> {
val folders = children.filterIsInstance<Folder>()
return folders.filter { it.getSize() < limit } +
folders.flatMap { it.findRecursiveFoldersNotLargerThan(limit) }
}
fun getRecursiveFolders(): List<Folder> {
val folders = children.filterIsInstance<Folder>()
return folders + folders.flatMap { it.getRecursiveFolders() }
}
fun findDirectFolderByName(name: String) =
children.filterIsInstance<Folder>().singleOrNull { it.name == name }
?: throw IllegalArgumentException("folder '$name' not found")
override fun toString() = "dir $name"
}
}
| 0 | Kotlin | 0 | 0 | dfa9cfda6626b0ee65014db73a388748b2319ed1 | 3,890 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | Miguel1235 | 726,260,839 | false | {"Kotlin": 21105} | private class Card(val id: Int, val winningNumbers: List<Int>, val ownNumbers: List<Int>) {
val ownWinnerNumbers = winningNumbers.filter { w -> ownNumbers.contains(w) }
val points = calculatePoints(ownWinnerNumbers.size)
private fun calculatePoints(size: Int): Int {
if (size <= 2) return size
return 2 * calculatePoints(size - 1)
}
fun calculateCopies(cards: List<Card>): Int {
var copies = 0
val stack: List<Card> = mutableListOf(this)
while (stack.isNotEmpty()) {
copies++
val card = stack.removeLast()
val copies2Make = card.ownWinnerNumbers.size
for (i in card.id + 1..card.id + copies2Make) {
stack.addLast(cards[i - 1])
}
}
return copies
}
}
private val obtainNumbers = { input: String -> input.trim().replace(Regex("\\s+"), " ").split(" ").map { it.toInt() } }
private fun createCards(input: List<String>): List<Card> {
val cardRegex = Regex("""(\d+): ([\d\s]+) \| ([\d\s]+)""")
val cards: MutableList<Card> = mutableListOf()
for (line in input) {
val results = cardRegex.findAll(line)
for (r in results) {
val g = r.groupValues
cards.add(Card(g[1].toInt(), obtainNumbers(g[2]), obtainNumbers(g[3])))
}
}
return cards
}
private val part1 = { cards: List<Card> -> cards.fold(0) { acc, card -> acc + card.points } }
private val part2 = { cards: List<Card> -> cards.fold(0) { acc, card -> acc + card.calculateCopies(cards) } }
fun main() {
val inputTest = readInput("Day04_test")
val cardsTest = createCards(inputTest)
check(part1(cardsTest) == 13)
check(part2(cardsTest) == 30)
val input = readInput("Day04")
val cards = createCards(input)
check(part1(cards) == 28538)
check(part2(cards) == 9425061)
} | 0 | Kotlin | 0 | 0 | 69a80acdc8d7ba072e4789044ec2d84f84500e00 | 1,870 | advent-of-code-2023 | MIT License |
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day05.kt | loehnertz | 573,145,141 | false | {"Kotlin": 53239} | package codes.jakob.aoc
import codes.jakob.aoc.shared.*
import java.util.*
class Day05 : Solution() {
override fun solvePart1(input: String): Any {
val (stacksById: Map<CrateStack, Stack<Crate>>, instructions: List<Instruction>) = parseInput(input)
for (instruction: Instruction in instructions) {
val from: Stack<Crate> = stacksById[instruction.from]!!
val to: Stack<Crate> = stacksById[instruction.to]!!
repeat(instruction.amount) { to.add(from.pop()) }
}
return stacksById.values.map { it.pop().id }.joinToString("")
}
override fun solvePart2(input: String): Any {
val (stacksById: Map<CrateStack, Stack<Crate>>, instructions: List<Instruction>) = parseInput(input)
for (instruction: Instruction in instructions) {
val from: Stack<Crate> = stacksById[instruction.from]!!
val to: Stack<Crate> = stacksById[instruction.to]!!
(0 until instruction.amount).map { from.pop() }.asReversed().forEach(to::add)
}
return stacksById.values.map { it.pop().id }.joinToString("")
}
private fun parseInput(input: String): Pair<Map<CrateStack, Stack<Crate>>, List<Instruction>> {
return input
.split("\n\n")
.toPair()
.map(this::parseStacks, this::parseInstructions)
}
private fun parseStacks(state: String): Map<CrateStack, Stack<Crate>> {
return state
.splitMultiline()
.map { it.splitByEach().splitEvery(3) }
.transpose()
.filter { it.last().isDigit() }
.groupBy { CrateStack(it.last().toString().toInt()) }
.mapValues { (_, crates) ->
crates
.first()
.filterNot { it.isWhitespace() }
.dropLast(1)
.map { Crate(it) }
}
.mapValues { (_, crates) ->
Stack<Crate>().also { crates.asReversed().forEach(it::add) }
}
}
private fun parseInstructions(instructions: String): List<Instruction> {
return instructions
.splitMultiline()
.mapNotNull { INSTRUCTION_REGEX.find(it)?.groupValues }
.map { match ->
Instruction(
match[1].toInt(),
CrateStack(match[2].toInt()),
CrateStack(match[3].toInt()),
)
}
}
data class Instruction(
val amount: Int,
val from: CrateStack,
val to: CrateStack,
)
@JvmInline
value class CrateStack(
val id: Int
)
@JvmInline
value class Crate(
val id: Char
)
companion object {
private val INSTRUCTION_REGEX: Regex = Regex("move\\s(\\d+)\\sfrom\\s(\\d+)\\sto\\s(\\d+)")
}
}
fun main() = Day05().solve()
| 0 | Kotlin | 0 | 0 | ddad8456dc697c0ca67255a26c34c1a004ac5039 | 2,903 | advent-of-code-2022 | MIT License |
app/src/main/kotlin/codes/jakob/aoc/solution/Day03.kt | loehnertz | 725,944,961 | false | {"Kotlin": 59236} | package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.*
object Day03 : Solution() {
private val symbolPattern = Regex("[^.\\d]")
private val gearPattern = Regex("\\*")
override fun solvePart1(input: String): Any {
return input
.parseGrid { it }
.cells
.asSequence()
// Filter out all cells that are not a digit
.filter { cell -> cell.content.value.isDigit() }
// Filter out all cells that are not adjacent to a symbol
.filter { cell ->
cell.getAdjacent(diagonally = true).any { adjacent ->
symbolPattern.matches(adjacent.content.value.toString())
}
}
// Map each cell to the starting cell of the number it belongs to (e.g., 987 -> 9)
.map { cell -> findStartingCell(cell) }
// Filter out all duplicate starting cells
.distinct()
// Build the numbers from the starting cells
.map { startingCell -> buildNumberFromStartingCell(startingCell) }
// Sum up the numbers
.sum()
}
override fun solvePart2(input: String): Any {
return input
.parseGrid { it }
.cells
// Filter out all cells that are not a digit
.filter { cell -> cell.content.value.isDigit() }
// Associate each cell with all adjacent cells that are gears
.associateWith { cell ->
cell.getAdjacent(diagonally = true).filter { adjacent ->
gearPattern.matches(adjacent.content.value.toString())
}.toSet()
}
// Associate each cell with the starting cell of the number it belongs to (e.g., 987 -> 9)
// As the result is a hash map, the number cells are grouped by their starting cell
.mapKeysMergingValues(
{ cell, _ -> findStartingCell(cell) },
{ accumulator, adjacentsGears ->
setOf(*accumulator.toTypedArray(), *adjacentsGears.toTypedArray())
}
)
// Only retain the cells that have an adjacent gear
.filterValues { gears -> gears.isNotEmpty() }
// Only retain the first gear (as there cannot be more than one gear adjacent to a part number)
.mapValues { (_, gears) -> gears.first() }
// Group the part numbers by their adjacent gear cell
.entries
.groupBy(
{ (_, gears) -> gears },
{ (partNumber, _) -> partNumber }
)
// Only retain the gears that are adjacent to exactly two part numbers
.filterValues { partNumbers -> partNumbers.size == 2 }
// Build the part numbers from the starting cells
.mapValues { (_, startingCells) ->
startingCells.map { buildNumberFromStartingCell(it) }
}
// Multiply the part numbers and sum them up
.mapValues { (_, partNumbers) -> partNumbers.multiply() }
.values
.sum()
}
/**
* Finds the starting cell of a number by going west until the next cell is not a digit anymore.
*/
private fun findStartingCell(cell: Grid.Cell<Char>): Grid.Cell<Char> {
tailrec fun findStartingCell(currentCell: Grid.Cell<Char>): Grid.Cell<Char> {
val adjacentWest: Grid.Cell<Char>? = currentCell.getInDirection(ExpandedDirection.WEST)
return if (adjacentWest?.content?.value?.isDigit() == true) {
findStartingCell(adjacentWest)
} else currentCell
}
return findStartingCell(cell)
}
/**
* Builds a number from a starting cell by going east until the next cell is not a digit anymore.
*/
private fun buildNumberFromStartingCell(cell: Grid.Cell<Char>): Int {
val partNumberCells: MutableList<Grid.Cell<Char>> = mutableListOf(cell)
tailrec fun addNextDigitCell(currentCell: Grid.Cell<Char>?) {
if (currentCell?.content?.value?.isDigit() == true) {
partNumberCells.add(currentCell)
addNextDigitCell(currentCell.getInDirection(ExpandedDirection.EAST))
}
}
addNextDigitCell(cell.getInDirection(ExpandedDirection.EAST))
require(partNumberCells.all { it.content.value.isDigit() }) { "The part number cells must all be digits." }
return partNumberCells.joinToString("") { it.content.value.toString() }.toInt()
}
}
fun main() {
Day03.solve()
}
| 0 | Kotlin | 0 | 0 | 6f2bd7bdfc9719fda6432dd172bc53dce049730a | 4,632 | advent-of-code-2023 | MIT License |
src/Day02.kt | devheitt | 573,207,407 | false | {"Kotlin": 11944} | enum class Options(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
companion object {
private val winConditions = mapOf(
Pair(ROCK, PAPER),
Pair(SCISSORS, ROCK),
Pair(PAPER, SCISSORS)
)
private val loseConditions = mapOf(
Pair(PAPER, ROCK),
Pair(ROCK, SCISSORS),
Pair(SCISSORS, PAPER)
)
fun getOption(input: String): Options {
return when (input) {
in listOf("A", "X") -> ROCK
in listOf("B", "Y") -> PAPER
else -> SCISSORS
}
}
fun getOptionWithCondition(opponent: Options, condition: String): Options {
//X = lose, Y = draw, and Z = win
return when (condition) {
"Y" -> opponent
"Z" -> winConditions[opponent]!!
else -> loseConditions[opponent]!!
}
}
}
}
fun main() {
fun calculateRoundResult(myOption: Options, opponent: Options): Int {
val score = myOption.score
return if (myOption == opponent) {
score + 3
} else if (myOption == Options.PAPER && opponent == Options.ROCK
|| myOption == Options.ROCK && opponent == Options.SCISSORS
|| myOption == Options.SCISSORS && opponent == Options.PAPER
) {
score + 6
} else {
score
}
}
fun part1(input: List<String>): Int {
var totalScore = 0
for (round in input) {
val (opponentOption, myOption) = round.split(" ").map { Options.getOption(it) }
totalScore += calculateRoundResult(myOption, opponentOption)
}
return totalScore
}
fun part2(input: List<String>): Int {
var totalScore = 0
for (round in input) {
val (opponentInput, condition) = round.split(" ").take(2)
val opponentOption = Options.getOption(opponentInput)
val myOption = Options.getOptionWithCondition(opponentOption, condition)
totalScore += calculateRoundResult(myOption, opponentOption)
}
return totalScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a9026a0253716d36294709a547eaddffc6387261 | 2,478 | advent-of-code-2022-kotlin | Apache License 2.0 |
2021/src/day08/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day08
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(lines: Input): Int {
return lines.sumOf { entry ->
val (_, reading) = entry.split("|")
reading.split(" ")
.filter { it.isNotBlank() }
.count { it.length in setOf(2, 3, 4, 7) }
}
}
fun part2(lines: Input): Int {
fun String.normalize() = String(this.toCharArray().sortedArray())
fun decode(digits: List<String>): Array<String> {
val map = arrayOfNulls<String>(10)
map[1] = digits.find { it.length == 2 }
map[7] = digits.find { it.length == 3 }
map[4] = digits.find { it.length == 4 }
map[8] = digits.find { it.length == 7 }
val zeroSixOrNine = digits.filter { it.length == 6 }
check(zeroSixOrNine.size == 3)
map[6] = zeroSixOrNine.find { !it.toSet().containsAll(map[1]!!.toSet()) }
map[9] = zeroSixOrNine.find { it.toSet().containsAll(map[4]!!.toSet()) }
map[0] = zeroSixOrNine.find { it != map[6] && it != map[9] }
val twoThreeOrFive = digits.filter { it.length == 5 }
check(twoThreeOrFive.size == 3)
map[3] = twoThreeOrFive.find { it.toSet().containsAll(map[1]!!.toSet()) }
map[5] = twoThreeOrFive.find { map[6]!!.toSet().containsAll(it.toSet()) }
map[2] = twoThreeOrFive.find { it != map[3] && it != map[5] }
return map.requireNoNulls()
}
return lines.sumOf { entry ->
val (digits, number) = entry.split("|")
val map = decode(digits.split(" ").filter { it.isNotBlank() }.map { it.normalize() })
number.split(" ")
.filter { it.isNotBlank() }
.map { it.normalize() }
.map { map.indexOf(it) }
.fold(0) { acc, i -> acc * 10 + i } as Int
}
}
check(part1(readInput("test-input.txt")) == 26)
check(part2(readInput("test-input.txt")) == 61229)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day08/$s")).readLines()
}
private typealias Input = List<String> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 2,091 | advent-of-code | Apache License 2.0 |
2022/Day19/problems.kt | moozzyk | 317,429,068 | false | {"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794} | import java.io.File
import kotlin.math.*
data class Resources(val ore: Int, val clay: Int, val obsidian: Int) {
operator fun plus(r: Resources): Resources {
return Resources(ore + r.ore, clay + r.clay, obsidian + r.obsidian)
}
operator fun minus(r: Resources): Resources {
return Resources(ore - r.ore, clay - r.clay, obsidian - r.obsidian)
}
operator fun times(m: Int): Resources {
return Resources(ore * m, clay * m, obsidian * m)
}
}
typealias Cost = Resources
data class Blueprint(
val id: Int,
val oreRobotCost: Cost,
val clayRobotCost: Cost,
val obsidianRobotCost: Cost,
val geodeRobotCost: Cost
)
data class Robots(
val oreRobots: Int,
val clayRobots: Int,
val obsidianRobots: Int,
val geodeRobots: Int
) {
operator fun plus(r: Robots): Robots {
return Robots(
oreRobots + r.oreRobots,
clayRobots + r.clayRobots,
obsidianRobots + r.obsidianRobots,
geodeRobots + r.geodeRobots
)
}
fun mine(): Resources {
return Resources(oreRobots, clayRobots, obsidianRobots)
}
}
class Factory(var blueprint: Blueprint) {}
fun main(args: Array<String>) {
val lines = File(args[0]).readLines()
val blueprints = createBlueprints(lines)
println(problem1(blueprints))
println(problem2(blueprints))
}
fun createBlueprints(lines: List<String>): List<Blueprint> {
val 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.""".toRegex()
return lines.map { regex.matchEntire(it)!!.destructured }.map {
(
id: String,
oreRobotOreCost: String,
clayRobotOreCost: String,
obsidianRobotOreCost: String,
obsidianRobotClayCost: String,
geodeRobotOreCost: String,
geodeRobotObsidianCost: String) ->
Blueprint(
id.toInt(),
oreRobotCost = Cost(ore = oreRobotOreCost.toInt(), clay = 0, obsidian = 0),
clayRobotCost = Cost(ore = clayRobotOreCost.toInt(), clay = 0, obsidian = 0),
obsidianRobotCost =
Cost(
ore = obsidianRobotOreCost.toInt(),
clay = obsidianRobotClayCost.toInt(),
obsidian = 0
),
geodeRobotCost =
Cost(
ore = geodeRobotOreCost.toInt(),
clay = 0,
obsidian = geodeRobotObsidianCost.toInt()
)
)
}
}
fun problem1(blueprints: List<Blueprint>): Int {
return solve(blueprints, 24).map { (blueprint, result) -> blueprint.id * result }.sum()
}
fun problem2(blueprints: List<Blueprint>): Int {
return solve(blueprints.take(3), 32).map { it.second }.reduce { a, v -> a * v }
}
fun solve(blueprints: List<Blueprint>, timeLimit: Int): List<Pair<Blueprint, Int>> {
var results =
blueprints.map {
Pair(it, executeBlueprint(it, 1, Robots(1, 0, 0, 0), Resources(0, 0, 0), timeLimit))
}
return results
}
fun executeBlueprint(
blueprint: Blueprint,
minute: Int,
robots: Robots,
resources: Resources,
timeLimit: Int
): Int {
var geodes = robots.geodeRobots
if (minute == timeLimit) {
return geodes
}
// Cut some branches
if (resources.ore > 10 || resources.clay > 100 || resources.obsidian > 30) {
return -1
}
val purchaseOptions = robotPurchaseOptions(blueprint, resources)
var maxDescGeodes = 0
for (p in purchaseOptions) {
val cost = robotCost(p, blueprint)
val descGeodes =
executeBlueprint(
blueprint,
minute + 1,
robots + p,
resources + robots.mine() - cost,
timeLimit,
)
maxDescGeodes = max(descGeodes, maxDescGeodes)
}
return geodes + maxDescGeodes
}
fun robotPurchaseOptions(blueprint: Blueprint, resources: Resources): List<Robots> {
if (canBuy(resources, blueprint.geodeRobotCost)) {
return listOf(Robots(0, 0, 0, 1))
}
if (canBuy(resources, blueprint.obsidianRobotCost)) {
// Heurestics to avoid too many turns without buying any robot
if (resources.ore > 6) {
return listOf(Robots(0, 0, 1, 0), Robots(0, 1, 0, 0))
}
return listOf(Robots(0, 0, 1, 0), Robots(0, 1, 0, 0), Robots(0, 0, 0, 0))
}
if (canBuy(resources, blueprint.clayRobotCost) && canBuy(resources, blueprint.oreRobotCost)) {
// Heurestics to avoid too many turns without buying any robot
if (resources.ore > 6) {
return listOf(Robots(1, 0, 0, 0), Robots(0, 1, 0, 0))
}
return listOf(Robots(1, 0, 0, 0), Robots(0, 1, 0, 0), Robots(0, 0, 0, 0))
}
if (canBuy(resources, blueprint.clayRobotCost)) {
return listOf(Robots(0, 1, 0, 0), Robots(0, 0, 0, 0))
}
if (canBuy(resources, blueprint.oreRobotCost)) {
return listOf(Robots(1, 0, 0, 0), Robots(0, 0, 0, 0))
}
return listOf(Robots(0, 0, 0, 0))
}
fun robotCost(robots: Robots, blueprint: Blueprint): Cost {
return blueprint.oreRobotCost * robots.oreRobots +
blueprint.clayRobotCost * robots.clayRobots +
blueprint.obsidianRobotCost * robots.obsidianRobots +
blueprint.geodeRobotCost * robots.geodeRobots
}
fun canBuy(resources: Resources, cost: Cost): Boolean {
return cost.ore <= resources.ore &&
cost.clay <= resources.clay &&
cost.obsidian <= resources.obsidian
}
| 0 | Rust | 0 | 0 | c265f4c0bddb0357fe90b6a9e6abdc3bee59f585 | 6,076 | AdventOfCode | MIT License |
src/main/kotlin/solutions/day16/Day16.kt | Dr-Horv | 570,666,285 | false | {"Kotlin": 115643} | package solutions.day16
import solutions.Solver
import utils.searchBreathFirst
data class Valve(val name: String, val flowRate: Int, val neighbourValves: MutableList<Valve>) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Valve
return name == other.name
}
override fun hashCode(): Int = name.hashCode()
}
data class Node(
val position: String,
val minute: Int,
val openValves: Set<String>,
val totalFlowRate: Int,
val released: Int
)
class Day16 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val valves = mutableMapOf<String, Valve>()
val connectionMap = mutableMapOf<String, List<String>>()
val regex = "Valve (.*) has flow rate=(\\d*); tunnels? leads? to valves? (.*)".toRegex()
val start = Node(position = "AA", minute = 0, openValves = emptySet(), totalFlowRate = 0, released = 0)
for (line in input) {
val result = regex.find(line)
if (result != null) {
val (name, flowRateStr, neighbourNames) = result.destructured
val valve = Valve(name = name, flowRate = flowRateStr.toInt(), neighbourValves = mutableListOf())
valves[name] = valve
connectionMap[name] = neighbourNames.split(",").map { it.trim() }
}
}
connectionMap.forEach { (name, neighbourNames) ->
val v = valves.getValue(name)
val neighbours = neighbourNames.map { valves.getValue(it) }
v.neighbourValves.addAll(neighbours)
}
val distances = mutableMapOf<Pair<String, String>, Int>()
valves.values.forEach { n1 ->
valves.values.forEach { n2 ->
if (n1.name != n2.name) {
val path = searchBreathFirst(n1, { n -> n.neighbourValves }, { n -> n.name == n2.name })
distances[Pair(n1.name, n2.name)] = path!!.size - 1
} else {
distances[Pair(n1.name, n2.name)] = 0
}
}
}
val paths = mutableListOf<List<Node>>()
val timeLimit = if (!partTwo) {
30
} else {
26
}
println("Find path time")
findPaths(listOf(start), paths, distances, valves.values.filter { it.flowRate > 0 }.toSet(), timeLimit)
println("Paths found: ${paths.size}")
if (!partTwo) {
val max = paths.maxBy { it.last().released }
println(max)
return max.last().released.toString()
} else {
val pairs = mutableListOf<Pair<Node, Node>>()
var currMax = -1
for ((index, p1) in paths.withIndex()) {
for (i2 in (index + 1) until paths.size) {
val n1 = p1.last()
val n2 = paths[i2].last()
if (n1.released + n2.released < currMax) {
continue
}
if (n1.openValves.none { n2.openValves.contains(it) }) {
currMax = n1.released + n2.released
pairs.add(Pair(n1, n2))
}
}
}
println("Pairs: " + pairs.size)
val best = pairs.maxBy { it.first.released + it.second.released }
return (best.first.released + best.second.released).toString()
}
}
private fun findPaths(
currPath: List<Node>,
paths: MutableList<List<Node>>,
distances: Map<Pair<String, String>, Int>,
closedVales: Set<Valve>,
timeLimit: Int
) {
val n = currPath.last()
val timeLeft = timeLimit - n.minute
if (timeLeft == 0) {
paths.add(currPath)
return
}
val nextNodeWaiting = n.copy(minute = timeLimit, released = n.released + (n.totalFlowRate * timeLeft))
findPaths(currPath + nextNodeWaiting, paths, distances, closedVales, timeLimit)
for (valve in closedVales) {
val dist = distances.getValue(Pair(n.position, valve.name))
val timeToMoveAndOpen = dist + 1
if (timeLeft > timeToMoveAndOpen) {
val openedValve = Node(
position = valve.name,
minute = n.minute + timeToMoveAndOpen,
openValves = n.openValves + valve.name,
totalFlowRate = n.totalFlowRate + valve.flowRate,
released = n.released + (timeToMoveAndOpen * n.totalFlowRate)
)
findPaths(currPath + openedValve, paths, distances, closedVales - valve, timeLimit)
}
}
}
}
| 0 | Kotlin | 0 | 2 | 6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e | 4,843 | Advent-of-Code-2022 | MIT License |
aoc21/day_19/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
import kotlin.math.abs
enum class Axe {
X, Y, Z;
companion object {
fun allRotations(): List<List<Axe>> = listOf(
// facing
listOf(), // x
listOf(Axe.Y, Axe.Y), // -x
listOf(Axe.Z), // y
listOf(Axe.Z, Axe.Z, Axe.Z), // -y
listOf(Axe.Y), // z
listOf(Axe.Y, Axe.Y, Axe.Y), // -z
).flatMap { rot ->
listOf(
// try all rotations of that facing
rot,
rot + listOf(Axe.X),
rot + listOf(Axe.X, Axe.X),
rot + listOf(Axe.X, Axe.X, Axe.X)
)
}
}
}
data class Pos(val x: Int, val y: Int, val z: Int) {
fun shift(rel: Pos): Pos = Pos(x + rel.x, y + rel.y, z + rel.z)
fun rotate(axe: Axe): Pos = when (axe) {
Axe.X -> Pos(x, z, -y)
Axe.Y -> Pos(-z, y, x)
Axe.Z -> Pos(y, -x, z)
}
fun rotate(axes: List<Axe>): Pos = axes.fold(this) { pos, axe -> pos.rotate(axe) }
fun transform(t: Transform): Pos = rotate(t.rotation).shift(t.shift)
fun transform(ts: List<Transform>): Pos = ts.fold(this) { pos, t -> pos.transform(t) }
fun dist(other: Pos): Int = abs(x - other.x) + abs(y - other.y) + abs(z - other.z)
}
data class Transform(val rotation: List<Axe>, val shift: Pos)
class Scanner(val beacons: List<Pos>) {
var transforms = listOf(Transform(listOf(), Pos(0, 0, 0)))
var pos = Pos(0, 0, 0)
fun overlap(other: Scanner): Transform? {
for (b1 in beacons) {
for (b2 in other.beacons) {
for (rot in Axe.allRotations()) {
val pos = b2.rotate(rot)
val shift = Pos(b1.x - pos.x, b1.y - pos.y, b1.z - pos.z)
val matches = other.beacons.count {
beacons.contains(it.rotate(rot).shift(shift))
}
if (matches >= 12)
return Transform(rot, shift)
}
}
}
return null
}
}
fun main() {
val scanners = File("input").readText().trim().split("\n\n").map {
Scanner(
it.split("\n").drop(1).map {
it.split(",").map(String::toInt).let { Pos(it[0], it[1], it[2]) }
}
)
}
val todo = mutableListOf(scanners[0])
val seen = mutableSetOf<Scanner>(scanners[0])
while (!todo.isEmpty()) {
val scanner = todo.first()
todo.removeFirst()
for (s in scanners) {
if (seen.contains(s))
continue
val transform = scanner.overlap(s)
if (transform != null) {
s.pos = transform.shift.transform(scanner.transforms)
s.transforms = listOf(transform) + scanner.transforms
todo.add(s)
seen.add(s)
}
}
}
val allBeacons = scanners
.flatMap { s -> s.beacons.map { b -> b.transform(s.transforms) } }
.toSet()
println("First: ${allBeacons.size}")
val second = scanners
.flatMap { s1 -> scanners.map { s2 -> s1 to s2 } }
.map { (s1, s2) -> s1.pos.dist(s2.pos) }
.maxOrNull()!!
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 3,280 | advent-of-code | MIT License |
src/Day04.kt | rbraeunlich | 573,282,138 | false | {"Kotlin": 63724} | fun main() {
fun part1(input: List<String>): Int {
var overlaps = 0
input.forEach { line ->
val pair = line.split(",").let { it[0] to it[1] }
val firstRange = pair.first.split("-").let {
it[0].toInt()..it[1].toInt()
}
val secondRange = pair.second.split("-").let {
it[0].toInt()..it[1].toInt()
}
println(firstRange)
println(secondRange)
if(firstRange.containsAllOf(secondRange) || secondRange.containsAllOf(firstRange)) {
overlaps++
}
}
return overlaps
}
fun part2(input: List<String>): Int {
var overlapsAtAll = 0
input.forEach { line ->
val pair = line.split(",").let { it[0] to it[1] }
val firstRange = pair.first.split("-").let {
it[0].toInt()..it[1].toInt()
}
val secondRange = pair.second.split("-").let {
it[0].toInt()..it[1].toInt()
}
println(firstRange)
println(secondRange)
if(firstRange.containsAnyOf(secondRange) || secondRange.containsAnyOf(firstRange)) {
overlapsAtAll++
}
}
return overlapsAtAll }
// 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))
}
private fun IntRange.containsAnyOf(range: IntRange): Boolean =
this.toList().any { range.contains(it) }
private fun IntRange.containsAllOf(range: IntRange): Boolean =
this.toList().containsAll(range.toList())
| 0 | Kotlin | 0 | 1 | 3c7e46ddfb933281be34e58933b84870c6607acd | 1,798 | advent-of-code-2022 | Apache License 2.0 |
src/y2023/Day07.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2023
import util.readInput
import util.timingStatistics
object Day07 {
private val nonNumbers = mapOf(
'T' to 10,
'J' to 11,
'Q' to 12,
'K' to 13,
'A' to 14
)
private val nonNumbers2 = mapOf(
'J' to 1,
'T' to 10,
'Q' to 11,
'K' to 12,
'A' to 13
)
data class Hand(
val cards: List<Int>,
val bid: Int,
val position: Int,
val setSizes: List<Int>
)
private fun parse(input: List<String>, faces: Map<Char, Int>): List<Hand> {
return input.mapIndexed { idx, line ->
val (cards, bid) = line.split(" ")
val parsedCards = cards.map {
faces[it] ?: it.digitToInt()
}
val sets = setSizes(parsedCards)
Hand(parsedCards, bid.toInt(), idx, sets)
}
}
private val maxSizeSelectors = List(2) { idx ->
{ hand: Hand -> hand.setSizes[idx] }
}
private val cardSelectors = List(5) { idx ->
{ hand: Hand -> hand.cards[idx] }
}
private val strengthComparator: Comparator<Hand> = compareBy(
*(maxSizeSelectors + cardSelectors).toTypedArray()
)
private fun setSizes(cards: List<Int>): List<Int> {
val sets = (2..14).map { c ->
cards.count { it == c }
}.sortedDescending().toMutableList()
sets[0] += cards.count { it == 1 }
return sets
}
fun part1(input: List<String>): Int {
return totalWinnings(input)
}
fun part2(input: List<String>): Int {
return totalWinnings(input, nonNumbers2)
}
private fun totalWinnings(input: List<String>, faces: Map<Char, Int> = nonNumbers): Int {
val hands = parse(input, faces).sortedWith(strengthComparator)
return hands.mapIndexed { idx, hand ->
hand.bid * (idx + 1)
}.sum()
}
}
fun main() {
val testInput = """
32T3K 765
T55J5 684
KK677 28
KTJJT 220
QQQJA 483
""".trimIndent().split("\n")
println("------Tests------")
println(Day07.part1(testInput))
println(Day07.part2(testInput))
println("------Real------")
val input = readInput(2023, 7)
println("Part 1 result: ${Day07.part1(input)}")
println("Part 2 result: ${Day07.part2(input)}")
timingStatistics { Day07.part1(input) }
timingStatistics { Day07.part2(input) }
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 2,443 | advent-of-code | Apache License 2.0 |
src/Day07.kt | benwicks | 572,726,620 | false | {"Kotlin": 29712} | fun main() {
fun buildFilesystemTree(input: List<String>): FilesystemNode.Directory {
val filesystemTree: FilesystemNode.Directory = FilesystemNode.Directory(null, "/")
var currentDirectory = filesystemTree
for (line in input) {
if (line.startsWith("$ cd ")) {
val nextDirectoryName = line.split("$ cd ")[1]
if (nextDirectoryName == "..") {
currentDirectory = currentDirectory.parentDirectory!!
} else if (nextDirectoryName != "/") {
currentDirectory = currentDirectory.findSubDirectory(nextDirectoryName)
}
} else if (!line.startsWith("$ ls")) {
// add contents to current directory
currentDirectory.addChild(FilesystemNode.from(line, currentDirectory))
}
}
return filesystemTree
}
fun part1(input: List<String>): Int {
val filesystemTree = buildFilesystemTree(input)
// Find all the directories with a total size of at most 100_000.
// What is the sum of the total sizes of those directories?
var sum = 0
val maxSize = 100_000
if (filesystemTree.size <= maxSize) {
sum = filesystemTree.size
}
return sum + filesystemTree.childDirectoriesMatching { it.size <= maxSize }.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val filesystemTree = buildFilesystemTree(input)
val needToFreeAtLeast = 30_000_000 + filesystemTree.size - 70_000_000
// Find the smallest directory that, if deleted, would free up enough space on the filesystem to run the update.
// What is the total size of that directory?
return filesystemTree.childDirectoriesMatching {
it.size >= needToFreeAtLeast
}.minBy { it.size }.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95_437)
check(part2(testInput) == 24_933_642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
sealed class FilesystemNode(open val name: String) {
abstract val size: Int
data class Directory(
val parentDirectory: Directory?,
override val name: String,
private var children: MutableList<FilesystemNode> = mutableListOf(),
) : FilesystemNode(name) {
fun addChild(child: FilesystemNode) {
children += child
}
fun findSubDirectory(subDirectoryName: String): Directory {
return children
.filterIsInstance<Directory>()
.first { it.name == subDirectoryName }
}
override val size
get() = children.sumOf { it.size }
override fun toString(): String {
return "Name: $name, Size: $size"
}
fun childDirectoriesMatching(predicate: (Directory) -> Boolean): List<Directory> {
val childDirectories = children.filterIsInstance<Directory>()
val filtered = childDirectories.filter(predicate).toMutableList()
for (index in 0 until filtered.size) {
val matchingDirectory = filtered[index]
filtered += matchingDirectory.childDirectoriesMatching(predicate)
}
// also recursively check children who didn't meet predicate (since they may have children that do)
val childDirectoriesThatDoNotMeetPredicate = childDirectories.filterNot(predicate).toMutableList()
for (child in childDirectoriesThatDoNotMeetPredicate) {
filtered += child.childDirectoriesMatching(predicate)
}
return filtered
}
}
data class File(
override val name: String,
override val size: Int,
) : FilesystemNode(name)
companion object {
fun from(line: String, currentDirectory: Directory): FilesystemNode {
return if (line.startsWith("dir ")) {
Directory(currentDirectory, line.split("dir ")[1])
} else {
val parts = line.split(" ")
File(parts[1], parts[0].toInt())
}
}
}
} | 0 | Kotlin | 0 | 0 | fbec04e056bc0933a906fd1383c191051a17c17b | 4,311 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2022/Day20.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import readInput
// input contains duplicates, so keep the original index
data class MixedNumber(val value: Long, val originalIndex: Int)
private fun mixNumbers(original: LongArray, rounds: Int): List<Long> {
val list = original.withIndex().map { MixedNumber(it.value, it.index) }.toMutableList()
repeat(rounds) {
original.indices.forEach { originalIndex ->
val oldIndex = list.indexOfFirst { it.originalIndex == originalIndex }
val element = list.removeAt(oldIndex)
val newIndex = ((((oldIndex + element.value) % list.size) + list.size) % list.size).toInt()
list.add(newIndex, element)
}
}
return list.map { it.value }
}
private fun part1(input: List<String>): Long {
val array = input.map { it.toLong() }.toLongArray()
val list = mixNumbers(array, 1)
val startIndex = list.indexOfFirst { it == 0L }
return list[(startIndex + 1000) % list.size] + list[(startIndex + 2000) % list.size] + list[(startIndex + 3000) % list.size]
}
private fun part2(input: List<String>): Long {
val array = input.map { it.toLong() * 811589153L }.toLongArray()
val list = mixNumbers(array, 10)
val startIndex = list.indexOfFirst { it == 0L }
return list[(startIndex + 1000) % list.size] + list[(startIndex + 2000) % list.size] + list[(startIndex + 3000) % list.size]
}
fun main() {
val testInput = readInput("Day20_test", 2022)
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20", 2022)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 1,618 | adventOfCode | Apache License 2.0 |
2015/src/main/kotlin/day13.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parse
import utils.Parser
import utils.Solution
import utils.mapItems
import utils.permutations
fun main() {
Day13.run()
}
object Day13 : Solution<List<Day13.Rule>>() {
override val name = "day13"
override val parser = Parser.lines.mapItems { parseRule(it) }
@Parse("{person} would {direction} {amount} happiness units by sitting next to {partner}.")
data class Rule(
val person: String,
val direction: Direction,
val amount: Int,
val partner: String,
)
enum class Direction(val mul: Int) {
gain(1), lose(-1)
}
private fun score(people: List<String>, weights: Map<Pair<String, String>, Int>): Int {
return people.windowed(2).sumOf { (a, b) -> weights[a to b]!! + weights[b to a]!! } +
weights[people.last() to people.first()]!! +
weights[people.first() to people.last()]!!
}
private fun bestSeating(rules: List<Rule>): Int {
val people = rules.map { it.person }.toSet()
val weights = rules.associate {
(it.partner to it.person) to (it.direction.mul * it.amount)
}
val first = people.first()
return (people - first).toList().permutations.maxOf { others ->
score(others + first, weights)
}
}
override fun part1(input: List<Rule>): Int {
return bestSeating(input)
}
override fun part2(input: List<Rule>): Int {
val modifiedRules = input + input.map { it.person }.toSet().flatMap { person ->
listOf(
Rule("Madis", Direction.gain, 0, person),
Rule(person, Direction.gain, 0, "Madis"),
)
}
return bestSeating(modifiedRules)
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,593 | aoc_kotlin | MIT License |
src/Day13.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | import kotlin.streams.toList
fun main() {
fun fold(vec: Pair<Int, Int>, folder: Pair<Int, Int>): Pair<Int, Int> {
var tmp = vec * folder.normalize()
if (tmp.total() < folder.total()) return vec
tmp = folder - (vec - folder)
return if (folder.first == 0) {
Pair(vec.first, tmp.second)
} else {
Pair(tmp.first, vec.second)
}
}
fun part1(input: Pair<List<Pair<Int, Int>>, List<Pair<Int, Int>>>): Int {
var points = HashSet(input.first)
val f = input.second[0]
val nextPoints = HashSet<Pair<Int, Int>>()
points.forEach { nextPoints.add(fold(it, f)) }
points = nextPoints
return points.size
}
fun part2(input: Pair<List<Pair<Int, Int>>, List<Pair<Int, Int>>>): Int {
var points = HashSet(input.first)
for (f in input.second) {
val nextPoints = HashSet<Pair<Int, Int>>()
points.forEach { nextPoints.add(fold(it, f)) }
points = nextPoints
}
val maxX = points.maxOf { it.first }
val maxY = points.maxOf { it.second }
for (x in 0..maxY) {
println((0..maxX).map { if (points.contains(Pair(it, x))) "##" else " " }.joinToString("") { it })
}
return 0
}
fun preprocessing(input: String): Pair<List<Pair<Int, Int>>, List<Pair<Int, Int>>> {
val tmp = input.trim().split("\r\n\r\n")
val l = tmp[0].split("\r\n").map { parsePair(it.trim(), ",") }
val f = tmp[1].split("\r\n").map {
val i = it.split("=")
when (i[0].last()) {
'x' -> Pair(i[1].toInt(), 0)
'y' -> Pair(0, i[1].toInt())
else -> Pair(0, 0)
}
}
return Pair(l, f)
}
val realInp = read_testInput("real13")
val testInp = read_testInput("test13")
// val testInp = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"
// println(fold(Pair(2, 2), Pair(2, 0)))
// 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,318 | advent_of_code21_kotlin | Apache License 2.0 |
src/day05/Day05.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day05
import utils.*
data class Instruction(val amount: Int, val from: Int, val to: Int)
fun parseCrates(input: List<String>): List<List<Char>> {
val count = (input.first().length + 1) / 4
return (0 until count).map { i ->
input.mapNotNull { line -> line[1 + i * 4].takeIf { it != ' ' } }
}
}
fun parseInstructions(input: List<String>): List<Instruction> {
val regex = """move (\d+) from (\d+) to (\d+)""".toRegex()
return input.map { line ->
val (amount, from, to) = regex.find(line)!!.groupValues
.drop(1)
.map(String::toInt)
Instruction(amount, from - 1, to - 1)
}
}
fun parseInput(input: List<String>): Pair<List<List<Char>>, List<Instruction>> {
val sepIdx = input.indexOf("")
val crates = parseCrates(input.take(sepIdx - 1))
val instructions = parseInstructions(input.drop(sepIdx + 1))
return Pair(crates, instructions)
}
fun executeInstructions(
crates: MutableList<List<Char>>,
instructions: List<Instruction>,
isReversed: Boolean
): String {
instructions.forEach {
val batch = crates[it.from].take(it.amount).let { batch ->
batch.takeIf { isReversed }?.reversed() ?: batch
}
crates[it.from] = crates[it.from].drop(it.amount)
crates[it.to] = batch + crates[it.to]
}
return crates.joinToString("") { "" + it.first() }
}
fun part1(input: List<String>): String {
val (crates, instructions) = parseInput(input)
return executeInstructions(crates.toMutableList(), instructions, true)
}
fun part2(input: List<String>): String {
val (crates, instructions) = parseInput(input)
return executeInstructions(crates.toMutableList(), instructions, false)
}
fun main() {
val testInput = readInput("Day05_test")
expect(part1(testInput), "CMZ")
expect(part2(testInput), "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 1,966 | AOC-2022-Kotlin | Apache License 2.0 |
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day08/Day08.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2021.day08
import eu.janvdb.aocutil.kotlin.readLines
private const val FILENAME = "input08.txt"
fun main() {
val digits = readLines(2021, FILENAME)
.map(::parseLine)
.map { getDigits(it.first, it.second) }
val result1 = digits.flatten().count { it == 1 || it == 4 || it == 7 || it == 8 }
println(result1)
val result2 = digits.map(::toNumber).sum()
println(result2)
}
fun parseLine(line: String): Pair<List<Set<Char>>, List<Set<Char>>> {
val parts = line.split(" | ")
return Pair(parsePart(parts[0]), parsePart(parts[1]))
}
fun parsePart(s: String): List<Set<Char>> {
return s.split(" ").map { it.trim().toCharArray().toSet() }
}
fun getDigits(inputs: List<Set<Char>>, outputs: List<Set<Char>>): List<Int> {
var remainingInputs: List<Set<Char>> = inputs
val pattern1 = remainingInputs.find { it.size == 2 }!!
val pattern4 = remainingInputs.find { it.size == 4 }!!
val pattern7 = remainingInputs.find { it.size == 3 }!!
val pattern8 = remainingInputs.find { it.size == 7 }!!
remainingInputs = remainingInputs - setOf(pattern1, pattern4, pattern7, pattern8)
val pattern3 = remainingInputs.find { it.size == 5 && it.containsAll(pattern1) }!!
val pattern9 = remainingInputs.find { it.size == 6 && it.containsAll(pattern3) }!!
remainingInputs = remainingInputs - setOf(pattern3, pattern9)
val pattern0 = remainingInputs.find { it.size == 6 && it.containsAll(pattern1) }!!
remainingInputs = remainingInputs - setOf(pattern0)
val pattern6 = remainingInputs.find { it.size == 6 }!!
remainingInputs = remainingInputs - setOf(pattern6)
val pattern5 = remainingInputs.find { it.size == 5 && pattern6.containsAll(it) }!!
remainingInputs = remainingInputs - setOf(pattern5)
val pattern2 = remainingInputs.find { it.size == 5 }!!
return outputs.map {
when (it) {
pattern0 -> 0
pattern1 -> 1
pattern2 -> 2
pattern3 -> 3
pattern4 -> 4
pattern5 -> 5
pattern6 -> 6
pattern7 -> 7
pattern8 -> 8
pattern9 -> 9
else -> -1
}
}
}
fun toNumber(digits: List<Int>): Int {
val result = digits.fold(0) { value, digit -> value * 10 + digit }
println(result)
return result
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,148 | advent-of-code | Apache License 2.0 |
src/Day09.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} | import kotlin.math.abs
private data class Position(val x: Int, val y: Int)
private enum class Direction(val dx: Int, val dy: Int){
LEFT(-1,0), RIGHT(+1,0), UP(0,+1), DOWN(0,-1)
}
private fun Char.toDir() = Direction.values().first{ this == it.name[0] }
private operator fun Position.plus(d: Direction) = Position(x+d.dx, y+d.dy)
private fun Position.follow(p: Position): Position {
val difX = p.x-x
val difY = p.y-y
return if (abs(difX) > 1 || abs(difY) > 1)
Position( x + difX.coerceIn(-1..1), y + difY.coerceIn(-1..1) )
else this
}
private fun tailVisits(input: List<String>, nodes: Int=0) = buildSet {
var head = Position(0,0)
val middle = MutableList(nodes){ Position(0,0) }
var tail = Position(0,0)
input.forEach {
val dir = it.substringBefore(' ')[0].toDir()
val steps = it.substringAfter(' ').toInt()
repeat(steps) {
head += dir
if (nodes>0) {
middle[0] = middle[0].follow(head)
for(i in 1..middle.lastIndex) middle[i] = middle[i].follow(middle[i-1])
tail = tail.follow(middle[nodes-1])
} else
tail = tail.follow(head)
add(tail)
}
}
}
private fun part1(input: List<String>): Int =
tailVisits(input).size
private fun part2(input: List<String>): Int =
tailVisits(input,8).size
fun main() {
val input_test = readInput("Day09_test")
check(part1(input_test) == 13)
check(part2(input_test) == 1)
val input_test1 = readInput("Day09_test1")
check(part2(input_test1) == 36)
val input = readInput("Day09")
println(part1(input)) // 6406
println(part2(input)) // 2643
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 1,708 | aoc2022 | Apache License 2.0 |
src/day9/day9.kt | bienenjakob | 573,125,960 | false | {"Kotlin": 53763} | package day9
import inputTextOfDay
import testTextOfDay
import kotlin.math.abs
fun parseInput(input: String): List<Pair<Direction, Int>> =
input.lines().map { line ->
line.split(" ").let { (d, n) -> Direction.valueOf(d) to n.toInt() }
}
fun part1(input: String) = visit(2, input).size
fun part2(input: String) = visit(10, input).size
fun visit(ropeSize: Int, input: String): MutableSet<Pos> {
val motions = parseInput(input)
val knots = MutableList(ropeSize) { Pos(0,0) }
val visited = mutableSetOf(knots.last())
for ((direction, n) in motions) {
repeat(n) {
knots.head += direction.move
for (tail in 1 until knots.size) {
knots[tail] = knots[tail] + tailMove(knots[tail - 1], knots[tail])
}
visited += knots.last()
}
}
return visited
}
val Move.chebyshevDistance: Int get () = maxOf(abs(dx), abs(dy))
fun tailMove(head: Pos, tail: Pos): Move {
val tailToHead = head - tail
return if (tailToHead.chebyshevDistance > 1)
Move(tailToHead.dx.coerceIn(-1,1), tailToHead.dy.coerceIn(-1,1))
else
Move(0,0)
}
fun main() {
val day = 9
val testInput = testTextOfDay(day)
check(part1(testInput) == 13)
val input = inputTextOfDay(day)
check(part1(input) == 5710)
check(part2(input) == 2259)
println(part1(input))
println(part2(input))
}
private var <E> MutableList<E>.head: E
get() = first()
set(e) = run { set(0, e) }
data class Pos(val x: Int, val y: Int){
override fun toString() = "(x:$x, y:$y)"
}
data class Move(val dx: Int, val dy: Int)
private operator fun Pos.plus(move: Move): Pos = copy(x = x + move.dx, y = y + move.dy)
private operator fun Pos.minus(other: Pos): Move = Move(this.x - other.x, this.y - other.y)
enum class Direction(val move: Move) {
U(Move(0, 1)),
R(Move(1, 0)),
D(Move(0, -1)),
L(Move(-1, 0))
}
| 0 | Kotlin | 0 | 0 | 6ff34edab6f7b4b0630fb2760120725bed725daa | 1,940 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day13/Day13.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day13
import org.json.JSONArray
import readInput
import java.lang.Integer.min
fun main() {
fun compare(arr1: JSONArray, arr2: JSONArray): Int {
for (i in 0 until min(arr1.length(), arr2.length())) {
val e1 = arr1.get(i)
val e2 = arr2.get(i)
if (e1 is Int && e2 is Int) {
if (e1 != e2) {
return e2 - e1
} else {
continue
}
}
if (e1 is JSONArray && e2 is JSONArray) {
val order = compare(e1, e2)
if (order != 0) {
return order
} else {
continue
}
}
if (e1 is Int && e2 is JSONArray) {
val order = compare(JSONArray(listOf(e1)), e2)
if (order != 0) {
return order
} else {
continue
}
}
if (e1 is JSONArray && e2 is Int) {
val order = compare(e1, JSONArray(listOf(e2)))
if (order != 0) {
return order
} else {
continue
}
}
}
return arr2.length() - arr1.length()
}
val comparator = Comparator<JSONArray> { e1, e2 -> compare(e1, e2) }
fun part1(input: List<Pair<JSONArray, JSONArray>>): Int = input.mapIndexed { index, pair ->
if (compare(pair.first, pair.second) > 0) index + 1 else 0
}.sum()
fun part2(input: List<JSONArray>): Int {
val fstDivider = JSONArray("[[2]]")
val sndDivider = JSONArray("[[6]]")
val sorted = input.toMutableList().also { it.add(fstDivider) }.also { it.add(sndDivider) }
.sortedWith(comparator)
.reversed()
var res = 1
sorted.forEachIndexed { index, jsonArray ->
if (jsonArray == fstDivider || jsonArray == sndDivider) {
res *= (index + 1)
}
}
return res
}
fun parse(input: String): JSONArray = JSONArray(input)
fun preprocess1(input: List<String>): List<Pair<JSONArray, JSONArray>> = input.indices.step(3).map {
Pair(parse(input[it]), parse(input[it + 1]))
}
fun preprocess2(input: List<String>): List<JSONArray> = input.filter { it.isNotBlank() }.map { parse(it) }
// test if implementation meets criteria from the description, like:
val testInput = readInput(13, true)
check(part1(preprocess1(testInput)) == 13)
val input = readInput(13)
println(part1(preprocess1(input)))
check(part2(preprocess2(testInput)) == 140)
println(part2(preprocess2(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 2,759 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | haraldsperre | 572,671,018 | false | {"Kotlin": 17302} | fun main() {
fun getPriority(input: Char): Int {
return when (input) {
in 'a'..'z' -> input - 'a' + 1
in 'A'..'Z' -> input - 'A' + 27
else -> throw Exception("Invalid input")
}
}
fun getCompartments(rucksack: String): Pair<String, String> {
val compartmentSize = rucksack.length / 2
return rucksack.take(compartmentSize) to rucksack.takeLast(compartmentSize)
}
fun findMatching(rucksack: String): Set<Char> {
val (left, right) = getCompartments(rucksack)
return left.filter { item ->
right.contains(item)
}.toSet()
}
fun findBadge(elves: List<String>): Set<Char> {
return elves.map { elf -> elf.toSet() }
.reduce { common, rucksack -> common.intersect(rucksack) }
}
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
findMatching(rucksack).sumOf { getPriority(it) }
}
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.sumOf { elves ->
findBadge(elves).sumOf { getPriority(it) }
}
}
// 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 | c4224fd73a52a2c9b218556c169c129cf21ea415 | 1,448 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | object Day03 {
const val EXPECTED_PART1_CHECK_ANSWER = 157
const val EXPECTED_PART2_CHECK_ANSWER = 70
const val ELF_GROUP_SIZE = 3
}
fun main() {
fun Char.mapToItemValue() = if (this.isUpperCase()) (this.minus('A') + 27) else (this.minus('a') + 1)
fun part1(input: List<String>): Int {
return input.sumOf {
val compartment1 = it
.take(it.length / 2)
val compartment2 = it
.takeLast(it.length / 2)
val inBothCompartments = compartment1.toSet().intersect(compartment2.toSet())
val itemValue = if (inBothCompartments.isEmpty()) 0 else inBothCompartments.first().mapToItemValue()
itemValue
}
}
fun part2(input: List<String>): Int {
val commonItemsValues = input.chunked(Day03.ELF_GROUP_SIZE) {
it
.map { rucksackContent -> rucksackContent.toSet() }
.foldIndexed(emptySet<Char>()) { idx, acc, chars -> if (idx == 0) chars else acc.intersect(chars) }
.firstOrNull()
?.mapToItemValue()
?: 0
}
return commonItemsValues.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == Day03.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day03.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 1,558 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/Excercise14.kt | underwindfall | 433,989,850 | false | {"Kotlin": 55774} | private fun part1() {
val input = getInputAsTest("14")
val map = input.drop(2).map { it.split("->") }.associate { it[0].trim() to it[1].trim() }
var pairFreq = mutableMapOf<String, Long>()
input[0].windowed(2).forEach { key -> pairFreq[key] = pairFreq.getOrDefault(key, 0) + 1 }
repeat(10) {
val newMap = mutableMapOf<String, Long>()
pairFreq.forEach { (k, v) ->
newMap[k[0] + map[k]!!] = newMap.getOrDefault(k[0] + map[k]!!, 0) + v
newMap[map[k]!! + k[1]] = newMap.getOrDefault(map[k]!! + k[1], 0) + v
}
pairFreq = newMap
}
val charFreq = mutableMapOf<Char, Long>()
pairFreq.forEach { (k, v) -> charFreq[k[0]] = charFreq.getOrDefault(k[0], 0) + v }
charFreq[input[0].last()] = charFreq.getOrDefault(input[0].last(), 0) + 1
val ans = charFreq.values.sorted().let { it.last() - it.first() }
println("Part 1: $ans")
}
private fun part2() {
val input = getInputAsTest("14")
val map = input.drop(2).map { it.split("->") }.associate { it[0].trim() to it[1].trim() }
var pairFreq = mutableMapOf<String, Long>()
input[0].windowed(2).forEach { key -> pairFreq[key] = pairFreq.getOrDefault(key, 0) + 1 }
repeat(40) {
val newMap = mutableMapOf<String, Long>()
pairFreq.forEach { (k, v) ->
newMap[k[0] + map[k]!!] = newMap.getOrDefault(k[0] + map[k]!!, 0) + v
newMap[map[k]!! + k[1]] = newMap.getOrDefault(map[k]!! + k[1], 0) + v
}
pairFreq = newMap
}
val charFreq = mutableMapOf<Char, Long>()
pairFreq.forEach { (k, v) -> charFreq[k[0]] = charFreq.getOrDefault(k[0], 0) + v }
charFreq[input[0].last()] = charFreq.getOrDefault(input[0].last(), 0) + 1
val ans = charFreq.values.sorted().let { it.last() - it.first() }
println("Part 2: $ans")
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 4fbee48352577f3356e9b9b57d215298cdfca1ed | 1,773 | advent-of-code-2021 | MIT License |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-04.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import kotlin.math.pow
fun main() {
val input = readInputLines(2023, "04-input")
val test1 = readInputLines(2023, "04-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val cards = input.map { Card.from(it) }
return cards.sumOf { it.worth() }
}
private fun part2(input: List<String>): Int {
val cards = input.map { Card.from(it) }
val counts = cards.map { 1 }.toMutableList()
cards.forEachIndexed { index, card ->
val matching = card.matching()
(index + 1 .. (index + matching).coerceAtMost(cards.lastIndex)).forEach {
counts[it] += counts[index]
}
}
return counts.sum()
}
private data class Card(val id: Int, val winning: Set<String>, val all: List<String>) {
companion object {
private val whitespace = """\s+""".toRegex()
private val separator = """ \|\s+""".toRegex()
fun from(line: String): Card {
val (card, numbers) = line.split(": ")
val (_, id) = card.split(whitespace)
val (winning, all) = numbers.split(separator)
return Card(id.toInt(), winning.split(whitespace).toSet(), all.split(whitespace))
}
}
fun matching() = all.count { it in winning }
fun worth(): Int {
val count = matching()
if (count == 0) return 0
return 2.0.pow(count - 1).toInt()
}
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,698 | advent-of-code | MIT License |
src/main/kotlin/day7/Day7.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day7
import execute
import readAllText
import wtf
fun main() {
val example = """
${'$'} 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()
val input = readAllText("local/day7_input.txt")
execute(::part1, example)
execute(::part1, input)
execute(::part2, example)
execute(::part2, input)
}
fun part1(input: String) = parse(input).sizes().filter { it <= 100000 }.sum()
fun part2(input: String) = parse(input).let { filesystem ->
val dirSizes = filesystem.sizes().sorted()
val required = dirSizes.last() - (70000000 - 30000000)
val index = dirSizes.binarySearch { it - required }
dirSizes[if (index >= 0) index else -index - 1]
}
private fun parse(input: String) = input.lineSequence().filterNot(String::isBlank)
.fold(Filesystem(cwd = "dummy")) { filesystem, command ->
when {
command.startsWith("$ cd ") -> filesystem.cd(command)
command.startsWith("dir ") -> filesystem.addDir(command.substringAfter("dir "))
command.first().isDigit() -> filesystem.addFile(command.substringBefore(" ").toInt())
command == "$ ls" -> filesystem.resetCwd()
else -> wtf(command)
}
}
data class Filesystem(
private val tree: Map<String, DirNode> = emptyMap(),
private val cwd: String
) {
fun cd(command: String) = copy(cwd = cwd.pathResolve(command.substringAfter("$ cd ")))
fun resetCwd() = copy(tree = tree - cwd)
fun addFile(size: Int) = copy(tree = tree + (cwd to (tree[cwd] ?: DirNode()).run {
copy(directContent = directContent + size)
}))
fun addDir(dirName: String) = copy(tree = tree + (cwd to (tree[cwd] ?: DirNode()).run {
copy(indirectContent = indirectContent + cwd.pathResolve(dirName))
}))
fun sizes() = tree.values.map { getSize(it) }
data class DirNode(val directContent: Int = 0, val indirectContent: List<String> = listOf())
private fun getSize(dirNode: DirNode): Int =
dirNode.directContent + dirNode.indirectContent.sumOf { this@Filesystem.tree[it]?.let(::getSize) ?: 0 }
private fun String.pathResolve(entry: String) = when (entry) {
".." -> substringBeforeLast("/").ifBlank { "/" }
"/" -> entry
else -> if (this == "/") "/$entry" else "$this/$entry"
}
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 2,690 | advent-of-code-2022 | MIT License |
src/Day12.kt | jwklomp | 572,195,432 | false | {"Kotlin": 65103} | fun main() {
val lookup = "_abcdefghijklmnopqrstuvwxyz"
val neighborFilterFn: (other: Node<Int>, self: Node<Int>) -> Boolean =
{ other, self -> other.isNeighborOf(self) && other.value <= self.value + 1 }
fun convertToNrs(inputAsStrings: List<List<String>>): List<List<Int>> =
inputAsStrings.map { strings ->
strings.map {
when (it) {
"S" -> 1
"E" -> 26
else -> lookup.indexOf(it)
}
}
}
fun part1(input: List<String>): Int {
val inputAsStrings = input.map { it.chunked(1) }
val startNodePos = findIndex(inputAsStrings, "S")
val endNodePos = findIndex(inputAsStrings, "E")
val grid: Grid2D<Int> = Grid2D(convertToNrs(inputAsStrings))
val startNode = grid.getCell(startNodePos.first(), startNodePos.last())
val endNode = grid.getCell(endNodePos.first(), endNodePos.last())
val dijkstraShortestPath = dijkstraSP(grid.getAllCells(), startNode, endNode, neighborFilterFn)
return dijkstraShortestPath.size - 1
}
fun part2(input: List<String>): Int {
val inputAsStrings = input.map { it.chunked(1) }
val grid: Grid2D<Int> = Grid2D(convertToNrs(inputAsStrings))
val endNodePos = findIndex(inputAsStrings, "E")
val minValue = grid.getAllCells().minOfOrNull { it.value }
val startNodes = grid.getAllCells().filter { it.value == minValue }
val endNode = grid.getCell(endNodePos.first(), endNodePos.last())
val shortestPathsForAllStartingPositions =
startNodes.map { startNode -> dijkstraSP(grid.getAllCells(), startNode, endNode, neighborFilterFn) }
return shortestPathsForAllStartingPositions.minOfOrNull { it.size }?.minus(1) ?: 0
}
val testInput = readInput("Day12_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1b1121cfc57bbb73ac84a2f58927ab59bf158888 | 2,036 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/ryanmoelter/advent/day04/Cleanup.kt | ryanmoelter | 573,615,605 | false | {"Kotlin": 84397} | package com.ryanmoelter.advent.day04
fun main() {
println(findOverlapping(day04input))
}
fun findOverlapping(input: String): Int = input.lines()
.toSectionRanges()
.map { it.isOverlapping() }
.sumOf { if (it) 1 else 0 as Int }
fun findFullyContained(input: String): Int = input.lines()
.toSectionRanges()
.map { it.isEitherFullyContained() }
.sumOf { if (it) 1 else 0 as Int }
fun List<String>.toSectionRanges(): List<SectionRange> = map { pairString -> pairString.split(',') }
.map { pair ->
pair.map { rangeString ->
rangeString
.split('-')
.map { it.toInt() }
}
.map { (first, second) -> first..second }
}
.map { (first, second) -> SectionRange(first, second) }
data class SectionRange(val first: IntRange, val second: IntRange) {
fun isEitherFullyContained(): Boolean {
val firstIsContained = second.contains(first.first) && second.contains(first.last)
val secondIsContained = first.contains(second.first) && first.contains(second.last)
return firstIsContained || secondIsContained
}
fun isOverlapping(): Boolean {
val firstIsContained = second.contains(first.first) || second.contains(first.last)
val secondIsContained = first.contains(second.first) || first.contains(second.last)
return firstIsContained || secondIsContained
}
}
| 0 | Kotlin | 0 | 0 | aba1b98a1753fa3f217b70bf55b1f2ff3f69b769 | 1,329 | advent-of-code-2022 | Apache License 2.0 |
src/main/aoc2018/Day6.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
import increase
import kotlin.math.abs
class Day6(input: List<String>) {
data class Location(val x: Int, val y: Int) {
fun distanceTo(other: Location) = abs(x - other.x) + abs(y - other.y)
fun withinFovUp(other: Location): Boolean {
return other.y < y // above
&& other.x - x >= other.y - y // within fov to the left (above the \ line)
&& other.x - x <= y - other.y // within fov to the right (above the / line)
}
fun withinFovLeft(other: Location): Boolean {
return other.x < x // to the left
&& other.x - x <= other.y - y // within fov upward (below the \ line)
&& other.x - x <= y - other.y // within fov downward (above the / line)
}
fun withinFovDown(other: Location): Boolean {
return other.y > y // below
&& other.x - x >= y - other.y // within fov to the left (below the / line)
&& other.x - x <= other.y - y // within fov to the right (below the \ line)
}
fun withinFovRight(other: Location): Boolean {
return other.x > x // to the right
&& other.x - x >= y - other.y // within fov to the top (below the / line)
&& other.x - x >= other.y - y // within fov to the bottom (above the \ line)
}
}
private val locations = input.map {
Location(it.substringBefore(",").toInt(), it.substringAfter(", ").toInt())
}
private fun findNonInfiniteLocations(locations: List<Location>): List<Location> {
// To not be infinite there must be at least one other coordinate in each direction
// within a 90 degree field of vision in the given direction
return locations.filter { pos ->
locations.any { pos.withinFovUp(it) }
&& locations.any { pos.withinFovLeft(it) }
&& locations.any { pos.withinFovDown(it) }
&& locations.any { pos.withinFovRight(it) }
}
}
fun solvePart1(): Int {
val xRange = locations.minByOrNull { it.x }!!.x..locations.maxByOrNull { it.x }!!.x
val yRange = locations.minByOrNull { it.y }!!.y..locations.maxByOrNull { it.y }!!.y
val finiteLocations = findNonInfiniteLocations(locations)
val areas = mutableMapOf<Location, Int>()
for (y in yRange) {
for (x in xRange) {
val locationByDistance = locations.groupBy { it.distanceTo(Location(x, y)) }.toSortedMap()
val closest = locationByDistance[locationByDistance.firstKey()]!!
if (closest.size == 1 && finiteLocations.contains(closest.first())) {
// Current coordinate is closest to a single location and it has a finite area
// increase it's area by one.
areas.increase(closest.first())
}
}
}
return areas.toList().maxByOrNull { it.second }!!.second
}
fun solvePart2(totalDistance: Int): Int {
val xRange = locations.minByOrNull { it.x }!!.x..locations.maxByOrNull { it.x }!!.x
val yRange = locations.minByOrNull { it.y }!!.y..locations.maxByOrNull { it.y }!!.y
var safeArea = 0
for (y in yRange) {
for (x in xRange) {
if (locations.sumOf { it.distanceTo(Location(x, y)) } < totalDistance) {
safeArea++
}
}
}
return safeArea
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,573 | aoc | MIT License |
2022/src/main/kotlin/org/suggs/adventofcode/Day07NoSpaceLeftOnDevice.kt | suggitpe | 321,028,552 | false | {"Kotlin": 156836} | package org.suggs.adventofcode
object Day07NoSpaceLeftOnDevice {
fun sumDirectoriesOver100KFrom(commands: List<String>): Long =
findAllDirectorySizes(buildTreeFrom(commands)).filter { it < 100000 }.sum()
fun findDirectoryThatFreesUpSpaceForUpdateFrom(commands: List<String>): Long {
val root = buildTreeFrom(commands)
return findAllDirectorySizes(root).filter { it > spaceNeededFrom(root) }.minOf { it }
}
private fun spaceNeededFrom(root: Dir) =
(30000000 - (70000000 - sumValueOfTree(root)))
private fun findAllDirectorySizes(context: Dir): List<Long> =
(listOf(sumValueOfTree(context)) + context.files.filterIsInstance<Dir>().flatMap { findAllDirectorySizes(it) })
private fun sumValueOfTree(tree: Dir): Long =
tree.files.filterIsInstance<File>().sumOf { (it).size } +
tree.files.filterIsInstance<Dir>().sumOf { sumValueOfTree(it) }
private fun buildTreeFrom(commands: List<String>): Dir {
fun buildTreeFrom(commands: List<String>, context: Dir): Dir =
when {
commands.isEmpty() -> context
else -> buildTreeFrom(commands.drop(1), process(commands.first(), context))
}
return buildTreeFrom(commands, Dir(NullNode(), "/", listOf())).findRoot()
}
private fun process(command: String, context: Dir): Dir =
when {
command.isEmpty() -> context
command.startsWith("cd /") -> context
command.startsWith("cd ..") -> context.parent as Dir
command.startsWith("cd ") -> context.files.filter { it.name() == command.split(" ")[1] }.first() as Dir
command.startsWith("ls") -> addNodesTo(command.split("\n").drop(1), context)
else -> throw IllegalStateException("I dont know how to process this one [$command]")
}
private fun addNodesTo(files: List<String>, context: Dir): Dir =
when {
files.isEmpty() -> context
else -> {
context.files = context.files + createNodeFrom(files.first(), context)
addNodesTo(files.drop(1), context)
}
}
private fun createNodeFrom(node: String, parent: Dir): Node =
when {
node.startsWith("dir") -> Dir(parent, node.split(" ")[1], listOf())
else -> File(parent, node.split(" ")[1], node.split(" ")[0].toLong())
}
}
interface Node {
fun parent(): Node
fun name(): String
}
data class File(val parent: Node, val name: String, val size: Long) : Node {
override fun parent() = parent
override fun name() = name
}
data class Dir(val parent: Node, val name: String, var files: List<Node>) : Node {
override fun parent() = parent
override fun name() = name
fun findRoot(): Dir {
return when {
parent is Dir -> parent.findRoot()
parent is NullNode -> this
else -> throw IllegalStateException("shit or bust")
}
}
}
class NullNode : Node {
override fun parent(): Node {
TODO("Not yet implemented")
}
override fun name(): String {
TODO("Not yet implemented")
}
}
| 0 | Kotlin | 0 | 0 | 9485010cc0ca6e9dff447006d3414cf1709e279e | 3,192 | advent-of-code | Apache License 2.0 |
src/day18/day18.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day18
import readInput
private fun parseInput(input: List<String>): List<IntArray> =
input.map { line ->
val parts = line.split(",")
val result = IntArray(3)
repeat(3) { result[it] = parts[it].toInt().coerceAtLeast(result[it]) }
result
}
private fun getMaxes(input: List<IntArray>): IntArray {
val result = IntArray(3)
input.forEach { line ->
for (index in line.indices) {
result[index] = line[index].coerceAtLeast(result[index])
}
}
return result
}
private fun Array<Array<BooleanArray>>.updateBoard(input: List<IntArray>) {
for (line in input) {
this[line[0]][line[1]][line[2]] = true
}
}
fun neighbours(x: Int, y: Int, z: Int): List<IntArray> {
val moves = listOf(
intArrayOf(0, 0, 1),
intArrayOf(0, 0, -1),
intArrayOf(1, 0, 0),
intArrayOf(-1, 0, 0),
intArrayOf(0, -1, 0),
intArrayOf(0, 1, 0),
)
return moves.map {
it[0] += x
it[1] += y
it[2] += z
it
}
}
private fun calculatePartOne(board: Array<Array<BooleanArray>>): Int {
fun isFreeSpace(x: Int, y: Int, z: Int): Boolean {
if (x < 0 || y < 0 || z < 0 || x >= board[0].size || y >= board[0][0].size || z >= board.size) {
return true
}
return board[z][x][y].not()
}
fun calculatePoint(x: Int, y: Int, z: Int): Int {
return neighbours(x, y, z).count { isFreeSpace(it[1], it[2], it[0]) }
}
var result = 0
for (z in board.indices) {
for (x in board[z].indices) {
for (y in board[z][x].indices) {
if (board[z][x][y]) {
result += calculatePoint(x, y, z)
}
}
}
}
return result
}
private fun part1(input: List<String>): Int {
val parsedInput = parseInput(input)
val sizes = getMaxes(parsedInput)
val board = Array(sizes[0] + 1) { Array(sizes[1] + 1) { BooleanArray(sizes[2] + 1) } }
board.updateBoard(parsedInput)
return calculatePartOne(board)
}
private fun calculatePartTwo(board: Array<Array<BooleanArray>>): Int {
val outside = hashSetOf<Triplet>()
val queue = mutableListOf(Triplet(-1, -1, -1)).also {
outside.add(it[0])
}
while (queue.isNotEmpty()) {
val item = queue.removeLast()
val neighbours = neighbours(item.first, item.second, item.third)
.asSequence()
.filter { it[0] in -1..board.size }
.filter { it[1] in -1..board[0].size }
.filter { it[2] in -1..board[0][0].size }
.filter {
it[0] == -1 || it[1] == -1 || it[2] == -1 ||
it[0] == board.size || it[1] == board[0].size || it[2] == board[0][0].size ||
board[it[0]][it[1]][it[2]].not()
}
neighbours.forEach {
val item = Triplet(it[0], it[1], it[2])
if (outside.contains(item).not()) {
outside.add(item)
queue.add(item)
}
}
}
var result = 0
for (x in board.indices) {
for (y in board[0].indices) {
for (z in board[0][0].indices) {
if (board[x][y][z]) {
result += neighbours(x, y, z).count { Triplet(it[0], it[1], it[2]) in outside }
}
}
}
}
return result
}
private fun part2(input: List<String>): Int {
val parsedInput = parseInput(input)
val sizes = getMaxes(parsedInput)
val board = Array(sizes[0] + 1) { Array(sizes[1] + 1) { BooleanArray(sizes[2] + 1) } }
board.updateBoard(parsedInput)
return calculatePartTwo(board)
}
fun main() {
val input = readInput("day18/input")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
data class Triplet(
val first: Int,
val second: Int,
val third: Int,
) | 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 3,951 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode2018/Day23ExperimentalEmergencyTeleportation.kt | n81ur3 | 484,801,748 | false | {"Kotlin": 476844, "Java": 275} | package adventofcode2018
import kotlin.math.abs
class Day23ExperimentalEmergencyTeleportation
data class TeleportCoordinate(val x: Int, val y: Int, val z: Int)
data class Nanobot(val x: Int, val y: Int, val z: Int, val radius: Int) {
fun inRange(otherBot: Nanobot): Boolean {
val manhattanDistance = distanceTo(otherBot.x, otherBot.y, otherBot.z)
return manhattanDistance <= otherBot.radius
}
fun withinRangeOfSharedPoint(otherBot: Nanobot) =
distanceTo(otherBot.x, otherBot.y, otherBot.z) <= radius + otherBot.radius
fun inRange(xDist: Int, yDist: Int, zDist: Int) = distanceTo(xDist, yDist, zDist) <= radius
internal fun distanceTo(xDist: Int, yDist: Int, zDist: Int) =
abs(x - xDist) + abs(y - yDist) + abs(z - zDist)
}
class TeleportationDevice(val input: List<String>) {
val bots: List<Nanobot>
val strongestBot: Nanobot
get() = bots.maxBy { it.radius }
init {
bots = input.map { parseBot(it) }
}
private fun parseBot(input: String): Nanobot {
val coordinates = input.substringAfter("<").substringBefore(">")
val (x, y, z) = coordinates.split(",").map { it.toInt() }
return Nanobot(x, y, z, input.substringAfterLast("=").toInt())
}
fun numberOfBotsInRangeOfStrongest() = bots.count { it.inRange(strongestBot) }
fun strongestCoordinate(): TeleportCoordinate {
var strongest = TeleportCoordinate(0, 0, 0)
var strongestCount = 0
val minX = bots.minOf { it.x }
val maxX = bots.maxOf { it.x }
val minY = bots.minOf { it.y }
val maxY = bots.maxOf { it.y }
val minZ = bots.minOf { it.z }
val maxZ = bots.maxOf { it.z }
var botsCount: Int
(minX..maxX).forEach { x ->
(minY..maxY).forEach { y ->
(minZ..maxZ).forEach { z ->
botsCount = bots.count { it.inRange(x, y, z) }
if (botsCount > strongestCount) {
strongestCount = botsCount
strongest = TeleportCoordinate(x, y, z)
}
}
}
}
return strongest
}
fun strongestDistance(): Int {
val neighbors: Map<Nanobot, Set<Nanobot>> = bots.map { bot ->
Pair(bot, bots.filterNot { it == bot }.filter { bot.withinRangeOfSharedPoint(it) }.toSet())
}.toMap()
val clique: Set<Nanobot> = BronKerbosch(neighbors).largestClique()
return clique.map { it.distanceTo(0, 0, 0) - it.radius }.max()
}
}
class BronKerbosch<T>(val neighbors: Map<T, Set<T>>) {
private var bestR: Set<T> = emptySet()
fun largestClique(): Set<T> {
execute(neighbors.keys)
return bestR
}
private fun execute(p: Set<T>, r: Set<T> = emptySet(), x: Set<T> = emptySet()) {
if (p.isEmpty() && x.isEmpty()) {
if (r.size > bestR.size) bestR = r
} else {
val mostNeighborsOfPandX: T = (p + x).maxBy { neighbors.getValue(it).size }!!
val pWithoutNeighbors = p.minus(neighbors[mostNeighborsOfPandX]!!)
pWithoutNeighbors.forEach { v ->
val neighborsOfV = neighbors[v]!!
execute(p.intersect(neighborsOfV), r + v, x.intersect(neighborsOfV))
}
}
}
} | 0 | Kotlin | 0 | 0 | fdc59410c717ac4876d53d8688d03b9b044c1b7e | 3,347 | kotlin-coding-challenges | MIT License |
src/Day07.kt | antonarhipov | 574,851,183 | false | {"Kotlin": 6403} | fun main() {
fun String.isCd() = startsWith("$ cd")
fun buildDirectoryTree(input: List<String>): Directory {
val root = Directory("/", null)
var currentDirectory = root
input.drop(1).forEach { line ->
if (line.isCd()) {
val (_, _, name) = line.split(" ")
currentDirectory = if (name.startsWith("..")) {
currentDirectory.parent ?: currentDirectory
} else {
val dir = Directory(name, currentDirectory)
currentDirectory.dirs.add(dir)
dir
}
}
if (line[0].isDigit()) {
val (size, name) = line.split(" ")
currentDirectory.files.add(FileEntry(name, size.toInt()))
}
}
return root
}
fun findDirectories(dir: Directory, threshold: Int) : List<Directory> {
val result = mutableListOf<Directory>()
if(dir.size< threshold) result.add(dir)
dir.dirs.forEach {
if(it.size < threshold) result.add(it)
result.addAll(findDirectories(it, threshold))
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
val result = findDirectories(buildDirectoryTree(testInput), 100000).distinct().sumOf { it.size }
println("test result = $result")
check(result == 95437)
val input = readInput("Day07")
val tree = buildDirectoryTree(input)
val directories = findDirectories(tree, 100000).distinct()
val resultPart1 = directories.sumOf { it.size }
println("part 1: $resultPart1")
val diskSpace = 70000000
val requiredSpace = 30000000
val freeSpace = diskSpace - tree.size
val needToDelete = requiredSpace - freeSpace
println("Disk space: $diskSpace, Used: ${tree.size}, Free space: $freeSpace, Required space: $requiredSpace")
println("Need to delete: $needToDelete")
val sortedBySize = findDirectories(tree, diskSpace).distinct().sortedBy { it.size }
for (d in sortedBySize) {
println(d)
}
val toDelete = sortedBySize.first {
it.size > needToDelete
}
println("Directory to delete: $toDelete")
}
class FileEntry(val name: String, val size: Int) {
override fun toString(): String = "File $name: $size]"
}
class Directory(val name: String, var parent: Directory?) {
val dirs: MutableList<Directory> = mutableListOf()
val files: MutableList<FileEntry> = mutableListOf()
val size: Int
get() = files.sumOf { it.size } + dirs.sumOf { it.size }
override fun toString(): String = "Directory $name: $size"
} | 0 | Kotlin | 0 | 0 | 8dd56fdbe67d0af74fbe65ff204275338785cd4a | 2,736 | aoc2022 | Apache License 2.0 |
src/Day14.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | import java.util.*
const val air = ' '
const val rock = '#'
const val sand = '*'
fun placeRocks(cave: Array<CharArray>, line: String): Int {
var maxRow = 0
val pairs = line.split(" -> ")
var (prevCol, prevRow) = listOf(-1, -1)
pairs.forEach { pair ->
val scanner = Scanner(pair)
var (col, row) = scanner.next().split(",").map { it.toInt() }
// col -= 490
if (prevCol != -1) {
if (col == prevCol) {
for (i in minOf(row, prevRow)..maxOf(row, prevRow)) cave[i][col] = rock
}
if (row == prevRow) {
for (i in minOf(col, prevCol)..maxOf(col, prevCol)) cave[row][i] = rock
}
}
prevCol = col
prevRow = row
maxRow = maxOf(maxRow, row)
}
return maxRow
}
fun moveSand(cave: Array<CharArray>, rc: Pair<Int, Int>): Pair<Int, Int> {
if (cave[rc.first + 1][rc.second] == air) return Pair(rc.first + 1, rc.second)
if (cave[rc.first + 1][rc.second - 1] == air) return Pair(rc.first + 1, rc.second - 1)
if (cave[rc.first + 1][rc.second + 1] == air) return Pair(rc.first + 1, rc.second + 1)
return rc
}
fun main() {
fun part1(input: List<String>): Int {
val (rows, cols) = listOf(1000, 1000)
val cave = Array(rows) { CharArray(cols) { air } }
input.forEach {
placeRocks(cave, it)
}
var sum = 0
var gone = false
while (!gone) {
var coords = Pair(0, 500) // row, col
while (true) {
if (coords.first in 0 until rows - 1 && coords.second in 1 until cols - 1) {
val newCoords = moveSand(cave, coords)
if (newCoords == coords) {
cave[coords.first][coords.second] = sand
sum++
break
}
coords = newCoords
} else {
gone = true
break
}
}
}
return sum
}
fun part2(input: List<String>): Int {
val (rows, cols) = listOf(1000, 1000)
val cave = Array(rows) { CharArray(cols) { air } }
var maxRow = 0
input.forEach {
maxRow = maxOf(maxRow, placeRocks(cave, it))
}
val floor = maxRow + 2
placeRocks(cave, "0,$floor -> ${cols - 1},$floor")
var sum = 0
var full = false
while (!full) {
var coords = Pair(0, 500) // row, col
while (true) {
val newCoords = moveSand(cave, coords)
if (newCoords == Pair(0, 500)) {
sum++
full = true
break
}
if (newCoords == coords) {
cave[coords.first][coords.second] = sand
sum++
break
}
coords = newCoords
}
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
// println(part1(testInput))
// check(part1(testInput) == 24)
println(part2(testInput))
check(part2(testInput) == 93)
val input = readInput("Day14")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 3,389 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2020/Day21.kt | tginsberg | 315,060,137 | false | null | /*
* Copyright (c) 2020 by <NAME>
*/
/**
* Advent of Code 2020, Day 21 - Allergen Assessment
* Problem Description: http://adventofcode.com/2020/day/21
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day21/
*/
package com.ginsberg.advent2020
class Day21(input: List<String>) {
private val food: Map<Set<String>, Set<String>> = parseInput(input)
private val allIngredients: Set<String> = food.keys.flatten().toSet()
private val allAllergies: Set<String> = food.values.flatten().toSet()
fun solvePart1(): Int {
val safeIngredients = safeIngredients()
return food.keys.sumOf { recipe ->
recipe.count { it in safeIngredients }
}
}
fun solvePart2(): String {
val ingredientsByAllergy = ingredientsByAllergy()
val found: MutableMap<String, String> = mutableMapOf()
while (ingredientsByAllergy.isNotEmpty()) {
val singles = ingredientsByAllergy
.filter { it.value.size == 1 }
.map { it.key to it.value.first() }
.toMap()
found.putAll(singles)
singles.keys.forEach { ingredientsByAllergy.remove(it) }
ingredientsByAllergy.values.forEach { it.removeAll(singles.values) }
}
return found.entries.sortedBy { it.key }.joinToString(",") { it.value }
}
private fun ingredientsByAllergy(): MutableMap<String, MutableSet<String>> {
val safeIngredients = safeIngredients()
return allAllergies.map { allergy ->
allergy to food.entries
.filter { allergy in it.value }
.map { it.key - safeIngredients }
.reduce { a, b -> a intersect b }
.toMutableSet()
}.toMap().toMutableMap()
}
private fun safeIngredients(): Set<String> =
allIngredients subtract allAllergies.flatMap { allergy ->
food
.filter { allergy in it.value }
.map { it.key }
.reduce { carry, ingredients -> ingredients intersect carry }
}.toSet()
private fun parseInput(input: List<String>): Map<Set<String>, Set<String>> =
input.map { line ->
val ingredients = line.substringBefore(" (").split(" ").toSet()
val allergies = line.substringAfter("(contains ").substringBefore(")").split(", ").toSet()
ingredients to allergies
}.toMap()
}
| 0 | Kotlin | 2 | 38 | 75766e961f3c18c5e392b4c32bc9a935c3e6862b | 2,471 | advent-2020-kotlin | Apache License 2.0 |
src/main/kotlin/Day15.kt | dliszewski | 573,836,961 | false | {"Kotlin": 57757} | import kotlin.math.abs
class Day15 {
fun part1(input: List<String>, lookupRow: Int): Int {
val sensors = mapToSensors(input)
val minRange = sensors.minOf { sensor ->
minOf(
sensor.position.x,
sensor.beacon.x,
sensor.position.x - sensor.distanceToBeacon()
)
}
val maxRange = sensors.maxOf { sensor ->
maxOf(
sensor.position.x,
sensor.beacon.x,
sensor.position.x + sensor.distanceToBeacon()
)
}
return (minRange..maxRange).count { x ->
val point = Point(x, lookupRow)
sensors.any { sensor -> sensor.beacon != point && sensor.position.distance(point) <= sensor.distanceToBeacon() }
}
}
fun part2(input: List<String>, limit: Int): Long {
val sensors = mapToSensors(input)
val pointNotCovered = findPositionNotCoveredByBeacon(limit, sensors)
return pointNotCovered.x.toLong() * 4000000 + pointNotCovered.y.toLong()
}
private fun findPositionNotCoveredByBeacon(limit: Int, sensors: List<Sensor>): Point {
for (y in 0..limit) {
var point = Point(0, y)
while (point.x <= limit) {
val coveredBySensor = pointCoveredBySensor(sensors, point)
if (coveredBySensor == null) {
return point
} else {
val maxCovered = coveredBySensor.maxDistanceCovered(point.y)
point = Point(maxCovered.x + 1, maxCovered.y)
}
}
}
error("Should find one...")
}
private fun pointCoveredBySensor(sensors: List<Sensor>, point: Point): Sensor? {
return sensors.find { it.isInRange(point) }
}
private fun mapToSensors(input: List<String>) =
input.map { it.split(": closest beacon is at ") }
.map { (point1, point2) ->
Sensor(
point1.substringAfter("Sensor at ").mapToPoint(),
point2.mapToPoint()
)
}
data class Sensor(val position: Point, val beacon: Point) {
fun distanceToBeacon(): Int {
return position.distance(beacon)
}
fun isInRange(other: Point): Boolean {
return position.distance(other) <= position.distance(beacon)
}
fun maxDistanceCovered(row: Int): Point {
return Point(position.x + abs(distanceToBeacon() - abs(row - position.y)), row)
}
}
data class Point(val x: Int, val y: Int) {
fun distance(other: Point): Int {
return abs(other.x - x) + abs(other.y - y)
}
}
private fun String.mapToPoint(): Point {
val (x, y) = split(", ")
return Point(x.substringAfter("x=").toInt(), y.substringAfter("y=").toInt())
}
}
| 0 | Kotlin | 0 | 0 | 76d5eea8ff0c96392f49f450660220c07a264671 | 2,947 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | freszu | 573,122,040 | false | {"Kotlin": 32507} | private val monkeyRegex = Regex(
"Monkey (\\d):\\n" +
" Starting items: ([\\d+, ]*)\\n" +
" Operation: new = old ([^\\n]*)\\n" +
" Test: divisible by (\\d+)\\n" +
" If true: throw to monkey (\\d+)\\n" +
" If false: throw to monkey (\\d+)"
)
private typealias WorryLevel = Long
private data class Monkey(
val items: MutableList<WorryLevel>,
val operation: (WorryLevel) -> WorryLevel,
val test: Long,
val trueTarget: Int,
val falseTarget: Int,
var inspectedItemsCounter: Long = 0
)
fun main() {
fun buildOperationFromString(fromString: String): (WorryLevel) -> WorryLevel {
val (opp, timesString) = fromString.split(" ")
val operation: (WorryLevel, WorryLevel) -> WorryLevel = when (opp) {
"*" -> Long::times
"+" -> Long::plus
else -> error("Unknown operation $opp")
}
val times = timesString.toLongOrNull()
return { old ->
if (times == null) operation(old, old)
else operation(old, times)
}
}
fun parseMonkeys(input: String) = input.split("\n\n")
.associate {
val (id, items, operation, test, trueTarget, falseTarget) = monkeyRegex.matchEntire(it)!!.destructured
id.toInt() to Monkey(
items.split(", ").map(String::toLong).toMutableList(),
buildOperationFromString(operation),
test.toLong(),
trueTarget.toInt(),
falseTarget.toInt()
)
}
fun runMonkeyRounds(monkeys: Map<Int, Monkey>, times: Int, worryLevelDivider: WorryLevel = 1): Long {
// part2 optimisation
val mod = monkeys.map { it.value.test }.reduce(Long::times)
repeat(times) {
monkeys.forEach { (_, monkey) ->
val newItems = monkey.items.map(monkey.operation).map { it / worryLevelDivider % mod }
val (trueItems, falseItems) = newItems.partition { it % monkey.test == 0L }
monkeys[monkey.trueTarget]?.items?.addAll(trueItems)
monkeys[monkey.falseTarget]?.items?.addAll(falseItems)
monkey.inspectedItemsCounter = monkey.inspectedItemsCounter + monkey.items.size
monkey.items.clear()
}
}
return monkeys.map { it.value.inspectedItemsCounter }.sortedDescending().take(2).reduce(Long::times)
}
val testInput = readInputAsString("Day11_test").dropLast(1)
val input = readInputAsString("Day11").dropLast(1)
check(runMonkeyRounds(parseMonkeys(testInput), 20, 3) == 10605L)
println("""Monkey business level: ${runMonkeyRounds(parseMonkeys(input), 20, 3)}""")
check(runMonkeyRounds(parseMonkeys(testInput), 10000) == 2713310158)
println("""Monkey business level: ${runMonkeyRounds(parseMonkeys(input), 10000)}""")
}
| 0 | Kotlin | 0 | 0 | 2f50262ce2dc5024c6da5e470c0214c584992ddb | 2,916 | aoc2022 | Apache License 2.0 |
kotlin/2021/round-1a/prime-time/src/main/kotlin/Solution.kt | ShreckYe | 345,946,821 | false | null | import kotlin.math.E
import kotlin.math.exp
import kotlin.math.pow
import kotlin.math.sqrt
fun main() {
val t = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val m = readLine()!!.toInt()
val pns = List(m) {
val lineInputs = readLine()!!.split(' ')
Pn(lineInputs[0].toInt(), lineInputs[1].toLong())
}
val y = ans(pns)
println("Case #${ti + 1}: $y")
}
fun ans(pns: List<Pn>): Long {
val upperBound = pns.sum()
val minProductGroupSum = (0..upperBound)
.first { exp(it.toDouble() / E) >= upperBound - it }
val maxProductGroupSum = (minProductGroupSum..upperBound).asSequence()
.takeWhile { maxPrime.toDouble().pow(it.toDouble() / maxPrime) <= upperBound - it }
.lastOrNull() ?: minProductGroupSum
val pnMap = LongArray(maxPrime + 1)
pns.forEach { pnMap[it.p] = it.n }
return (minProductGroupSum..maxProductGroupSum).asSequence()
.map { upperBound - it }
.firstOrNull { sumEqProduct ->
val (factorPns, remaining) = factorizeWithFactors(sumEqProduct, primesToMaxPrime)
if (remaining == 1L) {
val sumGroupPnMap = pnMap.copyOf().also {
for ((p, n) in factorPns) {
val rn = it[p] - n
if (rn >= 0)
it[p] = rn
else
return@firstOrNull false
}
}
val sumGroupPns =
sumGroupPnMap.asSequence().withIndex().map { Pn(it.index, it.value) }.filter { it.n > 0 }
sumGroupPns.sum() == sumEqProduct
} else false
} ?: 0
}
data class Pn(val p: Int, val n: Long)
fun List<Pn>.sum() = sumOf { it.p * it.n }
fun Sequence<Pn>.sum() = sumOf { it.p * it.n }
const val maxPrime = 499
val primesToMaxPrime = primesToWithSOE(maxPrime)
// copied from NumberTheory.kt
// see: https://en.wikipedia.org/wiki/Generation_of_primes#Complexity and https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
// see: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode
// O(n log(log(n)))
fun primesToWithSOE(n: Int): List<Int> {
// BooleanArray is slightly faster than BitSet
val a = BooleanArray(n + 1) { true }
for (i in 2..sqrt(n.toDouble()).toInt())
if (a[i]) {
var j = i.squared()
while (j <= n) {
a[j] = false
j += i
}
}
return (2..n).filter { a[it] }
}
data class FactorAndNum(val factor: Int, val num: Int)
data class FactorResult<R, N>(val result: R, val remaining: N)
// O(log(factor, n)) = O(log(n))
fun countFactors(n: Long, factor: Int): FactorResult<Int, Long> {
require(n > 0 && factor > 1)
return if (n % factor != 0L) FactorResult(0, n)
else {
val (nNum, remaining) = countFactors(n / factor, factor)
FactorResult(nNum + 1, remaining)
}
}
// O(max(primes.size, log(n)))
fun factorizeWithFactors(n: Long, factors: List<Int>): FactorResult<List<FactorAndNum>, Long> {
@Suppress("NAME_SHADOWING")
var n = n
val pns = ArrayList<FactorAndNum>(factors.size)
for (p in factors) {
val (num, remainingN) = countFactors(n, p)
if (num > 0) {
pns.add(FactorAndNum(p, num))
n = remainingN
if (n == 1L) break
}
}
pns.trimToSize()
return FactorResult(pns, n)
}
// copied from MathExtensions.kt
fun Int.squared(): Int =
this * this | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 3,561 | google-code-jam | MIT License |
src/day/_5/Day05.kt | Tchorzyksen37 | 572,924,533 | false | {"Kotlin": 42709} | package day._5
import readInput
class Day05(filePath: String) {
private val inputAsStringParts = readInput(filePath).joinToString("\n").split("\n\n")
private val numberOfStacks = inputAsStringParts[0].lines()
.last()
.split(" ")
.mapNotNull { if (it.isBlank()) null else it.toInt() }
.last()
private val moves = getMoves()
private fun readStacks(stacks: List<ArrayDeque<Char>>): List<ArrayDeque<Char>> {
inputAsStringParts[0].lines()
.map { line ->
line.mapIndexed { index, char ->
if (char.isLetter()) {
val stackNumber = index / 4
stacks[stackNumber].addLast(char)
}
}
}
return stacks
}
private fun getMoves(): List<Move> {
return inputAsStringParts[1].split("\n").map { Move.of(it) }
}
fun part1(): String {
val stacks = readStacks(List(numberOfStacks) { ArrayDeque() })
moves.forEach { step ->
repeat(step.quantity) {
val crate = stacks[step.source - 1].removeFirst()
stacks[step.target - 1].addFirst(crate)
}
}
return stacks.joinToString("") { it.first().toString() }
}
fun part2(): String {
val stacks = readStacks(List(numberOfStacks) { ArrayDeque() })
moves.forEach { step ->
stacks[step.source - 1]
.subList(0, step.quantity)
.asReversed()
.map { stacks[step.target - 1].addFirst(it) }
.map { stacks[step.source - 1].removeFirst() }
}
return stacks.joinToString("") { it.first().toString() }
}
data class Move(val quantity: Int, val source: Int, val target: Int) {
companion object {
private val NON_INT_DELIMITER = """(\D)+""".toRegex()
fun of(line: String): Move {
return line.extractInts().let { Move(it[0], it[1], it[2]) }
}
private fun String.extractInts(): List<Int> = this.split(NON_INT_DELIMITER).mapNotNull { it.toIntOrNull() }
}
}
}
fun main() {
val day05Test = Day05("day/_5/Day05_test")
check(day05Test.part1() == "CMZ")
check(day05Test.part2() == "MCD")
val day05 = Day05("day/_5/Day05")
println(day05.part1())
println(day05.part2())
}
| 0 | Kotlin | 0 | 0 | 27d4f1a6efee1c79d8ae601872cd3fa91145a3bd | 2,017 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day12.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | data class Position12(val r: Int, val c: Int)
data class HeightMap(val map: List<List<Char>>, val start: Position12, val end: Position12)
fun main() {
fun parse(input: List<String>): HeightMap {
var start: Position12? = null
var end: Position12? = null
for (rowIdx in input.indices) {
val row = input[rowIdx]
for (colIdx in row.indices) {
when (row[colIdx]) {
'S' -> start = Position12(rowIdx, colIdx)
'E' -> end = Position12(rowIdx, colIdx)
}
}
}
val map = input.map { it.toMutableList() }
map[start!!.r][start.c] = 'a'
map[end!!.r][end.c] = 'z'
return HeightMap(map.map { it.toList() }, start, end)
}
fun part1(input: List<String>): Int {
val map = parse(input)
return bfs(map.start, next = { p ->
sequence {
val row = p.r
val col = p.c
val height = map.map[row][col]
fun check(r2: Int, c2: Int): Position12? {
if (r2 in map.map.indices && c2 in map.map[r2].indices) {
val newHeight = map.map[r2][c2]
if (newHeight - height <= 1) {
return Position12(r2, c2)
}
}
return null
}
check(row - 1, col)?.let { yield(it) }
check(row + 1, col)?.let { yield(it) }
check(row, col - 1)?.let { yield(it) }
check(row, col + 1)?.let { yield(it) }
}
}, found = { p -> p == map.end })?.steps ?: -1
}
fun part2(input: List<String>): Int {
val map = parse(input)
return bfs(map.end, next = { p ->
sequence {
val row = p.r
val col = p.c
val height = map.map[row][col]
fun check(r2: Int, c2: Int): Position12? {
if (r2 in map.map.indices && c2 in map.map[r2].indices) {
val newHeight = map.map[r2][c2]
if (newHeight - height >= -1) {
return Position12(r2, c2)
}
}
return null
}
check(row - 1, col)?.let { yield(it) }
check(row + 1, col)?.let { yield(it) }
check(row, col - 1)?.let { yield(it) }
check(row, col + 1)?.let { yield(it) }
}
}, found = { p -> map.map[p.r][p.c] == 'a' })?.steps ?: -1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 2,958 | advent-of-code-2022 | Apache License 2.0 |
src/day21/Day21.kt | spyroid | 433,555,350 | false | null | package day21
import kotlin.system.measureTimeMillis
data class Die(var rolls: Int = 0) {
private fun roll() = ++rolls % 100
fun rolls(times: Int) = generateSequence { roll() }.take(times).sum()
}
data class Player(var space: Int, var score: Int = 0) {
fun move(steps: Int) {
space = (space + steps) % 10
score += space + 1
}
}
fun part1(s1: Int, s2: Int): Int {
val die = Die()
val p1 = Player(s1 - 1)
val p2 = Player(s2 - 1)
while (true) {
p1.move(die.rolls(3))
if (p1.score >= 1000) return p2.score * die.rolls
p2.move(die.rolls(3))
if (p2.score >= 1000) return p1.score * die.rolls
}
}
fun part2(s1: Int, s2: Int): Long {
val allRolls = mapOf(3 to 1L, 4 to 3L, 5 to 6L, 6 to 7L, 7 to 6L, 8 to 3L, 9 to 1L)
fun play(pos: List<Int>, scores: List<Int>, turn: Int): Pair<Long, Long> {
return allRolls.map { (roll, count) ->
val newPos = pos.toMutableList()
val newScores = scores.toMutableList()
newPos[turn] = (pos[turn] + roll) % 10
newScores[turn] = scores[turn] + newPos[turn] + 1
if (newScores[turn] >= 21) {
if (turn == 0) count to 0L else 0L to count
} else {
val nextResult = play(newPos, newScores, (turn + 1) % 2)
nextResult.first * count to nextResult.second * count
}
}.reduce { acc, p -> acc.first + p.first to acc.second + p.second }
}
val result = play(listOf(s1 - 1, s2 - 1), listOf(0, 0), 0)
return maxOf(result.first, result.second)
}
fun main() {
check(part1(4, 8) == 739785)
measureTimeMillis { print("⭐️ Part1: ${part1(7, 1)}") }.also { time -> println(" in $time ms") }
check(part2(4, 8) == 444356092776315)
measureTimeMillis { print("⭐️ Part2: ${part2(7, 1)}") }.also { time -> println(" in $time ms") }
}
| 0 | Kotlin | 0 | 0 | 939c77c47e6337138a277b5e6e883a7a3a92f5c7 | 1,917 | Advent-of-Code-2021 | Apache License 2.0 |
src/Day03.kt | maciekbartczak | 573,160,363 | false | {"Kotlin": 41932} | fun main() {
fun part1(input: List<String>): Int {
return input
.map {
val compartments = it.chunked(it.length / 2)
findDuplicateCharacter(compartments[0] to compartments[1])
}
.sumOf { calculatePriority(it) }
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map {
val firstDuplicates = findAllDuplicateCharacters(it[0] to it[1])
val secondDuplicates = findAllDuplicateCharacters(it[1] to it[2])
findDuplicateCharacter(
firstDuplicates.joinToString("") to secondDuplicates.joinToString("")
)
}.sumOf { calculatePriority(it) }
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
fun findDuplicateCharacter(strings: Pair<String, String>): Char {
val first = strings.first
val second = strings.second
first.forEach {
if (second.contains(it)) {
return it
}
}
return '-'
}
fun findAllDuplicateCharacters(strings: Pair<String, String>): Set<Char> {
val first = strings.first
val second = strings.second
val duplicates = mutableSetOf<Char>()
first.forEach {
if (second.contains(it)) {
duplicates.add(it)
}
}
return duplicates
}
fun calculatePriority(c: Char): Int {
return when {
c.isLowerCase() -> c.code - 96
c.isUpperCase() -> c.code - 38
else -> 0
}
} | 0 | Kotlin | 0 | 0 | 53c83d9eb49d126e91f3768140476a52ba4cd4f8 | 1,679 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/lucaszeta/adventofcode2020/day07/day07.kt | LucasZeta | 317,600,635 | false | null | package com.lucaszeta.adventofcode2020.day07
import com.lucaszeta.adventofcode2020.ext.getResourceAsText
fun main() {
val bags = parseData(getResourceAsText("/day07/rules-list.txt"))
val bagsThatContainShinyGold = countBagsThatCanContain(bags, "shiny gold")
val bagsInsideShinyGold = countIndividualBagsInside(bags, "shiny gold")
println("Bags that can contain shiny gold bag: %d".format(bagsThatContainShinyGold))
println("Bags inside shiny gold bag: %d".format(bagsInsideShinyGold))
}
fun countBagsThatCanContain(bags: List<Bag>, color: String): Int {
var bagsThatCanContainColor = 0
bags.forEach { bag ->
if (canContain(bag, color, bags)) {
bagsThatCanContainColor++
}
}
return bagsThatCanContainColor
}
fun countIndividualBagsInside(
bags: List<Bag>,
color: String,
firstLevel: Boolean = true
): Int {
bags.find { it.color == color }?.let { bag ->
if (bag.contents.isEmpty()) return if (firstLevel) 0 else 1
var count = if (firstLevel) 0 else 1
bag.contents.forEach { (color, quantity) ->
count += quantity * countIndividualBagsInside(bags, color, false)
}
return count
} ?: return 0
}
fun canContain(bag: Bag, targetColor: String, bags: List<Bag>): Boolean {
if (bag.contents.isEmpty()) return false
if (bag.contents.containsKey(targetColor)) {
return true
} else {
for (color in bag.contents.keys) {
bags.find { it.color == color }?.let {
if (canContain(it, targetColor, bags)) {
return true
}
}
}
return false
}
}
fun parseData(input: String): List<Bag> {
val colorInnerBagsDelimiter = " bags contain "
return input.split("\n")
.filter { it.isNotEmpty() }
.map { line ->
val allowedInnerBags = mutableMapOf<String, Int>()
val (color, allowedInnerBagsText) = line.split(colorInnerBagsDelimiter)
val result = "(\\d+) ([a-z ]*) bag(s)?([,.])"
.toRegex()
.findAll(allowedInnerBagsText)
result.forEach {
allowedInnerBags[it.groupValues[2]] = it.groupValues[1].toInt()
}
Bag(color, allowedInnerBags.toMap())
}
}
| 0 | Kotlin | 0 | 1 | 9c19513814da34e623f2bec63024af8324388025 | 2,344 | advent-of-code-2020 | MIT License |
src/day15/Day15.kt | JoeSkedulo | 573,328,678 | false | {"Kotlin": 69788} | package day15
import Runner
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
Day15Runner().solve()
}
class Day15Runner : Runner<Long>(
day = 15,
expectedPartOneTestAnswer = 26,
expectedPartTwoTestAnswer = 56000011
) {
override fun partOne(input: List<String>, test: Boolean): Long {
val sensors = sensors(input)
val sensorsAndBeacons = sensors.flatMap { sensor -> listOf(sensor, sensor.closestBeacon) }.toSet()
val y = if (test) {
10L
} else {
2000000L
}
return ranges(sensors, y = y)
.merge()
.sumOf { range -> range.last - range.first + 1 }
.minus(sensorsAndBeacons.count { it.y == y })
}
override fun partTwo(input: List<String>, test: Boolean): Long {
val sensors = sensors(input)
val maxCoord = if (test) {
20L
} else {
4000000L
}
return signal(candidates(sensors, maxCoord), maxCoord)
}
private fun signal(candidates: List<List<LongRange>>, maxCoord: Long) : Long {
return candidates.flatMapIndexed { y, ranges ->
ranges.merge()
.map { range -> range.first + range.last + 1 }
.map { x -> y to x }
}.first { (_, x) -> x <= maxCoord }
.let { (y, x) -> x * 4000000L + y }
}
private fun candidates(sensors: List<Sensor>, maxCoord: Long) : List<List<LongRange>> {
return buildList {
repeat(maxCoord.toInt()) { y ->
add(buildList {
sensors.forEach { sensor ->
val distance = sensor.manhattanDistance() - abs(y - sensor.y)
val min = max(0, (sensor.x - distance))
val max = min(maxCoord, (sensor.x + distance))
if (min <= max) {
add(min..max)
}
}
})
}
}
}
private fun ranges(sensors: List<Sensor>, y: Long) : List<LongRange> {
return buildList {
sensors.forEach { sensor ->
val distance = sensor.manhattanDistance() - abs(y - sensor.y)
if (distance >= 0) {
add((sensor.x - distance)..sensor.x + distance)
}
}
}
}
private fun List<LongRange>.merge(): List<LongRange> = let {ranges ->
val sortedRanges = ranges.sortedBy { it.first }
return buildList {
var currentRange: LongRange? = null
for (range in sortedRanges) {
if (currentRange == null) {
currentRange = range
}
currentRange = if (range.first <= currentRange.last + 1) {
LongRange(currentRange.first, maxOf(currentRange.last, range.last))
} else {
add(currentRange)
range
}
}
if (currentRange != null) {
add(currentRange)
}
}
}
private fun Sensor.manhattanDistance() : Long {
return manhattanDistance(
startX = x,
startY = y,
endX = closestBeacon.x,
endY = closestBeacon.y
)
}
private fun manhattanDistance(startX: Long, startY: Long, endX: Long, endY: Long): Long {
return abs(endX - startX) + abs(endY - startY)
}
private fun sensors(input: List<String>) : List<Sensor> {
return input.map { line ->
val (sensor, beacon) = line.split(":")
Sensor(
x = sensor.coordValue("x"),
y = sensor.coordValue("y"),
closestBeacon = Beacon(
x = beacon.coordValue("x"),
y = beacon.coordValue("y")
)
)
}
}
private fun String.coordValue(coord: String) : Long {
val subString = substring(indexOf(coord) + 2)
return if (subString.startsWith("-")) {
subString.drop(1)
.takeWhile { c -> c.isDigit() }.toLong() * -1
} else {
subString.takeWhile { c -> c.isDigit() }.toLong()
}
}
}
interface Coord {
val x: Long
val y: Long
}
data class Sensor(
override val x : Long,
override val y: Long,
val closestBeacon: Beacon
) : Coord
data class Beacon(
override val x : Long,
override val y: Long
) : Coord | 0 | Kotlin | 0 | 0 | bd8f4058cef195804c7a057473998bf80b88b781 | 4,577 | advent-of-code | Apache License 2.0 |
src/Day05.kt | TheOnlyTails | 573,028,916 | false | {"Kotlin": 9156} | fun getStackStringIndex(stackIndex: Int) = 4 * stackIndex + 1
fun parsing(input: List<String>): Pair<List<List<Int>>, MutableList<MutableList<Char>>> {
val (instructions, rawStacks) = input
.filter(String::isNotBlank)
.partition { it.startsWith("move") }
val stackCount = rawStacks.last().last().toString().toInt()
val stacks = (0 until stackCount)
.map {
rawStacks.dropLast(1)
.mapNotNull { l ->
l.getOrNull(getStackStringIndex(it))
}
.filter { it != ' ' }
.toMutableList()
}
.toMutableList()
return instructions.map { inst ->
inst.filter { it.isDigit() || it.isWhitespace() }
.trim()
.split(" ")
.filter(String::isNotBlank)
.map(String::toInt)
} to stacks
}
fun main() {
fun part1(input: List<String>): String {
val (instructions, stacks) = parsing(input)
for ((amount, from, to) in instructions) {
for (i in 0 until amount) {
stacks[to - 1].add(0, stacks[from - 1].removeFirst())
}
}
return stacks.joinToString("") { it.first().toString() }
}
fun part2(input: List<String>): String {
val (instructions, stacks) = parsing(input)
for ((amount, from, to) in instructions) {
val cache = mutableListOf<Char>()
for (i in 0 until amount) {
cache += stacks[from - 1].removeFirst()
}
stacks[to - 1].addAll(0, cache)
}
return stacks.joinToString("") { it.first().toString() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 685ce47586b6d5cea30dc92f4a8e55e688005d7c | 1,918 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | sabercon | 648,989,596 | false | null | fun main() {
fun modification1(mask: String, address: String, value: String): Map<String, String> {
return value.zip(mask) { v, m -> if (m == 'X') v else m }
.joinToString("")
.let { mapOf(address to it) }
}
fun modification2(mask: String, address: String, value: String): Map<String, String> {
return address.zip(mask) { a, m -> if (m == '0') a else m }
.fold(listOf("")) { acc, c ->
when (c) {
'X' -> acc.flatMap { listOf(it + '0', it + '1') }
else -> acc.map { it + c }
}
}.associateWith { value }
}
fun run(
mask: String,
memory: Map<Long, Long>,
instruction: String,
modificationFn: (String, String, String) -> Map<String, String>,
): Pair<String, Map<Long, Long>> {
if (instruction.startsWith("mask")) {
val newMask = instruction.split(" = ")[1]
return newMask to memory
}
val (addressStr, valueStr) = """mem\[(\d+)] = (\d+)""".toRegex().destructureGroups(instruction)
val address = addressStr.toLong().toString(2).padStart(36, '0')
val value = valueStr.toLong().toString(2).padStart(36, '0')
val newMemory = memory + modificationFn(mask, address, value)
.map { (k, v) -> k.toLong(2) to v.toLong(2) }
return mask to newMemory
}
fun run(instructions: List<String>, modificationFn: (String, String, String) -> Map<String, String>): Long {
return instructions
.fold("" to emptyMap<Long, Long>()) { (mask, memory), instruction ->
run(mask, memory, instruction, modificationFn)
}.second.values.sum()
}
val input = readLines("Day14")
run(input, ::modification1).println()
run(input, ::modification2).println()
}
| 0 | Kotlin | 0 | 0 | 81b51f3779940dde46f3811b4d8a32a5bb4534c8 | 1,874 | advent-of-code-2020 | MIT License |
08/part_two.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
import java.lang.Exception
fun readInput() : List<Display> {
return File("input.txt")
.readLines()
.map { Display(it) }
}
class Display(inputLine : String) {
companion object {
val UNIQUE_OUTPUT_SIZES = listOf(2, 3, 4, 7)
val INPUT_TO_OUTPUT_MAP = mapOf("abcefg" to 0,
"cf" to 1,
"acdeg" to 2,
"acdfg" to 3,
"bcdf" to 4,
"abdfg" to 5,
"abdefg" to 6,
"acf" to 7,
"abcdefg" to 8,
"abcdfg" to 9)
}
var input = listOf<String>()
var output = listOf<String>()
var digitSegmentUnionSize = mutableMapOf<Int, MutableList<Int>>()
init {
val (leftSide, rightSide) = inputLine.split('|')
input = leftSide.split(" ").filter { it.isNotEmpty() }.map { it.toCharArray().sorted().joinToString("") }
output = rightSide.split(" ").filter { it.isNotEmpty() }.map { it.toCharArray().sorted().joinToString("") }
for ((curSegments, curDigit) in INPUT_TO_OUTPUT_MAP) {
val segmentsUnionSize = mutableListOf<Int>()
for ((otherSegments, _) in INPUT_TO_OUTPUT_MAP) {
val segmentsUsed = curSegments + otherSegments
segmentsUsed.toCharArray().sort().toString()
val distinctUsed = segmentsUsed.toList().distinct().size
segmentsUnionSize.add(distinctUsed)
}
segmentsUnionSize.sort()
digitSegmentUnionSize[curDigit] = segmentsUnionSize
}
}
}
fun findDigitMatch(display: Display, curSegmentUnionSize : List<Int>) : Int {
for ((digit, knownSegmentUnionSize) in display.digitSegmentUnionSize) {
if (knownSegmentUnionSize == curSegmentUnionSize) {
return digit
}
}
throw Exception("Could not find corresponding digit")
}
fun calcSignalToDigitMap(display: Display) : Map<String, Int> {
val result = mutableMapOf<String, Int>()
for (curSegments in display.input) {
val segmentsUnionSize = mutableListOf<Int>()
for (otherSegments in display.input) {
val segmentsUsed = curSegments + otherSegments
segmentsUsed.toCharArray().sort().toString()
val distinctUsed = segmentsUsed.toList().distinct().size
segmentsUnionSize.add(distinctUsed)
}
segmentsUnionSize.sort()
result[curSegments] = findDigitMatch(display, segmentsUnionSize)
}
return result.toMap()
}
fun calcOutputValue(signalToDigitMap : Map<String, Int>, display : Display) : Int {
var result = 0
for (output in display.output) {
result = 10 * result + signalToDigitMap[output]!!
}
return result
}
fun solve(displays : List<Display>) : Int {
var result = 0
for (display in displays) {
val signalToDigitMap = calcSignalToDigitMap(display)
val outputValue = calcOutputValue(signalToDigitMap, display)
result += outputValue
}
return result
}
fun main() {
val displays = readInput()
val ans = solve(displays)
println(ans)
}
| 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 3,128 | advent-of-code-2021 | MIT License |
src/Day09.kt | xabgesagtx | 572,139,500 | false | {"Kotlin": 23192} | import kotlin.math.absoluteValue
fun main() {
val day = "Day09"
fun simulateRopeMovement(input: List<String>, numberOfTailElements: Int): Int {
return buildSet {
add(0 to 0)
var rope = List(numberOfTailElements + 1) { 0 to 0 }
for (command in input) {
rope.first().move(command).forEach { newHeadPosition ->
rope = rope.drop(1).fold(listOf(newHeadPosition)) { updatedRope, tailElement ->
updatedRope + tailElement.follow(updatedRope.last())
}
add(rope.last())
}
}
}.size
}
fun part1(input: List<String>): Int {
return simulateRopeMovement(input, 1)
}
fun part2(input: List<String>): Int {
return simulateRopeMovement(input, 9)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
println(part1(testInput))
check(part1(testInput) == 13)
val testInput2 = readInput("${day}_test2")
println(part2(testInput2))
check(part2(testInput2) == 36)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
private fun Pair<Int, Int>.move(command: String): List<Pair<Int, Int>> {
val (direction, steps) = command.split(" ")
return when (direction) {
"R" -> List(steps.toInt()) { first + it + 1 to second }
"L" -> List(steps.toInt()) { first - it - 1 to second }
"U" -> List(steps.toInt()) { first to second + it + 1 }
"D" -> List(steps.toInt()) { first to second - it - 1 }
else -> error("Unexpected command: $command")
}
}
private fun Pair<Int, Int>.follow(head: Pair<Int, Int>): Pair<Int, Int> {
val incFirst = (head.first - first).coerceIn(-1..1)
val incSecond = (head.second - second).coerceIn(-1..1)
incFirst.coerceIn(-1..1)
return when {
isTouching(head) -> this
else -> first + incFirst to second + incSecond
}
}
private fun Pair<Int, Int>.isTouching(other: Pair<Int, Int>): Boolean {
val xDiff = (this.first - other.first).absoluteValue
val yDiff = (this.second - other.second).absoluteValue
return xDiff < 2 && yDiff < 2
}
| 0 | Kotlin | 0 | 0 | 976d56bd723a7fc712074066949e03a770219b10 | 2,268 | advent-of-code-2022 | Apache License 2.0 |
src/Day18.kt | thorny-thorny | 573,065,588 | false | {"Kotlin": 57129} | import kotlin.math.abs
data class Cube(val x: Int, val y: Int, val z: Int) {
infix fun touches(other: Cube): Boolean {
val touchesX = abs(x - other.x) == 1 && y == other.y && z == other.z
val touchesY = abs(y - other.y) == 1 && x == other.x && z == other.z
val touchesZ = abs(z - other.z) == 1 && x == other.x && y == other.y
return touchesX || touchesY || touchesZ
}
fun min(other: Cube): Cube {
val minX = minOf(x, other.x)
val minY = minOf(y, other.y)
val minZ = minOf(z, other.z)
return Cube(minX, minY, minZ)
}
fun max(other: Cube): Cube {
val maxX = maxOf(x, other.x)
val maxY = maxOf(y, other.y)
val maxZ = maxOf(z, other.z)
return Cube(maxX, maxY, maxZ)
}
}
enum class SpaceType {
Unknown,
Water,
Lava,
}
fun main() {
fun parseCubes(input: List<String>): List<Cube> {
return input
.map {
val (x, y, z) = it.split(',').map(String::toInt)
Cube(x, y, z)
}
}
fun getCubesSurface(cubes: List<Cube>): Int {
val countedCubes = mutableListOf<Cube>()
return cubes.sumOf { cube ->
val cubeCoveredSides = countedCubes.count { cube touches it }
countedCubes.add(cube)
6 - 2 * cubeCoveredSides
}
}
fun part1(input: List<String>): Int {
return getCubesSurface(parseCubes(input))
}
fun part2(input: List<String>): Int {
val cubes = parseCubes(input)
val totalSurface = getCubesSurface(cubes)
var minCube = Cube(Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE)
var maxCube = Cube(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)
cubes.forEach {
minCube = minCube.min(it)
maxCube = maxCube.max(it)
}
val width = maxCube.x - minCube.x + 1
val height = maxCube.y - minCube.y + 1
val depth = maxCube.z - minCube.z + 1
val space = List(width) { xIndex ->
val x = minCube.x + xIndex
List(height) { yIndex ->
val y = minCube.y + yIndex
MutableList(depth) { zIndex ->
val z = minCube.z + zIndex
val isBoundaryCube = x == minCube.x || x == maxCube.x || y == minCube.y || y == maxCube.y || z == minCube.z || z == maxCube.z
when {
isBoundaryCube -> when {
cubes.find { it.x == x && it.y == y && it.z == z } != null -> SpaceType.Lava
else -> SpaceType.Water
}
else -> SpaceType.Unknown
}
}
}
}
do {
var updated = 0
(minCube.x + 1 until maxCube.x).forEach { x ->
val xIndex = x - minCube.x
(minCube.y + 1 until maxCube.y).forEach { y ->
val yIndex = y - minCube.y
(minCube.z + 1 until maxCube.z).forEach { z ->
val zIndex = z - minCube.z
if (space[xIndex][yIndex][zIndex] == SpaceType.Unknown) {
if (cubes.find { it.x == x && it.y == y && it.z == z } != null) {
space[xIndex][yIndex][zIndex] = SpaceType.Lava
updated += 1
} else {
val touchesWater = (1..6).any { d ->
val dx = if (d in 1..2) (d - 1) * 2 - 1 else 0
val dy = if (d in 3..4) (d - 3) * 2 - 1 else 0
val dz = if (d in 5..6) (d - 5) * 2 - 1 else 0
space[xIndex + dx][yIndex + dy][zIndex + dz] == SpaceType.Water
}
if (touchesWater) {
space[xIndex][yIndex][zIndex] = SpaceType.Water
updated += 1
}
}
}
}
}
}
} while (updated > 0)
val holes = mutableListOf<Cube>()
(minCube.x + 1 until maxCube.x).forEach { x ->
val xIndex = x - minCube.x
(minCube.y + 1 until maxCube.y).forEach { y ->
val yIndex = y - minCube.y
(minCube.z + 1 until maxCube.z).forEach { z ->
val zIndex = z - minCube.z
if (space[xIndex][yIndex][zIndex] == SpaceType.Unknown) {
holes.add(Cube(x, y, z))
}
}
}
}
val holesSurface = getCubesSurface(holes)
return totalSurface - holesSurface
}
val testInput = readInput("Day18_test")
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 843869d19d5457dc972c98a9a4d48b690fa094a6 | 5,146 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/nekomatic/types/graph/Sort.kt | nekomatic | 124,664,292 | false | null | package com.nekomatic.types.graph
import com.nekomatic.types.Option
import com.nekomatic.types.map
fun <V : Any> IGraph<V>.khanSort(): List<V> {
val zeroMap =
this.vertices.map { it to 0 }.toMap()
val inDegreeMap: Map<V, Int> = zeroMap + this.edges.asSequence().groupBy { it.second }.map { (n, l) -> n to l.size }.toList()
val startNodes = inDegreeMap.filter { it.value == 0 }.keys.toList()
fun topologicalSort(sNodes: List<V>, inDegMap: Map<V, Int>): List<V> =
if (sNodes.isEmpty()) listOf<V>()
else {
val nodeMs = this.neighbours(sNodes.first())
val newMCounts = nodeMs.map { n -> n to (inDegMap[n]!! - 1) }.toMap()
val newSNodes = sNodes.drop(1) + nodeMs.filter { newMCounts[it] == 0 }
listOf(sNodes.first()) + topologicalSort(newSNodes, inDegMap + newMCounts)
}
return topologicalSort(startNodes, inDegreeMap)
}
fun <V : Any> IGraph<V>.dfsSort(): List<V> {
data class DfsStep<V : Any>(val visited: Set<V> = setOf<V>(), val sort: List<V> = listOf<V>())
fun sort(node: V, dfsStep: DfsStep<V>): DfsStep<V> =
if (dfsStep.visited.contains(node)) dfsStep
else {
val preDfsStep = dfsStep.copy(visited = dfsStep.visited + node)
val postDfsStep = this.neighbours(node).fold(preDfsStep) { step, n -> sort(n, step) }
postDfsStep.copy(sort = listOf(node) + postDfsStep.sort)
}
return this.vertices.fold(DfsStep<V>()) { step, n -> sort(n, step) }.sort
}
| 1 | Kotlin | 0 | 1 | 05be9f022339619878bb5a8fe0719c7540f97b0a | 1,581 | types | MIT License |
src/Day09.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | import kotlin.math.abs
fun main() {
fun solve(input: List<String>, knotCnt: Int): Int {
val dirMap = mapOf(
"L" to (0 to -1),
"R" to (0 to 1),
"U" to (-1 to 0),
"D" to (1 to 0)
)
val tailPosSet = mutableSetOf("0_0")
val positions = Array(knotCnt) { Array(2) { 0 } }
fun isNeighbor(i: Int, j: Int): Boolean {
val (ix, iy) = positions[i]
val (jx, jy) = positions[j]
return abs(ix - jx) <= 1 && abs(iy - jy) <= 1
}
fun move(dir: String, step: Int) {
val (dx, dy) = dirMap[dir]!!
repeat(step) {
positions[0][0] += dx
positions[0][1] += dy
for (i in 1 until positions.size) {
if (isNeighbor(i - 1, i)) break
if (positions[i][0] != positions[i - 1][0]) positions[i][0] += (positions[i - 1][0] - positions[i][0]) / abs(positions[i - 1][0] - positions[i][0])
if (positions[i][1] != positions[i - 1][1]) positions[i][1] += (positions[i - 1][1] - positions[i][1]) / abs(positions[i - 1][1] - positions[i][1])
tailPosSet += "${positions[knotCnt - 1][0]}_${positions[knotCnt - 1][1]}"
}
}
}
input.forEach { line ->
val splits = line.split(" ")
move(splits[0], splits[1].toInt())
}
return tailPosSet.size
}
fun part1(input: List<String>): Int {
return solve(input, 2)
}
fun part2(input: List<String>): Int {
return solve(input, 10)
}
println(part1(readInput("data/Day09_test")))
println(part1(readInput("data/Day09")))
println(part2(readInput("data/Day09_test")))
println(part2(readInput("data/Day09")))
}
| 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 1,626 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1201/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1201
/**
* LeetCode page: [1201. Ugly Number III](https://leetcode.com/problems/ugly-number-iii/);
*/
class Solution {
/* Complexity:
* Time O(Log(NMK)) and Space O(1) where N, M, K equal a, b and c;
*/
fun nthUglyNumber(n: Int, a: Int, b: Int, c: Int): Int {
val divisors = Divisors(a.toLong(), b.toLong(), c.toLong())
return getNthUglyNumber(n, divisors)
}
private data class Divisors(val d1: Long, val d2: Long, val d3: Long) {
val lcmD1D2 = leastCommonMultiple(d1, d2)
val lcmD2D3 = leastCommonMultiple(d2, d3)
val lcmD3D1 = leastCommonMultiple(d3, d1)
val lcmD1D2D3 = leastCommonMultiple(lcmD1D2, d3)
private fun leastCommonMultiple(long1: Long, long2: Long): Long {
require(long1 > 0L && long2 > 0L) { "Require positive arguments." }
val gcd = greatestCommonDivisor(long1, long2)
return long1 * long2 / gcd
}
private fun greatestCommonDivisor(long1: Long, long2: Long): Long {
require(long1 > 0L && long2 > 0L) { "Require positive arguments." }
val (smaller, larger) = if (long1 < long2) long1 to long2 else long2 to long1
return if (larger % smaller == 0L) smaller else euclideanGcdAlgorithm(smaller, larger)
}
private tailrec fun euclideanGcdAlgorithm(smaller: Long, larger: Long): Long {
require(smaller <= larger)
return if (smaller == 0L) larger else euclideanGcdAlgorithm(larger % smaller, smaller)
}
}
private fun getNthUglyNumber(n: Int, divisors: Divisors): Int {
val numberOfUglyWithinLcm = getNumberOfUglyWithin(divisors.lcmD1D2D3, divisors)
var nThUgly = (n / numberOfUglyWithinLcm) * divisors.lcmD1D2D3
val rem = n % numberOfUglyWithinLcm
if (rem != 0L) {
val remThUgly = getNthUglyNumberWithinLcm(rem.toInt(), divisors)
nThUgly += remThUgly
}
return nThUgly.toInt()
}
private fun getNumberOfUglyWithin(value: Long, divisors: Divisors): Long {
val naiveCount =
divisors.run { value / d1 + value / d2 + value / d3 }
val duplication =
divisors.run { -value / lcmD1D2D3 + value / lcmD1D2 + value / lcmD2D3 + value / lcmD3D1 }
return naiveCount - duplication
}
private fun getNthUglyNumberWithinLcm(n: Int, divisors: Divisors): Long {
var leftBound = 1L
var rightBound = divisors.lcmD1D2D3
while (leftBound <= rightBound) {
val midValue = (leftBound + rightBound) shr 1
val numberOfUglyAtMid = getNumberOfUglyWithin(midValue, divisors)
if (numberOfUglyAtMid >= n) rightBound = midValue - 1 else leftBound = midValue + 1
}
return leftBound
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,848 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day08B.kt | zsmb13 | 572,719,881 | false | {"Kotlin": 32865} | @Suppress("DuplicatedCode")
fun main() {
fun left(x: Int, y: Int) = (x - 1 downTo 0).asSequence().map { x -> x to y }
fun right(x: Int, y: Int, xMax: Int) = (x + 1..xMax).asSequence().map { x -> x to y }
fun top(x: Int, y: Int) = (y - 1 downTo 0).asSequence().map { y -> x to y }
fun bottom(x: Int, y: Int, yMax: Int) = (y + 1..yMax).asSequence().map { y -> x to y }
fun part1(testInput: List<String>): Int {
val heights = testInput.map { line -> line.map(Char::digitToInt) }
val xValues = testInput.first().indices
val yValues = testInput.indices
return yValues.sumOf { y ->
xValues.count { x ->
val shorterThanCurrent: (Pair<Int, Int>) -> Boolean =
{ (nx, ny) -> heights[ny][nx] < heights[y][x] }
left(x, y).all(shorterThanCurrent) ||
top(x, y).all(shorterThanCurrent) ||
right(x, y, xValues.last).all(shorterThanCurrent) ||
bottom(x, y, yValues.last).all(shorterThanCurrent)
}
}
}
fun part2(testInput: List<String>): Int {
val heights = testInput.map { line -> line.map(Char::digitToInt) }
val xValues = testInput.first().indices
val yValues = testInput.indices
return yValues.maxOf { y ->
xValues.maxOf { x ->
fun Sequence<Pair<Int, Int>>.viewingDistance(): Int {
return when (val blocker = indexOfFirst { (nx, ny) -> heights[ny][nx] >= heights[y][x] }) {
-1 -> count()
else -> blocker + 1
}
}
left(x, y).viewingDistance() *
top(x, y).viewingDistance() *
right(x, y, xValues.last).viewingDistance() *
bottom(x, y, yValues.last).viewingDistance()
}
}
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 6 | 32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35 | 2,161 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | fun main() {
val input = readInput("Day03")
fun RowCol.isOutOfBounds(): Boolean {
val inRange = first >= 0 && first < input.size && second >= 0 && second < input[first].length
return !inRange
}
fun RowCol.isSymbol(): Boolean {
if (!isOutOfBounds()) {
val c = input[first][second]
return !c.isDigit() && c != '.'
}
return false
}
fun RowCol.isPartNumber(): Boolean {
if (input[first][second].isDigit()) {
((first - 1)..(first + 1)).forEach { r ->
((second - 1)..(second + 1)).forEach { c ->
if ((r to c).isSymbol())
return true
}
}
}
return false
}
fun findNumber(row: Int): List<Int> {
val line = input[row]
val regex = "\\d+".toRegex()
return regex.findAll(line).filter {
it.range.forEach { col ->
if ((row to col).isPartNumber()) {
return@filter true
}
}
return@filter false
}.map { it.value.toInt() }.toList()
}
fun RowCol.isPartNumber2(): RowCol? {
if (input[first][second].isDigit()) {
((first - 1)..(first + 1)).forEach { r ->
((second - 1)..(second + 1)).forEach { c ->
if ((r to c).isSymbol())
return r to c
}
}
}
return null
}
fun findNumber2(row: Int): List<Pair<Int, RowCol>> {
val line = input[row]
val regex = "\\d+".toRegex()
return regex.findAll(line).mapNotNull { mr ->
mr.range.forEach { col ->
(row to col).isPartNumber2()?.let {
return@mapNotNull mr.value.toInt() to it
}
}
null
}.toList()
}
fun part1(input: List<String>): Int {
return input.indices.flatMap { findNumber(it) }.sum()
}
fun part2(input: List<String>): Int {
return input.indices.flatMap { findNumber2(it) }
.filter { (_, rc) -> input[rc.first][rc.second] == '*' }
.groupBy { it.second }
.filterValues { it.size == 2 }
.values.sumOf { it.map { it.first }.reduce { acc, it -> acc * it } }
}
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 2,506 | aoc-2023 | Apache License 2.0 |
src/Day13.kt | RandomUserIK | 572,624,698 | false | {"Kotlin": 21278} | private object Parser {
fun from(input: String): Node =
from(
input
.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex())
.filter { it != "," && it.isNotBlank() }
.iterator()
)
fun from(input: Iterator<String>): Node {
val nodes = mutableListOf<Node>()
while (input.hasNext()) {
when (val token = input.next()) {
"[" -> nodes.add(from(input = input))
"]" -> return ListNode(nodes = nodes)
else -> nodes.add(NumberNode(value = token.toInt()))
}
}
return ListNode(nodes = nodes)
}
}
private abstract class Node : Comparable<Node>
private data class ListNode(val nodes: List<Node>) : Node() {
override fun compareTo(other: Node): Int =
when (other) {
is NumberNode -> compareTo(other.toListNode())
is ListNode -> nodes
.zip(other.nodes)
.map { it.first.compareTo(it.second) }
.firstOrNull { it != 0 }
?: nodes.size.compareTo(other.nodes.size)
else -> throw UnsupportedOperationException("Input is of another unknown Node subtype.")
}
}
private data class NumberNode(val value: Int) : Node() {
fun toListNode() = ListNode(nodes = listOf(this))
override fun compareTo(other: Node): Int =
when (other) {
is NumberNode -> value.compareTo(other.value)
is ListNode -> toListNode().compareTo(other)
else -> throw UnsupportedOperationException("Input is of another unknown Node subtype.")
}
}
fun main() {
fun part1(input: List<String>) =
input
.asSequence()
.filterNot { it.isBlank() }
.map { Parser.from(it) }
.chunked(2)
.mapIndexed { index, pair ->
if (pair.first() < pair.last()) index + 1 else 0
}
.sum()
fun part2(input: List<String>): Int {
val dividerNode1 = Parser.from("[[2]]")
val dividerNode2 = Parser.from("[[6]]")
return input
.filterNot { it.isBlank() }
.map { Parser.from(it) }
.plus(listOf(dividerNode1, dividerNode2))
.sorted()
.let {
(it.indexOf(dividerNode1) + 1) * (it.indexOf(dividerNode2) + 1)
}
}
val input = readInput("inputs/day13_input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | f22f10da922832d78dd444b5c9cc08fadc566b4b | 2,063 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/y2023/day06/Day06.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2023.day06
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
data class Race(
val duration: Int,
val distance: Long
)
fun input1(): List<Race> {
val inputLines = AoCGenerics.getInputLines("/y2023/day06/input.txt")
val timeLine = inputLines[0].split(":")[1].trim()
val distanceLine = inputLines[1].split(":")[1].trim()
val times = timeLine.split(" ").filter { it != "" }.map { it.toInt() }
val distances = distanceLine.split(" ").filter { it != "" }.map { it.toLong() }
return times.mapIndexed { index, i ->
Race(
duration = i,
distance = distances[index]
)
}
}
fun input2(): Race {
val inputLines = AoCGenerics.getInputLines("/y2023/day06/input.txt")
val timeLine = inputLines[0].split(":")[1].trim()
val distanceLine = inputLines[1].split(":")[1].trim()
val times = timeLine.split(" ").filter { it != "" }
val distances = distanceLine.split(" ").filter { it != "" }
return Race(
duration = times.joinToString("").toInt(),
distance = distances.joinToString("").toLong()
)
}
fun part1() =
input1().map { race ->
var winPossibilities = 0
repeat(race.duration) {chargeTime ->
val way = (race.duration - chargeTime) * chargeTime
if (way > race.distance) winPossibilities++
}
winPossibilities
}.reduce(Int::times)
fun part2(): Int {
val race = input2()
var winPossibilities = 0
repeat(race.duration) {chargeTime ->
val way = (race.duration.toLong() - chargeTime) * chargeTime
if (way > race.distance) winPossibilities++
}
return winPossibilities
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 1,753 | AdventOfCode | MIT License |
src/year2016/day01/Day01.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2016.day01
import check
import readInput
import kotlin.math.abs
fun main() {
check(part1(listOf("R2, L3")), 5)
check(part1(listOf("R2, R2, R2")), 2)
check(part1(listOf("R5, L5, R5, R3")), 12)
check(part2(listOf("R8, R4, R4, R8")), 4)
val input = readInput("2016", "Day01")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
var dir = Dir.U
val path = mutableListOf(Pos(0, 0))
for ((turn, steps) in input.parseInstructions()) {
dir = dir.turn(turn)
path += path.last().move(dir, steps)
}
return abs(path.last().x) + abs(path.last().y)
}
private fun part2(input: List<String>): Int {
var dir = Dir.U
val path = mutableListOf(Pos(0, 0))
for ((turn, steps) in input.parseInstructions()) {
dir = dir.turn(turn)
path += path.last().move(dir, steps)
}
return path.groupBy { it }.entries.first { it.value.size > 1 }.key.let { (x, y) -> abs(x) + abs(y) }
}
private fun List<String>.parseInstructions() = first().split(", ").map { instruction ->
val turn = Dir.valueOf(instruction.first().toString())
val steps = instruction.drop(1).toInt()
turn to steps
}
private enum class Dir {
U, D, L, R;
fun turn(dir: Dir): Dir {
if (dir == L) {
return when (this) {
U -> L
L -> D
D -> R
R -> U
}
}
if (dir == R) {
return when (this) {
U -> R
R -> D
D -> L
L -> U
}
}
error("Cannot turn to $dir")
}
}
private data class Pos(val x: Int, val y: Int) {
fun move(dir: Dir): Pos {
return when (dir) {
Dir.U -> copy(y = y + 1)
Dir.D -> copy(y = y - 1)
Dir.L -> copy(x = x + 1)
Dir.R -> copy(x = x - 1)
}
}
fun move(dir: Dir, steps: Int): List<Pos> {
val path = mutableListOf<Pos>()
repeat(steps) {
path += (path.lastOrNull() ?: this).move(dir)
}
return path
}
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 2,167 | AdventOfCode | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.