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/Day06.kt | Fenfax | 573,898,130 | false | {"Kotlin": 30582} | fun main() {
fun findUnique(c: Char, queue: ArrayDeque<Char>, uniqueAmount: Int): Boolean {
queue.add(c)
if (queue.size >= uniqueAmount && queue.distinct().size == queue.size) {
queue.clear()
return false
}
if (queue.size >= uniqueAmount)
queue.removeFirst()
return true
}
fun solve(input: List<String>, uniqueAmount: Int): Int {
val queue: ArrayDeque<Char> = ArrayDeque()
return input.map {
it.toList()
.takeWhile { c -> findUnique(c, queue, uniqueAmount) }
.size + 1
}.first()
}
fun solveShort(input: String, uniqueAmount: Int): Int {
val work = input.toList()
return (1..input.length).toList()
.takeWhile { work.subList(it, it + uniqueAmount).let { list -> list.size != list.distinct().size } }.last() + uniqueAmount + 1
}
fun solveEvenShorter(input: String, uniqueAmount: Int): Int {
return input.windowed(uniqueAmount).takeWhile { it.length != it.toSet().size }.count().plus(uniqueAmount)
}
val input = readInput("Day06")
println(solve(input, 4))
println(solve(input, 14))
println(solveShort(input[0], 4))
println(solveShort(input[0], 14))
println(solveEvenShorter(input[0], 4))
println(solveEvenShorter(input[0], 14))
}
| 0 | Kotlin | 0 | 0 | 28af8fc212c802c35264021ff25005c704c45699 | 1,376 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/InputData.kt | cyprienroche | 241,994,340 | false | null | import java.util.Scanner
class InputData(private val scanner: Scanner) {
private val totalBooks: Int = scanner.nextInt()
private val totalLibraries: Int = scanner.nextInt()
val totalDaysGiven: Day = Day(scanner.nextInt())
private val scores: List<Int> = List(totalBooks) { scanner.nextInt() }
val libraries: Map<Library, List<Book>>
val orderedBookIndexByScore = scores.withIndex().sortedBy { it.value }
private val bookIndexToScore = (0 until totalBooks).zip(scores).toMap()
init {
val libs = mutableMapOf<Library, List<Book>>()
for (i in 0 until totalLibraries) {
val numBooksInLibrary = scanner.nextInt()
val lib = Library(i, Day(scanner.nextInt()), scanner.nextInt(), 0)
val xs = List(numBooksInLibrary) { scanner.nextInt() }
val books = xs.map { Book(it, lib, bookIndexToScore[it]?:0) }
lib.maxScore = books.map { it.score }.max()?:0
libs[lib] = books
}
libraries = libs
}
val libsSorted = libraries.keys.sortedWith(Comparator { o1, o2 ->
if (o2 == null) 1
else o1?.compareTo(o2)?:-1
})
}
data class Library(val id: Int, val signUp: Day, val booksPerDay: Int, var maxScore: Int): Comparable<Library> {
override fun compareTo(other: Library): Int = when {
maxScore != other.maxScore -> -1 * maxScore.compareTo(other.maxScore)
signUp != other.signUp -> signUp.compareTo(other.signUp)
else -> -1 * booksPerDay.compareTo(other.booksPerDay)
}
}
data class Day(val size: Int): Comparable<Day> {
override fun compareTo(other: Day): Int = size.compareTo(other.size)
}
data class Book(val id: Int, val lib: Library, val score: Int)
| 0 | Kotlin | 0 | 0 | 519661283e7ff8509ff5895a89fbbd0ec6df3e1f | 1,754 | GoogleHashCode20 | MIT License |
04/part_two.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
private const val SIZE = 5
fun readInput() : Pair<List<Int>, List<Board>> {
val lines = File("input.txt")
.readLines()
.map { it.split("\n") }
.filter{ it[0] != "" }
val numbers = lines[0][0].split(",").map{ it.toInt() }
val boards = mutableListOf<Board>()
for (i in 1 until lines.size step SIZE) {
boards.add(Board(lines.subList(i, i + SIZE)))
}
return Pair(numbers, boards)
}
class Board(inputBoard: List<List<String>>) {
private val numbersPos = HashMap<Int, Pair<Int, Int>>()
private val filledInRows = IntArray(SIZE){0}
private val filledInCols = IntArray(SIZE){0}
private val crossed = HashSet<Int>()
private var boardSum = 0
private var crossedSum = 0
private var lastCrossedNumber = 0
init {
for ((rowIdx, row) in inputBoard.withIndex()) {
val values = row[0].split(" ")
.filter { it.isNotEmpty() }
.map{ it.toInt() }
for ((colIdx, num) in values.withIndex()) {
numbersPos[num] = Pair(rowIdx, colIdx)
boardSum += num
}
}
}
fun cross(num : Int) {
if (num in numbersPos) {
lastCrossedNumber = num
crossed.add(num)
crossedSum += num
val (rowIdx, colIdx) = numbersPos[num]!!
filledInRows[rowIdx]++
filledInCols[colIdx]++
}
}
fun hasBingo() : Boolean {
for (i in 0 until SIZE) {
if (filledInRows[i] >= SIZE || filledInCols[i] >= SIZE) {
return true
}
}
return false
}
fun getScore(): Int {
return (boardSum - crossedSum) * lastCrossedNumber
}
}
fun lastWinnerBoardScore(numbers : List<Int>, boards: List<Board>) : Int {
val winnerBoardsPoints = mutableListOf<Int>()
val winnerBoardsIdx = HashSet<Int>()
for (num in numbers) {
for ((idx, board) in boards.withIndex()) {
board.cross(num)
if (idx !in winnerBoardsIdx && board.hasBingo()) {
winnerBoardsPoints.add(board.getScore())
winnerBoardsIdx.add(idx)
}
}
}
if (winnerBoardsPoints.size == 0) {
throw Exception("No board won bingo")
}
return winnerBoardsPoints.last()
}
fun solve(numbers : List<Int>, boards : List<Board>) : Int {
return lastWinnerBoardScore(numbers, boards)
}
fun main() {
val (numbers, boards) = readInput()
val ans = solve(numbers, boards)
println(ans)
}
| 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 2,611 | advent-of-code-2021 | MIT License |
src/Day08.kt | shepard8 | 573,449,602 | false | {"Kotlin": 73637} | import kotlin.math.min
fun main() {
fun part1(input: List<List<Char>>): Int {
var visible = 99 + 99 + 97 + 97
(1..97).forEach { y ->
(1..97).forEach { x ->
val cell = input[y][x]
val visibleFromLeft = cell > input[y].take(x).max()
val visibleFromRight = cell > input[y].takeLast(99 - x - 1).max()
val visibleFromTop = cell > input.take(y).maxOf { it[x] }
val visibleFromBottom = cell > input.takeLast(99 - y - 1).maxOf { it[x] }
if (visibleFromLeft || visibleFromRight || visibleFromTop || visibleFromBottom) {
visible += 1
}
}
}
return visible
}
fun part2(input: List<List<Char>>): Int {
var best = 4
(0..98).forEach { y ->
(0..98).forEach { x ->
val cell = input[y][x]
val visibleOnLeft = min(x, input[y].take(x).takeLastWhile { it < cell }.count() + 1)
val visibleOnRight = min(99 - x - 1, input[y].takeLast(99 - x - 1).takeWhile { it < cell }.count() + 1)
val visibleOnTop = min(y, input.take(y).map { it[x] }.takeLastWhile { it < cell }.count() + 1)
val visibleOnBottom = min(99 - y - 1, input.takeLast(99 - y - 1).map { it[x] }.takeWhile { it < cell }.count() + 1)
val scenicScore = visibleOnLeft * visibleOnRight * visibleOnTop * visibleOnBottom
if (scenicScore > best) {
// println("($x, $y) : $visibleOnLeft * $visibleOnRight * $visibleOnTop * $visibleOnBottom = $scenicScore")
best = scenicScore
}
}
}
return best
}
val input = readInput("Day08").map { it.toList() }
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 81382d722718efcffdda9b76df1a4ea4e1491b3c | 1,866 | aoc2022-kotlin | Apache License 2.0 |
src/Day05.kt | wgolyakov | 572,463,468 | false | null | fun main() {
fun parse(input: List<String>): Pair<List<MutableList<Char>>, List<Triple<Int, Int, Int>>> {
val sep = input.indexOf("")
val n = input[sep - 1].substringAfterLast(' ').toInt()
val stacks = List(n) { mutableListOf<Char>() }
for (s in input.subList(0, sep).reversed()) {
for (i in 0 until n) {
val ind = 1 + i * 4
if (s.length <= ind) break
val c = s[ind]
if (c != ' ')
stacks[i].add(c)
}
}
val steps = mutableListOf<Triple<Int, Int, Int>>()
for (s in input.subList(sep + 1, input.size)) {
val (quantity, from, to) = Regex("move (\\d+) from (\\d+) to (\\d+)").matchEntire(s)!!.groupValues
.takeLast(3).map { it.toInt() }
steps.add(Triple(quantity, from - 1, to - 1))
}
return (stacks to steps)
}
fun part1(input: List<String>): String {
val (stacks, steps) = parse(input)
for ((quantity, from, to) in steps)
for (i in 0 until quantity)
stacks[to].add(stacks[from].removeLast())
return stacks.map { it.last() }.toCharArray().concatToString()
}
fun part2(input: List<String>): String {
val (stacks, steps) = parse(input)
for ((quantity, from, to) in steps)
for (i in quantity downTo 1)
stacks[to].add(stacks[from].removeAt(stacks[from].size - i))
return stacks.map { it.last() }.toCharArray().concatToString()
}
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 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 1,501 | advent-of-code-2022 | Apache License 2.0 |
y2021/src/main/kotlin/adventofcode/y2021/Day04.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2021
import adventofcode.io.AdventSolution
object Day04 : AdventSolution(2021, 4, "Giant Squid")
{
override fun solvePartOne(input: String): Int
{
val (drawnNumbers, cards) = parseInput(input)
return drawnNumbers.firstNotNullOf { n ->
cards.forEach { it.crossOff(n) }
cards.find(BingoCard::hasWon)?.let { it.sumUnmarked() * n }
}
}
override fun solvePartTwo(input: String): Int
{
val (drawnNumbers, cards) = parseInput(input)
drawnNumbers.forEach { n ->
cards.forEach { it.crossOff(n) }
cards.singleOrNull()?.takeIf(BingoCard::hasWon)?.let { return it.sumUnmarked() * n }
cards.removeIf(BingoCard::hasWon)
}
throw IllegalStateException()
}
private fun parseInput(input: String): Pair<List<Int>, MutableList<BingoCard>>
{
val chunks = input.split("\n\n")
val numbers = chunks[0].split(',').map(String::toInt)
val bingoCards = chunks.drop(1)
.map {
it.lines().map { line ->
line.chunked(3).map(String::trim).map(String::toInt)
}
}
.map(::BingoCard)
.toMutableList()
return Pair(numbers, bingoCards)
}
private class BingoCard(
val cells: List<Int>,
val crosses: List<MutableList<Boolean>>
)
{
constructor(cells: List<List<Int>>) : this(cells.flatten(), cells.map { MutableList(it.size) { false } })
fun hasWon() = hasFullRow() || hasFullColumn()
private fun hasFullRow() = crosses.any { row -> row.all { it } }
private fun hasFullColumn() = crosses[0].indices.any { iCol -> crosses.all { row -> row[iCol] } }
fun sumUnmarked() = cells.zip(crosses.flatten()) { num, crossed -> num.takeUnless { crossed } }.sumOf { it ?: 0 }
fun crossOff(drawnNumber: Int)
{
val i = cells.indexOf(drawnNumber)
if (i < 0) return
crosses[i / 5][i % 5] = true
}
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,091 | advent-of-code | MIT License |
src/Day04.kt | fouksf | 572,530,146 | false | {"Kotlin": 43124} | import kotlin.streams.toList
fun main() {
fun hasTotalOverlap(a: List<Int>, b: List<Int>): Boolean {
return a[0] >= b[0] && a[1] <= b[1]
}
fun hasOverlap(a: List<Int>, b: List<Int>): Boolean {
return a[0] in b[0]..b[1] ||
a[1] in b[0]..b[1] ||
b[0] in a[0]..a[1] ||
b[1] in a[0]..a[1]
}
fun part1(input: List<String>): Long {
return input.stream()
.map { it.split(",") }
.map { it.stream().map { sections -> sections.split("-") }.toList() }
.map {
it.stream()
.map { section -> section.map { sectionNumber -> sectionNumber.toInt() } }
.toList()
}
.filter { hasTotalOverlap(it[0], it[1]) || hasTotalOverlap(it[1], it[0]) }
.count()
}
fun part2(input: List<String>): Long {
return input.stream()
.map { it.split(",") }
.map { it.stream().map { sections -> sections.split("-") }.toList() }
.map {
it.stream()
.map { section -> section.map { sectionNumber -> sectionNumber.toInt() } }
.toList()
}
.filter { hasOverlap(it[1], it[0]) }
.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val input = readInput("Day04")
// println(part1(testInput))
println(part2(testInput))
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 701bae4d350353e2c49845adcd5087f8f5409307 | 1,584 | advent-of-code-2022 | Apache License 2.0 |
src/day3/Day03.kt | AhmedAshour | 574,898,033 | false | {"Kotlin": 4639} | package day3
import readInput
fun main() {
val input = readInput("src/day3", "input").toString()
val formattedInput = input.trim { it == '[' || it == ']' }.split(",").map { it.trim() }
println(partOne(formattedInput))
println(partTwo(formattedInput))
}
fun partOne(input: List<String>): Int {
var prioritiesSum = 0
input.forEach {
val firstCompartment = it.substring(0, it.length / 2)
val secondCompartment = it.substring(it.length / 2, it.length)
val charsFreq = firstCompartment.toSet()
var duplicateChar = ' '
secondCompartment.forEach { char ->
if (charsFreq.contains(char)) duplicateChar = char
}
val priority = (duplicateChar - 'a') + 1
prioritiesSum += if (priority > 0) priority else (duplicateChar - 'A') + 27
}
return prioritiesSum
}
fun partTwo(input: List<String>): Int {
var prioritiesSum = 0
for (i in input.indices step 3) {
val firstPerson = input[i].toSet()
val secondPerson = input[i + 1].toSet()
input[i + 2].toSet().forEach { char ->
val x = firstPerson.contains(char)
val y = secondPerson.contains(char)
if (x && y) {
val priority = (char - 'a') + 1
prioritiesSum += if (priority > 0) priority else (char - 'A') + 27
}
}
}
return prioritiesSum
}
| 0 | Kotlin | 0 | 0 | 59b9e895649858de0b95fa2e6eef779bc0d8b45c | 1,409 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/solutions/Day7NoSpaceLeftOnDevice.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import utils.Input
import utils.Solution
import utils.popWhile
import java.util.*
// run only this day
fun main() {
Day7NoSpaceLeftOnDevice()
}
class Day7NoSpaceLeftOnDevice : Solution() {
init {
begin("Day 7 - No Space Left On Device")
val input = Input.parseLines(filename = "/d7_commands_output.txt")
val stack = Stack<String>().apply { addAll(input.reversed()) }
val dirMap = getDirMap(stack)
val recursiveDirMap = getSumOfSmallDirectories(dirMap)
val sol1 = recursiveDirMap.values.filter { it <= 100000L }.sum()
output("Sum of Small Directory Sizes", sol1)
val sol2 = findSmallestDirToDelete(recursiveDirMap)
output("Smallest Directory To Delete", sol2)
}
// map out the directories with direct file sizes > 0
private fun getDirMap(stack: Stack<String>): Map<String, Int> {
val dirMap = mutableMapOf<String, Int>()
val currentDir = StringBuilder()
while (stack.size > 0) {
val command = stack.pop().removePrefix("$ ")
if (command.first() == 'c') { // cd
when (val newDir = command.split(" ").last()) {
"/" -> currentDir.clear().append("/")
".." -> {
val lastDirInd = currentDir.dropLast(1).lastIndexOf('/') + 1
currentDir.delete(lastDirInd, currentDir.length)
}
else -> currentDir.append("$newDir/")
}
} else { // ls
val files = stack.popWhile { !it.startsWith('$') }
dirMap[currentDir.toString()] = files
.filter { it.startsWith("d").not() }
.fold(initial = 0) { acc, str -> acc + str.split(" ").first().toInt() }
}
}
return dirMap
}
// add sizes from directory paths and subdirectories
private fun getSumOfSmallDirectories(dirMap: Map<String, Int>): Map<String, Int> {
val recursiveSizeMap = mutableMapOf<String, Int>()
dirMap.entries.forEach { entry ->
var dir = entry.key
while (dir.isNotEmpty()) {
dir = dir.dropLast(1)
val key = dir.ifBlank { "/" } // prevents empty key
recursiveSizeMap.merge(key, entry.value) { a, b -> a + b }
dir = dir.dropLastWhile { it != '/' }
}
}
return recursiveSizeMap
}
// compare sizes to find the single smallest directory to delete that provides enough disk space
private fun findSmallestDirToDelete(dirs: Map<String, Int>): Int {
val totalDiskSpace = 70000000
val neededDiskSpace = 30000000
val usedDiskSpace = dirs["/"]!!
val targetFreeSpace = neededDiskSpace - (totalDiskSpace - usedDiskSpace)
return dirs.values.groupBy { it > targetFreeSpace }[true]!!.min()
}
} | 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 2,965 | advent-of-code-2022 | MIT License |
src/Day11.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | fun main() {
class Monkey(
val itemStack: MutableList<Int>,
val operation: (Long) -> Long,
val divisibilityTest: Int,
val throwTargetTrue: Int,
val throwTargetFalse: Int,
) {
fun throwTargetOf(item: Int) =
if (item % divisibilityTest == 0) throwTargetTrue else throwTargetFalse
}
fun parse(input: List<String>) = input.chunked(7).map { chunk ->
val (_, operator, val2) = chunk[2].substringAfter("new = ").split(" ")
val fn: (Long, Long) -> Long = if (operator == "+") Long::plus else Long::times
val operation = { old: Long ->
val operand = if (val2 == "old") old else val2.toLong()
fn(old, operand)
}
Monkey(
chunk[1].substringAfter(": ").split(", ").mapTo(mutableListOf()) { it.toInt() },
operation,
chunk[3].substringAfter("by ").toInt(),
chunk[4].substringAfter("monkey ").toInt(),
chunk[5].substringAfter("monkey ").toInt(),
)
}
fun part1(input: List<String>): Int {
val monkeys = parse(input)
val inspections = IntArray(monkeys.size)
repeat(20) {
for ((index, monkey) in monkeys.withIndex()) {
while (monkey.itemStack.isNotEmpty()) {
var item = monkey.itemStack.removeFirst()
item = monkey.operation(item.toLong()).toInt()
item /= 3
val target = monkey.throwTargetOf(item)
monkeys[target].itemStack.add(item)
inspections[index]++
}
}
}
inspections.sortDescending()
return inspections[0] * inspections[1]
}
fun part2(input: List<String>): Long {
val monkeys = parse(input)
val inspections = LongArray(monkeys.size)
val commonDivisor = monkeys.fold(1) { acc, monkey -> acc * monkey.divisibilityTest }
repeat(10000) {
for ((index, monkey) in monkeys.withIndex()) {
while (monkey.itemStack.isNotEmpty()) {
val item = monkey.itemStack.removeFirst().toLong()
val newItem = (monkey.operation(item) % commonDivisor).toInt()
check(newItem >= 0) { "value overflew" }
val target = monkey.throwTargetOf(newItem)
monkeys[target].itemStack.add(newItem)
inspections[index]++
}
}
}
inspections.sortDescending()
return inspections[0] * inspections[1]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605)
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 2,921 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/Day9.kt | amitdev | 574,336,754 | false | {"Kotlin": 21489} | import Direction.D
import Direction.L
import Direction.R
import Direction.U
import java.io.File
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
fun main() {
val result = File("inputs/day_9.txt").useLines { tailPositions(it, 9) }
println(result)
}
fun tailPositions(lines: Sequence<String>, tailLength: Int = 1) =
max(lines.fold(listOf(Position(t = (0..tailLength).map { Point(0, 0) }))) { acc, line ->
acc + moves(Move.parse(line), acc.last(), tailLength)
}
.distinctBy { it.t[tailLength - 1] }
.count(), 1)
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
fun diff(other: Point) = Point(other.x - x, other.y - y)
fun follow(diff: Point) = when {
max(abs(diff.x), abs(diff.y)) <= 1 -> this
else -> copy(x = x + diff.x.sign, y = y + diff.y.sign)
}
}
fun moves(move: Move, current: Position, tailLength: Int) =
(1..move.steps).fold(listOf(current)) { positions, _ ->
val previousPos = positions.last()
val h = previousPos.h + next(move.direction)
val t =
(0 until tailLength).fold(listOf(previousPos.t[0].follow(previousPos.t[0].diff(h)))) { acc, i ->
acc + previousPos.t[i + 1].follow(previousPos.t[i + 1].diff(acc.last()))
}
positions + Position(h, t)
}
fun next(direction: Direction) = when (direction) {
R -> Point(0, 1)
U -> Point(-1, 0)
L -> Point(0, -1)
D -> Point(1, 0)
}
data class Position(val h: Point = Point(0, 0), val t: List<Point>)
data class Move(val direction: Direction, val steps: Int) {
companion object {
fun parse(line: String) = Move(toDirection(line), line.split(" ")[1].toInt())
private fun toDirection(line: String) = when (line.split(" ")[0]) {
"R" -> R
"U" -> U
"L" -> L
"D" -> D
else -> throw IllegalArgumentException()
}
}
}
enum class Direction {
R,
U,
L,
D
} | 0 | Kotlin | 0 | 0 | b2cb4ecac94fdbf8f71547465b2d6543710adbb9 | 1,919 | advent_2022 | MIT License |
src/year2023/11/Day11.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`11`
import readInput
import utils.printlnDebug
import kotlin.math.abs
private const val CURRENT_DAY = "11"
private data class Point(
val x: Long,
val y: Long,
)
private fun parseMap(input: List<String>): Set<Point> {
val mutableMap = mutableSetOf<Point>()
input.forEachIndexed { y, line ->
line.split("")
.filter { it.isNotBlank() }
.forEachIndexed { x, value ->
if (value == "#") {
mutableMap.add(Point(x.toLong(), y.toLong()))
}
}
}
return mutableMap
}
private fun expandTheUniverse(
input: Set<Point>,
multiplier: Long = 1,
): Set<Point> {
val maxX = input.maxOf { it.x }
val maxY = input.maxOf { it.y }
var newOutput = input
var countAccumulator = 0
for (x in 0 until maxX) {
if (input.all { it.x != x }) {
countAccumulator++
printlnDebug { "EXPAND X=$x countAccumulator=$countAccumulator" }
newOutput = newOutput.map {
if (it.x >= x + (countAccumulator - 1) * multiplier) {
printlnDebug { "Current Point For x $it" }
it.copy(x = it.x + multiplier)
} else {
it
}
}.toSet()
}
}
var yCountAccumulator = 0
for (y in 0 until maxY) {
if (input.all { it.y != y }) {
yCountAccumulator++
printlnDebug { "EXPAND Y=$y countAccumulator=$yCountAccumulator" }
newOutput = newOutput.map {
if (it.y >= y + (yCountAccumulator - 1) * multiplier) {
it.copy(y = it.y + multiplier)
} else {
it
}
}.toSet()
}
}
return newOutput
}
private fun Point.calculateDistanceTo(point: Point): Long {
val x = x - point.x
val y = y - point.y
return abs(x) + abs(y)
}
private fun countAllUniquePairs(input: Set<Point>): Set<Pair<Point, Point>> {
val resSet = mutableSetOf<Pair<Point, Point>>()
input.forEach { currentInitPoint ->
input.forEach { destInitPoint ->
val pair = currentInitPoint to destInitPoint
val pairInverse = destInitPoint to currentInitPoint
val hasInside = resSet.contains(pair) || resSet.contains(pairInverse)
if (currentInitPoint != destInitPoint && (hasInside.not())) {
resSet.add(currentInitPoint to destInitPoint)
}
}
}
return resSet
}
fun main() {
fun solution(input: List<String>, multiplier: Long): Long {
printlnDebug { "PART 2" }
val setOfGalaxies = parseMap(input)
val output = expandTheUniverse(setOfGalaxies, multiplier)
val pairsSet = countAllUniquePairs(output)
val distances = pairsSet.sumOf { it.first.calculateDistanceTo(it.second) }
printlnDebug { "Pairs: ${pairsSet.size}" }
return distances
}
fun part1(input: List<String>): Long {
return solution(input, 1)
}
fun part2(input: List<String>, multiplier: Long): Long {
return solution(input, multiplier)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 374L)
val part2Test = part2(testInput, 9)
println(part2Test)
check(part2Test == 1030L)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input)
println(part1)
check(part1 == 9608724L)
// Part 2
val part2 = part2(input, 999_999)
println(part2)
check(part2 == 904633799472L)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 3,767 | KotlinAdventOfCode | Apache License 2.0 |
src/com/ajithkumar/aoc2022/Day09.kt | ajithkumar | 574,372,025 | false | {"Kotlin": 21950} | package com.ajithkumar.aoc2022
import com.ajithkumar.utils.*
import kotlin.math.absoluteValue
class Knot(var X: Int, var Y: Int) {
fun moveAlone(direction: String) {
when(direction) {
"L" -> X-=1
"R" -> X+=1
"U" -> Y+=1
"D" -> Y-=1
}
}
fun moveLinked(leadingKnot: Knot): Boolean {
val xDiff = (leadingKnot.X - this.X)
val yDiff = (leadingKnot.Y - this.Y)
if(xDiff.absoluteValue > 1 || yDiff.absoluteValue > 1) {
if(xDiff.absoluteValue == 2 && yDiff.absoluteValue == 2) {
X = leadingKnot.X + (if(xDiff < 0) 1 else -1)
Y = leadingKnot.Y + (if(yDiff < 0) 1 else -1)
} else if(xDiff.absoluteValue == 2) {
X = leadingKnot.X + (if(xDiff < 0) 1 else -1)
Y = if(yDiff.absoluteValue > 0) leadingKnot.Y else this.Y
} else {
X = if(xDiff.absoluteValue > 0) leadingKnot.X else this.X
Y = leadingKnot.Y + (if(yDiff < 0) 1 else -1)
}
return true
}
return false
}
fun currentPosition(): Pair<Int, Int> {
return Pair(X, Y)
}
}
class Rope(private val numberOfKnots: Int) {
private val knots = buildList {
repeat(numberOfKnots) {
add(Knot(0,0))
}
}
val tailVisited = mutableSetOf(knots.last().currentPosition())
fun moveHead(direction: String, steps: Int) {
repeat(steps) {
moveHeadOnce(direction)
tailVisited.add(knots.last().currentPosition())
}
}
private fun moveHeadOnce(direction: String) {
knots[0].moveAlone(direction)
for(i in 1 until knots.size) {
val moved = knots[i].moveLinked(knots[i-1])
if(!moved) break
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val knotsInRope = 2
val moves = input.map { it.split(" ") }
val rope = Rope(knotsInRope)
moves.forEach { (dir, steps) ->
rope.moveHead(dir, steps.toInt())
}
return rope.tailVisited.size
}
fun part2(input: List<String>): Int {
val knotsInRope = 10
val moves = input.map { it.split(" ") }
val rope = Rope(knotsInRope)
moves.forEach { (dir, steps) ->
rope.moveHead(dir, steps.toInt())
}
return rope.tailVisited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
println(part1(testInput))
val testInput2 = readInput("Day09_test2")
println(part2(testInput2))
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f95b8d1c3c8a67576eb76058a1df5b78af47a29c | 2,774 | advent-of-code-kotlin-template | Apache License 2.0 |
src/day5/main.kt | DonaldLika | 434,183,449 | false | {"Kotlin": 11805} | package day5
import readLines
val NUMBER_EXTRACTOR = "\\d+".toRegex()
fun main() {
fun part1(segments: List<Segment>): Int {
val filteredLines = segments.filter { it.from.x == it.to.x || it.from.y == it.to.y }
return filteredLines.calculateIntersections()
}
fun part2(segments: List<Segment>): Int {
return segments.calculateIntersections()
}
val testInput = readSegments("day5/test")
assert(part1(testInput) == 5)
assert(part2(testInput) == 12)
val input = readSegments("day5/input")
val part1Result = part1(input)
val part2Result = part2(input)
println("Result of part 1= $part1Result")
println("Result of part 2= $part2Result")
}
fun readSegments(fileName: String): List<Segment> {
return readLines(fileName)
.map { line ->
NUMBER_EXTRACTOR.findAll(line).map { it.value.toInt() }.toList()
}.map {
Segment(Point(it[0], it[1]), Point(it[2], it[3]))
}
}
fun List<Segment>.calculateIntersections() = this
.flatMap { it.coveredPoints() }
.groupingBy { it }.eachCount()
.count { it.value >= 2 }
data class Segment(val from: Point, val to: Point) {
private fun absoluteSegment(): Segment {
if (from.x < to.x) return this
if (from.x == to.x && from.y < to.y) return this
return Segment(to, from)
}
private fun withHorizontalPosition(x: Int) = Point(x, from.y)
private fun withVerticalPosition(y: Int) = Point(from.x, y)
fun coveredPoints(): List<Point> = with(absoluteSegment()) {
if (from.x == to.x) {
return (from.y..to.y).map { withVerticalPosition(it) }
}
if (from.y == to.y) {
return (from.x..to.x).map { withHorizontalPosition(it) }
}
// calculate diagonal line
val dx = to.x - from.x
val dy = to.y - from.y
val direction = dy.compareTo(0)
return (0..dx).map { delta ->
Point(from.x + delta, from.y + direction * delta)
}
}
}
data class Point(val x: Int, val y: Int) | 0 | Kotlin | 0 | 0 | b288f16ee862c0a685a3f9e4db34d71b16c3e457 | 2,086 | advent-of-code-2021 | MIT License |
src/Day09.kt | purdyk | 572,817,231 | false | {"Kotlin": 19066} | data class Pos(val x: Int = 0, val y: Int = 0) {
fun touches(other: Pos): Boolean {
return kotlin.math.abs(this.x - other.x) < 2 &&
kotlin.math.abs(this.y - other.y) < 2
}
}
fun move(move: String, thing: Pos): List<Pos> {
val (dir, cnt) = move.split(" ")
return (0 until cnt.toInt()).runningFold(thing) { acc, _ ->
when (dir) {
"U" -> acc.copy(y = acc.y - 1)
"D" -> acc.copy(y = acc.y + 1)
"L" -> acc.copy(x = acc.x - 1)
"R" -> acc.copy(x = acc.x + 1)
else -> acc
}
}.drop(1)
}
fun Pos.chase(other: Pos): Pos {
return if (!other.touches(this)) {
Pos(x = this.x + (other.x - this.x).coerceIn(-1, 1),
y = this.y + (other.y - this.y).coerceIn(-1, 1))
} else this
}
fun printBoard(board: Set<Pos>) {
val minX = board.minOf { it.x }
val maxX = board.maxOf { it.x }
val minY = board.minOf { it.y }
val maxY = board.maxOf { it.y }
println((minY .. maxY).joinToString("\n") { y ->
(minX .. maxX).joinToString("") { x ->
if (Pos(x, y) in board) { "#" } else { "."}
}
})
}
fun main() {
fun part1(input: List<String>): String {
var tail = Pos()
val headPath = input.fold(listOf(Pos())) { acc, move ->
acc + move(move, acc.last())
}
val tailPositions = mutableSetOf(tail)
headPath.zipWithNext { prev, cur ->
tail = tail.chase(cur)
tailPositions.add(tail)
}
// printBoard(tailPositions)
return tailPositions.size.toString()
}
fun part2(input: List<String>): String {
val headPath = input.fold(listOf(Pos())) { acc, move ->
acc + move(move, acc.last())
}
var tail = List(9) { Pos() }
val tailPositions = mutableSetOf(tail.last())
headPath.zipWithNext { hprev, hcur ->
tail = tail.runningFold(hprev to hcur) { (prev, cur), me ->
me to me.chase(cur)
}.map { it.second }.drop(1)
// printBoard(tail.toSet())
// println("===")
tailPositions.add(tail.last())
}
// printBoard(tailPositions)
return tailPositions.size.toString()
}
val day = "09"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test").split("\n")
println("Test: ")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == "88")
check(part2(testInput) == "36")
val input = readInput("Day${day}").split("\n")
println("\nProblem: ")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 02ac9118326b1deec7dcfbcc59db8c268d9df096 | 2,733 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2020/Day21.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2020
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
import com.chriswk.aoc.util.reportableString
class Day21: AdventDay(2020, 21) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day21()
report {
day.part1()
}
reportableString {
day.part2()
}
}
}
fun reduce(input: Map<String, List<Allergen>>): Map<String, Set<String>> {
return input.entries.map {
val reducedPossibles = it.value.drop(1).fold(it.value.first().possibles) { previous, allergen ->
previous.intersect(allergen.possibles)
}
it.key to reducedPossibles
}.toMap()
}
fun assignIngredientToAllergen(allergens: Map<String, Set<String>>): Map<String, String> {
val ingredientToAllergen = mutableMapOf<String, String>()
val allergensMutable = allergens.toMutableMap()
while(allergensMutable.isNotEmpty()) {
allergensMutable.entries.sortedBy { it.value.size }.forEach { e ->
val remainingKeys = e.value - ingredientToAllergen.keys
if (remainingKeys.size == 1) {
ingredientToAllergen[remainingKeys.first()] = e.key
allergensMutable.remove(e.key)
}
}
}
return ingredientToAllergen
}
fun parse(input: List<String>): Map<String, List<Allergen>> {
return input.flatMap { line ->
val ingredients = line.substringBefore("(").trim().split(" ").toSet()
val names = line.substringAfter("contains ").substringBefore(")").split(", ")
names.map { Allergen(it, ingredients) }
}.groupBy { it.name }
}
fun countAppearences(dangerousIngredients: Set<String>, recipe: List<String>): Int {
return recipe.count { it !in dangerousIngredients }
}
fun answerPart1(input: List<String>, allergens: Map<String, String>): Int {
return input.map { line ->
line.substringBefore("(").trim().split(" ")
}.sumOf { countAppearences(allergens.keys, it) }
}
fun answerPart2(allergens: Map<String, String>): String {
return allergens.entries.sortedBy { it.value }.joinToString(separator = ",") { it.key }
}
fun part1(): Int {
val allergens = parse(inputAsLines)
val candidates = reduce(allergens)
val correctMap = assignIngredientToAllergen(candidates)
return answerPart1(inputAsLines, correctMap)
}
fun part2(): String {
val allergens = parse(inputAsLines)
val candidates = reduce(allergens)
val correctMap = assignIngredientToAllergen(candidates)
return answerPart2(correctMap)
}
data class Allergen(val name: String, val possibles: Set<String>)
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,929 | adventofcode | MIT License |
src/main/kotlin/com/github/michaelbull/advent2021/day8/Entry.kt | michaelbull | 433,565,311 | false | {"Kotlin": 162839} | package com.github.michaelbull.advent2021.day8
private val DIGITS = 0..9
private val SEGMENTS = 'a'..'g'
private val REGEX = "([${SEGMENTS.first}-${SEGMENTS.last}]+)".toRegex()
fun String.toEntry(): Entry {
val results = requireNotNull(REGEX.findAll(this)) {
"$this must match $REGEX"
}
val values = results.map { it.groupValues[1] }.toList()
return Entry(
signalPatterns = (0 until 10).map(values::get),
outputValueDigits = (10 until 14).map(values::get)
)
}
data class Entry(
val signalPatterns: List<String>,
val outputValueDigits: List<String>
) {
val distinctDigitCount: Int
get() = outputValueDigits.count { digit ->
digit.length in DISTINCT_SEGMENT_SIZES
}
val outputValue: Int
get() = outputValueDigits.fold(0) { acc, digit ->
(10 * acc) + valueOf(digit)
}
private val patternsByDigit: Map<Int, Set<Char>> by lazy {
DIGITS.associateWith { digit ->
val segmentSize = SEGMENT_SIZES_BY_DIGIT[digit]
val pattern = signalPatterns.find { it.length == segmentSize }
pattern?.toSet() ?: emptySet()
}
}
private fun valueOf(digit: String): Int {
return when (val segmentSize = digit.length) {
5 -> when {
digit.intersectingChars(1) == 2 -> 3
digit.intersectingChars(4) == 2 -> 2
else -> 5
}
6 -> when {
digit.intersectingChars(4) == 4 -> 9
digit.intersectingChars(1) == 2 -> 0
else -> 6
}
else -> DIGITS_BY_DISTINCT_SEGMENT_SIZE[segmentSize] ?: throw IllegalArgumentException()
}
}
private fun String.intersectingChars(digit: Int): Int {
val pattern = patternsByDigit.getValue(digit)
return toSet().intersect(pattern).size
}
private companion object {
private val SEGMENTS_BY_DIGIT = mapOf(
0 to setOf('a', 'b', 'c', 'e', 'f', 'g'),
1 to setOf('c', 'f'),
2 to setOf('a', 'c', 'd', 'e', 'g'),
3 to setOf('a', 'c', 'd', 'f', 'g'),
4 to setOf('b', 'c', 'd', 'f'),
5 to setOf('a', 'b', 'd', 'f', 'g'),
6 to setOf('a', 'b', 'd', 'e', 'f', 'g'),
7 to setOf('a', 'c', 'f'),
8 to setOf('a', 'b', 'c', 'd', 'e', 'f', 'g'),
9 to setOf('a', 'b', 'c', 'd', 'f', 'g')
)
private val SEGMENT_SIZES_BY_DIGIT = DIGITS.associateWith { digit ->
SEGMENTS_BY_DIGIT.getValue(digit).size
}
private val DISTINCT_SEGMENT_SIZES_BY_DIGIT = SEGMENT_SIZES_BY_DIGIT.filter { a ->
SEGMENT_SIZES_BY_DIGIT.count { b ->
a.value == b.value
} == 1
}
private fun <K, V> Map<K, V>.reversed(): Map<V, K> {
return entries.associateBy(Map.Entry<K, V>::value, Map.Entry<K, V>::key)
}
private val DISTINCT_SEGMENT_SIZES = DISTINCT_SEGMENT_SIZES_BY_DIGIT.values
private val DIGITS_BY_DISTINCT_SEGMENT_SIZE = DISTINCT_SEGMENT_SIZES_BY_DIGIT.reversed()
}
}
| 0 | Kotlin | 0 | 4 | 7cec2ac03705da007f227306ceb0e87f302e2e54 | 3,178 | advent-2021 | ISC License |
src/Day04.kt | juliantoledo | 570,579,626 | false | {"Kotlin": 34375} | fun main() {
fun pairsList(input: List<String>): List<Pair<Pair<Int,Int>, Pair<Int,Int>>> {
var pairs = mutableListOf<Pair<Pair<Int,Int>, Pair<Int,Int>>>()
input.forEach { line ->
line.splitTo(",") { a, b ->
a.splitTo("-") { i, j ->
b.splitTo("-") { k, l ->
pairs.add(
Pair(
Pair(i.toInt(), j.toInt()),
Pair(k.toInt(), l.toInt())
)
)
}
}
}
}
return pairs
}
fun part1(pairsList: List<Pair<Pair<Int,Int>, Pair<Int,Int>>>): Int {
var totalPairs = 0
pairsList.forEach { pair->
if (pair.first.first >= pair.second.first) {
if (pair.first.second <= pair.second.second) {
totalPairs += 1
return@forEach
}
}
if (pair.second.first >= pair.first.first) {
if (pair.second.second <= pair.first.second) totalPairs += 1
}
}
return totalPairs
}
fun part2(pairsList: List<Pair<Pair<Int,Int>, Pair<Int,Int>>>): Int {
var totalPairs = 0
pairsList.forEach { pair->
if (pair.second.first >= pair.first.first &&
pair.second.first <= pair.first.second) {
totalPairs += 1
return@forEach
}
if (pair.first.first >= pair.second.first &&
pair.first.first <= pair.second.second) {
totalPairs += 1
}
}
return totalPairs
}
var input = readInput("Day04_test")
var items = pairsList(input)
println(part1(items))
input = readInput("Day04_input")
items = pairsList(input)
println( part1(items))
println( part2(items))
}
| 0 | Kotlin | 0 | 0 | 0b9af1c79b4ef14c64e9a949508af53358335f43 | 1,968 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day05.kt | rossilor95 | 573,177,479 | false | {"Kotlin": 8837} | data class ProcedureStep(val cratesToMove: Int, val originStack: Int, val destinationStack: Int) {
constructor(cratesToMove: String, originStack: String, destinationStack: String) : this(
cratesToMove.toInt(), originStack.toInt() - 1, destinationStack.toInt() - 1
)
}
fun main() {
fun numberOfStacks(input: List<String>) = input.first {
it.startsWith(" 1")
}.split(" ").maxOf { stackIndex ->
stackIndex.trim().toInt()
}
fun parseStacks(input: List<String>): List<ArrayDeque<Char>> {
val stacks = List(numberOfStacks(input)) { ArrayDeque<Char>() }
input.takeWhile {
it.contains('[')
}.map { line -> line.chunked(4) }.forEach { chunks ->
chunks.withIndex().forEach { (index, chunk) ->
if (chunk[1].isLetter()) stacks[index].add(chunk[1])
}
}
return stacks
}
fun parseProcedure(input: List<String>): List<ProcedureStep> = input.dropWhile {
!it.startsWith("move")
}.map { row ->
row.split(" ").let { parts ->
ProcedureStep(parts[1], parts[3], parts[5])
}
}
fun List<ArrayDeque<Char>>.moveCrates(procedureStep: ProcedureStep, retainOrder: Boolean = false) {
val cratesToMove = this[procedureStep.originStack].take(procedureStep.cratesToMove)
repeat(procedureStep.cratesToMove) { this[procedureStep.originStack].removeFirst() }
this[procedureStep.destinationStack].addAll(0, if (retainOrder) cratesToMove else cratesToMove.reversed())
}
fun List<ArrayDeque<Char>>.getCratesOnTop(): String = this.map { it.first() }.joinToString(separator = "")
fun part1(input: List<String>): String {
val stacks: List<ArrayDeque<Char>> = parseStacks(input)
val procedure: List<ProcedureStep> = parseProcedure(input)
for (procedureStep in procedure) {
stacks.moveCrates(procedureStep)
}
return stacks.getCratesOnTop()
}
fun part2(input: List<String>): String {
val stacks: List<ArrayDeque<Char>> = parseStacks(input)
val procedure: List<ProcedureStep> = parseProcedure(input)
for (procedureStep in procedure) {
stacks.moveCrates(procedureStep, retainOrder = true)
}
return stacks.getCratesOnTop()
}
val testInput = readInput("Day05_test")
val input = readInput("Day05")
check(part1(testInput) == "CMZ")
println("Part 1 Answer: ${part1(input)}")
check(part2(testInput) == "MCD")
println("Part 2 Answer: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 0ed98d0ab5f44b2ccfc625ef091e736c5c748ff0 | 2,582 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day09/day9.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day09
import biz.koziolek.adventofcode.findInput
fun main() {
val inputFile = findInput(object {})
val report = parseOasisReport(inputFile.bufferedReader().readLines())
println("Sum of extrapolated values: ${report.readings.sumOf { predictNextValue(it) }}")
println("Sum of extrapolated values backwards: ${report.readings.sumOf { predictPreviousValue(it) }}")
}
data class OasisReport(val readings: List<List<Int>>)
fun parseOasisReport(lines: Iterable<String>): OasisReport =
lines
.map { line ->
line.split(" ").map { it.toInt() }
}
.let { OasisReport(it) }
fun predictNextValue(history: List<Int>): Int =
extrapolateHistory(history).first().last()
fun predictPreviousValue(history: List<Int>): Int =
extrapolateHistoryBackwards(history).first().first()
internal fun extrapolateHistory(history: List<Int>): List<List<Int>> {
val reduced = reduceHistory(history)
val lastRowExtended = reduced.last() + 0
return reduced
.dropLast(1)
.foldRight(listOf(lastRowExtended)) { ints, acc ->
val newRow = ints + (ints.last() + acc.first().last())
listOf(newRow) + acc
}
}
internal fun extrapolateHistoryBackwards(history: List<Int>): List<List<Int>> {
val reduced = reduceHistory(history)
val lastRowExtended = listOf(0) + reduced.last()
return reduced
.dropLast(1)
.foldRight(listOf(lastRowExtended)) { ints, acc ->
val newRow = listOf(ints.first() - acc.first().first()) + ints
listOf(newRow) + acc
}
}
internal fun reduceHistory(history: List<Int>): List<List<Int>> =
buildList {
var current = history
add(current)
while (current.any { it != 0 }) {
current = current.zipWithNext { a, b -> b - a }
add(current)
}
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 1,910 | advent-of-code | MIT License |
day2/src/main/kotlin/Main.kt | joshuabrandes | 726,066,005 | false | {"Kotlin": 47373} | import java.io.File
const val NUMBER_OF_RED = 12
const val NUMBER_OF_GREEN = 13
const val NUMBER_OF_BLUE = 14
fun main() {
println("------ Advent of Code 2023 - Day 2 -----")
val gamesFromInput = getPuzzleInput()
.map { Game.fromString(it) }
val possibleGames = gamesFromInput
.filter { it.isGamePossible() }
println("Task 1: Sum of possible gameIds: ${possibleGames.sumOf { it.gameId }}")
val minPowerForGames = gamesFromInput
.map { MinimumColorCount.fromGame(it) }
.sumOf { it.getPower() }
println("Task 2: Minimum power for all games: $minPowerForGames")
println("----------------------------------------")
}
fun getPuzzleInput(): List<String> {
val fileUrl = ClassLoader.getSystemResource("day2-input.txt")
return File(fileUrl.toURI()).readLines()
}
data class Game(val gameId: Int, val turns: List<Turn>) {
fun isGamePossible(): Boolean {
for (turn in turns) {
if (!turn.isTurnPossible()) {
return false
}
}
return true
}
override fun toString(): String {
return "Game $gameId: ${turns.joinToString("; ")}"
}
companion object {
fun fromString(input: String): Game {
val infos = input.split(": ")
.map { it.trim() }
assert(infos.size == 2) { "Invalid input: $input" }
// get gameId after "Game "
val gameId = infos[0].substring(5).toInt()
val turns = infos[1].split("; ")
.map { it.trim() }
.map { Turn.fromString(it) }
return Game(gameId, turns)
}
}
}
data class Turn(val turnResult: Map<Color, Int>) {
override fun toString(): String {
return turnResult.map { "${it.value} ${it.key.color}" }.joinToString(", ")
}
fun isTurnPossible(): Boolean {
val red = turnResult[Color.RED] ?: 0
val green = turnResult[Color.GREEN] ?: 0
val blue = turnResult[Color.BLUE] ?: 0
return red <= NUMBER_OF_RED
&& green <= NUMBER_OF_GREEN
&& blue <= NUMBER_OF_BLUE
}
companion object {
fun fromString(inputString: String): Turn {
val infoMap = inputString.split(", ")
.map { it.trim() }
.map {
val parts = it.split(" ")
assert(parts.size == 2) { "Invalid input: $inputString" }
return@map parts
}
.associate { Color.fromString(it[1]) to it[0].toInt() }
return Turn(infoMap)
}
}
}
data class MinimumColorCount(val red: Int, val green: Int, val blue: Int) {
fun getPower(): Int {
return red * green * blue
}
companion object {
fun fromGame(game: Game): MinimumColorCount {
var red = 0
var green = 0
var blue = 0
for (turn in game.turns) {
val redTurn = turn.turnResult[Color.RED] ?: 0
val greenTurn = turn.turnResult[Color.GREEN] ?: 0
val blueTurn = turn.turnResult[Color.BLUE] ?: 0
if (redTurn > red) {
red = redTurn
}
if (greenTurn > green) {
green = greenTurn
}
if (blueTurn > blue) {
blue = blueTurn
}
}
return MinimumColorCount(red, green, blue)
}
}
}
enum class Color(val color: String) {
RED("red"),
GREEN("green"),
BLUE("blue");
companion object {
fun fromString(color: String): Color {
return when (color) {
"red" -> RED
"green" -> GREEN
"blue" -> BLUE
else -> throw IllegalArgumentException("Invalid color: $color")
}
}
}
}
| 0 | Kotlin | 0 | 1 | de51fd9222f5438efe9a2c45e5edcb88fd9f2232 | 3,946 | aoc-2023-kotlin | The Unlicense |
src/main/kotlin/advent/of/code/day18/Solution.kt | brunorene | 160,263,437 | false | null | package advent.of.code.day18
import advent.of.code.day18.Acre.*
import java.io.File
data class Position(val x: Int, val y: Int) : Comparable<Position> {
override fun compareTo(other: Position): Int {
return compareBy<Position>({ it.y }, { it.x }).compare(this, other)
}
override fun toString(): String {
return "(${x.toString().padStart(3, ' ')},${y.toString().padStart(3, ' ')})"
}
fun up() = copy(y = y - 1)
fun down() = copy(y = y + 1)
fun left() = copy(x = x - 1)
fun right() = copy(x = x + 1)
fun upLeft() = copy(x = x - 1, y = y - 1)
fun upRight() = copy(x = x + 1, y = y - 1)
fun downLeft() = copy(y = y + 1, x = x - 1)
fun downRight() = copy(y = y + 1, x = x + 1)
fun around() = listOf(up(), down(), left(), right(), upLeft(), upRight(), downLeft(), downRight())
}
val input = File("day18.txt")
enum class Acre(val symbol: Char) {
TREES('|'), LUMBERYARD('#'), OPEN('.')
}
class ForestField(input: File) {
var acres = mapOf<Position, Acre>()
init {
var y = 0
acres = input.readLines().flatMap { line ->
var x = 0
line.mapNotNull { symbol ->
val pos = Position(x++, y)
when (symbol) {
TREES.symbol -> Pair(pos, TREES)
LUMBERYARD.symbol -> Pair(pos, LUMBERYARD)
else -> null
}
}.apply { y++ }
}.toMap()
}
fun around(position: Position) = position.around().mapNotNull { acres[it] }
fun plots() = (0..(acres.map { it.key.y }.max() ?: 0)).flatMap { y ->
(0..(acres.map { it.key.x }.max() ?: 0)).map { x ->
val pos = Position(x, y)
Pair(pos, acres[pos] ?: OPEN)
}
}
override fun toString(): String {
var output = ""
for (y in (0..(acres.map { it.key.y }.max() ?: 0))) {
for (x in (0..(acres.map { it.key.x }.max() ?: 0)))
output += (acres[Position(x, y)] ?: OPEN).symbol
output += '\n'
}
return output
}
}
// 1000000000
fun part1(): Int {
val forest = ForestField(input)
println((1..1000000000).map { idx ->
forest.acres = forest.plots().mapNotNull {
when (it.second) {
TREES -> {
if (forest.around(it.first).count { near -> near == LUMBERYARD } >= 3)
Pair(it.first, LUMBERYARD)
else
it
}
LUMBERYARD -> {
if (forest.around(it.first).count { near -> near == LUMBERYARD } >= 1 &&
forest.around(it.first).count { near -> near == TREES } >= 1)
Pair(it.first, LUMBERYARD)
else
null
}
else -> {
if (forest.around(it.first).count { near -> near == TREES } >= 3)
Pair(it.first, TREES)
else
it
}
}
}.toMap()
val wood = forest.plots().count { it.second == TREES }
val yards = forest.plots().count { it.second == LUMBERYARD }
if (((idx - 1000) % 7000 in listOf(6999, 0, 1))) println("$idx -> $wood -> $yards -> ${wood * yards}")
idx to wood * yards
}.last())
return forest.plots().count { it.second == LUMBERYARD } * forest.plots().count { it.second == TREES }
} | 0 | Kotlin | 0 | 0 | 0cb6814b91038a1ab99c276a33bf248157a88939 | 3,523 | advent_of_code_2018 | The Unlicense |
src/main/kotlin/g2701_2800/s2736_maximum_sum_queries/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2701_2800.s2736_maximum_sum_queries
// #Hard #Array #Sorting #Binary_Search #Stack #Monotonic_Stack #Segment_Tree #Binary_Indexed_Tree
// #2023_08_05_Time_1043_ms_(100.00%)_Space_126.2_MB_(9.09%)
import java.util.TreeMap
class Solution {
private fun update(map: TreeMap<Int, Int>, num: Int, sum: Int) {
var entry = map.floorEntry(num)
while (entry != null && entry.value <= sum) {
map.remove(entry.key)
val x = entry.key
entry = map.floorEntry(x)
}
entry = map.ceilingEntry(num)
if (entry == null || entry.value < sum) map.put(num, sum)
}
private fun queryVal(map: TreeMap<Int, Int>, num: Int): Int {
val (_, value) = map.ceilingEntry(num) ?: return -1
return value
}
fun maximumSumQueries(nums1: IntArray, nums2: IntArray, queries: Array<IntArray>): IntArray {
val n = nums1.size
val m = queries.size
val v: MutableList<IntArray> = ArrayList()
for (i in 0 until n) {
v.add(intArrayOf(nums1[i], nums2[i]))
}
v.sortWith(
Comparator { a: IntArray, b: IntArray ->
a[0] - b[0]
}
)
val ind: MutableList<Int> = ArrayList()
for (i in 0 until m) ind.add(i)
ind.sortWith(Comparator { a: Int?, b: Int? -> queries[b!!][0] - queries[a!!][0] })
val values = TreeMap<Int, Int>()
var j = n - 1
val ans = IntArray(m)
for (i in ind) {
val a = queries[i][0]
val b = queries[i][1]
while (j >= 0 && v[j][0] >= a) {
update(values, v[j][1], v[j][0] + v[j][1])
j--
}
ans[i] = queryVal(values, b)
}
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,792 | LeetCode-in-Kotlin | MIT License |
src/day3/Day3.kt | bartoszm | 572,719,007 | false | {"Kotlin": 39186} | package day3
import readInput
fun main() {
val testInput = parse(readInput("day03/test"))
val input = parse(readInput("day03/input"))
println(solve1(testInput))
println(solve1(input))
println(solve2(testInput))
println(solve2(input))
}
fun position(c: Char): Int {
return if (c.isLowerCase()) {
c.code - 'a'.code + 1
} else {
c.code - 'A'.code + 27
}
}
fun solve1(input: List<CharArray>): Int {
fun translate(a: CharArray): Pair<List<Char>, List<Char>> {
return a.toList().subList(0, a.size / 2) to a.toList().subList(a.size / 2, a.size)
}
return input
.map { translate(it) }.sumOf { (l, r) ->
val common = l.toSet() intersect r.toSet()
require(common.size == 1)
position(common.first())
}
}
fun solve2(input: List<CharArray>): Int {
return input.chunked(3)
.map {
it.map { x -> x.toSet() }
.reduce { acc, v -> acc intersect v }
.also { v -> require(v.size == 1) }
}
.sumOf { v -> position(v.first()) }
}
fun parse(input: List<String>): List<CharArray> {
return input
.map { it.toCharArray() }
}
| 0 | Kotlin | 0 | 0 | f1ac6838de23beb71a5636976d6c157a5be344ac | 1,214 | aoc-2022 | Apache License 2.0 |
archive/2022/Day14.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 24
private const val EXPECTED_2 = 93
private class Day14(isTest: Boolean) : Solver(isTest) {
private val dirs = listOf(0 to 1, -1 to 1, 1 to 1)
private fun parseField(): Pair<List<BooleanArray>, Int> {
val field = (0..1000).map { BooleanArray(1000) { false } }
var maxY = 0
for (line in readAsLines()) {
line.split(" -> ").map { pt -> pt.split(",").let { it[0].toInt() to it[1].toInt() } }.windowed(2).forEach { (a, b) ->
drawLine(a, b, field)
maxY = maxOf(a.second, b.second, maxY)
}
}
return Pair(field, maxY)
}
private fun drawLine(a: Pair<Int, Int>, b: Pair<Int, Int>, field: List<BooleanArray>) {
if (a.first == b.first) {
for (y in minOf(a.second, b.second)..maxOf(a.second, b.second)) {
field[a.first][y] = true
}
} else {
for (x in minOf(a.first, b.first)..maxOf(a.first, b.first)) {
field[x][a.second] = true
}
}
}
private fun simulate(field: List<BooleanArray>, maxY: Int): Int {
var n = 0
while (!field[500][0]) {
var pos = 500 to 0
while (pos.second < maxY) {
pos = dirs.map { (dx, dy) -> pos.first + dx to pos.second + dy }.firstOrNull { !field[it.first][it.second] }
?: break
}
if (pos.second >= maxY) {
break
}
field[pos.first][pos.second] = true
n++
}
return n
}
fun part1(): Any {
val (field, maxY) = parseField()
return simulate(field, maxY)
}
fun part2(): Any {
val (field, maxY) = parseField()
drawLine(0 to maxY + 2, 999 to maxY + 2, field)
return simulate(field, maxY + 2)
}
}
fun main() {
val testInstance = Day14(true)
val instance = Day14(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 2,270 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | josemarcilio | 572,290,152 | false | {"Kotlin": 5535} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val (elf, me) = it.split(" ")
mapOf(
"A" to mapOf("X" to 4, "Y" to 8, "Z" to 3),
"B" to mapOf("X" to 1, "Y" to 5, "Z" to 9),
"C" to mapOf("X" to 7, "Y" to 2, "Z" to 6)
)[elf]!![me]!!
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val (elf, me) = it.split(" ")
mapOf(
"A" to mapOf("X" to 3, "Y" to 4, "Z" to 8),
"B" to mapOf("X" to 1, "Y" to 5, "Z" to 9),
"C" to mapOf("X" to 2, "Y" to 6, "Z" to 7),
)[elf]!![me]!!
}
}
// 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 | d628345afeb014adce189fddac53a1fcd98479fb | 1,001 | advent-of-code-2022 | Apache License 2.0 |
src/day04/Day04.kt | banshay | 572,450,866 | false | {"Kotlin": 33644} | package day04
import readInput
fun main() {
fun part1(input: List<String>): Int {
return input.map { it.toElfPair() }.count { it.doesEnvelop() }
}
fun part2(input: List<String>): Int {
return input.map { it.toElfPair() }.count { it.doesOverlap() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val input = readInput("Day04")
println("test part1: ${part1(testInput)}")
println("result part1: ${part1(input)}")
println("test part2: ${part2(testInput)}")
println("result part2: ${part2(input)}")
}
fun String.toElfPair(): ElfPair {
val first = substringBefore(",")
val second = substringAfter(",")
return ElfPair(
Range(first.substringBefore("-").toInt(), first.substringAfter("-").toInt()),
Range(second.substringBefore("-").toInt(), second.substringAfter("-").toInt())
)
}
data class ElfPair(val first: Range, val second: Range) {
fun doesEnvelop(): Boolean = first.envelops(second) || second.envelops(first)
fun doesOverlap(): Boolean = first.overlaps(second)
}
data class Range(val lower: Int, val upper: Int) {
fun envelops(other: Range): Boolean =
lower <= other.lower && upper >= other.upper
fun overlaps(other: Range): Boolean = lower <= other.upper && upper >= other.lower
}
| 0 | Kotlin | 0 | 0 | c3de3641c20c8c2598359e7aae3051d6d7582e7e | 1,372 | advent-of-code-22 | Apache License 2.0 |
src/Day21.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | fun main() {
fun part1(input: List<String>): Long {
val yellsMap: MutableMap<String, MonkeyYell> = readYellsMap(input)
val calculation = MonkeyCalculation(yellsMap)
return calculation.calculate("root")
}
fun part2(input: List<String>): Long {
val yellsMap: MutableMap<String, MonkeyYell> = readYellsMap(input)
val currentRoot = yellsMap["root"]
if (currentRoot !is MonkeyOperation)
throw IllegalArgumentException()
val simplification = MonkeyCalculation(yellsMap)
yellsMap["root"] = MonkeyOperation(
currentRoot.operand1, currentRoot.operand2, '='
) { a, b -> a - b }
simplification.simplify("root")
//println(simplification.print("root"))
return simplification.solveEquation("root")
}
val testInput = readInput("Day21_test")
check(part1(testInput) == 152L)
check(part2(testInput) == 301L)
val input = readInput("Day21")
println(part1(input))
println(part2(input))
}
private val functionsMap = mapOf<Char, (Long, Long) -> Long>(
'+' to { a, b -> a + b },
'-' to { a, b -> a - b },
'*' to { a, b -> a * b },
'/' to { a, b -> a / b },
)
private fun readYellsMap(input: List<String>): MutableMap<String, MonkeyYell> {
val result = mutableMapOf<String, MonkeyYell>()
input.forEach {
val substrings = it.split(": ")
val id = substrings[0]
val number: Long? = substrings[1].toLongOrNull()
if (number != null)
result[id] = MonkeyNumber(number)
else {
val operationSubstrings = substrings[1].split(' ')
result[id] = MonkeyOperation(
operationSubstrings[0], operationSubstrings[2],
operationSubstrings[1][0],
functionsMap[operationSubstrings[1][0]]!!
)
}
}
return result
}
private abstract class MonkeyYell
private class MonkeyNumber(val number: Long) : MonkeyYell()
private class MonkeyOperation(
val operand1: String,
val operand2: String,
val functionChar: Char,
val function: (Long, Long) -> Long
) : MonkeyYell()
private class MonkeyCalculation(val yellsMap: MutableMap<String, MonkeyYell>) {
private val HUMN = "humn"
fun calculate(id: String): Long {
val yell = yellsMap[id]!!
return if (yell is MonkeyOperation) {
val result = yell.function(calculate(yell.operand1), calculate(yell.operand2))
yellsMap[id] = MonkeyNumber(result)
result
} else
(yell as MonkeyNumber).number
}
private val cannotSimplified = mutableSetOf(HUMN)
fun simplify(id: String): Long? {
if (cannotSimplified.contains(id))
return null
val yell = yellsMap[id]!!
return if (yell is MonkeyOperation) {
val operand1 = simplify(yell.operand1)
val operand2 = simplify(yell.operand2)
if (operand1 != null && operand2 != null) {
val result = yell.function(operand1, operand2)
yellsMap[id] = MonkeyNumber(result)
result
} else {
cannotSimplified.add(id)
null
}
} else
(yell as MonkeyNumber).number
}
fun print(id: String): String {
if (id == HUMN)
return "X"
val yell = yellsMap[id]!!
return if (yell is MonkeyOperation) {
" (" + print(yell.operand1) + yell.functionChar + print(yell.operand2) + ") "
}
else
(yell as MonkeyNumber).number.toString()
}
// solve equation operation = value
// with condition: only one part of operation has unknown value
private fun solve(operation: MonkeyOperation, value: MonkeyNumber): Long {
val yell1 = yellsMap[operation.operand1]!!
val yell2 = yellsMap[operation.operand2]!!
if (cannotSimplified.contains(operation.operand1)
&& cannotSimplified.contains(operation.operand2)) {
println("${print(operation.operand1)} ${operation.functionChar} ${operation.operand2} " +
"= ${value.number}")
throw IllegalArgumentException()
}
if (cannotSimplified.contains(operation.operand1)) {
val newValue = when(operation.functionChar) {
'+' -> value.number - (yell2 as MonkeyNumber).number
'-' -> value.number + (yell2 as MonkeyNumber).number
'*' -> value.number / (yell2 as MonkeyNumber).number
'/' -> value.number * (yell2 as MonkeyNumber).number
else -> throw IllegalArgumentException()
}
return if (operation.operand1 == HUMN)
newValue
else
solve(yell1 as MonkeyOperation, MonkeyNumber(newValue))
}
else {
val newValue = when(operation.functionChar) {
'+' -> value.number - (yell1 as MonkeyNumber).number
'-' -> (yell1 as MonkeyNumber).number - value.number
'*' -> value.number / (yell1 as MonkeyNumber).number
'/' -> (yell1 as MonkeyNumber).number / value.number
else -> throw IllegalArgumentException()
}
return if (operation.operand2 == HUMN)
newValue
else
solve(yell2 as MonkeyOperation, MonkeyNumber(newValue))
}
}
fun solveEquation(id: String): Long {
val rootOperation = yellsMap[id]
if (rootOperation !is MonkeyOperation)
throw IllegalArgumentException()
val yell1 = yellsMap[rootOperation.operand1]!!
val yell2 = yellsMap[rootOperation.operand2]!!
return if (yell1 is MonkeyOperation && yell2 is MonkeyNumber)
solve(yell1, yell2)
else if (yell2 is MonkeyOperation && yell1 is MonkeyNumber)
solve(yell2, yell1)
else
throw IllegalArgumentException()
}
} | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 6,066 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch7/Problem71.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch7
import dev.bogwalk.util.maths.gcd
import dev.bogwalk.util.maths.lcm
/**
* Problem 71: Ordered Fractions
*
* https://projecteuler.net/problem=71
*
* Goal: By listing the set of reduced proper fractions for d <= N in ascending order of size,
* find the numerator and denominator of the fraction immediately to the left of n/d.
*
* Constraints: 1 <= n < d <= 1e9, gcd(n, d) == 1, d < N <= 1e15
*
* Reduced Proper Fraction: A fraction n/d, where n & d are positive integers, n < d, and
* gcd(n, d) == 1.
*
* Farey Sequence: A sequence of completely reduced fractions, either between 0 and 1, or which
* when in reduced terms have denominators <= N, arranged in order of increasing size. The
* sequence optionally begins with 0/1 and ends with 1/1 if restricted. The middle term of a
* Farey sequence is always 1/2 for N > 1.
*
* e.g. if d <= 8, the Farey sequence would be ->
* 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4,
* 4/5, 5/6, 6/7, 7/8
*
* e.g.: N = 8, n = 3, d = 7
* ans = 2/5
*/
class OrderedFractions {
/**
* Solution finds Farey sequence neighbours based on the following:
*
* If a/b and n/d are neighbours, with a/b < n/d, then their difference:
*
* n/d - a/b = (nb - ad)/(db)
*
* with nb - ad = 1, it becomes ->
*
* n/d - a/b = 1/(db)
*
* A mediant fraction can be found between 2 neighbours using:
*
* p/q = (a + n)/(b + d)
*
* This solution could also be implemented similarly using a Stern-Brocot Tree fraction
* search algorithm that uses binary search to recursively find the target fraction [n]/[d]
* starting from the left & right ancestors, 0/1 & 1/0. Once found, the last left boundary is
* used with the target to find all mediants until a new mediant's denominator exceeds [limit].
*
* SPEED (WORST) 1.00s for N = 1e7
* SPEED (Impossible for N > 1e7)
*
* @return pair of (numerator, denominator) representing the fraction to the left of [n]/[d].
*/
fun leftFareyNeighbour(limit: Long, n: Long, d: Long): Pair<Long, Long> {
val upperBound = n to d
var lowerBound = if (d != limit) (n to d + 1).reduced() else (n - 1 to d).reduced()
val half = 1L to 2L
if (lowerBound < half && half < upperBound) {
lowerBound = half
}
var neighbour: Pair<Long, Long>? = null
while (true) {
val delta = upperBound - lowerBound
val neighbourDelta = 1L to lowerBound.second * d
if (delta == neighbourDelta) neighbour = lowerBound
lowerBound = ((lowerBound.first + n) to (lowerBound.second + d)).reduced()
if (lowerBound.second > limit) {
if (neighbour != null) break else continue
}
}
return neighbour!!
}
private fun Pair<Long, Long>.reduced(): Pair<Long, Long> {
val divisor = gcd(first, second)
return first / divisor to second / divisor
}
/**
* Rather than compare Doubles, whole numbers are compared based on the property that:
*
* if a/b < n/d, then ad < bn
*/
private operator fun Pair<Long, Long>.compareTo(other: Pair<Long, Long>): Int {
val left = this.first.toBigInteger() * other.second.toBigInteger()
val right = this.second.toBigInteger() * other.first.toBigInteger()
return if (left < right) -1 else if (left > right) 1 else 0
}
private operator fun Pair<Long, Long>.minus(other: Pair<Long, Long>): Pair<Long, Long> {
val denominator = lcm(this.second, other.second)
val firstNum = denominator / this.second * this.first
val secondNum = denominator / other.second * other.first
return (firstNum - secondNum) to denominator
}
/**
* Solution improved based on the following:
*
* For each denominator b up to N, the only fraction that needs to be considered is the one
* with the largest numerator a for which a/b < n/d.
*
* a/b < n/d becomes ad < bn, which means ad <= bn - 1
*
* a <= floor((bn - 1)/d)
*
* for b <= N, floor((bn - 1)/d)/b is the largest fraction.
*
* Fractions with larger denominators are spaced more closely than those with smaller
* denominators, so iterating backwards starting at N means the largest neighbour below
* [n]/[d] will be found sooner. The loop is broken based on the aforementioned property that:
*
* the difference between 2 neighbours is given as 1/(db)
*
* for a new fraction r/s to be closer to n/d than a/b ->
*
* 1/(ds) < (nb - da)/(db) -> s > b/(nb - da)
*
* if delta = nb - da = 1, this means s > b, & the loop can be broken as all
* denominators between b and N have already been examined.
*
* SPEED (BEST) 3.3e4ns for N = 1e7
* SPEED (BETTER) 29.48s for N = 1e15
*
* @return pair of (numerator, denominator) representing the fraction to the left of [n]/[d].
*/
fun leftFareyNeighbourImproved(limit: Long, n: Long, d: Long): Pair<Long, Long> {
val nBI = n.toBigInteger()
val dBI = d.toBigInteger()
var closestNeighbour = 0L to 1L
var b = limit.toBigInteger() // current denominator
var minB = 1.toBigInteger()
while (b >= minB) {
val a = (b * nBI - 1.toBigInteger()) / dBI // current numerator
// if closestA/closestB < currentA/currentB,
// then closestA * currentB < closestB * currentA
val currentIsLarger = closestNeighbour.first.toBigInteger() * b <
closestNeighbour.second.toBigInteger() * a
if (currentIsLarger) {
closestNeighbour = (a.longValueExact() to b.longValueExact()).reduced()
val delta = nBI * b - dBI * a
minB = b / delta + 1.toBigInteger()
}
b--
}
return closestNeighbour
}
/**
* Solution optimised by taking advantage of the Extended Euclidean Algorithm that generates
* coefficients x and y, in addition to the gcd.
*
* When a and b are co-prime, x will be the modular multiplicative inverse of a % b and y will
* be the modular multiplicative inverse of b % a. Remember that the modular multiplicative
* inverse of an integer a is an integer x such that the product ax is congruent to 1 with
* respect to the modulus b.
*
* SPEED (BETTER) 1.00ms for N = 1e7
* SPEED (BEST) 9.7e5ns for N = 1e15
*
* @return pair of (numerator, denominator) representing the fraction to the left of [n]/[d].
*/
fun leftFareyNeighbourOptimised(limit: Long, n: Long, d: Long): Pair<Long, Long> {
// add modulus to handle cases when x is negative, as Kotlin % would return negative
val modInverseOfN = (extendedGCD(n, d).second % d + d) % d
var newD = (limit % d) - modInverseOfN
if (newD < 0) newD += d
val neighbourDenom = (limit - newD).toBigInteger()
val neighbourNum = (neighbourDenom * n.toBigInteger() - 1.toBigInteger()) / d.toBigInteger()
return neighbourNum.longValueExact() to neighbourDenom.longValueExact()
}
/**
* Implements the Extended Euclidean Algorithm that calculates, in addition to the gcd of [n1]
* and [n2], the coefficients of Bezout's identity, integers x and y such that:
*
* ax + by = gcd(a, b)
*
* @return triple of (gcd, x, y).
* @throws IllegalArgumentException if either [n1] or [n2] is less than 0.
*/
private fun extendedGCD(n1: Long, n2: Long): Triple<Long, Long, Long> {
require(n1 >= 0 && n2 >= 0) { "Inputs should not be negative" }
if (n1 == 0L) {
return Triple(n2, 0, 1)
}
val (eGCD, x, y) = extendedGCD(n2 % n1, n1)
return Triple(eGCD, y - n2 / n1 * x, x)
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 8,090 | project-euler-kotlin | MIT License |
src/aoc2022/day15/AoC15.kt | Saxintosh | 576,065,000 | false | {"Kotlin": 30013} | package aoc2022.day15
import readLines
import kotlin.math.abs
import kotlin.math.max
private data class P(val x: Int, val y: Int) {
val tuningFrequency get() = x * 4000000L + y
}
private data class B(val p: P, val b: P) {
val radius = p distance b
override fun toString() = "(${p.x},${p.y})"
fun rAtY(y: Int): IntRange? {
val dx = radius - abs(p.y - y)
return if (dx < 0)
null
else
p.x - dx..p.x + dx
}
}
private infix fun P.distance(p2: P) = abs(p2.x - x) + abs(p2.y - y)
private operator fun B.contains(p2: P) = p2 distance p <= radius
private fun parse(list: List<String>) = list.map {
val (a, b) = it.split(": ")
val (a1, a2) = a.split(", ")
val px = a1.removePrefix("Sensor at x=").toInt()
val py = a2.removePrefix("y=").toInt()
val (b1, b2) = b.split(", ")
val bx = b1.removePrefix("closest beacon is at x=").toInt()
val by = b2.removePrefix("y=").toInt()
B(P(px, py), P(bx, by))
}
fun main() {
val yy = mutableListOf(10, 2000000)
fun part1(lines: List<String>): Int {
val beacons = parse(lines)
val y = yy.removeFirst()
var pLeft = P(0, y)
while (true) {
if (beacons.any { pLeft in it })
pLeft = P(pLeft.x - 1, y)
else
break
}
var pRight = P(0, y)
while (true) {
if (beacons.any { pRight in it })
pRight = P(pRight.x + 1, y)
else
break
}
return abs(pLeft.x) - 1 + abs(pRight.x) - 1
}
val maxs = mutableListOf(20, 4000000)
fun part2(lines: List<String>): Long {
val beacons = parse(lines)
val max = maxs.removeFirst()
for (y in 0..max) {
var lastX = -1
beacons.mapNotNull { it.rAtY(y) }.sortedBy { it.first }.forEach {
val x = lastX + 1
if (it.first > x)
return P(x,y).tuningFrequency
else
lastX = max(lastX, it.last)
}
}
return 0
}
readLines(26, 56000011L, ::part1, ::part2)
} | 0 | Kotlin | 0 | 0 | 877d58367018372502f03dcc97a26a6f831fc8d8 | 1,817 | aoc2022 | Apache License 2.0 |
src/Day7.kt | sitamshrijal | 574,036,004 | false | {"Kotlin": 34366} | fun main() {
fun parse(input: List<String>): Directory {
var current = Directory("/")
input.forEach {
when {
it.startsWith("$ cd /") -> {}
it.startsWith("$ ls") -> {}
it.startsWith("$ cd ..") -> {
current = current.parent ?: current
}
it.startsWith("$ cd") -> {
val name = it.substringAfter("$ cd ")
val directory = current.directories.find { it.name == name }
if (directory == null) {
val new = Directory(name = name, parent = current)
current = new
current.directories += new
} else {
current = directory
}
}
it.startsWith("dir") -> {
current.directories += Directory(
name = it.substringAfter("dir "),
parent = current
)
}
else -> {
val (size, name) = it.split(" ")
current.files += File(name, size.toInt())
}
}
}
return current.parent!!.parent!!
}
fun part1(input: List<String>): Int {
val directory = parse(input)
return directory.getAllChildren().map { it.size() }.filter { it <= 100_000 }.sum()
}
fun part2(input: List<String>): Int {
val directory = parse(input)
val unused = 70_000_000 - directory.size()
val needed = 30_000_000 - unused
return directory.getAllChildren().filter { it.size() >= needed }
.sortedBy { it.size() }[0].size()
}
val input = readInput("input7")
println(part1(input))
println(part2(input))
}
data class File(val name: String, val size: Int)
data class Directory(
val name: String = "",
val files: MutableList<File> = mutableListOf(),
val directories: MutableList<Directory> = mutableListOf(),
val parent: Directory? = null
) {
fun size(): Int = files.sumOf { it.size } + directories.sumOf { it.size() }
fun getAllChildren(): List<Directory> =
directories + directories.flatMap { it.getAllChildren() }
override fun toString(): String = name
}
| 0 | Kotlin | 0 | 0 | fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d | 2,382 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | esp-er | 573,196,902 | false | {"Kotlin": 29675} | package patriker.day05
import patriker.utils.*
import java.util.Deque
fun main() {
// test if implementation meets criteria from the description, like:
/*
val testInput = readInputText("Day05_test")
val input = readInputText("Day05_input")
println(solvePart1(input))
println(solvePart2(testInput))
check(solvePart2(testInput) == "MCD")
println(solvePart2(input))
*/
}
//used in part1
fun moveCrate(from: Int, dest: Int, numCrates: Int, crateStacks: Array<ArrayDeque<Char>>): Unit{
repeat(numCrates){
crateStacks[dest].addFirst( crateStacks[from].removeFirst() )
}
}
//used in part2
fun moveCrates(from: Int, dest: Int, numCrates: Int, crateStacks: Array<ArrayDeque<Char>>): Unit{
val toMove = crateStacks[from].slice(0 until numCrates)
repeat(numCrates){crateStacks[from].removeFirst()}
crateStacks[dest].addAll(0, toMove)
}
fun String.isInteger() : Boolean {
return this.toIntOrNull() != null
}
fun parseLine(line: String): Triple<Int,Int,Int> {
val (numCrates, from, dest) = line.split(" ").filter{ it.isInteger() }
return Triple(from.toInt(), dest.toInt(), numCrates.toInt())
}
fun solvePart1(input: String): String{
val (stacks, instructions) = input.split("\n\n")
val numStacks = stacks.lines().last().filter{!it.isWhitespace()}.length
val colPositions = stacks.lines().last().foldIndexed(emptyList<Int>()){ i, accum, c ->
if(!c.isWhitespace()){
accum + i
}else{
accum
}
}
val stackArr = Array(numStacks){
ArrayDeque<Char>()
}
stacks.lines().dropLast(1).reversed().forEach{ containerLine ->
colPositions.forEachIndexed{ i, p ->
if(p < containerLine.length && !containerLine[p].isWhitespace())
stackArr[i].addFirst(containerLine[p])
}
}
instructions.lines().forEach{ line ->
if(line.isNotBlank()) {
val (from, dest, numCrates) = parseLine(line)
moveCrate(from - 1, dest - 1, numCrates, stackArr)
}
}
return stackArr.map{it[0]}.joinToString("")
}
fun solvePart2(input: String): String{
val (stacks, instructions) = input.split("\n\n")
val numStacks = stacks.lines().last().filter{!it.isWhitespace()}.length
val colPositions = stacks.lines().last().foldIndexed(emptyList<Int>()){ i, accum, c ->
if(!c.isWhitespace()){
accum + i
}else{
accum
}
}
val stackArr = Array(numStacks){
ArrayDeque<Char>()
}
stacks.lines().dropLast(1).reversed().forEach{ containerLine ->
colPositions.forEachIndexed{ i, p ->
if(p < containerLine.length && !containerLine[p].isWhitespace())
stackArr[i].addFirst(containerLine[p])
}
}
instructions.lines().forEach{ line ->
if(line.isNotBlank()) {
val (from, dest, numCrates) = parseLine(line)
moveCrates(from - 1, dest - 1, numCrates, stackArr)
}
}
return stackArr.map{it[0]}.joinToString("")
}
| 0 | Kotlin | 0 | 0 | f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362 | 3,097 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2022/Day12.kt | colinodell | 572,710,708 | false | {"Kotlin": 105421} | package com.colinodell.advent2022
import java.util.PriorityQueue
class Day12(input: List<String>) {
private val grid = input.toGrid()
private val start = grid.entries.find { it.value == 'S' }!!.key
private val goal = grid.entries.find { it.value == 'E' }!!.key
private enum class Direction {
CLIMBING, DESCENDING;
fun canGo(currentElevation: Int, nextElevation: Int): Boolean {
return when (this) {
CLIMBING -> (nextElevation - currentElevation) <= 1
DESCENDING -> (currentElevation - nextElevation) <= 1
}
}
}
fun solvePart1() = findShortestPathLength(start, Direction.CLIMBING) { it == goal }
fun solvePart2() = findShortestPathLength(goal, Direction.DESCENDING) { grid[it]!! == 'a' }
private fun getElevation(c: Char) = when (c) {
'S' -> 'a'.code
'E' -> 'z'.code
else -> c.code
}
private fun nextMoves(current: Vector2, direction: Direction) = sequence {
for (neighbor in grid.neighborsOf(current)) {
if (direction.canGo(getElevation(grid[current]!!), getElevation(neighbor.value))) {
yield(neighbor)
}
}
}
/**
* Find the shortest path using the Dijkstra algorithm
*/
private fun findShortestPathLength(start: Vector2, direction: Direction, reachedEnd: (Vector2) -> Boolean): Int {
var end: Vector2? = null
val visited = mutableSetOf<Vector2>()
val distances = mutableMapOf<Vector2, Int>()
val previous = mutableMapOf<Vector2, Vector2>()
val queue = PriorityQueue<Vector2> { a, b -> distances[a]!! - distances[b]!! }
for (node in grid.keys) {
distances[node] = Int.MAX_VALUE
previous[node] = start
}
distances[start] = 0
queue.add(start)
while (queue.isNotEmpty()) {
val current = queue.poll()
visited.add(current)
if (reachedEnd(current)) {
end = current
break
}
for (neighbor in nextMoves(current, direction).map { it.key }) {
val distance = distances[current]!! + 1
if (distance < distances[neighbor]!!) {
distances[neighbor] = distance
previous[neighbor] = current
queue.add(neighbor)
}
}
}
// Determine the length of the path
var pathLength = 0
var current = end!!
while (current != start) {
pathLength++
current = previous[current]!!
}
return pathLength
}
}
| 0 | Kotlin | 0 | 1 | 32da24a888ddb8e8da122fa3e3a08fc2d4829180 | 2,705 | advent-2022 | MIT License |
src/Day03.kt | vlsolodilov | 573,277,339 | false | {"Kotlin": 19518} | fun main() {
fun getEqualItems(rucksack: String): Char {
val rucksackItems = rucksack.toList()
val rucksackSize = rucksackItems.size
val firstCompartment = rucksackItems.subList(0, (rucksackSize + 1) / 2)
val secondCompartment = rucksackItems.subList((rucksackSize + 1) / 2, rucksackSize)
return firstCompartment.first { item -> secondCompartment.contains(item) }
}
fun getPriorityItem(item: Char): Int {
val codeDelta = if (item.isLowerCase()) 96 else 38
return item.code - codeDelta
}
fun part1(input: List<String>): Int =
input.map { getEqualItems(it) }.sumOf { getPriorityItem(it) }
fun getGroupEqualItems(group: List<String>): Char =
group[0].toList().first { item ->
group[1].toList().contains(item) && group[2].toList().contains(item) }
fun part2(input: List<String>): Int =
input.chunked(3).map(::getGroupEqualItems).sumOf(::getPriorityItem)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b75427b90b64b21fcb72c16452c3683486b48d76 | 1,255 | aoc22 | Apache License 2.0 |
src/main/kotlin/year2023/day-03.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2023
import lib.Grid2d
import lib.Position
import lib.aoc.Day
import lib.aoc.Part
import lib.math.Vector
import lib.splitLines
fun main() {
Day(3, 2023, PartA3(), PartB3()).run()
}
open class PartA3 : Part() {
data class Number(val position: Position, val value: Int, val neighbors: Set<Position>) {
companion object {
fun at(position: Position, grid: Grid2d<Char>): Number {
val horizontalMoves = listOf(Vector.at(-1, 0), Vector.at(1, 0), Vector.at(0, 0))
val positions = position.neighbours(horizontalMoves, grid.limits)
.filter { grid[it] in '0'..'9' }
.toMutableSet()
while (true) {
val newDigitsFound = positions.addAll(positions.flatMap {
it.neighbours(horizontalMoves, grid.limits)
.filter { grid[it] in '0'..'9' }
.filter { it !in positions }
})
if (!newDigitsFound) {
break
}
}
val number = positions
.sortedBy { it.position.x }
.map { grid[it] }
.joinToString("")
val neighbors = number.indices
.map { position + Vector.at(it, 0) }
.flatMap { it.neighbours(Position.moves(diagonals = true), grid.limits) }
.toSet()
return Number(positions.minByOrNull { it.position.x }!!, number.toInt(), neighbors)
}
}
}
protected lateinit var grid: Grid2d<Char>
protected lateinit var numbers: List<Number>
override fun parse(text: String) {
val lines = text.splitLines()
grid = Grid2d.ofLines(lines)
numbers = grid.findAll("0123456789".asIterable())
.map { Number.at(it, grid) }
.distinctBy { it.position }
}
override fun compute(): String {
return numbers.filter { it.neighbors.any(::isSymbol) }
.sumOf { it.value }
.toString()
}
private fun isSymbol(position: Position) = grid[position] !in "0123456789."
override val exampleAnswer: String
get() = "4361"
}
class PartB3 : PartA3() {
override fun compute(): String {
return numbers.flatMap { number -> number.neighbors.filter { grid[it] == '*' }.map { it to number } }
.groupBy({ it.first }, { it.second })
.filter { it.value.size == 2 }
.map { it.value.first().value * it.value.last().value }
.sum()
.toString()
}
override val exampleAnswer: String
get() = "467835"
}
| 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 2,834 | Advent-Of-Code-Kotlin | MIT License |
src/main/kotlin/Day04.kt | rgawrys | 572,698,359 | false | {"Kotlin": 20855} | import utils.oneRangeFullyContainOther
import utils.rangesOverlap
import utils.readInput
fun main() {
fun part1(input: List<String>): Int =
countPairsThatOneRangeFullyContainOther(input)
fun part2(input: List<String>): Int =
countPairsThatRangesOverlap(input)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
part1(testInput).let {
check(it == 2) { "Part 1: Incorrect result. Is `$it`, but should be `2`" }
}
part2(testInput).let {
check(it == 4) { "Part 2: Incorrect result. Is `$it`, but should be `4`" }
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private val inputLineRegex = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex()
private fun countPairsThatOneRangeFullyContainOther(sectionAssignmentsForEachPairList: List<String>) =
countPairsBy(sectionAssignmentsForEachPairList) { it.oneRangeFullyContainOther() }
private fun countPairsThatRangesOverlap(sectionAssignmentsForEachPairList: List<String>) =
countPairsBy(sectionAssignmentsForEachPairList) { it.rangesOverlap() }
private fun countPairsBy(
sectionAssignmentsForEachPairList: List<String>,
condition: (Pair<IntRange, IntRange>) -> Boolean
) =
sectionAssignmentsForEachPairList
.map(String::toPairSection)
.count(condition)
private fun String.toPairSection(): Pair<IntRange, IntRange> =
inputLineRegex.matchEntire(this)!!.destructured
.let { (startX, endX, startY, endY) -> startX.toInt()..endX.toInt() to startY.toInt()..endY.toInt() }
// parsing input using split function
// private fun Pair<String, String>.toPairSections(): Pair<IntRange, IntRange> =
// this.let { it.first.toSection() to it.second.toSection() }
//
// private fun String.toSection(): IntRange =
// this.split("-")
// .let { it[0].toInt() to it[1].toInt() }
// .let { it.first..it.second }
//
// private fun String.toPair(): Pair<String, String> =
// this.split(",").let { it[0] to it[1] }
| 0 | Kotlin | 0 | 0 | 5102fab140d7194bc73701a6090702f2d46da5b4 | 2,070 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | bigtlb | 573,081,626 | false | {"Kotlin": 38940} | import kotlin.math.abs
fun main() {
val pairRegex = """x=(?<x>[\-0-9]+), y=(?<y>[\-0-9]+)""".toRegex()
fun parseList(input: List<String>): List<Pair<Loc, Loc>> =
input.map {
pairRegex.findAll(it).toList().let { (first, second) ->
val source = first.groups as MatchNamedGroupCollection
val beacon = second.groups as MatchNamedGroupCollection
Pair(
Loc(source["x"]?.value?.toInt() ?: 0, source["y"]?.value?.toInt() ?: 0),
Loc(beacon["x"]?.value?.toInt() ?: 0, beacon["y"]?.value?.toInt() ?: 0)
)
}
}
data class Diamond(
val top: Loc,
val bottom: Loc,
val left: Loc,
val right: Loc,
val center: Loc,
val distance: Int
) {
fun contains(test: Loc): Boolean = abs(test.first - center.first) + abs(test.second - center.second) <= distance
fun rightEdge(row: Int): Int =
if ((top.second..bottom.second).contains(row)) right.first - abs(center.second - row) else Int.MAX_VALUE
}
fun Pair<Loc, Loc>.getDistance() = abs(first.second - second.second) + abs(first.first - second.first)
fun Pair<Loc, Loc>.getDiamond(): Diamond {
val distance = getDistance()
return Diamond(
first + Loc(0, -distance),
first + Loc(0, distance),
first + Loc(-distance, 0),
first + Loc(distance, 0),
this.first,
distance
)
}
fun List<Pair<Loc, Loc>>.checkRow(row: Int): String {
val testSet = mutableSetOf<Loc>()
val beaconSet = mutableSetOf<Loc>()
val sourceSet = mutableSetOf<Loc>()
filter {
it.getDiamond().contains(Loc(it.first.first, row))
}.map {
val distance = it.getDistance()
val width = when {
row > it.first.second -> it.first.second + distance - row
row < it.first.second -> row - (it.first.second - distance)
else -> distance
}
testSet.addAll((it.first.first - width..it.first.first + width).toList().map { Loc(it, row) })
if (it.first.second == row) sourceSet.add(it.first)
if (it.second.second == row) beaconSet.add(it.second)
}
val bounds = Loc(testSet.minOf { it.first }, testSet.maxOf { it.first })
val result = String((bounds.first..bounds.second).toList().map {
val test = Loc(it, row)
when {
sourceSet.contains(test) -> 'S'
beaconSet.contains(test) -> 'B'
testSet.contains(test) -> '#'
else -> '.'
}
}.toCharArray())
return result
}
fun List<Pair<Loc, Loc>>.checkAll(searchSpace: Int): Loc {
val diamonds = this.map { Pair(it.first, it.getDiamond()) }
var found: Loc? = null
var curDiamond: Pair<Loc, Diamond>?
var x = 0
var y = 0
while (found == null && y <= searchSpace) {
while (found == null && x <= searchSpace) {
val test = Loc(x, y)
curDiamond = diamonds.firstOrNull { it.second.contains(test) }
if (curDiamond == null) {
found = Loc(x, y)
} else {
x = curDiamond.second.rightEdge(y)
}
x++
}
x = 0
y++
}
return found!!
}
fun part1(input: List<String>, row: Int): Int = parseList(input).checkRow(row).count { it == '#' }
fun part2(input: List<String>, searchSpace: Int): Long {
val found = parseList(input).checkAll(searchSpace)
return found.let {
it.first * 4000000L + it.second
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011L)
println("checked")
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 4000000))
}
| 0 | Kotlin | 0 | 0 | d8f76d3c75a30ae00c563c997ed2fb54827ea94a | 4,186 | aoc-2022-demo | Apache License 2.0 |
solutions/aockt/y2016/Y2016D01.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2016
import aockt.y2016.Y2016D01.Direction.*
import io.github.jadarma.aockt.core.Solution
import kotlin.math.absoluteValue
object Y2016D01 : Solution {
/** Parses the input and returns the sequence of turn and direction pairs. */
private fun parseInput(input: String): Sequence<Pair<Boolean, Int>> =
Regex("""(?:, )?([LR])(\d+)""")
.findAll(input)
.map {
val (turn, distance) = it.destructured
val clockwise = when (turn.first()) {
'R' -> true
'L' -> false
else -> throw IllegalArgumentException("Can only turn (L)eft or (R)ight.")
}
clockwise to distance.toInt()
}
/** The cardinal directions and their effect on grid movement. */
private enum class Direction(val horizontalMultiplier: Int, val verticalMultiplier: Int) {
North(0, 1), East(1, 0), South(0, -1), West(-1, 0)
}
/** Holds a position on the grid, and the direction you are facing. */
private data class Position(val x: Int, val y: Int, val direction: Direction)
/** Keep the current coordinates but change the direction by turning [clockwise] or not 90 degrees. */
private fun Position.turn(clockwise: Boolean) = copy(
direction = when (direction) {
North -> if (clockwise) West else East
East -> if (clockwise) North else South
South -> if (clockwise) East else West
West -> if (clockwise) South else North
}
)
/** Move [distance] units in the current [Position.direction]. */
private fun Position.move(distance: Int) = copy(
x = x + distance * direction.horizontalMultiplier,
y = y + distance * direction.verticalMultiplier,
)
/** Returns the distance between this position and the origin point (0,0). */
private val Position.distanceFromOrigin get() = x.absoluteValue + y.absoluteValue
override fun partOne(input: String) =
parseInput(input)
.fold(Position(0, 0, North)) { pos, instr -> pos.turn(instr.first).move(instr.second) }
.distanceFromOrigin
override fun partTwo(input: String): Int {
val visited = mutableSetOf(0 to 0)
parseInput(input)
.fold(Position(0, 0, North)) { pos, instr ->
(1..instr.second).fold(pos.turn(instr.first)) { it, _ ->
it.move(1).apply {
with(x to y) {
if (this in visited) return distanceFromOrigin
visited.add(this)
}
}
}
}
return -1
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 2,745 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day18.kt | wgolyakov | 572,463,468 | false | null | fun main() {
fun parse(input: List<String>) = input.map { it.split(',').map(String::toInt) }.toSet()
val surfaces = listOf(
listOf(1, 0, 0),
listOf(-1, 0, 0),
listOf(0, 1, 0),
listOf(0, -1, 0),
listOf(0, 0, 1),
listOf(0, 0, -1),
)
fun part1(input: List<String>): Int {
val cubes = parse(input)
var unconnectedCount = 0
for (cube in cubes) {
for (surface in surfaces) {
val neighbour = cube.zip(surface).map { it.first + it.second }
if (neighbour !in cubes) unconnectedCount ++
}
}
return unconnectedCount
}
fun part2(input: List<String>): Int {
val cubes = parse(input)
val minX = cubes.minOf { it[0] }
val maxX = cubes.maxOf { it[0] }
val minY = cubes.minOf { it[1] }
val maxY = cubes.maxOf { it[1] }
val minZ = cubes.minOf { it[2] }
val maxZ = cubes.maxOf { it[2] }
val rangeX = minX - 1..maxX + 1
val rangeY = minY - 1..maxY + 1
val rangeZ = minZ - 1..maxZ + 1
val a = listOf(minX - 1, minY - 1, minZ - 1)
val freeAir = mutableSetOf(a)
val queue = ArrayDeque<List<Int>>()
queue.addLast(a)
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
val neighbours = surfaces.map { surface -> curr.zip(surface).map { it.first + it.second } }
.filter { it[0] in rangeX && it[1] in rangeY && it[2] in rangeZ && it !in cubes }
for (next in neighbours) {
if (next !in freeAir) {
freeAir.add(next)
queue.addLast(next)
}
}
}
var unconnectedCount = 0
for (cube in cubes) {
for (surface in surfaces) {
val neighbour = cube.zip(surface).map { it.first + it.second }
if (neighbour in freeAir) unconnectedCount ++
}
}
return unconnectedCount
}
val testInput = readInput("Day18_test")
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 1,853 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | sebokopter | 570,715,585 | false | {"Kotlin": 38263} | fun main() {
data class Rearrangement(val amount: Int, val from: Int, val to: Int)
fun parseRearrangement(line: String): Rearrangement {
val regex = """\D+(\d+)\D+(\d+)\D+(\d+)""".toRegex()
val (amount, from, to) = regex.find(line)?.destructured ?: error("could not parse $line")
return Rearrangement(amount.toInt(), (from.toInt() - 1), (to.toInt() - 1))
}
fun readPuzzleInput(input: String): List<List<String>> = input.split("\n\n").map { it.lines() }
fun countStacks(stackIndices: String): Int = stackIndices.length / 3
fun separateStackIndices(startStacks: List<String>): Pair<List<String>, String> {
val (stacks, stackIndices) = startStacks.chunked(startStacks.lastIndex)
return stacks to stackIndices.single()
}
fun parseStacks(stacksPuzzleInput: List<String>): List<ArrayDeque<Char>> {
val (stacksString, stackIndices) = separateStackIndices(stacksPuzzleInput)
val stackCount = countStacks(stackIndices)
return stacksString.fold(List(stackCount) { ArrayDeque() }) { stacks, line ->
val potentialStacks = line.chunked(4)
for ((stackIndex, potentialStack) in potentialStacks.withIndex()) {
if (potentialStack.isBlank()) continue
val crateId = potentialStack[1]
stacks[stackIndex].addFirst(crateId)
}
stacks
}
}
fun topOfStack(stacks: List<ArrayDeque<Char>>) = stacks.fold("") { topOfStacks, stack ->
if (stack.isNotEmpty()) topOfStacks + stack.last()
else topOfStacks
}
fun List<Rearrangement>.rearrange(stacks: List<ArrayDeque<Char>>) = forEach { (amount, fromIndex, toIndex) ->
repeat(amount) {
val stackToMove = stacks[fromIndex].removeLast()
stacks[toIndex].add(stackToMove)
}
}
fun List<Rearrangement>.rearrange2(stacks: List<ArrayDeque<Char>>) = forEach { (amount, fromIndex, toIndex) ->
val stacksToMove = ArrayDeque<Char>()
repeat(amount) {
stacksToMove.addFirst(stacks[fromIndex].removeLast())
}
stacks[toIndex].addAll(stacksToMove)
}
fun part1(input: String): String {
val (stacksInput, rearrangementInput) = readPuzzleInput(input)
val stacks = parseStacks(stacksInput)
val rearrangements = rearrangementInput.map(::parseRearrangement)
rearrangements.rearrange(stacks)
return topOfStack(stacks)
}
fun part2(input: String): String {
val (stacksInput, rearrangementInput) = readPuzzleInput(input)
val stacks = parseStacks(stacksInput)
val rearrangements = rearrangementInput.map(::parseRearrangement)
rearrangements.rearrange2(stacks)
return topOfStack(stacks)
}
val testInput = readTextInput("Day05_test")
println("part1(testInput): " + part1(testInput))
println("part2(testInput): " + part2(testInput))
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readTextInput("Day05")
println("part1(input): " + part1(input))
println("part2(input): " + part2(input))
}
| 0 | Kotlin | 0 | 0 | bb2b689f48063d7a1b6892fc1807587f7050b9db | 3,171 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | bin-wang | 573,219,628 | false | {"Kotlin": 4145} | fun main() {
fun countTrees(input: List<String>, xSlope: Int, ySlope: Int): Int {
val h = input.size
val w = input.first().length
val posSequence = generateSequence(Pair(0, 0)) {
if (it.second + ySlope < h) Pair(
it.first + xSlope,
it.second + ySlope
) else null
}
return posSequence.map { (x, y) ->
input[y][x % w] == '#'
}.count { it }
}
fun part1(input: List<String>): Int {
return countTrees(input, 3, 1)
}
fun part2(input: List<String>): Long {
val slopeList = listOf(Pair(1, 1), Pair(3, 1), Pair(5, 1), Pair(7, 1), Pair(1, 2))
return slopeList.map { (xSlope, ySlope) ->
countTrees(input, xSlope, ySlope).toLong()
}.reduce(Long::times)
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 7)
check(part2(testInput) == 336L)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 929f812efb37d5aea34e741510481ca3fab0c3da | 1,033 | aoc20-kt | Apache License 2.0 |
src/Day11.kt | coolcut69 | 572,865,721 | false | {"Kotlin": 36853} | import java.math.BigInteger
fun main() {
fun extracted(inputs: List<String>, boredFactor: Int = 3): List<Monkey> {
val monkeys: MutableList<Monkey> = ArrayList()
for (i in 0..inputs.size / 7) {
val monkeyId = i * 7
val numbers: List<String> = inputs[monkeyId + 1].substringAfter("Starting items: ").split(", ")
val operation = inputs[monkeyId + 2].substringAfter("Operation: new = ")
val divide = inputs[monkeyId + 3].substringAfter("Test: divisible by ").toInt()
val trueMonkey = inputs[monkeyId + 4].substringAfter("If true: throw to monkey ").toInt()
val falseMonkey = inputs[monkeyId + 5].substringAfter("If false: throw to monkey ").toInt()
monkeys.add(
Monkey(
divide,
trueMonkey,
falseMonkey,
numbers.map { it.toLong() }.toMutableList(),
operation,
boredFactor
)
)
}
return monkeys
}
fun magicNumber(inputs: List<String>): Int {
var magicNumber = 1;
for (i in 0..inputs.size / 7) {
val monkeyId = i * 7
magicNumber *= inputs[monkeyId + 3].substringAfter("Test: divisible by ").toInt()
}
return magicNumber
}
fun part1(inputs: List<String>, magicNumber: Int): Long {
val monkeys = extracted(inputs)
repeat(20) {
for (monkey in monkeys) {
val passes = monkey.playRound(magicNumber)
for (pas in passes) {
val m = monkeys.get(pas.monkey)
m.addItem(pas.level)
}
}
}
val sorted = monkeys.map { it.inspections() }.sorted().reversed()
return sorted[0] * sorted[1]
}
fun part2(inputs: List<String>, magicNumber: Int): BigInteger {
val monkeys = extracted(inputs, 1)
repeat(10000) { index ->
for (monkey in monkeys) {
val passes = monkey.playRound(magicNumber)
for (pas in passes) {
val m = monkeys.get(pas.monkey)
m.addItem(pas.level)
}
}
}
val sorted = monkeys.map { it.inspections() }.sorted().reversed()
return BigInteger.valueOf(sorted[0]).multiply(BigInteger.valueOf(sorted[1]))
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput, magicNumber(testInput)) == 10605L)
check(part2(testInput, magicNumber(testInput)) == BigInteger.valueOf(2713310158L))
val input = readInput("Day11")
println(part1(input, magicNumber(input)))
check(part1(input, magicNumber(input)) == 66124L)
println(part2(input, magicNumber(input)))
check(part2(input, magicNumber(input)) == BigInteger.valueOf(19309892877L))
}
data class Monkey(
val divisionTest: Int,
val testTrue: Int,
val testFalse: Int,
var items: MutableList<Long>,
val operation: String,
val borredFactor: Int = 3
) {
private var inspections: Long = 0
fun playRound(i: Int): List<Pass> {
val passes: MutableList<Pass> = ArrayList()
for (item in items) {
inspections++
var new = applyOperation(item) / borredFactor
new %= i
if (new % divisionTest == 0L) {
passes.add(Pass(testTrue, new))
} else {
passes.add(Pass(testFalse, new))
}
}
items = ArrayList()
return passes
}
fun inspections(): Long {
return inspections
}
private fun applyOperation(old: Long): Long {
val s = operation.substringAfter("old ")
val op = s.split(" ")[0]
val otherValue = s.split(" ")[1]
return when (op) {
"+" -> old + getOldValue(old, otherValue)
"*" -> old * getOldValue(old, otherValue)
else -> throw IllegalArgumentException("unknown operator")
}
}
private fun getOldValue(old: Long, other: String): Long {
return if (other == "old") {
old
} else {
other.toLong()
}
}
fun addItem(level: Long) {
this.items.add(level)
}
}
data class Pass(val monkey: Int, val level: Long)
| 0 | Kotlin | 0 | 0 | 031301607c2e1c21a6d4658b1e96685c4135fd44 | 4,455 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day04.kt | uekemp | 575,483,293 | false | {"Kotlin": 69253} |
data class Section(private val lower: Int, private val upper: Int) {
init {
if (lower > upper) {
error("Wrong input: $lower > $upper")
}
}
fun fullyContains(other: Section): Boolean {
return this.lower >= other.lower && this.upper <= other.upper
}
fun overlaps(other: Section): Boolean {
return (lower in other.lower..other.upper) || (other.lower in lower..upper)
}
}
private val parser = "([0-9]+)-([0-9]+)".toRegex()
fun Section(text: String): Section {
val result = parser.find(text) ?: error("Bad input: $text")
return Section(result.groups[1]?.value!!.toInt(), result.groups[2]?.value!!.toInt())
}
fun main() {
fun part1(input: List<String>): Int {
return input.count { line ->
val (sec1, sec2) = line.split(",")
val s1 = Section(sec1)
val s2 = Section(sec2)
(s1.fullyContains(s2) || s2.fullyContains(s1))
}
}
fun part2(input: List<String>): Int {
return input.count { line ->
val (sec1, sec2) = line.split(",")
val s1 = Section(sec1)
val s2 = Section(sec2)
s1.overlaps(s2)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part2(testInput) == 4)
val input = readInput("Day04")
check(part1(input) == 494)
check(part2(input) == 833)
}
| 0 | Kotlin | 0 | 0 | bc32522d49516f561fb8484c8958107c50819f49 | 1,465 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/co/csadev/advent2020/Day13.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /*
* Copyright (c) 2021 by <NAME>
*/
package co.csadev.advent2020
class Day13(input: List<String>) {
private val start = input.first().toInt()
private val shuttles = input.last().split(",").mapNotNull { i -> i.toIntOrNull() }
private val shuttleMinutes = input.last().split(",")
.mapIndexedNotNull { idx, i -> i.toIntOrNull()?.let { it to idx } }
fun solvePart1() = shuttles.map { it to it * ((start / it) + 1) - start }
.minByOrNull { it.second }!!
.run { first * second }
fun solvePart2() = findTime2(shuttleMinutes)
private fun findTime2(buses: List<Pair<Int, Int>>): Long = longBuses(buses)
.fold(Pair(0L, 1L)) { acc, next -> applyBus(acc.first, acc.second, next.first, next.second) }.first
private fun applyBus(sum: Long, interval: Long, bus: Long, timeDif: Long) =
Pair(findTimeWithRightDiff(sum, interval, timeDif, bus), interval * bus)
private tailrec fun findTimeWithRightDiff(start: Long, interval: Long, expected: Long, bus: Long): Long =
if ((start + expected) % bus == 0L) {
start
} else {
findTimeWithRightDiff(start + interval, interval, expected, bus)
}
private fun longBuses(buses: List<Pair<Int, Int>>) = buses.map { Pair(it.first.toLong(), it.second.toLong()) }
fun findTime(buses: List<Pair<Long, Long>>): Long {
return chineseRemainder(buses)
}
/* returns x where (a * x) % b == 1 */
private fun multInv(a: Long, b: Long): Long {
if (b == 1L) return 1L
var aa = a
var bb = b
var x0 = 0L
var x1 = 1L
while (aa > 1) {
x0 = (x1 - (aa / bb) * x0).also { x1 = x0 }
bb = (aa % bb).also { aa = bb }
}
if (x1 < 0) x1 += b
return x1
}
private fun chineseRemainder(buses: List<Pair<Long, Long>>): Long {
val prod = buses.map { it.first }.fold(1L) { acc, i -> acc * i }
var sum = 0L
for (i in buses.indices) {
val p = prod / buses[i].first
sum += buses[i].second * multInv(p, buses[i].first) * p
}
return sum % prod
}
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 2,173 | advent-of-kotlin | Apache License 2.0 |
src/Day05.kt | ricardorlg-yml | 573,098,872 | false | {"Kotlin": 38331} | data class CrateStack(var data: String) {
fun remove(howMany: Int): String {
return data.takeLast(howMany)
.also {
data = data.dropLast(howMany)
}
}
fun add(data: String, crateMover9001: Boolean = false) {
if (crateMover9001) {
this.data += data
} else
this.data += data.reversed()
}
}
data class CrateMove(val howMany: Int, val from: Int, val to: Int)
fun main() {
val moveRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
fun parseInput(input: List<String>): Pair<List<CrateStack>, List<CrateMove>> {
val (inputMoves, inputStacksData) = input.partition { it.matches(moveRegex) }
val stacks = inputStacksData.takeWhile { it.contains("[") }
val crates = (1..stacks.last().length step 4).map { i ->
stacks.fold("") { acc, s ->
s.getOrNull(i)
.let {
if (it == null || !it.isUpperCase()) acc
else it + acc
}
}.let { CrateStack(it) }
}
val moves = inputMoves.mapNotNull {
moveRegex
.find(it)?.destructured?.toList()
?.map { s -> s.toInt() }
?.let { (a, b, c) -> CrateMove(a, b, c) }
}
return Pair(crates, moves)
}
fun part1(input: List<String>): String {
val (crates, moves) = parseInput(input)
moves.forEach { move ->
val dataRemoved = crates[move.from - 1].remove(move.howMany)
crates[move.to - 1].add(dataRemoved)
}
return crates.joinToString("") { it.data.takeLast(1) }
}
fun part2(input: List<String>): String {
val (crates, moves) = parseInput(input)
moves.forEach { move ->
val dataRemoved = crates[move.from - 1].remove(move.howMany)
crates[move.to - 1].add(dataRemoved, true)
}
return crates.joinToString("") { it.data.takeLast(1) }
}
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 | d7cd903485f41fe8c7023c015e4e606af9e10315 | 2,249 | advent_code_2022 | Apache License 2.0 |
src/Day16.kt | MatthiasDruwe | 571,730,990 | false | {"Kotlin": 47864} | import kotlin.math.ceil
fun main() {
data class Valve(val name: String, val pressure: Int, var pipesTo: List<String>, var open: Boolean = false)
fun parseInpunt(input: List<String>) = input.map {
val line = it.split(";")
val name = line[0].split(" ")[1]
val pressure = line[0].split(" ")[4].split("=")[1].toInt()
val pipesTo =
line[1].trim().removePrefix("tunnels lead to valves ").removePrefix("tunnel leads to valve ").split(",")
.map { it.trim() }
Valve(name, pressure, pipesTo)
}.groupBy { it.name }.mapValues { it.value.first() }
var maxcost = 0
fun calculateCost(remainingTime: Int, position: String, paths: Map<String, Valve>, path: String, cost: Int) {
val valve = paths[position] ?: return
val unvisitedValves = valve.pipesTo.filter { !path.contains(it) }
val valves = (unvisitedValves.ifEmpty { valve.pipesTo }).filter { it != position }
var time = remainingTime
val sum = paths.filter { !it.value.open }.values.sortedByDescending { it.pressure }.sumOf {
time = time - 1
it.pressure * time
}
if (remainingTime <= 1 || paths.all { it.value.pressure == 0 || it.value.open } || maxcost > cost + sum) {
if (maxcost < cost) {
maxcost = cost
print(path)
println(maxcost)
}
return
}
valves.forEach {
calculateCost(remainingTime - 1, it, paths, "$path $it", cost)
}
if (valve.pressure != 0 && !valve.open) {
valves.forEach {
calculateCost(
remainingTime - 2,
it,
paths.mapValues { it.value.copy(open = if (it.value.name == position) true else it.value.open) },
"$path $it",
cost + (remainingTime - 1) * valve.pressure
)
}
}
}
fun calculateCost(
remainingTime: Int,
position1: String,
position2: String,
paths: Map<String, Valve>,
path1: String,
path2: String,
cost: Int
) {
val valve1 = paths[position1] ?: return
val valve2 = paths[position2] ?: return
val unvisitedValves1 = valve1.pipesTo.filter { !path1.contains(it) && !path2.contains(it) }
val unvisitedValves2 = valve2.pipesTo.filter { !path1.contains(it) && !path2.contains(it) }
val valves1 = (unvisitedValves1.ifEmpty { valve1.pipesTo }).filter { it != position1 }
val valves2 = (unvisitedValves2.ifEmpty { valve2.pipesTo }).filter { it != position2 }
var time = remainingTime
val sum = paths.filter { !it.value.open }.values.sortedByDescending { it.pressure }.sumOf {
time--
it.pressure * (ceil(time.toDouble() / 2.0) * 2 + time % 2)
}
if (remainingTime <= 1 || paths.all { it.value.pressure == 0 || it.value.open } || maxcost > cost + sum) {
if (maxcost < cost) {
maxcost = cost
print(path1)
print("-")
print(path2)
println(maxcost)
}
return
}
if (valve2.pressure != 0 && !valve2.open && valve1.pressure != 0 && !valve1.open && valve1 != valve2) {
calculateCost(
remainingTime - 1,
position1,
position2,
paths.mapValues { it.value.copy(open = if (it.value.name == valve2.name || it.value.name == valve1.name) true else it.value.open) },
path1,
path2,
cost + (remainingTime - 1) * valve2.pressure + (remainingTime - 1) * valve1.pressure
)
}
if (valve1.pressure != 0 && !valve1.open) {
valves2.forEach {
calculateCost(
remainingTime - 1,
position1,
it,
paths.mapValues { it.value.copy(open = if (it.value.name == valve1.name) true else it.value.open) },
path1,
"$path2 $it",
cost + valve1.pressure * (remainingTime - 1)
)
}
}
if (valve2.pressure != 0 && !valve2.open) {
valves1.forEach {
calculateCost(
remainingTime - 1,
it,
position2,
paths.mapValues { it.value.copy(open = if (it.value.name == valve2.name) true else it.value.open) },
"$path1 $it",
path2,
cost + (remainingTime - 1) * valve2.pressure
)
}
}
valves1.forEach { v1 ->
valves2.forEach { v2 ->
calculateCost(remainingTime - 1, v1, v2, paths, "$path1 $v1", "$path2 $v2", cost)
}
}
}
fun part1(input: List<String>): Int {
var parsedInput = parseInpunt(input)
maxcost = 0
// parsedInput = parsedInput.mapValues {
// it.value.pipesTo = it.value.pipesTo.sortedByDescending { parsedInput[it]?.pressure }
// it.value
// }
val x = calculateCost(30, "AA", parsedInput, "AA", 0)
println(maxcost)
return maxcost
}
fun part2(input: List<String>): Int {
var parsedInput = parseInpunt(input)
maxcost = 0
// parsedInput = parsedInput.mapValues {
// it.value.pipesTo = it.value.pipesTo.sortedByDescending { parsedInput[it]?.pressure }
// it.value
// }
val x = calculateCost(26, "AA", "AA", parsedInput, "AA", "AA", 0)
println(maxcost)
return maxcost
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_example")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f35f01cea5075cfe7b4a1ead9b6480ffa57b4989 | 6,135 | Advent-of-code-2022 | Apache License 2.0 |
src/y2023/Day23.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2023
import util.Cardinal
import util.Pos
import util.neighborsManhattan
import util.readInput
import util.timingStatistics
object Day23 {
data class Tile(
val pos: Pos,
val slope: Cardinal?
) {
fun neighbors(tiles: Map<Pos, Tile>, visited: Set<Pos>): List<Pair<Int, Int>> {
val nexts = slope?.let {
listOf(it.of(pos))
} ?: pos.neighborsManhattan()
return nexts.filter { it in tiles && it !in visited }
}
}
private val slopeToCardinal = mapOf(
'>' to Cardinal.EAST,
'<' to Cardinal.WEST,
'^' to Cardinal.NORTH,
'v' to Cardinal.SOUTH
)
private fun parse(input: List<String>): List<Tile> {
return input.mapIndexed { row, line ->
line.mapIndexedNotNull { column, c ->
when (c) {
'#' -> null
'.' -> Tile(row to column, null)
else -> Tile(row to column, slopeToCardinal[c])
}
}
}.flatten()
}
fun part1(input: List<String>): Long {
val parsed = parse(input)
val start = parsed.first()
val end = parsed.last()
val tileLookup = parsed.associateBy { it.pos }
var paths = listOf(setOf(start.pos) to start)
val finished = mutableListOf<Set<Pos>>()
while (paths.isNotEmpty()) {
paths = paths.flatMap { (visited, last) ->
val n = last.neighbors(tileLookup, visited).map { pos ->
visited + pos to tileLookup[pos]!!
}
if (n.isEmpty()) {
finished.add(visited)
}
n
}
}
return finished.filter { end.pos in it }.maxOf { it.size }.toLong() - 1
}
fun neighbors(pos: Pos, tiles: Set<Pos>, visited: Set<Pos>): List<Pair<Int, Int>> {
return pos.neighborsManhattan().filter { it in tiles && it !in visited }
}
fun part2(input: List<String>): Long {
val parsed = parse(input)
val start = parsed.first().pos
val end = parsed.last().pos
val tiles = parsed.map { it.pos }.toSet()
val intersections = tiles.filter { tile ->
neighbors(tile, tiles, emptySet()).size > 2 || tile == start || tile == end
}.toSet()
val intersectionNeighbors = intersections.associateWith { startIntersection ->
neighbors(startIntersection, tiles, emptySet()).map { firstStep ->
pathToNextIntersection(startIntersection, firstStep, tiles, intersections)
}
}
var paths = listOf(Path(setOf(start), start, 0))
val finished = mutableListOf<Path>()
while (paths.isNotEmpty()) {
paths = paths.flatMap { path ->
val n = intersectionNeighbors[path.last]!!.map { (next, distance) ->
Path(path.visited + next, next, path.distance + distance)
}
n.firstOrNull { it.last == end }?.let {
finished.add(it)
emptyList()
} ?: n.filter { it.last !in path.visited }
}
}
return finished.maxOf { it.distance }.toLong()
}
data class Path(
val visited: Set<Pos>,
val last: Pos,
val distance: Int
)
private fun pathToNextIntersection(
startIntersection: Pos,
firstStep: Pos,
tiles: Set<Pos>,
intersections: Set<Pos>
): Pair<Pos, Int> {
val visited = mutableSetOf(startIntersection, firstStep)
var last = firstStep
while (last !in intersections) {
val next = neighbors(last, tiles, visited).first { it !in visited }
visited.add(next)
last = next
}
return last to visited.size - 1
}
}
fun main() {
val testInput = """
#.#####################
#.......#########...###
#######.#########.#.###
###.....#.>.>.###.#.###
###v#####.#v#.###.#.###
###.>...#.#.#.....#...#
###v###.#.#.#########.#
###...#.#.#.......#...#
#####.#.#.#######.#.###
#.....#.#.#.......#...#
#.#####.#.#.#########v#
#.#...#...#...###...>.#
#.#.#v#######v###.###v#
#...#.>.#...>.>.#.###.#
#####v#.#.###v#.#.###.#
#.....#...#...#.#.#...#
#.#########.###.#.#.###
#...###...#...#...#.###
###.###.#.###v#####v###
#...#...#.#.>.>.#.>.###
#.###.###.#.###.#.#v###
#.....###...###...#...#
#####################.#
""".trimIndent().split("\n")
println("------Tests------")
println(Day23.part1(testInput))
println(Day23.part2(testInput))
println("------Real------")
val input = readInput(2023, 23)
println("Part 1 result: ${Day23.part1(input)}")
println("Part 2 result: ${Day23.part2(input)}")
timingStatistics { Day23.part1(input) }
timingStatistics { Day23.part2(input) }
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 5,077 | advent-of-code | Apache License 2.0 |
src/day20/day20.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day20
import readInput
private fun parseInput(input: List<String>, multiplier: Long = 1L): List<Pair<Int, Long>> =
input.mapIndexed { index, value -> Pair(index, multiplier * value.toLong()) }
private fun decrypt(data: List<Pair<Int, Long>>): List<Pair<Int, Long>> {
val result = data.toMutableList()
data.indices.forEach { iteration ->
val index = result.indexOfFirst { it.first == iteration }
val item = result[index]
result.removeAt(index)
val nextIndex = (index + item.second).mod(result.size)
result.add(nextIndex, item)
}
return result
}
private fun solution(data: List<Pair<Int, Long>>): Long {
val zero = data.indexOfFirst { it.second == 0L }
return listOf(1000, 2000, 3000).sumOf { data[(zero + it) % data.size].second }
}
private fun part1(input: List<String>): Long {
val data = parseInput(input)
val mixed = decrypt(data)
return solution(mixed)
}
private const val MULTIPLIER = 811589153
private fun part2(input: List<String>): Long {
val data = parseInput(input, MULTIPLIER.toLong())
var mixed = data
repeat(10) { mixed = decrypt(mixed) }
return solution(mixed)
}
fun main() {
val input = readInput("day20/input")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 1,323 | aoc-2022 | Apache License 2.0 |
src/day3/Day03.kt | behnawwm | 572,034,416 | false | {"Kotlin": 11987} | package day3
import readInput
fun main() {
// val fileLines = readInput("day04.txt-test", "day3")
val fileLines = readInput("day04.txt", "day3")
fun part1(fileLines: List<String>): Int {
var sum = 0
fileLines.forEach { text ->
val text1 = text.substring(0, text.length / 2)
val text2 = text.substring(text.length / 2, text.length)
val set1 = text1.toCharArray().toSet()
val set2 = text2.toCharArray().toSet()
val point = set1.intersect(set2).first().toPriorityPoint()
sum += point
// println("${set1.intersect(set2).first()} -> $point")
}
return sum
}
fun part2(fileLines: List<String>): Int {
var sum = 0
fileLines.forEach { text ->
val chunkedList = fileLines.chunked(3)
chunkedList.forEach { group ->
val s1 = group[0].toCharArray().toSet()
val s2 = group[1].toCharArray().toSet()
val s3 = group[2].toCharArray().toSet()
val commonChar = s1.intersect(s2).intersect(s3)
sum += commonChar.first().toPriorityPoint()
}
}
return sum
}
// val sum = part1(fileLines)
val sum = part2(fileLines)
println(sum)
}
const val lowercaseStart: Int = 'a'.code
const val uppercaseStart: Int = 'A'.code
private fun Char.toPriorityPoint(): Int {
return if (isLowerCase()) {
this.code - lowercaseStart + 1
} else {
this.code - uppercaseStart + 27
}
}
| 0 | Kotlin | 0 | 2 | 9d1fee54837cfae38c965cc1a5b267d7d15f4b3a | 1,574 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/tasso/adventofcode/_2021/day10/Day10.kt | AndrewTasso | 433,656,563 | false | {"Kotlin": 75030} | package dev.tasso.adventofcode._2021.day10
import dev.tasso.adventofcode.Solution
import java.math.BigInteger
import java.util.*
class Day10 : Solution<BigInteger> {
override fun part1(input: List<String>): BigInteger {
val parsedInput = input.map { line -> line.toCharArray() }
val syntaxErrorScoreMap = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137)
var totalScore = 0
for(line in parsedInput) {
val firstCorruptedPosition = getFirstCorruptedPosition(line)
val score: Int = if (firstCorruptedPosition >= 0) syntaxErrorScoreMap[line[firstCorruptedPosition]]!! else 0
totalScore += score
}
return BigInteger.valueOf(totalScore.toLong())
}
override fun part2(input: List<String>): BigInteger {
val incompleteLines =
input.map { line -> line.toCharArray() }.filter {line -> getFirstCorruptedPosition(line) == -1 }
val syntaxErrorScoreMap : Map<Char, Long> = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4)
val scores = incompleteLines.map {
getCompletingCharacters(it).fold(BigInteger.valueOf(0)) { acc, c ->
acc * BigInteger.valueOf(5) + BigInteger.valueOf(syntaxErrorScoreMap[c]!!)
}
}.sorted()
return scores[scores.size / 2]
}
}
fun getFirstCorruptedPosition(line : CharArray): Int {
val closingCharMap = mapOf(')' to '(', ']' to '[', '}' to '{', '>' to '<')
val stack = Stack<Char>()
var firstInvalid = -1
line.forEachIndexed{ i, character ->
if (setOf('(', '[', '{', '<').contains(character))
stack.push(character)
else {
if (closingCharMap.keys.contains(character)) {
if(stack.peek() == closingCharMap[character])
stack.pop()
else if (firstInvalid < 0 )
firstInvalid = i
}
}
}
return firstInvalid
}
fun getCompletingCharacters(line : CharArray) : List<Char> {
val openingToClosingCharMap = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>')
val stack = Stack<Char>()
line.forEach{ character ->
//Assume that the lines are not malformed and will always be balanced up until the missing characters
if (setOf('(', '[', '{', '<').contains(character))
stack.push(character)
else {
stack.pop()
}
}
return stack.reversed().map { openingToClosingCharMap[it]!! }
}
| 0 | Kotlin | 0 | 0 | daee918ba3df94dc2a3d6dd55a69366363b4d46c | 2,525 | advent-of-code | MIT License |
src/main/kotlin/day14.kt | tobiasae | 434,034,540 | false | {"Kotlin": 72901} | class Day14 : Solvable("14") {
override fun solveA(input: List<String>): String {
return solve(input, 10)
}
override fun solveB(input: List<String>): String {
return solve(input, 40)
}
private fun solve(input: List<String>, iterations: Int): String {
val template = input.first()
val pairMap =
HashMap<Pair<Char, Char>, Long>().also {
template.take(template.length - 1).forEachIndexed { i, v ->
val p = Pair(v, template[i + 1])
it[p] = (it[p] ?: 0) + 1
}
}
val rulesMap =
HashMap<Pair<Char, Char>, Char>().also {
input.subList(2, input.size).map { r ->
val (match, insertion) = r.split(" -> ")
it[Pair(match[0], match[1])] = insertion[0]
}
}
repeat(iterations) {
val newPairs = HashMap<Pair<Char, Char>, Long>()
pairMap.forEach {
rulesMap[it.key]?.let { insert ->
val p1 = Pair(it.key.first, insert)
val p2 = Pair(insert, it.key.second)
newPairs[p1] = (newPairs[p1] ?: 0) + it.value
newPairs[p2] = (newPairs[p2] ?: 0) + it.value
newPairs[it.key] = (newPairs[it.key] ?: 0) - it.value
}
}
newPairs.forEach { pairMap[it.key] = (pairMap[it.key] ?: 0) + it.value }
pairMap.filter { it.value == 0L }.forEach { pairMap.remove(it.key) }
}
val letterCount =
HashMap<Char, Long>().also {
pairMap.forEach { p -> it[p.key.first] = (it[p.key.first] ?: 0) + p.value }
it[template.last()] = (it[template.last()] ?: 0) + 1
}
return (letterCount.maxBy { it.value }!!.value - letterCount.minBy { it.value }!!.value)
.toString()
}
}
| 0 | Kotlin | 0 | 0 | 16233aa7c4820db072f35e7b08213d0bd3a5be69 | 2,037 | AdventOfCode | Creative Commons Zero v1.0 Universal |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day13/Day13.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day13
import nl.sanderp.aoc.common.*
fun main() {
val (points, folds) = parse(readResource("Day13.txt"))
val (answer1, duration1) = measureDuration<Int> { partOne(points, folds) }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
println("Part two:")
val duration2 = measureDuration { partTwo(points, folds) }
println("took ${duration2.prettyPrint()}")
}
private sealed class Fold
private data class FoldHorizontal(val y: Int) : Fold()
private data class FoldVertical(val x: Int) : Fold()
private fun parse(input: String): Pair<Set<Point2D>, List<Fold>> {
val points = input.lines().takeWhile { it.isNotBlank() }.map { line ->
val (x, y) = line.split(',').map { it.toInt() }
x to y
}
val folds = input.lines().drop(points.size + 1).map { line ->
val (instruction, value) = line.split('=')
when (instruction) {
"fold along x" -> FoldVertical(value.toInt())
"fold along y" -> FoldHorizontal(value.toInt())
else -> throw IllegalArgumentException("Cannot parse fold instruction '$line'")
}
}
return points.toSet() to folds
}
private fun fold(points: Set<Point2D>, f: Fold) = when (f) {
is FoldHorizontal -> points.map { p -> if (p.y < f.y) p else p.x to (p.y - 2 * (p.y - f.y)) }.toSet()
is FoldVertical -> points.map { p -> if (p.x < f.x) p else (p.x - 2 * (p.x - f.x)) to p.y }.toSet()
}
private fun partOne(points: Set<Point2D>, folds: List<Fold>): Int {
val result = fold(points, folds.first())
return result.size
}
private fun partTwo(points: Set<Point2D>, folds: List<Fold>) {
val result = folds.fold(points, ::fold)
result.print()
} | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,735 | advent-of-code | MIT License |
src/Day24.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | object Day24 {
private enum class Direction {
UP, DOWN, LEFT, RIGHT;
companion object {
fun parse(char: Char): Direction = when (char) {
'^' -> UP
'v' -> DOWN
'<' -> LEFT
'>' -> RIGHT
else -> error("Unexpected char '$char'")
}
}
}
private data class Pos(val x: Int, val y: Int) {
fun move(direction: Direction): Pos = when (direction) {
Direction.UP -> copy(y = y - 1)
Direction.DOWN -> copy(y = y + 1)
Direction.LEFT -> copy(x = x - 1)
Direction.RIGHT -> copy(x = x + 1)
}
fun possibleMoves(): List<Pos> = Direction.values().map { move(it) } + this
}
private fun parseInitialState(input: List<String>) = input.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
when (char) {
'#', '.' -> null
else -> (Pos(x, y) to Direction.parse(char))
}
}
}.groupBy({ it.first }, { it.second })
private fun nextState(state: Map<Pos, List<Direction>>, xSize: Int, ySize: Int): Map<Pos, List<Direction>> {
return state.flatMap { (pos, directions) ->
directions.map { direction ->
val next = pos.move(direction)
when {
next.x == 0 -> next.copy(x = xSize - 2)
next.x == xSize - 1 -> next.copy(x = 1)
next.y == 0 -> next.copy(y = ySize - 2)
next.y == ySize - 1 -> next.copy(y = 1)
else -> next
} to direction
}
}.groupBy({ it.first }, { it.second })
}
private fun measureSteps(
start: Pos,
initialState: Map<Pos, List<Direction>>,
end: Pos,
xMax: Int,
yMax: Int
): Pair<Int, Map<Pos, List<Direction>>> {
fun exists(pos: Pos): Boolean {
return pos == start ||
pos == end ||
pos.x in 1..xMax - 2 && pos.y in 1..yMax - 2
}
val sequenceOfSteps = generateSequence(listOf(start) to initialState) { (cells, state) ->
val nextState = nextState(state, xMax, yMax)
val nextCells = cells.asSequence()
.flatMap { it.possibleMoves() }
.filter { exists(it) }
.filter { it !in nextState }
.distinct()
.toList()
nextCells to nextState
}
val (idx, cellsAndState) = sequenceOfSteps.withIndex().first { end in it.value.first }
return idx to cellsAndState.second
}
fun part1(input: List<String>): Int {
val yMax = input.size
val xMax = input.first().length
val start = Pos(1, 0)
val end = Pos(xMax - 2, yMax - 1)
val initialState = parseInitialState(input)
return measureSteps(start, initialState, end, xMax, yMax).first
}
fun part2(input: List<String>): Int {
val xMax = input.first().length
val yMax = input.size
val start = Pos(1, 0)
val end = Pos(xMax - 2, yMax - 1)
val initialState = parseInitialState(input)
val (steps1, state1) = measureSteps(start, initialState, end, xMax, yMax)
val (steps2, state2) = measureSteps(end, state1, start, xMax, yMax)
val (steps3, _) = measureSteps(start, state2, end, xMax, yMax)
return steps1 + steps2 + steps3
}
@JvmStatic
fun main(args: Array<String>) {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day24_test")
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInput("Day24")
println(part1(input))
println(part2(input))
}
} | 0 | Kotlin | 0 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 3,910 | aoc2022 | Apache License 2.0 |
src/Day05.kt | antonarhipov | 574,851,183 | false | {"Kotlin": 6403} | fun main() {
val input = readInput("Day05")
val split = input.indexOfFirst { it.isBlank() }
val stackLines = input.take(split - 1)
val moves = input.drop(split + 1)
println("Stacks:")
stackLines.forEach { println(it) }
println("-----------")
println("Moves:")
moves.forEach { println(it) }
println("-----------")
val stacksA = createStacks(stackLines)
val stacksB = createStacks(stackLines)
makeMovesWithCrateMover9000(moves, stacksA)
println("Moved with 9000: ${stacksA.toSortedMap().values.map { it.last() }.joinToString("")}")
makeMovesWithCrateMover9001(moves, stacksB)
println("Moved with 9001: ${stacksB.toSortedMap().values.map { it.last() }.joinToString("")}")
}
fun makeMovesWithCrateMover9000(moves: List<String>, stacks: HashMap<Int, ArrayList<Char>>) {
for (move in moves) {
val (count, from, to) = Regex("\\d+").findAll(move).toList().map { it.value.toInt() }
repeat(count) {
stacks[to]!!.add(stacks[from]!!.removeLast())
}
}
}
fun makeMovesWithCrateMover9001(moves: List<String>, stacks: HashMap<Int, ArrayList<Char>>) {
for ((i, move) in moves.withIndex()) {
val (count, from, to) = Regex("\\d+").findAll(move).toList().map { it.value.toInt() }
stacks[to]!!.addAll(stacks[from]!!.takeLast(count))
stacks[from] = ArrayList(stacks[from]!!.dropLast(count))
}
}
fun createStacks(input: List<String>): HashMap<Int, ArrayList<Char>> {
val crates = input.map { row ->
row.chunked(4).map {
it.replace(Regex("[\\[\\]\\s]"), "").firstOrNull()
}
}
val stacks = hashMapOf<Int, ArrayList<Char>>()
crates.forEach { row: List<Char?> ->
row.forEachIndexed { i, c ->
if (c != null) {
stacks.compute(i + 1) { _, current ->
current?.apply { add(0, c) } ?: arrayListOf(c)
}
}
}
}
return stacks
}
| 0 | Kotlin | 0 | 0 | 8dd56fdbe67d0af74fbe65ff204275338785cd4a | 1,987 | aoc2022 | Apache License 2.0 |
src/Day04.kt | SnyderConsulting | 573,040,913 | false | {"Kotlin": 46459} | fun main() {
fun part1(input: List<String>): Int {
val pairs = input.map { line -> line.splitAssignmentPair() }
return pairs.count { (part1, part2) ->
val sectionList1 = part1.getNumbersInRange()
val sectionList2 = part2.getNumbersInRange()
sectionList1.containsAll(sectionList2) || sectionList2.containsAll(sectionList1)
}
}
fun part2(input: List<String>): Int {
val pairs = input.map { it.splitAssignmentPair() }
return pairs.count { (part1, part2) ->
val sectionList1 = part1.getNumbersInRange()
val sectionList2 = part2.getNumbersInRange()
sectionList1.any { item -> sectionList2.contains(item) }
|| sectionList2.any { item -> sectionList1.contains(item) }
}
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun String.splitAssignmentPair(): List<String> {
return split(",")
}
fun String.getNumbersInRange(): List<Int> {
return split("-").map { it.toInt() }.let { (rangeStart, rangeEnd) ->
(rangeStart..rangeEnd).toList()
}
}
| 0 | Kotlin | 0 | 0 | ee8806b1b4916fe0b3d576b37269c7e76712a921 | 1,157 | Advent-Of-Code-2022 | Apache License 2.0 |
src/Day03.kt | punx120 | 573,421,386 | false | {"Kotlin": 30825} | fun main() {
fun priority(c : Char): Int {
return if (c.code >= 'a'.code) {
c.code - 'a'.code + 1
} else {
26 + c.code - 'A'.code + 1
}
}
fun part1(input: List<String>): Int {
var sum = 0
for (line in input) {
val first = mutableSetOf<Char>()
val middle = line.length / 2
for (i in 0 until middle) {
first.add(line[i])
}
val second = mutableSetOf<Char>()
for (i in middle until line.length) {
val item = line[i]
if (first.contains(item) && second.add(item)) {
sum += priority(item)
}
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (i in input.indices step 3) {
val map = mutableMapOf<Char, MutableSet<Int>>()
for (k in input[i].indices) {
map.computeIfAbsent(input[i][k]) { mutableSetOf() }.add(i)
}
for (k in input[i+1].indices) {
map.computeIfAbsent(input[i+1][k]) { mutableSetOf() }.add(i+1)
}
for (k in input[i+2].indices) {
map.computeIfAbsent(input[i+2][k]) { mutableSetOf() }.add(i+2)
}
map.forEach{e ->
if (e.value.size == 3) {
sum += priority(e.key)
}
}
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | eda0e2d6455dd8daa58ffc7292fc41d7411e1693 | 1,791 | aoc-2022 | Apache License 2.0 |
src/Day24.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | import java.math.BigInteger
import java.math.BigInteger.ONE
import java.math.BigInteger.ZERO
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sign
private const val EXPECTED_1 = 2L
private const val EXPECTED_2 = 47L
fun List<Pair<BigInteger, BigInteger>>.chineseRemainderTheorem(): BigInteger {
val product = fold(ONE) { acc, (number, _) -> acc * number }
val result = map { (number, remainder) ->
val pp = product / number
remainder * pp.moduloInverse(number) * pp
}.fold(ZERO, BigInteger::plus)
var base = result.rem(product)
while (base < ZERO) {
base += product
}
return base
}
fun BigInteger.moduloInverse(modulo: BigInteger): BigInteger {
if (modulo == ONE) return ZERO
var m = modulo
var a = this
var x0 = ZERO
var x1 = ONE
var temp: BigInteger
while (a > ONE) {
val quotient = a / m
temp = m
m = a % m
a = temp
temp = x0
x0 = x1 - quotient * x0
x1 = temp
}
return x1
}
private class Day24(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
data class Stone(val pos: List<Double>, val speed: List<Double>) {
val speedNorm by lazy {
1.0 / Math.hypot(speed[0], speed[1])
}
val x1 = pos[0]
val x2 = pos[0] + speed[0] / speedNorm
val y1 = pos[1]
val y2 = pos[1] + speed[1] / speedNorm
fun intersect2(other: Stone): List<Double> {
val x3 = other.x1
val y3 = other.y1
val x4 = other.x2
val y4 = other.y2
val div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
return listOf(
((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / div,
((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / div
)
}
}
val stones = readAsLines().map {
val all = it.splitDoubles()
Stone(all.subList(0, 3), all.subList(3, 6))
}
val rmin = if (isTest) 7.0 else 200000000000000.0
val rmax = if (isTest) 27.0 else 400000000000000.0
fun Double.inside(a: Double, b: Double): Boolean {
return (a - this) <= 1e-9 && (this - b) <= 1e-9
}
var ans = 0L
for ((a, sa) in stones.withIndex()) {
for ((b, sb) in stones.withIndex()) {
if (b > a) {
val p = sa.intersect2(sb)
if (p.any { !it.isFinite() }) {
continue
} else {
if (p[0].inside(rmin, rmax) && p[1].inside(rmin, rmax)) {
val t = p[0] - sa.pos[0]
val t2 = p[0] - sb.pos[0]
if (t.sign.toInt() == sa.speed[0].sign.toInt() && t2.sign.toInt() == sb.speed[0].sign.toInt()) {
ans++
}
}
}
}
}
}
return ans
}
fun part2(): Any {
data class Stone(val pos: List<Long>, val speed: List<Long>) {
fun posAt(t: Long): List<Long> {
return (0..2).map { pos[it] + speed[it] * t }
}
}
val stones = readAsLines().map {
val all = it.splitLongs()
Stone(all.subList(0, 3), all.subList(3, 6))
}.sortedBy { it.pos[2] }
println("test $isTest")
var limit = if (isTest) 10L else 1000L
zSpeed@ for (zSpeed in -limit..limit) {
var minPos = Long.MIN_VALUE
var maxPos = Long.MAX_VALUE
val relSpeeds = stones.mapNotNull {
val relSpeed = it.speed[2] - zSpeed
if (relSpeed >= 0) {
minPos = max(it.pos[2], minPos)
}
if (relSpeed <= 0) {
maxPos = min(it.pos[2], maxPos)
}
if (relSpeed != 0L) {
relSpeed.absoluteValue to (it.pos[2] % relSpeed.absoluteValue)
} else {
null
}
}
if (minPos > maxPos) {
continue
}
fun simplifySpeeds(l: List<Pair<Long, Long>>): List<Pair<Long, Long>>? {
val modulosByPrime = mutableMapOf<Long, Long>()
for ((prod, remain) in l) {
var prod2 = prod
val primes = mutableSetOf<Long>()
for (i in 2..Math.sqrt(prod.toDouble()).toLong()) {
while (prod2 % i == 0L) {
primes.add(i)
prod2 /= i
}
}
if (prod2 != 1L) {
primes.add(prod2)
}
for (p in primes) {
val current = modulosByPrime[p]
if (current != null && current != remain % p) {
return null
}
modulosByPrime[p] = remain % p
}
}
return modulosByPrime.toSortedMap().entries.map { it.key to it.value }
}
val simplified = simplifySpeeds(relSpeeds) ?: continue@zSpeed
val rs = simplified.map { it.first.toBigInteger() to it.second.toBigInteger() }
val crt = try {
rs.chineseRemainderTheorem()
} catch (e: Exception) {
continue@zSpeed
}
fun tryZ(zSpeed: Long, startZ: Long): Long {
val collideTime1 = (stones[0].pos[2] - startZ) / (zSpeed - stones[0].speed[2])
val collideTime2 = (stones[1].pos[2] - startZ) / (zSpeed - stones[1].speed[2])
check(stones[0].posAt(collideTime1)[2] == startZ + zSpeed * collideTime1)
val dt = collideTime2 - collideTime1
val c1 = stones[0].posAt(collideTime1)
val c2 = stones[1].posAt(collideTime2)
val xSpeed = (c2[0] - c1[0]) / dt
check(dt * xSpeed == c2[0] - c1[0]) { "$c1 $c2 $dt --> $xSpeed (${dt * xSpeed}, ${c2[0] - c1[0]})"}
val ySpeed = (c2[1] - c1[1]) / dt
check(dt * ySpeed == c2[1] - c1[1])
val xPos = c1[0] - collideTime1 * xSpeed
val yPos = c1[1] - collideTime1 * ySpeed
val me = Stone(listOf(xPos, yPos, startZ), listOf(xSpeed, ySpeed, zSpeed))
for (stone in stones) {
val collideTime = (stone.pos[2] - startZ) / (zSpeed - stone.speed[2])
check(stone.posAt(collideTime) == me.posAt(collideTime))
}
return xPos + yPos + startZ
}
try {
return tryZ(zSpeed, crt.toLong())
} catch(e: Exception) {
if(!isTest) {
e.printStackTrace()
}
println("speed $zSpeed @ $crt failed: $e")
}
}
error("No answer")
}
}
fun main() {
val testInstance = Day24(true)
val instance = Day24(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 7,764 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day24.kt | todynskyi | 573,152,718 | false | {"Kotlin": 47697} | fun main() {
fun simulate(original: List<String>, width: Int, height: Int, points: Set<Point>, end: Point, time: Int): Int =
if (points.contains(end)) time else {
val next = points.flatMap { it.neighbours() }.filter { it.valid(original, width, height, time + 1) }.toSet()
simulate(original, width, height, next, end, time + 1)
}
fun part1(input: List<String>): Int {
val width = input.first().length - 2
val height = input.size - 2
return simulate(input, width, height, setOf(Point(1, 0)), Point(width, height + 1), 0)
}
fun part2(input: List<String>): Int {
val width = input.first().length - 2
val height = input.size - 2
val start = Point(1, 0)
val end = Point(width, height + 1)
val firstTrip = simulate(input, width, height, setOf(start), end, 0)
val backTrip = simulate(input, width, height, setOf(end), start, firstTrip)
return simulate(input, width, height, setOf(start), end, backTrip)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day24_test")
check(part1(testInput) == 18)
println(part2(testInput))
val input = readInput("Day24")
println(part1(input))
println(part2(input))
}
val moves = listOf(Point(0, 0), Point(1, 0), Point(-1, 0), Point(0, 1), Point(0, -1))
val mod: (Int, Int) -> Int = { a, m ->
val remainder = (a - 1) % m
if (remainder < 0) remainder + m + 1 else remainder + 1
}
fun Point.valid(input: List<String>, width: Int, height: Int, time: Int): Boolean =
input.indices.contains(y) && input[y][x] != '#'
&& input[y][mod(x + time, width)] != '<'
&& input[y][mod(x - time, width)] != '>'
&& input[mod(y + time, height)][x] != '^'
&& input[mod(y - time, height)][x] != 'v'
fun Point.add(other: Point): Point = Point(x + other.x, y + other.y)
fun Point.neighbours(): List<Point> = moves.map { it.add(this) } | 0 | Kotlin | 0 | 0 | 5f9d9037544e0ac4d5f900f57458cc4155488f2a | 2,020 | KotlinAdventOfCode2022 | Apache License 2.0 |
app/src/main/kotlin/codes/jakob/aoc/solution/Day06.kt | loehnertz | 725,944,961 | false | {"Kotlin": 59236} | package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.middle
import codes.jakob.aoc.shared.multiply
import codes.jakob.aoc.shared.splitByLines
object Day06 : Solution() {
override fun solvePart1(input: String): Any {
/**
* Parses the race records from the [input] string.
* The [input] string is expected to be in the following format:
* ```
* Time: 7 15 30
* Distance: 9 40 200
* ```
* Each whitespace between the numbers is treated as a delimiter.
*/
fun parseRaceRecords(input: String): List<RaceRecord> {
val numberPattern = Regex("\\d+")
val (timeLine, distanceLine) = input.splitByLines()
val times: List<Long> = numberPattern.findAll(timeLine).map { it.value.toLong() }.toList()
val distances: List<Long> = numberPattern.findAll(distanceLine).map { it.value.toLong() }.toList()
return times.zip(distances) { time, distance -> RaceRecord(time, distance) }
}
return parseRaceRecords(input).map { findPossibleButtonHoldTimes(it) }.multiply()
}
override fun solvePart2(input: String): Any {
/**
* Parses the race records from the [input] string.
* The [input] string is expected to be in the following format:
* ```
* Time: 7 15 30
* Distance: 9 40 200
* ```
* The whitespace between the numbers is ignored, and the numbers are treated as a single one.
*/
fun parseRaceRecord(input: String): RaceRecord {
val numberPattern = Regex("\\d+")
val (timeLine, distanceLine) = input.splitByLines()
val time: Long = numberPattern.findAll(timeLine).map { it.value }.joinToString("").toLong()
val distance: Long = numberPattern.findAll(distanceLine).map { it.value }.joinToString("").toLong()
return RaceRecord(time, distance)
}
return findPossibleButtonHoldTimes(parseRaceRecord(input))
}
/**
* Finds the number of feasible button hold times for a given [record] to beat.
*/
private fun findPossibleButtonHoldTimes(record: RaceRecord): Long {
/**
* Calculates the distance the boat travels when the button is held for [buttonHoldTime] milliseconds.
*/
fun calculateDistance(raceRecord: RaceRecord, buttonHoldTime: Long): Long {
val timeLeft: Long = raceRecord.time - buttonHoldTime
return buttonHoldTime * timeLeft
}
val toBeEvaluatedButtonHoldTimes: ArrayDeque<Long> = ArrayDeque<Long>().also {
it.add((0..record.time).middle())
}
val evaluatedButtonHoldTimes: MutableSet<Long> = mutableSetOf()
var feasibleButtonHoldTimes: Long = 0
while (toBeEvaluatedButtonHoldTimes.isNotEmpty()) {
val buttonHoldTime: Long = toBeEvaluatedButtonHoldTimes.removeFirst().also {
evaluatedButtonHoldTimes.add(it)
}
val distance: Long = calculateDistance(record, buttonHoldTime)
if (distance > record.distance) {
feasibleButtonHoldTimes++
val next: Long = buttonHoldTime + 1
val previous: Long = buttonHoldTime - 1
if (next !in evaluatedButtonHoldTimes) toBeEvaluatedButtonHoldTimes.add(next)
if (previous !in evaluatedButtonHoldTimes) toBeEvaluatedButtonHoldTimes.add(previous)
}
}
return feasibleButtonHoldTimes
}
private data class RaceRecord(
val time: Long,
val distance: Long,
)
}
fun main() = Day06.solve()
| 0 | Kotlin | 0 | 0 | 6f2bd7bdfc9719fda6432dd172bc53dce049730a | 3,711 | advent-of-code-2023 | MIT License |
src/main/kotlin/g1901_2000/s1906_minimum_absolute_difference_queries/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1901_2000.s1906_minimum_absolute_difference_queries
// #Medium #Array #Hash_Table #2023_06_19_Time_1069_ms_(50.00%)_Space_98.7_MB_(100.00%)
import java.util.BitSet
class Solution {
private class SegmentTree(nums: IntArray, len: Int) {
class Node {
var bits: BitSet? = null
var minDiff = 0
}
var nums: IntArray
var tree: Array<Node?>
init {
this.nums = nums.copyOf(len)
tree = arrayOfNulls(4 * len)
buildTree(0, len - 1, 0)
}
private fun buildTree(i: Int, j: Int, ti: Int) {
if (i <= j) {
if (i == j) {
val node = Node()
node.bits = BitSet(101)
node.bits!!.set(nums[i])
node.minDiff = INF
tree[ti] = node
} else {
val mid = i + (j - i) / 2
buildTree(i, mid, 2 * ti + 1)
buildTree(mid + 1, j, 2 * ti + 2)
tree[ti] = combineNodes(tree[2 * ti + 1], tree[2 * ti + 2])
}
}
}
private fun combineNodes(n1: Node?, n2: Node?): Node {
val node = Node()
if (n1!!.minDiff == 1 || n2!!.minDiff == 1) {
node.minDiff = 1
} else {
node.bits = BitSet(101)
node.bits!!.or(n1.bits)
node.bits!!.or(n2.bits)
node.minDiff = findMinDiff(node.bits)
}
return node
}
private fun findMinDiff(bits: BitSet?): Int {
// minimum value of number is 1.
var first = bits!!.nextSetBit(1)
var minDiff = INF
while (first != -1) {
val next = bits.nextSetBit(first + 1)
if (next != -1) {
minDiff = Math.min(minDiff, next - first)
if (minDiff == 1) {
break
}
}
first = next
}
return minDiff
}
fun findMinAbsDiff(start: Int, end: Int, i: Int, j: Int, ti: Int): Int {
val node = findMinAbsDiff2(start, end, i, j, ti)
return if (node!!.minDiff == INF) -1 else node.minDiff
}
private fun findMinAbsDiff2(start: Int, end: Int, i: Int, j: Int, ti: Int): Node? {
if (i == start && j == end) {
return tree[ti]
}
val mid = i + (j - i) / 2
return if (end <= mid) {
findMinAbsDiff2(start, end, i, mid, 2 * ti + 1)
} else if (start >= mid + 1) {
findMinAbsDiff2(start, end, mid + 1, j, 2 * ti + 2)
} else {
val left = findMinAbsDiff2(start, mid, i, mid, 2 * ti + 1)
val right = findMinAbsDiff2(mid + 1, end, mid + 1, j, 2 * ti + 2)
combineNodes(left, right)
}
}
companion object {
const val INF = 200
}
}
fun minDifference(nums: IntArray, queries: Array<IntArray>): IntArray {
val len = nums.size
val qlen = queries.size
val st = SegmentTree(nums, len)
val answer = IntArray(qlen)
for (i in 0 until qlen) {
answer[i] = st.findMinAbsDiff(queries[i][0], queries[i][1], 0, len - 1, 0)
}
return answer
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,486 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/year2022/Day02.kt | simpor | 572,200,851 | false | {"Kotlin": 80923} | import AoCUtils
import AoCUtils.test
import Type.*
enum class Type(val score: Long) { ROCK(1L), PAPER(2L), SCISSOR(3L) }
fun main() {
val lost = 0L
val draw = 3L
val win = 6L
fun isRock(a: String) = a == "A" || a == "X"
fun isPaper(a: String) = a == "B" || a == "Y"
fun win(a: String) = a == "Z"
fun draw(a: String) = a == "Y"
fun toType(a: String) = if (isRock(a)) ROCK else if (isPaper(a)) PAPER else SCISSOR
fun part1(input: String, debug: Boolean = false): Long {
return input.lines().filter { it.isNotEmpty() }.sumOf { game ->
val a = game.split(" ")
val first = toType(a[0])
val second = toType(a[1])
when (first) {
ROCK -> when (second) {
ROCK -> second.score + draw
PAPER -> second.score + win
SCISSOR -> second.score + lost
}
PAPER -> when (second) {
ROCK -> second.score + lost
PAPER -> second.score + draw
SCISSOR -> second.score + win
}
else -> when (second) {
ROCK -> second.score + win
PAPER -> second.score + lost
SCISSOR -> second.score + draw
}
}
}
}
fun part2(input: String, debug: Boolean = false): Long {
return input.lines().filter { it.isNotEmpty() }.sumOf { game ->
val a = game.split(" ")
val first = toType(a[0])
val second = a[1]
when (first) {
ROCK -> when {
win(second) -> PAPER.score + win
draw(second) -> ROCK.score + draw
else -> SCISSOR.score + lost
}
PAPER -> when {
win(second) -> SCISSOR.score + win
draw(second) -> PAPER.score + draw
else -> ROCK.score + lost
}
SCISSOR -> when {
win(second) -> ROCK.score + win
draw(second) -> SCISSOR.score + draw
else -> PAPER.score + lost
}
}
}
}
val testInput = "A Y\n" +
"B X\n" +
"C Z\n"
val input = AoCUtils.readText("year2022/day02.txt")
part1(testInput) test Pair(15L, "test 1 part 1")
part1(input) test Pair(12535L, "part 1")
part2(testInput) test Pair(12, "test 2 part 2")
part2(input) test Pair(15457L, "part 2")
}
| 0 | Kotlin | 0 | 0 | 631cbd22ca7bdfc8a5218c306402c19efd65330b | 2,615 | aoc-2022-kotlin | Apache License 2.0 |
src/Day07.kt | sebastian-heeschen | 572,932,813 | false | {"Kotlin": 17461} | fun main() {
fun filetree(input: List<String>): Directory {
var directories = mutableListOf<Directory>()
directories.add(Directory("/"))
input.forEach { line ->
when {
line == "$ ls" -> Unit
line.startsWith("dir") -> Unit
line == "$ cd /" -> directories.removeIf { it.name != "/" }
line == "$ cd .." -> directories.removeFirst()
line.startsWith("$ cd") -> {
val name = line.substringAfterLast(" ")
val newList = listOf(directories.first().scan(name)) + directories
directories = newList.toMutableList()
}
else -> {
val size = line.substringBefore(" ").toInt()
directories.first().sizeOfFiles += size
}
}
}
val root = directories.last()
return root
}
fun part1(input: List<String>): Int {
val root = filetree(input)
return root.find { it.size <= 100000 }.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val root = filetree(input)
val unused = 70000000 - root.size
val targetSpace = 30000000 - unused
return root.find { it.size >= targetSpace }.minBy { it.size }.size
}
// 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(part1(input))
println(part2(input))
}
class Directory(val name: String) {
private val subDirectories: MutableMap<String, Directory> = mutableMapOf()
var sizeOfFiles: Int = 0
val size: Int
get() = sizeOfFiles + subDirectories.values.sumOf { it.size }
fun scan(dir: String): Directory = subDirectories.getOrPut(dir) { Directory(dir) }
fun find(predicate: (Directory) -> Boolean): List<Directory> =
subDirectories.values.filter(predicate) + subDirectories.values.flatMap { it.find(predicate) }
} | 0 | Kotlin | 0 | 0 | 4432581c8d9c27852ac217921896d19781f98947 | 2,138 | advent-of-code-2022 | Apache License 2.0 |
src/Day13/Solution.kt | cweinberger | 572,873,688 | false | {"Kotlin": 42814} | package Day13
import readInput
import toInt
import java.util.Scanner
object Solution {
fun getNextBrackets(line: String) : IntRange {
var start = -1
var end = -1
for (idx in line.indices) {
if (line[idx] == '[') {
start = idx
break
}
}
var nestedCount = 0
for (idx in line.indices) {
when (line[idx]) {
'[' -> nestedCount++
']' -> {
nestedCount--
if (nestedCount == 0) {
end = idx
break
}
}
}
}
return IntRange(start, end)
}
fun parseStringToLists(line: String) : List<Any> {
println("Parse: $line")
val range = getNextBrackets(line)
val start = range.first
val end = range.last
println("-- start: $start, end: $end")
return if (start == -1) {
line
.split(',')
.mapNotNull { it.ifEmpty { null } }
.map { it.toInt() }
.toList()
} else {
val contentStart = start + 1
val contentEnd = end - 1
val result = parseStringToLists(line.substring(contentStart .. contentEnd))
val remainder = line.substring(end + 1 until line.length)
if (remainder.isNotEmpty()) {
return listOf(result, parseStringToLists(remainder))
} else {
return result
}
}
}
fun comparePair(pair: Pair<String, String>) : Int {
return -1
}
fun parseInput(input: List<String>) : List<Pair<Any, Any>> {
return input
.chunked(3) { Pair(it[0], it[1]) }
.map { pair ->
val p = Pair(
parseStringToLists(pair.first),
parseStringToLists(pair.second),
)
println("Pair: $p")
p
}
}
fun compare(pair: Pair<Any, Any>): Int {
return 1
}
fun part1(input: List<String>) : Int {
val parsedInput = parseInput(input)
return parsedInput.mapIndexedNotNull { index, pair ->
if (compare(pair) == 1) index + 1 else null
}.sum()
}
fun part2(input: List<String>) : Int {
return 0
}
}
fun main() {
val testInput = readInput("Day13/TestInput")
val input = readInput("Day13/Input")
println("\n=== Part 1 - Test Input ===")
println(Solution.part1(testInput))
// println("\n=== Part 1 - Final Input ===")
// println(Solution.part1(input))
//
// println("\n=== Part 2 - Test Input ===")
// println(Solution.part2(testInput))
// println("\n=== Part 2 - Final Input ===")
// println(Solution.part2(input))
}
| 0 | Kotlin | 0 | 0 | 883785d661d4886d8c9e43b7706e6a70935fb4f1 | 2,901 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | mkfsn | 573,042,358 | false | {"Kotlin": 29625} | fun main() {
fun findCommonItem(vararg blocks: String): Char {
return blocks.fold(mutableMapOf<Char, Int>()) { acc, block ->
for (item in block.toCharArray().distinct()) {
acc[item] = (acc[item] ?: 0) + 1
}
acc
}.filterValues { it == blocks.size }.keys.first()
}
fun toPriority(commonItem: Char): Int = when (commonItem) {
in 'a'..'z' -> commonItem - 'a' + 1
in 'A'..'Z' -> commonItem - 'A' + 27
else -> 0
}
fun part1(input: List<String>): Int {
return input
.map { findCommonItem(*it.chunked(it.length / 2).toTypedArray()) }
.map { toPriority(it) }
.sumOf { it }
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map { findCommonItem(*it.toTypedArray()) }
.map { toPriority(it) }
.sumOf { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 8c7bdd66f8550a82030127aa36c2a6a4262592cd | 1,217 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | WaatzeG | 573,594,703 | false | {"Kotlin": 7476} | fun main() {
val testInput = readInput("Day04_input")
val solutionPart1 = part1(testInput)
println("Solution part 1: $solutionPart1")
val solutionPart2 = part2(testInput)
println("Solution part 2: $solutionPart2")
}
/**
* Count of fully overlapping schedules
*/
private fun part1(input: List<String>): Int {
return splitToRanges(input).count {
(it.first - it.second).isEmpty() || (it.second - it.first).isEmpty()
}
}
/**
* Count of overlapping schedules
*/
private fun part2(input: List<String>): Int {
return splitToRanges(input).count {
(it.first - it.second).count() < it.first.count() || (it.second - it.first).count() < it.second.count()
}
}
private fun splitToRanges(lines: List<String>): List<Pair<IntRange, IntRange>> {
return lines.map { line ->
line.split(",").let { ranges ->
ranges.map {
it.split("-").let {
IntRange(it[0].toInt(), it[1].toInt())
}
}
}.let {
it[0] to it[1]
}
}
}
| 0 | Kotlin | 0 | 0 | 324a98c51580b86121b6962651f1ba9eaad8f468 | 1,073 | advent_of_code_2022_kotlin | Apache License 2.0 |
src/main/kotlin/strategies.kt | rileynull | 448,412,739 | false | null | // Tuning parameters which control how heavily we value green matches vs yellow matches.
const val EXACT_MATCH_POINTS = 28
const val ANAGRAM_MATCH_POINTS = 10
/**
* Find a guess with letters that occur frequently in the same positions as in a lot of the remaining solutions.
*/
fun frequencyStrategy(last: String? = null, hint: List<Hint>? = null, blacklist: Set<Char>): String? {
fun filter(word: String): Boolean {
if (last == null || hint == null) return true
return isWordValid(word, last, hint, blacklist)
}
// Build occurrence counts.
val overallCounts = mutableMapOf<Char, Int>()
val countsPerPosition = mutableListOf<MutableMap<Char, Int>>(
mutableMapOf(),
mutableMapOf(),
mutableMapOf(),
mutableMapOf(),
mutableMapOf()
)
for (word in solutions.filter(::filter)) {
for (i in 0..4) {
overallCounts.merge(word[i], 1) { old, new -> old + new }
countsPerPosition[i].merge(word[i], 1) { old, new -> old + new }
}
}
// Score guesses. Yes it's actually better to restrict guesses to only valid solutions.
val scoredGuesses = solutions.filter(::filter).map { guess ->
val seenLetters = mutableSetOf<Char>()
var score = 0
for (i in 0..4) {
val exactCount = countsPerPosition[i][guess[i]] ?: 0
val anywhereCount = overallCounts[guess[i]] ?: 0
score += EXACT_MATCH_POINTS * exactCount
if (guess[i] !in seenLetters) {
score += ANAGRAM_MATCH_POINTS * (anywhereCount - exactCount)
seenLetters += guess[i]
}
}
Pair(guess, score)
}
return scoredGuesses.maxByOrNull { it.second }?.first
}
/**
* Try all of the possible guesses against all the remaining solutions and find the one with the overall most helpful hints.
*/
fun bruteScoringStrategy(last: String? = null, hint: List<Hint>? = null, blacklist: Set<Char>): String? {
fun filter(word: String): Boolean {
if (last == null || hint == null) return true
return isWordValid(word, last, hint, blacklist)
}
val validSolutions = solutions.filter(::filter)
if (validSolutions.isEmpty()) {
return null
}
return solutions.filter(::filter).maxByOrNull { guess ->
validSolutions.sumBy { solution ->
val hints = markGuess(guess, solution)
val seenYellows = mutableListOf<Char>()
hints.withIndex().sumBy { (i, hint) -> when (hint) {
Hint.GREEN -> EXACT_MATCH_POINTS
Hint.YELLOW -> {
if (solution[i] !in seenYellows) {
seenYellows += solution[i]
ANAGRAM_MATCH_POINTS
} else 0
}
else -> 0
} }
}
}
}
/**
* Try all of the possible guesses against all the remaining solutions and find the guess that minimizes the worst case
* number of solutions that could remain.
*/
fun bruteMinMaxStrategy(last: String? = null, hint: List<Hint>? = null, blacklist: Set<Char>): String? {
if (last == null || hint == null) {
return "ARISE" // Vast, vast speedup from precomputing this.
}
val validSolutions = solutions.filter { isWordValid(it, last, hint, blacklist) }
if (validSolutions.isEmpty()) {
return null
}
return solutions.filter { isWordValid(it, last, hint, blacklist) }
.minByOrNull { guess ->
validSolutions.maxOf { solution ->
val newHint = markGuess(guess, solution)
validSolutions.count { isWordValid(it, guess, newHint, blacklist) }
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Driver to auto-run through a game for a single solution word, printing the steps along the way.
fun main_() {
fun hintToString(hint: List<Hint>): String {
return hint.fold("") { acc, cur ->
acc + when (cur) {
Hint.GREEN -> "G"
Hint.YELLOW -> "Y"
Hint.GREY -> "A"
}
}
}
val answer = "COVER" // BOXER VOTER MOWER all also take the maximum guesses with this strategy
var lastGuess: String? = null
var lastHint = listOf<Hint>()
val blacklist = mutableSetOf<Char>()
while (lastHint.any { it != Hint.GREEN }) {
lastGuess = bruteMinMaxStrategy(lastGuess, lastHint, blacklist)!!
lastHint = markGuess(lastGuess, answer)
lastHint.withIndex().filter { it.value == Hint.GREY }.mapTo(blacklist) { lastGuess[it.index] }
println("Guess: $lastGuess")
println("Hint: ${hintToString(lastHint)}")
println("Blacklist: $blacklist")
}
}
// Driver to evaluate the performance of each strategy.
fun main() {
fun evaluateStrategy(bestWordStrategy: (String?, List<Hint>?, Set<Char>) -> String?) {
val roundsToCompletion = solutions.map { solution ->
val blacklist = mutableSetOf<Char>()
var lastGuess: String? = null
var lastHint: List<Hint>? = null
var rounds = 0
do {
lastGuess = bestWordStrategy(lastGuess, lastHint, blacklist)!!
lastHint = markGuess(lastGuess, solution)
lastHint.withIndex().filter { it.value == Hint.GREY }.mapTo(blacklist) { lastGuess[it.index] }
rounds++
// It can get stuck occasionally, for example on YYYYY anagrams.
if (rounds == 15) {
println("Got stuck on $solution. Penalty applied.")
rounds = 1000000
break
}
} while (lastHint!!.any { it != Hint.GREEN })
rounds
}
val average = roundsToCompletion.sum().toDouble() / roundsToCompletion.size
println("Most rounds to completion: ${roundsToCompletion.maxOrNull()}")
println("Least rounds to completion: ${roundsToCompletion.minOrNull()}")
println("Average rounds to completion: $average")
}
// for (i in 0..20) {
// println("Trying EXACT_MATCH_POINTS = $EXACT_MATCH_POINTS.")
// evaluateStrategy(::bruteScoringStrategy)
// EXACT_MATCH_POINTS++
// }
println("Frequency strategy...")
evaluateStrategy(::frequencyStrategy)
println("--------------------------------------------------")
println("Brute scoring strategy...")
evaluateStrategy(::bruteScoringStrategy)
println("--------------------------------------------------")
println("Brute minmax strategy...")
evaluateStrategy(::bruteMinMaxStrategy)
println("--------------------------------------------------")
}
// Driver to evaluate the strength of each starting word with bruteScoringStrategy.
fun main__() {
guesses.forEach { guess ->
val score = solutions.sumBy { solution ->
val hints = markGuess(guess, solution)
val seenYellows = mutableListOf<Char>()
hints.withIndex().sumBy { (i, hint) -> when (hint) {
Hint.GREEN -> EXACT_MATCH_POINTS
Hint.YELLOW -> {
if (solution[i] !in seenYellows) {
seenYellows += solution[i]
ANAGRAM_MATCH_POINTS
} else {
0
}
}
else -> 0
} }
}
println("$score $guess")
}
} | 0 | Kotlin | 0 | 0 | 9e92a16e9ad517b5afda7c70899bd0c67fd0e0a0 | 7,851 | wordle-kot | Apache License 2.0 |
day7/src/main/kotlin/com/lillicoder/adventofcode2023/day7/Day7.kt | lillicoder | 731,776,788 | false | {"Kotlin": 98872} | package com.lillicoder.adventofcode2023.day7
fun main() {
val day7 = Day7()
val parser = HandParser()
val (hands, jokerHands) = parser.parseFile("input.txt")
println("[Normal] Total winnings for the given hands is ${day7.part1(hands)}.")
println("[Jokers] Total winnings for the given hands is ${day7.part2(jokerHands)}.")
}
class Day7 {
fun part1(hands: List<Hand>) = WinningsCalculator().computeWinnings(hands)
fun part2(hands: List<Hand>) = WinningsCalculator().computeWinnings(hands)
}
/**
* Represents a single card in a hand of a game of Camel Cards.
*/
enum class Card(
private val symbol: String,
) {
JOKER("J"),
TWO("2"),
THREE("3"),
FOUR("4"),
FIVE("5"),
SIX("6"),
SEVEN("7"),
EIGHT("8"),
NINE("9"),
TEN("T"),
JACK("J"),
QUEEN("Q"),
KING("K"),
ACE("A"), ;
companion object {
/**
* Gets the [Card] enum matching the given symbol.
* @param symbol Card symbol.
* @param allowJokers True if 'J' should match [JOKER], false if 'J' should match [JACK].
* @return Corresponding card.
*/
fun from(
symbol: String,
allowJokers: Boolean = false,
) = when (symbol) {
"J" -> if (allowJokers) JOKER else JACK
else -> entries.find { it.symbol == symbol }!!
}
}
}
/**
* Represents the rank of a hand in a game of Camel Cards.
*/
enum class Rank {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND,
}
/**
* Represents a hand in a game of Camel Cards.
*/
data class Hand(
val cards: List<Card>,
val bid: Int,
val rank: Rank,
) : Comparable<Hand> {
override fun compareTo(other: Hand) =
when (val rankComparison = rank.compareTo(other.rank)) {
0 -> compareCards(other) // Same rank, sort by strongest card
else -> rankComparison // Different rank, sort by rank
}
/**
* Compares each card in this hand with the cards in the given [Hand].
* @param other Hand to compare.
* @return 1 if this hand's cards are stronger than the other's, -1 if the given hand's
* cards are stronger, or 0 if the cards are identical.
*/
private fun compareCards(other: Hand): Int {
// Walk each card position in order to find the stronger card
cards.zip(other.cards).forEach {
val cardComparison = it.first.compareTo(it.second)
if (cardComparison != 0) return cardComparison
}
// Identical cards
return 0
}
}
/**
* Calculates winnings for a given list of [Hand] in a game of Camel Cards.
*/
class WinningsCalculator {
/**
* Determines the total winnings for the give list of [Hand].
* @param hands Hands to evaluate.
* @return Total winnings.
*/
fun computeWinnings(hands: List<Hand>) =
hands.sorted().mapIndexed { index, hand ->
(index + 1) * hand.bid
}.sum().toLong()
}
/**
* Parses one or more [Hand] from some input.
*/
class HandParser {
/**
* Parses the raw hands input to a pair of list of [Hand].
* @param raw Raw hands input.
* @return Hands parsed as no having [Card.JOKER] and hands parsed as having [Card.JOKER].
*/
fun parse(raw: List<String>): Pair<List<Hand>, List<Hand>> {
val noJokers =
raw.map { line ->
val parts = line.split(" ")
val cards = parts[0].split("").filter { it.isNotEmpty() }.map { Card.from(it, false) }
val bid = parts[1].toInt()
val rank = rank(cards)
Hand(cards, bid, rank)
}
val jokers =
noJokers.map { hand ->
// Swap Jokers in for Jacks and recompute the rank
val cards = hand.cards.map { if (it == Card.JACK) Card.JOKER else it }
val rank = rank(cards)
Hand(cards, hand.bid, rank)
}
return Pair(noJokers, jokers)
}
/**
* Parses the file with the given filename to a pair of list of [Hand].
* @param filename Filename of the file to parse.
* @return Hands parsed as no having [Card.JOKER] and hands parsed as having [Card.JOKER].
*/
fun parseFile(filename: String) = parse(javaClass.classLoader.getResourceAsStream(filename)!!.reader().readLines())
/**
* Determines the [Rank] of the given list of [Card].
* @param cards Cards to rank.
* @return Rank.
*/
private fun rank(cards: List<Card>): Rank {
// Count each card type by its frequency
val frequency = cards.groupingBy { it }.eachCount()
val noJokers = frequency.filterKeys { it != Card.JOKER }
val biggestCount = if (noJokers.isEmpty()) 0 else noJokers.maxBy { it.value }.value
val jokerCount = frequency[Card.JOKER] ?: 0
if (isFiveOfAKind(frequency, jokerCount, biggestCount)) return Rank.FIVE_OF_A_KIND
if (isFourOfAKind(frequency, jokerCount, biggestCount)) return Rank.FOUR_OF_A_KIND
if (isFullHouse(frequency, jokerCount, biggestCount)) return Rank.FULL_HOUSE
if (isThreeOfAKind(frequency, jokerCount, biggestCount)) return Rank.THREE_OF_A_KIND
if (isTwoPair(frequency, jokerCount, biggestCount)) return Rank.TWO_PAIR
if (isOnePair(frequency, jokerCount, biggestCount)) return Rank.ONE_PAIR
// High card - only option left (should have grouped 5 keys)
return Rank.HIGH_CARD
}
private fun isFiveOfAKind(
frequency: Map<Card, Int>,
jokerCount: Int,
biggestCount: Int,
): Boolean {
// Case 1: no jokers, all the same card
// 1 1 1 1 1
val allSame = frequency.size == 1
// Case 2: any amount of jokers, jokers count plus biggest count = hand size
// J 1 1 1 1
// J J 1 1 1
// J J J 1 1
// J J J J 1
return allSame || (jokerCount + biggestCount == frequency.values.sum())
}
private fun isFourOfAKind(
frequency: Map<Card, Int>,
jokerCount: Int,
biggestCount: Int,
): Boolean {
// Case 1: no jokers, 4 of one kind of card (4 jokers makes 5 of a kind, so don't need to check that)
// 1111 5
val hasFourSameCards = frequency.values.find { it == 4 } != null
// Case 2: has 3 jokers and two other distinct cards (frequency == 3)
// JJJ 1 5
val hasThreeJokersAndTwoOtherDistinct = jokerCount == 3 && frequency.size == 3
// Case 3: has 2 jokers and two other distinct card types w/ at least 2 of one of those
// JJ 11 5
val hasTwoJokersAndTwoSameCards = jokerCount == 2 && frequency.size == 3 && biggestCount == 2
// Case 4: has 1 joker and two other distinct card types w/ at least 3 of one of those
// J 111 5
val hasOneJokerAndThreeSameCards = jokerCount == 1 && frequency.size == 3 && biggestCount == 3
return hasFourSameCards ||
hasThreeJokersAndTwoOtherDistinct ||
hasTwoJokersAndTwoSameCards ||
hasOneJokerAndThreeSameCards
}
private fun isFullHouse(
frequency: Map<Card, Int>,
jokerCount: Int,
biggestCount: Int,
): Boolean {
// Case 1: no jokers, 3 of one kind of card, 2 of another
// 111 55
val hasThreeAndTwo = jokerCount == 0 && biggestCount == 3 && frequency.size == 2
// Case 2: has 1 joker and two pair (joker matches with other of the pair for full house)
// J 11 55
val hasOneJokerAndTwoPair = jokerCount == 1 && biggestCount == 2 && frequency.size == 3
return hasThreeAndTwo || hasOneJokerAndTwoPair
}
private fun isThreeOfAKind(
frequency: Map<Card, Int>,
jokerCount: Int,
biggestCount: Int,
): Boolean {
// Case 1: no jokers, 3 of one kind of card nd two other distinct cards
// 111 5 9
val hasThreeAndTwoOtherDistinct = jokerCount == 0 && biggestCount == 3 && frequency.size == 3
// Case 2: has 1 joker, a pair of one kind of card and two other distinct cards
// J11 5 9
val hasOneJokerAndOnePair = jokerCount == 1 && biggestCount == 2 && frequency.size == 4
// Case 3: has 2 jokers and 3 other distinct cards (joker match with any card to make three of a kind)
// JJ1 5 9
val hasTwoJokersAndThreeDistinct = jokerCount == 2 && biggestCount == 1 && frequency.size == 4
return hasThreeAndTwoOtherDistinct || hasOneJokerAndOnePair || hasTwoJokersAndThreeDistinct
}
private fun isTwoPair(
frequency: Map<Card, Int>,
jokerCount: Int,
biggestCount: Int,
): Boolean {
// Case 1: no jokers, two pairs of cards with one extra distinct card
// 11 55 9
val hasTwoPairAndOneDistinct = jokerCount == 0 && biggestCount == 2 && frequency.size == 3
return hasTwoPairAndOneDistinct
}
private fun isOnePair(
frequency: Map<Card, Int>,
jokerCount: Int,
biggestCount: Int,
): Boolean {
// Case 1: no jokers, one pair and 3 distinct other cards
// 11 5 6 9
val hasOnePairAndThreeDistinct = jokerCount == 0 && biggestCount == 2 && frequency.size == 4
// Case 2: one joker, 4 distinct other cards (joker matches with any for a pair)
// J 1 5 6 9
val hasOneJokerAndFourDistinct = jokerCount == 1 && frequency.size == 5
return hasOnePairAndThreeDistinct || hasOneJokerAndFourDistinct
}
}
| 0 | Kotlin | 0 | 0 | 390f804a3da7e9d2e5747ef29299a6ad42c8d877 | 9,655 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/com/ab/advent/day02/Models.kt | battagliandrea | 574,137,910 | false | {"Kotlin": 27923} | package com.ab.advent.day02
import java.lang.IllegalArgumentException
// A. ROCK
// B. PAPER
// C. SCISSORS
// X. ROCK
// Y. PAPER
// Z. SCISSORS
// 1. Mappare l'input in un torneo che è una lista di round di shape
// 2. Dare un punteggio a quella determinata HandShape
// 3. Decretare il mio punteggio calcolandolo per ogni riga
enum class Output(val score: Int){
WIN(6),
DRAW(3),
LOSE(0);
fun inverse() = when (this){
WIN -> LOSE
DRAW -> DRAW
LOSE -> WIN
}
}
sealed class HandShape(val score: Int){
object Rock: HandShape(1)
object Paper: HandShape(2)
object Scissors: HandShape(3)
fun evaluate(other: HandShape): Output = when{
this == other -> Output.DRAW
this == Rock && other == Scissors -> Output.WIN
this == Scissors && other == Paper -> Output.WIN
this == Paper && other == Rock -> Output.WIN
else -> Output.LOSE
}
}
data class Result(val output1: Output, val output2: Output)
data class Round(
val left: HandShape,
val right: HandShape,
){
val result: Result = left.evaluate(right).let { output -> Result(output, output.inverse()) }
}
data class Tournament(
val rounds: List<Round>
){
val totalScore = rounds.sumOf { it.right.score + it.result.output2.score }
}
fun String.toShape(): HandShape = when(this){
"A", "X" -> HandShape.Rock
"B", "Y" -> HandShape.Paper
"C", "Z" -> HandShape.Scissors
else -> throw IllegalArgumentException()
}
fun String.toOutuput(): Output = when(this){
"X" -> Output.LOSE
"Y" -> Output.DRAW
"Z" -> Output.WIN
else -> throw IllegalArgumentException()
}
object Strategy {
private val scenarios: List<Round> = buildList {
val shapes: List<HandShape> = listOf(HandShape.Rock, HandShape.Paper, HandShape.Scissors)
lazyCartesianProduct(shapes, shapes).forEach { pair -> add(Round(left = pair.first, right = pair.second)) }
}
fun find(shape1: HandShape, shape2: HandShape): Round =
scenarios.single { it.left == shape1 && it.right == shape2 }
fun find(shape1: HandShape, shape2: Output): Round =
scenarios.single { it.left == shape1 && it.result.output2 == shape2 }
}
private fun <A, B> lazyCartesianProduct(
listA: Iterable<A>,
listB: Iterable<B>
): Sequence<Pair<A, B>> =
sequence {
listA.forEach { a ->
listB.forEach { b ->
yield(a to b)
}
}
}
fun List<List<String>>.toTournament1(): Tournament =
this.map { Strategy.find(it[0].toShape(), it[1].toShape()) }.let(::Tournament)
fun List<List<String>>.toTournament2(): Tournament =
this.map { Strategy.find(it[0].toShape(), it[1].toOutuput()) }.let(::Tournament)
| 0 | Kotlin | 0 | 0 | cb66735eea19a5f37dcd4a31ae64f5b450975005 | 2,755 | Advent-of-Kotlin | Apache License 2.0 |
src/Day02/Day02.kt | Trisiss | 573,815,785 | false | {"Kotlin": 16486} | fun main() {
operator fun String.component1() = this[0]
operator fun String.component2() = this[1]
operator fun String.component3() = this[2]
fun Char.toShape(): Shape = when (this) {
'A', 'X' -> Shape.Rock()
'B', 'Y' -> Shape.Paper()
'C', 'Z' -> Shape.Scissors()
else -> error("Unexpected char $this")
}
fun Pair<Shape, Shape>.getScore(): Int = second.getWinnerScore(first) + second.selectScore
fun part1(input: List<String>): Int = input.sumOf { s ->
val (theirShape, _, myShape) = s
(theirShape.toShape() to myShape.toShape()).getScore()
}
fun part2(input: List<String>): Int = input.sumOf { s ->
val (therShape, _, resultRound) = s
therShape.toShape().getWinnerScore(resultRound)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02/Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02/Day02")
println(part1(input))
println(part2(input))
}
private sealed interface Shape {
fun getWinnerScore(other: Shape): Int
fun getWinnerScore(resultRound: Char): Int
val selectScore: Int
class Rock : Shape {
override val selectScore = 1
override fun getWinnerScore(other: Shape): Int = when (other) {
is Rock -> 3
is Scissors -> 6
else -> 0
}
override fun getWinnerScore(resultRound: Char): Int = when (resultRound) {
'X' -> Scissors().run { selectScore + this.getWinnerScore(this@Rock) }
'Y' -> Rock().run { selectScore + this.getWinnerScore(this@Rock) }
else -> Paper().run { selectScore + this.getWinnerScore(this@Rock) }
}
}
class Paper : Shape {
override val selectScore = 2
override fun getWinnerScore(other: Shape): Int = when (other) {
is Paper -> 3
is Rock -> 6
else -> 0
}
override fun getWinnerScore(resultRound: Char): Int = when (resultRound) {
'X' -> Rock().run { selectScore + this.getWinnerScore(this@Paper) }
'Y' -> Paper().run { selectScore + this.getWinnerScore(this@Paper) }
else -> Scissors().run { selectScore + this.getWinnerScore(this@Paper) }
}
}
class Scissors : Shape {
override val selectScore = 3
override fun getWinnerScore(other: Shape): Int = when (other) {
is Scissors -> 3
is Paper -> 6
else -> 0
}
override fun getWinnerScore(resultRound: Char): Int = when (resultRound) {
'X' -> Paper().run { selectScore + this.getWinnerScore(this@Scissors) }
'Y' -> Scissors().run { selectScore + this.getWinnerScore(this@Scissors) }
else -> Rock().run { selectScore + this.getWinnerScore(this@Scissors) }
}
}
}
| 0 | Kotlin | 0 | 0 | cb81a0b8d3aa81a3f47b62962812f25ba34b57db | 2,960 | AOC-2022 | Apache License 2.0 |
src/Day03.kt | mcrispim | 573,449,109 | false | {"Kotlin": 46488} | fun main() {
fun priority(item: Char): Int {
return when (item) {
in 'a'..'z' -> item - 'a' + 1
in 'A'..'Z' -> item - 'A' + 27
else -> 0
}
}
fun part1(input: List<String>): Int = input.sumOf {
val partSize = it.length / 2
val compartment1 = it.substring(0 until partSize).toSet()
val compartment2 = it.substring(partSize until it.length).toSet()
val inBothList = compartment1.intersect(compartment2).toList()
priority(inBothList.first()) // because we now that there is only one item
}
fun part2(input: List<String>): Int {
var sum = 0
for(i in input.indices step 3) {
val elf1 = input[i + 0].toSet()
val elf2 = input[i + 1].toSet()
val elf3 = input[i + 2].toSet()
sum += priority(elf1.intersect(elf2).intersect(elf3).toList().first())
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5fcacc6316e1576a172a46ba5fc9f70bcb41f532 | 1,227 | AoC2022 | Apache License 2.0 |
src/day13/Day13.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day13
import readInput
fun readToPacket(chars: String): BasePacket {
if (chars.isEmpty()) {
return PacketList(mutableListOf())
}
if (chars.toIntOrNull() != null) {
return Packet(chars.toInt())
}
return PacketList(readNestedList(chars))
}
fun readNestedList(chars: String): List<BasePacket> {
val substring = chars.substring(1, chars.length - 1)
return buildList {
var index = 0
while (index < substring.length) {
if (substring[index] == '[') {
val parenthesisEnd = findParenthesisEnd(index, substring)
add(readToPacket(substring.substring(index, parenthesisEnd)))
index = parenthesisEnd + 1
} else {
var intEnd = substring.indexOf(',', startIndex = index + 1)
if (intEnd == -1) {
intEnd = substring.length
}
add(readToPacket(substring.substring(index, intEnd)))
index = intEnd + 1
}
}
}
}
fun findParenthesisEnd(start: Int, substring: String): Int {
var parenthesisCount = 1
var index = start + 1
while (parenthesisCount != 0) {
if (substring[index] == '[') {
parenthesisCount++
}
if (substring[index] == ']') {
parenthesisCount--
}
index++
}
return index
}
fun main() {
fun part1(input: List<String>): Int {
return input.windowed(2, 3).map { (first, second) ->
readToPacket(first) to readToPacket(second)
}.mapIndexed { i, (first, second) ->
if (first < second) {
i + 1
} else {
0
}
}.sum()
}
fun part2(input: List<String>): Int {
val additionalPacket1 = readToPacket("[[2]]")
val additionalPacket2 = readToPacket("[[6]]")
val sorted = input.filter {
it.isNotBlank()
}.map {
readToPacket(it)
}.toMutableList().apply {
add(additionalPacket1)
add(additionalPacket2)
}.sorted()
return (sorted.indexOf(additionalPacket1) + 1) * (sorted.indexOf(additionalPacket2) + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day13/Day13_test")
println(part1(testInput))
check(part1(testInput) == 13)
val input = readInput("day13/Day13")
println(part1(input))
println(part2(input))
}
sealed class BasePacket : Comparable<BasePacket>
class PacketList(
private val subLists: List<BasePacket>
) : BasePacket() {
override fun compareTo(other: BasePacket): Int {
return when (other) {
is PacketList -> {
this.subLists.zip(other.subLists).forEach { (first, second) ->
val compareTo = first.compareTo(second)
if (compareTo != 0) {
return compareTo
}
}
return subLists.size.compareTo(other.subLists.size)
}
is Packet -> {
this.compareTo(PacketList(listOf(other)))
}
}
}
override fun toString(): String = subLists.toString()
}
class Packet(
private val num: Int
) : BasePacket() {
override fun compareTo(other: BasePacket): Int {
return when (other) {
is PacketList -> PacketList(listOf(this)).compareTo(other)
is Packet -> {
this.num.compareTo(other.num)
}
}
}
override fun toString(): String = num.toString()
}
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 3,670 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day04.kt | winnerwinter | 573,917,144 | false | {"Kotlin": 20685} | fun main() {
fun String.toElfPair(): Pair<IntRange, IntRange> {
val (elfA, elfB) = this.split(",").map { sections ->
val (low, high) = sections.split("-")
low.toInt()..high.toInt()
}
return elfA to elfB
}
fun isOverlap(elfA: IntRange, elfB: IntRange): Boolean =
(elfA intersect elfB).let { it == elfA.toSet() || it == elfB.toSet() }
fun containsOverlap(elfA: IntRange, elfB: IntRange): Boolean =
(elfA intersect elfB).isNotEmpty()
fun countFreeloadingPartners(
elves: List<Pair<IntRange, IntRange>>,
determineFreeloading: (IntRange, IntRange) -> Boolean
): Int =
elves.sumOf { (elfA, elfB) -> if (determineFreeloading(elfA, elfB)) 1 else 0 as Int }
fun part1(): Int {
val testInput = readInput("Day04_test")
val test_ans = countFreeloadingPartners(testInput.map { it.toElfPair() }, ::isOverlap)
check(test_ans == 2)
val input = readInput("Day04")
val ans = countFreeloadingPartners(input.map { it.toElfPair() }, ::isOverlap)
return ans
}
fun part2(): Int {
val testInput = readInput("Day04_test")
val test_ans = countFreeloadingPartners(testInput.map { it.toElfPair() }, ::containsOverlap)
check(test_ans == 4)
val input = readInput("Day04")
val ans = countFreeloadingPartners(input.map { it.toElfPair() }, ::containsOverlap)
return ans
}
println(part1())
println(part2())
}
| 0 | Kotlin | 0 | 0 | a019e5006998224748bcafc1c07011cc1f02aa50 | 1,517 | advent-of-code-22 | Apache License 2.0 |
src/Day11.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | private interface Item {
infix fun divisibleBy(divisor: Int): Boolean
}
private interface ItemCompanion {
fun createItem(s: String): Item
fun add(one: Item, two: Item): Item
fun multiply(one: Item, two: Item): Item
}
private class Monkey(
val items: MutableList<Item>,
val divisor: Int,
val operation: (Item, Item) -> Item,
val leftOperand: Item?,
val rightOperand: Item?,
val successMonkey: Int,
val failureMonkey: Int
) {
override fun toString(): String {
return "$items, $divisor, $leftOperand, $rightOperand, $successMonkey, $failureMonkey"
}
}
private data class ItemAsMods(val mods: List<Int>) : Item {
override fun divisibleBy(divisor: Int): Boolean {
return mods[divisor] == 0
}
companion object : ItemCompanion {
override fun createItem(s: String): Item {
val v = s.trim().toInt()
return ItemAsMods(generateAllMods(v))
}
fun generateAllMods(value: Int): List<Int> {
return (0..20).map { if (it > 0) value % it else 0 }.toList()
}
override fun add(one: Item, two: Item): Item {
one as ItemAsMods
two as ItemAsMods
return one.mods.zip(two.mods).withIndex()
.map { p -> if (p.index == 0) 0 else (p.value.first + p.value.second) % p.index }
.let { mods -> ItemAsMods(mods) }
}
override fun multiply(one: Item, two: Item): Item {
one as ItemAsMods
two as ItemAsMods
return one.mods.zip(two.mods).withIndex()
.map { p -> if (p.index == 0) 0 else (p.value.first * p.value.second) % p.index }
.let { mods -> ItemAsMods(mods) }
}
}
}
private data class SimpleItem(val value: Int) : Item {
override infix fun divisibleBy(divisor: Int): Boolean {
return value % divisor == 0
}
companion object : ItemCompanion {
override fun createItem(s: String): Item {
val v = s.trim().toInt()
return SimpleItem(v)
}
override fun add(one: Item, two: Item): Item {
one as SimpleItem
two as SimpleItem
return SimpleItem((one.value + two.value) / 3)
}
override fun multiply(one: Item, two: Item): Item {
one as SimpleItem
two as SimpleItem
return SimpleItem((one.value * two.value) / 3)
}
}
}
fun main() {
fun solve(rounds: Int, monkeys: List<Monkey>): Long {
val inspectionCount = Array(monkeys.size) { 0 }
repeat(rounds) {
for (monkey in monkeys.withIndex()) {
val m = monkey.value
inspectionCount[monkey.index] += m.items.size
for (item in m.items) {
val left = m.leftOperand ?: item
val right = m.rightOperand ?: item
val worry = m.operation(left, right)
if (worry divisibleBy m.divisor) {
monkeys[m.successMonkey].items += worry
} else {
monkeys[m.failureMonkey].items += worry
}
}
m.items.clear()
}
}
val sortedList = inspectionCount.toList().sortedDescending()
return 1L * sortedList[0] * sortedList[1]
}
fun initMonkeys(input: List<String>, itemCompanion: ItemCompanion): List<Monkey> {
val monkeys = mutableListOf<Monkey>()
input.chunked(7).forEach {
val items = it[1].substringAfter(": ").split(",")
.map { str -> itemCompanion.createItem(str) }
.toMutableList()
val divisor = it[3].substringAfter("by ").trim().toInt()
val (left, op, right) = it[2].substringAfter("= ").split(" ")
val successMonkey = it[4].substringAfter("monkey ").trim().toInt()
val failureMonkey = it[5].substringAfter("monkey ").trim().toInt()
monkeys += Monkey(
items,
divisor,
if (op == "+") itemCompanion::add else itemCompanion::multiply,
if (left == "old") null else itemCompanion.createItem(left),
if (right == "old") null else itemCompanion.createItem(right),
successMonkey,
failureMonkey
)
}
return monkeys
}
fun solvePart1(input: List<String>) {
val rounds = 20
println(solve(rounds, initMonkeys(input, SimpleItem.Companion)))
}
fun solvePart2(input: List<String>) {
val rounds = 10000
println(solve(rounds, initMonkeys(input, ItemAsMods.Companion)))
}
val input = readInput("Day11_input")
solvePart1(input)
solvePart2(input)
} | 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 4,852 | aoc-2022 | Apache License 2.0 |
src/Day08.kt | mihansweatpants | 573,733,975 | false | {"Kotlin": 31704} | fun main() {
fun part1(grid: List<List<Int>>): Int {
var visibleTreesCount = 0
for (rowIndex in grid.indices) {
for (columnIndex in grid[rowIndex].indices) {
if (isExteriorCell(rowIndex, columnIndex, grid)) {
visibleTreesCount++
} else {
val currCell = grid[rowIndex][columnIndex]
val maxFromUp = grid.getMaxInColumn(columnIndex, 0, rowIndex - 1)
val maxFromDown = grid.getMaxInColumn(columnIndex, rowIndex + 1, grid.lastIndex)
val maxFromLeft = grid.getMaxInRow(rowIndex, 0, columnIndex - 1)
val maxFromRight = grid.getMaxInRow(rowIndex, columnIndex + 1, grid[rowIndex].lastIndex)
if (minOf(maxFromUp, maxFromDown, maxFromLeft, maxFromRight) < currCell) {
visibleTreesCount++
}
}
}
}
return visibleTreesCount
}
fun part2(grid: List<List<Int>>): Int {
var highestScore = 0
for (rowIndex in grid.indices) {
for (columnIndex in grid.indices) {
if (isExteriorCell(rowIndex, columnIndex, grid)) continue
val up = grid.countVisibleTreesInColumn(rowIndex, columnIndex, rowIndex - 1 downTo 0)
val down = grid.countVisibleTreesInColumn(rowIndex, columnIndex, rowIndex + 1..grid.lastIndex)
val left = grid.countVisibleTreesInRow(rowIndex, columnIndex, columnIndex - 1 downTo 0)
val right = grid.countVisibleTreesInRow(rowIndex, columnIndex, columnIndex + 1..grid[rowIndex].lastIndex)
highestScore = maxOf(highestScore, up * down * left * right)
}
}
return highestScore
}
val input = readInput("Day08")
.lines()
.map {
it.split("")
.filterNot(String::isBlank)
.map(String::toInt)
}
println(part1(input))
println(part2(input))
}
private fun isExteriorCell(rowIndex: Int, columnIndex: Int, grid: List<List<Int>>): Boolean {
return rowIndex == grid.indices.first ||
rowIndex == grid.indices.last ||
columnIndex == grid[rowIndex].indices.first ||
columnIndex == grid[rowIndex].indices.last
}
private fun List<List<Int>>.getMaxInRow(rowIndex: Int, leftBound: Int, rightBound: Int): Int {
var max = Int.MIN_VALUE
for (i in leftBound..rightBound) {
max = maxOf(max, this[rowIndex][i])
}
return max
}
private fun List<List<Int>>.getMaxInColumn(columnIndex: Int, topBound: Int, bottomBound: Int): Int {
var max = Int.MIN_VALUE
for (i in topBound..bottomBound) {
max = maxOf(max, this[i][columnIndex])
}
return max
}
private fun List<List<Int>>.countVisibleTreesInRow(
rowIndex: Int,
columnIndex: Int,
indexRange: IntProgression
): Int {
val currentTreeHeight = this[rowIndex][columnIndex]
var count = 0
for (i in indexRange) {
count++
if (currentTreeHeight <= this[rowIndex][i]) break
}
return count
}
private fun List<List<Int>>.countVisibleTreesInColumn(
rowIndex: Int,
columnIndex: Int,
indexRange: IntProgression
): Int {
val currentTreeHeight = this[rowIndex][columnIndex]
var count = 0
for (i in indexRange) {
count++
if (currentTreeHeight <= this[i][columnIndex]) break
}
return count
}
| 0 | Kotlin | 0 | 0 | 0de332053f6c8f44e94f857ba7fe2d7c5d0aae91 | 3,516 | aoc-2022 | Apache License 2.0 |
src/Day11.kt | sebokopter | 570,715,585 | false | {"Kotlin": 38263} | import java.math.BigInteger
fun main() {
fun parseInput(input: String): Pair<List<List<BigInteger>>, List<Inspection>> {
val monkeyInputs = input.split("\n\n")
val items = monkeyInputs.map { it ->
val lines = it.lines().map { it.trim() }
return@map lines[1].substringAfter(": ").split(", ").map { it.toBigInteger() }
}
val inspections = monkeyInputs.map { monkeyInput ->
val lines = monkeyInput.lines().map { it.trim() }
val operationElements = lines[2].substringAfter(" = ").split(" ")
val operation = Operation(operationElements[1], operationElements[0], operationElements[2])
val divisionOperator = lines[3].split(" by ").last().toBigInteger()
val testSuccess = lines[4].split(" monkey ").last().toInt()
val testFail = lines[5].split(" monkey ").last().toInt()
Inspection(operation, Route(divisionOperator, testSuccess, testFail))
}
return items to inspections
}
fun keepAway(items: List<List<BigInteger>>, inspections: List<Inspection>, rounds: Int, worryLevel: Int): List<BigInteger> {
val mutableItems = items.map { it.toMutableList() }.toMutableList()
val mutableInspection = inspections.toMutableList()
val maxModulo: Int = inspections.fold(1) { acc, it -> it.route.divisionOperator.toInt() * acc }
val inspectionCounter = MutableList(mutableInspection.size) { 0.toBigInteger() }
for (round in 1..rounds) {
for ((monkey, inspection) in mutableInspection.withIndex()) {
for (item in mutableItems[monkey]) {
val (operand, operator1String, operator2String) = inspection.operation
val operator1 = if (operator1String == "old") item else operator1String.toBigInteger()
val operator2 = if (operator2String == "old") item else operator2String.toBigInteger()
val route = inspection.route
val newItem = when (operand) {
"*" -> operator1 * operator2
"+" -> operator1 + operator2
else -> error("Operation $operand not supported")
}.div(worryLevel.toBigInteger())
val newMonkey = if (newItem % route.divisionOperator == 0.toBigInteger()) route.onSuccess
else route.onFailure
mutableItems[monkey] = mutableListOf()
mutableItems[newMonkey].add(newItem % maxModulo.toBigInteger())
inspectionCounter[monkey] = inspectionCounter[monkey] + 1.toBigInteger()
}
}
}
return inspectionCounter.toList()
}
fun monkeyBusiness(inspectionCounter: List<BigInteger>): BigInteger =
inspectionCounter.sorted().reversed().take(2).reduce { first, second -> first * second }
fun part1(input: String): BigInteger {
val rounds = 20
val worryLevel = 3
val (items, inspections) = parseInput(input)
val inspectionCounter = keepAway(items, inspections, rounds, worryLevel)
return monkeyBusiness(inspectionCounter)
}
fun part2(input: String): BigInteger {
val rounds = 10_000
val worryLevel = 1
val (items, inspections) = parseInput(input)
val inspectionCounter = keepAway(items, inspections, rounds, worryLevel)
return monkeyBusiness(inspectionCounter)
}
val testInput = readTextInput("Day11_test")
println("part1(testInput): " + part1(testInput))
println("part2(testInput): " + part2(testInput))
check(part1(testInput) == 10605.toBigInteger())
check(part2(testInput) == 2713310158.toBigInteger())
val input = readTextInput("Day11")
println("part1(input): " + part1(input))
println("part2(input): " + part2(input))
}
data class Inspection(val operation: Operation, val route: Route)
data class Operation(val operand: String, val operator1: String, val operator2: String)
data class Route(val divisionOperator: BigInteger, val onSuccess: Int, val onFailure: Int) | 0 | Kotlin | 0 | 0 | bb2b689f48063d7a1b6892fc1807587f7050b9db | 4,156 | advent-of-code-2022 | Apache License 2.0 |
cz.wrent.advent/Day8.kt | Wrent | 572,992,605 | false | {"Kotlin": 206165} | package cz.wrent.advent
fun main() {
println(partOne(test))
val result = partOne(input)
println("8a: $result")
println(partTwo(test))
val resultTwo = partTwo(input)
println("8b: $resultTwo")
}
private fun partOne(input: String): Long {
val map = input.parse()
val visible = mutableSetOf<Pair<Int, Int>>()
processDirectionFromZero(map, visible)
processDirectionFromZero(map, visible, true)
processDirectionToZero(map, visible)
processDirectionToZero(map, visible, true)
return visible.size.toLong()
}
private fun partTwo(input: String): Long {
val map = input.parse()
val scenicMap = map.map { it.key to getScenicScore(it.key, map) }.toMap()
println(scenicMap)
return scenicMap.values.maxByOrNull { it }!!.toLong()
}
private fun getScenicScore(coord: Pair<Int, Int>, map: Map<Pair<Int, Int>, Int>): Int {
val current = map[coord]!!
val a = map.getRightFrom(coord).getVisible(current)
val b = map.getLeftFrom(coord).getVisible(current)
val c = map.getUpFrom(coord).getVisible(current)
val d = map.getDownFrom(coord).getVisible(current)
return a * b * c * d
}
private fun List<Int>.getVisible(current: Int): Int {
val res = this.takeWhile{ it < current }.size
if (res == this.size) {
return res
} else {
return res + 1
}
}
private fun Map<Pair<Int, Int>, Int>.getRightFrom(coord: Pair<Int, Int>): List<Int> {
return this.filter { it.key.second == coord.second }
.filter { it.key.first > coord.first }.entries.sortedBy { it.key.first }.map { it.value }.toList()
}
private fun Map<Pair<Int, Int>, Int>.getLeftFrom(coord: Pair<Int, Int>): List<Int> {
return this.filter { it.key.second == coord.second }
.filter { it.key.first < coord.first }.entries.sortedByDescending { it.key.first }.map { it.value }.toList()
}
private fun Map<Pair<Int, Int>, Int>.getUpFrom(coord: Pair<Int, Int>): List<Int> {
return this.filter { it.key.first == coord.first }
.filter { it.key.second < coord.second }.entries.sortedByDescending { it.key.second }.map { it.value }.toList()
}
private fun Map<Pair<Int, Int>, Int>.getDownFrom(coord: Pair<Int, Int>): List<Int> {
return this.filter { it.key.first == coord.first }
.filter { it.key.second > coord.second }.entries.sortedBy { it.key.second }.map { it.value }.toList()
}
private fun processDirectionFromZero(
map: Map<Pair<Int, Int>, Int>,
visible: MutableSet<Pair<Int, Int>>,
switch: Boolean = false
) {
val max = map.keys.maxByOrNull { it.first }!!.first
var i = 0
var j = 0
var localMax = -1
while (j <= max) {
while (i <= max) {
val coord = if (switch) j to i else i to j
val current = map[coord] ?: break
if (current > localMax) {
visible.add(coord)
localMax = current
}
i++
}
localMax = -1
i = 0
j++
}
}
private fun processDirectionToZero(
map: Map<Pair<Int, Int>, Int>,
visible: MutableSet<Pair<Int, Int>>,
switch: Boolean = false
) {
val max = map.keys.maxByOrNull { it.first }!!.first
var i = max
var j = max
var localMax = -1
while (j >= 0) {
while (i >= 0) {
val coord = if (switch) j to i else i to j
val current = map[coord] ?: break
if (current > localMax) {
visible.add(coord)
localMax = current
}
i--
}
localMax = -1
i = max
j--
}
}
private fun String.parse(): Map<Pair<Int, Int>, Int> {
val map = mutableMapOf<Pair<Int, Int>, Int>()
this.split("\n")
.mapIndexed { i, row ->
row.split("").filter { it.isNotEmpty() }.forEachIndexed { j, value ->
map.put(j to i, value.toInt())
}
}
return map
}
private const val test = """30373
25512
65332
33549
35390"""
private const val input =
"""003112220410413101104044022234320204233341435252223642044225451531421012104343030211442433410302111
301233004003313130222434121135033231250505241131342032404032560542233000343455552123100410402211201
111301041221333142533352050250154136146324550411565615444115604102531135302000320033233340431313123
011312210420442043155233305201305643445224334303310253225205601265233454400214114322131420224022313
130102441231200141254202121022423405224443210463250415204410624313613034320040015223211432442333110
133121132322223054104323242043651144066341346000104210124535555236324451132555525220523220023202433
110011123024113203143145243605143331512223606564503661350336662505131254503242354031400131012444222
221400422202335053520044325014041432662161415523526711633662600635304000112322014001533351130303321
030222020044115331004065013253364503664435753416641653716424535324654054023321025154331103034342414
030331241153233040140314112524504535172167445223426653152774166352145410064425434012002122431142343
224111232453145423354550035141103644127571711431336236226321752314754510214316215104550522141301020
424321022432003551434012134531644165753146143232242275633762323631713541330463531053004424012234010
221233440041435131321565604060121637542135243721227576264551457171313165211546132314103242442012133
301320232222024200651041405631257577625236256225367443317773421262762172454463051224654015452230401
124314451244222611016300517414362722551374735555353871173242751564427674344212032442221554524035432
000210412345203005364660077252742673773341654558568632445755573574757433452636410261362004114032013
333130514223252440150314572132443233363783556666363566733363262631651361523573335361463232143300044
400403124212626240015541437753711632635435857234865883574647337436376563235264524230225211320425534
430312520241033613150127256341412352564548243842255622454762832274857163157242366022041262252034150
125211521340246341461723355443362487532437274863758283488567453538667642367654751321503343220351304
015045453331430626273664314125778234645658386774837783464366334264476243327176571544650404453253132
354034323663213666746174754737374552772744668787244468236435632534753452366177147233020313054042345
305241054630156250416544221136444247327848337737584777837244467756426322644474332262330430251551212
100144030632532041231474166555527386344645548655948476835366757558682728623657547471260405014131510
155501551351164622444476154658383338677369856795967346765977585753438378656352723127554031451225340
213252046404053134327512554784653544697439375473948735593644477348334755453317243676612665133404310
022440140420166534174335264388542568833984445757393864997986883894574577853347367415453352646352541
303425632364032563633467847288735478557676734393879573848466463466672455482853676764477400452414425
421140260266576264621526686828328833799894373434775335763857585383998562862724435337211515426106224
251234063153345361761483764445395779384568938899876568577359785776678952473247274437226445141011143
124165362100637756715727365876646574835535677777467785479666667584536895483528343623556220650044411
523533116461715454347526758528694839737349689796485884675949699354664766465728468324363766204426020
011655232111314171647378426863359767797699886798595874554677869353593448485338287251255363024600501
201454444103773472628888556987787587788889498545597569965587748496753787964648276727241677205552530
022050015673621733475438774338498584975649879876857968775687577968447843939528275674512475556245535
415145246426622536566872225778388854879897849855475687687595454675468637795674534385355242230005213
515410462156777244275234668693874665788796767699675757959578987749863457937753862877526274731341533
532441044352764132482273798897585496755464759898898996955476545867443535986538526852746625533463346
042116466642255478273735578633656564997786577695957789988869999965866866547392358543326526744105124
305463642721567264236826357995536786844968968785757997557699474697669835738584868845834527260231552
066231251534151145564875937345768799895756579656987695996797768779596848379994862646436522463360266
506513057363414584637639439854956668854878865987777598756576697549657897644947484484534264535522136
131666244551736787837659743739478747677995596779697659755568679946768553647438363837764527562663652
424404413335566473356634745356959967996577965786978695878778775749964899347635788855331715645156443
366410447316422733452686338845457787759555776998978979667795556665499755678449775626855353212651324
302136251253517685366593955978666557656668675898896669776695986549696689467499828826265743355612425
546506521534743584874443398869667685788797956777788696997955989646664668879679457843885333126334344
362262154313747445367249673496655464765879658679769897687679766789496785648597346877862642316202103
026226125354532563527338467655476495659657769687899897897899856576869585587683926347427571714351012
324246031677535478765836973778855888768885696676889798687785885666785975868394627754287365751563132
031351623136767474878299634934847976977866799698978866969865695657475657893553946224747277645245120
026056143144572747422538333594694756756655696798979976879958687957995676939686658475475623336500612
662533125413523284737634669357979456995895856799797767679899585888899799675553357648455413641663031
014206153225663545455694774965848955686699676678777689996997596965668976646983688667633463335404141
413012617325174456878669973969459678955956597997687976869576778966464554568469886777721516427616513
502662203642612255238447486939957458967857897679766997696655868558575999589335922456844736112131654
212661502516734223324889447354689969855787756889968698877896757975877697383989627364337421772343024
062105566125733258245733457473775547779958796868868895787767755559647545379345865238624356123242000
402335614754636628236824679555597465548989986755969565969678898559987586856955673832271674166105362
451334645753376162243335579543677879955598768556565759756869877876795947966569855573232735534601241
500262052615557247375888358635954578969966856685689678868986899965887995757987425824514566556143415
025221464647151347477323745438738647477798995699788989796688598687779795846437577837865212462025305
506261641542645445623578634938859695857548567987658895685668887664467397754563764284864222243613255
544001251632514343434242438697698767785468785559797877757559476976744589553445545348132556324315401
312662335054751647576346847944998349986995969646958568675577475645539379875732364426714676752004534
442336642122316123757636234859863735657746598877646757975758669549947438746824526434264347133600103
110222605363451462773826376864836593598856459788567868745977445869448964569655348846536363204056350
000101232124176476234372634789857987399659768658796566947966644948468844584756623732364133065443412
134465433226374477324823357757785535937975665949586889647565456766846389552458234767667646466124353
421406224300535763513347544755878674693949665984559799965894778876384773264625738631365460212615513
452351220036426717772576544574486575445936589965659469684553983864958887588836456352652752044465624
513131310021516677236857346343788436737376979889979498674877368855367664436225742117611411543534241
025341550553445563557374338552585545787433393754685485676457956894674542662544752536711135543323540
535152616216423251726174753447757785566344854848638858756838495369785886445488572266324260520452211
040010242452167571763413223445374499838658479769797468459895353937866635767567612446231533425561512
540233435611063354343623584674548775576735445736954663985773597646587532834332126771664204465150223
115125460640513624264577427672484376565394997956949478368583668555354324253116433334364541633501141
325235035031330065764773672233563447278366899833655673943396323666327273534372213517324021336301134
210455052102126060367721574443448283734742249765698995536842573866568587565571317173455040136014133
130303041444343616551636147765524538863657233824485633222587838375574238775244261440413305250410213
215411311040450233266672334763832288583822422248882386376826865647256855122326112462046245434214110
230231555011111141243461222762213386584878775753548542777758687642766773174237314624160241043301041
323544455001621231632772663352437368846236258422868628887825466644733647626344222306513541033345051
103143140115330535101443674523313247636278477357763543634765673375252223123145511514215131041302240
232425305344242122243634141575125456216884578682284677823883878251534364736772005201664151453532422
102015414143426060302001452111353522415644252842283555326642135161755673127454553246636405351210230
434225550123100466121402111553624464277266354226553673463535217337233242261322143516321221202244233
241043514014314144343662453056766274716234347315115145214653247673432611160552306341450310405413111
242112143335044304622645260260424573275613637141734623226773527441742321265241643455134145215344111
111301110035433343532532505066367716542154757534155161173124736561116131435620565213531350550432142
242323242143224035106205224411500635634124323342513747342475634262646442514656422055112331122023144
002021344233114150010341663531513334522142253265466242366366534525551142525131661102314124401314042
024004104024242151413420354625126365606642452553232242411563750634302214411623615524332515123123121
322320201030004104054100060453523451362415465573527326430616603635233444523531105134335533102202414
013231044323002420215041311645066036204353535300445225661352044506065120312154410321400034312200320
031030413344440552442114452066553136026033443442226333515665300213012326102141034413121232242040400
133131302014414220215344004521556454235620502443013233464014064103264525100404050140223431001414000
221120341111243124154321401255010441026151433422443520262166251632146441120442553301443334201231200
021222222103332103301112520131442023663055232552042262505152050120510455441325453404132240001402111"""
| 0 | Kotlin | 0 | 0 | 8230fce9a907343f11a2c042ebe0bf204775be3f | 13,492 | advent-of-code-2022 | MIT License |
src/main/kotlin/solutions/day08/Day8.kt | Dr-Horv | 112,381,975 | false | null |
package solutions.day08
import solutions.Solver
import utils.splitAtWhitespace
enum class Operation {
INC,
DEC
}
fun String.toOperation(): Operation = when(this) {
"inc" -> Operation.INC
"dec" -> Operation.DEC
else -> throw RuntimeException("Operation unparsable: $this")
}
fun String.toCondition(): Condition = when(this) {
">" -> Condition.GT
"<" -> Condition.LT
">=" -> Condition.GTE
"==" -> Condition.EQ
"<=" -> Condition.LTE
"!=" -> Condition.NEQ
else -> throw RuntimeException("Condition unparsable $this")
}
enum class Condition {
GT,
LT,
GTE,
EQ,
LTE,
NEQ
}
fun Int.checkCondition(condition: Condition, x: Int): Boolean = when(condition) {
Condition.GT -> this > x
Condition.LT -> this < x
Condition.GTE -> this >= x
Condition.EQ -> this == x
Condition.LTE -> this <= x
Condition.NEQ -> this != x
}
fun Int.doOperation(operation: Operation, amount: Int) : Int = when(operation) {
Operation.INC -> this + amount
Operation.DEC -> this - amount
}
data class Instruction(val registry: String,
val operation: Operation,
val amount: Int,
val registryForCondition: String,
val condition: Condition,
val comparision: Int)
class Day8: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val instructions = input.map(String::splitAtWhitespace)
.map {
Instruction(
registry = it[0],
operation = it[1].toOperation(),
amount = it[2].toInt(),
registryForCondition = it[4],
condition = it[5].toCondition(),
comparision = it[6].toInt()
)
}
val registries = mutableMapOf<String, Int>().withDefault { 0 }
var totalMax = Int.MIN_VALUE
instructions.forEach {
if(registries.getValue(it.registryForCondition)
.checkCondition(it.condition, it.comparision)) {
val value = registries.getValue(it.registry)
val newValue = value.doOperation(it.operation, it.amount)
if(newValue > totalMax) {
totalMax = newValue
}
registries.put(it.registry, newValue)
}
}
val max = registries.values.max()!!
return if(partTwo) {
totalMax.toString()
} else {
registries.values.max()!!.toString()
}
}
}
| 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 2,715 | Advent-of-Code-2017 | MIT License |
aoc/src/main/kotlin/com/bloidonia/aoc2023/day03/Main.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.day03
import com.bloidonia.aoc2023.lines
private data class Number(val x: IntRange, val y: Int, val value: String)
private data class Symbol(val x: Int, val y: Int, val value: String)
private data class Board(val numbers: List<Number>, val symbols: List<Symbol>) {
constructor(input: List<String>) : this(
input.flatMapIndexed(::numberLocations),
input.flatMapIndexed(::symbolLocations)
)
}
private fun numberLocations(y: Int, line: String) = Regex("""\d+""")
.findAll(line)
.map { r -> Number(r.range, y, r.groupValues[0]) }
.toList()
private fun symbolLocations(y: Int, line: String) = Regex("""[^\d.]""")
.findAll(line)
.map { r -> Symbol(r.range.first, y, r.groupValues[0]) }
.toList()
private fun partAdjacent(number: Number, symbols: List<Symbol>) = symbols.any { symbol ->
symbol.x in (number.x.first - 1..number.x.last + 1)
&& symbol.y in (number.y - 1)..(number.y + 1)
}
private fun numberAdjacent(symbol: Symbol, numbers: List<Number>) = numbers.filter { n ->
(symbol.x - 1..symbol.x + 1).intersect(n.x).isNotEmpty()
&& n.y in (symbol.y - 1..symbol.y + 1)
}
private fun part1(input: Board) = input.numbers
.filter { n -> partAdjacent(n, input.symbols) }
.sumOf { it.value.toInt() }
private fun part2(input: Board) = input.symbols
.filter { it.value == "*" }
.map { numberAdjacent(it, input.numbers) }
.filter { it.size == 2 }
.sumOf { it.first().value.toLong() * it.last().value.toLong() }
private const val example = """467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598.."""
fun main() {
val lines = lines("/day03.input")
val example = Board(example.lines())
val day03 = Board(lines)
part1(example).let(::println)
part1(day03).let(::println)
part2(example).let(::println)
part2(day03).let(::println)
} | 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 1,944 | aoc-2023 | MIT License |
src/year2023/day01/Day01.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2023.day01
import check
import readInput
fun main() {
val testInput1 = readInput("2023", "Day01_test_part1")
val testInput2 = readInput("2023", "Day01_test_part2")
check(part1(testInput1), 142)
check(part2(testInput2), 281)
val input = readInput("2023", "Day01")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = input.sumOf { it.parseCalibrationValue() }
private fun part2(input: List<String>) = input.sumOf { it.parseCalibrationValue(includeSpelledOut = true) }
private fun String.parseCalibrationValue(includeSpelledOut: Boolean = false): Int {
val nums = indices.mapNotNull { substring(it).getStartingDigitAsNumOrNull(includeSpelledOut) }
return nums.first() * 10 + nums.last()
}
private fun String.getStartingDigitAsNumOrNull(includeSpelledOut: Boolean = false): Int? {
val num = first().digitToIntOrNull()
if (num != null || !includeSpelledOut) return num
return numsByText.firstNotNullOfOrNull { (numAsWord, num) ->
num.takeIf { startsWith(numAsWord) }
}
}
private val numsByText = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
)
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,268 | AdventOfCode | Apache License 2.0 |
solutions/src/Day16.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | fun main() {
fun part1(input: List<String>): Int {
val pathTotalPressures = getTotalPressureForAllPaths(input, 30)
return pathTotalPressures.maxOf { (_, totalPressure) -> totalPressure }
}
fun part2(input: List<String>): Int {
val pathTotalPressures = getTotalPressureForAllPaths(input, 26)
val totalPressureByPath = pathTotalPressures.toMap()
val allPaths = pathTotalPressures.map { it.first }.map { it.toSet() }
var highestTotalPressure = 0
allPaths.forEach { path1 ->
allPaths.filter { path2 ->
val pathIntersection = (path1 - "AA").intersect(path2 - "AA")
pathIntersection.isEmpty()
}.forEach { path2 ->
val path1List = path1.toList()
val path1Total = totalPressureByPath[path1List]!!
val path2List = path2.toList()
val path2Total = totalPressureByPath[path2List]!!
if (path1Total + path2Total > highestTotalPressure) {
highestTotalPressure = path1Total + path2Total
}
}
}
return highestTotalPressure
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
private fun valvesById(input: List<String>) = input.associate { line ->
val split = line.split(" ")
val valve = Valve(
id = split[1],
flowRate = split[4].substringAfter("=").substringBefore(";").toInt(),
leadToValves = if (line.contains("valves")) {
line.substringAfter("valves").filterNot { it.isWhitespace() }.split(",")
} else {
listOf(line.substringAfter("valve").filterNot { it.isWhitespace() })
}
)
valve.id to valve
}
private fun getTotalPressureForAllPaths(input: List<String>, totalMinutes: Int): MutableList<Pair<List<String>, Int>> {
val valveDistanceMatrix = mutableMapOf<String, MutableMap<String, Int>>()
val valvesById = valvesById(input)
val valveIds = valvesById.keys
// BFS to find distance between each node
valveIds.forEach { valveId ->
val leadToValves = mutableMapOf<String, Int>()
valveDistanceMatrix[valveId] = leadToValves
val visited = mutableSetOf<String>()
val queue = ArrayDeque<Pair<String, Int>>()
queue.add(valveId to 0)
while (queue.isNotEmpty()) {
val (valveId, count) = queue.removeFirst()
visited.add(valveId)
leadToValves[valveId] = count
val valve = valvesById[valveId]!!
val remainingValves = valve.leadToValves.filter { v -> v !in visited }
remainingValves.forEach { v ->
queue.add(v to count + 1)
}
}
}
// Find highest node each time, remembering some nodes have 0 flow rate
val visitedValveIds = mutableSetOf<String>()
visitedValveIds.add("AA")
val nonZeroFlowRateValvesById = valveIds.map { valvesById[it]!! }.filter { it.flowRate != 0 }.associateBy { it.id }
val allPaths = mutableListOf<Pair<List<String>, Int>>()
// Recursive DFS to find total pressure for all paths
getTotalPressureForAllPaths(
currentNode = "AA",
valvesToVisit = nonZeroFlowRateValvesById.keys,
valvesById = nonZeroFlowRateValvesById,
matrix = valveDistanceMatrix,
minute = 1,
total = 0,
allPaths = allPaths,
path = listOf("AA"),
totalMinutes = totalMinutes,
)
return allPaths
}
private fun getTotalPressureForAllPaths(
currentNode: String,
valvesToVisit: Set<String>,
valvesById: Map<String, Valve>,
matrix: Map<String, Map<String, Int>>,
minute: Int,
total: Int,
allPaths: MutableList<Pair<List<String>, Int>>,
path: List<String>,
totalMinutes: Int,
) {
allPaths.add(path to total)
val otherValveDistancesById = matrix[currentNode]!!
if (minute > totalMinutes || valvesToVisit.isEmpty()) {
return
} else {
valvesToVisit.forEach { otherValve ->
val otherValves = valvesToVisit - otherValve
val newValve = valvesById[otherValve]!!
// travel to other node and open it
var newMinute = minute + otherValveDistancesById[otherValve]!!
if (newMinute > totalMinutes) {
return@forEach
}
val newTotal = total + (newValve.flowRate * (totalMinutes - newMinute))
newMinute++
getTotalPressureForAllPaths(
currentNode = otherValve,
valvesToVisit = otherValves,
valvesById = valvesById,
matrix = matrix,
minute = newMinute,
total = newTotal,
allPaths = allPaths,
path = path + otherValve,
totalMinutes = totalMinutes,
)
if (otherValves.isEmpty()) {
return@forEach
}
}
}
}
data class Valve(
val id: String,
val flowRate: Int,
val leadToValves: List<String>,
)
| 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 5,307 | advent-of-code-22 | Apache License 2.0 |
src/Day03.kt | razvn | 573,166,955 | false | {"Kotlin": 27208} |
fun main() {
val day = "Day03"
fun part1(input: List<String>): Int = input.fold(emptyList<Char>()) { acc, line ->
val commun = communChars(emptySet(), line.chunked(line.length/2))
acc + commun
}.let { value(it)}
fun part2(input: List<String>): Int = input.chunked(3).fold(0) { acc, group ->
val commun = communChars(emptySet(), group)
acc + value(commun)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
// println(part1(testInput))
// println(part2(testInput))
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
private tailrec fun communChars(commun: Set<Char>, remain: List<String>): Set<Char> = when {
commun.isEmpty() -> when {
remain.size > 1 -> {
val newCommun = remain[0].toSet().intersect(remain[1].toSet())
communChars(newCommun, remain.drop(2))
}
else -> emptySet()
}
remain.isEmpty() -> commun
else -> {
val newCommon = commun.intersect(remain.first().toSet())
communChars(newCommon, remain.drop(1))
}
}
private fun value(items: Collection<Char>): Int = items.fold(0) { acc, char ->
val baseCharCode = if (char in 'a'..'z') 'a'.code - 1 else 'A'.code - 1 - 26
val charValue = char.code - baseCharCode
acc + charValue
}
| 0 | Kotlin | 0 | 0 | 73d1117b49111e5044273767a120142b5797a67b | 1,469 | aoc-2022-kotlin | Apache License 2.0 |
src/Day12.kt | xNakero | 572,621,673 | false | {"Kotlin": 23869} | object Day12 {
fun part1(): Int {
val graph = readGraph()
val startAt = graph.first { it.value == 'S' }
val queue = mutableListOf(startAt.coordinate)
val visited = mutableSetOf(startAt.coordinate)
val results = graph.map { it.coordinate }.associateWith { 0 }.toMutableMap()
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
val currentNodeResult = results[node]!!
if (graph.nodeByCoordinate(node).adjacentNodes.any { graph.nodeByCoordinate(it).value == 'E' }) {
return currentNodeResult + 1
}
val adjacentNodes = graph.nodeByCoordinate(node).adjacentNodes
adjacentNodes
.filter { it !in visited }
.also { queue.addAll(it) }
.forEach { results[it] = currentNodeResult + 1 }
visited.addAll(adjacentNodes)
}
return 0
}
fun part2(): Int {
val graph = readGraph()
val startingPositions = graph.filter { it.value in setOf('a', 'S') }.map { it.coordinate }
val pathLengths = mutableSetOf<Int>()
startingPositions.forEach { startingPosition ->
val startAt = graph.first { it.coordinate == startingPosition }
val queue = mutableListOf(startAt.coordinate)
val queued = mutableSetOf(startAt.coordinate)
val nodePathLengths = graph.map { it.coordinate }.associateWith { 0 }.toMutableMap()
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
val currentNodeResult = nodePathLengths[node]!!
if (graph.nodeByCoordinate(node).adjacentNodes.any { graph.nodeByCoordinate(it).value == 'E' }) {
pathLengths.add(currentNodeResult + 1)
break
}
val adjacentNodes = graph.nodeByCoordinate(node).adjacentNodes
adjacentNodes
.filter { it !in queued }
.also { queue.addAll(it) }
.forEach { nodePathLengths[it] = currentNodeResult + 1 }
queued.addAll(adjacentNodes)
}
}
return pathLengths.min()
}
private fun readGraph(): List<HillNode> {
val nodes = readInput("day12")
.map { line -> line.chunked(1).map { it.toCharArray()[0] } }
.let { nodes ->
val width = nodes[0].size
nodes.flatten()
.mapIndexed { index, value -> HillNode(value, NodeCoordinate(index % width, index / width)) }
}
nodes.forEach { nodes.findAdjacentNodes(it) }
return nodes
}
}
private fun List<HillNode>.nodeByCoordinate(coordinate: NodeCoordinate): HillNode =
first { it.coordinate == coordinate }
private fun List<HillNode>.findAdjacentNodes(node: HillNode) {
val left = find { it.coordinate == NodeCoordinate(node.coordinate.x - 1, node.coordinate.y) }
val right = find { it.coordinate == NodeCoordinate(node.coordinate.x + 1, node.coordinate.y) }
val top = find { it.coordinate == NodeCoordinate(node.coordinate.x, node.coordinate.y - 1) }
val bottom = find { it.coordinate == NodeCoordinate(node.coordinate.x, node.coordinate.y + 1) }
listOfNotNull(left, right, top, bottom)
.filter { it.value.determineChar().code <= node.value.determineChar().code + 1 }
.map { it.coordinate }
.also { node.adjacentNodes.addAll(it) }
}
private fun Char.determineChar(): Char =
when (this) {
'E' -> 'z'
'S' -> 'a'
else -> this
}
data class HillNode(
val value: Char,
val coordinate: NodeCoordinate,
val adjacentNodes: MutableList<NodeCoordinate> = mutableListOf()
)
data class NodeCoordinate(val x: Int, val y: Int)
fun main() {
println(Day12.part1())
println(Day12.part2())
} | 0 | Kotlin | 0 | 0 | c3eff4f4c52ded907f2af6352dd7b3532a2da8c5 | 3,922 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day07.kt | EmRe-One | 726,902,443 | false | {"Kotlin": 95869, "Python": 18319} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
import tr.emreone.kotlin_utils.extensions.times
class Day07 : Day(7, 2023, "Camel Cards") {
class Hand(val hand: String, val value: Int, val withJoker: Boolean = false) : Comparable<Hand> {
val CARDS = buildList<String> {
if (withJoker) {
add("A,K,Q,T,9,8,7,6,5,4,3,2,J")
} else {
add("A,K,Q,J,T,9,8,7,6,5,4,3,2")
}
}.first()
.split(",")
.map { it.toCharArray()[0] }
.reversed()
fun rank(): Int {
val sortedCardSet = if (withJoker && this.hand.contains("J")) {
val jokerNumber = hand.count { it == 'J' }
val charList = hand.toCharArray().filter { it != 'J' }
.groupBy { it }
.toMutableMap()
if (charList.isEmpty()) {
charList['A'] = "AAAAA".toCharArray().toList()
} else {
val maxUsedChar = charList.values.maxBy { it.size }[0]
charList[maxUsedChar] = charList[maxUsedChar]!!.toMutableList().apply {
addAll("$maxUsedChar".times(jokerNumber).toCharArray().toList())
}
}
charList.entries
.sortedBy {
it.value.size
}
} else {
hand.toCharArray()
.groupBy { it }
.entries
.sortedBy {
it.value.size
}
}
return if (sortedCardSet.size == 1) {
6 // "Five of a kind"
} else if (sortedCardSet.size == 2) {
if (sortedCardSet[0].value.size == 1) {
5 // "Four of a kind"
} else {
4 // "Full House"
}
} else if (sortedCardSet.size == 3) {
if (sortedCardSet[2].value.size == 3) {
3 // "Three of a kind"
} else {
2 // "Two Pair"
}
} else if (sortedCardSet.size == 4) {
1 // "One Pair"
} else {
0 // "High Card"
}
}
override fun compareTo(other: Hand): Int {
if (this.rank() < other.rank()) return -1
if (this.rank() > other.rank()) return 1
for (i in 0 until this.hand.length) {
if (this.hand[i] != other.hand[i]) {
return CARDS.indexOf(this.hand[i]) - CARDS.indexOf(other.hand[i])
}
}
throw IllegalStateException("Should be not possible")
}
override fun toString(): String {
return "$hand $value"
}
}
override fun part1(): Long {
val sortedValues = inputAsList
.map {
val (hand, value) = it.split(" ")
Hand(hand, value.toInt())
}
.sorted()
return sortedValues
.mapIndexed { index, hand ->
hand.value.toLong() * (index + 1)
}
.sum()
}
override fun part2(): Long {
val sortedValues = inputAsList
.map {
val (hand, value) = it.split(" ")
Hand(hand, value.toInt(), true)
}
.sorted()
return sortedValues
.mapIndexed { index, hand ->
hand.value.toLong() * (index + 1)
}
.sum()
}
}
| 0 | Kotlin | 0 | 0 | c75d17635baffea50b6401dc653cc24f5c594a2b | 3,703 | advent-of-code-2023 | Apache License 2.0 |
src/Day07.kt | SimoneStefani | 572,915,832 | false | {"Kotlin": 33918} | fun main() {
class Node(
val name: String,
val parent: Node?,
val children: MutableSet<Node> = mutableSetOf(),
) {
private var itemSize = 0L
val totalSize: Long get() = itemSize + children.sumOf { it.totalSize }
fun addNode(dir: Node): Node = this.also { children.add(dir) }
fun addItem(size: Long): Node = this.also { itemSize += size }
fun allChildren(): Set<Node> = children + children.flatMap { it.allChildren() }
}
fun parseCommands(input: List<String>): Node {
return Node("/", null).apply {
input.fold(this) { node, command: String ->
when {
command == "$ cd /" -> node
command == "$ ls" -> node
command == "$ cd .." -> node.parent!!
command.startsWith("$ cd") -> node.children.first { it.name == command.substringAfter("cd ") }
command.startsWith("dir") -> node.addNode(Node(command.substringAfter("dir "), node))
else -> node.addItem(command.substringBefore(" ").toLong())
}
}
}
}
fun part1(input: List<String>): Long {
return parseCommands(input).allChildren().filter { it.totalSize <= 100_000 }.sumOf { it.totalSize }
}
fun part2(input: List<String>): Long {
val root = parseCommands(input)
val missingSpace = 30_000_000L - (70_000_000L - root.totalSize)
return parseCommands(input).allChildren().filter { it.totalSize >= missingSpace }.minOf { it.totalSize }
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95_437L)
check(part2(testInput) == 24_933_642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b3244a6dfb8a1f0f4b47db2788cbb3d55426d018 | 1,818 | aoc-2022 | Apache License 2.0 |
src/Day15.kt | sushovan86 | 573,586,806 | false | {"Kotlin": 47064} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class BeaconExclusionZone private constructor(
private val sensorBeaconDistances: List<SensorBeaconDistance>
) {
fun getNoBeaconPositionCountAtRow(rowNum: Int): Int =
getCoverageRangePairsAtRow(rowNum)
.let { rangePairsAtRow ->
val beaconsAtRow = sensorBeaconDistances
.filter { it.beaconCoordinate.y == rowNum }
.distinctBy { it.beaconCoordinate.x }
.count()
val extremeLeftPointAtRow = rangePairsAtRow.minOf { it.first }
val extremeRightPointAtRow = rangePairsAtRow.maxOf { it.second }
(extremeRightPointAtRow - extremeLeftPointAtRow + 1) - beaconsAtRow
}
fun getTuningFrequency(maxRow: Int): Long =
(0..maxRow)
.firstNotNullOfOrNull { getProbableBeaconPositionForRow(it) }
?.let { it.x * MAX_COORDINATE_SIZE + it.y } ?: error("No position found")
private fun getProbableBeaconPositionForRow(row: Int): Coordinate? {
val ranges = getCoverageRangePairsAtRow(row)
.sortedWith(compareBy({ it.first }, { it.second }))
if (ranges.isEmpty()) {
return Coordinate(row, 0)
}
var temp = ranges[0]
for (index in 1 until ranges.size) {
if (ranges[index].first - temp.second <= 1) {
temp = min(temp.first, ranges[index].first) to max(temp.second, ranges[index].second)
}
else {
return Coordinate(temp.second + 1, row)
}
}
return null
}
private fun getCoverageRangePairsAtRow(rowNum: Int): List<Pair<Int, Int>> =
sensorBeaconDistances
.mapNotNull { (sensor, _, distance) ->
val offset = abs(sensor.y - rowNum)
val startRange = sensor.x - distance + offset
val endRange = sensor.x + distance - offset
if (endRange >= startRange) startRange to endRange else null
}
data class SensorBeaconDistance(
val sensorCoordinate: Coordinate,
val beaconCoordinate: Coordinate,
val distance: Int
)
data class Coordinate(val x: Int = 0, val y: Int = 0) {
infix fun distanceTo(other: Coordinate): Int = abs(other.x - x) + abs(other.y - y)
}
companion object {
const val MAX_COORDINATE_SIZE = 4_000_000L
fun load(inputList: List<String>): BeaconExclusionZone = inputList
.map {
val (sensorString, beaconString) = it.split(":")
val sensorCoordinate = extractCoordinate(sensorString)
val beaconCoordinate = extractCoordinate(beaconString)
val distance = sensorCoordinate distanceTo beaconCoordinate
SensorBeaconDistance(sensorCoordinate, beaconCoordinate, distance)
}
.let(::BeaconExclusionZone)
private fun extractCoordinate(string: String): Coordinate {
val x = string.substringAfter("x=").substringBefore(",").toInt()
val y = string.substringAfter("y=").toInt()
return Coordinate(x, y)
}
}
}
fun main() {
val testInput = readInput("Day15_test")
val testBeaconExclusionZone = BeaconExclusionZone.load(testInput)
check(testBeaconExclusionZone.getNoBeaconPositionCountAtRow(10) == 26)
check(testBeaconExclusionZone.getTuningFrequency(20) == 56_000_011L)
val input = readInput("Day15")
val beaconExclusionZone = BeaconExclusionZone.load(input)
println(beaconExclusionZone.getNoBeaconPositionCountAtRow(2_000_000))
println(beaconExclusionZone.getTuningFrequency(4_000_000))
} | 0 | Kotlin | 0 | 0 | d5f85b6a48e3505d06b4ae1027e734e66b324964 | 3,771 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/y2023/day04/Day04.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2023.day04
import util.InputReader
class Day04(input: List<String>) {
private val deck: List<Card> = input.map { Card(it) }
fun partOne() = deck.sumOf { it.points }
fun partTwo(): Int {
val count = deck.associateWith { 1 }.toMutableMap()
deck.forEachIndexed { index, card ->
val thisCount = count[card] ?: error("Card ${card.id} not found")
for (i in 1..card.winners.size) {
val nextCard = deck[index + i]
count[nextCard] = count[nextCard]!! + thisCount
}
}
return count.values.sum()
}
data class Card(val id: Int, private val winningNumbers: List<Int>, private val gameNumbers: List<Int>) {
val winners: List<Int> by lazy { winningNumbers.filter { it in gameNumbers } }
// yes, I know, powers of 2 are a thing
val points: Int by lazy { winners.fold(0) { acc, _ -> if (acc == 0) 1 else acc * 2 } }
}
private fun Card(input: String): Card {
val (idStr, numStr) = input.split(": ")
val id = idStr.split(Regex("\\s+"))[1].toInt()
val (wN, nN) = numStr.split(" | ")
.map { strPart ->
strPart.trim().split(Regex("\\s+"))
.mapNotNull { if (it.trim().isNotEmpty()) it.toInt() else null }
}
return Card(id, wN, nN)
}
}
fun main() {
val exampleInput = InputReader.getExampleLines(2023, 4)
val puzzleInput = InputReader.getPuzzleLines(2023, 4)
println("Part 1 example: ${Day04(exampleInput).partOne()}")
println("Part 1: ${Day04(puzzleInput).partOne()}")
println("Part 2 example: ${Day04(exampleInput).partTwo()}")
println("Part 2: ${Day04(puzzleInput).partTwo()}")
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 1,756 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day07.kt | punx120 | 573,421,386 | false | {"Kotlin": 30825} | class Node(
val name: String,
var files: Long = 0,
val parent: Node? = null,
val children: MutableMap<String, Node> = mutableMapOf()
) {
fun totalSize(): Long {
return files + children.values.sumOf { it.totalSize() }
}
override fun toString(): String {
return "Node(name='$name', totalSize=${totalSize()})"
}
}
fun main() {
fun explore(node: Node): Long {
var total = 0L
for (n in node.children.values) {
if (n.totalSize() <= 100000) {
total += n.totalSize()
}
total += explore(n)
}
return total
}
fun buildDirectoryStructure(input: List<String>): Node {
val root = Node("/")
var current = root
for (line in input) {
if (line.startsWith("$")) {
if (line.startsWith("$ cd ")) {
val dest = line.subSequence(5, line.length)
if (dest == "/") {
current = root
} else if (dest == "..") {
current = current.parent!!
} else {
current = current.children[dest]!!
}
}
} else {
if (line.startsWith("dir")) {
val dirname = line.substring(4, line.length)
current.children[dirname] = Node(dirname, parent = current)
} else {
val e = line.split(" ")
current.files += e[0].toLong()
}
}
}
return root
}
fun part1(root: Node): Long {
var total = 0L
for (dir in root.children.values) {
if (dir.totalSize() <= 100000) {
total += dir.totalSize()
}
total += explore(dir)
}
return total
}
fun findDirectories(node: Node, minSize: Long): List<Node> {
val ans = ArrayList<Node>()
for (dir in node.children.values) {
if (dir.totalSize() >= minSize) {
ans.add(dir)
}
ans.addAll(findDirectories(dir, minSize))
}
return ans
}
fun part2(root: Node): Long {
val free = 70000000 - root.totalSize()
val toFree = 30000000 - free
val candidates = findDirectories(root, toFree)
return candidates.minBy { it.totalSize() }.totalSize()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
val testRoot = buildDirectoryStructure(testInput)
println(part1(testRoot))
println(part2(testRoot))
val input = readInput("Day07")
val root = buildDirectoryStructure(input)
println(part1(root))
println(part2(root))
}
| 0 | Kotlin | 0 | 0 | eda0e2d6455dd8daa58ffc7292fc41d7411e1693 | 2,851 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day16.kt | clechasseur | 318,029,920 | false | null | import org.clechasseur.adventofcode2020.Day16Data
object Day16 {
private val ticketRules = Day16Data.ticketRules
private const val yourTicket = Day16Data.yourTicket
private val nearbyTickets = Day16Data.nearbyTickets
private val ticketRuleRegex = """^([a-z ]+): (\d+)-(\d+) or (\d+)-(\d+)$""".toRegex()
fun part1(): Int {
val rules = ticketRules.toRules()
val ticketsToScan = nearbyTickets.lines().map { it.toTicket() }
return ticketsToScan.scanningErrorRate(rules)
}
fun part2(): Long {
val rules = ticketRules.toRules()
val ticketsToScan = nearbyTickets.lines().map { it.toTicket() }.filter {
it.scanningErrorRate(rules) == null
}
var orderedCandidates = ticketsToScan.first().fields.indices.map { fieldIdx ->
rules.rules.filter { rule ->
ticketsToScan.map { it.fields[fieldIdx] }.all { rule.valid(it) }
}
}
val handled = mutableSetOf<Rule>()
while (orderedCandidates.any { it.size > 1 }) {
val lone = orderedCandidates.first {
it.size == 1 && !handled.contains(it.single())
}.single()
orderedCandidates = orderedCandidates.map { candidates ->
if (candidates.size == 1) candidates else candidates - lone
}
handled.add(lone)
}
val orderedRules = orderedCandidates.map { it.single() }
val ticketToIdentify = yourTicket.toTicket()
return orderedRules.withIndex().filter {
it.value.field.startsWith("departure")
}.map {
ticketToIdentify.fields[it.index]
}.fold(1L) { acc, i -> acc * i.toLong() }
}
private data class Rule(val field: String, val range1: IntRange, val range2: IntRange) {
fun valid(value: Int): Boolean = value in range1 || value in range2
}
private class Rules(val rules: List<Rule>) {
fun validForOne(value: Int): Boolean = rules.any { it.valid(value) }
}
private data class Ticket(val fields: List<Int>) {
fun scanningErrorRate(rules: Rules): Int? = fields.firstOrNull { value ->
!rules.validForOne(value)
}
}
private fun List<Ticket>.scanningErrorRate(rules: Rules): Int = mapNotNull {
it.scanningErrorRate(rules)
}.sum()
private fun String.toRules(): Rules = Rules(lines().map { rule ->
val match = ticketRuleRegex.matchEntire(rule) ?: error("Wrong rule: $rule")
val (field, r1f, r1l, r2f, r2l) = match.destructured
Rule(field, r1f.toInt()..r1l.toInt(), r2f.toInt()..r2l.toInt())
})
private fun String.toTicket(): Ticket = Ticket(split(',').map { it.toInt() })
}
| 0 | Kotlin | 0 | 0 | 6173c9da58e3118803ff6ec5b1f1fc1c134516cb | 2,742 | adventofcode2020 | MIT License |
src/Day07.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | /**
* [Day07](https://adventofcode.com/2022/day/7)
*/
private class Day07 {
sealed class Node {
abstract val name: String
data class File(override val name: String, val size: Int) : Node() {
override fun toString(): String {
return "File: $name"
}
}
abstract class Dir : Node() {
abstract val parent: Dir
abstract val absPath: String
val children = mutableMapOf<String, Dir>()
val files = mutableMapOf<String, File>()
override fun toString(): String {
return "[Dir($name): (children: ${children}, files: ${files})]"
}
}
data class Root(override val name: String) : Dir() {
override val parent = this
override val absPath = "/"
override fun toString(): String {
return super.toString()
}
}
data class NDir(override val name: String, override val parent: Dir) : Dir() {
override val absPath = "${parent.absPath}$name/"
override fun toString(): String {
return super.toString()
}
}
}
enum class Command {
CD, LS
}
}
fun main() {
fun makeFileTree(input: List<String>): Day07.Node.Dir {
val root: Day07.Node.Dir = Day07.Node.Root("/")
var current: Day07.Node.Dir = root
input.forEach { line ->
val data = line.split(" ")
when (line[0]) {
'$' -> {
when (Day07.Command.valueOf(data[1].uppercase())) {
Day07.Command.LS -> return@forEach // continue
Day07.Command.CD -> {
val dest = data[2]
current = when (dest) {
"/" -> root
".." -> current.parent
else -> current.children.getOrPut(dest) { Day07.Node.NDir(dest, current) }
}
}
}
}
else -> {
if (data[0] == "dir") {
current.children.putIfAbsent(data[1], Day07.Node.NDir(data[1], current))
} else { // file
current.files.putIfAbsent(data[1], Day07.Node.File(data[1], data[0].toInt()))
}
}
}
}
return root
}
fun dfs(tree: Day07.Node.Dir, memo: MutableMap<String, Int>): Int {
if (tree.absPath in memo) {
return memo.getValue(tree.absPath)
}
val sum = tree.children.map { (_, v) ->
memo.getOrPut(v.absPath) { dfs(v, memo) }
}.sum()
val res = sum + tree.files.values.map(Day07.Node.File::size).sum()
memo[tree.absPath] = res
return res
}
fun part1(input: List<String>): Int {
val tree = makeFileTree(input)
val memo = mutableMapOf<String, Int>()
dfs(tree, memo)
return memo.values.filter { it <= 100000 }.sum()
}
fun part2(input: List<String>): Int {
val tree = makeFileTree(input)
val memo = mutableMapOf<String, Int>()
dfs(tree, memo)
val target = 30000000 - (70000000 - memo.getValue("/"))
return memo.values.filter { it >= target }.min()
}
// 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(part1(input))
println(part2(input))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 3,744 | aoc-in-kotlin-2022 | Apache License 2.0 |
advent-of-code-2021/src/main/kotlin/Day9.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 9: Smoke Basin
//https://adventofcode.com/2021/day/9
import java.io.File
fun main() {
val heightMaps = File("src/main/resources/Day9.txt").readLines()
val totalHeight = heightMaps.size
val totalWidth = heightMaps.first().length
val array = Array(totalHeight) { Array(totalWidth) { 0 } }
heightMaps.forEachIndexed { index, heightmap ->
heightmap.toList().forEachIndexed { heightIndex, height ->
array[index][heightIndex] = height.digitToInt()
}
}
val lowPoints = getLowPoints(array)
val riskLevel = lowPoints.sumOf { index ->
array[index.first][index.second] + 1
}
println(riskLevel)
getLargestBasins(array, lowPoints)
}
fun getLowPoints(array: Array<Array<Int>>): List<Pair<Int, Int>> {
val lowPoints = mutableListOf<Pair<Int, Int>>()
for (x in array.indices) {
for (y in 0 until array[x].size) {
val cell = array[x][y]
var isLower = true
if (x > 0) isLower = isLower && cell < array[x - 1][y]
if (x < array.size - 1) isLower = isLower && cell < array[x + 1][y]
if (y > 0) isLower = isLower && cell < array[x][y - 1]
if (y < array[x].size - 1) isLower = isLower && cell < array[x][y + 1]
if (isLower) lowPoints.add(x to y)
}
}
return lowPoints
}
fun getLargestBasins(array: Array<Array<Int>>, lowPoints: List<Pair<Int, Int>>) {
val basinSizes = lowPoints.map { point ->
var basin = mutableSetOf<Pair<Int, Int>>()
var newBasin = mutableSetOf(point.first to point.second)
while (newBasin != basin) {
basin = newBasin
newBasin = flowDownBasin(array, basin)
}
newBasin.size
}.sortedDescending()
println(basinSizes[0] * basinSizes[1] * basinSizes[2])
}
fun flowDownBasin(array: Array<Array<Int>>, oldBasin: Set<Pair<Int, Int>>): MutableSet<Pair<Int, Int>> {
val newBasin = oldBasin.toMutableSet()
oldBasin.forEach { point ->
val x = point.first
val y = point.second
if (x > 0 && array[x - 1][y] != 9) newBasin.add(x - 1 to y)
if (x < array.size - 1 && array[x + 1][y] != 9) newBasin.add(x + 1 to y)
if (y > 0 && array[x][y - 1] != 9) newBasin.add(x to y - 1)
if (y < array[x].size - 1 && array[x][y + 1] != 9) newBasin.add(x to y + 1)
}
return newBasin
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,404 | advent-of-code | Apache License 2.0 |
src/aoc2022/day07/Day07.kt | svilen-ivanov | 572,637,864 | false | {"Kotlin": 53827} | package aoc2022.day07
import readInput
sealed class Fs() {
abstract val parent: Dir?
abstract val name: String
abstract fun size(): Int
data class File(override val parent: Dir?, override val name: String, val size: Int) : Fs() {
override fun size(): Int = size
}
data class Dir(override val parent: Dir?, override val name: String) : Fs() {
val entries: MutableList<Fs> = mutableListOf()
override fun size() = entries.sumOf { it.size() }
}
}
fun flatten(dir: Fs.Dir): List<Fs.Dir> {
val list = mutableListOf<Fs.Dir>()
flatten(dir, list)
return list
}
fun flatten(dir: Fs.Dir, list: MutableList<Fs.Dir>) {
val dirs = dir.entries.filterIsInstance<Fs.Dir>()
list.addAll(dirs)
dirs.forEach { flatten(it, list) }
}
fun parseInput(input: List<String>): Fs.Dir {
val root = Fs.Dir(null, "/")
var current = root
for ((index, line) in input.withIndex()) {
if (index == 0) continue
if (line.startsWith("$")) {
val commandList = line.split(" ")
val commandName = commandList[1]
when (commandName) {
"cd" -> {
val arg = commandList[2]
if (arg == "..") {
current = current.parent!!
} else {
var dir = current.entries.find { it.name == arg }
if (dir == null) {
dir = Fs.Dir(current, arg)
current.entries.add(dir)
}
current = dir as Fs.Dir
}
}
"ls" -> {
}
}
} else {
val entry = line.split(" ")
if (entry[0] == "dir") {
current.entries.add(Fs.Dir(current, entry[1]))
} else {
current.entries.add(Fs.File(current, entry[1], entry[0].toInt()))
}
}
}
return root
}
fun main() {
fun part1(input: List<String>) {
val root = parseInput(input)
val size = flatten(root).filter { it.size() <= 100000 }.sumOf { it.size() }
println(size)
check(size == 1749646)
}
fun part2(input: List<String>) {
val root = parseInput(input)
val totalSize = 70000000
val sizeGoal = 30000000
val currentSize = root.size()
val currentUnused = totalSize - currentSize
val targetSizeToDelete = sizeGoal - currentUnused
println("$currentSize, $currentUnused, $targetSizeToDelete")
val dirs = flatten(root).filter {
targetSizeToDelete < it.size()
}.minBy { it.size() }
println(dirs.name)
println(dirs.size())
check(dirs.size() == 1498966)
}
val testInput = readInput("day07/day07")
part1(testInput)
part2(testInput)
}
| 0 | Kotlin | 0 | 0 | 456bedb4d1082890d78490d3b730b2bb45913fe9 | 2,929 | aoc-2022 | Apache License 2.0 |
leetcode2/src/leetcode/TwoSumIITnputArrayIsSorted.kt | hewking | 68,515,222 | false | null | package leetcode
/**
* https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
* 167. 两数之和 II - 输入有序数组
* Created by test
* Date 2019/6/16 10:31
* Description
* 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object TwoSumIITnputArrayIsSorted{
class Solution {
fun twoSum(numbers: IntArray, target: Int): IntArray {
// check param valid
val res = IntArray(2)
for (i in 0 until numbers.size - 1) {
for (j in (i + 1) until numbers.size) {
if (numbers[i] + numbers[j] == target) {
res[0] = i + 1
res[1] = j + 1
break
}
}
}
return res
}
/**
* 思路:
* 傻逼了,没有利用起来有序数组这个特性
*/
fun twoSum2(numbers: IntArray, target: Int): IntArray {
// check param valid
val res = IntArray(2)
var l = 0
var r = numbers.size - 1
while (l < r) {
if (numbers[l] + numbers[r] == target) {
res[0] = l + 1
res[1] = r + 1
break
} else if (numbers[l] + numbers[r] < target) {
l ++
} else {
r --
}
}
return res
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,185 | leetcode | MIT License |
src/Day09.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | import kotlin.math.abs
import kotlin.math.max
fun main() {
data class Point(val x: Int, val y: Int) {
fun dist(other: Point) = max(abs(x - other.x), abs(y - other.y))
}
fun Point.move(dir: String): Point {
return when (dir) {
"R" -> Point(x + 1, y)
"L" -> Point(x - 1, y)
"U" -> Point(x, y + 1)
"D" -> Point(x, y - 1)
else -> throw UnsupportedOperationException()
}
}
fun Point.moveToHead(head: Point): Point {
fun move(from: Int, to: Int) = when {
from > to -> from - 1
from < to -> from + 1
else -> from
}
return if (dist(head) > 1) {
Point(
move(x, head.x),
move(y, head.y)
)
} else this
}
fun solve(input: List<String>, numTails: Int): Int {
val visited = mutableSetOf<Point>()
val initial = Point(0, 0)
val rope = Array(numTails + 1) { initial }
visited += initial
input.forEach {
val (dir, steps) = it.split(" ")
repeat(steps.toInt()) {
rope[0] = rope[0].move(dir)
for (i in 1..numTails) {
rope[i] = rope[i].moveToHead(rope[i - 1])
}
visited += rope.last()
}
}
return visited.size
}
fun part1(input: List<String>) = solve(input, 1)
fun part2(input: List<String>) = solve(input, 9)
val testInput = readInputLines("Day09_test")
check(part1(testInput), 13)
check(part2(testInput), 1)
val testInput2 = readInputLines("Day09_test2")
check(part2(testInput2), 36)
val input = readInputLines("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 1,810 | Advent-of-Code-2022 | Apache License 2.0 |
src/aoc2018/kot/Day23.kt | Tandrial | 47,354,790 | false | null | package aoc2018.kot
import diffBy
import getNumbers
import java.io.File
import java.util.*
import kotlin.math.abs
object Day23 {
data class State(val sender: Sender, val inRange: Int) : Comparable<State> {
override fun compareTo(other: State) = if (other.inRange == inRange) sender.r.compareTo(other.sender.r) else other.inRange.compareTo(inRange)
}
data class Sender(val x: Long, val y: Long, val z: Long, var r: Long) {
val dist = abs(x) + abs(y) + abs(z)
fun inRange(other: Sender) = (abs(x - other.x) + abs(y - other.y) + abs(z - other.z)) <= r
fun intersect(other: Sender) = (abs(x - other.x) + abs(y - other.y) + abs(z - other.z)) <= r + other.r
}
fun partOne(input: List<String>): Int {
val senders = parse(input)
val maxSender = senders.maxBy { it.r }!!
return senders.count { maxSender.inRange(it) }
}
fun partTwo(input: List<String>): Long {
val senders = parse(input)
val radius = maxOf(senders.diffBy { it.x }, senders.diffBy { it.y }, senders.diffBy { it.z })
val checked = mutableSetOf<Sender>()
val queue = PriorityQueue<State>(listOf(State(Sender(0, 0, 0, radius), 0)))
var max = queue.peek()
while (queue.isNotEmpty()) {
val (sender, inRange) = queue.poll()
if (sender.r == 0L) {
if (inRange > max.inRange || (inRange == max.inRange && sender.dist < max.sender.dist)) {
max = State(sender, inRange)
queue.removeIf { it.inRange <= inRange }
}
} else if (checked.add(sender)) {
val neuR = sender.r / 2
val next = (-1L..1L).flatMap { xOff ->
(-1L..1L).flatMap { yOff ->
(-1L..1L).mapNotNull { zOff ->
val neu = Sender(sender.x + xOff * neuR, sender.y + yOff * neuR, sender.z + zOff * neuR, neuR)
val count = senders.count { it.intersect(neu) }
if (count >= max.inRange)
State(neu, count)
else null
}
}
}
queue.addAll(next)
}
}
return max.sender.dist
}
fun parse(input: List<String>) = input.map {
val (x, y, z, r) = it.getNumbers()
Sender(x.toLong(), y.toLong(), z.toLong(), r.toLong())
}
}
fun main(args: Array<String>) {
val input = File("./input/2018/Day23_input.txt").readLines()
println("Part One = ${Day23.partOne(input)}")
println("Part Two = ${Day23.partTwo(input)}")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 2,405 | Advent_of_Code | MIT License |
src/Day09.kt | Narmo | 573,031,777 | false | {"Kotlin": 34749} | import kotlin.math.abs
fun main() {
class Knot(var x: Int, var y: Int) {
fun copy() = Knot(x, y)
fun isAdjacentTo(other: Knot) = abs(x - other.x) < 2 && abs(y - other.y) < 2
override fun toString() = "($x, $y)"
override fun equals(other: Any?) = other is Knot && x == other.x && y == other.y
override fun hashCode() = x * 31 + y * y * y * y
fun moveToNear(other: Knot) {
if (x < other.x) x++
if (x > other.x) x--
if (y < other.y) y++
if (y > other.y) y--
}
}
fun process(input: List<String>, knotsNumber: Int): Int {
val knots = (0 until knotsNumber).map { Knot(0, 0) }
val visitedPoints = mutableSetOf(knots.last().copy())
input.forEach {
val (direction, steps) = it.split(" ")
for (i in 0 until steps.toInt()) {
val headPosition = knots.first()
when (direction) {
"U" -> headPosition.y += 1 // inverted
"D" -> headPosition.y -= 1 // inverted
"L" -> headPosition.x -= 1
"R" -> headPosition.x += 1
}
for (j in 1 until knots.size) {
val knot = knots[j]
val previousKnot = knots[j - 1]
if (!knot.isAdjacentTo(previousKnot)) {
knot.moveToNear(previousKnot)
}
}
visitedPoints.add(knots.last().copy())
}
}
return visitedPoints.size
}
fun part1(input: List<String>): Int = process(input, knotsNumber = 2)
fun part2(input: List<String>): Int = process(input, knotsNumber = 10)
val testInput1 = readInput("Day09_test1")
check(part1(testInput1) == 13)
check(part2(testInput1) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 335641aa0a964692c31b15a0bedeb1cc5b2318e0 | 1,666 | advent-of-code-2022 | Apache License 2.0 |
src/aoc23/Day03.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc23.day03
import aoc23.day03.PartNumber.Companion.findAllPartNumbers
import aoc23.day03.Symbol.Companion.findAllSymbols
import lib.Line
import lib.Point
import lib.Solution
data class PartNumber(val value: Int, val location: Line) {
companion object {
fun String.findAllPartNumbers(): List<PartNumber> =
lines().flatMapIndexed { i, line ->
Regex("""\d+""").findAll(line).map { it.toPartNumber(i) }
}
private fun MatchResult.toPartNumber(rowIdx: Int) =
PartNumber(value.toInt(), Line(Point(range.first, rowIdx), Point(range.last, rowIdx)))
}
}
data class Symbol(val value: Char, val location: Point) {
fun isStar() = value == '*'
companion object {
fun String.findAllSymbols(): List<Symbol> =
lines().flatMapIndexed { i, line ->
Regex("""[^\.\d]""").findAll(line).map { it.toSymbol(i) }
}
private fun MatchResult.toSymbol(rowIdx: Int) =
Symbol(value.single(), Point(range.first, rowIdx))
}
}
data class Gear(val symbol: Symbol, val partNumbers: List<PartNumber>) {
constructor(mapEntry: Map.Entry<Symbol, List<PartNumber>>) : this(mapEntry.key, mapEntry.value)
fun value(): Int = partNumbers.map { it.value }.reduce(Int::times)
fun isValidGear() = partNumbers.size == 2
}
data class EngineSchematic(val partNumbers: List<PartNumber>, val symbols: List<Symbol>) {
fun extractValidPartNumbers(): List<PartNumber> = partNumbers.filter(::isValidPartNumber)
fun extractGears(): List<Gear> = symbols
.filter(Symbol::isStar)
.associateWith(::adjacentPartNumbers)
.map(::Gear)
.filter(Gear::isValidGear)
private fun isValidPartNumber(partNumber: PartNumber): Boolean =
symbols.any { symbol ->
partNumber isAdjacentTo symbol
}
private fun adjacentPartNumbers(symbol: Symbol): List<PartNumber> =
partNumbers.filter { partNumber ->
partNumber isAdjacentTo symbol
}
private infix fun PartNumber.isAdjacentTo(symbol: Symbol): Boolean {
val xRange = location.start.x - 1..location.end.x + 1
val yRange = location.start.y - 1..location.end.y + 1
return symbol.location.x in xRange && symbol.location.y in yRange
}
companion object {
fun parse(schematicStr: String): EngineSchematic =
EngineSchematic(schematicStr.findAllPartNumbers(), schematicStr.findAllSymbols())
}
}
typealias Input = EngineSchematic
typealias Output = Int
private val solution = object : Solution<Input, Output>(2023, "Day03") {
override fun parse(input: String): Input = EngineSchematic.parse(input)
override fun format(output: Output): String = "$output"
override fun part1(input: Input): Output =
input.extractValidPartNumbers().sumOf(PartNumber::value)
override fun part2(input: Input): Output =
input.extractGears().sumOf(Gear::value)
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 2,883 | aoc-kotlin | Apache License 2.0 |
src/Day09.kt | proggler23 | 573,129,757 | false | {"Kotlin": 27990} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
fun part1(input: List<String>) = RopeGrid().apply { move(input.parse9()) }.visited.size
fun part2(input: List<String>) = RopeGrid(10).apply { move(input.parse9()) }.visited.size
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
fun List<String>.parse9() = map { line ->
line.split(" ").let { (d, l) -> RopeMovement(Direction.values().first { it.name.startsWith(d) }, l.toInt()) }
}
enum class Direction(val dx: Int = 0, val dy: Int = 0) {
UP(dy = -1),
DOWN(dy = 1),
LEFT(dx = -1),
RIGHT(dx = 1)
}
data class RopeMovement(val direction: Direction, var length: Int)
class RopeGrid(val knotCount: Int = 2) {
private val knots = MutableList(knotCount) { 0 to 0 }
val visited = mutableSetOf(knots[knotCount - 1])
fun move(movements: List<RopeMovement>) {
movements.forEach { moveHead(it) }
}
private fun moveHead(movement: RopeMovement) {
repeat(movement.length) {
knots[0] = knots[0].first + movement.direction.dx to knots[0].second + movement.direction.dy
(1 until knotCount).forEach { moveKnot(it) }
visited.add(knots[knotCount - 1])
}
}
private fun moveKnot(i: Int) {
val (hx, hy) = knots[i - 1]
val (tx, ty) = knots[i]
val dx = hx - tx
val dy = hy - ty
if (abs(dx) > 1 || abs(dy) > 1) {
knots[i] = tx + dx.sign to ty + dy.sign
}
}
}
| 0 | Kotlin | 0 | 0 | 584fa4d73f8589bc17ef56c8e1864d64a23483c8 | 1,707 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/io/trie/AutocompleteSearch.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.trie
// https://cheonhyangzhang.gitbooks.io/leetcode-solutions/642-design-search-autocomplete-system.html
class AutocompleteSearch(historicalData: List<Suggestion>) {
val historicalData: TreeNode = TreeNode(Suggestion("")).apply {
historicalData.forEach { (word, weight) -> addWord(word, weight) }
}
private var currentSearch: TreeNode = this.historicalData
fun getSuggestions(char: Char): List<Suggestion> = when (char) {
'#' -> {
currentSearch.finishPhrase()
updateSuggestions(historicalData, currentSearch.suggestion)
currentSearch = historicalData
emptyList()
}
else -> {
currentSearch = currentSearch.getOrAdd(char)
currentSearch.suggestions//.map { it.phrase }
}
}
data class TreeNode(
val suggestion: Suggestion,
val children: MutableMap<Int, TreeNode> = mutableMapOf(),
val suggestions: MutableList<Suggestion> = mutableListOf()) {
fun addWord(word: String, times: Int) =
word.fold(this) { acc, char -> acc.getOrAdd(char) }.also {
it.suggestion.weight = it.suggestion.weight + times
updateSuggestions(this, Suggestion(word, times))
}
fun getOrAdd(char: Char) = children[char.toInt()] ?: TreeNode(Suggestion(this.suggestion.phrase + char)).also { children[char.toInt()] = it }
fun updateSuggestions(suggestion: Suggestion) = this.suggestions.updateSuggestions(suggestion)
fun finishPhrase() {
suggestion.weight++
}
}
data class Suggestion(val phrase: String, var weight: Int=0) : Comparable<Suggestion> {
override fun compareTo(other: Suggestion): Int = when {
this.weight < other.weight -> 1
this.weight == other.weight -> -this.phrase.compareTo(other.phrase)
else -> -1
}
}
}
private fun updateSuggestions(root: AutocompleteSearch.TreeNode, suggestion: AutocompleteSearch.Suggestion) =
suggestion.phrase.fold(root) { acc, char ->
acc.children[char.toInt()]!!.also { it.updateSuggestions(suggestion) }
}
private fun MutableList<AutocompleteSearch.Suggestion>.updateSuggestions(suggestion: AutocompleteSearch.Suggestion) =
this.minByOrNull { it.weight }?.let { minSuggestion ->
when {
this.contains(suggestion) -> false.also { this.sort() }
this.size < 3 -> this.add(suggestion).also { this.sort() }
minSuggestion < suggestion -> {
this.remove(minSuggestion)
this.add(suggestion)
this.sort()
}
else -> false
}
} ?: this.add(suggestion)
fun main() {
val autocompleteSearch = AutocompleteSearch(listOf(
AutocompleteSearch.Suggestion("i love you", 5), AutocompleteSearch.Suggestion("island", 3), AutocompleteSearch.Suggestion("ironman", 2),
AutocompleteSearch.Suggestion("i love leetcode", 2)
))
println("You should see how 'i l#' grows and go before i love leetcode because the user uses it")
listOf("i l#", "i l#", "i l#", "i #").forEachIndexed { index, phrase ->
phrase.forEach { char ->
println("$index, $phrase $char ${autocompleteSearch.getSuggestions(char)}")
}
println("---")
}
}
| 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 3,145 | coding | MIT License |
src/Day09.kt | fouksf | 572,530,146 | false | {"Kotlin": 43124} | import java.lang.Exception
import kotlin.math.abs
fun main() {
data class Point(val x: Int, val y: Int) {
override fun toString(): String {
return "($x, $y)"
}
}
class Rope(knotsCount: Int) {
var knots = mutableListOf<Point>()
init {
for (i in 1..knotsCount) {
knots.add(Point(0, 0))
}
}
var visitedByTail: Set<String> = mutableSetOf(tail().toString())
fun tail(): Point {
return knots.last()
}
fun nextKnotHasToMove(i: Int): Boolean {
return i + 1 < knots.size && (abs(knots[i].x - knots[i + 1].x) == 2 || abs(knots[i].y - knots[i + 1].y) == 2)
}
fun moveTailOf(i: Int) {
if (nextKnotHasToMove(i)) {
val dx = if (knots[i].x == knots[i + 1].x) 0 else 1
val dy = if (knots[i].y == knots[i + 1].y) 0 else 1
knots[i + 1] = Point(knots[i + 1].x + if (knots[i + 1].x > knots[i].x) -1 * dx else dx,
knots[i + 1].y + if (knots[i + 1].y > knots[i].y) -1 * dy else dy )
if (nextKnotHasToMove(i + 1)) {
moveTailOf(i + 1)
}
}
}
fun moveUp() {
knots[0] = Point(knots[0].x - 1, knots[0].y)
}
fun moveDown() {
knots[0] = Point(knots[0].x + 1, knots[0].y)
}
fun moveLeft() {
knots[0] = Point(knots[0].x, knots[0].y - 1)
}
fun moveRight() {
knots[0] = Point(knots[0].x, knots[0].y + 1)
}
fun move(direction: String) {
when (direction) {
"L" -> moveLeft()
"R" -> moveRight()
"U" -> moveUp()
"D" -> moveDown()
}
moveTailOf(0)
visitedByTail = visitedByTail.plus(tail().toString())
}
}
fun findVisitedByTail(rope: Rope, input: List<String>): Int {
for (line in input) {
for (i in 1..line.split(" ")[1].toInt()) {
rope.move(line[0].toString())
}
}
return rope.visitedByTail.size
}
fun part1(input: List<String>): Int {
val rope = Rope(2)
return findVisitedByTail(rope, input)
}
fun part2(input: List<String>): Int {
val rope = Rope(10)
return findVisitedByTail(rope, input)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
println(part1(testInput))
val testInput2 = readInput("Day09_test_part2")
println(part2(testInput2))
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 701bae4d350353e2c49845adcd5087f8f5409307 | 2,791 | advent-of-code-2022 | Apache License 2.0 |
year2015/src/main/kotlin/net/olegg/aoc/year2015/day15/Day15.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2015.day15
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2015.DayOf2015
/**
* See [Year 2015, Day 15](https://adventofcode.com/2015/day/15)
*/
object Day15 : DayOf2015(15) {
private const val SPOONS = 100
private val PATTERN = ".* (-?\\d+)\\b.* (-?\\d+)\\b.* (-?\\d+)\\b.* (-?\\d+)\\b.* (-?\\d+)\\b.*".toRegex()
private val ITEMS = lines
.map { line ->
PATTERN.matchEntire(line)
?.destructured
?.toList()
?.map { it.toInt() }
.orEmpty()
}
override fun first(): Any? {
val itemsValues = (0..3).map { value -> ITEMS.map { it[value] } }
return splitRange(ITEMS.size, SPOONS)
.map { split ->
itemsValues.map { item ->
item.mapIndexed { index, value -> split[index] * value }.sum().coerceAtLeast(0)
}
}
.maxOf { it.reduce { acc, value -> acc * value } }
}
override fun second(): Any? {
val itemsValues = (0..3).map { value -> ITEMS.map { it[value] } }
val calories = ITEMS.map { it[4] }
return splitRange(ITEMS.size, SPOONS)
.filter { it.mapIndexed { index, value -> calories[index] * value }.sum() == 500 }
.map { split ->
itemsValues.map { item ->
item.mapIndexed { index, value -> split[index] * value }.sum().coerceAtLeast(0)
}
}
.maxOf { it.reduce { acc, value -> acc * value } }
}
}
fun splitRange(
splits: Int,
sum: Int
): List<List<Int>> = if (splits == 1) {
listOf(listOf(sum))
} else {
(0..sum).flatMap { value -> splitRange(splits - 1, sum - value).map { listOf(value) + it } }
}
fun main() = SomeDay.mainify(Day15)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,655 | adventofcode | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.