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/Day12.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | fun main() {
class Terrain constructor(input: List<String>) {
val distances: HashMap<Point, Int> = HashMap()
var queue: ArrayDeque<Point> = ArrayDeque()
var heightmap: List<List<Char>> = input.map { it.toList() }
fun enqueue(point: Point, distance: Int) {
if (distances[point] == null || distances[point]!! > distance) {
queue += point
distances[point] = distance
}
}
fun find(c: Char): Point {
heightmap.forEach { x, y ->
if (heightmap[x][y] == c) {
return Point(x, y)
}
}
error("Not found $c")
}
fun height(point: Point): Int {
val height = heightmap[point.x][point.y]
return when (height) {
'S' -> 0
'E' -> 'z' - 'a'
else -> height - 'a'
}
}
fun minSteps(start: Point, end: Point): Int {
enqueue(start, 0)
while (queue.isNotEmpty()) {
val point = queue.removeFirst()
val distance = distances[point]!! + 1
val height = height(point)
walk(Point(point.x-1, point.y), distance, height)
walk(Point(point.x+1, point.y), distance, height)
walk(Point(point.x, point.y-1), distance, height)
walk(Point(point.x, point.y+1), distance, height)
}
return distances[end] ?: Int.MAX_VALUE
}
fun walk(p: Point, distance: Int, height: Int) {
if (p.x !in heightmap.indices || p.y !in 0 until heightmap[0].size) return
if (height <= height(p) + 1) {
enqueue(p, distance)
}
}
}
fun part1(input: List<String>): Int {
val terrain = Terrain(input)
val start = terrain.find('E')
val end = terrain.find('S')
return terrain.minSteps(start, end)
}
fun part2(input: List<String>): Int {
val endingPoints = mutableListOf<Point>()
val terrain = Terrain(input)
terrain.heightmap
.forEach { x, y ->
val c = terrain.heightmap[x][y]
if (c == 'a' || c == 'S') {
endingPoints += Point(x, y)
}
}
val start = terrain.find('E')
terrain.minSteps(start, endingPoints[0])
return endingPoints.minOf { terrain.distances[it] ?: Int.MAX_VALUE }
}
val input = readInput("inputs/Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 2,651 | aoc-2022 | Apache License 2.0 |
src/Day12.kt | RogozhinRoman | 572,915,906 | false | {"Kotlin": 28985} | fun main() {
fun getNeighbours(currentNode: Pair<Int, Int>, grid: Array<CharArray>): MutableSet<Pair<Int, Int>> {
val cord = arrayOf(0, 1, 0, -1, 0)
val neighbours = mutableSetOf<Pair<Int, Int>>()
for (i in 0 until cord.lastIndex) {
val newX = currentNode.first + cord[i]
val newY = currentNode.second + cord[i + 1]
if (newX < 0 || newX >= grid.size || newY < 0 || newY >= grid.first().size) continue
neighbours.add(Pair(newX, newY))
}
return neighbours
}
class Path(val currentCoordinate: Pair<Int, Int>, val steps: Int)
fun getStepsNumber(startNode: Pair<Int, Int>, grid: Array<CharArray>): Int {
val visited = mutableSetOf<Pair<Int, Int>>()
val queue = ArrayDeque<Path>()
queue.addLast(Path(startNode, 1))
while (queue.isNotEmpty()) {
val currentNode = queue.removeFirst()
val currentCoordinates = currentNode.currentCoordinate
for (neighbour in getNeighbours(currentCoordinates, grid)) {
if (visited.contains(currentCoordinates)) continue
val currentItem = grid[currentCoordinates.first][currentCoordinates.second]
if (currentItem.code + 1 < grid[neighbour.first][neighbour.second].code ||
(grid[neighbour.first][neighbour.second] == 'E' && currentItem.code < 'y'.code)
) continue
if (grid[neighbour.first][neighbour.second] == 'E') return currentNode.steps
queue.addLast(Path(neighbour, currentNode.steps + 1))
}
visited.add(currentCoordinates)
}
return Int.MAX_VALUE
}
fun part1(input: List<String>): Int {
val grid = Array(input.size) { CharArray(input.first().length) }
var startI = 0
var startJ = 0
for ((i, line) in input.withIndex()) {
for ((j, symb) in line.withIndex()) {
if (symb == 'S') {
startI = i
startJ = j
grid[i][j] = 'a'
continue
}
grid[i][j] = symb
}
}
return getStepsNumber(Pair(startI, startJ), grid)
}
fun part2(input: List<String>): Int {
val grid = Array(input.size) { CharArray(input.first().length) }
val startNodes = mutableListOf<Pair<Int, Int>>()
for ((i, line) in input.withIndex()) {
for ((j, symb) in line.withIndex()) {
if (symb == 'S') {
grid[i][j] = 'a'
startNodes.add(Pair(i, j))
continue
}
grid[i][j] = symb
if (symb == 'a') startNodes.add(Pair(i, j))
}
}
return startNodes.minOf { getStepsNumber(it, grid) }
}
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 | 1 | 6375cf6275f6d78661e9d4baed84d1db8c1025de | 3,110 | AoC2022 | Apache License 2.0 |
src/Day11.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | fun main() {
class Monkey(
val holding: MutableList<Long>,
val operation: (Long) -> Long,
val test: Long,
val target: Pair<Long, Long>,
var throwCount: Long = 0
) {
fun inspect(): List<Pair<Long, Long>> = holding
.map(operation)
.map { it / 3 }
.map {
it.takeIf { it % test == 0L }
?.let { Pair(target.first, it) }
?: Pair(target.second, it)
}.also {
throwCount += it.size
holding.clear()
}
fun inspect(lcm: Long, items: List<Long>): List<Pair<Long, Long>> = items
.map(operation)
.map { it.mod(lcm) }
.map {
it.takeIf { it.mod(test) == 0L }
?.let { Pair(target.first, it) }
?: Pair(target.second, it)
}.also {
throwCount += it.size
holding.clear()
}
fun take(item: Long) {
holding.add(item)
}
override fun toString(): String {
return "Monkey(holding=$holding, test=$test, target=$target, throwCount=$throwCount)"
}
}
fun parseOperation(formula: String): (Long) -> Long {
val tokens = formula.split(" ")
val operator = tokens[1]
val operand = if (tokens[2] == "old") 0 else tokens[2].toLong()
return if (operand == 0L) when (operator) {
"+" -> { i -> i + i }
"*" -> { i -> i * i }
else -> { i -> i }
} else when (operator) {
"+" -> { i -> i + operand }
"-" -> { i -> i - operand }
"*" -> { i -> i * operand }
"/" -> { i -> i / operand }
else -> { i -> i }
}
}
fun parseMonkey(lines: List<String>): Monkey {
val items = lines[0].split(": ")[1].split(", ").map { it.toLong() }
val operation = parseOperation(lines[1].split("= ")[1])
val test = lines[2].split(" ")
.last()
.toLong()
val targets = lines[3].split(" ").last().toLong() to lines[4].split(" ").last().toLong()
return Monkey(items.toMutableList(), operation, test, targets)
}
fun parseMonkeys(input: List<String>): Map<Long, Monkey> {
val monkeys = mutableMapOf<Long, Monkey>()
input.forEachIndexed { index, line ->
if (line.startsWith("Monkey")) {
val id = line.split(" ")[1][0].digitToInt().toLong()
monkeys[id] = parseMonkey(input.drop(index + 1).takeWhile { it.isNotBlank() })
}
}
return monkeys.toMap()
}
fun part1(input: List<String>): Long {
val monkeys: Map<Long, Monkey> = parseMonkeys(input)
repeat(20) {
monkeys.forEach { (_, v) ->
val thrown = v.inspect()
thrown.forEach { (i, value) -> monkeys[i]?.take(value) }
}
}
return monkeys.map { it.value.throwCount }.sortedDescending().let { it[0] * it[1] }
}
fun part2(input: List<String>): Long {
val monkeys: Map<Long, Monkey> = parseMonkeys(input)
val lcm = monkeys.values.map { it.test }
.reduce { acc, i -> lcm(acc, i) }
val equalRound = mutableListOf<Pair<Int, Long>>()
repeat(10000) { round ->
monkeys.values.forEach {
val items = it.holding.toList()
it.inspect(lcm, items)
.forEach { (i, value) ->
monkeys[i]?.take(value)
}
}
if (monkeys[1]!!.throwCount == monkeys[2]!!.throwCount && round > 70) {
equalRound.add((round + 1) to (monkeys[1]?.throwCount ?: 0L))
}
}
return monkeys.map { it.value.throwCount }.sortedDescending().let { it[0] * it[1] }
}
val testInput = readInput("Day11_test")
checkEquals(part1(testInput), 10605L)
checkEquals(part2(testInput), 2_713_310_158L)
val input = readInput("Day11")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 4,178 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2021/day5/Venting.kt | arnab | 75,525,311 | false | null | package aoc2021.day5
import kotlin.math.absoluteValue
object Venting {
data class Point(val x: Int, val y: Int) {
companion object {
fun from(data: String): Point {
val x = data.split(",").first().toInt()
val y = data.split(",").last().toInt()
return Point(x, y)
}
}
}
fun parse(data: String): List<Pair<Point, Point>> = data.split("\n")
.map {
val left = Point.from(it.split(" -> ").first())
val right = Point.from(it.split(" -> ").last())
Pair(left, right)
}
fun countDangerousPoints(lines: List<Pair<Point, Point>>): Int {
val points = lines.fold(mutableMapOf<Point, Int>()) { counts, (start, end) ->
if (start.x == end.x) {
IntRange.from(start.y, end.y).forEach { y ->
val point = Point(start.x, y)
counts[point] = counts.getOrDefault(point, 0) + 1
}
}
if (start.y == end.y) {
IntRange.from(start.x, end.x).forEach { x ->
val point = Point(x, start.y)
counts[point] = counts.getOrDefault(point, 0) + 1
}
}
counts
}
return points.values.count { it >= 2 }
}
fun countDangerousPointsV2(lines: List<Pair<Point, Point>>): Int {
val points = lines.fold(mutableMapOf<Point, Int>()) { counts, (start, end) ->
findPointsAlong(start, end).forEach { point ->
counts[point] = counts.getOrDefault(point, 0) + 1
}
counts
}
return points.values.count { it >= 2 }
}
private fun findPointsAlong(start: Point, end: Point): List<Point> {
val xIterator = when {
start.x < end.x -> (start.x..end.x).iterator()
start.x > end.x -> (start.x downTo end.x).iterator()
else -> generateSequence { start.x }.iterator()
}
val yIterator = when {
start.y < end.y -> (start.y..end.y).iterator()
start.y > end.y -> (start.y downTo end.y).iterator()
else -> generateSequence { start.y }.iterator()
}
val pointsAlongDiagonal = mutableListOf<Point>()
while (xIterator.hasNext() && yIterator.hasNext()) {
pointsAlongDiagonal.add(Point(xIterator.next(), yIterator.next()))
}
return pointsAlongDiagonal
}
}
private fun IntRange.Companion.from(a: Int, b: Int): IntRange = listOf(a, b).sorted().let { nums ->
nums.first()..nums.last()
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 2,642 | adventofcode | MIT License |
src/Day12.kt | astrofyz | 572,802,282 | false | {"Kotlin": 124466} | import kotlin.math.max
fun main() {
fun parseInput(input: List<String>): Pair<MutableList<MutableList<Char>>, Pair<Pair<Int, Int>, Pair<Int, Int>>> {
var startPos = Pair(-1, -1)
var endPos = Pair(-1, -1)
var maze = input.mapIndexed{row, itRow -> itRow.toMutableList()
.also { if ('S' in it) {startPos = Pair(row, it.indexOf('S'))}
if ('E' in it){endPos = Pair(row, it.indexOf('E'))}
}
}.toMutableList()
maze[endPos.first][endPos.second] = 'z'
return Pair(maze, Pair(startPos, endPos))
}
fun part1(input: List<String>){
var (maze, startEnd) = parseInput(input)
var (startPos, endPos) = startEnd
var allPoints = mutableListOf<Pair<Int, Int>>()
for (i in 0 until maze.size){
for (j in 0 until maze[0].size){
allPoints.add(Pair(i, j))
}
}
var visitedPoints = mutableMapOf<Pair<Int, Int>, Int>()
var distances = mutableMapOf<Pair<Int, Int>, Int>()
var nextPoints = mutableListOf(Pair(startPos.first-1, startPos.second),
Pair(startPos.first+1, startPos.second),
Pair(startPos.first, startPos.second-1),
Pair(startPos.first, startPos.second+1))
.filter { (it.first in 0..maze.size)&&(it.second in 0..maze[0].size) }
.filter { maze[it.first][it.second] == 'a' }.toMutableList()
var curPos = startPos
distances[curPos] = 0
fun MutableList<Pair<Int, Int>>.update(pos: Pair<Int, Int>): MutableList<Pair<Int, Int>> {
return mutableListOf(Pair(pos.first-1, pos.second),
Pair(pos.first+1, pos.second),
Pair(pos.first, pos.second-1),
Pair(pos.first, pos.second+1))
.filter { (it.first in 0 until maze.size)&&(it.second in 0 until maze[0].size) }
.filter { maze[it.first][it.second] - maze[pos.first][pos.second] <= 1 }.toMutableList()
}
while (true) {
for (point in nextPoints){
if (point in visitedPoints.keys) {continue}
else if (distances.getOrDefault(point, 100000) > distances.getOrDefault(curPos, 100000) + 1 ){
distances[point] = distances.getOrDefault(curPos, 100000) + 1
}
}
visitedPoints[curPos] = distances.getOrDefault(curPos, 100000)
if (visitedPoints.size == maze.size*maze[0].size){break}
distances.remove(curPos)
if (distances.size == 0){break}
curPos = distances.filterValues { it == distances.values.min() }.keys.first()
nextPoints = nextPoints.update(curPos)
nextPoints = nextPoints.filter { it !in visitedPoints.keys }.toMutableList()
}
println("result part 1: ${visitedPoints[endPos]}")
}
fun part2(input: List<String>){
var (maze, startEnd) = parseInput(input)
var (_, startPos) = startEnd
var allPoints = mutableListOf<Pair<Int, Int>>()
for (i in 0..maze.size-1){
for (j in 0..maze[0].size-1){
allPoints.add(Pair(i, j))
}
}
var visitedPoints = mutableMapOf<Pair<Int, Int>, Int>()
var distances = mutableMapOf<Pair<Int, Int>, Int>()
var nextPoints = mutableListOf(Pair(startPos.first-1, startPos.second),
Pair(startPos.first+1, startPos.second),
Pair(startPos.first, startPos.second-1),
Pair(startPos.first, startPos.second+1))
.filter { (it.first in 0..maze.size)&&(it.second in 0..maze[0].size) }
.filter { maze[it.first][it.second] == 'z' }.toMutableList()
var curPos = startPos
distances[curPos] = 0
fun MutableList<Pair<Int, Int>>.update(pos: Pair<Int, Int>): MutableList<Pair<Int, Int>> {
return mutableListOf(Pair(pos.first-1, pos.second),
Pair(pos.first+1, pos.second),
Pair(pos.first, pos.second-1),
Pair(pos.first, pos.second+1))
.filter { (it.first in 0..maze.size-1)&&(it.second in 0..maze[0].size-1) }
.filter { maze[pos.first][pos.second] - maze[it.first][it.second] <= 1 }.toMutableList()
}
while (true) {
for (point in nextPoints){
if (point in visitedPoints.keys) {continue}
else if (distances.getOrDefault(point, 100000) > distances.getOrDefault(curPos, 100000) + 1 ){
distances[point] = distances.getOrDefault(curPos, 100000) + 1
}
}
visitedPoints[curPos] = distances.getOrDefault(curPos, 100000)
if (visitedPoints.size == maze.size*maze[0].size){break}
distances.remove(curPos)
if (distances.size == 0){break}
curPos = distances.filterValues { it == distances.values.min() }.keys.first()
nextPoints = nextPoints.update(curPos)
nextPoints = nextPoints.filter { it !in visitedPoints.keys }.toMutableList()
}
println("part 2 answer: ${visitedPoints.filterKeys { maze[it.first][it.second] == 'a' }.values.min()}")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
part1(testInput)
part2(testInput)
val input = readInput("Day12")
part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | a0bc190b391585ce3bb6fe2ba092fa1f437491a6 | 5,489 | aoc22 | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2023/d07/Day07.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d07
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.readLines
val cardOrderPartOne = listOf(
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'T',
'J',
'Q',
'K',
'A',
)
val cardOrderPartTwo = listOf(
'J',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'T',
'Q',
'K',
'A',
)
data class Hand(val cards: String, val bid: Long)
fun List<Int>.toType() = when {
// five of a kind
5 in this -> 7
// four of a kind
4 in this -> 6
// full house
3 in this && 2 in this -> 5
// three of a kind
3 in this -> 4
// two pair
this.filter { it == 2 }.size == 2 -> 3
// one pair
2 in this -> 2
// high card
else -> 1
}
fun Hand.typePartOne(): Int =
cards.groupBy { it }
.map { (_, l) -> l.size }
.toType()
fun Hand.comparePartOne(that: Hand): Int =
if (this.typePartOne() != that.typePartOne()) this.typePartOne() - that.typePartOne()
else this.cards
.indices
.first { this.cards[it] != that.cards[it] }
.let { cardOrderPartOne.indexOf(this.cards[it]) - cardOrderPartOne.indexOf(that.cards[it]) }
fun Hand.typePartTwo(): Int {
if (this.cards == "JJJJJ") {
// all jokers - five of a kind
return 7
}
val jokers = this.cards.filter { it == 'J' }.length
val counts = this.cards
.filterNot { it == 'J' }
.groupBy { it }
.mapTo(mutableListOf()) { (_, l) -> l.size }
// add jokers to whichever count is highest to make best hand
val maxIdx = counts.indexOf(counts.max())
counts[maxIdx] += jokers
return counts.toType()
}
fun Hand.comparePartTwo(that: Hand): Int =
if (this.typePartTwo() != that.typePartTwo()) this.typePartTwo() - that.typePartTwo()
else this.cards
.indices
.first { this.cards[it] != that.cards[it] }
.let { cardOrderPartTwo.indexOf(this.cards[it]) - cardOrderPartTwo.indexOf(that.cards[it]) }
fun List<Hand>.totalWinnings(): Long =
this
.mapIndexed { i, hand ->
hand.bid * (i + 1)
}
.sum()
fun main() = timed {
val hands = (DATAPATH / "2023/day07.txt").readLines()
.map { line ->
line.split(" ")
.let { (cards, bid) ->
Hand(cards, bid.toLong())
}
}
hands.sortedWith { a, b -> a.comparePartOne(b) }
.totalWinnings()
.also { println("Part one $it") }
hands.sortedWith { a, b -> a.comparePartTwo(b) }
.totalWinnings()
.also { println("Part two $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,728 | advent-of-code | MIT License |
app/src/main/kotlin/day10/Day10.kt | KingOfDog | 433,706,881 | false | {"Kotlin": 76907} | package day10
import common.InputRepo
import common.readSessionCookie
import common.solve
import java.util.*
import kotlin.math.floor
fun main(args: Array<String>) {
val day = 10
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay10Part1, ::solveDay10Part2)
}
fun solveDay10Part1(input: List<String>): Int {
val scores = mapOf(
null to 0,
BracketType.ROUND to 3,
BracketType.FLAT to 57,
BracketType.CURLY to 1197,
BracketType.POINTY to 25137,
)
return input.sumOf { line ->
val corrupted = line.firstCorrupted()
scores[corrupted]!!
}
}
fun solveDay10Part2(input: List<String>): Int {
val scoreTable = mapOf(
BracketType.ROUND to 1,
BracketType.FLAT to 2,
BracketType.CURLY to 3,
BracketType.POINTY to 4,
)
val scores = input
.filter { it.firstCorrupted() == null }
.map { line ->
line.autocomplete()
.map { scoreTable[it]!!.toULong() }
.reduce { acc, i -> acc * (5).toULong() + i }
}.sorted()
val middle = scores.size / 2
return scores[middle].toInt()
}
fun String.firstCorrupted(): BracketType? {
var corruptedBracket: BracketType? = null
parseBrackets { bracketType, lastOpened ->
if (corruptedBracket == null && bracketType != lastOpened) {
corruptedBracket = bracketType
}
}
return corruptedBracket
}
fun String.autocomplete(): List<BracketType> {
return parseBrackets().reversed()
}
private fun String.parseBrackets(onCloseBracket: ((BracketType, BracketType) -> Unit)? = null): Stack<BracketType> {
val openedBrackets = Stack<BracketType>()
this.toCharArray().forEach { bracket ->
val bracketType = BracketType.getBracketType(bracket)
val isOpening = bracketType.opening == bracket
if (isOpening) {
openedBrackets.push(bracketType)
} else {
val lastOpened = openedBrackets.pop()
onCloseBracket?.invoke(bracketType, lastOpened)
}
}
return openedBrackets
}
enum class BracketType(val opening: Char, val closing: Char) {
ROUND('(', ')'),
FLAT('[', ']'),
CURLY('{', '}'),
POINTY('<', '>');
companion object {
fun getBracketType(c: Char): BracketType {
return BracketType.values().first { it.opening == c || it.closing == c }
}
}
}
| 0 | Kotlin | 0 | 0 | 576e5599ada224e5cf21ccf20757673ca6f8310a | 2,483 | advent-of-code-kt | Apache License 2.0 |
_posts/2020-12-20/solve.kts | booniepepper | 317,946,432 | false | {"Go": 6095, "Rust": 5639, "Prolog": 4681, "Raku": 3895, "Elixir": 3361, "Kotlin": 3076, "Zig": 2873, "Common Lisp": 2105, "C": 2083, "Haskell": 1967, "Racket": 1873, "Scheme": 1498, "Awk": 1342, "Erlang": 1294, "OCaml": 1179, "Groovy": 1100, "JavaScript": 1099, "Tcl": 954, "Shell": 924, "Perl": 834, "PureScript": 806, "Ruby": 760, "Factor": 536, "Python": 522, "Lua": 458, "Crystal": 193} | #!/usr/bin/env kotlin
import java.io.File
import java.math.BigInteger
class Tile(raw: String) {
val n: BigInteger
val borders: List<String>
val rborders: List<String>
val tile: List<String>
init {
val lines = raw.split("\n")
n = lines[0].replace(Regex("\\D"), "").toBigInteger()
tile = lines.drop(1).take(10)
borders = listOf(
tile[0],
tile.map { it[9] }.joinToString(""),
tile.drop(9)[0].reversed(),
tile.map { it[0] }.joinToString("").reversed(),
)
rborders = borders.map { it.reversed() }.reversed()
}
}
fun edgesOf(tiles: List<Tile>): Set<String> =
tiles.flatMap { it.borders + it.rborders }
.groupBy { it }
.filterValues { it.size == 1 }
.keys
fun cornersOf(tiles: List<Tile>, edges: Set<String> = edgesOf(tiles)): List<Tile> =
tiles.filter { it.borders.intersect(edges).size == 2 }
val tiles: List<Tile> = File("input").readText()
.split("\n\n")
.filter { !it.isEmpty() }
.map { Tile(it) }
val edges: Set<String> = edgesOf(tiles)
val solutionOne: BigInteger = cornersOf(tiles, edges).map { it.n }
.fold(BigInteger.ONE, { a, b -> a * b })
// Part 1 Solution
println("Product of corner tile numbers: $solutionOne")
fun seaify(seas: List<Tile>, startingCorner: Tile): List<String> {
val seaMap: MutableMap<BigInteger, Tile> = seas.associateBy { it.n }.toMutableMap()
seaMap.remove(startingCorner.n)
while (seaMap.isNotEmpty()) {
seas.mapIndexedNotNull { i, it ->
if ((it.borders + it.rborders).intersect(startingCorner.borders).size == 1 &&
it.n != startingCorner.n
) { Pair(i, it) } else { null }
}
break
}
return listOf()
}
val seas: List<Tile> = tiles.filter { it.borders.intersect(edges).size == 0 }
val seaCorner: Tile = cornersOf(seas)[0]
println(seas)
println(seaify(seas, seaCorner))
| 0 | Go | 0 | 2 | c9645f1df08b83180ccc574a91e02a26099d0cba | 1,957 | adventofcode-solutions | Do What The F*ck You Want To Public License |
src/Day21.kt | sabercon | 648,989,596 | false | null | fun main() {
fun buildIngredientAllergenMap(allergenIngredientMap: Map<String, Set<String>>): Map<String, String> {
if (allergenIngredientMap.isEmpty()) return emptyMap()
val (allergen, ingredients) = allergenIngredientMap.entries.first { it.value.size == 1 }
val ingredient = ingredients.single()
return allergenIngredientMap
.minus(allergen)
.mapValues { it.value - ingredient }
.let { buildIngredientAllergenMap(it) }
.plus(ingredient to allergen)
}
fun buildIngredientAllergenMap(input: List<Pair<List<String>, List<String>>>): Map<String, String> {
return input.flatMap { (ingredients, allergens) -> allergens.map { it to ingredients.toSet() } }
.groupBy({ it.first }, { it.second })
.mapValues { it.value.reduce { acc, set -> acc intersect set } }
.let { buildIngredientAllergenMap(it) }
}
val input = readLines("Day21").map {
val (ingredients, allergens) = it.split(" (contains ")
ingredients.split(" ") to allergens.dropLast(1).split(", ")
}
val ingredientAllergenMap = buildIngredientAllergenMap(input)
input.flatMap { it.first }.count { it !in ingredientAllergenMap }.println()
ingredientAllergenMap.entries.sortedBy { it.value }.joinToString(",") { it.key }.println()
}
| 0 | Kotlin | 0 | 0 | 81b51f3779940dde46f3811b4d8a32a5bb4534c8 | 1,362 | advent-of-code-2020 | MIT License |
src/aoc2023/Day19.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2023
import readInput
fun main() {
data class Part(val x: Int, val m: Int, val a: Int, val s: Int)
abstract class Condition {
abstract fun evaluate(part: Part): Boolean
}
class TrueCondition : Condition() {
override fun evaluate(part: Part) = true
}
class Conditional(val variable: Char, val operator: Char, val value: Int) : Condition() {
override fun evaluate(part: Part): Boolean {
if (variable == 'x' && operator == '>') {
return part.x > value
} else if (variable == 'x' && operator == '<') {
return part.x < value
} else if (variable == 'm' && operator == '>') {
return part.m > value
} else if (variable == 'm' && operator == '<') {
return part.m < value
} else if (variable == 'a' && operator == '>') {
return part.a > value
} else if (variable == 'a' && operator == '<') {
return part.a < value
} else if (variable == 's' && operator == '>') {
return part.s > value
} else if (variable == 's' && operator == '<') {
return part.s < value
}
throw RuntimeException()
}
}
class SubRule(val condition: Condition, val action: String) {
fun matches(part: Part): Boolean {
return condition.evaluate(part)
}
}
class Rule(val name: String, val subrules: List<SubRule>) {
fun evaluate(part: Part): String {
for (rule in subrules) {
if (rule.matches(part)) {
return rule.action
}
}
throw RuntimeException()
}
}
fun parsePart(line: String): Part {
val props = line.split(',')
val x = props[0].substring(3).toInt()
val m = props[1].substring(2).toInt()
val a = props[2].substring(2).toInt()
val s = props[3].substring(2, props[3].length - 1).toInt()
return Part(x, m, a, s)
}
fun parseRule(line: String): Rule {
val ruleStart = line.indexOfFirst { it == '{' }
val ruleName = line.substring(0, ruleStart)
val subRules = mutableListOf<SubRule>()
val rules = line.substring(ruleStart + 1, line.length - 1).split(',')
for (i in rules.indices) {
if (i == rules.size - 1) {
subRules.add(SubRule(TrueCondition(), rules[i]))
} else {
val variable = rules[i][0]
val operator = rules[i][1]
val colonIndex = rules[i].indexOfFirst { it == ':' }
val value = rules[i].substring(2, colonIndex).toInt()
val condition = Conditional(variable, operator, value)
val action = rules[i].substring(colonIndex + 1)
subRules.add(SubRule(condition, action))
}
}
return Rule(ruleName, subRules)
}
fun part1(lines: List<String>): Int {
val splitIndex = lines.indexOfFirst { it.isEmpty() }
val rules = lines.subList(0, splitIndex).map { parseRule(it) }.groupBy { it.name }
val parts = lines.subList(splitIndex + 1, lines.size).map { parsePart(it) }
val accepted = mutableListOf<Part>()
for (part in parts) {
var action = "in"
while (action != "A" && action != "R") {
val rule = rules[action]!![0]
action = rule.evaluate(part)
if (action == "A") {
accepted.add(part)
}
}
}
return accepted.sumOf { it.x + it.m + it.a + it.s }
}
println(part1(readInput("aoc2023/Day19_test")))
println(part1(readInput("aoc2023/Day19")))
} | 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 3,843 | advent-of-code-kotlin | Apache License 2.0 |
src/Day16.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} |
data class Valve(val id: String, val rate: Int, val neighbors: List<String>)
data class VNode(val rate: Int, val friends: List<Int>)
fun main() {
fun String.toValve(): Valve {
val id = split(" ")[1]
val rate = split(";")[0].split("=")[1].toInt()
val neighbors = if (" valves " in this) split(" valves ")[1].split(", ")
else split(" valve ")[1].split(", ")
return Valve(id, rate, neighbors)
}
fun List<Valve>.toVNode(): List<VNode> {
val idMap = this.mapIndexed { index, valve -> valve.id to index }.toMap()
return this.map { VNode(it.rate, it.neighbors.map { n -> idMap[n]!! }) }
}
fun getDis(nodes: List<VNode>): Array<Array<Int>> {
val n = nodes.size
val MAX = Int.MAX_VALUE / 2
val dist = Array(n) { Array(n) { MAX } }
for (i in nodes.indices) {
for (j in nodes[i].friends) {
dist[i][j] = 1
dist[j][i] = 1
}
}
for (k in 0 until n) {
for (i in 0 until n) {
for (j in 0 until n) {
if (dist[i][j] > dist[i][k] + dist[k][j])
dist[i][j] = dist[i][k] + dist[k][j]
}
}
}
return dist
}
fun getAns(nodes: List<VNode>): Int {
val dist = getDis(nodes)
var ans = -1
fun dfs(x: Int, remains: MutableSet<Int>, now: Int, score: Int) {
if (now >= 30 || remains.isEmpty()) {
ans = maxOf(ans, score)
return
}
val allLeft = remains.toList()
for (y in allLeft) {
val then = now + dist[x][y] + 1
val yPressure = if (then <= 30) nodes[y].rate * (30 - then) else 0
remains -= y
dfs(y, remains, then, score + yPressure)
remains += y
}
}
val remains = nodes
.mapIndexed { index, vNode -> index to vNode }
.filter { it.second.rate > 0 }
.map { it.first }
.toMutableSet()
dfs(0, remains, 0, 0)
return ans
}
fun part1(input: List<String>): Int {
val valves = input.map { it.toValve() }.sortedBy { it.id }
val nodes = valves.toVNode()
return getAns(nodes)
}
fun getAns2(nodes: List<VNode>): Int {
val dist = getDis(nodes)
var ans = -1
fun dfs(x: Int, remains: MutableSet<Int>, now: Int, score: Int) {
if (now >= 30 || remains.isEmpty()) {
ans = maxOf(ans, score)
return
}
val allLeft = remains.toList()
for (y in allLeft) {
val then = now + dist[x][y] + 1
val yPressure = if (then <= 30) nodes[y].rate * (30 - then) else 0
remains -= y
dfs(y, remains, then, score + yPressure)
remains += y
}
}
val remains = nodes
.mapIndexed { index, vNode -> index to vNode }
.filter { it.second.rate > 0 }
.map { it.first }
.toMutableSet()
var result = -1
val remainList = remains.toList()
val size = remains.size
for (i in 0 until (1 shl size)) {
val left = mutableSetOf<Int>()
for (j in 0 until size) {
if ((i and (1 shl j)) > 0) {
left += remainList[j]
}
}
val right = remains - left
var tmp = 0
ans = -1
dfs(0, left, 4, 0)
tmp += ans
ans = -1
dfs(0, right.toMutableSet(), 4, 0)
tmp += ans
result = maxOf(result, tmp)
}
return result
}
fun part2(input: List<String>): Int {
val valves = input.map { it.toValve() }.sortedBy { it.id }
val nodes = valves.toVNode()
return getAns2(nodes)
}
println(part1(readInput("data/Day16_test")))
println(part1(readInput("data/Day16")))
println(part2(readInput("data/Day16_test")))
println(part2(readInput("data/Day16")))
} | 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 3,646 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day05.kt | f1qwase | 572,888,869 | false | {"Kotlin": 33268} | private data class Store(val stacks: Array<List<Char>>) {
fun move(from: Int, to: Int, count: Int) {
val movedCrates = stacks[from].take(count)
stacks[from] = stacks[from].drop(count)
stacks[to] = movedCrates + stacks[to]
}
val topCrates: List<Char>
get() = stacks.map { it.first() }
companion object {
fun parse(input: List<String>): Store {
val stacksCount = (input.maxOf { it.length } + 1) / 4
val stacks = List(stacksCount) { mutableListOf<Char>() }
input.forEach { line ->
line.forEachIndexed { index, c ->
if (c.isLetter()) {
stacks[index / 4].add(c)
}
}
}
return Store(stacks.map { it.toList() }.toTypedArray())
}
}
}
private data class Move(val from: Int, val to: Int, val count: Int) {
companion object {
fun parse(input: String): Move {
// "move 6 from 1 to 7"
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
return regex.matchEntire(input)!!.destructured.let { (count, from, to) ->
Move(from.toInt() - 1, to.toInt() - 1, count.toInt())
}
}
}
}
fun main() {
fun part1(input: List<String>): String {
val storeInput = input.takeWhile { it.isNotBlank() }
val store = Store.parse(storeInput)
val moves = input.drop(storeInput.size + 1).map { Move.parse(it) }
moves.forEach { (from, to, count) ->
repeat(count) {
store.move(from, to, 1)
}
}
return store.topCrates.joinToString("")
}
fun part2(input: List<String>): String {
val storeInput = input.takeWhile { it.isNotBlank() }
val store = Store.parse(storeInput)
val moves = input.drop(storeInput.size + 1).map { Move.parse(it) }
moves.forEach { (from, to, count) ->
store.move(from, to, count)
}
return store.topCrates.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ") {
part1(testInput)
}
val input = readInput("Day05")
println(part1(input))
check(part2(testInput) == "MCD") { part2(testInput) }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3fc7b74df8b6595d7cd48915c717905c4d124729 | 2,439 | aoc-2022 | Apache License 2.0 |
y2023/src/main/kotlin/adventofcode/y2023/Day17.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
import java.util.*
fun main() {
Day17.solve()
}
object Day17 : AdventSolution(2023, 17, "<NAME>") {
override fun solvePartOne(input: String): Int =
solve(input, CartState::regularMove) { grid, cart -> cart.pos == grid.target }
override fun solvePartTwo(input: String): Int =
solve(input, CartState::ultraMove) { grid, cart -> cart.pos == grid.target && cart.movesInDirection > 3 }
}
private inline fun solve(
input: String,
neighbors: CartState.() -> List<CartState>,
target: (City, CartState) -> Boolean
): Int {
val grid = City(input)
val visited = mutableSetOf<CartState>()
val open = PriorityQueue(compareBy(Pair<CartState, Int>::second))
open.add(CartState(grid.start, Direction.RIGHT, 0) to 0)
while (open.isNotEmpty()) {
val (oldState, oldCost) = open.remove()
if (oldState in visited) continue
visited += oldState
if (target(grid, oldState)) return oldCost
oldState.neighbors()
.filter { it.pos in grid }
.filter { it !in visited }
.forEach { open.add(it to oldCost + grid.costAt(it.pos)) }
}
error("no valid path")
}
private data class City(val grid: List<List<Int>>) {
constructor(input: String) : this(input.lines().map { it.map(Char::digitToInt) })
private val xs = grid[0].indices
private val ys = grid.indices
operator fun contains(pos: Vec2): Boolean {
return pos.x in xs && pos.y in ys
}
fun costAt(pos: Vec2) = grid[pos.y][pos.x]
val start = Vec2.origin
val target = Vec2(grid[0].lastIndex, grid.lastIndex)
}
private data class CartState(val pos: Vec2, val direction: Direction, val movesInDirection: Int) {
private fun left() = CartState(pos + direction.turnLeft.vector, direction.turnLeft, 1)
private fun right() = CartState(pos + direction.turnRight.vector, direction.turnRight, 1)
private fun straight() = CartState(pos + direction.vector, direction, movesInDirection + 1)
fun regularMove() = buildList {
if (movesInDirection < 3) add(straight())
add(left())
add(right())
}
fun ultraMove() = buildList {
if (movesInDirection < 10) add(straight())
if (movesInDirection > 3) {
add(left())
add(right())
}
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,485 | advent-of-code | MIT License |
aoc/src/Parts.kt | aragos | 726,211,893 | false | {"Kotlin": 16232} | import java.io.File
fun main() {
// countPartNumbers()
countGearRatios()
}
private data class PartNumber(val value: Int, val location: IntRange) {
fun isAdjacentTo(i: Int) = i in (location.first-1)..(location.last+1)
}
private fun countGearRatios() {
var line1: Set<PartNumber>
var line2 = setOf<PartNumber>()
var line3 = setOf<PartNumber>()
var previousLine = ""
val allRatios = File("inputs/parts.txt").readLines().map { line ->
line1 = line2
line2 = line3
line3 = Regex("\\d+").findAll(line).map { PartNumber(it.value.toInt(), it.range) }.toSet()
val ratioSum = scanRatios(previousLine, line1 + line2 + line3)
previousLine = line
ratioSum
}.sum()
println(allRatios + scanRatios(previousLine, line2 + line3))
}
private fun scanRatios(
previousLine: String,
partNumbers1: Set<PartNumber>,
): Int {
val ratioSum = previousLine.mapIndexedNotNull { ix, char ->
if (char != '*') {
null
} else {
val partNumbers = partNumbers1.filter { it.isAdjacentTo(ix) }
if (partNumbers.size == 2) {
partNumbers[0].value * partNumbers[1].value
} else {
null
}
}
}.sum()
return ratioSum
}
private fun countPartNumbers() {
var line1: Set<Int>
var line2 = setOf<Int>()
var line3 = setOf<Int>()
var previousLine = ""
val allNumbers = File("inputs/parts.txt").readLines().map { line ->
line1 = line2
line2 = line3
line3 =
line.mapIndexedNotNull { ix, char -> if (char != '.' && char.isNotANumber()) ix else null }
.toSet()
val line2PartNumberSum = scanPartNumbers(previousLine, line1 + line2 + line3)
previousLine = line
line2PartNumberSum
}.sum()
println(allNumbers + scanPartNumbers(previousLine, line2 + line3))
}
private fun scanPartNumbers(
partNumberLine: String,
partLocations: Set<Int>,
): Int {
return Regex("\\d+").findAll(partNumberLine).mapNotNull {
val number = it.value.toInt()
for (i in (it.range.first - 1)..(it.range.last + 1)) {
if (i in partLocations) {
return@mapNotNull number
}
}
null
}.sum()
}
private fun Char.isNotANumber() = digitToIntOrNull() == null
| 0 | Kotlin | 0 | 0 | 7bca0a857ea42d89435adc658c0ff55207ca374a | 2,177 | aoc2023 | Apache License 2.0 |
src/main/kotlin/day13/Day13.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day13
import execute
import readAllText
sealed class Node : Comparable<Node>
data class NumberNode(val value: Int) : Node() {
override fun compareTo(other: Node): Int = when (other) {
is ListNode -> ListNode(listOf(this)).compareTo(other)
is NumberNode -> value.compareTo(other.value)
}
}
data class ListNode(val value: List<Node>) : Node() {
override fun compareTo(other: Node): Int {
when (other) {
is NumberNode -> return compareTo(ListNode(listOf(other)))
is ListNode -> {
for (p in value.indices) {
if (p in other.value.indices) {
val r = value[p].compareTo(other.value[p])
if (r != 0) return r
}
}
return value.size.compareTo(other.value.size)
}
}
}
}
fun part1(input: String) = input.lineSequence().filterNot(String::isBlank)
.map(::parse)
.chunked(2)
.mapIndexed { index, (left, right) ->
if (left < right) index + 1 else 0
}
.sum()
private val separators by lazy { listOf("[[2]]", "[[6]]").map { parse(it) } }
fun part2(input: String) = input.lineSequence()
.filterNot(String::isBlank)
.map(::parse)
.toList()
.let { it + separators }
.sorted()
.let { ordered -> separators.map { ordered.indexOf(it) + 1 }.reduce(Int::times) }
private fun parse(str: String): Node =
if (str.startsWith("["))
ListNode(parseList(str).map { parse(it) })
else
NumberNode(str.toInt())
private fun parseList(str: String) = buildList {
var p = 0
var q = 0
var i = 0
while (q in str.indices) {
if (str[q] == '[') i++
if (str[q] == ']') i--
if (str[q] == ',' && i == 1) {
add(str.substring(p + 1, q))
p = q
}
q++
}
if (p + 1 != q - 1) add(str.substring(p + 1, q - 1))
}
fun main() {
val input = readAllText("local/day13_input.txt")
val test = """
[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
""".trimIndent()
execute(::part1, test, 13)
execute(::part1, input, 5720)
execute(::part2, test, 140)
execute(::part2, input, 23504)
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 2,509 | advent-of-code-2022 | MIT License |
lib/src/main/kotlin/com/bloidonia/advent/day09/Day09.kt | timyates | 433,372,884 | false | {"Kotlin": 48604, "Groovy": 33934} | package com.bloidonia.advent.day09
import com.bloidonia.advent.readList
data class Point(val x: Int, val y: Int)
data class Cave(val width: Int, val z: IntArray) {
private fun p(pt: Point) = p(pt.x, pt.y)
private fun p(x: Int, y: Int) =
if (x < 0 || y < 0 || x >= width || y >= z.size / width) Int.MAX_VALUE else z[x + (y * width)]
private fun minima() = (0 until z.size / width).flatMap { y ->
(0 until width).mapNotNull { x ->
val me = p(x, y)
if (p(x - 1, y) > me && p(x + 1, y) > me && p(x, y - 1) > me && p(x, y + 1) > me)
Point(x, y)
else
null
}
}
fun basin(seed: Point): Int {
val queue = ArrayDeque(listOf(seed))
val seen = mutableSetOf<Point>()
var size = 0
while (!queue.isEmpty()) {
val next = queue.removeFirst()
if (seen.contains(next)) {
continue
}
seen.add(next)
if (p(next) < 9) {
size++
listOfNotNull(
if (next.x > 0) Point(next.x - 1, next.y) else null,
if (next.x < width - 1) Point(next.x + 1, next.y) else null,
if (next.y > 0) Point(next.x, next.y - 1) else null,
if (next.y < z.size / width) Point(next.x, next.y + 1) else null,
)
.forEach { p -> queue.addLast(p) }
}
}
return size
}
fun part1() = minima().sumOf { p(it) + 1 }
fun part2() = minima().map(::basin).sorted().takeLast(3).reduce { a, b -> a * b }
}
fun List<String>.toCave() = Cave(first().length, joinToString("").map { "$it".toInt() }.toIntArray())
fun main() {
println(readList("/day09input.txt").toCave().part1())
println(readList("/day09input.txt").toCave().part2())
} | 0 | Kotlin | 0 | 1 | 9714e5b2c6a57db1b06e5ee6526eb30d587b94b4 | 1,882 | advent-of-kotlin-2021 | MIT License |
src/Day07.kt | Inn0 | 573,532,249 | false | {"Kotlin": 16938} | data class Dir(
val name: String,
val parent: Dir? = null,
val dirs: MutableList<Dir> = mutableListOf(),
val files: MutableList<File> = mutableListOf()
) {
fun allDirs(): List<Dir> = dirs + dirs.flatMap { it.allDirs() }
fun size(): Int = files.sumOf { it.size } + dirs.sumOf { it.size() }
}
data class File(val size: Int)
fun main() {
fun prepareDir(input: List<String>): Dir {
val root = Dir("/")
var current = root
input.drop(1).forEach { line ->
when {
line.startsWith("$ cd ..") -> current = current.parent!!
line.startsWith("$ cd") -> current = current.dirs.first { it.name == line.substringAfter("cd ") }
line.startsWith("dir") -> current.dirs.add(Dir(line.substringAfter("dir "), current))
!line.contains("$") -> current.files.add(File(line.substringBefore(" ").toInt()))
}
}
return root
}
fun part1(input: List<String>): Int {
val root = prepareDir(input)
return root.allDirs().map { it.size() }.filter { it < 100000 }.sum()
}
fun part2(input: List<String>): Int {
val root = prepareDir(input)
val spaceToFree = 30000000 - (70000000 - root.size())
return root.allDirs().map { it.size() }.sorted().first { it >= spaceToFree }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | f35b9caba5f0c76e6e32bc30196a2b462a70dbbe | 1,668 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} |
class Stack {
private val data = mutableListOf<Char>()
fun push(e: Char) { data.add(e) }
fun pop() = data.removeLast()
fun top() = data.last()
fun moveTo(n: Int, to: Stack) {
List(n){ pop() }.reversed().forEach { to.push(it) }
}
}
private fun List<String>.toStacks(): List<Stack> {
val lines = dropLast(1).map{ it.chunked(4).map{ it[1] } }
val stacks = List(lines.last().size){ Stack() }
lines.reversed().forEach { it.forEachIndexed { idx, box ->
if (box!=' ') stacks[idx].push(box)
} }
return stacks
}
private val movePattern = Regex("""move (\d+) from (\d+) to (\d+)""")
private fun partN(lines: List<String>, action: (n: Int, from: Stack, to: Stack) -> Unit): String {
val (stkLines, movesLines) = lines.splitBy { it.isBlank() }
val stacks = stkLines.toStacks()
movesLines.forEach {
val (n, from, to) = (movePattern.find(it) ?: error("invalid move $it"))
.destructured.toList()
.map { it.toInt() }
action(n, stacks[from-1], stacks[to-1])
}
return stacks.joinToString(separator = "") { it.top().toString() }
}
private fun part1(lines: List<String>) = partN(lines,
action = { n, from, to -> repeat(n) { to.push( from.pop() ) } }
)
private fun part2(lines: List<String>) = partN(lines,
action = { n, from, to -> from.moveTo(n,to) }
)
fun main() {
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input)) // ZBDRNPMVH
println(part2(input)) // WDLPFNNNB
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 1,618 | aoc2022 | Apache License 2.0 |
src/Day02.kt | alexaldev | 573,318,666 | false | {"Kotlin": 10807} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val (opp, me) = it.split(" ")
val oppM = OpponentMove.valueOf(opp)
val meM = MyMove.valueOf(me)
scorePart1(oppM, meM)
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val (opp, result) = it.split(" ")
val oppM = OpponentMove.valueOf(opp)
val resultMv = MovesResult.fromMyMove(MyMove.valueOf(result))
scorePart2(oppM, resultMv)
}
}
val testInput = readInput("In02.txt")
print(part2(testInput))
}
enum class OpponentMove {
A, B, C
}
enum class MyMove {
X, Y, Z
}
fun scorePart1(opponentMove: OpponentMove, myMove: MyMove): Int {
if (Move.fromMe(myMove) == Move.fromOpponent(opponentMove)) {
return 3 + Move.fromMe(myMove).points
}
return if (Move.winsTo.contains(Pair(Move.fromMe(myMove), Move.fromOpponent(opponentMove)))) {
6 + Move.fromMe(myMove).points
} else {
Move.fromMe(myMove).points
}
}
fun scorePart2(opponentMove: OpponentMove, expectedResult: MovesResult): Int {
return when(expectedResult) {
MovesResult.Win -> Move.losesToMap[Move.fromOpponent(opponentMove)]!!.points + 6
MovesResult.Lose -> Move.winsToMap[Move.fromOpponent(opponentMove)]!!.points
MovesResult.Draw -> Move.fromOpponent(opponentMove).points + 3
}
}
enum class Move(val points: Int) {
Paper(2),
Scissors(3),
Rock(1);
companion object {
// ----- Part 1 -----------
val winsTo = listOf(
Paper to Rock,
Rock to Scissors,
Scissors to Paper
)
val winsToMap = mapOf(
Paper to Rock,
Rock to Scissors,
Scissors to Paper
)
fun fromOpponent(opponentMove: OpponentMove): Move {
return when(opponentMove) {
OpponentMove.A -> Rock
OpponentMove.B -> Paper
OpponentMove.C -> Scissors
}
}
fun fromMe(myMove: MyMove): Move {
return when(myMove) {
MyMove.X -> Rock
MyMove.Y -> Paper
MyMove.Z -> Scissors
}
}
// ------- Part 2 --------
val losesToMap = mapOf(
Paper to Scissors,
Rock to Paper,
Scissors to Rock
)
}
}
enum class MovesResult {
Win, Lose, Draw;
companion object {
fun fromMyMove(myMove: MyMove): MovesResult {
return when(myMove) {
MyMove.X -> Lose
MyMove.Y -> Draw
MyMove.Z -> Win
}
}
}
} | 0 | Kotlin | 0 | 0 | 5abf10b2947e1c6379d179a48f1bdcc719e7062b | 2,773 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day09.kt | mvanderblom | 573,009,984 | false | {"Kotlin": 25405} | import kotlin.math.abs
operator fun Pair<Int,Int>.minus(other: Pair<Int, Int>): Pair<Int, Int> = this.first - other.first to this.second - other.second
fun main() {
val dayName = 9.toDayName()
val moves = mapOf(
"L" to { coords: Pair<Int, Int> -> coords.first - 1 to coords.second },
"R" to { coords: Pair<Int, Int> -> coords.first + 1 to coords.second },
"D" to { coords: Pair<Int, Int> -> coords.first to coords.second - 1 },
"U" to { coords: Pair<Int, Int> -> coords.first to coords.second + 1 }
)
val tailMovesByDistance = mapOf(
2 to 0 to listOf("R"),
-2 to 0 to listOf("L"),
0 to 2 to listOf("U"),
0 to -2 to listOf("D"),
1 to 2 to listOf("R", "U"),
2 to 1 to listOf("R", "U"),
2 to -1 to listOf("R", "D"),
1 to -2 to listOf("R", "D"),
-1 to -2 to listOf("L", "D"),
-2 to -1 to listOf("L", "D"),
-1 to 2 to listOf("L", "U"),
-2 to 1 to listOf("L", "U")
)
fun display(width: Int, height: Int, arr: Array<Pair<Int,Int>>) {
repeat(height) {y ->
repeat(width) {x ->
val coord = x to (height-y)
when {
arr[0] == coord -> print("H")
arr.last() == coord -> print("T")
arr.contains(coord) -> print("o")
else -> print(".")
}
}
println()
}
println()
}
fun getMoves(input: List<String>) = input
.map { it.split(" ") }
.flatMap { (direction, amount) ->
(1..amount.toInt()).map { direction }
}
fun part1(input: List<String>): Int {
var head = 0 to 0
var tail = 0 to 0
println("head: $head, tail: $tail")
val tailPositions = getMoves(input).map {
println(it)
head = moves.getValue(it)(head)
val distance = head - tail
if (abs(distance.first) >= 2 || abs(distance.second) >= 2) {
println("head moved to $head, moving tail by $distance")
tailMovesByDistance.getValue(distance)
.forEach { tail = moves.getValue(it)(tail) }
}
println("head: $head, tail: $tail")
tail
}
return tailPositions.toSet().size
}
fun follow(head: Pair<Int, Int>, tail: List<Pair<Int, Int>>): List<Pair<Int, Int>> {
val distance = head - tail[0]
if (abs(distance.first) >= 2 || abs(distance.second) >= 2) {
println("head moved to $head, moving tail by $distance")
val tailPath = tailMovesByDistance.getValue(distance)
.map { moves.getValue(it)(tail[0]) }
if( tail.size == 1 )
return tailPath
}
return follow(tail[0], tail.subList(1, tail.size))
}
fun part2(input: List<String>): Int {
val instructions = input
.map { it.split(" ") }
.map { (direction, amount) -> direction to amount.toInt() }
val tailPath = mutableListOf<Pair<Int, Int>>()
val rope = Array(10) { Pair(15,15) }
display(25, 25, rope)
instructions.forEach { (direction, amount) ->
println("$direction $amount")
repeat(amount) {
rope[0] = moves.getValue(direction)(rope[0])
(0 until rope.size - 1).forEach { i ->
val head = rope[i]
val tail = rope[i + 1]
val distance = head - tail
if (abs(distance.first) >= 2 || abs(distance.second) >= 2) {
val path = tailMovesByDistance
.getValue(distance)
.map {
val newPosition = moves.getValue(it)(tail)
rope[i+1] = newPosition
newPosition
}
if(i == rope.size - 2) {
tailPath.addAll(path)
}
}
}
display(25, 25, rope)
}
}
return 1
}
val input = readInput(dayName)
// Part 1
// val testOutputPart1 = part1(readInput("${dayName}_test"))
// testOutputPart1 isEqualTo 13
//
// val outputPart1 = part1(input)
// outputPart1 isEqualTo 6044
// Part 2
val testOutputPart2 = part2(readInput("${dayName}_test2"))
testOutputPart2 isEqualTo 36
val outputPart2 = part2(input)
outputPart2 isEqualTo null
}
| 0 | Kotlin | 0 | 0 | ba36f31112ba3b49a45e080dfd6d1d0a2e2cd690 | 4,877 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day13.kt | D000L | 575,350,411 | false | {"Kotlin": 23716} | sealed interface Packet {
infix fun compareTo(other: Packet): Int
}
class NumPacket(val num: Int) : Packet {
override fun toString(): String {
return num.toString()
}
override fun compareTo(other: Packet): Int {
return when (other) {
is NumPacket -> when {
num < other.num -> -1
num > other.num -> 1
else -> 0
}
is ListPacket -> ListPacket(listOf(this)) compareTo other
}
}
}
class ListPacket(val inners: List<Packet>) : Packet {
override fun toString(): String {
return "[" + inners.joinToString(",") + "]"
}
override fun compareTo(other: Packet): Int {
return when (other) {
is NumPacket -> this compareTo ListPacket(listOf(other))
is ListPacket -> inners.zip(other.inners).map { it.first compareTo it.second }.filterNot { it == 0 }
.firstOrNull() ?: (inners.size compareTo other.inners.size)
}
}
}
fun String.toPacket(): Packet = removeSurrounding("[", "]").run {
if (toIntOrNull() != null) return NumPacket(toInt())
if (isEmpty()) return ListPacket(emptyList())
val inner = mutableListOf<Packet>()
var word = ""
var brackets = 0
this.forEachIndexed { index, char ->
when (char) {
'[' -> brackets++
']' -> brackets--
}
if (char == ',' && brackets == 0) {
inner.add(word.toPacket())
word = ""
return@forEachIndexed
}
word += char
}
if (word.isNotEmpty()) inner.add(word.toPacket())
return ListPacket(inner)
}
fun main() {
fun part1(input: List<String>): Int {
var result = 0
var index = 0
input.filter { it.isNotEmpty() }.chunked(2).forEach { (a, b) ->
index++
val aWords = a.toPacket()
val bWords = b.toPacket()
if (aWords compareTo bWords < 0) result += index
}
return result
}
fun part2(input: List<String>): Int {
val first = "[[2]]".toPacket()
val second = "[[6]]".toPacket()
val sorted = ((input.filter { it.isNotEmpty() }.map { it.toPacket() } + listOf(
first, second
))).sortedWith(Packet::compareTo)
return (sorted.indexOf(first) + 1) * (sorted.indexOf(second) + 1)
}
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b733a4f16ebc7b71af5b08b947ae46afb62df05e | 2,481 | adventOfCode | Apache License 2.0 |
src/Day04.kt | aamielsan | 572,653,361 | false | {"Kotlin": 9363} | fun main() {
fun part1(input: List<String>): Int =
input
.map { line ->
line
.split(",")
.map(ElfCleaner::fromString)
.let { it[0].overlapsWithAllSection(it[1]) }
}
.sumOf(Boolean::toInt)
fun part2(input: List<String>): Int =
input
.map { line ->
line
.split(",")
.map(ElfCleaner::fromString)
.let { it[0].overlapsWithOneSection(it[1]) }
}
.sumOf(Boolean::toInt)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private class ElfCleaner private constructor(
private val sections: Set<Int>
) {
fun overlapsWithAllSection(other: ElfCleaner): Boolean =
overlapsSection(other) { section1, section2 ->
(section1 intersect section2)
.let { it == this.sections || it == other.sections }
}
fun overlapsWithOneSection(other: ElfCleaner): Boolean =
overlapsSection(other) { section1, section2 ->
(section1 intersect section2).isNotEmpty()
}
private fun overlapsSection(
other: ElfCleaner,
predicate: (Set<Int>, Set<Int>) -> Boolean
): Boolean =
predicate(sections, other.sections)
companion object {
fun fromString(string: String) =
ElfCleaner(
sections = string
.split("-")
.let {
(it[0].toInt()..it[1].toInt()).toSet()
}
)
}
}
private fun Boolean.toInt() = if (this) 1 else 0
| 0 | Kotlin | 0 | 0 | 9a522271bedb77496e572f5166c1884253cb635b | 1,719 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day20.kt | thpz2210 | 575,577,457 | false | {"Kotlin": 50995} | import java.lang.Math.floorMod
import kotlin.math.sign
private class Solution20(input: List<String>) {
val numbersPart1 = input.mapIndexed { index, it -> Number(it.toLong(), moveIndex = index) }.toMutableList()
val numbersPart2 = input.mapIndexed { index, it -> Number(it.toLong() * 811589153L, moveIndex = index) }.toMutableList()
fun part1(): Long {
mixNumbers(numbersPart1)
return groveCoordinates(numbersPart1)
}
fun part2(): Long {
repeat(10) { mixNumbers(numbersPart2) }
return groveCoordinates(numbersPart2)
}
private fun mixNumbers(numbers: MutableList<Number>) {
numbers.forEach { it.isMoved = false }
while (true) {
val item = numbers.filter { !it.isMoved }.minByOrNull { it.moveIndex } ?: break
item.isMoved = true
val index = numbers.indexOf(item)
numbers.removeAt(index)
var newIndex = floorMod(index + item.value, numbers.size)
if (newIndex == 0 && item.value.sign == -1) newIndex = numbers.size
numbers.add(newIndex, item)
}
}
private fun groveCoordinates(numbers: List<Number>) = listOf(1000, 2000, 3000)
.map { n -> numbers.indexOfFirst { it.value == 0L } + n }
.sumOf { numbers[it % numbers.size].value }
data class Number(val value: Long, var isMoved: Boolean = false, val moveIndex: Int)
}
fun main() {
val testSolution = Solution20(readInput("Day20_test"))
check(testSolution.part1() == 3L)
check(testSolution.part2() == 1623178306L)
val solution = Solution20(readInput("Day20"))
println(solution.part1())
println(solution.part2())
}
| 0 | Kotlin | 0 | 0 | 69ed62889ed90692de2f40b42634b74245398633 | 1,687 | aoc-2022 | Apache License 2.0 |
05/05.kt | Steve2608 | 433,779,296 | false | {"Python": 34592, "Julia": 13999, "Kotlin": 11412, "Shell": 349, "Cython": 211} | import java.io.File
private class Ocean(val diagonals: Boolean) {
data class Point(val x: Int, val y: Int)
private val counts: MutableMap<Point, Int> = HashMap()
val mostDangerous: Int
get() = counts.values.filter { it >= 2 }.size
private fun addPoint(point: Point) {
counts[point] = counts.getOrDefault(point, 0) + 1
}
fun expandPoints(start: Point, end: Point) {
val smaller: Point
val bigger: Point
if (start.x == end.x && start.y != end.y) {
if (end.y < start.y) {
smaller = end
bigger = start
} else {
smaller = start
bigger = end
}
for (i in smaller.y..bigger.y) {
addPoint(Point(start.x, i))
}
} else if (start.x != end.x && start.y == end.y) {
if (end.x < start.x) {
smaller = end
bigger = start
} else {
smaller = start
bigger = end
}
for (i in smaller.x..bigger.x) {
addPoint(Point(i, start.y))
}
} else if (diagonals) {
if (end.x < start.x) {
smaller = end
bigger = start
} else {
smaller = start
bigger = end
}
// main diagonal
if (smaller.y < bigger.y) {
for (i in 0..bigger.x - smaller.x) {
addPoint(Point(smaller.x + i, smaller.y + i))
}
}
// second diagonal
else {
for (i in 0..bigger.x - smaller.x) {
addPoint(Point(smaller.x + i, smaller.y - i))
}
}
}
}
}
private fun oceanSpots(data: List<Pair<Ocean.Point, Ocean.Point>>, diagonals: Boolean): Int {
val ocean = Ocean(diagonals)
for ((start, end) in data) {
ocean.expandPoints(start, end)
}
return ocean.mostDangerous
}
private fun part1(data: List<Pair<Ocean.Point, Ocean.Point>>): Int = oceanSpots(data, diagonals = false)
private fun part2(data: List<Pair<Ocean.Point, Ocean.Point>>): Int = oceanSpots(data, diagonals = true)
private fun File.readData(): List<Pair<Ocean.Point, Ocean.Point>> = this
.readLines()
.filter { it.isNotBlank() }
.map { it.split("\\s+->\\s+".toRegex()) }
.map {
val point1 = it[0].split(",")
val point2 = it[1].split(",")
return@map Pair(
point1.map { i -> i.toInt() },
point2.map { i -> i.toInt() }
)
}
.map {
Pair(
Ocean.Point(it.first[0], it.first[1]),
Ocean.Point(it.second[0], it.second[1])
)
}
fun main() {
val example = File("example.txt").readData()
assert(5 == part1(example)) { "expected 5 dangerous areas" }
assert(12 == part2(example)) { "expected 12 dangerous areas" }
val data = File("input.txt").readData()
println(part1(data))
println(part2(data))
}
| 0 | Python | 0 | 1 | 2dcad5ecdce5e166eb053593d40b40d3e8e3f9b6 | 2,480 | AoC-2021 | MIT License |
src/year2022/08/Day08.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`08`
import readInput
import transpose
fun main() {
fun createGrid(input: List<String>): List<List<Int>> {
return input.map {
it.split("")
.drop(1)
.dropLast(1)
.map { item -> item.toInt() }
}
}
fun <T> genericCombine(
first: List<List<T>>,
second: List<List<T>>,
block: (left: T, right: T) -> T
): List<List<T>> {
return first.mapIndexed { i, line ->
List(line.size) { j -> block(first[i][j], second[i][j]) }
}
}
fun <T> Iterable<T>.takeUntil(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
if (!predicate(item)) {
list.add(item)
return list
}
list.add(item)
}
return list
}
fun calculateHorizontalVisibilityGrid(
grid: List<List<Int>>,
): List<List<Boolean>> {
return grid.mapIndexed { i, line ->
List(line.size) { j ->
val currentTreeSize = grid[i][j]
val leftSide = grid[i].take(j)
val rightSide = grid[i].drop(j + 1)
val isVisibleFromLeft = leftSide.all { it < currentTreeSize }
val isVisibleFromRight = rightSide.all { it < currentTreeSize }
isVisibleFromLeft || isVisibleFromRight
}
}
}
fun calculateHorizontalScoreGrid(
grid: List<List<Int>>,
): List<List<Int>> {
return grid.mapIndexed { i, line ->
List(line.size) { j ->
val currentTreeSize = grid[i][j]
val fromLeft = grid[i].take(j).reversed()
val fromLeftTaken = fromLeft.takeUntil { it < currentTreeSize }
val fromRight = grid[i].drop(j + 1)
val fromRightTaken = fromRight.takeUntil { it < currentTreeSize }
val leftCount = fromLeftTaken.count().takeIf { it != 0 } ?: 1
val rightCount = fromRightTaken.count().takeIf { it != 0 } ?: 1
if (fromLeft.isEmpty() || fromRight.isEmpty()) {
0
} else {
leftCount * rightCount
}
}
}
}
fun part1(input: List<String>): Int {
val grid = createGrid(input)
val vertical = transpose(calculateHorizontalVisibilityGrid(transpose(grid)))
val horizontal = calculateHorizontalVisibilityGrid(grid)
return genericCombine(vertical, horizontal) { left, right -> left || right }
.flatten()
.count { it }
}
fun part2(input: List<String>): Int {
val grid = createGrid(input)
val horizontal = calculateHorizontalScoreGrid(grid)
val vertical = transpose(calculateHorizontalScoreGrid(transpose(grid)))
return genericCombine(vertical, horizontal) { left, right -> left * right }
.flatten()
.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
val part1Test = part2(testInput)
println(part1Test)
check(part1Test == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 3,344 | KotlinAdventOfCode | Apache License 2.0 |
src/Day02.kt | armandmgt | 573,595,523 | false | {"Kotlin": 47774} | fun main() {
val scores = mapOf(
Pair("A", "X") to 4, Pair("A", "Y") to 8, Pair("A", "Z") to 3,
Pair("B", "X") to 1, Pair("B", "Y") to 5, Pair("B", "Z") to 9,
Pair("C", "X") to 7, Pair("C", "Y") to 2, Pair("C", "Z") to 6,
)
fun part1(input: List<String>): Int {
return input.sumOf {
val shapes = it.split(' ')
scores[Pair(shapes[0], shapes[1])]!!
}
}
val choices = mapOf(
Pair("A", "X") to "Z", Pair("A", "Y") to "X", Pair("A", "Z") to "Y",
Pair("B", "X") to "X", Pair("B", "Y") to "Y", Pair("B", "Z") to "Z",
Pair("C", "X") to "Y", Pair("C", "Y") to "Z", Pair("C", "Z") to "X",
)
fun part2(input: List<String>): Int {
return input.sumOf {
val shapeAndOutcome = it.split(' ')
scores[Pair(shapeAndOutcome[0], choices[Pair(shapeAndOutcome[0], shapeAndOutcome[1])]!!)]!!
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("resources/Day02_test")
check(part1(testInput) == 15)
val input = readInput("resources/Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 0d63a5974dd65a88e99a70e04243512a8f286145 | 1,197 | advent_of_code_2022 | Apache License 2.0 |
Advent-of-Code-2023/src/Day13.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day13"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
/**
* Finds the reflection line of a pattern by comparing the last line of the first part reversed with the first line
* of the second part.
*/
fun findReflectionLine(grid: List<String>): Int {
for (row in 1..<grid.size) {
val above = grid.subList(0, row).reversed() // Flip the first part so the line matches with the below part.
val below = grid.subList(row, grid.size)
val minSize = minOf(above.size, below.size)
val aboveTrimmed = above.subList(0, minSize)
val belowTrimmed = below.subList(0, minSize)
if (aboveTrimmed == belowTrimmed) {
return row
}
}
return 0
}
/**
* Finds a new reflection line of a pattern, by fixing the smudge. When the sum of differences is equal to 1 in the
* entire pattern, it means that the smudge found corresponds the reflection line.
*/
fun findDifferentReflectionLine(grid: List<String>): Int {
for (row in 1..<grid.size) {
val above = grid.subList(0, row).reversed()
val below = grid.subList(row, grid.size)
// Zip the first line of above with the first of below, then zip the first char of each line and compare them.
if (above.zip(below).sumOf { pair -> pair.first.zip(pair.second).count { (c1, c2) -> c1 != c2 } } == 1) {
return row
}
}
return 0
}
/**
* Finds the reflection line of a pattern, either horizontally or vertically.
*/
private fun part1(input: List<String>): Int {
val patterns = input.joinToString("\n").split("\n\n").map { it.split("\n") }
val horizontalSum = patterns.sumOf { findReflectionLine(it) * 100 }
val verticalSum = patterns.innerTranspose().sumOf { findReflectionLine(it) }
return horizontalSum + verticalSum
}
/**
* Finds a new reflection line based on a smudge.
*/
private fun part2(input: List<String>): Int {
val patterns = input.joinToString("\n").split("\n\n").map { it.split("\n") }
val horizontalSum = patterns.sumOf { findDifferentReflectionLine(it) * 100 }
val verticalSum = patterns.innerTranspose().sumOf { findDifferentReflectionLine(it) }
return horizontalSum + verticalSum
}
fun main() {
createTestFiles(AOC_DAY)
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 405
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 400
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== 37025" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 32854" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 2,877 | Advent-of-Code-2023 | Apache License 2.0 |
src/Day02.kt | JanTie | 573,131,468 | false | {"Kotlin": 31854} | import kotlin.math.absoluteValue
enum class Symbol(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun resultAgainst(other: Symbol): Result {
return if (other == this) Result.DRAW
else if (this.ordinal > other.ordinal) {
// this ordinal is higher
if ((this.ordinal - other.ordinal).absoluteValue > 1) Result.LOSS
else Result.WIN
} else {
// opponents ordinal is higher
if ((this.ordinal - other.ordinal).absoluteValue > 1) Result.WIN
else Result.LOSS
}
}
}
enum class Result(val points: Int) {
LOSS(0),
DRAW(3),
WIN(6),
}
data class Play(
val opponentSymbol: Symbol,
val mySymbol: Symbol,
) {
val result: Result = mySymbol.resultAgainst(opponentSymbol)
val myPoints: Int = mySymbol.points + result.points
override fun toString(): String {
return "Play(opponentSymbol=$opponentSymbol, mySymbol=$mySymbol, result=$result, myPoints=$myPoints)"
}
}
fun main() {
fun <T> parseInput(input: List<String>, secondValueParser: (String) -> T?) = input.map { it.split(" ") }
.mapNotNull {
val opponentSymbol = when (it[0]) {
"A" -> Symbol.ROCK
"B" -> Symbol.PAPER
"C" -> Symbol.SCISSORS
else -> return@mapNotNull null // parsing error
}
return@mapNotNull opponentSymbol to (secondValueParser(it[1]) ?: error("Parsing error"))
}
fun part1(input: List<String>): Int {
return parseInput(input) {
when (it) {
"X" -> Symbol.ROCK
"Y" -> Symbol.PAPER
"Z" -> Symbol.SCISSORS
else -> null // parsing error
}
}
.map { (opponentSymbol, mySymbol) -> Play(opponentSymbol, mySymbol) }
.sumOf { it.myPoints }
}
fun part2(input: List<String>): Int {
return parseInput(input) {
when (it) {
"X" -> Result.LOSS
"Y" -> Result.DRAW
"Z" -> Result.WIN
else -> null // parsing error
}
}.map { (opponentSymbol, desiredResult) ->
Play(opponentSymbol, Symbol.values().first { it.resultAgainst(opponentSymbol) == desiredResult })
}
.sumOf { it.myPoints }
}
// 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 | 3452e167f7afe291960d41b6fe86d79fd821a545 | 2,674 | advent-of-code-2022 | Apache License 2.0 |
untitled/src/main/kotlin/Day5.kt | jlacar | 572,845,298 | false | {"Kotlin": 41161} | class Day5(private val fileName: String) : AocSolution {
override val description: String get() = "Day 5 - Supply Stacks ($fileName)"
private val input = InputReader(fileName).rawLines.filter { it.isNotBlank() }
override fun part1() = Day5X(input).solve()
override fun part2() = Day5X(input).solve2()
}
class Day5X(val input: List<String> = """
| [D]
|[N] [C]
|[Z] [M] [P]
| 1 2 3
|
|move 1 from 2 to 1
|move 3 from 1 to 3
|move 2 from 2 to 1
|move 1 from 1 to 2
""".trimMargin("|").lines().filter { it.isNotBlank() }) {
fun solve(): String {
val crates = input.filter { it.trim().first() == '[' }
val stacks = createStacks(input.first { it.trim().first() == '1' })
val moves = input.filter { it.trim().first() == 'm' }
crates.reversed().forEach { layer -> addTo(stacks, layer) }
moves.forEach { op -> perform(op, stacks) }
return stacks.fold("") { acc, stack -> acc + stack.peek() }
}
fun solve2(): String {
val crates = input.filter { it.trim().first() == '[' }
val stacks = createStacks(input.first { it.trim().first() == '1' })
val moves = input.filter { it.trim().first() == 'm' }
crates.reversed().forEach { layer -> addTo(stacks, layer) }
moves.forEach { op -> perform1(op, stacks) }
return stacks.fold("") { acc, stack -> acc + stack.peek() }
}
private fun perform(operation: String, stacks: List<Stack<Char>>) {
val (_, count, frStack, toStack) = operation.split("""move | from | to """.toRegex())
( 1..count.toInt()).forEach { _ -> stacks[toStack.toInt()-1].push(stacks[frStack.toInt()-1].pop()) }
}
private fun perform1(operation: String, stacks: List<Stack<Char>>) {
val (count, frStack, toStack) = moves(operation.split("""move | from | to """.toRegex()))
val tempStack = Stack<Char>()
(1..count).forEach { _ -> tempStack.push(stacks[frStack].pop()) }
(1..tempStack.height).forEach { _ -> stacks[toStack].push(tempStack.pop()) }
}
private fun moves(params: List<String>) = intArrayOf(params[1].toInt(), params[2].toInt()-1, params[3].toInt()-1)
private fun addTo(stacks: List<Stack<Char>>, layer: String) {
for (i in stacks.indices) {
(4 * i + 1).takeIf { it < layer.length }?.also { offset ->
layer.substring(offset).first().takeIf { ch -> ch != ' ' }?.also {
ch -> stacks[i].push(ch)
}
}
}
}
private fun createStacks(stackList: String): List<Stack<Char>> {
val stacks = mutableListOf<Stack<Char>>()
stackList.trim().split("""\s+""".toRegex()).forEach { _ -> stacks.add(Stack()) }
return stacks
}
}
class Stack<E> {
private val stack: ArrayDeque<E> = ArrayDeque()
val height: Int get() = stack.size
fun clear() = stack.clear()
fun push(element: E) = stack.add(element)
fun pop(): E = stack.removeLast()
fun peek(): E? = stack.lastOrNull()
fun isNotEmpty() = stack.isNotEmpty()
override fun toString(): String {
return stack.toString()
}
}
fun main() {
Day5("Day5-sample.txt") solution {
part1() shouldBe "CMZ"
part2() shouldBe "MCD"
}
Day5("Day5.txt") solution {
part1() shouldBe "MQTPGLLDN"
part2() shouldBe "LVZPSTTCZ"
}
Day5("Day5-alt.txt") solution {
part1() shouldBe "HBTMTBSDC"
part2() shouldBe "PQTJRSHWS"
}
} | 0 | Kotlin | 0 | 2 | dbdefda9a354589de31bc27e0690f7c61c1dc7c9 | 3,581 | adventofcode2022-kotlin | The Unlicense |
src/main/kotlin/days/Day10.kt | mstar95 | 317,305,289 | false | null | package days
import java.text.DecimalFormat
class Day10 : Day(10) {
override fun partOne(): Any {
val input = prepareInput(inputList)
val sorted = input.sorted()
val result = calculateDifferences(0, sorted, Differences(0, 0, 0))
println(result)
return result.one * result.three
}
override fun partTwo(): Any {
val input = prepareInput(inputList)
val sorted = input.sorted()
val result = calculateCombinations(0, sorted)
println(0.3.toFloat().toDouble().toFloat())
return result
}
private fun calculateCombinations(jolt: Int, jolts: List<Int>): Long {
if (jolts.size == 0) {
return 1
}
val v1 = jolts.first()
val v2 = jolts.getOrNull(1)
val v3 = jolts.getOrNull(2)
val v4 = jolts.getOrNull(3)
val d1 = v1 - jolt
val d2 = minus(v2, jolt)
val d3 = minus(v3, jolt)
val d4 = minus(v4, jolt)
// println( "V: $v1, $v2, $v3, $v4")
// println( "D: $d1, $d2, $d3, $d4")
if(d1 != 1 || v2 == null) {
return calculateCombinations(v1, jolts.drop(1))
}
if(d2 != 2 || v3 == null) {
return calculateCombinations(v1, jolts.drop(1))
}
if(d3 != 3 || v4 == null) {
return calculateCombinations(v2, jolts.drop(2)) * 2
}
if(d4 != 4 ) {
return calculateCombinations(v3 , jolts.drop(3)) * 4
}
return calculateCombinations( v4, jolts.drop(4)) * 7
}
private fun minus(v2: Int?, jolt: Int) = v2?.let { it - jolt } ?: 0
fun calculateDifferences(jolt: Int, jolts: List<Int>, differences: Differences): Differences {
if (jolts.isEmpty()) {
return differences.put(3)
}
val head = jolts.first()
return calculateDifferences(head, jolts.tail(), differences.put(head - jolt))
}
}
data class Differences(val one: Int, val two: Int, val three: Int) {
fun put(diff: Int): Differences {
return when (diff) {
1 -> copy(one = one + 1)
2 -> copy(two = two + 1)
3 -> copy(three = three + 1)
else -> throw error("Unsupported diff: $diff")
}
}
}
private fun <T> List<T>.tail() = drop(1)
private fun prepareInput(list: List<String>) = list.map { it.toInt() }
| 0 | Kotlin | 0 | 0 | ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81 | 2,388 | aoc-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day13/TransparentOrigami.kt | Arch-vile | 433,381,878 | false | {"Kotlin": 57129} | package day13
import utils.Matrix
import utils.Point
import utils.read
fun main() {
solve().let { println(it) }
}
fun solve(): Pair<Int, String> {
val lines = read("./src/main/resources/day13Input.txt")
val points = lines.takeWhile { it.isNotEmpty() }
.map { it.split(",") }
.map { Point(it[0].toLong(), it[1].toLong()) }
val folds = lines.dropWhile { it.isNotEmpty() }
.drop(1)
.map {
if (it.contains("y=")) {
Pair(0L, it.split("=")[1].toLong())
} else
Pair(it.split("=")[1].toLong(),0L)
}
val sheetWidth = points.maxOf { it.x } + 1L
val sheetHeight = points.maxOf { it.y } + 1L
val sheet = Matrix(sheetWidth!!,sheetHeight!!){
x,y -> if(points.contains(Point(x.toLong(),y.toLong()))) "#" else " "
}
val foldedOnce = fold(folds[0], sheet)
val folded = folds.fold(sheet) {
acc, next -> fold(next,acc)
}
val notBlanks = foldedOnce.all().map { it.value }
.filter { it.isNotBlank() }
.count()
return Pair(notBlanks, folded.toString())
}
fun fold(pair: Pair<Long, Long>, sheet: Matrix<String>): Matrix<String> {
return if(pair.first != 0L) foldX(pair.first,sheet) else foldY(pair.second, sheet)
}
fun foldX(foldAt: Long, sheet: Matrix<String>): Matrix<String> {
return foldY(foldAt, sheet.rotateCW()).rotateCW().rotateCW().rotateCW()
}
fun foldY(foldAt: Long, sheet: Matrix<String>): Matrix<String> {
val upperPart = sheet.tile(Point(0,0),
Point(sheet.width().toLong()-1,foldAt-1))
val lowerPart = sheet.tile(Point(0,foldAt+1),
Point(sheet.width().toLong()-1,sheet.height().toLong()-1))
val lowerFlipped = lowerPart.flipHorizontal()
upperPart.combine(lowerFlipped) {
u, l -> if (u.value.isNotBlank() || l.value.isNotBlank()) "#" else " "
}
return upperPart
}
| 0 | Kotlin | 0 | 0 | 4cdafaa524a863e28067beb668a3f3e06edcef96 | 1,888 | adventOfCode2021 | Apache License 2.0 |
y2023/src/main/kotlin/adventofcode/y2023/Day24.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
import adventofcode.util.collections.combinations
import java.math.BigDecimal
fun main() {
Day24.solve()
}
object Day24 : AdventSolution(2023, 24, "Never Tell Me The Odds") {
override fun solvePartOne(input: String): Any {
return solve(input, 200000000000000.toBigDecimal()..400000000000000.toBigDecimal())
}
fun solve(input: String, range: ClosedRange<BigDecimal>): Int {
val parsed = parse(input)
val result = parsed.combinations { a, b -> intersection(a, b) }
return result.filterNotNull().count { (x, y) -> x in range && y in range }
}
private fun intersection(a: Hailstone, b: Hailstone): Pair<BigDecimal, BigDecimal>? {
val v1 = a.position
val v2 = a.position + a.velocity
val v3 = b.position
val v4 = b.position + b.velocity
val x1 = v1.x
val y1 = v1.y
val x2 = v2.x
val y2 = v2.y
val x3 = v3.x
val y3 = v3.y
val x4 = v4.x
val y4 = v4.y
val denominator = ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))
val numeratorX =
(x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)
val numeratorY =
(x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)
return if (denominator.abs() < 0.000000000000001.toBigDecimal()) null
else {
val pair = numeratorX / denominator to numeratorY / denominator
if ((pair.first - x1).signum() != a.velocity.x.signum()) null
else if ((pair.first - x3).signum() != b.velocity.x.signum()) null
else pair
}
}
override fun solvePartTwo(input: String): Long {
//can probably prune this intelligently
fun generateVelocities() = buildList {
for (x in -200..200L)
for (y in -200..200L)
add(V3(x.toBigDecimal(), y.toBigDecimal(), BigDecimal.ZERO))
}
val stones = parse(input)
val velocity = generateVelocities().first { throwVelocity ->
val shifted = stones.map { it.copy(velocity = it.velocity - throwVelocity) }
val point = intersection(shifted[0], shifted[1]) ?: return@first false
shifted.all { (hp, hv) ->
if (hv.x == BigDecimal.ZERO) point.first == hp.x
else if (hv.y == BigDecimal.ZERO) point.second == hp.y
else {
val tx = (point.first - hp.x) / hv.x
val ty = (point.second - hp.y) / hv.y
tx == ty
}
}
}
val shifted1 = stones[0].copy(velocity = stones[0].velocity - velocity)
val shifted2 = stones[1].copy(velocity = stones[1].velocity - velocity)
val (x, y) = intersection(shifted1, shifted2)!!
val t1 = (x - shifted1.position.x) / shifted1.velocity.x
val z1 = shifted1.position.z + (shifted1.velocity.z * t1)
val t2 = (x - shifted2.position.x) / shifted2.velocity.x
val z2 = shifted2.position.z + (shifted2.velocity.z * t2)
val vz = (z2 - z1) / (t2 - t1)
val z = z1 - t1 * vz
return (x + y + z).toLong()
}
}
private fun parse(input: String) = input.lines().map {
it.split(", ", " @ ").map { it.trim().toBigDecimal() }.chunked(3) { (x, y, z) -> V3(x, y, z) }
.let { Hailstone(it[0], it[1]) }
}
private data class Hailstone(val position: V3, val velocity: V3)
private data class V3(val x: BigDecimal, val y: BigDecimal, val z: BigDecimal) {
operator fun plus(o: V3) = V3(x + o.x, y + o.y, z + o.z)
operator fun minus(o: V3) = V3(x - o.x, y - o.y, z - o.z)
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 3,759 | advent-of-code | MIT License |
2023/src/day04/day04.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day04
import GREEN
import RESET
import printTimeMillis
import readInput
import kotlin.math.pow
data class Card(
val winning: List<String>,
val numbers: List<String>
) {
fun matches() = numbers.toSet().intersect(winning.toSet())
fun score(): Double {
val matches = matches()
val score = 2.0.pow((matches.size - 1).toDouble())
if (score < 1) return 0.0
return score
}
}
private fun List<String>.toCardList(): List<Card> = map {
it.split(": ")[1].let {
val winning = it.split("|")[0].split(" ").map { it.trim() }
.filter { it.isNotBlank() }
val numbers = it.split("|")[1].split(" ").map { it.trim() }
.filter { it.isNotBlank() }
Card(winning = winning, numbers = numbers)
}
}
fun part1(input: List<String>) = input.toCardList().sumOf {it.score() }.toInt()
fun part2(input: List<String>): Int {
val cards = input.toCardList()
val nbCards = IntArray(cards.size) { 1 }
for (idx in cards.indices) {
val nbMatches = cards[idx].matches().size
for (i in 1..nbMatches) {
nbCards[idx + i] += nbCards[idx]
}
}
return nbCards.sum()
}
fun main() {
val testInput = readInput("day04_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day04.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 1,629 | advent-of-code | Apache License 2.0 |
src/Day02.kt | allisonjoycarter | 574,207,005 | false | {"Kotlin": 22303} |
enum class Scoring(val value: Int) {
Lose(0),
Draw(3),
Win(6)
}
fun main() {
fun part1(input: List<String>): Int {
val shapes = mapOf(
'A' to 1, // rock
'B' to 2, // paper
'C' to 3 // scissors
)
val responses = mapOf(
'X' to 1, // rock
'Y' to 2, // paper
'Z' to 3 // scissors
)
val wins = mapOf(
1 to 3,
2 to 1,
3 to 2,
)
var total = 0
input.forEach { line ->
val played = shapes[line.first()]
val response = responses[line.trim().last()]
val outcome: Scoring = when {
played == response -> Scoring.Draw
wins.entries.find { it.key == response && it.value == played } != null -> Scoring.Win
else -> Scoring.Lose
}
total += (response ?: 0) + outcome.value
}
return total
}
fun part2(input: List<String>): Int {
val shapes = mapOf(
'A' to 1, // rock
'B' to 2, // paper
'C' to 3 // scissors
)
val results = mapOf(
'X' to Scoring.Lose,
'Y' to Scoring.Draw,
'Z' to Scoring.Win
)
val wins = mapOf(
1 to 3,
2 to 1,
3 to 2,
)
var total = 0
input.forEach { line ->
val played = shapes[line.first()]
val desiredResult = results[line.trim().last()]
val shape = when(desiredResult) {
Scoring.Draw -> played
Scoring.Lose -> wins.entries.find { it.key == played }?.value
Scoring.Win -> wins.entries.find { it.value == played }?.key
else -> 0
}
total += (shape ?: 0) + (desiredResult?.value ?: 0)
}
return total
}
// 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("Part 1:")
println(part1(input))
println("Part 2:")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 86306ee6f4e90c1cab7c2743eb437fa86d4238e5 | 2,339 | adventofcode2022 | Apache License 2.0 |
src/Day09.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
fun part1(input: List<String>) = run(input, 2)
fun part2(input: List<String>) = run(input, 10)
// test if implementation meets criteria from the description, like:
check(part1(readInput("Day09_test")) == 13)
check(part2(readInput("Day09_test2")) == 36)
val input = readInput("Day09")
println(part1(input)) // 6266
println(part2(input)) // 2369
}
private fun run(input: List<String>, totalKnots: Int): Int {
val knots = Array(totalKnots) { 0 to 0 }
val tailVisited = hashSetOf<Pair<Int, Int>>()
input.map { it.split(' ', limit = 2) }
.forEach { (dir, quantity) ->
repeat(quantity.toInt()) {
val oldHead = knots.first()
knots[0] = when (dir) {
"U" -> oldHead.first to oldHead.second - 1
"D" -> oldHead.first to oldHead.second + 1
"L" -> oldHead.first - 1 to oldHead.second
"R" -> oldHead.first + 1 to oldHead.second
else -> throw Error("Bad Input!")
}
for (i in 1 until knots.size) {
val prev = knots[i - 1]
val curr = knots[i]
if (prev touching curr) break
val deltaX = (prev.first - curr.first).sign
val deltaY = (prev.second - curr.second).sign
knots[i] = curr.first + deltaX to curr.second + deltaY
}
tailVisited += knots.last()
}
}
return tailVisited.count()
}
private infix fun Pair<Int, Int>.touching(other: Pair<Int, Int>) = abs(first - other.first) <= 1 && abs(second - other.second) <= 1
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 1,770 | advent-of-code-2022 | Apache License 2.0 |
src/day_7/kotlin/Day7.kt | Nxllpointer | 573,051,992 | false | {"Kotlin": 41751} | // AOC Day 7
data class File(val name: String, val size: Long)
data class Directory(
val name: String,
val parent: Directory?,
val subDirectories: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf()
) {
fun getOrCreateSubDirectory(name: String): Directory =
subDirectories.firstOrNull { it.name == name } ?: Directory(name, this).also { subDirectories.add(it) }
fun getAllFiles(): List<File> = files + subDirectories.flatMap { it.getAllFiles() }
fun getAllSubDirectories(): List<Directory> = subDirectories + subDirectories.flatMap { it.getAllSubDirectories() }
fun getSize() = getAllFiles().sumOf { it.size }
}
fun part1(rootDirectory: Directory) {
val smallDirectoriesTotalSize = (rootDirectory.getAllSubDirectories() + rootDirectory)
.map { it.getSize() }
.filter { it <= 100000 }
.sum()
println("Part 1: The small directories have a total size of $smallDirectoriesTotalSize")
}
const val TOTAL_SPACE = 70_000_000
const val REQUIRED_SPACE = 30_000_000
fun part2(rootDirectory: Directory) {
val usedSpace = rootDirectory.getSize()
val smallestDirectoryToDeleteSize = (rootDirectory.getAllSubDirectories() + rootDirectory)
.map { it.getSize() }
.filter { TOTAL_SPACE - usedSpace + it >= REQUIRED_SPACE }
.min()
println("Part 2: The smallest directory to delete for the update has a size of $smallestDirectoryToDeleteSize")
}
fun main() {
val rootDirectory = getAOCInput { rawInput ->
val terminalOutput = rawInput.trim().split("\n").drop(1) // Drop root cd
var currentDirectory = Directory("/", null)
fun List<String>.isFileInfo() = this[0].all { it.isDigit() }
fun List<String>.isCDBackCommand() = this[0] == "$" && this[1] == "cd" && this[2] == ".."
fun List<String>.isCDCommand() = this[0] == "$" && this[1] == "cd"
terminalOutput.forEach { line ->
val sections = line.split(" ")
with(sections) {
when {
isFileInfo() -> currentDirectory.files.add(File(sections[1], sections[0].toLong()))
isCDBackCommand() -> currentDirectory = currentDirectory.parent!!
isCDCommand() -> currentDirectory = currentDirectory.getOrCreateSubDirectory(sections[2])
}
}
}
// Go back to root
while (currentDirectory.parent != null) currentDirectory = currentDirectory.parent!!
currentDirectory
}
part1(rootDirectory)
part2(rootDirectory)
}
| 0 | Kotlin | 0 | 0 | b6d7ef06de41ad01a8d64ef19ca7ca2610754151 | 2,606 | AdventOfCode2022 | MIT License |
src/Day02.kt | defvs | 572,381,346 | false | {"Kotlin": 16089} | import RPSResult.Companion.getShapeForResult
import Shapes.Companion.getResult
enum class RPSResult(val value: Int) {
Loss(0), Draw(3), Win(6);
companion object {
fun fromString(str: String) = when (str) {
"X" -> Loss
"Y" -> Draw
"Z" -> Win
else -> throw IllegalArgumentException("RPSResult fromString should be any of X,Y,Z.")
}
fun RPSResult.getShapeForResult(other: Shapes) = Shapes.values().single { it.getResult(other) == this }
}
}
enum class Shapes(val value: Int) {
Rock(1), Paper(2), Scissors(3);
companion object {
fun fromString(str: String) = when (str) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> throw IllegalArgumentException("Shapes fromString should be any of A,B,C,X,Y,Z.")
}
fun Shapes.getResult(other: Shapes) = when {
this == other -> RPSResult.Draw
this == Rock && other == Paper -> RPSResult.Loss
this == Paper && other == Scissors -> RPSResult.Loss
this == Scissors && other == Rock -> RPSResult.Loss
else -> RPSResult.Win
}
}
}
fun main() {
fun part1(input: List<String>) = input.map { it.split(" ").map { Shapes.fromString(it) }.zipWithNext().single() }
.sumOf { it.second.getResult(it.first).value + it.second.value }
fun part2(input: List<String>) = input.map {
it.split(" ").zipWithNext().single().let { Shapes.fromString(it.first) to RPSResult.fromString(it.second) }
}.sumOf {
it.second.getShapeForResult(it.first).value + it.second.value
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput).also { println("Test 1 result was: $it") } == 15)
check(part2(testInput).also { println("Test 2 result was: $it") } == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | caa75c608d88baf9eb2861eccfd398287a520a8a | 1,825 | aoc-2022-in-kotlin | Apache License 2.0 |
facebook/y2019/qual/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package facebook.y2019.qual
import kotlin.random.Random
private fun solve(): String {
val (n, m) = readInts()
val requirements = List(m) { readInts().map { it - 1 } }
val ans = IntArray(n)
try {
construct(ans, -1, List(n) { it }, requirements)
} catch (_: IllegalArgumentException) {
return "Impossible"
}
return ans.map { it + 1 }.joinToString(" ")
}
private fun construct(ans: IntArray, parent: Int, vertices: Collection<Int>, requirements: List<List<Int>>) {
val possibleRoots = vertices.toMutableSet()
for (r in requirements) {
repeat(2) {
if (r[it] != r[2]) {
possibleRoots.remove(r[it])
}
}
}
fun canBeRoot(root: Int): Pair<Int, DisjointSetUnion>? {
val different = mutableListOf<Pair<Int, Int>>()
val dsu = DisjointSetUnion(ans.size)
for (r in requirements) {
if (r[2] == root) {
if ((r[0] != root) and (r[1] != root)) {
different.add(Pair(r[0], r[1]))
}
continue
}
dsu.unite(r[0], r[1])
dsu.unite(r[0], r[2])
}
for ((a, b) in different) {
if (dsu[a] == dsu[b]) {
return null
}
}
return Pair(root, dsu)
}
val (root, dsu) = possibleRoots.mapNotNull(::canBeRoot).firstOrNull() ?: throw IllegalArgumentException()
ans[root] = parent
val children = vertices.filter { (dsu[it] == it) and (it != root) }
val requirementsByChild = requirements.filter { it[2] != root }.groupBy { dsu[it[0]] }
val verticesByChild = vertices.minus(root).groupBy { dsu[it] }
for (v in children) {
construct(ans, root, verticesByChild.getValue(v), requirementsByChild.getOrElse(v) { listOf() })
}
}
class DisjointSetUnion(n: Int) {
internal val p: IntArray = IntArray(n) { it }
internal val r = Random(566)
internal operator fun get(v: Int): Int {
if (p[v] == v) {
return v
}
p[v] = get(p[v])
return p[v]
}
internal fun unite(v: Int, u: Int) {
val a = get(v)
val b = get(u)
if (r.nextBoolean()) {
p[a] = b
} else {
p[b] = a
}
}
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,199 | competitions | The Unlicense |
src/Day13.kt | djleeds | 572,720,298 | false | {"Kotlin": 43505} | import kotlinx.serialization.json.*
import java.util.*
import kotlin.math.max
fun <T, R> List<T>.zipWithPadding(other: List<R>): List<Pair<T?, R?>> =
buildList { for (i in 0 until max(this@zipWithPadding.size, other.size)) add(this@zipWithPadding.getOrNull(i) to other.getOrNull(i)) }
private fun JsonArray.zipWithPadding(other: JsonArray) = this.toList().zipWithPadding(other.toList())
private fun isInRightOrder(leftPacket: JsonArray, rightPacket: JsonArray) = leftPacket < rightPacket
operator fun JsonArray.compareTo(other: JsonArray): Int {
val stack = Stack<Pair<JsonElement?, JsonElement?>>().apply { addAll(this@compareTo.zipWithPadding(other).reversed()) }
while (stack.isNotEmpty()) {
val (left, right) = stack.pop()
when {
left == null && right != null -> return -1
left != null && right == null -> return 1
left is JsonPrimitive && right is JsonPrimitive -> when {
left.int < right.int -> return -1
left.int == right.int -> continue
left.int > right.int -> return 1
}
left is JsonArray && right is JsonArray -> left.zipWithPadding(right).reversed().forEach(stack::add)
left is JsonPrimitive && right is JsonArray -> stack.push(JsonArray(listOf(left)) to right)
left is JsonArray && right is JsonPrimitive -> stack.push(left to JsonArray(listOf(right)))
else -> throw IllegalArgumentException()
}
}
throw IllegalStateException()
}
fun dividerPacket(number: Int): JsonArray = JsonArray(listOf(JsonArray(listOf(JsonPrimitive(number)))))
fun main() {
fun parse(input: List<String>) = input.filter { it.isNotEmpty() }.map { Json.parseToJsonElement(it).jsonArray }
fun part1(input: List<String>): Int = parse(input)
.chunked(2)
.map { isInRightOrder(it[0], it[1]) }
.mapIndexed { index, result -> (index + 1).takeIf { result } ?: 0 }
.sumOf { it }
fun part2(input: List<String>): Int {
val divider2 = dividerPacket(2)
val divider6 = dividerPacket(6)
return buildList { addAll(parse(input)); add(divider2); add(divider6) }
.sortedWith(JsonArray::compareTo)
.mapIndexed { index, it -> if (it == divider2 || it == divider6) index + 1 else 1 }
.fold(1) { acc, it -> acc * it }
}
val testInput = readInput("Day13_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 4 | 98946a517c5ab8cbb337439565f9eb35e0ce1c72 | 2,681 | advent-of-code-in-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/days/Solution19.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import adventOfCode.util.ints
import kotlin.math.max
import kotlin.math.min
typealias WorkflowCondition = Triple<String, Int, PairOf<Int>>
typealias WorkflowMap = Map<String, List<WorkflowCondition>>
object Solution19 : Solution<Pair<WorkflowMap, List<List<Int>>>>(AOC_YEAR, 19) {
override fun getInput(handler: InputHandler): Pair<WorkflowMap, List<List<Int>>> {
val pieces = handler.getInput("\n\n")
val workflows = mutableMapOf<String, List<WorkflowCondition>>()
pieces.first().split('\n').forEach workflowLoop@{ line ->
val source = line.substringBefore('{')
val conditions = mutableListOf<WorkflowCondition>()
line.substringAfter('{')
.substringBefore('}')
.split(',')
.map { it.split(':') }
.forEach { pieces ->
if (pieces.size == 1) {
conditions.add(Triple(pieces[0], -1, -1 to -1))
workflows[source] = conditions
return@workflowLoop
}
val condition = pieces[0]
val dest = pieces[1]
val index = "xmas".indexOf(condition[0])
val value = condition.substring(2).toInt()
conditions.add(
Triple(
dest,
index,
when (condition[1]) {
'<' -> 1 to value
else -> value + 1 to 4001
}
)
)
}
}
val parts = pieces.last().split('\n').map(String::ints)
return workflows to parts
}
private fun mapWorkflows(workflows: WorkflowMap): List<List<PairOf<Int>>> {
val validCombinations = mutableListOf<List<PairOf<Int>>>()
val queue = ArrayDeque<Pair<String, List<PairOf<Int>>>>()
queue.add("in" to List(4) { 1 to 4001 })
do {
val (curr, bounds) = queue.removeLast()
when (curr) {
"R" -> continue
"A" -> {
validCombinations.add(bounds)
continue
}
}
val remainingBounds = bounds.toMutableList()
for ((next, i, r) in workflows.getValue(curr)) {
if (i == -1) {
queue.add(next to remainingBounds)
break
}
val (a1, b1) = r
val (a2, b2) = remainingBounds[i]
val intersection = max(a1, a2) to min(b1, b2)
if (intersection.first < intersection.second) {
val passed = remainingBounds.toMutableList()
passed[i] = intersection
queue.add(next to passed)
}
val difference = when {
b2 <= a1 -> a2 to b2
a2 >= b1 -> a2 to b2
b2 <= b1 -> a2 to a1
else -> b1 to b2
}
if (difference.first >= difference.second) break
remainingBounds[i] = difference
}
} while (queue.isNotEmpty())
return validCombinations
}
override fun solve(input: Pair<WorkflowMap, List<List<Int>>>): Pair<Int, Long> {
val (workflows, parts) = input
val validCombinations = mapWorkflows(workflows)
val ans1 = parts.filter { part ->
validCombinations.any { combination -> combination.zip(part).all { (r, p) -> p in r.first until r.second } }
}.flatten().sum()
val ans2 = validCombinations.sumOf { combination ->
combination.map { it.second - it.first }.fold(1L, Long::times)
}
return ans1 to ans2
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 4,034 | Advent-of-Code-2023 | MIT License |
src/main/kotlin/dk/lessor/Day16.kt | aoc-team-1 | 317,571,356 | false | {"Java": 70687, "Kotlin": 34171} | package dk.lessor
fun main() {
val lines = readFile("day_16.txt")
val (ranges, myTicket, otherTickets) = parseTicketInformation(lines)
println(otherInvalidTickets(ranges, otherTickets))
println(determineTicketFields(ranges, myTicket, otherTickets))
}
fun parseTicketInformation(lines: List<String>): Triple<Map<String, List<IntRange>>, List<Int>, List<List<Int>>> {
val ranges = lines.take(20).associate {
val key = it.split(": ").first()
val r = it.split(": ").last().split(" or ").map { range ->
val (start, end) = range.split("-").map(String::toInt)
IntRange(start, end)
}
key to r
}
val ticket = lines.drop(22).take(1).first().split(",").map(String::toInt).toList()
val otherTicket = lines.drop(25).map { it.split(",").map(String::toInt) }
return Triple(ranges, ticket, otherTicket)
}
fun otherInvalidTickets(ranges: Map<String, List<IntRange>>, otherTickets: List<List<Int>>): Int {
val r = ranges.values.flatten()
val t = otherTickets.flatten()
return t.filter { v -> !r.any { it.contains(v) } }.sum()
}
fun determineTicketFields(ranges: Map<String, List<IntRange>>, myTicket: List<Int>, otherTickets: List<List<Int>>): Long {
val r = ranges.values.flatten()
val t = otherTickets.filter { it.validateTicket(r) }
val fieldValues = Array<MutableList<Int>>(myTicket.size) { mutableListOf() }
for (ticket in t) {
for (i in 0..myTicket.lastIndex) {
fieldValues[i].add(ticket[i])
}
}
val possibleRanges = Array<MutableList<String>>(myTicket.size) { mutableListOf() }
for (i in 0..fieldValues.lastIndex) {
for (range in ranges) {
if (fieldValues[i].validateTicket(range.value)) possibleRanges[i].add(range.key)
}
}
while (possibleRanges.any { it.size != 1 }) {
val unique = possibleRanges.filter { it.size == 1 }.flatten()
possibleRanges.filter { it.size > 1 && it.any { name -> unique.contains(name) } }.forEach { it.removeAll(unique) }
}
var sum = 1L
for (i in 0..possibleRanges.lastIndex) {
if (possibleRanges[i].first().startsWith("departure")) sum *= myTicket[i]
}
return sum
}
fun List<Int>.validateTicket(ranges: List<IntRange>): Boolean {
return all { v -> ranges.any { it.contains(v) } }
} | 0 | Java | 0 | 0 | 48ea750b60a6a2a92f9048c04971b1dc340780d5 | 2,357 | lessor-aoc-comp-2020 | MIT License |
src/Day02.kt | ajmfulcher | 573,611,837 | false | {"Kotlin": 24722} | fun main() {
val scores = hashMapOf(
"A" to 1,
"X" to 1,
"B" to 2,
"Y" to 2,
"C" to 3,
"Z" to 3
)
fun calculateScore(line: String): Int {
val them = scores[line.substring(0,1)]!!
val us = scores[line.substring(2,3)]!!
return us + when {
them == us -> 3
them == 3 && us == 1 -> 6
them == 1 && us == 3 -> 0
them + 1 == us -> 6
them - 1 == us -> 0
else -> 0
}
}
fun calculateScoreFromShape(line: String): Int {
val them = scores[line.substring(0,1)]!!
val result = line.substring(2,3)
return when {
result == "Y" -> them + 3
result == "X" && them == 1 -> 0 + 3
result == "Z" && them == 3 -> 6 + 1
result == "X" -> 0 + them - 1
result == "Z" -> 6 + them + 1
else -> 0
}
}
fun part1(input: List<String>): Int {
return input
.map { calculateScore(it) }
.fold(0) { acc, i -> acc + i }
}
fun part2(input: List<String>): Int {
return input
.map { calculateScoreFromShape(it) }
.fold(0) { acc, i -> acc + i }
}
// 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(testInput))
check(part2(testInput) == 12)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 981f6014b09e347241e64ba85e0c2c96de78ef8a | 1,572 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/de/consuli/aoc/year2022/days/Day11.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2022.days
import de.consuli.aoc.common.Day
class Day11 : Day(11, 2022) {
override fun partOne(testInput: Boolean): Any {
return doMonkeyBusiness(testInput, 20, true)
}
override fun partTwo(testInput: Boolean): Any {
return doMonkeyBusiness(testInput, 10000, false)
}
private fun doMonkeyBusiness(testInput: Boolean, repeat: Int, divideWorryLevel: Boolean): Long {
val monkeys = getMonkeysFromInput(testInput)
repeat(repeat) {
run {
round(monkeys, divideWorryLevel)
}
}
val sortedDescending = monkeys.map { it.inspections }.sortedDescending()
return sortedDescending[0] * sortedDescending[1]
}
fun getMonkeysFromInput(testInput: Boolean): List<Monkey> {
val monkeys = ArrayList<Monkey>()
getInput(testInput).chunked(7).forEach { monkeyInput ->
monkeys.add(
Monkey(
monkeyInput[1].split(":")[1].trim().split(",").map { it.trim().toLong() }
.map { Item(it) },
monkeyInput[2].split("new = ")[1],
TestAction(
monkeyInput[3].split("divisible by")[1].trim().toLong(),
Pair(
monkeyInput[4].split("throw to monkey ")[1].trim().toInt(),
monkeyInput[5].split("throw to monkey ")[1].trim().toInt()
)
)
)
)
}
return monkeys
}
private fun round(monkeys: List<Monkey>, divideWorryLevel: Boolean): List<Monkey> {
monkeys.forEach { monkey ->
run {
monkey.currentItems.forEach { item ->
monkey.inspections++
val operation = monkey.operation.split(" ")
val operand = if (operation[2] == "old") item.worryLevel else operation[2].toLong()
when (operation[1]) {
"+" -> item.worryLevel = item.worryLevel + operand
"*" -> item.worryLevel = item.worryLevel * operand
}
if (divideWorryLevel) {
item.worryLevel = item.worryLevel.floorDiv(3)
}
val receivingMonkey = monkeys[monkey.testAction.getTestResult(item.worryLevel)]
receivingMonkey.currentItems = receivingMonkey.currentItems.plus(item)
monkey.currentItems = monkey.currentItems.minus(item)
}
}
}
return monkeys
}
}
class Monkey(
var currentItems: List<Item>,
var operation: String,
var testAction: TestAction,
var inspections: Long = 0L
)
class TestAction(var divisibleBy: Long, var actions: Pair<Int, Int>) {
fun getTestResult(input: Long): Int {
return if (input % divisibleBy == 0L) {
actions.first
} else {
actions.second
}
}
}
class Item(var worryLevel: Long)
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 3,114 | advent-of-code | Apache License 2.0 |
src/Day05.kt | dmstocking | 575,012,721 | false | {"Kotlin": 40350} | import java.util.Stack
fun main() {
val regex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
fun part1(input: List<String>): String {
val stacks = input
.first { it[1] == '1' }
.trim()
.split("\\s+".toRegex())
.last()
.toInt()
.let { 0 until it }
.map { Stack<Char>() }
input
.takeWhile { it[1] != '1' }
.forEach { line ->
line.crates(stacks.size)
.mapIndexed { index, c -> index to c }
.filter { (_, c) -> c != ' ' }
.forEach { (i, c) ->
stacks[i].add(0, c)
}
}
input
.dropWhile { !it.startsWith("move") }
.flatMap {
val match = regex.matchEntire(it)!!
val n = match.groupValues[1].toInt()
List(n) {
match.groupValues[2].toInt() to match.groupValues[3].toInt()
}
}
.map { (f, t) -> (f-1) to (t-1) }
.forEach { (from, to) ->
stacks[to].add(stacks[from].pop())
}
return stacks.map { it.last() }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val stacks = input
.first { it[1] == '1' }
.trim()
.split("\\s+".toRegex())
.last()
.toInt()
.let { 0 until it }
.map { Stack<Char>() }
input
.takeWhile { it[1] != '1' }
.forEach { line ->
line.crates(stacks.size)
.mapIndexed { index, c -> index to c }
.filter { (_, c) -> c != ' ' }
.forEach { (i, c) ->
stacks[i].add(0, c)
}
}
input
.dropWhile { !it.startsWith("move") }
.forEach {
val match = regex.matchEntire(it)!!
val n = match.groupValues[1].toInt()
val from = stacks[match.groupValues[2].toInt()-1]
val to = stacks[match.groupValues[3].toInt()-1]
val at = from.size - n
repeat(n) {
to.push(from.removeAt(at))
}
}
return stacks.map { it.last() }.joinToString(separator = "")
}
// 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))
}
fun String.crates(numberOfStacks: Int): List<Char> {
val crates = mutableListOf<Char>()
var index = 1
while (index < length) {
crates.add(this[index])
index += 4
}
while (crates.size < numberOfStacks) {
crates.add(' ')
}
return crates
}
| 0 | Kotlin | 0 | 0 | e49d9247340037e4e70f55b0c201b3a39edd0a0f | 2,999 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day14/Day14.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day14
import readInput
import java.lang.Integer.max
import java.lang.Integer.min
enum class Point {
AIR,
ROCK,
SAND;
}
fun Array<Array<Point>>.get(pos: Pair<Int, Int>) = this[pos.first][pos.second]
fun Array<Array<Point>>.set(pos: Pair<Int, Int>, value: Point) {
this[pos.first][pos.second] = value
}
fun Pair<Int, Int>.down() = Pair(this.first, this.second + 1)
fun Pair<Int, Int>.diagLeft() = Pair(this.first - 1, this.second + 1)
fun Pair<Int, Int>.diagRight() = Pair(this.first + 1, this.second + 1)
fun Array<Array<Point>>.moveSandStep(pos: Pair<Int, Int>): Pair<Int, Int> {
val newPos = when (Point.AIR) {
this.get(pos.down()) -> pos.down()
this.get(pos.diagLeft()) -> pos.diagLeft()
this.get(pos.diagRight()) -> pos.diagRight()
else -> pos
}
this.set(pos, Point.AIR)
this.set(newPos, Point.SAND)
return newPos
}
fun Array<Array<Point>>.insertSand(insertPos: Pair<Int, Int> = Pair(500, 0)): Pair<Int, Int> {
this.set(insertPos, Point.SAND)
var lastPos: Pair<Int, Int>? = null
var pos = insertPos
while (pos != lastPos) {
lastPos = pos
pos = this.moveSandStep(pos)
}
return pos
}
fun main() {
fun part1(input: Array<Array<Point>>): Int {
var count = 0
var pos = Pair(0, 0)
while (pos.second < input[0].size - 2) {
pos = input.insertSand()
count++
}
return count - 1
}
fun part2(input: Array<Array<Point>>): Int {
var count = 0
while (input[500][0] == Point.AIR) {
input.insertSand()
count++
}
return count
}
fun preprocess(input: List<String>): Array<Array<Point>> {
val inputTransformed: List<List<Pair<Int, Int>>> = input.map {
it.split(" -> ").map {
val split = it.split(",")
Pair(split[0].toInt(), split[1].toInt())
}
}
val maxY = inputTransformed.flatten().maxOf { it.second } + 2
val maxX = inputTransformed.flatten().maxOf { it.first } + maxY + 2
val result = Array(maxX + 1) { Array(maxY + 1) { if (it == maxY) Point.ROCK else Point.AIR } }
for (path in inputTransformed) {
var lastPoint: Pair<Int, Int> = path[0]
for (point in path.subList(1, path.size)) {
for (x in min(lastPoint.first, point.first)..max(lastPoint.first, point.first)) {
for (y in min(lastPoint.second, point.second)..max(lastPoint.second, point.second)) {
result[x][y] = Point.ROCK
}
}
lastPoint = point
}
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(14, true)
check(part1(preprocess(testInput)) == 24)
val input = readInput(14)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) == 93)
println(part2(preprocess(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 3,071 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | dannyrm | 573,100,803 | false | null | typealias Forest = List<IntArray>
fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.toCharArray() }
.map { IntArray(it.size) { i -> it[i].digitToInt() } }
.numberOfVisibleTrees()
}
fun part2(input: List<String>): Int {
return input
.map { it.toCharArray() }
.map { IntArray(it.size) { i -> it[i].digitToInt() } }
.scenicScores().max()
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
fun Forest.scenicScores(): List<Int> {
val scenicScores = mutableListOf<Int>()
(this.indices).forEach { row ->
(0 until this[0].size).forEach { column ->
scenicScores.add(treeScenicScore(row, column))
}
}
return scenicScores
}
fun Forest.numberOfVisibleTrees(): Int {
var count = 0
(this.indices).forEach { row ->
(0 until this[0].size).forEach { column ->
if (isTreeVisible(row, column)) {
count++
}
}
}
return count
}
fun Forest.toStringRep(): String {
val stringBuilder = StringBuilder()
(this.indices).forEach { row ->
stringBuilder.appendLine()
(0 until this[0].size).forEach { column ->
stringBuilder.append(this[row][column])
if (isTreeVisible(row, column)) {
stringBuilder.append("(V) ")
} else {
stringBuilder.append("(I) ")
}
}
}
return stringBuilder.toString()
}
private fun Forest.surroundingRowAndColumn(x: Int, y: Int): Array<List<Int>> {
return arrayOf(this[y].copyOfRange(0, x).toList(), // West
this[y].copyOfRange(x+1, this[0].size).toList(), // East
this.map { it[x] }.subList(0, y), // North
this.map { it[x] }.subList(y+1, this.size)) // South
}
private fun Forest.isTreeVisible(x: Int, y: Int): Boolean {
if (x == 0 || x == this[0].size-1 || y == 0 || y == this.size-1) { // Tree is on the boundary of the forest
return true
}
val treeHeight = this[y][x]
val (treesWest, treesEast, treesNorth, treesSouth) = surroundingRowAndColumn(x, y)
return treeHeight > treesWest.max() ||
treeHeight > treesEast.max() ||
treeHeight > treesNorth.max() ||
treeHeight > treesSouth.max()
}
private fun Forest.treeScenicScore(x: Int, y: Int): Int {
val treeHeight = this[y][x]
fun calculateScoreForDirection(direction: List<Int>): Int {
var count = 0
for (i in direction.indices) {
count++
if (direction[i] >= treeHeight) {
break
}
}
return count
}
val (treesWest, treesEast, treesNorth, treesSouth) = surroundingRowAndColumn(x, y)
return calculateScoreForDirection(treesEast) *
calculateScoreForDirection(treesWest.reversed()) *
calculateScoreForDirection(treesNorth.reversed()) *
calculateScoreForDirection(treesSouth)
} | 0 | Kotlin | 0 | 0 | 9c89b27614acd268d0d620ac62245858b85ba92e | 3,070 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc2023/Day23.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2023
import PointL
import readInput
import to2dCharArray
import java.util.*
object Day23 {
private class HikingMap(input: List<String>) {
private val map = input.to2dCharArray()
private val start = PointL(
x = map.withIndex().find { (x, column) -> column.first() == '.' }?.index
?: throw IllegalArgumentException("No start point found"),
y = 0
)
private val end = PointL(
x = map.withIndex().find { (x, column) -> column.last() == '.' }?.index
?: throw IllegalArgumentException("No end point found"),
y = map.first().size - 1
)
private val grid = PointL(0, 0) to PointL(map.size - 1, map.first().size - 1)
companion object {
private val dRight = PointL(1, 0)
private val dLeft = PointL(-1, 0)
private val dTop = PointL(0, -1)
private val dBottom = PointL(0, 1)
}
private val longestDistances = mutableMapOf(start to 0)
private val longestDistancesWithComingFrom = mutableMapOf((start to start) to 0)
val longestDistance by lazy { getLongestDistance(end, start, 0, setOf(start)) }
private fun getLongestDistance(
target: PointL,
current: PointL,
stepCount: Int,
visited: Set<PointL>
): Int {
if (stepCount < (longestDistances[current] ?: 0)) {
return 0
} else {
longestDistances[current] = stepCount
}
val next = when (map[current.x.toInt()][current.y.toInt()]) {
'.' -> current.getNeighbours(validGrid = grid).filter { p -> map[p.x.toInt()][p.y.toInt()] != '#' }
'>' -> setOf(current + dRight)
'<' -> setOf(current + dLeft)
'^' -> setOf(current + dTop)
'v' -> setOf(current + dBottom)
else -> throw IllegalArgumentException("Invalid point on map $current")
}.filter { it !in visited }
return if (next.isEmpty()) {
return 0
} else if (target in next) {
stepCount + 1
} else {
next.maxOf {
getLongestDistance(target, it, stepCount + 1, visited + current)
}
}
}
val longestDistanceWithoutIce by lazy {
val start = Junction(start)
val allJunctions = mutableMapOf(this.start to start)
val toVisit: Queue<Junction> = LinkedList()
toVisit.add(start)
while (toVisit.isNotEmpty()) {
val current = toVisit.poll()
current.position.getNeighbours(validGrid = grid)
.filter { map[it.x.toInt()][it.y.toInt()] != '#' }
.map { next -> moveToNextJunction(next, current.position) }
.forEach { (point, distance) ->
val junction = allJunctions.getOrPut(point) { Junction(point) }
if (current.neighbours.put(junction, distance) == null) {
junction.neighbours[current] = distance
toVisit.add(junction)
}
}
}
getLongestDistance(end, start, 0, setOf(start))
}
private data class Junction(val position: PointL) {
val neighbours = mutableMapOf<Junction, Int>()
}
private fun getLongestDistance(
target: PointL,
current: Junction,
distanceSoFar: Int,
visited: Set<Junction>
): Int {
if (current.position == target) return distanceSoFar
val neighbours = current.neighbours.filter { it.key !in visited }
return if (neighbours.isEmpty()) 0 else neighbours.maxOf { (next, distance) ->
getLongestDistance(target, next, distance + distanceSoFar, visited + current)
}
}
private fun moveToNextJunction(currentPoint: PointL, previousPoint: PointL): Pair<PointL, Int> {
var steps = 1
var current = currentPoint
var previous = previousPoint
while (true) {
val neighbours = current.getNeighbours(validGrid = grid)
.filter { previous != it && map[it.x.toInt()][it.y.toInt()] != '#' }
if (neighbours.size == 1) {
previous = current
current = neighbours.first()
steps++
} else {
return current to steps
}
}
}
}
fun part1(input: List<String>) = HikingMap(input).longestDistance
fun part2(input: List<String>) = HikingMap(input).longestDistanceWithoutIce
}
fun main() {
val testInput = readInput("Day23_test", 2023)
check(Day23.part1(testInput) == 94)
check(Day23.part2(testInput) == 154)
val input = readInput("Day23", 2023)
println(Day23.part1(input))
println(Day23.part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 5,158 | adventOfCode | Apache License 2.0 |
src/day05/Day05.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day05
import component6
import readInput
fun main() {
fun readColumnCount(crateLines: List<String>) =
crateLines.last().split("\\s+".toRegex()).filter { it.isNotBlank() }.maxOf { it.toInt() }
fun createCrates(columnsCount: Int): List<MutableList<Char>> {
return (0 until columnsCount).map {
mutableListOf()
}
}
fun readCrates(crateLines: List<String>): List<ArrayDeque<Char>> {
val columnCount = readColumnCount(crateLines)
val crates = createCrates(columnCount)
crateLines.subList(0, crateLines.size - 1).forEach {
it.chunked(4).forEachIndexed { index, crateValue ->
if (crateValue.isNotBlank()) {
crates[index].add(crateValue[1])
}
}
}
return crates.map { ArrayDeque(it) }
}
fun splitByEmpty(input: List<String>): Int {
input.forEachIndexed { index, s ->
if (s.isBlank()) {
return index
}
}
return -1
}
fun readInstructions(instructions: List<String>): List<Instruction> = instructions
.map {
val (_, move, _, from, _, to) = it.split(" ")
Instruction(move.toInt(), from.toInt() - 1, to.toInt() - 1)
}
fun calculateMoves(crates: List<ArrayDeque<Char>>, instructions: List<Instruction>) {
instructions.forEach {inst ->
repeat(inst.move) {
val first = crates[inst.from].removeFirst()
crates[inst.to].addFirst(first)
}
}
}
fun calculateMoves2(crates: List<ArrayDeque<Char>>, instructions: List<Instruction>) {
instructions.forEach {inst ->
val tempStack = ArrayDeque<Char>()
repeat(inst.move) {
val first = crates[inst.from].removeFirst()
tempStack.addFirst(first)
}
repeat(inst.move){
val first = tempStack.removeFirst()
crates[inst.to].addFirst(first)
}
}
}
fun part1(input: List<String>): String {
val splitValue = splitByEmpty(input)
val crates = readCrates(input.subList(0, splitValue))
val instructions = readInstructions(input.subList(splitValue + 1, input.size))
calculateMoves(crates, instructions)
return crates.map { it.first() }.joinToString("")
}
fun part2(input: List<String>): String {
val splitValue = splitByEmpty(input)
val crates = readCrates(input.subList(0, splitValue))
val instructions = readInstructions(input.subList(splitValue + 1, input.size))
calculateMoves2(crates, instructions)
return crates.map { it.first() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day05/Day05_test")
println(part1(testInput))
check(part1(testInput) == "CMZ")
val input = readInput("day05/Day05")
println(part1(input))
println(part2(input))
}
data class Instruction(
val move: Int,
val from: Int,
val to: Int,
)
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 3,154 | advent-of-code-kotlin-2022 | Apache License 2.0 |
2015/Day16/src/main/kotlin/Main.kt | mcrispim | 658,165,735 | false | null | import java.io.File
typealias Auntie = Map<String, Int>
typealias SearchAuntie = Map<String, Pair<String, Int>>
val aunties = mutableListOf<Auntie>()
fun readAunties(input: List<String>): List<Auntie> {
input.forEach { line ->
val auntie = mutableMapOf<String, Int>()
val properties = line.substringAfter(":").split(",")
properties.forEach { property ->
val (key, value) = property.split(":").map { it.trim() }
auntie[key] = value.toInt()
}
aunties.add(auntie)
}
return aunties
}
fun main() {
fun compareAunties(
auntie: Auntie,
searchAuntie: Auntie,
greaterProperties: Set<String>,
lesserProperties: Set<String>
): Boolean {
for ((key, value) in auntie) {
if (!searchAuntie.containsKey(key)) return false
if (key in greaterProperties && value <= searchAuntie[key]!!) return false
if (key in lesserProperties && value >= searchAuntie[key]!!) return false
if (key !in greaterProperties && key !in lesserProperties && value != searchAuntie[key]!!) return false
}
return true
}
fun searchAuntie(
searchAuntie: Auntie,
greaterProperties: Set<String> = setOf(),
lesserProperties: Set<String> = setOf()
): Int {
aunties.forEachIndexed { index, auntie ->
val found = compareAunties(auntie, searchAuntie, greaterProperties, lesserProperties)
if (found) {
return index + 1
}
}
return 0
}
fun part1(input: List<String>): Int {
aunties.clear()
readAunties(input)
val mysteriousAuntie = mapOf(
"children" to 3,
"cats" to 7,
"samoyeds" to 2,
"pomeranians" to 3,
"akitas" to 0,
"vizslas" to 0,
"goldfish" to 5,
"trees" to 3,
"cars" to 2,
"perfumes" to 1
)
return searchAuntie(mysteriousAuntie)
}
fun part2(input: List<String>): Int {
aunties.clear()
readAunties(input)
val mysteriousAuntie = mapOf(
"children" to 3,
"cats" to 7,
"samoyeds" to 2,
"pomeranians" to 3,
"akitas" to 0,
"vizslas" to 0,
"goldfish" to 5,
"trees" to 3,
"cars" to 2,
"perfumes" to 1
)
val greaterProperties = setOf("cats", "trees")
val lesserProperties = setOf("pomeranians", "goldfish")
return searchAuntie(mysteriousAuntie, greaterProperties, lesserProperties)
}
val input = readInput("Day16_data")
println("Part 1 answer: ${part1(input)}")
println("Part 2 answer: ${part2(input)}")
}
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
| 0 | Kotlin | 0 | 0 | 2f4be35e78a8a56fd1e078858f4965886dfcd7fd | 2,952 | AdventOfCode | MIT License |
kotlin/src/main/kotlin/year2023/Day07.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
fun main() {
val input = readInput("Day07")
Day07.part1(input).println()
Day07.part2(input).println()
}
object Day07 {
fun part1(input: List<String>): Long {
val cardValues = { card: Char ->
when (card) {
'A' -> 14
'K' -> 13
'Q' -> 12
'J' -> 11
'T' -> 10
'9' -> 9
'8' -> 8
'7' -> 7
'6' -> 6
'5' -> 5
'4' -> 4
'3' -> 3
'2' -> 2
else -> 0
}
}
val typeGenerator = { cards: List<Char> ->
val cardCount = HashMap<Char, Int>()
cards.forEach {
cardCount[it] = (cardCount[it] ?: 0) + 1
}
val counts = cardCount.values
when {
counts.contains(5) -> Type.FIVE_OF_A_KIND
counts.contains(4) -> Type.FOUR_OF_A_KIND
counts.contains(3) && counts.contains(2) -> Type.FULL_HOUSE
counts.contains(3) -> Type.THREE_OF_A_KIND
counts.filter { it == 2 }.size == 2 -> Type.TWO_PAIR
counts.filter { it == 2 }.size == 1 -> Type.ONE_PAIR
else -> Type.HIGH_CARD
}
}
return input
.map {
val parts = it.split(" ")
val hand = Hand(parts[0].toCharArray().toList(), cardValues, typeGenerator)
val bid = parts[1].toLong()
Pair(hand, bid)
}
.sortedBy { it.first }
.mapIndexed { index, pair -> (index + 1) * pair.second }
.sum()
}
data class Hand(
val cards: List<Char>,
private val cardValues: (Char) -> Int,
private val typeGenerator: (List<Char>) -> Type
) : Comparable<Hand> {
val type: Type = typeGenerator(cards)
override fun compareTo(other: Hand): Int {
if (this.type != other.type) {
return this.type.value.compareTo(other.type.value)
}
for (i in cards.indices) {
val compareCards = this.getCardValue(i).compareTo(other.getCardValue(i))
if (compareCards != 0) {
return compareCards
}
}
return 0
}
private fun getCardValue(position: Int): Int {
val card = cards[position]
return cardValues(card)
}
}
enum class Type(val value: Int) {
FIVE_OF_A_KIND(7),
FOUR_OF_A_KIND(6),
FULL_HOUSE(5),
THREE_OF_A_KIND(4),
TWO_PAIR(3),
ONE_PAIR(2),
HIGH_CARD(1)
}
fun part2(input: List<String>): Long {
val cardValues = { card: Char ->
when (card) {
'A' -> 14
'K' -> 13
'Q' -> 12
'T' -> 10
'9' -> 9
'8' -> 8
'7' -> 7
'6' -> 6
'5' -> 5
'4' -> 4
'3' -> 3
'2' -> 2
'J' -> 1
else -> 0
}
}
val typeGenerator = { cards: List<Char> ->
val cardCount = HashMap<Char, Int>()
cards.forEach {
cardCount[it] = (cardCount[it] ?: 0) + 1
}
val cardWithHighestRepetition = cardCount.entries
.filter { it.key != 'J' }
.maxByOrNull { it.value }
?.key
?: 'J'
val howManyJs = cardCount['J'] ?: 0
cardCount['J'] = 0
cardCount[cardWithHighestRepetition] = (cardCount[cardWithHighestRepetition] ?: 0) + howManyJs
val counts = cardCount.values
when {
counts.contains(5) -> Type.FIVE_OF_A_KIND
counts.contains(4) -> Type.FOUR_OF_A_KIND
counts.contains(3) && counts.contains(2) -> Type.FULL_HOUSE
counts.contains(3) -> Type.THREE_OF_A_KIND
counts.filter { it == 2 }.size == 2 -> Type.TWO_PAIR
counts.filter { it == 2 }.size == 1 -> Type.ONE_PAIR
else -> Type.HIGH_CARD
}
}
return input
.map {
val parts = it.split(" ")
val hand = Hand(parts[0].toCharArray().toList(), cardValues, typeGenerator)
val bid = parts[1].toLong()
Pair(hand, bid)
}
.sortedBy { it.first }
.mapIndexed { index, pair -> (index + 1) * pair.second }
.sum()
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 4,764 | advent-of-code | MIT License |
src/Day15.kt | Fedannie | 572,872,414 | false | {"Kotlin": 64631} | import kotlin.concurrent.fixedRateTimer
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
fun parseInput(input: List<String>): List<List<Coordinate>> {
return input.map {
it
.replace("Sensor at x=", "")
.replace(" y=", "")
.replace(": closest beacon is at x=", ",")
.split(",")
.map { it.toInt() }
.chunked(2)
.map { Coordinate(it[0], it[1]) }
}
}
fun unify(segments: List<Pair<Int, Int>>): List<Pair<Int, Int>> {
val result = MutableList(0) { 0 to 0 }
var current = segments[0]
for (i in segments.indices) {
if (segments[i].first <= current.second) {
if (segments[i].second > current.second) {
current = current.first to segments[i].second
}
} else {
result.add(current)
current = segments[i]
}
}
result.add(current)
return result
}
fun getLine(pairs: List<List<Coordinate>>, y: Int, left: Int = -50000000, right: Int = 50000000): List<Pair<Int, Int>> {
val field = MutableList(0) { 0 to 0 }
pairs.forEach { (sensor, beacon) ->
val dx = sensor - beacon - abs(sensor.y - y)
if (dx >= 0 && sensor.x + dx >= left && sensor.x - dx <= right) {
field.add(max(left, sensor.x - dx) to min(sensor.x + dx, right))
}
}
return unify(field.sortedWith(compareBy<Pair<Int, Int>> { it.first }.thenBy { it.second }))
}
fun part1(input: List<String>, y: Int): Int {
val pairs = parseInput(input)
val coveredSegments = getLine(pairs, y)
val covered = coveredSegments.map { (it.first .. it.second).toSet() }.reduce { setA, setB -> setA.union(setB) }
return covered.subtract(pairs.filter { it[1].y == y }.map { it[1].x }.toSet()).size
}
fun part2(input: List<String>, border: Int): Long {
val pairs = parseInput(input)
for (y in 0 .. border) {
val covered = getLine(pairs, y, 0, border)
if (covered.size == 2) {
return y.toLong() + (covered[0].second + 1).toLong() * 4000000L
}
}
return 0
}
val testInput = readInputLines("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
val input = readInputLines(15)
println(part1(input, 2000000))
println(part2(input, 4000000))
} | 0 | Kotlin | 0 | 0 | 1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f | 2,311 | Advent-of-Code-2022-in-Kotlin | Apache License 2.0 |
src/Day07.kt | KliminV | 573,758,839 | false | {"Kotlin": 19586} | fun main() {
fun part1(input:Map<String, Int>): Int {
return input.values
.filter { it < 100_000 }
.sum()
}
fun part2(input: Map<String, Int>): Int {
val occupied = input[""]
val toFree = occupied!! - 40_000_000
val result = input.values
.filter {
it > toFree
}.min()
return result
}
fun buildFoldersMap(input : List<String>): Map<String, Int> {
val folders = HashMap<String, Int>()
var cwd = ""
for (line in input) {
val matchResult = PATTERN.matchEntire(line) ?: continue
matchResult.groups[1]?.value?.let { dir ->
cwd = when (dir) {
"/" -> ""
".." -> cwd.substringBeforeLast('/', "")
else -> if (cwd.isEmpty()) dir else "$cwd/$dir"
}
} ?: matchResult.groups[2]?.value?.toIntOrNull()?.let {
var dir = cwd
while (true) {
folders[dir] = folders.getOrElse(dir) { 0 } + it
if (dir.isEmpty()) break
dir = dir.substringBeforeLast('/', "")
}
}
}
return folders
}
// test if implementation meets criteria from the description, like:
val testInput = buildFoldersMap(readInput("Day07_test"))
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = buildFoldersMap(readInput("Day07"))
println(part1(input))
println(part2(input))
}
val PATTERN = """[$] cd (.*)|(\d+).*""".toRegex()
| 0 | Kotlin | 0 | 0 | 542991741cf37481515900894480304d52a989ae | 1,639 | AOC-2022-in-kotlin | Apache License 2.0 |
src/Day08.kt | Jaavv | 571,865,629 | false | {"Kotlin": 14896} | // https://adventofcode.com/2022/day/6
fun main() {
val testInput = readInput("Day08_test")
val input = readInput("Day08")
val grid = input.toString()
.removeSurrounding("[", "]")
.split(",")
.map { it.trim() }
.map { it.chunked(1) }
.map { it -> it.map { it.toInt() } }
println(day08Part1(grid)) // 1560
val part2 = day08Part2(grid)
println(part2.maxOfOrNull { it.max() }) // 25200
}
fun heightCheck(index: Int, trees: List<Int>): Boolean {
var left = true
var right = true
if (index == 0 || index == trees.size - 1) {
return true
} else {
for ( i in index-1 downTo 0) {
if (trees[index] > trees[i]) {
continue
} else {
left = false
break
}
}
for ( i in index+1 until trees.size) {
if (trees[index] > trees[i]) {
continue
} else {
right = false
break
}
}
return left || right
}
}
fun scenicScore(index: Int, trees: List<Int>): Pair<Int, Int> {
var left = 0
var right = 0
if (index == 0) left++
if (index == trees.size - 1) right++
for (i in index-1 downTo 0) {
if (trees[index] > trees[i]) {
left++
} else if (trees[index] == trees[i]) {
left++
break
}
}
for (i in index+1 until trees.size) {
if (trees[index] > trees[i]) {
right++
} else if (trees[index] <= trees[i]) {
right++
break
}
}
return Pair(left, right)
}
fun getVertical(index: Int, grid: List<List<Int>>): List<Int> {
val list = mutableListOf<Int>()
for (i in grid.indices) {
list.add(grid[i][index])
}
return list
}
fun day08Part1(input: List<List<Int>>): Int {
var count = 0
input.forEachIndexed { rowIndex, row ->
row.forEachIndexed { treeIndex, tree ->
if (rowIndex == 0 ||
rowIndex == (input.size - 1) ||
treeIndex == 0 ||
treeIndex == (row.size - 1)) {
count ++
}
else {
val col = getVertical(treeIndex, input)
if (heightCheck(treeIndex, row) || heightCheck(rowIndex, col)) {
count++
}
}
}
}
return count
}
fun day08Part2(input: List<List<Int>>): List<List<Int>> {
return input.mapIndexed { rowIndex, row ->
List(row.size) { treeIndex ->
val col = getVertical(treeIndex, input)
val rowScore = scenicScore(treeIndex, row).toList()
val colScore = scenicScore(rowIndex, col).toList()
val score = rowScore + colScore
val newScore = score.filter { it > 0 }
newScore.fold(1) { acc, i -> acc * i }
}
}
}
| 0 | Kotlin | 0 | 0 | 5ef23a16d13218cb1169e969f1633f548fdf5b3b | 2,968 | advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | jorgecastrejon | 573,097,701 | false | {"Kotlin": 33669} | fun main() {
fun part1(input: List<String>): Int =
input.windowed(2, 3).mapNotNull {
(createPacket(it.first()) as Packet.Composed compare createPacket(it.last()) as Packet.Composed)
}.foldRightIndexed(0) { index, isRight, acc -> if (isRight) acc + (index + 1) else acc }
fun part2(input: List<String>): Int {
val d1 = createPacket("[[2]]") as Packet.Composed
val d2 = createPacket("[[6]]") as Packet.Composed
val list = input.windowed(2, 3)
.map { listOf(createPacket(it.first()) as Packet.Composed, createPacket(it.last()) as Packet.Composed) }
.flatten()
.let { it + listOf(d1, d2) }
.sortedWith(comparator)
return (list.indexOf(d1) + 1) * (list.indexOf(d2) + 1)
}
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private val comparator = Comparator<Packet.Composed> { p1, p2 ->
when (p1 compare p2) {
null -> 0
true -> -1
false -> 1
}
}
private infix fun Packet.Composed.compare(another: Packet.Composed): Boolean? {
var solution: Boolean? = null
var index = 0
while (solution == null) {
val x = value.getOrNull(index)
val y = another.value.getOrNull(index)
if (x == null) return true
if (y == null) return false
if (x is Packet.Composed && y is Packet.Composed) {
if (x != y) {
solution = x compare y
}
} else if (x is Packet.Simple && y is Packet.Composed) {
solution = Packet.Composed(listOf(x)) compare y
} else if (x is Packet.Composed && y is Packet.Simple) {
solution = x compare Packet.Composed(listOf(y))
} else if (x is Packet.Simple && y is Packet.Simple) {
if (x.value != y.value) {
solution = x.value < y.value
}
} else {
throw IllegalArgumentException("no other option")
}
index++
}
return solution
}
fun createPacket(string: String): Packet {
if (string == "[]") return Packet.Composed(emptyList())
if (string.toIntOrNull() != null) return Packet.Simple(string.toInt())
val content = string.substring(1, string.length - 1)
var deep = 0
val elements = mutableListOf<String>()
var item = ""
for (char in content) {
when {
char == '[' -> {
deep++
item += char
}
char == ']' -> {
deep--
item += char
}
char == ',' && deep == 0 -> {
elements.add(item)
item = ""
}
else -> item += char
}
}
elements.add(item)
return Packet.Composed(elements.map(::createPacket))
}
sealed class Packet {
data class Simple(val value: Int) : Packet()
data class Composed(val value: List<Packet>) : Packet()
}
| 0 | Kotlin | 0 | 0 | d83b6cea997bd18956141fa10e9188a82c138035 | 2,976 | aoc-2022 | Apache License 2.0 |
src/Day12.kt | pimtegelaar | 572,939,409 | false | {"Kotlin": 24985} | import java.util.*
fun main() {
data class Node(
val x: Int,
val y: Int,
val value: String
) {
var top: Node? = null
var bottom: Node? = null
var left: Node? = null
var right: Node? = null
val neighbors get() = mutableListOf(bottom, right, top, left).filterNotNull()
var gScore: Int = 0
var parent: Node? = null
var visited = false
}
fun List<String>.parseNodes() = mapIndexed { y, line ->
line.mapIndexed { x, c ->
Node(x, y, c.toString())
}.toTypedArray()
}.toTypedArray()
fun Array<Node>.safeGet(x: Int): Node? =
if (x < 0 || x >= size) null else this[x]
fun Array<Array<Node>>.safeGet(x: Int, y: Int): Node? =
if (y < 0 || y >= size) null else this[y].safeGet(x)
fun Array<Array<Node>>.assignNeighbors() =
flatMap { row ->
row.map { node ->
node.apply {
left = row.safeGet(x - 1)
right = row.safeGet(x + 1)
top = safeGet(x, y - 1)
bottom = safeGet(x, y + 1)
}
}
}
fun bestScore(start: Node, nodes: List<Node>): Int {
val openSet = PriorityQueue<Node>(Comparator.comparing { it.gScore })
openSet.add(start)
start.visited = true
while (openSet.isNotEmpty()) {
val node = openSet.poll()
if (node.value == "E") {
break
}
node.neighbors.forEach { neighbor ->
val neighborCode = if (neighbor.value == "E") 'z'.code else neighbor.value.first().code
val nodeCode = if (node.value == "S") 'a'.code else node.value.first().code
if (!neighbor.visited && (neighborCode - nodeCode < 2)) {
neighbor.gScore = node.gScore + 1
neighbor.parent = node
neighbor.visited = true
openSet.add(neighbor)
}
}
}
return nodes.first { node -> node.value == "E" }.gScore
}
fun part1(input: List<String>): Int {
val nodes = input.parseNodes().assignNeighbors()
val startNode = nodes.first { node -> node.value == "S" }
return bestScore(startNode, nodes)
}
fun part2(input: List<String>): Int {
val nodes = input.parseNodes().assignNeighbors()
return nodes.filter { node -> node.value == "a" }
.map { start ->
bestScore(start, nodes.map { node ->
node.gScore = 0
node.visited = false
node.parent = null
node
})
}
.filter { it > 0 }
.min()
}
val testInput = readInput("Day12_test")
val input = readInput("Day12")
val part1 = part1(testInput)
check(part1 == 31) { part1 }
println(part1(input))
val part2 = part2(testInput)
check(part2 == 29) { part2 }
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 16ac3580cafa74140530667413900640b80dcf35 | 3,098 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | bjornchaudron | 574,072,387 | false | {"Kotlin": 18699} | val priorities = ('a'..'z').mapPriorities(1) + ('A'..'Z').mapPriorities(27)
fun CharRange.mapPriorities(target: Int): Map<Char, Int> {
val delta = target - first.code
return associateWith { it.code + delta }
}
fun groupSacks(sacks: List<String>): List<Triple<Set<Char>, Set<Char>, Set<Char>>> {
val groupsSize = 3
val groups = mutableListOf<Triple<Set<Char>, Set<Char>, Set<Char>>>()
for (i in sacks.indices step groupsSize) {
val triple = Triple(sacks[i].toSet(), sacks[i + 1].toSet(), sacks[i + 2].toSet())
groups.add(triple)
}
return groups
}
fun main() {
fun part1(sacks: List<String>) = sacks.asSequence()
.map { sack ->
val nrHalfContents = sack.length / 2
sack.take(nrHalfContents).toSet() to sack.takeLast(nrHalfContents).toSet()
}
.map { sack -> sack.first.intersect(sack.second) }
.flatMap { it.toList() }
.sumOf { priorities[it]!! }
fun part2(sacks: List<String>) =
groupSacks(sacks)
.map { it.first.intersect(it.second).intersect(it.third) }
.flatMap { it.toList() }
.sumOf { priorities[it]!! }
// test if implementation meets criteria from the description, like:
val day = "03"
val testInput = readLines("Day${day}_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readLines("Day$day")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | f714364698966450eff7983fb3fda3a300cfdef8 | 1,500 | advent-of-code-2022 | Apache License 2.0 |
src/day11/Day11.kt | maxmil | 578,287,889 | false | {"Kotlin": 32792} | package day11
import println
import readInput
data class Point(val x: Int, val y: Int)
typealias Grid = List<MutableList<Int>>
fun Grid.step(): Int {
this.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, _ -> this[rowIndex][colIndex]++ } }
val flashed = this.flatMapIndexed { rowIndex, row ->
row.mapIndexed { colIndex, col -> if (col > 9) Point(colIndex, rowIndex) else null }
}.filterNotNull().toMutableSet()
val queue = ArrayDeque(flashed)
while (queue.isNotEmpty()) {
val octopus = queue.removeFirst()
for (row in octopus.y - 1..octopus.y + 1) {
if (row >= 0 && row < this.size) {
for (col in octopus.x - 1..octopus.x + 1) {
if (col >= 0 && col < this[row].size && !(row == octopus.y && col == octopus.x)) {
this[row][col]++
val point = Point(col, row)
if (this[row][col] > 9 && !flashed.contains(point)) {
flashed.add(point)
queue.add(point)
}
}
}
}
}
}
flashed.forEach { this[it.y][it.x] = 0 }
return flashed.size
}
fun part1(input: List<String>): Int {
val grid = input.map { line -> line.toCharArray().map { char -> char.digitToInt() }.toMutableList() }
return (1..100).sumOf { grid.step() }
}
fun part2(input: List<String>): Int {
val grid = input.map { line -> line.toCharArray().map { char -> char.digitToInt() }.toMutableList() }
var cnt = 0
while (grid.step() < grid.size * grid[0].size) cnt++
return cnt + 1
}
fun main() {
val testInput = readInput("day11/input_test")
check(part1(testInput.toMutableList()) == 1656)
check(part2(testInput.toMutableList()) == 195)
val input = readInput("day11/input")
part1(input.toMutableList()).println()
part2(input.toMutableList()).println()
}
| 0 | Kotlin | 0 | 0 | 246353788b1259ba11321d2b8079c044af2e211a | 1,987 | advent-of-code-2021 | Apache License 2.0 |
src/Day07.kt | trosendo | 572,903,458 | false | {"Kotlin": 26100} | import utils.TreeNode
private data class Folder(
val path: String,
val name: String,
val files: MutableSet<File> = mutableSetOf()
) {
fun getFilesSize() = files.sumOf { it.size }
}
data class File(
val name: String,
val size: Int
)
fun main() {
fun TreeNode<Folder>.getTotalSizeOfFolder(): Int {
var totalSize = 0
this.forEachLevelOrder {
totalSize += it.value.getFilesSize()
}
return totalSize
}
fun TreeNode<Folder>.getPath(folderName: String): String {
return this.value.path + "/" + folderName
}
fun parseInput(inputAsList: List<String>, currentFolder: TreeNode<Folder>): TreeNode<Folder> {
inputAsList.forEachIndexed { index, commandLine ->
val command = commandLine.split(" ")
when (command[0]) {
"$" -> when (command[1]) {
"cd" -> {
return when (val cdTarget = command[2]) {
".." -> {
parseInput(
inputAsList.subList(index + 1, inputAsList.size),
currentFolder.getParent()!!
)
}
else -> {
val child =
if (currentFolder.isRoot() && cdTarget == currentFolder.value.name)
currentFolder
else {
currentFolder.search { it.path == currentFolder.getPath(cdTarget) }
?: throw Exception(
"Trying to change to an unknown folder... Current state: $currentFolder"
)
}
parseInput(inputAsList.subList(index + 1, inputAsList.size), child)
}
}
}
"ls" -> return parseInput(inputAsList.subList(index + 1, inputAsList.size), currentFolder)
}
"dir" -> {
val folderName = command[1]
val path = currentFolder.getPath(folderName)
currentFolder.search { it.path == path }
?: currentFolder.add(TreeNode(value = Folder(name = folderName, path = path)))
}
else -> {
val size = command[0].toInt()
val fileName = command[1]
currentFolder.value.files.find { it.name == fileName && it.size == size }
?: currentFolder.value.files.add(File(name = fileName, size = size))
}
}
}
return currentFolder
}
fun findSmallestFolderWithAtLeastSize(size: Int, folder: TreeNode<Folder>): Int? {
return folder.getNodes().map { it.getTotalSizeOfFolder() }.sorted().find { it >= size }
}
fun part1() {
val root = TreeNode(value = Folder(name = "/", path = ""))
val parsed = parseInput(readInputAsList("Day07"), root)
println(parsed.getRoot().getNodes().map { it.getTotalSizeOfFolder() }.filter { it <= 100_000 }.sum())
}
fun part2() {
val totalDiskSpace = 70_000_000
val spaceNeeded = 30_000_000
val root = TreeNode(value = Folder(name = "/", path = ""))
val parsed = parseInput(readInputAsList("Day07"), root)
val spaceUsed = parsed.getRoot().getTotalSizeOfFolder()
val freeSpace = totalDiskSpace - spaceUsed
val minimumSpaceToFree = spaceNeeded - freeSpace
val result = findSmallestFolderWithAtLeastSize(minimumSpaceToFree, parsed.getRoot())
println(result)
}
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | ea66a6f6179dc131a73f884c10acf3eef8e66a43 | 3,963 | AoC-2022 | Apache License 2.0 |
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day16/Day16.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2022.day16
import eu.janvdb.aocutil.kotlin.readLines
//const val FILENAME = "input16-test.txt"
const val FILENAME = "input16.txt"
/*
* Part 2 gives the correct result for the full input, but not for the test input.
* Probably the elephant needs enough empty nodes to operate independently.
*/
fun main() {
val valvesList = readLines(2022, FILENAME).map(String::toValve)
val valves = Valves.create(valvesList)
part1(valves)
part2(valves)
}
fun part1(valves: Valves) {
val best = findBestPath(valves, 30, valves.names, 1)
println("$best ${best?.totalFlow}")
}
fun part2(valves: Valves) {
val best = findBestPath(valves, 26, valves.names, 2)
println("$best ${best?.totalFlow}")
}
fun findBestPath(valves: Valves, minutes: Int, valvesToUse: Set<String>, actorsLeft: Int): Solution? {
if (actorsLeft == 0) return null
val queue = mutableListOf(Path(listOf(START_VALVE), 0, 0))
var best: Solution? = null
while (!queue.isEmpty()) {
val currentPath = queue.removeLast()
val lastStep = currentPath.steps.last()
val nextSteps = valvesToUse.asSequence()
.filter { !currentPath.steps.contains(it) }
.map { next ->
val stepLength = valves.stepLength(lastStep, next) + 1
val flow = valves.flowRate(next) * (minutes - currentPath.length - stepLength)
currentPath.addStep(next, stepLength, flow)
}
.filter { it.length <= minutes }
.toList()
queue.addAll(nextSteps)
if (nextSteps.isEmpty()) {
val solutionWithOtherActors = findBestPath(valves, minutes, valvesToUse - currentPath.steps, actorsLeft - 1)
val currentSolution = solutionWithOtherActors?.with(currentPath) ?: Solution(listOf(currentPath))
if (best == null || best.totalFlow < currentSolution.totalFlow) best = currentSolution
}
}
return best
}
data class Path(val steps: List<String>, val length: Int, val totalFlow: Int) {
fun addStep(step: String, stepLength: Int, flow: Int) =
Path(steps + step, length + stepLength, totalFlow + flow)
}
data class Solution(val paths: List<Path>) {
val totalFlow = paths.sumOf { it.totalFlow }
fun with(path: Path): Solution {
val newPaths = paths.toMutableList()
newPaths.add(0, path)
return Solution(newPaths)
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,213 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/aoc2022/Day12.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2022
import days.Day
import java.util.*
class Day12 : Day(2022, 12) {
override fun partOne(): Any {
return calculateShortestRoute(inputList)
}
override fun partTwo(): Any {
return calculateShortestRouteFromAnyAToEnd(inputList)
}
fun calculateShortestRouteFromAnyAToEnd(input: List<String>): Int {
val forest = parseForest(input)
var end: Point? = null
for (y in forest.indices) {
for (x in forest[y].indices) {
if (forest[y][x] == 'E') {
end = Point(x, y)
}
}
}
val distances = mutableListOf<Int>()
for (y in forest.indices) {
for (x in forest[y].indices) {
if (forest[y][x] == 'a') {
distances.add(findShortestPath(forest, Point(x, y), end!!))
}
}
}
return distances.minOf { it }
}
fun calculateShortestRoute(input: List<String>): Int {
val forest = parseForest(input)
var start: Point? = null
var end: Point? = null
for (y in forest.indices) {
for (x in forest[y].indices) {
if (forest[y][x] == 'S') {
start = Point(x, y)
}
if (forest[y][x] == 'E') {
end = Point(x, y)
}
}
}
return findShortestPath(forest, start!!, end!!)
}
private fun findShortestPath(forest: Array<Array<Char>>, start: Point, end: Point): Int {
val visited = mutableSetOf<Point>()
val queue = PriorityQueue<PathElement>()
queue.add(PathElement(start, 0))
while (queue.isNotEmpty()) {
val current = queue.poll()
if (current.point in visited) {
continue
}
visited.add(current.point)
if (current.point == end) {
// we did it
return current.cost
}
val currentTree = forest[current.point.y][current.point.x]
val currentHeight = if (currentTree == 'S') 'a' else currentTree
current.point.neighbors()
.filter { it.pointIsValid(forest) && !visited.contains(it) }
.forEach { neighbor ->
val neighboringTree = forest[neighbor.y][neighbor.x]
val height = if (neighboringTree == 'E') 'z' else neighboringTree
if (height - currentHeight <= 1) {
queue.offer(PathElement(neighbor, current.cost + 1))
}
}
}
return Int.MAX_VALUE
}
private fun parseForest(input: List<String>): Array<Array<Char>> {
val forest = Array(input.size) {
Array(input.first().length) { ' ' }
}
input.forEachIndexed { y, line ->
line.forEachIndexed { x, c -> forest[y][x] = c }
}
return forest
}
data class PathElement(val point: Point, val cost: Int) : Comparable<PathElement> {
override fun compareTo(other: PathElement): Int {
return cost.compareTo(other.cost)
}
}
data class Point(val x:Int, val y:Int) {
fun neighbors(): List<Point> = listOf(copy(x = x + 1), copy(x = x - 1), copy(y = y + 1), copy(y = y - 1))
fun pointIsValid(forest: Array<Array<Char>>): Boolean =
forest.indices.contains(y) && forest[y].indices.contains(x)
}
}
| 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,548 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/Day07.kt | carloxavier | 574,841,315 | false | {"Kotlin": 14082} | // https://adventofcode.com/2022/day/7
fun main() {
fun firstPart(inputFilePath: String): Long {
val rootDir = FileTreeParser(readInput(inputFilePath)).parse()
val dirSizes = TreeClimber(rootDir).climb().values
return dirSizes.filter { it <= 100000 }.sum()
}
check(firstPart("Day07_test") == 95437L)
println(firstPart("Day07"))
fun secondPart(inputFilePath: String): Long {
val rootDir = FileTreeParser(readInput(inputFilePath)).parse()
val dirSizes = TreeClimber(rootDir).climb().values.sorted()
return dirSizes.first { it >= 30000000 - (70000000 - dirSizes.last()) }
}
check(secondPart("Day07_test") == 24933642L)
println(secondPart("Day07"))
}
private class TreeClimber(private val rootDir: DataDir) {
private val dirSizesFound = hashMapOf<String, Long>()
fun climb(): Map<String, Long> {
climb(rootDir)
return dirSizesFound
}
private fun climb(dir: DataDir): Long {
val dirSize = dir.content.values.sumOf {
when (it) {
is DataFile -> it.fileSize
is DataDir -> climb(it)
}
}
dirSizesFound[dir.path] = dirSize
return dirSize
}
}
private class FileTreeParser(private val fileLines: List<String>) {
private val rootDir = DataDir("/", parentDir = null)
private var currentDir: DataDir = rootDir
fun parse(): DataDir {
val lineIterator = fileLines.iterator()
while (lineIterator.hasNext()) {
val textLine = lineIterator.next()
when (val firstToken = textLine.split(" ").first()) {
"$" -> parseCommandLine(textLine).executeChangeDirCommand()
else -> {
val (fileSize, fileName) = textLine.split(" ")
currentDir.content[fileName] = if (firstToken == "dir") {
DataDir("${currentDir.path}/$fileName", parentDir = currentDir)
} else {
DataFile("${currentDir.path}/$fileName", fileSize.toLong())
}
}
}
}
return rootDir
}
private fun parseCommandLine(commandLine: String) = when {
commandLine.startsWith("$ cd") -> when (val dirName = commandLine.split(" ").last()) {
"/" -> Command.GoToRootDir
".." -> Command.GoToParentDir(currentDir.parentDir!!)
else -> Command.ChangeDir(dirName, parentDir = currentDir)
}
commandLine.startsWith("$ ls") -> Command.ListFilesCurrentDir
else -> throw java.io.IOException("Unknown Command")
}
private fun Command.executeChangeDirCommand() {
when (this) {
is Command.ChangeDir -> currentDir = currentDir.content[this.dirName] as DataDir
is Command.GoToParentDir -> currentDir = currentDir.parentDir ?: currentDir
Command.GoToRootDir -> currentDir = rootDir
Command.ListFilesCurrentDir -> { /* ignore listing files, we only want to change dir */
}
}
}
}
private sealed class Command {
data class ChangeDir(val dirName: String, val parentDir: DataDir) : Command()
data class GoToParentDir(val dir: DataDir) : Command()
object GoToRootDir : Command()
object ListFilesCurrentDir : Command()
}
private sealed interface File {
val path: String
val fileSize: Long
}
private data class DataDir(
override val path: String, val parentDir: DataDir?, val content: HashMap<String, File> = hashMapOf(),
) : File {
override val fileSize = 0L
}
private data class DataFile(
override val path: String, override val fileSize: Long
) : File
| 0 | Kotlin | 0 | 0 | 4e84433fe866ce1a8c073a7a1e352595f3ea8372 | 3,720 | adventOfCode2022 | Apache License 2.0 |
src/main/kotlin/adventofcode2023/day7/day7.kt | dzkoirn | 725,682,258 | false | {"Kotlin": 133478} | package adventofcode2023.day7
import adventofcode2023.readInput
import kotlin.time.measureTime
fun main() {
val input = readInput("day7")
println("Day 7")
val puzzle1Time = measureTime {
println("Puzzle 1: ${puzzle1(input)}")
}
println("Puzzle 1 took $puzzle1Time")
val puzzle2Time = measureTime {
println("Puzzle 2: ${puzzle2(input)}")
}
println("Puzzle 2 took $puzzle2Time")
}
data class Hand(
val cards: String,
val bid: Int
)
fun prepareInput(input: List<String>): List<Hand> =
input.map { it.split(' ').filter { it.isNotEmpty() }.let { (f, s) -> Hand(cards = f, bid = s.toInt()) } }
fun sortHands(
input: List<Hand>,
toHandType: (String) -> HandType = ::toHandTypeV1,
sortedCards: CharArray = sortedCardsv1
): List<Hand> =
input.sortedWith { first, second -> compareHands(first.cards, second.cards, toHandType, sortedCards) }
val sortedCardsv1 = charArrayOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J')
enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_KIND,
FULL_HOUSE,
FOUR_OF_KIND,
FIVE_OF_KIND;
}
fun compareHands(
first: String,
second: String,
toHandType: (String) -> HandType,
sortedCards: CharArray
): Int {
val firstHand = toHandType(first)
val secondHand = toHandType(second)
var comparison = firstHand.compareTo(secondHand)
if (comparison == 0) {
var index = 0
do {
comparison = compareCards(first[index], second[index], sortedCards)
index++
} while (comparison == 0 && index < 5)
}
return comparison
}
fun compareCards(first: Char, second: Char, sortedCards: CharArray): Int =
with(sortedCards) {
indexOf(second) - indexOf(first)
}
fun toHandTypeV1(hand: String): HandType {
val mapped = hand.groupBy { it }
return when (mapped.keys.size) {
5 -> HandType.HIGH_CARD
4 -> HandType.ONE_PAIR
3 -> {
if (mapped.values.any { it.size == 3 }) {
HandType.THREE_OF_KIND
} else {
HandType.TWO_PAIR
}
}
2 -> {
if (mapped.values.any { it.size == 4 }) {
HandType.FOUR_OF_KIND
} else {
HandType.FULL_HOUSE
}
}
1 -> HandType.FIVE_OF_KIND
else -> {
throw IllegalStateException()
}
}
}
fun puzzle1(input: List<String>): Long =
sortHands(prepareInput(input)).foldIndexed(0L) { index: Int, acc: Long, hand: Hand -> acc + hand.bid * (index + 1) }
val sortedCardsv2 = charArrayOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J')
fun toHandTypeV2(hand: String): HandType {
val mapped = hand.groupBy { it }
if (mapped.keys.size == 1) {
return HandType.FIVE_OF_KIND
}
val tempHand = if (mapped.keys.contains('J')) {
val char = mapped.entries.filter { it.key != 'J' }.sortedWith { f, s ->
val comparison = f.value.size - s.value.size
if (comparison == 0) {
compareCards(f.key, s.key, sortedCardsv2)
} else {
comparison
}
}.last.key
hand.replace('J', char)
} else {
hand
}
return toHandTypeV1(tempHand)
}
fun puzzle2(input: List<String>): Long =
sortHands(prepareInput(input), ::toHandTypeV2, sortedCardsv2).foldIndexed(0L) { index: Int, acc: Long, hand: Hand -> acc + hand.bid * (index + 1) } | 0 | Kotlin | 0 | 0 | 8f248fcdcd84176ab0875969822b3f2b02d8dea6 | 3,549 | adventofcode2023 | MIT License |
src/2023/2023Day02.kt | bartee | 575,357,037 | false | {"Kotlin": 26727} |
data class GameResult (val ID: Int, val resultset: Map<String, Int>)
private fun calculateGameResult(it: String): GameResult{
val (gamestr, setsstr) = it.split(":")
var maxes = mutableMapOf<String, Int>()
// Create the set and the
val ID = gamestr.split(" ")[1].toInt()
val sets = setsstr.split(';')
for (set in sets) {
val colorsets = set.split(",")
for (colorset in colorsets) {
var (count, color) = colorset.trim().split(" ")
val cur_max = maxes.getOrDefault(color, 0)
if (count.toInt() > cur_max) {
maxes.put(color, count.toInt())
}
}
}
val result = GameResult(ID, maxes)
return result
}
fun validateGameResult(input: String, requiredOutcome: Map<String, Int>): Int {
val gameResult = calculateGameResult(input)
// check if the game matches the desired outcome
var valid = true
requiredOutcome.forEach{ entry ->
val maxed_val = gameResult.resultset.getOrDefault(entry.key, 1000)
if (maxed_val > entry.value)
valid = false
}
if (valid) return gameResult.ID
return 0
}
fun calculateGamePower(input: String): Int {
val gameResult = calculateGameResult(input)
val power = gameResult.resultset.getOrDefault("red",0) * gameResult.resultset.getOrDefault("green", 0)*gameResult.resultset.getOrDefault("blue", 0)
return power
}
fun partOne(input: List<String>): Int {
val requiredOutcome = mapOf<String, Int>("red" to 12, "green" to 13, "blue" to 14)
var sum = 0
input.map {
val res = validateGameResult(it, requiredOutcome)
sum = sum + res
}
return sum
}
fun partTwo(input: List<String>): Int {
val requiredOutcome = mapOf<String, Int>("red" to 12, "green" to 13, "blue" to 14)
var sum = 0
input.map {
val res = calculateGamePower(it)
sum = sum + res
}
return sum
}
fun main(){
val test_input = readInput("2023/resources/input/day02_test")
val game_input = readInput("2023/resources/input/day02_gameresults")
// Test the input
val testOne = partOne(test_input)
val testTwo = partTwo(test_input)
println("Testing ... ")
assert(testOne == 8)
assert(testTwo == 2286)
println("Tested! ")
var res = partOne(game_input)
println("Part one result: $res")
var power = partTwo(game_input)
println("Total game power: $power")
} | 0 | Kotlin | 0 | 0 | c7141d10deffe35675a8ca43297460a4cc16abba | 2,288 | adventofcode2022 | Apache License 2.0 |
day10/src/main/kotlin/Main.kt | rstockbridge | 225,212,001 | false | null | import kotlin.math.atan2
fun main() {
val input = resourceFile("input.txt")
.readLines()
println("Part I: the solution is ${solvePartI(input)}.")
println("Part II: the solution is ${solvePartII(input)}.")
}
fun solvePartI(input: List<String>): Int {
return calculateBestLocationAndNumberDetected(input).second
}
fun solvePartII(input: List<String>): Int {
return calculateResultGivenLocation(input, 200)
}
fun calculateBestLocationAndNumberDetected(asteroidMap: List<String>): Pair<GridPoint2d, Int> {
val height = asteroidMap.size
val width = asteroidMap[0].length
val asteroidLocationAndNumberItCanDetect = mutableMapOf<GridPoint2d, Int>()
for (y in 0 until height) {
for (x in 0 until width) {
if (asteroidMap[y][x] == '#') {
val asteroidLocation = GridPoint2d(x, y)
asteroidLocationAndNumberItCanDetect[asteroidLocation] =
calculateNumberOfAsteroidsDetected(asteroidLocation, asteroidMap)
}
}
}
return asteroidLocationAndNumberItCanDetect.maxBy { it.value }!!.toPair()
}
fun calculateNumberOfAsteroidsDetected(location: GridPoint2d, asteroidMap: List<String>): Int {
val closestDistanceByAngle = mutableMapOf<Double, Double>()
val height = asteroidMap.size
val width = asteroidMap[0].length
for (y in 0 until height) {
for (x in 0 until width) {
val otherLocation = GridPoint2d(x, y)
if (asteroidMap[y][x] != '#' || location == otherLocation) {
continue
}
val angle = calculateAngle(location, otherLocation)
val distance = location.l2DistanceTo(otherLocation)
if (!closestDistanceByAngle.containsKey(angle)) {
closestDistanceByAngle[angle] = distance
} else {
if (closestDistanceByAngle[angle]!! > distance) {
closestDistanceByAngle[angle] = distance
}
}
}
}
return closestDistanceByAngle.size
}
private fun calculateAngle(location: GridPoint2d, other: GridPoint2d): Double {
val untransformedAngle = atan2((location.x - other.x).toDouble(), (location.y - other.y).toDouble())
return if (untransformedAngle < 0) {
-untransformedAngle
} else if (untransformedAngle > 0 && untransformedAngle < Math.PI) {
(Math.PI - untransformedAngle) + Math.PI
} else {
untransformedAngle
}
}
fun calculateResultGivenLocation(asteroidMap: List<String>, rank: Int): Int {
val bestLocation = calculateBestLocationAndNumberDetected(asteroidMap).first
val chosenVaporizedAsteroid = calculateVaporizedAsteroidLocationGivenRank(bestLocation, asteroidMap, rank)
return 100 * chosenVaporizedAsteroid.x + chosenVaporizedAsteroid.y
}
fun calculateVaporizedAsteroidLocationGivenRank(
bestLocation: GridPoint2d,
asteroidMap: List<String>,
rank: Int
): GridPoint2d {
val groupedDistanceLocationPairsByAngle =
groupDistanceLocationPairsByAngle(bestLocation, asteroidMap, rank).toSortedMap()
val vaporizedAsteroids = mutableListOf<Pair<Int, Pair<Double, GridPoint2d>>>()
groupedDistanceLocationPairsByAngle.values.forEach { distanceLocationPairs ->
distanceLocationPairs.sortBy { it.first }
distanceLocationPairs.withIndex().forEach { (index, value) ->
vaporizedAsteroids.add(Pair(index, value))
}
}
vaporizedAsteroids.sortBy { it.first }
return vaporizedAsteroids[rank - 1].second.second
}
private fun groupDistanceLocationPairsByAngle(
bestLocation: GridPoint2d,
asteroidMap: List<String>,
rank: Int
): MutableMap<Double, MutableList<Pair<Double, GridPoint2d>>> {
val result = mutableMapOf<Double, MutableList<Pair<Double, GridPoint2d>>>()
val height = asteroidMap.size
val width = asteroidMap[0].length
for (y in 0 until height) {
for (x in 0 until width) {
val otherLocation = GridPoint2d(x, y)
if (asteroidMap[y][x] != '#' || bestLocation == otherLocation) {
continue
}
val angle = calculateAngle(bestLocation, otherLocation)
val distance = bestLocation.l2DistanceTo(otherLocation)
if (result.containsKey(angle)) {
result[angle]!!.add(Pair(distance, otherLocation))
} else {
result[angle] = mutableListOf(Pair(distance, otherLocation))
}
}
}
return result
}
| 0 | Kotlin | 0 | 0 | bcd6daf81787ed9a1d90afaa9646b1c513505d75 | 4,560 | AdventOfCode2019 | MIT License |
src/day03/Day03.kt | EndzeitBegins | 573,569,126 | false | {"Kotlin": 111428} | package day03
import readInput
import readTestInput
private data class Rucksack(val items: String) {
val compartmentA: Compartment = items.take(items.length / 2)
val compartmentB: Compartment = items.drop(items.length / 2)
}
private typealias Compartment = String
private typealias Item = Char
private typealias ElfGroup = List<Rucksack>
private fun List<String>.asRucksacks(): Sequence<Rucksack> = this
.asSequence()
.map { rucksackItems -> Rucksack(rucksackItems) }
private fun Rucksack.findItemsInBothCompartments(): Set<Item> =
compartmentA.toSet().intersect(compartmentB.toSet())
private fun ElfGroup.findCommonItems(): Set<Item> = this
.asSequence()
.map { it.items.toSet() }
.reduce { acc, curr -> acc.intersect(curr) }
private val Item.priority: Int
get() = when (code) {
in 65..90 -> code - 38
in 97..122 -> code - 96
else -> error("Character '$this' is not supported!")
}
private fun Sequence<Rucksack>.groupElves(): Sequence<ElfGroup> =
windowed(3, 3, partialWindows = false)
private fun part1(input: List<String>): Int = input
.asRucksacks()
.flatMap { rucksack -> rucksack.findItemsInBothCompartments() }
.map { item -> item.priority }
.sum()
private fun part2(input: List<String>): Int = input
.asRucksacks()
.groupElves()
.flatMap { elfGroup -> elfGroup.findCommonItems() }
.map { item -> item.priority }
.sum()
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day03")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebebdf13cfe58ae3e01c52686f2a715ace069dab | 1,729 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day08.kt | nikolakasev | 572,681,478 | false | {"Kotlin": 35834} | fun main() {
fun inputTo2DArray(input: String): Array<Array<Int>> {
return input.split("\n").map {
it.chunked(1).map { tree ->
tree.toInt()
}.toTypedArray()
}.toTypedArray()
}
fun part1(forest: Array<Array<Int>>): Int {
var count = 0
for (y in 1..forest.size - 2)
for (x in 1..forest[0].size - 2) {
if (checkIfVisible(x, y, forest)) count += 1
}
return count + 2 * forest.size + 2 * forest[0].size - 4
}
fun part2(forest: Array<Array<Int>>): Int {
return (0 until forest.size).maxOf { y ->
(0 until forest[0].size - 1).maxOf { x ->
scenicScore(x, y, forest)
}
}
}
val testInput = inputTo2DArray(readText("Day08_test"))
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = inputTo2DArray(readText("Day08"))
println(part1(input))
println(part2(input))
}
fun checkIfVisible(treeX: Int, treeY: Int, forest: Array<Array<Int>>): Boolean {
val top = (treeY - 1 downTo 0).all {
forest[treeY][treeX] > forest[it][treeX]
}
val down = ((treeY + 1)..(forest.size - 1)).all {
forest[treeY][treeX] > forest[it][treeX]
}
val left = (treeX - 1 downTo 0).all {
forest[treeY][treeX] > forest[treeY][it]
}
val right = ((treeX + 1)..(forest[0].size - 1)).all {
forest[treeY][treeX] > forest[treeY][it]
}
return top || left || down || right
}
fun scenicScore(treeX: Int, treeY: Int, forest: Array<Array<Int>>): Int {
val up = (treeY - 1 downTo 0).indexOfFirst {
forest[treeY][treeX] <= forest[it][treeX]
}
val upScore = if (up == -1)
treeY
else up + 1
val down =
((treeY + 1)..(forest.size - 1)).indexOfFirst {
forest[treeY][treeX] <= forest[it][treeX]
}
val downScore = if (down == -1)
(forest.size - treeY - 1)
else down + 1
val left = (treeX - 1 downTo 0).indexOfFirst {
forest[treeY][treeX] <= forest[treeY][it]
}
val leftScore = if (left == -1)
treeX
else left + 1
val right =
((treeX + 1)..(forest[0].size - 1)).indexOfFirst {
forest[treeY][treeX] <= forest[treeY][it]
}
val rightScore = if (right == -1)
(forest[0].size - treeX - 1)
else right + 1
return upScore * leftScore * downScore * rightScore
} | 0 | Kotlin | 0 | 1 | 5620296f1e7f2714c09cdb18c5aa6c59f06b73e6 | 2,481 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Day2.kt | ivan-gusiev | 726,608,707 | false | {"Kotlin": 34715, "Python": 2022, "Makefile": 50} | import util.AocDay
import util.AocInput
import kotlin.math.max
typealias InputType = List<String>;
class Day2 : Runner {
data class CubeSet(val red: Int, val green: Int, val blue: Int) {
companion object {
fun parse(input: String): CubeSet {
var red = 0;
var green = 0;
var blue = 0;
val pieces = input.split(",").map(String::trim)
pieces
.map { piece -> piece.split(" ").map(String::trim) }
.forEach { words ->
val value = words[0].toInt()
when (words[1]) {
"red" -> red += value
"green" -> green += value
"blue" -> blue += value
}
}
return CubeSet(red, green, blue)
}
}
fun includes(other: CubeSet): Boolean {
return this.red >= other.red && this.green >= other.green && this.blue >= other.blue
}
fun leastCommonCubes(other: CubeSet): CubeSet {
return CubeSet(
max(this.red, other.red),
max(this.green, other.green),
max(this.blue, other.blue)
)
}
fun power(): Int {
return red * green * blue
}
}
data class Game(val id: Int, val sets: List<CubeSet>) {
companion object {
fun parse(input: String): Game {
val parts = input.replace("Game ", "").split(":")
val index = parts[0].toInt()
val setStrings = parts[1].split(";").map(CubeSet::parse)
return Game(index, setStrings)
}
}
fun possible(bag: CubeSet): Boolean {
return sets.all(bag::includes)
}
fun leastCubesPossible(): CubeSet {
return sets.reduce(CubeSet::leastCommonCubes)
}
}
val TEST_INPUT = """
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
""".trimIndent()
override fun run() {
val day = AocDay("2023".toInt(), "2".toInt())
val lines = AocInput.lines(day)
//val lines = TEST_INPUT.split("\n")
//part1(lines)
part2(lines)
}
fun part1(input: InputType) {
val targetBag = CubeSet(12, 13, 14)
val games = input.map(Game::parse)
val possibleIds = games.map { g ->
if (g.possible(targetBag)) {
g.id
} else {
0
}
}
games.forEach { g -> println("${g.possible(targetBag)}: $g") }
println(possibleIds.sum())
}
fun part2(input: InputType) {
val games = input.map(Game::parse)
games.forEach { g -> println("${g.leastCubesPossible().power()}: $g") }
println(games.map { g -> g.leastCubesPossible().power() }.sum())
}
}
| 0 | Kotlin | 0 | 0 | 5585816b435b42b4e7c77ce9c8cabc544b2ada18 | 3,279 | advent-of-code-2023 | MIT License |
src/com/kingsleyadio/adventofcode/y2021/day03/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2021.day03
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
part1()
part2()
}
fun part1() {
var size = 0
var array = IntArray(0)
readInput(2021, 3).forEachLine { line ->
size++
if (array.isEmpty()) array = IntArray(line.length) // adjust array size
array.indices.forEach { i -> if (line[i] == '1') array[i]++ }
}
val halfSize = size shr 1
val gamma = array.foldIndexed(0) { index, acc, item ->
val add = if (item > halfSize) 1 shl (array.lastIndex - index) else 0
acc + add
}
val epsilon = gamma xor ((1 shl array.size) - 1)
println(gamma * epsilon)
}
fun part2() {
readInput(2021, 3).useLines { lines ->
val list = lines.map { it.map(Char::digitToInt) }.toList()
val o2 = reduce(list, mostSignificant = true)
val co2 = reduce(list, mostSignificant = false)
println(o2 * co2)
}
}
fun reduce(binaryList: List<List<Int>>, mostSignificant: Boolean): Int {
var result = binaryList
var bitPosition = 0
while (result.size > 1) { // _guaranteed_ to not overflow
val (ones, zeros) = result.partition { it[bitPosition] == 1 }
val halfSize = (result.size + 1) shr 1
result = when {
mostSignificant -> if (ones.size >= halfSize) ones else zeros
else -> if (ones.size < halfSize) ones else zeros
}
bitPosition++
}
// return result.single().joinToString("").toInt(2)
val winner = result.single()
return winner.foldIndexed(0) { index, acc, item ->
val add = if (item == 1) 1 shl (winner.lastIndex - index) else 0
acc + add
}
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,710 | adventofcode | Apache License 2.0 |
src/Day16.kt | sebokopter | 570,715,585 | false | {"Kotlin": 38263} | fun main() {
val regex = """Valve (\w{2}) has flow rate=(\d+); tunnels? leads? to valves? ((\w{2})(, \w{2})*)""".toRegex()
fun mostPressure(nodes: List<Node>, currentValve: String, minutesLeft: Int, totalFlowRate: Int, valvesOpened: Set<String>): Int {
if (minutesLeft <= 0) return totalFlowRate
println("currentValvue: $currentValve")
println("minutesLeft: $minutesLeft")
val currentValveNode = nodes.first { it.valve == currentValve }
if (currentValveNode.valve in valvesOpened) {
return currentValveNode.nextValves.maxOf {nextValve ->
mostPressure(nodes, nextValve, minutesLeft - 1, totalFlowRate, valvesOpened)
}
}
return maxOf(
currentValveNode.nextValves.maxOf { nextValve ->
mostPressure(nodes, nextValve, minutesLeft - 1, totalFlowRate, valvesOpened)
},
currentValveNode.nextValves.maxOf { nextValve ->
mostPressure(nodes, nextValve, minutesLeft - 2, totalFlowRate + currentValveNode.flowRate, valvesOpened + currentValveNode.valve)
}
)
}
fun part1(input: List<String>): Int {
val currentValve = "AA"
val minutesLeft = 30
val totalFlowRate = 0
val nodes = input.map { line ->
val (valve, flowRate, tunnelValves) = regex.find(line)?.destructured ?: error("asdf")
val nextValves = tunnelValves.split(", ")
Node(valve, flowRate.toInt(), nextValves)
}
mostPressure(nodes, currentValve, minutesLeft, totalFlowRate, emptySet())
return input.size
}
fun part2(input: List<String>): Int = input.size
val testInput = readInput("Day16_test")
println("part1(testInput): " + part1(testInput))
println("part2(testInput): " + part2(testInput))
check(part1(testInput) == 24000)
check(part2(testInput) == 24000)
val input = readInput("Day16")
println("part1(input): " + part1(input))
println("part2(input): " + part2(input))
}
data class Node(val valve: String, val flowRate: Int, val nextValves: List<String>)
| 0 | Kotlin | 0 | 0 | bb2b689f48063d7a1b6892fc1807587f7050b9db | 2,140 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | dmarmelo | 573,485,455 | false | {"Kotlin": 28178} | typealias Stack = Pair<Int, List<Char>>
private data class Move(
val quantity: Int,
val from: Int,
val to: Int
)
fun main() {
fun <T> List<List<T>>.transpose(): List<List<T>> {
return buildList {
for (column in this@transpose[0].indices) {
add(
buildList {
for (row in this@transpose.indices) {
add(this@transpose[this@transpose.lastIndex - row][column])
}
}
)
}
}
}
fun String.parseStacks(): List<Stack> = lines()
.map { line -> line.windowed(size = 3, step = 4) { it[1] } }
.transpose()
.map { it.filter { char -> !char.isWhitespace() } }
.map { it[0].digitToInt() to it.drop(1) }
fun String.parseMoves(): List<Move> =
Regex("""^move (\d+) from (\d+) to (\d+)$""", RegexOption.MULTILINE)
.findAll(this).map {
val (quantity, fromPosition, toPosition) = it.destructured
Move(quantity.toInt(), fromPosition.toInt(), toPosition.toInt())
}.toList()
fun String.parseInput(): Pair<List<Stack>, List<Move>> {
val (stacks, procedure) = split("\n\n", "\r\n\r\n")
return stacks.parseStacks() to procedure.parseMoves()
}
fun List<Stack>.toMutable() = map { (position, items) ->
position to items.toMutableList()
}
fun List<Stack>.joinTopItems() = joinToString("") { (_, items) ->
items.last().toString()
}
fun part1(input: Pair<List<Stack>, List<Move>>): String {
val (stacks, moves) = input
val workingStacks = stacks.toMutable()
moves.forEach {
val (_, fromStack) = workingStacks[it.from - 1]
val (_, toStack) = workingStacks[it.to - 1]
repeat(it.quantity) {
toStack.add(fromStack.removeLast())
}
}
return workingStacks.joinTopItems()
}
fun part2(input: Pair<List<Stack>, List<Move>>): String {
val (stacks, moves) = input
val workingStacks = stacks.toMutable()
moves.forEach {
val (_, fromStack) = workingStacks[it.from - 1]
val (_, toStack) = workingStacks[it.to - 1]
val cratesToMove = fromStack.takeLast(it.quantity)
repeat(it.quantity) { fromStack.removeLast() }
toStack.addAll(cratesToMove)
}
return workingStacks.joinTopItems()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputText("Day05_test").parseInput()
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInputText("Day05").parseInput()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5d3cbd227f950693b813d2a5dc3220463ea9f0e4 | 2,848 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | stcastle | 573,145,217 | false | {"Kotlin": 24899} | import java.util.LinkedList
import java.util.Queue
fun canGo(from: Char, to: Char): Boolean {
val tFrom = if (from == 'S') 'a' else from
val tTo = if (to == 'E') 'z' else to
return tTo.code - tFrom.code <= 1
}
fun getNeighbors(
row: Int,
col: Int,
grid: List<List<Char>>,
visited: List<List<Boolean>>
): List<GridItem> {
val lastRowIndex = grid.size - 1
val lastColumnIndex = grid[0].size - 1
val curr = grid[row][col]
val neighbors: MutableList<GridItem> = mutableListOf()
// up
val potentialNeighbors =
listOf(
GridItem(row - 1, col),
GridItem(row + 1, col),
GridItem(row, col - 1),
GridItem(row, col + 1))
potentialNeighbors.forEach {
if (it.row >= 0 &&
it.col >= 0 &&
it.row <= lastRowIndex &&
it.col <= lastColumnIndex &&
canGo(curr, grid[it.row][it.col]) &&
!visited[it.row][it.col])
neighbors.add(it)
}
return neighbors
}
fun getPath(parents: Map<GridItem, GridItem>, from: GridItem, to: GridItem): List<GridItem> {
val path: MutableList<GridItem> = mutableListOf()
var curr = to // work backward through parents.
path.add(curr)
while (curr != from) {
// println("curr is $curr. Destination is $from. End was $to. Parent is ${parents[curr]}")
curr = parents[curr]!!
path.add(curr)
}
return path
}
fun createVisited(numRows: Int, numColumns: Int): MutableList<MutableList<Boolean>> =
MutableList(numRows) { MutableList(numColumns) { false } }
/** Returns the shortest path from start to end. */
fun bfs(grid: List<List<Char>>, start: GridItem, end: GridItem): List<GridItem> {
val visited = createVisited(grid.size, grid[0].size)
val q: Queue<GridItem> = LinkedList()
// maps a grid item to its parent.
val parents: MutableMap<GridItem, GridItem> = mutableMapOf()
q.add(start)
visited[start.row][start.col] = true
var success = false
while (q.isNotEmpty()) {
val v = q.poll()
if (v == end) {
success = true
break
}
getNeighbors(v.row, v.col, grid, visited).forEach {
q.add(it)
visited[it.row][it.col] = true
parents[it] = v
}
}
return if (success) getPath(parents, start, end) else emptyList()
}
fun findStart(grid: List<List<Char>>) = findChar(grid, 'S')
fun findEnd(grid: List<List<Char>>) = findChar(grid, 'E')
fun findChar(grid: List<List<Char>>, char: Char): GridItem {
grid.forEachIndexed { row, innerList ->
innerList.forEachIndexed { col, c -> if (c == char) return GridItem(row, col) }
}
throw Exception("did not find char")
}
fun getStarts(grid: List<List<Char>>): List<GridItem> {
val starts: MutableList<GridItem> = mutableListOf()
grid.forEachIndexed { row, v ->
v.forEachIndexed { col, c -> if (c == 'S' || c == 'a') starts.add(GridItem(row, col)) }
}
return starts
}
fun main() {
fun part1(input: List<String>): Int {
val grid = inputToLoL(input)
val path = bfs(grid, findStart(grid), findEnd(grid))
// println(path)
return path.size - 1 // count the steps in the path, not the number of elements in the path.
}
fun part2(input: List<String>): Int {
val grid = inputToLoL(input)
val end = findEnd(grid)
return getStarts(grid).map { start -> bfs(grid, start, end).size - 1 }.filter { it != -1 }.min()
}
val day = "12"
val testInput = readInput("Day${day}_test")
println("Part 1 test = ${part1(testInput)}")
val input = readInput("Day${day}")
println("part1 = ${part1(input)}")
println("Part 2 test = ${part2(testInput)}")
println("part2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 746809a72ea9262c6347f7bc8942924f179438d5 | 3,602 | aoc2022 | Apache License 2.0 |
src/Day08.kt | Soykaa | 576,055,206 | false | {"Kotlin": 14045} | data class Quadtuple(
val a: Pair<Boolean, Int>,
val b: Pair<Boolean, Int>,
val c: Pair<Boolean, Int>,
val d: Pair<Boolean, Int>
)
private fun checkDirection(line: List<Int>, element: Int): Pair<Boolean, Int> {
var scenicScore = 0
for (currentElement in line) {
scenicScore++
if (currentElement >= element)
return Pair(false, scenicScore)
}
return Pair(true, scenicScore)
}
private fun lookAtDirections(input: List<String>): List<Quadtuple> {
val inputAsString = input.joinToString("").toList()
val result = mutableListOf<Quadtuple>()
(1 until input.size - 1).forEach { i ->
(1 until input[0].length - 1).forEach { j ->
val column = inputAsString.slice(j until inputAsString.size step input[i].length)
val visibilityLeft =
checkDirection(input[i].slice(0 until j).toList().map { it - '0' }.reversed(), input[i][j] - '0')
val visibilityRight = checkDirection(
input[i].slice(j + 1 until input[i].length).toList().map { it - '0' },
input[i][j] - '0'
)
val visibilityTop =
checkDirection(column.slice(0 until i).map { it - '0' }.reversed(), input[i][j] - '0')
val visibilityBottom =
checkDirection(column.slice(i + 1 until column.size).map { it - '0' }, input[i][j] - '0')
result += Quadtuple(visibilityBottom, visibilityTop, visibilityLeft, visibilityRight)
}
}
return result
}
fun main() {
fun part1(input: List<String>): Int = lookAtDirections(input).count { (bottom, top, left, right) ->
bottom.first || left.first || top.first || right.first
} + input.size * 2 + input[0].length * 2 - 4
fun part2(input: List<String>): Int = lookAtDirections(input).maxOf { (bottom, top, left, right) ->
bottom.second * left.second * top.second * right.second
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1e30571c475da4db99e5643933c5341aa6c72c59 | 2,034 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/mkuhn/aoc/Day11.kt | mtkuhn | 572,236,871 | false | {"Kotlin": 53161} | package mkuhn.aoc
import mkuhn.aoc.util.readInput
import mkuhn.aoc.util.splitList
fun main() {
val input = readInput("Day11")
println(day11part1(input))
println(day11part2(input))
}
fun day11part1(input: List<String>): Long {
val monkeys = Monkey.fromInputList(input)
(1 .. 20).forEach { round ->
monkeys.forEach { monkey ->
monkey.inspectItems(3, monkeys)
}
}
return monkeys.map { it.inspectionCount }.sortedDescending().let { it[0] * it[1] }
}
fun day11part2(input: List<String>): Long {
val monkeys = Monkey.fromInputList(input)
val modulus = monkeys.map { it.testDivisor }.reduce(Long::times)
(1 .. 10000).forEach { round ->
monkeys.forEach { monkey ->
monkey.inspectItems(1, monkeys, modulus)
}
}
return monkeys.map { it.inspectionCount }.sortedDescending().let { it[0] * it[1] }
}
data class Monkey(val itemWorryLevels: MutableList<Long>,
val operation: (Long) -> (Long),
val testDivisor: Long,
val trueRecipientIndex: Int,
val falseRecipientIndex: Int,
var inspectionCount: Long = 0L) {
companion object {
fun fromInputList(input: List<String>) =
input.splitList("").map { m ->
Monkey(
m[1].substringAfter("items: ").split(", ").map { it.toLong() }.toMutableList(),
m[2].substringAfter("new = ").split(" ").let {
when {
it[1] == "*" && it[2] == "old" -> { old -> old * old }
it[1] == "+" && it[2] == "old" -> { old -> old + old }
it[1] == "+" -> { old -> old + it[2].toLong() }
it[1] == "*" -> { old -> old * it[2].toLong() }
else -> error("bad operation")
}
},
m[3].substringAfter("by ").toLong(),
m[4].substringAfter("monkey ").toInt(),
m[5].substringAfter("monkey ").toInt()
)
}
}
fun inspectItems(worryDivisor: Long, monkeys: List<Monkey>, modulus: Long? = null) {
while(itemWorryLevels.isNotEmpty()) {
val inWorryLevel = itemWorryLevels.removeFirst()
val newWorryLevel = (operation(inWorryLevel)/worryDivisor).let { if(modulus != null) it % modulus else it }
val recipient = if(newWorryLevel%testDivisor == 0L) trueRecipientIndex else falseRecipientIndex
monkeys[recipient].itemWorryLevels += newWorryLevel
inspectionCount += 1L
}
}
} | 0 | Kotlin | 0 | 1 | 89138e33bb269f8e0ef99a4be2c029065b69bc5c | 2,715 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day05.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2021
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
class Aoc2021Day05 {
companion object {
private const val POINT_SEPARATOR = " -> "
private const val NUMBER_SEPARATOR = ","
}
data class Point(val x: Int, val y: Int) : Comparable<Point> {
override operator fun compareTo(other: Point): Int {
return when {
this === other -> 0
this.x > other.x -> 1
this.x < other.x -> -1
this.y > other.y -> 1
this.y < other.y -> -1
else -> 0
}
}
override fun toString(): String {
return "($x, $y)"
}
}
data class Space(var points: MutableMap<Point, Int> = mutableMapOf()) {
private fun addPoint(point: Point) {
points.merge(point, 1) { a, b -> a + b }
}
fun addPoints(newPoints: List<Point>) {
newPoints.forEach { point -> addPoint(point) }
}
fun countDangerousPoints(): Int {
return points.count { it.value > 1 }
}
}
data class Line(val from: Point, val to: Point) {
fun isStraight(): Boolean {
return (from.x == to.x || from.y == to.y)
}
fun toPoints(): List<Point> {
val points: MutableSet<Point> = mutableSetOf(from, to)
if (from.x == to.x) {
for (y in from.y until to.y) {
points.add(Point(from.x, y))
}
} else if (from.y == to.y) {
for (x in from.x until to.x) {
points.add(Point(x, from.y))
}
} else {
// 45 degrees
var x = from.x
var y = from.y
val dx = if (from.x < to.x) 1 else -1
val dy = if (from.y < to.y) 1 else -1
while (x != to.x) {
points.add(Point(x, y))
x += dx
y += dy
}
}
return points.toSortedSet().toList()
}
override fun toString(): String {
return "Line{$from - $to}"
}
}
private fun String.asLine(): Line {
val (x1, y1, x2, y2) = this
.replace(POINT_SEPARATOR, NUMBER_SEPARATOR)
.split(Regex(NUMBER_SEPARATOR))
.map { it.toInt() }
val points = listOf(Point(x1, y1), Point(x2, y2)).sorted()
return Line(points.first(), points.last())
}
fun part1(input: List<String>): Int {
val space = Space()
input
.map { it.asLine() }
.filter { it.isStraight() }
.map { it.toPoints() }
.forEach { space.addPoints(it) }
return space.countDangerousPoints()
}
fun part2(input: List<String>): Int {
val space = Space()
input
.map { it.asLine() }
.map { it.toPoints() }
.forEach { space.addPoints(it) }
return space.countDangerousPoints()
}
}
fun main() {
val solver = Aoc2021Day05()
val prefix = "aoc2021/aoc2021day05"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(5, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(12, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
} | 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 3,586 | adventofcode | MIT License |
solutions/aockt/y2023/Y2023D11.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.math.distinctPairs
import aockt.util.parse
import aockt.util.spacial.Point
import aockt.util.spacial.distanceTo
import io.github.jadarma.aockt.core.Solution
object Y2023D11 : Solution {
/**
* A galaxy expansion simulator.
* @param galaxies The apparent locations of the tracked galaxies.
*/
private class GalaxySimulator(private val galaxies: Set<Point>) {
private val emptyRows: List<Long>
private val emptyColumns: List<Long>
init {
require(galaxies.isNotEmpty()) { "Nothing to simulate." }
val populatedRows = galaxies.map { it.y }.toSet()
val populatedColumns = galaxies.map { it.x }.toSet()
emptyRows = (0L..populatedRows.max()).filterNot { it in populatedRows }.toList()
emptyColumns = (0L..populatedColumns.max()).filterNot { it in populatedColumns }.toList()
}
/** Expand the galaxy, increasing empty space by a [factor], returning the resulting locations of galaxies. */
fun expand(factor: Int): Set<Point> = buildSet {
val delta = factor - 1
for (galaxy in galaxies) {
val horizontalExpansions = emptyColumns.indexOfLast { it < galaxy.x }.plus(1)
val verticalExpansions = emptyRows.indexOfLast { it < galaxy.y }.plus(1)
Point(
x = galaxy.x + horizontalExpansions * delta,
y = galaxy.y + verticalExpansions * delta,
).let(::add)
}
}
}
/** Parse the [input] and return a [GalaxySimulator] initialized with current galactic readings. */
private fun parseInput(input: String): GalaxySimulator = parse {
input
.lines()
.asReversed()
.flatMapIndexed { row, line -> line.mapIndexed { column, c -> Triple(row, column, c) } }
.filter { it.third == '#' }
.map { (y, x, _) -> Point(x.toLong(), y.toLong()) }
.toSet()
.let(::GalaxySimulator)
}
/**
* Expand the galaxy by the given [expansionFactor], and return the sum of the shortest distances between all
* unique galaxy pairs.
*/
private fun GalaxySimulator.solve(expansionFactor: Int): Long =
expand(expansionFactor)
.distinctPairs()
.sumOf { it.first distanceTo it.second }
override fun partOne(input: String) = parseInput(input).solve(expansionFactor = 2)
override fun partTwo(input: String) = parseInput(input).solve(expansionFactor = 1_000_000)
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 2,600 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day13.kt | zsmb13 | 572,719,881 | false | {"Kotlin": 32865} | package day13
import readInputString
sealed interface PData : Comparable<PData>
data class PInt(val value: Int) : PData {
override fun toString() = value.toString()
override fun compareTo(other: PData): Int {
return when (other) {
is PInt -> value compareTo other.value
is PList -> PList(this) compareTo other
}
}
}
data class PList(val values: List<PData>) : PData {
override fun toString() = values.joinToString(separator = ",", prefix = "[", postfix = "]")
override fun compareTo(other: PData): Int {
return when (other) {
is PInt -> this compareTo PList(other)
is PList -> {
for (i in values.indices) {
if (i !in other.values.indices) {
return 1 // Ran out of right values, fail
}
val result = values[i] compareTo other.values[i]
if (result == 0) {
continue
}
return result
}
// Right list has more values still, pass
if (other.values.size > this.values.size) {
return -1
}
// Identical lists, no result yet
return 0
}
}
}
}
fun PList(pData: PData) = PList(listOf(pData))
fun parse(s: String): PData {
if (s.all(Char::isDigit)) return PInt(s.toInt())
if (s == "[]") return PList(emptyList())
val csv = s.removeSurrounding("[", "]")
val values = mutableListOf<PData>()
var done = 0
var nesting = 0
csv.forEachIndexed { i, char ->
when (char) {
'[' -> nesting++
']' -> nesting--
',' -> if (nesting == 0) {
values += parse(csv.substring(done, i))
done = i + 1
}
}
}
values += parse(csv.substring(done))
return PList(values)
}
fun main() {
fun part1(testInput: String): Int {
return testInput.trim()
.split(System.lineSeparator().repeat(2))
.mapIndexed { index, it ->
val (first, second) = it.split(System.lineSeparator()).map(::parse)
if (first < second) index + 1 else 0
}
.sum()
}
fun part2(testInput: String): Int {
val packets = testInput.split(System.lineSeparator())
.filter(String::isNotBlank)
.map(::parse)
val dividers = listOf("[[2]]", "[[6]]").map(::parse)
val pos1 = packets.count { it < dividers[0] } + 1
val pos2 = packets.count { it < dividers[1] } + 2
return pos1 * pos2
}
val testInput = readInputString("Day13_test")
check(part1(testInput).also(::println) == 13)
check(part2(testInput).also(::println) == 140)
val input = readInputString("Day13")
check(part1(input).also(::println) == 5252)
check(part2(input).also(::println) == 20592)
}
| 0 | Kotlin | 0 | 6 | 32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35 | 3,021 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | GarrettShorr | 571,769,671 | false | {"Kotlin": 82669} | fun main() {
fun part1(input: List<String>): Int {
val THEIR_ROCK = "A"
val THEIR_PAPER = "B"
val THEIR_SCISSORS = "C"
val MY_ROCK = "X"
val MY_PAPER = "Y"
val MY_SCISSORS = "Z"
val scores = mutableListOf<Int>()
val rounds = input.map { it.split(" ") }
val symbolScores = mapOf(
MY_ROCK to 1,
MY_PAPER to 2,
MY_SCISSORS to 3
)
val roundScores = mapOf(
THEIR_ROCK + MY_ROCK to 3,
THEIR_PAPER + MY_PAPER to 3,
THEIR_SCISSORS + MY_SCISSORS to 3,
THEIR_ROCK + MY_PAPER to 6,
THEIR_ROCK + MY_SCISSORS to 0,
THEIR_PAPER + MY_ROCK to 0,
THEIR_PAPER + MY_SCISSORS to 6,
THEIR_SCISSORS + MY_ROCK to 6,
THEIR_SCISSORS + MY_PAPER to 0
)
for(round in rounds) {
val theirs = round[0]
val yours = round[1]
var score = symbolScores[yours]
println("theirs: $theirs yours: $yours score: $score round result: ${roundScores[theirs+yours]!!}")
score = score?.plus(roundScores[theirs+yours]!!) ?: 0
println("after the round: $score")
scores.add(score)
}
return scores.sum()
}
// rock = A = 1 lose X: scissors 3, tie Y: rock 1, win Z: paper : 2
// paper B = 2 lose X: rock 1, tie Y: paper: 2, win Z: scissors: 3
// scissors = C = 3 lose X: paper 2, tie Y: scissors: 3, win Z: rock: 1
fun part2(input: List<String>): Int {
val scores = mutableListOf<Int>()
val roundScores = mapOf(
"A X" to 3 + 0,
"A Y" to 1 + 3,
"A Z" to 2 + 6,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 2 + 0,
"C Y" to 3 + 3,
"C Z" to 1 + 6
)
for(round in input) {
println("round: $round score: ${roundScores[round]!!}")
scores.add(roundScores[round]!!)
}
return scores.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
// println(part1(testInput))
println(part2(testInput))
val input = readInput("Day02")
// output(part1(input))
output(part2(input))
}
| 0 | Kotlin | 0 | 0 | 391336623968f210a19797b44d027b05f31484b5 | 2,375 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/days/Day8.kt | butnotstupid | 433,717,137 | false | {"Kotlin": 55124} | package days
class Day8 : Day(8) {
override fun partOne(): Any {
val uniqueDigitsLength = setOf(2, 3, 4, 7)
return inputList.sumOf { input ->
val (_, display) = input.split(" | ")
display.split(" ").count { it.length in uniqueDigitsLength }
}
}
override fun partTwo(): Any {
// "9" is the only (6) that's single signal extra of 4+7
// of remaining two (6) that contains 7 is "0", doesn't contain 7 is "6"
// "3" is the only (5) containing 7
// "5" is (5) with single signal to 6, another (5) is "2"
return inputList.sumOf { input ->
val (digits, display) = input.split(" | ")
val digitByLen = digits.split(" ").map { it.toSet() }.groupBy { it.size }
val (one, seven) = digitByLen.getValue(2).first() to digitByLen.getValue(3).first()
val (four, eight) = digitByLen.getValue(4).first() to digitByLen.getValue(7).first()
val nine = digitByLen.getValue(6).find { it.subtract(four.union(seven)).size == 1 }
val (zero, six) = digitByLen.getValue(6).filter { it != nine }
.partition { it.containsAll(seven) }
.let { it.first.first() to it.second.first() }
val three = digitByLen.getValue(5).find { it.containsAll(seven) }
val (five, two) = digitByLen.getValue(5).filter { it != three}
.partition { six.minus(it).size == 1 }
.let { it.first.first() to it.second.first() }
val digitMap = mapOf(
zero to 0, one to 1, two to 2, three to 3, four to 4,
five to 5, six to 6, seven to 7, eight to 8, nine to 9
)
display.split(" ").map { it.toSet() }
.fold(0L) { sum, digit -> sum * 10 + digitMap.getValue(digit) }
}
}
}
| 0 | Kotlin | 0 | 0 | a06eaaff7e7c33df58157d8f29236675f9aa7b64 | 1,866 | aoc-2021 | Creative Commons Zero v1.0 Universal |
kotlin/0973-k-closest-points-to-origin.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | /**
Solution using min heap
*/
class Solution {
fun kClosest(points: Array<IntArray>, k: Int): Array<IntArray> {
val minHeap = PriorityQueue<IntArray> { a, b -> a[0] - b[0] }
val result = Array<IntArray>(k) { IntArray(2) { 0 } }
for (point in points) {
minHeap.add(
intArrayOf(
/* distance from (0,0) */ point[0].squared() + point[1].squared(),
/* x coordinate */ point[0],
/* y coordinate */ point[1]
)
)
}
for (i in 0 until k) {
val pointWithDistance = minHeap.poll()
result[i][0] = pointWithDistance[1]
result[i][1] = pointWithDistance[2]
}
return result
}
private fun Int.squared() = this * this
}
/**
Solution using a max Heap
*/
class Solution {
fun kClosest(points: Array<IntArray>, k: Int): Array<IntArray> {
val maxHeap = PriorityQueue<IntArray>{ e1, e2 -> e2[0] - e1[0] }
val res = Array(k){ IntArray(2) }
for(point in points){
val (x,y) = point
val distance = (x * x) + (y * y) // we don't need to sqrt since the actual length is of no use
maxHeap.add(intArrayOf(distance,x,y))
if(maxHeap.size > k) // keep only the K closest distances
maxHeap.poll()
}
for(i in res.indices){
val (d,x,y) = maxHeap.poll()
res[i] = intArrayOf(x,y)
}
return res
}
}
/**
Solution using QuickSelect
*/
class Solution {
fun kClosest(points: Array<IntArray>, k: Int): Array<IntArray> {
if(points.size == k)
return points
val res = Array(k){ IntArray(2) }
quickSelect(0, points.size-1,points,k)
for(i in res.indices){
res[i] = points[i]
}
return res
}
private fun quickSelect(l: Int, r: Int, points: Array<IntArray>, k: Int){
var lPointer = l
for(i in l until r){
if(distance(i, points) <= distance(r,points)){ //r is pivot
swap(i,lPointer,points)
lPointer++
}
}
swap(lPointer,r,points)
if(lPointer > k)
quickSelect(l, lPointer-1, points, k)
else if(lPointer < k)
quickSelect(lPointer+1, r, points, k)
else //lPointer == k
return
}
private fun swap(i: Int, j: Int, points: Array<IntArray>){
val temp = points[i]
points[i] = points[j]
points[j] = temp
}
private fun distance(i: Int, points: Array<IntArray>) = (points[i][0] * points[i][0]) + (points[i][1] * points[i][1])
}
/**
Solution using built in sort function
*/
class Solution {
fun kClosest(points: Array<IntArray>, k: Int): Array<IntArray> {
val sorted = points.sortedBy{ it[0]*it[0] + it[1]*it[1]}
val list = arrayListOf<IntArray>()
for (i in 0..k-1) {
list.add(sorted[i])
}
return list.toTypedArray()
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 3,090 | leetcode | MIT License |
src/Day15.kt | wlghdu97 | 573,333,153 | false | {"Kotlin": 50633} | import kotlin.collections.List
import kotlin.collections.any
import kotlin.collections.firstOrNull
import kotlin.collections.map
import kotlin.collections.maxOf
import kotlin.collections.minOf
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
private class Map constructor(val sensors: List<Sensor>) {
val minX = sensors.minOf { min(it.sensorPos.x - it.sensorRadius, it.beaconPos.x) }
val maxX = sensors.maxOf { max(it.sensorPos.x + it.sensorRadius, it.beaconPos.x) }
fun inBeaconRange(position: Position): Boolean {
if (sensors.any { (position == it.sensorPos) || (position == it.beaconPos) }) {
return false
}
return sensors.any { it.intersects(position) }
}
fun firstSensorInPosition(position: Position): Sensor? {
return sensors.firstOrNull { it.intersects(position) }
}
class Sensor(val sensorPos: Position, val beaconPos: Position) {
val sensorRadius = sensorPos.taxicabDistance(beaconPos)
fun intersects(position: Position): Boolean {
val distance = sensorPos.taxicabDistance(position)
return (distance <= sensorRadius)
}
private fun Position.taxicabDistance(other: Position) =
abs(this.x - other.x) + abs(this.y - other.y)
}
data class Position(val x: Int, val y: Int)
}
private val sensorRegex = Regex("Sensor at x=([-\\d]+), y=([-\\d]+): closest beacon is at x=([-\\d]+), y=([-\\d]+)")
private fun parseMap(input: List<String>): Map {
val sensors = input.map {
val (sensorX, sensorY, beaconX, beaconY) = sensorRegex.matchEntire(it)?.destructured
?: throw IllegalArgumentException()
Map.Sensor(Map.Position(sensorX.toInt(), sensorY.toInt()), Map.Position(beaconX.toInt(), beaconY.toInt()))
}
return Map(sensors)
}
fun main() {
fun part1(input: List<String>, y: Int): Int {
val map = parseMap(input)
var intersects = 0
for (x in map.minX..map.maxX) {
if (map.inBeaconRange(Map.Position(x, y))) {
intersects += 1
}
}
return intersects
}
fun part2(input: List<String>, squareWidth: Int): Long {
val map = parseMap(input)
var beaconCandidate: Position? = null
for (x in 0..squareWidth) {
var y = 0
while (y in 0..squareWidth) {
val sensor = map.firstSensorInPosition(Map.Position(x, y))
if (sensor != null) {
// jump down to bottom of its sensor range
val localX = abs(sensor.sensorPos.x - x)
y = sensor.sensorPos.y + sensor.sensorRadius - localX + 1
continue
} else {
beaconCandidate = Position(x, y)
break
}
}
}
return beaconCandidate?.let {
(it.x * 4000000L) + it.y
} ?: throw NullPointerException()
}
val testInput = readInput("Day15-Test01")
val input = readInput("Day15")
println(part1(testInput, 10))
println(part1(input, 2000000))
println(part2(testInput, 20))
println(part2(input, 4000000))
}
| 0 | Kotlin | 0 | 0 | 2b95aaaa9075986fa5023d1bf0331db23cf2822b | 3,227 | aoc-2022 | Apache License 2.0 |
src/day11/Day11.kt | EndzeitBegins | 573,569,126 | false | {"Kotlin": 111428} | package day11
import readInput
import readTestInput
private data class Monkey(
val items: MutableList<Long>,
val operation: (initialWorryLevel: Long) -> Long,
val nextMonkey: (worryLevel: Long) -> Int,
)
private fun List<String>.toMonkeys(withStressRelief: Boolean): List<Monkey> {
val commonDivisor = this
.filter { line -> line.contains("divisible by") }
.map { it.substringAfter("divisible by ").toLong() }
.reduce { lhs, rhs -> lhs * rhs }
return this
.windowed(size = 6, step = 7) { monkeyLines ->
Monkey(
items = monkeyLines.extractStartingItems().toMutableList(),
operation = monkeyLines.extractOperation(
commonDivisor = commonDivisor,
withStressRelief = withStressRelief
),
nextMonkey = monkeyLines.extractMonkeyTargets()
)
}
}
private fun List<String>.extractStartingItems() =
this[1].substringAfter(':').split(',').map { it.trim().toLong() }
private fun List<String>.extractOperation(
commonDivisor: Long,
withStressRelief: Boolean
): (initialWorryLevel: Long) -> Long {
val (lhsStr, operatorStr, rhsStr) = this[2].substringAfter('=').trim().split(' ')
val lhs = lhsStr.toLongOrNull()
val rhs = rhsStr.toLongOrNull()
val operator: Long.(Long) -> Long = when (operatorStr) {
"*" -> Long::times
"+" -> Long::plus
else -> error("Operator $operatorStr is not supported!")
}
return { initialWorryLevel ->
val left = (lhs ?: initialWorryLevel) % commonDivisor
val right = (rhs ?: initialWorryLevel) % commonDivisor
if (withStressRelief) {
left.operator(right) / 3
} else {
left.operator(right)
}
}
}
private fun List<String>.extractMonkeyTargets(): (worryLevel: Long) -> Int {
val divisor = this[3].substringAfter("by ").toInt()
val monkeyA = this[4].substringAfter("monkey ").toInt()
val monkeyB = this[5].substringAfter("monkey ").toInt()
return { worryLevel -> if (worryLevel % divisor == 0L) monkeyA else monkeyB }
}
private fun List<Monkey>.inspectionsAfter(rounds: Int): List<Long> {
val monkeys = this.toMutableList()
val inspections = MutableList(monkeys.size) { 0L }
repeat(rounds) {
for (index in monkeys.indices) {
val monkey = monkeys[index]
inspections[index] += monkey.items.size.toLong()
while (monkey.items.isNotEmpty()) {
val item = monkey.items.removeFirst()
val updatedWorryLevel = monkey.operation(item)
val targetMonkey = monkey.nextMonkey(updatedWorryLevel)
monkeys[targetMonkey].items += updatedWorryLevel
}
}
}
return inspections
}
private fun List<Long>.toMonkeyBusiness(): Long =
this.sortedDescending().take(2).reduce { lhs, rhs -> lhs * rhs }
private fun part1(input: List<String>): Long {
val monkeys = input.toMonkeys(withStressRelief = true)
val inspections = monkeys.inspectionsAfter(rounds = 20)
return inspections.toMonkeyBusiness()
}
private fun part2(input: List<String>): Long {
val monkeys = input.toMonkeys(withStressRelief = false)
val inspections = monkeys.inspectionsAfter(rounds = 10_000)
return inspections.toMonkeyBusiness()
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day11")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ebebdf13cfe58ae3e01c52686f2a715ace069dab | 3,708 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day05.kt | tbilou | 572,829,933 | false | {"Kotlin": 40925} | fun main() {
val day = "Day05"
fun part1(input: String): String {
var parsedInput = parseInput(input)
parsedInput.instuctions.forEach { instruction ->
val fromStack = parsedInput.stacks.get(instruction.from - 1)
val toStack = parsedInput.stacks.get(instruction.to - 1)
repeat(instruction.amount) { toStack.add(fromStack.removeLast()) }
}
val result = parsedInput.stacks.fold("") { acc, item -> acc + item.last() }
return result
}
fun part2(input: String): String {
var parsedInput = parseInput(input)
parsedInput.instuctions.forEach { instruction ->
val fromStack = parsedInput.stacks.get(instruction.from - 1)
val toStack = parsedInput.stacks.get(instruction.to - 1)
toStack.addAll(fromStack.removeN(instruction.amount))
}
val result = parsedInput.stacks.fold("") { acc, item -> acc + item.last() }
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readText("${day}_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readText("$day")
println(part1(input))
println(part2(input))
}
private fun <String> ArrayDeque<String>.removeN(amount: Int): List<String> {
var tmp = mutableListOf<String>()
repeat(amount) {tmp.add(this.removeLast())}
return tmp.reversed()
}
// "[Z] [M] [P]" -> [Z, M, P]
fun parseInput(input: String): StacksAndOperations {
val stacks = mutableListOf<ArrayDeque<String>>()
val list = input.split("\n\n")
// Initial Stacks configuration
list.first().split('\n')
.reversed()
.also {
// Build the list of stacks.
val numColumns: Int = it.first().trim().last().digitToInt()
for (i in 1..numColumns) {
stacks.add(ArrayDeque(0))
}
}
.drop(1)
.map { s ->
s.chunked(4)
.map { it.filter { it in 'A'..'Z' } }
.mapIndexed { i, e -> if (e.isNotEmpty()) stacks[i].add(e) }
}
// List of operations
val operations = list.last().split('\n')
.map { line -> parseOperation(line) }
return StacksAndOperations(stacks, operations)
}
private fun parseOperation(line: String): Operation {
val inputLineRegex = """move (\d+) from (\d+) to (\d+)""".toRegex()
val (amount, from, to) = inputLineRegex
.matchEntire(line)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $line")
return Operation(amount.toInt(), from.toInt(), to.toInt())
}
data class Operation(val amount: Int, val from: Int, val to: Int)
data class StacksAndOperations(val stacks: List<ArrayDeque<String>>, val instuctions: List<Operation>)
| 0 | Kotlin | 0 | 0 | de480bb94785492a27f020a9e56f9ccf89f648b7 | 2,863 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/icu/trub/aoc/day11/Universe.kt | dtruebin | 728,432,747 | false | {"Kotlin": 76202} | package icu.trub.aoc.day11
import icu.trub.aoc.util.Point
data class Universe(val galaxyIdToCoordinates: Map<Int, Point>) {
/**
* @return [Point] for galaxy with the provided id
*/
fun get(galaxyId: Int) = galaxyIdToCoordinates[galaxyId]!!
/**
* @return a new universe, with each empty line (having no galaxies) replaced by [factor] lines.
* For example, with `factor = 2` an empty line would be turned into 2 empty lines.
*/
fun expand(factor: Int = 2): Universe = Universe(buildMap {
val knownCoordinates = galaxyIdToCoordinates.values
val xExpansionCoordinates = (0..knownCoordinates.maxOf { it.x }).asSequence()
.filter { x -> knownCoordinates.none { it.x == x } }
val yExpansionCoordinates = (0..knownCoordinates.maxOf { it.y }).asSequence()
.filter { y -> knownCoordinates.none { it.y == y } }
putAll(galaxyIdToCoordinates)
xExpansionCoordinates.sortedDescending().forEach { x ->
filterValues { it.x > x }
.mapValues { (_, point) -> point.right(factor - 1) }
.let { putAll(it) }
}
yExpansionCoordinates.sortedDescending().forEach { y ->
filterValues { it.y > y }
.mapValues { (_, point) -> point.down(factor - 1) }
.let { putAll(it) }
}
})
private fun Point.right(amount: Int = 1) = Point(x + amount, y)
private fun Point.down(amount: Int = 1) = Point(x, y + amount)
/**
* @return a map from [Pair] of galaxy ids to the length of the shortest path between them
*/
fun findShortestDistancesBetweenGalaxies(): Map<Pair<Int, Int>, Int> = buildPairsOfGalaxyIds()
.associateWith { get(it.first) distanceTo get(it.second) }
private fun buildPairsOfGalaxyIds() = buildSet {
val maxGalaxyId = galaxyIdToCoordinates.size
(1..maxGalaxyId).forEach { i ->
(i + 1..maxGalaxyId).forEach { j ->
add(i to j)
}
}
}
companion object {
fun parse(input: Sequence<String>): Universe = Universe(buildMap {
var id = 0
input.forEachIndexed { y, line ->
line.forEachIndexed { x, char ->
if (char == '#') put(++id, Point(x, y))
}
}
})
}
}
| 0 | Kotlin | 0 | 0 | 1753629bb13573145a9781f984a97e9bafc34b6d | 2,367 | advent-of-code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinCostArrayEqual.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
/**
* 2448. Minimum Cost to Make Array Equal
* @see <a href="https://leetcode.com/problems/minimum-cost-to-make-array-equal/">Source</a>
*/
fun interface MinCostArrayEqual {
fun minCost(nums: IntArray, cost: IntArray): Long
}
/**
* Approach 1: Prefix Sum
*/
class MinCostArrayEqualPrefixSum : MinCostArrayEqual {
override fun minCost(nums: IntArray, cost: IntArray): Long {
// Sort integers by values.
val n: Int = nums.size
val numsAndCost = Array(n) { IntArray(2) }
for (i in 0 until n) {
numsAndCost[i][0] = nums[i]
numsAndCost[i][1] = cost[i]
}
numsAndCost.sortWith { a: IntArray, b: IntArray -> a[0] - b[0] }
// Get the prefix sum array of the costs.
val prefixCost = LongArray(n)
prefixCost[0] = numsAndCost[0][1].toLong()
for (i in 1 until n) prefixCost[i] = numsAndCost[i][1] + prefixCost[i - 1]
// Then we try every integer nums[i] and make every element equals nums[i],
// Start with nums[0]
var totalCost = 0L
for (i in 1 until n) totalCost += 1L * numsAndCost[i][1] * (numsAndCost[i][0] - numsAndCost[0][0])
var answer = totalCost
// Then we try nums[1], nums[2] and so on. The cost difference is made by the change of
// two parts: 1. prefix sum of costs. 2. suffix sum of costs.
// During the iteration, record the minimum cost we have met.
for (i in 1 until n) {
val gap = numsAndCost[i][0] - numsAndCost[i - 1][0]
totalCost += 1L * prefixCost[i - 1] * gap
totalCost -= 1L * (prefixCost[n - 1] - prefixCost[i - 1]) * gap
answer = min(answer, totalCost)
}
return answer
}
}
/**
* Approach 2: Binary Search
*/
class MinCostArrayEqualBinarySearch : MinCostArrayEqual {
companion object {
private const val MAX = 1000001
}
override fun minCost(nums: IntArray, cost: IntArray): Long {
// Initialize the left and the right boundary of the binary search.
var left = MAX
var right = 0
for (num in nums) {
left = min(left, num)
right = max(right, num)
}
var answer = getCost(nums, cost, nums[0])
// As shown in the previous picture, if F(mid) > F(mid + 1), then the minimum
// is to the right of mid, otherwise, the minimum is to the left of mid.
while (left < right) {
val mid = (right + left) / 2
val cost1 = getCost(nums, cost, mid)
val cost2 = getCost(nums, cost, mid + 1)
answer = min(cost1, cost2)
if (cost1 > cost2) left = mid + 1 else right = mid
}
return answer
}
// Get the cost of making every element equals base.
private fun getCost(nums: IntArray, cost: IntArray, base: Int): Long {
var result = 0L
for (i in nums.indices) result += 1L * abs(nums[i] - base) * cost[i]
return result
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,719 | kotlab | Apache License 2.0 |
src/problems/day7/part2/part2.kt | klnusbaum | 733,782,662 | false | {"Kotlin": 43060} | package problems.day7.part2
import java.io.File
private const val inputFile = "input/day7/input.txt"
//private const val testFile = "input/day7/test.txt"
fun main() {
val scoreSum = File(inputFile).bufferedReader().useLines { sumScores(it) }
println("Sum of scores is $scoreSum")
}
private fun sumScores(lines: Sequence<String>): Int {
return lines.map { it.toHand() }
.sorted()
.foldIndexed(0) { index, acc, hand -> acc + ((index + 1) * hand.bid) }
}
private data class Hand(val cards: List<Card>, val bid: Int, val handType: HandType) : Comparable<Hand> {
override fun compareTo(other: Hand): Int {
if (this.handType == other.handType) {
return this.cards.compareTo(other.cards)
}
return this.handType.compareTo(other.handType)
}
}
private fun List<Card>.compareTo(other: List<Card>): Int {
for (pair in this.asSequence().zip(other.asSequence())) {
if (pair.first != pair.second) {
return pair.first.compareTo(pair.second)
}
}
return 0
}
private fun String.toHand(): Hand {
val cards = this.substringBefore(" ").map { it.toCard() }
val bid = this.substringAfter(" ").toInt()
val handType = cards.toHandType()
return Hand(cards, bid, handType)
}
private enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND,
}
private fun List<Card>.toHandType(): HandType {
val typeHistogram = mutableMapOf<Card, UInt>()
for (card in this) {
typeHistogram[card] = typeHistogram.getOrDefault(card, 0u) + 1u
}
return strongestHandType(typeHistogram)
}
private fun strongestHandType(typeHistogram: Map<Card, UInt>): HandType = when (typeHistogram[Card.JOKER]) {
null -> simpleHandType(typeHistogram)
0u -> simpleHandType(typeHistogram)
5u -> HandType.FIVE_OF_A_KIND
else -> typeHistogram.keys.filter { it != Card.JOKER }.maxOf {
val possibleHistogram = typeHistogram.toMutableMap()
possibleHistogram[Card.JOKER] = possibleHistogram[Card.JOKER]!! - 1u
possibleHistogram[it] = possibleHistogram[it]!! + 1u
strongestHandType(possibleHistogram)
}
}
private fun simpleHandType(typeHistogram: Map<Card, UInt>): HandType = when {
typeHistogram.any { it.value == 5u } -> HandType.FIVE_OF_A_KIND
typeHistogram.any { it.value == 4u } -> HandType.FOUR_OF_A_KIND
typeHistogram.any { it.value == 3u } and typeHistogram.any { it.value == 2u } -> HandType.FULL_HOUSE
typeHistogram.any { it.value == 3u } -> HandType.THREE_OF_A_KIND
typeHistogram.filter { it.value == 2u }.count() == 2 -> HandType.TWO_PAIR
typeHistogram.any { it.value == 2u } -> HandType.ONE_PAIR
else -> HandType.HIGH_CARD
}
private enum class Card {
JOKER,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
QUEEN,
KING,
ACE,
}
private fun Char.toCard() = when (this) {
'J' -> Card.JOKER
'2' -> Card.TWO
'3' -> Card.THREE
'4' -> Card.FOUR
'5' -> Card.FIVE
'6' -> Card.SIX
'7' -> Card.SEVEN
'8' -> Card.EIGHT
'9' -> Card.NINE
'T' -> Card.TEN
'Q' -> Card.QUEEN
'K' -> Card.KING
'A' -> Card.ACE
else -> throw IllegalArgumentException("Char $this does not have a corresponding card")
}
| 0 | Kotlin | 0 | 0 | d30db2441acfc5b12b52b4d56f6dee9247a6f3ed | 3,364 | aoc2023 | MIT License |
src/year2022/day02/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2022.day02
import java.lang.RuntimeException
import readInput
private const val ROCK = 1
private const val PAPER = 2
private const val SCISSORS = 3
private const val WIN = 3
private const val DRAW = 2
private const val LOOSE = 1
fun main() {
fun combatA(abc:String, xyz:String): Int{
val a : Int = abc[0] - 'A' + 1
val x : Int = xyz[0] - 'X' + 1
val res: Int = when {
a == ROCK && x == ROCK -> 3
a == ROCK && x == PAPER -> 6
a == ROCK && x == SCISSORS -> 0
a == PAPER && x == ROCK -> 0
a == PAPER && x == PAPER -> 3
a == PAPER && x == SCISSORS -> 6
a == SCISSORS && x == ROCK -> 6
a == SCISSORS && x == PAPER -> 0
a == SCISSORS && x == SCISSORS -> 3
else -> throw RuntimeException()
}
return x + res
}
fun combatB(abc:String, xyz:String): Int{
val a : Int = abc[0] - 'A' + 1
val x : Int = xyz[0] - 'X' + 1
val res: Int = when {
a == ROCK && x == WIN -> 6 + 2
a == ROCK && x == DRAW -> 3 + 1
a == ROCK && x == LOOSE -> 0 + 3
a == PAPER && x == WIN -> 6 + 3
a == PAPER && x == DRAW -> 3 + 2
a == PAPER && x == LOOSE -> 0 + 1
a == SCISSORS && x == WIN -> 6 + 1
a == SCISSORS && x == DRAW -> 3 + 3
a == SCISSORS && x == LOOSE -> 0 + 2
else -> throw RuntimeException()
}
return res
}
fun part1(input: List<String>): Int {
return input.sumOf { line -> line.split(" ").let { combatA(it[0], it[1]) } }
}
fun part2(input: List<String>): Int {
return input.sumOf { line -> line.split(" ").let { combatB(it[0], it[1]) } }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("year2022/day02/test")
check(part1(testInput) == 15)
val input = readInput("year2022/day02/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 2,067 | adventOfCode | Apache License 2.0 |
src/day25/Day25.kt | spyroid | 433,555,350 | false | null | package day25
import readInput
import kotlin.system.measureTimeMillis
data class Area(val input: List<String>) {
private val width = input.first().length
private val height = input.size
data class Herd(val x: Int, val y: Int, val isHor: Boolean)
private var herds = buildList {
input.forEachIndexed { y, line ->
line.forEachIndexed { x, c -> if (c != '.') add(Herd(x, y, c == '>')) }
}
}
private fun move(herd: Herd): Pair<Herd, Int> {
var (xx, yy) = herd
if (herd.isHor) {
xx = (herd.x + 1) % width
} else {
yy = (herd.y + 1) % height
}
if (herds.firstOrNull { it.x == xx && it.y == yy } == null) {
return Pair(Herd(xx, yy, herd.isHor), 1)
}
return Pair(Herd(herd.x, herd.y, herd.isHor), 0)
}
private fun step12(isHor: Boolean): Int {
var changes = 0
herds = buildList {
herds.forEach { herd ->
if (herd.isHor == isHor) {
val (newHerd, c) = move(herd)
changes += c
add(newHerd)
} else {
add(herd)
}
}
}
return changes
}
fun step() = step12(true) + step12(false)
override fun toString() = buildString {
for (y in 0 until height) {
for (x in 0 until width) {
val h = herds.firstOrNull { it.x == x && it.y == y }
if (h == null) {
append('.')
} else {
if (h.isHor) append('>') else append('V')
}
}
appendLine()
}
}
}
fun part1(input: List<String>): Int {
val area = Area(input)
return generateSequence(2) { it + 1 }.takeWhile { area.step() != 0 }.last()
}
fun main() {
check(part1(readInput("day25/test3")) == 58)
measureTimeMillis { print("⭐️ Part1: ${part1(readInput("day25/input"))}") }.also { time -> println(" in $time ms") }
}
| 0 | Kotlin | 0 | 0 | 939c77c47e6337138a277b5e6e883a7a3a92f5c7 | 2,070 | Advent-of-Code-2021 | Apache License 2.0 |
src/main/kotlin/Day8.kt | Walop | 573,012,840 | false | {"Kotlin": 53630} | import java.io.InputStream
import kotlin.math.sqrt
class Day8 {
companion object {
private fun readTreeMap(input: InputStream?): String {
if (input == null) {
throw Exception("Input missing")
}
return input.reader().readLines().joinToString("")
}
fun process(input: InputStream?): Int {
val treeMap = readTreeMap(input)
val side = sqrt(treeMap.length.toDouble()).toInt()
return treeMap.mapIndexed { index, c ->
val x = index % side
val y = index / side
if (x == 0 || x + 1 == side || y == 0 || y + 1 == side) {
print(1)
1
} else {
if ((y * side until index).any { treeMap[it] >= c } &&
(index + 1 until (y + 1) * side).any { treeMap[it] >= c } &&
(x until index step side).any { treeMap[it] >= c } &&
((index + side)..treeMap.length step side).any { treeMap[it] >= c }) {
print(0)
0
} else {
print(1)
1
}
}
}
.sum()
}
private fun countVisibility(treeMap: String, start: Int, end: Int, step: Int, height: Char): Int {
var index = start + step
var sum = 0
if (step > 0) {
while (index < treeMap.length && index < end) {
sum++
if (treeMap[index] >= height) break
index += step
}
} else {
while (index >= 0 && index > end) {
sum++
if (treeMap[index] >= height) break
index += step
}
}
return sum
}
fun process2(input: InputStream?): Int {
val treeMap = readTreeMap(input)
val side = sqrt(treeMap.length.toDouble()).toInt()
return treeMap.mapIndexed { index, c -> Pair(index, c) }.filter { pair ->
val x = pair.first % side
val y = pair.first / side
if (x == 0 || x + 1 == side || y == 0 || y + 1 == side) {
true
} else {
!((y * side until pair.first).any { treeMap[it] >= pair.second } &&
(pair.first + 1 until (y + 1) * side).any { treeMap[it] >= pair.second } &&
(x until pair.first step side).any { treeMap[it] >= pair.second } &&
((pair.first + side)..treeMap.length step side).any { treeMap[it] >= pair.second })
}
}.maxOf { pair ->
val x = pair.first % side
val y = pair.first / side
if (x == 0 || x + 1 == side || y == 0 || y + 1 == side) {
0
} else {
val left = countVisibility(treeMap, pair.first, y * side - 1, -1, pair.second)
val right = countVisibility(treeMap, pair.first, (y + 1) * side, 1, pair.second)
val up = countVisibility(treeMap, pair.first, x - 1, -side, pair.second)
val down = countVisibility(treeMap, pair.first, treeMap.length, side, pair.second)
// val left = (pair.first - 1..y * side).takeWhile { treeMap[it] < pair.second }.count() + 1
// val right = (pair.first + 1 until (y + 1) * side).takeWhile { treeMap[it] < pair.second }
// .count() + 1
// val up = (pair.first - side..x step side).takeWhile { treeMap[it] < pair.second }.count() + 1
// val down = (pair.first + side..treeMap.length step side).takeWhile { treeMap[it] < pair.second }
// .count() + 1
println("${x},${y}: ${left * right * up * down}")
left * right * up * down
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 7a13f6500da8cb2240972fbea780c0d8e0fde910 | 4,184 | AdventOfCode2022 | The Unlicense |
src/Day10.kt | niltsiar | 572,887,970 | false | {"Kotlin": 16548} | fun main() {
fun part1(input: List<String>): Int {
val inputs = parseInput(input)
val interestingCycles = listOf(20, 60, 100, 140, 180, 220)
return interestingCycles.sumOf { cycle -> cycle * calculateRegisterValue(inputs, cycle) }
}
fun part2(input: List<String>) {
val inputs = parseInput(input)
val s = StringBuilder()
for (cycle in 1..240) {
val registerValue = calculateRegisterValue(inputs, cycle)
val pixelPosition = (cycle % 40) - 1
if (pixelPosition in (registerValue - 1)..(registerValue + 1)) {
s.append("#")
} else {
s.append(".")
}
}
s.chunked(40)
.forEach { println(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
part2(testInput)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
private fun parseInput(input: List<String>): List<Int> {
return input.flatMap { line ->
val entries = line.split(' ')
when (entries[0]) {
"noop" -> listOf(0)
"addx" -> listOf(0, entries[1].toInt())
else -> emptyList()
}
}
}
private fun calculateRegisterValue(inputs: List<Int>, cycle: Int): Int {
return 1 + inputs.take(cycle).sum() - inputs[cycle - 1]
}
| 0 | Kotlin | 0 | 0 | 766b3e168fc481e4039fc41a90de4283133d3dd5 | 1,458 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | binaryannie | 573,120,071 | false | {"Kotlin": 10437} | private const val DAY = "04"
private const val PART_1_CHECK = 2
private const val PART_2_CHECK = 4
fun inputToRanges(input:List<String>):List<List<Set<Int>>> {
return input
.map {
it
.split(',', '-')
.map { zone -> zone.toInt() }
.chunked(2)
.map { pair -> pair[0].rangeTo(pair[1]).toSet() }
}
}
fun main() {
fun part1(input: List<String>): Int {
val ranges = inputToRanges(input)
val intersects = ranges.map { it[0].intersect(it[1]) }
return ranges.zip(intersects).filter { (pair, intersect) -> pair[0] == intersect || pair[1] == intersect }.size
}
fun part2(input: List<String>): Int {
val ranges = inputToRanges(input)
val intersects = ranges.map { it[0].intersect(it[1]) }
return intersects.filterNot { it.isEmpty() }.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${DAY}_test")
check(part1(testInput).also { println("Part 1 check: $it") } == PART_1_CHECK)
check(part2(testInput).also { println("Part 2 check: $it") } == PART_2_CHECK)
val input = readInput("Day${DAY}")
println("Part 1 solution: ${part1(input)}")
println("Part 2 solution: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 511fc33f9dded71937b6bfb55a675beace84ca22 | 1,319 | advent-of-code-2022 | Apache License 2.0 |
src/day18/Day18.kt | MaxBeauchemin | 573,094,480 | false | {"Kotlin": 60619} | package day18
import readInput
import java.util.*
data class Coordinate(
val x: Int,
val y: Int,
val z: Int
) {
val key = <KEY>"
fun surrounding(): List<Coordinate> {
return listOf(
Coordinate(x = this.x + 1, y = this.y, z = this.z),
Coordinate(x = this.x - 1, y = this.y, z = this.z),
Coordinate(x = this.x, y = this.y + 1, z = this.z),
Coordinate(x = this.x, y = this.y - 1, z = this.z),
Coordinate(x = this.x, y = this.y, z = this.z + 1),
Coordinate(x = this.x, y = this.y, z = this.z - 1)
)
}
}
class Graph {
val nodes: MutableMap<String, Node> = mutableMapOf()
}
data class Node(val coordinate: Coordinate) {
var shortestPath: List<Node> = LinkedList()
var distance = Int.MAX_VALUE
var adjacentNodes: MutableSet<Node> = mutableSetOf()
fun addNeighbor(neighbor: Node) {
this.adjacentNodes.add(neighbor)
neighbor.adjacentNodes.add(this)
}
}
fun calculateShortestPathFromSource(source: Node) {
source.distance = 0
val settledNodes: MutableSet<Node> = HashSet()
val unsettledNodes: MutableSet<Node> = HashSet()
unsettledNodes.add(source)
while (unsettledNodes.size != 0) {
val currentNode: Node = getLowestDistanceNode(unsettledNodes)
unsettledNodes.remove(currentNode)
currentNode.adjacentNodes.forEach { t ->
if (!settledNodes.contains(t)) {
calculateMinimumDistance(t, currentNode)
unsettledNodes.add(t)
}
}
settledNodes.add(currentNode)
}
}
fun getLowestDistanceNode(unsettledNodes: Set<Node>): Node {
var lowestDistanceNode: Node? = null
var lowestDistance = Int.MAX_VALUE
for (node in unsettledNodes) {
val nodeDistance = node.distance
if (nodeDistance < lowestDistance) {
lowestDistance = nodeDistance
lowestDistanceNode = node
}
}
return lowestDistanceNode!!
}
fun calculateMinimumDistance(evaluationNode: Node, sourceNode: Node) {
val sourceDistance = sourceNode.distance
if (sourceDistance < evaluationNode.distance) {
evaluationNode.distance = sourceDistance
val shortestPath = LinkedList(sourceNode.shortestPath)
shortestPath.add(sourceNode)
evaluationNode.shortestPath = shortestPath
}
}
fun parseCoordinates(input: List<String>): List<Coordinate> {
return input.map { row ->
row.split(",").let { tokens ->
Coordinate(tokens[0].toInt(), tokens[1].toInt(), tokens[2].toInt())
}
}
}
fun createGraph(coordinates: Set<Coordinate>): Graph {
return Graph().also { graph ->
coordinates.forEach { coord ->
Node(coord).also { node ->
graph.nodes[coord.key] = node
coord.surrounding().forEach { s ->
graph.nodes[s.key]?.also { neighbor ->
node.addNeighbor(neighbor)
}
}
}
}
}
}
fun totalSurfaceArea(coordinates: Set<Coordinate>): Int {
val occupied = mutableSetOf<String>()
var surfaceArea = 0
coordinates.forEach { coord ->
surfaceArea += 6
coord.surrounding().forEach { s ->
if (occupied.contains(s.key)) surfaceArea -= 2
}
occupied.add(coord.key)
}
return surfaceArea
}
fun main() {
fun part1(input: List<String>): Int {
val coordinates = parseCoordinates(input)
return totalSurfaceArea(coordinates.toSet())
}
fun part2(input: List<String>): Int {
val coordinates = parseCoordinates(input).toSet()
val coordKeys = coordinates.map { it.key }.toSet()
val xMinOutside = coordinates.minOf { it.x } - 1
val xMaxOutside = coordinates.maxOf { it.x } + 1
val yMinOutside = coordinates.minOf { it.y } - 1
val yMaxOutside = coordinates.maxOf { it.y } + 1
val zMinOutside = coordinates.minOf { it.z } - 1
val zMaxOutside = coordinates.maxOf { it.z } + 1
val emptyCoordinates = mutableSetOf<Coordinate>()
for (x in xMinOutside..xMaxOutside) {
for (y in yMinOutside..yMaxOutside) {
for (z in zMinOutside..zMaxOutside) {
Coordinate(x, y, z).also { coord ->
if (!coordKeys.contains(coord.key)) {
emptyCoordinates.add(coord)
}
}
}
}
}
val emptyGraph = createGraph(emptyCoordinates)
val outerNode = emptyGraph.nodes["$xMinOutside $yMinOutside $zMinOutside"]!!
calculateShortestPathFromSource(outerNode)
val enclosedEmptyNodes = emptyGraph.nodes.values.filter { it.distance == Int.MAX_VALUE }
var surfaceArea = totalSurfaceArea(coordinates)
enclosedEmptyNodes.forEach { node ->
node.coordinate.surrounding().forEach { s ->
if (coordKeys.contains(s.key)) surfaceArea -= 1
}
}
return surfaceArea
}
val testInput = readInput("Day18_test")
val input = readInput("Day18")
part1(testInput).also {
println("Part 1 [Test] : $it")
check(it == 64)
}
println("Part 1 [Real] : ${part1(input)}")
part2(testInput).also {
println("Part 2 [Test] : $it")
check(it == 58)
}
println("Part 2 [Real] : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 38018d252183bd6b64095a8c9f2920e900863a79 | 5,535 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | WaatzeG | 573,594,703 | false | {"Kotlin": 7476} | fun main() {
val testInput = readInput("Day03_input")
val solutionPart1 = part1(testInput)
println("Solution part 1: $solutionPart1")
val solutionPart2 = part2(testInput)
println("Solution part 2: $solutionPart2")
}
/**
* Total score of overlap
*/
private fun part1(input: List<String>): Int {
return input.sumOf { ruckSackContents ->
ruckSackContents
.chunkedSequence(ruckSackContents.length / 2)
.map(String::toSet)
.reduce { acc, s -> acc.intersect(s) }
.let { String(it.toCharArray()) }
.let { getValue(it) }
}
}
/**
* Total score of overlap per 3 elves
*/
private fun part2(input: List<String>): Int {
return input
.chunked(3)
.sumOf { group ->
group
.map(String::toSet)
.reduce { acc, s -> acc.intersect(s) }
.let { String(it.toCharArray()) }
.let { getValue(it) }
}
}
private const val lowercaseOffset = 'a'.code - 1
private const val uppercaseOffset = 'A'.code - 1
private fun getValue(priority: String): Int {
return priority.sumOf {
if (it.isLowerCase()) {
it.code - lowercaseOffset
} else {
it.code - uppercaseOffset + 26
}
}
}
| 0 | Kotlin | 0 | 0 | 324a98c51580b86121b6962651f1ba9eaad8f468 | 1,305 | advent_of_code_2022_kotlin | Apache License 2.0 |
src/Day05.kt | mlidal | 572,869,919 | false | {"Kotlin": 20582} | import java.util.*
data class Operation(val number: Int, val start: Int, val end: Int) {
}
fun parseCargo(input: List<String>) : List<Stack<Char>> {
val stacks = input.last().split(Regex(" \\d ")).map { Stack<Char>() }.toList()
input.subList(0, input.size - 1).forEach {
it.chunked(4).forEachIndexed { index, text ->
if (text.isNotBlank()) {
val code = text.trim()[1]
stacks[index].push(code)
}
}
}
return stacks
}
fun parseOperations(input: List<String>) : List<Operation> {
val regex = Regex("move (\\d+) from (\\d+) to (\\d+)")
return input.map {
val groups = regex.findAll(it).toList().first().groups
Operation(groups[1]!!.value.toInt(), groups[2]!!.value.toInt() - 1, groups[3]!!.value.toInt() - 1)
}
}
fun main() {
fun part1(input: List<String>): String {
val operationStart = input.indexOfFirst { it.isEmpty() }
val cargo = input.subList(0, operationStart)
val stacks = parseCargo(cargo)
val operations = parseOperations(input.subList(operationStart + 1, input.size))
operations.forEach { operation ->
for (i in 0 until operation.number) {
val element = stacks[operation.start].first()
stacks[operation.start].remove(element)
stacks[operation.end].insertElementAt(element, 0)
}
}
return stacks.map { it.first() }.joinToString("")
}
fun part2(input: List<String>): String {
val operationStart = input.indexOfFirst { it.isEmpty() }
val cargo = input.subList(0, operationStart)
val stacks = parseCargo(cargo)
val operations = parseOperations(input.subList(operationStart + 1, input.size))
operations.forEach { operation ->
val elements = stacks[operation.start].subList(0, operation.number).toList()
for (i in 0 until operation.number) {
stacks[operation.start].removeAt(0)
}
val reversed = elements.reversed()
reversed.forEach {
stacks[operation.end].insertElementAt(it, 0)
}
}
return stacks.map { it.first() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bea7801ed5398dcf86a82b633a011397a154a53d | 2,553 | AdventOfCode2022 | Apache License 2.0 |
src/Day07.kt | tomoki1207 | 572,815,543 | false | {"Kotlin": 28654} | import Entry.Dir
import Entry.File
sealed class Entry(open val parent: Dir?, open val name: String) {
abstract fun size(): Int
data class File(override val parent: Dir, override val name: String, val size: Int) : Entry(parent, name) {
override fun size() = size
}
data class Dir(override val parent: Dir?, override val name: String) : Entry(parent, name) {
val entries: MutableSet<Entry> = mutableSetOf()
override fun size() = entries.sumOf { it.size() }
}
}
fun main() {
fun execute(commands: List<String>, workingDir: Dir) {
if (commands.isEmpty()) {
return
}
val cmd = commands[0]
// cd
if (cmd.startsWith("$ cd")) {
val rest = commands.drop(1)
return when (val target = cmd.removePrefix("$ cd ")) {
"/" -> execute(rest, workingDir) // for the first line
".." -> execute(rest, workingDir.parent!!)
else -> execute(rest, workingDir.entries.filterIsInstance<Dir>().first { it.name == target })
}
}
// ls
if (cmd.startsWith("$ ls")) {
val prints = commands.drop(1).takeWhile { !it.startsWith("$") }
prints.forEach { print ->
val entry = if (print.startsWith("dir")) {
Dir(workingDir, print.split(" ")[1])
} else {
print.split(" ").let { File(workingDir, it[1], it[0].toInt()) }
}
workingDir.entries.add(entry)
}
return execute(commands.drop(1 + prints.size), workingDir)
}
// other command
throw Error("Not Supported command. $cmd")
}
fun walk(dir: Dir): List<Entry> {
val list = mutableListOf<Entry>(dir)
val (dirs, files) = dir.entries.partition { it is Dir }
dirs.flatMap { d -> walk(d as Dir) }.let { list.addAll(it) }
list.addAll(files)
return list
}
fun part1(input: List<String>): Int {
val root = Dir(null, "/").also { execute(input, it) }
return walk(root).filterIsInstance<Dir>()
.filter { it.size() <= 100_000 }
.sumOf { it.size() }
}
fun part2(input: List<String>): Int {
val root = Dir(null, "/").also { execute(input, it) }
val unused = 70_000_000 - root.size()
return walk(root).filterIsInstance<Dir>()
.filter { it.size() + unused > 30_000_000 }
.minOf { it.size() }
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2ecd45f48d9d2504874f7ff40d7c21975bc074ec | 2,752 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Dec12.kt | karlstjarne | 572,529,215 | false | {"Kotlin": 45095} | object Dec12 {
fun a(): Int {
val matrix = getMatrix(true)
return dijkstrasDistance(matrix)
}
fun b(): Int {
val matrix = getMatrix(false)
return matrix.flatten()
.filter { it.height == 'a'.toInt() }
.map {
it.dist = 0
val dist = dijkstrasDistance(matrix)
matrix.flatten().forEach { node ->
node.dist = Int.MAX_VALUE
node.evaluated = false
}
if (dist < 0) Int.MAX_VALUE else dist // ugh, ugly hack... again...
}
.minOf { it }
}
private fun getMatrix(includeStart: Boolean): List<MutableList<Node>> {
val input = readInput("dec12")
val matrix = List(input.size) { MutableList(input[0].length) { Node(x = 0, y = 0) } }
for (i in input.indices) {
for (j in input[i].indices) {
val startDist = if (includeStart) 0 else Int.MAX_VALUE
val node = when (input[i][j]) {
'S' -> Node(startDist, 'a'.toInt(), Type.START, x = j, y = i)
'E' -> Node(height = 'z'.toInt(), type = Type.END, x = j, y = i)
else -> Node(height = input[i][j].toInt(), x = j, y = i)
}
matrix[i][j] = node
}
}
return matrix
}
private fun dijkstrasDistance(matrix: List<MutableList<Node>>): Int {
while (matrix.any { it.any { node -> !node.evaluated } }) {
// 1. pick node with lowest dist and eval = false
val smallestNode = matrix.flatten().filter { !it.evaluated }.minBy { it.dist }
// 2. update adjacent nodes (and check if reachable)
if (evaluateNeighbours(smallestNode, matrix)) {
break
}
// 3. set eval = true
smallestNode.evaluated = true
}
return matrix.flatten().first { it.type == Type.END }.dist
}
private fun evaluateNeighbours(smallestNode: Node, matrix: List<MutableList<Node>>): Boolean {
for (k in (smallestNode.x - 1)..(smallestNode.x + 1) step 2) {
if (matrix[smallestNode.y].indices.contains(k)) {
val neighbour = matrix[smallestNode.y][k]
if (!neighbour.evaluated && (neighbour.height - smallestNode.height) <= 1) {
neighbour.dist = smallestNode.dist + 1
if (neighbour.type == Type.END) {
return true
}
}
}
}
for (k in (smallestNode.y - 1)..(smallestNode.y + 1) step 2) {
if (matrix.indices.contains(k)) {
val neighbour = matrix[k][smallestNode.x]
if (!neighbour.evaluated && (neighbour.height - smallestNode.height) <= 1) {
neighbour.dist = smallestNode.dist + 1
if (neighbour.type == Type.END) {
return true
}
}
}
}
return false
}
class Node(
var dist: Int = Int.MAX_VALUE,
val height: Int = 0,
val type: Type = Type.NODE,
var evaluated: Boolean = false,
val x: Int,
val y: Int
)
enum class Type {
NODE,
START,
END
}
} | 0 | Kotlin | 0 | 0 | 9220750bf71f39f693d129d170679f3be4328576 | 3,409 | AoC_2022 | Apache License 2.0 |
src/main/kotlin/Day12.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} |
fun main() {
val input = readFileAsList("Day12")
println(Day12.part1(input))
println(Day12.part2(input))
}
typealias Elevation = Char
object Day12 {
fun part1(input: List<String>): Int {
return findBestPath(input, 'S')
}
fun part2(input: List<String>): Int {
return findBestPath(input, 'a')
}
private fun findBestPath(input: List<String>, target: Elevation): Int {
val grid = input.flatMapIndexed { y, row -> row.mapIndexed { x, char -> Position(x, y) to char } }
.toMap()
val startingPoint = grid.entries.first { it.value == 'E' }.key
val distances = grid.keys.associateWith { Int.MAX_VALUE }.toMutableMap()
distances[startingPoint] = 0
val toVisit = mutableListOf(startingPoint)
while (toVisit.isNotEmpty()) {
val current = toVisit.removeFirst()
current.validNeighbours(grid)
.forEach { neighbour ->
val newDistance = distances[current]!! + 1
if (grid[neighbour] == target) return newDistance
if (newDistance < distances[neighbour]!!) {
distances[neighbour] = newDistance
toVisit.add(neighbour)
}
}
}
error("")
}
data class Position(
val x: Int,
val y: Int,
) {
fun validNeighbours(grid: Map<Position, Elevation>) = neighbours().filter { neighbour ->
neighbour in grid && grid[neighbour]!!.value - grid[this]!!.value >= -1
}
private fun neighbours(): List<Position> {
return arrayOf((-1 to 0), (1 to 0), (0 to -1), (0 to 1))
.map { (dx, dy) -> Position(x + dx, y + dy) }
}
}
private val Elevation.value: Int
get() = when (this) {
'S' -> 'a'.code
'E' -> 'z'.code
else -> this.code
}
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 1,968 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | SeanDijk | 575,314,390 | false | {"Kotlin": 29164} | fun main() {
fun splitBackpackInCompartments(input: List<String>) = input.asSequence().map {
val half = it.length / 2
Pair(it.substring(0, half), it.substring(half, it.length))
}
fun score(char: Char): Int {
// Use the char code so we don't have to make a score table.
// A to Z is 65 to 90, so use 'A' as start point to adjust to our scores
val startPoint = 'A'.code
// Determine score as if it were an uppercase char. Add 1 as baseline, since our scoring for 'A' is 1 and not 0
val lowerCaseScore = char.uppercaseChar().code - startPoint + 1
// Adjust the score if the original input was lowercase by adding 26 to it.
return if (char.isLowerCase())
lowerCaseScore
else
lowerCaseScore + 26
}
fun part1(input: List<String>): Int {
return splitBackpackInCompartments(input)
// Find the common letters between the two compartments
.map { (x, y) -> x.toSet().intersect(y.toSet()) }
// score them
.flatMap { letters -> letters.asSequence().map { score(it) } }
// and sum to get the total
.sum()
}
fun part2(input: List<String>): Int {
return input.asSequence()
// Process as groups of 3
.chunked(3) { list ->
list.asSequence()
.map { it.toSet() }
// Find the common item
.reduce { acc, chars -> acc.intersect(chars) }
// Map to the score
.sumOf { score(it) }
}
// Sum all the scores
.sum()
}
val test = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
""".trimIndent().lines()
println(part1(test))
println(part1(readInput("Day03")))
println(part2(test))
println(part2(readInput("Day03")))
}
| 0 | Kotlin | 0 | 0 | 363747c25efb002fe118e362fb0c7fecb02e3708 | 2,050 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1626/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1626
/**
* LeetCode page: [1626. Best Team With No Conflicts](https://leetcode.com/problems/best-team-with-no-conflicts/);
*
* TODO : There is a solution which make use of Fenwick Tree (see [Ref.](https://leetcode.com/problems/best-team-with-no-conflicts/solution/));
*/
class Solution {
/* Algorithm:
* 1. Build a list of player P from scores and ages;
* 2. Sort P by age and break tie by score, both in ascending orders;
* 3. Apply dynamic programming:
* a) Sub-Problem: X(i), the max overall score includes player i for sub-array of P from index 0 to index i.
* Array Dp stores the result of each sub-problem;
* b) Relation: X(i) = maxOf({P[i]+Dp[j] | j = 0 until i and P[j] <= P[i]} U {P[i]});
* c) Topological order: Solve X(i) from 0 to P.lastIndex;
* d) Base Case: Dp[0] = P[0];
* e) Original Problem: Max value in Dp;
* f) Time Complexity: P.size (i.e. number of sub-problems) * P.size (i.e. complexity of each sub-problem),
* thus (P.size)^2;
*/
/* Complexity:
* Time O(N^2) and Space O(N) where N is the number of players, i.e. size of scores and ages;
*/
fun bestTeamScore(scores: IntArray, ages: IntArray): Int {
val sortedPlayers = buildPlayers(scores, ages).apply { sortByAgeThenScore() }
return buildDp(sortedPlayers).max()!!
}
private fun buildPlayers(scores: IntArray, ages: IntArray): MutableList<Player> {
return MutableList(scores.size) { Player(scores[it], ages[it]) }
}
private data class Player(val score: Int, val age: Int)
private fun MutableList<Player>.sortByAgeThenScore() {
val comparator = compareBy<Player>({ it.age }, { it.score })
sortWith(comparator)
}
private fun buildDp(sortedPlayers: List<Player>): IntArray {
val dp = IntArray(sortedPlayers.size)
dp[0] = sortedPlayers[0].score // Base case
for (i in 1 until sortedPlayers.size) {
var subResult = sortedPlayers[i].score
for (j in 0 until i) {
if (sortedPlayers[j].score <= sortedPlayers[i].score) {
subResult = maxOf(subResult, sortedPlayers[i].score + dp[j])
}
}
dp[i] = subResult
}
return dp
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,335 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day05.kt | rweekers | 573,305,041 | false | {"Kotlin": 38747} | fun main() {
fun part1(
stacks: Map<Int, Stack<Char>>,
instructions: List<Instruction>
): String {
instructions
.forEach { instruction ->
repeat((1..instruction.times).count()) {
stacks[instruction.to]?.push(
stacks[instruction.from]?.pop() ?: throw IllegalArgumentException()
)
}
}
return stacks
.map { it.value.pop() }
.fold("") { acc, c -> acc + c }
}
fun part2(
stacks: Map<Int, Stack<Char>>,
instructions: List<Instruction>
): String {
instructions
.forEach { instruction ->
val t = stacks[instruction.from]?.pop(instruction.times) ?: throw IllegalArgumentException()
val s = stacks[instruction.to] ?: throw IllegalArgumentException()
s.push(t)
}
return stacks
.map { it.value.pop() }
.fold("") { acc, c -> acc + c }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
val testSplitIndex = testInput.indexOfFirst { it.isEmpty() }
val testPositionToIndex = determinePositionToIndex(testInput, testSplitIndex)
val testInstructions = determineInstructions(testInput, testSplitIndex)
check(part1(determineStacks(testPositionToIndex, testInput, testSplitIndex), testInstructions) == "CMZ")
check(part2(determineStacks(testPositionToIndex, testInput, testSplitIndex), testInstructions) == "MCD")
val input = readInput("Day05")
val splitIndex = input.indexOfFirst { it.isEmpty() }
val positionToIndex = determinePositionToIndex(input, splitIndex)
val instructions = determineInstructions(input, splitIndex)
println(part1(determineStacks(positionToIndex, input, splitIndex), instructions))
println(part2(determineStacks(positionToIndex, input, splitIndex), instructions))
}
private fun determinePositionToIndex(input: List<String>, splitIndex: Int) =
input.subList(splitIndex - 1, splitIndex)
.first()
.mapIndexed { index, s -> s.toString() to index }
.filter { it.first.trim().isNotEmpty() }
.map { it.first.toInt() to it.second }
private fun determineStacks(
positionToIndex: List<Pair<Int, Int>>,
input: List<String>,
splitIndex: Int
): Map<Int, Stack<Char>> {
val stacks = buildMap<Int, Stack<Char>> {
positionToIndex.forEach {
this[it.first] = Stack()
}
}
input.subList(0, splitIndex - 1)
.reversed()
.forEach {
positionToIndex
.forEach { p ->
if (p.second <= it.length && it[p.second].toString().trim().isNotEmpty()) {
val characterToStore = it[p.second]
stacks[p.first]?.push(characterToStore)
}
}
}
return stacks
}
private fun determineInstructions(input: List<String>, splitIndex: Int) =
input.subList(splitIndex + 1, input.size)
.map { it.split(" ") }
.map { Instruction(it[1].toInt(), it[3].toInt(), it[5].toInt()) }
class Instruction(val times: Int, val from: Int, val to: Int) | 0 | Kotlin | 0 | 1 | 276eae0afbc4fd9da596466e06866ae8a66c1807 | 3,303 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/dynamic_programming/EqualSumArraysWithMinimumNumberOfOperations.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.dynamic_programming
/**
* You are given two arrays of integers nums1 and nums2, possibly of different lengths.
* The values in the arrays are between 1 and 6, inclusive.
*
* In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.
*
* Return the minimum number of operations required
* to make the sum of values in nums1 equal to the sum of values in nums2.
* Return -1 if it is not possible to make the sum of the two arrays equal.
*
* Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
* Output: 3
* Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
* - Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
* - Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
* - Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].
*
* Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
* Output: -1
* Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
*
* Input: nums1 = [6,6], nums2 = [1]
* Output: 3
* Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
* - Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
* - Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
* - Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].
*/
// O(n + m) time | O(1) space
fun minOperations(nums1: IntArray, nums2: IntArray): Int {
if (nums1.size * 6 < nums2.size || nums1.size > nums2.size * 6) return -1
var sum1 = nums1.sum()
val sum2 = nums2.sum()
if (sum1 > sum2) return minOperations(nums2, nums1) // num1.sum() < num2.sum()
val cnt = IntArray(6)
nums1.forEach { cnt[6 - it]++ } // count of increases
nums2.forEach { cnt[it - 1]++ } // count of decreases
var i = 5
var operations = 0
while (sum2 > sum1) {
while (cnt[i] == 0) i--
sum1 += i
cnt[i]--
operations++
}
return operations
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 2,088 | algs4-leprosorium | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.